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/dist/prune.js CHANGED
@@ -33,8 +33,8 @@ import { dirname, join, resolve } from "node:path";
33
33
  import { statePath } from "./ledger.js";
34
34
  import { listSessions, isClaudeSession } from "./session.js";
35
35
  import { rowsOf } from "./scan.js";
36
- import { subagentDir } from "./subagents.js";
37
- import { claudeMcpConfigs, countMcpRow, serverUses } from "./mcpschema.js";
36
+ import { subagentFiles } from "./subagents.js";
37
+ import { claudeMcpConfigs, countMcpRow, serverUses, toolPrefixName } from "./mcpschema.js";
38
38
  import { estimateTokens, formatTokens } from "./tokens.js";
39
39
  import { formatUsd } from "./pricing.js";
40
40
  import { claudeDir, claudeJsonPath } from "./claudedir.js";
@@ -148,13 +148,9 @@ export function projectUsage(days = 30, paths, now = Date.now()) {
148
148
  };
149
149
  try {
150
150
  scan(path);
151
- let agents = [];
152
- try {
153
- agents = readdirSync(subagentDir(path)).filter((f) => f.endsWith(".jsonl"));
154
- }
155
- catch { /* none */ }
156
- for (const a of agents)
157
- scan(join(subagentDir(path), a));
151
+ // Subagents and workflow agents (subagents/workflows/<run>/) use servers too.
152
+ for (const a of subagentFiles(path))
153
+ scan(a.file);
158
154
  }
159
155
  catch {
160
156
  continue;
@@ -280,7 +276,74 @@ function offFor(cwd, home) {
280
276
  if (entry?.enableAllProjectMcpServers === true)
281
277
  all = true;
282
278
  }
283
- return { off, mcpjsonAllowlist: all ? undefined : allow };
279
+ return {
280
+ off,
281
+ mcpjsonAllowlist: all ? undefined : allow,
282
+ mcpjsonApproved: (name) => mcpjsonApprovedBy(name, cwd, home, read, off),
283
+ };
284
+ }
285
+ /**
286
+ * Claude Code's own approval of a project `.mcp.json` server (read from the
287
+ * 2.1.311 binary). Rejected when any settings file lists it in
288
+ * `disabledMcpjsonServers` (or it is toggled off). Otherwise the project's own
289
+ * files, `.claude/settings.json` and `.claude/settings.local.json`, count only
290
+ * once the user trusted the workspace (`hasTrustDialogAccepted` on its
291
+ * project, the repository root or the folder, in ~/.claude.json): both can
292
+ * arrive with a clone, and a repository approving its own servers is the
293
+ * attack the trust dialog stands in front of. Untrusted, only the user's
294
+ * settings approve; trusted, the files merge (a later file's
295
+ * `enableAllProjectMcpServers: false` overrides an earlier `true`). Names
296
+ * compare as Claude Code compares them, in their tool-name spelling.
297
+ */
298
+ function mcpjsonApprovedBy(name, cwd, home, read, off) {
299
+ const same = (n) => typeof n === "string" && toolPrefixName(n) === toolPrefixName(name);
300
+ for (const o of off)
301
+ if (o.startsWith("mcp:") && same(o.slice(4)))
302
+ return false;
303
+ const user = read(join(claudeDir(home), "settings.json"));
304
+ const projects = read(claudeJsonPath(home)).projects;
305
+ const keys = trustKeys(cwd);
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);
308
+ const legacy = keys.map(entry).find((e) => e && (e.enabledMcpjsonServers !== undefined || e.enableAllProjectMcpServers !== undefined)) ?? {};
309
+ const sources = trusted ? [user, read(join(cwd, ".claude", "settings.json")), legacy, read(localSettingsPath(cwd))] : [user];
310
+ let all = false;
311
+ for (const s of sources)
312
+ if (typeof s.enableAllProjectMcpServers === "boolean")
313
+ all = trusted ? s.enableAllProjectMcpServers : all || s.enableAllProjectMcpServers;
314
+ return all || sources.some((s) => list(s.enabledMcpjsonServers).some(same));
315
+ }
316
+ /**
317
+ * The keys ~/.claude.json may hold this workspace's trust under: the folder
318
+ * and the repository root it is in (Claude Code keys a project by its git
319
+ * root), each as given, resolved and real, with forward slashes too.
320
+ */
321
+ function trustKeys(cwd) {
322
+ const out = new Set();
323
+ const add = (p) => { for (const v of [p, resolve(p), canonical(p)]) {
324
+ out.add(v);
325
+ out.add(v.replace(/\\/g, "/"));
326
+ } };
327
+ add(cwd);
328
+ for (let d = canonical(cwd);; d = dirname(d)) {
329
+ if (existsSync(join(d, ".git"))) {
330
+ add(d);
331
+ break;
332
+ }
333
+ if (dirname(d) === d)
334
+ break;
335
+ }
336
+ return [...out];
337
+ }
338
+ /**
339
+ * Whether Claude Code would start this project `.mcp.json` server without
340
+ * asking: the user approved it (enabledMcpjsonServers, or
341
+ * enableAllProjectMcpServers, in a settings file or ~/.claude.json) and has
342
+ * not switched it off. A `.mcp.json` arrives with a clone, so its commands
343
+ * are a stranger's until then: `overhead --mcp` launches only approved ones.
344
+ */
345
+ export function mcpjsonServerApproved(name, cwd = process.cwd(), home = homedir()) {
346
+ return offFor(cwd, home).mcpjsonApproved(name);
284
347
  }
285
348
  /** context-doctor's own server: its standing rules work with no calls at all. */
286
349
  const OURS = /^context-doctor$/;
package/dist/savings.js CHANGED
@@ -16,10 +16,11 @@ import { AutoClearer } from "./autoclear.js";
16
16
  import { coldResumeEvents } from "./coldresume.js";
17
17
  import { listSessions, isClaudeSession } from "./session.js";
18
18
  import { rowsOf } from "./scan.js";
19
- import { CACHE_WRITE_1H, CACHE_WRITE_5M, cacheWriteSplit, pricingFor, usageCost, writeMultiplier } from "./pricing.js";
19
+ import { CACHE_WRITE_1H, CACHE_WRITE_5M, cacheWriteSplit, rateCard, ratesAt, requestCost, writeMultiplier } from "./pricing.js";
20
20
  import { estimateTokens, formatTokens, realModel } from "./tokens.js";
21
21
  import { withInvocation } from "./invocation.js";
22
22
  import { sessionsLabel } from "./compactwindow.js";
23
+ import { projectFromDir } from "./spend.js";
23
24
  /** System prompt and tool schemas: sent on every request, identical in both arms. */
24
25
  const FIXED_TOKENS = 54_000;
25
26
  const CLAUDE_CODE_TTL_MS = 3_600_000;
@@ -133,7 +134,6 @@ function replayExtractor(id, options, makeClearer, replay) {
133
134
  // Each request at its own model: a session that switched from a
134
135
  // $4 to a $10 model was priced at the first one throughout.
135
136
  const pm = realModel(m.model) ?? st.model;
136
- const price = pricingFor(pm);
137
137
  const ttl = cacheWriteSplit(u);
138
138
  st.writes5m += ttl.fiveMinute;
139
139
  st.writes1h += ttl.oneHour;
@@ -141,7 +141,7 @@ function replayExtractor(id, options, makeClearer, replay) {
141
141
  const r = {
142
142
  k: "r", now, cold,
143
143
  bw: fresh + read * 0.1 + ttl.fiveMinute * CACHE_WRITE_5M + ttl.oneHour * CACHE_WRITE_1H,
144
- usd: price ? usageCost(u, price).promptUsd : 0,
144
+ usd: requestCost(pm, u, now)?.promptUsd ?? 0,
145
145
  raw: fresh + read + write,
146
146
  };
147
147
  // Only what is set: a record read back from the cache must equal this one.
@@ -149,6 +149,11 @@ function replayExtractor(id, options, makeClearer, replay) {
149
149
  r.uuid = uuid;
150
150
  if (pm !== undefined)
151
151
  r.pm = pm;
152
+ // What bills the arms' requests as this one was (fast mode, US-only).
153
+ if (u.speed === "fast")
154
+ r.f = 1;
155
+ if (u.inference_geo === "us")
156
+ r.g = 1;
152
157
  if (st.base && st.auto) {
153
158
  const b = armRequest(st.base, now, cold), a = armRequest(st.auto, now, cold);
154
159
  Object.assign(r, { b: [b.read, b.write, b.total], a: [a.read, a.write, a.total] });
@@ -190,8 +195,8 @@ function replayExtractor(id, options, makeClearer, replay) {
190
195
  load: (v) => ({ ...v, ids: new Set(v.ids), base: loadArm(v.base, options), auto: loadArm(v.auto, options) }),
191
196
  };
192
197
  }
193
- const REPLAY = replayExtractor("replay.2", {}, undefined, true);
194
- const BILL = replayExtractor("bill.2", {}, undefined, false);
198
+ const REPLAY = replayExtractor("replay.3", {}, undefined, true);
199
+ const BILL = replayExtractor("bill.3", {}, undefined, false);
195
200
  /** What `estimateSavings` reads from each transcript, with or without autopilot's replay (for `prescan`). */
196
201
  export const savingsRows = (replay = true) => (replay ? REPLAY : BILL);
197
202
  /**
@@ -258,9 +263,12 @@ function settleReplay(path, rows, since, runRows, coldRows, replay) {
258
263
  billedUsd += r.usd;
259
264
  billedRaw += r.raw;
260
265
  requests++;
261
- const price = pricingFor(r.pm) ?? UNPRICED;
262
- charge(base, r.b, r.cold, price);
263
- charge(auto, r.a, r.cold, price);
266
+ // Each arm's request at its own tier (Haiku 5.5's 100k): as billed for the
267
+ // 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);
269
+ const cleared = r.b && r.a ? Math.max(0, r.b[2] - r.a[2]) : 0;
270
+ charge(base, r.b, r.cold, card ? ratesAt(card, r.raw) : UNPRICED);
271
+ charge(auto, r.a, r.cold, card ? ratesAt(card, r.raw - cleared) : UNPRICED);
264
272
  }
265
273
  }
266
274
  flush();
@@ -285,7 +293,7 @@ function settleReplay(path, rows, since, runRows, coldRows, replay) {
285
293
  const entrypoint = end?.entrypoint;
286
294
  return {
287
295
  path,
288
- project: dir.replace(/^-Users-[^-]+-/, "").replace(/^-/, "") || dir,
296
+ project: projectFromDir(dir),
289
297
  model: end?.model,
290
298
  requests,
291
299
  billedWeighted: billed,
package/dist/scan.d.ts CHANGED
@@ -103,4 +103,10 @@ export declare function clearScanMemo(): void;
103
103
  export declare function pruneScanCache(now?: number, force?: boolean): void;
104
104
  /** `o` with only `keys`, those set: what a record keeps of a row. Not an object: as it was. */
105
105
  export declare function pick(o: any, keys: readonly string[]): any;
106
- export declare const slimUsage: (u: unknown) => unknown;
106
+ /**
107
+ * Those fields, and what changes the request's price (requestCost) only
108
+ * when it does: fast mode, US-only inference, web searches. Every request
109
+ * records `speed`, `inference_geo` and `server_tool_use`; kept on each, they
110
+ * would grow every record for nothing.
111
+ */
112
+ export declare const slimUsage: (u: any) => unknown;
package/dist/scan.js CHANGED
@@ -501,4 +501,22 @@ export function pick(o, keys) {
501
501
  }
502
502
  /** The usage fields any report reads (cost, cache writes by TTL, reasoning, context edits). */
503
503
  const USAGE_KEYS = ["input_tokens", "cache_creation_input_tokens", "cache_read_input_tokens", "output_tokens", "cache_creation", "output_tokens_details", "context_management"];
504
- export const slimUsage = (u) => pick(u, USAGE_KEYS);
504
+ /**
505
+ * Those fields, and what changes the request's price (requestCost) only
506
+ * when it does: fast mode, US-only inference, web searches. Every request
507
+ * records `speed`, `inference_geo` and `server_tool_use`; kept on each, they
508
+ * would grow every record for nothing.
509
+ */
510
+ export const slimUsage = (u) => {
511
+ const out = pick(u, USAGE_KEYS);
512
+ if (!out || typeof out !== "object" || Array.isArray(out))
513
+ return out;
514
+ if (u.speed === "fast")
515
+ out.speed = "fast";
516
+ if (u.inference_geo === "us")
517
+ out.inference_geo = "us";
518
+ const searches = u.server_tool_use?.web_search_requests;
519
+ if (typeof searches === "number" && searches > 0)
520
+ out.server_tool_use = { web_search_requests: searches };
521
+ return out;
522
+ };
@@ -6,7 +6,8 @@
6
6
  * (the author's `gantry-ai` audit: 2,795 requests, 1.3B cached tokens read).
7
7
  * So before each prompt (Claude Code's and Codex's UserPromptSubmit, Gemini
8
8
  * CLI's BeforeAgent) the hook adds up what this session has cost, subagents
9
- * included (they bill to it), and when it passes $25, $100 and $500 says so
9
+ * included (they bill to it: Claude Code's, and the agents a Codex thread
10
+ * spawned, codexSpawnedRollouts), and when it passes $25, $100 and $500 says so
10
11
  * to the user once: the cost so far, what each message of the main
11
12
  * conversation now costs at the model's cache-read rate (or, after an idle
12
13
  * that expired the cache, the re-write this message pays), and that
@@ -43,8 +44,14 @@ export interface SessionPrice {
43
44
  /** The threshold just passed. */
44
45
  threshold: number;
45
46
  usd: number;
46
- /** Subagents' part of `usd`. */
47
+ /** Subagents' part of `usd`: the Agent tool's, or the agents a Codex thread spawned. */
47
48
  subagentUsd: number;
49
+ /** Workflow agents' part of `usd`. */
50
+ workflowUsd?: number;
51
+ /** Requests on a model with no list price, not in `usd`. */
52
+ unpriced?: number;
53
+ /** The part of `usd` priced at its model's family's row (an estimate). */
54
+ estimatedUsd?: number;
48
55
  /** The main conversation's context at its last request, and its model. */
49
56
  tokens?: number;
50
57
  model?: string;
@@ -6,7 +6,8 @@
6
6
  * (the author's `gantry-ai` audit: 2,795 requests, 1.3B cached tokens read).
7
7
  * So before each prompt (Claude Code's and Codex's UserPromptSubmit, Gemini
8
8
  * CLI's BeforeAgent) the hook adds up what this session has cost, subagents
9
- * included (they bill to it), and when it passes $25, $100 and $500 says so
9
+ * included (they bill to it: Claude Code's, and the agents a Codex thread
10
+ * spawned, codexSpawnedRollouts), and when it passes $25, $100 and $500 says so
10
11
  * to the user once: the cost so far, what each message of the main
11
12
  * conversation now costs at the model's cache-read rate (or, after an idle
12
13
  * that expired the cache, the re-write this message pays), and that
@@ -32,17 +33,17 @@
32
33
  * Thresholds: CONTEXT_DOCTOR_SESSION_PRICE (dollars, e.g. "50,200");
33
34
  * off: CONTEXT_DOCTOR_NO_SESSION_PRICE=1.
34
35
  */
35
- import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
36
+ import { mkdirSync, readFileSync, statSync, utimesSync, writeFileSync } from "node:fs";
36
37
  import { createHash } from "node:crypto";
37
38
  import { basename, dirname, join } from "node:path";
38
39
  import { statePath } from "./ledger.js";
39
40
  import { refreshEntry, wellFormed, writeWhole } from "./budget.js";
40
- import { codexFileSpend, geminiFileSpend } from "./spend.js";
41
+ import { codexFileSpend, codexSpawnedRollouts, geminiFileSpend } from "./spend.js";
41
42
  import { isGeminiChat } from "./gemini.js";
42
- import { subagentDir } from "./subagents.js";
43
+ import { subagentFiles } from "./subagents.js";
43
44
  import { tailUsage } from "./statusline.js";
44
45
  import { autoCompactsAt, detectColdResume, withResumeVerdict } from "./coldresume.js";
45
- import { formatUsd, pricingFor } from "./pricing.js";
46
+ import { formatUsd, rateCard, ratesAt } from "./pricing.js";
46
47
  import { formatTokens } from "./tokens.js";
47
48
  /** Where the hook speaks unless CONTEXT_DOCTOR_SESSION_PRICE says otherwise. */
48
49
  export const SESSION_PRICE_THRESHOLDS = [25, 100, 500];
@@ -68,7 +69,31 @@ function base(sessionId) {
68
69
  return join(statePath().replace(/\.json$/, "") + ".d", createHash("sha1").update(sessionId).digest("hex").slice(0, 16));
69
70
  }
70
71
  const ledgerFile = (b) => `${b}.price.json`;
72
+ /** The price file's format: 2 counts only the session's own rows and may leave a finished subagent's `r` out. */
73
+ const LEDGER_VERSION = 2;
74
+ /** A subagent transcript not written for this long is done: its entry keeps no recent replies. */
75
+ const FINISHED_MS = 60 * 60_000;
71
76
  const claimFile = (b, usd) => `${b}.price-${usd}`;
77
+ const DAY = 86_400_000;
78
+ /**
79
+ * Whether a threshold was said: its marker is there. The marker of a
80
+ * session still in use is touched once a day, so the hook's pruning (the
81
+ * sessions touched least recently go, hook.ts) does not take it while the
82
+ * session goes on, and the threshold is not said twice.
83
+ */
84
+ function said(path, now) {
85
+ try {
86
+ if (now - statSync(path).mtimeMs > DAY)
87
+ try {
88
+ utimesSync(path, new Date(now), new Date(now));
89
+ }
90
+ catch { /* read-only: said all the same */ }
91
+ return true;
92
+ }
93
+ catch {
94
+ return false;
95
+ }
96
+ }
72
97
  /** True for exactly one caller per path: the file is created only if it is not there. */
73
98
  function claim(path) {
74
99
  for (let attempt = 0; attempt < 2; attempt++) {
@@ -101,32 +126,34 @@ export function sessionPriceDue(input, now = Date.now(), env = process.env) {
101
126
  return undefined;
102
127
  const b = base(input.sessionId);
103
128
  // Everything said: one stat from now on.
104
- if (existsSync(claimFile(b, thresholds[thresholds.length - 1])))
129
+ if (said(claimFile(b, thresholds[thresholds.length - 1]), now))
105
130
  return undefined;
106
131
  const app = appOf(input.transcript, input.event);
107
- const files = [[input.transcript, false]];
108
- if (app === "claude") {
109
- // Subagents bill to the session that started them.
110
- const dir = subagentDir(input.transcript);
111
- try {
112
- for (const f of readdirSync(dir))
113
- if (f.endsWith(".jsonl"))
114
- files.push([join(dir, f), true]);
115
- }
116
- catch { /* no subagents */ }
117
- }
132
+ // Each file and whose it is: the main conversation, a subagent, a workflow agent.
133
+ const files = [[input.transcript, "main"]];
134
+ // Subagents and workflow agents bill to the session that started them.
135
+ if (app === "claude")
136
+ for (const f of subagentFiles(input.transcript))
137
+ files.push([f.file, f.run ? "workflow" : "sub"]);
138
+ // 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))
141
+ files.push([f, "sub"]);
118
142
  let saved = {};
119
143
  try {
120
- const raw = JSON.parse(readFileSync(ledgerFile(b), "utf8"))?.f;
121
- if (raw && typeof raw === "object")
122
- saved = raw;
144
+ const raw = JSON.parse(readFileSync(ledgerFile(b), "utf8"));
145
+ // Version 2 counts only this session's own rows: an older file counted a resumed session's copy of the old one.
146
+ if (raw?.v === LEDGER_VERSION && raw.f && typeof raw.f === "object")
147
+ saved = raw.f;
123
148
  }
124
149
  catch { /* none yet, or damaged: read again */ }
150
+ // A Claude Code session's own rows carry its id (the transcript's name); a resumed or forked session's copy of the old one's keep the old id.
151
+ const own = app === "claude" ? basename(input.transcript, ".jsonl") : undefined;
125
152
  const kept = {};
126
153
  let read = 0;
127
154
  for (const [file] of files) {
128
155
  const prev = saved[file];
129
- const r = refreshEntry(app, file, wellFormed(prev) && prev.t === app ? prev : undefined, 0, true);
156
+ const r = refreshEntry(app, file, wellFormed(prev) && prev.t === app ? prev : undefined, 0, true, own);
130
157
  if (!r)
131
158
  continue;
132
159
  kept[file] = r.e;
@@ -136,11 +163,12 @@ export function sessionPriceDue(input, now = Date.now(), env = process.env) {
136
163
  }
137
164
  // Each reply once: a fork's copy shares its key with the reply it copied.
138
165
  const seen = new Set();
139
- let usd = 0, subagentUsd = 0;
140
- for (const [file, sub] of files) {
166
+ let usd = 0, subagentUsd = 0, workflowUsd = 0, unpriced = 0, estimatedUsd = 0;
167
+ for (const [file, whose] of files) {
141
168
  const e = kept[file];
142
169
  if (!e)
143
170
  continue;
171
+ const x = new Set((e.x ?? []).map(([i]) => i)), y = new Set((e.y ?? []).map(([i]) => i));
144
172
  e.k.forEach((key, i) => {
145
173
  if (key) {
146
174
  if (seen.has(key))
@@ -148,17 +176,35 @@ export function sessionPriceDue(input, now = Date.now(), env = process.env) {
148
176
  seen.add(key);
149
177
  }
150
178
  usd += e.d[i];
151
- if (sub)
179
+ if (whose === "sub")
152
180
  subagentUsd += e.d[i];
181
+ if (whose === "workflow")
182
+ workflowUsd += e.d[i];
183
+ if (x.has(i))
184
+ unpriced++;
185
+ if (y.has(i))
186
+ estimatedUsd += e.d[i];
153
187
  });
154
188
  }
155
- const save = () => { try {
156
- writeWhole(ledgerFile(b), { f: kept });
157
- }
158
- catch { /* read again next time */ } };
189
+ const save = () => {
190
+ // A subagent done writing (nothing for FINISHED_MS) keeps no list of its last replies: with
191
+ // hundreds of agents the list was most of the file, read on every prompt. Should it grow
192
+ // after all, it is read again whole (readAppended will not resume without the list).
193
+ const out = {};
194
+ for (const [file, whose] of files) {
195
+ const e = kept[file];
196
+ if (!e)
197
+ continue;
198
+ out[file] = whose !== "main" && e.r && now - e.m > FINISHED_MS ? (({ r: _r, ...rest }) => rest)(e) : e;
199
+ }
200
+ try {
201
+ writeWhole(ledgerFile(b), { v: LEDGER_VERSION, f: out });
202
+ }
203
+ catch { /* read again next time */ }
204
+ };
159
205
  const passed = thresholds.filter((t) => usd >= t);
160
206
  const top = passed[passed.length - 1];
161
- if (top === undefined || existsSync(claimFile(b, top)) || !claim(claimFile(b, top))) {
207
+ if (top === undefined || said(claimFile(b, top), now) || !claim(claimFile(b, top))) {
162
208
  if (read >= SAVE_BYTES)
163
209
  save();
164
210
  return undefined;
@@ -167,7 +213,7 @@ export function sessionPriceDue(input, now = Date.now(), env = process.env) {
167
213
  for (const t of passed.slice(0, -1))
168
214
  claim(claimFile(b, t));
169
215
  save();
170
- return { app, threshold: top, usd, subagentUsd, ...perMessage(app, input, now) };
216
+ return { app, threshold: top, usd, subagentUsd, ...(workflowUsd > 0 ? { workflowUsd } : {}), ...(unpriced ? { unpriced } : {}), ...(estimatedUsd > 0 ? { estimatedUsd } : {}), ...perMessage(app, input, now) };
171
217
  }
172
218
  /** The main conversation's context now, and what the next message pays for it. */
173
219
  function perMessage(app, input, now) {
@@ -177,18 +223,21 @@ function perMessage(app, input, now) {
177
223
  const items = app === "codex" ? codexFileSpend(input.transcript, 0) : geminiFileSpend(input.transcript, 0);
178
224
  const last = items[items.length - 1];
179
225
  const model = last?.model ?? input.model;
180
- const p = pricingFor(model);
181
- if (!last || !p)
226
+ const tokens = last ? last.input + last.read + last.write : 0;
227
+ // At the rate the next request bills: its prompt's tier (a long prompt's on OpenAI and Gemini Pro).
228
+ const card = rateCard(model, undefined, now);
229
+ if (!last || !card)
182
230
  return {};
183
- const tokens = last.input + last.read + last.write;
184
- return { tokens, model, readUsd: (tokens * p.cacheReadPerM) / 1e6 };
231
+ return { tokens, model, readUsd: (tokens * ratesAt(card, tokens).cacheReadPerM) / 1e6 };
185
232
  }
186
233
  // Undefined right after a compaction: the new size is not known yet.
187
234
  const live = tailUsage(input.transcript);
188
235
  if (!live)
189
236
  return {};
190
237
  const model = live.model ?? input.model;
191
- const p = pricingFor(model);
238
+ // As the next request bills: fast mode and US-only as the last one recorded, the tier of its prompt.
239
+ const card = rateCard(model, live.billing, now);
240
+ const p = card && ratesAt(card, live.tokens);
192
241
  // Claude Code compacts this very prompt itself: the figure is about to be wrong.
193
242
  if (!p || live.tokens >= (autoCompactsAt(model) ?? Infinity))
194
243
  return {};
@@ -203,7 +252,17 @@ function perMessage(app, input, now) {
203
252
  const dollars = (n) => (n >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
204
253
  /** The line for the user (the hook's systemMessage). */
205
254
  export function renderSessionPrice(p) {
206
- const subs = p.subagentUsd >= 0.005 ? ` (${dollars(p.subagentUsd)} of it subagents)` : "";
255
+ // What the figure holds, briefly: its subagents and workflow agents, a part priced by family, and what it leaves out.
256
+ const agents = [
257
+ p.subagentUsd >= 0.005 ? `${dollars(p.subagentUsd)} of it subagents` : "",
258
+ (p.workflowUsd ?? 0) >= 0.005 ? `${dollars(p.workflowUsd)}${p.subagentUsd >= 0.005 ? "" : " of it"} workflow agents` : "",
259
+ ].filter(Boolean).join(", ");
260
+ const parts = [
261
+ agents,
262
+ (p.estimatedUsd ?? 0) >= 0.005 ? `~${dollars(p.estimatedUsd)} priced as its model's family, an estimate` : "",
263
+ p.unpriced ? `${p.unpriced.toLocaleString("en-US")} request${p.unpriced === 1 ? "" : "s"} with no list price not counted` : "",
264
+ ].filter(Boolean);
265
+ const subs = parts.length ? ` (${parts.join("; ")})` : "";
207
266
  const head = `context-doctor: this session has cost ${dollars(p.usd)} so far${subs}`;
208
267
  if (p.tokens === undefined || p.readUsd === undefined)
209
268
  return `${head}.`;
@@ -234,7 +234,8 @@ export function setJsonPath(text, path, value) {
234
234
  const root = skipWs(text, text.startsWith("") ? 1 : 0);
235
235
  const edit = (t, objStart, keys) => {
236
236
  const o = scanObject(t, objStart);
237
- const idx = o.members.findIndex((m) => m.key === keys[0]);
237
+ // A key written twice: the last one, the one JSON.parse (and Claude Code) reads.
238
+ const idx = o.members.map((m) => m.key).lastIndexOf(keys[0]);
238
239
  const m = idx >= 0 ? o.members[idx] : undefined;
239
240
  if (keys.length > 1) {
240
241
  if (m) {
@@ -304,7 +305,7 @@ function scanArray(t, start) {
304
305
  function arrayAt(t, path) {
305
306
  let at = skipWs(t, t.startsWith("") ? 1 : 0);
306
307
  for (const k of path) {
307
- const m = t[at] === "{" ? scanObject(t, at).members.find((x) => x.key === k) : undefined;
308
+ const m = t[at] === "{" ? scanObject(t, at).members.filter((x) => x.key === k).pop() : undefined;
308
309
  if (!m)
309
310
  throw new SettingsError(`"${path.join(".")}" is not in the settings file. Nothing was changed.`);
310
311
  at = m.valueStart;