context-doctor 0.42.0 → 0.44.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +6 -3
  2. package/dist/budget.d.ts +52 -0
  3. package/dist/budget.js +209 -59
  4. package/dist/cachettl.d.ts +5 -1
  5. package/dist/cachettl.js +10 -25
  6. package/dist/cli.js +33 -15
  7. package/dist/codexcompact.d.ts +137 -0
  8. package/dist/codexcompact.js +581 -0
  9. package/dist/compactwindow.js +2 -2
  10. package/dist/cursor.d.ts +10 -0
  11. package/dist/cursor.js +20 -0
  12. package/dist/doctor.d.ts +9 -0
  13. package/dist/doctor.js +55 -0
  14. package/dist/fanout.js +4 -2
  15. package/dist/fix.d.ts +38 -4
  16. package/dist/fix.js +249 -21
  17. package/dist/hook.js +65 -16
  18. package/dist/install.js +56 -19
  19. package/dist/ledger.d.ts +2 -1
  20. package/dist/ledger.js +1 -0
  21. package/dist/limits.d.ts +6 -2
  22. package/dist/limits.js +19 -16
  23. package/dist/mcp.js +63 -63
  24. package/dist/mcpclient.js +19 -19
  25. package/dist/mcpschema.js +5 -9
  26. package/dist/overhead.d.ts +7 -2
  27. package/dist/overhead.js +11 -3
  28. package/dist/pack.js +23 -3
  29. package/dist/pricing.d.ts +25 -5
  30. package/dist/pricing.js +157 -48
  31. package/dist/proxy.d.ts +15 -1
  32. package/dist/proxy.js +33 -5
  33. package/dist/prune.d.ts +8 -0
  34. package/dist/prune.js +20 -9
  35. package/dist/savings.js +2 -1
  36. package/dist/sessionprice.d.ts +77 -0
  37. package/dist/sessionprice.js +267 -0
  38. package/dist/settingsedit.js +3 -2
  39. package/dist/spend.d.ts +25 -3
  40. package/dist/spend.js +67 -19
  41. package/dist/subagentmodel.js +11 -1
  42. package/dist/subagentpay.d.ts +17 -0
  43. package/dist/subagentpay.js +41 -2
  44. package/dist/subagents.d.ts +24 -0
  45. package/dist/subagents.js +82 -17
  46. package/dist/tooloutput.d.ts +120 -0
  47. package/dist/tooloutput.js +357 -0
  48. package/package.json +1 -1
@@ -0,0 +1,357 @@
1
+ /**
2
+ * Long tool output: what it costs to keep in the context, and what a lower
3
+ * cap would save. The `tool-output` lever of `fix`.
4
+ *
5
+ * A tool result stays in the conversation, and every later request re-reads
6
+ * it (at the cache-read rate, or the write rate when the cache went cold)
7
+ * until a compaction. Claude Code caps it when it arrives. Read from the
8
+ * 2.1.309 binary and its docs (code.claude.com/docs/en/tools-reference,
9
+ * settings-reference, mcp, env-vars):
10
+ * - a successful Bash or PowerShell result over `bashOutputMaxChars`
11
+ * (settings, any scope; default 30,000 characters, clamped to
12
+ * 4,000-128,000; Claude Code 2.1.261+) is saved to a file, and the model
13
+ * receives the path and a preview of the first 2,000 characters
14
+ * (`<persisted-output>`). Set, it also replaces BASH_MAX_OUTPUT_LENGTH,
15
+ * which on its own sizes only the read-back window, not what the model
16
+ * receives. A failed command gets a head-and-tail excerpt of ~10,000
17
+ * characters instead, with no file, whatever the setting;
18
+ * - an MCP text result over MAX_MCP_OUTPUT_TOKENS (environment; default
19
+ * 25,000 tokens) is saved to a file and replaced by a message naming the
20
+ * path, with no preview; one over 50,000 characters is saved to a file
21
+ * whatever the variable says (with the same 2,000-character preview as
22
+ * Bash), unless the tool raises its own limit.
23
+ * Anthropic can also set a tool's threshold server-side (a remote flag the
24
+ * binary reads per tool name); that is not visible here.
25
+ *
26
+ * The replay reads each transcript's requests and its Bash and MCP results
27
+ * in order. For a candidate cap, a successful text result longer than the
28
+ * cap would have been the preview instead: the tokens past it are priced at
29
+ * the first request after the result (the cache write, at the session's own
30
+ * write price) and at every later request until a compaction (a cache read,
31
+ * or a write when that request found the cache cold: over 60% of its context
32
+ * written again). Token counts are estimates from the text's length, at the
33
+ * ratio measured on the growth of the billed prompt between consecutive
34
+ * calls (tokens.ts). Not counted: the model opening the file afterwards, or
35
+ * running the command again. Each such request costs about the context it
36
+ * re-reads, so the replay prices one per moved result and reports how many
37
+ * of them the saving still covers.
38
+ */
39
+ import { listSessions, isClaudeSession, replyCounter } from "./session.js";
40
+ import { pick, rowsOf, slimUsage } from "./scan.js";
41
+ import { cacheWriteSplit, pricingFor, usageCost, writeMultiplier } from "./pricing.js";
42
+ import { isCodeLike, realModel, tokensForLength } from "./tokens.js";
43
+ import { subagentTranscripts } from "./cachettl.js";
44
+ /** The settings key the lever writes. */
45
+ export const BASH_OUTPUT_KEY = "bashOutputMaxChars";
46
+ /** The environment variable the setting replaces (a value the user set there is theirs). */
47
+ export const BASH_OUTPUT_ENV = "BASH_MAX_OUTPUT_LENGTH";
48
+ /** The first Claude Code that reads the setting (its docs; older versions ignore it). */
49
+ export const BASH_OUTPUT_SINCE = "2.1.261";
50
+ /** Claude Code's inline ceiling for a successful command, unset. */
51
+ export const BASH_OUTPUT_DEFAULT = 30_000;
52
+ /** What Claude Code clamps the setting to. */
53
+ export const BASH_OUTPUT_MIN = 4_000;
54
+ export const BASH_OUTPUT_MAX = 128_000;
55
+ /** The caps the replay tries, smallest first; under 8,000 the 2,000-character preview is most of the output. */
56
+ export const BASH_OUTPUT_CAPS = [8_000, 12_000, 16_000, 20_000];
57
+ /** What the model receives instead: a 2,000-character preview, the path and the wrapper around them. */
58
+ const PREVIEW_CHARS = 2_250;
59
+ /** The MCP cap the replay tries, in tokens: the size at which Claude Code already warns. */
60
+ export const MCP_OUTPUT_CAP = 10_000;
61
+ /** What the model receives instead of a long MCP result: a message naming the file (no preview). */
62
+ const MCP_NOTICE_CHARS = 700;
63
+ /** A request that wrote over this share of its context found the cache cold. */
64
+ const COLD_SHARE = 0.6;
65
+ /** A context that fell this far with no compaction was cut (a rewind, cleared tool output): what it held is gone. */
66
+ const CUT_SHARE = 0.7;
67
+ /** "Output too large (43.1KB)": the size Claude Code gives a result it saved, in characters (about). */
68
+ function persistedSize(text) {
69
+ const m = /^<persisted-output>\s*Output (?:too large|exceeded the) \(?([\d.]+)\s*(bytes|KB|MB|GB)/.exec(text);
70
+ if (!m)
71
+ return undefined;
72
+ const n = Number(m[1]) * { bytes: 1, KB: 1024, MB: 1024 ** 2, GB: 1024 ** 3 }[m[2]];
73
+ return Number.isFinite(n) && n > 0 ? Math.round(n) : undefined;
74
+ }
75
+ /** The text a result's content holds; undefined when it carries an image or a document (never moved to a file). */
76
+ function resultText(content) {
77
+ if (typeof content === "string")
78
+ return content;
79
+ if (!Array.isArray(content))
80
+ return undefined;
81
+ let s = "";
82
+ for (const b of content) {
83
+ if (!b || typeof b !== "object")
84
+ continue;
85
+ if (b.type === "image" || b.type === "document")
86
+ return undefined;
87
+ if (b.type === "text" && typeof b.text === "string")
88
+ s += b.text;
89
+ }
90
+ return s;
91
+ }
92
+ export const TOOL_OUTPUT_ROWS = {
93
+ id: "tool-output.1",
94
+ init: () => ({ ids: {}, calls: {} }),
95
+ line(raw, row, out, st) {
96
+ if (!raw.includes('"usage"') && !raw.includes('"tool_use"') && !raw.includes('"tool_result"') && !raw.includes("compact_boundary"))
97
+ return;
98
+ let e;
99
+ try {
100
+ e = row();
101
+ }
102
+ catch {
103
+ return;
104
+ }
105
+ if (!e || typeof e !== "object")
106
+ return;
107
+ const th = e.isSidechain ? 1 : 0;
108
+ if (e.type === "system") {
109
+ if (e.subtype === "compact_boundary")
110
+ out.push({ t: "c", th });
111
+ return;
112
+ }
113
+ const m = e.message;
114
+ if (!m || typeof m !== "object" || !Array.isArray(m.content) && !m.usage)
115
+ return;
116
+ if (e.type === "assistant") {
117
+ // A reply is written one content block a row, each with its usage: one request, at its first row.
118
+ if (m.usage && typeof m.id === "string" && !((st.ids[m.id] ?? 0) & (th + 1))) {
119
+ st.ids[m.id] = (st.ids[m.id] ?? 0) | (th + 1);
120
+ out.push({ t: "r", th, ...pick(e, ["timestamp", "uuid"]), id: m.id, model: m.model, u: slimUsage(m.usage) });
121
+ }
122
+ else if (m.usage && typeof m.id !== "string") {
123
+ out.push({ t: "r", th, ...pick(e, ["timestamp", "uuid"]), model: m.model, u: slimUsage(m.usage) });
124
+ }
125
+ if (Array.isArray(m.content)) {
126
+ for (const b of m.content) {
127
+ if (b?.type !== "tool_use" || typeof b.id !== "string" || typeof b.name !== "string")
128
+ continue;
129
+ if (b.name === "Bash" || b.name === "PowerShell")
130
+ st.calls[b.id] = "b";
131
+ else if (b.name.startsWith("mcp__"))
132
+ st.calls[b.id] = "m";
133
+ }
134
+ }
135
+ return;
136
+ }
137
+ if (e.type !== "user" || !Array.isArray(m.content))
138
+ return;
139
+ for (const b of m.content) {
140
+ if (b?.type !== "tool_result" || typeof b.tool_use_id !== "string")
141
+ continue;
142
+ const kind = st.calls[b.tool_use_id];
143
+ if (!kind)
144
+ continue;
145
+ delete st.calls[b.tool_use_id];
146
+ // A failed command gets an excerpt of its own, whatever the cap.
147
+ if (b.is_error)
148
+ continue;
149
+ const text = resultText(b.content);
150
+ if (text === undefined)
151
+ continue;
152
+ const c = isCodeLike(text.slice(0, 20_000)) ? 1 : 0;
153
+ if (kind === "m") {
154
+ out.push({ t: "m", th, n: text.length, c });
155
+ continue;
156
+ }
157
+ const p = text.startsWith("<persisted-output>") ? persistedSize(text) : undefined;
158
+ out.push({ t: "b", th, n: text.length, c, ...(p !== undefined ? { p } : {}) });
159
+ }
160
+ },
161
+ };
162
+ /** One transcript as the replay walks it, per thread, fork copies marked once for every cap. */
163
+ function timeline(path, since, until, runRows) {
164
+ const threads = [[], []];
165
+ const rows = rowsOf(path, TOOL_OUTPUT_ROWS);
166
+ // The session's own write price, for writes the replay charges: mostly 1 hour on the main thread, 5 minutes in subagents.
167
+ let w5 = 0, w1 = 0;
168
+ for (const r of rows)
169
+ if (r?.t === "r") {
170
+ const s = cacheWriteSplit(r.u);
171
+ w5 += s.fiveMinute;
172
+ w1 += s.oneHour;
173
+ }
174
+ const writeMult = writeMultiplier(w5, w1);
175
+ const sighting = replyCounter(runRows);
176
+ const model = [undefined, undefined];
177
+ // Results met before the thread's first priced reply take that reply's model (its tokenizer).
178
+ const unsized = [[], []];
179
+ for (const r of rows) {
180
+ if (!r || typeof r !== "object")
181
+ continue;
182
+ const th = r.th === 1 ? 1 : 0;
183
+ const out = threads[th];
184
+ if (r.t === "c") {
185
+ out.push({ k: "c" });
186
+ continue;
187
+ }
188
+ if (r.t === "b" || r.t === "m") {
189
+ const res = { k: r.t, n: r.n, c: r.c, ...(r.t === "b" && r.p !== undefined ? { p: r.p } : {}), model: model[th] };
190
+ if (!res.model)
191
+ unsized[th].push(res);
192
+ out.push(res);
193
+ continue;
194
+ }
195
+ if (r.t !== "r")
196
+ continue;
197
+ const seen = sighting({ message: { id: r.id }, uuid: r.uuid });
198
+ if (seen === "repeat")
199
+ continue;
200
+ const u = (r.u ?? {});
201
+ const num = (v) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0);
202
+ const prompt = num(u.input_tokens) + num(u.cache_read_input_tokens) + num(u.cache_creation_input_tokens);
203
+ const at = Date.parse(String(r.timestamp ?? ""));
204
+ if (!(prompt > 0) || !Number.isFinite(at))
205
+ continue;
206
+ const m = realModel(r.model);
207
+ if (m) {
208
+ model[th] = m;
209
+ for (const x of unsized[th].splice(0))
210
+ x.model = m;
211
+ }
212
+ const price = pricingFor(m);
213
+ out.push({
214
+ k: "r", prompt,
215
+ readPerM: price?.cacheReadPerM ?? 0,
216
+ writePerM: (price?.inputPerM ?? 0) * writeMult,
217
+ cold: num(u.cache_creation_input_tokens) > COLD_SHARE * prompt,
218
+ counted: !!price && seen === "new" && at >= since && at < until,
219
+ billedUsd: price ? usageCost(u, price).promptUsd : 0,
220
+ });
221
+ }
222
+ return threads;
223
+ }
224
+ /** A candidate cap for Bash: a successful result longer than it, still inline, becomes the preview. */
225
+ export const bashCap = (cap) => (r) => (r.k === "b" && r.p === undefined && r.n > cap ? tokensForLength(r.n, !!r.c, r.model) - tokensForLength(PREVIEW_CHARS, !!r.c, r.model) : 0);
226
+ /** Since a cap was set: the results Claude Code moved that the cap before would have left inline. */
227
+ export const bashMovedSince = (previous) => (r) => (r.k === "b" && r.p !== undefined && r.p <= previous ? tokensForLength(r.p, !!r.c, r.model) - tokensForLength(Math.min(r.n, PREVIEW_CHARS), !!r.c, r.model) : 0);
228
+ /** MAX_MCP_OUTPUT_TOKENS at `tokens`: a longer text result becomes a message naming the file. */
229
+ export const mcpCap = (tokens) => (r) => {
230
+ if (r.k !== "m")
231
+ return 0;
232
+ const t = tokensForLength(r.n, !!r.c, r.model);
233
+ return t > tokens ? t - tokensForLength(MCP_NOTICE_CHARS, false, r.model) : 0;
234
+ };
235
+ /** Walk the timelines once for one cap. */
236
+ function walk(lines, move, kind) {
237
+ let moved = 0, results = 0, tokens = 0, savedUsd = 0, openUsd = 0;
238
+ for (const steps of lines) {
239
+ // The moved results still in the context, and whether a request has re-read each yet.
240
+ let live = [];
241
+ let prev;
242
+ // Results since the last request that a cap applies to (still inline as recorded): counted with the request that first reads them.
243
+ let arrived = 0;
244
+ for (const s of steps) {
245
+ if (s.k === "c") {
246
+ live = [];
247
+ prev = undefined;
248
+ continue;
249
+ }
250
+ if (s.k !== "r") {
251
+ if (s.k !== kind)
252
+ continue;
253
+ if (s.p === undefined)
254
+ arrived++;
255
+ const e = move(s);
256
+ if (e > 0)
257
+ live.push({ e, fresh: true });
258
+ continue;
259
+ }
260
+ if (s.counted)
261
+ results += arrived;
262
+ arrived = 0;
263
+ if (prev !== undefined && s.prompt < CUT_SHARE * prev)
264
+ live = live.filter((x) => x.fresh);
265
+ prev = s.prompt;
266
+ // Never more than the request held.
267
+ const held = live.reduce((n, x) => n + x.e, 0);
268
+ const scale = held > s.prompt ? s.prompt / held : 1;
269
+ for (const x of live) {
270
+ if (x.fresh && s.counted) {
271
+ moved++;
272
+ openUsd += (s.prompt * s.readPerM) / 1e6;
273
+ }
274
+ if (s.counted) {
275
+ const t = x.e * scale;
276
+ tokens += t;
277
+ savedUsd += (t * (x.fresh || s.cold ? s.writePerM : s.readPerM)) / 1e6;
278
+ }
279
+ x.fresh = false;
280
+ }
281
+ }
282
+ }
283
+ return { moved, results, tokens, savedUsd, openUsd };
284
+ }
285
+ /** The share of moved results the model could open before the cap stops paying (each opening costs openUsd / moved and loses that result's saving). */
286
+ export function breakEven(r) {
287
+ return r.savedUsd + r.openUsd > 0 ? r.savedUsd / (r.savedUsd + r.openUsd) : 0;
288
+ }
289
+ /** Claude Code transcripts written since `since`, subagents included: every place a tool result is re-read. */
290
+ export function toolOutputTranscripts(since) {
291
+ const main = listSessions(10_000).filter((s) => isClaudeSession(s) && s.modifiedAt.getTime() >= since).map((s) => s.path);
292
+ return [...main, ...subagentTranscripts(since)];
293
+ }
294
+ /** Replay every Bash and MCP result in [since, until) at each candidate cap. */
295
+ export function replayToolOutput(opts) {
296
+ const until = opts.until ?? Infinity;
297
+ const paths = opts.paths ?? toolOutputTranscripts(opts.since);
298
+ const runRows = new Set();
299
+ const lines = [];
300
+ let requests = 0, billedUsd = 0, alreadyMoved = 0;
301
+ for (const p of paths) {
302
+ let t;
303
+ try {
304
+ t = timeline(p, opts.since, until, runRows);
305
+ }
306
+ catch {
307
+ continue;
308
+ }
309
+ for (const steps of t) {
310
+ if (!steps.length)
311
+ continue;
312
+ lines.push(steps);
313
+ for (const s of steps) {
314
+ if (s.k === "r" && s.counted) {
315
+ requests++;
316
+ billedUsd += s.billedUsd;
317
+ }
318
+ if (s.k === "b" && s.p !== undefined)
319
+ alreadyMoved++;
320
+ }
321
+ }
322
+ }
323
+ const bash = (opts.caps ?? BASH_OUTPUT_CAPS).map((cap) => ({ cap, ...walk(lines, bashCap(cap), "b") }));
324
+ const mcp = { cap: MCP_OUTPUT_CAP, ...walk(lines, mcpCap(MCP_OUTPUT_CAP), "m") };
325
+ const paying = bash.filter((b) => b.moved > 0 && breakEven(b) >= 0.5).sort((a, b) => b.savedUsd - a.savedUsd);
326
+ return { transcripts: paths.length, requests, billedUsd, alreadyMoved, bash, mcp, recommended: paying[0]?.cap };
327
+ }
328
+ /** What a cap set at `since` saved: the results it moved that the cap before (`previous`) left inline, re-read no more. */
329
+ export function toolOutputSavedSince(since, previous, paths) {
330
+ const runRows = new Set();
331
+ const lines = [];
332
+ for (const p of paths ?? toolOutputTranscripts(since)) {
333
+ try {
334
+ lines.push(...timeline(p, since, Infinity, runRows).filter((s) => s.length));
335
+ }
336
+ catch { /* unreadable */ }
337
+ }
338
+ return walk(lines, bashMovedSince(previous), "b");
339
+ }
340
+ const usd = (n) => (Math.abs(n) >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
341
+ const pct = (x) => `${Math.round(x * 100)}%`;
342
+ const k = (n) => `${Math.round(n / 1000)}k`;
343
+ /** The lines under the lever in `fix`: each cap tried, and MCP's. */
344
+ export function renderToolOutputCaps(r) {
345
+ const out = [`${"cap (characters)".padEnd(18)}${"moved".padStart(14)}${"saved".padStart(10)} pays unless the model opens`];
346
+ for (const b of r.bash) {
347
+ const mark = b.cap === r.recommended ? " ←" : "";
348
+ out.push(`${k(b.cap).padEnd(18)}${`${b.moved.toLocaleString("en-US")} of ${b.results.toLocaleString("en-US")}`.padStart(14)}${usd(b.savedUsd).padStart(10)} over ${pct(breakEven(b))} of them${mark}`);
349
+ }
350
+ const m = r.mcp;
351
+ if (m.results > 0) {
352
+ out.push(m.moved > 0
353
+ ? `MCP results over ${k(m.cap)} tokens: ${m.moved.toLocaleString("en-US")} of ${m.results.toLocaleString("en-US")}, ${usd(m.savedUsd)} re-reading them; not offered: over MAX_MCP_OUTPUT_TOKENS the model gets only the file's path, no preview.`
354
+ : `MCP results: none of ${m.results.toLocaleString("en-US")} over ${k(m.cap)} tokens.`);
355
+ }
356
+ return out;
357
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "context-doctor",
3
- "version": "0.42.0",
3
+ "version": "0.44.0",
4
4
  "description": "Context and token optimizer for LLM agents: see where Claude Code, Cursor, Codex and Gemini CLI tokens go, then cut them: an every-prompt hook, smarter compaction, an autopilot proxy that edits history only when the prompt cache is cold, RAG chunk packing and an MCP server. Local, no API key. By gAI Ventures.",
5
5
  "keywords": [
6
6
  "agent",