@alexeiled/claude-router 1.20.1 → 1.21.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.
package/lib/panel.mjs CHANGED
@@ -15,39 +15,47 @@ import {
15
15
  tuningOf,
16
16
  } from './config.mjs';
17
17
  import { effortSharesCache, routeEffort } from './cost.mjs';
18
+ import { periodCost, resetText } from './costs.mjs';
18
19
  import {
19
20
  activityReading,
20
- activityVerb,
21
- COST_PART,
22
21
  classifierLabel,
23
22
  classifierStatus,
24
23
  comparedModel,
24
+ costText,
25
+ diffText,
25
26
  formatTokens,
26
27
  GATEWAY_CLEANUP,
27
28
  GATEWAY_SETTINGS,
29
+ gaugeCells,
30
+ limitColor,
28
31
  liveUsage,
29
32
  missingCredentials,
30
33
  missingText,
34
+ modeLever,
31
35
  modelColor,
32
36
  modelName,
33
- observedUsageText,
34
37
  percent,
35
38
  percentPair,
36
39
  probeOf,
40
+ reasonActivity,
37
41
  recordedModels,
38
42
  routeLabel,
39
43
  routeName,
40
- routingAnswer,
41
44
  routingModeOf,
42
45
  routingModeText,
43
46
  savingsColor,
47
+ sessionCost,
44
48
  sessionUsage,
49
+ shortReason,
50
+ shortRoute,
45
51
  shownConfig,
46
52
  signedUsd,
47
53
  sparkline,
48
54
  switchesLost,
49
55
  TIER_COLOR,
56
+ tierBars,
50
57
  unavailableReason,
58
+ uncomparedText,
51
59
  unpricedLine,
52
60
  usageMetrics,
53
61
  usd,
@@ -55,7 +63,7 @@ import {
55
63
  yourModel,
56
64
  } from './display.mjs';
57
65
  import { cellForModel, isSameModel } from './route.mjs';
58
- import { modelSpec, readout } from './savings.mjs';
66
+ import { modelSpec } from './savings.mjs';
59
67
  import {
60
68
  modelTotals,
61
69
  PASS_LABEL,
@@ -129,8 +137,7 @@ export function routeDraftOf(config, view) {
129
137
  return { ...structuredClone(base), base };
130
138
  }
131
139
 
132
- const dollars = (value) => (Number.isFinite(value) ? `$${value.toFixed(3)}` : 'not reported');
133
- const difference = (value) => `${value < 0 ? '−' : '+'}$${Math.abs(value).toFixed(3)}`;
140
+ const dollars = (value) => (Number.isFinite(value) ? usd(value) : 'not reported');
134
141
  // The host and port as the request sees them: user info before an `@` is not the host. An endpoint that does not
135
142
  // parse, such as one with a placeholder in its host, shows as written up to its path, and is not this machine.
136
143
  function urlOf(endpoint) {
@@ -160,7 +167,9 @@ function kit({ Box, Text, Button, Select }) {
160
167
  dim: (children) => text(children, { dimColor: true }),
161
168
  head: (children) => text(children, { bold: true, color: 'cyan' }),
162
169
  tier: (tier, children = tier) => text(children, { bold: true, color: TIER_COLOR[tier] }),
163
- activity: (activity) => text(activityVerb(activity), ACTIVITY_STYLE),
170
+ // A tier as its bars, the way the band and Now draw it.
171
+ bars: (tier) => text(tierBars(tier), { color: TIER_COLOR[tier] }),
172
+ activity: (activity) => text(activity, ACTIVITY_STYLE),
164
173
  // One row of mixed parts; strings become plain Text, nulls are dropped.
165
174
  line: (...parts) =>
166
175
  Box({
@@ -188,17 +197,17 @@ export function renderPanel(
188
197
  const ui = kit(elements);
189
198
  const tab = TABS.some(([id]) => id === view.tab) ? view.tab : 'now';
190
199
  const body = { now: nowTab, routes: routesTab, policy: policyTab, classifier: classifierTab, usage: usageTab }[tab];
200
+ // No Close button: Esc and the pane's own close dismiss it.
191
201
  return ui.Box({
192
202
  flexDirection: 'column',
193
203
  children: [
194
204
  ...header(ui, config, view, tab, actions),
205
+ ...(view.help ? helpLines(ui) : []),
195
206
  ...(config.provider && config.provider !== 'anthropic'
196
- ? [ui.dim(`Provider: ${config.provider} · ${view.configPath ?? config.nativePath ?? ''}`)]
207
+ ? [ui.dim(`profile ${[config.provider, view.configPath ?? config.nativePath].filter(Boolean).join(' · ')}`)]
197
208
  : []),
198
209
  ...body(ui, config, view, usage, actions, modelOptions, columns, now),
199
- ...(view.help ? helpLines(ui) : []),
200
210
  ...statusBar(ui, config, view, tab, actions),
201
- ui.Button({ key: 'close', label: 'Close', hotkey: 'q', role: 'dismiss', onPress: actions.close }),
202
211
  ],
203
212
  });
204
213
  }
@@ -208,12 +217,7 @@ export function renderPanel(
208
217
  function routingState(ui, config, view, actions) {
209
218
  if (view.phase === 'unavailable')
210
219
  return [
211
- ui.line(
212
- ui.head('ROUTING'),
213
- ' ',
214
- ui.text('unavailable', { color: 'yellow' }),
215
- ui.dim(' Claude’s model is kept'),
216
- ),
220
+ ui.line(ui.head('ROUTER'), ' ', ui.text('unavailable', { color: 'yellow' }), ui.dim(' Claude’s model is kept')),
217
221
  ui.text(unavailableReason(view), { color: 'yellow' }),
218
222
  ...(view.error === GATEWAY_SETTINGS ? GATEWAY_CLEANUP.map((line) => ui.text(line, { color: 'yellow' })) : []),
219
223
  ];
@@ -230,7 +234,7 @@ function routingState(ui, config, view, actions) {
230
234
  });
231
235
  return [
232
236
  ui.line(
233
- ui.head('ROUTING'),
237
+ ui.head('ROUTER'),
234
238
  ' ',
235
239
  option('auto', 'on', 'o'),
236
240
  ' ',
@@ -245,6 +249,7 @@ function routingState(ui, config, view, actions) {
245
249
  ];
246
250
  }
247
251
 
252
+ // The tabs carry their number keys in their labels, so every key the pane answers is on screen.
248
253
  function header(ui, config, view, tab, actions) {
249
254
  const changes = routingChanges(config, view);
250
255
  const unsaved = {
@@ -257,7 +262,7 @@ function header(ui, config, view, tab, actions) {
257
262
  ...TABS.flatMap(([id, hotkey, label]) => [
258
263
  ui.Button({
259
264
  key: `tab-${id}`,
260
- label: unsaved[id] ? `${label} ●` : label,
265
+ label: `${hotkey} ${label}${unsaved[id] ? ' ●' : ''}`,
261
266
  hotkey,
262
267
  variant: tab === id ? 'primary' : 'secondary',
263
268
  onPress: () => actions.tab(id),
@@ -270,107 +275,327 @@ function header(ui, config, view, tab, actions) {
270
275
  ];
271
276
  }
272
277
 
273
- // "Jev gave stronger tiers 88% (needs 82%) · next switch ≈ $0.48": the support for the switch the policy weighed against
274
- // the bar it set, and the switch cost. Null without a reading.
278
+ // "Jev 93% ≥ 90% · switch ≈ $0.48": the support for the switch the policy weighed against the bar it set, and the switch
279
+ // cost. Null without a reading.
275
280
  function supportText(label, estimate) {
276
281
  if (!Number.isFinite(estimate?.threshold)) return null;
277
- const [direction, mass] = Number.isFinite(estimate.upgradeMass)
278
- ? ['stronger', estimate.upgradeMass]
279
- : ['cheaper', estimate.downgradeMass];
280
- const [needs, gave] = percentPair(estimate.threshold, Number.isFinite(mass) ? mass : estimate.threshold);
281
- const cost = Number.isFinite(estimate.taxUsd) ? ` · next switch ≈ ${usd(estimate.taxUsd)}` : '';
282
- return `${label} gave ${direction} tiers ${Number.isFinite(mass) ? gave : '—'} (needs ${needs})${cost}`;
282
+ const mass = Number.isFinite(estimate.upgradeMass) ? estimate.upgradeMass : estimate.downgradeMass;
283
+ const cost = Number.isFinite(estimate.taxUsd) ? ` · switch ≈ ${usd(estimate.taxUsd)}` : '';
284
+ if (!Number.isFinite(mass)) return `${label} needs ${percent(estimate.threshold)}${cost}`;
285
+ const [gave, needs] = percentPair(mass, estimate.threshold);
286
+ return `${label} ${gave} ${mass >= estimate.threshold ? '≥' : '<'} ${needs}${cost}`;
283
287
  }
284
288
 
285
- // What runs next turn and why first, with the one-turn pins; then this session and today as headlines, the finding
286
- // worth a look, and Claude's context and cost readings.
289
+ // Three questions, in order: what runs next and why, what the plan and the session cost, and how full the context is.
290
+ // The cost table, today’s totals and the subagent list are on Usage.
287
291
  function nowTab(ui, config, view, usage, actions, _modelOptions, columns, now) {
288
- const metrics = usageMetrics(config, view, usage);
292
+ const cost = sessionCost(config, view, usage, now);
293
+ return [
294
+ ...nextLines(ui, config, view, actions, columns),
295
+ ...planLines(ui, cost, now),
296
+ ...sessionLines(ui, config, view, cost, actions, columns, now),
297
+ ...contextLines(ui, config, view, usage, actions, now),
298
+ ];
299
+ }
300
+
301
+ // NEXT TURN. With routing off or unavailable only the model applies: no tier, activity or reason from an earlier turn.
302
+ function nextLines(ui, config, view, actions, columns) {
289
303
  const unavailable = view.phase === 'unavailable';
290
304
  const auto = view.mode === 'auto' && !unavailable;
291
305
  const current = view.selectedModel ?? view.nativeModel;
292
- const label = classifierLabel(config);
293
- const missing = unavailable ? null : missingCredentials(config, view, config.classifier);
294
- const served = view.actualModel && current && !isSameModel(current, view.actualModel);
306
+ const out = [ui.head('NEXT TURN')];
307
+ if (!auto) return [...out, ...offLines(ui, view, unavailable, current)];
295
308
  const mode = config.activityRouting;
296
309
  const reading = mode === 'off' ? null : activityReading(view);
297
- // In `on` an override names the tier's own model, as the routing mode runs it.
298
310
  const shown = shownConfig(config, view);
299
311
  const base = view.tier ? resolveRoute(shown, view.tier) : null;
300
312
  const override =
301
313
  mode === 'on' && view.activity && base && !sameRoute(resolveRoute(shown, view.tier, view.activity), base);
302
- const support = auto ? supportText(label, view.estimate) : null;
303
- const out = [
314
+ const served = view.actualModel && current && !isSameModel(current, view.actualModel);
315
+ const support = supportText(classifierLabel(config), view.estimate);
316
+ const missing = missingCredentials(config, view, config.classifier);
317
+ const { mode: routingMode, source } = routingModeOf(view);
318
+ const lever = modeLever(config, view);
319
+ out.push(
304
320
  ui.line(
305
- 'Next turn ',
306
- view.tier ? ui.tier(view.tier, `▌${view.tier} `) : null,
321
+ ' ',
322
+ view.tier ? ui.bars(view.tier) : ui.dim('○'),
323
+ ' ',
307
324
  ui.text(routeLabel(current, view.effort), { bold: true }),
308
- auto ? null : ui.dim(unavailable ? ' Claude’s model' : ' your /model choice, routing off'),
309
- override ? ui.dim(` override · ${view.tier} runs ${routeName(config, base)}`) : null,
325
+ reading
326
+ ? ui.line(
327
+ ' ',
328
+ // `uncertain` is an answer, not an activity: it applies none.
329
+ ACTIVITIES.includes(reading.choice) ? ui.activity(reading.choice) : ui.dim(reading.choice),
330
+ reading.share ? ` ${reading.share}` : '',
331
+ reading.others.length ? ui.dim(` ${reading.others[0]}`) : null,
332
+ )
333
+ : null,
310
334
  ),
311
- reading
335
+ view.reason
312
336
  ? ui.line(
313
- 'Activity ',
314
- // `uncertain` is an answer, not an activity: it applies none.
315
- ACTIVITIES.includes(reading.choice) ? ui.activity(reading.choice) : ui.dim(reading.choice),
316
- reading.share ? ` ${reading.share}` : '',
317
- reading.others.length ? ui.dim(` ${reading.others.map(verbShare).join(' · ')}`) : null,
318
- ui.dim(` applies at ${percent(config.policy.activityMass)}+`),
337
+ ui.dim(' why '),
338
+ shortReason(view.reason, reasonActivity(config, view)),
339
+ support ? ui.dim(` ${support}`) : null,
319
340
  )
320
341
  : null,
321
- ui.line('Why ', whyText(config, view)),
322
- support ? ui.dim(` ${support}`) : null,
323
- ui.line(
324
- 'Mode ',
325
- routingModeText(view),
326
- routingModeOf(view).source === 'session' ? ui.dim(' /router mode default clears it') : null,
327
- ),
328
- view.projectError ? ui.text(` Ignored: ${view.projectError}`, { color: 'yellow' }) : null,
329
- served
330
- ? ui.line(ui.text('Served ', { color: 'yellow' }), `${modelName(view.actualModel)} · native fallback`)
331
- : null,
332
- view.pendingPin
342
+ override ? ui.dim(` ${whyText(config, view)} · tier route ${routeName(shown, base)}`) : null,
343
+ routingMode !== 'balanced' || source === 'session'
333
344
  ? ui.line(
334
- ui.text('Pinned ', { color: 'yellow' }),
335
- 'next turn → ',
336
- ui.tier(view.pendingPin),
337
- ' ',
338
- ui.Button({ key: 'unpin', label: 'unpin', onPress: actions.unpin }),
345
+ ui.dim(' mode '),
346
+ ui.text(` ${routingMode} `, { backgroundColor: '#2a3040', color: '#c0c6d4' }),
347
+ ui.dim(` from ${source}${lever ? ` · ${lever} on this tier` : ''}`),
348
+ source === 'session' ? ui.dim(' · /router mode default clears it') : null,
339
349
  )
340
350
  : null,
351
+ view.projectError ? ui.text(` Ignored: ${view.projectError}`, { color: 'yellow' }) : null,
352
+ served ? ui.text(` ! served by ${modelName(view.actualModel)} · native fallback`, { color: 'yellow' }) : null,
341
353
  missing
342
354
  ? ui.line(
343
- ui.text(`${classifierStatus(config, missing)}, keeping the model `, { color: 'yellow' }),
355
+ ui.text(` ${classifierStatus(config, missing)}, keeping the model `, { color: 'yellow' }),
344
356
  ui.Button({ key: 'key', label: 'Set up', hotkey: 'k', onPress: actions.key }),
345
357
  )
346
358
  : null,
347
- pinLine(ui, view, auto, unavailable, actions, columns),
359
+ ...pinLines(ui, config, view, actions, columns),
360
+ ui.text(' '),
361
+ );
362
+ return out.filter(Boolean);
363
+ }
364
+
365
+ // Routing off or unavailable: the model that runs, and why nothing else applies.
366
+ function offLines(ui, view, unavailable, current) {
367
+ const model = unavailable ? routeLabel(view.nativeModel, view.nativeEffort) : routeLabel(current, view.effort);
368
+ return [
369
+ ui.line(
370
+ unavailable ? ui.text(' ✕ ', { color: 'yellow' }) : ui.dim(' ○ '),
371
+ ui.text(model, { bold: true }),
372
+ ui.dim(unavailable ? ' routing unavailable · Claude’s model' : ' routing off · /model choice'),
373
+ ),
374
+ ui.line(ui.dim(' pin '), ui.dim(unavailable ? 'needs routing' : 'needs routing on (o)')),
375
+ ui.text(' '),
348
376
  ];
349
- const session = sessionUsage(view, now);
350
- const today = summarize(liveUsage(view, view.usageStore), periodRange('today', now));
351
- out.push(ui.text(' '), ...sessionLines(ui, config, view, session, actions, columns, now));
352
- // Today repeats this session's part of it until another session adds to it.
353
- const ownToday = summarize(liveUsage(view, view.usageSession), periodRange('today', now));
354
- if (today.observed.replies > ownToday.observed.replies)
355
- out.push(ui.text(' '), ...todayLines(ui, today, actions, columns));
356
- out.push(
357
- ...sessionAgentLines(ui, view, actions, columns),
358
- ...worthLines(ui, today, actions, columns),
377
+ }
378
+
379
+ // One button per tier, low to high, named by the route it runs ("▂▄ Haiku·high") with the classifier's support on the
380
+ // last turn; the current tier is marked and a pending pin is filled. A press pins the next turn only.
381
+ function pinLines(ui, config, view, actions, columns) {
382
+ const shown = shownConfig(config, view);
383
+ const pin = (tier) => {
384
+ const support = view.probabilities?.[tier];
385
+ return ui.Button({
386
+ key: `pin-${tier}`,
387
+ label: `${view.tier === tier ? '▶ ' : ''}${tierBars(tier)} ${shortRoute(config, resolveRoute(shown, tier))} ${Number.isFinite(support) ? percent(support) : '—'}`,
388
+ variant: view.pendingPin === tier ? 'primary' : 'secondary',
389
+ onPress: () => actions.pin(tier),
390
+ });
391
+ };
392
+ const narrow = Number.isFinite(columns) && columns < PIN_ROW_COLUMNS;
393
+ const rows = narrow ? TIERS.map((tier) => [tier]) : [TIERS.slice(0, 2), TIERS.slice(2)];
394
+ return [
395
+ ...rows.map((tiers, i) =>
396
+ ui.line(i ? ' ' : ui.dim(' pin '), ...tiers.flatMap((tier) => [pin(tier), ' '])),
397
+ ),
398
+ view.pendingPin
399
+ ? ui.line(
400
+ ui.text(' ⏵ next turn ', { color: 'yellow' }),
401
+ ui.bars(view.pendingPin),
402
+ ` ${shortRoute(config, resolveRoute(shown, view.pendingPin))} `,
403
+ ui.Button({ key: 'unpin', label: 'unpin', onPress: actions.unpin }),
404
+ )
405
+ : null,
406
+ ].filter(Boolean);
407
+ }
408
+ // Below this a pin row holds one pin.
409
+ const PIN_ROW_COLUMNS = 64;
410
+
411
+ // PLAN: Claude Code's plan windows, when it reports them.
412
+ function planLines(ui, cost, now) {
413
+ if (!cost.limits.length) return [];
414
+ return [
415
+ ui.line(ui.head('PLAN'), ui.dim(' Claude plan usage')),
416
+ ...cost.limits.map((limit) => {
417
+ const [filled, empty] = gaugeCells(limit.percent / 100, 20);
418
+ const color = limitColor(limit.percent);
419
+ const reset = resetText(limit.resetsAt, now);
420
+ return ui.line(
421
+ ` ${limit.label.padEnd(6)}`,
422
+ ui.text(filled, { color }),
423
+ ui.dim(empty),
424
+ ui.text(` ${String(limit.percent).padStart(3)}%`, { color }),
425
+ reset ? ui.dim(` resets ${reset}`) : null,
426
+ );
427
+ }),
359
428
  ui.text(' '),
360
- ui.gauge('Context ', metrics.contextBar, contextSuffix(metrics)),
429
+ ];
430
+ }
431
+
432
+ // How the session's dollars are paid, after the total: "API value · plan quota, not billed".
433
+ function billingWords(cost) {
434
+ if (cost.billing === 'plan') return 'API value · plan quota, not billed';
435
+ if (cost.billing === 'mixed') return `API value · ${usd(cost.creditsUsd)} of it billed as credits`;
436
+ return 'billed at list prices';
437
+ }
438
+
439
+ // SESSION: one total with the subagents, the difference against no routing, the main thread and the subagents as bars
440
+ // on one scale, then the replies by tier.
441
+ function sessionLines(ui, config, view, cost, actions, columns, now) {
442
+ const since = liveUsage(view, view.usageSession).since;
443
+ const running = view.subagentsRunning ?? 0;
444
+ const switches = sessionUsage(view, now).switches;
445
+ const switchCount = switches.tier + switches.activity;
446
+ const head = [
447
+ Number.isFinite(since) ? `since ${sinceText(since, now)}` : null,
448
+ cost.replies ? plural(cost.replies, 'reply', 'replies') : null,
449
+ cost.agents ? plural(cost.agents, 'agent') : null,
450
+ switchCount ? plural(switchCount, 'switch', 'switches') : null,
451
+ ].filter(Boolean);
452
+ const out = [
361
453
  ui.line(
362
- ui.text('Cache ', { color: metrics.cacheBar.color }),
454
+ ui.head('SESSION'),
455
+ head.length ? ui.dim(` ${head.join(' · ')}`) : null,
456
+ running ? ui.text(` ● ${running} running`, { color: 'yellow' }) : null,
457
+ ),
458
+ ];
459
+ // Replies without a list price reach the strip but not the usage record: the tiers still show, the cost cannot.
460
+ if (!cost.replies && !cost.agents)
461
+ return [
462
+ ...out,
463
+ ui.dim(view.strip?.cells?.length ? ' no priced replies: cost unknown' : ' no replies yet'),
464
+ ...stripLines(ui, view, columns, since, now),
465
+ ui.text(' '),
466
+ ];
467
+ out.push(
468
+ ui.line(
469
+ ' ',
470
+ ui.text(costText(cost.totalUsd, cost.billing), { bold: true }),
471
+ ui.dim(` ${billingWords(cost)} `),
472
+ ui.Button({ key: 'usage-session', label: 'Usage', onPress: () => actions.usageFor('session') }),
473
+ ),
474
+ );
475
+ if (cost.diffUsd !== null) {
476
+ const diff = diffText(cost.diffUsd, cost.baseUsd);
477
+ const of = ` of ${costText(cost.baseUsd, cost.billing)}${cost.early ? ' · early sample' : ''}`;
478
+ const fits = !Number.isFinite(columns) || 2 + diff.length + ' vs no routing'.length + of.length <= columns;
479
+ out.push(
480
+ ui.line(
481
+ ' ',
482
+ ui.text(diff, { bold: true, color: savingsColor(cost.diffUsd) }),
483
+ ' vs no routing',
484
+ fits ? ui.dim(of) : null,
485
+ ),
486
+ );
487
+ } else if (cost.effortOnly) out.push(ui.dim(' effort routing on one model: no saving is estimated'));
488
+ else if (cost.uncomparedReplies) out.push(ui.dim(` ${uncomparedText(cost)}: no saving shown`));
489
+ out.push(...costBars(ui, config, view, cost, now));
490
+ const r = cost.readout;
491
+ if (cost.comparable && !r.early && switchesLost(r)) out.push(lostLine(ui, actions));
492
+ out.push(...stripLines(ui, view, columns, since, now), ui.text(' '));
493
+ return out;
494
+ }
495
+
496
+ // The main thread and the subagents as bars on one scale, each with its difference against no routing; an effort-only
497
+ // profile shows its effort mix.
498
+ function costBars(ui, config, view, cost, now) {
499
+ const out = [];
500
+ const scale = Math.max(cost.mainUsd, cost.agentUsd);
501
+ const bar = (value, color) => {
502
+ const filled = scale > 0 ? Math.max(value > 0 ? 1 : 0, Math.round((value / scale) * SESSION_BAR)) : 0;
503
+ return [ui.text('█'.repeat(filled), { color }), ui.dim('░'.repeat(SESSION_BAR - filled))];
504
+ };
505
+ const amount = (value) => costText(value, cost.billing).padStart(7);
506
+ const against = (diff, words) =>
507
+ diff === null || cost.diffUsd === null
508
+ ? null
509
+ : ui.line(
510
+ ' ',
511
+ ui.text(signedUsd(diff), savingsColor(diff) ? { color: savingsColor(diff) } : {}),
512
+ ui.dim(` vs ${words}`),
513
+ );
514
+ out.push(
515
+ ui.line(
516
+ ' main ',
517
+ amount(cost.mainUsd),
518
+ ' ',
519
+ ...bar(cost.mainUsd, 'cyan'),
520
+ against(cost.replies ? cost.mainDiff : null, comparedModel(config, view, sessionUsage(view, now))),
521
+ ),
522
+ );
523
+ if (cost.agents)
524
+ out.push(
525
+ ui.line(
526
+ ' agents',
527
+ amount(cost.agentUsd),
528
+ ' ',
529
+ ...bar(cost.agentUsd, 'cyan'),
530
+ against(cost.agentDiff, 'their picks'),
531
+ ),
532
+ );
533
+ if (cost.effortOnly && cost.effortMix.length)
534
+ out.push(
535
+ ui.line(
536
+ ui.dim(' effort'),
537
+ ...cost.effortMix.flatMap(([effort, n]) => [ui.dim(` ${effort} `), ui.text(String(n), { bold: true })]),
538
+ ),
539
+ );
540
+ return out;
541
+ }
542
+
543
+ const SESSION_BAR = 16;
544
+
545
+ // The session's replies as a strip coloured by tier, then the replies per tier, low to high, as their bars.
546
+ function stripLines(ui, view, columns, since, now) {
547
+ if (!view.strip?.cells?.length) return [];
548
+ const strip = fittedStrip(view.strip, Number.isFinite(columns) ? columns - 8 : columns, since, now);
549
+ const counts = {};
550
+ for (const cell of view.strip.cells)
551
+ for (const [key, n] of Object.entries(cell)) counts[key] = (counts[key] ?? 0) + n;
552
+ return [
553
+ ui.line(
554
+ ui.dim(' tiers '),
555
+ ...strip.cells.map((cell) => {
556
+ const tier = cellTier(cell);
557
+ return tier === 'none' ? ui.dim('·') : ui.tier(tier, '█');
558
+ }),
559
+ strip.note ? ui.dim(` ${strip.note}`) : null,
560
+ ),
561
+ ui.line(
562
+ ' ',
563
+ ...TIERS.filter((tier) => counts[tier]).flatMap((tier) => [ui.bars(tier), ui.dim(` ${counts[tier]} `)]),
564
+ counts.none ? ui.dim(`· not routed ${counts.none}`) : null,
565
+ ),
566
+ ];
567
+ }
568
+
569
+ // CONTEXT: the window's fill on the model that runs next, and the cache reuse of the last reply and of the session.
570
+ function contextLines(ui, config, view, usage, actions, now) {
571
+ const metrics = usageMetrics(config, view, usage);
572
+ const session = sessionUsage(view, now).observed;
573
+ const fill = metrics.contextBar.percent;
574
+ const [filled, empty] = gaugeCells((fill ?? 0) / 100, 20);
575
+ return [
576
+ ui.head('CONTEXT'),
577
+ fill === null
578
+ ? ui.line(' ctx ', ui.dim('no reading yet'))
579
+ : ui.line(
580
+ ' ctx ',
581
+ ui.text(filled, { color: metrics.contextBar.color }),
582
+ ui.dim(empty),
583
+ ` ${String(fill).padStart(3)}%`,
584
+ ui.dim(` ${contextSuffix(metrics)}`),
585
+ ),
586
+ ui.line(
587
+ ' cache ',
363
588
  metrics.cacheBar.percent === null
364
589
  ? ui.dim('no reply yet')
365
- : ui.text(`${metrics.cacheBar.percent}% reused on the last reply`, { color: metrics.cacheBar.color }),
366
- ui.dim(' · '),
367
- `cost ${dollars(metrics.cost)} `,
368
- ui.dim('by Claude '),
590
+ : ui.line(ui.text(`${metrics.cacheBar.percent}%`, { color: metrics.cacheBar.color }), ui.dim(' last reply')),
591
+ session.inputTokens
592
+ ? ui.line(ui.dim(' · '), percent(session.cacheReadTokens / session.inputTokens), ui.dim(' session'))
593
+ : null,
594
+ ' ',
369
595
  detailButton(ui, view, actions),
370
596
  ),
371
597
  ...(view.usageDetail ? readingDetail(ui, view, metrics) : []),
372
- );
373
- return out;
598
+ ];
374
599
  }
375
600
 
376
601
  const detailButton = (ui, view, actions) =>
@@ -411,9 +636,7 @@ function readingDetail(ui, view, metrics) {
411
636
  ...(view.comparison
412
637
  ? [
413
638
  ui.text(`Compared tiers ${view.comparison.incumbent} → ${view.comparison.candidate}`),
414
- ui.text(
415
- `Next-turn difference ${difference(view.comparison.minUsd)} to ${difference(view.comparison.maxUsd)}`,
416
- ),
639
+ ui.text(`Next-turn difference ${signedUsd(view.comparison.minUsd)} to ${signedUsd(view.comparison.maxUsd)}`),
417
640
  ui.text(
418
641
  `Payback ${view.comparison.paybackTurns === null ? 'none projected' : `${view.comparison.paybackTurns} later turns`}`,
419
642
  ),
@@ -422,35 +645,6 @@ function readingDetail(ui, view, metrics) {
422
645
  ];
423
646
  }
424
647
 
425
- const verbShare = (text) => text.replace(/^(\S+)/, (name) => activityVerb(name));
426
-
427
- // One button per tier with the classifier's support on the last turn, the current tier marked; a press pins the next
428
- // turn only. Without routing there is nothing to pin.
429
- function pinLine(ui, view, auto, unavailable, actions, columns) {
430
- if (!auto)
431
- return ui.line(
432
- 'Pin next ',
433
- ui.dim(unavailable ? 'needs routing, which is unavailable' : 'needs routing on (o above)'),
434
- );
435
- return ui.line(
436
- 'Pin next ',
437
- ...LADDER.flatMap((tier) => {
438
- const support = view.probabilities?.[tier];
439
- return [
440
- ui.Button({
441
- key: `pin-${tier}`,
442
- label: `${view.tier === tier ? '▶ ' : ''}${tier} ${Number.isFinite(support) ? percent(support) : '—'}`,
443
- variant: view.pendingPin === tier ? 'primary' : 'secondary',
444
- onPress: () => actions.pin(tier),
445
- }),
446
- ' ',
447
- ];
448
- }),
449
- !Number.isFinite(columns) || columns >= PIN_HINT_COLUMNS ? ui.dim(' next turn only') : null,
450
- );
451
- }
452
- const PIN_HINT_COLUMNS = 80;
453
-
454
648
  // "13:41", or "Oct 12 13:41" for another day than `now`'s.
455
649
  const clockText = (ms) => new Date(ms).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' });
456
650
  const sinceText = (ms, now) =>
@@ -477,121 +671,6 @@ function fittedStrip(strip, columns, since, now) {
477
671
  return { cells, note: note() };
478
672
  }
479
673
 
480
- // This session: since its first routed reply, its routed replies and route switches; its replies as a strip colored
481
- // by tier, with the replies per tier, and the routed replies per activity; the last switch; and routing against your
482
- // model, linked to Usage.
483
- function sessionLines(ui, config, view, summary, actions, columns, now) {
484
- const since = liveUsage(view, view.usageSession).since;
485
- const strip = view.strip?.cells?.length ? fittedStrip(view.strip, columns, since, now) : null;
486
- const counts = {};
487
- for (const cell of view.strip?.cells ?? [])
488
- for (const [key, n] of Object.entries(cell)) counts[key] = (counts[key] ?? 0) + n;
489
- const replies = Object.values(counts).reduce((sum, n) => sum + n, 0);
490
- const switches = summary.switches.tier + summary.switches.activity;
491
- const head = [
492
- Number.isFinite(since) ? `since ${sinceText(since, now)}` : null,
493
- summary.observed.replies
494
- ? `${plural(summary.observed.replies, 'routed reply', 'routed replies')}${view.usageLive?.length ? ` (${view.usageLive.length} live)` : ''}`
495
- : replies
496
- ? plural(replies, 'reply', 'replies')
497
- : null,
498
- summary.turns ? plural(switches, 'route switch', 'route switches') : null,
499
- ].filter(Boolean);
500
- if (!strip && !summary.observed.replies) return [ui.line(ui.head('SESSION'), ui.dim(' · no replies yet'))];
501
- const out = [ui.line(ui.head('SESSION'), head.length ? ui.dim(` · ${head.join(' · ')}`) : null)];
502
- // The band's session row, then the parts that add up to it.
503
- if (summary.observed.uncomparedReplies) {
504
- out.push(
505
- ui.line(
506
- ' ',
507
- ui.text(observedUsageText(summary.observed)),
508
- ' ',
509
- ui.Button({ key: 'usage-session', label: 'Usage', onPress: () => actions.usageFor('session') }),
510
- ),
511
- );
512
- } else if (summary.replies) {
513
- const r = readout(summary);
514
- out.push(
515
- answerLine(ui, r, comparedModel(config, view, summary), () => actions.usageFor('session'), 'session', columns),
516
- );
517
- if (!r.early)
518
- out.push(...ledger(ui, config, view, { period: 'session', r, summary, legacy: null, columns, compact: true }));
519
- if (!r.early && switchesLost(r)) out.push(lostLine(ui, actions));
520
- }
521
- if (strip) {
522
- out.push(
523
- ui.line(
524
- ' ',
525
- ...strip.cells.map((cell) => {
526
- const tier = cellTier(cell);
527
- return tier === 'none' ? ui.dim('·') : ui.tier(tier, '█');
528
- }),
529
- strip.note ? ui.dim(` ${strip.note}`) : null,
530
- ),
531
- ui.line(
532
- ' ',
533
- ...TIERS.filter((tier) => counts[tier]).flatMap((tier) => [ui.tier(tier, '■ '), `${tier} ${counts[tier]} `]),
534
- counts.none ? ui.dim(`· not routed ${counts.none}`) : null,
535
- ),
536
- );
537
- }
538
- const used = breakdown(summary.observed.cells, 'activity')
539
- .filter((group) => ACTIVITIES.includes(group.name))
540
- .sort((a, b) => b.sums[0] - a.sums[0])
541
- .map((group) => [group.name, `${activityVerb(group.name)} ${group.sums[0]}`]);
542
- // The most used first, as many as fit the pane; the rest as a count.
543
- const shown = [];
544
- for (const [i, entry] of used.entries()) {
545
- const rest = used.length - i - 1;
546
- const width =
547
- 2 + [...shown, entry].map(([, text]) => text).join(' · ').length + (rest ? ` · +${rest} more`.length : 0);
548
- if (Number.isFinite(columns) && width > columns && shown.length) break;
549
- shown.push(entry);
550
- }
551
- if (shown.length)
552
- out.push(
553
- ui.line(
554
- ' ',
555
- ...shown.flatMap(([name, text], i) => [
556
- ui.activity(name),
557
- ui.dim(`${text.slice(activityVerb(name).length)}${i < shown.length - 1 ? ' · ' : ''}`),
558
- ]),
559
- shown.length < used.length ? ui.dim(` · +${used.length - shown.length} more`) : null,
560
- ),
561
- );
562
- const last = view.lastSwitch;
563
- if (Number.isFinite(last?.at) && last.from && last.to) out.push(lastSwitchLine(ui, last, now));
564
- return out;
565
- }
566
-
567
- // "last switch 13:41 medium → high · debugging"; routes by name when the switch kept the tier.
568
- function lastSwitchLine(ui, last, now) {
569
- const byTier = TIERS.includes(last.from.tier) && TIERS.includes(last.to.tier) && last.from.tier !== last.to.tier;
570
- return ui.line(
571
- ' ',
572
- ui.dim(`last switch ${sinceText(last.at, now)} `),
573
- ...(byTier
574
- ? [ui.tier(last.from.tier), ui.dim(' → '), ui.tier(last.to.tier)]
575
- : [routeLabel(last.from.model, last.from.effort), ui.dim(' → '), routeLabel(last.to.model, last.to.effort)]),
576
- ...(ACTIVITIES.includes(last.activity) ? [ui.dim(' · '), ui.activity(last.activity)] : []),
577
- );
578
- }
579
-
580
- // Routing against your model in the band's words, "routing −$1.84 (−22%) vs Opus 5.5 · xhigh", with the Usage tab on
581
- // the same period one press away; an early sample says so.
582
- function answerLine(ui, r, against, open, period, columns) {
583
- const early = ' · early sample';
584
- const width = 2 + routingAnswer(r).length + ` vs ${against}`.length + early.length + USAGE_LINK;
585
- return ui.line(
586
- ' ',
587
- ...answerParts(ui, r, against),
588
- r.early && (!Number.isFinite(columns) || width <= columns) ? ui.dim(early) : null,
589
- ' ',
590
- ui.Button({ key: `usage-${period}`, label: 'Usage', onPress: open }),
591
- );
592
- }
593
- // " [ Usage ]" after the answer.
594
- const USAGE_LINK = 11;
595
674
  // Cache rebuilds cost more than the cheaper models saved: the policy's switch weight is the lever.
596
675
  const lostLine = (ui, actions) =>
597
676
  ui.line(
@@ -599,33 +678,6 @@ const lostLine = (ui, actions) =>
599
678
  ui.Button({ key: 'session-policy', label: 'Policy', onPress: () => actions.tab('policy') }),
600
679
  );
601
680
 
602
- // Today across sessions, shown once another session added to it.
603
- function todayLines(ui, summary, actions, columns) {
604
- const switches = summary.switches.tier + summary.switches.activity;
605
- return [
606
- ui.line(
607
- ui.head('TODAY'),
608
- ui.dim(
609
- ` · ${plural(summary.observed.replies, 'routed reply', 'routed replies')} · ${plural(switches, 'route switch', 'route switches')}`,
610
- ),
611
- ),
612
- summary.observed.uncomparedReplies
613
- ? ui.line(
614
- ui.text(observedUsageText(summary.observed)),
615
- ' ',
616
- ui.Button({ key: 'usage-today', label: 'Usage', onPress: () => actions.usageFor('today') }),
617
- )
618
- : answerLine(ui, readout(summary), 'each session’s own model', () => actions.usageFor('today'), 'today', columns),
619
- ];
620
- }
621
-
622
- // Today's first finding from Usage's WORTH A LOOK, with the tab that changes it; nothing when there is none.
623
- function worthLines(ui, summary, actions, columns) {
624
- const [first] = !summary.observed.uncomparedReplies && summary.replies >= INSIGHT_REPLIES ? insights(summary) : [];
625
- if (!first) return [];
626
- return [ui.text(' '), ui.line(ui.head('WORTH A LOOK'), ui.dim(' · today')), insightLine(ui, first, actions, columns)];
627
- }
628
-
629
681
  // Rows: [key, label, format, router.json field]. Typed as tuples so tsc keeps each position's type.
630
682
  /** @type {[string, string, (value: number) => string, string][]} */
631
683
  const POLICY_ROWS = [
@@ -664,7 +716,7 @@ const marker = (ui, changed) => ui.cell(2, changed ? ui.text('●', { color: 'ye
664
716
  // "sonnet·high": the route's models key and its effort, short enough for the grid; `inherit` for a route that leaves
665
717
  // the effort to the session, and no effort for a model without efforts. The key, not the model name: two Haiku versions
666
718
  // in router.json still read apart.
667
- function shortRoute(config, route, narrow) {
719
+ function gridRoute(config, route, narrow) {
668
720
  if (!config.models[route.model].efforts.length) return route.model;
669
721
  const effort = route.effort ?? INHERIT;
670
722
  return `${route.model}·${narrow ? (EFFORT_SHORT[effort] ?? effort) : effort}`;
@@ -808,7 +860,7 @@ function routesTab(ui, config, view, _usage, actions, modelOptions, columns) {
808
860
  cellButton(
809
861
  TIER_ROW,
810
862
  tier,
811
- `${shortRoute(draft, draft.routes[tier], narrow)}${changes.tiers.includes(tier) ? '●' : ''}`,
863
+ `${gridRoute(draft, draft.routes[tier], narrow)}${changes.tiers.includes(tier) ? '●' : ''}`,
812
864
  false,
813
865
  ),
814
866
  ),
@@ -824,7 +876,7 @@ function routesTab(ui, config, view, _usage, actions, modelOptions, columns) {
824
876
  if (sameRoute(route, draft.routes[tier])) return cellButton(activity, tier, `·${edited}`, true);
825
877
  const preset = builtIn(draft, activity, tier);
826
878
  const mark = preset && sameRoute(route, { model: preset.model, effort: preset.effort ?? null }) ? '°' : '';
827
- return cellButton(activity, tier, `${shortRoute(draft, route, narrow)}${mark}${edited}`, mode !== 'on');
879
+ return cellButton(activity, tier, `${gridRoute(draft, route, narrow)}${mark}${edited}`, mode !== 'on');
828
880
  }),
829
881
  ),
830
882
  );
@@ -1290,9 +1342,8 @@ function storeUsage(ui, store, metrics) {
1290
1342
  // The footer as [text, joiner] pieces, packed to the pane: two lines at full width, more in a narrow pane, never a
1291
1343
  // line that ends in a joiner.
1292
1344
  const SAVINGS_FOOTER = [
1293
- ['every $ at API prices, plan and credits alike', ' · '],
1294
- ['not a bill;', ' '],
1295
- ['on a Claude plan it shows quota use', ' · '],
1345
+ ['$ = tokens × list prices', ' · '],
1346
+ ['≈ = API value of plan quota', ' · '],
1296
1347
  ['answer quality not measured', ''],
1297
1348
  ];
1298
1349
  const FULL_WIDTH = 68;
@@ -1489,7 +1540,7 @@ function moveText(m) {
1489
1540
  }
1490
1541
 
1491
1542
  // One row of the subagent table; open, the models it ran on with their cost, and its requests and retry proxies.
1492
- function agentRow(ui, view, actions, { id, name, counts, routed, why, narrow, columns }) {
1543
+ function agentRow(ui, view, actions, { id, name, counts, routed, why, narrow, columns, billing }) {
1493
1544
  const open = view.usageOpen === id;
1494
1545
  const models = Object.entries(counts.models)
1495
1546
  .filter(([, m]) => m.agents > 0)
@@ -1503,7 +1554,7 @@ function agentRow(ui, view, actions, { id, name, counts, routed, why, narrow, co
1503
1554
  const t = modelTotals(counts);
1504
1555
  // A row none of whose requests had a price says so rather than $0.00.
1505
1556
  const priced = counts.pricedRequests > 0;
1506
- const costCell = (value) => (priced ? usd(value).padStart(9) : ui.dim('no price'.padStart(9)));
1557
+ const costCell = (value) => (priced ? costText(value, billing).padStart(9) : ui.dim('no price'.padStart(9)));
1507
1558
  const out = [
1508
1559
  ui.line(
1509
1560
  ' ',
@@ -1547,7 +1598,7 @@ function agentRow(ui, view, actions, { id, name, counts, routed, why, narrow, co
1547
1598
  // plugin install). A strip of every agent by the model it ran on, filled where the router moved it off Claude Code's
1548
1599
  // pick, and the routed agents' cost against those picks. Then the routed types and the pass-throughs, each with its
1549
1600
  // squares, agents and cost, opening to its models; a pass-through says why Claude Code picked.
1550
- function subagentUsage(ui, config, view, actions, period, now, columns) {
1601
+ function subagentUsage(ui, config, view, actions, period, now, columns, billing) {
1551
1602
  const mode = config.subagentRouting;
1552
1603
  const record = readSubagentStore(period === 'session' ? view.subagentSession : view.subagentStore);
1553
1604
  const s = summarizeSubagents(record, periodRange(period, now));
@@ -1564,7 +1615,7 @@ function subagentUsage(ui, config, view, actions, period, now, columns) {
1564
1615
  const undated = s.undated
1565
1616
  ? [
1566
1617
  ui.dim(
1567
- ` + ${plural(s.undated.agents, 'agent')} from before 1.14.0, not split by model · ${usd(s.undated.usd)}`,
1618
+ ` + ${plural(s.undated.agents, 'agent')} from before 1.14.0, not split by model · ${costText(s.undated.usd, billing)}`,
1568
1619
  ),
1569
1620
  ]
1570
1621
  : [];
@@ -1583,7 +1634,7 @@ function subagentUsage(ui, config, view, actions, period, now, columns) {
1583
1634
  }
1584
1635
  const narrow = Number.isFinite(columns) && columns < AGENT_ROW;
1585
1636
  out.push(...agentSummary(ui, s, columns), ...agentTrend(ui, s, period, now), ...undated);
1586
- const rowOf = (fields) => agentRow(ui, view, actions, { narrow, columns, ...fields });
1637
+ const rowOf = (fields) => agentRow(ui, view, actions, { narrow, columns, billing, ...fields });
1587
1638
  if (routed.length) {
1588
1639
  out.push(
1589
1640
  ui.text(' '),
@@ -1616,22 +1667,6 @@ function subagentUsage(ui, config, view, actions, period, now, columns) {
1616
1667
  return out;
1617
1668
  }
1618
1669
 
1619
- // This session's subagents on the Now tab: how many run now, the strip, and how routing paid off. Nothing without any.
1620
- function sessionAgentLines(ui, view, actions, columns) {
1621
- const s = summarizeSubagents(readSubagentStore(view.subagentSession), { from: null, to: null });
1622
- const running = view.subagentsRunning ?? 0;
1623
- const any = [...Object.values(s.routed), ...Object.values(s.passed)].some((c) => c.agents > 0);
1624
- if (!any && !running) return [];
1625
- const head = ui.line(
1626
- ui.head('SUBAGENTS'),
1627
- ui.dim(' · this session'),
1628
- running ? ui.text(` · ● ${running} running`, { color: 'yellow' }) : null,
1629
- ' ',
1630
- ui.Button({ key: 'usage-agents', label: 'Usage', onPress: () => actions.usageFor('session') }),
1631
- );
1632
- return [ui.text(' '), head, ...(any ? agentSummary(ui, s, columns) : [])];
1633
- }
1634
-
1635
1670
  const PERIOD_LABEL = { session: 'Session', today: 'Today', '7d': '7d', '30d': '30d', month: 'Month', all: 'All' };
1636
1671
  // "No routed replies …" for each period.
1637
1672
  const PERIOD_PHRASE = {
@@ -1650,11 +1685,12 @@ const GROUPS = [
1650
1685
  // What an open row lists: the routes of an activity, the activities of a model or a tier.
1651
1686
  const CHILD_BY = { activity: 'route', model: 'activity', tier: 'activity' };
1652
1687
  // The ledger's label column after its sign, and its amount column.
1653
- const LEDGER_LABEL = 20;
1654
1688
  const LEDGER_AMOUNT = 9;
1655
1689
  // The breakdown: the open mark, the name, replies, cost and vs yours; "mostly on" or the share only where it fits.
1656
1690
  const NAME = 20;
1657
- const BREAKDOWN = 4 + NAME + 8 + 10 + 11;
1691
+ const BREAKDOWN = 4 + NAME + 8 + 10 + 15;
1692
+ // Tiers in their own order; `none` (not routed) last.
1693
+ const TIER_RANK = (name) => (TIERS.includes(name) ? TIERS.indexOf(name) : TIERS.length);
1658
1694
  const TAIL = 23;
1659
1695
  // Bars at full scale: the routed share of your model, and the costliest row of What if.
1660
1696
  const BAR = 22;
@@ -1681,7 +1717,7 @@ const differenceText = (ui, usdValue, width) => {
1681
1717
  function groupName(ui, by, name) {
1682
1718
  if (name === 'none') return ui.dim(by === 'activity' ? 'no activity' : 'not routed');
1683
1719
  if (by === 'activity') return ui.activity(name);
1684
- if (by === 'tier') return ui.tier(name);
1720
+ if (by === 'tier') return ui.bars(name);
1685
1721
  return ui.text(by === 'model' ? modelName(name) : routeText(name));
1686
1722
  }
1687
1723
 
@@ -1723,134 +1759,6 @@ function scopeLine(ui, config, view, period, summary, now) {
1723
1759
  return ui.dim(`all projects · ${span} · each session vs its own model`);
1724
1760
  }
1725
1761
 
1726
- // The answer first, in the band's words: "routing −$1.84 (−22%) vs Opus 5.5 · xhigh", or why there is nothing to compare.
1727
- function headline(ui, config, view, period, r, summary, observed = summary.observed) {
1728
- if (observed.uncomparedReplies)
1729
- return [
1730
- ui.text(observedUsageText(observed), { bold: true }),
1731
- ui.dim(
1732
- `${observed.uncomparedReplies} of ${observed.replies} replies have no comparison; savings are not estimated for them.`,
1733
- ),
1734
- ...(r.replies
1735
- ? [
1736
- ui.dim(`${plural(r.replies, 'comparable reply', 'comparable replies')} only:`),
1737
- ui.line(
1738
- ...answerParts(
1739
- ui,
1740
- r,
1741
- period === 'session' ? comparedModel(config, view, summary) : 'each session’s own model',
1742
- ),
1743
- ),
1744
- ]
1745
- : []),
1746
- ];
1747
- if (!r.replies) {
1748
- // A reply is priced against your model, so on a model without a price none is counted.
1749
- if (period === 'session' && !modelSpec(config, view.nativeModel))
1750
- return [ui.dim(`${modelName(view.nativeModel)} has no list price in router.json models.`)];
1751
- const off = period === 'session' && (view.phase === 'unavailable' || view.mode === 'manual');
1752
- return [
1753
- ui.dim(
1754
- off
1755
- ? `Routing is ${view.phase === 'unavailable' ? 'unavailable' : 'off'}: replies use your model and are not counted.`
1756
- : `No routed replies ${PERIOD_PHRASE[period]}.`,
1757
- ),
1758
- ];
1759
- }
1760
- const against = period === 'session' ? comparedModel(config, view, summary) : 'each session’s own model';
1761
- return [
1762
- ui.line(
1763
- ...answerParts(ui, r, against),
1764
- r.early ? ui.text(` early sample · ${plural(r.replies, 'reply', 'replies')}`, { color: 'yellow' }) : null,
1765
- ),
1766
- ];
1767
- }
1768
-
1769
- const capital = (words) => words[0].toUpperCase() + words.slice(1);
1770
-
1771
- // "routing −$1.84 (−22%) vs Opus 5.5 · xhigh", the answer bold in the savings color, as the band says it.
1772
- function answerParts(ui, r, against) {
1773
- return [ui.text(routingAnswer(r), { bold: true, color: savingsColor(r.differenceUsd) }), ` vs ${against}`];
1774
- }
1775
-
1776
- // Your model − cheaper models + stronger models + switch cache writes = routed, in whole cents that add up (readout).
1777
- function ledger(ui, config, view, { period, r, summary, legacy, columns, compact = false }) {
1778
- const tier = yourTier(config, view);
1779
- const row = (sign, label, value, color, note = null, bold = false) =>
1780
- ui.line(
1781
- ui.dim(` ${sign} `),
1782
- ui.cell(LEDGER_LABEL, ui.text(label, bold ? { bold: true } : {})),
1783
- ui.text(usd(value).padStart(LEDGER_AMOUNT), { ...(color ? { color } : {}), ...(bold ? { bold: true } : {}) }),
1784
- note ? ' ' : null,
1785
- note,
1786
- );
1787
- // The undated totals kept no switch count, so All with them names none.
1788
- const switches = legacy?.replies ? null : summary.switches.tier + summary.switches.activity;
1789
- const recorded = period === 'session' ? recordedModels(config, view, summary) : null;
1790
- const saving = -r.cheaperUsd;
1791
- const ratio = r.yoursUsd > 0 ? r.routedUsd / r.yoursUsd : null;
1792
- const wide = !Number.isFinite(columns) || columns >= 4 + LEDGER_LABEL + LEDGER_AMOUNT + 3 + BAR + 16;
1793
- const filled = ratio === null ? 0 : Math.max(0, Math.min(BAR, Math.round(ratio * BAR)));
1794
- const out = [
1795
- row(
1796
- ' ',
1797
- 'Your model',
1798
- r.yoursUsd,
1799
- undefined,
1800
- period !== 'session'
1801
- ? ui.dim('each session’s own model')
1802
- : recorded
1803
- ? ui.dim(recorded)
1804
- : tier
1805
- ? ui.tier(tier, yourModel(view))
1806
- : ui.text(yourModel(view)),
1807
- ),
1808
- compact && !r.cheaperUsd ? null : row('−', capital(COST_PART.cheaper), r.cheaperUsd, savingsColor(r.cheaperUsd)),
1809
- compact && !r.strongerUsd
1810
- ? null
1811
- : row('+', capital(COST_PART.stronger), r.strongerUsd, savingsColor(r.strongerUsd)),
1812
- compact && !r.switchUsd
1813
- ? null
1814
- : row(
1815
- '+',
1816
- capital(COST_PART.switches),
1817
- r.switchUsd,
1818
- savingsColor(r.switchUsd),
1819
- ui.dim(
1820
- [
1821
- switches === null ? null : plural(switches, 'route switch', 'route switches'),
1822
- saving > 0 && r.switchUsd > 0 ? `${percent(r.switchUsd / saving)} of the saving` : null,
1823
- ]
1824
- .filter(Boolean)
1825
- .join(' · '),
1826
- ),
1827
- ),
1828
- row(
1829
- '=',
1830
- 'Routed',
1831
- r.routedUsd,
1832
- undefined,
1833
- wide && ratio !== null
1834
- ? ui.line(
1835
- ui.text('█'.repeat(filled), { color: 'cyan' }),
1836
- ui.dim('░'.repeat(BAR - filled)),
1837
- ui.dim(` ${ratio < 2 ? percent(ratio) : `×${ratio.toFixed(1)}`} of your model`),
1838
- )
1839
- : null,
1840
- true,
1841
- ),
1842
- ].filter(Boolean);
1843
- if (legacy?.replies)
1844
- out.push(
1845
- ...dimLines(
1846
- ui,
1847
- ` includes ${usd(legacy.routedUsd)} routed before dated records, kept without a breakdown`,
1848
- columns,
1849
- ),
1850
- );
1851
- return out;
1852
- }
1853
-
1854
1762
  // Replies, turns, tokens and the cache share of the input.
1855
1763
  const statsLine = (ui, s) =>
1856
1764
  ui.dim(
@@ -1860,7 +1768,7 @@ const statsLine = (ui, s) =>
1860
1768
 
1861
1769
  // The period's cost by activity, model or tier, most first; `g` presses the next grouping. A row opens to what it
1862
1770
  // holds and its cost parts. A narrow pane drops "mostly on" (or the share) before any number.
1863
- function breakdownLines(ui, view, actions, summary, columns) {
1771
+ function breakdownLines(ui, view, actions, summary, columns, compare, billing) {
1864
1772
  const by = GROUPS.some(([id]) => id === view.usageGroup) ? view.usageGroup : 'activity';
1865
1773
  const next = GROUPS[(GROUPS.findIndex(([id]) => id === by) + 1) % GROUPS.length][0];
1866
1774
  const out = [
@@ -1880,19 +1788,21 @@ function breakdownLines(ui, view, actions, summary, columns) {
1880
1788
  ),
1881
1789
  ];
1882
1790
  const cells = summary.observed.cells;
1883
- const groups = breakdown(cells, by);
1791
+ // Tiers read low to high, as the band's bars; activities and models lead with the costliest.
1792
+ const groups =
1793
+ by === 'tier' ? breakdown(cells, by).sort((a, b) => TIER_RANK(a.name) - TIER_RANK(b.name)) : breakdown(cells, by);
1884
1794
  const missing = new Map(breakdown(summary.observed.uncompared, by).map((g) => [g.name, g]));
1885
1795
  if (!groups.length) return [...out, ui.dim(' no routed replies in this period')];
1886
1796
  const tail = !Number.isFinite(columns) || columns >= BREAKDOWN + TAIL;
1887
1797
  const tailHead = by === 'model' ? 'share' : 'mostly on';
1888
1798
  out.push(
1889
1799
  ui.dim(
1890
- ` ${''.padEnd(NAME)}${'replies'.padStart(8)}${'cost'.padStart(10)}${'vs yours'.padStart(11)}${tail ? ` ${tailHead}` : ''}`,
1800
+ ` ${''.padEnd(NAME)}${'replies'.padStart(8)}${'cost'.padStart(10)}${compare ? 'vs no routing'.padStart(15) : ''}${tail ? ` ${tailHead}` : ''}`,
1891
1801
  ),
1892
1802
  );
1893
1803
  const numbers = (sums, unavailable) => [
1894
- `${String(sums[0]).padStart(8)}${usd(sums[1]).padStart(10)}`,
1895
- unavailable ? ui.dim('—'.padStart(11)) : differenceText(ui, sums[1] - sums[2], 11),
1804
+ `${String(sums[0]).padStart(8)}${costText(sums[1], billing).padStart(10)}`,
1805
+ !compare ? null : unavailable ? ui.dim('—'.padStart(15)) : differenceText(ui, sums[1] - sums[2], 15),
1896
1806
  ];
1897
1807
  for (const group of groups) {
1898
1808
  const id = `${by}:${group.name}`;
@@ -1937,7 +1847,7 @@ function breakdownLines(ui, view, actions, summary, columns) {
1937
1847
  ui,
1938
1848
  missing.has(group.name)
1939
1849
  ? ` comparison unavailable · input ${formatTokens(input)} · output ${formatTokens(output)}`
1940
- : ` cheaper ${signedUsd(cents(cheaper))} · stronger ${signedUsd(cents(stronger))} · switch ${signedUsd(cents(switched))} · input ${formatTokens(input)} · output ${formatTokens(output)}`,
1850
+ : ` cheaper ${signedUsd(cents(cheaper))} · stronger ${signedUsd(cents(stronger))} · cache rebuilds ${signedUsd(cents(switched))} · input ${formatTokens(input)} · output ${formatTokens(output)}`,
1941
1851
  columns,
1942
1852
  ),
1943
1853
  );
@@ -1947,7 +1857,7 @@ function breakdownLines(ui, view, actions, summary, columns) {
1947
1857
 
1948
1858
  // What the period's tokens would cost on each model alone, as your model for every reply (compareModels), beside what
1949
1859
  // routing spent and your own models; a model some reply had no price on is left out.
1950
- function compareLines(ui, summary) {
1860
+ function compareLines(ui, summary, billing) {
1951
1861
  if (summary.observed.uncomparedReplies)
1952
1862
  return [ui.dim('What if unavailable: some replies have no comparable cache history.')];
1953
1863
  const yours = Object.keys(summary.yours);
@@ -1978,7 +1888,7 @@ function compareLines(ui, summary) {
1978
1888
  ui.cell(22, ui.text(row.label, row.routed ? { bold: true } : {})),
1979
1889
  ui.text('█'.repeat(filled), { color: row.routed ? 'cyan' : 'gray' }),
1980
1890
  ' '.repeat(BAR - filled),
1981
- usd(row.value).padStart(LEDGER_AMOUNT),
1891
+ costText(row.value, billing).padStart(LEDGER_AMOUNT),
1982
1892
  row.routed ? '' : row.yours ? ui.dim('—'.padStart(11)) : differenceText(ui, row.value - summary.yoursUsd, 11),
1983
1893
  );
1984
1894
  }),
@@ -1987,7 +1897,7 @@ function compareLines(ui, summary) {
1987
1897
  }
1988
1898
 
1989
1899
  // Routed cost per hour, day or week as one line of blocks, a dot for a bucket without replies; and the What if switch.
1990
- function trendLines(ui, view, actions, summary, period, now) {
1900
+ function trendLines(ui, view, actions, summary, period, now, billing) {
1991
1901
  const toggle = ui.Button({
1992
1902
  key: 'usage-compare',
1993
1903
  label: view.usageCompare ? 'Trend' : 'What if',
@@ -1995,14 +1905,15 @@ function trendLines(ui, view, actions, summary, period, now) {
1995
1905
  onPress: actions.usageCompare,
1996
1906
  });
1997
1907
  const t = trend(summary, period, now);
1998
- if (t.values.length < 2) return [ui.line(ui.head('COST'), ui.dim(' one bucket so far '), toggle)];
1908
+ if (t.values.length < 2)
1909
+ return [ui.line(ui.head(`COST BY ${t.unit.toUpperCase()}`), ui.dim(` one ${t.unit} so far `), toggle)];
1999
1910
  const max = Math.max(...t.values);
2000
1911
  const glyphs = t.values.map((v) => (v > 0 ? SPARK[Math.min(7, Math.floor((v / max) * 8))] : '·')).join('');
2001
1912
  return [
2002
1913
  ui.line(
2003
1914
  ui.head(`COST BY ${t.unit.toUpperCase()} `),
2004
1915
  ui.text(glyphs, { color: 'cyan' }),
2005
- ui.dim(` peak ${usd(max)} `),
1916
+ ui.dim(` peak ${costText(max, billing)} `),
2006
1917
  toggle,
2007
1918
  ),
2008
1919
  ];
@@ -2025,7 +1936,7 @@ function insightLines(ui, summary, actions, columns) {
2025
1936
  function insightLine(ui, insight, actions, columns) {
2026
1937
  const where = ({ activity, tier }) => [
2027
1938
  ...(ACTIVITIES.includes(activity) ? [ui.activity(activity), ui.dim(' · ')] : []),
2028
- TIERS.includes(tier) ? ui.tier(tier) : ui.dim('not routed'),
1939
+ TIERS.includes(tier) ? ui.bars(tier) : ui.dim('not routed'),
2029
1940
  ];
2030
1941
  const link = (insight) =>
2031
1942
  TIERS.includes(insight.tier)
@@ -2076,22 +1987,31 @@ function deleteLine(ui, view, actions) {
2076
1987
 
2077
1988
  // Answer first for the chosen period: routing against your model as a ledger that adds up, the tokens, the cost by
2078
1989
  // activity, model or tier, the trend or What if, and what is worth a look. Subagents follow, for the same period.
2079
- function usageTab(ui, config, view, _usage, actions, _modelOptions, columns, now) {
1990
+ function usageTab(ui, config, view, usage, actions, _modelOptions, columns, now) {
2080
1991
  const period = PERIODS.includes(view.usagePeriod) ? view.usagePeriod : 'session';
2081
1992
  const record = liveUsage(view, period === 'session' ? view.usageSession : view.usageStore);
2082
1993
  const summary = summarize(record, periodRange(period, now));
2083
1994
  // All adds the undated savings totals kept from before the usage records.
2084
1995
  const kept = period === 'all' ? allTime(record, view.savingsStore) : null;
2085
1996
  const legacy = kept?.legacy ?? null;
2086
- const r = readout(kept?.totals ?? summary);
1997
+ const agents = summarizeSubagents(
1998
+ readSubagentStore(period === 'session' ? view.subagentSession : view.subagentStore),
1999
+ period === 'session' ? { from: null, to: null } : periodRange(period, now),
2000
+ );
2001
+ const cost = periodCost(config, {
2002
+ summary: kept ? { ...summary, ...kept.totals, observed: kept.observed } : summary,
2003
+ agents,
2004
+ usage,
2005
+ });
2087
2006
  const out = [periodRow(ui, period, actions), scopeLine(ui, config, view, period, summary, now), ui.text(' ')];
2088
- out.push(...headline(ui, config, view, period, r, summary, kept?.observed ?? summary.observed));
2089
- if (r.replies) {
2090
- out.push(ui.text(' '), ...ledger(ui, config, view, { period, r, summary, legacy, columns }));
2091
- }
2007
+ out.push(...costTable(ui, config, view, period, cost, legacy, actions, columns));
2092
2008
  if (summary.observed.replies) out.push(ui.text(' '), statsLine(ui, { ...summary.observed, turns: summary.turns }));
2093
2009
  if (summary.observed.replies) {
2094
- out.push(ui.text(' '), ...breakdownLines(ui, view, actions, summary, columns), ui.text(' '));
2010
+ out.push(
2011
+ ui.text(' '),
2012
+ ...breakdownLines(ui, view, actions, summary, columns, !cost.effortOnly, cost.billing),
2013
+ ui.text(' '),
2014
+ );
2095
2015
  out.push(
2096
2016
  ...(view.usageCompare
2097
2017
  ? [
@@ -2100,15 +2020,15 @@ function usageTab(ui, config, view, _usage, actions, _modelOptions, columns, now
2100
2020
  ui.dim(' · the same tokens on one model '),
2101
2021
  ui.Button({ key: 'usage-compare', label: 'Trend', hotkey: 'c', onPress: actions.usageCompare }),
2102
2022
  ),
2103
- ...compareLines(ui, summary),
2023
+ ...compareLines(ui, summary, cost.billing),
2104
2024
  ]
2105
- : trendLines(ui, view, actions, summary, period, now)),
2025
+ : trendLines(ui, view, actions, summary, period, now, cost.billing)),
2106
2026
  ...insightLines(ui, summary, actions, columns),
2107
2027
  );
2108
2028
  }
2109
2029
  out.push(
2110
2030
  ui.text(' '),
2111
- ...subagentUsage(ui, config, view, actions, period, now, columns),
2031
+ ...subagentUsage(ui, config, view, actions, period, now, columns, cost.billing),
2112
2032
  ui.text(' '),
2113
2033
  ...footer(ui, columns),
2114
2034
  );
@@ -2116,15 +2036,136 @@ function usageTab(ui, config, view, _usage, actions, _modelOptions, columns, now
2116
2036
  return out;
2117
2037
  }
2118
2038
 
2119
- function helpLines(ui) {
2039
+ // Why a period has no cost to show.
2040
+ function emptyCost(ui, config, view, period) {
2041
+ if (period === 'session' && !modelSpec(config, view.nativeModel))
2042
+ return [ui.dim(`${modelName(view.nativeModel)} has no list price in router.json models.`)];
2043
+ const off = period === 'session' && (view.phase === 'unavailable' || view.mode === 'manual');
2120
2044
  return [
2045
+ ui.dim(
2046
+ off
2047
+ ? `Routing is ${view.phase === 'unavailable' ? 'unavailable' : 'off'}: replies use your model and are not counted.`
2048
+ : `No routed replies ${PERIOD_PHRASE[period]}.`,
2049
+ ),
2050
+ ];
2051
+ }
2052
+
2053
+ // The answer first: the difference against no routing, or why there is none.
2054
+ function costHeadline(ui, cost) {
2055
+ if (cost.diffUsd !== null)
2056
+ return ui.line(
2057
+ ui.text(diffText(cost.diffUsd, cost.baseUsd), { bold: true, color: savingsColor(cost.diffUsd) }),
2058
+ ' vs no routing',
2059
+ cost.early ? ui.text(` early sample · ${plural(cost.replies, 'reply', 'replies')}`, { color: 'yellow' }) : null,
2060
+ );
2061
+ return ui.dim(
2062
+ cost.effortOnly
2063
+ ? 'Effort routing on one model: no saving is estimated; the cost is what was billed.'
2064
+ : `${uncomparedText(cost).replace(/^./, (c) => c.toUpperCase())}: no saving is shown.`,
2065
+ );
2066
+ }
2067
+
2068
+ // The period's cost as one table that adds up: the main thread with the parts of its difference, the subagents and the
2069
+ // total. "No routing" is your model on the main thread and Claude Code's pick for each subagent; zero rows are left out.
2070
+ function costTable(ui, config, view, period, cost, legacy, actions, columns) {
2071
+ if (!cost.replies && !cost.agents) return emptyCost(ui, config, view, period);
2072
+ const compared = cost.diffUsd !== null;
2073
+ const r = cost.readout;
2074
+ // Amounts read as the session is paid: ≈ on a plan; the credits part is billed.
2075
+ const row = (label, amount, diff, base, style = {}, billing = cost.billing) =>
2076
+ ui.line(
2077
+ ui.cell(COST_LABEL, ui.text(label, style)),
2078
+ ui.text(amount === null ? ''.padStart(COST_AMOUNT) : costText(amount, billing).padStart(COST_AMOUNT), style),
2079
+ compared
2080
+ ? diff === null
2081
+ ? ui.text(''.padStart(COST_DIFF))
2082
+ : ui.text(signedUsd(diff).padStart(COST_DIFF), {
2083
+ ...style,
2084
+ ...(savingsColor(diff) ? { color: savingsColor(diff) } : {}),
2085
+ })
2086
+ : null,
2087
+ compared && base !== null ? ui.dim(costText(base, billing).padStart(COST_BASE)) : null,
2088
+ );
2089
+ const part = (label, value, note = null) =>
2090
+ value
2091
+ ? ui.line(
2092
+ ui.cell(COST_LABEL, ui.dim(` ${label}`)),
2093
+ ''.padStart(COST_AMOUNT),
2094
+ ui.text(signedUsd(value).padStart(COST_DIFF), savingsColor(value) ? { color: savingsColor(value) } : {}),
2095
+ note ? ui.dim(` ${note}`) : null,
2096
+ )
2097
+ : null;
2098
+ // The rebuilds' share of what the cheaper models saved; past all of it the switches lost money, which lostLine says.
2099
+ const share = r.switchUsd > 0 && -r.cheaperUsd > 0 ? r.switchUsd / -r.cheaperUsd : null;
2100
+ const switches = share !== null && share <= 1 ? `${percent(share)} of the saving` : null;
2101
+ const total =
2102
+ period === 'session'
2103
+ ? 'session'
2104
+ : { today: 'today', '7d': '7 days', '30d': '30 days', month: 'month', all: 'all' }[period];
2105
+ const out = [
2106
+ costHeadline(ui, cost),
2121
2107
  ui.text(' '),
2108
+ ui.line(
2109
+ ui.cell(COST_LABEL, ''),
2110
+ ui.dim('cost'.padStart(COST_AMOUNT)),
2111
+ compared ? ui.dim('vs no routing'.padStart(COST_DIFF)) : null,
2112
+ compared ? ui.dim('no routing'.padStart(COST_BASE)) : null,
2113
+ ),
2114
+ row(
2115
+ `main · ${plural(cost.replies, 'reply', 'replies')}`,
2116
+ cost.mainUsd,
2117
+ cost.mainDiff,
2118
+ compared ? r.yoursUsd : null,
2119
+ ),
2120
+ compared ? part('cheaper models', r.cheaperUsd) : null,
2121
+ compared ? part('stronger models', r.strongerUsd) : null,
2122
+ compared ? part('cache rebuilds', r.switchUsd, switches) : null,
2123
+ cost.agents
2124
+ ? row(
2125
+ `agents · ${cost.agents}`,
2126
+ cost.agentUsd,
2127
+ compared ? cost.agentDiff : null,
2128
+ compared ? cost.agentBaseUsd : null,
2129
+ )
2130
+ : null,
2131
+ ui.dim('─'.repeat(COST_LABEL + COST_AMOUNT + (compared ? COST_DIFF + COST_BASE : 0))),
2132
+ row(
2133
+ `${total} · ${cost.billing === 'billed' ? 'billed' : '≈ API value'}`,
2134
+ cost.totalUsd,
2135
+ cost.diffUsd,
2136
+ cost.baseUsd,
2137
+ { bold: true },
2138
+ ),
2139
+ cost.billing === 'mixed' ? row(' billed as credits', cost.creditsUsd, null, null, {}, 'billed') : null,
2140
+ ].filter(Boolean);
2141
+ if (legacy?.replies)
2142
+ out.push(
2143
+ ...dimLines(
2144
+ ui,
2145
+ `includes ${usd(legacy.routedUsd)} routed before dated records, kept without a breakdown`,
2146
+ columns,
2147
+ ),
2148
+ );
2149
+ if (compared && !r.early && switchesLost(r)) out.push(lostLine(ui, actions));
2150
+ return out;
2151
+ }
2152
+ // The cost table's columns: label, cost, difference, no routing.
2153
+ const COST_LABEL = 26;
2154
+ const COST_AMOUNT = 8;
2155
+ const COST_DIFF = 15;
2156
+ const COST_BASE = 12;
2157
+
2158
+ function helpLines(ui) {
2159
+ return [
2122
2160
  ui.head('ABOUT THESE NUMBERS'),
2123
- ui.dim('Cost, context and cache are Claude readings. Every $ is API prices:'),
2124
- ui.dim('tokens × router.json list prices, as if paid per token, on a plan too.'),
2125
- ui.dim('Routing vs your model holds tokens and output length the same'),
2126
- ui.dim('and does not measure answer quality. Cache benefit is before writes.'),
2127
- ui.dim('The context bar uses the routed model’s window, 20% in reserve.'),
2128
- ui.dim('Cache estimates follow the selected provider profile; minus means cheaper.'),
2161
+ ui.dim('$ is tokens × router.json list prices. On a Claude plan it is the quota’s'),
2162
+ ui.dim('API value, shown ≈$; with an API key or credits it is what is billed.'),
2163
+ ui.dim('No routing: your model on the main thread, Claude Code’s pick per agent,'),
2164
+ ui.dim('same tokens and output length. Answer quality is not measured.'),
2165
+ ui.dim('For the whole session cost, with side calls such as titles and compaction'),
2166
+ ui.dim('that the router does not see, run /cost.'),
2167
+ ui.dim('Plan bars are Claude Code’s 5-hour and 7-day readings. Tiers show as'),
2168
+ ui.dim('bars ▂▄▆█, low to high; a route never moves past 80% of its window.'),
2169
+ ui.text(' '),
2129
2170
  ];
2130
2171
  }