@deathbeam/pi-usage 0.0.11 → 0.0.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # [@deathbeam/pi-usage](https://www.npmjs.com/package/@deathbeam/pi-usage)
2
2
 
3
- Use the `/usage` command for a fullscreen dashboard of token usage and cost per day, provider, model, and project.
3
+ Use the `/usage` command for a fullscreen dashboard of token usage and cost. It opens on a Summary and has per-day, per-provider, per-model and per-project views.
4
4
 
5
5
  ## Installation
6
6
 
@@ -10,25 +10,6 @@ pi install npm:@deathbeam/pi-usage # this package
10
10
  pi install git:github.com/deathbeam/pi-packages # all my packages
11
11
  ```
12
12
 
13
- ## Keys
14
-
15
- | Key | Action |
16
- | --------------------- | -------------------------------------------- |
17
- | Tab, Shift+Tab, ← / → | Cycle groups. Inside an open day, skip day. |
18
- | `[` / `]` | Step the day when it is the innermost filter |
19
- | Enter | Open the selected row |
20
- | Esc | Go back, or close when at the top level |
21
- | `q` | Close |
22
- | ↑ / ↓, `j` / `k` | Move the cursor |
23
- | Page Up / Page Down | Move by a page |
24
- | `g` / `G` | Move to the first / last row |
25
-
26
- Day rows include days without usage. Δ compares cost with the previous day. The sparkline always shows total cost per day across all history; the day in context is highlighted.
27
-
28
- 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.
29
-
30
- Compaction and branch summaries are counted under `(summaries)`.
31
-
32
13
  ## Development
33
14
 
34
15
  From the repo root:
package/index.ts CHANGED
@@ -1,26 +1,36 @@
1
1
  /** /usage — fullscreen token usage and cost dashboard. */
2
2
 
3
- import { homedir } from "node:os";
4
3
  import { basename, dirname, join } from "node:path";
5
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
4
+ import type { ExtensionAPI, Theme } from "@earendil-works/pi-coding-agent";
6
5
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
7
6
  import { matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
7
+ import {
8
+ clip,
9
+ deltaText,
10
+ displayName,
11
+ fitLabel,
12
+ formatCost,
13
+ formatTokens,
14
+ hitPct,
15
+ padWidth,
16
+ shareBar,
17
+ } from "./src/format.ts";
18
+ import { summaryLines, summaryModel, type SummaryModel } from "./src/summary.ts";
8
19
  import {
9
20
  buildRows,
10
21
  cacheView,
11
22
  collectUsage,
12
- comparison,
13
23
  dailyTotals,
14
24
  dayKey,
15
25
  dayWindow,
16
26
  matchesFilter,
17
- percentChange,
18
27
  summarize,
19
28
  usageWindow,
20
29
  type DailyCost,
21
30
  type GroupMode,
22
31
  type GroupRow,
23
32
  type Stats,
33
+ type Summary,
24
34
  type UsageFilter,
25
35
  type UsageRecord,
26
36
  } from "./src/usage.ts";
@@ -28,19 +38,25 @@ import {
28
38
  type Column = {
29
39
  label: string;
30
40
  width: number;
31
- cell: (stats: Stats, requests: number, totalCost: number, row?: GroupRow) => string;
41
+ cell: (stats: Stats, requests: number, totalCost: number, row: GroupRow | undefined, theme: Theme) => string;
32
42
  };
33
43
  type BodyRow = GroupRow & { parent?: string };
34
44
  type Frame = { filters: UsageFilter[]; group: number; cursor: number; top: number };
35
45
  type SparkBar = { label: string; char: string };
46
+ type ViewMode = "summary" | GroupMode;
47
+ type TableView = { mode: GroupMode; summary: Summary; body: BodyRow[] };
48
+ type SummaryView = { mode: "summary"; model: SummaryModel };
36
49
 
37
50
  const GROUPS = ["day", "provider", "model", "project"] as const satisfies readonly GroupMode[];
51
+ /** Tab order; Summary is a view, not a grouping, so it has no rows to open. */
52
+ const VIEWS: readonly ViewMode[] = ["summary", ...GROUPS];
38
53
  const GROUP_LABELS: Record<GroupMode, string> = {
39
54
  day: "Day",
40
55
  provider: "Provider",
41
56
  model: "Model",
42
57
  project: "Project",
43
58
  };
59
+ const VIEW_LABELS: Record<ViewMode, string> = { summary: "Summary", ...GROUP_LABELS };
44
60
 
45
61
  const COLUMNS: Column[] = [
46
62
  {
@@ -51,42 +67,20 @@ const COLUMNS: Column[] = [
51
67
  {
52
68
  label: "Share",
53
69
  width: 13,
54
- cell: (s, _r, totalCost) => {
55
- const share = totalCost > 0 ? s.cost / totalCost : 0;
56
- const filled = Math.round(8 * share);
57
- return "█".repeat(filled) + "·".repeat(8 - filled) + " " + `${Math.round(100 * share)}%`.padStart(4);
58
- },
70
+ cell: (s, _r, totalCost, _row, theme) => shareBar(s.cost, totalCost, theme),
59
71
  },
60
72
  { label: "Reqs", width: 6, cell: (_s, requests) => formatTokens(requests) },
61
73
  { label: "In", width: 7, cell: (s) => formatTokens(s.input) },
62
74
  { label: "Out", width: 7, cell: (s) => formatTokens(s.output) },
63
75
  // Cost already prices read/write differently; one combined token column is enough.
64
76
  { label: "Cache", width: 7, cell: (s) => formatTokens(s.cacheRead + s.cacheWrite) },
65
- { label: "Hit%", width: 5, cell: (s) => hitPct(s) },
77
+ { label: "Hit%", width: 5, cell: (s, _r, _t, _row, theme) => hitPct(s, theme) },
66
78
  ];
67
79
 
68
80
  const SPARK_BARS = "▁▂▃▄▅▆▇█";
69
81
  const MIN_NAME_WIDTH = 12;
70
-
71
- function formatCost(cost: number): string {
72
- if (cost === 0) return "$0.00";
73
- if (cost < 0.01) return `$${cost.toFixed(4)}`;
74
- if (cost < 100) return `$${cost.toFixed(2)}`;
75
- return `$${Math.round(cost).toLocaleString("en-US")}`;
76
- }
77
-
78
- function formatTokens(count: number): string {
79
- if (count === 0) return "-";
80
- if (count < 1000) return String(count);
81
- if (count < 1_000_000) return `${(count / 1000).toFixed(count < 10_000 ? 1 : 0)}k`;
82
- if (count < 1_000_000_000) return `${(count / 1_000_000).toFixed(1)}M`;
83
- return `${(count / 1_000_000_000).toFixed(1)}B`;
84
- }
85
-
86
- function hitPct(stats: Stats): string {
87
- const total = stats.input + stats.cacheRead + stats.cacheWrite;
88
- return total > 0 ? `${Math.round((100 * stats.cacheRead) / total)}%` : "-";
89
- }
82
+ /** Columns the title keeps beside the tab bar; the rest goes to the tabs around the active one. */
83
+ const TITLE_WIDTH = 8;
90
84
 
91
85
  function layout(width: number, allColumns: Column[]): { nameWidth: number; columns: Column[] } {
92
86
  function used(cols: Column[]): number {
@@ -100,28 +94,13 @@ function layout(width: number, allColumns: Column[]): { nameWidth: number; colum
100
94
  return { nameWidth: Math.max(4, width - used(columns)), columns };
101
95
  }
102
96
 
103
- function padWidth(s: string, w: number): string {
104
- return s + " ".repeat(Math.max(0, w - visibleWidth(s)));
105
- }
106
-
107
- function displayName(mode: GroupMode, name: string): string {
108
- if (mode === "day") return `${name} ${new Date(`${name}T00:00`).toLocaleDateString("en-US", { weekday: "short" })}`;
109
- if (mode !== "project") return name;
110
- if (!name) return "(no cwd)";
111
- const home = homedir();
112
- return name === home || name.startsWith(home + "/") ? "~" + name.slice(home.length) : name;
113
- }
114
-
115
- /** Truncate a name to its column so ANSI codes and padding stay width-correct. */
116
- function fitLabel(name: string, nameWidth: number): string {
117
- return visibleWidth(name) > nameWidth ? truncateToWidth(name, nameWidth, "…") : name;
118
- }
119
-
120
- function tableLine(nameWidth: number, columns: Column[], row: GroupRow, totalCost: number): string {
97
+ function tableLine(nameWidth: number, columns: Column[], row: GroupRow, totalCost: number, theme: Theme): string {
121
98
  const label = fitLabel(row.name, nameWidth);
122
99
  return [
123
100
  padWidth(label, nameWidth),
124
- ...columns.map((c) => padWidth(fitLabel(c.cell(row.stats, row.requests, totalCost, row), c.width), c.width)),
101
+ ...columns.map((c) =>
102
+ padWidth(fitLabel(c.cell(row.stats, row.requests, totalCost, row, theme), c.width), c.width),
103
+ ),
125
104
  ]
126
105
  .join(" ")
127
106
  .trimEnd();
@@ -142,10 +121,10 @@ function sparkline(daily: DailyCost[], width: number): { first: string; last: st
142
121
  };
143
122
  }
144
123
 
145
- function flatten(rows: GroupRow[], mode: GroupMode): BodyRow[] {
124
+ function flatten(rows: GroupRow[], mode: GroupMode, theme: Theme): BodyRow[] {
146
125
  const body: BodyRow[] = [];
147
126
  for (const row of rows) {
148
- body.push({ ...row, name: displayName(mode, row.name) });
127
+ body.push({ ...row, name: displayName(mode, row.name, theme) });
149
128
  for (const child of row.children ?? []) body.push({ ...child, name: ` ${child.name}`, parent: row.key });
150
129
  }
151
130
  return body;
@@ -153,7 +132,7 @@ function flatten(rows: GroupRow[], mode: GroupMode): BodyRow[] {
153
132
 
154
133
  export default function (pi: ExtensionAPI) {
155
134
  pi.registerCommand("usage", {
156
- description: "Show token usage and cost per provider, model, or project",
135
+ description: "Show token usage and cost: summary, day, provider, model and project views",
157
136
  handler: async (_args, ctx) => {
158
137
  if (ctx.mode !== "tui") return;
159
138
  const state: { records?: UsageRecord[]; done: number; total: number } = {
@@ -197,17 +176,23 @@ export default function (pi: ExtensionAPI) {
197
176
  function dayFilter() {
198
177
  return filters().findLast((f) => f.mode === "day");
199
178
  }
200
- function derive(source: UsageRecord[]) {
179
+ function derive(source: UsageRecord[]): TableView | SummaryView {
201
180
  const active = filters();
202
181
  const records = source.filter((record) =>
203
182
  active.every((f) => f.mode === "day" || matchesFilter(record, f)),
204
183
  );
205
184
  const day = active.findLast((f) => f.mode === "day")?.key;
206
185
  const window = usageWindow(records, day);
207
- const mode = GROUPS[group]!;
186
+ const mode = VIEWS[group]!;
187
+ if (mode === "summary") {
188
+ const scoped = records.filter(
189
+ (record) => record.ts >= window.since && record.ts < window.until,
190
+ );
191
+ return { mode, model: summaryModel(scoped, day === undefined, Date.now(), window) };
192
+ }
208
193
  const summary = summarize(records, window.since, window.until);
209
- const body = flatten(buildRows(records, window.since, mode, window.until), mode);
210
- return { mode, summary, body, compare: day ? undefined : comparison(records) };
194
+ const body = flatten(buildRows(records, window.since, mode, window.until), mode, theme);
195
+ return { mode, summary, body };
211
196
  }
212
197
  const getView = cacheView(() => derive(state.records!));
213
198
  let allDays: DailyCost[] | undefined;
@@ -222,15 +207,33 @@ export default function (pi: ExtensionAPI) {
222
207
  abort.abort();
223
208
  done(undefined);
224
209
  }
225
- function colorDelta(delta: number | undefined): string {
226
- if (delta === undefined) return "-";
227
- if (delta === 0) return "0%";
228
- const text = Number.isFinite(delta)
229
- ? `${delta > 0 ? "▲" : "▼"}${Math.round(Math.abs(delta))}%`
230
- : "▲new";
231
- return theme.fg(delta > 0 ? "error" : "success", text);
210
+ const deltaColumn: Column = {
211
+ label: "Δ",
212
+ width: 9,
213
+ cell: (_s, _r, _t, row, _theme) => deltaText(row?.delta, theme),
214
+ };
215
+ /** Tabs around the active one that fit `budget`; the active tab is never dropped. */
216
+ function windowTabs(tabs: { text: string; active: boolean }[], budget: number): string[] {
217
+ const active = Math.max(
218
+ 0,
219
+ tabs.findIndex((entry) => entry.active),
220
+ );
221
+ let lo = active;
222
+ let hi = active;
223
+ let used = visibleWidth(tabs[active]!.text);
224
+ while (true) {
225
+ const next = tabs[hi + 1];
226
+ const prev = tabs[lo - 1];
227
+ if (next !== undefined && used + 1 + visibleWidth(next.text) <= budget) {
228
+ hi += 1;
229
+ used += 1 + visibleWidth(next.text);
230
+ } else if (prev !== undefined && used + 1 + visibleWidth(prev.text) <= budget) {
231
+ lo -= 1;
232
+ used += 1 + visibleWidth(prev.text);
233
+ } else break;
234
+ }
235
+ return tabs.slice(lo, hi + 1).map((entry) => entry.text);
232
236
  }
233
- const deltaColumn: Column = { label: "Δ", width: 9, cell: (_s, _r, _t, row) => colorDelta(row?.delta) };
234
237
  function title(width: number): string {
235
238
  function tab(label: string, active: boolean): string {
236
239
  return active ? theme.fg("accent", `[${label}]`) : theme.fg("muted", ` ${label} `);
@@ -240,12 +243,16 @@ export default function (pi: ExtensionAPI) {
240
243
  filters()
241
244
  .map((f) => ` › ${displayName(f.mode, f.key)}`)
242
245
  .join("");
243
- const tabs = GROUPS.map((g, i) => (i === 0 && dayFilter() ? "" : tab(GROUP_LABELS[g], i === group)))
244
- .filter(Boolean)
245
- .join(" ");
246
+ const tabs = VIEWS.map((g, i) => ({
247
+ text: g === "day" && dayFilter() ? "" : tab(VIEW_LABELS[g], i === group),
248
+ active: i === group,
249
+ })).filter((entry) => entry.text !== "");
250
+ const budget = Math.max(1, width - Math.min(visibleWidth(left), TITLE_WIDTH) - 1);
251
+ const shown = windowTabs(tabs, budget).join(" ");
246
252
  const hint = theme.fg("dim", " (tab/←→)");
247
253
  const right =
248
- tabs + (visibleWidth(left) + visibleWidth(tabs) + visibleWidth(hint) + 1 <= width ? hint : "");
254
+ shown +
255
+ (visibleWidth(left) + visibleWidth(shown) + visibleWidth(hint) + 1 <= width ? hint : "");
249
256
  const leftWidth = Math.max(0, width - visibleWidth(right) - 1);
250
257
  return truncateToWidth(
251
258
  truncateToWidth(left, leftWidth, "…") +
@@ -256,11 +263,16 @@ export default function (pi: ExtensionAPI) {
256
263
  width,
257
264
  );
258
265
  }
259
- function footer(width: number): string {
260
- return truncateToWidth(
261
- theme.fg("dim", "enter open · esc back · tab/←→ group · [ ] day · q close · ↑↓ scroll"),
262
- width,
263
- );
266
+ function footer(width: number, mode?: ViewMode): string {
267
+ const parts = [
268
+ ...(mode !== undefined && mode !== "summary" ? ["enter open"] : []),
269
+ "esc back",
270
+ "tab/←→ view",
271
+ ...(dayFilter() ? ["[ ] day"] : []),
272
+ "q close",
273
+ "↑↓ scroll",
274
+ ];
275
+ return truncateToWidth(theme.fg("dim", parts.join(" · ")), width);
264
276
  }
265
277
  return {
266
278
  render(width: number) {
@@ -279,15 +291,22 @@ export default function (pi: ExtensionAPI) {
279
291
  lines.push(rule, footer(width));
280
292
  return lines.slice(0, rows);
281
293
  }
282
- const view = getView(GROUPS[group]!, filters());
283
- const { mode, summary, compare } = view;
284
- const first = compare
285
- ? `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`
286
- : `Cost ${formatCost(summary.stats.cost)}`;
294
+ const view = getView(VIEWS[group]!, filters());
295
+ if (view.mode === "summary") {
296
+ const content = summaryLines(view.model, width, theme);
297
+ body = [];
298
+ rowCount = content.length;
299
+ viewHeight = Math.max(1, rows - lines.length - 2);
300
+ // The summary has no cursor: its position is the scroll offset.
301
+ cursor = Math.max(0, Math.min(cursor, Math.max(0, rowCount - viewHeight)));
302
+ top = cursor;
303
+ lines.push(...content.slice(top, top + viewHeight), rule, footer(width, view.mode));
304
+ return clip(lines, width, rows);
305
+ }
306
+ const { mode, summary } = view;
287
307
  lines.push(
288
- truncateToWidth(first, width),
289
308
  truncateToWidth(
290
- `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)}`,
309
+ `Cost ${formatCost(summary.stats.cost)} · Reqs ${formatTokens(summary.requests)} · Sessions ${formatTokens(summary.sessions)} · Hit ${hitPct(summary.stats, theme)}`,
291
310
  width,
292
311
  ),
293
312
  );
@@ -296,23 +315,22 @@ export default function (pi: ExtensionAPI) {
296
315
  cursor = Math.min(cursor, Math.max(0, rowCount - 1));
297
316
  const selected = body[cursor];
298
317
  const contextDay = dayFilter()?.key ?? (mode === "day" ? selected?.key : undefined);
299
- const contextLabel = contextDay?.slice(5);
300
318
  const spark = sparkline(allDaily(), width);
301
319
  if (spark)
302
320
  lines.push(
303
321
  truncateToWidth(
304
- theme.fg("dim", `${spark.first} `) +
322
+ theme.fg("dim", `${spark.first.slice(5)} `) +
305
323
  spark.bars
306
324
  .map((bar) =>
307
325
  theme.fg(
308
- contextLabel === undefined || bar.label === contextLabel
326
+ contextDay === undefined || bar.label === contextDay
309
327
  ? "accent"
310
328
  : "borderMuted",
311
329
  bar.char,
312
330
  ),
313
331
  )
314
332
  .join("") +
315
- theme.fg("dim", ` ${spark.last}`),
333
+ theme.fg("dim", ` ${spark.last.slice(5)}`),
316
334
  width,
317
335
  ),
318
336
  );
@@ -340,20 +358,18 @@ export default function (pi: ExtensionAPI) {
340
358
  const visible = body.slice(top, top + viewHeight);
341
359
  if (rowCount === 0) lines.push(theme.fg("dim", " No usage"));
342
360
  for (const [i, row] of visible.entries()) {
343
- let line = tableLine(nameWidth, columns, row, summary.stats.cost);
361
+ let line = tableLine(nameWidth, columns, row, summary.stats.cost, theme);
344
362
  if (top + i === cursor) line = theme.bg("selectedBg", line);
345
363
  else if (row.parent !== undefined) line = theme.fg("dim", line);
346
364
  lines.push(line);
347
365
  }
348
366
  const total = { key: "", name: "Total", stats: summary.stats, requests: summary.requests };
349
367
  lines.push(
350
- theme.bold(tableLine(nameWidth, columns, total, summary.stats.cost)),
368
+ theme.bold(tableLine(nameWidth, columns, total, summary.stats.cost, theme)),
351
369
  rule,
352
- footer(width),
370
+ footer(width, mode),
353
371
  );
354
- return lines
355
- .slice(0, rows)
356
- .map((line) => (visibleWidth(line) > width ? truncateToWidth(line, width) : line));
372
+ return clip(lines, width, rows);
357
373
  },
358
374
  invalidate() {},
359
375
  handleInput(data: string) {
@@ -371,15 +387,16 @@ export default function (pi: ExtensionAPI) {
371
387
  return;
372
388
  } else if (keys.matches(data, "tui.select.confirm") && body[cursor]) {
373
389
  const row = body[cursor]!;
374
- const rowMode = row.parent === undefined ? GROUPS[group]! : "model";
390
+ const mode = VIEWS[group]!;
391
+ const rowMode = row.parent === undefined && mode !== "summary" ? mode : "model";
375
392
  const selected: UsageFilter[] =
376
393
  row.parent === undefined ? [] : [{ mode: "provider", key: row.parent }];
377
394
  selected.push({ mode: rowMode, key: row.key });
378
395
  stack.push({ filters: selected, group, cursor, top });
379
396
  // Land on the first grouping that is not already filtered.
380
397
  const used = new Set(filters().map((f) => f.mode));
381
- group = GROUPS.findIndex((g) => !used.has(g));
382
- if (group < 0) group = dayFilter() ? 1 : 0;
398
+ group = VIEWS.findIndex((g) => g !== "summary" && !used.has(g));
399
+ if (group < 0) group = VIEWS.indexOf(dayFilter() ? "provider" : "day");
383
400
  cursor = top = 0;
384
401
  } else if ((data === "[" || data === "]") && filters().at(-1)?.mode === "day") {
385
402
  const filter = filters().at(-1)!;
@@ -392,8 +409,8 @@ export default function (pi: ExtensionAPI) {
392
409
  matchesKey(data, "left")
393
410
  ) {
394
411
  const offset = matchesKey(data, "tab") || matchesKey(data, "right") ? 1 : -1;
395
- do group = (group + offset + GROUPS.length) % GROUPS.length;
396
- while (group === 0 && dayFilter());
412
+ do group = (group + offset + VIEWS.length) % VIEWS.length;
413
+ while (VIEWS[group] === "day" && dayFilter());
397
414
  cursor = top = 0;
398
415
  } else if (keys.matches(data, "tui.select.up") || data === "k") cursor -= 1;
399
416
  else if (keys.matches(data, "tui.select.down") || data === "j") cursor += 1;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deathbeam/pi-usage",
3
- "version": "0.0.11",
3
+ "version": "0.0.13",
4
4
  "description": "Minimal extension for token usage and cost per provider, model and project.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/format.ts ADDED
@@ -0,0 +1,87 @@
1
+ /** Text helpers shared by the table views and the Summary view. */
2
+
3
+ import { homedir } from "node:os";
4
+ import type { Theme } from "@earendil-works/pi-coding-agent";
5
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
6
+ import type { GroupMode, GroupRow, Stats } from "./usage.ts";
7
+
8
+ const BAR_CELLS = 8;
9
+
10
+ export function formatCost(cost: number): string {
11
+ if (cost === 0) return "$0.00";
12
+ if (cost < 0.01) return `$${cost.toFixed(4)}`;
13
+ if (cost < 100) return `$${cost.toFixed(2)}`;
14
+ return `$${Math.round(cost).toLocaleString("en-US")}`;
15
+ }
16
+
17
+ export function formatTokens(count: number): string {
18
+ if (count === 0) return "-";
19
+ if (count < 1000) return String(count);
20
+ if (count < 1_000_000) return `${(count / 1000).toFixed(count < 10_000 ? 1 : 0)}k`;
21
+ if (count < 1_000_000_000) return `${(count / 1_000_000).toFixed(1)}M`;
22
+ return `${(count / 1_000_000_000).toFixed(1)}B`;
23
+ }
24
+
25
+ /** Cache reads as a share of the whole input, colored by how much of the session the cache carried. */
26
+ export function hitPct(stats: Stats, theme: Theme): string {
27
+ const total = stats.input + stats.cacheRead + stats.cacheWrite;
28
+ if (total === 0) return "-";
29
+ const pct = Math.round((100 * stats.cacheRead) / total);
30
+ return theme.fg(pct >= 90 ? "success" : pct >= 75 ? "warning" : "error", `${pct}%`);
31
+ }
32
+
33
+ export function padWidth(s: string, w: number): string {
34
+ return s + " ".repeat(Math.max(0, w - visibleWidth(s)));
35
+ }
36
+
37
+ /** Truncate a name to its column so ANSI codes and padding stay width-correct. */
38
+ export function fitLabel(name: string, nameWidth: number): string {
39
+ return visibleWidth(name) > nameWidth ? truncateToWidth(name, nameWidth, "…") : name;
40
+ }
41
+
42
+ /** Thin bar: heavy for the filled part, light for the rest, so a row reads as a line, not a block. */
43
+ export function shareBar(cost: number, totalCost: number, theme: Theme): string {
44
+ const share = totalCost > 0 ? Math.min(1, Math.max(0, cost / totalCost)) : 0;
45
+ const halves = Math.round(share * BAR_CELLS * 2);
46
+ const full = Math.floor(halves / 2);
47
+ const half = halves % 2 === 1 ? "╸" : "";
48
+ return (
49
+ theme.fg("accent", "━".repeat(full) + half) +
50
+ theme.fg("borderMuted", "─".repeat(BAR_CELLS - full - half.length)) +
51
+ " " +
52
+ `${Math.round(100 * share)}%`.padStart(4)
53
+ );
54
+ }
55
+
56
+ /** One top list row: name, share bar and cost. */
57
+ export function topLine(row: GroupRow, totalCost: number, nameWidth: number, theme: Theme): string {
58
+ return [
59
+ padWidth(fitLabel(row.name, nameWidth), nameWidth),
60
+ shareBar(row.stats.cost, totalCost, theme),
61
+ formatCost(row.stats.cost).padStart(9),
62
+ ].join(" ");
63
+ }
64
+ /** `theme` marks a weekend day; the breadcrumb and list callers leave the weekday suffix plain. */
65
+ export function displayName(mode: GroupMode, name: string, theme?: Theme): string {
66
+ if (mode === "day") {
67
+ const weekday = new Date(`${name}T00:00`).toLocaleDateString("en-US", { weekday: "short" });
68
+ if (theme === undefined || (weekday !== "Sat" && weekday !== "Sun")) return `${name} ${weekday}`;
69
+ return `${name} ${theme.fg("accent", weekday)}`;
70
+ }
71
+ if (mode !== "project") return name;
72
+ if (!name) return "(no cwd)";
73
+ const home = homedir();
74
+ return name === home || name.startsWith(home + "/") ? "~" + name.slice(home.length) : name;
75
+ }
76
+
77
+ /** Rise in red, fall in green: the money spent, not the money saved. */
78
+ export function deltaText(delta: number | undefined, theme: Theme): string {
79
+ if (delta === undefined) return "-";
80
+ if (delta === 0) return "0%";
81
+ const text = Number.isFinite(delta) ? `${delta > 0 ? "▲" : "▼"}${Math.round(Math.abs(delta))}%` : "▲new";
82
+ return theme.fg(delta > 0 ? "error" : "success", text);
83
+ }
84
+
85
+ export function clip(lines: string[], width: number, rows: number): string[] {
86
+ return lines.slice(0, rows).map((line) => (visibleWidth(line) > width ? truncateToWidth(line, width) : line));
87
+ }
package/src/summary.ts ADDED
@@ -0,0 +1,521 @@
1
+ /** The Summary view: data model (totals, trends, streaks, calendar, top lists) and its layout. */
2
+
3
+ import { basename } from "node:path";
4
+ import type { Theme } from "@earendil-works/pi-coding-agent";
5
+ import { visibleWidth } from "@earendil-works/pi-tui";
6
+ import { deltaText, displayName, formatCost, formatTokens, hitPct, padWidth, topLine } from "./format.ts";
7
+ import {
8
+ buildRows,
9
+ comparison,
10
+ dailyTotals,
11
+ dayKey,
12
+ percentChange,
13
+ summarize,
14
+ type DailyCost,
15
+ type GroupMode,
16
+ type GroupRow,
17
+ type Stats,
18
+ type TimeWindow,
19
+ type UsageRecord,
20
+ } from "./usage.ts";
21
+
22
+ export type Streaks = { current: number; longest: number };
23
+
24
+ /** `level` is 0 for a day without usage and 1..4 for its cost on a log scale. */
25
+ export type HeatCell = { cost: number; level: number };
26
+
27
+ /** `rows[weekday][week]`, Monday first; a cell is undefined outside the recorded range. */
28
+ export type Heatmap = { header: string; rows: (HeatCell | undefined)[][] };
29
+
30
+ export type Trends = {
31
+ today: number;
32
+ /** Per-day spend so far this week and this month, with the change against the previous one. */
33
+ week: number;
34
+ weekDelta: number;
35
+ month: number;
36
+ monthDelta: number;
37
+ };
38
+
39
+ export type TopLists = { models: GroupRow[]; projects: GroupRow[]; sessions: GroupRow[] };
40
+
41
+ type Cell = { label: string; value: string };
42
+ type List = { title: string; mode?: GroupMode; rows: GroupRow[] };
43
+ type Section = { title: string; maxColumns: number; cells: (width: number) => Cell[] };
44
+
45
+ export type SummaryModel = {
46
+ stats: Stats;
47
+ requests: number;
48
+ sessions: number;
49
+ activeDays: number;
50
+ perDay: number;
51
+ perSession: number;
52
+ streak: Streaks;
53
+ busiest?: DailyCost;
54
+ /** One entry per local day of the active window. */
55
+ daily: DailyCost[];
56
+ /** Absent when a single day is in context: there is nothing to compare it with. */
57
+ trends?: Trends;
58
+ top: TopLists;
59
+ };
60
+
61
+ const WEEKDAYS = ["Mon", "", "Wed", "", "Fri", "", ""];
62
+ /** Empty first, then four steps: glyph and hue both rise, so a level reads without color. */
63
+ const HEAT_LEVELS = [
64
+ { glyph: "·", color: "borderMuted" },
65
+ { glyph: "▪", color: "muted" },
66
+ { glyph: "■", color: "text" },
67
+ { glyph: "■", color: "warning" },
68
+ { glyph: "■", color: "error" },
69
+ ] as const;
70
+ const INDENT = " ";
71
+ const COLUMN_GAP = 3;
72
+ /** Narrowest a section may get before it is stacked instead of placed beside another. */
73
+ const MIN_SECTION_WIDTH = 44;
74
+ /** Longest a name column grows; a longer list would push the bar too far from the name. */
75
+ const MAX_NAME_WIDTH = 30;
76
+ /** Space the bar and the cost take in a top list row. */
77
+ const LIST_OVERHEAD = 24;
78
+
79
+ function emptyStats(): Stats {
80
+ return { cost: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
81
+ }
82
+
83
+ function trends(records: UsageRecord[], now: number): Trends {
84
+ const compare = comparison(records, now);
85
+ return {
86
+ today: compare.today,
87
+ week: compare.week,
88
+ weekDelta: percentChange(compare.week, compare.lastWeek),
89
+ month: compare.month,
90
+ monthDelta: percentChange(compare.month, compare.lastMonth),
91
+ };
92
+ }
93
+
94
+ function heading(theme: Theme, text: string): string {
95
+ return theme.fg("accent", theme.bold(text));
96
+ }
97
+
98
+ /** Bold value; `accent` marks the headline number of its block. */
99
+ function cellValue(text: string, accent: boolean, theme: Theme): string {
100
+ const value = theme.bold(text);
101
+ return accent ? theme.fg("accent", value) : value;
102
+ }
103
+
104
+ /** `labelWidth` pads the labels of a column so its values line up. */
105
+ function cellText(cell: Cell, theme: Theme, labelWidth = visibleWidth(cell.label)): string {
106
+ return theme.fg("muted", padWidth(cell.label, labelWidth)) + " " + cell.value;
107
+ }
108
+
109
+ /** One label/value column per entry, sized to its widest cell plus the gap. */
110
+ function columnWidths(cells: Cell[], count: number, theme: Theme): number[] {
111
+ const widths = Array.from({ length: count }, () => 0);
112
+ for (const [index, cell] of cells.entries()) {
113
+ const column = index % count;
114
+ widths[column] = Math.max(widths[column]!, visibleWidth(cellText(cell, theme)) + COLUMN_GAP);
115
+ }
116
+ return widths;
117
+ }
118
+
119
+ /** Label/value pairs in as many aligned columns as `maxColumns` and the width allow. */
120
+ function grid(cells: Cell[], width: number, maxColumns: number, theme: Theme): string[] {
121
+ for (let count = Math.min(cells.length, maxColumns); count > 0; count--) {
122
+ const widths = columnWidths(cells, count, theme);
123
+ const used = widths.reduce((sum, column) => sum + column, 0) - COLUMN_GAP;
124
+ if (count > 1 && used > width) continue;
125
+ const rows: string[] = [];
126
+ for (let start = 0; start < cells.length; start += count) {
127
+ rows.push(
128
+ cells
129
+ .slice(start, start + count)
130
+ .map((cell, column) => padWidth(cellText(cell, theme), widths[column]!))
131
+ .join("")
132
+ .trimEnd(),
133
+ );
134
+ }
135
+ return rows;
136
+ }
137
+ return [];
138
+ }
139
+
140
+ function indent(rows: string[]): string[] {
141
+ return rows.map((row) => INDENT + row);
142
+ }
143
+
144
+ /** Month labels over the week columns; a label too close to the next one is dropped instead of colliding. */
145
+ function monthHeader(months: (string | undefined)[], weeks: number): string {
146
+ const chars = Array.from({ length: 4 + weeks * 2 }, () => " ");
147
+ const labels: { start: number; text: string }[] = [];
148
+ for (const [week, month] of months.entries()) if (month) labels.push({ start: 4 + week * 2, text: month });
149
+ for (const [index, label] of labels.entries()) {
150
+ const next = labels[index + 1];
151
+ const end = label.start + label.text.length;
152
+ // One space between labels reads as no gap in a terminal, so each label needs a column of its own.
153
+ if (next !== undefined && next.start - end < 2) continue;
154
+ // The last label may run past the grid: a one-day calendar has only one 2-wide column for `Sep`.
155
+ for (const [i, char] of Array.from(label.text).entries()) chars[label.start + i] = char;
156
+ }
157
+ return chars.join("").trimEnd();
158
+ }
159
+
160
+ /** `05-21 Wed` for a `YYYY-MM-DD` key, matching the sparkline and session list dates. */
161
+ function dayName(key: string): string {
162
+ const weekday = new Date(`${key}T00:00`).toLocaleDateString("en-US", { weekday: "short" });
163
+ return `${key.slice(5)} ${weekday}`;
164
+ }
165
+
166
+ function activity(daily: DailyCost[], width: number, theme: Theme): string[] {
167
+ const weeks = Math.max(1, Math.min(53, Math.floor((width - 4) / 2)));
168
+ const heat = heatmap(daily, weeks);
169
+ const rows = [theme.fg("dim", heat.header)];
170
+ for (const [weekday, row] of heat.rows.entries()) {
171
+ // A one-day window leaves six empty rows; skip them instead of printing bare weekday labels.
172
+ if (row.every((cell) => cell === undefined)) continue;
173
+ const label = WEEKDAYS[weekday]!;
174
+ let line = label ? theme.fg("dim", label.padEnd(4)) : " ".repeat(4);
175
+ for (const cell of row) {
176
+ if (cell === undefined) line += " ";
177
+ else {
178
+ const level = HEAT_LEVELS[cell.level]!;
179
+ line += theme.fg(level.color, `${level.glyph} `);
180
+ }
181
+ }
182
+ rows.push(line.trimEnd());
183
+ }
184
+ const legend = HEAT_LEVELS.map((level) => theme.fg(level.color, level.glyph)).join(" ");
185
+ rows.push(theme.fg("dim", "less ") + legend + theme.fg("dim", " more"));
186
+ return rows;
187
+ }
188
+
189
+ /** Cost, volume and token cells; one group per column so the three start side by side. */
190
+ function kpiGroups(model: SummaryModel, theme: Theme): Cell[][] {
191
+ const { stats } = model;
192
+ return [
193
+ [
194
+ { label: "Total", value: cellValue(formatCost(stats.cost), true, theme) },
195
+ { label: "Per day", value: cellValue(formatCost(model.perDay), false, theme) },
196
+ { label: "Per session", value: cellValue(formatCost(model.perSession), false, theme) },
197
+ ],
198
+ [
199
+ { label: "Reqs", value: cellValue(formatTokens(model.requests), false, theme) },
200
+ { label: "Sessions", value: cellValue(formatTokens(model.sessions), false, theme) },
201
+ { label: "Active days", value: cellValue(formatTokens(model.activeDays), false, theme) },
202
+ ],
203
+ [
204
+ { label: "In", value: cellValue(formatTokens(stats.input), false, theme) },
205
+ { label: "Out", value: cellValue(formatTokens(stats.output), false, theme) },
206
+ // shortcut: no per-model price table, so cache savings show as the read/write split, not dollars.
207
+ { label: "Cache R", value: cellValue(formatTokens(stats.cacheRead), false, theme) },
208
+ { label: "Cache W", value: cellValue(formatTokens(stats.cacheWrite), false, theme) },
209
+ { label: "Hit", value: cellValue(hitPct(stats, theme), false, theme) },
210
+ ],
211
+ ];
212
+ }
213
+
214
+ /** Column-major: each group is a column with its labels padded, so every value in a column lines up. */
215
+ function kpiBlock(groups: Cell[][], width: number, theme: Theme): string[] {
216
+ const labelWidths = groups.map((group) => Math.max(...group.map((cell) => visibleWidth(cell.label))));
217
+ const widths = groups.map(
218
+ (group, column) =>
219
+ Math.max(...group.map((cell) => visibleWidth(cellText(cell, theme, labelWidths[column]!)))) + COLUMN_GAP,
220
+ );
221
+ if (widths.reduce((sum, column) => sum + column, 0) - COLUMN_GAP > width)
222
+ return groups.flatMap((group) => grid(group, width, group.length, theme));
223
+ const height = Math.max(...groups.map((group) => group.length));
224
+ return Array.from({ length: height }, (_, row) =>
225
+ groups
226
+ .map((group, column) =>
227
+ padWidth(
228
+ group[row] === undefined ? "" : cellText(group[row]!, theme, labelWidths[column]!),
229
+ widths[column]!,
230
+ ),
231
+ )
232
+ .join("")
233
+ .trimEnd(),
234
+ );
235
+ }
236
+
237
+ function trendCells(model: SummaryModel, width: number, theme: Theme): Cell[] {
238
+ const trends = model.trends!;
239
+ /** Bold average, colored delta, muted comparison; only the suffix is dropped when space runs out. */
240
+ function trend(label: string, average: number, delta: number, suffix: string): Cell {
241
+ const avg = `${formatCost(average)}/day`;
242
+ const change = deltaText(delta, theme);
243
+ // grid() skips its width test for a single column, so an oversized value would be cut mid-word.
244
+ const fits = visibleWidth(`${label} ${avg} ${change} ${suffix}`) <= width;
245
+ return { label, value: `${theme.bold(avg)} ${change}${fits ? theme.fg("muted", ` ${suffix}`) : ""}` };
246
+ }
247
+ return [
248
+ { label: "Today", value: cellValue(formatCost(trends.today), true, theme) },
249
+ trend("This week", trends.week, trends.weekDelta, "vs last week"),
250
+ trend("This month", trends.month, trends.monthDelta, "vs last month"),
251
+ ];
252
+ }
253
+
254
+ function days(count: number): string {
255
+ return `${count} ${count === 1 ? "day" : "days"}`;
256
+ }
257
+
258
+ function listName(list: List, row: GroupRow): string {
259
+ return list.mode === undefined ? row.name : displayName(list.mode, row.name);
260
+ }
261
+
262
+ function listBlock(list: List, totalCost: number, width: number, theme: Theme): string[] {
263
+ const bodyWidth = Math.max(1, width - INDENT.length);
264
+ const nameWidth = Math.max(6, Math.min(MAX_NAME_WIDTH, bodyWidth - LIST_OVERHEAD));
265
+ return [
266
+ heading(theme, list.title),
267
+ ...indent(list.rows.map((row) => topLine({ ...row, name: listName(list, row) }, totalCost, nameWidth, theme))),
268
+ ];
269
+ }
270
+
271
+ /** A list's width when its longest name keeps its space next to the bar and the cost. */
272
+ function listWidth(list: List, width: number): number {
273
+ const longest = Math.max(0, ...list.rows.map((row) => visibleWidth(listName(list, row))));
274
+ return Math.min(width, INDENT.length + Math.min(MAX_NAME_WIDTH, longest) + LIST_OVERHEAD);
275
+ }
276
+
277
+ /** Widths for `count` blocks sharing a row, the last one taking the rounding remainder. */
278
+ function rowWidths(width: number, count: number): number[] {
279
+ const share = Math.floor((width - COLUMN_GAP * (count - 1)) / count);
280
+ return Array.from({ length: count }, (_, column) =>
281
+ column === count - 1 ? width - (share + COLUMN_GAP) * (count - 1) : share,
282
+ );
283
+ }
284
+
285
+ /** One row of already rendered blocks, each padded to its column width. */
286
+ function sideBySide(blocks: string[][], widths: number[]): string[] {
287
+ const height = Math.max(...blocks.map((block) => block.length));
288
+ const lines: string[] = [];
289
+ for (let line = 0; line < height; line++)
290
+ lines.push(
291
+ blocks
292
+ .map((block, column) => padWidth(block[line] ?? "", widths[column]!))
293
+ .join(" ".repeat(COLUMN_GAP))
294
+ .trimEnd(),
295
+ );
296
+ return lines;
297
+ }
298
+
299
+ function listRow(lists: List[], totalCost: number, width: number, theme: Theme): string[] {
300
+ const widths = rowWidths(width, lists.length);
301
+ return sideBySide(
302
+ lists.map((list, column) => listBlock(list, totalCost, widths[column]!, theme)),
303
+ widths,
304
+ );
305
+ }
306
+
307
+ /** Trends and streaks share a row while each keeps a readable width. */
308
+ function sections(items: Section[], width: number, theme: Theme): string[] {
309
+ const count = Math.max(
310
+ 1,
311
+ Math.min(items.length, Math.floor((width + COLUMN_GAP) / (MIN_SECTION_WIDTH + COLUMN_GAP))),
312
+ );
313
+ const lines: string[] = [];
314
+ for (let start = 0; start < items.length; start += count) {
315
+ if (lines.length > 0) lines.push("");
316
+ const row = items.slice(start, start + count);
317
+ const widths = rowWidths(width, row.length);
318
+ lines.push(
319
+ ...sideBySide(
320
+ row.map((section, column) => {
321
+ const bodyWidth = Math.max(1, widths[column]! - INDENT.length);
322
+ return [
323
+ heading(theme, section.title),
324
+ ...indent(grid(section.cells(bodyWidth), bodyWidth, section.maxColumns, theme)),
325
+ ];
326
+ }),
327
+ widths,
328
+ ),
329
+ );
330
+ }
331
+ return lines;
332
+ }
333
+
334
+ function streakCells(model: SummaryModel, theme: Theme): Cell[] {
335
+ return [
336
+ { label: "Current", value: cellValue(days(model.streak.current), false, theme) },
337
+ { label: "Longest", value: cellValue(days(model.streak.longest), false, theme) },
338
+ {
339
+ label: "Busiest",
340
+ value: cellValue(
341
+ model.busiest ? `${dayName(model.busiest.label)} ${formatCost(model.busiest.cost)}` : "-",
342
+ false,
343
+ theme,
344
+ ),
345
+ },
346
+ ];
347
+ }
348
+
349
+ /** Consecutive active days; `daily` must be contiguous days ending today, so the trailing run is current. */
350
+ export function streaks(daily: DailyCost[]): Streaks {
351
+ let longest = 0;
352
+ let run = 0;
353
+ for (const day of daily) {
354
+ run = day.cost > 0 ? run + 1 : 0;
355
+ longest = Math.max(longest, run);
356
+ }
357
+ return { current: run, longest };
358
+ }
359
+
360
+ export function busiestDay(daily: DailyCost[]): DailyCost | undefined {
361
+ let best: DailyCost | undefined;
362
+ for (const day of daily) {
363
+ if (day.cost > 0 && (best === undefined || day.cost > best.cost)) best = day;
364
+ }
365
+ return best;
366
+ }
367
+
368
+ /** `level` rises with cost on a log scale, so a few expensive days do not flatten every other day. */
369
+ function heatLevel(cost: number, max: number): number {
370
+ if (cost <= 0 || max <= 0) return 0;
371
+ return Math.min(4, Math.max(1, Math.ceil((4 * Math.log1p(cost)) / Math.log1p(max))));
372
+ }
373
+
374
+ /** Local date of a daily label; totals use `YYYY-MM-DD`, tests and callers may pass a bare `MM-DD`. */
375
+ function labelDate(label: string, now: number): Date {
376
+ const full = label.length === 10 ? label : `${new Date(now).getFullYear()}-${label}`;
377
+ return new Date(`${full}T00:00`);
378
+ }
379
+
380
+ /** `weeks` is the space available; the grid shrinks to the recorded history and ends on its last day. */
381
+ export function heatmap(daily: DailyCost[], weeks: number, now = Date.now()): Heatmap {
382
+ const last = daily.length - 1;
383
+ const end = last >= 0 ? labelDate(daily[last]!.label, now) : new Date(now);
384
+ const today = (end.getDay() + 6) % 7; // Monday = 0
385
+ const columns = Math.max(1, Math.min(weeks, Math.ceil((daily.length + today) / 7)));
386
+ const first = last - today - 7 * (columns - 1);
387
+ const max = daily.reduce((top, day) => Math.max(top, day.cost), 0);
388
+ const rows: (HeatCell | undefined)[][] = [[], [], [], [], [], [], []];
389
+ for (let weekday = 0; weekday < 7; weekday++) {
390
+ for (let week = 0; week < columns; week++) {
391
+ const index = first + week * 7 + weekday;
392
+ if (index < 0 || index > last) {
393
+ rows[weekday]!.push(undefined);
394
+ continue;
395
+ }
396
+ const { cost } = daily[index]!;
397
+ rows[weekday]!.push({ cost, level: heatLevel(cost, max) });
398
+ }
399
+ }
400
+ const months: (string | undefined)[] = [];
401
+ let month = -1;
402
+ for (let week = 0; week < columns; week++) {
403
+ // The week starts on its Monday, but a one-day column shows only its day, so label the first day it shows.
404
+ const date = labelDate(daily[Math.max(0, first + week * 7)]!.label, now);
405
+ months.push(date.getMonth() === month ? undefined : date.toLocaleDateString("en-US", { month: "short" }));
406
+ month = date.getMonth();
407
+ }
408
+ return { header: monthHeader(months, columns), rows };
409
+ }
410
+
411
+ /** Top groups by cost, in the same shape the table views use. */
412
+ export function topGroups(
413
+ records: UsageRecord[],
414
+ since: number,
415
+ until: number,
416
+ mode: GroupMode,
417
+ count = 5,
418
+ ): GroupRow[] {
419
+ return buildRows(records, since, mode, until).slice(0, count);
420
+ }
421
+
422
+ /** Sessions have no grouping of their own; the name pairs the start date with a short id and the project. */
423
+ export function topSessions(records: UsageRecord[], since: number, until: number, count = 5): GroupRow[] {
424
+ const sessions = new Map<string, { cwd: string; start: number; stats: Stats; requests: number }>();
425
+ for (const record of records) {
426
+ if (record.ts < since || record.ts >= until) continue;
427
+ let session = sessions.get(record.sessionId);
428
+ if (!session)
429
+ sessions.set(
430
+ record.sessionId,
431
+ (session = { cwd: record.cwd, start: record.ts, stats: emptyStats(), requests: 0 }),
432
+ );
433
+ session.start = Math.min(session.start, record.ts);
434
+ session.stats.cost += record.cost;
435
+ session.stats.input += record.input;
436
+ session.stats.output += record.output;
437
+ session.stats.cacheRead += record.cacheRead;
438
+ session.stats.cacheWrite += record.cacheWrite;
439
+ session.requests += record.requests;
440
+ }
441
+ return [...sessions]
442
+ .map(([id, session]) => ({
443
+ key: id,
444
+ // The id identifies the session, so it comes before the project and survives a truncated name.
445
+ name: `${dayKey(session.start).slice(5)} ${id.slice(0, 6)} ${basename(session.cwd) || "(no cwd)"}`,
446
+ stats: session.stats,
447
+ requests: session.requests,
448
+ }))
449
+ .sort((a, b) => b.stats.cost - a.stats.cost || b.requests - a.requests)
450
+ .slice(0, count);
451
+ }
452
+
453
+ /**
454
+ * The whole Summary view as data. `records` is the active set: drill-down filters already applied and
455
+ * `window` is the day or history it covers, so a single day in context yields a one-day calendar.
456
+ */
457
+ export function summaryModel(
458
+ records: UsageRecord[],
459
+ withTrends = true,
460
+ now = Date.now(),
461
+ window?: TimeWindow,
462
+ ): SummaryModel {
463
+ const summary = summarize(records);
464
+ const daily = dailyTotals(records, window, now);
465
+ const activeDays = daily.filter((day) => day.cost > 0).length;
466
+ return {
467
+ stats: summary.stats,
468
+ requests: summary.requests,
469
+ sessions: summary.sessions,
470
+ activeDays,
471
+ perDay: activeDays > 0 ? summary.stats.cost / activeDays : 0,
472
+ perSession: summary.sessions > 0 ? summary.stats.cost / summary.sessions : 0,
473
+ streak: streaks(daily),
474
+ busiest: busiestDay(daily),
475
+ daily,
476
+ trends: withTrends ? trends(records, now) : undefined,
477
+ top: {
478
+ models: topGroups(records, 0, Infinity, "model"),
479
+ projects: topGroups(records, 0, Infinity, "project"),
480
+ sessions: topSessions(records, 0, Infinity),
481
+ },
482
+ };
483
+ }
484
+
485
+ export function summaryLines(model: SummaryModel, width: number, theme: Theme): string[] {
486
+ const bodyWidth = Math.max(1, width - INDENT.length);
487
+ const lines = [heading(theme, "Overview"), ...indent(kpiBlock(kpiGroups(model, theme), bodyWidth, theme))];
488
+ const items: Section[] = [];
489
+ if (model.trends) items.push({ title: "Trends", maxColumns: 1, cells: (w) => trendCells(model, w, theme) });
490
+ items.push({ title: "Streaks", maxColumns: 1, cells: () => streakCells(model, theme) });
491
+ lines.push("", ...sections(items, width, theme));
492
+ if (model.daily.length > 0) {
493
+ lines.push("", heading(theme, "Activity"), ...indent(activity(model.daily, bodyWidth, theme)));
494
+ }
495
+ const lists = (
496
+ [
497
+ { title: "Models", mode: "model", rows: model.top.models },
498
+ { title: "Projects", mode: "project", rows: model.top.projects },
499
+ ] satisfies List[]
500
+ ).filter((list) => list.rows.length > 0);
501
+ let listColumn = width;
502
+ if (lists.length > 0) {
503
+ // Names are the point of a list, so two blocks share a row only while both keep them readable.
504
+ const needed = lists.reduce((sum, list) => sum + listWidth(list, width), 0) + COLUMN_GAP * (lists.length - 1);
505
+ if (needed <= width) {
506
+ listColumn = rowWidths(width, lists.length)[0]!;
507
+ lines.push("", ...listRow(lists, model.stats.cost, width, theme));
508
+ } else {
509
+ for (const list of lists) lines.push("", ...listBlock(list, model.stats.cost, width, theme));
510
+ }
511
+ }
512
+ const sessions: List = { title: "Sessions", rows: model.top.sessions };
513
+ if (sessions.rows.length > 0) {
514
+ // Session names carry the date and the id, so the block outgrows its column rather than cut them.
515
+ lines.push(
516
+ "",
517
+ ...listBlock(sessions, model.stats.cost, Math.max(listColumn, listWidth(sessions, width)), theme),
518
+ );
519
+ }
520
+ return lines;
521
+ }
package/src/usage.ts CHANGED
@@ -55,10 +55,11 @@ export type Summary = {
55
55
  };
56
56
 
57
57
  export type DailyCost = { label: string; cost: number };
58
+ export type TimeWindow = { since: number; until: number };
58
59
 
59
- type Tally = { stats: Stats; requests: number; models?: Map<string, Tally>; providers?: Set<string> };
60
+ type Tally = { stats: Stats; requests: number; models?: Map<string, Tally> };
60
61
 
61
- const CACHE_VERSION = 3;
62
+ const CACHE_VERSION = 5;
62
63
 
63
64
  function emptyStats(): Stats {
64
65
  return { cost: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
@@ -125,8 +126,9 @@ async function sessionFiles(dir: string, out: string[]): Promise<void> {
125
126
  }
126
127
  for (const entry of entries) {
127
128
  const path = join(dir, entry.name);
128
- if (entry.isDirectory()) await sessionFiles(path, out);
129
- else if (entry.name.endsWith(".jsonl")) out.push(path);
129
+ if (entry.isDirectory()) {
130
+ await sessionFiles(path, out);
131
+ } else if (entry.name.endsWith(".jsonl")) out.push(path);
130
132
  }
131
133
  }
132
134
 
@@ -200,7 +202,7 @@ async function parseFile(file: string): Promise<UsageRecord[]> {
200
202
  } else {
201
203
  // Compaction and branch-summary calls carry no model, so their cost gets its own row.
202
204
  provider = "(summaries)";
203
- model = entry.type;
205
+ model = String(entry.type || "unknown");
204
206
  }
205
207
  const cost = typeof usage.cost === "number" ? usage.cost : num(usage.cost?.total);
206
208
  const input = num(usage.input);
@@ -233,9 +235,8 @@ async function parseFile(file: string): Promise<UsageRecord[]> {
233
235
  * Files are streamed line by line: the corpus is gigabytes, and reading whole files stalls the event
234
236
  * loop and spikes RSS. The recursive scan includes `sessions/delegates`, where pi-delegate children
235
237
  * write their own transcripts, so subagent usage is counted with full provider/model attribution and
236
- * its own cwd. Parent sessions never embed the delegate child's usage (the delegate tool result
237
- * carries only text), so there is nothing to double-count. toolResult usage from other tools is
238
- * ignored for the same reason: those children also persist their own session files inside the scan.
238
+ * its own cwd. toolResult usage is ignored: those children persist their own session files inside
239
+ * the scan, so counting it would double their cost.
239
240
  *
240
241
  * shortcut: a file rewritten with the same size and mtime is not re-parsed.
241
242
  * shortcut: usage reported by tools whose child sessions live outside this dir is not counted.
@@ -285,8 +286,9 @@ export async function collectUsage(
285
286
 
286
287
  export function cacheView<T>(derive: () => T) {
287
288
  let cached: { key: string; value: T } | undefined;
288
- return (mode: GroupMode, filters: UsageFilter[], now = Date.now()): T => {
289
- const key = JSON.stringify([mode, filters, dayKey(now)]);
289
+ // `scope` is a grouping mode or the name of a non-grouping view.
290
+ return (scope: string, filters: UsageFilter[], now = Date.now()): T => {
291
+ const key = JSON.stringify([scope, filters, dayKey(now)]);
290
292
  if (!cached || cached.key !== key) cached = { key, value: derive() };
291
293
  return cached.value;
292
294
  };
@@ -303,7 +305,7 @@ export function startOfDay(ts: number): number {
303
305
  return date.getTime();
304
306
  }
305
307
 
306
- export function dayWindow(key: string, offset = 0): { since: number; until: number } {
308
+ export function dayWindow(key: string, offset = 0): TimeWindow {
307
309
  const date = new Date(`${key}T00:00`);
308
310
  date.setDate(date.getDate() + offset);
309
311
  const since = startOfDay(date.getTime());
@@ -329,7 +331,7 @@ export function matchesFilter(record: UsageRecord, filter: UsageFilter): boolean
329
331
  return recordKey(record, filter.mode) === filter.key;
330
332
  }
331
333
 
332
- export function usageWindow(records: UsageRecord[], day?: string, now = Date.now()) {
334
+ export function usageWindow(records: UsageRecord[], day?: string, now = Date.now()): TimeWindow {
333
335
  if (day) return dayWindow(day);
334
336
  const until = dayWindow(dayKey(now)).until;
335
337
  let first = Infinity;
@@ -386,12 +388,10 @@ export function buildRows(
386
388
  if (!group) {
387
389
  group = newTally();
388
390
  if (mode === "provider") group.models = new Map();
389
- if (mode === "model") group.providers = new Set();
390
391
  groups.set(key, group);
391
392
  }
392
393
  addStats(group.stats, record);
393
394
  group.requests += record.requests;
394
- if (mode === "model") group.providers!.add(record.provider);
395
395
  if (mode === "provider") {
396
396
  let model = group.models!.get(record.model);
397
397
  if (!model) group.models!.set(record.model, (model = newTally()));
@@ -418,7 +418,7 @@ export function buildRows(
418
418
  function toRow([name, group]: [string, Tally]): GroupRow {
419
419
  return {
420
420
  key: name,
421
- name: mode === "model" && group.providers!.size > 1 ? `${name} (${group.providers!.size})` : name,
421
+ name,
422
422
  stats: group.stats,
423
423
  requests: group.requests,
424
424
  children: group.models && [...group.models].map(toRow).sort(byCost),
@@ -441,46 +441,22 @@ export function summarize(records: UsageRecord[], sinceMs = 0, untilMs = Infinit
441
441
  return { stats, requests, sessions: sessions.size };
442
442
  }
443
443
 
444
- export function seriesKey(key: string, parent?: string): string {
445
- return JSON.stringify([key, parent ?? null]);
446
- }
447
-
448
- export function buildDailySeries(
449
- records: UsageRecord[],
450
- since: number,
451
- until: number,
452
- mode: GroupMode,
453
- ): { total: DailyCost[]; rows: Map<string, Map<number, number>> } {
454
- const days = windowDays(since, until);
455
- const total: DailyCost[] = [];
444
+ /** Total cost per local calendar day in `window`; without one, from the first recorded day through today. */
445
+ export function dailyTotals(records: UsageRecord[], window?: TimeWindow, now = Date.now()): DailyCost[] {
446
+ const { since, until } = window ?? usageWindow(records, undefined, now);
456
447
  const positions = new Map<string, number>();
448
+ const total: DailyCost[] = [];
457
449
  let cursor = since;
458
- for (let i = 0; i < days; i++) {
450
+ for (let day = windowDays(since, until); day > 0; day--) {
459
451
  const key = dayKey(cursor);
460
- positions.set(key, i);
461
- total.push({ label: key.slice(5), cost: 0 });
452
+ positions.set(key, total.length);
453
+ total.push({ label: key, cost: 0 });
462
454
  cursor = dayWindow(key).until;
463
455
  }
464
- const costs = new Map<string, Map<number, number>>();
465
- function add(key: string, index: number, cost: number): void {
466
- let values = costs.get(key);
467
- if (!values) costs.set(key, (values = new Map()));
468
- values.set(index, (values.get(index) ?? 0) + cost);
469
- }
470
456
  for (const record of records) {
471
457
  if (record.ts < since || record.ts >= until) continue;
472
458
  const index = positions.get(dayKey(record.ts));
473
- if (index === undefined) continue;
474
- total[index]!.cost += record.cost;
475
- const key = recordKey(record, mode);
476
- add(seriesKey(key), index, record.cost);
477
- if (mode === "provider") add(seriesKey(record.model, record.provider), index, record.cost);
459
+ if (index !== undefined) total[index]!.cost += record.cost;
478
460
  }
479
- return { total, rows: costs };
480
- }
481
-
482
- /** Total cost per local calendar day from the first recorded day through today. */
483
- export function dailyTotals(records: UsageRecord[], now = Date.now()): DailyCost[] {
484
- const { since, until } = usageWindow(records, undefined, now);
485
- return buildDailySeries(records, since, until, "day").total;
461
+ return total;
486
462
  }