@foldrun/core 18.4.0 → 19.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.
@@ -47,6 +47,8 @@ import type { SearchRoot, RunDigest } from "./context-tools.ts";
47
47
  import type { TranslatorSpec } from "./translator.ts";
48
48
  import { parseBrowserPod, type BrowserPodOutcome } from "./browser-pod.ts";
49
49
  import type { RemoteSpec } from "./a2a-remotes.ts";
50
+ import { stageRunInputs, type RunInputFile } from "./storage.ts";
51
+ import { INPUTS_DIR, stagedLine } from "./run-inputs.ts";
50
52
 
51
53
  /** What crosses the boundary. Everything in here is values — pre-resolved
52
54
  * secrets in headers, assembled prompt, serializable MCP configs. */
@@ -482,6 +484,10 @@ export function mergeAppends(was: Buffer | string | null, host: Buffer, next: Bu
482
484
  }
483
485
 
484
486
  export interface ApplyOptions {
487
+ /** Never take back what is under this workspace-relative folder (with its
488
+ * trailing `/`) — a step's staged inputs (FOL-163): whatever it does in
489
+ * there stays in the sandbox. Checked before anything is read. */
490
+ drop?: string;
485
491
  /** Take back only what is under this workspace-relative folder (with its
486
492
  * trailing `/`) — a snapshot run's outputs (Part B3): the folder it was
487
493
  * given, and anything it copied anywhere else, never reach the workspace. */
@@ -559,10 +565,12 @@ export function applyContainerChanges(
559
565
  const posix = rel.replaceAll("\\", "/");
560
566
  if (entry.isDirectory()) {
561
567
  const d = posix + "/";
568
+ if (opts.drop && d.startsWith(opts.drop)) continue;
562
569
  if (opts.keepOnly && !(d.startsWith(opts.keepOnly) || opts.keepOnly.startsWith(d))) continue;
563
570
  if (allowedBack(rel + "/")) walk(abs);
564
571
  continue;
565
572
  }
573
+ if (opts.drop && (posix.startsWith(opts.drop) || `${posix}/` === opts.drop)) continue;
566
574
  if (opts.keepOnly && !posix.startsWith(opts.keepOnly)) continue;
567
575
  if (!allowedBack(rel)) continue;
568
576
  let next: Buffer = fs.readFileSync(abs);
@@ -1875,6 +1883,9 @@ export interface RunInContainerArgs {
1875
1883
  * agents/<name>/snapshot/, takes back only that agent's outputs/, and
1876
1884
  * leaves the patch there as outputs/snapshot.patch. */
1877
1885
  snapshot?: { id: string };
1886
+ /** FOL-163: the run's inputs, for the step its task reaches — staged at
1887
+ * <agentRel>/inputs/ after the workspace copy, never copied back. */
1888
+ inputs?: { runId: string; files: RunInputFile[] };
1878
1889
  /** A person approved this step before it ran: configuration and code it
1879
1890
  * changed are kept, not refused (copy-back.ts, FOL-96). */
1880
1891
  configWrites?: boolean;
@@ -2159,6 +2170,14 @@ export async function runStepInContainer(args: RunInContainerArgs): Promise<Cont
2159
2170
  const laid = overlayTestWrites(wsIn, args.divert.to);
2160
2171
  if (laid.length) args.emit("info", `test: this step sees ${laid.length} file${laid.length === 1 ? "" : "s"} earlier steps of this run wrote`);
2161
2172
  }
2173
+ // The run's inputs (FOL-163), at <agentRel>/inputs/ — after the copy and
2174
+ // the test overlay, so the copy is their baseline too and a folder of
2175
+ // that name in the workspace never mixes in.
2176
+ if (args.inputs?.files.length) {
2177
+ if (!args.tenant) throw new Error("a step with inputs needs its account");
2178
+ const staged = await stageRunInputs(args.tenant, path.basename(args.workspaceRoot), args.inputs.runId, args.inputs.files, path.join(wsIn, args.input.agentRel, INPUTS_DIR));
2179
+ args.emit("info", stagedLine(staged.files, staged.bytes));
2180
+ }
2162
2181
  const libIn = path.join(staging, "library");
2163
2182
  if (args.galleryRoot && fs.existsSync(args.galleryRoot)) fs.cpSync(args.galleryRoot, libIn, { recursive: true });
2164
2183
  if (fs.existsSync(args.libraryRoot)) fs.cpSync(args.libraryRoot, libIn, { recursive: true });
@@ -2324,6 +2343,8 @@ export async function runStepInContainer(args: RunInContainerArgs): Promise<Cont
2324
2343
  allowConfig: args.configWrites === true,
2325
2344
  onKept: (r) => kept.push(r),
2326
2345
  revision: args.tenant ? { tenant: args.tenant, runId: args.runId, step: containerId, base: pinned?.base ?? null } : undefined,
2346
+ // Staged inputs stay in the sandbox, whatever the step did there (FOL-163).
2347
+ ...(args.inputs?.files.length ? { drop: `${args.input.agentRel}/${INPUTS_DIR}/` } : {}),
2327
2348
  });
2328
2349
  if (refused.length) args.emit("info", refusedLine(refused));
2329
2350
  if (kept.length) args.emit("info", keptLine(kept));
@@ -0,0 +1,62 @@
1
+ // Inputs on a run (FOL-163, 11 Nov 2026): files a caller hands a run — storage
2
+ // paths, as GET …/storage lists them — staged into the step its task reaches,
3
+ // at agents/<name>/inputs/<path>. What the run reads is fixed when it is made
4
+ // (storage.ts holdRunInputs holds each file's blob for the run), so an
5
+ // overwrite or a delete in between changes nothing.
6
+ //
7
+ // Only an isolated executor stages them — docker (`container`) or one the
8
+ // platform says can hold them (platform.holdsInputs: k8s) — and whatever the
9
+ // step does inside inputs/ never comes back to the workspace (ApplyOptions
10
+ // drop). In-process, a step works in the real folder: two runs of one agent
11
+ // would share inputs/, and nothing stands between its writes and the
12
+ // workspace, so a run with inputs there is refused before anything starts.
13
+ //
14
+ // Images and PDFs are shown to the model when it reads them with Read: the
15
+ // Agent SDK turns them into image and document blocks, and the translator
16
+ // carries those to an OpenAI-format endpoint where it can (translator.ts).
17
+
18
+ import type { RunInputFile } from "./storage.ts";
19
+
20
+ export type { RunInputFile };
21
+
22
+ /** foldrun's limits on what one run may be handed — not a model's. */
23
+ export const INPUT_LIMITS = {
24
+ files: 20,
25
+ /** All of them together: 100 MiB. */
26
+ totalBytes: 100 * 1024 * 1024,
27
+ } as const;
28
+
29
+ /** The folder, under the agent's working directory. */
30
+ export const INPUTS_DIR = "inputs";
31
+
32
+ /** Null when `paths` is a list the run routes may take; otherwise why not. */
33
+ export function inputsProblem(paths: unknown): string | null {
34
+ if (!Array.isArray(paths)) return "inputs is a list of storage paths";
35
+ if (paths.some((p) => typeof p !== "string" || !p.trim())) return "inputs is a list of storage paths (strings)";
36
+ if (new Set(paths).size > INPUT_LIMITS.files) return `at most ${INPUT_LIMITS.files} inputs on one run`;
37
+ return null;
38
+ }
39
+
40
+ /** Null when the resolved files fit foldrun's limits; otherwise why not. */
41
+ export function inputsSizeProblem(files: RunInputFile[]): string | null {
42
+ const total = files.reduce((n, f) => n + f.size, 0);
43
+ if (total > INPUT_LIMITS.totalBytes) return `the inputs come to ${(total / 1048576).toFixed(1)} MiB — at most ${INPUT_LIMITS.totalBytes / 1048576} MiB on one run`;
44
+ return null;
45
+ }
46
+
47
+ const human = (n: number) => (n >= 1048576 ? `${(n / 1048576).toFixed(1)} MiB` : n >= 1024 ? `${Math.round(n / 1024)} KiB` : `${n} B`);
48
+
49
+ /** What the step is told, after its instruction. */
50
+ export function inputsNote(files: RunInputFile[]): string {
51
+ const lines = files.map((f) => `- ${INPUTS_DIR}/${f.path} (${f.mime}, ${human(f.size)})`);
52
+ return (
53
+ `<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
+ "Read them with the Read tool. Supported images and PDFs are shown to you as they are; when a model cannot be shown a file, the tool result says so. " +
55
+ `The files stay available to scripts. Anything you write in ${INPUTS_DIR}/ is not kept — put results in outputs/.\n</inputs>`
56
+ );
57
+ }
58
+
59
+ /** The trail's line once they are staged. */
60
+ export function stagedLine(files: number, bytes: number): string {
61
+ return `inputs: ${files} file${files === 1 ? "" : "s"} in ${INPUTS_DIR}/ (${human(bytes)})`;
62
+ }
package/src/runner.ts CHANGED
@@ -126,6 +126,8 @@ import { NEWER_ACTIONS, resolveActionApi } from "./web-actions.ts";
126
126
  import { resolveLanguage, languageName, type LanguageChoice } from "./language.ts";
127
127
  import { resolveRegion, deriveLocale, localeProse, regionName, type RegionChoice, type LocaleFacts } from "./locale.ts";
128
128
  import { trimChars } from "./paths.ts";
129
+ import { earlierTurns, conversationBlock, type RunContext, type RunInput } from "./conversation.ts";
130
+ import { inputsNote, type RunInputFile } from "./run-inputs.ts";
129
131
  import { resolveClock, localDate, type ClockChoice } from "./clock.ts";
130
132
 
131
133
  export { localDate } from "./clock.ts";
@@ -2224,6 +2226,10 @@ async function runStep(
2224
2226
  * mayDefer). Absent: it waits here, however long — a rescue, a step
2225
2227
  * outside a flow, a foreground run. */
2226
2228
  mayDefer?: () => boolean,
2229
+ /** FOL-162: the earlier turns of the run's conversation, as the block
2230
+ * conversation.ts built — read before the instruction. Already escaped;
2231
+ * never resolved for [[links]] (it is other runs' words). */
2232
+ conversation?: string,
2227
2233
  ) {
2228
2234
  // Secret values are injected into scripts as environment variables and
2229
2235
  // substituted into API headers, so a model that reads one back — from a
@@ -2360,6 +2366,8 @@ async function runStep(
2360
2366
  // The ceiling it was given rides on the line, so the budget arithmetic
2361
2367
  // around fan-out is testable without a model to stop.
2362
2368
  push("info", `stub call ${call + 1}${stepBudgetUsd !== null ? ` (ceiling $${stepBudgetUsd.toFixed(2)})` : ""}`);
2369
+ // What a real step would have read before its instruction (FOL-162).
2370
+ if (conversation) push("info", `stub conversation: ${conversation}`);
2363
2371
  step.status = "completed";
2364
2372
  // A stub answer may open with `cost: 0.25` — a pretend price, so the
2365
2373
  // parts of orchestration that watch money (budget:) are testable too.
@@ -2779,6 +2787,9 @@ async function runStep(
2779
2787
  let prompt = step.instruction
2780
2788
  ? resolveDocLinks(step.instruction, workspaceRoot)
2781
2789
  : "Begin your run now, following your instructions.";
2790
+ // The conversation's earlier turns go first, the request after them —
2791
+ // in the user turn, not the system prompt (conversation.ts says why).
2792
+ if (conversation) prompt = `${conversation}\n\n${prompt}`;
2782
2793
  if (context) prompt += `\n\n<previous_step_results>\n${context.slice(0, CONTEXT_CHARS)}\n</previous_step_results>`;
2783
2794
  if (priorData !== undefined) {
2784
2795
  // The value itself, beside the prose that mentioned it. This is the
@@ -2972,7 +2983,19 @@ async function runStep(
2972
2983
  // run was made. Only an executor that says it can hold one may run it —
2973
2984
  // in-process, the step would work in the real workspace folder, and no
2974
2985
  // copy-back stands between what it writes and the workspace (Codex).
2975
- const snapshotId = runId ? readRun(tenant, path.basename(workspaceRootOf(agentDir)), runId)?.snapshot?.id : undefined;
2986
+ const runRecord = runId ? readRun(tenant, path.basename(workspaceRootOf(agentDir)), runId) : null;
2987
+ const snapshotId = runRecord?.snapshot?.id;
2988
+ // The run's inputs (FOL-163), for the step its task reaches. Staged only
2989
+ // by an executor that can hold them: in-process the step would share the
2990
+ // real agents/<name>/inputs/ with every other run of the agent, and its
2991
+ // writes there would land in the workspace.
2992
+ const stepInputs = step.inputsTurn && runRecord?.inputs?.length ? runRecord.inputs : null;
2993
+ if (stepInputs) {
2994
+ const able = isolatedRun() && (isolation === "container" || (Boolean(platform.isolation[isolation!]) && platform.holdsInputs?.(isolation!) === true));
2995
+ if (!able) {
2996
+ throw new Error("this run was handed input files, and this install cannot stage them: it needs a sandbox (FOLDRUN_RUN_ISOLATION=k8s or container). Nothing was run.");
2997
+ }
2998
+ }
2976
2999
  if (snapshotId) {
2977
3000
  const able = isolatedRun() && isolation !== "container" && Boolean(platform.isolation[isolation!]) && platform.holdsSnapshot?.(isolation!) === true;
2978
3001
  if (!able) {
@@ -3000,7 +3023,7 @@ async function runStep(
3000
3023
  // before anything is copied in. Null where no proxy is configured
3001
3024
  // (the CLI, a compose install without FOLDRUN_EGRESS_URL), and then
3002
3025
  // everything below materialises exactly as it always did.
3003
- const grant: EgressGrant = { secrets: {}, timezone: clock.timezone };
3026
+ const grant: EgressGrant = { secrets: {}, timezone: clock.timezone, ...(runRecord?.customer ? { customer: runRecord.customer } : {}) };
3004
3027
  // A direct search API's key: granted to that API's host and no other,
3005
3028
  // exactly as an http tool's key is granted to its base URL's host. The
3006
3029
  // script sends the placeholder; the worker fills it on the way out.
@@ -3361,6 +3384,7 @@ async function runStep(
3361
3384
  const isolatedArgs = (modelEnv: Record<string, string | undefined>, keyName = MODEL_KEY_NAME) => ({
3362
3385
  workspaceRoot,
3363
3386
  ...(snapshotId ? { snapshot: { id: snapshotId } } : {}),
3387
+ ...(stepInputs && runId ? { inputs: { runId, files: stepInputs } } : {}),
3364
3388
  libraryRoot: libraryDir(tenant),
3365
3389
  galleryRoot: platform.galleryDir() ?? undefined,
3366
3390
  // Keys this step's dependency cache. Per-account by design — see
@@ -3371,7 +3395,7 @@ async function runStep(
3371
3395
  // Its file tools inside the sandbox get the same allowance (FOL-96).
3372
3396
  configWrites: step.approve === true && Boolean(step.approvedAt),
3373
3397
  // A snapshot step is told where its folder is, and what comes back.
3374
- prompt: snapshotId ? `${prompt}\n\n${SNAPSHOT_NOTE}` : prompt,
3398
+ prompt: `${prompt}${snapshotId ? `\n\n${SNAPSHOT_NOTE}` : ""}${stepInputs ? `\n\n${inputsNote(stepInputs)}` : ""}`,
3375
3399
  model,
3376
3400
  effort,
3377
3401
  systemPrompt,
@@ -4579,6 +4603,16 @@ export function createFlowRun(
4579
4603
  /** A snapshot run's folder (Part B3): the id POST …/snapshots answered.
4580
4604
  * Its own trailing argument, as a2a is, so the signature only widened. */
4581
4605
  snapshot?: string,
4606
+ /** FOL-162: the conversation this run is a turn of, and what it was
4607
+ * asked — written with the record, before any worker can see it. The
4608
+ * run's first step (the one its task reaches) reads the earlier turns. */
4609
+ conversation?: { context: RunContext; input?: RunInput },
4610
+ /** FOL-163: the files the run is handed, already held for it (storage.ts
4611
+ * holdRunInputs). The run's first step — the one its task reaches — is
4612
+ * given them at agents/<name>/inputs/. */
4613
+ inputs?: RunInputFile[],
4614
+ /** FOL-168: which of the partner's own users the run is for. */
4615
+ customer?: string,
4582
4616
  ): RunRecord {
4583
4617
  let flowMaxOut: number | undefined;
4584
4618
  try {
@@ -4642,6 +4676,16 @@ export function createFlowRun(
4642
4676
  costUsd: null,
4643
4677
  })),
4644
4678
  };
4679
+ if (conversation?.context) {
4680
+ run.context = conversation.context;
4681
+ if (conversation.input) run.input = conversation.input;
4682
+ if (run.steps[0]) run.steps[0].conversationTurn = true;
4683
+ }
4684
+ if (inputs?.length) {
4685
+ run.inputs = inputs;
4686
+ if (run.steps[0]) run.steps[0].inputsTurn = true;
4687
+ }
4688
+ if (customer) run.customer = customer;
4645
4689
  writeRun(tenant, workspace, run);
4646
4690
 
4647
4691
  // Start every run from an empty outputs/ for each agent it will touch.
@@ -5736,6 +5780,32 @@ function driveRunInner(
5736
5780
  // of its group is under way (a sibling still running keeps the run
5737
5781
  // here anyway), and only once the group has waited a while, so a
5738
5782
  // short wait stays a short wait. Never on a foreground run.
5783
+ // FOL-162: the earlier turns of the run's conversation, for the step
5784
+ // the run's task reaches. Read fresh at each start (a retry, a
5785
+ // resume) — the same turns each time, since which runs count is
5786
+ // fixed by when this run was made. A lookup that fails costs the
5787
+ // step its history, never the step.
5788
+ const conversationFor = (step: StepRecord): string | undefined => {
5789
+ if (!step.conversationTurn || !run.context) return undefined;
5790
+ try {
5791
+ const built = conversationBlock(run, earlierTurns(tenant, workspace, run));
5792
+ if (!built) {
5793
+ delete step.history;
5794
+ return undefined;
5795
+ }
5796
+ step.history = built.record;
5797
+ const r = built.record;
5798
+ step.events.push({
5799
+ t: new Date().toISOString(),
5800
+ type: "info",
5801
+ text: `conversation ${run.context.id}: given ${r.runs.length} earlier run${r.runs.length === 1 ? "" : "s"} (${r.chars.toLocaleString("en")} characters)${r.omitted ? `, ${r.omitted} older not given` : ""}${r.truncated ? `, ${r.truncated} cut short` : ""}`,
5802
+ });
5803
+ return built.text;
5804
+ } catch (err) {
5805
+ step.events.push({ t: new Date().toISOString(), type: "info", text: `conversation ${run.context.id}: the earlier runs could not be read (${err instanceof Error ? err.message : String(err)}) — this step runs without them` });
5806
+ return undefined;
5807
+ }
5808
+ };
5739
5809
  const mayDefer = (step: StepRecord) => () => {
5740
5810
  if (!opts.parkOnApproval) return false;
5741
5811
  if (launching.some((s) => s !== step && s.status === "running" && !s.roomWait)) return false;
@@ -5875,6 +5945,7 @@ function driveRunInner(
5875
5945
  peerBus,
5876
5946
  delegateFor(step),
5877
5947
  mayDefer(step),
5948
+ conversationFor(step),
5878
5949
  ).finally(() => reserved.delete(step));
5879
5950
  // Sent back for room: not a try. The run parks once the
5880
5951
  // group is done (below) and this attempt starts again later.
@@ -6063,7 +6134,7 @@ function driveRunInner(
6063
6134
  resumed.attempts = Math.max(1, resumed.attempts ?? 0);
6064
6135
  resumed.status = "running";
6065
6136
  save();
6066
- await runStep(rescuerDir, tenant, resumed, ctx, save, modelOverride, tags, effortOverride, run.id, ctxData, null, undefined, run.test === true, stopPoll, flowTimezone, run.steps.indexOf(resumed));
6137
+ await runStep(rescuerDir, tenant, resumed, ctx, save, modelOverride, tags, effortOverride, run.id, ctxData, null, undefined, run.test === true, stopPoll, flowTimezone, run.steps.indexOf(resumed), [], undefined, undefined, undefined, conversationFor(resumed));
6067
6138
  settleRescue(step, resumed);
6068
6139
  return;
6069
6140
  }
@@ -6106,6 +6177,10 @@ function driveRunInner(
6106
6177
  // medium-desk).
6107
6178
  output: step.output,
6108
6179
  ...(step.verify ? { verify: step.verify } : {}),
6180
+ // Taking over the step the run's task reached: the conversation
6181
+ // and the inputs too.
6182
+ ...(step.conversationTurn ? { conversationTurn: true } : {}),
6183
+ ...(step.inputsTurn ? { inputsTurn: true } : {}),
6109
6184
  attempts: 0,
6110
6185
  status: "pending",
6111
6186
  events: [],
@@ -6117,7 +6192,7 @@ function driveRunInner(
6117
6192
  rescue.attempts = 1;
6118
6193
  rescue.status = "running";
6119
6194
  save();
6120
- await runStep(rescuerDir, tenant, rescue, ctx, save, modelOverride, tags, effortOverride, run.id, ctxData, null, undefined, run.test === true, stopPoll, flowTimezone, run.steps.indexOf(rescue));
6195
+ await runStep(rescuerDir, tenant, rescue, ctx, save, modelOverride, tags, effortOverride, run.id, ctxData, null, undefined, run.test === true, stopPoll, flowTimezone, run.steps.indexOf(rescue), [], undefined, undefined, undefined, conversationFor(rescue));
6121
6196
  settleRescue(step, rescue);
6122
6197
  };
6123
6198
  // What a rescue's end means for the step it took over.
@@ -16,10 +16,14 @@ export interface RunFilter {
16
16
  minTokens?: number;
17
17
  /** The run took at least this many seconds. */
18
18
  minSecs?: number;
19
+ /** The run is a turn of this conversation: its `context` id, exactly (FOL-162). */
20
+ context?: string;
21
+ /** The run is for this end customer, exactly (FOL-168). */
22
+ customer?: string;
19
23
  }
20
24
 
21
25
  /** The query parameters a filter comes from: tool, tool_error, agent,
22
- * model, min_tokens, min_secs. Unreadable numbers are refused in words. */
26
+ * model, min_tokens, min_secs, context. Unreadable numbers are refused in words. */
23
27
  export function parseRunFilter(q: { get(name: string): string | null }): { filter: RunFilter; problems: string[] } {
24
28
  const filter: RunFilter = {};
25
29
  const problems: string[] = [];
@@ -32,6 +36,10 @@ export function parseRunFilter(q: { get(name: string): string | null }): { filte
32
36
  if (agent) filter.agent = agent;
33
37
  const model = text("model");
34
38
  if (model) filter.model = model.toLowerCase();
39
+ const context = q.get("context");
40
+ if (context) filter.context = context;
41
+ const customer = q.get("customer");
42
+ if (customer) filter.customer = customer;
35
43
  for (const [k, field] of [["min_tokens", "minTokens"], ["min_secs", "minSecs"]] as const) {
36
44
  const v = text(k);
37
45
  if (v === undefined) continue;
@@ -57,7 +65,7 @@ type FilterableStep = {
57
65
  startedAt?: string;
58
66
  finishedAt?: string;
59
67
  };
60
- type FilterableRun = { startedAt: string; finishedAt?: string | null; steps: FilterableStep[] };
68
+ type FilterableRun = { startedAt: string; finishedAt?: string | null; context?: { id: string }; customer?: string; steps: FilterableStep[] };
61
69
 
62
70
  /** The index's facts, or worked out from a whole record's events (Codex
63
71
  * review: the workspace runs page reads whole records). */
@@ -74,6 +82,8 @@ function factsOf(s: FilterableStep): { tools: string[]; toolErrors: number } {
74
82
  }
75
83
 
76
84
  export function matchesRunFilter(run: FilterableRun, f: RunFilter, now = Date.now()): boolean {
85
+ if (f.context !== undefined && run.context?.id !== f.context) return false;
86
+ if (f.customer !== undefined && run.customer !== f.customer) return false;
77
87
  const steps = (run.steps ?? []).map((s) => ({ ...s, ...factsOf(s) }));
78
88
  if (f.tool && !steps.some((s) => (s.tools ?? []).some((t) => t.toLowerCase().includes(f.tool!)))) return false;
79
89
  if (f.toolError !== undefined && steps.some((s) => (s.toolErrors ?? 0) > 0) !== f.toolError) return false;
package/src/storage.ts CHANGED
@@ -172,6 +172,159 @@ export function assertFilePath(rel: string): string {
172
172
  return norm;
173
173
  }
174
174
 
175
+ // ---------- foldrun's own records: a run's held inputs (FOL-163) ----------
176
+ //
177
+ // A run with `inputs` reads the files as they were when it was made, not as
178
+ // they are when its step starts: an overwrite or a delete in between changes
179
+ // nothing it reads. Each input is held by a record of foldrun's own under
180
+ // `.foldrun/run-inputs/<runId>/<path>`, naming the same blob — zero copies,
181
+ // and the collector (collectLocked) keeps a blob while any record names it,
182
+ // so nothing new had to learn about holds. Those records are never listed,
183
+ // mirrored into a sandbox or harvested, and no person's write, upload or
184
+ // delete may name the prefix; they go when the run's record does.
185
+
186
+ const RESERVED = ".foldrun";
187
+ export const RUN_INPUTS_PREFIX = `${RESERVED}/run-inputs/`;
188
+
189
+ /** A path under foldrun's own prefix. */
190
+ export function isReservedPath(rel: string): boolean {
191
+ return rel === RESERVED || rel.startsWith(`${RESERVED}/`);
192
+ }
193
+
194
+ /** Refuse foldrun's own prefix on a person's or a run's write. */
195
+ export function assertNotReserved(norm: string): string {
196
+ if (isReservedPath(norm)) throw new Error(`${norm}: storage/${RESERVED}/ is foldrun's own — choose another path`);
197
+ return norm;
198
+ }
199
+
200
+ /** One input as the run holds it: the storage path it was given and the
201
+ * blob it named then. */
202
+ export interface RunInputFile {
203
+ path: string;
204
+ sha: string;
205
+ size: number;
206
+ mime: string;
207
+ }
208
+
209
+ /** An input path that names no stored file (or a reserved one). */
210
+ export class MissingInput extends Error {
211
+ readonly path: string;
212
+ constructor(path: string) {
213
+ super(`no stored file ${path}`);
214
+ this.path = path;
215
+ }
216
+ }
217
+
218
+ const heldPath = (runId: string, rel: string) => `${RUN_INPUTS_PREFIX}${runId}/${rel}`;
219
+
220
+ /**
221
+ * Resolve `paths` (storage-relative, as GET …/storage lists them) to the
222
+ * blob each names now. Throws MissingInput for a path with no record.
223
+ * Returns them in the order given, duplicates dropped. Holds nothing:
224
+ * holdRunInputs does, once the run exists.
225
+ */
226
+ export function resolveRunInputs(tenant: string, workspace: string, paths: string[]): RunInputFile[] {
227
+ const files = readIndex(tenant, workspace).files;
228
+ const out: RunInputFile[] = [];
229
+ const seen = new Set<string>();
230
+ for (const p of paths) {
231
+ let norm: string;
232
+ try {
233
+ norm = assertFilePath(p);
234
+ } catch {
235
+ throw new MissingInput(p);
236
+ }
237
+ if (isReservedPath(norm)) throw new MissingInput(norm);
238
+ if (seen.has(norm)) continue;
239
+ seen.add(norm);
240
+ const rec = files.find((f) => f.path === norm);
241
+ if (!rec) throw new MissingInput(norm);
242
+ out.push({ path: norm, sha: rec.sha, size: rec.size, mime: rec.mime });
243
+ }
244
+ return out;
245
+ }
246
+
247
+ /**
248
+ * Hold `inputs` for `runId`, under the workspace's lock: from here no
249
+ * overwrite or delete can take the bytes the run will read. Each blob must
250
+ * still be named by some record — the file itself, or another run's hold (a
251
+ * re-run reads what its source read). Throws MissingInput for one that is
252
+ * gone; nothing is held then.
253
+ */
254
+ export async function holdRunInputs(tenant: string, workspace: string, runId: string, inputs: RunInputFile[]): Promise<void> {
255
+ assertSafeName(runId, "run id");
256
+ await withFileStoreLock(tenant, workspace, async () => {
257
+ const shas = new Set(readIndex(tenant, workspace).files.map((f) => f.sha));
258
+ for (const i of inputs) if (!shas.has(i.sha)) throw new MissingInput(i.path);
259
+ holdLocked(tenant, workspace, runId, inputs);
260
+ });
261
+ }
262
+
263
+ function holdLocked(tenant: string, workspace: string, runId: string, inputs: RunInputFile[]) {
264
+ const now = new Date().toISOString();
265
+ for (const i of inputs) {
266
+ // Re-read each time: the file store rewrites the whole index per put.
267
+ indexPut(tenant, workspace, readIndex(tenant, workspace), { path: heldPath(runId, i.path), sha: i.sha, size: i.size, mime: i.mime, updatedAt: now, by: `run:${runId}:inputs` });
268
+ }
269
+ }
270
+
271
+ /** Let go of a run's held inputs; a blob nothing else names is collected. */
272
+ export async function releaseRunInputs(tenant: string, workspace: string, runId: string): Promise<number> {
273
+ if (!fileStoreEnabled()) return 0;
274
+ const prefix = `${RUN_INPUTS_PREFIX}${runId}/`;
275
+ return withFileStoreLock(tenant, workspace, async () => {
276
+ const held = readIndex(tenant, workspace).files.filter((f) => f.path.startsWith(prefix));
277
+ for (const f of held) indexRemove(tenant, workspace, readIndex(tenant, workspace), f.path);
278
+ for (const sha of new Set(held.map((f) => f.sha))) await collectLocked(tenant, workspace, sha);
279
+ return held.length;
280
+ });
281
+ }
282
+
283
+ /** Let go of the holds of runs that no longer exist — what a crash between
284
+ * a run's delete and its release left. `alive` says whether a run is there.
285
+ * Returns how many runs' holds went. */
286
+ export async function sweepHeldInputs(tenant: string, workspace: string, alive: (runId: string) => boolean): Promise<number> {
287
+ if (!fileStoreEnabled()) return 0;
288
+ const runs = new Set(
289
+ readIndex(tenant, workspace)
290
+ .files.filter((f) => f.path.startsWith(RUN_INPUTS_PREFIX))
291
+ .map((f) => f.path.slice(RUN_INPUTS_PREFIX.length).split("/")[0]!)
292
+ .filter(Boolean),
293
+ );
294
+ let gone = 0;
295
+ for (const runId of runs) {
296
+ if (alive(runId)) continue;
297
+ if ((await releaseRunInputs(tenant, workspace, runId)) > 0) gone++;
298
+ }
299
+ return gone;
300
+ }
301
+
302
+ /**
303
+ * Write a run's held inputs into `intoDir` (made fresh: whatever was there
304
+ * is removed first, so a folder of the same name never mixes in), each at
305
+ * its storage path. Reads the blob each input named when the run was made,
306
+ * never the path again. Throws when one is gone.
307
+ */
308
+ export async function stageRunInputs(tenant: string, workspace: string, runId: string, inputs: RunInputFile[], intoDir: string): Promise<{ files: number; bytes: number }> {
309
+ fs.rmSync(intoDir, { recursive: true, force: true });
310
+ fs.mkdirSync(intoDir, { recursive: true });
311
+ const held = new Set(readIndex(tenant, workspace).files.filter((f) => f.path.startsWith(`${RUN_INPUTS_PREFIX}${runId}/`)).map((f) => f.sha));
312
+ const driver = driverFor(tenant, workspace);
313
+ let bytes = 0;
314
+ for (const i of inputs) {
315
+ const norm = assertFilePath(i.path);
316
+ if (!held.has(i.sha)) throw new MissingInput(norm);
317
+ const body = await driver.get(blobKey(tenant, workspace, i.sha));
318
+ if (sha256(body) !== i.sha) throw new Error(`input ${norm}: the stored bytes do not match what the run was given`);
319
+ const abs = path.join(intoDir, norm);
320
+ if (!abs.startsWith(intoDir + path.sep)) throw new MissingInput(norm);
321
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
322
+ fs.writeFileSync(abs, body, { flag: "wx" });
323
+ bytes += body.length;
324
+ }
325
+ return { files: inputs.length, bytes };
326
+ }
327
+
175
328
  // ---------- mime ----------
176
329
 
177
330
  const MIME: Record<string, string> = {
@@ -248,7 +401,8 @@ function indexRemove(tenant: string, workspace: string, index: Index, rel: strin
248
401
  }
249
402
 
250
403
  export function listStorage(tenant: string, workspace: string): FileRecord[] {
251
- return readIndex(tenant, workspace).files.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
404
+ // foldrun's own records (a run's held inputs) are not the workspace's files.
405
+ return readIndex(tenant, workspace).files.filter((f) => !isReservedPath(f.path)).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
252
406
  }
253
407
 
254
408
  export function getFile(tenant: string, workspace: string, rel: string): FileRecord | null {
@@ -910,7 +1064,7 @@ async function putFileQuietly(
910
1064
  body: Buffer,
911
1065
  by: string,
912
1066
  ): Promise<FileRecord> {
913
- const norm = assertFilePath(rel);
1067
+ const norm = assertNotReserved(assertFilePath(rel));
914
1068
  if (body.length > maxBytes()) {
915
1069
  throw new Error(`${norm} is ${Math.round(body.length / 1e6)}MB — the limit is ${maxBytes() / 1e6}MB`);
916
1070
  }
@@ -979,7 +1133,7 @@ export async function registerUpload(
979
1133
  _claimed: number,
980
1134
  by: string,
981
1135
  ): Promise<FileRecord> {
982
- const norm = assertFilePath(rel);
1136
+ const norm = assertNotReserved(assertFilePath(rel));
983
1137
  if (!/^[0-9a-f]{64}$/.test(sha)) throw new Error("expected a sha256");
984
1138
  requireWorkspace(tenant, workspace);
985
1139
  const driver = driverFor(tenant, workspace);
@@ -1066,7 +1220,7 @@ export async function openFile(
1066
1220
  }
1067
1221
 
1068
1222
  export async function deleteFile(tenant: string, workspace: string, rel: string): Promise<boolean> {
1069
- const norm = assertFilePath(rel);
1223
+ const norm = assertNotReserved(assertFilePath(rel));
1070
1224
  return withFileStoreLock(tenant, workspace, async () => {
1071
1225
  const index = readIndex(tenant, workspace);
1072
1226
  const record = index.files.find((f) => f.path === norm);
@@ -1141,7 +1295,7 @@ export async function uploadUrl(
1141
1295
  sha: string,
1142
1296
  size?: number,
1143
1297
  ): Promise<string | null> {
1144
- const norm = assertFilePath(rel);
1298
+ const norm = assertNotReserved(assertFilePath(rel));
1145
1299
  if (!/^[0-9a-f]{64}$/.test(sha)) throw new Error("expected a sha256");
1146
1300
  requireWorkspace(tenant, workspace);
1147
1301
  // The limits, before a byte moves, and the length signed into the URL so
@@ -1269,6 +1423,8 @@ export async function materializeFiles(tenant: string, workspace: string): Promi
1269
1423
  const brought: string[] = [];
1270
1424
 
1271
1425
  for (const record of readIndex(tenant, workspace).files) {
1426
+ // A run's held inputs are staged into its own step, never mirrored.
1427
+ if (isReservedPath(record.path)) continue;
1272
1428
  const target = path.join(root, record.path);
1273
1429
  try {
1274
1430
  const stat = fs.statSync(target);
@@ -1303,7 +1459,7 @@ export async function materializeFiles(tenant: string, workspace: string): Promi
1303
1459
  * files it was handed. */
1304
1460
  export function storageBaseline(tenant: string, workspace: string): Record<string, string> {
1305
1461
  if (!fileStoreEnabled()) return {};
1306
- return Object.fromEntries(readIndex(tenant, workspace).files.map((f) => [f.path, f.sha]));
1462
+ return Object.fromEntries(readIndex(tenant, workspace).files.filter((f) => !isReservedPath(f.path)).map((f) => [f.path, f.sha]));
1307
1463
  }
1308
1464
 
1309
1465
  /**