@runappsai/agent 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +162 -2
  3. package/dist/agent-core.umd.js +266 -0
  4. package/dist/agent.d.ts +222 -0
  5. package/dist/agent.js +1331 -0
  6. package/dist/agent.umd.js +732 -0
  7. package/dist/browser.d.ts +2 -0
  8. package/dist/browser.js +4 -0
  9. package/dist/chat-theme.d.ts +24 -0
  10. package/dist/chat-theme.js +101 -0
  11. package/dist/chat.d.ts +271 -0
  12. package/dist/chat.js +4097 -0
  13. package/dist/compaction.d.ts +48 -0
  14. package/dist/compaction.js +208 -0
  15. package/dist/completion.d.ts +29 -0
  16. package/dist/completion.js +88 -0
  17. package/dist/context.d.ts +44 -0
  18. package/dist/context.js +177 -0
  19. package/dist/debug-panel.d.ts +40 -0
  20. package/dist/debug-panel.js +262 -0
  21. package/dist/dialogs.d.ts +7 -0
  22. package/dist/dialogs.js +231 -0
  23. package/dist/directory-fs.d.ts +5 -0
  24. package/dist/directory-fs.js +118 -0
  25. package/dist/dom.d.ts +83 -0
  26. package/dist/dom.js +163 -0
  27. package/dist/edit.d.ts +22 -0
  28. package/dist/edit.js +133 -0
  29. package/dist/file-guard.d.ts +46 -0
  30. package/dist/file-guard.js +153 -0
  31. package/dist/file-tools.d.ts +16 -0
  32. package/dist/file-tools.js +339 -0
  33. package/dist/files-panel.d.ts +60 -0
  34. package/dist/files-panel.js +613 -0
  35. package/dist/index.cjs +4848 -0
  36. package/dist/index.d.ts +37 -0
  37. package/dist/index.js +44 -0
  38. package/dist/json-schema.d.ts +3 -0
  39. package/dist/json-schema.js +141 -0
  40. package/dist/llm.d.ts +95 -0
  41. package/dist/llm.js +5 -0
  42. package/dist/markdown.d.ts +4 -0
  43. package/dist/markdown.js +265 -0
  44. package/dist/mcp.d.ts +82 -0
  45. package/dist/mcp.js +325 -0
  46. package/dist/node.cjs +402 -0
  47. package/dist/node.d.ts +78 -0
  48. package/dist/node.js +432 -0
  49. package/dist/pdf.d.ts +52 -0
  50. package/dist/pdf.js +77 -0
  51. package/dist/provider.d.ts +135 -0
  52. package/dist/provider.js +181 -0
  53. package/dist/sandbox.d.ts +33 -0
  54. package/dist/sandbox.js +219 -0
  55. package/dist/select.d.ts +30 -0
  56. package/dist/select.js +185 -0
  57. package/dist/skill-zips.d.ts +28 -0
  58. package/dist/skill-zips.js +123 -0
  59. package/dist/skills.d.ts +20 -0
  60. package/dist/skills.js +111 -0
  61. package/dist/templates.d.ts +24 -0
  62. package/dist/templates.js +136 -0
  63. package/dist/tool.d.ts +28 -0
  64. package/dist/tool.js +102 -0
  65. package/dist/types.d.ts +571 -0
  66. package/dist/types.js +7 -0
  67. package/dist/ui.cjs +6246 -0
  68. package/dist/ui.d.ts +6 -0
  69. package/dist/ui.js +11 -0
  70. package/dist/vlist.d.ts +80 -0
  71. package/dist/vlist.js +277 -0
  72. package/dist/workspace.d.ts +343 -0
  73. package/dist/workspace.js +1203 -0
  74. package/dist/zip.d.ts +26 -0
  75. package/dist/zip.js +204 -0
  76. package/docs/agent.md +228 -0
  77. package/docs/chat-ui.md +307 -0
  78. package/docs/node.md +135 -0
  79. package/docs/providers.md +176 -0
  80. package/docs/reference.md +143 -0
  81. package/docs/skills.md +131 -0
  82. package/docs/tools.md +254 -0
  83. package/docs/workspace.md +198 -0
  84. package/package.json +59 -4
package/dist/node.js ADDED
@@ -0,0 +1,432 @@
1
+ // @runappsai/agent/node — what an agent needs outside a browser: a folder
2
+ // on disk as the workspace's directory (`nodeFS`), the workspace's own
3
+ // storage on disk instead of IndexedDB (`nodeStore`: sessions, the user's
4
+ // skills, meta), dialogs in the terminal (`terminalUI`), and PDFs read with
5
+ // the pdfjs-dist package (`nodePdf`). Node 18+.
6
+ import { promises as fsp } from "node:fs";
7
+ import * as path from "node:path";
8
+ import * as os from "node:os";
9
+ import { createInterface } from "node:readline/promises";
10
+ import { configurePdf, decodeText, guessType, normalizePath } from "./index.js";
11
+ /* ------------------------------------------------------------------ */
12
+ /* Shared helpers */
13
+ /* ------------------------------------------------------------------ */
14
+ /**
15
+ * A file's content as the workspace keeps it: text when it decodes as
16
+ * UTF-8 with no control characters but whitespace and ESC; bytes otherwise
17
+ * (a disk does not remember which one was written).
18
+ */
19
+ function contentOf(buf) {
20
+ const bytes = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
21
+ for (const b of bytes)
22
+ if (b < 0x20 && b !== 0x09 && b !== 0x0a && b !== 0x0d && b !== 0x0c && b !== 0x1b)
23
+ return bytes;
24
+ return decodeText(bytes) ?? bytes;
25
+ }
26
+ /** Every regular file under `dir` (symbolic links are not followed), skipping folders named in `skip` and files `keep` refuses. */
27
+ async function walkFiles(dir, skip = new Set(), keep = () => true) {
28
+ const out = [];
29
+ const walk = async (d) => {
30
+ for (const e of await fsp.readdir(d, { withFileTypes: true }).catch(() => [])) {
31
+ const full = path.join(d, e.name);
32
+ if (e.isDirectory()) {
33
+ if (!skip.has(e.name))
34
+ await walk(full);
35
+ }
36
+ else if (e.isFile() && keep(e.name))
37
+ out.push(full);
38
+ }
39
+ };
40
+ await walk(dir);
41
+ return out;
42
+ }
43
+ /** Whether `full` is `base` or inside it. */
44
+ const within = (base, full) => full === base || full.startsWith(base.endsWith(path.sep) ? base : base + path.sep);
45
+ /**
46
+ * A folder on disk as an `AgentFS`: give it to a workspace as `dir` and the
47
+ * agent works in that folder (`openWorkspace(provider, { dir: nodeFS(process.cwd()) })`).
48
+ * Paths cannot leave the folder — neither by `..` nor through a symbolic
49
+ * link pointing outside it.
50
+ */
51
+ export function nodeFS(root, opts = {}) {
52
+ const base = path.resolve(root);
53
+ const ignore = new Set(opts.ignore ?? [".git", "node_modules"]);
54
+ let realBase = null;
55
+ const abs = async (p) => {
56
+ const full = path.join(base, normalizePath(p));
57
+ if (!within(base, full))
58
+ throw new Error(`${p} is outside the folder`);
59
+ // Where it really is: the nearest part of it that exists, with links resolved, must still be inside.
60
+ realBase ??= fsp.realpath(base).catch(() => base);
61
+ let probe = full;
62
+ for (;;) {
63
+ const real = await fsp.realpath(probe).catch(() => null);
64
+ if (real) {
65
+ if (!within(await realBase, real))
66
+ throw new Error(`${p} leads outside the folder`);
67
+ break;
68
+ }
69
+ const up = path.dirname(probe);
70
+ if (up === probe)
71
+ break;
72
+ probe = up;
73
+ }
74
+ return full;
75
+ };
76
+ const rel = (full) => "/" + path.relative(base, full).split(path.sep).join("/");
77
+ const statOf = async (full) => {
78
+ const st = await fsp.stat(full).catch(() => null);
79
+ return st && st.isFile() ? { path: rel(full), size: st.size, mtime: st.mtimeMs, contentType: guessType(full, new Uint8Array()) } : null;
80
+ };
81
+ const fs = {
82
+ description: opts.description ?? `the folder ${base}`,
83
+ async list(prefix) {
84
+ const full = await abs(prefix);
85
+ const st = await fsp.stat(full).catch(() => null);
86
+ if (!st)
87
+ return [];
88
+ if (st.isFile())
89
+ return [(await statOf(full))];
90
+ const out = [];
91
+ for (const f of await walkFiles(full, ignore)) {
92
+ const s = await statOf(f);
93
+ if (s)
94
+ out.push(s);
95
+ }
96
+ return out;
97
+ },
98
+ async stat(p) { return statOf(await abs(p)); },
99
+ async read(p) {
100
+ const buf = await fsp.readFile(await abs(p)).catch((err) => {
101
+ throw new Error(err.code === "ENOENT" ? `No such file: ${normalizePath(p)}` : err.message);
102
+ });
103
+ return contentOf(buf);
104
+ },
105
+ };
106
+ if (!opts.readonly) {
107
+ fs.write = async (p, content) => {
108
+ const full = await abs(p);
109
+ await fsp.mkdir(path.dirname(full), { recursive: true });
110
+ await fsp.writeFile(full, content);
111
+ };
112
+ fs.delete = async (p) => {
113
+ await fsp.rm(await abs(p)).catch((err) => {
114
+ throw new Error(err.code === "ENOENT" ? `No such file: ${normalizePath(p)}` : err.message);
115
+ });
116
+ };
117
+ }
118
+ return fs;
119
+ }
120
+ /* ------------------------------------------------------------------ */
121
+ /* The workspace's storage on disk */
122
+ /* ------------------------------------------------------------------ */
123
+ /** A name safe as one path segment: nothing is left that a filesystem reads specially (`/`, `\`, `.` and `..`, `*`). */
124
+ const enc = (s) => encodeURIComponent(s).replace(/[.*!'()~]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
125
+ const dec = (s) => decodeURIComponent(s);
126
+ /** JSON that keeps Uint8Arrays (meta values, session attachments). */
127
+ const toJSON = (v) => JSON.stringify(v, (_k, x) => (x instanceof Uint8Array ? { __u8: Buffer.from(x).toString("base64") } : x));
128
+ const fromJSON = (s) => JSON.parse(s, (_k, x) => (x && typeof x === "object" && typeof x.__u8 === "string" ? new Uint8Array(Buffer.from(x.__u8, "base64")) : x));
129
+ async function readJSON(file) {
130
+ try {
131
+ return fromJSON(await fsp.readFile(file, "utf8"));
132
+ }
133
+ catch {
134
+ return undefined;
135
+ }
136
+ }
137
+ let tmpSeq = 0;
138
+ /** Written to a temporary file of its own and renamed, so a crash never leaves half a file and two writes never share one. */
139
+ async function writeAtomic(file, data) {
140
+ await fsp.mkdir(path.dirname(file), { recursive: true });
141
+ const tmp = `${file}.${process.pid}.${Date.now().toString(36)}.${(tmpSeq++).toString(36)}.${Math.random().toString(36).slice(2, 8)}.tmp`;
142
+ try {
143
+ await fsp.writeFile(tmp, data);
144
+ await fsp.rename(tmp, file);
145
+ }
146
+ catch (err) {
147
+ await fsp.rm(tmp, { force: true });
148
+ throw err;
149
+ }
150
+ }
151
+ const notTmp = (name) => !name.endsWith(".tmp");
152
+ /**
153
+ * The workspace's storage in a folder (default `~/.runapps-agent`): give it
154
+ * to a workspace as `store` and its sessions, meta data and the user's
155
+ * skills — and its files, when it has no `dir` — survive the process.
156
+ * Meant for one process at a time per folder.
157
+ *
158
+ * <root>/<app>/spaces/<directory id>/files/… the directory's files
159
+ * <root>/<app>/spaces/<directory id>/meta/… its meta data (JSON)
160
+ * <root>/<app>/sessions/<directory id>/<session id>.json
161
+ *
162
+ * (Names are percent-encoded, dots included.)
163
+ */
164
+ export function nodeStore(root = path.join(os.homedir(), ".runapps-agent")) {
165
+ const base = path.resolve(root);
166
+ return {
167
+ async open(dbName, space) {
168
+ const app = path.join(base, enc(dbName));
169
+ const spaceDir = (s) => path.join(app, "spaces", enc(s));
170
+ const filesDir = path.join(spaceDir(space), "files");
171
+ const metaDir = path.join(spaceDir(space), "meta");
172
+ const sessionsDir = path.join(app, "sessions");
173
+ // Each segment encoded: a file named ".." or "a.b" is just a name here.
174
+ const fileOf = (p) => path.join(filesDir, ...normalizePath(p).split("/").filter(Boolean).map(enc));
175
+ const pathOf = (full) => "/" + path.relative(filesDir, full).split(path.sep).map(dec).join("/");
176
+ const statOf = async (full) => {
177
+ const st = await fsp.stat(full).catch(() => null);
178
+ if (!st || !st.isFile())
179
+ return null;
180
+ const p = pathOf(full);
181
+ return { path: p, size: st.size, mtime: st.mtimeMs, contentType: guessType(p, new Uint8Array()) };
182
+ };
183
+ const recordOf = async (full) => {
184
+ const [buf, st] = await Promise.all([fsp.readFile(full).catch(() => null), statOf(full)]);
185
+ if (!buf || !st)
186
+ return undefined;
187
+ const data = contentOf(buf);
188
+ return { space, path: st.path, data, contentType: guessType(st.path, data), mtime: st.mtime ?? Date.now(), layer: "work" };
189
+ };
190
+ // Only the folder asked for is walked ("/a/" → files/a).
191
+ const under = (prefix) => (prefix === "/" ? filesDir : fileOf(prefix));
192
+ const filesUnder = async (prefix) => walkFiles(under(prefix), undefined, notTmp);
193
+ const metaFile = (key) => path.join(metaDir, `${enc(key)}.json`);
194
+ const metaKeys = async () => (await fsp.readdir(metaDir).catch(() => [])).filter((n) => n.endsWith(".json")).map((n) => dec(n.slice(0, -5)));
195
+ const sessionFile = (s, id) => path.join(sessionsDir, enc(s), `${enc(id)}.json`);
196
+ return {
197
+ get: async (p) => recordOf(fileOf(p)),
198
+ stat: async (p) => statOf(fileOf(p)),
199
+ put: async (rec) => { await writeAtomic(fileOf(rec.path), rec.data); },
200
+ delete: async (p) => { await fsp.rm(fileOf(p), { force: true }); },
201
+ list: async (prefix) => {
202
+ const out = [];
203
+ for (const full of await filesUnder(prefix)) {
204
+ const r = await recordOf(full);
205
+ if (r)
206
+ out.push(r);
207
+ }
208
+ return out;
209
+ },
210
+ listStats: async (prefix) => {
211
+ const out = [];
212
+ for (const full of await filesUnder(prefix)) {
213
+ const s = await statOf(full);
214
+ if (s)
215
+ out.push(s);
216
+ }
217
+ return out;
218
+ },
219
+ getMeta: async (key) => readJSON(metaFile(key)),
220
+ putMeta: async (key, value) => { await writeAtomic(metaFile(key), toJSON(value)); },
221
+ deleteMeta: async (key) => { await fsp.rm(metaFile(key), { force: true }); },
222
+ listMeta: async (prefix) => {
223
+ const out = [];
224
+ for (const k of await metaKeys())
225
+ if (k.startsWith(prefix)) {
226
+ const v = await readJSON(metaFile(k));
227
+ if (v !== undefined)
228
+ out.push(v);
229
+ }
230
+ return out;
231
+ },
232
+ listMetaKeys: async (prefix) => (await metaKeys()).filter((k) => k.startsWith(prefix)),
233
+ getSession: async (s, id) => readJSON(sessionFile(s, id)),
234
+ putSession: async (data) => { await writeAtomic(sessionFile(data.space ?? space, data.id ?? "default"), toJSON({ ...data, space: data.space ?? space })); },
235
+ deleteSession: async (s, id) => { await fsp.rm(sessionFile(s, id), { force: true }); },
236
+ listSessions: async () => {
237
+ const out = [];
238
+ for (const full of await walkFiles(sessionsDir, undefined, (n) => n.endsWith(".json"))) {
239
+ const d = await readJSON(full);
240
+ if (d)
241
+ out.push(d);
242
+ }
243
+ return out;
244
+ },
245
+ clear: async (s = space) => {
246
+ await fsp.rm(spaceDir(s), { recursive: true, force: true });
247
+ await fsp.rm(path.join(sessionsDir, enc(s)), { recursive: true, force: true });
248
+ },
249
+ close: () => { },
250
+ };
251
+ },
252
+ };
253
+ }
254
+ const readers = new WeakMap();
255
+ /**
256
+ * Lines of `input`, queued: a line that arrives while nobody asks (typed
257
+ * ahead, or piped in) waits for the next question instead of being lost,
258
+ * as it is with readline's own `question()`; questions asked at once are
259
+ * answered in turn. One reader per input stream — a program's prompt loop
260
+ * and `terminalUI` share it. The prompt goes through readline, so editing
261
+ * the line keeps it on screen. A terminal is read all the time (Ctrl+C
262
+ * reaches readline's "SIGINT" even while no question is open) but does not
263
+ * keep the process alive between questions; a pipe is paused between them.
264
+ */
265
+ export function lineReader(opts = {}) {
266
+ const input = opts.input ?? process.stdin;
267
+ const output = opts.output ?? process.stdout;
268
+ const known = readers.get(input);
269
+ if (known)
270
+ return known;
271
+ const tty = !!input.isTTY;
272
+ const rl = createInterface({ input, output, terminal: tty });
273
+ const queue = [];
274
+ const waiters = [];
275
+ let closed = false;
276
+ const handle = input;
277
+ // Between questions: a terminal stays in flowing raw mode (so Ctrl+C is read) but stops holding the process; a pipe pauses.
278
+ const idle = () => { rl.setPrompt(""); if (tty)
279
+ handle.unref?.();
280
+ else
281
+ rl.pause(); };
282
+ const activate = () => {
283
+ const w = waiters[0];
284
+ if (!w)
285
+ return idle();
286
+ if (tty)
287
+ handle.ref?.();
288
+ rl.setPrompt(w.prompt);
289
+ rl.prompt(true); // writes the prompt and resumes reading
290
+ };
291
+ rl.on("line", (line) => {
292
+ const w = waiters.shift();
293
+ if (w) {
294
+ w.done(line);
295
+ activate();
296
+ }
297
+ else {
298
+ queue.push(line);
299
+ idle();
300
+ }
301
+ });
302
+ rl.on("close", () => {
303
+ closed = true;
304
+ readers.delete(input);
305
+ for (const w of waiters.splice(0))
306
+ w.done(null);
307
+ });
308
+ idle();
309
+ const reader = {
310
+ rl,
311
+ ask(prompt, signal) {
312
+ return new Promise((done) => {
313
+ if (!waiters.length && queue.length) {
314
+ output.write(prompt);
315
+ return done(queue.shift());
316
+ }
317
+ if (closed || signal?.aborted)
318
+ return done(null);
319
+ const w = { prompt, done };
320
+ waiters.push(w);
321
+ if (waiters.length === 1)
322
+ activate();
323
+ signal?.addEventListener("abort", () => {
324
+ const i = waiters.indexOf(w);
325
+ if (i < 0)
326
+ return;
327
+ waiters.splice(i, 1);
328
+ if (i === 0) {
329
+ output.write("\n");
330
+ activate();
331
+ }
332
+ done(null);
333
+ }, { once: true });
334
+ });
335
+ },
336
+ close() { rl.close(); },
337
+ };
338
+ readers.set(input, reader);
339
+ return reader;
340
+ }
341
+ /**
342
+ * `AgentUI` in a terminal: confirmations as y/N, choices as a numbered
343
+ * list, free text on a line (a blank line ends multi-line text). A
344
+ * question whose run is stopped is dismissed.
345
+ */
346
+ export function terminalUI(opts = {}) {
347
+ const input = opts.input ?? process.stdin;
348
+ const output = opts.output ?? process.stdout;
349
+ const color = !!output.isTTY;
350
+ const paint = (code, s) => (color ? `\x1b[${code}m${s}\x1b[0m` : s);
351
+ const write = (s) => { output.write(s); };
352
+ const viaRl = opts.rl;
353
+ const ask = opts.ask
354
+ ?? (viaRl
355
+ ? async (q, signal) => { try {
356
+ return await viaRl.question(q, signal ? { signal } : {});
357
+ }
358
+ catch {
359
+ return null;
360
+ } }
361
+ : (q, signal) => lineReader({ input, output }).ask(q, signal));
362
+ const head = (title, message) => {
363
+ write(`\n${paint("1", title)}\n`);
364
+ if (message)
365
+ write(`${paint("2", message)}\n`);
366
+ };
367
+ return {
368
+ async confirm(title, message, o = {}) {
369
+ head(title, message);
370
+ const a = await ask(`${paint(o.danger ? "31" : "36", `${o.ok ?? "Yes"} / ${o.cancel ?? "No"}`)} [y/N] `, o.signal);
371
+ return !!a && /^(y|yes|ok|是|好)$/i.test(a.trim());
372
+ },
373
+ async select(title, options, o = {}) {
374
+ head(title, o.message);
375
+ options.forEach((opt, i) => write(` ${paint("36", String(i + 1))}) ${opt.label ?? opt.value}${opt.description ? paint("2", ` — ${opt.description}`) : ""}\n`));
376
+ const hint = o.multi ? "numbers, comma-separated" : "a number";
377
+ for (;;) {
378
+ const a = await ask(`${hint}${o.allowOther ? ", or type an answer" : ""}: `, o.signal);
379
+ if (a === null || !a.trim())
380
+ return null;
381
+ const picks = a.split(",").map((x) => x.trim()).filter(Boolean);
382
+ const nums = picks.map((x) => Number(x));
383
+ if (nums.every((n) => Number.isInteger(n) && n >= 1 && n <= options.length) && (o.multi || nums.length === 1))
384
+ return nums.map((n) => options[n - 1].value);
385
+ if (o.allowOther)
386
+ return [a.trim()];
387
+ write(paint("33", `Pick ${hint} from 1 to ${options.length}.\n`));
388
+ }
389
+ },
390
+ async input(title, o = {}) {
391
+ head(title, o.message);
392
+ if (!o.multiline) {
393
+ const a = await ask(`${o.placeholder ? paint("2", `(${o.placeholder}) `) : ""}> `, o.signal);
394
+ return a === null ? null : a || o.initial || "";
395
+ }
396
+ write(paint("2", "(a blank line ends it)\n"));
397
+ const lines = [];
398
+ for (;;) {
399
+ const a = await ask("> ", o.signal);
400
+ if (a === null)
401
+ return lines.length ? lines.join("\n") : null;
402
+ if (!a.length)
403
+ return lines.join("\n");
404
+ lines.push(a);
405
+ }
406
+ },
407
+ notify(message, level = "info") {
408
+ write(`${level === "error" ? paint("31", "✗") : level === "warning" ? paint("33", "!") : paint("36", "i")} ${message}\n`);
409
+ },
410
+ };
411
+ }
412
+ /* ------------------------------------------------------------------ */
413
+ /* PDFs */
414
+ /* ------------------------------------------------------------------ */
415
+ /**
416
+ * Reads PDFs with the pdfjs-dist package (`npm i pdfjs-dist`) instead of
417
+ * the CDN copy a browser loads.
418
+ */
419
+ export function nodePdf() {
420
+ // Imported by name at run time, so neither TypeScript nor a bundler needs pdfjs-dist present.
421
+ const load = new Function("m", "return import(m)");
422
+ configurePdf({
423
+ load: async () => {
424
+ try {
425
+ return (await load("pdfjs-dist/legacy/build/pdf.mjs"));
426
+ }
427
+ catch (err) {
428
+ throw new Error(`reading PDFs in Node needs the pdfjs-dist package (npm i pdfjs-dist): ${err.message}`);
429
+ }
430
+ },
431
+ });
432
+ }
package/dist/pdf.d.ts ADDED
@@ -0,0 +1,52 @@
1
+ /** The parts of pdf.js used here. */
2
+ export interface PdfLib {
3
+ getDocument(src: {
4
+ data: Uint8Array;
5
+ isEvalSupported?: boolean;
6
+ }): {
7
+ promise: Promise<PdfDocument>;
8
+ destroy?(): Promise<void> | void;
9
+ };
10
+ GlobalWorkerOptions: {
11
+ workerSrc?: string;
12
+ workerPort?: unknown;
13
+ };
14
+ }
15
+ interface PdfDocument {
16
+ numPages: number;
17
+ getPage(n: number): Promise<{
18
+ getTextContent(): Promise<{
19
+ items: Array<{
20
+ str?: string;
21
+ hasEOL?: boolean;
22
+ }>;
23
+ }>;
24
+ cleanup?(): void;
25
+ }>;
26
+ destroy?(): Promise<void> | void;
27
+ }
28
+ /**
29
+ * Where pdf.js comes from: `url` / `workerUrl` (an app that hosts its own
30
+ * copy, or pins another version), or `load` returning the library itself
31
+ * (a bundler import, or a stub in tests).
32
+ */
33
+ export declare function configurePdf(c: {
34
+ url?: string;
35
+ workerUrl?: string;
36
+ load?: () => Promise<PdfLib>;
37
+ }): void;
38
+ /** Whether a file is a PDF: by name, type, or its `%PDF` signature. */
39
+ export declare function isPdf(path: string, contentType?: string, data?: string | Uint8Array): boolean;
40
+ /** The text of each page (up to `maxPages`, default 500). */
41
+ export declare function extractPdfText(bytes: Uint8Array, opts?: {
42
+ maxPages?: number;
43
+ }): Promise<{
44
+ pages: string[];
45
+ numPages: number;
46
+ }>;
47
+ /** The pages as one text, each under a `--- page N ---` line; a PDF with no text layer says so. */
48
+ export declare function formatPdfText(path: string, r: {
49
+ pages: string[];
50
+ numPages: number;
51
+ }): string;
52
+ export {};
package/dist/pdf.js ADDED
@@ -0,0 +1,77 @@
1
+ // PDF text, with Mozilla's pdf.js loaded only when a PDF is first read
2
+ // (≈500 KB gzip from a CDN; nothing is bundled). Pages come back as text
3
+ // with their numbers, so the agent reads a PDF like any long file.
4
+ const VERSION = "6.4.299";
5
+ const config = {
6
+ url: `https://cdn.jsdelivr.net/npm/pdfjs-dist@${VERSION}/build/pdf.min.mjs`,
7
+ workerUrl: `https://cdn.jsdelivr.net/npm/pdfjs-dist@${VERSION}/build/pdf.worker.min.mjs`,
8
+ };
9
+ let lib = null;
10
+ /**
11
+ * Where pdf.js comes from: `url` / `workerUrl` (an app that hosts its own
12
+ * copy, or pins another version), or `load` returning the library itself
13
+ * (a bundler import, or a stub in tests).
14
+ */
15
+ export function configurePdf(c) {
16
+ Object.assign(config, c);
17
+ lib = null;
18
+ }
19
+ // A plain dynamic import, kept away from bundlers that would try to resolve the URL.
20
+ const importURL = (u) => import(/* webpackIgnore: true */ /* @vite-ignore */ u);
21
+ function loadLib() {
22
+ if (!lib) {
23
+ lib = (async () => {
24
+ const mod = (config.load ? await config.load() : await importURL(config.url));
25
+ const pdfjs = mod.default?.getDocument ? mod.default : mod;
26
+ if (!config.load && typeof Worker !== "undefined" && typeof Blob !== "undefined") {
27
+ // A module worker cannot start from another origin; a same-origin blob that imports the CDN worker can.
28
+ try {
29
+ const blob = new Blob([`import ${JSON.stringify(config.workerUrl)};`], { type: "text/javascript" });
30
+ pdfjs.GlobalWorkerOptions.workerPort = new Worker(URL.createObjectURL(blob), { type: "module" });
31
+ }
32
+ catch {
33
+ pdfjs.GlobalWorkerOptions.workerSrc = config.workerUrl;
34
+ }
35
+ }
36
+ return pdfjs;
37
+ })();
38
+ lib.catch(() => { lib = null; });
39
+ }
40
+ return lib;
41
+ }
42
+ /** Whether a file is a PDF: by name, type, or its `%PDF` signature. */
43
+ export function isPdf(path, contentType, data) {
44
+ if (/\.pdf$/i.test(path) || contentType === "application/pdf")
45
+ return true;
46
+ return data instanceof Uint8Array && data.length > 4 && data[0] === 0x25 && data[1] === 0x50 && data[2] === 0x44 && data[3] === 0x46;
47
+ }
48
+ /** The text of each page (up to `maxPages`, default 500). */
49
+ export async function extractPdfText(bytes, opts = {}) {
50
+ const pdfjs = await loadLib();
51
+ // pdf.js takes ownership of the buffer it is given: hand it a copy.
52
+ const task = pdfjs.getDocument({ data: bytes.slice(), isEvalSupported: false });
53
+ const doc = await task.promise;
54
+ try {
55
+ const pages = [];
56
+ const n = Math.min(doc.numPages, opts.maxPages ?? 500);
57
+ for (let i = 1; i <= n; i++) {
58
+ const page = await doc.getPage(i);
59
+ const content = await page.getTextContent();
60
+ pages.push(content.items.map((it) => (it.str ?? "") + (it.hasEOL ? "\n" : "")).join("").replace(/[ \t]+\n/g, "\n").trim());
61
+ page.cleanup?.();
62
+ }
63
+ return { pages, numPages: doc.numPages };
64
+ }
65
+ finally {
66
+ // Newer pdf.js releases free a document through its loading task; older ones on the document.
67
+ await (task.destroy ? task.destroy() : doc.destroy?.());
68
+ }
69
+ }
70
+ /** The pages as one text, each under a `--- page N ---` line; a PDF with no text layer says so. */
71
+ export function formatPdfText(path, r) {
72
+ const head = `[PDF ${path}: ${r.numPages} page${r.numPages === 1 ? "" : "s"}${r.pages.length < r.numPages ? `, text of the first ${r.pages.length}` : ""}]`;
73
+ if (!r.pages.some((p) => p.trim())) {
74
+ return `${head}\nThis PDF has no text layer (it is probably scanned images), so there is no text to read. Tell the user; the pages would need to be read as pictures.`;
75
+ }
76
+ return [head, ...r.pages.map((p, i) => `--- page ${i + 1} ---\n${p}`)].join("\n\n");
77
+ }