SLOPSHOPPER

agent-ClaudeRouter

Picks the model and effort per request, and shows a live band above the prompt: routing, running agents, skills, MCP, context and plan usage, plus a…

panebandguardcommandtoastprompt
★ 2v0.4.0no licenseupdated 2026-10-24visualife/ClaudeRouter
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · agent-ClaudeRouter
│ ┃ ClaudeRouter ✕ › fix the failing auth test and add an audit log call │ ┃ No task yet route: — │ ┃ ⏺ Read(src/auth.ts) │ ┃ ╭──────────────────────────────────────────╮ ⎿ Read 6 lines │ ┃ │ Cost │ ⏺ Update(src/auth.ts) │ ┃ │ ≈$0.42 │ ⎿ Added 2 lines, removed 1 line │ ┃ ╰──────────────────────────────────────────╯ ⏺ Bash(bun test) │ ┃ ⎿ 3 pass, 1 fail │ ┃ ▾ Running · 0 │ ┃ none ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ │ ┃ ▾ Finished · 0 ✻ Worked for 42s · done 4:20 PM │ ┃ none │ › /clauderouter │ │ ClaudeRouter idle · turn 1 ⇄ Model route waiting for the first request ✦ Skills none used yet 0 used ◇ MCP no calls yet 0 calls ▣ Plugins none seen 0 mods ◆ Context ⡀⡀⡄⡄⡄⡆⡆⡆⡇⡇⡇⣿⣿⣿⣿⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂ 97k / 200k · 49% ◷ Session · 5h ⡀⡄⡄⡆⡆⡇⡇⣿⣿⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂ 5h · 31% used ◷ Weekly · 7d ⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂ no reading ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
ClaudeRouter idle · turn 1 ⇄ Model route waiting for the first request ✦ Skills none used yet 0 used ◇ MCP no calls yet 0 calls ▣ Plugins none seen 0 mods ◆ Context ⡀⡀⡄⡄⡄⡆⡆⡆⡇⡇⡇⣿⣿⣿⣿⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂ 97k / 200k · 49% ◷ Session · 5h ⡀⡄⡄⡆⡆⡇⡇⣿⣿⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂ 5h · 31% used ◷ Weekly · 7d ⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂ no reading
Pane · ClaudeRouter
No task yet route: — ╭──────────────────────────────────────────────────────────╮ │ Cost │ │ ≈$0.42 │ ╰──────────────────────────────────────────────────────────╯ ▾ Running · 0 none ▾ Finished · 0 none
README

ClaudeRouter

A Claude Code mod that picks the model and effort for each request, and keeps a live band above your prompt showing what the session is doing.

ClaudeRouter band and /clauderouter pane

What it does

  • Routes every request to haiku, sonnet or opus with a reasoning effort (low → xhigh) and a confidence score. Routing is local keyword/length/tool heuristics: no model is called to decide. A small hysteresis stops it flip-flopping between tiers.
  • Live band above the prompt: current route, running agents, skills used, MCP calls, plugins seen, context window, and 5h / 7d plan usage.
  • /clauderouter pane: cost, tokens and elapsed time cards, plus the running and finished subagents with the model and effort each one got.
  • Jev as the router (optional): let Jev (TypeSafe System One) pick the tier instead of the keyword rules. Falls back to the rules on any error or timeout.
  • Keep the cache warm (optional): pings the prompt cache every 50 minutes while you are idle, so a break does not cost a full re-write.
  • Pixel mascots per subagent role: scout (Explore), planner (Plan), researcher, builder.

Cost guards (v0.4)

Applied on every model request, after the router (or Jev) has picked. Defaults protect your plan; change them with /clauderouter.

GuardDefaultEffect
Effort ceilinghighxhigh is never picked automatically. /clauderouter cap medium to lower it.
Opus plans, Sonnet executesfirst 2 requestsAfter that, or once the turn writes files / runs 6+ tools, the turn moves to Sonnet (medium).
Long spec> 1200 charsOpus never runs above medium on it.
Subagentsnot OpusOnly Plan subagents may use Opus; all others capped at medium.
Turn budget$3 per turnOver it: Sonnet medium. Over 2×: Sonnet low. A toast tells you. /clauderouter budget 5 or off.
Context cap150k tokensOver it: Sonnet medium. Over 1.5×: Sonnet low. /clauderouter ctx 200k or off.
Your choice winsnone/clauderouter pin sonnet medium applies from the next request, even mid-turn. pin auto releases it. Or prefix one prompt: @sonnet:med build the app / @opus:high ....

The band's second line shows guard ... with the reason whenever a limit changed the pick. Budget uses the session cost the engine reports (API-equivalent USD).

Claude desktop

The mod is surface-aware: the band and pane already draw with plain Text bars on desktop (no Raster), and the tests cover both surfaces. Claude desktop's Code tab runs the same Claude Code engine, so install it there with the same two commands:

/plugin marketplace add C:\Users\studi.REAL\Documents\GitHub\ClaudeRouter
/plugin install agent-ClaudeRouter@router-mods
/reload-plugins

Install at user scope so the CLI and the desktop Code tab share it. Chat and Cowork tabs do not run mods.

Requirements

  • A Claude Code build that supports mods (plugins that ship hooks/*.ts modules and a types entry).
  • Git, to clone the repo.

Install

  1. Clone the repo anywhere on your machine:
   git clone https://github.com/visualife/ClaudeRouter
  1. In Claude Code, add the clone as a local marketplace and install the plugin:
   /plugin marketplace add ./ClaudeRouter
   /plugin install agent-ClaudeRouter@router-mods

Use the full path to the clone if it is not in the directory you launched Claude Code from.

  1. Reload plugins (/reload-plugins) or restart Claude Code. The band appears above the prompt.

Usage

  • Band: shows automatically. It updates on every prompt with the picked model, effort and confidence, and tells you when it switched model.
  • Pane: type /clauderouter to open it. Press Esc to close.
  • Subagents: each one appears in the pane's Running and Finished lists with its own model and effort.

Options

Set them from the prompt; they persist across reloads.

CommandEffect
/clauderouter engine jevJev picks haiku / sonnet / opus. Needs TYPESAFE_API_KEY in the environment.
/clauderouter engine rulesLocal keyword rules (default).
/clauderouter warm 2hKeep the prompt cache warm for 2h (default 2h, max 6h).
/clauderouter warm offStop.
/clauderouter pin <model> [effort] / pin autoForce a model (and effort), effective next request.
/clauderouter cap <effort>Highest effort the router may pick.
`/clauderouter budget <usd\off>`Per-turn spend limit.
`/clauderouter ctx <150k\off>`Context size limit.
/clauderouter statusShow the current options.

Jev: it only chooses the tier; Claude still does the work. Each routed request sends the prompt text (first 4000 characters) to api.typesafe.ai and costs one small Jev call (about 0.3 s). In the band, jev sits beside haiku sonnet opus on the Model route row: lit when Jev made the pick, dim when the rules did. Once Jev has been used, a Jev · context bar appears: the last call's input tokens against Jev's 64k per-request window, with the call count. A Jev pick also starts the band's second line with jev ·. With no key, an error or a 2.5 s timeout, the rules decide, so nothing blocks.

Keep warm: each ping is a short model call on the existing conversation (cache reads, cheap). It only runs while the window is open and no turn is running, and it ends the window if a ping fails, since the cache is then probably gone. Switching model tiers loses the cache of the previous tier, which is what this is for. If you already run the cache-tax mod's /keepwarm, use one of the two, not both.

Update / uninstall

git -C ClaudeRouter pull
/plugin uninstall agent-ClaudeRouter@router-mods
/plugin marketplace remove router-mods

Tuning

Routing lives in hooks/route.ts: edit the HEAVY, MID and LIGHT keyword lists, or HYSTERESIS, to change how eagerly it moves between tiers.

Layout

PathRole
hooks/register.tsHook and command registration, state, /clauderouter
hooks/route.tsModel and effort heuristics
hooks/guard.tsCost guards: effort ceiling, plan/execute split, budget, context cap, pin
hooks/band.tsThe band above the prompt
hooks/pane.tsThe /clauderouter pane
hooks/pixel.ts, format.ts, lists.tsSprites, formatting, list rows
tests/router.test.tsRouting tests

Notes

  • Built against the Claude Code mod API; type stubs are generated into .claude-plugin/types/ (git-ignored).
  • Routing is a heuristic. Check the log of what it picked before trusting it on a real task.
Source 11 files
hooks/register.ts 304 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3import type { Agent, Route, Task } from '../types'
4import { JEV_TIMEOUT_MS, askJev } from './jev'
5import { DEFAULT_OPTIONS, WARM_EVERY_MS, applyArgs } from './options'
6import { type Pin, directiveOf, guard } from './guard'
7import { type Els, type Snapshot, drawBand } from './band'
8import { drawPane } from './pane'
9import { type Anim, animCells } from './pixel'
10import { effortFor, familyOf, idFor, pickRoute, roleOf, whyOf } from './route'
11import { attachAgent, addPlugin, bumpMcp, bumpSkill, nameOf, patchAgent, patchTask, toUsage } from './lists'
12
13const PANE = 'agent-ClaudeRouter'
14
15// The values ClaudeRouter draws, kept in $.state. A write redraws the sites that read it.
16// Declared here, beside their writes: the state scan reads each atom where it is written.
17const route = atom({ plugin: 'agent-ClaudeRouter', key: 'route' } as const, null)
18const tasks = atom({ plugin: 'agent-ClaudeRouter', key: 'tasks' } as const, [])
19const skills = atom({ plugin: 'agent-ClaudeRouter', key: 'skills' } as const, [])
20const mcp = atom({ plugin: 'agent-ClaudeRouter', key: 'mcp' } as const, [])
21const plugins = atom({ plugin: 'agent-ClaudeRouter', key: 'plugins' } as const, [])
22const usage = atom({ plugin: 'agent-ClaudeRouter', key: 'usage' } as const, null)
23const jev = atom({ plugin: 'agent-ClaudeRouter', key: 'jev' } as const, null)
24const options = atom({ plugin: 'agent-ClaudeRouter', key: 'options' } as const, DEFAULT_OPTIONS)
25const totals = atom({ plugin: 'agent-ClaudeRouter', key: 'totals' } as const, { tokens: 0, turns: 0 })
26
27// Shared by the hooks below. A reload starts them over; $.state keeps what the band shows.
28let busy = false
29let frame = 0
30let terminal = false
31let turnId = ''
32let turnText = ''
33let turnTools: string[] = []
34// Cost guards: the session cost when this turn began, a "@model:effort" prompt prefix, and one warning per turn
35let turnCostStart = 0
36let turnPin: Pin | null = null
37let warned = false
38// When the main thread last sent a request, for keep-warm
39let lastRequestAt: number | null = null
40const subagents = new Map<string, { text: string; subagentType?: string }>()
41// The Rasters each drawn site mounted that shimmer or move: what the timer repaints with $.ui.blit
42const mounted = new Map<string, Anim[]>()
43
44// Gathers what a drawing reads. The validator follows $ only into functions declared at the top of the file.
45async function snapshot($: EngineInterface, surface: string, columns: number, rows: number): Promise<Snapshot> {
46  return {
47    route: await read($, route),
48    tasks: await read($, tasks),
49    skills: await read($, skills),
50    mcp: await read($, mcp),
51    plugins: await read($, plugins),
52    usage: await read($, usage),
53    jev: await read($, jev),
54    totals: await read($, totals),
55    now: await $.clock.now(),
56    frame,
57    terminal: surface === 'terminal',
58    columns,
59    rows,
60    anim: [],
61  }
62}
63
64export const register: Register = on => {
65  // Runs before your first prompt, and again after a reload
66  on('session.start', async ($, e, next) => {
67    await $.command.register({
68      name: 'clauderouter',
69      description: 'Open ClaudeRouter: cost, tokens, time, running and finished agents',
70      immediate: true,
71    })
72    const raw = await $.session.usage()
73    await update($, usage, () => toUsage(raw))
74    // Ten frames a second, and only while a turn is running
75    $.clock.every(100, async () => {
76      if (!busy) return
77      frame += 1
78      if (!terminal) {
79        // The desktop has no Raster: its Text bars are redrawn
80        $.ui.invalidate('ui.render')
81        return
82      }
83      for (const [requestId, list] of mounted) {
84        for (const a of list) {
85          if (a.kind === 'sprite' && frame % 4 !== 0) continue
86          await $.ui.blit({ requestId, key: a.key, cells: animCells(a, frame) })
87        }
88      }
89      // The seconds counters are Text, which a blit does not reach: redraw once a second
90      if (frame % 10 === 0) $.ui.invalidate('ui.render')
91    })
92    // Keep-warm: once a minute, ping the cache if the window is open and the main thread has been idle for 50 min
93    $.clock.every(60_000, async () => {
94      const now = await $.clock.now()
95      const { warmUntil } = await read($, options)
96      if (warmUntil <= now || busy || lastRequestAt === null || now - lastRequestAt < WARM_EVERY_MS) return
97      const reply = await $.model.fork({ prompt: 'Reply with the single word: warm' }).catch(() => null)
98      // A failed ping ends the window: the cache is probably gone, and retrying would only pay to write it again
99      if (!reply || !reply.isAnswered) await update($, options, o => ({ ...o, warmUntil: 0 }))
100      else lastRequestAt = now
101    })
102    return next(e)
103  })
104
105  // Runs when you type /ClaudeRouter. Opening the pane draws nothing by itself; ui.render fills it.
106  on('command.run', { command: 'clauderouter' }, async ($, e) => {
107    if (e.args.trim()) {
108      const now = await $.clock.now()
109      const { next, text } = applyArgs(e.args, { ...DEFAULT_OPTIONS, ...(await read($, options)) }, now)
110      if (next) await update($, options, () => next)
111      return { text }
112    }
113    await $.ui.open({ id: PANE, title: 'ClaudeRouter', closeOnEscape: true })
114    return {}
115  })
116
117  // Runs when a turn begins: a new task row, named by the prompt
118  on('turn.start', async ($, e, next) => {
119    busy = true
120    turnId = e.turnId
121    turnText = e.text
122    turnTools = []
123    turnPin = directiveOf(e.text)
124    warned = false
125    turnCostStart = (await read($, usage))?.cost ?? 0
126    const task: Task = {
127      id: e.turnId,
128      name: nameOf(e.text),
129      status: 'running',
130      startedAt: await $.clock.now(),
131      seconds: null,
132      steps: 0,
133      model: null,
134      effort: null,
135      tokens: null,
136      agents: [],
137    }
138    await update($, tasks, list => [...list.slice(-19), task])
139    return next(e)
140  })
141
142  // Runs before each request to the model: picks the model and effort, then records what was chosen
143  on('turn.step', async function* ($, e, next) {
144    const sub = e.agentId ? subagents.get(e.agentId) : undefined
145    const input = {
146      text: e.agentId ? (sub?.text ?? '') : turnText,
147      tools: e.agentId ? [] : turnTools,
148      subagentType: sub?.subagentType,
149      current: familyOf(e.model),
150    }
151    let pick = pickRoute(input)
152    let by: Route['by'] = 'rules'
153    if (!e.agentId) lastRequestAt = await $.clock.now()
154    // Options saved by an older version lack the guard fields: defaults fill them in
155    const opts = { ...DEFAULT_OPTIONS, ...(await read($, options)) }
156    if (opts.engine === 'jev') {
157      const key = await $.env.get('TYPESAFE_API_KEY')
158      const timeout = new Promise<null>(resolve => { $.clock.after(JEV_TIMEOUT_MS, () => resolve(null)) })
159      const asked = key ? await Promise.race([askJev((url, init) => $.http.fetch(url, init), key, input), timeout]) : null
160      if (asked) {
161        pick = { model: asked.model, conf: asked.conf, effort: effortFor(asked.model, input.text, input.subagentType) }
162        by = 'jev'
163        await update($, jev, u => ({ calls: (u?.calls ?? 0) + 1, input: asked.input, output: asked.output }))
164      }
165    }
166    // Cost guards run last, on whoever picked: they cap what the turn may spend
167    const u = await read($, usage)
168    const turnCost = u?.cost != null ? Math.max(0, u.cost - turnCostStart) : null
169    const guarded = guard({
170      pick,
171      pin: e.agentId ? null : (turnPin ?? (opts.pin ? { model: opts.pin, effort: opts.pinEffort } : null)),
172      maxEffort: opts.maxEffort,
173      budget: opts.budget,
174      ctxCap: opts.ctxCap,
175      isSub: Boolean(e.agentId),
176      isPlan: input.subagentType === 'Plan',
177      step: e.index,
178      textLen: input.text.length,
179      turnTools,
180      contextTokens: u?.context.tokens ?? null,
181      turnCost,
182    })
183    if (!warned && guarded.limits.some(l => l.startsWith('turn $') || l.startsWith('ctx '))) {
184      warned = true
185      $.ui.toast(`ClaudeRouter: ${guarded.limits.join(', ')}. Downgraded to ${guarded.model}/${guarded.effort}.`)
186    }
187    pick = { ...pick, model: guarded.model, effort: guarded.effort }
188    const kept = familyOf(e.model) === pick.model
189    const result = yield* next({ ...e, model: idFor(pick.model, e.model), effort: pick.effort })
190
191    const decided: Route = {
192      model: pick.model,
193      effort: pick.effort,
194      conf: pick.conf,
195      kept,
196      by,
197      engineModel: e.model,
198      source: e.agentId ? 'subagent' : 'main',
199      why: (by === 'jev' ? 'jev · ' : '') + whyOf(input) + (guarded.limits.length > 0 ? ` · guard ${guarded.limits.join(',')}` : ''),
200    }
201    await update($, route, () => decided)
202    if (e.agentId) {
203      const agentId = e.agentId
204      await update($, tasks, list => patchAgent(list, agentId, { model: pick.model, effort: pick.effort }))
205    } else {
206      const turn = e.turnId
207      await update($, tasks, list => patchTask(list, turn, { steps: e.index + 1, model: pick.model, effort: pick.effort }))
208    }
209    return result
210  })
211
212  // Runs before each tool call: counts the turn's tools, and MCP calls by server and tool
213  on('tool.call', async ($, e, next) => {
214    if (!e.agentId) turnTools = [...turnTools.slice(-49), e.tool]
215    if (e.tool.startsWith('mcp__')) {
216      const [, server = '', ...rest] = e.tool.split('__')
217      const tool = rest.join('__')
218      await update($, mcp, list => bumpMcp(list, server, tool))
219    }
220    return next(e)
221  }).catch(($, e, next) => next(e))
222
223  // Runs when a skill's text is expanded for Claude: it has loaded and is in use
224  on('skill.prompt', async ($, e, next) => {
225    await update($, skills, list => bumpSkill(list, e.skill))
226    return next(e)
227  })
228
229  // Runs as each hooks module loads: the plugin names ClaudeRouter can see
230  on('plugin.register', async ($, e, next) => {
231    await update($, plugins, list => addPlugin(list, e.name))
232    return next(e)
233  }).catch(($, e, next) => next(e))
234
235  // Runs when a subagent is about to start. A model the Agent call already named stays as it is.
236  on('agent.spawn', async ($, e, next) => {
237    const text = `${e.description} ${e.prompt}`
238    const pick = pickRoute({ text, tools: [], subagentType: e.subagentType })
239    // Subagents never start on Opus unless they plan: execution is Sonnet or Haiku
240    const spawnModel = pick.model === 'opus' && e.subagentType !== 'Plan' ? 'sonnet' : pick.model
241    const result = await next({ ...e, model: e.model ?? spawnModel })
242    if (result.deny) return result
243
244    if (result.agentId) subagents.set(result.agentId, { text, subagentType: e.subagentType })
245    const agent: Agent = {
246      id: result.agentId ?? null,
247      name: e.description || e.subagentType,
248      role: roleOf(e.subagentType, text),
249      model: result.model ?? null,
250      effort: null,
251      status: 'running',
252      startedAt: await $.clock.now(),
253      seconds: null,
254      tokens: 0,
255    }
256    await update($, tasks, list => attachAgent(list, turnId, agent))
257    return result
258  }).catch(($, e, next) => next(e))
259
260  // Runs when a turn ends, for the main conversation and for each subagent
261  on('turn.complete', async ($, e, next) => {
262    const tokens = e.usage ? e.usage.input_tokens + e.usage.output_tokens : 0
263    const status = e.reason === 'error' ? 'failed' : 'done'
264    const seconds = e.durationMs / 1000
265    const agentId = e.agentId
266    await update($, totals, t => ({ tokens: t.tokens + tokens, turns: t.turns + (agentId ? 0 : 1) }))
267
268    if (agentId) {
269      await update($, tasks, list => patchAgent(list, agentId, { status, seconds, tokens }))
270    } else {
271      busy = false
272      await update($, tasks, list => patchTask(list, e.turnId, { status, seconds, tokens }))
273      const raw = await $.session.usage()
274      await update($, usage, () => toUsage(raw))
275    }
276    return next(e)
277  })
278
279  // Runs when the session's figures change: context, rate limits, cost
280  on('session.measure', async ($, e, next) => {
281    await update($, usage, prev => toUsage({ ...e, startedAt: prev?.startedAt ?? 0 }))
282    return next(e)
283  })
284
285  // Draws the ClaudeRouter band above the prompt, one row per fact the events expose
286  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
287    if (e.props.hasSurvey) return next(e)
288    const snap = await snapshot($, e.surface, e.props.bodyColumns, e.props.maxRows)
289    terminal = snap.terminal
290    const tree = drawBand($.ui.resolve(e) as Els, snap)
291    mounted.set(e.requestId, snap.anim)
292    return tree
293  })
294
295  // Draws the /ClaudeRouter pane: the cards, the running and finished lists
296  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e, next) => {
297    const snap = await snapshot($, e.surface, e.props.bodyColumns, e.props.scroll.bodyRows)
298    terminal = snap.terminal
299    const tree = drawPane($.ui.resolve(e) as Els, snap)
300    mounted.set(e.requestId, snap.anim)
301    return tree
302  })
303}
304
hooks/jev.ts 67 lines
1import type { Model } from '../types'
2import type { RouteInput } from './route'
3
4// Jev (TypeSafe System One) as the judge: one Choice question over the three tiers.
5// It picks the tier; Claude still does the work. Any failure returns null and the caller falls back to the rules.
6const URL = 'https://api.typesafe.ai/v1/systemone'
7export const JEV_TIMEOUT_MS = 2500
8const TIERS: Model[] = ['haiku', 'sonnet', 'opus']
9
10export type JevFetch = (
11  url: string,
12  init: { method: string; headers: Record<string, string>; body: string },
13) => Promise<{ ok: boolean; text: string }>
14
15// jev-1.13: 64k tokens per request (docs.typesafe.ai/models)
16export const JEV_WINDOW = 64_000
17
18export type JevPick = { model: Model; conf: number; input: number; output: number }
19
20export function jevBody(input: RouteInput) {
21  return {
22    model: 'jev-latest',
23    state: {
24      request: input.text.slice(0, 4000),
25      agent: input.subagentType ?? 'main conversation',
26      tools_used_this_turn: [...new Set(input.tools)].slice(-8),
27    },
28    questions: {
29      route: {
30        type: 'choice',
31        instructions: 'Which Claude model tier is the cheapest one that will do this request well?',
32        choice: {
33          haiku: 'Lookups, listing, reading, renaming, formatting, short summaries; no real reasoning.',
34          sonnet: 'Ordinary implementation: writing code, fixing a known bug, tests, small multi-file edits.',
35          opus: 'Architecture, planning, hard debugging, security, ambiguous or cross-cutting work.',
36        },
37      },
38    },
39  }
40}
41
42export async function askJev(fetch: JevFetch, key: string, input: RouteInput): Promise<JevPick | null> {
43  try {
44    const res = await fetch(URL, {
45      method: 'POST',
46      headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' },
47      body: JSON.stringify(jevBody(input)),
48    })
49    if (!res.ok) return null
50    const body = JSON.parse(res.text)
51    const answer = body?.answers?.route
52    const model = TIERS.find(t => t === answer?.choice)
53    const p = answer?.probabilities?.[model ?? '']
54    if (!model || typeof p !== 'number' || !Number.isFinite(p)) return null
55    const inTok = Number(body?.usage?.input_tokens)
56    const outTok = Number(body?.usage?.output_tokens)
57    return {
58      model,
59      conf: Math.round(Math.min(0.99, Math.max(0.5, p)) * 100) / 100,
60      input: Number.isFinite(inTok) ? inTok : 0,
61      output: Number.isFinite(outTok) ? outTok : 0,
62    }
63  } catch {
64    return null
65  }
66}
67
hooks/options.ts 110 lines
1import type { Effort, Model, Options } from '../types'
2import { EFFORTS, toEffort } from './guard'
3
4export const DEFAULT_OPTIONS: Options = {
5  engine: 'rules',
6  warmUntil: 0,
7  pin: null,
8  pinEffort: null,
9  // xhigh/max are never picked automatically
10  maxEffort: 'high',
11  budget: 3,
12  ctxCap: 150_000,
13}
14// A ping every 50 minutes keeps a one-hour prompt cache read instead of re-written
15export const WARM_EVERY_MS = 50 * 60 * 1000
16const WARM_DEFAULT_MS = 2 * 60 * 60 * 1000
17const WARM_MAX_MS = 6 * 60 * 60 * 1000
18
19export const USAGE = [
20  '/clauderouter                 open the pane',
21  '/clauderouter engine jev      let Jev pick the model tier (needs TYPESAFE_API_KEY)',
22  '/clauderouter engine rules    use the local keyword rules (default)',
23  '/clauderouter warm [2h]       keep the prompt cache warm for 2h (max 6h)',
24  '/clauderouter warm off        stop keeping it warm',
25  '/clauderouter pin sonnet [medium]  force a model (and effort) from the next request, even mid-turn',
26  '/clauderouter pin auto        let the router decide again',
27  '/clauderouter cap high        highest effort the router may pick by itself (default high)',
28  '/clauderouter budget 3        USD one turn may spend before it is downgraded (off = no limit)',
29  '/clauderouter ctx 150k        context size above which requests are downgraded (off = no limit)',
30  '/clauderouter status          show the current options',
31  'Prompt prefix: "@sonnet:med ..." pins that one turn.',
32].join('\n')
33
34// "90m", "2h", "45" (minutes) -> ms, or null
35export function parseWindow(s: string): number | null {
36  const m = /^(\d+(?:\.\d+)?)\s*([mh]?)$/i.exec(s.trim())
37  if (!m) return null
38  const ms = Number(m[1]) * (m[2]?.toLowerCase() === 'h' ? 3_600_000 : 60_000)
39  return ms > 0 ? Math.min(ms, WARM_MAX_MS) : null
40}
41
42// "3", "$3", "off" -> USD / 0, or null
43export function parseBudget(s: string): number | null {
44  if (s.trim().toLowerCase() === 'off') return 0
45  const n = Number(s.trim().replace(/^\$/, ''))
46  return Number.isFinite(n) && n > 0 ? n : null
47}
48
49// "150k", "200000", "off" -> tokens / 0, or null
50export function parseTokens(s: string): number | null {
51  if (s.trim().toLowerCase() === 'off') return 0
52  const m = /^(\d+(?:\.\d+)?)\s*(k?)$/i.exec(s.trim())
53  if (!m) return null
54  const n = Number(m[1]) * (m[2] ? 1000 : 1)
55  return n > 0 ? Math.round(n) : null
56}
57
58export function describe(o: Options, now: number): string {
59  const warm = o.warmUntil > now ? `on, ${Math.round((o.warmUntil - now) / 60_000)} min left` : 'off'
60  const pin = o.pin ? `${o.pin}${o.pinEffort ? `/${o.pinEffort}` : ''}` : 'auto'
61  const budget = o.budget > 0 ? `$${o.budget}/turn` : 'off'
62  const ctx = o.ctxCap > 0 ? `${Math.round(o.ctxCap / 1000)}k` : 'off'
63  return `engine: ${o.engine} · model: ${pin} · max effort: ${o.maxEffort} · budget: ${budget} · ctx cap: ${ctx} · keep-warm: ${warm}`
64}
65
66// Applies one /clauderouter argument string. next is null when the args are not an option change.
67export function applyArgs(args: string, o: Options, now: number): { next: Options | null; text: string } {
68  const [cmd = '', ...rest] = args.trim().split(/\s+/)
69  const arg = rest.join(' ')
70  switch (cmd.toLowerCase()) {
71    case 'engine':
72      if (arg !== 'jev' && arg !== 'rules') return { next: null, text: `engine takes jev or rules\n${USAGE}` }
73      return { next: { ...o, engine: arg }, text: `engine: ${arg}` }
74    case 'warm': {
75      if (arg === 'off') return { next: { ...o, warmUntil: 0 }, text: 'keep-warm: off' }
76      const ms = arg ? parseWindow(arg) : WARM_DEFAULT_MS
77      if (ms === null) return { next: null, text: `warm takes a duration like 90m or 2h, or off\n${USAGE}` }
78      return { next: { ...o, warmUntil: now + ms }, text: `keep-warm: on for ${Math.round(ms / 60_000)} min, a ping every 50 min while idle` }
79    }
80    case 'pin': {
81      const [m = '', e = ''] = arg.split(/\s+/)
82      if (m === 'auto' || m === 'off') return { next: { ...o, pin: null, pinEffort: null }, text: 'model: auto' }
83      if (m !== 'haiku' && m !== 'sonnet' && m !== 'opus') return { next: null, text: `pin takes haiku, sonnet, opus or auto\n${USAGE}` }
84      const effort: Effort | null = e ? toEffort(e) : null
85      if (e && !effort) return { next: null, text: `effort takes ${EFFORTS.join(', ')}\n${USAGE}` }
86      const pin: Model = m
87      return { next: { ...o, pin, pinEffort: effort }, text: `model pinned: ${pin}${effort ? `/${effort}` : ''}` }
88    }
89    case 'cap': {
90      const effort = toEffort(arg)
91      if (!effort) return { next: null, text: `cap takes ${EFFORTS.join(', ')}\n${USAGE}` }
92      return { next: { ...o, maxEffort: effort }, text: `max auto effort: ${effort}` }
93    }
94    case 'budget': {
95      const usd = parseBudget(arg)
96      if (usd === null) return { next: null, text: `budget takes a USD amount like 3, or off\n${USAGE}` }
97      return { next: { ...o, budget: usd }, text: usd > 0 ? `turn budget: $${usd}` : 'turn budget: off' }
98    }
99    case 'ctx': {
100      const tokens = parseTokens(arg)
101      if (tokens === null) return { next: null, text: `ctx takes a size like 150k, or off\n${USAGE}` }
102      return { next: { ...o, ctxCap: tokens }, text: tokens > 0 ? `context cap: ${Math.round(tokens / 1000)}k` : 'context cap: off' }
103    }
104    case 'status':
105      return { next: null, text: describe(o, now) }
106    default:
107      return { next: null, text: USAGE }
108  }
109}
110
hooks/guard.ts 110 lines
1import type { Effort, Model } from '../types'
2import type { RoutePick } from './route'
3
4// Cost guards: pure limits applied on top of the router's pick, on every model request.
5// The router decides what a prompt *looks like*; the guard decides what the turn may *cost*.
6
7export const EFFORTS: Effort[] = ['low', 'medium', 'high', 'xhigh']
8const MODELS: Model[] = ['haiku', 'sonnet', 'opus']
9const rankE = (e: Effort) => EFFORTS.indexOf(e)
10const rankM = (m: Model) => MODELS.indexOf(m)
11
12export const capEffort = (e: Effort, max: Effort): Effort => (rankE(e) > rankE(max) ? max : e)
13const capModel = (m: Model, max: Model): Model => (rankM(m) > rankM(max) ? max : m)
14
15// Effort when a model is pinned without one
16export const DEFAULT_EFFORT: Record<Model, Effort> = { haiku: 'low', sonnet: 'medium', opus: 'high' }
17
18// Opus may plan: it keeps the first requests of a turn, then the turn moves to Sonnet
19export const OPUS_STEPS = 2
20// A prompt longer than this is a spec, not a question: Opus on it never runs above medium
21export const LONG_PROMPT = 1200
22// This many tool calls in one turn = it is executing, not planning
23export const EXEC_TOOLS = 6
24const WRITES = ['Edit', 'Write', 'MultiEdit', 'NotebookEdit']
25
26export type Pin = { model: Model; effort: Effort | null }
27
28export type GuardInput = {
29  pick: RoutePick
30  // The user's explicit choice (a turn directive or /clauderouter pin): wins over every limit
31  pin: Pin | null
32  maxEffort: Effort
33  // USD one turn may spend before the guard downgrades it; 0 = off
34  budget: number
35  // Context tokens above which the guard downgrades; 0 = off
36  ctxCap: number
37  isSub: boolean
38  isPlan: boolean
39  // Index of this request within its turn
40  step: number
41  textLen: number
42  turnTools: readonly string[]
43  contextTokens: number | null
44  // USD spent since the turn started
45  turnCost: number | null
46}
47
48export type Guarded = { model: Model; effort: Effort; limits: string[] }
49
50export function guard(i: GuardInput): Guarded {
51  if (i.pin) {
52    const effort = i.pin.effort ?? (i.pin.model === i.pick.model ? i.pick.effort : DEFAULT_EFFORT[i.pin.model])
53    return { model: i.pin.model, effort, limits: ['pinned'] }
54  }
55  let { model, effort } = i.pick
56  const limits: string[] = []
57
58  if (rankE(effort) > rankE(i.maxEffort)) {
59    effort = i.maxEffort
60    limits.push(`effort≤${i.maxEffort}`)
61  }
62
63  // Plan with Opus, execute with Sonnet
64  if (model === 'opus') {
65    const executing = i.turnTools.some(t => WRITES.includes(t)) || i.turnTools.length >= EXEC_TOOLS
66    if (i.isSub && !i.isPlan) {
67      model = 'sonnet'
68      effort = capEffort(effort, 'medium')
69      limits.push('subagent→sonnet')
70    } else if (!i.isSub && (i.step >= OPUS_STEPS || executing)) {
71      model = 'sonnet'
72      effort = capEffort(effort, 'medium')
73      limits.push('opus plans only')
74    } else if (i.textLen > LONG_PROMPT) {
75      effort = capEffort(effort, 'medium')
76      limits.push('long prompt')
77    }
78  }
79
80  // A subagent is never above medium unless it plans
81  if (i.isSub && !i.isPlan) effort = capEffort(effort, 'medium')
82
83  if (i.ctxCap > 0 && i.contextTokens !== null && i.contextTokens > i.ctxCap) {
84    model = capModel(model, 'sonnet')
85    effort = capEffort(effort, i.contextTokens > i.ctxCap * 1.5 ? 'low' : 'medium')
86    limits.push(`ctx ${Math.round(i.contextTokens / 1000)}k`)
87  }
88
89  if (i.budget > 0 && i.turnCost !== null && i.turnCost > i.budget) {
90    model = capModel(model, 'sonnet')
91    effort = capEffort(effort, i.turnCost > i.budget * 2 ? 'low' : 'medium')
92    limits.push(`turn $${i.turnCost.toFixed(2)}>$${i.budget}`)
93  }
94  return { model, effort, limits }
95}
96
97// "@sonnet", "@opus:high", "@haiku:med" at the very start of a prompt pins that turn
98const DIRECTIVE = /^\s*@(haiku|sonnet|opus)(?::(low|med|medium|high|xhigh))?(?=\s|$)/i
99
100export function toEffort(s: string): Effort | null {
101  const v = s.toLowerCase() === 'med' ? 'medium' : s.toLowerCase()
102  return EFFORTS.find(e => e === v) ?? null
103}
104
105export function directiveOf(text: string): Pin | null {
106  const m = DIRECTIVE.exec(text)
107  if (!m) return null
108  return { model: m[1]!.toLowerCase() as Model, effort: m[2] ? toEffort(m[2]) : null }
109}
110
hooks/band.ts 199 lines
1import type { Elements, RenderElement } from 'claude-code'
2import type { JevUse, McpUse, Route, SkillUse, Task, Usage } from '../types'
3import { JEV_WINDOW } from './jev'
4import { familyOf } from './route'
5import { ACCENT, type Anim, type Role, type Tone, barCells, packCells, spriteCells, SPRITE_COLUMNS, SPRITE_ROWS } from './pixel'
6import { fmtFit, fmtPct, fmtTime, fmtTokens } from './format'
7
8export type Els = Elements['terminal']
9
10// Everything the drawings read, gathered by the hooks: the drawings take values, never $.
11// `anim` is the one thing they write: the Rasters they mount that the timer repaints.
12export type Snapshot = {
13  route: Route | null
14  tasks: Task[]
15  skills: SkillUse[]
16  mcp: McpUse[]
17  plugins: string[]
18  usage: Usage | null
19  jev: JevUse | null
20  totals: { tokens: number; turns: number }
21  now: number
22  frame: number
23  terminal: boolean
24  columns: number
25  rows: number
26  anim: Anim[]
27}
28
29// Text uses theme keys so light and dark both read; Rasters use the design's accents
30export const MODEL_TONE = { haiku: 'success', sonnet: 'suggestion', opus: 'warning' } as const
31const EFFORT_LEVEL = { low: 1, medium: 2, high: 3, xhigh: 4 } as const
32const MODELS = ['haiku', 'sonnet', 'opus'] as const
33const LABEL = 16
34// The crew needs this many rows above the band's own before it is drawn
35const CREW_MIN_ROWS = 22
36
37export function accentOf(model: string | null): number {
38  const family = model ? familyOf(model) : null
39  return family ? ACCENT[family] : ACCENT.brand
40}
41
42// A bar: a Raster in the terminal, a Text row on the desktop, which has no Raster.
43// A running bar with no total (pct null) shimmers; the terminal's timer repaints it with $.ui.blit.
44export function bar(els: Els, key: string, t: Snapshot, width: number, tone: Tone, pct: number | null, accent: number): RenderElement {
45  const cells = barCells(width, t.frame, tone, pct, accent)
46  if (!t.terminal) {
47    const color = tone === 'fail' ? 'error' : tone === 'done' ? 'success' : pct === null ? 'suggestion' : 'warning'
48    return els.Text({ children: [cells.map(c => (c[0] === '⠂' ? '·' : '█')).join('')], color })
49  }
50  if (tone === 'run' && pct === null) t.anim.push({ key, kind: 'bar', width, accent })
51  return els.Raster({ key, columns: width, rows: 1, cells: packCells([cells]) })
52}
53
54export function toneOf(status: Task['status']): Tone {
55  return status === 'running' ? 'run' : status === 'done' ? 'done' : 'fail'
56}
57
58// One crab of the crew: running ones step and wave, the rest stand still
59export function crab(els: Els, t: Snapshot, key: string, role: Role, running: boolean): RenderElement {
60  if (running) t.anim.push({ key, kind: 'sprite', role })
61  return els.Raster({ key, columns: SPRITE_COLUMNS, rows: SPRITE_ROWS, cells: spriteCells(role, 'still', t.frame) })
62}
63
64const barWidth = (t: Snapshot) => Math.max(8, Math.min(30, t.columns - 46))
65
66function label(els: Els, glyph: string, text: string, color = 'subtle'): RenderElement {
67  return els.Box({ width: LABEL, children: [els.Text({ children: [`${glyph} ${text}`], color })] })
68}
69
70function row(els: Els, children: RenderElement[]): RenderElement {
71  return els.Box({ flexDirection: 'row', columnGap: 2, children })
72}
73
74function header(els: Els, t: Snapshot): RenderElement[] {
75  const { Box, Text } = els
76  const running = t.tasks.filter(task => task.status === 'running')
77  const agents = running.flatMap(task => task.agents).filter(a => a.status === 'running')
78  const sub = running.length === 0 ? 'idle' : agents.length > 0 ? `working · ${agents.length} agent${agents.length === 1 ? '' : 's'}` : 'working'
79  const title = Box({
80    flexDirection: 'row',
81    columnGap: 2,
82    children: [Text({ children: ['ClaudeRouter'], bold: true, color: 'claude' }), Text({ children: [`${sub} · turn ${t.totals.turns + running.length}`], color: 'subtle' })],
83  })
84  if (!t.terminal || t.rows < CREW_MIN_ROWS) return [title]
85  const room = Math.max(0, Math.floor((t.columns - SPRITE_COLUMNS) / (SPRITE_COLUMNS + 1)))
86  const crew = [
87    crab(els, t, 'crab-router', 'router', running.length > 0),
88    ...agents.slice(0, Math.min(4, room)).map((a, i) => crab(els, t, `crab-${i}`, a.role, true)),
89  ]
90  return [Box({ flexDirection: 'row', columnGap: 1, children: crew }), title]
91}
92
93function routeRows(els: Els, r: Route): RenderElement[] {
94  const why = r.why
95  const { Box, Text } = els
96  const level = EFFORT_LEVEL[r.effort]
97  const prev = familyOf(r.engineModel)
98  const chips = MODELS.map(m =>
99    Text({
100      children: [m === prev && !r.kept ? `[${m}]` : ` ${m} `],
101      color: MODEL_TONE[m],
102      bold: m === r.model,
103      inverse: m === r.model,
104      dimColor: m !== r.model && m !== prev,
105    }),
106  )
107  // Jev sits beside the tiers: lit when it made this pick, dim when the rules did
108  chips.push(Text({ children: [' jev '], color: 'claude', bold: r.by === 'jev', inverse: r.by === 'jev', dimColor: r.by !== 'jev' }))
109  const signal = [1, 2, 3, 4].map(i => Text({ children: ['▂▄▆█'[i - 1] ?? ' '], color: i <= level ? MODEL_TONE[r.model] : 'inactive' }))
110  const confBar = '▬'.repeat(Math.round(r.conf * 5)).padEnd(5, '·')
111  return [
112    row(els, [
113      label(els, '⇄', 'Model route'),
114      Text({ children: [`${prev ?? '—'} =`], color: 'subtle' }),
115      Box({ flexDirection: 'row', children: chips }),
116      Box({ flexDirection: 'row', columnGap: 1, children: [Box({ flexDirection: 'row', children: signal }), Text({ children: [r.effort] })] }),
117      Text({ children: [`conf ${confBar} ${r.conf.toFixed(2)}`] }),
118      Text({ children: [r.kept ? '= kept' : '→ switched'], color: r.kept ? 'subtle' : 'claude' }),
119    ]),
120    ...(why ? [row(els, [Box({ width: LABEL }), Text({ children: [why], color: 'subtle', dimColor: true })])] : []),
121  ]
122}
123
124function taskRows(els: Els, t: Snapshot, task: Task): RenderElement[] {
125  const { Box, Text } = els
126  const done = task.agents.filter(a => a.status !== 'running').length
127  const status = task.status === 'running' ? `step ${task.steps}` : `${task.status} · ${fmtTime(task.seconds ?? 0)}`
128  const head = row(els, [
129    Box({
130      width: LABEL,
131      children: [Text({ children: [`● ${fmtFit(task.name, LABEL - 3)}`], bold: true, color: task.status === 'failed' ? 'error' : 'text' })],
132    }),
133    bar(els, `task-${task.id}`, t, barWidth(t), toneOf(task.status), null, accentOf(task.model)),
134    Text({ children: [status], color: 'subtle' }),
135    ...(task.agents.length > 0 ? [Text({ children: [`${done}/${task.agents.length} agents`] })] : []),
136  ])
137  const agents = task.agents.map(a => {
138    const seconds = a.status === 'running' ? (t.now - a.startedAt) / 1000 : (a.seconds ?? 0)
139    const family = a.model ? familyOf(a.model) : null
140    const state = a.status === 'running' ? 'running' : a.status === 'done' ? 'Done' : 'failed'
141    return Box({
142      flexDirection: 'row',
143      columnGap: 1,
144      children: [
145        Text({ children: [`   └ ${fmtFit(a.name, 28)} ·`], color: 'subtle' }),
146        Text({ children: [state], color: a.status === 'failed' ? 'error' : a.status === 'done' ? 'success' : family ? MODEL_TONE[family] : 'text' }),
147        Text({ children: ['·'], color: 'subtle' }),
148        Text({ children: [` ${family ?? a.model ?? '—'} `], color: family ? MODEL_TONE[family] : 'subtle', inverse: family !== null }),
149        Text({ children: [`· ${fmtTime(seconds)}`], color: 'subtle' }),
150      ],
151    })
152  })
153  return [head, ...agents]
154}
155
156function meterRow(els: Els, t: Snapshot, glyph: string, name: string, detail: string, key: string, pct: number | null, accent: number): RenderElement {
157  // No reading means an empty track, never a shimmer or an invented figure
158  return row(els, [label(els, glyph, name), bar(els, key, t, barWidth(t), 'run', pct ?? 0, accent), els.Text({ children: [detail] })])
159}
160
161function listRow(els: Els, glyph: string, name: string, items: string[], empty: string, total: string): RenderElement {
162  const { Text } = els
163  return row(els, [
164    label(els, glyph, name),
165    ...(items.length > 0 ? items.map(s => Text({ children: [s] })) : [Text({ children: [empty], color: 'subtle' })]),
166    Text({ children: [total], color: 'subtle' }),
167  ])
168}
169
170// The band above the prompt. One row per fact the events expose; nothing is estimated.
171export function drawBand(els: Els, t: Snapshot): RenderElement {
172  const { Box, Text } = els
173  const shown = [...t.tasks.filter(task => task.status === 'running'), ...t.tasks.filter(task => task.status !== 'running').slice(-1)]
174  const extra = t.plugins.length - 5
175  const ctx = t.usage?.context ?? null
176  const five = t.usage?.rateLimits.find(r => r.kind === 'five_hour')
177  const week = t.usage?.rateLimits.find(r => r.kind === 'seven_day')
178  const calls = t.mcp.reduce((n, m) => n + m.calls, 0)
179
180  return Box({
181    flexDirection: 'column',
182    children: [
183      ...header(els, t),
184      ...(t.route ? routeRows(els, t.route) : [row(els, [label(els, '⇄', 'Model route'), Text({ children: ['waiting for the first request'], color: 'subtle' })])]),
185      ...shown.flatMap(task => taskRows(els, t, task)),
186      listRow(els, '✦', 'Skills', t.skills.slice(-4).map(s => `${s.name} used ×${s.uses}`), 'none used yet', `${t.skills.length} used`),
187      listRow(els, '◇', 'MCP', t.mcp.slice(-3).map(m => `${m.server} · ${m.tool} ×${m.calls}`), 'no calls yet', `${calls} calls`),
188      listRow(els, '▣', 'Plugins', [...t.plugins.slice(-5), ...(extra > 0 ? [`+${extra}`] : [])], 'none seen', `${t.plugins.length} mods`),
189      meterRow(els, t, '◆', 'Context', ctx ? `${fmtTokens(ctx.tokens)} / ${fmtTokens(ctx.window)} · ${fmtPct(ctx.percent)}` : '—', 'context', ctx?.percent ?? null, ACCENT.brand),
190      ...(t.jev
191        ? [meterRow(els, t, '◈', 'Jev · context', `${fmtTokens(t.jev.input)} / ${fmtTokens(JEV_WINDOW)} · ${fmtPct((t.jev.input / JEV_WINDOW) * 100)} · ${t.jev.calls} calls`, 'jev', (t.jev.input / JEV_WINDOW) * 100, ACCENT.brand)]
192        : []),
193      meterRow(els, t, '◷', 'Session · 5h', five ? `5h · ${fmtPct(five.percentUsed)} used` : 'no reading', 'session', five?.percentUsed ?? null, ACCENT.sonnet),
194      meterRow(els, t, '◷', 'Weekly · 7d', week ? `7d · ${fmtPct(week.percentUsed)} used` : 'no reading', 'weekly', week?.percentUsed ?? null, ACCENT.opus),
195    ],
196  })
197}
198
199
hooks/pane.ts 144 lines
1import type { RenderElement } from 'claude-code'
2import type { Agent, Task } from '../types'
3import { accentOf, bar, crab, MODEL_TONE, toneOf, type Els, type Snapshot } from './band'
4import { fmtFit, fmtPct, fmtTime, fmtTokens } from './format'
5import { familyOf } from './route'
6
7// One line of the Running or Finished list: a task, or a subagent under it
8type Row = {
9  key: string
10  name: string
11  role: Agent['role'] | 'router'
12  model: string | null
13  effort: string | null
14  ctx: string
15  tokens: number | null
16  status: Task['status']
17  seconds: number | null
18  startedAt: number
19  indent: boolean
20}
21
22// Context % is the main conversation's, so only its running task shows it; no agent has its own reading
23function rowsOf(tasks: Task[], ctx: string): Row[] {
24  return tasks.flatMap((task): Row[] => [
25    {
26      key: task.id,
27      name: task.name,
28      role: 'router',
29      model: task.model,
30      effort: task.effort,
31      ctx: task.status === 'running' ? ctx : '—',
32      tokens: task.tokens,
33      status: task.status,
34      seconds: task.seconds,
35      startedAt: task.startedAt,
36      indent: false,
37    },
38    ...task.agents.map((a, i): Row => ({
39      key: `${task.id}-${a.id ?? i}`,
40      name: a.name,
41      role: a.role,
42      model: a.model,
43      effort: a.effort,
44      ctx: '—',
45      tokens: a.status === 'running' ? null : a.tokens,
46      status: a.status,
47      seconds: a.seconds,
48      startedAt: a.startedAt,
49      indent: true,
50    })),
51  ])
52}
53
54function col(els: Els, width: number, text: string, props: { bold?: boolean; color?: string } = {}): RenderElement {
55  return els.Box({ width, children: [els.Text({ children: [text], ...props })] })
56}
57
58// A row: its crab beside two lines, name · role · model · effort · state over ctx · tokens · time and the bar
59function rowView(els: Els, t: Snapshot, r: Row, crabs: boolean): RenderElement {
60  const { Box, Text } = els
61  const seconds = r.status === 'running' ? (t.now - r.startedAt) / 1000 : (r.seconds ?? 0)
62  const family = r.model ? familyOf(r.model) : null
63  const running = r.status === 'running'
64  const mark = r.status === 'done' ? '✓' : r.status === 'failed' ? '✗' : t.frame % 10 < 5 ? '●' : '○'
65  const lines = Box({
66    flexDirection: 'column',
67    children: [
68      Box({
69        flexDirection: 'row',
70        columnGap: 1,
71        children: [
72          col(els, 26, `${r.indent && !crabs ? '└ ' : ''}${fmtFit(r.name, 24)}`, { bold: true }),
73          col(els, 11, r.role, { color: 'claude' }),
74          Text({ children: [`${family ?? '—'} · ${r.effort ?? '—'} · ${r.status}`], color: family ? MODEL_TONE[family] : 'subtle' }),
75        ],
76      }),
77      Box({
78        flexDirection: 'row',
79        columnGap: 1,
80        children: [
81          bar(els, `row-${r.key}`, t, Math.max(8, Math.min(36, t.columns - (crabs ? 52 : 30))), toneOf(r.status), null, accentOf(r.model)),
82          Text({ children: [`ctx ${r.ctx} · ${r.tokens === null ? '—' : fmtTokens(r.tokens)} · ${fmtTime(seconds)}`], color: 'subtle' }),
83          Text({ children: [mark], color: r.status === 'failed' ? 'error' : running ? 'claude' : 'success' }),
84        ],
85      }),
86    ],
87  })
88  if (!crabs) return lines
89  return Box({ flexDirection: 'row', columnGap: 1, children: [crab(els, t, `crab-${r.key}`, r.role, running), lines] })
90}
91
92function section(els: Els, t: Snapshot, title: string, rows: Row[], crabs: boolean): RenderElement[] {
93  const head = els.Text({ children: [`▾ ${title} · ${rows.length}`], bold: true })
94  if (rows.length === 0) return [head, els.Text({ children: ['none'], color: 'subtle' })]
95  return [head, ...rows.map(r => rowView(els, t, r, crabs))]
96}
97
98// The /ClaudeRouter pane: the current task and route, three cards, then the running and finished lists
99export function drawPane(els: Els, t: Snapshot): RenderElement {
100  const { Box, Text } = els
101  const card = (title: string, value: string) =>
102    Box({
103      flexDirection: 'column',
104      borderStyle: 'round',
105      paddingX: 1,
106      minWidth: 14,
107      children: [Text({ children: [title], color: 'subtle' }), Text({ children: [value], bold: true })],
108    })
109  const cost = t.usage?.cost ?? null
110  const started = t.usage?.startedAt ?? 0
111  const rows = rowsOf(t.tasks, fmtPct(t.usage?.context.percent))
112  const running = rows.filter(r => r.status === 'running')
113  // The crabs are terminal Rasters and need width; past a few rows they would bury the list
114  const crabs = t.terminal && t.columns >= 80 && rows.length <= 3
115  const current = t.tasks.filter(task => task.status === 'running').at(-1) ?? t.tasks.at(-1)
116  const r = t.route
117
118  return Box({
119    flexDirection: 'column',
120    gap: 1,
121    children: [
122      Box({
123        flexDirection: 'row',
124        justifyContent: 'space-between',
125        children: [
126          Text({ children: [current ? fmtFit(current.name, Math.max(20, t.columns - 40)) : 'No task yet'], bold: true }),
127          Text({ children: [r ? `route: ${r.model} · ${r.effort} · conf ${r.conf.toFixed(2)}` : 'route: —'], color: 'subtle' }),
128        ],
129      }),
130      Box({
131        flexDirection: 'row',
132        columnGap: 1,
133        children: [
134          card('Cost', cost === null ? '—' : `≈$${cost.toFixed(2)}`),
135          card('Tokens', fmtTokens(t.totals.tokens)),
136          card('Time', started > 0 ? fmtTime((t.now - started) / 1000) : '—'),
137        ],
138      }),
139      Box({ flexDirection: 'column', children: section(els, t, 'Running', running, crabs) }),
140      Box({ flexDirection: 'column', children: section(els, t, 'Finished', rows.filter(x => x.status !== 'running'), crabs) }),
141    ],
142  })
143}
144
hooks/pixel.ts 133 lines
1// Raster cells: the crab crew and the bars. A mod cannot read the theme, so Raster colours are
2// the design's fixed RGB; empty cells use the terminal's own default so light and dark both read.
3export const DEFAULT = 0x01000000
4
5// The design's accents: model chips, meters and the bars that follow them
6export const ACCENT = {
7  haiku: 0x55c99a,
8  sonnet: 0xa79cf2,
9  opus: 0xf0b84a,
10  brand: 0xe8835f,
11  fail: 0xd9534f,
12  track: 0x55535b,
13}
14
15// One cell: a character, its foreground colour and its background (the terminal's by default)
16export type Cell = [string, number, number?]
17
18// Pack rows of cells into the base64 string a Raster takes: per cell the code point, foreground, background
19export function packCells(rows: Cell[][]): string {
20  const words = Uint32Array.from(rows.flat().flatMap(([char, fg, bg]) => [char.codePointAt(0) ?? 32, fg, bg ?? DEFAULT]))
21  // toBase64 is in the mods runtime but not in the es2023 lib the types check against
22  return (new Uint8Array(words.buffer) as Uint8Array & { toBase64(): string }).toBase64()
23}
24
25// The crab, two frames (arm wave and step), from the design's BA / BB maps
26const BA = ['................', '................', '................', '..BBBBBBBBBBBB..', '..BBBBBBBBBBBB..', '..BBBEBBBBEBBB..', 'AABBBEBBBBEBBBAA', 'AABBBBBBBBBBBBAA', '..BRRBBBBBBRRB..', '..BBBBBBBBBBBB..', '...FF......FF...', '...FF......FF...']
27const BB = ['................', '................', '................', '..BBBBBBBBBBBB..', '..BBBBBBBBBBBBAA', '..BBBEBBBBEBBBAA', 'AABBBEBBBBEBBB..', 'AABBBBBBBBBBBB..', '..BRRBBBBBBRRB..', '..BBBBBBBBBBBB..', '...FF......FF...', '....FF....FF....']
28const PAL: Record<string, number> = {
29  A: 0xd06e54, R: 0xd9706f, F: 0xb4573f, B: 0xe07a5f, E: 0x1a1214, W: 0xece9e4, K: 0x2b2a30,
30  G: 0xa3a1a9, T: 0xb08a5a, P: 0xd9d6dd, N: 0x2f3a5c, Y: 0xe9c84a, Q: 0xa6d8ec,
31}
32
33type Part = [row: number, col: number, px: string]
34type RoleArt = { c: Record<string, number>; hat: Part[]; prop: Part[] }
35
36// Each role wears a hat and holds a tool: router headset + signpost, scout cap + flag,
37// builder hard hat + wrench, researcher bucket hat + magnifier, planner captain's cap + clipboard
38const ROLES = {
39  router: { c: { X: ACCENT.brand }, hat: [[0, 5, 'KKKKKK'], [1, 4, 'K......K'], [2, 3, 'XX......XX'], [3, 3, 'X........X']], prop: [[-3, 16, 'XXX'], [-2, 16, 'XXXX'], [-1, 16, 'XXX'], [0, 17, 'T'], [1, 17, 'T'], [2, 17, 'T']] },
40  scout: { c: { H: 0x2fa374, V: 0x1f6b4d }, hat: [[0, 5, 'HHHHHH'], [1, 4, 'HHHWWHHH'], [2, 4, 'HHHHHHHHV']], prop: [[-4, 16, 'PKWK'], [-3, 16, 'PWKW'], [-2, 16, 'PKWK'], [-1, 16, 'P'], [0, 16, 'P'], [1, 16, 'P']] },
41  builder: { c: { H: 0xe9c84a, h: 0xb88a2a }, hat: [[0, 6, 'HHHH'], [1, 4, 'HHHhHHHH'], [2, 3, 'hhhhhhhhhh']], prop: [[-3, 16, 'G.G'], [-2, 16, 'GGG'], [-1, 17, 'G'], [0, 17, 'G'], [1, 17, 'G']] },
42  researcher: { c: { H: 0x7a5236, h: 0xa8744c }, hat: [[0, 5, 'HhHHhH'], [1, 4, 'HHHHHHHH'], [2, 3, 'HHHHHHHHHH']], prop: [[-4, 17, 'GG'], [-3, 16, 'GQQG'], [-2, 16, 'GQQG'], [-1, 17, 'GG'], [0, 16, 'T'], [1, 15, 'T']] },
43  planner: { c: {}, hat: [[0, 5, 'WWWWWW'], [1, 4, 'WWWYYWWW'], [2, 4, 'NNNNNNNN']], prop: [[-3, 17, 'T'], [-2, 16, 'WWW'], [-1, 16, 'WKW'], [0, 16, 'WWW'], [1, 16, 'WKW']] },
44} satisfies Record<string, RoleArt>
45
46export type Role = keyof typeof ROLES
47export type Mode = 'run' | 'still'
48
49// The used part of the design's grid: body rows -4 (the tallest prop) to 11, columns 0 to 19
50const TOP = -4
51const PX_ROWS = 16
52export const SPRITE_COLUMNS = 20
53export const SPRITE_ROWS = PX_ROWS / 2
54
55function pixels(role: Role, step: boolean): (number | null)[][] {
56  const art: RoleArt = ROLES[role]
57  const pal: Record<string, number> = { ...PAL, ...art.c }
58  const grid = Array.from({ length: PX_ROWS }, () => Array<number | null>(SPRITE_COLUMNS).fill(null))
59  const put = (r: number, c: number, s: string) =>
60    [...s].forEach((ch, i) => {
61      const row = grid[r - TOP]
62      if (ch !== '.' && row && c + i < SPRITE_COLUMNS) row[c + i] = pal[ch] ?? null
63    })
64  ;(step ? BB : BA).forEach((row, r) => put(r, 0, row))
65  art.hat.forEach(([r, c, s]) => put(r, c, s))
66  // The tool bobs with the step, as the design's two frames do
67  art.prop.forEach(([r, c, s]) => put(r + (step ? 0 : 1), c, s))
68  return grid
69}
70
71// Two pixel rows per terminal row: '▀' holds the top pixel in its foreground and the bottom in its background
72export function spriteCells(role: Role, mode: Mode, frame: number): string {
73  const px = pixels(role, mode === 'run' && Math.floor(frame / 4) % 2 === 1)
74  const rows: Cell[][] = []
75  for (let y = 0; y + 1 < px.length; y += 2) {
76    const top = px[y] ?? []
77    const bottom = px[y + 1] ?? []
78    rows.push(
79      top.map((t, x): Cell => {
80        const b = bottom[x] ?? null
81        if (t === null && b === null) return [' ', DEFAULT]
82        if (t === b) return ['█', t ?? DEFAULT]
83        if (b === null) return ['▀', t ?? DEFAULT]
84        if (t === null) return ['▄', b]
85        return ['▀', t, b]
86      }),
87    )
88  }
89  return packCells(rows)
90}
91
92export type Tone = 'run' | 'done' | 'fail'
93
94// Dither ramp: sparse at the left, dense at the leading edge, like the design's fading dot field
95const RAMP = ['⡀', '⡄', '⡆', '⡇', '⣿']
96const TRACK: Cell = ['⠂', ACCENT.track]
97
98function lighten(c: number): number {
99  const ch = (s: number) => Math.min(255, (((c >> s) & 0xff) + 255) >> 1) << s
100  return ch(16) | ch(8) | ch(0)
101}
102
103// One row of a bar in an accent colour. A known percent fills to it along the ramp; 'run' with
104// none shimmers (a twinkling dithered field with a bright head sweeping through); 'done' and 'fail' are solid.
105export function barCells(width: number, frame: number, tone: Tone, pct: number | null, accent: number): Cell[] {
106  if (tone === 'fail') return Array.from({ length: width }, (): Cell => ['█', ACCENT.fail])
107  if (tone === 'done') return Array.from({ length: width }, (): Cell => ['█', accent])
108  if (pct !== null) {
109    const filled = Math.round((Math.min(100, Math.max(0, pct)) / 100) * width)
110    return Array.from({ length: width }, (_, x): Cell => {
111      if (x >= filled) return TRACK
112      const level = Math.min(RAMP.length - 1, Math.floor(((x + 1) / filled) * RAMP.length))
113      return [RAMP[level] ?? '⣿', accent]
114    })
115  }
116  const head = (frame % (width + 6)) - 3
117  return Array.from({ length: width }, (_, x): Cell => {
118    const d = x - head
119    if (d >= 0 && d < 3) return ['⣿', lighten(accent)]
120    const twinkle = (x * 7 + frame) % 5
121    return [RAMP[twinkle < 2 ? 1 : twinkle < 4 ? 2 : 3] ?? '⡆', accent]
122  })
123}
124
125// A Raster the timer repaints with $.ui.blit: a shimmering bar, or a running crab
126export type Anim =
127  | { key: string; kind: 'bar'; width: number; accent: number }
128  | { key: string; kind: 'sprite'; role: Role }
129
130export function animCells(a: Anim, frame: number): string {
131  return a.kind === 'sprite' ? spriteCells(a.role, 'run', frame) : packCells([barCells(a.width, frame, 'run', null, a.accent)])
132}
133
hooks/route.ts 101 lines
1import type { Agent, Effort, Model } from '../types'
2
3// The mascot a subagent wears: Explore scouts, Plan plans, research reads, the rest build
4export function roleOf(subagentType: string, text: string): Agent['role'] {
5  if (/explore/i.test(subagentType)) return 'scout'
6  if (/plan/i.test(subagentType)) return 'planner'
7  if (/\b(research|investigat\w*|verify|trace|review|audit)\b/i.test(text)) return 'researcher'
8  return 'builder'
9}
10
11// Local heuristics only: no model is called to decide. Counts keyword hits per tier,
12// prompt length, the subagent's type and the tools this turn has used.
13export type RouteInput = {
14  text: string
15  tools: readonly string[]
16  subagentType?: string
17  current?: Model | null
18}
19
20// ponytail: fixed constant; move to $.state config if tuning is wanted
21export const HYSTERESIS = 0.08
22
23export type RoutePick = { model: Model; effort: Effort; conf: number }
24
25const HEAVY = /\b(plan|architect\w*|design|debug\w*|trace|root cause|refactor\w*|migrat\w*|security|race|deadlock|trade-?offs?|investigat\w*|why|performance|optimi[sz]e\w*|across|system)\b/gi
26const MID = /\b(write|implement\w*|fix\w*|test\w*|fixtures?|review\w*|add|update|build)\b/gi
27const LIGHT = /\b(list|read|show|rename|print|count|find|grep|format|typo|log|open|which|where|summari[sz]e)\b/gi
28const DEEP = /\b(plan|architect\w*)\b/i
29const EDITS = ['Edit', 'Write', 'MultiEdit', 'NotebookEdit']
30const SEARCH = ['Glob', 'Grep', 'Read']
31const FAMILIES: Model[] = ['haiku', 'sonnet', 'opus']
32
33// The model family a full model id belongs to, or null when it names none
34export function familyOf(id: string): Model | null {
35  return FAMILIES.find(f => id.includes(f)) ?? null
36}
37
38// The full model id for a family: the running id with its family swapped, so the version suffix is kept
39export function idFor(family: Model, running: string): string {
40  return familyOf(running) ? running.replace(/haiku|sonnet|opus/, family) : `claude-${family}-5-5`
41}
42
43const hits = (text: string, re: RegExp, cap: number) => Math.min(cap, (text.match(re) ?? []).length)
44
45// Scores each tier and picks the highest; a tie, or no signal at all, stays on sonnet
46export function pickRoute(input: RouteInput): RoutePick {
47  const { text, tools } = input
48  const heavy = hits(text, HEAVY, 3)
49  const score = { haiku: hits(text, LIGHT, 2), sonnet: 0.5 + hits(text, MID, 2), opus: heavy }
50
51  if (text.length > 400) score.opus += 1
52  else if (text.length < 60 && heavy === 0) score.haiku += 1
53  if (input.subagentType === 'Explore') score.haiku += 2
54  if (input.subagentType === 'Plan') score.opus += 2
55  if (heavy === 0 && tools.length > 0 && tools.every(t => SEARCH.includes(t))) score.haiku += 1
56  if (tools.some(t => EDITS.includes(t))) score.sonnet += 1
57  if (tools.includes('Bash') && tools.filter(t => EDITS.includes(t)).length >= 3) score.opus += 1
58
59  const ranked = FAMILIES.map(m => [m, score[m]] as const).sort((a, b) => b[1] - a[1])
60  const [top, second] = ranked
61  let model: Model = top && second && top[1] > second[1] ? top[0] : 'sonnet'
62  // Hysteresis: stay on the current model unless the new one beats it by more than HYSTERESIS (softmax share)
63  const total = FAMILIES.reduce((s, m) => s + Math.exp(score[m]), 0)
64  const share = (m: Model) => Math.exp(score[m]) / total
65  if (input.current && input.current !== model && share(model) - share(input.current) <= HYSTERESIS) model = input.current
66  const effort: Effort =
67    model === 'haiku' ? 'low'
68    : model === 'sonnet' ? (score.sonnet >= 2 ? 'medium' : 'low')
69    : DEEP.test(text) || input.subagentType === 'Plan' ? 'xhigh'
70    : heavy >= 2 ? 'high'
71    : 'medium'
72  // Confidence from the margin over the runner-up, kept to 0.50–0.99
73  const margin = (top?.[1] ?? 0) - (second?.[1] ?? 0)
74  const conf = Math.min(0.99, Math.max(0.5, 0.5 + 0.5 * (1 - Math.exp(-margin))))
75
76  return { model, effort, conf: Math.round(conf * 100) / 100 }
77}
78
79// The effort for a tier chosen by something other than pickRoute (Jev): the same ladder, without the scores
80export function effortFor(model: Model, text: string, subagentType?: string): Effort {
81  if (model === 'haiku') return 'low'
82  if (model === 'sonnet') return 'medium'
83  return DEEP.test(text) || subagentType === 'Plan' ? 'xhigh' : 'high'
84}
85
86// The signals behind a pick, as the band's dim second line: “excerpt” · kw:debug · len 212 · tools Bash·Edit
87export function whyOf(input: RouteInput): string {
88  const kw = (input.text.match(HEAVY) ?? input.text.match(MID) ?? input.text.match(LIGHT) ?? [])[0]?.toLowerCase()
89  const excerpt = input.text.replace(/\s+/g, ' ').trim().slice(0, 40)
90  const tools = [...new Set(input.tools)].slice(-3)
91  return [
92    excerpt ? `“${excerpt}${input.text.length > 40 ? '…' : ''}”` : '',
93    input.subagentType ? `agent:${input.subagentType}` : '',
94    kw ? `kw:${kw}` : '',
95    `len ${input.text.length}`,
96    tools.length > 0 ? `tools ${tools.join('·')}` : 'no tools',
97  ]
98    .filter(Boolean)
99    .join(' · ')
100}
101
hooks/lists.ts 57 lines
1import type { Agent, McpUse, SkillUse, Task, Usage } from '../types'
2
3// Pure list and value helpers the hooks use. No mods API calls here.
4
5// The session usage the engine reports, in ClaudeRouter's shape
6export type RawUsage = {
7  startedAt: number
8  context: { tokens?: number; window: number; percent?: number }
9  rateLimits: { kind: string; percentUsed: number; resetsAt?: string }[]
10  cost?: { usd: number }
11}
12
13export function toUsage(raw: RawUsage): Usage {
14  return {
15    startedAt: raw.startedAt,
16    context: { tokens: raw.context.tokens ?? null, window: raw.context.window, percent: raw.context.percent ?? null },
17    rateLimits: raw.rateLimits.map(r => ({ kind: r.kind, percentUsed: r.percentUsed, resetsAt: r.resetsAt ?? null })),
18    cost: raw.cost?.usd ?? null,
19  }
20}
21
22// A task's name is its prompt, shortened to one line
23export function nameOf(text: string): string {
24  return text.replace(/\s+/g, ' ').trim().slice(0, 60) || 'prompt'
25}
26
27export function bumpSkill(list: SkillUse[], name: string): SkillUse[] {
28  const hit = list.find(s => s.name === name)
29  if (!hit) return [...list.slice(-7), { name, uses: 1 }]
30  return list.map(s => (s === hit ? { ...s, uses: s.uses + 1 } : s))
31}
32
33export function bumpMcp(list: McpUse[], server: string, tool: string): McpUse[] {
34  const hit = list.find(m => m.server === server && m.tool === tool)
35  if (!hit) return [...list.slice(-7), { server, tool, calls: 1 }]
36  return list.map(m => (m === hit ? { ...m, calls: m.calls + 1 } : m))
37}
38
39export function addPlugin(list: string[], name: string): string[] {
40  return list.includes(name) ? list : [...list, name]
41}
42
43export function attachAgent(list: Task[], taskId: string, agent: Agent): Task[] {
44  return list.map(t => (t.id === taskId ? { ...t, agents: [...t.agents, agent] } : t))
45}
46
47export function patchAgent(list: Task[], agentId: string, patch: Partial<Agent>): Task[] {
48  return list.map(t => ({
49    ...t,
50    agents: t.agents.map(a => (a.id === agentId ? { ...a, ...patch } : a)),
51  }))
52}
53
54export function patchTask(list: Task[], taskId: string, patch: Partial<Task>): Task[] {
55  return list.map(t => (t.id === taskId ? { ...t, ...patch } : t))
56}
57
hooks/format.ts 22 lines
1// Compact figures for ClaudeRouter: 124k, 1.0M, 1:02
2
3export function fmtTokens(n: number | null | undefined): string {
4  if (n === null || n === undefined) return '—'
5  if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`
6  if (n >= 1000) return `${Math.round(n / 1000)}k`
7  return String(n)
8}
9
10export function fmtTime(seconds: number): string {
11  const s = Math.max(0, Math.round(seconds))
12  return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`
13}
14
15export function fmtFit(text: string, n: number): string {
16  return text.length <= n ? text : `${text.slice(0, n - 1)}…`
17}
18
19export function fmtPct(p: number | null | undefined): string {
20  return p === null || p === undefined ? '—' : `${Math.round(p)}%`
21}
22
types/index.d.ts 93 lines
1// The state contract: every value ClaudeRouter keeps in $.state, declared under the mod's name
2
3export type Model = 'haiku' | 'sonnet' | 'opus'
4export type Effort = 'low' | 'medium' | 'high' | 'xhigh'
5// Who picks the tier: the local keyword rules, or Jev (falls back to the rules when it is unreachable)
6export type Engine = 'rules' | 'jev'
7
8// The user's switches, set with /clauderouter. warmUntil is a clock time in ms; 0 means keep-warm is off.
9// pin/pinEffort: a model (and effort) forced on every main-thread request; null = the router decides.
10// maxEffort: the highest effort the router may pick by itself. budget: USD one turn may spend before it is
11// downgraded (0 = off). ctxCap: context tokens above which requests are downgraded (0 = off).
12export type Options = {
13  engine: Engine
14  warmUntil: number
15  pin: Model | null
16  pinEffort: Effort | null
17  maxEffort: Effort
18  budget: number
19  ctxCap: number
20}
21
22// The latest routing decision, for the main conversation or one subagent request
23export type Route = {
24  model: Model
25  effort: Effort
26  conf: number
27  kept: boolean
28  // Who made the pick; 'rules' also when Jev was asked and failed
29  by: Engine
30  engineModel: string
31  source: 'main' | 'subagent'
32  // The signals it was picked on, for the band's second line
33  why: string
34}
35
36// A subagent of a task; its tokens and seconds arrive with its own turn.complete
37export type Agent = {
38  id: string | null
39  name: string
40  // The mascot it wears, from its type and task: scout, builder, researcher or planner
41  role: 'scout' | 'builder' | 'researcher' | 'planner'
42  model: string | null
43  effort: Effort | null
44  status: 'running' | 'done' | 'failed'
45  startedAt: number
46  seconds: number | null
47  tokens: number
48}
49
50// One user turn. There is no total for it, so its bar shimmers until it ends.
51// Its model and effort are the router's latest pick for it; its tokens arrive with turn.complete.
52export type Task = {
53  id: string
54  name: string
55  status: 'running' | 'done' | 'failed'
56  startedAt: number
57  seconds: number | null
58  steps: number
59  model: Model | null
60  effort: Effort | null
61  tokens: number | null
62  agents: Agent[]
63}
64
65// What Jev has cost this session: calls made, and the last call's tokens against its 64k window
66export type JevUse = { calls: number; input: number; output: number }
67
68export type SkillUse = { name: string; uses: number }
69export type McpUse = { server: string; tool: string; calls: number }
70
71export type Usage = {
72  startedAt: number
73  context: { tokens: number | null; window: number; percent: number | null }
74  rateLimits: { kind: string; percentUsed: number; resetsAt: string | null }[]
75  cost: number | null
76}
77
78declare module 'claude-code' {
79  interface PluginState {
80    'agent-ClaudeRouter': {
81      route: Route | null
82      tasks: Task[]
83      skills: SkillUse[]
84      mcp: McpUse[]
85      plugins: string[]
86      usage: Usage | null
87      options: Options
88      jev: JevUse | null
89      totals: { tokens: number; turns: number }
90    }
91  }
92}
93