context-doctor 0.36.0 → 0.37.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 CHANGED
@@ -100,21 +100,24 @@ On a Claude subscription you do not pay list price; the same tokens come out of
100
100
  | **Cursor** (agent) | A native **after-tool-call hook** (`~/.cursor/hooks.json`): in a heavy chat the agent gets the same hygiene guidance and the largest waste, once per 40% of growth. (Cursor's prompt hook can only allow or block a prompt, so this is the event where guidance reaches the model) | MCP tools, editor status bar extension, `cursor` profiler. With your own OpenAI key, autopilot too via a tokened tunnel ([how](./docs/proxy.md#putting-the-proxy-on-a-public-url-cursor-with-your-own-openai-key-remote-apps)) |
101
101
  | **Codex** (ChatGPT app's Codex tab, IDE extension, CLI) | Every-prompt hook with the API's own token counts | MCP tools, skill, `session` reads Codex rollouts. On an API key, autopilot too (`autopilot on` sets `openai_base_url` in `~/.codex/config.toml`; Codex no longer reads `OPENAI_BASE_URL`) |
102
102
  | **Gemini CLI** | Every-prompt hook (`BeforeAgent`) with the API's own token counts. On an API key, autopilot too: `GOOGLE_GEMINI_BASE_URL=http://127.0.0.1:8787` (Google sign-in traffic goes elsewhere) | MCP tools, `session` and `watch` read its chats, `overhead` sizes GEMINI.md |
103
- | **GitHub Copilot** (Copilot CLI, the Copilot app, VS Code agent sessions) | A **session-start hook** (`~/.copilot/hooks/context-doctor.json`) gives every new or resumed session the five standing rules. No size check: Copilot passes a transcript only to hooks that cannot add context | MCP tools (`~/.copilot/mcp-config.json`, which VS Code's Copilot sessions read too) |
103
+ | **GitHub Copilot** (Copilot CLI, the Copilot app, VS Code agent sessions) | A **session-start hook** (`~/.copilot/hooks/context-doctor.json`) gives every new or resumed session the standing rules. No size check: Copilot passes a transcript only to hooks that cannot add context | MCP tools (`~/.copilot/mcp-config.json`, which VS Code's Copilot sessions read too) |
104
104
  | **Your own apps on the Anthropic, OpenAI or Gemini API** | Autopilot on `/v1/messages`, `/v1/chat/completions`, `/v1/responses` and Gemini's `generateContent` (`ANTHROPIC_BASE_URL` / `OPENAI_BASE_URL` / `GOOGLE_GEMINI_BASE_URL`), or the optimizing proxy (which can cost more on cached traffic); no proxy possible (serverless, edge)? `withContextDoctor(client)` runs autopilot inside the SDK client | Exact usage and cache hit rates in `/stats`, prompt-cache placement advice ([proxy](./docs/proxy.md)) |
105
- | **Claude Desktop chat** | The five standing rules below in every chat; one cheap `profile_context` call the model makes once at ~30 turns and on any cost question; `pack_context` instead of reading a big local file whole | One-click `.mcpb` install, `context_checkup` prompt ([chat apps](./docs/chat-apps.md)) |
105
+ | **Claude Desktop chat** | The six standing rules below, sent to every chat (whether classic Chat shows them to the model is unverified, [why](./docs/chat-apps.md)); one cheap `profile_context` call the model makes once at ~30 turns and on any cost question; `pack_context` instead of reading a big local file whole; a handoff offered once a chat is long, since a chat's history cannot be cut and a new chat can | One-click `.mcpb` install, `context_checkup`, `handoff` and `ask_file` prompts, `handoff://latest` to attach in the next chat ([handoff](./docs/handoff.md)) |
106
106
  | **claude.ai, ChatGPT, the phone apps** | Your account's standing preferences, pasted once ([Quick start](#quick-start)) | Profile an exported chat with `analyze` or `session` |
107
107
  | **CI** | `analyze --fail-over-budget` fails a build whose prompts outgrow a budget; the GitHub Action gates memory-file growth | `.contextdoctorrc` budgets and presets ([CI](./docs/ci.md)) |
108
108
 
109
109
  Not claimed, because no process on your machine sends those requests: trimming inside Claude Desktop chat, claude.ai, ChatGPT, Cursor's own subscription models, or Codex signed in with ChatGPT. Those get the rules and the measurements above, not autopilot.
110
110
 
111
- The MCP server hands these standing rules, verbatim, to every chat where it is enabled (Claude Desktop, Cursor and Claude Code put them in front of the model):
111
+ The MCP server hands these standing rules, verbatim, to every chat where it is enabled (Cursor and Claude Code put them in front of the model; for Claude Desktop's classic Chat that is [unverified](./docs/chat-apps.md)):
112
112
 
113
- > 1. When asked about tokens, cost, speed or limits, and once at ~30 turns or 3+ large pastes: call profile_context BEFORE answering; act on its top finding. In a chat app pass a `sketch` (turns + big blocks). Do not estimate token counts yourself.
114
- > 2. Summarize any paste or tool result over ~2k tokens into the points you need; keep it verbatim only to edit or quote it exactly.
115
- > 3. Refer to earlier content by name; never re-quote it or inline base64.
116
- > 4. To answer from a big file or folder you won't edit, call pack_context with the question; don't read it whole.
117
- > 5. If optimize_context returns a pruned-turns digest, write its ≤150-token summary.
113
+ > 1. When asked about tokens, cost, speed or limits, and once at ~30 turns or 3+ large pastes: call profile_context BEFORE answering; in a chat app pass a `sketch`. Act on its top finding. Do not estimate token counts yourself.
114
+ > 2. When a chat grows long, offer a handoff once (save_handoff): only a new chat cuts its history.
115
+ > 3. Summarize any paste or tool result over ~2k tokens into the points you need.
116
+ > 4. Refer to earlier content by name; never re-quote it or inline base64.
117
+ > 5. For a big file you won't edit, call pack_context with the question; don't read it whole.
118
+ > 6. If optimize_context returns a pruned-turns digest, write its ≤150-token summary.
119
+
120
+ Rules 1-4 end exactly at character 512, the part ChatGPT's guide says must stand alone.
118
121
 
119
122
  ## Commands
120
123
 
@@ -126,9 +129,10 @@ The MCP server hands these standing rules, verbatim, to every chat where it is e
126
129
  | `context-doctor autopilot on\|off\|pause\|resume\|status` | Every new Claude Code session started in a terminal or IDE goes through the local proxy, which clears stale tool output only when the prompt cache is cold: measured 12.7% less input cost, no session worse ([details](./docs/autopilot.md)) |
127
130
  | `context-doctor proxy --autopilot` | Local proxy for your own Anthropic, OpenAI and Gemini API apps: clears stale tool output only when the prompt cache is cold, so it never costs more. Plain `proxy` runs the optimizing strategies (dedupe, trim, strip base64), which can cost more on cached traffic. `--token` for a public URL; `/stats` for cumulative savings ([details](./docs/proxy.md)) |
128
131
  | `context-doctor compact-window [status\|off\|<size>]` | Replay your last 30 days at auto-compact windows from 200k to 800k: input cost, saving, and how many more compactions each means. `400k` (or `250000`, `0.4m`) sets Claude Code's `autoCompactWindow`, with a backup; `off` removes it. Works in every Claude Code surface, the desktop app included |
129
- | `context-doctor instructions [--copy]` | The ~185-token standing rules (~125 on GPT) for claude.ai / ChatGPT preferences, for web and phones where no server runs |
132
+ | `context-doctor instructions [--copy]` | The ~190-token standing rules (~130 on GPT) for claude.ai / ChatGPT preferences, for web and phones where no server runs |
133
+ | `context-doctor handoff [list\|show <id>\|latest] [--copy]` | Handoffs saved from chat apps (the `handoff` prompt or `save_handoff`): list them, print one, or copy it to paste as a new chat's first message ([handoff](./docs/handoff.md)) |
130
134
  | `context-doctor mcp [--http]` | The MCP server as a subcommand, for clients and registries that launch `npx -y context-doctor mcp` |
131
- | `context-doctor-mcp` | The MCP server itself — stdio by default (what the installer wires); `--http [--port 8808] [--host H]` serves streamable HTTP at `/mcp` for URL-based clients like ChatGPT developer-mode connectors |
135
+ | `context-doctor-mcp` | The MCP server itself — stdio by default (what the installer wires); `--http [--port 8808] [--host H] [--allowed-hosts names] [--store-handoffs]` serves streamable HTTP at `/mcp` for URL-based clients like ChatGPT developer-mode connectors (only for the host names it knows: behind a tunnel, pass its name to `--allowed-hosts`) |
132
136
  | `context-doctor session [file]` | Profile a Claude Code session: live context, findings, **measured tokens and prompt-cache economics**, **where the wall clock went** per tool, and **what its subagents cost** (their own windows, your bill; never in the parent's profile). Also reads Codex rollouts, Gemini CLI chats and ChatGPT data exports (`conversations.json`); `--list` to browse |
133
137
  | `context-doctor watch [file]` | Live monitor of a growing session transcript or agent trace (Claude Code / Codex JSONL, or a plain OpenAI/Anthropic conversation JSON file): token/cost line per change, findings as they appear |
134
138
  | `context-doctor cursor [--list]` | Profile a chat from Cursor's local history (both storage formats) |
@@ -159,8 +163,8 @@ The MCP server hands these standing rules, verbatim, to every chat where it is e
159
163
 
160
164
  ## What's new
161
165
 
166
+ - **0.37 Desktop chat apps: a handoff, uploads, compact results, and a security pass**: a chat app's history cannot be edited, so the `handoff` prompt (Claude Desktop's **+** menu) has the model write a ≤400-token brief and save it with `save_handoff` (secrets masked, `handoff://latest` to attach in the next chat, the per-turn saving reported: a 52k-token chat drops to ~600). `ask_file` answers from a big file through `pack_context`, which over `--http` also takes ChatGPT uploads; ChatGPT gets compact results. An independent QA pass's eleven findings were fixed with tests; **behind a tunnel, `--http` now needs `--allowed-hosts <tunnel host>`** ([handoff](./docs/handoff.md)).
162
167
  - **0.36 GitHub Copilot, and a quality test for every lever**: `install` wires GitHub Copilot (CLI, app, VS Code agent sessions): the MCP server, and a session-start hook that gives each new or resumed session the standing rules (no size check: Copilot gives no transcript to the hooks that could add context). `context-doctor ab` runs eight small coding tasks, scored by hidden checks, with and without each lever (the standing rules, autopilot's clearing, `pack_context`, the PreCompact instructions) through the Messages API and puts pass counts, tokens and cost side by side; it bills your key, prints the estimate first, sends nothing without `--yes` and never passes `--budget` ([details](./docs/ab.md)). Not yet run on a real key, so no pass rates are claimed.
163
- - **0.35 Cache misses, a price before a model switch, and a QA pass fixed**: `context-doctor cache-misses` finds requests that re-wrote the prompt cache while it was still warm (on the author's history: 390 such misses, $1,925 above the cache-read price, 28% of all cache writes; claude-sonnet-5 missed on 10.4% of warm requests, claude-opus-5-5 on 0.11%) and says which model versions miss less; `savings` mentions them when they add up. On Claude Code 2.1.251+ a `PreModelSwitch` hook shows what a `/model` switch will cost before it happens. `pack` no longer reads `.env`, `.npmrc`, private keys or other credential files unless you pass `--include-secrets`, refuses `~/.ssh`-style folders, and survives unreadable files. Fixed from a QA pass: rc values warned as ignored were applied, near-duplicates were counted per pair (781 findings), autopilot's cleared results leaked between conversations reusing tool ids, a malformed config stopped `uninstall` midway, and more ([list](./ROADMAP.md#shipped-in-0350-cache-misses-a-model-switch-price-and-a-qa-pass)).
164
168
 
165
169
  Every release: [docs/whats-new.md](./docs/whats-new.md).
166
170
 
package/dist/cli.js CHANGED
@@ -55,6 +55,7 @@ import { planCache, renderCachePlan } from "./cacheplan.js";
55
55
  import { cacheMisses, cacheMissesLine, cacheMissesSignificant, renderCacheMisses } from "./cachemisses.js";
56
56
  import { renderPayback, subagentPayback } from "./subagentpay.js";
57
57
  import { compactionQuality, renderCompactionQuality } from "./compactquality.js";
58
+ import { isHandoffId, listHandoffs, readHandoff, renderHandoffList, stripControls } from "./handoff.js";
58
59
  const HELP = `context-doctor — profile and optimize LLM context windows
59
60
 
60
61
  Start here:
@@ -151,6 +152,10 @@ Fix on request:
151
152
  Where an Anthropic request should carry cache_control,
152
153
  what it saves over n calls; --out writes it applied
153
154
  (top-level automatic caching unless --explicit)
155
+ context-doctor handoff [list|show <id>|latest] [--copy]
156
+ Handoffs saved from chat apps (the \`handoff\` prompt or
157
+ save_handoff): list them, print one, or --copy it to
158
+ paste as the first message of a new chat
154
159
 
155
160
  Integrations:
156
161
  context-doctor ci [--base <ref>] [--max-tokens n] [--max-increase n] [--markdown]
@@ -269,7 +274,7 @@ const COMMANDS = [
269
274
  "analyze", "optimize", "proxy", "install", "uninstall", "savings", "compact-window", "autopilot", "mcp",
270
275
  "instructions", "session", "cursor", "statusline", "hook", "report", "doctor", "dashboard", "init",
271
276
  "experiment", "diff", "accuracy", "overhead", "ci", "cache-plan", "compactions", "cache-misses", "subagents", "tasks",
272
- "reads", "pack", "watch", "ab", "help", "version",
277
+ "reads", "pack", "watch", "ab", "handoff", "help", "version",
273
278
  ];
274
279
  /** --strategy takes one of the optimizer's ids; a typo used to run nothing and report success. */
275
280
  function strategyArg(v) {
@@ -334,6 +339,9 @@ const FLAGS = [
334
339
  { names: ["--upstream-google"], value: "text", set: (a, v) => { a.upstreamGoogle = v; } },
335
340
  // Read by the MCP server itself: `mcp --http [--port n] [--host h]`.
336
341
  { names: ["--http"], set: () => { } },
342
+ { names: ["--store-handoffs"], set: () => { } },
343
+ { names: ["--allowed-hosts"], value: "text", set: () => { } },
344
+ { names: ["--allowed-origins"], value: "text", set: () => { } },
337
345
  ];
338
346
  const FLAG_BY_NAME = new Map(FLAGS.flatMap((f) => f.names.map((n) => [n, f])));
339
347
  const FLAG_NAMES = [...FLAG_BY_NAME.keys(), "--help", "--version"];
@@ -858,6 +866,47 @@ async function main() {
858
866
  }
859
867
  return;
860
868
  }
869
+ if (args.command === "handoff") {
870
+ // Read-only: handoffs are written by the MCP server's save_handoff.
871
+ const sub = args.file ?? "list";
872
+ if (sub === "list") {
873
+ const metas = listHandoffs();
874
+ console.log(args.json ? JSON.stringify(metas, null, 2) : renderHandoffList(metas));
875
+ return;
876
+ }
877
+ const id = sub === "show" ? args.positionals?.[1] : sub === "latest" || isHandoffId(sub) ? sub : undefined;
878
+ if (!id) {
879
+ console.error(sub === "show"
880
+ ? "Usage: context-doctor handoff show <id> (the ids are in `context-doctor handoff list`)."
881
+ : `Usage: context-doctor handoff [list | show <id> | latest] [--copy] [--json]; got "${sub}".`);
882
+ process.exitCode = 1;
883
+ return;
884
+ }
885
+ const h = readHandoff(id);
886
+ if (!h) {
887
+ console.error(id === "latest"
888
+ ? "No handoffs saved yet. In a long chat, pick the `handoff` prompt (Claude Desktop's + menu) or ask for a handoff."
889
+ : `No saved handoff "${id}". List them: ${selfCommand("handoff list")}`);
890
+ process.exitCode = 1;
891
+ return;
892
+ }
893
+ if (args.json) {
894
+ console.log(JSON.stringify({ ...h.meta, markdown: h.markdown }, null, 2));
895
+ return;
896
+ }
897
+ // Control characters out before anything reaches a terminal or the
898
+ // clipboard: a hand-edited or older file could carry escape sequences.
899
+ const markdown = stripControls(h.markdown);
900
+ if (args.copy) {
901
+ const copied = copyToClipboard(markdown);
902
+ console.log(copied
903
+ ? `Copied handoff ${h.meta.id} (~${formatTokens(h.meta.tokens)} tokens). Paste it as the first message of a new chat.`
904
+ : `No clipboard tool found; copy the handoff below by hand.\n\n${markdown}`);
905
+ return;
906
+ }
907
+ process.stdout.write(markdown);
908
+ return;
909
+ }
861
910
  if (args.command === "instructions") {
862
911
  console.log(renderPreferences(args.copy ? copyToClipboard(CHAT_PREFERENCES) : undefined));
863
912
  return;
@@ -0,0 +1,36 @@
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 type { ContextProfile } from "./profile.js";
22
+ import type { SketchProfile } from "./sketch.js";
23
+ import type { PackResult } from "./pack.js";
24
+ export type ResultMode = "full" | "compact";
25
+ export interface CompactResult {
26
+ text: string;
27
+ structured: Record<string, unknown>;
28
+ meta: Record<string, unknown>;
29
+ }
30
+ export declare function resultMode(requestMeta: unknown, env?: NodeJS.ProcessEnv): ResultMode;
31
+ /** profile_context on a conversation. */
32
+ export declare function compactProfile(p: ContextProfile, fullText: string): CompactResult;
33
+ /** profile_context on a chat-app sketch. */
34
+ export declare function compactSketch(p: SketchProfile, fullText: string): CompactResult;
35
+ /** pack_context with no query: sections instead of one line per chunk. */
36
+ export declare function compactOutline(r: PackResult, fullText: string, maxSections?: number): CompactResult;
@@ -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
+ }
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,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
+ }>;