@foldrun/core 19.2.0 → 20.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/src/browser-pod.js +4 -0
  2. package/dist/src/completions.js +1 -0
  3. package/dist/src/egress.d.ts +5 -1
  4. package/dist/src/input-text.d.ts +48 -0
  5. package/dist/src/input-text.js +212 -0
  6. package/dist/src/limits.js +2 -1
  7. package/dist/src/manifest.d.ts +6 -1
  8. package/dist/src/manifest.js +8 -5
  9. package/dist/src/ops-log.js +21 -6
  10. package/dist/src/platform.d.ts +23 -0
  11. package/dist/src/platform.js +1 -0
  12. package/dist/src/records.d.ts +11 -0
  13. package/dist/src/run-container.d.ts +11 -7
  14. package/dist/src/run-container.js +50 -11
  15. package/dist/src/run-inputs.d.ts +6 -1
  16. package/dist/src/run-inputs.js +10 -2
  17. package/dist/src/run-output-refusal.d.ts +3 -0
  18. package/dist/src/run-output-refusal.js +16 -0
  19. package/dist/src/run-outputs.d.ts +134 -0
  20. package/dist/src/run-outputs.js +521 -0
  21. package/dist/src/runner.d.ts +1 -0
  22. package/dist/src/runner.js +59 -11
  23. package/dist/src/starter.js +1 -1
  24. package/dist/src/step-state.d.ts +10 -0
  25. package/dist/src/step-state.js +93 -0
  26. package/dist/src/storage.d.ts +12 -1
  27. package/dist/src/storage.js +50 -16
  28. package/dist/src/store.d.ts +25 -4
  29. package/dist/src/store.js +15 -4
  30. package/dist/src/text-tool.d.ts +177 -0
  31. package/dist/src/text-tool.js +220 -0
  32. package/dist/src/tool-names.d.ts +3 -1
  33. package/dist/src/tool-names.js +4 -2
  34. package/dist/src/workspace-revisions.js +11 -0
  35. package/package.json +1 -1
  36. package/src/browser-pod.ts +3 -0
  37. package/src/completions.ts +1 -0
  38. package/src/egress.ts +5 -2
  39. package/src/input-text.ts +215 -0
  40. package/src/limits.ts +2 -1
  41. package/src/manifest.ts +12 -5
  42. package/src/ops-log.ts +22 -6
  43. package/src/platform.ts +22 -0
  44. package/src/records.ts +11 -0
  45. package/src/run-container.ts +49 -11
  46. package/src/run-inputs.ts +10 -2
  47. package/src/run-output-refusal.ts +20 -0
  48. package/src/run-outputs.ts +597 -0
  49. package/src/runner.ts +55 -10
  50. package/src/starter.ts +1 -1
  51. package/src/step-state.ts +97 -0
  52. package/src/storage.ts +45 -15
  53. package/src/store.ts +32 -4
  54. package/src/text-tool.ts +267 -0
  55. package/src/tool-names.ts +4 -2
  56. package/src/workspace-revisions.ts +11 -0
@@ -101,6 +101,9 @@ export interface ContainerStepInput {
101
101
  self: string;
102
102
  siblings: PeerInfo[];
103
103
  };
104
+ /** tools: [text] — extract_text, rebuilt in here over the lease's /text
105
+ * door to the extraction service (text-tool.ts). */
106
+ text?: boolean;
104
107
  /** A Chat-Completions provider: the driver starts the runtime's translator
105
108
  * on loopback and points the SDK at it. Null or absent: the env's
106
109
  * ANTHROPIC_BASE_URL is spoken to directly. */
@@ -244,12 +247,13 @@ export declare function hashTree(dir: string): Record<string, string>;
244
247
  * read back from there, where the step could rewrite it (FOL-96).
245
248
  */
246
249
  export declare function handedInPath(workspaceRoot: string, runId: string, ref: string): string | null;
247
- /** Note what a sandbox was handed, on the host. */
248
- export declare function writeHandedIn(workspaceRoot: string, runId: string, ref: string, hashes: Record<string, string>): void;
250
+ /** Note what a sandbox was handed, on the host. With `tenant`, where step
251
+ * state is kept in the database (step-state.ts), a row; otherwise the file. */
252
+ export declare function writeHandedIn(workspaceRoot: string, runId: string, ref: string, hashes: Record<string, string>, tenant?: string): Promise<void>;
249
253
  /** What the host noted a sandbox was handed, or undefined. */
250
- export declare function readHandedIn(workspaceRoot: string, runId: string, ref: string): Record<string, string> | undefined;
254
+ export declare function readHandedIn(workspaceRoot: string, runId: string, ref: string, tenant?: string): Promise<Record<string, string> | undefined>;
251
255
  /** Forget it once the step's copy-out is done. */
252
- export declare function dropHandedIn(workspaceRoot: string, runId: string, ref: string): void;
256
+ export declare function dropHandedIn(workspaceRoot: string, runId: string, ref: string, tenant?: string): Promise<void>;
253
257
  /**
254
258
  * The revisions a step's stage-in started from (FOL-126 fixes), kept on the host
255
259
  * beside what it was handed, for the same reason: a driver that inherits the
@@ -257,8 +261,8 @@ export declare function dropHandedIn(workspaceRoot: string, runId: string, ref:
257
261
  * heads hold by then. Platform-owned, never staged, erased with the run.
258
262
  */
259
263
  export declare function baseRevisionPath(workspaceRoot: string, runId: string, ref: string): string | null;
260
- export declare function writeBaseRevision(workspaceRoot: string, runId: string, ref: string, base: RunBase): void;
261
- export declare function readBaseRevision(workspaceRoot: string, runId: string, ref: string): RunBase | undefined;
264
+ export declare function writeBaseRevision(workspaceRoot: string, runId: string, ref: string, base: RunBase, tenant?: string): Promise<void>;
265
+ export declare function readBaseRevision(workspaceRoot: string, runId: string, ref: string, tenant?: string): Promise<RunBase | undefined>;
262
266
  /**
263
267
  * Every file's mtime under `dir`, relative path to milliseconds — so a copy
264
268
  * that cannot carry times can have them put back. `kubectl cp` unpacks with
@@ -410,7 +414,7 @@ export declare function runtimeCacheMount(tenant: string | undefined): {
410
414
  target: string;
411
415
  } | null;
412
416
  /** The runner container's entrypoint, as JS text: written into the image as driver.mjs, so it must be plain JS — a TypeScript cast here broke every step on v2026.10.21.5 (tests/run-container.test.ts checks it). */
413
- export declare const DRIVER = "// The runner container's entrypoint. Reads one step, executes it with the\n// same core the server uses, speaks JSONL on stdout, exits.\nimport fs from \"node:fs\";\nconst input = JSON.parse(fs.readFileSync(\"/opt/runner/job/input.json\", \"utf8\"));\n// Start-up marks (run-container.ts#STARTUP_PHASES): which phase just ended,\n// on the sandbox's clock. A worker that does not know a mark skips the line.\nconst mark = (name) => process.stdout.write(JSON.stringify({ e: \"mark\", name, at: Date.now() }) + \"\\n\");\nmark(\"driver\");\nlet modelSpoke = false;\nconst emit = (type, text, extra) => {\n // The model's first text or tool call is where start-up ends and the\n // step's own work begins \u2014 runtime and tool lines before it are set-up.\n if (!modelSpoke && (type === \"text\" || type === \"tool\")) { modelSpoke = true; mark(\"model\"); }\n process.stdout.write(JSON.stringify({ e: \"event\", type, text, ...extra }) + \"\\n\");\n};\n// What this sandbox actually touched, read at the last moment from the\n// kernel's own books: cgroup v2 for CPU busy-time and peak memory,\n// /proc/net/dev for bytes on the wire. Every read is best-effort \u2014 gVisor\n// exposes some of these files and not others depending on version, and a\n// metric we cannot read is null, never guessed. Reservation is what is\n// billed; these exist so the reservation can be right-sized.\nfunction readActuals() {\n // fs from the module's own import \u2014 the driver is ESM, and a require()\n // here threw on every call, silently nulling every metric it guarded.\n const read = (p) => { try { return fs.readFileSync(p, \"utf8\"); } catch { return null; } };\n // Two cgroup dialects: v2 (cpu.stat, microseconds; memory.peak) on a\n // plain runtime, v1-style controllers under gVisor (cpuacct.usage,\n // NANOseconds; memory.max_usage_in_bytes) \u2014 probed on the real cluster,\n // not assumed. Whichever answers wins; both silent means null.\n const cpuStat = read(\"/sys/fs/cgroup/cpu.stat\");\n const usage = cpuStat?.match(/^usage_usec (\\d+)/m);\n const cpuacctNs = usage ? NaN : Number(read(\"/sys/fs/cgroup/cpuacct/cpuacct.usage\")?.trim());\n // Time the CPU cap held the sandbox back: v2's throttled_usec in the same\n // cpu.stat, v1's throttled_time (nanoseconds) under gVisor. Large against\n // busy time means the step wanted more cores than its class gives.\n const throttledUs = cpuStat?.match(/^throttled_usec (\\d+)/m);\n const throttledNs = throttledUs ? null : read(\"/sys/fs/cgroup/cpu/cpu.stat\")?.match(/^throttled_time (\\d+)/m);\n const peak =\n read(\"/sys/fs/cgroup/memory.peak\") ??\n read(\"/sys/fs/cgroup/memory/memory.max_usage_in_bytes\") ??\n read(\"/sys/fs/cgroup/memory/memory.usage_in_bytes\");\n let rx = 0, tx = 0, sawNet = false;\n const net = read(\"/proc/net/dev\");\n if (net) {\n for (const line of net.split(\"\\n\").slice(2)) {\n const m = line.trim().match(/^(\\S+):\\s+(\\d+)(?:\\s+\\d+){7}\\s+(\\d+)/);\n if (m && m[1] !== \"lo\") { rx += Number(m[2]); tx += Number(m[3]); sawNet = true; }\n }\n }\n return {\n busyCpuSecs: usage\n ? Number(usage[1]) / 1e6\n : Number.isFinite(cpuacctNs) && cpuacctNs > 0\n ? cpuacctNs / 1e9\n : null,\n peakMemBytes: peak ? Number(peak.trim()) || null : null,\n throttledSecs: throttledUs ? Number(throttledUs[1]) / 1e6 : throttledNs ? Number(throttledNs[1]) / 1e9 : null,\n rxBytes: sawNet ? rx : null,\n txBytes: sawNet ? tx : null,\n };\n}\n\ntry {\n // Runtime state (venvs, npm prefixes) lands in the agent user's real home\n // \u2014 writable, inside the container, gone with it.\n process.env.FOLDRUN_DATA = \"/home/agent/.foldrun\";\n const { executeStep } = await import(\"@foldrun/core/step-exec\");\n const { buildApiTools } = await import(\"@foldrun/core/api-tools\");\n const { buildA2ATools } = await import(\"@foldrun/core/a2a-tools\");\n const { buildScriptTools } = await import(\"@foldrun/core/script-tools\");\n const { buildConsultTools } = await import(\"@foldrun/core/agent-tools\");\n const { buildSearchTools, buildHistoryTools, buildDeskTools } = await import(\"@foldrun/core/context-tools\");\n const { httpChannel, buildAskTool, buildPeerTools, inboxReader } = await import(\"@foldrun/core/operator\");\n const { buildDelegateTools } = await import(\"@foldrun/core/delegate-tools\");\n const { startTranslator } = await import(\"@foldrun/core/translator\");\n const { prepareRuntime } = await import(\"@foldrun/core/runtime\");\n const { materializeFileSecrets } = await import(\"@foldrun/core/secret-files\");\n const { paidWebActions } = await import(\"@foldrun/core/browser-pod\");\n mark(\"imports\");\n\n const agentDir = \"/workspace/\" + input.agentRel;\n // HOME is where a bare relative path lands when anything resolves one\n // outside cwd \u2014 and root's /root is outside the workspace, so such a read\n // was refused by confinement with a path the agent never typed. Its own\n // directory is both the truthful answer and the safe one.\n // @file secrets crossed as content; materialise them to 0600 paths inside\n // the container (a host path from the other side would not exist here).\n const env = materializeFileSecrets(agentDir, { ...process.env, HOME: agentDir }).env;\n // Caches go to the sandbox user's own home, not to HOME: the Claude CLI's\n // logs, fontconfig, Mesa and gstreamer all follow XDG_CACHE_HOME, and under\n // agents/<name>/.cache they were copied back after every step \u2014 3,855 files\n // across 179 agent folders on the box by 17 Oct 2026, read by nothing.\n env.XDG_CACHE_HOME = \"/home/agent/.cache\";\n\n // The declared runtime, built in here \u2014 pip and npm have the network, which\n // the host side may not. It lands in .foldrun/runner/.runtimes, which the\n // executors mount from a per-tenant directory (run-container.ts#RUNTIME_CACHE):\n // the first step for a given fingerprint installs, every later one finds\n // .ready and skips. With no mount it still works, just fresh every time \u2014\n // which is what this used to be unconditionally. The log says which happened.\n const runtime = input.runtime\n ? prepareRuntime(\"runner\", input.runtime)\n : { interpreters: {}, env: {}, log: [], error: null };\n for (const line of runtime.log) emit(\"info\", \"runtime: \" + line);\n if (runtime.error) emit(\"error\", \"runtime: \" + runtime.error);\n // The step's own environment gets it too, not only the script tools: an\n // agent that runs \"python3 x.py\" or a shebang script through Bash should\n // meet the packages its runtime declared, not the image's bare python.\n Object.assign(env, runtime.env);\n\n // install: what the agent finds it needs mid-step. apt goes through the\n // root start-up's helper (install-helper.ts); pip and npm land in a\n // directory of this container's own, on the paths from the first turn.\n const { buildInstallTool, INSTALL_TOOL } = await import(\"@foldrun/core/install-tool\");\n const { stepInstallEnv, INSTALL_SOCKET } = await import(\"@foldrun/core/runtime\");\n const installDir = \"/home/agent/.foldrun/step\";\n const installing = (input.allowed ?? []).includes(INSTALL_TOOL);\n if (installing) Object.assign(env, stepInstallEnv(installDir, env));\n const install = installing\n ? buildInstallTool({\n dir: installDir,\n socket: env.FOLDRUN_INSTALL_SOCKET || INSTALL_SOCKET,\n cacheRoot: \"/home/agent/.foldrun/runner/.runtimes\",\n python: env.VIRTUAL_ENV ? env.VIRTUAL_ENV + \"/bin/python\" : \"python3\",\n env,\n emit,\n })\n : { server: null };\n\n // API and script tools, rebuilt in here from their specs. Secrets were\n // substituted into API headers before the input crossed the boundary, so\n // buildApiTools gets an already-resolved environment. verify: gets the\n // container's own environment, whole: it is the boundary, assembled on\n // the host from an allowlist, and the declared secrets are in it.\n // A long result is kept in a file only when the agent can read it back.\n // (tool-output.ts canReadBack, inlined: the driver imports core by subpath.)\n const keepIn = { dir: agentDir, readable: () => (input.allowed ?? []).some((t) => t === \"Read\" || t === \"Grep\") };\n // A declared secret named like a model variable crosses as\n // FOLDRUN_DECLARED_<NAME> (runner.ts, FOL-19): the model keeps its own\n // settings, and the agent's API and script tools and verify: get the value\n // back under the name it declared. Built here, after the runtime and any\n // mid-step install have added their paths to env.\n const toolEnv = { ...env };\n for (const [k, v] of Object.entries(env)) if (k.startsWith(\"FOLDRUN_DECLARED_\")) toolEnv[k.slice(\"FOLDRUN_DECLARED_\".length)] = v;\n const api = buildApiTools(\"\", input.apis, undefined, { env: toolEnv, missing: [] }, keepIn);\n // remotes: \u2014 the four a2a tools, rebuilt from values. Each token crossed in\n // its spec (a placeholder the proxy fills for the card's origin alone), so\n // nothing here asks a vault; handles go under the workspace's state/.\n const a2a = input.a2a && Array.isArray(input.a2a.remotes) && input.a2a.remotes.length\n ? buildA2ATools(\"\", input.a2a.remotes, undefined, { env: {}, missing: [] }, {\n stateDir: \"/workspace/state/a2a/\" + input.agentRel.split(\"/\").pop(),\n runId: input.a2a.runId,\n step: input.a2a.step,\n egress: env.FOLDRUN_EGRESS || null,\n test: env.FOLDRUN_TEST_MODE === \"1\",\n keepIn,\n emit,\n })\n : { server: null, drainLog: () => [] };\n const script = buildScriptTools(\n agentDir,\n input.scripts,\n toolEnv,\n \"/library/scripts\",\n runtime.interpreters,\n null,\n keepIn.readable,\n );\n // The translator, when the provider speaks Chat Completions: a loopback\n // server for the length of this step. Its env replaces the endpoint the\n // host assembled; the provider's real URL and key stay inside it.\n const translator = input.translator ? await startTranslator(input.translator) : null;\n if (translator) {\n Object.assign(env, translator.env);\n emit(\"info\", \"translator: listening on \" + translator.baseUrl + \" for \" + (input.translator.label ?? input.translator.upstreamBase));\n }\n const consult = buildConsultTools(input.consults ?? [], env, emit);\n // The platform's own two groups, rebuilt from values like everything else.\n const search = buildSearchTools(input.search ?? []);\n const history = input.history?.length ? buildHistoryTools(input.history) : { server: null };\n const desks = input.desks?.length ? buildDeskTools(input.desks) : { server: null };\n // A person in the loop, over the proxy this step's lease already names:\n // ask_person when tools: [ask], and the run's inbox after every tool call.\n const channel = httpChannel(env.FOLDRUN_EGRESS);\n const ask = input.ask ? buildAskTool({ channel, timeoutSec: input.ask.timeoutSec, emit }) : { server: null };\n const peers = input.peers ? buildPeerTools({ channel, self: input.peers.self, siblings: input.peers.siblings, emit }) : { server: null };\n const inbox = channel ? inboxReader(channel, emit) : undefined;\n // sandbox: own sub-agents: a tool each, whose job runs in its own sandbox\n // on the worker, reached over the same proxy door.\n const delegate = input.delegates?.length ? buildDelegateTools({ specs: input.delegates, channel, emit, timeoutSec: input.timeoutSec, workspaceRoot: \"/workspace\" }) : { server: null };\n\n // Keyless cloud identities (FOLDRUN_IDENTITIES): each token file kept\n // fresh through the proxy's /identity door, which mints only what this\n // step's lease was granted. Fetched before the step starts, renewed five\n // minutes before it expires (with jitter); a failure is said and retried.\n // Plain JS: this text is the driver, not TypeScript.\n const identityNames = (env.FOLDRUN_IDENTITIES || \"\").split(\",\").filter(Boolean);\n if (identityNames.length) {\n // No backslashes: this sits inside a template literal, which eats them.\n const ep = new RegExp(\"^(https?://[^/]+)/e/([A-Za-z0-9_-]{16,})/?$\").exec(env.FOLDRUN_EGRESS || \"\");\n const dir = env.FOLDRUN_IDENTITY_DIR || \"/tmp/foldrun-identity\";\n fs.mkdirSync(dir, { recursive: true, mode: 0o700 });\n const keepFresh = async (name) => {\n let wait = 30000;\n try {\n if (!ep) throw new Error(\"no egress proxy to ask\");\n const res = await fetch(ep[1] + \"/identity/\" + ep[2] + \"/\" + name, { signal: AbortSignal.timeout(15000) });\n const body = await res.json().catch(() => ({}));\n if (!res.ok || !body.token) throw new Error((body.error && body.error.message) || (\"proxy answered \" + res.status));\n const file = dir + \"/\" + name.toLowerCase() + \".jwt\";\n fs.writeFileSync(file + \".tmp\", body.token, { mode: 0o600 });\n fs.renameSync(file + \".tmp\", file);\n wait = Math.max(30000, body.expiresAt - Date.now() - 300000 + Math.floor(Math.random() * 60000) - 30000);\n } catch (err) {\n emit(\"error\", \"identity \" + name + \": \" + (err && err.message ? err.message : String(err)) + \" \u2014 trying again in 30s\");\n }\n setTimeout(() => { void keepFresh(name); }, wait).unref();\n };\n await Promise.all(identityNames.map(keepFresh));\n }\n\n mark(\"tools\");\n const outcome = await executeStep({\n agentDir,\n workspaceRoot: \"/workspace\",\n libraryRoot: \"/library\",\n configWrites: input.configWrites === true,\n prompt: input.prompt,\n model: input.model,\n effort: input.effort ?? null,\n systemPrompt: input.systemPrompt,\n allowed: input.allowed,\n mcpNames: input.mcpNames,\n mcpServers: {\n ...(api.server ? { foldrun_apis: api.server } : {}),\n ...(a2a.server ? { foldrun_a2a: a2a.server } : {}),\n ...(script.server ? { foldrun_scripts: script.server } : {}),\n ...(consult.server ? { foldrun_agents: consult.server } : {}),\n ...(search.server ? { foldrun_search: search.server } : {}),\n ...(history.server ? { foldrun_history: history.server } : {}),\n ...(desks.server ? { foldrun_desks: desks.server } : {}),\n ...(ask.server ? { foldrun_ask: ask.server } : {}),\n ...(peers.server ? { foldrun_peers: peers.server } : {}),\n ...(delegate.server ? { foldrun_delegate: delegate.server } : {}),\n ...(install.server ? { foldrun_install: install.server } : {}),\n ...input.mcpServers,\n },\n ...(inbox ? { inbox } : {}),\n ...(input.subagents?.length ? { subagents: input.subagents } : {}),\n env,\n timeoutSec: input.timeoutSec,\n budgetUsd: input.budgetUsd,\n budgetNote: input.budgetNote,\n price: input.price,\n verify: input.verify,\n verifyEnv: toolEnv,\n ...(typeof input.judgeModel === \"string\" ? { judgeModel: input.judgeModel } : {}),\n ...(typeof input.judgeEffort === \"string\" ? { judgeEffort: input.judgeEffort } : {}),\n output: input.output,\n schema: input.schema,\n maxTurns: input.maxTurns,\n ...(input.capture === \"metadata\" || input.capture === \"full\" ? { capture: input.capture } : {}),\n ...(input.limits && Object.keys(input.limits).length ? { limits: input.limits, toolOwners: input.toolOwners ?? {} } : {}),\n ...(input.hookNames?.length ? { hookNames: input.hookNames, hookBase: input.hookBase ?? {} } : {}),\n // Slim browsing: the platform put this step on the slim image to browse\n // through the account's pod, and named the file the web tool logs its\n // reconnects to. A lost pod stops the step; what it wrote decides what\n // the runner does next (browser-pod.ts).\n ...(env.FOLDRUN_BROWSER_POD_EVENTS ? { browserPod: { events: env.FOLDRUN_BROWSER_POD_EVENTS, methods: api.methods ?? {}, paidWeb: paidWebActions(env), ...(env.FOLDRUN_BROWSER_INIT ? { browseInit: env.FOLDRUN_BROWSER_INIT } : {}) } } : {}),\n // The container is the boundary; the SDK's own bash sandbox here would\n // only block declared network use (SSH, curl) for no added safety.\n sandboxBash: false,\n emit,\n });\n for (const line of api.drainLog()) emit(\"info\", \"api: \" + line);\n for (const line of a2a.drainLog()) emit(\"info\", \"a2a: \" + line);\n for (const line of script.drainLog()) emit(\"info\", \"script: \" + line);\n if (translator) {\n for (const line of translator.drainLog()) emit(\"info\", line.startsWith(\"translator\") ? line : \"translator: \" + line);\n await translator.close();\n }\n // A consult's spend belongs to the step that asked.\n const consultCost = consult.drainCost();\n if (consultCost > 0) outcome.costUsd = (outcome.costUsd ?? 0) + consultCost;\n if (consultCost > 0 && typeof outcome.turnsCostUsd === \"number\") outcome.turnsCostUsd += consultCost;\n process.stdout.write(JSON.stringify({ e: \"done\", ...outcome, res: readActuals() }) + \"\\n\");\n process.exit(0);\n} catch (err) {\n emit(\"error\", err instanceof Error ? err.message : String(err));\n // The failure path reports actuals too \u2014 a step that died eleven minutes\n // in still held its slice for eleven minutes, and the failed runs are\n // exactly the ones whose resource story gets read.\n let res = null;\n try { res = readActuals(); } catch { /* the reading must never mask the error */ }\n process.stdout.write(JSON.stringify({ e: \"done\", status: \"failed\", result: null, costUsd: null, res }) + \"\\n\");\n process.exit(0);\n}\n";
417
+ export declare const DRIVER = "// The runner container's entrypoint. Reads one step, executes it with the\n// same core the server uses, speaks JSONL on stdout, exits.\nimport fs from \"node:fs\";\nconst input = JSON.parse(fs.readFileSync(\"/opt/runner/job/input.json\", \"utf8\"));\n// Start-up marks (run-container.ts#STARTUP_PHASES): which phase just ended,\n// on the sandbox's clock. A worker that does not know a mark skips the line.\nconst mark = (name) => process.stdout.write(JSON.stringify({ e: \"mark\", name, at: Date.now() }) + \"\\n\");\nmark(\"driver\");\nlet modelSpoke = false;\nconst emit = (type, text, extra) => {\n // The model's first text or tool call is where start-up ends and the\n // step's own work begins \u2014 runtime and tool lines before it are set-up.\n if (!modelSpoke && (type === \"text\" || type === \"tool\")) { modelSpoke = true; mark(\"model\"); }\n process.stdout.write(JSON.stringify({ e: \"event\", type, text, ...extra }) + \"\\n\");\n};\n// What this sandbox actually touched, read at the last moment from the\n// kernel's own books: cgroup v2 for CPU busy-time and peak memory,\n// /proc/net/dev for bytes on the wire. Every read is best-effort \u2014 gVisor\n// exposes some of these files and not others depending on version, and a\n// metric we cannot read is null, never guessed. Reservation is what is\n// billed; these exist so the reservation can be right-sized.\nfunction readActuals() {\n // fs from the module's own import \u2014 the driver is ESM, and a require()\n // here threw on every call, silently nulling every metric it guarded.\n const read = (p) => { try { return fs.readFileSync(p, \"utf8\"); } catch { return null; } };\n // Two cgroup dialects: v2 (cpu.stat, microseconds; memory.peak) on a\n // plain runtime, v1-style controllers under gVisor (cpuacct.usage,\n // NANOseconds; memory.max_usage_in_bytes) \u2014 probed on the real cluster,\n // not assumed. Whichever answers wins; both silent means null.\n const cpuStat = read(\"/sys/fs/cgroup/cpu.stat\");\n const usage = cpuStat?.match(/^usage_usec (\\d+)/m);\n const cpuacctNs = usage ? NaN : Number(read(\"/sys/fs/cgroup/cpuacct/cpuacct.usage\")?.trim());\n // Time the CPU cap held the sandbox back: v2's throttled_usec in the same\n // cpu.stat, v1's throttled_time (nanoseconds) under gVisor. Large against\n // busy time means the step wanted more cores than its class gives.\n const throttledUs = cpuStat?.match(/^throttled_usec (\\d+)/m);\n const throttledNs = throttledUs ? null : read(\"/sys/fs/cgroup/cpu/cpu.stat\")?.match(/^throttled_time (\\d+)/m);\n const peak =\n read(\"/sys/fs/cgroup/memory.peak\") ??\n read(\"/sys/fs/cgroup/memory/memory.max_usage_in_bytes\") ??\n read(\"/sys/fs/cgroup/memory/memory.usage_in_bytes\");\n let rx = 0, tx = 0, sawNet = false;\n const net = read(\"/proc/net/dev\");\n if (net) {\n for (const line of net.split(\"\\n\").slice(2)) {\n const m = line.trim().match(/^(\\S+):\\s+(\\d+)(?:\\s+\\d+){7}\\s+(\\d+)/);\n if (m && m[1] !== \"lo\") { rx += Number(m[2]); tx += Number(m[3]); sawNet = true; }\n }\n }\n return {\n busyCpuSecs: usage\n ? Number(usage[1]) / 1e6\n : Number.isFinite(cpuacctNs) && cpuacctNs > 0\n ? cpuacctNs / 1e9\n : null,\n peakMemBytes: peak ? Number(peak.trim()) || null : null,\n throttledSecs: throttledUs ? Number(throttledUs[1]) / 1e6 : throttledNs ? Number(throttledNs[1]) / 1e9 : null,\n rxBytes: sawNet ? rx : null,\n txBytes: sawNet ? tx : null,\n };\n}\n\ntry {\n // Runtime state (venvs, npm prefixes) lands in the agent user's real home\n // \u2014 writable, inside the container, gone with it.\n process.env.FOLDRUN_DATA = \"/home/agent/.foldrun\";\n const { executeStep } = await import(\"@foldrun/core/step-exec\");\n const { buildApiTools } = await import(\"@foldrun/core/api-tools\");\n const { buildA2ATools } = await import(\"@foldrun/core/a2a-tools\");\n const { buildScriptTools } = await import(\"@foldrun/core/script-tools\");\n const { buildConsultTools } = await import(\"@foldrun/core/agent-tools\");\n const { buildSearchTools, buildHistoryTools, buildDeskTools } = await import(\"@foldrun/core/context-tools\");\n const { httpChannel, buildAskTool, buildPeerTools, inboxReader } = await import(\"@foldrun/core/operator\");\n const { buildDelegateTools } = await import(\"@foldrun/core/delegate-tools\");\n const { buildTextTools } = await import(\"@foldrun/core/text-tool\");\n const { startTranslator } = await import(\"@foldrun/core/translator\");\n const { prepareRuntime } = await import(\"@foldrun/core/runtime\");\n const { materializeFileSecrets } = await import(\"@foldrun/core/secret-files\");\n const { paidWebActions } = await import(\"@foldrun/core/browser-pod\");\n mark(\"imports\");\n\n const agentDir = \"/workspace/\" + input.agentRel;\n // HOME is where a bare relative path lands when anything resolves one\n // outside cwd \u2014 and root's /root is outside the workspace, so such a read\n // was refused by confinement with a path the agent never typed. Its own\n // directory is both the truthful answer and the safe one.\n // @file secrets crossed as content; materialise them to 0600 paths inside\n // the container (a host path from the other side would not exist here).\n const env = materializeFileSecrets(agentDir, { ...process.env, HOME: agentDir }).env;\n // Caches go to the sandbox user's own home, not to HOME: the Claude CLI's\n // logs, fontconfig, Mesa and gstreamer all follow XDG_CACHE_HOME, and under\n // agents/<name>/.cache they were copied back after every step \u2014 3,855 files\n // across 179 agent folders on the box by 17 Oct 2026, read by nothing.\n env.XDG_CACHE_HOME = \"/home/agent/.cache\";\n\n // The declared runtime, built in here \u2014 pip and npm have the network, which\n // the host side may not. It lands in .foldrun/runner/.runtimes, which the\n // executors mount from a per-tenant directory (run-container.ts#RUNTIME_CACHE):\n // the first step for a given fingerprint installs, every later one finds\n // .ready and skips. With no mount it still works, just fresh every time \u2014\n // which is what this used to be unconditionally. The log says which happened.\n const runtime = input.runtime\n ? prepareRuntime(\"runner\", input.runtime)\n : { interpreters: {}, env: {}, log: [], error: null };\n for (const line of runtime.log) emit(\"info\", \"runtime: \" + line);\n if (runtime.error) emit(\"error\", \"runtime: \" + runtime.error);\n // The step's own environment gets it too, not only the script tools: an\n // agent that runs \"python3 x.py\" or a shebang script through Bash should\n // meet the packages its runtime declared, not the image's bare python.\n Object.assign(env, runtime.env);\n\n // install: what the agent finds it needs mid-step. apt goes through the\n // root start-up's helper (install-helper.ts); pip and npm land in a\n // directory of this container's own, on the paths from the first turn.\n const { buildInstallTool, INSTALL_TOOL } = await import(\"@foldrun/core/install-tool\");\n const { stepInstallEnv, INSTALL_SOCKET } = await import(\"@foldrun/core/runtime\");\n const installDir = \"/home/agent/.foldrun/step\";\n const installing = (input.allowed ?? []).includes(INSTALL_TOOL);\n if (installing) Object.assign(env, stepInstallEnv(installDir, env));\n const install = installing\n ? buildInstallTool({\n dir: installDir,\n socket: env.FOLDRUN_INSTALL_SOCKET || INSTALL_SOCKET,\n cacheRoot: \"/home/agent/.foldrun/runner/.runtimes\",\n python: env.VIRTUAL_ENV ? env.VIRTUAL_ENV + \"/bin/python\" : \"python3\",\n env,\n emit,\n })\n : { server: null };\n\n // API and script tools, rebuilt in here from their specs. Secrets were\n // substituted into API headers before the input crossed the boundary, so\n // buildApiTools gets an already-resolved environment. verify: gets the\n // container's own environment, whole: it is the boundary, assembled on\n // the host from an allowlist, and the declared secrets are in it.\n // A long result is kept in a file only when the agent can read it back.\n // (tool-output.ts canReadBack, inlined: the driver imports core by subpath.)\n const keepIn = { dir: agentDir, readable: () => (input.allowed ?? []).some((t) => t === \"Read\" || t === \"Grep\") };\n // A declared secret named like a model variable crosses as\n // FOLDRUN_DECLARED_<NAME> (runner.ts, FOL-19): the model keeps its own\n // settings, and the agent's API and script tools and verify: get the value\n // back under the name it declared. Built here, after the runtime and any\n // mid-step install have added their paths to env.\n const toolEnv = { ...env };\n for (const [k, v] of Object.entries(env)) if (k.startsWith(\"FOLDRUN_DECLARED_\")) toolEnv[k.slice(\"FOLDRUN_DECLARED_\".length)] = v;\n const api = buildApiTools(\"\", input.apis, undefined, { env: toolEnv, missing: [] }, keepIn);\n // remotes: \u2014 the four a2a tools, rebuilt from values. Each token crossed in\n // its spec (a placeholder the proxy fills for the card's origin alone), so\n // nothing here asks a vault; handles go under the workspace's state/.\n const a2a = input.a2a && Array.isArray(input.a2a.remotes) && input.a2a.remotes.length\n ? buildA2ATools(\"\", input.a2a.remotes, undefined, { env: {}, missing: [] }, {\n stateDir: \"/workspace/state/a2a/\" + input.agentRel.split(\"/\").pop(),\n runId: input.a2a.runId,\n step: input.a2a.step,\n egress: env.FOLDRUN_EGRESS || null,\n test: env.FOLDRUN_TEST_MODE === \"1\",\n keepIn,\n emit,\n })\n : { server: null, drainLog: () => [] };\n const script = buildScriptTools(\n agentDir,\n input.scripts,\n toolEnv,\n \"/library/scripts\",\n runtime.interpreters,\n null,\n keepIn.readable,\n );\n // The translator, when the provider speaks Chat Completions: a loopback\n // server for the length of this step. Its env replaces the endpoint the\n // host assembled; the provider's real URL and key stay inside it.\n const translator = input.translator ? await startTranslator(input.translator) : null;\n if (translator) {\n Object.assign(env, translator.env);\n emit(\"info\", \"translator: listening on \" + translator.baseUrl + \" for \" + (input.translator.label ?? input.translator.upstreamBase));\n }\n const consult = buildConsultTools(input.consults ?? [], env, emit);\n // The platform's own two groups, rebuilt from values like everything else.\n const search = buildSearchTools(input.search ?? []);\n const history = input.history?.length ? buildHistoryTools(input.history) : { server: null };\n const desks = input.desks?.length ? buildDeskTools(input.desks) : { server: null };\n // A person in the loop, over the proxy this step's lease already names:\n // ask_person when tools: [ask], and the run's inbox after every tool call.\n const channel = httpChannel(env.FOLDRUN_EGRESS);\n const ask = input.ask ? buildAskTool({ channel, timeoutSec: input.ask.timeoutSec, emit }) : { server: null };\n const peers = input.peers ? buildPeerTools({ channel, self: input.peers.self, siblings: input.peers.siblings, emit }) : { server: null };\n const inbox = channel ? inboxReader(channel, emit) : undefined;\n // tools: [text] \u2014 a file as text, through the extraction service behind\n // the same proxy; the lease was granted the door only for this tool.\n const textTool = input.text ? buildTextTools({ egress: env.FOLDRUN_EGRESS || null, agentDir, workspaceRoot: \"/workspace\", libraryRoot: \"/library\", emit }) : { server: null };\n // sandbox: own sub-agents: a tool each, whose job runs in its own sandbox\n // on the worker, reached over the same proxy door.\n const delegate = input.delegates?.length ? buildDelegateTools({ specs: input.delegates, channel, emit, timeoutSec: input.timeoutSec, workspaceRoot: \"/workspace\" }) : { server: null };\n\n // Keyless cloud identities (FOLDRUN_IDENTITIES): each token file kept\n // fresh through the proxy's /identity door, which mints only what this\n // step's lease was granted. Fetched before the step starts, renewed five\n // minutes before it expires (with jitter); a failure is said and retried.\n // Plain JS: this text is the driver, not TypeScript.\n const identityNames = (env.FOLDRUN_IDENTITIES || \"\").split(\",\").filter(Boolean);\n if (identityNames.length) {\n // No backslashes: this sits inside a template literal, which eats them.\n const ep = new RegExp(\"^(https?://[^/]+)/e/([A-Za-z0-9_-]{16,})/?$\").exec(env.FOLDRUN_EGRESS || \"\");\n const dir = env.FOLDRUN_IDENTITY_DIR || \"/tmp/foldrun-identity\";\n fs.mkdirSync(dir, { recursive: true, mode: 0o700 });\n const keepFresh = async (name) => {\n let wait = 30000;\n try {\n if (!ep) throw new Error(\"no egress proxy to ask\");\n const res = await fetch(ep[1] + \"/identity/\" + ep[2] + \"/\" + name, { signal: AbortSignal.timeout(15000) });\n const body = await res.json().catch(() => ({}));\n if (!res.ok || !body.token) throw new Error((body.error && body.error.message) || (\"proxy answered \" + res.status));\n const file = dir + \"/\" + name.toLowerCase() + \".jwt\";\n fs.writeFileSync(file + \".tmp\", body.token, { mode: 0o600 });\n fs.renameSync(file + \".tmp\", file);\n wait = Math.max(30000, body.expiresAt - Date.now() - 300000 + Math.floor(Math.random() * 60000) - 30000);\n } catch (err) {\n emit(\"error\", \"identity \" + name + \": \" + (err && err.message ? err.message : String(err)) + \" \u2014 trying again in 30s\");\n }\n setTimeout(() => { void keepFresh(name); }, wait).unref();\n };\n await Promise.all(identityNames.map(keepFresh));\n }\n\n mark(\"tools\");\n const outcome = await executeStep({\n agentDir,\n workspaceRoot: \"/workspace\",\n libraryRoot: \"/library\",\n configWrites: input.configWrites === true,\n prompt: input.prompt,\n model: input.model,\n effort: input.effort ?? null,\n systemPrompt: input.systemPrompt,\n allowed: input.allowed,\n mcpNames: input.mcpNames,\n mcpServers: {\n ...(api.server ? { foldrun_apis: api.server } : {}),\n ...(a2a.server ? { foldrun_a2a: a2a.server } : {}),\n ...(script.server ? { foldrun_scripts: script.server } : {}),\n ...(consult.server ? { foldrun_agents: consult.server } : {}),\n ...(search.server ? { foldrun_search: search.server } : {}),\n ...(history.server ? { foldrun_history: history.server } : {}),\n ...(desks.server ? { foldrun_desks: desks.server } : {}),\n ...(ask.server ? { foldrun_ask: ask.server } : {}),\n ...(peers.server ? { foldrun_peers: peers.server } : {}),\n ...(textTool.server ? { foldrun_text: textTool.server } : {}),\n ...(delegate.server ? { foldrun_delegate: delegate.server } : {}),\n ...(install.server ? { foldrun_install: install.server } : {}),\n ...input.mcpServers,\n },\n ...(inbox ? { inbox } : {}),\n ...(input.subagents?.length ? { subagents: input.subagents } : {}),\n env,\n timeoutSec: input.timeoutSec,\n budgetUsd: input.budgetUsd,\n budgetNote: input.budgetNote,\n price: input.price,\n verify: input.verify,\n verifyEnv: toolEnv,\n ...(typeof input.judgeModel === \"string\" ? { judgeModel: input.judgeModel } : {}),\n ...(typeof input.judgeEffort === \"string\" ? { judgeEffort: input.judgeEffort } : {}),\n output: input.output,\n schema: input.schema,\n maxTurns: input.maxTurns,\n ...(input.capture === \"metadata\" || input.capture === \"full\" ? { capture: input.capture } : {}),\n ...(input.limits && Object.keys(input.limits).length ? { limits: input.limits, toolOwners: input.toolOwners ?? {} } : {}),\n ...(input.hookNames?.length ? { hookNames: input.hookNames, hookBase: input.hookBase ?? {} } : {}),\n // Slim browsing: the platform put this step on the slim image to browse\n // through the account's pod, and named the file the web tool logs its\n // reconnects to. A lost pod stops the step; what it wrote decides what\n // the runner does next (browser-pod.ts).\n ...(env.FOLDRUN_BROWSER_POD_EVENTS ? { browserPod: { events: env.FOLDRUN_BROWSER_POD_EVENTS, methods: api.methods ?? {}, paidWeb: paidWebActions(env), ...(env.FOLDRUN_BROWSER_INIT ? { browseInit: env.FOLDRUN_BROWSER_INIT } : {}) } } : {}),\n // The container is the boundary; the SDK's own bash sandbox here would\n // only block declared network use (SSH, curl) for no added safety.\n sandboxBash: false,\n emit,\n });\n for (const line of api.drainLog()) emit(\"info\", \"api: \" + line);\n for (const line of a2a.drainLog()) emit(\"info\", \"a2a: \" + line);\n for (const line of script.drainLog()) emit(\"info\", \"script: \" + line);\n if (translator) {\n for (const line of translator.drainLog()) emit(\"info\", line.startsWith(\"translator\") ? line : \"translator: \" + line);\n await translator.close();\n }\n // A consult's spend belongs to the step that asked.\n const consultCost = consult.drainCost();\n if (consultCost > 0) outcome.costUsd = (outcome.costUsd ?? 0) + consultCost;\n if (consultCost > 0 && typeof outcome.turnsCostUsd === \"number\") outcome.turnsCostUsd += consultCost;\n process.stdout.write(JSON.stringify({ e: \"done\", ...outcome, res: readActuals() }) + \"\\n\");\n process.exit(0);\n} catch (err) {\n emit(\"error\", err instanceof Error ? err.message : String(err));\n // The failure path reports actuals too \u2014 a step that died eleven minutes\n // in still held its slice for eleven minutes, and the failed runs are\n // exactly the ones whose resource story gets read.\n let res = null;\n try { res = readActuals(); } catch { /* the reading must never mask the error */ }\n process.stdout.write(JSON.stringify({ e: \"done\", status: \"failed\", result: null, costUsd: null, res }) + \"\\n\");\n process.exit(0);\n}\n";
414
418
  /** The uv release copied into the image. Pinned: a floating uv is a floating
415
419
  * resolver, and the runtime cache is keyed on the declaration, not on it. */
416
420
  export declare const UV_VERSION = "0.11.25";
@@ -35,8 +35,10 @@ import { anyMemoryMi, quantityMi } from "./resources.js";
35
35
  import { STARTUP_PHASES } from "./startup.js";
36
36
  import { isOperatorEvent } from "./operator.js";
37
37
  import { parseBrowserPod } from "./browser-pod.js";
38
+ import { putStepState, getStepState, dropStepState } from "./step-state.js";
38
39
  import { stageRunInputs } from "./storage.js";
39
40
  import { INPUTS_DIR, stagedLine } from "./run-inputs.js";
41
+ import { textBesideInputs } from "./input-text.js";
40
42
  /** The start-up phases and what each marks — startup.ts, where every
41
43
  * surface that shows them reads them from (FOL-74). */
42
44
  export { STARTUP_PHASES };
@@ -178,29 +180,40 @@ export function handedInPath(workspaceRoot, runId, ref) {
178
180
  return null;
179
181
  return path.join(workspaceRoot, "runs", runId, "sandbox", `${ref}.json`);
180
182
  }
181
- /** Note what a sandbox was handed, on the host. */
182
- export function writeHandedIn(workspaceRoot, runId, ref, hashes) {
183
+ /** Note what a sandbox was handed, on the host. With `tenant`, where step
184
+ * state is kept in the database (step-state.ts), a row; otherwise the file. */
185
+ export async function writeHandedIn(workspaceRoot, runId, ref, hashes, tenant) {
186
+ if (await putStepState(tenant, path.basename(workspaceRoot), runId, "handed-in", ref, hashes))
187
+ return;
183
188
  const file = handedInPath(workspaceRoot, runId, ref);
184
189
  if (!file)
185
190
  return;
186
191
  fs.mkdirSync(path.dirname(file), { recursive: true });
187
192
  fs.writeFileSync(file, JSON.stringify(hashes));
188
193
  }
194
+ const isHashes = (m) => !!m && typeof m === "object" && !Array.isArray(m);
189
195
  /** What the host noted a sandbox was handed, or undefined. */
190
- export function readHandedIn(workspaceRoot, runId, ref) {
196
+ export async function readHandedIn(workspaceRoot, runId, ref, tenant) {
197
+ const row = await getStepState(tenant, path.basename(workspaceRoot), runId, "handed-in", ref);
198
+ if (isHashes(row))
199
+ return row;
191
200
  const file = handedInPath(workspaceRoot, runId, ref);
192
201
  if (!file)
193
202
  return undefined;
194
203
  try {
195
204
  const m = JSON.parse(fs.readFileSync(file, "utf8"));
196
- return m && typeof m === "object" && !Array.isArray(m) ? m : undefined;
205
+ return isHashes(m) ? m : undefined;
197
206
  }
198
207
  catch {
199
208
  return undefined;
200
209
  }
201
210
  }
202
211
  /** Forget it once the step's copy-out is done. */
203
- export function dropHandedIn(workspaceRoot, runId, ref) {
212
+ export async function dropHandedIn(workspaceRoot, runId, ref, tenant) {
213
+ // Best effort: a row left behind goes with the run (deleteRun), and failing
214
+ // the step it belongs to, after its copy-out succeeded, would be worse.
215
+ for (const kind of ["handed-in", "base"])
216
+ await dropStepState(tenant, path.basename(workspaceRoot), runId, kind, ref).catch(() => { });
204
217
  const file = handedInPath(workspaceRoot, runId, ref);
205
218
  if (file)
206
219
  fs.rmSync(file, { force: true });
@@ -218,21 +231,28 @@ export function baseRevisionPath(workspaceRoot, runId, ref) {
218
231
  const file = handedInPath(workspaceRoot, runId, ref);
219
232
  return file ? file.replace(/\.json$/, ".base.json") : null;
220
233
  }
221
- export function writeBaseRevision(workspaceRoot, runId, ref, base) {
234
+ export async function writeBaseRevision(workspaceRoot, runId, ref, base, tenant) {
235
+ if (await putStepState(tenant, path.basename(workspaceRoot), runId, "base", ref, base))
236
+ return;
222
237
  const file = baseRevisionPath(workspaceRoot, runId, ref);
223
238
  if (!file)
224
239
  return;
225
240
  fs.mkdirSync(path.dirname(file), { recursive: true });
226
241
  fs.writeFileSync(file, JSON.stringify(base));
227
242
  }
228
- export function readBaseRevision(workspaceRoot, runId, ref) {
243
+ const asBase = (m) => {
244
+ const ok = (v) => v === null || typeof v === "string";
245
+ return m && typeof m === "object" && ok(m.workspace) && ok(m.state) ? { workspace: m.workspace ?? null, state: m.state ?? null } : undefined;
246
+ };
247
+ export async function readBaseRevision(workspaceRoot, runId, ref, tenant) {
248
+ const row = asBase((await getStepState(tenant, path.basename(workspaceRoot), runId, "base", ref)));
249
+ if (row)
250
+ return row;
229
251
  const file = baseRevisionPath(workspaceRoot, runId, ref);
230
252
  if (!file)
231
253
  return undefined;
232
254
  try {
233
- const m = JSON.parse(fs.readFileSync(file, "utf8"));
234
- const ok = (v) => v === null || typeof v === "string";
235
- return m && ok(m.workspace) && ok(m.state) ? { workspace: m.workspace ?? null, state: m.state ?? null } : undefined;
255
+ return asBase(JSON.parse(fs.readFileSync(file, "utf8")));
236
256
  }
237
257
  catch {
238
258
  return undefined;
@@ -703,6 +723,7 @@ try {
703
723
  const { buildSearchTools, buildHistoryTools, buildDeskTools } = await import("@foldrun/core/context-tools");
704
724
  const { httpChannel, buildAskTool, buildPeerTools, inboxReader } = await import("@foldrun/core/operator");
705
725
  const { buildDelegateTools } = await import("@foldrun/core/delegate-tools");
726
+ const { buildTextTools } = await import("@foldrun/core/text-tool");
706
727
  const { startTranslator } = await import("@foldrun/core/translator");
707
728
  const { prepareRuntime } = await import("@foldrun/core/runtime");
708
729
  const { materializeFileSecrets } = await import("@foldrun/core/secret-files");
@@ -816,6 +837,9 @@ try {
816
837
  const ask = input.ask ? buildAskTool({ channel, timeoutSec: input.ask.timeoutSec, emit }) : { server: null };
817
838
  const peers = input.peers ? buildPeerTools({ channel, self: input.peers.self, siblings: input.peers.siblings, emit }) : { server: null };
818
839
  const inbox = channel ? inboxReader(channel, emit) : undefined;
840
+ // tools: [text] — a file as text, through the extraction service behind
841
+ // the same proxy; the lease was granted the door only for this tool.
842
+ const textTool = input.text ? buildTextTools({ egress: env.FOLDRUN_EGRESS || null, agentDir, workspaceRoot: "/workspace", libraryRoot: "/library", emit }) : { server: null };
819
843
  // sandbox: own sub-agents: a tool each, whose job runs in its own sandbox
820
844
  // on the worker, reached over the same proxy door.
821
845
  const delegate = input.delegates?.length ? buildDelegateTools({ specs: input.delegates, channel, emit, timeoutSec: input.timeoutSec, workspaceRoot: "/workspace" }) : { server: null };
@@ -872,6 +896,7 @@ try {
872
896
  ...(desks.server ? { foldrun_desks: desks.server } : {}),
873
897
  ...(ask.server ? { foldrun_ask: ask.server } : {}),
874
898
  ...(peers.server ? { foldrun_peers: peers.server } : {}),
899
+ ...(textTool.server ? { foldrun_text: textTool.server } : {}),
875
900
  ...(delegate.server ? { foldrun_delegate: delegate.server } : {}),
876
901
  ...(install.server ? { foldrun_install: install.server } : {}),
877
902
  ...input.mcpServers,
@@ -1849,8 +1874,22 @@ export async function runStepInContainer(args) {
1849
1874
  if (args.inputs?.files.length) {
1850
1875
  if (!args.tenant)
1851
1876
  throw new Error("a step with inputs needs its account");
1852
- const staged = await stageRunInputs(args.tenant, path.basename(args.workspaceRoot), args.inputs.runId, args.inputs.files, path.join(wsIn, args.input.agentRel, INPUTS_DIR));
1877
+ const inputsDir = path.join(wsIn, args.input.agentRel, INPUTS_DIR);
1878
+ const staged = await stageRunInputs(args.tenant, path.basename(args.workspaceRoot), args.inputs.runId, args.inputs.files, inputsDir);
1853
1879
  args.emit("info", stagedLine(staged.files, staged.bytes));
1880
+ // `<file>.txt` beside the media ones, when the platform extracts text:
1881
+ // best effort, bounded, never a reason the step does not start.
1882
+ if (platform.extractText) {
1883
+ await textBesideInputs({
1884
+ tenant: args.tenant,
1885
+ workspace: path.basename(args.workspaceRoot),
1886
+ runId: args.inputs.runId,
1887
+ files: args.inputs.files,
1888
+ dir: inputsDir,
1889
+ extract: (ask) => platform.extractText(ask),
1890
+ emit: (line) => args.emit("info", line),
1891
+ });
1892
+ }
1854
1893
  }
1855
1894
  const libIn = path.join(staging, "library");
1856
1895
  if (args.galleryRoot && fs.existsSync(args.galleryRoot))
@@ -13,6 +13,11 @@ export declare function inputsProblem(paths: unknown): string | null;
13
13
  /** Null when the resolved files fit foldrun's limits; otherwise why not. */
14
14
  export declare function inputsSizeProblem(files: RunInputFile[]): string | null;
15
15
  /** What the step is told, after its instruction. */
16
- export declare function inputsNote(files: RunInputFile[]): string;
16
+ /** `textBeside`: the paths whose text the platform will try to put at
17
+ * `<path>.txt` at staging (input-text.ts textCandidates) — marked, and the
18
+ * note says how to use them. Absent or empty: nothing is said of .txt. */
19
+ export declare function inputsNote(files: RunInputFile[], opts?: {
20
+ textBeside?: string[];
21
+ }): string;
17
22
  /** The trail's line once they are staged. */
18
23
  export declare function stagedLine(files: number, bytes: number): string;
@@ -41,9 +41,17 @@ export function inputsSizeProblem(files) {
41
41
  }
42
42
  const human = (n) => (n >= 1048576 ? `${(n / 1048576).toFixed(1)} MiB` : n >= 1024 ? `${Math.round(n / 1024)} KiB` : `${n} B`);
43
43
  /** What the step is told, after its instruction. */
44
- export function inputsNote(files) {
45
- const lines = files.map((f) => `- ${INPUTS_DIR}/${f.path} (${f.mime}, ${human(f.size)})`);
44
+ /** `textBeside`: the paths whose text the platform will try to put at
45
+ * `<path>.txt` at staging (input-text.ts textCandidates) — marked, and the
46
+ * note says how to use them. Absent or empty: nothing is said of .txt. */
47
+ export function inputsNote(files, opts) {
48
+ const beside = new Set(opts?.textBeside ?? []);
49
+ 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` : ""}`);
50
+ const textNote = beside.size
51
+ ? `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). `
52
+ : "";
46
53
  return (`<inputs>\nThis run was handed ${files.length} file${files.length === 1 ? "" : "s"}, in ${INPUTS_DIR}/ inside your working directory:\n${lines.join("\n")}\n` +
54
+ textNote +
47
55
  "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. " +
48
56
  `The files stay available to scripts. Anything you write in ${INPUTS_DIR}/ is not kept — put results in outputs/.\n</inputs>`);
49
57
  }
@@ -0,0 +1,3 @@
1
+ import type { RefusedOutput } from "./store.ts";
2
+ /** One refusal as a sentence a person reads on the run page. */
3
+ export declare function refusalText(r: RefusedOutput): string;
@@ -0,0 +1,16 @@
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
+ const mib = (n) => `${(n / 1048576).toFixed(n >= 10 * 1048576 ? 0 : 1)} MiB`;
4
+ /** One refusal as a sentence a person reads on the run page. */
5
+ export function refusalText(r) {
6
+ switch (r.reason) {
7
+ case "file-cap":
8
+ return `${r.agent}/${r.path} (${mib(r.bytes)}) was not kept: a file may be at most ${mib(r.limit ?? 0)}`;
9
+ case "run-cap":
10
+ return `${r.agent}/${r.path} (${mib(r.bytes)}) was not kept: this run's outputs may total at most ${mib(r.limit ?? 0)}`;
11
+ case "count":
12
+ return `${r.agent}/${r.path} was not kept: a run keeps at most ${r.limit ?? 50_000} files per agent`;
13
+ default:
14
+ 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)`;
15
+ }
16
+ }
@@ -0,0 +1,134 @@
1
+ import { type BlobStore } from "./blob-store.ts";
2
+ import { type BlobPins, type PinHolder } from "./blob-pins.ts";
3
+ import { type ManifestId } from "./manifest.ts";
4
+ import { refusalText } from "./run-output-refusal.ts";
5
+ export { refusalText };
6
+ import { type RefusedOutput, type RunOutputFile } from "./store.ts";
7
+ /** What the commit writes down: which manifest is this agent's outputs of this run. */
8
+ export interface RunOutputRecord {
9
+ tenant: string;
10
+ workspace: string;
11
+ runId: string;
12
+ agent: string;
13
+ manifest: ManifestId;
14
+ files: number;
15
+ bytes: number;
16
+ at: string;
17
+ }
18
+ export interface RunOutputStore {
19
+ readonly kind: "local" | "database";
20
+ /** Upsert by (tenant, workspace, run, agent). Returns the record it replaced. */
21
+ put(rec: RunOutputRecord): Promise<RunOutputRecord | null>;
22
+ list(tenant: string, workspace: string, runId: string): Promise<RunOutputRecord[]>;
23
+ /** Remove records and return them (the caller releases their pins):
24
+ * one run, one workspace, or (no workspace) the whole account. */
25
+ drop(scope: {
26
+ tenant: string;
27
+ workspace?: string;
28
+ runId?: string;
29
+ }): Promise<RunOutputRecord[]>;
30
+ /** A workspace was renamed: its records follow. What `to` held is replaced. */
31
+ move(tenant: string, from: string, to: string): Promise<void>;
32
+ /** The bytes this workspace's runs keep in the store, for the usage statement
33
+ * (synchronous like the rest of that code). Unset: counted as 0. */
34
+ bytes?(tenant: string, workspace: string): number;
35
+ }
36
+ /** Files under <data>/.run-outputs/<tenant>/<workspace>/<run>/<agent>.json.
37
+ * For an install that has a blob store but no database (and for the tests):
38
+ * the database one is platform's run-outputs-pg.ts. */
39
+ export declare function localRunOutputStore(root?: string): RunOutputStore;
40
+ export interface RunOutputsBackend {
41
+ blobs: BlobStore;
42
+ /** Unset: no sweeper to agree with (noPins). */
43
+ pins?: BlobPins;
44
+ store: RunOutputStore;
45
+ /** The `runs.outputs_store` setting, read on every call. */
46
+ enabled: () => boolean;
47
+ /** Per file (`runs.output_file_mb`) and per run (`runs.output_run_mb`), in bytes. */
48
+ fileMaxBytes: () => number;
49
+ runMaxBytes: () => number;
50
+ }
51
+ /** Where run outputs are published, or null (every run archives to the volume). */
52
+ export declare function setRunOutputsBackend(b: RunOutputsBackend | null): void;
53
+ export declare const runOutputsBackend: () => RunOutputsBackend | null;
54
+ /** Publishing is on: a backend is registered and the operator has said so. */
55
+ export declare const runOutputsOn: () => boolean;
56
+ /** The permanent pin on one record's manifest. The manifest id is part of the
57
+ * holder, so a re-archive (a resumed run) can pin the new manifest before it
58
+ * releases the old one. */
59
+ export declare function outputsHolder(runId: string, agent: string, manifest: ManifestId): PinHolder;
60
+ export interface PublishedOutputs {
61
+ record: RunOutputRecord | null;
62
+ refused: RefusedOutput[];
63
+ }
64
+ /**
65
+ * Publish one agent's outputs of one run. Returns the record (null: nothing
66
+ * was kept — no files, or every one refused) and what was refused. Throws when
67
+ * the store or the database fails; the caller decides what that means
68
+ * (archiveRunOutputs: the temporary volume fallback). Idempotent: the same
69
+ * files again are the same manifest and the same record.
70
+ */
71
+ export declare function publishRunOutputs(b: RunOutputsBackend, tenant: string, workspace: string, runId: string, agent: string, dir: string): Promise<PublishedOutputs>;
72
+ /** The caller's note on the run: what was refused, on the record, in the
73
+ * step's trail. Mutates `run` (the caller saves it). */
74
+ export declare function noteRefused(run: {
75
+ outputsRefused?: RefusedOutput[];
76
+ outputsRefusedCount?: number;
77
+ steps: {
78
+ status: string;
79
+ events: {
80
+ t: string;
81
+ type: string;
82
+ text: string;
83
+ }[];
84
+ }[];
85
+ }, refused: readonly RefusedOutput[]): void;
86
+ /**
87
+ * runner.ts archive() for one agent: publish when it is on, else (or when it
88
+ * fails) say "volume" and the caller copies the folder as before.
89
+ */
90
+ export declare function archiveRunOutputs(tenant: string, workspace: string, runId: string, agent: string, dir: string): Promise<{
91
+ where: "store";
92
+ refused: RefusedOutput[];
93
+ } | {
94
+ where: "volume";
95
+ }>;
96
+ /** What a run archived, from the store and from the volume (an agent the store
97
+ * has wins). Sorted by agent, then path. */
98
+ export declare function listRunOutputs(tenant: string, workspace: string, runId: string): Promise<RunOutputFile[]>;
99
+ export interface OpenedOutput {
100
+ size: number;
101
+ /** The bytes, or one inclusive range of them. */
102
+ read(range?: {
103
+ start: number;
104
+ end: number;
105
+ }): ReadableStream<Uint8Array>;
106
+ }
107
+ /** One archived output, or null when the name escapes the archive or names
108
+ * nothing — the API serves only what this returns. */
109
+ export declare function openRunOutput(tenant: string, workspace: string, runId: string, agent: string, rel: string): Promise<OpenedOutput | null>;
110
+ /** The whole file as bytes (a small one: a test, a preview). */
111
+ export declare function readRunOutput(tenant: string, workspace: string, runId: string, agent: string, rel: string): Promise<Buffer | null>;
112
+ /** A run is deleted: its records and their pins go. Throws when the store
113
+ * cannot be reached (deleteRun's caller retries in the background). */
114
+ export declare function dropRunOutputs(tenant: string, workspace: string, runId: string): Promise<void>;
115
+ /** A workspace is deleted: every run's records of it. */
116
+ export declare function dropWorkspaceOutputs(tenant: string, workspace: string): Promise<void>;
117
+ /** An account is deleted. Its pins are released by dropTenantRevisions (all pins
118
+ * of the account); the records go here. */
119
+ export declare function dropTenantOutputs(tenant: string): Promise<void>;
120
+ /** A workspace was renamed: the records follow (the pins are not keyed by
121
+ * it). What the new name held belonged to a workspace that no longer
122
+ * exists: those records go first, and their pins with them (the database
123
+ * store does both in its move too; the file store did not — review, 12 Nov
124
+ * 2026). */
125
+ export declare function moveWorkspaceOutputs(tenant: string, from: string, to: string): Promise<void>;
126
+ /** What a workspace's runs hold in the store, in bytes: counted with the run
127
+ * history on the usage statement, where the volume's `runs/` folder was. A
128
+ * store that cannot say, or cannot be reached, counts 0 (a statement must not fail). */
129
+ export declare function runOutputBytes(tenant: string, workspace: string): number;
130
+ /** Wait for the retries a sync caller started (tests, process end). */
131
+ export declare function settleRunOutputs(): Promise<void>;
132
+ /** deleteRun cannot wait: do it now, and on a failure try again 1, 2, 4, 8 s
133
+ * later, then say so (`run_outputs.drop_failed`; the blobs stay until a human looks). */
134
+ export declare function runDeleted(tenant: string, workspace: string, runId: string): void;