context-doctor 0.44.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.
package/README.md CHANGED
@@ -28,7 +28,7 @@ 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.44.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
 
@@ -181,6 +181,7 @@ 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)).
184
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)).
185
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).
186
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)).
package/dist/budget.d.ts CHANGED
@@ -69,7 +69,10 @@ export declare function periodEnd(period: Period, now?: number): number;
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
71
  * model): in `d` at $0, and said so rather than silently left out. `y`
72
- * lists those priced only by their model's family (an estimate), the same way.
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.
73
76
  */
74
77
  export interface FileEntry {
75
78
  t: Tool;
@@ -83,6 +86,7 @@ export interface FileEntry {
83
86
  r?: Array<[string, number, number, number]>;
84
87
  x?: Array<[number, string]>;
85
88
  y?: Array<[number, string]>;
89
+ z?: Array<[number, string, string]>;
86
90
  }
87
91
  /** A ledger entry this version can use: a damaged one threw on every prompt until its transcript changed. */
88
92
  export declare function wellFormed(e: FileEntry | undefined): e is FileEntry;
@@ -118,6 +122,12 @@ export interface PeriodSpend {
118
122
  usd: number;
119
123
  models: string[];
120
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
+ };
121
131
  }
122
132
  /**
123
133
  * What the period holding `now` has cost so far, across Claude Code, Codex
package/dist/budget.js CHANGED
@@ -32,7 +32,7 @@ import { claudeCodePresent, claudeDir } from "./claudedir.js";
32
32
  import { claudeFileUsage, codexSessionsRoot, rolloutFiles, SUBAGENT_LOOKBACK_MS, USAGE_ROWS } from "./limits.js";
33
33
  import { subagentFiles } from "./subagents.js";
34
34
  import { codexFileSpend, codexFiles, geminiFileSpend, geminiFiles, TOOL_NAME } from "./spend.js";
35
- import { hasKnownPrice, isUnbilledModel, pricingFor, usageCost } from "./pricing.js";
35
+ import { isUnbilledModel, priceChangedText, requestCost } from "./pricing.js";
36
36
  import { anchorOf, rowsOf } from "./scan.js";
37
37
  import { realModel } from "./tokens.js";
38
38
  /** Beside the hook state and the ledger: ~/.claude/.context-doctor-budget.json. */
@@ -303,26 +303,29 @@ function lineStart(fd, size) {
303
303
  * shared scan, so only what it has not cached), as the ledger keeps them.
304
304
  */
305
305
  function readFile(tool, file, since, size) {
306
- const k = [], d = [], x = [], y = [];
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 } : {}) });
307
316
  if (tool !== "claude") {
308
317
  // A Codex request's key (a forked rollout repeats its parent's) kept short: 12 hex digits of its hash.
309
318
  for (const r of tool === "codex" ? codexFileSpend(file, since) : geminiFileSpend(file, since)) {
310
- if (!r.priced)
311
- x.push([k.length, r.model ?? "unknown"]);
312
- else if (r.estimated)
313
- y.push([k.length, r.model ?? "unknown"]);
319
+ flag(k.length, r);
314
320
  k.push(r.key ? createHash("sha1").update(r.key).digest("hex").slice(0, 12) : "");
315
321
  d.push(r.usd);
316
322
  }
317
- return { k, d, ...(x.length ? { x } : {}), ...(y.length ? { y } : {}) };
323
+ return { k, d, ...flags() };
318
324
  }
319
325
  const reqs = claudeFileUsage(file, since);
320
326
  const at = new Map();
321
327
  reqs.forEach((q, i) => {
322
- if (!pricingFor(q.model))
323
- x.push([i, q.model ?? "unknown"]);
324
- else if (!hasKnownPrice(q.model))
325
- y.push([i, q.model ?? "unknown"]);
328
+ flag(i, { ...q, priced: q.rates !== undefined });
326
329
  k.push(keyOf(q.uuid));
327
330
  d.push(q.usd);
328
331
  if (q.id)
@@ -344,7 +347,7 @@ function readFile(tool, file, since, size) {
344
347
  continue;
345
348
  }
346
349
  const i = at.get(m.id) ?? -1;
347
- 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]);
348
351
  if (last.size > RECENT_REPLIES)
349
352
  last.delete(last.keys().next().value);
350
353
  }
@@ -352,7 +355,7 @@ function readFile(tool, file, since, size) {
352
355
  const fd = openSync(file, "r");
353
356
  try {
354
357
  const o = lineStart(fd, size);
355
- return { k, d, o, a: anchorOf(fd, o), r: r.slice(-RECENT_REPLIES), ...(x.length ? { x } : {}), ...(y.length ? { y } : {}) };
358
+ return { k, d, o, a: anchorOf(fd, o), r: r.slice(-RECENT_REPLIES), ...flags() };
356
359
  }
357
360
  finally {
358
361
  closeSync(fd);
@@ -441,22 +444,25 @@ function countLines(e, recent, text, since, own) {
441
444
  }
442
445
  const ts = Date.parse(String(row.timestamp ?? ""));
443
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);
444
- const price = pricingFor(realModel(m.model));
447
+ const model = realModel(m.model);
448
+ const c = requestCost(model, u, ts);
445
449
  let index = -1;
446
450
  // A reply on <synthetic> was made by Claude Code itself, never billed: not a request at all.
447
451
  // A row of another session (`own`): a copy of its history, its spend, not this session's.
448
452
  const copied = own !== undefined && typeof row.sessionId === "string" && row.sessionId !== own;
449
453
  if (Number.isFinite(ts) && ts >= since && tokens > 0 && !isUnbilledModel(m.model) && !copied) {
450
454
  index = e.k.length;
451
- if (!price)
452
- (e.x ??= []).push([index, realModel(m.model) ?? "unknown"]);
453
- else if (!hasKnownPrice(realModel(m.model)))
454
- (e.y ??= []).push([index, realModel(m.model) ?? "unknown"]);
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"]);
455
461
  e.k.push(keyOf(typeof row.uuid === "string" ? row.uuid : undefined));
456
- e.d.push(price ? usageCost(u, price).totalUsd : 0);
462
+ e.d.push(c ? c.totalUsd : 0);
457
463
  }
458
464
  if (typeof m.id === "string")
459
- recent.push([m.id, index, out, price?.outputPerM ?? 0]);
465
+ recent.push([m.id, index, out, c?.rates.outputPerM ?? 0]);
460
466
  }
461
467
  }
462
468
  }
@@ -464,7 +470,8 @@ function countLines(e, recent, text, since, own) {
464
470
  export function wellFormed(e) {
465
471
  return Boolean(e) && typeof e === "object" && Array.isArray(e.k) && Array.isArray(e.d) && e.k.length === e.d.length &&
466
472
  e.k.every((x) => typeof x === "string") && e.d.every((x) => typeof x === "number" && Number.isFinite(x)) &&
467
- (e.a === undefined || typeof e.a === "string") && (e.x === undefined || (Array.isArray(e.x) && e.x.every((y) => Array.isArray(y) && typeof y[0] === "number"))) && (e.y === undefined || (Array.isArray(e.y) && e.y.every((y) => Array.isArray(y) && typeof y[0] === "number"))) && (e.r === undefined || (Array.isArray(e.r) && e.r.every((x) => Array.isArray(x) && x.length === 4)));
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")));
468
475
  }
469
476
  /**
470
477
  * One transcript's entry brought up to date: kept when the file is as last
@@ -553,9 +560,10 @@ export function periodSpend(period, now = Date.now(), home = homedir(), warnAt)
553
560
  let unpriced = 0;
554
561
  const models = new Set();
555
562
  const estimated = { requests: 0, usd: 0, models: new Set() };
563
+ const changedPrice = { requests: 0, usd: 0, models: new Map() };
556
564
  for (const file of Object.keys(kept).sort()) {
557
565
  const e = kept[file];
558
- const x = new Map(e.x ?? []), y = new Map(e.y ?? []);
566
+ const x = new Map(e.x ?? []), y = new Map(e.y ?? []), z = new Map((e.z ?? []).map(([i, m, on]) => [i, [m, on]]));
559
567
  e.k.forEach((key, i) => {
560
568
  if (key) {
561
569
  if (seen.has(key))
@@ -573,6 +581,12 @@ export function periodSpend(period, now = Date.now(), home = homedir(), warnAt)
573
581
  estimated.usd += e.d[i];
574
582
  estimated.models.add(y.get(i));
575
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
+ }
576
590
  });
577
591
  }
578
592
  const level = warnAt ? warnAt(usd, st.warned) : 0;
@@ -594,7 +608,7 @@ export function periodSpend(period, now = Date.now(), home = homedir(), warnAt)
594
608
  }
595
609
  if (changed)
596
610
  saveState({ ...st, files: kept, usd, byTool });
597
- return { start, end: periodEnd(period, now), usd, byTool, ...(unpriced ? { unpriced: { requests: unpriced, models: [...models] } } : {}), ...(estimated.requests ? { estimated: { requests: estimated.requests, usd: estimated.usd, models: [...estimated.models] } } : {}), ...(warn ? { warn } : {}), ...(unpricedNew ? { unpricedNew } : {}) };
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 } : {}) };
598
612
  }
599
613
  // ---------------------------------------------------------------------------
600
614
  // What the hook, the status line and `budget` say
@@ -678,6 +692,8 @@ export function renderBudgetStatus(b, s, hookInstalled) {
678
692
  const one = s.estimated.models.length === 1;
679
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.`);
680
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)}).`);
681
697
  lines.push(hookInstalled
682
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).`
683
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 = () => {
package/dist/cachettl.js CHANGED
@@ -38,7 +38,7 @@ 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";
@@ -105,14 +105,16 @@ export function replayTtlTranscript(path, acc, since, until = Infinity, sidechai
105
105
  // wrote nothing keeps the lifetime of the last one that did.
106
106
  if (W > 0)
107
107
  lastTtl = split.oneHour > split.fiveMinute ? HOUR : FIVE_MIN;
108
- 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;
109
111
  if (at >= since && at < until && seen === "new") {
110
112
  counted++;
111
113
  acc.requests++;
112
- if (!p)
114
+ if (!c || !p)
113
115
  acc.unpriced++;
114
116
  else {
115
- acc.billedUsd += usageCost(u, p).promptUsd;
117
+ acc.billedUsd += c.promptUsd;
116
118
  acc.writes += W;
117
119
  acc.writes1h += split.oneHour;
118
120
  const inp = p.inputPerM / 1e6;
package/dist/ci.js CHANGED
@@ -128,6 +128,22 @@ export function ciReport(opts = {}) {
128
128
  }
129
129
  return { base: opts.base, files, baseTotal, headTotal, breaches };
130
130
  }
131
+ /**
132
+ * A path as inline code that stays code: a pull request names its files, and
133
+ * a name may hold a backtick, a pipe or a line break (all allowed in a
134
+ * repository), which closed the code span in the bot's comment and made the
135
+ * rest of the name markdown of the PR author's choosing (a link, an
136
+ * @mention, a heading). Line breaks are written as \n; in a table cell a
137
+ * pipe is escaped.
138
+ */
139
+ function codePath(p, inTable = false) {
140
+ let s = p.replace(/[\r\n\t\u2028\u2029]/g, (c) => ({ "\r": "\\r", "\n": "\\n", "\t": "\\t" })[c] ?? `\\u${c.charCodeAt(0).toString(16)}`);
141
+ if (inTable)
142
+ s = s.replace(/\|/g, "\\|");
143
+ const fence = "`".repeat(Math.max(0, ...[...s.matchAll(/`+/g)].map((m) => m[0].length)) + 1);
144
+ const pad = s.startsWith("`") || s.endsWith("`") ? " " : "";
145
+ return `${fence}${pad}${s}${pad}${fence}`;
146
+ }
131
147
  const signed = (n) => (n > 0 ? `+${formatTokens(n)}` : n < 0 ? `−${formatTokens(-n)}` : "0");
132
148
  /** Markdown for a PR comment or a job summary. */
133
149
  export function renderCiMarkdown(r, opts = {}) {
@@ -152,7 +168,7 @@ export function renderCiMarkdown(r, opts = {}) {
152
168
  if (changed.length) {
153
169
  out.push(r.base ? "| File | Agent | Base | This PR | Change |" : "| File | Agent | Tokens |", r.base ? "|---|---|---:|---:|---:|" : "|---|---|---:|");
154
170
  for (const f of changed) {
155
- const name = `\`${f.path}\`${f.imported ? " (imported)" : ""}`;
171
+ const name = `${codePath(f.path, true)}${f.imported ? " (imported)" : ""}`;
156
172
  out.push(r.base ? `| ${name} | ${f.agent} | ${f.base ? "~" + formatTokens(f.base) : "—"} | ${f.head ? "~" + formatTokens(f.head) : "—"} | ${signed(f.head - f.base)} |` : `| ${name} | ${f.agent} | ~${formatTokens(f.head)} |`);
157
173
  }
158
174
  }
@@ -163,7 +179,7 @@ export function renderCiMarkdown(r, opts = {}) {
163
179
  out.push("", ...r.breaches.map((b) => `**Over budget:** ${b}.`));
164
180
  const big = r.files.filter((f) => f.head >= 2000);
165
181
  if (big.length)
166
- out.push("", `Large files: ${big.map((f) => `\`${f.path}\``).join(", ")}. \`npx context-doctor overhead split <file>\` moves reference sections out, word for word.`);
182
+ out.push("", `Large files: ${big.map((f) => codePath(f.path)).join(", ")}. \`npx context-doctor overhead split <file>\` moves reference sections out, word for word.`);
167
183
  return out.join("\n");
168
184
  }
169
185
  /** Plain-text rendering for a terminal. */
package/dist/cli.js CHANGED
@@ -302,7 +302,9 @@ Options:
302
302
  --chunk-tokens <n> (pack) Largest chunk, in tokens (default 400)
303
303
  --ids <a#2,b#5> (pack) Return these chunks by id
304
304
  --include-secrets (pack) Also pack .env, .npmrc, private keys and other credential files,
305
- and paths under ~/.ssh, ~/.aws and similar (skipped by default)
305
+ paths under ~/.ssh, ~/.aws and similar, and the agents' MCP and
306
+ settings files in your home folder, whose servers' env holds API keys
307
+ (skipped by default; a project's own .mcp.json is read)
306
308
  --min-tokens <n> (overhead split) Smallest section to move, in tokens (default 400)
307
309
  --requests-per-day <n> (ci --markdown) Price the change at this many requests a day
308
310
  --check <cmd> (experiment) Command whose exit code is the pass/fail for each arm
@@ -319,6 +321,9 @@ Options:
319
321
  --token <secret> (proxy) Require /t/<secret>/ in every request path; needed before
320
322
  putting the proxy on a public URL (Cursor BYO-key, tunnels).
321
323
  Also read from CONTEXT_DOCTOR_PROXY_TOKEN
324
+ --allowed-hosts <names> (proxy) Host names it answers to besides localhost, an IP address and
325
+ --host (a container's service name); a web page that rebinds its own
326
+ name to this address is refused. Not checked with --token
322
327
  --config <file> (proxy) Per-route overrides: {"routes":[{"modelPrefix":"gpt","strategies":[...],
323
328
  "keepRecent":n,"maxToolResultTokens":n}]} — first prefix match wins
324
329
  --upstream-anthropic <url> (proxy) Override Anthropic upstream (testing)
@@ -561,8 +566,8 @@ const FLAGS = [
561
566
  // Read by the MCP server itself: `mcp --http [--port n] [--host h]`.
562
567
  { names: ["--http"], set: () => { } },
563
568
  { names: ["--store-handoffs"], set: () => { } },
564
- { names: ["--allowed-hosts"], value: "text", set: () => { } },
565
- { names: ["--allowed-origins"], value: "text", set: () => { } },
569
+ { names: ["--allowed-hosts"], value: "text", set: (a, v) => { a.allowedHosts = v; } },
570
+ { names: ["--allowed-origins"], value: "text", set: (a, v) => { a.allowedOrigins = v; } },
566
571
  ];
567
572
  const FLAG_BY_NAME = new Map(FLAGS.flatMap((f) => f.names.map((n) => [n, f])));
568
573
  const FLAG_NAMES = [...FLAG_BY_NAME.keys(), "--help", "--version"];
@@ -1226,6 +1231,8 @@ async function main() {
1226
1231
  port: args.port,
1227
1232
  host: args.host,
1228
1233
  token: args.token ?? process.env.CONTEXT_DOCTOR_PROXY_TOKEN,
1234
+ allowedHosts: args.allowedHosts,
1235
+ allowedOrigins: args.allowedOrigins,
1229
1236
  autopilot: args.autopilot,
1230
1237
  autopilotStatePath: args.autopilotState,
1231
1238
  autopilotPauseFile: args.autopilotPauseFile,
@@ -34,7 +34,7 @@ import { homedir } from "node:os";
34
34
  import { basename, dirname, join, resolve } from "node:path";
35
35
  import { codexDir } from "./codexdir.js";
36
36
  import { codexEventKey, codexSessionsRoot, rolloutFiles } from "./limits.js";
37
- import { openAIUsage, pricingFor, usageCost } from "./pricing.js";
37
+ import { openAIUsage, rateCard, ratesAt, requestCost } from "./pricing.js";
38
38
  import { pick, rowsOf } from "./scan.js";
39
39
  import { tilde } from "./claudedir.js";
40
40
  /** The config.toml key the lever writes. */
@@ -128,19 +128,21 @@ function readSteps(file, seen) {
128
128
  if (!Number.isFinite(at))
129
129
  continue;
130
130
  const u = openAIUsage(r.u);
131
- const price = pricingFor(model);
131
+ const prompt = num(u.input_tokens) + num(u.cache_read_input_tokens) + num(u.cache_creation_input_tokens);
132
+ const card = rateCard(model, u, at);
133
+ const price = card && ratesAt(card, prompt);
132
134
  const copy = !!r.key && seen.has(r.key);
133
135
  if (r.key)
134
136
  seen.add(r.key);
135
137
  const window = num(r.win) ? num(r.win) / RECORDED_SHARE : DEFAULT_WINDOW;
136
138
  steps.push({
137
- k: "r", at, copy,
138
- prompt: num(u.input_tokens) + num(u.cache_read_input_tokens) + num(u.cache_creation_input_tokens),
139
+ k: "r", at, copy, prompt,
139
140
  cached: num(u.cache_read_input_tokens),
140
141
  out: num(u.output_tokens),
141
142
  inPerM: price?.inputPerM ?? 0, readPerM: price?.cacheReadPerM ?? 0, outPerM: price?.outputPerM ?? 0,
142
- billedUsd: price ? usageCost(u, price).promptUsd : 0,
143
+ billedUsd: requestCost(model, u, at)?.promptUsd ?? 0,
143
144
  trigger: DEFAULT_SHARE * window,
145
+ ...(card ? { card } : {}),
144
146
  });
145
147
  }
146
148
  return steps;
@@ -178,11 +180,15 @@ function replay(steps, limit, since, until, after, scope = "total") {
178
180
  fresh = false;
179
181
  }
180
182
  let cost = s.billedUsd;
183
+ // A smaller prompt can fall under a long-context tier (OpenAI's 272k): all of it then bills at the lower rates.
184
+ const low = s.card && ctx < s.prompt ? ratesAt(s.card, ctx) : undefined;
181
185
  if (fresh)
182
- cost = (ctx * s.inPerM) / 1e6;
186
+ cost = (ctx * (low ? low.inputPerM : s.inPerM)) / 1e6;
183
187
  else if (removed > 0) {
184
188
  const fromCache = Math.min(removed, s.cached);
185
189
  cost = Math.max(0, s.billedUsd - (fromCache * s.readPerM + (removed - fromCache) * s.inPerM) / 1e6);
190
+ if (low && low.inputPerM < s.inPerM)
191
+ cost *= low.inputPerM / s.inPerM;
186
192
  }
187
193
  fresh = false;
188
194
  prefill ??= ctx;
@@ -195,8 +201,9 @@ function replay(steps, limit, since, until, after, scope = "total") {
195
201
  : ctx + s.out >= Math.min(limit, s.trigger) && limit < s.trigger;
196
202
  if (reached) {
197
203
  // Compacted after this turn: one request reading the context, a summary written; the next starts from `after`.
204
+ const at = low ?? { cacheReadPerM: s.readPerM, outputPerM: s.outPerM };
198
205
  if (counted) {
199
- sim += (ctx * s.readPerM + SUMMARY_OUTPUT * s.outPerM) / 1e6;
206
+ sim += (ctx * at.cacheReadPerM + SUMMARY_OUTPUT * at.outputPerM) / 1e6;
200
207
  extra++;
201
208
  }
202
209
  removed = s.prompt + s.out - after;
@@ -30,7 +30,7 @@ import { homedir } from "node:os";
30
30
  import { join } from "node:path";
31
31
  import { forEachLine, replyCounter, textOf } from "./session.js";
32
32
  import { pick, rowsOf, slimUsage } from "./scan.js";
33
- import { cacheWriteSplit, pricingFor, formatUsd, writeMultiplier } from "./pricing.js";
33
+ import { cacheWriteSplit, formatUsd, rateCard, ratesAt, writeMultiplier } from "./pricing.js";
34
34
  import { contextWindowFor, formatTokens, isCodeLike, realModel } from "./tokens.js";
35
35
  import { claudeDir } from "./claudedir.js";
36
36
  /**
@@ -68,7 +68,7 @@ export function isIdleCompactNotice(e) {
68
68
  * reader meets it as a repeat of that reply and skips it.
69
69
  */
70
70
  export const REQUEST_ROWS = {
71
- id: "requests.1",
71
+ id: "requests.2",
72
72
  init: () => ({ ids: {}, user: false }),
73
73
  line(raw, row, out, st) {
74
74
  let e;
@@ -260,7 +260,9 @@ export function detectColdResume(path, now = Date.now(), idleMs, minTokens = COL
260
260
  if (idle < gate || tokens < minTokens)
261
261
  return undefined;
262
262
  const model = realModel(e.message?.model);
263
- const p = pricingFor(model);
263
+ // As the resuming request bills: fast mode and US-only as the last one recorded, its prompt's tier.
264
+ const card = rateCard(model, u, now);
265
+ const p = card && ratesAt(card, tokens);
264
266
  // The rebuild is written at the TTL this session writes at: Claude
265
267
  // Code's main thread has mostly written the 1-hour cache (2x input,
266
268
  // 97% of the author's main-thread writes), which a flat 1.25x
@@ -394,7 +396,7 @@ export function coldResumeEvents(path, idleMs, minTokens = COLD_MIN_TOKENS, runR
394
396
  writes5m += w.fiveMinute;
395
397
  writes1h += w.oneHour;
396
398
  ttl = writtenTtlMs(u) ?? ttl;
397
- reqs.push({ at, total, price: pricingFor(model), copy: seen === "copy", ttl });
399
+ reqs.push({ at, total, card: rateCard(model, u, at), copy: seen === "copy", ttl });
398
400
  });
399
401
  const mix = writeMultiplier(writes5m, writes1h);
400
402
  const real = reqs.filter((r) => r !== "compact");
@@ -409,8 +411,9 @@ export function coldResumeEvents(path, idleMs, minTokens = COLD_MIN_TOKENS, runR
409
411
  const gate = (r) => idleMs ?? r.ttl + COLD_MARGIN_MS;
410
412
  if (b.at - a.at <= gate(a) || b.total < minTokens)
411
413
  continue;
412
- if (b.copy || !b.price)
414
+ if (b.copy || !b.card)
413
415
  continue;
416
+ const price = ratesAt(b.card, b.total);
414
417
  const removed = Math.max(0, b.total - AFTER_COMPACT_TOKENS);
415
418
  let saved = 0, n = 0, prev = b;
416
419
  for (const c of reqs.slice(i + 1)) {
@@ -418,14 +421,19 @@ export function coldResumeEvents(path, idleMs, minTokens = COLD_MIN_TOKENS, runR
418
421
  break;
419
422
  if (c.at - prev.at > gate(prev) && c.total >= minTokens)
420
423
  break;
421
- const p = c.price ?? b.price;
422
- saved += removed * (c.at - prev.at > prev.ttl ? mix * p.inputPerM : p.cacheReadPerM);
424
+ const card = c.card ?? b.card;
425
+ const cold = c.at - prev.at > prev.ttl;
426
+ const per = (p) => (cold ? mix * p.inputPerM : p.cacheReadPerM);
427
+ // A long-prompt tier: the smaller prompt may bill all of it at the lower rates.
428
+ const after = Math.max(0, c.total - removed);
429
+ const hi = ratesAt(card, c.total), lo = ratesAt(card, after);
430
+ saved += hi === lo ? removed * per(hi) : c.total * per(hi) - after * per(lo);
423
431
  prev = c;
424
432
  n++;
425
433
  }
426
434
  // The compaction re-reads the context just rebuilt and writes a summary;
427
435
  // the next request writes the fresh context.
428
- const cost = b.total * b.price.cacheReadPerM + SUMMARY_OUTPUT_TOKENS * b.price.outputPerM + mix * AFTER_COMPACT_TOKENS * b.price.inputPerM;
436
+ const cost = b.total * price.cacheReadPerM + SUMMARY_OUTPUT_TOKENS * price.outputPerM + mix * AFTER_COMPACT_TOKENS * ratesAt(b.card, AFTER_COMPACT_TOKENS).inputPerM;
429
437
  events.push({ at: b.at, tokens: b.total, messagesAfter: n, netUsd: (saved - cost) / 1e6 });
430
438
  }
431
439
  return events;
@@ -22,7 +22,7 @@
22
22
  */
23
23
  import { join } from "node:path";
24
24
  import { listSessions, replyCounter, isClaudeSession } from "./session.js";
25
- import { cacheWriteSplit, pricingFor, usageCost, writeMultiplier } from "./pricing.js";
25
+ import { cacheWriteSplit, rateCard, ratesAt, requestCost, writeMultiplier } from "./pricing.js";
26
26
  import { realModel } from "./tokens.js";
27
27
  import { backupOnce } from "./install.js";
28
28
  import { ABSENT, readSettings, setJsonPath, withSettingsLock, writeAtomic } from "./settingsedit.js";
@@ -40,6 +40,7 @@ const SUMMARY_OUTPUT = 20_000;
40
40
  const TTL_MS = 3_600_000;
41
41
  export const MIN_WINDOW = 100_000;
42
42
  export const MAX_WINDOW = 1_000_000;
43
+ const UNPRICED = { inputPerM: 0, outputPerM: 0, cacheReadPerM: 0 };
43
44
  /**
44
45
  * `writeMult`: what this session pays to write a token to the cache,
45
46
  * relative to input, from the 5-minute and 1-hour writes its usage records.
@@ -81,13 +82,13 @@ function readRequests(path, runRows) {
81
82
  return;
82
83
  // Each request at its own model's price; "<synthetic>" rows carry no usage.
83
84
  model = realModel(e.message.model) ?? model;
84
- const p = pricingFor(model);
85
- if (p)
85
+ const card = rateCard(model, u, at);
86
+ if (card)
86
87
  priced = true;
87
88
  const w = cacheWriteSplit(u);
88
89
  writes5m += w.fiveMinute;
89
90
  writes1h += w.oneHour;
90
- reqs.push({ at, prompt, inPerM: p?.inputPerM ?? 0, readPerM: p?.cacheReadPerM ?? 0, outPerM: p?.outputPerM ?? 0, copy: seen === "copy", billedUsd: p ? usageCost(u, p).promptUsd : 0 });
91
+ reqs.push({ at, prompt, ...(card ? { card } : {}), copy: seen === "copy", billedUsd: requestCost(model, u, at)?.promptUsd ?? 0 });
91
92
  });
92
93
  return { reqs, writeMult: writeMultiplier(writes5m, writes1h), priced };
93
94
  }
@@ -133,12 +134,15 @@ function replay(reqs, window, since, reread = 0, writeMult = 1.25, idleMin = idl
133
134
  // still shape both arms; only the rest are billed.
134
135
  const counted = r.at >= since && !r.copy;
135
136
  const cold = prevAt === undefined || r.at - prevAt > TTL_MS;
136
- const write = writeMult * r.inPerM;
137
+ // Each prompt, real or simulated, at its own tier's rates.
138
+ const rates = (ctx) => (r.card ? ratesAt(r.card, ctx) : UNPRICED);
137
139
  const cost = (ctx, prev) => {
140
+ const p = rates(ctx);
141
+ const write = writeMult * p.inputPerM;
138
142
  if (cold)
139
143
  return write * ctx;
140
144
  const fresh = prev === undefined || ctx < prev ? ctx : ctx - prev;
141
- return r.readPerM * (ctx - fresh) + write * fresh;
145
+ return p.cacheReadPerM * (ctx - fresh) + write * fresh;
142
146
  };
143
147
  if (counted)
144
148
  base += cost(r.prompt, prevActual);
@@ -151,8 +155,9 @@ function replay(reqs, window, since, reread = 0, writeMult = 1.25, idleMin = idl
151
155
  }
152
156
  let simPrev = prevSim;
153
157
  if (ctx >= TRIGGER_SHARE * window) {
158
+ const p = rates(ctx);
154
159
  if (counted) {
155
- sim += r.readPerM * ctx + r.outPerM * SUMMARY_OUTPUT + write * reread;
160
+ sim += p.cacheReadPerM * ctx + p.outputPerM * SUMMARY_OUTPUT + writeMult * p.inputPerM * reread;
156
161
  extra++;
157
162
  }
158
163
  removed = r.prompt - AFTER_COMPACT - reread;
package/dist/doctor.js CHANGED
@@ -30,7 +30,7 @@ import { codexDir } from "./codexdir.js";
30
30
  import { periodSpend, readBudget } from "./budget.js";
31
31
  import { sessionPriceThresholds } from "./sessionprice.js";
32
32
  import { claudeSpend, codexSpend } from "./spend.js";
33
- import { hasKnownPrice, isUnbilledModel } from "./pricing.js";
33
+ import { hasKnownPrice, isUnbilledModel, priceChangedText } from "./pricing.js";
34
34
  function claudeDesktopConfigPath() {
35
35
  switch (platform()) {
36
36
  case "darwin": return join(homedir(), "Library", "Application Support", "Claude", "claude_desktop_config.json");
@@ -297,10 +297,15 @@ export function unpricedModelsCheck(days = 30, now = Date.now(), home = homedir(
297
297
  const label = "Model prices";
298
298
  const since = now - days * 86_400_000;
299
299
  const seen = new Map();
300
+ // A price in the table that changed on a day before some requests (pricing.ts's end dates).
301
+ const changed = new Map();
300
302
  const add = (items) => {
301
303
  for (const i of items)
302
- if (i.model)
304
+ if (i.model) {
303
305
  seen.set(i.model, (seen.get(i.model) ?? 0) + 1);
306
+ if (i.changedOn)
307
+ changed.set(i.model, [i.model, i.changedOn]);
308
+ }
304
309
  };
305
310
  try {
306
311
  add(claudeSpend(since, now));
@@ -313,6 +318,8 @@ export function unpricedModelsCheck(days = 30, now = Date.now(), home = homedir(
313
318
  if (seen.size === 0)
314
319
  return undefined;
315
320
  const unknown = [...seen].filter(([m]) => !hasKnownPrice(m) && !isUnbilledModel(m)).sort((a, b) => b[1] - a[1]);
321
+ if (!unknown.length && changed.size)
322
+ return { label, status: "warn", detail: `${priceChangedText([...changed.values()])}: those requests are estimated. npm install -g context-doctor@latest` };
316
323
  if (!unknown.length)
317
324
  return { label, status: "ok", detail: `every model used in the last ${days} days has a list price on file` };
318
325
  const named = unknown.slice(0, 5).map(([m, n]) => `${m} (${n.toLocaleString("en-US")} request${n === 1 ? "" : "s"})`).join(", ") + (unknown.length > 5 ? ` and ${unknown.length - 5} more` : "");
package/dist/extract.d.ts CHANGED
@@ -22,7 +22,7 @@ export declare const EXTRACTABLE: Set<string>;
22
22
  /** Never load or write a document's subsidiary resources (stylesheets, images, frames). */
23
23
  export declare const TEXTUTIL_ARGS: string[];
24
24
  /** The document's text, or the reason it could not be read. */
25
- export declare function extractText(path: string): {
25
+ export declare function extractText(name: string): {
26
26
  text: string;
27
27
  } | {
28
28
  error: string;
@@ -42,7 +42,7 @@ export declare const monotonicNow: () => number;
42
42
  * `end` on the same clock: a deadline on the wall clock, converted per
43
43
  * document, let a clock jump between two documents cut the later ones short.
44
44
  */
45
- export declare function extractTextAsync(path: string, end?: number): Promise<{
45
+ export declare function extractTextAsync(name: string, end?: number): Promise<{
46
46
  text: string;
47
47
  } | {
48
48
  error: string;