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/dist/pack.d.ts CHANGED
@@ -118,6 +118,15 @@ export interface ReadSourcesOptions {
118
118
  includeSecrets?: boolean;
119
119
  /** How the caller can opt in, appended to a "secret, skipped" note. */
120
120
  secretsHint?: string;
121
+ /**
122
+ * Internal (readSourcesAsync): instead of extracting a PDF or office file
123
+ * on the spot, reserve its slot and list it here for asynchronous
124
+ * extraction under a time budget.
125
+ */
126
+ defer?: Array<{
127
+ slot: number;
128
+ path: string;
129
+ }>;
121
130
  }
122
131
  /**
123
132
  * Read files and directories (recursively, skipping build and dependency
@@ -138,3 +147,14 @@ export declare function readSources(paths: string[], cwdOrOptions?: string | Rea
138
147
  sources: PackSource[];
139
148
  skipped: string[];
140
149
  };
150
+ /**
151
+ * readSources for a server: the same walk, with PDFs and office documents
152
+ * extracted asynchronously and all of them within one time budget, so a slow
153
+ * or hostile document neither blocks the event loop nor holds the call.
154
+ */
155
+ export declare function readSourcesAsync(paths: string[], options?: Omit<ReadSourcesOptions, "defer"> & {
156
+ budgetMs?: number;
157
+ }): Promise<{
158
+ sources: PackSource[];
159
+ skipped: string[];
160
+ }>;
package/dist/pack.js CHANGED
@@ -18,7 +18,7 @@ import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync, statSyn
18
18
  import { homedir } from "node:os";
19
19
  import { basename, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
20
20
  import { estimateTokens, formatTokens } from "./tokens.js";
21
- import { EXTRACTABLE, extractText } from "./extract.js";
21
+ import { EXTRACT_BUDGET_MS, EXTRACTABLE, extractText, extractTextAsync } from "./extract.js";
22
22
  const DEFAULT_BUDGET = 4000;
23
23
  const DEFAULT_CHUNK_TOKENS = 400;
24
24
  /** Claude's tokenizer produces the most tokens per char; a budget in its terms never overruns another's. */
@@ -590,6 +590,13 @@ export function readSources(paths, cwdOrOptions = process.cwd()) {
590
590
  const rel = relative(cwd, p);
591
591
  const name = rel && !rel.startsWith("..") ? rel : p;
592
592
  if (EXTRACTABLE.has(extname(p).toLowerCase())) {
593
+ if (options.defer) {
594
+ bytes += st.size;
595
+ seen.add(real);
596
+ sources.push({ name, text: "" });
597
+ options.defer.push({ slot: sources.length - 1, path: p });
598
+ return;
599
+ }
593
600
  const got = extractText(p);
594
601
  if ("error" in got)
595
602
  skipped.push(`${p}: ${got.error}`);
@@ -631,3 +638,24 @@ export function readSources(paths, cwdOrOptions = process.cwd()) {
631
638
  }
632
639
  return { sources, skipped };
633
640
  }
641
+ /**
642
+ * readSources for a server: the same walk, with PDFs and office documents
643
+ * extracted asynchronously and all of them within one time budget, so a slow
644
+ * or hostile document neither blocks the event loop nor holds the call.
645
+ */
646
+ export async function readSourcesAsync(paths, options = {}) {
647
+ const defer = [];
648
+ const { sources, skipped } = readSources(paths, { ...options, defer });
649
+ const deadline = Date.now() + (options.budgetMs ?? EXTRACT_BUDGET_MS);
650
+ const failed = new Set();
651
+ for (const d of defer) {
652
+ const got = await extractTextAsync(d.path, deadline);
653
+ if ("error" in got) {
654
+ skipped.push(`${d.path}: ${got.error}`);
655
+ failed.add(d.slot);
656
+ }
657
+ else
658
+ sources[d.slot].text = got.text;
659
+ }
660
+ return { sources: sources.filter((_, i) => !failed.has(i)), skipped };
661
+ }
@@ -4,7 +4,9 @@
4
4
  * "custom instructions" are read on every turn of every chat, which is the
5
5
  * closest thing those surfaces have to a UserPromptSubmit hook.
6
6
  *
7
- * Kept short (~185 Claude tokens, ~125 GPT): it rides in every conversation.
7
+ * Kept short (~190 Claude tokens, ~125 GPT): it rides in every conversation.
8
+ * The handoff is the one real cut a chat app allows: its history cannot be
9
+ * edited, so a long chat continues in a new one from a short brief.
8
10
  */
9
11
  export declare const CHAT_PREFERENCES: string;
10
12
  /** Where to paste, per app. Paths are the UI labels, not URLs, so they survive redesigns. */
@@ -4,15 +4,17 @@
4
4
  * "custom instructions" are read on every turn of every chat, which is the
5
5
  * closest thing those surfaces have to a UserPromptSubmit hook.
6
6
  *
7
- * Kept short (~185 Claude tokens, ~125 GPT): it rides in every conversation.
7
+ * Kept short (~190 Claude tokens, ~125 GPT): it rides in every conversation.
8
+ * The handoff is the one real cut a chat app allows: its history cannot be
9
+ * edited, so a long chat continues in a new one from a short brief.
8
10
  */
9
11
  import { spawnSync } from "node:child_process";
10
12
  export const CHAT_PREFERENCES = [
11
- "Context hygiene: when I paste something long, summarize it into the points you will use and work from that;",
12
- "do not carry it verbatim or re-quote it later, refer to it by name. Never inline base64.",
13
- "Once, when a chat first passes ~30 turns, and whenever I ask about tokens, limits, cost or speed: if a profile_context",
14
- "tool exists, call it with a sketch before answering and act on its top finding; otherwise offer me a 300-token",
15
- "handoff summary (decisions, current state, open items) to start a fresh chat.",
13
+ "Context hygiene: summarize anything long I paste into the points you will use; refer to it by name, never re-quote it,",
14
+ "never inline base64. When I ask about tokens, limits, cost or speed, and once past ~30 turns: if profile_context exists,",
15
+ "call it with a sketch and act on its top finding. When a chat grows long, offer a handoff once (its history cannot",
16
+ "be trimmed): a 400-token brief of goal, decisions, state and open items, plus what must stay exact, saved with",
17
+ "save_handoff if it exists, to start a new chat.",
16
18
  ].join(" ");
17
19
  /** Where to paste, per app. Paths are the UI labels, not URLs, so they survive redesigns. */
18
20
  export const PREFERENCE_TARGETS = [
package/dist/proxy.d.ts CHANGED
@@ -65,7 +65,7 @@ export interface ProxyOptions extends OptimizeOptions {
65
65
  /** Default request body cap: far above any real request (a 1M-token context is ~4 MB of JSON, images aside). */
66
66
  export declare const DEFAULT_MAX_BODY_BYTES: number;
67
67
  /** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
68
- export declare const PROXY_VERSION = "0.36.0";
68
+ export declare const PROXY_VERSION = "0.37.0";
69
69
  /**
70
70
  * Remove a leading `/t/<token>` from a request path, or return undefined when
71
71
  * the prefix is absent or the token differs. The comparison is constant time
package/dist/proxy.js CHANGED
@@ -24,7 +24,7 @@ import { withPromptCacheKey } from "./cachekey.js";
24
24
  /** Default request body cap: far above any real request (a 1M-token context is ~4 MB of JSON, images aside). */
25
25
  export const DEFAULT_MAX_BODY_BYTES = 100 * 1024 * 1024;
26
26
  /** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
27
- export const PROXY_VERSION = "0.36.0";
27
+ export const PROXY_VERSION = "0.37.0";
28
28
  /** Connection-level headers that must not be forwarded. */
29
29
  const SKIP_REQUEST_HEADERS = new Set(["host", "content-length", "connection", "transfer-encoding", "accept-encoding", "expect"]);
30
30
  const SKIP_RESPONSE_HEADERS = new Set(["content-length", "content-encoding", "transfer-encoding", "connection"]);
package/dist/rules.d.ts CHANGED
@@ -9,8 +9,11 @@
9
9
  */
10
10
  /**
11
11
  * The standing rules every chat gets. ChatGPT's MCP guide says to keep the
12
- * most important details in the first 512 characters, so rules 1-3 (when to
13
- * measure, and the two habits) end before character 512; the two that need
14
- * a particular tool come after.
12
+ * most important details in the first 512 characters, so rules 1-4 (when to
13
+ * measure, the handoff, and the two habits) end exactly at character 512: a
14
+ * client that keeps only that much gets whole rules, none cut mid-sentence
15
+ * (mcp-http.test.ts pins the boundary). The two that need a particular tool
16
+ * come after. Rule 2 is the only real cut a chat app allows: its history
17
+ * cannot be edited, so a long chat moves to a new one (save_handoff).
15
18
  */
16
- export declare const SERVER_INSTRUCTIONS = "Context hygiene rules (always on):\n1. 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.\n2. Summarize any paste or tool result over ~2k tokens into the points you need; keep it verbatim only to edit or quote it exactly.\n3. Refer to earlier content by name; never re-quote it or inline base64.\n4. To answer from a big file or folder you won't edit, call pack_context with the question; don't read it whole.\n5. If optimize_context returns a pruned-turns digest, write its \u2264150-token summary.";
19
+ export declare const SERVER_INSTRUCTIONS = "Context hygiene rules (always on):\n1. 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.\n2. When a chat grows long, offer a handoff once (save_handoff): only a new chat cuts its history.\n3. Summarize any paste or tool result over ~2k tokens into the points you need.\n4. Refer to earlier content by name; never re-quote it or inline base64.\n5. For a big file you won't edit, call pack_context with the question; don't read it whole.\n6. If optimize_context returns a pruned-turns digest, write its \u2264150-token summary.";
package/dist/rules.js CHANGED
@@ -18,13 +18,17 @@
18
18
  // than it saves.
19
19
  /**
20
20
  * The standing rules every chat gets. ChatGPT's MCP guide says to keep the
21
- * most important details in the first 512 characters, so rules 1-3 (when to
22
- * measure, and the two habits) end before character 512; the two that need
23
- * a particular tool come after.
21
+ * most important details in the first 512 characters, so rules 1-4 (when to
22
+ * measure, the handoff, and the two habits) end exactly at character 512: a
23
+ * client that keeps only that much gets whole rules, none cut mid-sentence
24
+ * (mcp-http.test.ts pins the boundary). The two that need a particular tool
25
+ * come after. Rule 2 is the only real cut a chat app allows: its history
26
+ * cannot be edited, so a long chat moves to a new one (save_handoff).
24
27
  */
25
28
  export const SERVER_INSTRUCTIONS = `Context hygiene rules (always on):
26
- 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.
27
- 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.
28
- 3. Refer to earlier content by name; never re-quote it or inline base64.
29
- 4. To answer from a big file or folder you won't edit, call pack_context with the question; don't read it whole.
30
- 5. If optimize_context returns a pruned-turns digest, write its ≤150-token summary.`;
29
+ 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.
30
+ 2. When a chat grows long, offer a handoff once (save_handoff): only a new chat cuts its history.
31
+ 3. Summarize any paste or tool result over ~2k tokens into the points you need.
32
+ 4. Refer to earlier content by name; never re-quote it or inline base64.
33
+ 5. For a big file you won't edit, call pack_context with the question; don't read it whole.
34
+ 6. If optimize_context returns a pruned-turns digest, write its ≤150-token summary.`;
package/dist/sketch.d.ts CHANGED
@@ -61,5 +61,9 @@ export declare function exchangeTokens(model?: string): number;
61
61
  export declare const MAX_LABEL_CHARS = 60;
62
62
  export declare function profileSketch(sketch: ConversationSketch): SketchProfile;
63
63
  export declare function renderSketchProfile(p: SketchProfile): string;
64
- /** Profile a sketch, log it to the ledger like a hook check, and render. */
64
+ /** Profile a sketch and log it to the ledger like a hook check (unless `record` is false: the HTTP server). */
65
+ export declare function runSketchProfile(sketch: ConversationSketch, { record }?: {
66
+ record?: boolean;
67
+ }): SketchProfile;
68
+ /** Profile a sketch, log it, and render. */
65
69
  export declare function runSketch(sketch: ConversationSketch): string;
package/dist/sketch.js CHANGED
@@ -43,7 +43,10 @@ const DEFAULT_CHARS = {
43
43
  const IMAGE_TOKENS = 1500;
44
44
  const LARGE_BLOCK_TOKENS = 2000;
45
45
  const LONG_HISTORY_TURNS = 30;
46
- const HANDOFF_SUMMARY_TOKENS = 300;
46
+ // The handoff brief's target size (save_handoff, the `handoff` prompt).
47
+ const HANDOFF_SUMMARY_TOKENS = 400;
48
+ // Below this, a new chat is not worth the user's trouble.
49
+ const HANDOFF_WORTH_TOKENS = 10_000;
47
50
  const RECENT_TURNS_KEPT = 6;
48
51
  /** Code, tool output and base64 tokenize at the code ratio; pastes and text at the prose ratio. */
49
52
  function ratioFor(kind, model) {
@@ -137,7 +140,7 @@ export function profileSketch(sketch) {
137
140
  severity: totalTokens > 100_000 ? "high" : "warn",
138
141
  estSavings: Math.max(0, totalTokens - afterHandoff),
139
142
  message: `${turns} turns: every new message re-reads ~${formatTokens(totalTokens)}.`,
140
- action: `Offer a handoff: write a ≤${HANDOFF_SUMMARY_TOKENS}-token summary (decisions, current state, open items, key identifiers) for the user to start a new chat with. A fresh chat re-reads ~${formatTokens(afterHandoff)} of conversation instead, plus the app's own system prompt, which every chat carries.`,
143
+ action: `Offer a handoff once: with the user's agreement, write a ≤${HANDOFF_SUMMARY_TOKENS}-token brief (goal, decisions, current state, open items, key identifiers) and call save_handoff, or the user picks the \`handoff\` prompt. A new chat re-reads ~${formatTokens(afterHandoff)} of conversation instead, plus the app's own system prompt, which every chat carries.`,
141
144
  });
142
145
  }
143
146
  const contextWindow = contextWindowFor(sketch.model);
@@ -182,21 +185,34 @@ export function renderSketchProfile(p) {
182
185
  return lines.join("\n");
183
186
  }
184
187
  lines.push("");
185
- lines.push(`Findings (recoverable ~${formatTokens(p.totalEstSavings)} tokens):`);
188
+ // A chat app's history cannot be edited: summarizing a block stops it being
189
+ // quoted again, but the block is still re-read on every turn. Saying
190
+ // "recoverable" without that sent models to promise savings that never came.
191
+ lines.push(`Findings (recoverable ~${formatTokens(p.totalEstSavings)} tokens, but only in a new chat: a chat app's history cannot be edited):`);
186
192
  p.findings.forEach((f, i) => {
187
193
  const save = f.estSavings > 0 ? ` [~${formatTokens(f.estSavings)}]` : "";
188
194
  lines.push(`${i + 1}. ${f.severity.toUpperCase()}${save} ${f.message}`);
189
195
  lines.push(` → ${f.action}`);
190
196
  });
191
197
  lines.push("");
192
- lines.push("Act on #1 in your reply (do it, do not just suggest it), and tell the user in one line what you dropped and roughly what it saves per turn.");
198
+ lines.push("Act on #1 in your reply (do it, do not just suggest it): work from your summary and refer to blocks by name from now on, which stops this chat growing; tell the user in one line what you summarized. What is already here stays until a new chat.");
199
+ const handoffOffered = p.findings.some((f) => f.id === "long_history");
200
+ if (!handoffOffered && p.totalEstSavings >= HANDOFF_WORTH_TOKENS) {
201
+ lines.push(`To recover the ~${formatTokens(p.totalEstSavings)}: offer a handoff once. With the user's agreement, call save_handoff (a ≤${HANDOFF_SUMMARY_TOKENS}-token brief plus the blocks that must stay exact); a new chat starts from that.`);
202
+ }
193
203
  return lines.join("\n");
194
204
  }
195
- /** Profile a sketch, log it to the ledger like a hook check, and render. */
196
- export function runSketch(sketch) {
205
+ /** Profile a sketch and log it to the ledger like a hook check (unless `record` is false: the HTTP server). */
206
+ export function runSketchProfile(sketch, { record = true } = {}) {
197
207
  const profile = profileSketch(sketch);
208
+ if (!record)
209
+ return profile;
198
210
  // No session id: each sketch describes a different chat, and a shared id made
199
211
  // the dashboard read "big sketch, then a smaller one" as tokens saved.
200
212
  recordLedger({ ev: "check", src: "mcp", tok: profile.totalTokens, warn: profile.findings.some((f) => f.severity !== "info"), model: sketch.model });
201
- return renderSketchProfile(profile);
213
+ return profile;
214
+ }
215
+ /** Profile a sketch, log it, and render. */
216
+ export function runSketch(sketch) {
217
+ return renderSketchProfile(runSketchProfile(sketch));
202
218
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "context-doctor",
3
- "version": "0.36.0",
3
+ "version": "0.37.0",
4
4
  "description": "Context and token optimizer for LLM agents: see where Claude Code, Cursor, Codex and Gemini CLI tokens go, then cut them: an every-prompt hook, smarter compaction, an autopilot proxy that edits history only when the prompt cache is cold, RAG chunk packing and an MCP server. Local, no API key. By gAI Ventures.",
5
5
  "keywords": [
6
6
  "agent",
@@ -22,11 +22,13 @@ Proactively (do not wait to be asked):
22
22
  - Summarize large tool outputs right after consuming them.
23
23
  - Once, when the session first passes roughly 30 turns or contains several large pastes, offer: "This conversation is getting heavy — want me to compact the older history into a summary so responses stay fast and cheap?"
24
24
  - When asked to summarize/compact, produce a dense factual summary (decisions made, current state, open items, key identifiers) — not a narrative.
25
+ - In a chat app (claude.ai, Claude Desktop, ChatGPT) the history cannot be edited: a summary stops further re-quoting, but the old turns are still re-read on every turn. The real cut is a new chat, so offer a **handoff** once instead: a ≤400-token brief (goal, decisions, current state, open items, key identifiers) plus only the blocks that must stay exact, saved with `save_handoff` when it is available, for the user to start a new chat from.
25
26
 
26
27
  ## Using the context-doctor tools
27
28
 
28
29
  If the `context-doctor` MCP tools are available:
29
30
  - `profile_context` — pass a conversation JSON (OpenAI or Anthropic format) or raw text; returns a token breakdown, largest messages, findings with estimated savings. In a chat app, where you cannot export the conversation, pass a `sketch` instead: the turn count plus the large, repeated or image blocks, one size hint each (~120 tokens to write).
31
+ - `save_handoff` — stores the handoff brief you wrote and the exact blocks, masks secret-looking strings, and returns the per-turn saving and how to continue (attach `handoff://latest` in a new chat, or paste it). Call it only when the user agrees.
30
32
  - `optimize_context` — applies deterministic fixes (dedupe, trim stale tool results, strip base64; opt-in `trim-tool-calls` for big inline file writes and `prune-history`). When the result contains pruned-turn source material and asks for a summary, **you write that summary** (≤150 tokens, dense, factual) and place it where the stub indicates — this is how summarization works without any API key.
31
33
  - `pack_context` — before reading a large document, log or folder to answer a question (not to edit it), pass `paths` and the `query`: it returns only the best-matching chunks within `max_tokens` (default 4000), each with an id and line range, plus the next-best ids. No query = an outline to pick from with `ids`.
32
34
  - `context_best_practices` — provider-specific checklist to share with the user.