context-doctor 0.35.1 → 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.
@@ -0,0 +1,529 @@
1
+ /**
2
+ * Handoffs: the only real cut a chat app allows.
3
+ *
4
+ * In Claude Desktop, claude.ai and ChatGPT nothing can edit a chat's history:
5
+ * a model that summarizes a 30k paste stops quoting it, but the paste is
6
+ * still re-read on every turn. Moving to a new chat is the cut. A handoff is
7
+ * what the new chat starts from: a dense brief the HOST model writes in its
8
+ * own turn (goal, decisions, current state, open items, key identifiers; no
9
+ * API key here, the calling model does the language work) plus the few
10
+ * blocks that must stay exact (code, config, numbers).
11
+ *
12
+ * This module stores and reads them; it imports nothing from the MCP SDK so
13
+ * the CLI (`context-doctor handoff`) can use it too. Layout, one folder per
14
+ * handoff, under the home directory (os.homedir(), so a sandboxed HOME or
15
+ * USERPROFILE is respected):
16
+ *
17
+ * ~/.context-doctor/handoffs/<yyyymmdd-hhmmss>-<slug>/handoff.md
18
+ * ~/.context-doctor/handoffs/<yyyymmdd-hhmmss>-<slug>/meta.json
19
+ *
20
+ * Folders are 0700 and files 0600: a handoff holds chat content. Secret-looking
21
+ * strings are masked before anything is written, and the caller is told.
22
+ */
23
+ import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
24
+ import { homedir } from "node:os";
25
+ import { isAbsolute, join, relative, sep } from "node:path";
26
+ import { estimateTokens, formatTokens } from "./tokens.js";
27
+ import { formatUsd, inputCostUsd, pricingFor } from "./pricing.js";
28
+ import { exchangeTokens } from "./sketch.js";
29
+ /** Bounds on what a handoff may hold. The brief's target is ≤400 tokens; the cap is a hard stop. */
30
+ export const HANDOFF_LIMITS = {
31
+ briefTargetTokens: 400,
32
+ briefChars: 6_000,
33
+ titleChars: 80,
34
+ modelChars: 100,
35
+ blocks: 20,
36
+ labelChars: 80,
37
+ blockChars: 20_000,
38
+ totalChars: 60_000,
39
+ /** Newest handoffs kept on disk; older ones are removed when a new one is saved. */
40
+ kept: 100,
41
+ /** Largest handoff.md read back (a hand-edited file could be anything). */
42
+ readBytes: 512 * 1024,
43
+ };
44
+ /** ~/.context-doctor/handoffs, under whatever home this process has. */
45
+ export function handoffDir(home = homedir()) {
46
+ return join(home, ".context-doctor", "handoffs");
47
+ }
48
+ /** yyyymmdd-hhmmss-slug, optionally with a -n suffix for a second save in the same second. */
49
+ const ID_RE = /^\d{8}-\d{6}-[a-z0-9]+(?:-[a-z0-9]+)*$/;
50
+ export function isHandoffId(id) {
51
+ return typeof id === "string" && id.length <= 80 && ID_RE.test(id);
52
+ }
53
+ export function slugify(title) {
54
+ const s = title
55
+ .normalize("NFKD")
56
+ .replace(/[\u0300-\u036f]/g, "")
57
+ .toLowerCase()
58
+ .replace(/[^a-z0-9]+/g, "-")
59
+ .replace(/^-+|-+$/g, "")
60
+ .slice(0, 40)
61
+ .replace(/-+$/g, "");
62
+ return s || "handoff";
63
+ }
64
+ function stamp(d) {
65
+ const p = (n) => String(n).padStart(2, "0");
66
+ return `${d.getUTCFullYear()}${p(d.getUTCMonth() + 1)}${p(d.getUTCDate())}-${p(d.getUTCHours())}${p(d.getUTCMinutes())}${p(d.getUTCSeconds())}`;
67
+ }
68
+ /** Problems with an input, or an empty list. Enforced here too, not only by the MCP schema. */
69
+ export function validateHandoff(input) {
70
+ const errs = [];
71
+ const L = HANDOFF_LIMITS;
72
+ if (typeof input?.brief !== "string" || !input.brief.trim())
73
+ errs.push("`brief` is empty: write the handoff brief first.");
74
+ else if (input.brief.length > L.briefChars)
75
+ errs.push(`\`brief\` is ${input.brief.length} characters; the limit is ${L.briefChars} (aim for ≤${L.briefTargetTokens} tokens).`);
76
+ if (input.title !== undefined && (typeof input.title !== "string" || input.title.length > L.titleChars))
77
+ errs.push(`\`title\` must be a string of at most ${L.titleChars} characters.`);
78
+ const blocks = input.verbatim ?? [];
79
+ if (!Array.isArray(blocks))
80
+ errs.push("`verbatim` must be a list of {label, text}.");
81
+ else {
82
+ if (blocks.length > L.blocks)
83
+ errs.push(`${blocks.length} verbatim blocks; the limit is ${L.blocks}. Keep only what must stay exact.`);
84
+ let total = typeof input.brief === "string" ? input.brief.length : 0;
85
+ blocks.forEach((b, i) => {
86
+ if (typeof b?.label !== "string" || !b.label.trim() || b.label.length > L.labelChars)
87
+ errs.push(`verbatim[${i}].label must be 1-${L.labelChars} characters.`);
88
+ if (typeof b?.text !== "string" || !b.text.trim())
89
+ errs.push(`verbatim[${i}].text is empty.`);
90
+ else if (b.text.length > L.blockChars)
91
+ errs.push(`verbatim[${i}] ("${String(b.label).slice(0, 40)}") is ${b.text.length} characters; the limit is ${L.blockChars}. Summarize it, or keep only the exact lines needed.`);
92
+ else
93
+ total += b.text.length;
94
+ });
95
+ if (total > L.totalChars)
96
+ errs.push(`The handoff is ${total} characters; the limit is ${L.totalChars}. A handoff that big is not a cut.`);
97
+ }
98
+ if (input.model !== undefined && typeof input.model !== "string")
99
+ errs.push("`model` must be a string.");
100
+ for (const n of ["chatTokens", "turns"]) {
101
+ const v = input[n];
102
+ if (v !== undefined && (typeof v !== "number" || !Number.isFinite(v) || v < 0 || v > 100_000_000))
103
+ errs.push(`\`${n}\` must be a non-negative number.`);
104
+ }
105
+ return errs;
106
+ }
107
+ const MASK = "masked by context-doctor";
108
+ const whole = (kind, re, accept = () => true) => ({
109
+ kind,
110
+ re,
111
+ replace: (m) => (accept(m[0]) ? `[${kind.replace(/^an? /, "")} ${MASK}]` : undefined),
112
+ });
113
+ /** OpenAI keys mix cases and digits; `sk-spinner-wave-12345` (a CSS class) does not. */
114
+ const mixed = (t) => /[0-9]/.test(t) && /[A-Z]/.test(t) && /[a-z]/.test(t);
115
+ const SECRET_MASKERS = [
116
+ whole("a private key", /-----BEGIN [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----[\s\S]*?(?:-----END [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----|$)/g),
117
+ whole("an Anthropic key", /(?<![A-Za-z0-9_.-])sk-ant-[A-Za-z0-9_-]{20,}/g),
118
+ whole("an OpenAI key", /(?<![A-Za-z0-9_.-])sk-(?:proj-|svcacct-|admin-)?[A-Za-z0-9_-]{20,}/g, mixed),
119
+ whole("an AWS access key", /(?<![A-Za-z0-9])(?:AKIA|ASIA)[0-9A-Z]{16}(?![A-Za-z0-9])/g),
120
+ whole("a GitHub token", /(?<![A-Za-z0-9])(?:gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{22,})/g),
121
+ whole("a GitLab token", /(?<![A-Za-z0-9])glpat-[A-Za-z0-9_-]{20,}/g),
122
+ whole("a Slack token", /(?<![A-Za-z0-9])xox[abposr]-[A-Za-z0-9-]{10,}/g),
123
+ whole("a Slack webhook", /https:\/\/hooks\.slack\.com\/(?:services|workflows|triggers)\/[A-Za-z0-9_/-]+/g),
124
+ whole("a Google API key", /(?<![A-Za-z0-9])AIza[0-9A-Za-z_-]{30,}/g),
125
+ whole("an npm token", /(?<![A-Za-z0-9])npm_[A-Za-z0-9]{36}(?![A-Za-z0-9])/g),
126
+ whole("a Stripe key", /(?<![A-Za-z0-9])(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,}/g),
127
+ whole("a Stripe webhook secret", /(?<![A-Za-z0-9])whsec_[A-Za-z0-9]{20,}/g),
128
+ whole("a Hugging Face token", /(?<![A-Za-z0-9])hf_[A-Za-z0-9]{30,}/g),
129
+ whole("a SendGrid key", /(?<![A-Za-z0-9])SG\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}/g),
130
+ whole("a Twilio key", /(?<![A-Za-z0-9])SK[0-9a-f]{32}(?![A-Za-z0-9])/g),
131
+ whole("a JWT", /(?<![A-Za-z0-9])eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g),
132
+ {
133
+ kind: "a password in a URL",
134
+ re: /\b([a-z][a-z0-9+.-]*:\/\/)([^\s:@/]*):([^\s@/]+)@/gi,
135
+ replace: (m) => `${m[1]}${m[2]}:[${MASK}]@`,
136
+ },
137
+ {
138
+ kind: "a bearer token",
139
+ re: /\b(Bearer|Basic|Token)(\s+)([A-Za-z0-9._~+/=-]{16,})/g,
140
+ replace: (m) => `${m[1]}${m[2]}[${MASK}]`,
141
+ },
142
+ {
143
+ kind: "a database password",
144
+ re: /(\bmysql(?:dump|admin)?\b[^\n]*?\s-p)([^\s-][^\s]*)/g,
145
+ replace: (m) => `${m[1]}[${MASK}]`,
146
+ },
147
+ ];
148
+ const SECRET_KEY_NAME = "(?:password|passwd|passphrase|pwd|secret|secret[_-]?key|secret[_-]?access[_-]?key|access[_-]?key|client[_-]?secret|api[_-]?key|apikey|" +
149
+ "access[_-]?token|auth[_-]?token|authtoken|refresh[_-]?token|bearer[_-]?token|token|private[_-]?key|account[_-]?key|shared[_-]?access[_-]?key|credentials?)";
150
+ // The key: an identifier whose LAST segment names a secret (DB_PASSWORD,
151
+ // OPENAI_API_KEY, _authToken), so token_count or max_tokens are not keys.
152
+ const ASSIGNMENT = new RegExp(`(?<![A-Za-z0-9])((?:[A-Za-z0-9]+[_.-])*${SECRET_KEY_NAME}["']?\\s*[:=]\\s*["']?)([^\\s"'\`,;()<>{}\\[\\]]{3,})(?=$|[\\s"'\`,;)\\]}])`, "gim");
153
+ const NOT_A_VALUE = /^(?:string|str|number|int|integer|bool|boolean|any|null|nil|none|undefined|true|false|required|optional|empty|redacted|hidden|secret|password|\*+|x{3,}|\.{3,})$/i;
154
+ const PLACEHOLDER = /^(?:your[_-]|<|\$\{?|%|\{\{|changeme|placeholder|example|dummy)|(?:[_-]here)(?:[_-]?\d+)?$/i;
155
+ function isRealValue(v) {
156
+ if (NOT_A_VALUE.test(v) || PLACEHOLDER.test(v))
157
+ return false;
158
+ if (/^(?:\/|~\/|\.{1,2}\/|[A-Za-z]:\\)/.test(v))
159
+ return false; // a path (pwd: /home/...)
160
+ if (/^(?:process\.env|os\.environ|env\.|ENV\[|getenv)/i.test(v))
161
+ return false;
162
+ if (/^[A-Za-z_$][\w$]*(?:\.[\w$]+)+$/.test(v) && !/[0-9]/.test(v))
163
+ return false; // config.apiKey
164
+ if (/^\d{1,7}$/.test(v))
165
+ return false; // a count, a port
166
+ return true;
167
+ }
168
+ /** Mask secret-looking strings. Returns the text, how many were masked, and of what kinds. */
169
+ export function maskSecrets(text) {
170
+ let count = 0;
171
+ const kinds = new Set();
172
+ let out = String(text ?? "");
173
+ for (const m of SECRET_MASKERS) {
174
+ out = out.replace(m.re, (...args) => {
175
+ const groups = args.slice(0, -2).filter((a) => typeof a === "string" || a === undefined);
176
+ const r = m.replace(groups);
177
+ if (r === undefined)
178
+ return groups[0];
179
+ count++;
180
+ kinds.add(m.kind);
181
+ return r;
182
+ });
183
+ }
184
+ out = out.replace(ASSIGNMENT, (whole, key, value) => {
185
+ if (!isRealValue(value))
186
+ return whole;
187
+ count++;
188
+ kinds.add("a password or secret assignment");
189
+ return `${key}[${MASK}]`;
190
+ });
191
+ return { text: out, count, kinds: [...kinds] };
192
+ }
193
+ /** A code fence longer than any backtick run inside `text`, so the block cannot close early. */
194
+ function fenceFor(text) {
195
+ const longest = Math.max(0, ...(text.match(/`+/g) ?? []).map((r) => r.length));
196
+ return "`".repeat(Math.max(3, longest + 1));
197
+ }
198
+ function oneLine(s, max) {
199
+ const t = s.replace(/\s+/g, " ").trim();
200
+ return t.length > max ? t.slice(0, max - 1) + "…" : t;
201
+ }
202
+ /** The text a new chat starts from: what is attached, pasted or copied. */
203
+ export function renderHandoffMarkdown(title, created, brief, blocks) {
204
+ const lines = [
205
+ `# Handoff: ${title}`,
206
+ "",
207
+ `Continue from this handoff (written ${created.slice(0, 16).replace("T", " ")} UTC, saved by context-doctor). It replaces the earlier chat; ask for anything it does not cover.`,
208
+ "",
209
+ brief.trim(),
210
+ ];
211
+ if (blocks.length) {
212
+ lines.push("", "## Verbatim (keep exact)");
213
+ for (const b of blocks) {
214
+ const fence = fenceFor(b.text);
215
+ lines.push("", `### ${oneLine(b.label, HANDOFF_LIMITS.labelChars)}`, "", fence, b.text.replace(/\s+$/, ""), fence);
216
+ }
217
+ }
218
+ return lines.join("\n") + "\n";
219
+ }
220
+ /** What the current chat costs per turn vs a new chat that starts from the handoff. */
221
+ export function handoffMath(handoffTokens, input) {
222
+ const math = { after: handoffTokens };
223
+ if (input.chatTokens !== undefined && input.chatTokens > 0) {
224
+ math.now = Math.round(input.chatTokens);
225
+ math.nowSource = "given";
226
+ }
227
+ else if (input.turns !== undefined && input.turns > 0) {
228
+ math.now = Math.round(input.turns) * exchangeTokens(input.model);
229
+ math.nowSource = "turns";
230
+ }
231
+ const pricing = pricingFor(input.model);
232
+ if (pricing) {
233
+ math.afterUsd = inputCostUsd(math.after, pricing);
234
+ math.afterCachedUsd = (math.after / 1_000_000) * pricing.cacheReadPerM;
235
+ if (math.now !== undefined) {
236
+ math.nowUsd = inputCostUsd(math.now, pricing);
237
+ math.nowCachedUsd = (math.now / 1_000_000) * pricing.cacheReadPerM;
238
+ }
239
+ }
240
+ return math;
241
+ }
242
+ /** "Now ~48k tokens re-read every turn … after ~600" lines, or a hint when the size is unknown. */
243
+ export function renderMath(m) {
244
+ const price = (usd, cached) => (usd !== undefined ? ` (${formatUsd(usd)} at list price, ${formatUsd(cached ?? 0)} cached)` : "");
245
+ if (m.now === undefined) {
246
+ return `A new chat starts from ~${formatTokens(m.after)} tokens${price(m.afterUsd, m.afterCachedUsd)}, plus the app's own system prompt. Pass chat_tokens (from profile_context) to see the per-turn saving.`;
247
+ }
248
+ const est = m.nowSource === "turns" ? " (estimated from the turn count)" : "";
249
+ const saved = Math.max(0, m.now - m.after);
250
+ return [
251
+ `Now: ~${formatTokens(m.now)} tokens re-read on every turn${est}${price(m.nowUsd, m.nowCachedUsd)}.`,
252
+ `After: ~${formatTokens(m.after)} in a new chat${price(m.afterUsd, m.afterCachedUsd)}, plus the app's own system prompt, which every chat carries.`,
253
+ `Saves ~${formatTokens(saved)} tokens per further turn${m.now > 0 ? ` (${Math.round((saved / m.now) * 100)}%)` : ""}; on a subscription that is usage limit.`,
254
+ ].join("\n");
255
+ }
256
+ /** `inner` is `root` itself or somewhere under it. */
257
+ function within(root, inner) {
258
+ const rel = relative(root, inner);
259
+ return rel === "" || (rel !== ".." && !rel.startsWith(".." + sep) && !isAbsolute(rel));
260
+ }
261
+ /** An error whose message names paths relative to the home directory, never absolutely. */
262
+ class HandoffError extends Error {
263
+ }
264
+ /**
265
+ * The handoffs folder, if it is safe to use: ~/.context-doctor and its
266
+ * handoffs folder must be real directories (not symbolic links) whose real
267
+ * path is inside the home directory's. With `create`, missing ones are made
268
+ * (0700), one level at a time, and checked after. Otherwise undefined (read)
269
+ * or a HandoffError (create). A QA pass pointed handoffs at another folder
270
+ * with a link, and rotation deleted a folder outside the home directory.
271
+ */
272
+ function safeHandoffDir(home, create) {
273
+ const refuse = (why) => {
274
+ if (create)
275
+ throw new HandoffError(why);
276
+ return undefined;
277
+ };
278
+ let realHome;
279
+ try {
280
+ realHome = realpathSync(home);
281
+ }
282
+ catch {
283
+ return refuse("the home directory cannot be read");
284
+ }
285
+ const parent = join(home, ".context-doctor");
286
+ const dir = handoffDir(home);
287
+ for (const d of [parent, dir]) {
288
+ let st;
289
+ try {
290
+ st = lstatSync(d);
291
+ }
292
+ catch {
293
+ if (!create)
294
+ return undefined;
295
+ try {
296
+ mkdirSync(d, { mode: 0o700 });
297
+ st = lstatSync(d);
298
+ }
299
+ catch (e) {
300
+ return refuse(`cannot create ${tildify(d, home)} (${e.code ?? "error"})`);
301
+ }
302
+ }
303
+ if (st.isSymbolicLink())
304
+ return refuse(`${tildify(d, home)} is a symbolic link; handoffs are only written to a real folder in the home directory`);
305
+ if (!st.isDirectory())
306
+ return refuse(`${tildify(d, home)} is not a folder`);
307
+ let real;
308
+ try {
309
+ real = realpathSync(d);
310
+ }
311
+ catch {
312
+ return refuse(`${tildify(d, home)} cannot be read`);
313
+ }
314
+ if (!within(realHome, real))
315
+ return refuse(`${tildify(d, home)} resolves outside the home directory`);
316
+ }
317
+ return dir;
318
+ }
319
+ /** Ordering time: a handoff dated in the future (clock skew, a planted folder) sorts as the oldest, never the newest. */
320
+ function sortTime(meta, now) {
321
+ const t = Date.parse(meta.created);
322
+ return Number.isFinite(t) && t <= now + 60_000 ? t : 0;
323
+ }
324
+ /** Newest first by `created` (future dates last), then by save order, then by id. Never by the id string alone. */
325
+ function newestFirst(now) {
326
+ const order = (m) => (typeof m.order === "number" && Number.isFinite(m.order) ? m.order : 0);
327
+ return (a, b) => sortTime(b, now) - sortTime(a, now) || order(b) - order(a) || (a.id < b.id ? 1 : a.id > b.id ? -1 : 0);
328
+ }
329
+ let saveCounter = 0;
330
+ /** Every saved handoff, newest first. Entries that are not ours (bad name, symlink, no meta) are skipped. */
331
+ export function listHandoffs(home = homedir()) {
332
+ const dir = safeHandoffDir(home, false);
333
+ if (!dir)
334
+ return [];
335
+ let names;
336
+ try {
337
+ names = readdirSync(dir);
338
+ }
339
+ catch {
340
+ return [];
341
+ }
342
+ const metas = [];
343
+ for (const name of names) {
344
+ if (!isHandoffId(name))
345
+ continue;
346
+ const folder = join(dir, name);
347
+ try {
348
+ if (!lstatSync(folder).isDirectory())
349
+ continue;
350
+ const metaPath = join(folder, "meta.json");
351
+ if (!lstatSync(metaPath).isFile())
352
+ continue;
353
+ const meta = JSON.parse(readFileSync(metaPath, "utf8"));
354
+ if (meta?.id !== name || typeof meta.created !== "string")
355
+ continue;
356
+ metas.push(meta);
357
+ }
358
+ catch {
359
+ continue;
360
+ }
361
+ }
362
+ return metas.sort(newestFirst(Date.now()));
363
+ }
364
+ /**
365
+ * One handoff by id, or the newest for "latest". Undefined for anything that
366
+ * is not a well-formed id of a saved handoff: no path from a caller (a
367
+ * resource URI, a CLI argument) ever reaches the filesystem as given.
368
+ */
369
+ export function readHandoff(idOrLatest, home = homedir()) {
370
+ const id = idOrLatest === "latest" ? listHandoffs(home)[0]?.id : idOrLatest;
371
+ if (!isHandoffId(id))
372
+ return undefined;
373
+ const dir = safeHandoffDir(home, false);
374
+ if (!dir)
375
+ return undefined;
376
+ const folder = join(dir, id);
377
+ const file = join(folder, "handoff.md");
378
+ if (!within(dir, file))
379
+ return undefined;
380
+ try {
381
+ const st = lstatSync(file);
382
+ if (!st.isFile() || st.size > HANDOFF_LIMITS.readBytes || !lstatSync(folder).isDirectory() || !lstatSync(join(folder, "meta.json")).isFile())
383
+ return undefined;
384
+ const meta = JSON.parse(readFileSync(join(folder, "meta.json"), "utf8"));
385
+ if (meta?.id !== id)
386
+ return undefined;
387
+ return { meta, markdown: readFileSync(file, "utf8") };
388
+ }
389
+ catch {
390
+ return undefined;
391
+ }
392
+ }
393
+ /**
394
+ * Keep the newest `kept` handoffs, the one just written always among them;
395
+ * remove older folders that are ours: named like one, a real directory (not
396
+ * a link) in the real handoffs folder, with our meta.json naming it.
397
+ */
398
+ function rotate(home, kept, justWritten) {
399
+ const dir = safeHandoffDir(home, false);
400
+ if (!dir)
401
+ return 0;
402
+ const others = listHandoffs(home).filter((m) => m.id !== justWritten);
403
+ let removed = 0;
404
+ for (const meta of others.slice(Math.max(0, kept - 1))) {
405
+ const folder = join(dir, meta.id);
406
+ try {
407
+ if (!within(dir, folder) || !lstatSync(folder).isDirectory() || !lstatSync(join(folder, "meta.json")).isFile())
408
+ continue;
409
+ if (!within(realpathSync(dir), realpathSync(folder)))
410
+ continue;
411
+ rmSync(folder, { recursive: true, force: true });
412
+ removed++;
413
+ }
414
+ catch {
415
+ // Best effort: a locked folder stays until next time.
416
+ }
417
+ }
418
+ return removed;
419
+ }
420
+ /**
421
+ * C0 and C1 control characters out, so a title or brief cannot drive a
422
+ * terminal (escape sequences that retitle a window or clear the screen) when
423
+ * the CLI prints it. Newlines and tabs stay; CRLF becomes LF.
424
+ */
425
+ export function stripControls(text, { keepNewlines = true } = {}) {
426
+ const t = String(text ?? "").replace(/\r\n?/g, "\n");
427
+ // eslint-disable-next-line no-control-regex
428
+ return keepNewlines ? t.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, "") : t.replace(/[\u0000-\u001f\u007f-\u009f]/g, " ");
429
+ }
430
+ /**
431
+ * Build a handoff, and store it unless `store` is false (the HTTP server keeps
432
+ * nothing by default). Throws with the validation problems on bad input, and
433
+ * with a message that names no absolute path when the folder is unsafe.
434
+ */
435
+ export function saveHandoff(input, { home = homedir(), now = new Date(), store = true } = {}) {
436
+ const errs = validateHandoff(input);
437
+ if (errs.length)
438
+ throw new Error(errs.join(" "));
439
+ const kinds = new Set();
440
+ let masked = 0;
441
+ const mask = (s) => {
442
+ const m = maskSecrets(s);
443
+ masked += m.count;
444
+ m.kinds.forEach((k) => kinds.add(k));
445
+ return m.text;
446
+ };
447
+ const brief = mask(stripControls(input.brief));
448
+ // Untitled: the brief's first line, which is already masked.
449
+ const title = oneLine(input.title?.trim() ? mask(stripControls(input.title, { keepNewlines: false })) : brief.split("\n").find((l) => l.trim())?.replace(/^#+\s*/, "") || "handoff", HANDOFF_LIMITS.titleChars);
450
+ const blocks = (input.verbatim ?? []).map((b) => ({ label: oneLine(mask(stripControls(b.label, { keepNewlines: false })), HANDOFF_LIMITS.labelChars), text: mask(stripControls(b.text)) }));
451
+ // The model name is the caller's string: capped, cleaned and masked like the rest.
452
+ const model = input.model === undefined ? undefined : mask(stripControls(String(input.model), { keepNewlines: false })).slice(0, HANDOFF_LIMITS.modelChars) || undefined;
453
+ const created = now.toISOString();
454
+ const markdown = renderHandoffMarkdown(title, created, brief, blocks);
455
+ const base = `${stamp(now)}-${slugify(title)}`;
456
+ const meta = {
457
+ id: base,
458
+ title,
459
+ created,
460
+ model,
461
+ tokens: estimateTokens(markdown, model),
462
+ briefTokens: estimateTokens(brief, model),
463
+ blocks: blocks.map((b) => ({ label: b.label, tokens: estimateTokens(b.text, model) })),
464
+ masked,
465
+ order: Date.now() * 1000 + (saveCounter++ % 1000),
466
+ };
467
+ const math = handoffMath(meta.tokens, { ...input, model });
468
+ if (!store)
469
+ return { meta, markdown, maskedKinds: [...kinds], math, rotated: 0 };
470
+ const dir = safeHandoffDir(home, true);
471
+ // A second save in the same second gets -2, -3, …: never overwrite one.
472
+ let folder = "";
473
+ for (let n = 1; n <= 200; n++) {
474
+ const id = n === 1 ? base : `${base}-${n}`;
475
+ const candidate = join(dir, id);
476
+ try {
477
+ mkdirSync(candidate, { mode: 0o700 });
478
+ meta.id = id;
479
+ folder = candidate;
480
+ break;
481
+ }
482
+ catch (e) {
483
+ if (e.code !== "EEXIST")
484
+ throw new HandoffError(`cannot create a handoff folder in ${tildify(dir, home)} (${e.code ?? "error"})`);
485
+ }
486
+ }
487
+ if (!folder)
488
+ throw new HandoffError(`too many handoffs saved in the same second in ${tildify(dir, home)}`);
489
+ try {
490
+ // "wx": fail rather than write through anything already at that path.
491
+ writeFileSync(join(folder, "handoff.md"), markdown, { mode: 0o600, flag: "wx" });
492
+ writeFileSync(join(folder, "meta.json"), JSON.stringify(meta, null, 2) + "\n", { mode: 0o600, flag: "wx" });
493
+ }
494
+ catch (e) {
495
+ throw new HandoffError(`cannot write the handoff in ${tildify(folder, home)} (${e.code ?? "error"})`);
496
+ }
497
+ const rotated = rotate(home, HANDOFF_LIMITS.kept, meta.id);
498
+ if (!existsSync(join(folder, "handoff.md")))
499
+ throw new HandoffError(`the handoff in ${tildify(folder, home)} is gone`);
500
+ return { meta, markdown, dir: folder, maskedKinds: [...kinds], math, rotated };
501
+ }
502
+ /** Where a path sits, with the home directory shown as ~. */
503
+ export function tildify(path, home = homedir()) {
504
+ return home && path.startsWith(home) ? "~" + path.slice(home.length) : path;
505
+ }
506
+ /** Every absolute mention of the home directory in `text` as ~ (error messages that reach a client). */
507
+ export function tildifyAll(text, home = homedir()) {
508
+ return home && home.length > 1 ? String(text).split(home).join("~") : String(text);
509
+ }
510
+ /** `context-doctor handoff list`. */
511
+ export function renderHandoffList(metas, home = homedir()) {
512
+ if (metas.length === 0) {
513
+ return [
514
+ "No handoffs saved yet.",
515
+ "In Claude Desktop pick the `handoff` prompt from the + menu (context-doctor); elsewhere ask the assistant for a handoff, and it calls save_handoff.",
516
+ `They are kept in ${tildify(handoffDir(home), home)}.`,
517
+ ].join("\n");
518
+ }
519
+ const lines = metas.map((m) => {
520
+ const blocks = m.blocks.length ? `, ${m.blocks.length} verbatim` : "";
521
+ return ` ${m.id} ~${formatTokens(m.tokens)}${blocks} ${oneLine(stripControls(String(m.title ?? ""), { keepNewlines: false }), 60)}`;
522
+ });
523
+ return [
524
+ `${metas.length} handoff(s), newest first (${tildify(handoffDir(home), home)}; the newest ${HANDOFF_LIMITS.kept} are kept):`,
525
+ ...lines,
526
+ "",
527
+ "Show one: context-doctor handoff show <id>. The newest: context-doctor handoff latest [--copy], then paste it as the first message of a new chat.",
528
+ ].join("\n");
529
+ }
package/dist/hook.d.ts CHANGED
@@ -29,4 +29,4 @@ export interface HookInput {
29
29
  * DeprecationWarning into the user's session (and will throw on a later one).
30
30
  */
31
31
  export declare function hookInput(raw: unknown): HookInput;
32
- export declare function runHook(): Promise<void>;
32
+ export declare function runHook(app?: "copilot"): Promise<void>;
package/dist/hook.js CHANGED
@@ -14,8 +14,9 @@
14
14
  import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
15
15
  import { createHash } from "node:crypto";
16
16
  import { homedir } from "node:os";
17
- import { join } from "node:path";
18
- import { recordLedger, statePath } from "./ledger.js";
17
+ import { dirname, join } from "node:path";
18
+ import { ledgerPath, recordLedger, statePath } from "./ledger.js";
19
+ import { copilotSessionStartOutput } from "./copilot.js";
19
20
  import { parseConversation } from "./parse.js";
20
21
  import { profileConversation } from "./profile.js";
21
22
  import { parseSessionFile } from "./session.js";
@@ -164,9 +165,30 @@ export function hookInput(raw) {
164
165
  delete out.workspace_roots;
165
166
  return out;
166
167
  }
167
- export async function runHook() {
168
+ export async function runHook(app) {
168
169
  // A hook must never break the user's prompt: any failure exits silently.
169
170
  try {
171
+ // GitHub Copilot (`hook copilot`, its sessionStart): the standing rules,
172
+ // nothing else. No Copilot hook that can add context gets a transcript,
173
+ // and Copilot never routes through autopilot, so there is no self-heal.
174
+ if (app === "copilot") {
175
+ // An input that does not parse (empty, a BOM, cut short) is still a
176
+ // session start: the rules go in rather than nothing.
177
+ let input = {};
178
+ try {
179
+ input = JSON.parse((await readStdin()).replace(/^\uFEFF/, ""));
180
+ }
181
+ catch { /* not JSON: answer as for an empty input */ }
182
+ const out = copilotSessionStartOutput(input);
183
+ if (out) {
184
+ process.stdout.write(out + "\n");
185
+ // Evidence for `doctor`, only where the ledger's folder already is:
186
+ // creating ~/.claude would make install and doctor see Claude Code.
187
+ if (existsSync(dirname(ledgerPath())))
188
+ recordLedger({ ev: "session_rules", app: "copilot" });
189
+ }
190
+ return;
191
+ }
170
192
  // Autopilot self-heal: this prompt's request is about to go to the proxy,
171
193
  // so if the proxy died, start it now. One existsSync when autopilot is
172
194
  // off; a ~1ms localhost health check when it is on and healthy.
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Guards for the MCP server's --http mode, kept apart from mcp.ts (which
3
+ * starts a server on import) so they can be tested directly.
4
+ *
5
+ * A server on 127.0.0.1 is still reachable from a browser: a page can POST to
6
+ * it (a cross-origin "simple" request needs no preflight), and with DNS
7
+ * rebinding a page on attacker.example can even make the browser treat the
8
+ * server as same-origin. A QA pass did exactly that: a foreign origin saved
9
+ * 101 handoffs through --store-handoffs, evicted the user's own and planted
10
+ * handoff://latest. So every /mcp request is checked:
11
+ *
12
+ * - Host must name this server: localhost, 127.0.0.1, [::1], the --host it
13
+ * was given, or a name in --allowed-hosts (a tunnel's host name, say).
14
+ * `--allowed-hosts '*'` turns the check off, explicitly.
15
+ * - Origin, when a browser sends one, must be a loopback origin, one whose
16
+ * host is allowed above, or one in --allowed-origins. ChatGPT's own
17
+ * origins are allowed by default; requests without an Origin (servers,
18
+ * CLIs, ChatGPT's connector backend) are not affected.
19
+ * - The body is read here, capped (10 MB, else 413), and parsed (else 400),
20
+ * then handed to the transport, so no request can make the server buffer
21
+ * an unbounded body.
22
+ */
23
+ import type { IncomingMessage } from "node:http";
24
+ export declare const HTTP_LIMITS: {
25
+ bodyBytes: number;
26
+ bodyMs: number;
27
+ };
28
+ /** Origins a browser may call from without being listed: ChatGPT's. */
29
+ export declare const DEFAULT_ALLOWED_ORIGINS: string[];
30
+ export interface HttpGuard {
31
+ /** Host names (lowercase, no port, no brackets) accepted in Host; "*" accepts any. */
32
+ hosts: Set<string> | "*";
33
+ origins: Set<string>;
34
+ }
35
+ /** A Host header's or URL's host name: lowercase, no port, no brackets, no trailing dot. */
36
+ export declare function hostName(hostHeader: string): string;
37
+ /**
38
+ * The guard for a server bound to `bindHost`, from --allowed-hosts and
39
+ * --allowed-origins (comma lists) and the CONTEXT_DOCTOR_ALLOWED_HOSTS and
40
+ * CONTEXT_DOCTOR_ALLOWED_ORIGINS environment variables.
41
+ */
42
+ export declare function makeGuard(bindHost: string, allowedHosts?: string, allowedOrigins?: string, env?: NodeJS.ProcessEnv): HttpGuard;
43
+ /** Why this request may not reach /mcp, or undefined when it may. */
44
+ export declare function refusal(guard: HttpGuard, headers: IncomingMessage["headers"]): string | undefined;
45
+ /**
46
+ * The request body as JSON, at most `limit` bytes and within `ms` (a client
47
+ * that declares more than it sends must not hold a request open); otherwise
48
+ * the status and reason to answer with.
49
+ */
50
+ export declare function readJsonBody(req: IncomingMessage, limit?: number, ms?: number): Promise<{
51
+ value: unknown;
52
+ } | {
53
+ status: number;
54
+ code: number;
55
+ message: string;
56
+ }>;