SLOPSHOPPER

subagent-router

Runs search subagents on Haiku and general-purpose ones on Sonnet, and /orchestrate splits a big task across scout, worker and reviewer subagents

paneguardcommandtoasttooltimer
★ 3v0.3.2MITupdated 2026-10-10noash-xrc/claude-tools/subagent-router
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · subagent-router
│ ┃ orchestrate ✕ › fix the failing auth test and add an audit log call │ ┃ No orchestration. /orchestrate <task> starts │ ┃ one. ⏺ Read(src/auth.ts) │ ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /subagent-router │ ⎿ subagent-router: subagent-router is on: Explore on haiku, genera │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · orchestrate
No orchestration. /orchestrate <task> starts one.
README

Subagent router

A Claude Code mod that starts subagents on a cheaper model than the main one. A subagent reads files and searches in its own context and hands back a summary, so a cheaper model reading through a codebase saves tokens without touching the main conversation's prompt cache.

Agent typeModel
ExploreHaiku
general-purposeSonnet

Every other type, such as Plan or an agent you wrote, keeps the model its definition names.

The mod leaves a spawn alone when:

  • Claude named a model in the call
  • the subagent is a fork, which always runs on the main model
  • the subagent is a teammate
  • the route wouldn't be cheaper, for example a general-purpose agent started from a Sonnet session

Effort isn't set here. With auto-effort installed, Explore agents run at low.

Orchestrate

/orchestrate <task> runs a big task with the main session as orchestrator and three subagent roles under it:

  • scout reads code and answers questions, never edits
  • worker completes one task from a contract: the files it owns, a check command and what to report back. It can spawn Explore agents for searches, and no other type. Those take no slot under the agent limit, and their spend counts toward the run's
  • reviewer checks a worker's diff against its contract, for the tasks the orchestrator marks as risky

A pane opens first with three settings, then Start:

Levelscoutworkerreviewer
lowHaiku, lowSonnet, mediumSonnet, high
mid (default)Haiku, lowSonnet, highOpus, medium
highHaiku, lowOpus, mediumOpus, high
xhighHaiku, mediumOpus, highOpus, high
  • Workers at once, 3 by default. A spawn past the limit is refused until one finishes.
  • Approval: plan (default) stops once for you to approve the plan after scouting, step before every step, off never.

The orchestrator keeps the plan in the mod's own task list, through its update_tasks tool. Tasks that edit the same files run one after another. It runs each task's check command itself, and a task that fails gets one retry, then a retry on the next level's worker, then it asks you. After Start the pane keeps a fixed height: the time since Start (it stops when the last task completes), a progress bar of finished tasks, a folded line counting the running agents (click it for one row per worker slot with the agent's role, model and spend), what comes next, and Stop. Approve appears only while the orchestrator waits for you. At xhigh, consider /model fable for the orchestrator first; the mod leaves the main model alone.

  • /orchestrate <level> changes the level mid-run, for agents spawned from the next turn
  • /orchestrate stop ends the run and prints what its agents spent at API prices
  • a toast warns when the 5-hour window passes 80%

Commands

  • /subagent-router shows whether routing is on
  • /subagent-router off and /subagent-router on turn it off and back on for the session

Install

/plugin install subagent-router --marketplace noash-xrc/claude-tools

Answer y to add the marketplace, then pick a scope.

Update

claude plugin marketplace update noash-tools
claude plugin update subagent-router@noash-tools

Restart Claude Code to load the new version.

License

MIT

Source 2 files
hooks/register.tsx 408 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, Timer, TurnStepResult } from 'claude-code'
3import type { Approval, Level, Run, RunAgent, RunTask } from '../types/index'
4
5// Agent types whose work a cheaper model does as well; any other type keeps its own model.
6const ROUTES: Record<string, string> = { Explore: 'haiku', 'general-purpose': 'sonnet' }
7const RANK = ['haiku', 'sonnet', 'opus']
8// ponytail: a model id naming none of the three ranks as unknown, so the route is skipped
9const rank = (model: string) => RANK.findIndex(m => model.toLowerCase().includes(m))
10
11let enabled = true
12// numbers the slot an orchestration agent holds until its spawn returns an id
13let reserved = 0
14// redraws the pane each second while a run is on, so its timer moves
15let tick: Timer | undefined
16// savings-meter reads this to price the routed agents' tokens
17const routedAtom = atom({ plugin: 'subagent-router', key: 'routed' } as const, [])
18const runAtom = atom({ plugin: 'subagent-router', key: 'run' } as const, null)
19const tasksAtom = atom({ plugin: 'subagent-router', key: 'tasks' } as const, [])
20const agentsAtom = atom({ plugin: 'subagent-router', key: 'agents' } as const, [])
21
22// /orchestrate: each level sets the model and effort of the three roles the orchestrator spawns.
23type Role = 'scout' | 'worker' | 'reviewer'
24const ROLES: Role[] = ['scout', 'worker', 'reviewer']
25const LEVELS: Level[] = ['low', 'mid', 'high', 'xhigh']
26const TABLE: Record<Level, Record<Role, [string, string]>> = {
27  low: { scout: ['haiku', 'low'], worker: ['sonnet', 'medium'], reviewer: ['sonnet', 'high'] },
28  mid: { scout: ['haiku', 'low'], worker: ['sonnet', 'high'], reviewer: ['opus', 'medium'] },
29  high: { scout: ['haiku', 'low'], worker: ['opus', 'medium'], reviewer: ['opus', 'high'] },
30  xhigh: { scout: ['haiku', 'medium'], worker: ['opus', 'high'], reviewer: ['opus', 'high'] },
31}
32const APPROVALS: Approval[] = ['plan', 'step', 'off']
33const ROLE_SPECS: Record<Role, { description: string; prompt: string; disallowedTools: string[] }> = {
34  scout: {
35    description: 'Orchestration scout: reads code and answers questions about it, never edits',
36    prompt: 'You are a scout for an orchestrator. Read the code the brief points at and answer its questions with file paths and line numbers. Do not edit files. Keep the answer under 300 words: facts, not advice.',
37    disallowedTools: ['Edit', 'Write', 'NotebookEdit', 'Agent'],
38  },
39  worker: {
40    description: 'Orchestration worker: completes one task from a contract',
41    prompt: 'You are a worker for an orchestrator. You get one task as a contract: what to do, the files you own, a check command and a deliverable format. Edit only the files you own; if the task needs another file, stop and say which and why. To find something across many files, spawn an Explore agent and work from its answer; it is the only agent type you can spawn. Run the check command before you finish. Reply in the deliverable format only: files changed, the check result, open questions.',
42    // the Agent tool stays for Explore; agent.spawn refuses any other type a worker asks for
43    disallowedTools: [],
44  },
45  reviewer: {
46    description: 'Orchestration reviewer: checks one task\'s diff against its contract, never edits',
47    prompt: 'You are a reviewer for an orchestrator. You get a contract and the task\'s diff, not the worker\'s reasoning. Find bugs that break the contract or would fail in use: each with file:line, what goes wrong and when. Most severe first. Do not edit files. If you find nothing, say so in one line.',
48    disallowedTools: ['Edit', 'Write', 'NotebookEdit', 'Agent'],
49  },
50}
51const row = (level: Level) => ROLES.map(r => `${r} ${TABLE[level][r].join('-')}`).join(', ')
52const roleOf = (type: string) => (type.startsWith('subagent-router:') ? (type.slice(16) as Role) : undefined)
53
54// The orchestrator calls this where the skill says to wait; the pane shows Approve only then.
55const APPROVAL_TOOL = 'mcp__subagent-router__await_approval'
56// The run's task list, the mod's own: TaskCreate isn't in every session's toolset.
57const TASKS_TOOL = 'mcp__subagent-router__update_tasks'
58type TaskChange = { id: string; subject?: string; status?: string; blockedBy?: string[]; contract?: string }
59const registerRoles = ($: EngineInterface, level: Level) =>
60  Promise.all([
61    ...ROLES.map(r => {
62      const [model, effort] = TABLE[level][r]
63      return $.agent.register({ name: r, ...ROLE_SPECS[r], model, effort })
64    }),
65    $.tool.register({
66      name: 'await_approval',
67      description: 'Orchestration only: ask the person to approve the plan or the next step. Shows an Approve button in the Orchestrate pane. End your turn right after calling it.',
68      inputSchema: { type: 'object', properties: { summary: { type: 'string', description: 'What needs approval, in one line' } }, required: ['summary'] },
69      isDeferred: false,
70    }),
71    $.tool.register({
72      name: 'update_tasks',
73      description: 'Orchestration only: the run\'s task list, drawn in the Orchestrate pane. Each entry adds a task under a new id or changes the given fields of one already there; status "deleted" removes it. Call it with no tasks to read the list back with each contract.',
74      inputSchema: {
75        type: 'object',
76        properties: {
77          tasks: {
78            type: 'array',
79            items: {
80              type: 'object',
81              properties: {
82                id: { type: 'string', description: 'Short id, such as "1"' },
83                subject: { type: 'string', description: 'A title of a few words for the pane' },
84                status: { type: 'string', enum: ['pending', 'in_progress', 'completed', 'deleted'] },
85                blockedBy: { type: 'array', items: { type: 'string' }, description: 'Ids of the tasks this one waits for; replaces the earlier list' },
86                contract: { type: 'string', description: 'Goal, Owns, Check, Review, Deliverable' },
87              },
88              required: ['id'],
89            },
90          },
91        },
92      },
93      isDeferred: false,
94    }),
95  ])
96
97const kickoff = (run: Run) => {
98  const next = LEVELS[LEVELS.indexOf(run.level) + 1]
99  const escalate = next ? `spawn the worker again with model "${TABLE[next].worker[0]}" and effort "${TABLE[next].worker[1]}"` : 'there is no higher level, so ask the person'
100  return [
101    'Orchestrate the task below with the subagent-router:orchestrating skill.',
102    `Level ${run.level}: ${row(run.level)}. Spawn them as subagent-router:scout, subagent-router:worker and subagent-router:reviewer without a model or effort.`,
103    `When a task fails its check twice: ${escalate}.`,
104    `At most ${run.workers} agents at once. Approval: ${run.approval}.`,
105    '',
106    `Task: ${run.task}`,
107  ].join('\n')
108}
109
110// API dollars per million tokens: input, output, cache read, as savings-meter prices them.
111// ponytail: copied from savings-meter, cache writes at twice the input price
112const PRICES: Record<string, [number, number, number]> = { opus: [4, 20, 0.2], sonnet: [2, 10, 0.2], haiku: [0.1, 0.5, 0.01] }
113const cost = (model: string, u: NonNullable<TurnStepResult['usage']>) => {
114  const p = Object.entries(PRICES).find(([family]) => model.includes(family))?.[1]
115  if (!p) return 0
116  return (u.input_tokens * p[0] + u.cache_creation_input_tokens * p[0] * 2 + u.cache_read_input_tokens * p[2] + u.output_tokens * p[1]) / 1e6
117}
118const usd = (n: number) => `$${n.toFixed(2)}`
119// m:ss, or h:mm:ss from an hour on
120const elapsed = (ms: number) => {
121  const s = Math.max(0, Math.floor(ms / 1000))
122  const mmss = `${Math.floor(s / 60) % 60}:${String(s % 60).padStart(2, '0')}`
123  return s < 3600 ? mmss : `${Math.floor(s / 3600)}:${mmss.padStart(5, '0')}`
124}
125const ticking = ($: EngineInterface, on: boolean) => {
126  tick?.cancel()
127  tick = on ? $.clock.every(1000, () => $.ui.invalidate('ui.render')) : undefined
128}
129// orchestration agents holding a slot; a worker's Explore agents take none
130const holding = (list: RunAgent[]) => list.filter(a => !a.isDone && a.role !== 'explore')
131
132const set =($: EngineInterface, change: Partial<Run>) => update($, runAtom, r => (r ? { ...r, ...change } : r))
133
134const PANE = 'orchestrate'
135const approve = async ($: EngineInterface) => {
136  await set($, { awaiting: '' })
137  await $.prompt.submit({ text: 'Approved. Go ahead.', asUser: true })
138}
139
140const stop = async ($: EngineInterface) => {
141  const spent = (await read($, agentsAtom)).reduce((sum, a) => sum + a.usd, 0)
142  ticking($, false)
143  await update($, runAtom, () => null)
144  await update($, tasksAtom, () => [])
145  await update($, agentsAtom, () => [])
146  await $.ui.close({ id: PANE })
147  return `Orchestration stopped. Its agents spent about ${usd(spent)} at API prices.`
148}
149
150const start = async ($: EngineInterface) => {
151  const now = await $.clock.now()
152  const run = await update($, runAtom, r => (r ? { ...r, started: true, startedAt: now, finishedAt: 0 } : r))
153  if (!run) return
154  ticking($, true)
155  try {
156    await registerRoles($, run.level)
157    if (run.level === 'xhigh') $.ui.toast('xhigh: consider /model fable for the orchestrator')
158    const sent = await $.prompt.submit({ text: kickoff(run) })
159    if (sent.drop !== undefined) throw new Error(sent.drop)
160  }
161  catch (err) {
162    // no orchestrator got the kickoff, so the pane goes back to its settings
163    await set($, { started: false })
164    ticking($, false)
165    $.ui.toast(`Could not start: ${err instanceof Error ? err.message : err}`)
166  }
167}
168
169
170export const register: Register = on => {
171  on('session.start', async ($, e, next) => {
172    await $.command.register({ name: 'subagent-router', description: 'Show, or turn on or off, routing subagents to cheaper models', argumentHint: '[on | off]' })
173    await $.command.register({ name: 'orchestrate', description: 'Split a big task across scout, worker and reviewer subagents', argumentHint: '<task> | <level> | stop' })
174    // a reload drops the plugin's agent types; a run in progress needs them back
175    const run = await read($, runAtom)
176    if (run?.started) {
177      await registerRoles($, run.level)
178      ticking($, true)
179    }
180    return next(e)
181  })
182
183  on('command.run', { command: 'subagent-router' }, async ($, e) => {
184    const arg = e.args.trim().toLowerCase()
185    if (arg === 'on' || arg === 'off') enabled = arg === 'on'
186    else if (arg) return { text: `Unknown argument "${arg}". Use on or off.` }
187    const routes = Object.entries(ROUTES).map(([type, model]) => `${type} on ${model}`).join(', ')
188    return { text: enabled ? `subagent-router is on: ${routes}.` : 'subagent-router is off.' }
189  })
190
191  on('command.run', { command: 'orchestrate' }, async ($, e) => {
192    const arg = e.args.trim()
193    const run = await read($, runAtom)
194    if (arg === 'stop') return { text: run ? await stop($) : 'No orchestration is running.' }
195    if (run?.started && LEVELS.includes(arg as Level)) {
196      await set($, { level: arg as Level })
197      await registerRoles($, arg as Level)
198      return { text: `Level ${arg}: ${row(arg as Level)}. Agents spawned from the next turn on use it.` }
199    }
200    if (!arg && !run) return { text: 'Usage: /orchestrate <task>' }
201    if (arg && run?.started) return { text: 'An orchestration is running. /orchestrate stop ends it first.' }
202    if (arg) {
203      await update($, runAtom, () => ({ task: arg, level: run?.level ?? 'mid', workers: run?.workers ?? 3, approval: run?.approval ?? 'plan', started: false, warned: false, awaiting: '', showAgents: false, startedAt: 0, finishedAt: 0 }))
204      await update($, tasksAtom, () => [])
205      await update($, agentsAtom, () => [])
206    }
207    await $.ui.open({ id: PANE, title: 'Orchestrate', focus: true })
208    return { text: arg ? 'Pick the settings in the Orchestrate pane, then press Start.' : 'Orchestrate pane opened.' }
209  })
210
211  // A model Claude named in the call, a fork or a teammate is left alone; so is a route that wouldn't be cheaper than the parent.
212  // An orchestration role past the worker limit is refused, and each one started is tracked for the pane.
213  // A worker may spawn Explore and nothing else; its Explore agents take no slot but their spend counts.
214  on('agent.spawn', async ($, e, next) => {
215    const fromWorker = e.parentAgentId !== undefined && (await read($, agentsAtom)).some(a => a.id === e.parentAgentId && a.role === 'worker')
216    if (fromWorker && e.subagentType !== 'Explore') return { deny: 'A worker can spawn Explore agents only.' }
217    const role = roleOf(e.subagentType)
218    if (role) {
219      const run = await read($, runAtom)
220      const limit = run?.started ? run.workers : Infinity
221      const running = (list: RunAgent[]) => holding(list).length
222      // count and take the slot in one write, so two spawns at once can't both pass the limit
223      const slot = `pending-${reserved++}`
224      const taken = await update($, agentsAtom, list => (running(list) >= limit ? list : [...list, { id: slot, role, model: '', description: e.description, isDone: false, usd: 0 }]))
225      if (!taken.some(a => a.id === slot)) return { deny: `${running(taken)} orchestration agents are running and the limit is ${limit}. Wait for one to finish.` }
226      const release = () => update($, agentsAtom, list => list.filter(a => a.id !== slot))
227      const r = await next(e).catch(async err => {
228        await release()
229        throw err
230      })
231      const id = r.agentId
232      if (id) await update($, agentsAtom, list => list.map(a => (a.id === slot ? { ...a, id, model: r.model } : a)))
233      else await release()
234      return r
235    }
236    const model = Object.hasOwn(ROUTES, e.subagentType) ? ROUTES[e.subagentType] : undefined
237    const cheaper = model !== undefined && rank(model) < rank(e.parentModel)
238    const routed = enabled && cheaper && e.model === undefined && !e.fork && !e.isTeammate
239    const r = await next(routed ? { ...e, model } : e)
240    const id = 'agentId' in r ? r.agentId : undefined
241    if (id && routed) await update($, routedAtom, ids => [...ids, id])
242    if (id && fromWorker) await update($, agentsAtom, list => [...list, { id, role: 'explore', model: r.model, description: e.description, isDone: false, usd: 0 }])
243    return r
244  }).catch(($, e, next) => next(e))
245
246  on('turn.step', async function* ($, e, next) {
247    const result = yield* next(e)
248    if (e.agentId !== undefined && result.usage) {
249      const u = result.usage
250      const id = e.agentId
251      if ((await read($, agentsAtom)).some(a => a.id === id)) await update($, agentsAtom, list => list.map(a => (a.id === id ? { ...a, usd: a.usd + cost(u.model ?? a.model, u) } : a)))
252    }
253    return result
254  })
255
256  on('turn.complete', async ($, e, next) => {
257    const result = await next(e)
258    const id = e.agentId
259    if (id !== undefined && (await read($, agentsAtom)).some(a => a.id === id)) await update($, agentsAtom, list => list.map(a => (a.id === id ? { ...a, isDone: true } : a)))
260    return result
261  })
262
263  on('tool.call', { tool: TASKS_TOOL }, async ($, e) => {
264    const changes = (e as { tasks?: TaskChange[] }).tasks ?? []
265    const list = await update($, tasksAtom, list => changes.reduce((l, c) => {
266      if (c.status === 'deleted') return l.filter(t => t.id !== c.id)
267      const old = l.find(t => t.id === c.id)
268      const t = { id: c.id, subject: c.subject ?? old?.subject ?? `#${c.id}`, status: c.status ?? old?.status ?? 'pending', blockedBy: c.blockedBy ?? old?.blockedBy ?? [], contract: c.contract ?? old?.contract ?? '' }
269      return old ? l.map(x => (x.id === c.id ? t : x)) : [...l, t]
270    }, list))
271    // the pane's timer stops when the last task completes, and runs on if a task is added after
272    const finished = list.length > 0 && list.every(t => t.status === 'completed')
273    const now = await $.clock.now()
274    await update($, runAtom, r => (r ? { ...r, finishedAt: finished ? r.finishedAt || now : 0 } : r))
275    // contracts only on a read, so each update doesn't echo them all back
276    const line = (t: RunTask) => `#${t.id} ${t.status}: ${t.subject}${t.blockedBy.length ? ` (after #${t.blockedBy.join(', #')})` : ''}${changes.length || !t.contract ? '' : `\n${t.contract}`}`
277    return { result: list.map(line).join('\n') || 'No tasks.' } as never
278  })
279
280  on('tool.call', { tool: APPROVAL_TOOL }, async ($, e) => {
281    const summary = String((e as { summary?: unknown }).summary ?? 'the plan')
282    await set($, { awaiting: summary })
283    return { result: 'The Orchestrate pane now shows Approve. End your turn; the approval or the changes come as the next message.' } as never
284  })
285
286  // whatever the person sends next answers the approval
287  on('turn.start', async ($, e, next) => {
288    if ((await read($, runAtom))?.awaiting) await set($, { awaiting: '' })
289    return next(e)
290  })
291
292  on('session.measure', async ($, e, next) => {
293    const used = e.rateLimits.find(l => l.kind === 'five_hour')?.percentUsed ?? 0
294    const run = await read($, runAtom)
295    if (run?.started && !run.warned && used >= 80) {
296      await set($, { warned: true })
297      $.ui.toast(`The 5-hour window is ${Math.round(used)}% used. /orchestrate low makes the rest of the run cheaper.`)
298    }
299    return next(e)
300  })
301
302  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
303    const { Box, Text, Button } = $.ui.resolve(e)
304    const [run, tasks, agents] = await Promise.all([read($, runAtom), read($, tasksAtom), read($, agentsAtom)])
305    if (!run) return <Text dimColor>No orchestration. /orchestrate &lt;task&gt; starts one.</Text>
306    const width = Math.max(20, e.props.bodyColumns || 60)
307    const fit = (text: string, n = width) => (text.length > n ? `${text.slice(0, n - 1)}…` : text)
308    const pick = <T extends string>(key: string, options: T[], chosen: T, choose: (o: T) => void) => (
309      <Box key={key}>
310        {options.map(o => (o === chosen
311          ? <Button key={`${key}-${o}`} plain onPress={choose.bind(null, o)}><Text color="cyan" bold>{`● ${o}`}</Text>{'   '}</Button>
312          : <Button key={`${key}-${o}`} plain dimColor onPress={choose.bind(null, o)}>{`○ ${o}   `}</Button>))}
313      </Box>
314    )
315
316    if (!run.started) {
317      return (
318        <Box flexDirection="column">
319          <Text bold>{fit(run.task)}</Text>
320          <Text dimColor>{'─'.repeat(Math.min(width, 40))}</Text>
321          <Text bold>Level</Text>
322          {pick('level', LEVELS, run.level, level => void set($, { level }))}
323          <Text dimColor>{fit(`${row(run.level)}${run.level === 'xhigh' ? '. Consider /model fable first.' : ''}`)}</Text>
324          <Text> </Text>
325          <Box>
326            <Text bold>Agents at once  </Text>
327            <Button key="fewer" plain dimColor={run.workers === 1} onPress={() => void set($, { workers: Math.max(1, run.workers - 1) })}>−</Button>
328            <Text color="cyan" bold>{` ${run.workers} `}</Text>
329            <Button key="more" plain dimColor={run.workers === 8} onPress={() => void set($, { workers: Math.min(8, run.workers + 1) })}>+</Button>
330          </Box>
331          <Text> </Text>
332          <Text bold>Approval</Text>
333          {pick('approval', APPROVALS, run.approval, approval => void set($, { approval }))}
334          <Text dimColor>{{ plan: 'You approve the plan once, after scouting.', step: 'You approve before every step.', off: 'No pauses.' }[run.approval]}</Text>
335          <Text> </Text>
336          <Box>
337            <Button key="start" variant="primary" autoFocus onPress={() => void start($)}>Start</Button>
338            <Text>  </Text>
339            <Button key="cancel" dimColor onPress={() => void stop($)}>Cancel</Button>
340          </Box>
341        </Box>
342      )
343    }
344
345    // The height is capped so the pane never grows over the prompt: at most SHOWN task rows, and the agents fold.
346    const SHOWN = 5
347    const spent = agents.reduce((sum, a) => sum + a.usd, 0)
348    const done = tasks.filter(t => t.status === 'completed').length
349    const allDone = tasks.length > 0 && done === tasks.length
350    const label = `${done}/${tasks.length} tasks${tasks.length ? ` · ${Math.round((done / tasks.length) * 100)}%` : ''}`
351    const barWidth = Math.max(10, Math.min(40, width - label.length - 1))
352    const filled = tasks.length ? Math.round((done / tasks.length) * barWidth) : 0
353    const running = holding(agents)
354    const slots = Array.from({ length: run.workers }, (_, i) => running[i])
355    const family = (model: string) => RANK.find(m => model.includes(m)) ?? model
356    // a deleted blocker no longer holds a task back
357    const ready = (t: RunTask) => t.blockedBy.every(id => (tasks.find(d => d.id === id)?.status ?? 'completed') === 'completed')
358    const next = tasks.find(t => t.status === 'pending' && ready(t))
359    // the window starts one row above the first unfinished task
360    const unfinished = tasks.findIndex(t => t.status !== 'completed')
361    const from = Math.max(0, Math.min((unfinished < 0 ? tasks.length : unfinished) - 1, tasks.length - SHOWN))
362    const shown = tasks.slice(from, from + SHOWN)
363    const taskRow = (t: RunTask) => {
364      const [icon, color] = t.status === 'completed' ? ['✓', 'green'] : t.status === 'in_progress' ? ['◐', 'yellow'] : ['○', undefined]
365      const waits = t.status === 'pending' && !ready(t) ? `  after #${t.blockedBy.join(', #')}` : ''
366      return (
367        <Text key={`task-${t.id}`} dimColor={t.status === 'completed' || !!waits}>
368          <Text color={color}>{icon}</Text> {fit(`${t.subject}${waits}`, width - 2)}
369        </Text>
370      )
371    }
372    const status = run.awaiting ? `⏸ Waiting for your approval: ${run.awaiting}`
373      : !tasks.length ? '… Scouting and planning'
374      : allDone ? '✓ All tasks done'
375      : next ? `→ Next: ${next.subject}` : '… Working'
376    // a run started before the timer existed has no startedAt
377    const time = run.startedAt ? ` · ${elapsed((run.finishedAt || await $.clock.now()) - run.startedAt)}` : ''
378    const meta = `${run.level}${time} · ${usd(spent)}`
379    return (
380      <Box flexDirection="column">
381        <Text><Text bold>{fit(run.task, width - meta.length - 2)}</Text>  <Text color="cyan">{run.level}</Text><Text dimColor>{`${time} · ${usd(spent)}`}</Text></Text>
382        <Text>
383          <Text color={allDone ? 'green' : 'cyan'}>{'█'.repeat(filled)}</Text>
384          <Text dimColor>{'░'.repeat(barWidth - filled)}</Text>
385          <Text> {label}</Text>
386        </Text>
387        <Text> </Text>
388        {shown.map(taskRow)}
389        {tasks.length > shown.length && <Text dimColor>{`  +${tasks.length - shown.length} more`}</Text>}
390        {tasks.length > 0 && <Text> </Text>}
391        <Button key="agents" plain dimColor onPress={() => void set($, { showAgents: !run.showAgents })}>
392          {fit(`${run.showAgents ? '▾' : '▸'} ${running.length} of ${run.workers} agents running · ${agents.filter(a => a.role !== 'explore').length} so far`)}
393        </Button>
394        {run.showAgents && slots.map((a, i) => (a
395          ? <Text key={`slot-${i}`}><Text color="yellow">◐</Text>{fit(` ${a.role.padEnd(8)} ${family(a.model).padEnd(6)} ${usd(a.usd).padStart(6)}  ${a.description}`, width - 1)}</Text>
396          : <Text key={`slot-${i}`} dimColor>· idle</Text>))}
397        <Text color={run.awaiting ? 'yellow' : allDone ? 'green' : undefined} bold={!!run.awaiting} dimColor={!run.awaiting && !allDone}>{fit(status)}</Text>
398        <Text> </Text>
399        <Box>
400          {run.awaiting && <Button key="approve" variant="primary" autoFocus onPress={() => void approve($)}>Approve</Button>}
401          {run.awaiting && <Text>  </Text>}
402          <Button key="stop" dimColor onPress={() => void stop($).then(text => $.ui.toast(text))}>Stop</Button>
403        </Box>
404      </Box>
405    )
406  })
407}
408
types/index.d.ts 22 lines
1export type Level = 'low' | 'mid' | 'high' | 'xhigh'
2export type Approval = 'plan' | 'step' | 'off'
3// started is false while the pane still shows the settings; awaiting is what the orchestrator asked approval for, '' when nothing;
4// showAgents unfolds the agent rows, folded by default since Claude Code lists running agents itself;
5// startedAt is when Start was pressed and finishedAt when the last task completed, in epoch ms, 0 when not yet
6export type Run = { task: string; level: Level; workers: number; approval: Approval; started: boolean; warned: boolean; awaiting: string; showAgents: boolean; startedAt: number; finishedAt: number }
7export type RunTask = { id: string; subject: string; status: string; blockedBy: string[]; contract: string }
8export type RunAgent = { id: string; role: string; model: string; description: string; isDone: boolean; usd: number }
9
10declare module 'claude-code' {
11  interface PluginState {
12    'subagent-router': {
13      // ids of the subagents this session started on a cheaper model
14      routed: string[]
15      // the /orchestrate run, null when none
16      run: Run | null
17      tasks: RunTask[]
18      agents: RunAgent[]
19    }
20  }
21}
22