context-doctor 0.44.0 → 0.46.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 (62) hide show
  1. package/README.md +5 -2
  2. package/dist/budget.d.ts +14 -1
  3. package/dist/budget.js +50 -28
  4. package/dist/cache.js +5 -4
  5. package/dist/cachemisses.js +6 -4
  6. package/dist/cacheplan.js +2 -2
  7. package/dist/cachettl.js +8 -5
  8. package/dist/ci.js +18 -2
  9. package/dist/cli.js +27 -6
  10. package/dist/codexcompact.js +14 -7
  11. package/dist/coldresume.d.ts +6 -0
  12. package/dist/coldresume.js +20 -11
  13. package/dist/compactwindow.js +14 -8
  14. package/dist/doctor.js +26 -2
  15. package/dist/extract.d.ts +2 -2
  16. package/dist/extract.js +14 -3
  17. package/dist/fanout.js +1 -1
  18. package/dist/fix.js +14 -10
  19. package/dist/hook.js +6 -2
  20. package/dist/httpguard.d.ts +9 -1
  21. package/dist/httpguard.js +5 -4
  22. package/dist/lens.js +7 -7
  23. package/dist/limits.d.ts +14 -5
  24. package/dist/limits.js +26 -17
  25. package/dist/mcp.js +62 -62
  26. package/dist/mcpschema.js +5 -3
  27. package/dist/mod/api.d.ts +129 -0
  28. package/dist/mod/api.js +12 -0
  29. package/dist/mod/logic.d.ts +146 -0
  30. package/dist/mod/logic.js +222 -0
  31. package/dist/mod/register.d.ts +58 -0
  32. package/dist/mod/register.js +237 -0
  33. package/dist/modelids.d.ts +23 -0
  34. package/dist/modelids.js +49 -0
  35. package/dist/modmeasure.d.ts +121 -0
  36. package/dist/modmeasure.js +298 -0
  37. package/dist/orgrates.d.ts +75 -0
  38. package/dist/orgrates.js +165 -0
  39. package/dist/overhead.js +11 -8
  40. package/dist/pack.js +95 -22
  41. package/dist/pricing.d.ts +123 -6
  42. package/dist/pricing.js +236 -62
  43. package/dist/proxy.d.ts +12 -1
  44. package/dist/proxy.js +13 -1
  45. package/dist/prune.js +55 -3
  46. package/dist/savings.js +19 -10
  47. package/dist/scan.d.ts +7 -1
  48. package/dist/scan.js +19 -1
  49. package/dist/sessionprice.d.ts +25 -2
  50. package/dist/sessionprice.js +60 -20
  51. package/dist/spend.d.ts +62 -10
  52. package/dist/spend.js +255 -29
  53. package/dist/statusline.d.ts +10 -2
  54. package/dist/statusline.js +18 -9
  55. package/dist/subagentmodel.d.ts +2 -2
  56. package/dist/subagentmodel.js +31 -24
  57. package/dist/subagentpay.d.ts +7 -1
  58. package/dist/subagentpay.js +51 -25
  59. package/dist/subagents.js +15 -10
  60. package/dist/tasks.js +9 -6
  61. package/dist/tooloutput.js +14 -5
  62. package/package.json +1 -1
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,7 +44,7 @@ export interface SessionPrice {
43
44
  /** The threshold just passed. */
44
45
  threshold: number;
45
46
  usd: number;
46
- /** Subagents' part of `usd` (the Agent tool's). */
47
+ /** Subagents' part of `usd`: the Agent tool's, or the agents a Codex thread spawned. */
47
48
  subagentUsd: number;
48
49
  /** Workflow agents' part of `usd`. */
49
50
  workflowUsd?: number;
@@ -73,5 +74,27 @@ export interface SessionPriceInput {
73
74
  * Claims the threshold: a second call for the same one gets undefined.
74
75
  */
75
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;
76
99
  /** The line for the user (the hook's systemMessage). */
77
100
  export declare function renderSessionPrice(p: SessionPrice): 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
@@ -37,12 +38,12 @@ 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
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,6 +69,8 @@ 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
+ /** A Codex thread's candidate rollouts and what their first lines named (codexSpawnedRollouts). */
73
+ const headsFile = (b) => `${b}.spawn-heads.json`;
71
74
  /** The price file's format: 2 counts only the session's own rows and may leave a finished subagent's `r` out. */
72
75
  const LEDGER_VERSION = 2;
73
76
  /** A subagent transcript not written for this long is done: its entry keeps no recent replies. */
@@ -127,6 +130,28 @@ export function sessionPriceDue(input, now = Date.now(), env = process.env) {
127
130
  // Everything said: one stat from now on.
128
131
  if (said(claimFile(b, thresholds[thresholds.length - 1]), now))
129
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);
130
155
  const app = appOf(input.transcript, input.event);
131
156
  // Each file and whose it is: the main conversation, a subagent, a workflow agent.
132
157
  const files = [[input.transcript, "main"]];
@@ -134,6 +159,24 @@ export function sessionPriceDue(input, now = Date.now(), env = process.env) {
134
159
  if (app === "claude")
135
160
  for (const f of subagentFiles(input.transcript))
136
161
  files.push([f.file, f.run ? "workflow" : "sub"]);
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).
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))
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
+ }
137
180
  let saved = {};
138
181
  try {
139
182
  const raw = JSON.parse(readFileSync(ledgerFile(b), "utf8"));
@@ -197,18 +240,12 @@ export function sessionPriceDue(input, now = Date.now(), env = process.env) {
197
240
  }
198
241
  catch { /* read again next time */ }
199
242
  };
200
- const passed = thresholds.filter((t) => usd >= t);
201
- const top = passed[passed.length - 1];
202
- if (top === undefined || said(claimFile(b, top), now) || !claim(claimFile(b, top))) {
203
- if (read >= SAVE_BYTES)
204
- save();
205
- return undefined;
206
- }
207
- // Passed two at once (a first look at a long session): said once, for the higher.
208
- for (const t of passed.slice(0, -1))
209
- claim(claimFile(b, t));
210
- save();
211
- 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();
212
249
  }
213
250
  /** The main conversation's context now, and what the next message pays for it. */
214
251
  function perMessage(app, input, now) {
@@ -218,18 +255,21 @@ function perMessage(app, input, now) {
218
255
  const items = app === "codex" ? codexFileSpend(input.transcript, 0) : geminiFileSpend(input.transcript, 0);
219
256
  const last = items[items.length - 1];
220
257
  const model = last?.model ?? input.model;
221
- const p = pricingFor(model);
222
- if (!last || !p)
258
+ const tokens = last ? last.input + last.read + last.write : 0;
259
+ // At the rate the next request bills: its prompt's tier (a long prompt's on OpenAI and Gemini Pro).
260
+ const card = rateCard(model, undefined, now);
261
+ if (!last || !card)
223
262
  return {};
224
- const tokens = last.input + last.read + last.write;
225
- return { tokens, model, readUsd: (tokens * p.cacheReadPerM) / 1e6 };
263
+ return { tokens, model, readUsd: (tokens * ratesAt(card, tokens).cacheReadPerM) / 1e6 };
226
264
  }
227
265
  // Undefined right after a compaction: the new size is not known yet.
228
266
  const live = tailUsage(input.transcript);
229
267
  if (!live)
230
268
  return {};
231
269
  const model = live.model ?? input.model;
232
- const p = pricingFor(model);
270
+ // As the next request bills: fast mode and US-only as the last one recorded, the tier of its prompt.
271
+ const card = rateCard(model, live.billing, now);
272
+ const p = card && ratesAt(card, live.tokens);
233
273
  // Claude Code compacts this very prompt itself: the figure is about to be wrong.
234
274
  if (!p || live.tokens >= (autoCompactsAt(model) ?? Infinity))
235
275
  return {};
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
  *
@@ -21,7 +21,10 @@
21
21
  * and an upper bound. Replies on Auto ("default") have no list price and
22
22
  * are counted, not priced.
23
23
  *
24
- * Priced at pricing.ts's list prices (usageCost), as every report here is.
24
+ * Priced at pricing.ts's list prices with what each request recorded that
25
+ * changes its bill (requestCost: fast mode, US-only inference, a long
26
+ * prompt's tier, web searches, a price past its end date), as every report
27
+ * here is; the report says what the modifiers added.
25
28
  * Claude Code, Codex and Gemini CLI are read through the shared scan
26
29
  * (scan.ts), so a second run reads only what was appended since; Cursor's
27
30
  * replies are kept per chat until the chat changes.
@@ -31,6 +34,7 @@
31
34
  * sessions with 10+ requests. `spend` counts every request, its output and
32
35
  * subagents too; on the requests both count, the dollars are the same.
33
36
  */
37
+ import { type Modifiers } from "./pricing.js";
34
38
  import { type Extractor } from "./scan.js";
35
39
  export type Tool = "claude" | "codex" | "gemini" | "cursor";
36
40
  export declare const TOOLS: Tool[];
@@ -54,9 +58,13 @@ export interface SpendItem {
54
58
  readUsd: number;
55
59
  outputUsd: number;
56
60
  priced: boolean;
57
- /** Priced by its family's row, not one of its own (a new release, an id the table does not list): an estimate. */
61
+ /** Priced by its family's row, not one of its own (a new release, an id the table does not list), or past `changedOn`: an estimate. */
58
62
  estimated?: boolean;
59
- /** Claude Code: run by a subagent (the Agent tool's). */
63
+ /** Its model's price in the table changed on this day ("YYYY-MM-DD"), before the request: priced at what the page said would follow, an estimate. */
64
+ changedOn?: string;
65
+ /** What fast mode, US-only, a long prompt's tier and web searches added to its list price, inside `usd`; absent when nothing. */
66
+ modifiers?: Modifiers;
67
+ /** Run by a subagent: Claude Code's (the Agent tool's), or an agent a Codex thread spawned (its `session` is then the thread's). */
60
68
  subagent?: boolean;
61
69
  /** Claude Code: run by a workflow agent: its run, "<session>/<run>". */
62
70
  workflow?: string;
@@ -73,22 +81,54 @@ export interface SpendItem {
73
81
  export declare function projectFromDir(dir: string): string;
74
82
  /** A project's name as `savings` shows it: the folder's path with "-" for separators, less the home folder. */
75
83
  export declare function projectName(folder: string): string;
84
+ /** Whether a request's modifiers added anything (kept on an item only then). */
85
+ export declare const anyModifier: (m: Modifiers | undefined) => m is Modifiers;
76
86
  /**
77
87
  * Claude Code's requests between `since` and `until`, main threads and
78
88
  * subagents, over `tops` (default: every transcript written since `since`).
79
89
  */
80
90
  export declare function claudeSpend(since: number, until?: number, tops?: string[], onProgress?: (done: number, total: number) => void): SpendItem[];
81
91
  /**
82
- * What `spend` takes from a Codex rollout: its folder, each model change,
83
- * and every token_count event's last request and running total.
92
+ * What `spend` takes from a Codex rollout: its folder, its own id and the
93
+ * thread that spawned it (the first session_meta), each model change, and
94
+ * every token_count event's last request and running total.
84
95
  */
85
- export declare const CODEX_SPEND_ROWS: Extractor<null>;
96
+ export declare const CODEX_SPEND_ROWS: Extractor<{
97
+ m?: 1;
98
+ }>;
86
99
  /** The requests of one Codex rollout since `since`. Throws when it cannot be read. */
87
100
  export declare function codexFileSpend(file: string, since: number, until?: number): SpendItem[];
88
101
  /** Codex rollouts written since `since`: the live ones and the archived. */
89
102
  export declare function codexFiles(since: number, home?: string): string[];
90
- /** Every Codex request in the window, once: a forked rollout's copy of its parent's (codexEventKey) counts at the earliest time met. */
103
+ /** A Codex rollout's own thread id and the thread that spawned it, when one did (spawnedBy). Throws when it cannot be read. */
104
+ export declare function codexRolloutMeta(file: string): {
105
+ id?: string;
106
+ parent?: string;
107
+ };
108
+ /**
109
+ * Every Codex request in the window, once: a forked rollout's copy of its
110
+ * parent's (codexEventKey) counts at the earliest time met. A spawned
111
+ * agent's requests are its session's (the thread at the top of its
112
+ * parents, when its rollout is among the window's), marked `subagent`: they
113
+ * bill to the same work, as a Claude Code subagent's do.
114
+ */
91
115
  export declare function codexSpend(since: number, until?: number, home?: string): SpendItem[];
116
+ /** What rollouts' first lines named, by file name: [its thread id, the thread that spawned it]. */
117
+ export interface SpawnHeads {
118
+ heads: Record<string, [id: string, parent?: string]>;
119
+ /** Set when `heads` gained or lost a rollout, so the caller saves it. */
120
+ changed?: boolean;
121
+ }
122
+ /**
123
+ * The rollouts of the agents a Codex thread spawned (and theirs), for the
124
+ * session price: those written since the thread began in its own folder,
125
+ * the day folders from then to `now` (by local and UTC date) and the
126
+ * archive. Only each candidate's first line is read, and with `known` only
127
+ * once: a rollout's first line (its own session_meta) never changes, so
128
+ * what it named is kept there by file name, and a prompt reads only the
129
+ * rollouts written since the last (`known.changed` says when to save it).
130
+ */
131
+ export declare function codexSpawnedRollouts(parent: string, now?: number, home?: string, known?: SpawnHeads): string[];
92
132
  /**
93
133
  * What `spend` takes from a Gemini CLI chat (JSONL): each `gemini` message's
94
134
  * id, time, model and token counts. A message without a time of its own
@@ -113,7 +153,7 @@ export interface ToolSpend {
113
153
  write: number;
114
154
  output: number;
115
155
  };
116
- /** Claude Code: what its subagents cost, inside `usd`. */
156
+ /** What its subagents cost, inside `usd`: Claude Code's (the Agent tool's), Codex's spawned agents. */
117
157
  subagentUsd?: number;
118
158
  /** Claude Code: what its workflow agents cost, inside `usd`, and in how many workflow runs. */
119
159
  workflowUsd?: number;
@@ -153,13 +193,23 @@ export interface SpendReport {
153
193
  daily: Array<SpendRow & {
154
194
  day: string;
155
195
  }>;
156
- /** The bill by what it paid for. */
196
+ /** The bill by what it paid for; web searches (Claude's, per use) only when there were any. */
157
197
  parts: {
158
198
  inputUsd: number;
159
199
  writeUsd: number;
160
200
  readUsd: number;
161
201
  outputUsd: number;
202
+ webSearchUsd?: number;
162
203
  };
204
+ /** What billing modifiers added to the list prices, inside `usd` (fast mode, US-only, long-prompt tiers, web searches); absent when nothing. */
205
+ modifiers?: Modifiers;
206
+ /** Models whose price in the table changed on a day before some of their requests: those are priced at what the page said would follow, an estimate. */
207
+ priceChanged?: Array<{
208
+ model: string;
209
+ on: string;
210
+ requests: number;
211
+ usd: number;
212
+ }>;
163
213
  sessions: Array<{
164
214
  tool: Tool;
165
215
  project: string;
@@ -196,6 +246,8 @@ export declare const MAX_SPEND_DAYS = 3650;
196
246
  /** The last `days` days, every tool on this machine. A tool with nothing on disk is just absent. */
197
247
  export declare function spendReport(days?: number, opts?: SpendOptions): SpendReport;
198
248
  export declare const usd: (n: number) => string;
249
+ /** "fast mode +$4.10, US-only +$0.93, web searches $0.12 (12), long-prompt tier +$0.40": what each billing modifier added, the ones that added anything. */
250
+ export declare function modifiersText(m: Modifiers): string;
199
251
  /** The full report, kept within 80 columns. `top`: rows per list. */
200
252
  export declare function renderSpend(r: SpendReport, top?: number): string;
201
253
  /**