@alexeiled/claude-router 1.8.0 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,12 @@
1
- <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 657 1123" role="img" aria-labelledby="title desc">
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 657 1180" role="img" aria-labelledby="title desc">
2
2
  <title id="title">Router pane, Usage tab</title>
3
3
  <desc id="desc">Routing vs your model first: routed replies against the same tokens on your model, Opus 5.5 at xhigh this session and each session’s own model since the last reset, the difference split into cheaper models, stronger models and switch cache writes, the session against the other models, the two costs as bars and the replies by tier; then Claude’s own readings, activity counts with their estimated cost and route, the counts across sessions, and estimates.</desc>
4
4
  <style>
5
5
  text { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, 'Liberation Mono', monospace; font-size: 13px; }
6
6
  .cap { font-family: system-ui, -apple-system, 'Segoe UI', sans-serif; font-size: 12px; fill: #9a988f; }
7
7
  </style>
8
- <rect width="657" height="1123" rx="8" fill="#1c1c1c"/>
9
- <rect x="10" y="10" width="637" height="1103" rx="6" fill="none" stroke="#3f5f8f"/>
8
+ <rect width="657" height="1180" rx="8" fill="#1c1c1c"/>
9
+ <rect x="10" y="10" width="637" height="1160" rx="6" fill="none" stroke="#3f5f8f"/>
10
10
  <text x="24.0" y="34" fill="#5fafd7" font-weight="700" xml:space="preserve">ROUTING</text>
11
11
  <rect x="94.2" y="20" width="62.4" height="18" rx="4" fill="#87afff"/>
12
12
  <text x="94.2" y="34" fill="#0d1016" font-weight="700" xml:space="preserve">[ ◉ on ]</text>
@@ -126,10 +126,13 @@
126
126
  <rect x="24.0" y="970" width="117.0" height="18" rx="4" fill="#2e3340"/>
127
127
  <text x="24.0" y="984" fill="#d0d0d0" xml:space="preserve">[ Reset stats ]</text>
128
128
  <text x="141.0" y="984" fill="#7c7c7c" xml:space="preserve"> clears activity stats and routing vs your model, all sessions</text>
129
- <text x="24.0" y="1022" fill="#5fafd7" font-weight="700" xml:space="preserve">ESTIMATES · configured list prices</text>
130
- <text x="24.0" y="1041" fill="#d0d0d0" xml:space="preserve">Cache hits saved $1.522</text>
131
- <text x="24.0" y="1060" fill="#d0d0d0" xml:space="preserve">Switch cost $0.476</text>
132
- <text x="24.0" y="1079" fill="#7c7c7c" xml:space="preserve">Press ? for what these estimates leave out.</text>
133
- <rect x="24.0" y="1084" width="70.2" height="18" rx="4" fill="#2e3340"/>
134
- <text x="24.0" y="1098" fill="#d0d0d0" xml:space="preserve">[ Close ]</text>
129
+ <text x="24.0" y="1022" fill="#5fafd7" font-weight="700" xml:space="preserve">SUBAGENTS · across sessions</text>
130
+ <text x="234.6" y="1022" fill="#7c7c7c" xml:space="preserve"> subagent routing on</text>
131
+ <text x="24.0" y="1041" fill="#7c7c7c" xml:space="preserve"> no subagents yet</text>
132
+ <text x="24.0" y="1079" fill="#5fafd7" font-weight="700" xml:space="preserve">ESTIMATES · configured list prices</text>
133
+ <text x="24.0" y="1098" fill="#d0d0d0" xml:space="preserve">Cache hits saved $1.522</text>
134
+ <text x="24.0" y="1117" fill="#d0d0d0" xml:space="preserve">Switch cost $0.476</text>
135
+ <text x="24.0" y="1136" fill="#7c7c7c" xml:space="preserve">Press ? for what these estimates leave out.</text>
136
+ <rect x="24.0" y="1141" width="70.2" height="18" rx="4" fill="#2e3340"/>
137
+ <text x="24.0" y="1155" fill="#d0d0d0" xml:space="preserve">[ Close ]</text>
135
138
  </svg>
@@ -37,8 +37,8 @@ Router draws one line above the prompt. The line ends with a **Router** button t
37
37
  Read the first line of the picture from left to right:
38
38
 
39
39
  - **Tier meter** `▂▄▆█`: one bar per tier, lit up to the current tier in its color, like signal strength.
40
- - **Tier, activity, and model**: the route for this turn. The activity, such as `code →`, sits between the tier and the model; see [Route by activity](#route-by-activity). **fallback** means Claude Code answered with another model.
41
- - **Reason**: one or two words with a direction, such as `↑ jump`, `↓ downgrade`, `= fits`, or `… waiting to go down`. An activity move reads `↗ code` or `↘ ops`, and a refused one `… ops: not worth a switch`.
40
+ - **Tier, activity, and model**: the route for this turn. The activity sits between the tier and the model as a verb in orange italic, such as `coding →`: `coding`, `debugging`, `exploring`, `planning`, `reviewing`, `running` (commands: git, builds, tests, CI) or `documenting`. See [Route by activity](#route-by-activity). **fallback** means Claude Code answered with another model.
41
+ - **Reason**: one or two words with a direction, such as `↑ jump`, `↓ downgrade`, `= fits`, or `… waiting to go down`. An activity move reads `↗ coding` or `↘ running`, and a refused one `… running: not worth a switch`.
42
42
  - **Classifier support**: what the active classifier, such as Jev or Clef Flash, gave the switch against the bar the policy required, such as `Jev 88% ≥ 82%`. When whole percents would read as equal, it shows tenths: `Jev 81.0% < 81.4%`.
43
43
  - **Switch cost**: `switch cost ≈ $0.37`, the policy's price for the switch it weighed this turn, mostly the prompt cache the other model must write. For a move to a cheaper model it is net of what that model saves over the next turns. The higher the cost, the higher the bar a stronger model must clear.
44
44
  - **ctx** and **cache hit**: context use and the share of input read from the cache on the last reply. They turn yellow at 60% context and red at 80%.
@@ -53,13 +53,13 @@ Read the first line of the picture from left to right:
53
53
  | `⚠ Jev timed out · keeping model` | The classifier failed: timed out, unreachable, rejected the key, or paused. |
54
54
  | `○ Routing off [ Turn on ] · every turn uses …` | Routing is off: Claude's model answers every turn. **Turn on** turns it back on. The footer also shows `routing off`. |
55
55
  | `✕ Routing unavailable` | Nothing routes: an old Claude Code or leftover v0.8 settings. **Fix** opens the pane. |
56
- | `○ Router · subagents keep their own model` | You are viewing a subagent's transcript, which Router does not route. |
56
+ | `○ Router · subagents keep their own model` | You are viewing a subagent's transcript. Its steps are not routed; in `on` the band reads `subagent model chosen at spawn`. |
57
57
 
58
58
  The band shows one routing control at a time. While routing is on, hover over the band for a second row: pin a tier for the next turn, **Turn off** routing, or show two rows. While routing is off, **Turn on** sits on the first line next to `Routing off` and stays at any width: a narrow band drops the explanation and the model first. On a narrow band the hover row drops `routing on`, then **2 rows**, then `pin next turn`, then the pins; it keeps **Turn off**, and **1 row** when the band shows two. The hover row needs a pointer: from the keyboard, run `/router off`, or open the pane and press `f`. The two-row band adds this session against your model, the one `/model` selects now: `session saved $1.84 (22%) vs Opus 5.5 · xhigh · 64 replies · cold-cache writes +$0.47`, or `session extra $2.48 (×5.0) vs Haiku 5.5 · high · 41 replies · stronger models +$2.31` when routing cost more. The last part names the larger of the two costs behind the result, when there is one. After a `/model` change the row shows the whole session against the new model. Before the tenth routed reply it reads `session 3 replies · too early to compare`. When the row is short, the cost part drops first, then the reply count. Router remembers that choice across sessions. When Router changes the model between turns, a toast reads `Model changed: old → new · reason`. A pin does not raise one, and neither does a change of effort alone.
59
59
 
60
60
  The band steps aside while a survey needs the space.
61
61
 
62
- Tool continuations do not trigger another classification. Subagent choices remain unchanged.
62
+ Tool continuations do not trigger another classification. A subagent gets at most one model, when it starts, and keeps it for every step: Haiku for exploration, Opus for clearly hard tasks, Sonnet for the rest. An agent that pins a model in its definition keeps it, unless it sets `modelRouting: auto`. The Usage tab's **SUBAGENTS** section shows what each agent type ran on and cost. See [Subagent routing](configuration.md#subagent-routing).
63
63
 
64
64
  ## Open the router pane
65
65
 
@@ -166,7 +166,7 @@ The band's activity label appears only when the activity applies, so a weak or `
166
166
  ### Read the activity on the pane
167
167
 
168
168
  - **Now**: the **Activity** line names the classifier's choice with its share and the two next-best answers, such as `code 84% debug 8% · plan 5%`. In `on`, **Why** names the cell when the activity moved the route or the route is an override, such as `code at low runs on Sonnet 5.5 · high`, or `low runs on its base route, Haiku 5.5 · high` for a move without an activity; a refused move, a hold, or a tier change keeps its reason. The **Route** line shows the route the cell resolves to. **Replies** has a letter row under the strip.
169
- - **Routing**: **ACTIVITIES** starts with the **Activity routing** selector (`off`, `shadow`, `on`) and what the mode does. The matrix under it shows the effective routes per tier, with `·` where a cell uses the base route, and counts the distinct routes, because the router counts each as its own cache. Routes are abbreviated, such as `S·high` for Sonnet · high, and activities with the same cells share a row. **OVERRIDES** says whether the overrides are in use, then lists each override with a model, an effort, and **remove**, plus a selector to add one. **Activity threshold** under **POLICY** is the least probability at which an activity applies. Edits join the routing draft: **Save** and **Discard** apply as for routes. Yellow notes flag an override with no effect (`same as base`), one stronger than the tier above, and the only cell or tier on its (model, effort) pair, which adds a cache.
169
+ - **Routing**: **ACTIVITIES** starts with the **Activity routing** selector (`off`, `shadow`, `on`) and what the mode does. The matrix under it shows the effective routes per tier, with `·` where a cell uses the base route, and counts the distinct routes and the caches they use. Routes are abbreviated, such as `S·high` for Sonnet · high, and activities with the same cells share a row. **OVERRIDES** says whether the overrides are in use, then lists each override with a model, an effort, and **remove**, plus a selector to add one. **Activity threshold** under **POLICY** is the least probability at which an activity applies. Edits join the routing draft: **Save** and **Discard** apply as for routes. Yellow notes flag an override with no effect (`same as base`), one stronger than the tier above, and the only cell or tier on its cache, which adds one.
170
170
  - **Usage**: **ACTIVITY · this session** lists turns, requests, and share per activity, then `est. cost`, the list price of that activity's replies (the same per-reply estimate as Routing vs your model, but only for turns recorded with activity routing `shadow` or `on`, so the rows need not add up to its routed total; `—` when a reply had no price), and `mostly on`, the route most of its replies used, such as `Sonnet 5.5 · high`. A narrow pane drops `mostly on`, then `est. cost`. Below the table are the switches split by tier and by activity, with `· 2 refused` when activity moves were refused in `on` (not worth the cache write, a hold after an escalation, or the credits cap), and **Agreement**, how often the tools a turn used fit the classifier's activity (see [Evaluation](evaluation.md#tool-agreement)). In `shadow` the **Shadow** line counts how many turns `on` would have routed differently, such as `on would route 5 of 20 turns differently · est. −$0.300 … −$0.120 at list prices`. The estimate sums, over those turns, what the next request on the route `on` would use would cost against the route that ran, as a low and a high scenario at the configured list prices in `router.json`. Minus means cheaper. It covers only turns after a measured reply, and adds `for 3` when only three of the turns have one. It is not a measured saving.
171
171
 
172
172
  **ACROSS SESSIONS · since the last reset** shows the counts kept across sessions: the turns labelled from their tools, **Agreement** over them, **Code/ops/explore**, the same agreement over the turns the classifier answered `code`, `ops` or `explore` (omitted when there are none), the two most frequent mismatches as `predicted → observed count` (`code → read 3`), **Activity moves**, the moves to another route inside a tier, taken and refused for any reason, **Escalations**, such as `after a cheaper activity move: 1 in 12 moves`, the tool-error escalations that followed a move to a cheaper route in `on` while the turns stayed on it in `on` (turning routing off, a turn with routing off, or a turn in `shadow` or `off` ends the watch, a pin in between does not, and an escalation the credits cap held counts), **Latency**, the active classifier's p95 wait as a bucket bound such as `Jev p95 ≤ 350 ms · 20 turns` (not recorded with activity routing `off`), and the **Shadow** line summed over all shadow turns. Each of these lines appears only when it has data. This agreement compares the classifier's raw answer, so it can differ from the session's. The pane reads these counts when the session starts and when it opens, and adds this session's turns as they finish; another session's new latency and escalation readings show the next time the pane opens. **Reset stats** clears the activity counts and routing vs your model, for this session and across sessions.
@@ -21,6 +21,7 @@ import { resolveCredentials } from '../lib/classifier-contract.mjs';
21
21
  import {
22
22
  ACTIVITY_MODES,
23
23
  activeClassifier,
24
+ CLASSIFY,
24
25
  DEFAULTS,
25
26
  editActivity,
26
27
  effectiveActivities,
@@ -79,7 +80,27 @@ import {
79
80
  SAVINGS_PREFIX,
80
81
  SAVINGS_RESET_KEY,
81
82
  sessionCacheTtl,
83
+ subagentCacheTtl,
82
84
  } from '../lib/savings.mjs';
85
+ import {
86
+ addAgentReply,
87
+ agentFrontmatter,
88
+ classifiedAlias,
89
+ coreModelOf,
90
+ emptySubagentStore,
91
+ flushedAgent,
92
+ mergeSubagentStores,
93
+ passReason,
94
+ RESPAWN_WINDOW_MS,
95
+ readSubagentStore,
96
+ recordAgent,
97
+ SPAWN_DEADLINE_MS,
98
+ SUBAGENT_PREFIX,
99
+ spawnPrompt,
100
+ spawnRecord,
101
+ subagentsAfterReset,
102
+ typeRoute,
103
+ } from '../lib/subagents.mjs';
83
104
  import { CLEARED_READINGS, continuationView, healthOf, initialView, responseMetrics } from '../lib/view.mjs';
84
105
 
85
106
  // The engine follows $ only into functions declared in this file, never across an import: every helper that takes $
@@ -91,6 +112,7 @@ const PANE = 'jev-router';
91
112
  const PANE_TITLE = 'Router';
92
113
  const BAND_DETAIL = 'band:detail';
93
114
  const MODE_PREFIX = 'mode:';
115
+ const isSet = (value) => /^(1|true|yes|on)$/i.test(String(value ?? '').trim());
94
116
 
95
117
  // Everything the hooks change between events, in one object `register()` creates and passes to its helpers. Module
96
118
  // variables, not $.state: a reload starts them over, and the view is written through to $.state as it changes.
@@ -129,6 +151,14 @@ function createRouter(options) {
129
151
  metricsOthers: null,
130
152
  // Bumped by Reset activity stats, so a store write that read the counts before the reset skips.
131
153
  statsResets: 0,
154
+ // Each spawned agent's record by agentId (spawnRecord), and when each parent loop last finished an agent of a type,
155
+ // for respawns. The subagent totals kept across sessions, held as the savings records are.
156
+ agents: new Map(),
157
+ finished: new Map(),
158
+ // Each agent type's definition frontmatter by provider and type, read once per session (agentDefinition).
159
+ definitions: new Map(),
160
+ subagentsOwn: null,
161
+ subagentsOthers: null,
132
162
  };
133
163
  }
134
164
 
@@ -231,6 +261,32 @@ async function otherMetrics($, sessionId, resetAt) {
231
261
  return mergeMetrics(await Promise.all(keys.map((key) => $.store.get(key))), resetAt);
232
262
  }
233
263
 
264
+ // This session's subagent record and the last reset, as ownSavings: Reset stats clears it with the same marker.
265
+ async function ownSubagents($, router) {
266
+ const sessionId = await $.session.id();
267
+ const resetAt = await $.store.get(SAVINGS_RESET_KEY);
268
+ if (router.subagentsOwn?.sessionId !== sessionId) {
269
+ const record = readSubagentStore(await $.store.get(`${SUBAGENT_PREFIX}${sessionId}`));
270
+ if (router.subagentsOwn?.sessionId !== sessionId) router.subagentsOwn = { sessionId, record };
271
+ }
272
+ router.subagentsOwn.record = subagentsAfterReset(router.subagentsOwn.record, resetAt);
273
+ return { own: router.subagentsOwn, resetAt };
274
+ }
275
+
276
+ // Every other session's subagent record since the last reset, added up.
277
+ async function otherSubagents($, sessionId, resetAt) {
278
+ const own = `${SUBAGENT_PREFIX}${sessionId}`;
279
+ const keys = (await $.store.keys()).filter((key) => key.startsWith(SUBAGENT_PREFIX) && key !== own);
280
+ return mergeSubagentStores(await Promise.all(keys.map((key) => $.store.get(key))), resetAt);
281
+ }
282
+
283
+ // The view's subagent totals, this session's and the others', from what the router holds; nothing until a read
284
+ // succeeded.
285
+ const subagentView = (router) =>
286
+ router.subagentsOthers
287
+ ? { subagentStore: mergeSubagentStores([router.subagentsOthers, router.subagentsOwn?.record]) }
288
+ : {};
289
+
234
290
  const metricsView = (router) => mergeMetrics([router.metricsOthers, router.metricsOwn?.record]);
235
291
 
236
292
  // The view's totals kept across sessions, from what the router holds; nothing until a read succeeded.
@@ -254,6 +310,11 @@ async function storeView($, router) {
254
310
  const { own, resetAt } = await ownSavings($, router);
255
311
  router.savingsOthers = await otherSavings($, own.sessionId, resetAt);
256
312
  } catch {}
313
+ try {
314
+ const { own, resetAt } = await ownSubagents($, router);
315
+ router.subagentsOthers = await otherSubagents($, own.sessionId, resetAt);
316
+ Object.assign(out, subagentView(router));
317
+ } catch {}
257
318
  return out;
258
319
  }
259
320
 
@@ -371,6 +432,19 @@ function openKeySettings($) {
371
432
  $.clock.after(0, () => $.command.run({ command: 'plugin', args: `configure ${$.plugin.name}` }).catch(() => {}));
372
433
  }
373
434
 
435
+ // Whether this session's provider gives each effort its own prompt cache (effortSharesCache in lib/cost.mjs): Amazon
436
+ // Bedrock, Google Cloud, Microsoft Foundry, a custom ANTHROPIC_BASE_URL (it may be a Claude apps gateway) or
437
+ // CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS. A HIPAA configuration is not visible to a Mod. $.env.get takes literal names.
438
+ async function effortSplitsCacheOf($) {
439
+ const flags = [
440
+ await $.env.get('CLAUDE_CODE_USE_BEDROCK'),
441
+ await $.env.get('CLAUDE_CODE_USE_VERTEX'),
442
+ await $.env.get('CLAUDE_CODE_USE_FOUNDRY'),
443
+ await $.env.get('CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS'),
444
+ ];
445
+ return flags.some(isSet) || Boolean(await $.env.get('ANTHROPIC_BASE_URL'));
446
+ }
447
+
374
448
  async function loadNativeConfig($) {
375
449
  for (const source of ['project', 'local']) {
376
450
  const settings = await $.settings.read({ source });
@@ -381,7 +455,7 @@ async function loadNativeConfig($) {
381
455
  const profile = (await $.env.get('CLAUDE_CONFIG_DIR')) ?? `${home}/.claude`;
382
456
  const path = `${profile}/router.json`;
383
457
  const userFile = (await $.fs.exists(path)) ? JSON.parse(await $.fs.read(path)) : null;
384
- return { ...loadConfig({ userFile }), nativePath: path };
458
+ return { ...loadConfig({ userFile }), nativePath: path, effortSplitsCache: await effortSplitsCacheOf($) };
385
459
  }
386
460
 
387
461
  // Writes router.json through `change(previousFile)` once the result validates. Returns the new config or an error
@@ -392,7 +466,7 @@ async function saveConfig($, path, change) {
392
466
  return { error: 'Not saved: router.json is a symlink. Edit its maintained source instead.' };
393
467
  const { config, text } = rewrittenConfig((await $.fs.exists(path)) ? await $.fs.read(path) : null, change);
394
468
  await $.fs.write(path, text);
395
- return { config: { ...config, nativePath: path } };
469
+ return { config: { ...config, nativePath: path, effortSplitsCache: await effortSplitsCacheOf($) } };
396
470
  } catch (error) {
397
471
  return { error: notSaved(error) };
398
472
  }
@@ -456,7 +530,7 @@ async function* passMain($, e, next, loop, version, nativeModel, reason, router)
456
530
  const sessionId = await $.session.id();
457
531
  const response = yield* next(e);
458
532
  if (!next.signal.aborted && (await $.session.id()) === sessionId) {
459
- const observed = observeResponse(loop, {
533
+ const observed = observeResponse(router.config, loop, {
460
534
  usage: response.usage,
461
535
  requestedModel: e.model,
462
536
  effort: e.effort ?? null,
@@ -616,7 +690,7 @@ async function publishReply($, router, turnId, response, tier, route, routedUsd)
616
690
  // A routed reply written to the loop at `loopVersion`, then published: the view's metrics and the routing-vs-your-model
617
691
  // totals. A lost write publishes nothing.
618
692
  async function observeRouted($, router, { turnId, cfg, loop, loopVersion, request, response, nativeModel }) {
619
- const observed = observeResponse(loop, {
693
+ const observed = observeResponse(cfg, loop, {
620
694
  usage: response.usage,
621
695
  requestedModel: request.model,
622
696
  effort: request.effort ?? null,
@@ -789,6 +863,210 @@ async function flushRun($, run) {
789
863
  } catch {}
790
864
  }
791
865
 
866
+ // The frontmatter of the agent file a spawn starts (agentFrontmatter), or null when it cannot be found or read. Read
867
+ // once per provider and type in a session, and never for a built-in, whose definition is not on disk.
868
+ async function agentDefinition($, router, e) {
869
+ const plugin = e.provider?.plugin;
870
+ if (typeof plugin !== 'string' || plugin === 'engine' || typeof e.subagentType !== 'string') return null;
871
+ const key = `${plugin} ${e.subagentType}`;
872
+ if (!router.definitions.has(key)) router.definitions.set(key, await findDefinition($, plugin, e.subagentType));
873
+ return router.definitions.get(key);
874
+ }
875
+
876
+ // A plugin agent (provider `plugin@marketplace`) is looked up under each install path installed_plugins.json gives
877
+ // that plugin, the files Claude Code itself loads; any other agent under the session's .claude/agents, then the
878
+ // profile's agents. Every match must agree on the model, or the definition is unknown. Limit: a plugin that keeps its
879
+ // agents outside `agents/` reads as unknown, so its agents pass through.
880
+ async function findDefinition($, plugin, type) {
881
+ try {
882
+ const home = await $.env.get('HOME');
883
+ const profile = (await $.env.get('CLAUDE_CONFIG_DIR')) ?? `${home}/.claude`;
884
+ const name = type.slice(type.indexOf(':') + 1);
885
+ const fromPlugin = plugin.includes('@');
886
+ const dirs = fromPlugin
887
+ ? (JSON.parse(await $.fs.read(`${profile}/plugins/installed_plugins.json`)).plugins?.[plugin] ?? []).map(
888
+ (entry) => `${entry.installPath}/agents`,
889
+ )
890
+ : [`${await $.session.cwd()}/.claude/agents`, `${profile}/agents`];
891
+ const found = [];
892
+ for (const dir of dirs) {
893
+ if (!(await $.fs.exists(dir))) continue;
894
+ for (const entry of await $.fs.list(dir)) {
895
+ if (entry.kind === 'dir' || !entry.name.endsWith('.md')) continue;
896
+ const definition = agentFrontmatter(await $.fs.read(`${dir}/${entry.name}`));
897
+ if (definition && (definition.name ?? entry.name.slice(0, -3)) === name) found.push(definition);
898
+ }
899
+ // A project agent replaces a user agent of the same name.
900
+ if (found.length && !fromPlugin) break;
901
+ }
902
+ const agree = found.every((d) => d.model === found[0].model && d.modelRouting === found[0].modelRouting);
903
+ return found.length && agree ? found[0] : null;
904
+ } catch {
905
+ return null;
906
+ }
907
+ }
908
+
909
+ // The spawn path's classifier client: a breaker of its own, so spawn failures never pause main-turn routing, and no
910
+ // in-flight slot, so a parent that spawns several agents at once gets an answer for each.
911
+ function spawnClientOf(router, id) {
912
+ const key = `spawn:${id}`;
913
+ if (!router.clients.has(key)) router.clients.set(key, new ClassifierClient({ exclusive: false }));
914
+ return router.clients.get(key);
915
+ }
916
+
917
+ // A listed spawn's model: the models key its type names, or the classifier's pick for a `classify` type from the task
918
+ // text alone. `choice: 'core'` keeps core's model: no advice (`failed`), or a model availableModels blocks.
919
+ async function decideSpawn($, router, cfg, e, definition, signal) {
920
+ let alias = typeRoute(cfg, e, definition).route;
921
+ let failed = false;
922
+ if (alias === CLASSIFY) {
923
+ const entry = activeClassifier(cfg);
924
+ const credentials = await resolveCredentials(entry, (name) => settingOf($, router.options, name));
925
+ // The wait delays the subagent's start, so it is the classifier's deadline capped at SPAWN_DEADLINE_MS.
926
+ const timeoutMs = Math.min(entry.timeoutMs, SPAWN_DEADLINE_MS);
927
+ const result = await spawnClientOf(router, cfg.classifier).ask({
928
+ request: (url, init) => $.http.fetch(url, init),
929
+ sleep: (ms, args) => $.clock.sleep(ms, args),
930
+ config: { ...cfg, classifiers: { ...cfg.classifiers, [cfg.classifier]: { ...entry, timeoutMs } } },
931
+ apiKey: credentials.apiKey,
932
+ endpoint: credentials.endpoint,
933
+ prompt: spawnPrompt(cfg, e),
934
+ turns: [],
935
+ signal,
936
+ });
937
+ alias = classifiedAlias(cfg, result.advice);
938
+ failed = !result.advice;
939
+ }
940
+ // The full id, not an alias: a family alias would resolve to the parent's exact model when the families match.
941
+ const model = alias ? cfg.models[alias].id : null;
942
+ const settings = await $.settings.read().catch(() => ({}));
943
+ if (!model || !isModelAllowed(model, settings.availableModels, e.parentModel))
944
+ return { choice: 'core', model: null, failed };
945
+ return { choice: alias, model, failed };
946
+ }
947
+
948
+ // One model per subagent, chosen before its cache exists. `on` waits for the decision and sends its model, which
949
+ // Claude Code uses in place of the Agent call's `model` and the agent's frontmatter. `shadow` spawns as Claude Code
950
+ // would at once and records the decision once it is in, so it never delays an agent's start. Routing off or
951
+ // unavailable keeps every model Claude Code chooses, and records nothing.
952
+ async function spawnAgent($, router, e, next) {
953
+ const cfg = router.config;
954
+ const mode = cfg.subagentRouting;
955
+ if (mode === 'off') return next(e);
956
+ const view = router.view ?? (await readView($, router));
957
+ if (view.phase === 'unavailable' || (await modeOf($, router, view.mode)) === 'manual') return next(e);
958
+ const definition = await agentDefinition($, router, e);
959
+ const pass = passReason(cfg, e, definition);
960
+ const deciding = pass ? null : decideSpawn($, router, cfg, e, definition, next.signal).catch(() => null);
961
+ const decided = mode === 'on' ? await deciding : null;
962
+ const routed = Boolean(decided?.model);
963
+ const result = await next(routed ? { ...e, model: decided.model } : e);
964
+ if (!result.agentId) return result;
965
+ // In shadow the agent may reply, and even finish, before the decision lands: a pending entry keeps its replies.
966
+ if (mode !== 'on' && deciding !== null)
967
+ router.agents.set(result.agentId, { pending: true, usages: [], finished: false });
968
+ try {
969
+ const decision = mode === 'on' ? decided : await deciding;
970
+ if (pass || decision) await noteSpawn($, router, { cfg, mode, e, pass, decision, routed, result, definition });
971
+ else router.agents.delete(result.agentId);
972
+ } catch {
973
+ if (router.agents.get(result.agentId)?.pending) router.agents.delete(result.agentId);
974
+ }
975
+ return result;
976
+ }
977
+
978
+ // The spawn's record, kept until the session ends. In `on` core's model is an estimate (coreModelOf); otherwise it is
979
+ // the model the agent started on.
980
+ async function noteSpawn($, router, { cfg, mode, e, pass, decision, routed, result, definition }) {
981
+ const parentKey = `${e.parentAgentId ?? 'main'} ${e.subagentType}`;
982
+ const finishedAt = router.finished.get(parentKey);
983
+ const ttl = await subagentTtlOf($).catch(() => null);
984
+ const coreModel = routed
985
+ ? coreModelOf(cfg, e, {
986
+ envModel: await $.env.get('CLAUDE_CODE_SUBAGENT_MODEL'),
987
+ force: isSet(await $.env.get('CLAUDE_CODE_SUBAGENT_MODEL_FORCE')),
988
+ definition,
989
+ })
990
+ : result.model;
991
+ const record = spawnRecord({
992
+ sessionId: await $.session.id(),
993
+ mode,
994
+ spawn: e,
995
+ pass,
996
+ choice: decision?.choice ?? null,
997
+ routedModel: decision?.model ?? result.model,
998
+ coreModel,
999
+ failed: decision?.failed,
1000
+ respawn: Number.isFinite(finishedAt) && Date.now() - finishedAt < RESPAWN_WINDOW_MS,
1001
+ });
1002
+ // Read after the last await, so no reply lands in the pending entry after its replay.
1003
+ const pending = router.agents.get(result.agentId);
1004
+ const replies = pending?.pending ? pending.usages : [];
1005
+ router.agents.set(
1006
+ result.agentId,
1007
+ replies.reduce((agent, usage) => addAgentReply(cfg, agent, usage, ttl), { ...record, parentKey }),
1008
+ );
1009
+ if (pending?.finished) await finishAgent($, router, result.agentId);
1010
+ }
1011
+
1012
+ // A subagent's prompt-cache lifetime, by Claude Code's rule for requests outside the main conversation.
1013
+ async function subagentTtlOf($) {
1014
+ const settings = await $.settings.read();
1015
+ return subagentCacheTtl({
1016
+ force5m: await $.env.get('FORCE_PROMPT_CACHING_5M'),
1017
+ envTtl: await $.env.get('CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL'),
1018
+ settingTtl: settings.subagentPromptCacheTtl,
1019
+ enable1h: await $.env.get('ENABLE_PROMPT_CACHING_1H'),
1020
+ });
1021
+ }
1022
+
1023
+ // A subagent's step runs exactly as Claude Code sent it: a model switch between its steps would rewrite its context
1024
+ // cold. Its reply is added to its spawn record; the record never breaks the step.
1025
+ async function* stepAgent($, router, e, next) {
1026
+ const response = yield* next(e);
1027
+ if (router.agents.has(e.agentId) && response?.usage) {
1028
+ try {
1029
+ const ttl = await subagentTtlOf($);
1030
+ const agent = router.agents.get(e.agentId);
1031
+ if (agent?.pending) agent.usages.push(response.usage);
1032
+ else if (agent) router.agents.set(e.agentId, addAgentReply(router.config, agent, response.usage, ttl));
1033
+ } catch {}
1034
+ }
1035
+ return response;
1036
+ }
1037
+
1038
+ // A subagent's turn ended: its counts since the last flush go to this session's record kept across sessions.
1039
+ async function finishAgent($, router, agentId) {
1040
+ const agent = router.agents.get(agentId);
1041
+ if (!agent) return;
1042
+ // A pending agent is flushed when its decision lands (noteSpawn).
1043
+ if (agent.pending) {
1044
+ agent.finished = true;
1045
+ return;
1046
+ }
1047
+ router.finished.set(agent.parentKey, Date.now());
1048
+ router.agents.set(agentId, flushedAgent(agent));
1049
+ await flushSubagents($, router, [agent]);
1050
+ }
1051
+
1052
+ // Agents' counts added to this session's record, with the guard flushSavings uses: counts read before a reset are not
1053
+ // written back. Stats never break a turn: a failed read or write loses these counts.
1054
+ async function flushSubagents($, router, agents) {
1055
+ try {
1056
+ const resets = router.statsResets;
1057
+ const { own, resetAt } = await ownSubagents($, router);
1058
+ const mine = agents.filter((agent) => agent.sessionId === own.sessionId);
1059
+ if (!mine.length) return;
1060
+ if (!router.subagentsOthers || subagentsAfterReset(router.subagentsOthers, resetAt) !== router.subagentsOthers)
1061
+ router.subagentsOthers = await otherSubagents($, own.sessionId, resetAt);
1062
+ if (router.statsResets !== resets) return;
1063
+ const now = Date.now();
1064
+ own.record = mine.reduce((record, agent) => recordAgent(record, agent, now), own.record);
1065
+ await $.store.set(`${SUBAGENT_PREFIX}${own.sessionId}`, own.record);
1066
+ if (router.statsResets === resets) await updateView($, router, subagentView(router));
1067
+ } catch {}
1068
+ }
1069
+
792
1070
  // The pane's handlers. `view` is the view the pane was drawn from; a handler reads `router.view` first, which holds
793
1071
  // any press since.
794
1072
  function paneActions($, router, view) {
@@ -944,6 +1222,7 @@ function paneActions($, router, view) {
944
1222
  router.run = null;
945
1223
  router.afterDown = null;
946
1224
  router.turnSavings.clear();
1225
+ for (const [id, agent] of router.agents) if (!agent.pending) router.agents.set(id, flushedAgent(agent));
947
1226
  const clear = (key, value) =>
948
1227
  $.store
949
1228
  .set(key, value)
@@ -954,14 +1233,16 @@ function paneActions($, router, view) {
954
1233
  // Written first, so a session still holding its record from before the reset drops it, unless that record's
955
1234
  // first reading has the reset's millisecond or the clock moved back across the reset.
956
1235
  await $.store.set(SAVINGS_RESET_KEY, Date.now());
957
- const keys = (await $.store.keys()).filter(
958
- (key) => key.startsWith(SAVINGS_PREFIX) || key.startsWith(METRICS_PREFIX),
1236
+ const keys = (await $.store.keys()).filter((key) =>
1237
+ [SAVINGS_PREFIX, METRICS_PREFIX, SUBAGENT_PREFIX].some((prefix) => key.startsWith(prefix)),
959
1238
  );
960
1239
  await Promise.all(keys.map((key) => $.store.delete(key)));
961
1240
  router.savingsOwn = null;
962
1241
  router.savingsOthers = emptySavingsStore();
963
1242
  router.metricsOwn = null;
964
1243
  router.metricsOthers = emptyMetrics();
1244
+ router.subagentsOwn = null;
1245
+ router.subagentsOthers = emptySubagentStore();
965
1246
  return true;
966
1247
  };
967
1248
  const [stats, records] = await Promise.all([clear(STORE_KEY, emptyStore()), clearRecords().catch(() => false)]);
@@ -969,7 +1250,9 @@ function paneActions($, router, view) {
969
1250
  activityStats: null,
970
1251
  savingsBy: {},
971
1252
  ...(stats ? { activityStore: emptyStore() } : {}),
972
- ...(records ? { activityMetrics: emptyMetrics(), savingsStore: emptySavingsStore() } : {}),
1253
+ ...(records
1254
+ ? { activityMetrics: emptyMetrics(), savingsStore: emptySavingsStore(), subagentStore: emptySubagentStore() }
1255
+ : {}),
973
1256
  notice:
974
1257
  stats && records
975
1258
  ? 'Stats reset: activity and routing vs your model, this session and saved.'
@@ -1027,10 +1310,47 @@ function paneActions($, router, view) {
1027
1310
  };
1028
1311
  }
1029
1312
 
1313
+ // The session's turns, open run and running agents end with it; the view starts the next session from the counts kept
1314
+ // across sessions.
1315
+ async function endSession($, router) {
1316
+ for (const controller of router.controllers) controller.abort();
1317
+ router.decisions.clear();
1318
+ router.prompts.clear();
1319
+ router.turnConfigs.clear();
1320
+ router.turnActivities.clear();
1321
+ router.turnSavings.clear();
1322
+ const run = router.run;
1323
+ router.run = null;
1324
+ router.afterDown = null;
1325
+ if (run) await flushRun($, run);
1326
+ // Agents still running when the session ends: what they did so far is counted.
1327
+ const agents = [...router.agents.values()];
1328
+ router.agents.clear();
1329
+ router.finished.clear();
1330
+ await flushSubagents($, router, agents);
1331
+ router.view = {
1332
+ ...initialView(router.view?.nativeModel ?? ''),
1333
+ // The effort carries over /clear until the next turn reads it again, so "your model" keeps its effort.
1334
+ nativeEffort: router.view?.nativeEffort ?? null,
1335
+ mode: 'auto',
1336
+ credentials: router.view?.credentials ?? null,
1337
+ // Counts kept across sessions: the next session starts from them.
1338
+ activityStore: router.view?.activityStore ?? null,
1339
+ activityMetrics: router.view?.activityMetrics ?? null,
1340
+ savingsStore: router.view?.savingsStore ?? null,
1341
+ subagentStore: router.view?.subagentStore ?? null,
1342
+ health: healthOf(clientOf(router, router.config.classifier), router.config.classifier),
1343
+ configPath: router.config.nativePath,
1344
+ phase: router.view?.phase === 'unavailable' ? 'unavailable' : 'ready',
1345
+ error: router.view?.phase === 'unavailable' ? router.view.error : null,
1346
+ };
1347
+ }
1348
+
1030
1349
  export function register(on, options) {
1031
1350
  const router = createRouter(options);
1032
1351
 
1033
1352
  on('session.start', async ($, e, next) => {
1353
+ router.definitions.clear();
1034
1354
  await $.command.register({
1035
1355
  name: 'router',
1036
1356
  description: 'Open the Router pane, or switch routing: auto, off, pin <tier>, activities <mode>.',
@@ -1105,8 +1425,14 @@ export function register(on, options) {
1105
1425
  return next(e);
1106
1426
  });
1107
1427
 
1428
+ // A hook failure spawns the agent as Claude Code would; next(e) replays a spawn already made. agent.spawn and a
1429
+ // catchable on() are in the 2.1.293 build types, not checked on 2.1.289: an engine without them still loads routing.
1430
+ try {
1431
+ on('agent.spawn', ($, e, next) => spawnAgent($, router, e, next)).catch((_$, e, next) => next(e));
1432
+ } catch {}
1433
+
1108
1434
  on('turn.step', async function* ($, e, next) {
1109
- if (e.agentId) return yield* next(e);
1435
+ if (e.agentId) return yield* stepAgent($, router, e, next);
1110
1436
  const cfg = router.turnConfigs.get(e.turnId) ?? router.config;
1111
1437
  const sessionId = await $.session.id();
1112
1438
  const nativeModel = await $.session.model();
@@ -1179,6 +1505,10 @@ export function register(on, options) {
1179
1505
  });
1180
1506
 
1181
1507
  on('turn.complete', async ($, e, next) => {
1508
+ if (e.agentId) {
1509
+ await finishAgent($, router, e.agentId);
1510
+ return next(e);
1511
+ }
1182
1512
  router.turnConfigs.delete(e.turnId);
1183
1513
  router.turnControllers.get(e.turnId)?.abort();
1184
1514
  if (router.view?.activeTurnId === e.turnId && router.view.phase === 'choosing') {
@@ -1214,31 +1544,7 @@ export function register(on, options) {
1214
1544
  });
1215
1545
 
1216
1546
  on('session.end', async ($, e, next) => {
1217
- for (const controller of router.controllers) controller.abort();
1218
- router.decisions.clear();
1219
- router.prompts.clear();
1220
- router.turnConfigs.clear();
1221
- router.turnActivities.clear();
1222
- router.turnSavings.clear();
1223
- const run = router.run;
1224
- router.run = null;
1225
- router.afterDown = null;
1226
- if (run) await flushRun($, run);
1227
- router.view = {
1228
- ...initialView(router.view?.nativeModel ?? ''),
1229
- // The effort carries over /clear until the next turn reads it again, so "your model" keeps its effort.
1230
- nativeEffort: router.view?.nativeEffort ?? null,
1231
- mode: 'auto',
1232
- credentials: router.view?.credentials ?? null,
1233
- // Counts kept across sessions: the next session starts from them.
1234
- activityStore: router.view?.activityStore ?? null,
1235
- activityMetrics: router.view?.activityMetrics ?? null,
1236
- savingsStore: router.view?.savingsStore ?? null,
1237
- health: healthOf(clientOf(router, router.config.classifier), router.config.classifier),
1238
- configPath: router.config.nativePath,
1239
- phase: router.view?.phase === 'unavailable' ? 'unavailable' : 'ready',
1240
- error: router.view?.phase === 'unavailable' ? router.view.error : null,
1241
- };
1547
+ await endSession($, router);
1242
1548
  return next(e);
1243
1549
  });
1244
1550