@foldrun/core 15.0.0 → 16.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/dist/src/a2a-publish.d.ts +7 -0
  2. package/dist/src/a2a-publish.js +15 -1
  3. package/dist/src/a2a-reach.d.ts +156 -0
  4. package/dist/src/a2a-reach.js +446 -0
  5. package/dist/src/browse-egress.d.ts +1 -1
  6. package/dist/src/browse-egress.js +7 -6
  7. package/dist/src/capture.js +2 -1
  8. package/dist/src/env-names.d.ts +12 -0
  9. package/dist/src/env-names.js +49 -0
  10. package/dist/src/failure.d.ts +92 -0
  11. package/dist/src/failure.js +294 -0
  12. package/dist/src/frontmatter-fields.js +1 -1
  13. package/dist/src/install-helper.js +10 -5
  14. package/dist/src/mail.js +2 -1
  15. package/dist/src/network.js +1 -1
  16. package/dist/src/notify.js +12 -7
  17. package/dist/src/ops-log.d.ts +55 -0
  18. package/dist/src/ops-log.js +393 -0
  19. package/dist/src/otel.d.ts +16 -1
  20. package/dist/src/otel.js +121 -5
  21. package/dist/src/run-container.d.ts +55 -3
  22. package/dist/src/run-container.js +109 -17
  23. package/dist/src/run-event.d.ts +179 -0
  24. package/dist/src/run-event.js +473 -0
  25. package/dist/src/runner.js +14 -5
  26. package/dist/src/runtime.d.ts +113 -16
  27. package/dist/src/runtime.js +528 -44
  28. package/dist/src/scan.js +80 -18
  29. package/dist/src/secrets.js +4 -3
  30. package/dist/src/starter.js +1 -1
  31. package/dist/src/step-exec.d.ts +4 -2
  32. package/dist/src/step-exec.js +10 -4
  33. package/dist/src/storage.js +2 -1
  34. package/dist/src/store.d.ts +25 -3
  35. package/dist/src/store.js +40 -10
  36. package/dist/src/triggers.js +6 -5
  37. package/dist/src/webhook.js +3 -2
  38. package/package.json +2 -1
  39. package/src/a2a-publish.ts +19 -1
  40. package/src/a2a-reach.ts +503 -0
  41. package/src/browse-egress.ts +8 -7
  42. package/src/capture.ts +2 -1
  43. package/src/env-names.ts +53 -0
  44. package/src/failure.ts +368 -0
  45. package/src/frontmatter-fields.ts +1 -1
  46. package/src/install-helper.ts +10 -5
  47. package/src/mail.ts +2 -1
  48. package/src/network.ts +1 -1
  49. package/src/notify.ts +12 -9
  50. package/src/ops-log.ts +403 -0
  51. package/src/otel.ts +122 -7
  52. package/src/run-container.ts +112 -21
  53. package/src/run-event.ts +563 -0
  54. package/src/runner.ts +14 -5
  55. package/src/runtime.ts +543 -45
  56. package/src/scan.ts +91 -20
  57. package/src/secrets.ts +4 -5
  58. package/src/starter.ts +1 -1
  59. package/src/step-exec.ts +10 -4
  60. package/src/storage.ts +2 -1
  61. package/src/store.ts +59 -11
  62. package/src/triggers.ts +6 -5
  63. package/src/webhook.ts +3 -2
@@ -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,393 @@
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 run's sandbox (FOL-122): the runner image and size class — the
104
+ // platform's own words — and the model, an identifier like a flow's name
105
+ // (one with `/` or `:` in it does not fit, and is dropped).
106
+ image: "word", size: "word", model: "id",
107
+ // A failure.
108
+ errorClass: "class", errorName: "errorName", code: "code", syscall: "word", cause: "cause",
109
+ at: "frame", frames: "frames", retrying: "bool", ok: "bool",
110
+ };
111
+ /** Is this value one this kind of field may carry? */
112
+ function fits(kind, v) {
113
+ switch (kind) {
114
+ case "num": return typeof v === "number" && Number.isFinite(v);
115
+ case "bool": return typeof v === "boolean";
116
+ case "id": return typeof v === "string" && ID.test(v);
117
+ case "word": return typeof v === "string" && WORD.test(v);
118
+ case "code": return typeof v === "string" && CODE.test(v);
119
+ case "class": return isErrorClass(v);
120
+ case "cause": return typeof v === "string" && CAUSES.includes(v);
121
+ case "errorName": return typeof v === "string" && ERROR_NAME.test(v);
122
+ case "frame": return typeof v === "string" && FRAME.test(v);
123
+ case "frames": return Array.isArray(v) && v.length <= 5 && v.every((f) => typeof f === "string" && FRAME.test(f));
124
+ }
125
+ }
126
+ /**
127
+ * The line as an object: the event, the fields that fit, and how many did
128
+ * not (by count — a refused field's name could itself be the content).
129
+ */
130
+ export function opsLine(level, event, fields = {}) {
131
+ const line = { ops: 1, level, event: typeof event === "string" && event.length <= 64 && EVENT.test(event) ? event : "invalid_event" };
132
+ let dropped = 0;
133
+ for (const [k, v] of Object.entries(fields)) {
134
+ if (v === undefined || v === null)
135
+ continue;
136
+ const kind = Object.prototype.hasOwnProperty.call(FIELDS, k) ? FIELDS[k] : undefined;
137
+ if (!kind || !fits(kind, v)) {
138
+ dropped += 1;
139
+ continue;
140
+ }
141
+ line[k] = v;
142
+ }
143
+ if (dropped)
144
+ line.dropped = dropped;
145
+ return line;
146
+ }
147
+ /** The real streams, once the boundary holds them; null outside it. */
148
+ let real = null;
149
+ /** Is this process inside the boundary — a hosted pod? */
150
+ export function opsBoundaryInstalled() {
151
+ return real !== null;
152
+ }
153
+ function readable(level, line, detail) {
154
+ const parts = Object.entries(line)
155
+ .filter(([k]) => k !== "ops" && k !== "level" && k !== "event")
156
+ .map(([k, v]) => `${k}=${Array.isArray(v) ? v.join(",") : String(v)}`);
157
+ return `[ops] ${line.event}${parts.length ? ` ${parts.join(" ")}` : ""}${detail ? ` — ${detail}` : ""}`;
158
+ }
159
+ function emit(level, line, detail) {
160
+ if (real) {
161
+ (level === "info" ? real.out : real.err)(JSON.stringify(line) + "\n");
162
+ return;
163
+ }
164
+ // No boundary: a laptop, a test, `next dev` — the reader is the person
165
+ // whose content it is, so the error's own words come along.
166
+ const text = readable(level, line, detail);
167
+ if (level === "info")
168
+ console.log(text);
169
+ else if (level === "warn")
170
+ console.warn(text);
171
+ else
172
+ console.error(text);
173
+ }
174
+ /** Say something about the platform: an event and its fields. */
175
+ export function opsLog(level, event, fields = {}) {
176
+ emit(level, opsLine(level, event, fields));
177
+ }
178
+ // ------------------------------------------------------------------- errors
179
+ /** Which class an error belongs to — from its code, its name and its status;
180
+ * a few fixed markers our own code and the cluster write are matched in its
181
+ * message, which never leaves this function. */
182
+ export function errorClass(err) {
183
+ try {
184
+ if (!err || typeof err !== "object")
185
+ return "platform_error";
186
+ const e = err;
187
+ if (isErrorClass(e.errorClass))
188
+ return e.errorClass;
189
+ const code = typeof e.code === "string" ? e.code : typeof e.code === "number" ? String(e.code) : "";
190
+ const name = typeof e.name === "string" ? e.name : "";
191
+ const status = typeof e.status === "number" ? e.status : typeof e.statusCode === "number" ? e.statusCode : 0;
192
+ if (name === "TimeoutError" || ["ETIMEDOUT", "ESOCKETTIMEDOUT", "UND_ERR_HEADERS_TIMEOUT", "UND_ERR_BODY_TIMEOUT", "UND_ERR_CONNECT_TIMEOUT", "57014"].includes(code))
193
+ return "timeout";
194
+ if (name === "AbortError" || code === "ABORT_ERR")
195
+ return "cancelled";
196
+ if (code === "ENOSPC" || code === "EDQUOT" || code === "53100")
197
+ return "disk_full";
198
+ if (code === "ENOMEM" || code === "ERR_WORKER_OUT_OF_MEMORY" || code === "53200")
199
+ return "oom";
200
+ if (["ECONNREFUSED", "ECONNRESET", "ENOTFOUND", "EAI_AGAIN", "EHOSTUNREACH", "ENETUNREACH", "EPIPE", "UND_ERR_SOCKET", "UND_ERR_CONNECT", "08000", "08001", "08003", "08006"].includes(code))
201
+ return "network_error";
202
+ if (code === "ENOENT" || code === "ENOTDIR" || status === 404)
203
+ return "not_found";
204
+ if (code === "EACCES" || code === "EPERM" || status === 401 || status === 403 || status === 423)
205
+ return "policy_denied";
206
+ if (status === 408 || status === 504)
207
+ return "timeout";
208
+ const message = typeof e.message === "string" ? e.message.slice(0, 4000) : "";
209
+ if (/\bOOMKilled\b|JavaScript heap out of memory/.test(message))
210
+ return "oom";
211
+ if (/no space left on device/i.test(message))
212
+ return "disk_full";
213
+ if (/\b(Claude Code process|model process|api\.anthropic\.com)\b/.test(message))
214
+ return "model_error";
215
+ return "platform_error";
216
+ }
217
+ catch {
218
+ return "platform_error";
219
+ }
220
+ }
221
+ /** Is this source path the platform's own code (core, platform, web, their
222
+ * dependencies), not something an account brought — and a file that is
223
+ * really there? A stack is a settable string; a frame naming a file that
224
+ * does not exist was written by someone, not by V8. */
225
+ const seenPaths = new Map();
226
+ function ourPath(p) {
227
+ if (/^node:[a-z_/]+$/.test(p))
228
+ return true;
229
+ // A checkout (the image runs core and platform from source), the web's
230
+ // build, or the published package (`node_modules/@foldrun/core/dist`).
231
+ if (!/\/foldrun-(core|platform|web)\/(src|server|app|lib|dist|\.next|node_modules|tests|scripts|instrumentation)|\/node_modules\/@foldrun\//.test(p))
232
+ return false;
233
+ let known = seenPaths.get(p);
234
+ if (known === undefined) {
235
+ try {
236
+ known = fs.statSync(p).isFile();
237
+ }
238
+ catch {
239
+ known = false;
240
+ }
241
+ if (seenPaths.size > 2000)
242
+ seenPaths.clear();
243
+ seenPaths.set(p, known);
244
+ }
245
+ return known;
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, max = 5, skip = 0) {
251
+ if (typeof stack !== "string")
252
+ return [];
253
+ const out = [];
254
+ let seen = 0;
255
+ for (const raw of stack.slice(0, 20_000).split("\n")) {
256
+ const m = /^\s+at (?:.*? \()?(.+?):(\d+):\d+\)?$/.exec(raw);
257
+ if (!m)
258
+ continue;
259
+ const where = m[1].replace(/^file:\/\//, "");
260
+ if (!ourPath(where))
261
+ continue;
262
+ if (seen++ < skip)
263
+ continue;
264
+ const frame = `${where.split("/").pop()}:${m[2]}`;
265
+ if (FRAME.test(frame))
266
+ out.push(frame);
267
+ if (out.length >= max)
268
+ break;
269
+ }
270
+ return out;
271
+ }
272
+ /** The fields of an error a log line may carry. Never throws: a getter on a
273
+ * strange object is not allowed to take the log down with it. */
274
+ export function errorFields(err) {
275
+ try {
276
+ const e = (err && typeof err === "object" ? err : {});
277
+ const code = typeof e.code === "string" ? e.code : typeof e.code === "number" ? String(e.code) : undefined;
278
+ const status = typeof e.status === "number" ? e.status : typeof e.statusCode === "number" ? e.statusCode : undefined;
279
+ let errorName = "NotAnError";
280
+ if (err instanceof Error) {
281
+ const cls = err.constructor?.name;
282
+ errorName = BUILTIN_NAMES.has(err.name) ? err.name : typeof cls === "string" && ERROR_NAME.test(cls) ? cls : "Error";
283
+ }
284
+ return {
285
+ errorClass: errorClass(err),
286
+ errorName,
287
+ code: code && CODE.test(code) && knownCode(code) ? code : undefined,
288
+ syscall: typeof e.syscall === "string" && WORD.test(e.syscall) ? e.syscall : undefined,
289
+ status,
290
+ // A reason our own code attached (`opsReason`: a word, by FIELDS).
291
+ reason: typeof e.opsReason === "string" && WORD.test(e.opsReason) ? e.opsReason : undefined,
292
+ frames: err instanceof Error ? stackFrames(e.stack) : [],
293
+ };
294
+ }
295
+ catch {
296
+ return { errorClass: "platform_error", errorName: "Error" };
297
+ }
298
+ }
299
+ /** An Error whose message is for a person and whose `reason` — a word —
300
+ * is what a hosted log says instead: `throw withOpsReason(new Error("egress.ts
301
+ * needs FOLDRUN_EGRESS_URL…"), "no_egress_url")`. */
302
+ export function withOpsReason(err, reason) {
303
+ return Object.assign(err, { opsReason: reason });
304
+ }
305
+ /** The message an error would show, for the readable line outside the
306
+ * boundary only. */
307
+ function messageOf(err) {
308
+ try {
309
+ return err instanceof Error ? err.message : String(err);
310
+ }
311
+ catch {
312
+ return "";
313
+ }
314
+ }
315
+ /** A failure: its class and where it happened — never its words inside the
316
+ * boundary. A field the caller names (an `errorClass` it knows) wins. */
317
+ export function opsError(event, err, fields = {}, level = "error") {
318
+ emit(level, opsLine(level, event, { ...errorFields(err), ...fields }), real ? undefined : messageOf(err));
319
+ }
320
+ // ----------------------------------------------------------------- boundary
321
+ /** Where in our code a raw console call was made: the first frame outside
322
+ * this file. From a stack we made, so it is a real code location. */
323
+ function callsite() {
324
+ const stack = new Error().stack ?? "";
325
+ for (const raw of stack.split("\n").slice(1)) {
326
+ const m = /^\s+at (?:.*? \()?(.+?):(\d+):\d+\)?$/.exec(raw);
327
+ if (!m || /\/ops-log\.(ts|js)$/.test(m[1]))
328
+ continue;
329
+ const where = m[1].replace(/^file:\/\//, "");
330
+ if (!ourPath(where))
331
+ return undefined;
332
+ const frame = `${where.split("/").pop()}:${m[2]}`;
333
+ return FRAME.test(frame) ? frame : undefined;
334
+ }
335
+ return undefined;
336
+ }
337
+ /**
338
+ * Put this process inside the boundary. Idempotent. Off only where
339
+ * FOLDRUN_LOG_MODE=raw or NODE_ENV=development (`next dev`).
340
+ */
341
+ export function installOpsBoundary(opts = {}) {
342
+ const env = opts.env ?? process.env;
343
+ if (real)
344
+ return true;
345
+ if (env.FOLDRUN_LOG_MODE === "raw" || (env.FOLDRUN_LOG_MODE !== "ops" && env.NODE_ENV === "development"))
346
+ return false;
347
+ const outWrite = process.stdout.write.bind(process.stdout);
348
+ const errWrite = process.stderr.write.bind(process.stderr);
349
+ real = { out: (s) => void outWrite(s), err: (s) => void errWrite(s) };
350
+ const fromConsole = (level) => (...args) => {
351
+ // Never formatted: an argument's text, its inspect() and its toJSON()
352
+ // are not read. An Error handed over gives its class, name and code.
353
+ let firstError;
354
+ for (const a of args) {
355
+ if (a instanceof Error) {
356
+ firstError = a;
357
+ break;
358
+ }
359
+ }
360
+ const fields = { at: callsite(), ...(firstError ? errorFields(firstError) : {}) };
361
+ emit(level, opsLine(level, "console", fields));
362
+ };
363
+ console.log = fromConsole("info");
364
+ console.info = fromConsole("info");
365
+ console.debug = fromConsole("info");
366
+ console.trace = fromConsole("info");
367
+ console.warn = fromConsole("warn");
368
+ console.error = fromConsole("error");
369
+ // Anything else that writes to the streams — a dependency, Next.js, a
370
+ // warning — is counted, not passed on. The write contract is kept: the
371
+ // callback runs, and the answer is "keep writing".
372
+ const fromStream = (stream) => function write(chunk, encoding, cb) {
373
+ const done = typeof encoding === "function" ? encoding : cb;
374
+ const bytes = typeof chunk === "string" ? Buffer.byteLength(chunk) : chunk instanceof Uint8Array ? chunk.byteLength : 0;
375
+ emit(stream === "stdout" ? "info" : "error", opsLine(stream === "stdout" ? "info" : "error", "stream.raw", { stream, bytes, at: callsite() }));
376
+ if (typeof done === "function")
377
+ queueMicrotask(() => done(null));
378
+ return true;
379
+ };
380
+ process.stdout.write = fromStream("stdout");
381
+ process.stderr.write = fromStream("stderr");
382
+ if (opts.exitOnUncaught) {
383
+ process.on("uncaughtException", (err) => {
384
+ opsError("process.uncaught_exception", err);
385
+ process.exit(1);
386
+ });
387
+ process.on("unhandledRejection", (err) => {
388
+ opsError("process.unhandled_rejection", err);
389
+ process.exit(1);
390
+ });
391
+ }
392
+ return true;
393
+ }
@@ -1,4 +1,4 @@
1
- import type { RunRecord } from "./store.ts";
1
+ import { type RunRecord } from "./store.ts";
2
2
  export { parseTelemetry, telemetrySecretNames, telemetryHeaders, type TelemetryConfig } from "./otel-config.ts";
3
3
  type AttrValue = {
4
4
  stringValue: string;
@@ -8,11 +8,26 @@ type AttrValue = {
8
8
  doubleValue: number;
9
9
  } | {
10
10
  boolValue: boolean;
11
+ } | {
12
+ arrayValue: {
13
+ values: {
14
+ stringValue: string;
15
+ }[];
16
+ };
11
17
  };
12
18
  type Attr = {
13
19
  key: string;
14
20
  value: AttrValue;
15
21
  };
22
+ /** What `error.type` may say: one of the platform's error classes
23
+ * (ops-log.ts, FOL-121), or the spec's `_OTHER` when the words of the
24
+ * failure match none. The spec asks an instrumentation to document the
25
+ * list it reports; this is it. */
26
+ export declare const SPAN_ERROR_TYPES: readonly ["timeout", "cancelled", "model_error", "oom", "disk_full", "network_error", "not_found", "policy_denied", "platform_error", "_OTHER"];
27
+ export type SpanErrorType = (typeof SPAN_ERROR_TYPES)[number];
28
+ /** A failure's class from its words, the way an operator counts them.
29
+ * Only the class leaves: the words stay where they were. */
30
+ export declare function spanErrorType(text: string | null | undefined, stopped?: boolean): SpanErrorType;
16
31
  export interface TraceContext {
17
32
  tenant: string;
18
33
  workspace: string;
package/dist/src/otel.js CHANGED
@@ -13,9 +13,35 @@
13
13
  // whole, like notify:). Ids are derived from the run and span ids, so a run
14
14
  // sent twice is the same trace, not two. No OpenTelemetry SDK: the wire
15
15
  // format is small, and a dependency in every runner image is not.
16
+ //
17
+ // Names follow the OpenTelemetry GenAI semantic conventions — since 2026 in
18
+ // their own repository, github.com/open-telemetry/semantic-conventions-genai
19
+ // (docs/gen-ai/gen-ai-agent-spans.md, gen-ai-spans.md, client-inference.md;
20
+ // read at 58daeb9, 5 Nov 2026, status Development):
21
+ //
22
+ // run invoke_workflow {flow} INTERNAL gen_ai.workflow.name
23
+ // step invoke_agent {agent} INTERNAL gen_ai.agent.name
24
+ // model call chat {model} CLIENT gen_ai.provider.name, usage
25
+ // tool call execute_tool {tool} INTERNAL gen_ai.tool.name, call.id
26
+ //
27
+ // each with gen_ai.operation.name, and error.type on a failed span. A direct
28
+ // agent run (flow "adhoc:<agent>") is not a workflow — the spec says not to
29
+ // report one for a standalone agent — so its root stays `run adhoc:<agent>`
30
+ // with no operation, and the step under it is the invoke_agent.
31
+ //
32
+ // Content stays out: no gen_ai.input/output.messages, no tool call
33
+ // arguments or results — the spec makes every one of them Opt-In, and a
34
+ // trace is built from the run record alone, which holds none of them (a
35
+ // captured call's content is under runs/<run>/calls/, never read here).
36
+ // What a span says of a failure is its class (error.type) and the step's
37
+ // own error line as the status message, capped.
16
38
  import crypto from "node:crypto";
39
+ import { isSplicedRecord } from "./store.js";
17
40
  import { buildTraceTree } from "./trace-tree.js";
41
+ import { errorClass } from "./ops-log.js";
42
+ import { platformCause } from "./issues.js";
18
43
  export { parseTelemetry, telemetrySecretNames, telemetryHeaders } from "./otel-config.js";
44
+ const strings = (key, v) => (v.length ? [{ key, value: { arrayValue: { values: v.map((x) => ({ stringValue: x })) } } }] : []);
19
45
  const attr = (key, v) => {
20
46
  if (v === null || v === undefined || v === "")
21
47
  return [];
@@ -29,37 +55,127 @@ const hex = (s, len) => crypto.createHash("sha256").update(s).digest("hex").slic
29
55
  const nanos = (msEpoch) => (BigInt(Math.round(msEpoch)) * BigInt(1_000_000)).toString();
30
56
  /** OTLP span kinds: INTERNAL, and CLIENT for a call that leaves the platform. */
31
57
  const SPAN_KIND = { internal: 1, client: 3 };
58
+ /** What `error.type` may say: one of the platform's error classes
59
+ * (ops-log.ts, FOL-121), or the spec's `_OTHER` when the words of the
60
+ * failure match none. The spec asks an instrumentation to document the
61
+ * list it reports; this is it. */
62
+ export const SPAN_ERROR_TYPES = ["timeout", "cancelled", "model_error", "oom", "disk_full", "network_error", "not_found", "policy_denied", "platform_error", "_OTHER"];
63
+ /** A failure's class from its words, the way an operator counts them.
64
+ * Only the class leaves: the words stay where they were. */
65
+ export function spanErrorType(text, stopped = false) {
66
+ if (stopped)
67
+ return "cancelled";
68
+ if (!text)
69
+ return "_OTHER";
70
+ // What stopRun writes on the step it interrupted, and on the run.
71
+ if (/\b(stopped by a person|cancelled by .+) — sandbox destroyed|^run (stopped|cancelled)\b/.test(text))
72
+ return "cancelled";
73
+ const cause = platformCause(text)?.key;
74
+ if (cause === "model-auth" || cause === "model-cap" || cause === "model-busy")
75
+ return "model_error";
76
+ if (cause === "sandbox" || cause === "worker")
77
+ return "platform_error";
78
+ if (/\btimed out\b/i.test(text))
79
+ return "timeout";
80
+ const cls = errorClass({ message: text });
81
+ return cls !== "platform_error" && SPAN_ERROR_TYPES.includes(cls) ? cls : "_OTHER";
82
+ }
83
+ /** The step that failed the run, by the runner's own rule (runner.ts: a
84
+ * failed step that is not optional, carried from an earlier run or a
85
+ * spliced record); else any failed one. */
86
+ const failingStep = (run) => run.steps.find((s) => s.status === "failed" && !s.optional && !s.carriedFrom && !isSplicedRecord(s)) ?? run.steps.find((s) => s.status === "failed");
87
+ const lastError = (s) => {
88
+ const errors = (s?.events ?? []).filter((e) => e.type === "error");
89
+ return errors[errors.length - 1]?.text ?? null;
90
+ };
91
+ /** gen_ai.provider.name — the spec's well-known value, only where the record
92
+ * says whose model it was: the platform's own Claude credential, or one of
93
+ * foldrun's models. An account's own provider: block could be anyone's, so
94
+ * it says nothing rather than guess. */
95
+ const PROVIDER = { anthropic: "anthropic", openai: "openai", gemini: "gcp.gemini", deepseek: "deepseek", moonshot: "moonshot_ai" };
96
+ function providerOf(step) {
97
+ if (!step)
98
+ return null;
99
+ // A refusal retried on the fallback supply (runner.ts) runs calls the
100
+ // step's `supply` does not describe; the record does not say which call
101
+ // went where, so none of them claims a provider.
102
+ if (step.events.some((e) => e.type === "info" && /retrying this step on the fallback provider/.test(e.text)))
103
+ return null;
104
+ if (step.supply === "operator")
105
+ return "anthropic";
106
+ if (step.supply === "foldrun" && step.supplyProvider)
107
+ return PROVIDER[step.supplyProvider] ?? step.supplyProvider;
108
+ return null;
109
+ }
32
110
  /** The ExportTraceServiceRequest for one run. */
33
111
  export function runToOtlp(run, ctx, now = Date.now()) {
34
112
  const tree = buildTraceTree(run, now);
35
113
  const traceId = hex(`foldrun-trace\0${ctx.tenant}\0${ctx.workspace}\0${run.id}`, 32);
36
114
  const spans = [];
115
+ const adhoc = run.flow.startsWith("adhoc:");
37
116
  const visit = (s, parent, inherited) => {
38
117
  const spanId = hex(`${traceId}\0${s.id}`, 16);
39
118
  const start = s.start ?? inherited.start;
40
119
  const end = Math.max(start, s.end ?? s.start ?? now);
41
120
  const step = s.step !== undefined ? run.steps[s.step] : undefined;
42
121
  const agent = s.kind === "step" ? step?.agent : inherited.agent;
122
+ const operation = s.kind === "run" ? (adhoc ? null : "invoke_workflow") : s.kind === "step" ? "invoke_agent" : s.kind === "model" ? "chat" : s.kind === "tool" ? "execute_tool" : null;
123
+ const name = s.kind === "run" ? (adhoc ? `run ${s.label}` : `invoke_workflow ${s.label}`)
124
+ : s.kind === "step" ? `invoke_agent ${s.label}`
125
+ : s.kind === "model" ? `chat ${s.model ?? s.label}`
126
+ : s.kind === "tool" ? `execute_tool ${s.label}`
127
+ : s.label;
128
+ // Why it failed, as a class: the run by its failing step, a step by its
129
+ // last error line, an error leaf by its own words. A failed tool call's
130
+ // record holds no words, only that it erred.
131
+ const failed = s.status === "error";
132
+ // A person (or a caller) stopping the run is why the run failed; a step
133
+ // that failed before the stop failed for its own reason — the step the
134
+ // stop interrupted is marked skipped, and its error line says cancelled.
135
+ const stopped = run.stopRequested === true && s.kind === "run";
136
+ const errorText = !failed ? null
137
+ : s.kind === "run" ? lastError(failingStep(run))
138
+ : s.kind === "step" ? lastError(step)
139
+ : s.text ?? null;
43
140
  spans.push({
44
141
  traceId,
45
142
  spanId,
46
143
  ...(parent ? { parentSpanId: parent } : {}),
47
- name: s.kind === "run" ? `run ${s.label}` : s.kind === "step" ? `step ${s.label}` : s.kind === "model" ? `chat ${s.model ?? s.label}` : s.kind === "tool" ? `tool ${s.label}` : s.label,
144
+ name,
48
145
  kind: s.kind === "model" ? SPAN_KIND.client : SPAN_KIND.internal,
49
146
  startTimeUnixNano: nanos(start),
50
147
  endTimeUnixNano: nanos(end),
51
148
  attributes: [
149
+ ...attr("gen_ai.operation.name", operation),
52
150
  ...attr("foldrun.span.kind", s.kind),
53
151
  ...attr("foldrun.status", s.status),
54
- ...(s.kind === "step" ? [...attr("foldrun.agent", agent), ...attr("foldrun.owner", agent ? ctx.owners?.[agent] ?? null : null), ...attr("foldrun.step", s.step)] : []),
152
+ ...(s.kind === "run" && !adhoc ? attr("gen_ai.workflow.name", s.label) : []),
153
+ ...(s.kind === "step" ? [...attr("gen_ai.agent.name", agent), ...attr("foldrun.agent", agent), ...attr("foldrun.owner", agent ? ctx.owners?.[agent] ?? null : null), ...attr("foldrun.step", s.step)] : []),
154
+ ...(s.kind === "model" ? attr("gen_ai.provider.name", providerOf(step)) : []),
55
155
  ...attr("gen_ai.request.model", s.model),
56
- ...(s.tokens ? [...attr("gen_ai.usage.input_tokens", s.tokens.input), ...attr("gen_ai.usage.output_tokens", s.tokens.output), ...attr("gen_ai.usage.cache_read_tokens", s.tokens.cacheRead), ...attr("gen_ai.usage.cache_write_tokens", s.tokens.cacheWrite)] : []),
156
+ ...(s.tokens
157
+ ? [
158
+ ...attr("gen_ai.usage.input_tokens", s.tokens.input),
159
+ ...attr("gen_ai.usage.output_tokens", s.tokens.output),
160
+ // The spec's names: "when available and non-zero".
161
+ ...(s.tokens.cacheRead ? attr("gen_ai.usage.cache_read.input_tokens", s.tokens.cacheRead) : []),
162
+ ...(s.tokens.cacheWrite ? attr("gen_ai.usage.cache_write.input_tokens", s.tokens.cacheWrite) : []),
163
+ // Deprecated (5 Nov 2026): the names this export sent before the
164
+ // spec named them. Kept for one release; read the ones above.
165
+ ...attr("gen_ai.usage.cache_read_tokens", s.tokens.cacheRead),
166
+ ...attr("gen_ai.usage.cache_write_tokens", s.tokens.cacheWrite),
167
+ ]
168
+ : []),
169
+ ...(s.stop ? strings("gen_ai.response.finish_reasons", [s.stop]) : []),
170
+ // Deprecated (5 Nov 2026): the singular this export sent before; the
171
+ // spec's is the array above. Kept for one release.
57
172
  ...attr("gen_ai.response.finish_reason", s.stop),
58
173
  ...(typeof s.costUsd === "number" ? attr("foldrun.cost_usd", s.costUsd) : []),
59
- ...(s.kind === "tool" ? [...attr("gen_ai.tool.name", s.label), ...attr("gen_ai.tool.call.id", s.call)] : []),
174
+ ...(s.kind === "tool" ? [...attr("gen_ai.tool.name", s.label), ...attr("gen_ai.tool.call.id", s.call), ...attr("gen_ai.agent.name", s.subagent ?? agent)] : []),
60
175
  ...attr("foldrun.subagent", s.subagent),
176
+ ...(failed ? attr("error.type", spanErrorType(errorText, stopped)) : []),
61
177
  ],
62
- status: s.status === "error" ? { code: 2, ...(s.text ? { message: s.text.slice(0, 500) } : {}) } : { code: 0 },
178
+ status: failed ? { code: 2, ...(errorText ? { message: errorText.slice(0, 500) } : {}) } : { code: 0 },
63
179
  });
64
180
  for (const c of s.children)
65
181
  visit(c, spanId, { start, agent });