@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.
@@ -0,0 +1,389 @@
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
+ import fs from "node:fs";
43
+ import os from "node:os";
44
+ /** Why something failed, in one word an operator can count. Small on
45
+ * purpose: a class is a bucket on a dashboard, not a diagnosis. */
46
+ export const ERROR_CLASSES = [
47
+ "policy_denied", // a rule said no: network, limits, a hook, a scope
48
+ "timeout", // ran out of time
49
+ "oom", // out of memory (OOMKilled, heap)
50
+ "disk_full", // ENOSPC, EDQUOT
51
+ "model_error", // the model or its process failed
52
+ "network_error", // a peer could not be reached (DNS, refused, reset)
53
+ "user_code_error", // the account's own code failed: a script, a tool, a hook
54
+ "not_found", // the thing named is not there
55
+ "cancelled", // stopped on purpose (a person, a shutdown, an abort)
56
+ "platform_error", // ours: everything else
57
+ ];
58
+ export function isErrorClass(v) {
59
+ return typeof v === "string" && ERROR_CLASSES.includes(v);
60
+ }
61
+ /** The platform-wide failure causes an issue is grouped by (issues.ts
62
+ * PLATFORM_CAUSES keys), as a log field. */
63
+ export const CAUSES = ["sandbox", "model-auth", "model-cap", "model-busy", "worker"];
64
+ /** A short lowercase word: an outcome, a role, a reason code. */
65
+ const WORD = /^[a-z][a-z0-9_-]{0,31}$/;
66
+ /** An id or a name: no whitespace, quotes, `/`, `:` or `@` — nothing a
67
+ * sentence, a URL, a path or an email address fits in. */
68
+ const ID = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/;
69
+ /** A code, as the field holds it: errno, SQLSTATE, an undici or Node code. */
70
+ const CODE = /^[A-Z0-9_]{2,40}$/;
71
+ /** A code an error may hand over. Not any upper-case word — an error's
72
+ * `code` is whatever its thrower set — but the system's errno names, a
73
+ * SQLSTATE (five characters, a digit first, or XX000), and Node's and
74
+ * undici's own `ERR_…` codes. */
75
+ const ERRNO = new Set(Object.keys(os.constants.errno));
76
+ function knownCode(code) {
77
+ 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);
78
+ }
79
+ /** An Error subclass's name, as the field holds it. */
80
+ const ERROR_NAME = /^[A-Z][A-Za-z0-9]{0,40}$/;
81
+ /** Names an error's `name` may give as they are; any other comes from its
82
+ * class (`constructor.name`) — our code's, since an account's code does
83
+ * not run in a platform process — because `name` is a settable string. */
84
+ const BUILTIN_NAMES = new Set(["Error", "TypeError", "RangeError", "SyntaxError", "ReferenceError", "EvalError", "URIError", "AggregateError", "AbortError", "TimeoutError", "SystemError"]);
85
+ /** Where in our code: a source file's base name and a line. */
86
+ const FRAME = /^[A-Za-z0-9_.-]{1,60}\.(ts|tsx|mts|js|mjs|cjs):\d{1,6}$/;
87
+ const EVENT = /^[a-z][a-z0-9_]*(\.[a-z0-9_]+){0,3}$/;
88
+ /** Every field a platform log line may carry, and its shape. Adding one is
89
+ * a decision that its values can never be an account's content. */
90
+ export const FIELDS = {
91
+ // Who and what: ids, and the names an account gave its workspaces, flows,
92
+ // agents and evals (identifiers, by policy — never their contents).
93
+ tenant: "id", workspace: "id", flow: "id", agent: "id", eval: "id", tool: "id",
94
+ runId: "id", jobId: "id", taskId: "id", proposal: "id", lease: "id", pod: "id",
95
+ worker: "id", provider: "id", plan: "id", fingerprint: "id", invoice: "id", order: "id",
96
+ stripeEvent: "id", subscription: "id", migration: "id", housekeeping: "id",
97
+ // How many, how long, how much.
98
+ count: "num", ms: "num", secs: "num", bytes: "num", usd: "num", attempt: "num",
99
+ step: "num", port: "num", status: "num", exitCode: "num", percent: "num", tries: "num",
100
+ // What kind.
101
+ op: "word", role: "word", outcome: "word", reason: "word", stream: "word", kind: "word",
102
+ verdict: "word", phase: "word", signal: "code", where: "word",
103
+ // A failure.
104
+ errorClass: "class", errorName: "errorName", code: "code", syscall: "word", cause: "cause",
105
+ at: "frame", frames: "frames", retrying: "bool", ok: "bool",
106
+ };
107
+ /** Is this value one this kind of field may carry? */
108
+ function fits(kind, v) {
109
+ switch (kind) {
110
+ case "num": return typeof v === "number" && Number.isFinite(v);
111
+ case "bool": return typeof v === "boolean";
112
+ case "id": return typeof v === "string" && ID.test(v);
113
+ case "word": return typeof v === "string" && WORD.test(v);
114
+ case "code": return typeof v === "string" && CODE.test(v);
115
+ case "class": return isErrorClass(v);
116
+ case "cause": return typeof v === "string" && CAUSES.includes(v);
117
+ case "errorName": return typeof v === "string" && ERROR_NAME.test(v);
118
+ case "frame": return typeof v === "string" && FRAME.test(v);
119
+ case "frames": return Array.isArray(v) && v.length <= 5 && v.every((f) => typeof f === "string" && FRAME.test(f));
120
+ }
121
+ }
122
+ /**
123
+ * The line as an object: the event, the fields that fit, and how many did
124
+ * not (by count — a refused field's name could itself be the content).
125
+ */
126
+ export function opsLine(level, event, fields = {}) {
127
+ const line = { ops: 1, level, event: typeof event === "string" && event.length <= 64 && EVENT.test(event) ? event : "invalid_event" };
128
+ let dropped = 0;
129
+ for (const [k, v] of Object.entries(fields)) {
130
+ if (v === undefined || v === null)
131
+ continue;
132
+ const kind = Object.prototype.hasOwnProperty.call(FIELDS, k) ? FIELDS[k] : undefined;
133
+ if (!kind || !fits(kind, v)) {
134
+ dropped += 1;
135
+ continue;
136
+ }
137
+ line[k] = v;
138
+ }
139
+ if (dropped)
140
+ line.dropped = dropped;
141
+ return line;
142
+ }
143
+ /** The real streams, once the boundary holds them; null outside it. */
144
+ let real = null;
145
+ /** Is this process inside the boundary — a hosted pod? */
146
+ export function opsBoundaryInstalled() {
147
+ return real !== null;
148
+ }
149
+ function readable(level, line, detail) {
150
+ const parts = Object.entries(line)
151
+ .filter(([k]) => k !== "ops" && k !== "level" && k !== "event")
152
+ .map(([k, v]) => `${k}=${Array.isArray(v) ? v.join(",") : String(v)}`);
153
+ return `[ops] ${line.event}${parts.length ? ` ${parts.join(" ")}` : ""}${detail ? ` — ${detail}` : ""}`;
154
+ }
155
+ function emit(level, line, detail) {
156
+ if (real) {
157
+ (level === "info" ? real.out : real.err)(JSON.stringify(line) + "\n");
158
+ return;
159
+ }
160
+ // No boundary: a laptop, a test, `next dev` — the reader is the person
161
+ // whose content it is, so the error's own words come along.
162
+ const text = readable(level, line, detail);
163
+ if (level === "info")
164
+ console.log(text);
165
+ else if (level === "warn")
166
+ console.warn(text);
167
+ else
168
+ console.error(text);
169
+ }
170
+ /** Say something about the platform: an event and its fields. */
171
+ export function opsLog(level, event, fields = {}) {
172
+ emit(level, opsLine(level, event, fields));
173
+ }
174
+ // ------------------------------------------------------------------- errors
175
+ /** Which class an error belongs to — from its code, its name and its status;
176
+ * a few fixed markers our own code and the cluster write are matched in its
177
+ * message, which never leaves this function. */
178
+ export function errorClass(err) {
179
+ try {
180
+ if (!err || typeof err !== "object")
181
+ return "platform_error";
182
+ const e = err;
183
+ if (isErrorClass(e.errorClass))
184
+ return e.errorClass;
185
+ const code = typeof e.code === "string" ? e.code : typeof e.code === "number" ? String(e.code) : "";
186
+ const name = typeof e.name === "string" ? e.name : "";
187
+ const status = typeof e.status === "number" ? e.status : typeof e.statusCode === "number" ? e.statusCode : 0;
188
+ if (name === "TimeoutError" || ["ETIMEDOUT", "ESOCKETTIMEDOUT", "UND_ERR_HEADERS_TIMEOUT", "UND_ERR_BODY_TIMEOUT", "UND_ERR_CONNECT_TIMEOUT", "57014"].includes(code))
189
+ return "timeout";
190
+ if (name === "AbortError" || code === "ABORT_ERR")
191
+ return "cancelled";
192
+ if (code === "ENOSPC" || code === "EDQUOT" || code === "53100")
193
+ return "disk_full";
194
+ if (code === "ENOMEM" || code === "ERR_WORKER_OUT_OF_MEMORY" || code === "53200")
195
+ return "oom";
196
+ if (["ECONNREFUSED", "ECONNRESET", "ENOTFOUND", "EAI_AGAIN", "EHOSTUNREACH", "ENETUNREACH", "EPIPE", "UND_ERR_SOCKET", "UND_ERR_CONNECT", "08000", "08001", "08003", "08006"].includes(code))
197
+ return "network_error";
198
+ if (code === "ENOENT" || code === "ENOTDIR" || status === 404)
199
+ return "not_found";
200
+ if (code === "EACCES" || code === "EPERM" || status === 401 || status === 403 || status === 423)
201
+ return "policy_denied";
202
+ if (status === 408 || status === 504)
203
+ return "timeout";
204
+ const message = typeof e.message === "string" ? e.message.slice(0, 4000) : "";
205
+ if (/\bOOMKilled\b|JavaScript heap out of memory/.test(message))
206
+ return "oom";
207
+ if (/no space left on device/i.test(message))
208
+ return "disk_full";
209
+ if (/\b(Claude Code process|model process|api\.anthropic\.com)\b/.test(message))
210
+ return "model_error";
211
+ return "platform_error";
212
+ }
213
+ catch {
214
+ return "platform_error";
215
+ }
216
+ }
217
+ /** Is this source path the platform's own code (core, platform, web, their
218
+ * dependencies), not something an account brought — and a file that is
219
+ * really there? A stack is a settable string; a frame naming a file that
220
+ * does not exist was written by someone, not by V8. */
221
+ const seenPaths = new Map();
222
+ function ourPath(p) {
223
+ if (/^node:[a-z_/]+$/.test(p))
224
+ return true;
225
+ // A checkout (the image runs core and platform from source), the web's
226
+ // build, or the published package (`node_modules/@foldrun/core/dist`).
227
+ if (!/\/foldrun-(core|platform|web)\/(src|server|app|lib|dist|\.next|node_modules|tests|scripts|instrumentation)|\/node_modules\/@foldrun\//.test(p))
228
+ return false;
229
+ let known = seenPaths.get(p);
230
+ if (known === undefined) {
231
+ try {
232
+ known = fs.statSync(p).isFile();
233
+ }
234
+ catch {
235
+ known = false;
236
+ }
237
+ if (seenPaths.size > 2000)
238
+ seenPaths.clear();
239
+ seenPaths.set(p, known);
240
+ }
241
+ return known;
242
+ }
243
+ /** `file.ts:12` frames of our code from a stack, first `max` of them. The
244
+ * first line (the message) is never read, and function names are left
245
+ * out: only a base name and a line, which a sentence cannot be. */
246
+ export function stackFrames(stack, max = 5, skip = 0) {
247
+ if (typeof stack !== "string")
248
+ return [];
249
+ const out = [];
250
+ let seen = 0;
251
+ for (const raw of stack.slice(0, 20_000).split("\n")) {
252
+ const m = /^\s+at (?:.*? \()?(.+?):(\d+):\d+\)?$/.exec(raw);
253
+ if (!m)
254
+ continue;
255
+ const where = m[1].replace(/^file:\/\//, "");
256
+ if (!ourPath(where))
257
+ continue;
258
+ if (seen++ < skip)
259
+ continue;
260
+ const frame = `${where.split("/").pop()}:${m[2]}`;
261
+ if (FRAME.test(frame))
262
+ out.push(frame);
263
+ if (out.length >= max)
264
+ break;
265
+ }
266
+ return out;
267
+ }
268
+ /** The fields of an error a log line may carry. Never throws: a getter on a
269
+ * strange object is not allowed to take the log down with it. */
270
+ export function errorFields(err) {
271
+ try {
272
+ const e = (err && typeof err === "object" ? err : {});
273
+ const code = typeof e.code === "string" ? e.code : typeof e.code === "number" ? String(e.code) : undefined;
274
+ const status = typeof e.status === "number" ? e.status : typeof e.statusCode === "number" ? e.statusCode : undefined;
275
+ let errorName = "NotAnError";
276
+ if (err instanceof Error) {
277
+ const cls = err.constructor?.name;
278
+ errorName = BUILTIN_NAMES.has(err.name) ? err.name : typeof cls === "string" && ERROR_NAME.test(cls) ? cls : "Error";
279
+ }
280
+ return {
281
+ errorClass: errorClass(err),
282
+ errorName,
283
+ code: code && CODE.test(code) && knownCode(code) ? code : undefined,
284
+ syscall: typeof e.syscall === "string" && WORD.test(e.syscall) ? e.syscall : undefined,
285
+ status,
286
+ // A reason our own code attached (`opsReason`: a word, by FIELDS).
287
+ reason: typeof e.opsReason === "string" && WORD.test(e.opsReason) ? e.opsReason : undefined,
288
+ frames: err instanceof Error ? stackFrames(e.stack) : [],
289
+ };
290
+ }
291
+ catch {
292
+ return { errorClass: "platform_error", errorName: "Error" };
293
+ }
294
+ }
295
+ /** An Error whose message is for a person and whose `reason` — a word —
296
+ * is what a hosted log says instead: `throw withOpsReason(new Error("egress.ts
297
+ * needs FOLDRUN_EGRESS_URL…"), "no_egress_url")`. */
298
+ export function withOpsReason(err, reason) {
299
+ return Object.assign(err, { opsReason: reason });
300
+ }
301
+ /** The message an error would show, for the readable line outside the
302
+ * boundary only. */
303
+ function messageOf(err) {
304
+ try {
305
+ return err instanceof Error ? err.message : String(err);
306
+ }
307
+ catch {
308
+ return "";
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, err, fields = {}, level = "error") {
314
+ emit(level, opsLine(level, event, { ...errorFields(err), ...fields }), real ? undefined : messageOf(err));
315
+ }
316
+ // ----------------------------------------------------------------- boundary
317
+ /** Where in our code a raw console call was made: the first frame outside
318
+ * this file. From a stack we made, so it is a real code location. */
319
+ function callsite() {
320
+ const stack = new Error().stack ?? "";
321
+ for (const raw of stack.split("\n").slice(1)) {
322
+ const m = /^\s+at (?:.*? \()?(.+?):(\d+):\d+\)?$/.exec(raw);
323
+ if (!m || /\/ops-log\.(ts|js)$/.test(m[1]))
324
+ continue;
325
+ const where = m[1].replace(/^file:\/\//, "");
326
+ if (!ourPath(where))
327
+ return undefined;
328
+ const frame = `${where.split("/").pop()}:${m[2]}`;
329
+ return FRAME.test(frame) ? frame : undefined;
330
+ }
331
+ return undefined;
332
+ }
333
+ /**
334
+ * Put this process inside the boundary. Idempotent. Off only where
335
+ * FOLDRUN_LOG_MODE=raw or NODE_ENV=development (`next dev`).
336
+ */
337
+ export function installOpsBoundary(opts = {}) {
338
+ const env = opts.env ?? process.env;
339
+ if (real)
340
+ return true;
341
+ if (env.FOLDRUN_LOG_MODE === "raw" || (env.FOLDRUN_LOG_MODE !== "ops" && env.NODE_ENV === "development"))
342
+ return false;
343
+ const outWrite = process.stdout.write.bind(process.stdout);
344
+ const errWrite = process.stderr.write.bind(process.stderr);
345
+ real = { out: (s) => void outWrite(s), err: (s) => void errWrite(s) };
346
+ const fromConsole = (level) => (...args) => {
347
+ // Never formatted: an argument's text, its inspect() and its toJSON()
348
+ // are not read. An Error handed over gives its class, name and code.
349
+ let firstError;
350
+ for (const a of args) {
351
+ if (a instanceof Error) {
352
+ firstError = a;
353
+ break;
354
+ }
355
+ }
356
+ const fields = { at: callsite(), ...(firstError ? errorFields(firstError) : {}) };
357
+ emit(level, opsLine(level, "console", fields));
358
+ };
359
+ console.log = fromConsole("info");
360
+ console.info = fromConsole("info");
361
+ console.debug = fromConsole("info");
362
+ console.trace = fromConsole("info");
363
+ console.warn = fromConsole("warn");
364
+ console.error = fromConsole("error");
365
+ // Anything else that writes to the streams — a dependency, Next.js, a
366
+ // warning — is counted, not passed on. The write contract is kept: the
367
+ // callback runs, and the answer is "keep writing".
368
+ const fromStream = (stream) => function write(chunk, encoding, cb) {
369
+ const done = typeof encoding === "function" ? encoding : cb;
370
+ const bytes = typeof chunk === "string" ? Buffer.byteLength(chunk) : chunk instanceof Uint8Array ? chunk.byteLength : 0;
371
+ emit(stream === "stdout" ? "info" : "error", opsLine(stream === "stdout" ? "info" : "error", "stream.raw", { stream, bytes, at: callsite() }));
372
+ if (typeof done === "function")
373
+ queueMicrotask(() => done(null));
374
+ return true;
375
+ };
376
+ process.stdout.write = fromStream("stdout");
377
+ process.stderr.write = fromStream("stderr");
378
+ if (opts.exitOnUncaught) {
379
+ process.on("uncaughtException", (err) => {
380
+ opsError("process.uncaught_exception", err);
381
+ process.exit(1);
382
+ });
383
+ process.on("unhandledRejection", (err) => {
384
+ opsError("process.unhandled_rejection", err);
385
+ process.exit(1);
386
+ });
387
+ }
388
+ return true;
389
+ }
@@ -83,9 +83,13 @@ export interface PlatformHooks {
83
83
  * recorded — the delivery as seen, the throttle window — so the sender's
84
84
  * retry is a fresh event rather than a "duplicate" of a run that never
85
85
  * existed. Default: nothing, because the default gate records nothing. */
86
- rollbackTrigger(tenant: string, workspace: string, flow: FlowInfo, opts?: {
86
+ rollbackTrigger(tenant: string, workspace: string, flow: FlowInfo,
87
+ /** `code`: the refusal's own code, when it had one — `waiting_cap`
88
+ * is logged as `queue-full` rather than `failed`. */
89
+ opts?: {
87
90
  deliveryKey?: string | null;
88
91
  reason?: string;
92
+ code?: string;
89
93
  }): Promise<void>;
90
94
  /** Step executors by FOLDRUN_RUN_ISOLATION value, beyond the `container`
91
95
  * one core ships. The platform adds `k8s`. */
@@ -148,6 +152,16 @@ export interface PlatformHooks {
148
152
  * only where no provider: block of the account's own says otherwise.
149
153
  * Absent: nobody can (a laptop, a self-hosted install). */
150
154
  modelSupply?(tenant: string): SupplyAnswer;
155
+ /**
156
+ * Does this isolation mode wall a step's network to the egress proxy and
157
+ * DNS when its `network:` is restricted and enforced — and is browsing
158
+ * put under that wall (FOL-110 phase 3, browse-egress.ts browseVerdict)?
159
+ * True: a browsing step gets the forward proxy like any other and its
160
+ * browser runs inside the walled sandbox, so the list holds for it.
161
+ * Absent or false: a browsing step browses as before phase 3, said in the
162
+ * trace as not enforced.
163
+ */
164
+ confinesBrowsing?(isolation: string): boolean;
151
165
  /**
152
166
  * An operator setting, by the environment variable that used to hold it
153
167
  * (30 Oct 2026): the platform answers with the operator's value where one
@@ -2,6 +2,7 @@
2
2
  // group receives every prior result, labeled per agent. Optional steps ("2?")
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
+ import { opsLog, opsError } from "./ops-log.js";
5
6
  import { globMatch } from "./bounded-match.js";
6
7
  import { latestRevisionId } from "./history.js";
7
8
  import { recordCallIo, redactionsFor } from "./capture.js";
@@ -48,7 +49,7 @@ import { PromptLayers, promptCacheKey } from "./prompt-layers.js";
48
49
  import { loadCatalog, checkModel, clampEffort, catalogCost, findModel, tokenPriceOf } from "./catalog.js";
49
50
  import { resolveSecrets, getSecret, materializeSecrets, secretSites, isClientCertValue, clientCertOf, withoutHeldCerts, isIdentityValue, identityOf } from "./secrets.js";
50
51
  import { resolveNetwork, networkLine, networkEnforceWanted, proxyEnv, siteCovers, EGRESS_CA_ENV } from "./network.js";
51
- import { browseNetworkLine } from "./browse-egress.js";
52
+ import { BROWSER_CONFINED_ENV, browseNetworkLine, browseVerdict } from "./browse-egress.js";
52
53
  import { materializeFileSecrets, cleanupFileSecrets } from "./secret-files.js";
53
54
  import { buildApiTools, secretsUsedByApi } from "./api-tools.js";
54
55
  import { buildA2ATools } from "./a2a-tools.js";
@@ -2228,7 +2229,7 @@ mayDefer) {
2228
2229
  const why = await platform.checkUntrustedUrl(r.card);
2229
2230
  if (why) {
2230
2231
  cardProblems.set(r.name, why);
2231
- console.warn(`[a2a] remotes: ${r.name} refused for ${tenant}/${path.basename(workspaceRootOf(agentDir))} (${step.agent}): ${why}`);
2232
+ opsLog("warn", "a2a.remote_refused", { tenant, workspace: path.basename(workspaceRootOf(agentDir)), agent: step.agent, tool: r.name });
2232
2233
  }
2233
2234
  }
2234
2235
  const stepRemotes = remotes.map((r) => {
@@ -2827,6 +2828,27 @@ mayDefer) {
2827
2828
  save();
2828
2829
  return;
2829
2830
  }
2831
+ // A step that may browse, on an install with the forward door: held to
2832
+ // its list where the executor walls the step's network, refused when
2833
+ // it names a vendor that list cannot hold, else as before phase 3
2834
+ // (browse-egress.ts browseVerdict, FOL-110).
2835
+ const browses = scriptSpecs.some((sc) => sc.name === "web") && (!web.actions || web.actions.includes("browse"));
2836
+ const browse = browses && lease?.proxy
2837
+ ? browseVerdict({
2838
+ level: network.level,
2839
+ enforce: lease.enforce === true,
2840
+ vendor: clockEnv.FOLDRUN_BROWSER_VENDOR,
2841
+ confines: !!isolation && platform.confinesBrowsing?.(isolation) === true,
2842
+ })
2843
+ : null;
2844
+ if (lease && browse?.kind === "refuse") {
2845
+ push("info", networkLine(network, true));
2846
+ push("error", browse.message);
2847
+ await lease.release();
2848
+ step.status = "failed";
2849
+ save();
2850
+ return;
2851
+ }
2830
2852
  // Serve those jobs while this step runs: each one becomes a step of
2831
2853
  // its own (delegateJob), and the door answers the long-poll with its
2832
2854
  // reply. No proxy, or a platform without the door: not offered — the
@@ -2851,16 +2873,18 @@ mayDefer) {
2851
2873
  // The forward door: every program in the sandbox sends through the
2852
2874
  // proxy, which holds the site list and fills bound secrets. A proxy
2853
2875
  // without the door (an older platform) leaves programs going direct.
2854
- // A step that may browse gets no proxy variables: the browser in it
2855
- // reads HTTPS_PROXY too, and Chromium cannot send credentials written
2856
- // into a proxy URL — every page failed ERR_INVALID_AUTH_CREDENTIALS
2857
- // (14 Oct 2026, the reel posters). Such a step is open by default,
2858
- // and its bound secrets materialise as they did before the door.
2859
- const browses = scriptSpecs.some((sc) => sc.name === "web") && (!web.actions || web.actions.includes("browse"));
2860
- const forward = lease?.proxy && !browses ? lease : null;
2861
- // A browsing step on an install with the door says it is not held to
2862
- // its list yet, and which tier its browser falls in (browse-egress.ts).
2863
- push("info", browses && lease?.proxy ? browseNetworkLine(network, clockEnv.FOLDRUN_BROWSER_VENDOR) : networkLine(network, forward ? forward.enforce === true : null));
2876
+ // A step that may browse gets no proxy variables unless it is held
2877
+ // (browse.kind "hosted"): the browser in it reads HTTPS_PROXY too, and
2878
+ // Chromium cannot send credentials written into a proxy URL — every
2879
+ // page failed ERR_INVALID_AUTH_CREDENTIALS (14 Oct 2026, the reel
2880
+ // posters). A held step's web tool hands the browser the proxy and its
2881
+ // credential as launch options instead (FOLDRUN_BROWSER_CONFINED).
2882
+ // Every other browsing step is open by default, and its bound secrets
2883
+ // materialise as they did before the door.
2884
+ const forward = lease?.proxy && (!browses || browse?.kind === "hosted") ? lease : null;
2885
+ // A browsing step on an install with the door says whether it is held
2886
+ // to its list, and which tier its browser falls in (browse-egress.ts).
2887
+ push("info", browse ? browseNetworkLine(network, clockEnv.FOLDRUN_BROWSER_VENDOR, { hosted: browse.kind === "hosted" }) : networkLine(network, forward ? forward.enforce === true : null));
2864
2888
  const bound = forward ? Object.keys(boundSites).filter((name) => name in liveSecrets) : [];
2865
2889
  for (const name of bound) {
2866
2890
  for (const site of boundSites[name])
@@ -3084,11 +3108,20 @@ mayDefer) {
3084
3108
  // Every program's HTTP(S) through the proxy's forward door, and
3085
3109
  // the CA it signs bound sites with, for the sandbox to trust.
3086
3110
  ...(forward ? proxyEnv(forward.proxy) : {}),
3111
+ // A browsing step held to its list: the web tool gives its
3112
+ // browser the forward door as launch options, refuses what
3113
+ // cannot go through it, and the platform starts no account
3114
+ // browser pod for it (browse-egress.ts, FOL-110 phase 3).
3115
+ ...(browse?.kind === "hosted" ? { [BROWSER_CONFINED_ENV]: "1" } : {}),
3087
3116
  // Only a step with a bound secret has a site the proxy
3088
3117
  // intercepts, so only that step's TLS clients are pointed at a
3089
3118
  // bundle with the egress CA in it; every other step's are as
3090
3119
  // they always were.
3091
- ...(forward?.ca && bound.length ? { [EGRESS_CA_ENV]: Buffer.from(forward.ca).toString("base64") } : {}),
3120
+ // A browser held to its list (browse "hosted") meets the proxy's
3121
+ // leaf on any host a secret is granted to — an api tool's, a web
3122
+ // provider's — not only a bound site, so it is handed the CA
3123
+ // whenever the step has one: the web tool trusts it for Chromium.
3124
+ ...(forward?.ca && (bound.length || (browse?.kind === "hosted" && Object.keys(grant.secrets).length)) ? { [EGRESS_CA_ENV]: Buffer.from(forward.ca).toString("base64") } : {}),
3092
3125
  ...clockEnv,
3093
3126
  // Who is running: the in-process path stamps scripts with these
3094
3127
  // host-side, but a container rebuilds its tools from its own
@@ -4041,7 +4074,8 @@ export function platformModelCredential(env = process.env) {
4041
4074
  // thing an operator needs to know about before the next step fails.
4042
4075
  if (!credentialFileWarned) {
4043
4076
  credentialFileWarned = true;
4044
- console.warn(`[model] FOLDRUN_MODEL_KEY_FILE=${file} could not be read; falling back to the environment`);
4077
+ // FOLDRUN_MODEL_KEY_FILE could not be read: the environment's key is used.
4078
+ opsLog("warn", "model.key_file_unreadable", { outcome: "environment" });
4045
4079
  }
4046
4080
  }
4047
4081
  }
@@ -6075,7 +6109,7 @@ export function reconcileRuns(tenant, now = Date.now(), live, onEnd) {
6075
6109
  if (onEnd && after && (after.status === "completed" || after.status === "failed"))
6076
6110
  return onEnd(tenant, workspace.name, run.id);
6077
6111
  })
6078
- .catch((err) => console.error(`[foldrun] reconcile: ${tenant}/${workspace.name}/${run.id} after resume:`, err));
6112
+ .catch((err) => opsError("reconcile.after_resume_failed", err, { tenant, workspace: workspace.name, runId: run.id }));
6079
6113
  closed.push({
6080
6114
  runId: run.id,
6081
6115
  tenant,
@@ -6125,7 +6159,7 @@ export function reconcileRuns(tenant, now = Date.now(), live, onEnd) {
6125
6159
  if (onEnd) {
6126
6160
  void Promise.resolve()
6127
6161
  .then(() => onEnd(tenant, workspace.name, run.id))
6128
- .catch((err) => console.error(`[foldrun] reconcile: ${tenant}/${workspace.name}/${run.id} after close:`, err));
6162
+ .catch((err) => opsError("reconcile.after_close_failed", err, { tenant, workspace: workspace.name, runId: run.id }));
6129
6163
  }
6130
6164
  }
6131
6165
  }
@@ -18,6 +18,7 @@
18
18
  //
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
+ import { opsLog, withOpsReason } from "./ops-log.js";
21
22
  import fs from "node:fs";
22
23
  import path from "node:path";
23
24
  import { dataRoot } from "./paths.js";
@@ -63,7 +64,7 @@ export function installKeyMaterial() {
63
64
  // so; without this, asking for it would quietly mint a NEW random key on
64
65
  // the shared data volume — a second root key nobody chose.
65
66
  if (process.env.FOLDRUN_INSTALL_KEY_ABSENT === "1") {
66
- throw new Error("this process runs without the install key (FOLDRUN_INSTALL_KEY_ABSENT=1) — whatever asked for it belongs in the worker");
67
+ 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");
67
68
  }
68
69
  fs.mkdirSync(dataRoot(), { recursive: true });
69
70
  if (!fs.existsSync(keyFile())) {
@@ -475,8 +476,8 @@ function decrypt(tenant, rec, aad) {
475
476
  // "no such secret" — a process that forgot to load the account keys
476
477
  // would look exactly like an account that never set one, which is the
477
478
  // most expensive kind of wrong answer to debug.
478
- console.error(`[secrets] ${tenant} has account-keyed secrets but no key is loaded — ` +
479
- `call loadTenantKeys() before reading, or the value will read as absent`);
479
+ // loadTenantKeys() was not called before reading: the value reads as absent.
480
+ opsLog("error", "secrets.account_key_not_loaded", { tenant });
480
481
  return null;
481
482
  }
482
483
  key = own;
@@ -336,8 +336,10 @@ export declare function judgePrompt(rubric: string, reply: string, work: string)
336
336
  * A model process's failure as a person should read it: one short line. The
337
337
  * SDK's error for a CLI that died carries the CLI's stderr, which can be KBs
338
338
  * of its minified bundle — internal prompt text included (FOL-107) — so that
339
- * part goes to the server log, never to an eval result or a trace. An error
340
- * that is already short (an API error the model answered) is kept as it is.
339
+ * part goes neither to an eval result or a trace, nor to a hosted log
340
+ * (FOL-121): there the log line is the failure's class and our frames. An
341
+ * error that is already short (an API error the model answered) is kept as
342
+ * it is.
341
343
  */
342
344
  export declare function modelProcessError(err: unknown, where: string): Error;
343
345
  export declare function sdkEnv(base: Record<string, string | undefined> | undefined, extra?: Record<string, string>): Record<string, string | undefined>;
@@ -7,6 +7,7 @@
7
7
  // assembles the system prompt and builds MCP servers, then hands this the
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
+ import { opsError } from "./ops-log.js";
10
11
  import { judgeVerdict, JUDGE_VERDICT_INSTRUCTION } from "./judge-verdict.js";
11
12
  import { runHook, runToolCallHooks, matchesTool, hookLine, resolveHooks } from "./hooks.js";
12
13
  import fs from "node:fs";
@@ -1171,17 +1172,22 @@ function runVerify(agentDir, command, env, data, signal) {
1171
1172
  * A model process's failure as a person should read it: one short line. The
1172
1173
  * SDK's error for a CLI that died carries the CLI's stderr, which can be KBs
1173
1174
  * of its minified bundle — internal prompt text included (FOL-107) — so that
1174
- * part goes to the server log, never to an eval result or a trace. An error
1175
- * that is already short (an API error the model answered) is kept as it is.
1175
+ * part goes neither to an eval result or a trace, nor to a hosted log
1176
+ * (FOL-121): there the log line is the failure's class and our frames. An
1177
+ * error that is already short (an API error the model answered) is kept as
1178
+ * it is.
1176
1179
  */
1177
1180
  export function modelProcessError(err, where) {
1178
1181
  const full = err instanceof Error ? err.message : String(err);
1179
1182
  const at = full.indexOf(" stderr:");
1180
1183
  if (at < 0 && full.length <= 500)
1181
1184
  return err instanceof Error ? err : new Error(full);
1182
- console.error(`[foldrun] ${where}: ${full}`);
1185
+ // Inside the hosted boundary this is the class, name and our frames only:
1186
+ // the stderr is the CLI's, and can carry the prompt (FOL-107, FOL-121).
1187
+ // On a laptop the full text comes along, for the person it belongs to.
1188
+ opsError("model.process_failed", err, { where: where.replace(/\W+/g, "_").toLowerCase(), errorClass: "model_error" });
1183
1189
  const head = (at >= 0 ? full.slice(0, at) : full.slice(0, 300)).trim().replace(/[.:]$/, "");
1184
- return new Error(`${head} — the model process failed; the details are in the server log`);
1190
+ return new Error(`${head} — the model process failed`);
1185
1191
  }
1186
1192
  export function sdkEnv(base, extra = {}) {
1187
1193
  return { ...(base ?? process.env), ...extra, ENABLE_CLAUDEAI_MCP_SERVERS: "false" };