@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,215 @@
1
+ // Text beside a run's media inputs (12 Nov 2026). A run handed a photo, a
2
+ // scanned PDF, a slide deck or a voice note (FOL-163, run-inputs.ts) gets,
3
+ // at staging, `<file>.txt` beside each one the platform could read — OCR, the
4
+ // document's text, a transcript — so the step starts with text it can read
5
+ // for the price of text, instead of an image block, a zip it cannot open, or
6
+ // nothing at all for audio.
7
+ //
8
+ // Core does not extract anything: the platform does, through
9
+ // platform.extractText (foldrun's own extraction pods). No hook — a laptop,
10
+ // a self-hosted install without the service — means no .txt and no note in
11
+ // the prompt. Best effort and bounded, so staging never stalls a run or
12
+ // fails it: INPUT_TEXT_LIMITS.totalMs across every input (past it, the rest
13
+ // are skipped), a size cap per file, recordings of at most ten minutes
14
+ // (the platform refuses longer before Whisper is asked). A file that yields
15
+ // nothing gets one line in the trail saying why; a `.txt` is never written
16
+ // over an input or a file of that name (`wx`).
17
+
18
+ import fs from "node:fs";
19
+ import path from "node:path";
20
+ import type { RunInputFile } from "./storage.ts";
21
+ import type { ExtractTextAsk } from "./platform.ts";
22
+
23
+ export const INPUT_TEXT_LIMITS = {
24
+ /** Every input's extraction together, at staging. */
25
+ totalMs: 120_000,
26
+ /** The largest input sent for its text. */
27
+ fileBytes: 50 * 1024 * 1024,
28
+ /** The longest recording transcribed (the platform holds it). */
29
+ speechSeconds: 600,
30
+ } as const;
31
+
32
+ export type MediaKind = "image" | "pdf" | "office" | "audio" | "video";
33
+
34
+ /** The extensions taken, by kind. Text, data and code are not here: the step
35
+ * reads those as they are. */
36
+ const BY_EXT: Record<string, MediaKind> = {
37
+ ...Object.fromEntries(["png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "heic", "heif"].map((e) => [e, "image" as const])),
38
+ pdf: "pdf",
39
+ ...Object.fromEntries(["docx", "doc", "pptx", "ppt", "xlsx", "xls", "odt", "odp", "ods", "rtf", "epub"].map((e) => [e, "office" as const])),
40
+ ...Object.fromEntries(["mp3", "wav", "m4a", "aac", "ogg", "oga", "opus", "flac", "wma", "amr"].map((e) => [e, "audio" as const])),
41
+ ...Object.fromEntries(["mp4", "mov", "mkv", "webm", "avi", "m4v", "3gp", "mpeg", "mpg"].map((e) => [e, "video" as const])),
42
+ };
43
+
44
+ /** The kind a file's name says, or null for anything not sent for text. */
45
+ export function mediaKindByName(name: string): MediaKind | null {
46
+ const ext = /\.([a-z0-9]{1,8})$/i.exec(name)?.[1]?.toLowerCase();
47
+ return ext ? (BY_EXT[ext] ?? null) : null;
48
+ }
49
+
50
+ /** What a file's first bytes say it is — the containers, not the codecs. */
51
+ export type Sniffed = "png" | "jpeg" | "gif" | "webp" | "tiff" | "bmp" | "pdf" | "zip" | "ole" | "rtf" | "mp3" | "wav" | "ogg" | "flac" | "aac" | "amr" | "asf" | "avi" | "isobmff" | "ebml" | "mpeg-ps";
52
+
53
+ export function sniff(head: Buffer): Sniffed | null {
54
+ const at = (off: number, sig: number[]) => head.length >= off + sig.length && sig.every((b, i) => head[off + i] === b);
55
+ const ascii = (off: number, s: string) => head.length >= off + s.length && head.toString("latin1", off, off + s.length) === s;
56
+ if (at(0, [0x89, 0x50, 0x4e, 0x47])) return "png";
57
+ if (at(0, [0xff, 0xd8, 0xff])) return "jpeg";
58
+ if (ascii(0, "GIF8")) return "gif";
59
+ if (ascii(0, "RIFF") && ascii(8, "WEBP")) return "webp";
60
+ if (ascii(0, "RIFF") && ascii(8, "WAVE")) return "wav";
61
+ if (ascii(0, "RIFF") && ascii(8, "AVI ")) return "avi";
62
+ if (at(0, [0x49, 0x49, 0x2a, 0x00]) || at(0, [0x4d, 0x4d, 0x00, 0x2a])) return "tiff";
63
+ if (ascii(0, "BM")) return "bmp";
64
+ if (ascii(0, "%PDF")) return "pdf";
65
+ if (at(0, [0x50, 0x4b, 0x03, 0x04])) return "zip";
66
+ if (at(0, [0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1])) return "ole";
67
+ if (ascii(0, "{\\rtf")) return "rtf";
68
+ if (ascii(0, "ID3") || (head.length >= 2 && head[0] === 0xff && (head[1]! & 0xe6) === 0xe2)) return "mp3";
69
+ if (head.length >= 2 && head[0] === 0xff && (head[1]! & 0xf6) === 0xf0) return "aac";
70
+ if (ascii(0, "OggS")) return "ogg";
71
+ if (ascii(0, "fLaC")) return "flac";
72
+ if (ascii(0, "#!AMR")) return "amr";
73
+ if (at(0, [0x30, 0x26, 0xb2, 0x75, 0x8e, 0x66, 0xcf, 0x11])) return "asf";
74
+ if (ascii(4, "ftyp")) return "isobmff";
75
+ if (at(0, [0x1a, 0x45, 0xdf, 0xa3])) return "ebml";
76
+ if (at(0, [0x00, 0x00, 0x01, 0xba])) return "mpeg-ps";
77
+ return null;
78
+ }
79
+
80
+ /** The containers each kind may arrive in. */
81
+ const FITS: Record<MediaKind, ReadonlySet<Sniffed>> = {
82
+ image: new Set(["png", "jpeg", "gif", "webp", "tiff", "bmp", "isobmff"]),
83
+ pdf: new Set(["pdf"]),
84
+ office: new Set(["zip", "ole", "rtf"]),
85
+ audio: new Set(["mp3", "wav", "ogg", "flac", "aac", "amr", "asf", "isobmff", "ebml"]),
86
+ video: new Set(["isobmff", "ebml", "avi", "asf", "mpeg-ps", "ogg"]),
87
+ };
88
+
89
+ /** The kind, when the name and the first bytes agree on one; else null. */
90
+ export function mediaKind(name: string, head: Buffer): MediaKind | null {
91
+ const byName = mediaKindByName(name);
92
+ if (!byName) return null;
93
+ const s = sniff(head);
94
+ return s && FITS[byName].has(s) ? byName : null;
95
+ }
96
+
97
+ /** Inputs whose text may be put beside them: the media ones, small enough,
98
+ * with no input already taking `<path>.txt`. What the prompt's note marks. */
99
+ export function textCandidates(files: RunInputFile[]): RunInputFile[] {
100
+ const names = new Set(files.map((f) => f.path));
101
+ return files.filter((f) => mediaKindByName(f.path) && f.size <= INPUT_TEXT_LIMITS.fileBytes && !names.has(`${f.path}.txt`));
102
+ }
103
+
104
+ export interface TextBesideInputs {
105
+ tenant: string;
106
+ workspace: string;
107
+ runId: string;
108
+ files: RunInputFile[];
109
+ /** The staged inputs folder (stageRunInputs' `intoDir`). */
110
+ dir: string;
111
+ extract: (ask: ExtractTextAsk) => Promise<{ text: string; warnings?: string[] }>;
112
+ /** One line for the run's trail. */
113
+ emit: (line: string) => void;
114
+ /** Overrides, for tests. */
115
+ totalMs?: number;
116
+ fileBytes?: number;
117
+ }
118
+
119
+ const short = (s: string) => s.replace(/\s+/g, " ").trim().slice(0, 200);
120
+
121
+ /**
122
+ * Write `<file>.txt` beside each media input the platform can read. Never
123
+ * throws for one file, and never runs past `totalMs`: what is left then is
124
+ * named in one line. Returns the .txt paths written (relative to `dir`) and
125
+ * the lines emitted.
126
+ */
127
+ export async function textBesideInputs(o: TextBesideInputs): Promise<{ wrote: string[]; notes: string[] }> {
128
+ const totalMs = o.totalMs ?? INPUT_TEXT_LIMITS.totalMs;
129
+ const fileBytes = o.fileBytes ?? INPUT_TEXT_LIMITS.fileBytes;
130
+ const notes: string[] = [];
131
+ const note = (line: string) => {
132
+ notes.push(line);
133
+ try {
134
+ o.emit(line);
135
+ } catch {
136
+ /* the trail's problem, not the run's */
137
+ }
138
+ };
139
+ const wrote: string[] = [];
140
+ const late: string[] = [];
141
+ const names = new Set(o.files.map((f) => f.path));
142
+ const clock = new AbortController();
143
+ // NOT unref'd: this function awaits the deadline, so the timer must keep
144
+ // the process alive until it fires (cleared in finally, at most totalMs).
145
+ // Unref'd, a hung extractor in a process with nothing else to do — the
146
+ // CLI's `foldrun run`, a test — let the event loop empty and the await
147
+ // never settle (the dev gate, 12 Nov 2026: "Promise resolution is still
148
+ // pending but the event loop has already resolved").
149
+ const timer = setTimeout(() => clock.abort(), totalMs);
150
+ try {
151
+ for (const f of o.files) {
152
+ const byName = mediaKindByName(f.path);
153
+ if (!byName) continue;
154
+ const target = `${f.path}.txt`;
155
+ if (names.has(target)) {
156
+ note(`inputs: ${f.path} → no text (${target} is an input of its own)`);
157
+ continue;
158
+ }
159
+ if (clock.signal.aborted) {
160
+ late.push(f.path);
161
+ continue;
162
+ }
163
+ if (f.size > fileBytes) {
164
+ note(`inputs: ${f.path} → no text (larger than ${Math.round(fileBytes / 1048576)} MB)`);
165
+ continue;
166
+ }
167
+ const abs = path.join(o.dir, f.path);
168
+ const out = `${abs}.txt`;
169
+ try {
170
+ if (fs.existsSync(out)) {
171
+ note(`inputs: ${f.path} → no text (${target} is already there)`);
172
+ continue;
173
+ }
174
+ const bytes = fs.readFileSync(abs);
175
+ if (!mediaKind(f.path, bytes.subarray(0, 64))) {
176
+ note(`inputs: ${f.path} → no text (its bytes are not ${/^[aeiou]/.test(byName) ? "an" : "a"} ${byName} file)`);
177
+ continue;
178
+ }
179
+ // Raced against the budget: an extractor that ignores its signal (or
180
+ // hangs) must not hold the step's start past it; an answer arriving
181
+ // after the deadline is dropped, never written.
182
+ const r = await new Promise<Awaited<ReturnType<typeof o.extract>>>((resolve, reject) => {
183
+ if (clock.signal.aborted) return reject(new Error("the budget ran out"));
184
+ const onAbort = () => reject(new Error("the budget ran out"));
185
+ clock.signal.addEventListener("abort", onAbort, { once: true });
186
+ o.extract({ tenant: o.tenant, workspace: o.workspace, runId: o.runId, name: path.basename(f.path), bytes, signal: clock.signal })
187
+ .then(resolve, reject)
188
+ .finally(() => clock.signal.removeEventListener("abort", onAbort));
189
+ });
190
+ if (clock.signal.aborted) {
191
+ late.push(f.path);
192
+ continue;
193
+ }
194
+ if (!r.text.trim()) {
195
+ note(`inputs: ${f.path} → no text (none found)`);
196
+ continue;
197
+ }
198
+ fs.writeFileSync(out, r.text.endsWith("\n") ? r.text : `${r.text}\n`, { flag: "wx" });
199
+ wrote.push(target);
200
+ } catch (err) {
201
+ if (clock.signal.aborted) {
202
+ late.push(f.path);
203
+ continue;
204
+ }
205
+ const code = (err as NodeJS.ErrnoException)?.code;
206
+ note(`inputs: ${f.path} → no text (${code === "EEXIST" ? `${target} is already there` : short((err as Error)?.message ?? String(err)) || "the extraction failed"})`);
207
+ }
208
+ }
209
+ } finally {
210
+ clearTimeout(timer);
211
+ }
212
+ if (late.length) note(`inputs: ${late.join(", ")} → no text (the ${Math.round(totalMs / 1000)} s for inputs' text ran out)`);
213
+ if (wrote.length) note(`inputs: text beside ${wrote.length} file${wrote.length === 1 ? "" : "s"} — ${wrote.join(", ")}`);
214
+ return { wrote, notes };
215
+ }
package/src/limits.ts CHANGED
@@ -66,6 +66,7 @@ const PLATFORM_SERVERS: Record<string, string> = {
66
66
  foldrun_desks: "desks",
67
67
  foldrun_ask: "ask",
68
68
  foldrun_peers: "peers",
69
+ foldrun_text: "text",
69
70
  };
70
71
 
71
72
  /** One spelling for comparing: `desk-email` and `desk_email` are the same
@@ -291,7 +292,7 @@ export function limitKeyProblems(
291
292
  ctx: { known: Iterable<string>; granted: Iterable<string> },
292
293
  ): { level: "error" | "warn"; message: string }[] {
293
294
  const out: { level: "error" | "warn"; message: string }[] = [];
294
- const builtinKeys = ["read", "write", "code", ...Object.keys(BUILTIN_GROUP), "TodoWrite", "search", "history", "desks", "ask", "web", A2A_LIMIT_KEY];
295
+ const builtinKeys = ["read", "write", "code", ...Object.keys(BUILTIN_GROUP), "TodoWrite", "search", "history", "desks", "ask", "text", "web", A2A_LIMIT_KEY];
295
296
  const known = new Set([...builtinKeys, ...ctx.known].map(normKey));
296
297
  const granted = new Set([...ctx.granted].flatMap((g) => {
297
298
  const n = normKey(g);
package/src/manifest.ts CHANGED
@@ -44,6 +44,11 @@ export interface ManifestEntry {
44
44
 
45
45
  export interface Manifest {
46
46
  v: 1;
47
+ /** Absent: a workspace manifest (paths under the authored/state roots).
48
+ * "run-output": what one agent of one run left in outputs/ (FOL-126 phase 5):
49
+ * any legal relative path, never a head, never restored. Part of the
50
+ * canonical form, so the two kinds can never share an id. */
51
+ kind?: "run-output";
47
52
  /** Forward-slashed paths, relative to the workspace root. */
48
53
  files: Record<string, ManifestEntry>;
49
54
  }
@@ -115,7 +120,7 @@ export const MAX_PATH_BYTES = 400;
115
120
  * are sharded. 50k files is ~5 MB of canonical JSON. */
116
121
  export const MAX_MANIFEST_FILES = 50_000;
117
122
 
118
- export function assertManifestPath(rel: string): string {
123
+ export function assertManifestPath(rel: string, kind?: Manifest["kind"]): string {
119
124
  if (typeof rel !== "string" || !rel || Buffer.byteLength(rel) > MAX_PATH_BYTES) throw new Error(`illegal manifest path: ${String(rel).slice(0, 80)}`);
120
125
  if (rel.includes("\\") || rel.startsWith("/") || /^[a-zA-Z]:/.test(rel)) throw new Error(`illegal manifest path: ${rel}`);
121
126
  if (rel.split("/").some((s) => s === "" || s === "." || s === "..")) throw new Error(`illegal manifest path: ${rel}`);
@@ -124,7 +129,7 @@ export function assertManifestPath(rel: string): string {
124
129
  // name on a Mac and two on Linux. A manifest holds the composed form, so it
125
130
  // extracts the same everywhere. (Case is handled per manifest, below.)
126
131
  if (rel !== rel.normalize("NFC")) throw new Error(`illegal manifest path (not NFC-normalised): ${rel}`);
127
- if (sideOf(rel) === null) throw new Error(`${rel} is not workspace content (authored: ${[...AUTHORED_DIRS, ...AUTHORED_ROOT_FILES].join(", ")}; state: state/)`);
132
+ if (kind !== "run-output" && sideOf(rel) === null) throw new Error(`${rel} is not workspace content (authored: ${[...AUTHORED_DIRS, ...AUTHORED_ROOT_FILES].join(", ")}; state: state/)`);
128
133
  return rel;
129
134
  }
130
135
 
@@ -158,7 +163,7 @@ export function assertEntry(p: string, e: ManifestEntry): void {
158
163
  * to WRITE — a revision must never point at a manifest it cannot read back. */
159
164
  export function assertManifest(m: Manifest): void {
160
165
  for (const [p, e] of Object.entries(m.files)) {
161
- assertManifestPath(p);
166
+ assertManifestPath(p, m.kind);
162
167
  assertEntry(p, e);
163
168
  }
164
169
  assertNoCaseCollisions(m);
@@ -176,12 +181,13 @@ export function modeFor(executable: boolean): number {
176
181
  /** Sorted keys at every level, no whitespace: one tree, one byte string, one
177
182
  * id — whichever machine wrote it. */
178
183
  export function canonicalManifest(m: Manifest): string {
179
- const files: Record<string, ManifestEntry> = {};
184
+ // No prototype: a path may be `__proto__` (review, 12 Nov 2026).
185
+ const files: Record<string, ManifestEntry> = Object.create(null);
180
186
  for (const p of Object.keys(m.files).sort()) {
181
187
  const e = m.files[p];
182
188
  files[p] = { sha: e.sha, size: e.size, mode: e.mode };
183
189
  }
184
- return JSON.stringify({ v: 1, files });
190
+ return JSON.stringify(m.kind ? { v: 1, kind: m.kind, files } : { v: 1, files });
185
191
  }
186
192
 
187
193
  export function manifestId(m: Manifest): ManifestId {
@@ -201,6 +207,7 @@ export function parseManifest(text: string): Manifest {
201
207
  if (raw?.v !== 1 || typeof raw.files !== "object" || raw.files === null || Array.isArray(raw.files)) {
202
208
  throw new Error("not a manifest (v1)");
203
209
  }
210
+ if (raw.kind !== undefined && raw.kind !== "run-output") throw new Error("not a manifest (unknown kind)");
204
211
  assertManifest(raw);
205
212
  return raw;
206
213
  }
package/src/ops-log.ts CHANGED
@@ -105,12 +105,18 @@ export const FIELDS: Record<string, Kind> = {
105
105
  runId: "id", jobId: "id", taskId: "id", proposal: "id", lease: "id", pod: "id",
106
106
  worker: "id", provider: "id", plan: "id", fingerprint: "id", invoice: "id", order: "id",
107
107
  stripeEvent: "id", subscription: "id", migration: "id", housekeeping: "id",
108
+ // Who asked, for the operator console's per-account timeline (D239 phase 1,
109
+ // 12 Nov 2026): a member's id and an API key's id (never an email — `@`
110
+ // does not fit an id, so one cannot slip in), and the request's own id.
111
+ user: "id", key: "id", requestId: "id",
108
112
  // How many, how long, how much.
109
113
  count: "num", ms: "num", secs: "num", bytes: "num", usd: "num", attempt: "num",
110
114
  step: "num", port: "num", status: "num", exitCode: "num", percent: "num", tries: "num",
111
115
  // What kind.
112
116
  op: "word", role: "word", outcome: "word", reason: "word", stream: "word", kind: "word",
113
117
  verdict: "word", phase: "word", signal: "code", where: "word",
118
+ // Where a refusal happened: login, api, gateway, mcp, a2a, egress, webhook.
119
+ surface: "word",
114
120
  // A run's sandbox (FOL-122): the runner image and size class — the
115
121
  // platform's own words — and the model, an identifier like a flow's name
116
122
  // (one with `/` or `:` in it does not fit, and is dropped).
@@ -163,12 +169,21 @@ export function opsLine(level: OpsLevel, event: string, fields: OpsFields = {}):
163
169
  // ------------------------------------------------------------------ writing
164
170
 
165
171
  type Write = (text: string) => void;
166
- /** The real streams, once the boundary holds them; null outside it. */
167
- let real: { out: Write; err: Write } | null = null;
172
+ /** The real streams, once the boundary holds them; null outside it. Held on
173
+ * globalThis, not in this module: a bundler can load this file more than
174
+ * once in one process (Next.js gives the instrumentation hook and the route
175
+ * handlers their own copies), and a copy that could not see the boundary
176
+ * printed the readable form through console.*, which the boundary then
177
+ * turned into a bare {"event":"console"} line — every web route's ops line
178
+ * was lost that way (D239 phase 1, found on dev 12 Nov 2026). */
179
+ const BOUNDARY = Symbol.for("foldrun.ops-log.boundary");
180
+ type Streams = { out: Write; err: Write };
181
+ const shared = globalThis as unknown as Record<symbol, Streams | null | undefined>;
182
+ const boundary = (): Streams | null => shared[BOUNDARY] ?? null;
168
183
 
169
184
  /** Is this process inside the boundary — a hosted pod? */
170
185
  export function opsBoundaryInstalled(): boolean {
171
- return real !== null;
186
+ return boundary() !== null;
172
187
  }
173
188
 
174
189
  function readable(level: OpsLevel, line: Record<string, unknown>, detail?: string): string {
@@ -179,6 +194,7 @@ function readable(level: OpsLevel, line: Record<string, unknown>, detail?: strin
179
194
  }
180
195
 
181
196
  function emit(level: OpsLevel, line: Record<string, unknown>, detail?: string): void {
197
+ const real = boundary();
182
198
  if (real) {
183
199
  (level === "info" ? real.out : real.err)(JSON.stringify(line) + "\n");
184
200
  return;
@@ -337,7 +353,7 @@ function messageOf(err: unknown): string {
337
353
  /** A failure: its class and where it happened — never its words inside the
338
354
  * boundary. A field the caller names (an `errorClass` it knows) wins. */
339
355
  export function opsError(event: string, err: unknown, fields: OpsFields = {}, level: OpsLevel = "error"): void {
340
- emit(level, opsLine(level, event, { ...errorFields(err), ...fields }), real ? undefined : messageOf(err));
356
+ emit(level, opsLine(level, event, { ...errorFields(err), ...fields }), boundary() ? undefined : messageOf(err));
341
357
  }
342
358
 
343
359
  // ----------------------------------------------------------------- boundary
@@ -371,11 +387,11 @@ export interface BoundaryOptions {
371
387
  */
372
388
  export function installOpsBoundary(opts: BoundaryOptions = {}): boolean {
373
389
  const env = opts.env ?? process.env;
374
- if (real) return true;
390
+ if (boundary()) return true;
375
391
  if (env.FOLDRUN_LOG_MODE === "raw" || (env.FOLDRUN_LOG_MODE !== "ops" && env.NODE_ENV === "development")) return false;
376
392
  const outWrite = process.stdout.write.bind(process.stdout) as (s: string) => boolean;
377
393
  const errWrite = process.stderr.write.bind(process.stderr) as (s: string) => boolean;
378
- real = { out: (s) => void outWrite(s), err: (s) => void errWrite(s) };
394
+ shared[BOUNDARY] = { out: (s) => void outWrite(s), err: (s) => void errWrite(s) };
379
395
 
380
396
  const fromConsole = (level: OpsLevel) => (...args: unknown[]) => {
381
397
  // Never formatted: an argument's text, its inspect() and its toJSON()
package/src/platform.ts CHANGED
@@ -21,6 +21,18 @@ import type { RecordsPort } from "./records.ts";
21
21
 
22
22
  export type IsolatedStepRunner = (args: RunInContainerArgs) => Promise<ContainerStepOutcome>;
23
23
 
24
+ /** One of a run's inputs, sent for its text at staging (input-text.ts). */
25
+ export interface ExtractTextAsk {
26
+ tenant: string;
27
+ workspace: string;
28
+ runId: string;
29
+ /** The file's name (its last segment): the extension helps the parser. */
30
+ name: string;
31
+ bytes: Buffer;
32
+ /** Aborts when staging's time for inputs runs out. */
33
+ signal: AbortSignal;
34
+ }
35
+
24
36
  /** Who this install is for. `hosted` means someone is paying the operator
25
37
  * for it — a wallet, a plan, a bill. `self-hosted` is everything else: a
26
38
  * laptop, a dev install, a box nobody bills on. */
@@ -178,6 +190,15 @@ export interface PlatformHooks {
178
190
  * can; a run with inputs on one that cannot fails before anything starts
179
191
  * (FOL-163). Default: none can. */
180
192
  holdsInputs?(isolation: string): boolean;
193
+ /**
194
+ * The text of one of a run's media inputs, for the `<file>.txt` written
195
+ * beside it at staging (input-text.ts textBesideInputs): OCR, a
196
+ * document's text, a transcript. Throws when it cannot — the caller notes
197
+ * why and moves on; the run never fails for it. Absent: no extraction on
198
+ * this install (a laptop, or a platform without the service), and no
199
+ * `.txt` is written or promised in the prompt.
200
+ */
201
+ extractText?(ask: ExtractTextAsk): Promise<{ text: string; warnings?: string[] }>;
181
202
  /**
182
203
  * Does this isolation mode wall a step whose `network:` is restricted and
183
204
  * enforced to the egress proxy alone (a `filtered` pod)? True: such a
@@ -378,4 +399,5 @@ export function platformQueues(): boolean {
378
399
  export function resetPlatform(): void {
379
400
  Object.assign(platform, local, { isolation: {} });
380
401
  delete platform.records;
402
+ delete platform.extractText;
381
403
  }
package/src/records.ts CHANGED
@@ -34,11 +34,22 @@ export interface RecordsPortAsync {
34
34
  * lock its async context holds, with the event loop free while it waits.
35
35
  * Optional like the reads: a port without it is written through runPut. */
36
36
  runPut?(tenant: string, workspace: string, run: RunRecord, summary: RunSummary, live: boolean): Promise<void>;
37
+ /** What a step was handed and started from, per run (FOL-126 phase 7, step
38
+ * state): small JSON, one row per (run, kind, ref). Optional like the rest;
39
+ * step-state.ts is the only caller. */
40
+ stepGet?(tenant: string, workspace: string, runId: string, kind: string, ref: string): Promise<unknown | undefined>;
41
+ stepPut?(tenant: string, workspace: string, runId: string, kind: string, ref: string, data: unknown): Promise<void>;
42
+ /** `ref` null: every ref of the kind. */
43
+ stepDrop?(tenant: string, workspace: string, runId: string, kind: string, ref: string | null): Promise<void>;
37
44
  }
38
45
 
39
46
  export interface RecordsPort {
40
47
  /** Async reads (see RecordsPortAsync). */
41
48
  async?: RecordsPortAsync;
49
+ /** The `runs.step_state_store` setting, read per call: while false, step
50
+ * state is written to the run's folder as before (it is still READ from
51
+ * rows first, so switching off mid-run loses nothing). */
52
+ stepStateOn?(): boolean;
42
53
  // ---- runs: the whole record, and the row a list reads
43
54
  /** Insert or replace one run. `live`: queued, running or parked at a gate. Last write wins. */
44
55
  runPut(tenant: string, workspace: string, run: RunRecord, summary: RunSummary, live: boolean): void;
@@ -47,8 +47,10 @@ import type { SearchRoot, RunDigest } from "./context-tools.ts";
47
47
  import type { TranslatorSpec } from "./translator.ts";
48
48
  import { parseBrowserPod, type BrowserPodOutcome } from "./browser-pod.ts";
49
49
  import type { RemoteSpec } from "./a2a-remotes.ts";
50
+ import { putStepState, getStepState, dropStepState } from "./step-state.ts";
50
51
  import { stageRunInputs, type RunInputFile } from "./storage.ts";
51
52
  import { INPUTS_DIR, stagedLine } from "./run-inputs.ts";
53
+ import { textBesideInputs } from "./input-text.ts";
52
54
 
53
55
  /** What crosses the boundary. Everything in here is values — pre-resolved
54
56
  * secrets in headers, assembled prompt, serializable MCP configs. */
@@ -122,6 +124,9 @@ export interface ContainerStepInput {
122
124
  * parallel group, gathered host-side at launch. The driver rebuilds the
123
125
  * colleagues' tools in here over the lease's /peers door. */
124
126
  peers?: { self: string; siblings: PeerInfo[] };
127
+ /** tools: [text] — extract_text, rebuilt in here over the lease's /text
128
+ * door to the extraction service (text-tool.ts). */
129
+ text?: boolean;
125
130
  /** A Chat-Completions provider: the driver starts the runtime's translator
126
131
  * on loopback and points the SDK at it. Null or absent: the env's
127
132
  * ANTHROPIC_BASE_URL is spoken to directly. */
@@ -348,28 +353,37 @@ export function handedInPath(workspaceRoot: string, runId: string, ref: string):
348
353
  return path.join(workspaceRoot, "runs", runId, "sandbox", `${ref}.json`);
349
354
  }
350
355
 
351
- /** Note what a sandbox was handed, on the host. */
352
- export function writeHandedIn(workspaceRoot: string, runId: string, ref: string, hashes: Record<string, string>): void {
356
+ /** Note what a sandbox was handed, on the host. With `tenant`, where step
357
+ * state is kept in the database (step-state.ts), a row; otherwise the file. */
358
+ export async function writeHandedIn(workspaceRoot: string, runId: string, ref: string, hashes: Record<string, string>, tenant?: string): Promise<void> {
359
+ if (await putStepState(tenant, path.basename(workspaceRoot), runId, "handed-in", ref, hashes)) return;
353
360
  const file = handedInPath(workspaceRoot, runId, ref);
354
361
  if (!file) return;
355
362
  fs.mkdirSync(path.dirname(file), { recursive: true });
356
363
  fs.writeFileSync(file, JSON.stringify(hashes));
357
364
  }
358
365
 
366
+ const isHashes = (m: unknown): m is Record<string, string> => !!m && typeof m === "object" && !Array.isArray(m);
367
+
359
368
  /** What the host noted a sandbox was handed, or undefined. */
360
- export function readHandedIn(workspaceRoot: string, runId: string, ref: string): Record<string, string> | undefined {
369
+ export async function readHandedIn(workspaceRoot: string, runId: string, ref: string, tenant?: string): Promise<Record<string, string> | undefined> {
370
+ const row = await getStepState(tenant, path.basename(workspaceRoot), runId, "handed-in", ref);
371
+ if (isHashes(row)) return row;
361
372
  const file = handedInPath(workspaceRoot, runId, ref);
362
373
  if (!file) return undefined;
363
374
  try {
364
375
  const m = JSON.parse(fs.readFileSync(file, "utf8"));
365
- return m && typeof m === "object" && !Array.isArray(m) ? (m as Record<string, string>) : undefined;
376
+ return isHashes(m) ? m : undefined;
366
377
  } catch {
367
378
  return undefined;
368
379
  }
369
380
  }
370
381
 
371
382
  /** Forget it once the step's copy-out is done. */
372
- export function dropHandedIn(workspaceRoot: string, runId: string, ref: string): void {
383
+ export async function dropHandedIn(workspaceRoot: string, runId: string, ref: string, tenant?: string): Promise<void> {
384
+ // Best effort: a row left behind goes with the run (deleteRun), and failing
385
+ // the step it belongs to, after its copy-out succeeded, would be worse.
386
+ for (const kind of ["handed-in", "base"] as const) await dropStepState(tenant, path.basename(workspaceRoot), runId, kind, ref).catch(() => {});
373
387
  const file = handedInPath(workspaceRoot, runId, ref);
374
388
  if (file) fs.rmSync(file, { force: true });
375
389
  const base = baseRevisionPath(workspaceRoot, runId, ref);
@@ -386,19 +400,24 @@ export function baseRevisionPath(workspaceRoot: string, runId: string, ref: stri
386
400
  const file = handedInPath(workspaceRoot, runId, ref);
387
401
  return file ? file.replace(/\.json$/, ".base.json") : null;
388
402
  }
389
- export function writeBaseRevision(workspaceRoot: string, runId: string, ref: string, base: RunBase): void {
403
+ export async function writeBaseRevision(workspaceRoot: string, runId: string, ref: string, base: RunBase, tenant?: string): Promise<void> {
404
+ if (await putStepState(tenant, path.basename(workspaceRoot), runId, "base", ref, base)) return;
390
405
  const file = baseRevisionPath(workspaceRoot, runId, ref);
391
406
  if (!file) return;
392
407
  fs.mkdirSync(path.dirname(file), { recursive: true });
393
408
  fs.writeFileSync(file, JSON.stringify(base));
394
409
  }
395
- export function readBaseRevision(workspaceRoot: string, runId: string, ref: string): RunBase | undefined {
410
+ const asBase = (m: Partial<RunBase> | null | undefined): RunBase | undefined => {
411
+ const ok = (v: unknown) => v === null || typeof v === "string";
412
+ return m && typeof m === "object" && ok(m.workspace) && ok(m.state) ? { workspace: m.workspace ?? null, state: m.state ?? null } : undefined;
413
+ };
414
+ export async function readBaseRevision(workspaceRoot: string, runId: string, ref: string, tenant?: string): Promise<RunBase | undefined> {
415
+ const row = asBase((await getStepState(tenant, path.basename(workspaceRoot), runId, "base", ref)) as Partial<RunBase> | undefined);
416
+ if (row) return row;
396
417
  const file = baseRevisionPath(workspaceRoot, runId, ref);
397
418
  if (!file) return undefined;
398
419
  try {
399
- const m = JSON.parse(fs.readFileSync(file, "utf8")) as Partial<RunBase>;
400
- const ok = (v: unknown) => v === null || typeof v === "string";
401
- return m && ok(m.workspace) && ok(m.state) ? { workspace: m.workspace ?? null, state: m.state ?? null } : undefined;
420
+ return asBase(JSON.parse(fs.readFileSync(file, "utf8")) as Partial<RunBase>);
402
421
  } catch {
403
422
  return undefined;
404
423
  }
@@ -896,6 +915,7 @@ try {
896
915
  const { buildSearchTools, buildHistoryTools, buildDeskTools } = await import("@foldrun/core/context-tools");
897
916
  const { httpChannel, buildAskTool, buildPeerTools, inboxReader } = await import("@foldrun/core/operator");
898
917
  const { buildDelegateTools } = await import("@foldrun/core/delegate-tools");
918
+ const { buildTextTools } = await import("@foldrun/core/text-tool");
899
919
  const { startTranslator } = await import("@foldrun/core/translator");
900
920
  const { prepareRuntime } = await import("@foldrun/core/runtime");
901
921
  const { materializeFileSecrets } = await import("@foldrun/core/secret-files");
@@ -1009,6 +1029,9 @@ try {
1009
1029
  const ask = input.ask ? buildAskTool({ channel, timeoutSec: input.ask.timeoutSec, emit }) : { server: null };
1010
1030
  const peers = input.peers ? buildPeerTools({ channel, self: input.peers.self, siblings: input.peers.siblings, emit }) : { server: null };
1011
1031
  const inbox = channel ? inboxReader(channel, emit) : undefined;
1032
+ // tools: [text] — a file as text, through the extraction service behind
1033
+ // the same proxy; the lease was granted the door only for this tool.
1034
+ const textTool = input.text ? buildTextTools({ egress: env.FOLDRUN_EGRESS || null, agentDir, workspaceRoot: "/workspace", libraryRoot: "/library", emit }) : { server: null };
1012
1035
  // sandbox: own sub-agents: a tool each, whose job runs in its own sandbox
1013
1036
  // on the worker, reached over the same proxy door.
1014
1037
  const delegate = input.delegates?.length ? buildDelegateTools({ specs: input.delegates, channel, emit, timeoutSec: input.timeoutSec, workspaceRoot: "/workspace" }) : { server: null };
@@ -1065,6 +1088,7 @@ try {
1065
1088
  ...(desks.server ? { foldrun_desks: desks.server } : {}),
1066
1089
  ...(ask.server ? { foldrun_ask: ask.server } : {}),
1067
1090
  ...(peers.server ? { foldrun_peers: peers.server } : {}),
1091
+ ...(textTool.server ? { foldrun_text: textTool.server } : {}),
1068
1092
  ...(delegate.server ? { foldrun_delegate: delegate.server } : {}),
1069
1093
  ...(install.server ? { foldrun_install: install.server } : {}),
1070
1094
  ...input.mcpServers,
@@ -2175,8 +2199,22 @@ export async function runStepInContainer(args: RunInContainerArgs): Promise<Cont
2175
2199
  // that name in the workspace never mixes in.
2176
2200
  if (args.inputs?.files.length) {
2177
2201
  if (!args.tenant) throw new Error("a step with inputs needs its account");
2178
- const staged = await stageRunInputs(args.tenant, path.basename(args.workspaceRoot), args.inputs.runId, args.inputs.files, path.join(wsIn, args.input.agentRel, INPUTS_DIR));
2202
+ const inputsDir = path.join(wsIn, args.input.agentRel, INPUTS_DIR);
2203
+ const staged = await stageRunInputs(args.tenant, path.basename(args.workspaceRoot), args.inputs.runId, args.inputs.files, inputsDir);
2179
2204
  args.emit("info", stagedLine(staged.files, staged.bytes));
2205
+ // `<file>.txt` beside the media ones, when the platform extracts text:
2206
+ // best effort, bounded, never a reason the step does not start.
2207
+ if (platform.extractText) {
2208
+ await textBesideInputs({
2209
+ tenant: args.tenant,
2210
+ workspace: path.basename(args.workspaceRoot),
2211
+ runId: args.inputs.runId,
2212
+ files: args.inputs.files,
2213
+ dir: inputsDir,
2214
+ extract: (ask) => platform.extractText!(ask),
2215
+ emit: (line) => args.emit("info", line),
2216
+ });
2217
+ }
2180
2218
  }
2181
2219
  const libIn = path.join(staging, "library");
2182
2220
  if (args.galleryRoot && fs.existsSync(args.galleryRoot)) fs.cpSync(args.galleryRoot, libIn, { recursive: true });
package/src/run-inputs.ts CHANGED
@@ -47,10 +47,18 @@ export function inputsSizeProblem(files: RunInputFile[]): string | null {
47
47
  const human = (n: number) => (n >= 1048576 ? `${(n / 1048576).toFixed(1)} MiB` : n >= 1024 ? `${Math.round(n / 1024)} KiB` : `${n} B`);
48
48
 
49
49
  /** What the step is told, after its instruction. */
50
- export function inputsNote(files: RunInputFile[]): string {
51
- const lines = files.map((f) => `- ${INPUTS_DIR}/${f.path} (${f.mime}, ${human(f.size)})`);
50
+ /** `textBeside`: the paths whose text the platform will try to put at
51
+ * `<path>.txt` at staging (input-text.ts textCandidates) — marked, and the
52
+ * note says how to use them. Absent or empty: nothing is said of .txt. */
53
+ export function inputsNote(files: RunInputFile[], opts?: { textBeside?: string[] }): string {
54
+ const beside = new Set(opts?.textBeside ?? []);
55
+ const lines = files.map((f) => `- ${INPUTS_DIR}/${f.path} (${f.mime}, ${human(f.size)})${beside.has(f.path) ? ` — its text, when it could be extracted: ${INPUTS_DIR}/${f.path}.txt` : ""}`);
56
+ const textNote = beside.size
57
+ ? `Where ${INPUTS_DIR}/<file>.txt exists beside a file, it holds that file's text, extracted before this step started (OCR for images and scans, the document's text, a transcript for audio and video): read it first — it costs far less than the file — and open the file itself only when the text looks wrong or incomplete. No .txt means no text could be extracted (the step's trail says why). `
58
+ : "";
52
59
  return (
53
60
  `<inputs>\nThis run was handed ${files.length} file${files.length === 1 ? "" : "s"}, in ${INPUTS_DIR}/ inside your working directory:\n${lines.join("\n")}\n` +
61
+ textNote +
54
62
  "Read them with the Read tool. Supported images and PDFs are shown to you as they are; when a model cannot be shown a file, the tool result says so. " +
55
63
  `The files stay available to scripts. Anything you write in ${INPUTS_DIR}/ is not kept — put results in outputs/.\n</inputs>`
56
64
  );
@@ -0,0 +1,20 @@
1
+ // One refused run output as a sentence a person reads (FOL-126 phase 5).
2
+ // Pure, so the run page (a client component) can use it without the store.
3
+
4
+ import type { RefusedOutput } from "./store.ts";
5
+
6
+ const mib = (n: number) => `${(n / 1048576).toFixed(n >= 10 * 1048576 ? 0 : 1)} MiB`;
7
+ /** One refusal as a sentence a person reads on the run page. */
8
+ export function refusalText(r: RefusedOutput): string {
9
+ switch (r.reason) {
10
+ case "file-cap":
11
+ return `${r.agent}/${r.path} (${mib(r.bytes)}) was not kept: a file may be at most ${mib(r.limit ?? 0)}`;
12
+ case "run-cap":
13
+ return `${r.agent}/${r.path} (${mib(r.bytes)}) was not kept: this run's outputs may total at most ${mib(r.limit ?? 0)}`;
14
+ case "count":
15
+ return `${r.agent}/${r.path} was not kept: a run keeps at most ${r.limit ?? 50_000} files per agent`;
16
+ default:
17
+ return `${r.agent}/${r.path} was not kept: its name cannot be stored (control characters, over 400 bytes, or differs from another file only by case)`;
18
+ }
19
+ }
20
+