context-doctor 0.32.0 → 0.34.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 (50) hide show
  1. package/README.md +84 -694
  2. package/dist/autoclear.js +4 -1
  3. package/dist/autopilot.d.ts +20 -6
  4. package/dist/autopilot.js +105 -7
  5. package/dist/cachekey.d.ts +25 -0
  6. package/dist/cachekey.js +73 -0
  7. package/dist/cacheplan.d.ts +29 -9
  8. package/dist/cacheplan.js +110 -29
  9. package/dist/ci.js +9 -1
  10. package/dist/cli.js +359 -247
  11. package/dist/clihelp.d.ts +24 -0
  12. package/dist/clihelp.js +116 -0
  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 +3 -1
  18. package/dist/compactquality.js +15 -4
  19. package/dist/compactwindow.d.ts +31 -5
  20. package/dist/compactwindow.js +80 -25
  21. package/dist/diff.js +24 -2
  22. package/dist/doctor.d.ts +8 -2
  23. package/dist/doctor.js +138 -35
  24. package/dist/hook.js +23 -4
  25. package/dist/install.d.ts +35 -0
  26. package/dist/install.js +280 -48
  27. package/dist/invocation.d.ts +18 -0
  28. package/dist/invocation.js +49 -0
  29. package/dist/ledger.d.ts +2 -0
  30. package/dist/mcp.d.ts +5 -2
  31. package/dist/mcp.js +93 -299
  32. package/dist/mcpclient.js +45 -0
  33. package/dist/mcpschema.d.ts +1 -1
  34. package/dist/mcpschema.js +11 -8
  35. package/dist/optimize.d.ts +2 -0
  36. package/dist/optimize.js +2 -0
  37. package/dist/overhead.d.ts +12 -1
  38. package/dist/overhead.js +31 -7
  39. package/dist/preferences.d.ts +1 -1
  40. package/dist/preferences.js +5 -5
  41. package/dist/proxy.d.ts +14 -1
  42. package/dist/proxy.js +45 -4
  43. package/dist/savings.d.ts +17 -1
  44. package/dist/savings.js +12 -13
  45. package/dist/session.d.ts +15 -0
  46. package/dist/session.js +43 -0
  47. package/dist/subagentpay.d.ts +1 -1
  48. package/dist/subagentpay.js +3 -2
  49. package/package.json +5 -8
  50. package/skills/context-doctor/SKILL.md +3 -3
package/dist/autoclear.js CHANGED
@@ -129,7 +129,10 @@ export function requestTtlMs(body) {
129
129
  const openai = Array.isArray(body.input) || (Array.isArray(body.messages) && isOpenAIChat(body.messages));
130
130
  if (openai)
131
131
  return body.prompt_cache_retention === "24h" ? 24 * HOUR : HOUR;
132
- const json = JSON.stringify(body.system ?? "") + JSON.stringify(body.tools ?? "") + JSON.stringify(body.messages?.slice(-3) ?? "");
132
+ // Automatic caching puts cache_control at the top level of the request; a
133
+ // 1-hour cache marked there was read as the 5-minute default, so autopilot
134
+ // could clear into a cache that was still warm.
135
+ const json = JSON.stringify(body.cache_control ?? "") + JSON.stringify(body.system ?? "") + JSON.stringify(body.tools ?? "") + JSON.stringify(body.messages?.slice(-3) ?? "");
133
136
  return /"ttl"\s*:\s*"1h"/.test(json) ? HOUR : 300_000;
134
137
  }
135
138
  function isOpenAIChat(messages) {
@@ -46,6 +46,16 @@ export declare function windowsTaskCommand(args: string[]): string;
46
46
  * task name), not per HOME.
47
47
  */
48
48
  export type ServiceExec = (cmd: string, args: string[]) => boolean;
49
+ /**
50
+ * Claude Code turns MCP tool search off when ANTHROPIC_BASE_URL is not an
51
+ * Anthropic host ("Set ENABLE_TOOL_SEARCH=true (or auto / auto:N) if your
52
+ * proxy forwards tool_reference blocks", 2.1.295), so routing it through
53
+ * autopilot loaded every MCP tool definition into every request. The proxy
54
+ * forwards those blocks and the anthropic-beta header untouched, so tool
55
+ * search stays on ("auto", Claude Code's own default) unless the user set it.
56
+ * Returns true when we set it.
57
+ */
58
+ export declare function keepToolSearch(env: Record<string, string>): boolean;
49
59
  /** Version of the package a CLI path belongs to (dist/cli.js -> ../package.json). */
50
60
  export declare function installedVersion(cli: string): string | undefined;
51
61
  /** Restart the installed background service onto the current build (launchd, systemd). */
@@ -57,12 +67,6 @@ export interface Health {
57
67
  version?: string;
58
68
  }
59
69
  export declare function health(port: number, timeoutMs?: number): Promise<Health>;
60
- /**
61
- * The ANTHROPIC_BASE_URL `off` should restore, decided at `on`: the one an
62
- * earlier `on` recorded, else what settings.json holds now, but never our own
63
- * proxy's. With the config damaged, settings.json already holds the proxy URL
64
- * from the last `on`, and recording that made `off` put the proxy URL back.
65
- */
66
70
  export declare function baseUrlToRestore(paths: AutopilotPaths, port: number, current: string | null): string | null;
67
71
  /** Which Claude Code surfaces ran recent sessions: entrypoint -> count. */
68
72
  export declare function recentSurfaces(days?: number, home?: string): Map<string, number>;
@@ -75,6 +79,16 @@ export declare function autopilotOn(port?: number, paths?: AutopilotPaths): Prom
75
79
  }>;
76
80
  export declare function autopilotOff(paths?: AutopilotPaths, exec?: ServiceExec): Promise<string[]>;
77
81
  export declare function autopilotPause(paused: boolean, paths?: AutopilotPaths): string;
82
+ /**
83
+ * Pause or resume, saying what actually happened. Without autopilot on there
84
+ * is no proxy to pause: this used to claim "✓ Paused" over nothing, and on a
85
+ * machine with no ~/.claude it threw ENOENT writing the pause file. `ok` is
86
+ * false when nothing was done, for the exit code.
87
+ */
88
+ export declare function autopilotPauseResult(paused: boolean, paths?: AutopilotPaths): {
89
+ ok: boolean;
90
+ message: string;
91
+ };
78
92
  export declare function autopilotStatus(paths?: AutopilotPaths): Promise<string[]>;
79
93
  /**
80
94
  * Called by the every-prompt hook: if autopilot is on and the proxy is down,
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()) {
@@ -188,6 +189,39 @@ function startService(home, exec) {
188
189
  return exec("systemctl", ["--user", "start", "context-doctor-proxy.service"]);
189
190
  return false;
190
191
  }
192
+ /**
193
+ * Claude Code turns MCP tool search off when ANTHROPIC_BASE_URL is not an
194
+ * Anthropic host ("Set ENABLE_TOOL_SEARCH=true (or auto / auto:N) if your
195
+ * proxy forwards tool_reference blocks", 2.1.295), so routing it through
196
+ * autopilot loaded every MCP tool definition into every request. The proxy
197
+ * forwards those blocks and the anthropic-beta header untouched, so tool
198
+ * search stays on ("auto", Claude Code's own default) unless the user set it.
199
+ * Returns true when we set it.
200
+ */
201
+ export function keepToolSearch(env) {
202
+ if (env.ENABLE_TOOL_SEARCH !== undefined)
203
+ return false;
204
+ env.ENABLE_TOOL_SEARCH = "auto";
205
+ return true;
206
+ }
207
+ /** Installs from before 0.33 routed Claude Code without it: add it once, from the every-prompt self-heal. */
208
+ function migrateToolSearch(paths, cfg) {
209
+ if (cfg.setToolSearch !== undefined)
210
+ return;
211
+ try {
212
+ const settings = readJson(paths.settings);
213
+ const env = settings.env;
214
+ if (!env || env.ANTHROPIC_BASE_URL !== proxyUrl(cfg.port))
215
+ return;
216
+ const set = keepToolSearch(env);
217
+ if (set)
218
+ writeJsonWithBackup(paths.settings, settings);
219
+ writeFileSync(paths.config, JSON.stringify({ ...cfg, setToolSearch: set }, null, 2));
220
+ }
221
+ catch {
222
+ /* the self-heal must never disturb a prompt */
223
+ }
224
+ }
191
225
  /** Version of the package a CLI path belongs to (dist/cli.js -> ../package.json). */
192
226
  export function installedVersion(cli) {
193
227
  try {
@@ -264,6 +298,9 @@ function isOurProxyUrl(url, port, paths) {
264
298
  * proxy's. With the config damaged, settings.json already holds the proxy URL
265
299
  * from the last `on`, and recording that made `off` put the proxy URL back.
266
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);
267
304
  export function baseUrlToRestore(paths, port, current) {
268
305
  const prev = readConfig(paths);
269
306
  if (prev?.previousBaseUrl !== undefined)
@@ -396,15 +433,28 @@ export async function autopilotOn(port = DEFAULT_AUTOPILOT_PORT, paths = autopil
396
433
  lines.push(`! settings.json already routed Claude Code to ${previousBaseUrl}; autopilot forwards to api.anthropic.com instead. \`autopilot off\` restores it.`);
397
434
  }
398
435
  env.ANTHROPIC_BASE_URL = proxyUrl(port);
436
+ const setToolSearch = keepToolSearch(env);
399
437
  writeJsonWithBackup(paths.settings, settings);
400
- writeFileSync(paths.config, JSON.stringify({ port, previousBaseUrl, 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));
401
447
  if (existsSync(paths.pauseFile))
402
448
  rmSync(paths.pauseFile);
403
449
  lines.push(`✓ Claude Code routed through it (env.ANTHROPIC_BASE_URL in ${paths.settings})`);
404
- lines.push(" Applies to Claude Code sessions started from now on (CLI, IDE, and the desktop app's Code tab).");
450
+ if (setToolSearch)
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");
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).");
405
453
  lines.push(" Sessions already open keep their old route until restarted.");
454
+ if (codex.line)
455
+ lines.push(codex.line);
406
456
  lines.push(...reachNote());
407
- 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)`);
408
458
  return { ok: true, lines };
409
459
  }
410
460
  export async function autopilotOff(paths = autopilotPaths(), exec = tryRun) {
@@ -422,11 +472,19 @@ export async function autopilotOff(paths = autopilotPaths(), exec = tryRun) {
422
472
  env.ANTHROPIC_BASE_URL = restore;
423
473
  else
424
474
  delete env.ANTHROPIC_BASE_URL;
475
+ if (cfg?.setToolSearch && env.ENABLE_TOOL_SEARCH === "auto")
476
+ delete env.ENABLE_TOOL_SEARCH;
425
477
  if (Object.keys(env).length === 0)
426
478
  delete settings.env;
427
479
  writeJsonWithBackup(paths.settings, settings);
428
480
  lines.push("✓ Claude Code no longer routed through the proxy (new sessions)");
429
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 */ }
430
488
  removeService(homeOf(paths), exec, Boolean(cfg) || existsSync(paths.config));
431
489
  if (existsSync(paths.config))
432
490
  rmSync(paths.config);
@@ -438,13 +496,37 @@ export async function autopilotOff(paths = autopilotPaths(), exec = tryRun) {
438
496
  return lines;
439
497
  }
440
498
  export function autopilotPause(paused, paths = autopilotPaths()) {
499
+ return autopilotPauseResult(paused, paths).message;
500
+ }
501
+ /**
502
+ * Pause or resume, saying what actually happened. Without autopilot on there
503
+ * is no proxy to pause: this used to claim "✓ Paused" over nothing, and on a
504
+ * machine with no ~/.claude it threw ENOENT writing the pause file. `ok` is
505
+ * false when nothing was done, for the exit code.
506
+ */
507
+ export function autopilotPauseResult(paused, paths = autopilotPaths()) {
508
+ // A config that exists but no longer parses still means a proxy may be
509
+ // running and routed: pausing it is the safe thing, so only absence is "off".
510
+ if (!existsSync(paths.config)) {
511
+ // A pause file left behind by an older version has nothing to pause.
512
+ if (!paused && existsSync(paths.pauseFile))
513
+ rmSync(paths.pauseFile);
514
+ return {
515
+ ok: false,
516
+ message: `Autopilot is off; nothing to ${paused ? "pause" : "resume"}. \`context-doctor autopilot on\` turns it on for new Claude Code sessions.`,
517
+ };
518
+ }
441
519
  if (paused) {
520
+ if (existsSync(paths.pauseFile))
521
+ return { ok: true, message: "Already paused: the proxy forwards every request unchanged. `autopilot resume` turns it back on." };
522
+ mkdirSync(dirname(paths.pauseFile), { recursive: true });
442
523
  writeFileSync(paths.pauseFile, new Date().toISOString());
443
- return "✓ Paused: the proxy now forwards every request unchanged. `autopilot resume` turns it back on.";
524
+ return { ok: true, message: "✓ Paused: the proxy now forwards every request unchanged. `autopilot resume` turns it back on." };
444
525
  }
445
- if (existsSync(paths.pauseFile))
446
- rmSync(paths.pauseFile);
447
- return "✓ Resumed: stale tool output is cleared again.";
526
+ if (!existsSync(paths.pauseFile))
527
+ return { ok: true, message: "Not paused: autopilot is already clearing stale tool output." };
528
+ rmSync(paths.pauseFile);
529
+ return { ok: true, message: "✓ Resumed: stale tool output is cleared again." };
448
530
  }
449
531
  export async function autopilotStatus(paths = autopilotPaths()) {
450
532
  const cfg = readConfig(paths);
@@ -455,6 +537,12 @@ export async function autopilotStatus(paths = autopilotPaths()) {
455
537
  const env = (readJson(paths.settings).env ?? {});
456
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)"}`);
457
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
+ }
458
546
  if (existsSync(paths.pauseFile))
459
547
  lines.push("! Paused: requests pass through unchanged");
460
548
  if (h.ok) {
@@ -489,6 +577,16 @@ export async function ensureProxyUp(paths = autopilotPaths(), exec = tryRun) {
489
577
  const cfg = readConfig(paths);
490
578
  if (!cfg)
491
579
  return;
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
+ }
492
590
  const h = await health(cfg.port, 300);
493
591
  if (h.ok) {
494
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
+ }
@@ -6,21 +6,35 @@
6
6
  * messages. A breakpoint caches everything up to and including the block it
7
7
  * sits on, a prefix under the model's minimum (512 to 4,096 tokens, see
8
8
  * minCacheableTokens) is not cached at all, a request may carry at most 4
9
- * breakpoints, and the cache looks back at most 20 blocks from a breakpoint
10
- * for an earlier hit.
9
+ * breakpoints, and the cache looks back at most 20 positions from a
10
+ * breakpoint for an earlier hit (a run of tool_use blocks, or of
11
+ * tool_result blocks, is one position).
12
+ *
13
+ * Automatic caching (prompt-caching docs, Oct 2026): one top-level
14
+ * `cache_control` puts a breakpoint on the last cacheable block and moves it
15
+ * forward as the conversation grows, so the app never re-places it. It takes
16
+ * one of the 4 slots; with 4 explicit breakpoints as well, or an explicit one
17
+ * on the last block at a different TTL, the API answers 400. Every platform
18
+ * has it except Bedrock's legacy integration (Opus 4.6 and earlier), which
19
+ * rejects the field.
20
+ *
11
21
  * The planner places breakpoints at the ends of the stable parts (last tool,
12
- * last system block) and on the last block of the conversation, adds a
13
- * middle anchor when the conversation is longer than the 20-block lookback,
14
- * prices the request sent N times with and without the plan, and with
15
- * --out saves the request with the breakpoints in place.
22
+ * last system block) and at the end of the conversation, there by automatic
23
+ * caching unless the platform lacks it or --explicit asks for a block-level
24
+ * one; adds a middle anchor when the conversation is longer than the
25
+ * 20-position lookback; prices the request sent N times with and without the
26
+ * plan; and with --out saves the request with the breakpoints in place.
16
27
  *
17
28
  * Pricing assumes the same request is sent N times (an agent loop's steps, a
18
29
  * shared system prompt and document set); cache writes cost 1.25x input
19
- * (2x with ttl "1h"), reads 0.1x.
30
+ * (2x with ttl "1h"), reads the model's own cache-read rate (0.1x; 0.05x on
31
+ * Opus 5.5 and Sonnet 5.5; 0.025x on Fable and Mythos 5.1).
20
32
  */
21
33
  export interface Breakpoint {
22
- /** Where: "tools[3]", "system[1]", "messages[12].content[0]". */
34
+ /** Where: "tools[3]", "system[1]", "messages[12].content[0]", or "top level (automatic)". */
23
35
  at: string;
36
+ /** The top-level automatic breakpoint: it lands on the last block and follows the conversation. */
37
+ automatic?: boolean;
24
38
  /** Prefix tokens cached up to and including this point. */
25
39
  prefixTokens: number;
26
40
  why: string;
@@ -37,10 +51,16 @@ export interface CachePlan {
37
51
  calls: number;
38
52
  usdWithout?: number;
39
53
  usdWith?: number;
54
+ /** Cache reads relative to input, for this model. */
55
+ readMultiplier?: number;
40
56
  notes: string[];
41
57
  }
42
58
  export declare function minCacheableTokens(model?: string): number;
43
- export declare function planCache(request: unknown, calls?: number, modelOverride?: string): {
59
+ export interface CachePlanOptions {
60
+ /** Place the conversation's breakpoint on its last block instead of using top-level automatic caching. */
61
+ explicit?: boolean;
62
+ }
63
+ export declare function planCache(request: unknown, calls?: number, modelOverride?: string, opts?: CachePlanOptions): {
44
64
  plan: CachePlan;
45
65
  apply: () => Record<string, any>;
46
66
  };
package/dist/cacheplan.js CHANGED
@@ -6,17 +6,29 @@
6
6
  * messages. A breakpoint caches everything up to and including the block it
7
7
  * sits on, a prefix under the model's minimum (512 to 4,096 tokens, see
8
8
  * minCacheableTokens) is not cached at all, a request may carry at most 4
9
- * breakpoints, and the cache looks back at most 20 blocks from a breakpoint
10
- * for an earlier hit.
9
+ * breakpoints, and the cache looks back at most 20 positions from a
10
+ * breakpoint for an earlier hit (a run of tool_use blocks, or of
11
+ * tool_result blocks, is one position).
12
+ *
13
+ * Automatic caching (prompt-caching docs, Oct 2026): one top-level
14
+ * `cache_control` puts a breakpoint on the last cacheable block and moves it
15
+ * forward as the conversation grows, so the app never re-places it. It takes
16
+ * one of the 4 slots; with 4 explicit breakpoints as well, or an explicit one
17
+ * on the last block at a different TTL, the API answers 400. Every platform
18
+ * has it except Bedrock's legacy integration (Opus 4.6 and earlier), which
19
+ * rejects the field.
20
+ *
11
21
  * The planner places breakpoints at the ends of the stable parts (last tool,
12
- * last system block) and on the last block of the conversation, adds a
13
- * middle anchor when the conversation is longer than the 20-block lookback,
14
- * prices the request sent N times with and without the plan, and with
15
- * --out saves the request with the breakpoints in place.
22
+ * last system block) and at the end of the conversation, there by automatic
23
+ * caching unless the platform lacks it or --explicit asks for a block-level
24
+ * one; adds a middle anchor when the conversation is longer than the
25
+ * 20-position lookback; prices the request sent N times with and without the
26
+ * plan; and with --out saves the request with the breakpoints in place.
16
27
  *
17
28
  * Pricing assumes the same request is sent N times (an agent loop's steps, a
18
29
  * shared system prompt and document set); cache writes cost 1.25x input
19
- * (2x with ttl "1h"), reads 0.1x.
30
+ * (2x with ttl "1h"), reads the model's own cache-read rate (0.1x; 0.05x on
31
+ * Opus 5.5 and Sonnet 5.5; 0.025x on Fable and Mythos 5.1).
20
32
  */
21
33
  import { estimateTokens, formatTokens } from "./tokens.js";
22
34
  import { formatUsd, pricingFor } from "./pricing.js";
@@ -66,7 +78,7 @@ function blocksOf(req, model, longTtl = false) {
66
78
  };
67
79
  const tok = (x) => estimateTokens(typeof x === "string" ? x : JSON.stringify(x ?? ""), model);
68
80
  (Array.isArray(req.tools) ? req.tools : []).forEach((t, i) => {
69
- out.push({ at: `tools[${i}]`, tokens: tok(t), section: "tools", hasBreakpoint: Boolean(t?.cache_control), set: mark(t) });
81
+ out.push({ at: `tools[${i}]`, tokens: tok(t), section: "tools", hasBreakpoint: Boolean(t?.cache_control), ttl: blockTtl(t), set: mark(t) });
70
82
  });
71
83
  if (typeof req.system === "string" && req.system) {
72
84
  // A string system prompt cannot carry cache_control: it becomes one text block when planned.
@@ -83,7 +95,7 @@ function blocksOf(req, model, longTtl = false) {
83
95
  });
84
96
  }
85
97
  else if (Array.isArray(req.system)) {
86
- req.system.forEach((b, i) => out.push({ at: `system[${i}]`, tokens: tok(b?.text ?? b), section: "system", hasBreakpoint: Boolean(b?.cache_control), set: mark(b) }));
98
+ req.system.forEach((b, i) => out.push({ at: `system[${i}]`, tokens: tok(b?.text ?? b), section: "system", hasBreakpoint: Boolean(b?.cache_control), ttl: blockTtl(b), set: mark(b) }));
87
99
  }
88
100
  (Array.isArray(req.messages) ? req.messages : []).forEach((m, i) => {
89
101
  if (typeof m?.content === "string") {
@@ -103,20 +115,48 @@ function blocksOf(req, model, longTtl = false) {
103
115
  else if (Array.isArray(m?.content)) {
104
116
  m.content.forEach((b, j) => {
105
117
  const isImage = b?.type === "image";
106
- out.push({ at: `messages[${i}].content[${j}]`, tokens: isImage ? 1600 : tok(b?.text ?? b?.content ?? b) + (j === 0 ? 4 : 0), section: "messages", hasBreakpoint: Boolean(b?.cache_control), set: mark(b) });
118
+ out.push({ at: `messages[${i}].content[${j}]`, tokens: isImage ? 1600 : tok(b?.text ?? b?.content ?? b) + (j === 0 ? 4 : 0), section: "messages", type: b?.type, hasBreakpoint: Boolean(b?.cache_control), ttl: blockTtl(b), set: mark(b) });
107
119
  });
108
120
  }
109
121
  });
110
122
  return out;
111
123
  }
112
- export function planCache(request, calls = 10, modelOverride) {
124
+ const blockTtl = (obj) => (obj?.cache_control ? (obj.cache_control.ttl === "1h" ? "1h" : "5m") : undefined);
125
+ /**
126
+ * Bedrock's legacy integration rejects a top-level cache_control (400): its
127
+ * ids are `anthropic.claude-…` (with an optional region prefix) and it serves
128
+ * Opus 4.6 and earlier.
129
+ */
130
+ function legacyBedrock(model) {
131
+ const m = (model ?? "").toLowerCase();
132
+ if (!/^(?:[a-z]{2,6}\.)?anthropic\.claude/.test(m))
133
+ return false;
134
+ const cur = /(opus|sonnet|haiku)-(\d+)(?:-(\d{1,2}))?(?!\d)/.exec(m);
135
+ if (cur)
136
+ return Number(cur[2]) + Number(cur[3] ?? 0) / 10 <= 4.6;
137
+ return /claude-\d(?:-\d)?-(opus|sonnet|haiku)/.test(m); // Claude 3.x
138
+ }
139
+ /** Lookback positions of each block: a run of tool_use (or tool_result) blocks is one. */
140
+ function positions(blocks) {
141
+ const out = [];
142
+ let pos = -1;
143
+ blocks.forEach((b, i) => {
144
+ const prev = blocks[i - 1];
145
+ const sameRun = prev && b.section === "messages" && prev.section === "messages" && (b.type === "tool_use" || b.type === "tool_result") && prev.type === b.type;
146
+ if (!sameRun)
147
+ pos++;
148
+ out.push(pos);
149
+ });
150
+ return out;
151
+ }
152
+ export function planCache(request, calls = 10, modelOverride, opts = {}) {
113
153
  const req = (typeof request === "string" ? JSON.parse(request) : request);
114
154
  const model = modelOverride ?? (typeof req.model === "string" ? req.model : undefined);
115
155
  const notes = [];
116
156
  const isOpenAI = Array.isArray(req.input) || (Array.isArray(req.messages) && req.messages.some((m) => m?.role === "system" || m?.role === "developer" || m?.role === "tool"));
117
157
  if (isOpenAI || /gpt|^o\d/i.test(model ?? "")) {
118
158
  const text = JSON.stringify(req.tools ?? "") + JSON.stringify(req.messages ?? req.input ?? "");
119
- notes.push("OpenAI caches automatically: any request prefix over 1,024 tokens that matches an earlier one is billed at the cached rate, with no markers to place.", "What you control is order: keep tools, instructions and reference documents first and identical between calls, and put per-call content last.", "Set `prompt_cache_key` to a stable value per conversation or tenant so requests that share a prefix land on the same cache.");
159
+ notes.push("OpenAI caches automatically: any request prefix over 1,024 tokens that matches an earlier one is billed at the cached rate, with no markers to place.", "What you control is order: keep tools, instructions and reference documents first and identical between calls, and put per-call content last.", "Set `prompt_cache_key` to a stable value per conversation or tenant so requests that share a prefix land on the same cache (models before GPT-5.6; from 5.6 on it only separates cache accounting). The context-doctor proxy adds one per conversation when a request has none.");
120
160
  return {
121
161
  plan: { provider: "openai", model, totalTokens: estimateTokens(text, model), minCacheable: 1024, existing: [], plan: [], cachedTokens: 0, calls, notes },
122
162
  apply: () => req,
@@ -131,39 +171,70 @@ export function planCache(request, calls = 10, modelOverride) {
131
171
  const minCacheable = minCacheableTokens(model);
132
172
  const prefixAt = (i) => blocks.slice(0, i + 1).reduce((s, b) => s + b.tokens, 0);
133
173
  const lastIndex = (section) => blocks.map((b) => b.section).lastIndexOf(section);
174
+ // A top-level cache_control already in the request is automatic caching.
175
+ const autoNow = req.cache_control && typeof req.cache_control === "object" ? req.cache_control : undefined;
176
+ const bedrock = legacyBedrock(model);
177
+ const useAuto = !bedrock && (!opts.explicit || autoNow !== undefined);
134
178
  const picks = [];
135
- const pick = (i, why) => {
136
- if (i < 0 || picks.some((p) => p.i === i) || prefixAt(i) < minCacheable)
179
+ const pick = (i, why, auto = false) => {
180
+ if (i < 0 || picks.some((p) => p.i === i && !p.auto) || prefixAt(i) < minCacheable)
137
181
  return;
138
- picks.push({ i, why });
182
+ picks.push({ i, why, auto });
139
183
  };
140
184
  const lastMsg = lastIndex("messages");
185
+ // Automatic caching lands on the last cacheable block, whichever section it is in.
186
+ const lastBlock = blocks.length - 1;
141
187
  pick(lastIndex("tools"), "end of the tool definitions: stable across every call");
142
188
  pick(lastIndex("system"), "end of the system prompt: stable across every call");
143
189
  // The conversation boundary moves forward each turn; a breakpoint on the last block caches the whole history for the next call.
144
- pick(lastMsg, "last block of the conversation: the next call reads everything before it from cache");
145
- // Beyond 20 blocks back from the moving breakpoint the cache stops looking; anchor the middle.
190
+ if (useAuto) {
191
+ // An explicit breakpoint where the automatic one lands adds nothing.
192
+ const dup = picks.findIndex((p) => p.i === lastBlock);
193
+ if (dup >= 0)
194
+ picks.splice(dup, 1);
195
+ pick(lastBlock, "automatic caching: one top-level cache_control puts the breakpoint on the last block and moves it forward as the conversation grows", true);
196
+ }
197
+ else {
198
+ pick(lastMsg, "last block of the conversation: the next call reads everything before it from cache");
199
+ }
200
+ // Beyond 20 positions back from the moving breakpoint the cache stops looking; anchor the middle.
201
+ const pos = positions(blocks);
146
202
  const firstMsg = blocks.findIndex((b) => b.section === "messages");
147
- if (firstMsg >= 0 && lastMsg - firstMsg > LOOKBACK_BLOCKS && picks.length < MAX_BREAKPOINTS) {
148
- pick(lastMsg - LOOKBACK_BLOCKS, `anchor ${LOOKBACK_BLOCKS} blocks back: the cache only looks back ${LOOKBACK_BLOCKS} blocks from a breakpoint`);
203
+ if (firstMsg >= 0 && lastMsg >= 0 && pos[lastMsg] - pos[firstMsg] > LOOKBACK_BLOCKS && picks.length < MAX_BREAKPOINTS) {
204
+ const target = pos[lastMsg] - LOOKBACK_BLOCKS;
205
+ pick(pos.findIndex((p) => p >= target), `anchor ${LOOKBACK_BLOCKS} positions back: the cache only looks back ${LOOKBACK_BLOCKS} positions from a breakpoint`);
149
206
  }
150
- picks.sort((a, b) => a.i - b.i);
207
+ picks.sort((a, b) => a.i - b.i || Number(a.auto) - Number(b.auto));
151
208
  while (picks.length > MAX_BREAKPOINTS)
152
209
  picks.splice(1, 1);
153
- const existing = blocks.filter((b) => b.hasBreakpoint).map((b) => b.at);
154
- if (existing.length > MAX_BREAKPOINTS)
155
- notes.push(`The request carries ${existing.length} breakpoints; the API rejects more than ${MAX_BREAKPOINTS}.`);
210
+ const explicitNow = blocks.filter((b) => b.hasBreakpoint);
211
+ const existing = [...(autoNow ? ["top level (automatic)"] : []), ...explicitNow.map((b) => b.at)];
212
+ if (existing.length > MAX_BREAKPOINTS) {
213
+ notes.push(autoNow
214
+ ? `The request carries ${explicitNow.length} block breakpoints and a top-level cache_control, which takes a slot of its own: the API rejects more than ${MAX_BREAKPOINTS} (400).`
215
+ : `The request carries ${existing.length} breakpoints; the API rejects more than ${MAX_BREAKPOINTS}.`);
216
+ }
217
+ const last = blocks[blocks.length - 1];
218
+ const ttlOf = (c) => (c?.ttl === "1h" ? "1h" : "5m");
219
+ if (autoNow && last?.hasBreakpoint && last.ttl !== ttlOf(autoNow)) {
220
+ notes.push(`The last block's own cache_control (${last.ttl}) differs from the top-level one (${ttlOf(autoNow)}): the API answers 400. Remove one.`);
221
+ }
222
+ if (bedrock && autoNow)
223
+ notes.push("Bedrock's legacy integration (Opus 4.6 and earlier) answers a top-level cache_control with a 400: use block-level breakpoints there (this plan does).");
224
+ if (useAuto && picks.length === 1 && picks[0].auto)
225
+ notes.push("Automatic caching is all this request needs: one top-level field, nothing to move as the conversation grows.");
156
226
  if (total < minCacheable)
157
227
  notes.push(`The whole request is ~${formatTokens(total)} tokens, under the ${formatTokens(minCacheable)} minimum ${model ?? "this model"} caches: caching cannot help until it grows.`);
158
228
  const cachedTokens = picks.length ? prefixAt(picks[picks.length - 1].i) : 0;
159
229
  const price = pricingFor(model);
160
230
  const writeMult = longTtl ? 2 : 1.25;
161
- let usdWithout, usdWith;
231
+ let usdWithout, usdWith, readMultiplier;
162
232
  if (price) {
163
233
  const p = price.inputPerM / 1e6;
234
+ readMultiplier = price.cacheReadPerM / price.inputPerM;
164
235
  usdWithout = calls * total * p;
165
236
  const rest = total - cachedTokens;
166
- usdWith = cachedTokens * writeMult * p + rest * p + (calls - 1) * (cachedTokens * 0.1 * p + rest * p);
237
+ usdWith = cachedTokens * writeMult * p + rest * p + (calls - 1) * (cachedTokens * readMultiplier * p + rest * p);
167
238
  }
168
239
  return {
169
240
  plan: {
@@ -172,18 +243,26 @@ export function planCache(request, calls = 10, modelOverride) {
172
243
  totalTokens: total,
173
244
  minCacheable,
174
245
  existing,
175
- plan: picks.map((p) => ({ at: blocks[p.i].at, prefixTokens: prefixAt(p.i), why: p.why })),
246
+ plan: picks.map((p) => (p.auto
247
+ ? { at: "top level (automatic)", automatic: true, prefixTokens: prefixAt(p.i), why: p.why }
248
+ : { at: blocks[p.i].at, prefixTokens: prefixAt(p.i), why: p.why })),
176
249
  cachedTokens,
177
250
  calls,
178
251
  usdWithout,
179
252
  usdWith,
253
+ readMultiplier,
180
254
  notes,
181
255
  },
182
256
  apply: () => {
183
257
  for (const b of blocks)
184
258
  b.set(false);
185
- for (const p of picks)
186
- blocks[p.i].set(true);
259
+ delete req.cache_control;
260
+ for (const p of picks) {
261
+ if (p.auto)
262
+ req.cache_control = autoNow ?? (longTtl ? { type: "ephemeral", ttl: "1h" } : { type: "ephemeral" });
263
+ else
264
+ blocks[p.i].set(true);
265
+ }
187
266
  return req;
188
267
  },
189
268
  };
@@ -203,10 +282,12 @@ export function renderCachePlan(p) {
203
282
  out.push(`Place cache_control on (${p.plan.length} of ${MAX_BREAKPOINTS} allowed):`);
204
283
  for (const b of p.plan)
205
284
  out.push(` ${b.at.padEnd(26)} prefix ~${formatTokens(b.prefixTokens).padStart(6)} ${b.why}`);
285
+ if (p.plan.some((b) => b.automatic))
286
+ out.push(` (top level: "cache_control": {"type": "ephemeral"} beside "model"; --explicit plans a block-level one instead)`);
206
287
  }
207
288
  if (p.usdWithout !== undefined && p.usdWith !== undefined && p.plan.length) {
208
289
  const saved = p.usdWithout - p.usdWith;
209
- out.push("", `Sent ${p.calls} times: ${formatUsd(p.usdWithout)} of input without caching, ${formatUsd(p.usdWith)} with this plan (${saved >= 0 ? "saves" : "costs"} ${formatUsd(Math.abs(saved))}, ${Math.round((Math.abs(saved) / p.usdWithout) * 100)}%).`, `(~${formatTokens(p.cachedTokens)} tokens read at 0.1x after the first call, which writes them once at the cache-write rate.)`);
290
+ out.push("", `Sent ${p.calls} times: ${formatUsd(p.usdWithout)} of input without caching, ${formatUsd(p.usdWith)} with this plan (${saved >= 0 ? "saves" : "costs"} ${formatUsd(Math.abs(saved))}, ${Math.round((Math.abs(saved) / p.usdWithout) * 100)}%).`, `(~${formatTokens(p.cachedTokens)} tokens read at ${p.readMultiplier !== undefined ? `${+p.readMultiplier.toFixed(3)}x` : "the cache-read rate"} after the first call, which writes them once at the cache-write rate.)`);
210
291
  }
211
292
  if (p.notes.length)
212
293
  out.push("", ...p.notes.map((n) => `! ${n}`));