@alexeiled/claude-router 1.24.0 → 1.25.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.
Files changed (78) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +44 -0
  3. package/README.md +39 -7
  4. package/docs/architecture.md +27 -4
  5. package/docs/configuration.md +23 -14
  6. package/docs/evaluation.md +3 -3
  7. package/docs/native-router.md +11 -3
  8. package/docs/router-band.svg +124 -133
  9. package/docs/router-pane-classifier.svg +24 -23
  10. package/docs/router-pane-now.svg +9 -7
  11. package/docs/router-pane-policy.svg +4 -4
  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 +70 -17
  17. package/hooks/native-router.mjs +333 -80
  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 +69 -20
  30. package/lib/facts.mjs +3 -0
  31. package/lib/modes.mjs +8 -4
  32. package/lib/panel.mjs +75 -2167
  33. package/lib/policy.mjs +7 -6
  34. package/lib/replay-trace.mjs +5 -2
  35. package/lib/replay.mjs +7 -1
  36. package/lib/route-line.mjs +46 -0
  37. package/lib/route.mjs +21 -16
  38. package/lib/savings.mjs +14 -3
  39. package/lib/subagents.mjs +41 -11
  40. package/lib/subcommands.mjs +60 -0
  41. package/lib/ui/fallback.mjs +22 -0
  42. package/lib/ui/graphical/band.mjs +256 -0
  43. package/lib/ui/graphical/charts.mjs +163 -0
  44. package/lib/ui/graphical/classifier.mjs +153 -0
  45. package/lib/ui/graphical/frame.mjs +227 -0
  46. package/lib/ui/graphical/kit.mjs +156 -0
  47. package/lib/ui/graphical/meter.mjs +25 -0
  48. package/lib/ui/graphical/now.mjs +353 -0
  49. package/lib/ui/graphical/policy.mjs +56 -0
  50. package/lib/ui/graphical/routes.mjs +264 -0
  51. package/lib/ui/graphical/squares.mjs +29 -0
  52. package/lib/ui/graphical/usage.mjs +376 -0
  53. package/lib/ui/model/band.mjs +439 -0
  54. package/lib/ui/model/classifier.mjs +308 -0
  55. package/lib/ui/model/draft.mjs +62 -0
  56. package/lib/ui/model/format.mjs +41 -0
  57. package/lib/ui/model/frame.mjs +359 -0
  58. package/lib/ui/model/now.mjs +390 -0
  59. package/lib/ui/model/policy.mjs +194 -0
  60. package/lib/ui/model/routes.mjs +392 -0
  61. package/lib/ui/model/usage-agents.mjs +311 -0
  62. package/lib/ui/model/usage-breakdown.mjs +237 -0
  63. package/lib/ui/model/usage-shared.mjs +58 -0
  64. package/lib/ui/model/usage.mjs +330 -0
  65. package/lib/ui/terminal/band.mjs +220 -0
  66. package/lib/ui/terminal/classifier.mjs +142 -0
  67. package/lib/ui/terminal/frame.mjs +169 -0
  68. package/lib/ui/terminal/kit.mjs +133 -0
  69. package/lib/ui/terminal/now.mjs +300 -0
  70. package/lib/ui/terminal/policy.mjs +52 -0
  71. package/lib/ui/terminal/routes.mjs +167 -0
  72. package/lib/ui/terminal/usage.mjs +363 -0
  73. package/lib/ui/terminal/wrap.mjs +37 -0
  74. package/lib/ui/tokens.mjs +106 -0
  75. package/lib/usage.mjs +5 -5
  76. package/lib/view.mjs +5 -2
  77. package/package.json +3 -2
  78. package/types/index.d.ts +15 -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' };
@@ -146,6 +139,34 @@ export const missingCredentials = (config, view, id) => {
146
139
  if (view.credentials && Object.hasOwn(view.credentials, id)) return view.credentials[id];
147
140
  return config.classifiers[id].keyOption === null ? null : 'missing-key';
148
141
  };
142
+ // The plugin's id as `claude plugin configure` takes it: `<name>@<marketplace>`, read from where an installed plugin's
143
+ // files are kept (…/plugins/cache/<marketplace>/<name>/<version>). A plugin loaded from elsewhere (`--plugin-dir`)
144
+ // has only its name.
145
+ //
146
+ // Where the path names no marketplace (a folder install), the one enabled `<name>@…` key of settings' `enabledPlugins`
147
+ // other than `@inline` names it: a disabled earlier install (`false`) is not a candidate. An id with anything but word
148
+ // characters, dots, `@` and `-` falls back to the name, so the command it goes into stays plain.
149
+ export function pluginIdOf({ name, root }, enabledPlugins = null) {
150
+ const parts = String(root ?? '').split(/[\\/]/);
151
+ const at = parts.lastIndexOf('cache');
152
+ const found = at > 0 && parts[at - 1] === 'plugins' && parts[at + 1] && parts[at + 2] === name;
153
+ const listed =
154
+ enabledPlugins && typeof enabledPlugins === 'object'
155
+ ? Object.entries(enabledPlugins)
156
+ .filter(
157
+ ([key, value]) =>
158
+ key.startsWith(`${name}@`) &&
159
+ key !== `${name}@inline` &&
160
+ value !== false &&
161
+ value !== null &&
162
+ value !== undefined,
163
+ )
164
+ .map(([key]) => key)
165
+ : [];
166
+ const id = found ? `${name}@${parts[at + 1]}` : listed.length === 1 ? listed[0] : name;
167
+ return /^[\w.@-]+$/.test(id) ? id : name;
168
+ }
169
+
149
170
  // What classifier `id` lacks, named by the setting the person enters: "no API token", "no account ID".
150
171
  export function missingText(config, id, missing) {
151
172
  const entry = config.classifiers[id];
@@ -225,7 +246,7 @@ export function reasonActivity(config, view) {
225
246
  activity: { choice: view.activityChoice, probabilities: view.activityProbabilities },
226
247
  phase: { choice: view.phaseChoice, probabilities: view.phaseProbabilities },
227
248
  });
228
- return signal?.mass >= config.policy.activityMass ? signal.choice : null;
249
+ return signal && signal.mass >= config.policy.activityMass ? signal.choice : null;
229
250
  }
230
251
 
231
252
  // The classifier's activity answer: its choice with the share it got and the two runners-up, or null when there is
@@ -298,7 +319,7 @@ export function storeAgreementLine(view) {
298
319
  const share = ({ matched, total }) => `${matched} of ${total}`;
299
320
  if (!agreement.total) return 'Tool compatibility across sessions: no labelled turns yet';
300
321
  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)})` : '';
322
+ const code = focus.total > 0 ? ` · code/ops/explore ${share(focus)} (${percent(focus.matched / focus.total)})` : '';
302
323
  return `Tool compatibility across sessions (not accuracy): ${all}${code}`;
303
324
  }
304
325
 
@@ -321,13 +342,9 @@ export function probeText(config, id) {
321
342
  return `activity probe ${probe.correct}/${probe.probes} · p95 ${probe.p95Ms} ms · ${day}`;
322
343
  }
323
344
 
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
345
  // "$6.40"; signed for a difference or a part: "−$1.84", "+$0.47", "$0.00".
328
346
  export const usd = (value) => `$${Math.abs(value).toFixed(2)}`;
329
347
  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
348
 
332
349
  export const yourModel = (view) => routeLabel(view.nativeModel, view.nativeEffort);
333
350
  const replyCount = (n, what = 'replies') => `${n} ${n === 1 ? what.replace(/ies$/, 'y') : what}`;
@@ -379,7 +396,7 @@ export function savingsLine(config, view, usage, now) {
379
396
  const plan = cost.limits.map((l) => `${l.label} ${l.percent}%`).join(' · ');
380
397
  const lines = plan ? [`Plan: ${plan}`] : [];
381
398
  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)})` : '';
399
+ const split = cost.agents > 0 ? ` (main ${usd(cost.mainUsd)} + agents ${usd(cost.agentUsd)})` : '';
383
400
  const credits = cost.creditsUsd ? ` · credits ${costText(cost.creditsUsd, cost.billing)}` : '';
384
401
  const versus =
385
402
  cost.diffUsd !== null
@@ -411,13 +428,16 @@ export function formatTokens(value) {
411
428
  }
412
429
 
413
430
  export function bar(value, maximum, width = 16) {
414
- if (!Number.isFinite(value) || !(maximum > 0)) return { text: 'unknown', percent: null, color: 'gray' };
431
+ if (!Number.isFinite(value) || !(maximum > 0))
432
+ return { text: 'unknown', percent: null, tone: /** @type {import('./ui/tokens.mjs').Tone} */ ('muted') };
415
433
  const fraction = Math.max(0, value / maximum);
416
434
  const filled = Math.min(width, Math.round(fraction * width));
417
435
  return {
418
436
  text: `${'█'.repeat(filled)}${'░'.repeat(width - filled)}`,
419
437
  percent: Math.round(fraction * 100),
420
- color: fraction > 0.8 ? 'red' : fraction > 0.6 ? 'yellow' : 'green',
438
+ tone: /** @type {import('./ui/tokens.mjs').Tone} */ (
439
+ fraction > 0.8 ? 'danger' : fraction > 0.6 ? 'warning' : 'success'
440
+ ),
421
441
  };
422
442
  }
423
443
 
@@ -444,7 +464,9 @@ export function usageMetrics(config, view, usage) {
444
464
  contextBar: bar(nextContext, window),
445
465
  cacheBar: {
446
466
  ...bar(reuse, 1),
447
- color: reuse === null ? 'gray' : reuse >= 0.6 ? 'green' : reuse >= 0.2 ? 'yellow' : 'gray',
467
+ tone: /** @type {import('./ui/tokens.mjs').Tone} */ (
468
+ reuse === null ? 'muted' : reuse >= 0.6 ? 'success' : reuse >= 0.2 ? 'warning' : 'muted'
469
+ ),
448
470
  },
449
471
  };
450
472
  }
@@ -474,11 +496,32 @@ export function shortRoute(config, route) {
474
496
  return `${shortModelName(model.id)}${effort ? `·${effort}` : ''}`;
475
497
  }
476
498
 
499
+ // "Opus 5.5 · medium": a route as a card names it, in the words the editor's Selects show; "inherit" where it leaves
500
+ // the effort to the session, and no effort on a model without efforts. `short` names the family alone, "Opus ·
501
+ // medium", as a graphical pin and the band's pin Select do.
502
+ export function cardRoute(config, route, { short = false } = {}) {
503
+ const model = config.models[route.model];
504
+ if (!model) return route.model;
505
+ // A name that is all version, with nothing left once the numbers go, keeps them.
506
+ const name = (short && shortModelName(model.id)) || modelName(model.id);
507
+ return `${name}${model.efforts.length ? ` · ${route.effort ?? 'inherit'}` : ''}`;
508
+ }
509
+
477
510
  // A tier as signal-strength bars, "▂▄▆" for medium: the band and pane draw the tier this way, never as a word, so the
478
511
  // only "low" or "high" beside a model is its effort.
479
512
  const METER = '▂▄▆█';
480
513
  export const tierBars = (tier) => METER.slice(0, TIERS.indexOf(tier) + 1);
481
514
 
515
+ // What a pin button says it runs. The table engine runs the tier's configured route in every routing mode, so the label
516
+ // names it. Auto reads no route table: a pin sets only the demand and the cheapest capable model is chosen when the turn
517
+ // runs, so no label can name one in advance. There the terminal shows the bars alone and a card names the tier.
518
+ export const pinShort = (config, tier) =>
519
+ config.routingEngine === 'auto' ? '' : shortRoute(config, resolveRoute(config, tier));
520
+ export const pinCard = (config, tier) =>
521
+ config.routingEngine === 'auto'
522
+ ? `${tier[0]?.toUpperCase()}${tier.slice(1)} tier`
523
+ : cardRoute(config, resolveRoute(config, tier), { short: true });
524
+
482
525
  // All amounts price observed tokens at configured rates, irrespective of the billing product.
483
526
  export const costText = (value, _billing) => `≈${usd(value)}`;
484
527
  export const API_ESTIMATE = 'API estimate';
@@ -496,9 +539,6 @@ export function gaugeCells(fraction, cells) {
496
539
  const filled = Math.min(cells, lit);
497
540
  return ['▰'.repeat(filled), '▱'.repeat(cells - filled)];
498
541
  }
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
542
  // This session's cost with its subagents and plan windows (costs.mjs periodCost).
503
543
  export function sessionCost(config, view, usage, now) {
504
544
  return periodCost(config, {
@@ -507,3 +547,12 @@ export function sessionCost(config, view, usage, now) {
507
547
  usage,
508
548
  });
509
549
  }
550
+
551
+ // The classifier's state as the pane's title line says it: a warning with the error or the missing credential, or the
552
+ // classifier ready with its last latency. Null latency (NaN included) is left out.
553
+ export function classifierState(config, view) {
554
+ const error = view.error ?? missingCredentials(config, view, config.classifier);
555
+ if (error) return { tone: /** @type {const} */ ('warning'), text: classifierStatus(config, error) };
556
+ const latency = Number.isFinite(view.adviceMs) ? ` · ${view.adviceMs} ms` : '';
557
+ return { tone: /** @type {const} */ ('success'), text: `${classifierLabel(config)} ready${latency}` };
558
+ }
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')
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
  }