@alexeiled/claude-router 1.23.1 → 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 (81) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +62 -1
  3. package/README.md +39 -7
  4. package/docs/architecture.md +27 -4
  5. package/docs/auto-engine.md +152 -0
  6. package/docs/configuration.md +47 -3
  7. package/docs/evaluation.md +222 -3
  8. package/docs/native-router.md +11 -3
  9. package/docs/providers.md +28 -0
  10. package/docs/router-band.svg +124 -133
  11. package/docs/router-pane-classifier.svg +24 -23
  12. package/docs/router-pane-now.svg +9 -7
  13. package/docs/router-pane-policy.svg +4 -4
  14. package/docs/router-pane-routes.svg +8 -8
  15. package/docs/router-pane-usage-whatif.svg +14 -14
  16. package/docs/router-pane-usage.svg +20 -20
  17. package/docs/routing-modes.md +13 -4
  18. package/docs/user-guide.md +79 -19
  19. package/hooks/native-router.mjs +1194 -215
  20. package/lib/activity-stats.mjs +23 -4
  21. package/lib/activity.mjs +7 -5
  22. package/lib/auto-engine.mjs +414 -0
  23. package/lib/auto-route.mjs +253 -0
  24. package/lib/band.mjs +35 -440
  25. package/lib/classifier-client.mjs +12 -8
  26. package/lib/config-file.mjs +7 -2
  27. package/lib/config.mjs +64 -15
  28. package/lib/cost.mjs +5 -1
  29. package/lib/costs.mjs +4 -2
  30. package/lib/decisions.mjs +80 -5
  31. package/lib/display.mjs +69 -20
  32. package/lib/facts.mjs +30 -0
  33. package/lib/modes.mjs +8 -4
  34. package/lib/panel.mjs +75 -2163
  35. package/lib/policy.mjs +7 -6
  36. package/lib/providers.mjs +7 -0
  37. package/lib/replay-trace.mjs +550 -0
  38. package/lib/replay.mjs +718 -0
  39. package/lib/route-line.mjs +46 -0
  40. package/lib/route.mjs +35 -21
  41. package/lib/savings.mjs +14 -3
  42. package/lib/subagents.mjs +41 -11
  43. package/lib/subcommands.mjs +60 -0
  44. package/lib/ui/fallback.mjs +22 -0
  45. package/lib/ui/graphical/band.mjs +256 -0
  46. package/lib/ui/graphical/charts.mjs +163 -0
  47. package/lib/ui/graphical/classifier.mjs +153 -0
  48. package/lib/ui/graphical/frame.mjs +227 -0
  49. package/lib/ui/graphical/kit.mjs +156 -0
  50. package/lib/ui/graphical/meter.mjs +25 -0
  51. package/lib/ui/graphical/now.mjs +353 -0
  52. package/lib/ui/graphical/policy.mjs +56 -0
  53. package/lib/ui/graphical/routes.mjs +264 -0
  54. package/lib/ui/graphical/squares.mjs +29 -0
  55. package/lib/ui/graphical/usage.mjs +376 -0
  56. package/lib/ui/model/band.mjs +439 -0
  57. package/lib/ui/model/classifier.mjs +308 -0
  58. package/lib/ui/model/draft.mjs +62 -0
  59. package/lib/ui/model/format.mjs +41 -0
  60. package/lib/ui/model/frame.mjs +359 -0
  61. package/lib/ui/model/now.mjs +390 -0
  62. package/lib/ui/model/policy.mjs +194 -0
  63. package/lib/ui/model/routes.mjs +392 -0
  64. package/lib/ui/model/usage-agents.mjs +311 -0
  65. package/lib/ui/model/usage-breakdown.mjs +237 -0
  66. package/lib/ui/model/usage-shared.mjs +58 -0
  67. package/lib/ui/model/usage.mjs +330 -0
  68. package/lib/ui/terminal/band.mjs +220 -0
  69. package/lib/ui/terminal/classifier.mjs +142 -0
  70. package/lib/ui/terminal/frame.mjs +169 -0
  71. package/lib/ui/terminal/kit.mjs +133 -0
  72. package/lib/ui/terminal/now.mjs +300 -0
  73. package/lib/ui/terminal/policy.mjs +52 -0
  74. package/lib/ui/terminal/routes.mjs +167 -0
  75. package/lib/ui/terminal/usage.mjs +363 -0
  76. package/lib/ui/terminal/wrap.mjs +37 -0
  77. package/lib/ui/tokens.mjs +106 -0
  78. package/lib/usage.mjs +5 -5
  79. package/lib/view.mjs +5 -2
  80. package/package.json +3 -2
  81. package/types/index.d.ts +15 -0
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) {
@@ -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
  }