context-doctor 0.33.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.
- package/README.md +9 -9
- package/dist/autopilot.d.ts +0 -6
- package/dist/autopilot.js +37 -2
- package/dist/cachekey.d.ts +25 -0
- package/dist/cachekey.js +73 -0
- package/dist/cacheplan.d.ts +29 -9
- package/dist/cacheplan.js +110 -29
- package/dist/cli.js +5 -3
- package/dist/codexroute.d.ts +46 -0
- package/dist/codexroute.js +122 -0
- package/dist/coldresume.d.ts +62 -0
- package/dist/coldresume.js +85 -6
- package/dist/compactquality.d.ts +2 -0
- package/dist/compactquality.js +12 -2
- package/dist/compactwindow.d.ts +2 -0
- package/dist/compactwindow.js +30 -7
- package/dist/doctor.d.ts +5 -0
- package/dist/doctor.js +62 -9
- package/dist/hook.js +23 -4
- package/dist/install.d.ts +10 -0
- package/dist/install.js +45 -21
- package/dist/ledger.d.ts +2 -0
- package/dist/mcp.js +5 -5
- package/dist/proxy.d.ts +14 -1
- package/dist/proxy.js +45 -4
- package/dist/savings.d.ts +14 -1
- package/dist/savings.js +3 -10
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -96,7 +96,7 @@ On a Claude subscription you do not pay list price; the same tokens come out of
|
|
|
96
96
|
| **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
97
|
| **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
98
|
| **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`) |
|
|
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 (`autopilot on` sets `openai_base_url` in `~/.codex/config.toml`; Codex no longer reads `OPENAI_BASE_URL`) |
|
|
100
100
|
| **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
101
|
| **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
102
|
| **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 +107,17 @@ Not claimed, because no process on your machine sends those requests: trimming i
|
|
|
107
107
|
|
|
108
108
|
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
109
|
|
|
110
|
-
> 1.
|
|
111
|
-
> 2.
|
|
112
|
-
> 3.
|
|
113
|
-
> 4.
|
|
114
|
-
> 5.
|
|
110
|
+
> 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.
|
|
111
|
+
> 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.
|
|
112
|
+
> 3. Refer to earlier content by name; never re-quote it or inline base64.
|
|
113
|
+
> 4. To answer from a big file or folder you won't edit, call pack_context with the question; don't read it whole.
|
|
114
|
+
> 5. If optimize_context returns a pruned-turns digest, write its ≤150-token summary.
|
|
115
115
|
|
|
116
116
|
## Commands
|
|
117
117
|
|
|
118
118
|
| Command | What it does |
|
|
119
119
|
|---|---|
|
|
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`
|
|
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`, `postToolUseFailure` and `sessionStart`); Claude Code's `PreCompact` and `SessionStart` hooks. `--statusline` adds the status bar line ([details](./docs/install.md)) |
|
|
121
121
|
| `context-doctor doctor` | Self-check the whole installation — one pasteable ✓/✗ diagnosis with fixes |
|
|
122
122
|
| `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
123
|
| `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 +139,7 @@ The MCP server hands these standing rules, verbatim, to every chat where it is e
|
|
|
139
139
|
| `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
140
|
| `context-doctor subagents [--days n]` | Which subagents paid for themselves: each one's bill vs the same steps run in the parent session |
|
|
141
141
|
| `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
|
|
142
|
+
| `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
143
|
| `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
144
|
| `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
145
|
| `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 +154,8 @@ The MCP server hands these standing rules, verbatim, to every chat where it is e
|
|
|
154
154
|
|
|
155
155
|
## What's new
|
|
156
156
|
|
|
157
|
+
- **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.
|
|
157
158
|
- **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.
|
|
159
159
|
|
|
160
160
|
Every release: [docs/whats-new.md](./docs/whats-new.md).
|
|
161
161
|
|
package/dist/autopilot.d.ts
CHANGED
|
@@ -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
|
-
|
|
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;
|
package/dist/cachekey.js
ADDED
|
@@ -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
|
+
}
|
package/dist/cacheplan.d.ts
CHANGED
|
@@ -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
|
|
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
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
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
|
|
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
|
|
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
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
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
|
-
|
|
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
|
-
|
|
145
|
-
|
|
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
|
-
|
|
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
|
|
154
|
-
|
|
155
|
-
|
|
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 *
|
|
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) => (
|
|
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
|
-
|
|
186
|
-
|
|
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
|
|
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}`));
|
package/dist/cli.js
CHANGED
|
@@ -134,9 +134,10 @@ Fix on request:
|
|
|
134
134
|
--semantic: also rank by meaning with a local
|
|
135
135
|
Ollama embedding model, when one is installed
|
|
136
136
|
(--embed-model <name> picks it)
|
|
137
|
-
context-doctor cache-plan <request.json> [--calls n] [--out file]
|
|
137
|
+
context-doctor cache-plan <request.json> [--calls n] [--out file] [--explicit]
|
|
138
138
|
Where an Anthropic request should carry cache_control,
|
|
139
139
|
what it saves over n calls; --out writes it applied
|
|
140
|
+
(top-level automatic caching unless --explicit)
|
|
140
141
|
|
|
141
142
|
Integrations:
|
|
142
143
|
context-doctor ci [--base <ref>] [--max-tokens n] [--max-increase n] [--markdown]
|
|
@@ -295,6 +296,7 @@ const FLAGS = [
|
|
|
295
296
|
{ names: ["--mcp"], set: (a) => { a.mcp = true; } },
|
|
296
297
|
{ names: ["--write"], set: (a) => { a.write = true; } },
|
|
297
298
|
{ names: ["--calls"], value: "number", num: { min: 1, integer: true }, set: (a, v) => { a.calls = v; } },
|
|
299
|
+
{ names: ["--explicit"], set: (a) => { a.explicit = true; } },
|
|
298
300
|
{ names: ["--semantic"], set: (a) => { a.semantic = a.semantic || true; } },
|
|
299
301
|
{ names: ["--embed-model"], value: "text", set: (a, v) => { a.semantic = v; } },
|
|
300
302
|
{ names: ["--base"], value: "text", set: (a, v) => { a.base = v; } },
|
|
@@ -857,12 +859,12 @@ async function main() {
|
|
|
857
859
|
if (args.command === "cache-plan") {
|
|
858
860
|
const file = args.positionals?.[0];
|
|
859
861
|
if (!file) {
|
|
860
|
-
console.error("usage: context-doctor cache-plan <request.json|-> [--calls 10] [--out planned.json]");
|
|
862
|
+
console.error("usage: context-doctor cache-plan <request.json|-> [--calls 10] [--out planned.json] [--explicit]");
|
|
861
863
|
process.exit(1);
|
|
862
864
|
}
|
|
863
865
|
let result;
|
|
864
866
|
try {
|
|
865
|
-
result = planCache(readInput(file), args.calls ?? 10, args.model);
|
|
867
|
+
result = planCache(readInput(file), args.calls ?? 10, args.model, { explicit: args.explicit });
|
|
866
868
|
}
|
|
867
869
|
catch (e) {
|
|
868
870
|
console.error(`Could not read a request from ${file}: ${e.message}`);
|