@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,308 @@
1
+ // The Classifier tab's model: one row per configured classifier, then the active one's settings and readings, and its
2
+ // accuracy across sessions.
3
+
4
+ import { latencyP95, readMetrics, readStore, storeSummary } from '../../activity-stats.mjs';
5
+ import { activeClassifier } from '../../config.mjs';
6
+ import { classifierStatus, missingCredentials, missingText, percent, probeOf, unpricedLine } from '../../display.mjs';
7
+ import { plural, sentence } from './format.mjs';
8
+ import { choiceOf } from './policy.mjs';
9
+
10
+ // The host and port as the request sees them: user info before an `@` is not the host. An endpoint that does not
11
+ // parse, such as one with a placeholder in its host, shows as written up to its path, and is not this machine.
12
+ function urlOf(endpoint) {
13
+ try {
14
+ return new URL(endpoint);
15
+ } catch {
16
+ return null;
17
+ }
18
+ }
19
+ const hostOf = (endpoint) => urlOf(endpoint)?.host ?? endpoint.replace(/^https?:\/\//, '').split('/')[0];
20
+ const LOCAL_HOSTS = ['127.0.0.1', 'localhost', '[::1]'];
21
+ const isLocal = (endpoint) => LOCAL_HOSTS.includes(urlOf(endpoint)?.hostname ?? '');
22
+
23
+ // Where a classifier's prompt goes: this machine, or the endpoint's host.
24
+ const whereOf = (entry) => (isLocal(entry.endpoint) ? 'this machine' : hostOf(entry.endpoint));
25
+ const pausedText = (health) => `paused until ${new Date(health.pausedUntil).toLocaleTimeString()}`;
26
+
27
+ /**
28
+ * @typedef {object} ClassifierRow one classifier: the terminal row's columns, and a card's status, readings and Button
29
+ * @property {string} key
30
+ * @property {string} label
31
+ * @property {boolean} active
32
+ * @property {() => void} press
33
+ * @property {{ label: string } | null} use a card's header Button, on every card but the active one's
34
+ * @property {{ text: string, local: boolean }} where where the prompt goes
35
+ * @property {string | null} probe
36
+ * @property {string | null} p95
37
+ * @property {{ tone: import('../tokens.mjs').Tone, text: string }} state the terminal's mark and word
38
+ * @property {{ key: string, label: string, press: (press: any) => void } | null} setup
39
+ * @property {string} narrowDetail the terminal's second line in a narrow pane
40
+ * @property {{ tone: import('../tokens.mjs').Tone, text: string }} status a card's
41
+ * @property {{ status: { tone: import('../tokens.mjs').Tone, text: string }, detail: string }} compact
42
+ * @property {{ label: string, value: string, tone: import('../tokens.mjs').Tone }[]} readings
43
+ * @property {{ key: string, label: string, hotkey?: string, press: (press: any) => void, note?: string } | null} credentials
44
+ *
45
+ * @typedef {object} ClassifierModel The Classifier tab: a row per classifier and the active one in full.
46
+ * @property {ClassifierRow[]} rows
47
+ * @property {ClassifierRow | undefined} current the active classifier's card
48
+ * @property {{ title: string, rows: ClassifierRow[] } | null} others
49
+ * @property {import('./format.mjs').Words} probeNote
50
+ * @property {{ label: string, mark: { glyph: string, tone: import('../tokens.mjs').Tone, text: string }, deadline: { label: string, control: import('./routes.mjs').Choice & { key: string, text: string }, help: import('./format.mjs').Words }, wait: { text: string, slow: boolean }, sends: { label: string, text: import('./format.mjs').Words, help: import('./format.mjs').Words }, health: { label: string, paused: string | null, steady: string, failures: string, last: string | null, value: string, tone: import('../tokens.mjs').Tone }, credentials: { label: string, button: { key: string, label: string, hotkey: string, press: (press: any) => void }, note: string }, session: { head: string, text: string } | null, readings: { label: string, value: string, tone: import('../tokens.mjs').Tone, help?: string }[] }} active
51
+ * @property {{ head: string, title: string, hint: string, rows: { text: string, label: string, value: string }[], unpriced: string | null } | null} store
52
+ */
53
+ /**
54
+ * @param {import('./frame.mjs').PaneContext} ctx
55
+ * @returns {ClassifierModel}
56
+ */
57
+ export function classifierOf({ config, view, actions }) {
58
+ const active = activeClassifier(config);
59
+ const health = view.health ?? { failures: 0, pausedUntil: 0 };
60
+ const paused = health.pausedUntil > Date.now();
61
+ const rows = Object.entries(config.classifiers).map(([id, entry]) =>
62
+ classifierRowOf(config, view, actions, id, entry, paused ? health : null),
63
+ );
64
+ const wait = waitOf(config, view, active);
65
+ const { matched = 0, total = 0 } = view.activityStats?.agreement ?? {};
66
+ const store = storeSummary(readStore(view.activityStore));
67
+ const healthParts = {
68
+ paused: paused ? pausedText(health) : null,
69
+ steady: 'not paused',
70
+ failures: plural(health.failures, 'recent failure'),
71
+ last: Number.isFinite(view.adviceMs) ? `last ${view.adviceMs} ms` : null,
72
+ };
73
+ return {
74
+ rows,
75
+ // A card's layout: the active classifier's full card, then the others as compact rows in one card.
76
+ current: rows.find((row) => row.active),
77
+ others: rows.some((row) => !row.active)
78
+ ? { title: 'Other classifiers', rows: rows.filter((row) => !row.active) }
79
+ : null,
80
+ probeNote: {
81
+ terminal: 'probe: historical turn-activity questions, not goal/phase accuracy; p95 from that run',
82
+ graphical: 'Probe: historical turn-activity questions, not goal/phase accuracy; p95 from that run',
83
+ },
84
+ active: {
85
+ label: active.label,
86
+ mark: { glyph: '●', tone: /** @type {const} */ ('accent'), text: 'Active' },
87
+ deadline: {
88
+ label: 'Deadline',
89
+ control: choiceOf('timeoutMs', active.timeoutMs, (v) => `${v} ms`, actions.classifierTimeout),
90
+ help: {
91
+ terminal: 'past the deadline the turn keeps its model',
92
+ graphical: 'Past the deadline the turn keeps its model',
93
+ },
94
+ },
95
+ wait: { text: wait.slow ? `${wait.text}: slower than the deadline` : wait.text, slow: wait.slow },
96
+ sends: {
97
+ label: 'Sends',
98
+ text: {
99
+ terminal: `prompt + ${config.context.recentTurns} recent turns → ${whereOf(active)}`,
100
+ graphical: `Prompt + ${config.context.recentTurns} recent turns → ${whereOf(active)}`,
101
+ },
102
+ help: {
103
+ terminal: 'the bounded active goal and current step also go to the classifier',
104
+ graphical: 'The bounded active goal and current step also go to the classifier',
105
+ },
106
+ },
107
+ health: {
108
+ label: 'Health',
109
+ ...healthParts,
110
+ // A card's one line.
111
+ value: sentence(
112
+ [healthParts.paused ?? healthParts.steady, healthParts.failures, healthParts.last]
113
+ .filter(Boolean)
114
+ .join(' · '),
115
+ ),
116
+ tone: /** @type {import('../tokens.mjs').Tone} */ (paused ? 'warning' : 'primary'),
117
+ },
118
+ credentials: {
119
+ label: 'Credentials',
120
+ button: { key: 'key', label: 'Edit', hotkey: 'k', press: (press) => actions.key(press, config.classifier) },
121
+ note: 'opens /plugin configure',
122
+ },
123
+ // How often this session's tools fit the classifier's accepted activity; none before a labelled turn.
124
+ session: total
125
+ ? { head: 'THIS SESSION', text: `Tool compatibility (not accuracy): ${agreement(matched, total)}` }
126
+ : null,
127
+ // A card's readings: the wait against the deadline, and this session's agreement.
128
+ readings: [
129
+ {
130
+ label: 'Wait',
131
+ value: wait.measured
132
+ ? wait.slow
133
+ ? `${wait.text} · slower than the deadline`
134
+ : wait.text
135
+ : 'None measured yet',
136
+ tone: /** @type {import('../tokens.mjs').Tone} */ (wait.slow ? 'warning' : 'primary'),
137
+ },
138
+ total
139
+ ? {
140
+ label: 'Tool agreement',
141
+ value: `${agreement(matched, total)} this session`,
142
+ tone: /** @type {import('../tokens.mjs').Tone} */ ('primary'),
143
+ help: 'Compatibility with the tools a turn used, not accuracy',
144
+ }
145
+ : null,
146
+ ].filter((one) => one !== null),
147
+ },
148
+ store: store.labelled > 0 ? storeUsageOf(store, view.activityMetrics) : null,
149
+ };
150
+ }
151
+
152
+ // One classifier: the terminal row's columns, and a card's status, readings and credentials Button. `paused` is the
153
+ // health while the classifier is paused, else null.
154
+ function classifierRowOf(config, view, actions, id, entry, paused) {
155
+ const isActive = id === config.classifier;
156
+ const missing = missingCredentials(config, view, id);
157
+ const probe = probeOf(config, id);
158
+ const local = isLocal(entry.endpoint);
159
+ // The active classifier's last error, when it is not one of the missing credentials the row already names. While
160
+ // routing is unavailable the error is the router's reason, which the notices show.
161
+ const failed =
162
+ isActive && view.phase !== 'unavailable' && view.error && !['missing-key', 'missing-account'].includes(view.error)
163
+ ? view.error
164
+ : null;
165
+ /** @type {{ tone: import('../tokens.mjs').Tone, text: string }} */
166
+ const status = missing
167
+ ? { tone: 'warning', text: sentence(missingText(config, id, missing)) }
168
+ : isActive && paused
169
+ ? { tone: 'warning', text: sentence(pausedText(paused)) }
170
+ : failed
171
+ ? { tone: 'warning', text: `Last error: ${classifierStatus(config, failed)}` }
172
+ : { tone: 'success', text: 'Ready' };
173
+ return {
174
+ key: `classifier-${id}`,
175
+ label: entry.label,
176
+ active: isActive,
177
+ press: () => actions.classifier(id),
178
+ // A card's header: Use on every card but the active one's.
179
+ use: isActive ? null : { label: 'Use' },
180
+ // The terminal's columns.
181
+ where: { text: whereOf(entry), local },
182
+ probe: probe ? `${probe.correct}/${probe.probes}` : null,
183
+ p95: probe ? `${probe.p95Ms} ms` : null,
184
+ state: missing
185
+ ? { tone: /** @type {const} */ ('warning'), text: `○ ${missingText(config, id, missing)}` }
186
+ : { tone: /** @type {const} */ ('success'), text: '● ready' },
187
+ setup: missing ? { key: `key-${id}`, label: 'Set up', press: (press) => actions.key(press, id) } : null,
188
+ // The terminal's second line in a narrow pane: where the prompt goes, and the probe result.
189
+ narrowDetail: [whereOf(entry), probe ? `${probe.correct}/${probe.probes} · p95 ${probe.p95Ms} ms` : null]
190
+ .filter(Boolean)
191
+ .join(' · '),
192
+ // A card's.
193
+ status,
194
+ // A compact row's: its status, and where the prompt goes with its probe result.
195
+ compact: {
196
+ status,
197
+ detail: [
198
+ local ? 'This machine' : whereOf(entry),
199
+ probe ? `${probe.correct} of ${probe.probes} right · p95 ${probe.p95Ms} ms` : null,
200
+ ]
201
+ .filter(Boolean)
202
+ .join(' · '),
203
+ },
204
+ readings: [
205
+ {
206
+ label: 'Prompt goes to',
207
+ value: local ? 'This machine' : whereOf(entry),
208
+ tone: /** @type {import('../tokens.mjs').Tone} */ (local ? 'success' : 'primary'),
209
+ },
210
+ probe
211
+ ? {
212
+ label: 'Activity probe',
213
+ value: `${probe.correct} of ${probe.probes} right · p95 ${probe.p95Ms} ms`,
214
+ tone: /** @type {import('../tokens.mjs').Tone} */ ('primary'),
215
+ }
216
+ : null,
217
+ ].filter((one) => one !== null),
218
+ // One credentials Button per card: Set up where something is missing, else the active one's Edit.
219
+ // The active one's answers k either way, as the terminal's Edit does.
220
+ credentials: missing
221
+ ? {
222
+ key: `key-${id}`,
223
+ label: 'Set up',
224
+ ...(isActive ? { hotkey: 'k' } : {}),
225
+ press: (press) => actions.key(press, id),
226
+ }
227
+ : isActive
228
+ ? {
229
+ key: 'key',
230
+ label: 'Edit credentials',
231
+ hotkey: 'k',
232
+ press: (press) => actions.key(press, id),
233
+ note: 'Shows how to add them',
234
+ }
235
+ : null,
236
+ };
237
+ }
238
+
239
+ // The active classifier's wait: live p95 over this session's turns, else its probe's; slow past the deadline.
240
+ function waitOf(config, view, active) {
241
+ const { latency } = readMetrics(view.activityMetrics);
242
+ const live = latencyP95(Object.hasOwn(latency, config.classifier) ? latency[config.classifier] : null);
243
+ const probe = probeOf(config, config.classifier);
244
+ const p95 = live ? live.ms : probe?.p95Ms;
245
+ const text = live
246
+ ? `p95 ${live.over ? '>' : '≤'} ${live.ms} ms over ${plural(live.turns, 'turn')}`
247
+ : probe
248
+ ? `p95 ${probe.p95Ms} ms in its probe`
249
+ : 'no wait measured yet';
250
+ return {
251
+ text,
252
+ measured: Boolean(live || probe),
253
+ slow: Number.isFinite(p95) && Boolean(p95 > active.timeoutMs || live?.over),
254
+ };
255
+ }
256
+
257
+ // "19 of 22 turns (86%)".
258
+ const agreement = (matched, total) => `${matched} of ${total} turns (${percent(matched / total)})`;
259
+
260
+ // The counts kept across sessions, read from the stores as last loaded: how often the tools a turn used fit the
261
+ // classifier's activity, and what the activity moves led to. Agreement uses the classifier's raw answer, so it can
262
+ // differ from the session's. Each row is the terminal's line and a card's label and value.
263
+ function storeUsageOf(summary, metrics) {
264
+ const { downMoves } = readMetrics(metrics);
265
+ const rows = [
266
+ { text: `Labelled ${summary.labelled} turns`, label: 'Labelled', value: plural(summary.labelled, 'turn') },
267
+ ];
268
+ const { matched, total } = summary.agreement;
269
+ if (total > 0)
270
+ rows.push({
271
+ text: `Tool compatibility (not accuracy): ${agreement(matched, total)}`,
272
+ label: 'Tool agreement',
273
+ value: agreement(matched, total),
274
+ });
275
+ const { focus } = summary;
276
+ if (focus.total > 0)
277
+ rows.push({
278
+ text: `Code/ops/explore classifier vs tools: ${agreement(focus.matched, focus.total)}`,
279
+ label: 'Code, ops and explore',
280
+ value: agreement(focus.matched, focus.total),
281
+ });
282
+ if (summary.disagreements.length) {
283
+ const pairs = summary.disagreements.map((d) => `${d.predicted} → ${d.observed} ${d.n}`).join(' · ');
284
+ rows.push({ text: `Mismatch ${pairs}`, label: 'Mismatches', value: pairs });
285
+ }
286
+ const { taken, refused } = summary.lateral;
287
+ if (taken + refused > 0)
288
+ rows.push({
289
+ text: `Activity moves ${taken} taken · ${refused} refused`,
290
+ label: 'Activity moves',
291
+ value: `${taken} taken · ${refused} refused`,
292
+ });
293
+ const { moves, escalations } = downMoves;
294
+ if (moves > 0) {
295
+ rows.push({
296
+ text: `Escalations after a cheaper activity move: ${escalations} in ${moves} move${moves === 1 ? '' : 's'}`,
297
+ label: 'Escalations',
298
+ value: `${escalations} after ${plural(moves, 'cheaper activity move')}`,
299
+ });
300
+ }
301
+ return {
302
+ head: 'ACROSS SESSIONS · since the last reset',
303
+ title: 'Across sessions',
304
+ hint: 'Since the last reset',
305
+ rows,
306
+ unpriced: unpricedLine(metrics),
307
+ };
308
+ }
@@ -0,0 +1,62 @@
1
+ // The route draft the Routes and Policy tabs edit, and what it changed against the saved config. Routes and Policy edit
2
+ // one draft and save together; Classifier saves each pick at once.
3
+
4
+ import {
5
+ ACTIVITIES,
6
+ effectiveActivities,
7
+ effectiveRoutes,
8
+ sameCell,
9
+ sameRoute,
10
+ TIERS,
11
+ tuningOf,
12
+ } from '../../config.mjs';
13
+ import { percent } from '../../display.mjs';
14
+ import { plural } from './format.mjs';
15
+
16
+ // The route draft the Routes and Policy tabs edit: the saved routes, activity overrides and mode until the person
17
+ // changes one.
18
+ export function routeDraftOf(config, view) {
19
+ if (view.routeDraft) return view.routeDraft;
20
+ const base = structuredClone({
21
+ ...(config.provider && config.provider !== 'anthropic' ? { provider: config.provider } : {}),
22
+ routes: config.routes,
23
+ baselineTier: config.baselineTier,
24
+ activities: config.activities,
25
+ activityRouting: config.activityRouting,
26
+ });
27
+ return { ...structuredClone(base), base };
28
+ }
29
+
30
+ /** @typedef {'downgradeVotes' | 'horizon' | 'cashCapUsd' | 'activityMass'} TuneKey */
31
+
32
+ // Rows: [key, label, format, router.json field]. Typed as tuples so tsc keeps each position's type.
33
+ /** @type {[TuneKey, string, (value: number) => string, string][]} */
34
+ export const POLICY_ROWS = [
35
+ ['downgradeVotes', 'Votes to go down', String, 'policy.downgradeVotes'],
36
+ ['horizon', 'Payback horizon', (v) => plural(v, 'turn'), 'policy.downgradeHorizonTurns'],
37
+ ['cashCapUsd', 'Credits cap', (v) => `$${v.toFixed(2)}`, 'policy.cashCapUsd'],
38
+ ['activityMass', 'Activity threshold', percent, 'policy.activityMass'],
39
+ ];
40
+
41
+ // What Routes and Policy changed and have not saved: tiers, baseline, activity cells and mode against the saved config,
42
+ // policy values against the values the draft started from. `cells` lists [activity, tier] pairs.
43
+ export function routingChanges(config, view) {
44
+ const raw = routeDraftOf(config, view);
45
+ const draft = { ...effectiveRoutes(raw, config), ...effectiveActivities(raw, config) };
46
+ const saved = tuningOf(config);
47
+ const base = view.tuningBase ?? saved;
48
+ const tuning = { ...saved, ...view.tuning };
49
+ const tiers = TIERS.filter((tier) => !sameRoute(draft.routes[tier], config.routes[tier]));
50
+ const baseline = draft.baselineTier !== config.baselineTier;
51
+ const cells = ACTIVITIES.flatMap((activity) =>
52
+ TIERS.filter((tier) => !sameCell(draft.activities[activity]?.[tier], config.activities[activity]?.[tier])).map(
53
+ (tier) => [activity, tier],
54
+ ),
55
+ );
56
+ const mode = draft.activityRouting !== config.activityRouting;
57
+ const policy = POLICY_ROWS.map(([key]) => key).filter(
58
+ (key) => Object.hasOwn(view.tuning ?? {}, key) && view.tuning[key] !== base[key],
59
+ );
60
+ const count = tiers.length + Number(baseline) + cells.length + Number(mode) + policy.length;
61
+ return { draft, saved, tuning, tiers, baseline, cells, mode, policy, count };
62
+ }
@@ -0,0 +1,41 @@
1
+ // Words and dates the tab models share: a count with its noun, the capital a card starts a sentence with, a day and a
2
+ // time, and the session strip's note.
3
+ import { TIERS } from '../../config.mjs';
4
+ import { dayKey } from '../../usage.mjs';
5
+
6
+ /**
7
+ * A sentence the terminal and a graphical surface word alike (a string) or each their own way.
8
+ * @typedef {string | { terminal: string, graphical: string }} Words
9
+ */
10
+
11
+ // "1 reply", "3 replies".
12
+ export const plural = (n, word, many = `${word}s`) => `${n} ${n === 1 ? word : many}`;
13
+
14
+ // The model's words start lower case, as the terminal writes them; a card starts them with a capital.
15
+ export const sentence = (words) => words.charAt(0).toUpperCase() + words.slice(1);
16
+
17
+ // A tier as a card labels it: "Micro", "High". Activity and effort words stay lower case.
18
+ export const tierLabel = (tier) => sentence(tier);
19
+
20
+ export const dayLabel = (key) => {
21
+ const [y, m, d] = key.split('-').map(Number);
22
+ return new Date(y, m - 1, d).toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
23
+ };
24
+
25
+ // "13:41", or "Oct 12 13:41" for another day than `now`'s.
26
+ const clockText = (ms) => new Date(ms).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' });
27
+ export const sinceText = (ms, now) =>
28
+ dayKey(ms) === dayKey(now) ? clockText(ms) : `${dayLabel(dayKey(ms))} ${clockText(ms)}`;
29
+
30
+ // The strip cell's tier: the one with most replies, the stronger on a tie; `none` where routing served none.
31
+ const STRIP_ORDER = [...TIERS].reverse().concat('none');
32
+ export const cellTier = (cell) => STRIP_ORDER.reduce((top, key) => ((cell[key] ?? 0) > (cell[top] ?? 0) ? key : top));
33
+
34
+ // The note beside the session strip: how many replies a cell holds once cells have merged (`per`), and since when the
35
+ // strip runs when Claude Code restarted after the session's first reply.
36
+ export function stripNote(strip, per, since, now) {
37
+ const restarted = Number.isFinite(strip.from) && Number.isFinite(since) && strip.from > since;
38
+ return [per > 1 ? `${per} replies per cell` : null, restarted ? `since ${sinceText(strip.from, now)}` : null]
39
+ .filter(Boolean)
40
+ .join(' · ');
41
+ }