@alexeiled/claude-router 1.24.0 → 1.25.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/CHANGELOG.md +74 -0
- package/README.md +55 -7
- package/docs/architecture.md +30 -4
- package/docs/configuration.md +23 -14
- package/docs/evaluation.md +3 -3
- package/docs/native-router.md +12 -4
- package/docs/router-band.svg +140 -142
- package/docs/router-pane-classifier.svg +48 -31
- package/docs/router-pane-now.svg +162 -120
- package/docs/router-pane-policy.svg +79 -47
- package/docs/router-pane-routes.svg +8 -8
- package/docs/router-pane-usage-whatif.svg +14 -14
- package/docs/router-pane-usage.svg +20 -20
- package/docs/routing-modes.md +10 -8
- package/docs/user-guide.md +151 -22
- package/hooks/native-router.mjs +415 -88
- package/lib/activity-stats.mjs +23 -4
- package/lib/activity.mjs +7 -5
- package/lib/auto-engine.mjs +13 -6
- package/lib/auto-route.mjs +10 -4
- package/lib/band.mjs +35 -440
- package/lib/classifier-client.mjs +12 -8
- package/lib/config-file.mjs +7 -2
- package/lib/config.mjs +24 -9
- package/lib/cost.mjs +5 -1
- package/lib/costs.mjs +4 -2
- package/lib/decisions.mjs +13 -9
- package/lib/display.mjs +71 -20
- package/lib/facts.mjs +3 -0
- package/lib/failover.mjs +55 -0
- package/lib/modes.mjs +8 -4
- package/lib/panel.mjs +75 -2167
- package/lib/policy.mjs +7 -6
- package/lib/replay-trace.mjs +5 -2
- package/lib/replay.mjs +7 -1
- package/lib/route-line.mjs +46 -0
- package/lib/route.mjs +51 -32
- package/lib/savings.mjs +14 -3
- package/lib/subagents.mjs +41 -11
- package/lib/subcommands.mjs +60 -0
- package/lib/ui/fallback.mjs +22 -0
- package/lib/ui/graphical/band.mjs +256 -0
- package/lib/ui/graphical/charts.mjs +163 -0
- package/lib/ui/graphical/classifier.mjs +153 -0
- package/lib/ui/graphical/frame.mjs +231 -0
- package/lib/ui/graphical/kit.mjs +156 -0
- package/lib/ui/graphical/meter.mjs +25 -0
- package/lib/ui/graphical/now.mjs +357 -0
- package/lib/ui/graphical/policy.mjs +56 -0
- package/lib/ui/graphical/routes.mjs +264 -0
- package/lib/ui/graphical/squares.mjs +29 -0
- package/lib/ui/graphical/usage.mjs +376 -0
- package/lib/ui/model/band.mjs +441 -0
- package/lib/ui/model/classifier.mjs +308 -0
- package/lib/ui/model/draft.mjs +62 -0
- package/lib/ui/model/format.mjs +41 -0
- package/lib/ui/model/frame.mjs +359 -0
- package/lib/ui/model/now.mjs +421 -0
- package/lib/ui/model/policy.mjs +194 -0
- package/lib/ui/model/routes.mjs +392 -0
- package/lib/ui/model/usage-agents.mjs +311 -0
- package/lib/ui/model/usage-breakdown.mjs +237 -0
- package/lib/ui/model/usage-shared.mjs +58 -0
- package/lib/ui/model/usage.mjs +330 -0
- package/lib/ui/terminal/band.mjs +253 -0
- package/lib/ui/terminal/classifier.mjs +150 -0
- package/lib/ui/terminal/frame.mjs +169 -0
- package/lib/ui/terminal/kit.mjs +162 -0
- package/lib/ui/terminal/now.mjs +293 -0
- package/lib/ui/terminal/policy.mjs +55 -0
- package/lib/ui/terminal/routes.mjs +167 -0
- package/lib/ui/terminal/usage.mjs +363 -0
- package/lib/ui/terminal/wrap.mjs +37 -0
- package/lib/ui/tokens.mjs +106 -0
- package/lib/usage.mjs +5 -5
- package/lib/view.mjs +5 -2
- package/package.json +4 -2
- package/types/index.d.ts +17 -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,253 @@
|
|
|
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 bracketed Button, `[ Router ]`, where the brackets cost no reading,
|
|
29
|
+
// or as a plain label where they would. The graphical band always draws Router as a bordered Button.
|
|
30
|
+
const ROUTER_LABEL = 'Router';
|
|
31
|
+
const ROUTER_GAP = 2;
|
|
32
|
+
const BRACKETS = '[ ]'.length;
|
|
33
|
+
// The fewest columns the hover controls are drawn in: Turn off and a gap.
|
|
34
|
+
const OVERLAY_MIN = 12;
|
|
35
|
+
// The tier meter's glyphs, one per bar.
|
|
36
|
+
const BARS = '▂▄▆█';
|
|
37
|
+
|
|
38
|
+
// A part's glyphs: what it takes on the terminal.
|
|
39
|
+
export function partGlyphs(p) {
|
|
40
|
+
if (p.button) return `[ ${p.button.label} ]`;
|
|
41
|
+
if (p.meter) return BARS;
|
|
42
|
+
if (p.gauge !== undefined) return gaugeCells(p.gauge / 100, p.cells).join('');
|
|
43
|
+
return p.text;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// A text part's props on the terminal: its tone's colour, dim for secondary text, a chip's ground.
|
|
47
|
+
function textStyle(p) {
|
|
48
|
+
const color = p.tone ? toneColor(p.tone, 'terminal') : undefined;
|
|
49
|
+
return {
|
|
50
|
+
...(p.chip ? { backgroundColor: CHIP_BACKGROUND } : {}),
|
|
51
|
+
...(color ? { color } : {}),
|
|
52
|
+
...(p.dim ? { dimColor: true } : {}),
|
|
53
|
+
...(p.weight ? { weight: p.weight } : {}),
|
|
54
|
+
...(p.italic ? { italic: true } : {}),
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// A part as elements: a Button, a meter or gauge as its glyphs in single Texts, or one Text.
|
|
59
|
+
function drawPart({ Text, Button }, p) {
|
|
60
|
+
if (p.button) return [Button(p.button)];
|
|
61
|
+
if (p.meter) {
|
|
62
|
+
const lit = p.meter === 'off' || p.meter === 'pending' ? -1 : TIERS.indexOf(p.meter);
|
|
63
|
+
return [...BARS].map((bar, i) =>
|
|
64
|
+
Text(
|
|
65
|
+
p.meter === 'pending'
|
|
66
|
+
? { color: toneColor('accent', 'terminal'), children: bar }
|
|
67
|
+
: i <= lit
|
|
68
|
+
? { color: TIER_COLOR[p.meter], children: bar }
|
|
69
|
+
: { dimColor: true, children: bar },
|
|
70
|
+
),
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
if (p.gauge !== undefined) {
|
|
74
|
+
const [filled, empty] = gaugeCells(p.gauge / 100, p.cells);
|
|
75
|
+
return [
|
|
76
|
+
Text({ color: toneColor(p.tone, 'terminal'), children: filled }),
|
|
77
|
+
Text({ dimColor: true, children: empty }),
|
|
78
|
+
];
|
|
79
|
+
}
|
|
80
|
+
return [Text({ ...textStyle(p), children: p.text })];
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const joinSegments = (segments) => segments.flatMap((s, i) => (i ? [part(SEPARATOR), ...s.parts] : s.parts));
|
|
84
|
+
|
|
85
|
+
// The second row's parts at `columns`.
|
|
86
|
+
export const sessionRow = (config, view, usage, columns, now = Date.now()) =>
|
|
87
|
+
joinSegments(fitSegments(sessionSegments(config, view, usage, now), columns));
|
|
88
|
+
|
|
89
|
+
// The controls revealed under the pointer: a pin per tier, low to high, each named by what it runs ("▂▄ Haiku·high"), then
|
|
90
|
+
// Turn off and the one- or two-row choice. No digit hotkeys, since a bare digit in an empty prompt would press them.
|
|
91
|
+
// When there is little room the pins lose their model names first, then 2 rows and the pins go and Turn off stays;
|
|
92
|
+
// while two rows show, the pins and then Turn off go and 1 row stays.
|
|
93
|
+
function hoverSegments(config, view, actions, columns) {
|
|
94
|
+
// 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.
|
|
95
|
+
const two = Boolean(view.bandDetail);
|
|
96
|
+
const pins = (withNames) =>
|
|
97
|
+
segment(
|
|
98
|
+
two ? 2 : 1,
|
|
99
|
+
dim('pin '),
|
|
100
|
+
TIERS.flatMap((tier, i) => [
|
|
101
|
+
i ? part(' ') : null,
|
|
102
|
+
button({
|
|
103
|
+
key: `band-pin-${tier}`,
|
|
104
|
+
label: `${tierBars(tier)}${withNames && pinShort(config, tier) ? ` ${pinShort(config, tier)}` : ''}`,
|
|
105
|
+
onPress: () => actions.pin(tier),
|
|
106
|
+
}),
|
|
107
|
+
]),
|
|
108
|
+
);
|
|
109
|
+
const rest = [
|
|
110
|
+
isRouting(view)
|
|
111
|
+
? segment(two ? 1 : 0, button({ key: 'band-manual', label: 'Turn off', onPress: () => actions.mode('manual') }))
|
|
112
|
+
: null,
|
|
113
|
+
segment(
|
|
114
|
+
two ? 0 : 3,
|
|
115
|
+
button({ key: 'band-detail', label: two ? '1 row' : '2 rows', onPress: actions.toggleDetail }),
|
|
116
|
+
),
|
|
117
|
+
].filter(Boolean);
|
|
118
|
+
if (!isRouting(view)) return rest;
|
|
119
|
+
const named = [pins(true), ...rest];
|
|
120
|
+
return Number.isFinite(columns) && lineWidth(named, GAP) > columns ? [pins(false), ...rest] : named;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* The terminal band: a subagent's row with its way back, or the main thread's segments and Router, the running agents
|
|
125
|
+
* under them and the session row when asked.
|
|
126
|
+
* @param {any} elements
|
|
127
|
+
*/
|
|
128
|
+
export function terminalBand(elements, config, view, usage, { columns, agentId, agent, agents, back, now }, actions) {
|
|
129
|
+
const { Box } = elements;
|
|
130
|
+
const row = (parts) => Box({ children: parts.flatMap((p) => drawPart(elements, p)) });
|
|
131
|
+
if (agentId) {
|
|
132
|
+
const room = Number.isFinite(columns) ? Math.max(0, columns - BACK_CELLS) : columns;
|
|
133
|
+
return row([
|
|
134
|
+
...(back
|
|
135
|
+
? [button({ key: 'band-back', label: BACK_LABEL, plain: true, onPress: actions.back }), part(SEPARATOR)]
|
|
136
|
+
: []),
|
|
137
|
+
...agentParts(config, agent, back ? room : columns),
|
|
138
|
+
]);
|
|
139
|
+
}
|
|
140
|
+
const segments = bandSegments(config, view, usage, actions);
|
|
141
|
+
// The brackets go first: Router keeps them only where they cost nothing the plain label leaves room for, neither a
|
|
142
|
+
// reading nor a hover control.
|
|
143
|
+
const plain = bandLayout(config, view, actions, segments, columns, false);
|
|
144
|
+
const bracketed = bandLayout(config, view, actions, segments, columns, true);
|
|
145
|
+
const { line, hover } = sameLayout(plain, bracketed, columns) ? bracketed : plain;
|
|
146
|
+
const running = joinSegments(agentSegments(agents ?? [], columns, actions));
|
|
147
|
+
const second = view.bandDetail ? sessionRow(config, view, usage, columns, now) : [];
|
|
148
|
+
return Box({
|
|
149
|
+
key: 'router-band',
|
|
150
|
+
flexDirection: 'column',
|
|
151
|
+
children: [
|
|
152
|
+
Box({
|
|
153
|
+
children: [
|
|
154
|
+
...line.flatMap((p) => drawPart(elements, p)),
|
|
155
|
+
...hover.map((stretch) => overlay(elements, stretch)),
|
|
156
|
+
],
|
|
157
|
+
}),
|
|
158
|
+
running.length ? row(running) : null,
|
|
159
|
+
second.length ? row(second) : null,
|
|
160
|
+
],
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// The first row's parts with Router after them, plain or in brackets, and where its hover controls go.
|
|
165
|
+
function bandLayout(config, view, actions, segments, columns, brackets) {
|
|
166
|
+
const tail = ROUTER_GAP + ROUTER_LABEL.length + (brackets ? BRACKETS : 0);
|
|
167
|
+
const width = Number.isFinite(columns) ? Math.max(0, columns - tail) : columns;
|
|
168
|
+
const kept = fitSegments(segments, width);
|
|
169
|
+
const left = joinSegments(kept.filter((s) => !s.right));
|
|
170
|
+
const end = joinSegments(kept.filter((s) => s.right));
|
|
171
|
+
const pad = end.length
|
|
172
|
+
? Number.isFinite(width)
|
|
173
|
+
? Math.max(SEPARATOR.length, width - partsWidth(left) - partsWidth(end))
|
|
174
|
+
: SEPARATOR.length
|
|
175
|
+
: 0;
|
|
176
|
+
const line = [
|
|
177
|
+
...left,
|
|
178
|
+
...(pad ? [part(' '.repeat(pad))] : []),
|
|
179
|
+
...end,
|
|
180
|
+
part(' '.repeat(ROUTER_GAP)),
|
|
181
|
+
// The engine takes `plain` as true or not at all.
|
|
182
|
+
button({ key: 'details', label: ROUTER_LABEL, ...(brackets ? {} : { plain: true }), onPress: actions.open }),
|
|
183
|
+
];
|
|
184
|
+
const readings = lineWidth(kept, SEPARATOR);
|
|
185
|
+
return { width, readings, line, hover: hoverPlan(config, view, actions, { kept, line, tail }, columns) };
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// The hover controls' labels, in order: what a layout offers under the pointer.
|
|
189
|
+
const hoverLabels = (hover) =>
|
|
190
|
+
hover.flatMap(({ fitted }) => fitted.flatMap((s) => s.parts.filter((p) => p.button).map((p) => p.button.label)));
|
|
191
|
+
|
|
192
|
+
// Whether the bracketed layout shows every reading and hover control the plain one does, within its width.
|
|
193
|
+
function sameLayout(plain, bracketed, columns) {
|
|
194
|
+
if (bracketed.readings !== plain.readings) return false;
|
|
195
|
+
if (Number.isFinite(columns) && plain.readings > bracketed.width) return false;
|
|
196
|
+
return hoverLabels(bracketed.hover).join('\n') === hoverLabels(plain.hover).join('\n');
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// Where the hover controls go, drawn on the row rather than on a row of their own, so the pointer moves nothing. The row
|
|
200
|
+
// has two free stretches: over the readings, from after the leading segments up to the last one holding a control (the
|
|
201
|
+
// meter and model, a warning with Set up, a pin with its ✕) to the gap before Router; and after Router, to the band's
|
|
202
|
+
// end. With readings at the row's end Router sits at the band's end, and the first is all there is. The controls fill
|
|
203
|
+
// the wider stretch, and what does not fit goes to the other; each is padded with spaces to blank what is beneath, so
|
|
204
|
+
// no Button of the row is covered. A stretch under OVERLAY_MIN columns holds none.
|
|
205
|
+
function hoverPlan(config, view, actions, { kept, line, tail }, columns) {
|
|
206
|
+
const lead = kept.filter((s) => !s.right);
|
|
207
|
+
const last = lead.findLastIndex((s) => s.parts.some((p) => p.button));
|
|
208
|
+
const over = lineWidth(lead.slice(0, Math.max(0, last) + 1), SEPARATOR) + SEPARATOR.length;
|
|
209
|
+
const after = partsWidth(line) + GAP.length;
|
|
210
|
+
const stretches = [
|
|
211
|
+
{ left: over, width: partsWidth(line) - tail - over },
|
|
212
|
+
{ left: after, width: Number.isFinite(columns) ? columns - after : Number.POSITIVE_INFINITY },
|
|
213
|
+
]
|
|
214
|
+
.filter((stretch) => stretch.width >= OVERLAY_MIN)
|
|
215
|
+
.sort((a, b) => b.width - a.width);
|
|
216
|
+
const [widest, narrower] = stretches;
|
|
217
|
+
if (!widest) return [];
|
|
218
|
+
// A fit that is still too wide (one segment of Buttons, which cannot be cut) is dropped.
|
|
219
|
+
const fit = (candidates, room) => {
|
|
220
|
+
const fitted = fitSegments(candidates, room, GAP);
|
|
221
|
+
return lineWidth(fitted, GAP) <= room ? fitted : [];
|
|
222
|
+
};
|
|
223
|
+
const segments = hoverSegments(config, view, actions, widest.width).map((s, n) => ({ ...s, n }));
|
|
224
|
+
const first = fit(segments, widest.width);
|
|
225
|
+
const rest = segments.filter((s) => !first.some((placed) => placed.n === s.n));
|
|
226
|
+
const second = narrower && rest.length ? fit(rest, narrower.width) : [];
|
|
227
|
+
return [
|
|
228
|
+
...(first.length ? [{ ...widest, fitted: first }] : []),
|
|
229
|
+
...(narrower && second.length ? [{ ...narrower, fitted: second }] : []),
|
|
230
|
+
];
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// One stretch of hover controls: hidden until the pointer is over the row, padded to blank what is beneath.
|
|
234
|
+
function overlay(elements, { left, width, fitted }) {
|
|
235
|
+
const controls = fitted.flatMap((s, i) => (i ? [part(GAP), ...s.parts] : s.parts));
|
|
236
|
+
const pad = Number.isFinite(width) ? width - partsWidth(controls) : 0;
|
|
237
|
+
return elements.Box({
|
|
238
|
+
position: 'absolute',
|
|
239
|
+
top: 0,
|
|
240
|
+
left,
|
|
241
|
+
display: 'none',
|
|
242
|
+
hover: { display: 'flex' },
|
|
243
|
+
children: [...controls, ...(pad > 0 ? [part(' '.repeat(pad))] : [])].flatMap((p) => drawPart(elements, p)),
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// The route line the terminal places under a turn: the band's words, indented like the transcript's own dim lines.
|
|
248
|
+
export function terminalRouteLine(elements, config, line, { columns }) {
|
|
249
|
+
const indent = ' ';
|
|
250
|
+
const room = Number.isFinite(columns) ? Math.max(0, columns - indent.length) : columns;
|
|
251
|
+
const parts = joinSegments(fitSegments(routeLineSegments(config, line), room));
|
|
252
|
+
return elements.Box({ children: [part(indent), ...parts].flatMap((p) => drawPart(elements, p)) });
|
|
253
|
+
}
|