@luxass/pi-cost-explorer 0.0.0-stage → 0.1.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/src/dialog.ts ADDED
@@ -0,0 +1,784 @@
1
+ import type { Theme } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ isKeyRelease,
4
+ Key,
5
+ matchesKey,
6
+ truncateToWidth,
7
+ visibleWidth,
8
+ wrapTextWithAnsi,
9
+ type Component,
10
+ type KeybindingsManager,
11
+ type TUI,
12
+ type TuiMouseEvent,
13
+ type TuiMouseEventResult,
14
+ } from "@earendil-works/pi-tui";
15
+
16
+ import {
17
+ cacheHitRate,
18
+ createUsageTotals,
19
+ SOURCE_LABELS,
20
+ tokenCount,
21
+ type Analysis,
22
+ type UsageRecord,
23
+ type UsageTotals,
24
+ } from "./analysis";
25
+ import {
26
+ bar,
27
+ clock,
28
+ duration,
29
+ fit,
30
+ money,
31
+ percent,
32
+ plural,
33
+ sparkline,
34
+ table,
35
+ tokens,
36
+ type Column,
37
+ } from "./format";
38
+
39
+ type Tab = "Overview" | "Models" | "Turns" | "Tools" | "Requests";
40
+
41
+ /** What a tab or detail screen shows. */
42
+ interface Screen {
43
+ /** A line that stays above the scrolling lines, such as a table header. */
44
+ header?: string;
45
+ lines: string[];
46
+ /** One id per line in a list. Lists have a selected row; other screens only scroll. */
47
+ ids?: string[];
48
+ }
49
+
50
+ interface ScreenContext {
51
+ analysis: Analysis;
52
+ theme: Theme;
53
+ width: number;
54
+ sort: string;
55
+ onlyCurrentBranch: boolean;
56
+ }
57
+
58
+ interface TabConfig {
59
+ screen: (context: ScreenContext) => Screen;
60
+ /** The two sort orders of a list. The first is the default. */
61
+ sorts?: readonly [string, string];
62
+ /** The screen that Enter opens for a row. */
63
+ detail?: (context: ScreenContext, id: string) => Screen | undefined;
64
+ }
65
+
66
+ const TABS: Record<Tab, TabConfig> = {
67
+ Overview: { screen: overviewScreen },
68
+ Models: { screen: modelsScreen, sorts: ["cost", "requests"] },
69
+ Turns: { screen: turnsScreen, sorts: ["cost", "order"], detail: turnDetail },
70
+ Tools: { screen: toolsScreen, sorts: ["cost", "calls"] },
71
+ Requests: { screen: requestsScreen, sorts: ["order", "cost"], detail: recordDetail },
72
+ };
73
+ const TAB_NAMES = Object.keys(TABS) as Tab[];
74
+
75
+ const MAX_HEIGHT = 34;
76
+
77
+ interface Position {
78
+ selected: number;
79
+ top: number;
80
+ }
81
+
82
+ interface CostDialogOptions {
83
+ tui: TUI;
84
+ theme: Theme;
85
+ keybindings: KeybindingsManager;
86
+ load: (onlyCurrentBranch: boolean) => Analysis;
87
+ done: () => void;
88
+ }
89
+
90
+ export class CostDialog implements Component {
91
+ private readonly tui: TUI;
92
+ private readonly theme: Theme;
93
+ private readonly keybindings: KeybindingsManager;
94
+ private readonly load: (onlyCurrentBranch: boolean) => Analysis;
95
+ private readonly done: () => void;
96
+
97
+ private analysis: Analysis;
98
+ private onlyCurrentBranch = false;
99
+ private tab: Tab = "Overview";
100
+ /** Id of the row whose detail screen is open. */
101
+ private detailId: string | undefined;
102
+ private readonly alternateSort = new Set<Tab>();
103
+ private readonly positions = new Map<string, Position>();
104
+ /** Layout of the last render. Input handling uses it. */
105
+ private layout = {
106
+ width: 0,
107
+ page: 1,
108
+ rows: 0,
109
+ bodyTop: 0,
110
+ ids: undefined as string[] | undefined,
111
+ };
112
+
113
+ constructor({ tui, theme, keybindings, load, done }: CostDialogOptions) {
114
+ this.tui = tui;
115
+ this.theme = theme;
116
+ this.keybindings = keybindings;
117
+ this.load = load;
118
+ this.done = done;
119
+ this.analysis = load(false);
120
+ }
121
+
122
+ refresh(): void {
123
+ this.analysis = this.load(this.onlyCurrentBranch);
124
+ this.tui.requestRender();
125
+ }
126
+
127
+ close(): void {
128
+ this.done();
129
+ }
130
+
131
+ private sortOrder(): string | undefined {
132
+ return TABS[this.tab].sorts?.[this.alternateSort.has(this.tab) ? 1 : 0];
133
+ }
134
+
135
+ private position(): Position {
136
+ const key = this.detailId ? `${this.tab}:${this.detailId}` : this.tab;
137
+ let position = this.positions.get(key);
138
+ if (!position) {
139
+ position = { selected: 0, top: 0 };
140
+ this.positions.set(key, position);
141
+ }
142
+ return position;
143
+ }
144
+
145
+ private screen(width: number): Screen {
146
+ const config = TABS[this.tab];
147
+ const context: ScreenContext = {
148
+ analysis: this.analysis,
149
+ theme: this.theme,
150
+ width,
151
+ sort: this.sortOrder() ?? "",
152
+ onlyCurrentBranch: this.onlyCurrentBranch,
153
+ };
154
+ if (this.detailId) {
155
+ const detail = config.detail?.(context, this.detailId);
156
+ if (detail) return detail;
157
+ // The row is gone, for example after switching to the current branch.
158
+ this.detailId = undefined;
159
+ }
160
+ return config.screen(context);
161
+ }
162
+
163
+ private showTab(tab: Tab): void {
164
+ this.tab = tab;
165
+ this.detailId = undefined;
166
+ }
167
+
168
+ private open(): void {
169
+ // Read the current screen. A key can arrive before the screen it changed is rendered.
170
+ const id = this.screen(this.layout.width - 4).ids?.[this.position().selected];
171
+ if (id && TABS[this.tab].detail && !this.detailId) this.detailId = id;
172
+ }
173
+
174
+ private scroll(step: number): void {
175
+ const position = this.position();
176
+ const { lines, ids } = this.screen(this.layout.width - 4);
177
+ if (ids) position.selected = clamp(position.selected + step, 0, lines.length - 1);
178
+ else position.top = clamp(position.top + step, 0, lines.length - this.layout.page);
179
+ }
180
+
181
+ // Rendering
182
+
183
+ render(width: number): string[] {
184
+ const theme = this.theme;
185
+ const inner = width - 4;
186
+ const height = Math.min(MAX_HEIGHT, this.tui.terminal.rows - 4);
187
+ const screen = this.screen(inner);
188
+ const header = screen.header === undefined ? [] : [theme.fg("dim", screen.header)];
189
+ // Top border, two tab rows, hints, and bottom border surround the body.
190
+ const page = Math.max(1, height - 5 - header.length);
191
+
192
+ const position = this.position();
193
+ if (screen.ids) {
194
+ position.selected = clamp(position.selected, 0, screen.lines.length - 1);
195
+ // Scroll just enough to keep the selected row visible.
196
+ position.top = clamp(position.top, position.selected - page + 1, position.selected);
197
+ }
198
+ position.top = clamp(position.top, 0, screen.lines.length - page);
199
+ this.layout = {
200
+ width,
201
+ page,
202
+ rows: screen.lines.length,
203
+ bodyTop: 3 + header.length,
204
+ ids: screen.ids,
205
+ };
206
+
207
+ const body = screen.lines
208
+ .slice(position.top, position.top + page)
209
+ .map((line, index) =>
210
+ screen.ids && position.top + index === position.selected
211
+ ? highlight(theme, line, inner)
212
+ : line,
213
+ );
214
+ if (screen.ids?.length === 0) body.push(theme.fg("muted", "Nothing recorded yet."));
215
+ while (body.length < page) body.push("");
216
+
217
+ const border = (text: string) => theme.fg("borderAccent", text);
218
+ const row = (text: string) => border("│ ") + fit(text, inner) + border(" │");
219
+ const edge = (left: string, label: string, right: string) =>
220
+ border(left + "─") +
221
+ label +
222
+ border("─".repeat(Math.max(0, inner - visibleWidth(label))) + "─" + right);
223
+
224
+ const branches = this.onlyCurrentBranch ? "current branch" : "all branches";
225
+ const title = theme.bold(
226
+ theme.fg(
227
+ "accent",
228
+ truncateToWidth(
229
+ ` Cost explorer · ${money(this.analysis.total.cost.total)} · ${branches} `,
230
+ inner,
231
+ "…",
232
+ ),
233
+ ),
234
+ );
235
+ const scrolled =
236
+ screen.lines.length > page
237
+ ? ` ${position.top + 1}–${Math.min(screen.lines.length, position.top + page)} / ${screen.lines.length} `
238
+ : "";
239
+
240
+ return [
241
+ edge("╭", title, "╮"),
242
+ ...this.tabBar(inner).map(row),
243
+ ...header.map(row),
244
+ ...body.map(row),
245
+ row(this.hints(inner)),
246
+ edge("╰", theme.fg("dim", scrolled), "╯"),
247
+ ];
248
+ }
249
+
250
+ /** Draws the tabs in equal cells, so a click maps to a tab by division. */
251
+ private tabBar(width: number): string[] {
252
+ const titles: string[] = [];
253
+ const rails: string[] = [];
254
+ for (const [index, tab] of TAB_NAMES.entries()) {
255
+ const active = tab === this.tab;
256
+ // The last tab takes the columns left over by the division.
257
+ const cell =
258
+ tabWidth(width) + (index === TAB_NAMES.length - 1 ? width % TAB_NAMES.length : 0);
259
+ const label = fit(" ".repeat(Math.max(0, Math.floor((cell - tab.length) / 2))) + tab, cell);
260
+ titles.push(
261
+ active ? this.theme.bold(this.theme.fg("accent", label)) : this.theme.fg("muted", label),
262
+ );
263
+ rails.push(
264
+ this.theme.fg(active ? "accent" : "borderMuted", (active ? "━" : "─").repeat(cell)),
265
+ );
266
+ }
267
+ return [titles.join(""), rails.join("")];
268
+ }
269
+
270
+ private hints(width: number): string {
271
+ const sort = this.sortOrder();
272
+ const hints = [
273
+ this.detailId ? "Esc back" : TABS[this.tab].detail ? "Enter open" : undefined,
274
+ "q close",
275
+ sort && !this.detailId ? `s sort: ${sort}` : undefined,
276
+ "b branches",
277
+ "Tab tabs",
278
+ this.layout.ids ? "↑↓ select" : "↑↓ scroll",
279
+ "r refresh",
280
+ ];
281
+
282
+ let line = "";
283
+ for (const hint of hints) {
284
+ if (!hint) continue;
285
+ const [key = "", ...label] = hint.split(" ");
286
+ const styled = this.theme.fg("accent", key) + this.theme.fg("dim", ` ${label.join(" ")}`);
287
+ const candidate = line ? line + this.theme.fg("borderMuted", " · ") + styled : styled;
288
+ if (visibleWidth(candidate) <= width) line = candidate;
289
+ }
290
+ return line;
291
+ }
292
+
293
+ // Input
294
+
295
+ handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
296
+ const { width, page, rows, bodyTop, ids } = this.layout;
297
+ if (event.width !== width) return undefined;
298
+ const position = this.position();
299
+
300
+ if (event.type === "wheel") {
301
+ position.top = clamp(position.top + (event.wheelDelta ?? 0), 0, rows - page);
302
+ if (ids) position.selected = clamp(position.selected, position.top, position.top + page - 1);
303
+ this.tui.requestRender();
304
+ // Contain the event even at an edge so the transcript does not scroll.
305
+ return { handled: true, focus: true };
306
+ }
307
+ if (event.button !== "left" || (event.type !== "press" && event.type !== "click")) {
308
+ return undefined;
309
+ }
310
+
311
+ // Rows 1 and 2 are the tab bar, which starts after the two-column left border.
312
+ const tab =
313
+ TAB_NAMES[Math.min(TAB_NAMES.length - 1, Math.floor((event.x - 2) / tabWidth(width - 4)))];
314
+ const index = position.top + event.y - bodyTop;
315
+ const onTab =
316
+ (event.y === 1 || event.y === 2) && event.x >= 2 && event.x < width - 2 && tab !== undefined;
317
+ const onRow =
318
+ ids !== undefined && event.y >= bodyTop && index < rows && index < position.top + page;
319
+ if (!onTab && !onRow) return undefined;
320
+
321
+ if (event.type === "click") {
322
+ if (onTab) this.showTab(tab);
323
+ // Clicking the selected row opens it. Clicking another row selects it.
324
+ else if (index === position.selected) this.open();
325
+ else position.selected = index;
326
+ this.tui.requestRender();
327
+ }
328
+ return { handled: true, focus: true };
329
+ }
330
+
331
+ handleInput(data: string): void {
332
+ if (isKeyRelease(data)) return;
333
+ const keys = this.keybindings;
334
+ const index = TAB_NAMES.indexOf(this.tab);
335
+
336
+ if (data === "q" || (keys.matches(data, "tui.select.cancel") && !this.detailId)) {
337
+ this.done();
338
+ return;
339
+ }
340
+
341
+ if (keys.matches(data, "tui.select.cancel")) this.detailId = undefined;
342
+ else if (keys.matches(data, "tui.select.confirm")) this.open();
343
+ else if (matchesKey(data, Key.tab) || matchesKey(data, Key.right)) {
344
+ this.showTab(TAB_NAMES[(index + 1) % TAB_NAMES.length]!);
345
+ } else if (matchesKey(data, Key.shift(Key.tab)) || matchesKey(data, Key.left)) {
346
+ this.showTab(TAB_NAMES[(index - 1 + TAB_NAMES.length) % TAB_NAMES.length]!);
347
+ } else if (/^[1-5]$/.test(data)) this.showTab(TAB_NAMES[Number(data) - 1]!);
348
+ else if (data === "s" && this.sortOrder() && !this.detailId) {
349
+ if (this.alternateSort.has(this.tab)) this.alternateSort.delete(this.tab);
350
+ else this.alternateSort.add(this.tab);
351
+ this.positions.delete(this.tab);
352
+ } else if (data === "b") {
353
+ this.onlyCurrentBranch = !this.onlyCurrentBranch;
354
+ this.positions.clear();
355
+ this.analysis = this.load(this.onlyCurrentBranch);
356
+ } else if (data === "r") this.analysis = this.load(this.onlyCurrentBranch);
357
+ else if (keys.matches(data, "tui.select.up")) this.scroll(-1);
358
+ else if (keys.matches(data, "tui.select.down")) this.scroll(1);
359
+ else if (keys.matches(data, "tui.select.pageUp")) this.scroll(-this.layout.page);
360
+ else if (keys.matches(data, "tui.select.pageDown")) this.scroll(this.layout.page);
361
+ else if (matchesKey(data, Key.home)) this.scroll(-Infinity);
362
+ else if (matchesKey(data, Key.end)) this.scroll(Infinity);
363
+ else return;
364
+
365
+ this.tui.requestRender();
366
+ }
367
+
368
+ invalidate(): void {}
369
+ }
370
+
371
+ // Screens
372
+
373
+ function overviewScreen({ analysis, theme, width, onlyCurrentBranch }: ScreenContext): Screen {
374
+ const { total } = analysis;
375
+ if (total.count === 0) {
376
+ return {
377
+ lines: [
378
+ theme.fg("muted", "No usage recorded yet. Costs appear after the first model response."),
379
+ ],
380
+ };
381
+ }
382
+
383
+ const lines: string[] = [];
384
+ const labelWidth = 17;
385
+ const field = (label: string, value: string) => {
386
+ for (const [index, text] of wrapTextWithAnsi(value, width - labelWidth).entries()) {
387
+ lines.push(fit(theme.fg("muted", index === 0 ? label : ""), labelWidth) + text);
388
+ }
389
+ };
390
+ const dot = theme.fg("borderMuted", " · ");
391
+ const requests = analysis.bySource.get("assistant") ?? createUsageTotals();
392
+ const prompts = analysis.turns.filter((turn) => turn.records.length > 0).length;
393
+ const span =
394
+ analysis.firstTimestamp && analysis.lastTimestamp
395
+ ? ` · over ${duration(analysis.lastTimestamp - analysis.firstTimestamp)}`
396
+ : "";
397
+
398
+ field(
399
+ "Total",
400
+ theme.bold(theme.fg("accent", money(total.cost.total))) +
401
+ theme.fg(
402
+ "dim",
403
+ ` ${plural(requests.count, "request")} · ${plural(prompts, "prompt")}${span}`,
404
+ ),
405
+ );
406
+ field(
407
+ "Tokens",
408
+ [
409
+ theme.fg("text", tokens(tokenCount(total))),
410
+ `in ${tokens(total.input)}`,
411
+ `out ${tokens(total.output)}`,
412
+ `cache read ${tokens(total.cacheRead)}`,
413
+ `cache write ${tokens(total.cacheWrite)}`,
414
+ ].join(dot),
415
+ );
416
+ field("Cost split", costSplit(theme, total, Math.min(40, width - labelWidth)));
417
+ field(
418
+ "",
419
+ COST_PARTS.map(
420
+ ([label, color, cost]) => `${theme.fg(color, "■")} ${label} ${money(cost(total))}`,
421
+ ).join(dot),
422
+ );
423
+ field("Cache hit rate", `${percent(cacheHitRate(total))} of prompt tokens read from cache`);
424
+ field(
425
+ "Averages",
426
+ `${money(prompts > 0 ? total.cost.total / prompts : 0)} per prompt${dot}${money(requests.count > 0 ? requests.cost.total / requests.count : 0)} per request`,
427
+ );
428
+ field(
429
+ "Cost over time",
430
+ theme.fg(
431
+ "accent",
432
+ sparkline(
433
+ analysis.records.map((record) => record.usage.cost.total),
434
+ Math.min(48, width - labelWidth),
435
+ ),
436
+ ),
437
+ );
438
+
439
+ const sources = [...analysis.bySource].toSorted(
440
+ (left, right) => right[1].cost.total - left[1].cost.total,
441
+ );
442
+ lines.push("", theme.bold("By source"));
443
+ lines.push(
444
+ ...table<(typeof sources)[number]>(
445
+ [
446
+ { header: "", cell: ([source]) => ` ${SOURCE_LABELS[source]}` },
447
+ costColumn(theme, ([, totals]) => totals.cost.total),
448
+ numberColumn("", 6, ([, totals]) => percent(totals.cost.total / total.cost.total)),
449
+ numberColumn("", 6, ([, totals]) => `${totals.count}×`),
450
+ barColumn(theme, sources, ([, totals]) => totals.cost.total),
451
+ ],
452
+ sources,
453
+ width,
454
+ ).lines,
455
+ );
456
+
457
+ const model = analysis.models[0];
458
+ const turn = analysis.turns.toSorted(
459
+ (left, right) => right.totals.cost.total - left.totals.cost.total,
460
+ )[0];
461
+ const tool = analysis.tools[0];
462
+ lines.push("", theme.bold("Biggest spenders"));
463
+ if (model) {
464
+ field(
465
+ "Model",
466
+ `${model.model} ${theme.fg("accent", money(model.totals.cost.total))} ${theme.fg("dim", `(${percent(model.totals.cost.total / total.cost.total)})`)}`,
467
+ );
468
+ }
469
+ if (turn && turn.totals.cost.total > 0) {
470
+ field(
471
+ "Prompt",
472
+ `#${turn.index} ${theme.fg("text", `“${truncateToWidth(turn.prompt, 60, "…")}”`)} ${theme.fg("accent", money(turn.totals.cost.total))}`,
473
+ );
474
+ }
475
+ if (tool && tool.calls > 0) {
476
+ field(
477
+ "Tool",
478
+ `${tool.name} ${theme.fg("accent", `≈${money(tool.share + tool.nested.cost.total)}`)} ${theme.fg("dim", `over ${plural(tool.calls, "call")}`)}`,
479
+ );
480
+ }
481
+
482
+ const warning = theme.fg("warning", "!");
483
+ const notes = [
484
+ analysis.unpriced > 0 &&
485
+ `${warning} ${plural(analysis.unpriced, "usage record")} with tokens but no cost. Pi has no price for that model, so totals are too low.`,
486
+ analysis.failedCount > 0 &&
487
+ `${warning} ${money(analysis.failedCost)} went to ${plural(analysis.failedCount, "failed or aborted request")}.`,
488
+ !onlyCurrentBranch &&
489
+ analysis.offBranchCost > 0 &&
490
+ `${theme.fg("muted", "·")} ${money(analysis.offBranchCost)} was spent on other session branches. Press b to show only the current branch.`,
491
+ ].filter((note) => typeof note === "string");
492
+ if (notes.length > 0) {
493
+ lines.push("");
494
+ for (const note of notes) lines.push(...wrapTextWithAnsi(note, width));
495
+ }
496
+
497
+ return { lines };
498
+ }
499
+
500
+ function modelsScreen({ analysis, theme, width, sort }: ScreenContext): Screen {
501
+ const rows =
502
+ sort === "requests"
503
+ ? analysis.models.toSorted((left, right) => right.totals.count - left.totals.count)
504
+ : analysis.models;
505
+ const columns: Column<(typeof rows)[number]>[] = [
506
+ { header: "Model", cell: (row) => row.model },
507
+ { header: "Provider", width: 12, optional: true, cell: (row) => row.provider ?? "–" },
508
+ numberColumn("Reqs", 5, (row) => String(row.totals.count)),
509
+ numberColumn("Input", 7, (row) => tokens(row.totals.input), true),
510
+ numberColumn("Output", 7, (row) => tokens(row.totals.output), true),
511
+ numberColumn("Cache", 6, (row) => percent(cacheHitRate(row.totals)), true),
512
+ costColumn(theme, (row) => row.totals.cost.total),
513
+ numberColumn(
514
+ "Share",
515
+ 5,
516
+ (row) => percent(row.totals.cost.total / analysis.total.cost.total),
517
+ true,
518
+ ),
519
+ barColumn(theme, rows, (row) => row.totals.cost.total),
520
+ ];
521
+ return { ...table(columns, rows, width), ids: rows.map((row) => row.key) };
522
+ }
523
+
524
+ function turnsScreen({ analysis, theme, width, sort }: ScreenContext): Screen {
525
+ const turns = analysis.turns.filter((turn) => turn.records.length > 0);
526
+ const rows =
527
+ sort === "cost"
528
+ ? turns.toSorted((left, right) => right.totals.cost.total - left.totals.cost.total)
529
+ : turns;
530
+ const columns: Column<(typeof rows)[number]>[] = [
531
+ numberColumn("#", 4, (row) => String(row.index)),
532
+ { header: "Time", width: 5, optional: true, cell: (row) => clock(row.timestamp) },
533
+ { header: "Prompt", cell: (row) => row.prompt },
534
+ numberColumn("Reqs", 4, (row) => String(row.totals.count), true),
535
+ numberColumn("Tools", 5, (row) => String(row.toolCalls), true),
536
+ numberColumn("Tokens", 7, (row) => tokens(tokenCount(row.totals)), true),
537
+ costColumn(theme, (row) => row.totals.cost.total),
538
+ barColumn(theme, rows, (row) => row.totals.cost.total),
539
+ ];
540
+ const { header, lines } = table(columns, rows, width);
541
+ return { header, lines: dimOffBranch(theme, rows, lines), ids: rows.map((row) => row.id) };
542
+ }
543
+
544
+ function toolsScreen({ analysis, theme, width, sort }: ScreenContext): Screen {
545
+ const rows =
546
+ sort === "calls"
547
+ ? analysis.tools.toSorted((left, right) => right.calls - left.calls)
548
+ : analysis.tools;
549
+ const columns: Column<(typeof rows)[number]>[] = [
550
+ { header: "Tool", cell: (row) => row.name },
551
+ numberColumn("Calls", 5, (row) => String(row.calls)),
552
+ numberColumn(
553
+ "Errors",
554
+ 6,
555
+ (row) => (row.errors > 0 ? theme.fg("error", String(row.errors)) : "0"),
556
+ true,
557
+ ),
558
+ numberColumn(
559
+ "Run time",
560
+ 8,
561
+ (row) => (row.durationMs > 0 ? duration(row.durationMs) : "–"),
562
+ true,
563
+ ),
564
+ numberColumn(
565
+ "Nested",
566
+ 9,
567
+ (row) => (row.nested.count > 0 ? money(row.nested.cost.total) : "–"),
568
+ true,
569
+ ),
570
+ costColumn(theme, (row) => row.share, "≈ Calling"),
571
+ barColumn(theme, rows, (row) => row.share + row.nested.cost.total),
572
+ ];
573
+ return { ...table(columns, rows, width), ids: rows.map((row) => row.name) };
574
+ }
575
+
576
+ function requestsScreen({ analysis, theme, width, sort }: ScreenContext): Screen {
577
+ const rows =
578
+ sort === "cost"
579
+ ? analysis.records.toSorted((left, right) => right.usage.cost.total - left.usage.cost.total)
580
+ : analysis.records;
581
+ return { ...requestsTable(theme, rows, width), ids: rows.map((row) => row.entryId) };
582
+ }
583
+
584
+ function turnDetail({ analysis, theme, width }: ScreenContext, id: string): Screen | undefined {
585
+ const turn = analysis.turns.find((item) => item.id === id);
586
+ if (!turn) return undefined;
587
+
588
+ const prompt = wrapTextWithAnsi(theme.fg("text", turn.prompt), width);
589
+ const records = requestsTable(theme, turn.records, width);
590
+ return {
591
+ lines: [
592
+ theme.bold(`Prompt #${turn.index}`) + theme.fg("dim", ` · ${clock(turn.timestamp)}`),
593
+ ...prompt.slice(0, 8),
594
+ ...(prompt.length > 8
595
+ ? [theme.fg("dim", `… ${plural(prompt.length - 8, "more line")}`)]
596
+ : []),
597
+ "",
598
+ ...breakdown(theme, turn.totals, width),
599
+ theme.fg(
600
+ "dim",
601
+ `${plural(turn.totals.count, "usage record")} · ${plural(turn.toolCalls, "tool call")} · cache hit ${percent(cacheHitRate(turn.totals))}`,
602
+ ),
603
+ "",
604
+ theme.bold("Usage records"),
605
+ theme.fg("dim", records.header),
606
+ ...records.lines,
607
+ ],
608
+ };
609
+ }
610
+
611
+ function recordDetail({ analysis, theme, width }: ScreenContext, id: string): Screen | undefined {
612
+ const record = analysis.records.find((item) => item.entryId === id);
613
+ if (!record) return undefined;
614
+
615
+ const turn = analysis.turns.find((item) => item.id === record.turnId);
616
+ const totals = { ...record.usage, count: 1 };
617
+
618
+ const fields: [string, string | undefined][] = [
619
+ ["Source", SOURCE_LABELS[record.source]],
620
+ ["Provider", record.provider],
621
+ ["Model", record.model],
622
+ ["Time", new Date(record.timestamp).toLocaleString()],
623
+ [
624
+ "Stop reason",
625
+ record.stopReason &&
626
+ (failed(record) ? theme.fg("warning", record.stopReason) : record.stopReason),
627
+ ],
628
+ ["Branch", record.onBranch ? undefined : theme.fg("dim", "not on the current session branch")],
629
+ ["Prompt", turn && `#${turn.index} ${truncateToWidth(turn.prompt, 80, "…")}`],
630
+ ["Tool calls", record.toolCalls.join(", ") || undefined],
631
+ ];
632
+ const lines = [theme.bold(recordLabel(record)), ""];
633
+ for (const [label, value] of fields) {
634
+ if (value) lines.push(...wrapTextWithAnsi(fit(theme.fg("muted", label), 14) + value, width));
635
+ }
636
+ lines.push("", ...breakdown(theme, totals, width));
637
+ if (record.usage.reasoning) {
638
+ lines.push(
639
+ theme.fg("dim", `Output includes ${tokens(record.usage.reasoning)} reasoning tokens.`),
640
+ );
641
+ }
642
+ return { lines };
643
+ }
644
+
645
+ // Shared pieces
646
+
647
+ const COST_PARTS = [
648
+ ["input", "accent", (totals: UsageTotals) => totals.cost.input],
649
+ ["output", "success", (totals: UsageTotals) => totals.cost.output],
650
+ ["cache read", "muted", (totals: UsageTotals) => totals.cost.cacheRead],
651
+ ["cache write", "warning", (totals: UsageTotals) => totals.cost.cacheWrite],
652
+ ] as const;
653
+
654
+ /** One bar split into the cost of each token kind. */
655
+ function costSplit(theme: Theme, totals: UsageTotals, width: number): string {
656
+ if (totals.cost.total <= 0) return "";
657
+ let used = 0;
658
+ return COST_PARTS.map(([, color, cost], index) => {
659
+ // The last part takes what is left, so rounding never changes the bar's width.
660
+ const share = Math.round((cost(totals) / totals.cost.total) * width);
661
+ const cells = index === COST_PARTS.length - 1 ? width - used : Math.min(width - used, share);
662
+ used += cells;
663
+ return theme.fg(color, "█".repeat(cells));
664
+ }).join("");
665
+ }
666
+
667
+ function breakdown(theme: Theme, totals: UsageTotals, width: number): string[] {
668
+ const rows: [label: string, count: number, cost: number][] = [
669
+ ["Input", totals.input, totals.cost.input],
670
+ ["Output", totals.output, totals.cost.output],
671
+ ["Cache read", totals.cacheRead, totals.cost.cacheRead],
672
+ ["Cache write", totals.cacheWrite, totals.cost.cacheWrite],
673
+ ["Total", tokenCount(totals), totals.cost.total],
674
+ ];
675
+ const { header, lines } = table<(typeof rows)[number]>(
676
+ [
677
+ { header: "", width: 14, cell: ([label]) => theme.fg("muted", label) },
678
+ numberColumn("Tokens", 9, ([, count]) => tokens(count)),
679
+ numberColumn("Cost", 11, ([, , cost]) => money(cost)),
680
+ ],
681
+ rows,
682
+ width,
683
+ );
684
+ return [theme.fg("dim", header), ...lines];
685
+ }
686
+
687
+ function requestsTable(theme: Theme, rows: readonly UsageRecord[], width: number) {
688
+ const columns: Column<UsageRecord>[] = [
689
+ { header: "Time", width: 5, cell: (row) => clock(row.timestamp) },
690
+ {
691
+ header: "Model",
692
+ cell: (row) =>
693
+ failed(row)
694
+ ? `${theme.fg("warning", "!")} ${recordLabel(row)}`
695
+ : row.source === "assistant"
696
+ ? recordLabel(row)
697
+ : theme.fg("muted", recordLabel(row)),
698
+ },
699
+ numberColumn("Input", 7, (row) => tokens(row.usage.input), true),
700
+ numberColumn("Output", 7, (row) => tokens(row.usage.output), true),
701
+ numberColumn("Cached", 7, (row) => tokens(row.usage.cacheRead), true),
702
+ numberColumn(
703
+ "Tools",
704
+ 5,
705
+ (row) => (row.toolCalls.length > 0 ? String(row.toolCalls.length) : "–"),
706
+ true,
707
+ ),
708
+ costColumn(theme, (row) => row.usage.cost.total),
709
+ barColumn(theme, rows, (row) => row.usage.cost.total),
710
+ ];
711
+ const { header, lines } = table(columns, rows, width);
712
+ return { header, lines: dimOffBranch(theme, rows, lines) };
713
+ }
714
+
715
+ function numberColumn<Row>(
716
+ header: string,
717
+ width: number,
718
+ cell: (row: Row) => string,
719
+ optional = false,
720
+ ): Column<Row> {
721
+ return { header, width, align: "right", optional, cell };
722
+ }
723
+
724
+ function costColumn<Row>(theme: Theme, cost: (row: Row) => number, header = "Cost"): Column<Row> {
725
+ return { header, width: 9, align: "right", cell: (row) => theme.fg("accent", money(cost(row))) };
726
+ }
727
+
728
+ /** A bar scaled to the largest value in `rows`. It is the first column to go when space runs out. */
729
+ function barColumn<Row>(
730
+ theme: Theme,
731
+ rows: readonly Row[],
732
+ value: (row: Row) => number,
733
+ ): Column<Row> {
734
+ const peak = Math.max(0, ...rows.map(value));
735
+ return {
736
+ header: "",
737
+ width: 10,
738
+ optional: true,
739
+ cell: (row) => theme.fg("accent", bar(peak > 0 ? value(row) / peak : 0, 10)),
740
+ };
741
+ }
742
+
743
+ function dimOffBranch(
744
+ theme: Theme,
745
+ rows: readonly { onBranch: boolean }[],
746
+ lines: string[],
747
+ ): string[] {
748
+ return lines.map((line, index) =>
749
+ rows[index]?.onBranch === false ? theme.fg("dim", line) : line,
750
+ );
751
+ }
752
+
753
+ function recordLabel(record: UsageRecord): string {
754
+ if (record.source === "assistant") return record.label;
755
+ if (record.source === "tool") return `↳ ${record.label} (tool)`;
756
+ if (record.source === "usage") return `${record.label} · ${record.model ?? "unknown"}`;
757
+ return SOURCE_LABELS[record.source];
758
+ }
759
+
760
+ function failed(record: UsageRecord): boolean {
761
+ return record.stopReason === "error" || record.stopReason === "aborted";
762
+ }
763
+
764
+ /**
765
+ * Draws a row on the selection background. Truncated cells end with a full reset, which
766
+ * also clears the background, so the background is applied again after each reset.
767
+ */
768
+ function highlight(theme: Theme, line: string, width: number): string {
769
+ const closeBackground = "\u001b[49m";
770
+ const openBackground = theme.bg("selectedBg", "").slice(0, -closeBackground.length);
771
+ let highlighted = fit(line, width);
772
+ for (const reset of ["\u001b[0m", "\u001b[m", closeBackground]) {
773
+ highlighted = highlighted.replaceAll(reset, reset + openBackground);
774
+ }
775
+ return openBackground + highlighted + closeBackground;
776
+ }
777
+
778
+ function tabWidth(width: number): number {
779
+ return Math.floor(width / TAB_NAMES.length);
780
+ }
781
+
782
+ function clamp(value: number, min: number, max: number): number {
783
+ return Math.max(min, Math.min(Math.max(min, max), value));
784
+ }