@deathbeam/pi-usage 0.0.3 → 0.0.4

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 +20 -0
  2. package/index.ts +190 -114
  3. package/package.json +1 -1
  4. package/usage.ts +207 -30
package/README.md CHANGED
@@ -2,6 +2,26 @@
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 periods |
10
+ | ← / → | Cycle periods, or step the last filter if it is a time bucket |
11
+ | `v` | Cycle provider, model, project, day, week, and month groups |
12
+ | Enter | Open the selected row |
13
+ | Esc | Go back, or close when at the top level |
14
+ | `q` | Close |
15
+ | ↑ / ↓, `j` / `k` | Move the cursor |
16
+ | Page Up / Page Down | Move by a page |
17
+ | `g` / `G` | Move to the first / last row |
18
+
19
+ Switching periods removes time filters and keeps provider, model, and project filters. The sparkline shows daily costs for the selected row.
20
+
21
+ Weeks start on Monday in local time. Time rows include days without usage. `/day` uses the days in the visible window, including today. Δ compares that pace with the next older row. A rise from zero is shown as `▲new`.
22
+
23
+ The summary compares the current window with the same number of calendar days immediately before it. All has no comparison unless a time bucket is open.
24
+
5
25
  ## Installation
6
26
 
7
27
  ```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,18 +7,36 @@ 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,
13
+ clearTimeFilters,
11
14
  collectUsage,
12
- dailyCosts,
15
+ dayKey,
16
+ isTimeFilter,
17
+ isTimeMode,
18
+ matchesFilter,
19
+ percentChange,
20
+ previousSummary,
21
+ seriesKey,
22
+ stepFilter,
13
23
  summarize,
24
+ usageWindow,
25
+ type DailyCost,
14
26
  type GroupMode,
15
27
  type GroupRow,
16
28
  type Stats,
29
+ type UsageFilter,
17
30
  type UsageRecord,
18
31
  } from "./usage.ts";
19
32
 
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 };
33
+ type Column = {
34
+ label: string;
35
+ width: number;
36
+ cell: (stats: Stats, requests: number, totalCost: number, row?: GroupRow) => string;
37
+ };
38
+ type BodyRow = GroupRow & { parent?: string };
39
+ type Frame = { filters: UsageFilter[]; group: number; cursor: number; top: number };
22
40
 
23
41
  const PERIODS = [
24
42
  { label: "Today", days: 1 },
@@ -27,16 +45,22 @@ const PERIODS = [
27
45
  { label: "All", days: Infinity },
28
46
  ] as const;
29
47
 
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",
48
+ const GROUPS = ["provider", "model", "project", "day", "week", "month"] as const satisfies readonly GroupMode[];
49
+ const GROUP_LABELS: Record<GroupMode, string> = {
50
+ provider: "Provider",
34
51
  model: "Model",
35
52
  project: "Project",
53
+ day: "Day",
54
+ week: "Week",
55
+ month: "Month",
36
56
  };
37
57
 
38
58
  const COLUMNS: Column[] = [
39
- { label: "Cost", width: 10, cell: (s) => formatCost(s.cost) },
59
+ {
60
+ label: "Cost",
61
+ width: 10,
62
+ cell: (s, _r, _t, row) => formatCost(s.cost, row?.perDay !== undefined),
63
+ },
40
64
  {
41
65
  label: "Share",
42
66
  width: 13,
@@ -57,8 +81,8 @@ const COLUMNS: Column[] = [
57
81
  const SPARK_BARS = "▁▂▃▄▅▆▇█";
58
82
  const MIN_NAME_WIDTH = 12;
59
83
 
60
- function formatCost(cost: number): string {
61
- if (cost === 0) return "-";
84
+ function formatCost(cost: number, showZero = false): string {
85
+ if (cost === 0) return showZero ? "$0.00" : "-";
62
86
  if (cost < 0.01) return `$${cost.toFixed(4)}`;
63
87
  if (cost < 100) return `$${cost.toFixed(2)}`;
64
88
  return `$${Math.round(cost).toLocaleString("en-US")}`;
@@ -72,32 +96,28 @@ function formatTokens(count: number): string {
72
96
  return `${(count / 1_000_000_000).toFixed(1)}B`;
73
97
  }
74
98
 
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
99
  function hitPct(stats: Stats): string {
85
100
  const total = stats.input + stats.cacheRead + stats.cacheWrite;
86
101
  return total > 0 ? `${Math.round((100 * stats.cacheRead) / total)}%` : "-";
87
102
  }
88
103
 
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[] } {
104
+ function layout(width: number, allColumns: Column[]): { nameWidth: number; columns: Column[] } {
91
105
  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%");
106
+ let columns = allColumns;
107
+ for (const label of ["Share", "Hit%", "Cache", "Out", "In", "Reqs", "Δ", "/day"]) {
108
+ if (width - used(columns) >= MIN_NAME_WIDTH) break;
109
+ columns = columns.filter((c) => c.label !== label);
110
+ }
95
111
  return { nameWidth: Math.max(4, width - used(columns)), columns };
96
112
  }
97
113
 
98
114
  const padWidth = (s: string, w: number): string => s + " ".repeat(Math.max(0, w - visibleWidth(s)));
99
115
 
100
116
  function displayName(mode: GroupMode, name: string): string {
117
+ if (mode === "day") return `${name} ${new Date(`${name}T00:00`).toLocaleDateString("en-US", { weekday: "short" })}`;
118
+ if (mode === "week") return `${name} wk`;
119
+ if (mode === "month")
120
+ return `${name} ${new Date(`${name}-01T00:00`).toLocaleDateString("en-US", { month: "short" })}`;
101
121
  if (mode !== "project") return name;
102
122
  if (!name) return "(no cwd)";
103
123
  const home = homedir();
@@ -109,46 +129,23 @@ function fitLabel(name: string, nameWidth: number): string {
109
129
  return visibleWidth(name) > nameWidth ? truncateToWidth(name, nameWidth, "…") : name;
110
130
  }
111
131
 
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))]
132
+ function tableLine(nameWidth: number, columns: Column[], row: GroupRow, totalCost: number): string {
133
+ const label = fitLabel(row.name, nameWidth);
134
+ return [
135
+ padWidth(label, nameWidth),
136
+ ...columns.map((c) => padWidth(fitLabel(c.cell(row.stats, row.requests, totalCost, row), c.width), c.width)),
137
+ ]
122
138
  .join(" ")
123
139
  .trimEnd();
124
140
  }
125
141
 
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);
142
+ function sparkline(daily: DailyCost[], width: number): { first: string; bars: string; last: string } | undefined {
143
+ if (daily.length <= 1) return undefined;
145
144
  const first = daily[0]!.label;
146
145
  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)));
146
+ const bars = bucketCosts(daily, Math.ceil(daily.length / Math.max(1, width - 12)));
149
147
  let max = 0;
150
148
  for (const bar of bars) if (bar.cost > max) max = bar.cost;
151
- if (max <= 0) return undefined;
152
149
  return {
153
150
  first,
154
151
  bars: bars.map((d) => (d.cost <= 0 ? " " : SPARK_BARS[Math.max(1, Math.round((7 * d.cost) / max))])).join(""),
@@ -159,9 +156,8 @@ function sparkline(
159
156
  function flatten(rows: GroupRow[], mode: GroupMode): BodyRow[] {
160
157
  const body: BodyRow[] = [];
161
158
  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 });
159
+ body.push({ ...row, name: displayName(mode, row.name) });
160
+ for (const child of row.children ?? []) body.push({ ...child, name: ` ${child.name}`, parent: row.key });
165
161
  }
166
162
  return body;
167
163
  }
@@ -195,27 +191,77 @@ export default function (pi: ExtensionAPI) {
195
191
  let top = 0;
196
192
  let rowCount = 0;
197
193
  let viewHeight = 1; // set on first render; 1 keeps page keys sane before it
194
+ let body: BodyRow[] = [];
195
+ const stack: Frame[] = [];
196
+ const filters = () => stack.flatMap((frame) => frame.filters);
197
+ const timeIsInnermost = () => isTimeFilter(filters().at(-1));
198
+ const derive = (source: UsageRecord[]) => {
199
+ const active = filters();
200
+ const records = source.filter((record) =>
201
+ active.every((f) => isTimeMode(f.mode) || matchesFilter(record, f)),
202
+ );
203
+ const window = usageWindow(records, PERIODS[period].days, active);
204
+ const mode = GROUPS[group]!;
205
+ const summary = summarize(records, window.since, window.until);
206
+ const compare =
207
+ window.days > 0 &&
208
+ (active.some((f) => isTimeMode(f.mode)) || PERIODS[period].days !== Infinity);
209
+ const previous = compare ? previousSummary(records, window.since, window.days) : undefined;
210
+ const body = flatten(buildRows(records, window.since, mode, window.until), mode);
211
+ const series = buildDailySeries(records, window.since, window.until, mode, body);
212
+ return { records, window, mode, summary, previous, body, series };
213
+ };
214
+ const getView = cacheView(() => derive(state.records!));
215
+ const changePeriod = (offset: number) => {
216
+ period = (period + offset + PERIODS.length) % PERIODS.length;
217
+ clearTimeFilters(stack);
218
+ cursor = top = 0;
219
+ };
198
220
  render = () => tui.requestRender();
199
221
  void loaded.then(render);
222
+ const colorDelta = (delta: number | undefined): string => {
223
+ if (delta === undefined) return "-";
224
+ if (delta === 0) return "0%";
225
+ const text = Number.isFinite(delta)
226
+ ? `${delta > 0 ? "▲" : "▼"}${Math.round(Math.abs(delta))}%`
227
+ : "▲new";
228
+ return theme.fg(delta > 0 ? "error" : "success", text);
229
+ };
230
+ const timeColumns: Column[] = [
231
+ {
232
+ label: "/day",
233
+ width: 10,
234
+ cell: (_s, _r, _t, row) => (row?.perDay === undefined ? "-" : formatCost(row.perDay, true)),
235
+ },
236
+ { label: "Δ", width: 9, cell: (_s, _r, _t, row) => colorDelta(row?.delta) },
237
+ ];
200
238
  const title = (width: number): string => {
201
239
  const tab = (label: string, active: boolean) =>
202
240
  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);
241
+ const left = stack.length
242
+ ? theme.fg("accent", theme.bold("Usage")) +
243
+ " › " +
244
+ [PERIODS[period].label, ...filters().map((f) => displayName(f.mode, f.key))].join(" › ")
245
+ : `${theme.fg("accent", theme.bold("Usage"))} ${PERIODS.map(({ label }, i) => tab(label, i === period)).join(" ")}`;
246
+ const right = GROUPS.map((g, i) => tab(GROUP_LABELS[g], i === group)).join(" ");
247
+ const leftWidth = Math.max(0, width - visibleWidth(right) - 1);
248
+ return truncateToWidth(
249
+ truncateToWidth(left, leftWidth, "…") +
250
+ " ".repeat(
251
+ Math.max(1, width - Math.min(visibleWidth(left), leftWidth) - visibleWidth(right)),
252
+ ) +
253
+ right,
254
+ width,
255
+ );
216
256
  };
217
257
  const footer = (width: number): string =>
218
- truncateToWidth(theme.fg("dim", "↑↓ scroll · tab period · v group · q close"), width);
258
+ truncateToWidth(
259
+ theme.fg(
260
+ "dim",
261
+ `enter open · esc back · v group · tab period · ←→ ${timeIsInnermost() ? "bucket" : "period"} · q close · ↑↓ scroll`,
262
+ ),
263
+ width,
264
+ );
219
265
  return {
220
266
  render(width: number) {
221
267
  const rows = tui.terminal.rows;
@@ -233,14 +279,33 @@ export default function (pi: ExtensionAPI) {
233
279
  lines.push(rule, footer(width));
234
280
  return lines.slice(0, rows);
235
281
  }
236
- const since = periodStart(PERIODS[period].days);
237
- const mode = GROUPS[group]!;
238
- const summary = summarize(state.records, since);
282
+ const view = getView(period, GROUPS[group]!, filters());
283
+ const { window, mode, summary, previous, series } = view;
284
+ const label =
285
+ window.days === 1 && dayKey(window.since) === dayKey(Date.now())
286
+ ? "yesterday"
287
+ : `prev ${window.days}d`;
288
+ const trend = previous
289
+ ? ` ${colorDelta(percentChange(summary.stats.cost, previous.stats.cost))} vs ${label}`
290
+ : "";
239
291
  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)}`,
292
+ truncateToWidth(
293
+ `Cost ${formatCost(summary.stats.cost)}${trend} · ${formatCost(window.days ? summary.stats.cost / window.days : 0)}/day · Reqs ${formatTokens(summary.requests)} · Sessions ${formatTokens(summary.sessions)}`,
294
+ width,
295
+ ),
296
+ truncateToWidth(
297
+ `In ${formatTokens(summary.stats.input)} · Out ${formatTokens(summary.stats.output)} · Cache ${formatTokens(summary.stats.cacheRead + summary.stats.cacheWrite)} · Hit ${hitPct(summary.stats)}`,
298
+ width,
299
+ ),
242
300
  );
243
- const spark = sparkline(state.records, PERIODS[period].days, width);
301
+ body = view.body;
302
+ rowCount = body.length;
303
+ cursor = Math.min(cursor, Math.max(0, rowCount - 1));
304
+ const selected = body[cursor];
305
+ const daily = selected
306
+ ? (series.rows.get(seriesKey(selected.key, selected.parent)) ?? series.total)
307
+ : series.total;
308
+ const spark = sparkline(daily, width);
244
309
  if (spark)
245
310
  lines.push(
246
311
  truncateToWidth(
@@ -248,12 +313,16 @@ export default function (pi: ExtensionAPI) {
248
313
  width,
249
314
  ),
250
315
  );
251
- const { nameWidth, columns } = layout(width);
316
+ const { nameWidth, columns } = layout(
317
+ width,
318
+ isTimeMode(mode) ? [COLUMNS[0]!, ...timeColumns, ...COLUMNS.slice(1)] : COLUMNS,
319
+ );
320
+ const header = mode === "provider" ? "Provider / Model" : GROUP_LABELS[mode];
252
321
  lines.push(
253
322
  theme.fg(
254
323
  "muted",
255
324
  [
256
- padWidth(fitLabel(NAME_HEADERS[mode], nameWidth), nameWidth),
325
+ padWidth(fitLabel(header, nameWidth), nameWidth),
257
326
  ...columns.map((c) => padWidth(c.label, c.width)),
258
327
  ]
259
328
  .join(" ")
@@ -261,56 +330,63 @@ export default function (pi: ExtensionAPI) {
261
330
  ),
262
331
  );
263
332
  // 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
333
  viewHeight = Math.max(0, rows - lines.length - 3);
267
- cursor = Math.min(cursor, Math.max(0, rowCount - 1));
268
334
  top = Math.max(0, Math.min(top, rowCount - viewHeight));
269
335
  if (cursor < top) top = cursor;
270
336
  if (viewHeight > 0 && cursor >= top + viewHeight) top = cursor - viewHeight + 1;
271
337
  const visible = body.slice(top, top + viewHeight);
272
338
  if (rowCount === 0) lines.push(theme.fg("dim", " No usage in this period"));
273
339
  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
- );
340
+ let line = tableLine(nameWidth, columns, row, summary.stats.cost);
282
341
  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);
342
+ else if (row.parent !== undefined) line = theme.fg("dim", line);
343
+ lines.push(line);
285
344
  }
345
+ const total = { key: "", name: "Total", stats: summary.stats, requests: summary.requests };
286
346
  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
- ),
347
+ theme.bold(tableLine(nameWidth, columns, total, summary.stats.cost)),
297
348
  rule,
298
349
  footer(width),
299
350
  );
300
- return lines.slice(0, rows);
351
+ return lines
352
+ .slice(0, rows)
353
+ .map((line) => (visibleWidth(line) > width ? truncateToWidth(line, width) : line));
301
354
  },
302
355
  invalidate() {},
303
356
  handleInput(data: string) {
304
- if (keys.matches(data, "tui.select.cancel") || data === "q") {
357
+ if (data === "q") {
305
358
  done(undefined);
306
359
  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;
360
+ } else if (keys.matches(data, "tui.select.cancel")) {
361
+ const frame = stack.pop();
362
+ if (!frame) {
363
+ done(undefined);
364
+ return;
365
+ }
366
+ ({ group, cursor, top } = frame);
367
+ tui.requestRender();
368
+ return;
369
+ } else if (keys.matches(data, "tui.select.confirm") && body[cursor]) {
370
+ const row = body[cursor]!;
371
+ const rowMode = row.parent === undefined ? GROUPS[group]! : "model";
372
+ const selected: UsageFilter[] =
373
+ row.parent === undefined ? [] : [{ mode: "provider", key: row.parent }];
374
+ selected.push({ mode: rowMode, key: row.key });
375
+ stack.push({ filters: selected, group, cursor, top });
376
+ group = isTimeMode(rowMode) ? 0 : GROUPS.indexOf("day");
377
+ cursor = top = 0;
378
+ } else if ((matchesKey(data, "right") || matchesKey(data, "left")) && timeIsInnermost()) {
379
+ const active = filters();
380
+ const next = stepFilter(active, matchesKey(data, "right") ? 1 : -1);
381
+ if (next !== undefined) active.at(-1)!.key = next;
382
+ } else if (matchesKey(data, "tab") || matchesKey(data, "right")) {
383
+ changePeriod(1);
384
+ } else if (matchesKey(data, "shift+tab") || matchesKey(data, "left")) {
385
+ changePeriod(-1);
386
+ } else if (data === "v") {
387
+ group = (group + 1) % GROUPS.length;
388
+ cursor = top = 0;
389
+ } else if (keys.matches(data, "tui.select.up") || data === "k") cursor -= 1;
314
390
  else if (keys.matches(data, "tui.select.down") || data === "j") cursor += 1;
315
391
  else if (matchesKey(data, "pageUp")) cursor -= Math.max(1, viewHeight);
316
392
  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.4",
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,135 @@ 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
+ type TimeMode = "day" | "week" | "month";
133
+ export type GroupMode = "provider" | "model" | "project" | TimeMode;
134
+ export type UsageFilter = { mode: GroupMode; key: string };
135
+
136
+ export const isTimeMode = (mode: GroupMode): mode is TimeMode => mode === "day" || mode === "week" || mode === "month";
137
+
138
+ export function isTimeFilter(filter: UsageFilter | undefined): filter is UsageFilter & { mode: TimeMode } {
139
+ return filter !== undefined && isTimeMode(filter.mode);
140
+ }
141
+
142
+ export function clearTimeFilters(stack: { filters: UsageFilter[] }[]): void {
143
+ for (let i = stack.length - 1; i >= 0; i--) {
144
+ stack[i]!.filters = stack[i]!.filters.filter((filter) => !isTimeMode(filter.mode));
145
+ if (!stack[i]!.filters.length) stack.splice(i, 1);
146
+ }
147
+ }
148
+
149
+ export function cacheView<T>(derive: () => T) {
150
+ let cached: { key: string; value: T } | undefined;
151
+ return (period: number, mode: GroupMode, filters: UsageFilter[], now = Date.now()): T => {
152
+ const key = JSON.stringify([period, mode, filters, dayKey(now)]);
153
+ if (!cached || cached.key !== key) cached = { key, value: derive() };
154
+ return cached.value;
155
+ };
156
+ }
157
+
158
+ export function dayKey(ts: number): string {
159
+ const d = new Date(ts);
160
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
161
+ }
162
+
163
+ function bucketStart(ts: number, mode: TimeMode): number {
164
+ const d = new Date(ts);
165
+ d.setHours(0, 0, 0, 0);
166
+ if (mode === "week") d.setDate(d.getDate() - ((d.getDay() + 6) % 7));
167
+ if (mode === "month") d.setDate(1);
168
+ d.setHours(0, 0, 0, 0);
169
+ return d.getTime();
170
+ }
171
+
172
+ export function bucketKey(ts: number, mode: TimeMode): string {
173
+ const key = dayKey(bucketStart(ts, mode));
174
+ return mode === "month" ? key.slice(0, 7) : key;
175
+ }
176
+
177
+ export function bucketWindow(key: string, mode: TimeMode, offset = 0): { since: number; until: number } {
178
+ const date = new Date(`${mode === "month" ? key + "-01" : key}T00:00`);
179
+ const shift = (n: number) => {
180
+ if (mode === "month") date.setMonth(date.getMonth() + n);
181
+ else date.setDate(date.getDate() + n * (mode === "week" ? 7 : 1));
182
+ // A skipped midnight can leave 01:00 on the next calendar day.
183
+ date.setHours(0, 0, 0, 0);
184
+ };
185
+ shift(offset);
186
+ const since = date.getTime();
187
+ shift(1);
188
+ return { since, until: date.getTime() };
189
+ }
190
+
191
+ export function stepFilter(filters: UsageFilter[], offset: number, now = Date.now()): string | undefined {
192
+ const last = filters.at(-1);
193
+ if (!isTimeFilter(last)) return undefined;
194
+ let { since, until } = bucketWindow(last.key, last.mode, offset);
195
+ const key = bucketKey(since, last.mode);
196
+ if (key > bucketKey(now, last.mode)) return undefined;
197
+ for (const outer of filters.slice(0, -1)) {
198
+ if (!isTimeMode(outer.mode)) continue;
199
+ const window = bucketWindow(outer.key, outer.mode);
200
+ since = Math.max(since, window.since);
201
+ until = Math.min(until, window.until);
202
+ }
203
+ return since < until ? key : undefined;
204
+ }
205
+
206
+ // UTC ordinals count local calendar days without DST changing their length.
207
+ export function windowDays(since: number, until: number): number {
208
+ if (since >= until) return 0;
209
+ const ordinal = (ts: number) => {
210
+ const d = new Date(ts);
211
+ return Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()) / 86_400_000;
212
+ };
213
+ return ordinal(until - 1) - ordinal(since) + 1;
214
+ }
215
+
216
+ export function percentChange(current: number, previous: number): number {
217
+ return previous === 0 ? (current === 0 ? 0 : Infinity) : ((current - previous) / previous) * 100;
218
+ }
219
+
220
+ function recordKey(record: UsageRecord, mode: GroupMode): string {
221
+ return isTimeMode(mode) ? bucketKey(record.ts, mode) : mode === "project" ? record.cwd : record[mode];
222
+ }
223
+
224
+ export function matchesFilter(record: UsageRecord, filter: UsageFilter): boolean {
225
+ return recordKey(record, filter.mode) === filter.key;
226
+ }
227
+
228
+ export function usageWindow(records: UsageRecord[], days: number, filters: UsageFilter[], now = Date.now()) {
229
+ const { since: today, until: end } = bucketWindow(dayKey(now), "day");
230
+ const timeFilters = filters.filter((f) => isTimeMode(f.mode));
231
+ let since = today;
232
+ let until = end;
233
+ if (timeFilters.length) {
234
+ since = 0;
235
+ for (const filter of timeFilters) {
236
+ const window = bucketWindow(filter.key, filter.mode as TimeMode);
237
+ since = Math.max(since, window.since);
238
+ until = Math.min(until, window.until);
239
+ }
240
+ } else if (days === Infinity) {
241
+ let first = Infinity;
242
+ for (const record of records) if (record.ts < end) first = Math.min(first, record.ts);
243
+ since = first === Infinity ? end : bucketWindow(dayKey(first), "day").since;
244
+ } else {
245
+ since = bucketWindow(dayKey(now), "day", 1 - days).since;
246
+ }
247
+ return { since, until, days: windowDays(since, until) };
248
+ }
249
+
250
+ export function previousSummary(records: UsageRecord[], since: number, days: number): Summary {
251
+ return summarize(records, bucketWindow(dayKey(since), "day", -days).since, since);
252
+ }
133
253
 
134
254
  export type GroupRow = {
255
+ key: string;
135
256
  name: string;
136
257
  stats: Stats;
137
258
  requests: number;
259
+ perDay?: number;
260
+ delta?: number;
138
261
  /** Nested model rows; only produced by provider grouping. */
139
262
  children?: GroupRow[];
140
263
  };
@@ -148,16 +271,18 @@ type Tally = { stats: Stats; requests: number; models?: Map<string, Tally>; prov
148
271
 
149
272
  const newTally = (): Tally => ({ stats: emptyStats(), requests: 0 });
150
273
 
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[] {
274
+ export function buildRows(
275
+ records: UsageRecord[],
276
+ sinceMs = 0,
277
+ mode: GroupMode = "provider",
278
+ untilMs = Infinity,
279
+ ): GroupRow[] {
280
+ if (isTimeMode(mode) && (!Number.isFinite(sinceMs) || !Number.isFinite(untilMs)))
281
+ throw new RangeError("Time grouping requires a finite window");
157
282
  const groups = new Map<string, Tally>();
158
283
  for (const record of records) {
159
- if (record.ts < sinceMs) continue;
160
- const key = mode === "provider" ? record.provider : mode === "model" ? record.model : record.cwd;
284
+ if (record.ts < sinceMs || record.ts >= untilMs) continue;
285
+ const key = recordKey(record, mode);
161
286
  let group = groups.get(key);
162
287
  if (!group) {
163
288
  group = newTally();
@@ -175,7 +300,34 @@ export function buildRows(records: UsageRecord[], sinceMs = 0, mode: GroupMode =
175
300
  model.requests++;
176
301
  }
177
302
  }
303
+ if (isTimeMode(mode)) {
304
+ if (sinceMs < untilMs) {
305
+ let key = bucketKey(sinceMs, mode);
306
+ const last = bucketKey(untilMs - 1, mode);
307
+ while (key <= last) {
308
+ if (!groups.has(key)) groups.set(key, newTally());
309
+ key = bucketKey(bucketWindow(key, mode).until, mode);
310
+ }
311
+ }
312
+ const rows = [...groups]
313
+ .map(([key, group]): GroupRow => {
314
+ const window = bucketWindow(key, mode);
315
+ const days = windowDays(Math.max(sinceMs, window.since), Math.min(untilMs, window.until));
316
+ return {
317
+ key,
318
+ name: key,
319
+ stats: group.stats,
320
+ requests: group.requests,
321
+ perDay: days ? group.stats.cost / days : 0,
322
+ };
323
+ })
324
+ .sort((a, b) => b.key.localeCompare(a.key));
325
+ for (let i = 0; i + 1 < rows.length; i++)
326
+ rows[i]!.delta = percentChange(rows[i]!.perDay!, rows[i + 1]!.perDay!);
327
+ return rows;
328
+ }
178
329
  const toRow = ([name, group]: [string, Tally]): GroupRow => ({
330
+ key: name,
179
331
  name: mode === "model" && group.providers!.size > 1 ? `${name} (${group.providers!.size})` : name,
180
332
  stats: group.stats,
181
333
  requests: group.requests,
@@ -193,13 +345,13 @@ export type Summary = {
193
345
  hit: number;
194
346
  };
195
347
 
196
- /** Totals for the summary block: one pass over the window. */
197
- export function summarize(records: UsageRecord[], sinceMs = 0): Summary {
348
+ /** Totals for the summary block: one pass over [sinceMs, untilMs). */
349
+ export function summarize(records: UsageRecord[], sinceMs = 0, untilMs = Infinity): Summary {
198
350
  const stats = emptyStats();
199
351
  let requests = 0;
200
352
  const sessions = new Set<string>();
201
353
  for (const record of records) {
202
- if (record.ts < sinceMs) continue;
354
+ if (record.ts < sinceMs || record.ts >= untilMs) continue;
203
355
  addStats(stats, record);
204
356
  requests++;
205
357
  sessions.add(record.sessionId);
@@ -215,28 +367,53 @@ export function summarize(records: UsageRecord[], sinceMs = 0): Summary {
215
367
 
216
368
  export type DailyCost = { label: string; cost: number };
217
369
 
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);
370
+ export const seriesKey = (key: string, parent?: string): string => JSON.stringify([key, parent ?? null]);
371
+
372
+ export function buildDailySeries(
373
+ records: UsageRecord[],
374
+ since: number,
375
+ until: number,
376
+ mode: GroupMode,
377
+ rows: { key: string; parent?: string }[],
378
+ ): { total: DailyCost[]; rows: Map<string, DailyCost[]> } {
379
+ const days = windowDays(since, until);
380
+ const total: DailyCost[] = [];
381
+ const positions = new Map<string, number>();
382
+ let cursor = since;
224
383
  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);
384
+ const key = dayKey(cursor);
385
+ positions.set(key, i);
386
+ total.push({ label: key.slice(5), cost: 0 });
387
+ cursor = bucketWindow(key, "day").until;
232
388
  }
389
+ const costs = new Map<string, Map<number, number>>();
390
+ const add = (key: string, index: number, cost: number) => {
391
+ let values = costs.get(key);
392
+ if (!values) costs.set(key, (values = new Map()));
393
+ values.set(index, (values.get(index) ?? 0) + cost);
394
+ };
233
395
  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;
396
+ if (record.ts < since || record.ts >= until) continue;
397
+ const index = positions.get(dayKey(record.ts));
398
+ if (index === undefined) continue;
399
+ total[index]!.cost += record.cost;
400
+ const key = recordKey(record, mode);
401
+ add(seriesKey(key), index, record.cost);
402
+ if (mode === "provider") add(seriesKey(record.model, record.provider), index, record.cost);
403
+ }
404
+ const result = new Map<string, DailyCost[]>();
405
+ for (const row of rows) {
406
+ const key = seriesKey(row.key, row.parent);
407
+ const values = costs.get(key);
408
+ const bucket = isTimeMode(mode) ? bucketWindow(row.key, mode) : { since, until };
409
+ const start = windowDays(since, Math.max(since, bucket.since));
410
+ const end = windowDays(since, Math.min(until, bucket.until));
411
+ result.set(
412
+ key,
413
+ total.slice(start, end).map((day, i) => ({ label: day.label, cost: values?.get(start + i) ?? 0 })),
414
+ );
238
415
  }
239
- return buckets;
416
+ return { total, rows: result };
240
417
  }
241
418
 
242
419
  /** Sum `perBar` consecutive daily buckets into one bar, labeled by its first day. */