@foldrun/core 23.3.0 → 24.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 PlainOpts } from "./safe-open.ts";
1
2
  export declare class BlobNotFound extends Error {
2
3
  readonly key: string;
3
4
  constructor(key: string);
@@ -136,8 +137,11 @@ export declare function assertKey(key: string): string;
136
137
  export declare function bufferSource(buf: Uint8Array): BlobSource;
137
138
  /** A file on disk. The size is taken now; if the file is shorter (or longer)
138
139
  * when it is read, the read throws BlobSourceError rather than send a body
139
- * that no longer matches what was announced. */
140
- export declare function fileSource(filePath: string): BlobSource;
140
+ * that no longer matches what was announced. A link is never followed, and a
141
+ * different file (or a FIFO) swapped in since the size was taken is refused:
142
+ * each read opens the path without following links and must find the same
143
+ * inode (safe-open.ts, SYMRACE). */
144
+ export declare function fileSource(filePath: string, expect?: PlainOpts): BlobSource;
141
145
  /** sha256 (and md5, which is what a single-request ETag is) of a range. */
142
146
  export declare function hashRange(source: BlobSource, start: number, end: number, signal?: AbortSignal): Promise<{
143
147
  sha256: string;
@@ -2,8 +2,8 @@
2
2
  // Split out of blob-store.ts so the s3 driver (s3-blob-store.ts) and the fs
3
3
  // driver can both use the errors and the source type without importing each
4
4
  // other.
5
- import fs from "node:fs";
6
5
  import crypto from "node:crypto";
6
+ import { plainStream, statPlain, UnsafeFileError } from "./safe-open.js";
7
7
  export class BlobNotFound extends Error {
8
8
  key;
9
9
  constructor(key) {
@@ -83,16 +83,28 @@ export function bufferSource(buf) {
83
83
  }
84
84
  /** A file on disk. The size is taken now; if the file is shorter (or longer)
85
85
  * when it is read, the read throws BlobSourceError rather than send a body
86
- * that no longer matches what was announced. */
87
- export function fileSource(filePath) {
88
- const size = fs.statSync(filePath).size;
86
+ * that no longer matches what was announced. A link is never followed, and a
87
+ * different file (or a FIFO) swapped in since the size was taken is refused:
88
+ * each read opens the path without following links and must find the same
89
+ * inode (safe-open.ts, SYMRACE). */
90
+ export function fileSource(filePath, expect = {}) {
91
+ const seen = statPlain(filePath, expect);
92
+ const size = seen.size;
89
93
  return {
90
94
  size,
91
95
  async *read(start, end, signal) {
92
96
  const hi = Math.min(end, size);
93
97
  if (hi <= start)
94
98
  return;
95
- const stream = fs.createReadStream(filePath, { start, end: hi - 1, highWaterMark: 1 << 20, signal });
99
+ let stream;
100
+ try {
101
+ stream = plainStream(filePath, { start, end: hi - 1, highWaterMark: 1 << 20, signal, dev: seen.dev, ino: seen.ino, root: expect.root });
102
+ }
103
+ catch (err) {
104
+ if (err instanceof UnsafeFileError)
105
+ throw new BlobSourceError(`${filePath} changed while it was being uploaded: ${err.message}`);
106
+ throw err;
107
+ }
96
108
  let got = 0;
97
109
  for await (const chunk of stream) {
98
110
  got += chunk.length;
@@ -19,6 +19,24 @@ export declare function redactionsFor(secrets: Record<string, string | undefined
19
19
  * bytes alone at each alignment, so the form matches inside a longer
20
20
  * encoding whatever came before or after the value. */
21
21
  export declare function encodedForms(v: string): string[];
22
+ /**
23
+ * Every secret value in `text` → `[redacted:NAME]` (the runner's scrub), and
24
+ * also the piece of one a cut left at an end of the text. A sandbox cuts what
25
+ * it sends (a tool's output, a reply, an error line, the stderr tail) before
26
+ * the host sees it, so a secret on the cut arrives as a prefix at the end
27
+ * (or a suffix at the start), which no whole-value match recognises — and
28
+ * masking first and cutting second cannot help what was cut before it got
29
+ * here. An end that is the start of a value (8+ characters, `EDGE_MIN`) is
30
+ * masked as that value, plain or in any of the encoded forms in the list.
31
+ */
32
+ export declare function scrubWith(redactions: [string, string][], text: string): string;
33
+ /** What no vault value covers: a credential-shaped string (a GitHub, Anthropic
34
+ * or AWS key, a JWT, `token=…`, a bearer) and a private key's whole block.
35
+ * Applied after the step's own value masks, to every piece of stored text that
36
+ * came out of a sandbox or a model — a tool's output, a prompt, stderr — so a
37
+ * key a tool read off disk is not kept just because it was never a secret
38
+ * of ours. Ordinary text (ids, URLs, paths, hashes) is left as it was. */
39
+ export declare function maskPatterns(text: string): string;
22
40
  /** Masked, then cut to the cap. */
23
41
  export declare function maskCall(text: string, redactSecrets: (text: string) => string): {
24
42
  text: string;
@@ -129,14 +129,71 @@ export function encodedForms(v) {
129
129
  forms.delete(v);
130
130
  return [...forms].filter((f) => f.length >= 12);
131
131
  }
132
+ /** The shortest piece of a secret that is masked when a cut left only that
133
+ * much of it at an edge of a text. The same floor as a whole secret (8):
134
+ * fewer characters than that is no key. */
135
+ const EDGE_MIN = 8;
136
+ /**
137
+ * Every secret value in `text` → `[redacted:NAME]` (the runner's scrub), and
138
+ * also the piece of one a cut left at an end of the text. A sandbox cuts what
139
+ * it sends (a tool's output, a reply, an error line, the stderr tail) before
140
+ * the host sees it, so a secret on the cut arrives as a prefix at the end
141
+ * (or a suffix at the start), which no whole-value match recognises — and
142
+ * masking first and cutting second cannot help what was cut before it got
143
+ * here. An end that is the start of a value (8+ characters, `EDGE_MIN`) is
144
+ * masked as that value, plain or in any of the encoded forms in the list.
145
+ */
146
+ export function scrubWith(redactions, text) {
147
+ let out = text;
148
+ for (const [value, name] of redactions)
149
+ out = out.split(value).join(`[redacted:${name}]`);
150
+ if (out.length < EDGE_MIN)
151
+ return out;
152
+ for (const [value, name] of redactions) {
153
+ if (value.length <= EDGE_MIN)
154
+ continue;
155
+ const mark = `[redacted:${name}]`;
156
+ // the end of the text begins the value: look only where a piece shorter
157
+ // than the whole value can fit
158
+ const tail = out.slice(-(value.length - 1));
159
+ const head8 = value.slice(0, EDGE_MIN);
160
+ for (let at = tail.indexOf(head8); at >= 0; at = tail.indexOf(head8, at + 1)) {
161
+ if (value.startsWith(tail.slice(at))) {
162
+ out = out.slice(0, out.length - (tail.length - at)) + mark;
163
+ break;
164
+ }
165
+ }
166
+ // the start of the text ends the value
167
+ const lead = out.slice(0, value.length - 1);
168
+ const first8 = lead.slice(0, EDGE_MIN);
169
+ if (first8.length === EDGE_MIN) {
170
+ for (let j = value.indexOf(first8, 1); j >= 0 && value.length - j >= EDGE_MIN; j = value.indexOf(first8, j + 1)) {
171
+ if (out.startsWith(value.slice(j))) {
172
+ out = mark + out.slice(value.length - j);
173
+ break;
174
+ }
175
+ }
176
+ }
177
+ }
178
+ return out;
179
+ }
132
180
  // A private key's whole block — scan.ts names a key header and leaves the
133
181
  // body, which is right for a finding and wrong for a stored output.
134
182
  // Unterminated too: a key cut short, or printed without its END line, is
135
183
  // masked to the end of the text.
136
184
  const PRIVATE_KEY = /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z0-9 ]*PRIVATE KEY-----|$(?![\s\S]))/g;
185
+ /** What no vault value covers: a credential-shaped string (a GitHub, Anthropic
186
+ * or AWS key, a JWT, `token=…`, a bearer) and a private key's whole block.
187
+ * Applied after the step's own value masks, to every piece of stored text that
188
+ * came out of a sandbox or a model — a tool's output, a prompt, stderr — so a
189
+ * key a tool read off disk is not kept just because it was never a secret
190
+ * of ours. Ordinary text (ids, URLs, paths, hashes) is left as it was. */
191
+ export function maskPatterns(text) {
192
+ return redactText(text).replace(PRIVATE_KEY, "[redacted:private key]");
193
+ }
137
194
  /** Masked, then cut to the cap. */
138
195
  export function maskCall(text, redactSecrets) {
139
- const masked = redactText(redactSecrets(text)).replace(PRIVATE_KEY, "[redacted:private key]");
196
+ const masked = maskPatterns(redactSecrets(text));
140
197
  return masked.length > CAPTURE_CAP ? { text: masked.slice(0, CAPTURE_CAP), cut: true } : { text: masked, cut: false };
141
198
  }
142
199
  export function recordCallIo(workspaceRoot, runId, callId, tool, io,
@@ -1,4 +1,5 @@
1
1
  import { type Deps } from "./publish.ts";
2
+ import { type PlainOpts } from "./safe-open.ts";
2
3
  export declare const IMPORT_BY = "import:data-folder";
3
4
  /** Files at or under this are read whole for the publish; a larger one is
4
5
  * streamed from disk. */
@@ -60,7 +61,7 @@ export interface ScanOptions {
60
61
  tenants?: string[];
61
62
  workspaces?: string[];
62
63
  }
63
- export declare function hashFile(abs: string): Promise<string>;
64
+ export declare function hashFile(abs: string, expect?: PlainOpts): Promise<string>;
64
65
  /**
65
66
  * Two names that differ only by case cannot share a manifest. The first in
66
67
  * byte order keeps its name; each later one is kept as a conflict copy beside
@@ -53,6 +53,7 @@ import { pipeline } from "node:stream/promises";
53
53
  import { AUTHORED_DIRS, MAX_MANIFEST_FILES, MODE_EXEC, MODE_FILE, assertManifestPath, blobObjectKey, conflictPath, diffManifests, emptyManifest, sha256Hex, sideOf, } from "./manifest.js";
54
54
  import { headsOf, manifestsAt, publish, requestDigest } from "./publish.js";
55
55
  import { BlobNotFound, BlobSourceError, downloadToFile, fileSource } from "./blob-store.js";
56
+ import { plainStream, readPlain } from "./safe-open.js";
56
57
  import { isPlatformPath } from "./store.js";
57
58
  // store.ts keeps this pattern private; a name that fails it is not an account or workspace.
58
59
  const SAFE_NAME = /^[a-z0-9]+(-[a-z0-9]+)*$/;
@@ -63,9 +64,11 @@ export const LARGE_FILE_BYTES = 8 * 1024 * 1024;
63
64
  /** How long the importer's own pin on a streamed blob lives (a publish's is
64
65
  * shorter); released as soon as the publish is done. */
65
66
  const LARGE_PIN_TTL_MS = 30 * 60_000;
66
- export async function hashFile(abs) {
67
+ export async function hashFile(abs, expect = {}) {
67
68
  const h = crypto.createHash("sha256");
68
- await pipeline(fs.createReadStream(abs), h);
69
+ // Never through a link, never waiting on a pipe, and (with `st`) the file the
70
+ // scan listed: the scan's lstat said "regular file" earlier (safe-open.ts).
71
+ await pipeline(plainStream(abs, expect), h);
69
72
  return h.digest("hex");
70
73
  }
71
74
  /** Count what is under a folder without following links or reading content. */
@@ -253,7 +256,7 @@ async function scanWorkspace(tenant, workspace, dir) {
253
256
  ws.conflicts.push({ path: from, keptAs: rel });
254
257
  let sha;
255
258
  try {
256
- sha = await hashFile(f.abs);
259
+ sha = await hashFile(f.abs, { dev: f.st.dev, ino: f.st.ino, root: dir });
257
260
  }
258
261
  catch (err) {
259
262
  ws.unmapped.push({ path: f.rel, reason: `unreadable (${err.code ?? "error"})`, files: 1, bytes: f.st.size });
@@ -432,7 +435,7 @@ export async function importWorkspace(scan, opts) {
432
435
  const f = bySha.get(sha);
433
436
  if (!f)
434
437
  throw new Error(`no source file for ${sha.slice(0, 12)}…`);
435
- const b = fs.readFileSync(f.abs);
438
+ const b = readPlain(f.abs);
436
439
  if (sha256Hex(b) !== sha)
437
440
  throw new Error(`${f.path} changed while it was being imported`);
438
441
  return b;
@@ -39,6 +39,7 @@ import { putStepState, getStepState, dropStepState } from "./step-state.js";
39
39
  import { stageRunInputs } from "./storage.js";
40
40
  import { INPUTS_DIR, stagedLine } from "./run-inputs.js";
41
41
  import { textBesideInputs } from "./input-text.js";
42
+ import { readPlain, readPlainText, UnsafeFileError } from "./safe-open.js";
42
43
  /** The start-up phases and what each marks — startup.ts, where every
43
44
  * surface that shows them reads them from (FOL-74). */
44
45
  export { STARTUP_PHASES };
@@ -358,8 +359,8 @@ export function applyContainerChanges(hostWs, containerWs, baseline, note, diver
358
359
  // the same rule as every file below.
359
360
  const dir = path.join(containerWs, ".foldrun");
360
361
  const file = path.join(dir, "copied-back.json");
361
- if (fs.lstatSync(dir).isDirectory() && fs.lstatSync(file).isFile()) {
362
- const m = JSON.parse(fs.readFileSync(file, "utf8"));
362
+ if (fs.lstatSync(dir).isDirectory()) {
363
+ const m = JSON.parse(readPlainText(file, { root: containerWs, maxBytes: 16 * 1024 * 1024 }));
363
364
  if (m && typeof m === "object" && !Array.isArray(m)) {
364
365
  for (const [rel, h] of Object.entries(m)) {
365
366
  // Every version the host handed back for the path counts: two jobs
@@ -404,7 +405,21 @@ export function applyContainerChanges(hostWs, containerWs, baseline, note, diver
404
405
  continue;
405
406
  if (!allowedBack(rel))
406
407
  continue;
407
- let next = fs.readFileSync(abs);
408
+ // Read from a descriptor opened without following a link, inside the
409
+ // sandbox's folder: the walk's readdir said "regular file" a moment ago,
410
+ // and the step may have swapped it for a link to the host's
411
+ // /proc/self/environ, or a FIFO that would block this read forever
412
+ // (SYMRACE). Such a path is skipped and said, like any other refusal.
413
+ let next;
414
+ try {
415
+ next = readPlain(abs, { root: containerWs });
416
+ }
417
+ catch (err) {
418
+ if (!(err instanceof UnsafeFileError))
419
+ throw err;
420
+ note?.(`${posix} was not copied back: ${err.message}`);
421
+ continue;
422
+ }
408
423
  // What the step was handed: its bytes (a staging dir) or its hash.
409
424
  // null when the file did not exist then; undefined when no baseline.
410
425
  let was;
@@ -10,6 +10,8 @@ export function refusalText(r) {
10
10
  return `${r.agent}/${r.path} (${mib(r.bytes)}) was not kept: this run's outputs may total at most ${mib(r.limit ?? 0)}`;
11
11
  case "count":
12
12
  return `${r.agent}/${r.path} was not kept: a run keeps at most ${r.limit ?? 50_000} files per agent`;
13
+ case "unsafe":
14
+ return `${r.agent}/${r.path} was not kept: it was replaced by a link or a pipe while the run ended, so it was not read`;
13
15
  default:
14
16
  return `${r.agent}/${r.path} was not kept: its name cannot be stored (control characters, over 400 bytes, or differs from another file only by case)`;
15
17
  }
@@ -57,6 +57,14 @@ export declare const runOutputsOn: () => boolean;
57
57
  * holder, so a re-archive (a resumed run) can pin the new manifest before it
58
58
  * releases the old one. */
59
59
  export declare function outputsHolder(runId: string, agent: string, manifest: ManifestId): PinHolder;
60
+ /** Up to this size a file is read whole (4 lanes at most, so at most 4 x this in
61
+ * memory); past it, it is hashed and uploaded from disk in chunks. */
62
+ export declare const SMALL_OUTPUT_FILE_BYTES: number;
63
+ /** No output is kept past this, whatever `runs.output_file_mb` says (0 = no
64
+ * setting, which is what the backfill uses): the streamed path bounds memory,
65
+ * not time or storage, and a file this big is not an output an agent should
66
+ * leave. Refused as "file-cap", so it is named, never silent. */
67
+ export declare const HARD_OUTPUT_FILE_BYTES: number;
60
68
  export interface PublishedOutputs {
61
69
  record: RunOutputRecord | null;
62
70
  refused: RefusedOutput[];
@@ -96,6 +104,16 @@ export declare function archiveRunOutputs(tenant: string, workspace: string, run
96
104
  /** What a run archived, from the store and from the volume (an agent the store
97
105
  * has wins). Sorted by agent, then path. */
98
106
  export declare function listRunOutputs(tenant: string, workspace: string, runId: string): Promise<RunOutputFile[]>;
107
+ /** What the STORE holds for a run, with each file's hash — the volume is not
108
+ * asked (the backfill's verify compares these to the folder's bytes). */
109
+ export declare function storedRunOutputs(tenant: string, workspace: string, runId: string): Promise<{
110
+ agent: string;
111
+ path: string;
112
+ sha: string;
113
+ size: number;
114
+ }[]>;
115
+ /** The blob is in the store at the size the manifest says (a head, no bytes read). */
116
+ export declare function storedBlobIntact(tenant: string, sha: string, size: number): Promise<boolean>;
99
117
  export interface OpenedOutput {
100
118
  size: number;
101
119
  /** The bytes, or one inclusive range of them. */
@@ -42,7 +42,8 @@ import path from "node:path";
42
42
  import crypto from "node:crypto";
43
43
  import { dataRoot } from "./paths.js";
44
44
  import { processState } from "./process-state.js";
45
- import { BlobNotFound } from "./blob-store.js";
45
+ import { BlobNotFound, fileSource, hashRange } from "./blob-store.js";
46
+ import { plainStream, readPlain, statPlain, UnsafeFileError } from "./safe-open.js";
46
47
  import { PUBLISH_PIN_TTL_MS, noPins } from "./blob-pins.js";
47
48
  import { MAX_MANIFEST_FILES, MODE_EXEC, MODE_FILE, assertManifest, assertManifestPath, blobObjectKey, canonicalManifest, manifestId, manifestObjectKey, sha256Hex, } from "./manifest.js";
48
49
  import { BlobMissing, loadManifest } from "./publish.js";
@@ -165,9 +166,22 @@ const releaseRecords = async (b, recs) => {
165
166
  // ------------------------------------------------------------------ publishing
166
167
  /** How many files are in flight at once, and so at most this many buffered. */
167
168
  const UPLOAD_CONCURRENCY = 4;
169
+ /** Up to this size a file is read whole (4 lanes at most, so at most 4 x this in
170
+ * memory); past it, it is hashed and uploaded from disk in chunks. */
171
+ export const SMALL_OUTPUT_FILE_BYTES = 8 * 1024 * 1024;
172
+ /** No output is kept past this, whatever `runs.output_file_mb` says (0 = no
173
+ * setting, which is what the backfill uses): the streamed path bounds memory,
174
+ * not time or storage, and a file this big is not an output an agent should
175
+ * leave. Refused as "file-cap", so it is named, never silent. */
176
+ export const HARD_OUTPUT_FILE_BYTES = 32 * 1024 * 1024 * 1024;
168
177
  const MAX_REFUSALS_ON_RECORD = 100;
169
178
  function walk(root) {
170
179
  const out = [];
180
+ // The folder itself a link (an agent folder pointed elsewhere): its
181
+ // contents are not this run's outputs, and the per-file root check would
182
+ // take the link's target for the root. Nothing is kept from it.
183
+ if (fs.lstatSync(root).isSymbolicLink())
184
+ return out;
171
185
  const rec = (dir, rel) => {
172
186
  for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
173
187
  const abs = path.join(dir, e.name);
@@ -176,7 +190,7 @@ function walk(root) {
176
190
  rec(abs, r);
177
191
  else if (e.isFile()) {
178
192
  const st = fs.lstatSync(abs);
179
- out.push({ rel: r, abs, size: st.size, mode: st.mode & 0o111 ? MODE_EXEC : MODE_FILE });
193
+ out.push({ rel: r, abs, size: st.size, mode: st.mode & 0o111 ? MODE_EXEC : MODE_FILE, dev: st.dev, ino: st.ino });
180
194
  }
181
195
  // symlinks, sockets and the like are not outputs (the volume copy skipped them too)
182
196
  }
@@ -194,6 +208,7 @@ function walk(root) {
194
208
  export async function publishRunOutputs(b, tenant, workspace, runId, agent, dir) {
195
209
  safeName(agent, "agent");
196
210
  const fileMax = b.fileMaxBytes();
211
+ const fileCap = fileMax > 0 ? Math.min(fileMax, HARD_OUTPUT_FILE_BYTES) : HARD_OUTPUT_FILE_BYTES;
197
212
  const runMax = b.runMaxBytes();
198
213
  const refused = [];
199
214
  // What the run's other agents already hold counts against the run's cap.
@@ -219,8 +234,8 @@ export async function publishRunOutputs(b, tenant, workspace, runId, agent, dir)
219
234
  refuse("count", MAX_MANIFEST_FILES);
220
235
  continue;
221
236
  }
222
- if (fileMax > 0 && c.size > fileMax) {
223
- refuse("file-cap", fileMax);
237
+ if (c.size > fileCap) {
238
+ refuse("file-cap", fileCap);
224
239
  continue;
225
240
  }
226
241
  if (runMax > 0 && used + c.size > runMax) {
@@ -242,8 +257,10 @@ export async function publishRunOutputs(b, tenant, workspace, runId, agent, dir)
242
257
  let id = null;
243
258
  try {
244
259
  // Pin BEFORE the objects exist: a sweeper that looks now sees the pin.
245
- // Read each file once for its hash (a file can only be named by its
246
- // bytes), then upload; at most UPLOAD_CONCURRENCY buffers are live.
260
+ // A file can only be named by its bytes, so each is hashed first, then
261
+ // uploaded. A small one is read whole (as always); a bigger one is hashed
262
+ // and uploaded from disk in chunks, so at most UPLOAD_CONCURRENCY small
263
+ // buffers (and some 1 MiB chunks) are live, whatever the file's size.
247
264
  let next = 0;
248
265
  const lane = async () => {
249
266
  for (;;) {
@@ -251,17 +268,49 @@ export async function publishRunOutputs(b, tenant, workspace, runId, agent, dir)
251
268
  if (i >= kept.length)
252
269
  return;
253
270
  const c = kept[i];
254
- const body = fs.readFileSync(c.abs);
255
- // Grew since it was measured (an agent still writing): same rule, same cap.
256
- if (fileMax > 0 && body.length > fileMax) {
257
- refused.push({ agent, path: c.rel, bytes: body.length, reason: "file-cap", limit: fileMax });
258
- continue;
271
+ let sha;
272
+ let size;
273
+ // The walk looked with lstat; the read opens the path without following
274
+ // a link and must find the inode the walk saw (a file the agent swapped
275
+ // for a link to a secret, or a FIFO, since is refused, not read). The
276
+ // outputs folder is the root: a folder swapped for a link out is too.
277
+ const want = { dev: c.dev, ino: c.ino, root: dir };
278
+ try {
279
+ if (c.size <= SMALL_OUTPUT_FILE_BYTES) {
280
+ // A file that grew past twice the small size since the walk is not read whole.
281
+ const body = readPlain(c.abs, { ...want, maxBytes: 2 * SMALL_OUTPUT_FILE_BYTES });
282
+ // Grew since it was measured (an agent still writing): same rule, same cap.
283
+ if (body.length > fileCap) {
284
+ refused.push({ agent, path: c.rel, bytes: body.length, reason: "file-cap", limit: fileCap });
285
+ continue;
286
+ }
287
+ sha = sha256Hex(body);
288
+ size = body.length;
289
+ // Pin each blob before its put; a repeat extends the lease.
290
+ await pins.pinBlobs(tenant, [sha], publishHolder, { ttlMs: PUBLISH_PIN_TTL_MS });
291
+ await b.blobs.putIfAbsent(blobObjectKey(tenant, sha), body);
292
+ }
293
+ else {
294
+ const source = fileSource(c.abs, want);
295
+ if (source.size > fileCap) {
296
+ refused.push({ agent, path: c.rel, bytes: source.size, reason: "file-cap", limit: fileCap });
297
+ continue;
298
+ }
299
+ // A file that changes under the read throws BlobSourceError (and the
300
+ // store checks the hash it is given): the publish fails, never stores
301
+ // bytes under a name they do not have.
302
+ sha = (await hashRange(source, 0, source.size)).sha256;
303
+ size = source.size;
304
+ await pins.pinBlobs(tenant, [sha], publishHolder, { ttlMs: PUBLISH_PIN_TTL_MS });
305
+ await b.blobs.putSourceIfAbsent(blobObjectKey(tenant, sha), source, { sha256: sha });
306
+ }
307
+ files[c.rel] = { sha, size, mode: c.mode };
308
+ }
309
+ catch (err) {
310
+ if (!(err instanceof UnsafeFileError))
311
+ throw err;
312
+ refused.push({ agent, path: c.rel, bytes: c.size, reason: "unsafe" });
259
313
  }
260
- const sha = sha256Hex(body);
261
- // Pin each blob before its put; a repeat extends the lease.
262
- await pins.pinBlobs(tenant, [sha], publishHolder, { ttlMs: PUBLISH_PIN_TTL_MS });
263
- await b.blobs.putIfAbsent(blobObjectKey(tenant, sha), body);
264
- files[c.rel] = { sha, size: body.length, mode: c.mode };
265
314
  }
266
315
  };
267
316
  await Promise.all(Array.from({ length: Math.min(UPLOAD_CONCURRENCY, kept.length) }, lane));
@@ -384,6 +433,26 @@ export async function listRunOutputs(tenant, workspace, runId) {
384
433
  out.push(f);
385
434
  return out.sort((a, b) => a.agent.localeCompare(b.agent) || a.path.localeCompare(b.path));
386
435
  }
436
+ /** What the STORE holds for a run, with each file's hash — the volume is not
437
+ * asked (the backfill's verify compares these to the folder's bytes). */
438
+ export async function storedRunOutputs(tenant, workspace, runId) {
439
+ const out = [];
440
+ if (!OUT.backend)
441
+ return out;
442
+ for (const r of await recordsOf(tenant, workspace, runId)) {
443
+ const m = await loadManifest(readDeps(OUT.backend), tenant, r.manifest);
444
+ for (const [p, e] of Object.entries(m.files))
445
+ out.push({ agent: r.agent, path: p, sha: e.sha, size: e.size });
446
+ }
447
+ return out;
448
+ }
449
+ /** The blob is in the store at the size the manifest says (a head, no bytes read). */
450
+ export async function storedBlobIntact(tenant, sha, size) {
451
+ if (!OUT.backend)
452
+ return false;
453
+ const h = await OUT.backend.blobs.head(blobObjectKey(tenant, sha));
454
+ return !!h && h.size === size;
455
+ }
387
456
  /** One archived output, or null when the name escapes the archive or names
388
457
  * nothing — the API serves only what this returns. */
389
458
  export async function openRunOutput(tenant, workspace, runId, agent, rel) {
@@ -435,11 +504,13 @@ export async function openRunOutput(tenant, workspace, runId, agent, rel) {
435
504
  const file = runOutputPathOnVolume(tenant, workspace, runId, agent, rel);
436
505
  if (!file)
437
506
  return null;
438
- const size = fs.statSync(file).size;
507
+ // Opened without following a link: the path was checked by
508
+ // runOutputPathOnVolume, and a swap since (link, FIFO) is refused (SYMRACE).
509
+ const seen = statPlain(file);
439
510
  return {
440
- size,
511
+ size: seen.size,
441
512
  // Node's own bridge keeps the file stream paused until the reader pulls.
442
- read: (range) => Readable.toWeb(fs.createReadStream(file, range ? { start: range.start, end: range.end } : undefined)),
513
+ read: (range) => Readable.toWeb(plainStream(file, { dev: seen.dev, ino: seen.ino, ...(range ? { start: range.start, end: range.end } : {}) })),
443
514
  };
444
515
  }
445
516
  /** The whole file as bytes (a small one: a test, a preview). */
@@ -5,7 +5,7 @@
5
5
  import { opsLog, opsError } from "./ops-log.js";
6
6
  import { globMatch } from "./bounded-match.js";
7
7
  import { latestRevisionId } from "./history.js";
8
- import { recordCallIo, redactionsFor } from "./capture.js";
8
+ import { maskPatterns, recordCallIo, redactionsFor, scrubWith } from "./capture.js";
9
9
  import { callSink, flushCalls } from "./captured-calls.js";
10
10
  import { AUTH_REFUSAL, platformCause } from "./issues.js";
11
11
  import { hookNames } from "./hooks.js";
@@ -2099,11 +2099,27 @@ conversation) {
2099
2099
  // read; the verdict at the end of this function reads it.
2100
2100
  let canActOutward = false;
2101
2101
  const eventsAtStart = step.events.length;
2102
- const redact = (text) => {
2103
- let out = text;
2104
- for (const [value, name] of redactions)
2105
- out = out.split(value).join(`[redacted:${name}]`);
2106
- return out;
2102
+ const redact = (text) => scrubWith(redactions, text);
2103
+ // An event line, a question, a message: text that came out of a sandbox or a
2104
+ // model, read by viewers, A2A callers, notifications and exports. The values
2105
+ // above, then what no vault value covers (a key a tool printed, a private
2106
+ // key block) — the mask a captured call already gets. One place: the retry
2107
+ // row's error, the run's failure reason and a notification's summary are all
2108
+ // read back off these events.
2109
+ const mask = (text) => maskPatterns(redact(text));
2110
+ const maskOperator = (ev) => {
2111
+ switch (ev.kind) {
2112
+ case "asked":
2113
+ return { ...ev, question: mask(ev.question), ...(ev.options ? { options: ev.options.map(mask) } : {}) };
2114
+ case "message":
2115
+ case "peer":
2116
+ case "told":
2117
+ return { ...ev, text: mask(ev.text) };
2118
+ case "answered":
2119
+ return { ...ev, answer: mask(ev.answer) };
2120
+ default:
2121
+ return ev;
2122
+ }
2107
2123
  };
2108
2124
  // The reply, the conclusion and an `output: json` value land on the same
2109
2125
  // record the events do, and a model that quotes a script's stdout puts
@@ -2140,7 +2156,9 @@ conversation) {
2140
2156
  let captureFull = false;
2141
2157
  const callsRoot = path.resolve(agentDir, "..", "..");
2142
2158
  const sink = runId ? callSink(step, { tenant, workspace: path.basename(callsRoot), runId, workspaceRoot: callsRoot }) : undefined;
2143
- const push = (type, text, extra) => {
2159
+ const push = (type, text, given) => {
2160
+ // A question or a message a model wrote is masked before it is stored or sent on.
2161
+ const extra = given?.operator ? { ...given, operator: maskOperator(given.operator) } : given;
2144
2162
  const t = new Date().toISOString();
2145
2163
  // The model has begun its first response: held only in memory, for
2146
2164
  // the fan-out gate (warmGate). Not a line in the trace.
@@ -2181,7 +2199,7 @@ conversation) {
2181
2199
  rest = { ...others, captured: true };
2182
2200
  }
2183
2201
  }
2184
- step.events.push({ t, type, text: redact(text), ...rest });
2202
+ step.events.push({ t, type, text: mask(text), ...rest });
2185
2203
  // A person in the loop: the question, its answer, a message delivered —
2186
2204
  // onto the step, so the run page, the API and history show them.
2187
2205
  if (extra?.operator) {
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Reading a file a sandbox, an agent or a customer's upload could have
3
+ * touched — without following a link it swapped in after we looked.
4
+ *
5
+ * The walkers (run outputs, copy-back, folder scan, import) list a tree with
6
+ * lstat, which is honest at that moment. The read comes later, by path, and a
7
+ * path is looked up again: a regular file replaced by a symlink to /proc/self/environ
8
+ * or another tenant's file in between was followed and its bytes stored or
9
+ * served; one replaced by a FIFO blocked the whole worker in a synchronous
10
+ * read. So the read opens with O_NOFOLLOW (a link at the last step is ELOOP)
11
+ * and O_NONBLOCK (a FIFO opens at once instead of waiting for a writer), asks
12
+ * the OPEN file what it is (fstat: a regular file, within the size cap, the
13
+ * same device and inode the walk saw, when it knows them) and reads from that
14
+ * descriptor, so what was checked is what is read.
15
+ *
16
+ * `root`: a directory ON THE WAY can also be swapped for a link (the open only
17
+ * refuses a link at the last step). With a root given, after the open the
18
+ * file's real path must be inside the real root and be the very inode that was
19
+ * opened. That narrows the window to an attacker who flips a directory link
20
+ * back and forth across two syscalls; it does not close it (Node has no
21
+ * openat2 / RESOLVE_NO_SYMLINKS). Callers that need no link anywhere on the way
22
+ * must keep the directory off the sandbox's reach, as the live archive does.
23
+ *
24
+ * Windows has no O_NOFOLLOW: there the check stays what it was (lstat, then
25
+ * open, then fstat) — no weaker than before, with the same small window.
26
+ */
27
+ import fs from "node:fs";
28
+ export declare class UnsafeFileError extends Error {
29
+ readonly code = "EUNSAFEFILE";
30
+ constructor(file: string, why: string);
31
+ }
32
+ export interface PlainOpts {
33
+ /** Refuse a file bigger than this (checked on the open file, not on a stat before). */
34
+ maxBytes?: number;
35
+ /** The inode the walk saw: a different one was swapped in since. */
36
+ dev?: number | bigint;
37
+ ino?: number | bigint;
38
+ /** A real (symlink-free) directory the file must really be inside. */
39
+ root?: string;
40
+ }
41
+ /** Open a regular file for reading without following a link at its last step
42
+ * or waiting on a FIFO. The caller closes `fd`. Throws UnsafeFileError. */
43
+ export declare function openPlain(file: string, opts?: PlainOpts): {
44
+ fd: number;
45
+ st: fs.Stats;
46
+ };
47
+ /** The whole file as bytes, from the checked descriptor. */
48
+ export declare function readPlain(file: string, opts?: PlainOpts): Buffer;
49
+ export declare function readPlainText(file: string, opts?: PlainOpts): string;
50
+ /** What the file is right now (size, device, inode), without following a link. */
51
+ export declare function statPlain(file: string, opts?: PlainOpts): fs.Stats;
52
+ /** A read stream over the checked descriptor (a byte range is inclusive, as
53
+ * createReadStream's). The descriptor is closed with the stream. */
54
+ export declare function plainStream(file: string, opts?: PlainOpts & {
55
+ start?: number;
56
+ end?: number;
57
+ highWaterMark?: number;
58
+ signal?: AbortSignal;
59
+ }): fs.ReadStream;
60
+ /** The whole file as bytes, read off the event loop from the checked descriptor. */
61
+ export declare function readPlainAsync(file: string, opts?: PlainOpts): Promise<Buffer>;
62
+ /** copyFileSync, but from a checked descriptor: a link or a pipe swapped in
63
+ * since the caller's lstat is refused, not followed or waited on. The copy
64
+ * keeps the file's permission bits and is streamed (1 MiB at a time). */
65
+ export declare function copyPlain(from: string, to: string, opts?: PlainOpts): void;