@alexeiled/claude-router 1.24.0 → 1.25.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.
Files changed (78) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +44 -0
  3. package/README.md +39 -7
  4. package/docs/architecture.md +27 -4
  5. package/docs/configuration.md +23 -14
  6. package/docs/evaluation.md +3 -3
  7. package/docs/native-router.md +11 -3
  8. package/docs/router-band.svg +124 -133
  9. package/docs/router-pane-classifier.svg +24 -23
  10. package/docs/router-pane-now.svg +9 -7
  11. package/docs/router-pane-policy.svg +4 -4
  12. package/docs/router-pane-routes.svg +8 -8
  13. package/docs/router-pane-usage-whatif.svg +14 -14
  14. package/docs/router-pane-usage.svg +20 -20
  15. package/docs/routing-modes.md +10 -8
  16. package/docs/user-guide.md +70 -17
  17. package/hooks/native-router.mjs +333 -80
  18. package/lib/activity-stats.mjs +23 -4
  19. package/lib/activity.mjs +7 -5
  20. package/lib/auto-engine.mjs +13 -6
  21. package/lib/auto-route.mjs +10 -4
  22. package/lib/band.mjs +35 -440
  23. package/lib/classifier-client.mjs +12 -8
  24. package/lib/config-file.mjs +7 -2
  25. package/lib/config.mjs +24 -9
  26. package/lib/cost.mjs +5 -1
  27. package/lib/costs.mjs +4 -2
  28. package/lib/decisions.mjs +13 -9
  29. package/lib/display.mjs +69 -20
  30. package/lib/facts.mjs +3 -0
  31. package/lib/modes.mjs +8 -4
  32. package/lib/panel.mjs +75 -2167
  33. package/lib/policy.mjs +7 -6
  34. package/lib/replay-trace.mjs +5 -2
  35. package/lib/replay.mjs +7 -1
  36. package/lib/route-line.mjs +46 -0
  37. package/lib/route.mjs +21 -16
  38. package/lib/savings.mjs +14 -3
  39. package/lib/subagents.mjs +41 -11
  40. package/lib/subcommands.mjs +60 -0
  41. package/lib/ui/fallback.mjs +22 -0
  42. package/lib/ui/graphical/band.mjs +256 -0
  43. package/lib/ui/graphical/charts.mjs +163 -0
  44. package/lib/ui/graphical/classifier.mjs +153 -0
  45. package/lib/ui/graphical/frame.mjs +227 -0
  46. package/lib/ui/graphical/kit.mjs +156 -0
  47. package/lib/ui/graphical/meter.mjs +25 -0
  48. package/lib/ui/graphical/now.mjs +353 -0
  49. package/lib/ui/graphical/policy.mjs +56 -0
  50. package/lib/ui/graphical/routes.mjs +264 -0
  51. package/lib/ui/graphical/squares.mjs +29 -0
  52. package/lib/ui/graphical/usage.mjs +376 -0
  53. package/lib/ui/model/band.mjs +439 -0
  54. package/lib/ui/model/classifier.mjs +308 -0
  55. package/lib/ui/model/draft.mjs +62 -0
  56. package/lib/ui/model/format.mjs +41 -0
  57. package/lib/ui/model/frame.mjs +359 -0
  58. package/lib/ui/model/now.mjs +390 -0
  59. package/lib/ui/model/policy.mjs +194 -0
  60. package/lib/ui/model/routes.mjs +392 -0
  61. package/lib/ui/model/usage-agents.mjs +311 -0
  62. package/lib/ui/model/usage-breakdown.mjs +237 -0
  63. package/lib/ui/model/usage-shared.mjs +58 -0
  64. package/lib/ui/model/usage.mjs +330 -0
  65. package/lib/ui/terminal/band.mjs +220 -0
  66. package/lib/ui/terminal/classifier.mjs +142 -0
  67. package/lib/ui/terminal/frame.mjs +169 -0
  68. package/lib/ui/terminal/kit.mjs +133 -0
  69. package/lib/ui/terminal/now.mjs +300 -0
  70. package/lib/ui/terminal/policy.mjs +52 -0
  71. package/lib/ui/terminal/routes.mjs +167 -0
  72. package/lib/ui/terminal/usage.mjs +363 -0
  73. package/lib/ui/terminal/wrap.mjs +37 -0
  74. package/lib/ui/tokens.mjs +106 -0
  75. package/lib/usage.mjs +5 -5
  76. package/lib/view.mjs +5 -2
  77. package/package.json +3 -2
  78. package/types/index.d.ts +15 -0
@@ -0,0 +1,330 @@
1
+ // The Usage tab's model: every reading, word and tone the terminal rows and the graphical cards draw, decided once.
2
+ // `usageOf` is the tab's one entry; `lib/ui/terminal/usage.mjs` and `lib/ui/graphical/usage.mjs` lay it out. Where the
3
+ // terminal and a card need different words, both sit side by side (`text` and `graphical`, or `{ terminal, graphical }`).
4
+ import { resolveRoute, TIERS } from '../../config.mjs';
5
+ import { routeEffort } from '../../cost.mjs';
6
+ import { periodCost } from '../../costs.mjs';
7
+ import {
8
+ API_ESTIMATE,
9
+ costText,
10
+ diffText,
11
+ EARLY_NOTE,
12
+ formatTokens,
13
+ liveUsage,
14
+ modelName,
15
+ percent,
16
+ recordedModels,
17
+ repliesText,
18
+ switchesLost,
19
+ UNROUTED,
20
+ uncomparedText,
21
+ usd,
22
+ yourModel,
23
+ } from '../../display.mjs';
24
+ import { cellForModel, isSameModel } from '../../route.mjs';
25
+ import { modelSpec } from '../../savings.mjs';
26
+ import { readSubagentStore, summarizeSubagents } from '../../subagents.mjs';
27
+ import { allTime, dayKey, PERIODS, periodRange, summarize, trend } from '../../usage.mjs';
28
+ import { savingTone } from '../tokens.mjs';
29
+ import { dayLabel, plural, sentence } from './format.mjs';
30
+ import { agentsOf } from './usage-agents.mjs';
31
+ import { breakdownOf, compareOf, insightsOf } from './usage-breakdown.mjs';
32
+ import { chartOf, finite, PERIOD_PHRASE, saving, spanText } from './usage-shared.mjs';
33
+
34
+ /** @typedef {import('../tokens.mjs').Tone} Tone */
35
+ /** @typedef {{ text: string, tone: Tone }} Toned */
36
+
37
+ const PERIOD_LABEL = { session: 'Session', today: 'Today', '7d': '7d', '30d': '30d', month: 'Month', all: 'All' };
38
+ // The cost table's total row: the terminal's word, and the caption under a card's headline figure.
39
+ const TOTAL = {
40
+ session: { terminal: 'session', graphical: 'This session' },
41
+ today: { terminal: 'today', graphical: 'Today' },
42
+ '7d': { terminal: '7 days', graphical: 'Last 7 days' },
43
+ '30d': { terminal: '30 days', graphical: 'Last 30 days' },
44
+ month: { terminal: 'month', graphical: 'This month' },
45
+ all: { terminal: 'all', graphical: 'All time' },
46
+ };
47
+ // The footer as [text, joiner] pieces, packed to the pane: two lines at full width, more in a narrow pane.
48
+ /** @type {[string, string][]} */
49
+ const SAVINGS_FOOTER = [
50
+ ['≈$ = tokens × configured API rates (list/custom)', ' · '],
51
+ ['not invoices or measured quota savings', ' · '],
52
+ ['answer quality not measured', ''],
53
+ ];
54
+ const NOTES = {
55
+ pieces: SAVINGS_FOOTER,
56
+ width: 68,
57
+ title: 'About these numbers',
58
+ lines: [
59
+ '≈$ = tokens × configured API rates (list/custom)',
60
+ 'Not invoices or measured quota savings',
61
+ 'Answer quality not measured',
62
+ ],
63
+ };
64
+
65
+ // The tier whose route is your model at your effort, for its color; else any tier on your model.
66
+ function yourTier(config, view) {
67
+ const runs = (tier) => {
68
+ const route = resolveRoute(config, tier);
69
+ return (
70
+ isSameModel(config.models[route.model].id, view.nativeModel) &&
71
+ routeEffort(config, route, view.nativeEffort) === (view.nativeEffort ?? null)
72
+ );
73
+ };
74
+ return TIERS.find(runs) ?? cellForModel(config, view.nativeModel)?.tier ?? null;
75
+ }
76
+
77
+ /**
78
+ * The Usage tab, answer first for the chosen period: routing against your model as a ledger that adds up, the tokens,
79
+ * the cost by activity, model or tier, the trend and What if, and what is worth a look. Subagents follow, for the same
80
+ * period, then the notes and Delete history.
81
+ */
82
+ /**
83
+ * @typedef {object} UsageModel The Usage tab. Each part holds its own readings, words and tones; the parts whose shape
84
+ * differs by state (an empty summary, a period without replies) are typed loosely.
85
+ * @property {{ value: string, options: { value: string, key: string, label: string, selected: boolean, hotkey?: string }[], pick: (period: string) => void, hint: string }} period
86
+ * @property {{ text: string, model: { text: string, tier: string | null } | null, graphical: string }} scope
87
+ * @property {any} summary the cost ledger
88
+ * @property {{ text: string } | null} stats
89
+ * @property {any} breakdown
90
+ * @property {any} compare
91
+ * @property {any} trend
92
+ * @property {any} insights
93
+ * @property {any} agents
94
+ * @property {{ pieces: [string, string][], width: number, title: string, lines: string[] }} notes
95
+ * @property {{ confirming: boolean, ask: any, question: string, yes: any, no: any }} delete
96
+ */
97
+ /**
98
+ * @param {import('./frame.mjs').PaneContext} ctx
99
+ * @returns {UsageModel}
100
+ */
101
+ export function usageOf({ config, view, usage, actions, now }) {
102
+ const period = PERIODS.includes(view.usagePeriod) ? view.usagePeriod : 'session';
103
+ const record = liveUsage(view, period === 'session' ? view.usageSession : view.usageStore);
104
+ const summary = summarize(record, periodRange(period, now));
105
+ // All adds the undated savings totals kept from before the usage records.
106
+ const kept = period === 'all' ? allTime(record, view.savingsStore) : null;
107
+ const legacy = kept?.legacy ?? null;
108
+ const agents = summarizeSubagents(
109
+ readSubagentStore(period === 'session' ? view.subagentSession : view.subagentStore),
110
+ period === 'session' ? { from: null, to: null } : periodRange(period, now),
111
+ );
112
+ const cost = periodCost(config, {
113
+ summary: kept ? { ...summary, ...kept.totals, observed: kept.observed } : summary,
114
+ agents,
115
+ usage,
116
+ });
117
+ const replies = Boolean(summary.observed.replies);
118
+ const compare = !cost.effortOnly;
119
+ return {
120
+ period: periodOf(period, actions),
121
+ scope: scopeOf(config, view, period, summary, now),
122
+ summary: summaryOf(config, view, period, cost, legacy, actions),
123
+ stats: replies ? statsOf({ ...summary.observed, turns: summary.turns }) : null,
124
+ breakdown: replies ? breakdownOf(view, actions, summary, compare, cost.billing) : null,
125
+ compare: replies ? compareOf(view, actions, summary, cost.billing) : null,
126
+ trend: replies ? trendOf(summary, period, now, cost.billing) : null,
127
+ insights: replies ? insightsOf(summary, actions) : null,
128
+ agents: agentsOf(config, view, actions, period, now, cost.billing),
129
+ notes: NOTES,
130
+ delete: deleteOf(view, actions),
131
+ };
132
+ }
133
+
134
+ // The period buttons; `p` presses the one after the shown period, so it steps through them.
135
+ function periodOf(period, actions) {
136
+ const next = PERIODS[(PERIODS.indexOf(period) + 1) % PERIODS.length];
137
+ return {
138
+ value: period,
139
+ options: PERIODS.map((id) => ({
140
+ value: id,
141
+ key: `period-${id}`,
142
+ label: PERIOD_LABEL[id],
143
+ selected: id === period,
144
+ ...(id === next ? { hotkey: 'p' } : {}),
145
+ })),
146
+ pick: (id) => actions.period(id),
147
+ hint: 'p next',
148
+ };
149
+ }
150
+
151
+ // Whose replies the period holds and what each is compared with. `model` is your model with its tier, when the
152
+ // terminal draws it in the tier's colour.
153
+ function scopeOf(config, view, period, summary, now) {
154
+ if (period === 'session') {
155
+ const recorded = recordedModels(config, view, summary);
156
+ if (recorded) {
157
+ const text =
158
+ Object.keys(summary.yours).length > 1
159
+ ? `this session · each reply vs the model /model selected: ${recorded}`
160
+ : `this session · your model ${recorded}`;
161
+ return { text, model: null, graphical: sentence(text) };
162
+ }
163
+ const yours = yourModel(view);
164
+ return {
165
+ text: 'this session · your model ',
166
+ model: { text: yours, tier: yourTier(config, view) },
167
+ graphical: `This session · your model ${yours}`,
168
+ };
169
+ }
170
+ const span = spanText(period, now, summary.days[0]?.[0]) ?? 'no dated replies yet';
171
+ const text = `all projects · ${span} · each session vs its own model`;
172
+ return { text, model: null, graphical: sentence(text) };
173
+ }
174
+
175
+ // Why a period has no cost to show.
176
+ function emptyOf(config, view, period) {
177
+ if (period === 'session' && !modelSpec(config, view.nativeModel)) {
178
+ const name = modelName(view.nativeModel);
179
+ return {
180
+ text: `${name} has no list price in router.json models.`,
181
+ graphical: `${name} has no list price in the settings file.`,
182
+ };
183
+ }
184
+ const off = period === 'session' && (view.phase === 'unavailable' || view.mode === 'manual');
185
+ const text = off
186
+ ? `Routing is ${view.phase === 'unavailable' ? 'unavailable' : 'off'}: replies use your model and are not counted.`
187
+ : `No routed replies ${PERIOD_PHRASE[period]}.`;
188
+ return { text, graphical: text };
189
+ }
190
+
191
+ // The period's cost as one table that adds up: the main thread with the parts of its difference, the subagents and the
192
+ // total. "No routing" is your model on the main thread and Claude Code's pick for each subagent; zero rows are left out.
193
+ function summaryOf(config, view, period, cost, legacy, actions) {
194
+ if (!cost.replies && !cost.agents) return { empty: emptyOf(config, view, period) };
195
+ const { billing } = cost;
196
+ const compared = cost.diffUsd !== null;
197
+ const r = cost.readout;
198
+ // A row: its label, cost, difference against no routing and what no routing costs; null where a column is empty.
199
+ const row = (label, graphical, amount, diff, base, rowBilling = billing) => ({
200
+ kind: 'row',
201
+ label,
202
+ graphical,
203
+ amount: costText(amount, rowBilling),
204
+ diff: compared ? (diff === null ? { text: '', tone: 'primary' } : saving(diff)) : null,
205
+ base: compared && base !== null ? costText(base, rowBilling) : null,
206
+ });
207
+ const part = (label, graphical, value, /** @type {string | null} */ note = null) =>
208
+ value
209
+ ? { kind: 'part', label, graphical, diff: saving(value), note: note && { text: note, graphical: note } }
210
+ : null;
211
+ // The rebuilds' share of what the cheaper models saved; past all of it the switches lost money, which `lost` says.
212
+ const share = r.switchUsd > 0 && -r.cheaperUsd > 0 ? r.switchUsd / -r.cheaperUsd : null;
213
+ const switches = share !== null && share <= 1 ? `${percent(share)} of the saving` : null;
214
+ const total = TOTAL[period];
215
+ const mainReplies = plural(cost.replies, 'reply', 'replies');
216
+ return {
217
+ empty: null,
218
+ compared,
219
+ headline: compared
220
+ ? {
221
+ compared: true,
222
+ text: diffText(cost.diffUsd, cost.baseUsd),
223
+ tone: savingTone(cost.diffUsd),
224
+ versus: `vs ${UNROUTED}`,
225
+ // A card's delta beside the headline figure.
226
+ delta: `${diffText(cost.diffUsd, cost.baseUsd)} vs ${UNROUTED}`,
227
+ early: cost.early ? `${repliesText(cost)}: ${EARLY_NOTE}` : null,
228
+ }
229
+ : {
230
+ compared: false,
231
+ text: cost.effortOnly
232
+ ? 'Effort routing on one model: no saving is estimated; cost uses configured API rates.'
233
+ : `${sentence(uncomparedText(cost))}: no saving is shown.`,
234
+ },
235
+ // A card's headline figure: the period's total and what it is.
236
+ stat: { value: costText(cost.totalUsd, billing), caption: `${total.graphical} · ${API_ESTIMATE}` },
237
+ header: {
238
+ cost: { terminal: 'cost', graphical: 'Cost' },
239
+ diff: compared ? { terminal: `vs ${UNROUTED}`, graphical: `Vs ${UNROUTED}` } : null,
240
+ base: compared ? { terminal: UNROUTED, graphical: 'Unrouted' } : null,
241
+ },
242
+ rows: [
243
+ row(`main · ${mainReplies}`, `Main · ${mainReplies}`, cost.mainUsd, cost.mainDiff, compared ? r.yoursUsd : null),
244
+ compared ? part('cheaper models', 'Cheaper models', r.cheaperUsd) : null,
245
+ compared ? part('stronger models', 'Stronger models', r.strongerUsd) : null,
246
+ compared ? part('cache rebuilds', 'Cache rebuilds', r.switchUsd, switches) : null,
247
+ cost.agents
248
+ ? row(
249
+ `agents · ${cost.agents}`,
250
+ `Agents · ${cost.agents}`,
251
+ cost.agentUsd,
252
+ compared ? cost.agentDiff : null,
253
+ compared ? cost.agentBaseUsd : null,
254
+ )
255
+ : null,
256
+ ].filter(Boolean),
257
+ total: {
258
+ ...row(`${total.terminal} · ${API_ESTIMATE}`, 'Total', cost.totalUsd, cost.diffUsd, cost.baseUsd),
259
+ strong: true,
260
+ },
261
+ credits:
262
+ billing === 'mixed' ? row(' credits estimate', 'Credits estimate', cost.creditsUsd, null, null, 'billed') : null,
263
+ // A card's columns and their headings; a `wide` column is dropped in a narrow pane.
264
+ labels: { label: '', amount: 'Cost', diff: `Vs ${UNROUTED}`, base: 'Unrouted' },
265
+ columns: [
266
+ { key: 'label' },
267
+ { key: 'amount' },
268
+ ...(compared ? [{ key: 'diff' }, { key: 'base', show: 'wide' }] : []),
269
+ ],
270
+ legacy: legacy?.replies
271
+ ? {
272
+ text: `includes ${usd(legacy.routedUsd)} routed before dated records, kept without a breakdown`,
273
+ graphical: `Includes ${usd(legacy.routedUsd)} routed before dated records, kept without a breakdown`,
274
+ }
275
+ : null,
276
+ lost:
277
+ compared && !r.early && switchesLost(r)
278
+ ? {
279
+ text: 'Switches cost more than they saved',
280
+ button: { key: 'session-policy', label: 'Policy' },
281
+ press: () => actions.tab('policy'),
282
+ }
283
+ : null,
284
+ };
285
+ }
286
+
287
+ // Replies, turns, tokens and the cache share of the input.
288
+ const statsOf = (s) => ({
289
+ text:
290
+ `${plural(s.replies, 'reply', 'replies')} · ${plural(s.turns, 'turn')} · input ${formatTokens(s.inputTokens)}` +
291
+ ` · cache hit ${s.inputTokens ? percent(s.cacheReadTokens / s.inputTokens) : '—'} · output ${formatTokens(s.outputTokens)}`,
292
+ });
293
+
294
+ // Routed cost per hour, day or week: the terminal's one line of blocks (a dot for a bucket without replies) and its
295
+ // peak, and a card's line chart once there is more than one bucket.
296
+ function trendOf(summary, period, now, billing) {
297
+ const t = trend(summary, period, now);
298
+ const head = `COST BY ${t.unit.toUpperCase()}`;
299
+ if (t.values.length < 2) return { head, single: `one ${t.unit} so far`, points: [], peak: null, chart: null };
300
+ const points = t.values.map(finite);
301
+ const max = Math.max(...points);
302
+ const all =
303
+ t.unit === 'hour'
304
+ ? points.map((_, i) => `${t.from + i}:00`)
305
+ : points.map((_, i) => {
306
+ const [y, m, d] = t.from.split('-').map(Number);
307
+ return dayLabel(dayKey(new Date(y, m - 1, d + i * (t.unit === 'week' ? 7 : 1)).getTime()));
308
+ });
309
+ const title = `Cost by ${t.unit}`;
310
+ return {
311
+ head,
312
+ single: null,
313
+ points,
314
+ peak: { terminal: `peak ${costText(max, billing)}`, graphical: `Peak ${costText(max, billing)}` },
315
+ title: 'Trend',
316
+ hint: title,
317
+ chart: chartOf(title, points, { all }, (value) => costText(value, billing), t.unit === 'hour' ? 'at' : 'on'),
318
+ };
319
+ }
320
+
321
+ // Delete history waits for a second press, as nothing brings the records back.
322
+ function deleteOf(view, actions) {
323
+ return {
324
+ confirming: Boolean(view.confirmDelete),
325
+ ask: { key: 'delete-history', label: 'Delete history', press: () => actions.confirmDelete(true) },
326
+ question: 'Delete the usage, activity and subagent history of every session?',
327
+ yes: { key: 'delete-confirm', label: 'Delete', press: actions.resetStats },
328
+ no: { key: 'delete-keep', label: 'Keep', press: () => actions.confirmDelete(false) },
329
+ };
330
+ }
@@ -0,0 +1,220 @@
1
+ // The band as the terminal draws it: one row of the segments the model fits to the width, the Router button after
2
+ // them, a second row under the session's readings, and the hover controls drawn on the row itself so the pointer moves
3
+ // nothing.
4
+ import { TIERS } from '../../config.mjs';
5
+ import { gaugeCells, pinShort, tierBars } from '../../display.mjs';
6
+ import { isRouting } from '../../view.mjs';
7
+ import {
8
+ agentParts,
9
+ agentSegments,
10
+ BACK_CELLS,
11
+ BACK_LABEL,
12
+ bandSegments,
13
+ button,
14
+ dim,
15
+ fitSegments,
16
+ lineWidth,
17
+ part,
18
+ partsWidth,
19
+ routeLineSegments,
20
+ SEPARATOR,
21
+ segment,
22
+ sessionSegments,
23
+ } from '../model/band.mjs';
24
+ import { CHIP_BACKGROUND, TIER_COLOR, toneColor } from '../tokens.mjs';
25
+
26
+ // The hover row's controls sit closer: they are buttons, not readings.
27
+ const GAP = ' ';
28
+ // What follows the readings: a gap, then Router as a plain label. The graphical band draws Router as a bordered Button,
29
+ // which is its label and the Button's own `[ ` and ` ]` wide, with no gap before it.
30
+ const ROUTER_TAIL = 2 + 'Router'.length;
31
+ // The fewest columns the hover controls are drawn in: Turn off and a gap.
32
+ const OVERLAY_MIN = 12;
33
+ // The tier meter's glyphs, one per bar.
34
+ const BARS = '▂▄▆█';
35
+
36
+ // A part's glyphs: what it takes on the terminal.
37
+ export function partGlyphs(p) {
38
+ if (p.button) return `[ ${p.button.label} ]`;
39
+ if (p.meter) return BARS;
40
+ if (p.gauge !== undefined) return gaugeCells(p.gauge / 100, p.cells).join('');
41
+ return p.text;
42
+ }
43
+
44
+ // A text part's props on the terminal: its tone's colour, dim for secondary text, a chip's ground.
45
+ function textStyle(p) {
46
+ const color = p.tone ? toneColor(p.tone, 'terminal') : undefined;
47
+ return {
48
+ ...(p.chip ? { backgroundColor: CHIP_BACKGROUND } : {}),
49
+ ...(color ? { color } : {}),
50
+ ...(p.dim ? { dimColor: true } : {}),
51
+ ...(p.weight ? { weight: p.weight } : {}),
52
+ ...(p.italic ? { italic: true } : {}),
53
+ };
54
+ }
55
+
56
+ // A part as elements: a Button, a meter or gauge as its glyphs in single Texts, or one Text.
57
+ function drawPart({ Text, Button }, p) {
58
+ if (p.button) return [Button(p.button)];
59
+ if (p.meter) {
60
+ const lit = p.meter === 'off' || p.meter === 'pending' ? -1 : TIERS.indexOf(p.meter);
61
+ return [...BARS].map((bar, i) =>
62
+ Text(
63
+ p.meter === 'pending'
64
+ ? { color: toneColor('accent', 'terminal'), children: bar }
65
+ : i <= lit
66
+ ? { color: TIER_COLOR[p.meter], children: bar }
67
+ : { dimColor: true, children: bar },
68
+ ),
69
+ );
70
+ }
71
+ if (p.gauge !== undefined) {
72
+ const [filled, empty] = gaugeCells(p.gauge / 100, p.cells);
73
+ return [
74
+ Text({ color: toneColor(p.tone, 'terminal'), children: filled }),
75
+ Text({ dimColor: true, children: empty }),
76
+ ];
77
+ }
78
+ return [Text({ ...textStyle(p), children: p.text })];
79
+ }
80
+
81
+ const joinSegments = (segments) => segments.flatMap((s, i) => (i ? [part(SEPARATOR), ...s.parts] : s.parts));
82
+
83
+ // The second row's parts at `columns`.
84
+ export const sessionRow = (config, view, usage, columns, now = Date.now()) =>
85
+ joinSegments(fitSegments(sessionSegments(config, view, usage, now), columns));
86
+
87
+ // The controls revealed under the pointer: a pin per tier, low to high, each named by what it runs ("▂▄ Haiku·high"), then
88
+ // Turn off and the one- or two-row choice. No digit hotkeys, since a bare digit in an empty prompt would press them.
89
+ // When there is little room the pins lose their model names first, then 2 rows and the pins go and Turn off stays;
90
+ // while two rows show, the pins and then Turn off go and 1 row stays.
91
+ function hoverSegments(config, view, actions, columns) {
92
+ // While two rows show, 1 row is the band's way back and outranks Turn off, which /router off and the pane's f also do.
93
+ const two = Boolean(view.bandDetail);
94
+ const pins = (withNames) =>
95
+ segment(
96
+ two ? 2 : 1,
97
+ dim('pin '),
98
+ TIERS.flatMap((tier, i) => [
99
+ i ? part(' ') : null,
100
+ button({
101
+ key: `band-pin-${tier}`,
102
+ label: `${tierBars(tier)}${withNames && pinShort(config, tier) ? ` ${pinShort(config, tier)}` : ''}`,
103
+ onPress: () => actions.pin(tier),
104
+ }),
105
+ ]),
106
+ );
107
+ const rest = [
108
+ isRouting(view)
109
+ ? segment(two ? 1 : 0, button({ key: 'band-manual', label: 'Turn off', onPress: () => actions.mode('manual') }))
110
+ : null,
111
+ segment(
112
+ two ? 0 : 3,
113
+ button({ key: 'band-detail', label: two ? '1 row' : '2 rows', onPress: actions.toggleDetail }),
114
+ ),
115
+ ].filter(Boolean);
116
+ if (!isRouting(view)) return rest;
117
+ const named = [pins(true), ...rest];
118
+ return Number.isFinite(columns) && lineWidth(named, GAP) > columns ? [pins(false), ...rest] : named;
119
+ }
120
+
121
+ /**
122
+ * The terminal band: a subagent's row with its way back, or the main thread's segments and Router, the running agents
123
+ * under them and the session row when asked.
124
+ * @param {any} elements
125
+ */
126
+ export function terminalBand(elements, config, view, usage, { columns, agentId, agent, agents, back, now }, actions) {
127
+ const { Box } = elements;
128
+ const row = (parts) => Box({ children: parts.flatMap((p) => drawPart(elements, p)) });
129
+ if (agentId) {
130
+ const room = Number.isFinite(columns) ? Math.max(0, columns - BACK_CELLS) : columns;
131
+ return row([
132
+ ...(back
133
+ ? [button({ key: 'band-back', label: BACK_LABEL, plain: true, onPress: actions.back }), part(SEPARATOR)]
134
+ : []),
135
+ ...agentParts(config, agent, back ? room : columns),
136
+ ]);
137
+ }
138
+ const width = Number.isFinite(columns) ? Math.max(0, columns - ROUTER_TAIL) : columns;
139
+ const kept = fitSegments(bandSegments(config, view, usage, actions), width);
140
+ const left = joinSegments(kept.filter((s) => !s.right));
141
+ const end = joinSegments(kept.filter((s) => s.right));
142
+ const pad = end.length
143
+ ? Number.isFinite(width)
144
+ ? Math.max(SEPARATOR.length, width - partsWidth(left) - partsWidth(end))
145
+ : SEPARATOR.length
146
+ : 0;
147
+ const line = [...left, ...(pad ? [part(' '.repeat(pad))] : []), ...end];
148
+ line.push(part(' '), button({ key: 'details', label: 'Router', plain: true, onPress: actions.open }));
149
+ const running = joinSegments(agentSegments(agents ?? [], columns, actions));
150
+ const second = view.bandDetail ? sessionRow(config, view, usage, columns, now) : [];
151
+ return Box({
152
+ key: 'router-band',
153
+ flexDirection: 'column',
154
+ children: [
155
+ Box({
156
+ children: [
157
+ ...line.flatMap((p) => drawPart(elements, p)),
158
+ ...hoverOverlays(elements, config, view, actions, kept, line, columns),
159
+ ],
160
+ }),
161
+ running.length ? row(running) : null,
162
+ second.length ? row(second) : null,
163
+ ],
164
+ });
165
+ }
166
+
167
+ // The hover controls, drawn on the row rather than on a row of their own, so the pointer moves nothing. The row has two
168
+ // free stretches: over the readings, from after the leading segments up to the last one holding a control (the meter
169
+ // and model, a warning with Set up, a pin with its ✕) to the gap before Router; and after Router, to the band's end.
170
+ // With readings at the row's end Router sits at the band's end, and the first is all there is. The controls fill the
171
+ // wider stretch, and what does not fit goes to the other; each is padded with spaces to blank what is beneath, so no
172
+ // Button of the row is covered. A stretch under OVERLAY_MIN columns holds none.
173
+ function hoverOverlays(elements, config, view, actions, kept, line, columns) {
174
+ const { Box } = elements;
175
+ const lead = kept.filter((s) => !s.right);
176
+ const last = lead.findLastIndex((s) => s.parts.some((p) => p.button));
177
+ const over = lineWidth(lead.slice(0, Math.max(0, last) + 1), SEPARATOR) + SEPARATOR.length;
178
+ const after = partsWidth(line) + GAP.length;
179
+ const stretches = [
180
+ { left: over, width: partsWidth(line) - ROUTER_TAIL - over },
181
+ { left: after, width: Number.isFinite(columns) ? columns - after : Number.POSITIVE_INFINITY },
182
+ ]
183
+ .filter((stretch) => stretch.width >= OVERLAY_MIN)
184
+ .sort((a, b) => b.width - a.width);
185
+ const [widest, narrower] = stretches;
186
+ if (!widest) return [];
187
+ // A fit that is still too wide (one segment of Buttons, which cannot be cut) is dropped.
188
+ const fit = (candidates, room) => {
189
+ const fitted = fitSegments(candidates, room, GAP);
190
+ return lineWidth(fitted, GAP) <= room ? fitted : [];
191
+ };
192
+ const segments = hoverSegments(config, view, actions, widest.width).map((s, n) => ({ ...s, n }));
193
+ const first = fit(segments, widest.width);
194
+ const rest = segments.filter((s) => !first.some((placed) => placed.n === s.n));
195
+ const second = narrower && rest.length ? fit(rest, narrower.width) : [];
196
+ const overlay = ({ left, width }, fitted) => {
197
+ const controls = fitted.flatMap((s, i) => (i ? [part(GAP), ...s.parts] : s.parts));
198
+ const pad = Number.isFinite(width) ? width - partsWidth(controls) : 0;
199
+ return Box({
200
+ position: 'absolute',
201
+ top: 0,
202
+ left,
203
+ display: 'none',
204
+ hover: { display: 'flex' },
205
+ children: [...controls, ...(pad > 0 ? [part(' '.repeat(pad))] : [])].flatMap((p) => drawPart(elements, p)),
206
+ });
207
+ };
208
+ return [
209
+ ...(first.length ? [overlay(widest, first)] : []),
210
+ ...(narrower && second.length ? [overlay(narrower, second)] : []),
211
+ ];
212
+ }
213
+
214
+ // The route line the terminal places under a turn: the band's words, indented like the transcript's own dim lines.
215
+ export function terminalRouteLine(elements, config, line, { columns }) {
216
+ const indent = ' ';
217
+ const room = Number.isFinite(columns) ? Math.max(0, columns - indent.length) : columns;
218
+ const parts = joinSegments(fitSegments(routeLineSegments(config, line), room));
219
+ return elements.Box({ children: [part(indent), ...parts].flatMap((p) => drawPart(elements, p)) });
220
+ }