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
package/README.md CHANGED
@@ -18,6 +18,8 @@ npx context-doctor spend # one bill across Claude Code, Codex, Gemini CLI
18
18
 
19
19
  ## Quick start
20
20
 
21
+ **See it first, nothing installed:** in a terminal, `npx context-doctor` reads your last 30 days of Claude Code sessions on this machine and shows what the fixes with no quality cost would have saved, as one total, then asks once: `y` applies them all, `npx context-doctor fix undo` puts them back. The fixes that trade something (compacting earlier, the subagents' model) are listed with their dollars and the command for each.
22
+
21
23
  Pick where you work. Each takes about a minute and is fully reversible.
22
24
 
23
25
  | You use | Do this |
@@ -28,12 +30,12 @@ Pick where you work. Each takes about a minute and is fully reversible.
28
30
  | **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
31
  | **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
32
  | **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.45.0` comments how much a PR grows CLAUDE.md, AGENTS.md and rules, and can fail over a budget ([setup](./docs/ci.md)) |
33
+ | **GitHub pull requests** | `uses: KushalP1/context-doctor@v0.47.0` comments how much a PR grows CLAUDE.md, AGENTS.md and rules, and can fail over a budget ([setup](./docs/ci.md)) |
32
34
 
33
35
  ## What it does
34
36
 
35
37
  **Measure, in dollars, on your own history** ([profiling](./docs/profiling.md))
36
- - `spend`: one bill across Claude Code (subagents and workflow agents included), Codex, Gemini CLI and Cursor, by tool, project, model and day, at list prices ([spend and budget](./docs/spend.md)).
38
+ - `spend`: one bill across Claude Code (subagents and workflow agents included), Codex, Gemini CLI and Cursor, by tool, project, model and day, as billed at list rates ([spend and budget](./docs/spend.md)).
37
39
  - `savings`: what your recent Claude Code sessions cost and what each fix below would have saved, replayed request by request against what you were billed.
38
40
  - `overhead`: what every request re-reads before your message (system prompt, tools, MCP servers, CLAUDE.md, rules, memory), each file priced per month.
39
41
  - `tasks`, `reads`, `subagents`, `compactions`: cost per commit; files read into session after session; whether each subagent was cheaper than the same steps in the parent; whether sessions work worse after compacting.
@@ -137,7 +139,7 @@ Rules 1-4 end exactly at character 512, the part ChatGPT's guide says must stand
137
139
  | `context-doctor spend [--days n] [--share]` | One bill across every tool on this machine: Claude Code (main conversation and subagents), Codex, Gemini CLI and Cursor (an estimate: no cache split), by tool, project, model and day, with what drives it ([docs](./docs/spend.md)) |
138
140
  | `context-doctor budget [<$>/day\|<$>/week [--block]\|off]` | A spend budget the every-prompt hook applies: a line at 50%, 80% and 100%, and with `--block` prompts over it are held until you raise it or turn it off ([docs](./docs/spend.md#a-budget-the-hook-applies-context-doctor-budget)) |
139
141
  | `context-doctor doctor` | Self-check the whole installation — one pasteable ✓/✗ diagnosis with fixes, including which surfaces autopilot can reach and any other program on its port |
140
- | `context-doctor savings [--days n] [--share [--copy]]` | What your recent Claude Code sessions cost, and what `/compact` at cold resumes, autopilot and an earlier auto-compact window would save, replayed through the shipped code against your actual billed usage. `--share` prints totals only (no project names or paths) to post. A bare `context-doctor` in a terminal shows the same |
142
+ | `context-doctor savings [--days n] [--share [--copy]]` | What your recent Claude Code sessions cost, and what `/compact` at cold resumes, autopilot and an earlier auto-compact window would save, replayed through the shipped code against your actual billed usage. `--share` prints totals only (no project names or paths) to post. A bare `context-doctor` in a terminal shows `fix`'s plan instead, with one question for the fixes that cost nothing in quality |
141
143
  | `context-doctor autopilot on\|off\|pause\|resume\|status` | Every new Claude Code session started in a terminal or IDE goes through the local proxy, which clears stale tool output only when the prompt cache is cold: measured 12.7% less input cost, no session worse ([details](./docs/autopilot.md)) |
142
144
  | `context-doctor proxy --autopilot` | Local proxy for your own Anthropic, OpenAI and Gemini API apps: clears stale tool output only when the prompt cache is cold, so it never costs more. Plain `proxy` runs the optimizing strategies (dedupe, trim, strip base64), which can cost more on cached traffic. `--token` for a public URL; `/stats` for cumulative savings ([details](./docs/proxy.md)) |
143
145
  | `context-doctor compact-window [status\|off\|<size>]` | Replay your last 30 days at auto-compact windows from 200k to 800k: input cost, saving, and how many more compactions each means. `400k` (or `250000`, `0.4m`) sets Claude Code's `autoCompactWindow`, with a backup; `off` removes it. Works in every Claude Code surface, the desktop app included |
@@ -181,6 +183,8 @@ Rules 1-4 end exactly at character 512, the part ChatGPT's guide says must stand
181
183
 
182
184
  ## What's new
183
185
 
186
+ - **0.47 One keystroke to a saving, the mod through `install`, a weekly live check, and an audit of 0.46**: a bare `context-doctor` in a terminal shows the fixes that cost no quality as one monthly total and asks once (the author's: $469 a month: long Bash output to a file, the 1-hour cache). On Claude Code 2.1.286+, `install` enables the plugin, so npm users get the mod too (limit readings and Claude Code's own cost after each turn, Compact first, `/context-doctor-fix`). A weekly canary runs the plugin and mod in the newest Claude Code against a local mock API. `spend` estimates compaction requests and, for terminal sessions, subagent progress summaries, and `fix` can switch the summaries off. An audit fixed, among others, the GitHub Action's YAML (it could not load), programs planted in a cloned repository running on Windows, `pack_context` opening network shares, a re-pricing gap after upgrades, and a test that would have failed from 2026-12-16 ([details](./ROADMAP.md#shipped-in-0470-one-keystroke-the-mod-through-install-a-weekly-live-check-and-an-audit-of-046)).
187
+ - **0.46 Fable 5.2, the Desktop app, and an audit**: Claude Fable 5.2 is priced (0.45 read it 1.5x too high); managed `modelPricing` is honoured; a check catches new models without a price. The plugin's new mod brings limit readings, Claude Code's own cost and `/context-doctor-fix` with Apply and Undo buttons to the Desktop app, VS Code and the terminal, and a cache-expiry band with **Compact first** to the Desktop app and the terminal (Claude Code draws a mod's band on no other surface) ([Desktop](./docs/desktop.md), [details](./ROADMAP.md#shipped-in-0460-fable-52-the-desktop-app-and-an-audit-of-045)).
184
188
  - **0.45 Price what is billed, and a security pass**: fast mode, US-only inference, Haiku 5.5's long-prompt rates, web searches and OpenAI's and Gemini's long-prompt tiers are priced per request in every report, and prices that end on a known day say so. A security pass fixed a cloned repository approving its own MCP servers for `overhead --mcp`, a PDF's name running as a command through `pack` on macOS, the agents' API-key configs being packed, and the proxy answering a DNS-rebinding page ([details](./ROADMAP.md#shipped-in-0450-price-what-is-billed-and-a-security-pass-on-044)).
185
189
  - **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)).
186
190
  - **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).
@@ -207,6 +211,7 @@ Every release, with the details: [docs/whats-new.md](./docs/whats-new.md).
207
211
  - [Detectors and fixes](./docs/detectors.md): what the profiler finds and what each optimizer strategy changes
208
212
  - [Library](./docs/library.md): `profileConversation`, `optimizeConversation`, `packContext`, `withContextDoctor`
209
213
  - [Budgets and CI](./docs/ci.md): the GitHub Action and `.contextdoctorrc`
214
+ - [Desktop app and VS Code](./docs/desktop.md): the plugin's mod: limit readings, Claude Code's own cost and `/context-doctor-fix` (Desktop app, VS Code, terminal), and the cache band with Compact first (Desktop app and terminal only)
210
215
  - [Editor and status line](./docs/editor-and-statusline.md): the VS Code / Cursor extension and Claude Code's status bar
211
216
  - [Token counts](./docs/tokenizer.md): why counts are "~", how the Claude ratios were measured, exact counts
212
217
  - [Performance](./docs/performance.md): what context-doctor itself costs (its six MCP tool definitions: at most ~2,344 tokens)
package/dist/ab.js CHANGED
@@ -36,6 +36,7 @@
36
36
  * local mock server through ANTHROPIC_BASE_URL.
37
37
  */
38
38
  import { spawn, spawnSync } from "node:child_process";
39
+ import { toolCwd } from "./toolcwd.js";
39
40
  import { randomBytes } from "node:crypto";
40
41
  import { accessSync, chmodSync, constants as fsConstants, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, readlinkSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
41
42
  import { tmpdir } from "node:os";
@@ -138,7 +139,7 @@ function killTree(child) {
138
139
  if (child.pid === undefined)
139
140
  return;
140
141
  if (process.platform === "win32") {
141
- spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
142
+ spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { cwd: toolCwd(), stdio: "ignore", windowsHide: true });
142
143
  return;
143
144
  }
144
145
  try {
@@ -172,7 +173,7 @@ function killLeftovers(root) {
172
173
  else {
173
174
  // lsof walks every process's open files: ~0.5 s here, several on a loaded machine. Cut off
174
175
  // early, it found nothing and the leftover lived on, so it gets time.
175
- const r = spawnSync("lsof", ["-t", "+D", root], { encoding: "utf8", timeout: 30_000 });
176
+ const r = spawnSync("lsof", ["-t", "+D", root], { cwd: toolCwd(), encoding: "utf8", timeout: 30_000 });
176
177
  for (const line of (r.stdout ?? "").split("\n"))
177
178
  if (/^\d+$/.test(line.trim()))
178
179
  pids.add(Number(line.trim()));
package/dist/autopilot.js CHANGED
@@ -19,6 +19,7 @@
19
19
  * backend, not an API base URL).
20
20
  */
21
21
  import { execFileSync, spawn } from "node:child_process";
22
+ import { toolCwd } from "./toolcwd.js";
22
23
  import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, rmSync, statSync, writeFileSync } from "node:fs";
23
24
  import { homedir, platform } from "node:os";
24
25
  import { dirname, join } from "node:path";
@@ -106,7 +107,7 @@ function uid() {
106
107
  return String(process.getuid?.() ?? "");
107
108
  }
108
109
  function run(cmd, args) {
109
- execFileSync(cmd, args, { stdio: "ignore" });
110
+ execFileSync(cmd, args, { cwd: toolCwd(), stdio: "ignore" });
110
111
  }
111
112
  function tryRun(cmd, args) {
112
113
  try {
@@ -262,7 +263,10 @@ export function restartService(home = homedir(), exec = tryRun) {
262
263
  export function startDetached(args, log) {
263
264
  mkdirSync(dirname(log), { recursive: true });
264
265
  const out = openSync(log, "a");
265
- const child = spawn(args[0], args.slice(1), { detached: true, stdio: ["ignore", out, out], windowsHide: true });
266
+ // Not the caller's folder: the every-prompt hook restarts the proxy from
267
+ // the project it runs in, and on Windows a process standing in a folder
268
+ // keeps it from being renamed or deleted for as long as the proxy lives.
269
+ const child = spawn(args[0], args.slice(1), { cwd: toolCwd(), detached: true, stdio: ["ignore", out, out], windowsHide: true });
266
270
  child.unref();
267
271
  }
268
272
  export async function health(port, timeoutMs = 800) {
@@ -324,20 +328,20 @@ async function canBind(port) {
324
328
  function listenerProcess(port) {
325
329
  try {
326
330
  if (platform() === "win32") {
327
- const net = execFileSync("netstat", ["-ano", "-p", "TCP"], { encoding: "utf8", timeout: 3000, stdio: ["ignore", "pipe", "ignore"] });
331
+ const net = execFileSync("netstat", ["-ano", "-p", "TCP"], { cwd: toolCwd(), encoding: "utf8", timeout: 3000, stdio: ["ignore", "pipe", "ignore"] });
328
332
  const line = net.split(/\r?\n/).find((l) => new RegExp(`:${port}\\s+\\S+\\s+LISTENING\\s+\\d+`, "i").test(l));
329
333
  const pid = Number(/LISTENING\s+(\d+)/i.exec(line ?? "")?.[1]);
330
334
  if (!(pid > 0))
331
335
  return {};
332
336
  let command;
333
337
  try {
334
- const task = execFileSync("tasklist", ["/FI", `PID eq ${pid}`, "/FO", "CSV", "/NH"], { encoding: "utf8", timeout: 3000, stdio: ["ignore", "pipe", "ignore"] });
338
+ const task = execFileSync("tasklist", ["/FI", `PID eq ${pid}`, "/FO", "CSV", "/NH"], { cwd: toolCwd(), encoding: "utf8", timeout: 3000, stdio: ["ignore", "pipe", "ignore"] });
335
339
  command = /^"([^"]+)"/.exec(task.trim())?.[1];
336
340
  }
337
341
  catch { /* the pid alone */ }
338
342
  return { pid, command };
339
343
  }
340
- const out = execFileSync("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-Fpc"], { encoding: "utf8", timeout: 2000, stdio: ["ignore", "pipe", "ignore"] });
344
+ const out = execFileSync("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-Fpc"], { cwd: toolCwd(), encoding: "utf8", timeout: 2000, stdio: ["ignore", "pipe", "ignore"] });
341
345
  const pid = Number(/^p(\d+)/m.exec(out)?.[1]);
342
346
  return { pid: pid > 0 ? pid : undefined, command: /^c(.+)$/m.exec(out)?.[1] };
343
347
  }
package/dist/blob.js CHANGED
@@ -9,7 +9,9 @@
9
9
  * character dominating.
10
10
  */
11
11
  /** Runs of base64 alphabet long enough to be worth reporting (~375 bytes+). */
12
- const BASE64_RE = /(?:data:[\w/+.-]+;base64,)?[A-Za-z0-9+/]{500,}={0,2}/g;
12
+ const MIN_RUN = 500;
13
+ /** The data: URI header a run may follow (the candidate then starts at "data:"). */
14
+ const DATA_URI_HEAD = /data:[\w/+.-]+;base64,$/;
13
15
  export const BASE64_PLACEHOLDER = "[context-doctor: base64 blob removed — use file/image APIs instead]";
14
16
  /** Distinct characters a genuine base64 payload is expected to span. */
15
17
  const MIN_DISTINCT_CHARS = 24;
@@ -19,26 +21,78 @@ function isBase64Blob(candidate) {
19
21
  // An explicit data: URI declares its own encoding — no need to guess.
20
22
  if (candidate.startsWith("data:"))
21
23
  return true;
22
- const counts = new Map();
23
- for (const ch of candidate)
24
- counts.set(ch, (counts.get(ch) ?? 0) + 1);
25
- if (counts.size < MIN_DISTINCT_CHARS)
26
- return false;
24
+ // A candidate is ASCII (the alphabet and "="): a count per character code.
25
+ const counts = new Uint32Array(128);
26
+ let distinct = 0;
27
27
  let max = 0;
28
- for (const n of counts.values())
29
- if (n > max)
30
- max = n;
28
+ for (let k = 0; k < candidate.length; k++) {
29
+ const c = candidate.charCodeAt(k) & 127;
30
+ if (counts[c]++ === 0)
31
+ distinct++;
32
+ if (counts[c] > max)
33
+ max = counts[c];
34
+ }
35
+ if (distinct < MIN_DISTINCT_CHARS)
36
+ return false;
31
37
  return max / candidate.length < MAX_SINGLE_CHAR_SHARE;
32
38
  }
39
+ /** A-Z, a-z, 0-9, + and /. */
40
+ function inAlphabet(c) {
41
+ return (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || (c >= 48 && c <= 57) || c === 43 || c === 47;
42
+ }
43
+ /**
44
+ * The candidates, as [start, end) spans: what
45
+ * /(?:data:[\w/+.-]+;base64,)?[A-Za-z0-9+/]{500,}={0,2}/g matched, found by
46
+ * a scan. That expression threw "Maximum call stack size exceeded" on a run
47
+ * past about 5.5 million characters (a 4 MB image or PDF pasted as base64),
48
+ * which ended analyze, profile_context and optimize at the very blob they
49
+ * exist to find.
50
+ */
51
+ function* candidates(text) {
52
+ const n = text.length;
53
+ let i = 0;
54
+ // Where the last candidate ended: a header cannot reuse its characters ("…xYdata" ends one).
55
+ let last = 0;
56
+ while (i < n) {
57
+ if (!inAlphabet(text.charCodeAt(i))) {
58
+ i++;
59
+ continue;
60
+ }
61
+ let j = i;
62
+ while (j < n && inAlphabet(text.charCodeAt(j)))
63
+ j++;
64
+ if (j - i < MIN_RUN) {
65
+ i = j;
66
+ continue;
67
+ }
68
+ let end = j;
69
+ while (end < n && end - j < 2 && text.charCodeAt(end) === 61)
70
+ end++; // up to two "=" of padding
71
+ const head = DATA_URI_HEAD.exec(text.slice(Math.max(last, i - 1000), i));
72
+ yield [head ? i - head[0].length : i, end];
73
+ i = last = end;
74
+ }
75
+ }
33
76
  /** True when the text carries at least one inline base64 blob. */
34
77
  export function hasBase64Blob(text) {
35
- for (const m of text.matchAll(BASE64_RE)) {
36
- if (isBase64Blob(m[0]))
78
+ for (const [s, e] of candidates(text)) {
79
+ if (isBase64Blob(text.slice(s, e)))
37
80
  return true;
38
81
  }
39
82
  return false;
40
83
  }
41
84
  /** Replace real base64 blobs with a placeholder, leaving lookalikes intact. */
42
85
  export function stripBase64Blobs(text) {
43
- return text.replace(BASE64_RE, (m) => (isBase64Blob(m) ? BASE64_PLACEHOLDER : m));
86
+ const parts = [];
87
+ let from = 0;
88
+ for (const [s, e] of candidates(text)) {
89
+ if (!isBase64Blob(text.slice(s, e)))
90
+ continue;
91
+ parts.push(text.slice(from, s), BASE64_PLACEHOLDER);
92
+ from = e;
93
+ }
94
+ if (parts.length === 0)
95
+ return text;
96
+ parts.push(text.slice(from));
97
+ return parts.join("");
44
98
  }
package/dist/budget.d.ts CHANGED
@@ -23,6 +23,7 @@
23
23
  * replies count once. Measured on the author's history: docs/spend.md.
24
24
  */
25
25
  import { type Tool } from "./spend.js";
26
+ import { type CompactTrack } from "./compactcost.js";
26
27
  export type Period = "day" | "week";
27
28
  export interface Budget {
28
29
  usd: number;
@@ -72,7 +73,13 @@ export declare function periodEnd(period: Period, now?: number): number;
72
73
  * lists those priced only by their model's family (an estimate), the same
73
74
  * way; `z` those priced past the day their model's price changed (index,
74
75
  * 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.
76
+ * US-only and web searches, and the output price in `r` is its own. `p`
77
+ * fingerprints the price table `d` was priced by (pricing.ts priceTableKey)
78
+ * and the organization's rates (orgrates.ts), when set: an entry priced
79
+ * under another table or other rates is read again. `c` is where reading a
80
+ * Claude Code transcript's compactions stopped (compactcost.ts): each
81
+ * compaction's own request is in `k`/`d` too, estimated, keyed by its
82
+ * boundary's uuid.
76
83
  */
77
84
  export interface FileEntry {
78
85
  t: Tool;
@@ -87,6 +94,8 @@ export interface FileEntry {
87
94
  x?: Array<[number, string]>;
88
95
  y?: Array<[number, string]>;
89
96
  z?: Array<[number, string, string]>;
97
+ p?: string;
98
+ c?: CompactTrack;
90
99
  }
91
100
  /** A ledger entry this version can use: a damaged one threw on every prompt until its transcript changed. */
92
101
  export declare function wellFormed(e: FileEntry | undefined): e is FileEntry;
package/dist/budget.js CHANGED
@@ -32,9 +32,11 @@ 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 { isUnbilledModel, priceChangedText, requestCost } from "./pricing.js";
35
+ import { isUnbilledModel, priceChangedText, priceTableKey, requestCost } from "./pricing.js";
36
+ import { orgRates, orgRatesLine } from "./orgrates.js";
36
37
  import { anchorOf, rowsOf } from "./scan.js";
37
38
  import { realModel } from "./tokens.js";
39
+ import { isCompactionRow, isTrack, newTrack, trackCompaction } from "./compactcost.js";
38
40
  /** Beside the hook state and the ledger: ~/.claude/.context-doctor-budget.json. */
39
41
  export function budgetPath() {
40
42
  return join(dirname(statePath()), ".context-doctor-budget.json");
@@ -176,6 +178,8 @@ export function periodEnd(period, now = Date.now()) {
176
178
  s.setDate(s.getDate() + (period === "week" ? 7 : 1));
177
179
  return s.getTime();
178
180
  }
181
+ /** What a ledger entry counts: 2, each Claude Code compaction's own request too (compactcost.ts). An entry counted otherwise is read again. */
182
+ const COUNTED = 2;
179
183
  /** Replies remembered per transcript, to tell a later row of one from a new reply. */
180
184
  const RECENT_REPLIES = 64;
181
185
  function readState() {
@@ -336,7 +340,10 @@ function readFile(tool, file, since, size) {
336
340
  // appended after this read, must still be known as its own (they were
337
341
  // counted again as a new request).
338
342
  const last = new Map();
343
+ // Where the compactions stand at the end (claudeFileUsage counted those before it): an append goes on from here.
344
+ const track = newTrack();
339
345
  for (const row of rowsOf(file, USAGE_ROWS)) {
346
+ trackCompaction(track, row);
340
347
  const m = row?.message;
341
348
  if (row?.type !== "assistant" || typeof m?.id !== "string")
342
349
  continue;
@@ -355,7 +362,7 @@ function readFile(tool, file, since, size) {
355
362
  const fd = openSync(file, "r");
356
363
  try {
357
364
  const o = lineStart(fd, size);
358
- return { k, d, o, a: anchorOf(fd, o), r: r.slice(-RECENT_REPLIES), ...flags() };
365
+ return { k, d, o, a: anchorOf(fd, o), r: r.slice(-RECENT_REPLIES), c: track, ...flags() };
359
366
  }
360
367
  finally {
361
368
  closeSync(fd);
@@ -418,7 +425,8 @@ function countLines(e, recent, text, since, own) {
418
425
  // Only the last replies matter (a reply's rows are written together): a whole transcript read at once stays linear.
419
426
  if (recent.length > 2 * RECENT_REPLIES)
420
427
  recent.splice(0, recent.length - RECENT_REPLIES);
421
- if (!line.includes('"usage"'))
428
+ const compaction = isCompactionRow(line);
429
+ if (!compaction && !line.includes('"usage"'))
422
430
  continue;
423
431
  let row;
424
432
  try {
@@ -427,6 +435,19 @@ function countLines(e, recent, text, since, own) {
427
435
  catch {
428
436
  continue;
429
437
  }
438
+ // A compaction's own request, estimated (compactcost.ts), as claudeFileUsage counts it.
439
+ if (!isTrack(e.c))
440
+ e.c = newTrack();
441
+ const done = trackCompaction(e.c, row);
442
+ if (done && (Number.isFinite(done.ts) ? done.ts >= since : since <= 0) && !(own !== undefined && done.sessionId !== undefined && done.sessionId !== own)) {
443
+ const index = e.k.length;
444
+ if (done.cost.changedOn)
445
+ (e.z ??= []).push([index, done.model, done.cost.changedOn]);
446
+ else if (done.cost.estimated)
447
+ (e.y ??= []).push([index, done.model]);
448
+ e.k.push(keyOf(done.uuid));
449
+ e.d.push(done.cost.totalUsd);
450
+ }
430
451
  const m = row?.message;
431
452
  if (row?.type !== "assistant" || !m?.usage)
432
453
  continue;
@@ -450,7 +471,8 @@ function countLines(e, recent, text, since, own) {
450
471
  // A reply on <synthetic> was made by Claude Code itself, never billed: not a request at all.
451
472
  // A row of another session (`own`): a copy of its history, its spend, not this session's.
452
473
  const copied = own !== undefined && typeof row.sessionId === "string" && row.sessionId !== own;
453
- if (Number.isFinite(ts) && ts >= since && tokens > 0 && !isUnbilledModel(m.model) && !copied) {
474
+ // A row with no time of its own fits no period, but it is in the session's price (since 0), at today's rates (requestCost).
475
+ if ((Number.isFinite(ts) ? ts >= since : since <= 0) && tokens > 0 && !isUnbilledModel(m.model) && !copied) {
454
476
  index = e.k.length;
455
477
  if (!c)
456
478
  (e.x ??= []).push([index, model ?? "unknown"]);
@@ -493,8 +515,12 @@ export function refreshEntry(tool, file, prev, since, direct = false, own) {
493
515
  catch {
494
516
  return undefined;
495
517
  }
496
- // An entry not in the shape this version writes (edited, or another version's) is read again.
497
- const e = wellFormed(prev) ? prev : undefined;
518
+ // An entry not in the shape this version writes (edited, or another version's), or priced at other
519
+ // rates (the organization's, or another price table: an upgrade that corrected a price), or counted
520
+ // otherwise (COUNTED: 2 adds each compaction's own request), is read again.
521
+ const org = orgRates()?.key;
522
+ const p = `${COUNTED}.${priceTableKey()}${org ? ` ${org}` : ""}`;
523
+ const e = wellFormed(prev) && prev.p === p ? prev : undefined;
498
524
  if (e && e.t === tool && e.s === s.size && e.m === s.mtimeMs && e.i === s.ino)
499
525
  return { e, read: -1 };
500
526
  try {
@@ -514,11 +540,11 @@ export function refreshEntry(tool, file, prev, since, direct = false, own) {
514
540
  finally {
515
541
  closeSync(fd);
516
542
  }
517
- const blank = { t: tool, s: 0, m: 0, i: s.ino, k: [], d: [], o: 0, a, r: [] };
543
+ const blank = { t: tool, s: 0, m: 0, i: s.ino, k: [], d: [], o: 0, a, r: [], p };
518
544
  if (readAppended(blank, file, since, own))
519
545
  return { e: { ...blank, s: s.size, m: s.mtimeMs }, read: s.size };
520
546
  }
521
- return { e: { t: tool, s: s.size, m: s.mtimeMs, i: s.ino, ...readFile(tool, file, since, s.size) }, read: s.size };
547
+ return { e: { t: tool, s: s.size, m: s.mtimeMs, i: s.ino, ...readFile(tool, file, since, s.size), p }, read: s.size };
522
548
  }
523
549
  catch {
524
550
  return undefined;
@@ -686,6 +712,9 @@ export function renderBudgetStatus(b, s, hookInstalled) {
686
712
  `Budget: ${amount(b.usd)} a ${per(b.period)}, across Claude Code, Codex and Gemini CLI${b.block ? "; prompts over it are held" : ""}.`,
687
713
  `${span(b.period) === "today" ? "Today" : "This week"}: ${money(s.usd)} so far, ${Math.round((s.usd / b.usd) * 100)}%${byToolText(s.byTool)}. ${resets(b.period)}`,
688
714
  ];
715
+ const org = orgRatesLine();
716
+ if (org)
717
+ lines.push(org);
689
718
  if (s.unpriced)
690
719
  lines.push(`Not counted: ${unpricedText(s.unpriced)}`);
691
720
  if (s.estimated) {
@@ -37,7 +37,7 @@
37
37
  import { listSessions, isClaudeSession } from "./session.js";
38
38
  import { rowsOf, slimUsage } from "./scan.js";
39
39
  import { formatTokens, isCodeLike, realModel, tokensForLength } from "./tokens.js";
40
- import { CACHE_WRITE_1H, CACHE_WRITE_5M, pricingFor } from "./pricing.js";
40
+ import { CACHE_WRITE_1H, CACHE_WRITE_5M, requestCost } from "./pricing.js";
41
41
  import { compareVersions } from "./modelswitch.js";
42
42
  import { diagnosedMisses, missLogPath } from "./missledger.js";
43
43
  /** Dollars as a person reads them: "$1,925", "$12.26", "$0". */
@@ -209,10 +209,12 @@ runRows, onLate = () => { }) {
209
209
  if (prev && at - prev.at >= prev.ttl)
210
210
  colds++;
211
211
  if (at >= since) {
212
- const price = pricingFor(model);
212
+ // As billed (requestCost): fast mode, US-only, the prompt's tier, its day's price, each TTL at its own rate.
213
+ const cost = requestCost(model, u, at);
214
+ const price = cost?.rates;
213
215
  const w1h = Math.min(write, num(u.cache_creation?.ephemeral_1h_input_tokens));
214
216
  const w5m = u.cache_creation ? Math.min(write - w1h, num(u.cache_creation?.ephemeral_5m_input_tokens)) : write - w1h;
215
- onRequest(price ? (write * price.inputPerM * (oneHour ? CACHE_WRITE_1H : CACHE_WRITE_5M)) / 1e6 : 0, { at, version, write, oneHour: w1h, fiveMinute: w5m, first, model, entrypoint: r.ep });
217
+ onRequest(cost?.writeUsd ?? 0, { at, version, write, oneHour: w1h, fiveMinute: w5m, first, model, entrypoint: r.ep });
216
218
  if (prev && !compacted && at - prev.at < Math.min(ttl, prev.ttl) && prev.total > MIN_CONTEXT) {
217
219
  const isMiss = write > MISS_SHARE * prev.total;
218
220
  let miss;
package/dist/cacheplan.js CHANGED
@@ -42,8 +42,8 @@ const MAX_BREAKPOINTS = 4;
42
42
  * on some models and called cacheable prompts too small on others.
43
43
  */
44
44
  const CACHE_MINIMUMS = {
45
- "opus 5.5": 512, "opus 5.0": 512, "fable 5.0": 512, "fable 5.1": 512,
46
- "mythos 5.0": 512, "mythos 5.1": 512, "sonnet 5.5": 512, "haiku 5.5": 512,
45
+ "opus 5.5": 512, "opus 5.0": 512, "fable 5.0": 512, "fable 5.1": 512, "fable 5.2": 512,
46
+ "mythos 5.0": 512, "mythos 5.1": 512, "mythos 5.2": 512, "sonnet 5.5": 512, "haiku 5.5": 512,
47
47
  "opus 4.8": 1024, "sonnet 5.0": 1024, "sonnet 4.6": 1024, "sonnet 4.5": 1024,
48
48
  "opus 4.1": 1024, "opus 4.0": 1024, "sonnet 4.0": 1024,
49
49
  "opus 4.7": 2048, "haiku 3.5": 2048, "mythos preview": 2048,
package/dist/cachettl.js CHANGED
@@ -39,6 +39,7 @@ import { listSessions, replyCounter, isClaudeSession } from "./session.js";
39
39
  import { REQUEST_ROWS } from "./coldresume.js";
40
40
  import { rowsOf } from "./scan.js";
41
41
  import { CACHE_WRITE_1H, CACHE_WRITE_5M, cacheWriteSplit, requestCost } from "./pricing.js";
42
+ import { priceBasis } from "./orgrates.js";
42
43
  import { realModel } from "./tokens.js";
43
44
  import { backupOnce } from "./install.js";
44
45
  import { ABSENT, readSettings, setJsonPath, withSettingsLock, writeAtomic } from "./settingsedit.js";
@@ -311,7 +312,7 @@ function block(label, r, set, kind) {
311
312
  export function renderCacheTtl(r, current, installs = [], command = (s) => `context-doctor ${s}`) {
312
313
  const out = [];
313
314
  out.push("Prompt cache lifetime: 5 minutes or 1 hour (Claude Code's own setting)");
314
- out.push(`Last ${r.days} days, at list prices; the same content is sent either way`);
315
+ out.push(`Last ${r.days} days, ${priceBasis()}; the same content is sent either way`);
315
316
  out.push("─".repeat(66));
316
317
  out.push(...block("Main conversation", r.main, current.main, "main"));
317
318
  out.push("");
package/dist/ci.js CHANGED
@@ -10,6 +10,7 @@
10
10
  * Base contents come from `git show <base>:<path>`; nothing is checked out.
11
11
  */
12
12
  import { execFileSync } from "node:child_process";
13
+ import { toolCwd } from "./toolcwd.js";
13
14
  import { readFileSync, statSync } from "node:fs";
14
15
  import { join, posix } from "node:path";
15
16
  import { estimateTokens, formatTokens } from "./tokens.js";
@@ -27,7 +28,7 @@ const MEMORY_PATTERNS = [
27
28
  ];
28
29
  function git(args, cwd) {
29
30
  try {
30
- return execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 64 * 1024 * 1024 });
31
+ return execFileSync("git", ["-C", cwd, ...args], { cwd: toolCwd(), encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 64 * 1024 * 1024 });
31
32
  }
32
33
  catch {
33
34
  return undefined;
@@ -0,0 +1,97 @@
1
+ /**
2
+ * The Claude Code plugin as `install`'s way into Claude Code (E1).
3
+ *
4
+ * The plugin carries everything install used to wire into Claude Code by
5
+ * hand (the MCP server, the skills, the every-prompt, compaction,
6
+ * session-start, subagent-price and model-switch hooks) plus the one thing
7
+ * install could not: the mod (limits readings and Claude Code's own session
8
+ * cost after each turn, the cold-return Compact first button,
9
+ * /context-doctor-fix). Claude Code runs mods from 2.1.286 (Desktop app),
10
+ * 2.1.287 (terminal) and 2.1.299 (VS Code).
11
+ *
12
+ * How it is switched on, verified on 2.1.321 (the Desktop app's) and 2.1.311
13
+ * (Homebrew) in a throwaway HOME: two keys in ~/.claude/settings.json,
14
+ * `extraKnownMarketplaces.context-doctor` (this repository on GitHub) and
15
+ * `enabledPlugins["context-doctor@context-doctor"]: true`. Claude Code never
16
+ * rewrites the file for them. At its next start it clones the marketplace in
17
+ * the background (known_marketplaces.json, plugins/marketplaces/), then
18
+ * downloads the enabled plugin (installed_plugins.json, plugins/cache/), and
19
+ * loads it from the next session start (or /reload-plugins); a `-p` run with
20
+ * CLAUDE_CODE_SYNC_PLUGIN_INSTALL=1 loads it in the first session. The code
21
+ * reconciling declared marketplaces is the binary's "[reconcile]" step; the
22
+ * docs: code.claude.com/docs/en/plugins/loading ("Plugins and marketplaces
23
+ * that aren't on disk at session start"). With both keys taken out again,
24
+ * `claude plugin list` shows the downloaded copy "disabled" and no session
25
+ * loads it. `claude plugin install` does not read the declaration (it
26
+ * answers "not found in marketplace" until `marketplace add`, which
27
+ * re-serialises settings.json), so the CLI is not the way.
28
+ *
29
+ * Settings are one file for every Claude Code on the machine, so the plugin
30
+ * replaces install's own wiring only when every Claude Code found runs mods;
31
+ * with an older one present (or none found) install keeps its own wiring for
32
+ * all of them, as it does for the model-switch hook.
33
+ */
34
+ import { type ClaudeCodeInstall } from "./modelswitch.js";
35
+ /** The first Claude Code that runs a plugin's mod (the Desktop app's Code tab; the terminal from 2.1.287). */
36
+ export declare const MOD_SINCE = "2.1.286";
37
+ /** Our marketplace's name (.claude-plugin/marketplace.json) and where it lives. */
38
+ export declare const MARKETPLACE = "context-doctor";
39
+ export declare const MARKETPLACE_REPO = "KushalP1/context-doctor";
40
+ /**
41
+ * The key Claude Code enables our plugin under: "<plugin>@<marketplace>".
42
+ * A copy listed in another marketplace keeps the plugin name, so any
43
+ * "context-doctor@…" key is ours.
44
+ */
45
+ export declare const PLUGIN_KEY = "context-doctor@context-doctor";
46
+ export declare function isOurPluginKey(key: string): boolean;
47
+ /**
48
+ * The declaration install writes. autoUpdate: Claude Code refreshes it and
49
+ * updates the plugin in the background after startup when plugin.json's
50
+ * version changes (each release), as the npx-launched MCP server follows
51
+ * npm; a third-party marketplace is off by default.
52
+ */
53
+ export declare function marketplaceDeclaration(): {
54
+ source: {
55
+ source: "github";
56
+ repo: string;
57
+ };
58
+ autoUpdate: boolean;
59
+ };
60
+ /** Is this extraKnownMarketplaces entry ours: this repository on GitHub, however Claude Code has touched it since? */
61
+ export declare function isOurDeclaration(entry: unknown): boolean;
62
+ export interface ModReadiness {
63
+ /** Every Claude Code found runs mods: the plugin can stand in for install's own wiring. */
64
+ ok: boolean;
65
+ /** The ones that predate MOD_SINCE. */
66
+ old: ClaudeCodeInstall[];
67
+ installs: ClaudeCodeInstall[];
68
+ }
69
+ export declare function modReadiness(installs: ClaudeCodeInstall[]): ModReadiness;
70
+ /** What install added to settings.json for the plugin, so uninstall takes out only that. */
71
+ export interface PluginMarker {
72
+ /** install wrote extraKnownMarketplaces.context-doctor. */
73
+ marketplace: boolean;
74
+ /** install wrote enabledPlugins["context-doctor@context-doctor"]: true. */
75
+ enabled: boolean;
76
+ }
77
+ export declare function pluginMarkerPath(): string;
78
+ export declare function readPluginMarker(): PluginMarker | undefined;
79
+ /** Claude Code's plugins folder: CLAUDE_CODE_PLUGIN_CACHE_DIR, else ~/.claude/plugins. */
80
+ export declare function claudePluginsRoot(env?: NodeJS.ProcessEnv): string;
81
+ /** Is a marketplace named context-doctor registered with Claude Code (from any source)? */
82
+ export declare function marketplaceRegistered(): boolean;
83
+ /**
84
+ * How far Claude Code has got with the plugin: "installed" (downloaded, at
85
+ * `version`), "registered" (marketplace fetched, plugin not yet), or "none".
86
+ */
87
+ export declare function pluginStage(): {
88
+ stage: "installed" | "registered" | "none";
89
+ version?: string;
90
+ };
91
+ /** When the mod last wrote each ledger (ms since epoch), from the files' modification times. */
92
+ export declare function modActivity(): {
93
+ cost?: number;
94
+ limits?: number;
95
+ };
96
+ /** "3 h ago", "2 days ago". */
97
+ export declare function ago(ms: number, now?: number): string;