@foldrun/core 19.2.0 → 20.0.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 (56) hide show
  1. package/dist/src/browser-pod.js +4 -0
  2. package/dist/src/completions.js +1 -0
  3. package/dist/src/egress.d.ts +5 -1
  4. package/dist/src/input-text.d.ts +48 -0
  5. package/dist/src/input-text.js +212 -0
  6. package/dist/src/limits.js +2 -1
  7. package/dist/src/manifest.d.ts +6 -1
  8. package/dist/src/manifest.js +8 -5
  9. package/dist/src/ops-log.js +21 -6
  10. package/dist/src/platform.d.ts +23 -0
  11. package/dist/src/platform.js +1 -0
  12. package/dist/src/records.d.ts +11 -0
  13. package/dist/src/run-container.d.ts +11 -7
  14. package/dist/src/run-container.js +50 -11
  15. package/dist/src/run-inputs.d.ts +6 -1
  16. package/dist/src/run-inputs.js +10 -2
  17. package/dist/src/run-output-refusal.d.ts +3 -0
  18. package/dist/src/run-output-refusal.js +16 -0
  19. package/dist/src/run-outputs.d.ts +134 -0
  20. package/dist/src/run-outputs.js +521 -0
  21. package/dist/src/runner.d.ts +1 -0
  22. package/dist/src/runner.js +59 -11
  23. package/dist/src/starter.js +1 -1
  24. package/dist/src/step-state.d.ts +10 -0
  25. package/dist/src/step-state.js +93 -0
  26. package/dist/src/storage.d.ts +12 -1
  27. package/dist/src/storage.js +50 -16
  28. package/dist/src/store.d.ts +25 -4
  29. package/dist/src/store.js +15 -4
  30. package/dist/src/text-tool.d.ts +177 -0
  31. package/dist/src/text-tool.js +220 -0
  32. package/dist/src/tool-names.d.ts +3 -1
  33. package/dist/src/tool-names.js +4 -2
  34. package/dist/src/workspace-revisions.js +11 -0
  35. package/package.json +1 -1
  36. package/src/browser-pod.ts +3 -0
  37. package/src/completions.ts +1 -0
  38. package/src/egress.ts +5 -2
  39. package/src/input-text.ts +215 -0
  40. package/src/limits.ts +2 -1
  41. package/src/manifest.ts +12 -5
  42. package/src/ops-log.ts +22 -6
  43. package/src/platform.ts +22 -0
  44. package/src/records.ts +11 -0
  45. package/src/run-container.ts +49 -11
  46. package/src/run-inputs.ts +10 -2
  47. package/src/run-output-refusal.ts +20 -0
  48. package/src/run-outputs.ts +597 -0
  49. package/src/runner.ts +55 -10
  50. package/src/starter.ts +1 -1
  51. package/src/step-state.ts +97 -0
  52. package/src/storage.ts +45 -15
  53. package/src/store.ts +32 -4
  54. package/src/text-tool.ts +267 -0
  55. package/src/tool-names.ts +4 -2
  56. package/src/workspace-revisions.ts +11 -0
@@ -0,0 +1,267 @@
1
+ // tools: [text] — a file in the sandbox, as text (12 Nov 2026).
2
+ //
3
+ // An agent handed a scanned contract, a photo of a receipt, a slide deck or
4
+ // a voice note used to have two bad choices: Read the bytes (an image goes to
5
+ // the model whole and costs what it costs; a .docx is a zip it cannot read;
6
+ // audio is nothing at all), or install an OCR stack mid-step and hope it
7
+ // knows Persian. `extract_text` hands the file to foldrun's own extraction
8
+ // service — Persian and English OCR, Docling for office files and PDFs,
9
+ // Whisper for speech — and gets text back.
10
+ //
11
+ // The service is not in the sandbox. Like ask_person and the colleagues'
12
+ // tools (operator.ts), the call goes out through the one live door a run pod
13
+ // has: the worker's egress proxy, at the lease address the pod already holds
14
+ // (FOLDRUN_EGRESS = http://<proxy>/e/<lease>). The proxy honours the door
15
+ // only for a lease granted `text: true` — a step whose agent holds the tool —
16
+ // and the lease names the account, so what the service is asked is billed
17
+ // and recorded against the right run.
18
+ //
19
+ // POST {base}/text/{token}?name=<basename>&lang=<fa|en|auto>&ocr=<auto|always|never>
20
+ // body: the file's bytes, application/octet-stream
21
+ // 200: ExtractResult (below) 4xx/5xx: {error: string | {message}}
22
+ //
23
+ // No proxy (a `foldrun run` on a laptop, an in-process step) means no
24
+ // service: the tool says so instead of pretending.
25
+
26
+ import fs from "node:fs";
27
+ import path from "node:path";
28
+ import { Readable } from "node:stream";
29
+ import { createSdkMcpServer, tool } from "@anthropic-ai/claude-agent-sdk";
30
+ import { z } from "zod";
31
+ import { checkPaths, expandVirtual, type Roots } from "./confine.ts";
32
+ import { operatorEndpoint } from "./operator.ts";
33
+ import type { EventExtra } from "./step-exec.ts";
34
+
35
+ /** What the extraction service answers for one file. */
36
+ export interface ExtractResult {
37
+ sha256: string;
38
+ /** image | pdf | office | html | audio | video | text … — the service's word. */
39
+ kind: string;
40
+ /** The file format it read it as (png, pdf, docx, mp3 …). */
41
+ format: string;
42
+ text: string;
43
+ pages?: number;
44
+ /** The pages read by OCR: the platform sends their numbers; a count is
45
+ * taken too. */
46
+ ocrPages?: number | number[];
47
+ /** Audio and video: how long the recording is. */
48
+ seconds?: number;
49
+ confidence?: number;
50
+ language?: string;
51
+ engine: { parser: string; speech?: string };
52
+ /** The service cut the text short. */
53
+ truncated: boolean;
54
+ warnings: string[];
55
+ /** Answered from the service's cache (same bytes, same options). */
56
+ cached: boolean;
57
+ ms: number;
58
+ }
59
+
60
+ export type TextLang = "fa" | "en" | "auto";
61
+ export type TextOcr = "auto" | "always" | "never";
62
+
63
+ /** The granted name of the tool — the same on every path. */
64
+ export const TEXT_TOOL = "mcp__foldrun_text__extract_text";
65
+ export const TEXT_SERVER = "foldrun_text";
66
+ /** The largest file sent: anything bigger is refused before a byte leaves. */
67
+ export const TEXT_MAX_FILE_BYTES = 200 * 1024 * 1024;
68
+ /** Text up to this many bytes (UTF-8) comes back whole in the tool result. */
69
+ export const TEXT_INLINE_MAX = 200 * 1024;
70
+ /** Longer text is saved to a file; this many characters of it come back. */
71
+ export const TEXT_HEAD_CHARS = 20_000;
72
+ /** Long recordings take minutes; past this the call is given up. */
73
+ export const TEXT_TIMEOUT_MS = 15 * 60_000;
74
+
75
+ type Emit = (type: "text" | "tool" | "info" | "error", text: string, extra?: EventExtra) => void;
76
+
77
+ /** The door's URL for one file. */
78
+ export function textDoorUrl(ep: { base: string; token: string }, q: { name: string; lang: TextLang; ocr: TextOcr }): string {
79
+ const query = new URLSearchParams({ name: q.name, lang: q.lang, ocr: q.ocr });
80
+ return `${ep.base}/text/${ep.token}?${query.toString()}`;
81
+ }
82
+
83
+ /** The one line above the text: what the file was, how much of it, in what
84
+ * language, and anything the service warned about. */
85
+ export function extractHeader(name: string, r: ExtractResult, chars: number): string {
86
+ const parts: string[] = [`${r.kind}${r.format && r.format !== r.kind ? ` (${r.format})` : ""}`];
87
+ const ocr = Array.isArray(r.ocrPages) ? r.ocrPages.length : typeof r.ocrPages === "number" ? r.ocrPages : 0;
88
+ if (typeof r.pages === "number") parts.push(`${r.pages} page${r.pages === 1 ? "" : "s"}${ocr ? ` (${ocr} by OCR)` : ""}`);
89
+ if (typeof r.seconds === "number") parts.push(`${fmtSeconds(r.seconds)}`);
90
+ if (r.language) parts.push(`language ${r.language}`);
91
+ if (typeof r.confidence === "number") parts.push(`confidence ${Math.round(r.confidence * 100) / 100}`);
92
+ const engine = [r.engine?.parser, r.engine?.speech].filter(Boolean).join(" + ");
93
+ if (engine) parts.push(engine);
94
+ parts.push(`${chars.toLocaleString("en-US")} chars`);
95
+ if (r.cached) parts.push("cached");
96
+ const warnings = [...(r.warnings ?? []), ...(r.truncated ? ["the service cut the text short"] : [])];
97
+ return `[extract_text] ${name}: ${parts.join(", ")}${warnings.length ? ` — warnings: ${warnings.join("; ")}` : ""}`;
98
+ }
99
+
100
+ const fmtSeconds = (s: number) => (s >= 3600 ? `${Math.floor(s / 3600)} h ${Math.round((s % 3600) / 60)} min` : s >= 60 ? `${Math.floor(s / 60)} min ${Math.round(s % 60)} s` : `${Math.round(s * 10) / 10} s`);
101
+
102
+ /** The line the system prompt gets for tools: [text]. */
103
+ export function textPromptLine(): string {
104
+ return (
105
+ "`extract_text` turns a file you can reach — an image, a scanned or text PDF, DOCX, PPTX, XLSX, EPUB, HTML, audio or video — " +
106
+ "into text with foldrun's extraction service (Persian and English OCR, document parsing, speech recognition). " +
107
+ "Give it the file's path (`workspace/…` for the workspace's folders); `lang` is fa, en or auto; `save: true` also writes `<path>.txt` beside the file. " +
108
+ "Use it rather than reading a binary file yourself. A long recording can take minutes."
109
+ );
110
+ }
111
+
112
+ /** The `extract_text` tool. `egress` is the step's FOLDRUN_EGRESS (null in
113
+ * process: the tool then refuses); the roots confine which files it may
114
+ * send and where it may write the `.txt`. `fetchImpl` is for tests. */
115
+ export function buildTextTools(opts: {
116
+ egress: string | null | undefined;
117
+ agentDir: string;
118
+ workspaceRoot: string;
119
+ libraryRoot: string;
120
+ emit?: Emit;
121
+ fetchImpl?: typeof fetch;
122
+ timeoutMs?: number;
123
+ maxFileBytes?: number;
124
+ }) {
125
+ const fetchImpl = opts.fetchImpl ?? fetch;
126
+ const roots: Roots = { agentDir: opts.agentDir, workspaceRoot: opts.workspaceRoot, libraryRoot: opts.libraryRoot };
127
+ const maxBytes = opts.maxFileBytes ?? TEXT_MAX_FILE_BYTES;
128
+ const text = (t: string) => ({ content: [{ type: "text" as const, text: t }] });
129
+ const fail = (t: string) => ({ ...text(t), isError: true });
130
+
131
+ /** Where `raw` points, or why it may not be read. The file tools' own
132
+ * rule (confine.ts): the workspace and the library, never secrets or the
133
+ * run journal; `workspace/…` from the workspace root. */
134
+ const resolve = (raw: string): { abs: string } | { error: string } => {
135
+ const verdict = checkPaths("Read", { file_path: raw }, roots);
136
+ if (!verdict.ok) return { error: (verdict.reason ?? `"${raw}" may not be read`).replace(/^Read was denied/, "extract_text was refused") };
137
+ return { abs: expandVirtual(raw, roots)?.abs ?? path.resolve(roots.agentDir, raw) };
138
+ };
139
+
140
+ /** Write the text where the agent can find it: `<path>.txt` beside the
141
+ * file when the file tools would allow that write, else the agent's own
142
+ * outputs/. Never over an existing file (a person's notes, an earlier
143
+ * save): each place is created new or skipped, the last a stamped name.
144
+ * Returns the path as the agent should write it, or null. */
145
+ const saveText = (raw: string, abs: string, body: string): { shown: string; abs: string } | null => {
146
+ const besideRaw = `${raw}.txt`;
147
+ const attempts: { shown: string; check: string }[] = [
148
+ { shown: besideRaw, check: besideRaw },
149
+ { shown: `outputs/${path.basename(abs)}.txt`, check: `outputs/${path.basename(abs)}.txt` },
150
+ { shown: `outputs/${path.basename(abs)}.${Date.now()}.txt`, check: `outputs/${path.basename(abs)}.${Date.now()}.txt` },
151
+ ];
152
+ for (const a of attempts) {
153
+ const verdict = checkPaths("Write", { file_path: a.check }, roots);
154
+ if (!verdict.ok) continue;
155
+ const target = expandVirtual(a.check, roots)?.abs ?? path.resolve(roots.agentDir, a.check);
156
+ try {
157
+ fs.mkdirSync(path.dirname(target), { recursive: true });
158
+ fs.writeFileSync(target, body, { flag: "wx" });
159
+ return { shown: a.shown, abs: target };
160
+ } catch {
161
+ /* the next place */
162
+ }
163
+ }
164
+ return null;
165
+ };
166
+
167
+ const extract = tool(
168
+ "extract_text",
169
+ "Turn a file into text: an image or a scanned PDF (OCR, Persian and English), a text PDF, DOCX, PPTX, XLSX, EPUB or HTML (document parsing), audio or video (speech recognition). Returns a one-line header (kind, pages or length, language, warnings) and the text. Very long text returns its start; ask again with save: true to keep all of it in <path>.txt (the second call is answered from the cache).",
170
+ {
171
+ path: z.string().describe("The file, relative to your agent folder, or workspace/… for the workspace (workspace/storage/scan.pdf)"),
172
+ lang: z.enum(["fa", "en", "auto"]).optional().describe("The language of the text or speech: fa, en, or auto (default) to detect it"),
173
+ ocr: z.enum(["auto", "always", "never"]).optional().describe("auto (default): OCR only pages with no text layer; always: OCR every page; never: the text layer only"),
174
+ save: z.boolean().optional().describe("Also write the text to <path>.txt beside the file, never over an existing file (default false)"),
175
+ },
176
+ async (args) => {
177
+ const raw = String(args.path ?? "").trim();
178
+ const lang: TextLang = args.lang === "fa" || args.lang === "en" ? args.lang : "auto";
179
+ const ocr: TextOcr = args.ocr === "always" || args.ocr === "never" ? args.ocr : "auto";
180
+ if (!raw) return fail("extract_text needs `path`: the file to turn into text.");
181
+ const ep = operatorEndpoint(opts.egress);
182
+ if (!ep) {
183
+ return fail(
184
+ "Text extraction needs a platform run: it is foldrun's extraction service, reached through the step's egress proxy, and this step has none (a local or in-process run). Nothing was sent.",
185
+ );
186
+ }
187
+ const where = resolve(raw);
188
+ if ("error" in where) return fail(where.error);
189
+ let size: number;
190
+ try {
191
+ const st = fs.statSync(where.abs);
192
+ if (!st.isFile()) return fail(`extract_text: "${raw}" is not a file.`);
193
+ size = st.size;
194
+ } catch {
195
+ return fail(`extract_text: "${raw}" does not exist.`);
196
+ }
197
+ if (size === 0) return fail(`extract_text: "${raw}" is empty.`);
198
+ if (size > maxBytes) {
199
+ return fail(`extract_text: "${raw}" is ${fmtMb(size)}; the largest file it takes is ${fmtMb(maxBytes)}. Split it (pages, or a shorter clip) and extract the parts. Nothing was sent.`);
200
+ }
201
+ const name = path.basename(where.abs);
202
+ const started = Date.now();
203
+ let res: Response;
204
+ try {
205
+ res = await fetchImpl(textDoorUrl(ep, { name, lang, ocr }), {
206
+ method: "POST",
207
+ headers: { "content-type": "application/octet-stream", "content-length": String(size) },
208
+ // Streamed, not read whole: a 200 MB recording stays on disk.
209
+ body: Readable.toWeb(fs.createReadStream(where.abs)) as unknown as BodyInit,
210
+ duplex: "half",
211
+ signal: AbortSignal.timeout(opts.timeoutMs ?? TEXT_TIMEOUT_MS),
212
+ } as RequestInit);
213
+ } catch (err) {
214
+ const e = err as { name?: string; message?: string };
215
+ const why = e?.name === "TimeoutError" ? `no answer after ${Math.round((opts.timeoutMs ?? TEXT_TIMEOUT_MS) / 60_000)} min` : (e?.message ?? String(err));
216
+ opts.emit?.("error", `extract_text: ${raw} — ${why}`);
217
+ return fail(`Text extraction failed: ${why}.`);
218
+ }
219
+ const body = (await res.json().catch(() => null)) as Record<string, unknown> | null;
220
+ if (!res.ok || !body || typeof body.text !== "string") {
221
+ const errField = body?.error;
222
+ const message =
223
+ typeof errField === "string"
224
+ ? errField
225
+ : errField && typeof (errField as { message?: unknown }).message === "string"
226
+ ? String((errField as { message: string }).message)
227
+ : res.ok
228
+ ? "the extraction service answered without text"
229
+ : `the extraction service answered ${res.status}`;
230
+ opts.emit?.("error", `extract_text: ${raw} — ${message}`);
231
+ return fail(`Text extraction failed: ${message}`);
232
+ }
233
+ const r = { ...(body as unknown as ExtractResult), warnings: Array.isArray(body.warnings) ? (body.warnings as unknown[]).map(String) : [] };
234
+ const all = r.text;
235
+ const header = extractHeader(name, r, all.length);
236
+ opts.emit?.("info", `extract_text: ${raw} → ${r.kind}, ${all.length} chars in ${Date.now() - started} ms${r.cached ? " (cached)" : ""}`);
237
+
238
+ if (Buffer.byteLength(all, "utf8") <= TEXT_INLINE_MAX) {
239
+ if (!args.save) return text(`${header}\n\n${all}`);
240
+ const saved = saveText(raw, where.abs, all);
241
+ const note = saved ? `Saved to ${saved.shown}.` : `Could not save it beside the file or in outputs/.`;
242
+ return text(`${header}\n${note}\n\n${all}`);
243
+ }
244
+ // Too long to hand back whole: the start comes back; the whole text is
245
+ // written only when asked (save: true) — a read never writes on its own.
246
+ const saved = args.save ? saveText(raw, where.abs, all) : null;
247
+ const head = all.slice(0, TEXT_HEAD_CHARS);
248
+ const total = all.length.toLocaleString("en-US");
249
+ const note = saved
250
+ ? `The text is ${total} characters, too long to return whole: all of it is in ${saved.shown} — read it in parts. The first ${head.length.toLocaleString("en-US")} follow.`
251
+ : args.save
252
+ ? `The text is ${total} characters, too long to return whole, and it could not be saved beside the file or in outputs/. The first ${head.length.toLocaleString("en-US")} follow.`
253
+ : `The text is ${total} characters, too long to return whole. The first ${head.length.toLocaleString("en-US")} follow; call extract_text again with save: true to keep all of it in a file (the second call is answered from the cache).`;
254
+ return text(`${header}\n${note}\n\n${head}`);
255
+ },
256
+ );
257
+ return {
258
+ server: createSdkMcpServer({ name: TEXT_SERVER, version: "1.0.0", tools: [extract] }),
259
+ /** The tool's own function, for tests. */
260
+ call: (args: { path: string; lang?: TextLang; ocr?: TextOcr; save?: boolean }) =>
261
+ extract.handler({ path: args.path, lang: args.lang, ocr: args.ocr, save: args.save }, {}),
262
+ toolNames: [TEXT_TOOL],
263
+ promptLines: [textPromptLine()],
264
+ };
265
+ }
266
+
267
+ const fmtMb = (n: number) => `${Math.round((n / (1024 * 1024)) * 10) / 10} MB`;
package/src/tool-names.ts CHANGED
@@ -51,8 +51,10 @@ export const BUILTIN_TOOLS = new Set([
51
51
 
52
52
  /** The platform's own groups, served in-process rather than by the SDK.
53
53
  * `install` is granted to every agent anyway (install-tool.ts); naming it is
54
- * accepted so a file that says so is not flagged. */
55
- export const PLATFORM_GROUPS = new Set(["search", "history", "desks", "ask", "peers", "install"]);
54
+ * accepted so a file that says so is not flagged. `text` is extract_text
55
+ * (text-tool.ts) — named `text`, not `extract`, because `extract` is
56
+ * already one of the web tool's actions (`limits: {web.extract: 5}`). */
57
+ export const PLATFORM_GROUPS = new Set(["search", "history", "desks", "ask", "peers", "install", "text"]);
56
58
 
57
59
  /** Would this name resolve to something the runtime provides? Built-ins win a
58
60
  * clash, so a tool file of the same name is shadowed rather than granted. */
@@ -58,6 +58,7 @@ import { headsOf, loadManifest, manifestsAt, manifestsOf, publish, restore, requ
58
58
  import { OpIdReused, type Revision, type WorkspaceRef } from "./revision-store.ts";
59
59
  import { pruneStateRevisions, type StateRetention } from "./state-retention.ts";
60
60
  import type { SweepMarks } from "./blob-sweeper.ts";
61
+ import { dropTenantOutputs, dropWorkspaceOutputs, moveWorkspaceOutputs, settleRunOutputs } from "./run-outputs.ts";
61
62
 
62
63
  // ------------------------------------------------------------- the backend
63
64
 
@@ -515,6 +516,7 @@ const lifecycleBusy = new Set<string>(); // keys a lifecycle call is handling (t
515
516
  const background = new Set<Promise<unknown>>();
516
517
  export async function settleLifecycle(): Promise<void> {
517
518
  while (background.size) await Promise.allSettled([...background]);
519
+ await settleRunOutputs();
518
520
  }
519
521
  function inBackground(p: Promise<unknown>): void {
520
522
  const q = p.finally(() => background.delete(q));
@@ -567,6 +569,8 @@ export async function dropWorkspaceRevisions(tenant: string, workspace: string,
567
569
  await before?.catch(() => {});
568
570
  try {
569
571
  await deps.revisions.drop({ tenant, workspace });
572
+ // The run outputs published to the blob store (run-outputs.ts) are this workspace's too.
573
+ await dropWorkspaceOutputs(tenant, workspace);
570
574
  } catch (err) {
571
575
  // Nothing was removed and the workspace stays: whatever was queued is lost to the queue, so it is reconciled from the folder.
572
576
  marked.add(k);
@@ -576,6 +580,7 @@ export async function dropWorkspaceRevisions(tenant: string, workspace: string,
576
580
  remove?.();
577
581
  dropJournal(tenant, workspace);
578
582
  await deps.revisions.drop({ tenant, workspace });
583
+ await dropWorkspaceOutputs(tenant, workspace);
579
584
  marked.delete(k);
580
585
  verified.delete(k);
581
586
  } finally {
@@ -599,6 +604,7 @@ export async function dropTenantRevisions(tenant: string): Promise<void> {
599
604
  verified.delete(k);
600
605
  }
601
606
  await deps.revisions.drop({ tenant });
607
+ await dropTenantOutputs(tenant);
602
608
  await (deps.blobs as Partial<BlobSweeper>).purgeTenant?.(tenant);
603
609
  }
604
610
 
@@ -633,11 +639,16 @@ export async function moveWorkspaceRevisions(tenant: string, from: string, to: s
633
639
  // process left for it is stale.
634
640
  dropJournal(tenant, to);
635
641
  await deps.revisions.move(tenant, from, to);
642
+ await moveWorkspaceOutputs(tenant, from, to).catch(async (err) => {
643
+ await deps.revisions.move(tenant, to, from).catch((e) => opsError("revisions.move_back_failed", e, { tenant, workspace: from, to }));
644
+ throw err;
645
+ });
636
646
  if (rename) {
637
647
  try {
638
648
  rename();
639
649
  } catch (err) {
640
650
  await deps.revisions.move(tenant, to, from).catch((e) => opsError("revisions.move_back_failed", e, { tenant, workspace: from, to }));
651
+ await moveWorkspaceOutputs(tenant, to, from).catch((e) => opsError("run_outputs.move_back_failed", e, { tenant, workspace: from, to }));
641
652
  throw err;
642
653
  }
643
654
  }