context-doctor 0.42.0 → 0.44.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 (48) hide show
  1. package/README.md +6 -3
  2. package/dist/budget.d.ts +52 -0
  3. package/dist/budget.js +209 -59
  4. package/dist/cachettl.d.ts +5 -1
  5. package/dist/cachettl.js +10 -25
  6. package/dist/cli.js +33 -15
  7. package/dist/codexcompact.d.ts +137 -0
  8. package/dist/codexcompact.js +581 -0
  9. package/dist/compactwindow.js +2 -2
  10. package/dist/cursor.d.ts +10 -0
  11. package/dist/cursor.js +20 -0
  12. package/dist/doctor.d.ts +9 -0
  13. package/dist/doctor.js +55 -0
  14. package/dist/fanout.js +4 -2
  15. package/dist/fix.d.ts +38 -4
  16. package/dist/fix.js +249 -21
  17. package/dist/hook.js +65 -16
  18. package/dist/install.js +56 -19
  19. package/dist/ledger.d.ts +2 -1
  20. package/dist/ledger.js +1 -0
  21. package/dist/limits.d.ts +6 -2
  22. package/dist/limits.js +19 -16
  23. package/dist/mcp.js +63 -63
  24. package/dist/mcpclient.js +19 -19
  25. package/dist/mcpschema.js +5 -9
  26. package/dist/overhead.d.ts +7 -2
  27. package/dist/overhead.js +11 -3
  28. package/dist/pack.js +23 -3
  29. package/dist/pricing.d.ts +25 -5
  30. package/dist/pricing.js +157 -48
  31. package/dist/proxy.d.ts +15 -1
  32. package/dist/proxy.js +33 -5
  33. package/dist/prune.d.ts +8 -0
  34. package/dist/prune.js +20 -9
  35. package/dist/savings.js +2 -1
  36. package/dist/sessionprice.d.ts +77 -0
  37. package/dist/sessionprice.js +267 -0
  38. package/dist/settingsedit.js +3 -2
  39. package/dist/spend.d.ts +25 -3
  40. package/dist/spend.js +67 -19
  41. package/dist/subagentmodel.js +11 -1
  42. package/dist/subagentpay.d.ts +17 -0
  43. package/dist/subagentpay.js +41 -2
  44. package/dist/subagents.d.ts +24 -0
  45. package/dist/subagents.js +82 -17
  46. package/dist/tooloutput.d.ts +120 -0
  47. package/dist/tooloutput.js +357 -0
  48. package/package.json +1 -1
package/README.md CHANGED
@@ -28,12 +28,12 @@ Pick where you work. Each takes about a minute and is fully reversible.
28
28
  | **claude.ai, ChatGPT, phone apps** | `npx context-doctor instructions --copy`, then paste into the app's personal preferences (it tells you where). ChatGPT can also reach the MCP server at a URL ([how](./docs/chat-apps.md#chatgpt)) |
29
29
  | **Your own app on an LLM API** | Run `npx context-doctor proxy --autopilot` and point `ANTHROPIC_BASE_URL`, `OPENAI_BASE_URL` (add `/v1`) or `GOOGLE_GEMINI_BASE_URL` at the proxy on `127.0.0.1:8787`, plain HTTP ([exact values](./docs/proxy.md)). No proxy possible? Wrap the SDK client: `withContextDoctor(new Anthropic())` ([library](./docs/library.md)) |
30
30
  | **Python / RAG pipelines** | `pip install "git+https://github.com/KushalP1/context-doctor#subdirectory=python"` (PyPI release coming), then `pack_documents(retrieved_docs, question, budget=4000)` trims LangChain or LlamaIndex results to the chunks that matter. [Python README](./python/README.md) |
31
- | **GitHub pull requests** | `uses: KushalP1/context-doctor@v0.42.0` comments how much a PR grows CLAUDE.md, AGENTS.md and rules, and can fail over a budget ([setup](./docs/ci.md)) |
31
+ | **GitHub pull requests** | `uses: KushalP1/context-doctor@v0.44.0` comments how much a PR grows CLAUDE.md, AGENTS.md and rules, and can fail over a budget ([setup](./docs/ci.md)) |
32
32
 
33
33
  ## What it does
34
34
 
35
35
  **Measure, in dollars, on your own history** ([profiling](./docs/profiling.md))
36
- - `spend`: one bill across Claude Code (subagents included), Codex, Gemini CLI and Cursor, by tool, project, model and day, at list prices ([spend and budget](./docs/spend.md)).
36
+ - `spend`: one bill across Claude Code (subagents and workflow agents included), Codex, Gemini CLI and Cursor, by tool, project, model and day, at list prices ([spend and budget](./docs/spend.md)).
37
37
  - `savings`: what your recent Claude Code sessions cost and what each fix below would have saved, replayed request by request against what you were billed.
38
38
  - `overhead`: what every request re-reads before your message (system prompt, tools, MCP servers, CLAUDE.md, rules, memory), each file priced per month.
39
39
  - `tasks`, `reads`, `subagents`, `compactions`: cost per commit; files read into session after session; whether each subagent was cheaper than the same steps in the parent; whether sessions work worse after compacting.
@@ -53,6 +53,7 @@ Pick where you work. Each takes about a minute and is fully reversible.
53
53
  - A subagent price (`PreToolUse` on the Agent tool) shows what a subagent costs before it starts, at your own median for that type (the author's: $3.99 for general-purpose, $1.43 for Explore, 422 runs in 30 days), with the Sonnet price where it would run on Opus or Fable, and a total when launches bunch up. It never blocks.
54
54
  - A compaction hook (`PreCompact`) tells each Claude Code compaction what the session cannot lose (files changed, open tasks, your instructions, failing tests), so compacting saves tokens without losing the thread.
55
55
  - An every-prompt hook (Claude Code, Codex, Gemini CLI; Cursor after each tool call) tells the model its real context size and the largest waste, and offers `/compact` when you return to a big session after the cache expired.
56
+ - A session's own price: once a session passes $25, $100 and $500 (subagents included), the every-prompt hook tells you what it has cost and what each message now costs, and that `/compact` or a fresh session cuts it ([docs](./docs/spend.md#a-sessions-own-price-while-it-runs)).
56
57
  - `budget 50/day` (or `/week`): the every-prompt hook in Claude Code, Codex and Gemini CLI says when today's spend passes 50%, 80% and 100% of it, and with `--block` holds prompts over budget; the status line shows `$12/$50 today`.
57
58
  - `compact-window`: sets Claude Code's own auto-compact window, measured on your history first. Works in the desktop app too.
58
59
  - `cache-ttl`: replays your own pauses at a 5-minute and a 1-hour prompt cache and sets Claude Code's `promptCacheTtl` to the cheaper one (the author's: 7% less main-conversation input at 1 hour; 22% less than the 5-minute default an API key gets). Same content either way, so no quality cost ([fixes](./docs/fix.md)).
@@ -132,7 +133,7 @@ Rules 1-4 end exactly at character 512, the part ChatGPT's guide says must stand
132
133
  | Command | What it does |
133
134
  |---|---|
134
135
  | `context-doctor install` / `uninstall` | Wire (or remove) everything it finds: the MCP server for Claude Desktop, Claude Code, Cursor, Codex, Gemini CLI, Google Antigravity and GitHub Copilot; the Agent Skill (Claude Code, Codex, Antigravity); the every-prompt hook (Claude Code, Codex, Gemini CLI's `BeforeAgent`, Cursor's `postToolUse`, `postToolUseFailure` and `sessionStart`); Claude Code's `PreCompact`, `SessionStart`, `PreToolUse` (the subagent price) and, on 2.1.251+, `PreModelSwitch` hooks; Copilot's `sessionStart` (the standing rules). `--statusline` adds the status bar line ([details](./docs/install.md)) |
135
- | `context-doctor fix [--apply ids\|all] [--share]` / `fix undo` | Every lever ranked by what it would have saved on your last 30 days (compact earlier, the cache lifetime, autopilot, MCP tool search, unused servers, the subagents' model), with what each costs in quality; applies one only on a yes (the subagents' model only when named), `fix undo` reverts exactly what it changed, later runs show what each saved since ([details](./docs/fix.md)) |
136
+ | `context-doctor fix [--apply ids\|all] [--share]` / `fix undo` | Every lever ranked by what it would have saved on your last 30 days (compact earlier, the cache lifetime, autopilot, MCP tool search, unused servers, the subagents' model, long Bash output to a file, Codex's auto-compact limit), with what each costs in quality; applies one only on a yes (the subagents' model only when named), `fix undo` reverts exactly what it changed, later runs show what each saved since ([details](./docs/fix.md)) |
136
137
  | `context-doctor spend [--days n] [--share]` | One bill across every tool on this machine: Claude Code (main conversation and subagents), Codex, Gemini CLI and Cursor (an estimate: no cache split), by tool, project, model and day, with what drives it ([docs](./docs/spend.md)) |
137
138
  | `context-doctor budget [<$>/day\|<$>/week [--block]\|off]` | A spend budget the every-prompt hook applies: a line at 50%, 80% and 100%, and with `--block` prompts over it are held until you raise it or turn it off ([docs](./docs/spend.md#a-budget-the-hook-applies-context-doctor-budget)) |
138
139
  | `context-doctor doctor` | Self-check the whole installation — one pasteable ✓/✗ diagnosis with fixes, including which surfaces autopilot can reach and any other program on its port |
@@ -180,6 +181,8 @@ Rules 1-4 end exactly at character 512, the part ChatGPT's guide says must stand
180
181
 
181
182
  ## What's new
182
183
 
184
+ - **0.44 Workflow agents on the bill, current prices, and an audit**: Claude Code's workflow agents were in no report: on the author's last 30 days $1,494 of $5,542. `spend`, the budget, a session's price, `subagents` and `fix` now count them, and `spend` equals an independent sum of every transcript to the cent. Prices re-read from each provider (Sonnet 5.5's cache read $0.10, gpt-5.5 $5/$30, the gpt-6 family); estimates are labelled. An audit fixed `overhead --mcp` launching a cloned repository's unapproved MCP servers, `pack_context` returning the agents' sign-in files, and more ([details](./ROADMAP.md#shipped-in-0440-workflow-agents-on-the-bill-current-prices-and-an-audit-of-043)).
185
+ - **0.43 Long tool output, `fix` for Codex, and a session's price**: every Bash result stays in the conversation and is re-read on every later message until a compaction; `fix` now replays them at lower caps and, on a yes, sets Claude Code's `bashOutputMaxChars`, so longer output goes to a file the model can still open after a 2,000-character preview (the author's 30 days: $323 less at 8k, 9% of input). `fix` also works for Codex: it replays your rollouts at earlier auto-compact limits and sets `model_auto_compact_token_limit` in `config.toml`, on a machine with only Codex too. And the every-prompt hook now tells you once when a session passes $25, $100 and $500, with what each message costs from there (the author's: 15 sessions passed $25 in 30 days and spent $3,369 after).
183
186
  - **0.42 An audit of 0.41**: each Codex request counts once (forks repeat their parent's), the budget no longer double-counts a reply streamed across midnight, unpriced models show as such instead of $0, Cursor is read after it quits, and `CODEX_HOME` is followed everywhere. `fix`'s subagent lever reads agent files the way Claude Code merges them, and every writer of `settings.json` takes one lock, so concurrent runs lose nothing ([details](./ROADMAP.md#shipped-in-0420-an-audit-of-041)).
184
187
  - **0.41 One bill, a budget, and the subagents' model**: `context-doctor spend` puts Claude Code (subagents included), Codex, Gemini CLI and Cursor on one bill by tool, project, model and day. `context-doctor budget 50/day` has the every-prompt hook tell you at 50%, 80% and 100%, and with `--block` holds prompts over budget; the status line shows `$12/$50 today`, at about 5 ms a prompt. `fix` gains `subagent-model`: subagents run on your main conversation's model (Opus or Fable included), and `CLAUDE_CODE_SUBAGENT_MODEL` set to Sonnet 5.5 would have cost the author $632 less in 30 days (38% of the subagents' $1,658); it changes the model, so it is applied only when you name it, and `fix undo` reverts it.
185
188
  - **0.40 Reports in under a second**: `fix`, `savings`, `compact-window`, `cache-ttl`, `cache-misses` and `overhead` read each transcript once and keep what they took from it in `~/.cache/context-doctor`, so a second run reads only what was appended: `fix` 23.5 s → 0.4 s, `savings` 41 s → 0.6 s on the author's 2.7 GB history, every figure unchanged ([details](./docs/performance.md#the-transcript-cache)). Also from a QA pass on 0.39: `install` then `uninstall` gives every config back byte for byte, and `doctor` warns about an out-of-date skill.
package/dist/budget.d.ts CHANGED
@@ -49,6 +49,8 @@ export declare function parseBudget(arg: string): {
49
49
  error: string;
50
50
  };
51
51
  export declare function readBudget(): Budget | undefined;
52
+ /** A whole file renamed into place, so two prompts at once never read half of one. */
53
+ export declare function writeWhole(path: string, value: unknown): void;
52
54
  export declare function writeBudget(b: Budget): void;
53
55
  /** Remove the budget and its ledger. True when there was one. */
54
56
  export declare function clearBudget(): boolean;
@@ -56,6 +58,50 @@ export declare function clearBudget(): boolean;
56
58
  export declare function periodStart(period: Period, now?: number): number;
57
59
  /** When the period holding `now` ends (the next one starts). */
58
60
  export declare function periodEnd(period: Period, now?: number): number;
61
+ /**
62
+ * One transcript as last read: size, time, inode; the period's requests in
63
+ * it as keys ("" for none) and dollars. A Claude Code transcript also keeps
64
+ * where reading stopped (`o`, after the last whole line) and its last
65
+ * replies (`r`: message id, index into k/d or -1, output so far, output
66
+ * price per 1M), so an append is read from there: a reply's later rows are
67
+ * met within its last few, and only settle its output. `a` fingerprints the
68
+ * bytes before `o` (the shared scan's anchorOf): a transcript rewritten in
69
+ * place, same inode and no smaller, is read again in full, not from `o`.
70
+ * `x` lists the requests on a model with no list price (index into k/d,
71
+ * model): in `d` at $0, and said so rather than silently left out. `y`
72
+ * lists those priced only by their model's family (an estimate), the same way.
73
+ */
74
+ export interface FileEntry {
75
+ t: Tool;
76
+ s: number;
77
+ m: number;
78
+ i: number;
79
+ k: string[];
80
+ d: number[];
81
+ o?: number;
82
+ a?: string;
83
+ r?: Array<[string, number, number, number]>;
84
+ x?: Array<[number, string]>;
85
+ y?: Array<[number, string]>;
86
+ }
87
+ /** A ledger entry this version can use: a damaged one threw on every prompt until its transcript changed. */
88
+ export declare function wellFormed(e: FileEntry | undefined): e is FileEntry;
89
+ /**
90
+ * One transcript's entry brought up to date: kept when the file is as last
91
+ * read, read from where the last read stopped when a Claude Code transcript
92
+ * only grew, read in full otherwise. `read`: the bytes read, -1 when the
93
+ * entry was kept as it was. Undefined when the file cannot be read now.
94
+ * `direct`: a Claude Code transcript met for the first time is read here,
95
+ * not through the shared scan, which keeps a cache entry of it on disk (the
96
+ * session price reads one session, and writes nothing while it has nothing
97
+ * to say). `own`: a Claude Code transcript's rows of other sessions are not
98
+ * counted (readAppended); only with `direct`, which reads every Claude Code
99
+ * transcript itself.
100
+ */
101
+ export declare function refreshEntry(tool: Tool, file: string, prev: FileEntry | undefined, since: number, direct?: boolean, own?: string): {
102
+ e: FileEntry;
103
+ read: number;
104
+ } | undefined;
59
105
  export interface PeriodSpend {
60
106
  start: number;
61
107
  end: number;
@@ -66,6 +112,12 @@ export interface PeriodSpend {
66
112
  requests: number;
67
113
  models: string[];
68
114
  };
115
+ /** Requests on a model priced only by its family: in `usd`, an estimate. */
116
+ estimated?: {
117
+ requests: number;
118
+ usd: number;
119
+ models: string[];
120
+ };
69
121
  }
70
122
  /**
71
123
  * What the period holding `now` has cost so far, across Claude Code, Codex
package/dist/budget.js CHANGED
@@ -29,9 +29,10 @@ import { dirname, join } from "node:path";
29
29
  import { codexDir } from "./codexdir.js";
30
30
  import { fallbackStateDir, statePath } from "./ledger.js";
31
31
  import { claudeCodePresent, claudeDir } from "./claudedir.js";
32
- import { claudeFileUsage, claudeUsageFiles, codexSessionsRoot, rolloutFiles, USAGE_ROWS } from "./limits.js";
32
+ import { claudeFileUsage, codexSessionsRoot, rolloutFiles, SUBAGENT_LOOKBACK_MS, USAGE_ROWS } from "./limits.js";
33
+ import { subagentFiles } from "./subagents.js";
33
34
  import { codexFileSpend, codexFiles, geminiFileSpend, geminiFiles, TOOL_NAME } from "./spend.js";
34
- import { pricingFor, usageCost } from "./pricing.js";
35
+ import { hasKnownPrice, isUnbilledModel, pricingFor, usageCost } from "./pricing.js";
35
36
  import { anchorOf, rowsOf } from "./scan.js";
36
37
  import { realModel } from "./tokens.js";
37
38
  /** Beside the hook state and the ledger: ~/.claude/.context-doctor-budget.json. */
@@ -69,7 +70,7 @@ export function readBudget() {
69
70
  return undefined;
70
71
  }
71
72
  /** A whole file renamed into place, so two prompts at once never read half of one. */
72
- function writeWhole(path, value) {
73
+ export function writeWhole(path, value) {
73
74
  const tmp = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
74
75
  try {
75
76
  mkdirSync(dirname(path), { recursive: true });
@@ -91,6 +92,52 @@ export function writeBudget(b) {
91
92
  const st = readState();
92
93
  if (st)
93
94
  writeWhole(budgetStatePath(), { ...st, warned: 0 });
95
+ clearSaid();
96
+ }
97
+ /**
98
+ * The thresholds said this period, one marker file each
99
+ * (~/.claude/.context-doctor-budget-said.d/<period start>-<percent>). The
100
+ * ledger records them too, but it is read, then written: two prompts at once
101
+ * (two sessions) could both read "not said" and both say it.
102
+ */
103
+ function saidDir() {
104
+ return join(dirname(budgetStatePath()), ".context-doctor-budget-said.d");
105
+ }
106
+ /** True for exactly one caller: the marker of `level` (and of the lower thresholds, so a stale lower one is not said after it) did not exist. */
107
+ function claimSaid(start, level) {
108
+ const create = (t) => {
109
+ for (let attempt = 0; attempt < 2; attempt++) {
110
+ try {
111
+ writeFileSync(join(saidDir(), `${start}-${t}`), "", { flag: "wx", mode: 0o600 });
112
+ return true;
113
+ }
114
+ catch (e) {
115
+ if (e.code !== "ENOENT" || attempt)
116
+ return e.code !== "EEXIST";
117
+ try {
118
+ mkdirSync(saidDir(), { recursive: true });
119
+ }
120
+ catch {
121
+ return true;
122
+ }
123
+ }
124
+ }
125
+ return true;
126
+ };
127
+ const mine = create(level);
128
+ for (const t of THRESHOLDS)
129
+ if (t < level)
130
+ create(t);
131
+ return mine;
132
+ }
133
+ /** A new period, budget or none: the markers of other periods (or all) go. */
134
+ function clearSaid(keep) {
135
+ try {
136
+ for (const f of readdirSync(saidDir()))
137
+ if (keep === undefined || !f.startsWith(`${keep}-`))
138
+ rmSync(join(saidDir(), f), { force: true });
139
+ }
140
+ catch { /* none */ }
94
141
  }
95
142
  /** Remove the budget and its ledger. True when there was one. */
96
143
  export function clearBudget() {
@@ -107,6 +154,7 @@ export function clearBudget() {
107
154
  catch { /* no folder */ }
108
155
  rmSync(budgetPath(), { force: true });
109
156
  rmSync(budgetStatePath(), { force: true });
157
+ rmSync(saidDir(), { recursive: true, force: true });
110
158
  if (ours)
111
159
  try {
112
160
  rmdirSync(dir);
@@ -156,8 +204,15 @@ function saveState(st) {
156
204
  }
157
205
  catch { /* a read-only folder: worked out again next time */ }
158
206
  }
159
- /** Claude Code's main transcripts written since `since`, without listing Codex's or Gemini's too. */
160
- function claudeTops(since) {
207
+ /**
208
+ * Claude Code's transcripts written since `since`, without listing Codex's or
209
+ * Gemini's too: each main transcript written since then, and the subagents
210
+ * (workflow agents included) written since then of every session written in
211
+ * the SUBAGENT_LOOKBACK_MS before it. A subagent still running after
212
+ * midnight, its session quiet meanwhile, was not counted until the session
213
+ * itself was written again.
214
+ */
215
+ function claudePeriodFiles(since) {
161
216
  const root = join(claudeDir(), "projects");
162
217
  const out = [];
163
218
  let dirs;
@@ -178,11 +233,20 @@ function claudeTops(since) {
178
233
  for (const n of names) {
179
234
  if (!n.endsWith(".jsonl"))
180
235
  continue;
236
+ const top = join(root, d, n);
237
+ let m;
181
238
  try {
182
- if (statSync(join(root, d, n)).mtimeMs >= since)
183
- out.push(join(root, d, n));
239
+ m = statSync(top).mtimeMs;
184
240
  }
185
- catch { /* vanished */ }
241
+ catch {
242
+ continue; /* vanished */
243
+ }
244
+ if (m < since - SUBAGENT_LOOKBACK_MS)
245
+ continue;
246
+ if (m >= since)
247
+ out.push(top);
248
+ for (const f of subagentFiles(top, since))
249
+ out.push(f.file);
186
250
  }
187
251
  }
188
252
  return out;
@@ -239,22 +303,26 @@ function lineStart(fd, size) {
239
303
  * shared scan, so only what it has not cached), as the ledger keeps them.
240
304
  */
241
305
  function readFile(tool, file, since, size) {
242
- const k = [], d = [], x = [];
306
+ const k = [], d = [], x = [], y = [];
243
307
  if (tool !== "claude") {
244
308
  // A Codex request's key (a forked rollout repeats its parent's) kept short: 12 hex digits of its hash.
245
309
  for (const r of tool === "codex" ? codexFileSpend(file, since) : geminiFileSpend(file, since)) {
246
310
  if (!r.priced)
247
311
  x.push([k.length, r.model ?? "unknown"]);
312
+ else if (r.estimated)
313
+ y.push([k.length, r.model ?? "unknown"]);
248
314
  k.push(r.key ? createHash("sha1").update(r.key).digest("hex").slice(0, 12) : "");
249
315
  d.push(r.usd);
250
316
  }
251
- return { k, d, ...(x.length ? { x } : {}) };
317
+ return { k, d, ...(x.length ? { x } : {}), ...(y.length ? { y } : {}) };
252
318
  }
253
319
  const reqs = claudeFileUsage(file, since);
254
320
  const at = new Map();
255
321
  reqs.forEach((q, i) => {
256
322
  if (!pricingFor(q.model))
257
323
  x.push([i, q.model ?? "unknown"]);
324
+ else if (!hasKnownPrice(q.model))
325
+ y.push([i, q.model ?? "unknown"]);
258
326
  k.push(keyOf(q.uuid));
259
327
  d.push(q.usd);
260
328
  if (q.id)
@@ -284,7 +352,7 @@ function readFile(tool, file, since, size) {
284
352
  const fd = openSync(file, "r");
285
353
  try {
286
354
  const o = lineStart(fd, size);
287
- return { k, d, o, a: anchorOf(fd, o), r: r.slice(-RECENT_REPLIES), ...(x.length ? { x } : {}) };
355
+ return { k, d, o, a: anchorOf(fd, o), r: r.slice(-RECENT_REPLIES), ...(x.length ? { x } : {}), ...(y.length ? { y } : {}) };
288
356
  }
289
357
  finally {
290
358
  closeSync(fd);
@@ -294,22 +362,59 @@ function readFile(tool, file, since, size) {
294
362
  * A Claude Code transcript that grew: the whole lines after `e.o`, each
295
363
  * reply counted as claudeFileUsage counts it (once, its output settled on
296
364
  * its later rows, priced with usageCost), into `e`. False, `e` untouched,
297
- * when what came before `e.o` is not what was read (rewritten in place).
365
+ * when what came before `e.o` is not what was read (rewritten in place), or
366
+ * when the entry no longer keeps its last replies (`r`, dropped for a
367
+ * finished subagent): then a later row of a reply would not be known as one.
368
+ * Read in blocks, so a long transcript never needs one buffer of all of it.
369
+ * `own`: count only the rows of this session, by their `sessionId`: a
370
+ * session resumed or forked into a new one starts with a copy of the old
371
+ * one's rows, which keep its id (seen on the author's machine), and were
372
+ * counted as the new session's spend.
298
373
  */
299
- function readAppended(e, file, since) {
374
+ function readAppended(e, file, since, own) {
300
375
  const fd = openSync(file, "r");
301
376
  try {
302
377
  const size = fstatSync(fd).size;
303
378
  const from = e.o ?? 0;
304
- if (e.a === undefined || size < from || anchorOf(fd, from) !== e.a)
379
+ if (e.a === undefined || e.r === undefined || size < from || anchorOf(fd, from) !== e.a)
305
380
  return false;
306
- const buf = Buffer.alloc(size - from);
307
- const n = readSync(fd, buf, 0, buf.length, from);
308
- const end = buf.subarray(0, n).lastIndexOf(10);
309
- if (end < 0)
310
- return true;
311
- const recent = e.r ?? [];
312
- for (const line of buf.subarray(0, end).toString("utf8").split("\n")) {
381
+ const recent = e.r;
382
+ let pos = from;
383
+ let carry = Buffer.alloc(0);
384
+ while (pos < size) {
385
+ const block = Buffer.alloc(Math.min(READ_BLOCK, size - pos));
386
+ const n = readSync(fd, block, 0, block.length, pos);
387
+ if (n <= 0)
388
+ break;
389
+ pos += n;
390
+ const buf = carry.length ? Buffer.concat([carry, block.subarray(0, n)]) : block.subarray(0, n);
391
+ const end = buf.lastIndexOf(10);
392
+ if (end < 0) {
393
+ carry = buf;
394
+ continue;
395
+ }
396
+ carry = buf.subarray(end + 1);
397
+ countLines(e, recent, buf.subarray(0, end).toString("utf8"), since, own);
398
+ }
399
+ e.r = recent.slice(-RECENT_REPLIES);
400
+ // After the last whole line: a half-written one is read next time.
401
+ e.o = pos - carry.length;
402
+ e.a = anchorOf(fd, e.o);
403
+ return true;
404
+ }
405
+ finally {
406
+ closeSync(fd);
407
+ }
408
+ }
409
+ /** Lines read at a time by readAppended. */
410
+ const READ_BLOCK = 8 * 1024 * 1024;
411
+ /** Whole lines of a Claude Code transcript counted into `e` (readAppended). */
412
+ function countLines(e, recent, text, since, own) {
413
+ {
414
+ for (const line of text.split("\n")) {
415
+ // Only the last replies matter (a reply's rows are written together): a whole transcript read at once stays linear.
416
+ if (recent.length > 2 * RECENT_REPLIES)
417
+ recent.splice(0, recent.length - RECENT_REPLIES);
313
418
  if (!line.includes('"usage"'))
314
419
  continue;
315
420
  let row;
@@ -338,30 +443,79 @@ function readAppended(e, file, since) {
338
443
  const tokens = [u.input_tokens, u.cache_read_input_tokens, u.cache_creation_input_tokens].reduce((t, v) => t + (Number(v) > 0 ? Number(v) : 0), 0);
339
444
  const price = pricingFor(realModel(m.model));
340
445
  let index = -1;
341
- if (Number.isFinite(ts) && ts >= since && tokens > 0) {
446
+ // A reply on <synthetic> was made by Claude Code itself, never billed: not a request at all.
447
+ // A row of another session (`own`): a copy of its history, its spend, not this session's.
448
+ const copied = own !== undefined && typeof row.sessionId === "string" && row.sessionId !== own;
449
+ if (Number.isFinite(ts) && ts >= since && tokens > 0 && !isUnbilledModel(m.model) && !copied) {
342
450
  index = e.k.length;
343
451
  if (!price)
344
452
  (e.x ??= []).push([index, realModel(m.model) ?? "unknown"]);
453
+ else if (!hasKnownPrice(realModel(m.model)))
454
+ (e.y ??= []).push([index, realModel(m.model) ?? "unknown"]);
345
455
  e.k.push(keyOf(typeof row.uuid === "string" ? row.uuid : undefined));
346
456
  e.d.push(price ? usageCost(u, price).totalUsd : 0);
347
457
  }
348
458
  if (typeof m.id === "string")
349
459
  recent.push([m.id, index, out, price?.outputPerM ?? 0]);
350
460
  }
351
- e.r = recent.slice(-RECENT_REPLIES);
352
- e.o = from + end + 1;
353
- e.a = anchorOf(fd, e.o);
354
- return true;
355
- }
356
- finally {
357
- closeSync(fd);
358
461
  }
359
462
  }
360
463
  /** A ledger entry this version can use: a damaged one threw on every prompt until its transcript changed. */
361
- function wellFormed(e) {
464
+ export function wellFormed(e) {
362
465
  return Boolean(e) && typeof e === "object" && Array.isArray(e.k) && Array.isArray(e.d) && e.k.length === e.d.length &&
363
466
  e.k.every((x) => typeof x === "string") && e.d.every((x) => typeof x === "number" && Number.isFinite(x)) &&
364
- (e.a === undefined || typeof e.a === "string") && (e.x === undefined || (Array.isArray(e.x) && e.x.every((y) => Array.isArray(y) && typeof y[0] === "number"))) && (e.r === undefined || (Array.isArray(e.r) && e.r.every((x) => Array.isArray(x) && x.length === 4)));
467
+ (e.a === undefined || typeof e.a === "string") && (e.x === undefined || (Array.isArray(e.x) && e.x.every((y) => Array.isArray(y) && typeof y[0] === "number"))) && (e.y === undefined || (Array.isArray(e.y) && e.y.every((y) => Array.isArray(y) && typeof y[0] === "number"))) && (e.r === undefined || (Array.isArray(e.r) && e.r.every((x) => Array.isArray(x) && x.length === 4)));
468
+ }
469
+ /**
470
+ * One transcript's entry brought up to date: kept when the file is as last
471
+ * read, read from where the last read stopped when a Claude Code transcript
472
+ * only grew, read in full otherwise. `read`: the bytes read, -1 when the
473
+ * entry was kept as it was. Undefined when the file cannot be read now.
474
+ * `direct`: a Claude Code transcript met for the first time is read here,
475
+ * not through the shared scan, which keeps a cache entry of it on disk (the
476
+ * session price reads one session, and writes nothing while it has nothing
477
+ * to say). `own`: a Claude Code transcript's rows of other sessions are not
478
+ * counted (readAppended); only with `direct`, which reads every Claude Code
479
+ * transcript itself.
480
+ */
481
+ export function refreshEntry(tool, file, prev, since, direct = false, own) {
482
+ let s;
483
+ try {
484
+ s = statSync(file);
485
+ }
486
+ catch {
487
+ return undefined;
488
+ }
489
+ // An entry not in the shape this version writes (edited, or another version's) is read again.
490
+ const e = wellFormed(prev) ? prev : undefined;
491
+ if (e && e.t === tool && e.s === s.size && e.m === s.mtimeMs && e.i === s.ino)
492
+ return { e, read: -1 };
493
+ try {
494
+ // Claude Code appends: a transcript that only grew is read from where the last read stopped.
495
+ if (e && tool === "claude" && e.o !== undefined && e.i === s.ino && s.size >= e.s) {
496
+ const from = e.o;
497
+ if (readAppended(e, file, since, direct ? own : undefined))
498
+ return { e: { ...e, s: s.size, m: s.mtimeMs }, read: s.size - from };
499
+ }
500
+ if (direct && tool === "claude") {
501
+ // From the start, as an append to nothing: the same counting, without the scan.
502
+ const fd = openSync(file, "r");
503
+ let a;
504
+ try {
505
+ a = anchorOf(fd, 0);
506
+ }
507
+ finally {
508
+ closeSync(fd);
509
+ }
510
+ const blank = { t: tool, s: 0, m: 0, i: s.ino, k: [], d: [], o: 0, a, r: [] };
511
+ if (readAppended(blank, file, since, own))
512
+ return { e: { ...blank, s: s.size, m: s.mtimeMs }, read: s.size };
513
+ }
514
+ return { e: { t: tool, s: s.size, m: s.mtimeMs, i: s.ino, ...readFile(tool, file, since, s.size) }, read: s.size };
515
+ }
516
+ catch {
517
+ return undefined;
518
+ }
365
519
  }
366
520
  /**
367
521
  * What the period holding `now` has cost so far, across Claude Code, Codex
@@ -376,38 +530,19 @@ export function periodSpend(period, now = Date.now(), home = homedir(), warnAt)
376
530
  const st = fresh ? { start, files: {}, warned: 0, usd: 0, byTool: {} } : prev;
377
531
  const walked = st.cx?.at;
378
532
  const files = [
379
- ...claudeUsageFiles(start, claudeTops(start)).map((f) => ["claude", f.file]),
533
+ ...claudePeriodFiles(start).map((f) => ["claude", f]),
380
534
  ...codexPeriodFiles(st, start, now, home).map((f) => ["codex", f]),
381
535
  ...geminiFiles(start, home).map((f) => ["gemini", f]),
382
536
  ];
383
537
  let changed = fresh || st.cx?.at !== walked;
384
538
  const kept = {};
385
539
  for (const [tool, file] of files) {
386
- let s;
387
- try {
388
- s = statSync(file);
389
- }
390
- catch {
391
- continue;
392
- }
393
- // An entry not in the shape this version writes (edited, or another version's) is read again.
394
- const e = wellFormed(st.files[file]) ? st.files[file] : undefined;
395
- if (e && e.t === tool && e.s === s.size && e.m === s.mtimeMs && e.i === s.ino) {
396
- kept[file] = e;
397
- continue;
398
- }
399
- try {
400
- // Claude Code appends: a transcript that only grew is read from where the last read stopped.
401
- if (e && tool === "claude" && e.o !== undefined && e.i === s.ino && s.size >= e.s && readAppended(e, file, start)) {
402
- kept[file] = { ...e, s: s.size, m: s.mtimeMs };
403
- }
404
- else
405
- kept[file] = { t: tool, s: s.size, m: s.mtimeMs, i: s.ino, ...readFile(tool, file, start, s.size) };
406
- }
407
- catch {
540
+ const r = refreshEntry(tool, file, st.files[file], start);
541
+ if (!r)
408
542
  continue; // unreadable now: left out, read again next time
409
- }
410
- changed = true;
543
+ kept[file] = r.e;
544
+ if (r.read >= 0)
545
+ changed = true;
411
546
  }
412
547
  if (Object.keys(st.files).some((f) => !(f in kept)))
413
548
  changed = true;
@@ -417,9 +552,10 @@ export function periodSpend(period, now = Date.now(), home = homedir(), warnAt)
417
552
  const byTool = {};
418
553
  let unpriced = 0;
419
554
  const models = new Set();
555
+ const estimated = { requests: 0, usd: 0, models: new Set() };
420
556
  for (const file of Object.keys(kept).sort()) {
421
557
  const e = kept[file];
422
- const x = new Map(e.x ?? []);
558
+ const x = new Map(e.x ?? []), y = new Map(e.y ?? []);
423
559
  e.k.forEach((key, i) => {
424
560
  if (key) {
425
561
  if (seen.has(key))
@@ -432,14 +568,24 @@ export function periodSpend(period, now = Date.now(), home = homedir(), warnAt)
432
568
  unpriced++;
433
569
  models.add(x.get(i));
434
570
  }
571
+ else if (y.has(i)) {
572
+ estimated.requests++;
573
+ estimated.usd += e.d[i];
574
+ estimated.models.add(y.get(i));
575
+ }
435
576
  });
436
577
  }
437
578
  const level = warnAt ? warnAt(usd, st.warned) : 0;
438
- const warn = level > st.warned ? level : undefined;
579
+ let warn = level > st.warned ? level : undefined;
439
580
  if (warn) {
440
581
  st.warned = warn;
441
582
  changed = true;
583
+ // Said by exactly one of several prompts at once: the one that creates the threshold's marker.
584
+ if (!claimSaid(start, warn))
585
+ warn = undefined;
442
586
  }
587
+ if (fresh)
588
+ clearSaid(start);
443
589
  // The hook (warnAt) says once a period that part of it has no price.
444
590
  const unpricedNew = Boolean(warnAt) && unpriced > 0 && !st.unpricedSaid;
445
591
  if (unpricedNew) {
@@ -448,7 +594,7 @@ export function periodSpend(period, now = Date.now(), home = homedir(), warnAt)
448
594
  }
449
595
  if (changed)
450
596
  saveState({ ...st, files: kept, usd, byTool });
451
- return { start, end: periodEnd(period, now), usd, byTool, ...(unpriced ? { unpriced: { requests: unpriced, models: [...models] } } : {}), ...(warn ? { warn } : {}), ...(unpricedNew ? { unpricedNew } : {}) };
597
+ return { start, end: periodEnd(period, now), usd, byTool, ...(unpriced ? { unpriced: { requests: unpriced, models: [...models] } } : {}), ...(estimated.requests ? { estimated: { requests: estimated.requests, usd: estimated.usd, models: [...estimated.models] } } : {}), ...(warn ? { warn } : {}), ...(unpricedNew ? { unpricedNew } : {}) };
452
598
  }
453
599
  // ---------------------------------------------------------------------------
454
600
  // What the hook, the status line and `budget` say
@@ -528,6 +674,10 @@ export function renderBudgetStatus(b, s, hookInstalled) {
528
674
  ];
529
675
  if (s.unpriced)
530
676
  lines.push(`Not counted: ${unpricedText(s.unpriced)}`);
677
+ if (s.estimated) {
678
+ const one = s.estimated.models.length === 1;
679
+ lines.push(`An estimate: ${money(s.estimated.usd)} of it is on ${s.estimated.models.slice(0, 2).join(", ")}${s.estimated.models.length > 2 ? " and others" : ""}, with no list price of ${one ? "its" : "their"} own, priced as ${one ? "its" : "their"} model's family.`);
680
+ }
531
681
  lines.push(hookInstalled
532
682
  ? `The every-prompt hook says so at ${THRESHOLDS.join("%, ").replace(/, (\d+)$/, " and $1")}%${b.block ? ", and holds prompts over it" : ""}. Cursor is not counted (context-doctor spend shows it).`
533
683
  : "No every-prompt hook is installed, so nothing will say so: run context-doctor install.");
@@ -71,7 +71,11 @@ interface Acc extends TtlReplay {
71
71
  * rows; a main transcript skips them. Returns the requests counted.
72
72
  */
73
73
  export declare function replayTtlTranscript(path: string, acc: Acc, since: number, until?: number, sidechains?: boolean, runRows?: Set<string>, otherIds?: Set<string>): number;
74
- /** Subagent transcripts of the main transcripts under ~/.claude/projects written since `since`. */
74
+ /**
75
+ * Subagent transcripts of the sessions under ~/.claude/projects written
76
+ * since `since`: the Agent tool's and the workflow agents'
77
+ * (subagents/workflows/<run>/, subagentFiles).
78
+ */
75
79
  export declare function subagentTranscripts(since: number, home?: string): string[];
76
80
  export interface TtlOptions {
77
81
  /** Main transcripts (default: Claude Code transcripts written in the period). */
package/dist/cachettl.js CHANGED
@@ -32,7 +32,7 @@
32
32
  * start a new cache in every arm. The main conversation and subagents are
33
33
  * replayed apart, since each has its own setting.
34
34
  */
35
- import { existsSync, readdirSync, statSync } from "node:fs";
35
+ import { existsSync, readdirSync } from "node:fs";
36
36
  import { homedir } from "node:os";
37
37
  import { join } from "node:path";
38
38
  import { listSessions, replyCounter, isClaudeSession } from "./session.js";
@@ -45,6 +45,7 @@ import { ABSENT, readSettings, setJsonPath, withSettingsLock, writeAtomic } from
45
45
  import { effectiveTtl, settingsSources, ttlOverrides } from "./effective.js";
46
46
  import { compareVersions, describeInstalls } from "./modelswitch.js";
47
47
  import { claudeDir } from "./claudedir.js";
48
+ import { subagentFiles } from "./subagents.js";
48
49
  /** The first Claude Code with the promptCacheTtl and subagentPromptCacheTtl settings (CHANGELOG). */
49
50
  export const CACHE_TTL_SINCE = "2.1.243";
50
51
  const FIVE_MIN = 300_000;
@@ -159,7 +160,11 @@ function finish(acc) {
159
160
  const { writes, writes1h, ...r } = acc;
160
161
  return { ...r, oneHourShare: writes > 0 ? writes1h / writes : 0 };
161
162
  }
162
- /** Subagent transcripts of the main transcripts under ~/.claude/projects written since `since`. */
163
+ /**
164
+ * Subagent transcripts of the sessions under ~/.claude/projects written
165
+ * since `since`: the Agent tool's and the workflow agents'
166
+ * (subagents/workflows/<run>/, subagentFiles).
167
+ */
163
168
  export function subagentTranscripts(since, home = homedir()) {
164
169
  const root = join(claudeDir(home), "projects");
165
170
  const out = [];
@@ -179,30 +184,10 @@ export function subagentTranscripts(since, home = homedir()) {
179
184
  continue;
180
185
  }
181
186
  for (const entry of entries) {
182
- if (entry.endsWith(".jsonl"))
183
- continue;
184
- const dir = join(root, project, entry, "subagents");
185
- if (!existsSync(dir))
186
- continue;
187
- let files;
188
- try {
189
- files = readdirSync(dir);
190
- }
191
- catch {
187
+ if (entry.endsWith(".jsonl") || !existsSync(join(root, project, entry, "subagents")))
192
188
  continue;
193
- }
194
- for (const f of files) {
195
- if (!f.endsWith(".jsonl"))
196
- continue;
197
- const p = join(dir, f);
198
- try {
199
- if (statSync(p).mtimeMs >= since)
200
- out.push(p);
201
- }
202
- catch {
203
- /* gone */
204
- }
205
- }
189
+ for (const f of subagentFiles(join(root, project, `${entry}.jsonl`), since))
190
+ out.push(f.file);
206
191
  }
207
192
  }
208
193
  return out;