@alexeiled/claude-router 1.12.0 → 1.14.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
@@ -17,7 +17,6 @@ import { effortSharesCache, routeEffort } from './cost.mjs';
17
17
  import {
18
18
  activityReading,
19
19
  activityVerb,
20
- bar,
21
20
  classifierLabel,
22
21
  classifierStatus,
23
22
  differenceShare,
@@ -26,6 +25,7 @@ import {
26
25
  GATEWAY_SETTINGS,
27
26
  missingCredentials,
28
27
  missingText,
28
+ modelColor,
29
29
  modelName,
30
30
  percent,
31
31
  percentPair,
@@ -35,7 +35,6 @@ import {
35
35
  savingsColor,
36
36
  signedUsd,
37
37
  sparkline,
38
- switchCount,
39
38
  TIER_COLOR,
40
39
  unavailableReason,
41
40
  usageMetrics,
@@ -45,11 +44,19 @@ import {
45
44
  } from './display.mjs';
46
45
  import { cellForModel, isSameModel } from './route.mjs';
47
46
  import { modelSpec, readout } from './savings.mjs';
48
- import { PASS_REASONS, readSubagentStore } from './subagents.mjs';
47
+ import {
48
+ modelTotals,
49
+ PASS_LABEL,
50
+ PASS_REASONS,
51
+ PASS_WHY,
52
+ readSubagentStore,
53
+ summarizeSubagents,
54
+ } from './subagents.mjs';
49
55
  import {
50
56
  allTime,
51
57
  breakdown,
52
58
  cellsWhere,
59
+ dayKey,
53
60
  INSIGHT_REPLIES,
54
61
  insights,
55
62
  mostlyOn,
@@ -59,6 +66,7 @@ import {
59
66
  summarize,
60
67
  trend,
61
68
  } from './usage.mjs';
69
+ import { mergePairs, STRIP_CELLS } from './view.mjs';
62
70
 
63
71
  // Routes and Policy edit one draft and save together; Classifier saves each pick at once.
64
72
  const TABS = [
@@ -259,9 +267,9 @@ function supportText(label, estimate) {
259
267
  return `${label} gave ${direction} tiers ${Number.isFinite(mass) ? gave : '—'} (needs ${needs})${cost}`;
260
268
  }
261
269
 
262
- // What runs next turn and why first; then the classifier's support per tier with pins, the recent replies, and the
263
- // context and cost readings.
264
- function nowTab(ui, config, view, usage, actions) {
270
+ // What runs next turn and why first, with the one-turn pins; then this session and today as headlines, the finding
271
+ // worth a look, and Claude's context and cost readings.
272
+ function nowTab(ui, config, view, usage, actions, _modelOptions, columns, now) {
265
273
  const metrics = usageMetrics(config, view, usage);
266
274
  const unavailable = view.phase === 'unavailable';
267
275
  const auto = view.mode === 'auto' && !unavailable;
@@ -314,30 +322,17 @@ function nowTab(ui, config, view, usage, actions) {
314
322
  ui.Button({ key: 'key', label: 'Set up', hotkey: 'k', onPress: actions.key }),
315
323
  )
316
324
  : null,
317
- ui.text(' '),
318
- ui.line(
319
- ui.head('TIERS'),
320
- ui.dim(auto ? ` · ${label} support on the last turn · pin = next turn only` : ` · ${label} support`),
321
- ),
325
+ pinLine(ui, view, auto, unavailable, actions, columns),
322
326
  ];
323
- for (const tier of LADDER) {
324
- const support = view.probabilities?.[tier];
325
- const meter = Number.isFinite(support) ? bar(support, 1, 10) : null;
326
- out.push(
327
- ui.line(
328
- view.tier === tier ? ui.tier(tier, '▶ ') : ' ',
329
- ui.tier(tier, tier.padEnd(8)),
330
- routeName(config, config.routes[tier]).padEnd(22),
331
- meter ? ui.text(meter.text, { color: TIER_COLOR[tier] }) : ui.dim('—'.padEnd(10)),
332
- meter ? ` ${percent(support).padStart(4)} ` : ' ',
333
- auto ? ui.Button({ key: `pin-${tier}`, label: 'pin', onPress: () => actions.pin(tier) }) : null,
334
- ),
335
- );
336
- }
337
- if (!auto)
338
- out.push(ui.dim(unavailable ? ' Pins need routing, which is unavailable.' : ' Pins need routing on (o above).'));
339
- out.push(ui.text(' '), ...replies(ui, view));
327
+ const session = summarize(readUsage(view.usageSession), periodRange('session', now));
328
+ const today = summarize(readUsage(view.usageStore), periodRange('today', now));
329
+ out.push(ui.text(' '), ...sessionLines(ui, view, session, actions, columns, now));
330
+ // Today repeats this session's part of it until another session adds to it.
331
+ const ownToday = summarize(readUsage(view.usageSession), periodRange('today', now));
332
+ if (today.replies > ownToday.replies) out.push(ui.text(' '), ...todayLines(ui, today, actions, columns));
340
333
  out.push(
334
+ ...sessionAgentLines(ui, view, actions, columns),
335
+ ...worthLines(ui, today, actions, columns),
341
336
  ui.text(' '),
342
337
  ui.gauge('Context ', metrics.contextBar, contextSuffix(metrics)),
343
338
  ui.line(
@@ -384,7 +379,7 @@ function readingDetail(ui, view, metrics) {
384
379
  ui.dim(` cache read ${formatTokens(view.cacheRead)} · written ${formatTokens(view.cacheWrite)} tokens`),
385
380
  ui.dim(` output ${formatTokens(view.outputTokens)} tokens on the last reply`),
386
381
  ui.text(' '),
387
- ui.head('INPUT PER REPLY · lowest to highest'),
382
+ ui.head(`INPUT PER REPLY · last ${plural(history.length, 'reply', 'replies')} · lowest to highest`),
388
383
  trend,
389
384
  ui.text(' '),
390
385
  ui.head('ESTIMATES · configured list prices'),
@@ -406,47 +401,183 @@ function readingDetail(ui, view, metrics) {
406
401
 
407
402
  const verbShare = (text) => text.replace(/^(\S+)/, (name) => activityVerb(name));
408
403
 
409
- // The last replies, one cell each colored by the tier that served it, a dot where routing did not choose; the switch
410
- // count; the replies per tier, which is also the color key; and the replies per activity.
411
- function replies(ui, view) {
412
- const tiers = view.tiers ?? [];
413
- if (!tiers.length) return [ui.head('LAST REPLIES'), ui.dim(' no replies yet')];
414
- const switches = switchCount((view.routes ?? []).slice(-tiers.length));
415
- const count = (list, value) => list.filter((item) => item === value).length;
416
- const notRouted = count(tiers, null);
417
- // A view from before 1.6 has fewer activities: they align from the newest.
418
- const activities = (view.activities ?? []).slice(-tiers.length);
419
- const used = ACTIVITIES.map((activity) => [activity, count(activities, activity)])
420
- .filter(([, n]) => n > 0)
421
- .sort((a, b) => b[1] - a[1]);
404
+ // One button per tier with the classifier's support on the last turn, the current tier marked; a press pins the next
405
+ // turn only. Without routing there is nothing to pin.
406
+ function pinLine(ui, view, auto, unavailable, actions, columns) {
407
+ if (!auto)
408
+ return ui.line(
409
+ 'Pin next ',
410
+ ui.dim(unavailable ? 'needs routing, which is unavailable' : 'needs routing on (o above)'),
411
+ );
412
+ return ui.line(
413
+ 'Pin next ',
414
+ ...LADDER.flatMap((tier) => {
415
+ const support = view.probabilities?.[tier];
416
+ return [
417
+ ui.Button({
418
+ key: `pin-${tier}`,
419
+ label: `${view.tier === tier ? '▶ ' : ''}${tier} ${Number.isFinite(support) ? percent(support) : '—'}`,
420
+ variant: view.pendingPin === tier ? 'primary' : 'secondary',
421
+ onPress: () => actions.pin(tier),
422
+ }),
423
+ ' ',
424
+ ];
425
+ }),
426
+ !Number.isFinite(columns) || columns >= PIN_HINT_COLUMNS ? ui.dim(' next turn only') : null,
427
+ );
428
+ }
429
+ const PIN_HINT_COLUMNS = 80;
430
+
431
+ // "13:41", or "Oct 12 13:41" for another day than `now`'s.
432
+ const clockText = (ms) => new Date(ms).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' });
433
+ const sinceText = (ms, now) =>
434
+ dayKey(ms) === dayKey(now) ? clockText(ms) : `${dayLabel(dayKey(ms))} ${clockText(ms)}`;
435
+
436
+ // The strip cell's tier: the one with most replies, the stronger on a tie; `none` where routing served none.
437
+ const STRIP_ORDER = [...LADDER, 'none'];
438
+ const cellTier = (cell) => STRIP_ORDER.reduce((top, key) => ((cell[key] ?? 0) > (cell[top] ?? 0) ? key : top));
439
+
440
+ // The session strip fitted to the pane beside its note: pairs of cells merge until both fit. The note says how many
441
+ // replies a cell holds, and since when the strip runs when Claude Code restarted after the session's first reply.
442
+ function fittedStrip(strip, columns, since, now) {
443
+ let { per, cells } = strip;
444
+ const restarted = Number.isFinite(strip.from) && Number.isFinite(since) && strip.from > since;
445
+ const note = () =>
446
+ [per > 1 ? `${per} replies per cell` : null, restarted ? `since ${sinceText(strip.from, now)}` : null]
447
+ .filter(Boolean)
448
+ .join(' · ');
449
+ const room = () => (Number.isFinite(columns) ? Math.max(8, columns - 4 - note().length) : STRIP_CELLS);
450
+ while (cells.length > room()) {
451
+ cells = mergePairs(cells);
452
+ per *= 2;
453
+ }
454
+ return { cells, note: note() };
455
+ }
456
+
457
+ // This session: since its first routed reply, its routed replies and route switches; its replies as a strip colored
458
+ // by tier, with the replies per tier, and the routed replies per activity; the last switch; and routing against your
459
+ // model, linked to Usage.
460
+ function sessionLines(ui, view, summary, actions, columns, now) {
461
+ const since = readUsage(view.usageSession).since;
462
+ const strip = view.strip?.cells?.length ? fittedStrip(view.strip, columns, since, now) : null;
463
+ const counts = {};
464
+ for (const cell of view.strip?.cells ?? [])
465
+ for (const [key, n] of Object.entries(cell)) counts[key] = (counts[key] ?? 0) + n;
466
+ const replies = Object.values(counts).reduce((sum, n) => sum + n, 0);
467
+ const switches = summary.switches.tier + summary.switches.activity;
468
+ const head = [
469
+ Number.isFinite(since) ? `since ${sinceText(since, now)}` : null,
470
+ summary.replies
471
+ ? plural(summary.replies, 'routed reply', 'routed replies')
472
+ : replies
473
+ ? plural(replies, 'reply', 'replies')
474
+ : null,
475
+ summary.turns ? plural(switches, 'route switch', 'route switches') : null,
476
+ ].filter(Boolean);
477
+ if (!strip && !summary.replies) return [ui.line(ui.head('SESSION'), ui.dim(' · no replies yet'))];
478
+ const out = [ui.line(ui.head('SESSION'), head.length ? ui.dim(` · ${head.join(' · ')}`) : null)];
479
+ if (strip) {
480
+ out.push(
481
+ ui.line(
482
+ ' ',
483
+ ...strip.cells.map((cell) => {
484
+ const tier = cellTier(cell);
485
+ return tier === 'none' ? ui.dim('·') : ui.tier(tier, '█');
486
+ }),
487
+ strip.note ? ui.dim(` ${strip.note}`) : null,
488
+ ),
489
+ ui.line(
490
+ ' ',
491
+ ...TIERS.filter((tier) => counts[tier]).flatMap((tier) => [ui.tier(tier, '■ '), `${tier} ${counts[tier]} `]),
492
+ counts.none ? ui.dim(`· not routed ${counts.none}`) : null,
493
+ ),
494
+ );
495
+ }
496
+ const used = breakdown(summary.cells, 'activity')
497
+ .filter((group) => ACTIVITIES.includes(group.name))
498
+ .sort((a, b) => b.sums[0] - a.sums[0])
499
+ .map((group) => [group.name, `${activityVerb(group.name)} ${group.sums[0]}`]);
500
+ // The most used first, as many as fit the pane; the rest as a count.
501
+ const shown = [];
502
+ for (const [i, entry] of used.entries()) {
503
+ const rest = used.length - i - 1;
504
+ const width =
505
+ 2 + [...shown, entry].map(([, text]) => text).join(' · ').length + (rest ? ` · +${rest} more`.length : 0);
506
+ if (Number.isFinite(columns) && width > columns && shown.length) break;
507
+ shown.push(entry);
508
+ }
509
+ if (shown.length)
510
+ out.push(
511
+ ui.line(
512
+ ' ',
513
+ ...shown.flatMap(([name, text], i) => [
514
+ ui.activity(name),
515
+ ui.dim(`${text.slice(activityVerb(name).length)}${i < shown.length - 1 ? ' · ' : ''}`),
516
+ ]),
517
+ shown.length < used.length ? ui.dim(` · +${used.length - shown.length} more`) : null,
518
+ ),
519
+ );
520
+ const last = view.lastSwitch;
521
+ if (Number.isFinite(last?.at) && last.from && last.to) out.push(lastSwitchLine(ui, last, now));
522
+ if (summary.replies)
523
+ out.push(verdictLine(ui, readout(summary), () => actions.usageFor('session'), 'session', columns));
524
+ return out;
525
+ }
526
+
527
+ // "last switch 13:41 medium → high · debugging"; routes by name when the switch kept the tier.
528
+ function lastSwitchLine(ui, last, now) {
529
+ const byTier = TIERS.includes(last.from.tier) && TIERS.includes(last.to.tier) && last.from.tier !== last.to.tier;
530
+ return ui.line(
531
+ ' ',
532
+ ui.dim(`last switch ${sinceText(last.at, now)} `),
533
+ ...(byTier
534
+ ? [ui.tier(last.from.tier), ui.dim(' → '), ui.tier(last.to.tier)]
535
+ : [routeLabel(last.from.model, last.from.effort), ui.dim(' → '), routeLabel(last.to.model, last.to.effort)]),
536
+ ...(ACTIVITIES.includes(last.activity) ? [ui.dim(' · '), ui.activity(last.activity)] : []),
537
+ );
538
+ }
539
+
540
+ // Routing against your model, with the Usage tab on the same period one press away. The switch writes in it and an
541
+ // early sample follow where the pane has room, the early sample dropping first.
542
+ function verdictLine(ui, r, open, period, columns) {
543
+ const notes = [
544
+ r.switchUsd > 0 ? ` · switch writes ${usd(r.switchUsd)}` : null,
545
+ r.early ? ' · early sample' : null,
546
+ ].filter(Boolean);
547
+ const width = () => 2 + verdictText(r).join('').length + notes.join('').length + USAGE_LINK;
548
+ while (notes.length && Number.isFinite(columns) && width() > columns) notes.pop();
549
+ return ui.line(
550
+ ' ',
551
+ ...verdictParts(ui, r),
552
+ ...notes.map((note) => ui.dim(note)),
553
+ ' ',
554
+ ui.Button({ key: `usage-${period}`, label: 'Usage', onPress: open }),
555
+ );
556
+ }
557
+ // " [ Usage ]" after the verdict.
558
+ const USAGE_LINK = 11;
559
+
560
+ // Today across sessions, shown once another session added to it.
561
+ function todayLines(ui, summary, actions, columns) {
562
+ const switches = summary.switches.tier + summary.switches.activity;
422
563
  return [
423
564
  ui.line(
424
- ui.head(tiers.length === 1 ? 'LAST REPLY' : `LAST ${tiers.length} REPLIES`),
425
- ui.dim(` · ${plural(switches, 'model switch', 'model switches')}`),
426
- ),
427
- ui.line(' ', ...tiers.map((tier) => (tier ? ui.tier(tier, '█') : ui.dim('·')))),
428
- ui.line(
429
- ' ',
430
- ...TIERS.filter((tier) => tiers.includes(tier)).flatMap((tier) => [
431
- ui.tier(tier, '■ '),
432
- `${tier} ${count(tiers, tier)} `,
433
- ]),
434
- notRouted ? ui.dim(`· not routed ${notRouted}`) : null,
565
+ ui.head('TODAY'),
566
+ ui.dim(
567
+ ` · ${plural(summary.replies, 'routed reply', 'routed replies')} · ${plural(switches, 'route switch', 'route switches')}`,
568
+ ),
435
569
  ),
436
- ...(used.length
437
- ? [
438
- ui.line(
439
- ' ',
440
- ...used.flatMap(([activity, n], i) => [
441
- ui.activity(activity),
442
- ui.dim(` ${n}${i < used.length - 1 ? ' · ' : ''}`),
443
- ]),
444
- ),
445
- ]
446
- : []),
570
+ verdictLine(ui, readout(summary), () => actions.usageFor('today'), 'today', columns),
447
571
  ];
448
572
  }
449
573
 
574
+ // Today's first finding from Usage's WORTH A LOOK, with the tab that changes it; nothing when there is none.
575
+ function worthLines(ui, summary, actions, columns) {
576
+ const [first] = summary.replies >= INSIGHT_REPLIES ? insights(summary) : [];
577
+ if (!first) return [];
578
+ return [ui.text(' '), ui.line(ui.head('WORTH A LOOK'), ui.dim(' · today')), insightLine(ui, first, actions, columns)];
579
+ }
580
+
450
581
  // Rows: [key, label, format, router.json field]. Typed as tuples so tsc keeps each position's type.
451
582
  /** @type {[string, string, (value: number) => string, string][]} */
452
583
  const POLICY_ROWS = [
@@ -1111,45 +1242,298 @@ function yourTier(config, view) {
1111
1242
  const pricedText = (text, counts) =>
1112
1243
  counts.pricedRequests < counts.requests ? `${text} (${counts.requests - counts.pricedRequests} unpriced)` : text;
1113
1244
 
1114
- // Subagent routing across sessions since the last reset. Per routed type: agents, how many the decision moved off
1115
- // core's model, requests per agent and respawns (the retry proxies), and core's cost against the routed one at list
1116
- // prices, with core's model estimated. Then the spawns that passed through, by reason, priced on the model they ran on.
1117
- function subagentUsage(ui, config, view, columns) {
1245
+ // "Oct 7 – Oct 13" for a period's span, or "since Oct 10", its `first` day, for one without a range; null without one.
1246
+ function spanText(period, now, first) {
1247
+ const { from, to } = periodRange(period, now);
1248
+ if (period === 'today') return `today, ${dayLabel(to)}`;
1249
+ if (from) return `${dayLabel(from)} – ${dayLabel(to)}`;
1250
+ return first ? `since ${dayLabel(first)}` : null;
1251
+ }
1252
+
1253
+ // The subagent rows: the open mark, the type, its squares, agents, cost, and against Claude Code's pick with its arrow.
1254
+ const AGENT_TYPE = 19;
1255
+ const AGENT_SQUARES = 12;
1256
+ const AGENT_ROW = 4 + AGENT_TYPE + AGENT_SQUARES + 3 + 9 + 11;
1257
+ // The summary strip's squares at most: past this each model gets its share of them, not one per agent.
1258
+ const AGENT_STRIP = 25;
1259
+ // The models in the order their squares go, by family; any other after them by name.
1260
+ const FAMILIES = ['haiku', 'sonnet', 'opus', 'fable'];
1261
+ const clipped = (text, width) => (text.length < width ? text : `${text.slice(0, width - 2)}…`);
1262
+ const familyRank = (id) => {
1263
+ const rank = FAMILIES.findIndex((family) => id.includes(family));
1264
+ return rank < 0 ? FAMILIES.length : rank;
1265
+ };
1266
+ const byFamily = (a, b) => familyRank(a[0]) - familyRank(b[0]) || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);
1267
+ const colored = (ui, id, text) => {
1268
+ const color = modelColor(id);
1269
+ return ui.text(text, color ? { color } : {});
1270
+ };
1271
+
1272
+ // Each model's agents in a period and how many the router moved, across the routed types and the pass-throughs.
1273
+ function agentsByModel(s) {
1274
+ const models = new Map();
1275
+ for (const kind of ['routed', 'passed'])
1276
+ for (const counts of Object.values(s[kind]))
1277
+ for (const [id, m] of Object.entries(counts.models)) {
1278
+ const sum = models.get(id) ?? { agents: 0, moved: 0 };
1279
+ models.set(id, { agents: sum.agents + m.agents, moved: sum.moved + (m.moved ?? 0) });
1280
+ }
1281
+ return [...models].filter(([, m]) => m.agents > 0).sort(byFamily);
1282
+ }
1283
+
1284
+ // Squares for `models` ([id, { agents, moved }]), colored by model, filled for the agents the router moved. `scale`:
1285
+ // one per agent up to `max`, then each model's share of `max`, at least one. Else one per agent up to `max`, and
1286
+ // `rest` counts the agents past them.
1287
+ function squares(ui, models, max, scale) {
1288
+ const total = models.reduce((n, [, m]) => n + m.agents, 0);
1289
+ const shown = (n) => (!scale || total <= max || !n ? n : Math.max(1, Math.round((n / total) * max)));
1290
+ const parts = [];
1291
+ let left = max;
1292
+ for (const [id, m] of models) {
1293
+ const n = Math.min(shown(m.agents), left);
1294
+ const filled = Math.min(n, shown(m.moved));
1295
+ if (filled) parts.push(colored(ui, id, '■'.repeat(filled)));
1296
+ if (n > filled) parts.push(colored(ui, id, '□'.repeat(n - filled)));
1297
+ left -= n;
1298
+ }
1299
+ return { parts, width: max - left, rest: scale ? 0 : total - (max - left) };
1300
+ }
1301
+
1302
+ // "Routing saved $0.21 (5%) on 7 routed agents": the routed agents' cost against Claude Code's picks.
1303
+ function agentVerdict(ui, routed) {
1304
+ const agents = routed.reduce((n, [, c]) => n + c.agents, 0);
1305
+ const totals = routed.map(([, c]) => modelTotals(c));
1306
+ const cost = totals.reduce((n, t) => n + t.usd, 0);
1307
+ const core = totals.reduce((n, t) => n + t.coreUsd, 0);
1308
+ const counts = {
1309
+ requests: routed.reduce((n, [, c]) => n + c.requests, 0),
1310
+ pricedRequests: routed.reduce((n, [, c]) => n + c.pricedRequests, 0),
1311
+ };
1312
+ if (!counts.pricedRequests) return ui.dim(` ${plural(agents, 'routed agent')}, not priced`);
1313
+ const difference = cents(cost - core);
1314
+ const on = pricedText(` on ${plural(agents, 'routed agent')}`, counts);
1315
+ if (!difference) return ui.line(' Routing cost the same as Claude Code’s picks', ui.dim(on));
1316
+ return ui.line(
1317
+ ` Routing ${difference < 0 ? 'saved' : 'cost'} `,
1318
+ ui.text(usd(difference), { color: savingsColor(difference) }),
1319
+ difference < 0 ? '' : ' more',
1320
+ core > 0 ? ` (${percent(Math.abs(difference) / core)})` : '',
1321
+ ui.dim(on),
1322
+ );
1323
+ }
1324
+
1325
+ // The strip of every agent by model, what the router moved, and how routing paid off.
1326
+ function agentSummary(ui, s, columns) {
1327
+ const models = agentsByModel(s);
1328
+ const total = models.reduce((n, [, m]) => n + m.agents, 0);
1329
+ const moved = models.reduce((n, [, m]) => n + m.moved, 0);
1330
+ const strip = squares(ui, models, AGENT_STRIP, true);
1331
+ const labels = models.map(([id, m]) => [id, `${modelName(id)} ${m.agents}`]);
1332
+ const names = labels.flatMap(([id, text], i) => [i ? ui.dim(' · ') : null, colored(ui, id, text)]);
1333
+ const namesWidth = labels.reduce((n, [, text], i) => n + (i ? 3 : 0) + text.length, 0);
1334
+ const out =
1335
+ Number.isFinite(columns) && 2 + strip.width + 2 + namesWidth > columns
1336
+ ? [ui.line(' ', ...strip.parts), ui.line(' ', ...names)]
1337
+ : [ui.line(' ', ...strip.parts, ' ', ...names)];
1338
+ out.push(
1339
+ ui.line(
1340
+ ` ${plural(total, 'agent')}`,
1341
+ ui.dim(' · '),
1342
+ `■ ${moved} moved by the router`,
1343
+ ui.dim(' · '),
1344
+ `□ ${total - moved} on Claude Code’s pick`,
1345
+ ),
1346
+ );
1347
+ const routed = Object.entries(s.routed).filter(([, c]) => c.agents > 0);
1348
+ if (routed.length) out.push(agentVerdict(ui, routed));
1349
+ return out;
1350
+ }
1351
+
1352
+ // Agents per day from the period's first day, or the first recorded one, to today, with the busiest day.
1353
+ function agentTrend(ui, s, period, now) {
1354
+ if (period === 'session' || period === 'today' || !s.perDay.length) return [];
1355
+ const counts = new Map(s.perDay);
1356
+ const start = periodRange(period, now).from ?? s.perDay[0][0];
1357
+ const [y, m, d] = start.split('-').map(Number);
1358
+ const days = [];
1359
+ for (let i = 0; ; i += 1) {
1360
+ const key = dayKey(new Date(y, m - 1, d + i).getTime());
1361
+ if (key > dayKey(now)) break;
1362
+ days.push([key, counts.get(key) ?? 0]);
1363
+ }
1364
+ if (days.length < 2) return [];
1365
+ const [peakDay, peak] = days.reduce((top, day) => (day[1] > top[1] ? day : top));
1366
+ // A long All period keeps its last days, as many as the row has room for.
1367
+ const values = days.map(([, n]) => n).slice(-(AGENT_ROW - 30));
1368
+ return [
1369
+ ui.line(' per day ', ui.text(sparkline(values), { bold: true }), ui.dim(` peak ${peak} on ${dayLabel(peakDay)}`)),
1370
+ ];
1371
+ }
1372
+
1373
+ // "+$0.44 ▲" against Claude Code's pick, in the savings colors; a dim dash when it rounds to nothing.
1374
+ const pickDifference = (ui, value) =>
1375
+ value
1376
+ ? ui.text(`${signedUsd(value)} ${value > 0 ? '▲' : '▼'}`.padStart(11), { color: savingsColor(value) })
1377
+ : ui.dim('—'.padStart(9));
1378
+
1379
+ // What a routed model row holds: "2 moved up", or "1 kept, 2 down".
1380
+ function moveText(m) {
1381
+ const kept = m.agents - m.moved;
1382
+ const other = m.moved - m.up - m.down;
1383
+ const parts = [
1384
+ kept ? `${kept} kept` : null,
1385
+ m.up ? `${m.up} up` : null,
1386
+ m.down ? `${m.down} down` : null,
1387
+ other ? `${other} moved` : null,
1388
+ ].filter(Boolean);
1389
+ if (parts.length > 1 || kept) return parts.join(', ');
1390
+ return `${m.moved} moved${m.up ? ' up' : m.down ? ' down' : ''}`;
1391
+ }
1392
+
1393
+ // One row of the subagent table; open, the models it ran on with their cost, and its requests and retry proxies.
1394
+ function agentRow(ui, view, actions, { id, name, counts, routed, why, narrow, columns }) {
1395
+ const open = view.usageOpen === id;
1396
+ const models = Object.entries(counts.models)
1397
+ .filter(([, m]) => m.agents > 0)
1398
+ .sort(byFamily);
1399
+ const marks = squares(
1400
+ ui,
1401
+ models.map(([model, m]) => [model, { agents: m.agents, moved: m.moved ?? 0 }]),
1402
+ AGENT_SQUARES - 3,
1403
+ false,
1404
+ );
1405
+ const t = modelTotals(counts);
1406
+ // A row none of whose requests had a price says so rather than $0.00.
1407
+ const priced = counts.pricedRequests > 0;
1408
+ const costCell = (value) => (priced ? usd(value).padStart(9) : ui.dim('no price'.padStart(9)));
1409
+ const out = [
1410
+ ui.line(
1411
+ ' ',
1412
+ ui.Button({
1413
+ key: `row-${id}`,
1414
+ label: open ? '▾' : '▸',
1415
+ plain: true,
1416
+ onPress: () => actions.usageOpen(open ? null : id),
1417
+ }),
1418
+ ' ',
1419
+ ui.cell(AGENT_TYPE, clipped(name, AGENT_TYPE)),
1420
+ ui.cell(AGENT_SQUARES, ui.line(...marks.parts, marks.rest ? ui.dim(`+${marks.rest}`) : null)),
1421
+ String(counts.agents).padStart(3),
1422
+ narrow ? null : costCell(t.usd),
1423
+ routed && priced ? pickDifference(ui, cents(t.usd - t.coreUsd)) : null,
1424
+ !routed && why && !narrow ? ui.dim(` ${why}`) : null,
1425
+ ),
1426
+ ];
1427
+ if (!open) return out;
1428
+ for (const [model, m] of models)
1429
+ out.push(
1430
+ ui.line(
1431
+ ' ',
1432
+ ui.cell(17, colored(ui, model, `${m.moved ? '■' : '□'} ${modelName(model)}`)),
1433
+ ui.cell(15, ui.dim(routed ? moveText(m) : plural(m.agents, 'agent'))),
1434
+ narrow ? null : costCell(m.usd),
1435
+ routed && priced ? pickDifference(ui, cents(m.usd - m.coreUsd)) : null,
1436
+ ),
1437
+ );
1438
+ const notes = [
1439
+ `${(counts.requests / counts.agents).toFixed(1)} requests per agent`,
1440
+ routed ? `${counts.respawns || 'none'} respawned within 10 min` : null,
1441
+ counts.failures ? plural(counts.failures, 'classifier failure') : null,
1442
+ counts.pricedRequests < counts.requests ? `${counts.requests - counts.pricedRequests} requests not priced` : null,
1443
+ ].filter(Boolean);
1444
+ out.push(...dimLines(ui, ` ${notes.join(' · ')}`, columns));
1445
+ return out;
1446
+ }
1447
+
1448
+ // Subagents in the chosen period: this session's record, or every session's in every project (one $.store per
1449
+ // plugin install). A strip of every agent by the model it ran on, filled where the router moved it off Claude Code's
1450
+ // pick, and the routed agents' cost against those picks. Then the routed types and the pass-throughs, each with its
1451
+ // squares, agents and cost, opening to its models; a pass-through says why Claude Code picked.
1452
+ function subagentUsage(ui, config, view, actions, period, now, columns) {
1118
1453
  const mode = config.subagentRouting;
1119
- const store = readSubagentStore(view.subagentStore);
1120
- const out = [ui.line(ui.head('SUBAGENTS · across sessions'), ui.dim(` subagent routing ${mode}`))];
1121
- const rows = Object.entries(store.routed.on).filter(([, counts]) => counts.agents > 0);
1122
- const passed = PASS_REASONS.filter((reason) => store.passed[reason]?.agents > 0);
1123
- if (!rows.length && !passed.length)
1454
+ const record = readSubagentStore(period === 'session' ? view.subagentSession : view.subagentStore);
1455
+ const s = summarizeSubagents(record, periodRange(period, now));
1456
+ const first = Number.isFinite(record.since) ? dayKey(record.since) : null;
1457
+ const scope =
1458
+ period === 'session' ? 'this session' : `all projects · ${spanText(period, now, first) ?? 'nothing yet'}`;
1459
+ const out = [ui.line(ui.head('SUBAGENTS'), ui.dim(` · ${scope} subagent routing ${mode}`))];
1460
+ const routed = Object.entries(s.routed)
1461
+ .filter(([, c]) => c.agents > 0)
1462
+ .sort((a, b) => b[1].agents - a[1].agents || (a[0] < b[0] ? -1 : 1));
1463
+ const passed = PASS_REASONS.filter((reason) => s.passed[reason]?.agents > 0).sort(
1464
+ (a, b) => s.passed[b].agents - s.passed[a].agents,
1465
+ );
1466
+ const undated = s.undated
1467
+ ? [
1468
+ ui.dim(
1469
+ ` + ${plural(s.undated.agents, 'agent')} from before 1.14.0, not split by model · ${usd(s.undated.usd)}`,
1470
+ ),
1471
+ ]
1472
+ : [];
1473
+ if (!routed.length && !passed.length) {
1474
+ const older = !s.undated && periodRange(period, now).from !== null && readSubagentStore(view.subagentStore).undated;
1124
1475
  return [
1125
1476
  ...out,
1126
- ui.dim(mode === 'off' ? ' Not recorded. Set subagentRouting to on in router.json.' : ' no subagents yet'),
1477
+ ui.dim(
1478
+ mode === 'off'
1479
+ ? ' Not recorded: subagentRouting is off in router.json.'
1480
+ : ` No subagents ${PERIOD_PHRASE[period]}.`,
1481
+ ),
1482
+ ...undated,
1483
+ ...(older ? [ui.dim(' Agents from before 1.14.0 have no date: All shows them.')] : []),
1127
1484
  ];
1128
- if (rows.length) {
1129
- out.push(ui.dim(' core’s model (est.) → routed'));
1130
- for (const [type, c] of rows.sort((a, b) => b[1].agents - a[1].agents)) {
1131
- const cost = pricedText(`${usd(c.coreUsd)} → ${usd(c.routedUsd)}`, c);
1132
- out.push(
1133
- ui.text(
1134
- ` ${type} ${c.agents} agent${c.agents === 1 ? '' : 's'} · ${c.differs} moved · ${(c.requests / c.agents).toFixed(1)} req/agent · ${c.respawns} respawns · ${cost}`,
1135
- ),
1136
- );
1137
- const choices = Object.entries(c.choices).map(([choice, n]) => `${choice} ${n}`);
1138
- if (c.failures) choices.push(`${c.failures} classifier failures`);
1139
- out.push(...dimLines(ui, ` ${choices.join(' · ')}`, columns));
1140
- }
1141
1485
  }
1142
- if (passed.length) {
1143
- const sum = (field) => passed.reduce((total, reason) => total + store.passed[reason][field], 0);
1144
- const total = { requests: sum('requests'), pricedRequests: sum('pricedRequests') };
1486
+ const narrow = Number.isFinite(columns) && columns < AGENT_ROW;
1487
+ out.push(...agentSummary(ui, s, columns), ...agentTrend(ui, s, period, now), ...undated);
1488
+ const rowOf = (fields) => agentRow(ui, view, actions, { narrow, columns, ...fields });
1489
+ if (routed.length) {
1145
1490
  out.push(
1146
- ui.text(` Not routed ${passed.map((reason) => `${reason} ${store.passed[reason].agents}`).join(' · ')}`),
1147
- ui.dim(` ${pricedText(`${usd(sum('usd'))} on the model they ran on`, total)}`),
1491
+ ui.text(' '),
1492
+ ui.line(ui.text(' ROUTED', { bold: true }), ui.dim(' · the router picked the model at spawn')),
1493
+ ui.dim(
1494
+ ` ${'type'.padEnd(AGENT_TYPE)}${'agents'.padEnd(AGENT_SQUARES + 3)}${narrow ? '' : 'cost'.padStart(9)}${'vs CC'.padStart(9)}`,
1495
+ ),
1148
1496
  );
1497
+ for (const [type, counts] of routed)
1498
+ out.push(...rowOf({ id: `subagent:${type}`, name: type, counts, routed: true }));
1149
1499
  }
1500
+ if (passed.length) {
1501
+ out.push(ui.text(' '), ui.line(ui.text(' NOT ROUTED', { bold: true }), ui.dim(' · Claude Code picked the model')));
1502
+ for (const reason of passed)
1503
+ out.push(
1504
+ ...rowOf({
1505
+ id: `subagent-pass:${reason}`,
1506
+ name: PASS_LABEL[reason],
1507
+ counts: s.passed[reason],
1508
+ routed: false,
1509
+ why: PASS_WHY[reason],
1510
+ }),
1511
+ );
1512
+ }
1513
+ out.push(
1514
+ ui.text(' '),
1515
+ ...dimLines(ui, ' ■ moved by the router · □ Claude Code’s pick · color: the model', columns),
1516
+ ...(routed.length ? dimLines(ui, ' vs CC: the same tokens on Claude Code’s pick, at list prices', columns) : []),
1517
+ );
1150
1518
  return out;
1151
1519
  }
1152
1520
 
1521
+ // This session's subagents on the Now tab: how many run now, the strip, and how routing paid off. Nothing without any.
1522
+ function sessionAgentLines(ui, view, actions, columns) {
1523
+ const s = summarizeSubagents(readSubagentStore(view.subagentSession), { from: null, to: null });
1524
+ const running = view.subagentsRunning ?? 0;
1525
+ const any = [...Object.values(s.routed), ...Object.values(s.passed)].some((c) => c.agents > 0);
1526
+ if (!any && !running) return [];
1527
+ const head = ui.line(
1528
+ ui.head('SUBAGENTS'),
1529
+ ui.dim(' · this session'),
1530
+ running ? ui.text(` · ● ${running} running`, { color: 'yellow' }) : null,
1531
+ ' ',
1532
+ ui.Button({ key: 'usage-agents', label: 'Usage', onPress: () => actions.usageFor('session') }),
1533
+ );
1534
+ return [ui.text(' '), head, ...(any ? agentSummary(ui, s, columns) : [])];
1535
+ }
1536
+
1153
1537
  const PERIOD_LABEL = { session: 'Session', today: 'Today', '7d': '7d', '30d': '30d', month: 'Month', all: 'All' };
1154
1538
  // "No routed replies …" for each period.
1155
1539
  const PERIOD_PHRASE = {
@@ -1237,17 +1621,8 @@ function scopeLine(ui, config, view, period, summary, now) {
1237
1621
  tier ? ui.tier(tier, yourModel(view)) : ui.text(yourModel(view)),
1238
1622
  );
1239
1623
  }
1240
- const { from, to } = periodRange(period, now);
1241
- const first = summary.days[0]?.[0];
1242
- const span =
1243
- period === 'today'
1244
- ? `today, ${dayLabel(to)}`
1245
- : from
1246
- ? `${dayLabel(from)} – ${dayLabel(to)}`
1247
- : first
1248
- ? `since ${dayLabel(first)}`
1249
- : 'no dated replies yet';
1250
- return ui.dim(`all sessions · ${span} · each session vs its own model`);
1624
+ const span = spanText(period, now, summary.days[0]?.[0]) ?? 'no dated replies yet';
1625
+ return ui.dim(`all projects · ${span} · each session vs its own model`);
1251
1626
  }
1252
1627
 
1253
1628
  // The models a session's replies were priced against, when they are not the one `/model` selects now: after a
@@ -1273,19 +1648,29 @@ function headline(ui, config, view, period, r) {
1273
1648
  ),
1274
1649
  ];
1275
1650
  }
1276
- const share = differenceShare(r)?.replace(/^[−+]/, '');
1277
- const amount = `${usd(r.differenceUsd)}${share ? ` (${share})` : ''}`;
1278
- const color = savingsColor(r.differenceUsd);
1279
1651
  return [
1280
1652
  ui.line(
1281
- r.differenceUsd < 0 ? 'Routing saved ' : r.differenceUsd > 0 ? 'Routing cost ' : 'Routing cost the same as',
1282
- r.differenceUsd === 0 ? '' : ui.text(amount, { bold: true, color }),
1283
- r.differenceUsd < 0 ? ' vs your model' : r.differenceUsd > 0 ? ' more than your model' : ' your model',
1653
+ ...verdictParts(ui, r),
1284
1654
  r.early ? ui.text(` early sample · ${plural(r.replies, 'reply', 'replies')}`, { color: 'yellow' }) : null,
1285
1655
  ),
1286
1656
  ];
1287
1657
  }
1288
1658
 
1659
+ // "Routing saved $1.84 (22%) vs your model", or what it cost more: the text before the amount, the amount, the rest.
1660
+ function verdictText(r) {
1661
+ const share = differenceShare(r)?.replace(/^[−+]/, '');
1662
+ return [
1663
+ r.differenceUsd < 0 ? 'Routing saved ' : r.differenceUsd > 0 ? 'Routing cost ' : 'Routing cost the same as',
1664
+ r.differenceUsd === 0 ? '' : `${usd(r.differenceUsd)}${share ? ` (${share})` : ''}`,
1665
+ r.differenceUsd < 0 ? ' vs your model' : r.differenceUsd > 0 ? ' more than your model' : ' your model',
1666
+ ];
1667
+ }
1668
+ // The verdict as line parts, the amount bold in the savings color.
1669
+ function verdictParts(ui, r) {
1670
+ const [before, amount, after] = verdictText(r);
1671
+ return [before, amount ? ui.text(amount, { bold: true, color: savingsColor(r.differenceUsd) }) : '', after];
1672
+ }
1673
+
1289
1674
  // Your model − cheaper models + stronger models + switch cache writes = routed, in whole cents that add up (readout).
1290
1675
  function ledger(ui, config, view, { period, r, summary, legacy, columns }) {
1291
1676
  const tier = yourTier(config, view);
@@ -1508,6 +1893,15 @@ function insightLines(ui, summary, actions, columns) {
1508
1893
  if (summary.replies < INSIGHT_REPLIES) return [];
1509
1894
  const list = insights(summary);
1510
1895
  if (!list.length) return [];
1896
+ return [
1897
+ ui.text(' '),
1898
+ ui.line(ui.head('WORTH A LOOK'), ui.dim(' · from the numbers; answer quality is not measured')),
1899
+ ...list.map((insight) => insightLine(ui, insight, actions, columns)),
1900
+ ];
1901
+ }
1902
+
1903
+ // One finding with the tab that changes it.
1904
+ function insightLine(ui, insight, actions, columns) {
1511
1905
  const where = ({ activity, tier }) => [
1512
1906
  ...(ACTIVITIES.includes(activity) ? [ui.activity(activity), ui.dim(' · ')] : []),
1513
1907
  TIERS.includes(tier) ? ui.tier(tier) : ui.dim('not routed'),
@@ -1523,30 +1917,23 @@ function insightLines(ui, summary, actions, columns) {
1523
1917
  ),
1524
1918
  })
1525
1919
  : null;
1526
- const lines = list.map((insight) =>
1527
- insight.kind === 'switch'
1528
- ? ui.line(
1529
- ` Switch cache writes used ${percent(insight.share)} of the cheaper-model saving `,
1530
- ui.Button({ key: 'insight-switch', label: 'Policy', onPress: () => actions.tab('policy') }),
1531
- )
1532
- : ui.line(
1533
- ' ',
1534
- ...where(insight),
1535
- insight.kind === 'cost'
1536
- ? ` carried ${percent(insight.share)} of the cost`
1537
- : ` ran ${usd(insight.usd)} above your model`,
1538
- insight.route && (!Number.isFinite(columns) || columns >= 90)
1539
- ? ui.dim(` · mostly ${routeText(insight.route)}`)
1540
- : null,
1541
- ' ',
1542
- link(insight),
1543
- ),
1544
- );
1545
- return [
1546
- ui.text(' '),
1547
- ui.line(ui.head('WORTH A LOOK'), ui.dim(' · from the numbers; answer quality is not measured')),
1548
- ...lines,
1549
- ];
1920
+ return insight.kind === 'switch'
1921
+ ? ui.line(
1922
+ ` Switch cache writes used ${percent(insight.share)} of the cheaper-model saving `,
1923
+ ui.Button({ key: 'insight-switch', label: 'Policy', onPress: () => actions.tab('policy') }),
1924
+ )
1925
+ : ui.line(
1926
+ ' ',
1927
+ ...where(insight),
1928
+ insight.kind === 'cost'
1929
+ ? ` carried ${percent(insight.share)} of the cost`
1930
+ : ` ran ${usd(insight.usd)} above your model`,
1931
+ insight.route && (!Number.isFinite(columns) || columns >= 90)
1932
+ ? ui.dim(` · mostly ${routeText(insight.route)}`)
1933
+ : null,
1934
+ ' ',
1935
+ link(insight),
1936
+ );
1550
1937
  }
1551
1938
 
1552
1939
  // Delete history waits for a second press, as nothing brings the records back.
@@ -1567,7 +1954,7 @@ function deleteLine(ui, view, actions) {
1567
1954
  }
1568
1955
 
1569
1956
  // Answer first for the chosen period: routing against your model as a ledger that adds up, the tokens, the cost by
1570
- // activity, model or tier, the trend or What if, and what is worth a look. Subagents follow, across sessions.
1957
+ // activity, model or tier, the trend or What if, and what is worth a look. Subagents follow, for the same period.
1571
1958
  function usageTab(ui, config, view, _usage, actions, _modelOptions, columns, now) {
1572
1959
  const period = PERIODS.includes(view.usagePeriod) ? view.usagePeriod : 'session';
1573
1960
  const record = readUsage(period === 'session' ? view.usageSession : view.usageStore);
@@ -1598,7 +1985,12 @@ function usageTab(ui, config, view, _usage, actions, _modelOptions, columns, now
1598
1985
  ...insightLines(ui, summary, actions, columns),
1599
1986
  );
1600
1987
  }
1601
- out.push(ui.text(' '), ...subagentUsage(ui, config, view, columns), ui.text(' '), ...footer(ui, columns));
1988
+ out.push(
1989
+ ui.text(' '),
1990
+ ...subagentUsage(ui, config, view, actions, period, now, columns),
1991
+ ui.text(' '),
1992
+ ...footer(ui, columns),
1993
+ );
1602
1994
  out.push(ui.text(' '), deleteLine(ui, view, actions));
1603
1995
  return out;
1604
1996
  }