context-doctor 0.45.0 → 0.47.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 (75) hide show
  1. package/README.md +8 -3
  2. package/dist/ab.js +3 -2
  3. package/dist/autopilot.js +9 -5
  4. package/dist/blob.js +66 -12
  5. package/dist/budget.d.ts +10 -1
  6. package/dist/budget.js +37 -8
  7. package/dist/cachemisses.js +5 -3
  8. package/dist/cacheplan.js +2 -2
  9. package/dist/cachettl.js +2 -1
  10. package/dist/ci.js +2 -1
  11. package/dist/claudeplugin.d.ts +97 -0
  12. package/dist/claudeplugin.js +142 -0
  13. package/dist/cli.js +126 -39
  14. package/dist/coldresume.d.ts +6 -0
  15. package/dist/coldresume.js +7 -6
  16. package/dist/compactcost.d.ts +74 -0
  17. package/dist/compactcost.js +115 -0
  18. package/dist/compactwindow.js +5 -4
  19. package/dist/cursor.js +2 -0
  20. package/dist/doctor.js +106 -17
  21. package/dist/extract.js +4 -3
  22. package/dist/fanout.d.ts +15 -0
  23. package/dist/fanout.js +31 -10
  24. package/dist/firstfix.d.ts +43 -0
  25. package/dist/firstfix.js +80 -0
  26. package/dist/fix.d.ts +46 -2
  27. package/dist/fix.js +109 -20
  28. package/dist/hook.js +6 -2
  29. package/dist/httpguard.d.ts +13 -0
  30. package/dist/httpguard.js +22 -0
  31. package/dist/install.d.ts +21 -9
  32. package/dist/install.js +211 -40
  33. package/dist/limits.d.ts +5 -0
  34. package/dist/limits.js +26 -2
  35. package/dist/mcp.js +63 -62
  36. package/dist/missledger.js +5 -3
  37. package/dist/mod/api.d.ts +135 -0
  38. package/dist/mod/api.js +12 -0
  39. package/dist/mod/logic.d.ts +158 -0
  40. package/dist/mod/logic.js +244 -0
  41. package/dist/mod/register.d.ts +60 -0
  42. package/dist/mod/register.js +251 -0
  43. package/dist/modelids.d.ts +24 -0
  44. package/dist/modelids.js +65 -0
  45. package/dist/modelswitch.js +8 -4
  46. package/dist/modmeasure.d.ts +121 -0
  47. package/dist/modmeasure.js +310 -0
  48. package/dist/orgrates.d.ts +93 -0
  49. package/dist/orgrates.js +214 -0
  50. package/dist/overhead.js +11 -8
  51. package/dist/pack.d.ts +13 -0
  52. package/dist/pack.js +68 -3
  53. package/dist/preferences.js +2 -1
  54. package/dist/pricing.d.ts +26 -0
  55. package/dist/pricing.js +61 -7
  56. package/dist/progresssummaries.d.ts +148 -0
  57. package/dist/progresssummaries.js +248 -0
  58. package/dist/proxy.d.ts +1 -1
  59. package/dist/proxy.js +1 -1
  60. package/dist/prune.d.ts +8 -0
  61. package/dist/prune.js +11 -1
  62. package/dist/savings.js +8 -6
  63. package/dist/sessionprice.d.ts +22 -0
  64. package/dist/sessionprice.js +46 -14
  65. package/dist/spend.d.ts +46 -3
  66. package/dist/spend.js +86 -10
  67. package/dist/statusline.js +2 -2
  68. package/dist/subagentmodel.d.ts +12 -0
  69. package/dist/subagentmodel.js +17 -4
  70. package/dist/subagentpay.d.ts +15 -1
  71. package/dist/subagentpay.js +58 -25
  72. package/dist/subagents.js +4 -0
  73. package/dist/toolcwd.d.ts +14 -0
  74. package/dist/toolcwd.js +17 -0
  75. package/package.json +1 -1
@@ -0,0 +1,248 @@
1
+ /**
2
+ * Claude Code's subagent progress summaries, estimated: side requests no
3
+ * transcript records. The `progress-summaries` lever of `fix`.
4
+ *
5
+ * While a background subagent runs, Claude Code asks a model every 30
6
+ * seconds for a 3-5 word line about what it is doing (the text on its task
7
+ * row). The request is made with `skipTranscript`, so no transcript row
8
+ * carries it, and Claude Code bills it and counts it in its own cost
9
+ * (anthropics/claude-code#86879 measured 22.7% of one subagent-heavy
10
+ * session's requests). `CLAUDE_CODE_DISABLE_AGENT_PROGRESS_SUMMARIES=1`
11
+ * (2.1.318+, documented in 2.1.323) turns them off, and the requests with
12
+ * them. The summary never enters the agent's context: the work is the same.
13
+ *
14
+ * Read from the 2.1.321 binary (the Desktop app's bundled Claude Code, with
15
+ * `strings`; docs/spend.md has the details):
16
+ * - Who gets them. Only a subagent run in the background (the async
17
+ * runner), and there only when the host asked for them (the SDK's
18
+ * `agentProgressSummaries` option) or the session is interactive (a
19
+ * terminal, `entrypoint: "cli"`) and the fork gate is open (on unless
20
+ * CLAUDE_CODE_FORK_SUBAGENT=0) or coordinator mode is on. A fork launched
21
+ * in the background gets them in every mode. A foreground subagent gets
22
+ * them only when the host asked. Workflow agents never do. The Desktop
23
+ * app's Code tab runs Claude Code through the SDK, so its sessions are
24
+ * not interactive, and its bundle (5.11492) never sets the option: none.
25
+ * - How often. A timer every 30 s from the agent's start; a tick is skipped
26
+ * while the agent's transcript has fewer than 3 messages or has not
27
+ * changed since the last summary; it stops when the agent ends.
28
+ * - What each sends. Either the agent's whole conversation as a one-turn
29
+ * fork on the agent's own model (no cache write, so its prefix is read
30
+ * from the agent's cache), or ("short") at most ~1,500 tokens of notes
31
+ * about its recent steps, with prompt caching off and low effort, on the
32
+ * agent's own model (or Haiku). Which one is served per model from
33
+ * Anthropic's side and is not in any file here; Anthropic said on
34
+ * 2026-11-09 (#86879) that the summaries now "consume 99% less", which is
35
+ * the notes. So both are priced: the notes as the low figure, the whole
36
+ * context as the high one.
37
+ *
38
+ * Estimated per subagent from what its transcript does record: the time of
39
+ * each message (the ticks and whether the transcript changed), each reply's
40
+ * prompt size and model (the context a fork would read, the rates). Each
41
+ * summary's output is #86879's measured mean (65 tokens). Not counted: a
42
+ * tick held while the agent's own request waits on a cold cache (it fires
43
+ * later, not more often), and the thinking a summary may do.
44
+ */
45
+ import { existsSync, readFileSync } from "node:fs";
46
+ import { pick, rowsOf } from "./scan.js";
47
+ import { requestCost } from "./pricing.js";
48
+ import { realModel } from "./tokens.js";
49
+ import { workflowRunOf } from "./subagents.js";
50
+ import { compareVersions } from "./modelswitch.js";
51
+ /** The variable the lever writes, and the value: Claude Code passes only "1" on to the sessions it starts in the background. */
52
+ export const PROGRESS_SUMMARIES_ENV = "CLAUDE_CODE_DISABLE_AGENT_PROGRESS_SUMMARIES";
53
+ export const PROGRESS_SUMMARIES_OFF = "1";
54
+ /** The first Claude Code that reads it (its CHANGELOG, 2.1.323: "available since 2.1.318"). */
55
+ export const PROGRESS_SUMMARIES_SINCE = "2.1.318";
56
+ /** The summary timer (the binary's default; #86879 and #105981 measured 30-32 s). */
57
+ export const SUMMARY_TICK_MS = 30_000;
58
+ /** A short summary's prompt: notes capped at 2,000 - 500 tokens, plus its system prompt and instruction. */
59
+ export const NOTES_TOKENS = 1_850;
60
+ /** A fork summary's own instruction, after the agent's context. */
61
+ export const FORK_PROMPT_TOKENS = 150;
62
+ /** Each summary's output: #86879's measured mean (21,966 tokens over 339 summaries). */
63
+ export const SUMMARY_OUTPUT_TOKENS = 65;
64
+ /** How Claude Code reads the variable (a boolean: "1", "true", "yes", "on"). */
65
+ export const disablesSummaries = (v) => ["1", "true", "yes", "on"].includes(String(v ?? "").trim().toLowerCase());
66
+ /**
67
+ * One subagent transcript's timeline: the first row's host and version, the
68
+ * time of each message, and each reply's prompt size and model (once per
69
+ * reply; its output is in the next prompt).
70
+ */
71
+ export const PROGRESS_ROWS = {
72
+ id: "progress-summaries.1",
73
+ init: () => ({ head: false, ids: {} }),
74
+ line(raw, row, out, st) {
75
+ if (!raw.includes('"timestamp"'))
76
+ return;
77
+ let e;
78
+ try {
79
+ e = row();
80
+ }
81
+ catch {
82
+ return;
83
+ }
84
+ if (!e || typeof e !== "object")
85
+ return;
86
+ if (!st.head && (typeof e.entrypoint === "string" || typeof e.version === "string")) {
87
+ st.head = true;
88
+ out.push({ t: "h", ...pick(e, ["entrypoint", "version"]) });
89
+ }
90
+ if (e.type !== "user" && e.type !== "assistant" && e.type !== "attachment")
91
+ return;
92
+ const ts = Date.parse(String(e.timestamp ?? ""));
93
+ if (!Number.isFinite(ts))
94
+ return;
95
+ out.push({ t: "m", ts });
96
+ const m = e.message;
97
+ if (e.type !== "assistant" || !m?.usage)
98
+ return;
99
+ const id = typeof m.id === "string" ? m.id : undefined;
100
+ if (id) {
101
+ if (st.ids[id])
102
+ return;
103
+ st.ids[id] = 1;
104
+ }
105
+ const u = m.usage;
106
+ const n = (v) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0);
107
+ const prompt = n(u.input_tokens) + n(u.cache_read_input_tokens) + n(u.cache_creation_input_tokens);
108
+ out.push({ t: "r", ts, model: realModel(m.model), p: prompt, ...(u.speed === "fast" ? { speed: "fast" } : {}), ...(u.inference_geo === "us" ? { geo: "us" } : {}) });
109
+ },
110
+ };
111
+ export function readAgentMeta(file) {
112
+ const p = file.replace(/\.jsonl$/, ".meta.json");
113
+ if (!existsSync(p))
114
+ return undefined;
115
+ try {
116
+ const j = JSON.parse(readFileSync(p, "utf8"));
117
+ if (!j || typeof j !== "object")
118
+ return undefined;
119
+ return { ...(typeof j.agentType === "string" ? { agentType: j.agentType } : {}), ...(typeof j.requestShape === "string" ? { requestShape: j.requestShape } : {}), ...(j.isFork === true ? { isFork: true } : {}) };
120
+ }
121
+ catch {
122
+ return undefined;
123
+ }
124
+ }
125
+ /**
126
+ * Whether Claude Code (2.1.321's rules) wrote progress summaries for this
127
+ * agent. `interactive`: whether its host counts as interactive (default: a
128
+ * terminal session, entrypoint "cli").
129
+ */
130
+ export function eligibility(meta, entrypoint, opts = {}) {
131
+ if (opts.workflow || meta?.agentType === "workflow-subagent")
132
+ return "workflow";
133
+ if (!meta?.requestShape)
134
+ return "unknown";
135
+ if (meta.requestShape !== "background")
136
+ return "foreground";
137
+ if (meta.isFork)
138
+ return "yes";
139
+ const interactive = opts.interactive ?? ((ep) => ep === "cli");
140
+ if (!interactive(entrypoint))
141
+ return "host";
142
+ return opts.forkGateOff ? "fork-gate-off" : "yes";
143
+ }
144
+ /**
145
+ * The ticks a running agent's timer made and the summaries they sent, from
146
+ * its timeline: every 30 s from its first row to its last, a summary when
147
+ * it has 3+ messages and more than at the last summary. Only ticks in
148
+ * [since, until] are counted.
149
+ */
150
+ export function simulateAgent(recs, since = -Infinity, until = Infinity) {
151
+ const msgs = recs.filter((r) => r.t === "m").map((r) => r.ts).sort((a, b) => a - b);
152
+ const replies = recs.filter((r) => r.t === "r").sort((a, b) => a.ts - b.ts);
153
+ const out = { calls: 0, notesUsd: 0, forkUsd: 0 };
154
+ if (msgs.length < 3 || replies.length === 0)
155
+ return out;
156
+ const start = msgs[0];
157
+ const end = msgs[msgs.length - 1];
158
+ let n = 0, last = 0, ri = -1;
159
+ for (let at = start + SUMMARY_TICK_MS; at <= end; at += SUMMARY_TICK_MS) {
160
+ while (n < msgs.length && msgs[n] <= at)
161
+ n++;
162
+ while (ri + 1 < replies.length && replies[ri + 1].ts <= at)
163
+ ri++;
164
+ if (n < 3 || n === last)
165
+ continue;
166
+ last = n;
167
+ if (at < since || at > until)
168
+ continue;
169
+ // The last reply's prompt is cached (the fork reads it); what came after it (its output, the
170
+ // tool results) is new, as far as the next reply's prompt says; before any reply, the first prompt.
171
+ const cur = ri >= 0 ? replies[ri] : undefined;
172
+ const next = replies[ri + 1];
173
+ const ref = cur ?? next;
174
+ const model = ref.model;
175
+ if (!model)
176
+ continue;
177
+ const read = cur ? cur.p : 0;
178
+ const fresh = (next ? Math.max(0, next.p - read) : 0) + FORK_PROMPT_TOKENS;
179
+ const b = { ...(ref.speed ? { speed: ref.speed } : {}), ...(ref.geo ? { inference_geo: ref.geo } : {}) };
180
+ const fork = requestCost(model, { input_tokens: fresh, cache_read_input_tokens: read, cache_creation_input_tokens: 0, output_tokens: SUMMARY_OUTPUT_TOKENS, ...b }, at);
181
+ const notes = requestCost(model, { input_tokens: NOTES_TOKENS, cache_read_input_tokens: 0, cache_creation_input_tokens: 0, output_tokens: SUMMARY_OUTPUT_TOKENS, ...b }, at);
182
+ if (!fork || !notes)
183
+ continue;
184
+ out.calls++;
185
+ out.forkUsd += fork.totalUsd;
186
+ out.notesUsd += notes.totalUsd;
187
+ }
188
+ return out;
189
+ }
190
+ /** The summaries of the subagents in `files` (their `.jsonl` transcripts), estimated. */
191
+ export function estimateProgressSummaries(files, opts = {}) {
192
+ const r = { agents: 0, summarized: 0, calls: 0, notesUsd: 0, forkUsd: 0, none: {}, hosts: [] };
193
+ const hosts = new Set();
194
+ for (const file of files) {
195
+ let recs;
196
+ try {
197
+ recs = rowsOf(file, PROGRESS_ROWS);
198
+ }
199
+ catch {
200
+ continue;
201
+ }
202
+ // An agent that ran outside the window is not one of its agents (its file may be newer: a resumed session).
203
+ if (!recs.some((x) => x.t === "m" && x.ts >= (opts.since ?? -Infinity) && x.ts <= (opts.until ?? Infinity)))
204
+ continue;
205
+ r.agents++;
206
+ const head = recs.find((x) => x.t === "h");
207
+ let why = eligibility(readAgentMeta(file), head?.entrypoint, { workflow: workflowRunOf(file) !== undefined, forkGateOff: opts.forkGateOff, interactive: opts.interactive });
208
+ if (why === "yes" && opts.minVersion && !(head?.version && compareVersions(head.version, opts.minVersion) >= 0))
209
+ why = "old";
210
+ let until = opts.until ?? Infinity;
211
+ // The variable set from offSince on: a Claude Code that reads it wrote none after.
212
+ if (why === "yes" && opts.offSince !== undefined && head?.version && compareVersions(head.version, PROGRESS_SUMMARIES_SINCE) >= 0)
213
+ until = Math.min(until, opts.offSince);
214
+ if (why === "yes") {
215
+ const first = recs.reduce((m, x) => (x.t === "m" && x.ts < m ? x.ts : m), Infinity);
216
+ // An agent that started after the variable was set got none.
217
+ if (first > until)
218
+ why = "off";
219
+ else {
220
+ const s = simulateAgent(recs, opts.since, until);
221
+ // One that ran under 30 s, or outside the window, sent none.
222
+ if (s.calls)
223
+ r.summarized++;
224
+ r.calls += s.calls;
225
+ r.notesUsd += s.notesUsd;
226
+ r.forkUsd += s.forkUsd;
227
+ continue;
228
+ }
229
+ }
230
+ if (why === "host" && head?.entrypoint)
231
+ hosts.add(head.entrypoint);
232
+ r.none[why] = (r.none[why] ?? 0) + 1;
233
+ }
234
+ r.hosts = [...hosts].sort();
235
+ return r;
236
+ }
237
+ /** "the Desktop app", "the SDK or -p": a host as a person knows it. */
238
+ export function hostName(entrypoint) {
239
+ if (entrypoint === "claude-desktop")
240
+ return "the Desktop app";
241
+ if (entrypoint === "claude-vscode")
242
+ return "the VS Code extension";
243
+ if (entrypoint === "sdk-cli")
244
+ return "claude -p";
245
+ if (entrypoint.startsWith("sdk"))
246
+ return "the Agent SDK";
247
+ return entrypoint;
248
+ }
package/dist/proxy.d.ts CHANGED
@@ -76,7 +76,7 @@ export interface ProxyOptions extends OptimizeOptions {
76
76
  /** Default request body cap: far above any real request (a 1M-token context is ~4 MB of JSON, images aside). */
77
77
  export declare const DEFAULT_MAX_BODY_BYTES: number;
78
78
  /** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
79
- export declare const PROXY_VERSION = "0.45.0";
79
+ export declare const PROXY_VERSION = "0.47.0";
80
80
  /**
81
81
  * Remove a leading `/t/<token>` from a request path, or return undefined when
82
82
  * the prefix is absent or the token differs. The comparison is constant time
package/dist/proxy.js CHANGED
@@ -25,7 +25,7 @@ import { makeGuard, refusal } from "./httpguard.js";
25
25
  /** Default request body cap: far above any real request (a 1M-token context is ~4 MB of JSON, images aside). */
26
26
  export const DEFAULT_MAX_BODY_BYTES = 100 * 1024 * 1024;
27
27
  /** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
28
- export const PROXY_VERSION = "0.45.0";
28
+ export const PROXY_VERSION = "0.47.0";
29
29
  /** Connection-level headers that must not be forwarded. */
30
30
  const SKIP_REQUEST_HEADERS = new Set(["host", "content-length", "connection", "transfer-encoding", "accept-encoding", "expect"]);
31
31
  const SKIP_RESPONSE_HEADERS = new Set(["content-length", "content-encoding", "transfer-encoding", "connection"]);
package/dist/prune.d.ts CHANGED
@@ -85,6 +85,14 @@ export interface PrunePlan {
85
85
  }
86
86
  /** The project's own settings file, where prune writes. */
87
87
  export declare function localSettingsPath(cwd: string): string;
88
+ /**
89
+ * CLAUDE_CODE_IGNORE_PERSISTED_TRUST, read as Claude Code reads it (2.1.321:
90
+ * a boolean variable, true for 1, true, yes or on). Set, "no workspace trust
91
+ * record counts in this process" (a self-hosted runner sets it when started
92
+ * with --trust-workspace false): ~/.claude.json's hasTrustDialogAccepted is
93
+ * not read, so a project's own settings approve nothing.
94
+ */
95
+ export declare function persistedTrustIgnored(env?: NodeJS.ProcessEnv): boolean;
88
96
  /**
89
97
  * Whether Claude Code would start this project `.mcp.json` server without
90
98
  * asking: the user approved it (enabledMcpjsonServers, or
package/dist/prune.js CHANGED
@@ -304,7 +304,7 @@ function mcpjsonApprovedBy(name, cwd, home, read, off) {
304
304
  const projects = read(claudeJsonPath(home)).projects;
305
305
  const keys = trustKeys(cwd);
306
306
  const entry = (k) => (projects && typeof projects === "object" && projects[k] && typeof projects[k] === "object" ? projects[k] : undefined);
307
- const trusted = keys.some((k) => entry(k)?.hasTrustDialogAccepted === true);
307
+ const trusted = !persistedTrustIgnored() && keys.some((k) => entry(k)?.hasTrustDialogAccepted === true);
308
308
  const legacy = keys.map(entry).find((e) => e && (e.enabledMcpjsonServers !== undefined || e.enableAllProjectMcpServers !== undefined)) ?? {};
309
309
  const sources = trusted ? [user, read(join(cwd, ".claude", "settings.json")), legacy, read(localSettingsPath(cwd))] : [user];
310
310
  let all = false;
@@ -313,6 +313,16 @@ function mcpjsonApprovedBy(name, cwd, home, read, off) {
313
313
  all = trusted ? s.enableAllProjectMcpServers : all || s.enableAllProjectMcpServers;
314
314
  return all || sources.some((s) => list(s.enabledMcpjsonServers).some(same));
315
315
  }
316
+ /**
317
+ * CLAUDE_CODE_IGNORE_PERSISTED_TRUST, read as Claude Code reads it (2.1.321:
318
+ * a boolean variable, true for 1, true, yes or on). Set, "no workspace trust
319
+ * record counts in this process" (a self-hosted runner sets it when started
320
+ * with --trust-workspace false): ~/.claude.json's hasTrustDialogAccepted is
321
+ * not read, so a project's own settings approve nothing.
322
+ */
323
+ export function persistedTrustIgnored(env = process.env) {
324
+ return ["1", "true", "yes", "on"].includes(String(env.CLAUDE_CODE_IGNORE_PERSISTED_TRUST ?? "").trim().toLowerCase());
325
+ }
316
326
  /**
317
327
  * The keys ~/.claude.json may hold this workspace's trust under: the folder
318
328
  * and the repository root it is in (Claude Code keys a project by its git
package/dist/savings.js CHANGED
@@ -17,6 +17,7 @@ import { coldResumeEvents } from "./coldresume.js";
17
17
  import { listSessions, isClaudeSession } from "./session.js";
18
18
  import { rowsOf } from "./scan.js";
19
19
  import { CACHE_WRITE_1H, CACHE_WRITE_5M, cacheWriteSplit, rateCard, ratesAt, requestCost, writeMultiplier } from "./pricing.js";
20
+ import { priceBasis } from "./orgrates.js";
20
21
  import { estimateTokens, formatTokens, realModel } from "./tokens.js";
21
22
  import { withInvocation } from "./invocation.js";
22
23
  import { sessionsLabel } from "./compactwindow.js";
@@ -141,7 +142,8 @@ function replayExtractor(id, options, makeClearer, replay) {
141
142
  const r = {
142
143
  k: "r", now, cold,
143
144
  bw: fresh + read * 0.1 + ttl.fiveMinute * CACHE_WRITE_5M + ttl.oneHour * CACHE_WRITE_1H,
144
- usd: requestCost(pm, u, now)?.promptUsd ?? 0,
145
+ // No time of its own (now is 0 then): priced as of now, as requestCost prices one.
146
+ usd: requestCost(pm, u, now || undefined)?.promptUsd ?? 0,
145
147
  raw: fresh + read + write,
146
148
  };
147
149
  // Only what is set: a record read back from the cache must equal this one.
@@ -195,8 +197,8 @@ function replayExtractor(id, options, makeClearer, replay) {
195
197
  load: (v) => ({ ...v, ids: new Set(v.ids), base: loadArm(v.base, options), auto: loadArm(v.auto, options) }),
196
198
  };
197
199
  }
198
- const REPLAY = replayExtractor("replay.3", {}, undefined, true);
199
- const BILL = replayExtractor("bill.3", {}, undefined, false);
200
+ const REPLAY = replayExtractor("replay.4", {}, undefined, true);
201
+ const BILL = replayExtractor("bill.4", {}, undefined, false);
200
202
  /** What `estimateSavings` reads from each transcript, with or without autopilot's replay (for `prescan`). */
201
203
  export const savingsRows = (replay = true) => (replay ? REPLAY : BILL);
202
204
  /**
@@ -265,7 +267,7 @@ function settleReplay(path, rows, since, runRows, coldRows, replay) {
265
267
  requests++;
266
268
  // Each arm's request at its own tier (Haiku 5.5's 100k): as billed for the
267
269
  // session as it ran, less what autopilot cleared for the other.
268
- const card = rateCard(r.pm, { ...(r.f ? { speed: "fast" } : {}), ...(r.g ? { inference_geo: "us" } : {}) }, r.now);
270
+ const card = rateCard(r.pm, { ...(r.f ? { speed: "fast" } : {}), ...(r.g ? { inference_geo: "us" } : {}) }, r.now || undefined);
269
271
  const cleared = r.b && r.a ? Math.max(0, r.b[2] - r.a[2]) : 0;
270
272
  charge(base, r.b, r.cold, card ? ratesAt(card, r.raw) : UNPRICED);
271
273
  charge(auto, r.a, r.cold, card ? ratesAt(card, r.raw - cleared) : UNPRICED);
@@ -364,7 +366,7 @@ export function renderSavings(r, autopilotOn = false, cw, missLines, limitLines,
364
366
  // Kept within 80 columns: this is most people's first screen of the tool.
365
367
  lines.push("What context-doctor finds in your Claude Code sessions");
366
368
  // The same count, said the same way, as compact-window's.
367
- lines.push(`Last ${r.days} days, ${sessionsLabel(n, r.transcripts ?? n)}, at list prices`);
369
+ lines.push(`Last ${r.days} days, ${sessionsLabel(n, r.transcripts ?? n)}, ${priceBasis()}`);
368
370
  lines.push("─".repeat(60));
369
371
  lines.push(`Input you were billed for ${usd(r.billedUsd).padStart(9)} from your transcripts' usage`);
370
372
  lines.push("");
@@ -428,7 +430,7 @@ export function renderShare(r) {
428
430
  if (r.sessions.length === 0)
429
431
  return "context-doctor found no Claude Code sessions to measure yet.";
430
432
  const lines = [
431
- `My Claude Code input, last ${r.days} days: ${usd(r.billedUsd)} at list price (${r.sessions.length} sessions).`,
433
+ `My Claude Code input, last ${r.days} days: ${usd(r.billedUsd)} ${priceBasis(false)} (${r.sessions.length} sessions).`,
432
434
  ];
433
435
  if (r.coldResumeNetUsd > 0) {
434
436
  lines.push(`Running /compact when I came back to a big session after the cache expired would have saved ${usd(r.coldResumeNetUsd)} (${Math.round((r.coldResumeNetUsd / r.billedUsd) * 100)}%, ${r.coldResumes} times).`);
@@ -74,5 +74,27 @@ export interface SessionPriceInput {
74
74
  * Claims the threshold: a second call for the same one gets undefined.
75
75
  */
76
76
  export declare function sessionPriceDue(input: SessionPriceInput, now?: number, env?: NodeJS.ProcessEnv): SessionPrice | undefined;
77
+ /** What a session has cost so far, subagents included, as the threshold check prices it. */
78
+ export interface SessionTotal {
79
+ app: Tool;
80
+ usd: number;
81
+ subagentUsd: number;
82
+ workflowUsd: number;
83
+ unpriced: number;
84
+ estimatedUsd: number;
85
+ /** Bytes read to bring the entries up to date. */
86
+ read: number;
87
+ /** Keeps the entries, so the next look reads only what was appended. */
88
+ save: () => void;
89
+ }
90
+ /**
91
+ * The session's price so far, from the per-transcript entries the threshold
92
+ * check keeps (shared, so each reads only what the other has not). Claims
93
+ * no threshold: the mod compares it with Claude Code's own cost after each
94
+ * turn (modmeasure.ts).
95
+ */
96
+ export declare function sessionTotal(input: Pick<SessionPriceInput, "sessionId" | "transcript" | "event">, now?: number): SessionTotal;
97
+ /** Keeps a look's entries once it read enough to be worth it, as the threshold check does. */
98
+ export declare function saveIfWorthIt(t: Pick<SessionTotal, "read" | "save">): void;
77
99
  /** The line for the user (the hook's systemMessage). */
78
100
  export declare function renderSessionPrice(p: SessionPrice): string;
@@ -69,6 +69,8 @@ function base(sessionId) {
69
69
  return join(statePath().replace(/\.json$/, "") + ".d", createHash("sha1").update(sessionId).digest("hex").slice(0, 16));
70
70
  }
71
71
  const ledgerFile = (b) => `${b}.price.json`;
72
+ /** A Codex thread's candidate rollouts and what their first lines named (codexSpawnedRollouts). */
73
+ const headsFile = (b) => `${b}.spawn-heads.json`;
72
74
  /** The price file's format: 2 counts only the session's own rows and may leave a finished subagent's `r` out. */
73
75
  const LEDGER_VERSION = 2;
74
76
  /** A subagent transcript not written for this long is done: its entry keeps no recent replies. */
@@ -128,6 +130,28 @@ export function sessionPriceDue(input, now = Date.now(), env = process.env) {
128
130
  // Everything said: one stat from now on.
129
131
  if (said(claimFile(b, thresholds[thresholds.length - 1]), now))
130
132
  return undefined;
133
+ const { app, usd, subagentUsd, workflowUsd, unpriced, estimatedUsd, read, save } = sessionTotal(input, now);
134
+ const passed = thresholds.filter((t) => usd >= t);
135
+ const top = passed[passed.length - 1];
136
+ if (top === undefined || said(claimFile(b, top), now) || !claim(claimFile(b, top))) {
137
+ if (read >= SAVE_BYTES)
138
+ save();
139
+ return undefined;
140
+ }
141
+ // Passed two at once (a first look at a long session): said once, for the higher.
142
+ for (const t of passed.slice(0, -1))
143
+ claim(claimFile(b, t));
144
+ save();
145
+ return { app, threshold: top, usd, subagentUsd, ...(workflowUsd > 0 ? { workflowUsd } : {}), ...(unpriced ? { unpriced } : {}), ...(estimatedUsd > 0 ? { estimatedUsd } : {}), ...perMessage(app, input, now) };
146
+ }
147
+ /**
148
+ * The session's price so far, from the per-transcript entries the threshold
149
+ * check keeps (shared, so each reads only what the other has not). Claims
150
+ * no threshold: the mod compares it with Claude Code's own cost after each
151
+ * turn (modmeasure.ts).
152
+ */
153
+ export function sessionTotal(input, now = Date.now()) {
154
+ const b = base(input.sessionId);
131
155
  const app = appOf(input.transcript, input.event);
132
156
  // Each file and whose it is: the main conversation, a subagent, a workflow agent.
133
157
  const files = [[input.transcript, "main"]];
@@ -136,9 +160,23 @@ export function sessionPriceDue(input, now = Date.now(), env = process.env) {
136
160
  for (const f of subagentFiles(input.transcript))
137
161
  files.push([f.file, f.run ? "workflow" : "sub"]);
138
162
  // A Codex thread's spawned agents: their rollouts name it as their parent (a forked one's copy of its history counts once, by key).
139
- if (app === "codex")
140
- for (const f of codexSpawnedRollouts(input.transcript, now))
163
+ if (app === "codex") {
164
+ // What each rollout's first line named, kept: a prompt reads only the rollouts new since the last.
165
+ const known = { heads: {} };
166
+ try {
167
+ const raw = JSON.parse(readFileSync(headsFile(b), "utf8"));
168
+ if (raw && typeof raw === "object" && !Array.isArray(raw))
169
+ known.heads = raw;
170
+ }
171
+ catch { /* none yet, or damaged: read again */ }
172
+ for (const f of codexSpawnedRollouts(input.transcript, now, undefined, known))
141
173
  files.push([f, "sub"]);
174
+ if (known.changed)
175
+ try {
176
+ writeWhole(headsFile(b), known.heads);
177
+ }
178
+ catch { /* read again next time */ }
179
+ }
142
180
  let saved = {};
143
181
  try {
144
182
  const raw = JSON.parse(readFileSync(ledgerFile(b), "utf8"));
@@ -202,18 +240,12 @@ export function sessionPriceDue(input, now = Date.now(), env = process.env) {
202
240
  }
203
241
  catch { /* read again next time */ }
204
242
  };
205
- const passed = thresholds.filter((t) => usd >= t);
206
- const top = passed[passed.length - 1];
207
- if (top === undefined || said(claimFile(b, top), now) || !claim(claimFile(b, top))) {
208
- if (read >= SAVE_BYTES)
209
- save();
210
- return undefined;
211
- }
212
- // Passed two at once (a first look at a long session): said once, for the higher.
213
- for (const t of passed.slice(0, -1))
214
- claim(claimFile(b, t));
215
- save();
216
- return { app, threshold: top, usd, subagentUsd, ...(workflowUsd > 0 ? { workflowUsd } : {}), ...(unpriced ? { unpriced } : {}), ...(estimatedUsd > 0 ? { estimatedUsd } : {}), ...perMessage(app, input, now) };
243
+ return { app, usd, subagentUsd, workflowUsd, unpriced, estimatedUsd, read, save };
244
+ }
245
+ /** Keeps a look's entries once it read enough to be worth it, as the threshold check does. */
246
+ export function saveIfWorthIt(t) {
247
+ if (t.read >= SAVE_BYTES)
248
+ t.save();
217
249
  }
218
250
  /** The main conversation's context now, and what the next message pays for it. */
219
251
  function perMessage(app, input, now) {
package/dist/spend.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * `context-doctor spend`: one bill across every AI coding tool on this
3
- * machine, at list prices.
3
+ * machine, each request as billed at list rates.
4
4
  *
5
5
  * Each tool keeps its own record of what it sent, and none adds them up:
6
6
  *
@@ -29,11 +29,17 @@
29
29
  * (scan.ts), so a second run reads only what was appended since; Cursor's
30
30
  * replies are kept per chat until the chat changes.
31
31
  *
32
+ * Not in the total: Claude Code's subagent progress summaries, side requests
33
+ * no transcript records (progresssummaries.ts). They are estimated per
34
+ * background subagent and shown beside the total as a range, the two ways
35
+ * Anthropic may serve them (short notes, or the whole context).
36
+ *
32
37
  * `savings` bills a narrower slice of the same Claude Code requests: the main
33
38
  * conversation's input (cache writes and reads included, output not), in
34
39
  * sessions with 10+ requests. `spend` counts every request, its output and
35
40
  * subagents too; on the requests both count, the dollars are the same.
36
41
  */
42
+ import { type ProgressOptions } from "./progresssummaries.js";
37
43
  import { type Modifiers } from "./pricing.js";
38
44
  import { type Extractor } from "./scan.js";
39
45
  export type Tool = "claude" | "codex" | "gemini" | "cursor";
@@ -70,6 +76,8 @@ export interface SpendItem {
70
76
  workflow?: string;
71
77
  /** Claude Code: the reply's row uuid, which a fork's copy shares. Codex: the event's codexEventKey, which a forked rollout's copy shares. */
72
78
  key?: string;
79
+ /** Claude Code: a compaction's own request, which no row records usage for: estimated from the context it read and its summary (compactcost.ts). */
80
+ compaction?: boolean;
73
81
  }
74
82
  /**
75
83
  * A project folder's name (its path with "-" for separators, as Claude Code
@@ -113,13 +121,22 @@ export declare function codexRolloutMeta(file: string): {
113
121
  * bill to the same work, as a Claude Code subagent's do.
114
122
  */
115
123
  export declare function codexSpend(since: number, until?: number, home?: string): SpendItem[];
124
+ /** What rollouts' first lines named, by file name: [its thread id, the thread that spawned it]. */
125
+ export interface SpawnHeads {
126
+ heads: Record<string, [id: string, parent?: string]>;
127
+ /** Set when `heads` gained or lost a rollout, so the caller saves it. */
128
+ changed?: boolean;
129
+ }
116
130
  /**
117
131
  * The rollouts of the agents a Codex thread spawned (and theirs), for the
118
132
  * session price: those written since the thread began in its own folder,
119
133
  * the day folders from then to `now` (by local and UTC date) and the
120
- * archive. Only each candidate's first line is read.
134
+ * archive. Only each candidate's first line is read, and with `known` only
135
+ * once: a rollout's first line (its own session_meta) never changes, so
136
+ * what it named is kept there by file name, and a prompt reads only the
137
+ * rollouts written since the last (`known.changed` says when to save it).
121
138
  */
122
- export declare function codexSpawnedRollouts(parent: string, now?: number, home?: string): string[];
139
+ export declare function codexSpawnedRollouts(parent: string, now?: number, home?: string, known?: SpawnHeads): string[];
123
140
  /**
124
141
  * What `spend` takes from a Gemini CLI chat (JSONL): each `gemini` message's
125
142
  * id, time, model and token counts. A message without a time of its own
@@ -201,6 +218,25 @@ export interface SpendReport {
201
218
  requests: number;
202
219
  usd: number;
203
220
  }>;
221
+ /** Claude Code's compactions, each one's own request estimated (no row records its usage): inside `usd`; absent when none. */
222
+ compactions?: {
223
+ requests: number;
224
+ usd: number;
225
+ };
226
+ /**
227
+ * Claude Code's subagent progress summaries, estimated (no transcript records them): NOT in `usd`.
228
+ * `notesUsd` as short notes (served since November 2026), `forkUsd` as the whole context (before).
229
+ * `set`: CLAUDE_CODE_DISABLE_AGENT_PROGRESS_SUMMARIES is set there, since when unknown: not estimated.
230
+ * Absent when no subagent got any.
231
+ */
232
+ progressSummaries?: {
233
+ agents: number;
234
+ calls: number;
235
+ notesUsd: number;
236
+ forkUsd: number;
237
+ } | {
238
+ set: string;
239
+ };
204
240
  sessions: Array<{
205
241
  tool: Tool;
206
242
  project: string;
@@ -227,6 +263,13 @@ export interface SpendOptions {
227
263
  claudePaths?: string[];
228
264
  onProgress?: (done: number, total: number) => void;
229
265
  now?: number;
266
+ /**
267
+ * The progress summaries' estimate: the fork gate, when the variable turned them off
268
+ * (fix's record), or where it is set with no record (then not estimated); false: none.
269
+ */
270
+ progress?: false | (Pick<ProgressOptions, "forkGateOff" | "offSince"> & {
271
+ set?: string;
272
+ });
230
273
  }
231
274
  /**
232
275
  * The longest window: ten years, older than any history these tools keep.