@foldrun/core 19.3.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 (53) 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/store.d.ts +25 -4
  27. package/dist/src/store.js +15 -4
  28. package/dist/src/text-tool.d.ts +177 -0
  29. package/dist/src/text-tool.js +220 -0
  30. package/dist/src/tool-names.d.ts +3 -1
  31. package/dist/src/tool-names.js +4 -2
  32. package/dist/src/workspace-revisions.js +11 -0
  33. package/package.json +1 -1
  34. package/src/browser-pod.ts +3 -0
  35. package/src/completions.ts +1 -0
  36. package/src/egress.ts +5 -2
  37. package/src/input-text.ts +215 -0
  38. package/src/limits.ts +2 -1
  39. package/src/manifest.ts +12 -5
  40. package/src/ops-log.ts +22 -6
  41. package/src/platform.ts +22 -0
  42. package/src/records.ts +11 -0
  43. package/src/run-container.ts +49 -11
  44. package/src/run-inputs.ts +10 -2
  45. package/src/run-output-refusal.ts +20 -0
  46. package/src/run-outputs.ts +597 -0
  47. package/src/runner.ts +55 -10
  48. package/src/starter.ts +1 -1
  49. package/src/step-state.ts +97 -0
  50. package/src/store.ts +32 -4
  51. package/src/text-tool.ts +267 -0
  52. package/src/tool-names.ts +4 -2
  53. package/src/workspace-revisions.ts +11 -0
@@ -173,6 +173,10 @@ export function classifyCall(tool, input, ctx = {}) {
173
173
  // colleague is said, and a re-run would say it twice.
174
174
  if (server === "foldrun_peers")
175
175
  return name === "peers_list" ? { write: false } : write("a message to a colleague");
176
+ // tools: [text] — reading a file out as text changes nothing, unless it
177
+ // was asked to save that text beside the file.
178
+ if (server === "foldrun_text")
179
+ return args.save === true ? write(`${String(args.path ?? "a file")}.txt (extract_text)`) : { write: false };
176
180
  // remotes: — reading where a request got to changes nothing; a send, a
177
181
  // reply or a cancel acts on an outside agent's system.
178
182
  if (server === "foldrun_a2a")
@@ -38,6 +38,7 @@ const TOOL_GROUPS = [
38
38
  { label: "web", hint: "search, fetch, browse, crawl, map, extract, answer, monitor — providers under web:" },
39
39
  { label: "ask", hint: "ask_person — ask the person running the desk mid-step, and wait for the answer" },
40
40
  { label: "peers", hint: "peers_list + peers_message — the colleagues running beside it in its parallel group, and a message to one of them" },
41
+ { label: "text", hint: "extract_text — an image, scanned PDF, office file, audio or video as text (Persian + English OCR, speech)" },
41
42
  { label: "install", hint: "install apt, pip or npm packages mid-step — every agent has it; disallowedTools: [install] removes it" },
42
43
  ];
43
44
  const SDK_TOOL_NAMES = [
@@ -134,7 +134,10 @@ export interface EgressHooks {
134
134
  * addresses a colleague's message to the right inbox.
135
135
  * `delegates` — the `sandbox: own` sub-agents this step may hand a job
136
136
  * to over the delegate door (delegate-tools.ts); the proxy refuses any
137
- * other name. */
137
+ * other name.
138
+ * `text` — the step's agent holds tools: [text] (text-tool.ts): the proxy
139
+ * serves its `POST /text/<lease>` door to the extraction service, and
140
+ * refuses it on every other lease. */
138
141
  /** `job` — a lease for a host-side model call (an eval's judge, a
139
142
  * grader, a draft, the assistant) rather than a step: what the model
140
143
  * gateway records the call against. */
@@ -148,6 +151,7 @@ export interface EgressHooks {
148
151
  peers?: PeerInfo[];
149
152
  who?: LeaseWho;
150
153
  delegates?: string[];
154
+ text?: boolean;
151
155
  job?: {
152
156
  kind: "grade" | "judge" | "draft" | "assistant";
153
157
  name?: string;
@@ -0,0 +1,48 @@
1
+ import type { RunInputFile } from "./storage.ts";
2
+ import type { ExtractTextAsk } from "./platform.ts";
3
+ export declare const INPUT_TEXT_LIMITS: {
4
+ /** Every input's extraction together, at staging. */
5
+ readonly totalMs: 120000;
6
+ /** The largest input sent for its text. */
7
+ readonly fileBytes: number;
8
+ /** The longest recording transcribed (the platform holds it). */
9
+ readonly speechSeconds: 600;
10
+ };
11
+ export type MediaKind = "image" | "pdf" | "office" | "audio" | "video";
12
+ /** The kind a file's name says, or null for anything not sent for text. */
13
+ export declare function mediaKindByName(name: string): MediaKind | null;
14
+ /** What a file's first bytes say it is — the containers, not the codecs. */
15
+ 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";
16
+ export declare function sniff(head: Buffer): Sniffed | null;
17
+ /** The kind, when the name and the first bytes agree on one; else null. */
18
+ export declare function mediaKind(name: string, head: Buffer): MediaKind | null;
19
+ /** Inputs whose text may be put beside them: the media ones, small enough,
20
+ * with no input already taking `<path>.txt`. What the prompt's note marks. */
21
+ export declare function textCandidates(files: RunInputFile[]): RunInputFile[];
22
+ export interface TextBesideInputs {
23
+ tenant: string;
24
+ workspace: string;
25
+ runId: string;
26
+ files: RunInputFile[];
27
+ /** The staged inputs folder (stageRunInputs' `intoDir`). */
28
+ dir: string;
29
+ extract: (ask: ExtractTextAsk) => Promise<{
30
+ text: string;
31
+ warnings?: string[];
32
+ }>;
33
+ /** One line for the run's trail. */
34
+ emit: (line: string) => void;
35
+ /** Overrides, for tests. */
36
+ totalMs?: number;
37
+ fileBytes?: number;
38
+ }
39
+ /**
40
+ * Write `<file>.txt` beside each media input the platform can read. Never
41
+ * throws for one file, and never runs past `totalMs`: what is left then is
42
+ * named in one line. Returns the .txt paths written (relative to `dir`) and
43
+ * the lines emitted.
44
+ */
45
+ export declare function textBesideInputs(o: TextBesideInputs): Promise<{
46
+ wrote: string[];
47
+ notes: string[];
48
+ }>;
@@ -0,0 +1,212 @@
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
+ import fs from "node:fs";
18
+ import path from "node:path";
19
+ export const INPUT_TEXT_LIMITS = {
20
+ /** Every input's extraction together, at staging. */
21
+ totalMs: 120_000,
22
+ /** The largest input sent for its text. */
23
+ fileBytes: 50 * 1024 * 1024,
24
+ /** The longest recording transcribed (the platform holds it). */
25
+ speechSeconds: 600,
26
+ };
27
+ /** The extensions taken, by kind. Text, data and code are not here: the step
28
+ * reads those as they are. */
29
+ const BY_EXT = {
30
+ ...Object.fromEntries(["png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "heic", "heif"].map((e) => [e, "image"])),
31
+ pdf: "pdf",
32
+ ...Object.fromEntries(["docx", "doc", "pptx", "ppt", "xlsx", "xls", "odt", "odp", "ods", "rtf", "epub"].map((e) => [e, "office"])),
33
+ ...Object.fromEntries(["mp3", "wav", "m4a", "aac", "ogg", "oga", "opus", "flac", "wma", "amr"].map((e) => [e, "audio"])),
34
+ ...Object.fromEntries(["mp4", "mov", "mkv", "webm", "avi", "m4v", "3gp", "mpeg", "mpg"].map((e) => [e, "video"])),
35
+ };
36
+ /** The kind a file's name says, or null for anything not sent for text. */
37
+ export function mediaKindByName(name) {
38
+ const ext = /\.([a-z0-9]{1,8})$/i.exec(name)?.[1]?.toLowerCase();
39
+ return ext ? (BY_EXT[ext] ?? null) : null;
40
+ }
41
+ export function sniff(head) {
42
+ const at = (off, sig) => head.length >= off + sig.length && sig.every((b, i) => head[off + i] === b);
43
+ const ascii = (off, s) => head.length >= off + s.length && head.toString("latin1", off, off + s.length) === s;
44
+ if (at(0, [0x89, 0x50, 0x4e, 0x47]))
45
+ return "png";
46
+ if (at(0, [0xff, 0xd8, 0xff]))
47
+ return "jpeg";
48
+ if (ascii(0, "GIF8"))
49
+ return "gif";
50
+ if (ascii(0, "RIFF") && ascii(8, "WEBP"))
51
+ return "webp";
52
+ if (ascii(0, "RIFF") && ascii(8, "WAVE"))
53
+ return "wav";
54
+ if (ascii(0, "RIFF") && ascii(8, "AVI "))
55
+ return "avi";
56
+ if (at(0, [0x49, 0x49, 0x2a, 0x00]) || at(0, [0x4d, 0x4d, 0x00, 0x2a]))
57
+ return "tiff";
58
+ if (ascii(0, "BM"))
59
+ return "bmp";
60
+ if (ascii(0, "%PDF"))
61
+ return "pdf";
62
+ if (at(0, [0x50, 0x4b, 0x03, 0x04]))
63
+ return "zip";
64
+ if (at(0, [0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1]))
65
+ return "ole";
66
+ if (ascii(0, "{\\rtf"))
67
+ return "rtf";
68
+ if (ascii(0, "ID3") || (head.length >= 2 && head[0] === 0xff && (head[1] & 0xe6) === 0xe2))
69
+ return "mp3";
70
+ if (head.length >= 2 && head[0] === 0xff && (head[1] & 0xf6) === 0xf0)
71
+ return "aac";
72
+ if (ascii(0, "OggS"))
73
+ return "ogg";
74
+ if (ascii(0, "fLaC"))
75
+ return "flac";
76
+ if (ascii(0, "#!AMR"))
77
+ return "amr";
78
+ if (at(0, [0x30, 0x26, 0xb2, 0x75, 0x8e, 0x66, 0xcf, 0x11]))
79
+ return "asf";
80
+ if (ascii(4, "ftyp"))
81
+ return "isobmff";
82
+ if (at(0, [0x1a, 0x45, 0xdf, 0xa3]))
83
+ return "ebml";
84
+ if (at(0, [0x00, 0x00, 0x01, 0xba]))
85
+ return "mpeg-ps";
86
+ return null;
87
+ }
88
+ /** The containers each kind may arrive in. */
89
+ const FITS = {
90
+ image: new Set(["png", "jpeg", "gif", "webp", "tiff", "bmp", "isobmff"]),
91
+ pdf: new Set(["pdf"]),
92
+ office: new Set(["zip", "ole", "rtf"]),
93
+ audio: new Set(["mp3", "wav", "ogg", "flac", "aac", "amr", "asf", "isobmff", "ebml"]),
94
+ video: new Set(["isobmff", "ebml", "avi", "asf", "mpeg-ps", "ogg"]),
95
+ };
96
+ /** The kind, when the name and the first bytes agree on one; else null. */
97
+ export function mediaKind(name, head) {
98
+ const byName = mediaKindByName(name);
99
+ if (!byName)
100
+ return null;
101
+ const s = sniff(head);
102
+ return s && FITS[byName].has(s) ? byName : null;
103
+ }
104
+ /** Inputs whose text may be put beside them: the media ones, small enough,
105
+ * with no input already taking `<path>.txt`. What the prompt's note marks. */
106
+ export function textCandidates(files) {
107
+ const names = new Set(files.map((f) => f.path));
108
+ return files.filter((f) => mediaKindByName(f.path) && f.size <= INPUT_TEXT_LIMITS.fileBytes && !names.has(`${f.path}.txt`));
109
+ }
110
+ const short = (s) => s.replace(/\s+/g, " ").trim().slice(0, 200);
111
+ /**
112
+ * Write `<file>.txt` beside each media input the platform can read. Never
113
+ * throws for one file, and never runs past `totalMs`: what is left then is
114
+ * named in one line. Returns the .txt paths written (relative to `dir`) and
115
+ * the lines emitted.
116
+ */
117
+ export async function textBesideInputs(o) {
118
+ const totalMs = o.totalMs ?? INPUT_TEXT_LIMITS.totalMs;
119
+ const fileBytes = o.fileBytes ?? INPUT_TEXT_LIMITS.fileBytes;
120
+ const notes = [];
121
+ const note = (line) => {
122
+ notes.push(line);
123
+ try {
124
+ o.emit(line);
125
+ }
126
+ catch {
127
+ /* the trail's problem, not the run's */
128
+ }
129
+ };
130
+ const wrote = [];
131
+ const late = [];
132
+ const names = new Set(o.files.map((f) => f.path));
133
+ const clock = new AbortController();
134
+ // NOT unref'd: this function awaits the deadline, so the timer must keep
135
+ // the process alive until it fires (cleared in finally, at most totalMs).
136
+ // Unref'd, a hung extractor in a process with nothing else to do — the
137
+ // CLI's `foldrun run`, a test — let the event loop empty and the await
138
+ // never settle (the dev gate, 12 Nov 2026: "Promise resolution is still
139
+ // pending but the event loop has already resolved").
140
+ const timer = setTimeout(() => clock.abort(), totalMs);
141
+ try {
142
+ for (const f of o.files) {
143
+ const byName = mediaKindByName(f.path);
144
+ if (!byName)
145
+ continue;
146
+ const target = `${f.path}.txt`;
147
+ if (names.has(target)) {
148
+ note(`inputs: ${f.path} → no text (${target} is an input of its own)`);
149
+ continue;
150
+ }
151
+ if (clock.signal.aborted) {
152
+ late.push(f.path);
153
+ continue;
154
+ }
155
+ if (f.size > fileBytes) {
156
+ note(`inputs: ${f.path} → no text (larger than ${Math.round(fileBytes / 1048576)} MB)`);
157
+ continue;
158
+ }
159
+ const abs = path.join(o.dir, f.path);
160
+ const out = `${abs}.txt`;
161
+ try {
162
+ if (fs.existsSync(out)) {
163
+ note(`inputs: ${f.path} → no text (${target} is already there)`);
164
+ continue;
165
+ }
166
+ const bytes = fs.readFileSync(abs);
167
+ if (!mediaKind(f.path, bytes.subarray(0, 64))) {
168
+ note(`inputs: ${f.path} → no text (its bytes are not ${/^[aeiou]/.test(byName) ? "an" : "a"} ${byName} file)`);
169
+ continue;
170
+ }
171
+ // Raced against the budget: an extractor that ignores its signal (or
172
+ // hangs) must not hold the step's start past it; an answer arriving
173
+ // after the deadline is dropped, never written.
174
+ const r = await new Promise((resolve, reject) => {
175
+ if (clock.signal.aborted)
176
+ return reject(new Error("the budget ran out"));
177
+ const onAbort = () => reject(new Error("the budget ran out"));
178
+ clock.signal.addEventListener("abort", onAbort, { once: true });
179
+ o.extract({ tenant: o.tenant, workspace: o.workspace, runId: o.runId, name: path.basename(f.path), bytes, signal: clock.signal })
180
+ .then(resolve, reject)
181
+ .finally(() => clock.signal.removeEventListener("abort", onAbort));
182
+ });
183
+ if (clock.signal.aborted) {
184
+ late.push(f.path);
185
+ continue;
186
+ }
187
+ if (!r.text.trim()) {
188
+ note(`inputs: ${f.path} → no text (none found)`);
189
+ continue;
190
+ }
191
+ fs.writeFileSync(out, r.text.endsWith("\n") ? r.text : `${r.text}\n`, { flag: "wx" });
192
+ wrote.push(target);
193
+ }
194
+ catch (err) {
195
+ if (clock.signal.aborted) {
196
+ late.push(f.path);
197
+ continue;
198
+ }
199
+ const code = err?.code;
200
+ note(`inputs: ${f.path} → no text (${code === "EEXIST" ? `${target} is already there` : short(err?.message ?? String(err)) || "the extraction failed"})`);
201
+ }
202
+ }
203
+ }
204
+ finally {
205
+ clearTimeout(timer);
206
+ }
207
+ if (late.length)
208
+ note(`inputs: ${late.join(", ")} → no text (the ${Math.round(totalMs / 1000)} s for inputs' text ran out)`);
209
+ if (wrote.length)
210
+ note(`inputs: text beside ${wrote.length} file${wrote.length === 1 ? "" : "s"} — ${wrote.join(", ")}`);
211
+ return { wrote, notes };
212
+ }
@@ -58,6 +58,7 @@ const PLATFORM_SERVERS = {
58
58
  foldrun_desks: "desks",
59
59
  foldrun_ask: "ask",
60
60
  foldrun_peers: "peers",
61
+ foldrun_text: "text",
61
62
  };
62
63
  /** One spelling for comparing: `desk-email` and `desk_email` are the same
63
64
  * tool (a script tool's SDK name has its dashes made underscores). */
@@ -279,7 +280,7 @@ export class CallCounter {
279
280
  */
280
281
  export function limitKeyProblems(limits, ctx) {
281
282
  const out = [];
282
- const builtinKeys = ["read", "write", "code", ...Object.keys(BUILTIN_GROUP), "TodoWrite", "search", "history", "desks", "ask", "web", A2A_LIMIT_KEY];
283
+ const builtinKeys = ["read", "write", "code", ...Object.keys(BUILTIN_GROUP), "TodoWrite", "search", "history", "desks", "ask", "text", "web", A2A_LIMIT_KEY];
283
284
  const known = new Set([...builtinKeys, ...ctx.known].map(normKey));
284
285
  const granted = new Set([...ctx.granted].flatMap((g) => {
285
286
  const n = normKey(g);
@@ -9,6 +9,11 @@ export interface ManifestEntry {
9
9
  }
10
10
  export interface Manifest {
11
11
  v: 1;
12
+ /** Absent: a workspace manifest (paths under the authored/state roots).
13
+ * "run-output": what one agent of one run left in outputs/ (FOL-126 phase 5):
14
+ * any legal relative path, never a head, never restored. Part of the
15
+ * canonical form, so the two kinds can never share an id. */
16
+ kind?: "run-output";
12
17
  /** Forward-slashed paths, relative to the workspace root. */
13
18
  files: Record<string, ManifestEntry>;
14
19
  }
@@ -35,7 +40,7 @@ export declare const MAX_PATH_BYTES = 400;
35
40
  * rewritten whole on every publish; this bounds that cost until manifests
36
41
  * are sharded. 50k files is ~5 MB of canonical JSON. */
37
42
  export declare const MAX_MANIFEST_FILES = 50000;
38
- export declare function assertManifestPath(rel: string): string;
43
+ export declare function assertManifestPath(rel: string, kind?: Manifest["kind"]): string;
39
44
  /** Two paths that differ only by case cannot both be extracted on a
40
45
  * case-insensitive disk (macOS and Windows laptops, Docker Desktop volumes).
41
46
  * Display casing is kept; a collision inside one manifest is refused. */
@@ -90,7 +90,7 @@ export const MAX_PATH_BYTES = 400;
90
90
  * rewritten whole on every publish; this bounds that cost until manifests
91
91
  * are sharded. 50k files is ~5 MB of canonical JSON. */
92
92
  export const MAX_MANIFEST_FILES = 50_000;
93
- export function assertManifestPath(rel) {
93
+ export function assertManifestPath(rel, kind) {
94
94
  if (typeof rel !== "string" || !rel || Buffer.byteLength(rel) > MAX_PATH_BYTES)
95
95
  throw new Error(`illegal manifest path: ${String(rel).slice(0, 80)}`);
96
96
  if (rel.includes("\\") || rel.startsWith("/") || /^[a-zA-Z]:/.test(rel))
@@ -104,7 +104,7 @@ export function assertManifestPath(rel) {
104
104
  // extracts the same everywhere. (Case is handled per manifest, below.)
105
105
  if (rel !== rel.normalize("NFC"))
106
106
  throw new Error(`illegal manifest path (not NFC-normalised): ${rel}`);
107
- if (sideOf(rel) === null)
107
+ if (kind !== "run-output" && sideOf(rel) === null)
108
108
  throw new Error(`${rel} is not workspace content (authored: ${[...AUTHORED_DIRS, ...AUTHORED_ROOT_FILES].join(", ")}; state: state/)`);
109
109
  return rel;
110
110
  }
@@ -136,7 +136,7 @@ export function assertEntry(p, e) {
136
136
  * to WRITE — a revision must never point at a manifest it cannot read back. */
137
137
  export function assertManifest(m) {
138
138
  for (const [p, e] of Object.entries(m.files)) {
139
- assertManifestPath(p);
139
+ assertManifestPath(p, m.kind);
140
140
  assertEntry(p, e);
141
141
  }
142
142
  assertNoCaseCollisions(m);
@@ -151,12 +151,13 @@ export function modeFor(executable) {
151
151
  /** Sorted keys at every level, no whitespace: one tree, one byte string, one
152
152
  * id — whichever machine wrote it. */
153
153
  export function canonicalManifest(m) {
154
- const files = {};
154
+ // No prototype: a path may be `__proto__` (review, 12 Nov 2026).
155
+ const files = Object.create(null);
155
156
  for (const p of Object.keys(m.files).sort()) {
156
157
  const e = m.files[p];
157
158
  files[p] = { sha: e.sha, size: e.size, mode: e.mode };
158
159
  }
159
- return JSON.stringify({ v: 1, files });
160
+ return JSON.stringify(m.kind ? { v: 1, kind: m.kind, files } : { v: 1, files });
160
161
  }
161
162
  export function manifestId(m) {
162
163
  return sha256Hex(canonicalManifest(m));
@@ -173,6 +174,8 @@ export function parseManifest(text) {
173
174
  if (raw?.v !== 1 || typeof raw.files !== "object" || raw.files === null || Array.isArray(raw.files)) {
174
175
  throw new Error("not a manifest (v1)");
175
176
  }
177
+ if (raw.kind !== undefined && raw.kind !== "run-output")
178
+ throw new Error("not a manifest (unknown kind)");
176
179
  assertManifest(raw);
177
180
  return raw;
178
181
  }
@@ -96,12 +96,18 @@ export const FIELDS = {
96
96
  runId: "id", jobId: "id", taskId: "id", proposal: "id", lease: "id", pod: "id",
97
97
  worker: "id", provider: "id", plan: "id", fingerprint: "id", invoice: "id", order: "id",
98
98
  stripeEvent: "id", subscription: "id", migration: "id", housekeeping: "id",
99
+ // Who asked, for the operator console's per-account timeline (D239 phase 1,
100
+ // 12 Nov 2026): a member's id and an API key's id (never an email — `@`
101
+ // does not fit an id, so one cannot slip in), and the request's own id.
102
+ user: "id", key: "id", requestId: "id",
99
103
  // How many, how long, how much.
100
104
  count: "num", ms: "num", secs: "num", bytes: "num", usd: "num", attempt: "num",
101
105
  step: "num", port: "num", status: "num", exitCode: "num", percent: "num", tries: "num",
102
106
  // What kind.
103
107
  op: "word", role: "word", outcome: "word", reason: "word", stream: "word", kind: "word",
104
108
  verdict: "word", phase: "word", signal: "code", where: "word",
109
+ // Where a refusal happened: login, api, gateway, mcp, a2a, egress, webhook.
110
+ surface: "word",
105
111
  // A run's sandbox (FOL-122): the runner image and size class — the
106
112
  // platform's own words — and the model, an identifier like a flow's name
107
113
  // (one with `/` or `:` in it does not fit, and is dropped).
@@ -146,11 +152,19 @@ export function opsLine(level, event, fields = {}) {
146
152
  line.dropped = dropped;
147
153
  return line;
148
154
  }
149
- /** The real streams, once the boundary holds them; null outside it. */
150
- let real = null;
155
+ /** The real streams, once the boundary holds them; null outside it. Held on
156
+ * globalThis, not in this module: a bundler can load this file more than
157
+ * once in one process (Next.js gives the instrumentation hook and the route
158
+ * handlers their own copies), and a copy that could not see the boundary
159
+ * printed the readable form through console.*, which the boundary then
160
+ * turned into a bare {"event":"console"} line — every web route's ops line
161
+ * was lost that way (D239 phase 1, found on dev 12 Nov 2026). */
162
+ const BOUNDARY = Symbol.for("foldrun.ops-log.boundary");
163
+ const shared = globalThis;
164
+ const boundary = () => shared[BOUNDARY] ?? null;
151
165
  /** Is this process inside the boundary — a hosted pod? */
152
166
  export function opsBoundaryInstalled() {
153
- return real !== null;
167
+ return boundary() !== null;
154
168
  }
155
169
  function readable(level, line, detail) {
156
170
  const parts = Object.entries(line)
@@ -159,6 +173,7 @@ function readable(level, line, detail) {
159
173
  return `[ops] ${line.event}${parts.length ? ` ${parts.join(" ")}` : ""}${detail ? ` — ${detail}` : ""}`;
160
174
  }
161
175
  function emit(level, line, detail) {
176
+ const real = boundary();
162
177
  if (real) {
163
178
  (level === "info" ? real.out : real.err)(JSON.stringify(line) + "\n");
164
179
  return;
@@ -338,7 +353,7 @@ function messageOf(err) {
338
353
  /** A failure: its class and where it happened — never its words inside the
339
354
  * boundary. A field the caller names (an `errorClass` it knows) wins. */
340
355
  export function opsError(event, err, fields = {}, level = "error") {
341
- 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));
342
357
  }
343
358
  // ----------------------------------------------------------------- boundary
344
359
  /** Where in our code a raw console call was made: the first frame outside
@@ -363,13 +378,13 @@ function callsite() {
363
378
  */
364
379
  export function installOpsBoundary(opts = {}) {
365
380
  const env = opts.env ?? process.env;
366
- if (real)
381
+ if (boundary())
367
382
  return true;
368
383
  if (env.FOLDRUN_LOG_MODE === "raw" || (env.FOLDRUN_LOG_MODE !== "ops" && env.NODE_ENV === "development"))
369
384
  return false;
370
385
  const outWrite = process.stdout.write.bind(process.stdout);
371
386
  const errWrite = process.stderr.write.bind(process.stderr);
372
- real = { out: (s) => void outWrite(s), err: (s) => void errWrite(s) };
387
+ shared[BOUNDARY] = { out: (s) => void outWrite(s), err: (s) => void errWrite(s) };
373
388
  const fromConsole = (level) => (...args) => {
374
389
  // Never formatted: an argument's text, its inspect() and its toJSON()
375
390
  // are not read. An Error handed over gives its class, name and code.
@@ -4,6 +4,17 @@ import type { RunInContainerArgs, ContainerStepOutcome } from "./run-container.t
4
4
  import type { EgressHooks } from "./egress.ts";
5
5
  import type { RecordsPort } from "./records.ts";
6
6
  export type IsolatedStepRunner = (args: RunInContainerArgs) => Promise<ContainerStepOutcome>;
7
+ /** One of a run's inputs, sent for its text at staging (input-text.ts). */
8
+ export interface ExtractTextAsk {
9
+ tenant: string;
10
+ workspace: string;
11
+ runId: string;
12
+ /** The file's name (its last segment): the extension helps the parser. */
13
+ name: string;
14
+ bytes: Buffer;
15
+ /** Aborts when staging's time for inputs runs out. */
16
+ signal: AbortSignal;
17
+ }
7
18
  /** Who this install is for. `hosted` means someone is paying the operator
8
19
  * for it — a wallet, a plan, a bill. `self-hosted` is everything else: a
9
20
  * laptop, a dev install, a box nobody bills on. */
@@ -173,6 +184,18 @@ export interface PlatformHooks {
173
184
  * can; a run with inputs on one that cannot fails before anything starts
174
185
  * (FOL-163). Default: none can. */
175
186
  holdsInputs?(isolation: string): boolean;
187
+ /**
188
+ * The text of one of a run's media inputs, for the `<file>.txt` written
189
+ * beside it at staging (input-text.ts textBesideInputs): OCR, a
190
+ * document's text, a transcript. Throws when it cannot — the caller notes
191
+ * why and moves on; the run never fails for it. Absent: no extraction on
192
+ * this install (a laptop, or a platform without the service), and no
193
+ * `.txt` is written or promised in the prompt.
194
+ */
195
+ extractText?(ask: ExtractTextAsk): Promise<{
196
+ text: string;
197
+ warnings?: string[];
198
+ }>;
176
199
  /**
177
200
  * Does this isolation mode wall a step whose `network:` is restricted and
178
201
  * enforced to the egress proxy alone (a `filtered` pod)? True: such a
@@ -115,4 +115,5 @@ export function platformQueues() {
115
115
  export function resetPlatform() {
116
116
  Object.assign(platform, local, { isolation: {} });
117
117
  delete platform.records;
118
+ delete platform.extractText;
118
119
  }
@@ -16,10 +16,21 @@ export interface RecordsPortAsync {
16
16
  * lock its async context holds, with the event loop free while it waits.
17
17
  * Optional like the reads: a port without it is written through runPut. */
18
18
  runPut?(tenant: string, workspace: string, run: RunRecord, summary: RunSummary, live: boolean): Promise<void>;
19
+ /** What a step was handed and started from, per run (FOL-126 phase 7, step
20
+ * state): small JSON, one row per (run, kind, ref). Optional like the rest;
21
+ * step-state.ts is the only caller. */
22
+ stepGet?(tenant: string, workspace: string, runId: string, kind: string, ref: string): Promise<unknown | undefined>;
23
+ stepPut?(tenant: string, workspace: string, runId: string, kind: string, ref: string, data: unknown): Promise<void>;
24
+ /** `ref` null: every ref of the kind. */
25
+ stepDrop?(tenant: string, workspace: string, runId: string, kind: string, ref: string | null): Promise<void>;
19
26
  }
20
27
  export interface RecordsPort {
21
28
  /** Async reads (see RecordsPortAsync). */
22
29
  async?: RecordsPortAsync;
30
+ /** The `runs.step_state_store` setting, read per call: while false, step
31
+ * state is written to the run's folder as before (it is still READ from
32
+ * rows first, so switching off mid-run loses nothing). */
33
+ stepStateOn?(): boolean;
23
34
  /** Insert or replace one run. `live`: queued, running or parked at a gate. Last write wins. */
24
35
  runPut(tenant: string, workspace: string, run: RunRecord, summary: RunSummary, live: boolean): void;
25
36
  runGet(tenant: string, workspace: string, id: string): RunRecord | null;