@deathbeam/pi-usage 0.0.0-stage → 0.0.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.
Files changed (5) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +31 -2
  3. package/index.ts +332 -0
  4. package/package.json +35 -4
  5. package/usage.ts +252 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tomas Slusny
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,32 @@
1
- # Temporary Holding Version
1
+ # [@deathbeam/pi-usage](https://www.npmjs.com/package/@deathbeam/pi-usage)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Use the `/usage` command for a fullscreen dashboard of token usage and cost: a summary block (total
4
+ cost, requests, sessions, input/output/cache tokens, cache hit ratio, daily cost sparkline) and a
5
+ table you can group by provider (with models nested), model, or project (session cwd).
6
+
7
+ ## Installation
8
+
9
+ ```sh
10
+ # Choose one:
11
+ pi install npm:@deathbeam/pi-usage # this package
12
+ pi install git:github.com/deathbeam/pi-packages # all my packages
13
+ ```
14
+
15
+ ## Development
16
+
17
+ From this package directory:
18
+
19
+ ```sh
20
+ npm install
21
+ npm test
22
+ pi install .
23
+ ```
24
+
25
+ ## Keys
26
+
27
+ - `q` / `esc` — close
28
+ - `tab` / `←→` — cycle period (Today, 7d, 30d, All)
29
+ - `v` — cycle grouping (Provider, Model, Project)
30
+ - `↑↓` / `j k` — move the cursor
31
+ - `pgup` / `pgdn` — page the table
32
+ - `home` / `g`, `end` / `G` — jump to the top / bottom
package/index.ts ADDED
@@ -0,0 +1,332 @@
1
+ /** /usage — fullscreen token usage and cost dashboard, grouped by provider, model, or project. */
2
+
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
6
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
7
+ import { matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
8
+ import {
9
+ bucketCosts,
10
+ buildRows,
11
+ collectUsage,
12
+ dailyCosts,
13
+ summarize,
14
+ type GroupMode,
15
+ type GroupRow,
16
+ type Stats,
17
+ type UsageRecord,
18
+ } from "./usage.ts";
19
+
20
+ const PERIODS = [
21
+ { label: "Today", days: 1 },
22
+ { label: "7d", days: 7 },
23
+ { label: "30d", days: 30 },
24
+ { label: "All", days: Infinity },
25
+ ] as const;
26
+
27
+ const GROUPS = ["provider", "model", "project"] as const satisfies readonly GroupMode[];
28
+ const GROUP_LABELS: Record<GroupMode, string> = { provider: "Provider", model: "Model", project: "Project" };
29
+ const NAME_HEADERS: Record<GroupMode, string> = {
30
+ provider: "Provider / Model",
31
+ model: "Model",
32
+ project: "Project",
33
+ };
34
+
35
+ const SPARK_BARS = "▁▂▃▄▅▆▇█";
36
+ const MIN_NAME_WIDTH = 12;
37
+
38
+ function formatCost(cost: number): string {
39
+ if (cost === 0) return "-";
40
+ if (cost < 0.01) return `$${cost.toFixed(4)}`;
41
+ if (cost < 100) return `$${cost.toFixed(2)}`;
42
+ return `$${Math.round(cost).toLocaleString("en-US")}`;
43
+ }
44
+
45
+ function formatTokens(count: number): string {
46
+ if (count === 0) return "-";
47
+ if (count < 1000) return String(count);
48
+ if (count < 1_000_000) return `${(count / 1000).toFixed(count < 10_000 ? 1 : 0)}k`;
49
+ if (count < 1_000_000_000) return `${(count / 1_000_000).toFixed(1)}M`;
50
+ return `${(count / 1_000_000_000).toFixed(1)}B`;
51
+ }
52
+
53
+ /** Start of the `days`-day window ending today; 0 for All. */
54
+ function periodStart(days: number): number {
55
+ if (days === Infinity) return 0;
56
+ const start = new Date();
57
+ start.setHours(0, 0, 0, 0);
58
+ start.setDate(start.getDate() - (days - 1));
59
+ return start.getTime();
60
+ }
61
+
62
+ function hitPct(stats: Stats): string {
63
+ const total = stats.input + stats.cacheRead + stats.cacheWrite;
64
+ return total > 0 ? `${Math.round((100 * stats.cacheRead) / total)}%` : "-";
65
+ }
66
+
67
+ type Column = { label: string; width: number; cell: (stats: Stats, requests: number, totalCost: number) => string };
68
+
69
+ const COLUMNS: Column[] = [
70
+ { label: "Cost", width: 10, cell: (s) => formatCost(s.cost) },
71
+ // Cost already prices read/write differently; one combined token column is enough.
72
+ {
73
+ label: "Share",
74
+ width: 13,
75
+ cell: (s, _r, totalCost) => {
76
+ const share = totalCost > 0 ? s.cost / totalCost : 0;
77
+ const filled = Math.round(8 * share);
78
+ return "█".repeat(filled) + "·".repeat(8 - filled) + " " + `${Math.round(100 * share)}%`.padStart(4);
79
+ },
80
+ },
81
+ { label: "Reqs", width: 6, cell: (_s, requests) => formatTokens(requests) },
82
+ { label: "In", width: 7, cell: (s) => formatTokens(s.input) },
83
+ { label: "Out", width: 7, cell: (s) => formatTokens(s.output) },
84
+ { label: "Cache", width: 7, cell: (s) => formatTokens(s.cacheRead + s.cacheWrite) },
85
+ { label: "Hit%", width: 5, cell: (s) => hitPct(s) },
86
+ ];
87
+
88
+ /** Widths fit the worst case ($999,999 / 999.9B); the name column shrinks first, then Share, then Hit%. */
89
+ function layout(width: number): { nameWidth: number; columns: Column[] } {
90
+ const used = (cols: Column[]) => cols.reduce((sum, c) => sum + c.width + 1, 0);
91
+ let columns = COLUMNS;
92
+ if (width - used(columns) < MIN_NAME_WIDTH) columns = columns.filter((c) => c.label !== "Share");
93
+ if (width - used(columns) < MIN_NAME_WIDTH) columns = columns.filter((c) => c.label !== "Hit%");
94
+ return { nameWidth: Math.max(4, width - used(columns)), columns };
95
+ }
96
+
97
+ const padWidth = (s: string, w: number): string => s + " ".repeat(Math.max(0, w - visibleWidth(s)));
98
+
99
+ function displayName(mode: GroupMode, name: string): string {
100
+ if (mode !== "project") return name;
101
+ if (!name) return "(no cwd)";
102
+ const home = homedir();
103
+ return name === home || name.startsWith(home + "/") ? "~" + name.slice(home.length) : name;
104
+ }
105
+
106
+ /** Truncate a name to its column so ANSI codes and padding stay width-correct. */
107
+ function fitLabel(name: string, nameWidth: number): string {
108
+ return visibleWidth(name) > nameWidth ? truncateToWidth(name, nameWidth, "…") : name;
109
+ }
110
+
111
+ function tableLine(
112
+ nameWidth: number,
113
+ columns: Column[],
114
+ name: string,
115
+ stats: Stats,
116
+ requests: number,
117
+ totalCost: number,
118
+ ): string {
119
+ const label = fitLabel(name, nameWidth);
120
+ return [padWidth(label, nameWidth), ...columns.map((c) => padWidth(c.cell(stats, requests, totalCost), c.width))]
121
+ .join(" ")
122
+ .trimEnd();
123
+ }
124
+
125
+ /** Daily-cost sparkline `MM-DD ▁▂▃ MM-DD`: the whole period, downsampled to fit `width`. */
126
+ function sparkline(
127
+ records: UsageRecord[],
128
+ days: number,
129
+ width: number,
130
+ ): { first: string; bars: string; last: string } | undefined {
131
+ if (days === 1) return undefined;
132
+ let dayCount = days;
133
+ if (days === Infinity) {
134
+ let first = Infinity;
135
+ for (const record of records) if (record.ts < first) first = record.ts;
136
+ if (first === Infinity) return undefined;
137
+ const firstDay = new Date(first);
138
+ firstDay.setHours(0, 0, 0, 0);
139
+ const today = new Date();
140
+ today.setHours(0, 0, 0, 0);
141
+ dayCount = Math.max(1, Math.round((today.getTime() - firstDay.getTime()) / 86_400_000) + 1);
142
+ }
143
+ const daily = dailyCosts(records, dayCount);
144
+ const first = daily[0]!.label;
145
+ const last = daily[daily.length - 1]!.label;
146
+ // Two MM-DD labels and two spaces around the bars leave width - 12 columns of bars.
147
+ const bars = bucketCosts(daily, Math.ceil(dayCount / Math.max(1, width - 12)));
148
+ let max = 0;
149
+ for (const bar of bars) if (bar.cost > max) max = bar.cost;
150
+ if (max <= 0) return undefined;
151
+ return {
152
+ first,
153
+ bars: bars.map((d) => (d.cost <= 0 ? " " : SPARK_BARS[Math.max(1, Math.round((7 * d.cost) / max))])).join(""),
154
+ last,
155
+ };
156
+ }
157
+
158
+ type BodyRow = { name: string; stats: Stats; requests: number; dim: boolean };
159
+
160
+ function flatten(rows: GroupRow[]): BodyRow[] {
161
+ const body: BodyRow[] = [];
162
+ for (const row of rows) {
163
+ body.push({ name: row.name, stats: row.stats, requests: row.requests, dim: false });
164
+ for (const child of row.children ?? [])
165
+ body.push({ name: ` ${child.name}`, stats: child.stats, requests: child.requests, dim: true });
166
+ }
167
+ return body;
168
+ }
169
+
170
+ export default function (pi: ExtensionAPI) {
171
+ pi.registerCommand("usage", {
172
+ description: "Show token usage and cost per provider, model, or project",
173
+ handler: async (_args, ctx) => {
174
+ if (ctx.mode !== "tui") return;
175
+ const state: { records?: UsageRecord[]; done: number; total: number } = {
176
+ done: 0,
177
+ total: 0,
178
+ };
179
+ let render = () => {};
180
+ // Scanning on open is fast enough for a dashboard; no cache file.
181
+ const loaded = collectUsage(join(getAgentDir(), "sessions"), (done, total) => {
182
+ state.done = done;
183
+ state.total = total;
184
+ render();
185
+ }).then((records) => {
186
+ state.records = records;
187
+ });
188
+ const screen = {
189
+ overlay: true,
190
+ overlayOptions: { width: "100%", maxHeight: "100%", row: 0, col: 0 },
191
+ } as const;
192
+ await ctx.ui.custom((tui, theme, keys, done) => {
193
+ let period = 0;
194
+ let group: number = 0;
195
+ let cursor = 0;
196
+ let top = 0;
197
+ let rowCount = 0;
198
+ let viewHeight = 1; // set on first render; 1 keeps page keys sane before it
199
+ render = () => tui.requestRender();
200
+ void loaded.then(render);
201
+ const title = (width: number): string => {
202
+ const periodTabs = PERIODS.map(({ label }, i) =>
203
+ i === period ? theme.fg("accent", `[${label}]`) : theme.fg("muted", ` ${label} `),
204
+ ).join(" ");
205
+ const groupTabs = GROUPS.map((g, i) =>
206
+ i === group
207
+ ? theme.fg("accent", `[${GROUP_LABELS[g]}]`)
208
+ : theme.fg("muted", ` ${GROUP_LABELS[g]} `),
209
+ ).join(" ");
210
+ let left = `${theme.fg("accent", theme.bold("Usage"))} ${periodTabs}${theme.fg("dim", " (tab/←→)")}`;
211
+ let right = `${groupTabs}${theme.fg("dim", " (v)")}`;
212
+ if (visibleWidth(left) + 1 + visibleWidth(right) > width) {
213
+ left = left.replace(theme.fg("dim", " (tab/←→)"), "");
214
+ right = right.replace(theme.fg("dim", " (v)"), "");
215
+ }
216
+ const pad = Math.max(1, width - visibleWidth(left) - visibleWidth(right));
217
+ return truncateToWidth(left + " ".repeat(pad) + right, width);
218
+ };
219
+ const footer = (width: number): string =>
220
+ truncateToWidth(theme.fg("dim", "↑↓ scroll · tab period · v group · q close"), width);
221
+ return {
222
+ render(width: number) {
223
+ const rows = tui.terminal.rows;
224
+ const rule = theme.fg("borderMuted", "─".repeat(Math.max(0, width)));
225
+ const lines: string[] = [title(width), rule];
226
+ if (!state.records) {
227
+ const barWidth = Math.max(10, Math.min(40, width - 30));
228
+ const filled = state.total ? Math.round((state.done / state.total) * barWidth) : 0;
229
+ lines.push(
230
+ truncateToWidth(
231
+ `${theme.fg("muted", "Scanning ")}${theme.fg("accent", "█".repeat(filled))}${theme.fg("borderMuted", "·".repeat(barWidth - filled))} ${state.done}/${state.total} files`,
232
+ width,
233
+ ),
234
+ );
235
+ lines.push(rule, footer(width));
236
+ return lines.slice(0, rows);
237
+ }
238
+ const since = periodStart(PERIODS[period].days);
239
+ const mode = GROUPS[group]!;
240
+ const summary = summarize(state.records, since);
241
+ lines.push(
242
+ `Cost ${formatCost(summary.stats.cost)} · Reqs ${formatTokens(summary.requests)} · Sessions ${formatTokens(summary.sessions)}`,
243
+ `In ${formatTokens(summary.stats.input)} · Out ${formatTokens(summary.stats.output)} · Cache ${formatTokens(summary.stats.cacheRead + summary.stats.cacheWrite)} · Hit ${hitPct(summary.stats)}`,
244
+ );
245
+ const spark = sparkline(state.records, PERIODS[period].days, width);
246
+ if (spark)
247
+ lines.push(
248
+ truncateToWidth(
249
+ `${theme.fg("dim", `${spark.first} `)}${theme.fg("accent", spark.bars)}${theme.fg("dim", ` ${spark.last}`)}`,
250
+ width,
251
+ ),
252
+ );
253
+ const { nameWidth, columns } = layout(width);
254
+ lines.push(
255
+ theme.fg(
256
+ "muted",
257
+ [
258
+ padWidth(fitLabel(NAME_HEADERS[mode], nameWidth), nameWidth),
259
+ ...columns.map((c) => padWidth(c.label, c.width)),
260
+ ]
261
+ .join(" ")
262
+ .trimEnd(),
263
+ ),
264
+ );
265
+ // Fixed top: title, rule, summary, sparkline, column header. Fixed bottom: totals, rule, footer.
266
+ const body = flatten(buildRows(state.records, since, mode)).map((row) => ({
267
+ ...row,
268
+ name: displayName(mode, row.name),
269
+ }));
270
+ rowCount = body.length;
271
+ viewHeight = Math.max(0, rows - lines.length - 3);
272
+ cursor = Math.min(cursor, Math.max(0, rowCount - 1));
273
+ top = Math.max(0, Math.min(top, rowCount - viewHeight));
274
+ if (cursor < top) top = cursor;
275
+ if (viewHeight > 0 && cursor >= top + viewHeight) top = cursor - viewHeight + 1;
276
+ const visible = body.slice(top, top + viewHeight);
277
+ if (rowCount === 0) lines.push(theme.fg("dim", " No usage in this period"));
278
+ for (const [i, row] of visible.entries()) {
279
+ let line = tableLine(
280
+ nameWidth,
281
+ columns,
282
+ row.name,
283
+ row.stats,
284
+ row.requests,
285
+ summary.stats.cost,
286
+ );
287
+ if (top + i === cursor) line = theme.bg("selectedBg", line);
288
+ else if (row.dim) line = theme.fg("dim", line);
289
+ lines.push(visibleWidth(line) > width ? truncateToWidth(line, width) : line);
290
+ }
291
+ lines.push(
292
+ theme.bold(
293
+ tableLine(
294
+ nameWidth,
295
+ columns,
296
+ "Total",
297
+ summary.stats,
298
+ summary.requests,
299
+ summary.stats.cost,
300
+ ),
301
+ ),
302
+ rule,
303
+ footer(width),
304
+ );
305
+ return lines.slice(0, rows);
306
+ },
307
+ invalidate() {},
308
+ handleInput(data: string) {
309
+ if (keys.matches(data, "tui.select.cancel") || data === "q") {
310
+ done(undefined);
311
+ return;
312
+ }
313
+ if (matchesKey(data, "tab") || matchesKey(data, "right"))
314
+ period = (period + 1) % PERIODS.length;
315
+ else if (matchesKey(data, "shift+tab") || matchesKey(data, "left"))
316
+ period = (period + PERIODS.length - 1) % PERIODS.length;
317
+ else if (data === "v") group = (group + 1) % GROUPS.length;
318
+ else if (keys.matches(data, "tui.select.up") || data === "k") cursor -= 1;
319
+ else if (keys.matches(data, "tui.select.down") || data === "j") cursor += 1;
320
+ else if (matchesKey(data, "pageUp")) cursor -= Math.max(1, viewHeight);
321
+ else if (matchesKey(data, "pageDown")) cursor += Math.max(1, viewHeight);
322
+ else if (matchesKey(data, "home") || data === "g") cursor = 0;
323
+ else if (matchesKey(data, "end") || matchesKey(data, "shift+g")) cursor = rowCount - 1;
324
+ else return;
325
+ cursor = Math.max(0, Math.min(rowCount - 1, cursor));
326
+ tui.requestRender();
327
+ },
328
+ };
329
+ }, screen);
330
+ },
331
+ });
332
+ }
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
1
  {
2
2
  "name": "@deathbeam/pi-usage",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.1",
4
+ "description": "Minimal extension for token usage and cost per provider, model and project.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/deathbeam/pi-packages.git",
10
+ "directory": "packages/pi-usage"
11
+ },
12
+ "keywords": [
13
+ "pi-package",
14
+ "pi-extension"
15
+ ],
16
+ "engines": {
17
+ "node": ">=22.19.0"
18
+ },
19
+ "files": [
20
+ "index.ts",
21
+ "usage.ts",
22
+ "README.md",
23
+ "LICENSE"
24
+ ],
25
+ "pi": {
26
+ "extensions": [
27
+ "./index.ts"
28
+ ]
29
+ },
30
+ "scripts": {
31
+ "test": "node check.mjs"
32
+ },
33
+ "peerDependencies": {
34
+ "@earendil-works/pi-coding-agent": "*",
35
+ "@earendil-works/pi-tui": "*"
36
+ }
37
+ }
package/usage.ts ADDED
@@ -0,0 +1,252 @@
1
+ /** Usage aggregation over Pi's persisted session JSONL files. */
2
+
3
+ import { createReadStream } from "node:fs";
4
+ import { readdir } from "node:fs/promises";
5
+ import { createInterface } from "node:readline";
6
+ import { join } from "node:path";
7
+
8
+ export type UsageRecord = {
9
+ provider: string;
10
+ model: string;
11
+ ts: number;
12
+ cost: number;
13
+ input: number;
14
+ output: number;
15
+ cacheRead: number;
16
+ cacheWrite: number;
17
+ /** cwd from the session header line; empty when the file has no header. */
18
+ cwd: string;
19
+ /** Session id from the session header line; empty when the file has no header. */
20
+ sessionId: string;
21
+ };
22
+
23
+ export type Stats = {
24
+ cost: number;
25
+ input: number;
26
+ output: number;
27
+ cacheRead: number;
28
+ cacheWrite: number;
29
+ };
30
+
31
+ export function emptyStats(): Stats {
32
+ return { cost: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
33
+ }
34
+
35
+ function num(value: unknown): number {
36
+ return typeof value === "number" && Number.isFinite(value) ? value : 0;
37
+ }
38
+
39
+ async function sessionFiles(dir: string, out: string[]): Promise<void> {
40
+ let entries;
41
+ try {
42
+ entries = await readdir(dir, { withFileTypes: true });
43
+ } catch {
44
+ return; // unreadable directory: nothing to count
45
+ }
46
+ for (const entry of entries) {
47
+ const path = join(dir, entry.name);
48
+ if (entry.isDirectory()) await sessionFiles(path, out);
49
+ else if (entry.name.endsWith(".jsonl")) out.push(path);
50
+ }
51
+ }
52
+
53
+ /**
54
+ * One record per assistant message that carries usage, from every session file under `dir`.
55
+ *
56
+ * Files are streamed line by line: the corpus is gigabytes, and reading whole files stalls the event
57
+ * loop and spikes RSS. The recursive scan includes `sessions/delegates`, where pi-delegate children
58
+ * write their own transcripts, so subagent usage is counted with full provider/model attribution and
59
+ * its own cwd. Parent sessions never embed the delegate child's usage (the delegate tool result
60
+ * carries only text), so there is nothing to double-count. toolResult usage from other tools is
61
+ * ignored for the same reason: those children also persist their own session files inside the scan.
62
+ * shortcut: usage reported by tools whose child sessions live outside this dir is not counted.
63
+ */
64
+ export async function collectUsage(
65
+ dir: string,
66
+ onProgress?: (done: number, total: number) => void,
67
+ ): Promise<UsageRecord[]> {
68
+ const files: string[] = [];
69
+ await sessionFiles(dir, files);
70
+ const records: UsageRecord[] = [];
71
+ for (const [done, file] of files.entries()) {
72
+ onProgress?.(done, files.length);
73
+ let cwd = "";
74
+ let sessionId = "";
75
+ try {
76
+ const lines = createInterface({ input: createReadStream(file, "utf8"), crlfDelay: Infinity });
77
+ for await (const line of lines) {
78
+ // Cheap prefilter: escaped JSON inside tool results never matches this literal.
79
+ if (!line.includes('"role":"assistant"')) {
80
+ // The session header (type:"session", cwd, id) is normally the first line.
81
+ if (sessionId === "" && line.includes('"type":"session"')) {
82
+ try {
83
+ const header = JSON.parse(line);
84
+ if (header?.type === "session") {
85
+ cwd = String(header.cwd ?? "");
86
+ sessionId = String(header.id ?? "");
87
+ }
88
+ } catch {
89
+ // malformed header line: keep scanning for a later one
90
+ }
91
+ }
92
+ continue;
93
+ }
94
+ let entry: any;
95
+ try {
96
+ entry = JSON.parse(line);
97
+ } catch {
98
+ continue;
99
+ }
100
+ const msg = entry?.message;
101
+ const usage = msg?.usage;
102
+ if (!usage || !msg.provider || !msg.model) continue;
103
+ const cost = typeof usage.cost === "number" ? usage.cost : num(usage.cost?.total);
104
+ records.push({
105
+ provider: String(msg.provider),
106
+ model: String(msg.model),
107
+ ts: num(msg.timestamp),
108
+ cost,
109
+ input: num(usage.input),
110
+ output: num(usage.output),
111
+ cacheRead: num(usage.cacheRead),
112
+ cacheWrite: num(usage.cacheWrite),
113
+ cwd,
114
+ sessionId,
115
+ });
116
+ }
117
+ } catch {
118
+ continue; // unreadable or truncated file: skip it, keep what other files gave
119
+ }
120
+ }
121
+ return records;
122
+ }
123
+
124
+ function addStats(stats: Stats, record: UsageRecord): void {
125
+ stats.cost += record.cost;
126
+ stats.input += record.input;
127
+ stats.output += record.output;
128
+ stats.cacheRead += record.cacheRead;
129
+ stats.cacheWrite += record.cacheWrite;
130
+ }
131
+
132
+ export type GroupMode = "provider" | "model" | "project";
133
+
134
+ export type GroupRow = {
135
+ name: string;
136
+ stats: Stats;
137
+ requests: number;
138
+ /** Nested model rows; only produced by provider grouping. */
139
+ children?: GroupRow[];
140
+ };
141
+
142
+ const tokens = (s: Stats): number => s.input + s.output + s.cacheRead + s.cacheWrite;
143
+
144
+ /** Cost descending, then total tokens (so free models still rank by usage). */
145
+ const byCost = (a: GroupRow, b: GroupRow): number => b.stats.cost - a.stats.cost || tokens(b.stats) - tokens(a.stats);
146
+
147
+ type Tally = { stats: Stats; requests: number; models?: Map<string, Tally>; providers?: Set<string> };
148
+
149
+ const newTally = (): Tally => ({ stats: emptyStats(), requests: 0 });
150
+
151
+ /**
152
+ * Aggregate records older than `sinceMs` into rows for one grouping mode.
153
+ * Provider rows nest their models as children; model rows append `(n)` when n providers share the
154
+ * model; project rows are keyed by the session cwd (delegates count toward their own cwd).
155
+ */
156
+ export function buildRows(records: UsageRecord[], sinceMs = 0, mode: GroupMode = "provider"): GroupRow[] {
157
+ const groups = new Map<string, Tally>();
158
+ for (const record of records) {
159
+ if (record.ts < sinceMs) continue;
160
+ const key = mode === "provider" ? record.provider : mode === "model" ? record.model : record.cwd;
161
+ let group = groups.get(key);
162
+ if (!group) {
163
+ group = newTally();
164
+ if (mode === "provider") group.models = new Map();
165
+ if (mode === "model") group.providers = new Set();
166
+ groups.set(key, group);
167
+ }
168
+ addStats(group.stats, record);
169
+ group.requests++;
170
+ if (mode === "model") group.providers!.add(record.provider);
171
+ if (mode === "provider") {
172
+ let model = group.models!.get(record.model);
173
+ if (!model) group.models!.set(record.model, (model = newTally()));
174
+ addStats(model.stats, record);
175
+ model.requests++;
176
+ }
177
+ }
178
+ const toRow = ([name, group]: [string, Tally]): GroupRow => ({
179
+ name: mode === "model" && group.providers!.size > 1 ? `${name} (${group.providers!.size})` : name,
180
+ stats: group.stats,
181
+ requests: group.requests,
182
+ children: group.models && [...group.models].map(toRow).sort(byCost),
183
+ });
184
+ return [...groups].map(toRow).sort(byCost);
185
+ }
186
+
187
+ export type Summary = {
188
+ stats: Stats;
189
+ requests: number;
190
+ /** Distinct session ids (files) seen in the window. */
191
+ sessions: number;
192
+ /** cacheRead / (input + cacheRead + cacheWrite); 0 without any tokens. */
193
+ hit: number;
194
+ };
195
+
196
+ /** Totals for the summary block: one pass over the window. */
197
+ export function summarize(records: UsageRecord[], sinceMs = 0): Summary {
198
+ const stats = emptyStats();
199
+ let requests = 0;
200
+ const sessions = new Set<string>();
201
+ for (const record of records) {
202
+ if (record.ts < sinceMs) continue;
203
+ addStats(stats, record);
204
+ requests++;
205
+ sessions.add(record.sessionId);
206
+ }
207
+ const cacheTotal = stats.input + stats.cacheRead + stats.cacheWrite;
208
+ return {
209
+ stats,
210
+ requests,
211
+ sessions: sessions.size,
212
+ hit: cacheTotal > 0 ? stats.cacheRead / cacheTotal : 0,
213
+ };
214
+ }
215
+
216
+ export type DailyCost = { label: string; cost: number };
217
+
218
+ /** Cost per local calendar day, oldest first, covering the `days` days ending today. */
219
+ export function dailyCosts(records: UsageRecord[], days: number, now = Date.now()): DailyCost[] {
220
+ const start = new Date(now);
221
+ start.setHours(0, 0, 0, 0);
222
+ // setDate walks calendar days, so DST shifts cannot misplace a bucket.
223
+ const buckets: DailyCost[] = [];
224
+ const index = new Map<number, number>();
225
+ const cursor = new Date(start);
226
+ for (let i = 0; i < days; i++) {
227
+ index.set(cursor.getTime(), days - 1 - i);
228
+ buckets.unshift({
229
+ label: `${String(cursor.getMonth() + 1).padStart(2, "0")}-${String(cursor.getDate()).padStart(2, "0")}`,
230
+ cost: 0,
231
+ });
232
+ cursor.setDate(cursor.getDate() - 1);
233
+ }
234
+ for (const record of records) {
235
+ const day = new Date(record.ts);
236
+ day.setHours(0, 0, 0, 0);
237
+ const at = index.get(day.getTime());
238
+ if (at !== undefined) buckets[at]!.cost += record.cost;
239
+ }
240
+ return buckets;
241
+ }
242
+
243
+ /** Sum `perBar` consecutive daily buckets into one bar, labeled by its first day. */
244
+ export function bucketCosts(days: DailyCost[], perBar: number): DailyCost[] {
245
+ if (perBar <= 1) return days;
246
+ const bars: DailyCost[] = [];
247
+ for (let i = 0; i < days.length; i += perBar) {
248
+ const group = days.slice(i, i + perBar);
249
+ bars.push({ label: group[0]!.label, cost: group.reduce((sum, d) => sum + d.cost, 0) });
250
+ }
251
+ return bars;
252
+ }