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
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `context-doctor cache-misses`: requests that re-wrote the prompt cache while
|
|
3
|
+
* it should still have been warm.
|
|
4
|
+
*
|
|
5
|
+
* Claude Code caches the conversation as it goes; the next request within the
|
|
6
|
+
* cache's lifetime reads that prefix at the cache-read rate (5-10% of input)
|
|
7
|
+
* and writes only what is new. When a request instead writes most of the
|
|
8
|
+
* context again, at 1.25x input (2x at the 1-hour TTL), the cache missed.
|
|
9
|
+
* Some misses are expected (a model switch: each model has its own cache;
|
|
10
|
+
* a compaction: a new history), the rest are invisible from the client.
|
|
11
|
+
*
|
|
12
|
+
* Definition, request by request over each main-chain transcript:
|
|
13
|
+
* - two consecutive requests (sidechains and synthetic replies skipped),
|
|
14
|
+
* with no compaction (compact_boundary) between them;
|
|
15
|
+
* - the gap under the cache lifetime of both: 1 hour when the request wrote
|
|
16
|
+
* to the 1-hour cache (usage.cache_creation.ephemeral_1h_input_tokens > 0),
|
|
17
|
+
* else 5 minutes;
|
|
18
|
+
* - the previous request's context over 20k tokens (smaller ones are noise);
|
|
19
|
+
* - a miss when the request's cache_creation_input_tokens exceed 60% of the
|
|
20
|
+
* previous request's whole context (input + cache read + cache write).
|
|
21
|
+
*
|
|
22
|
+
* Priced above what the same tokens would have cost as cache reads: the
|
|
23
|
+
* re-written part (up to the previous context) at the write rate minus the
|
|
24
|
+
* read rate. Measured on the author's last 30 days (Oct 2026): 390 misses in
|
|
25
|
+
* 29,287 requests, ~$1,925 above cache-read price, 28% of all cache-write
|
|
26
|
+
* spend; 382 of them with nothing in the transcript to explain them.
|
|
27
|
+
*/
|
|
28
|
+
import { forEachLine, listSessions } from "./session.js";
|
|
29
|
+
import { formatTokens, realModel } from "./tokens.js";
|
|
30
|
+
import { CACHE_WRITE_1H, CACHE_WRITE_5M, pricingFor } from "./pricing.js";
|
|
31
|
+
/** Dollars as a person reads them: "$1,925", "$12.26", "$0". */
|
|
32
|
+
function money(n) {
|
|
33
|
+
if (!(n > 0))
|
|
34
|
+
return "$0";
|
|
35
|
+
if (n >= 100)
|
|
36
|
+
return `$${Math.round(n).toLocaleString("en-US")}`;
|
|
37
|
+
if (n >= 0.01)
|
|
38
|
+
return `$${n.toFixed(2)}`;
|
|
39
|
+
return "<$0.01";
|
|
40
|
+
}
|
|
41
|
+
const FIVE_MIN = 300_000;
|
|
42
|
+
const HOUR = 3_600_000;
|
|
43
|
+
/** Below this the previous context is too small for a miss to matter (or to be told from noise). */
|
|
44
|
+
const MIN_CONTEXT = 20_000;
|
|
45
|
+
/** A request that writes more than this share of the previous context re-wrote it. */
|
|
46
|
+
const MISS_SHARE = 0.6;
|
|
47
|
+
/** Anthropic's cache looks back at most this many blocks from a breakpoint for an earlier hit. */
|
|
48
|
+
const LOOKBACK_BLOCKS = 20;
|
|
49
|
+
const SIZE_BUCKETS = [["<100k", 100_000], ["100-300k", 300_000], ["300-600k", 600_000], ["600k+", Infinity]];
|
|
50
|
+
const bucketOf = (tokens) => SIZE_BUCKETS.find(([, max]) => tokens < max)[0];
|
|
51
|
+
const num = (x) => (typeof x === "number" && Number.isFinite(x) && x > 0 ? x : 0);
|
|
52
|
+
/** Misses in one transcript; `since` drops requests before it. */
|
|
53
|
+
export function missesInTranscript(path, since = 0, add = () => { }, onRequest = () => { }) {
|
|
54
|
+
let prev;
|
|
55
|
+
let lastId;
|
|
56
|
+
let compacted = false;
|
|
57
|
+
let apiError = false;
|
|
58
|
+
let blocks = 0;
|
|
59
|
+
let edited = false;
|
|
60
|
+
forEachLine(path, (line) => {
|
|
61
|
+
// Cheap row counting without a parse: Claude Code writes one row per
|
|
62
|
+
// content block, so main-chain rows since the last request are the blocks
|
|
63
|
+
// it added (what the 20-block lookback counts).
|
|
64
|
+
const usage = line.includes('"usage"');
|
|
65
|
+
if (!usage && !line.includes("compact_boundary") && !line.includes("api_error")) {
|
|
66
|
+
if ((line.includes('"type":"user"') || line.includes('"type":"assistant"')) && !line.includes('"isSidechain":true'))
|
|
67
|
+
blocks++;
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
let e;
|
|
71
|
+
try {
|
|
72
|
+
e = JSON.parse(line);
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
if (!e || typeof e !== "object" || e.isSidechain)
|
|
78
|
+
return;
|
|
79
|
+
if (e.type === "system" && e.subtype === "compact_boundary") {
|
|
80
|
+
compacted = true;
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
if (e.type === "system" && e.subtype === "api_error") {
|
|
84
|
+
apiError = true;
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
if (e.type === "user" || e.type === "assistant")
|
|
88
|
+
blocks++;
|
|
89
|
+
const msg = e.message;
|
|
90
|
+
if (e.type !== "assistant" || !msg?.usage)
|
|
91
|
+
return;
|
|
92
|
+
// One reply is written as several rows sharing its id and usage: count it once.
|
|
93
|
+
if (typeof msg.id === "string" && msg.id === lastId)
|
|
94
|
+
return;
|
|
95
|
+
lastId = typeof msg.id === "string" ? msg.id : undefined;
|
|
96
|
+
const model = realModel(msg.model);
|
|
97
|
+
if (!model)
|
|
98
|
+
return;
|
|
99
|
+
const at = Date.parse(String(e.timestamp ?? ""));
|
|
100
|
+
if (!Number.isFinite(at))
|
|
101
|
+
return;
|
|
102
|
+
const u = msg.usage;
|
|
103
|
+
const write = num(u.cache_creation_input_tokens);
|
|
104
|
+
const read = num(u.cache_read_input_tokens);
|
|
105
|
+
const total = write + read + num(u.input_tokens);
|
|
106
|
+
const oneHour = num(u.cache_creation?.ephemeral_1h_input_tokens) > 0;
|
|
107
|
+
const ttl = oneHour ? HOUR : FIVE_MIN;
|
|
108
|
+
const cm = u.context_management ?? msg.context_management;
|
|
109
|
+
const cmText = cm ? JSON.stringify(cm) : "";
|
|
110
|
+
if (cmText.includes("applied") && !/"applied_edits"\s*:\s*\[\s*\]/.test(cmText))
|
|
111
|
+
edited = true;
|
|
112
|
+
if (at >= since) {
|
|
113
|
+
const price = pricingFor(model);
|
|
114
|
+
if (price)
|
|
115
|
+
onRequest((write * price.inputPerM * (oneHour ? CACHE_WRITE_1H : CACHE_WRITE_5M)) / 1e6);
|
|
116
|
+
if (prev && !compacted && at - prev.at < Math.min(ttl, prev.ttl) && prev.total > MIN_CONTEXT) {
|
|
117
|
+
const isMiss = write > MISS_SHARE * prev.total;
|
|
118
|
+
let miss;
|
|
119
|
+
if (isMiss) {
|
|
120
|
+
const cause = prev.model !== model ? "model switch"
|
|
121
|
+
: edited ? "context edited"
|
|
122
|
+
: apiError ? "after an API error"
|
|
123
|
+
: blocks > LOOKBACK_BLOCKS ? "over 20 new blocks"
|
|
124
|
+
: "nothing visible";
|
|
125
|
+
miss = {
|
|
126
|
+
path,
|
|
127
|
+
at: new Date(at).toISOString(),
|
|
128
|
+
model,
|
|
129
|
+
previousModel: prev.model,
|
|
130
|
+
contextTokens: prev.total,
|
|
131
|
+
writeTokens: write,
|
|
132
|
+
readShare: prev.total > 0 ? read / prev.total : 0,
|
|
133
|
+
gapSeconds: Math.round((at - prev.at) / 1000),
|
|
134
|
+
cause,
|
|
135
|
+
extraUsd: price ? (Math.min(write, prev.total) * (price.inputPerM * (oneHour ? CACHE_WRITE_1H : CACHE_WRITE_5M) - price.cacheReadPerM)) / 1e6 : undefined,
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
add({ model, contextTokens: prev.total }, miss);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
prev = { at, total, model, ttl };
|
|
142
|
+
compacted = false;
|
|
143
|
+
apiError = false;
|
|
144
|
+
edited = false;
|
|
145
|
+
blocks = 0;
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
/** Two rates differ beyond chance (two-proportion z-test, 99%). */
|
|
149
|
+
function differs(a, b) {
|
|
150
|
+
const p = (a.misses + b.misses) / (a.eligible + b.eligible);
|
|
151
|
+
if (p <= 0 || p >= 1)
|
|
152
|
+
return false;
|
|
153
|
+
const se = Math.sqrt(p * (1 - p) * (1 / a.eligible + 1 / b.eligible));
|
|
154
|
+
return Math.abs(a.rate - b.rate) > 2.58 * se;
|
|
155
|
+
}
|
|
156
|
+
/** Enough requests for a model's rate to mean something. */
|
|
157
|
+
const MIN_ELIGIBLE = 100;
|
|
158
|
+
const pct = (x) => `${(x * 100).toFixed(x < 0.01 ? 2 : 1)}%`;
|
|
159
|
+
/** "claude-opus-5-5" → "opus": versions of one family are compared with each other. */
|
|
160
|
+
function family(model) {
|
|
161
|
+
return /(opus|sonnet|haiku|fable|mythos)/i.exec(model)?.[1]?.toLowerCase();
|
|
162
|
+
}
|
|
163
|
+
function recommend(byModel, bySize) {
|
|
164
|
+
const out = [];
|
|
165
|
+
const solid = byModel.filter((m) => m.eligible >= MIN_ELIGIBLE);
|
|
166
|
+
// Within a family: the version that misses least, where another misses
|
|
167
|
+
// significantly more. Same capabilities class, so a fair swap to suggest.
|
|
168
|
+
const families = new Map();
|
|
169
|
+
for (const m of solid) {
|
|
170
|
+
const f = family(m.model);
|
|
171
|
+
if (f)
|
|
172
|
+
families.set(f, [...(families.get(f) ?? []), m]);
|
|
173
|
+
}
|
|
174
|
+
for (const [f, models] of families) {
|
|
175
|
+
if (models.length < 2)
|
|
176
|
+
continue;
|
|
177
|
+
const best = [...models].sort((a, b) => a.rate - b.rate)[0];
|
|
178
|
+
const worse = models.filter((m) => m !== best && m.misses >= 5 && m.rate > best.rate * 2 && differs(m, best));
|
|
179
|
+
if (worse.length === 0)
|
|
180
|
+
continue;
|
|
181
|
+
const name = f[0].toUpperCase() + f.slice(1);
|
|
182
|
+
out.push(`${name}: ${best.model} missed on ${pct(best.rate)} of warm requests; ` +
|
|
183
|
+
worse.map((m) => `${m.model} on ${pct(m.rate)} (${m.misses} misses, ${money(m.extraUsd)})`).join(", ") +
|
|
184
|
+
`. Prefer ${best.model} where you choose the ${name} version.`);
|
|
185
|
+
}
|
|
186
|
+
// Across your models: the outlier, when it is one beyond chance.
|
|
187
|
+
if (solid.length >= 2) {
|
|
188
|
+
const sorted = [...solid].sort((a, b) => b.rate - a.rate);
|
|
189
|
+
const worst = sorted[0];
|
|
190
|
+
const rest = sorted.slice(1);
|
|
191
|
+
const pooled = rest.reduce((s, m) => ({ eligible: s.eligible + m.eligible, misses: s.misses + m.misses }), { eligible: 0, misses: 0 });
|
|
192
|
+
const others = { ...pooled, rate: pooled.eligible ? pooled.misses / pooled.eligible : 0, extraUsd: 0 };
|
|
193
|
+
if (worst.misses >= 10 && worst.rate > others.rate * 3 && differs(worst, others) && !out.some((l) => l.includes(`${worst.model} on`))) {
|
|
194
|
+
out.push(`${worst.model} misses most: ${pct(worst.rate)} of its warm requests (${worst.misses} of ${worst.eligible}, ${money(worst.extraUsd)}), ` +
|
|
195
|
+
`against ${pct(others.rate)} on your other models. Where another model would do, it re-writes the cache less.`);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
// Context size: misses grow with the context, and each costs more there.
|
|
199
|
+
const small = bySize.filter((b) => b.bucket === "<100k" || b.bucket === "100-300k");
|
|
200
|
+
const large = bySize.filter((b) => b.bucket === "300-600k" || b.bucket === "600k+");
|
|
201
|
+
const sum = (bs) => {
|
|
202
|
+
const eligible = bs.reduce((n, b) => n + b.eligible, 0);
|
|
203
|
+
const misses = bs.reduce((n, b) => n + b.misses, 0);
|
|
204
|
+
return { eligible, misses, rate: eligible ? misses / eligible : 0, extraUsd: bs.reduce((n, b) => n + b.extraUsd, 0) };
|
|
205
|
+
};
|
|
206
|
+
const s = sum(small), l = sum(large);
|
|
207
|
+
if (s.eligible >= MIN_ELIGIBLE && l.eligible >= MIN_ELIGIBLE && l.misses >= 10 && l.rate > s.rate * 1.5 && differs(l, s)) {
|
|
208
|
+
out.push(`Above 300k tokens of context the cache missed ${(l.rate / Math.max(s.rate, 1e-9)).toFixed(1)}x as often (${pct(l.rate)} vs ${pct(s.rate)}), ` +
|
|
209
|
+
`and each miss there re-writes more: compacting earlier cuts both (context-doctor compact-window).`);
|
|
210
|
+
}
|
|
211
|
+
return out;
|
|
212
|
+
}
|
|
213
|
+
export function cacheMisses(days = 30, paths, onProgress) {
|
|
214
|
+
const since = Date.now() - days * 86_400_000;
|
|
215
|
+
// Claude Code transcripts: they record the API's cache usage per request.
|
|
216
|
+
const targets = paths ?? listSessions(10_000).filter((s) => s.path.includes(".claude") && s.modifiedAt.getTime() >= since).map((s) => s.path);
|
|
217
|
+
const models = new Map();
|
|
218
|
+
const sizes = new Map();
|
|
219
|
+
const causes = { "model switch": 0, "context edited": 0, "after an API error": 0, "over 20 new blocks": 0, "nothing visible": 0 };
|
|
220
|
+
const all = [];
|
|
221
|
+
let requests = 0, eligible = 0, cacheWriteUsd = 0;
|
|
222
|
+
const bump = (map, key, miss) => {
|
|
223
|
+
const s = map.get(key) ?? { eligible: 0, misses: 0, rate: 0, extraUsd: 0 };
|
|
224
|
+
s.eligible++;
|
|
225
|
+
if (miss) {
|
|
226
|
+
s.misses++;
|
|
227
|
+
s.extraUsd += miss.extraUsd ?? 0;
|
|
228
|
+
}
|
|
229
|
+
map.set(key, s);
|
|
230
|
+
};
|
|
231
|
+
for (const [i, p] of targets.entries()) {
|
|
232
|
+
onProgress?.(i, targets.length);
|
|
233
|
+
try {
|
|
234
|
+
missesInTranscript(p, since, (e, miss) => {
|
|
235
|
+
eligible++;
|
|
236
|
+
bump(models, e.model, miss);
|
|
237
|
+
bump(sizes, bucketOf(e.contextTokens), miss);
|
|
238
|
+
if (miss) {
|
|
239
|
+
all.push(miss);
|
|
240
|
+
causes[miss.cause]++;
|
|
241
|
+
}
|
|
242
|
+
}, (writeUsd) => {
|
|
243
|
+
requests++;
|
|
244
|
+
cacheWriteUsd += writeUsd;
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
catch {
|
|
248
|
+
/* one unreadable transcript must not sink the report */
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
onProgress?.(targets.length, targets.length);
|
|
252
|
+
const finish = (s) => ({ ...s, rate: s.eligible ? s.misses / s.eligible : 0 });
|
|
253
|
+
const byModel = [...models.entries()].map(([model, s]) => ({ model, ...finish(s) })).sort((a, b) => b.rate - a.rate);
|
|
254
|
+
const bySize = SIZE_BUCKETS.filter(([b]) => sizes.has(b)).map(([bucket]) => ({ bucket, ...finish(sizes.get(bucket)) }));
|
|
255
|
+
return {
|
|
256
|
+
days,
|
|
257
|
+
transcripts: targets.length,
|
|
258
|
+
requests,
|
|
259
|
+
eligible,
|
|
260
|
+
misses: all.length,
|
|
261
|
+
missWriteTokens: all.reduce((n, m) => n + m.writeTokens, 0),
|
|
262
|
+
extraUsd: all.reduce((n, m) => n + (m.extraUsd ?? 0), 0),
|
|
263
|
+
cacheWriteUsd,
|
|
264
|
+
unpricedMisses: all.filter((m) => m.extraUsd === undefined).length,
|
|
265
|
+
byModel,
|
|
266
|
+
bySize,
|
|
267
|
+
causes,
|
|
268
|
+
recommendations: recommend(byModel, bySize),
|
|
269
|
+
largest: [...all].sort((a, b) => (b.extraUsd ?? 0) - (a.extraUsd ?? 0) || b.writeTokens - a.writeTokens).slice(0, 10),
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
/** Worth a line in `savings`: enough misses, and enough money, to act on. */
|
|
273
|
+
export function cacheMissesSignificant(r) {
|
|
274
|
+
return r.misses >= 10 && r.extraUsd >= 5;
|
|
275
|
+
}
|
|
276
|
+
/** The one line `savings` adds when the misses are significant. */
|
|
277
|
+
export function cacheMissesLine(r) {
|
|
278
|
+
const share = r.cacheWriteUsd > 0 ? ` (${Math.round((r.extraUsd / r.cacheWriteUsd) * 100)}% of cache writes)` : "";
|
|
279
|
+
// Within the 60 columns the rest of `savings` keeps to.
|
|
280
|
+
return [
|
|
281
|
+
`Also: ${r.misses} cache misses within the cache lifetime cost ${money(r.extraUsd)}`,
|
|
282
|
+
`above cache-read price${share}. By model and`,
|
|
283
|
+
"context size: context-doctor cache-misses",
|
|
284
|
+
];
|
|
285
|
+
}
|
|
286
|
+
export function renderCacheMisses(r) {
|
|
287
|
+
const out = ["CACHE MISSES WITHIN THE CACHE LIFETIME", "═".repeat(60)];
|
|
288
|
+
if (r.eligible === 0) {
|
|
289
|
+
out.push(`No Claude Code requests in the last ${r.days} days that could have read a warm cache (consecutive, within the cache lifetime, over 20k tokens).`);
|
|
290
|
+
return out.join("\n");
|
|
291
|
+
}
|
|
292
|
+
const share = r.cacheWriteUsd > 0 ? ` (${Math.round((r.extraUsd / r.cacheWriteUsd) * 100)}% of your ${money(r.cacheWriteUsd)} of cache writes)` : "";
|
|
293
|
+
out.push(`Last ${r.days} days, ${r.transcripts} transcripts, ${r.requests.toLocaleString("en-US")} requests.`, `${r.misses} of ${r.eligible.toLocaleString("en-US")} warm requests (${pct(r.misses / r.eligible)}) re-wrote the cache instead of reading it:`, `~${formatTokens(r.missWriteTokens)} tokens written again, ${money(r.extraUsd)} above cache-read price${share}.` +
|
|
294
|
+
(r.unpricedMisses ? ` ${r.unpricedMisses} on unpriced models not included.` : ""), "", ` ${"model".padEnd(24)} ${"misses".padStart(14)} ${"rate".padStart(7)} ${"cost".padStart(9)}`);
|
|
295
|
+
for (const m of r.byModel) {
|
|
296
|
+
out.push(` ${m.model.slice(0, 24).padEnd(24)} ${`${m.misses}/${m.eligible}`.padStart(14)} ${pct(m.rate).padStart(7)} ${money(m.extraUsd).padStart(9)}`);
|
|
297
|
+
}
|
|
298
|
+
out.push("", ` ${"context before".padEnd(24)} ${"misses".padStart(14)} ${"rate".padStart(7)} ${"cost".padStart(9)}`);
|
|
299
|
+
for (const b of r.bySize) {
|
|
300
|
+
out.push(` ${b.bucket.padEnd(24)} ${`${b.misses}/${b.eligible}`.padStart(14)} ${pct(b.rate).padStart(7)} ${money(b.extraUsd).padStart(9)}`);
|
|
301
|
+
}
|
|
302
|
+
const causes = Object.entries(r.causes).filter(([, n]) => n > 0).sort((a, b) => b[1] - a[1]);
|
|
303
|
+
if (causes.length) {
|
|
304
|
+
out.push("", "Cause, where the transcript shows one:");
|
|
305
|
+
for (const [c, n] of causes)
|
|
306
|
+
out.push(` ${String(n).padStart(5)} ${c}`);
|
|
307
|
+
if (r.causes["nothing visible"] > 0) {
|
|
308
|
+
out.push(" \"Nothing visible\": no model switch, compaction, context edit, API error or", " long tool run before it. The system prompt, tools or memory changing, or the", " provider evicting the cache early, would look like this from the client.");
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
if (r.recommendations.length) {
|
|
312
|
+
out.push("", "What the data supports:");
|
|
313
|
+
for (const rec of r.recommendations)
|
|
314
|
+
out.push(` • ${rec}`);
|
|
315
|
+
}
|
|
316
|
+
if (r.largest.length) {
|
|
317
|
+
out.push("", "Costliest:");
|
|
318
|
+
for (const m of r.largest.slice(0, 5)) {
|
|
319
|
+
const file = m.path.split(/[\\/]/).pop()?.slice(0, 12) ?? "";
|
|
320
|
+
out.push(` ${m.at.slice(0, 16).replace("T", " ")} ${m.model.slice(0, 18).padEnd(18)} ~${formatTokens(m.contextTokens).padStart(5)} ctx, ${m.gapSeconds}s gap, ${m.cause}${m.extraUsd !== undefined ? `, ${money(m.extraUsd)}` : ""} ${file}`);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
out.push("", "A miss: within the cache lifetime of both requests (5 min, or 1 h when written at", "the 1-hour TTL), no compaction between, previous context over 20k, and the request", "wrote over 60% of that context again. Model switches always miss: each model has", "its own cache. On Claude Code 2.1.251+, `context-doctor install` (or the plugin)", "shows that price before a /model switch.");
|
|
324
|
+
return out.join("\n");
|
|
325
|
+
}
|
package/dist/cacheplan.d.ts
CHANGED
|
@@ -6,27 +6,41 @@
|
|
|
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;
|
|
27
41
|
}
|
|
28
42
|
export interface CachePlan {
|
|
29
|
-
provider: "anthropic" | "openai" | "unknown";
|
|
43
|
+
provider: "anthropic" | "openai" | "gemini" | "unknown";
|
|
30
44
|
model?: string;
|
|
31
45
|
totalTokens: number;
|
|
32
46
|
minCacheable: number;
|
|
@@ -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
|
};
|