@deathbeam/pi-usage 0.0.3 → 0.0.5

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 (4) hide show
  1. package/README.md +17 -0
  2. package/index.ts +166 -122
  3. package/package.json +1 -1
  4. package/usage.ts +155 -30
package/README.md CHANGED
@@ -2,6 +2,23 @@
2
2
 
3
3
  Use the `/usage` command for a fullscreen dashboard of token usage and costs.
4
4
 
5
+ ## Keys
6
+
7
+ | Key | Action |
8
+ | --------------------- | -------------------------------------------- |
9
+ | Tab, Shift+Tab, ← / → | Cycle groups. Inside an open day, skip day. |
10
+ | `[` / `]` | Step the day when it is the innermost filter |
11
+ | Enter | Open the selected row |
12
+ | Esc | Go back, or close when at the top level |
13
+ | `q` | Close |
14
+ | ↑ / ↓, `j` / `k` | Move the cursor |
15
+ | Page Up / Page Down | Move by a page |
16
+ | `g` / `G` | Move to the first / last row |
17
+
18
+ Day rows include days without usage. Δ compares cost with the previous day. The sparkline shows the selected row over all history and is hidden when a day is open.
19
+
20
+ The summary compares the daily spend so far this week and month with last week and month. Weeks start on Monday in local time. `▲new` means the previous period had no spend.
21
+
5
22
  ## Installation
6
23
 
7
24
  ```sh
package/index.ts CHANGED
@@ -1,4 +1,4 @@
1
- /** /usage — fullscreen token usage and cost dashboard, grouped by provider, model, or project. */
1
+ /** /usage — fullscreen token usage and cost dashboard. */
2
2
 
3
3
  import { homedir } from "node:os";
4
4
  import { join } from "node:path";
@@ -7,36 +7,48 @@ import { getAgentDir } from "@earendil-works/pi-coding-agent";
7
7
  import { matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
8
8
  import {
9
9
  bucketCosts,
10
+ buildDailySeries,
10
11
  buildRows,
12
+ cacheView,
11
13
  collectUsage,
12
- dailyCosts,
14
+ comparison,
15
+ dayKey,
16
+ dayWindow,
17
+ matchesFilter,
18
+ percentChange,
19
+ seriesKey,
13
20
  summarize,
21
+ usageWindow,
22
+ type DailyCost,
14
23
  type GroupMode,
15
24
  type GroupRow,
16
25
  type Stats,
26
+ type UsageFilter,
17
27
  type UsageRecord,
18
28
  } from "./usage.ts";
19
29
 
20
- type Column = { label: string; width: number; cell: (stats: Stats, requests: number, totalCost: number) => string };
21
- type BodyRow = { name: string; stats: Stats; requests: number; dim: boolean };
22
-
23
- const PERIODS = [
24
- { label: "Today", days: 1 },
25
- { label: "7d", days: 7 },
26
- { label: "30d", days: 30 },
27
- { label: "All", days: Infinity },
28
- ] as const;
30
+ type Column = {
31
+ label: string;
32
+ width: number;
33
+ cell: (stats: Stats, requests: number, totalCost: number, row?: GroupRow) => string;
34
+ };
35
+ type BodyRow = GroupRow & { parent?: string };
36
+ type Frame = { filters: UsageFilter[]; group: number; cursor: number; top: number };
29
37
 
30
- const GROUPS = ["provider", "model", "project"] as const satisfies readonly GroupMode[];
31
- const GROUP_LABELS: Record<GroupMode, string> = { provider: "Provider", model: "Model", project: "Project" };
32
- const NAME_HEADERS: Record<GroupMode, string> = {
33
- provider: "Provider / Model",
38
+ const GROUPS = ["day", "provider", "model", "project"] as const satisfies readonly GroupMode[];
39
+ const GROUP_LABELS: Record<GroupMode, string> = {
40
+ day: "Day",
41
+ provider: "Provider",
34
42
  model: "Model",
35
43
  project: "Project",
36
44
  };
37
45
 
38
46
  const COLUMNS: Column[] = [
39
- { label: "Cost", width: 10, cell: (s) => formatCost(s.cost) },
47
+ {
48
+ label: "Cost",
49
+ width: 10,
50
+ cell: (s) => formatCost(s.cost),
51
+ },
40
52
  {
41
53
  label: "Share",
42
54
  width: 13,
@@ -58,7 +70,7 @@ const SPARK_BARS = "▁▂▃▄▅▆▇█";
58
70
  const MIN_NAME_WIDTH = 12;
59
71
 
60
72
  function formatCost(cost: number): string {
61
- if (cost === 0) return "-";
73
+ if (cost === 0) return "$0.00";
62
74
  if (cost < 0.01) return `$${cost.toFixed(4)}`;
63
75
  if (cost < 100) return `$${cost.toFixed(2)}`;
64
76
  return `$${Math.round(cost).toLocaleString("en-US")}`;
@@ -72,32 +84,25 @@ function formatTokens(count: number): string {
72
84
  return `${(count / 1_000_000_000).toFixed(1)}B`;
73
85
  }
74
86
 
75
- /** Start of the `days`-day window ending today; 0 for All. */
76
- function periodStart(days: number): number {
77
- if (days === Infinity) return 0;
78
- const start = new Date();
79
- start.setHours(0, 0, 0, 0);
80
- start.setDate(start.getDate() - (days - 1));
81
- return start.getTime();
82
- }
83
-
84
87
  function hitPct(stats: Stats): string {
85
88
  const total = stats.input + stats.cacheRead + stats.cacheWrite;
86
89
  return total > 0 ? `${Math.round((100 * stats.cacheRead) / total)}%` : "-";
87
90
  }
88
91
 
89
- /** Widths fit the worst case ($999,999 / 999.9B); the name column shrinks first, then Share, then Hit%. */
90
- function layout(width: number): { nameWidth: number; columns: Column[] } {
92
+ function layout(width: number, allColumns: Column[]): { nameWidth: number; columns: Column[] } {
91
93
  const used = (cols: Column[]) => cols.reduce((sum, c) => sum + c.width + 1, 0);
92
- let columns = COLUMNS;
93
- if (width - used(columns) < MIN_NAME_WIDTH) columns = columns.filter((c) => c.label !== "Share");
94
- if (width - used(columns) < MIN_NAME_WIDTH) columns = columns.filter((c) => c.label !== "Hit%");
94
+ let columns = allColumns;
95
+ for (const label of ["Share", "Hit%", "Cache", "Out", "In", "Reqs", "Δ"]) {
96
+ if (width - used(columns) >= MIN_NAME_WIDTH) break;
97
+ columns = columns.filter((c) => c.label !== label);
98
+ }
95
99
  return { nameWidth: Math.max(4, width - used(columns)), columns };
96
100
  }
97
101
 
98
102
  const padWidth = (s: string, w: number): string => s + " ".repeat(Math.max(0, w - visibleWidth(s)));
99
103
 
100
104
  function displayName(mode: GroupMode, name: string): string {
105
+ if (mode === "day") return `${name} ${new Date(`${name}T00:00`).toLocaleDateString("en-US", { weekday: "short" })}`;
101
106
  if (mode !== "project") return name;
102
107
  if (!name) return "(no cwd)";
103
108
  const home = homedir();
@@ -109,46 +114,23 @@ function fitLabel(name: string, nameWidth: number): string {
109
114
  return visibleWidth(name) > nameWidth ? truncateToWidth(name, nameWidth, "…") : name;
110
115
  }
111
116
 
112
- function tableLine(
113
- nameWidth: number,
114
- columns: Column[],
115
- name: string,
116
- stats: Stats,
117
- requests: number,
118
- totalCost: number,
119
- ): string {
120
- const label = fitLabel(name, nameWidth);
121
- return [padWidth(label, nameWidth), ...columns.map((c) => padWidth(c.cell(stats, requests, totalCost), c.width))]
117
+ function tableLine(nameWidth: number, columns: Column[], row: GroupRow, totalCost: number): string {
118
+ const label = fitLabel(row.name, nameWidth);
119
+ return [
120
+ padWidth(label, nameWidth),
121
+ ...columns.map((c) => padWidth(fitLabel(c.cell(row.stats, row.requests, totalCost, row), c.width), c.width)),
122
+ ]
122
123
  .join(" ")
123
124
  .trimEnd();
124
125
  }
125
126
 
126
- /** Daily-cost sparkline `MM-DD ▁▂▃ MM-DD`: the whole period, downsampled to fit `width`. */
127
- function sparkline(
128
- records: UsageRecord[],
129
- days: number,
130
- width: number,
131
- ): { first: string; bars: string; last: string } | undefined {
132
- if (days === 1) return undefined;
133
- let dayCount = days;
134
- if (days === Infinity) {
135
- let first = Infinity;
136
- for (const record of records) if (record.ts < first) first = record.ts;
137
- if (first === Infinity) return undefined;
138
- const firstDay = new Date(first);
139
- firstDay.setHours(0, 0, 0, 0);
140
- const today = new Date();
141
- today.setHours(0, 0, 0, 0);
142
- dayCount = Math.max(1, Math.round((today.getTime() - firstDay.getTime()) / 86_400_000) + 1);
143
- }
144
- const daily = dailyCosts(records, dayCount);
127
+ function sparkline(daily: DailyCost[], width: number): { first: string; bars: string; last: string } | undefined {
128
+ if (daily.length <= 1) return undefined;
145
129
  const first = daily[0]!.label;
146
130
  const last = daily[daily.length - 1]!.label;
147
- // Two MM-DD labels and two spaces around the bars leave width - 12 columns of bars.
148
- const bars = bucketCosts(daily, Math.ceil(dayCount / Math.max(1, width - 12)));
131
+ const bars = bucketCosts(daily, Math.ceil(daily.length / Math.max(1, width - 12)));
149
132
  let max = 0;
150
133
  for (const bar of bars) if (bar.cost > max) max = bar.cost;
151
- if (max <= 0) return undefined;
152
134
  return {
153
135
  first,
154
136
  bars: bars.map((d) => (d.cost <= 0 ? " " : SPARK_BARS[Math.max(1, Math.round((7 * d.cost) / max))])).join(""),
@@ -159,9 +141,8 @@ function sparkline(
159
141
  function flatten(rows: GroupRow[], mode: GroupMode): BodyRow[] {
160
142
  const body: BodyRow[] = [];
161
143
  for (const row of rows) {
162
- body.push({ name: displayName(mode, row.name), stats: row.stats, requests: row.requests, dim: false });
163
- for (const child of row.children ?? [])
164
- body.push({ name: ` ${child.name}`, stats: child.stats, requests: child.requests, dim: true });
144
+ body.push({ ...row, name: displayName(mode, row.name) });
145
+ for (const child of row.children ?? []) body.push({ ...child, name: ` ${child.name}`, parent: row.key });
165
146
  }
166
147
  return body;
167
148
  }
@@ -189,33 +170,69 @@ export default function (pi: ExtensionAPI) {
189
170
  overlayOptions: { width: "100%", maxHeight: "100%", row: 0, col: 0 },
190
171
  } as const;
191
172
  await ctx.ui.custom((tui, theme, keys, done) => {
192
- let period = 0;
193
173
  let group = 0;
194
174
  let cursor = 0;
195
175
  let top = 0;
196
176
  let rowCount = 0;
197
177
  let viewHeight = 1; // set on first render; 1 keeps page keys sane before it
178
+ let body: BodyRow[] = [];
179
+ const stack: Frame[] = [];
180
+ const filters = () => stack.flatMap((frame) => frame.filters);
181
+ const dayFilter = () => filters().findLast((f) => f.mode === "day");
182
+ const derive = (source: UsageRecord[]) => {
183
+ const active = filters();
184
+ const records = source.filter((record) =>
185
+ active.every((f) => f.mode === "day" || matchesFilter(record, f)),
186
+ );
187
+ const day = active.findLast((f) => f.mode === "day")?.key;
188
+ const window = usageWindow(records, day);
189
+ const mode = GROUPS[group]!;
190
+ const summary = summarize(records, window.since, window.until);
191
+ const body = flatten(buildRows(records, window.since, mode, window.until), mode);
192
+ const series = day ? undefined : buildDailySeries(records, window.since, window.until, mode);
193
+ return { mode, summary, body, series, compare: day ? undefined : comparison(records) };
194
+ };
195
+ const getView = cacheView(() => derive(state.records!));
198
196
  render = () => tui.requestRender();
199
197
  void loaded.then(render);
198
+ const colorDelta = (delta: number | undefined): string => {
199
+ if (delta === undefined) return "-";
200
+ if (delta === 0) return "0%";
201
+ const text = Number.isFinite(delta)
202
+ ? `${delta > 0 ? "▲" : "▼"}${Math.round(Math.abs(delta))}%`
203
+ : "▲new";
204
+ return theme.fg(delta > 0 ? "error" : "success", text);
205
+ };
206
+ const deltaColumn: Column = { label: "Δ", width: 9, cell: (_s, _r, _t, row) => colorDelta(row?.delta) };
200
207
  const title = (width: number): string => {
201
208
  const tab = (label: string, active: boolean) =>
202
209
  active ? theme.fg("accent", `[${label}]`) : theme.fg("muted", ` ${label} `);
203
- const periodTabs = PERIODS.map(({ label }, i) => tab(label, i === period)).join(" ");
204
- const groupTabs = GROUPS.map((g, i) => tab(GROUP_LABELS[g], i === group)).join(" ");
205
- const periodHint = theme.fg("dim", " (tab/←→)");
206
- const groupHint = theme.fg("dim", " (v)");
207
- let left = `${theme.fg("accent", theme.bold("Usage"))} ${periodTabs}${periodHint}`;
208
- let right = `${groupTabs}${groupHint}`;
209
- // Drop the key hints before the tabs, so the right-hand tabs survive truncation.
210
- if (visibleWidth(left) + 1 + visibleWidth(right) > width) {
211
- left = left.replace(periodHint, "");
212
- right = right.replace(groupHint, "");
213
- }
214
- const pad = Math.max(1, width - visibleWidth(left) - visibleWidth(right));
215
- return truncateToWidth(left + " ".repeat(pad) + right, width);
210
+ const left =
211
+ theme.fg("accent", theme.bold("Usage")) +
212
+ filters()
213
+ .map((f) => ` › ${displayName(f.mode, f.key)}`)
214
+ .join("");
215
+ const tabs = GROUPS.map((g, i) => (i === 0 && dayFilter() ? "" : tab(GROUP_LABELS[g], i === group)))
216
+ .filter(Boolean)
217
+ .join(" ");
218
+ const hint = theme.fg("dim", " (tab/←→)");
219
+ const right =
220
+ tabs + (visibleWidth(left) + visibleWidth(tabs) + visibleWidth(hint) + 1 <= width ? hint : "");
221
+ const leftWidth = Math.max(0, width - visibleWidth(right) - 1);
222
+ return truncateToWidth(
223
+ truncateToWidth(left, leftWidth, "…") +
224
+ " ".repeat(
225
+ Math.max(1, width - Math.min(visibleWidth(left), leftWidth) - visibleWidth(right)),
226
+ ) +
227
+ right,
228
+ width,
229
+ );
216
230
  };
217
231
  const footer = (width: number): string =>
218
- truncateToWidth(theme.fg("dim", "↑↓ scroll · tab period · v group · q close"), width);
232
+ truncateToWidth(
233
+ theme.fg("dim", "enter open · esc back · tab/←→ group · [ ] day · q close · ↑↓ scroll"),
234
+ width,
235
+ );
219
236
  return {
220
237
  render(width: number) {
221
238
  const rows = tui.terminal.rows;
@@ -233,14 +250,27 @@ export default function (pi: ExtensionAPI) {
233
250
  lines.push(rule, footer(width));
234
251
  return lines.slice(0, rows);
235
252
  }
236
- const since = periodStart(PERIODS[period].days);
237
- const mode = GROUPS[group]!;
238
- const summary = summarize(state.records, since);
253
+ const view = getView(GROUPS[group]!, filters());
254
+ const { mode, summary, series, compare } = view;
255
+ const first = compare
256
+ ? `Today ${formatCost(compare.today)} · This week ${formatCost(compare.week)}/day ${colorDelta(percentChange(compare.week, compare.lastWeek))} vs last week · This month ${formatCost(compare.month)}/day ${colorDelta(percentChange(compare.month, compare.lastMonth))} vs last month`
257
+ : `Cost ${formatCost(summary.stats.cost)}`;
239
258
  lines.push(
240
- `Cost ${formatCost(summary.stats.cost)} · Reqs ${formatTokens(summary.requests)} · Sessions ${formatTokens(summary.sessions)}`,
241
- `In ${formatTokens(summary.stats.input)} · Out ${formatTokens(summary.stats.output)} · Cache ${formatTokens(summary.stats.cacheRead + summary.stats.cacheWrite)} · Hit ${hitPct(summary.stats)}`,
259
+ truncateToWidth(first, width),
260
+ truncateToWidth(
261
+ `In ${formatTokens(summary.stats.input)} · Out ${formatTokens(summary.stats.output)} · Cache ${formatTokens(summary.stats.cacheRead + summary.stats.cacheWrite)} · Hit ${hitPct(summary.stats)} · Reqs ${formatTokens(summary.requests)} · Sessions ${formatTokens(summary.sessions)}`,
262
+ width,
263
+ ),
242
264
  );
243
- const spark = sparkline(state.records, PERIODS[period].days, width);
265
+ body = view.body;
266
+ rowCount = body.length;
267
+ cursor = Math.min(cursor, Math.max(0, rowCount - 1));
268
+ const selected = body[cursor];
269
+ const costs = selected && series?.rows.get(seriesKey(selected.key, selected.parent));
270
+ const daily = selected
271
+ ? series?.total.map((d, i) => ({ ...d, cost: costs?.get(i) ?? 0 }))
272
+ : series?.total;
273
+ const spark = daily && sparkline(daily, width);
244
274
  if (spark)
245
275
  lines.push(
246
276
  truncateToWidth(
@@ -248,12 +278,16 @@ export default function (pi: ExtensionAPI) {
248
278
  width,
249
279
  ),
250
280
  );
251
- const { nameWidth, columns } = layout(width);
281
+ const { nameWidth, columns } = layout(
282
+ width,
283
+ mode === "day" ? [COLUMNS[0]!, deltaColumn, ...COLUMNS.slice(1)] : COLUMNS,
284
+ );
285
+ const header = mode === "provider" ? "Provider / Model" : GROUP_LABELS[mode];
252
286
  lines.push(
253
287
  theme.fg(
254
288
  "muted",
255
289
  [
256
- padWidth(fitLabel(NAME_HEADERS[mode], nameWidth), nameWidth),
290
+ padWidth(fitLabel(header, nameWidth), nameWidth),
257
291
  ...columns.map((c) => padWidth(c.label, c.width)),
258
292
  ]
259
293
  .join(" ")
@@ -261,56 +295,66 @@ export default function (pi: ExtensionAPI) {
261
295
  ),
262
296
  );
263
297
  // Fixed top: title, rule, summary, sparkline, column header. Fixed bottom: totals, rule, footer.
264
- const body = flatten(buildRows(state.records, since, mode), mode);
265
- rowCount = body.length;
266
298
  viewHeight = Math.max(0, rows - lines.length - 3);
267
- cursor = Math.min(cursor, Math.max(0, rowCount - 1));
268
299
  top = Math.max(0, Math.min(top, rowCount - viewHeight));
269
300
  if (cursor < top) top = cursor;
270
301
  if (viewHeight > 0 && cursor >= top + viewHeight) top = cursor - viewHeight + 1;
271
302
  const visible = body.slice(top, top + viewHeight);
272
- if (rowCount === 0) lines.push(theme.fg("dim", " No usage in this period"));
303
+ if (rowCount === 0) lines.push(theme.fg("dim", " No usage"));
273
304
  for (const [i, row] of visible.entries()) {
274
- let line = tableLine(
275
- nameWidth,
276
- columns,
277
- row.name,
278
- row.stats,
279
- row.requests,
280
- summary.stats.cost,
281
- );
305
+ let line = tableLine(nameWidth, columns, row, summary.stats.cost);
282
306
  if (top + i === cursor) line = theme.bg("selectedBg", line);
283
- else if (row.dim) line = theme.fg("dim", line);
284
- lines.push(visibleWidth(line) > width ? truncateToWidth(line, width) : line);
307
+ else if (row.parent !== undefined) line = theme.fg("dim", line);
308
+ lines.push(line);
285
309
  }
310
+ const total = { key: "", name: "Total", stats: summary.stats, requests: summary.requests };
286
311
  lines.push(
287
- theme.bold(
288
- tableLine(
289
- nameWidth,
290
- columns,
291
- "Total",
292
- summary.stats,
293
- summary.requests,
294
- summary.stats.cost,
295
- ),
296
- ),
312
+ theme.bold(tableLine(nameWidth, columns, total, summary.stats.cost)),
297
313
  rule,
298
314
  footer(width),
299
315
  );
300
- return lines.slice(0, rows);
316
+ return lines
317
+ .slice(0, rows)
318
+ .map((line) => (visibleWidth(line) > width ? truncateToWidth(line, width) : line));
301
319
  },
302
320
  invalidate() {},
303
321
  handleInput(data: string) {
304
- if (keys.matches(data, "tui.select.cancel") || data === "q") {
322
+ if (data === "q") {
305
323
  done(undefined);
306
324
  return;
307
- }
308
- if (matchesKey(data, "tab") || matchesKey(data, "right"))
309
- period = (period + 1) % PERIODS.length;
310
- else if (matchesKey(data, "shift+tab") || matchesKey(data, "left"))
311
- period = (period + PERIODS.length - 1) % PERIODS.length;
312
- else if (data === "v") group = (group + 1) % GROUPS.length;
313
- else if (keys.matches(data, "tui.select.up") || data === "k") cursor -= 1;
325
+ } else if (keys.matches(data, "tui.select.cancel")) {
326
+ const frame = stack.pop();
327
+ if (!frame) {
328
+ done(undefined);
329
+ return;
330
+ }
331
+ ({ group, cursor, top } = frame);
332
+ tui.requestRender();
333
+ return;
334
+ } else if (keys.matches(data, "tui.select.confirm") && body[cursor]) {
335
+ const row = body[cursor]!;
336
+ const rowMode = row.parent === undefined ? GROUPS[group]! : "model";
337
+ const selected: UsageFilter[] =
338
+ row.parent === undefined ? [] : [{ mode: "provider", key: row.parent }];
339
+ selected.push({ mode: rowMode, key: row.key });
340
+ stack.push({ filters: selected, group, cursor, top });
341
+ group = rowMode === "day" ? 1 : 0;
342
+ cursor = top = 0;
343
+ } else if ((data === "[" || data === "]") && filters().at(-1)?.mode === "day") {
344
+ const filter = filters().at(-1)!;
345
+ const next = dayKey(dayWindow(filter.key, data === "]" ? 1 : -1).since);
346
+ if (next <= dayKey(Date.now())) filter.key = next;
347
+ } else if (
348
+ matchesKey(data, "tab") ||
349
+ matchesKey(data, "right") ||
350
+ matchesKey(data, "shift+tab") ||
351
+ matchesKey(data, "left")
352
+ ) {
353
+ const offset = matchesKey(data, "tab") || matchesKey(data, "right") ? 1 : -1;
354
+ do group = (group + offset + GROUPS.length) % GROUPS.length;
355
+ while (group === 0 && dayFilter());
356
+ cursor = top = 0;
357
+ } else if (keys.matches(data, "tui.select.up") || data === "k") cursor -= 1;
314
358
  else if (keys.matches(data, "tui.select.down") || data === "j") cursor += 1;
315
359
  else if (matchesKey(data, "pageUp")) cursor -= Math.max(1, viewHeight);
316
360
  else if (matchesKey(data, "pageDown")) cursor += Math.max(1, viewHeight);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deathbeam/pi-usage",
3
- "version": "0.0.3",
3
+ "version": "0.0.5",
4
4
  "description": "Minimal extension for token usage and cost per provider, model and project.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/usage.ts CHANGED
@@ -129,12 +129,106 @@ function addStats(stats: Stats, record: UsageRecord): void {
129
129
  stats.cacheWrite += record.cacheWrite;
130
130
  }
131
131
 
132
- export type GroupMode = "provider" | "model" | "project";
132
+ export type GroupMode = "day" | "provider" | "model" | "project";
133
+ export type UsageFilter = { mode: GroupMode; key: string };
134
+
135
+ export function cacheView<T>(derive: () => T) {
136
+ let cached: { key: string; value: T } | undefined;
137
+ return (mode: GroupMode, filters: UsageFilter[], now = Date.now()): T => {
138
+ const key = JSON.stringify([mode, filters, dayKey(now)]);
139
+ if (!cached || cached.key !== key) cached = { key, value: derive() };
140
+ return cached.value;
141
+ };
142
+ }
143
+
144
+ export function dayKey(ts: number): string {
145
+ const d = new Date(ts);
146
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
147
+ }
148
+
149
+ export function dayWindow(key: string, offset = 0): { since: number; until: number } {
150
+ const date = new Date(`${key}T00:00`);
151
+ date.setDate(date.getDate() + offset);
152
+ date.setHours(0, 0, 0, 0);
153
+ const since = date.getTime();
154
+ date.setDate(date.getDate() + 1);
155
+ // A skipped midnight can leave 01:00 on the next calendar day.
156
+ date.setHours(0, 0, 0, 0);
157
+ return { since, until: date.getTime() };
158
+ }
159
+
160
+ // UTC ordinals count local calendar days without DST changing their length.
161
+ export function windowDays(since: number, until: number): number {
162
+ if (since >= until) return 0;
163
+ const ordinal = (ts: number) => {
164
+ const d = new Date(ts);
165
+ return Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()) / 86_400_000;
166
+ };
167
+ return ordinal(until - 1) - ordinal(since) + 1;
168
+ }
169
+
170
+ export function percentChange(current: number, previous: number): number {
171
+ return previous === 0 ? (current === 0 ? 0 : Infinity) : ((current - previous) / previous) * 100;
172
+ }
173
+
174
+ function recordKey(record: UsageRecord, mode: GroupMode): string {
175
+ return mode === "day" ? dayKey(record.ts) : mode === "project" ? record.cwd : record[mode];
176
+ }
177
+
178
+ export function matchesFilter(record: UsageRecord, filter: UsageFilter): boolean {
179
+ return recordKey(record, filter.mode) === filter.key;
180
+ }
181
+
182
+ export function usageWindow(records: UsageRecord[], day?: string, now = Date.now()) {
183
+ if (day) return dayWindow(day);
184
+ const until = dayWindow(dayKey(now)).until;
185
+ let first = Infinity;
186
+ for (const record of records) if (record.ts < until) first = Math.min(first, record.ts);
187
+ return { since: first === Infinity ? until : dayWindow(dayKey(first)).since, until };
188
+ }
189
+
190
+ export function comparison(records: UsageRecord[], now = Date.now()) {
191
+ const { since: today, until } = dayWindow(dayKey(now));
192
+ const week = new Date(today);
193
+ week.setDate(week.getDate() - ((week.getDay() + 6) % 7));
194
+ week.setHours(0, 0, 0, 0);
195
+ const weekStart = week.getTime();
196
+ const lastWeek = dayWindow(dayKey(weekStart), -7).since;
197
+ const month = new Date(today);
198
+ month.setDate(1);
199
+ month.setHours(0, 0, 0, 0);
200
+ const monthStart = month.getTime();
201
+ month.setMonth(month.getMonth() - 1);
202
+ month.setHours(0, 0, 0, 0);
203
+ const lastMonth = month.getTime();
204
+ let todayCost = 0,
205
+ weekCost = 0,
206
+ lastWeekCost = 0,
207
+ monthCost = 0,
208
+ lastMonthCost = 0;
209
+ for (const record of records) {
210
+ if (record.ts >= until) continue;
211
+ if (record.ts >= today) todayCost += record.cost;
212
+ if (record.ts >= weekStart) weekCost += record.cost;
213
+ else if (record.ts >= lastWeek) lastWeekCost += record.cost;
214
+ if (record.ts >= monthStart) monthCost += record.cost;
215
+ else if (record.ts >= lastMonth) lastMonthCost += record.cost;
216
+ }
217
+ return {
218
+ today: todayCost,
219
+ week: weekCost / windowDays(weekStart, until),
220
+ lastWeek: lastWeekCost / 7,
221
+ month: monthCost / windowDays(monthStart, until),
222
+ lastMonth: lastMonthCost / windowDays(lastMonth, monthStart),
223
+ };
224
+ }
133
225
 
134
226
  export type GroupRow = {
227
+ key: string;
135
228
  name: string;
136
229
  stats: Stats;
137
230
  requests: number;
231
+ delta?: number;
138
232
  /** Nested model rows; only produced by provider grouping. */
139
233
  children?: GroupRow[];
140
234
  };
@@ -148,16 +242,18 @@ type Tally = { stats: Stats; requests: number; models?: Map<string, Tally>; prov
148
242
 
149
243
  const newTally = (): Tally => ({ stats: emptyStats(), requests: 0 });
150
244
 
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[] {
245
+ export function buildRows(
246
+ records: UsageRecord[],
247
+ sinceMs = 0,
248
+ mode: GroupMode = "provider",
249
+ untilMs = Infinity,
250
+ ): GroupRow[] {
251
+ if (mode === "day" && (!Number.isFinite(sinceMs) || !Number.isFinite(untilMs)))
252
+ throw new RangeError("Time grouping requires a finite window");
157
253
  const groups = new Map<string, Tally>();
158
254
  for (const record of records) {
159
- if (record.ts < sinceMs) continue;
160
- const key = mode === "provider" ? record.provider : mode === "model" ? record.model : record.cwd;
255
+ if (record.ts < sinceMs || record.ts >= untilMs) continue;
256
+ const key = recordKey(record, mode);
161
257
  let group = groups.get(key);
162
258
  if (!group) {
163
259
  group = newTally();
@@ -175,7 +271,24 @@ export function buildRows(records: UsageRecord[], sinceMs = 0, mode: GroupMode =
175
271
  model.requests++;
176
272
  }
177
273
  }
274
+ if (mode === "day") {
275
+ if (sinceMs < untilMs) {
276
+ let key = dayKey(sinceMs);
277
+ const last = dayKey(untilMs - 1);
278
+ while (key <= last) {
279
+ if (!groups.has(key)) groups.set(key, newTally());
280
+ key = dayKey(dayWindow(key).until);
281
+ }
282
+ }
283
+ const rows = [...groups]
284
+ .map(([key, group]): GroupRow => ({ key, name: key, stats: group.stats, requests: group.requests }))
285
+ .sort((a, b) => b.key.localeCompare(a.key));
286
+ for (let i = 0; i + 1 < rows.length; i++)
287
+ rows[i]!.delta = percentChange(rows[i]!.stats.cost, rows[i + 1]!.stats.cost);
288
+ return rows;
289
+ }
178
290
  const toRow = ([name, group]: [string, Tally]): GroupRow => ({
291
+ key: name,
179
292
  name: mode === "model" && group.providers!.size > 1 ? `${name} (${group.providers!.size})` : name,
180
293
  stats: group.stats,
181
294
  requests: group.requests,
@@ -193,13 +306,13 @@ export type Summary = {
193
306
  hit: number;
194
307
  };
195
308
 
196
- /** Totals for the summary block: one pass over the window. */
197
- export function summarize(records: UsageRecord[], sinceMs = 0): Summary {
309
+ /** Totals for the summary block: one pass over [sinceMs, untilMs). */
310
+ export function summarize(records: UsageRecord[], sinceMs = 0, untilMs = Infinity): Summary {
198
311
  const stats = emptyStats();
199
312
  let requests = 0;
200
313
  const sessions = new Set<string>();
201
314
  for (const record of records) {
202
- if (record.ts < sinceMs) continue;
315
+ if (record.ts < sinceMs || record.ts >= untilMs) continue;
203
316
  addStats(stats, record);
204
317
  requests++;
205
318
  sessions.add(record.sessionId);
@@ -215,28 +328,40 @@ export function summarize(records: UsageRecord[], sinceMs = 0): Summary {
215
328
 
216
329
  export type DailyCost = { label: string; cost: number };
217
330
 
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 buckets: DailyCost[] = [];
221
- const index = new Map<number, number>();
222
- const cursor = new Date(now);
223
- cursor.setHours(0, 0, 0, 0);
331
+ export const seriesKey = (key: string, parent?: string): string => JSON.stringify([key, parent ?? null]);
332
+
333
+ export function buildDailySeries(
334
+ records: UsageRecord[],
335
+ since: number,
336
+ until: number,
337
+ mode: GroupMode,
338
+ ): { total: DailyCost[]; rows: Map<string, Map<number, number>> } {
339
+ const days = windowDays(since, until);
340
+ const total: DailyCost[] = [];
341
+ const positions = new Map<string, number>();
342
+ let cursor = since;
224
343
  for (let i = 0; i < days; i++) {
225
- index.set(cursor.getTime(), days - 1 - i);
226
- buckets.unshift({
227
- label: `${String(cursor.getMonth() + 1).padStart(2, "0")}-${String(cursor.getDate()).padStart(2, "0")}`,
228
- cost: 0,
229
- });
230
- // setDate walks calendar days, so DST shifts cannot misplace a bucket.
231
- cursor.setDate(cursor.getDate() - 1);
344
+ const key = dayKey(cursor);
345
+ positions.set(key, i);
346
+ total.push({ label: key.slice(5), cost: 0 });
347
+ cursor = dayWindow(key).until;
232
348
  }
349
+ const costs = new Map<string, Map<number, number>>();
350
+ const add = (key: string, index: number, cost: number) => {
351
+ let values = costs.get(key);
352
+ if (!values) costs.set(key, (values = new Map()));
353
+ values.set(index, (values.get(index) ?? 0) + cost);
354
+ };
233
355
  for (const record of records) {
234
- const day = new Date(record.ts);
235
- day.setHours(0, 0, 0, 0);
236
- const at = index.get(day.getTime());
237
- if (at !== undefined) buckets[at]!.cost += record.cost;
356
+ if (record.ts < since || record.ts >= until) continue;
357
+ const index = positions.get(dayKey(record.ts));
358
+ if (index === undefined) continue;
359
+ total[index]!.cost += record.cost;
360
+ const key = recordKey(record, mode);
361
+ add(seriesKey(key), index, record.cost);
362
+ if (mode === "provider") add(seriesKey(record.model, record.provider), index, record.cost);
238
363
  }
239
- return buckets;
364
+ return { total, rows: costs };
240
365
  }
241
366
 
242
367
  /** Sum `perBar` consecutive daily buckets into one bar, labeled by its first day. */