context-doctor 0.36.0 → 0.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +25 -15
  2. package/dist/autoclear.d.ts +11 -4
  3. package/dist/autoclear.js +52 -6
  4. package/dist/autopilot.d.ts +24 -0
  5. package/dist/autopilot.js +108 -0
  6. package/dist/cachemisses.d.ts +104 -2
  7. package/dist/cachemisses.js +199 -11
  8. package/dist/cli.js +172 -12
  9. package/dist/compact.d.ts +36 -0
  10. package/dist/compact.js +144 -0
  11. package/dist/compactwindow.d.ts +1 -1
  12. package/dist/compactwindow.js +6 -1
  13. package/dist/doctor.js +58 -1
  14. package/dist/extract.d.ts +23 -0
  15. package/dist/extract.js +121 -4
  16. package/dist/fanout.d.ts +131 -0
  17. package/dist/fanout.js +317 -0
  18. package/dist/fileparams.d.ts +61 -0
  19. package/dist/fileparams.js +308 -0
  20. package/dist/handoff.d.ts +143 -0
  21. package/dist/handoff.js +539 -0
  22. package/dist/hook.js +15 -0
  23. package/dist/httpguard.d.ts +56 -0
  24. package/dist/httpguard.js +141 -0
  25. package/dist/install.js +17 -5
  26. package/dist/ledger.d.ts +2 -0
  27. package/dist/ledger.js +44 -7
  28. package/dist/lens.d.ts +56 -0
  29. package/dist/lens.js +213 -0
  30. package/dist/limits.d.ts +229 -0
  31. package/dist/limits.js +869 -0
  32. package/dist/mcp.d.ts +3 -0
  33. package/dist/mcp.js +79 -56
  34. package/dist/mcpschema.d.ts +25 -1
  35. package/dist/mcpschema.js +78 -25
  36. package/dist/overhead.js +7 -6
  37. package/dist/pack.d.ts +20 -0
  38. package/dist/pack.js +29 -1
  39. package/dist/precompact.js +8 -7
  40. package/dist/preferences.d.ts +3 -1
  41. package/dist/preferences.js +8 -6
  42. package/dist/pricing.d.ts +29 -2
  43. package/dist/pricing.js +46 -8
  44. package/dist/proxy.d.ts +5 -3
  45. package/dist/proxy.js +12 -7
  46. package/dist/prune.d.ts +116 -0
  47. package/dist/prune.js +428 -0
  48. package/dist/recall.d.ts +104 -0
  49. package/dist/recall.js +393 -0
  50. package/dist/rules.d.ts +7 -4
  51. package/dist/rules.js +12 -8
  52. package/dist/savings.d.ts +1 -1
  53. package/dist/savings.js +11 -1
  54. package/dist/session.js +6 -13
  55. package/dist/sketch.d.ts +5 -1
  56. package/dist/sketch.js +23 -7
  57. package/dist/statusline.d.ts +6 -0
  58. package/dist/statusline.js +9 -0
  59. package/dist/subagentpay.d.ts +11 -0
  60. package/dist/subagentpay.js +1 -1
  61. package/package.json +1 -1
  62. package/skills/context-doctor/SKILL.md +3 -0
package/README.md CHANGED
@@ -24,7 +24,7 @@ Pick where you work. Each takes about a minute and is fully reversible.
24
24
  | **Everything on this machine at once** | `npm install -g context-doctor && context-doctor install` wires Claude Code, Claude Desktop, Cursor, Codex, Gemini CLI and GitHub Copilot: MCP server, skill and hooks ([what it writes](./docs/install.md)). `context-doctor doctor` checks it; `context-doctor uninstall` removes it. Then, for Claude Code in a terminal or IDE, `context-doctor autopilot on` |
25
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
26
  | **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)) |
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())` ([library](./docs/library.md)) |
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://127.0.0.1:8787`. No proxy possible? Wrap the SDK client: `withContextDoctor(new Anthropic())` ([library](./docs/library.md)) |
28
28
  | **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) |
29
29
  | **GitHub pull requests** | `uses: KushalP1/context-doctor@v0.32.0` comments how much a PR grows CLAUDE.md, AGENTS.md and rules, and can fail over a budget ([setup](./docs/ci.md)) |
30
30
 
@@ -35,16 +35,19 @@ Pick where you work. Each takes about a minute and is fully reversible.
35
35
  - `overhead`: what every request re-reads before your message (system prompt, tools, MCP servers, CLAUDE.md, rules, memory), each file priced per month.
36
36
  - `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.
37
37
  - `cache-misses`: requests that re-wrote the prompt cache while it should still have been warm, priced, by model and context size, with the cause where the transcript shows one.
38
+ - `limits`: your plan's 5-hour and weekly windows (Claude Pro/Max, recorded by the status line) and Codex's, the pace and when each runs out, and what 1M tokens of each kind cost in % of the limit, fitted on your own readings with the error shown.
38
39
  - `cache-plan <request.json>`: where an Anthropic API request should carry `cache_control`, and what it saves over N calls.
39
40
  - `session`, `watch`, `analyze`, `report`, `dashboard`: token breakdown and wasted-context findings for any session, conversation file or agent trace.
40
41
 
41
42
  **Keep waste out of the context** ([pack and overhead](./docs/pack-and-overhead.md))
42
43
  - `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.
44
+ - `recall` (and the `recall` MCP tool): the few lines of this session's own transcript a question needs, including turns a compaction summarised away and tool output autopilot cleared, with their time and position; secrets masked.
43
45
  - `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.
44
46
  - `ci` and the GitHub Action: review memory-file growth like any other cost.
45
47
 
46
48
  **Remove waste automatically**
47
49
  - A model-switch warning (`PreModelSwitch`, Claude Code 2.1.251+) shows what a `/model` switch costs before it happens: the whole context re-written into the new model's cache.
50
+ - A subagent price (`PreToolUse` on the Agent tool) shows what a subagent costs before it starts, at your own median for that type (the author's: $3.99 for general-purpose, $1.43 for Explore, 422 runs in 30 days), with the Sonnet price where it would run on Opus or Fable, and a total when launches bunch up. It never blocks.
48
51
  - A compaction hook (`PreCompact`) tells each Claude Code compaction what the session cannot lose (files changed, open tasks, your instructions, failing tests), so compacting saves tokens without losing the thread.
49
52
  - 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.
50
53
  - `compact-window`: sets Claude Code's own auto-compact window, measured on your history first. Works in the desktop app too.
@@ -100,21 +103,24 @@ On a Claude subscription you do not pay list price; the same tokens come out of
100
103
  | **Cursor** (agent) | A native **after-tool-call hook** (`~/.cursor/hooks.json`): in a heavy chat the agent gets the same hygiene guidance and the largest waste, once per 40% of growth. (Cursor's prompt hook can only allow or block a prompt, so this is the event where guidance reaches the model) | MCP tools, editor status bar extension, `cursor` profiler. With your own OpenAI key, autopilot too via a tokened tunnel ([how](./docs/proxy.md#putting-the-proxy-on-a-public-url-cursor-with-your-own-openai-key-remote-apps)) |
101
104
  | **Codex** (ChatGPT app's Codex tab, IDE extension, CLI) | Every-prompt hook with the API's own token counts | MCP tools, skill, `session` reads Codex rollouts. On an API key, autopilot too (`autopilot on` sets `openai_base_url` in `~/.codex/config.toml`; Codex no longer reads `OPENAI_BASE_URL`) |
102
105
  | **Gemini CLI** | Every-prompt hook (`BeforeAgent`) with the API's own token counts. On an API key, autopilot too: `GOOGLE_GEMINI_BASE_URL=http://127.0.0.1:8787` (Google sign-in traffic goes elsewhere) | MCP tools, `session` and `watch` read its chats, `overhead` sizes GEMINI.md |
103
- | **GitHub Copilot** (Copilot CLI, the Copilot app, VS Code agent sessions) | A **session-start hook** (`~/.copilot/hooks/context-doctor.json`) gives every new or resumed session the five standing rules. No size check: Copilot passes a transcript only to hooks that cannot add context | MCP tools (`~/.copilot/mcp-config.json`, which VS Code's Copilot sessions read too) |
106
+ | **GitHub Copilot** (Copilot CLI, the Copilot app, VS Code agent sessions) | A **session-start hook** (`~/.copilot/hooks/context-doctor.json`) gives every new or resumed session the standing rules. No size check: Copilot passes a transcript only to hooks that cannot add context | MCP tools (`~/.copilot/mcp-config.json`, which VS Code's Copilot sessions read too) |
104
107
  | **Your own apps on the Anthropic, OpenAI or Gemini API** | Autopilot on `/v1/messages`, `/v1/chat/completions`, `/v1/responses` and Gemini's `generateContent` (`ANTHROPIC_BASE_URL` / `OPENAI_BASE_URL` / `GOOGLE_GEMINI_BASE_URL`), or the optimizing proxy (which can cost more on cached traffic); no proxy possible (serverless, edge)? `withContextDoctor(client)` runs autopilot inside the SDK client | Exact usage and cache hit rates in `/stats`, prompt-cache placement advice ([proxy](./docs/proxy.md)) |
105
- | **Claude Desktop chat** | The five standing rules below in every chat; one cheap `profile_context` call the model makes once at ~30 turns and on any cost question; `pack_context` instead of reading a big local file whole | One-click `.mcpb` install, `context_checkup` prompt ([chat apps](./docs/chat-apps.md)) |
108
+ | **Claude Desktop chat** | The six standing rules below, sent to every chat (whether classic Chat shows them to the model is unverified, [why](./docs/chat-apps.md)); one cheap `profile_context` call the model makes once at ~30 turns and on any cost question; `pack_context` instead of reading a big local file whole; a handoff offered once a chat is long, since a chat's history cannot be cut and a new chat can | One-click `.mcpb` install, `context_checkup`, `handoff` and `ask_file` prompts, `handoff://latest` to attach in the next chat ([handoff](./docs/handoff.md)) |
106
109
  | **claude.ai, ChatGPT, the phone apps** | Your account's standing preferences, pasted once ([Quick start](#quick-start)) | Profile an exported chat with `analyze` or `session` |
107
110
  | **CI** | `analyze --fail-over-budget` fails a build whose prompts outgrow a budget; the GitHub Action gates memory-file growth | `.contextdoctorrc` budgets and presets ([CI](./docs/ci.md)) |
108
111
 
109
112
  Not claimed, because no process on your machine sends those requests: trimming inside Claude Desktop chat, claude.ai, ChatGPT, Cursor's own subscription models, or Codex signed in with ChatGPT. Those get the rules and the measurements above, not autopilot.
110
113
 
111
- The MCP server hands these standing rules, verbatim, to every chat where it is enabled (Claude Desktop, Cursor and Claude Code put them in front of the model):
114
+ The MCP server hands these standing rules, verbatim, to every chat where it is enabled (Cursor and Claude Code put them in front of the model; for Claude Desktop's classic Chat that is [unverified](./docs/chat-apps.md)):
112
115
 
113
- > 1. When asked about tokens, cost, speed or limits, and once at ~30 turns or 3+ large pastes: call profile_context BEFORE answering; act on its top finding. In a chat app pass a `sketch` (turns + big blocks). Do not estimate token counts yourself.
114
- > 2. Summarize any paste or tool result over ~2k tokens into the points you need; keep it verbatim only to edit or quote it exactly.
115
- > 3. Refer to earlier content by name; never re-quote it or inline base64.
116
- > 4. To answer from a big file or folder you won't edit, call pack_context with the question; don't read it whole.
117
- > 5. If optimize_context returns a pruned-turns digest, write its ≤150-token summary.
116
+ > 1. When asked about tokens, cost, speed or limits, and once at ~30 turns or 3+ large pastes: call profile_context BEFORE answering; in a chat app pass a `sketch`. Act on its top finding. Do not estimate token counts yourself.
117
+ > 2. When a chat grows long, offer a handoff once (save_handoff): only a new chat cuts its history.
118
+ > 3. Summarize any paste or tool result over ~2k tokens into the points you need.
119
+ > 4. Refer to earlier content by name; never re-quote it or inline base64.
120
+ > 5. For a big file you won't edit, call pack_context with the question; don't read it whole.
121
+ > 6. If optimize_context returns a pruned-turns digest, write its ≤150-token summary.
122
+
123
+ Rules 1-4 end exactly at character 512, the part ChatGPT's guide says must stand alone.
118
124
 
119
125
  ## Commands
120
126
 
@@ -126,23 +132,27 @@ The MCP server hands these standing rules, verbatim, to every chat where it is e
126
132
  | `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)) |
127
133
  | `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)) |
128
134
  | `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 |
129
- | `context-doctor instructions [--copy]` | The ~185-token standing rules (~125 on GPT) for claude.ai / ChatGPT preferences, for web and phones where no server runs |
135
+ | `context-doctor instructions [--copy]` | The ~190-token standing rules (~130 on GPT) for claude.ai / ChatGPT preferences, for web and phones where no server runs |
136
+ | `context-doctor handoff [list\|show <id>\|latest] [--copy]` | Handoffs saved from chat apps (the `handoff` prompt or `save_handoff`): list them, print one, or copy it to paste as a new chat's first message ([handoff](./docs/handoff.md)) |
130
137
  | `context-doctor mcp [--http]` | The MCP server as a subcommand, for clients and registries that launch `npx -y context-doctor mcp` |
131
- | `context-doctor-mcp` | The MCP server itself — stdio by default (what the installer wires); `--http [--port 8808] [--host H]` serves streamable HTTP at `/mcp` for URL-based clients like ChatGPT developer-mode connectors |
132
- | `context-doctor session [file]` | Profile a Claude Code session: live context, findings, **measured tokens and prompt-cache economics**, **where the wall clock went** per tool, and **what its subagents cost** (their own windows, your bill; never in the parent's profile). Also reads Codex rollouts, Gemini CLI chats and ChatGPT data exports (`conversations.json`); `--list` to browse |
138
+ | `context-doctor-mcp` | The MCP server itself — stdio by default (what the installer wires); `--http [--port 8808] [--host H] [--allowed-hosts names] [--store-handoffs]` serves streamable HTTP at `/mcp` for URL-based clients like ChatGPT developer-mode connectors (only for the host names it knows: behind a tunnel, pass its name to `--allowed-hosts`) |
139
+ | `context-doctor session [file]` | Profile a Claude Code session: live context, findings, **measured tokens and prompt-cache economics**, **where the wall clock went** per tool, output's and reasoning's share of the cost, repeated identical (polling) tool calls priced, and **what its subagents cost** (their own windows, your bill; never in the parent's profile). Also reads Codex rollouts, Gemini CLI chats and ChatGPT data exports (`conversations.json`); `--list` to browse |
133
140
  | `context-doctor watch [file]` | Live monitor of a growing session transcript or agent trace (Claude Code / Codex JSONL, or a plain OpenAI/Anthropic conversation JSON file): token/cost line per change, findings as they appear |
134
141
  | `context-doctor cursor [--list]` | Profile a chat from Cursor's local history (both storage formats) |
135
142
  | `context-doctor analyze <file>` | Profile a conversation: token breakdown, findings, cost + latency estimates. `--exact` adds a true count; `--fail-over-budget` exits 1 on a breach, for CI |
136
143
  | `context-doctor optimize <file>` | Apply the safe fixes; add `--strategy trim-tool-calls` for big inline file writes, `--strategy prune-history` for consented lossy compaction ([what each does](./docs/detectors.md)) |
137
144
  | `context-doctor diff <before> <after>` | Compare two profiles: what moved by category, which findings were resolved or introduced, and what it saves in money and latency |
138
145
  | `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 |
146
+ | `context-doctor overhead prune [--days n] [--write] [--undo]` | Per project, the MCP servers and skills its sessions never used in n days; `--write` switches them off for this folder's project in its `.claude/settings.local.json` (backup kept, every entry recorded), `--undo` takes exactly those out. Never the app's connectors, plugins, or context-doctor itself |
139
147
  | `context-doctor overhead split <file> [--min-tokens n] [--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 |
140
148
  | `context-doctor pack <files\|dirs\|-> -q "…"` | 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. `--semantic` also ranks by meaning with a local Ollama model. Offline, no key |
149
+ | `context-doctor recall "<query>" [--session <id\|path>]` | Search this session's own transcript on disk (Claude Code or Codex; turns before a compaction and tool output cleared from the context included) and print the best excerpts with time and position, secrets masked. Never another project's session unless named with `--session`. Also the `recall` MCP tool |
141
150
  | `context-doctor tasks [--days n]` | Cost per commit, per project: each session priced from its recorded usage against the commits it made |
142
151
  | `context-doctor reads [--days n] [--limit n]` | Files read into session after session: reads, tokens, cost, and whether a CLAUDE.md summary or `pack` pays |
143
152
  | `context-doctor subagents [--days n]` | Which subagents paid for themselves: each one's bill vs the same steps run in the parent session |
144
153
  | `context-doctor compactions [--days n]` | Do sessions work worse right after compacting? Re-reads, tool errors and your corrections, before vs after each compaction |
145
- | `context-doctor cache-misses [--days n]` | Requests that re-wrote the prompt cache within its lifetime (no compaction between, previous context over 20k, over 60% of it written again): priced above the cache-read rate, by model and context size, with the cause where visible and the model versions that miss less; `--json` per model |
154
+ | `context-doctor cache-misses [--days n]` | Requests that re-wrote the prompt cache within its lifetime (no compaction between, previous context over 20k, over 60% of it written again): priced above the cache-read rate, by model and context size, with the cause where visible and the model versions that miss less; by Claude Code version, with step changes after an upgrade flagged (the 1-hour cache share, the first request's size, a model's miss rate); `--json` per model and version |
155
+ | `context-doctor limits [--days n]` | Your plan's limits in their own unit: each window's %, pace and run-out time (Claude's 5-hour and weekly windows from the status line's readings, Codex's from its rollouts), and % of the limit per 1M tokens of input, cache read, cache write and output, fitted on your readings with the fit's error; too-thin data is said to be thin, never quoted |
146
156
  | `context-doctor cache-plan <request.json> [--calls n] [--out file] [--explicit]` | Where an Anthropic API request should carry `cache_control` (top-level automatic caching for the moving end, unless `--explicit`), and what it saves over n calls; `--out` writes it applied |
147
157
  | `context-doctor accuracy` | How much of what you are billed for is visible in your transcript (the fixed harness baseline, per-turn injected content), plus a tokenizer check: real chars/token per model from the API's own counts, next to the ratio the estimator uses |
148
158
  | `context-doctor report` | Machine-wide impact report (proxy savings persist across restarts): exact proxy savings, hook activity, how often the cold-resume `/compact` offer was followed by a compaction, recoverable waste in recent sessions |
@@ -159,8 +169,8 @@ The MCP server hands these standing rules, verbatim, to every chat where it is e
159
169
 
160
170
  ## What's new
161
171
 
162
- - **0.36 GitHub Copilot, and a quality test for every lever**: `install` wires GitHub Copilot (CLI, app, VS Code agent sessions): the MCP server, and a session-start hook that gives each new or resumed session the standing rules (no size check: Copilot gives no transcript to the hooks that could add context). `context-doctor ab` runs eight small coding tasks, scored by hidden checks, with and without each lever (the standing rules, autopilot's clearing, `pack_context`, the PreCompact instructions) through the Messages API and puts pass counts, tokens and cost side by side; it bills your key, prints the estimate first, sends nothing without `--yes` and never passes `--budget` ([details](./docs/ab.md)). Not yet run on a real key, so no pass rates are claimed.
163
- - **0.35 Cache misses, a price before a model switch, and a QA pass fixed**: `context-doctor cache-misses` finds requests that re-wrote the prompt cache while it was still warm (on the author's history: 390 such misses, $1,925 above the cache-read price, 28% of all cache writes; claude-sonnet-5 missed on 10.4% of warm requests, claude-opus-5-5 on 0.11%) and says which model versions miss less; `savings` mentions them when they add up. On Claude Code 2.1.251+ a `PreModelSwitch` hook shows what a `/model` switch will cost before it happens. `pack` no longer reads `.env`, `.npmrc`, private keys or other credential files unless you pass `--include-secrets`, refuses `~/.ssh`-style folders, and survives unreadable files. Fixed from a QA pass: rc values warned as ignored were applied, near-duplicates were counted per pair (781 findings), autopilot's cleared results leaked between conversations reusing tool ids, a malformed config stopped `uninstall` midway, and more ([list](./ROADMAP.md#shipped-in-0350-cache-misses-a-model-switch-price-and-a-qa-pass)).
172
+ - **0.38 Your limits in their own unit, regressions after upgrades, recall, and a subagent price**: `context-doctor limits` shows each plan window's %, pace and run-out time (Claude Pro/Max through the status line, Codex from its rollouts) and what 1M tokens cost in % of it, fitted on your readings with the error; `savings` then speaks in your limit too. `cache-misses` flags step changes after a Claude Code upgrade, `recall` searches the session's own transcript (compacted turns included), a hook prices a subagent before it starts (never blocking), and `overhead prune` switches off unused MCP servers and skills per project, reversibly. OpenAI caches count as warm for up to 24 hours. An independent QA pass's findings were fixed before the release ([what's new](./docs/whats-new.md)).
173
+ - **0.37 Desktop chat apps: a handoff, uploads, compact results, and a security pass**: a chat app's history cannot be edited, so the `handoff` prompt (Claude Desktop's **+** menu) has the model write a ≤400-token brief and save it with `save_handoff` (secrets masked, `handoff://latest` to attach in the next chat, the per-turn saving reported: a 52k-token chat drops to ~600). `ask_file` answers from a big file through `pack_context`, which over `--http` also takes ChatGPT uploads; ChatGPT gets compact results. An independent QA pass's eleven findings were fixed with tests; **behind a tunnel, `--http` now needs `--allowed-hosts <tunnel host>`** ([handoff](./docs/handoff.md)).
164
174
 
165
175
  Every release: [docs/whats-new.md](./docs/whats-new.md).
166
176
 
@@ -130,14 +130,15 @@ interface View {
130
130
  seenUpTo: number;
131
131
  ttlMs: number;
132
132
  }
133
- export declare function clearedNote(tokens: number): string;
133
+ export declare function clearedNote(tokens: number, recall?: boolean): string;
134
+ /** GPT-5.6 or later (gpt-5.6-sol, gpt-6.1-sol...): the models that take prompt_cache_options. */
135
+ export declare function openAICacheOptionsModel(model: unknown): boolean;
134
136
  /**
135
137
  * How long the provider may keep this prompt cached, taking the LONGER
136
138
  * possibility when unsure: calling a warm cache cold would pay a rewrite,
137
139
  * calling a cold one warm only delays a free clearing.
138
140
  * - Anthropic: the request's own cache_control, "1h" or the 5-minute default.
139
- * - OpenAI: caches live up to an hour (in-memory retention), or 24 hours when
140
- * the request sets prompt_cache_retention "24h".
141
+ * - OpenAI: see openAITtlMs (24 hours unless the request says otherwise).
141
142
  */
142
143
  export declare function requestTtlMs(body: Record<string, unknown>): number;
143
144
  export declare function viewOf(body: Record<string, unknown>): View | undefined;
@@ -160,8 +161,14 @@ export declare class AutoClearer {
160
161
  * OpenAI Responses request. Never throws; anything unrecognised is left alone.
161
162
  * `account` names the credential the request carries (the proxy passes a
162
163
  * salted hash), for accounts whose API rejects edited history.
164
+ * `recallHint`: the client keeps a transcript recall can search (Claude
165
+ * Code); the cleared note then says where the full output still is. It
166
+ * must be the same on every request of a conversation (the note is part of
167
+ * the cached prefix), which a client's User-Agent is.
163
168
  */
164
- apply(body: Record<string, unknown>, now?: number, modelHint?: string, account?: string): AutoClearResult;
169
+ apply(body: Record<string, unknown>, now?: number, modelHint?: string, account?: string, opts?: {
170
+ recallHint?: boolean;
171
+ }): AutoClearResult;
165
172
  /**
166
173
  * Warm cache: clearing rewrites everything after the first cleared result
167
174
  * at the write rate (1.25x instead of 0.1x: 1.15x extra, once), and saves
package/dist/autoclear.js CHANGED
@@ -93,9 +93,14 @@ function lastIndex(items, pred) {
93
93
  return i;
94
94
  return -1;
95
95
  }
96
- export function clearedNote(tokens) {
96
+ export function clearedNote(tokens, recall = false) {
97
97
  // Not "run it again": a cleared Bash result may come from a command with
98
98
  // side effects (a push, a delete), and repeating that would be wrong.
99
+ // Claude Code keeps the original output in its transcript on disk, where
100
+ // recall finds it; other clients may keep no transcript, so they are not
101
+ // pointed there.
102
+ if (recall)
103
+ return `[context-doctor: old tool output cleared to keep context lean (~${tokens} tokens). The call above shows what ran; the full output is in the session transcript (the recall tool, or npx context-doctor recall "<words>"). Repeat the call only if it is read-only, otherwise ask the user.]`;
99
104
  return `[context-doctor: old tool output cleared to keep context lean (~${tokens} tokens). The call above shows what ran; repeat it only if it is read-only, otherwise ask the user.]`;
100
105
  }
101
106
  function resultTokens(content, model) {
@@ -114,13 +119,50 @@ function resultTokens(content, model) {
114
119
  }
115
120
  return n;
116
121
  }
122
+ /** GPT-5.6 or later (gpt-5.6-sol, gpt-6.1-sol...): the models that take prompt_cache_options. */
123
+ export function openAICacheOptionsModel(model) {
124
+ const m = /gpt-(\d+)(?:\.(\d+))?/i.exec(typeof model === "string" ? model : "");
125
+ if (!m)
126
+ return false;
127
+ const major = Number(m[1]), minor = Number(m[2] ?? 0);
128
+ return major > 5 || (major === 5 && minor >= 6);
129
+ }
130
+ /**
131
+ * How long OpenAI may keep this request's prompt cached, the longest it
132
+ * plausibly could. From OpenAI's prompt caching guide (read 2026-10-26):
133
+ * - GPT-5.6 and later set the lifetime with `prompt_cache_options.ttl`
134
+ * ("30m", the default, or "12h") and per breakpoint with
135
+ * `prompt_cache_breakpoint.ttl`; both are minimums ("OpenAI may retain
136
+ * entries longer than the requested minimum"; "12h" "does not set a
137
+ * deletion deadline"). Measured on the author's Codex history (gpt-5.6-sol,
138
+ * no ttl set): requests after 48- and 83-minute gaps read 100% from cache.
139
+ * - Earlier models use `prompt_cache_retention`: "in_memory" lasts "up to one
140
+ * hour", "24h" up to 24 hours, and organizations without Zero Data
141
+ * Retention default to "24h".
142
+ * - Any entry: "a maximum retention period of 24 hours".
143
+ * So 24 hours, unless the request asks an earlier model for "in_memory" (one
144
+ * hour; not GPT-5.5 or 5.5 Pro, which "support only 24h"), or uses explicit
145
+ * mode with no breakpoint, which caches nothing.
146
+ * Through 0.37 this was one hour unless "24h": a GPT-5.6 cache still warm at
147
+ * 83 minutes was called cold, and clearing it paid a rewrite.
148
+ */
149
+ function openAITtlMs(body) {
150
+ const options = body.prompt_cache_options;
151
+ const history = JSON.stringify(body.input ?? body.messages ?? "");
152
+ if (options && typeof options === "object" && options.mode === "explicit" && !history.includes('"prompt_cache_breakpoint"'))
153
+ return 0;
154
+ // GPT-5.5 and GPT-5.5 Pro support only "24h": an "in_memory" there is not what the cache does.
155
+ const only24h = /gpt-5\.5(?![\d.])/i.test(typeof body.model === "string" ? body.model : "");
156
+ if (!openAICacheOptionsModel(body.model) && !only24h && !options && body.prompt_cache_retention === "in_memory" && !history.includes('"prompt_cache_breakpoint"'))
157
+ return HOUR;
158
+ return 24 * HOUR;
159
+ }
117
160
  /**
118
161
  * How long the provider may keep this prompt cached, taking the LONGER
119
162
  * possibility when unsure: calling a warm cache cold would pay a rewrite,
120
163
  * calling a cold one warm only delays a free clearing.
121
164
  * - Anthropic: the request's own cache_control, "1h" or the 5-minute default.
122
- * - OpenAI: caches live up to an hour (in-memory retention), or 24 hours when
123
- * the request sets prompt_cache_retention "24h".
165
+ * - OpenAI: see openAITtlMs (24 hours unless the request says otherwise).
124
166
  */
125
167
  export function requestTtlMs(body) {
126
168
  // Gemini: implicit caching's lifetime is not published, explicit caches default to an hour.
@@ -128,7 +170,7 @@ export function requestTtlMs(body) {
128
170
  return HOUR;
129
171
  const openai = Array.isArray(body.input) || (Array.isArray(body.messages) && isOpenAIChat(body.messages));
130
172
  if (openai)
131
- return body.prompt_cache_retention === "24h" ? 24 * HOUR : HOUR;
173
+ return openAITtlMs(body);
132
174
  // Automatic caching puts cache_control at the top level of the request; a
133
175
  // 1-hour cache marked there was read as the 5-minute default, so autopilot
134
176
  // could clear into a cache that was still warm.
@@ -290,8 +332,12 @@ export class AutoClearer {
290
332
  * OpenAI Responses request. Never throws; anything unrecognised is left alone.
291
333
  * `account` names the credential the request carries (the proxy passes a
292
334
  * salted hash), for accounts whose API rejects edited history.
335
+ * `recallHint`: the client keeps a transcript recall can search (Claude
336
+ * Code); the cleared note then says where the full output still is. It
337
+ * must be the same on every request of a conversation (the note is part of
338
+ * the cached prefix), which a client's User-Agent is.
293
339
  */
294
- apply(body, now = Date.now(), modelHint, account) {
340
+ apply(body, now = Date.now(), modelHint, account, opts = {}) {
295
341
  const none = (reason, cold = false) => ({ changed: false, newlyCleared: 0, tokensRemoved: 0, cold, reason, firstChanged: -1, newIds: [], appliedIds: [] });
296
342
  try {
297
343
  const view = viewOf(body);
@@ -369,7 +415,7 @@ export class AutoClearer {
369
415
  const sk = scoped(key, r.id);
370
416
  if (!this.cleared.has(sk) || !eligibleIds.has(r.id))
371
417
  continue;
372
- const note = clearedNote(this.cleared.get(sk));
418
+ const note = clearedNote(this.cleared.get(sk), opts.recallHint === true);
373
419
  if (r.content === note)
374
420
  continue;
375
421
  removed += Math.max(0, r.tokens - estimateTokens(note, model));
@@ -67,6 +67,30 @@ export interface Health {
67
67
  version?: string;
68
68
  }
69
69
  export declare function health(port: number, timeoutMs?: number): Promise<Health>;
70
+ /** Who holds a local port: nobody, our proxy, or another program (named when it says). */
71
+ export interface PortOccupant {
72
+ /** Something answers a connection to 127.0.0.1:port. */
73
+ listening: boolean;
74
+ ours: boolean;
75
+ /** What the other program calls itself: its /health service, its Server header, or its process name. */
76
+ name?: string;
77
+ pid?: number;
78
+ /**
79
+ * Whether the proxy could bind 127.0.0.1:port beside it. On macOS a
80
+ * listener on 0.0.0.0, :: or ::1 leaves 127.0.0.1 free (the more specific
81
+ * address wins for 127.0.0.1 traffic); on Linux a 0.0.0.0 listener does not.
82
+ */
83
+ bindable?: boolean;
84
+ /** Another program on [::1]:port, where `localhost` may resolve, while 127.0.0.1 is ours or free. */
85
+ onIpv6Loopback?: string;
86
+ }
87
+ /**
88
+ * Whether something already listens on 127.0.0.1:`port`, whether it is this
89
+ * proxy (by its /health, however slowly it answers), whether the proxy could
90
+ * still bind 127.0.0.1 beside it, and whether another program holds
91
+ * [::1]:port, where `localhost` may go. Headroom's default port is 8787 too.
92
+ */
93
+ export declare function portOccupant(port: number, timeoutMs?: number): Promise<PortOccupant>;
70
94
  export declare function baseUrlToRestore(paths: AutopilotPaths, port: number, current: string | null): string | null;
71
95
  /** Which Claude Code surfaces ran recent sessions: entrypoint -> count. */
72
96
  export declare function recentSurfaces(days?: number, home?: string): Map<string, number>;
package/dist/autopilot.js CHANGED
@@ -270,6 +270,114 @@ export async function health(port, timeoutMs = 800) {
270
270
  return { ok: false };
271
271
  }
272
272
  }
273
+ const isOurHealth = (j) => j?.service === "context-doctor-proxy";
274
+ /** GET a local URL's /health (or /) and say who it is, without throwing. */
275
+ async function probe(base, timeoutMs) {
276
+ for (const path of ["/health", "/"]) {
277
+ try {
278
+ const r = await fetch(`${base}${path}`, { signal: AbortSignal.timeout(timeoutMs) });
279
+ const text = (await r.text()).slice(0, 2000);
280
+ let j;
281
+ try {
282
+ j = JSON.parse(text);
283
+ }
284
+ catch { /* not JSON */ }
285
+ if (isOurHealth(j))
286
+ return { ours: true };
287
+ const service = j?.service ?? j?.name ?? j?.app;
288
+ const named = typeof service === "string" && service.trim() ? service : /headroom/i.test(text) ? "headroom" : r.headers.get("server") ?? undefined;
289
+ if (named)
290
+ return { ours: false, name: named.replace(/[\u0000-\u001f]/g, "").slice(0, 60) };
291
+ if (path === "/")
292
+ return { ours: false };
293
+ }
294
+ catch {
295
+ /* not HTTP, or slow */
296
+ }
297
+ }
298
+ return undefined;
299
+ }
300
+ async function connects(host, port, timeoutMs) {
301
+ const { createConnection } = await import("node:net");
302
+ return new Promise((resolve) => {
303
+ const socket = createConnection({ host, port });
304
+ const done = (v) => { socket.destroy(); resolve(v); };
305
+ socket.setTimeout(timeoutMs, () => done(false));
306
+ socket.once("connect", () => done(true));
307
+ socket.once("error", () => done(false));
308
+ });
309
+ }
310
+ async function canBind(port) {
311
+ const { createServer } = await import("node:net");
312
+ return new Promise((resolve) => {
313
+ const s = createServer();
314
+ s.once("error", () => resolve(false));
315
+ s.listen(port, "127.0.0.1", () => s.close(() => resolve(true)));
316
+ });
317
+ }
318
+ /** The process listening on a TCP port: lsof on macOS and Linux, netstat and tasklist on Windows; nothing when neither can say. */
319
+ function listenerProcess(port) {
320
+ try {
321
+ if (platform() === "win32") {
322
+ const net = execFileSync("netstat", ["-ano", "-p", "TCP"], { encoding: "utf8", timeout: 3000, stdio: ["ignore", "pipe", "ignore"] });
323
+ const line = net.split(/\r?\n/).find((l) => new RegExp(`:${port}\\s+\\S+\\s+LISTENING\\s+\\d+`, "i").test(l));
324
+ const pid = Number(/LISTENING\s+(\d+)/i.exec(line ?? "")?.[1]);
325
+ if (!(pid > 0))
326
+ return {};
327
+ let command;
328
+ try {
329
+ const task = execFileSync("tasklist", ["/FI", `PID eq ${pid}`, "/FO", "CSV", "/NH"], { encoding: "utf8", timeout: 3000, stdio: ["ignore", "pipe", "ignore"] });
330
+ command = /^"([^"]+)"/.exec(task.trim())?.[1];
331
+ }
332
+ catch { /* the pid alone */ }
333
+ return { pid, command };
334
+ }
335
+ const out = execFileSync("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-Fpc"], { encoding: "utf8", timeout: 2000, stdio: ["ignore", "pipe", "ignore"] });
336
+ const pid = Number(/^p(\d+)/m.exec(out)?.[1]);
337
+ return { pid: pid > 0 ? pid : undefined, command: /^c(.+)$/m.exec(out)?.[1] };
338
+ }
339
+ catch {
340
+ return {}; // no lsof (minimal Linux), no netstat, or nothing it can see
341
+ }
342
+ }
343
+ /**
344
+ * Whether something already listens on 127.0.0.1:`port`, whether it is this
345
+ * proxy (by its /health, however slowly it answers), whether the proxy could
346
+ * still bind 127.0.0.1 beside it, and whether another program holds
347
+ * [::1]:port, where `localhost` may go. Headroom's default port is 8787 too.
348
+ */
349
+ export async function portOccupant(port, timeoutMs = 2000) {
350
+ const h = await health(port, timeoutMs);
351
+ const ipv6 = async () => {
352
+ if (!(await connects("::1", port, 500)))
353
+ return undefined;
354
+ const p = await probe(`http://[::1]:${port}`, timeoutMs);
355
+ return p && !p.ours ? p.name ?? "another program" : undefined;
356
+ };
357
+ if (h.ok) {
358
+ const other = await ipv6();
359
+ return { listening: true, ours: true, ...(other ? { onIpv6Loopback: other } : {}) };
360
+ }
361
+ if (!(await connects("127.0.0.1", port, timeoutMs))) {
362
+ const other = await ipv6();
363
+ return { listening: false, ours: false, ...(other ? { onIpv6Loopback: other } : {}) };
364
+ }
365
+ const who = await probe(proxyUrl(port), timeoutMs);
366
+ // Our own proxy, answering /health too slowly the first time.
367
+ if (who?.ours)
368
+ return { listening: true, ours: true };
369
+ const out = { listening: true, ours: false, bindable: await canBind(port) };
370
+ if (who?.name)
371
+ out.name = who.name;
372
+ const proc = listenerProcess(port);
373
+ if (proc.pid)
374
+ out.pid = proc.pid;
375
+ if (proc.command && !out.name)
376
+ out.name = proc.command.slice(0, 60);
377
+ else if (proc.command && out.name && !out.name.toLowerCase().includes(proc.command.toLowerCase()))
378
+ out.name = `${out.name} (${proc.command.slice(0, 40)})`;
379
+ return out;
380
+ }
273
381
  async function waitHealthy(port, ms) {
274
382
  const end = Date.now() + ms;
275
383
  for (;;) {
@@ -74,15 +74,117 @@ export interface CacheMissReport {
74
74
  recommendations: string[];
75
75
  /** The costliest misses. */
76
76
  largest: CacheMiss[];
77
+ /** The same requests by the Claude Code version that sent them (oldest first). */
78
+ byVersion: VersionStats[];
79
+ /** Step changes from one version to the next that the numbers support. */
80
+ regressions: Regression[];
81
+ }
82
+ /** One Claude Code version's requests (the `version` every transcript line carries). */
83
+ export interface VersionStats {
84
+ version: string;
85
+ /** Main-chain requests, and the transcripts they came from. */
86
+ requests: number;
87
+ sessions: number;
88
+ /** First requests of new sessions: the fixed overhead (system prompt, tools, memory), median. */
89
+ firstRequests: number;
90
+ firstMedian?: number;
91
+ /** Cache-write tokens per request, mean. */
92
+ writesPerRequest: number;
93
+ /** Share of cache writes at the 1-hour TTL (Claude Code's main thread writes almost all at 1 h). */
94
+ oneHourShare?: number;
95
+ /** Warm requests and misses, by the definition above. */
96
+ eligible: number;
97
+ misses: number;
98
+ missRate: number;
99
+ /** The same per model (a version's rate mostly follows the models it ran). */
100
+ byModel: Array<{
101
+ model: string;
102
+ eligible: number;
103
+ misses: number;
104
+ }>;
105
+ /** The 1-hour share per model and surface. */
106
+ ttlBy: Array<{
107
+ key: string;
108
+ requests: number;
109
+ oneHourShare?: number;
110
+ }>;
111
+ /** First and last time the version was seen. */
112
+ from: string;
113
+ to: string;
114
+ }
115
+ export interface Regression {
116
+ metric: "1-hour cache share" | "first request" | "miss rate";
117
+ from: string;
118
+ to: string;
119
+ before: number;
120
+ after: number;
121
+ /** In words, with the numbers. */
122
+ text: string;
77
123
  }
78
124
  /** Misses in one transcript; `since` drops requests before it. */
125
+ /** What `onRequest` is told about each main-chain request in the period. */
126
+ export interface RequestInfo {
127
+ at: number;
128
+ /** The Claude Code version on the transcript line, when recorded. */
129
+ version?: string;
130
+ write: number;
131
+ oneHour: number;
132
+ fiveMinute: number;
133
+ /** The session's first request, minus its first user message: the fixed overhead. Only on that request. */
134
+ first?: number;
135
+ model?: string;
136
+ /** The Claude Code surface (cli, claude-vscode, claude-desktop...): it can choose the cache TTL too. */
137
+ entrypoint?: string;
138
+ }
79
139
  export declare function missesInTranscript(path: string, since?: number, add?: (eligible: {
80
140
  model: string;
81
141
  contextTokens: number;
82
- }, miss?: CacheMiss) => void, onRequest?: (writeUsd: number) => void): void;
142
+ version?: string;
143
+ }, miss?: CacheMiss) => void, onRequest?: (writeUsd: number, info: RequestInfo) => void,
144
+ /** Shared by every transcript of one report: a fork's copied rows (same uuids) have no first request of their own. */
145
+ runRows?: Set<string>): void;
83
146
  export declare function cacheMisses(days?: number, paths?: string[], onProgress?: (done: number, total: number) => void): CacheMissReport;
147
+ interface VersionAcc {
148
+ requests: number;
149
+ sessions: Set<string>;
150
+ firsts: number[];
151
+ writes: number;
152
+ oneHour: number;
153
+ fiveMinute: number;
154
+ eligible: number;
155
+ misses: number;
156
+ /** Warm requests and misses per model: miss rates differ by model far more than by version. */
157
+ byModel: Map<string, {
158
+ eligible: number;
159
+ misses: number;
160
+ }>;
161
+ /** Cache writes by TTL per model and surface: either can change the TTL as much as the version. */
162
+ ttlBy: Map<string, {
163
+ requests: number;
164
+ oneHour: number;
165
+ fiveMinute: number;
166
+ }>;
167
+ from: number;
168
+ to: number;
169
+ }
170
+ /**
171
+ * Per version, oldest first, and the step changes between consecutive
172
+ * versions with enough data (thin versions are skipped over, so a change
173
+ * is credited to the first well-measured version after it):
174
+ * - the 1-hour share of cache writes moving by 30+ points (the TTL
175
+ * regressions users report after upgrades: 1 h to 5 min);
176
+ * - the median first request (fixed overhead) moving by 15% and 3k tokens;
177
+ * - one model's miss rate doubling (or halving), beyond chance at 99%,
178
+ * 5+ misses, 100+ warm requests on each version.
179
+ * Cache writes per request are shown, not flagged (they follow the work).
180
+ */
181
+ export declare function versionReport(versions: Map<string, VersionAcc>): {
182
+ byVersion: VersionStats[];
183
+ regressions: Regression[];
184
+ };
84
185
  /** Worth a line in `savings`: enough misses, and enough money, to act on. */
85
186
  export declare function cacheMissesSignificant(r: CacheMissReport): boolean;
86
187
  /** The one line `savings` adds when the misses are significant. */
87
188
  export declare function cacheMissesLine(r: CacheMissReport): string[];
88
- export declare function renderCacheMisses(r: CacheMissReport): string;
189
+ export declare function renderCacheMisses(r: CacheMissReport, limitLines?: string[]): string;
190
+ export {};