@foldrun/core 15.0.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.
@@ -4,6 +4,7 @@
4
4
  // credential or a private key — a key the agent read from a file or a page
5
5
  // is not in the vault, and is still a key. Masked first, cut second, so a
6
6
  // secret on the cap's edge is never kept half. Recording never fails the step.
7
+ import { opsError } from "./ops-log.js";
7
8
  import { redactText } from "./scan.js";
8
9
  import { writeCapturedCall, CAPTURE_CAP } from "./store.js";
9
10
  import { isFileValue, fileContent, isApiValue, apiConfigOf, isClientCertValue, clientCertOf } from "./secrets.js";
@@ -112,7 +113,7 @@ redactSecrets) {
112
113
  return true;
113
114
  }
114
115
  catch (err) {
115
- console.error(`[capture] ${tool} (${callId}) for ${runId}:`, err instanceof Error ? err.message : err);
116
+ opsError("capture.write_failed", err, { tool, runId });
116
117
  return false;
117
118
  }
118
119
  }
package/dist/src/mail.js CHANGED
@@ -23,6 +23,7 @@
23
23
  // The preference is asked at send time, here, through platform.mailPreference
24
24
  // — the platform keeps them as records. A laptop has no preferences store and
25
25
  // sends everything, which is what it always did.
26
+ import { opsError } from "./ops-log.js";
26
27
  import crypto from "node:crypto";
27
28
  import { platform } from "./platform.js";
28
29
  import { installKey, publicUrl } from "./webhook.js";
@@ -178,7 +179,7 @@ export async function mailWanted(tenant, email, category, workspace = null) {
178
179
  catch (err) {
179
180
  // A preferences store that cannot be read sends: a missed alert is
180
181
  // worse than one unwanted mail, and the next send asks again.
181
- console.error(`[foldrun] mail: preference for ${category} unreadable, sending:`, err instanceof Error ? err.message : err);
182
+ opsError("mail.preference_unreadable", err, { tenant, kind: category, outcome: "sent" }, "warn");
182
183
  return true;
183
184
  }
184
185
  }
@@ -30,6 +30,7 @@
30
30
  // Defaults: failed and awaiting-approval. Completed is opt-in — a schedule
31
31
  // that works is the quiet kind of good news, and a channel that pings on
32
32
  // every success gets muted, which un-pings the failures too.
33
+ import { opsLog, opsError } from "./ops-log.js";
33
34
  import crypto from "node:crypto";
34
35
  import { readAgentsMd } from "./runner.js";
35
36
  import { accountDir, workspaceDir, runCost, readFlow, runVerdict } from "./store.js";
@@ -159,7 +160,7 @@ export function signatureHeaders(tenant, workspace, config, body) {
159
160
  return {};
160
161
  const secret = getSecret(tenant, config.signingSecret, workspace);
161
162
  if (!secret) {
162
- console.error(`[foldrun] notify: signing_secret names ${signingSecretShown(config.signingSecret)}, which is not in the vault for ${tenant}/${workspace} — sending unsigned`);
163
+ opsLog("warn", "notify.signing_secret_missing", { tenant, workspace, outcome: "sent_unsigned" });
163
164
  return {};
164
165
  }
165
166
  const timestamp = Math.floor(Date.now() / 1000).toString();
@@ -437,7 +438,7 @@ export async function sendPlainNotificationOutcome(tenant, workspace, msg) {
437
438
  return { ok: r.ok, retrying: r.retrying === true };
438
439
  }
439
440
  catch (err) {
440
- console.error(`[foldrun] notify (${msg.event}): ${tenant}/${workspace} →`, err instanceof Error ? err.message : err);
441
+ opsError("notify.event_failed", err, { tenant, workspace, kind: msg.event });
441
442
  return no;
442
443
  }
443
444
  }
@@ -594,7 +595,9 @@ export async function sendRunNotification(tenant, workspace, run) {
594
595
  if (config.email) {
595
596
  const mail = notifyMail(tenant, workspace);
596
597
  if (!mail) {
597
- console.error(`[foldrun] notify: email configured but no mail credential — set RESEND_API_KEY (and EMAIL_FROM) on the account ${tenant}, or FOLDRUN_RESEND_API_KEY on the platform`);
598
+ // RESEND_API_KEY (and EMAIL_FROM) on the account, or
599
+ // FOLDRUN_RESEND_API_KEY on the platform.
600
+ opsLog("error", "notify.no_mail_credential", { tenant, workspace });
598
601
  return false;
599
602
  }
600
603
  // A gate is its own category: a person may want failures and not
@@ -629,7 +632,9 @@ export async function sendRunNotification(tenant, workspace, run) {
629
632
  // Resend's body says WHY — "domain not verified", "can only send to
630
633
  // your own address" — and a status alone sent someone to the wrong
631
634
  // dashboard for twenty minutes on 2026-09-06.
632
- console.error(`[foldrun] notify email: ${tenant}/${workspace} → ${r.status ? `HTTP ${r.status} ` : ""}${r.error ?? ""}`);
635
+ // The provider's words stay out of our log (they quote what was
636
+ // sent); the status is what an operator can act on.
637
+ opsLog("error", "notify.email_failed", { tenant, workspace, status: r.status });
633
638
  return false;
634
639
  }
635
640
  return true;
@@ -638,19 +643,19 @@ export async function sendRunNotification(tenant, workspace, run) {
638
643
  // vault instead of in a file that gets committed.
639
644
  const target = webhookTarget(tenant, workspace, config);
640
645
  if (!target.url) {
641
- console.error(`[foldrun] notify: ${target.refused ?? "secret in URL not set"} for ${tenant}/${workspace}`);
646
+ opsLog("error", "notify.no_webhook_url", { tenant, workspace, reason: target.refused ? "refused" : "secret_not_set" });
642
647
  return false;
643
648
  }
644
649
  const event = blocked ? "blocked" : run.status;
645
650
  const r = await platform.deliverWebhook(tenant, workspace, { event, body: JSON.stringify(body), retry: true });
646
651
  if (!r.ok) {
647
- console.error(`[foldrun] notify: ${tenant}/${workspace} → ${r.statusCode ? `HTTP ${r.statusCode}` : r.detail}${r.retrying ? " (will retry)" : ""}`);
652
+ opsLog("error", "notify.webhook_failed", { tenant, workspace, status: r.statusCode, retrying: r.retrying === true });
648
653
  return false;
649
654
  }
650
655
  return true;
651
656
  }
652
657
  catch (err) {
653
- console.error(`[foldrun] notify: ${tenant}/${workspace} →`, err instanceof Error ? err.message : err);
658
+ opsError("notify.failed", err, { tenant, workspace });
654
659
  return false;
655
660
  }
656
661
  }
@@ -0,0 +1,55 @@
1
+ /** Why something failed, in one word an operator can count. Small on
2
+ * purpose: a class is a bucket on a dashboard, not a diagnosis. */
3
+ export declare const ERROR_CLASSES: readonly ["policy_denied", "timeout", "oom", "disk_full", "model_error", "network_error", "user_code_error", "not_found", "cancelled", "platform_error"];
4
+ export type ErrorClass = (typeof ERROR_CLASSES)[number];
5
+ export declare function isErrorClass(v: unknown): v is ErrorClass;
6
+ /** The platform-wide failure causes an issue is grouped by (issues.ts
7
+ * PLATFORM_CAUSES keys), as a log field. */
8
+ export declare const CAUSES: readonly ["sandbox", "model-auth", "model-cap", "model-busy", "worker"];
9
+ type Kind = "id" | "num" | "word" | "code" | "class" | "cause" | "errorName" | "frame" | "frames" | "bool";
10
+ /** Every field a platform log line may carry, and its shape. Adding one is
11
+ * a decision that its values can never be an account's content. */
12
+ export declare const FIELDS: Record<string, Kind>;
13
+ export type OpsValue = string | number | boolean | null | undefined | readonly string[];
14
+ export type OpsFields = Record<string, OpsValue>;
15
+ export type OpsLevel = "info" | "warn" | "error";
16
+ /**
17
+ * The line as an object: the event, the fields that fit, and how many did
18
+ * not (by count — a refused field's name could itself be the content).
19
+ */
20
+ export declare function opsLine(level: OpsLevel, event: string, fields?: OpsFields): Record<string, unknown>;
21
+ /** Is this process inside the boundary — a hosted pod? */
22
+ export declare function opsBoundaryInstalled(): boolean;
23
+ /** Say something about the platform: an event and its fields. */
24
+ export declare function opsLog(level: OpsLevel, event: string, fields?: OpsFields): void;
25
+ /** Which class an error belongs to — from its code, its name and its status;
26
+ * a few fixed markers our own code and the cluster write are matched in its
27
+ * message, which never leaves this function. */
28
+ export declare function errorClass(err: unknown): ErrorClass;
29
+ /** `file.ts:12` frames of our code from a stack, first `max` of them. The
30
+ * first line (the message) is never read, and function names are left
31
+ * out: only a base name and a line, which a sentence cannot be. */
32
+ export declare function stackFrames(stack: unknown, max?: number, skip?: number): string[];
33
+ /** The fields of an error a log line may carry. Never throws: a getter on a
34
+ * strange object is not allowed to take the log down with it. */
35
+ export declare function errorFields(err: unknown): OpsFields;
36
+ /** An Error whose message is for a person and whose `reason` — a word —
37
+ * is what a hosted log says instead: `throw withOpsReason(new Error("egress.ts
38
+ * needs FOLDRUN_EGRESS_URL…"), "no_egress_url")`. */
39
+ export declare function withOpsReason<E extends Error>(err: E, reason: string): E;
40
+ /** A failure: its class and where it happened — never its words inside the
41
+ * boundary. A field the caller names (an `errorClass` it knows) wins. */
42
+ export declare function opsError(event: string, err: unknown, fields?: OpsFields, level?: OpsLevel): void;
43
+ export interface BoundaryOptions {
44
+ /** On an uncaught exception or unhandled rejection: log its class and
45
+ * exit 1, as Node would — for processes with no handler of their own
46
+ * (the worker, egress, the assistant; Next.js has its own). */
47
+ exitOnUncaught?: boolean;
48
+ env?: NodeJS.ProcessEnv;
49
+ }
50
+ /**
51
+ * Put this process inside the boundary. Idempotent. Off only where
52
+ * FOLDRUN_LOG_MODE=raw or NODE_ENV=development (`next dev`).
53
+ */
54
+ export declare function installOpsBoundary(opts?: BoundaryOptions): boolean;
55
+ export {};
@@ -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
+ }
@@ -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";
@@ -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) => {
@@ -4073,7 +4074,8 @@ export function platformModelCredential(env = process.env) {
4073
4074
  // thing an operator needs to know about before the next step fails.
4074
4075
  if (!credentialFileWarned) {
4075
4076
  credentialFileWarned = true;
4076
- 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" });
4077
4079
  }
4078
4080
  }
4079
4081
  }
@@ -6107,7 +6109,7 @@ export function reconcileRuns(tenant, now = Date.now(), live, onEnd) {
6107
6109
  if (onEnd && after && (after.status === "completed" || after.status === "failed"))
6108
6110
  return onEnd(tenant, workspace.name, run.id);
6109
6111
  })
6110
- .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 }));
6111
6113
  closed.push({
6112
6114
  runId: run.id,
6113
6115
  tenant,
@@ -6157,7 +6159,7 @@ export function reconcileRuns(tenant, now = Date.now(), live, onEnd) {
6157
6159
  if (onEnd) {
6158
6160
  void Promise.resolve()
6159
6161
  .then(() => onEnd(tenant, workspace.name, run.id))
6160
- .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 }));
6161
6163
  }
6162
6164
  }
6163
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>;