context-doctor 0.33.0 → 0.35.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 (54) hide show
  1. package/README.md +13 -10
  2. package/dist/autoclear.d.ts +5 -2
  3. package/dist/autoclear.js +57 -19
  4. package/dist/autopilot.d.ts +0 -6
  5. package/dist/autopilot.js +37 -2
  6. package/dist/cachekey.d.ts +25 -0
  7. package/dist/cachekey.js +73 -0
  8. package/dist/cachemisses.d.ts +88 -0
  9. package/dist/cachemisses.js +325 -0
  10. package/dist/cacheplan.d.ts +30 -10
  11. package/dist/cacheplan.js +157 -32
  12. package/dist/cli.js +68 -19
  13. package/dist/codexroute.d.ts +46 -0
  14. package/dist/codexroute.js +122 -0
  15. package/dist/coldresume.d.ts +62 -0
  16. package/dist/coldresume.js +85 -6
  17. package/dist/compactquality.d.ts +2 -0
  18. package/dist/compactquality.js +21 -3
  19. package/dist/compactwindow.d.ts +2 -0
  20. package/dist/compactwindow.js +30 -7
  21. package/dist/config.d.ts +11 -0
  22. package/dist/config.js +117 -4
  23. package/dist/dashboard.js +15 -1
  24. package/dist/doctor.d.ts +23 -0
  25. package/dist/doctor.js +133 -10
  26. package/dist/hook.d.ts +18 -0
  27. package/dist/hook.js +58 -8
  28. package/dist/impact.js +32 -4
  29. package/dist/index.d.ts +2 -0
  30. package/dist/index.js +2 -0
  31. package/dist/install.d.ts +25 -0
  32. package/dist/install.js +148 -45
  33. package/dist/ledger.d.ts +2 -0
  34. package/dist/mcp.js +56 -53
  35. package/dist/modelswitch.d.ts +76 -0
  36. package/dist/modelswitch.js +184 -0
  37. package/dist/optimize.js +40 -6
  38. package/dist/pack.d.ts +32 -3
  39. package/dist/pack.js +176 -24
  40. package/dist/parse.d.ts +3 -1
  41. package/dist/parse.js +123 -3
  42. package/dist/pricing.js +8 -0
  43. package/dist/profile.js +60 -17
  44. package/dist/proxy.d.ts +22 -1
  45. package/dist/proxy.js +89 -12
  46. package/dist/report.js +8 -2
  47. package/dist/savings.d.ts +15 -2
  48. package/dist/savings.js +9 -11
  49. package/dist/session.js +19 -3
  50. package/dist/sketch.d.ts +2 -0
  51. package/dist/sketch.js +10 -1
  52. package/dist/tokens.js +20 -9
  53. package/dist/wrap.js +27 -5
  54. package/package.json +1 -1
package/README.md CHANGED
@@ -34,6 +34,7 @@ Pick where you work. Each takes about a minute and is fully reversible.
34
34
  - `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.
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
+ - `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.
37
38
  - `cache-plan <request.json>`: where an Anthropic API request should carry `cache_control`, and what it saves over N calls.
38
39
  - `session`, `watch`, `analyze`, `report`, `dashboard`: token breakdown and wasted-context findings for any session, conversation file or agent trace.
39
40
 
@@ -43,6 +44,7 @@ Pick where you work. Each takes about a minute and is fully reversible.
43
44
  - `ci` and the GitHub Action: review memory-file growth like any other cost.
44
45
 
45
46
  **Remove waste automatically**
47
+ - 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.
46
48
  - 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.
47
49
  - 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.
48
50
  - `compact-window`: sets Claude Code's own auto-compact window, measured on your history first. Works in the desktop app too.
@@ -96,7 +98,7 @@ On a Claude subscription you do not pay list price; the same tokens come out of
96
98
  | **Claude Code** in the terminal, VS Code or JetBrains | **Autopilot** clears stale tool output (cold cache only, never more expensive). **Hook** on every prompt: real context size, largest waste, and a `/compact` offer when you return to a large session after the cache expired. **Compaction hook** on every compaction. **`compact-window`**, if you set one | Install via npm or as a **plugin**. Status bar context meter, `/context-doctor:savings`, `session`, `watch`, `report`, dashboard, MCP tools |
97
99
  | **Claude Code** in the desktop app's Code tab | **Hooks**, as above, the cold-resume `/compact` offer shown to you as well as the model. **`compact-window`**, if you set one: Claude Code compacts earlier by itself. Not autopilot: the app sets its own API address and ignores the one in settings | Same as above |
98
100
  | **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)) |
99
- | **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 (`OPENAI_BASE_URL`) |
101
+ | **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`) |
100
102
  | **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 |
101
103
  | **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)) |
102
104
  | **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)) |
@@ -107,17 +109,17 @@ Not claimed, because no process on your machine sends those requests: trimming i
107
109
 
108
110
  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):
109
111
 
110
- > 1. Summarize any paste or tool result over ~2k tokens into the points you need; don't carry it verbatim unless you will edit or quote it exactly.
111
- > 2. Refer to earlier content by name; never re-quote it or inline base64.
112
- > 3. Once, at ~30 turns or 3+ large pastes, and when asked about tokens, cost, speed or limits: 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.
113
- > 4. If optimize_context returns a pruned-turns digest, write its ≤150-token summary.
114
- > 5. To answer from a big file or folder you won't edit, call pack_context with the question; don't read it whole.
112
+ > 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.
113
+ > 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.
114
+ > 3. Refer to earlier content by name; never re-quote it or inline base64.
115
+ > 4. To answer from a big file or folder you won't edit, call pack_context with the question; don't read it whole.
116
+ > 5. If optimize_context returns a pruned-turns digest, write its ≤150-token summary.
115
117
 
116
118
  ## Commands
117
119
 
118
120
  | Command | What it does |
119
121
  |---|---|
120
- | `context-doctor install` / `uninstall` | Wire (or remove) everything it finds: the MCP server for Claude Desktop, Claude Code, Cursor, Codex and Gemini CLI; the Agent Skill (Claude Code, Codex); the every-prompt hook (Claude Code, Codex, Gemini CLI's `BeforeAgent`, Cursor's `postToolUse`); Claude Code's `PreCompact` hook. `--statusline` adds the status bar line ([details](./docs/install.md)) |
122
+ | `context-doctor install` / `uninstall` | Wire (or remove) everything it finds: the MCP server for Claude Desktop, Claude Code, Cursor, Codex and Gemini CLI; the Agent Skill (Claude Code, Codex); the every-prompt hook (Claude Code, Codex, Gemini CLI's `BeforeAgent`, Cursor's `postToolUse`, `postToolUseFailure` and `sessionStart`); Claude Code's `PreCompact` and `SessionStart` hooks. `--statusline` adds the status bar line ([details](./docs/install.md)) |
121
123
  | `context-doctor doctor` | Self-check the whole installation — one pasteable ✓/✗ diagnosis with fixes |
122
124
  | `context-doctor savings [--days n] [--share [--copy]]` | What your recent Claude Code sessions cost, and what `/compact` at cold resumes, autopilot and an earlier auto-compact window would save, replayed through the shipped code against your actual billed usage. `--share` prints totals only (no project names or paths) to post. A bare `context-doctor` in a terminal shows the same |
123
125
  | `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)) |
@@ -139,7 +141,8 @@ The MCP server hands these standing rules, verbatim, to every chat where it is e
139
141
  | `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 |
140
142
  | `context-doctor subagents [--days n]` | Which subagents paid for themselves: each one's bill vs the same steps run in the parent session |
141
143
  | `context-doctor compactions [--days n]` | Do sessions work worse right after compacting? Re-reads, tool errors and your corrections, before vs after each compaction |
142
- | `context-doctor cache-plan <request.json> [--calls n] [--out file]` | Where an Anthropic API request should carry `cache_control`, and what it saves over n calls; `--out` writes it applied |
144
+ | `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 |
145
+ | `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 |
143
146
  | `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 |
144
147
  | `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 |
145
148
  | `context-doctor dashboard` | Local savings dashboard on 127.0.0.1: tokens saved per day, sessions by context in use vs recoverable, budget status |
@@ -154,8 +157,8 @@ The MCP server hands these standing rules, verbatim, to every chat where it is e
154
157
 
155
158
  ## What's new
156
159
 
157
- - **0.33 Easier to start, fewer tokens behind a proxy**: `npx context-doctor` now installs one package and starts in under a second (the MCP SDK is bundled; it took 4.5 to 9 s). A bare `context-doctor` opens on a short "Start here" screen, `--help` is grouped, and unknown flags are errors with a suggestion. With autopilot on, Claude Code keeps MCP tool search on (it turned it off behind a non-Anthropic address, loading every tool definition into every request). `install` no longer duplicates an enabled plugin, `session` profiles the current session, `doctor` exits 1 on failures, `uninstall` removes only what install added, and `savings`, `compact-window` and `overhead` report the same session count and billed baseline. A 1-hour cache marked at the top level of a request is treated as 1 hour. The README is a 185-line front page with the detail in docs/.
158
- - **0.32 A full audit, fixed**: five reviewers read every module against real data; each finding was reproduced, fixed and tested (list in [ROADMAP.md](./ROADMAP.md#fixed-by-a-local-audit-2026-10-13)). The ones that mattered most: `npx context-doctor install` wrote an MCP launcher for a package that does not exist; `uninstall` left Claude Code pointed at a dead proxy port; the optimizer could move one parallel tool result under another's id and drop the note beside them; autopilot could clear output the model had not read; edited histories now respect thinking-block signatures; current prices (Opus 5.5 $4, Sonnet 5.x $2, Haiku 5.5 $0.10) and 1-hour cache writes at 2x; replies counted once and `--days` applied per request. The cold-resume offer follows the cache lifetime a session writes. The figures above were re-measured with it.
160
+ - **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)).
161
+ - **0.34 Native idle compaction, automatic caching, Codex and Cursor fixes**: the cold-resume offer steps aside for Claude Code's own idle compaction (silent after it, still there for the 5-minute caches and sessions under 200k it skips), uses Claude Code's SessionStart verdict and price on a resumed session, and no longer offers `/compact` on a conversation that was just compacted. `cache-plan` uses Anthropic's automatic caching for the conversation's moving end and prices reads at each model's own rate. Codex on an API key is routed by `autopilot on` through `openai_base_url` (Codex no longer reads `OPENAI_BASE_URL`); ChatGPT sign-in is left alone. The OpenAI proxy adds a stable `prompt_cache_key` per conversation where the app sent none (models before GPT-5.6). Cursor gets `postToolUseFailure` and `sessionStart` hooks, and `doctor` says what your Cursor version does with the guidance. Measured and dropped: Anthropic's server-side tool-result clearing (7 to 14 of 37 replayed sessions more expensive). Re-run `context-doctor install` to add the new hooks.
159
162
 
160
163
  Every release: [docs/whats-new.md](./docs/whats-new.md).
161
164
 
@@ -83,6 +83,8 @@ export interface AutoClearResult {
83
83
  newIds: string[];
84
84
  /** Every id whose clearing this request carries, earlier batches included. */
85
85
  appliedIds: string[];
86
+ /** The conversation these ids belong to; pass it back to forget(). */
87
+ conversation?: string;
86
88
  }
87
89
  /**
88
90
  * Whether a thinking block comes at or after message `index`. On current
@@ -140,8 +142,9 @@ export declare function clearedNote(tokens: number): string;
140
142
  export declare function requestTtlMs(body: Record<string, unknown>): number;
141
143
  export declare function viewOf(body: Record<string, unknown>): View | undefined;
142
144
  export declare class AutoClearer {
145
+ /** Cleared results, keyed by scoped(conversation, id): tokens the output had. */
143
146
  private cleared;
144
- /** Tool results never change once sent, so their size is computed once per id. */
147
+ /** Tool results never change once sent, so their size is computed once per conversation and id. */
145
148
  private sizes;
146
149
  private convs;
147
150
  private opts;
@@ -179,7 +182,7 @@ export declare class AutoClearer {
179
182
  * them, and any thinking it produces from now on is bound to the history
180
183
  * without them.
181
184
  */
182
- forget(ids: string[]): void;
185
+ forget(ids: string[], conversation?: string): void;
183
186
  private load;
184
187
  private save;
185
188
  }
package/dist/autoclear.js CHANGED
@@ -252,9 +252,20 @@ function conversationKey(view, body) {
252
252
  h.update("\0").update(tag);
253
253
  return h.digest("hex");
254
254
  }
255
+ /**
256
+ * Cleared ids and result sizes are per conversation. Tool call ids are only
257
+ * unique within one: OpenAI-compatible clients number them call_0, call_1…
258
+ * in every conversation, so a global map cleared a new, warm conversation's
259
+ * results on its first request because another conversation had cleared
260
+ * the same ids, and reported the other conversation's sizes for them.
261
+ */
262
+ function scoped(conversation, id) {
263
+ return `${conversation}\u0000${id}`;
264
+ }
255
265
  export class AutoClearer {
266
+ /** Cleared results, keyed by scoped(conversation, id): tokens the output had. */
256
267
  cleared = new Map();
257
- /** Tool results never change once sent, so their size is computed once per id. */
268
+ /** Tool results never change once sent, so their size is computed once per conversation and id. */
258
269
  sizes = new Map();
259
270
  convs = new Map();
260
271
  opts;
@@ -298,10 +309,11 @@ export class AutoClearer {
298
309
  this.convs.delete(this.convs.keys().next().value);
299
310
  this.convsDirty = true;
300
311
  const results = view.results.map((r) => {
301
- let tokens = this.sizes.get(r.id);
312
+ const sk = scoped(key, r.id);
313
+ let tokens = this.sizes.get(sk);
302
314
  if (tokens === undefined) {
303
315
  tokens = resultTokens(r.content, model);
304
- this.sizes.set(r.id, tokens);
316
+ this.sizes.set(sk, tokens);
305
317
  if (this.sizes.size > 100_000)
306
318
  this.sizes.delete(this.sizes.keys().next().value);
307
319
  }
@@ -312,7 +324,7 @@ export class AutoClearer {
312
324
  const eligible = results.slice(0, Math.max(0, results.length - this.opts.keepRecent))
313
325
  .filter((r) => r.unit <= view.seenUpTo && CLEARABLE_TOOLS.has(view.toolName.get(r.id) ?? ""));
314
326
  const eligibleIds = new Set(eligible.map((r) => r.id));
315
- const pending = eligible.filter((r) => !this.cleared.has(r.id) && r.tokens > 200);
327
+ const pending = eligible.filter((r) => !this.cleared.has(scoped(key, r.id)) && r.tokens > 200);
316
328
  const pendingTokens = pending.reduce((n, r) => n + r.tokens, 0);
317
329
  let reason = "nothing to clear";
318
330
  let taken = [];
@@ -342,7 +354,7 @@ export class AutoClearer {
342
354
  reason = "thinking blocks follow the stale output and this account rejects edited history: left as is";
343
355
  }
344
356
  for (const r of taken)
345
- this.cleared.set(r.id, r.tokens);
357
+ this.cleared.set(scoped(key, r.id), r.tokens);
346
358
  if (taken.length)
347
359
  this.dirty = true;
348
360
  // Apply every clearing ever decided for this conversation, so the
@@ -354,9 +366,10 @@ export class AutoClearer {
354
366
  let firstChanged = -1;
355
367
  const appliedIds = [];
356
368
  for (const r of results) {
357
- if (!this.cleared.has(r.id) || !eligibleIds.has(r.id))
369
+ const sk = scoped(key, r.id);
370
+ if (!this.cleared.has(sk) || !eligibleIds.has(r.id))
358
371
  continue;
359
- const note = clearedNote(this.cleared.get(r.id));
372
+ const note = clearedNote(this.cleared.get(sk));
360
373
  if (r.content === note)
361
374
  continue;
362
375
  removed += Math.max(0, r.tokens - estimateTokens(note, model));
@@ -367,7 +380,7 @@ export class AutoClearer {
367
380
  firstChanged = r.unit;
368
381
  }
369
382
  this.save();
370
- return { changed, newlyCleared: taken.length, tokensRemoved: removed, cold, reason, firstChanged, newIds: taken.map((r) => r.id), appliedIds };
383
+ return { changed, newlyCleared: taken.length, tokensRemoved: removed, cold, reason, firstChanged, newIds: taken.map((r) => r.id), appliedIds, conversation: key };
371
384
  }
372
385
  catch {
373
386
  return none("error: request forwarded unchanged");
@@ -411,10 +424,20 @@ export class AutoClearer {
411
424
  * them, and any thinking it produces from now on is bound to the history
412
425
  * without them.
413
426
  */
414
- forget(ids) {
427
+ forget(ids, conversation) {
415
428
  let any = false;
416
- for (const id of ids)
417
- any = this.cleared.delete(id) || any;
429
+ if (conversation !== undefined) {
430
+ for (const id of ids)
431
+ any = this.cleared.delete(scoped(conversation, id)) || any;
432
+ }
433
+ else {
434
+ // No conversation named: these ids in every conversation.
435
+ const wanted = new Set(ids);
436
+ for (const k of [...this.cleared.keys()]) {
437
+ if (wanted.has(k.slice(k.indexOf("\u0000") + 1)))
438
+ any = this.cleared.delete(k) || any;
439
+ }
440
+ }
418
441
  if (any) {
419
442
  this.dirty = true;
420
443
  this.save();
@@ -425,17 +448,29 @@ export class AutoClearer {
425
448
  return;
426
449
  try {
427
450
  const data = JSON.parse(readFileSync(this.opts.statePath, "utf8"));
428
- for (const [id, tokens] of data.cleared ?? [])
429
- this.cleared.set(id, tokens);
430
- for (const account of data.rejectsEdits ?? [])
431
- if (typeof account === "string")
432
- this.rejecting.add(account);
451
+ // Through 0.34 cleared ids were global (`cleared: [id, tokens][]`) and
452
+ // say nothing about which conversation they belong to; they are not
453
+ // carried over. An open conversation re-clears at its next cold gap.
454
+ for (const entry of Array.isArray(data.clearedByConversation) ? data.clearedByConversation : []) {
455
+ if (!Array.isArray(entry))
456
+ continue;
457
+ const [conv, id, tokens] = entry;
458
+ if (typeof conv === "string" && typeof id === "string" && typeof tokens === "number")
459
+ this.cleared.set(scoped(conv, id), tokens);
460
+ }
433
461
  // Each conversation's last request time, so a restart does not make
434
462
  // every open conversation "unseen" (cold) and rewrite a warm cache.
435
- for (const [key, last, requests] of data.convs ?? []) {
463
+ for (const entry of Array.isArray(data.convs) ? data.convs : []) {
464
+ if (!Array.isArray(entry))
465
+ continue;
466
+ const [key, last, requests] = entry;
436
467
  if (typeof key === "string" && typeof last === "number")
437
468
  this.convs.set(key, { last: last + CONV_SAVE_MS, requests: Number(requests) || 1 });
438
469
  }
470
+ if (Array.isArray(data.rejectsEdits))
471
+ for (const account of data.rejectsEdits)
472
+ if (typeof account === "string")
473
+ this.rejecting.add(account);
439
474
  }
440
475
  catch {
441
476
  /* a corrupt state file only means results may be re-cleared once */
@@ -452,10 +487,13 @@ export class AutoClearer {
452
487
  this.lastSave = Date.now();
453
488
  try {
454
489
  // Newest 50k ids: far more than any live session holds.
455
- const entries = [...this.cleared.entries()].slice(-50_000);
490
+ const entries = [...this.cleared.entries()].slice(-50_000).map(([k, tokens]) => {
491
+ const at = k.indexOf("\u0000");
492
+ return [k.slice(0, at), k.slice(at + 1), tokens];
493
+ });
456
494
  const convs = [...this.convs.entries()].map(([k, c]) => [k, c.last, c.requests]);
457
495
  mkdirSync(dirname(this.opts.statePath), { recursive: true });
458
- writeFileSync(this.opts.statePath, JSON.stringify({ cleared: entries, convs, rejectsEdits: [...this.rejecting] }));
496
+ writeFileSync(this.opts.statePath, JSON.stringify({ clearedByConversation: entries, convs, rejectsEdits: [...this.rejecting] }));
459
497
  }
460
498
  catch {
461
499
  /* persistence is best effort */
@@ -67,12 +67,6 @@ export interface Health {
67
67
  version?: string;
68
68
  }
69
69
  export declare function health(port: number, timeoutMs?: number): Promise<Health>;
70
- /**
71
- * The ANTHROPIC_BASE_URL `off` should restore, decided at `on`: the one an
72
- * earlier `on` recorded, else what settings.json holds now, but never our own
73
- * proxy's. With the config damaged, settings.json already holds the proxy URL
74
- * from the last `on`, and recording that made `off` put the proxy URL back.
75
- */
76
70
  export declare function baseUrlToRestore(paths: AutopilotPaths, port: number, current: string | null): string | null;
77
71
  /** Which Claude Code surfaces ran recent sessions: entrypoint -> count. */
78
72
  export declare function recentSurfaces(days?: number, home?: string): Map<string, number>;
package/dist/autopilot.js CHANGED
@@ -25,6 +25,7 @@ import { dirname, join } from "node:path";
25
25
  import { fileURLToPath } from "node:url";
26
26
  import { isEphemeralPath, readJson, writeJsonWithBackup } from "./install.js";
27
27
  import { formatTokens } from "./tokens.js";
28
+ import { codexAuthMode, codexHomeIn, codexRouting, routeCodex, unrouteCodex } from "./codexroute.js";
28
29
  export const DEFAULT_AUTOPILOT_PORT = 8787;
29
30
  const LABEL = "com.gai-ventures.context-doctor.proxy";
30
31
  export function autopilotPaths(home = homedir()) {
@@ -297,6 +298,9 @@ function isOurProxyUrl(url, port, paths) {
297
298
  * proxy's. With the config damaged, settings.json already holds the proxy URL
298
299
  * from the last `on`, and recording that made `off` put the proxy URL back.
299
300
  */
301
+ /** Codex's address for the proxy: the OpenAI routes live under /v1. */
302
+ const codexUrl = (port) => `${proxyUrl(port)}/v1`;
303
+ const isOurCodexUrl = (port, paths) => (u) => isOurProxyUrl(u.replace(/\/v1\/?$/, ""), port, paths);
300
304
  export function baseUrlToRestore(paths, port, current) {
301
305
  const prev = readConfig(paths);
302
306
  if (prev?.previousBaseUrl !== undefined)
@@ -431,7 +435,15 @@ export async function autopilotOn(port = DEFAULT_AUTOPILOT_PORT, paths = autopil
431
435
  env.ANTHROPIC_BASE_URL = proxyUrl(port);
432
436
  const setToolSearch = keepToolSearch(env);
433
437
  writeJsonWithBackup(paths.settings, settings);
434
- writeFileSync(paths.config, JSON.stringify({ port, previousBaseUrl, setToolSearch, node: process.execPath, cli }, null, 2));
438
+ // Codex on an API key: its address is openai_base_url in config.toml.
439
+ let codex = { routed: false };
440
+ try {
441
+ codex = routeCodex(homeOf(paths), codexUrl(port), isOurCodexUrl(port, paths));
442
+ }
443
+ catch (e) {
444
+ codex = { routed: false, line: `! Codex not routed: ${e.message}` };
445
+ }
446
+ writeFileSync(paths.config, JSON.stringify({ port, previousBaseUrl, setToolSearch, codexRouted: codex.routed || undefined, node: process.execPath, cli }, null, 2));
435
447
  if (existsSync(paths.pauseFile))
436
448
  rmSync(paths.pauseFile);
437
449
  lines.push(`✓ Claude Code routed through it (env.ANTHROPIC_BASE_URL in ${paths.settings})`);
@@ -439,8 +451,10 @@ export async function autopilotOn(port = DEFAULT_AUTOPILOT_PORT, paths = autopil
439
451
  lines.push("✓ MCP tool search kept on (env.ENABLE_TOOL_SEARCH=auto): Claude Code turns it off behind a non-Anthropic address, which would load every MCP tool definition on every request");
440
452
  lines.push(" Applies to Claude Code sessions started from now on in a terminal or IDE (the desktop app's Code tab sets its own address).");
441
453
  lines.push(" Sessions already open keep their old route until restarted.");
454
+ if (codex.line)
455
+ lines.push(codex.line);
442
456
  lines.push(...reachNote());
443
- lines.push(` GPT apps on your own OpenAI key get the same: export OPENAI_BASE_URL=${proxyUrl(port)}/v1`);
457
+ lines.push(` GPT apps on your own OpenAI key get the same: export OPENAI_BASE_URL=${proxyUrl(port)}/v1 (Codex reads openai_base_url instead)`);
444
458
  return { ok: true, lines };
445
459
  }
446
460
  export async function autopilotOff(paths = autopilotPaths(), exec = tryRun) {
@@ -465,6 +479,12 @@ export async function autopilotOff(paths = autopilotPaths(), exec = tryRun) {
465
479
  writeJsonWithBackup(paths.settings, settings);
466
480
  lines.push("✓ Claude Code no longer routed through the proxy (new sessions)");
467
481
  }
482
+ // Our address in Codex's config.toml goes too, whether or not we recorded it.
483
+ try {
484
+ if (unrouteCodex(homeOf(paths), isOurCodexUrl(cfg?.port, paths)))
485
+ lines.push("✓ Codex no longer routed through the proxy (new sessions)");
486
+ }
487
+ catch { /* an unreadable config.toml is the user's to fix */ }
468
488
  removeService(homeOf(paths), exec, Boolean(cfg) || existsSync(paths.config));
469
489
  if (existsSync(paths.config))
470
490
  rmSync(paths.config);
@@ -517,6 +537,12 @@ export async function autopilotStatus(paths = autopilotPaths()) {
517
537
  const env = (readJson(paths.settings).env ?? {});
518
538
  lines.push(`${h.ok ? "✓" : "✗"} Proxy ${proxyUrl(cfg.port)} ${h.ok ? `up (v${h.version ?? "?"})` : "NOT RESPONDING (the next Claude Code prompt restarts it via the hook)"}`);
519
539
  lines.push(`${env.ANTHROPIC_BASE_URL === proxyUrl(cfg.port) ? "✓" : "✗"} Claude Code routed through it`);
540
+ const cx = codexRouting(homeOf(paths));
541
+ if (cx.present) {
542
+ lines.push(cx.baseUrl === codexUrl(cfg.port)
543
+ ? "✓ Codex (API key) routed through it"
544
+ : ` Codex not routed${cx.auth === "apikey" ? "" : " (it signs in with ChatGPT; autopilot routes Codex only on an API key)"}`);
545
+ }
520
546
  if (existsSync(paths.pauseFile))
521
547
  lines.push("! Paused: requests pass through unchanged");
522
548
  if (h.ok) {
@@ -552,6 +578,15 @@ export async function ensureProxyUp(paths = autopilotPaths(), exec = tryRun) {
552
578
  if (!cfg)
553
579
  return;
554
580
  migrateToolSearch(paths, cfg);
581
+ // Signed in with ChatGPT since `autopilot on`? Then Codex must not be
582
+ // pointed at the proxy: take our address out before its next session.
583
+ if (cfg.codexRouted && codexAuthMode(codexHomeIn(homeOf(paths))) !== "apikey") {
584
+ try {
585
+ unrouteCodex(homeOf(paths), isOurCodexUrl(cfg.port, paths));
586
+ writeFileSync(paths.config, JSON.stringify({ ...cfg, codexRouted: undefined }, null, 2));
587
+ }
588
+ catch { /* never fail a prompt over this */ }
589
+ }
555
590
  const h = await health(cfg.port, 300);
556
591
  if (h.ok) {
557
592
  // A service keeps running the code it started with: after an update it
@@ -0,0 +1,25 @@
1
+ /**
2
+ * A stable `prompt_cache_key` per conversation for OpenAI requests that do
3
+ * not carry one.
4
+ *
5
+ * OpenAI routes a request to a cache by a hash of its first tokens and, when
6
+ * present, the key (prompt-caching guide, checked 2026-10-18). On models
7
+ * before GPT-5.6 (GPT-5.5 and earlier) a stable key per group of related
8
+ * requests is how to keep them on one cache; from GPT-5.6 on the key is
9
+ * optional and only separates cache accounting, so it is left alone there.
10
+ * A key the app set is never touched, and requests that continue a
11
+ * server-side conversation (`previous_response_id`, `conversation`) are left
12
+ * as they are: their history is not in the request to identify.
13
+ *
14
+ * The key is derived from what stays fixed for a conversation's life: its
15
+ * instructions (system/developer messages, Responses `instructions`) and its
16
+ * first user message. Two conversations that open identically share a key,
17
+ * which is what a shared prefix wants anyway.
18
+ */
19
+ /** Models whose cache routing uses the key: GPT before 5.6, the o-series, codex-mini. */
20
+ export declare function usesPromptCacheKey(model: unknown): boolean;
21
+ /** The request with a conversation key added, or undefined when it should go as it is. */
22
+ export declare function withPromptCacheKey(raw: string): {
23
+ body: string;
24
+ key: string;
25
+ } | undefined;
@@ -0,0 +1,73 @@
1
+ /**
2
+ * A stable `prompt_cache_key` per conversation for OpenAI requests that do
3
+ * not carry one.
4
+ *
5
+ * OpenAI routes a request to a cache by a hash of its first tokens and, when
6
+ * present, the key (prompt-caching guide, checked 2026-10-18). On models
7
+ * before GPT-5.6 (GPT-5.5 and earlier) a stable key per group of related
8
+ * requests is how to keep them on one cache; from GPT-5.6 on the key is
9
+ * optional and only separates cache accounting, so it is left alone there.
10
+ * A key the app set is never touched, and requests that continue a
11
+ * server-side conversation (`previous_response_id`, `conversation`) are left
12
+ * as they are: their history is not in the request to identify.
13
+ *
14
+ * The key is derived from what stays fixed for a conversation's life: its
15
+ * instructions (system/developer messages, Responses `instructions`) and its
16
+ * first user message. Two conversations that open identically share a key,
17
+ * which is what a shared prefix wants anyway.
18
+ */
19
+ import { createHash } from "node:crypto";
20
+ /** Models whose cache routing uses the key: GPT before 5.6, the o-series, codex-mini. */
21
+ export function usesPromptCacheKey(model) {
22
+ if (typeof model !== "string")
23
+ return false;
24
+ const m = model.toLowerCase().replace(/^openai\//, "");
25
+ const gpt = /^gpt-(\d+)(?:\.(\d+))?/.exec(m);
26
+ if (gpt)
27
+ return Number(gpt[1]) < 5 || (Number(gpt[1]) === 5 && Number(gpt[2] ?? 0) < 6);
28
+ return /^(o1|o3|o4)(-|$)|^codex-mini/.test(m);
29
+ }
30
+ const text = (c) => (typeof c === "string" ? c : JSON.stringify(c ?? ""));
31
+ /** The fixed part of a conversation: instructions and the first user message. */
32
+ function anchor(body) {
33
+ if (Array.isArray(body.messages)) {
34
+ const msgs = body.messages;
35
+ const first = msgs.findIndex((m) => m?.role === "user");
36
+ if (first < 0)
37
+ return undefined;
38
+ return [...msgs.slice(0, first).filter((m) => m?.role === "system" || m?.role === "developer").map((m) => text(m.content)), text(msgs[first].content)].join("\0");
39
+ }
40
+ if (typeof body.input === "string")
41
+ return `${text(body.instructions)}\0${body.input}`;
42
+ if (Array.isArray(body.input)) {
43
+ const items = body.input;
44
+ const first = items.find((i) => i?.role === "user");
45
+ if (!first)
46
+ return undefined;
47
+ const sys = items.filter((i) => i?.role === "system" || i?.role === "developer").map((i) => text(i.content));
48
+ return [text(body.instructions), ...sys, text(first.content)].join("\0");
49
+ }
50
+ return undefined;
51
+ }
52
+ /** The request with a conversation key added, or undefined when it should go as it is. */
53
+ export function withPromptCacheKey(raw) {
54
+ let body;
55
+ try {
56
+ body = JSON.parse(raw);
57
+ }
58
+ catch {
59
+ return undefined;
60
+ }
61
+ if (!body || typeof body !== "object" || Array.isArray(body))
62
+ return undefined;
63
+ if ("prompt_cache_key" in body || body.previous_response_id || body.conversation)
64
+ return undefined;
65
+ if (!usesPromptCacheKey(body.model))
66
+ return undefined;
67
+ const a = anchor(body);
68
+ if (a === undefined)
69
+ return undefined;
70
+ const key = "cd-" + createHash("sha256").update(a.slice(0, 20_000)).digest("hex").slice(0, 32);
71
+ body.prompt_cache_key = key;
72
+ return { body: JSON.stringify(body), key };
73
+ }
@@ -0,0 +1,88 @@
1
+ /**
2
+ * `context-doctor cache-misses`: requests that re-wrote the prompt cache while
3
+ * it should still have been warm.
4
+ *
5
+ * Claude Code caches the conversation as it goes; the next request within the
6
+ * cache's lifetime reads that prefix at the cache-read rate (5-10% of input)
7
+ * and writes only what is new. When a request instead writes most of the
8
+ * context again, at 1.25x input (2x at the 1-hour TTL), the cache missed.
9
+ * Some misses are expected (a model switch: each model has its own cache;
10
+ * a compaction: a new history), the rest are invisible from the client.
11
+ *
12
+ * Definition, request by request over each main-chain transcript:
13
+ * - two consecutive requests (sidechains and synthetic replies skipped),
14
+ * with no compaction (compact_boundary) between them;
15
+ * - the gap under the cache lifetime of both: 1 hour when the request wrote
16
+ * to the 1-hour cache (usage.cache_creation.ephemeral_1h_input_tokens > 0),
17
+ * else 5 minutes;
18
+ * - the previous request's context over 20k tokens (smaller ones are noise);
19
+ * - a miss when the request's cache_creation_input_tokens exceed 60% of the
20
+ * previous request's whole context (input + cache read + cache write).
21
+ *
22
+ * Priced above what the same tokens would have cost as cache reads: the
23
+ * re-written part (up to the previous context) at the write rate minus the
24
+ * read rate. Measured on the author's last 30 days (Oct 2026): 390 misses in
25
+ * 29,287 requests, ~$1,925 above cache-read price, 28% of all cache-write
26
+ * spend; 382 of them with nothing in the transcript to explain them.
27
+ */
28
+ export type MissCause = "model switch" | "context edited" | "after an API error" | "over 20 new blocks" | "nothing visible";
29
+ export interface CacheMiss {
30
+ path: string;
31
+ /** ISO time of the request that missed. */
32
+ at: string;
33
+ model: string;
34
+ previousModel: string;
35
+ /** The previous request's whole context: what should have been read from cache. */
36
+ contextTokens: number;
37
+ writeTokens: number;
38
+ /** Cache read on the miss as a share of the previous context (the part that still matched). */
39
+ readShare: number;
40
+ gapSeconds: number;
41
+ cause: MissCause;
42
+ /** Above the cache-read price; undefined when the model has no known price. */
43
+ extraUsd?: number;
44
+ }
45
+ export interface MissStats {
46
+ /** Requests that could have read a warm cache (the definition above). */
47
+ eligible: number;
48
+ misses: number;
49
+ rate: number;
50
+ extraUsd: number;
51
+ }
52
+ export interface CacheMissReport {
53
+ days: number;
54
+ transcripts: number;
55
+ /** Every main-chain request with usage in the period. */
56
+ requests: number;
57
+ eligible: number;
58
+ misses: number;
59
+ missWriteTokens: number;
60
+ /** Misses priced above cache-read price (priced models only). */
61
+ extraUsd: number;
62
+ /** All cache writes in the period, priced: the share the misses take of it. */
63
+ cacheWriteUsd: number;
64
+ /** Misses on models with no known price (not in extraUsd). */
65
+ unpricedMisses: number;
66
+ byModel: Array<{
67
+ model: string;
68
+ } & MissStats>;
69
+ bySize: Array<{
70
+ bucket: string;
71
+ } & MissStats>;
72
+ causes: Record<MissCause, number>;
73
+ /** Advice the data supports (model versions with fewer misses, context size), possibly none. */
74
+ recommendations: string[];
75
+ /** The costliest misses. */
76
+ largest: CacheMiss[];
77
+ }
78
+ /** Misses in one transcript; `since` drops requests before it. */
79
+ export declare function missesInTranscript(path: string, since?: number, add?: (eligible: {
80
+ model: string;
81
+ contextTokens: number;
82
+ }, miss?: CacheMiss) => void, onRequest?: (writeUsd: number) => void): void;
83
+ export declare function cacheMisses(days?: number, paths?: string[], onProgress?: (done: number, total: number) => void): CacheMissReport;
84
+ /** Worth a line in `savings`: enough misses, and enough money, to act on. */
85
+ export declare function cacheMissesSignificant(r: CacheMissReport): boolean;
86
+ /** The one line `savings` adds when the misses are significant. */
87
+ export declare function cacheMissesLine(r: CacheMissReport): string[];
88
+ export declare function renderCacheMisses(r: CacheMissReport): string;