context-doctor 0.40.0 → 0.42.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.
Files changed (53) hide show
  1. package/README.md +12 -4
  2. package/dist/ab.js +3 -1
  3. package/dist/autopilot.d.ts +1 -1
  4. package/dist/autopilot.js +38 -24
  5. package/dist/budget.d.ts +102 -0
  6. package/dist/budget.js +550 -0
  7. package/dist/cachettl.js +12 -9
  8. package/dist/claudedir.d.ts +8 -0
  9. package/dist/claudedir.js +19 -0
  10. package/dist/cli.js +145 -15
  11. package/dist/codexdir.d.ts +11 -0
  12. package/dist/codexdir.js +20 -0
  13. package/dist/codexroute.d.ts +1 -0
  14. package/dist/codexroute.js +3 -1
  15. package/dist/compactwindow.js +12 -9
  16. package/dist/cursor.d.ts +23 -0
  17. package/dist/cursor.js +140 -6
  18. package/dist/doctor.d.ts +9 -0
  19. package/dist/doctor.js +49 -12
  20. package/dist/effective.d.ts +18 -0
  21. package/dist/effective.js +39 -4
  22. package/dist/extract.d.ts +12 -3
  23. package/dist/extract.js +39 -12
  24. package/dist/fileparams.d.ts +1 -1
  25. package/dist/fileparams.js +8 -8
  26. package/dist/fix.d.ts +23 -2
  27. package/dist/fix.js +86 -10
  28. package/dist/hook.js +45 -7
  29. package/dist/install.js +108 -47
  30. package/dist/ledger.d.ts +15 -0
  31. package/dist/ledger.js +30 -1
  32. package/dist/limits.d.ts +53 -6
  33. package/dist/limits.js +152 -77
  34. package/dist/mcp.js +58 -58
  35. package/dist/overhead.js +2 -1
  36. package/dist/pack.js +3 -2
  37. package/dist/proxy.d.ts +1 -1
  38. package/dist/proxy.js +1 -1
  39. package/dist/recall.js +3 -2
  40. package/dist/scan.d.ts +10 -0
  41. package/dist/scan.js +23 -1
  42. package/dist/session.js +2 -1
  43. package/dist/settingsedit.d.ts +4 -0
  44. package/dist/settingsedit.js +61 -3
  45. package/dist/spend.d.ts +183 -0
  46. package/dist/spend.js +493 -0
  47. package/dist/statusline.d.ts +9 -2
  48. package/dist/statusline.js +20 -4
  49. package/dist/subagentmodel.d.ts +141 -0
  50. package/dist/subagentmodel.js +408 -0
  51. package/dist/subagentpay.d.ts +11 -0
  52. package/dist/subagentpay.js +23 -4
  53. package/package.json +1 -1
package/dist/ledger.d.ts CHANGED
@@ -55,6 +55,21 @@ export interface CarriedTotals {
55
55
  * rotations rather than only the first.
56
56
  */
57
57
  export declare function foldTotals(entries: LedgerEntry[]): CarriedTotals;
58
+ /**
59
+ * Where context-doctor keeps its own state on a machine without Claude Code's
60
+ * folder (Codex or Gemini CLI alone): $XDG_STATE_HOME/context-doctor,
61
+ * ~/.local/state/context-doctor, or %LOCALAPPDATA%\context-doctor on Windows.
62
+ * Creating ~/.claude for it (the budget, the hooks' ledger) made `install`
63
+ * see a Claude Code that is not there, and left the folder behind.
64
+ */
65
+ export declare function fallbackStateDir(): string;
66
+ /**
67
+ * The folder our state files live in: ~/.claude (or CLAUDE_CONFIG_DIR) when
68
+ * it is there, as always; otherwise the fallback folder. Once the fallback
69
+ * holds our files it stays theirs, so a Claude Code installed later does not
70
+ * strand the ledger and the budget in it.
71
+ */
72
+ export declare function stateDir(): string;
58
73
  export declare function statePath(): string;
59
74
  export declare function ledgerPath(): string;
60
75
  /** Longest string field kept in a ledger entry (a model name, a session id). */
package/dist/ledger.js CHANGED
@@ -17,6 +17,7 @@
17
17
  * what it drops into a single rollup entry instead of discarding it.
18
18
  */
19
19
  import { appendFileSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
20
+ import { homedir } from "node:os";
20
21
  import { dirname, join } from "node:path";
21
22
  import { claudeDir } from "./claudedir.js";
22
23
  const EMPTY_CARRIED = {
@@ -78,8 +79,36 @@ export function foldTotals(entries) {
78
79
  }
79
80
  return out;
80
81
  }
82
+ /**
83
+ * Where context-doctor keeps its own state on a machine without Claude Code's
84
+ * folder (Codex or Gemini CLI alone): $XDG_STATE_HOME/context-doctor,
85
+ * ~/.local/state/context-doctor, or %LOCALAPPDATA%\context-doctor on Windows.
86
+ * Creating ~/.claude for it (the budget, the hooks' ledger) made `install`
87
+ * see a Claude Code that is not there, and left the folder behind.
88
+ */
89
+ export function fallbackStateDir() {
90
+ const xdg = process.env.XDG_STATE_HOME?.trim();
91
+ if (xdg)
92
+ return join(xdg, "context-doctor");
93
+ if (process.platform === "win32")
94
+ return join(process.env.LOCALAPPDATA?.trim() || join(homedir(), "AppData", "Local"), "context-doctor");
95
+ return join(homedir(), ".local", "state", "context-doctor");
96
+ }
97
+ /**
98
+ * The folder our state files live in: ~/.claude (or CLAUDE_CONFIG_DIR) when
99
+ * it is there, as always; otherwise the fallback folder. Once the fallback
100
+ * holds our files it stays theirs, so a Claude Code installed later does not
101
+ * strand the ledger and the budget in it.
102
+ */
103
+ export function stateDir() {
104
+ const fallback = fallbackStateDir();
105
+ if (existsSync(fallback))
106
+ return fallback;
107
+ const claude = claudeDir();
108
+ return existsSync(claude) ? claude : fallback;
109
+ }
81
110
  export function statePath() {
82
- return process.env.CONTEXT_DOCTOR_HOOK_STATE ?? join(claudeDir(), ".context-doctor-hook-state.json");
111
+ return process.env.CONTEXT_DOCTOR_HOOK_STATE ?? join(stateDir(), ".context-doctor-hook-state.json");
83
112
  }
84
113
  export function ledgerPath() {
85
114
  return join(dirname(statePath()), ".context-doctor-ledger.jsonl");
package/dist/limits.d.ts CHANGED
@@ -70,28 +70,75 @@ export declare function recordLimits(rateLimits: unknown, now?: number, path?: s
70
70
  /** Every Claude reading in the log since `since`. */
71
71
  export declare function readClaudeReadings(since?: number, path?: string): LimitReading[];
72
72
  export declare function codexSessionsRoot(home?: string): string;
73
+ /** Codex rollouts under `root` (YYYY/MM/DD folders, or flat) written since `since`. */
74
+ export declare function rolloutFiles(root: string, since: number): string[];
75
+ /** The token counts a Codex event's identity is made of, in its running total and its last request. */
76
+ export declare const CODEX_USAGE_FIELDS: readonly ["input_tokens", "cached_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"];
77
+ /**
78
+ * A Codex token_count event's identity: its running total and its last
79
+ * request. A forked rollout (a subagent's, a fork of a thread) begins with a
80
+ * copy of its parent's history, token_count events included, all stamped at
81
+ * the moment of the fork: seen on this machine, a subagent's rollout repeated
82
+ * 11 of its parent's 18 requests. The copy carries the same counts, so this
83
+ * key counts each request once, however many rollouts hold it. "" when the
84
+ * event has no running total (nothing to tell a copy by).
85
+ */
86
+ export declare function codexEventKey(total: unknown, last: unknown): string;
73
87
  /**
74
88
  * Codex readings and usage since `since`. A token_count event repeats the
75
89
  * last request's usage when only the limits were refreshed, so a request is
76
- * counted when the running total moves.
90
+ * counted when the running total moves. A forked rollout's copy of its
91
+ * parent's events (codexEventKey) is counted once, at the earliest time met:
92
+ * the copy is stamped at the fork, its limits readings stale by then.
77
93
  */
78
94
  export declare function codexLimitData(since: number, root?: string): {
79
95
  readings: LimitReading[];
80
96
  usage: UsagePoint[];
81
97
  };
82
- /**
83
- * Every Claude Code request between `since` and `until`, main threads and
84
- * subagents alike (both draw on the same limits), each reply once.
85
- */
86
98
  /**
87
99
  * What the usage fit takes from a Claude Code transcript (subagents' too):
88
100
  * every assistant row with usage, in order. A later row of a reply already
89
101
  * met keeps only its id and output tokens: it is a repeat, read only for the
90
- * output a streamed reply settles on its last row.
102
+ * output a streamed reply settles on its last row. `isSidechain` is kept for
103
+ * `spend`, which tells a subagent inlined in an older transcript from the
104
+ * main thread.
91
105
  */
92
106
  export declare const USAGE_ROWS: Extractor<{
93
107
  ids: Record<string, 1>;
94
108
  }>;
109
+ /** One Claude Code request as `claudeFileUsage` reads it: the usage point, and what `spend` and `budget` add up. */
110
+ export interface ClaudeRequest extends UsagePoint {
111
+ /** The row's uuid: what tells a fork's copy of a reply from the reply itself. */
112
+ uuid?: string;
113
+ /** The reply's message id, which its later rows share. */
114
+ id?: string;
115
+ /** Written as a subagent's, inline in the main transcript (older Claude Code). */
116
+ sidechain?: boolean;
117
+ /** The prompt's part of `usd` (input, cache writes, cache reads): what `savings` bills. */
118
+ promptUsd: number;
119
+ }
120
+ /**
121
+ * The requests of one Claude Code transcript between `since` and `until`,
122
+ * each reply once, its output settled on its last row. `runRows` is shared
123
+ * by every file of one report, so a fork's copy of its parent's replies is
124
+ * counted once, in the file met first (replyCounter). Throws when the
125
+ * transcript cannot be read.
126
+ */
127
+ export declare function claudeFileUsage(file: string, since: number, until?: number, runRows?: Set<string>): ClaudeRequest[];
128
+ /**
129
+ * The Claude Code transcripts written since `since`: each session's main
130
+ * transcript (`tops`, or every one under the projects folder, newest
131
+ * first), each followed by its subagents'.
132
+ */
133
+ export declare function claudeUsageFiles(since: number, tops?: string[]): Array<{
134
+ file: string;
135
+ top: string;
136
+ subagent: boolean;
137
+ }>;
138
+ /**
139
+ * Every Claude Code request between `since` and `until`, main threads and
140
+ * subagents alike (both draw on the same limits), each reply once.
141
+ */
95
142
  export declare function claudeUsage(since: number, until?: number, paths?: string[]): UsagePoint[];
96
143
  export interface WindowStatus {
97
144
  window: string;
package/dist/limits.js CHANGED
@@ -28,6 +28,7 @@
28
28
  import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, statSync, writeFileSync } from "node:fs";
29
29
  import { homedir } from "node:os";
30
30
  import { dirname, join } from "node:path";
31
+ import { codexDir } from "./codexdir.js";
31
32
  import { statePath } from "./ledger.js";
32
33
  import { forEachLine, listSessions, outputSettler, replyCounter, isClaudeSession } from "./session.js";
33
34
  import { subagentDir } from "./subagents.js";
@@ -175,33 +176,41 @@ export function readClaudeReadings(since = 0, path = limitsLogPath()) {
175
176
  // Codex: readings and usage, both from its rollouts
176
177
  // ---------------------------------------------------------------------------
177
178
  export function codexSessionsRoot(home = homedir()) {
178
- return join(home, ".codex", "sessions");
179
+ return join(codexDir(home), "sessions");
179
180
  }
180
- function rolloutFiles(root, since) {
181
+ /** Codex rollouts under `root` (YYYY/MM/DD folders, or flat) written since `since`. */
182
+ export function rolloutFiles(root, since) {
181
183
  const out = [];
182
184
  const walk = (dir, depth) => {
183
- let names;
185
+ let entries;
184
186
  try {
185
- names = readdirSync(dir);
187
+ entries = readdirSync(dir, { withFileTypes: true });
186
188
  }
187
189
  catch {
188
190
  return;
189
191
  }
190
- for (const name of names) {
191
- const p = join(dir, name);
192
- let st;
193
- try {
194
- st = statSync(p);
195
- }
196
- catch {
197
- continue;
192
+ for (const e of entries) {
193
+ const p = join(dir, e.name);
194
+ // A folder needs no stat of its own; a symlink is stat'ed to see what it is.
195
+ let isDir = e.isDirectory();
196
+ if (e.isSymbolicLink()) {
197
+ try {
198
+ isDir = statSync(p).isDirectory();
199
+ }
200
+ catch {
201
+ continue;
202
+ }
198
203
  }
199
- if (st.isDirectory()) {
204
+ if (isDir) {
200
205
  if (depth < 3)
201
206
  walk(p, depth + 1);
202
207
  }
203
- else if (name.endsWith(".jsonl") && st.mtimeMs >= since) {
204
- out.push(p);
208
+ else if (e.name.endsWith(".jsonl")) {
209
+ try {
210
+ if (statSync(p).mtimeMs >= since)
211
+ out.push(p);
212
+ }
213
+ catch { /* vanished */ }
205
214
  }
206
215
  }
207
216
  };
@@ -209,6 +218,25 @@ function rolloutFiles(root, since) {
209
218
  return out;
210
219
  }
211
220
  const num = (v) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0);
221
+ /** The token counts a Codex event's identity is made of, in its running total and its last request. */
222
+ export const CODEX_USAGE_FIELDS = ["input_tokens", "cached_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"];
223
+ /**
224
+ * A Codex token_count event's identity: its running total and its last
225
+ * request. A forked rollout (a subagent's, a fork of a thread) begins with a
226
+ * copy of its parent's history, token_count events included, all stamped at
227
+ * the moment of the fork: seen on this machine, a subagent's rollout repeated
228
+ * 11 of its parent's 18 requests. The copy carries the same counts, so this
229
+ * key counts each request once, however many rollouts hold it. "" when the
230
+ * event has no running total (nothing to tell a copy by).
231
+ */
232
+ export function codexEventKey(total, last) {
233
+ if (!total || typeof total !== "object" || !last || typeof last !== "object")
234
+ return "";
235
+ const t = total, l = last;
236
+ if (!num(t.total_tokens))
237
+ return "";
238
+ return `cx:${CODEX_USAGE_FIELDS.map((k) => num(t[k])).join(",")}/${CODEX_USAGE_FIELDS.map((k) => num(l[k])).join(",")}`;
239
+ }
212
240
  /** "codex:300", "codex:10080"; a limit id other than "codex" is kept in the key. */
213
241
  function codexWindow(limitId, minutes, plan) {
214
242
  // The plan is part of the key: two sign-ins (a team plan, a free one) are two accounts' limits.
@@ -218,13 +246,16 @@ function codexWindow(limitId, minutes, plan) {
218
246
  /**
219
247
  * Codex readings and usage since `since`. A token_count event repeats the
220
248
  * last request's usage when only the limits were refreshed, so a request is
221
- * counted when the running total moves.
249
+ * counted when the running total moves. A forked rollout's copy of its
250
+ * parent's events (codexEventKey) is counted once, at the earliest time met:
251
+ * the copy is stamped at the fork, its limits readings stale by then.
222
252
  */
223
253
  export function codexLimitData(since, root = codexSessionsRoot()) {
224
254
  const readings = [];
225
255
  const usage = [];
226
256
  if (!existsSync(root))
227
257
  return { readings, usage };
258
+ const events = [];
228
259
  for (const file of rolloutFiles(root, since)) {
229
260
  let model;
230
261
  let total = -1;
@@ -254,50 +285,61 @@ export function codexLimitData(since, root = codexSessionsRoot()) {
254
285
  return;
255
286
  const runTotal = num(p.info?.total_token_usage?.total_tokens);
256
287
  const last = p.info?.last_token_usage;
288
+ const ev = { ts, key: codexEventKey(p.info?.total_token_usage, last), file, readings: [] };
257
289
  // No running total recorded: every event is a request.
258
290
  if (last && num(last.input_tokens) > 0 && (runTotal === 0 || runTotal !== total)) {
259
291
  total = runTotal;
260
292
  const u = openAIUsage(last);
261
293
  const price = pricingFor(model);
262
- usage.push({ ts, app: "codex", model, input: num(u.input_tokens), read: num(u.cache_read_input_tokens), write: num(u.cache_creation_input_tokens), output: num(u.output_tokens), usd: price ? usageCost(u, price).totalUsd : 0 });
294
+ ev.point = { ts, app: "codex", model, input: num(u.input_tokens), read: num(u.cache_read_input_tokens), write: num(u.cache_creation_input_tokens), output: num(u.output_tokens), usd: price ? usageCost(u, price).totalUsd : 0 };
263
295
  }
264
296
  const rl = p.rate_limits;
265
- if (!rl || typeof rl !== "object")
266
- return;
267
- for (const slot of ["primary", "secondary"]) {
268
- const w = rl[slot];
269
- const pct = w?.used_percent;
270
- const minutes = num(w?.window_minutes);
271
- if (typeof pct !== "number" || !Number.isFinite(pct) || pct < 0 || pct > 1000 || !minutes)
272
- continue;
273
- const reset = num(w.resets_at);
274
- readings.push({ ts, app: "codex", window: codexWindow(rl.limit_id, minutes, rl.plan_type), pct, resetsAt: reset ? reset * 1000 : undefined, windowMs: minutes * MIN, plan: typeof rl.plan_type === "string" ? rl.plan_type.slice(0, 20) : undefined });
297
+ if (rl && typeof rl === "object") {
298
+ for (const slot of ["primary", "secondary"]) {
299
+ const w = rl[slot];
300
+ const pct = w?.used_percent;
301
+ const minutes = num(w?.window_minutes);
302
+ if (typeof pct !== "number" || !Number.isFinite(pct) || pct < 0 || pct > 1000 || !minutes)
303
+ continue;
304
+ const reset = num(w.resets_at);
305
+ ev.readings.push({ ts, app: "codex", window: codexWindow(rl.limit_id, minutes, rl.plan_type), pct, resetsAt: reset ? reset * 1000 : undefined, windowMs: minutes * MIN, plan: typeof rl.plan_type === "string" ? rl.plan_type.slice(0, 20) : undefined });
306
+ }
275
307
  }
308
+ if (ev.point || ev.readings.length)
309
+ events.push(ev);
276
310
  });
277
311
  }
278
312
  catch {
279
313
  /* one unreadable rollout must not sink the report */
280
314
  }
281
315
  }
282
- readings.sort((a, b) => a.ts - b.ts);
283
- usage.sort((a, b) => a.ts - b.ts);
316
+ // A key belongs to the rollout that has it first; within it, a refresh of the limits shares its request's key.
317
+ const owner = new Map();
318
+ for (const ev of events.sort((a, b) => a.ts - b.ts)) {
319
+ if (ev.key) {
320
+ const first = owner.get(ev.key) ?? (owner.set(ev.key, ev.file), ev.file);
321
+ if (first !== ev.file)
322
+ continue;
323
+ }
324
+ if (ev.point)
325
+ usage.push(ev.point);
326
+ readings.push(...ev.readings);
327
+ }
284
328
  return { readings, usage };
285
329
  }
286
330
  // ---------------------------------------------------------------------------
287
331
  // Claude usage: every request on this machine, subagents included
288
332
  // ---------------------------------------------------------------------------
289
- /**
290
- * Every Claude Code request between `since` and `until`, main threads and
291
- * subagents alike (both draw on the same limits), each reply once.
292
- */
293
333
  /**
294
334
  * What the usage fit takes from a Claude Code transcript (subagents' too):
295
335
  * every assistant row with usage, in order. A later row of a reply already
296
336
  * met keeps only its id and output tokens: it is a repeat, read only for the
297
- * output a streamed reply settles on its last row.
337
+ * output a streamed reply settles on its last row. `isSidechain` is kept for
338
+ * `spend`, which tells a subagent inlined in an older transcript from the
339
+ * main thread.
298
340
  */
299
341
  export const USAGE_ROWS = {
300
- id: "usage.1",
342
+ id: "usage.2",
301
343
  init: () => ({ ids: {} }),
302
344
  line(line, row, out, st) {
303
345
  if (!line.includes('"usage"'))
@@ -319,63 +361,96 @@ export const USAGE_ROWS = {
319
361
  }
320
362
  st.ids[m.id] = 1;
321
363
  }
322
- out.push(pick({ ...e, message: pick({ ...m, usage: slimUsage(m.usage) }, ["id", "model", "usage"]) }, ["type", "uuid", "timestamp", "message"]));
364
+ out.push(pick({ ...e, isSidechain: e.isSidechain === true || undefined, message: pick({ ...m, usage: slimUsage(m.usage) }, ["id", "model", "usage"]) }, ["type", "uuid", "timestamp", "isSidechain", "message"]));
323
365
  },
324
366
  };
325
- export function claudeUsage(since, until = Infinity, paths) {
326
- const tops = paths ?? listSessions(10_000).filter((s) => isClaudeSession(s) && s.modifiedAt.getTime() >= since).map((s) => s.path);
367
+ /**
368
+ * The requests of one Claude Code transcript between `since` and `until`,
369
+ * each reply once, its output settled on its last row. `runRows` is shared
370
+ * by every file of one report, so a fork's copy of its parent's replies is
371
+ * counted once, in the file met first (replyCounter). Throws when the
372
+ * transcript cannot be read.
373
+ */
374
+ export function claudeFileUsage(file, since, until = Infinity, runRows) {
375
+ const out = [];
376
+ const sighting = replyCounter(runRows);
377
+ const settle = outputSettler();
378
+ const byId = new Map();
379
+ rowsOf(file, USAGE_ROWS).forEach((e) => {
380
+ const m = e?.message;
381
+ if (e?.type !== "assistant" || !m?.usage)
382
+ return;
383
+ const seen = sighting(e);
384
+ if (seen === "repeat") {
385
+ const known = typeof m.id === "string" ? byId.get(m.id) : undefined;
386
+ const more = settle(e, false);
387
+ if (known && more) {
388
+ known.point.output += more;
389
+ if (known.price)
390
+ known.point.usd += (more * known.price.outputPerM) / 1e6;
391
+ }
392
+ return;
393
+ }
394
+ if (seen !== "new")
395
+ return;
396
+ settle(e, true);
397
+ const ts = Date.parse(String(e.timestamp ?? ""));
398
+ if (!Number.isFinite(ts) || ts < since || ts > until)
399
+ return;
400
+ const u = m.usage;
401
+ const point = { ts, app: "claude", model: realModel(m.model), input: num(u.input_tokens), read: num(u.cache_read_input_tokens), write: num(u.cache_creation_input_tokens), output: num(u.output_tokens), usd: 0, promptUsd: 0 };
402
+ if (point.input + point.read + point.write === 0)
403
+ return;
404
+ if (typeof e.uuid === "string")
405
+ point.uuid = e.uuid;
406
+ if (typeof m.id === "string")
407
+ point.id = m.id;
408
+ if (e.isSidechain === true)
409
+ point.sidechain = true;
410
+ const price = pricingFor(point.model);
411
+ if (price) {
412
+ const c = usageCost(u, price);
413
+ point.usd = c.totalUsd;
414
+ point.promptUsd = c.promptUsd;
415
+ }
416
+ out.push(point);
417
+ if (typeof m.id === "string")
418
+ byId.set(m.id, { point, price });
419
+ });
420
+ return out;
421
+ }
422
+ /**
423
+ * The Claude Code transcripts written since `since`: each session's main
424
+ * transcript (`tops`, or every one under the projects folder, newest
425
+ * first), each followed by its subagents'.
426
+ */
427
+ export function claudeUsageFiles(since, tops) {
428
+ const mains = tops ?? listSessions(10_000).filter((s) => isClaudeSession(s) && s.modifiedAt.getTime() >= since).map((s) => s.path);
327
429
  const files = [];
328
- for (const t of tops) {
329
- files.push(t);
430
+ for (const t of mains) {
431
+ files.push({ file: t, top: t, subagent: false });
330
432
  const dir = subagentDir(t);
331
433
  try {
332
434
  for (const f of readdirSync(dir))
333
435
  if (f.endsWith(".jsonl") && statSync(join(dir, f)).mtimeMs >= since)
334
- files.push(join(dir, f));
436
+ files.push({ file: join(dir, f), top: t, subagent: true });
335
437
  }
336
438
  catch {
337
439
  /* no subagents */
338
440
  }
339
441
  }
442
+ return files;
443
+ }
444
+ /**
445
+ * Every Claude Code request between `since` and `until`, main threads and
446
+ * subagents alike (both draw on the same limits), each reply once.
447
+ */
448
+ export function claudeUsage(since, until = Infinity, paths) {
340
449
  const out = [];
341
450
  const runRows = new Set();
342
- for (const file of files) {
343
- const sighting = replyCounter(runRows);
344
- const settle = outputSettler();
345
- const byId = new Map();
451
+ for (const { file } of claudeUsageFiles(since, paths)) {
346
452
  try {
347
- rowsOf(file, USAGE_ROWS).forEach((e) => {
348
- const m = e?.message;
349
- if (e?.type !== "assistant" || !m?.usage)
350
- return;
351
- const seen = sighting(e);
352
- if (seen === "repeat") {
353
- const known = typeof m.id === "string" ? byId.get(m.id) : undefined;
354
- const more = settle(e, false);
355
- if (known && more) {
356
- known.point.output += more;
357
- if (known.price)
358
- known.point.usd += (more * known.price.outputPerM) / 1e6;
359
- }
360
- return;
361
- }
362
- if (seen !== "new")
363
- return;
364
- settle(e, true);
365
- const ts = Date.parse(String(e.timestamp ?? ""));
366
- if (!Number.isFinite(ts) || ts < since || ts > until)
367
- return;
368
- const u = m.usage;
369
- const point = { ts, app: "claude", model: realModel(m.model), input: num(u.input_tokens), read: num(u.cache_read_input_tokens), write: num(u.cache_creation_input_tokens), output: num(u.output_tokens), usd: 0 };
370
- if (point.input + point.read + point.write === 0)
371
- return;
372
- const price = pricingFor(point.model);
373
- if (price)
374
- point.usd = usageCost(u, price).totalUsd;
375
- out.push(point);
376
- if (typeof m.id === "string")
377
- byId.set(m.id, { point, price });
378
- });
453
+ out.push(...claudeFileUsage(file, since, until, runRows));
379
454
  }
380
455
  catch {
381
456
  /* skip an unreadable transcript */