context-doctor 0.36.0 → 0.38.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 (62) hide show
  1. package/README.md +25 -15
  2. package/dist/autoclear.d.ts +11 -4
  3. package/dist/autoclear.js +52 -6
  4. package/dist/autopilot.d.ts +24 -0
  5. package/dist/autopilot.js +108 -0
  6. package/dist/cachemisses.d.ts +104 -2
  7. package/dist/cachemisses.js +199 -11
  8. package/dist/cli.js +172 -12
  9. package/dist/compact.d.ts +36 -0
  10. package/dist/compact.js +144 -0
  11. package/dist/compactwindow.d.ts +1 -1
  12. package/dist/compactwindow.js +6 -1
  13. package/dist/doctor.js +58 -1
  14. package/dist/extract.d.ts +23 -0
  15. package/dist/extract.js +121 -4
  16. package/dist/fanout.d.ts +131 -0
  17. package/dist/fanout.js +317 -0
  18. package/dist/fileparams.d.ts +61 -0
  19. package/dist/fileparams.js +308 -0
  20. package/dist/handoff.d.ts +143 -0
  21. package/dist/handoff.js +539 -0
  22. package/dist/hook.js +15 -0
  23. package/dist/httpguard.d.ts +56 -0
  24. package/dist/httpguard.js +141 -0
  25. package/dist/install.js +17 -5
  26. package/dist/ledger.d.ts +2 -0
  27. package/dist/ledger.js +44 -7
  28. package/dist/lens.d.ts +56 -0
  29. package/dist/lens.js +213 -0
  30. package/dist/limits.d.ts +229 -0
  31. package/dist/limits.js +869 -0
  32. package/dist/mcp.d.ts +3 -0
  33. package/dist/mcp.js +79 -56
  34. package/dist/mcpschema.d.ts +25 -1
  35. package/dist/mcpschema.js +78 -25
  36. package/dist/overhead.js +7 -6
  37. package/dist/pack.d.ts +20 -0
  38. package/dist/pack.js +29 -1
  39. package/dist/precompact.js +8 -7
  40. package/dist/preferences.d.ts +3 -1
  41. package/dist/preferences.js +8 -6
  42. package/dist/pricing.d.ts +29 -2
  43. package/dist/pricing.js +46 -8
  44. package/dist/proxy.d.ts +5 -3
  45. package/dist/proxy.js +12 -7
  46. package/dist/prune.d.ts +116 -0
  47. package/dist/prune.js +428 -0
  48. package/dist/recall.d.ts +104 -0
  49. package/dist/recall.js +393 -0
  50. package/dist/rules.d.ts +7 -4
  51. package/dist/rules.js +12 -8
  52. package/dist/savings.d.ts +1 -1
  53. package/dist/savings.js +11 -1
  54. package/dist/session.js +6 -13
  55. package/dist/sketch.d.ts +5 -1
  56. package/dist/sketch.js +23 -7
  57. package/dist/statusline.d.ts +6 -0
  58. package/dist/statusline.js +9 -0
  59. package/dist/subagentpay.d.ts +11 -0
  60. package/dist/subagentpay.js +1 -1
  61. package/package.json +1 -1
  62. package/skills/context-doctor/SKILL.md +3 -0
package/dist/fanout.js ADDED
@@ -0,0 +1,317 @@
1
+ /**
2
+ * The fan-out guard: a price on a subagent before it starts.
3
+ *
4
+ * Claude Code launches subagents with its Agent tool (named Task before
5
+ * 2.1.63; 2.1.308 still maps a "Task" matcher to it, 2.1.62 knows only
6
+ * "Task", so the matcher is "Agent|Task"). Each one has its own context and
7
+ * its own bill, and a fan-out of five is five bills, with nothing shown
8
+ * before they start. A PreToolUse hook on that tool runs first: it answers
9
+ * with a `systemMessage` the user sees, and once per session an
10
+ * `additionalContext` note the model reads, and never a permission decision,
11
+ * so the subagent always starts (verified in the hooks docs and both
12
+ * binaries: no decision means the normal permission flow; a hook that fails
13
+ * or times out does not block a PreToolUse call; only exit 2 would, and this
14
+ * never exits 2). PreToolUse is in 2.1.62's event list, so it needs none of
15
+ * PreModelSwitch's version guard.
16
+ *
17
+ * The price is the user's own: the median cost of the subagents of that
18
+ * type (and model) in their transcripts, the same reading `context-doctor
19
+ * subagents` does, cached for a day. Where the subagent would run on Opus or
20
+ * Fable, the note gives the Sonnet price too: the Agent tool takes
21
+ * `model: "sonnet"`.
22
+ */
23
+ import { appendFileSync, existsSync, readdirSync, readFileSync, statSync, writeFileSync, mkdirSync } from "node:fs";
24
+ import { createHash, randomUUID } from "node:crypto";
25
+ import { basename, dirname, join } from "node:path";
26
+ import { statePath } from "./ledger.js";
27
+ import { listSessions } from "./session.js";
28
+ import { scanSubagent } from "./subagentpay.js";
29
+ import { formatUsd, pricingFor } from "./pricing.js";
30
+ import { tailUsage } from "./statusline.js";
31
+ /** The subagent tool, by its current name and its pre-2.1.63 alias. */
32
+ export const FANOUT_MATCHER = "Agent|Task";
33
+ const DAY = 86_400_000;
34
+ /** Enough runs for a median to mean something. */
35
+ const MIN_RUNS = 3;
36
+ export function subagentCostsPath() {
37
+ return join(dirname(statePath()), ".context-doctor-subagent-costs.json");
38
+ }
39
+ function stat(costs) {
40
+ const s = costs.map((c) => c.usd).sort((a, b) => a - b);
41
+ const models = new Map();
42
+ for (const c of costs)
43
+ if (c.model)
44
+ models.set(c.model, (models.get(c.model) ?? 0) + 1);
45
+ return {
46
+ n: s.length,
47
+ median: s[Math.floor(s.length / 2)],
48
+ p90: s[Math.min(s.length - 1, Math.floor(s.length * 0.9))],
49
+ model: [...models.entries()].sort((a, b) => b[1] - a[1])[0]?.[0],
50
+ };
51
+ }
52
+ /**
53
+ * Each subagent's bill in the last `days`, newest transcripts first, by
54
+ * type and model. `limit` and `budgetMs` bound the work when the hook has
55
+ * to measure (the cache is a day old): the newest subagents are the best
56
+ * guide anyway.
57
+ */
58
+ export function measureSubagentCosts(days = 30, opts = {}) {
59
+ const now = opts.now ?? Date.now();
60
+ const since = now - days * DAY;
61
+ const started = Date.now();
62
+ const parents = opts.sessions ?? listSessions(10_000).filter((s) => s.path.includes(".claude") && s.modifiedAt.getTime() >= since).map((s) => s.path);
63
+ const files = [];
64
+ for (const parent of parents) {
65
+ const dir = join(parent.replace(/\.jsonl$/, ""), "subagents");
66
+ let names;
67
+ try {
68
+ names = readdirSync(dir);
69
+ }
70
+ catch {
71
+ continue;
72
+ }
73
+ for (const f of names) {
74
+ if (!/^agent-.+\.jsonl$/.test(f))
75
+ continue;
76
+ const file = join(dir, f);
77
+ try {
78
+ const at = statSync(file).mtimeMs;
79
+ if (at >= since)
80
+ files.push({ file, meta: join(dir, f.replace(/\.jsonl$/, ".meta.json")), at });
81
+ }
82
+ catch { /* gone */ }
83
+ }
84
+ }
85
+ files.sort((a, b) => b.at - a.at);
86
+ const runs = [];
87
+ for (const f of files.slice(0, opts.limit ?? Infinity)) {
88
+ if (opts.budgetMs !== undefined && Date.now() - started > opts.budgetMs)
89
+ break;
90
+ try {
91
+ const s = scanSubagent(f.file);
92
+ if (!(s.costUsd > 0))
93
+ continue;
94
+ let type = "unknown";
95
+ try {
96
+ type = String(JSON.parse(readFileSync(f.meta, "utf8"))?.agentType ?? "unknown").slice(0, 60);
97
+ }
98
+ catch { /* older Claude Code: no meta */ }
99
+ runs.push({ type, model: s.model, usd: s.costUsd });
100
+ }
101
+ catch { /* unreadable */ }
102
+ }
103
+ const group = (key) => {
104
+ const m = new Map();
105
+ for (const r of runs) {
106
+ const k = key(r);
107
+ if (k)
108
+ m.set(k, [...(m.get(k) ?? []), r]);
109
+ }
110
+ return Object.fromEntries([...m.entries()].map(([k, v]) => [k, stat(v)]));
111
+ };
112
+ return {
113
+ computedAt: now,
114
+ days,
115
+ n: runs.length,
116
+ all: runs.length ? stat(runs) : undefined,
117
+ byType: group((r) => r.type),
118
+ byTypeModel: group((r) => (r.model ? `${r.type}|${r.model}` : undefined)),
119
+ byModel: group((r) => r.model),
120
+ };
121
+ }
122
+ export function saveSubagentCosts(c, path = subagentCostsPath()) {
123
+ try {
124
+ mkdirSync(dirname(path), { recursive: true });
125
+ writeFileSync(path, JSON.stringify(c));
126
+ }
127
+ catch { /* a cache */ }
128
+ }
129
+ /** The cached medians when under a day old, else measured now (bounded) and cached. */
130
+ export function subagentCosts(now = Date.now(), path = subagentCostsPath()) {
131
+ try {
132
+ if (existsSync(path)) {
133
+ const c = JSON.parse(readFileSync(path, "utf8"));
134
+ if (typeof c?.computedAt === "number" && now - c.computedAt < DAY && now >= c.computedAt && c.byType && typeof c.byType === "object")
135
+ return c;
136
+ }
137
+ }
138
+ catch { /* remeasure */ }
139
+ try {
140
+ const c = measureSubagentCosts(30, { limit: 80, budgetMs: 1500, now });
141
+ saveSubagentCosts(c, path);
142
+ return c;
143
+ }
144
+ catch {
145
+ return undefined;
146
+ }
147
+ }
148
+ /** The Agent tool's model aliases, as a model id to price them at: the one these runs used most, else the current version. */
149
+ const ALIAS = {
150
+ sonnet: { family: /sonnet/i, fallback: "claude-sonnet-5-5" },
151
+ opus: { family: /opus/i, fallback: "claude-opus-5-5" },
152
+ haiku: { family: /haiku/i, fallback: "claude-haiku-5-5" },
153
+ fable: { family: /fable|mythos/i, fallback: "claude-fable-5-1" },
154
+ };
155
+ function aliasModel(alias, costs) {
156
+ const a = ALIAS[alias.toLowerCase()];
157
+ if (!a)
158
+ return undefined;
159
+ const seen = Object.entries(costs.byModel).filter(([m]) => a.family.test(m)).sort((x, y) => y[1].n - x[1].n)[0]?.[0];
160
+ return seen ?? a.fallback;
161
+ }
162
+ const short = (model) => {
163
+ const m = /claude-(opus|sonnet|haiku|fable|mythos)-(\d+)(?:-(\d{1,2}))?(?!\d)/i.exec(model ?? "");
164
+ return m ? `${m[1][0].toUpperCase()}${m[1].slice(1)} ${m[2]}${m[3] ? `.${m[3]}` : ""}` : model ?? "its model";
165
+ };
166
+ const familyOf = (model) => /(opus|sonnet|haiku|fable|mythos)/i.exec(model)?.[1]?.toLowerCase().replace("mythos", "fable");
167
+ /** The model a type is pinned to: 90%+ of its runs (3 or more) in one family, priced at that family's most-run model. */
168
+ export function pinnedModel(costs, type) {
169
+ const runs = Object.entries(costs.byTypeModel).filter(([k]) => k.startsWith(`${type}|`)).map(([k, v]) => ({ model: k.slice(type.length + 1), n: v.n }));
170
+ const total = runs.reduce((a, r) => a + r.n, 0);
171
+ if (total < MIN_RUNS)
172
+ return undefined;
173
+ const families = new Map();
174
+ for (const r of runs) {
175
+ const f = familyOf(r.model);
176
+ if (f)
177
+ families.set(f, (families.get(f) ?? 0) + r.n);
178
+ }
179
+ const [family, n] = [...families.entries()].sort((a, b) => b[1] - a[1])[0] ?? [];
180
+ if (!family || n / total < 0.9)
181
+ return undefined;
182
+ return runs.filter((r) => familyOf(r.model) === family).sort((a, b) => b.n - a.n)[0].model;
183
+ }
184
+ /** What a subagent of this type on this model costs, from the user's own runs. Undefined with too few. */
185
+ export function estimateSubagent(costs, type, modelAlias, parentModel) {
186
+ const byType = costs.byType[type];
187
+ // A subagent runs on the model it is given; else a type whose runs all
188
+ // used one family is pinned to it by its definition (claude-code-guide runs
189
+ // on Haiku whatever the parent is), priced at its usual model; else it
190
+ // inherits the parent's model (general-purpose and Explore ran on several
191
+ // families on the author's history: they follow the parent).
192
+ const model = (modelAlias ? aliasModel(modelAlias, costs) : undefined) ?? pinnedModel(costs, type) ?? parentModel ?? (byType && byType.n >= MIN_RUNS ? byType.model : undefined);
193
+ const scale = (from, to) => {
194
+ const a = pricingFor(from), b = pricingFor(to);
195
+ return a && b && a.inputPerM > 0 ? b.inputPerM / a.inputPerM : 1;
196
+ };
197
+ let base, factor = 1;
198
+ const exact = model ? costs.byTypeModel[`${type}|${model}`] : undefined;
199
+ if (exact && exact.n >= MIN_RUNS)
200
+ base = exact;
201
+ else if (byType && byType.n >= MIN_RUNS) {
202
+ base = byType;
203
+ factor = scale(byType.model, model ?? byType.model);
204
+ }
205
+ else if (model && costs.byModel[model]?.n >= MIN_RUNS)
206
+ base = costs.byModel[model];
207
+ else if (costs.all && costs.all.n >= MIN_RUNS) {
208
+ base = costs.all;
209
+ factor = scale(costs.all.model, model ?? costs.all.model);
210
+ }
211
+ if (!base)
212
+ return undefined;
213
+ const est = { type, model: model ?? base.model, median: base.median * factor, p90: base.p90 * factor, runs: base.n };
214
+ const sonnet = aliasModel("sonnet", costs);
215
+ // Sonnet is offered only where it is cheaper than what the subagent runs on.
216
+ if (est.model && /opus|fable|mythos/i.test(est.model) && (pricingFor(sonnet)?.inputPerM ?? Infinity) < (pricingFor(est.model)?.inputPerM ?? 0)) {
217
+ const measured = costs.byTypeModel[`${type}|${sonnet}`];
218
+ est.cheaper = measured && measured.n >= MIN_RUNS
219
+ ? { model: sonnet, median: measured.median, measured: true }
220
+ : { model: sonnet, median: est.median * scale(est.model, sonnet), measured: false };
221
+ if (!(est.cheaper.median < est.median))
222
+ delete est.cheaper;
223
+ }
224
+ return est;
225
+ }
226
+ const BURST_MS = 120_000;
227
+ /** The session's launch log, beside the hook's per-session state. */
228
+ export function spawnLogPath(sessionId) {
229
+ return join(statePath().replace(/\.json$/, "") + ".d", createHash("sha1").update(sessionId).digest("hex").slice(0, 16) + ".spawns.jsonl");
230
+ }
231
+ /** Append this launch, then read the log back (its last 64 KB: hundreds of launches). */
232
+ export function recordSpawn(path, line) {
233
+ try {
234
+ mkdirSync(dirname(path), { recursive: true });
235
+ appendFileSync(path, JSON.stringify(line) + "\n");
236
+ const size = statSync(path).size;
237
+ const text = readFileSync(path, "utf8");
238
+ return text.slice(Math.max(0, size - 64 * 1024)).split("\n").flatMap((l) => {
239
+ try {
240
+ const v = JSON.parse(l);
241
+ return v && typeof v.t === "number" && typeof v.type === "string" && typeof v.id === "string" ? [{ t: v.t, type: v.type, id: v.id, c: v.c === true }] : [];
242
+ }
243
+ catch {
244
+ return [];
245
+ }
246
+ });
247
+ }
248
+ catch {
249
+ return [line];
250
+ }
251
+ }
252
+ /** What a launch's input says: its type and the model alias it asks for. */
253
+ export function launchOf(input) {
254
+ if (!/^(Agent|Task)$/.test(String(input.tool_name ?? "")))
255
+ return undefined;
256
+ const ti = input.tool_input && typeof input.tool_input === "object" ? input.tool_input : {};
257
+ const type = typeof ti.subagent_type === "string" && ti.subagent_type.trim() ? ti.subagent_type.trim().slice(0, 60) : "general-purpose";
258
+ return { type, alias: typeof ti.model === "string" ? ti.model : undefined };
259
+ }
260
+ /**
261
+ * What to say before this launch, from the session's launch log (this one
262
+ * included, as `own`). The user sees the price on the first launch of a type
263
+ * in the session and when launches bunch up (3 within two minutes, then
264
+ * every 5th); the model gets one short note a session, on the first launch
265
+ * that was quoted a cheaper model.
266
+ */
267
+ export function fanoutMessage(est, alias, log, own) {
268
+ if (!est)
269
+ return {};
270
+ const at = log.findIndex((l) => l.id === own.id);
271
+ const upTo = at >= 0 ? log.slice(0, at + 1) : [...log, own];
272
+ const firstOfType = upTo.find((l) => l.type === own.type)?.id === own.id;
273
+ const burst = upTo.filter((l) => Math.abs(own.t - l.t) < BURST_MS).length;
274
+ const showBurst = burst >= 3 && (burst === 3 || burst % 5 === 0);
275
+ const out = {};
276
+ const cheaper = est.cheaper && !alias ? est.cheaper : undefined;
277
+ if (firstOfType || showBurst) {
278
+ const runs = `${est.runs} run${est.runs === 1 ? "" : "s"}`;
279
+ const sonnet = cheaper ? ` On Sonnet: ~${formatUsd(cheaper.median)}${cheaper.measured ? "" : " at its price"}.` : "";
280
+ out.systemMessage = showBurst
281
+ ? `context-doctor: ${burst} subagents in 2 minutes, ~${formatUsd(est.median * burst)} together at your median of ~${formatUsd(est.median)} for ${own.type} on ${short(est.model)} (${runs}).${sonnet}`
282
+ : `context-doctor: a ${own.type} subagent on ${short(est.model)} costs ~${formatUsd(est.median)} at your median (p90 ${formatUsd(est.p90)}, ${runs}, list price).${sonnet}`;
283
+ }
284
+ if (cheaper && upTo.find((l) => l.c)?.id === own.id) {
285
+ out.additionalContext = `context-doctor: on this machine a ${own.type} subagent costs ~${formatUsd(est.median)} at the median on ${short(est.model)}, ~${formatUsd(cheaper.median)} on Sonnet. For search, reading or summarising, pass model: "sonnet" to the Agent tool.`;
286
+ }
287
+ return out;
288
+ }
289
+ /** The whole PreToolUse answer: estimate, log, decide. Silent (an empty object) for anything else. */
290
+ export function fanoutHook(input, costs, sessionId, now = Date.now()) {
291
+ const launch = launchOf(input);
292
+ if (!launch || !costs)
293
+ return {};
294
+ const parentModel = input.transcript_path && existsSync(input.transcript_path) ? tailUsage(input.transcript_path)?.model : undefined;
295
+ const est = estimateSubagent(costs, launch.type, launch.alias, parentModel);
296
+ if (!est)
297
+ return {};
298
+ const own = { t: now, type: launch.type, id: randomUUID(), c: Boolean(est.cheaper && !launch.alias) };
299
+ return fanoutMessage(est, launch.alias, recordSpawn(spawnLogPath(sessionId), own), own);
300
+ }
301
+ /** For `doctor` and the docs: where the medians come from. */
302
+ export function describeCosts(c) {
303
+ if (!c || !c.all)
304
+ return "no subagent runs measured yet";
305
+ return `${c.n} subagents in ${c.days} days, median ${formatUsd(c.all.median)} (${basename(subagentCostsPath())})`;
306
+ }
307
+ /** The medians the subagent price quotes, for `context-doctor subagents`. */
308
+ export function renderCostMedians(c) {
309
+ const types = Object.entries(c.byType).filter(([, s]) => s.n >= MIN_RUNS).sort((a, b) => b[1].n - a[1].n).slice(0, 8);
310
+ if (!types.length)
311
+ return [];
312
+ return [
313
+ "",
314
+ `What a subagent costs here (median, p90; the price shown before one starts):`,
315
+ ...types.map(([t, s]) => ` ${t.slice(0, 26).padEnd(26)} ${formatUsd(s.median).padStart(8)} ${formatUsd(s.p90).padStart(8)} ${s.n} runs, mostly ${short(s.model)}`),
316
+ ];
317
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * ChatGPT file inputs for pack_context over --http.
3
+ *
4
+ * A tool that lists a top-level field in `_meta["openai/fileParams"]` receives
5
+ * a file the user uploaded as `{ download_url, file_id, mime_type?, file_name? }`
6
+ * (developers.openai.com/plugins/reference, "Define file inputs"; every file
7
+ * object schema must declare all four properties and require only
8
+ * download_url and file_id). The server downloads it and packs it like a
9
+ * file read from disk, so a 200-page PDF reaches the model as the few chunks a
10
+ * question needs.
11
+ *
12
+ * A URL from a caller is an SSRF risk on a server anyone with the tunnel URL
13
+ * can reach, so a download is: https only (redirects too, at most three,
14
+ * never to http), never to a private, loopback or link-local address (checked
15
+ * on the resolved address at connect time, so DNS cannot point it inward),
16
+ * no credentials in the URL, capped in size and time. Plain http to a
17
+ * loopback address is allowed only when CONTEXT_DOCTOR_TEST_LOOPBACK_FILES=1,
18
+ * for the tests' local mock server.
19
+ */
20
+ import type { PackSource } from "./pack.js";
21
+ export interface OpenAiFile {
22
+ download_url: string;
23
+ file_id: string;
24
+ mime_type?: string;
25
+ file_name?: string;
26
+ }
27
+ /** Per file: bytes and time. Per call: files, bytes and time (downloads and extraction together). */
28
+ export declare const FILE_LIMITS: {
29
+ files: number;
30
+ bytes: number;
31
+ totalBytes: number;
32
+ timeoutMs: number;
33
+ redirects: number;
34
+ callMs: number;
35
+ };
36
+ /** Loopback, private, link-local, CGNAT, unspecified, multicast or reserved: never a place a download should go. */
37
+ export declare function isPrivateAddress(ip: string): boolean;
38
+ /** A download URL this server may fetch, or the reason it may not. */
39
+ export declare function checkFileUrl(raw: string, env?: NodeJS.ProcessEnv): {
40
+ url: URL;
41
+ } | {
42
+ error: string;
43
+ };
44
+ /**
45
+ * Download one file, following at most FILE_LIMITS.redirects https redirects,
46
+ * within FILE_LIMITS.timeoutMs (or the caller's earlier `deadline`) and
47
+ * `maxBytes` (default the per-file limit). Never throws.
48
+ */
49
+ export declare function downloadFile(raw: string, env?: NodeJS.ProcessEnv, { deadline: callDeadline, maxBytes }?: {
50
+ deadline?: number;
51
+ maxBytes?: number;
52
+ }): Promise<{
53
+ body: Buffer;
54
+ } | {
55
+ error: string;
56
+ }>;
57
+ /** Download and read files ChatGPT passed, into pack sources. Never throws. */
58
+ export declare function sourcesFromOpenAiFiles(files: OpenAiFile[], env?: NodeJS.ProcessEnv): Promise<{
59
+ sources: PackSource[];
60
+ skipped: string[];
61
+ }>;