@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.
@@ -72,6 +72,8 @@ import { NEWER_ACTIONS, resolveActionApi } from "./web-actions.js";
72
72
  import { resolveLanguage, languageName } from "./language.js";
73
73
  import { resolveRegion, deriveLocale, localeProse, regionName } from "./locale.js";
74
74
  import { trimChars } from "./paths.js";
75
+ import { earlierTurns, conversationBlock } from "./conversation.js";
76
+ import { inputsNote } from "./run-inputs.js";
75
77
  import { resolveClock, localDate } from "./clock.js";
76
78
  export { localDate } from "./clock.js";
77
79
  // An MCP tool definition becomes an SDK server config. ${SECRET} placeholders
@@ -2032,7 +2034,11 @@ delegateJob,
2032
2034
  * with its run instead of waiting in this driver (the drive loop's
2033
2035
  * mayDefer). Absent: it waits here, however long — a rescue, a step
2034
2036
  * outside a flow, a foreground run. */
2035
- mayDefer) {
2037
+ mayDefer,
2038
+ /** FOL-162: the earlier turns of the run's conversation, as the block
2039
+ * conversation.ts built — read before the instruction. Already escaped;
2040
+ * never resolved for [[links]] (it is other runs' words). */
2041
+ conversation) {
2036
2042
  // Secret values are injected into scripts as environment variables and
2037
2043
  // substituted into API headers, so a model that reads one back — from a
2038
2044
  // script that prints it, an API error that echoes it, or its own `env` —
@@ -2168,6 +2174,9 @@ mayDefer) {
2168
2174
  // The ceiling it was given rides on the line, so the budget arithmetic
2169
2175
  // around fan-out is testable without a model to stop.
2170
2176
  push("info", `stub call ${call + 1}${stepBudgetUsd !== null ? ` (ceiling $${stepBudgetUsd.toFixed(2)})` : ""}`);
2177
+ // What a real step would have read before its instruction (FOL-162).
2178
+ if (conversation)
2179
+ push("info", `stub conversation: ${conversation}`);
2171
2180
  step.status = "completed";
2172
2181
  // A stub answer may open with `cost: 0.25` — a pretend price, so the
2173
2182
  // parts of orchestration that watch money (budget:) are testable too.
@@ -2565,6 +2574,10 @@ mayDefer) {
2565
2574
  let prompt = step.instruction
2566
2575
  ? resolveDocLinks(step.instruction, workspaceRoot)
2567
2576
  : "Begin your run now, following your instructions.";
2577
+ // The conversation's earlier turns go first, the request after them —
2578
+ // in the user turn, not the system prompt (conversation.ts says why).
2579
+ if (conversation)
2580
+ prompt = `${conversation}\n\n${prompt}`;
2568
2581
  if (context)
2569
2582
  prompt += `\n\n<previous_step_results>\n${context.slice(0, CONTEXT_CHARS)}\n</previous_step_results>`;
2570
2583
  if (priorData !== undefined) {
@@ -2766,7 +2779,19 @@ mayDefer) {
2766
2779
  // run was made. Only an executor that says it can hold one may run it —
2767
2780
  // in-process, the step would work in the real workspace folder, and no
2768
2781
  // copy-back stands between what it writes and the workspace (Codex).
2769
- 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
+ }
2770
2795
  if (snapshotId) {
2771
2796
  const able = isolatedRun() && isolation !== "container" && Boolean(platform.isolation[isolation]) && platform.holdsSnapshot?.(isolation) === true;
2772
2797
  if (!able) {
@@ -2794,7 +2819,7 @@ mayDefer) {
2794
2819
  // before anything is copied in. Null where no proxy is configured
2795
2820
  // (the CLI, a compose install without FOLDRUN_EGRESS_URL), and then
2796
2821
  // everything below materialises exactly as it always did.
2797
- const grant = { secrets: {}, timezone: clock.timezone };
2822
+ const grant = { secrets: {}, timezone: clock.timezone, ...(runRecord?.customer ? { customer: runRecord.customer } : {}) };
2798
2823
  // A direct search API's key: granted to that API's host and no other,
2799
2824
  // exactly as an http tool's key is granted to its base URL's host. The
2800
2825
  // script sends the placeholder; the worker fills it on the way out.
@@ -3147,6 +3172,7 @@ mayDefer) {
3147
3172
  const isolatedArgs = (modelEnv, keyName = MODEL_KEY_NAME) => ({
3148
3173
  workspaceRoot,
3149
3174
  ...(snapshotId ? { snapshot: { id: snapshotId } } : {}),
3175
+ ...(stepInputs && runId ? { inputs: { runId, files: stepInputs } } : {}),
3150
3176
  libraryRoot: libraryDir(tenant),
3151
3177
  galleryRoot: platform.galleryDir() ?? undefined,
3152
3178
  // Keys this step's dependency cache. Per-account by design — see
@@ -3157,7 +3183,7 @@ mayDefer) {
3157
3183
  // Its file tools inside the sandbox get the same allowance (FOL-96).
3158
3184
  configWrites: step.approve === true && Boolean(step.approvedAt),
3159
3185
  // A snapshot step is told where its folder is, and what comes back.
3160
- prompt: snapshotId ? `${prompt}\n\n${SNAPSHOT_NOTE}` : prompt,
3186
+ prompt: `${prompt}${snapshotId ? `\n\n${SNAPSHOT_NOTE}` : ""}${stepInputs ? `\n\n${inputsNote(stepInputs)}` : ""}`,
3161
3187
  model,
3162
3188
  effort,
3163
3189
  systemPrompt,
@@ -4359,7 +4385,17 @@ export function createFlowRun(tenant, workspace, steps, flowName, status, tags =
4359
4385
  a2a,
4360
4386
  /** A snapshot run's folder (Part B3): the id POST …/snapshots answered.
4361
4387
  * Its own trailing argument, as a2a is, so the signature only widened. */
4362
- snapshot) {
4388
+ snapshot,
4389
+ /** FOL-162: the conversation this run is a turn of, and what it was
4390
+ * asked — written with the record, before any worker can see it. The
4391
+ * run's first step (the one its task reaches) reads the earlier turns. */
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) {
4363
4399
  let flowMaxOut;
4364
4400
  try {
4365
4401
  flowMaxOut = readFlow(tenant, workspace, flowName)?.maxOutputTokens;
@@ -4423,6 +4459,20 @@ snapshot) {
4423
4459
  costUsd: null,
4424
4460
  })),
4425
4461
  };
4462
+ if (conversation?.context) {
4463
+ run.context = conversation.context;
4464
+ if (conversation.input)
4465
+ run.input = conversation.input;
4466
+ if (run.steps[0])
4467
+ run.steps[0].conversationTurn = true;
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;
4426
4476
  writeRun(tenant, workspace, run);
4427
4477
  // Start every run from an empty outputs/ for each agent it will touch.
4428
4478
  //
@@ -5488,6 +5538,34 @@ function driveRunInner(tenant, workspace, run, modelOverride, tags, opts) {
5488
5538
  // of its group is under way (a sibling still running keeps the run
5489
5539
  // here anyway), and only once the group has waited a while, so a
5490
5540
  // short wait stays a short wait. Never on a foreground run.
5541
+ // FOL-162: the earlier turns of the run's conversation, for the step
5542
+ // the run's task reaches. Read fresh at each start (a retry, a
5543
+ // resume) — the same turns each time, since which runs count is
5544
+ // fixed by when this run was made. A lookup that fails costs the
5545
+ // step its history, never the step.
5546
+ const conversationFor = (step) => {
5547
+ if (!step.conversationTurn || !run.context)
5548
+ return undefined;
5549
+ try {
5550
+ const built = conversationBlock(run, earlierTurns(tenant, workspace, run));
5551
+ if (!built) {
5552
+ delete step.history;
5553
+ return undefined;
5554
+ }
5555
+ step.history = built.record;
5556
+ const r = built.record;
5557
+ step.events.push({
5558
+ t: new Date().toISOString(),
5559
+ type: "info",
5560
+ 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` : ""}`,
5561
+ });
5562
+ return built.text;
5563
+ }
5564
+ catch (err) {
5565
+ 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` });
5566
+ return undefined;
5567
+ }
5568
+ };
5491
5569
  const mayDefer = (step) => () => {
5492
5570
  if (!opts.parkOnApproval)
5493
5571
  return false;
@@ -5610,7 +5688,7 @@ function driveRunInner(tenant, workspace, run, modelOverride, tags, opts) {
5610
5688
  () => {
5611
5689
  save();
5612
5690
  return run.stopRequested === true;
5613
- }, flowTimezone, run.steps.indexOf(step), siblingsOf(step), peerBus, delegateFor(step), mayDefer(step)).finally(() => reserved.delete(step));
5691
+ }, flowTimezone, run.steps.indexOf(step), siblingsOf(step), peerBus, delegateFor(step), mayDefer(step), conversationFor(step)).finally(() => reserved.delete(step));
5614
5692
  // Sent back for room: not a try. The run parks once the
5615
5693
  // group is done (below) and this attempt starts again later.
5616
5694
  if (verdict?.deferred) {
@@ -5801,7 +5879,7 @@ function driveRunInner(tenant, workspace, run, modelOverride, tags, opts) {
5801
5879
  resumed.attempts = Math.max(1, resumed.attempts ?? 0);
5802
5880
  resumed.status = "running";
5803
5881
  save();
5804
- await runStep(rescuerDir, tenant, resumed, ctx, save, modelOverride, tags, effortOverride, run.id, ctxData, null, undefined, run.test === true, stopPoll, flowTimezone, run.steps.indexOf(resumed));
5882
+ 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));
5805
5883
  settleRescue(step, resumed);
5806
5884
  return;
5807
5885
  }
@@ -5843,6 +5921,10 @@ function driveRunInner(tenant, workspace, run, modelOverride, tags, opts) {
5843
5921
  // medium-desk).
5844
5922
  output: step.output,
5845
5923
  ...(step.verify ? { verify: step.verify } : {}),
5924
+ // Taking over the step the run's task reached: the conversation
5925
+ // and the inputs too.
5926
+ ...(step.conversationTurn ? { conversationTurn: true } : {}),
5927
+ ...(step.inputsTurn ? { inputsTurn: true } : {}),
5846
5928
  attempts: 0,
5847
5929
  status: "pending",
5848
5930
  events: [],
@@ -5854,7 +5936,7 @@ function driveRunInner(tenant, workspace, run, modelOverride, tags, opts) {
5854
5936
  rescue.attempts = 1;
5855
5937
  rescue.status = "running";
5856
5938
  save();
5857
- await runStep(rescuerDir, tenant, rescue, ctx, save, modelOverride, tags, effortOverride, run.id, ctxData, null, undefined, run.test === true, stopPoll, flowTimezone, run.steps.indexOf(rescue));
5939
+ 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));
5858
5940
  settleRescue(step, rescue);
5859
5941
  };
5860
5942
  // What a rescue's end means for the step it took over.
@@ -11,9 +11,13 @@ export interface RunFilter {
11
11
  minTokens?: number;
12
12
  /** The run took at least this many seconds. */
13
13
  minSecs?: number;
14
+ /** The run is a turn of this conversation: its `context` id, exactly (FOL-162). */
15
+ context?: string;
16
+ /** The run is for this end customer, exactly (FOL-168). */
17
+ customer?: string;
14
18
  }
15
19
  /** The query parameters a filter comes from: tool, tool_error, agent,
16
- * model, min_tokens, min_secs. Unreadable numbers are refused in words. */
20
+ * model, min_tokens, min_secs, context. Unreadable numbers are refused in words. */
17
21
  export declare function parseRunFilter(q: {
18
22
  get(name: string): string | null;
19
23
  }): {
@@ -42,6 +46,10 @@ type FilterableStep = {
42
46
  type FilterableRun = {
43
47
  startedAt: string;
44
48
  finishedAt?: string | null;
49
+ context?: {
50
+ id: string;
51
+ };
52
+ customer?: string;
45
53
  steps: FilterableStep[];
46
54
  };
47
55
  export declare function matchesRunFilter(run: FilterableRun, f: RunFilter, now?: number): boolean;
@@ -3,7 +3,7 @@
3
3
  // called, its tool errors, its agent and model, tokens and how long it took.
4
4
  // Pure.
5
5
  /** The query parameters a filter comes from: tool, tool_error, agent,
6
- * model, min_tokens, min_secs. Unreadable numbers are refused in words. */
6
+ * model, min_tokens, min_secs, context. Unreadable numbers are refused in words. */
7
7
  export function parseRunFilter(q) {
8
8
  const filter = {};
9
9
  const problems = [];
@@ -20,6 +20,12 @@ export function parseRunFilter(q) {
20
20
  const model = text("model");
21
21
  if (model)
22
22
  filter.model = model.toLowerCase();
23
+ const context = q.get("context");
24
+ if (context)
25
+ filter.context = context;
26
+ const customer = q.get("customer");
27
+ if (customer)
28
+ filter.customer = customer;
23
29
  for (const [k, field] of [["min_tokens", "minTokens"], ["min_secs", "minSecs"]]) {
24
30
  const v = text(k);
25
31
  if (v === undefined)
@@ -53,6 +59,10 @@ function factsOf(s) {
53
59
  return { tools: [...tools], toolErrors: errs };
54
60
  }
55
61
  export function matchesRunFilter(run, f, now = Date.now()) {
62
+ if (f.context !== undefined && run.context?.id !== f.context)
63
+ return false;
64
+ if (f.customer !== undefined && run.customer !== f.customer)
65
+ return false;
56
66
  const steps = (run.steps ?? []).map((s) => ({ ...s, ...factsOf(s) }));
57
67
  if (f.tool && !steps.some((s) => (s.tools ?? []).some((t) => t.toLowerCase().includes(f.tool))))
58
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[];
@@ -142,6 +142,152 @@ export function assertFilePath(rel) {
142
142
  throw new Error(`illegal file path: ${rel}`);
143
143
  return norm;
144
144
  }
145
+ // ---------- foldrun's own records: a run's held inputs (FOL-163) ----------
146
+ //
147
+ // A run with `inputs` reads the files as they were when it was made, not as
148
+ // they are when its step starts: an overwrite or a delete in between changes
149
+ // nothing it reads. Each input is held by a record of foldrun's own under
150
+ // `.foldrun/run-inputs/<runId>/<path>`, naming the same blob — zero copies,
151
+ // and the collector (collectLocked) keeps a blob while any record names it,
152
+ // so nothing new had to learn about holds. Those records are never listed,
153
+ // mirrored into a sandbox or harvested, and no person's write, upload or
154
+ // delete may name the prefix; they go when the run's record does.
155
+ const RESERVED = ".foldrun";
156
+ export const RUN_INPUTS_PREFIX = `${RESERVED}/run-inputs/`;
157
+ /** A path under foldrun's own prefix. */
158
+ export function isReservedPath(rel) {
159
+ return rel === RESERVED || rel.startsWith(`${RESERVED}/`);
160
+ }
161
+ /** Refuse foldrun's own prefix on a person's or a run's write. */
162
+ export function assertNotReserved(norm) {
163
+ if (isReservedPath(norm))
164
+ throw new Error(`${norm}: storage/${RESERVED}/ is foldrun's own — choose another path`);
165
+ return norm;
166
+ }
167
+ /** An input path that names no stored file (or a reserved one). */
168
+ export class MissingInput extends Error {
169
+ path;
170
+ constructor(path) {
171
+ super(`no stored file ${path}`);
172
+ this.path = path;
173
+ }
174
+ }
175
+ const heldPath = (runId, rel) => `${RUN_INPUTS_PREFIX}${runId}/${rel}`;
176
+ /**
177
+ * Resolve `paths` (storage-relative, as GET …/storage lists them) to the
178
+ * blob each names now. Throws MissingInput for a path with no record.
179
+ * Returns them in the order given, duplicates dropped. Holds nothing:
180
+ * holdRunInputs does, once the run exists.
181
+ */
182
+ export function resolveRunInputs(tenant, workspace, paths) {
183
+ const files = readIndex(tenant, workspace).files;
184
+ const out = [];
185
+ const seen = new Set();
186
+ for (const p of paths) {
187
+ let norm;
188
+ try {
189
+ norm = assertFilePath(p);
190
+ }
191
+ catch {
192
+ throw new MissingInput(p);
193
+ }
194
+ if (isReservedPath(norm))
195
+ throw new MissingInput(norm);
196
+ if (seen.has(norm))
197
+ continue;
198
+ seen.add(norm);
199
+ const rec = files.find((f) => f.path === norm);
200
+ if (!rec)
201
+ throw new MissingInput(norm);
202
+ out.push({ path: norm, sha: rec.sha, size: rec.size, mime: rec.mime });
203
+ }
204
+ return out;
205
+ }
206
+ /**
207
+ * Hold `inputs` for `runId`, under the workspace's lock: from here no
208
+ * overwrite or delete can take the bytes the run will read. Each blob must
209
+ * still be named by some record — the file itself, or another run's hold (a
210
+ * re-run reads what its source read). Throws MissingInput for one that is
211
+ * gone; nothing is held then.
212
+ */
213
+ export async function holdRunInputs(tenant, workspace, runId, inputs) {
214
+ assertSafeName(runId, "run id");
215
+ await withFileStoreLock(tenant, workspace, async () => {
216
+ const shas = new Set(readIndex(tenant, workspace).files.map((f) => f.sha));
217
+ for (const i of inputs)
218
+ if (!shas.has(i.sha))
219
+ throw new MissingInput(i.path);
220
+ holdLocked(tenant, workspace, runId, inputs);
221
+ });
222
+ }
223
+ function holdLocked(tenant, workspace, runId, inputs) {
224
+ const now = new Date().toISOString();
225
+ for (const i of inputs) {
226
+ // Re-read each time: the file store rewrites the whole index per put.
227
+ 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` });
228
+ }
229
+ }
230
+ /** Let go of a run's held inputs; a blob nothing else names is collected. */
231
+ export async function releaseRunInputs(tenant, workspace, runId) {
232
+ if (!fileStoreEnabled())
233
+ return 0;
234
+ const prefix = `${RUN_INPUTS_PREFIX}${runId}/`;
235
+ return withFileStoreLock(tenant, workspace, async () => {
236
+ const held = readIndex(tenant, workspace).files.filter((f) => f.path.startsWith(prefix));
237
+ for (const f of held)
238
+ indexRemove(tenant, workspace, readIndex(tenant, workspace), f.path);
239
+ for (const sha of new Set(held.map((f) => f.sha)))
240
+ await collectLocked(tenant, workspace, sha);
241
+ return held.length;
242
+ });
243
+ }
244
+ /** Let go of the holds of runs that no longer exist — what a crash between
245
+ * a run's delete and its release left. `alive` says whether a run is there.
246
+ * Returns how many runs' holds went. */
247
+ export async function sweepHeldInputs(tenant, workspace, alive) {
248
+ if (!fileStoreEnabled())
249
+ return 0;
250
+ const runs = new Set(readIndex(tenant, workspace)
251
+ .files.filter((f) => f.path.startsWith(RUN_INPUTS_PREFIX))
252
+ .map((f) => f.path.slice(RUN_INPUTS_PREFIX.length).split("/")[0])
253
+ .filter(Boolean));
254
+ let gone = 0;
255
+ for (const runId of runs) {
256
+ if (alive(runId))
257
+ continue;
258
+ if ((await releaseRunInputs(tenant, workspace, runId)) > 0)
259
+ gone++;
260
+ }
261
+ return gone;
262
+ }
263
+ /**
264
+ * Write a run's held inputs into `intoDir` (made fresh: whatever was there
265
+ * is removed first, so a folder of the same name never mixes in), each at
266
+ * its storage path. Reads the blob each input named when the run was made,
267
+ * never the path again. Throws when one is gone.
268
+ */
269
+ export async function stageRunInputs(tenant, workspace, runId, inputs, intoDir) {
270
+ fs.rmSync(intoDir, { recursive: true, force: true });
271
+ fs.mkdirSync(intoDir, { recursive: true });
272
+ const held = new Set(readIndex(tenant, workspace).files.filter((f) => f.path.startsWith(`${RUN_INPUTS_PREFIX}${runId}/`)).map((f) => f.sha));
273
+ const driver = driverFor(tenant, workspace);
274
+ let bytes = 0;
275
+ for (const i of inputs) {
276
+ const norm = assertFilePath(i.path);
277
+ if (!held.has(i.sha))
278
+ throw new MissingInput(norm);
279
+ const body = await driver.get(blobKey(tenant, workspace, i.sha));
280
+ if (sha256(body) !== i.sha)
281
+ throw new Error(`input ${norm}: the stored bytes do not match what the run was given`);
282
+ const abs = path.join(intoDir, norm);
283
+ if (!abs.startsWith(intoDir + path.sep))
284
+ throw new MissingInput(norm);
285
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
286
+ fs.writeFileSync(abs, body, { flag: "wx" });
287
+ bytes += body.length;
288
+ }
289
+ return { files: inputs.length, bytes };
290
+ }
145
291
  // ---------- mime ----------
146
292
  const MIME = {
147
293
  ".pdf": "application/pdf",
@@ -215,7 +361,8 @@ function indexRemove(tenant, workspace, index, rel) {
215
361
  writeIndex(tenant, workspace, { version: 1, files: index.files.filter((f) => f.path !== rel) });
216
362
  }
217
363
  export function listStorage(tenant, workspace) {
218
- return readIndex(tenant, workspace).files.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
364
+ // foldrun's own records (a run's held inputs) are not the workspace's files.
365
+ return readIndex(tenant, workspace).files.filter((f) => !isReservedPath(f.path)).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
219
366
  }
220
367
  export function getFile(tenant, workspace, rel) {
221
368
  const norm = assertFilePath(rel);
@@ -766,7 +913,7 @@ export async function putFile(tenant, workspace, rel, body, by) {
766
913
  return record;
767
914
  }
768
915
  async function putFileQuietly(tenant, workspace, rel, body, by) {
769
- const norm = assertFilePath(rel);
916
+ const norm = assertNotReserved(assertFilePath(rel));
770
917
  if (body.length > maxBytes()) {
771
918
  throw new Error(`${norm} is ${Math.round(body.length / 1e6)}MB — the limit is ${maxBytes() / 1e6}MB`);
772
919
  }
@@ -828,7 +975,7 @@ async function putFileQuietly(tenant, workspace, rel, body, by) {
828
975
  * claim, so an object registered as 0 bytes (or -1e12) sat outside every
829
976
  * limit and lowered the quota line for everything after it. */
830
977
  export async function registerUpload(tenant, workspace, rel, sha, _claimed, by) {
831
- const norm = assertFilePath(rel);
978
+ const norm = assertNotReserved(assertFilePath(rel));
832
979
  if (!/^[0-9a-f]{64}$/.test(sha))
833
980
  throw new Error("expected a sha256");
834
981
  requireWorkspace(tenant, workspace);
@@ -909,7 +1056,7 @@ export async function openFile(tenant, workspace, rel, range) {
909
1056
  return { record, size, body: await driver.open(key, range ?? undefined) };
910
1057
  }
911
1058
  export async function deleteFile(tenant, workspace, rel) {
912
- const norm = assertFilePath(rel);
1059
+ const norm = assertNotReserved(assertFilePath(rel));
913
1060
  return withFileStoreLock(tenant, workspace, async () => {
914
1061
  const index = readIndex(tenant, workspace);
915
1062
  const record = index.files.find((f) => f.path === norm);
@@ -966,7 +1113,7 @@ export function previewType(rel) {
966
1113
  }
967
1114
  /** A link the browser can PUT to, plus the key it will land at. Null on fs. */
968
1115
  export async function uploadUrl(tenant, workspace, rel, sha, size) {
969
- const norm = assertFilePath(rel);
1116
+ const norm = assertNotReserved(assertFilePath(rel));
970
1117
  if (!/^[0-9a-f]{64}$/.test(sha))
971
1118
  throw new Error("expected a sha256");
972
1119
  requireWorkspace(tenant, workspace);
@@ -1102,6 +1249,9 @@ export async function materializeFiles(tenant, workspace) {
1102
1249
  const driver = driverFor(tenant, workspace);
1103
1250
  const brought = [];
1104
1251
  for (const record of readIndex(tenant, workspace).files) {
1252
+ // A run's held inputs are staged into its own step, never mirrored.
1253
+ if (isReservedPath(record.path))
1254
+ continue;
1105
1255
  const target = path.join(root, record.path);
1106
1256
  try {
1107
1257
  const stat = fs.statSync(target);
@@ -1140,7 +1290,7 @@ export async function materializeFiles(tenant, workspace) {
1140
1290
  export function storageBaseline(tenant, workspace) {
1141
1291
  if (!fileStoreEnabled())
1142
1292
  return {};
1143
- return Object.fromEntries(readIndex(tenant, workspace).files.map((f) => [f.path, f.sha]));
1293
+ return Object.fromEntries(readIndex(tenant, workspace).files.filter((f) => !isReservedPath(f.path)).map((f) => [f.path, f.sha]));
1144
1294
  }
1145
1295
  /**
1146
1296
  * Take what the run left in `storage/` back into the store, stamped with the
@@ -20,6 +20,8 @@ import { type FailureExplained, type FailureFacts } from "./failure.ts";
20
20
  import { type NetworkPolicy } from "./network.ts";
21
21
  import { type SearchingAction } from "./search-egress.ts";
22
22
  import { type WireFormat, type AuthShape } from "./providers.ts";
23
+ import type { RunContext, RunInput, ConversationRecord } from "./conversation.ts";
24
+ import type { RunInputFile } from "./storage.ts";
23
25
  /**
24
26
  * Single-workspace mode. When set, the workspace IS this directory — no
25
27
  * tenant, no projects/ nesting. That's the difference between a framework you
@@ -1396,6 +1398,19 @@ export interface StepRecord {
1396
1398
  delegation?: string;
1397
1399
  /** On a step that delegated to isolated sub-agents: each job, in order. */
1398
1400
  delegations?: StepDelegation[];
1401
+ /** FOL-162: this step reads the run's conversation — the earlier runs of
1402
+ * its `context` — before its instruction. Set when the run is made on
1403
+ * the step the run's task reaches (its fan-out instances and an on-fail
1404
+ * rescue of it inherit it; a re-run sets it on the first step it runs). */
1405
+ conversationTurn?: boolean;
1406
+ /** What that step was given, written when it starts: which runs, how many
1407
+ * did not fit, and a hash of the block (conversation.ts). Never the text. */
1408
+ history?: ConversationRecord;
1409
+ /** FOL-163: this step is handed the run's `inputs`, staged at
1410
+ * agents/<name>/inputs/. Set when the run is made on the step the task
1411
+ * reaches; fan-out instances and an on-fail rescue inherit it; a re-run
1412
+ * sets it on the first step it runs. */
1413
+ inputsTurn?: boolean;
1399
1414
  /** On an isolated sub-agent's run: the workspace paths its sandbox's
1400
1415
  * changes were applied to — what its delegating step is told it wrote. */
1401
1416
  wrote?: string[];
@@ -1642,6 +1657,21 @@ export interface RunRecord {
1642
1657
  snapshot?: {
1643
1658
  id: string;
1644
1659
  };
1660
+ /** FOL-162: the conversation this run belongs to — the id its caller
1661
+ * gave and the key it is found by (conversation.ts). Set when the run
1662
+ * is made, carried onto a re-run. */
1663
+ context?: RunContext;
1664
+ /** What the run was asked, as given: the task of an agent or flow run,
1665
+ * an A2A message's text and data. Kept on a run with a `context`, so a
1666
+ * later turn reads the question, never a step's decorated instruction. */
1667
+ input?: RunInput;
1668
+ /** FOL-163: the files the run was handed — storage paths and the blob each
1669
+ * named when the run was made (held for it; storage.ts holdRunInputs). */
1670
+ inputs?: RunInputFile[];
1671
+ /** FOL-168: which of the partner's own users this run is for — an opaque
1672
+ * id the partner maps (customer.ts). Limits, blocks and the provider's
1673
+ * end-user id follow it. Set when the run is made, carried on a re-run. */
1674
+ customer?: string;
1645
1675
  steps: StepRecord[];
1646
1676
  }
1647
1677
  /** Merge one part (the input, on the call; the output, on its completion)
@@ -1796,6 +1826,10 @@ export interface RunSummary {
1796
1826
  task: string;
1797
1827
  key: string;
1798
1828
  };
1829
+ /** RunRecord.context: the conversation it belongs to (FOL-162). */
1830
+ context?: RunContext;
1831
+ /** RunRecord.customer (FOL-168). */
1832
+ customer?: string;
1799
1833
  steps: RunSummaryStep[];
1800
1834
  }
1801
1835
  /** One run's row. */
package/dist/src/store.js CHANGED
@@ -2984,7 +2984,14 @@ export function deleteRun(tenant, workspace, runId, opts = {}) {
2984
2984
  const file = runFilePath(tenant, workspace, runId);
2985
2985
  const dir = path.join(workspaceDir(tenant, workspace), "runs", runId);
2986
2986
  const port = records(tenant, workspace);
2987
- const had = port ? port.runGet(tenant, workspace, runId) !== null : fs.existsSync(file);
2987
+ let prior = null;
2988
+ try {
2989
+ prior = port ? port.runGet(tenant, workspace, runId) : fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, "utf8")) : null;
2990
+ }
2991
+ catch {
2992
+ prior = null; // a half-written record still goes
2993
+ }
2994
+ const had = port ? prior !== null : fs.existsSync(file);
2988
2995
  if (!had && !fs.existsSync(dir))
2989
2996
  return false;
2990
2997
  // The folder first (archived outputs, captured calls), the record last:
@@ -2998,6 +3005,12 @@ export function deleteRun(tenant, workspace, runId, opts = {}) {
2998
3005
  fs.rmSync(file, { force: true });
2999
3006
  noteRunDeleted(path.dirname(file), runId);
3000
3007
  }
3008
+ // Its held inputs go with it (FOL-163): a blob nothing else names is
3009
+ // collected. Asynchronous, and never the delete's failure — storage's own
3010
+ // sweep (sweepHeldInputs) finds any a crash left behind.
3011
+ if (prior?.inputs?.length) {
3012
+ void import("./storage.js").then((m) => m.releaseRunInputs(tenant, workspace, runId)).catch(() => { });
3013
+ }
3001
3014
  if (!had)
3002
3015
  return true;
3003
3016
  // The retention window's prune (`pruned`) is policy, not a person erasing
@@ -3267,6 +3280,8 @@ export function summarizeRun(run) {
3267
3280
  ...(run.revision ? { revision: run.revision } : {}),
3268
3281
  ...(run.trigger ? { trigger: run.trigger } : {}),
3269
3282
  ...(run.a2a ? { a2a: run.a2a } : {}),
3283
+ ...(run.context ? { context: run.context } : {}),
3284
+ ...(run.customer ? { customer: run.customer } : {}),
3270
3285
  awaitingApproval: run.steps.some((s) => s.status === "awaiting-approval" && s.waitFor !== "event"),
3271
3286
  steps: run.steps.map((s) => {
3272
3287
  // A failed step's last error — and, on a run that failed between