@foldrun/core 21.2.0 → 22.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.
@@ -1,3 +1,4 @@
1
+ import { type CapturedCall } from "./store.ts";
1
2
  import type { CallIo } from "./step-exec.ts";
2
3
  /** How much past the cap a step sends, so masking sees a secret whole
3
4
  * before the cut (a value longer than this is a file secret, which is also
@@ -21,9 +22,5 @@ export declare function maskCall(text: string, redactSecrets: (text: string) =>
21
22
  export declare function recordCallIo(workspaceRoot: string, runId: string, callId: string, tool: string, io: CallIo,
22
23
  /** The step's own scrub: its resolved secret values → `[redacted:NAME]`. */
23
24
  redactSecrets: (text: string) => string,
24
- /** Whose run it is: with it the call is kept where the platform keeps a
25
- * workspace's small state (rows), without it beside the run as a file. */
26
- scope?: {
27
- tenant: string;
28
- workspace: string;
29
- }): boolean;
25
+ /** Where the part goes instead of the file beside the run (captured-calls.ts). */
26
+ sink?: (part: CapturedCall) => boolean): boolean;
@@ -98,13 +98,12 @@ export function maskCall(text, redactSecrets) {
98
98
  export function recordCallIo(workspaceRoot, runId, callId, tool, io,
99
99
  /** The step's own scrub: its resolved secret values → `[redacted:NAME]`. */
100
100
  redactSecrets,
101
- /** Whose run it is: with it the call is kept where the platform keeps a
102
- * workspace's small state (rows), without it beside the run as a file. */
103
- scope) {
101
+ /** Where the part goes instead of the file beside the run (captured-calls.ts). */
102
+ sink) {
104
103
  try {
105
104
  const input = io.input === undefined ? null : maskCall(io.input, redactSecrets);
106
105
  const output = io.output === undefined ? null : maskCall(io.output, redactSecrets);
107
- writeCapturedCall(workspaceRoot, runId, {
106
+ const part = {
108
107
  id: callId,
109
108
  tool,
110
109
  // Which part was cut, each on its own: in the sandbox (the whole was
@@ -112,7 +111,10 @@ scope) {
112
111
  ...(input ? { input: input.text, ...(io.inputChars !== undefined ? { inputChars: io.inputChars } : {}), ...(input.cut || (io.inputChars ?? 0) > io.input.length ? { inputCut: true } : {}) } : {}),
113
112
  ...(output ? { output: output.text, ...(io.outputChars !== undefined ? { outputChars: io.outputChars } : {}), ...(output.cut || (io.outputChars ?? 0) > io.output.length ? { outputCut: true } : {}) } : {}),
114
113
  ...(io.truncated || input?.cut || output?.cut ? { truncated: true } : {}),
115
- }, scope);
114
+ };
115
+ if (sink)
116
+ return sink(part);
117
+ writeCapturedCall(workspaceRoot, runId, part);
116
118
  return true;
117
119
  }
118
120
  catch (err) {
@@ -0,0 +1,30 @@
1
+ import type { Deps } from "./publish.ts";
2
+ import { type CapturedCall } from "./store.ts";
3
+ /** Registered with the revision backend (workspace-revisions.ts): the blob store and the pins. */
4
+ export declare function setCallsBackend(deps: Deps | null): void;
5
+ /** The call could not be read back from where it was recorded. */
6
+ export declare class CapturedCallUnavailable extends Error {
7
+ constructor(callId: string, cause?: unknown);
8
+ }
9
+ interface Ctx {
10
+ tenant: string;
11
+ workspace: string;
12
+ runId: string;
13
+ workspaceRoot: string;
14
+ }
15
+ /**
16
+ * The runner's place to put a call's part (input on the call, output on its
17
+ * completion). Returns whether it was taken (the event says `captured`).
18
+ * `owner` is the step: flushCalls(owner) settles what it left.
19
+ */
20
+ export declare function callSink(owner: object, ctx: Ctx): (part: CapturedCall) => boolean;
21
+ /** The step ended: write the inputs that never got an output, wait for every write. Never throws. */
22
+ export declare function flushCalls(owner: object): Promise<void>;
23
+ /** One recorded call, or null (not recorded). The row first, then the file. */
24
+ export declare function readCapturedCallAsync(tenant: string, workspace: string, runId: string, callId: string): Promise<CapturedCall | null>;
25
+ /** What the run-delete hook started and has not finished (tests, a process that is ending). */
26
+ export declare function settleCalls(): Promise<void>;
27
+ /** A workspace is being deleted (its rows still there): release the pin of every run that has calls
28
+ * in the store. Throws when the pins cannot be reached, so the delete can be retried. */
29
+ export declare function dropWorkspaceCalls(tenant: string, workspace: string): Promise<void>;
30
+ export {};
@@ -0,0 +1,219 @@
1
+ // Captured tool calls in the blob store (FOL-126 phase 7, step 2).
2
+ //
3
+ // A call's masked input and output used to be a file beside its run
4
+ // (runs/<run>/calls/<call>.json — store.ts writeCapturedCall), merged in place
5
+ // when the output arrived. With a database, a blob store and the setting
6
+ // `runs.calls_store` on, each call is ONE blob, written once when the call
7
+ // completes (the input waits in memory for its output: no read-merge-write),
8
+ // pinned by a run holder (`calls:<run>`, no lease — it lives until the run is
9
+ // deleted) before the upload, and indexed by a step-state row (kind "call",
10
+ // ref = the call id → {sha, size}). Masking is capture.ts's and is done before
11
+ // anything gets here; a part over the cap was cut and flagged there.
12
+ //
13
+ // Reads look at the row first, then at the file, so every run stays readable
14
+ // whichever way the switch is set. A row whose blob cannot be read is an error
15
+ // (CapturedCallUnavailable), never "nothing recorded".
16
+ //
17
+ // TEMPORARY, remove at cutover (phase 9): a write that fails with an error
18
+ // (store down, database refuses) falls back to the volume file and logs
19
+ // `captured_calls.fallback`. At cutover that branch becomes "the call is not
20
+ // recorded, and the event says so".
21
+ import { records } from "./records.js";
22
+ import { blobObjectKey, sha256Hex } from "./manifest.js";
23
+ import { opsError } from "./ops-log.js";
24
+ import { BlobNotFound, readAll } from "./blob-store.js";
25
+ import { writeCapturedCall, readCapturedCall, registerRunRemovedHook } from "./store.js";
26
+ import { processState } from "./process-state.js";
27
+ const KIND = "call";
28
+ const SAFE = /^[A-Za-z0-9_.-]{1,128}$/;
29
+ const holderOf = (runId) => ({ kind: "run", id: `calls:${runId}` });
30
+ /** One per process (process-state.ts): the store the boot registered and the
31
+ * clean-ups in flight, whichever copy of this module a route handler holds. */
32
+ const CALLS = processState("captured-calls", () => ({ backend: null, background: new Set() }));
33
+ /** Registered with the revision backend (workspace-revisions.ts): the blob store and the pins. */
34
+ export function setCallsBackend(deps) {
35
+ CALLS.backend = deps;
36
+ registerRunRemovedHook(deps ? runGone : null, "captured-calls");
37
+ }
38
+ /** The call could not be read back from where it was recorded. */
39
+ export class CapturedCallUnavailable extends Error {
40
+ constructor(callId, cause) {
41
+ super(`captured call unavailable: the recorded content of call "${callId}" could not be read from storage`);
42
+ this.name = "CapturedCallUnavailable";
43
+ if (cause !== undefined)
44
+ this.cause = cause;
45
+ }
46
+ }
47
+ const portFor = (tenant, workspace) => {
48
+ const p = records(tenant, workspace);
49
+ // stepRuns too: without it a deleted workspace's calls could never be
50
+ // found again to release their pins (Codex review, 13 Nov 2026).
51
+ return p?.async?.stepPut && p.async.stepGet && p.async.stepRuns ? p : null;
52
+ };
53
+ const switchedOn = (p) => {
54
+ try {
55
+ return p.callsStoreOn?.() === true;
56
+ }
57
+ catch {
58
+ return false;
59
+ }
60
+ };
61
+ /** Where a new call goes: the store (deps + port), or null (the volume). */
62
+ function active(tenant, workspace) {
63
+ const deps = CALLS.backend;
64
+ const port = portFor(tenant, workspace);
65
+ return deps && port && switchedOn(port) ? { deps, port } : null;
66
+ }
67
+ const merge = (prev, part) => {
68
+ const next = { ...prev, ...part, truncated: Boolean(prev?.truncated || part.truncated) || undefined };
69
+ if (!next.truncated)
70
+ delete next.truncated;
71
+ return next;
72
+ };
73
+ const sessions = new WeakMap();
74
+ /** One blob per call: pin, upload, then the row that names it. */
75
+ async function storeCall(ctx, call) {
76
+ const a = active(ctx.tenant, ctx.workspace);
77
+ const fall = (err) => {
78
+ // TEMPORARY (see the header): the volume copy, so the call is not lost.
79
+ opsError("captured_calls.fallback", err, { tenant: ctx.tenant, workspace: ctx.workspace, runId: ctx.runId, callId: call.id });
80
+ try {
81
+ writeCapturedCall(ctx.workspaceRoot, ctx.runId, call);
82
+ }
83
+ catch (e) {
84
+ opsError("capture.write_failed", e, { runId: ctx.runId });
85
+ }
86
+ };
87
+ if (!a)
88
+ return fall(new Error("the call store went away before the call was written"));
89
+ try {
90
+ const bytes = Buffer.from(JSON.stringify(call));
91
+ const sha = sha256Hex(bytes);
92
+ await a.deps.pins?.pinBlobs(ctx.tenant, [sha], holderOf(ctx.runId));
93
+ await a.deps.blobs.putIfAbsent(blobObjectKey(ctx.tenant, sha), bytes, { contentType: "application/json" });
94
+ await a.port.async.stepPut(ctx.tenant, ctx.workspace, ctx.runId, KIND, call.id, { sha, size: bytes.length });
95
+ }
96
+ catch (err) {
97
+ fall(err);
98
+ }
99
+ }
100
+ /**
101
+ * The runner's place to put a call's part (input on the call, output on its
102
+ * completion). Returns whether it was taken (the event says `captured`).
103
+ * `owner` is the step: flushCalls(owner) settles what it left.
104
+ */
105
+ export function callSink(owner, ctx) {
106
+ const s = { ctx, pending: new Map(), writes: new Set() };
107
+ sessions.set(owner, s);
108
+ return (part) => {
109
+ if (!SAFE.test(part.id) || !SAFE.test(ctx.runId))
110
+ return false;
111
+ const live = active(ctx.tenant, ctx.workspace);
112
+ const waiting = s.pending.get(part.id);
113
+ if (live && part.output === undefined) {
114
+ s.pending.set(part.id, merge(waiting, part));
115
+ return true;
116
+ }
117
+ s.pending.delete(part.id);
118
+ // A call whose input went to the volume before the switch flipped, or on another worker.
119
+ const prev = waiting ?? (live ? readCapturedCall(ctx.tenant, ctx.workspace, ctx.runId, part.id) ?? undefined : undefined);
120
+ const whole = merge(prev, part);
121
+ if (!live) {
122
+ writeCapturedCall(ctx.workspaceRoot, ctx.runId, whole);
123
+ return true;
124
+ }
125
+ const w = storeCall(ctx, whole).finally(() => s.writes.delete(w));
126
+ s.writes.add(w);
127
+ return true;
128
+ };
129
+ }
130
+ /** The step ended: write the inputs that never got an output, wait for every write. Never throws. */
131
+ export async function flushCalls(owner) {
132
+ const s = sessions.get(owner);
133
+ if (!s)
134
+ return;
135
+ sessions.delete(owner);
136
+ for (const call of s.pending.values()) {
137
+ if (active(s.ctx.tenant, s.ctx.workspace))
138
+ s.writes.add(storeCall(s.ctx, call));
139
+ else {
140
+ try {
141
+ writeCapturedCall(s.ctx.workspaceRoot, s.ctx.runId, call);
142
+ }
143
+ catch (err) {
144
+ opsError("capture.write_failed", err, { runId: s.ctx.runId });
145
+ }
146
+ }
147
+ }
148
+ s.pending.clear();
149
+ await Promise.allSettled([...s.writes]);
150
+ }
151
+ /** One recorded call, or null (not recorded). The row first, then the file. */
152
+ export async function readCapturedCallAsync(tenant, workspace, runId, callId) {
153
+ if (!SAFE.test(runId) || !SAFE.test(callId) || callId.startsWith(".") || runId.startsWith("."))
154
+ return null;
155
+ const port = portFor(tenant, workspace);
156
+ if (port) {
157
+ let row;
158
+ try {
159
+ row = (await port.async.stepGet(tenant, workspace, runId, KIND, callId));
160
+ }
161
+ catch (err) {
162
+ throw new CapturedCallUnavailable(callId, err);
163
+ }
164
+ if (row) {
165
+ try {
166
+ if (!CALLS.backend || typeof row.sha !== "string")
167
+ throw new Error("the call store is not available here");
168
+ const call = JSON.parse((await readAll(CALLS.backend.blobs, blobObjectKey(tenant, row.sha))).toString("utf8"));
169
+ if (!call || typeof call !== "object" || call.id !== callId)
170
+ throw new Error("the stored object is not this call");
171
+ return call;
172
+ }
173
+ catch (err) {
174
+ if (!(err instanceof BlobNotFound))
175
+ opsError("captured_calls.read_failed", err, { tenant, workspace, runId, callId });
176
+ throw new CapturedCallUnavailable(callId, err);
177
+ }
178
+ }
179
+ }
180
+ return readCapturedCall(tenant, workspace, runId, callId);
181
+ }
182
+ // ---------------------------------------------------------------- lifecycle
183
+ /** What the run-delete hook started and has not finished (tests, a process that is ending). */
184
+ export async function settleCalls() {
185
+ while (CALLS.background.size)
186
+ await Promise.allSettled([...CALLS.background]);
187
+ }
188
+ /** A run was deleted: its calls' pin goes (the rows went with it; the sweeper takes the blobs). */
189
+ function runGone(tenant, _workspace, runId) {
190
+ const deps = CALLS.backend;
191
+ if (!deps?.pins || !SAFE.test(runId))
192
+ return;
193
+ const p = (async () => {
194
+ for (let attempt = 0;; attempt++) {
195
+ try {
196
+ await deps.pins.release(tenant, holderOf(runId));
197
+ return;
198
+ }
199
+ catch (err) {
200
+ // A pin that cannot be released is kept: a leak is safe, a loss is not.
201
+ if (attempt >= 4)
202
+ return opsError("captured_calls.drop_failed", err, { tenant, runId });
203
+ await new Promise((r) => setTimeout(r, 1000 * 2 ** attempt));
204
+ }
205
+ }
206
+ })();
207
+ const q = p.finally(() => CALLS.background.delete(q));
208
+ CALLS.background.add(q);
209
+ }
210
+ /** A workspace is being deleted (its rows still there): release the pin of every run that has calls
211
+ * in the store. Throws when the pins cannot be reached, so the delete can be retried. */
212
+ export async function dropWorkspaceCalls(tenant, workspace) {
213
+ const deps = CALLS.backend;
214
+ const port = records(tenant, workspace);
215
+ if (!deps?.pins || !port?.async?.stepRuns)
216
+ return;
217
+ for (const runId of await port.async.stepRuns(tenant, workspace, KIND))
218
+ await deps.pins.release(tenant, holderOf(runId));
219
+ }
@@ -23,11 +23,13 @@ export interface RecordsPortAsync {
23
23
  stepPut?(tenant: string, workspace: string, runId: string, kind: string, ref: string, data: unknown): Promise<void>;
24
24
  /** `ref` null: every ref of the kind. */
25
25
  stepDrop?(tenant: string, workspace: string, runId: string, kind: string, ref: string | null): Promise<void>;
26
+ /** The ids of the runs that have rows of this kind in the workspace. */
27
+ stepRuns?(tenant: string, workspace: string, kind: string): Promise<string[]>;
26
28
  }
27
29
  /** Small per-workspace state that used to be files in the workspace's folder
28
30
  * (FOL-126, the last files on the volume): webhook generations and the
29
31
  * delivery log, eval results and their history, grades and grader cursors,
30
- * the deployed commit, captured tool calls. Two shapes: a DOCUMENT per
32
+ * the deployed commit. Two shapes: a DOCUMENT per
31
33
  * (kind, key), and an append-only LOG per kind. Synchronous like the rest of
32
34
  * the port; workspace-docs.ts is the only caller. */
33
35
  export interface DocsPort {
@@ -72,6 +74,9 @@ export interface RecordsPort {
72
74
  * state is written to the run's folder as before (it is still READ from
73
75
  * rows first, so switching off mid-run loses nothing). */
74
76
  stepStateOn?(): boolean;
77
+ /** The `runs.calls_store` setting, read per call: while false, a captured
78
+ * call is written to the run's folder as before (captured-calls.ts). */
79
+ callsStoreOn?(): boolean;
75
80
  /** Insert or replace one run. `live`: queued, running or parked at a gate. Last write wins. */
76
81
  runPut(tenant: string, workspace: string, run: RunRecord, summary: RunSummary, live: boolean): void;
77
82
  runGet(tenant: string, workspace: string, id: string): RunRecord | null;
@@ -6,6 +6,7 @@ import { opsLog, opsError } from "./ops-log.js";
6
6
  import { globMatch } from "./bounded-match.js";
7
7
  import { latestRevisionId } from "./history.js";
8
8
  import { recordCallIo, redactionsFor } from "./capture.js";
9
+ import { callSink, flushCalls } from "./captured-calls.js";
9
10
  import { AUTH_REFUSAL, platformCause } from "./issues.js";
10
11
  import { hookNames } from "./hooks.js";
11
12
  import crypto from "node:crypto";
@@ -65,7 +66,7 @@ import { buildScriptTools, parseScripts } from "./script-tools.js";
65
66
  import { libraryDir, libraryTools, libraryMemoryIndex } from "./library.js";
66
67
  import { fingerprint, mergeRuntimes, parseRuntime, prepareRuntime, stepInstallEnv } from "./runtime.js";
67
68
  import { buildInstallTool, INSTALL_TOOL } from "./install-tool.js";
68
- import { dataRoot, singleWorkspace } from "./paths.js";
69
+ import { dataRoot } from "./paths.js";
69
70
  import { materializeFiles, harvestFiles, storageBaseline } from "./storage.js";
70
71
  import { readStorageBaseline, writeStorageBaseline } from "./step-state.js";
71
72
  import { chooseExecutor, ensureImage } from "./container.js";
@@ -2014,7 +2015,16 @@ export function operatorBlock(step, workspaceRoot) {
2014
2015
  }
2015
2016
  return "";
2016
2017
  }
2017
- async function runStep(agentDir, tenant, step, context, save, modelOverride, tags = [], effortOverride, runId,
2018
+ /** A step, and then whatever its captured calls still hold (captured-calls.ts). */
2019
+ async function runStep(...args) {
2020
+ try {
2021
+ return await runStepBody(...args);
2022
+ }
2023
+ finally {
2024
+ await flushCalls(args[2]);
2025
+ }
2026
+ }
2027
+ async function runStepBody(agentDir, tenant, step, context, save, modelOverride, tags = [], effortOverride, runId,
2018
2028
  /** What the previous group returned as DATA (an `output: json` step's
2019
2029
  * value), beside the prose in `context`. Undefined when nothing did. */
2020
2030
  priorData,
@@ -2122,6 +2132,8 @@ conversation) {
2122
2132
  // calls keep their names, sizes and times (FOL-54 step 4).
2123
2133
  let capturedChars = 0;
2124
2134
  let captureFull = false;
2135
+ const callsRoot = path.resolve(agentDir, "..", "..");
2136
+ const sink = runId ? callSink(step, { tenant, workspace: path.basename(callsRoot), runId, workspaceRoot: callsRoot }) : undefined;
2125
2137
  const push = (type, text, extra) => {
2126
2138
  const t = new Date().toISOString();
2127
2139
  // The model has begun its first response: held only in memory, for
@@ -2158,7 +2170,7 @@ conversation) {
2158
2170
  captureFull = true;
2159
2171
  step.events.push({ t, type: "info", text: `capture: this step recorded ${Math.round(capturedChars / 1000)}k characters of tool content — the rest of its calls keep only their names, sizes and times` });
2160
2172
  }
2161
- if (runId && extra.call && capture === "full" && !captureFull && recordCallIo(path.resolve(agentDir, "..", ".."), runId, extra.call, text, io, redact, singleWorkspace() ? undefined : { tenant, workspace: path.basename(path.resolve(agentDir, "..", "..")) })) {
2173
+ if (runId && extra.call && capture === "full" && !captureFull && recordCallIo(callsRoot, runId, extra.call, text, io, redact, sink)) {
2162
2174
  capturedChars += size;
2163
2175
  rest = { ...others, captured: true };
2164
2176
  }
@@ -1691,10 +1691,7 @@ export interface RunRecord {
1691
1691
  }
1692
1692
  /** Merge one part (the input, on the call; the output, on its completion)
1693
1693
  * into the call's file. */
1694
- export declare function writeCapturedCall(workspaceRoot: string, runId: string, part: CapturedCall, scope?: {
1695
- tenant: string;
1696
- workspace: string;
1697
- }): void;
1694
+ export declare function writeCapturedCall(workspaceRoot: string, runId: string, part: CapturedCall): void;
1698
1695
  /** One recorded call of a run, or null (not recorded, or not a call). */
1699
1696
  export declare function readCapturedCall(tenant: string, workspace: string, runId: string, callId: string): CapturedCall | null;
1700
1697
  export declare function runFilePath(tenant: string, workspace: string, runId: string): string;
@@ -1716,9 +1713,11 @@ export declare function runFilePath(tenant: string, workspace: string, runId: st
1716
1713
  export declare function deleteRun(tenant: string, workspace: string, runId: string, opts?: {
1717
1714
  pruned?: boolean;
1718
1715
  }): boolean;
1719
- /** run-outputs.ts registers here (it imports this module). */
1716
+ /** run-outputs.ts and captured-calls.ts register here (they import this module). */
1720
1717
  type RunHook = (tenant: string, workspace: string, runId: string) => void;
1721
- export declare function registerRunRemovedHook(fn: RunHook | null): void;
1718
+ /** A run's content lives somewhere other than its folder: `name` says whose hook
1719
+ * this is, so one registering (or clearing, with null) never replaces another's. */
1720
+ export declare function registerRunRemovedHook(fn: RunHook | null, name?: string): void;
1722
1721
  /** ledger.ts registers here — store cannot import it without a cycle, and
1723
1722
  * money must not depend on one. */
1724
1723
  export declare function registerRunDeletionListener(fn: RunHook | undefined): void;
package/dist/src/store.js CHANGED
@@ -19,6 +19,7 @@
19
19
  // or an agent, and belongs in git.
20
20
  //
21
21
  // An account is a named directory (per OKF: tenancy is a hosting concern).
22
+ import { opsError } from "./ops-log.js";
22
23
  import { readCompute } from "./resources.js";
23
24
  import { expandPlatformVars } from "./host-env.js";
24
25
  import { FLOW_TRIGGERS } from "./frontmatter-fields.js";
@@ -29,7 +30,7 @@ import { processState } from "./process-state.js";
29
30
  import { dataRoot, singleWorkspace, singleAccountRoot, entriesNoFollow } from "./paths.js";
30
31
  import { platform } from "./platform.js";
31
32
  import { records } from "./records.js";
32
- import { docRows, docStore, quietly } from "./workspace-docs.js";
33
+ import { docRows, quietly } from "./workspace-docs.js";
33
34
  import { toLF, asRaw } from "./eol.js";
34
35
  import matter, { frontmatterErrorText, configMatter } from "./matter.js";
35
36
  import { readAgentsMdKeys, patchFrontmatter } from "./agents-md.js";
@@ -2925,7 +2926,9 @@ export function isSplicedRecord(step) {
2925
2926
  // and every page reads whole, and gone with the run (deleteRun removes
2926
2927
  // runs/<run>/). The runner writes them, secrets already masked.
2927
2928
  const SAFE_ID = /^[A-Za-z0-9_.-]{1,128}$/;
2928
- const CALL_KIND = "call";
2929
+ /** Captured calls kept as rows for one day on dev (13 Nov 2026); read and
2930
+ * dropped with their run, never written again. */
2931
+ const LEGACY_CALL_KIND = "call";
2929
2932
  function capturedCallFile(workspaceRoot, runId, callId) {
2930
2933
  if (!SAFE_ID.test(runId) || !SAFE_ID.test(callId) || callId.startsWith(".") || runId.startsWith("."))
2931
2934
  return null;
@@ -2933,16 +2936,10 @@ function capturedCallFile(workspaceRoot, runId, callId) {
2933
2936
  }
2934
2937
  /** Merge one part (the input, on the call; the output, on its completion)
2935
2938
  * into the call's file. */
2936
- export function writeCapturedCall(workspaceRoot, runId, part, scope) {
2939
+ export function writeCapturedCall(workspaceRoot, runId, part) {
2937
2940
  const file = capturedCallFile(workspaceRoot, runId, part.id);
2938
2941
  if (!file)
2939
2942
  return;
2940
- // A row when the platform keeps them (FOL-126): the two parts of a call
2941
- // merge in one statement, and the web's copies read it wherever they run.
2942
- // `truncated` is only ever sent true, so a merge keeps it once set.
2943
- const store = scope ? docStore(scope.tenant, scope.workspace) : null;
2944
- if (store && scope)
2945
- return store.merge(scope.tenant, scope.workspace, CALL_KIND, `${runId}/${part.id}`, part);
2946
2943
  let prev = {};
2947
2944
  try {
2948
2945
  prev = JSON.parse(fs.readFileSync(file, "utf8"));
@@ -2963,22 +2960,17 @@ export function readCapturedCall(tenant, workspace, runId, callId) {
2963
2960
  const file = capturedCallFile(workspaceDir(tenant, workspace), runId, callId);
2964
2961
  if (!file)
2965
2962
  return null;
2966
- const row = quietly(() => docRows(tenant, workspace)?.get(tenant, workspace, CALL_KIND, `${runId}/${callId}`), undefined);
2967
- let onFile;
2963
+ // A call kept as a workspace_docs row (records.docs_store, 13 Nov 2026,
2964
+ // before calls went to the blob store): still read until its run goes.
2965
+ const legacy = quietly(() => docRows(tenant, workspace)?.get(tenant, workspace, LEGACY_CALL_KIND, `${runId}/${callId}`), undefined);
2966
+ if (legacy)
2967
+ return legacy;
2968
2968
  try {
2969
- onFile = JSON.parse(fs.readFileSync(file, "utf8"));
2969
+ return JSON.parse(fs.readFileSync(file, "utf8"));
2970
2970
  }
2971
2971
  catch {
2972
- /* none */
2973
- }
2974
- // A switch between a call's two parts leaves one part in each place: both, merged.
2975
- if (row && onFile) {
2976
- const merged = { ...onFile, ...row, truncated: Boolean(onFile.truncated || row.truncated) || undefined };
2977
- if (!merged.truncated)
2978
- delete merged.truncated;
2979
- return merged;
2972
+ return null;
2980
2973
  }
2981
- return row ?? onFile ?? null;
2982
2974
  }
2983
2975
  export function runFilePath(tenant, workspace, runId) {
2984
2976
  assertSafeName(runId, "run id");
@@ -3018,9 +3010,8 @@ export function deleteRun(tenant, workspace, runId, opts = {}) {
3018
3010
  // and finishes — the other order left the content with nothing pointing
3019
3011
  // at it (Codex review, FOL-124).
3020
3012
  fs.rmSync(dir, { recursive: true, force: true });
3021
- // Its captured calls kept as rows go the same way, before the record.
3022
3013
  if (SAFE_ID.test(runId))
3023
- docRows(tenant, workspace)?.dropPrefix(tenant, workspace, CALL_KIND, `${runId}/`);
3014
+ quietly(() => docRows(tenant, workspace)?.dropPrefix(tenant, workspace, LEGACY_CALL_KIND, `${runId}/`), undefined);
3024
3015
  if (port)
3025
3016
  port.runDelete(tenant, workspace, runId);
3026
3017
  else {
@@ -3033,9 +3024,18 @@ export function deleteRun(tenant, workspace, runId, opts = {}) {
3033
3024
  if (prior?.inputs?.length) {
3034
3025
  void import("./storage.js").then((m) => m.releaseRunInputs(tenant, workspace, runId)).catch(() => { });
3035
3026
  }
3036
- // Outputs published to the blob store (run-outputs.ts) are records and pins,
3037
- // not files under dir: they go in the background, retried.
3038
- RUN_HOOKS.removed?.(tenant, workspace, runId);
3027
+ // Outputs and captured calls published to the blob store (run-outputs.ts,
3028
+ // captured-calls.ts) are records and pins, not files under dir: they go in
3029
+ // the background, retried.
3030
+ for (const [name, hook] of RUN_HOOKS.removed) {
3031
+ try {
3032
+ hook(tenant, workspace, runId);
3033
+ }
3034
+ catch (err) {
3035
+ // One store's clean-up failing must not stop the next one's.
3036
+ opsError("run_removed_hook.failed", err, { hook: name, tenant, runId });
3037
+ }
3038
+ }
3039
3039
  if (!had)
3040
3040
  return true;
3041
3041
  // The retention window's prune (`pruned`) is policy, not a person erasing
@@ -3046,9 +3046,14 @@ export function deleteRun(tenant, workspace, runId, opts = {}) {
3046
3046
  }
3047
3047
  /** One per process (process-state.ts): a run deleted from a route handler must
3048
3048
  * reach the hooks the boot registered. */
3049
- const RUN_HOOKS = processState("run-hooks", () => ({ removed: null, deleted: undefined }));
3050
- export function registerRunRemovedHook(fn) {
3051
- RUN_HOOKS.removed = fn;
3049
+ const RUN_HOOKS = processState("run-hooks", () => ({ removed: new Map(), deleted: undefined }));
3050
+ /** A run's content lives somewhere other than its folder: `name` says whose hook
3051
+ * this is, so one registering (or clearing, with null) never replaces another's. */
3052
+ export function registerRunRemovedHook(fn, name = "run-outputs") {
3053
+ if (fn)
3054
+ RUN_HOOKS.removed.set(name, fn);
3055
+ else
3056
+ RUN_HOOKS.removed.delete(name);
3052
3057
  }
3053
3058
  /** ledger.ts registers here — store cannot import it without a cycle, and
3054
3059
  * money must not depend on one. */
@@ -46,6 +46,7 @@ import { AUTHORED_DIRS, AUTHORED_ROOT_FILES, STATE_DIRS, assertManifestPath, blo
46
46
  import { headsOf, loadManifest, manifestsAt, manifestsOf, publish, restore, requestDigest, stateOpId, BlobMissing, PublishError } from "./publish.js";
47
47
  import { OpIdReused } from "./revision-store.js";
48
48
  import { pruneStateRevisions } from "./state-retention.js";
49
+ import { setCallsBackend, dropWorkspaceCalls, settleCalls } from "./captured-calls.js";
49
50
  import { dropTenantOutputs, dropWorkspaceOutputs, moveWorkspaceOutputs, settleRunOutputs } from "./run-outputs.js";
50
51
  // ------------------------------------------------------------- the backend
51
52
  /** Everything this module is told at boot, and every queue that goes with it,
@@ -93,6 +94,7 @@ export function setRevisionBackend(deps, opts = {}) {
93
94
  S.retentionEvery = opts.retentionEveryMs ?? 10 * 60_000;
94
95
  S.orphanMarks = opts.sweepMarks ?? null;
95
96
  S.orphanGrace = opts.orphanGraceMs ?? 3_600_000;
97
+ setCallsBackend(deps);
96
98
  registerJournal(deps ? journalChange : null);
97
99
  registerWorkspaceGone(deps ? (t, w) => goneNow(t, w) : null);
98
100
  registerWorkspaceLifecycle(deps ? { drop: dropWorkspaceRevisions, move: moveWorkspaceRevisions, moved: movedNow } : null);
@@ -454,6 +456,7 @@ export async function settleLifecycle() {
454
456
  while (background.size)
455
457
  await Promise.allSettled([...background]);
456
458
  await settleRunOutputs();
459
+ await settleCalls();
457
460
  }
458
461
  function inBackground(p) {
459
462
  const q = p.finally(() => background.delete(q));
@@ -501,6 +504,8 @@ export async function dropWorkspaceRevisions(tenant, workspace, remove) {
501
504
  dropJournal(tenant, workspace);
502
505
  await before?.catch(() => { });
503
506
  try {
507
+ // Its captured calls' pins, while the rows that name the runs are still there.
508
+ await dropWorkspaceCalls(tenant, workspace);
504
509
  await deps.revisions.drop({ tenant, workspace });
505
510
  // The run outputs published to the blob store (run-outputs.ts) are this workspace's too.
506
511
  await dropWorkspaceOutputs(tenant, workspace);
@@ -513,6 +518,7 @@ export async function dropWorkspaceRevisions(tenant, workspace, remove) {
513
518
  }
514
519
  remove?.();
515
520
  dropJournal(tenant, workspace);
521
+ await dropWorkspaceCalls(tenant, workspace);
516
522
  await deps.revisions.drop({ tenant, workspace });
517
523
  await dropWorkspaceOutputs(tenant, workspace);
518
524
  marked.delete(k);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foldrun/core",
3
- "version": "21.2.0",
3
+ "version": "22.0.0",
4
4
  "description": "Agents are just folders. The format, the runner, the checks.",
5
5
  "license": "FSL-1.1-ALv2",
6
6
  "type": "module",
package/src/capture.ts CHANGED
@@ -7,7 +7,7 @@
7
7
 
8
8
  import { opsError } from "./ops-log.ts";
9
9
  import { redactText } from "./scan.ts";
10
- import { writeCapturedCall, CAPTURE_CAP } from "./store.ts";
10
+ import { writeCapturedCall, CAPTURE_CAP, type CapturedCall } from "./store.ts";
11
11
  import { isFileValue, fileContent, isApiValue, apiConfigOf, isClientCertValue, clientCertOf } from "./secrets.ts";
12
12
  import type { CallIo } from "./step-exec.ts";
13
13
 
@@ -100,14 +100,13 @@ export function recordCallIo(
100
100
  io: CallIo,
101
101
  /** The step's own scrub: its resolved secret values → `[redacted:NAME]`. */
102
102
  redactSecrets: (text: string) => string,
103
- /** Whose run it is: with it the call is kept where the platform keeps a
104
- * workspace's small state (rows), without it beside the run as a file. */
105
- scope?: { tenant: string; workspace: string },
103
+ /** Where the part goes instead of the file beside the run (captured-calls.ts). */
104
+ sink?: (part: CapturedCall) => boolean,
106
105
  ): boolean {
107
106
  try {
108
107
  const input = io.input === undefined ? null : maskCall(io.input, redactSecrets);
109
108
  const output = io.output === undefined ? null : maskCall(io.output, redactSecrets);
110
- writeCapturedCall(workspaceRoot, runId, {
109
+ const part: CapturedCall = {
111
110
  id: callId,
112
111
  tool,
113
112
  // Which part was cut, each on its own: in the sandbox (the whole was
@@ -115,7 +114,9 @@ export function recordCallIo(
115
114
  ...(input ? { input: input.text, ...(io.inputChars !== undefined ? { inputChars: io.inputChars } : {}), ...(input.cut || (io.inputChars ?? 0) > io.input!.length ? { inputCut: true } : {}) } : {}),
116
115
  ...(output ? { output: output.text, ...(io.outputChars !== undefined ? { outputChars: io.outputChars } : {}), ...(output.cut || (io.outputChars ?? 0) > io.output!.length ? { outputCut: true } : {}) } : {}),
117
116
  ...(io.truncated || input?.cut || output?.cut ? { truncated: true } : {}),
118
- }, scope);
117
+ };
118
+ if (sink) return sink(part);
119
+ writeCapturedCall(workspaceRoot, runId, part);
119
120
  return true;
120
121
  } catch (err) {
121
122
  opsError("capture.write_failed", err, { tool, runId });
@@ -0,0 +1,226 @@
1
+ // Captured tool calls in the blob store (FOL-126 phase 7, step 2).
2
+ //
3
+ // A call's masked input and output used to be a file beside its run
4
+ // (runs/<run>/calls/<call>.json — store.ts writeCapturedCall), merged in place
5
+ // when the output arrived. With a database, a blob store and the setting
6
+ // `runs.calls_store` on, each call is ONE blob, written once when the call
7
+ // completes (the input waits in memory for its output: no read-merge-write),
8
+ // pinned by a run holder (`calls:<run>`, no lease — it lives until the run is
9
+ // deleted) before the upload, and indexed by a step-state row (kind "call",
10
+ // ref = the call id → {sha, size}). Masking is capture.ts's and is done before
11
+ // anything gets here; a part over the cap was cut and flagged there.
12
+ //
13
+ // Reads look at the row first, then at the file, so every run stays readable
14
+ // whichever way the switch is set. A row whose blob cannot be read is an error
15
+ // (CapturedCallUnavailable), never "nothing recorded".
16
+ //
17
+ // TEMPORARY, remove at cutover (phase 9): a write that fails with an error
18
+ // (store down, database refuses) falls back to the volume file and logs
19
+ // `captured_calls.fallback`. At cutover that branch becomes "the call is not
20
+ // recorded, and the event says so".
21
+
22
+ import { records } from "./records.ts";
23
+ import { blobObjectKey, sha256Hex } from "./manifest.ts";
24
+ import { opsError } from "./ops-log.ts";
25
+ import { BlobNotFound, readAll } from "./blob-store.ts";
26
+ import type { Deps } from "./publish.ts";
27
+ import { writeCapturedCall, readCapturedCall, registerRunRemovedHook, type CapturedCall } from "./store.ts";
28
+ import { processState } from "./process-state.ts";
29
+
30
+ const KIND = "call";
31
+ const SAFE = /^[A-Za-z0-9_.-]{1,128}$/;
32
+ const holderOf = (runId: string) => ({ kind: "run" as const, id: `calls:${runId}` });
33
+
34
+ /** One per process (process-state.ts): the store the boot registered and the
35
+ * clean-ups in flight, whichever copy of this module a route handler holds. */
36
+ const CALLS = processState("captured-calls", () => ({ backend: null as Deps | null, background: new Set<Promise<unknown>>() }));
37
+
38
+ /** Registered with the revision backend (workspace-revisions.ts): the blob store and the pins. */
39
+ export function setCallsBackend(deps: Deps | null): void {
40
+ CALLS.backend = deps;
41
+ registerRunRemovedHook(deps ? runGone : null, "captured-calls");
42
+ }
43
+
44
+ /** The call could not be read back from where it was recorded. */
45
+ export class CapturedCallUnavailable extends Error {
46
+ constructor(callId: string, cause?: unknown) {
47
+ super(`captured call unavailable: the recorded content of call "${callId}" could not be read from storage`);
48
+ this.name = "CapturedCallUnavailable";
49
+ if (cause !== undefined) this.cause = cause;
50
+ }
51
+ }
52
+
53
+ const portFor = (tenant: string, workspace: string) => {
54
+ const p = records(tenant, workspace);
55
+ // stepRuns too: without it a deleted workspace's calls could never be
56
+ // found again to release their pins (Codex review, 13 Nov 2026).
57
+ return p?.async?.stepPut && p.async.stepGet && p.async.stepRuns ? p : null;
58
+ };
59
+ const switchedOn = (p: { callsStoreOn?(): boolean }): boolean => {
60
+ try {
61
+ return p.callsStoreOn?.() === true;
62
+ } catch {
63
+ return false;
64
+ }
65
+ };
66
+ /** Where a new call goes: the store (deps + port), or null (the volume). */
67
+ function active(tenant: string, workspace: string) {
68
+ const deps = CALLS.backend;
69
+ const port = portFor(tenant, workspace);
70
+ return deps && port && switchedOn(port) ? { deps, port } : null;
71
+ }
72
+
73
+ const merge = (prev: CapturedCall | undefined, part: CapturedCall): CapturedCall => {
74
+ const next: CapturedCall = { ...prev, ...part, truncated: Boolean(prev?.truncated || part.truncated) || undefined };
75
+ if (!next.truncated) delete next.truncated;
76
+ return next;
77
+ };
78
+
79
+ interface Ctx {
80
+ tenant: string;
81
+ workspace: string;
82
+ runId: string;
83
+ workspaceRoot: string;
84
+ }
85
+ interface Session {
86
+ ctx: Ctx;
87
+ /** Inputs waiting for their output. */
88
+ pending: Map<string, CapturedCall>;
89
+ writes: Set<Promise<void>>;
90
+ }
91
+ const sessions = new WeakMap<object, Session>();
92
+
93
+ /** One blob per call: pin, upload, then the row that names it. */
94
+ async function storeCall(ctx: Ctx, call: CapturedCall): Promise<void> {
95
+ const a = active(ctx.tenant, ctx.workspace);
96
+ const fall = (err: unknown) => {
97
+ // TEMPORARY (see the header): the volume copy, so the call is not lost.
98
+ opsError("captured_calls.fallback", err, { tenant: ctx.tenant, workspace: ctx.workspace, runId: ctx.runId, callId: call.id });
99
+ try {
100
+ writeCapturedCall(ctx.workspaceRoot, ctx.runId, call);
101
+ } catch (e) {
102
+ opsError("capture.write_failed", e, { runId: ctx.runId });
103
+ }
104
+ };
105
+ if (!a) return fall(new Error("the call store went away before the call was written"));
106
+ try {
107
+ const bytes = Buffer.from(JSON.stringify(call));
108
+ const sha = sha256Hex(bytes);
109
+ await a.deps.pins?.pinBlobs(ctx.tenant, [sha], holderOf(ctx.runId));
110
+ await a.deps.blobs.putIfAbsent(blobObjectKey(ctx.tenant, sha), bytes, { contentType: "application/json" });
111
+ await a.port.async!.stepPut!(ctx.tenant, ctx.workspace, ctx.runId, KIND, call.id, { sha, size: bytes.length });
112
+ } catch (err) {
113
+ fall(err);
114
+ }
115
+ }
116
+
117
+ /**
118
+ * The runner's place to put a call's part (input on the call, output on its
119
+ * completion). Returns whether it was taken (the event says `captured`).
120
+ * `owner` is the step: flushCalls(owner) settles what it left.
121
+ */
122
+ export function callSink(owner: object, ctx: Ctx): (part: CapturedCall) => boolean {
123
+ const s: Session = { ctx, pending: new Map(), writes: new Set() };
124
+ sessions.set(owner, s);
125
+ return (part) => {
126
+ if (!SAFE.test(part.id) || !SAFE.test(ctx.runId)) return false;
127
+ const live = active(ctx.tenant, ctx.workspace);
128
+ const waiting = s.pending.get(part.id);
129
+ if (live && part.output === undefined) {
130
+ s.pending.set(part.id, merge(waiting, part));
131
+ return true;
132
+ }
133
+ s.pending.delete(part.id);
134
+ // A call whose input went to the volume before the switch flipped, or on another worker.
135
+ const prev = waiting ?? (live ? readCapturedCall(ctx.tenant, ctx.workspace, ctx.runId, part.id) ?? undefined : undefined);
136
+ const whole = merge(prev, part);
137
+ if (!live) {
138
+ writeCapturedCall(ctx.workspaceRoot, ctx.runId, whole);
139
+ return true;
140
+ }
141
+ const w: Promise<void> = storeCall(ctx, whole).finally(() => s.writes.delete(w));
142
+ s.writes.add(w);
143
+ return true;
144
+ };
145
+ }
146
+
147
+ /** The step ended: write the inputs that never got an output, wait for every write. Never throws. */
148
+ export async function flushCalls(owner: object): Promise<void> {
149
+ const s = sessions.get(owner);
150
+ if (!s) return;
151
+ sessions.delete(owner);
152
+ for (const call of s.pending.values()) {
153
+ if (active(s.ctx.tenant, s.ctx.workspace)) s.writes.add(storeCall(s.ctx, call));
154
+ else {
155
+ try {
156
+ writeCapturedCall(s.ctx.workspaceRoot, s.ctx.runId, call);
157
+ } catch (err) {
158
+ opsError("capture.write_failed", err, { runId: s.ctx.runId });
159
+ }
160
+ }
161
+ }
162
+ s.pending.clear();
163
+ await Promise.allSettled([...s.writes]);
164
+ }
165
+
166
+ /** One recorded call, or null (not recorded). The row first, then the file. */
167
+ export async function readCapturedCallAsync(tenant: string, workspace: string, runId: string, callId: string): Promise<CapturedCall | null> {
168
+ if (!SAFE.test(runId) || !SAFE.test(callId) || callId.startsWith(".") || runId.startsWith(".")) return null;
169
+ const port = portFor(tenant, workspace);
170
+ if (port) {
171
+ let row: { sha?: string } | undefined;
172
+ try {
173
+ row = (await port.async!.stepGet!(tenant, workspace, runId, KIND, callId)) as { sha?: string } | undefined;
174
+ } catch (err) {
175
+ throw new CapturedCallUnavailable(callId, err);
176
+ }
177
+ if (row) {
178
+ try {
179
+ if (!CALLS.backend || typeof row.sha !== "string") throw new Error("the call store is not available here");
180
+ const call = JSON.parse((await readAll(CALLS.backend.blobs, blobObjectKey(tenant, row.sha))).toString("utf8")) as CapturedCall;
181
+ if (!call || typeof call !== "object" || call.id !== callId) throw new Error("the stored object is not this call");
182
+ return call;
183
+ } catch (err) {
184
+ if (!(err instanceof BlobNotFound)) opsError("captured_calls.read_failed", err, { tenant, workspace, runId, callId });
185
+ throw new CapturedCallUnavailable(callId, err);
186
+ }
187
+ }
188
+ }
189
+ return readCapturedCall(tenant, workspace, runId, callId);
190
+ }
191
+
192
+ // ---------------------------------------------------------------- lifecycle
193
+
194
+ /** What the run-delete hook started and has not finished (tests, a process that is ending). */
195
+ export async function settleCalls(): Promise<void> {
196
+ while (CALLS.background.size) await Promise.allSettled([...CALLS.background]);
197
+ }
198
+
199
+ /** A run was deleted: its calls' pin goes (the rows went with it; the sweeper takes the blobs). */
200
+ function runGone(tenant: string, _workspace: string, runId: string): void {
201
+ const deps = CALLS.backend;
202
+ if (!deps?.pins || !SAFE.test(runId)) return;
203
+ const p = (async () => {
204
+ for (let attempt = 0; ; attempt++) {
205
+ try {
206
+ await deps.pins!.release(tenant, holderOf(runId));
207
+ return;
208
+ } catch (err) {
209
+ // A pin that cannot be released is kept: a leak is safe, a loss is not.
210
+ if (attempt >= 4) return opsError("captured_calls.drop_failed", err, { tenant, runId });
211
+ await new Promise((r) => setTimeout(r, 1000 * 2 ** attempt));
212
+ }
213
+ }
214
+ })();
215
+ const q = p.finally(() => CALLS.background.delete(q));
216
+ CALLS.background.add(q);
217
+ }
218
+
219
+ /** A workspace is being deleted (its rows still there): release the pin of every run that has calls
220
+ * in the store. Throws when the pins cannot be reached, so the delete can be retried. */
221
+ export async function dropWorkspaceCalls(tenant: string, workspace: string): Promise<void> {
222
+ const deps = CALLS.backend;
223
+ const port = records(tenant, workspace);
224
+ if (!deps?.pins || !port?.async?.stepRuns) return;
225
+ for (const runId of await port.async.stepRuns(tenant, workspace, KIND)) await deps.pins.release(tenant, holderOf(runId));
226
+ }
package/src/records.ts CHANGED
@@ -41,12 +41,14 @@ export interface RecordsPortAsync {
41
41
  stepPut?(tenant: string, workspace: string, runId: string, kind: string, ref: string, data: unknown): Promise<void>;
42
42
  /** `ref` null: every ref of the kind. */
43
43
  stepDrop?(tenant: string, workspace: string, runId: string, kind: string, ref: string | null): Promise<void>;
44
+ /** The ids of the runs that have rows of this kind in the workspace. */
45
+ stepRuns?(tenant: string, workspace: string, kind: string): Promise<string[]>;
44
46
  }
45
47
 
46
48
  /** Small per-workspace state that used to be files in the workspace's folder
47
49
  * (FOL-126, the last files on the volume): webhook generations and the
48
50
  * delivery log, eval results and their history, grades and grader cursors,
49
- * the deployed commit, captured tool calls. Two shapes: a DOCUMENT per
51
+ * the deployed commit. Two shapes: a DOCUMENT per
50
52
  * (kind, key), and an append-only LOG per kind. Synchronous like the rest of
51
53
  * the port; workspace-docs.ts is the only caller. */
52
54
  export interface DocsPort {
@@ -86,6 +88,9 @@ export interface RecordsPort {
86
88
  * state is written to the run's folder as before (it is still READ from
87
89
  * rows first, so switching off mid-run loses nothing). */
88
90
  stepStateOn?(): boolean;
91
+ /** The `runs.calls_store` setting, read per call: while false, a captured
92
+ * call is written to the run's folder as before (captured-calls.ts). */
93
+ callsStoreOn?(): boolean;
89
94
  // ---- runs: the whole record, and the row a list reads
90
95
  /** Insert or replace one run. `live`: queued, running or parked at a gate. Last write wins. */
91
96
  runPut(tenant: string, workspace: string, run: RunRecord, summary: RunSummary, live: boolean): void;
package/src/runner.ts CHANGED
@@ -7,6 +7,7 @@ import { opsLog, opsError } from "./ops-log.ts";
7
7
  import { globMatch } from "./bounded-match.ts";
8
8
  import { latestRevisionId } from "./history.ts";
9
9
  import { recordCallIo, redactionsFor } from "./capture.ts";
10
+ import { callSink, flushCalls } from "./captured-calls.ts";
10
11
  import { AUTH_REFUSAL, platformCause } from "./issues.ts";
11
12
  import { hookNames } from "./hooks.ts";
12
13
  import crypto from "node:crypto";
@@ -118,7 +119,7 @@ import { buildScriptTools, parseScripts, type ExecutionContext, type ScriptSpec
118
119
  import { libraryDir, libraryTools, libraryMemoryIndex } from "./library.ts";
119
120
  import { fingerprint, mergeRuntimes, parseRuntime, prepareRuntime, stepInstallEnv, type PreparedRuntime, type RuntimeSpec } from "./runtime.ts";
120
121
  import { buildInstallTool, INSTALL_TOOL } from "./install-tool.ts";
121
- import { dataRoot, singleWorkspace } from "./paths.ts";
122
+ import { dataRoot } from "./paths.ts";
122
123
  import { materializeFiles, harvestFiles, storageBaseline } from "./storage.ts";
123
124
  import { readStorageBaseline, writeStorageBaseline } from "./step-state.ts";
124
125
  import { chooseExecutor, ensureImage } from "./container.ts";
@@ -2194,7 +2195,16 @@ export function operatorBlock(step: Pick<StepRecord, "ask" | "approvalNote" | "a
2194
2195
  }
2195
2196
 
2196
2197
 
2197
- async function runStep(
2198
+ /** A step, and then whatever its captured calls still hold (captured-calls.ts). */
2199
+ async function runStep(...args: Parameters<typeof runStepBody>): ReturnType<typeof runStepBody> {
2200
+ try {
2201
+ return await runStepBody(...args);
2202
+ } finally {
2203
+ await flushCalls(args[2]);
2204
+ }
2205
+ }
2206
+
2207
+ async function runStepBody(
2198
2208
  agentDir: string,
2199
2209
  tenant: string,
2200
2210
  step: StepRecord,
@@ -2312,6 +2322,8 @@ async function runStep(
2312
2322
  // calls keep their names, sizes and times (FOL-54 step 4).
2313
2323
  let capturedChars = 0;
2314
2324
  let captureFull = false;
2325
+ const callsRoot = path.resolve(agentDir, "..", "..");
2326
+ const sink = runId ? callSink(step, { tenant, workspace: path.basename(callsRoot), runId, workspaceRoot: callsRoot }) : undefined;
2315
2327
  const push = (type: StepRecord["events"][number]["type"], text: string, extra?: EventExtra) => {
2316
2328
  const t = new Date().toISOString();
2317
2329
  // The model has begun its first response: held only in memory, for
@@ -2346,7 +2358,7 @@ async function runStep(
2346
2358
  captureFull = true;
2347
2359
  step.events.push({ t, type: "info", text: `capture: this step recorded ${Math.round(capturedChars / 1000)}k characters of tool content — the rest of its calls keep only their names, sizes and times` });
2348
2360
  }
2349
- if (runId && extra.call && capture === "full" && !captureFull && recordCallIo(path.resolve(agentDir, "..", ".."), runId, extra.call, text, io, redact, singleWorkspace() ? undefined : { tenant, workspace: path.basename(path.resolve(agentDir, "..", "..")) })) {
2361
+ if (runId && extra.call && capture === "full" && !captureFull && recordCallIo(callsRoot, runId, extra.call, text, io, redact, sink)) {
2350
2362
  capturedChars += size;
2351
2363
  rest = { ...others, captured: true };
2352
2364
  }
package/src/store.ts CHANGED
@@ -20,6 +20,7 @@
20
20
  //
21
21
  // An account is a named directory (per OKF: tenancy is a hosting concern).
22
22
 
23
+ import { opsError } from "./ops-log.ts";
23
24
  import { readCompute } from "./resources.ts";
24
25
  import { expandPlatformVars } from "./host-env.ts";
25
26
  import { EFFORT_LEVELS, FLOW_TRIGGERS } from "./frontmatter-fields.ts";
@@ -31,7 +32,7 @@ import { processState } from "./process-state.ts";
31
32
  import { dataRoot, singleWorkspace, singleAccountRoot, entriesNoFollow } from "./paths.ts";
32
33
  import { platform } from "./platform.ts";
33
34
  import { records } from "./records.ts";
34
- import { docRows, docStore, quietly } from "./workspace-docs.ts";
35
+ import { docRows, quietly } from "./workspace-docs.ts";
35
36
  import { toLF, asRaw } from "./eol.ts";
36
37
  import type { TestEffect } from "./test-mode.ts";
37
38
  import type { OperatorEvent } from "./operator.ts";
@@ -4066,7 +4067,9 @@ export interface RunRecord {
4066
4067
  // runs/<run>/). The runner writes them, secrets already masked.
4067
4068
 
4068
4069
  const SAFE_ID = /^[A-Za-z0-9_.-]{1,128}$/;
4069
- const CALL_KIND = "call";
4070
+ /** Captured calls kept as rows for one day on dev (13 Nov 2026); read and
4071
+ * dropped with their run, never written again. */
4072
+ const LEGACY_CALL_KIND = "call";
4070
4073
 
4071
4074
  function capturedCallFile(workspaceRoot: string, runId: string, callId: string): string | null {
4072
4075
  if (!SAFE_ID.test(runId) || !SAFE_ID.test(callId) || callId.startsWith(".") || runId.startsWith(".")) return null;
@@ -4075,14 +4078,9 @@ function capturedCallFile(workspaceRoot: string, runId: string, callId: string):
4075
4078
 
4076
4079
  /** Merge one part (the input, on the call; the output, on its completion)
4077
4080
  * into the call's file. */
4078
- export function writeCapturedCall(workspaceRoot: string, runId: string, part: CapturedCall, scope?: { tenant: string; workspace: string }): void {
4081
+ export function writeCapturedCall(workspaceRoot: string, runId: string, part: CapturedCall): void {
4079
4082
  const file = capturedCallFile(workspaceRoot, runId, part.id);
4080
4083
  if (!file) return;
4081
- // A row when the platform keeps them (FOL-126): the two parts of a call
4082
- // merge in one statement, and the web's copies read it wherever they run.
4083
- // `truncated` is only ever sent true, so a merge keeps it once set.
4084
- const store = scope ? docStore(scope.tenant, scope.workspace) : null;
4085
- if (store && scope) return store.merge(scope.tenant, scope.workspace, CALL_KIND, `${runId}/${part.id}`, part as unknown as Record<string, unknown>);
4086
4084
  let prev: Partial<CapturedCall> = {};
4087
4085
  try {
4088
4086
  prev = JSON.parse(fs.readFileSync(file, "utf8")) as CapturedCall;
@@ -4101,20 +4099,15 @@ export function writeCapturedCall(workspaceRoot: string, runId: string, part: Ca
4101
4099
  export function readCapturedCall(tenant: string, workspace: string, runId: string, callId: string): CapturedCall | null {
4102
4100
  const file = capturedCallFile(workspaceDir(tenant, workspace), runId, callId);
4103
4101
  if (!file) return null;
4104
- const row = quietly(() => docRows(tenant, workspace)?.get(tenant, workspace, CALL_KIND, `${runId}/${callId}`), undefined) as CapturedCall | undefined;
4105
- let onFile: CapturedCall | undefined;
4102
+ // A call kept as a workspace_docs row (records.docs_store, 13 Nov 2026,
4103
+ // before calls went to the blob store): still read until its run goes.
4104
+ const legacy = quietly(() => docRows(tenant, workspace)?.get(tenant, workspace, LEGACY_CALL_KIND, `${runId}/${callId}`), undefined) as CapturedCall | undefined;
4105
+ if (legacy) return legacy;
4106
4106
  try {
4107
- onFile = JSON.parse(fs.readFileSync(file, "utf8")) as CapturedCall;
4107
+ return JSON.parse(fs.readFileSync(file, "utf8")) as CapturedCall;
4108
4108
  } catch {
4109
- /* none */
4110
- }
4111
- // A switch between a call's two parts leaves one part in each place: both, merged.
4112
- if (row && onFile) {
4113
- const merged: CapturedCall = { ...onFile, ...row, truncated: Boolean(onFile.truncated || row.truncated) || undefined };
4114
- if (!merged.truncated) delete merged.truncated;
4115
- return merged;
4109
+ return null;
4116
4110
  }
4117
- return row ?? onFile ?? null;
4118
4111
  }
4119
4112
 
4120
4113
  export function runFilePath(tenant: string, workspace: string, runId: string) {
@@ -4154,8 +4147,7 @@ export function deleteRun(tenant: string, workspace: string, runId: string, opts
4154
4147
  // and finishes — the other order left the content with nothing pointing
4155
4148
  // at it (Codex review, FOL-124).
4156
4149
  fs.rmSync(dir, { recursive: true, force: true });
4157
- // Its captured calls kept as rows go the same way, before the record.
4158
- if (SAFE_ID.test(runId)) docRows(tenant, workspace)?.dropPrefix(tenant, workspace, CALL_KIND, `${runId}/`);
4150
+ if (SAFE_ID.test(runId)) quietly(() => docRows(tenant, workspace)?.dropPrefix(tenant, workspace, LEGACY_CALL_KIND, `${runId}/`), undefined);
4159
4151
  if (port) port.runDelete(tenant, workspace, runId);
4160
4152
  else {
4161
4153
  fs.rmSync(file, { force: true });
@@ -4167,9 +4159,17 @@ export function deleteRun(tenant: string, workspace: string, runId: string, opts
4167
4159
  if (prior?.inputs?.length) {
4168
4160
  void import("./storage.ts").then((m) => m.releaseRunInputs(tenant, workspace, runId)).catch(() => {});
4169
4161
  }
4170
- // Outputs published to the blob store (run-outputs.ts) are records and pins,
4171
- // not files under dir: they go in the background, retried.
4172
- RUN_HOOKS.removed?.(tenant, workspace, runId);
4162
+ // Outputs and captured calls published to the blob store (run-outputs.ts,
4163
+ // captured-calls.ts) are records and pins, not files under dir: they go in
4164
+ // the background, retried.
4165
+ for (const [name, hook] of RUN_HOOKS.removed) {
4166
+ try {
4167
+ hook(tenant, workspace, runId);
4168
+ } catch (err) {
4169
+ // One store's clean-up failing must not stop the next one's.
4170
+ opsError("run_removed_hook.failed", err, { hook: name, tenant, runId });
4171
+ }
4172
+ }
4173
4173
  if (!had) return true;
4174
4174
  // The retention window's prune (`pruned`) is policy, not a person erasing
4175
4175
  // history: no per-run ledger note. The charge stands either way.
@@ -4177,13 +4177,16 @@ export function deleteRun(tenant: string, workspace: string, runId: string, opts
4177
4177
  return true;
4178
4178
  }
4179
4179
 
4180
- /** run-outputs.ts registers here (it imports this module). */
4180
+ /** run-outputs.ts and captured-calls.ts register here (they import this module). */
4181
4181
  type RunHook = (tenant: string, workspace: string, runId: string) => void;
4182
4182
  /** One per process (process-state.ts): a run deleted from a route handler must
4183
4183
  * reach the hooks the boot registered. */
4184
- const RUN_HOOKS = processState("run-hooks", () => ({ removed: null as RunHook | null, deleted: undefined as RunHook | undefined }));
4185
- export function registerRunRemovedHook(fn: RunHook | null) {
4186
- RUN_HOOKS.removed = fn;
4184
+ const RUN_HOOKS = processState("run-hooks", () => ({ removed: new Map<string, RunHook>(), deleted: undefined as RunHook | undefined }));
4185
+ /** A run's content lives somewhere other than its folder: `name` says whose hook
4186
+ * this is, so one registering (or clearing, with null) never replaces another's. */
4187
+ export function registerRunRemovedHook(fn: RunHook | null, name = "run-outputs") {
4188
+ if (fn) RUN_HOOKS.removed.set(name, fn);
4189
+ else RUN_HOOKS.removed.delete(name);
4187
4190
  }
4188
4191
 
4189
4192
  /** ledger.ts registers here — store cannot import it without a cycle, and
@@ -64,6 +64,7 @@ import { headsOf, loadManifest, manifestsAt, manifestsOf, publish, restore, requ
64
64
  import { OpIdReused, type Revision, type WorkspaceRef } from "./revision-store.ts";
65
65
  import { pruneStateRevisions, type StateRetention } from "./state-retention.ts";
66
66
  import type { SweepMarks } from "./blob-sweeper.ts";
67
+ import { setCallsBackend, dropWorkspaceCalls, settleCalls } from "./captured-calls.ts";
67
68
  import { dropTenantOutputs, dropWorkspaceOutputs, moveWorkspaceOutputs, settleRunOutputs } from "./run-outputs.ts";
68
69
 
69
70
  // ------------------------------------------------------------- the backend
@@ -138,6 +139,7 @@ export function setRevisionBackend(deps: Deps | null, opts: BackendOptions = {})
138
139
  S.retentionEvery = opts.retentionEveryMs ?? 10 * 60_000;
139
140
  S.orphanMarks = opts.sweepMarks ?? null;
140
141
  S.orphanGrace = opts.orphanGraceMs ?? 3_600_000;
142
+ setCallsBackend(deps);
141
143
  registerJournal(deps ? journalChange : null);
142
144
  registerWorkspaceGone(deps ? (t, w) => goneNow(t, w) : null);
143
145
  registerWorkspaceLifecycle(deps ? { drop: dropWorkspaceRevisions, move: moveWorkspaceRevisions, moved: movedNow } : null);
@@ -557,6 +559,7 @@ const background = S.background;
557
559
  export async function settleLifecycle(): Promise<void> {
558
560
  while (background.size) await Promise.allSettled([...background]);
559
561
  await settleRunOutputs();
562
+ await settleCalls();
560
563
  }
561
564
  function inBackground(p: Promise<unknown>): void {
562
565
  const q = p.finally(() => background.delete(q));
@@ -608,6 +611,8 @@ export async function dropWorkspaceRevisions(tenant: string, workspace: string,
608
611
  dropJournal(tenant, workspace);
609
612
  await before?.catch(() => {});
610
613
  try {
614
+ // Its captured calls' pins, while the rows that name the runs are still there.
615
+ await dropWorkspaceCalls(tenant, workspace);
611
616
  await deps.revisions.drop({ tenant, workspace });
612
617
  // The run outputs published to the blob store (run-outputs.ts) are this workspace's too.
613
618
  await dropWorkspaceOutputs(tenant, workspace);
@@ -619,6 +624,7 @@ export async function dropWorkspaceRevisions(tenant: string, workspace: string,
619
624
  }
620
625
  remove?.();
621
626
  dropJournal(tenant, workspace);
627
+ await dropWorkspaceCalls(tenant, workspace);
622
628
  await deps.revisions.drop({ tenant, workspace });
623
629
  await dropWorkspaceOutputs(tenant, workspace);
624
630
  marked.delete(k);