@foldrun/core 18.5.0 → 19.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,88 @@
1
+ // An end customer's id (FOL-168, 11 Nov 2026): a partner — one foldrun
2
+ // account serving thousands of people of its own — names which of its own
3
+ // users a run or a gateway call is for. foldrun then limits and blocks by
4
+ // it, so one bad end customer is held alone and the partner's account
5
+ // carries on; and the model provider is told the same, as its end-user id,
6
+ // so a provider acts on that one user, not the platform's key.
7
+ //
8
+ // Opaque by contract: the partner maps it to a person, foldrun never does,
9
+ // and it must not be personal data (an email, a name). It is not an access
10
+ // boundary either: anyone who may start runs in the account may name any
11
+ // customer.
12
+ //
13
+ // To a provider it goes hashed with the account — `fr-` and 32 hex — so two
14
+ // partners' `user-1` are never one identity there, and the partner's own id
15
+ // never leaves foldrun.
16
+
17
+ import crypto from "node:crypto";
18
+ import { listRunSummaries, listWorkspaces } from "./store.ts";
19
+ import { records } from "./records.ts";
20
+
21
+ /** A customer id as a partner writes it: printable, no spaces, 1–128. */
22
+ export const CUSTOMER_ID = /^[A-Za-z0-9._:@-]{1,128}$/;
23
+
24
+ /** Null when the id is fine; otherwise why not. */
25
+ export function customerProblem(id: unknown): string | null {
26
+ if (typeof id !== "string") return "customer must be a string";
27
+ if (!CUSTOMER_ID.test(id)) return "customer is 1–128 characters: letters, digits and . _ : @ - (an opaque id, never personal data)";
28
+ return null;
29
+ }
30
+
31
+ /** What a model provider is told for this account's customer: its end-user
32
+ * id (Anthropic metadata.user_id; OpenAI user / safety_identifier). */
33
+ export function providerUserId(tenant: string, customer: string): string {
34
+ return `fr-${crypto.createHash("sha256").update(`${tenant}\u0000${customer}`).digest("hex").slice(0, 32)}`;
35
+ }
36
+
37
+ /** A short, stable key for counters and logs — never the id itself. */
38
+ export function customerKey(tenant: string, customer: string): string {
39
+ return crypto.createHash("sha256").update(`customer\u0000${tenant}\u0000${customer}`).digest("hex").slice(0, 24);
40
+ }
41
+
42
+ /**
43
+ * Set the provider's end-user id on a model request body, in whichever shape
44
+ * it is: Anthropic Messages (`metadata.user_id`, other metadata kept),
45
+ * OpenAI Responses (`safety_identifier`), OpenAI Chat Completions (`user`).
46
+ * Returns the body unchanged when it is not JSON or not one of those.
47
+ */
48
+ export function withProviderUser(body: Buffer, userId: string, shape: "anthropic" | "responses" | "chat"): Buffer {
49
+ let parsed: Record<string, unknown>;
50
+ try {
51
+ parsed = JSON.parse(body.toString("utf8")) as Record<string, unknown>;
52
+ } catch {
53
+ return body;
54
+ }
55
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return body;
56
+ if (shape === "anthropic") {
57
+ const meta = parsed.metadata && typeof parsed.metadata === "object" && !Array.isArray(parsed.metadata) ? (parsed.metadata as Record<string, unknown>) : {};
58
+ parsed.metadata = { ...meta, user_id: userId };
59
+ } else if (shape === "responses") {
60
+ parsed.safety_identifier = userId;
61
+ } else {
62
+ parsed.user = userId;
63
+ }
64
+ return Buffer.from(JSON.stringify(parsed), "utf8");
65
+ }
66
+
67
+ const OPEN = new Set(["queued", "running", "awaiting-approval"]);
68
+
69
+ /**
70
+ * How many runs of this end customer are open — queued, running or parked
71
+ * at a gate — across every workspace of the account. Read from the run
72
+ * records themselves, so a wiped cache never hands out more room than the
73
+ * customer has. What the platform's open-runs limit counts under its lock.
74
+ */
75
+ export function openRunsOfCustomer(tenant: string, customer: string): number {
76
+ const workspaces = listWorkspaces(tenant).map((w) => w.name);
77
+ const port = records();
78
+ // The database's count covers every workspace whose records live there;
79
+ // a workspace still on files (its import pending — records() answers
80
+ // null for it) is counted from its own summaries and added (Codex review).
81
+ const counted = port?.openRunsOfCustomer ? port.openRunsOfCustomer(tenant, customer) : null;
82
+ let n = counted ?? 0;
83
+ for (const ws of workspaces) {
84
+ if (counted !== null && records(tenant, ws)) continue;
85
+ for (const s of listRunSummaries(tenant, ws)) if (s.customer === customer && OPEN.has(s.status)) n++;
86
+ }
87
+ return n;
88
+ }
package/src/egress.ts CHANGED
@@ -118,6 +118,10 @@ export interface EgressGrant {
118
118
  * that has to put a rate-limit reset into words — and a reset time is
119
119
  * only useful in the calendar the step works to. See refusal.ts. */
120
120
  timezone?: string;
121
+ /** FOL-168: the end customer the run is for — written by the worker from
122
+ * the run record, never by the sandbox. The proxy refuses a blocked one's
123
+ * model calls and tells the provider its hashed end-user id. */
124
+ customer?: string;
121
125
  /** Which sites the step may reach through the proxy's forward door
122
126
  * (network.ts). Absent on a grant from a runner that predates it: the
123
127
  * forward door then allows only the hosts the secrets were granted to. */
package/src/platform.ts CHANGED
@@ -173,6 +173,11 @@ export interface PlatformHooks {
173
173
  * snapshot on any executor that cannot fails before anything starts.
174
174
  * Default: none can. */
175
175
  holdsSnapshot?(isolation: string): boolean;
176
+ /** Can this executor stage a run's inputs (RunInContainerArgs.inputs: the
177
+ * files at agents/<name>/inputs/, never copied back)? The docker executor
178
+ * can; a run with inputs on one that cannot fails before anything starts
179
+ * (FOL-163). Default: none can. */
180
+ holdsInputs?(isolation: string): boolean;
176
181
  /**
177
182
  * Does this isolation mode wall a step whose `network:` is restricted and
178
183
  * enforced to the egress proxy alone (a `filtered` pod)? True: such a
package/src/providers.ts CHANGED
@@ -59,6 +59,11 @@ export interface ProviderPreset {
59
59
  * to. Only set where the parameter is documented; an endpoint that does
60
60
  * not know it may refuse the request. */
61
61
  promptCacheKey?: boolean;
62
+ /** What the endpoint can be shown (FOL-163): unset is the format's
63
+ * default — images yes; PDFs on `responses`, not on `openai` (Chat
64
+ * Completions has no portable PDF part). Set `pdf: true` only where the
65
+ * endpoint is documented to take Chat's `file` part. */
66
+ media?: { images?: boolean; pdf?: boolean };
62
67
  /** One line a person should read before relying on it. */
63
68
  note?: string;
64
69
  /** A tool loop was driven through this endpoint from this runtime. */
package/src/records.ts CHANGED
@@ -64,6 +64,10 @@ export interface RecordsPort {
64
64
  * whole, newest first, at most `limit`. Optional: without it
65
65
  * conversation.ts filters the run summaries itself. */
66
66
  runsInContext?(tenant: string, workspace: string, key: string, before: string, test: boolean, limit: number): RunRecord[];
67
+ /** FOL-168: how many runs of this end customer are open (queued, running
68
+ * or parked at a gate) across every workspace of the account. Optional:
69
+ * without it customer.ts counts the run summaries itself. */
70
+ openRunsOfCustomer?(tenant: string, customer: string): number;
67
71
  /** When the row last changed, in epoch MICROseconds, or null when there is
68
72
  * none — what a poller compares instead of a file's mtime (two writes in one
69
73
  * millisecond still differ), and what runUpdatedMs divides by 1000 for the
@@ -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
@@ -127,6 +127,7 @@ import { resolveLanguage, languageName, type LanguageChoice } from "./language.t
127
127
  import { resolveRegion, deriveLocale, localeProse, regionName, type RegionChoice, type LocaleFacts } from "./locale.ts";
128
128
  import { trimChars } from "./paths.ts";
129
129
  import { earlierTurns, conversationBlock, type RunContext, type RunInput } from "./conversation.ts";
130
+ import { inputsNote, type RunInputFile } from "./run-inputs.ts";
130
131
  import { resolveClock, localDate, type ClockChoice } from "./clock.ts";
131
132
 
132
133
  export { localDate } from "./clock.ts";
@@ -2982,7 +2983,19 @@ async function runStep(
2982
2983
  // run was made. Only an executor that says it can hold one may run it —
2983
2984
  // in-process, the step would work in the real workspace folder, and no
2984
2985
  // copy-back stands between what it writes and the workspace (Codex).
2985
- 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
+ }
2986
2999
  if (snapshotId) {
2987
3000
  const able = isolatedRun() && isolation !== "container" && Boolean(platform.isolation[isolation!]) && platform.holdsSnapshot?.(isolation!) === true;
2988
3001
  if (!able) {
@@ -3010,7 +3023,7 @@ async function runStep(
3010
3023
  // before anything is copied in. Null where no proxy is configured
3011
3024
  // (the CLI, a compose install without FOLDRUN_EGRESS_URL), and then
3012
3025
  // everything below materialises exactly as it always did.
3013
- const grant: EgressGrant = { secrets: {}, timezone: clock.timezone };
3026
+ const grant: EgressGrant = { secrets: {}, timezone: clock.timezone, ...(runRecord?.customer ? { customer: runRecord.customer } : {}) };
3014
3027
  // A direct search API's key: granted to that API's host and no other,
3015
3028
  // exactly as an http tool's key is granted to its base URL's host. The
3016
3029
  // script sends the placeholder; the worker fills it on the way out.
@@ -3371,6 +3384,7 @@ async function runStep(
3371
3384
  const isolatedArgs = (modelEnv: Record<string, string | undefined>, keyName = MODEL_KEY_NAME) => ({
3372
3385
  workspaceRoot,
3373
3386
  ...(snapshotId ? { snapshot: { id: snapshotId } } : {}),
3387
+ ...(stepInputs && runId ? { inputs: { runId, files: stepInputs } } : {}),
3374
3388
  libraryRoot: libraryDir(tenant),
3375
3389
  galleryRoot: platform.galleryDir() ?? undefined,
3376
3390
  // Keys this step's dependency cache. Per-account by design — see
@@ -3381,7 +3395,7 @@ async function runStep(
3381
3395
  // Its file tools inside the sandbox get the same allowance (FOL-96).
3382
3396
  configWrites: step.approve === true && Boolean(step.approvedAt),
3383
3397
  // A snapshot step is told where its folder is, and what comes back.
3384
- prompt: snapshotId ? `${prompt}\n\n${SNAPSHOT_NOTE}` : prompt,
3398
+ prompt: `${prompt}${snapshotId ? `\n\n${SNAPSHOT_NOTE}` : ""}${stepInputs ? `\n\n${inputsNote(stepInputs)}` : ""}`,
3385
3399
  model,
3386
3400
  effort,
3387
3401
  systemPrompt,
@@ -4593,6 +4607,12 @@ export function createFlowRun(
4593
4607
  * asked — written with the record, before any worker can see it. The
4594
4608
  * run's first step (the one its task reaches) reads the earlier turns. */
4595
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,
4596
4616
  ): RunRecord {
4597
4617
  let flowMaxOut: number | undefined;
4598
4618
  try {
@@ -4661,6 +4681,11 @@ export function createFlowRun(
4661
4681
  if (conversation.input) run.input = conversation.input;
4662
4682
  if (run.steps[0]) run.steps[0].conversationTurn = true;
4663
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;
4664
4689
  writeRun(tenant, workspace, run);
4665
4690
 
4666
4691
  // Start every run from an empty outputs/ for each agent it will touch.
@@ -6152,8 +6177,10 @@ function driveRunInner(
6152
6177
  // medium-desk).
6153
6178
  output: step.output,
6154
6179
  ...(step.verify ? { verify: step.verify } : {}),
6155
- // Taking over the step the run's task reached: the conversation too.
6180
+ // Taking over the step the run's task reached: the conversation
6181
+ // and the inputs too.
6156
6182
  ...(step.conversationTurn ? { conversationTurn: true } : {}),
6183
+ ...(step.inputsTurn ? { inputsTurn: true } : {}),
6157
6184
  attempts: 0,
6158
6185
  status: "pending",
6159
6186
  events: [],
@@ -18,6 +18,8 @@ export interface RunFilter {
18
18
  minSecs?: number;
19
19
  /** The run is a turn of this conversation: its `context` id, exactly (FOL-162). */
20
20
  context?: string;
21
+ /** The run is for this end customer, exactly (FOL-168). */
22
+ customer?: string;
21
23
  }
22
24
 
23
25
  /** The query parameters a filter comes from: tool, tool_error, agent,
@@ -36,6 +38,8 @@ export function parseRunFilter(q: { get(name: string): string | null }): { filte
36
38
  if (model) filter.model = model.toLowerCase();
37
39
  const context = q.get("context");
38
40
  if (context) filter.context = context;
41
+ const customer = q.get("customer");
42
+ if (customer) filter.customer = customer;
39
43
  for (const [k, field] of [["min_tokens", "minTokens"], ["min_secs", "minSecs"]] as const) {
40
44
  const v = text(k);
41
45
  if (v === undefined) continue;
@@ -61,7 +65,7 @@ type FilterableStep = {
61
65
  startedAt?: string;
62
66
  finishedAt?: string;
63
67
  };
64
- type FilterableRun = { startedAt: string; finishedAt?: string | null; context?: { id: string }; steps: FilterableStep[] };
68
+ type FilterableRun = { startedAt: string; finishedAt?: string | null; context?: { id: string }; customer?: string; steps: FilterableStep[] };
65
69
 
66
70
  /** The index's facts, or worked out from a whole record's events (Codex
67
71
  * review: the workspace runs page reads whole records). */
@@ -79,6 +83,7 @@ function factsOf(s: FilterableStep): { tools: string[]; toolErrors: number } {
79
83
 
80
84
  export function matchesRunFilter(run: FilterableRun, f: RunFilter, now = Date.now()): boolean {
81
85
  if (f.context !== undefined && run.context?.id !== f.context) return false;
86
+ if (f.customer !== undefined && run.customer !== f.customer) return false;
82
87
  const steps = (run.steps ?? []).map((s) => ({ ...s, ...factsOf(s) }));
83
88
  if (f.tool && !steps.some((s) => (s.tools ?? []).some((t) => t.toLowerCase().includes(f.tool!)))) return false;
84
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
  /**