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
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Compact tool results: a short text, the detail as `structuredContent`, and
3
+ * presentation-only data in `_meta`.
4
+ *
5
+ * Why: every byte of a tool result is re-read on every later turn of the chat.
6
+ * profile_context's full report (bars, message previews) and pack_context's
7
+ * outline (one line per chunk, the heading path repeated on each) are mostly
8
+ * presentation. ChatGPT surfaces `content` and `structuredContent` to the
9
+ * model and keeps `_meta` for the widget only (developers.openai.com/plugins/reference,
10
+ * "Tool results"), so the compact form puts one line of text and
11
+ * the decision-relevant fields in front of the model, and the rest where only
12
+ * a widget would read it.
13
+ *
14
+ * Not the default: a client that ignores `structuredContent` would lose the
15
+ * detail. The server sends this form to ChatGPT (recognised by the
16
+ * `openai/session` or `openai/subject` request metadata, the anonymized
17
+ * conversation and user ids it attaches to tool calls) or when
18
+ * CONTEXT_DOCTOR_RESULTS=compact; everything else gets the full text, as
19
+ * before. Measured sizes are in ROADMAP.md ("Desktop chat apps").
20
+ */
21
+ import { formatTokens } from "./tokens.js";
22
+ /**
23
+ * Which form a tool call gets. `requestMeta` is the request's `_meta`.
24
+ * ChatGPT's identification keys mark ChatGPT itself, the client documented to
25
+ * show structuredContent to the model; any `openai/*` key would also catch
26
+ * other OpenAI clients (locale, user agent) that may not. An explicit
27
+ * CONTEXT_DOCTOR_RESULTS (full or compact) wins.
28
+ */
29
+ const CHATGPT_KEYS = ["openai/session", "openai/subject"];
30
+ export function resultMode(requestMeta, env = process.env) {
31
+ const forced = env.CONTEXT_DOCTOR_RESULTS?.trim().toLowerCase();
32
+ if (forced === "full" || forced === "compact")
33
+ return forced;
34
+ if (requestMeta && typeof requestMeta === "object" && CHATGPT_KEYS.some((k) => typeof requestMeta[k] === "string"))
35
+ return "compact";
36
+ return "full";
37
+ }
38
+ const round = (n) => Math.round(n);
39
+ /** profile_context on a conversation. */
40
+ export function compactProfile(p, fullText) {
41
+ const top = p.findings[0];
42
+ const pct = p.totalTokens > 0 ? Math.round((p.totalEstSavings / p.totalTokens) * 100) : 0;
43
+ const lines = [
44
+ `~${formatTokens(p.totalTokens)} tokens in ${p.messageCount} messages (${p.sourceFormat})${p.usagePct !== undefined ? `, ${p.usagePct.toFixed(0)}% of the window` : ""}; ~${formatTokens(p.totalEstSavings)} recoverable (${pct}%).`,
45
+ ];
46
+ if (p.parseWarning)
47
+ lines.unshift(`⚠ ${p.parseWarning}`);
48
+ lines.push(top ? `Act on #1 (first in structuredContent.findings).` : "No findings.");
49
+ const categories = Object.fromEntries(Object.entries(p.categories).filter(([, t]) => t > 0).sort((a, b) => b[1] - a[1]).map(([k, t]) => [k, round(t)]));
50
+ const structured = {
51
+ total_tokens: round(p.totalTokens),
52
+ messages: p.messageCount,
53
+ recoverable_tokens: round(p.totalEstSavings),
54
+ by_category: categories,
55
+ // One string per finding: JSON keys repeated per object cost more than they say.
56
+ findings: p.findings.slice(0, 6).map((f) => `${f.severity}${f.estSavings > 0 ? ` ~${formatTokens(f.estSavings)}` : ""}: ${f.message} → ${f.suggestion}`),
57
+ };
58
+ if (p.findings.length > 6)
59
+ structured.more_findings = p.findings.length - 6;
60
+ if (p.model)
61
+ structured.model = p.model;
62
+ if (p.usagePct !== undefined)
63
+ structured.window_pct = Number(p.usagePct.toFixed(1));
64
+ if (p.cost)
65
+ structured.usd_per_call = Number(p.cost.perCallUsd.toFixed(4));
66
+ return {
67
+ text: lines.join("\n"),
68
+ structured,
69
+ // The bar chart and message previews: presentation, and raw conversation
70
+ // text the model already has. A widget can show them; the model need not.
71
+ meta: { "context-doctor/report": fullText, "context-doctor/largest": p.largestMessages.map((m) => ({ index: m.index, kind: m.kind, tokens: round(m.tokens), preview: m.preview })) },
72
+ };
73
+ }
74
+ /** profile_context on a chat-app sketch. */
75
+ export function compactSketch(p, fullText) {
76
+ // The sketch report is short already: what makes it longer than it needs to
77
+ // be is every finding's action. Only #1 is acted on, so only #1 keeps its
78
+ // action (in the text); the rest are one line each.
79
+ const [top, ...rest] = p.findings;
80
+ const lines = [`~${formatTokens(p.totalTokens)} tokens, ${p.turns} turns${p.usagePct !== undefined ? `, ~${p.usagePct}% of the window` : ""} (estimate); ~${formatTokens(p.totalEstSavings)} recoverable, only in a new chat.`];
81
+ if (top) {
82
+ lines.push(`Act on #1 now: ${top.message} → ${top.action}`);
83
+ lines.push("This chat's history cannot be edited: what is already here comes back only in a new chat (save_handoff).");
84
+ }
85
+ else
86
+ lines.push("No findings. Keep going.");
87
+ const structured = {
88
+ total_tokens: p.totalTokens,
89
+ recoverable_tokens: p.totalEstSavings,
90
+ recoverable_by: "a new chat (handoff)",
91
+ };
92
+ if (rest.length)
93
+ structured.other_findings = rest.map((f) => `${f.severity}${f.estSavings > 0 ? ` ~${formatTokens(f.estSavings)}` : ""}: ${f.message}`);
94
+ if (p.usagePct !== undefined)
95
+ structured.window_pct = p.usagePct;
96
+ if (p.perTurnUsd !== undefined)
97
+ structured.usd_per_turn = Number(p.perTurnUsd.toFixed(4));
98
+ return { text: lines.join("\n"), structured, meta: { "context-doctor/report": fullText } };
99
+ }
100
+ /** "#2-5" for a run of consecutive chunk numbers. */
101
+ function idRange(first, last) {
102
+ const n = (id) => id.slice(id.lastIndexOf("#") + 1);
103
+ return first === last ? `#${n(first)}` : `#${n(first)}-${n(last)}`;
104
+ }
105
+ /** The last segment of a heading path, without the "(cont.)" a split chunk carries. */
106
+ function shortHeading(heading) {
107
+ const base = heading.replace(/\s*\(cont\.\)$/, "");
108
+ const parts = base.split(" > ");
109
+ return parts[parts.length - 1] || base;
110
+ }
111
+ /** pack_context with no query: sections instead of one line per chunk. */
112
+ export function compactOutline(r, fullText, maxSections = 120) {
113
+ // Consecutive chunks of one source under the same heading are one section.
114
+ const bySource = new Map();
115
+ for (const c of r.chunks) {
116
+ const list = bySource.get(c.source) ?? [];
117
+ const heading = shortHeading(c.heading);
118
+ const prev = list[list.length - 1];
119
+ if (prev && prev.heading === heading) {
120
+ prev.last = c.id;
121
+ prev.tokens += c.tokens;
122
+ }
123
+ else
124
+ list.push({ first: c.id, last: c.id, heading, tokens: c.tokens });
125
+ bySource.set(c.source, list);
126
+ }
127
+ let budget = maxSections;
128
+ let omitted = 0;
129
+ const sources = [...bySource.entries()].map(([name, sections]) => {
130
+ const shown = sections.slice(0, Math.max(0, budget));
131
+ budget -= shown.length;
132
+ omitted += sections.length - shown.length;
133
+ const tokens = sections.reduce((n, s) => n + s.tokens, 0);
134
+ return { name, tokens: round(tokens), sections: shown.map((s) => `${idRange(s.first, s.last)} ${s.heading} ~${formatTokens(s.tokens)}`) };
135
+ });
136
+ const names = r.sources.length === 1 ? r.sources[0].name : `${r.sources.length} files`;
137
+ const example = r.chunks[0]?.id ?? "name#1";
138
+ const text = `OUTLINE of ${names}: ~${formatTokens(r.totalTokens)} tokens in ${r.chunks.length} chunks, as sections in structuredContent. ` +
139
+ `Nothing packed: pass a query, or ids (<name>#<n>, e.g. ${example}).`;
140
+ const structured = { total_tokens: round(r.totalTokens), chunks: r.chunks.length, sources };
141
+ if (omitted > 0)
142
+ structured.sections_not_shown = omitted;
143
+ return { text, structured, meta: { "context-doctor/outline": fullText } };
144
+ }
@@ -71,4 +71,4 @@ export interface SetWindowResult {
71
71
  export declare function setCompactWindow(window: number | undefined, home?: string): SetWindowResult;
72
72
  /** "400k" / "400000" / "0.4m" -> 400000. Undefined when unparseable. */
73
73
  export declare function parseWindow(raw: string): number | undefined;
74
- export declare function renderCompactWindows(r: CompactWindowReport, current?: number): string;
74
+ export declare function renderCompactWindows(r: CompactWindowReport, current?: number, limitLines?: (estimates: WindowEstimate[]) => string[]): string;
@@ -280,7 +280,7 @@ export function parseWindow(raw) {
280
280
  }
281
281
  const usd = (n) => (Math.abs(n) >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
282
282
  const k = (n) => `${Math.round(n / 1000)}k`;
283
- export function renderCompactWindows(r, current) {
283
+ export function renderCompactWindows(r, current, limitLines) {
284
284
  const lines = [];
285
285
  lines.push("Auto-compact window: compact earlier, automatically (Claude Code's own setting)");
286
286
  // Counted and said exactly as `savings` says it, so the two screens agree.
@@ -298,6 +298,11 @@ export function renderCompactWindows(r, current) {
298
298
  lines.push(` ${k(e.window).padStart(6)} ${usd(e.withWindowUsd).padStart(10)} ${(usd(e.savedUsd) + ` (${Math.round(e.savedPct * 100)}%)`).padEnd(16)} ${String(e.compactions).padStart(4)} (${((e.compactions / r.days) * 7).toFixed(1)}/week)${mark}`);
299
299
  }
300
300
  lines.push(` as now ${usd(r.estimates[0]?.baselineUsd ?? 0).padStart(10)} ${String(r.actualCompactions).padStart(4)} (${((r.actualCompactions / r.days) * 7).toFixed(1)}/week${r.idleCompactions ? `; ${r.idleCompactions} while idle` : ""})`);
301
+ const inLimitLines = limitLines?.(r.estimates) ?? [];
302
+ if (inLimitLines.length) {
303
+ lines.push("");
304
+ lines.push(...inLimitLines);
305
+ }
301
306
  lines.push("");
302
307
  lines.push("\"as now\" is what you were billed (transcript usage at list price, as in");
303
308
  lines.push("`context-doctor savings`); each window saves the replay's share of it.");
package/dist/doctor.js CHANGED
@@ -6,7 +6,7 @@
6
6
  * when any check fails (✗), so a script can tell; an app that is absent, or
7
7
  * that nothing was installed into, is a note (–), not a failure.
8
8
  */
9
- import { autopilotPaths, health, installedVersion, proxyUrl, recentSurfaces } from "./autopilot.js";
9
+ import { autopilotPaths, DEFAULT_AUTOPILOT_PORT, health, installedVersion, portOccupant, proxyUrl, recentSurfaces } from "./autopilot.js";
10
10
  import { spawn } from "node:child_process";
11
11
  import { accessSync, constants as fsConstants, existsSync, readFileSync } from "node:fs";
12
12
  import { homedir, platform } from "node:os";
@@ -21,6 +21,7 @@ import { COPILOT_HOOK_EVENT, copilotHookFilePath, copilotLegacyConfigPath, copil
21
21
  import { describeDesktopUsage, desktopUsage } from "./desktopusage.js";
22
22
  import { withInvocation } from "./invocation.js";
23
23
  import { describeInstalls, modelSwitchReadiness, PRE_MODEL_SWITCH_SINCE } from "./modelswitch.js";
24
+ import { describeCosts, subagentCostsPath } from "./fanout.js";
24
25
  function claudeDesktopConfigPath() {
25
26
  switch (platform()) {
26
27
  case "darwin": return join(homedir(), "Library", "Application Support", "Claude", "claude_desktop_config.json");
@@ -143,6 +144,33 @@ function pluginEnabled(layers) {
143
144
  }
144
145
  return [...state.values()].some(Boolean);
145
146
  }
147
+ /** "headroom (pid 4242)", or "another program". */
148
+ function occupantName(o) {
149
+ return `${o.name ?? "another program"}${o.pid ? ` (pid ${o.pid})` : ""}`;
150
+ }
151
+ /**
152
+ * The subagent price (PreToolUse on the Agent tool, fanout.ts): registered
153
+ * with a matcher that names the tool by both its names, and what the medians
154
+ * it quotes come from.
155
+ */
156
+ function fanoutCheck(settings, plugin) {
157
+ const label = "Subagent price";
158
+ const entries = Array.isArray(settings.hooks?.PreToolUse) ? settings.hooks.PreToolUse : [];
159
+ const ours = entries.find((e) => /context-doctor|cli\.js"?\s+hook/.test(e.hooks?.[0]?.command ?? ""));
160
+ let costs;
161
+ try {
162
+ costs = JSON.parse(readFileSync(subagentCostsPath(), "utf8"));
163
+ }
164
+ catch { /* not measured yet */ }
165
+ const basis = costs?.all ? `; quotes your medians (${describeCosts(costs)})` : "; quotes your medians once you have run a few subagents";
166
+ if (ours && !/\bAgent\b/.test(ours.matcher ?? ""))
167
+ return { label, status: "warn", detail: `PreToolUse entry without the Agent matcher (${JSON.stringify(ours.matcher ?? "")}): it runs before every tool; re-run context-doctor install` };
168
+ if (ours)
169
+ return { label, status: "ok", detail: `PreToolUse on the Agent tool: before a subagent starts, its price at your median and the Sonnet option; never blocks${basis}` };
170
+ if (plugin)
171
+ return { label, status: "ok", detail: `PreToolUse: provided by the context-doctor plugin${basis}` };
172
+ return { label, status: "warn", detail: "not registered: subagents start with no price shown; run context-doctor install" };
173
+ }
146
174
  /**
147
175
  * The model-switch warning (PreModelSwitch). Its entry in settings.json is a
148
176
  * failure next to a Claude Code older than the event: that version skips the
@@ -375,6 +403,7 @@ export async function runDoctor() {
375
403
  else if (!ours && plugin) {
376
404
  checks.push({ label: "Every-prompt hook", status: "ok", detail: "provided by the context-doctor plugin" });
377
405
  checks.push({ label: "Compaction hook", status: "ok", detail: "PreCompact: provided by the context-doctor plugin" });
406
+ checks.push(fanoutCheck(settings, plugin));
378
407
  }
379
408
  else if (!ours) {
380
409
  checks.push(missingHook("Every-prompt hook", claudeMcp));
@@ -392,6 +421,7 @@ export async function runDoctor() {
392
421
  checks.push(preOurs
393
422
  ? { label: "Compaction hook", status: "ok", detail: "PreCompact: each compaction's summary keeps the session's files, open tasks, your instructions and failing commands" }
394
423
  : { label: "Compaction hook", status: "warn", detail: "not registered: compactions use generic instructions; run context-doctor install" });
424
+ checks.push(fanoutCheck(settings, plugin));
395
425
  }
396
426
  checks.push(modelSwitchCheck(settings, plugin));
397
427
  }
@@ -635,6 +665,20 @@ export async function runDoctor() {
635
665
  }
636
666
  if (!existsSync(paths.config)) {
637
667
  checks.push({ label: "Autopilot", status: "skip", detail: "off (context-doctor autopilot on: clears stale tool output in every new Claude Code session)" });
668
+ // Another local proxy on autopilot's port: `autopilot on` would not start there.
669
+ const other = await portOccupant(DEFAULT_AUTOPILOT_PORT);
670
+ if (other.listening && !other.ours) {
671
+ checks.push({
672
+ label: "Autopilot port",
673
+ status: "warn",
674
+ detail: other.bindable
675
+ ? `${occupantName(other)} listens on port ${DEFAULT_AUTOPILOT_PORT} on another address: \`autopilot on\` would start beside it on 127.0.0.1 and take the traffic sent to 127.0.0.1 (Claude Code's), while apps that use localhost:${DEFAULT_AUTOPILOT_PORT} may reach ${occupantName(other)}; to keep them apart: context-doctor autopilot on --port 8788`
676
+ : `${occupantName(other)} already listens on ${proxyUrl(DEFAULT_AUTOPILOT_PORT)}: \`autopilot on\` could not start there; use another port (context-doctor autopilot on --port 8788)`,
677
+ });
678
+ }
679
+ else if (other.onIpv6Loopback) {
680
+ checks.push({ label: "Autopilot port", status: "warn", detail: `${other.onIpv6Loopback} listens on [::1]:${DEFAULT_AUTOPILOT_PORT}: apps that use localhost:${DEFAULT_AUTOPILOT_PORT} may reach it instead of autopilot, which uses 127.0.0.1` });
681
+ }
638
682
  }
639
683
  else if (!cfg) {
640
684
  let routedTo;
@@ -676,6 +720,19 @@ export async function runDoctor() {
676
720
  : h.ok && h.autopilot && routed
677
721
  ? { label: "Autopilot", status: "ok", detail: `proxy up on ${proxyUrl(cfg.port)}, Claude Code routed through it${seen >= 0 ? ` (${seen} requests since start)` : ""}${paused ? " (PAUSED: passthrough)" : ""}` }
678
722
  : { label: "Autopilot", status: "fail", detail: !h.ok ? `proxy not answering on ${proxyUrl(cfg.port)}: the next Claude Code prompt restarts it; or run: context-doctor autopilot on` : "settings.json no longer routes Claude Code to the proxy: run context-doctor autopilot on" });
723
+ // Not ours, yet listening on our port: with Claude Code routed there,
724
+ // its requests go through that program, and the proxy cannot restart.
725
+ const other = await portOccupant(cfg.port);
726
+ if (!h.ok && other.listening && !other.ours) {
727
+ checks.push({
728
+ label: "Autopilot port",
729
+ status: "fail",
730
+ detail: `${occupantName(other)} answers on ${proxyUrl(cfg.port)} instead of the proxy${routed ? ", and Claude Code's requests go to it" : ""}${other.bindable ? " (the proxy can start beside it on 127.0.0.1: the next Claude Code prompt restarts it)" : ""}: stop it, or move autopilot (context-doctor autopilot off, then autopilot on --port 8788)`,
731
+ });
732
+ }
733
+ else if (other.onIpv6Loopback) {
734
+ checks.push({ label: "Autopilot port", status: "warn", detail: `${other.onIpv6Loopback} listens on [::1]:${cfg.port}: Claude Code reaches autopilot at 127.0.0.1, but apps that use localhost:${cfg.port} may reach ${other.onIpv6Loopback} instead` });
735
+ }
679
736
  }
680
737
  }
681
738
  const mark = { ok: "✓", warn: "!", fail: "✗", skip: "–" };
package/dist/extract.d.ts CHANGED
@@ -7,11 +7,34 @@
7
7
  * `textutil` for Word/RTF/ODT on macOS, and `unzip` for the zipped XML
8
8
  * formats (docx, pptx, odt) elsewhere. When none is available the caller
9
9
  * gets a reason that names what to install, never a silent skip.
10
+ *
11
+ * Two safety rules, both learned from a QA pass on uploads over --http:
12
+ * - textutil runs with -noload -nostore. A ".doc" that is really HTML made
13
+ * textutil fetch its stylesheets and images, from 127.0.0.1 and from
14
+ * 169.254.169.254 as readily as from the web: a server-side request
15
+ * forgery through a document;
16
+ * - the MCP server extracts with extractTextAsync, which never blocks the
17
+ * event loop and stops at a time budget for the whole call (a slow PDF
18
+ * held /health for 30 s; one can take 120 s). The synchronous
19
+ * extractText stays for the one-shot CLI.
10
20
  */
11
21
  export declare const EXTRACTABLE: Set<string>;
22
+ /** Never load or write a document's subsidiary resources (stylesheets, images, frames). */
23
+ export declare const TEXTUTIL_ARGS: string[];
12
24
  /** The document's text, or the reason it could not be read. */
13
25
  export declare function extractText(path: string): {
14
26
  text: string;
15
27
  } | {
16
28
  error: string;
17
29
  };
30
+ /** Default time budget for one extraction call in the MCP server. */
31
+ export declare const EXTRACT_BUDGET_MS = 20000;
32
+ /**
33
+ * extractText for a server: asynchronous, and bounded by `deadline` (ms since
34
+ * the epoch) across every tool it tries. Past the deadline the reason says so.
35
+ */
36
+ export declare function extractTextAsync(path: string, deadline?: number): Promise<{
37
+ text: string;
38
+ } | {
39
+ error: string;
40
+ }>;
package/dist/extract.js CHANGED
@@ -7,8 +7,18 @@
7
7
  * `textutil` for Word/RTF/ODT on macOS, and `unzip` for the zipped XML
8
8
  * formats (docx, pptx, odt) elsewhere. When none is available the caller
9
9
  * gets a reason that names what to install, never a silent skip.
10
+ *
11
+ * Two safety rules, both learned from a QA pass on uploads over --http:
12
+ * - textutil runs with -noload -nostore. A ".doc" that is really HTML made
13
+ * textutil fetch its stylesheets and images, from 127.0.0.1 and from
14
+ * 169.254.169.254 as readily as from the web: a server-side request
15
+ * forgery through a document;
16
+ * - the MCP server extracts with extractTextAsync, which never blocks the
17
+ * event loop and stops at a time budget for the whole call (a slow PDF
18
+ * held /health for 30 s; one can take 120 s). The synchronous
19
+ * extractText stays for the one-shot CLI.
10
20
  */
11
- import { spawnSync } from "node:child_process";
21
+ import { execFile, spawnSync } from "node:child_process";
12
22
  import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
13
23
  import { tmpdir } from "node:os";
14
24
  import { dirname, extname, join } from "node:path";
@@ -23,6 +33,8 @@ function run(cmd, args) {
23
33
  return undefined;
24
34
  }
25
35
  }
36
+ /** Never load or write a document's subsidiary resources (stylesheets, images, frames). */
37
+ export const TEXTUTIL_ARGS = ["-convert", "txt", "-noload", "-nostore", "-stdout"];
26
38
  const PDFKIT_JXA = 'ObjC.import("PDFKit"); function run(a) { const d = $.PDFDocument.alloc.initWithURL($.NSURL.fileURLWithPath(a[0])); return d.isNil() ? "" : d.string.js }';
27
39
  /**
28
40
  * pdftotext comes in two families (poppler, and Xpdf as shipped with some
@@ -49,8 +61,9 @@ function pdftotext(path) {
49
61
  /** Paragraph-ish text from zipped XML: one paragraph per closing p/slide-text tag, entities decoded. */
50
62
  function fromZippedXml(path, members) {
51
63
  const xml = run("unzip", ["-p", path, ...members]);
52
- if (!xml)
53
- return undefined;
64
+ return xml ? xmlToText(xml) : undefined;
65
+ }
66
+ function xmlToText(xml) {
54
67
  return xml
55
68
  .replace(/<\/(w:p|a:p|text:p|text:h)>/g, "\n\n")
56
69
  .replace(/<(w:tab|w:br)\/>/g, " ")
@@ -75,7 +88,7 @@ export function extractText(path) {
75
88
  }
76
89
  else {
77
90
  if (mac && ext !== ".pptx")
78
- text = run("textutil", ["-convert", "txt", "-stdout", path]);
91
+ text = run("textutil", [...TEXTUTIL_ARGS, path]);
79
92
  if (!text) {
80
93
  const members = ext === ".docx" ? ["word/document.xml"] : ext === ".pptx" ? ["ppt/slides/*.xml"] : ext === ".odt" ? ["content.xml"] : [];
81
94
  if (members.length)
@@ -86,3 +99,107 @@ export function extractText(path) {
86
99
  }
87
100
  return { text };
88
101
  }
102
+ /** Default time budget for one extraction call in the MCP server. */
103
+ export const EXTRACT_BUDGET_MS = 20_000;
104
+ /**
105
+ * A command's stdout, or undefined, without blocking the event loop: killed
106
+ * (SIGKILL) when `deadline` passes. `timedOut` says which happened.
107
+ */
108
+ function runAsync(cmd, args, deadline) {
109
+ const timeout = deadline - Date.now();
110
+ if (timeout <= 0)
111
+ return Promise.resolve({ timedOut: true });
112
+ return new Promise((resolve) => {
113
+ let settled = false;
114
+ const finish = (r) => {
115
+ if (settled)
116
+ return;
117
+ settled = true;
118
+ clearTimeout(timer);
119
+ resolve(r);
120
+ };
121
+ let child;
122
+ // execFile's own timeout kills the child, but its callback waits for the
123
+ // output pipes to close, which a grandchild can hold open: answer at the
124
+ // deadline whatever the pipes do.
125
+ const timer = setTimeout(() => {
126
+ child?.kill("SIGKILL");
127
+ finish({ timedOut: true });
128
+ }, timeout);
129
+ try {
130
+ child = execFile(cmd, args, { encoding: "utf8", timeout, killSignal: "SIGKILL", maxBuffer: 64 * 1024 * 1024, windowsHide: true }, (err, stdout) => {
131
+ if (err)
132
+ return finish({ timedOut: Boolean(err.killed) || Date.now() >= deadline });
133
+ finish({ out: typeof stdout === "string" && stdout.trim() ? stdout : undefined, timedOut: false });
134
+ });
135
+ child.on("error", () => finish({ timedOut: false }));
136
+ }
137
+ catch {
138
+ finish({ timedOut: false });
139
+ }
140
+ });
141
+ }
142
+ /**
143
+ * extractText for a server: asynchronous, and bounded by `deadline` (ms since
144
+ * the epoch) across every tool it tries. Past the deadline the reason says so.
145
+ */
146
+ export async function extractTextAsync(path, deadline = Date.now() + EXTRACT_BUDGET_MS) {
147
+ const ext = extname(path).toLowerCase();
148
+ const mac = process.platform === "darwin";
149
+ let text;
150
+ let timedOut = false;
151
+ const tryRun = async (cmd, args) => {
152
+ if (text || timedOut)
153
+ return;
154
+ const r = await runAsync(cmd, args, deadline);
155
+ if (r.timedOut)
156
+ timedOut = true;
157
+ else
158
+ text = r.out;
159
+ };
160
+ const late = () => ({ error: "not read: the time allowed for reading documents in this call ran out" });
161
+ if (ext === ".pdf") {
162
+ await tryRun("pdftotext", ["-enc", "UTF-8", path, "-"]);
163
+ await tryRun("pdftotext", [path, "-"]);
164
+ if (!text && !timedOut) {
165
+ const out = join(mkdtempSync(join(tmpdir(), "cd-pdf-")), "out.txt");
166
+ try {
167
+ const r = await runAsync("pdftotext", [path, out], deadline);
168
+ if (r.timedOut)
169
+ timedOut = true;
170
+ else if (existsSync(out))
171
+ text = readFileSync(out, "utf8").trim() ? readFileSync(out, "utf8") : undefined;
172
+ }
173
+ finally {
174
+ rmSync(dirname(out), { recursive: true, force: true });
175
+ }
176
+ }
177
+ text = text?.replace(/\f/g, "\n\n");
178
+ if (!text && mac)
179
+ await tryRun("osascript", ["-l", "JavaScript", "-e", PDFKIT_JXA, path]);
180
+ if (!text) {
181
+ if (timedOut)
182
+ return late();
183
+ return { error: mac ? "no text layer (scanned PDF?) or unreadable" : "needs pdftotext (install poppler-utils), or the PDF has no text layer" };
184
+ }
185
+ return { text };
186
+ }
187
+ if (mac && ext !== ".pptx")
188
+ await tryRun("textutil", [...TEXTUTIL_ARGS, path]);
189
+ if (!text && !timedOut) {
190
+ const members = ext === ".docx" ? ["word/document.xml"] : ext === ".pptx" ? ["ppt/slides/*.xml"] : ext === ".odt" ? ["content.xml"] : [];
191
+ if (members.length) {
192
+ const r = await runAsync("unzip", ["-p", path, ...members], deadline);
193
+ if (r.timedOut)
194
+ timedOut = true;
195
+ else if (r.out)
196
+ text = xmlToText(r.out);
197
+ }
198
+ }
199
+ if (!text) {
200
+ if (timedOut)
201
+ return late();
202
+ return { error: mac ? "unreadable document" : `needs unzip${ext === ".doc" || ext === ".rtf" ? " (and .doc/.rtf need macOS textutil; save as .docx)" : ""}` };
203
+ }
204
+ return { text };
205
+ }
@@ -0,0 +1,131 @@
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
+ /** The subagent tool, by its current name and its pre-2.1.63 alias. */
24
+ export declare const FANOUT_MATCHER = "Agent|Task";
25
+ export interface CostStat {
26
+ n: number;
27
+ median: number;
28
+ p90: number;
29
+ /** The model most of these ran on. */
30
+ model?: string;
31
+ }
32
+ export interface SubagentCosts {
33
+ computedAt: number;
34
+ days: number;
35
+ /** Subagents measured (each priced at list price, as `subagents` does). */
36
+ n: number;
37
+ all?: CostStat;
38
+ byType: Record<string, CostStat>;
39
+ /** "<type>|<model>" */
40
+ byTypeModel: Record<string, CostStat>;
41
+ byModel: Record<string, CostStat>;
42
+ }
43
+ export declare function subagentCostsPath(): string;
44
+ /**
45
+ * Each subagent's bill in the last `days`, newest transcripts first, by
46
+ * type and model. `limit` and `budgetMs` bound the work when the hook has
47
+ * to measure (the cache is a day old): the newest subagents are the best
48
+ * guide anyway.
49
+ */
50
+ export declare function measureSubagentCosts(days?: number, opts?: {
51
+ limit?: number;
52
+ budgetMs?: number;
53
+ sessions?: string[];
54
+ now?: number;
55
+ }): SubagentCosts;
56
+ export declare function saveSubagentCosts(c: SubagentCosts, path?: string): void;
57
+ /** The cached medians when under a day old, else measured now (bounded) and cached. */
58
+ export declare function subagentCosts(now?: number, path?: string): SubagentCosts | undefined;
59
+ export interface FanoutEstimate {
60
+ type: string;
61
+ model?: string;
62
+ median: number;
63
+ p90: number;
64
+ runs: number;
65
+ /** The Sonnet option, when the subagent would run on Opus or Fable. */
66
+ cheaper?: {
67
+ model: string;
68
+ median: number;
69
+ measured: boolean;
70
+ };
71
+ }
72
+ /** 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. */
73
+ export declare function pinnedModel(costs: SubagentCosts, type: string): string | undefined;
74
+ /** What a subagent of this type on this model costs, from the user's own runs. Undefined with too few. */
75
+ export declare function estimateSubagent(costs: SubagentCosts, type: string, modelAlias?: string, parentModel?: string): FanoutEstimate | undefined;
76
+ /** PreToolUse input for the Agent tool, as far as this reads it. */
77
+ export interface FanoutInput {
78
+ session_id?: string;
79
+ transcript_path?: string;
80
+ tool_name?: string;
81
+ tool_input?: {
82
+ subagent_type?: unknown;
83
+ model?: unknown;
84
+ description?: unknown;
85
+ run_in_background?: unknown;
86
+ };
87
+ }
88
+ /**
89
+ * One launch, as the session's launch log records it. The log is appended
90
+ * to before it is read, so hooks that run at once for a fan-out (one per
91
+ * subagent) each see the launches before their own and decide alone:
92
+ * exactly one is the first of its type, the third is the burst. A shared
93
+ * state file read and written back by each would lose all but one write.
94
+ */
95
+ export interface SpawnLine {
96
+ t: number;
97
+ type: string;
98
+ /** Unique per launch. */
99
+ id: string;
100
+ /** This launch was quoted a cheaper model (the model gets one note, on the first such launch). */
101
+ c: boolean;
102
+ }
103
+ /** The session's launch log, beside the hook's per-session state. */
104
+ export declare function spawnLogPath(sessionId: string): string;
105
+ /** Append this launch, then read the log back (its last 64 KB: hundreds of launches). */
106
+ export declare function recordSpawn(path: string, line: SpawnLine): SpawnLine[];
107
+ /** What a launch's input says: its type and the model alias it asks for. */
108
+ export declare function launchOf(input: FanoutInput): {
109
+ type: string;
110
+ alias?: string;
111
+ } | undefined;
112
+ /**
113
+ * What to say before this launch, from the session's launch log (this one
114
+ * included, as `own`). The user sees the price on the first launch of a type
115
+ * in the session and when launches bunch up (3 within two minutes, then
116
+ * every 5th); the model gets one short note a session, on the first launch
117
+ * that was quoted a cheaper model.
118
+ */
119
+ export declare function fanoutMessage(est: FanoutEstimate | undefined, alias: string | undefined, log: SpawnLine[], own: SpawnLine): {
120
+ systemMessage?: string;
121
+ additionalContext?: string;
122
+ };
123
+ /** The whole PreToolUse answer: estimate, log, decide. Silent (an empty object) for anything else. */
124
+ export declare function fanoutHook(input: FanoutInput, costs: SubagentCosts | undefined, sessionId: string, now?: number): {
125
+ systemMessage?: string;
126
+ additionalContext?: string;
127
+ };
128
+ /** For `doctor` and the docs: where the medians come from. */
129
+ export declare function describeCosts(c: SubagentCosts | undefined): string;
130
+ /** The medians the subagent price quotes, for `context-doctor subagents`. */
131
+ export declare function renderCostMedians(c: SubagentCosts): string[];