context-doctor 0.43.0 → 0.45.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 (61) hide show
  1. package/README.md +4 -2
  2. package/dist/budget.d.ts +23 -3
  3. package/dist/budget.js +184 -50
  4. package/dist/cache.js +5 -4
  5. package/dist/cachemisses.js +1 -1
  6. package/dist/cachettl.d.ts +5 -1
  7. package/dist/cachettl.js +16 -29
  8. package/dist/ci.js +18 -2
  9. package/dist/cli.js +16 -12
  10. package/dist/codexcompact.d.ts +24 -3
  11. package/dist/codexcompact.js +221 -48
  12. package/dist/coldresume.js +16 -8
  13. package/dist/compactwindow.js +14 -9
  14. package/dist/cursor.d.ts +10 -0
  15. package/dist/cursor.js +20 -0
  16. package/dist/doctor.d.ts +9 -0
  17. package/dist/doctor.js +52 -0
  18. package/dist/extract.d.ts +2 -2
  19. package/dist/extract.js +14 -3
  20. package/dist/fanout.js +4 -2
  21. package/dist/fix.d.ts +8 -1
  22. package/dist/fix.js +59 -13
  23. package/dist/hook.js +45 -15
  24. package/dist/httpguard.d.ts +9 -1
  25. package/dist/httpguard.js +5 -4
  26. package/dist/install.js +56 -19
  27. package/dist/lens.js +7 -7
  28. package/dist/limits.d.ts +17 -4
  29. package/dist/limits.js +41 -29
  30. package/dist/mcp.js +63 -63
  31. package/dist/mcpclient.js +19 -19
  32. package/dist/mcpschema.js +10 -12
  33. package/dist/overhead.d.ts +7 -2
  34. package/dist/overhead.js +11 -3
  35. package/dist/pack.js +87 -23
  36. package/dist/pricing.d.ts +125 -6
  37. package/dist/pricing.js +304 -59
  38. package/dist/proxy.d.ts +26 -1
  39. package/dist/proxy.js +45 -5
  40. package/dist/prune.d.ts +8 -0
  41. package/dist/prune.js +73 -10
  42. package/dist/savings.js +17 -9
  43. package/dist/scan.d.ts +7 -1
  44. package/dist/scan.js +19 -1
  45. package/dist/sessionprice.d.ts +9 -2
  46. package/dist/sessionprice.js +95 -36
  47. package/dist/settingsedit.js +3 -2
  48. package/dist/spend.d.ts +75 -10
  49. package/dist/spend.js +279 -37
  50. package/dist/statusline.d.ts +10 -2
  51. package/dist/statusline.js +17 -8
  52. package/dist/subagentmodel.d.ts +2 -2
  53. package/dist/subagentmodel.js +42 -25
  54. package/dist/subagentpay.d.ts +17 -0
  55. package/dist/subagentpay.js +41 -2
  56. package/dist/subagents.d.ts +24 -0
  57. package/dist/subagents.js +93 -27
  58. package/dist/tasks.js +9 -6
  59. package/dist/tooloutput.d.ts +2 -0
  60. package/dist/tooloutput.js +16 -5
  61. 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.43.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.45.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.
@@ -181,6 +181,8 @@ Rules 1-4 end exactly at character 512, the part ChatGPT's guide says must stand
181
181
 
182
182
  ## What's new
183
183
 
184
+ - **0.45 Price what is billed, and a security pass**: fast mode, US-only inference, Haiku 5.5's long-prompt rates, web searches and OpenAI's and Gemini's long-prompt tiers are priced per request in every report, and prices that end on a known day say so. A security pass fixed a cloned repository approving its own MCP servers for `overhead --mcp`, a PDF's name running as a command through `pack` on macOS, the agents' API-key configs being packed, and the proxy answering a DNS-rebinding page ([details](./ROADMAP.md#shipped-in-0450-price-what-is-billed-and-a-security-pass-on-044)).
185
+ - **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)).
184
186
  - **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).
185
187
  - **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)).
186
188
  - **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.
package/dist/budget.d.ts CHANGED
@@ -68,7 +68,11 @@ export declare function periodEnd(period: Period, now?: number): number;
68
68
  * bytes before `o` (the shared scan's anchorOf): a transcript rewritten in
69
69
  * place, same inode and no smaller, is read again in full, not from `o`.
70
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.
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
73
+ * way; `z` those priced past the day their model's price changed (index,
74
+ * model, the day). `d` is requestCost's: each request's tier, fast mode,
75
+ * US-only and web searches, and the output price in `r` is its own.
72
76
  */
73
77
  export interface FileEntry {
74
78
  t: Tool;
@@ -81,6 +85,8 @@ export interface FileEntry {
81
85
  a?: string;
82
86
  r?: Array<[string, number, number, number]>;
83
87
  x?: Array<[number, string]>;
88
+ y?: Array<[number, string]>;
89
+ z?: Array<[number, string, string]>;
84
90
  }
85
91
  /** A ledger entry this version can use: a damaged one threw on every prompt until its transcript changed. */
86
92
  export declare function wellFormed(e: FileEntry | undefined): e is FileEntry;
@@ -92,9 +98,11 @@ export declare function wellFormed(e: FileEntry | undefined): e is FileEntry;
92
98
  * `direct`: a Claude Code transcript met for the first time is read here,
93
99
  * not through the shared scan, which keeps a cache entry of it on disk (the
94
100
  * session price reads one session, and writes nothing while it has nothing
95
- * to say).
101
+ * to say). `own`: a Claude Code transcript's rows of other sessions are not
102
+ * counted (readAppended); only with `direct`, which reads every Claude Code
103
+ * transcript itself.
96
104
  */
97
- export declare function refreshEntry(tool: Tool, file: string, prev: FileEntry | undefined, since: number, direct?: boolean): {
105
+ export declare function refreshEntry(tool: Tool, file: string, prev: FileEntry | undefined, since: number, direct?: boolean, own?: string): {
98
106
  e: FileEntry;
99
107
  read: number;
100
108
  } | undefined;
@@ -108,6 +116,18 @@ export interface PeriodSpend {
108
116
  requests: number;
109
117
  models: string[];
110
118
  };
119
+ /** Requests on a model priced only by its family: in `usd`, an estimate. */
120
+ estimated?: {
121
+ requests: number;
122
+ usd: number;
123
+ models: string[];
124
+ };
125
+ /** Requests priced past the day their model's price changed (model, day): in `usd`, an estimate. */
126
+ changed?: {
127
+ requests: number;
128
+ usd: number;
129
+ models: Array<[string, string]>;
130
+ };
111
131
  }
112
132
  /**
113
133
  * 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 { isUnbilledModel, priceChangedText, requestCost } 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. */
@@ -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,29 @@ 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 = [], z = [];
307
+ const flag = (i, q) => {
308
+ if (!q.priced)
309
+ x.push([i, q.model ?? "unknown"]);
310
+ else if (q.changedOn)
311
+ z.push([i, q.model ?? "unknown", q.changedOn]);
312
+ else if (q.estimated)
313
+ y.push([i, q.model ?? "unknown"]);
314
+ };
315
+ const flags = () => ({ ...(x.length ? { x } : {}), ...(y.length ? { y } : {}), ...(z.length ? { z } : {}) });
243
316
  if (tool !== "claude") {
244
317
  // A Codex request's key (a forked rollout repeats its parent's) kept short: 12 hex digits of its hash.
245
318
  for (const r of tool === "codex" ? codexFileSpend(file, since) : geminiFileSpend(file, since)) {
246
- if (!r.priced)
247
- x.push([k.length, r.model ?? "unknown"]);
319
+ flag(k.length, r);
248
320
  k.push(r.key ? createHash("sha1").update(r.key).digest("hex").slice(0, 12) : "");
249
321
  d.push(r.usd);
250
322
  }
251
- return { k, d, ...(x.length ? { x } : {}) };
323
+ return { k, d, ...flags() };
252
324
  }
253
325
  const reqs = claudeFileUsage(file, since);
254
326
  const at = new Map();
255
327
  reqs.forEach((q, i) => {
256
- if (!pricingFor(q.model))
257
- x.push([i, q.model ?? "unknown"]);
328
+ flag(i, { ...q, priced: q.rates !== undefined });
258
329
  k.push(keyOf(q.uuid));
259
330
  d.push(q.usd);
260
331
  if (q.id)
@@ -276,7 +347,7 @@ function readFile(tool, file, since, size) {
276
347
  continue;
277
348
  }
278
349
  const i = at.get(m.id) ?? -1;
279
- last.set(m.id, [m.id, i, out, pricingFor(i >= 0 ? reqs[i].model : realModel(m.model))?.outputPerM ?? 0]);
350
+ last.set(m.id, [m.id, i, out, (i >= 0 ? reqs[i].rates : requestCost(realModel(m.model), m.usage, Date.parse(String(row.timestamp ?? "")))?.rates)?.outputPerM ?? 0]);
280
351
  if (last.size > RECENT_REPLIES)
281
352
  last.delete(last.keys().next().value);
282
353
  }
@@ -284,7 +355,7 @@ function readFile(tool, file, since, size) {
284
355
  const fd = openSync(file, "r");
285
356
  try {
286
357
  const o = lineStart(fd, size);
287
- return { k, d, o, a: anchorOf(fd, o), r: r.slice(-RECENT_REPLIES), ...(x.length ? { x } : {}) };
358
+ return { k, d, o, a: anchorOf(fd, o), r: r.slice(-RECENT_REPLIES), ...flags() };
288
359
  }
289
360
  finally {
290
361
  closeSync(fd);
@@ -294,22 +365,59 @@ function readFile(tool, file, since, size) {
294
365
  * A Claude Code transcript that grew: the whole lines after `e.o`, each
295
366
  * reply counted as claudeFileUsage counts it (once, its output settled on
296
367
  * 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).
368
+ * when what came before `e.o` is not what was read (rewritten in place), or
369
+ * when the entry no longer keeps its last replies (`r`, dropped for a
370
+ * finished subagent): then a later row of a reply would not be known as one.
371
+ * Read in blocks, so a long transcript never needs one buffer of all of it.
372
+ * `own`: count only the rows of this session, by their `sessionId`: a
373
+ * session resumed or forked into a new one starts with a copy of the old
374
+ * one's rows, which keep its id (seen on the author's machine), and were
375
+ * counted as the new session's spend.
298
376
  */
299
- function readAppended(e, file, since) {
377
+ function readAppended(e, file, since, own) {
300
378
  const fd = openSync(file, "r");
301
379
  try {
302
380
  const size = fstatSync(fd).size;
303
381
  const from = e.o ?? 0;
304
- if (e.a === undefined || size < from || anchorOf(fd, from) !== e.a)
382
+ if (e.a === undefined || e.r === undefined || size < from || anchorOf(fd, from) !== e.a)
305
383
  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")) {
384
+ const recent = e.r;
385
+ let pos = from;
386
+ let carry = Buffer.alloc(0);
387
+ while (pos < size) {
388
+ const block = Buffer.alloc(Math.min(READ_BLOCK, size - pos));
389
+ const n = readSync(fd, block, 0, block.length, pos);
390
+ if (n <= 0)
391
+ break;
392
+ pos += n;
393
+ const buf = carry.length ? Buffer.concat([carry, block.subarray(0, n)]) : block.subarray(0, n);
394
+ const end = buf.lastIndexOf(10);
395
+ if (end < 0) {
396
+ carry = buf;
397
+ continue;
398
+ }
399
+ carry = buf.subarray(end + 1);
400
+ countLines(e, recent, buf.subarray(0, end).toString("utf8"), since, own);
401
+ }
402
+ e.r = recent.slice(-RECENT_REPLIES);
403
+ // After the last whole line: a half-written one is read next time.
404
+ e.o = pos - carry.length;
405
+ e.a = anchorOf(fd, e.o);
406
+ return true;
407
+ }
408
+ finally {
409
+ closeSync(fd);
410
+ }
411
+ }
412
+ /** Lines read at a time by readAppended. */
413
+ const READ_BLOCK = 8 * 1024 * 1024;
414
+ /** Whole lines of a Claude Code transcript counted into `e` (readAppended). */
415
+ function countLines(e, recent, text, since, own) {
416
+ {
417
+ for (const line of text.split("\n")) {
418
+ // Only the last replies matter (a reply's rows are written together): a whole transcript read at once stays linear.
419
+ if (recent.length > 2 * RECENT_REPLIES)
420
+ recent.splice(0, recent.length - RECENT_REPLIES);
313
421
  if (!line.includes('"usage"'))
314
422
  continue;
315
423
  let row;
@@ -336,35 +444,35 @@ function readAppended(e, file, since) {
336
444
  }
337
445
  const ts = Date.parse(String(row.timestamp ?? ""));
338
446
  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
- const price = pricingFor(realModel(m.model));
447
+ const model = realModel(m.model);
448
+ const c = requestCost(model, u, ts);
340
449
  let index = -1;
341
- if (Number.isFinite(ts) && ts >= since && tokens > 0) {
450
+ // A reply on <synthetic> was made by Claude Code itself, never billed: not a request at all.
451
+ // A row of another session (`own`): a copy of its history, its spend, not this session's.
452
+ const copied = own !== undefined && typeof row.sessionId === "string" && row.sessionId !== own;
453
+ if (Number.isFinite(ts) && ts >= since && tokens > 0 && !isUnbilledModel(m.model) && !copied) {
342
454
  index = e.k.length;
343
- if (!price)
344
- (e.x ??= []).push([index, realModel(m.model) ?? "unknown"]);
455
+ if (!c)
456
+ (e.x ??= []).push([index, model ?? "unknown"]);
457
+ else if (c.changedOn)
458
+ (e.z ??= []).push([index, model ?? "unknown", c.changedOn]);
459
+ else if (c.estimated)
460
+ (e.y ??= []).push([index, model ?? "unknown"]);
345
461
  e.k.push(keyOf(typeof row.uuid === "string" ? row.uuid : undefined));
346
- e.d.push(price ? usageCost(u, price).totalUsd : 0);
462
+ e.d.push(c ? c.totalUsd : 0);
347
463
  }
348
464
  if (typeof m.id === "string")
349
- recent.push([m.id, index, out, price?.outputPerM ?? 0]);
465
+ recent.push([m.id, index, out, c?.rates.outputPerM ?? 0]);
350
466
  }
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
467
  }
359
468
  }
360
469
  /** A ledger entry this version can use: a damaged one threw on every prompt until its transcript changed. */
361
470
  export function wellFormed(e) {
362
471
  return Boolean(e) && typeof e === "object" && Array.isArray(e.k) && Array.isArray(e.d) && e.k.length === e.d.length &&
363
472
  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)));
473
+ (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))) &&
474
+ (e.z === undefined || (Array.isArray(e.z) && e.z.every((z) => Array.isArray(z) && typeof z[0] === "number" && typeof z[2] === "string")));
365
475
  }
366
- /** Above this, a transcript met for the first time goes through the shared scan even when `direct`: one buffer of all of it is too much. */
367
- const DIRECT_MAX_BYTES = 16 * 1024 * 1024;
368
476
  /**
369
477
  * One transcript's entry brought up to date: kept when the file is as last
370
478
  * read, read from where the last read stopped when a Claude Code transcript
@@ -373,9 +481,11 @@ const DIRECT_MAX_BYTES = 16 * 1024 * 1024;
373
481
  * `direct`: a Claude Code transcript met for the first time is read here,
374
482
  * not through the shared scan, which keeps a cache entry of it on disk (the
375
483
  * session price reads one session, and writes nothing while it has nothing
376
- * to say).
484
+ * to say). `own`: a Claude Code transcript's rows of other sessions are not
485
+ * counted (readAppended); only with `direct`, which reads every Claude Code
486
+ * transcript itself.
377
487
  */
378
- export function refreshEntry(tool, file, prev, since, direct = false) {
488
+ export function refreshEntry(tool, file, prev, since, direct = false, own) {
379
489
  let s;
380
490
  try {
381
491
  s = statSync(file);
@@ -391,10 +501,10 @@ export function refreshEntry(tool, file, prev, since, direct = false) {
391
501
  // Claude Code appends: a transcript that only grew is read from where the last read stopped.
392
502
  if (e && tool === "claude" && e.o !== undefined && e.i === s.ino && s.size >= e.s) {
393
503
  const from = e.o;
394
- if (readAppended(e, file, since))
504
+ if (readAppended(e, file, since, direct ? own : undefined))
395
505
  return { e: { ...e, s: s.size, m: s.mtimeMs }, read: s.size - from };
396
506
  }
397
- if (direct && tool === "claude" && s.size <= DIRECT_MAX_BYTES) {
507
+ if (direct && tool === "claude") {
398
508
  // From the start, as an append to nothing: the same counting, without the scan.
399
509
  const fd = openSync(file, "r");
400
510
  let a;
@@ -405,7 +515,7 @@ export function refreshEntry(tool, file, prev, since, direct = false) {
405
515
  closeSync(fd);
406
516
  }
407
517
  const blank = { t: tool, s: 0, m: 0, i: s.ino, k: [], d: [], o: 0, a, r: [] };
408
- if (readAppended(blank, file, since))
518
+ if (readAppended(blank, file, since, own))
409
519
  return { e: { ...blank, s: s.size, m: s.mtimeMs }, read: s.size };
410
520
  }
411
521
  return { e: { t: tool, s: s.size, m: s.mtimeMs, i: s.ino, ...readFile(tool, file, since, s.size) }, read: s.size };
@@ -427,7 +537,7 @@ export function periodSpend(period, now = Date.now(), home = homedir(), warnAt)
427
537
  const st = fresh ? { start, files: {}, warned: 0, usd: 0, byTool: {} } : prev;
428
538
  const walked = st.cx?.at;
429
539
  const files = [
430
- ...claudeUsageFiles(start, claudeTops(start)).map((f) => ["claude", f.file]),
540
+ ...claudePeriodFiles(start).map((f) => ["claude", f]),
431
541
  ...codexPeriodFiles(st, start, now, home).map((f) => ["codex", f]),
432
542
  ...geminiFiles(start, home).map((f) => ["gemini", f]),
433
543
  ];
@@ -449,9 +559,11 @@ export function periodSpend(period, now = Date.now(), home = homedir(), warnAt)
449
559
  const byTool = {};
450
560
  let unpriced = 0;
451
561
  const models = new Set();
562
+ const estimated = { requests: 0, usd: 0, models: new Set() };
563
+ const changedPrice = { requests: 0, usd: 0, models: new Map() };
452
564
  for (const file of Object.keys(kept).sort()) {
453
565
  const e = kept[file];
454
- const x = new Map(e.x ?? []);
566
+ const x = new Map(e.x ?? []), y = new Map(e.y ?? []), z = new Map((e.z ?? []).map(([i, m, on]) => [i, [m, on]]));
455
567
  e.k.forEach((key, i) => {
456
568
  if (key) {
457
569
  if (seen.has(key))
@@ -464,14 +576,30 @@ export function periodSpend(period, now = Date.now(), home = homedir(), warnAt)
464
576
  unpriced++;
465
577
  models.add(x.get(i));
466
578
  }
579
+ else if (y.has(i)) {
580
+ estimated.requests++;
581
+ estimated.usd += e.d[i];
582
+ estimated.models.add(y.get(i));
583
+ }
584
+ else if (z.has(i)) {
585
+ const [m, on] = z.get(i);
586
+ changedPrice.requests++;
587
+ changedPrice.usd += e.d[i];
588
+ changedPrice.models.set(`${m}\u0000${on}`, [m, on]);
589
+ }
467
590
  });
468
591
  }
469
592
  const level = warnAt ? warnAt(usd, st.warned) : 0;
470
- const warn = level > st.warned ? level : undefined;
593
+ let warn = level > st.warned ? level : undefined;
471
594
  if (warn) {
472
595
  st.warned = warn;
473
596
  changed = true;
597
+ // Said by exactly one of several prompts at once: the one that creates the threshold's marker.
598
+ if (!claimSaid(start, warn))
599
+ warn = undefined;
474
600
  }
601
+ if (fresh)
602
+ clearSaid(start);
475
603
  // The hook (warnAt) says once a period that part of it has no price.
476
604
  const unpricedNew = Boolean(warnAt) && unpriced > 0 && !st.unpricedSaid;
477
605
  if (unpricedNew) {
@@ -480,7 +608,7 @@ export function periodSpend(period, now = Date.now(), home = homedir(), warnAt)
480
608
  }
481
609
  if (changed)
482
610
  saveState({ ...st, files: kept, usd, byTool });
483
- return { start, end: periodEnd(period, now), usd, byTool, ...(unpriced ? { unpriced: { requests: unpriced, models: [...models] } } : {}), ...(warn ? { warn } : {}), ...(unpricedNew ? { unpricedNew } : {}) };
611
+ 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] } } : {}), ...(changedPrice.requests ? { changed: { requests: changedPrice.requests, usd: changedPrice.usd, models: [...changedPrice.models.values()] } } : {}), ...(warn ? { warn } : {}), ...(unpricedNew ? { unpricedNew } : {}) };
484
612
  }
485
613
  // ---------------------------------------------------------------------------
486
614
  // What the hook, the status line and `budget` say
@@ -560,6 +688,12 @@ export function renderBudgetStatus(b, s, hookInstalled) {
560
688
  ];
561
689
  if (s.unpriced)
562
690
  lines.push(`Not counted: ${unpricedText(s.unpriced)}`);
691
+ if (s.estimated) {
692
+ const one = s.estimated.models.length === 1;
693
+ 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.`);
694
+ }
695
+ if (s.changed)
696
+ lines.push(`An estimate: ${money(s.changed.usd)} of it is priced past the day its model's price changed (${priceChangedText(s.changed.models)}).`);
563
697
  lines.push(hookInstalled
564
698
  ? `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).`
565
699
  : "No every-prompt hook is installed, so nothing will say so: run context-doctor install.");
package/dist/cache.js CHANGED
@@ -10,7 +10,7 @@
10
10
  * caching at all.
11
11
  */
12
12
  import { readFileSync } from "node:fs";
13
- import { cacheWriteSplit, pricingFor, usageCost } from "./pricing.js";
13
+ import { cacheWriteSplit, requestCost } from "./pricing.js";
14
14
  import { replyCounter } from "./session.js";
15
15
  import { realModel } from "./tokens.js";
16
16
  export function analyzeCacheUsage(transcriptPath) {
@@ -65,9 +65,10 @@ export function analyzeCacheUsage(transcriptPath) {
65
65
  cacheWrite1hTokens += cacheWriteSplit(usage).oneHour;
66
66
  uncachedTokens += fresh;
67
67
  // Each request at its own model's price: a session can switch models.
68
- const pricing = pricingFor(model);
69
- if (pricing) {
70
- const cost = usageCost(usage, pricing);
68
+ // As billed (requestCost): its tier, fast mode, US-only.
69
+ const cost = requestCost(model, usage, Date.parse(String(entry.timestamp ?? "")) || undefined);
70
+ const pricing = cost?.rates;
71
+ if (cost && pricing) {
71
72
  priced++;
72
73
  paidUsd += cost.promptUsd;
73
74
  writeUsd += cost.writeUsd;
@@ -66,7 +66,7 @@ const SIZE_BUCKETS = [["<100k", 100_000], ["100-300k", 300_000], ["300-600k", 60
66
66
  const bucketOf = (tokens) => SIZE_BUCKETS.find(([, max]) => tokens < max)[0];
67
67
  const num = (x) => (typeof x === "number" && Number.isFinite(x) && x > 0 ? x : 0);
68
68
  export const MISS_ROWS = {
69
- id: "misses.1",
69
+ id: "misses.2",
70
70
  init: () => ({ user: false }),
71
71
  line(line, row, out, st) {
72
72
  const block = () => {
@@ -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,19 +32,20 @@
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";
39
39
  import { REQUEST_ROWS } from "./coldresume.js";
40
40
  import { rowsOf } from "./scan.js";
41
- import { CACHE_WRITE_1H, CACHE_WRITE_5M, cacheWriteSplit, pricingFor, usageCost } from "./pricing.js";
41
+ import { CACHE_WRITE_1H, CACHE_WRITE_5M, cacheWriteSplit, requestCost } from "./pricing.js";
42
42
  import { realModel } from "./tokens.js";
43
43
  import { backupOnce } from "./install.js";
44
44
  import { ABSENT, readSettings, setJsonPath, withSettingsLock, writeAtomic } from "./settingsedit.js";
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;
@@ -104,14 +105,16 @@ export function replayTtlTranscript(path, acc, since, until = Infinity, sidechai
104
105
  // wrote nothing keeps the lifetime of the last one that did.
105
106
  if (W > 0)
106
107
  lastTtl = split.oneHour > split.fiveMinute ? HOUR : FIVE_MIN;
107
- const p = pricingFor(model);
108
+ // The rates it billed at (its tier, fast mode, US-only): a lifetime changes reads and writes, not the prompt's length.
109
+ const c = requestCost(model, u, at);
110
+ const p = c?.rates;
108
111
  if (at >= since && at < until && seen === "new") {
109
112
  counted++;
110
113
  acc.requests++;
111
- if (!p)
114
+ if (!c || !p)
112
115
  acc.unpriced++;
113
116
  else {
114
- acc.billedUsd += usageCost(u, p).promptUsd;
117
+ acc.billedUsd += c.promptUsd;
115
118
  acc.writes += W;
116
119
  acc.writes1h += split.oneHour;
117
120
  const inp = p.inputPerM / 1e6;
@@ -159,7 +162,11 @@ function finish(acc) {
159
162
  const { writes, writes1h, ...r } = acc;
160
163
  return { ...r, oneHourShare: writes > 0 ? writes1h / writes : 0 };
161
164
  }
162
- /** Subagent transcripts of the main transcripts under ~/.claude/projects written since `since`. */
165
+ /**
166
+ * Subagent transcripts of the sessions under ~/.claude/projects written
167
+ * since `since`: the Agent tool's and the workflow agents'
168
+ * (subagents/workflows/<run>/, subagentFiles).
169
+ */
163
170
  export function subagentTranscripts(since, home = homedir()) {
164
171
  const root = join(claudeDir(home), "projects");
165
172
  const out = [];
@@ -179,30 +186,10 @@ export function subagentTranscripts(since, home = homedir()) {
179
186
  continue;
180
187
  }
181
188
  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 {
189
+ if (entry.endsWith(".jsonl") || !existsSync(join(root, project, entry, "subagents")))
192
190
  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
- }
191
+ for (const f of subagentFiles(join(root, project, `${entry}.jsonl`), since))
192
+ out.push(f.file);
206
193
  }
207
194
  }
208
195
  return out;