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.
- package/README.md +13 -10
- package/dist/autoclear.d.ts +5 -2
- package/dist/autoclear.js +57 -19
- 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/cachemisses.d.ts +88 -0
- package/dist/cachemisses.js +325 -0
- package/dist/cacheplan.d.ts +30 -10
- package/dist/cacheplan.js +157 -32
- package/dist/cli.js +68 -19
- 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 +21 -3
- package/dist/compactwindow.d.ts +2 -0
- package/dist/compactwindow.js +30 -7
- package/dist/config.d.ts +11 -0
- package/dist/config.js +117 -4
- package/dist/dashboard.js +15 -1
- package/dist/doctor.d.ts +23 -0
- package/dist/doctor.js +133 -10
- package/dist/hook.d.ts +18 -0
- package/dist/hook.js +58 -8
- package/dist/impact.js +32 -4
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/install.d.ts +25 -0
- package/dist/install.js +148 -45
- package/dist/ledger.d.ts +2 -0
- package/dist/mcp.js +56 -53
- package/dist/modelswitch.d.ts +76 -0
- package/dist/modelswitch.js +184 -0
- package/dist/optimize.js +40 -6
- package/dist/pack.d.ts +32 -3
- package/dist/pack.js +176 -24
- package/dist/parse.d.ts +3 -1
- package/dist/parse.js +123 -3
- package/dist/pricing.js +8 -0
- package/dist/profile.js +60 -17
- package/dist/proxy.d.ts +22 -1
- package/dist/proxy.js +89 -12
- package/dist/report.js +8 -2
- package/dist/savings.d.ts +15 -2
- package/dist/savings.js +9 -11
- package/dist/session.js +19 -3
- package/dist/sketch.d.ts +2 -0
- package/dist/sketch.js +10 -1
- package/dist/tokens.js +20 -9
- package/dist/wrap.js +27 -5
- package/package.json +1 -1
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,92 @@ 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
|
-
|
|
113
|
-
|
|
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
|
+
/** Gemini text in a request: the text of every part (attachments as a nominal size). */
|
|
153
|
+
function geminiTokens(req, model) {
|
|
154
|
+
const parts = [];
|
|
155
|
+
const sys = req.systemInstruction ?? req.system_instruction;
|
|
156
|
+
if (typeof sys === "string")
|
|
157
|
+
parts.push({ text: sys });
|
|
158
|
+
else if (Array.isArray(sys?.parts))
|
|
159
|
+
parts.push(...sys.parts);
|
|
160
|
+
for (const c of Array.isArray(req.contents) ? req.contents : [])
|
|
161
|
+
if (Array.isArray(c?.parts))
|
|
162
|
+
parts.push(...c.parts);
|
|
163
|
+
let n = req.tools ? estimateTokens(JSON.stringify(req.tools), model) : 0;
|
|
164
|
+
for (const p of parts) {
|
|
165
|
+
if (typeof p?.text === "string")
|
|
166
|
+
n += estimateTokens(p.text, model);
|
|
167
|
+
else if (p?.inlineData || p?.fileData)
|
|
168
|
+
n += 258; // nominal: a small image on Gemini 2.x; tiling and Gemini 3's media_resolution change it
|
|
169
|
+
else
|
|
170
|
+
n += estimateTokens(JSON.stringify(p ?? ""), model);
|
|
171
|
+
}
|
|
172
|
+
return n;
|
|
173
|
+
}
|
|
174
|
+
/** Smallest prefix Gemini caches implicitly (Gemini API caching docs, Oct 2026: 4,096 for Gemini 3; Vertex lists up to 6,144 for some). */
|
|
175
|
+
const GEMINI_CACHE_MINIMUM = 4096;
|
|
176
|
+
export function planCache(request, calls = 10, modelOverride, opts = {}) {
|
|
177
|
+
// A copy: apply() places breakpoints on the request it returns, and the
|
|
178
|
+
// caller's own object (the library takes one) must come back as it was.
|
|
179
|
+
const req = (typeof request === "string" ? JSON.parse(request) : structuredClone(request));
|
|
180
|
+
if (!req || typeof req !== "object" || Array.isArray(req))
|
|
181
|
+
throw new Error("expected a request object ({model, messages, …})");
|
|
114
182
|
const model = modelOverride ?? (typeof req.model === "string" ? req.model : undefined);
|
|
115
183
|
const notes = [];
|
|
184
|
+
// Gemini: `contents`, or a gemini model. Read as Anthropic it was ~0 tokens
|
|
185
|
+
// with breakpoints Gemini has no field for.
|
|
186
|
+
if (Array.isArray(req.contents) || /gemini/i.test(model ?? "")) {
|
|
187
|
+
const total = geminiTokens(req, model);
|
|
188
|
+
notes.push(`Gemini caches implicitly (on by default from Gemini 2.5): a request whose prefix matches an earlier one and is at least ~${formatTokens(GEMINI_CACHE_MINIMUM)} tokens (Gemini 3 on the Gemini API; Vertex lists up to 6,144 for some models) bills that prefix at the cached rate, about 10% of input. There are no markers to place.`, "What you control is order: keep systemInstruction, tools and shared documents first and byte-identical between calls, and put the per-call question last.", "For a guaranteed discount on a large prefix reused for a while, create an explicit cache (cachedContents.create; default TTL 60 minutes, storage billed per hour) and pass its name as `cachedContent` in each request.");
|
|
189
|
+
if (typeof req.cachedContent === "string" || typeof req.cached_content === "string") {
|
|
190
|
+
notes.push("This request already uses an explicit cache (cachedContent): its cached part bills at the cached rate.");
|
|
191
|
+
}
|
|
192
|
+
else if (total < GEMINI_CACHE_MINIMUM) {
|
|
193
|
+
notes.push(`The whole request is ~${formatTokens(total)} tokens, under the implicit-caching minimum: caching cannot help until it grows.`);
|
|
194
|
+
}
|
|
195
|
+
return {
|
|
196
|
+
plan: { provider: "gemini", model, totalTokens: total, minCacheable: GEMINI_CACHE_MINIMUM, existing: [], plan: [], cachedTokens: 0, calls, notes },
|
|
197
|
+
apply: () => req,
|
|
198
|
+
};
|
|
199
|
+
}
|
|
116
200
|
const isOpenAI = Array.isArray(req.input) || (Array.isArray(req.messages) && req.messages.some((m) => m?.role === "system" || m?.role === "developer" || m?.role === "tool"));
|
|
117
201
|
if (isOpenAI || /gpt|^o\d/i.test(model ?? "")) {
|
|
118
202
|
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.");
|
|
203
|
+
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
204
|
return {
|
|
121
205
|
plan: { provider: "openai", model, totalTokens: estimateTokens(text, model), minCacheable: 1024, existing: [], plan: [], cachedTokens: 0, calls, notes },
|
|
122
206
|
apply: () => req,
|
|
@@ -131,39 +215,70 @@ export function planCache(request, calls = 10, modelOverride) {
|
|
|
131
215
|
const minCacheable = minCacheableTokens(model);
|
|
132
216
|
const prefixAt = (i) => blocks.slice(0, i + 1).reduce((s, b) => s + b.tokens, 0);
|
|
133
217
|
const lastIndex = (section) => blocks.map((b) => b.section).lastIndexOf(section);
|
|
218
|
+
// A top-level cache_control already in the request is automatic caching.
|
|
219
|
+
const autoNow = req.cache_control && typeof req.cache_control === "object" ? req.cache_control : undefined;
|
|
220
|
+
const bedrock = legacyBedrock(model);
|
|
221
|
+
const useAuto = !bedrock && (!opts.explicit || autoNow !== undefined);
|
|
134
222
|
const picks = [];
|
|
135
|
-
const pick = (i, why) => {
|
|
136
|
-
if (i < 0 || picks.some((p) => p.i === i) || prefixAt(i) < minCacheable)
|
|
223
|
+
const pick = (i, why, auto = false) => {
|
|
224
|
+
if (i < 0 || picks.some((p) => p.i === i && !p.auto) || prefixAt(i) < minCacheable)
|
|
137
225
|
return;
|
|
138
|
-
picks.push({ i, why });
|
|
226
|
+
picks.push({ i, why, auto });
|
|
139
227
|
};
|
|
140
228
|
const lastMsg = lastIndex("messages");
|
|
229
|
+
// Automatic caching lands on the last cacheable block, whichever section it is in.
|
|
230
|
+
const lastBlock = blocks.length - 1;
|
|
141
231
|
pick(lastIndex("tools"), "end of the tool definitions: stable across every call");
|
|
142
232
|
pick(lastIndex("system"), "end of the system prompt: stable across every call");
|
|
143
233
|
// The conversation boundary moves forward each turn; a breakpoint on the last block caches the whole history for the next call.
|
|
144
|
-
|
|
145
|
-
|
|
234
|
+
if (useAuto) {
|
|
235
|
+
// An explicit breakpoint where the automatic one lands adds nothing.
|
|
236
|
+
const dup = picks.findIndex((p) => p.i === lastBlock);
|
|
237
|
+
if (dup >= 0)
|
|
238
|
+
picks.splice(dup, 1);
|
|
239
|
+
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);
|
|
240
|
+
}
|
|
241
|
+
else {
|
|
242
|
+
pick(lastMsg, "last block of the conversation: the next call reads everything before it from cache");
|
|
243
|
+
}
|
|
244
|
+
// Beyond 20 positions back from the moving breakpoint the cache stops looking; anchor the middle.
|
|
245
|
+
const pos = positions(blocks);
|
|
146
246
|
const firstMsg = blocks.findIndex((b) => b.section === "messages");
|
|
147
|
-
if (firstMsg >= 0 && lastMsg - firstMsg > LOOKBACK_BLOCKS && picks.length < MAX_BREAKPOINTS) {
|
|
148
|
-
|
|
247
|
+
if (firstMsg >= 0 && lastMsg >= 0 && pos[lastMsg] - pos[firstMsg] > LOOKBACK_BLOCKS && picks.length < MAX_BREAKPOINTS) {
|
|
248
|
+
const target = pos[lastMsg] - LOOKBACK_BLOCKS;
|
|
249
|
+
pick(pos.findIndex((p) => p >= target), `anchor ${LOOKBACK_BLOCKS} positions back: the cache only looks back ${LOOKBACK_BLOCKS} positions from a breakpoint`);
|
|
149
250
|
}
|
|
150
|
-
picks.sort((a, b) => a.i - b.i);
|
|
251
|
+
picks.sort((a, b) => a.i - b.i || Number(a.auto) - Number(b.auto));
|
|
151
252
|
while (picks.length > MAX_BREAKPOINTS)
|
|
152
253
|
picks.splice(1, 1);
|
|
153
|
-
const
|
|
154
|
-
|
|
155
|
-
|
|
254
|
+
const explicitNow = blocks.filter((b) => b.hasBreakpoint);
|
|
255
|
+
const existing = [...(autoNow ? ["top level (automatic)"] : []), ...explicitNow.map((b) => b.at)];
|
|
256
|
+
if (existing.length > MAX_BREAKPOINTS) {
|
|
257
|
+
notes.push(autoNow
|
|
258
|
+
? `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).`
|
|
259
|
+
: `The request carries ${existing.length} breakpoints; the API rejects more than ${MAX_BREAKPOINTS}.`);
|
|
260
|
+
}
|
|
261
|
+
const last = blocks[blocks.length - 1];
|
|
262
|
+
const ttlOf = (c) => (c?.ttl === "1h" ? "1h" : "5m");
|
|
263
|
+
if (autoNow && last?.hasBreakpoint && last.ttl !== ttlOf(autoNow)) {
|
|
264
|
+
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.`);
|
|
265
|
+
}
|
|
266
|
+
if (bedrock && autoNow)
|
|
267
|
+
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).");
|
|
268
|
+
if (useAuto && picks.length === 1 && picks[0].auto)
|
|
269
|
+
notes.push("Automatic caching is all this request needs: one top-level field, nothing to move as the conversation grows.");
|
|
156
270
|
if (total < minCacheable)
|
|
157
271
|
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
272
|
const cachedTokens = picks.length ? prefixAt(picks[picks.length - 1].i) : 0;
|
|
159
273
|
const price = pricingFor(model);
|
|
160
274
|
const writeMult = longTtl ? 2 : 1.25;
|
|
161
|
-
let usdWithout, usdWith;
|
|
275
|
+
let usdWithout, usdWith, readMultiplier;
|
|
162
276
|
if (price) {
|
|
163
277
|
const p = price.inputPerM / 1e6;
|
|
278
|
+
readMultiplier = price.cacheReadPerM / price.inputPerM;
|
|
164
279
|
usdWithout = calls * total * p;
|
|
165
280
|
const rest = total - cachedTokens;
|
|
166
|
-
usdWith = cachedTokens * writeMult * p + rest * p + (calls - 1) * (cachedTokens *
|
|
281
|
+
usdWith = cachedTokens * writeMult * p + rest * p + (calls - 1) * (cachedTokens * readMultiplier * p + rest * p);
|
|
167
282
|
}
|
|
168
283
|
return {
|
|
169
284
|
plan: {
|
|
@@ -172,26 +287,34 @@ export function planCache(request, calls = 10, modelOverride) {
|
|
|
172
287
|
totalTokens: total,
|
|
173
288
|
minCacheable,
|
|
174
289
|
existing,
|
|
175
|
-
plan: picks.map((p) => (
|
|
290
|
+
plan: picks.map((p) => (p.auto
|
|
291
|
+
? { at: "top level (automatic)", automatic: true, prefixTokens: prefixAt(p.i), why: p.why }
|
|
292
|
+
: { at: blocks[p.i].at, prefixTokens: prefixAt(p.i), why: p.why })),
|
|
176
293
|
cachedTokens,
|
|
177
294
|
calls,
|
|
178
295
|
usdWithout,
|
|
179
296
|
usdWith,
|
|
297
|
+
readMultiplier,
|
|
180
298
|
notes,
|
|
181
299
|
},
|
|
182
300
|
apply: () => {
|
|
183
301
|
for (const b of blocks)
|
|
184
302
|
b.set(false);
|
|
185
|
-
|
|
186
|
-
|
|
303
|
+
delete req.cache_control;
|
|
304
|
+
for (const p of picks) {
|
|
305
|
+
if (p.auto)
|
|
306
|
+
req.cache_control = autoNow ?? (longTtl ? { type: "ephemeral", ttl: "1h" } : { type: "ephemeral" });
|
|
307
|
+
else
|
|
308
|
+
blocks[p.i].set(true);
|
|
309
|
+
}
|
|
187
310
|
return req;
|
|
188
311
|
},
|
|
189
312
|
};
|
|
190
313
|
}
|
|
191
314
|
export function renderCachePlan(p) {
|
|
192
315
|
const out = ["CACHE PLAN", "═".repeat(56)];
|
|
193
|
-
out.push(`${p.provider === "openai" ? "OpenAI" : "Anthropic"} request${p.model ? ` for ${p.model}` : ""}: ~${formatTokens(p.totalTokens)} tokens.`);
|
|
194
|
-
if (p.provider === "openai") {
|
|
316
|
+
out.push(`${p.provider === "openai" ? "OpenAI" : p.provider === "gemini" ? "Gemini" : "Anthropic"} request${p.model ? ` for ${p.model}` : ""}: ~${formatTokens(p.totalTokens)} tokens.`);
|
|
317
|
+
if (p.provider === "openai" || p.provider === "gemini") {
|
|
195
318
|
out.push("", ...p.notes.map((n) => `• ${n}`));
|
|
196
319
|
return out.join("\n");
|
|
197
320
|
}
|
|
@@ -203,10 +326,12 @@ export function renderCachePlan(p) {
|
|
|
203
326
|
out.push(`Place cache_control on (${p.plan.length} of ${MAX_BREAKPOINTS} allowed):`);
|
|
204
327
|
for (const b of p.plan)
|
|
205
328
|
out.push(` ${b.at.padEnd(26)} prefix ~${formatTokens(b.prefixTokens).padStart(6)} ${b.why}`);
|
|
329
|
+
if (p.plan.some((b) => b.automatic))
|
|
330
|
+
out.push(` (top level: "cache_control": {"type": "ephemeral"} beside "model"; --explicit plans a block-level one instead)`);
|
|
206
331
|
}
|
|
207
332
|
if (p.usdWithout !== undefined && p.usdWith !== undefined && p.plan.length) {
|
|
208
333
|
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
|
|
334
|
+
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
335
|
}
|
|
211
336
|
if (p.notes.length)
|
|
212
337
|
out.push("", ...p.notes.map((n) => `! ${n}`));
|
package/dist/cli.js
CHANGED
|
@@ -39,7 +39,7 @@ import { findPreset, PRESETS, RC_FILENAME } from "./config.js";
|
|
|
39
39
|
import { runWatch } from "./watch.js";
|
|
40
40
|
import { exactTokenCount } from "./exact.js";
|
|
41
41
|
import { modelFamily, recordCalibration } from "./calibration.js";
|
|
42
|
-
import { checkBudget, loadConfig } from "./config.js";
|
|
42
|
+
import { checkBudget, loadConfig, sanitizeRoutes, validateRoutes } from "./config.js";
|
|
43
43
|
import { startDashboard } from "./dashboard.js";
|
|
44
44
|
import { listCursorChats, parseCursorChat } from "./cursor.js";
|
|
45
45
|
import { analyzeCacheUsage, renderCacheReport } from "./cache.js";
|
|
@@ -51,6 +51,7 @@ import { ciReport, renderCiMarkdown, renderCiText } from "./ci.js";
|
|
|
51
51
|
import { renderReads, repeatedReads } from "./reads.js";
|
|
52
52
|
import { costPerTask, renderTasks } from "./tasks.js";
|
|
53
53
|
import { planCache, renderCachePlan } from "./cacheplan.js";
|
|
54
|
+
import { cacheMisses, cacheMissesLine, cacheMissesSignificant, renderCacheMisses } from "./cachemisses.js";
|
|
54
55
|
import { renderPayback, subagentPayback } from "./subagentpay.js";
|
|
55
56
|
import { compactionQuality, renderCompactionQuality } from "./compactquality.js";
|
|
56
57
|
const HELP = `context-doctor — profile and optimize LLM context windows
|
|
@@ -91,6 +92,9 @@ Measure:
|
|
|
91
92
|
cost, and whether a CLAUDE.md summary or pack pays
|
|
92
93
|
context-doctor compactions [--days n] Do sessions work worse right after compacting? Re-reads,
|
|
93
94
|
tool errors and your corrections, before vs after
|
|
95
|
+
context-doctor cache-misses [--days n] Requests that re-wrote the prompt cache while it was
|
|
96
|
+
still warm: priced, by model and context size, with
|
|
97
|
+
the cause where the transcript shows one
|
|
94
98
|
context-doctor accuracy Measure the token heuristic against the API's own
|
|
95
99
|
counts recorded in your transcripts (--limit n)
|
|
96
100
|
context-doctor diff <before> <after> Compare two profiles: what moved, which findings
|
|
@@ -134,9 +138,10 @@ Fix on request:
|
|
|
134
138
|
--semantic: also rank by meaning with a local
|
|
135
139
|
Ollama embedding model, when one is installed
|
|
136
140
|
(--embed-model <name> picks it)
|
|
137
|
-
context-doctor cache-plan <request.json> [--calls n] [--out file]
|
|
141
|
+
context-doctor cache-plan <request.json> [--calls n] [--out file] [--explicit]
|
|
138
142
|
Where an Anthropic request should carry cache_control,
|
|
139
143
|
what it saves over n calls; --out writes it applied
|
|
144
|
+
(top-level automatic caching unless --explicit)
|
|
140
145
|
|
|
141
146
|
Integrations:
|
|
142
147
|
context-doctor ci [--base <ref>] [--max-tokens n] [--max-increase n] [--markdown]
|
|
@@ -182,12 +187,15 @@ Options:
|
|
|
182
187
|
--max-tool-tokens <n> (optimize) Token budget for trimmed tool results (default 300)
|
|
183
188
|
--limit <n> (accuracy, session --list, reads, tasks, subagents) How many to sample
|
|
184
189
|
or list
|
|
185
|
-
--days <n> (savings, compact-window, overhead, reads, tasks, subagents, compactions
|
|
190
|
+
--days <n> (savings, compact-window, overhead, reads, tasks, subagents, compactions,
|
|
191
|
+
cache-misses)
|
|
186
192
|
Days of history to read (default 30; compactions 60)
|
|
187
193
|
-q, --query <text> (pack) The question to rank chunks against
|
|
188
194
|
--max-tokens <n> (pack) Token budget (default 4000); (ci) fail over this many tokens
|
|
189
195
|
--chunk-tokens <n> (pack) Largest chunk, in tokens (default 400)
|
|
190
196
|
--ids <a#2,b#5> (pack) Return these chunks by id
|
|
197
|
+
--include-secrets (pack) Also pack .env, .npmrc, private keys and other credential files,
|
|
198
|
+
and paths under ~/.ssh, ~/.aws and similar (skipped by default)
|
|
191
199
|
--min-tokens <n> (overhead split) Smallest section to move, in tokens (default 400)
|
|
192
200
|
--requests-per-day <n> (ci --markdown) Price the change at this many requests a day
|
|
193
201
|
--check <cmd> (experiment) Command whose exit code is the pass/fail for each arm
|
|
@@ -250,7 +258,7 @@ function usageError(message) {
|
|
|
250
258
|
const COMMANDS = [
|
|
251
259
|
"analyze", "optimize", "proxy", "install", "uninstall", "savings", "compact-window", "autopilot", "mcp",
|
|
252
260
|
"instructions", "session", "cursor", "statusline", "hook", "report", "doctor", "dashboard", "init",
|
|
253
|
-
"experiment", "diff", "accuracy", "overhead", "ci", "cache-plan", "compactions", "subagents", "tasks",
|
|
261
|
+
"experiment", "diff", "accuracy", "overhead", "ci", "cache-plan", "compactions", "cache-misses", "subagents", "tasks",
|
|
254
262
|
"reads", "pack", "watch", "help", "version",
|
|
255
263
|
];
|
|
256
264
|
/** --strategy takes one of the optimizer's ids; a typo used to run nothing and report success. */
|
|
@@ -295,8 +303,10 @@ const FLAGS = [
|
|
|
295
303
|
{ names: ["--mcp"], set: (a) => { a.mcp = true; } },
|
|
296
304
|
{ names: ["--write"], set: (a) => { a.write = true; } },
|
|
297
305
|
{ names: ["--calls"], value: "number", num: { min: 1, integer: true }, set: (a, v) => { a.calls = v; } },
|
|
306
|
+
{ names: ["--explicit"], set: (a) => { a.explicit = true; } },
|
|
298
307
|
{ names: ["--semantic"], set: (a) => { a.semantic = a.semantic || true; } },
|
|
299
308
|
{ names: ["--embed-model"], value: "text", set: (a, v) => { a.semantic = v; } },
|
|
309
|
+
{ names: ["--include-secrets"], set: (a) => { a.includeSecrets = true; } },
|
|
300
310
|
{ names: ["--base"], value: "text", set: (a, v) => { a.base = v; } },
|
|
301
311
|
{ names: ["--markdown"], set: (a) => { a.markdown = true; } },
|
|
302
312
|
{ names: ["--max-increase"], value: "number", num: { min: 0, integer: true }, set: (a, v) => { a.maxIncrease = v; } },
|
|
@@ -396,9 +406,15 @@ function applyBudgetGate(overBudget, failOverBudget) {
|
|
|
396
406
|
}
|
|
397
407
|
}
|
|
398
408
|
function readInput(file) {
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
409
|
+
return stripBom(readFileSync(file === "-" ? 0 : file, "utf8"));
|
|
410
|
+
}
|
|
411
|
+
/**
|
|
412
|
+
* A UTF-8 byte-order mark (Windows editors, PowerShell's Out-File) is not
|
|
413
|
+
* part of the text: left in, JSON.parse rejects the file and a valid
|
|
414
|
+
* conversation was reported as not being one.
|
|
415
|
+
*/
|
|
416
|
+
function stripBom(text) {
|
|
417
|
+
return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
|
|
402
418
|
}
|
|
403
419
|
/** The installed package's version, read from its package.json so it cannot drift. */
|
|
404
420
|
function packageVersion() {
|
|
@@ -637,7 +653,15 @@ async function main() {
|
|
|
637
653
|
console.error(`Could not read session: ${e.message}`);
|
|
638
654
|
process.exit(1);
|
|
639
655
|
}
|
|
640
|
-
const
|
|
656
|
+
const sessionConversation = parseConversation(parsed.conversationJson);
|
|
657
|
+
// A file that is not a transcript parses to no messages. It used to print
|
|
658
|
+
// the warning inside a normal report and exit 0; analyze exits 1 for the
|
|
659
|
+
// same thing, and a script cannot tell a profile from a non-file otherwise.
|
|
660
|
+
if (sessionConversation.parseWarning) {
|
|
661
|
+
usageError(`Could not profile ${path} as a session: no conversation messages in it. ` +
|
|
662
|
+
"session reads Claude Code, Codex and Gemini CLI transcripts and ChatGPT exports; for a conversation JSON or a prompt, use analyze.");
|
|
663
|
+
}
|
|
664
|
+
const profile = profileConversation(sessionConversation, args.model ?? parsed.model);
|
|
641
665
|
if (args.json) {
|
|
642
666
|
console.log(JSON.stringify({ session: { path: parsed.path, title: parsed.title, ...(picked ? { picked: picked.how } : {}), toolTimings: parsed.toolTimings ?? [], subagents: subagentReport(path) }, profile }, null, 2));
|
|
643
667
|
// --json is what CI pipes, so the gate must hold here too (as it does for
|
|
@@ -709,9 +733,14 @@ async function main() {
|
|
|
709
733
|
const cwLine = cwReport.sessions > 0 && est
|
|
710
734
|
? { window: est.window, savedUsd: est.savedUsd, compactionsPerWeek: (est.compactions / cwReport.days) * 7, nowPerWeek: (cwReport.actualCompactions / cwReport.days) * 7, isCurrent: setWindow !== undefined }
|
|
711
735
|
: undefined;
|
|
736
|
+
const checking = progressLine("Checking for cache misses");
|
|
737
|
+
const misses = cacheMisses(args.days ?? 30, undefined, checking.tick);
|
|
738
|
+
checking.clear();
|
|
712
739
|
const on = existsSync(autopilotPaths().config);
|
|
713
|
-
if (args.json)
|
|
714
|
-
|
|
740
|
+
if (args.json) {
|
|
741
|
+
const { largest: _largest, ...missSummary } = misses;
|
|
742
|
+
console.log(JSON.stringify({ ...report, cacheMisses: missSummary }, null, 2));
|
|
743
|
+
}
|
|
715
744
|
else if (args.share) {
|
|
716
745
|
const text = renderShare(report);
|
|
717
746
|
console.log(text);
|
|
@@ -719,7 +748,7 @@ async function main() {
|
|
|
719
748
|
console.log(copyToClipboard(text) ? "\n(copied to the clipboard)" : "\n(no clipboard tool found; copy the lines above)");
|
|
720
749
|
}
|
|
721
750
|
else {
|
|
722
|
-
console.log(renderSavings(report, on, cwLine));
|
|
751
|
+
console.log(renderSavings(report, on, cwLine, cacheMissesSignificant(misses) ? cacheMissesLine(misses) : undefined));
|
|
723
752
|
if (!args.command)
|
|
724
753
|
console.log(`\nAll commands: ${selfCommand("--help")}`);
|
|
725
754
|
}
|
|
@@ -816,7 +845,14 @@ async function main() {
|
|
|
816
845
|
let routes = loadedRc.config.routes;
|
|
817
846
|
if (args.config) {
|
|
818
847
|
try {
|
|
819
|
-
|
|
848
|
+
const raw = JSON.parse(readFileSync(args.config, "utf8")).routes;
|
|
849
|
+
// The same rule as the rc file: a value the warning calls ignored is not applied.
|
|
850
|
+
if (raw !== undefined && !Array.isArray(raw))
|
|
851
|
+
console.error(`context-doctor: ${args.config}: routes must be an array — ignored`);
|
|
852
|
+
else if (Array.isArray(raw))
|
|
853
|
+
for (const w of validateRoutes(raw, args.config))
|
|
854
|
+
console.error(`context-doctor: ${w}`);
|
|
855
|
+
routes = sanitizeRoutes(raw);
|
|
820
856
|
}
|
|
821
857
|
catch (e) {
|
|
822
858
|
console.error(`Could not read --config ${args.config}: ${e.message}`);
|
|
@@ -824,7 +860,7 @@ async function main() {
|
|
|
824
860
|
}
|
|
825
861
|
}
|
|
826
862
|
startProxy({
|
|
827
|
-
routes
|
|
863
|
+
routes,
|
|
828
864
|
port: args.port,
|
|
829
865
|
host: args.host,
|
|
830
866
|
token: args.token ?? process.env.CONTEXT_DOCTOR_PROXY_TOKEN,
|
|
@@ -841,6 +877,13 @@ async function main() {
|
|
|
841
877
|
});
|
|
842
878
|
return; // server keeps the process alive
|
|
843
879
|
}
|
|
880
|
+
if (args.command === "cache-misses") {
|
|
881
|
+
const reading = progressLine("Reading your Claude Code transcripts");
|
|
882
|
+
const report = cacheMisses(args.days ?? 30, undefined, reading.tick);
|
|
883
|
+
reading.clear();
|
|
884
|
+
console.log(args.json ? JSON.stringify(report, null, 2) : renderCacheMisses(report));
|
|
885
|
+
return;
|
|
886
|
+
}
|
|
844
887
|
if (args.command === "compactions") {
|
|
845
888
|
const days = args.days ?? 60;
|
|
846
889
|
const q = compactionQuality(days);
|
|
@@ -857,12 +900,12 @@ async function main() {
|
|
|
857
900
|
if (args.command === "cache-plan") {
|
|
858
901
|
const file = args.positionals?.[0];
|
|
859
902
|
if (!file) {
|
|
860
|
-
console.error("usage: context-doctor cache-plan <request.json|-> [--calls 10] [--out planned.json]");
|
|
903
|
+
console.error("usage: context-doctor cache-plan <request.json|-> [--calls 10] [--out planned.json] [--explicit]");
|
|
861
904
|
process.exit(1);
|
|
862
905
|
}
|
|
863
906
|
let result;
|
|
864
907
|
try {
|
|
865
|
-
result = planCache(readInput(file), args.calls ?? 10, args.model);
|
|
908
|
+
result = planCache(readInput(file), args.calls ?? 10, args.model, { explicit: args.explicit });
|
|
866
909
|
}
|
|
867
910
|
catch (e) {
|
|
868
911
|
console.error(`Could not read a request from ${file}: ${e.message}`);
|
|
@@ -871,7 +914,9 @@ async function main() {
|
|
|
871
914
|
console.log(args.json ? JSON.stringify(result.plan, null, 2) : renderCachePlan(result.plan));
|
|
872
915
|
if (args.out) {
|
|
873
916
|
writeFileSync(args.out, JSON.stringify(result.apply(), null, 2));
|
|
874
|
-
console.error(
|
|
917
|
+
console.error(result.plan.plan.length
|
|
918
|
+
? `context-doctor: request with the planned breakpoints written to ${args.out}`
|
|
919
|
+
: `context-doctor: nothing to place; the request was written unchanged to ${args.out}`);
|
|
875
920
|
}
|
|
876
921
|
return;
|
|
877
922
|
}
|
|
@@ -943,9 +988,13 @@ async function main() {
|
|
|
943
988
|
console.error('usage: context-doctor pack <files|dirs...> --query "<question>" [--max-tokens 4000] [--ids a#2,b#5] [--json]');
|
|
944
989
|
process.exit(1);
|
|
945
990
|
}
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
991
|
+
// "-" is stdin, read once beside any other paths (it used to drop them silently).
|
|
992
|
+
const files = paths.filter((p) => p !== "-");
|
|
993
|
+
const { sources, skipped } = files.length
|
|
994
|
+
? readSources(files, { includeSecrets: args.includeSecrets, secretsHint: " (--include-secrets packs it)" })
|
|
995
|
+
: { sources: [], skipped: [] };
|
|
996
|
+
if (paths.includes("-"))
|
|
997
|
+
sources.unshift({ name: "stdin", text: stripBom(readFileSync(0, "utf8")) });
|
|
949
998
|
for (const s of skipped)
|
|
950
999
|
console.error(`context-doctor: skipped ${s}`);
|
|
951
1000
|
if (sources.length === 0)
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Codex on an API key, through autopilot.
|
|
3
|
+
*
|
|
4
|
+
* Verified 2026-10-18 against codex-cli 0.153.4 (the ChatGPT app's) and
|
|
5
|
+
* 0.154.0-alpha (the IDE extension's), and openai/codex main:
|
|
6
|
+
* - The built-in `openai` provider's address is `openai_base_url`, a
|
|
7
|
+
* top-level key of the user's ~/.codex/config.toml (Codex ignores it in a
|
|
8
|
+
* project's .codex/config.toml). The OPENAI_BASE_URL environment variable
|
|
9
|
+
* no longer routes it: with only the variable set, Codex went straight to
|
|
10
|
+
* wss://api.openai.com. With the key set, `codex exec` on an API key sent
|
|
11
|
+
* its requests through the proxy and they showed in /stats.
|
|
12
|
+
* - The key applies whatever the sign-in. With ChatGPT sign-in Codex
|
|
13
|
+
* otherwise talks to chatgpt.com/backend-api/codex, so autopilot sets it
|
|
14
|
+
* only when ~/.codex/auth.json says "apikey", and the every-prompt hook's
|
|
15
|
+
* self-heal takes it out again if the sign-in changes. A ChatGPT-signed-in
|
|
16
|
+
* Codex that reads the same file anyway (the ChatGPT app's Codex tab) is
|
|
17
|
+
* relayed by the proxy to chatgpt.com unedited (see proxy.ts).
|
|
18
|
+
* - Codex tries Responses over WebSocket first; the proxy answers 426, and
|
|
19
|
+
* Codex switches to HTTP for the session at once.
|
|
20
|
+
*
|
|
21
|
+
* config.toml is the user's file: only our one top-level line is ever
|
|
22
|
+
* added, replaced or removed, and a value someone else set is left alone.
|
|
23
|
+
*/
|
|
24
|
+
export declare function codexHomeIn(home: string): string;
|
|
25
|
+
/** How Codex signs in, from auth.json: "apikey", "chatgpt", another mode, or undefined (none yet). */
|
|
26
|
+
export declare function codexAuthMode(codexHome: string): string | undefined;
|
|
27
|
+
/** A top-level string value (before the first [table]), or undefined. */
|
|
28
|
+
export declare function topLevelString(toml: string, key: string): string | undefined;
|
|
29
|
+
/** Set (or with undefined, remove) a top-level string key, touching no other line. */
|
|
30
|
+
export declare function setTopLevelString(toml: string, key: string, value: string | undefined): string;
|
|
31
|
+
export interface CodexRoute {
|
|
32
|
+
/** We wrote our address into config.toml. */
|
|
33
|
+
routed: boolean;
|
|
34
|
+
/** One line for the user, or undefined when Codex is not on this machine. */
|
|
35
|
+
line?: string;
|
|
36
|
+
}
|
|
37
|
+
/** Point Codex at the proxy when, and only when, it signs in with an API key. */
|
|
38
|
+
export declare function routeCodex(home: string, url: string, isOurs: (u: string) => boolean): CodexRoute;
|
|
39
|
+
/** Take our address out of config.toml. True when there was one to take out. */
|
|
40
|
+
export declare function unrouteCodex(home: string, isOurs: (u: string) => boolean): boolean;
|
|
41
|
+
/** What config.toml routes Codex to now, and how Codex signs in. */
|
|
42
|
+
export declare function codexRouting(home: string): {
|
|
43
|
+
present: boolean;
|
|
44
|
+
baseUrl?: string;
|
|
45
|
+
auth?: string;
|
|
46
|
+
};
|