@foldrun/core 14.5.0 → 15.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.
package/src/ops-log.ts ADDED
@@ -0,0 +1,399 @@
1
+ // What the platform says about itself, in a shape that cannot carry an
2
+ // account's content (FOL-121).
3
+ //
4
+ // A hosted pod's stdout and stderr leave the cluster: they are our
5
+ // operations log (Grafana Cloud, through Alloy), read by us, not by the
6
+ // account whose run it was. An account's prompts, replies, files, tool
7
+ // arguments and the words of its errors belong in that account's own run
8
+ // trace — never here.
9
+ //
10
+ // FOL-107 is why. An eval judge's model process died, and modelProcessError
11
+ // did the right thing for the person (one short line in the eval result) and
12
+ // the wrong thing for the log: "the details are in the server log" meant
13
+ // 2 KB of the CLI's stderr, prompt text included, shipped out with every
14
+ // other platform line. Nothing about a string says whether it is content,
15
+ // so the rule here is structural, in three parts:
16
+ //
17
+ // 1. One writer. `opsLog(level, event, fields)` and `opsError(event, err,
18
+ // fields)` build a line from a CLOSED set of field names, each with a
19
+ // shape (FIELDS below): numbers, short lowercase words, ids with no
20
+ // whitespace, quotes, `/`, `:` or `@` — so no sentence, URL, path or
21
+ // email address fits. A value that does not fit is dropped, never
22
+ // truncated (a truncated prompt is still a prompt), and an unknown field
23
+ // name is counted, not echoed. An error is its class, its name, its
24
+ // code, its status and where in OUR code it was thrown — never its
25
+ // message, which is whatever the thrower put there.
26
+ // 2. One boundary. `installOpsBoundary()`, the first import of every
27
+ // hosted entry point (worker, egress, assistant, the web's
28
+ // instrumentation), replaces console.* and process.stdout/stderr.write.
29
+ // A raw console call becomes {"event":"console","at":"queue.ts:1511"}
30
+ // plus the class of an Error it was handed; a raw stream write becomes
31
+ // {"event":"stream.raw","bytes":n}. Its arguments are never formatted.
32
+ // Only the writer above reaches the real streams.
33
+ // 3. A guard on the source: `scripts/log-guard.mjs` refuses a new raw
34
+ // console call in server code that prints anything but a literal, and
35
+ // an opsLog/opsError whose event is not a literal.
36
+ //
37
+ // Outside a hosted process — the CLI on a laptop, `next dev`, the tests —
38
+ // no boundary is installed and the writer prints a readable line with the
39
+ // error's message: there the reader is the person whose content it is.
40
+ // FOLDRUN_LOG_MODE=raw keeps a process out of the boundary on purpose;
41
+ // infra's tests refuse it in any manifest.
42
+
43
+ import fs from "node:fs";
44
+ import os from "node:os";
45
+
46
+ /** Why something failed, in one word an operator can count. Small on
47
+ * purpose: a class is a bucket on a dashboard, not a diagnosis. */
48
+ export const ERROR_CLASSES = [
49
+ "policy_denied", // a rule said no: network, limits, a hook, a scope
50
+ "timeout", // ran out of time
51
+ "oom", // out of memory (OOMKilled, heap)
52
+ "disk_full", // ENOSPC, EDQUOT
53
+ "model_error", // the model or its process failed
54
+ "network_error", // a peer could not be reached (DNS, refused, reset)
55
+ "user_code_error", // the account's own code failed: a script, a tool, a hook
56
+ "not_found", // the thing named is not there
57
+ "cancelled", // stopped on purpose (a person, a shutdown, an abort)
58
+ "platform_error", // ours: everything else
59
+ ] as const;
60
+ export type ErrorClass = (typeof ERROR_CLASSES)[number];
61
+
62
+ export function isErrorClass(v: unknown): v is ErrorClass {
63
+ return typeof v === "string" && (ERROR_CLASSES as readonly string[]).includes(v);
64
+ }
65
+
66
+ /** The platform-wide failure causes an issue is grouped by (issues.ts
67
+ * PLATFORM_CAUSES keys), as a log field. */
68
+ export const CAUSES = ["sandbox", "model-auth", "model-cap", "model-busy", "worker"] as const;
69
+
70
+ /** A short lowercase word: an outcome, a role, a reason code. */
71
+ const WORD = /^[a-z][a-z0-9_-]{0,31}$/;
72
+ /** An id or a name: no whitespace, quotes, `/`, `:` or `@` — nothing a
73
+ * sentence, a URL, a path or an email address fits in. */
74
+ const ID = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/;
75
+ /** A code, as the field holds it: errno, SQLSTATE, an undici or Node code. */
76
+ const CODE = /^[A-Z0-9_]{2,40}$/;
77
+ /** A code an error may hand over. Not any upper-case word — an error's
78
+ * `code` is whatever its thrower set — but the system's errno names, a
79
+ * SQLSTATE (five characters, a digit first, or XX000), and Node's and
80
+ * undici's own `ERR_…` codes. */
81
+ const ERRNO = new Set(Object.keys(os.constants.errno));
82
+ function knownCode(code: string): boolean {
83
+ return ERRNO.has(code) || /^[0-9][0-9A-Z]{4}$/.test(code) || /^XX00[0-2]$/.test(code) || /^(UND_)?ERR_[A-Z0-9_]{2,36}$/.test(code);
84
+ }
85
+ /** An Error subclass's name, as the field holds it. */
86
+ const ERROR_NAME = /^[A-Z][A-Za-z0-9]{0,40}$/;
87
+ /** Names an error's `name` may give as they are; any other comes from its
88
+ * class (`constructor.name`) — our code's, since an account's code does
89
+ * not run in a platform process — because `name` is a settable string. */
90
+ const BUILTIN_NAMES = new Set(["Error", "TypeError", "RangeError", "SyntaxError", "ReferenceError", "EvalError", "URIError", "AggregateError", "AbortError", "TimeoutError", "SystemError"]);
91
+ /** Where in our code: a source file's base name and a line. */
92
+ const FRAME = /^[A-Za-z0-9_.-]{1,60}\.(ts|tsx|mts|js|mjs|cjs):\d{1,6}$/;
93
+ const EVENT = /^[a-z][a-z0-9_]*(\.[a-z0-9_]+){0,3}$/;
94
+
95
+ type Kind = "id" | "num" | "word" | "code" | "class" | "cause" | "errorName" | "frame" | "frames" | "bool";
96
+
97
+ /** Every field a platform log line may carry, and its shape. Adding one is
98
+ * a decision that its values can never be an account's content. */
99
+ export const FIELDS: Record<string, Kind> = {
100
+ // Who and what: ids, and the names an account gave its workspaces, flows,
101
+ // agents and evals (identifiers, by policy — never their contents).
102
+ tenant: "id", workspace: "id", flow: "id", agent: "id", eval: "id", tool: "id",
103
+ runId: "id", jobId: "id", taskId: "id", proposal: "id", lease: "id", pod: "id",
104
+ worker: "id", provider: "id", plan: "id", fingerprint: "id", invoice: "id", order: "id",
105
+ stripeEvent: "id", subscription: "id", migration: "id", housekeeping: "id",
106
+ // How many, how long, how much.
107
+ count: "num", ms: "num", secs: "num", bytes: "num", usd: "num", attempt: "num",
108
+ step: "num", port: "num", status: "num", exitCode: "num", percent: "num", tries: "num",
109
+ // What kind.
110
+ op: "word", role: "word", outcome: "word", reason: "word", stream: "word", kind: "word",
111
+ verdict: "word", phase: "word", signal: "code", where: "word",
112
+ // A failure.
113
+ errorClass: "class", errorName: "errorName", code: "code", syscall: "word", cause: "cause",
114
+ at: "frame", frames: "frames", retrying: "bool", ok: "bool",
115
+ };
116
+
117
+ export type OpsValue = string | number | boolean | null | undefined | readonly string[];
118
+ export type OpsFields = Record<string, OpsValue>;
119
+ export type OpsLevel = "info" | "warn" | "error";
120
+
121
+ /** Is this value one this kind of field may carry? */
122
+ function fits(kind: Kind, v: unknown): boolean {
123
+ switch (kind) {
124
+ case "num": return typeof v === "number" && Number.isFinite(v);
125
+ case "bool": return typeof v === "boolean";
126
+ case "id": return typeof v === "string" && ID.test(v);
127
+ case "word": return typeof v === "string" && WORD.test(v);
128
+ case "code": return typeof v === "string" && CODE.test(v);
129
+ case "class": return isErrorClass(v);
130
+ case "cause": return typeof v === "string" && (CAUSES as readonly string[]).includes(v);
131
+ case "errorName": return typeof v === "string" && ERROR_NAME.test(v);
132
+ case "frame": return typeof v === "string" && FRAME.test(v);
133
+ case "frames": return Array.isArray(v) && v.length <= 5 && v.every((f) => typeof f === "string" && FRAME.test(f));
134
+ }
135
+ }
136
+
137
+ /**
138
+ * The line as an object: the event, the fields that fit, and how many did
139
+ * not (by count — a refused field's name could itself be the content).
140
+ */
141
+ export function opsLine(level: OpsLevel, event: string, fields: OpsFields = {}): Record<string, unknown> {
142
+ const line: Record<string, unknown> = { ops: 1, level, event: typeof event === "string" && event.length <= 64 && EVENT.test(event) ? event : "invalid_event" };
143
+ let dropped = 0;
144
+ for (const [k, v] of Object.entries(fields)) {
145
+ if (v === undefined || v === null) continue;
146
+ const kind = Object.prototype.hasOwnProperty.call(FIELDS, k) ? FIELDS[k] : undefined;
147
+ if (!kind || !fits(kind, v)) {
148
+ dropped += 1;
149
+ continue;
150
+ }
151
+ line[k] = v;
152
+ }
153
+ if (dropped) line.dropped = dropped;
154
+ return line;
155
+ }
156
+
157
+ // ------------------------------------------------------------------ writing
158
+
159
+ type Write = (text: string) => void;
160
+ /** The real streams, once the boundary holds them; null outside it. */
161
+ let real: { out: Write; err: Write } | null = null;
162
+
163
+ /** Is this process inside the boundary — a hosted pod? */
164
+ export function opsBoundaryInstalled(): boolean {
165
+ return real !== null;
166
+ }
167
+
168
+ function readable(level: OpsLevel, line: Record<string, unknown>, detail?: string): string {
169
+ const parts = Object.entries(line)
170
+ .filter(([k]) => k !== "ops" && k !== "level" && k !== "event")
171
+ .map(([k, v]) => `${k}=${Array.isArray(v) ? v.join(",") : String(v)}`);
172
+ return `[ops] ${line.event}${parts.length ? ` ${parts.join(" ")}` : ""}${detail ? ` — ${detail}` : ""}`;
173
+ }
174
+
175
+ function emit(level: OpsLevel, line: Record<string, unknown>, detail?: string): void {
176
+ if (real) {
177
+ (level === "info" ? real.out : real.err)(JSON.stringify(line) + "\n");
178
+ return;
179
+ }
180
+ // No boundary: a laptop, a test, `next dev` — the reader is the person
181
+ // whose content it is, so the error's own words come along.
182
+ const text = readable(level, line, detail);
183
+ if (level === "info") console.log(text);
184
+ else if (level === "warn") console.warn(text);
185
+ else console.error(text);
186
+ }
187
+
188
+ /** Say something about the platform: an event and its fields. */
189
+ export function opsLog(level: OpsLevel, event: string, fields: OpsFields = {}): void {
190
+ emit(level, opsLine(level, event, fields));
191
+ }
192
+
193
+ // ------------------------------------------------------------------- errors
194
+
195
+ /** Which class an error belongs to — from its code, its name and its status;
196
+ * a few fixed markers our own code and the cluster write are matched in its
197
+ * message, which never leaves this function. */
198
+ export function errorClass(err: unknown): ErrorClass {
199
+ try {
200
+ if (!err || typeof err !== "object") return "platform_error";
201
+ const e = err as { name?: unknown; code?: unknown; status?: unknown; statusCode?: unknown; errorClass?: unknown; message?: unknown };
202
+ if (isErrorClass(e.errorClass)) return e.errorClass;
203
+ const code = typeof e.code === "string" ? e.code : typeof e.code === "number" ? String(e.code) : "";
204
+ const name = typeof e.name === "string" ? e.name : "";
205
+ const status = typeof e.status === "number" ? e.status : typeof e.statusCode === "number" ? e.statusCode : 0;
206
+ if (name === "TimeoutError" || ["ETIMEDOUT", "ESOCKETTIMEDOUT", "UND_ERR_HEADERS_TIMEOUT", "UND_ERR_BODY_TIMEOUT", "UND_ERR_CONNECT_TIMEOUT", "57014"].includes(code)) return "timeout";
207
+ if (name === "AbortError" || code === "ABORT_ERR") return "cancelled";
208
+ if (code === "ENOSPC" || code === "EDQUOT" || code === "53100") return "disk_full";
209
+ if (code === "ENOMEM" || code === "ERR_WORKER_OUT_OF_MEMORY" || code === "53200") return "oom";
210
+ if (["ECONNREFUSED", "ECONNRESET", "ENOTFOUND", "EAI_AGAIN", "EHOSTUNREACH", "ENETUNREACH", "EPIPE", "UND_ERR_SOCKET", "UND_ERR_CONNECT", "08000", "08001", "08003", "08006"].includes(code)) return "network_error";
211
+ if (code === "ENOENT" || code === "ENOTDIR" || status === 404) return "not_found";
212
+ if (code === "EACCES" || code === "EPERM" || status === 401 || status === 403 || status === 423) return "policy_denied";
213
+ if (status === 408 || status === 504) return "timeout";
214
+ const message = typeof e.message === "string" ? e.message.slice(0, 4000) : "";
215
+ if (/\bOOMKilled\b|JavaScript heap out of memory/.test(message)) return "oom";
216
+ if (/no space left on device/i.test(message)) return "disk_full";
217
+ if (/\b(Claude Code process|model process|api\.anthropic\.com)\b/.test(message)) return "model_error";
218
+ return "platform_error";
219
+ } catch {
220
+ return "platform_error";
221
+ }
222
+ }
223
+
224
+ /** Is this source path the platform's own code (core, platform, web, their
225
+ * dependencies), not something an account brought — and a file that is
226
+ * really there? A stack is a settable string; a frame naming a file that
227
+ * does not exist was written by someone, not by V8. */
228
+ const seenPaths = new Map<string, boolean>();
229
+ function ourPath(p: string): boolean {
230
+ if (/^node:[a-z_/]+$/.test(p)) return true;
231
+ // A checkout (the image runs core and platform from source), the web's
232
+ // build, or the published package (`node_modules/@foldrun/core/dist`).
233
+ if (!/\/foldrun-(core|platform|web)\/(src|server|app|lib|dist|\.next|node_modules|tests|scripts|instrumentation)|\/node_modules\/@foldrun\//.test(p)) return false;
234
+ let known = seenPaths.get(p);
235
+ if (known === undefined) {
236
+ try {
237
+ known = fs.statSync(p).isFile();
238
+ } catch {
239
+ known = false;
240
+ }
241
+ if (seenPaths.size > 2000) seenPaths.clear();
242
+ seenPaths.set(p, known);
243
+ }
244
+ return known;
245
+ }
246
+
247
+ /** `file.ts:12` frames of our code from a stack, first `max` of them. The
248
+ * first line (the message) is never read, and function names are left
249
+ * out: only a base name and a line, which a sentence cannot be. */
250
+ export function stackFrames(stack: unknown, max = 5, skip = 0): string[] {
251
+ if (typeof stack !== "string") return [];
252
+ const out: string[] = [];
253
+ let seen = 0;
254
+ for (const raw of stack.slice(0, 20_000).split("\n")) {
255
+ const m = /^\s+at (?:.*? \()?(.+?):(\d+):\d+\)?$/.exec(raw);
256
+ if (!m) continue;
257
+ const where = m[1].replace(/^file:\/\//, "");
258
+ if (!ourPath(where)) continue;
259
+ if (seen++ < skip) continue;
260
+ const frame = `${where.split("/").pop()}:${m[2]}`;
261
+ if (FRAME.test(frame)) out.push(frame);
262
+ if (out.length >= max) break;
263
+ }
264
+ return out;
265
+ }
266
+
267
+ /** The fields of an error a log line may carry. Never throws: a getter on a
268
+ * strange object is not allowed to take the log down with it. */
269
+ export function errorFields(err: unknown): OpsFields {
270
+ try {
271
+ const e = (err && typeof err === "object" ? err : {}) as { name?: unknown; code?: unknown; syscall?: unknown; status?: unknown; statusCode?: unknown; stack?: unknown; opsReason?: unknown };
272
+ const code = typeof e.code === "string" ? e.code : typeof e.code === "number" ? String(e.code) : undefined;
273
+ const status = typeof e.status === "number" ? e.status : typeof e.statusCode === "number" ? e.statusCode : undefined;
274
+ let errorName = "NotAnError";
275
+ if (err instanceof Error) {
276
+ const cls = (err as { constructor?: { name?: unknown } }).constructor?.name;
277
+ errorName = BUILTIN_NAMES.has(err.name) ? err.name : typeof cls === "string" && ERROR_NAME.test(cls) ? cls : "Error";
278
+ }
279
+ return {
280
+ errorClass: errorClass(err),
281
+ errorName,
282
+ code: code && CODE.test(code) && knownCode(code) ? code : undefined,
283
+ syscall: typeof e.syscall === "string" && WORD.test(e.syscall) ? e.syscall : undefined,
284
+ status,
285
+ // A reason our own code attached (`opsReason`: a word, by FIELDS).
286
+ reason: typeof e.opsReason === "string" && WORD.test(e.opsReason) ? e.opsReason : undefined,
287
+ frames: err instanceof Error ? stackFrames(e.stack) : [],
288
+ };
289
+ } catch {
290
+ return { errorClass: "platform_error", errorName: "Error" };
291
+ }
292
+ }
293
+
294
+ /** An Error whose message is for a person and whose `reason` — a word —
295
+ * is what a hosted log says instead: `throw withOpsReason(new Error("egress.ts
296
+ * needs FOLDRUN_EGRESS_URL…"), "no_egress_url")`. */
297
+ export function withOpsReason<E extends Error>(err: E, reason: string): E {
298
+ return Object.assign(err, { opsReason: reason });
299
+ }
300
+
301
+ /** The message an error would show, for the readable line outside the
302
+ * boundary only. */
303
+ function messageOf(err: unknown): string {
304
+ try {
305
+ return err instanceof Error ? err.message : String(err);
306
+ } catch {
307
+ return "";
308
+ }
309
+ }
310
+
311
+ /** A failure: its class and where it happened — never its words inside the
312
+ * boundary. A field the caller names (an `errorClass` it knows) wins. */
313
+ export function opsError(event: string, err: unknown, fields: OpsFields = {}, level: OpsLevel = "error"): void {
314
+ emit(level, opsLine(level, event, { ...errorFields(err), ...fields }), real ? undefined : messageOf(err));
315
+ }
316
+
317
+ // ----------------------------------------------------------------- boundary
318
+
319
+ /** Where in our code a raw console call was made: the first frame outside
320
+ * this file. From a stack we made, so it is a real code location. */
321
+ function callsite(): string | undefined {
322
+ const stack = new Error().stack ?? "";
323
+ for (const raw of stack.split("\n").slice(1)) {
324
+ const m = /^\s+at (?:.*? \()?(.+?):(\d+):\d+\)?$/.exec(raw);
325
+ if (!m || /\/ops-log\.(ts|js)$/.test(m[1])) continue;
326
+ const where = m[1].replace(/^file:\/\//, "");
327
+ if (!ourPath(where)) return undefined;
328
+ const frame = `${where.split("/").pop()}:${m[2]}`;
329
+ return FRAME.test(frame) ? frame : undefined;
330
+ }
331
+ return undefined;
332
+ }
333
+
334
+ export interface BoundaryOptions {
335
+ /** On an uncaught exception or unhandled rejection: log its class and
336
+ * exit 1, as Node would — for processes with no handler of their own
337
+ * (the worker, egress, the assistant; Next.js has its own). */
338
+ exitOnUncaught?: boolean;
339
+ env?: NodeJS.ProcessEnv;
340
+ }
341
+
342
+ /**
343
+ * Put this process inside the boundary. Idempotent. Off only where
344
+ * FOLDRUN_LOG_MODE=raw or NODE_ENV=development (`next dev`).
345
+ */
346
+ export function installOpsBoundary(opts: BoundaryOptions = {}): boolean {
347
+ const env = opts.env ?? process.env;
348
+ if (real) return true;
349
+ if (env.FOLDRUN_LOG_MODE === "raw" || (env.FOLDRUN_LOG_MODE !== "ops" && env.NODE_ENV === "development")) return false;
350
+ const outWrite = process.stdout.write.bind(process.stdout) as (s: string) => boolean;
351
+ const errWrite = process.stderr.write.bind(process.stderr) as (s: string) => boolean;
352
+ real = { out: (s) => void outWrite(s), err: (s) => void errWrite(s) };
353
+
354
+ const fromConsole = (level: OpsLevel) => (...args: unknown[]) => {
355
+ // Never formatted: an argument's text, its inspect() and its toJSON()
356
+ // are not read. An Error handed over gives its class, name and code.
357
+ let firstError: unknown;
358
+ for (const a of args) {
359
+ if (a instanceof Error) {
360
+ firstError = a;
361
+ break;
362
+ }
363
+ }
364
+ const fields: OpsFields = { at: callsite(), ...(firstError ? errorFields(firstError) : {}) };
365
+ emit(level, opsLine(level, "console", fields));
366
+ };
367
+ console.log = fromConsole("info");
368
+ console.info = fromConsole("info");
369
+ console.debug = fromConsole("info");
370
+ console.trace = fromConsole("info");
371
+ console.warn = fromConsole("warn");
372
+ console.error = fromConsole("error");
373
+
374
+ // Anything else that writes to the streams — a dependency, Next.js, a
375
+ // warning — is counted, not passed on. The write contract is kept: the
376
+ // callback runs, and the answer is "keep writing".
377
+ const fromStream = (stream: "stdout" | "stderr") =>
378
+ function write(chunk: unknown, encoding?: unknown, cb?: unknown): boolean {
379
+ const done = typeof encoding === "function" ? encoding : cb;
380
+ const bytes = typeof chunk === "string" ? Buffer.byteLength(chunk) : chunk instanceof Uint8Array ? chunk.byteLength : 0;
381
+ emit(stream === "stdout" ? "info" : "error", opsLine(stream === "stdout" ? "info" : "error", "stream.raw", { stream, bytes, at: callsite() }));
382
+ if (typeof done === "function") queueMicrotask(() => (done as (e?: Error | null) => void)(null));
383
+ return true;
384
+ };
385
+ process.stdout.write = fromStream("stdout") as typeof process.stdout.write;
386
+ process.stderr.write = fromStream("stderr") as typeof process.stderr.write;
387
+
388
+ if (opts.exitOnUncaught) {
389
+ process.on("uncaughtException", (err) => {
390
+ opsError("process.uncaught_exception", err);
391
+ process.exit(1);
392
+ });
393
+ process.on("unhandledRejection", (err) => {
394
+ opsError("process.unhandled_rejection", err);
395
+ process.exit(1);
396
+ });
397
+ }
398
+ return true;
399
+ }
package/src/platform.ts CHANGED
@@ -105,7 +105,9 @@ export interface PlatformHooks {
105
105
  tenant: string,
106
106
  workspace: string,
107
107
  flow: FlowInfo,
108
- opts?: { deliveryKey?: string | null; reason?: string },
108
+ /** `code`: the refusal's own code, when it had one — `waiting_cap`
109
+ * is logged as `queue-full` rather than `failed`. */
110
+ opts?: { deliveryKey?: string | null; reason?: string; code?: string },
109
111
  ): Promise<void>;
110
112
  /** Step executors by FOLDRUN_RUN_ISOLATION value, beyond the `container`
111
113
  * one core ships. The platform adds `k8s`. */
@@ -155,6 +157,16 @@ export interface PlatformHooks {
155
157
  * only where no provider: block of the account's own says otherwise.
156
158
  * Absent: nobody can (a laptop, a self-hosted install). */
157
159
  modelSupply?(tenant: string): SupplyAnswer;
160
+ /**
161
+ * Does this isolation mode wall a step's network to the egress proxy and
162
+ * DNS when its `network:` is restricted and enforced — and is browsing
163
+ * put under that wall (FOL-110 phase 3, browse-egress.ts browseVerdict)?
164
+ * True: a browsing step gets the forward proxy like any other and its
165
+ * browser runs inside the walled sandbox, so the list holds for it.
166
+ * Absent or false: a browsing step browses as before phase 3, said in the
167
+ * trace as not enforced.
168
+ */
169
+ confinesBrowsing?(isolation: string): boolean;
158
170
  /**
159
171
  * An operator setting, by the environment variable that used to hold it
160
172
  * (30 Oct 2026): the platform answers with the operator's value where one
package/src/runner.ts CHANGED
@@ -3,6 +3,7 @@
3
3
  // fail without failing the flow. A direct agent run is a one-step ad-hoc
4
4
  // flow, so there is a single execution path.
5
5
 
6
+ import { opsLog, opsError } from "./ops-log.ts";
6
7
  import { globMatch } from "./bounded-match.ts";
7
8
  import { latestRevisionId } from "./history.ts";
8
9
  import { recordCallIo, redactionsFor } from "./capture.ts";
@@ -101,7 +102,7 @@ import { PromptLayers, promptCacheKey } from "./prompt-layers.ts";
101
102
  import { loadCatalog, checkModel, clampEffort, catalogCost, findModel, tokenPriceOf, type Catalog, type TokenPrice } from "./catalog.ts";
102
103
  import { resolveSecrets, getSecret, materializeSecrets, secretSites, isClientCertValue, clientCertOf, withoutHeldCerts, isIdentityValue, identityOf } from "./secrets.ts";
103
104
  import { resolveNetwork, networkLine, networkEnforceWanted, proxyEnv, siteCovers, EGRESS_CA_ENV } from "./network.ts";
104
- import { browseNetworkLine } from "./browse-egress.ts";
105
+ import { BROWSER_CONFINED_ENV, browseNetworkLine, browseVerdict } from "./browse-egress.ts";
105
106
  import { materializeFileSecrets, cleanupFileSecrets } from "./secret-files.ts";
106
107
  import { buildApiTools, secretsUsedByApi } from "./api-tools.ts";
107
108
  import { buildA2ATools } from "./a2a-tools.ts";
@@ -2428,7 +2429,7 @@ async function runStep(
2428
2429
  const why = await platform.checkUntrustedUrl(r.card);
2429
2430
  if (why) {
2430
2431
  cardProblems.set(r.name, why);
2431
- console.warn(`[a2a] remotes: ${r.name} refused for ${tenant}/${path.basename(workspaceRootOf(agentDir))} (${step.agent}): ${why}`);
2432
+ opsLog("warn", "a2a.remote_refused", { tenant, workspace: path.basename(workspaceRootOf(agentDir)), agent: step.agent, tool: r.name });
2432
2433
  }
2433
2434
  }
2434
2435
  const stepRemotes: RemoteSpec[] = remotes.map((r) => {
@@ -3035,6 +3036,27 @@ async function runStep(
3035
3036
  save();
3036
3037
  return;
3037
3038
  }
3039
+ // A step that may browse, on an install with the forward door: held to
3040
+ // its list where the executor walls the step's network, refused when
3041
+ // it names a vendor that list cannot hold, else as before phase 3
3042
+ // (browse-egress.ts browseVerdict, FOL-110).
3043
+ const browses = scriptSpecs.some((sc) => sc.name === "web") && (!web.actions || web.actions.includes("browse"));
3044
+ const browse = browses && lease?.proxy
3045
+ ? browseVerdict({
3046
+ level: network.level,
3047
+ enforce: lease.enforce === true,
3048
+ vendor: clockEnv.FOLDRUN_BROWSER_VENDOR,
3049
+ confines: !!isolation && platform.confinesBrowsing?.(isolation) === true,
3050
+ })
3051
+ : null;
3052
+ if (lease && browse?.kind === "refuse") {
3053
+ push("info", networkLine(network, true));
3054
+ push("error", browse.message);
3055
+ await lease.release();
3056
+ step.status = "failed";
3057
+ save();
3058
+ return;
3059
+ }
3038
3060
  // Serve those jobs while this step runs: each one becomes a step of
3039
3061
  // its own (delegateJob), and the door answers the long-poll with its
3040
3062
  // reply. No proxy, or a platform without the door: not offered — the
@@ -3060,16 +3082,18 @@ async function runStep(
3060
3082
  // The forward door: every program in the sandbox sends through the
3061
3083
  // proxy, which holds the site list and fills bound secrets. A proxy
3062
3084
  // without the door (an older platform) leaves programs going direct.
3063
- // A step that may browse gets no proxy variables: the browser in it
3064
- // reads HTTPS_PROXY too, and Chromium cannot send credentials written
3065
- // into a proxy URL — every page failed ERR_INVALID_AUTH_CREDENTIALS
3066
- // (14 Oct 2026, the reel posters). Such a step is open by default,
3067
- // and its bound secrets materialise as they did before the door.
3068
- const browses = scriptSpecs.some((sc) => sc.name === "web") && (!web.actions || web.actions.includes("browse"));
3069
- const forward = lease?.proxy && !browses ? lease : null;
3070
- // A browsing step on an install with the door says it is not held to
3071
- // its list yet, and which tier its browser falls in (browse-egress.ts).
3072
- push("info", browses && lease?.proxy ? browseNetworkLine(network, clockEnv.FOLDRUN_BROWSER_VENDOR) : networkLine(network, forward ? forward.enforce === true : null));
3085
+ // A step that may browse gets no proxy variables unless it is held
3086
+ // (browse.kind "hosted"): the browser in it reads HTTPS_PROXY too, and
3087
+ // Chromium cannot send credentials written into a proxy URL — every
3088
+ // page failed ERR_INVALID_AUTH_CREDENTIALS (14 Oct 2026, the reel
3089
+ // posters). A held step's web tool hands the browser the proxy and its
3090
+ // credential as launch options instead (FOLDRUN_BROWSER_CONFINED).
3091
+ // Every other browsing step is open by default, and its bound secrets
3092
+ // materialise as they did before the door.
3093
+ const forward = lease?.proxy && (!browses || browse?.kind === "hosted") ? lease : null;
3094
+ // A browsing step on an install with the door says whether it is held
3095
+ // to its list, and which tier its browser falls in (browse-egress.ts).
3096
+ push("info", browse ? browseNetworkLine(network, clockEnv.FOLDRUN_BROWSER_VENDOR, { hosted: browse.kind === "hosted" }) : networkLine(network, forward ? forward.enforce === true : null));
3073
3097
  const bound = forward ? Object.keys(boundSites).filter((name) => name in liveSecrets) : [];
3074
3098
  for (const name of bound) {
3075
3099
  for (const site of boundSites[name]) addGrant(grant, name, liveSecrets[name], site);
@@ -3297,11 +3321,20 @@ async function runStep(
3297
3321
  // Every program's HTTP(S) through the proxy's forward door, and
3298
3322
  // the CA it signs bound sites with, for the sandbox to trust.
3299
3323
  ...(forward ? proxyEnv(forward.proxy!) : {}),
3324
+ // A browsing step held to its list: the web tool gives its
3325
+ // browser the forward door as launch options, refuses what
3326
+ // cannot go through it, and the platform starts no account
3327
+ // browser pod for it (browse-egress.ts, FOL-110 phase 3).
3328
+ ...(browse?.kind === "hosted" ? { [BROWSER_CONFINED_ENV]: "1" } : {}),
3300
3329
  // Only a step with a bound secret has a site the proxy
3301
3330
  // intercepts, so only that step's TLS clients are pointed at a
3302
3331
  // bundle with the egress CA in it; every other step's are as
3303
3332
  // they always were.
3304
- ...(forward?.ca && bound.length ? { [EGRESS_CA_ENV]: Buffer.from(forward.ca).toString("base64") } : {}),
3333
+ // A browser held to its list (browse "hosted") meets the proxy's
3334
+ // leaf on any host a secret is granted to — an api tool's, a web
3335
+ // provider's — not only a bound site, so it is handed the CA
3336
+ // whenever the step has one: the web tool trusts it for Chromium.
3337
+ ...(forward?.ca && (bound.length || (browse?.kind === "hosted" && Object.keys(grant.secrets).length)) ? { [EGRESS_CA_ENV]: Buffer.from(forward.ca).toString("base64") } : {}),
3305
3338
  ...clockEnv,
3306
3339
  // Who is running: the in-process path stamps scripts with these
3307
3340
  // host-side, but a container rebuilds its tools from its own
@@ -4255,7 +4288,8 @@ export function platformModelCredential(env: NodeJS.ProcessEnv = process.env): s
4255
4288
  // thing an operator needs to know about before the next step fails.
4256
4289
  if (!credentialFileWarned) {
4257
4290
  credentialFileWarned = true;
4258
- console.warn(`[model] FOLDRUN_MODEL_KEY_FILE=${file} could not be read; falling back to the environment`);
4291
+ // FOLDRUN_MODEL_KEY_FILE could not be read: the environment's key is used.
4292
+ opsLog("warn", "model.key_file_unreadable", { outcome: "environment" });
4259
4293
  }
4260
4294
  }
4261
4295
  }
@@ -6377,7 +6411,7 @@ export function reconcileRuns(tenant: string, now = Date.now(), live?: ReadonlyS
6377
6411
  const after = readRun(tenant, workspace.name, run.id);
6378
6412
  if (onEnd && after && (after.status === "completed" || after.status === "failed")) return onEnd(tenant, workspace.name, run.id);
6379
6413
  })
6380
- .catch((err) => console.error(`[foldrun] reconcile: ${tenant}/${workspace.name}/${run.id} after resume:`, err));
6414
+ .catch((err) => opsError("reconcile.after_resume_failed", err, { tenant, workspace: workspace.name, runId: run.id }));
6381
6415
  closed.push({
6382
6416
  runId: run.id,
6383
6417
  tenant,
@@ -6425,7 +6459,7 @@ export function reconcileRuns(tenant: string, now = Date.now(), live?: ReadonlyS
6425
6459
  if (onEnd) {
6426
6460
  void Promise.resolve()
6427
6461
  .then(() => onEnd(tenant, workspace.name, run.id))
6428
- .catch((err) => console.error(`[foldrun] reconcile: ${tenant}/${workspace.name}/${run.id} after close:`, err));
6462
+ .catch((err) => opsError("reconcile.after_close_failed", err, { tenant, workspace: workspace.name, runId: run.id }));
6429
6463
  }
6430
6464
  }
6431
6465
  }
package/src/secrets.ts CHANGED
@@ -19,6 +19,7 @@
19
19
  // Secrets are injected as environment variables into the agent's tools at run
20
20
  // time and are never returned by the API.
21
21
 
22
+ import { opsLog, withOpsReason } from "./ops-log.ts";
22
23
  import fs from "node:fs";
23
24
  import path from "node:path";
24
25
  import { dataRoot } from "./paths.ts";
@@ -71,7 +72,7 @@ export function installKeyMaterial(): string {
71
72
  // so; without this, asking for it would quietly mint a NEW random key on
72
73
  // the shared data volume — a second root key nobody chose.
73
74
  if (process.env.FOLDRUN_INSTALL_KEY_ABSENT === "1") {
74
- throw new Error("this process runs without the install key (FOLDRUN_INSTALL_KEY_ABSENT=1) — whatever asked for it belongs in the worker");
75
+ throw withOpsReason(new Error("this process runs without the install key (FOLDRUN_INSTALL_KEY_ABSENT=1) — whatever asked for it belongs in the worker"), "install_key_absent");
75
76
  }
76
77
  fs.mkdirSync(dataRoot(), { recursive: true });
77
78
  if (!fs.existsSync(keyFile())) {
@@ -549,10 +550,8 @@ function decrypt(tenant: string, rec: StoredSecret | undefined, aad?: Buffer): s
549
550
  // "no such secret" — a process that forgot to load the account keys
550
551
  // would look exactly like an account that never set one, which is the
551
552
  // most expensive kind of wrong answer to debug.
552
- console.error(
553
- `[secrets] ${tenant} has account-keyed secrets but no key is loaded — ` +
554
- `call loadTenantKeys() before reading, or the value will read as absent`,
555
- );
553
+ // loadTenantKeys() was not called before reading: the value reads as absent.
554
+ opsLog("error", "secrets.account_key_not_loaded", { tenant });
556
555
  return null;
557
556
  }
558
557
  key = own;
package/src/step-exec.ts CHANGED
@@ -8,6 +8,7 @@
8
8
  // results. That is what lets the same function run somewhere the vault, the
9
9
  // library and the account do not exist.
10
10
 
11
+ import { opsError } from "./ops-log.ts";
11
12
  import { judgeVerdict, JUDGE_VERDICT_INSTRUCTION } from "./judge-verdict.ts";
12
13
  import { runHook, runToolCallHooks, matchesTool, hookLine, resolveHooks, type HookDef, type HookRecord } from "./hooks.ts";
13
14
  import fs from "node:fs";
@@ -1381,16 +1382,21 @@ function runVerify(
1381
1382
  * A model process's failure as a person should read it: one short line. The
1382
1383
  * SDK's error for a CLI that died carries the CLI's stderr, which can be KBs
1383
1384
  * of its minified bundle — internal prompt text included (FOL-107) — so that
1384
- * part goes to the server log, never to an eval result or a trace. An error
1385
- * that is already short (an API error the model answered) is kept as it is.
1385
+ * part goes neither to an eval result or a trace, nor to a hosted log
1386
+ * (FOL-121): there the log line is the failure's class and our frames. An
1387
+ * error that is already short (an API error the model answered) is kept as
1388
+ * it is.
1386
1389
  */
1387
1390
  export function modelProcessError(err: unknown, where: string): Error {
1388
1391
  const full = err instanceof Error ? err.message : String(err);
1389
1392
  const at = full.indexOf(" stderr:");
1390
1393
  if (at < 0 && full.length <= 500) return err instanceof Error ? err : new Error(full);
1391
- console.error(`[foldrun] ${where}: ${full}`);
1394
+ // Inside the hosted boundary this is the class, name and our frames only:
1395
+ // the stderr is the CLI's, and can carry the prompt (FOL-107, FOL-121).
1396
+ // On a laptop the full text comes along, for the person it belongs to.
1397
+ opsError("model.process_failed", err, { where: where.replace(/\W+/g, "_").toLowerCase(), errorClass: "model_error" });
1392
1398
  const head = (at >= 0 ? full.slice(0, at) : full.slice(0, 300)).trim().replace(/[.:]$/, "");
1393
- return new Error(`${head} — the model process failed; the details are in the server log`);
1399
+ return new Error(`${head} — the model process failed`);
1394
1400
  }
1395
1401
 
1396
1402
  export function sdkEnv(base: Record<string, string | undefined> | undefined, extra: Record<string, string> = {}): Record<string, string | undefined> {
package/src/storage.ts CHANGED
@@ -48,6 +48,7 @@
48
48
  // FOLDRUN_STORAGE_MAX_MB per object, default 512
49
49
  // FOLDRUN_STORAGE_QUOTA_MB per workspace, default 5120
50
50
 
51
+ import { opsError } from "./ops-log.ts";
51
52
  import fs from "node:fs";
52
53
  import path from "node:path";
53
54
  import crypto from "node:crypto";
@@ -686,7 +687,7 @@ async function announceFiles(tenant: string, workspace: string, paths: string[],
686
687
  const { fireStorageTriggers } = await import("./triggers.ts");
687
688
  await fireStorageTriggers(tenant, workspace, paths, by);
688
689
  } catch (err) {
689
- console.error(`[foldrun] storage trigger ${tenant}/${workspace}:`, err instanceof Error ? err.message : err);
690
+ opsError("trigger.storage_failed", err, { tenant, workspace });
690
691
  }
691
692
  }
692
693