@bismawy/pi-arnative 0.10.0 → 0.11.0

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.
@@ -4,11 +4,22 @@
4
4
  * - mtime+size keyed cache in ~/.pi/agent/arnative/usage-cache.json, read into
5
5
  * memory once (parsing 4MB per header frame cost ~50ms and lagged long chats).
6
6
  * - No double counting: the active session is already in its own file, so it is
7
- * NOT re-added from sessionManager (that inflated the ↑↓ totals).
7
+ * NOT re-added from sessionManager (that inflated the ↑↓ totals), and a subagent's
8
+ * spend is read from the child's own session file, never from the parent's tool result. Child spend
9
+ * (subagent / nested tool calls) rides on the tool result only, never on an
10
+ * assistant message, so summing both roles counts it once.
11
+ * - Rollups also keep per-day buckets (UTC) and the session cwd, so /usage can answer
12
+ * "today", the range bar (All/Today/7d/30d/3m) and "per project" from the cache without a
13
+ * full re-scan.
14
+ * - A statistics reset writes `usage-baseline.json`: the summary subtracts the baseline
15
+ * rollup per file, so earlier messages stop counting in every view while the session
16
+ * files stay untouched (see {@link resetUsageStats}).
8
17
  */
9
- import { closeSync, copyFileSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
18
+ import { closeSync, existsSync, fstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
19
+ import { tmpdir } from "node:os";
10
20
  import { join, relative } from "node:path";
11
21
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
22
+ import { assert, isMain } from "./check.ts";
12
23
 
13
24
  interface UsageEntry {
14
25
  provider: string;
@@ -16,40 +27,23 @@ interface UsageEntry {
16
27
  input: number;
17
28
  output: number;
18
29
  cacheRead: number;
30
+ cacheWrite: number;
19
31
  cost: number;
20
- /** Local day (YYYY-MM-DD) the message was written, so a range view can skip it. */
32
+ /** True when `cost` is the provider-billed total (`totalFromProvider`); false when it is a catalog estimate. */
33
+ billed: boolean;
34
+ /** UTC day bucket (`YYYY-MM-DD`) the message counts in. A line without a usable
35
+ * timestamp inherits the file's mtime day (`fallbackDay`), like the range feature
36
+ * always did — an undated record must not fall into 1970 and vanish from every window. */
21
37
  day: string;
22
38
  }
23
39
 
24
- /** A time window the dashboard can show. `all` is the whole history. */
25
- export type UsageRange = "all" | "today" | "7d" | "30d" | "3m";
26
-
27
- /** Tab order of the range bar. */
28
- export const USAGE_RANGES: readonly UsageRange[] = ["all", "today", "7d", "30d", "3m"];
29
-
30
- /** Local calendar day of a timestamp, the unit day buckets and ranges are compared in. */
31
- export function dayKey(ms: number): string {
32
- const d = new Date(ms);
33
- const pad = (n: number): string => String(n).padStart(2, "0");
34
- return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
35
- }
36
-
37
- /** Local midnight where `range` starts: today, 7 or 30 calendar days back, 3 months back.
38
- * `undefined` for `all`, which has no floor. */
39
- export function rangeStart(range: UsageRange, now = Date.now()): number | undefined {
40
- if (range === "all") return undefined;
41
- const d = new Date(now);
42
- d.setHours(0, 0, 0, 0);
43
- if (range === "today") return d.getTime();
44
- if (range === "3m") d.setMonth(d.getMonth() - 3);
45
- else d.setDate(d.getDate() - (range === "7d" ? 6 : 29));
46
- return d.getTime();
47
- }
48
-
49
40
  interface FileCacheItem {
50
41
  mtimeMs: number;
51
42
  size: number;
52
43
  v?: number;
44
+ /** The session's cwd, from the first line of the file. Absent on a tail-only parse, where
45
+ * the value already stored in the cache item is kept (the head is not re-read). */
46
+ cwd?: string;
53
47
  /** Byte offset of the last complete line parsed. Session files are append-only, so a
54
48
  * grown file only needs its tail read — re-parsing the whole 1MB+ active session on the
55
49
  * 5s render path cost ~15ms and grew with chat length. */
@@ -60,64 +54,87 @@ interface FileCacheItem {
60
54
  rollup: FileRollup;
61
55
  }
62
56
 
63
- /** Usage totals for one session file, per provider and per provider+model. */
57
+ /** Usage totals for one session file, per provider and per provider+model, plus per-day rows. */
64
58
  interface FileRollup {
65
59
  providers: Record<string, Rollup>;
66
- /** provider\0model key -> day -> totals. Absent on an item cached before ranges
67
- * existed; that item is re-parsed once so a range view never reads a wrong number. */
68
- days?: Record<string, Record<string, Buckets>>;
60
+ /** Day buckets keyed `YYYY-MM-DD\0provider\0model` (UTC day — see dayKey), so the disk `d`
61
+ * map reuses the provider rows' compact array and a day's totals are the sum of its rows. */
62
+ days: Record<string, Rollup>;
69
63
  }
70
64
 
71
- /** One day's totals for one provider\0model key. */
72
- type Buckets = { msgs: number; input: number; output: number; cacheRead: number; cost: number };
73
-
74
65
  interface Rollup {
75
66
  sessions: number;
76
67
  msgs: number;
77
68
  input: number;
78
69
  output: number;
79
70
  cacheRead: number;
71
+ cacheWrite: number;
72
+ /** Sum of `cost.total`, billed plus catalog estimates, exactly as pi reported them. */
80
73
  cost: number;
74
+ /** The billed subset of `cost`; `cost - billed` is the catalog-estimate part. */
75
+ billed: number;
81
76
  }
82
77
 
83
- const emptyRollup = (): Rollup => ({ sessions: 0, msgs: 0, input: 0, output: 0, cacheRead: 0, cost: 0 });
78
+ const emptyRollup = (): Rollup => ({ sessions: 0, msgs: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, billed: 0 });
84
79
 
85
80
  function addToRollup(r: Rollup, e: UsageEntry): void {
86
81
  r.msgs++;
87
82
  r.input += e.input;
88
83
  r.output += e.output;
89
84
  r.cacheRead += e.cacheRead;
85
+ r.cacheWrite += e.cacheWrite;
90
86
  r.cost += e.cost;
87
+ r.billed += e.billed ? e.cost : 0;
91
88
  }
92
89
 
93
- const emptyBuckets = (): Buckets => ({ msgs: 0, input: 0, output: 0, cacheRead: 0, cost: 0 });
90
+ /** A time window the dashboard can show. `all` is the whole history. */
91
+ export type UsageRange = "all" | "today" | "7d" | "30d" | "3m";
92
+
93
+ /** Tab order of the range bar. */
94
+ export const USAGE_RANGES: readonly UsageRange[] = ["all", "today", "7d", "30d", "3m"];
94
95
 
95
- /** Fold entries into an existing file rollup, updating provider and provider+model keys together. */
96
+ /** UTC day bucket key (`YYYY-MM-DD`) of a timestamp. UTC on purpose: local time would make the
97
+ * on-disk cache depend on the timezone of the machine that wrote it, so a restore elsewhere
98
+ * would re-bucket every entry. Exported for the range bar, whose windows share the buckets. */
99
+ export function dayKey(ms: number): string {
100
+ return new Date(ms > 0 ? ms : 0).toISOString().slice(0, 10);
101
+ }
102
+
103
+ /** UTC midnight where `range` starts: today, 7 or 30 calendar days back, 3 months back.
104
+ * `undefined` for `all`, which has no floor. UTC to match the day buckets: a local-midnight
105
+ * floor would cut a UTC+7 "today" at 7am local and drop the morning's spend. */
106
+ export function rangeStart(range: UsageRange, now = Date.now()): number | undefined {
107
+ if (range === "all") return undefined;
108
+ const d = new Date(now);
109
+ d.setUTCHours(0, 0, 0, 0);
110
+ if (range === "today") return d.getTime();
111
+ if (range === "3m") d.setUTCMonth(d.getUTCMonth() - 3);
112
+ else d.setUTCDate(d.getUTCDate() - (range === "7d" ? 6 : 29));
113
+ return d.getTime();
114
+ }
115
+
116
+ /** Fold entries into an existing file rollup, updating provider, provider+model and day keys
117
+ * together in one pass over the entries. */
96
118
  function foldInto(rollup: FileRollup, entries: UsageEntry[]): void {
97
119
  if (entries.length === 0) return;
98
120
  for (const e of entries) {
99
121
  const key = `${e.provider}\u0000${e.model}`;
100
- for (const k of [e.provider, key]) {
101
- (rollup.providers[k] ??= emptyRollup());
102
- addToRollup(rollup.providers[k]!, e);
103
- }
104
- // Day buckets are stored on the model key only: the provider row is their sum, so a
105
- // long history is not written twice to disk.
106
- const perDay = ((rollup.days ??= {})[key] ??= {});
107
- const day = (perDay[e.day] ??= emptyBuckets());
108
- day.msgs++;
109
- day.input += e.input;
110
- day.output += e.output;
111
- day.cacheRead += e.cacheRead;
112
- day.cost += e.cost;
122
+ (rollup.providers[e.provider] ??= emptyRollup());
123
+ addToRollup(rollup.providers[e.provider]!, e);
124
+ (rollup.providers[key] ??= emptyRollup());
125
+ addToRollup(rollup.providers[key]!, e);
126
+ const day = `${e.day}\u0000${key}`;
127
+ (rollup.days[day] ??= emptyRollup());
128
+ addToRollup(rollup.days[day]!, e);
113
129
  }
114
130
  // `sessions` counts the file, not the messages, so it is 1 once the file has any use.
115
131
  for (const key of Object.keys(rollup.providers)) rollup.providers[key]!.sessions = 1;
132
+ for (const key of Object.keys(rollup.days)) rollup.days[key]!.sessions = 1;
116
133
  }
117
134
 
118
135
  /** The rollup of a freshly parsed file (a foldInto that starts from nothing). */
119
136
  function rollupOfFile(entries: UsageEntry[]): FileRollup {
120
- const rollup: FileRollup = { providers: {} };
137
+ const rollup: FileRollup = { providers: {}, days: {} };
121
138
  foldInto(rollup, entries);
122
139
  return rollup;
123
140
  }
@@ -129,10 +146,11 @@ interface UsageModelStats {
129
146
  input: number;
130
147
  output: number;
131
148
  cacheRead: number;
132
- /** Prompt + completion + cache reads: the same total a vendor dashboard reports. */
149
+ cacheWrite: number;
133
150
  totalTokens: number;
151
+ /** Billed cost only (`totalFromProvider`); catalog estimates live in `estimatedCost`. */
134
152
  cost: number;
135
- /** Cost reconstructed from the price table, only when `cost` is 0. Never folded into `cost`. */
153
+ /** Catalog totals plus the price-table reconstruction for rows that carried no cost at all. Never folded into `cost`. */
136
154
  estimatedCost: number;
137
155
  }
138
156
 
@@ -145,13 +163,41 @@ interface UsageProviderStats {
145
163
  cacheRead: number;
146
164
  totalTokens: number;
147
165
  cost: number;
148
- /** Sum of the models' `estimatedCost`, for the same rows this provider could not price. */
166
+ /** Sum of the models' `estimatedCost`, for the same rows this provider could not bill. */
149
167
  estimatedCost: number;
150
168
  models: UsageModelStats[];
151
169
  }
152
170
 
171
+ /** Per-project (cwd) stats: the same fields as a provider row, with the providers seen in that
172
+ * project as its children, so `/usage` can tree Project → Provider. */
173
+ export interface UsageProjectStats {
174
+ name: string;
175
+ sessions: number;
176
+ msgs: number;
177
+ input: number;
178
+ output: number;
179
+ cacheRead: number;
180
+ totalTokens: number;
181
+ cost: number;
182
+ estimatedCost: number;
183
+ providers: UsageProviderStats[];
184
+ }
185
+
186
+ /** One day-window total, summed from the day buckets. */
187
+ export interface UsageDayWindow {
188
+ /** Billed cost only, like the summary's `cost`. */
189
+ cost: number;
190
+ /** Catalog-estimated cost in the same window: a budget warns on it, never blocks. */
191
+ estimated: number;
192
+ input: number;
193
+ output: number;
194
+ cacheRead: number;
195
+ }
196
+
153
197
  export interface UsageSummary {
154
198
  providers: UsageProviderStats[];
199
+ /** Per-project rollup; `"unknown"` for files whose header carried no cwd. */
200
+ projects: UsageProjectStats[];
155
201
  totals: {
156
202
  sessions: number;
157
203
  msgs: number;
@@ -159,29 +205,49 @@ export interface UsageSummary {
159
205
  output: number;
160
206
  cacheRead: number;
161
207
  totalTokens: number;
208
+ /** Billed cost only (`totalFromProvider`); never includes the estimate. */
162
209
  cost: number;
163
- /** Provider-reported cost only (never includes the estimate). */
210
+ /** Same billed total under its old name. */
164
211
  reportedCost: number;
165
- /** Cost reconstructed from `models.json` rates. Shown with a `~`, never folded into `cost`. */
212
+ /** Catalog totals plus cost reconstructed from `models.json` rates. Shown with a `~`, never folded into `cost`. */
166
213
  estimatedCost: number;
214
+ /** Day-bucket windows, present only when the scan saw day buckets (a v8 cache). */
215
+ today?: UsageDayWindow;
216
+ last7d?: UsageDayWindow;
217
+ last30d?: UsageDayWindow;
167
218
  };
168
219
  }
169
220
 
170
- export type ModelPrices = Record<string, { input?: number; output?: number; cacheRead?: number }>;
221
+ export type ModelPrices = Record<string, { input?: number; output?: number; cacheRead?: number; cacheWrite?: number }>;
171
222
  export type PriceTable = Record<string, ModelPrices>;
172
223
 
173
224
  const modelsFilePath = (): string => join(getAgentDir(), "models.json");
174
225
 
175
- type ModelsJsonCost = { input?: number; output?: number; cacheRead?: number };
226
+ type ModelsJsonCost = { input?: number; output?: number; cacheRead?: number; cacheWrite?: number };
227
+
228
+ /** Memo of the last price-table read, keyed by the models.json path + mtimeMs + size: one
229
+ * `statSync` per call instead of a `readFileSync` on every footer frame. Cleared by
230
+ * `resetUsageCache()` so the self-checks see a cold read after changing the fixture. */
231
+ let priceMemo: { key: string; table: PriceTable } | null = null;
176
232
 
177
233
  /**
178
234
  * Rates declared automatically in pi's `models.json` (`providers.<name>.models[].cost`).
179
- * Keyed by provider to reconstruct estimates for historical or 0-cost rows.
235
+ * Keyed by provider to reconstruct estimates for historical or 0-cost rows. Memoized on the
236
+ * file's stat, so an unchanged file is parsed once, not once per caller.
180
237
  */
181
238
  export function loadPriceTable(): PriceTable {
239
+ const path = modelsFilePath();
240
+ let key: string;
241
+ try {
242
+ const st = statSync(path);
243
+ key = `${path}\u0000${st.mtimeMs}\u0000${st.size}`;
244
+ } catch {
245
+ key = `${path}\u0000absent`;
246
+ }
247
+ if (priceMemo && priceMemo.key === key) return priceMemo.table;
182
248
  const table: PriceTable = {};
183
249
  try {
184
- const raw = JSON.parse(readFileSync(modelsFilePath(), "utf8")) as {
250
+ const raw = JSON.parse(readFileSync(path, "utf8")) as {
185
251
  providers?: Record<string, { models?: { id?: string; cost?: ModelsJsonCost }[] }>;
186
252
  };
187
253
  for (const [provider, cfg] of Object.entries(raw.providers ?? {})) {
@@ -189,27 +255,40 @@ export function loadPriceTable(): PriceTable {
189
255
  for (const m of cfg?.models ?? []) {
190
256
  const c = m?.cost;
191
257
  if (!m?.id || !c || typeof c.input !== "number" || typeof c.output !== "number") continue;
192
- models[m.id] = { input: c.input, output: c.output, cacheRead: typeof c.cacheRead === "number" ? c.cacheRead : 0 };
258
+ models[m.id] = {
259
+ input: c.input,
260
+ output: c.output,
261
+ cacheRead: typeof c.cacheRead === "number" ? c.cacheRead : 0,
262
+ cacheWrite: typeof c.cacheWrite === "number" ? c.cacheWrite : 0,
263
+ };
193
264
  }
194
265
  if (Object.keys(models).length > 0) table[provider] = models;
195
266
  }
196
267
  } catch {
197
268
  // Malformed or absent models.json means no declared rates.
198
269
  }
270
+ priceMemo = { key, table };
199
271
  return table;
200
272
  }
201
273
 
202
- /** True when this provider+model has a usable input+output price (cacheRead is optional). */
274
+ /** True when this provider+model has a usable input+output price (cacheRead/cacheWrite are optional). */
203
275
  export function hasPrice(provider: string, modelId: string, table: PriceTable = loadPriceTable()): boolean {
204
276
  return findPrice(provider, modelId, table) !== null;
205
277
  }
206
278
 
207
279
  /** Rates for one provider+model. The provider's own entry wins over the `*` fallback. */
208
- function findPrice(provider: string, modelId: string, table: PriceTable): { input: number; output: number; cacheRead: number } | null {
280
+ function findPrice(
281
+ provider: string,
282
+ modelId: string,
283
+ table: PriceTable,
284
+ ): { input: number; output: number; cacheRead: number; cacheWrite: number } | null {
209
285
  return rateFor(table[provider], modelId) ?? rateFor(table["*"], modelId);
210
286
  }
211
287
 
212
- function rateFor(entries: ModelPrices | undefined, modelId: string): { input: number; output: number; cacheRead: number } | null {
288
+ function rateFor(
289
+ entries: ModelPrices | undefined,
290
+ modelId: string,
291
+ ): { input: number; output: number; cacheRead: number; cacheWrite: number } | null {
213
292
  if (!entries || typeof entries !== "object") return null;
214
293
  const lower = modelId.toLowerCase();
215
294
  const keys = Object.keys(entries).filter((k) => !k.startsWith("_"));
@@ -219,7 +298,12 @@ function rateFor(entries: ModelPrices | undefined, modelId: string): { input: nu
219
298
  if (!key) return null;
220
299
  const p = entries[key]!;
221
300
  if (typeof p.input !== "number" || typeof p.output !== "number") return null;
222
- return { input: p.input, output: p.output, cacheRead: typeof p.cacheRead === "number" ? p.cacheRead : 0 };
301
+ return {
302
+ input: p.input,
303
+ output: p.output,
304
+ cacheRead: typeof p.cacheRead === "number" ? p.cacheRead : 0,
305
+ cacheWrite: typeof p.cacheWrite === "number" ? p.cacheWrite : 0,
306
+ };
223
307
  }
224
308
 
225
309
  /** Cost of one provider+model's token counts from the price table, or null when unpriced. */
@@ -227,13 +311,14 @@ export function estimateCost(
227
311
  input: number,
228
312
  output: number,
229
313
  cacheRead: number,
314
+ cacheWrite: number,
230
315
  modelId: string,
231
316
  provider: string,
232
317
  table: PriceTable = loadPriceTable(),
233
318
  ): number | null {
234
319
  const p = findPrice(provider, modelId, table);
235
320
  if (!p) return null;
236
- return (input / 1e6) * p.input + (output / 1e6) * p.output + (cacheRead / 1e6) * p.cacheRead;
321
+ return (input / 1e6) * p.input + (output / 1e6) * p.output + (cacheRead / 1e6) * p.cacheRead + (cacheWrite / 1e6) * p.cacheWrite;
237
322
  }
238
323
 
239
324
  /** Scaled value with 1 decimal ("2.5k"); a value that rounds up to the next unit is promoted (999,999 -> "1M", not "1000k"). */
@@ -260,74 +345,138 @@ const legacyCachePath = (): string => join(getAgentDir(), "arnative-usage-cache.
260
345
  /** Dead since pricing moved into `cost` fields in models.json: nothing reads it, so the
261
346
  * first load after the update removes it (layout "1" — see lib/preset-store.ts). */
262
347
  const legacyPricesPath = (): string => join(getAgentDir(), "arnative-prices.json");
263
- const CACHE_VERSION = 4; // v4: per-file rollup (was raw entries in v3)
348
+ const CACHE_VERSION = 10; // v10: the session cwd (`w`) joined v9, which a build without it already wrote; v9: no tool-result rows (v8: cacheWrite + the billed split, v7: day buckets, v6: the compact rows, v5: model rows only, v4: full rollup)
264
349
 
265
- /** The v5 disk shape: one-char keys, and only provider\0model rows — provider-level
350
+ /** Where pi-subagents keeps a run's transcript, inside the session's own project dir. */
351
+ const SUBAGENT_ARTIFACTS_DIR = "subagent-artifacts";
352
+
353
+ /** Synthetic provider for the spend pi attaches to a tool result instead of an assistant
354
+ * message (a subagent or a nested tool call). The store never reads it — the child's own
355
+ * session file already carries it — but the footer does, from the branch, where no child
356
+ * file exists. */
357
+ export const TOOL_PROVIDER = "tool";
358
+
359
+ /** The v8 disk shape: one-char keys, model rows in `r`, day rows in `d` (keyed
360
+ * `YYYY-MM-DD\0provider\0model`), the session cwd in `w` — provider-level and per-day
266
361
  * rollups are derived on load, so every number is stored once. Keys on disk are
267
- * paths relative to the sessions dir (the absolute path dominated the old size). */
362
+ * paths relative to the sessions dir (the absolute path dominated the old size).
363
+ * A row is `[msgs, input, output, cacheRead, cacheWrite, cost, billed]`; the 5-number
364
+ * rows of v5/v6 are decoded with cacheWrite 0 and the whole cost counted as billed.
365
+ * `t` marks an item written by the current version — anything else is re-parsed once, which
366
+ * is how a cache written by a build that also stored tool-result rows loses them. */
268
367
  type DiskItem = {
269
368
  m: number;
270
369
  s: number;
271
370
  c?: number;
272
- r: Record<string, [number, number, number, number, number]>;
273
- /** provider\0model -> day -> the same five numbers. Optional: an item cached before
274
- * ranges existed has none, and is re-parsed whole when a range is first asked for. */
275
- d?: Record<string, Record<string, [number, number, number, number, number]>>;
371
+ r: Record<string, [number, number, number, number, number, number, number]>;
372
+ d?: Record<string, [number, number, number, number, number, number, number]>;
373
+ w?: string;
374
+ t?: number;
375
+ };
376
+
377
+ /** Decode one disk row: a 7-number v7 row verbatim, a pre-v7 5-number row with cacheWrite 0
378
+ * and its cost counted as billed (that was the headline meaning before the split). */
379
+ const rowOf = (a: unknown): [number, number, number, number, number, number, number] | null => {
380
+ if (!Array.isArray(a) || a.length < 5) return null;
381
+ return a.length >= 7
382
+ ? [a[0]!, a[1]!, a[2]!, a[3]!, a[4]!, a[5]!, a[6]!]
383
+ : [a[0]!, a[1]!, a[2]!, a[3]!, 0, a[4]!, a[4]!];
276
384
  };
277
385
 
278
- /** Decode one disk item (v5 compact or v4 full) into the in-memory shape. */
386
+ /** Decode one disk item (v8 compact, v7/v6/v5 compact or v4 full) into the in-memory shape. */
279
387
  function decodeDiskItem(raw: unknown): FileCacheItem | null {
280
388
  if (!raw || typeof raw !== "object") return null;
281
389
  if ("rollup" in raw) {
282
390
  const v4 = raw as FileCacheItem;
283
- return v4.rollup ? { ...v4, v: CACHE_VERSION } : null;
391
+ if (!v4.rollup) return null;
392
+ // A v4 rollup predates cache writes, the billed split and the day buckets: its cost
393
+ // counts as billed so a migrated headline is unchanged, but the item is stamped 5 so the
394
+ // scan re-parses its file once and re-saves it with its days and its real billed split.
395
+ for (const r of Object.values(v4.rollup.providers)) {
396
+ if (typeof r.cacheWrite !== "number") r.cacheWrite = 0;
397
+ if (typeof r.billed !== "number") r.billed = r.cost;
398
+ }
399
+ return { ...v4, v: 5, rollup: { days: {}, ...v4.rollup } };
284
400
  }
285
401
  const d = raw as Partial<DiskItem>;
286
402
  if (typeof d.m !== "number" || typeof d.s !== "number" || !d.r) return null;
287
- const rollup: FileRollup = { providers: {} };
403
+ const rollup: FileRollup = { providers: {}, days: {} };
404
+ // v7+ rows are 7 numbers; a shorter row means a pre-v7 entry, stamped below 7 so the scan
405
+ // re-parses its file once and re-saves it with cache writes and the billed split. An empty
406
+ // `r` (a session with no assistant message) is a v7 item, not a pre-v7 one: `some` over an
407
+ // empty map is false, and treating it as old would re-read that file on every start.
408
+ const wide = !Object.values(d.r).some((a) => Array.isArray(a) && a.length < 7);
288
409
  for (const [pm, a] of Object.entries(d.r)) {
289
- if (!Array.isArray(a) || a.length < 5) continue;
290
- const [msgs, input, output, cacheRead, cost] = a as [number, number, number, number, number];
291
- Object.assign((rollup.providers[pm] ??= emptyRollup()), { sessions: 1, msgs, input, output, cacheRead, cost });
410
+ const row = rowOf(a);
411
+ if (!row) continue;
412
+ const [msgs, input, output, cacheRead, cacheWrite, cost, billed] = row;
413
+ Object.assign((rollup.providers[pm] ??= emptyRollup()), { sessions: 1, msgs, input, output, cacheRead, cacheWrite, cost, billed });
292
414
  const p = (rollup.providers[pm.split("\u0000")[0]!] ??= emptyRollup());
293
415
  p.sessions = 1;
294
416
  p.msgs += msgs;
295
417
  p.input += input;
296
418
  p.output += output;
297
419
  p.cacheRead += cacheRead;
420
+ p.cacheWrite += cacheWrite;
298
421
  p.cost += cost;
422
+ p.billed += billed;
299
423
  }
300
- return { mtimeMs: d.m, size: d.s, v: CACHE_VERSION, consumed: typeof d.c === "number" ? d.c : d.s, rollup: { providers: rollup.providers, ...(decodeDays(d.d) ?? {}) } };
301
- }
302
-
303
- /** Decode the optional day map; a missing or malformed one stays absent on purpose. */
304
- function decodeDays(raw: unknown): { days: NonNullable<FileRollup["days"]> } | null {
305
- if (!raw || typeof raw !== "object") return null;
306
- const days: NonNullable<FileRollup["days"]> = {};
307
- for (const [pm, perDay] of Object.entries(raw as Record<string, unknown>)) {
308
- if (!perDay || typeof perDay !== "object") continue;
309
- for (const [day, a] of Object.entries(perDay as Record<string, unknown>)) {
310
- if (!Array.isArray(a) || a.length < 5) continue;
311
- const [msgs, input, output, cacheRead, cost] = a as [number, number, number, number, number];
312
- (days[pm] ??= {})[day] = { msgs, input, output, cacheRead, cost };
424
+ // v6 adds the day buckets (`d`) and the cwd (`w`). A compact item without `d` is a pre-v6
425
+ // entry: it decodes the same way, but is stamped v5 so the scan re-parses its file once
426
+ // and re-saves it with its days (that one re-parse is what a version bump costs).
427
+ const hasDays = d.d !== undefined;
428
+ if (hasDays) {
429
+ for (const [dk, a] of Object.entries(d.d!)) {
430
+ if (Array.isArray(a)) {
431
+ // v6+ flat shape: `day\0provider\0model` -> one row.
432
+ const row = rowOf(a);
433
+ if (!row) continue;
434
+ const [msgs, input, output, cacheRead, cacheWrite, cost, billed] = row;
435
+ Object.assign((rollup.days[dk] ??= emptyRollup()), { sessions: 1, msgs, input, output, cacheRead, cacheWrite, cost, billed });
436
+ continue;
437
+ }
438
+ // Pre-merge shape (the range-bar cache): `provider\0model` -> `day` -> row. Fold it
439
+ // into the flat keys so an old cache or baseline still answers the windows; the
440
+ // item is stamped below current anyway and re-parsed once from its file.
441
+ if (!a || typeof a !== "object") continue;
442
+ for (const [day, rowRaw] of Object.entries(a as Record<string, unknown>)) {
443
+ const row = rowOf(rowRaw);
444
+ if (!row) continue;
445
+ const [msgs, input, output, cacheRead, cacheWrite, cost, billed] = row;
446
+ const flat = `${day}\u0000${dk}`;
447
+ Object.assign((rollup.days[flat] ??= emptyRollup()), { sessions: 1, msgs, input, output, cacheRead, cacheWrite, cost, billed });
448
+ }
313
449
  }
314
450
  }
315
- return Object.keys(days).length > 0 ? { days } : null;
451
+ return {
452
+ mtimeMs: d.m,
453
+ size: d.s,
454
+ // Only an item carrying `t`, the day map AND the cwd field is current: a v10 writer always
455
+ // emits `d` and `w` (empty string when the file has no header), so a missing `w` is a
456
+ // cache written before this shape and must be re-read.
457
+ v: d.t === CACHE_VERSION && d.d !== undefined && d.w !== undefined ? CACHE_VERSION : hasDays ? (wide ? 7 : 6) : 5,
458
+ cwd: typeof d.w === "string" && d.w !== "" ? d.w : undefined,
459
+ consumed: typeof d.c === "number" ? d.c : d.s,
460
+ rollup,
461
+ };
316
462
  }
317
463
 
318
- /** Encode an in-memory item as v5: model rows only (see DiskItem). */
464
+ /** Encode an in-memory item as v8: model rows in `r`, day rows in `d`, the cwd in `w`, and `t`
465
+ * marking that the rollups include tool-result spend. */
319
466
  function encodeDiskItem(item: FileCacheItem): DiskItem {
320
467
  const r: DiskItem["r"] = {};
468
+ const d: DiskItem["d"] = {};
321
469
  for (const [pm, roll] of Object.entries(item.rollup.providers)) {
322
- if (pm.includes("\u0000")) r[pm] = [roll.msgs, roll.input, roll.output, roll.cacheRead, roll.cost];
470
+ if (pm.includes("\u0000")) r[pm] = [roll.msgs, roll.input, roll.output, roll.cacheRead, roll.cacheWrite, roll.cost, roll.billed];
323
471
  }
324
- const d: NonNullable<DiskItem["d"]> = {};
325
- for (const [pm, perDay] of Object.entries(item.rollup.days ?? {})) {
326
- const out: Record<string, [number, number, number, number, number]> = {};
327
- for (const [day, b] of Object.entries(perDay)) out[day] = [b.msgs, b.input, b.output, b.cacheRead, b.cost];
328
- if (Object.keys(out).length > 0) d[pm] = out;
472
+ for (const [dk, roll] of Object.entries(item.rollup.days)) {
473
+ d[dk] = [roll.msgs, roll.input, roll.output, roll.cacheRead, roll.cacheWrite, roll.cost, roll.billed];
329
474
  }
330
- return { m: item.mtimeMs, s: item.size, c: item.consumed ?? item.size, r, ...(Object.keys(d).length > 0 ? { d } : {}) };
475
+ const out: DiskItem = { m: item.mtimeMs, s: item.size, c: item.consumed ?? item.size, r, d, t: CACHE_VERSION };
476
+ // Always emitted: an empty string says "this file carries no cwd", which is what lets the
477
+ // reader trust a current item without re-reading the head on every scan.
478
+ out.w = item.cwd ?? "";
479
+ return out;
331
480
  }
332
481
 
333
482
  // Disk cache is memoized; save writes memory + disk together.
@@ -398,13 +547,16 @@ function scanSessionFiles(dir: string): string[] {
398
547
  const files: string[] = [];
399
548
  try {
400
549
  if (!existsSync(dir)) return files;
401
- const list = readdirSync(dir, { withFileTypes: true });
402
- for (const ent of list) {
403
- const full = join(dir, ent.name);
404
- if (ent.isDirectory()) {
405
- files.push(...scanSessionFiles(full));
406
- } else if (ent.isFile() && ent.name.endsWith(".jsonl")) {
407
- files.push(full);
550
+ for (const ent of readdirSync(dir, { withFileTypes: true })) {
551
+ if (!ent.isDirectory() || ent.name === SUBAGENT_ARTIFACTS_DIR) continue;
552
+ const projectDir = join(dir, ent.name);
553
+ for (const f of readdirSync(projectDir, { withFileTypes: true })) {
554
+ // A session file lives directly in its project dir (`<ts>_<id>.jsonl`).
555
+ if (f.isFile() && f.name.endsWith(".jsonl")) files.push(join(projectDir, f.name));
556
+ // A subagent run is a session of its own, one level deeper
557
+ // (`<project>/<parent id>/<run id>/run-N/session.jsonl`): its spend is real and
558
+ // must be counted once, under its own provider/model.
559
+ else if (f.isDirectory()) files.push(...childSessionFiles(join(projectDir, f.name)));
408
560
  }
409
561
  }
410
562
  } catch {
@@ -413,8 +565,30 @@ function scanSessionFiles(dir: string): string[] {
413
565
  return files;
414
566
  }
415
567
 
416
- /** Extract a usage entry from one line, or null when it is not an assistant message.
417
- * `fallbackDay` dates a line that carries no timestamp of its own (older records). */
568
+ /** The child sessions of subagent runs under one project dir. Only `session.jsonl` counts: the
569
+ * run's transcript (`<project>/subagent-artifacts/*.jsonl`) repeats the same messages, and
570
+ * counting both billed every child twice — the same tokens also ride on the parent's tool
571
+ * result, which the store never reads for the same reason. */
572
+ function childSessionFiles(dir: string): string[] {
573
+ const files: string[] = [];
574
+ try {
575
+ for (const ent of readdirSync(dir, { withFileTypes: true })) {
576
+ if (ent.name === SUBAGENT_ARTIFACTS_DIR) continue;
577
+ const full = join(dir, ent.name);
578
+ if (ent.isDirectory()) files.push(...childSessionFiles(full));
579
+ else if (ent.name === "session.jsonl") files.push(full);
580
+ }
581
+ } catch {
582
+ // ignore
583
+ }
584
+ return files;
585
+ }
586
+
587
+ /** Extract a usage entry from one line, or null when the line carries none. Only an
588
+ * assistant message is read: pi also attaches child spend to a tool result
589
+ * (`ToolResultMessage.usage`), but that spend already sits in the child's own session file
590
+ * (see {@link scanSessionFiles}), so reading it here would count it twice. The footer reads
591
+ * it from the branch instead, where no child file exists. */
418
592
  function entryOfLine(line: string, fallbackDay: string): UsageEntry | null {
419
593
  // Loose prefilter (fast path only): exact key would break on JSON formatting changes
420
594
  // and silently drop usage. The role is re-checked on the parsed object below.
@@ -423,41 +597,94 @@ function entryOfLine(line: string, fallbackDay: string): UsageEntry | null {
423
597
  const rec = JSON.parse(line) as { timestamp?: unknown; message?: { role?: string; provider?: string; model?: string; usage?: Record<string, unknown> } };
424
598
  const m = rec?.message;
425
599
  if (m?.role !== "assistant") return null;
426
- const u = (m.usage ?? {}) as { input?: unknown; output?: unknown; cacheRead?: unknown; cost?: { total?: unknown } };
427
- const written = typeof rec.timestamp === "string" ? Date.parse(rec.timestamp) : Number.NaN;
600
+ const u = (m.usage ?? {}) as { input?: unknown; output?: unknown; cacheRead?: unknown; cacheWrite?: unknown; cost?: { total?: unknown; totalFromProvider?: unknown } };
601
+ // The session entry carries its own ISO `timestamp`; the inner message carries ms.
602
+ // Either dates the day bucket — prefer the record's, fall back to the message's,
603
+ // then to the file's mtime day for records that carry neither.
604
+ const recTs = typeof rec?.timestamp === "string" ? Date.parse(rec.timestamp) : tsOf(rec?.timestamp);
605
+ const written = (Number.isFinite(recTs) && recTs > 0 ? recTs : 0) || tsOf(m?.timestamp);
428
606
  return {
429
607
  provider: String(m.provider || "unknown"),
430
608
  model: String(m.model || "unknown"),
431
609
  input: Number(u.input) || 0,
432
610
  output: Number(u.output) || 0,
433
611
  cacheRead: Number(u.cacheRead) || 0,
612
+ cacheWrite: Number(u.cacheWrite) || 0,
434
613
  cost: Number(u.cost?.total) || 0,
435
- day: Number.isFinite(written) ? dayKey(written) : fallbackDay,
614
+ billed: u.cost?.totalFromProvider === true,
615
+ day: written > 0 ? dayKey(written) : fallbackDay,
436
616
  };
437
617
  } catch {
438
618
  return null;
439
619
  }
440
620
  }
441
621
 
622
+ /** A usable timestamp, or 0. `new Date(1e16).toISOString()` throws a RangeError, and one
623
+ * corrupt line must not break the whole scan (`/usage` and the Model tab both read it). */
624
+ function tsOf(raw: unknown): number {
625
+ const ts = Number(raw);
626
+ return Number.isFinite(ts) && ts > 0 && ts <= 8.64e15 ? ts : 0;
627
+ }
628
+
629
+ /** The cwd of a session-header line (`{"type":"session",...,"cwd":...}`), the first line of a
630
+ * session file. Undefined for any other line, so a tail parse reports none and the caller
631
+ * keeps the value already stored in the cache item. */
632
+ function sessionCwdOf(line: string): string | undefined {
633
+ if (!line.includes('"type"')) return undefined;
634
+ try {
635
+ const o = JSON.parse(line) as { type?: unknown; cwd?: unknown };
636
+ return o?.type === "session" && typeof o.cwd === "string" ? o.cwd : undefined;
637
+ } catch {
638
+ return undefined;
639
+ }
640
+ }
641
+
642
+ /**
643
+ * The cwd from the file's first line, without reading the whole file. A re-parse that starts
644
+ * at the baseline offset skips the header, so the cwd would be lost exactly when the cache
645
+ * shape changes. One 64 KB read covers a session header.
646
+ */
647
+ function headCwd(filePath: string): string | undefined {
648
+ try {
649
+ const fd = openSync(filePath, "r");
650
+ try {
651
+ const buf = Buffer.alloc(64 * 1024);
652
+ const n = readSync(fd, buf, 0, buf.length, 0);
653
+ return sessionCwdOf(buf.subarray(0, n).toString("utf8").split("\n", 1)[0] ?? "");
654
+ } finally {
655
+ closeSync(fd);
656
+ }
657
+ } catch {
658
+ return undefined;
659
+ }
660
+ }
661
+
442
662
  /**
443
663
  * Parse newline-terminated lines from a buffer. The returned offset is byte-granular, so it can
444
664
  * be fed back to `readSync`; a trailing segment without a newline counts only when it parses, so
445
- * a write caught mid-flight is left for the next scan rather than dropped.
665
+ * a write caught mid-flight is left for the next scan rather than dropped. `cwd` is set only
666
+ * when the buffer starts with the session header, i.e. on a whole-file parse. `fallbackDay`
667
+ * dates a line that carries no usable timestamp of its own (the file's mtime day).
446
668
  */
447
- function parseBuffer(buf: Buffer, fallbackDay: string): { entries: UsageEntry[]; consumed: number } {
669
+ function parseBuffer(buf: Buffer, fallbackDay: string): { entries: UsageEntry[]; consumed: number; cwd?: string } {
448
670
  const entries: UsageEntry[] = [];
449
671
  let start = 0;
450
672
  let consumed = 0;
673
+ let cwd: string | undefined;
451
674
  for (;;) {
452
675
  const nl = buf.indexOf(10, start);
453
676
  if (nl === -1) break;
454
- const entry = entryOfLine(buf.toString("utf8", start, nl), fallbackDay);
677
+ const line = buf.toString("utf8", start, nl);
678
+ // Only the buffer's first line can be the session header; a tail never contains it.
679
+ if (start === 0) cwd = sessionCwdOf(line) ?? cwd;
680
+ const entry = entryOfLine(line, fallbackDay);
455
681
  if (entry) entries.push(entry);
456
682
  start = nl + 1;
457
683
  consumed = start;
458
684
  }
459
685
  if (start < buf.length) {
460
686
  const tail = buf.toString("utf8", start);
687
+ if (start === 0) cwd = sessionCwdOf(tail) ?? cwd;
461
688
  const entry = entryOfLine(tail, fallbackDay);
462
689
  if (entry) {
463
690
  entries.push(entry);
@@ -468,7 +695,7 @@ function parseBuffer(buf: Buffer, fallbackDay: string): { entries: UsageEntry[];
468
695
  }
469
696
  // Anything else is a half-written record; leave it for the next scan.
470
697
  }
471
- return { entries, consumed };
698
+ return { entries, consumed, cwd };
472
699
  }
473
700
 
474
701
  /** True when the text parses as JSON. Used to tell a whole record from a half-written one. */
@@ -510,133 +737,248 @@ let lastScanMs = 0;
510
737
  * against itself and can never fail. */
511
738
  export function resetUsageCache(): void {
512
739
  diskMemo = null;
740
+ priceMemo = null;
741
+ baselineMemo = null;
513
742
  cachedSummary = null;
514
743
  cachedRange = null;
515
744
  lastScanMs = 0;
516
745
  }
517
746
 
518
747
  // =============================================================================
519
- // Reset: move the history aside, never destroy it
748
+ // Reset statistics without changing the session history
520
749
  // =============================================================================
521
- //
522
- // The numbers on the dashboard are not a counter we own: they are a fold over Pi's
523
- // session files. Deleting the cache changes nothing, so a real reset has to move those
524
- // files. They go to `arnative/usage-trash/<stamp>/` with their folder structure intact,
525
- // which is what makes the reset undoable; Pi simply stops seeing them, and `/resume`
526
- // forgets those sessions until they are moved back.
527
750
 
528
- /** Where a reset parks the history: one folder per reset, so two resets never collide. */
529
- export function usageTrashRoot(): string {
530
- return join(cacheDir(), "usage-trash");
751
+ const baselinePath = (): string => join(cacheDir(), "usage-baseline.json");
752
+ let baselineMemo: { path: string; mtimeMs: number; size: number; items: Map<string, FileCacheItem> } | null = null;
753
+
754
+ function loadUsageBaseline(): Map<string, FileCacheItem> {
755
+ const path = baselinePath();
756
+ if (!existsSync(path)) {
757
+ baselineMemo = null;
758
+ return new Map();
759
+ }
760
+ const stat = statSync(path);
761
+ if (baselineMemo?.path === path && baselineMemo.mtimeMs === stat.mtimeMs && baselineMemo.size === stat.size) return baselineMemo.items;
762
+ const raw: unknown = JSON.parse(readFileSync(path, "utf8"));
763
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error("Invalid usage baseline");
764
+ const items = new Map<string, FileCacheItem>();
765
+ for (const [key, value] of Object.entries(raw)) {
766
+ const item = decodeDiskItem(value);
767
+ if (!item) throw new Error("Invalid usage baseline entry");
768
+ items.set(join(getAgentDir(), "sessions", key), item);
769
+ }
770
+ baselineMemo = { path, mtimeMs: stat.mtimeMs, size: stat.size, items };
771
+ return items;
531
772
  }
532
773
 
533
- /** What a reset would move: used by the confirmation line, before anything is touched. */
534
- export function usageHistorySize(keep: readonly string[] = []): { files: number; bytes: number } {
535
- const sessionsDir = join(getAgentDir(), "sessions");
536
- const kept = new Set(keep.map((p) => p.toLowerCase()));
537
- let files = 0;
538
- let bytes = 0;
539
- for (const file of scanSessionFiles(sessionsDir)) {
540
- if (kept.has(file.toLowerCase())) continue;
774
+ function writeUsageBaseline(raw: string | null): void {
775
+ const path = baselinePath();
776
+ if (raw === null) rmSync(path, { force: true });
777
+ else {
778
+ mkdirSync(cacheDir(), { recursive: true });
779
+ const tmp = path + "." + process.pid + ".tmp";
541
780
  try {
542
- bytes += statSync(file).size;
543
- files++;
544
- } catch {
545
- // Vanished between the scan and the stat: it is gone, so it is not part of the total.
781
+ writeFileSync(tmp, raw, "utf8");
782
+ renameSync(tmp, path);
783
+ } finally {
784
+ rmSync(tmp, { force: true });
546
785
  }
547
786
  }
548
- return { files, bytes };
787
+ resetUsageCache();
549
788
  }
550
789
 
551
- /** Move every session file except `keep` (the one in use) into the trash, and drop the
552
- * cache. Returns the folder to pass to {@link restoreUsageHistory}. */
553
- export function resetUsageHistory(keep: readonly string[] = []): { moved: number; bytes: number; dir: string } {
790
+ /** Snapshot complete messages, including daily totals, so appended messages still count. */
791
+ export function resetUsageStats(): string | null {
792
+ collectUsageSummary(true, "today");
793
+ const path = baselinePath();
794
+ const previous = existsSync(path) ? readFileSync(path, "utf8") : null;
554
795
  const sessionsDir = join(getAgentDir(), "sessions");
555
- const kept = new Set(keep.map((p) => p.toLowerCase()));
556
- const stamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
557
- const dir = join(usageTrashRoot(), stamp);
558
- let moved = 0;
559
- let bytes = 0;
560
- for (const file of scanSessionFiles(sessionsDir)) {
561
- if (kept.has(file.toLowerCase())) continue;
562
- const rel = relative(sessionsDir, file);
563
- const dest = join(dir, rel);
564
- try {
565
- bytes += statSync(file).size;
566
- mkdirSync(join(dest, ".."), { recursive: true });
567
- try {
568
- renameSync(file, dest);
569
- } catch {
570
- // Different volume: copy, then drop the original.
571
- copyFileSync(file, dest);
572
- unlinkSync(file);
796
+ const snapshot = Object.fromEntries([...loadDiskCache()].map(([file, item]) => [relative(sessionsDir, file), encodeDiskItem(item)]));
797
+ writeUsageBaseline(JSON.stringify(snapshot));
798
+ return previous;
799
+ }
800
+
801
+ /** Restore the previous counting baseline; session files stay where they are. */
802
+ export function restoreUsageStats(previous: string | null): void {
803
+ writeUsageBaseline(previous);
804
+ }
805
+
806
+ /** A provider map as folded per file: provider → its models. Shared by the global provider
807
+ * list and each project's breakdown, so both count exactly the same rows. */
808
+ type ProviderMap = Map<
809
+ string,
810
+ {
811
+ sessions: Set<string>;
812
+ msgs: number;
813
+ input: number;
814
+ output: number;
815
+ cacheRead: number;
816
+ cacheWrite: number;
817
+ cost: number;
818
+ billed: number;
819
+ models: Map<
820
+ string,
821
+ {
822
+ sessions: Set<string>;
823
+ msgs: number;
824
+ input: number;
825
+ output: number;
826
+ cacheRead: number;
827
+ cacheWrite: number;
828
+ cost: number;
829
+ billed: number;
573
830
  }
574
- moved++;
575
- } catch {
576
- // A locked file (Windows, session still open elsewhere) stays where it is: the reset
577
- // moved what it could, and the confirmation line reports the count it actually moved.
831
+ >;
832
+ }
833
+ >;
834
+
835
+ /** Fold one file's rollup rows into a provider map. */
836
+ function foldFileIntoProviderMap(map: ProviderMap, file: string, rollup: FileRollup): void {
837
+ for (const [key, r] of Object.entries(rollup.providers)) {
838
+ const sep = key.indexOf("\u0000");
839
+ const pname = sep === -1 ? key : key.slice(0, sep);
840
+ if (!map.has(pname)) {
841
+ map.set(pname, { sessions: new Set(), msgs: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, billed: 0, models: new Map() });
842
+ }
843
+ const p = map.get(pname)!;
844
+ p.sessions.add(file);
845
+
846
+ if (sep === -1) {
847
+ // Provider-level key: the message totals belong here only.
848
+ p.msgs += r.msgs;
849
+ p.input += r.input;
850
+ p.output += r.output;
851
+ p.cacheRead += r.cacheRead;
852
+ p.cacheWrite += r.cacheWrite;
853
+ p.cost += r.cost;
854
+ p.billed += r.billed;
855
+ continue;
578
856
  }
857
+
858
+ const mname = key.slice(sep + 1);
859
+ if (!p.models.has(mname)) {
860
+ p.models.set(mname, { sessions: new Set(), msgs: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, billed: 0 });
861
+ }
862
+ const m = p.models.get(mname)!;
863
+ m.sessions.add(file);
864
+ m.msgs += r.msgs;
865
+ m.input += r.input;
866
+ m.output += r.output;
867
+ m.cacheRead += r.cacheRead;
868
+ m.cacheWrite += r.cacheWrite;
869
+ m.cost += r.cost;
870
+ m.billed += r.billed;
579
871
  }
580
- resetUsageCache();
581
- return { moved, bytes, dir };
582
872
  }
583
873
 
584
- /** The undo of {@link resetUsageHistory}: move the parked files back into place. */
585
- export function restoreUsageHistory(dir: string): { restored: number } {
586
- const sessionsDir = join(getAgentDir(), "sessions");
587
- let restored = 0;
588
- for (const file of scanSessionFiles(dir)) {
589
- const dest = join(sessionsDir, relative(dir, file));
590
- try {
591
- mkdirSync(join(dest, ".."), { recursive: true });
592
- if (existsSync(dest)) continue; // A new session took that name: keep both.
593
- try {
594
- renameSync(file, dest);
595
- } catch {
596
- copyFileSync(file, dest);
597
- unlinkSync(file);
598
- }
599
- restored++;
600
- } catch {
601
- // Locked: leave it in the trash, the rest still comes back.
874
+ /** Build the sorted provider rows (models sorted, estimates filled) from a folded provider
875
+ * map — used for the global list and for each project's providers, so both read the same
876
+ * numbers the same way. */
877
+ function providerStatsOf(map: ProviderMap, priceTable: PriceTable): UsageProviderStats[] {
878
+ const providers: UsageProviderStats[] = [];
879
+
880
+ for (const [pName, pData] of map.entries()) {
881
+ const models: UsageModelStats[] = [];
882
+ let providerEstimate = 0;
883
+ for (const [mName, mData] of pData.models.entries()) {
884
+ // Billed and estimated never blend: `cost` keeps only the provider-billed part, while
885
+ // the catalog-estimate remainder — or, for a row that carried no cost at all, a
886
+ // price-table reconstruction with cache writes — lands in `estimatedCost`.
887
+ const estimatedCost =
888
+ mData.cost > 0
889
+ ? mData.cost - mData.billed
890
+ : (estimateCost(mData.input, mData.output, mData.cacheRead, mData.cacheWrite, mName, pName, priceTable) ?? 0);
891
+ providerEstimate += estimatedCost;
892
+ models.push({
893
+ name: mName,
894
+ sessions: mData.sessions.size,
895
+ msgs: mData.msgs,
896
+ input: mData.input,
897
+ output: mData.output,
898
+ cacheRead: mData.cacheRead,
899
+ cacheWrite: mData.cacheWrite,
900
+ totalTokens: mData.input + mData.output + mData.cacheRead,
901
+ cost: mData.billed,
902
+ estimatedCost,
903
+ });
602
904
  }
905
+ models.sort((a, b) => b.totalTokens - a.totalTokens);
906
+
907
+ providers.push({
908
+ name: pName,
909
+ sessions: pData.sessions.size,
910
+ msgs: pData.msgs,
911
+ input: pData.input,
912
+ output: pData.output,
913
+ cacheRead: pData.cacheRead,
914
+ totalTokens: pData.input + pData.output + pData.cacheRead,
915
+ cost: pData.billed,
916
+ estimatedCost: providerEstimate,
917
+ models,
918
+ });
603
919
  }
604
- resetUsageCache();
605
- return { restored };
920
+
921
+ providers.sort((a, b) => b.totalTokens - a.totalTokens);
922
+ return providers;
606
923
  }
607
924
 
608
- /** One file's rollup, narrowed to the days a range covers. Same shape the `all` path reads
609
- * straight from `providers`, so the aggregation below runs once for both. */
925
+ /** One file's rollup, narrowed to the days a range covers. Reads the flat
926
+ * `day\0provider\0model` buckets and emits the same provider/provider\0model keys the
927
+ * `all` path reads straight from `providers`, so the aggregation below runs once for both. */
610
928
  function rollupSince(rollup: FileRollup, sinceDay: string): Record<string, Rollup> {
611
929
  const out: Record<string, Rollup> = {};
612
- for (const [pm, perDay] of Object.entries(rollup.days ?? {})) {
930
+ for (const [dk, r] of Object.entries(rollup.days)) {
931
+ // Day keys start with the fixed-width `YYYY-MM-DD`.
932
+ const day = dk.slice(0, 10);
933
+ if (day < sinceDay) continue;
934
+ const pm = dk.slice(11);
613
935
  const sep = pm.indexOf("\u0000");
614
936
  if (sep === -1) continue;
615
937
  const pname = pm.slice(0, sep);
616
- for (const [day, b] of Object.entries(perDay)) {
617
- if (day < sinceDay) continue;
618
- for (const key of [pm, pname]) {
619
- const r = (out[key] ??= emptyRollup());
620
- r.msgs += b.msgs;
621
- r.input += b.input;
622
- r.output += b.output;
623
- r.cacheRead += b.cacheRead;
624
- r.cost += b.cost;
625
- }
938
+ for (const key of [pm, pname]) {
939
+ const o = (out[key] ??= emptyRollup());
940
+ o.msgs += r.msgs;
941
+ o.input += r.input;
942
+ o.output += r.output;
943
+ o.cacheRead += r.cacheRead;
944
+ o.cacheWrite += r.cacheWrite;
945
+ o.cost += r.cost;
946
+ o.billed += r.billed;
626
947
  }
627
948
  }
628
949
  for (const r of Object.values(out)) r.sessions = 1;
629
950
  return out;
630
951
  }
631
952
 
953
+ const ROLLUP_FIELDS = ["msgs", "input", "output", "cacheRead", "cacheWrite", "cost", "billed"] as const;
954
+
955
+ /** A file's provider rows as the summary should count them: the range's day window when one
956
+ * is active, minus the statistics-reset baseline — field-wise, floored at 0, empty rows
957
+ * dropped. Both the global provider list and the per-project breakdown read this same map,
958
+ * so a project never counts what the provider row above it excluded. */
959
+ function effectiveProviders(rollup: FileRollup, baseline: FileRollup | undefined, sinceDay: string, needDays: boolean): Record<string, Rollup> {
960
+ const current = needDays ? rollupSince(rollup, sinceDay) : rollup.providers;
961
+ const before = baseline === undefined ? undefined : needDays ? rollupSince(baseline, sinceDay) : baseline.providers;
962
+ if (before === undefined) return current;
963
+ const out: Record<string, Rollup> = {};
964
+ for (const [key, r] of Object.entries(current)) {
965
+ const b = before[key];
966
+ const nr = { ...r };
967
+ for (const f of ROLLUP_FIELDS) nr[f] = Math.max(0, r[f] - (b?.[f] ?? 0));
968
+ if (nr.msgs === 0) continue;
969
+ out[key] = nr;
970
+ }
971
+ return out;
972
+ }
973
+
632
974
  export function collectUsageSummary(forceScan = false, range: UsageRange = "all"): UsageSummary {
633
975
  const now = Date.now();
634
976
  if (!forceScan && cachedSummary && cachedRange === range && now - lastScanMs < 5000) {
635
977
  return cachedSummary;
636
978
  }
637
979
 
638
- // A range reads day buckets, so a file cached before they existed is parsed once more.
639
- // `all` never needs them, which keeps the first open of the dashboard as cheap as before.
980
+ // A range reads day buckets. Every v9 item carries them, and anything older is already
981
+ // re-parsed by the version stamp, so no separate "needs days" pass is required.
640
982
  const start = rangeStart(range, now);
641
983
  const sinceDay = start === undefined ? "" : dayKey(start);
642
984
  const needDays = start !== undefined;
@@ -644,20 +986,17 @@ export function collectUsageSummary(forceScan = false, range: UsageRange = "all"
644
986
  const sessionsDir = join(getAgentDir(), "sessions");
645
987
  const files = scanSessionFiles(sessionsDir);
646
988
  const diskCache = loadDiskCache();
989
+ const baseline = loadUsageBaseline();
647
990
  let cacheDirty = false;
648
991
 
649
- const providerMap = new Map<
650
- string,
651
- {
652
- sessions: Set<string>;
653
- msgs: number;
654
- input: number;
655
- output: number;
656
- cacheRead: number;
657
- cost: number;
658
- models: Map<string, { sessions: Set<string>; msgs: number; input: number; output: number; cacheRead: number; cost: number }>;
659
- }
660
- >();
992
+ const priceTable = loadPriceTable();
993
+ const providerMap: ProviderMap = new Map();
994
+ /** Per-project aggregation: a file's project is its cwd, so each file folds into exactly
995
+ * one entry, whose providers keep their own model rows for the Project view. */
996
+ const projectMap = new Map<string, { sessions: Set<string>; providers: ProviderMap }>();
997
+ /** Day buckets across all files, keyed by the UTC day (the `day` prefix of each bucket
998
+ * key), baseline-subtracted so the windows answer the same statistics the rows do. */
999
+ const dayMap = new Map<string, Rollup>();
661
1000
 
662
1001
  for (const file of files) {
663
1002
  let stat;
@@ -669,15 +1008,36 @@ export function collectUsageSummary(forceScan = false, range: UsageRange = "all"
669
1008
 
670
1009
  let cached = diskCache.get(file);
671
1010
  if (!(cached && cached.v === CACHE_VERSION && cached.rollup)) cached = undefined;
672
- if (cached && needDays && !cached.rollup.days) cached = undefined;
1011
+
673
1012
  const fallbackDay = dayKey(stat.mtimeMs);
1013
+ const baselineItem = baseline.get(file);
1014
+ const reparse = (): FileCacheItem => {
1015
+ // Keep the prefix's original day buckets: undated records otherwise inherit the
1016
+ // file's new modification day when a cache is rebuilt after an append. The rollup
1017
+ // seeds from the baseline so the cached item still holds the full history — the
1018
+ // baseline is subtracted at read time, never baked into the cache.
1019
+ const offset = baselineItem && (baselineItem.consumed ?? 0) <= stat.size ? (baselineItem.consumed ?? 0) : 0;
1020
+ const rollup: FileRollup = offset > 0 ? structuredClone(baselineItem!.rollup) : { providers: {}, days: {} };
1021
+ const bytes = offset > 0 ? (readTail(file, offset) ?? readFileSync(file).subarray(offset)) : readFileSync(file);
1022
+ const parsed = parseBuffer(bytes, fallbackDay);
1023
+ foldInto(rollup, parsed.entries);
1024
+ return {
1025
+ mtimeMs: stat.mtimeMs,
1026
+ size: stat.size,
1027
+ v: CACHE_VERSION,
1028
+ cwd: parsed.cwd ?? (offset > 0 ? baselineItem!.cwd ?? headCwd(file) : undefined) ?? cached?.cwd,
1029
+ consumed: offset + parsed.consumed,
1030
+ rollup,
1031
+ };
1032
+ };
674
1033
 
675
1034
  if (cached && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) {
676
1035
  // Unchanged since the last scan: its rollup already holds everything.
677
1036
  } else if (cached && (cached.consumed ?? 0) > 0 && stat.size > (cached.consumed ?? 0)) {
678
1037
  // Grew, and a prefix was already parsed: read only the appended tail and fold it into
679
1038
  // the existing rollup. (A shrunk file, or one whose size is below the offset,
680
- // re-parses whole — see the final branch.)
1039
+ // re-parses whole — see the final branch.) The cwd stays the one already stored:
1040
+ // the tail does not contain the session header, so the head is not re-read.
681
1041
  const tail = readTail(file, cached.consumed!);
682
1042
  const parsed = tail ? parseBuffer(tail, fallbackDay) : null;
683
1043
  if (parsed) {
@@ -687,48 +1047,41 @@ export function collectUsageSummary(forceScan = false, range: UsageRange = "all"
687
1047
  cached.size = stat.size;
688
1048
  } else {
689
1049
  // Unreadable: fall back to whole-file.
690
- const full = parseBuffer(readFileSync(file), fallbackDay);
691
- cached = { mtimeMs: stat.mtimeMs, size: stat.size, v: CACHE_VERSION, consumed: full.consumed, rollup: rollupOfFile(full.entries) };
1050
+ cached = reparse();
692
1051
  diskCache.set(file, cached);
693
1052
  }
694
1053
  cacheDirty = true;
695
1054
  } else {
696
- const full = parseBuffer(readFileSync(file), fallbackDay);
697
- cached = { mtimeMs: stat.mtimeMs, size: stat.size, v: CACHE_VERSION, consumed: full.consumed, rollup: rollupOfFile(full.entries) };
1055
+ cached = reparse();
698
1056
  diskCache.set(file, cached);
699
1057
  cacheDirty = true;
700
1058
  }
701
1059
 
702
- for (const [key, r] of Object.entries(needDays ? rollupSince(cached.rollup, sinceDay) : cached.rollup.providers)) {
703
- const sep = key.indexOf("\u0000");
704
- const pname = sep === -1 ? key : key.slice(0, sep);
705
- if (!providerMap.has(pname)) {
706
- providerMap.set(pname, { sessions: new Set(), msgs: 0, input: 0, output: 0, cacheRead: 0, cost: 0, models: new Map() });
707
- }
708
- const p = providerMap.get(pname)!;
709
- p.sessions.add(file);
710
-
711
- if (sep === -1) {
712
- // Provider-level key: the message totals belong here only.
713
- p.msgs += r.msgs;
714
- p.input += r.input;
715
- p.output += r.output;
716
- p.cacheRead += r.cacheRead;
717
- p.cost += r.cost;
718
- continue;
719
- }
720
-
721
- const mname = key.slice(sep + 1);
722
- if (!p.models.has(mname)) {
723
- p.models.set(mname, { sessions: new Set(), msgs: 0, input: 0, output: 0, cacheRead: 0, cost: 0 });
724
- }
725
- const m = p.models.get(mname)!;
726
- m.sessions.add(file);
727
- m.msgs += r.msgs;
728
- m.input += r.input;
729
- m.output += r.output;
730
- m.cacheRead += r.cacheRead;
731
- m.cost += r.cost;
1060
+ // What this file contributes: range window and reset baseline already applied.
1061
+ const effective: FileRollup = { providers: effectiveProviders(cached.rollup, baselineItem?.rollup, sinceDay, needDays), days: {} };
1062
+
1063
+ // A file with no cwd in its cache item lands in "unknown" rather than being re-read.
1064
+ const projectName = cached.cwd ?? "unknown";
1065
+ let project = projectMap.get(projectName);
1066
+ if (!project) projectMap.set(projectName, (project = { sessions: new Set(), providers: new Map() }));
1067
+ project.sessions.add(file);
1068
+ foldFileIntoProviderMap(providerMap, file, effective);
1069
+ foldFileIntoProviderMap(project.providers, file, effective);
1070
+ const baseDays = baselineItem?.rollup.days;
1071
+ for (const [dk, r] of Object.entries(cached.rollup.days)) {
1072
+ // Day keys start with the fixed-width `YYYY-MM-DD`; the baseline's same-key row is
1073
+ // subtracted field-wise so the windows never resurrect pre-reset spend.
1074
+ const day = dk.slice(0, 10);
1075
+ const b = baseDays?.[dk];
1076
+ let t = dayMap.get(day);
1077
+ if (!t) dayMap.set(day, (t = emptyRollup()));
1078
+ t.msgs += Math.max(0, r.msgs - (b?.msgs ?? 0));
1079
+ t.input += Math.max(0, r.input - (b?.input ?? 0));
1080
+ t.output += Math.max(0, r.output - (b?.output ?? 0));
1081
+ t.cacheRead += Math.max(0, r.cacheRead - (b?.cacheRead ?? 0));
1082
+ t.cacheWrite += Math.max(0, r.cacheWrite - (b?.cacheWrite ?? 0));
1083
+ t.cost += Math.max(0, r.cost - (b?.cost ?? 0));
1084
+ t.billed += Math.max(0, r.billed - (b?.billed ?? 0));
732
1085
  }
733
1086
  }
734
1087
 
@@ -745,84 +1098,101 @@ export function collectUsageSummary(forceScan = false, range: UsageRange = "all"
745
1098
  saveDiskCache(diskCache);
746
1099
  }
747
1100
 
1101
+ const providers = providerStatsOf(providerMap, priceTable);
1102
+
748
1103
  // Fold per-provider results into totals
749
1104
  let totalMsgs = 0;
750
1105
  let totalInp = 0;
751
1106
  let totalOut = 0;
752
1107
  let totalCache = 0;
753
1108
  let totalCost = 0;
1109
+ let estimatedCost = 0;
754
1110
 
755
1111
  const allSessions = new Set<string>();
756
- const providers: UsageProviderStats[] = [];
757
-
758
- for (const [pName, pData] of providerMap.entries()) {
1112
+ for (const pData of providerMap.values()) {
759
1113
  for (const s of pData.sessions) allSessions.add(s);
760
- totalMsgs += pData.msgs;
761
- totalInp += pData.input;
762
- totalOut += pData.output;
763
- totalCache += pData.cacheRead;
764
- totalCost += pData.cost;
1114
+ }
1115
+ for (const p of providers) {
1116
+ totalMsgs += p.msgs;
1117
+ totalInp += p.input;
1118
+ totalOut += p.output;
1119
+ totalCache += p.cacheRead;
1120
+ totalCost += p.cost;
1121
+ estimatedCost += p.estimatedCost;
1122
+ }
765
1123
 
766
- const models: UsageModelStats[] = [];
767
- for (const [mName, mData] of pData.models.entries()) {
768
- models.push({
769
- name: mName,
770
- sessions: mData.sessions.size,
771
- msgs: mData.msgs,
772
- input: mData.input,
773
- output: mData.output,
774
- cacheRead: mData.cacheRead,
775
- totalTokens: mData.input + mData.output + mData.cacheRead,
776
- cost: mData.cost,
777
- });
1124
+ const projects: UsageProjectStats[] = [];
1125
+ for (const [name, pData] of projectMap.entries()) {
1126
+ const pStats = providerStatsOf(pData.providers, priceTable);
1127
+ let msgs = 0;
1128
+ let input = 0;
1129
+ let output = 0;
1130
+ let cacheRead = 0;
1131
+ let cost = 0;
1132
+ let est = 0;
1133
+ for (const ps of pStats) {
1134
+ msgs += ps.msgs;
1135
+ input += ps.input;
1136
+ output += ps.output;
1137
+ cacheRead += ps.cacheRead;
1138
+ cost += ps.cost;
1139
+ est += ps.estimatedCost;
778
1140
  }
779
- models.sort((a, b) => b.totalTokens - a.totalTokens);
780
-
781
- providers.push({
782
- name: pName,
1141
+ projects.push({
1142
+ name,
783
1143
  sessions: pData.sessions.size,
784
- msgs: pData.msgs,
785
- input: pData.input,
786
- output: pData.output,
787
- cacheRead: pData.cacheRead,
788
- totalTokens: pData.input + pData.output + pData.cacheRead,
789
- cost: pData.cost,
790
- models,
1144
+ msgs,
1145
+ input,
1146
+ output,
1147
+ cacheRead,
1148
+ totalTokens: input + output + cacheRead,
1149
+ cost,
1150
+ estimatedCost: est,
1151
+ providers: pStats,
791
1152
  });
792
1153
  }
793
-
794
- providers.sort((a, b) => b.totalTokens - a.totalTokens);
795
-
796
- // Estimate unpriced pairs from price table. Kept separate in estimatedCost.
797
- const priceTable = loadPriceTable();
798
- let estimatedCost = 0;
799
- for (const p of providers) {
800
- let providerEstimate = 0;
801
- for (const m of p.models) {
802
- const est = m.cost > 0 ? null : estimateCost(m.input, m.output, m.cacheRead, m.name, p.name, priceTable);
803
- m.estimatedCost = est ?? 0;
804
- providerEstimate += m.estimatedCost;
1154
+ projects.sort((a, b) => b.totalTokens - a.totalTokens);
1155
+
1156
+ /** Sum of the day buckets over the last `n` UTC days, today included. */
1157
+ const windowOf = (n: number): UsageDayWindow => {
1158
+ let cost = 0;
1159
+ let estimated = 0;
1160
+ let input = 0;
1161
+ let output = 0;
1162
+ let cacheRead = 0;
1163
+ for (let i = 0; i < n; i++) {
1164
+ const r = dayMap.get(dayKey(now - i * 86_400_000));
1165
+ if (!r) continue;
1166
+ cost += r.billed;
1167
+ estimated += Math.max(0, r.cost - r.billed);
1168
+ input += r.input;
1169
+ output += r.output;
1170
+ cacheRead += r.cacheRead;
805
1171
  }
806
- p.estimatedCost = providerEstimate;
807
- estimatedCost += providerEstimate;
808
- }
809
-
810
- cachedSummary = {
811
- providers,
812
- totals: {
813
- sessions: allSessions.size,
814
- msgs: totalMsgs,
815
- input: totalInp,
816
- output: totalOut,
817
- cacheRead: totalCache,
818
- totalTokens: totalInp + totalOut + totalCache,
819
- cost: totalCost,
820
- reportedCost: totalCost,
821
- estimatedCost,
822
- },
1172
+ return { cost, estimated, input, output, cacheRead };
823
1173
  };
824
- lastScanMs = now;
1174
+
1175
+ const totals: UsageSummary["totals"] = {
1176
+ sessions: allSessions.size,
1177
+ msgs: totalMsgs,
1178
+ input: totalInp,
1179
+ output: totalOut,
1180
+ cacheRead: totalCache,
1181
+ totalTokens: totalInp + totalOut + totalCache,
1182
+ cost: totalCost,
1183
+ reportedCost: totalCost,
1184
+ estimatedCost,
1185
+ };
1186
+ // The windows exist only when the scan saw day buckets (a cache that is all v8).
1187
+ if (dayMap.size > 0) {
1188
+ totals.today = windowOf(1);
1189
+ totals.last7d = windowOf(7);
1190
+ totals.last30d = windowOf(30);
1191
+ }
1192
+
1193
+ cachedSummary = { providers, projects, totals };
825
1194
  cachedRange = range;
1195
+ lastScanMs = now;
826
1196
  return cachedSummary;
827
1197
  }
828
1198
 
@@ -865,3 +1235,234 @@ export function getModelAllTimeUsage(modelId?: string): { input: number; output:
865
1235
 
866
1236
  return { input: inp, output: out, cacheRead: read };
867
1237
  }
1238
+
1239
+ // Self-check: `node lib/usage-store.ts`
1240
+ if (isMain(import.meta.url)) {
1241
+ const NL = String.fromCharCode(10);
1242
+ const fixture = mkdtempSync(join(tmpdir(), "arnative-store-"));
1243
+ process.env.PI_CODING_AGENT_DIR = fixture;
1244
+ const asst = (model: string, input: number, ts: number, cost = 0.02) =>
1245
+ JSON.stringify({
1246
+ message: {
1247
+ role: "assistant",
1248
+ provider: "google",
1249
+ model,
1250
+ timestamp: ts,
1251
+ usage: { input, output: 5, cacheRead: 1, cacheWrite: 2, cost: { total: cost, totalFromProvider: true } },
1252
+ },
1253
+ });
1254
+ const header = (cwd: string) => JSON.stringify({ type: "session", cwd });
1255
+ const tsToday = Date.now();
1256
+ const tsYesterday = Date.now() - 86_400_000;
1257
+ const today = new Date(tsToday).toISOString().slice(0, 10);
1258
+ const yesterday = new Date(tsYesterday).toISOString().slice(0, 10);
1259
+
1260
+ mkdirSync(join(fixture, "sessions", "proj-a"), { recursive: true });
1261
+ mkdirSync(join(fixture, "sessions", "proj-b"), { recursive: true });
1262
+ // proj-a carries a session header (cwd); proj-b has none, so it must land in "unknown".
1263
+ const fileA = join(fixture, "sessions", "proj-a", "a.jsonl");
1264
+ writeFileSync(fileA, [header("/repo/alpha"), asst("m1", 100, tsToday), asst("m1", 50, tsYesterday)].join(NL) + NL);
1265
+ writeFileSync(join(fixture, "sessions", "proj-b", "b.jsonl"), asst("m2", 7, tsToday) + NL);
1266
+
1267
+ const summary = collectUsageSummary(true);
1268
+ assert(summary.projects.length === 2, "one project per cwd plus unknown");
1269
+ const alpha = summary.projects.find((p) => p.name === "/repo/alpha")!;
1270
+ const unknown = summary.projects.find((p) => p.name === "unknown")!;
1271
+ assert(alpha.msgs === 2 && alpha.input === 150 && Math.abs(alpha.cost - 0.04) < 1e-9, "a project row carries its files' totals");
1272
+ assert(unknown.msgs === 1 && unknown.input === 7, "a file with no cwd lands in unknown");
1273
+ assert(alpha.providers.length === 1 && alpha.providers[0]!.name === "google" && alpha.providers[0]!.models[0]!.name === "m1", "a project trees into its providers and models");
1274
+ const sumOf = (f: (p: (typeof summary.projects)[number]) => number) => summary.projects.reduce((n, p) => n + f(p), 0);
1275
+ assert(
1276
+ sumOf((p) => p.msgs) === summary.totals.msgs &&
1277
+ sumOf((p) => p.input) === summary.totals.input &&
1278
+ sumOf((p) => p.output) === summary.totals.output &&
1279
+ Math.abs(sumOf((p) => p.cost) - summary.totals.cost) < 1e-9,
1280
+ "projects totals equal totals",
1281
+ );
1282
+
1283
+ // Day buckets: windows come from them, and on disk they sum to the file total.
1284
+ assert(summary.totals.today !== undefined && summary.totals.last7d !== undefined && summary.totals.last30d !== undefined, "day buckets produce the today/7d/30d windows");
1285
+ assert(summary.totals.today.input === 107 && Math.abs(summary.totals.today.cost - 0.04) < 1e-9, "today sums only today's bucket");
1286
+ assert(summary.totals.last7d.input === 157 && Math.abs(summary.totals.last7d.cost - 0.06) < 1e-9, "last7d includes yesterday");
1287
+ assert(summary.totals.last30d.input === 157, "last30d includes yesterday too");
1288
+ const cachePath = join(fixture, "arnative", "usage-cache.json");
1289
+ const disk = JSON.parse(readFileSync(cachePath, "utf8")) as Record<string, { r: Record<string, number[]>; d?: Record<string, number[]>; w?: string }>;
1290
+ const relA = join("proj-a", "a.jsonl");
1291
+ const msgsOf = (rows: Record<string, number[]>) => Object.values(rows).reduce((n, a) => n + a[0]!, 0);
1292
+ assert(disk[relA]!.w === "/repo/alpha", "v8 stores the session cwd in w");
1293
+ assert(disk[relA]!.d !== undefined && msgsOf(disk[relA]!.d!) === msgsOf(disk[relA]!.r), "day buckets sum to the file total on disk");
1294
+ const rowA = disk[relA]!.r["google\u0000m1"]!;
1295
+ assert(rowA.length === 7 && rowA[4] === 4, "v8 rows carry cacheWrite (two entries x 2)");
1296
+ assert(Math.abs(rowA[6]! - 0.04) < 1e-9, "v8 rows carry the billed split of the cost");
1297
+ assert(
1298
+ Object.keys(disk[relA]!.d!).every((k) => k.startsWith(`${today}\u0000`) || k.startsWith(`${yesterday}\u0000`)) && disk[relA]!.d![`${today}\u0000google\u0000m1`] !== undefined,
1299
+ "day keys are the UTC day + provider + model",
1300
+ );
1301
+ assert(disk[join("proj-b", "b.jsonl")]!.w === "", "a file with no cwd stores the empty marker (it reads as unknown)");
1302
+
1303
+ // A grown file tail-folds: the cwd stays the cached one (the head is not re-read) and the
1304
+ // new entry lands in its day bucket.
1305
+ writeFileSync(fileA, asst("m1", 1000, tsToday) + NL, { flag: "a" });
1306
+ const grown = collectUsageSummary(true);
1307
+ assert(grown.totals.msgs === 4, "an appended record is folded from the tail");
1308
+ assert(grown.projects.find((p) => p.name === "/repo/alpha")!.input === 1150, "the tail fold keeps the cached cwd (the project is unchanged)");
1309
+ assert(grown.totals.today!.input === 1107, "the appended entry lands in today's bucket");
1310
+ const grownDisk = JSON.parse(readFileSync(cachePath, "utf8")) as Record<string, { w?: string }>;
1311
+ assert(grownDisk[relA]!.w === "/repo/alpha", "the cwd survives a tail fold on disk too");
1312
+
1313
+ // A pre-v8 (v5 compact, no `d`) cache item is re-parsed once from its file — not trusted —
1314
+ // and re-saved as v8 with its days, cwd, cache writes, billed split and tool-result spend.
1315
+ const fileC = join(fixture, "sessions", "proj-b", "c.jsonl");
1316
+ writeFileSync(fileC, asst("m2", 11, tsToday) + NL);
1317
+ const cStat = statSync(fileC);
1318
+ writeFileSync(
1319
+ cachePath,
1320
+ JSON.stringify({ [join("proj-b", "c.jsonl")]: { m: cStat.mtimeMs, s: cStat.size, c: cStat.size, r: { "google\u0000m2": [99, 999, 1, 1, 9] } } }),
1321
+ );
1322
+ resetUsageCache();
1323
+ const reparsed = collectUsageSummary(true);
1324
+ assert(reparsed.totals.msgs === 5 && reparsed.totals.input === 1168, "a v5 cache item is re-parsed from the file (the stale 99 is not counted)");
1325
+ const afterDisk = JSON.parse(readFileSync(cachePath, "utf8")) as Record<string, { d?: Record<string, number[]>; w?: string }>;
1326
+ const relC = join("proj-b", "c.jsonl");
1327
+ assert(afterDisk[relC]!.d !== undefined && msgsOf(afterDisk[relC]!.d!) === 1, "the re-parsed item is re-saved as v8 with day buckets");
1328
+
1329
+ // A v6 item (day buckets but 5-number rows) is also re-parsed once: its rows carry neither
1330
+ // cacheWrite nor the billed split, so it is stamped 6 and not trusted.
1331
+ const fileD = join(fixture, "sessions", "proj-b", "d.jsonl");
1332
+ writeFileSync(fileD, asst("m2", 13, tsToday) + NL);
1333
+ const dStat = statSync(fileD);
1334
+ writeFileSync(
1335
+ cachePath,
1336
+ JSON.stringify({
1337
+ [join("proj-b", "d.jsonl")]: {
1338
+ m: dStat.mtimeMs,
1339
+ s: dStat.size,
1340
+ c: dStat.size,
1341
+ r: { "google\u0000m2": [99, 999, 1, 1, 9] },
1342
+ d: { [`${today}\u0000google\u0000m2`]: [99, 999, 1, 1, 9] },
1343
+ },
1344
+ }),
1345
+ );
1346
+ resetUsageCache();
1347
+ const reparsed6 = collectUsageSummary(true);
1348
+ assert(reparsed6.totals.msgs === 6 && reparsed6.totals.input === 1181, "a v6 cache item is re-parsed from its file (the stale 99 is not counted)");
1349
+
1350
+ // Child spend: pi attaches it to the tool result, but the child also writes its own session
1351
+ // file, so the store must not read the tool result — that counts the same tokens twice.
1352
+ // Its own fixture, so the totals above stay untouched.
1353
+ assert(TOOL_PROVIDER === "tool", "child spend is attributed to the synthetic `tool` provider");
1354
+ const toolFixture = mkdtempSync(join(tmpdir(), "arnative-tool-"));
1355
+ process.env.PI_CODING_AGENT_DIR = toolFixture;
1356
+ resetUsageCache();
1357
+ mkdirSync(join(toolFixture, "sessions", "p"), { recursive: true });
1358
+ const toolFile = join(toolFixture, "sessions", "p", "t.jsonl");
1359
+ const toolResult = (toolName: string, usage?: object) =>
1360
+ JSON.stringify({
1361
+ message: { role: "toolResult", toolCallId: "c1", toolName, content: [], isError: false, timestamp: tsToday, ...(usage ? { usage } : {}) },
1362
+ });
1363
+ writeFileSync(
1364
+ toolFile,
1365
+ [
1366
+ header("/repo/alpha"),
1367
+ asst("m1", 100, tsToday),
1368
+ toolResult("subagent", { input: 40, output: 6, cacheRead: 2, cacheWrite: 1, cost: { total: 0.01, totalFromProvider: true } }),
1369
+ toolResult("bash"), // no usage at all
1370
+ ].join(NL) + NL,
1371
+ );
1372
+ const parentOnly = collectUsageSummary(true);
1373
+ assert(parentOnly.totals.msgs === 1 && parentOnly.totals.input === 100, "a tool result's usage is not read: the child's own session file carries it");
1374
+ assert(parentOnly.providers.every((p) => p.name !== TOOL_PROVIDER), "no synthetic `tool` row: /usage never sees child spend twice");
1375
+
1376
+ // A subagent run writes <project>/<parent id>/<run id>/run-N/session.jsonl, and its
1377
+ // transcript under <project>/subagent-artifacts/: the child session is real spend, the
1378
+ // transcript is the same messages again.
1379
+ const childDir = join(toolFixture, "sessions", "p", "parent-1", "run-1", "run-0");
1380
+ mkdirSync(childDir, { recursive: true });
1381
+ writeFileSync(join(childDir, "session.jsonl"), [header("/repo/alpha"), asst("m1", 40, tsToday)].join(NL) + NL);
1382
+ mkdirSync(join(toolFixture, "sessions", "p", SUBAGENT_ARTIFACTS_DIR), { recursive: true });
1383
+ writeFileSync(
1384
+ join(toolFixture, "sessions", "p", SUBAGENT_ARTIFACTS_DIR, "x_transcript.jsonl"),
1385
+ [header("/repo/alpha"), asst("m1", 7, tsToday)].join(NL) + NL,
1386
+ );
1387
+ resetUsageCache();
1388
+ const nested = collectUsageSummary(true);
1389
+ assert(nested.totals.msgs === 2 && nested.totals.input === 140, "a child session is counted once (40), its transcript not at all (7)");
1390
+ assert(nested.totals.sessions === 2, "the parent session and the child session, not the transcript");
1391
+
1392
+ // A v7 item (7-number rows with day buckets, no `t`) is re-parsed once from its file — not
1393
+ // trusted — and re-saved as v8.
1394
+ const tStat = statSync(toolFile);
1395
+ writeFileSync(
1396
+ join(toolFixture, "arnative", "usage-cache.json"),
1397
+ JSON.stringify({
1398
+ [join("p", "t.jsonl")]: {
1399
+ m: tStat.mtimeMs,
1400
+ s: tStat.size,
1401
+ c: tStat.size,
1402
+ r: { "google\u0000m1": [99, 999, 1, 1, 1, 9, 9] },
1403
+ d: { [`${today}\u0000google\u0000m1`]: [99, 999, 1, 1, 1, 9, 9] },
1404
+ },
1405
+ }),
1406
+ );
1407
+ resetUsageCache();
1408
+ const reparsed7 = collectUsageSummary(true);
1409
+ assert(reparsed7.totals.msgs === 2 && reparsed7.totals.input === 140, "a v7 cache item is re-parsed from its file (the stale 99 is not counted)");
1410
+ const after7 = JSON.parse(readFileSync(join(toolFixture, "arnative", "usage-cache.json"), "utf8")) as Record<string, { t?: number }>;
1411
+ assert(after7[join("p", "t.jsonl")]!.t === CACHE_VERSION, "the re-parsed item is re-saved as the current version");
1412
+
1413
+ // A cache written by the build that also stored tool-result rows is stamped `t: 8`: it must
1414
+ // be re-parsed, or the child spend it holds is counted a second time next to the child's file.
1415
+ const staleDisk = JSON.parse(readFileSync(join(toolFixture, "arnative", "usage-cache.json"), "utf8")) as Record<string, unknown>;
1416
+ staleDisk[join("p", "t.jsonl")] = {
1417
+ m: tStat.mtimeMs,
1418
+ s: tStat.size,
1419
+ c: tStat.size,
1420
+ t: 8,
1421
+ r: { [`${TOOL_PROVIDER}\u0000subagent`]: [1, 40, 6, 2, 1, 0.01, 0.01], "google\u0000m1": [1, 100, 5, 1, 0, 0.02, 0.02] },
1422
+ };
1423
+ writeFileSync(join(toolFixture, "arnative", "usage-cache.json"), JSON.stringify(staleDisk));
1424
+ resetUsageCache();
1425
+ const afterStale = collectUsageSummary(true);
1426
+ assert(afterStale.providers.every((p) => p.name !== TOOL_PROVIDER), "a `t: 8` item's tool rows are dropped: the item is re-parsed");
1427
+ assert(afterStale.totals.input === 140, "the re-parsed item keeps the parent and the child, once each");
1428
+
1429
+ // An empty session (no assistant message) writes `r: {}`: that is a current item, not a
1430
+ // pre-v7 one — `some` over an empty map is false, and treating it as old would re-read that
1431
+ // file on every start. A tampered row proves the item is trusted rather than re-parsed.
1432
+ const emptyFile = join(toolFixture, "sessions", "p", "empty.jsonl");
1433
+ writeFileSync(emptyFile, header("/repo/alpha") + NL);
1434
+ resetUsageCache();
1435
+ collectUsageSummary(true);
1436
+ const emptyCachePath = join(toolFixture, "arnative", "usage-cache.json");
1437
+ const emptyDisk = JSON.parse(readFileSync(emptyCachePath, "utf8")) as Record<string, { r: Record<string, number[]> }>;
1438
+ assert(emptyDisk[join("p", "empty.jsonl")] !== undefined, "an empty session is cached");
1439
+ emptyDisk[join("p", "empty.jsonl")]!.r = { "google\u0000m9": [5, 500, 0, 0, 0, 0, 0] };
1440
+ writeFileSync(emptyCachePath, JSON.stringify(emptyDisk));
1441
+ resetUsageCache();
1442
+ assert(collectUsageSummary(true).totals.input === 640, "an empty `r` item is trusted, not re-read on every start");
1443
+ rmSync(toolFixture, { recursive: true, force: true });
1444
+ process.env.PI_CODING_AGENT_DIR = fixture;
1445
+ resetUsageCache();
1446
+
1447
+ // Price table: cacheWrite is priced like the other three, and an unchanged models.json is
1448
+ // read once — two loadPriceTable() calls return the same memo object.
1449
+ writeFileSync(
1450
+ join(fixture, "models.json"),
1451
+ JSON.stringify({ providers: { google: { models: [{ id: "m1", cost: { input: 1, output: 2, cacheRead: 0.1, cacheWrite: 3 } }] } } }),
1452
+ );
1453
+ const table1 = loadPriceTable();
1454
+ assert(table1 === loadPriceTable(), "two loadPriceTable() calls with an unchanged file read it once (memo identity)");
1455
+ assert(estimateCost(1_000_000, 0, 0, 0, "m1", "google") === 1, "input keeps its own rate");
1456
+ assert(estimateCost(0, 0, 0, 1_000_000, "m1", "google") === 3, "cache writes use their own rate");
1457
+ assert(Math.abs(estimateCost(0, 0, 1_000_000, 1_000_000, "m1", "google")! - 3.1) < 1e-9, "cache read and cache write add up");
1458
+ await new Promise((r) => setTimeout(r, 5)); // mtime granularity: a rewrite must change the memo key
1459
+ writeFileSync(
1460
+ join(fixture, "models.json"),
1461
+ JSON.stringify({ providers: { google: { models: [{ id: "m1", cost: { input: 10, output: 2, cacheRead: 0.1, cacheWrite: 3 } }] } } }),
1462
+ );
1463
+ const table2 = loadPriceTable();
1464
+ assert(table2 !== table1 && estimateCost(1_000_000, 0, 0, 0, "m1", "google") === 10, "a changed models.json is re-read");
1465
+
1466
+ rmSync(fixture, { recursive: true, force: true });
1467
+ console.log("usage-store.ts self-check OK");
1468
+ }