@deathbeam/pi-usage 0.0.5 → 0.0.7

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
@@ -15,7 +15,7 @@ Use the `/usage` command for a fullscreen dashboard of token usage and costs.
15
15
  | Page Up / Page Down | Move by a page |
16
16
  | `g` / `G` | Move to the first / last row |
17
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.
18
+ 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.
19
19
 
20
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
21
 
package/index.ts CHANGED
@@ -6,17 +6,15 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
6
6
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
7
7
  import { matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
8
8
  import {
9
- bucketCosts,
10
- buildDailySeries,
11
9
  buildRows,
12
10
  cacheView,
13
11
  collectUsage,
14
12
  comparison,
13
+ dailyTotals,
15
14
  dayKey,
16
15
  dayWindow,
17
16
  matchesFilter,
18
17
  percentChange,
19
- seriesKey,
20
18
  summarize,
21
19
  usageWindow,
22
20
  type DailyCost,
@@ -25,7 +23,7 @@ import {
25
23
  type Stats,
26
24
  type UsageFilter,
27
25
  type UsageRecord,
28
- } from "./usage.ts";
26
+ } from "./src/usage.ts";
29
27
 
30
28
  type Column = {
31
29
  label: string;
@@ -124,17 +122,20 @@ function tableLine(nameWidth: number, columns: Column[], row: GroupRow, totalCos
124
122
  .trimEnd();
125
123
  }
126
124
 
127
- function sparkline(daily: DailyCost[], width: number): { first: string; bars: string; last: string } | undefined {
128
- if (daily.length <= 1) return undefined;
129
- const first = daily[0]!.label;
130
- const last = daily[daily.length - 1]!.label;
131
- const bars = bucketCosts(daily, Math.ceil(daily.length / Math.max(1, width - 12)));
125
+ type SparkBar = { label: string; char: string };
126
+
127
+ function sparkline(daily: DailyCost[], width: number): { first: string; last: string; bars: SparkBar[] } | undefined {
128
+ const recent = daily.slice(-Math.max(1, width - 12));
129
+ if (recent.length === 0) return undefined;
132
130
  let max = 0;
133
- for (const bar of bars) if (bar.cost > max) max = bar.cost;
131
+ for (const day of recent) if (day.cost > max) max = day.cost;
134
132
  return {
135
- first,
136
- bars: bars.map((d) => (d.cost <= 0 ? " " : SPARK_BARS[Math.max(1, Math.round((7 * d.cost) / max))])).join(""),
137
- last,
133
+ first: recent[0]!.label,
134
+ last: recent[recent.length - 1]!.label,
135
+ bars: recent.map(({ label, cost }) => ({
136
+ label,
137
+ char: cost <= 0 ? " " : SPARK_BARS[Math.max(1, Math.round((7 * cost) / max))]!,
138
+ })),
138
139
  };
139
140
  }
140
141
 
@@ -157,12 +158,16 @@ export default function (pi: ExtensionAPI) {
157
158
  total: 0,
158
159
  };
159
160
  let render = () => {};
160
- // Scanning on open is fast enough for a dashboard; no cache file.
161
- const loaded = collectUsage(join(getAgentDir(), "sessions"), (done, total) => {
162
- state.done = done;
163
- state.total = total;
164
- render();
165
- }).then((records) => {
161
+ const agentDir = getAgentDir();
162
+ const loaded = collectUsage(
163
+ join(agentDir, "sessions"),
164
+ (done, total) => {
165
+ state.done = done;
166
+ state.total = total;
167
+ render();
168
+ },
169
+ join(agentDir, "usage-cache.json"),
170
+ ).then((records) => {
166
171
  state.records = records;
167
172
  });
168
173
  const screen = {
@@ -189,10 +194,11 @@ export default function (pi: ExtensionAPI) {
189
194
  const mode = GROUPS[group]!;
190
195
  const summary = summarize(records, window.since, window.until);
191
196
  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) };
197
+ return { mode, summary, body, compare: day ? undefined : comparison(records) };
194
198
  };
195
199
  const getView = cacheView(() => derive(state.records!));
200
+ let allDays: DailyCost[] | undefined;
201
+ const allDaily = () => (allDays ??= dailyTotals(state.records!));
196
202
  render = () => tui.requestRender();
197
203
  void loaded.then(render);
198
204
  const colorDelta = (delta: number | undefined): string => {
@@ -251,7 +257,7 @@ export default function (pi: ExtensionAPI) {
251
257
  return lines.slice(0, rows);
252
258
  }
253
259
  const view = getView(GROUPS[group]!, filters());
254
- const { mode, summary, series, compare } = view;
260
+ const { mode, summary, compare } = view;
255
261
  const first = compare
256
262
  ? `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
263
  : `Cost ${formatCost(summary.stats.cost)}`;
@@ -266,15 +272,24 @@ export default function (pi: ExtensionAPI) {
266
272
  rowCount = body.length;
267
273
  cursor = Math.min(cursor, Math.max(0, rowCount - 1));
268
274
  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);
275
+ const contextDay = dayFilter()?.key ?? (mode === "day" ? selected?.key : undefined);
276
+ const contextLabel = contextDay?.slice(5);
277
+ const spark = sparkline(allDaily(), width);
274
278
  if (spark)
275
279
  lines.push(
276
280
  truncateToWidth(
277
- `${theme.fg("dim", `${spark.first} `)}${theme.fg("accent", spark.bars)}${theme.fg("dim", ` ${spark.last}`)}`,
281
+ theme.fg("dim", `${spark.first} `) +
282
+ spark.bars
283
+ .map((bar) =>
284
+ theme.fg(
285
+ contextLabel === undefined || bar.label === contextLabel
286
+ ? "accent"
287
+ : "borderMuted",
288
+ bar.char,
289
+ ),
290
+ )
291
+ .join("") +
292
+ theme.fg("dim", ` ${spark.last}`),
278
293
  width,
279
294
  ),
280
295
  );
@@ -338,7 +353,10 @@ export default function (pi: ExtensionAPI) {
338
353
  row.parent === undefined ? [] : [{ mode: "provider", key: row.parent }];
339
354
  selected.push({ mode: rowMode, key: row.key });
340
355
  stack.push({ filters: selected, group, cursor, top });
341
- group = rowMode === "day" ? 1 : 0;
356
+ // Land on the first grouping that is not already filtered.
357
+ const used = new Set(filters().map((f) => f.mode));
358
+ group = GROUPS.findIndex((g) => !used.has(g));
359
+ if (group < 0) group = dayFilter() ? 1 : 0;
342
360
  cursor = top = 0;
343
361
  } else if ((data === "[" || data === "]") && filters().at(-1)?.mode === "day") {
344
362
  const filter = filters().at(-1)!;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deathbeam/pi-usage",
3
- "version": "0.0.5",
3
+ "version": "0.0.7",
4
4
  "description": "Minimal extension for token usage and cost per provider, model and project.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -18,7 +18,7 @@
18
18
  },
19
19
  "files": [
20
20
  "index.ts",
21
- "usage.ts",
21
+ "src",
22
22
  "README.md",
23
23
  "LICENSE"
24
24
  ],
@@ -1,9 +1,10 @@
1
1
  /** Usage aggregation over Pi's persisted session JSONL files. */
2
2
 
3
+ import { randomUUID } from "node:crypto";
3
4
  import { createReadStream } from "node:fs";
4
- import { readdir } from "node:fs/promises";
5
+ import { readdir, readFile, rename, stat, unlink, writeFile } from "node:fs/promises";
5
6
  import { createInterface } from "node:readline";
6
- import { join } from "node:path";
7
+ import { dirname, join } from "node:path";
7
8
 
8
9
  export type UsageRecord = {
9
10
  provider: string;
@@ -28,7 +29,7 @@ export type Stats = {
28
29
  cacheWrite: number;
29
30
  };
30
31
 
31
- export function emptyStats(): Stats {
32
+ function emptyStats(): Stats {
32
33
  return { cost: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
33
34
  }
34
35
 
@@ -50,6 +51,80 @@ async function sessionFiles(dir: string, out: string[]): Promise<void> {
50
51
  }
51
52
  }
52
53
 
54
+ type CacheEntry = { size: number; mtimeMs: number; records: UsageRecord[] };
55
+ type Cache = { version: number; files: Record<string, CacheEntry> };
56
+
57
+ const CACHE_VERSION = 1;
58
+
59
+ async function readCache(file: string): Promise<Record<string, CacheEntry>> {
60
+ try {
61
+ const cache = JSON.parse(await readFile(file, "utf8")) as Cache;
62
+ if (cache?.version !== CACHE_VERSION || typeof cache.files !== "object" || cache.files === null) return {};
63
+ return cache.files;
64
+ } catch {
65
+ return {};
66
+ }
67
+ }
68
+
69
+ async function writeCache(file: string, files: Record<string, CacheEntry>): Promise<void> {
70
+ const temp = join(dirname(file), `.tmp-${randomUUID()}`);
71
+ try {
72
+ await writeFile(temp, JSON.stringify({ version: CACHE_VERSION, files } satisfies Cache));
73
+ await rename(temp, file);
74
+ } catch {
75
+ await unlink(temp).catch(() => undefined);
76
+ }
77
+ }
78
+
79
+ /** Throws only on read errors, so a partial parse is never cached. */
80
+ async function parseFile(file: string): Promise<UsageRecord[]> {
81
+ const records: UsageRecord[] = [];
82
+ let cwd = "";
83
+ let sessionId = "";
84
+ const lines = createInterface({ input: createReadStream(file, "utf8"), crlfDelay: Infinity });
85
+ for await (const line of lines) {
86
+ // Cheap prefilter: escaped JSON inside tool results never matches this literal.
87
+ if (!line.includes('"role":"assistant"')) {
88
+ // The session header (type:"session", cwd, id) is normally the first line.
89
+ if (sessionId === "" && line.includes('"type":"session"')) {
90
+ try {
91
+ const header = JSON.parse(line);
92
+ if (header?.type === "session") {
93
+ cwd = String(header.cwd ?? "");
94
+ sessionId = String(header.id ?? "");
95
+ }
96
+ } catch {
97
+ // malformed header line: keep scanning for a later one
98
+ }
99
+ }
100
+ continue;
101
+ }
102
+ let entry: any;
103
+ try {
104
+ entry = JSON.parse(line);
105
+ } catch {
106
+ continue;
107
+ }
108
+ const msg = entry?.message;
109
+ const usage = msg?.usage;
110
+ if (!usage || !msg.provider || !msg.model) continue;
111
+ const cost = typeof usage.cost === "number" ? usage.cost : num(usage.cost?.total);
112
+ records.push({
113
+ provider: String(msg.provider),
114
+ model: String(msg.model),
115
+ ts: num(msg.timestamp),
116
+ cost,
117
+ input: num(usage.input),
118
+ output: num(usage.output),
119
+ cacheRead: num(usage.cacheRead),
120
+ cacheWrite: num(usage.cacheWrite),
121
+ cwd,
122
+ sessionId,
123
+ });
124
+ }
125
+ return records;
126
+ }
127
+
53
128
  /**
54
129
  * One record per assistant message that carries usage, from every session file under `dir`.
55
130
  *
@@ -59,65 +134,47 @@ async function sessionFiles(dir: string, out: string[]): Promise<void> {
59
134
  * its own cwd. Parent sessions never embed the delegate child's usage (the delegate tool result
60
135
  * carries only text), so there is nothing to double-count. toolResult usage from other tools is
61
136
  * ignored for the same reason: those children also persist their own session files inside the scan.
137
+ *
138
+ * shortcut: a file rewritten with the same size and mtime is not re-parsed.
62
139
  * shortcut: usage reported by tools whose child sessions live outside this dir is not counted.
63
140
  */
64
141
  export async function collectUsage(
65
142
  dir: string,
66
143
  onProgress?: (done: number, total: number) => void,
144
+ cacheFile?: string,
67
145
  ): Promise<UsageRecord[]> {
68
146
  const files: string[] = [];
69
147
  await sessionFiles(dir, files);
148
+ const cached = cacheFile ? await readCache(cacheFile) : {};
149
+ const next: Record<string, CacheEntry> = {};
70
150
  const records: UsageRecord[] = [];
151
+ let dirty = false;
71
152
  for (const [done, file] of files.entries()) {
72
153
  onProgress?.(done, files.length);
73
- let cwd = "";
74
- let sessionId = "";
154
+ let info;
75
155
  try {
76
- const lines = createInterface({ input: createReadStream(file, "utf8"), crlfDelay: Infinity });
77
- for await (const line of lines) {
78
- // Cheap prefilter: escaped JSON inside tool results never matches this literal.
79
- if (!line.includes('"role":"assistant"')) {
80
- // The session header (type:"session", cwd, id) is normally the first line.
81
- if (sessionId === "" && line.includes('"type":"session"')) {
82
- try {
83
- const header = JSON.parse(line);
84
- if (header?.type === "session") {
85
- cwd = String(header.cwd ?? "");
86
- sessionId = String(header.id ?? "");
87
- }
88
- } catch {
89
- // malformed header line: keep scanning for a later one
90
- }
91
- }
92
- continue;
93
- }
94
- let entry: any;
95
- try {
96
- entry = JSON.parse(line);
97
- } catch {
98
- continue;
99
- }
100
- const msg = entry?.message;
101
- const usage = msg?.usage;
102
- if (!usage || !msg.provider || !msg.model) continue;
103
- const cost = typeof usage.cost === "number" ? usage.cost : num(usage.cost?.total);
104
- records.push({
105
- provider: String(msg.provider),
106
- model: String(msg.model),
107
- ts: num(msg.timestamp),
108
- cost,
109
- input: num(usage.input),
110
- output: num(usage.output),
111
- cacheRead: num(usage.cacheRead),
112
- cacheWrite: num(usage.cacheWrite),
113
- cwd,
114
- sessionId,
115
- });
116
- }
156
+ info = await stat(file);
157
+ } catch {
158
+ dirty = true;
159
+ continue;
160
+ }
161
+ const hit = cached[file];
162
+ if (hit?.size === info.size && hit.mtimeMs === info.mtimeMs && Array.isArray(hit.records)) {
163
+ next[file] = hit;
164
+ for (const record of hit.records) records.push(record);
165
+ continue;
166
+ }
167
+ dirty = true;
168
+ try {
169
+ const parsed = await parseFile(file);
170
+ next[file] = { size: info.size, mtimeMs: info.mtimeMs, records: parsed };
171
+ for (const record of parsed) records.push(record);
117
172
  } catch {
118
173
  continue; // unreadable or truncated file: skip it, keep what other files gave
119
174
  }
120
175
  }
176
+ if (!cacheFile) return records;
177
+ if (dirty || Object.keys(next).length !== Object.keys(cached).length) await writeCache(cacheFile, next);
121
178
  return records;
122
179
  }
123
180
 
@@ -146,15 +203,18 @@ export function dayKey(ts: number): string {
146
203
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
147
204
  }
148
205
 
206
+ export function startOfDay(ts: number): number {
207
+ const date = new Date(ts);
208
+ date.setHours(0, 0, 0, 0);
209
+ return date.getTime();
210
+ }
211
+
149
212
  export function dayWindow(key: string, offset = 0): { since: number; until: number } {
150
213
  const date = new Date(`${key}T00:00`);
151
214
  date.setDate(date.getDate() + offset);
152
- date.setHours(0, 0, 0, 0);
153
- const since = date.getTime();
215
+ const since = startOfDay(date.getTime());
154
216
  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() };
217
+ return { since, until: startOfDay(date.getTime()) };
158
218
  }
159
219
 
160
220
  // UTC ordinals count local calendar days without DST changing their length.
@@ -191,16 +251,13 @@ export function comparison(records: UsageRecord[], now = Date.now()) {
191
251
  const { since: today, until } = dayWindow(dayKey(now));
192
252
  const week = new Date(today);
193
253
  week.setDate(week.getDate() - ((week.getDay() + 6) % 7));
194
- week.setHours(0, 0, 0, 0);
195
- const weekStart = week.getTime();
254
+ const weekStart = startOfDay(week.getTime());
196
255
  const lastWeek = dayWindow(dayKey(weekStart), -7).since;
197
256
  const month = new Date(today);
198
257
  month.setDate(1);
199
- month.setHours(0, 0, 0, 0);
200
- const monthStart = month.getTime();
258
+ const monthStart = startOfDay(month.getTime());
201
259
  month.setMonth(month.getMonth() - 1);
202
- month.setHours(0, 0, 0, 0);
203
- const lastMonth = month.getTime();
260
+ const lastMonth = startOfDay(month.getTime());
204
261
  let todayCost = 0,
205
262
  weekCost = 0,
206
263
  lastWeekCost = 0,
@@ -302,8 +359,6 @@ export type Summary = {
302
359
  requests: number;
303
360
  /** Distinct session ids (files) seen in the window. */
304
361
  sessions: number;
305
- /** cacheRead / (input + cacheRead + cacheWrite); 0 without any tokens. */
306
- hit: number;
307
362
  };
308
363
 
309
364
  /** Totals for the summary block: one pass over [sinceMs, untilMs). */
@@ -317,13 +372,7 @@ export function summarize(records: UsageRecord[], sinceMs = 0, untilMs = Infinit
317
372
  requests++;
318
373
  sessions.add(record.sessionId);
319
374
  }
320
- const cacheTotal = stats.input + stats.cacheRead + stats.cacheWrite;
321
- return {
322
- stats,
323
- requests,
324
- sessions: sessions.size,
325
- hit: cacheTotal > 0 ? stats.cacheRead / cacheTotal : 0,
326
- };
375
+ return { stats, requests, sessions: sessions.size };
327
376
  }
328
377
 
329
378
  export type DailyCost = { label: string; cost: number };
@@ -364,13 +413,8 @@ export function buildDailySeries(
364
413
  return { total, rows: costs };
365
414
  }
366
415
 
367
- /** Sum `perBar` consecutive daily buckets into one bar, labeled by its first day. */
368
- export function bucketCosts(days: DailyCost[], perBar: number): DailyCost[] {
369
- if (perBar <= 1) return days;
370
- const bars: DailyCost[] = [];
371
- for (let i = 0; i < days.length; i += perBar) {
372
- const group = days.slice(i, i + perBar);
373
- bars.push({ label: group[0]!.label, cost: group.reduce((sum, d) => sum + d.cost, 0) });
374
- }
375
- return bars;
416
+ /** Total cost per local calendar day from the first recorded day through today. */
417
+ export function dailyTotals(records: UsageRecord[], now = Date.now()): DailyCost[] {
418
+ const { since, until } = usageWindow(records, undefined, now);
419
+ return buildDailySeries(records, since, until, "day").total;
376
420
  }