@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
@@ -0,0 +1,359 @@
1
+ // The pane's frame as data: the provider profile, the warnings under the tabs, how to add a classifier's credentials,
2
+ // the title's state, the save bar and the help.
3
+
4
+ import { endpointSettings, resolveRoute, TIERS } from '../../config.mjs';
5
+ import {
6
+ classifierLabel,
7
+ classifierState,
8
+ classifierStatus,
9
+ GATEWAY_CLEANUP,
10
+ GATEWAY_SETTINGS,
11
+ missingCredentials,
12
+ modelName,
13
+ routeName,
14
+ unavailableReason,
15
+ } from '../../display.mjs';
16
+ import { isSameModel } from '../../route.mjs';
17
+ import { isRouting } from '../../view.mjs';
18
+ import { isGraphical } from '../tokens.mjs';
19
+ import { POLICY_ROWS, routingChanges } from './draft.mjs';
20
+ import { plural, sentence, tierLabel } from './format.mjs';
21
+
22
+ // Routes and Policy edit one draft and save together; Classifier saves each pick at once.
23
+ const DRAFT_TABS = ['routes', 'policy'];
24
+
25
+ // The provider profile's names on a card; any other profile shows its own key.
26
+ const PROVIDER_NAME = { deepseek: 'DeepSeek', zai: 'z.ai', minimax: 'MiniMax', mimo: 'MiMo', kimi: 'Kimi' };
27
+
28
+ // The provider profile and the file it reads, under the tabs; null on Anthropic.
29
+ function profileOf(config, view) {
30
+ if (!config.provider || config.provider === 'anthropic') return null;
31
+ const path = view.configPath ?? config.nativePath;
32
+ const name = PROVIDER_NAME[config.provider] ?? config.provider;
33
+ return {
34
+ terminal: `profile ${[config.provider, path].filter(Boolean).join(' · ')}`,
35
+ graphical: `Profile: ${[name, path].filter(Boolean).join(' · ')}`,
36
+ };
37
+ }
38
+
39
+ /**
40
+ * A warning under the tab row. `text` is as the terminal draws it, which pads it; `action` is a Button the notice carries.
41
+ * @typedef {object} Notice
42
+ * @property {import('../tokens.mjs').Tone} tone
43
+ * @property {string} text
44
+ * @property {{ key: string, label: string, hotkey: string, press: (press: any) => void } | null} [action]
45
+ * @property {boolean} [graphicalOnly] drawn on a graphical surface only, where the header has no room for it
46
+ */
47
+
48
+ // The warnings that apply to the next turn, drawn once under the tab row on every tab: an ignored project config, a
49
+ // native fallback, and classifier credentials that are missing. They matter only while routing is on. The graphical
50
+ // pane has no header text for an unavailable router, so its reason joins them, and its title states the classifier's
51
+ // error only where no notice does. `statesClassifier` says whether one does.
52
+ function noticesOf({ config, view, actions }, tab, keyHelp) {
53
+ const unavailable = view.phase === 'unavailable';
54
+ /** @type {Notice[]} */
55
+ const notices = [];
56
+ // In place of the credentials notice a graphical Set up's card states their lack; an Edit's card, with nothing missing,
57
+ // states nothing.
58
+ let statesClassifier =
59
+ Boolean(keyHelp) && keyHelp.id === config.classifier && Boolean(noticedCredentials(config, view));
60
+ const warn = (text, extra = {}) => notices.push({ tone: 'warning', text, ...extra });
61
+ if (unavailable) {
62
+ warn(unavailableReason(view), { graphicalOnly: true });
63
+ if (view.error === GATEWAY_SETTINGS) for (const line of GATEWAY_CLEANUP) warn(line, { graphicalOnly: true });
64
+ }
65
+ // Missing credentials have their own notice below, with Set up; this one would say them a second time.
66
+ if (!unavailable && view.error && !['missing-key', 'missing-account'].includes(view.error)) {
67
+ warn(classifierStatus(config, view.error), { graphicalOnly: true });
68
+ statesClassifier = true;
69
+ }
70
+ if (!isRouting(view)) return { notices, statesClassifier };
71
+ const current = view.selectedModel ?? view.nativeModel;
72
+ const missing = noticedCredentials(config, view);
73
+ if (view.projectError) warn(`Ignored: ${view.projectError}`);
74
+ if (view.actualModel && current && !isSameModel(current, view.actualModel))
75
+ warn(`! served by ${modelName(view.actualModel)} · native fallback`);
76
+ if (missing && keyHelp?.id !== config.classifier) {
77
+ // On the Classifier tab the notice leaves k to the tab: the active card's Set up on a graphical surface, the
78
+ // Credentials row's Edit on the terminal.
79
+ warn(`${classifierStatus(config, missing)}, keeping the model`, {
80
+ action:
81
+ tab === 'classifier'
82
+ ? null
83
+ : { key: 'key', label: 'Set up', hotkey: 'k', press: (press) => actions.key(press, config.classifier) },
84
+ });
85
+ statesClassifier = true;
86
+ }
87
+ return { notices, statesClassifier };
88
+ }
89
+
90
+ // How to add a classifier's credentials where the surface cannot open `/plugin configure`'s dialog: one zsh line that
91
+ // asks for each option (the secret hidden, nothing in the shell's history) and saves them with `claude plugin
92
+ // configure --values-stdin`, or the dialog from a terminal's claude. Null for a classifier that needs none.
93
+ const OPTION_PROMPT = {
94
+ typesafe_api_key: 'Jev key',
95
+ cloudflare_api_token: 'Cloudflare token',
96
+ cloudflare_account_id: 'Cloudflare account ID',
97
+ openai_api_key: 'OpenAI key',
98
+ };
99
+ // A word as zsh reads it: unchanged when it holds nothing the shell treats specially, otherwise single-quoted.
100
+ const shellWord = (word) => (/^[\w@.:/+-]+$/.test(word) ? word : `'${word.replaceAll("'", "'\\''")}'`);
101
+
102
+ /**
103
+ * @param {any} config
104
+ * @param {string} id the classifier
105
+ * @param {string} pluginId as `claude plugin configure` takes it
106
+ * @param {{ edit?: boolean }} [opts] changing a credential that is there, not adding a missing one
107
+ */
108
+ export function keyHelpOf(config, id, pluginId, { edit = false } = {}) {
109
+ const entry = config.classifiers[id];
110
+ if (!entry) return null;
111
+ const options = [entry.keyOption, ...endpointSettings(entry.endpoint)].filter(Boolean);
112
+ if (!options.length) return null;
113
+ const names = options.map((_, i) => 'KABCDEFG'[i]);
114
+ const reads = options.flatMap((option, i) => {
115
+ const secret = option === entry.keyOption;
116
+ const prompt = OPTION_PROMPT[option] ?? (secret ? 'Key' : option);
117
+ // A hidden read leaves the cursor on its line: the next prompt starts on a fresh one.
118
+ return [
119
+ `read -r${secret ? 's' : ''} "${names[i]}?${prompt}: "`,
120
+ ...(secret && i < options.length - 1 ? ['echo'] : []),
121
+ ];
122
+ });
123
+ const json = `{${options.map((option) => `"${option}":"%s"`).join(',')}}`;
124
+ const values = names.map((name) => `"$${name}"`).join(' ');
125
+ const verb = edit ? 'Change' : 'Add';
126
+ const plugin = shellWord(pluginId);
127
+ return {
128
+ id,
129
+ edit,
130
+ title: options.includes('cloudflare_account_id')
131
+ ? `${verb} the Cloudflare token and account ID`
132
+ : `${verb} the ${entry.label} key`,
133
+ sentence:
134
+ 'This app can’t open the plugin settings dialog, so add it from a terminal: this zsh line asks for it without showing the key or keeping it in your history.',
135
+ command: `${reads.join(' && ')} && printf '${json}' ${values} | claude plugin configure ${plugin} --values-stdin; echo; unset ${names.join(' ')}`,
136
+ alternative: `Or run claude in a terminal and type /plugin configure ${pluginId}`,
137
+ // A plugin id with no marketplace may be refused by the CLI; the full one is in /plugin.
138
+ note: pluginId.includes('@')
139
+ ? null
140
+ : 'If the command says the plugin is not found, use the full name shown by /plugin (name@marketplace).',
141
+ // Whether the reload reaches this session's credentials is not known, so Done is the way out.
142
+ reload: 'Then run /reload-plugins and press Done.',
143
+ };
144
+ }
145
+
146
+ // The open key help with its Copy command and Done: an Edit's until Done, a Set up's while the classifier it is for
147
+ // still lacks a credential. `view.keyHelp` is `{ id, edit }`.
148
+ function keyHelpCardOf({ config, view, actions, pluginId }) {
149
+ const { id, edit = false } = view.keyHelp ?? {};
150
+ if (!id || !config.classifiers[id] || (!edit && !missingCredentials(config, view, id))) return null;
151
+ const help = keyHelpOf(config, id, pluginId, { edit });
152
+ return (
153
+ help && {
154
+ ...help,
155
+ copy: { key: 'key-help-copy', label: 'Copy command', press: actions.copyKeyHelp },
156
+ done: { key: 'key-help-done', label: 'Done', press: actions.keyHelpDone },
157
+ }
158
+ );
159
+ }
160
+
161
+ // The graphical title's short state: why routing is unavailable, the classifier's state, or, where a notice already
162
+ // states the classifier's error, a short pointer to it.
163
+ /** @returns {{ tone: import('../tokens.mjs').Tone, text: string }} */
164
+ function titleStatus(config, view, statesClassifier) {
165
+ if (view.phase === 'unavailable') return { tone: 'warning', text: 'unavailable · Claude’s model is kept' };
166
+ if (statesClassifier) return { tone: 'warning', text: `${classifierLabel(config)} needs attention` };
167
+ return classifierState(config, view);
168
+ }
169
+
170
+ // The classifier's missing credentials the notices name under the tab row: only while routing is on and available.
171
+ const noticedCredentials = (config, view) =>
172
+ isRouting(view) ? missingCredentials(config, view, config.classifier) : null;
173
+
174
+ // Which tabs hold an unsaved draft.
175
+ function unsavedTabs(config, view) {
176
+ const changes = routingChanges(config, view);
177
+ return {
178
+ routes: changes.tiers.length + changes.cells.length + Number(changes.mode) > 0,
179
+ policy: changes.policy.length + Number(changes.baseline) > 0,
180
+ };
181
+ }
182
+
183
+ // Success for a write or its undo, danger for a refused write, warning for everything else that needs a look.
184
+ /** @returns {import('../tokens.mjs').Tone} */
185
+ const noticeTone = (notice) =>
186
+ /^Not saved/.test(notice) ? 'danger' : /^(Saved|Undid|Path copied)/.test(notice) ? 'success' : 'warning';
187
+
188
+ /**
189
+ * What each pane tab's model and the frame read: the config, the router view and its usage, the pane's actions, the
190
+ * models the route editor offers, the pane's width (null for none), the clock, the surface and the plugin's id.
191
+ * @typedef {object} PaneContext
192
+ * @property {any} config
193
+ * @property {any} view
194
+ * @property {any} usage
195
+ * @property {any} actions
196
+ * @property {string[]} modelOptions
197
+ * @property {number | null} columns
198
+ * @property {number} now
199
+ * @property {string | undefined} surface
200
+ * @property {string} pluginId
201
+ */
202
+
203
+ // The one place for commit state on every tab: the unsaved Routes and Policy draft with Save and Discard (the
204
+ // router.json lines it writes on those two tabs, a count elsewhere), the last notice, and Undo for the last write.
205
+ // Each changed setting is its router.json key and the before and after the terminal lists, and a card's label and
206
+ // values.
207
+ function saveBarOf({ config, view, actions }, tab) {
208
+ const changes = routingChanges(config, view);
209
+ const rows = [];
210
+ const row = (key, label, before, after) => rows.push({ key, label, before, after });
211
+ for (const tier of changes.tiers)
212
+ row(
213
+ `routes.${tier}`,
214
+ `${tierLabel(tier)} route`,
215
+ routeName(config, config.routes[tier]),
216
+ routeName(config, changes.draft.routes[tier]),
217
+ );
218
+ const tierWords = (tier) => ({ terminal: tier, graphical: tierLabel(tier) });
219
+ if (changes.baseline)
220
+ row('baselineTier', 'Start tier', tierWords(config.baselineTier), tierWords(changes.draft.baselineTier));
221
+ const draft = { ...config, ...changes.draft };
222
+ const cellName = (c, activity, tier) =>
223
+ c.activities[activity]?.[tier]
224
+ ? routeName(c, resolveRoute(c, tier, activity))
225
+ : { terminal: 'no override', graphical: 'No override' };
226
+ for (const [activity, tier] of changes.cells)
227
+ row(
228
+ `activities.${activity}.${tier}`,
229
+ `${activity} at ${tierLabel(tier)}`,
230
+ cellName(config, activity, tier),
231
+ cellName(draft, activity, tier),
232
+ );
233
+ const modeWords = (mode) => ({ terminal: mode, graphical: sentence(mode) });
234
+ if (changes.mode)
235
+ row(
236
+ 'activityRouting',
237
+ 'Activity routing',
238
+ modeWords(config.activityRouting),
239
+ modeWords(changes.draft.activityRouting),
240
+ );
241
+ for (const [key, label, format, field] of POLICY_ROWS.filter(([name]) => changes.policy.includes(name)))
242
+ row(field, label, format(changes.saved[key]), format(changes.tuning[key]));
243
+ const { count } = changes;
244
+ const listed = DRAFT_TABS.includes(tab);
245
+ const confirms = Boolean(view.lastWrite && view.notice?.startsWith('Saved'));
246
+ return {
247
+ count,
248
+ // On Routes and Policy the changes are listed; elsewhere only counted.
249
+ listed,
250
+ rows,
251
+ pending: {
252
+ tone: /** @type {import('../tokens.mjs').Tone} */ ('warning'),
253
+ text: `● ${count} unsaved routing change${count === 1 ? '' : 's'}`,
254
+ },
255
+ elsewhere: 'listed on Routes and Policy',
256
+ title: 'Unsaved changes',
257
+ hint: listed ? plural(count, 'change') : `${plural(count, 'change')}, listed on Routes and Policy`,
258
+ columns: { label: 'Setting', before: 'Before', after: 'After' },
259
+ save: { key: 'save-routing', label: 'Save', hotkey: 's', press: actions.saveRouting },
260
+ discard: { key: 'discard-routing', label: 'Discard', hotkey: 'd', press: actions.discardRouting },
261
+ notice: view.notice ? { tone: noticeTone(view.notice), text: view.notice } : null,
262
+ // Undo beside a notice that confirms the write, else on its own line under the write it undoes.
263
+ undo: view.lastWrite
264
+ ? {
265
+ key: 'undo',
266
+ label: 'Undo',
267
+ hotkey: 'u',
268
+ press: actions.undo,
269
+ confirms,
270
+ last: `Last change: ${view.lastWrite.label}`,
271
+ }
272
+ : null,
273
+ };
274
+ }
275
+ // What the numbers mean, behind `?`: the same paragraphs under the terminal's head and on a card. The tier paragraph
276
+ // draws the tiers' bars inline on the terminal and as their meters, low to high, on a card.
277
+ const HELP = {
278
+ head: 'ABOUT THESE NUMBERS',
279
+ title: 'About the router',
280
+ paragraphs: [
281
+ { text: '≈$ is tokens × configured API rates in router.json (list/custom).' },
282
+ { text: 'These are estimates, not invoices or measured plan-quota savings.' },
283
+ {
284
+ text: 'No routing: your model on the main thread, Claude Code’s pick per agent, same tokens and output length. Answer quality is not measured.',
285
+ },
286
+ {
287
+ text: 'For the whole session cost, with side calls such as titles and compaction that the router does not see, run /cost.',
288
+ },
289
+ { text: 'Plan bars are Claude Code’s 5-hour and 7-day readings.' },
290
+ {
291
+ text: {
292
+ terminal: 'Tiers show as bars ▂▄▆█, low to high; a route never moves past 80% of its window.',
293
+ graphical: 'Tiers show as rising bars, low to high; a route never moves past 80% of its window.',
294
+ },
295
+ tiers: TIERS,
296
+ },
297
+ ],
298
+ };
299
+
300
+ /**
301
+ * @typedef {object} SaveBar the one place for commit state: the unsaved draft, the last notice, Undo
302
+ * @property {number} count
303
+ * @property {boolean} listed the changes are listed (Routes and Policy), not only counted
304
+ * @property {{ key: string, label: string, before: import('./format.mjs').Words, after: import('./format.mjs').Words }[]} rows
305
+ * @property {{ tone: import('../tokens.mjs').Tone, text: string }} pending
306
+ * @property {string} elsewhere
307
+ * @property {string} title
308
+ * @property {string} hint
309
+ * @property {{ label: string, before: string, after: string }} columns
310
+ * @property {{ key: string, label: string, hotkey: string, press: () => void }} save
311
+ * @property {{ key: string, label: string, hotkey: string, press: () => void }} discard
312
+ * @property {{ tone: import('../tokens.mjs').Tone, text: string } | null} notice
313
+ * @property {{ key: string, label: string, hotkey: string, press: () => void, confirms: boolean, last: string } | null} undo
314
+ *
315
+ * @typedef {object} FrameModel Everything the pane draws around a tab.
316
+ * @property {string} mode the router's mode
317
+ * @property {{ reason: string, cleanup: string[] } | null} unavailable why routing is unavailable
318
+ * @property {{ tone: import('../tokens.mjs').Tone, text: string, repeated: boolean }} classifier its state, and whether the notices say it again
319
+ * @property {boolean} helpOpen
320
+ * @property {typeof HELP | null} help
321
+ * @property {import('./format.mjs').Words | null} profile
322
+ * @property {ReturnType<typeof keyHelpCardOf>} keyHelp
323
+ * @property {Notice[]} notices
324
+ * @property {{ tone: import('../tokens.mjs').Tone, text: string }} status the graphical title's short state
325
+ * @property {Record<string, boolean>} unsaved which tabs hold an unsaved draft
326
+ * @property {SaveBar} bar
327
+ */
328
+ /**
329
+ * Everything the pane draws around a tab, as data: the warnings, the key help card, the title's state, the save bar and
330
+ * the help.
331
+ * @param {PaneContext} ctx
332
+ * @param {string} tab the shown tab's id
333
+ * @returns {FrameModel}
334
+ */
335
+ export function frameOf(ctx, tab) {
336
+ const { config, view } = ctx;
337
+ // Only a graphical surface cannot open `/plugin configure`'s dialog.
338
+ const keyHelp = isGraphical(ctx.surface) ? keyHelpCardOf(ctx) : null;
339
+ const { notices, statesClassifier } = noticesOf(ctx, tab, keyHelp);
340
+ const unavailable = view.phase === 'unavailable';
341
+ const state = classifierState(config, view);
342
+ // The notices under the tab row name missing credentials with their remedy; the terminal's header points there.
343
+ const missing = noticedCredentials(config, view);
344
+ return {
345
+ mode: view.mode,
346
+ unavailable: unavailable
347
+ ? { reason: unavailableReason(view), cleanup: view.error === GATEWAY_SETTINGS ? GATEWAY_CLEANUP : [] }
348
+ : null,
349
+ classifier: { ...state, repeated: Boolean(missing && state.text === classifierStatus(config, missing)) },
350
+ helpOpen: Boolean(view.help),
351
+ help: view.help ? HELP : null,
352
+ profile: profileOf(config, view),
353
+ keyHelp,
354
+ notices,
355
+ status: titleStatus(config, view, statesClassifier),
356
+ unsaved: unsavedTabs(config, view),
357
+ bar: saveBarOf(ctx, tab),
358
+ };
359
+ }