@alexeiled/claude-router 1.24.0 → 1.25.1

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.
Files changed (79) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +74 -0
  3. package/README.md +55 -7
  4. package/docs/architecture.md +30 -4
  5. package/docs/configuration.md +23 -14
  6. package/docs/evaluation.md +3 -3
  7. package/docs/native-router.md +12 -4
  8. package/docs/router-band.svg +140 -142
  9. package/docs/router-pane-classifier.svg +48 -31
  10. package/docs/router-pane-now.svg +162 -120
  11. package/docs/router-pane-policy.svg +79 -47
  12. package/docs/router-pane-routes.svg +8 -8
  13. package/docs/router-pane-usage-whatif.svg +14 -14
  14. package/docs/router-pane-usage.svg +20 -20
  15. package/docs/routing-modes.md +10 -8
  16. package/docs/user-guide.md +151 -22
  17. package/hooks/native-router.mjs +415 -88
  18. package/lib/activity-stats.mjs +23 -4
  19. package/lib/activity.mjs +7 -5
  20. package/lib/auto-engine.mjs +13 -6
  21. package/lib/auto-route.mjs +10 -4
  22. package/lib/band.mjs +35 -440
  23. package/lib/classifier-client.mjs +12 -8
  24. package/lib/config-file.mjs +7 -2
  25. package/lib/config.mjs +24 -9
  26. package/lib/cost.mjs +5 -1
  27. package/lib/costs.mjs +4 -2
  28. package/lib/decisions.mjs +13 -9
  29. package/lib/display.mjs +71 -20
  30. package/lib/facts.mjs +3 -0
  31. package/lib/failover.mjs +55 -0
  32. package/lib/modes.mjs +8 -4
  33. package/lib/panel.mjs +75 -2167
  34. package/lib/policy.mjs +7 -6
  35. package/lib/replay-trace.mjs +5 -2
  36. package/lib/replay.mjs +7 -1
  37. package/lib/route-line.mjs +46 -0
  38. package/lib/route.mjs +51 -32
  39. package/lib/savings.mjs +14 -3
  40. package/lib/subagents.mjs +41 -11
  41. package/lib/subcommands.mjs +60 -0
  42. package/lib/ui/fallback.mjs +22 -0
  43. package/lib/ui/graphical/band.mjs +256 -0
  44. package/lib/ui/graphical/charts.mjs +163 -0
  45. package/lib/ui/graphical/classifier.mjs +153 -0
  46. package/lib/ui/graphical/frame.mjs +231 -0
  47. package/lib/ui/graphical/kit.mjs +156 -0
  48. package/lib/ui/graphical/meter.mjs +25 -0
  49. package/lib/ui/graphical/now.mjs +357 -0
  50. package/lib/ui/graphical/policy.mjs +56 -0
  51. package/lib/ui/graphical/routes.mjs +264 -0
  52. package/lib/ui/graphical/squares.mjs +29 -0
  53. package/lib/ui/graphical/usage.mjs +376 -0
  54. package/lib/ui/model/band.mjs +441 -0
  55. package/lib/ui/model/classifier.mjs +308 -0
  56. package/lib/ui/model/draft.mjs +62 -0
  57. package/lib/ui/model/format.mjs +41 -0
  58. package/lib/ui/model/frame.mjs +359 -0
  59. package/lib/ui/model/now.mjs +421 -0
  60. package/lib/ui/model/policy.mjs +194 -0
  61. package/lib/ui/model/routes.mjs +392 -0
  62. package/lib/ui/model/usage-agents.mjs +311 -0
  63. package/lib/ui/model/usage-breakdown.mjs +237 -0
  64. package/lib/ui/model/usage-shared.mjs +58 -0
  65. package/lib/ui/model/usage.mjs +330 -0
  66. package/lib/ui/terminal/band.mjs +253 -0
  67. package/lib/ui/terminal/classifier.mjs +150 -0
  68. package/lib/ui/terminal/frame.mjs +169 -0
  69. package/lib/ui/terminal/kit.mjs +162 -0
  70. package/lib/ui/terminal/now.mjs +293 -0
  71. package/lib/ui/terminal/policy.mjs +55 -0
  72. package/lib/ui/terminal/routes.mjs +167 -0
  73. package/lib/ui/terminal/usage.mjs +363 -0
  74. package/lib/ui/terminal/wrap.mjs +37 -0
  75. package/lib/ui/tokens.mjs +106 -0
  76. package/lib/usage.mjs +5 -5
  77. package/lib/view.mjs +5 -2
  78. package/package.json +4 -2
  79. package/types/index.d.ts +17 -0
@@ -12,9 +12,11 @@ import { activeClassifier } from './config.mjs';
12
12
  // A classifier answer is a few hundred bytes; anything far larger is not one.
13
13
  const MAX_ANSWER_CHARS = 16_384;
14
14
 
15
+ const errorText = (error) => (error instanceof Error ? error.message : String(error));
16
+
15
17
  class AdviceError extends Error {
16
- constructor(code) {
17
- super(code);
18
+ constructor(code, options) {
19
+ super(code, options);
18
20
  this.code = code;
19
21
  }
20
22
  }
@@ -28,6 +30,8 @@ export class ClassifierClient {
28
30
  this.exclusive = exclusive;
29
31
  this.pending = null;
30
32
  this.active = false;
33
+ this.failures = 0;
34
+ this.pausedUntil = 0;
31
35
  this.restore(health);
32
36
  }
33
37
 
@@ -88,12 +92,12 @@ export class ClassifierClient {
88
92
  try {
89
93
  response = await this.send(transport, body, remaining);
90
94
  } catch (error) {
91
- if (signal?.aborted) throw new AdviceError('cancelled');
95
+ if (signal?.aborted) throw new AdviceError('cancelled', { cause: error });
92
96
  if (error instanceof AdviceError) throw error;
93
- if (/policy|denied|(?<!conn)refus|network access|nonessential/i.test(String(error?.message)))
94
- throw new AdviceError('policy');
95
- if (attempt === 1) throw new AdviceError('unreachable');
96
- if (RETRY_DELAY_MS >= deadline - this.now()) throw new AdviceError('timeout');
97
+ if (/policy|denied|(?<!conn)refus|network access|nonessential/i.test(errorText(error)))
98
+ throw new AdviceError('policy', { cause: error });
99
+ if (attempt === 1) throw new AdviceError('unreachable', { cause: error });
100
+ if (RETRY_DELAY_MS >= deadline - this.now()) throw new AdviceError('timeout', { cause: error });
97
101
  await sleep(RETRY_DELAY_MS, { signal });
98
102
  continue;
99
103
  }
@@ -108,7 +112,7 @@ export class ClassifierClient {
108
112
  if (this.now() >= deadline) throw new AdviceError('timeout');
109
113
  } catch (error) {
110
114
  if (error instanceof AdviceError) throw error;
111
- throw new AdviceError('malformed');
115
+ throw new AdviceError('malformed', { cause: error });
112
116
  }
113
117
  const step = buildActivityRequest(config, prompt, turns, { activeGoal, currentStep });
114
118
  if (!step || deadline - this.now() < ACTIVITY_STEP_MIN_MS) return advice;
@@ -32,6 +32,11 @@ export function changedLeaves(before, after, path = []) {
32
32
  return out;
33
33
  }
34
34
 
35
+ function removeKey(node, key) {
36
+ // biome-ignore lint/nursery/noDynamicDelete: the key comes from a config path, and the tree is a private clone
37
+ delete node[key];
38
+ }
39
+
35
40
  // The router.json `file` with each leaf of one pane write put back as it was before it: a value written again
36
41
  // verbatim, a leaf that was absent deleted along with any object that leaves empty. Leaves the write did not touch,
37
42
  // such as an edit made on disk since, stay as they are.
@@ -55,8 +60,8 @@ export function restored(file, leaves) {
55
60
  chain.push(chain.at(-1)[name]);
56
61
  }
57
62
  if (chain.length !== path.length) continue;
58
- delete chain.at(-1)[key];
59
- for (let i = chain.length - 1; i > 0 && !Object.keys(chain[i]).length; i -= 1) delete chain[i - 1][path[i - 1]];
63
+ removeKey(chain.at(-1), key);
64
+ for (let i = chain.length - 1; i > 0 && !Object.keys(chain[i]).length; i -= 1) removeKey(chain[i - 1], path[i - 1]);
60
65
  }
61
66
  return next;
62
67
  }
package/lib/config.mjs CHANGED
@@ -60,10 +60,11 @@ export const DEFAULTS = {
60
60
  // `inherit`, or sets `modelRouting: auto` gets `light`, `standard` or `heavy` from the classifier; a pinned one keeps
61
61
  // its model. `types` overrides by agent type: a models key, `classify`, or null to never route it. A key without a
62
62
  // colon matches only the built-in of that name, whose definition is not readable, so only the listed built-ins route.
63
+ // A workflow `agent()` is always `workflow-subagent`, whatever its own type says; its own `agent({ model })` stands.
63
64
  // A listed type is routed even if it pins a model. docs/plans/2026-10-10-subagent-routing-plan.md.
64
65
  subagentRouting: 'on',
65
66
  subagents: {
66
- types: { Explore: 'haiku', Plan: CLASSIFY, 'general-purpose': CLASSIFY },
67
+ types: { Explore: 'haiku', Plan: CLASSIFY, 'general-purpose': CLASSIFY, 'workflow-subagent': CLASSIFY },
67
68
  light: 'haiku',
68
69
  standard: 'sonnet',
69
70
  heavy: 'opus',
@@ -293,6 +294,7 @@ export const MIGRATION_HINT =
293
294
 
294
295
  export const defaultsFor = (provider = 'anthropic') => executionDefaults(providerName(provider), DEFAULTS);
295
296
 
297
+ /** @param {{ userFile?: { models?: Record<string, { id?: string, capability?: object, efforts?: string[] }> } | null, provider?: string }} [options] */
296
298
  export function loadConfig({ userFile = null, provider = 'anthropic' } = {}) {
297
299
  provider = providerName(provider);
298
300
  if (userFile !== null) checkShape(userFile);
@@ -305,12 +307,14 @@ export function loadConfig({ userFile = null, provider = 'anthropic' } = {}) {
305
307
  if (changed && !Object.hasOwn(patch, 'strength')) delete model.strength;
306
308
  if (Object.hasOwn(patch, 'capability')) model.capability = { ...patch.capability };
307
309
  else if (changed) delete model.capability;
308
- else if (patch.efforts && model.capability && Array.isArray(patch.efforts))
310
+ else if (patch.efforts && model.capability && Array.isArray(patch.efforts)) {
311
+ const { efforts } = patch;
309
312
  model.capability = Object.fromEntries(
310
313
  Object.entries(model.capability).filter(([effort]) =>
311
- patch.efforts.length ? patch.efforts.includes(effort) : effort === 'default',
314
+ efforts.length ? efforts.includes(effort) : effort === 'default',
312
315
  ),
313
316
  );
317
+ }
314
318
  }
315
319
  // A user entry without `api` speaks the System One protocol that every entry spoke before 1.5.
316
320
  const config = {
@@ -392,7 +396,7 @@ export function withRoutes(file, draft) {
392
396
  // Activity cells are sparse: a missing field inherits the tier's route, so `effort: undefined` and `effort: null`
393
397
  // differ. A null or missing cell is no override.
394
398
  export const sameCell = (a, b) => (a && b ? a.model === b.model && a.effort === b.effort : !a === !b);
395
- const cellOf = (activities, activity, tier) => activities?.[activity]?.[tier];
399
+ const cellOf = (activities, activity, tier) => (activity ? activities?.[activity]?.[tier] : undefined);
396
400
 
397
401
  // The activity side of a route draft, with the effectiveRoutes rule: a cell or the mode counts as edited when it
398
402
  // differs from the draft's `base`; everything else follows `current`. A draft built without `activities` or
@@ -422,11 +426,15 @@ export function effectiveActivities(draft, current) {
422
426
  // An added cell starts from the built-in override, so re-adding a removed default restores it, else from the base
423
427
  // route, which the pane flags as having no effect until edited. An edit that lands on the route the saved cell
424
428
  // already resolves to is the saved cell, so a partial cell is not rewritten with the fields it inherits.
429
+ /** @param {string | null} [value] */
425
430
  export function editActivity(draft, current, activity, tier, kind, value = null) {
426
431
  const config = { ...current, ...effectiveRoutes(draft, current), ...effectiveActivities(draft, current) };
427
432
  const route = resolveRoute(config, tier, activity);
428
433
  let cell = {
429
- model: () => ({ model: value, effort: config.models[value]?.efforts.includes(route.effort) ? route.effort : null }),
434
+ model: () => ({
435
+ model: value,
436
+ effort: value !== null && config.models[value]?.efforts.includes(route.effort) ? route.effort : null,
437
+ }),
430
438
  effort: () => ({ model: route.model, effort: value }),
431
439
  add: () => ({
432
440
  ...(cellOf(defaultsFor(current.provider).activities, activity, tier) ?? resolveRoute(config, tier)),
@@ -483,6 +491,7 @@ export function withMode(file, mode) {
483
491
  }
484
492
 
485
493
  // The pane's policy controls and the router.json fields they stand for. The classifier deadline saves on its own.
494
+ /** @type {Record<string, [string, string]>} */
486
495
  const TUNING_FIELDS = {
487
496
  downgradeVotes: ['policy', 'downgradeVotes'],
488
497
  horizon: ['policy', 'downgradeHorizonTurns'],
@@ -528,20 +537,25 @@ export function rank(tier) {
528
537
 
529
538
  // The (model, effort) a tier runs on for an activity: the tier's route with that activity's sparse override on top.
530
539
  // A null activity (off, uncertain, failed) resolves to the tier's route.
540
+ /** @param {string | null} [activity] */
531
541
  export function resolveRoute(config, tier, activity = null) {
532
- const route = { ...config.routes[tier], ...config.activities?.[activity]?.[tier] };
542
+ const route = { ...config.routes[tier], ...cellOf(config.activities, activity, tier) };
533
543
  return { model: route.model, effort: route.effort ?? null };
534
544
  }
535
545
 
536
546
  // The model entry a route runs on.
537
547
  export const routeSpec = (config, route) => config.models[route.model];
538
548
 
539
- // Whether a Claude Code version, such as 2.1.289 or a 2.1.290-beta build, runs the router: 2.1.289 or newer.
549
+ // The oldest Claude Code the router runs on: the first build whose engine takes the graphical surfaces' spacing steps.
550
+ export const MIN_CLAUDE_CODE = '2.1.321';
551
+ const MIN_PATCH = Number(MIN_CLAUDE_CODE.split('.')[2]);
552
+
553
+ // Whether a Claude Code version, such as 2.1.321 or a 2.1.322-beta build, runs the router.
540
554
  export function supportedVersion(version) {
541
555
  const parts = /^(\d+)\.(\d+)\.(\d+)(?:$|-)/.exec(version ?? '');
542
556
  if (!parts) return false;
543
- const [major, minor, patch] = parts.slice(1).map(Number);
544
- return major > 2 || (major === 2 && (minor > 1 || (minor === 1 && patch >= 289)));
557
+ const [major = 0, minor = 0, patch = 0] = parts.slice(1).map(Number);
558
+ return major > 2 || (major === 2 && (minor > 1 || (minor === 1 && patch >= MIN_PATCH)));
545
559
  }
546
560
 
547
561
  function merge(base, override) {
@@ -623,6 +637,7 @@ function checkShape(file) {
623
637
  }
624
638
 
625
639
  // `allowed` null: an open map.
640
+ /** @param {string[] | null} [allowed] */
626
641
  function checkObject(value, path, allowed = null) {
627
642
  if (typeof value !== 'object' || value === null || Array.isArray(value)) throw new Error(`${path} must be an object`);
628
643
  for (const key of Object.keys(value)) {
package/lib/cost.mjs CHANGED
@@ -143,7 +143,10 @@ export function nextTurnRange(config, candidate, incumbent, facts, now) {
143
143
  ratesAt(routeSpec(config, incumbent), tokens, now),
144
144
  ];
145
145
  const outputTokens = facts.lastRequest?.outputTokens ?? 0;
146
- const output = to.output > 0 && from.output > 0 ? ((to.output - from.output) * outputTokens) / 1e6 : 0;
146
+ const output =
147
+ to.output !== undefined && from.output !== undefined && to.output > 0 && from.output > 0
148
+ ? ((to.output - from.output) * outputTokens) / 1e6
149
+ : 0;
147
150
  return { minUsd: proposed.min - current.max + output, maxUsd: proposed.max - current.min + output };
148
151
  }
149
152
 
@@ -152,6 +155,7 @@ export function switchEconomics(config, candidate, incumbent, facts, now) {
152
155
  const tokens = nextContextTokens(facts);
153
156
  const proposed = ratesAt(routeSpec(config, candidate), tokens, now);
154
157
  const current = ratesAt(routeSpec(config, incumbent), tokens, now);
158
+ if (proposed.output === undefined || current.output === undefined) return null;
155
159
  if (!(proposed.output > 0) || !(current.output > 0)) return null;
156
160
  const outputTokens = facts.lastRequest?.outputTokens ?? 0;
157
161
  const output = ((proposed.output - current.output) * outputTokens) / 1e6;
package/lib/costs.mjs CHANGED
@@ -12,6 +12,7 @@ import { dayKey } from './usage.mjs';
12
12
 
13
13
  // The plan windows Claude Code reports, in the order shown. `spend_limit` is a gateway's cap on billed spend, not a
14
14
  // plan's quota.
15
+ /** @type {[string, string][]} */
15
16
  const WINDOWS = [
16
17
  ['five_hour', '5h'],
17
18
  ['seven_day', '7d'],
@@ -112,8 +113,9 @@ export function periodCost(config, { summary, agents, usage = null }) {
112
113
  const mainDiff = comparable ? r.differenceUsd : null;
113
114
  const agentDiff = cents(agentUsd - agentBaseUsd);
114
115
  const baseUsd = comparable ? cents(r.yoursUsd + agentBaseUsd) : null;
115
- const diffUsd = comparable ? cents(mainDiff + agentDiff) : null;
116
+ const diffUsd = mainDiff === null ? null : cents(mainDiff + agentDiff);
116
117
  const billing = billingOf(config, usage);
118
+ /** @type {number | null} */
117
119
  let creditsUsd = null;
118
120
  if (billing === 'mixed') {
119
121
  let main = 0;
@@ -134,7 +136,7 @@ export function periodCost(config, { summary, agents, usage = null }) {
134
136
  agentDiff: agentUsd || agentBaseUsd ? agentDiff : null,
135
137
  baseUsd,
136
138
  diffUsd,
137
- share: baseUsd > 0 ? diffUsd / baseUsd : null,
139
+ share: baseUsd !== null && diffUsd !== null && baseUsd > 0 ? diffUsd / baseUsd : null,
138
140
  // A sample of main replies: agents alone are each priced against their own pick, not sampled.
139
141
  early: r.early && summary.replies > 0,
140
142
  readout: r,
package/lib/decisions.mjs CHANGED
@@ -89,7 +89,7 @@ const AUTO_ROUTE = /^([^\p{Cc}\p{Cf}\p{Zl}\p{Zp}]+)@(low|medium|high|xhigh|max|s
89
89
  function validAutoRoute(value) {
90
90
  if (typeof value !== 'string' || value.length > 72) return false;
91
91
  const match = AUTO_ROUTE.exec(value);
92
- return Boolean(match && match[1].length <= 64);
92
+ return Boolean(match?.[1] && match[1].length <= 64);
93
93
  }
94
94
  function readAlt(alt, auto = false) {
95
95
  if (!isRecord(alt)) return null;
@@ -137,6 +137,8 @@ function compared(kind, decision) {
137
137
  return mass === null || bar === null ? {} : { mass, bar };
138
138
  }
139
139
 
140
+ /** @typedef {{ choice: string, probabilities?: Record<string, number> }} AdviceChoice */
141
+
140
142
  // One routing decision as a row: `kind` start (the turn's first step), review (a classifier review applied inside the
141
143
  // turn) or observed (a move on the turn's own tool calls). `advice` is the classifier's answer or null, `error` why
142
144
  // there is none, `decision` the route chosen (chooseRoute's), `facts` what it was chosen on, `sameTask` sameTaskOf.
@@ -145,13 +147,15 @@ export function decisionRow({
145
147
  kind,
146
148
  origin = null,
147
149
  mode = null,
148
- advice = null,
150
+ advice = /** @type {(AdviceChoice & { continuation?: number, activity?: AdviceChoice | null, phase?: AdviceChoice }) | null} */ (
151
+ null
152
+ ),
149
153
  error = null,
150
154
  decision,
151
155
  facts = {},
152
- sameTask = null,
153
- engine = null,
154
- alt = null,
156
+ sameTask = /** @type {boolean | null} */ (null),
157
+ engine = /** @type {string | null} */ (null),
158
+ alt = /** @type {object | null} */ (null),
155
159
  }) {
156
160
  const activity = advice?.activity ?? null;
157
161
  const { downAllowed, contextTokens } = /** @type {{ downAllowed?: boolean, contextTokens?: number }} */ (facts);
@@ -161,10 +165,10 @@ export function decisionRow({
161
165
  origin: label(origin),
162
166
  mode: label(mode),
163
167
  cls: label(advice?.choice),
164
- p: round(advice?.probabilities?.[advice?.choice]),
168
+ p: round(advice?.probabilities?.[advice.choice]),
165
169
  cont: round(advice?.continuation),
166
170
  act: label(activity?.choice),
167
- actP: round(activity?.probabilities?.[activity?.choice]),
171
+ actP: round(activity?.probabilities?.[activity.choice]),
168
172
  ...(advice?.phase
169
173
  ? { phase: label(advice.phase.choice), phaseP: round(advice.phase.probabilities?.[advice.phase.choice]) }
170
174
  : {}),
@@ -177,9 +181,9 @@ export function decisionRow({
177
181
  pinned: Boolean(decision?.pinned),
178
182
  same: typeof sameTask === 'boolean' ? sameTask : null,
179
183
  down: typeof downAllowed === 'boolean' ? downAllowed : null,
180
- ctx: Number.isFinite(contextTokens) ? Math.round(contextTokens / 1000) : null,
184
+ ctx: typeof contextTokens === 'number' && Number.isFinite(contextTokens) ? Math.round(contextTokens / 1000) : null,
181
185
  ...compared(kind, decision),
182
- ...(ROUTING_ENGINES.includes(engine) && engine !== 'table' ? { engine } : {}),
186
+ ...(engine !== null && engine !== 'table' && ROUTING_ENGINES.includes(engine) ? { engine } : {}),
183
187
  ...(engine === 'shadow' && readAlt(alt) ? { alt: readAlt(alt) } : {}),
184
188
  ...(engine === 'auto' && readAlt(decision?.auto, true)
185
189
  ? { auto: { ...readAlt(decision.auto, true), move: label(decision.auto.move) } }
package/lib/display.mjs CHANGED
@@ -18,13 +18,6 @@ import { modelSpec } from './savings.mjs';
18
18
  import { readSubagentStore, summarizeSubagents } from './subagents.mjs';
19
19
  import { periodRange, readUsage, summarize, withReplies } from './usage.mjs';
20
20
 
21
- // Cost order, cheapest first, so the colors read as a scale. Hex values: every surface draws them.
22
- export const TIER_COLOR = { micro: '#5fd7af', low: '#5f9fe0', medium: '#d7af5f', high: '#e0708a' };
23
- // A subagent's square by the model family it ran on, apart from the tier colors so a model never reads as a tier.
24
- const MODEL_COLOR = { haiku: '#c3e88d', sonnet: '#f78c6c', opus: '#c792ea', fable: '#89ddff' };
25
- export const modelColor = (id) =>
26
- Object.entries(MODEL_COLOR).find(([family]) => String(id ?? '').includes(family))?.[1] ?? null;
27
-
28
21
  // The config as the view's routing mode routes it: the route texts name what runs, not the configured route. A view
29
22
  // from before 1.15 has no mode and reads as balanced.
30
23
  export const DEFAULT_ROUTING_MODE = { mode: 'balanced', source: 'default' };
@@ -128,6 +121,7 @@ export const REASONS = {
128
121
  'context-unknown': 'context is not measured reliably',
129
122
  'context-full': 'the context is too full for any route, so Claude’s model is kept',
130
123
  'model-unavailable': 'the requested model is not available',
124
+ 'model-held': 'the model failed with an API error and is held out for a while',
131
125
  pinned: 'one-turn model pin',
132
126
  manual: 'routing did not choose this turn, so Claude’s model is kept',
133
127
  'routing off': 'routing is off, so Claude’s model is kept',
@@ -146,6 +140,34 @@ export const missingCredentials = (config, view, id) => {
146
140
  if (view.credentials && Object.hasOwn(view.credentials, id)) return view.credentials[id];
147
141
  return config.classifiers[id].keyOption === null ? null : 'missing-key';
148
142
  };
143
+ // The plugin's id as `claude plugin configure` takes it: `<name>@<marketplace>`, read from where an installed plugin's
144
+ // files are kept (…/plugins/cache/<marketplace>/<name>/<version>). A plugin loaded from elsewhere (`--plugin-dir`)
145
+ // has only its name.
146
+ //
147
+ // Where the path names no marketplace (a folder install), the one enabled `<name>@…` key of settings' `enabledPlugins`
148
+ // other than `@inline` names it: a disabled earlier install (`false`) is not a candidate. An id with anything but word
149
+ // characters, dots, `@` and `-` falls back to the name, so the command it goes into stays plain.
150
+ export function pluginIdOf({ name, root }, enabledPlugins = null) {
151
+ const parts = String(root ?? '').split(/[\\/]/);
152
+ const at = parts.lastIndexOf('cache');
153
+ const found = at > 0 && parts[at - 1] === 'plugins' && parts[at + 1] && parts[at + 2] === name;
154
+ const listed =
155
+ enabledPlugins && typeof enabledPlugins === 'object'
156
+ ? Object.entries(enabledPlugins)
157
+ .filter(
158
+ ([key, value]) =>
159
+ key.startsWith(`${name}@`) &&
160
+ key !== `${name}@inline` &&
161
+ value !== false &&
162
+ value !== null &&
163
+ value !== undefined,
164
+ )
165
+ .map(([key]) => key)
166
+ : [];
167
+ const id = found ? `${name}@${parts[at + 1]}` : listed.length === 1 ? listed[0] : name;
168
+ return /^[\w.@-]+$/.test(id) ? id : name;
169
+ }
170
+
149
171
  // What classifier `id` lacks, named by the setting the person enters: "no API token", "no account ID".
150
172
  export function missingText(config, id, missing) {
151
173
  const entry = config.classifiers[id];
@@ -201,6 +223,7 @@ export const SHORT_REASONS = {
201
223
  'context-unknown': '= context unknown',
202
224
  'context-full': '! context full',
203
225
  'model-unavailable': '! model unavailable',
226
+ 'model-held': '! held out',
204
227
  'native-fallback': '! fallback',
205
228
  pinned: '⏵ pinned',
206
229
  manual: '= routing skipped',
@@ -225,7 +248,7 @@ export function reasonActivity(config, view) {
225
248
  activity: { choice: view.activityChoice, probabilities: view.activityProbabilities },
226
249
  phase: { choice: view.phaseChoice, probabilities: view.phaseProbabilities },
227
250
  });
228
- return signal?.mass >= config.policy.activityMass ? signal.choice : null;
251
+ return signal && signal.mass >= config.policy.activityMass ? signal.choice : null;
229
252
  }
230
253
 
231
254
  // The classifier's activity answer: its choice with the share it got and the two runners-up, or null when there is
@@ -298,7 +321,7 @@ export function storeAgreementLine(view) {
298
321
  const share = ({ matched, total }) => `${matched} of ${total}`;
299
322
  if (!agreement.total) return 'Tool compatibility across sessions: no labelled turns yet';
300
323
  const all = `${share(agreement)} turns (${percent(agreement.matched / agreement.total)})`;
301
- const code = focus.total ? ` · code/ops/explore ${share(focus)} (${percent(focus.matched / focus.total)})` : '';
324
+ const code = focus.total > 0 ? ` · code/ops/explore ${share(focus)} (${percent(focus.matched / focus.total)})` : '';
302
325
  return `Tool compatibility across sessions (not accuracy): ${all}${code}`;
303
326
  }
304
327
 
@@ -321,13 +344,9 @@ export function probeText(config, id) {
321
344
  return `activity probe ${probe.correct}/${probe.probes} · p95 ${probe.p95Ms} ms · ${day}`;
322
345
  }
323
346
 
324
- // Routing vs no routing: less is green, more is amber, not red: a stronger model is a purchase, not a fault.
325
- export const SAVINGS_COLOR = { less: '#6fcf97', more: '#f0b429' };
326
-
327
347
  // "$6.40"; signed for a difference or a part: "−$1.84", "+$0.47", "$0.00".
328
348
  export const usd = (value) => `$${Math.abs(value).toFixed(2)}`;
329
349
  export const signedUsd = (value) => (value === 0 ? '$0.00' : `${value < 0 ? '−' : '+'}${usd(value)}`);
330
- export const savingsColor = (value) => (value < 0 ? SAVINGS_COLOR.less : value > 0 ? SAVINGS_COLOR.more : undefined);
331
350
 
332
351
  export const yourModel = (view) => routeLabel(view.nativeModel, view.nativeEffort);
333
352
  const replyCount = (n, what = 'replies') => `${n} ${n === 1 ? what.replace(/ies$/, 'y') : what}`;
@@ -379,7 +398,7 @@ export function savingsLine(config, view, usage, now) {
379
398
  const plan = cost.limits.map((l) => `${l.label} ${l.percent}%`).join(' · ');
380
399
  const lines = plan ? [`Plan: ${plan}`] : [];
381
400
  if (!cost.replies && !cost.agents) return [...lines, 'Session: no routed replies yet'].join('\n');
382
- const split = cost.agents ? ` (main ${usd(cost.mainUsd)} + agents ${usd(cost.agentUsd)})` : '';
401
+ const split = cost.agents > 0 ? ` (main ${usd(cost.mainUsd)} + agents ${usd(cost.agentUsd)})` : '';
383
402
  const credits = cost.creditsUsd ? ` · credits ${costText(cost.creditsUsd, cost.billing)}` : '';
384
403
  const versus =
385
404
  cost.diffUsd !== null
@@ -411,13 +430,16 @@ export function formatTokens(value) {
411
430
  }
412
431
 
413
432
  export function bar(value, maximum, width = 16) {
414
- if (!Number.isFinite(value) || !(maximum > 0)) return { text: 'unknown', percent: null, color: 'gray' };
433
+ if (!Number.isFinite(value) || !(maximum > 0))
434
+ return { text: 'unknown', percent: null, tone: /** @type {import('./ui/tokens.mjs').Tone} */ ('muted') };
415
435
  const fraction = Math.max(0, value / maximum);
416
436
  const filled = Math.min(width, Math.round(fraction * width));
417
437
  return {
418
438
  text: `${'█'.repeat(filled)}${'░'.repeat(width - filled)}`,
419
439
  percent: Math.round(fraction * 100),
420
- color: fraction > 0.8 ? 'red' : fraction > 0.6 ? 'yellow' : 'green',
440
+ tone: /** @type {import('./ui/tokens.mjs').Tone} */ (
441
+ fraction > 0.8 ? 'danger' : fraction > 0.6 ? 'warning' : 'success'
442
+ ),
421
443
  };
422
444
  }
423
445
 
@@ -444,7 +466,9 @@ export function usageMetrics(config, view, usage) {
444
466
  contextBar: bar(nextContext, window),
445
467
  cacheBar: {
446
468
  ...bar(reuse, 1),
447
- color: reuse === null ? 'gray' : reuse >= 0.6 ? 'green' : reuse >= 0.2 ? 'yellow' : 'gray',
469
+ tone: /** @type {import('./ui/tokens.mjs').Tone} */ (
470
+ reuse === null ? 'muted' : reuse >= 0.6 ? 'success' : reuse >= 0.2 ? 'warning' : 'muted'
471
+ ),
448
472
  },
449
473
  };
450
474
  }
@@ -474,11 +498,32 @@ export function shortRoute(config, route) {
474
498
  return `${shortModelName(model.id)}${effort ? `·${effort}` : ''}`;
475
499
  }
476
500
 
501
+ // "Opus 5.5 · medium": a route as a card names it, in the words the editor's Selects show; "inherit" where it leaves
502
+ // the effort to the session, and no effort on a model without efforts. `short` names the family alone, "Opus ·
503
+ // medium", as a graphical pin and the band's pin Select do.
504
+ export function cardRoute(config, route, { short = false } = {}) {
505
+ const model = config.models[route.model];
506
+ if (!model) return route.model;
507
+ // A name that is all version, with nothing left once the numbers go, keeps them.
508
+ const name = (short && shortModelName(model.id)) || modelName(model.id);
509
+ return `${name}${model.efforts.length ? ` · ${route.effort ?? 'inherit'}` : ''}`;
510
+ }
511
+
477
512
  // A tier as signal-strength bars, "▂▄▆" for medium: the band and pane draw the tier this way, never as a word, so the
478
513
  // only "low" or "high" beside a model is its effort.
479
514
  const METER = '▂▄▆█';
480
515
  export const tierBars = (tier) => METER.slice(0, TIERS.indexOf(tier) + 1);
481
516
 
517
+ // What a pin button says it runs. The table engine runs the tier's configured route in every routing mode, so the label
518
+ // names it. Auto reads no route table: a pin sets only the demand and the cheapest capable model is chosen when the turn
519
+ // runs, so no label can name one in advance. There the terminal shows the bars alone and a card names the tier.
520
+ export const pinShort = (config, tier) =>
521
+ config.routingEngine === 'auto' ? '' : shortRoute(config, resolveRoute(config, tier));
522
+ export const pinCard = (config, tier) =>
523
+ config.routingEngine === 'auto'
524
+ ? `${tier[0]?.toUpperCase()}${tier.slice(1)} tier`
525
+ : cardRoute(config, resolveRoute(config, tier), { short: true });
526
+
482
527
  // All amounts price observed tokens at configured rates, irrespective of the billing product.
483
528
  export const costText = (value, _billing) => `≈${usd(value)}`;
484
529
  export const API_ESTIMATE = 'API estimate';
@@ -496,9 +541,6 @@ export function gaugeCells(fraction, cells) {
496
541
  const filled = Math.min(cells, lit);
497
542
  return ['▰'.repeat(filled), '▱'.repeat(cells - filled)];
498
543
  }
499
- // A plan window's colour by how much is used: green, then the warning colour past 75%, red past 90%.
500
- export const limitColor = (percent) => (percent >= 90 ? 'red' : percent >= 75 ? SAVINGS_COLOR.more : 'green');
501
-
502
544
  // This session's cost with its subagents and plan windows (costs.mjs periodCost).
503
545
  export function sessionCost(config, view, usage, now) {
504
546
  return periodCost(config, {
@@ -507,3 +549,12 @@ export function sessionCost(config, view, usage, now) {
507
549
  usage,
508
550
  });
509
551
  }
552
+
553
+ // The classifier's state as the pane's title line says it: a warning with the error or the missing credential, or the
554
+ // classifier ready with its last latency. Null latency (NaN included) is left out.
555
+ export function classifierState(config, view) {
556
+ const error = view.error ?? missingCredentials(config, view, config.classifier);
557
+ if (error) return { tone: /** @type {const} */ ('warning'), text: classifierStatus(config, error) };
558
+ const latency = Number.isFinite(view.adviceMs) ? ` · ${view.adviceMs} ms` : '';
559
+ return { tone: /** @type {const} */ ('success'), text: `${classifierLabel(config)} ready${latency}` };
560
+ }
package/lib/facts.mjs CHANGED
@@ -308,6 +308,7 @@ function runsCheck(words) {
308
308
  // cheaper route on the same task waits for. False when none ran since, or the last one failed (an unresolved failure),
309
309
  // or it went to the background, by request or after a timeout: its result reports the launch, not the check.
310
310
  export function verifiedSince(messages, fromIndex) {
311
+ /** @type {{ id: string, index: number, background: boolean } | null} */
311
312
  let last = null;
312
313
  for (let i = Math.max(0, fromIndex); i < messages.length; i += 1)
313
314
  if (messages[i]?.role === 'assistant')
@@ -374,6 +375,7 @@ export function progressEvidence(messages) {
374
375
  const edit = last((block) => FILE_EDIT_TOOLS.has(block.name));
375
376
  const run = last((block) => block.name === 'Bash' && ['ops', 'shell'].includes(commandKind(block.input?.command)));
376
377
  const outcome = (call) => (call ? { index: call.index, ok: succeeded(messages, call) } : null);
378
+ /** @type {{ index: number, error: boolean } | null} */
377
379
  let result = null;
378
380
  messages.forEach((message, index) => {
379
381
  if (message?.role === 'user')
@@ -402,6 +404,7 @@ function callsSince(messages, fromIndex) {
402
404
  }
403
405
 
404
406
  function lastResultSince(messages, fromIndex) {
407
+ /** @type {{ is_error?: boolean } | null} */
405
408
  let last = null;
406
409
  for (let i = Math.max(0, fromIndex); i < messages.length; i += 1)
407
410
  if (messages[i]?.role === 'user')
@@ -0,0 +1,55 @@
1
+ // API failover: a model whose request ended a turn on an API error is held out of routing for a while, so the next
2
+ // turn runs another model. Pure: the hook passes the error Claude Code classified (`StopFailure`'s `error`), the model
3
+ // and the clock.
4
+
5
+ const MINUTE = 60_000;
6
+
7
+ // How long each error holds the model out. Only errors that are the model's: busy, limited or failing on the provider's
8
+ // side, or not served at all. Claude Code does not report a retry-after, so the times are fixed. A model that is not
9
+ // found does not come back by itself; an hour bounds the hold in case it was a provider's outage. A billing error, a
10
+ // rejected key or request, a cut-off answer and an unknown error are not the model's, so another model would not help.
11
+ export const HOLD_MS = {
12
+ rate_limit: 5 * MINUTE,
13
+ overloaded: 5 * MINUTE,
14
+ server_error: 2 * MINUTE,
15
+ model_not_found: 60 * MINUTE,
16
+ };
17
+
18
+ // The words a notice uses for each error.
19
+ const ERROR_WORDS = {
20
+ rate_limit: 'rate limited',
21
+ overloaded: 'overloaded',
22
+ server_error: 'server error',
23
+ model_not_found: 'model not found',
24
+ };
25
+
26
+ /** How long `error` holds the failed model out, in milliseconds, or null when it holds nothing. */
27
+ export const holdMs = (error) => (Object.hasOwn(HOLD_MS, error) ? HOLD_MS[error] : null);
28
+
29
+ /** The holds still running at `now`: a hold ends at its `until`. */
30
+ export function activeHolds(held, now) {
31
+ return Object.fromEntries(Object.entries(held ?? {}).filter(([, hold]) => hold.until > now));
32
+ }
33
+
34
+ /** The model ids held out at `now`. */
35
+ export const heldModels = (held, now) => Object.keys(activeHolds(held, now));
36
+
37
+ /**
38
+ * The holds after `model` failed with `error` at `now`: expired holds dropped, and the model held for the error's time.
39
+ * A longer hold already running stays. An error that holds nothing changes no hold.
40
+ * @returns {Record<string, { error: string, until: number }>}
41
+ */
42
+ export function holdModel(held, model, error, now) {
43
+ const kept = activeHolds(held, now);
44
+ const ms = holdMs(error);
45
+ if (ms === null || typeof model !== 'string' || !model) return kept;
46
+ const running = kept[model];
47
+ if (running && running.until >= now + ms) return kept;
48
+ return { ...kept, [model]: { error, until: now + ms } };
49
+ }
50
+
51
+ /** "overloaded, 5 min": why a model is held out and for how long, rounded up to a minute. */
52
+ export function holdText(hold, now) {
53
+ const minutes = Math.max(1, Math.ceil((hold.until - now) / MINUTE));
54
+ return `${ERROR_WORDS[hold.error] ?? hold.error}, ${minutes} min`;
55
+ }
package/lib/modes.mjs CHANGED
@@ -21,7 +21,7 @@ function steppedEffort(config, route, step) {
21
21
  // tier's route without its activity override (never `micro`); else one effort level less. `high` keeps its model, so a turn that clears the upgrade bar runs on the
22
22
  // strongest one. `quality` one effort level more, else the tier above. One lever per decision; quality keeps the
23
23
  // model and its cache. `micro` and `balanced` keep the configured route.
24
- export function modeRoute(config, mode, tier, activity = null) {
24
+ export function modeRoute(config, mode, tier, activity = /** @type {string | null} */ (null)) {
25
25
  const routeAt = (t) => resolveRoute(config, t, activity);
26
26
  const route = routeAt(tier);
27
27
  if (mode === 'balanced' || tier === 'micro') return route;
@@ -65,9 +65,13 @@ export function applyMode(config, routingMode) {
65
65
  }
66
66
 
67
67
  // The active mode and its source: a session override, then the project file, then the profile router.json.
68
- export function resolveRoutingMode({ session = null, project = null, profile = DEFAULTS.mode } = {}) {
69
- if (ROUTING_MODES.includes(session)) return { mode: session, source: 'session' };
70
- if (ROUTING_MODES.includes(project)) return { mode: project, source: 'project' };
68
+ export function resolveRoutingMode({
69
+ session = /** @type {string | null} */ (null),
70
+ project = /** @type {string | null} */ (null),
71
+ profile = DEFAULTS.mode,
72
+ } = {}) {
73
+ if (session !== null && ROUTING_MODES.includes(session)) return { mode: session, source: 'session' };
74
+ if (project !== null && ROUTING_MODES.includes(project)) return { mode: project, source: 'project' };
71
75
  if (profile !== DEFAULTS.mode) return { mode: profile, source: 'profile' };
72
76
  return { mode: DEFAULTS.mode, source: 'default' };
73
77
  }