@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
@@ -26,6 +26,7 @@ import { parseJudge } from "./judge-verdict.js";
26
26
  import { validateSchema, describeSchemaErrors, looksLikeSchema } from "./json-schema.js";
27
27
  import { EGRESS_ENV, MODEL_KEY_NAME, addGrant, grantModelKey, hostOf, placeholderNames, proxyModelEnv, unsubstitute } from "./egress.js";
28
28
  import { SUPPLY_TITLES, supplyProviderBlock } from "./model-supply.js";
29
+ import { archiveRunOutputs, noteRefused } from "./run-outputs.js";
29
30
  import { explainRefusal, isRefusalStatus, refusalFromLine, supplyNote } from "./refusal.js";
30
31
  import { platform } from "./platform.js";
31
32
  import { healthKey } from "./secret-health.js";
@@ -39,6 +40,7 @@ const isolatedRun = () => {
39
40
  import { gatherConsults, buildConsultTools } from "./agent-tools.js";
40
41
  import { DELEGATE_TOOL, gatherSubagents, ownSandbox, subagentPrompt, subagentTools, SUBAGENT_NO_REMOTES } from "./subagents.js";
41
42
  import { DELEGATE_SERVER, buildDelegateTools, delegatePromptLine, delegateToolNames, localDelegateChannel, readCopyBack } from "./delegate-tools.js";
43
+ import { TEXT_SERVER, TEXT_TOOL, buildTextTools, textPromptLine } from "./text-tool.js";
42
44
  import { ASK_TOOL, PEER_TOOLS, applyOperatorEvent, askPromptLine, askTimeoutSec, buildAskTool, buildPeerTools, inboxReader, localPeerBus, peersPromptLine } from "./operator.js";
43
45
  import { sendPlainNotification } from "./notify.js";
44
46
  import { TOOL_MAP, BUILTIN_TOOLS, ownToolNames, toolRefs, legacyUseNames, legacyUseError, retiredToolNames, retiredToolError } from "./tool-names.js";
@@ -65,6 +67,7 @@ import { fingerprint, mergeRuntimes, parseRuntime, prepareRuntime, stepInstallEn
65
67
  import { buildInstallTool, INSTALL_TOOL } from "./install-tool.js";
66
68
  import { dataRoot } from "./paths.js";
67
69
  import { materializeFiles, harvestFiles, storageBaseline } from "./storage.js";
70
+ import { readStorageBaseline, writeStorageBaseline } from "./step-state.js";
68
71
  import { chooseExecutor, ensureImage } from "./container.js";
69
72
  import { stampBundle } from "./okf.js";
70
73
  import { readBrowseSettings, readSearchSettings, resolveSearch, searchSettingsEnv, webConfig, browseSessionProblems } from "./providers.js";
@@ -74,6 +77,7 @@ import { resolveRegion, deriveLocale, localeProse, regionName } from "./locale.j
74
77
  import { trimChars } from "./paths.js";
75
78
  import { earlierTurns, conversationBlock } from "./conversation.js";
76
79
  import { inputsNote } from "./run-inputs.js";
80
+ import { textCandidates } from "./input-text.js";
77
81
  import { resolveClock, localDate } from "./clock.js";
78
82
  export { localDate } from "./clock.js";
79
83
  // An MCP tool definition becomes an SDK server config. ${SECRET} placeholders
@@ -1593,6 +1597,7 @@ grantsOnly = false) {
1593
1597
  let wantDesks = false;
1594
1598
  let wantAsk = false;
1595
1599
  let wantPeers = false;
1600
+ let wantText = false;
1596
1601
  for (const ref of toolRefs(front)) {
1597
1602
  const toolName = ref.name;
1598
1603
  if (ref.mode === "ask") {
@@ -1627,7 +1632,7 @@ grantsOnly = false) {
1627
1632
  if (available[toolName])
1628
1633
  shadowed.push(toolName);
1629
1634
  }
1630
- else if (toolName === "search" || toolName === "history" || toolName === "desks" || toolName === "ask" || toolName === "peers") {
1635
+ else if (toolName === "search" || toolName === "history" || toolName === "desks" || toolName === "ask" || toolName === "peers" || toolName === "text") {
1631
1636
  // The platform's own groups, served in-process — built below, once
1632
1637
  // the roots and the records are known.
1633
1638
  if (toolName === "search")
@@ -1638,6 +1643,8 @@ grantsOnly = false) {
1638
1643
  wantAsk = true;
1639
1644
  else if (toolName === "peers")
1640
1645
  wantPeers = true;
1646
+ else if (toolName === "text")
1647
+ wantText = true;
1641
1648
  else
1642
1649
  wantDesks = true;
1643
1650
  if (available[toolName])
@@ -1710,6 +1717,14 @@ grantsOnly = false) {
1710
1717
  const peers = wantPeers;
1711
1718
  if (peers)
1712
1719
  allowed.push(...PEER_TOOLS);
1720
+ // tools: [text] — extract_text, through the extraction service behind the
1721
+ // step's egress proxy. The server is the step's (it needs the step's roots
1722
+ // and, in a pod, the lease address); here the grant and the prompt's line.
1723
+ const textTool = wantText;
1724
+ if (textTool) {
1725
+ allowed.push(TEXT_TOOL);
1726
+ parts.add("text", `# Files as text\n\n${textPromptLine()}`);
1727
+ }
1713
1728
  if (searchTools.promptLines.length || historyTools.promptLines.length || deskTools.promptLines.length) {
1714
1729
  parts.add("finding", `# Finding things\n\n${[...searchTools.promptLines, ...historyTools.promptLines, ...deskTools.promptLines].join("\n")}`);
1715
1730
  }
@@ -1731,6 +1746,8 @@ grantsOnly = false) {
1731
1746
  const denied = refNames(front.disallowedTools);
1732
1747
  if (denied.includes("install"))
1733
1748
  denied.push(INSTALL_TOOL);
1749
+ if (denied.includes("text"))
1750
+ denied.push(TEXT_TOOL);
1734
1751
  const finalAllowed = allowed.filter((t) => !denied.includes(t));
1735
1752
  readsFiles = canReadBack(finalAllowed);
1736
1753
  const prompt = parts.assemble();
@@ -1779,6 +1796,7 @@ grantsOnly = false) {
1779
1796
  deskTools,
1780
1797
  ask,
1781
1798
  peers,
1799
+ textTool,
1782
1800
  // `spec` is the MERGED declaration — the agent's own block or its
1783
1801
  // workspace's, plus every granted tool's. The isolated path builds its
1784
1802
  // runtime from this; passing the agent's frontmatter alone silently drops
@@ -2187,6 +2205,16 @@ conversation) {
2187
2205
  answer = answer
2188
2206
  .split("\n")
2189
2207
  .filter((line) => {
2208
+ // `write: <path> => <text>` / `bytes: <path> => <n>`: the step leaves a
2209
+ // file in its outputs/ (n bytes of "x"), so what archive() does with a
2210
+ // run's outputs is testable end to end.
2211
+ const w = /^(write|bytes): (\S+) => (.*)$/.exec(line);
2212
+ if (w) {
2213
+ const target = path.join(agentDir, "outputs", w[2]);
2214
+ fs.mkdirSync(path.dirname(target), { recursive: true });
2215
+ fs.writeFileSync(target, w[1] === "write" ? w[3] : "x".repeat(Number(w[3])));
2216
+ return false;
2217
+ }
2190
2218
  const m = /^call: (\S+) (.*?) => (.*)$/.exec(line);
2191
2219
  if (!m)
2192
2220
  return true;
@@ -2239,7 +2267,7 @@ conversation) {
2239
2267
  // step: the generic HTTP tool still works without the typed ones.
2240
2268
  for (const w of await prefetchOpenApi(tenant, openApiSources(agentDir, tenant)))
2241
2269
  push("error", `openapi: ${w}`);
2242
- const { front, clockEnv, clock, systemPrompt, promptLayers, allowed, disabled, apiTools, scriptTools, secretEnv, secretScopes, missingSecrets, missingTools, runtime, unknownTools, shadowed, legacyUse, retiredTools, mcpServers, mcpNames, apiSpecs, scriptSpecs, brokenTools, size: agentSize, remotes, remoteOnlySecrets, remoteSecretEnv, providerEnv, providerLabel, providerSecrets, providerWarnings, formatWarning, searchChoice, fetchChoice, actionChoices, web, language, region, fallbackEnv, apiWarnings, searchRoots, historyDigest, deskDigest, searchTools, historyTools, deskTools, ask, peers, translator, fallbackTranslator, outward, supply, } = agentContext(agentDir, tenant, tags, { runId, agent: step.agent }, flowTimezone);
2270
+ const { front, clockEnv, clock, systemPrompt, promptLayers, allowed, disabled, apiTools, scriptTools, secretEnv, secretScopes, missingSecrets, missingTools, runtime, unknownTools, shadowed, legacyUse, retiredTools, mcpServers, mcpNames, apiSpecs, scriptSpecs, brokenTools, size: agentSize, remotes, remoteOnlySecrets, remoteSecretEnv, providerEnv, providerLabel, providerSecrets, providerWarnings, formatWarning, searchChoice, fetchChoice, actionChoices, web, language, region, fallbackEnv, apiWarnings, searchRoots, historyDigest, deskDigest, searchTools, historyTools, deskTools, ask, peers, textTool, translator, fallbackTranslator, outward, supply, } = agentContext(agentDir, tenant, tags, { runId, agent: step.agent }, flowTimezone);
2243
2271
  disposeRuntime = runtime.dispose;
2244
2272
  canActOutward = outward;
2245
2273
  // Sent again on every turn; with turns and the tools' result sizes, what
@@ -2636,6 +2664,7 @@ conversation) {
2636
2664
  ...(consults.length ? ["foldrun_agents"] : []),
2637
2665
  ...(ask ? ["foldrun_ask"] : []),
2638
2666
  ...(peers ? ["foldrun_peers"] : []),
2667
+ ...(textTool ? [TEXT_SERVER] : []),
2639
2668
  ];
2640
2669
  if (peers) {
2641
2670
  // The colleagues' contract, in the prompt the step reads: who runs
@@ -2927,6 +2956,8 @@ conversation) {
2927
2956
  ...(peers && stepIndex !== undefined && stepIndex >= 0 ? { agent: step.agent, peers: siblings } : {}),
2928
2957
  // sandbox: own sub-agents: the only names the delegate door takes.
2929
2958
  ...(delegates.length ? { delegates: delegates.map((d) => d.name) } : {}),
2959
+ // tools: [text] — the only leases the proxy serves the /text door on.
2960
+ ...(textTool ? { text: true } : {}),
2930
2961
  });
2931
2962
  // foldrun's models need the proxy: it holds the platform's key and
2932
2963
  // meters each call. No lease (no FOLDRUN_EGRESS_URL) — refused, and
@@ -3183,7 +3214,7 @@ conversation) {
3183
3214
  // Its file tools inside the sandbox get the same allowance (FOL-96).
3184
3215
  configWrites: step.approve === true && Boolean(step.approvedAt),
3185
3216
  // A snapshot step is told where its folder is, and what comes back.
3186
- prompt: `${prompt}${snapshotId ? `\n\n${SNAPSHOT_NOTE}` : ""}${stepInputs ? `\n\n${inputsNote(stepInputs)}` : ""}`,
3217
+ prompt: `${prompt}${snapshotId ? `\n\n${SNAPSHOT_NOTE}` : ""}${stepInputs ? `\n\n${inputsNote(stepInputs, platform.extractText ? { textBeside: textCandidates(stepInputs).map((f) => f.path) } : undefined)}` : ""}`,
3187
3218
  model,
3188
3219
  effort,
3189
3220
  systemPrompt,
@@ -3200,6 +3231,7 @@ conversation) {
3200
3231
  runtime: runtime.spec,
3201
3232
  consults,
3202
3233
  ...(peers ? { peers: { self: step.agent, siblings } } : {}),
3234
+ ...(textTool ? { text: true } : {}),
3203
3235
  ...(subagents.length ? { subagents } : {}),
3204
3236
  ...(delegates.length ? { delegates } : {}),
3205
3237
  timeoutSec: step.timeout,
@@ -3654,6 +3686,11 @@ conversation) {
3654
3686
  const peerChannel = peerBus && stepIndex !== undefined && stepIndex >= 0 ? peerBus.channelFor({ agent: step.agent, step: stepIndex }, siblings) : null;
3655
3687
  const peerTools = peers ? buildPeerTools({ channel: peerChannel, self: step.agent, siblings, emit: push }) : null;
3656
3688
  const localInbox = peerChannel ? inboxReader(peerChannel, push) : undefined;
3689
+ // tools: [text] — no proxy in this process, so no extraction service:
3690
+ // the tool is there and says so, rather than going missing.
3691
+ const textTools = textTool
3692
+ ? buildTextTools({ egress: null, agentDir, workspaceRoot, libraryRoot: libraryDir(tenant), emit: (type, t) => push(type, t) })
3693
+ : null;
3657
3694
  // sandbox: own sub-agents, here: no proxy between the step and this
3658
3695
  // process, so the job is handed to the drive loop directly.
3659
3696
  const delegateTools = delegates.length && delegateJob
@@ -3720,6 +3757,7 @@ conversation) {
3720
3757
  ...(deskTools.server ? { foldrun_desks: deskTools.server } : {}),
3721
3758
  ...(askTools ? { foldrun_ask: askTools.server } : {}),
3722
3759
  ...(peerTools ? { foldrun_peers: peerTools.server } : {}),
3760
+ ...(textTools ? { [TEXT_SERVER]: textTools.server } : {}),
3723
3761
  ...(delegateTools?.server ? { foldrun_delegate: delegateTools.server } : {}),
3724
3762
  ...(a2aTools?.server ? { foldrun_a2a: a2aTools.server } : {}),
3725
3763
  ...(installTools ? { foldrun_install: installTools.server } : {}),
@@ -4708,12 +4746,21 @@ function driveRunInner(tenant, workspace, run, modelOverride, tags, opts) {
4708
4746
  run.memoryWrites = [...(run.memoryWrites ?? []), ...written];
4709
4747
  };
4710
4748
  // Archive what a run produced, so history survives the next run's reset.
4711
- const archive = () => {
4749
+ // Where a backend is registered and `runs.outputs_store` is on, each agent's
4750
+ // outputs are published to the blob store (run-outputs.ts) and what could
4751
+ // not be kept is written on the run; otherwise (a laptop, the setting off, or
4752
+ // — TEMPORARILY, until the EFS cutover — a publish that failed) the folder is
4753
+ // copied to the volume as before.
4754
+ const archive = async () => {
4712
4755
  for (const agent of new Set(run.steps.map((s) => s.agent))) {
4713
4756
  const from = path.join(runRoot, "agents", agent, "outputs");
4714
4757
  if (!fs.existsSync(from) || fs.readdirSync(from).length === 0)
4715
4758
  continue;
4716
- copyTreeBytes(from, path.join(runRoot, "runs", run.id, "outputs", agent));
4759
+ const done = await archiveRunOutputs(tenant, workspace, run.id, agent, from);
4760
+ if (done.where === "store")
4761
+ noteRefused(run, done.refused);
4762
+ else
4763
+ copyTreeBytes(from, path.join(runRoot, "runs", run.id, "outputs", agent));
4717
4764
  }
4718
4765
  };
4719
4766
  // A parked run is paused, not finished — the completion bookkeeping in
@@ -4838,10 +4885,12 @@ function driveRunInner(tenant, workspace, run, modelOverride, tags, opts) {
4838
4885
  // posted it a second time. So a run that has been here before (its
4839
4886
  // baseline is on disk) stores what it changed first; files it did not
4840
4887
  // touch still come fresh from the store.
4841
- const baselineFile = path.join(runRoot, "runs", run.id, "storage-baseline.json");
4842
- if (fs.existsSync(baselineFile)) {
4888
+ // A baseline that cannot be READ is not "never here": materializing
4889
+ // then would be the 6 Oct overwrite again. The error stands and the
4890
+ // step fails as any store fault does (review, 12 Nov 2026).
4891
+ const changedFrom = await readStorageBaseline(runRoot, tenant, workspace, run.id);
4892
+ if (changedFrom) {
4843
4893
  try {
4844
- const changedFrom = JSON.parse(fs.readFileSync(baselineFile, "utf8"));
4845
4894
  const { saved } = await harvestFiles(tenant, workspace, `run:${run.id}`, { changedFrom });
4846
4895
  if (saved.length) {
4847
4896
  run.steps[0]?.events.push({
@@ -4864,8 +4913,7 @@ function driveRunInner(tenant, workspace, run, modelOverride, tags, opts) {
4864
4913
  text: `files: ${brought.length} brought into the workspace`,
4865
4914
  });
4866
4915
  }
4867
- fs.mkdirSync(path.dirname(baselineFile), { recursive: true });
4868
- fs.writeFileSync(baselineFile, JSON.stringify(storageBaseline(tenant, workspace)));
4916
+ await writeStorageBaseline(runRoot, tenant, workspace, run.id, storageBaseline(tenant, workspace));
4869
4917
  }
4870
4918
  catch (err) {
4871
4919
  // A file store that is down must not take the run with it: most flows
@@ -6151,7 +6199,7 @@ function driveRunInner(tenant, workspace, run, modelOverride, tags, opts) {
6151
6199
  // failure too.
6152
6200
  try {
6153
6201
  stampMemories();
6154
- archive();
6202
+ await archive();
6155
6203
  }
6156
6204
  catch {
6157
6205
  // never let bookkeeping fail a run that already finished
@@ -486,7 +486,7 @@ model: default # fast | default | max
486
486
  effort: low # how hard to think about it
487
487
  size: large # small | large | heavy — the sandbox it rents
488
488
  resources: { memory: 4Gi } # optional: cpu, memory, disk in numbers, over the size class
489
- tools: [web, read, ask, peers, my-folder-tool] # built-ins and your own tools/, one list; \`ask\` lets it ask you mid-step, \`peers\` lets it message the steps running beside it
489
+ tools: [web, read, ask, peers, text, my-folder-tool] # built-ins and your own tools/, one list; \`ask\` lets it ask you mid-step, \`peers\` lets it message the steps running beside it, \`text\` reads images, PDFs, office files and recordings as text
490
490
  disallowedTools: [Bash] # subtract from what it would otherwise have
491
491
  skills: [house-style] # from skills/
492
492
  hooks: [no-force-push] # from hooks/ or the library: code at every tool call
@@ -0,0 +1,10 @@
1
+ export type StepStateKind = "handed-in" | "base" | "storage";
2
+ /** Stored as a row? False: the caller writes the file. */
3
+ export declare function putStepState(tenant: string | undefined, workspace: string, runId: string, kind: StepStateKind, ref: string, data: unknown): Promise<boolean>;
4
+ /** The row, or undefined (look at the file). */
5
+ export declare function getStepState(tenant: string | undefined, workspace: string, runId: string, kind: StepStateKind, ref: string): Promise<unknown | undefined>;
6
+ /** Forget rows (a step's copy-out is done). Files are the caller's. */
7
+ export declare function dropStepState(tenant: string | undefined, workspace: string, runId: string, kind: StepStateKind, ref: string | null): Promise<void>;
8
+ /** The storage index this run first materialized, or undefined: it has not been here. */
9
+ export declare function readStorageBaseline(workspaceRoot: string, tenant: string | undefined, workspace: string, runId: string): Promise<Record<string, string> | undefined>;
10
+ export declare function writeStorageBaseline(workspaceRoot: string, tenant: string | undefined, workspace: string, runId: string, hashes: Record<string, string>): Promise<void>;
@@ -0,0 +1,93 @@
1
+ // What a step was handed and started from, kept beside its run (FOL-126 phase 7).
2
+ //
3
+ // Three small records, all platform-owned and never staged into a sandbox:
4
+ // handed-in the hash of every file a driver put in the pod (copy-back diff)
5
+ // base the revisions the stage-in started from (RunBase)
6
+ // storage the storage/ index as it was when the run first materialized it
7
+ // (its existence is "this run has been here before" — a worker
8
+ // that picks a run up again stores what it changed first)
9
+ //
10
+ // With a database and `runs.step_state_store` on they are rows (records port,
11
+ // table run_step_state), deleted with the run, the workspace and the account.
12
+ // Otherwise they are files under runs/<id>/, as before. Reads look at rows
13
+ // first whatever the switch says, then at the file, so turning it off — or on —
14
+ // mid-run loses nothing; a write with the switch off removes the key's row
15
+ // first, so the file written is the one read. A row that cannot be read is an error, not "none":
16
+ // "none" means "start again from scratch", and that is not what a database
17
+ // that is down means.
18
+ import fs from "node:fs";
19
+ import path from "node:path";
20
+ import { records } from "./records.js";
21
+ const SAFE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,120}$/;
22
+ const okIds = (runId, ref) => SAFE.test(runId) && (ref === "" || SAFE.test(ref));
23
+ /** The rows' port for this run, or null: it is files (no database, the workspace
24
+ * not moved yet, no tenant known). */
25
+ function port(tenant, workspace) {
26
+ if (!tenant)
27
+ return null;
28
+ const p = records(tenant, workspace);
29
+ return p?.async?.stepGet ? p : null;
30
+ }
31
+ /** Stored as a row? False: the caller writes the file. */
32
+ export async function putStepState(tenant, workspace, runId, kind, ref, data) {
33
+ const p = port(tenant, workspace);
34
+ if (!p || !tenant || !p.async?.stepPut || !okIds(runId, ref))
35
+ return false;
36
+ if (!safeOn(p)) {
37
+ // Switched off with a row already there: reads look at rows first, so
38
+ // the old row would shadow the file the caller is about to write (a
39
+ // resumed run's storage baseline is rewritten each time — review, 12 Nov
40
+ // 2026). The row goes; a failure here is an error, not a quiet stale read.
41
+ await p.async.stepDrop?.(tenant, workspace, runId, kind, ref);
42
+ return false;
43
+ }
44
+ await p.async.stepPut(tenant, workspace, runId, kind, ref, data);
45
+ return true;
46
+ }
47
+ const safeOn = (p) => {
48
+ try {
49
+ return p.stepStateOn?.() === true;
50
+ }
51
+ catch {
52
+ return false;
53
+ }
54
+ };
55
+ /** The row, or undefined (look at the file). */
56
+ export async function getStepState(tenant, workspace, runId, kind, ref) {
57
+ const p = port(tenant, workspace);
58
+ if (!p || !tenant || !p.async?.stepGet || !okIds(runId, ref))
59
+ return undefined;
60
+ return p.async.stepGet(tenant, workspace, runId, kind, ref);
61
+ }
62
+ /** Forget rows (a step's copy-out is done). Files are the caller's. */
63
+ export async function dropStepState(tenant, workspace, runId, kind, ref) {
64
+ const p = port(tenant, workspace);
65
+ if (!p || !tenant || !p.async?.stepDrop || !okIds(runId, ref ?? ""))
66
+ return;
67
+ await p.async.stepDrop(tenant, workspace, runId, kind, ref);
68
+ }
69
+ // ------------------------------------------------------------ storage baseline
70
+ const baselineFile = (workspaceRoot, runId) => path.join(workspaceRoot, "runs", runId, "storage-baseline.json");
71
+ const asHashes = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : undefined);
72
+ /** The storage index this run first materialized, or undefined: it has not been here. */
73
+ export async function readStorageBaseline(workspaceRoot, tenant, workspace, runId) {
74
+ const row = asHashes(await getStepState(tenant, workspace, runId, "storage", ""));
75
+ if (row)
76
+ return row;
77
+ const file = baselineFile(workspaceRoot, runId);
78
+ if (!fs.existsSync(file))
79
+ return undefined;
80
+ try {
81
+ return asHashes(JSON.parse(fs.readFileSync(file, "utf8")));
82
+ }
83
+ catch {
84
+ return undefined;
85
+ }
86
+ }
87
+ export async function writeStorageBaseline(workspaceRoot, tenant, workspace, runId, hashes) {
88
+ if (await putStepState(tenant, workspace, runId, "storage", "", hashes))
89
+ return;
90
+ const file = baselineFile(workspaceRoot, runId);
91
+ fs.mkdirSync(path.dirname(file), { recursive: true });
92
+ fs.writeFileSync(file, JSON.stringify(hashes));
93
+ }
@@ -155,7 +155,18 @@ export interface S3Config {
155
155
  /** `https://s3.ap-southeast-2.amazonaws.com` → `ap-southeast-2`. Null for
156
156
  * anything else (R2, MinIO), whose region is whatever the env says. */
157
157
  export declare function regionOfEndpoint(endpoint: string): string | null;
158
- export declare function s3Config(): S3Config | null;
158
+ export declare function s3Config(env?: NodeJS.ProcessEnv): S3Config | null;
159
+ /**
160
+ * The origin the browser reaches the object store at — where a presigned PUT
161
+ * (an upload) and a presigned GET (a video, audio or PDF preview) go — so the
162
+ * dashboard's Content-Security-Policy can name it and nothing wider. Null
163
+ * unless S3 is the driver in force (the same test driverFor makes), or when
164
+ * the address is not a plain http(s) host. It is built by the same function
165
+ * as the signed URLs (bucketHost), so the two cannot drift: path-style gives
166
+ * the endpoint's origin, virtual-hosted gives `https://<bucket>.<host>`.
167
+ * Reads only the environment; it fetches no credentials.
168
+ */
169
+ export declare function storeOrigin(env?: NodeJS.ProcessEnv): string | null;
159
170
  /** For tests: forget cached role credentials. */
160
171
  export declare function forgetS3Credentials(): void;
161
172
  /** A body that is not held in memory: read as it is sent. `length` and
@@ -434,31 +434,59 @@ export function regionOfEndpoint(endpoint) {
434
434
  /** True when this process runs under an AWS role handed out through the
435
435
  * container credential endpoint — EKS Pod Identity, ECS, or an IRSA-style
436
436
  * shim. The endpoint is the pod's, and the token file is mounted beside it. */
437
- function containerCredentialsAvailable() {
438
- return Boolean(process.env.AWS_CONTAINER_CREDENTIALS_FULL_URI || process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI);
439
- }
440
- export function s3Config() {
441
- const endpoint = process.env.FOLDRUN_S3_ENDPOINT;
442
- const bucket = process.env.FOLDRUN_S3_BUCKET;
443
- const accessKeyId = process.env.FOLDRUN_S3_ACCESS_KEY_ID;
444
- const secretAccessKey = process.env.FOLDRUN_S3_SECRET_ACCESS_KEY;
437
+ function containerCredentialsAvailable(env = process.env) {
438
+ return Boolean(env.AWS_CONTAINER_CREDENTIALS_FULL_URI || env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI);
439
+ }
440
+ export function s3Config(env = process.env) {
441
+ const endpoint = env.FOLDRUN_S3_ENDPOINT;
442
+ const bucket = env.FOLDRUN_S3_BUCKET;
443
+ const accessKeyId = env.FOLDRUN_S3_ACCESS_KEY_ID;
444
+ const secretAccessKey = env.FOLDRUN_S3_SECRET_ACCESS_KEY;
445
445
  if (!endpoint || !bucket)
446
446
  return null;
447
447
  const staticKeys = Boolean(accessKeyId && secretAccessKey);
448
448
  // No key and no role is a half-set environment: fall back to fs rather
449
449
  // than fail at the first upload (driverFor says why).
450
- if (!staticKeys && !containerCredentialsAvailable())
450
+ if (!staticKeys && !containerCredentialsAvailable(env))
451
451
  return null;
452
452
  return {
453
453
  endpoint: endpoint.replace(/\/+$/, ""),
454
454
  bucket,
455
455
  // R2 has one region and calls it `auto`. An AWS endpoint names its own;
456
456
  // anything else says so in the env.
457
- region: process.env.FOLDRUN_S3_REGION ?? regionOfEndpoint(endpoint) ?? "auto",
457
+ region: env.FOLDRUN_S3_REGION ?? regionOfEndpoint(endpoint) ?? "auto",
458
458
  ...(staticKeys ? { accessKeyId, secretAccessKey } : {}),
459
- pathStyle: process.env.FOLDRUN_S3_PATH_STYLE !== "false",
459
+ pathStyle: env.FOLDRUN_S3_PATH_STYLE !== "false",
460
460
  };
461
461
  }
462
+ /**
463
+ * The origin the browser reaches the object store at — where a presigned PUT
464
+ * (an upload) and a presigned GET (a video, audio or PDF preview) go — so the
465
+ * dashboard's Content-Security-Policy can name it and nothing wider. Null
466
+ * unless S3 is the driver in force (the same test driverFor makes), or when
467
+ * the address is not a plain http(s) host. It is built by the same function
468
+ * as the signed URLs (bucketHost), so the two cannot drift: path-style gives
469
+ * the endpoint's origin, virtual-hosted gives `https://<bucket>.<host>`.
470
+ * Reads only the environment; it fetches no credentials.
471
+ */
472
+ export function storeOrigin(env = process.env) {
473
+ if (env.FOLDRUN_STORAGE_DRIVER !== "s3")
474
+ return null;
475
+ try {
476
+ const cfg = s3Config(env);
477
+ if (!cfg)
478
+ return null;
479
+ const u = new URL(bucketHost(cfg).origin);
480
+ if (u.protocol !== "https:" && u.protocol !== "http:")
481
+ return null;
482
+ if (!u.hostname || u.hostname.includes("*") || u.origin === "null")
483
+ return null;
484
+ return u.origin;
485
+ }
486
+ catch {
487
+ return null; // an endpoint that is not a URL: no source, never a broken one
488
+ }
489
+ }
462
490
  // ---------- credentials ----------
463
491
  //
464
492
  // Static keys are used as given. Without them, the process is running under
@@ -523,13 +551,19 @@ function signingKey(cfg, creds, dateStamp) {
523
551
  }
524
552
  /** Where a key lives, split into the host and the canonical path SigV4 signs. */
525
553
  function target(cfg, key) {
526
- const url = new URL(cfg.endpoint);
527
554
  const encoded = uriEncode(key, true);
528
- if (cfg.pathStyle) {
529
- return { host: url.host, origin: url.origin, canonicalUri: `/${cfg.bucket}/${encoded}` };
530
- }
555
+ const { host, origin } = bucketHost(cfg);
556
+ return { host, origin, canonicalUri: cfg.pathStyle ? `/${cfg.bucket}/${encoded}` : `/${encoded}` };
557
+ }
558
+ /** The host a request for this bucket goes to: the endpoint's own
559
+ * (path-style), or `<bucket>.<endpoint host>` (virtual-hosted). Shared by
560
+ * target() and storeOrigin(). */
561
+ function bucketHost(cfg) {
562
+ const url = new URL(cfg.endpoint);
563
+ if (cfg.pathStyle)
564
+ return { host: url.host, origin: url.origin };
531
565
  const host = `${cfg.bucket}.${url.host}`;
532
- return { host, origin: `${url.protocol}//${host}`, canonicalUri: `/${encoded}` };
566
+ return { host, origin: `${url.protocol}//${host}` };
533
567
  }
534
568
  /**
535
569
  * A presigned URL — SigV4 in the query string, so the browser (or a run pod)
@@ -1533,6 +1533,15 @@ export interface PriceSnapshot {
1533
1533
  at: string;
1534
1534
  values: Record<string, number>;
1535
1535
  }
1536
+ export interface RefusedOutput {
1537
+ agent: string;
1538
+ /** Relative to that agent's outputs/. */
1539
+ path: string;
1540
+ bytes: number;
1541
+ reason: "file-cap" | "run-cap" | "name" | "count";
1542
+ /** The cap in bytes that was exceeded (the count for "count"). */
1543
+ limit?: number;
1544
+ }
1536
1545
  export interface RunRecord {
1537
1546
  id: string;
1538
1547
  flow: string;
@@ -1604,6 +1613,12 @@ export interface RunRecord {
1604
1613
  * the agents decided was worth remembering, listed so a person can review
1605
1614
  * the lesson without diffing the folder. */
1606
1615
  memoryWrites?: string[];
1616
+ /** Files a run's agents left in outputs/ that were NOT kept, and why (FOL-126
1617
+ * phase 5): over the per-file or per-run size cap, a name the store cannot
1618
+ * hold, or too many files. Shown on the run page and listed by /files. At
1619
+ * most 100 are named; `outputsRefusedCount` is the whole number. */
1620
+ outputsRefused?: RefusedOutput[];
1621
+ outputsRefusedCount?: number;
1607
1622
  /** The workspace's deployed commit when the run was created — which
1608
1623
  * version of the files it ran (FOL-54 step 4). Absent for a workspace
1609
1624
  * never deployed, and before 19 Oct 2026. */
@@ -1698,6 +1713,9 @@ export declare function runFilePath(tenant: string, workspace: string, runId: st
1698
1713
  export declare function deleteRun(tenant: string, workspace: string, runId: string, opts?: {
1699
1714
  pruned?: boolean;
1700
1715
  }): boolean;
1716
+ /** run-outputs.ts registers here (it imports this module). */
1717
+ declare let onRunRemoved: ((tenant: string, workspace: string, runId: string) => void) | null;
1718
+ export declare function registerRunRemovedHook(fn: typeof onRunRemoved): void;
1701
1719
  /** ledger.ts registers here — store cannot import it without a cycle, and
1702
1720
  * money must not depend on one. */
1703
1721
  declare let onRunDeleted: ((tenant: string, workspace: string, runId: string) => void) | undefined;
@@ -1709,17 +1727,20 @@ export interface RunOutputFile {
1709
1727
  bytes: number;
1710
1728
  }
1711
1729
  /**
1712
- * What a run archived: every file its agents left in outputs/, copied under
1713
- * runs/<id>/outputs/<agent>/ when the run finished (runner.ts, archive()).
1730
+ * What a run archived ON THE VOLUME: every file its agents left in outputs/,
1731
+ * copied under runs/<id>/outputs/<agent>/ when the run finished (runner.ts,
1732
+ * archive()). Where run outputs are published to the blob store (FOL-126
1733
+ * phase 5, run-outputs.ts) this is only the fallback and the laptop's copy;
1734
+ * callers use run-outputs.ts listRunOutputs, which asks both.
1714
1735
  *
1715
1736
  * Per agent, not per step — the archive is a copy of each agent's folder,
1716
1737
  * and the record cannot say which step wrote which file. An agent that
1717
1738
  * steps twice in one run shows the same files against both steps.
1718
1739
  */
1719
- export declare function listRunOutputs(tenant: string, workspace: string, runId: string): RunOutputFile[];
1740
+ export declare function listRunOutputsOnVolume(tenant: string, workspace: string, runId: string): RunOutputFile[];
1720
1741
  /** The absolute path of one archived output, or null when the name escapes
1721
1742
  * the archive or names nothing — the API serves only what this returns. */
1722
- export declare function runOutputPath(tenant: string, workspace: string, runId: string, agent: string, rel: string): string | null;
1743
+ export declare function runOutputPathOnVolume(tenant: string, workspace: string, runId: string, agent: string, rel: string): string | null;
1723
1744
  export declare function readRun(tenant: string, workspace: string, runId: string): RunRecord | null;
1724
1745
  /** readRun without holding the event loop: asked of the database directly
1725
1746
  * where the port has async reads, otherwise the synchronous read. */
package/dist/src/store.js CHANGED
@@ -3011,6 +3011,9 @@ export function deleteRun(tenant, workspace, runId, opts = {}) {
3011
3011
  if (prior?.inputs?.length) {
3012
3012
  void import("./storage.js").then((m) => m.releaseRunInputs(tenant, workspace, runId)).catch(() => { });
3013
3013
  }
3014
+ // Outputs published to the blob store (run-outputs.ts) are records and pins,
3015
+ // not files under dir: they go in the background, retried.
3016
+ onRunRemoved?.(tenant, workspace, runId);
3014
3017
  if (!had)
3015
3018
  return true;
3016
3019
  // The retention window's prune (`pruned`) is policy, not a person erasing
@@ -3019,6 +3022,11 @@ export function deleteRun(tenant, workspace, runId, opts = {}) {
3019
3022
  onRunDeleted?.(tenant, workspace, runId);
3020
3023
  return true;
3021
3024
  }
3025
+ /** run-outputs.ts registers here (it imports this module). */
3026
+ let onRunRemoved = null;
3027
+ export function registerRunRemovedHook(fn) {
3028
+ onRunRemoved = fn;
3029
+ }
3022
3030
  /** ledger.ts registers here — store cannot import it without a cycle, and
3023
3031
  * money must not depend on one. */
3024
3032
  let onRunDeleted;
@@ -3026,14 +3034,17 @@ export function registerRunDeletionListener(fn) {
3026
3034
  onRunDeleted = fn;
3027
3035
  }
3028
3036
  /**
3029
- * What a run archived: every file its agents left in outputs/, copied under
3030
- * runs/<id>/outputs/<agent>/ when the run finished (runner.ts, archive()).
3037
+ * What a run archived ON THE VOLUME: every file its agents left in outputs/,
3038
+ * copied under runs/<id>/outputs/<agent>/ when the run finished (runner.ts,
3039
+ * archive()). Where run outputs are published to the blob store (FOL-126
3040
+ * phase 5, run-outputs.ts) this is only the fallback and the laptop's copy;
3041
+ * callers use run-outputs.ts listRunOutputs, which asks both.
3031
3042
  *
3032
3043
  * Per agent, not per step — the archive is a copy of each agent's folder,
3033
3044
  * and the record cannot say which step wrote which file. An agent that
3034
3045
  * steps twice in one run shows the same files against both steps.
3035
3046
  */
3036
- export function listRunOutputs(tenant, workspace, runId) {
3047
+ export function listRunOutputsOnVolume(tenant, workspace, runId) {
3037
3048
  const root = path.join(workspaceDir(tenant, workspace), "runs", runId, "outputs");
3038
3049
  if (!fs.existsSync(root))
3039
3050
  return [];
@@ -3056,7 +3067,7 @@ export function listRunOutputs(tenant, workspace, runId) {
3056
3067
  }
3057
3068
  /** The absolute path of one archived output, or null when the name escapes
3058
3069
  * the archive or names nothing — the API serves only what this returns. */
3059
- export function runOutputPath(tenant, workspace, runId, agent, rel) {
3070
+ export function runOutputPathOnVolume(tenant, workspace, runId, agent, rel) {
3060
3071
  if (!agent || !rel || agent.includes("/") || agent.includes("\\") || agent.startsWith("."))
3061
3072
  return null;
3062
3073
  const root = path.resolve(workspaceDir(tenant, workspace), "runs", runId, "outputs", agent);