@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,421 @@
1
+ // The Now tab's model: what runs next and why, what the plan and the session cost, and how full the context is. The
2
+ // model holds the readings as text, numbers and tones; the terminal draws it as rows and the graphical surfaces as cards.
3
+
4
+ import { ACTIVITIES, resolveRoute, sameRoute, TIERS } from '../../config.mjs';
5
+ import { resetText } from '../../costs.mjs';
6
+ import { decisionLines } from '../../decisions.mjs';
7
+ import {
8
+ API_ESTIMATE,
9
+ activityReading,
10
+ baselineName,
11
+ classifierLabel,
12
+ comparedModel,
13
+ costText,
14
+ diffText,
15
+ EARLY_NOTE,
16
+ formatTokens,
17
+ liveUsage,
18
+ modeLever,
19
+ percent,
20
+ percentPair,
21
+ pinCard,
22
+ pinShort,
23
+ reasonActivity,
24
+ repliesText,
25
+ routeLabel,
26
+ routeName,
27
+ routingModeOf,
28
+ sessionCost,
29
+ sessionUsage,
30
+ shortReason,
31
+ shownConfig,
32
+ signedUsd,
33
+ switchesLost,
34
+ tierBars,
35
+ uncomparedText,
36
+ usageMetrics,
37
+ usd,
38
+ whyText,
39
+ } from '../../display.mjs';
40
+ import { limitTone, savingTone } from '../tokens.mjs';
41
+ import { NO_PIN, noPinLabel } from './band.mjs';
42
+ import { plural, sentence, sinceText } from './format.mjs';
43
+
44
+ const dollars = (value) => (Number.isFinite(value) ? usd(value) : 'not reported');
45
+ const contextSuffix = (metrics) =>
46
+ Number.isFinite(metrics.nextContext)
47
+ ? `~${formatTokens(metrics.nextContext)} / ${formatTokens(metrics.window)}`
48
+ : 'no reading yet';
49
+
50
+ // "Jev 93% ≥ 90% · switch ≈ $0.48": the support for the switch the policy weighed against the bar it set, and the switch
51
+ // cost. Null without a reading.
52
+ function supportText(label, estimate) {
53
+ if (!Number.isFinite(estimate?.threshold)) return null;
54
+ const mass = Number.isFinite(estimate.upgradeMass) ? estimate.upgradeMass : estimate.downgradeMass;
55
+ const cost = Number.isFinite(estimate.taxUsd) ? ` · switch ≈ ${usd(estimate.taxUsd)}` : '';
56
+ if (!Number.isFinite(mass)) return `${label} needs ${percent(estimate.threshold)}${cost}`;
57
+ const [gave, needs] = percentPair(mass, estimate.threshold);
58
+ return `${label} ${gave} ${mass >= estimate.threshold ? '≥' : '<'} ${needs}${cost}`;
59
+ }
60
+
61
+ /**
62
+ * @typedef {object} NextPin one per tier, low to high
63
+ * @property {string} tier
64
+ * @property {string} route the route it runs, as a card names it
65
+ * @property {string | null} reading a card's: `current` on the tier that runs now, then the support
66
+ *
67
+ * @typedef {object} NextOffModel NEXT TURN with routing off or unavailable: only the model, a note and what pinning needs.
68
+ * @property {'off' | 'unavailable'} state
69
+ * @property {string} label the model and effort that run
70
+ * @property {import('./format.mjs').Words} note
71
+ * @property {import('./format.mjs').Words} pin why pinning is not offered
72
+ *
73
+ * @typedef {object} NextRoutedModel NEXT TURN with routing on.
74
+ * @property {'routed'} state
75
+ * @property {string} label the model and effort that run
76
+ * @property {string | null} tier
77
+ * @property {{ choice: string, isActivity: boolean, share: string | null, other: string | null } | null} reading
78
+ * @property {string | null} phase
79
+ * @property {string | null} why
80
+ * @property {string | null} support
81
+ * @property {string | null} override
82
+ * @property {{ name: string, from: import('./format.mjs').Words, clear: string | null } | null} mode
83
+ * @property {import('./format.mjs').Words} pinHead what the pin row offers and the model that runs now
84
+ * @property {import('./format.mjs').Words} pinNote where a model no tier routes to is chosen
85
+ * @property {NextPin[]} pins
86
+ * @property {PinControl} pinControl the pins as one Select: no pin, then one per tier, low to high
87
+ * @property {string | null} pendingPin
88
+ * @property {string} firstTurn a card's line before the first routed turn
89
+ * @property {(tier: string) => void} pick pins the next turn; the pending pin again unpins
90
+ *
91
+ * @typedef {object} PinControl
92
+ * @property {'pin'} key
93
+ * @property {string} value the pending pin's tier, or NO_PIN
94
+ * @property {{ value: string, label: string }[]} options
95
+ * @property {(value: string) => void} pick a tier pins the next turn; NO_PIN unpins
96
+ * @property {string} text the pending pin's route, or `none`, where a surface has no Select
97
+ *
98
+ * @typedef {NextOffModel | NextRoutedModel} NextModel
99
+ *
100
+ * @typedef {object} Against a part's difference against no routing
101
+ * @property {number} usd
102
+ * @property {string} text
103
+ * @property {import('../tokens.mjs').Tone | null} tone null when it is zero
104
+ * @property {string} versus
105
+ *
106
+ * @typedef {object} SessionModel SESSION: one total with the subagents, the difference, the parts on one scale.
107
+ * @property {string} head
108
+ * @property {number} running
109
+ * @property {boolean} bandDetail
110
+ * @property {() => void} toggleDetail
111
+ * @property {import('./format.mjs').Words} detailToggle the band's second row, on and off
112
+ * @property {boolean} priced
113
+ * @property {import('./format.mjs').Words | null} empty
114
+ * @property {any} strip the session's replies as cells by tier
115
+ * @property {number | null} since
116
+ * @property {string} total
117
+ * @property {string} billing
118
+ * @property {() => void} usage
119
+ * @property {{ usd: number, text: string, tone: import('../tokens.mjs').Tone, versus: string, of: string } | null} diff
120
+ * @property {string | null} note
121
+ * @property {number} scale
122
+ * @property {{ name: string, usd: number, amount: string, against: Against | null }[]} parts
123
+ * @property {[string, number][]} effortMix
124
+ * @property {boolean} lost
125
+ * @property {() => void} policy
126
+ *
127
+ * @typedef {object} ContextModel CONTEXT: the window's fill, the cache reuse, and what is behind Details.
128
+ * @property {number | null} fill
129
+ * @property {import('../tokens.mjs').Tone} fillTone
130
+ * @property {string} suffix
131
+ * @property {import('./format.mjs').Words} empty
132
+ * @property {{ tone: import('../tokens.mjs').Tone, last: { figure: string, words: string } | null, session: { figure: string, words: string } | null, empty: import('./format.mjs').Words }} cache
133
+ * @property {{ open: boolean, toggle: () => void, readings: { terminal: string[], graphical: string }, input: import('./format.mjs').Words, history: number[], tiers: string[], chart: { points: number[], labels: string[], alt: string, tone: import('../tokens.mjs').Tone } | null, range: import('./format.mjs').Words | null, empty: import('./format.mjs').Words, estimatesHead: import('./format.mjs').Words, estimates: [string, string][] }} detail
134
+ *
135
+ * @typedef {object} NowModel The Now tab: what runs next, the plan, the session and the context.
136
+ * @property {NextModel} next
137
+ * @property {string[]} decisions
138
+ * @property {{ label: string, percent: number, tone: import('../tokens.mjs').Tone, reset: string | null }[]} plan
139
+ * @property {SessionModel} session
140
+ * @property {ContextModel} context
141
+ */
142
+ /**
143
+ * @param {import('./frame.mjs').PaneContext} ctx
144
+ * @returns {NowModel}
145
+ */
146
+ export function nowOf({ config, view, usage, actions, now }) {
147
+ const cost = sessionCost(config, view, usage, now);
148
+ return {
149
+ next: nextOf(config, view, actions),
150
+ decisions: view.decisionRows?.length ? decisionLines(view.decisionRows, 5) : [],
151
+ plan: cost.limits.map((limit) => ({
152
+ label: limit.label,
153
+ percent: limit.percent,
154
+ tone: limitTone(limit.percent),
155
+ reset: resetText(limit.resetsAt, now),
156
+ })),
157
+ session: sessionOf(config, view, cost, actions, now),
158
+ context: contextOf(config, view, usage, actions, now),
159
+ };
160
+ }
161
+
162
+ // NEXT TURN. With routing off or unavailable only the model applies: no tier, activity or reason from an earlier turn.
163
+ /** @returns {NextModel} */
164
+ function nextOf(config, view, actions) {
165
+ const unavailable = view.phase === 'unavailable';
166
+ const current = view.selectedModel ?? view.nativeModel;
167
+ if (unavailable)
168
+ return {
169
+ state: 'unavailable',
170
+ label: routeLabel(view.nativeModel, view.nativeEffort),
171
+ note: { terminal: 'routing unavailable · Claude’s model', graphical: 'Routing unavailable · Claude’s model' },
172
+ pin: { terminal: 'needs routing', graphical: 'Pinning needs routing' },
173
+ };
174
+ if (view.mode !== 'auto')
175
+ return {
176
+ state: 'off',
177
+ label: routeLabel(view.nativeModel, view.nativeEffort),
178
+ note: { terminal: 'routing off · /model choice', graphical: 'Routing off · /model choice' },
179
+ pin: { terminal: 'needs routing on (o)', graphical: 'Pinning needs routing on' },
180
+ };
181
+ const mode = config.activityRouting;
182
+ const reading = mode === 'off' ? null : activityReading(view);
183
+ const shown = shownConfig(config, view);
184
+ const base = view.tier ? resolveRoute(shown, view.tier) : null;
185
+ const override =
186
+ mode === 'on' && view.activity && base && !sameRoute(resolveRoute(shown, view.tier, view.activity), base);
187
+ const { mode: routingMode, source } = routingModeOf(view);
188
+ const runsNow = current ? ` · now ${routeLabel(current, view.effort)}` : '';
189
+ const lever = modeLever(config, view);
190
+ const pending = view.pendingPin ?? null;
191
+ const supportOf = (tier) => {
192
+ const support = view.probabilities?.[tier];
193
+ return Number.isFinite(support) ? percent(support) : null;
194
+ };
195
+ return {
196
+ state: 'routed',
197
+ label: routeLabel(current, view.effort),
198
+ tier: view.tier ?? null,
199
+ reading: reading && {
200
+ choice: reading.choice,
201
+ isActivity: ACTIVITIES.includes(reading.choice),
202
+ share: reading.share || null,
203
+ other: reading.others[0] ?? null,
204
+ },
205
+ phase: view.taskPhase ? `phase ${view.taskPhase} · route activity ${view.activity ?? 'base'}` : null,
206
+ why: view.reason ? shortReason(view.reason, reasonActivity(config, view)) : null,
207
+ support: supportText(classifierLabel(config), view.estimate),
208
+ override: override ? `${whyText(config, view)} · tier route ${routeName(shown, base)}` : null,
209
+ mode:
210
+ routingMode !== 'balanced' || source === 'session'
211
+ ? {
212
+ name: routingMode,
213
+ from: {
214
+ terminal: `from ${source}${lever ? ` · ${lever} on this tier` : ''}`,
215
+ graphical: `${sentence(routingMode)} mode from ${source}${lever ? ` · ${lever} on this tier` : ''}`,
216
+ },
217
+ clear: source === 'session' ? '/router mode default clears it' : null,
218
+ }
219
+ : null,
220
+ // The pins are tier pins, not a model picker: say so, show what runs now and point to /model for the rest.
221
+ pinHead: {
222
+ terminal: `pin next turn to a tier${runsNow}`,
223
+ graphical: `Pin next turn to a tier${runsNow}`,
224
+ },
225
+ pinNote: {
226
+ terminal: 'other models: /model, with routing off',
227
+ graphical: 'Other models: /model, with routing off',
228
+ },
229
+ // The graphical pins, one per tier, low to high: the route it runs and the classifier's support on the last turn.
230
+ pins: TIERS.map((tier) => ({
231
+ tier,
232
+ // A card names the model's family and the effort, as the Routes cards word them.
233
+ route: pinCard(config, tier),
234
+ // `current` on the tier that runs now, then the support; null with neither.
235
+ reading: [tier === view.tier ? 'current' : null, supportOf(tier)].filter(Boolean).join(' · ') || null,
236
+ })),
237
+ // The terminal's pins as one Select: no pin first, then each tier named by its bars, its route and its support, the
238
+ // tier that runs now marked.
239
+ pinControl: {
240
+ key: 'pin',
241
+ value: pending ?? NO_PIN,
242
+ options: [
243
+ { value: NO_PIN, label: noPinLabel(pending) },
244
+ ...TIERS.map((tier) => ({
245
+ value: tier,
246
+ label: `${tier === view.tier ? '▶ ' : ''}${tierBars(tier)} ${pinShort(config, tier)} ${supportOf(tier) ?? '—'}`,
247
+ })),
248
+ ],
249
+ pick: (value) => (value === NO_PIN ? actions.unpin() : actions.pin(value)),
250
+ text: pending ? [tierBars(pending), pinShort(config, pending)].filter(Boolean).join(' ') : 'none',
251
+ },
252
+ pendingPin: pending,
253
+ // A card's line before the first routed turn, where the terminal shows none.
254
+ firstTurn: 'No routed turn yet — the first reply sets the route.',
255
+ // A press pins the next turn; pressing the pending pin again unpins it.
256
+ pick: (tier) => (view.pendingPin === tier ? actions.unpin() : actions.pin(tier)),
257
+ };
258
+ }
259
+
260
+ // The session's empty states: no reply carries a price, or no reply yet.
261
+ const UNPRICED_SESSION = { terminal: 'no priced replies: cost unknown', graphical: 'No priced replies: cost unknown' };
262
+ const EMPTY_SESSION = { terminal: 'no replies yet', graphical: 'No routed replies yet' };
263
+
264
+ // The estimate's billing product is context, never evidence of an invoice or measured quota use.
265
+ function billingWords(cost) {
266
+ if (cost.billing === 'plan') return `${API_ESTIMATE} · plan quota, not a charge`;
267
+ if (cost.billing === 'mixed') return `${API_ESTIMATE} · credits ${costText(cost.creditsUsd, cost.billing)}`;
268
+ return `${API_ESTIMATE} · configured rates, not an invoice`;
269
+ }
270
+
271
+ // SESSION: one total with the subagents, the difference against no routing, the main thread and the subagents on one
272
+ // scale, then the replies by tier.
273
+ function sessionOf(config, view, cost, actions, now) {
274
+ const since = liveUsage(view, view.usageSession).since;
275
+ const switches = sessionUsage(view, now).switches;
276
+ const switchCount = switches.tier + switches.activity;
277
+ const head = [
278
+ Number.isFinite(since) ? `since ${sinceText(since, now)}` : null,
279
+ cost.replies ? plural(cost.replies, 'reply', 'replies') : null,
280
+ cost.agents ? plural(cost.agents, 'agent') : null,
281
+ switchCount ? plural(switchCount, 'switch', 'switches') : null,
282
+ ].filter(Boolean);
283
+ const compared = cost.diffUsd !== null;
284
+ const r = cost.readout;
285
+ const priced = Boolean(cost.replies || cost.agents);
286
+ // A part's difference against no routing, and what it is measured against.
287
+ const against = (diff, versus) =>
288
+ diff === null ? null : { usd: diff, text: signedUsd(diff), tone: diff ? savingTone(diff) : null, versus };
289
+ return {
290
+ head: head.join(' · '),
291
+ running: view.subagentsRunning ?? 0,
292
+ bandDetail: Boolean(view.bandDetail),
293
+ toggleDetail: actions.toggleDetail,
294
+ // The band's second row, on and off: the terminal's SESSION line names the band's rows, a card the setting.
295
+ detailToggle: view.bandDetail
296
+ ? { terminal: 'band: 1 row', graphical: 'Hide session row in band' }
297
+ : { terminal: 'band: 2 rows', graphical: 'Show session row in band' },
298
+ // Replies without a list price reach the strip but not the usage record: the tiers still show, the cost cannot.
299
+ priced,
300
+ empty: priced ? null : view.strip?.cells?.length ? UNPRICED_SESSION : EMPTY_SESSION,
301
+ strip: view.strip,
302
+ since,
303
+ total: costText(cost.totalUsd, cost.billing),
304
+ billing: billingWords(cost),
305
+ usage: () => actions.usageFor('session'),
306
+ diff: compared
307
+ ? {
308
+ usd: cost.diffUsd,
309
+ text: diffText(cost.diffUsd, cost.baseUsd),
310
+ tone: savingTone(cost.diffUsd),
311
+ versus: baselineName(view, sessionUsage(view, now), cost),
312
+ of: costText(cost.baseUsd, cost.billing),
313
+ }
314
+ : null,
315
+ note: compared
316
+ ? cost.early
317
+ ? `${repliesText(cost)}: ${EARLY_NOTE}`
318
+ : null
319
+ : cost.effortOnly
320
+ ? 'effort routing on one model: no saving is estimated'
321
+ : cost.uncomparedReplies
322
+ ? `${uncomparedText(cost)}: no saving shown`
323
+ : null,
324
+ scale: Math.max(cost.mainUsd, cost.agentUsd),
325
+ parts: [
326
+ {
327
+ name: 'main',
328
+ usd: cost.mainUsd,
329
+ amount: costText(cost.mainUsd, cost.billing),
330
+ against: against(
331
+ compared && cost.replies ? cost.mainDiff : null,
332
+ comparedModel(config, view, sessionUsage(view, now)),
333
+ ),
334
+ },
335
+ ...(cost.agents
336
+ ? [
337
+ {
338
+ name: 'agents',
339
+ usd: cost.agentUsd,
340
+ amount: costText(cost.agentUsd, cost.billing),
341
+ against: against(compared ? cost.agentDiff : null, 'their picks'),
342
+ },
343
+ ]
344
+ : []),
345
+ ],
346
+ effortMix: cost.effortOnly ? cost.effortMix : [],
347
+ lost: Boolean(cost.comparable && !r.early && switchesLost(r)),
348
+ policy: () => actions.tab('policy'),
349
+ };
350
+ }
351
+
352
+ // Behind Context's Details: Claude's readings of the last reply, and the input per reply as a trend from the oldest
353
+ // reply to the latest, with its range.
354
+ function detailOf(observed, view, history, actions, comparison, metrics) {
355
+ const low = formatTokens(Math.min(...history));
356
+ const high = formatTokens(Math.max(...history));
357
+ const replies = `last ${plural(history.length, 'reply', 'replies')}`;
358
+ const tokens = (value) => formatTokens(value);
359
+ return {
360
+ open: Boolean(view.usageDetail),
361
+ toggle: actions.usageDetail,
362
+ readings: {
363
+ terminal: [
364
+ `context observed ${tokens(observed)} · estimated ${tokens(view.contextTokens)}`,
365
+ `cache read ${tokens(view.cacheRead)} · written ${tokens(view.cacheWrite)} tokens`,
366
+ `output ${tokens(view.outputTokens)} tokens on the last reply`,
367
+ ],
368
+ graphical: `Observed ${tokens(observed)} · estimated ${tokens(view.contextTokens)} · cache read ${tokens(view.cacheRead)} · written ${tokens(view.cacheWrite)} · output ${tokens(view.outputTokens)} tokens`,
369
+ },
370
+ input: { terminal: `INPUT PER REPLY · ${replies} · lowest to highest`, graphical: `Input per reply · ${replies}` },
371
+ // The input per reply and the tier each reply ran on, oldest first.
372
+ history,
373
+ tiers: view.tiers ?? [],
374
+ chart: history.length
375
+ ? {
376
+ points: history,
377
+ labels: ['Oldest', 'Latest'],
378
+ alt: `Input per reply over the ${replies}: ${low} to ${high} tokens`,
379
+ tone: /** @type {import('../tokens.mjs').Tone} */ ('accent'),
380
+ }
381
+ : null,
382
+ range: history.length ? { terminal: `${low} … ${high}`, graphical: `${low} lowest · ${high} highest` } : null,
383
+ empty: { terminal: 'no replies yet', graphical: 'No replies yet' },
384
+ estimatesHead: { terminal: 'ESTIMATES · configured API rates', graphical: 'Estimates · configured API rates' },
385
+ // The estimates the last decision weighed, as label and value.
386
+ estimates: /** @type {([string, string] | null)[]} */ ([
387
+ ['Cache hits saved', dollars(metrics.cacheBenefit)],
388
+ Number.isFinite(view.estimate?.taxUsd) ? ['Switch cost', dollars(view.estimate.taxUsd)] : null,
389
+ ...(comparison
390
+ ? [
391
+ ['Compared tiers', `${comparison.incumbent} → ${comparison.candidate}`],
392
+ ['Next-turn difference', `${signedUsd(comparison.minUsd)} to ${signedUsd(comparison.maxUsd)}`],
393
+ ['Payback', comparison.paybackTurns === null ? 'none projected' : `${comparison.paybackTurns} later turns`],
394
+ ]
395
+ : []),
396
+ ]).filter((one) => one !== null),
397
+ };
398
+ }
399
+
400
+ // CONTEXT: the window's fill on the model that runs next, and the cache reuse of the last reply and of the session.
401
+ function contextOf(config, view, usage, actions, now) {
402
+ const metrics = usageMetrics(config, view, usage);
403
+ const session = sessionUsage(view, now).observed;
404
+ const history = view.history ?? [];
405
+ return {
406
+ fill: metrics.contextBar.percent,
407
+ fillTone: metrics.contextBar.tone,
408
+ suffix: contextSuffix(metrics),
409
+ empty: { terminal: 'no reading yet', graphical: 'No reading yet' },
410
+ // The cache reuse of the last reply and of the session, each a figure and its words.
411
+ cache: {
412
+ tone: metrics.cacheBar.tone,
413
+ last: metrics.cacheBar.percent === null ? null : { figure: `${metrics.cacheBar.percent}%`, words: 'last reply' },
414
+ session: session.inputTokens
415
+ ? { figure: percent(session.cacheReadTokens / session.inputTokens), words: 'session' }
416
+ : null,
417
+ empty: { terminal: 'no reply yet', graphical: 'No reply yet' },
418
+ },
419
+ detail: detailOf(metrics.observed, view, history, actions, view.comparison, metrics),
420
+ };
421
+ }
@@ -0,0 +1,194 @@
1
+ // The Policy tab's model: each control inside the sentence it completes, its default named when the value differs. One
2
+ // Save writes it with the Routes draft.
3
+
4
+ import { defaultsFor, ROUTING_MODES, TIERS, tuningOf } from '../../config.mjs';
5
+ import { classifierLabel, percent, routingModeOf, routingModeText } from '../../display.mjs';
6
+ import { POLICY_ROWS, routingChanges } from './draft.mjs';
7
+ import { sentence, tierLabel } from './format.mjs';
8
+ import { ROUTE_MARKS } from './routes.mjs';
9
+
10
+ const TUNING_CHOICES = {
11
+ timeoutMs: [500, 1000, 1500, 3000, 5000],
12
+ downgradeVotes: [1, 2, 3],
13
+ horizon: [1, 3, 5, 10],
14
+ cashCapUsd: [0.5, 1, 2, 5],
15
+ activityMass: [0.5, 0.6, 0.7, 0.8],
16
+ };
17
+ // What `subagentRouting` does, under the router.json path: it is set in the file, not in the pane.
18
+ const SUBAGENT_LINE = {
19
+ off: 'Subagents keep their own model (subagentRouting off).',
20
+ on: 'Subagents: on. Agents that pin no model get one at spawn, kept for every step.',
21
+ };
22
+ // The same on a card, which names no router.json key.
23
+ const SUBAGENT_CARD = {
24
+ off: 'Subagents keep their own model.',
25
+ on: 'Subagents that pin no model get one at spawn, kept for every step.',
26
+ };
27
+
28
+ // A Select's data over TUNING_CHOICES[key], with a saved value outside them kept as the first option; picking that one
29
+ // changes nothing. `text` is what a terminal without Select shows.
30
+ export function choiceOf(key, value, format, pick) {
31
+ const values = TUNING_CHOICES[key].includes(value) ? TUNING_CHOICES[key] : [value, ...TUNING_CHOICES[key]];
32
+ return {
33
+ key,
34
+ value: String(value),
35
+ text: format(value),
36
+ options: values.map((v) => ({ value: String(v), label: format(v) })),
37
+ pick: (picked) => (TUNING_CHOICES[key].includes(Number(picked)) ? pick(Number(picked)) : undefined),
38
+ };
39
+ }
40
+
41
+ // What the profile's routing mode does, under its control on the Policy tab.
42
+ const MODE_HINT = {
43
+ cost: 'a cheaper model or one effort level less where a turn allows',
44
+ balanced: 'each tier runs its route as configured',
45
+ quality: 'one effort level more, or the tier above, where a turn allows',
46
+ };
47
+ // A sentence a card starts with a capital, as the terminal writes it.
48
+ const sayWords = (words) => ({ terminal: words, graphical: sentence(words) });
49
+ // "default 5 turns" beside a changed value in the terminal, "Default 5 turns" on a card.
50
+ const defaultOf = (value) => ({ terminal: `default ${value}`, graphical: `Default ${value}` });
51
+ // The Policy form's cards on a graphical surface, in order. Switching up holds no control, only its derived line.
52
+ const POLICY_GROUPS = ['Routing mode', 'Switching down', 'Switching up', 'Activities', 'Credits'];
53
+ // Each tuning value's card and help line on a graphical surface; the label is POLICY_ROWS'.
54
+ export const POLICY_FORM = {
55
+ downgradeVotes: { group: 'Switching down', help: 'Agreeing turns before a cheaper model runs' },
56
+ horizon: { group: 'Switching down', help: 'A cache write must pay back within this many turns' },
57
+ activityMass: {
58
+ group: 'Activities',
59
+ help: 'Below this certainty a new task runs its tier’s model; a continuation keeps it',
60
+ },
61
+ cashCapUsd: { group: 'Credits', help: 'The most one cold cache write may cost, on a model that bills credits' },
62
+ };
63
+
64
+ /**
65
+ * @typedef {object} Control a Select's data: its value, options, and what a surface without Select shows
66
+ * @property {string} key
67
+ * @property {string} value
68
+ * @property {string} text
69
+ * @property {{ value: string, label: import('./format.mjs').Words }[]} options
70
+ * @property {(value: string) => void} pick
71
+ *
72
+ * @typedef {object} PolicyField
73
+ * @property {string} key
74
+ * @property {string} group a card's group
75
+ * @property {string} label
76
+ * @property {Control} control
77
+ * @property {boolean} [changed]
78
+ * @property {import('./format.mjs').Words | null} [default] its default, where the value differs
79
+ * @property {import('./format.mjs').Words} [hint]
80
+ * @property {string} [help] a card's help line
81
+ * @property {string} [note]
82
+ * @property {import('./format.mjs').Words | null} [session]
83
+ *
84
+ * @typedef {object} PolicyModel The Policy tab: each control with its words, marks and defaults.
85
+ * @property {import('./routes.mjs').RouteMark} unsaved
86
+ * @property {PolicyField} mode
87
+ * @property {PolicyField} baseline
88
+ * @property {Record<import('./draft.mjs').TuneKey, PolicyField>} tune
89
+ * @property {import('./format.mjs').Words} up
90
+ * @property {string} activitiesHint
91
+ * @property {string} creditsHint
92
+ * @property {{ title: string, fields: PolicyField[], notes: string[], warnings: string[] }[]} groups
93
+ * @property {{ label: string, press: () => void }} reset
94
+ * @property {{ path: string, title: string, copy: { label: import('./format.mjs').Words, press: () => void } | null }} file
95
+ * @property {import('./format.mjs').Words} subagents
96
+ */
97
+ /**
98
+ * @param {import('./frame.mjs').PaneContext} ctx
99
+ * @returns {PolicyModel}
100
+ */
101
+ export function policyOf({ config, view, actions }) {
102
+ const changes = routingChanges(config, view);
103
+ const { draft, tuning, policy } = changes;
104
+ const preset = defaultsFor(config.provider);
105
+ const defaults = tuningOf(preset);
106
+ const { upgradeBase, upgradeSlope } = config.policy;
107
+ const credits = Object.values(config.models).some((model) => model.billing === 'credits');
108
+ const active = routingModeOf(view);
109
+ const creditsHelp = credits
110
+ ? 'on a model that bills credits'
111
+ : 'no model in router.json bills credits, so this has no effect';
112
+ const tune = /** @type {Record<import('./draft.mjs').TuneKey, PolicyField>} */ (
113
+ Object.fromEntries(
114
+ POLICY_ROWS.map(([key, label, format]) => {
115
+ const form = POLICY_FORM[key];
116
+ return [
117
+ key,
118
+ {
119
+ key,
120
+ group: form.group,
121
+ label,
122
+ control: choiceOf(key, tuning[key], format, (value) => actions.tune(key, value)),
123
+ changed: policy.includes(key),
124
+ default: tuning[key] === defaults[key] ? null : defaultOf(format(defaults[key])),
125
+ // A setting with no effect says so in its help line.
126
+ help: key === 'cashCapUsd' && !credits ? sentence(creditsHelp) : form.help,
127
+ },
128
+ ];
129
+ }),
130
+ )
131
+ );
132
+ const mode = {
133
+ key: 'routing-mode',
134
+ group: 'Routing mode',
135
+ label: 'Mode',
136
+ control: {
137
+ key: 'routing-mode',
138
+ value: config.mode,
139
+ text: config.mode,
140
+ options: ROUTING_MODES.map((m) => ({ value: m, label: { terminal: m, graphical: sentence(m) } })),
141
+ pick: (m) => actions.routingMode(m),
142
+ },
143
+ note: 'saved at once',
144
+ hint: { terminal: MODE_HINT[config.mode], graphical: `${sentence(MODE_HINT[config.mode])} · saved at once` },
145
+ // A session or project mode runs instead of the profile's.
146
+ session:
147
+ active.source === 'session' || active.source === 'project'
148
+ ? sayWords(`this session runs ${routingModeText(view)}`)
149
+ : null,
150
+ };
151
+ const baseline = {
152
+ key: 'baseline',
153
+ group: 'Routing mode',
154
+ label: 'Start tier',
155
+ control: {
156
+ key: 'baseline',
157
+ value: draft.baselineTier,
158
+ text: draft.baselineTier,
159
+ options: TIERS.map((tier) => ({ value: tier, label: { terminal: tier, graphical: sentence(tier) } })),
160
+ pick: (tier) => actions.baseline(tier),
161
+ },
162
+ changed: changes.baseline,
163
+ default:
164
+ draft.baselineTier === preset.baselineTier
165
+ ? null
166
+ : { terminal: `default ${preset.baselineTier}`, graphical: `Default ${tierLabel(preset.baselineTier)}` },
167
+ hint: sayWords('when the session’s model is no tier’s model'),
168
+ };
169
+ const up = `needs ${classifierLabel(config)} support of ${percent(upgradeBase)}, up to ${percent(upgradeBase + upgradeSlope)} as the switch costs more`;
170
+ const fields = [mode, baseline, ...Object.values(tune)];
171
+ return {
172
+ unsaved: ROUTE_MARKS.edited,
173
+ mode,
174
+ baseline,
175
+ tune,
176
+ up: sayWords(up),
177
+ activitiesHint: 'else a new task runs its tier’s model; a continuation keeps it',
178
+ creditsHint: creditsHelp,
179
+ groups: POLICY_GROUPS.map((title) => ({
180
+ title,
181
+ fields: fields.filter((field) => field.group === title),
182
+ notes: title === 'Switching up' ? [sayWords(up).graphical] : [],
183
+ // A session or project mode runs instead of the profile's.
184
+ warnings: title === 'Routing mode' && mode.session ? [mode.session.graphical] : [],
185
+ })),
186
+ reset: { label: 'Reset policy to defaults', press: actions.resetPolicy },
187
+ file: {
188
+ path: view.configPath ?? 'profile router.json',
189
+ title: 'Settings file',
190
+ copy: view.configPath ? { label: { terminal: 'copy', graphical: 'Copy path' }, press: actions.copyPath } : null,
191
+ },
192
+ subagents: { terminal: SUBAGENT_LINE[config.subagentRouting], graphical: SUBAGENT_CARD[config.subagentRouting] },
193
+ };
194
+ }