@alexeiled/claude-router 1.20.0 → 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,46 +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
- answerSegments,
22
- answerText,
23
- BILLINGS,
24
- billingDifference,
25
- billingOf,
26
- billingSplit,
27
- COST_PART,
28
21
  classifierLabel,
29
22
  classifierStatus,
30
23
  comparedModel,
24
+ costText,
25
+ diffText,
31
26
  formatTokens,
32
27
  GATEWAY_CLEANUP,
33
28
  GATEWAY_SETTINGS,
34
- keptSplit,
29
+ gaugeCells,
30
+ limitColor,
35
31
  liveUsage,
36
32
  missingCredentials,
37
33
  missingText,
34
+ modeLever,
38
35
  modelColor,
39
36
  modelName,
40
- observedUsageText,
41
37
  percent,
42
38
  percentPair,
43
39
  probeOf,
40
+ reasonActivity,
44
41
  recordedModels,
45
42
  routeLabel,
46
43
  routeName,
47
44
  routingModeOf,
48
45
  routingModeText,
49
46
  savingsColor,
47
+ sessionCost,
50
48
  sessionUsage,
49
+ shortReason,
50
+ shortRoute,
51
51
  shownConfig,
52
52
  signedUsd,
53
53
  sparkline,
54
- splitCompared,
55
54
  switchesLost,
56
55
  TIER_COLOR,
56
+ tierBars,
57
57
  unavailableReason,
58
+ uncomparedText,
58
59
  unpricedLine,
59
60
  usageMetrics,
60
61
  usd,
@@ -62,7 +63,7 @@ import {
62
63
  yourModel,
63
64
  } from './display.mjs';
64
65
  import { cellForModel, isSameModel } from './route.mjs';
65
- import { modelSpec, readout } from './savings.mjs';
66
+ import { modelSpec } from './savings.mjs';
66
67
  import {
67
68
  modelTotals,
68
69
  PASS_LABEL,
@@ -136,8 +137,7 @@ export function routeDraftOf(config, view) {
136
137
  return { ...structuredClone(base), base };
137
138
  }
138
139
 
139
- const dollars = (value) => (Number.isFinite(value) ? `$${value.toFixed(3)}` : 'not reported');
140
- const difference = (value) => `${value < 0 ? '−' : '+'}$${Math.abs(value).toFixed(3)}`;
140
+ const dollars = (value) => (Number.isFinite(value) ? usd(value) : 'not reported');
141
141
  // The host and port as the request sees them: user info before an `@` is not the host. An endpoint that does not
142
142
  // parse, such as one with a placeholder in its host, shows as written up to its path, and is not this machine.
143
143
  function urlOf(endpoint) {
@@ -167,7 +167,9 @@ function kit({ Box, Text, Button, Select }) {
167
167
  dim: (children) => text(children, { dimColor: true }),
168
168
  head: (children) => text(children, { bold: true, color: 'cyan' }),
169
169
  tier: (tier, children = tier) => text(children, { bold: true, color: TIER_COLOR[tier] }),
170
- 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),
171
173
  // One row of mixed parts; strings become plain Text, nulls are dropped.
172
174
  line: (...parts) =>
173
175
  Box({
@@ -195,17 +197,17 @@ export function renderPanel(
195
197
  const ui = kit(elements);
196
198
  const tab = TABS.some(([id]) => id === view.tab) ? view.tab : 'now';
197
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.
198
201
  return ui.Box({
199
202
  flexDirection: 'column',
200
203
  children: [
201
204
  ...header(ui, config, view, tab, actions),
205
+ ...(view.help ? helpLines(ui) : []),
202
206
  ...(config.provider && config.provider !== 'anthropic'
203
- ? [ui.dim(`Provider: ${config.provider} · ${view.configPath ?? config.nativePath ?? ''}`)]
207
+ ? [ui.dim(`profile ${[config.provider, view.configPath ?? config.nativePath].filter(Boolean).join(' · ')}`)]
204
208
  : []),
205
209
  ...body(ui, config, view, usage, actions, modelOptions, columns, now),
206
- ...(view.help ? helpLines(ui) : []),
207
210
  ...statusBar(ui, config, view, tab, actions),
208
- ui.Button({ key: 'close', label: 'Close', hotkey: 'q', role: 'dismiss', onPress: actions.close }),
209
211
  ],
210
212
  });
211
213
  }
@@ -215,12 +217,7 @@ export function renderPanel(
215
217
  function routingState(ui, config, view, actions) {
216
218
  if (view.phase === 'unavailable')
217
219
  return [
218
- ui.line(
219
- ui.head('ROUTING'),
220
- ' ',
221
- ui.text('unavailable', { color: 'yellow' }),
222
- ui.dim(' Claude’s model is kept'),
223
- ),
220
+ ui.line(ui.head('ROUTER'), ' ', ui.text('unavailable', { color: 'yellow' }), ui.dim(' Claude’s model is kept')),
224
221
  ui.text(unavailableReason(view), { color: 'yellow' }),
225
222
  ...(view.error === GATEWAY_SETTINGS ? GATEWAY_CLEANUP.map((line) => ui.text(line, { color: 'yellow' })) : []),
226
223
  ];
@@ -237,7 +234,7 @@ function routingState(ui, config, view, actions) {
237
234
  });
238
235
  return [
239
236
  ui.line(
240
- ui.head('ROUTING'),
237
+ ui.head('ROUTER'),
241
238
  ' ',
242
239
  option('auto', 'on', 'o'),
243
240
  ' ',
@@ -252,6 +249,7 @@ function routingState(ui, config, view, actions) {
252
249
  ];
253
250
  }
254
251
 
252
+ // The tabs carry their number keys in their labels, so every key the pane answers is on screen.
255
253
  function header(ui, config, view, tab, actions) {
256
254
  const changes = routingChanges(config, view);
257
255
  const unsaved = {
@@ -264,7 +262,7 @@ function header(ui, config, view, tab, actions) {
264
262
  ...TABS.flatMap(([id, hotkey, label]) => [
265
263
  ui.Button({
266
264
  key: `tab-${id}`,
267
- label: unsaved[id] ? `${label} ●` : label,
265
+ label: `${hotkey} ${label}${unsaved[id] ? ' ●' : ''}`,
268
266
  hotkey,
269
267
  variant: tab === id ? 'primary' : 'secondary',
270
268
  onPress: () => actions.tab(id),
@@ -277,107 +275,327 @@ function header(ui, config, view, tab, actions) {
277
275
  ];
278
276
  }
279
277
 
280
- // "Jev gave stronger tiers 88% (needs 82%) · next switch ≈ $0.48": the support for the switch the policy weighed against
281
- // 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.
282
280
  function supportText(label, estimate) {
283
281
  if (!Number.isFinite(estimate?.threshold)) return null;
284
- const [direction, mass] = Number.isFinite(estimate.upgradeMass)
285
- ? ['stronger', estimate.upgradeMass]
286
- : ['cheaper', estimate.downgradeMass];
287
- const [needs, gave] = percentPair(estimate.threshold, Number.isFinite(mass) ? mass : estimate.threshold);
288
- const cost = Number.isFinite(estimate.taxUsd) ? ` · next switch ≈ ${usd(estimate.taxUsd)}` : '';
289
- 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}`;
290
287
  }
291
288
 
292
- // What runs next turn and why first, with the one-turn pins; then this session and today as headlines, the finding
293
- // 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.
294
291
  function nowTab(ui, config, view, usage, actions, _modelOptions, columns, now) {
295
- 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) {
296
303
  const unavailable = view.phase === 'unavailable';
297
304
  const auto = view.mode === 'auto' && !unavailable;
298
305
  const current = view.selectedModel ?? view.nativeModel;
299
- const label = classifierLabel(config);
300
- const missing = unavailable ? null : missingCredentials(config, view, config.classifier);
301
- 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)];
302
308
  const mode = config.activityRouting;
303
309
  const reading = mode === 'off' ? null : activityReading(view);
304
- // In `on` an override names the tier's own model, as the routing mode runs it.
305
310
  const shown = shownConfig(config, view);
306
311
  const base = view.tier ? resolveRoute(shown, view.tier) : null;
307
312
  const override =
308
313
  mode === 'on' && view.activity && base && !sameRoute(resolveRoute(shown, view.tier, view.activity), base);
309
- const support = auto ? supportText(label, view.estimate) : null;
310
- 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(
311
320
  ui.line(
312
- 'Next turn ',
313
- view.tier ? ui.tier(view.tier, `▌${view.tier} `) : null,
321
+ ' ',
322
+ view.tier ? ui.bars(view.tier) : ui.dim('○'),
323
+ ' ',
314
324
  ui.text(routeLabel(current, view.effort), { bold: true }),
315
- auto ? null : ui.dim(unavailable ? ' Claude’s model' : ' your /model choice, routing off'),
316
- 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,
317
334
  ),
318
- reading
335
+ view.reason
319
336
  ? ui.line(
320
- 'Activity ',
321
- // `uncertain` is an answer, not an activity: it applies none.
322
- ACTIVITIES.includes(reading.choice) ? ui.activity(reading.choice) : ui.dim(reading.choice),
323
- reading.share ? ` ${reading.share}` : '',
324
- reading.others.length ? ui.dim(` ${reading.others.map(verbShare).join(' · ')}`) : null,
325
- 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,
326
340
  )
327
341
  : null,
328
- ui.line('Why ', whyText(config, view)),
329
- support ? ui.dim(` ${support}`) : null,
330
- ui.line(
331
- 'Mode ',
332
- routingModeText(view),
333
- routingModeOf(view).source === 'session' ? ui.dim(' /router mode default clears it') : null,
334
- ),
335
- view.projectError ? ui.text(` Ignored: ${view.projectError}`, { color: 'yellow' }) : null,
336
- served
337
- ? ui.line(ui.text('Served ', { color: 'yellow' }), `${modelName(view.actualModel)} · native fallback`)
338
- : null,
339
- view.pendingPin
342
+ override ? ui.dim(` ${whyText(config, view)} · tier route ${routeName(shown, base)}`) : null,
343
+ routingMode !== 'balanced' || source === 'session'
340
344
  ? ui.line(
341
- ui.text('Pinned ', { color: 'yellow' }),
342
- 'next turn → ',
343
- ui.tier(view.pendingPin),
344
- ' ',
345
- 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,
346
349
  )
347
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,
348
353
  missing
349
354
  ? ui.line(
350
- ui.text(`${classifierStatus(config, missing)}, keeping the model `, { color: 'yellow' }),
355
+ ui.text(` ${classifierStatus(config, missing)}, keeping the model `, { color: 'yellow' }),
351
356
  ui.Button({ key: 'key', label: 'Set up', hotkey: 'k', onPress: actions.key }),
352
357
  )
353
358
  : null,
354
- 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(' '),
355
376
  ];
356
- const session = sessionUsage(view, now);
357
- const today = summarize(liveUsage(view, view.usageStore), periodRange('today', now));
358
- out.push(ui.text(' '), ...sessionLines(ui, config, view, session, actions, columns, now));
359
- // Today repeats this session's part of it until another session adds to it.
360
- const ownToday = summarize(liveUsage(view, view.usageSession), periodRange('today', now));
361
- if (today.observed.replies > ownToday.observed.replies)
362
- out.push(ui.text(' '), ...todayLines(ui, config, today, actions, columns));
363
- out.push(
364
- ...sessionAgentLines(ui, view, actions, columns),
365
- ...worthLines(ui, config, 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
+ }),
366
428
  ui.text(' '),
367
- 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 = [
453
+ ui.line(
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
+ ),
368
586
  ui.line(
369
- ui.text('Cache ', { color: metrics.cacheBar.color }),
587
+ ' cache ',
370
588
  metrics.cacheBar.percent === null
371
589
  ? ui.dim('no reply yet')
372
- : ui.text(`${metrics.cacheBar.percent}% reused on the last reply`, { color: metrics.cacheBar.color }),
373
- ui.dim(' · '),
374
- `cost ${dollars(metrics.cost)} `,
375
- 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
+ ' ',
376
595
  detailButton(ui, view, actions),
377
596
  ),
378
597
  ...(view.usageDetail ? readingDetail(ui, view, metrics) : []),
379
- );
380
- return out;
598
+ ];
381
599
  }
382
600
 
383
601
  const detailButton = (ui, view, actions) =>
@@ -418,9 +636,7 @@ function readingDetail(ui, view, metrics) {
418
636
  ...(view.comparison
419
637
  ? [
420
638
  ui.text(`Compared tiers ${view.comparison.incumbent} → ${view.comparison.candidate}`),
421
- ui.text(
422
- `Next-turn difference ${difference(view.comparison.minUsd)} to ${difference(view.comparison.maxUsd)}`,
423
- ),
639
+ ui.text(`Next-turn difference ${signedUsd(view.comparison.minUsd)} to ${signedUsd(view.comparison.maxUsd)}`),
424
640
  ui.text(
425
641
  `Payback ${view.comparison.paybackTurns === null ? 'none projected' : `${view.comparison.paybackTurns} later turns`}`,
426
642
  ),
@@ -429,35 +645,6 @@ function readingDetail(ui, view, metrics) {
429
645
  ];
430
646
  }
431
647
 
432
- const verbShare = (text) => text.replace(/^(\S+)/, (name) => activityVerb(name));
433
-
434
- // One button per tier with the classifier's support on the last turn, the current tier marked; a press pins the next
435
- // turn only. Without routing there is nothing to pin.
436
- function pinLine(ui, view, auto, unavailable, actions, columns) {
437
- if (!auto)
438
- return ui.line(
439
- 'Pin next ',
440
- ui.dim(unavailable ? 'needs routing, which is unavailable' : 'needs routing on (o above)'),
441
- );
442
- return ui.line(
443
- 'Pin next ',
444
- ...LADDER.flatMap((tier) => {
445
- const support = view.probabilities?.[tier];
446
- return [
447
- ui.Button({
448
- key: `pin-${tier}`,
449
- label: `${view.tier === tier ? '▶ ' : ''}${tier} ${Number.isFinite(support) ? percent(support) : '—'}`,
450
- variant: view.pendingPin === tier ? 'primary' : 'secondary',
451
- onPress: () => actions.pin(tier),
452
- }),
453
- ' ',
454
- ];
455
- }),
456
- !Number.isFinite(columns) || columns >= PIN_HINT_COLUMNS ? ui.dim(' next turn only') : null,
457
- );
458
- }
459
- const PIN_HINT_COLUMNS = 80;
460
-
461
648
  // "13:41", or "Oct 12 13:41" for another day than `now`'s.
462
649
  const clockText = (ms) => new Date(ms).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' });
463
650
  const sinceText = (ms, now) =>
@@ -484,134 +671,6 @@ function fittedStrip(strip, columns, since, now) {
484
671
  return { cells, note: note() };
485
672
  }
486
673
 
487
- // This session: since its first routed reply, its routed replies and route switches; its replies as a strip colored
488
- // by tier, with the replies per tier, and the routed replies per activity; the last switch; and routing against your
489
- // model, linked to Usage.
490
- function sessionLines(ui, config, view, summary, actions, columns, now) {
491
- const since = liveUsage(view, view.usageSession).since;
492
- const strip = view.strip?.cells?.length ? fittedStrip(view.strip, columns, since, now) : null;
493
- const counts = {};
494
- for (const cell of view.strip?.cells ?? [])
495
- for (const [key, n] of Object.entries(cell)) counts[key] = (counts[key] ?? 0) + n;
496
- const replies = Object.values(counts).reduce((sum, n) => sum + n, 0);
497
- const switches = summary.switches.tier + summary.switches.activity;
498
- const head = [
499
- Number.isFinite(since) ? `since ${sinceText(since, now)}` : null,
500
- summary.observed.replies
501
- ? `${plural(summary.observed.replies, 'routed reply', 'routed replies')}${view.usageLive?.length ? ` (${view.usageLive.length} live)` : ''}`
502
- : replies
503
- ? plural(replies, 'reply', 'replies')
504
- : null,
505
- summary.turns ? plural(switches, 'route switch', 'route switches') : null,
506
- ].filter(Boolean);
507
- if (!strip && !summary.observed.replies) return [ui.line(ui.head('SESSION'), ui.dim(' · no replies yet'))];
508
- const out = [ui.line(ui.head('SESSION'), head.length ? ui.dim(` · ${head.join(' · ')}`) : null)];
509
- // The band's session row, then the parts that add up to it.
510
- const split = billingSplit(config, summary);
511
- if (summary.observed.uncomparedReplies) {
512
- out.push(
513
- ui.line(
514
- ' ',
515
- ui.text(observedUsageText(summary.observed, split)),
516
- ' ',
517
- ui.Button({ key: 'usage-session', label: 'Usage', onPress: () => actions.usageFor('session') }),
518
- ),
519
- );
520
- } else if (summary.replies) {
521
- const r = readout(summary);
522
- out.push(
523
- answerLine(
524
- ui,
525
- r,
526
- split,
527
- comparedModel(config, view, summary),
528
- () => actions.usageFor('session'),
529
- 'session',
530
- columns,
531
- ),
532
- );
533
- if (!r.early)
534
- out.push(
535
- ...(split
536
- ? billingLedger(ui, split)
537
- : ledger(ui, config, view, { period: 'session', r, summary, legacy: null, columns, compact: true })),
538
- );
539
- if (!r.early && !split && switchesLost(r)) out.push(lostLine(ui, actions));
540
- }
541
- if (strip) {
542
- out.push(
543
- ui.line(
544
- ' ',
545
- ...strip.cells.map((cell) => {
546
- const tier = cellTier(cell);
547
- return tier === 'none' ? ui.dim('·') : ui.tier(tier, '█');
548
- }),
549
- strip.note ? ui.dim(` ${strip.note}`) : null,
550
- ),
551
- ui.line(
552
- ' ',
553
- ...TIERS.filter((tier) => counts[tier]).flatMap((tier) => [ui.tier(tier, '■ '), `${tier} ${counts[tier]} `]),
554
- counts.none ? ui.dim(`· not routed ${counts.none}`) : null,
555
- ),
556
- );
557
- }
558
- const used = breakdown(summary.observed.cells, 'activity')
559
- .filter((group) => ACTIVITIES.includes(group.name))
560
- .sort((a, b) => b.sums[0] - a.sums[0])
561
- .map((group) => [group.name, `${activityVerb(group.name)} ${group.sums[0]}`]);
562
- // The most used first, as many as fit the pane; the rest as a count.
563
- const shown = [];
564
- for (const [i, entry] of used.entries()) {
565
- const rest = used.length - i - 1;
566
- const width =
567
- 2 + [...shown, entry].map(([, text]) => text).join(' · ').length + (rest ? ` · +${rest} more`.length : 0);
568
- if (Number.isFinite(columns) && width > columns && shown.length) break;
569
- shown.push(entry);
570
- }
571
- if (shown.length)
572
- out.push(
573
- ui.line(
574
- ' ',
575
- ...shown.flatMap(([name, text], i) => [
576
- ui.activity(name),
577
- ui.dim(`${text.slice(activityVerb(name).length)}${i < shown.length - 1 ? ' · ' : ''}`),
578
- ]),
579
- shown.length < used.length ? ui.dim(` · +${used.length - shown.length} more`) : null,
580
- ),
581
- );
582
- const last = view.lastSwitch;
583
- if (Number.isFinite(last?.at) && last.from && last.to) out.push(lastSwitchLine(ui, last, now));
584
- return out;
585
- }
586
-
587
- // "last switch 13:41 medium → high · debugging"; routes by name when the switch kept the tier.
588
- function lastSwitchLine(ui, last, now) {
589
- const byTier = TIERS.includes(last.from.tier) && TIERS.includes(last.to.tier) && last.from.tier !== last.to.tier;
590
- return ui.line(
591
- ' ',
592
- ui.dim(`last switch ${sinceText(last.at, now)} `),
593
- ...(byTier
594
- ? [ui.tier(last.from.tier), ui.dim(' → '), ui.tier(last.to.tier)]
595
- : [routeLabel(last.from.model, last.from.effort), ui.dim(' → '), routeLabel(last.to.model, last.to.effort)]),
596
- ...(ACTIVITIES.includes(last.activity) ? [ui.dim(' · '), ui.activity(last.activity)] : []),
597
- );
598
- }
599
-
600
- // Routing against your model in the band's words, "routing −$1.84 (−22%) vs Opus 5.5 · xhigh", with the Usage tab on
601
- // the same period one press away; an early sample says so.
602
- function answerLine(ui, r, split, against, open, period, columns) {
603
- const early = ' · early sample';
604
- const width = 2 + answerText(r, split).length + ` vs ${against}`.length + early.length + USAGE_LINK;
605
- return ui.line(
606
- ' ',
607
- ...answerParts(ui, r, split, against),
608
- r.early && (!Number.isFinite(columns) || width <= columns) ? ui.dim(early) : null,
609
- ' ',
610
- ui.Button({ key: `usage-${period}`, label: 'Usage', onPress: open }),
611
- );
612
- }
613
- // " [ Usage ]" after the answer.
614
- const USAGE_LINK = 11;
615
674
  // Cache rebuilds cost more than the cheaper models saved: the policy's switch weight is the lever.
616
675
  const lostLine = (ui, actions) =>
617
676
  ui.line(
@@ -619,49 +678,6 @@ const lostLine = (ui, actions) =>
619
678
  ui.Button({ key: 'session-policy', label: 'Policy', onPress: () => actions.tab('policy') }),
620
679
  );
621
680
 
622
- // Today across sessions, shown once another session added to it.
623
- function todayLines(ui, config, summary, actions, columns) {
624
- const switches = summary.switches.tier + summary.switches.activity;
625
- const split = billingSplit(config, summary);
626
- return [
627
- ui.line(
628
- ui.head('TODAY'),
629
- ui.dim(
630
- ` · ${plural(summary.observed.replies, 'routed reply', 'routed replies')} · ${plural(switches, 'route switch', 'route switches')}`,
631
- ),
632
- ),
633
- summary.observed.uncomparedReplies
634
- ? ui.line(
635
- ui.text(observedUsageText(summary.observed, split)),
636
- ' ',
637
- ui.Button({ key: 'usage-today', label: 'Usage', onPress: () => actions.usageFor('today') }),
638
- )
639
- : answerLine(
640
- ui,
641
- readout(summary),
642
- split,
643
- 'each session’s own model',
644
- () => actions.usageFor('today'),
645
- 'today',
646
- columns,
647
- ),
648
- ];
649
- }
650
-
651
- // The findings that hold within one billing: with plan and credits apart, a part against your model would subtract
652
- // quota from cash, so only the share of the cost stays.
653
- const billingInsights = (summary, split) => insights(summary).filter((insight) => !split || insight.kind === 'cost');
654
-
655
- // Today's first finding from Usage's WORTH A LOOK, with the tab that changes it; nothing when there is none.
656
- function worthLines(ui, config, summary, actions, columns) {
657
- const [first] =
658
- !summary.observed.uncomparedReplies && summary.replies >= INSIGHT_REPLIES
659
- ? billingInsights(summary, billingSplit(config, summary))
660
- : [];
661
- if (!first) return [];
662
- return [ui.text(' '), ui.line(ui.head('WORTH A LOOK'), ui.dim(' · today')), insightLine(ui, first, actions, columns)];
663
- }
664
-
665
681
  // Rows: [key, label, format, router.json field]. Typed as tuples so tsc keeps each position's type.
666
682
  /** @type {[string, string, (value: number) => string, string][]} */
667
683
  const POLICY_ROWS = [
@@ -700,7 +716,7 @@ const marker = (ui, changed) => ui.cell(2, changed ? ui.text('●', { color: 'ye
700
716
  // "sonnet·high": the route's models key and its effort, short enough for the grid; `inherit` for a route that leaves
701
717
  // the effort to the session, and no effort for a model without efforts. The key, not the model name: two Haiku versions
702
718
  // in router.json still read apart.
703
- function shortRoute(config, route, narrow) {
719
+ function gridRoute(config, route, narrow) {
704
720
  if (!config.models[route.model].efforts.length) return route.model;
705
721
  const effort = route.effort ?? INHERIT;
706
722
  return `${route.model}·${narrow ? (EFFORT_SHORT[effort] ?? effort) : effort}`;
@@ -844,7 +860,7 @@ function routesTab(ui, config, view, _usage, actions, modelOptions, columns) {
844
860
  cellButton(
845
861
  TIER_ROW,
846
862
  tier,
847
- `${shortRoute(draft, draft.routes[tier], narrow)}${changes.tiers.includes(tier) ? '●' : ''}`,
863
+ `${gridRoute(draft, draft.routes[tier], narrow)}${changes.tiers.includes(tier) ? '●' : ''}`,
848
864
  false,
849
865
  ),
850
866
  ),
@@ -860,7 +876,7 @@ function routesTab(ui, config, view, _usage, actions, modelOptions, columns) {
860
876
  if (sameRoute(route, draft.routes[tier])) return cellButton(activity, tier, `·${edited}`, true);
861
877
  const preset = builtIn(draft, activity, tier);
862
878
  const mark = preset && sameRoute(route, { model: preset.model, effort: preset.effort ?? null }) ? '°' : '';
863
- 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');
864
880
  }),
865
881
  ),
866
882
  );
@@ -1326,10 +1342,8 @@ function storeUsage(ui, store, metrics) {
1326
1342
  // The footer as [text, joiner] pieces, packed to the pane: two lines at full width, more in a narrow pane, never a
1327
1343
  // line that ends in a joiner.
1328
1344
  const SAVINGS_FOOTER = [
1329
- ['API list prices', ' · '],
1330
- ['same tokens and output length', ' · '],
1331
- ['not a bill;', ' '],
1332
- ['on a Claude plan it stands for quota', ' · '],
1345
+ ['$ = tokens × list prices', ' · '],
1346
+ ['≈ = API value of plan quota', ' · '],
1333
1347
  ['answer quality not measured', ''],
1334
1348
  ];
1335
1349
  const FULL_WIDTH = 68;
@@ -1526,7 +1540,7 @@ function moveText(m) {
1526
1540
  }
1527
1541
 
1528
1542
  // One row of the subagent table; open, the models it ran on with their cost, and its requests and retry proxies.
1529
- 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 }) {
1530
1544
  const open = view.usageOpen === id;
1531
1545
  const models = Object.entries(counts.models)
1532
1546
  .filter(([, m]) => m.agents > 0)
@@ -1540,7 +1554,7 @@ function agentRow(ui, view, actions, { id, name, counts, routed, why, narrow, co
1540
1554
  const t = modelTotals(counts);
1541
1555
  // A row none of whose requests had a price says so rather than $0.00.
1542
1556
  const priced = counts.pricedRequests > 0;
1543
- 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)));
1544
1558
  const out = [
1545
1559
  ui.line(
1546
1560
  ' ',
@@ -1584,7 +1598,7 @@ function agentRow(ui, view, actions, { id, name, counts, routed, why, narrow, co
1584
1598
  // plugin install). A strip of every agent by the model it ran on, filled where the router moved it off Claude Code's
1585
1599
  // pick, and the routed agents' cost against those picks. Then the routed types and the pass-throughs, each with its
1586
1600
  // squares, agents and cost, opening to its models; a pass-through says why Claude Code picked.
1587
- function subagentUsage(ui, config, view, actions, period, now, columns) {
1601
+ function subagentUsage(ui, config, view, actions, period, now, columns, billing) {
1588
1602
  const mode = config.subagentRouting;
1589
1603
  const record = readSubagentStore(period === 'session' ? view.subagentSession : view.subagentStore);
1590
1604
  const s = summarizeSubagents(record, periodRange(period, now));
@@ -1601,7 +1615,7 @@ function subagentUsage(ui, config, view, actions, period, now, columns) {
1601
1615
  const undated = s.undated
1602
1616
  ? [
1603
1617
  ui.dim(
1604
- ` + ${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)}`,
1605
1619
  ),
1606
1620
  ]
1607
1621
  : [];
@@ -1620,7 +1634,7 @@ function subagentUsage(ui, config, view, actions, period, now, columns) {
1620
1634
  }
1621
1635
  const narrow = Number.isFinite(columns) && columns < AGENT_ROW;
1622
1636
  out.push(...agentSummary(ui, s, columns), ...agentTrend(ui, s, period, now), ...undated);
1623
- const rowOf = (fields) => agentRow(ui, view, actions, { narrow, columns, ...fields });
1637
+ const rowOf = (fields) => agentRow(ui, view, actions, { narrow, columns, billing, ...fields });
1624
1638
  if (routed.length) {
1625
1639
  out.push(
1626
1640
  ui.text(' '),
@@ -1653,22 +1667,6 @@ function subagentUsage(ui, config, view, actions, period, now, columns) {
1653
1667
  return out;
1654
1668
  }
1655
1669
 
1656
- // This session's subagents on the Now tab: how many run now, the strip, and how routing paid off. Nothing without any.
1657
- function sessionAgentLines(ui, view, actions, columns) {
1658
- const s = summarizeSubagents(readSubagentStore(view.subagentSession), { from: null, to: null });
1659
- const running = view.subagentsRunning ?? 0;
1660
- const any = [...Object.values(s.routed), ...Object.values(s.passed)].some((c) => c.agents > 0);
1661
- if (!any && !running) return [];
1662
- const head = ui.line(
1663
- ui.head('SUBAGENTS'),
1664
- ui.dim(' · this session'),
1665
- running ? ui.text(` · ● ${running} running`, { color: 'yellow' }) : null,
1666
- ' ',
1667
- ui.Button({ key: 'usage-agents', label: 'Usage', onPress: () => actions.usageFor('session') }),
1668
- );
1669
- return [ui.text(' '), head, ...(any ? agentSummary(ui, s, columns) : [])];
1670
- }
1671
-
1672
1670
  const PERIOD_LABEL = { session: 'Session', today: 'Today', '7d': '7d', '30d': '30d', month: 'Month', all: 'All' };
1673
1671
  // "No routed replies …" for each period.
1674
1672
  const PERIOD_PHRASE = {
@@ -1687,11 +1685,12 @@ const GROUPS = [
1687
1685
  // What an open row lists: the routes of an activity, the activities of a model or a tier.
1688
1686
  const CHILD_BY = { activity: 'route', model: 'activity', tier: 'activity' };
1689
1687
  // The ledger's label column after its sign, and its amount column.
1690
- const LEDGER_LABEL = 20;
1691
1688
  const LEDGER_AMOUNT = 9;
1692
1689
  // The breakdown: the open mark, the name, replies, cost and vs yours; "mostly on" or the share only where it fits.
1693
1690
  const NAME = 20;
1694
- 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);
1695
1694
  const TAIL = 23;
1696
1695
  // Bars at full scale: the routed share of your model, and the costliest row of What if.
1697
1696
  const BAR = 22;
@@ -1718,7 +1717,7 @@ const differenceText = (ui, usdValue, width) => {
1718
1717
  function groupName(ui, by, name) {
1719
1718
  if (name === 'none') return ui.dim(by === 'activity' ? 'no activity' : 'not routed');
1720
1719
  if (by === 'activity') return ui.activity(name);
1721
- if (by === 'tier') return ui.tier(name);
1720
+ if (by === 'tier') return ui.bars(name);
1722
1721
  return ui.text(by === 'model' ? modelName(name) : routeText(name));
1723
1722
  }
1724
1723
 
@@ -1760,164 +1759,6 @@ function scopeLine(ui, config, view, period, summary, now) {
1760
1759
  return ui.dim(`all projects · ${span} · each session vs its own model`);
1761
1760
  }
1762
1761
 
1763
- // The answer first, in the band's words: "routing −$1.84 (−22%) vs Opus 5.5 · xhigh", or why there is nothing to compare.
1764
- function headline(ui, config, view, period, r, summary, observed, split) {
1765
- if (observed.uncomparedReplies)
1766
- return [
1767
- ui.text(observedUsageText(observed, split), { bold: true }),
1768
- ui.dim(
1769
- `${observed.uncomparedReplies} of ${observed.replies} replies have no comparison; savings are not estimated for them.`,
1770
- ),
1771
- ...(r.replies
1772
- ? [
1773
- ui.dim(`${plural(r.replies, 'comparable reply', 'comparable replies')} only:`),
1774
- ui.line(
1775
- ...answerParts(
1776
- ui,
1777
- r,
1778
- split,
1779
- period === 'session' ? comparedModel(config, view, summary) : 'each session’s own model',
1780
- ),
1781
- ),
1782
- ]
1783
- : []),
1784
- ];
1785
- if (!r.replies) {
1786
- // A reply is priced against your model, so on a model without a price none is counted.
1787
- if (period === 'session' && !modelSpec(config, view.nativeModel))
1788
- return [ui.dim(`${modelName(view.nativeModel)} has no list price in router.json models.`)];
1789
- const off = period === 'session' && (view.phase === 'unavailable' || view.mode === 'manual');
1790
- return [
1791
- ui.dim(
1792
- off
1793
- ? `Routing is ${view.phase === 'unavailable' ? 'unavailable' : 'off'}: replies use your model and are not counted.`
1794
- : `No routed replies ${PERIOD_PHRASE[period]}.`,
1795
- ),
1796
- ];
1797
- }
1798
- const against = period === 'session' ? comparedModel(config, view, summary) : 'each session’s own model';
1799
- return [
1800
- ui.line(
1801
- ...answerParts(ui, r, split, against),
1802
- r.early ? ui.text(` early sample · ${plural(r.replies, 'reply', 'replies')}`, { color: 'yellow' }) : null,
1803
- ),
1804
- ];
1805
- }
1806
-
1807
- const capital = (words) => words[0].toUpperCase() + words.slice(1);
1808
-
1809
- // "routing −$1.84 (−22%) vs Opus 5.5 · xhigh", the answer bold in the savings color, as the band says it; per billing
1810
- // each difference in its own color. A split without one billing for your models compares with nothing.
1811
- function answerParts(ui, r, split, against) {
1812
- return [
1813
- ...answerSegments(r, split).map(({ text, value }) =>
1814
- ui.text(text, { bold: true, ...(savingsColor(value) ? { color: savingsColor(value) } : {}) }),
1815
- ),
1816
- split && !splitCompared(split) ? null : ` vs ${against}`,
1817
- ].filter(Boolean);
1818
- }
1819
-
1820
- // Per billing, what the replies cost, what your model would have, and the difference: plan dollars stand for quota
1821
- // and credits are paid, so neither is added to the other. `note` says so under the table.
1822
- function billingLedger(ui, split, note = false) {
1823
- const amount = (value) => (value === null ? '—' : usd(value)).padStart(BILLING_AMOUNT);
1824
- return [
1825
- ui.dim(
1826
- ` ${''.padEnd(LEDGER_LABEL)}${'routed'.padStart(LEDGER_AMOUNT)}${'your model'.padStart(BILLING_AMOUNT)}${'difference'.padStart(BILLING_AMOUNT)}`,
1827
- ),
1828
- ...BILLINGS.map((billing) => {
1829
- const side = split[billing];
1830
- return ui.line(
1831
- ' ',
1832
- ui.cell(LEDGER_LABEL, ui.text(capital(billing))),
1833
- usd(side.routedUsd).padStart(LEDGER_AMOUNT),
1834
- amount(side.yoursUsd),
1835
- side.yoursUsd === null ? amount(null) : differenceText(ui, billingDifference(side), BILLING_AMOUNT),
1836
- );
1837
- }),
1838
- ...(note ? [ui.dim(' at list prices; plan dollars stand for quota, credits are paid')] : []),
1839
- ];
1840
- }
1841
- const BILLING_AMOUNT = 13;
1842
-
1843
- // Your model − cheaper models + stronger models + switch cache writes = routed, in whole cents that add up (readout).
1844
- function ledger(ui, config, view, { period, r, summary, legacy, columns, compact = false }) {
1845
- const tier = yourTier(config, view);
1846
- const row = (sign, label, value, color, note = null, bold = false) =>
1847
- ui.line(
1848
- ui.dim(` ${sign} `),
1849
- ui.cell(LEDGER_LABEL, ui.text(label, bold ? { bold: true } : {})),
1850
- ui.text(usd(value).padStart(LEDGER_AMOUNT), { ...(color ? { color } : {}), ...(bold ? { bold: true } : {}) }),
1851
- note ? ' ' : null,
1852
- note,
1853
- );
1854
- // The undated totals kept no switch count, so All with them names none.
1855
- const switches = legacy?.replies ? null : summary.switches.tier + summary.switches.activity;
1856
- const recorded = period === 'session' ? recordedModels(config, view, summary) : null;
1857
- const saving = -r.cheaperUsd;
1858
- const ratio = r.yoursUsd > 0 ? r.routedUsd / r.yoursUsd : null;
1859
- const wide = !Number.isFinite(columns) || columns >= 4 + LEDGER_LABEL + LEDGER_AMOUNT + 3 + BAR + 16;
1860
- const filled = ratio === null ? 0 : Math.max(0, Math.min(BAR, Math.round(ratio * BAR)));
1861
- const out = [
1862
- row(
1863
- ' ',
1864
- 'Your model',
1865
- r.yoursUsd,
1866
- undefined,
1867
- period !== 'session'
1868
- ? ui.dim('each session’s own model')
1869
- : recorded
1870
- ? ui.dim(recorded)
1871
- : tier
1872
- ? ui.tier(tier, yourModel(view))
1873
- : ui.text(yourModel(view)),
1874
- ),
1875
- compact && !r.cheaperUsd ? null : row('−', capital(COST_PART.cheaper), r.cheaperUsd, savingsColor(r.cheaperUsd)),
1876
- compact && !r.strongerUsd
1877
- ? null
1878
- : row('+', capital(COST_PART.stronger), r.strongerUsd, savingsColor(r.strongerUsd)),
1879
- compact && !r.switchUsd
1880
- ? null
1881
- : row(
1882
- '+',
1883
- capital(COST_PART.switches),
1884
- r.switchUsd,
1885
- savingsColor(r.switchUsd),
1886
- ui.dim(
1887
- [
1888
- switches === null ? null : plural(switches, 'route switch', 'route switches'),
1889
- saving > 0 && r.switchUsd > 0 ? `${percent(r.switchUsd / saving)} of the saving` : null,
1890
- ]
1891
- .filter(Boolean)
1892
- .join(' · '),
1893
- ),
1894
- ),
1895
- row(
1896
- '=',
1897
- 'Routed',
1898
- r.routedUsd,
1899
- undefined,
1900
- wide && ratio !== null
1901
- ? ui.line(
1902
- ui.text('█'.repeat(filled), { color: 'cyan' }),
1903
- ui.dim('░'.repeat(BAR - filled)),
1904
- ui.dim(` ${ratio < 2 ? percent(ratio) : `×${ratio.toFixed(1)}`} of your model`),
1905
- )
1906
- : null,
1907
- true,
1908
- ),
1909
- ].filter(Boolean);
1910
- if (legacy?.replies)
1911
- out.push(
1912
- ...dimLines(
1913
- ui,
1914
- ` includes ${usd(legacy.routedUsd)} routed before dated records, kept without a breakdown`,
1915
- columns,
1916
- ),
1917
- );
1918
- return out;
1919
- }
1920
-
1921
1762
  // Replies, turns, tokens and the cache share of the input.
1922
1763
  const statsLine = (ui, s) =>
1923
1764
  ui.dim(
@@ -1926,10 +1767,8 @@ const statsLine = (ui, s) =>
1926
1767
  );
1927
1768
 
1928
1769
  // The period's cost by activity, model or tier, most first; `g` presses the next grouping. A row opens to what it
1929
- // holds and its cost parts. A narrow pane drops "mostly on" (or the share) before any number. With a billing split, a
1930
- // row whose models are not all billed as your model is names its billing in place of `vs yours` and its parts: that
1931
- // difference would subtract quota from cash.
1932
- function breakdownLines(ui, config, view, actions, summary, columns, split) {
1770
+ // holds and its cost parts. A narrow pane drops "mostly on" (or the share) before any number.
1771
+ function breakdownLines(ui, view, actions, summary, columns, compare, billing) {
1933
1772
  const by = GROUPS.some(([id]) => id === view.usageGroup) ? view.usageGroup : 'activity';
1934
1773
  const next = GROUPS[(GROUPS.findIndex(([id]) => id === by) + 1) % GROUPS.length][0];
1935
1774
  const out = [
@@ -1949,34 +1788,26 @@ function breakdownLines(ui, config, view, actions, summary, columns, split) {
1949
1788
  ),
1950
1789
  ];
1951
1790
  const cells = summary.observed.cells;
1952
- 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);
1953
1794
  const missing = new Map(breakdown(summary.observed.uncompared, by).map((g) => [g.name, g]));
1954
1795
  if (!groups.length) return [...out, ui.dim(' no routed replies in this period')];
1955
1796
  const tail = !Number.isFinite(columns) || columns >= BREAKDOWN + TAIL;
1956
1797
  const tailHead = by === 'model' ? 'share' : 'mostly on';
1957
1798
  out.push(
1958
1799
  ui.dim(
1959
- ` ${''.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}` : ''}`,
1960
1801
  ),
1961
1802
  );
1962
- const otherBilling = (rowCells) => {
1963
- if (!split) return null;
1964
- const billings = new Set(breakdown(rowCells, 'model').map(({ name }) => billingOf(config, name)));
1965
- if (billings.size === 1 && billings.has(split.yours)) return null;
1966
- return billings.size === 1 ? [...billings][0] : 'both';
1967
- };
1968
- const numbers = (sums, unavailable, rowCells) => {
1969
- const other = unavailable ? null : otherBilling(rowCells);
1970
- return [
1971
- `${String(sums[0]).padStart(8)}${usd(sums[1]).padStart(10)}`,
1972
- unavailable || other ? ui.dim((other ?? '—').padStart(11)) : differenceText(ui, sums[1] - sums[2], 11),
1973
- ];
1974
- };
1803
+ const numbers = (sums, unavailable) => [
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),
1806
+ ];
1975
1807
  for (const group of groups) {
1976
1808
  const id = `${by}:${group.name}`;
1977
1809
  const open = view.usageOpen === id;
1978
- const groupCells = cellsWhere(cells, by, group.name);
1979
- const route = by === 'model' ? null : mostlyOn(groupCells);
1810
+ const route = by === 'model' ? null : mostlyOn(cellsWhere(cells, by, group.name));
1980
1811
  out.push(
1981
1812
  ui.line(
1982
1813
  ' ',
@@ -1988,7 +1819,7 @@ function breakdownLines(ui, config, view, actions, summary, columns, split) {
1988
1819
  }),
1989
1820
  ' ',
1990
1821
  ui.cell(NAME, groupName(ui, by, group.name)),
1991
- ...numbers(group.sums, missing.has(group.name), groupCells),
1822
+ ...numbers(group.sums, missing.has(group.name)),
1992
1823
  !tail
1993
1824
  ? null
1994
1825
  : by === 'model'
@@ -2007,20 +1838,16 @@ function breakdownLines(ui, config, view, actions, summary, columns, split) {
2007
1838
  ...numbers(
2008
1839
  child.sums,
2009
1840
  missing.get(group.name)?.children.some((c) => c.name === child.name),
2010
- cellsWhere(groupCells, CHILD_BY[by], child.name),
2011
1841
  ),
2012
1842
  ),
2013
1843
  );
2014
1844
  const [, , , cheaper, stronger, switched, input, , output] = group.sums;
2015
- const tokens = `input ${formatTokens(input)} · output ${formatTokens(output)}`;
2016
1845
  out.push(
2017
1846
  ...dimLines(
2018
1847
  ui,
2019
1848
  missing.has(group.name)
2020
- ? ` comparison unavailable · ${tokens}`
2021
- : otherBilling(groupCells)
2022
- ? ` ${tokens}`
2023
- : ` cheaper ${signedUsd(cents(cheaper))} · stronger ${signedUsd(cents(stronger))} · switch ${signedUsd(cents(switched))} · ${tokens}`,
1849
+ ? ` comparison unavailable · 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)}`,
2024
1851
  columns,
2025
1852
  ),
2026
1853
  );
@@ -2029,9 +1856,8 @@ function breakdownLines(ui, config, view, actions, summary, columns, split) {
2029
1856
  }
2030
1857
 
2031
1858
  // What the period's tokens would cost on each model alone, as your model for every reply (compareModels), beside what
2032
- // routing spent and your own models; a model some reply had no price on is left out. With a billing split, a model
2033
- // billed otherwise than your model names its billing in place of the difference.
2034
- function compareLines(ui, config, summary, split) {
1859
+ // routing spent and your own models; a model some reply had no price on is left out.
1860
+ function compareLines(ui, summary, billing) {
2035
1861
  if (summary.observed.uncomparedReplies)
2036
1862
  return [ui.dim('What if unavailable: some replies have no comparable cache history.')];
2037
1863
  const yours = Object.keys(summary.yours);
@@ -2043,7 +1869,6 @@ function compareLines(ui, config, summary, split) {
2043
1869
  value,
2044
1870
  routed: false,
2045
1871
  yours: model === single,
2046
- other: split && billingOf(config, model) !== split.yours ? billingOf(config, model) : null,
2047
1872
  }));
2048
1873
  if (!rows.some((row) => row.yours))
2049
1874
  rows.push({
@@ -2051,9 +1876,8 @@ function compareLines(ui, config, summary, split) {
2051
1876
  value: summary.yoursUsd,
2052
1877
  routed: false,
2053
1878
  yours: true,
2054
- other: null,
2055
1879
  });
2056
- rows.push({ label: 'Routed', value: summary.routedUsd, routed: true, yours: false, other: null });
1880
+ rows.push({ label: 'Routed', value: summary.routedUsd, routed: true, yours: false });
2057
1881
  rows.sort((a, b) => a.value - b.value);
2058
1882
  const max = Math.max(...rows.map((row) => row.value));
2059
1883
  return [
@@ -2064,21 +1888,16 @@ function compareLines(ui, config, summary, split) {
2064
1888
  ui.cell(22, ui.text(row.label, row.routed ? { bold: true } : {})),
2065
1889
  ui.text('█'.repeat(filled), { color: row.routed ? 'cyan' : 'gray' }),
2066
1890
  ' '.repeat(BAR - filled),
2067
- usd(row.value).padStart(LEDGER_AMOUNT),
2068
- row.routed
2069
- ? ''
2070
- : row.yours || row.other
2071
- ? ui.dim((row.other ?? '—').padStart(11))
2072
- : differenceText(ui, row.value - summary.yoursUsd, 11),
1891
+ costText(row.value, billing).padStart(LEDGER_AMOUNT),
1892
+ row.routed ? '' : row.yours ? ui.dim('—'.padStart(11)) : differenceText(ui, row.value - summary.yoursUsd, 11),
2073
1893
  );
2074
1894
  }),
2075
1895
  ui.dim(' same tokens and output on each model alone · answer quality not measured'),
2076
- ...(split ? [ui.dim(' Routed adds plan and credits at list prices; plan dollars stand for quota')] : []),
2077
1896
  ];
2078
1897
  }
2079
1898
 
2080
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.
2081
- function trendLines(ui, view, actions, summary, period, now) {
1900
+ function trendLines(ui, view, actions, summary, period, now, billing) {
2082
1901
  const toggle = ui.Button({
2083
1902
  key: 'usage-compare',
2084
1903
  label: view.usageCompare ? 'Trend' : 'What if',
@@ -2086,14 +1905,15 @@ function trendLines(ui, view, actions, summary, period, now) {
2086
1905
  onPress: actions.usageCompare,
2087
1906
  });
2088
1907
  const t = trend(summary, period, now);
2089
- 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)];
2090
1910
  const max = Math.max(...t.values);
2091
1911
  const glyphs = t.values.map((v) => (v > 0 ? SPARK[Math.min(7, Math.floor((v / max) * 8))] : '·')).join('');
2092
1912
  return [
2093
1913
  ui.line(
2094
1914
  ui.head(`COST BY ${t.unit.toUpperCase()} `),
2095
1915
  ui.text(glyphs, { color: 'cyan' }),
2096
- ui.dim(` peak ${usd(max)} `),
1916
+ ui.dim(` peak ${costText(max, billing)} `),
2097
1917
  toggle,
2098
1918
  ),
2099
1919
  ];
@@ -2101,9 +1921,9 @@ function trendLines(ui, view, actions, summary, period, now) {
2101
1921
 
2102
1922
  // The evidence worth a look, each with the tab that changes it: the cell that carried most of the cost, the switch
2103
1923
  // writes against the saving, the cell that ran above your model. Never which model to use.
2104
- function insightLines(ui, summary, actions, columns, split) {
1924
+ function insightLines(ui, summary, actions, columns) {
2105
1925
  if (summary.observed.uncomparedReplies || summary.replies < INSIGHT_REPLIES) return [];
2106
- const list = billingInsights(summary, split);
1926
+ const list = insights(summary);
2107
1927
  if (!list.length) return [];
2108
1928
  return [
2109
1929
  ui.text(' '),
@@ -2116,7 +1936,7 @@ function insightLines(ui, summary, actions, columns, split) {
2116
1936
  function insightLine(ui, insight, actions, columns) {
2117
1937
  const where = ({ activity, tier }) => [
2118
1938
  ...(ACTIVITIES.includes(activity) ? [ui.activity(activity), ui.dim(' · ')] : []),
2119
- TIERS.includes(tier) ? ui.tier(tier) : ui.dim('not routed'),
1939
+ TIERS.includes(tier) ? ui.bars(tier) : ui.dim('not routed'),
2120
1940
  ];
2121
1941
  const link = (insight) =>
2122
1942
  TIERS.includes(insight.tier)
@@ -2167,29 +1987,31 @@ function deleteLine(ui, view, actions) {
2167
1987
 
2168
1988
  // Answer first for the chosen period: routing against your model as a ledger that adds up, the tokens, the cost by
2169
1989
  // activity, model or tier, the trend or What if, and what is worth a look. Subagents follow, for the same period.
2170
- function usageTab(ui, config, view, _usage, actions, _modelOptions, columns, now) {
1990
+ function usageTab(ui, config, view, usage, actions, _modelOptions, columns, now) {
2171
1991
  const period = PERIODS.includes(view.usagePeriod) ? view.usagePeriod : 'session';
2172
1992
  const record = liveUsage(view, period === 'session' ? view.usageSession : view.usageStore);
2173
1993
  const summary = summarize(record, periodRange(period, now));
2174
1994
  // All adds the undated savings totals kept from before the usage records.
2175
1995
  const kept = period === 'all' ? allTime(record, view.savingsStore) : null;
2176
1996
  const legacy = kept?.legacy ?? null;
2177
- const r = readout(kept?.totals ?? summary);
2178
- const split = billingSplit(config, summary);
2179
- const answerSplit = kept ? keptSplit(config, kept) : split;
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
+ });
2180
2006
  const out = [periodRow(ui, period, actions), scopeLine(ui, config, view, period, summary, now), ui.text(' ')];
2181
- out.push(...headline(ui, config, view, period, r, summary, kept?.observed ?? summary.observed, answerSplit));
2182
- if (r.replies) {
2007
+ out.push(...costTable(ui, config, view, period, cost, legacy, actions, columns));
2008
+ if (summary.observed.replies) out.push(ui.text(' '), statsLine(ui, { ...summary.observed, turns: summary.turns }));
2009
+ if (summary.observed.replies) {
2183
2010
  out.push(
2184
2011
  ui.text(' '),
2185
- ...(answerSplit
2186
- ? billingLedger(ui, answerSplit, true)
2187
- : ledger(ui, config, view, { period, r, summary, legacy, columns })),
2012
+ ...breakdownLines(ui, view, actions, summary, columns, !cost.effortOnly, cost.billing),
2013
+ ui.text(' '),
2188
2014
  );
2189
- }
2190
- if (summary.observed.replies) out.push(ui.text(' '), statsLine(ui, { ...summary.observed, turns: summary.turns }));
2191
- if (summary.observed.replies) {
2192
- out.push(ui.text(' '), ...breakdownLines(ui, config, view, actions, summary, columns, split), ui.text(' '));
2193
2015
  out.push(
2194
2016
  ...(view.usageCompare
2195
2017
  ? [
@@ -2198,15 +2020,15 @@ function usageTab(ui, config, view, _usage, actions, _modelOptions, columns, now
2198
2020
  ui.dim(' · the same tokens on one model '),
2199
2021
  ui.Button({ key: 'usage-compare', label: 'Trend', hotkey: 'c', onPress: actions.usageCompare }),
2200
2022
  ),
2201
- ...compareLines(ui, config, summary, split),
2023
+ ...compareLines(ui, summary, cost.billing),
2202
2024
  ]
2203
- : trendLines(ui, view, actions, summary, period, now)),
2204
- ...insightLines(ui, summary, actions, columns, split),
2025
+ : trendLines(ui, view, actions, summary, period, now, cost.billing)),
2026
+ ...insightLines(ui, summary, actions, columns),
2205
2027
  );
2206
2028
  }
2207
2029
  out.push(
2208
2030
  ui.text(' '),
2209
- ...subagentUsage(ui, config, view, actions, period, now, columns),
2031
+ ...subagentUsage(ui, config, view, actions, period, now, columns, cost.billing),
2210
2032
  ui.text(' '),
2211
2033
  ...footer(ui, columns),
2212
2034
  );
@@ -2214,15 +2036,136 @@ function usageTab(ui, config, view, _usage, actions, _modelOptions, columns, now
2214
2036
  return out;
2215
2037
  }
2216
2038
 
2217
- 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');
2218
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),
2219
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 [
2220
2160
  ui.head('ABOUT THESE NUMBERS'),
2221
- ui.dim('Cost, context and cache are Claude readings. $ estimates use the'),
2222
- ui.dim('list prices in router.json; plan prices are equivalents, not cash.'),
2223
- ui.dim('Routing vs your model holds tokens and output length the same'),
2224
- ui.dim('and does not measure answer quality. Cache benefit is before writes.'),
2225
- ui.dim('The context bar uses the routed model’s window, 20% in reserve.'),
2226
- 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(' '),
2227
2170
  ];
2228
2171
  }