context-doctor 0.27.0 → 0.28.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
@@ -1,58 +1,66 @@
1
1
  # context-doctor 🩺
2
2
 
3
- [![CI](https://github.com/KushalP1/context-doctor/actions/workflows/ci.yml/badge.svg)](https://github.com/KushalP1/context-doctor/actions) [![npm](https://img.shields.io/npm/v/context-doctor)](https://www.npmjs.com/package/context-doctor) [![npm downloads](https://img.shields.io/npm/dm/context-doctor)](https://www.npmjs.com/package/context-doctor) [![license: MIT](https://img.shields.io/badge/license-MIT-blue)](./LICENSE) ![macOS | Linux | Windows](https://img.shields.io/badge/platform-macOS%20%7C%20Linux%20%7C%20Windows-lightgrey)
3
+ [![CI](https://github.com/KushalP1/context-doctor/actions/workflows/ci.yml/badge.svg)](https://github.com/KushalP1/context-doctor/actions) [![npm](https://img.shields.io/npm/v/context-doctor)](https://www.npmjs.com/package/context-doctor) [![npm downloads](https://img.shields.io/npm/dm/context-doctor)](https://www.npmjs.com/package/context-doctor) [![MCP Registry](https://img.shields.io/badge/MCP%20Registry-io.github.KushalP1%2Fcontext--doctor-blue)](https://registry.modelcontextprotocol.io) [![license: MIT](https://img.shields.io/badge/license-MIT-blue)](./LICENSE) ![macOS | Linux | Windows](https://img.shields.io/badge/platform-macOS%20%7C%20Linux%20%7C%20Windows-lightgrey)
4
4
 
5
- **Cut your Claude Code bill, measured on your own sessions.**
5
+ **See where your AI agent's tokens go, and stop paying for the ones that do nothing.**
6
+
7
+ AI agents re-send their whole context on every message: old tool output, pasted files, long instructions. A 500k-token session pays for all of it again each time, and at full price after a coffee break, when the prompt cache has expired. context-doctor measures that waste on your own sessions, in dollars, and removes it at the moments it pays: before it enters the context, while it sits there, and on every request.
8
+
9
+ It runs on your machine, needs no API key, sends no telemetry, and works with **Claude Code, Claude Desktop, Cursor, Codex, Gemini CLI**, any app on the **Anthropic, OpenAI or Gemini API**, and **CI**. MIT licensed, Node 20+, macOS, Linux and Windows.
6
10
 
7
11
  ```bash
8
- npx context-doctor savings
12
+ npx context-doctor savings # what your recent sessions cost, and what each fix would have saved
9
13
  ```
10
14
 
11
- One command shows, in dollars, what your recent sessions cost and what each lever below would have saved on them. Then the levers do it: an every-prompt hook, an auto-compact window, and a proxy that never makes a request more expensive.
15
+ <img src="https://raw.githubusercontent.com/KushalP1/context-doctor/main/assets/savings.svg" alt="npx context-doctor savings: input billed, what /compact at cold resumes, autopilot and an earlier auto-compact window would have saved" width="640">
12
16
 
13
- Long agent sessions fill up with tool output nobody reads again, and a 500k-token session re-reads all of it on every message. The most expensive moment is coming back after lunch: the prompt cache has expired, so the next message re-sends everything at full price. `context-doctor` measures this on your own sessions and acts on it at the moments that pay.
17
+ ## Quick start
14
18
 
15
- - **Tells you when to `/compact`, at the moment it pays.** When you come back to a large session after the cache expired, the every-prompt hook gives the model the numbers and it offers `/compact` once. Replayed over 133 days of the author's Claude Code history: 401 such returns, and compacting then would have saved **$4,053 net at list price, about $914 a month**. It works in every Claude Code surface, including the desktop app. [What it saves →](#what-it-saves)
16
- - **Compacts earlier, automatically, in every Claude Code surface.** Claude Code auto-compacts near the full window (measured: ~970k tokens on a 1M model), so long sessions re-read 400k-900k tokens on every message. `context-doctor compact-window` replays your history at smaller windows and, if you choose, sets Claude Code's own `autoCompactWindow`. On the author's last 30 days: **a 400k window would have cut input cost 55%** ($6,119 to $2,757), for 15 compactions a week instead of 5. A native setting, so it works in the desktop app too. [The trade-off →](#3-compacting-earlier-automatic)
17
- - **Autopilot for terminal and IDE sessions and API apps:** a local proxy that clears stale tool output only when the prompt cache is cold, so it never costs more. **9.8% less input cost, no session made more expensive**, in the same replay. (The desktop app's Code tab sets its own API address, so autopilot cannot reach it; `doctor` tells you if that is your case.)
18
- - **Keeps waste out in the first place.** `context-doctor pack` (and the `pack_context` MCP tool) puts only the chunks of a big document, log or codebase that a question needs into the context, within a token budget: 9 of 10 questions about this repo answered from 0.6% of its tokens. `context-doctor overhead` measures what every request re-reads before your message (system prompt, tools, CLAUDE.md, rules, memory) and prices each memory file per month. [How →](#before-it-enters-the-context-pack-and-overhead)
19
- - **Counts Claude correctly.** Current Claude models pack 2.75 characters per token, not the 4 most tools assume, so estimates built on 4 undercount Claude by about 40%. The ratios were measured from the API's own counts; `context-doctor accuracy` re-checks them on yours.
20
- - **Works where you work:** Claude Code (terminal, IDE, desktop app, plugin), Cursor, Codex, Gemini CLI, Claude Desktop chat, any Anthropic or OpenAI API app, VS Code, CI. macOS, Linux and Windows, Node 20+. Local, keyless, no telemetry, MIT.
19
+ Pick where you work. Each takes about a minute and is fully reversible.
21
20
 
22
- Built and maintained by [gAI Ventures](https://gai.ventures).
21
+ | You use | Do this |
22
+ |---|---|
23
+ | **Claude Code** (terminal, IDE, desktop app) | Inside Claude Code: `/plugin marketplace add KushalP1/context-doctor`, then `/plugin install context-doctor@context-doctor`. You get the every-prompt check, the MCP tools and `/context-doctor:savings`, `:checkup`, `:overhead`, `:pack`, `:autopilot`, `:compact-window` |
24
+ | **Everything on this machine at once** | `npm install -g context-doctor && context-doctor install` wires Claude Code, Claude Desktop, Cursor, Codex and Gemini CLI. `context-doctor doctor` checks it; `context-doctor uninstall` removes it |
25
+ | **Claude Desktop, Cursor or any MCP client** | Add the server to the client's MCP config (or install the one-click `.mcpb` from the [latest release](https://github.com/KushalP1/context-doctor/releases/latest) in Claude Desktop):<br>`{"mcpServers": {"context-doctor": {"command": "npx", "args": ["-y", "context-doctor", "mcp"]}}}` |
26
+ | **claude.ai, ChatGPT, phone apps** | `npx context-doctor instructions --copy`, then paste into the app's personal preferences |
27
+ | **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 `http://localhost:8787`. No proxy possible? Wrap the SDK client: `withContextDoctor(new Anthropic())` |
28
+ | **GitHub pull requests** | `uses: KushalP1/context-doctor@v0.27.0` comments how much a PR grows CLAUDE.md, AGENTS.md and rules, and can fail over a budget ([setup](#enforce-a-budget-in-ci)) |
23
29
 
24
- > **Which context-doctor is this?** Several projects share the name. This one is [`context-doctor` on npm](https://www.npmjs.com/package/context-doctor) and `io.github.KushalP1/context-doctor` in the [official MCP Registry](https://registry.modelcontextprotocol.io): the one you run as `npx context-doctor`, and the one that prices what it saves on your own history.
30
+ ## What it does
25
31
 
26
- ## Quick start
32
+ **Measure, in dollars, on your own history**
33
+ - `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.
34
+ - `overhead`: what every request re-reads before your message (system prompt, tools, MCP servers, CLAUDE.md, rules, memory), each file priced per month.
35
+ - `session`, `watch`, `analyze`, `report`, `dashboard`: token breakdown and wasted-context findings for any session, conversation file or agent trace.
27
36
 
28
- **See what it would save you first** (no install, reads your local Claude Code history):
37
+ **Keep waste out of the context**
38
+ - `pack` (and the `pack_context` MCP tool): only the chunks of a big document, PDF, log or codebase that a question needs, within a token budget, instead of the whole thing.
39
+ - `overhead split`: turns a heavy CLAUDE.md or memory file into a lean one plus a reference file the agent opens when needed, word for word, nothing lost.
40
+ - `ci` and the GitHub Action: review memory-file growth like any other cost.
29
41
 
30
- ```bash
31
- npx context-doctor savings
32
- ```
42
+ **Remove waste automatically**
43
+ - An every-prompt hook (Claude Code, Codex, Gemini CLI; Cursor after each tool call) tells the model its real context size and the largest waste, and offers `/compact` when you return to a big session after the cache expired.
44
+ - `compact-window`: sets Claude Code's own auto-compact window, measured on your history first. Works in the desktop app too.
45
+ - Autopilot: a local proxy (or SDK wrapper) that clears stale tool output only when the prompt cache is cold, so a request never costs more.
33
46
 
34
- <img src="https://raw.githubusercontent.com/KushalP1/context-doctor/main/assets/savings.svg" alt="npx context-doctor savings: input billed, what /compact at cold resumes, autopilot and an earlier auto-compact window would have saved" width="640">
47
+ ## What it has measured
35
48
 
36
- That is the author's machine: every session there runs in the desktop app, which autopilot cannot reach, so lines 1 and 3 are the ones that apply. Yours is computed the same way, from your own transcripts: every session replayed request by request through the shipped code, against what you were actually billed. `context-doctor savings --share` prints a few lines with totals only (no project names or paths) if you want to post your number.
49
+ On the author's own Claude Code history (mostly Opus and Fable models with the 1M window, priced at API list prices; `savings` computes yours the same way):
37
50
 
38
- **Then install it**, whichever way suits you:
51
+ - **Compacting when you come back after the cache expired:** 401 such returns in 133 days; compacting then would have saved **$4,053 net, about $914 a month**. [Details →](#what-it-saves)
52
+ - **A 400k auto-compact window instead of ~970k:** **55% less input cost** over 30 days ($6,119 to $2,757), for 15 compactions a week instead of 5. [The trade-off →](#3-compacting-earlier-automatic)
53
+ - **Autopilot:** **9.8% less input cost, no session made more expensive.**
54
+ - **pack:** 9 of 10 questions about this repository answered from **0.6% of its tokens**. [How →](#before-it-enters-the-context-pack-and-overhead)
55
+ - **Counting Claude correctly:** current Claude models pack 2.75 characters per token, not the 4 most tools assume, so estimates built on 4 undercount Claude by about 40%. `context-doctor accuracy` re-checks the ratio on your own sessions.
39
56
 
40
- ```bash
41
- # Everything, every app it finds (Claude Code, Cursor, Codex, Claude Desktop)
42
- npm install -g context-doctor
43
- context-doctor install
44
- context-doctor autopilot on # every new Claude Code session keeps its context lean
45
- ```
57
+ On a Claude subscription you do not pay list price; the same tokens come out of your usage limit instead, so read the dollars as the size of the effect.
46
58
 
47
- ```text
48
- # Or as a Claude Code plugin, from inside Claude Code
49
- /plugin marketplace add KushalP1/context-doctor
50
- /plugin install context-doctor@context-doctor
51
- ```
59
+ Built and maintained by [gAI Ventures](https://gai.ventures).
52
60
 
53
- The plugin brings the every-prompt check, the MCP tools, and `/context-doctor:savings`, `/context-doctor:checkup`, `/context-doctor:autopilot` and `/context-doctor:compact-window`. It needs no npm step: the MCP server ships as one self-contained file, so it also works on Claude Code versions that do not install plugin dependencies.
61
+ > **Which context-doctor is this?** Several projects share the name. This one is [`context-doctor` on npm](https://www.npmjs.com/package/context-doctor) and `io.github.KushalP1/context-doctor` in the [official MCP Registry](https://registry.modelcontextprotocol.io).
54
62
 
55
- `context-doctor autopilot status` shows what autopilot did; `context-doctor doctor` checks the whole setup. Everything is reversible: `context-doctor autopilot off`, `context-doctor uninstall`, or `/plugin uninstall`.
63
+ A profile looks like this (`npx context-doctor analyze conversation.json`, or `session` for your latest Claude Code session):
56
64
 
57
65
  ```
58
66
  Where the tokens go
@@ -166,6 +174,7 @@ MCP servers are part of the same overhead: each one's tool definitions ride on e
166
174
 
167
175
  ## What's new
168
176
 
177
+ - **0.28 Wider reach**: `/context-doctor:overhead` and `/context-doctor:pack` in the Claude Code plugin; `pack` reads a folder inside a git repository the way git does, so `.gitignore`'d build output and secrets stay out; `withContextDoctor` wraps Google's `@google/genai` client too; `overhead` measures the fixed start-of-session cost of Codex and Gemini CLI sessions as well as Claude Code's, priced with each provider's cache rules.
169
178
  - **0.27 Keep waste out**: `pack` and the `pack_context` MCP tool put only the chunks of big files (text, code, PDF, Word, PowerPoint) a question needs into the context, within a budget; `overhead` measures and prices the front matter every request re-reads (system prompt, tools, CLAUDE.md, rules, memory, AGENTS.md, Cursor rules, GEMINI.md). MCP servers sized and their use counted; `overhead split` turns a heavy memory file into a lean one plus a reference file. `withContextDoctor(client)` runs autopilot inside an Anthropic or OpenAI SDK client, for apps with no proxy. Gemini joins: `install` wires Gemini CLI's MCP server and every-prompt hook, `session` and `watch` read its chats, and the proxy and autopilot carry Google's Gemini API. A GitHub Action (and `context-doctor ci`) reports memory-file growth on every pull request and gates on a budget. Re-verified on every surface: 229 tests on macOS, Linux and Windows, plus MCP, OpenAI and Gemini end-to-end smoke runs, now in CI, MCP over stdio and HTTP, the OpenAI proxy, and a live `doctor`.
170
179
  - **0.26 Checked on every platform, three fixes**: tested end to end in Claude Code (terminal, desktop app, plugin from GitHub), Claude Desktop, Cursor, Codex on GPT-5.5, VS Code, the MCP server on every launch path, and the proxy on OpenAI's APIs. Found and fixed: Cursor's agent never received the hook's guidance (Cursor runs Claude Code's hook where output cannot add context), so `install` now adds a native Cursor hook; Codex blocked the MCP tools behind an approval it never grants in `codex exec`, so the tools are now marked read-only; autopilot skipped Codex's newest tools (`exec`, `wait`) and some of Cursor's. Also: a history imported into Codex no longer reads as "2136% of the window", and the chat-app settings paths are current.
171
180
  - **0.25 Compact earlier, by itself**: the `/compact` offer at cold resumes was followed 1 time in 33 on the author's machine, so two changes. The hook now also shows you the notice (it went only to the model, which rarely raised it), with the dollar cost of the message you just sent. And `context-doctor compact-window` measures and sets Claude Code's own auto-compact window, which works without anyone acting on advice, in every surface including the desktop app: 55% less input cost at 400k on the author's last 30 days. `savings` shows it as a third lever.
@@ -243,7 +252,7 @@ Practical upshot: a developer who only wants cheaper, faster API calls never tou
243
252
  | `context-doctor autopilot on\|off\|pause\|resume\|status` | Every new Claude Code session goes through the local proxy, which clears stale tool output only when the prompt cache is cold: measured 9.8% less input cost, no session worse |
244
253
  | `context-doctor instructions [--copy]` | The ~180-token standing rules (~120 on GPT) for claude.ai / ChatGPT preferences, for web and phones where no server runs |
245
254
  | `context-doctor pack <files\|dirs\|-> --query "…"` | Only the chunks of big documents, logs or code a question needs, ranked and fit to `--max-tokens` (default 4000). No query: an outline; `--ids a#2,b#5` picks chunks from it. Offline, no key |
246
- | `context-doctor overhead [--days n] [--mcp]` | What every request re-reads before your message: measured first-request size, each memory file (CLAUDE.md and imports, rules, auto memory, AGENTS.md, Cursor rules, GEMINI.md) priced per month, MCP calls per server; `--mcp` sizes each configured server's tool definitions and flags unused ones |
255
+ | `context-doctor overhead [--days n] [--mcp]` | What every request re-reads before your message: measured first-request size (Claude Code, Codex and Gemini CLI sessions), each memory file (CLAUDE.md and imports, rules, auto memory, AGENTS.md, Cursor rules, GEMINI.md) priced per month, MCP calls per server; `--mcp` sizes each configured server's tool definitions and flags unused ones |
247
256
  | `context-doctor overhead split <file> [--write]` | Move a memory file's big or code-heavy sections word for word to `<name>.reference.md`, leaving pointers; indexes stay. A plan until `--write`, which backs up first |
248
257
  | `context-doctor ci [--base <ref>] [--max-tokens n] [--max-increase n]` | Memory files (CLAUDE.md, AGENTS.md, GEMINI.md, rules, their imports) at HEAD vs a base commit; exit 1 over budget. What the GitHub Action runs |
249
258
  | `context-doctor analyze <file>` | Profile a conversation: token breakdown, findings, cost + latency estimates. `--fail-over-budget` exits 1 on a breach, for CI |
@@ -480,7 +489,7 @@ console.log(packed.selected.map((c) => `${c.id} L${c.startLine}-${c.endLine}`),
480
489
 
481
490
  ### Autopilot inside your app: `withContextDoctor`
482
491
 
483
- For apps that cannot send traffic through a local proxy (serverless and edge functions, managed hosts), wrap the SDK client. `messages.create` / `stream`, `chat.completions.create` / `stream` / `parse` and `responses.create` / `stream` / `parse` (beta namespaces too) go through the same autopilot as the proxy: stale tool output is cleared only when the prompt cache is cold. Each request is cloned before it changes, so the history your app holds is never rewritten; only the copy on the wire is slimmer. State lives in the process: one long-lived process per conversation stream behaves like the proxy, and a conversation the process has not seen counts as warm, so a fresh serverless instance never clears blind (pass `statePath` on shared storage if many instances serve the same conversations). Tested with the real `@anthropic-ai/sdk` and `openai` packages.
492
+ For apps that cannot send traffic through a local proxy (serverless and edge functions, managed hosts), wrap the SDK client. `messages.create` / `stream`, `chat.completions.create` / `stream` / `parse` and `responses.create` / `stream` / `parse` (beta namespaces too) and Google's `models.generateContent` / `generateContentStream` go through the same autopilot as the proxy: stale tool output is cleared only when the prompt cache is cold. Each request is cloned before it changes, so the history your app holds is never rewritten; only the copy on the wire is slimmer. State lives in the process: one long-lived process per conversation stream behaves like the proxy, and a conversation the process has not seen counts as warm, so a fresh serverless instance never clears blind (pass `statePath` on shared storage if many instances serve the same conversations). Tested with the real `@anthropic-ai/sdk` and `openai` packages.
484
493
 
485
494
  ## Subagents: their own windows, your bill
486
495
 
package/dist/cli.js CHANGED
@@ -42,7 +42,7 @@ import { listCursorChats, parseCursorChat } from "./cursor.js";
42
42
  import { analyzeCacheUsage, renderCacheReport } from "./cache.js";
43
43
  import { renderToolTimings } from "./timing.js";
44
44
  import { packContextSemantic, readSources, renderPack } from "./pack.js";
45
- import { measureBaseline, measureMcpSizes, overheadReport, renderOverhead } from "./overhead.js";
45
+ import { measureBaselines, measureMcpSizes, overheadReport, renderOverhead } from "./overhead.js";
46
46
  import { applySplit, planSplit, renderSplit } from "./split.js";
47
47
  import { ciReport, renderCiMarkdown, renderCiText } from "./ci.js";
48
48
  const HELP = `context-doctor — profile and optimize LLM context windows
@@ -732,7 +732,9 @@ async function main() {
732
732
  console.error(`Could not read ${file}: ${e.message}`);
733
733
  process.exit(1);
734
734
  }
735
- console.log(renderSplit(plan, measureBaseline(args.days ?? 30)?.usdPerKPerMonth));
735
+ // Price the file at the rate of the agent that loads it.
736
+ const agent = /AGENTS(\.override)?\.md$/i.test(file) ? "Codex" : /GEMINI\.md$/i.test(file) ? "Gemini CLI" : "Claude Code";
737
+ console.log(renderSplit(plan, measureBaselines(args.days ?? 30).find((b) => b.agent === agent)?.usdPerKPerMonth));
736
738
  if (args.write && plan.sections.some((s) => s.moved)) {
737
739
  const { backup } = applySplit(plan);
738
740
  console.log(`\nWritten. Backup: ${backup}\nUndo: mv "${backup}" "${file}" (and delete or trim ${plan.referencePath}).`);
package/dist/gemini.d.ts CHANGED
@@ -18,6 +18,8 @@
18
18
  import { type ParsedSession, type SessionInfo } from "./session.js";
19
19
  /** True when the file's first record looks like a Gemini CLI chat (cheap: reads 4 KB). */
20
20
  export declare function isGeminiChat(path: string): boolean;
21
+ /** The ordered, de-duplicated, rewind-applied messages of a chat file. */
22
+ export declare function readGeminiMessages(path: string): any[];
21
23
  export declare function parseGeminiChat(path: string): ParsedSession;
22
24
  /** Gemini CLI chats on this machine: ~/.gemini/tmp/<project>/chats/session-*.json[l]. */
23
25
  export declare function listGeminiChats(home?: string): SessionInfo[];
package/dist/gemini.js CHANGED
@@ -62,7 +62,7 @@ function resultText(call) {
62
62
  return typeof call?.resultDisplay === "string" ? call.resultDisplay : r === undefined ? "" : JSON.stringify(r);
63
63
  }
64
64
  /** The ordered, de-duplicated, rewind-applied messages of a chat file. */
65
- function readMessages(path) {
65
+ export function readGeminiMessages(path) {
66
66
  const order = [];
67
67
  const byId = new Map();
68
68
  let anon = 0;
@@ -115,7 +115,7 @@ export function parseGeminiChat(path) {
115
115
  const usageSamples = [];
116
116
  let model;
117
117
  let reportedInputTokens;
118
- for (const m of readMessages(path)) {
118
+ for (const m of readGeminiMessages(path)) {
119
119
  if (m.type === "user") {
120
120
  const t = text(m.content);
121
121
  if (t)
package/dist/mcp.js CHANGED
@@ -52,7 +52,7 @@ const STRATEGY_IDS = ["dedupe", "trim-tool-results", "trim-tool-calls", "strip-b
52
52
  * recommended pattern.
53
53
  */
54
54
  function createServer({ fileAccess = true } = {}) {
55
- const server = new McpServer({ name: "context-doctor", version: "0.27.0" }, { instructions: SERVER_INSTRUCTIONS });
55
+ const server = new McpServer({ name: "context-doctor", version: "0.28.0" }, { instructions: SERVER_INSTRUCTIONS });
56
56
  server.tool("profile_context", "Profile an LLM conversation or prompt: token breakdown, largest blocks, and actionable findings about wasted context (duplicates, oversized pastes or tool results, base64 blobs, long history). Two inputs, pass ONE: `conversation` (full OpenAI/Anthropic JSON or raw text, for agents, files and proxies) or `sketch` (for chat apps such as Claude Desktop or ChatGPT where you cannot export the conversation: the turn count plus the few blocks that matter, ~120 tokens to write). Call it whenever the user asks about token usage, context size, cost, speed or limits, and on your own once the conversation passes ~30 turns or holds 3+ large pastes. Act on the top finding in your reply.", {
57
57
  conversation: z.string().optional().describe("Conversation JSON (OpenAI or Anthropic format, or bare message array) or raw prompt text. Omit in chat apps and pass `sketch`."),
58
58
  sketch: z.object({
@@ -29,6 +29,7 @@ export interface OverheadFinding {
29
29
  suggestion: string;
30
30
  }
31
31
  export interface Baseline {
32
+ agent: Agent;
32
33
  sessions: number;
33
34
  /** Median tokens of the first request, minus the first user message. */
34
35
  median: number;
@@ -42,7 +43,10 @@ export interface Baseline {
42
43
  }
43
44
  export interface OverheadReport {
44
45
  cwd: string;
46
+ /** Claude Code's baseline (memory-file prices for Claude Code are quoted against it). */
45
47
  baseline?: Baseline;
48
+ /** Every agent with sessions in the period: Claude Code, Codex, Gemini CLI. */
49
+ baselines: Baseline[];
46
50
  files: MemoryFile[];
47
51
  findings: OverheadFinding[];
48
52
  mcp: McpSection;
@@ -56,13 +60,16 @@ export interface McpSection {
56
60
  /** Every memory file the four agents load for a session started in `cwd`. */
57
61
  export declare function findMemoryFiles(cwd?: string, home?: string): MemoryFile[];
58
62
  /**
59
- * Fixed overhead per session, measured: the first main-chain request's input
60
- * (input + cache read + cache write) minus the first user message, plus the
63
+ * Fixed overhead per session and agent, measured: each session's first
64
+ * request (the API's own count) minus the first user message, plus the
61
65
  * request and cold-start counts that turn tokens into a monthly bill.
66
+ * Claude Code, Codex and Gemini CLI sessions, newest `days` only.
62
67
  */
68
+ export declare function measureBaselines(days?: number, paths?: string[]): Baseline[];
69
+ /** Claude Code's baseline (the one memory-file prices are quoted against). */
63
70
  export declare function measureBaseline(days?: number, paths?: string[]): Baseline | undefined;
64
71
  /** What is worth changing in the memory files. */
65
- export declare function overheadFindings(files: MemoryFile[], baseline?: Baseline): OverheadFinding[];
72
+ export declare function overheadFindings(files: MemoryFile[], baselines?: Baseline | Baseline[]): OverheadFinding[];
66
73
  export declare function overheadReport(opts?: {
67
74
  cwd?: string;
68
75
  home?: string;
package/dist/overhead.js CHANGED
@@ -18,8 +18,9 @@ import { readdirSync, readFileSync, statSync } from "node:fs";
18
18
  import { homedir } from "node:os";
19
19
  import { dirname, isAbsolute, join, relative, resolve } from "node:path";
20
20
  import { forEachLine, listSessions } from "./session.js";
21
- import { estimateTokens, formatTokens } from "./tokens.js";
21
+ import { estimateTokens, formatTokens, providerFor } from "./tokens.js";
22
22
  import { formatUsd, pricingFor } from "./pricing.js";
23
+ import { isGeminiChat, readGeminiMessages } from "./gemini.js";
23
24
  import { claudeMcpConfigs, mcpUsage, measureServer, toolPrefixName } from "./mcpschema.js";
24
25
  const TTL_MS = 3_600_000;
25
26
  const CLAUDE = "claude-opus-5"; // Claude's tokenizer ratios; the model only picks the provider here.
@@ -139,72 +140,147 @@ export function findMemoryFiles(cwd = process.cwd(), home = homedir()) {
139
140
  add("Gemini CLI", join(d, "GEMINI.md"), "project");
140
141
  return files;
141
142
  }
143
+ function textOf(content) {
144
+ if (typeof content === "string")
145
+ return content;
146
+ if (!Array.isArray(content))
147
+ return "";
148
+ return content.map((b) => (typeof b === "string" ? b : typeof b?.text === "string" ? b.text : "")).filter(Boolean).join("\n");
149
+ }
150
+ /** Claude Code: usage rows on assistant messages (one per API reply id). */
151
+ function claudeUsage(path) {
152
+ const out = { agent: "Claude Code", reqs: [] };
153
+ let firstUser;
154
+ let lastId;
155
+ forEachLine(path, (line) => {
156
+ let e;
157
+ try {
158
+ e = JSON.parse(line);
159
+ }
160
+ catch {
161
+ return;
162
+ }
163
+ if (!e || e.isSidechain)
164
+ return;
165
+ if (e.type === "user" && out.first === undefined && firstUser === undefined && !e.isMeta) {
166
+ const text = textOf(e.message?.content);
167
+ if (text)
168
+ firstUser = text;
169
+ return;
170
+ }
171
+ if (e.type !== "assistant" || !e.message?.usage || e.message.id === lastId)
172
+ return;
173
+ lastId = e.message.id;
174
+ const u = e.message.usage;
175
+ const prompt = (u.input_tokens ?? 0) + (u.cache_read_input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0);
176
+ const at = Date.parse(e.timestamp);
177
+ if (!(prompt > 0) || !Number.isFinite(at))
178
+ return;
179
+ out.first ??= Math.max(0, prompt - estimateTokens(firstUser ?? "", CLAUDE));
180
+ out.reqs.push({ at, model: e.message.model });
181
+ });
182
+ return out;
183
+ }
142
184
  /**
143
- * Fixed overhead per session, measured: the first main-chain request's input
144
- * (input + cache read + cache write) minus the first user message, plus the
145
- * request and cold-start counts that turn tokens into a monthly bill.
185
+ * Codex rollouts: token_count events carry each request's input (cached part
186
+ * included). Codex sends AGENTS.md and its environment as user messages;
187
+ * those are overhead, so the first real prompt is the one subtracted.
146
188
  */
147
- export function measureBaseline(days = 30, paths) {
148
- const since = Date.now() - days * 86_400_000;
149
- const files = paths ?? listSessions(10_000).filter((s) => s.path.includes(".claude") && s.modifiedAt.getTime() >= since).map((s) => s.path);
189
+ function codexUsage(path) {
190
+ const out = { agent: "Codex", reqs: [] };
191
+ let firstUser;
192
+ let model;
193
+ forEachLine(path, (line) => {
194
+ let e;
195
+ try {
196
+ e = JSON.parse(line);
197
+ }
198
+ catch {
199
+ return;
200
+ }
201
+ const p = e?.payload;
202
+ if (!p)
203
+ return;
204
+ if (e.type === "turn_context" && typeof p.model === "string")
205
+ model = p.model;
206
+ if (e.type === "response_item" && p.type === "message" && p.role === "user" && firstUser === undefined) {
207
+ const text = textOf(p.content);
208
+ if (text && !/^\s*(<user_instructions>|<environment_context>|# AGENTS\.md)/.test(text))
209
+ firstUser = text;
210
+ }
211
+ if (e.type === "event_msg" && p.type === "token_count") {
212
+ const input = Number(p.info?.last_token_usage?.input_tokens);
213
+ const at = Date.parse(e.timestamp);
214
+ if (!(input > 0) || !Number.isFinite(at))
215
+ return;
216
+ out.first ??= Math.max(0, input - estimateTokens(firstUser ?? "", model));
217
+ out.reqs.push({ at, model });
218
+ }
219
+ });
220
+ return out;
221
+ }
222
+ /** Gemini CLI chats: each gemini message records its request's promptTokenCount. */
223
+ function geminiUsage(path) {
224
+ const out = { agent: "Gemini CLI", reqs: [] };
225
+ let firstUser;
226
+ for (const m of readGeminiMessages(path)) {
227
+ if (m?.type === "user" && firstUser === undefined)
228
+ firstUser = textOf(m.content) || undefined;
229
+ if (m?.type !== "gemini")
230
+ continue;
231
+ const input = Number(m.tokens?.input);
232
+ const at = Date.parse(m.timestamp);
233
+ if (!(input > 0) || !Number.isFinite(at))
234
+ continue;
235
+ out.first ??= Math.max(0, input - estimateTokens(firstUser ?? "", m.model));
236
+ out.reqs.push({ at, model: m.model });
237
+ }
238
+ return out;
239
+ }
240
+ function usageOf(path) {
241
+ if (isGeminiChat(path))
242
+ return geminiUsage(path);
243
+ if (/[\\/]\.codex[\\/]/.test(path))
244
+ return codexUsage(path);
245
+ return claudeUsage(path);
246
+ }
247
+ /** Cache writes cost 1.25x input on Anthropic; OpenAI and Google charge no write premium. */
248
+ function writeMultiplier(model) {
249
+ return providerFor(model) === "anthropic" ? 1.25 : 1;
250
+ }
251
+ function aggregate(agent, sessions, since, days) {
150
252
  const firsts = [];
151
- let requests = 0, coldStarts = 0;
253
+ let requests = 0, coldStarts = 0, warm = 0;
152
254
  const models = new Map();
153
- for (const path of files) {
154
- let firstUser;
155
- let first;
156
- let lastId;
255
+ for (const s of sessions) {
256
+ if (s.first !== undefined && s.first > 1000)
257
+ firsts.push(s.first);
157
258
  let prevAt;
158
- forEachLine(path, (line) => {
159
- let e;
160
- try {
161
- e = JSON.parse(line);
162
- }
163
- catch {
164
- return;
165
- }
166
- if (!e || e.isSidechain)
167
- return;
168
- if (e.type === "user" && first === undefined && firstUser === undefined && !e.isMeta) {
169
- const c = e.message?.content;
170
- const text = typeof c === "string" ? c : Array.isArray(c) ? c.filter((b) => b?.type === "text").map((b) => b.text).join("\n") : "";
171
- if (text)
172
- firstUser = text;
173
- return;
174
- }
175
- if (e.type !== "assistant" || !e.message?.usage || e.message.id === lastId)
176
- return;
177
- lastId = e.message.id;
178
- const u = e.message.usage;
179
- const prompt = (u.input_tokens ?? 0) + (u.cache_read_input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0);
180
- const at = Date.parse(e.timestamp);
181
- if (!(prompt > 0) || !Number.isFinite(at))
182
- return;
183
- if (first === undefined)
184
- first = Math.max(0, prompt - estimateTokens(firstUser ?? "", CLAUDE));
185
- if (at >= since) {
259
+ for (const r of s.reqs) {
260
+ if (r.at >= since) {
186
261
  requests++;
187
- if (prevAt === undefined || at - prevAt > TTL_MS)
262
+ if (prevAt === undefined || r.at - prevAt > TTL_MS)
188
263
  coldStarts++;
189
- if (e.message.model)
190
- models.set(e.message.model, (models.get(e.message.model) ?? 0) + 1);
264
+ else
265
+ warm++;
266
+ if (r.model)
267
+ models.set(r.model, (models.get(r.model) ?? 0) + 1);
191
268
  }
192
- prevAt = at;
193
- });
194
- if (first !== undefined && first > 1000)
195
- firsts.push(first);
269
+ prevAt = r.at;
270
+ }
196
271
  }
197
272
  if (firsts.length === 0)
198
273
  return undefined;
199
274
  firsts.sort((a, b) => a - b);
200
275
  const model = [...models.entries()].sort((a, b) => b[1] - a[1])[0]?.[0];
201
276
  const price = pricingFor(model);
202
- // Each overhead token is a cache read on warm requests and a cache write
203
- // (1.25x input) after every cold start.
277
+ // Each overhead token is a cache read on warm requests and a full-price
278
+ // write (with the provider's premium) after every cold start.
204
279
  const usdPerKPerMonth = price
205
- ? ((1000 * ((requests - coldStarts) * price.cacheReadPerM + coldStarts * 1.25 * price.inputPerM)) / 1e6) * (30 / days)
280
+ ? ((1000 * (warm * price.cacheReadPerM + coldStarts * writeMultiplier(model) * price.inputPerM)) / 1e6) * (30 / days)
206
281
  : undefined;
207
282
  return {
283
+ agent,
208
284
  sessions: firsts.length,
209
285
  median: firsts[Math.floor(firsts.length / 2)],
210
286
  p90: firsts[Math.min(firsts.length - 1, Math.floor(firsts.length * 0.9))],
@@ -215,18 +291,52 @@ export function measureBaseline(days = 30, paths) {
215
291
  usdPerKPerMonth,
216
292
  };
217
293
  }
294
+ /**
295
+ * Fixed overhead per session and agent, measured: each session's first
296
+ * request (the API's own count) minus the first user message, plus the
297
+ * request and cold-start counts that turn tokens into a monthly bill.
298
+ * Claude Code, Codex and Gemini CLI sessions, newest `days` only.
299
+ */
300
+ export function measureBaselines(days = 30, paths) {
301
+ const since = Date.now() - days * 86_400_000;
302
+ const files = paths ?? listSessions(10_000).filter((s) => s.modifiedAt.getTime() >= since).map((s) => s.path);
303
+ const byAgent = new Map();
304
+ for (const path of files) {
305
+ let u;
306
+ try {
307
+ u = usageOf(path);
308
+ }
309
+ catch {
310
+ continue;
311
+ }
312
+ (byAgent.get(u.agent) ?? byAgent.set(u.agent, []).get(u.agent)).push(u);
313
+ }
314
+ const order = ["Claude Code", "Codex", "Gemini CLI"];
315
+ return order.flatMap((a) => {
316
+ const b = byAgent.has(a) ? aggregate(a, byAgent.get(a), since, days) : undefined;
317
+ return b ? [b] : [];
318
+ });
319
+ }
320
+ /** Claude Code's baseline (the one memory-file prices are quoted against). */
321
+ export function measureBaseline(days = 30, paths) {
322
+ return measureBaselines(days, paths).find((b) => b.agent === "Claude Code");
323
+ }
218
324
  function normalize(s) {
219
325
  return s.toLowerCase().replace(/\s+/g, " ").trim();
220
326
  }
221
327
  /** What is worth changing in the memory files. */
222
- export function overheadFindings(files, baseline) {
328
+ export function overheadFindings(files, baselines) {
223
329
  const out = [];
224
- const cost = (tok) => (baseline?.usdPerKPerMonth ? ` (~${formatUsd((tok / 1000) * baseline.usdPerKPerMonth)}/month at your usage)` : "");
330
+ const list = Array.isArray(baselines) ? baselines : baselines ? [baselines] : [];
331
+ const cost = (tok, agent) => {
332
+ const b = list.find((x) => x.agent === agent);
333
+ return b?.usdPerKPerMonth ? ` (~${formatUsd((tok / 1000) * b.usdPerKPerMonth)}/month at your usage)` : "";
334
+ };
225
335
  for (const f of files) {
226
336
  if (f.tokens >= 2000) {
227
337
  out.push({
228
338
  severity: f.tokens >= 5000 ? "warn" : "info",
229
- message: `${f.path} is ~${formatTokens(f.tokens)} tokens, read on every ${f.agent} request${f.agent === "Claude Code" ? cost(f.tokens) : ""}.`,
339
+ message: `${f.path} is ~${formatTokens(f.tokens)} tokens, read on every ${f.agent} request${cost(f.tokens, f.agent)}.`,
230
340
  suggestion: `Keep rules the agent needs on most requests; move reference material to a file it reads when relevant. \`context-doctor overhead split ${f.path}\` shows the split first.`,
231
341
  });
232
342
  }
@@ -280,9 +390,12 @@ export function overheadReport(opts = {}) {
280
390
  const cwd = opts.cwd ?? process.cwd();
281
391
  const home = opts.home ?? homedir();
282
392
  const files = findMemoryFiles(cwd, home);
283
- const baseline = measureBaseline(opts.days ?? 30, opts.paths);
284
- const mcp = { configs: claudeMcpConfigs(cwd, home), usage: mcpUsage(opts.days ?? 30, opts.paths) };
285
- return { cwd, baseline, files, findings: overheadFindings(files, baseline), mcp };
393
+ const baselines = measureBaselines(opts.days ?? 30, opts.paths);
394
+ const baseline = baselines.find((b) => b.agent === "Claude Code");
395
+ // MCP usage comes from Claude Code transcripts only (the tool-name scheme is theirs).
396
+ const claudePaths = opts.paths?.filter((p) => !isGeminiChat(p) && !/[\\/]\.codex[\\/]/.test(p));
397
+ const mcp = { configs: claudeMcpConfigs(cwd, home), usage: mcpUsage(opts.days ?? 30, claudePaths) };
398
+ return { cwd, baseline, baselines, files, findings: overheadFindings(files, baselines), mcp };
286
399
  }
287
400
  /** Launch each configured server and size its tool definitions, then add the findings they support. */
288
401
  export async function measureMcpSizes(r) {
@@ -323,12 +436,20 @@ export function renderOverhead(r, home = homedir()) {
323
436
  else {
324
437
  out.push("No Claude Code sessions in the period to measure; memory files are sized below.");
325
438
  }
439
+ for (const o of r.baselines.filter((x) => x.agent !== "Claude Code")) {
440
+ const tokens = r.files.filter((f) => f.agent === o.agent).reduce((s, f) => s + f.tokens, 0);
441
+ out.push("", `${o.agent}, last ${o.days} days: ${o.sessions} sessions start at a median ~${formatTokens(o.median)} tokens (p90 ~${formatTokens(o.p90)}); ${tokens ? `memory files loaded here ~${formatTokens(tokens)} of it` : "no memory files of its own here"}.` +
442
+ (o.usdPerKPerMonth !== undefined
443
+ ? ` Each 1k tokens ~${formatUsd(o.usdPerKPerMonth)} a month (${o.requests.toLocaleString("en-US")} requests, ${o.coldStarts.toLocaleString("en-US")} cold starts, ${o.model} list prices).`
444
+ : ""));
445
+ }
326
446
  out.push(...renderMcp(r));
327
447
  out.push("", "Memory files loaded in this directory", "─".repeat(56));
328
448
  if (r.files.length === 0)
329
449
  out.push(" none");
330
450
  for (const f of r.files) {
331
- const usd = f.agent === "Claude Code" && b?.usdPerKPerMonth !== undefined ? ` ${formatUsd((f.tokens / 1000) * b.usdPerKPerMonth)}/mo` : "";
451
+ const fb = r.baselines.find((x) => x.agent === f.agent);
452
+ const usd = fb?.usdPerKPerMonth !== undefined ? ` ${formatUsd((f.tokens / 1000) * fb.usdPerKPerMonth)}/mo` : "";
332
453
  out.push(` ${f.agent.padEnd(11)} ~${formatTokens(f.tokens).padStart(5)}${usd.padEnd(12)} ${short(f.path)}${f.via === "project" ? "" : ` (${f.via})`}`);
333
454
  }
334
455
  out.push("", `Findings (${r.findings.length})`, "─".repeat(56));
package/dist/pack.d.ts CHANGED
@@ -94,11 +94,6 @@ export declare const PACK_LIMITS: {
94
94
  fileBytes: number;
95
95
  totalBytes: number;
96
96
  };
97
- /**
98
- * Read files and directories (recursively, skipping build and dependency
99
- * folders, binaries, and anything past the size limits) into sources.
100
- * `skipped` says what was left out and why, so nothing vanishes silently.
101
- */
102
97
  export declare function readSources(paths: string[], cwd?: string): {
103
98
  sources: PackSource[];
104
99
  skipped: string[];
package/dist/pack.js CHANGED
@@ -13,6 +13,7 @@
13
13
  * and no model calls. Lexical ranking misses pure paraphrase; the outline that
14
14
  * comes with every result lets the model pick sections by heading when it does.
15
15
  */
16
+ import { spawnSync } from "node:child_process";
16
17
  import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
17
18
  import { basename, extname, join, relative } from "node:path";
18
19
  import { estimateTokens, formatTokens } from "./tokens.js";
@@ -333,6 +334,19 @@ export const PACK_LIMITS = { files: 500, fileBytes: 5 * 1024 * 1024, totalBytes:
333
334
  * folders, binaries, and anything past the size limits) into sources.
334
335
  * `skipped` says what was left out and why, so nothing vanishes silently.
335
336
  */
337
+ /** Files git would consider part of the repository under `dir` (relative to it), or undefined outside git. */
338
+ function gitFiles(dir) {
339
+ try {
340
+ const r = spawnSync("git", ["-C", dir, "ls-files", "-z", "--cached", "--others", "--exclude-standard"], { encoding: "utf8", maxBuffer: 64 * 1024 * 1024, timeout: 30_000 });
341
+ if (r.status !== 0 || typeof r.stdout !== "string")
342
+ return undefined;
343
+ // --cached lists files deleted from the work tree too; only what exists is read.
344
+ return r.stdout.split("\0").filter((f) => f && existsSync(join(dir, f))).sort();
345
+ }
346
+ catch {
347
+ return undefined;
348
+ }
349
+ }
336
350
  export function readSources(paths, cwd = process.cwd()) {
337
351
  const sources = [];
338
352
  const skipped = [];
@@ -354,6 +368,15 @@ export function readSources(paths, cwd = process.cwd()) {
354
368
  if (st.isDirectory()) {
355
369
  if (!top && (SKIP_DIRS.has(basename(p)) || basename(p).startsWith(".")))
356
370
  return;
371
+ // Inside a git repository the repository says what is source: tracked
372
+ // files plus untracked ones not ignored, so .gitignore'd build output,
373
+ // data dumps and secrets stay out. Elsewhere, walk with SKIP_DIRS.
374
+ const listed = top ? gitFiles(p) : undefined;
375
+ if (listed) {
376
+ for (const f of listed)
377
+ visit(join(p, f), false);
378
+ return;
379
+ }
357
380
  for (const e of readdirSync(p).sort())
358
381
  visit(join(p, e), false);
359
382
  return;
package/dist/proxy.d.ts CHANGED
@@ -48,7 +48,7 @@ export interface ProxyOptions extends OptimizeOptions {
48
48
  googleUpstream?: string;
49
49
  }
50
50
  /** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
51
- export declare const PROXY_VERSION = "0.27.0";
51
+ export declare const PROXY_VERSION = "0.28.0";
52
52
  /**
53
53
  * Remove a leading `/t/<token>` from a request path, or return undefined when
54
54
  * the prefix is absent or the token differs. The comparison is constant time
package/dist/proxy.js CHANGED
@@ -20,7 +20,7 @@ import { formatTokens, CHARS_PER_TOKEN, providerFor } from "./tokens.js";
20
20
  import { formatUsd, inputCostUsd, pricingFor } from "./pricing.js";
21
21
  import { recordLedger } from "./ledger.js";
22
22
  /** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
23
- export const PROXY_VERSION = "0.27.0";
23
+ export const PROXY_VERSION = "0.28.0";
24
24
  /** Connection-level headers that must not be forwarded. */
25
25
  const SKIP_REQUEST_HEADERS = new Set(["host", "content-length", "connection", "transfer-encoding", "accept-encoding", "expect"]);
26
26
  const SKIP_RESPONSE_HEADERS = new Set(["content-length", "content-encoding", "transfer-encoding", "connection"]);
package/dist/wrap.d.ts CHANGED
@@ -7,9 +7,12 @@
7
7
  * import { withContextDoctor } from "context-doctor";
8
8
  * const client = withContextDoctor(new Anthropic());
9
9
  *
10
- * Works on the official Anthropic and OpenAI SDK clients (and anything shaped
11
- * like them): messages.create/stream, chat.completions.create/stream/parse and
12
- * responses.create/stream/parse, beta namespaces included. Each request goes
10
+ * Works on the official Anthropic, OpenAI and Google Gen AI SDK clients (and
11
+ * anything shaped like them): messages.create/stream,
12
+ * chat.completions.create/stream/parse, responses.create/stream/parse (beta
13
+ * namespaces included) and models.generateContent/generateContentStream.
14
+ * Gemini chat sessions (ai.chats) keep their history inside the SDK, out of
15
+ * reach; use generateContent with your own history to get autopilot. Each request goes
13
16
  * through the same AutoClearer the proxy uses: stale tool output is cleared
14
17
  * only when the prompt cache is cold, so a request never costs more.
15
18
  *
package/dist/wrap.js CHANGED
@@ -7,9 +7,12 @@
7
7
  * import { withContextDoctor } from "context-doctor";
8
8
  * const client = withContextDoctor(new Anthropic());
9
9
  *
10
- * Works on the official Anthropic and OpenAI SDK clients (and anything shaped
11
- * like them): messages.create/stream, chat.completions.create/stream/parse and
12
- * responses.create/stream/parse, beta namespaces included. Each request goes
10
+ * Works on the official Anthropic, OpenAI and Google Gen AI SDK clients (and
11
+ * anything shaped like them): messages.create/stream,
12
+ * chat.completions.create/stream/parse, responses.create/stream/parse (beta
13
+ * namespaces included) and models.generateContent/generateContentStream.
14
+ * Gemini chat sessions (ai.chats) keep their history inside the SDK, out of
15
+ * reach; use generateContent with your own history to get autopilot. Each request goes
13
16
  * through the same AutoClearer the proxy uses: stale tool output is cleared
14
17
  * only when the prompt cache is cold, so a request never costs more.
15
18
  *
@@ -39,6 +42,9 @@ const WRAPPED = new Set([
39
42
  "responses.create",
40
43
  "responses.stream",
41
44
  "responses.parse",
45
+ // Google's @google/genai: ai.models.generateContent({ model, contents, config })
46
+ "models.generateContent",
47
+ "models.generateContentStream",
42
48
  ]);
43
49
  const PARENTS = new Set([...WRAPPED].flatMap((p) => p.split(".").slice(0, -1).map((_, i, a) => a.slice(0, i + 1).join("."))));
44
50
  const STATS = Symbol.for("context-doctor.stats");
@@ -53,15 +59,22 @@ export function withContextDoctor(client, options = {}) {
53
59
  const prepare = (method, params) => {
54
60
  if (!params || typeof params !== "object" || Array.isArray(params))
55
61
  return params;
62
+ // Copy the top level and deep-clone only the history, the one part
63
+ // autopilot rewrites: the rest can hold things that do not clone
64
+ // (an AbortSignal or callable tools in @google/genai's config).
65
+ stats.requests++;
66
+ const src = params;
67
+ const field = ["messages", "input", "contents"].find((k) => Array.isArray(src[k]));
68
+ if (!field)
69
+ return params;
56
70
  let body;
57
71
  try {
58
- body = structuredClone(params);
72
+ body = { ...src, [field]: structuredClone(src[field]) };
59
73
  }
60
74
  catch {
61
- return params; // something uncloneable (a function, a stream): leave the request alone
75
+ return params; // something uncloneable inside the history: leave the request alone
62
76
  }
63
77
  const result = clearer.apply(body);
64
- stats.requests++;
65
78
  if (result.changed) {
66
79
  stats.changed++;
67
80
  stats.tokensRemoved += result.tokensRemoved;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "context-doctor",
3
- "version": "0.27.0",
3
+ "version": "0.28.0",
4
4
  "description": "Cut your Claude Code bill, measured on your own sessions: `npx context-doctor savings` shows what each lever saves, then the hook, autopilot and an earlier auto-compact window do it. Also Cursor, Codex, Claude Desktop and any Anthropic or OpenAI API app. MCP server and Claude Code plugin.",
5
5
  "keywords": [
6
6
  "agent",