@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,23 @@
1
+ /** A customer id as a partner writes it: printable, no spaces, 1–128. */
2
+ export declare const CUSTOMER_ID: RegExp;
3
+ /** Null when the id is fine; otherwise why not. */
4
+ export declare function customerProblem(id: unknown): string | null;
5
+ /** What a model provider is told for this account's customer: its end-user
6
+ * id (Anthropic metadata.user_id; OpenAI user / safety_identifier). */
7
+ export declare function providerUserId(tenant: string, customer: string): string;
8
+ /** A short, stable key for counters and logs — never the id itself. */
9
+ export declare function customerKey(tenant: string, customer: string): string;
10
+ /**
11
+ * Set the provider's end-user id on a model request body, in whichever shape
12
+ * it is: Anthropic Messages (`metadata.user_id`, other metadata kept),
13
+ * OpenAI Responses (`safety_identifier`), OpenAI Chat Completions (`user`).
14
+ * Returns the body unchanged when it is not JSON or not one of those.
15
+ */
16
+ export declare function withProviderUser(body: Buffer, userId: string, shape: "anthropic" | "responses" | "chat"): Buffer;
17
+ /**
18
+ * How many runs of this end customer are open — queued, running or parked
19
+ * at a gate — across every workspace of the account. Read from the run
20
+ * records themselves, so a wiped cache never hands out more room than the
21
+ * customer has. What the platform's open-runs limit counts under its lock.
22
+ */
23
+ export declare function openRunsOfCustomer(tenant: string, customer: string): number;
@@ -0,0 +1,89 @@
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
+ import crypto from "node:crypto";
17
+ import { listRunSummaries, listWorkspaces } from "./store.js";
18
+ import { records } from "./records.js";
19
+ /** A customer id as a partner writes it: printable, no spaces, 1–128. */
20
+ export const CUSTOMER_ID = /^[A-Za-z0-9._:@-]{1,128}$/;
21
+ /** Null when the id is fine; otherwise why not. */
22
+ export function customerProblem(id) {
23
+ if (typeof id !== "string")
24
+ return "customer must be a string";
25
+ if (!CUSTOMER_ID.test(id))
26
+ return "customer is 1–128 characters: letters, digits and . _ : @ - (an opaque id, never personal data)";
27
+ return null;
28
+ }
29
+ /** What a model provider is told for this account's customer: its end-user
30
+ * id (Anthropic metadata.user_id; OpenAI user / safety_identifier). */
31
+ export function providerUserId(tenant, customer) {
32
+ return `fr-${crypto.createHash("sha256").update(`${tenant}\u0000${customer}`).digest("hex").slice(0, 32)}`;
33
+ }
34
+ /** A short, stable key for counters and logs — never the id itself. */
35
+ export function customerKey(tenant, customer) {
36
+ return crypto.createHash("sha256").update(`customer\u0000${tenant}\u0000${customer}`).digest("hex").slice(0, 24);
37
+ }
38
+ /**
39
+ * Set the provider's end-user id on a model request body, in whichever shape
40
+ * it is: Anthropic Messages (`metadata.user_id`, other metadata kept),
41
+ * OpenAI Responses (`safety_identifier`), OpenAI Chat Completions (`user`).
42
+ * Returns the body unchanged when it is not JSON or not one of those.
43
+ */
44
+ export function withProviderUser(body, userId, shape) {
45
+ let parsed;
46
+ try {
47
+ parsed = JSON.parse(body.toString("utf8"));
48
+ }
49
+ catch {
50
+ return body;
51
+ }
52
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
53
+ return body;
54
+ if (shape === "anthropic") {
55
+ const meta = parsed.metadata && typeof parsed.metadata === "object" && !Array.isArray(parsed.metadata) ? parsed.metadata : {};
56
+ parsed.metadata = { ...meta, user_id: userId };
57
+ }
58
+ else if (shape === "responses") {
59
+ parsed.safety_identifier = userId;
60
+ }
61
+ else {
62
+ parsed.user = userId;
63
+ }
64
+ return Buffer.from(JSON.stringify(parsed), "utf8");
65
+ }
66
+ const OPEN = new Set(["queued", "running", "awaiting-approval"]);
67
+ /**
68
+ * How many runs of this end customer are open — queued, running or parked
69
+ * at a gate — across every workspace of the account. Read from the run
70
+ * records themselves, so a wiped cache never hands out more room than the
71
+ * customer has. What the platform's open-runs limit counts under its lock.
72
+ */
73
+ export function openRunsOfCustomer(tenant, customer) {
74
+ const workspaces = listWorkspaces(tenant).map((w) => w.name);
75
+ const port = records();
76
+ // The database's count covers every workspace whose records live there;
77
+ // a workspace still on files (its import pending — records() answers
78
+ // null for it) is counted from its own summaries and added (Codex review).
79
+ const counted = port?.openRunsOfCustomer ? port.openRunsOfCustomer(tenant, customer) : null;
80
+ let n = counted ?? 0;
81
+ for (const ws of workspaces) {
82
+ if (counted !== null && records(tenant, ws))
83
+ continue;
84
+ for (const s of listRunSummaries(tenant, ws))
85
+ if (s.customer === customer && OPEN.has(s.status))
86
+ n++;
87
+ }
88
+ return n;
89
+ }
@@ -51,6 +51,10 @@ export interface EgressGrant {
51
51
  * that has to put a rate-limit reset into words — and a reset time is
52
52
  * only useful in the calendar the step works to. See refusal.ts. */
53
53
  timezone?: string;
54
+ /** FOL-168: the end customer the run is for — written by the worker from
55
+ * the run record, never by the sandbox. The proxy refuses a blocked one's
56
+ * model calls and tells the provider its hashed end-user id. */
57
+ customer?: string;
54
58
  /** Which sites the step may reach through the proxy's forward door
55
59
  * (network.ts). Absent on a grant from a runner that predates it: the
56
60
  * forward door then allows only the hosts the secrets were granted to. */
@@ -168,6 +168,11 @@ export interface PlatformHooks {
168
168
  * snapshot on any executor that cannot fails before anything starts.
169
169
  * Default: none can. */
170
170
  holdsSnapshot?(isolation: string): boolean;
171
+ /** Can this executor stage a run's inputs (RunInContainerArgs.inputs: the
172
+ * files at agents/<name>/inputs/, never copied back)? The docker executor
173
+ * can; a run with inputs on one that cannot fails before anything starts
174
+ * (FOL-163). Default: none can. */
175
+ holdsInputs?(isolation: string): boolean;
171
176
  /**
172
177
  * Does this isolation mode wall a step whose `network:` is restricted and
173
178
  * enforced to the egress proxy alone (a `filtered` pod)? True: such a
@@ -25,6 +25,14 @@ export interface ProviderPreset {
25
25
  * to. Only set where the parameter is documented; an endpoint that does
26
26
  * not know it may refuse the request. */
27
27
  promptCacheKey?: boolean;
28
+ /** What the endpoint can be shown (FOL-163): unset is the format's
29
+ * default — images yes; PDFs on `responses`, not on `openai` (Chat
30
+ * Completions has no portable PDF part). Set `pdf: true` only where the
31
+ * endpoint is documented to take Chat's `file` part. */
32
+ media?: {
33
+ images?: boolean;
34
+ pdf?: boolean;
35
+ };
28
36
  /** One line a person should read before relying on it. */
29
37
  note?: string;
30
38
  /** A tool loop was driven through this endpoint from this runtime. */
@@ -44,6 +44,10 @@ export interface RecordsPort {
44
44
  * whole, newest first, at most `limit`. Optional: without it
45
45
  * conversation.ts filters the run summaries itself. */
46
46
  runsInContext?(tenant: string, workspace: string, key: string, before: string, test: boolean, limit: number): RunRecord[];
47
+ /** FOL-168: how many runs of this end customer are open (queued, running
48
+ * or parked at a gate) across every workspace of the account. Optional:
49
+ * without it customer.ts counts the run summaries itself. */
50
+ openRunsOfCustomer?(tenant: string, customer: string): number;
47
51
  /** When the row last changed, in epoch MICROseconds, or null when there is
48
52
  * none — what a poller compares instead of a file's mtime (two writes in one
49
53
  * millisecond still differ), and what runUpdatedMs divides by 1000 for the
@@ -19,6 +19,7 @@ import type { SearchRoot, RunDigest } from "./context-tools.ts";
19
19
  import type { TranslatorSpec } from "./translator.ts";
20
20
  import { type BrowserPodOutcome } from "./browser-pod.ts";
21
21
  import type { RemoteSpec } from "./a2a-remotes.ts";
22
+ import { type RunInputFile } from "./storage.ts";
22
23
  /** What crosses the boundary. Everything in here is values — pre-resolved
23
24
  * secrets in headers, assembled prompt, serializable MCP configs. */
24
25
  export interface ContainerStepInput {
@@ -279,6 +280,10 @@ export declare const APPLY_MTIMES_JS: string;
279
280
  */
280
281
  export declare function mergeAppends(was: Buffer | string | null, host: Buffer, next: Buffer): Buffer | null;
281
282
  export interface ApplyOptions {
283
+ /** Never take back what is under this workspace-relative folder (with its
284
+ * trailing `/`) — a step's staged inputs (FOL-163): whatever it does in
285
+ * there stays in the sandbox. Checked before anything is read. */
286
+ drop?: string;
282
287
  /** Take back only what is under this workspace-relative folder (with its
283
288
  * trailing `/`) — a snapshot run's outputs (Part B3): the folder it was
284
289
  * given, and anything it copied anywhere else, never reach the workspace. */
@@ -588,6 +593,12 @@ export interface RunInContainerArgs {
588
593
  snapshot?: {
589
594
  id: string;
590
595
  };
596
+ /** FOL-163: the run's inputs, for the step its task reaches — staged at
597
+ * <agentRel>/inputs/ after the workspace copy, never copied back. */
598
+ inputs?: {
599
+ runId: string;
600
+ files: RunInputFile[];
601
+ };
591
602
  /** A person approved this step before it ran: configuration and code it
592
603
  * changed are kept, not refused (copy-back.ts, FOL-96). */
593
604
  configWrites?: boolean;
@@ -35,6 +35,8 @@ import { anyMemoryMi, quantityMi } from "./resources.js";
35
35
  import { STARTUP_PHASES } from "./startup.js";
36
36
  import { isOperatorEvent } from "./operator.js";
37
37
  import { parseBrowserPod } from "./browser-pod.js";
38
+ import { stageRunInputs } from "./storage.js";
39
+ import { INPUTS_DIR, stagedLine } from "./run-inputs.js";
38
40
  /** The start-up phases and what each marks — startup.ts, where every
39
41
  * surface that shows them reads them from (FOL-74). */
40
42
  export { STARTUP_PHASES };
@@ -368,12 +370,16 @@ export function applyContainerChanges(hostWs, containerWs, baseline, note, diver
368
370
  const posix = rel.replaceAll("\\", "/");
369
371
  if (entry.isDirectory()) {
370
372
  const d = posix + "/";
373
+ if (opts.drop && d.startsWith(opts.drop))
374
+ continue;
371
375
  if (opts.keepOnly && !(d.startsWith(opts.keepOnly) || opts.keepOnly.startsWith(d)))
372
376
  continue;
373
377
  if (allowedBack(rel + "/"))
374
378
  walk(abs);
375
379
  continue;
376
380
  }
381
+ if (opts.drop && (posix.startsWith(opts.drop) || `${posix}/` === opts.drop))
382
+ continue;
377
383
  if (opts.keepOnly && !posix.startsWith(opts.keepOnly))
378
384
  continue;
379
385
  if (!allowedBack(rel))
@@ -1837,6 +1843,15 @@ export async function runStepInContainer(args) {
1837
1843
  if (laid.length)
1838
1844
  args.emit("info", `test: this step sees ${laid.length} file${laid.length === 1 ? "" : "s"} earlier steps of this run wrote`);
1839
1845
  }
1846
+ // The run's inputs (FOL-163), at <agentRel>/inputs/ — after the copy and
1847
+ // the test overlay, so the copy is their baseline too and a folder of
1848
+ // that name in the workspace never mixes in.
1849
+ if (args.inputs?.files.length) {
1850
+ if (!args.tenant)
1851
+ throw new Error("a step with inputs needs its account");
1852
+ const staged = await stageRunInputs(args.tenant, path.basename(args.workspaceRoot), args.inputs.runId, args.inputs.files, path.join(wsIn, args.input.agentRel, INPUTS_DIR));
1853
+ args.emit("info", stagedLine(staged.files, staged.bytes));
1854
+ }
1840
1855
  const libIn = path.join(staging, "library");
1841
1856
  if (args.galleryRoot && fs.existsSync(args.galleryRoot))
1842
1857
  fs.cpSync(args.galleryRoot, libIn, { recursive: true });
@@ -2006,6 +2021,8 @@ export async function runStepInContainer(args) {
2006
2021
  allowConfig: args.configWrites === true,
2007
2022
  onKept: (r) => kept.push(r),
2008
2023
  revision: args.tenant ? { tenant: args.tenant, runId: args.runId, step: containerId, base: pinned?.base ?? null } : undefined,
2024
+ // Staged inputs stay in the sandbox, whatever the step did there (FOL-163).
2025
+ ...(args.inputs?.files.length ? { drop: `${args.input.agentRel}/${INPUTS_DIR}/` } : {}),
2009
2026
  });
2010
2027
  if (refused.length)
2011
2028
  args.emit("info", refusedLine(refused));
@@ -0,0 +1,18 @@
1
+ import type { RunInputFile } from "./storage.ts";
2
+ export type { RunInputFile };
3
+ /** foldrun's limits on what one run may be handed — not a model's. */
4
+ export declare const INPUT_LIMITS: {
5
+ readonly files: 20;
6
+ /** All of them together: 100 MiB. */
7
+ readonly totalBytes: number;
8
+ };
9
+ /** The folder, under the agent's working directory. */
10
+ export declare const INPUTS_DIR = "inputs";
11
+ /** Null when `paths` is a list the run routes may take; otherwise why not. */
12
+ export declare function inputsProblem(paths: unknown): string | null;
13
+ /** Null when the resolved files fit foldrun's limits; otherwise why not. */
14
+ export declare function inputsSizeProblem(files: RunInputFile[]): string | null;
15
+ /** What the step is told, after its instruction. */
16
+ export declare function inputsNote(files: RunInputFile[]): string;
17
+ /** The trail's line once they are staged. */
18
+ export declare function stagedLine(files: number, bytes: number): string;
@@ -0,0 +1,53 @@
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
+ /** foldrun's limits on what one run may be handed — not a model's. */
18
+ export const INPUT_LIMITS = {
19
+ files: 20,
20
+ /** All of them together: 100 MiB. */
21
+ totalBytes: 100 * 1024 * 1024,
22
+ };
23
+ /** The folder, under the agent's working directory. */
24
+ export const INPUTS_DIR = "inputs";
25
+ /** Null when `paths` is a list the run routes may take; otherwise why not. */
26
+ export function inputsProblem(paths) {
27
+ if (!Array.isArray(paths))
28
+ return "inputs is a list of storage paths";
29
+ if (paths.some((p) => typeof p !== "string" || !p.trim()))
30
+ return "inputs is a list of storage paths (strings)";
31
+ if (new Set(paths).size > INPUT_LIMITS.files)
32
+ return `at most ${INPUT_LIMITS.files} inputs on one run`;
33
+ return null;
34
+ }
35
+ /** Null when the resolved files fit foldrun's limits; otherwise why not. */
36
+ export function inputsSizeProblem(files) {
37
+ const total = files.reduce((n, f) => n + f.size, 0);
38
+ if (total > INPUT_LIMITS.totalBytes)
39
+ return `the inputs come to ${(total / 1048576).toFixed(1)} MiB — at most ${INPUT_LIMITS.totalBytes / 1048576} MiB on one run`;
40
+ return null;
41
+ }
42
+ const human = (n) => (n >= 1048576 ? `${(n / 1048576).toFixed(1)} MiB` : n >= 1024 ? `${Math.round(n / 1024)} KiB` : `${n} B`);
43
+ /** What the step is told, after its instruction. */
44
+ export function inputsNote(files) {
45
+ const lines = files.map((f) => `- ${INPUTS_DIR}/${f.path} (${f.mime}, ${human(f.size)})`);
46
+ return (`<inputs>\nThis run was handed ${files.length} file${files.length === 1 ? "" : "s"}, in ${INPUTS_DIR}/ inside your working directory:\n${lines.join("\n")}\n` +
47
+ "Read them with the Read tool. Supported images and PDFs are shown to you as they are; when a model cannot be shown a file, the tool result says so. " +
48
+ `The files stay available to scripts. Anything you write in ${INPUTS_DIR}/ is not kept — put results in outputs/.\n</inputs>`);
49
+ }
50
+ /** The trail's line once they are staged. */
51
+ export function stagedLine(files, bytes) {
52
+ return `inputs: ${files} file${files === 1 ? "" : "s"} in ${INPUTS_DIR}/ (${human(bytes)})`;
53
+ }
@@ -11,6 +11,7 @@ import type { McpServerConfig } from "@anthropic-ai/claude-agent-sdk";
11
11
  import { type LanguageChoice } from "./language.ts";
12
12
  import { type RegionChoice } from "./locale.ts";
13
13
  import { type RunContext, type RunInput } from "./conversation.ts";
14
+ import { type RunInputFile } from "./run-inputs.ts";
14
15
  import { type ClockChoice } from "./clock.ts";
15
16
  export { localDate } from "./clock.ts";
16
17
  /** Remote MCP servers with each bound secret's value put back as its
@@ -409,6 +410,7 @@ grantsOnly?: boolean): {
409
410
  cacheKey?: string;
410
411
  label?: string;
411
412
  egress?: string;
413
+ media?: import("./translator.ts").TranslatorMedia;
412
414
  timezone: string;
413
415
  } | null;
414
416
  fallbackTranslator: {
@@ -423,6 +425,7 @@ grantsOnly?: boolean): {
423
425
  cacheKey?: string;
424
426
  label?: string;
425
427
  egress?: string;
428
+ media?: import("./translator.ts").TranslatorMedia;
426
429
  timezone: string;
427
430
  } | null;
428
431
  apiWarnings: string[];
@@ -609,7 +612,13 @@ snapshot?: string,
609
612
  conversation?: {
610
613
  context: RunContext;
611
614
  input?: RunInput;
612
- }): RunRecord;
615
+ },
616
+ /** FOL-163: the files the run is handed, already held for it (storage.ts
617
+ * holdRunInputs). The run's first step — the one its task reaches — is
618
+ * given them at agents/<name>/inputs/. */
619
+ inputs?: RunInputFile[],
620
+ /** FOL-168: which of the partner's own users the run is for. */
621
+ customer?: string): RunRecord;
613
622
  export declare function startFlowRun(tenant: string, workspace: string, steps: FlowStep[], flowName: string, modelOverride?: string | null, tags?: string[], effortOverride?: string | null, startedBy?: string | null, opts?: {
614
623
  test?: boolean;
615
624
  }): RunRecord;
@@ -73,6 +73,7 @@ import { resolveLanguage, languageName } from "./language.js";
73
73
  import { resolveRegion, deriveLocale, localeProse, regionName } from "./locale.js";
74
74
  import { trimChars } from "./paths.js";
75
75
  import { earlierTurns, conversationBlock } from "./conversation.js";
76
+ import { inputsNote } from "./run-inputs.js";
76
77
  import { resolveClock, localDate } from "./clock.js";
77
78
  export { localDate } from "./clock.js";
78
79
  // An MCP tool definition becomes an SDK server config. ${SECRET} placeholders
@@ -2778,7 +2779,19 @@ conversation) {
2778
2779
  // run was made. Only an executor that says it can hold one may run it —
2779
2780
  // in-process, the step would work in the real workspace folder, and no
2780
2781
  // copy-back stands between what it writes and the workspace (Codex).
2781
- const snapshotId = runId ? readRun(tenant, path.basename(workspaceRootOf(agentDir)), runId)?.snapshot?.id : undefined;
2782
+ const runRecord = runId ? readRun(tenant, path.basename(workspaceRootOf(agentDir)), runId) : null;
2783
+ const snapshotId = runRecord?.snapshot?.id;
2784
+ // The run's inputs (FOL-163), for the step its task reaches. Staged only
2785
+ // by an executor that can hold them: in-process the step would share the
2786
+ // real agents/<name>/inputs/ with every other run of the agent, and its
2787
+ // writes there would land in the workspace.
2788
+ const stepInputs = step.inputsTurn && runRecord?.inputs?.length ? runRecord.inputs : null;
2789
+ if (stepInputs) {
2790
+ const able = isolatedRun() && (isolation === "container" || (Boolean(platform.isolation[isolation]) && platform.holdsInputs?.(isolation) === true));
2791
+ if (!able) {
2792
+ 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.");
2793
+ }
2794
+ }
2782
2795
  if (snapshotId) {
2783
2796
  const able = isolatedRun() && isolation !== "container" && Boolean(platform.isolation[isolation]) && platform.holdsSnapshot?.(isolation) === true;
2784
2797
  if (!able) {
@@ -2806,7 +2819,7 @@ conversation) {
2806
2819
  // before anything is copied in. Null where no proxy is configured
2807
2820
  // (the CLI, a compose install without FOLDRUN_EGRESS_URL), and then
2808
2821
  // everything below materialises exactly as it always did.
2809
- const grant = { secrets: {}, timezone: clock.timezone };
2822
+ const grant = { secrets: {}, timezone: clock.timezone, ...(runRecord?.customer ? { customer: runRecord.customer } : {}) };
2810
2823
  // A direct search API's key: granted to that API's host and no other,
2811
2824
  // exactly as an http tool's key is granted to its base URL's host. The
2812
2825
  // script sends the placeholder; the worker fills it on the way out.
@@ -3159,6 +3172,7 @@ conversation) {
3159
3172
  const isolatedArgs = (modelEnv, keyName = MODEL_KEY_NAME) => ({
3160
3173
  workspaceRoot,
3161
3174
  ...(snapshotId ? { snapshot: { id: snapshotId } } : {}),
3175
+ ...(stepInputs && runId ? { inputs: { runId, files: stepInputs } } : {}),
3162
3176
  libraryRoot: libraryDir(tenant),
3163
3177
  galleryRoot: platform.galleryDir() ?? undefined,
3164
3178
  // Keys this step's dependency cache. Per-account by design — see
@@ -3169,7 +3183,7 @@ conversation) {
3169
3183
  // Its file tools inside the sandbox get the same allowance (FOL-96).
3170
3184
  configWrites: step.approve === true && Boolean(step.approvedAt),
3171
3185
  // A snapshot step is told where its folder is, and what comes back.
3172
- prompt: snapshotId ? `${prompt}\n\n${SNAPSHOT_NOTE}` : prompt,
3186
+ prompt: `${prompt}${snapshotId ? `\n\n${SNAPSHOT_NOTE}` : ""}${stepInputs ? `\n\n${inputsNote(stepInputs)}` : ""}`,
3173
3187
  model,
3174
3188
  effort,
3175
3189
  systemPrompt,
@@ -4375,7 +4389,13 @@ snapshot,
4375
4389
  /** FOL-162: the conversation this run is a turn of, and what it was
4376
4390
  * asked — written with the record, before any worker can see it. The
4377
4391
  * run's first step (the one its task reaches) reads the earlier turns. */
4378
- conversation) {
4392
+ conversation,
4393
+ /** FOL-163: the files the run is handed, already held for it (storage.ts
4394
+ * holdRunInputs). The run's first step — the one its task reaches — is
4395
+ * given them at agents/<name>/inputs/. */
4396
+ inputs,
4397
+ /** FOL-168: which of the partner's own users the run is for. */
4398
+ customer) {
4379
4399
  let flowMaxOut;
4380
4400
  try {
4381
4401
  flowMaxOut = readFlow(tenant, workspace, flowName)?.maxOutputTokens;
@@ -4446,6 +4466,13 @@ conversation) {
4446
4466
  if (run.steps[0])
4447
4467
  run.steps[0].conversationTurn = true;
4448
4468
  }
4469
+ if (inputs?.length) {
4470
+ run.inputs = inputs;
4471
+ if (run.steps[0])
4472
+ run.steps[0].inputsTurn = true;
4473
+ }
4474
+ if (customer)
4475
+ run.customer = customer;
4449
4476
  writeRun(tenant, workspace, run);
4450
4477
  // Start every run from an empty outputs/ for each agent it will touch.
4451
4478
  //
@@ -5894,8 +5921,10 @@ function driveRunInner(tenant, workspace, run, modelOverride, tags, opts) {
5894
5921
  // medium-desk).
5895
5922
  output: step.output,
5896
5923
  ...(step.verify ? { verify: step.verify } : {}),
5897
- // Taking over the step the run's task reached: the conversation too.
5924
+ // Taking over the step the run's task reached: the conversation
5925
+ // and the inputs too.
5898
5926
  ...(step.conversationTurn ? { conversationTurn: true } : {}),
5927
+ ...(step.inputsTurn ? { inputsTurn: true } : {}),
5899
5928
  attempts: 0,
5900
5929
  status: "pending",
5901
5930
  events: [],
@@ -13,6 +13,8 @@ export interface RunFilter {
13
13
  minSecs?: number;
14
14
  /** The run is a turn of this conversation: its `context` id, exactly (FOL-162). */
15
15
  context?: string;
16
+ /** The run is for this end customer, exactly (FOL-168). */
17
+ customer?: string;
16
18
  }
17
19
  /** The query parameters a filter comes from: tool, tool_error, agent,
18
20
  * model, min_tokens, min_secs, context. Unreadable numbers are refused in words. */
@@ -47,6 +49,7 @@ type FilterableRun = {
47
49
  context?: {
48
50
  id: string;
49
51
  };
52
+ customer?: string;
50
53
  steps: FilterableStep[];
51
54
  };
52
55
  export declare function matchesRunFilter(run: FilterableRun, f: RunFilter, now?: number): boolean;
@@ -23,6 +23,9 @@ export function parseRunFilter(q) {
23
23
  const context = q.get("context");
24
24
  if (context)
25
25
  filter.context = context;
26
+ const customer = q.get("customer");
27
+ if (customer)
28
+ filter.customer = customer;
26
29
  for (const [k, field] of [["min_tokens", "minTokens"], ["min_secs", "minSecs"]]) {
27
30
  const v = text(k);
28
31
  if (v === undefined)
@@ -58,6 +61,8 @@ function factsOf(s) {
58
61
  export function matchesRunFilter(run, f, now = Date.now()) {
59
62
  if (f.context !== undefined && run.context?.id !== f.context)
60
63
  return false;
64
+ if (f.customer !== undefined && run.customer !== f.customer)
65
+ return false;
61
66
  const steps = (run.steps ?? []).map((s) => ({ ...s, ...factsOf(s) }));
62
67
  if (f.tool && !steps.some((s) => (s.tools ?? []).some((t) => t.toLowerCase().includes(f.tool))))
63
68
  return false;
@@ -56,6 +56,55 @@ export declare function blobKey(tenant: string, workspace: string, sha: string):
56
56
  * path.normalize alone will happily keep.
57
57
  */
58
58
  export declare function assertFilePath(rel: string): string;
59
+ export declare const RUN_INPUTS_PREFIX = ".foldrun/run-inputs/";
60
+ /** A path under foldrun's own prefix. */
61
+ export declare function isReservedPath(rel: string): boolean;
62
+ /** Refuse foldrun's own prefix on a person's or a run's write. */
63
+ export declare function assertNotReserved(norm: string): string;
64
+ /** One input as the run holds it: the storage path it was given and the
65
+ * blob it named then. */
66
+ export interface RunInputFile {
67
+ path: string;
68
+ sha: string;
69
+ size: number;
70
+ mime: string;
71
+ }
72
+ /** An input path that names no stored file (or a reserved one). */
73
+ export declare class MissingInput extends Error {
74
+ readonly path: string;
75
+ constructor(path: string);
76
+ }
77
+ /**
78
+ * Resolve `paths` (storage-relative, as GET …/storage lists them) to the
79
+ * blob each names now. Throws MissingInput for a path with no record.
80
+ * Returns them in the order given, duplicates dropped. Holds nothing:
81
+ * holdRunInputs does, once the run exists.
82
+ */
83
+ export declare function resolveRunInputs(tenant: string, workspace: string, paths: string[]): RunInputFile[];
84
+ /**
85
+ * Hold `inputs` for `runId`, under the workspace's lock: from here no
86
+ * overwrite or delete can take the bytes the run will read. Each blob must
87
+ * still be named by some record — the file itself, or another run's hold (a
88
+ * re-run reads what its source read). Throws MissingInput for one that is
89
+ * gone; nothing is held then.
90
+ */
91
+ export declare function holdRunInputs(tenant: string, workspace: string, runId: string, inputs: RunInputFile[]): Promise<void>;
92
+ /** Let go of a run's held inputs; a blob nothing else names is collected. */
93
+ export declare function releaseRunInputs(tenant: string, workspace: string, runId: string): Promise<number>;
94
+ /** Let go of the holds of runs that no longer exist — what a crash between
95
+ * a run's delete and its release left. `alive` says whether a run is there.
96
+ * Returns how many runs' holds went. */
97
+ export declare function sweepHeldInputs(tenant: string, workspace: string, alive: (runId: string) => boolean): Promise<number>;
98
+ /**
99
+ * Write a run's held inputs into `intoDir` (made fresh: whatever was there
100
+ * is removed first, so a folder of the same name never mixes in), each at
101
+ * its storage path. Reads the blob each input named when the run was made,
102
+ * never the path again. Throws when one is gone.
103
+ */
104
+ export declare function stageRunInputs(tenant: string, workspace: string, runId: string, inputs: RunInputFile[], intoDir: string): Promise<{
105
+ files: number;
106
+ bytes: number;
107
+ }>;
59
108
  export declare function mimeFor(rel: string): string;
60
109
  export declare function readIndex(tenant: string, workspace: string): Index;
61
110
  export declare function listStorage(tenant: string, workspace: string): FileRecord[];