@foldrun/core 21.1.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.
- package/dist/src/capture.d.ts +3 -6
- package/dist/src/capture.js +7 -5
- package/dist/src/captured-calls.d.ts +30 -0
- package/dist/src/captured-calls.js +219 -0
- package/dist/src/records.d.ts +6 -1
- package/dist/src/runner.js +15 -3
- package/dist/src/secrets.d.ts +9 -0
- package/dist/src/secrets.js +48 -2
- package/dist/src/store.d.ts +5 -6
- package/dist/src/store.js +34 -29
- package/dist/src/workspace-revisions.js +6 -0
- package/package.json +1 -1
- package/src/capture.ts +7 -6
- package/src/captured-calls.ts +226 -0
- package/src/records.ts +6 -1
- package/src/runner.ts +15 -3
- package/src/secrets.ts +46 -2
- package/src/store.ts +31 -28
- package/src/workspace-revisions.ts +6 -0
|
@@ -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
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
|
-
/**
|
|
104
|
-
|
|
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
|
-
|
|
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
|
-
}
|
|
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
|
|
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
|
|
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
|
-
|
|
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(
|
|
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/secrets.ts
CHANGED
|
@@ -503,6 +503,7 @@ export function setSecretSites(tenant: string, name: string, sites: string[], wo
|
|
|
503
503
|
}
|
|
504
504
|
let found = false;
|
|
505
505
|
mutateVault(tenant, workspace, (all) => {
|
|
506
|
+
found = false; // a store may run this again against a newer read
|
|
506
507
|
const rec = all[name];
|
|
507
508
|
if (!rec) return null;
|
|
508
509
|
found = true;
|
|
@@ -692,6 +693,7 @@ export function setSecretWorkspaces(
|
|
|
692
693
|
const expected = opts.ifWorkspaces === undefined ? undefined : cleanWorkspaceList(opts.ifWorkspaces);
|
|
693
694
|
let found = false;
|
|
694
695
|
mutateVault(tenant, undefined, (all) => {
|
|
696
|
+
found = false; // a store may run this again against a newer read
|
|
695
697
|
const rec = all[name];
|
|
696
698
|
if (!rec) return null;
|
|
697
699
|
found = true;
|
|
@@ -865,8 +867,9 @@ export function masterKeySource(): { source: "env" | "file"; path: string | null
|
|
|
865
867
|
: { source: "file", path: keyFile() };
|
|
866
868
|
}
|
|
867
869
|
|
|
868
|
-
/**
|
|
869
|
-
|
|
870
|
+
/** The secrets.json files that exist under an account: the account's (named
|
|
871
|
+
* even where there is none), then each workspace's. */
|
|
872
|
+
function diskSecretFiles(tenant: string): { file: string; workspace?: string }[] {
|
|
870
873
|
const out: { file: string; workspace?: string }[] = [{ file: secretsFile(tenant) }];
|
|
871
874
|
for (const dirName of ["workspaces", "projects"]) {
|
|
872
875
|
const dir = path.join(dataRoot(), tenant, dirName);
|
|
@@ -877,6 +880,35 @@ function secretFiles(tenant: string): { file: string; workspace?: string }[] {
|
|
|
877
880
|
if (fs.existsSync(f)) out.push({ file: f, workspace: entry.name });
|
|
878
881
|
}
|
|
879
882
|
}
|
|
883
|
+
return out;
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
/** Every vault scope that has a FILE on this volume, across all accounts:
|
|
887
|
+
* what a fleet check or a move to a store starts from. Never opens one. */
|
|
888
|
+
export function vaultFileScopes(): { tenant: string; workspace?: string }[] {
|
|
889
|
+
const out: { tenant: string; workspace?: string }[] = [];
|
|
890
|
+
if (!fs.existsSync(dataRoot())) return out;
|
|
891
|
+
for (const e of fs.readdirSync(dataRoot(), { withFileTypes: true })) {
|
|
892
|
+
if (!e.isDirectory()) continue;
|
|
893
|
+
try {
|
|
894
|
+
assertSafeName(e.name, "tenant");
|
|
895
|
+
} catch {
|
|
896
|
+
continue; // not an account's folder
|
|
897
|
+
}
|
|
898
|
+
for (const { file, workspace } of diskSecretFiles(e.name)) if (fs.existsSync(file)) out.push({ tenant: e.name, ...(workspace ? { workspace } : {}) });
|
|
899
|
+
}
|
|
900
|
+
return out;
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
/** Does this stored record open for its place with this process's keys? True
|
|
904
|
+
* or false: the value is never handed out. */
|
|
905
|
+
export function vaultRecordOpens(tenant: string, workspace: string | undefined, name: string, rec: SecretsFile[string]): boolean {
|
|
906
|
+
return openRecord(tenant, workspace, name, rec) !== null;
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
/** Every secrets.json under an account: the account's, then each workspace's. */
|
|
910
|
+
function secretFiles(tenant: string): { file: string; workspace?: string }[] {
|
|
911
|
+
const out = diskSecretFiles(tenant);
|
|
880
912
|
// Scopes in the platform's store have no file; they are named by where
|
|
881
913
|
// the file would be (the result's `file` is a label, never opened).
|
|
882
914
|
for (const workspace of VAULT.store?.workspaces(tenant) ?? []) {
|
|
@@ -921,7 +953,10 @@ export function rotateMasterKey(
|
|
|
921
953
|
|
|
922
954
|
for (const { file, workspace } of secretFiles(tenant)) {
|
|
923
955
|
let count = 0;
|
|
956
|
+
const seen = unreadable.length;
|
|
924
957
|
mutateVault(tenant, workspace, (all) => {
|
|
958
|
+
count = 0; // a store may run this again against a newer read
|
|
959
|
+
unreadable.length = seen;
|
|
925
960
|
const next: SecretsFile = {};
|
|
926
961
|
for (const [name, rec] of Object.entries(all)) {
|
|
927
962
|
// A record under the ACCOUNT's key is not under the install key, so
|
|
@@ -1109,6 +1144,7 @@ export function replaceOAuth2RefreshToken(tenant: string, name: string, workspac
|
|
|
1109
1144
|
for (const scope of workspace ? [workspace, undefined] : [undefined]) {
|
|
1110
1145
|
let replaced = false;
|
|
1111
1146
|
mutateVault(tenant, scope, (all) => {
|
|
1147
|
+
replaced = false; // a store may run this again against a newer read
|
|
1112
1148
|
const rec = all[name];
|
|
1113
1149
|
if (rec && openRecord(tenant, scope, name, rec) === usedValue) {
|
|
1114
1150
|
// Built whole, not spread over the old record: a spread kept a stale
|
|
@@ -1962,7 +1998,11 @@ export function sealVaultBindings(tenant: string): { sealed: number; unreadable:
|
|
|
1962
1998
|
let sealed = 0;
|
|
1963
1999
|
const unreadable: string[] = [];
|
|
1964
2000
|
for (const { workspace } of secretFiles(tenant)) {
|
|
2001
|
+
const [sealedBefore, seen] = [sealed, unreadable.length];
|
|
1965
2002
|
mutateVault(tenant, workspace, (all) => {
|
|
2003
|
+
// a store may run this again against a newer read: count it once
|
|
2004
|
+
sealed = sealedBefore;
|
|
2005
|
+
unreadable.length = seen;
|
|
1966
2006
|
const plain = new Map<string, string>();
|
|
1967
2007
|
const bad: string[] = [];
|
|
1968
2008
|
for (const [name, rec] of Object.entries(all)) {
|
|
@@ -2006,7 +2046,11 @@ export function rewrapTenantSecrets(tenant: string): { moved: number; unreadable
|
|
|
2006
2046
|
for (const { workspace } of secretFiles(tenant)) {
|
|
2007
2047
|
// Under the vault's lock: every pod runs this at boot, and a save made
|
|
2008
2048
|
// between our read and our write must not be lost.
|
|
2049
|
+
const [movedBefore, seen] = [moved, unreadable.length];
|
|
2009
2050
|
mutateVault(tenant, workspace, (all) => {
|
|
2051
|
+
// a store may run this again against a newer read: count it once
|
|
2052
|
+
moved = movedBefore;
|
|
2053
|
+
unreadable.length = seen;
|
|
2010
2054
|
const plain = new Map<string, string>();
|
|
2011
2055
|
const unreadableHere: string[] = [];
|
|
2012
2056
|
for (const [name, rec] of Object.entries(all)) {
|
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,
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
4105
|
-
|
|
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
|
-
|
|
4107
|
+
return JSON.parse(fs.readFileSync(file, "utf8")) as CapturedCall;
|
|
4108
4108
|
} catch {
|
|
4109
|
-
|
|
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
|
-
|
|
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
|
|
4171
|
-
// not files under dir: they go in
|
|
4172
|
-
|
|
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
|
|
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:
|
|
4185
|
-
|
|
4186
|
-
|
|
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);
|