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.
- package/README.md +21 -14
- package/dist/ab.d.ts +188 -0
- package/dist/ab.js +857 -0
- package/dist/abtasks.d.ts +49 -0
- package/dist/abtasks.js +287 -0
- package/dist/cli.js +83 -8
- package/dist/compact.d.ts +36 -0
- package/dist/compact.js +144 -0
- package/dist/copilot.d.ts +63 -0
- package/dist/copilot.js +96 -0
- package/dist/doctor.js +114 -1
- package/dist/extract.d.ts +23 -0
- package/dist/extract.js +121 -4
- package/dist/fileparams.d.ts +61 -0
- package/dist/fileparams.js +308 -0
- package/dist/handoff.d.ts +143 -0
- package/dist/handoff.js +529 -0
- package/dist/hook.d.ts +1 -1
- package/dist/hook.js +25 -3
- package/dist/httpguard.d.ts +56 -0
- package/dist/httpguard.js +141 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/install.d.ts +16 -0
- package/dist/install.js +176 -3
- package/dist/ledger.d.ts +6 -1
- package/dist/ledger.js +45 -7
- package/dist/mcp.d.ts +2 -0
- package/dist/mcp.js +72 -56
- package/dist/pack.d.ts +20 -0
- package/dist/pack.js +29 -1
- package/dist/preferences.d.ts +3 -1
- package/dist/preferences.js +8 -6
- package/dist/pricing.d.ts +7 -0
- package/dist/pricing.js +29 -5
- package/dist/proxy.d.ts +1 -1
- package/dist/proxy.js +1 -1
- package/dist/rules.d.ts +19 -0
- package/dist/rules.js +34 -0
- package/dist/sketch.d.ts +5 -1
- package/dist/sketch.js +23 -7
- package/package.json +1 -1
- package/skills/context-doctor/SKILL.md +2 -0
|
@@ -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
|
+
}>;
|
|
@@ -0,0 +1,308 @@
|
|
|
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 { lookup as dnsLookup } from "node:dns";
|
|
21
|
+
import { request as httpRequest } from "node:http";
|
|
22
|
+
import { request as httpsRequest } from "node:https";
|
|
23
|
+
import { isIP } from "node:net";
|
|
24
|
+
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
25
|
+
import { tmpdir } from "node:os";
|
|
26
|
+
import { extname, join } from "node:path";
|
|
27
|
+
import { EXTRACT_BUDGET_MS, EXTRACTABLE, extractTextAsync } from "./extract.js";
|
|
28
|
+
/** Per file: bytes and time. Per call: files, bytes and time (downloads and extraction together). */
|
|
29
|
+
export const FILE_LIMITS = { files: 10, bytes: 5 * 1024 * 1024, totalBytes: 20 * 1024 * 1024, timeoutMs: 20_000, redirects: 3, callMs: 60_000 };
|
|
30
|
+
const MIME_EXT = {
|
|
31
|
+
"application/pdf": ".pdf",
|
|
32
|
+
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx",
|
|
33
|
+
"application/msword": ".doc",
|
|
34
|
+
"application/rtf": ".rtf",
|
|
35
|
+
"text/rtf": ".rtf",
|
|
36
|
+
"application/vnd.oasis.opendocument.text": ".odt",
|
|
37
|
+
"application/vnd.openxmlformats-officedocument.presentationml.presentation": ".pptx",
|
|
38
|
+
};
|
|
39
|
+
function loopbackAllowed(env = process.env) {
|
|
40
|
+
return env.CONTEXT_DOCTOR_TEST_LOOPBACK_FILES === "1";
|
|
41
|
+
}
|
|
42
|
+
function isPrivateV4(ip) {
|
|
43
|
+
const [a, b] = ip.split(".").map(Number);
|
|
44
|
+
const c = Number(ip.split(".")[2]);
|
|
45
|
+
return (a === 0 || a === 10 || a === 127 || a >= 224 || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) ||
|
|
46
|
+
(a === 100 && b >= 64 && b <= 127) || (a === 192 && b === 0) || (a === 198 && (b === 18 || b === 19)) ||
|
|
47
|
+
// Documentation (TEST-NET-2/3) and the old 6to4 relay anycast: never a file host.
|
|
48
|
+
(a === 198 && b === 51 && c === 100) || (a === 203 && b === 0 && c === 113) || (a === 192 && b === 88 && c === 99));
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* The eight 16-bit groups of an IPv6 address, a dotted IPv4 tail included,
|
|
52
|
+
* or undefined. Needed because one address has many spellings: the URL
|
|
53
|
+
* parser writes [::ffff:127.0.0.1] as [::ffff:7f00:1], which a pattern for
|
|
54
|
+
* the dotted form lets through to the loopback interface.
|
|
55
|
+
*/
|
|
56
|
+
function hextets(ip) {
|
|
57
|
+
let s = ip.toLowerCase().replace(/^\[|\]$/g, "").replace(/%.*$/, "");
|
|
58
|
+
const v4 = s.match(/(\d+\.\d+\.\d+\.\d+)$/);
|
|
59
|
+
if (v4) {
|
|
60
|
+
const [a, b, c, d] = v4[1].split(".").map(Number);
|
|
61
|
+
s = s.slice(0, -v4[1].length) + `${((a << 8) | b).toString(16)}:${((c << 8) | d).toString(16)}`;
|
|
62
|
+
}
|
|
63
|
+
const [head, tail] = s.split("::");
|
|
64
|
+
const h = head ? head.split(":") : [];
|
|
65
|
+
const t = tail !== undefined && tail ? tail.split(":") : [];
|
|
66
|
+
const fill = s.includes("::") ? 8 - h.length - t.length : 0;
|
|
67
|
+
const all = [...h, ...Array(Math.max(0, fill)).fill("0"), ...t].map((x) => parseInt(x || "0", 16));
|
|
68
|
+
return all.length === 8 && all.every((n) => Number.isInteger(n) && n >= 0 && n <= 0xffff) ? all : undefined;
|
|
69
|
+
}
|
|
70
|
+
/** Loopback, private, link-local, CGNAT, unspecified, multicast or reserved: never a place a download should go. */
|
|
71
|
+
export function isPrivateAddress(ip) {
|
|
72
|
+
const bare = ip.replace(/^\[|\]$/g, "");
|
|
73
|
+
const v = isIP(bare);
|
|
74
|
+
if (v === 4)
|
|
75
|
+
return isPrivateV4(bare);
|
|
76
|
+
if (v === 6) {
|
|
77
|
+
const g = hextets(bare);
|
|
78
|
+
if (!g)
|
|
79
|
+
return true;
|
|
80
|
+
// ::, ::1, IPv4-mapped (::ffff:a.b.c.d) and IPv4-compatible (::a.b.c.d): judge the IPv4 inside.
|
|
81
|
+
if (g.slice(0, 5).every((n) => n === 0) && (g[5] === 0xffff || g[5] === 0)) {
|
|
82
|
+
if (g[5] === 0 && g[6] === 0 && g[7] <= 1)
|
|
83
|
+
return true;
|
|
84
|
+
return isPrivateV4(`${g[6] >> 8}.${g[6] & 255}.${g[7] >> 8}.${g[7] & 255}`);
|
|
85
|
+
}
|
|
86
|
+
// IPv4-translated (::ffff:0:a.b.c.d, RFC 2765): judge the IPv4 inside.
|
|
87
|
+
if (g.slice(0, 4).every((n) => n === 0) && g[4] === 0xffff && g[5] === 0) {
|
|
88
|
+
return isPrivateV4(`${g[6] >> 8}.${g[6] & 255}.${g[7] >> 8}.${g[7] & 255}`);
|
|
89
|
+
}
|
|
90
|
+
if (g[0] === 0x64 && g[1] === 0xff9b)
|
|
91
|
+
return true; // NAT64: whatever IPv4 it carries
|
|
92
|
+
// 6to4 (2002::/16) and Teredo (2001:0::/32) tunnel to an IPv4 written into
|
|
93
|
+
// the address, private ones included; no file host needs them.
|
|
94
|
+
if (g[0] === 0x2002)
|
|
95
|
+
return true;
|
|
96
|
+
if (g[0] === 0x2001 && g[1] === 0)
|
|
97
|
+
return true;
|
|
98
|
+
if ((g[0] & 0xfe00) === 0xfc00)
|
|
99
|
+
return true; // fc00::/7, unique local
|
|
100
|
+
if ((g[0] & 0xffc0) === 0xfe80)
|
|
101
|
+
return true; // fe80::/10, link-local
|
|
102
|
+
if ((g[0] & 0xff00) === 0xff00)
|
|
103
|
+
return true; // multicast
|
|
104
|
+
if (g[0] === 0x2001 && g[1] === 0x0db8)
|
|
105
|
+
return true; // documentation
|
|
106
|
+
if (g[0] === 0x0100 && g[1] === 0 && g[2] === 0 && g[3] === 0)
|
|
107
|
+
return true; // discard
|
|
108
|
+
return false;
|
|
109
|
+
}
|
|
110
|
+
return true; // not an address at all: refuse
|
|
111
|
+
}
|
|
112
|
+
function isLoopback(host) {
|
|
113
|
+
const h = host.replace(/^\[|\]$/g, "").toLowerCase();
|
|
114
|
+
return h === "localhost" || h === "::1" || /^127\./.test(h);
|
|
115
|
+
}
|
|
116
|
+
/** A download URL this server may fetch, or the reason it may not. */
|
|
117
|
+
export function checkFileUrl(raw, env = process.env) {
|
|
118
|
+
let url;
|
|
119
|
+
try {
|
|
120
|
+
url = new URL(raw);
|
|
121
|
+
}
|
|
122
|
+
catch {
|
|
123
|
+
return { error: "not a URL" };
|
|
124
|
+
}
|
|
125
|
+
if (url.username || url.password)
|
|
126
|
+
return { error: "credentials in the URL" };
|
|
127
|
+
const host = url.hostname.replace(/^\[|\]$/g, "");
|
|
128
|
+
const testLoopback = loopbackAllowed(env) && isLoopback(host);
|
|
129
|
+
if (url.protocol !== "https:" && !(url.protocol === "http:" && testLoopback))
|
|
130
|
+
return { error: `only https downloads are allowed (got ${url.protocol.replace(":", "")})` };
|
|
131
|
+
if (testLoopback)
|
|
132
|
+
return { url };
|
|
133
|
+
if (/^localhost$|\.localhost$|\.local$|\.internal$/i.test(host.replace(/\.$/, "")))
|
|
134
|
+
return { error: "a local host name" };
|
|
135
|
+
if (isIP(host) && isPrivateAddress(host))
|
|
136
|
+
return { error: "a private or loopback address" };
|
|
137
|
+
return { url };
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* dns.lookup that refuses private addresses, used as the socket's lookup so
|
|
141
|
+
* the address checked is the address connected to. Node 20+ asks with
|
|
142
|
+
* `all: true` (happy eyeballs), older paths with a single address.
|
|
143
|
+
*/
|
|
144
|
+
function guardedLookup(allowLoopback) {
|
|
145
|
+
return (hostname, options, callback) => {
|
|
146
|
+
dnsLookup(hostname, options, (err, address, family) => {
|
|
147
|
+
if (err)
|
|
148
|
+
return callback(err);
|
|
149
|
+
const list = Array.isArray(address) ? address : [{ address, family: family ?? 4 }];
|
|
150
|
+
const bad = list.find((a) => isPrivateAddress(a.address) && !(allowLoopback && isLoopback(a.address)));
|
|
151
|
+
if (bad)
|
|
152
|
+
return callback(Object.assign(new Error(`${hostname} resolves to a private address`), { code: "EPRIVATE" }));
|
|
153
|
+
if (Array.isArray(address))
|
|
154
|
+
callback(null, address);
|
|
155
|
+
else
|
|
156
|
+
callback(null, address, family);
|
|
157
|
+
});
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
function getOnce(url, env, deadline, maxBytes) {
|
|
161
|
+
return new Promise((resolve) => {
|
|
162
|
+
const allowLoopback = loopbackAllowed(env) && isLoopback(url.hostname);
|
|
163
|
+
const request = url.protocol === "https:" ? httpsRequest : httpRequest;
|
|
164
|
+
let settled = false;
|
|
165
|
+
const done = (r) => {
|
|
166
|
+
if (settled)
|
|
167
|
+
return;
|
|
168
|
+
settled = true;
|
|
169
|
+
clearTimeout(overall);
|
|
170
|
+
resolve(r);
|
|
171
|
+
};
|
|
172
|
+
const timeout = Math.max(1, deadline - Date.now());
|
|
173
|
+
// The socket timeout is an idle timeout; a server dripping a byte at a
|
|
174
|
+
// time would never trip it. This one bounds the whole download.
|
|
175
|
+
const overall = setTimeout(() => {
|
|
176
|
+
req.destroy();
|
|
177
|
+
done({ status: 0, error: "timed out" });
|
|
178
|
+
}, timeout);
|
|
179
|
+
const req = request(url, { method: "GET", lookup: guardedLookup(allowLoopback), timeout, headers: { accept: "*/*", "user-agent": "context-doctor" } }, (res) => {
|
|
180
|
+
const status = res.statusCode ?? 0;
|
|
181
|
+
if (status >= 300 && status < 400) {
|
|
182
|
+
res.resume();
|
|
183
|
+
return done({ status, location: typeof res.headers.location === "string" ? res.headers.location : undefined });
|
|
184
|
+
}
|
|
185
|
+
if (status !== 200) {
|
|
186
|
+
res.resume();
|
|
187
|
+
return done({ status, error: `HTTP ${status}` });
|
|
188
|
+
}
|
|
189
|
+
// The smaller of the per-file limit and what is left of the call's total,
|
|
190
|
+
// enforced as bytes arrive: nothing past it is ever held in memory.
|
|
191
|
+
const tooLarge = maxBytes < FILE_LIMITS.bytes
|
|
192
|
+
? `over the ${FILE_LIMITS.totalBytes / 1024 / 1024} MB total for one call`
|
|
193
|
+
: `too large (over ${FILE_LIMITS.bytes / 1024 / 1024} MB)`;
|
|
194
|
+
const declared = Number(res.headers["content-length"]);
|
|
195
|
+
if (Number.isFinite(declared) && declared > maxBytes) {
|
|
196
|
+
req.destroy();
|
|
197
|
+
return done({ status, error: tooLarge });
|
|
198
|
+
}
|
|
199
|
+
const parts = [];
|
|
200
|
+
let size = 0;
|
|
201
|
+
res.on("data", (d) => {
|
|
202
|
+
size += d.length;
|
|
203
|
+
if (size > maxBytes) {
|
|
204
|
+
req.destroy();
|
|
205
|
+
done({ status, error: tooLarge });
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
parts.push(d);
|
|
209
|
+
});
|
|
210
|
+
res.on("end", () => done({ status, body: Buffer.concat(parts) }));
|
|
211
|
+
res.on("error", (e) => done({ status, error: e.message }));
|
|
212
|
+
});
|
|
213
|
+
req.on("timeout", () => {
|
|
214
|
+
req.destroy();
|
|
215
|
+
done({ status: 0, error: "timed out" });
|
|
216
|
+
});
|
|
217
|
+
req.on("error", (e) => done({ status: 0, error: e.code === "EPRIVATE" ? "refused: the host resolves to a private address" : e.message }));
|
|
218
|
+
req.end();
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Download one file, following at most FILE_LIMITS.redirects https redirects,
|
|
223
|
+
* within FILE_LIMITS.timeoutMs (or the caller's earlier `deadline`) and
|
|
224
|
+
* `maxBytes` (default the per-file limit). Never throws.
|
|
225
|
+
*/
|
|
226
|
+
export async function downloadFile(raw, env = process.env, { deadline: callDeadline, maxBytes = FILE_LIMITS.bytes } = {}) {
|
|
227
|
+
const deadline = Math.min(Date.now() + FILE_LIMITS.timeoutMs, callDeadline ?? Infinity);
|
|
228
|
+
const limit = Math.max(0, Math.min(maxBytes, FILE_LIMITS.bytes));
|
|
229
|
+
let current = raw;
|
|
230
|
+
for (let hop = 0; hop <= FILE_LIMITS.redirects; hop++) {
|
|
231
|
+
const checked = checkFileUrl(current, env);
|
|
232
|
+
if ("error" in checked)
|
|
233
|
+
return { error: hop === 0 ? `refused: ${checked.error}` : `refused a redirect: ${checked.error}` };
|
|
234
|
+
if (Date.now() >= deadline)
|
|
235
|
+
return { error: "timed out" };
|
|
236
|
+
const r = await getOnce(checked.url, env, deadline, limit);
|
|
237
|
+
if (r.error)
|
|
238
|
+
return { error: r.error };
|
|
239
|
+
if (r.location !== undefined) {
|
|
240
|
+
if (!r.location)
|
|
241
|
+
return { error: `HTTP ${r.status} without a location` };
|
|
242
|
+
// A malformed Location (http://[::1) is that file's problem, not the call's.
|
|
243
|
+
try {
|
|
244
|
+
current = new URL(r.location, checked.url).toString();
|
|
245
|
+
}
|
|
246
|
+
catch {
|
|
247
|
+
return { error: "refused a redirect: not a URL" };
|
|
248
|
+
}
|
|
249
|
+
continue;
|
|
250
|
+
}
|
|
251
|
+
return { body: r.body ?? Buffer.alloc(0) };
|
|
252
|
+
}
|
|
253
|
+
return { error: `more than ${FILE_LIMITS.redirects} redirects` };
|
|
254
|
+
}
|
|
255
|
+
/** A name for chunk ids: the file's own name without any path, or its id. */
|
|
256
|
+
function safeName(f) {
|
|
257
|
+
const base = (f.file_name ?? "").split(/[\\/]/).pop()?.replace(/[^\w.\- ]+/g, "_").trim();
|
|
258
|
+
return (base || String(f.file_id || "file").replace(/[^\w.-]+/g, "_")).slice(0, 80);
|
|
259
|
+
}
|
|
260
|
+
/** Download and read files ChatGPT passed, into pack sources. Never throws. */
|
|
261
|
+
export async function sourcesFromOpenAiFiles(files, env = process.env) {
|
|
262
|
+
const sources = [];
|
|
263
|
+
const skipped = [];
|
|
264
|
+
let total = 0;
|
|
265
|
+
// One budget for the whole call, downloads and extraction together.
|
|
266
|
+
const callDeadline = Date.now() + FILE_LIMITS.callMs;
|
|
267
|
+
for (const f of files.slice(0, FILE_LIMITS.files)) {
|
|
268
|
+
const name = safeName(f);
|
|
269
|
+
if (Date.now() >= callDeadline) {
|
|
270
|
+
skipped.push(`${name}: not read, the ${FILE_LIMITS.callMs / 1000} s allowed for one call ran out`);
|
|
271
|
+
continue;
|
|
272
|
+
}
|
|
273
|
+
const got = await downloadFile(String(f.download_url ?? ""), env, { deadline: callDeadline, maxBytes: FILE_LIMITS.totalBytes - total });
|
|
274
|
+
if ("error" in got) {
|
|
275
|
+
skipped.push(`${name}: ${got.error}`);
|
|
276
|
+
continue;
|
|
277
|
+
}
|
|
278
|
+
total += got.body.length;
|
|
279
|
+
const ext = extname(name).toLowerCase();
|
|
280
|
+
const docExt = EXTRACTABLE.has(ext) ? ext : MIME_EXT[(f.mime_type ?? "").split(";")[0].trim().toLowerCase()];
|
|
281
|
+
if (docExt) {
|
|
282
|
+
// The extractors work on files: write it to a private temp folder, read, remove.
|
|
283
|
+
const dir = mkdtempSync(join(tmpdir(), "cd-file-"));
|
|
284
|
+
try {
|
|
285
|
+
const path = join(dir, `upload${docExt}`);
|
|
286
|
+
writeFileSync(path, got.body, { mode: 0o600 });
|
|
287
|
+
// Asynchronous and bounded: a hostile document cannot hold the server.
|
|
288
|
+
const text = await extractTextAsync(path, Math.min(Date.now() + EXTRACT_BUDGET_MS, callDeadline));
|
|
289
|
+
if ("error" in text)
|
|
290
|
+
skipped.push(`${name}: ${text.error}`);
|
|
291
|
+
else
|
|
292
|
+
sources.push({ name, text: text.text });
|
|
293
|
+
}
|
|
294
|
+
finally {
|
|
295
|
+
rmSync(dir, { recursive: true, force: true });
|
|
296
|
+
}
|
|
297
|
+
continue;
|
|
298
|
+
}
|
|
299
|
+
if (got.body.subarray(0, 8000).includes(0)) {
|
|
300
|
+
skipped.push(`${name}: binary (pack reads text, PDF and Word/PowerPoint/ODT files)`);
|
|
301
|
+
continue;
|
|
302
|
+
}
|
|
303
|
+
sources.push({ name, text: got.body.toString("utf8") });
|
|
304
|
+
}
|
|
305
|
+
if (files.length > FILE_LIMITS.files)
|
|
306
|
+
skipped.push(`${files.length - FILE_LIMITS.files} more file(s): at most ${FILE_LIMITS.files} per call`);
|
|
307
|
+
return { sources, skipped };
|
|
308
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
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
|
+
/** Bounds on what a handoff may hold. The brief's target is ≤400 tokens; the cap is a hard stop. */
|
|
24
|
+
export declare const HANDOFF_LIMITS: {
|
|
25
|
+
readonly briefTargetTokens: 400;
|
|
26
|
+
readonly briefChars: 6000;
|
|
27
|
+
readonly titleChars: 80;
|
|
28
|
+
readonly modelChars: 100;
|
|
29
|
+
readonly blocks: 20;
|
|
30
|
+
readonly labelChars: 80;
|
|
31
|
+
readonly blockChars: 20000;
|
|
32
|
+
readonly totalChars: 60000;
|
|
33
|
+
/** Newest handoffs kept on disk; older ones are removed when a new one is saved. */
|
|
34
|
+
readonly kept: 100;
|
|
35
|
+
/** Largest handoff.md read back (a hand-edited file could be anything). */
|
|
36
|
+
readonly readBytes: number;
|
|
37
|
+
};
|
|
38
|
+
export interface VerbatimBlock {
|
|
39
|
+
label: string;
|
|
40
|
+
text: string;
|
|
41
|
+
}
|
|
42
|
+
export interface HandoffInput {
|
|
43
|
+
brief: string;
|
|
44
|
+
verbatim?: VerbatimBlock[];
|
|
45
|
+
title?: string;
|
|
46
|
+
model?: string;
|
|
47
|
+
/** The current chat's size, when the model has a profile_context figure. */
|
|
48
|
+
chatTokens?: number;
|
|
49
|
+
/** Exchanges so far, for an estimate when there is no figure. */
|
|
50
|
+
turns?: number;
|
|
51
|
+
}
|
|
52
|
+
export interface HandoffMeta {
|
|
53
|
+
id: string;
|
|
54
|
+
title: string;
|
|
55
|
+
/** ISO timestamp. */
|
|
56
|
+
created: string;
|
|
57
|
+
model?: string;
|
|
58
|
+
/** The whole handoff.md, i.e. what a new chat starts with. */
|
|
59
|
+
tokens: number;
|
|
60
|
+
briefTokens: number;
|
|
61
|
+
blocks: Array<{
|
|
62
|
+
label: string;
|
|
63
|
+
tokens: number;
|
|
64
|
+
}>;
|
|
65
|
+
/** Secret-looking strings replaced before saving. */
|
|
66
|
+
masked: number;
|
|
67
|
+
/** Save order on this machine (wall clock in µs plus a counter): breaks ties between saves with the same `created`. */
|
|
68
|
+
order?: number;
|
|
69
|
+
}
|
|
70
|
+
export interface HandoffMath {
|
|
71
|
+
/** Tokens the current chat re-reads per turn, when known. */
|
|
72
|
+
now?: number;
|
|
73
|
+
nowSource?: "given" | "turns";
|
|
74
|
+
/** Tokens a new chat starting from the handoff re-reads. */
|
|
75
|
+
after: number;
|
|
76
|
+
nowUsd?: number;
|
|
77
|
+
afterUsd?: number;
|
|
78
|
+
nowCachedUsd?: number;
|
|
79
|
+
afterCachedUsd?: number;
|
|
80
|
+
}
|
|
81
|
+
export interface SavedHandoff {
|
|
82
|
+
meta: HandoffMeta;
|
|
83
|
+
markdown: string;
|
|
84
|
+
/** Folder it was written to; undefined when it was not stored. */
|
|
85
|
+
dir?: string;
|
|
86
|
+
maskedKinds: string[];
|
|
87
|
+
math: HandoffMath;
|
|
88
|
+
/** Folders removed to keep the newest HANDOFF_LIMITS.kept. */
|
|
89
|
+
rotated: number;
|
|
90
|
+
}
|
|
91
|
+
/** ~/.context-doctor/handoffs, under whatever home this process has. */
|
|
92
|
+
export declare function handoffDir(home?: string): string;
|
|
93
|
+
export declare function isHandoffId(id: unknown): id is string;
|
|
94
|
+
export declare function slugify(title: string): string;
|
|
95
|
+
/** Problems with an input, or an empty list. Enforced here too, not only by the MCP schema. */
|
|
96
|
+
export declare function validateHandoff(input: HandoffInput): string[];
|
|
97
|
+
/** Mask secret-looking strings. Returns the text, how many were masked, and of what kinds. */
|
|
98
|
+
export declare function maskSecrets(text: string): {
|
|
99
|
+
text: string;
|
|
100
|
+
count: number;
|
|
101
|
+
kinds: string[];
|
|
102
|
+
};
|
|
103
|
+
/** The text a new chat starts from: what is attached, pasted or copied. */
|
|
104
|
+
export declare function renderHandoffMarkdown(title: string, created: string, brief: string, blocks: VerbatimBlock[]): string;
|
|
105
|
+
/** What the current chat costs per turn vs a new chat that starts from the handoff. */
|
|
106
|
+
export declare function handoffMath(handoffTokens: number, input: Pick<HandoffInput, "chatTokens" | "turns" | "model">): HandoffMath;
|
|
107
|
+
/** "Now ~48k tokens re-read every turn … after ~600" lines, or a hint when the size is unknown. */
|
|
108
|
+
export declare function renderMath(m: HandoffMath): string;
|
|
109
|
+
/** Every saved handoff, newest first. Entries that are not ours (bad name, symlink, no meta) are skipped. */
|
|
110
|
+
export declare function listHandoffs(home?: string): HandoffMeta[];
|
|
111
|
+
/**
|
|
112
|
+
* One handoff by id, or the newest for "latest". Undefined for anything that
|
|
113
|
+
* is not a well-formed id of a saved handoff: no path from a caller (a
|
|
114
|
+
* resource URI, a CLI argument) ever reaches the filesystem as given.
|
|
115
|
+
*/
|
|
116
|
+
export declare function readHandoff(idOrLatest: string, home?: string): {
|
|
117
|
+
meta: HandoffMeta;
|
|
118
|
+
markdown: string;
|
|
119
|
+
} | undefined;
|
|
120
|
+
/**
|
|
121
|
+
* C0 and C1 control characters out, so a title or brief cannot drive a
|
|
122
|
+
* terminal (escape sequences that retitle a window or clear the screen) when
|
|
123
|
+
* the CLI prints it. Newlines and tabs stay; CRLF becomes LF.
|
|
124
|
+
*/
|
|
125
|
+
export declare function stripControls(text: string, { keepNewlines }?: {
|
|
126
|
+
keepNewlines?: boolean;
|
|
127
|
+
}): string;
|
|
128
|
+
/**
|
|
129
|
+
* Build a handoff, and store it unless `store` is false (the HTTP server keeps
|
|
130
|
+
* nothing by default). Throws with the validation problems on bad input, and
|
|
131
|
+
* with a message that names no absolute path when the folder is unsafe.
|
|
132
|
+
*/
|
|
133
|
+
export declare function saveHandoff(input: HandoffInput, { home, now, store }?: {
|
|
134
|
+
home?: string;
|
|
135
|
+
now?: Date;
|
|
136
|
+
store?: boolean;
|
|
137
|
+
}): SavedHandoff;
|
|
138
|
+
/** Where a path sits, with the home directory shown as ~. */
|
|
139
|
+
export declare function tildify(path: string, home?: string): string;
|
|
140
|
+
/** Every absolute mention of the home directory in `text` as ~ (error messages that reach a client). */
|
|
141
|
+
export declare function tildifyAll(text: string, home?: string): string;
|
|
142
|
+
/** `context-doctor handoff list`. */
|
|
143
|
+
export declare function renderHandoffList(metas: HandoffMeta[], home?: string): string;
|