@foldrun/core 23.4.0 → 24.1.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;
@@ -30,6 +30,13 @@ export declare function encodedForms(v: string): string[];
30
30
  * masked as that value, plain or in any of the encoded forms in the list.
31
31
  */
32
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;
33
40
  /** Masked, then cut to the cap. */
34
41
  export declare function maskCall(text: string, redactSecrets: (text: string) => string): {
35
42
  text: string;
@@ -182,9 +182,18 @@ export function scrubWith(redactions, text) {
182
182
  // Unterminated too: a key cut short, or printed without its END line, is
183
183
  // masked to the end of the text.
184
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
+ }
185
194
  /** Masked, then cut to the cap. */
186
195
  export function maskCall(text, redactSecrets) {
187
- const masked = redactText(redactSecrets(text)).replace(PRIVATE_KEY, "[redacted:private key]");
196
+ const masked = maskPatterns(redactSecrets(text));
188
197
  return masked.length > CAPTURE_CAP ? { text: masked.slice(0, CAPTURE_CAP), cut: true } : { text: masked, cut: false };
189
198
  }
190
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;
@@ -220,7 +220,12 @@ export declare function unsubstitute(text: string, knownSecrets: Record<string,
220
220
  * not from what the step reports. */
221
221
  export interface SupplyGrant {
222
222
  provider: string;
223
+ /** "login": the account's Claude subscription — the proxy sends the call
224
+ * on one of the platform's Claude logins (the gateway's login path),
225
+ * after checking the account still holds a plan; nothing is metered on
226
+ * an API key. Absent: the platform's API key for `provider`, metered. */
227
+ via?: "login";
223
228
  }
224
229
  /** Grant the platform's key for `provider` under `name`, to its host. */
225
- export declare function addSupplyGrant(grant: EgressGrant, name: string, provider: string, host: string): void;
230
+ export declare function addSupplyGrant(grant: EgressGrant, name: string, provider: string, host: string, via?: "login"): void;
226
231
  export declare function addGrant(grant: EgressGrant, name: string, value: string, host: string): void;
@@ -42,7 +42,7 @@
42
42
  // This file is the vocabulary both sides share. The server is the
43
43
  // platform's (it needs a long-lived process and a Service); the pod side is
44
44
  // here in core, because it is what the runner image runs.
45
- import { supplyProviderOfToken } from "./model-supply.js";
45
+ import { supplyProviderOfToken, supplyViaOfToken } from "./model-supply.js";
46
46
  import { trimSlashes } from "./paths.js";
47
47
  /** `${NAME}` — the shape a secret reference takes everywhere in foldrun. */
48
48
  export const PLACEHOLDER = /\$\{([A-Z][A-Z0-9_]*)\}/g;
@@ -123,7 +123,7 @@ export function proxyModelEnv(env, leaseUrl, grant, knownSecrets = {}, name = MO
123
123
  export function grantModelKey(grant, name, value, host) {
124
124
  const supply = supplyProviderOfToken(value);
125
125
  if (supply)
126
- addSupplyGrant(grant, name, supply, host);
126
+ addSupplyGrant(grant, name, supply, host, supplyViaOfToken(value) ?? undefined);
127
127
  else
128
128
  addGrant(grant, name, value, host);
129
129
  }
@@ -142,20 +142,21 @@ export function unsubstitute(text, knownSecrets, host, grant) {
142
142
  return out;
143
143
  }
144
144
  /** Grant the platform's key for `provider` under `name`, to its host. */
145
- export function addSupplyGrant(grant, name, provider, host) {
145
+ export function addSupplyGrant(grant, name, provider, host, via) {
146
146
  const h = host.toLowerCase();
147
147
  const existing = grant.secrets[name];
148
148
  // A name already granted as an ordinary secret is never turned into the
149
149
  // platform's key, nor the other way round: two meanings under one name
150
- // is how a value would be filled where it was not meant to be.
151
- if (existing && existing.supply?.provider !== provider)
150
+ // is how a value would be filled where it was not meant to be. Nor is a
151
+ // subscription grant the API key's, or the other way round.
152
+ if (existing && (existing.supply?.provider !== provider || existing.supply?.via !== via))
152
153
  throw new Error(`egress: ${name} is already granted as another credential`);
153
154
  if (existing) {
154
155
  if (!existing.hosts.includes(h))
155
156
  existing.hosts.push(h);
156
157
  }
157
158
  else
158
- grant.secrets[name] = { value: "", hosts: [h], supply: { provider } };
159
+ grant.secrets[name] = { value: "", hosts: [h], supply: { provider, ...(via ? { via } : {}) } };
159
160
  }
160
161
  export function addGrant(grant, name, value, host) {
161
162
  const h = host.toLowerCase();
@@ -41,7 +41,7 @@ export function accountModelEnv(tenant, workspace, platformEnv) {
41
41
  if (supply.kind === "refused")
42
42
  throw new ModelKeyError(`foldrun's models: ${supply.reason}`, 403);
43
43
  if (supply.kind === "foldrun") {
44
- const s = parseProvider(supplyProviderBlock(supply.provider, supply.tiers));
44
+ const s = parseProvider(supplyProviderBlock(supply.provider, supply.tiers, supply.via));
45
45
  const preset = providerPreset(s.name);
46
46
  return {
47
47
  env: providerEnvFor({ baseUrl: s.baseUrl, token: s.token, auth: s.auth, models: s.models, headers: {} }),
@@ -62,7 +62,11 @@ export declare const SUPPLY_KEY_NAME = "FOLDRUN_SUPPLY_KEY";
62
62
  * What the platform says about one account's model supply, before any
63
63
  * provider: block of its own is considered (a written block always wins):
64
64
  * none — it did not choose foldrun's models: its own key, as before
65
- * foldrun — it chose them and they are on: run on the platform's key
65
+ * foldrun — it chose them and they are on: run on the platform's key;
66
+ * with `via: "login"`, on the account's Claude subscription
67
+ * instead (16 Nov 2026: an account holding a Claude Code plan
68
+ * runs its routines and sessions on Claude, counted in the
69
+ * plan's monthly and weekly windows like its Claude Code calls)
66
70
  * refused — it chose them and they cannot be had now (switched off, the
67
71
  * provider withdrawn, the account refused). The step FAILS
68
72
  * with the reason: never quietly onto the account's stored
@@ -77,16 +81,23 @@ export type SupplyAnswer = {
77
81
  /** The price list's output ceiling per model id: the most one reply
78
82
  * may be on the platform's key, told to the runtime up front. */
79
83
  ceilings?: Record<string, number>;
84
+ /** "login": the calls go on the platform's Claude logins, as the
85
+ * account's subscription — the proxy sends them through the gateway's
86
+ * login path (pool, windows, extra usage), not metered on an API key.
87
+ * Anthropic only. Absent: the platform's API key, metered. */
88
+ via?: "login";
80
89
  } | {
81
90
  kind: "refused";
82
91
  reason: string;
83
92
  };
84
- export declare const supplyToken: (provider: SupplyProviderName) => string;
93
+ export declare const supplyToken: (provider: SupplyProviderName, via?: "login") => string;
85
94
  export declare function supplyProviderOfToken(value: string | null | undefined): SupplyProviderName | null;
95
+ /** "login" when the marker is the subscription's, else null. */
96
+ export declare function supplyViaOfToken(value: string | null | undefined): "login" | null;
86
97
  /** The provider block a step on foldrun's models runs with: the preset's
87
98
  * endpoint and format, the operator's tier map, and the key as a
88
99
  * placeholder only. */
89
- export declare function supplyProviderBlock(provider: SupplyProviderName, tiers: Partial<Record<"fast" | "default" | "max", string>>): Record<string, unknown>;
100
+ export declare function supplyProviderBlock(provider: SupplyProviderName, tiers: Partial<Record<"fast" | "default" | "max", string>>, via?: "login"): Record<string, unknown>;
90
101
  /**
91
102
  * Reshape a request body for a provider (its `send`), in place. True when
92
103
  * anything changed. What a provider's schema does not list is not sent,
@@ -182,17 +182,29 @@ export const SUPPLY_KEY_NAME = "FOLDRUN_SUPPLY_KEY";
182
182
  * which the proxy fills with the platform's key. Sent anywhere unproxied
183
183
  * it is only a word a provider refuses. */
184
184
  const MARKER = "foldrun-supply:";
185
- export const supplyToken = (provider) => `${MARKER}${provider}`;
185
+ /** `+login` after the provider: the subscription's marker (SupplyAnswer.via). */
186
+ const VIA_LOGIN = "+login";
187
+ export const supplyToken = (provider, via) => `${MARKER}${provider}${via === "login" ? VIA_LOGIN : ""}`;
186
188
  export function supplyProviderOfToken(value) {
187
189
  if (typeof value !== "string" || !value.startsWith(MARKER))
188
190
  return null;
189
- const p = value.slice(MARKER.length);
191
+ let p = value.slice(MARKER.length);
192
+ if (p.endsWith(VIA_LOGIN)) {
193
+ p = p.slice(0, -VIA_LOGIN.length);
194
+ // A subscription is Claude's alone.
195
+ if (p !== "anthropic")
196
+ return null;
197
+ }
190
198
  return isSupplyProvider(p) ? p : null;
191
199
  }
200
+ /** "login" when the marker is the subscription's, else null. */
201
+ export function supplyViaOfToken(value) {
202
+ return supplyProviderOfToken(value) !== null && String(value).endsWith(VIA_LOGIN) ? "login" : null;
203
+ }
192
204
  /** The provider block a step on foldrun's models runs with: the preset's
193
205
  * endpoint and format, the operator's tier map, and the key as a
194
206
  * placeholder only. */
195
- export function supplyProviderBlock(provider, tiers) {
207
+ export function supplyProviderBlock(provider, tiers, via) {
196
208
  const p = SUPPLY_PROVIDERS[provider];
197
209
  const preset = p.preset ? providerPreset(p.preset) : undefined;
198
210
  const baseUrl = p.baseUrl ?? preset?.baseUrl;
@@ -205,7 +217,7 @@ export function supplyProviderBlock(provider, tiers) {
205
217
  base_url: baseUrl,
206
218
  format: p.format,
207
219
  auth: p.auth,
208
- token: supplyToken(provider),
220
+ token: supplyToken(provider, via),
209
221
  ...(Object.keys(tiers).length ? { models: tiers } : {}),
210
222
  };
211
223
  }
@@ -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
  }
@@ -43,6 +43,7 @@ import crypto from "node:crypto";
43
43
  import { dataRoot } from "./paths.js";
44
44
  import { processState } from "./process-state.js";
45
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";
@@ -176,6 +177,11 @@ export const HARD_OUTPUT_FILE_BYTES = 32 * 1024 * 1024 * 1024;
176
177
  const MAX_REFUSALS_ON_RECORD = 100;
177
178
  function walk(root) {
178
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;
179
185
  const rec = (dir, rel) => {
180
186
  for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
181
187
  const abs = path.join(dir, e.name);
@@ -184,7 +190,7 @@ function walk(root) {
184
190
  rec(abs, r);
185
191
  else if (e.isFile()) {
186
192
  const st = fs.lstatSync(abs);
187
- 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 });
188
194
  }
189
195
  // symlinks, sockets and the like are not outputs (the volume copy skipped them too)
190
196
  }
@@ -264,34 +270,47 @@ export async function publishRunOutputs(b, tenant, workspace, runId, agent, dir)
264
270
  const c = kept[i];
265
271
  let sha;
266
272
  let size;
267
- if (c.size <= SMALL_OUTPUT_FILE_BYTES) {
268
- const body = fs.readFileSync(c.abs);
269
- // Grew since it was measured (an agent still writing): same rule, same cap.
270
- if (body.length > fileCap) {
271
- refused.push({ agent, path: c.rel, bytes: body.length, reason: "file-cap", limit: fileCap });
272
- continue;
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);
273
292
  }
274
- sha = sha256Hex(body);
275
- size = body.length;
276
- // Pin each blob before its put; a repeat extends the lease.
277
- await pins.pinBlobs(tenant, [sha], publishHolder, { ttlMs: PUBLISH_PIN_TTL_MS });
278
- await b.blobs.putIfAbsent(blobObjectKey(tenant, sha), body);
279
- }
280
- else {
281
- const source = fileSource(c.abs);
282
- if (source.size > fileCap) {
283
- refused.push({ agent, path: c.rel, bytes: source.size, reason: "file-cap", limit: fileCap });
284
- continue;
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 });
285
306
  }
286
- // A file that changes under the read throws BlobSourceError (and the
287
- // store checks the hash it is given): the publish fails, never stores
288
- // bytes under a name they do not have.
289
- sha = (await hashRange(source, 0, source.size)).sha256;
290
- size = source.size;
291
- await pins.pinBlobs(tenant, [sha], publishHolder, { ttlMs: PUBLISH_PIN_TTL_MS });
292
- await b.blobs.putSourceIfAbsent(blobObjectKey(tenant, sha), source, { sha256: sha });
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" });
293
313
  }
294
- files[c.rel] = { sha, size, mode: c.mode };
295
314
  }
296
315
  };
297
316
  await Promise.all(Array.from({ length: Math.min(UPLOAD_CONCURRENCY, kept.length) }, lane));
@@ -485,11 +504,13 @@ export async function openRunOutput(tenant, workspace, runId, agent, rel) {
485
504
  const file = runOutputPathOnVolume(tenant, workspace, runId, agent, rel);
486
505
  if (!file)
487
506
  return null;
488
- 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);
489
510
  return {
490
- size,
511
+ size: seen.size,
491
512
  // Node's own bridge keeps the file stream paused until the reader pulls.
492
- 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 } : {}) })),
493
514
  };
494
515
  }
495
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, scrubWith } 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";
@@ -1285,7 +1285,7 @@ grantsOnly = false) {
1285
1285
  const supply = fileBlock ? { kind: "none" } : platform.modelSupply?.(tenant) ?? { kind: "none" };
1286
1286
  const providerBlock = fileBlock ??
1287
1287
  (supply.kind === "foldrun"
1288
- ? supplyProviderBlock(supply.provider, supply.tiers)
1288
+ ? supplyProviderBlock(supply.provider, supply.tiers, supply.via)
1289
1289
  : supply.kind === "refused"
1290
1290
  ? undefined
1291
1291
  : accountModelBlock((name) => getSecret(tenant, name)?.value ?? null));
@@ -2100,6 +2100,27 @@ conversation) {
2100
2100
  let canActOutward = false;
2101
2101
  const eventsAtStart = step.events.length;
2102
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
+ }
2123
+ };
2103
2124
  // The reply, the conclusion and an `output: json` value land on the same
2104
2125
  // record the events do, and a model that quotes a script's stdout puts
2105
2126
  // the credential in its answer rather than in a tool event. Same scrub,
@@ -2135,7 +2156,9 @@ conversation) {
2135
2156
  let captureFull = false;
2136
2157
  const callsRoot = path.resolve(agentDir, "..", "..");
2137
2158
  const sink = runId ? callSink(step, { tenant, workspace: path.basename(callsRoot), runId, workspaceRoot: callsRoot }) : undefined;
2138
- 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;
2139
2162
  const t = new Date().toISOString();
2140
2163
  // The model has begun its first response: held only in memory, for
2141
2164
  // the fan-out gate (warmGate). Not a line in the trace.
@@ -2176,7 +2199,7 @@ conversation) {
2176
2199
  rest = { ...others, captured: true };
2177
2200
  }
2178
2201
  }
2179
- step.events.push({ t, type, text: redact(text), ...rest });
2202
+ step.events.push({ t, type, text: mask(text), ...rest });
2180
2203
  // A person in the loop: the question, its answer, a message delivered —
2181
2204
  // onto the step, so the run page, the API and history show them.
2182
2205
  if (extra?.operator) {
@@ -2397,7 +2420,9 @@ conversation) {
2397
2420
  for (const t of step.tries ?? [])
2398
2421
  t.supply ??= before;
2399
2422
  step.credential = onSupply
2400
- ? `foldrun models · ${SUPPLY_TITLES[supply.provider]}`
2423
+ ? supply.via === "login"
2424
+ ? "Claude subscription"
2425
+ : `foldrun models · ${SUPPLY_TITLES[supply.provider]}`
2401
2426
  : credential ? credential.label : noKey ? "none — this account has no model key" : `provider: ${providerLabel}`;
2402
2427
  step.supply = onSupply ? "foldrun" : primaryOnPlatform ? "operator" : "own";
2403
2428
  if (onSupply)
@@ -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;