@alexeiled/claude-router 1.20.1 → 1.21.1

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