SLOPSHOPPER

model-router

Picks Haiku, Sonnet, Opus or Fable for each subagent and shows what it cost.

panebandguardcommandtoaststatus
v0.8.0no licenseupdated 2026-10-20aott33/model-router
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · model-router
│ ┃ Model router ✕ › fix the failing auth test and add an audit log call │ ┃ Model router · on │ ┃ ⏺ Read(src/auth.ts) │ ┃ Spent $0 ⎿ Read 6 lines │ ┃ Unrouted $0 ⏺ Update(src/auth.ts) │ ┃ 5h limit ██░░░ 31% ⎿ Added 2 lines, removed 1 line │ ┃ Last turn 0:00 · +$0 ⏺ Bash(bun test) │ ┃ Claude Code $0.42 total · this bill $0 befor ⎿ 3 pass, 1 fail │ ┃ │ ┃ No subagents yet. Ask Claude to use an agent ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ shows up here. │ ✻ Worked for 42s · done 4:20 PM │ │ › /router │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Model router
Model router · on Spent $0 Unrouted $0 5h limit ██░░░ 31% Last turn 0:00 · +$0 Claude Code $0.42 total · this bill $0 before the cla… No subagents yet. Ask Claude to use an agent and it shows up here.
README

model-router

A Claude Code mod that picks a model for each subagent and shows what it cost.

Install

/plugin install model-router --marketplace aott33/model-router

Needs Claude Code 2.1.287+. For development: claude --plugin-dir ./model-router.

How it routes

Haiku 5.5 reads each subagent's task and picks a tier:

TierModelEffortFor
easyHaiku 5.5lowrenames, searches, running tests
normalSonnet 5.5medium at mostfeature work, plans, fixes with a known failure
hardOpus 5.5unchangedunknown-cause or racy bugs, security, design trade-offs
longFable 5.1unchangedwork the task says is long or unattended

Rules on top:

  • Roles. Adds four agents: architect (plans, Sonnet+), builder, runner (runs commands, Sonnet max) and fixer (Sonnet+).
  • Risk floor. A task whose agent will do lasting harm (deploy to prod, delete real data, force-push) runs on Opus or higher. Writing such code doesn't count.
  • Rate limits. At 80% of your 5-hour or weekly limit, routing goes one tier cheaper. Builders and fixers stay on Sonnet or higher.
  • Rescue. A Haiku or Sonnet agent that is stuck (3 failed tool calls in a row, or far too many requests or minutes) moves up one model mid-run.
  • Budget. With a session budget set, routing goes one tier cheaper at 80% and to the cheapest allowed model at 100%. Risky tasks still get Opus.
  • Effort is only ever lowered, never raised.
  • Left alone: models Claude names, forks, workflow agents and teammates.

If Haiku doesn't answer, the engine's classifier tries, then the role's default. Verdicts are cached, so a repeated task skips the classifier.

Commands

CommandDoes
/routeropen the pane
/router offstop routing
/router haiku, sonnet, opussend every routed agent to one model
/router onroute again
/router statusshow the mode
/router resetclear the bill

The mode is kept across sessions.

The pane

  • Header: spent, unrouted cost and savings, rate-limit and budget gauges, the last turn's receipt, and Claude Code's own total.
  • Table: each agent's status (◐ running, ✓ done), tier, model, time, cost and unrouted cost.
  • Why: press ctrl+x tab, then an agent's number, to see why it got its model. Esc returns to the prompt.
  • Marks: ! risky, ↓ lowered for rate limits or budget, ↑ rescued. Dim rows weren't routed.

A band above the prompt shows each running agent; a status line shows the total.

Settings (/config)

SettingDefault
Open the pane at startonoff: only /router opens it
Compare againstunroutedprice the unrouted column on what each agent would have used, or on fable, opus, sonnet
Route every subagentonoff: only the four router agents
Keep a model Claude asked foron
Lower effort for easy taskson
Send risky tasks to Opuson
Move up a struggling agenton
Route cheaper near rate limits8070, 90 or off
Session budgetoff$1, $2, $5, $10, $20 or $50

Limits

  • Only subagents are routed. The main conversation keeps your model.
  • Dollar figures use API list prices. On Pro or Max they're API-equivalent; the real saving is rate-limit headroom.
  • "Saved" assumes the same tokens on another model, so it's an estimate.
  • A rescue re-reads the agent's context at the new model's price.
  • The risk flag is a judgment call. It doesn't replace permission prompts.
  • Explore's own model is learned only from runs it wasn't routed.
  • Model ids and prices live in hooks/lib/pricing.ts.

Develop

claude plugin validate .
claude plugin test .

See RELEASING.md and CHANGELOG.md.

Credits

Clock, gauge and receipt ideas from claude-flightdeck (MIT).

Source 5 files
hooks/register.tsx 1187 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, RenderElement } from 'claude-code'
3
4import type { AgentRow, RouterLedger, RouterMeter, RouterView, Tier, Tokens } from '../types'
5import { ROLES, ROLE_MODEL } from './lib/agents'
6import {
7  BUDGET_WARN,
8  CLASSIFIER_EFFORT,
9  CLASSIFIER_MODEL,
10  CLASSIFIER_SYSTEM,
11  TIER_WORD,
12  EFFORT_CAP,
13  FORCED_TIER,
14  MODEL_FOR_TIER,
15  ORDER,
16  ZERO,
17  addTokens,
18  asksForLongRun,
19  budgetUsd,
20  classifyKey,
21  builtinClassifierText,
22  capEffort,
23  classifierPrompt,
24  costOf,
25  explainTier,
26  clockText,
27  fallbackTier,
28  familyOf,
29  fullestWindow,
30  isLongPrompt,
31  looksRisky,
32  parseMode,
33  parseRisky,
34  parseTier,
35  pressureThreshold,
36  rescueReason,
37  rescueTier,
38  roleOf,
39  routeTier,
40  subTokens,
41  tierOfModel,
42  tokensFromUsage,
43  usd,
44  limitName,
45  windowGauge,
46  type CacheTtl,
47  type Family,
48  type Effort,
49  type Mode,
50} from './lib/pricing'
51
52const PANE = 'model-router'
53const EMPTY: RouterLedger = { rows: {}, classifierCost: 0, routed: 0 }
54const ledger = atom({ plugin: 'model-router', key: 'ledger' } as const, EMPTY)
55/** The `/router` mode in this session; the pane redraws when it is written. */
56const modeState = atom({ plugin: 'model-router', key: 'mode' } as const, undefined)
57const EMPTY_METER: RouterMeter = { limits: [] }
58/** What the engine measures for the session (its cost, the rate-limit windows) and the turn receipt. */
59const meter = atom({ plugin: 'model-router', key: 'meter' } as const, EMPTY_METER)
60/** Which pane row is expanded. */
61const view = atom({ plugin: 'model-router', key: 'view' } as const, {} as RouterView)
62
63/** The classifier's budget. A spawn waits on it, so a slow answer costs more than a wrong tier. */
64const CLASSIFY_MS = 3000
65/** How long a subagent's first request waits for its spawn to be recorded, so it gets its effort. */
66const SPAWN_WAIT_MS = 2000
67const MODE_KEY = 'mode'
68/** The model each unrouted agent type was last seen running on, for a fair baseline. */
69const TYPE_MODELS_KEY = 'agentModels'
70
71/** A router role's registered model as a full id, the model it runs on unrouted. */
72const ROLE_BASELINE = MODEL_FOR_TIER[tierOfModel(ROLE_MODEL)]
73
74/** True for the router's own roles, as registered from ROLES. */
75function isRole(role: string | undefined): boolean {
76  return ROLES.some(r => r.name === role)
77}
78
79type Baseline = 'unrouted' | Exclude<Family, 'haiku4' | 'haiku5'>
80
81function blankRow(id: string, label: string, agentType: string, now: number): AgentRow {
82  return { id, label, agentType, tokens: ZERO, cost: 0, startedAt: now }
83}
84
85function shortModel(model: string | undefined): string {
86  if (!model) return '?'
87  return { haiku4: 'Haiku4', haiku5: 'Haiku', sonnet: 'Sonnet', opus: 'Opus', fable: 'Fable' }[familyOf(model)]
88}
89
90/** The main conversation's cache lives an hour; a subagent's five minutes. */
91function ttlOf(id: string): CacheTtl {
92  return id === 'main' ? '1h' : '5m'
93}
94
95/**
96 * The same tokens on the baseline. Priced from the row's summed tokens, so a fixed baseline
97 * or a later change of the setting reprices the whole bill; a row that ran on its own model
98 * is, under the unrouted baseline, its own cost.
99 */
100function baselineCost(r: AgentRow, baseline: Baseline): number {
101  // A row that ran on its own model (the main conversation, a fork, a model Claude named) cost
102  // what it cost: no repricing, so a model the main conversation switched to counts as itself.
103  if (baseline === 'unrouted' && (r.via === 'unrouted' || r.via === 'explicit')) return r.cost
104  const family = baseline === 'unrouted' ? familyOf(r.baselineModel ?? r.model) : baseline
105  const ttl = ttlOf(r.id)
106  // Each side of Haiku 5.5's long-prompt threshold at its own rate, as the requests were billed.
107  const long = r.longTokens ?? ZERO
108  return costOf(subTokens(r.tokens, long), family, ttl, false) + costOf(long, family, ttl, true)
109}
110
111function totals(l: RouterLedger, baseline: Baseline) {
112  let cost = l.classifierCost
113  let base = 0
114  for (const r of Object.values(l.rows)) {
115    cost += r.cost
116    base += baselineCost(r, baseline)
117  }
118  return { cost, base, saved: base > 0 ? 1 - cost / base : 0 }
119}
120
121/** A spawn's row details, kept in memory so a row that `/clear` wiped can be written again. */
122type SpawnRow = Partial<AgentRow> & { startedAt: number }
123
124/**
125 * The row a step or a finish writes to: the ledger's, else one rebuilt from what the spawn
126 * recorded (its tokens and cost start over), else a blank one. `routed` counts a rebuilt
127 * routed row again, since the wipe took its count with it.
128 */
129function rowFor(
130  l: RouterLedger,
131  id: string,
132  now: number,
133  spawnRows: ReadonlyMap<string, SpawnRow>,
134): { row: AgentRow; routed: number } {
135  const row = l.rows[id]
136  if (row) return { row, routed: l.routed }
137  const blank =
138    id === 'main' ? blankRow(id, 'main conversation', 'main', now) : blankRow(id, 'subagent', '?', now)
139  const saved = spawnRows.get(id)
140  if (!saved) return { row: blank, routed: l.routed }
141  return {
142    row: { ...blank, ...saved, tokens: ZERO, cost: 0 },
143    routed: l.routed + (saved.via !== undefined && saved.via !== 'unrouted' ? 1 : 0),
144  }
145}
146
147/** Writes a spawned agent's row; its steps may have landed first, so it merges into them. */
148async function record(
149  $: EngineInterface,
150  id: string,
151  now: number,
152  fields: Partial<AgentRow>,
153  routed: boolean,
154  spawnRows: Map<string, SpawnRow>,
155) {
156  // Dropped oldest first, never all at once: a running agent's details must outlive a burst of spawns.
157  if (spawnRows.size > 500) spawnRows.delete(spawnRows.keys().next().value!)
158  spawnRows.set(id, { ...fields, startedAt: now })
159  await update($, ledger, l => {
160    const row = l.rows[id] ?? blankRow(id, 'subagent', '?', now)
161    return { ...l, routed: l.routed + (routed ? 1 : 0), rows: { ...l.rows, [id]: { ...row, ...fields } } }
162  })
163}
164
165/** How long a finished agent's line stays in the band above the prompt. */
166const BAND_FADE_MS = 30_000
167
168/**
169 * Marks an agent finished, once: its row gets `finishedAt`, restored first if a `/clear`
170 * wiped it, and the band is drawn again when the line's time is up.
171 */
172async function finishAgent(
173  $: EngineInterface,
174  id: string,
175  spawnRows: ReadonlyMap<string, SpawnRow>,
176  health: ReadonlyMap<string, Health>,
177) {
178  const now = await $.clock.now()
179  // The rescue's clock stops while the agent is finished: time waiting for a wake is not time
180  // struggling. rescueStep starts it again, and the counts over, when the agent runs again.
181  const h = health.get(id)
182  if (h && h.idleFrom === undefined) h.idleFrom = now
183  let finished = false
184  await update($, ledger, l => {
185    finished = false
186    if (!l.rows[id] && !spawnRows.has(id)) return l
187    const { row, routed } = rowFor(l, id, now, spawnRows)
188    if (row.finishedAt !== undefined) return l
189    finished = true
190    return { ...l, routed, rows: { ...l.rows, [id]: { ...row, finishedAt: now } } }
191  })
192  if (finished) $.clock.after(BAND_FADE_MS, () => $.ui.invalidate('ui.render'))
193}
194
195/** Statuses after which an agent will not step again on its own. */
196const ENDED = new Set(['completed', 'failed', 'killed', 'idle'])
197/** How old a row must be before a missing list entry counts as finished: a new spawn may not be listed yet. */
198const RECONCILE_AFTER_MS = 10_000
199
200/**
201 * Finishes the rows of agents the engine no longer runs, for an agent whose finish events
202 * were missed (it ended before this module loaded, or was killed): its band line would
203 * otherwise stay up for the rest of the session.
204 */
205async function reconcileAgents(
206  $: EngineInterface,
207  spawnRows: ReadonlyMap<string, SpawnRow>,
208  health: ReadonlyMap<string, Health>,
209) {
210  const l = await read($, ledger)
211  const now = await $.clock.now()
212  const open = Object.values(l.rows).filter(
213    r => r.id !== 'main' && r.finishedAt === undefined && now - r.startedAt > RECONCILE_AFTER_MS,
214  )
215  if (open.length === 0) return
216  const status = new Map((await $.agent.list()).map(a => [a.id, a.status as string]))
217  for (const r of open) {
218    const s = status.get(r.id)
219    if (s === undefined || ENDED.has(s)) await finishAgent($, r.id, spawnRows, health)
220  }
221}
222
223/** The pane's fixed column widths; Agent takes what is left of the pane. */
224const TIER_WIDTH = 8
225const MODEL_WIDTH = 8
226const TIME_WIDTH = 6
227const COST_WIDTH = 8
228const BASE_WIDTH = 10
229/** The columns that always show; Time joins them when the Agent column can spare it. */
230const MIN_FIXED = TIER_WIDTH + MODEL_WIDTH + COST_WIDTH + BASE_WIDTH
231/** The narrowest Agent column: a status mark and the ellipsis. */
232const AGENT_MIN = 4
233/** The header's label column. */
234const FIELD_WIDTH = 12
235/** The Agent column the Time column must leave before it shows. */
236const AGENT_WIDE = 16
237
238/**
239 * Tier word for the pane: `↑` when it was moved up after struggling, `!` when the risk floor
240 * raised it, `↓` when rate limits lowered it.
241 */
242function tierLabel(r: AgentRow): string {
243  if (!r.tier || r.via === 'unrouted') return '-'
244  return TIER_WORD[r.tier] + (r.rescued ? '↑' : r.risky ? '!' : r.pressure !== undefined || r.budget !== undefined ? '↓' : '')
245}
246
247/**
248 * How a routed agent is getting on, for the rescue: its tier and role, what went wrong so far,
249 * and when it finished (`idleFrom`) if it has not run since.
250 */
251type Health = { tier: Tier; role: string | undefined; errors: number; steps: number; since: number; idleFrom?: number }
252
253/**
254 * Counts one more request of a routed agent and, when it is struggling, moves it up one model:
255 * its next requests go there, its effort cap follows the new tier, and its row says why.
256 * The counts start over, so an agent still stuck one tier up can move once more.
257 */
258async function rescueStep(
259  $: EngineInterface,
260  id: string,
261  maps: {
262    health: Map<string, Health>
263    rescuedTo: Map<string, string>
264    effortCaps: Map<string, Effort | undefined>
265    spawnRows: Map<string, SpawnRow>
266  },
267  effortByTier: boolean,
268) {
269  const h = maps.health.get(id)
270  if (!h) return
271  const now = await $.clock.now()
272  if (h.idleFrom !== undefined) {
273    // Woken after finishing (SendMessage): the time it sat idle is left out, and the counts start over.
274    h.since += now - h.idleFrom
275    h.idleFrom = undefined
276    h.steps = 0
277    h.errors = 0
278  }
279  h.steps += 1
280  const reason = rescueReason(h.tier, { errors: h.errors, steps: h.steps, ms: now - h.since })
281  if (!reason) return
282  const up = rescueTier(h.tier, h.role)
283  if (!up) {
284    maps.health.delete(id) // nowhere left to go: stop counting
285    return
286  }
287  const model = MODEL_FOR_TIER[up]
288  if (maps.rescuedTo.size > 500) maps.rescuedTo.delete(maps.rescuedTo.keys().next().value!)
289  maps.rescuedTo.set(id, model)
290  maps.health.set(id, { ...h, tier: up, errors: 0, steps: 0, since: now })
291  const effort = effortByTier ? EFFORT_CAP[up] : undefined
292  if (maps.effortCaps.has(id)) maps.effortCaps.set(id, effort)
293  const note = ` · moved up to ${shortModel(model)} (${reason})`
294  const saved = maps.spawnRows.get(id)
295  if (saved) maps.spawnRows.set(id, { ...saved, tier: up, model, effort, why: (saved.why ?? '') + note })
296  await update($, ledger, l => {
297    const row = l.rows[id]
298    if (!row) return l
299    return {
300      ...l,
301      rows: { ...l.rows, [id]: { ...row, tier: up, model, effort, rescued: (row.rescued ?? 0) + 1, why: (row.why ?? '') + note } },
302    }
303  })
304}
305
306/** One running (or just finished) routed subagent, as the band above the prompt shows it. */
307function bandLine(r: AgentRow): string {
308  return `⇄ ${roleOf(r.agentType) ?? r.agentType}: ${r.label} → ${shortModel(r.model)} · ${usd(r.cost)}`
309}
310
311/** The pane's savings: `saved N%`, or `N% more` when routing cost more than the baseline. */
312function savedText(t: { base: number; saved: number }): string {
313  if (t.base <= 0) return ''
314  const pct = Math.round(t.saved * 100)
315  return pct < 0 ? `   ${-pct}% more` : `   saved ${pct}%`
316}
317
318/** The status line's savings: `N% saved`, or `N% more` when routing cost more than the baseline. */
319function statusSaved(saved: number): string {
320  const pct = Math.round(saved * 100)
321  return pct < 0 ? `${-pct}% more` : `${pct}% saved`
322}
323
324/** A label cut to fit `width` cells with a space to spare, ending in `…` when cut. */
325function fit(text: string, width: number): string {
326  return text.length > width - 1 ? text.slice(0, Math.max(0, width - 2)) + '…' : text
327}
328
329/** The fullest rate-limit window in percent; 0 when the engine has none or the call fails. */
330async function windowPercent($: EngineInterface): Promise<number> {
331  try {
332    return fullestWindow((await $.session.usage()).rateLimits)
333  } catch {
334    return 0
335  }
336}
337
338/** What a mode does, as `/router` and `/router status` say it. */
339function modeText(mode: Mode): string {
340  if (mode === 'on') return 'on: Haiku picks the model for each subagent'
341  if (mode === 'off') return 'off: subagents run on the model they would have without the router'
342  return `sending every routed subagent to ${shortModel(MODEL_FOR_TIER[FORCED_TIER[mode]])}`
343}
344
345function modeLabel(mode: Mode): string | undefined {
346  if (mode === 'on') return undefined
347  if (mode === 'off') return 'router off'
348  return `router: all ${shortModel(MODEL_FOR_TIER[FORCED_TIER[mode]])}`
349}
350
351async function refreshStatus(
352  $: EngineInterface,
353  baseline: Baseline,
354  baselineName: string,
355  mode: Mode,
356  pressureAt: number | undefined,
357  budgetLimit?: number,
358) {
359  const l = await read($, ledger)
360  const t = totals(l, baseline)
361  const parts = [modeLabel(mode)]
362  if (budgetLimit !== undefined) parts.push(`budget ${Math.round((t.cost / budgetLimit) * 100)}% of $${budgetLimit}`)
363  if (mode === 'on' && pressureAt !== undefined) {
364    const pct = await windowPercent($)
365    if (pct >= pressureAt) parts.push(`limits ${Math.round(pct)}%: one tier down`)
366  }
367  // Against the unrouted baseline nothing can be saved until an agent is routed: the main
368  // conversation is never routed, so "N vs N (0% saved)" would only look like a fault.
369  if (baseline === 'unrouted' && l.routed === 0) {
370    if (t.cost > 0) parts.push(`${usd(t.cost)} · no agents routed yet`)
371  } else if (t.base > 0) parts.push(`${usd(t.cost)} vs ${usd(t.base)} ${baselineName} (${statusSaved(t.saved)})`)
372  const text = parts.filter(Boolean).join(' · ')
373  $.ui.status(text || undefined)
374}
375
376/** Resolves undefined after `ms`, so a call raced against it can't hold a spawn up. */
377function timeout($: EngineInterface, ms: number): Promise<undefined> {
378  return $.clock.sleep(ms).then(() => undefined)
379}
380
381/**
382 * The `/router` mode: the atom when it holds one, else what the store kept from an earlier
383 * session, else on. It only reads, so a ui.render hook may call it: state.set is refused
384 * while one draws, and /clear empties the atom before the pane is drawn again.
385 */
386async function currentMode($: EngineInterface): Promise<Mode> {
387  return (await read($, modeState)) ?? (await storedMode($)) ?? 'on'
388}
389
390/**
391 * currentMode, and the atom filled when it was empty so the pane reads it from then on.
392 * For the hooks that run outside a draw (session.start, command.run, agent.spawn,
393 * turn.step, session.end), never a ui.render hook.
394 */
395async function loadMode($: EngineInterface): Promise<Mode> {
396  const held = await read($, modeState)
397  if (held !== undefined) return held
398  const mode = (await storedMode($)) ?? 'on'
399  await update($, modeState, () => mode)
400  return mode
401}
402
403async function setMode($: EngineInterface, next: Mode) {
404  await update($, modeState, () => next)
405}
406
407/** The `/router` mode saved by an earlier session, if any. */
408async function storedMode($: EngineInterface): Promise<Mode | undefined> {
409  try {
410    return parseMode(await $.store.get(MODE_KEY))
411  } catch {
412    return undefined
413  }
414}
415
416/** The models agent types ran on in earlier sessions; empty when nothing is stored or the read fails. */
417async function storedTypeModels($: EngineInterface): Promise<Record<string, string>> {
418  try {
419    const v = await $.store.get(TYPE_MODELS_KEY)
420    if (!v || typeof v !== 'object' || Array.isArray(v)) return {}
421    return Object.fromEntries(Object.entries(v).filter((p): p is [string, string] => typeof p[1] === 'string'))
422  } catch {
423    return {}
424  }
425}
426
427type TypeModels = { models: Record<string, string>; loaded: boolean }
428
429/** Reads the stored type models once; a type seen before the read keeps what was seen. */
430async function loadTypeModels($: EngineInterface, t: TypeModels) {
431  if (t.loaded) return
432  t.loaded = true
433  t.models = { ...(await storedTypeModels($)), ...t.models }
434}
435
436/** Remembers the model an unrouted agent type ran on, writing the store only on a change. */
437async function rememberTypeModel($: EngineInterface, t: TypeModels, type: string, model: string) {
438  if (t.models[type] === model) return
439  t.models = { ...t.models, [type]: model }
440  try {
441    await $.store.set(TYPE_MODELS_KEY, t.models)
442  } catch (err) {
443    $.ui.log(`could not save the model of ${type}: ${String(err)}`)
444  }
445}
446
447/**
448 * The effort cap of a routed subagent. Its first step can beat its spawn's answer, so it
449 * waits briefly for spawns in flight. The caps are kept in memory because a hook reads
450 * `$.state` as of the moment it started: a row written during the wait is not seen. The
451 * ledger is the fallback after a hot reload has emptied memory.
452 */
453async function effortCapOf(
454  $: EngineInterface,
455  agentId: string,
456  caps: ReadonlyMap<string, Effort | undefined>,
457  starting: ReadonlySet<Promise<unknown>>,
458) {
459  if (!caps.has(agentId) && starting.size > 0) {
460    await Promise.race([Promise.allSettled([...starting]), timeout($, SPAWN_WAIT_MS)])
461  }
462  return caps.has(agentId) ? caps.get(agentId) : (await read($, ledger)).rows[agentId]?.effort
463}
464
465/** Where classifier verdicts are kept across sessions, by a hash of what the classifier read. */
466const CLASS_CACHE_KEY = 'classified'
467/** How many verdicts the cache keeps; the oldest goes first. */
468const CLASS_CACHE_MAX = 300
469
470type ClassCache = { entries: Map<string, { tier: Tier; risky: boolean }>; loaded: boolean }
471
472/** A SHA-256 of the text, so the store keeps no task text. */
473async function hashKey(text: string): Promise<string> {
474  const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))
475  return Array.from(new Uint8Array(digest), b => b.toString(16).padStart(2, '0')).join('')
476}
477
478/** Reads the cached verdicts once; a verdict made before the read keeps its place. */
479async function loadClassCache($: EngineInterface, c: ClassCache) {
480  if (c.loaded) return
481  c.loaded = true
482  try {
483    const v = await $.store.get(CLASS_CACHE_KEY)
484    if (!v || typeof v !== 'object' || Array.isArray(v)) return
485    const stored = new Map<string, { tier: Tier; risky: boolean }>()
486    for (const [k, x] of Object.entries(v as Record<string, unknown>)) {
487      const [tier, risky] = String(x).split('|')
488      if (ORDER.includes(tier as Tier)) stored.set(k, { tier: tier as Tier, risky: risky === 'r' })
489    }
490    c.entries = new Map([...stored, ...c.entries])
491  } catch {
492    // start with an empty cache
493  }
494}
495
496/** Keeps a verdict, dropping the oldest past the cap, and saves the cache. */
497async function rememberClass($: EngineInterface, c: ClassCache, key: string, v: { tier: Tier; risky: boolean }) {
498  c.entries.delete(key)
499  c.entries.set(key, v)
500  while (c.entries.size > CLASS_CACHE_MAX) c.entries.delete(c.entries.keys().next().value!)
501  try {
502    await $.store.set(
503      CLASS_CACHE_KEY,
504      Object.fromEntries([...c.entries].map(([k, x]) => [k, `${x.tier}|${x.risky ? 'r' : ''}`])),
505    )
506  } catch (err) {
507    $.ui.log(`could not save the classifier cache: ${String(err)}`)
508  }
509}
510
511/** The budget gauge's text: `████░ 84% of $5`. */
512function budgetText(spent: number, usd: number, now: number): string {
513  return `${windowGauge({ percentUsed: (spent / usd) * 100 }, now)} of $${usd}`
514}
515
516export const register: Register = (on, options) => {
517  const baseline = (['unrouted', 'fable', 'opus', 'sonnet'].includes(String(options.baseline))
518    ? options.baseline
519    : 'unrouted') as Baseline
520  const routeAll = options.routeAll !== false
521  const respectExplicit = options.respectExplicitModel !== false
522  const baselineName = baseline === 'unrouted' ? 'unrouted' : `on ${shortModel(baseline)}`
523  const effortByTier = options.effortByTier !== false
524  const rescueOn = options.rescue !== false
525  const budgetLimit = budgetUsd(options.budget)
526  const riskFloor = options.riskFloor !== false
527  const openAtStart = options.openPane !== false
528  const pressureAt = options.limitPressure === 'off' ? undefined : pressureThreshold(options.limitPressure)
529
530  /**
531   * The model each agent type ran on when the router left it alone, by type. A built-in
532   * such as Explore runs on its own model, not its parent's, so this is its baseline.
533   */
534  const typeModels: TypeModels = { models: {}, loaded: false }
535  /** Agent calls that set their own effort, by tool_use_id, until their spawn reads it. */
536  const callEffort = new Set<string>()
537  /** Spawns between the call to `next` and its answer, which a first step may overtake. */
538  const starting = new Set<Promise<unknown>>()
539  /** Each routed subagent's effort cap, by agent id, as soon as it has started. */
540  const effortCaps = new Map<string, Effort | undefined>()
541  /** Each spawn's row details, by agent id, for rows a `/clear` wiped while the agent ran on. */
542  const spawnRows = new Map<string, SpawnRow>()
543  /** Each agent the classifier placed, by id: how it is doing, for the rescue. */
544  const health = new Map<string, Health>()
545  /** The model each rescued agent now runs on, by id. */
546  const rescuedTo = new Map<string, string>()
547  /** Classifier verdicts by a hash of what it read, so a repeated task skips the call. */
548  const classCache: ClassCache = { entries: new Map(), loaded: false }
549  /** The highest budget mark already announced with a toast: 0, 80 or 100. */
550  let budgetToasted = 0
551
552  on('session.start', async ($, e, next) => {
553    const mode = await loadMode($)
554    if (mode !== 'on') $.ui.status(modeLabel(mode))
555    for (const role of ROLES) {
556      try {
557        await $.agent.register({ ...role, model: ROLE_MODEL })
558      } catch (err) {
559        $.ui.log(`could not add agent ${role.name}: ${String(err)}`)
560      }
561    }
562    try {
563      await $.command.register({
564        name: 'router',
565        description: 'Open the model router bill pane; on, off, haiku, sonnet or opus sets the mode; reset clears the bill',
566        argumentHint: '[on|off|haiku|sonnet|opus|status|reset]',
567        immediate: true,
568      })
569    } catch (err) {
570      $.ui.log(`could not add /router: ${String(err)}`)
571    }
572    // Opened unasked, so it only seats in a wide terminal; /router opens it anywhere.
573    if (openAtStart) void $.ui.open({ id: PANE, title: 'Model router' })
574    return next(e)
575  })
576
577  on('command.run', { command: 'router' }, async ($, e) => {
578    const arg = e.args.trim().toLowerCase()
579    const mode = await loadMode($)
580    if (arg === 'reset') {
581      await update($, ledger, () => EMPTY)
582      await update($, meter, m => ({ ...(m ?? EMPTY_METER), turn: undefined, lastTurn: undefined }))
583      await update($, view, () => ({}))
584      budgetToasted = 0
585      $.ui.status(modeLabel(mode))
586      return { text: 'Model router bill cleared.' }
587    }
588    if (arg === 'status') return { text: `Model router ${modeText(mode)}.` }
589    const picked = parseMode(arg)
590    if (picked) {
591      await setMode($, picked)
592      try {
593        await $.store.set(MODE_KEY, picked)
594      } catch (err) {
595        $.ui.log(`could not save the router mode: ${String(err)}`)
596      }
597      await refreshStatus($, baseline, baselineName, picked, pressureAt, budgetLimit)
598      const back = picked === 'on' ? '' : '; /router on to go back'
599      return { text: `Model router ${modeText(picked)}. Kept across sessions${back}.` }
600    }
601    if (arg) return { text: `Unknown option "${arg}". Use on, off, haiku, sonnet, opus, status or reset.` }
602    await $.ui.open({ id: PANE, title: 'Model router', focus: true, closeOnEscape: true })
603    return {}
604  })
605
606  // An Agent call that sets its own effort was asked for that effort: remember it so
607  // the router leaves that agent's effort alone.
608  on('tool.call', { tool: 'Agent' }, async ($, e, next) => {
609    if (e.tool === 'Agent' && e.effort && e.tool_use_id) {
610      // Read and removed by the spawn; a call that never spawns leaves one id behind.
611      if (callEffort.size > 200) callEffort.clear()
612      callEffort.add(e.tool_use_id)
613    }
614    return next(e)
615  }).catch(($, e, next) => next(e)) // a note about effort is a side job: never block the call
616
617  // A routed agent's tool calls: failures in a row are the rescue's first sign of trouble.
618  // Not for a runner: reporting a failing command is its job, not a sign it is stuck.
619  on('tool.call', async ($, e, next) => {
620    const result = await next(e)
621    const h = e.agentId ? health.get(e.agentId) : undefined
622    if (h && h.role !== 'runner' && result.deny === undefined) h.errors = 'isError' in result && result.isError ? h.errors + 1 : 0
623    return result
624  }).catch(($, e, next) => next(e)) // watching is a side job: never block the call
625
626  // 1. Haiku reads the task and sorts it. 2. The router sets the model.
627  on('agent.spawn', async ($, e, next) => {
628    const mode = await loadMode($)
629    await loadTypeModels($, typeModels)
630    const callSetEffort = callEffort.delete(e.tool_use_id)
631    const role = roleOf(e.subagentType)
632    const now = await $.clock.now()
633
634    // Not routed: forks always inherit, a workflow agent's model cannot be rewritten,
635    // a teammate is long-lived and always background (so it would qualify for Fable on
636    // its first message alone), and with routing narrowed only the router's own agents
637    // are touched. `/router off` leaves everything alone.
638    if (mode === 'off' || e.fork || e.workflow || e.isTeammate || (!routeAll && !role)) {
639      const result = await next(e)
640      if (result.deny === undefined && result.agentId) {
641        await record($, result.agentId, now, {
642          label: e.description || e.name || e.subagentType,
643          agentType: e.subagentType,
644          via: 'unrouted',
645          model: result.model,
646          baselineModel: result.model,
647          why:
648            mode === 'off'
649              ? 'not routed: /router off'
650              : e.fork
651                ? 'not routed: a fork keeps its parent\'s model'
652                : e.workflow
653                  ? 'not routed: a workflow agent\'s model cannot be changed'
654                  : e.isTeammate
655                    ? 'not routed: teammates keep their team\'s model'
656                    : 'not routed: Route every subagent is off',
657        }, false, spawnRows)
658        // What this type runs on by itself: a fork or teammate takes its parent's, a
659        // workflow agent or a named model is the call's choice, not the type's. The
660        // router's own agents are compared with their registered model instead.
661        if (!role && !e.fork && !e.workflow && !e.isTeammate && !e.model && result.model) {
662          await rememberTypeModel($, typeModels, e.subagentType, result.model)
663        }
664      }
665      return result
666    }
667
668    let tier: Tier
669    let via: AgentRow['via']
670    let model: string | undefined
671    let risky = false
672    let pressure: number | undefined
673    let budgetPct: number | undefined
674    let why: string
675
676    if (respectExplicit && e.model) {
677      via = 'explicit'
678      model = e.model
679      tier = tierOfModel(e.model)
680      why = `kept: the Agent call named ${shortModel(e.model)}`
681    } else if (mode !== 'on') {
682      via = 'forced'
683      tier = FORCED_TIER[mode]
684      model = MODEL_FOR_TIER[tier]
685      why = `/router ${mode}: every routed subagent on ${shortModel(model)}`
686    } else {
687      let picked: Tier | undefined
688      let cached = false
689      const asked0 = { agentType: e.subagentType, description: e.description, prompt: e.prompt }
690      const key = await hashKey(classifyKey(asked0))
691      await loadClassCache($, classCache)
692      const hit = classCache.entries.get(key)
693      if (hit) {
694        picked = hit.tier
695        risky = hit.risky
696        cached = true
697      } else try {
698        const r = await $.model.complete(
699          {
700            model: CLASSIFIER_MODEL,
701            system: CLASSIFIER_SYSTEM,
702            prompt: classifierPrompt({
703              agentType: e.subagentType,
704              description: e.description,
705              prompt: e.prompt,
706            }),
707            // Room for a short explanation before the verdict: a reply cut off before its
708            // last line would be read without one.
709            maxTokens: 48,
710            effort: CLASSIFIER_EFFORT,
711            timeoutMs: CLASSIFY_MS,
712          },
713          { signal: next.signal },
714        )
715        const c = costOf(tokensFromUsage(r.usage), familyOf(CLASSIFIER_MODEL))
716        await update($, ledger, l => ({ ...l, classifierCost: l.classifierCost + c }))
717        if (r.isAnswered) {
718          picked = parseTier(r.text)
719          // The risk flag comes with a verdict or not at all: a reply cut off mid-explanation
720          // ("...so no risky") must not flag the task.
721          risky = picked !== undefined && parseRisky(r.text)
722          if (picked) await rememberClass($, classCache, key, { tier: picked, risky })
723        }
724      } catch {
725        // try the built-in classifier
726      }
727      via = picked ? 'haiku' : undefined
728      if (!picked) {
729        // The engine's own small model, with no rubric: worse than Haiku 4.5 with one, better
730        // than a fixed default, and it keeps working if the pinned classifier model goes away.
731        try {
732          const label = await Promise.race([
733            $.model.classify(builtinClassifierText({
734              agentType: e.subagentType,
735              description: e.description,
736              prompt: e.prompt,
737            }), ORDER),
738            timeout($, CLASSIFY_MS),
739          ])
740          picked = parseTier(label ?? '')
741          if (picked) via = 'builtin'
742        } catch {
743          // fall through to the role's default
744        }
745      }
746      via ??= 'fallback'
747      // Without Haiku's judgment, only a plainly destructive act counts as risky.
748      if (via !== 'haiku') risky ||= looksRisky(`${e.description}\n${e.prompt}`)
749      risky &&= riskFloor
750      const asked = picked ?? fallbackTier(role)
751      // Agents run in the background by default, so only the task's own words open up `long`.
752      const allowLong = asksForLongRun(`${e.description}\n${e.prompt}`)
753      tier = routeTier(asked, role, allowLong, { risky })
754      if (pressureAt !== undefined) {
755        const pct = await windowPercent($)
756        const lower = pct >= pressureAt ? routeTier(asked, role, allowLong, { risky, underPressure: true }) : tier
757        // Marked only when the window actually moved the agent down.
758        if (lower !== tier) {
759          tier = lower
760          pressure = pct
761        }
762      }
763      if (budgetLimit !== undefined) {
764        const pct = (totals(await read($, ledger), baseline).cost / budgetLimit) * 100
765        if (pct >= BUDGET_WARN) {
766          const lower = routeTier(asked, role, allowLong, { risky, underPressure: true, cheapest: pct >= 100 })
767          if (ORDER.indexOf(lower) < ORDER.indexOf(tier)) {
768            tier = lower
769            budgetPct = pct
770          }
771        }
772      }
773      model = MODEL_FOR_TIER[tier]
774      why = explainTier({
775        source: via,
776        asked,
777        final: tier,
778        role,
779        risky,
780        allowLong,
781        pressure,
782        cached,
783        budget: budgetPct !== undefined && budgetLimit !== undefined ? { pct: budgetPct, usd: budgetLimit } : undefined,
784      })
785    }
786
787    // Effort is set per request in turn.step; here the router only decides the cap.
788    const effort =
789      effortByTier && via !== 'explicit' && via !== 'forced' && !callSetEffort
790        ? EFFORT_CAP[tier]
791        : undefined
792    if (effort) why += ` · effort ≤ ${effort}`
793
794    // Held in `starting` until the cap is known: the agent's first request can arrive
795    // before `next` answers and must wait for its effort cap.
796    const spawned = (async () => {
797      const result = await next({ ...e, model })
798      if (result.deny !== undefined || !result.agentId) return result
799      if (effortCaps.size > 500) effortCaps.clear()
800      effortCaps.set(result.agentId, effort)
801      // Only an agent the classifier placed can be moved up: a named or forced model stays.
802      if (rescueOn && (via === 'haiku' || via === 'builtin' || via === 'fallback')) {
803        if (health.size > 500) health.delete(health.keys().next().value!)
804        health.set(result.agentId, { tier, role, errors: 0, steps: 0, since: now })
805      }
806      await record($, result.agentId, now, {
807        label: e.description,
808        agentType: e.subagentType,
809        tier,
810        via,
811        model: result.model,
812        effort,
813        risky: risky || undefined,
814        pressure,
815        budget: budgetPct,
816        why,
817        // A model Claude named would have run anyway. A router role runs on its registered
818        // model; another type on its own model when it was seen running unrouted (a built-in
819        // such as Explore), else on the parent's it inherits. The parent's model is a guess,
820        // marked for the pane.
821        baselineModel:
822          via === 'explicit'
823            ? result.model
824            : isRole(role)
825              ? ROLE_BASELINE
826              : (typeModels.models[e.subagentType] ?? e.parentModel),
827        baselineGuessed:
828          (via !== 'explicit' && !isRole(role) && typeModels.models[e.subagentType] === undefined) || undefined,
829      }, true, spawnRows)
830      return result
831    })()
832    starting.add(spawned)
833    try {
834      return await spawned
835    } finally {
836      starting.delete(spawned)
837    }
838  }).catch(($, e, next) => next(e)) // routing is an optimisation: on failure, spawn as asked
839
840  // 3. Effort, lowered for easy tiers. 4. The bill: every model request, priced on the model that answered it.
841  on('turn.step', async function* ($, e, next) {
842    await loadMode($) // the first hook after /clear with a prompt: the pane reads the mode again
843    let request = e
844    if (e.agentId && health.has(e.agentId)) {
845      try {
846        await rescueStep($, e.agentId, { health, rescuedTo, effortCaps, spawnRows }, effortByTier)
847      } catch {
848        // the rescue is a side job: the request goes as it was
849      }
850    }
851    const movedTo = e.agentId ? rescuedTo.get(e.agentId) : undefined
852    if (movedTo && movedTo !== e.model) request = { ...request, model: movedTo }
853    if (effortByTier && e.agentId && e.effort !== undefined) {
854      try {
855        const effort = capEffort(e.effort, await effortCapOf($, e.agentId, effortCaps, starting))
856        if (effort !== e.effort) request = { ...request, effort }
857      } catch {
858        // leave the request as it is
859      }
860    }
861    const result = yield* next(request)
862    if (!result.usage) return result
863    const usage = result.usage
864    const t: Tokens = tokensFromUsage(usage)
865    const id = e.agentId ?? 'main'
866    const actual = costOf(t, familyOf(usage.model), ttlOf(id))
867    const now = await $.clock.now()
868    await update($, ledger, l => {
869      const { row, routed } = rowFor(l, id, now, spawnRows)
870      return {
871        ...l,
872        routed,
873        rows: {
874          ...l.rows,
875          [id]: {
876            ...row,
877            // The main conversation shows the model it is on now (/model can change it); a
878            // subagent keeps the model it was spawned on or moved up to.
879            model: id === 'main' ? (usage.model ?? row.model) : (row.model ?? usage.model),
880            via: row.via ?? (id === 'main' ? 'unrouted' : row.via),
881            baselineModel: row.baselineModel ?? (id === 'main' ? usage.model : undefined),
882            tokens: addTokens(row.tokens, t),
883            longTokens: isLongPrompt(t) ? addTokens(row.longTokens ?? ZERO, t) : row.longTokens,
884            cost: row.cost + actual,
885            // A finished agent woken again (SendMessage) is running once more.
886            finishedAt: undefined,
887          },
888        },
889      }
890    })
891    return result
892  })
893
894  // The main conversation's turn: the bill as it stood when the turn began, for the receipt.
895  // A subagent's run starts turns of its own inside it, which must not restart the mark.
896  on('turn.start', async ($, e, next) => {
897    if (e.agentId !== undefined) return next(e)
898    try {
899      const t = totals(await read($, ledger), baseline)
900      const agents = Object.keys((await read($, ledger)).rows).filter(id => id !== 'main').length
901      const startedAt = await $.clock.now()
902      await update($, meter, m => ({ ...(m ?? EMPTY_METER), turn: { startedAt, cost: t.cost, base: t.base, agents } }))
903    } catch {
904      // the receipt is a side job
905    }
906    return next(e)
907  })
908
909  // A subagent's run ends with its own turn.complete; SubagentStop backs it up. Either
910  // marks the row finished (once) and brings the status line up to date at once. The
911  // main conversation's turn writes the receipt and finishes agents the engine has dropped.
912  on('turn.complete', async ($, e, next) => {
913    if (e.agentId) {
914      await finishAgent($, e.agentId, spawnRows, health)
915    } else {
916      try {
917        const l = await read($, ledger)
918        const t = totals(l, baseline)
919        const agents = Object.keys(l.rows).filter(id => id !== 'main').length
920        const now = await $.clock.now()
921        await update($, meter, m => {
922          const mark = (m ?? EMPTY_METER).turn
923          if (!mark) return m ?? EMPTY_METER
924          const cost = t.cost - mark.cost
925          return {
926            ...(m ?? EMPTY_METER),
927            turn: undefined,
928            lastTurn: { ms: now - mark.startedAt, agents: agents - mark.agents, cost, saved: t.base - mark.base - cost },
929          }
930        })
931        await reconcileAgents($, spawnRows, health)
932        // session.measure can trail the turn; read the engine's figures once more as it ends.
933        const u = await $.session.usage()
934        await update($, meter, m => ({
935          ...(m ?? EMPTY_METER),
936          limits: u.rateLimits.map(w => ({ kind: w.kind, percentUsed: w.percentUsed, resetsAt: w.resetsAt })),
937          engineCost: u.cost?.usd ?? (m ?? EMPTY_METER).engineCost,
938        }))
939      } catch {
940        // the receipt is a side job
941      }
942    }
943    await refreshStatus($, baseline, baselineName, await currentMode($), pressureAt, budgetLimit)
944    if (budgetLimit !== undefined) {
945      const pct = (totals(await read($, ledger), baseline).cost / budgetLimit) * 100
946      const mark = pct >= 100 ? 100 : pct >= BUDGET_WARN ? BUDGET_WARN : 0
947      if (mark > budgetToasted) {
948        budgetToasted = mark
949        $.ui.toast(
950          mark === 100
951            ? `Model router: $${budgetLimit} budget spent. Routed agents now get the cheapest model their role allows.`
952            : `Model router: ${Math.round(pct)}% of the $${budgetLimit} budget. Routing one tier cheaper.`,
953        )
954      }
955    }
956    return next(e)
957  })
958
959  // The engine's own figures: the rate-limit windows for the pane's gauges, and the
960  // session's cost to set beside the bill.
961  on('session.measure', async ($, e, next) => {
962    if (e.changed.includes('rateLimits') || e.changed.includes('cost')) {
963      try {
964        await update($, meter, m => ({
965          ...(m ?? EMPTY_METER),
966          limits: e.rateLimits.map(l => ({ kind: l.kind, percentUsed: l.percentUsed, resetsAt: l.resetsAt })),
967          engineCost: e.cost?.usd ?? (m ?? EMPTY_METER).engineCost,
968        }))
969      } catch {
970        // a reading is a side job
971      }
972    }
973    return next(e)
974  })
975
976  on('classic.SubagentStop', async ($, e, next) => {
977    await finishAgent($, e.agent_id, spawnRows, health)
978    await refreshStatus($, baseline, baselineName, await currentMode($), pressureAt, budgetLimit)
979    return next(e)
980  }).catch(($, e, next) => next(e)) // the bill is a side job: never hold up a stop
981
982  // /clear starts a new session with an empty bill, so the totals go. Kept to one call:
983  // session.end shares a short bound. spawnRows stays, for agents still running.
984  on('session.end', async ($, e, next) => {
985    if (e.reason === 'clear') {
986      budgetToasted = 0
987      $.ui.status(modeLabel(await loadMode($)))
988    }
989    return next(e)
990  })
991
992  // The band above the prompt: one line per routed subagent while it runs, fading
993  // BAND_FADE_MS after it finished.
994  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
995    if (e.props.hasSurvey) return next(e)
996    const l = await read($, ledger)
997    const now = await $.clock.now()
998    const rows = Object.values(l.rows)
999      .filter(r => r.id !== 'main' && r.via !== undefined && r.via !== 'unrouted')
1000      .filter(r => r.finishedAt === undefined || now - r.finishedAt < BAND_FADE_MS)
1001      .sort((a, b) => a.startedAt - b.startedAt)
1002    if (rows.length === 0) return next(e)
1003    const { Box, Text } = $.ui.resolve(e)
1004    return (
1005      <Box flexDirection="column" width={e.props.bodyColumns}>
1006        {rows.slice(0, Math.max(1, e.props.maxRows)).map(r => (
1007          <Text wrap="truncate" dimColor={r.finishedAt !== undefined}>
1008            {bandLine(r)}
1009          </Text>
1010        ))}
1011      </Box>
1012    )
1013  })
1014
1015  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
1016    const els = $.ui.resolve(e)
1017    const { Box, Text, Button } = els
1018    const hasClient = 'Client' in els
1019    const mode = await currentMode($)
1020    const l = await read($, ledger)
1021    const m = (await read($, meter)) ?? EMPTY_METER
1022    const expanded = ((await read($, view)) ?? {}).expanded
1023    const now = await $.clock.now()
1024    const t = totals(l, baseline)
1025    const width = Math.max(MIN_FIXED + AGENT_MIN, (e.props.bodyColumns ?? 60) - 2)
1026    // The Time column goes first when the pane is narrow: the money columns stay whole.
1027    const withTime = width >= MIN_FIXED + TIME_WIDTH + AGENT_WIDE
1028    const fixed = MIN_FIXED + (withTime ? TIME_WIDTH : 0)
1029    const rows = Object.values(l.rows).sort((a, b) => b.startedAt - a.startedAt)
1030    const agents = rows.filter(r => r.id !== 'main').length
1031    const room = Math.max(3, (e.viewport?.rows ?? 30) - 18)
1032    const shown = rows.slice(0, room)
1033    const agentWidth = width - fixed
1034    const baseHead = baseline === 'unrouted' ? 'Unrouted' : `On ${shortModel(baseline)}`
1035    const hasRisky = shown.some(r => tierLabel(r).endsWith('!'))
1036    const hasRescued = shown.some(r => tierLabel(r).endsWith('↑'))
1037    const hasPressure = shown.some(r => tierLabel(r).endsWith('↓'))
1038    const hasGuessed = baseline === 'unrouted' && shown.some(r => r.baselineGuessed)
1039    const tight = pressureAt !== undefined && m.limits.some(w => w.percentUsed >= pressureAt)
1040    const rowsCost = Object.values(l.rows).reduce((sum, r) => sum + r.cost, 0)
1041
1042    // A labelled header row: the label in a fixed column so the values line up.
1043    const field = (label: string, value: string, color?: string) => (
1044      <Text key={`field-${label}`} wrap="truncate" color={color}>
1045        {label.padEnd(FIELD_WIDTH) + value}
1046      </Text>
1047    )
1048
1049    const toggle = (id: string) => () =>
1050      update($, view, v => ({ expanded: (v ?? {}).expanded === id ? undefined : id }))
1051
1052    const clock = (r: AgentRow) =>
1053      r.id === 'main' ? (
1054        <Text dimColor>–</Text>
1055      ) : hasClient && r.finishedAt === undefined ? (
1056        <els.Client key={`clock-${r.id}`} module="./clock.tsx" props={{ since: r.startedAt, now, endAt: null }} />
1057      ) : (
1058        <Text dimColor>{clockText((r.finishedAt ?? now) - r.startedAt)}</Text>
1059      )
1060
1061    // One fixed-width Box per cell; the money columns right-aligned.
1062    const line = (
1063      agent: RenderElement | string,
1064      tier: string,
1065      model: string,
1066      time: RenderElement | string,
1067      cost: string,
1068      base: string,
1069      dim: boolean,
1070    ) => (
1071      <Box flexDirection="row">
1072        <Box width={agentWidth}>{typeof agent === 'string' ? <Text wrap="truncate" dimColor={dim}>{agent}</Text> : agent}</Box>
1073        <Box width={TIER_WIDTH} flexShrink={0}>
1074          <Text wrap="truncate" dimColor={dim}>{tier}</Text>
1075        </Box>
1076        <Box width={MODEL_WIDTH} flexShrink={0}>
1077          <Text wrap="truncate" dimColor={dim}>{model}</Text>
1078        </Box>
1079        {withTime && (
1080          <Box width={TIME_WIDTH} flexShrink={0} justifyContent="flex-end">
1081            {typeof time === 'string' ? <Text dimColor>{time}</Text> : time}
1082          </Box>
1083        )}
1084        <Box width={COST_WIDTH} flexShrink={0} justifyContent="flex-end">
1085          <Text wrap="truncate" dimColor={dim}>{cost}</Text>
1086        </Box>
1087        <Box width={BASE_WIDTH} flexShrink={0} justifyContent="flex-end">
1088          <Text wrap="truncate" dimColor={dim}>{base}</Text>
1089        </Box>
1090      </Box>
1091    )
1092
1093    // The agent cell: ✓ finished or ◐ running, then the name, pressable by its number.
1094    const agentCell = (r: AgentRow, i: number) => {
1095      const dim = r.via === 'unrouted'
1096      const mark = r.id === 'main' ? '  ' : r.finishedAt === undefined ? '◐ ' : '✓ '
1097      const key = i < 9 && r.id !== 'main' ? String(i + 1) : undefined
1098      // The surface draws a Button's hotkey itself (`1:`), so the label is the name alone.
1099      const name = fit(r.label, agentWidth - (key ? 5 : 2))
1100      return (
1101        <Box flexDirection="row">
1102          <Text dimColor={r.finishedAt !== undefined || dim}>{mark}</Text>
1103          {key ? (
1104            <Button key={`row-${r.id}`} plain hotkey={key} label={name} dimColor={dim} onPress={toggle(r.id)} />
1105          ) : (
1106            <Text wrap="truncate" dimColor={dim}>{name}</Text>
1107          )}
1108        </Box>
1109      )
1110    }
1111
1112    let numbered = 0
1113    return (
1114      <Box flexDirection="column" width={width}>
1115        <Text bold>{`Model router · ${mode}`}</Text>
1116        {mode !== 'on' && <Text color="yellow">{`${modeLabel(mode)} (/router on to go back)`}</Text>}
1117        <Text> </Text>
1118        {field('Spent', usd(t.cost))}
1119        {field(baseHead, `${usd(t.base)}${savedText(t)}`, t.saved > 0 ? 'green' : undefined)}
1120        {m.limits.map(w =>
1121          field(
1122            limitName(w.kind),
1123            windowGauge(w, now) + (tight && mode === 'on' && pressureAt !== undefined && w.percentUsed >= pressureAt ? '  · one tier down' : ''),
1124            pressureAt !== undefined && w.percentUsed >= pressureAt ? 'yellow' : undefined,
1125          ),
1126        )}
1127        {budgetLimit !== undefined &&
1128          field('Budget', budgetText(t.cost, budgetLimit, now), t.cost >= (budgetLimit * BUDGET_WARN) / 100 ? 'yellow' : undefined)}
1129        {m.lastTurn &&
1130          field(
1131            'Last turn',
1132            `${clockText(m.lastTurn.ms)}` +
1133              (m.lastTurn.agents > 0 ? ` · ${m.lastTurn.agents} agent${m.lastTurn.agents === 1 ? '' : 's'}` : '') +
1134              ` · +${usd(m.lastTurn.cost)}` +
1135              (m.lastTurn.saved > 0.005 ? ` · saved ${usd(m.lastTurn.saved)}` : ''),
1136          )}
1137        {/* On a subscription Claude Code reports no cost: nothing to compare with then. */}
1138        {(m.engineCost ?? 0) > 0 && field('Claude Code', `${usd(m.engineCost!)} total · this bill ${usd(rowsCost)} before the classifier`)}
1139        <Text> </Text>
1140        {agents === 0 ? (
1141          <Text dimColor wrap="wrap">No subagents yet. Ask Claude to use an agent and it shows up here.</Text>
1142        ) : (
1143          <Box flexDirection="column">
1144            {line('  Agent', 'Tier', 'Model', 'Time', 'Cost', baseHead, true)}
1145            <Text dimColor>{'─'.repeat(width)}</Text>
1146            {shown.map(r => {
1147              const i = r.id === 'main' ? -1 : numbered++
1148              const open = expanded === r.id && r.why
1149              return (
1150                <Box flexDirection="column">
1151                  {line(
1152                    agentCell(r, i),
1153                    tierLabel(r),
1154                    shortModel(r.model),
1155                    clock(r),
1156                    usd(r.cost),
1157                    (baseline === 'unrouted' && r.baselineGuessed ? '~' : '') + usd(baselineCost(r, baseline)),
1158                    r.via === 'unrouted',
1159                  )}
1160                  {open && (
1161                    <Text wrap="wrap" color="cyan">
1162                      {`    ${r.why}`}
1163                    </Text>
1164                  )}
1165                </Box>
1166              )
1167            })}
1168            {rows.length > room && <Text dimColor>{`…${rows.length - room} more`}</Text>}
1169            <Text> </Text>
1170            <Text dimColor wrap="truncate">
1171              {`${agents} agent${agents === 1 ? '' : 's'} · ${l.routed} routed · classifier ${usd(l.classifierCost)}`}
1172            </Text>
1173            <Text dimColor wrap="wrap">Why: ctrl+x tab, then a number. Esc: back</Text>
1174            {hasRescued && <Text dimColor>↑ moved up a model after struggling</Text>}
1175            {hasRisky && <Text dimColor>! risky: sent to Opus at least</Text>}
1176            {hasPressure && <Text dimColor>↓ moved down for rate limits or budget</Text>}
1177            {hasGuessed && <Text dimColor>~ guessed: this agent type's own model isn't known yet</Text>}
1178            <Text dimColor wrap="wrap">
1179              Dim rows are not routed. API list prices; plans billed by subscription see rate-limit use, not dollars.
1180            </Text>
1181          </Box>
1182        )}
1183      </Box>
1184    )
1185  })
1186}
1187
hooks/lib/agents.ts 42 lines
1/**
2 * The model the roles are registered with: what one runs on when the router leaves it
3 * alone, so the bill compares a routed role against it.
4 */
5export const ROLE_MODEL = 'sonnet'
6
7/** The four roles the router adds. Their model is decided per task at spawn time. */
8export const ROLES = [
9  {
10    name: 'architect',
11    description:
12      'Plans before code is written: reads the codebase, weighs designs, and returns a step-by-step plan with the files to touch. Use for new features, refactors and anything with design choices. Does not edit files.',
13    tools: ['Read', 'Grep', 'Glob', 'WebFetch', 'WebSearch'],
14    prompt: `You are the architect. Read the relevant code, then return a plan another agent can follow without re-deriving it.
15Output: the goal in one line; the files to change and why; ordered steps; risks and how to test the result.
16Do not edit files. Keep the plan as short as the task allows.`,
17  },
18  {
19    name: 'builder',
20    description:
21      'Writes and edits code to carry out a defined task or an architect plan. Use for implementing features, writing tests, and refactors with a clear target.',
22    prompt: `You are the builder. Make the change you are given, following the existing style of the codebase.
23Keep the diff focused. When done, list the files you changed and anything you could not finish.`,
24  },
25  {
26    name: 'runner',
27    description:
28      'Runs commands and reports results: tests, builds, linters, type checks, searches. Use when the job is to execute and summarize, not to change code.',
29    tools: ['Bash', 'Read', 'Grep', 'Glob'],
30    prompt: `You are the runner. Run what you are asked to run and report the result.
31Report: the command, pass or fail, and for each failure the test or file, the error, and the line. Quote errors exactly; do not paraphrase.
32Do not change code.`,
33  },
34  {
35    name: 'fixer',
36    description:
37      'Fixes what failed: takes a failing test, build error or bug report, finds the root cause, and changes the code until it passes. Use after a runner reports failures.',
38    prompt: `You are the fixer. Find the root cause of the failure you are given before changing anything.
39Fix the cause, not the symptom. Re-run the failing check to confirm. Report the cause in one or two lines and the files you changed.`,
40  },
41] as const
42
hooks/lib/pricing.ts 470 lines
1import type { Tier, Tokens } from '../../types'
2
3/** USD per million tokens, from platform.claude.com/docs/en/about-claude/pricing (Oct 2026). */
4export type Price = { input: number; output: number; cacheWrite: number; cacheRead: number }
5
6export const PRICES: Record<'haiku4' | 'haiku5' | 'sonnet' | 'opus' | 'fable', Price> = {
7  haiku4: { input: 1, output: 5, cacheWrite: 1.25, cacheRead: 0.1 },
8  // Prompts up to 100,000 tokens; HAIKU5_LONG above that.
9  haiku5: { input: 0.1, output: 0.5, cacheWrite: 0.125, cacheRead: 0.01 },
10  sonnet: { input: 2, output: 10, cacheWrite: 2.5, cacheRead: 0.1 },
11  opus: { input: 4, output: 20, cacheWrite: 5, cacheRead: 0.2 },
12  fable: { input: 10, output: 50, cacheWrite: 12.5, cacheRead: 0.25 },
13}
14
15/** Haiku 5.5 for a prompt (input, cache reads and cache writes together) over 100,000 tokens. */
16export const HAIKU5_LONG: Price = { input: 0.5, output: 2.5, cacheWrite: 0.625, cacheRead: 0.05 }
17export const HAIKU5_LONG_FROM = 100_000
18
19export type Family = keyof typeof PRICES
20
21/** Full model ids the router spawns on. */
22export const MODEL_FOR_TIER: Record<Tier, string> = {
23  simple: 'claude-haiku-5-5',
24  standard: 'claude-sonnet-5-5',
25  hard: 'claude-opus-5-5',
26  long: 'claude-fable-5-1',
27}
28
29/**
30 * The classifier: Haiku 5.5 at low effort. In a live run it answered all eight test tasks
31 * in one word each, at a seventh of Haiku 4.5's cost, and placed a small feature as
32 * standard where Haiku 4.5 said simple.
33 */
34export const CLASSIFIER_MODEL = 'claude-haiku-5-5'
35export const CLASSIFIER_EFFORT = 'low' as const
36
37/**
38 * How long a request's cache writes live. Claude Code writes the main conversation's
39 * prompt cache for an hour (2x input) and a subagent's for five minutes (1.25x input):
40 * pricing them so matched its own session cost to the cent in a live run.
41 */
42export type CacheTtl = '5m' | '1h'
43
44export const ORDER: Tier[] = ['simple', 'standard', 'hard', 'long']
45
46export type Effort = 'low' | 'medium' | 'high' | 'xhigh' | 'max'
47const EFFORTS: Effort[] = ['low', 'medium', 'high', 'xhigh', 'max']
48
49/**
50 * The most reasoning effort a routed agent's requests may ask for, by tier. Easy work
51 * thinks less; hard and long work keep whatever the session would have used.
52 */
53export const EFFORT_CAP: Record<Tier, Effort | undefined> = {
54  simple: 'low',
55  standard: 'medium',
56  hard: undefined,
57  long: undefined,
58}
59
60/**
61 * The lower of a request's effort and the cap. An integer budget or a level this
62 * table does not know is left alone, as is a request without effort.
63 */
64export function capEffort<E>(effort: E, cap: Effort | undefined): E | Effort {
65  if (!cap || typeof effort !== 'string') return effort
66  const i = EFFORTS.indexOf(effort as Effort)
67  return i < 0 || i <= EFFORTS.indexOf(cap) ? effort : cap
68}
69
70/** `/router` modes: `on` classifies, `off` leaves every spawn alone, a model name sends every routed spawn there. */
71export type Mode = 'on' | 'off' | 'haiku' | 'sonnet' | 'opus'
72export const MODES: Mode[] = ['on', 'off', 'haiku', 'sonnet', 'opus']
73
74export function parseMode(text: unknown): Mode | undefined {
75  const m = String(text ?? '').trim().toLowerCase()
76  return (MODES as string[]).includes(m) ? (m as Mode) : undefined
77}
78
79export const FORCED_TIER: Record<Exclude<Mode, 'on' | 'off'>, Tier> = {
80  haiku: 'simple',
81  sonnet: 'standard',
82  opus: 'hard',
83}
84
85/**
86 * Which price row a model id or alias falls in. Mythos bills as Fable.
87 * A bare `haiku` alias is the current Haiku (5.5). Unknown ids price as Opus.
88 */
89export function familyOf(model: string | undefined): Family {
90  const m = (model ?? '').toLowerCase()
91  if (m.includes('haiku')) return /haiku-[34]/.test(m) ? 'haiku4' : 'haiku5'
92  if (m.includes('sonnet')) return 'sonnet'
93  if (m.includes('fable') || m.includes('mythos')) return 'fable'
94  return 'opus'
95}
96
97const FAMILY_TIER: Record<Family, Tier> = {
98  haiku4: 'simple',
99  haiku5: 'simple',
100  sonnet: 'standard',
101  opus: 'hard',
102  fable: 'long',
103}
104
105/** The tier a model belongs to, for a model Claude named itself. */
106export function tierOfModel(model: string): Tier {
107  return FAMILY_TIER[familyOf(model)]
108}
109
110/** True for a request whose prompt (input, cache reads and cache writes) is over Haiku 5.5's threshold. */
111export function isLongPrompt(t: Tokens): boolean {
112  return t.input + t.cacheRead + t.cacheWrite > HAIKU5_LONG_FROM
113}
114
115/**
116 * Cost of a request's tokens on a family. Haiku 5.5 switches price above a 100K-token prompt,
117 * judged per request: `long` says which side the request fell on, else it is read off `t`.
118 * Summed tokens must be split by `isLongPrompt` first, or the sum crosses the threshold and
119 * everything is priced at the higher rate. Cache writes cost 1.25x input for 5 minutes, 2x
120 * for an hour.
121 */
122export function costOf(t: Tokens, family: Family, ttl: CacheTtl = '5m', long = isLongPrompt(t)): number {
123  const p = family === 'haiku5' && long ? HAIKU5_LONG : PRICES[family]
124  const write = ttl === '1h' ? p.input * 2 : p.cacheWrite
125  return (t.input * p.input + t.output * p.output + t.cacheWrite * write + t.cacheRead * p.cacheRead) / 1e6
126}
127
128export function tokensFromUsage(u: {
129  input_tokens: number
130  output_tokens: number
131  cache_read_input_tokens: number
132  cache_creation_input_tokens: number
133}): Tokens {
134  return {
135    input: u.input_tokens ?? 0,
136    output: u.output_tokens ?? 0,
137    cacheRead: u.cache_read_input_tokens ?? 0,
138    cacheWrite: u.cache_creation_input_tokens ?? 0,
139  }
140}
141
142export function addTokens(a: Tokens, b: Tokens): Tokens {
143  return {
144    input: a.input + b.input,
145    output: a.output + b.output,
146    cacheRead: a.cacheRead + b.cacheRead,
147    cacheWrite: a.cacheWrite + b.cacheWrite,
148  }
149}
150
151export function subTokens(a: Tokens, b: Tokens): Tokens {
152  return {
153    input: a.input - b.input,
154    output: a.output - b.output,
155    cacheRead: a.cacheRead - b.cacheRead,
156    cacheWrite: a.cacheWrite - b.cacheWrite,
157  }
158}
159
160export const ZERO: Tokens = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }
161
162/**
163 * Role guard rails, applied after Haiku's answer.
164 * runner never goes above standard (running tests is not Opus work).
165 * architect and fixer never go below standard (a bad plan or a bad fix costs more than the tokens).
166 */
167export const ROLE_LIMITS: Record<string, { min?: Tier; max?: Tier; fallback: Tier }> = {
168  architect: { min: 'standard', fallback: 'hard' },
169  builder: { fallback: 'standard' },
170  runner: { max: 'standard', fallback: 'simple' },
171  fixer: { min: 'standard', fallback: 'standard' },
172}
173
174export function roleOf(agentType: string): string | undefined {
175  const m = /^model-router:(\w+)$/.exec(agentType)
176  return m ? m[1] : undefined
177}
178
179/**
180 * The role's limits, then `long` only when allowed: a task that does not ask for
181 * long-running or unattended work goes to Opus, never to Fable at 2.5 times the price.
182 */
183export function clampTier(tier: Tier, role: string | undefined, allowLong = true): Tier {
184  let i = ORDER.indexOf(tier)
185  const lim = role ? ROLE_LIMITS[role] : undefined
186  if (lim?.min) i = Math.max(i, ORDER.indexOf(lim.min))
187  if (lim?.max) i = Math.min(i, ORDER.indexOf(lim.max))
188  if (!allowLong) i = Math.min(i, ORDER.indexOf('hard'))
189  return ORDER[i]!
190}
191
192/**
193 * Words that ask for a long or unattended run. Narrow on purpose: the Agent tool runs
194 * agents in the background by default, so "in the background" says nothing about length.
195 */
196const LONG_RUN =
197  /(?<!\bin\s+the\s+)\blong[- ]?run(ning)?\b|\bunattended\b|\bovernight\b|\bmulti[- ]?hours?\b|\bfor\s+((several|many|a\s+few|\d+)\s+)?hours\b|\bhours[- ]long\b|\bautonomously\b|\bkeep\s+(going|working|running)\s+until\b/i
198
199/** True when the task itself asks for long-running or unattended work: the only way to `long`. */
200export function asksForLongRun(text: string): boolean {
201  return LONG_RUN.test(text)
202}
203
204/**
205 * The tier after the risk floor and rate-limit pressure.
206 *
207 * Under pressure (a rate-limit window past the threshold) the tier drops one step and
208 * `long` is off the table; the role's limits still hold. A risky task then goes to at
209 * least `hard`, past a role's cap too: getting a destructive act wrong costs more than
210 * the tokens, so the risk floor wins over pressure.
211 */
212/**
213 * How low rate-limit pressure may push a role that writes code. A builder or fixer moved
214 * from Sonnet to Haiku stalled for 56 minutes on a subtle bug in a live run; easy work the
215 * classifier already put on Haiku stays there.
216 */
217export const PRESSURE_FLOOR: Record<string, Tier> = { builder: 'standard', fixer: 'standard' }
218
219export function routeTier(
220  tier: Tier,
221  role: string | undefined,
222  allowLong: boolean,
223  o: { risky?: boolean; underPressure?: boolean; cheapest?: boolean } = {},
224): Tier {
225  // The budget is spent: the cheapest tier the role allows. Only the risk floor goes higher.
226  if (o.cheapest) {
227    const t = clampTier('simple', role, false)
228    return o.risky && ORDER.indexOf(t) < ORDER.indexOf('hard') ? 'hard' : t
229  }
230  const i = ORDER.indexOf(tier)
231  const floor = role && PRESSURE_FLOOR[role] ? Math.min(i, ORDER.indexOf(PRESSURE_FLOOR[role]!)) : 0
232  let t = clampTier(o.underPressure ? ORDER[Math.max(floor, i - 1)]! : tier, role, allowLong && !o.underPressure)
233  if (o.risky && ORDER.indexOf(t) < ORDER.indexOf('hard')) t = 'hard'
234  return t
235}
236
237/**
238 * Destructive acts, for when no classifier answered. Narrow on purpose: it names the act
239 * (deploying to production, dropping a table, a forced push), not the subject, so code
240 * that merely deals with payments or databases does not match.
241 */
242const RISKY_ACT =
243  /\b(deploy|ship|release|roll\s?out)\w*\b[^.\n]{0,40}\b(to|on|in)\s+(prod|production|live)\b|\bdrop\s+(table|database|schema)\b|\btruncate\s+table\b|\brm\s+-rf\s+\/|\bgit\s+push\s+(-f|--force)\b|\bforce[- ]push\b|\b(delete|wipe|purge)\b[^.\n]{0,30}\b(prod|production)\s+(data|database|db|bucket|users?)\b/i
244
245export function looksRisky(text: string): boolean {
246  return RISKY_ACT.test(text)
247}
248
249const TIER_RE = /\b(simple|standard|hard|long)\b/i
250/** `risky` not negated: "not risky", "no risky flag", "non-risky" and "never risky" do not count. */
251const RISKY_RE = /(?<!\b(?:not|no|non|never|isn'?t|without)[\s-]+)\brisky\b/i
252
253function trimmedLines(text: string): string[] {
254  return text.split('\n').map(l => l.trim()).filter(Boolean)
255}
256
257/** The index of the last line that names a tier, or -1. */
258function lastTierLine(lines: string[]): number {
259  for (let i = lines.length - 1; i >= 0; i--) if (TIER_RE.test(lines[i]!)) return i
260  return -1
261}
262
263/**
264 * The classifier's verdict: the last line that names a tier. Haiku sometimes explains before
265 * or after it, and the explanation can name other tiers or say "not risky"; a reply cut off
266 * before any tier word has no verdict.
267 */
268function verdictLine(text: string): string {
269  const lines = trimmedLines(text)
270  const at = lastTierLine(lines)
271  return at >= 0 ? lines[at]! : ''
272}
273
274/**
275 * Reads the classifier's risk flag: an unnegated `risky` on the verdict line or after it
276 * ("hard risky", or "hard" then "risky: deploys to production"); false without a verdict.
277 */
278export function parseRisky(text: string): boolean {
279  const lines = trimmedLines(text)
280  const at = lastTierLine(lines)
281  return at >= 0 && RISKY_RE.test(lines.slice(at).join('\n'))
282}
283
284/** The fullest rate-limit window, in percent; 0 off a subscription or before the first reading. */
285export function fullestWindow(limits: readonly { percentUsed: number }[] | undefined): number {
286  return (limits ?? []).reduce((m, l) => Math.max(m, l.percentUsed), 0)
287}
288
289/** The `limitPressure` setting as a percentage, or undefined when off. */
290export function pressureThreshold(setting: unknown): number | undefined {
291  const n = Number(setting ?? 80)
292  return Number.isFinite(n) && n > 0 && n <= 100 ? n : undefined
293}
294
295/** The share of the budget at which routing goes one tier cheaper; at 100% it goes cheapest. */
296export const BUDGET_WARN = 80
297
298/** The `budget` setting in dollars, or undefined when off. */
299export function budgetUsd(setting: unknown): number | undefined {
300  const n = Number(setting)
301  return Number.isFinite(n) && n > 0 ? n : undefined
302}
303
304/** Bumped when replies are read differently, so verdicts an older reading stored are not reused. */
305const CLASSIFIER_PARSE = 2
306
307/**
308 * What the classifier read, as one string: the cache's key before hashing. The rubric and the
309 * parse version are part of it, so a new rubric or a new reading of replies doesn't reuse
310 * verdicts the old one gave.
311 */
312export function classifyKey(input: { agentType: string; description: string; prompt: string }): string {
313  return `parse ${CLASSIFIER_PARSE}\n${CLASSIFIER_SYSTEM}\n${input.agentType}\n${input.description}\n${input.prompt}`
314}
315
316/** The tier as the pane says it. */
317export const TIER_WORD: Record<Tier, string> = { simple: 'easy', standard: 'normal', hard: 'hard', long: 'long' }
318
319/**
320 * One line on why an agent got its tier: what the classifier said, then each rule that moved
321 * it. For the pane's expanded row.
322 */
323export function explainTier(o: {
324  source: 'haiku' | 'builtin' | 'fallback'
325  asked: Tier
326  final: Tier
327  role: string | undefined
328  risky: boolean
329  allowLong: boolean
330  pressure?: number
331  /** The session's spend as a share of its budget, when the budget moved the agent. */
332  budget?: { pct: number; usd: number }
333  cached?: boolean
334}): string {
335  const said =
336    o.source === 'haiku'
337      ? `classifier${o.cached ? ' (cached)' : ''}: ${TIER_WORD[o.asked]}${o.risky ? ' risky' : ''}`
338      : o.source === 'builtin'
339        ? `built-in classifier: ${TIER_WORD[o.asked]}`
340        : `no classifier answer, ${o.role ?? 'agent'} default: ${TIER_WORD[o.asked]}`
341  const rules: string[] = []
342  const lim = o.role ? ROLE_LIMITS[o.role] : undefined
343  if (lim?.max && ORDER.indexOf(o.asked) > ORDER.indexOf(lim.max)) rules.push(`${o.role} capped at ${TIER_WORD[lim.max]}`)
344  if (lim?.min && ORDER.indexOf(o.asked) < ORDER.indexOf(lim.min)) rules.push(`${o.role} at least ${TIER_WORD[lim.min]}`)
345  if (o.asked === 'long' && !o.allowLong) rules.push('long work not asked for')
346  if (o.risky && o.final === 'hard' && ORDER.indexOf(o.asked) < ORDER.indexOf('hard')) rules.push('risk floor')
347  if (o.pressure !== undefined) rules.push(`limits ${Math.round(o.pressure)}%: one tier down`)
348  if (o.budget)
349    rules.push(
350      o.budget.pct >= 100
351        ? `$${o.budget.usd} budget spent: cheapest allowed`
352        : `${Math.round(o.budget.pct)}% of $${o.budget.usd} budget: one tier down`,
353    )
354  return o.final === o.asked && rules.length === 0
355    ? said
356    : `${said} → ${TIER_WORD[o.final]}${rules.length ? ` (${rules.join(', ')})` : ''}`
357}
358
359/** A duration as `0:42`, `3:05` or `1h04`. */
360export function clockText(ms: number): string {
361  const s = Math.max(0, Math.floor(ms / 1000))
362  const m = Math.floor(s / 60)
363  return m < 60 ? `${m}:${String(s % 60).padStart(2, '0')}` : `${Math.floor(m / 60)}h${String(m % 60).padStart(2, '0')}`
364}
365
366/** A rate-limit window's name for the pane: `5h limit`, `7d limit`. */
367export function limitName(kind: string): string {
368  return kind === 'five_hour' ? '5h limit' : kind === 'seven_day' ? '7d limit' : kind.replace(/_/g, ' ')
369}
370
371/** Time left as `42m`, `4h24` or `6d 1h`. */
372export function untilText(ms: number): string {
373  const mins = Math.ceil(ms / 60_000)
374  if (mins < 60) return `${mins}m`
375  const h = Math.floor(mins / 60)
376  if (h < 24) return `${h}h${String(mins % 60).padStart(2, '0')}`
377  return `${Math.floor(h / 24)}d ${h % 24}h`
378}
379
380/**
381 * A rate-limit window as `██░░░ 42%  resets in 4h24`; the reset is left out when unknown or
382 * past. Full and light blocks, which every terminal font draws.
383 */
384export function windowGauge(l: { percentUsed: number; resetsAt?: string }, now: number): string {
385  const pct = Math.max(0, Math.min(100, l.percentUsed))
386  const filled = Math.round(pct / 20)
387  const bar = '█'.repeat(filled) + '░'.repeat(5 - filled)
388  const left = l.resetsAt ? Date.parse(l.resetsAt) - now : NaN
389  const reset = Number.isFinite(left) && left > 0 ? `  resets in ${untilText(left)}` : ''
390  return `${bar} ${Math.round(l.percentUsed)}%${reset}`
391}
392
393/**
394 * When a cheap agent counts as struggling: tool calls failing in a row, or more requests or
395 * time than its tier's work should take. Generous on purpose: a rescue switches models
396 * mid-run, which rewrites the agent's whole context at the new model's price once.
397 */
398export const RESCUE = {
399  errorsInARow: 3,
400  steps: { simple: 25, standard: 60 } as Partial<Record<Tier, number>>,
401  minutes: { simple: 10, standard: 30 } as Partial<Record<Tier, number>>,
402}
403
404/** Why an agent on `tier` should move up, or undefined while it is doing fine. */
405export function rescueReason(tier: Tier, h: { errors: number; steps: number; ms: number }): string | undefined {
406  if (h.errors >= RESCUE.errorsInARow) return `${h.errors} failed tool calls in a row`
407  const steps = RESCUE.steps[tier]
408  if (steps !== undefined && h.steps > steps) return `over ${steps} requests`
409  const minutes = RESCUE.minutes[tier]
410  if (minutes !== undefined && h.ms > minutes * 60_000) return `over ${minutes} minutes`
411  return undefined
412}
413
414/** The tier a struggling agent moves up to: one step, never to `long`, never past its role's cap. */
415export function rescueTier(tier: Tier, role: string | undefined): Tier | undefined {
416  const i = ORDER.indexOf(tier) + 1
417  const max = Math.min(ORDER.indexOf('hard'), role && ROLE_LIMITS[role]?.max ? ORDER.indexOf(ROLE_LIMITS[role]!.max!) : 3)
418  return i <= max ? ORDER[i] : undefined
419}
420
421export function fallbackTier(role: string | undefined): Tier {
422  return (role && ROLE_LIMITS[role]?.fallback) || 'standard'
423}
424
425/** Reads the classifier's reply: the tier word on its verdict line; undefined without one. */
426export function parseTier(text: string): Tier | undefined {
427  return TIER_RE.exec(verdictLine(text))?.[1]?.toLowerCase() as Tier | undefined
428}
429
430export const CLASSIFIER_SYSTEM = `You route coding subagent tasks to a model. Read the task and reply with exactly one word.
431
432simple   - mechanical, little judgment: rename, find/search/grep, list files, run an existing test or build command and report, format, small single-file edits with an obvious answer.
433standard - most coding work: implement, plan or review a feature or fix, write tests, refactor across several files, fix a bug whose failure is known, follow a detailed plan. Long or detailed instructions do not make a task harder; they make it easier.
434hard     - only when the problem itself needs deep reasoning: a bug whose cause is unknown and intermittent or cross-cutting, concurrency or race conditions, a security audit, performance tuning, a design with real trade-offs between competing approaches, a data migration with subtle risk. Planning a change whose steps the task already spells out is standard.
435long     - only when the task explicitly asks for long-running or unattended multi-hour work, such as a large build or migration left to run overnight. Running in the background is not long.
436
437Pick the cheapest tier that will succeed. If unsure between simple and standard, pick standard. If unsure between standard and hard, pick standard.
438
439Then add the word risky only if the agent itself will do costly or hard-to-reverse harm outside the working tree: deploying to production, a migration or destructive command against production or shared data, deleting data not in version control, rotating or exposing credentials, moving money, force-pushing over shared history. Judge only what the agent will run, not what the code it writes would do. Not risky: writing or editing code (including a migration or script that deletes data), running tests or a test database, committing locally, deleting files under version control.
440
441Reply with the tier word alone, or the tier word and risky: for example "standard" or "hard risky". Do not explain.`
442
443/** What the engine's built-in classifier reads when Haiku 4.5 gives no tier: no rubric, so keep it short. */
444export function builtinClassifierText(input: { agentType: string; description: string; prompt: string }): string {
445  const body = input.prompt.length > 2000 ? input.prompt.slice(0, 2000) + ' [...]' : input.prompt
446  return `How hard is this coding task for an AI agent? Agent: ${input.agentType}. ${input.description}. ${body}`
447}
448
449export function classifierPrompt(input: {
450  agentType: string
451  description: string
452  prompt: string
453}): string {
454  const body = input.prompt.length > 6000 ? input.prompt.slice(0, 6000) + '\n[...truncated]' : input.prompt
455  return [
456    `Agent type: ${input.agentType}`,
457    `Short description: ${input.description}`,
458    'Task:',
459    '<task>',
460    body,
461    '</task>',
462  ].join('\n')
463}
464
465export function usd(n: number): string {
466  if (n === 0) return '$0'
467  if (n < 0.01) return '<$0.01'
468  return '$' + n.toFixed(2)
469}
470
hooks/clock.tsx 40 lines
1// A running agent's clock for the /router pane. It ticks on the surface's own frame clock, so
2// the pane is not drawn again every second. The idea comes from claude-flightdeck's elapsed
3// clock (MIT, Stephen Casella).
4import type { ClientModule } from 'claude-code'
5
6/** Kept here, not imported: a surface module runs on its own, apart from the hooks module. */
7function clockText(ms: number): string {
8  const s = Math.max(0, Math.floor(ms / 1000))
9  const m = Math.floor(s / 60)
10  return m < 60 ? `${m}:${String(s % 60).padStart(2, '0')}` : `${Math.floor(m / 60)}h${String(m % 60).padStart(2, '0')}`
11}
12
13type Props = { since: number; now: number; endAt: number | null }
14type Ref = { base: number; ticks: number; lastNow: number; isRunning: boolean }
15type State = { ref: Ref }
16
17const Clock: ClientModule<Props, State> = (props, surface) => {
18  const { Text } = surface.elements
19  const ref = surface.state?.ref ?? { base: 0, ticks: 0, lastNow: -1, isRunning: true }
20  if (props.now !== ref.lastNow) {
21    // A fresh reading from the hooks module: count on from it.
22    ref.lastNow = props.now
23    ref.base = (props.endAt ?? props.now) - props.since
24    ref.ticks = 0
25  }
26  ref.isRunning = props.endAt === null
27  if (surface.state === undefined) {
28    surface.setState({ ref })
29    surface.every(1000, () => {
30      if (ref.isRunning) {
31        ref.ticks += 1
32        surface.setState({ ref })
33      }
34    })
35  }
36  return <Text dimColor={!ref.isRunning}>{clockText(ref.base + ref.ticks * 1000)}</Text>
37}
38
39export default Clock
40
types/index.d.ts 93 lines
1export type Tier = 'simple' | 'standard' | 'hard' | 'long'
2
3export type Effort = 'low' | 'medium' | 'high' | 'xhigh' | 'max'
4
5export type Tokens = {
6  input: number
7  output: number
8  cacheRead: number
9  cacheWrite: number
10}
11
12/** One subagent (or the main loop, id "main") as the bill pane shows it. */
13export type AgentRow = {
14  id: string
15  label: string
16  agentType: string
17  tier?: Tier
18  /**
19   * How the model was decided: the Haiku classifier, the engine's built-in classifier
20   * when Haiku gave no tier, the role fallback, a model Claude named, a `/router` mode
21   * that sends everything to one model, or not routed (main, forks, workflow agents,
22   * teammates, built-ins when routing is narrowed, everything under `/router off`).
23   */
24  via?: 'haiku' | 'builtin' | 'fallback' | 'explicit' | 'forced' | 'unrouted'
25  model?: string
26  /** True when the task was judged risky and sent to at least the hard tier. */
27  risky?: boolean
28  /** The fullest rate-limit window, in percent, when it pushed this agent a tier down. */
29  pressure?: number
30  /** The most effort this agent's requests may ask for; absent when the router leaves effort alone. */
31  effort?: Effort
32  /** What this agent would have run on without the router: the parent's model, or its own when unrouted. */
33  baselineModel?: string
34  /**
35   * True when `baselineModel` is a guess: the call named no model, the type is not a router
36   * role, and the type had not yet been seen running unrouted, so the parent's model stood in.
37   */
38  baselineGuessed?: boolean
39  tokens: Tokens
40  /** The part of `tokens` from requests over Haiku 5.5's long-prompt threshold, which price higher there. */
41  longTokens?: Tokens
42  /** USD at the price of the model that actually answered each step. */
43  cost: number
44  startedAt: number
45  /** When the agent last finished; absent while it runs. The band above the prompt fades it out after this. */
46  finishedAt?: number
47  /** Why it got its model, in one line: what the classifier said and each rule that moved it. */
48  why?: string
49  /** The session's spend as a share of its budget, in percent, when the budget moved it down. */
50  budget?: number
51  /** How many times it was moved up a model mid-run after struggling. */
52  rescued?: number
53}
54
55/** One rate-limit window as the engine reports it. */
56export type LimitWindow = { kind: string; percentUsed: number; resetsAt?: string }
57
58/** The main conversation's turn now running: the bill as it stood when it began. */
59export type TurnMark = { startedAt: number; cost: number; base: number; agents: number }
60
61/** The last finished turn of the main conversation, for the pane's receipt line. */
62export type TurnReceipt = { ms: number; agents: number; cost: number; saved: number }
63
64/** What the engine measures for the whole session, and the turn receipt. */
65export type RouterMeter = {
66  /** Claude Code's own session cost: every priced response, the router's classifier calls not included. */
67  engineCost?: number
68  limits: LimitWindow[]
69  turn?: TurnMark
70  lastTurn?: TurnReceipt
71}
72
73/** The pane's view: which agent row is expanded to show why it got its model. */
74export type RouterView = { expanded?: string }
75
76export type RouterLedger = {
77  rows: Record<string, AgentRow>
78  /** What the Haiku classifier calls themselves cost. */
79  classifierCost: number
80  routed: number
81}
82
83declare module 'claude-code' {
84  interface PluginState {
85    'model-router': {
86      ledger: RouterLedger
87      mode: 'on' | 'off' | 'haiku' | 'sonnet' | 'opus' | undefined
88      meter: RouterMeter
89      view: RouterView
90    }
91  }
92}
93