@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
@@ -128,7 +128,13 @@ const LATENCY_CLASSIFIERS = 8;
128
128
 
129
129
  // `since` (ms) is the first count after a reset; null in a record from before 1.10.3.
130
130
  export function emptyStore() {
131
- return { version: 1, since: null, confusion: {}, runs: {}, lateral: { taken: 0, refused: 0 } };
131
+ return {
132
+ version: 1,
133
+ since: /** @type {number | null} */ (null),
134
+ confusion: {},
135
+ runs: {},
136
+ lateral: { taken: 0, refused: 0 },
137
+ };
132
138
  }
133
139
 
134
140
  // The p95 of a latency histogram: the upper bound of its bucket in ms, `over` when it lies above the last bound, and
@@ -229,7 +235,13 @@ export function mergeStores(values, resetAt = null) {
229
235
  // classifier id, and the cheaper activity moves taken in `on` with the escalations that followed one, since `since`
230
236
  // (ms), the first reading after a reset.
231
237
  export function emptyMetrics() {
232
- return { version: 1, since: null, latency: {}, downMoves: { moves: 0, escalations: 0 }, unpriced: emptyUnpriced() };
238
+ return {
239
+ version: 1,
240
+ since: /** @type {number | null} */ (null),
241
+ latency: {},
242
+ downMoves: { moves: 0, escalations: 0 },
243
+ unpriced: emptyUnpriced(),
244
+ };
233
245
  }
234
246
 
235
247
  // Why a routed main reply was left out of the usage record (unpricedCause in savings.mjs): its usage did not read
@@ -264,7 +276,13 @@ export function readMetrics(value) {
264
276
  // returns `metrics` itself.
265
277
  export function recordMetrics(
266
278
  metrics,
267
- { classifier = null, adviceMs = null, downMove = null, unpriced = {}, now = null },
279
+ {
280
+ classifier = /** @type {string | null} */ (null),
281
+ adviceMs = /** @type {number | null} */ (null),
282
+ downMove = /** @type {string | null} */ (null),
283
+ unpriced = {},
284
+ now = /** @type {number | null} */ (null),
285
+ },
268
286
  ) {
269
287
  const next = {
270
288
  version: 1,
@@ -280,9 +298,10 @@ export function recordMetrics(
280
298
  next.unpriced[cause] += n;
281
299
  counted = true;
282
300
  }
283
- const known = Object.hasOwn(next.latency, classifier);
301
+ const known = typeof classifier === 'string' && Object.hasOwn(next.latency, classifier);
284
302
  if (
285
303
  typeof classifier === 'string' &&
304
+ typeof adviceMs === 'number' &&
286
305
  Number.isFinite(adviceMs) &&
287
306
  adviceMs >= 0 &&
288
307
  (known || Object.keys(next.latency).length < LATENCY_CLASSIFIERS)
package/lib/activity.mjs CHANGED
@@ -46,7 +46,9 @@ export function routingActivity(config, advice) {
46
46
 
47
47
  const acceptRoutingActivity = (config, advice) => {
48
48
  const signal = routingActivity(config, advice);
49
- return ACTIVITIES.includes(signal?.choice) && signal.mass >= config.policy.activityMass ? signal.choice : null;
49
+ return signal !== null && ACTIVITIES.includes(signal.choice) && signal.mass >= config.policy.activityMass
50
+ ? signal.choice
51
+ : null;
50
52
  };
51
53
 
52
54
  // 1 when route `a` is stronger than `b`, -1 when weaker, 0 when equal in declared strength, null when unordered.
@@ -83,10 +85,10 @@ export function chooseActivity(config, advice, incumbent, sentEffort, facts = {}
83
85
  if (!sameTaskOf(config, advice, facts)) return nominate(acceptRoutingActivity(config, advice));
84
86
  const signal = routingActivity(config, advice);
85
87
  const label = signal?.choice;
86
- if (!ACTIVITIES.includes(label)) return stay;
88
+ if (!signal || !ACTIVITIES.includes(label)) return stay;
87
89
  const candidate = resolveRoute(config, incumbent.tier, label);
88
90
  const order = compareRoutes(config, candidate, incumbent.route, sentEffort);
89
- if (order > 0) return nominate(label);
91
+ if (order !== null && order > 0) return nominate(label);
90
92
  // An explicitly declared ops work floor may be nominated without inventing a physical-model ranking.
91
93
  // The lateral confidence/cache/hold/cash gates still decide; inherited generic cells get no exception.
92
94
  // Equal requests can adopt the semantic work preference without a model/effort switch. Higher tiers may differ.
@@ -94,7 +96,7 @@ export function chooseActivity(config, advice, incumbent, sentEffort, facts = {}
94
96
  const declared = config.configuredActivities ?? config.activities;
95
97
  if (order === null && label === floor && declared[label]?.[incumbent.tier]) return nominate(label);
96
98
  const mass = signal.mass;
97
- if (order < 0 && facts.downAllowed && mass >= config.policy.downgradeMass) return nominate(label);
99
+ if (order !== null && order < 0 && facts.downAllowed && mass >= config.policy.downgradeMass) return nominate(label);
98
100
  return stay;
99
101
  }
100
102
 
@@ -109,7 +111,7 @@ export function chooseActivity(config, advice, incumbent, sentEffort, facts = {}
109
111
  // { move, reason, estimate }.
110
112
  export function lateralMove({ config, from, to, mass, hold, sameTask = false, facts, now, costs }) {
111
113
  const order = compareRoutes(config, to, from, facts.effort);
112
- if (hold && !(order > 0)) return { move: false, reason: 'hold', estimate: null };
114
+ if (hold && !(order !== null && order > 0)) return { move: false, reason: 'hold', estimate: null };
113
115
  const p = config.policy;
114
116
  let estimate;
115
117
  if (order !== -1 && sameTask && !facts.downAllowed && cheaperPerTurn(routeSpec(config, to), routeSpec(config, from)))
@@ -39,7 +39,14 @@ function trailing(votes, predicate) {
39
39
 
40
40
  // Only vote/hold policy fields are read here: no route, cache, price, checkpoint or dwell evidence.
41
41
  // Raw demand is integer; the accepted bounded execute discount never accumulates or discounts a pin/escalation.
42
- export function advanceDemand({ config, state, advice = null, facts, pin = null, boundedExecute = false }) {
42
+ export function advanceDemand({
43
+ config,
44
+ state,
45
+ advice = /** @type {{ choice: string, probabilities: Record<string, number> } | null} */ (null),
46
+ facts,
47
+ pin = null,
48
+ boundedExecute = false,
49
+ }) {
43
50
  const pinned = pin === null ? null : typeof pin === 'string' ? TIERS.indexOf(pin) : pin;
44
51
  if (pinned !== null && (!Number.isInteger(pinned) || !validLevel(pinned)))
45
52
  throw new RangeError('pin must name a tier or integer demand 0..3');
@@ -293,16 +300,16 @@ export function decideMove({
293
300
  demandResult,
294
301
  target,
295
302
  candidates,
296
- advice = null,
303
+ advice = /** @type {{ choice: string, probabilities: Record<string, number> } | null} */ (null),
297
304
  facts,
298
305
  now,
299
- changeCause = null,
306
+ changeCause = /** @type {string | null} */ (null),
300
307
  startup = false,
301
308
  incumbentOrigin = null,
302
309
  }) {
303
310
  const current = candidates.find((candidate) => candidate.incumbent);
304
311
  const proposed = candidates.find((candidate) => sameRoute(candidate.route, target.route));
305
- const stay = (reason, evidence = null) => ({
312
+ const stay = (reason, evidence = /** @type {object | null} */ (null)) => ({
306
313
  move: false,
307
314
  route: current?.eligible ? current.route : null,
308
315
  reason,
@@ -311,7 +318,7 @@ export function decideMove({
311
318
  // The selected physical request can accept new demand without a switch or new route provenance.
312
319
  state: reason === 'same-route' ? { ...state, routedDemand: demandResult.level } : state,
313
320
  });
314
- const move = (reason, cause, evidence = null) => ({
321
+ const move = (reason, cause, evidence = /** @type {object | null} */ (null)) => ({
315
322
  move: true,
316
323
  route: target.route,
317
324
  reason,
@@ -366,7 +373,7 @@ export function decideMove({
366
373
  return move('downgrade', 'classifier', evidence);
367
374
  }
368
375
  if (stronger || (target.capability === null && current.capability !== null)) {
369
- if (!['mode', 'catalog'].includes(changeCause)) return stay('no-evidence');
376
+ if (changeCause !== 'mode' && changeCause !== 'catalog') return stay('no-evidence');
370
377
  return upgrade(1, 'explicit-up', changeCause);
371
378
  }
372
379
  if (target.estimate.maxUsd < current.estimate.maxUsd) {
@@ -162,7 +162,12 @@ function decisionFor(config, auto, input, proposal, pin) {
162
162
 
163
163
  // Only versioned state is authoritative; resets never restore old demand votes or pending moves.
164
164
  // Cache and resolution observations belong to the shared physical loop, not the engine state.
165
- export function autoRoute(config, previous, input, { continuation = false, observed = null } = {}) {
165
+ export function autoRoute(
166
+ config,
167
+ previous,
168
+ input,
169
+ { continuation = false, observed = /** @type {string | null} */ (null) } = {},
170
+ ) {
166
171
  const { facts, now, nativeModel, availableModels, contextKnown } = input;
167
172
  const mode = config.routingMode?.mode ?? config.mode ?? 'balanced';
168
173
  const projected = economicConfig(config, previous);
@@ -189,11 +194,12 @@ export function autoRoute(config, previous, input, { continuation = false, obser
189
194
  auto.advice = input.advice;
190
195
  const accepted = config.activityRouting === 'on' ? acceptActivity(config, input.advice) : null;
191
196
  const signal = routingActivity(config, input.advice);
192
- if (accepted) auto.activity = signal?.mass >= config.policy.activityMass ? signal.choice : accepted;
197
+ if (accepted)
198
+ auto.activity = signal !== null && signal.mass >= config.policy.activityMass ? signal.choice : accepted;
193
199
  auto.boundedExecute = accepted !== null && acceptPhase(config, input.advice) === 'execute';
194
200
  }
195
- if (!pin && ['code', 'docs', 'ops'].includes(observed)) auto.activity = observed;
196
- if (!pin && ['code', 'docs'].includes(observed)) auto.boundedExecute = false;
201
+ if (!pin && observed !== null && ['code', 'docs', 'ops'].includes(observed)) auto.activity = observed;
202
+ if (!pin && observed !== null && ['code', 'docs'].includes(observed)) auto.boundedExecute = false;
197
203
  const args = {
198
204
  config: projected,
199
205
  facts: {
package/lib/band.mjs CHANGED
@@ -1,447 +1,42 @@
1
- import { activeClassifier, resolveRoute, TIERS } from './config.mjs';
2
- import { resetText } from './costs.mjs';
3
- import {
4
- API_ESTIMATE,
5
- baselineName,
6
- classifierLabel,
7
- classifierStatus,
8
- classifierWarns,
9
- costText,
10
- diffText,
11
- gaugeCells,
12
- limitColor,
13
- modeLever,
14
- modelColor,
15
- modelName,
16
- NOT_A_TIER_REASON,
17
- percentPair,
18
- reasonActivity,
19
- reasonNamesActivity,
20
- repliesText,
21
- routeLabel,
22
- routingModeOf,
23
- savingsColor,
24
- sessionCost,
25
- sessionUsage,
26
- shortReason,
27
- shortRoute,
28
- shownConfig,
29
- TIER_COLOR,
30
- tierBars,
31
- unavailableReason,
32
- usageMetrics,
33
- usd,
34
- } from './display.mjs';
35
- import { isSameModel } from './route.mjs';
36
- import { PASS_WHY } from './subagents.mjs';
37
-
38
- const BARS = '▂▄▆█';
39
- // Groups on a row sit apart by space alone: the meter, colours and glyphs already separate them.
40
- const SEPARATOR = ' ';
41
- // The hover row's controls sit closer: they are buttons, not readings.
42
- const GAP = ' ';
43
- // Space the band keeps for the trailing Router button.
44
- const ROUTER_BUTTON = 8;
45
- // Cells in the band's gauges: the context window and a plan window.
46
- const CONTEXT_CELLS = 5;
47
- const PLAN_CELLS = 8;
48
-
49
- // Hex, like TIER_COLOR, so every surface draws the same shades. Yellow stays out: it marks a fault that needs action.
50
- // Activity is Claude Code's orange for a turn's action; italic sets it apart from the high and medium tier colors.
51
- const COLOR = {
52
- accent: '#7c9cff',
53
- off: '#2a3040',
54
- muted: '#8b93a7',
55
- warn: '#f0b429',
56
- activity: '#d77757',
57
- gauge: '#87d787',
58
- };
59
-
60
- const part = (text, style = {}) => ({ text, style });
61
- const dim = (text) => part(text, { dimColor: true });
62
- const button = (props) => ({ button: props });
63
- // `priority` 0 never drops; higher numbers drop first when the band is narrow. `right` segments sit at the row's end.
64
- const segment = (priority, ...parts) => ({ priority, parts: parts.flat().filter(Boolean) });
65
- const right = (seg) => ({ ...seg, right: true });
66
- const partWidth = (p) => (p.button ? p.button.label.length + (p.button.plain ? 0 : 4) : p.text.length);
67
- const partsWidth = (parts) => parts.reduce((n, p) => n + partWidth(p), 0);
68
- const lineWidth = (segments, separator) =>
69
- segments.reduce((sum, s, i) => sum + (i ? separator.length : 0) + partsWidth(s.parts), 0);
70
-
71
- // Drops the highest-priority segments and parts, later ones first on a tie, until the line fits `columns`. If the
72
- // priority-0 segments alone are too wide, the later ones go too, and the first is cut with an ellipsis: Ink would
73
- // otherwise shrink every Text in the row and garble it.
74
- export function fitSegments(segments, columns, separator = SEPARATOR) {
75
- const kept = [...segments];
76
- while (lineWidth(kept, separator) > columns) {
77
- let drop = null;
78
- kept.forEach((s, i) => {
79
- s.parts.forEach((p, j) => {
80
- if (p.priority > 0 && (!drop || p.priority >= drop.priority)) drop = { priority: p.priority, i, j };
81
- });
82
- if (kept.length > 1 && s.priority > 0 && (!drop || s.priority >= drop.priority))
83
- drop = { priority: s.priority, i };
84
- });
85
- if (drop?.j !== undefined)
86
- kept[drop.i] = { ...kept[drop.i], parts: kept[drop.i].parts.filter((_, j) => j !== drop.j) };
87
- else if (drop) kept.splice(drop.i, 1);
88
- else if (kept.length > 1) kept.pop();
89
- else break;
90
- }
91
- const overflow = lineWidth(kept, separator) - columns;
92
- if (overflow > 0 && kept.length) {
93
- const parts = [...kept[0].parts];
94
- const last = parts.findLastIndex((p) => !p.button && p.text.length > overflow);
95
- if (last >= 0) parts[last] = { ...parts[last], text: `${parts[last].text.slice(0, -overflow - 1)}…` };
96
- kept[0] = { ...kept[0], parts };
97
- }
98
- return kept;
99
- }
100
-
101
- // Signal-strength bars: lit up to the tier in its color, dim above it or when `dim`.
102
- function meter(tier, off = false) {
103
- const lit = off ? -1 : TIERS.indexOf(tier);
104
- return [...BARS].map((bar, i) => part(bar, i <= lit ? { color: TIER_COLOR[tier] } : { dimColor: true }));
105
- }
106
-
107
- // The classifier is working: every bar in the accent colour.
108
- const pendingMeter = () => [...BARS].map((bar) => part(bar, { color: COLOR.accent }));
109
-
110
- // "Haiku 5.5 · high", the model in bold so the eye finds it first.
111
- const routeParts = (model, effort) => [
112
- part(modelName(model), { bold: true }),
113
- effort === null || effort === undefined ? null : part(` · ${effort}`),
114
- ];
115
-
116
- function served(view) {
117
- const { actualModel: actual, selectedModel: selected } = view;
118
- return Boolean(actual && selected && !isSameModel(selected, actual));
119
- }
120
-
121
- // "Jev 93% ≥ 90%": the classifier's support for the switch the policy weighed, against the bar it set.
122
- function supportText(config, estimate) {
123
- if (!Number.isFinite(estimate?.threshold)) return null;
124
- const mass = Number.isFinite(estimate.upgradeMass) ? estimate.upgradeMass : estimate.downgradeMass;
125
- if (!Number.isFinite(mass)) return null;
126
- const [shown, bar] = percentPair(mass, estimate.threshold);
127
- return `${classifierLabel(config)} ${shown} ${mass >= estimate.threshold ? '≥' : '<'} ${bar}`;
128
- }
129
-
130
- // The routing mode as a chip, only when it is not balanced: "cost", or "cost effort only" when the mode kept the model.
131
- function modeChip(config, view) {
132
- const { mode } = routingModeOf(view);
133
- if (mode === 'balanced') return null;
134
- const lever = modeLever(config, view);
135
- return segment(
136
- 5,
137
- part(` ${mode} `, { backgroundColor: COLOR.off, color: COLOR.muted }),
138
- lever ? dim(` ${lever}`) : null,
1
+ import { routeLabel, shortReason } from './display.mjs';
2
+ import { orTerminal } from './ui/fallback.mjs';
3
+ import { graphicalRouteLine, renderGraphicalBand } from './ui/graphical/band.mjs';
4
+ import { supportText } from './ui/model/band.mjs';
5
+ import { terminalBand, terminalRouteLine } from './ui/terminal/band.mjs';
6
+ import { isGraphical } from './ui/tokens.mjs';
7
+
8
+ /** Draws the band for the surface: native on desktop, VS Code and mobile, the terminal's row otherwise. */
9
+ export function renderBand(elements, config, view, usage, opts, actions) {
10
+ return orTerminal(
11
+ opts.surface,
12
+ (surface) => {
13
+ const { columns, agentId, agent = null, agents = [], back = false, now = Date.now() } = opts;
14
+ return isGraphical(surface)
15
+ ? renderGraphicalBand(
16
+ elements,
17
+ config,
18
+ view,
19
+ usage,
20
+ { columns, agentId, agent, agents, back, now, surface },
21
+ actions,
22
+ )
23
+ : terminalBand(elements, config, view, usage, { columns, agentId, agent, agents, back, now }, actions);
24
+ },
25
+ opts.onFallback,
139
26
  );
140
27
  }
141
28
 
142
- // Context fill and the last reply's cache reuse, kept at the row's end so they stay in one place turn after turn.
143
- function gauges(config, view, usage) {
144
- const metrics = usageMetrics(config, view, usage);
145
- const out = [];
146
- if (metrics.contextBar.percent !== null) {
147
- const [filled, empty] = gaugeCells(metrics.contextBar.percent / 100, CONTEXT_CELLS);
148
- out.push(
149
- right(
150
- segment(
151
- 3,
152
- dim('ctx '),
153
- part(filled, { color: metrics.contextBar.color }),
154
- dim(empty),
155
- part(` ${metrics.contextBar.percent}%`, { color: metrics.contextBar.color }),
156
- ),
157
- ),
158
- );
159
- }
160
- if (metrics.cacheBar.percent !== null)
161
- out.push(
162
- right(
163
- segment(
164
- 4,
165
- dim('cache '),
166
- part(`${metrics.cacheBar.percent}%`, { color: metrics.cacheBar.color }),
167
- dim(' last'),
168
- ),
169
- ),
170
- );
171
- return out;
172
- }
173
-
174
- export function bandSegments(config, view, usage, actions) {
175
- const native = () => routeParts(view.nativeModel, view.nativeEffort);
176
- if (view.phase === 'unavailable')
177
- return [
178
- segment(
179
- 0,
180
- part('✕ ', { color: 'red' }),
181
- native(),
182
- part(' '),
183
- button({ key: 'band-fix', label: 'Fix', onPress: actions.open }),
184
- ),
185
- segment(1, part('routing unavailable', { color: 'red' })),
186
- segment(3, part(unavailableReason(view), { color: 'red', dimColor: true })),
187
- ];
188
- // Turn on shares the first segment, which never drops and whose cut keeps buttons whole, so the band's one way back
189
- // on survives any width.
190
- if (view.mode === 'manual')
191
- return [
192
- segment(
193
- 0,
194
- dim('○ '),
195
- native(),
196
- part(' '),
197
- button({ key: 'band-auto', label: 'Turn on', variant: 'primary', onPress: () => actions.mode('auto') }),
198
- ),
199
- segment(1, dim(`routing off${view.reason === 'model selected manually' ? ' · /model' : ''}`)),
200
- view.reason === NOT_A_TIER_REASON ? segment(2, dim('not a routing tier')) : null,
201
- ].filter(Boolean);
202
- if (view.phase === 'choosing')
203
- return [
204
- segment(0, pendingMeter(), dim(' choosing…')),
205
- segment(3, dim(`${classifierLabel(config)} ≤ ${activeClassifier(config).timeoutMs / 1000} s`)),
206
- ];
207
- const pin = view.pendingPin
208
- ? segment(
209
- 0,
210
- part('⏵ next ', { color: COLOR.accent }),
211
- part(tierBars(view.pendingPin), { color: TIER_COLOR[view.pendingPin] }),
212
- part(` ${shortRoute(config, resolveRoute(shownConfig(config, view), view.pendingPin))}`, {
213
- color: TIER_COLOR[view.pendingPin],
214
- }),
215
- part(' '),
216
- button({ key: 'band-unpin', label: '✕', plain: true, onPress: actions.unpin }),
217
- )
218
- : null;
219
- if (!view.tier && view.phase === 'ready' && !view.actualModel)
220
- return [
221
- segment(0, meter(null, true), part(' '), native()),
222
- segment(1, dim('ready')),
223
- pin,
224
- modeChip(config, view),
225
- ].filter(Boolean);
226
- const main = segment(
227
- 0,
228
- view.tier ? meter(view.tier) : dim('○'),
229
- part(' '),
230
- routeParts(view.actualModel ?? view.selectedModel ?? view.nativeModel, view.effort),
231
- served(view) ? part(' fallback', { color: 'yellow' }) : null,
232
- );
233
- const activityText = view.goal
234
- ? `${view.goal}${view.taskPhase ? ` / ${view.taskPhase}` : ''}${view.activity && view.activity !== view.goal ? ` → ${view.activity}` : ''}`
235
- : view.activity;
236
- const activity =
237
- activityText &&
238
- config.activityRouting !== 'off' &&
239
- ((view.goal && (view.taskPhase || view.goal !== view.activity)) || !reasonNamesActivity(view.reason))
240
- ? segment(2, part(activityText, { color: COLOR.activity, italic: true }))
241
- : null;
242
- const reason = segment(1, dim(shortReason(view.reason, reasonActivity(config, view))));
243
- // The warning leads and the route yields: when the band is narrow, what to fix matters more than the model kept.
244
- if (classifierWarns(view.error))
245
- return [
246
- segment(0, part(`⚠ ${classifierStatus(config, view.error)}`, { color: COLOR.warn })),
247
- view.error === 'missing-key' || view.error === 'missing-account'
248
- ? segment(0, button({ key: 'band-key', label: 'Set up', variant: 'primary', onPress: actions.key }))
249
- : segment(2, button({ key: 'band-fix', label: 'Details', onPress: actions.open })),
250
- { ...main, priority: 1 },
251
- pin,
252
- { ...reason, priority: 3 },
253
- ].filter(Boolean);
254
- const support = supportText(config, view.estimate);
255
- // The policy's price for the switch it weighed: mostly the prompt cache the other model must write.
256
- const switchUsd = view.estimate?.taxUsd;
257
- return [
258
- main,
259
- activity,
260
- pin,
261
- reason,
262
- modeChip(config, view),
263
- support ? segment(6, dim(support)) : null,
264
- Number.isFinite(switchUsd) && switchUsd >= 0.005 ? segment(6, dim(`switch ≈ ${usd(switchUsd)}`)) : null,
265
- ...gauges(config, view, usage),
266
- ].filter(Boolean);
267
- }
268
-
269
- // The second row: the plan windows on a Claude plan, then this session's cost with its subagents, and how it compares
270
- // with your /model (or `unrouted` with subagents):
271
- // "plan 5h ▰▰▰▱▱▱▱▱ 37% ↻17:00 7d 62% session ≈$7.60 API estimate −$1.76 (−19%) vs Sonnet 5.5 24 replies".
272
- // An effort-only profile shows its effort mix instead of a saving. When the band is narrow the reset time, the
273
- // counts and the words go first; the 5h window and the session total stay.
274
- export function sessionSegments(config, view, usage, now = Date.now()) {
275
- const cost = sessionCost(config, view, usage, now);
276
- const out = [];
277
- for (const limit of cost.limits) {
278
- const color = limitColor(limit.percent);
279
- if (limit.kind === 'five_hour') {
280
- const [filled, empty] = gaugeCells(limit.percent / 100, PLAN_CELLS);
281
- const reset = resetText(limit.resetsAt, now);
282
- out.push(
283
- segment(
284
- 0,
285
- dim('plan 5h '),
286
- part(filled, { color }),
287
- dim(empty),
288
- part(` ${limit.percent}%`, { color }),
289
- reset ? { ...dim(` ↻${reset}`), priority: 4 } : null,
290
- ),
291
- );
292
- } else out.push(segment(3, dim(`${limit.label} `), part(`${limit.percent}%`, { color })));
293
- }
294
- const routing = view.mode === 'auto' && view.phase !== 'unavailable';
295
- if (!routing) return out.filter(Boolean);
296
- if (!cost.replies && !cost.agents) return [...out, segment(2, dim('session · no replies yet'))].filter(Boolean);
297
- out.push(
298
- segment(0, dim('session '), part(costText(cost.totalUsd, cost.billing), { bold: true }), {
299
- ...dim(` ${API_ESTIMATE}`),
300
- priority: 5,
301
- }),
302
- );
303
- if (cost.billing === 'mixed') out.push(segment(1, part(`credits ${costText(cost.creditsUsd, cost.billing)}`)));
304
- if (cost.effortOnly && cost.effortMix.length)
305
- out.push(segment(2, dim('effort '), part(cost.effortMix.map(([effort, n]) => `${effort} ${n}`).join(' · '))));
306
- else if (cost.diffUsd !== null)
307
- out.push(
308
- segment(
309
- 1,
310
- part(diffText(cost.diffUsd, cost.baseUsd), { bold: true, color: savingsColor(cost.diffUsd) }),
311
- dim(` vs ${baselineName(view, sessionUsage(view, now), cost)}`),
312
- ),
313
- );
314
- else if (cost.uncomparedReplies)
315
- out.push(
316
- segment(
317
- 2,
318
- dim(
319
- cost.uncomparedReplies === cost.replies
320
- ? 'not compared'
321
- : `${cost.uncomparedReplies} of ${cost.replies} not compared`,
322
- ),
323
- ),
324
- );
325
- out.push(
326
- segment(
327
- 6,
328
- dim(`${repliesText(cost)}${cost.agents ? ` · ${cost.agents} agent${cost.agents === 1 ? '' : 's'}` : ''}`),
329
- ),
330
- );
331
- return out.filter(Boolean);
332
- }
333
-
334
- // The second row's parts at `columns`.
335
- export const sessionRow = (config, view, usage, columns, now = Date.now()) =>
336
- fitSegments(sessionSegments(config, view, usage, now), columns).flatMap((s, i) =>
337
- i ? [part(SEPARATOR), ...s.parts] : s.parts,
29
+ /** Draws a turn's route line for the surface (see lib/route-line.mjs). */
30
+ export function renderRouteLine(elements, config, line, opts) {
31
+ const { columns, surface, onFallback } = opts;
32
+ return orTerminal(
33
+ surface,
34
+ (drawn) =>
35
+ isGraphical(drawn)
36
+ ? graphicalRouteLine(elements, config, line, { columns })
37
+ : terminalRouteLine(elements, config, line, { columns }),
38
+ onFallback,
338
39
  );
339
-
340
- // The row revealed under the pointer: a pin per tier, low to high, each named by what it runs ("▂▄ Haiku·high"), then
341
- // Turn off and the one- or two-row choice. No digit hotkeys, since a bare digit in an empty prompt would press them.
342
- // When the row is narrow the pins lose their model names first; Turn off and the row choice stay.
343
- function hoverSegments(config, view, actions, routing, columns) {
344
- const shown = shownConfig(config, view);
345
- const pins = (named) =>
346
- segment(
347
- 1,
348
- dim('pin '),
349
- TIERS.flatMap((tier, i) => [
350
- i ? part(' ') : null,
351
- button({
352
- key: `band-pin-${tier}`,
353
- label: `${tierBars(tier)}${named ? ` ${shortRoute(config, resolveRoute(shown, tier))}` : ''}`,
354
- onPress: () => actions.pin(tier),
355
- }),
356
- ]),
357
- );
358
- const rest = [
359
- routing
360
- ? segment(0, button({ key: 'band-manual', label: 'Turn off', onPress: () => actions.mode('manual') }))
361
- : null,
362
- segment(
363
- view.bandDetail ? 0 : 3,
364
- button({ key: 'band-detail', label: view.bandDetail ? '1 row' : '2 rows', onPress: actions.toggleDetail }),
365
- ),
366
- ].filter(Boolean);
367
- if (!routing) return rest;
368
- const named = [pins(true), ...rest];
369
- return Number.isFinite(columns) && lineWidth(named, GAP) > columns ? [pins(false), ...rest] : named;
370
- }
371
-
372
- // A subagent's model and how it was chosen: "agent ■ Haiku 5.5 ↓ from Sonnet 5.5 (Claude Code’s pick)". The square is
373
- // filled when the router moved it off Claude Code's pick, as the Usage tab's squares show it.
374
- function agentParts(agent, columns) {
375
- const color = modelColor(agent.routedModel);
376
- const moved = !agent.pass && agent.move;
377
- const name = part(`${moved ? '■' : '□'} ${modelName(agent.routedModel)}`, {
378
- bold: true,
379
- ...(color ? { color } : {}),
380
- });
381
- const glyph = { up: '↑', down: '↓' }[agent.move] ?? '↕';
382
- const why = agent.pass
383
- ? `= Claude Code’s pick: ${PASS_WHY[agent.pass]}`
384
- : moved
385
- ? `${glyph} from ${modelName(agent.coreModel)} (Claude Code’s pick)`
386
- : agent.choice === 'core'
387
- ? `= Claude Code’s pick: ${agent.failed ? 'classifier did not answer' : 'the router sent no model'}`
388
- : '= Claude Code’s pick, kept by the router';
389
- const parts = [dim('agent '), name, dim(` ${why}`)];
390
- return Number.isFinite(columns) && partsWidth(parts) > columns ? parts.slice(0, 2) : parts;
391
- }
392
-
393
- export function renderBand(
394
- { Box, Text, Button },
395
- config,
396
- view,
397
- usage,
398
- { columns, agentId, agent = null, now = Date.now() },
399
- actions,
400
- ) {
401
- const draw = (p) => (p.button ? Button(p.button) : Text({ ...p.style, children: p.text }));
402
- const row = (parts) => Box({ children: parts.map(draw) });
403
- // A subagent's model is chosen once, at spawn, and never changes between its steps. Without its record (routing
404
- // off, or the router reloaded since the spawn) only the mode is known.
405
- if (agentId)
406
- return row(
407
- agent
408
- ? agentParts(agent, columns)
409
- : [
410
- dim(
411
- config.subagentRouting === 'on'
412
- ? 'agent · model chosen at spawn'
413
- : 'agent · keeps its own model (subagent routing off)',
414
- ),
415
- ],
416
- );
417
- const width = Number.isFinite(columns) ? Math.max(0, columns - ROUTER_BUTTON) : columns;
418
- const kept = fitSegments(bandSegments(config, view, usage, actions), width);
419
- const join = (segs) => segs.flatMap((s, i) => (i ? [part(SEPARATOR), ...s.parts] : s.parts));
420
- const left = join(kept.filter((s) => !s.right));
421
- const end = join(kept.filter((s) => s.right));
422
- const pad = end.length
423
- ? Number.isFinite(width)
424
- ? Math.max(SEPARATOR.length, width - partsWidth(left) - partsWidth(end))
425
- : SEPARATOR.length
426
- : 0;
427
- const line = [...left, ...(pad ? [part(' '.repeat(pad))] : []), ...end];
428
- line.push(part(' '), button({ key: 'details', label: 'Router', plain: true, onPress: actions.open }));
429
- const routing = view.mode === 'auto' && view.phase !== 'unavailable';
430
- const second = view.bandDetail ? sessionRow(config, view, usage, columns, now) : [];
431
- const hover = fitSegments(hoverSegments(config, view, actions, routing, columns), columns, GAP);
432
- return Box({
433
- key: 'router-band',
434
- flexDirection: 'column',
435
- children: [
436
- row(line),
437
- second.length ? row(second) : null,
438
- Box({
439
- display: 'none',
440
- hover: { display: 'flex' },
441
- children: hover.flatMap((s, i) => (i ? [part(GAP), ...s.parts] : s.parts)).map(draw),
442
- }),
443
- ],
444
- });
445
40
  }
446
41
 
447
42
  export function switchToast(config, previous, next, estimate) {