@foldrun/core 23.4.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.
package/dist/src/store.js CHANGED
@@ -67,6 +67,7 @@ import { readTransport, KINDS } from "./kinds.js";
67
67
  import { providerPreset, looksOpenAiShaped, PROTECTED_PARAMS } from "./providers.js";
68
68
  import { starterFiles, accountFiles, blankWorkspaceFiles } from "./starter.js";
69
69
  import { trimSlashes, MAX_EDITABLE_FILE } from "./paths.js";
70
+ import { copyPlain, readPlainText, UnsafeFileError } from "./safe-open.js";
70
71
  // Where workspaces live. The hosted app keeps many under data/; the CLI runs
71
72
  // against one folder, which is what `foldrun run ./my-desk` has to mean.
72
73
  /**
@@ -424,7 +425,7 @@ meta = {}) {
424
425
  if (fs.existsSync(dir)) {
425
426
  for (const rel of listWorkspaceFiles(tenant, workspace)) {
426
427
  try {
427
- before.set(rel, fs.readFileSync(path.join(dir, rel), "utf8"));
428
+ before.set(rel, readPlainText(path.join(dir, rel)));
428
429
  }
429
430
  catch {
430
431
  // vanished mid-read; not part of the revision
@@ -451,7 +452,17 @@ meta = {}) {
451
452
  }
452
453
  const to = path.join(snapshot, rel);
453
454
  fs.mkdirSync(path.dirname(to), { recursive: true });
454
- fs.copyFileSync(from, to);
455
+ try {
456
+ // From a descriptor opened without following a link: the lstat above
457
+ // can be out of date by now (SYMRACE), and a swapped-in link would copy
458
+ // its target into the snapshot, then back into the workspace.
459
+ copyPlain(from, to);
460
+ }
461
+ catch (err) {
462
+ if (err instanceof UnsafeFileError || err.code === "ENOENT")
463
+ continue;
464
+ throw err;
465
+ }
455
466
  preserved.push(rel);
456
467
  }
457
468
  }
@@ -2480,7 +2491,18 @@ export function readWorkspaceFile(tenant, workspace, rel) {
2480
2491
  if (!fs.existsSync(p))
2481
2492
  throw new Error(`file not found: ${rel}`);
2482
2493
  assertLandsInside(dir, p, rel);
2483
- return fs.readFileSync(p, "utf8");
2494
+ // The check above is by path. A link that stays inside the workspace is
2495
+ // allowed, so the read goes to where it really lands, opened without
2496
+ // following a link and found still inside the workspace: a file or folder
2497
+ // swapped for a link out since the check is refused (SYMRACE).
2498
+ try {
2499
+ return readPlainText(realLanding(p) ?? p, { root: dir });
2500
+ }
2501
+ catch (err) {
2502
+ if (err instanceof UnsafeFileError)
2503
+ throw new Error(`illegal path: ${rel} leads out of the workspace through a symlink`);
2504
+ throw err;
2505
+ }
2484
2506
  }
2485
2507
  export function writeWorkspaceFile(tenant, workspace, rel, content, meta = {}) {
2486
2508
  // 512 KB: a folder tool's program is one file, and the gallery browser's is
@@ -48,6 +48,7 @@ import { headsOf, loadManifest, manifestsAt, manifestsOf, publish, restore, requ
48
48
  import { OpIdReused } from "./revision-store.js";
49
49
  import { pruneStateRevisions } from "./state-retention.js";
50
50
  import { setCallsBackend, dropWorkspaceCalls, settleCalls } from "./captured-calls.js";
51
+ import { plainStream, readPlain, readPlainAsync, UnsafeFileError } from "./safe-open.js";
51
52
  import { dropTenantOutputs, dropWorkspaceOutputs, moveWorkspaceOutputs, settleRunOutputs } from "./run-outputs.js";
52
53
  // ------------------------------------------------------------- the backend
53
54
  /** Everything this module is told at boot, and every queue that goes with it,
@@ -1002,15 +1003,33 @@ export async function reconcileAll(opts = {}) {
1002
1003
  /** A file this big is sent to the store from disk, never read whole. */
1003
1004
  const LARGE_FILE = 8 * 1024 * 1024;
1004
1005
  const LARGE_PIN_TTL_MS = 30 * 60_000;
1005
- async function hashOf(abs, size) {
1006
+ async function hashOf(abs, size, expect = {}) {
1006
1007
  // Read off the event loop: a dashboard process runs this too, and a desk can
1007
- // hold thousands of files.
1008
+ // hold thousands of files. From a descriptor opened without following a link,
1009
+ // on the inode the scan listed (a swap since is refused: safe-open.ts).
1008
1010
  if (size <= LARGE_FILE)
1009
- return sha256Hex(await fs.promises.readFile(abs));
1011
+ return sha256Hex(await readPlainAsync(abs, expect));
1010
1012
  const h = crypto.createHash("sha256");
1011
- await pipeline(fs.createReadStream(abs), h);
1013
+ await pipeline(plainStream(abs, expect), h);
1012
1014
  return h.digest("hex");
1013
1015
  }
1016
+ /** What a file holds now: its sha, null when there is none. A link or a pipe
1017
+ * that took its place since the caller's link check reads as something that
1018
+ * matches nothing — "changed meanwhile", so the file is left alone — instead
1019
+ * of being followed or waited on (safe-open.ts). */
1020
+ const NOT_A_FILE = "!not-a-regular-file";
1021
+ function shaOnDisk(abs) {
1022
+ try {
1023
+ return sha256Hex(readPlain(abs));
1024
+ }
1025
+ catch (err) {
1026
+ if (err.code === "ENOENT")
1027
+ return null;
1028
+ if (err instanceof UnsafeFileError)
1029
+ return NOT_A_FILE;
1030
+ throw err;
1031
+ }
1032
+ }
1014
1033
  /**
1015
1034
  * The workspace's content as the folder holds it now: every regular file on
1016
1035
  * one of the two sides (manifest.ts sideOf), whatever its bytes — the rule
@@ -1092,7 +1111,7 @@ async function scanFolder(tenant, workspace) {
1092
1111
  assertManifestPath(f.rel);
1093
1112
  if (lower.has(fold))
1094
1113
  throw new Error("differs only by case");
1095
- files.set(f.rel, { abs: f.abs, sha: await hashOf(f.abs, f.st.size), size: f.st.size, mode: f.st.mode & 0o111 ? MODE_EXEC : MODE_FILE });
1114
+ files.set(f.rel, { abs: f.abs, sha: await hashOf(f.abs, f.st.size, { dev: f.st.dev, ino: f.st.ino, root: dir }), size: f.st.size, mode: f.st.mode & 0o111 ? MODE_EXEC : MODE_FILE });
1096
1115
  lower.add(fold);
1097
1116
  }
1098
1117
  catch {
@@ -1286,7 +1305,7 @@ async function commitEntry(deps, tenant, workspace, entry) {
1286
1305
  changes: todo,
1287
1306
  restoredFrom: done.authored ? undefined : restoredFrom,
1288
1307
  bytesOf: async (sha) => {
1289
- const b = bytes.get(sha) ?? (onDisk.has(sha) ? fs.readFileSync(onDisk.get(sha)) : null);
1308
+ const b = bytes.get(sha) ?? (onDisk.has(sha) ? readPlain(onDisk.get(sha)) : null);
1290
1309
  if (!b)
1291
1310
  throw new Error(`the journal lost the bytes for ${sha.slice(0, 12)}…`);
1292
1311
  return b;
@@ -1467,7 +1486,7 @@ async function afterPublish(deps, ws, changes, r) {
1467
1486
  // Never through a link, on any branch below (Codex review).
1468
1487
  if (throughLink(dir, p) || (fs.existsSync(abs) && fs.lstatSync(abs).isSymbolicLink()))
1469
1488
  continue;
1470
- const local = fs.existsSync(abs) ? sha256Hex(fs.readFileSync(abs)) : null;
1489
+ const local = shaOnDisk(abs);
1471
1490
  // Only while the file is still what this pod published (or gone, for a delete).
1472
1491
  if (c.op === "delete" ? local !== null : local !== c.sha)
1473
1492
  continue;
@@ -1479,7 +1498,7 @@ async function afterPublish(deps, ws, changes, r) {
1479
1498
  // through a link — the file or a folder on its way (Codex review).
1480
1499
  if (throughLink(dir, p) || (fs.existsSync(abs) && fs.lstatSync(abs).isSymbolicLink()))
1481
1500
  continue;
1482
- if ((fs.existsSync(abs) ? sha256Hex(fs.readFileSync(abs)) : null) !== local)
1501
+ if (shaOnDisk(abs) !== local)
1483
1502
  continue;
1484
1503
  fs.mkdirSync(path.dirname(abs), { recursive: true });
1485
1504
  // A new file renamed over the old one: replaces it, follows nothing.
@@ -1634,7 +1653,7 @@ async function syncNow(tenant, workspace) {
1634
1653
  next[p] = s;
1635
1654
  continue;
1636
1655
  }
1637
- if (fs.existsSync(f.abs) && (sha256Hex(fs.readFileSync(f.abs)) !== f.sha || modeOfFile(f.abs) !== f.mode)) {
1656
+ if (fs.existsSync(f.abs) && (shaOnDisk(f.abs) !== f.sha || modeOfFile(f.abs) !== f.mode)) {
1638
1657
  ownChanges = true;
1639
1658
  next[p] = s;
1640
1659
  continue;
@@ -1707,7 +1726,7 @@ async function syncNow(tenant, workspace) {
1707
1726
  // the scan saw, or it is this pod's change now and is left alone.
1708
1727
  if (busy())
1709
1728
  return "skipped";
1710
- const nowSha = fs.existsSync(abs) ? sha256Hex(fs.readFileSync(abs)) : null;
1729
+ const nowSha = shaOnDisk(abs);
1711
1730
  if (nowSha !== (f?.sha ?? null) || (f && modeOfFile(abs) !== f.mode)) {
1712
1731
  ownChanges = true;
1713
1732
  if (synced[p])
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foldrun/core",
3
- "version": "23.4.0",
3
+ "version": "24.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/blob-types.ts CHANGED
@@ -5,6 +5,7 @@
5
5
 
6
6
  import fs from "node:fs";
7
7
  import crypto from "node:crypto";
8
+ import { plainStream, statPlain, UnsafeFileError, type PlainOpts } from "./safe-open.ts";
8
9
 
9
10
  export class BlobNotFound extends Error {
10
11
  readonly key: string;
@@ -185,15 +186,25 @@ export function bufferSource(buf: Uint8Array): BlobSource {
185
186
 
186
187
  /** A file on disk. The size is taken now; if the file is shorter (or longer)
187
188
  * when it is read, the read throws BlobSourceError rather than send a body
188
- * that no longer matches what was announced. */
189
- export function fileSource(filePath: string): BlobSource {
190
- const size = fs.statSync(filePath).size;
189
+ * that no longer matches what was announced. A link is never followed, and a
190
+ * different file (or a FIFO) swapped in since the size was taken is refused:
191
+ * each read opens the path without following links and must find the same
192
+ * inode (safe-open.ts, SYMRACE). */
193
+ export function fileSource(filePath: string, expect: PlainOpts = {}): BlobSource {
194
+ const seen = statPlain(filePath, expect);
195
+ const size = seen.size;
191
196
  return {
192
197
  size,
193
198
  async *read(start, end, signal) {
194
199
  const hi = Math.min(end, size);
195
200
  if (hi <= start) return;
196
- const stream = fs.createReadStream(filePath, { start, end: hi - 1, highWaterMark: 1 << 20, signal });
201
+ let stream: fs.ReadStream;
202
+ try {
203
+ stream = plainStream(filePath, { start, end: hi - 1, highWaterMark: 1 << 20, signal, dev: seen.dev, ino: seen.ino, root: expect.root });
204
+ } catch (err) {
205
+ if (err instanceof UnsafeFileError) throw new BlobSourceError(`${filePath} changed while it was being uploaded: ${err.message}`);
206
+ throw err;
207
+ }
197
208
  let got = 0;
198
209
  for await (const chunk of stream) {
199
210
  got += (chunk as Buffer).length;
package/src/capture.ts CHANGED
@@ -175,9 +175,19 @@ export function scrubWith(redactions: [string, string][], text: string): string
175
175
  // masked to the end of the text.
176
176
  const PRIVATE_KEY = /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z0-9 ]*PRIVATE KEY-----|$(?![\s\S]))/g;
177
177
 
178
+ /** What no vault value covers: a credential-shaped string (a GitHub, Anthropic
179
+ * or AWS key, a JWT, `token=…`, a bearer) and a private key's whole block.
180
+ * Applied after the step's own value masks, to every piece of stored text that
181
+ * came out of a sandbox or a model — a tool's output, a prompt, stderr — so a
182
+ * key a tool read off disk is not kept just because it was never a secret
183
+ * of ours. Ordinary text (ids, URLs, paths, hashes) is left as it was. */
184
+ export function maskPatterns(text: string): string {
185
+ return redactText(text).replace(PRIVATE_KEY, "[redacted:private key]");
186
+ }
187
+
178
188
  /** Masked, then cut to the cap. */
179
189
  export function maskCall(text: string, redactSecrets: (text: string) => string): { text: string; cut: boolean } {
180
- const masked = redactText(redactSecrets(text)).replace(PRIVATE_KEY, "[redacted:private key]");
190
+ const masked = maskPatterns(redactSecrets(text));
181
191
  return masked.length > CAPTURE_CAP ? { text: masked.slice(0, CAPTURE_CAP), cut: true } : { text: masked, cut: false };
182
192
  }
183
193
 
@@ -68,6 +68,7 @@ import {
68
68
  } from "./manifest.ts";
69
69
  import { headsOf, manifestsAt, publish, requestDigest, type Deps } from "./publish.ts";
70
70
  import { BlobNotFound, BlobSourceError, downloadToFile, fileSource } from "./blob-store.ts";
71
+ import { plainStream, readPlain, type PlainOpts } from "./safe-open.ts";
71
72
  import type { Revision, WorkspaceRef } from "./revision-store.ts";
72
73
  import { isPlatformPath } from "./store.ts";
73
74
 
@@ -135,9 +136,11 @@ export interface ScanOptions {
135
136
  workspaces?: string[];
136
137
  }
137
138
 
138
- export async function hashFile(abs: string): Promise<string> {
139
+ export async function hashFile(abs: string, expect: PlainOpts = {}): Promise<string> {
139
140
  const h = crypto.createHash("sha256");
140
- await pipeline(fs.createReadStream(abs), h);
141
+ // Never through a link, never waiting on a pipe, and (with `st`) the file the
142
+ // scan listed: the scan's lstat said "regular file" earlier (safe-open.ts).
143
+ await pipeline(plainStream(abs, expect), h);
141
144
  return h.digest("hex");
142
145
  }
143
146
 
@@ -313,7 +316,7 @@ async function scanWorkspace(tenant: string, workspace: string, dir: string): Pr
313
316
  if (from) ws.conflicts.push({ path: from, keptAs: rel });
314
317
  let sha: string;
315
318
  try {
316
- sha = await hashFile(f.abs);
319
+ sha = await hashFile(f.abs, { dev: f.st.dev, ino: f.st.ino, root: dir });
317
320
  } catch (err) {
318
321
  ws.unmapped.push({ path: f.rel, reason: `unreadable (${(err as NodeJS.ErrnoException).code ?? "error"})`, files: 1, bytes: f.st.size });
319
322
  continue;
@@ -508,7 +511,7 @@ export async function importWorkspace(scan: WorkspaceScan, opts: ImportOptions):
508
511
  bytesOf: async (sha) => {
509
512
  const f = bySha.get(sha);
510
513
  if (!f) throw new Error(`no source file for ${sha.slice(0, 12)}…`);
511
- const b = fs.readFileSync(f.abs);
514
+ const b = readPlain(f.abs);
512
515
  if (sha256Hex(b) !== sha) throw new Error(`${f.path} changed while it was being imported`);
513
516
  return b;
514
517
  },
@@ -51,6 +51,7 @@ import { putStepState, getStepState, dropStepState } from "./step-state.ts";
51
51
  import { stageRunInputs, type RunInputFile } from "./storage.ts";
52
52
  import { INPUTS_DIR, stagedLine } from "./run-inputs.ts";
53
53
  import { textBesideInputs } from "./input-text.ts";
54
+ import { readPlain, readPlainText, UnsafeFileError } from "./safe-open.ts";
54
55
 
55
56
  /** What crosses the boundary. Everything in here is values — pre-resolved
56
57
  * secrets in headers, assembled prompt, serializable MCP configs. */
@@ -555,8 +556,8 @@ export function applyContainerChanges(
555
556
  // the same rule as every file below.
556
557
  const dir = path.join(containerWs, ".foldrun");
557
558
  const file = path.join(dir, "copied-back.json");
558
- if (fs.lstatSync(dir).isDirectory() && fs.lstatSync(file).isFile()) {
559
- const m = JSON.parse(fs.readFileSync(file, "utf8"));
559
+ if (fs.lstatSync(dir).isDirectory()) {
560
+ const m = JSON.parse(readPlainText(file, { root: containerWs, maxBytes: 16 * 1024 * 1024 }));
560
561
  if (m && typeof m === "object" && !Array.isArray(m)) {
561
562
  for (const [rel, h] of Object.entries(m as Record<string, unknown>)) {
562
563
  // Every version the host handed back for the path counts: two jobs
@@ -592,7 +593,19 @@ export function applyContainerChanges(
592
593
  if (opts.drop && (posix.startsWith(opts.drop) || `${posix}/` === opts.drop)) continue;
593
594
  if (opts.keepOnly && !posix.startsWith(opts.keepOnly)) continue;
594
595
  if (!allowedBack(rel)) continue;
595
- let next: Buffer = fs.readFileSync(abs);
596
+ // Read from a descriptor opened without following a link, inside the
597
+ // sandbox's folder: the walk's readdir said "regular file" a moment ago,
598
+ // and the step may have swapped it for a link to the host's
599
+ // /proc/self/environ, or a FIFO that would block this read forever
600
+ // (SYMRACE). Such a path is skipped and said, like any other refusal.
601
+ let next: Buffer;
602
+ try {
603
+ next = readPlain(abs, { root: containerWs });
604
+ } catch (err) {
605
+ if (!(err instanceof UnsafeFileError)) throw err;
606
+ note?.(`${posix} was not copied back: ${err.message}`);
607
+ continue;
608
+ }
596
609
  // What the step was handed: its bytes (a staging dir) or its hash.
597
610
  // null when the file did not exist then; undefined when no baseline.
598
611
  let was: Buffer | string | null | undefined;
@@ -13,6 +13,8 @@ export function refusalText(r: RefusedOutput): string {
13
13
  return `${r.agent}/${r.path} (${mib(r.bytes)}) was not kept: this run's outputs may total at most ${mib(r.limit ?? 0)}`;
14
14
  case "count":
15
15
  return `${r.agent}/${r.path} was not kept: a run keeps at most ${r.limit ?? 50_000} files per agent`;
16
+ case "unsafe":
17
+ 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`;
16
18
  default:
17
19
  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)`;
18
20
  }
@@ -44,6 +44,7 @@ import crypto from "node:crypto";
44
44
  import { dataRoot } from "./paths.ts";
45
45
  import { processState } from "./process-state.ts";
46
46
  import { BlobNotFound, fileSource, hashRange, type BlobStore } from "./blob-store.ts";
47
+ import { plainStream, readPlain, statPlain, UnsafeFileError } from "./safe-open.ts";
47
48
  import { PUBLISH_PIN_TTL_MS, noPins, type BlobPins, type PinHolder } from "./blob-pins.ts";
48
49
  import {
49
50
  MAX_MANIFEST_FILES,
@@ -237,10 +238,17 @@ interface Candidate {
237
238
  abs: string;
238
239
  size: number;
239
240
  mode: number;
241
+ /** The inode the walk saw: the read must find the same one (safe-open.ts). */
242
+ dev: number;
243
+ ino: number;
240
244
  }
241
245
 
242
246
  function walk(root: string): Candidate[] {
243
247
  const out: Candidate[] = [];
248
+ // The folder itself a link (an agent folder pointed elsewhere): its
249
+ // contents are not this run's outputs, and the per-file root check would
250
+ // take the link's target for the root. Nothing is kept from it.
251
+ if (fs.lstatSync(root).isSymbolicLink()) return out;
244
252
  const rec = (dir: string, rel: string) => {
245
253
  for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
246
254
  const abs = path.join(dir, e.name);
@@ -248,7 +256,7 @@ function walk(root: string): Candidate[] {
248
256
  if (e.isDirectory()) rec(abs, r);
249
257
  else if (e.isFile()) {
250
258
  const st = fs.lstatSync(abs);
251
- out.push({ rel: r, abs, size: st.size, mode: st.mode & 0o111 ? MODE_EXEC : MODE_FILE });
259
+ out.push({ rel: r, abs, size: st.size, mode: st.mode & 0o111 ? MODE_EXEC : MODE_FILE, dev: st.dev, ino: st.ino });
252
260
  }
253
261
  // symlinks, sockets and the like are not outputs (the volume copy skipped them too)
254
262
  }
@@ -340,33 +348,44 @@ export async function publishRunOutputs(
340
348
  const c = kept[i];
341
349
  let sha: string;
342
350
  let size: number;
343
- if (c.size <= SMALL_OUTPUT_FILE_BYTES) {
344
- const body = fs.readFileSync(c.abs);
345
- // Grew since it was measured (an agent still writing): same rule, same cap.
346
- if (body.length > fileCap) {
347
- refused.push({ agent, path: c.rel, bytes: body.length, reason: "file-cap", limit: fileCap });
348
- continue;
349
- }
350
- sha = sha256Hex(body);
351
- size = body.length;
352
- // Pin each blob before its put; a repeat extends the lease.
353
- await pins.pinBlobs(tenant, [sha], publishHolder, { ttlMs: PUBLISH_PIN_TTL_MS });
354
- await b.blobs.putIfAbsent(blobObjectKey(tenant, sha), body);
355
- } else {
356
- const source = fileSource(c.abs);
357
- if (source.size > fileCap) {
358
- refused.push({ agent, path: c.rel, bytes: source.size, reason: "file-cap", limit: fileCap });
359
- continue;
351
+ // The walk looked with lstat; the read opens the path without following
352
+ // a link and must find the inode the walk saw (a file the agent swapped
353
+ // for a link to a secret, or a FIFO, since is refused, not read). The
354
+ // outputs folder is the root: a folder swapped for a link out is too.
355
+ const want = { dev: c.dev, ino: c.ino, root: dir };
356
+ try {
357
+ if (c.size <= SMALL_OUTPUT_FILE_BYTES) {
358
+ // A file that grew past twice the small size since the walk is not read whole.
359
+ const body = readPlain(c.abs, { ...want, maxBytes: 2 * SMALL_OUTPUT_FILE_BYTES });
360
+ // Grew since it was measured (an agent still writing): same rule, same cap.
361
+ if (body.length > fileCap) {
362
+ refused.push({ agent, path: c.rel, bytes: body.length, reason: "file-cap", limit: fileCap });
363
+ continue;
364
+ }
365
+ sha = sha256Hex(body);
366
+ size = body.length;
367
+ // Pin each blob before its put; a repeat extends the lease.
368
+ await pins.pinBlobs(tenant, [sha], publishHolder, { ttlMs: PUBLISH_PIN_TTL_MS });
369
+ await b.blobs.putIfAbsent(blobObjectKey(tenant, sha), body);
370
+ } else {
371
+ const source = fileSource(c.abs, want);
372
+ if (source.size > fileCap) {
373
+ refused.push({ agent, path: c.rel, bytes: source.size, reason: "file-cap", limit: fileCap });
374
+ continue;
375
+ }
376
+ // A file that changes under the read throws BlobSourceError (and the
377
+ // store checks the hash it is given): the publish fails, never stores
378
+ // bytes under a name they do not have.
379
+ sha = (await hashRange(source, 0, source.size)).sha256;
380
+ size = source.size;
381
+ await pins.pinBlobs(tenant, [sha], publishHolder, { ttlMs: PUBLISH_PIN_TTL_MS });
382
+ await b.blobs.putSourceIfAbsent(blobObjectKey(tenant, sha), source, { sha256: sha });
360
383
  }
361
- // A file that changes under the read throws BlobSourceError (and the
362
- // store checks the hash it is given): the publish fails, never stores
363
- // bytes under a name they do not have.
364
- sha = (await hashRange(source, 0, source.size)).sha256;
365
- size = source.size;
366
- await pins.pinBlobs(tenant, [sha], publishHolder, { ttlMs: PUBLISH_PIN_TTL_MS });
367
- await b.blobs.putSourceIfAbsent(blobObjectKey(tenant, sha), source, { sha256: sha });
384
+ files[c.rel] = { sha, size, mode: c.mode };
385
+ } catch (err) {
386
+ if (!(err instanceof UnsafeFileError)) throw err;
387
+ refused.push({ agent, path: c.rel, bytes: c.size, reason: "unsafe" });
368
388
  }
369
- files[c.rel] = { sha, size, mode: c.mode };
370
389
  }
371
390
  };
372
391
  await Promise.all(Array.from({ length: Math.min(UPLOAD_CONCURRENCY, kept.length) }, lane));
@@ -560,11 +579,13 @@ export async function openRunOutput(tenant: string, workspace: string, runId: st
560
579
  }
561
580
  const file = runOutputPathOnVolume(tenant, workspace, runId, agent, rel);
562
581
  if (!file) return null;
563
- const size = fs.statSync(file).size;
582
+ // Opened without following a link: the path was checked by
583
+ // runOutputPathOnVolume, and a swap since (link, FIFO) is refused (SYMRACE).
584
+ const seen = statPlain(file);
564
585
  return {
565
- size,
586
+ size: seen.size,
566
587
  // Node's own bridge keeps the file stream paused until the reader pulls.
567
- read: (range) => Readable.toWeb(fs.createReadStream(file, range ? { start: range.start, end: range.end } : undefined)) as ReadableStream<Uint8Array>,
588
+ read: (range) => Readable.toWeb(plainStream(file, { dev: seen.dev, ino: seen.ino, ...(range ? { start: range.start, end: range.end } : {}) })) as ReadableStream<Uint8Array>,
568
589
  };
569
590
  }
570
591
 
package/src/runner.ts CHANGED
@@ -6,7 +6,7 @@
6
6
  import { opsLog, opsError } from "./ops-log.ts";
7
7
  import { globMatch } from "./bounded-match.ts";
8
8
  import { latestRevisionId } from "./history.ts";
9
- import { recordCallIo, redactionsFor, scrubWith } from "./capture.ts";
9
+ import { maskPatterns, recordCallIo, redactionsFor, scrubWith } from "./capture.ts";
10
10
  import { callSink, flushCalls } from "./captured-calls.ts";
11
11
  import { AUTH_REFUSAL, platformCause } from "./issues.ts";
12
12
  import { hookNames } from "./hooks.ts";
@@ -45,7 +45,7 @@ const isolatedRun = () => {
45
45
  import { gatherConsults, buildConsultTools } from "./agent-tools.ts";
46
46
  import { DELEGATE_TOOL, gatherSubagents, ownSandbox, subagentPrompt, subagentTools, SUBAGENT_NO_REMOTES, type DelegateSpec, type SubagentSpec } from "./subagents.ts";
47
47
  import { DELEGATE_SERVER, buildDelegateTools, delegatePromptLine, delegateToolNames, localDelegateChannel, readCopyBack } from "./delegate-tools.ts";
48
- import type { DelegationResult } from "./operator.ts";
48
+ import type { DelegationResult, OperatorEvent } from "./operator.ts";
49
49
  import type { StepDelegation } from "./store.ts";
50
50
  import { TEXT_SERVER, TEXT_TOOL, buildTextTools, textPromptLine } from "./text-tool.ts";
51
51
  import { ASK_TOOL, PEER_TOOLS, applyOperatorEvent, askPromptLine, askTimeoutSec, buildAskTool, buildPeerTools, inboxReader, localPeerBus, peersPromptLine, type PeerInfo } from "./operator.ts";
@@ -2293,6 +2293,27 @@ async function runStepBody(
2293
2293
  let canActOutward = false;
2294
2294
  const eventsAtStart = step.events.length;
2295
2295
  const redact = (text: string) => scrubWith(redactions, text);
2296
+ // An event line, a question, a message: text that came out of a sandbox or a
2297
+ // model, read by viewers, A2A callers, notifications and exports. The values
2298
+ // above, then what no vault value covers (a key a tool printed, a private
2299
+ // key block) — the mask a captured call already gets. One place: the retry
2300
+ // row's error, the run's failure reason and a notification's summary are all
2301
+ // read back off these events.
2302
+ const mask = (text: string) => maskPatterns(redact(text));
2303
+ const maskOperator = (ev: OperatorEvent): OperatorEvent => {
2304
+ switch (ev.kind) {
2305
+ case "asked":
2306
+ return { ...ev, question: mask(ev.question), ...(ev.options ? { options: ev.options.map(mask) } : {}) };
2307
+ case "message":
2308
+ case "peer":
2309
+ case "told":
2310
+ return { ...ev, text: mask(ev.text) };
2311
+ case "answered":
2312
+ return { ...ev, answer: mask(ev.answer) };
2313
+ default:
2314
+ return ev;
2315
+ }
2316
+ };
2296
2317
 
2297
2318
  // The reply, the conclusion and an `output: json` value land on the same
2298
2319
  // record the events do, and a model that quotes a script's stdout puts
@@ -2329,7 +2350,9 @@ async function runStepBody(
2329
2350
  let captureFull = false;
2330
2351
  const callsRoot = path.resolve(agentDir, "..", "..");
2331
2352
  const sink = runId ? callSink(step, { tenant, workspace: path.basename(callsRoot), runId, workspaceRoot: callsRoot }) : undefined;
2332
- const push = (type: StepRecord["events"][number]["type"], text: string, extra?: EventExtra) => {
2353
+ const push = (type: StepRecord["events"][number]["type"], text: string, given?: EventExtra) => {
2354
+ // A question or a message a model wrote is masked before it is stored or sent on.
2355
+ const extra: EventExtra | undefined = given?.operator ? { ...given, operator: maskOperator(given.operator) } : given;
2333
2356
  const t = new Date().toISOString();
2334
2357
  // The model has begun its first response: held only in memory, for
2335
2358
  // the fan-out gate (warmGate). Not a line in the trace.
@@ -2368,7 +2391,7 @@ async function runStepBody(
2368
2391
  rest = { ...others, captured: true };
2369
2392
  }
2370
2393
  }
2371
- step.events.push({ t, type, text: redact(text), ...rest });
2394
+ step.events.push({ t, type, text: mask(text), ...rest });
2372
2395
  // A person in the loop: the question, its answer, a message delivered —
2373
2396
  // onto the step, so the run page, the API and history show them.
2374
2397
  if (extra?.operator) {