@foldrun/core 19.3.0 → 20.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 (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/secrets.d.ts +15 -1
  24. package/dist/src/secrets.js +34 -15
  25. package/dist/src/starter.js +1 -1
  26. package/dist/src/step-state.d.ts +10 -0
  27. package/dist/src/step-state.js +93 -0
  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/secrets.ts +58 -16
  51. package/src/starter.ts +1 -1
  52. package/src/step-state.ts +97 -0
  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,177 @@
1
+ import type { EventExtra } from "./step-exec.ts";
2
+ /** What the extraction service answers for one file. */
3
+ export interface ExtractResult {
4
+ sha256: string;
5
+ /** image | pdf | office | html | audio | video | text … — the service's word. */
6
+ kind: string;
7
+ /** The file format it read it as (png, pdf, docx, mp3 …). */
8
+ format: string;
9
+ text: string;
10
+ pages?: number;
11
+ /** The pages read by OCR: the platform sends their numbers; a count is
12
+ * taken too. */
13
+ ocrPages?: number | number[];
14
+ /** Audio and video: how long the recording is. */
15
+ seconds?: number;
16
+ confidence?: number;
17
+ language?: string;
18
+ engine: {
19
+ parser: string;
20
+ speech?: string;
21
+ };
22
+ /** The service cut the text short. */
23
+ truncated: boolean;
24
+ warnings: string[];
25
+ /** Answered from the service's cache (same bytes, same options). */
26
+ cached: boolean;
27
+ ms: number;
28
+ }
29
+ export type TextLang = "fa" | "en" | "auto";
30
+ export type TextOcr = "auto" | "always" | "never";
31
+ /** The granted name of the tool — the same on every path. */
32
+ export declare const TEXT_TOOL = "mcp__foldrun_text__extract_text";
33
+ export declare const TEXT_SERVER = "foldrun_text";
34
+ /** The largest file sent: anything bigger is refused before a byte leaves. */
35
+ export declare const TEXT_MAX_FILE_BYTES: number;
36
+ /** Text up to this many bytes (UTF-8) comes back whole in the tool result. */
37
+ export declare const TEXT_INLINE_MAX: number;
38
+ /** Longer text is saved to a file; this many characters of it come back. */
39
+ export declare const TEXT_HEAD_CHARS = 20000;
40
+ /** Long recordings take minutes; past this the call is given up. */
41
+ export declare const TEXT_TIMEOUT_MS: number;
42
+ type Emit = (type: "text" | "tool" | "info" | "error", text: string, extra?: EventExtra) => void;
43
+ /** The door's URL for one file. */
44
+ export declare function textDoorUrl(ep: {
45
+ base: string;
46
+ token: string;
47
+ }, q: {
48
+ name: string;
49
+ lang: TextLang;
50
+ ocr: TextOcr;
51
+ }): string;
52
+ /** The one line above the text: what the file was, how much of it, in what
53
+ * language, and anything the service warned about. */
54
+ export declare function extractHeader(name: string, r: ExtractResult, chars: number): string;
55
+ /** The line the system prompt gets for tools: [text]. */
56
+ export declare function textPromptLine(): string;
57
+ /** The `extract_text` tool. `egress` is the step's FOLDRUN_EGRESS (null in
58
+ * process: the tool then refuses); the roots confine which files it may
59
+ * send and where it may write the `.txt`. `fetchImpl` is for tests. */
60
+ export declare function buildTextTools(opts: {
61
+ egress: string | null | undefined;
62
+ agentDir: string;
63
+ workspaceRoot: string;
64
+ libraryRoot: string;
65
+ emit?: Emit;
66
+ fetchImpl?: typeof fetch;
67
+ timeoutMs?: number;
68
+ maxFileBytes?: number;
69
+ }): {
70
+ server: import("@anthropic-ai/claude-agent-sdk").McpSdkServerConfigWithInstance;
71
+ /** The tool's own function, for tests. */
72
+ call: (args: {
73
+ path: string;
74
+ lang?: TextLang;
75
+ ocr?: TextOcr;
76
+ save?: boolean;
77
+ }) => Promise<{
78
+ [x: string]: unknown;
79
+ _meta?: {
80
+ [x: string]: unknown;
81
+ progressToken?: string | number | undefined;
82
+ "io.modelcontextprotocol/related-task"?: {
83
+ taskId: string;
84
+ } | undefined;
85
+ } | undefined;
86
+ content: ({
87
+ type: "text";
88
+ text: string;
89
+ annotations?: {
90
+ audience?: ("assistant" | "user")[] | undefined;
91
+ priority?: number | undefined;
92
+ lastModified?: string | undefined;
93
+ } | undefined;
94
+ _meta?: {
95
+ [x: string]: unknown;
96
+ } | undefined;
97
+ } | {
98
+ type: "image";
99
+ data: string;
100
+ mimeType: string;
101
+ annotations?: {
102
+ audience?: ("assistant" | "user")[] | undefined;
103
+ priority?: number | undefined;
104
+ lastModified?: string | undefined;
105
+ } | undefined;
106
+ _meta?: {
107
+ [x: string]: unknown;
108
+ } | undefined;
109
+ } | {
110
+ type: "audio";
111
+ data: string;
112
+ mimeType: string;
113
+ annotations?: {
114
+ audience?: ("assistant" | "user")[] | undefined;
115
+ priority?: number | undefined;
116
+ lastModified?: string | undefined;
117
+ } | undefined;
118
+ _meta?: {
119
+ [x: string]: unknown;
120
+ } | undefined;
121
+ } | {
122
+ uri: string;
123
+ description?: string | undefined;
124
+ mimeType?: string | undefined;
125
+ size?: number | undefined;
126
+ annotations?: {
127
+ audience?: ("assistant" | "user")[] | undefined;
128
+ priority?: number | undefined;
129
+ lastModified?: string | undefined;
130
+ } | undefined;
131
+ _meta?: {
132
+ [x: string]: unknown;
133
+ } | undefined;
134
+ icons?: {
135
+ src: string;
136
+ mimeType?: string | undefined;
137
+ sizes?: string[] | undefined;
138
+ theme?: "dark" | "light" | undefined;
139
+ }[] | undefined;
140
+ name: string;
141
+ title?: string | undefined;
142
+ type: "resource_link";
143
+ } | {
144
+ type: "resource";
145
+ resource: {
146
+ uri: string;
147
+ mimeType?: string | undefined;
148
+ _meta?: {
149
+ [x: string]: unknown;
150
+ } | undefined;
151
+ text: string;
152
+ } | {
153
+ uri: string;
154
+ mimeType?: string | undefined;
155
+ _meta?: {
156
+ [x: string]: unknown;
157
+ } | undefined;
158
+ blob: string;
159
+ };
160
+ annotations?: {
161
+ audience?: ("assistant" | "user")[] | undefined;
162
+ priority?: number | undefined;
163
+ lastModified?: string | undefined;
164
+ } | undefined;
165
+ _meta?: {
166
+ [x: string]: unknown;
167
+ } | undefined;
168
+ })[];
169
+ structuredContent?: {
170
+ [x: string]: unknown;
171
+ } | undefined;
172
+ isError?: boolean | undefined;
173
+ }>;
174
+ toolNames: string[];
175
+ promptLines: string[];
176
+ };
177
+ export {};
@@ -0,0 +1,220 @@
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
+ import fs from "node:fs";
26
+ import path from "node:path";
27
+ import { Readable } from "node:stream";
28
+ import { createSdkMcpServer, tool } from "@anthropic-ai/claude-agent-sdk";
29
+ import { z } from "zod";
30
+ import { checkPaths, expandVirtual } from "./confine.js";
31
+ import { operatorEndpoint } from "./operator.js";
32
+ /** The granted name of the tool — the same on every path. */
33
+ export const TEXT_TOOL = "mcp__foldrun_text__extract_text";
34
+ export const TEXT_SERVER = "foldrun_text";
35
+ /** The largest file sent: anything bigger is refused before a byte leaves. */
36
+ export const TEXT_MAX_FILE_BYTES = 200 * 1024 * 1024;
37
+ /** Text up to this many bytes (UTF-8) comes back whole in the tool result. */
38
+ export const TEXT_INLINE_MAX = 200 * 1024;
39
+ /** Longer text is saved to a file; this many characters of it come back. */
40
+ export const TEXT_HEAD_CHARS = 20_000;
41
+ /** Long recordings take minutes; past this the call is given up. */
42
+ export const TEXT_TIMEOUT_MS = 15 * 60_000;
43
+ /** The door's URL for one file. */
44
+ export function textDoorUrl(ep, q) {
45
+ const query = new URLSearchParams({ name: q.name, lang: q.lang, ocr: q.ocr });
46
+ return `${ep.base}/text/${ep.token}?${query.toString()}`;
47
+ }
48
+ /** The one line above the text: what the file was, how much of it, in what
49
+ * language, and anything the service warned about. */
50
+ export function extractHeader(name, r, chars) {
51
+ const parts = [`${r.kind}${r.format && r.format !== r.kind ? ` (${r.format})` : ""}`];
52
+ const ocr = Array.isArray(r.ocrPages) ? r.ocrPages.length : typeof r.ocrPages === "number" ? r.ocrPages : 0;
53
+ if (typeof r.pages === "number")
54
+ parts.push(`${r.pages} page${r.pages === 1 ? "" : "s"}${ocr ? ` (${ocr} by OCR)` : ""}`);
55
+ if (typeof r.seconds === "number")
56
+ parts.push(`${fmtSeconds(r.seconds)}`);
57
+ if (r.language)
58
+ parts.push(`language ${r.language}`);
59
+ if (typeof r.confidence === "number")
60
+ parts.push(`confidence ${Math.round(r.confidence * 100) / 100}`);
61
+ const engine = [r.engine?.parser, r.engine?.speech].filter(Boolean).join(" + ");
62
+ if (engine)
63
+ parts.push(engine);
64
+ parts.push(`${chars.toLocaleString("en-US")} chars`);
65
+ if (r.cached)
66
+ parts.push("cached");
67
+ const warnings = [...(r.warnings ?? []), ...(r.truncated ? ["the service cut the text short"] : [])];
68
+ return `[extract_text] ${name}: ${parts.join(", ")}${warnings.length ? ` — warnings: ${warnings.join("; ")}` : ""}`;
69
+ }
70
+ const fmtSeconds = (s) => (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`);
71
+ /** The line the system prompt gets for tools: [text]. */
72
+ export function textPromptLine() {
73
+ return ("`extract_text` turns a file you can reach — an image, a scanned or text PDF, DOCX, PPTX, XLSX, EPUB, HTML, audio or video — " +
74
+ "into text with foldrun's extraction service (Persian and English OCR, document parsing, speech recognition). " +
75
+ "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. " +
76
+ "Use it rather than reading a binary file yourself. A long recording can take minutes.");
77
+ }
78
+ /** The `extract_text` tool. `egress` is the step's FOLDRUN_EGRESS (null in
79
+ * process: the tool then refuses); the roots confine which files it may
80
+ * send and where it may write the `.txt`. `fetchImpl` is for tests. */
81
+ export function buildTextTools(opts) {
82
+ const fetchImpl = opts.fetchImpl ?? fetch;
83
+ const roots = { agentDir: opts.agentDir, workspaceRoot: opts.workspaceRoot, libraryRoot: opts.libraryRoot };
84
+ const maxBytes = opts.maxFileBytes ?? TEXT_MAX_FILE_BYTES;
85
+ const text = (t) => ({ content: [{ type: "text", text: t }] });
86
+ const fail = (t) => ({ ...text(t), isError: true });
87
+ /** Where `raw` points, or why it may not be read. The file tools' own
88
+ * rule (confine.ts): the workspace and the library, never secrets or the
89
+ * run journal; `workspace/…` from the workspace root. */
90
+ const resolve = (raw) => {
91
+ const verdict = checkPaths("Read", { file_path: raw }, roots);
92
+ if (!verdict.ok)
93
+ return { error: (verdict.reason ?? `"${raw}" may not be read`).replace(/^Read was denied/, "extract_text was refused") };
94
+ return { abs: expandVirtual(raw, roots)?.abs ?? path.resolve(roots.agentDir, raw) };
95
+ };
96
+ /** Write the text where the agent can find it: `<path>.txt` beside the
97
+ * file when the file tools would allow that write, else the agent's own
98
+ * outputs/. Never over an existing file (a person's notes, an earlier
99
+ * save): each place is created new or skipped, the last a stamped name.
100
+ * Returns the path as the agent should write it, or null. */
101
+ const saveText = (raw, abs, body) => {
102
+ const besideRaw = `${raw}.txt`;
103
+ const attempts = [
104
+ { shown: besideRaw, check: besideRaw },
105
+ { shown: `outputs/${path.basename(abs)}.txt`, check: `outputs/${path.basename(abs)}.txt` },
106
+ { shown: `outputs/${path.basename(abs)}.${Date.now()}.txt`, check: `outputs/${path.basename(abs)}.${Date.now()}.txt` },
107
+ ];
108
+ for (const a of attempts) {
109
+ const verdict = checkPaths("Write", { file_path: a.check }, roots);
110
+ if (!verdict.ok)
111
+ continue;
112
+ const target = expandVirtual(a.check, roots)?.abs ?? path.resolve(roots.agentDir, a.check);
113
+ try {
114
+ fs.mkdirSync(path.dirname(target), { recursive: true });
115
+ fs.writeFileSync(target, body, { flag: "wx" });
116
+ return { shown: a.shown, abs: target };
117
+ }
118
+ catch {
119
+ /* the next place */
120
+ }
121
+ }
122
+ return null;
123
+ };
124
+ const extract = tool("extract_text", "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).", {
125
+ path: z.string().describe("The file, relative to your agent folder, or workspace/… for the workspace (workspace/storage/scan.pdf)"),
126
+ lang: z.enum(["fa", "en", "auto"]).optional().describe("The language of the text or speech: fa, en, or auto (default) to detect it"),
127
+ 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"),
128
+ save: z.boolean().optional().describe("Also write the text to <path>.txt beside the file, never over an existing file (default false)"),
129
+ }, async (args) => {
130
+ const raw = String(args.path ?? "").trim();
131
+ const lang = args.lang === "fa" || args.lang === "en" ? args.lang : "auto";
132
+ const ocr = args.ocr === "always" || args.ocr === "never" ? args.ocr : "auto";
133
+ if (!raw)
134
+ return fail("extract_text needs `path`: the file to turn into text.");
135
+ const ep = operatorEndpoint(opts.egress);
136
+ if (!ep) {
137
+ return fail("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.");
138
+ }
139
+ const where = resolve(raw);
140
+ if ("error" in where)
141
+ return fail(where.error);
142
+ let size;
143
+ try {
144
+ const st = fs.statSync(where.abs);
145
+ if (!st.isFile())
146
+ return fail(`extract_text: "${raw}" is not a file.`);
147
+ size = st.size;
148
+ }
149
+ catch {
150
+ return fail(`extract_text: "${raw}" does not exist.`);
151
+ }
152
+ if (size === 0)
153
+ return fail(`extract_text: "${raw}" is empty.`);
154
+ if (size > maxBytes) {
155
+ 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.`);
156
+ }
157
+ const name = path.basename(where.abs);
158
+ const started = Date.now();
159
+ let res;
160
+ try {
161
+ res = await fetchImpl(textDoorUrl(ep, { name, lang, ocr }), {
162
+ method: "POST",
163
+ headers: { "content-type": "application/octet-stream", "content-length": String(size) },
164
+ // Streamed, not read whole: a 200 MB recording stays on disk.
165
+ body: Readable.toWeb(fs.createReadStream(where.abs)),
166
+ duplex: "half",
167
+ signal: AbortSignal.timeout(opts.timeoutMs ?? TEXT_TIMEOUT_MS),
168
+ });
169
+ }
170
+ catch (err) {
171
+ const e = err;
172
+ const why = e?.name === "TimeoutError" ? `no answer after ${Math.round((opts.timeoutMs ?? TEXT_TIMEOUT_MS) / 60_000)} min` : (e?.message ?? String(err));
173
+ opts.emit?.("error", `extract_text: ${raw} — ${why}`);
174
+ return fail(`Text extraction failed: ${why}.`);
175
+ }
176
+ const body = (await res.json().catch(() => null));
177
+ if (!res.ok || !body || typeof body.text !== "string") {
178
+ const errField = body?.error;
179
+ const message = typeof errField === "string"
180
+ ? errField
181
+ : errField && typeof errField.message === "string"
182
+ ? String(errField.message)
183
+ : res.ok
184
+ ? "the extraction service answered without text"
185
+ : `the extraction service answered ${res.status}`;
186
+ opts.emit?.("error", `extract_text: ${raw} — ${message}`);
187
+ return fail(`Text extraction failed: ${message}`);
188
+ }
189
+ const r = { ...body, warnings: Array.isArray(body.warnings) ? body.warnings.map(String) : [] };
190
+ const all = r.text;
191
+ const header = extractHeader(name, r, all.length);
192
+ opts.emit?.("info", `extract_text: ${raw} → ${r.kind}, ${all.length} chars in ${Date.now() - started} ms${r.cached ? " (cached)" : ""}`);
193
+ if (Buffer.byteLength(all, "utf8") <= TEXT_INLINE_MAX) {
194
+ if (!args.save)
195
+ return text(`${header}\n\n${all}`);
196
+ const saved = saveText(raw, where.abs, all);
197
+ const note = saved ? `Saved to ${saved.shown}.` : `Could not save it beside the file or in outputs/.`;
198
+ return text(`${header}\n${note}\n\n${all}`);
199
+ }
200
+ // Too long to hand back whole: the start comes back; the whole text is
201
+ // written only when asked (save: true) — a read never writes on its own.
202
+ const saved = args.save ? saveText(raw, where.abs, all) : null;
203
+ const head = all.slice(0, TEXT_HEAD_CHARS);
204
+ const total = all.length.toLocaleString("en-US");
205
+ const note = saved
206
+ ? `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.`
207
+ : args.save
208
+ ? `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.`
209
+ : `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).`;
210
+ return text(`${header}\n${note}\n\n${head}`);
211
+ });
212
+ return {
213
+ server: createSdkMcpServer({ name: TEXT_SERVER, version: "1.0.0", tools: [extract] }),
214
+ /** The tool's own function, for tests. */
215
+ call: (args) => extract.handler({ path: args.path, lang: args.lang, ocr: args.ocr, save: args.save }, {}),
216
+ toolNames: [TEXT_TOOL],
217
+ promptLines: [textPromptLine()],
218
+ };
219
+ }
220
+ const fmtMb = (n) => `${Math.round((n / (1024 * 1024)) * 10) / 10} MB`;
@@ -14,7 +14,9 @@ export declare const RETIRED_TOOLS: Record<string, string>;
14
14
  export declare const BUILTIN_TOOLS: Set<string>;
15
15
  /** The platform's own groups, served in-process rather than by the SDK.
16
16
  * `install` is granted to every agent anyway (install-tool.ts); naming it is
17
- * accepted so a file that says so is not flagged. */
17
+ * accepted so a file that says so is not flagged. `text` is extract_text
18
+ * (text-tool.ts) — named `text`, not `extract`, because `extract` is
19
+ * already one of the web tool's actions (`limits: {web.extract: 5}`). */
18
20
  export declare const PLATFORM_GROUPS: Set<string>;
19
21
  /** Would this name resolve to something the runtime provides? Built-ins win a
20
22
  * clash, so a tool file of the same name is shadowed rather than granted. */
@@ -46,8 +46,10 @@ export const BUILTIN_TOOLS = new Set([
46
46
  ]);
47
47
  /** The platform's own groups, served in-process rather than by the SDK.
48
48
  * `install` is granted to every agent anyway (install-tool.ts); naming it is
49
- * accepted so a file that says so is not flagged. */
50
- export const PLATFORM_GROUPS = new Set(["search", "history", "desks", "ask", "peers", "install"]);
49
+ * accepted so a file that says so is not flagged. `text` is extract_text
50
+ * (text-tool.ts) — named `text`, not `extract`, because `extract` is
51
+ * already one of the web tool's actions (`limits: {web.extract: 5}`). */
52
+ export const PLATFORM_GROUPS = new Set(["search", "history", "desks", "ask", "peers", "install", "text"]);
51
53
  /** Would this name resolve to something the runtime provides? Built-ins win a
52
54
  * clash, so a tool file of the same name is shadowed rather than granted. */
53
55
  export function isRuntimeTool(name) {
@@ -44,6 +44,7 @@ import { blobObjectKey, diffManifests, emptyManifest, entryId, EMPTY_MANIFEST_ID
44
44
  import { headsOf, loadManifest, manifestsAt, manifestsOf, publish, restore, requestDigest, stateOpId, BlobMissing, PublishError } from "./publish.js";
45
45
  import { OpIdReused } from "./revision-store.js";
46
46
  import { pruneStateRevisions } from "./state-retention.js";
47
+ import { dropTenantOutputs, dropWorkspaceOutputs, moveWorkspaceOutputs, settleRunOutputs } from "./run-outputs.js";
47
48
  // ------------------------------------------------------------- the backend
48
49
  let backend = null;
49
50
  let gate = { journal: () => false, read: () => false };
@@ -424,6 +425,7 @@ const background = new Set();
424
425
  export async function settleLifecycle() {
425
426
  while (background.size)
426
427
  await Promise.allSettled([...background]);
428
+ await settleRunOutputs();
427
429
  }
428
430
  function inBackground(p) {
429
431
  const q = p.finally(() => background.delete(q));
@@ -472,6 +474,8 @@ export async function dropWorkspaceRevisions(tenant, workspace, remove) {
472
474
  await before?.catch(() => { });
473
475
  try {
474
476
  await deps.revisions.drop({ tenant, workspace });
477
+ // The run outputs published to the blob store (run-outputs.ts) are this workspace's too.
478
+ await dropWorkspaceOutputs(tenant, workspace);
475
479
  }
476
480
  catch (err) {
477
481
  // Nothing was removed and the workspace stays: whatever was queued is lost to the queue, so it is reconciled from the folder.
@@ -482,6 +486,7 @@ export async function dropWorkspaceRevisions(tenant, workspace, remove) {
482
486
  remove?.();
483
487
  dropJournal(tenant, workspace);
484
488
  await deps.revisions.drop({ tenant, workspace });
489
+ await dropWorkspaceOutputs(tenant, workspace);
485
490
  marked.delete(k);
486
491
  verified.delete(k);
487
492
  }
@@ -506,6 +511,7 @@ export async function dropTenantRevisions(tenant) {
506
511
  verified.delete(k);
507
512
  }
508
513
  await deps.revisions.drop({ tenant });
514
+ await dropTenantOutputs(tenant);
509
515
  await deps.blobs.purgeTenant?.(tenant);
510
516
  }
511
517
  /** The sync hook: a folder was renamed by a caller that did not wait for us. */
@@ -539,12 +545,17 @@ export async function moveWorkspaceRevisions(tenant, from, to, rename) {
539
545
  // process left for it is stale.
540
546
  dropJournal(tenant, to);
541
547
  await deps.revisions.move(tenant, from, to);
548
+ await moveWorkspaceOutputs(tenant, from, to).catch(async (err) => {
549
+ await deps.revisions.move(tenant, to, from).catch((e) => opsError("revisions.move_back_failed", e, { tenant, workspace: from, to }));
550
+ throw err;
551
+ });
542
552
  if (rename) {
543
553
  try {
544
554
  rename();
545
555
  }
546
556
  catch (err) {
547
557
  await deps.revisions.move(tenant, to, from).catch((e) => opsError("revisions.move_back_failed", e, { tenant, workspace: from, to }));
558
+ await moveWorkspaceOutputs(tenant, to, from).catch((e) => opsError("run_outputs.move_back_failed", e, { tenant, workspace: from, to }));
548
559
  throw err;
549
560
  }
550
561
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foldrun/core",
3
- "version": "19.3.0",
3
+ "version": "20.1.0",
4
4
  "description": "Agents are just folders. The format, the runner, the checks.",
5
5
  "license": "FSL-1.1-ALv2",
6
6
  "type": "module",
@@ -162,6 +162,9 @@ export function classifyCall(tool: string, input: Record<string, unknown> | unde
162
162
  // tools: [peers] — reading the roster changes nothing; a message to a
163
163
  // colleague is said, and a re-run would say it twice.
164
164
  if (server === "foldrun_peers") return name === "peers_list" ? { write: false } : write("a message to a colleague");
165
+ // tools: [text] — reading a file out as text changes nothing, unless it
166
+ // was asked to save that text beside the file.
167
+ if (server === "foldrun_text") return args.save === true ? write(`${String(args.path ?? "a file")}.txt (extract_text)`) : { write: false };
165
168
  // remotes: — reading where a request got to changes nothing; a send, a
166
169
  // reply or a cancel acts on an outside agent's system.
167
170
  if (server === "foldrun_a2a") return name === "a2a_status" ? { write: false } : write(`${name.replace(/^a2a_/, "")} to an outside agent`);
@@ -78,6 +78,7 @@ const TOOL_GROUPS: Completion[] = [
78
78
  { label: "web", hint: "search, fetch, browse, crawl, map, extract, answer, monitor — providers under web:" },
79
79
  { label: "ask", hint: "ask_person — ask the person running the desk mid-step, and wait for the answer" },
80
80
  { label: "peers", hint: "peers_list + peers_message — the colleagues running beside it in its parallel group, and a message to one of them" },
81
+ { label: "text", hint: "extract_text — an image, scanned PDF, office file, audio or video as text (Persian + English OCR, speech)" },
81
82
  { label: "install", hint: "install apt, pip or npm packages mid-step — every agent has it; disallowedTools: [install] removes it" },
82
83
  ];
83
84
 
package/src/egress.ts CHANGED
@@ -192,11 +192,14 @@ export interface EgressHooks {
192
192
  * addresses a colleague's message to the right inbox.
193
193
  * `delegates` — the `sandbox: own` sub-agents this step may hand a job
194
194
  * to over the delegate door (delegate-tools.ts); the proxy refuses any
195
- * other name. */
195
+ * other name.
196
+ * `text` — the step's agent holds tools: [text] (text-tool.ts): the proxy
197
+ * serves its `POST /text/<lease>` door to the extraction service, and
198
+ * refuses it on every other lease. */
196
199
  /** `job` — a lease for a host-side model call (an eval's judge, a
197
200
  * grader, a draft, the assistant) rather than a step: what the model
198
201
  * gateway records the call against. */
199
- lease(args: { tenant: string; runId: string; grant: EgressGrant; test?: boolean; step?: number; agent?: string; peers?: PeerInfo[]; who?: LeaseWho; delegates?: string[]; job?: { kind: "grade" | "judge" | "draft" | "assistant"; name?: string } }): Promise<EgressLease | null>;
202
+ lease(args: { tenant: string; runId: string; grant: EgressGrant; test?: boolean; step?: number; agent?: string; peers?: PeerInfo[]; who?: LeaseWho; delegates?: string[]; text?: boolean; job?: { kind: "grade" | "judge" | "draft" | "assistant"; name?: string } }): Promise<EgressLease | null>;
200
203
  /** The run is still being driven: renew its leases' heartbeat. Optional —
201
204
  * an install without leases has nothing to renew. */
202
205
  renew?(runId: string): Promise<number>;