@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
@@ -0,0 +1,363 @@
1
+ // The Usage tab as terminal rows, drawn from the model in ui/model/usage.mjs: the period
2
+ // buttons and scope, the cost ledger, the tokens, the breakdown, the trend or What if, what is worth a look, the
3
+ // subagents, the footer and Delete history.
4
+ import { sparkline } from '../../display.mjs';
5
+ import { dimLines, pack } from './wrap.mjs';
6
+
7
+ // The cost table's columns: label, cost, difference, no routing.
8
+ const COST_LABEL = 26;
9
+ const COST_AMOUNT = 8;
10
+ const COST_DIFF = 15;
11
+ const COST_BASE = 12;
12
+ // The ledger's amount column; the breakdown's name column; bars at full scale.
13
+ const LEDGER_AMOUNT = 9;
14
+ const NAME = 20;
15
+ const BAR = 22;
16
+ const AGENT_TYPE = 19;
17
+ const AGENT_SQUARES = 12;
18
+ // The breakdown's row: the open mark, the name, replies, cost and vs yours; "mostly on" or the share only where it fits.
19
+ const BREAKDOWN = 4 + 20 + 8 + 10 + 15;
20
+ const TAIL = 23;
21
+ // A route beside an insight needs this many columns.
22
+ const INSIGHT_ROUTE = 90;
23
+ // The subagent rows: the open mark, the type, its squares, agents, cost, and against Claude Code's pick with its arrow;
24
+ // a narrower pane drops the cost column and the reason.
25
+ const AGENT_ROW = 4 + AGENT_TYPE + AGENT_SQUARES + 3 + 9 + 11;
26
+ // A long All period keeps its last days of the agents-per-day trend, as many as the row has room for.
27
+ const TREND_DAYS = AGENT_ROW - 30;
28
+ const clipped = (text, width) => (text.length < width ? text : `${text.slice(0, width - 2)}…`);
29
+
30
+ // A difference in its savings colour; muted is a dim dash.
31
+ const differenceText = (ui, diff, width) =>
32
+ diff.tone === 'muted'
33
+ ? ui.dim(diff.text.padStart(width))
34
+ : ui.text(diff.text.padStart(width), ui.color(diff.tone) ? { color: ui.color(diff.tone) } : {});
35
+ // Text in a model's colour; a model of no known family (muted) is plain.
36
+ const colored = (ui, tone, text) => ui.text(text, tone === 'muted' ? {} : { color: ui.color(tone) });
37
+
38
+ /**
39
+ * @param {any} ui the terminal kit
40
+ * @param {import('../model/usage.mjs').UsageModel} model
41
+ * @param {{ columns: number | null }} opts
42
+ */
43
+ export function terminalUsage(ui, model, { columns }) {
44
+ const out = [periodRow(ui, model.period), scopeLine(ui, model.scope), ui.text(' ')];
45
+ out.push(...summaryLines(ui, model.summary, columns));
46
+ if (model.stats) out.push(ui.text(' '), ui.dim(` ${model.stats.text}`));
47
+ if (model.breakdown) {
48
+ out.push(ui.text(' '), ...breakdownLines(ui, model.breakdown, columns), ui.text(' '));
49
+ const { compare } = model;
50
+ const toggle = ui.Button({
51
+ key: compare.toggle.key,
52
+ label: compare.toggle.label.terminal,
53
+ hotkey: compare.toggle.hotkey,
54
+ onPress: compare.toggle.press,
55
+ });
56
+ out.push(
57
+ ...(compare.on
58
+ ? [
59
+ ui.line(ui.head(compare.head), ui.dim(` · ${compare.hint.terminal} `), toggle),
60
+ ...compareLines(ui, compare),
61
+ ]
62
+ : trendLines(ui, model.trend, toggle)),
63
+ ...insightLines(ui, model.insights, columns),
64
+ );
65
+ }
66
+ out.push(
67
+ ui.text(' '),
68
+ ...agentLines(ui, model.agents, columns),
69
+ ui.text(' '),
70
+ ...pack(model.notes.pieces, Math.min(model.notes.width, columns ?? model.notes.width), ' ').map((line) =>
71
+ ui.dim(line),
72
+ ),
73
+ );
74
+ out.push(ui.text(' '), deleteLine(ui, model.delete));
75
+ return out;
76
+ }
77
+
78
+ const periodRow = (ui, period) =>
79
+ ui.line(
80
+ ...period.options.flatMap((option) => [
81
+ ui.Button({
82
+ key: option.key,
83
+ label: option.label,
84
+ ...(option.hotkey ? { hotkey: option.hotkey } : {}),
85
+ variant: option.selected ? 'primary' : 'secondary',
86
+ onPress: () => period.pick(option.value),
87
+ }),
88
+ ' ',
89
+ ]),
90
+ ui.dim(` ${period.hint}`),
91
+ );
92
+
93
+ const scopeLine = (ui, scope) =>
94
+ scope.model
95
+ ? ui.line(
96
+ ui.dim(scope.text),
97
+ scope.model.tier ? ui.tier(scope.model.tier, scope.model.text) : ui.text(scope.model.text),
98
+ )
99
+ : ui.dim(scope.text);
100
+
101
+ function summaryLines(ui, summary, columns) {
102
+ if (summary.empty) return [ui.dim(summary.empty.text)];
103
+ const { compared, headline, header } = summary;
104
+ const row = (one) => {
105
+ const style = one.strong ? { weight: 'semibold' } : {};
106
+ return ui.line(
107
+ ui.cell(COST_LABEL, ui.text(one.label, style)),
108
+ ui.text(one.amount.padStart(COST_AMOUNT), style),
109
+ one.diff
110
+ ? ui.text(one.diff.text.padStart(COST_DIFF), {
111
+ ...style,
112
+ ...(ui.color(one.diff.tone) ? { color: ui.color(one.diff.tone) } : {}),
113
+ })
114
+ : null,
115
+ one.base !== null ? ui.dim(one.base.padStart(COST_BASE)) : null,
116
+ );
117
+ };
118
+ const part = (one) =>
119
+ ui.line(
120
+ ui.cell(COST_LABEL, ui.dim(` ${one.label}`)),
121
+ ''.padStart(COST_AMOUNT),
122
+ differenceText(ui, one.diff, COST_DIFF),
123
+ one.note ? ui.dim(` ${one.note.text}`) : null,
124
+ );
125
+ const out = [
126
+ headline.compared
127
+ ? ui.line(
128
+ ui.text(headline.text, { weight: 'semibold', color: ui.color(headline.tone) }),
129
+ ` ${headline.versus}`,
130
+ headline.early ? ui.text(` ${headline.early}`, { color: ui.color('warning') }) : null,
131
+ )
132
+ : ui.dim(headline.text),
133
+ ui.text(' '),
134
+ ui.line(
135
+ ui.cell(COST_LABEL, ''),
136
+ ui.dim(header.cost.terminal.padStart(COST_AMOUNT)),
137
+ header.diff ? ui.dim(header.diff.terminal.padStart(COST_DIFF)) : null,
138
+ header.base ? ui.dim(header.base.terminal.padStart(COST_BASE)) : null,
139
+ ),
140
+ ...summary.rows.map((one) => (one.kind === 'part' ? part(one) : row(one))),
141
+ ui.dim('─'.repeat(COST_LABEL + COST_AMOUNT + (compared ? COST_DIFF + COST_BASE : 0))),
142
+ row(summary.total),
143
+ summary.credits ? row(summary.credits) : null,
144
+ ].filter(Boolean);
145
+ if (summary.legacy) out.push(...dimLines(ui, summary.legacy.text, columns));
146
+ if (summary.lost) out.push(ui.lostLine(summary.lost.press));
147
+ return out;
148
+ }
149
+
150
+ // A breakdown row's name: an activity as its verb, a tier as its bars, a model or a route by name.
151
+ function groupName(ui, name) {
152
+ if (name.kind === 'none') return ui.dim(name.text);
153
+ if (name.kind === 'activity') return ui.activity(name.text);
154
+ if (name.kind === 'tier') return ui.bars(name.text);
155
+ return ui.text(name.text);
156
+ }
157
+
158
+ function breakdownLines(ui, breakdown, columns) {
159
+ const { group } = breakdown;
160
+ const out = [
161
+ ui.line(
162
+ ui.head(group.head),
163
+ ...group.options.flatMap((option) => [
164
+ ui.Button({
165
+ key: option.key,
166
+ label: option.label.terminal,
167
+ ...(option.hotkey ? { hotkey: option.hotkey } : {}),
168
+ variant: option.selected ? 'primary' : 'secondary',
169
+ onPress: () => group.pick(option.value),
170
+ }),
171
+ ' ',
172
+ ]),
173
+ ui.dim(` ${group.hint}`),
174
+ ),
175
+ ];
176
+ if (breakdown.empty) return [...out, ui.dim(` ${breakdown.empty.text}`)];
177
+ const { header } = breakdown;
178
+ const tail = !Number.isFinite(columns) || columns >= BREAKDOWN + TAIL;
179
+ out.push(
180
+ ui.dim(
181
+ ` ${''.padEnd(NAME)}${header.replies.terminal.padStart(8)}${header.cost.terminal.padStart(10)}${header.diff ? header.diff.terminal.padStart(15) : ''}${tail ? ` ${header.tail}` : ''}`,
182
+ ),
183
+ );
184
+ const numbers = (one) => [
185
+ `${one.replies.padStart(8)}${one.cost.padStart(10)}`,
186
+ one.diff ? differenceText(ui, one.diff, 15) : null,
187
+ ];
188
+ for (const row of breakdown.rows) {
189
+ out.push(
190
+ ui.line(
191
+ ' ',
192
+ ui.Button({ key: row.key, label: row.open ? '▾' : '▸', plain: true, onPress: row.toggle }),
193
+ ' ',
194
+ ui.cell(NAME, groupName(ui, row.name)),
195
+ ...numbers(row),
196
+ tail && row.tail ? ui.dim(` ${row.tail}`) : null,
197
+ ),
198
+ );
199
+ for (const child of row.children)
200
+ out.push(ui.line(' ', ui.cell(NAME - 2, groupName(ui, child.name)), ...numbers(child)));
201
+ if (row.note) out.push(...dimLines(ui, ` ${row.note.text}`, columns));
202
+ }
203
+ return out;
204
+ }
205
+
206
+ function compareLines(ui, compare) {
207
+ if (compare.unavailable) return [ui.dim(compare.unavailable)];
208
+ return [
209
+ ...compare.rows.map((row) => {
210
+ const filled = Math.max(0, Math.min(BAR, Math.round(row.fill * BAR)));
211
+ return ui.line(
212
+ ' ',
213
+ ui.cell(22, ui.text(row.label, row.strong ? { weight: 'semibold' } : {})),
214
+ ui.text('█'.repeat(filled), { color: ui.color(row.tone) }),
215
+ ' '.repeat(BAR - filled),
216
+ row.cost.padStart(LEDGER_AMOUNT),
217
+ row.diff ? differenceText(ui, row.diff, 11) : '',
218
+ );
219
+ }),
220
+ ui.dim(` ${compare.note.text}`),
221
+ ];
222
+ }
223
+
224
+ function trendLines(ui, trend, toggle) {
225
+ if (trend.single) return [ui.line(ui.head(trend.head), ui.dim(` ${trend.single} `), toggle)];
226
+ return [
227
+ ui.line(
228
+ ui.head(`${trend.head} `),
229
+ ui.trend({ points: trend.points, labels: trend.chart.labels, alt: trend.chart.alt, tone: trend.chart.tone }),
230
+ ui.dim(` ${trend.peak.terminal} `),
231
+ toggle,
232
+ ),
233
+ ];
234
+ }
235
+
236
+ function insightLines(ui, insights, columns) {
237
+ if (!insights) return [];
238
+ return [
239
+ ui.text(' '),
240
+ ui.line(ui.head(insights.head), ui.dim(` · ${insights.hint.terminal}`)),
241
+ ...insights.items.map((item) => insightLine(ui, item, columns)),
242
+ ];
243
+ }
244
+
245
+ function insightLine(ui, item, columns) {
246
+ const button = (b) => (b ? ui.Button({ key: b.key, label: b.label, onPress: b.press }) : null);
247
+ if (item.kind === 'switch') return ui.line(` ${item.text} `, button(item.button));
248
+ return ui.line(
249
+ ' ',
250
+ ...(item.activity ? [ui.activity(item.activity), ui.dim(' · ')] : []),
251
+ item.tier ? ui.bars(item.tier) : ui.dim(item.notRouted.terminal),
252
+ ` ${item.text}`,
253
+ item.route && (!Number.isFinite(columns) || columns >= INSIGHT_ROUTE) ? ui.dim(` · ${item.route}`) : null,
254
+ ' ',
255
+ button(item.button),
256
+ );
257
+ }
258
+
259
+ const squareParts = (ui, squares) => squares.runs.map((run) => colored(ui, run.tone, run.text));
260
+
261
+ // The names go under the strip where both do not fit on one row.
262
+ const split = (summary, columns) => {
263
+ const namesWidth = summary.names.reduce((n, { text }, i) => n + (i ? 3 : 0) + text.length, 0);
264
+ return Number.isFinite(columns) && 2 + summary.strip.width + 2 + namesWidth > columns;
265
+ };
266
+
267
+ function agentLines(ui, agents, columns) {
268
+ const out = [ui.line(ui.head(agents.head), ui.dim(agents.scope))];
269
+ const undated = agents.undated ? [ui.dim(` ${agents.undated.text}`)] : [];
270
+ if (agents.empty)
271
+ return [
272
+ ...out,
273
+ ui.dim(` ${agents.empty.text}`),
274
+ ...undated,
275
+ ...(agents.older ? [ui.dim(` ${agents.older}`)] : []),
276
+ ];
277
+ const { summary } = agents;
278
+ const narrow = Number.isFinite(columns) && columns < AGENT_ROW;
279
+ const strip = squareParts(ui, summary.strip);
280
+ const names = summary.names.flatMap((one, i) => [i ? ui.dim(' · ') : null, colored(ui, one.tone, one.text)]);
281
+ out.push(
282
+ ...(split(summary, columns)
283
+ ? [ui.line(' ', ...strip), ui.line(' ', ...names)]
284
+ : [ui.line(' ', ...strip, ' ', ...names)]),
285
+ ui.line(` ${summary.total}`, ui.dim(' · '), summary.moved.terminal, ui.dim(' · '), summary.kept.terminal),
286
+ );
287
+ if (summary.verdict)
288
+ out.push(
289
+ summary.verdict.priced
290
+ ? ui.line(
291
+ ' ',
292
+ ui.text(summary.verdict.text, { weight: 'semibold', color: ui.color(summary.verdict.tone) }),
293
+ summary.verdict.versus,
294
+ ui.dim(summary.verdict.on),
295
+ )
296
+ : ui.dim(` ${summary.verdict.text}`),
297
+ );
298
+ if (agents.trend)
299
+ out.push(
300
+ ui.line(
301
+ ` ${agents.trend.label} `,
302
+ ui.text(sparkline(agents.trend.values.slice(-TREND_DAYS)), { weight: 'semibold' }),
303
+ ui.dim(` ${agents.trend.peak.terminal}`),
304
+ ),
305
+ );
306
+ out.push(...undated);
307
+ const cost = (one) => (one.tone === 'muted' ? ui.dim(one.text.padStart(9)) : one.text.padStart(9));
308
+ const pick = (one) => (one.dash ? ui.dim(one.text.padStart(9)) : differenceText(ui, one, 11));
309
+ for (const group of agents.groups) {
310
+ out.push(
311
+ ui.text(' '),
312
+ ui.line(ui.text(` ${group.head}`, { weight: 'semibold' }), ui.dim(` · ${group.hint.terminal}`)),
313
+ );
314
+ if (group.header)
315
+ out.push(
316
+ ui.dim(
317
+ ` ${group.header.type.padEnd(AGENT_TYPE)}${group.header.agents.padEnd(AGENT_SQUARES + 3)}${narrow ? '' : group.header.cost.padStart(9)}${group.header.pick.padStart(9)}`,
318
+ ),
319
+ );
320
+ for (const row of group.rows) {
321
+ out.push(
322
+ ui.line(
323
+ ' ',
324
+ ui.Button({ key: row.key, label: row.open ? '▾' : '▸', plain: true, onPress: row.toggle }),
325
+ ' ',
326
+ ui.cell(AGENT_TYPE, clipped(row.name.terminal, AGENT_TYPE)),
327
+ ui.cell(
328
+ AGENT_SQUARES,
329
+ ui.line(...squareParts(ui, row.squares), row.squares.rest ? ui.dim(row.squares.rest) : null),
330
+ ),
331
+ row.agents.padStart(3),
332
+ narrow ? null : cost(row.cost),
333
+ row.pick ? pick(row.pick) : null,
334
+ row.why && !narrow ? ui.dim(` ${row.why.terminal}`) : null,
335
+ ),
336
+ );
337
+ for (const child of row.children)
338
+ out.push(
339
+ ui.line(
340
+ ' ',
341
+ ui.cell(17, colored(ui, child.tone, child.text)),
342
+ ui.cell(15, ui.dim(child.detail)),
343
+ narrow ? null : cost(child.cost),
344
+ child.pick ? pick(child.pick) : null,
345
+ ),
346
+ );
347
+ if (row.notes) out.push(...dimLines(ui, ` ${row.notes.text}`, columns));
348
+ }
349
+ }
350
+ out.push(ui.text(' '), ...agents.legend.flatMap((one) => dimLines(ui, ` ${one.text}`, columns)));
351
+ return out;
352
+ }
353
+
354
+ function deleteLine(ui, del) {
355
+ if (!del.confirming)
356
+ return ui.Button({ key: del.ask.key, label: del.ask.label, dimColor: true, onPress: del.ask.press });
357
+ return ui.line(
358
+ ui.text(`${del.question} `, { color: ui.color('warning') }),
359
+ ui.Button({ key: del.yes.key, label: del.yes.label, variant: 'primary', onPress: del.yes.press }),
360
+ ' ',
361
+ ui.Button({ key: del.no.key, label: del.no.label, onPress: del.no.press }),
362
+ );
363
+ }
@@ -0,0 +1,37 @@
1
+ // Word wrapping for terminal rows, which Ink's own wrap would do without the row's indent.
2
+ import { isFiniteNumber } from '../tokens.mjs';
3
+
4
+ /**
5
+ * `pieces` packed into lines of at most `width` cells after `indent`.
6
+ * @param {[string, string][]} pieces each piece and the joiner that follows it
7
+ * @param {number} width
8
+ * @param {string} indent
9
+ */
10
+ export function pack(pieces, width, indent) {
11
+ const lines = [];
12
+ let line = '';
13
+ let joiner = '';
14
+ for (const [text, next] of pieces) {
15
+ if (line && indent.length + line.length + joiner.length + text.length > width) {
16
+ lines.push(indent + line);
17
+ line = text;
18
+ } else line += (line ? joiner : '') + text;
19
+ joiner = next;
20
+ }
21
+ return line ? [...lines, indent + line] : lines;
22
+ }
23
+
24
+ /**
25
+ * A dim sentence wrapped by words to a narrow pane, keeping its indent.
26
+ * @param {any} ui the terminal kit
27
+ * @param {string} text
28
+ * @param {number | null} columns
29
+ */
30
+ export const dimLines = (ui, text, columns) => {
31
+ const indent = /^ */.exec(text)?.[0] ?? '';
32
+ const words = text
33
+ .trim()
34
+ .split(' ')
35
+ .map((word) => /** @type {[string, string]} */ ([word, ' ']));
36
+ return (isFiniteNumber(columns) ? pack(words, columns, indent) : [text]).map((line) => ui.dim(line));
37
+ };
@@ -0,0 +1,106 @@
1
+ // Every colour the router draws lives in this file, each by the tone it means. Tone is the one vocabulary a renderer
2
+ // colours with: a terminal draws an ANSI name or a hex; a graphical surface (desktop, mobile, vscode) draws a Claude
3
+ // Code theme key, so the colour follows the user's theme, or a mid-lightness hex where no theme key reads as a tier;
4
+ // an Svg draws a hex.
5
+
6
+ /** @typedef {'micro' | 'low' | 'medium' | 'high'} Tier */
7
+ /** @typedef {'haiku' | 'sonnet' | 'opus' | 'fable'} Family A model family, which colours a subagent's squares. */
8
+ /** @typedef {'primary' | 'muted' | 'accent' | 'success' | 'warning' | 'danger' | 'activity' | `tier:${Tier}` | `model:${Family}`} Tone */
9
+ /** @typedef {'terminal' | 'desktop' | 'mobile' | 'vscode'} Surface */
10
+ // The theme keys each tone draws in, so a terminal and a graphical surface follow the user's theme; change them here and
11
+ // nowhere else. Activity has no theme key: it is Claude Code's orange as a hex, a darker one on a graphical surface.
12
+ const THEME_TONE = {
13
+ primary: 'text',
14
+ muted: 'subtle',
15
+ accent: 'suggestion',
16
+ success: 'success',
17
+ warning: 'warning',
18
+ danger: 'error',
19
+ };
20
+ const TERMINAL = { ...THEME_TONE, activity: '#d77757' };
21
+
22
+ // Cost order, cheapest first, so the colors read as a scale. Hex values: every surface draws them.
23
+ export const TIER_COLOR = { micro: '#5fd7af', low: '#5f9fe0', medium: '#d7af5f', high: '#e0708a' };
24
+ // A subagent's square by the model family it ran on, apart from the tier colors so a model never reads as a tier.
25
+ const MODEL_COLOR = { haiku: '#c3e88d', sonnet: '#f78c6c', opus: '#c792ea', fable: '#89ddff' };
26
+
27
+ // A mode chip's ground on the terminal; its text is a tone.
28
+ export const CHIP_BACKGROUND = '#2a3040';
29
+
30
+ export const GRAPHICAL_TONE = { ...THEME_TONE, activity: '#c4693f' };
31
+
32
+ // The quiet track behind a bar and the unlit bars of a meter: a grey that reads on a white and a dark ground.
33
+ export const GRAPHICAL_TRACK = 'rgba(127,127,127,0.18)';
34
+ export const GRAPHICAL_UNLIT = 'rgba(127,127,127,0.35)';
35
+
36
+ // Mid-lightness, so each reads at 3:1 or better on both a white and a #1f1f1f ground.
37
+ const GRAPHICAL_TIER = { micro: '#2a9d78', low: '#3b82c4', medium: '#a67c1a', high: '#c8506b' };
38
+
39
+ // The classifier-working colour of the tier meter: an Svg cannot take a theme key, so it is a hex, held to the same 3:1.
40
+ export const GRAPHICAL_PENDING = '#5b7fd9';
41
+
42
+ // Each model family's colour on a graphical surface, held to the same 3:1; the terminal's MODEL_COLOR is for a dark
43
+ // ground.
44
+ export const GRAPHICAL_MODEL = { haiku: '#4f9a3a', sonnet: '#c8643c', opus: '#9161c9', fable: '#2f8bb8' };
45
+
46
+ // The tones an Svg draws in, as hex: an Svg cannot take a theme key.
47
+ const SVG_TONE = { accent: GRAPHICAL_PENDING, muted: '#8b93a7', success: '#2a9d78', warning: '#a67c1a' };
48
+
49
+ /**
50
+ * A tone as the hex an Svg draws it in; accent for a tone without one.
51
+ * @param {Tone} tone
52
+ * @returns {string}
53
+ */
54
+ export function svgColor(tone) {
55
+ if (tone.startsWith('tier:')) return GRAPHICAL_TIER[tone.slice(5)];
56
+ if (tone.startsWith('model:')) return GRAPHICAL_MODEL[tone.slice(6)];
57
+ return SVG_TONE[tone] ?? SVG_TONE.accent;
58
+ }
59
+
60
+ /**
61
+ * A difference against no routing as a tone: a saving in the success tone, a cost above in the warning tone, zero plain.
62
+ * @param {number} usd
63
+ * @returns {Tone}
64
+ */
65
+ export const savingTone = (usd) => (usd < 0 ? 'success' : usd > 0 ? 'warning' : 'primary');
66
+
67
+ // A plan window's tone by how much is used: success, then warning past 75%, danger past 90%.
68
+ /** @returns {Tone} */
69
+ export const limitTone = (percent) => (percent >= 90 ? 'danger' : percent >= 75 ? 'warning' : 'success');
70
+
71
+ /**
72
+ * The tone of the family a model id belongs to; undefined for a model of no known family.
73
+ * @param {string | null | undefined} id
74
+ * @returns {Tone | undefined}
75
+ */
76
+ export const modelTone = (id) => {
77
+ const family = Object.keys(MODEL_COLOR).find((name) => String(id ?? '').includes(name));
78
+ return family ? /** @type {Tone} */ (`model:${family}`) : undefined;
79
+ };
80
+
81
+ /**
82
+ * Whether `value` is a usable number: Number.isFinite, as a guard so `columns` narrows from `number | null`.
83
+ * @param {unknown} value
84
+ * @returns {value is number}
85
+ */
86
+ export const isFiniteNumber = (value) => Number.isFinite(value);
87
+
88
+ export const isGraphical = (surface) => surface !== undefined && surface !== 'terminal';
89
+
90
+ /**
91
+ * @param {Tone} tone
92
+ * @param {string} [surface]
93
+ * @returns {string | undefined}
94
+ */
95
+ export function toneColor(tone, surface) {
96
+ const graphical = isGraphical(surface);
97
+ if (tone.startsWith('tier:')) {
98
+ const tier = tone.slice(5);
99
+ return (graphical ? GRAPHICAL_TIER : TIER_COLOR)[tier];
100
+ }
101
+ if (tone.startsWith('model:')) {
102
+ const family = tone.slice(6);
103
+ return (graphical ? GRAPHICAL_MODEL : MODEL_COLOR)[family];
104
+ }
105
+ return (graphical ? GRAPHICAL_TONE : TERMINAL)[tone];
106
+ }
package/lib/usage.mjs CHANGED
@@ -63,7 +63,7 @@ export function daysBefore(ms, days) {
63
63
  }
64
64
 
65
65
  export function emptyUsage() {
66
- return { version: USAGE_VERSION, since: null, days: {} };
66
+ return { version: USAGE_VERSION, since: /** @type {number | null} */ (null), days: {} };
67
67
  }
68
68
 
69
69
  const emptyDay = () => ({
@@ -95,7 +95,7 @@ export function replyEntry({
95
95
  usage,
96
96
  observedUsd = /** @type {number | null} */ (null),
97
97
  }) {
98
- if (!reply && !(Number.isFinite(observedUsd) && observedUsd >= 0))
98
+ if (!reply && !(typeof observedUsd === 'number' && Number.isFinite(observedUsd) && observedUsd >= 0))
99
99
  throw new Error('Observed usage requires a known price');
100
100
  const input = usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens;
101
101
  return {
@@ -139,8 +139,8 @@ export function recordUsage(record, entries, { switched = null, now }) {
139
139
  if (switched === 'tier' || switched === 'activity') ended.switches[switched] += 1;
140
140
  days[dayKey(now)] = ended;
141
141
  const cutoff = daysBefore(now, RETAIN_DAYS);
142
- for (const key of Object.keys(days)) if (key < cutoff) delete days[key];
143
- return { version: USAGE_VERSION, since: record.since ?? now, days };
142
+ const kept = Object.fromEntries(Object.entries(days).filter(([date]) => date >= cutoff));
143
+ return { version: USAGE_VERSION, since: record.since ?? now, days: kept };
144
144
  }
145
145
 
146
146
  // The record's days with the entries added. Only the days they touch are copied: the readouts add the running turn's
@@ -251,7 +251,7 @@ export function prunedUsage(entries, now, max = MAX_RECORDS) {
251
251
  const over = entries.length - gone.size - max;
252
252
  if (over > 0)
253
253
  for (const [key] of dated
254
- .filter(([key]) => !gone.has(key))
254
+ .filter(([name]) => !gone.has(name))
255
255
  .sort(([, a], [, b]) => (a < b ? -1 : a > b ? 1 : 0))
256
256
  .slice(0, over))
257
257
  gone.add(key);
package/lib/view.mjs CHANGED
@@ -1,6 +1,9 @@
1
1
  // The view the band and pane draw from: its initial shape and the patches built from pure inputs. Pure: the hook
2
2
  // writes the view to $.state.
3
3
 
4
+ // Whether routing decides the next turn: on, and not unavailable. Off or unavailable, only Claude Code's model applies.
5
+ export const isRouting = (view) => view.mode === 'auto' && view.phase !== 'unavailable';
6
+
4
7
  // Replies kept for the input trend behind the Now tab's details.
5
8
  export const HISTORY = 30;
6
9
  // The session strip's most cells. Once it is full, neighbouring cells merge, so each covers twice the replies and the
@@ -127,7 +130,7 @@ const routeOf = (decision) => ({ tier: decision.tier ?? null, model: decision.mo
127
130
  // replies by tier, `none` for one routing did not serve, and `from` is when the first reply arrived. A full strip
128
131
  // merges each pair of cells first. The view lives as long as the Claude Code process, so after a restart the strip
129
132
  // starts again while the session's usage record goes on: `from` tells the two apart.
130
- export function addToStrip(strip, tier, at = null) {
133
+ export function addToStrip(strip, tier, at = /** @type {number | null} */ (null)) {
131
134
  const key = tier ?? 'none';
132
135
  const from = strip?.from ?? at;
133
136
  let per = strip?.per ?? 1;
@@ -154,7 +157,7 @@ export function mergePairs(cells) {
154
157
  }
155
158
 
156
159
  // The view patch for a main reply's usage that arrived `at` (ms). `tier` is the routed tier that served it, else null.
157
- export function responseMetrics(view, response, tier, at = null) {
160
+ export function responseMetrics(view, response, tier, at = /** @type {number | null} */ (null)) {
158
161
  const usage = response.usage;
159
162
  const counters = usage ? [usage.input_tokens, usage.cache_read_input_tokens, usage.cache_creation_input_tokens] : [];
160
163
  const inputTokens =
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexeiled/claude-router",
3
- "version": "1.24.0",
3
+ "version": "1.25.1",
4
4
  "description": "Native Claude Code model and effort routing with Anthropic, DeepSeek, z.ai, MiniMax, MiMo and Kimi defaults, custom provider profiles, and classifier advice.",
5
5
  "license": "MIT",
6
6
  "author": "Alexei Ledenev",
@@ -30,13 +30,15 @@
30
30
  "scripts": {
31
31
  "setup": "npm ci --prefix tools --ignore-scripts",
32
32
  "test": "node --test --test-timeout=8000 test/*.test.mjs experiments/mod-router/scripts/*.test.mjs",
33
- "check": "tools/node_modules/.bin/biome check lib scripts test hooks types .claude-plugin package.json biome.json tsconfig.json tools/package.json tools/package-lock.json experiments/mod-router",
33
+ "test:ci": "node --test --test-timeout=8000 --test-reporter=spec --test-reporter-destination=stdout --test-reporter=./.github/test-reporter.mjs --test-reporter-destination=stdout test/*.test.mjs experiments/mod-router/scripts/*.test.mjs",
34
+ "check": "tools/node_modules/.bin/biome check --error-on-warnings lib scripts test hooks types .claude-plugin package.json biome.json tsconfig.json tools/package.json tools/package-lock.json experiments/mod-router",
34
35
  "typecheck": "tools/node_modules/.bin/tsc -p tsconfig.json",
35
36
  "validate": "claude plugin validate .claude-plugin/plugin.json && claude plugin validate .claude-plugin/marketplace.json",
36
37
  "test:plugin": "bash scripts/plugin-test.sh",
37
38
  "test:providers": "node experiments/mod-router/scripts/provider-acceptance.mjs",
38
39
  "format": "tools/node_modules/.bin/biome format --write .",
39
40
  "docs:images": "node scripts/render-doc-images.mjs",
41
+ "docs:desktop-images": "node scripts/render-desktop-images.mjs",
40
42
  "prices:check": "node scripts/check-prices.mjs",
41
43
  "docs:modes": "node scripts/mode-matrix.mjs",
42
44
  "probe:results": "node scripts/probe-results.mjs",
package/types/index.d.ts CHANGED
@@ -264,6 +264,9 @@ declare module 'claude-code' {
264
264
  usageDetail?: boolean;
265
265
  help?: boolean;
266
266
  bandDetail?: boolean;
267
+ // The subagents with a record that are running, by `$.agent.list()` id, and how many: a change redraws the band's rows.
268
+ subagentIds?: string[];
269
+ subagentsRunning?: number;
267
270
  notice?: string | null;
268
271
  }
269
272
  interface RouterPolicyState {
@@ -311,16 +314,30 @@ declare module 'claude-code' {
311
314
  requestedPin: RouterTier | null;
312
315
  } | null;
313
316
  ineligible: string[];
317
+ // Models an API error held out of routing (lib/failover.mjs), by model id: the error and when the hold ends.
318
+ held?: Record<string, { error: string; until: number }>;
314
319
  // Your model's simulated cache for routing vs your model: the last prompt's tokens, when, whether that reply ran
315
320
  // on your route, and the model and effort it was kept for. Null at the start and after a compaction.
316
321
  yours?: { total: number; at: number; onYours: boolean; model: string; effort: string | null } | null;
317
322
  engineModel?: string;
318
323
  suspended?: boolean;
319
324
  }
325
+ // What a route line records, under the id `$.ui.place` was given: the route that ran, its tier and why, the activity,
326
+ // and the policy's estimate (lib/route-line.mjs).
327
+ interface RouterLine {
328
+ model: string;
329
+ effort: string | number | null;
330
+ tier: RouterTier | null;
331
+ reason: string;
332
+ activity: RouterActivity | null;
333
+ reasonActivity: RouterActivity | null;
334
+ estimate: RouterEstimate | null;
335
+ }
320
336
  interface PluginState {
321
337
  router: {
322
338
  view: RouterView;
323
339
  loops: StateFamily<RouterLoop>;
340
+ lines: StateFamily<RouterLine>;
324
341
  };
325
342
  }
326
343
  }