@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.
- package/dist/src/a2a-publish.d.ts +7 -0
- package/dist/src/a2a-publish.js +15 -1
- package/dist/src/a2a-reach.d.ts +156 -0
- package/dist/src/a2a-reach.js +446 -0
- package/dist/src/browse-egress.d.ts +1 -1
- package/dist/src/browse-egress.js +7 -6
- package/dist/src/capture.js +2 -1
- package/dist/src/env-names.d.ts +12 -0
- package/dist/src/env-names.js +49 -0
- package/dist/src/failure.d.ts +92 -0
- package/dist/src/failure.js +294 -0
- package/dist/src/frontmatter-fields.js +1 -1
- package/dist/src/install-helper.js +10 -5
- package/dist/src/mail.js +2 -1
- package/dist/src/network.js +1 -1
- package/dist/src/notify.js +12 -7
- package/dist/src/ops-log.d.ts +55 -0
- package/dist/src/ops-log.js +393 -0
- package/dist/src/otel.d.ts +16 -1
- package/dist/src/otel.js +121 -5
- package/dist/src/run-container.d.ts +55 -3
- package/dist/src/run-container.js +109 -17
- package/dist/src/run-event.d.ts +179 -0
- package/dist/src/run-event.js +473 -0
- package/dist/src/runner.js +14 -5
- package/dist/src/runtime.d.ts +113 -16
- package/dist/src/runtime.js +528 -44
- package/dist/src/scan.js +80 -18
- package/dist/src/secrets.js +4 -3
- package/dist/src/starter.js +1 -1
- package/dist/src/step-exec.d.ts +4 -2
- package/dist/src/step-exec.js +10 -4
- package/dist/src/storage.js +2 -1
- package/dist/src/store.d.ts +25 -3
- package/dist/src/store.js +40 -10
- package/dist/src/triggers.js +6 -5
- package/dist/src/webhook.js +3 -2
- package/package.json +2 -1
- package/src/a2a-publish.ts +19 -1
- package/src/a2a-reach.ts +503 -0
- package/src/browse-egress.ts +8 -7
- package/src/capture.ts +2 -1
- package/src/env-names.ts +53 -0
- package/src/failure.ts +368 -0
- package/src/frontmatter-fields.ts +1 -1
- package/src/install-helper.ts +10 -5
- package/src/mail.ts +2 -1
- package/src/network.ts +1 -1
- package/src/notify.ts +12 -9
- package/src/ops-log.ts +403 -0
- package/src/otel.ts +122 -7
- package/src/run-container.ts +112 -21
- package/src/run-event.ts +563 -0
- package/src/runner.ts +14 -5
- package/src/runtime.ts +543 -45
- package/src/scan.ts +91 -20
- package/src/secrets.ts +4 -5
- package/src/starter.ts +1 -1
- package/src/step-exec.ts +10 -4
- package/src/storage.ts +2 -1
- package/src/store.ts +59 -11
- package/src/triggers.ts +6 -5
- package/src/webhook.ts +3 -2
package/src/ops-log.ts
ADDED
|
@@ -0,0 +1,403 @@
|
|
|
1
|
+
// What the platform says about itself, in a shape that cannot carry an
|
|
2
|
+
// account's content (FOL-121).
|
|
3
|
+
//
|
|
4
|
+
// A hosted pod's stdout and stderr leave the cluster: they are our
|
|
5
|
+
// operations log (Grafana Cloud, through Alloy), read by us, not by the
|
|
6
|
+
// account whose run it was. An account's prompts, replies, files, tool
|
|
7
|
+
// arguments and the words of its errors belong in that account's own run
|
|
8
|
+
// trace — never here.
|
|
9
|
+
//
|
|
10
|
+
// FOL-107 is why. An eval judge's model process died, and modelProcessError
|
|
11
|
+
// did the right thing for the person (one short line in the eval result) and
|
|
12
|
+
// the wrong thing for the log: "the details are in the server log" meant
|
|
13
|
+
// 2 KB of the CLI's stderr, prompt text included, shipped out with every
|
|
14
|
+
// other platform line. Nothing about a string says whether it is content,
|
|
15
|
+
// so the rule here is structural, in three parts:
|
|
16
|
+
//
|
|
17
|
+
// 1. One writer. `opsLog(level, event, fields)` and `opsError(event, err,
|
|
18
|
+
// fields)` build a line from a CLOSED set of field names, each with a
|
|
19
|
+
// shape (FIELDS below): numbers, short lowercase words, ids with no
|
|
20
|
+
// whitespace, quotes, `/`, `:` or `@` — so no sentence, URL, path or
|
|
21
|
+
// email address fits. A value that does not fit is dropped, never
|
|
22
|
+
// truncated (a truncated prompt is still a prompt), and an unknown field
|
|
23
|
+
// name is counted, not echoed. An error is its class, its name, its
|
|
24
|
+
// code, its status and where in OUR code it was thrown — never its
|
|
25
|
+
// message, which is whatever the thrower put there.
|
|
26
|
+
// 2. One boundary. `installOpsBoundary()`, the first import of every
|
|
27
|
+
// hosted entry point (worker, egress, assistant, the web's
|
|
28
|
+
// instrumentation), replaces console.* and process.stdout/stderr.write.
|
|
29
|
+
// A raw console call becomes {"event":"console","at":"queue.ts:1511"}
|
|
30
|
+
// plus the class of an Error it was handed; a raw stream write becomes
|
|
31
|
+
// {"event":"stream.raw","bytes":n}. Its arguments are never formatted.
|
|
32
|
+
// Only the writer above reaches the real streams.
|
|
33
|
+
// 3. A guard on the source: `scripts/log-guard.mjs` refuses a new raw
|
|
34
|
+
// console call in server code that prints anything but a literal, and
|
|
35
|
+
// an opsLog/opsError whose event is not a literal.
|
|
36
|
+
//
|
|
37
|
+
// Outside a hosted process — the CLI on a laptop, `next dev`, the tests —
|
|
38
|
+
// no boundary is installed and the writer prints a readable line with the
|
|
39
|
+
// error's message: there the reader is the person whose content it is.
|
|
40
|
+
// FOLDRUN_LOG_MODE=raw keeps a process out of the boundary on purpose;
|
|
41
|
+
// infra's tests refuse it in any manifest.
|
|
42
|
+
|
|
43
|
+
import fs from "node:fs";
|
|
44
|
+
import os from "node:os";
|
|
45
|
+
|
|
46
|
+
/** Why something failed, in one word an operator can count. Small on
|
|
47
|
+
* purpose: a class is a bucket on a dashboard, not a diagnosis. */
|
|
48
|
+
export const ERROR_CLASSES = [
|
|
49
|
+
"policy_denied", // a rule said no: network, limits, a hook, a scope
|
|
50
|
+
"timeout", // ran out of time
|
|
51
|
+
"oom", // out of memory (OOMKilled, heap)
|
|
52
|
+
"disk_full", // ENOSPC, EDQUOT
|
|
53
|
+
"model_error", // the model or its process failed
|
|
54
|
+
"network_error", // a peer could not be reached (DNS, refused, reset)
|
|
55
|
+
"user_code_error", // the account's own code failed: a script, a tool, a hook
|
|
56
|
+
"not_found", // the thing named is not there
|
|
57
|
+
"cancelled", // stopped on purpose (a person, a shutdown, an abort)
|
|
58
|
+
"platform_error", // ours: everything else
|
|
59
|
+
] as const;
|
|
60
|
+
export type ErrorClass = (typeof ERROR_CLASSES)[number];
|
|
61
|
+
|
|
62
|
+
export function isErrorClass(v: unknown): v is ErrorClass {
|
|
63
|
+
return typeof v === "string" && (ERROR_CLASSES as readonly string[]).includes(v);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** The platform-wide failure causes an issue is grouped by (issues.ts
|
|
67
|
+
* PLATFORM_CAUSES keys), as a log field. */
|
|
68
|
+
export const CAUSES = ["sandbox", "model-auth", "model-cap", "model-busy", "worker"] as const;
|
|
69
|
+
|
|
70
|
+
/** A short lowercase word: an outcome, a role, a reason code. */
|
|
71
|
+
const WORD = /^[a-z][a-z0-9_-]{0,31}$/;
|
|
72
|
+
/** An id or a name: no whitespace, quotes, `/`, `:` or `@` — nothing a
|
|
73
|
+
* sentence, a URL, a path or an email address fits in. */
|
|
74
|
+
const ID = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/;
|
|
75
|
+
/** A code, as the field holds it: errno, SQLSTATE, an undici or Node code. */
|
|
76
|
+
const CODE = /^[A-Z0-9_]{2,40}$/;
|
|
77
|
+
/** A code an error may hand over. Not any upper-case word — an error's
|
|
78
|
+
* `code` is whatever its thrower set — but the system's errno names, a
|
|
79
|
+
* SQLSTATE (five characters, a digit first, or XX000), and Node's and
|
|
80
|
+
* undici's own `ERR_…` codes. */
|
|
81
|
+
const ERRNO = new Set(Object.keys(os.constants.errno));
|
|
82
|
+
function knownCode(code: string): boolean {
|
|
83
|
+
return ERRNO.has(code) || /^[0-9][0-9A-Z]{4}$/.test(code) || /^XX00[0-2]$/.test(code) || /^(UND_)?ERR_[A-Z0-9_]{2,36}$/.test(code);
|
|
84
|
+
}
|
|
85
|
+
/** An Error subclass's name, as the field holds it. */
|
|
86
|
+
const ERROR_NAME = /^[A-Z][A-Za-z0-9]{0,40}$/;
|
|
87
|
+
/** Names an error's `name` may give as they are; any other comes from its
|
|
88
|
+
* class (`constructor.name`) — our code's, since an account's code does
|
|
89
|
+
* not run in a platform process — because `name` is a settable string. */
|
|
90
|
+
const BUILTIN_NAMES = new Set(["Error", "TypeError", "RangeError", "SyntaxError", "ReferenceError", "EvalError", "URIError", "AggregateError", "AbortError", "TimeoutError", "SystemError"]);
|
|
91
|
+
/** Where in our code: a source file's base name and a line. */
|
|
92
|
+
const FRAME = /^[A-Za-z0-9_.-]{1,60}\.(ts|tsx|mts|js|mjs|cjs):\d{1,6}$/;
|
|
93
|
+
const EVENT = /^[a-z][a-z0-9_]*(\.[a-z0-9_]+){0,3}$/;
|
|
94
|
+
|
|
95
|
+
type Kind = "id" | "num" | "word" | "code" | "class" | "cause" | "errorName" | "frame" | "frames" | "bool";
|
|
96
|
+
|
|
97
|
+
/** Every field a platform log line may carry, and its shape. Adding one is
|
|
98
|
+
* a decision that its values can never be an account's content. */
|
|
99
|
+
export const FIELDS: Record<string, Kind> = {
|
|
100
|
+
// Who and what: ids, and the names an account gave its workspaces, flows,
|
|
101
|
+
// agents and evals (identifiers, by policy — never their contents).
|
|
102
|
+
tenant: "id", workspace: "id", flow: "id", agent: "id", eval: "id", tool: "id",
|
|
103
|
+
runId: "id", jobId: "id", taskId: "id", proposal: "id", lease: "id", pod: "id",
|
|
104
|
+
worker: "id", provider: "id", plan: "id", fingerprint: "id", invoice: "id", order: "id",
|
|
105
|
+
stripeEvent: "id", subscription: "id", migration: "id", housekeeping: "id",
|
|
106
|
+
// How many, how long, how much.
|
|
107
|
+
count: "num", ms: "num", secs: "num", bytes: "num", usd: "num", attempt: "num",
|
|
108
|
+
step: "num", port: "num", status: "num", exitCode: "num", percent: "num", tries: "num",
|
|
109
|
+
// What kind.
|
|
110
|
+
op: "word", role: "word", outcome: "word", reason: "word", stream: "word", kind: "word",
|
|
111
|
+
verdict: "word", phase: "word", signal: "code", where: "word",
|
|
112
|
+
// A run's sandbox (FOL-122): the runner image and size class — the
|
|
113
|
+
// platform's own words — and the model, an identifier like a flow's name
|
|
114
|
+
// (one with `/` or `:` in it does not fit, and is dropped).
|
|
115
|
+
image: "word", size: "word", model: "id",
|
|
116
|
+
// A failure.
|
|
117
|
+
errorClass: "class", errorName: "errorName", code: "code", syscall: "word", cause: "cause",
|
|
118
|
+
at: "frame", frames: "frames", retrying: "bool", ok: "bool",
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
export type OpsValue = string | number | boolean | null | undefined | readonly string[];
|
|
122
|
+
export type OpsFields = Record<string, OpsValue>;
|
|
123
|
+
export type OpsLevel = "info" | "warn" | "error";
|
|
124
|
+
|
|
125
|
+
/** Is this value one this kind of field may carry? */
|
|
126
|
+
function fits(kind: Kind, v: unknown): boolean {
|
|
127
|
+
switch (kind) {
|
|
128
|
+
case "num": return typeof v === "number" && Number.isFinite(v);
|
|
129
|
+
case "bool": return typeof v === "boolean";
|
|
130
|
+
case "id": return typeof v === "string" && ID.test(v);
|
|
131
|
+
case "word": return typeof v === "string" && WORD.test(v);
|
|
132
|
+
case "code": return typeof v === "string" && CODE.test(v);
|
|
133
|
+
case "class": return isErrorClass(v);
|
|
134
|
+
case "cause": return typeof v === "string" && (CAUSES as readonly string[]).includes(v);
|
|
135
|
+
case "errorName": return typeof v === "string" && ERROR_NAME.test(v);
|
|
136
|
+
case "frame": return typeof v === "string" && FRAME.test(v);
|
|
137
|
+
case "frames": return Array.isArray(v) && v.length <= 5 && v.every((f) => typeof f === "string" && FRAME.test(f));
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* The line as an object: the event, the fields that fit, and how many did
|
|
143
|
+
* not (by count — a refused field's name could itself be the content).
|
|
144
|
+
*/
|
|
145
|
+
export function opsLine(level: OpsLevel, event: string, fields: OpsFields = {}): Record<string, unknown> {
|
|
146
|
+
const line: Record<string, unknown> = { ops: 1, level, event: typeof event === "string" && event.length <= 64 && EVENT.test(event) ? event : "invalid_event" };
|
|
147
|
+
let dropped = 0;
|
|
148
|
+
for (const [k, v] of Object.entries(fields)) {
|
|
149
|
+
if (v === undefined || v === null) continue;
|
|
150
|
+
const kind = Object.prototype.hasOwnProperty.call(FIELDS, k) ? FIELDS[k] : undefined;
|
|
151
|
+
if (!kind || !fits(kind, v)) {
|
|
152
|
+
dropped += 1;
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
line[k] = v;
|
|
156
|
+
}
|
|
157
|
+
if (dropped) line.dropped = dropped;
|
|
158
|
+
return line;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// ------------------------------------------------------------------ writing
|
|
162
|
+
|
|
163
|
+
type Write = (text: string) => void;
|
|
164
|
+
/** The real streams, once the boundary holds them; null outside it. */
|
|
165
|
+
let real: { out: Write; err: Write } | null = null;
|
|
166
|
+
|
|
167
|
+
/** Is this process inside the boundary — a hosted pod? */
|
|
168
|
+
export function opsBoundaryInstalled(): boolean {
|
|
169
|
+
return real !== null;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function readable(level: OpsLevel, line: Record<string, unknown>, detail?: string): string {
|
|
173
|
+
const parts = Object.entries(line)
|
|
174
|
+
.filter(([k]) => k !== "ops" && k !== "level" && k !== "event")
|
|
175
|
+
.map(([k, v]) => `${k}=${Array.isArray(v) ? v.join(",") : String(v)}`);
|
|
176
|
+
return `[ops] ${line.event}${parts.length ? ` ${parts.join(" ")}` : ""}${detail ? ` — ${detail}` : ""}`;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function emit(level: OpsLevel, line: Record<string, unknown>, detail?: string): void {
|
|
180
|
+
if (real) {
|
|
181
|
+
(level === "info" ? real.out : real.err)(JSON.stringify(line) + "\n");
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
// No boundary: a laptop, a test, `next dev` — the reader is the person
|
|
185
|
+
// whose content it is, so the error's own words come along.
|
|
186
|
+
const text = readable(level, line, detail);
|
|
187
|
+
if (level === "info") console.log(text);
|
|
188
|
+
else if (level === "warn") console.warn(text);
|
|
189
|
+
else console.error(text);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Say something about the platform: an event and its fields. */
|
|
193
|
+
export function opsLog(level: OpsLevel, event: string, fields: OpsFields = {}): void {
|
|
194
|
+
emit(level, opsLine(level, event, fields));
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// ------------------------------------------------------------------- errors
|
|
198
|
+
|
|
199
|
+
/** Which class an error belongs to — from its code, its name and its status;
|
|
200
|
+
* a few fixed markers our own code and the cluster write are matched in its
|
|
201
|
+
* message, which never leaves this function. */
|
|
202
|
+
export function errorClass(err: unknown): ErrorClass {
|
|
203
|
+
try {
|
|
204
|
+
if (!err || typeof err !== "object") return "platform_error";
|
|
205
|
+
const e = err as { name?: unknown; code?: unknown; status?: unknown; statusCode?: unknown; errorClass?: unknown; message?: unknown };
|
|
206
|
+
if (isErrorClass(e.errorClass)) return e.errorClass;
|
|
207
|
+
const code = typeof e.code === "string" ? e.code : typeof e.code === "number" ? String(e.code) : "";
|
|
208
|
+
const name = typeof e.name === "string" ? e.name : "";
|
|
209
|
+
const status = typeof e.status === "number" ? e.status : typeof e.statusCode === "number" ? e.statusCode : 0;
|
|
210
|
+
if (name === "TimeoutError" || ["ETIMEDOUT", "ESOCKETTIMEDOUT", "UND_ERR_HEADERS_TIMEOUT", "UND_ERR_BODY_TIMEOUT", "UND_ERR_CONNECT_TIMEOUT", "57014"].includes(code)) return "timeout";
|
|
211
|
+
if (name === "AbortError" || code === "ABORT_ERR") return "cancelled";
|
|
212
|
+
if (code === "ENOSPC" || code === "EDQUOT" || code === "53100") return "disk_full";
|
|
213
|
+
if (code === "ENOMEM" || code === "ERR_WORKER_OUT_OF_MEMORY" || code === "53200") return "oom";
|
|
214
|
+
if (["ECONNREFUSED", "ECONNRESET", "ENOTFOUND", "EAI_AGAIN", "EHOSTUNREACH", "ENETUNREACH", "EPIPE", "UND_ERR_SOCKET", "UND_ERR_CONNECT", "08000", "08001", "08003", "08006"].includes(code)) return "network_error";
|
|
215
|
+
if (code === "ENOENT" || code === "ENOTDIR" || status === 404) return "not_found";
|
|
216
|
+
if (code === "EACCES" || code === "EPERM" || status === 401 || status === 403 || status === 423) return "policy_denied";
|
|
217
|
+
if (status === 408 || status === 504) return "timeout";
|
|
218
|
+
const message = typeof e.message === "string" ? e.message.slice(0, 4000) : "";
|
|
219
|
+
if (/\bOOMKilled\b|JavaScript heap out of memory/.test(message)) return "oom";
|
|
220
|
+
if (/no space left on device/i.test(message)) return "disk_full";
|
|
221
|
+
if (/\b(Claude Code process|model process|api\.anthropic\.com)\b/.test(message)) return "model_error";
|
|
222
|
+
return "platform_error";
|
|
223
|
+
} catch {
|
|
224
|
+
return "platform_error";
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Is this source path the platform's own code (core, platform, web, their
|
|
229
|
+
* dependencies), not something an account brought — and a file that is
|
|
230
|
+
* really there? A stack is a settable string; a frame naming a file that
|
|
231
|
+
* does not exist was written by someone, not by V8. */
|
|
232
|
+
const seenPaths = new Map<string, boolean>();
|
|
233
|
+
function ourPath(p: string): boolean {
|
|
234
|
+
if (/^node:[a-z_/]+$/.test(p)) return true;
|
|
235
|
+
// A checkout (the image runs core and platform from source), the web's
|
|
236
|
+
// build, or the published package (`node_modules/@foldrun/core/dist`).
|
|
237
|
+
if (!/\/foldrun-(core|platform|web)\/(src|server|app|lib|dist|\.next|node_modules|tests|scripts|instrumentation)|\/node_modules\/@foldrun\//.test(p)) return false;
|
|
238
|
+
let known = seenPaths.get(p);
|
|
239
|
+
if (known === undefined) {
|
|
240
|
+
try {
|
|
241
|
+
known = fs.statSync(p).isFile();
|
|
242
|
+
} catch {
|
|
243
|
+
known = false;
|
|
244
|
+
}
|
|
245
|
+
if (seenPaths.size > 2000) seenPaths.clear();
|
|
246
|
+
seenPaths.set(p, known);
|
|
247
|
+
}
|
|
248
|
+
return known;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** `file.ts:12` frames of our code from a stack, first `max` of them. The
|
|
252
|
+
* first line (the message) is never read, and function names are left
|
|
253
|
+
* out: only a base name and a line, which a sentence cannot be. */
|
|
254
|
+
export function stackFrames(stack: unknown, max = 5, skip = 0): string[] {
|
|
255
|
+
if (typeof stack !== "string") return [];
|
|
256
|
+
const out: string[] = [];
|
|
257
|
+
let seen = 0;
|
|
258
|
+
for (const raw of stack.slice(0, 20_000).split("\n")) {
|
|
259
|
+
const m = /^\s+at (?:.*? \()?(.+?):(\d+):\d+\)?$/.exec(raw);
|
|
260
|
+
if (!m) continue;
|
|
261
|
+
const where = m[1].replace(/^file:\/\//, "");
|
|
262
|
+
if (!ourPath(where)) continue;
|
|
263
|
+
if (seen++ < skip) continue;
|
|
264
|
+
const frame = `${where.split("/").pop()}:${m[2]}`;
|
|
265
|
+
if (FRAME.test(frame)) out.push(frame);
|
|
266
|
+
if (out.length >= max) break;
|
|
267
|
+
}
|
|
268
|
+
return out;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** The fields of an error a log line may carry. Never throws: a getter on a
|
|
272
|
+
* strange object is not allowed to take the log down with it. */
|
|
273
|
+
export function errorFields(err: unknown): OpsFields {
|
|
274
|
+
try {
|
|
275
|
+
const e = (err && typeof err === "object" ? err : {}) as { name?: unknown; code?: unknown; syscall?: unknown; status?: unknown; statusCode?: unknown; stack?: unknown; opsReason?: unknown };
|
|
276
|
+
const code = typeof e.code === "string" ? e.code : typeof e.code === "number" ? String(e.code) : undefined;
|
|
277
|
+
const status = typeof e.status === "number" ? e.status : typeof e.statusCode === "number" ? e.statusCode : undefined;
|
|
278
|
+
let errorName = "NotAnError";
|
|
279
|
+
if (err instanceof Error) {
|
|
280
|
+
const cls = (err as { constructor?: { name?: unknown } }).constructor?.name;
|
|
281
|
+
errorName = BUILTIN_NAMES.has(err.name) ? err.name : typeof cls === "string" && ERROR_NAME.test(cls) ? cls : "Error";
|
|
282
|
+
}
|
|
283
|
+
return {
|
|
284
|
+
errorClass: errorClass(err),
|
|
285
|
+
errorName,
|
|
286
|
+
code: code && CODE.test(code) && knownCode(code) ? code : undefined,
|
|
287
|
+
syscall: typeof e.syscall === "string" && WORD.test(e.syscall) ? e.syscall : undefined,
|
|
288
|
+
status,
|
|
289
|
+
// A reason our own code attached (`opsReason`: a word, by FIELDS).
|
|
290
|
+
reason: typeof e.opsReason === "string" && WORD.test(e.opsReason) ? e.opsReason : undefined,
|
|
291
|
+
frames: err instanceof Error ? stackFrames(e.stack) : [],
|
|
292
|
+
};
|
|
293
|
+
} catch {
|
|
294
|
+
return { errorClass: "platform_error", errorName: "Error" };
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/** An Error whose message is for a person and whose `reason` — a word —
|
|
299
|
+
* is what a hosted log says instead: `throw withOpsReason(new Error("egress.ts
|
|
300
|
+
* needs FOLDRUN_EGRESS_URL…"), "no_egress_url")`. */
|
|
301
|
+
export function withOpsReason<E extends Error>(err: E, reason: string): E {
|
|
302
|
+
return Object.assign(err, { opsReason: reason });
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/** The message an error would show, for the readable line outside the
|
|
306
|
+
* boundary only. */
|
|
307
|
+
function messageOf(err: unknown): string {
|
|
308
|
+
try {
|
|
309
|
+
return err instanceof Error ? err.message : String(err);
|
|
310
|
+
} catch {
|
|
311
|
+
return "";
|
|
312
|
+
}
|
|
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: string, err: unknown, fields: OpsFields = {}, level: OpsLevel = "error"): void {
|
|
318
|
+
emit(level, opsLine(level, event, { ...errorFields(err), ...fields }), real ? undefined : messageOf(err));
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
// ----------------------------------------------------------------- boundary
|
|
322
|
+
|
|
323
|
+
/** Where in our code a raw console call was made: the first frame outside
|
|
324
|
+
* this file. From a stack we made, so it is a real code location. */
|
|
325
|
+
function callsite(): string | undefined {
|
|
326
|
+
const stack = new Error().stack ?? "";
|
|
327
|
+
for (const raw of stack.split("\n").slice(1)) {
|
|
328
|
+
const m = /^\s+at (?:.*? \()?(.+?):(\d+):\d+\)?$/.exec(raw);
|
|
329
|
+
if (!m || /\/ops-log\.(ts|js)$/.test(m[1])) continue;
|
|
330
|
+
const where = m[1].replace(/^file:\/\//, "");
|
|
331
|
+
if (!ourPath(where)) return undefined;
|
|
332
|
+
const frame = `${where.split("/").pop()}:${m[2]}`;
|
|
333
|
+
return FRAME.test(frame) ? frame : undefined;
|
|
334
|
+
}
|
|
335
|
+
return undefined;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
export interface BoundaryOptions {
|
|
339
|
+
/** On an uncaught exception or unhandled rejection: log its class and
|
|
340
|
+
* exit 1, as Node would — for processes with no handler of their own
|
|
341
|
+
* (the worker, egress, the assistant; Next.js has its own). */
|
|
342
|
+
exitOnUncaught?: boolean;
|
|
343
|
+
env?: NodeJS.ProcessEnv;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* Put this process inside the boundary. Idempotent. Off only where
|
|
348
|
+
* FOLDRUN_LOG_MODE=raw or NODE_ENV=development (`next dev`).
|
|
349
|
+
*/
|
|
350
|
+
export function installOpsBoundary(opts: BoundaryOptions = {}): boolean {
|
|
351
|
+
const env = opts.env ?? process.env;
|
|
352
|
+
if (real) return true;
|
|
353
|
+
if (env.FOLDRUN_LOG_MODE === "raw" || (env.FOLDRUN_LOG_MODE !== "ops" && env.NODE_ENV === "development")) return false;
|
|
354
|
+
const outWrite = process.stdout.write.bind(process.stdout) as (s: string) => boolean;
|
|
355
|
+
const errWrite = process.stderr.write.bind(process.stderr) as (s: string) => boolean;
|
|
356
|
+
real = { out: (s) => void outWrite(s), err: (s) => void errWrite(s) };
|
|
357
|
+
|
|
358
|
+
const fromConsole = (level: OpsLevel) => (...args: unknown[]) => {
|
|
359
|
+
// Never formatted: an argument's text, its inspect() and its toJSON()
|
|
360
|
+
// are not read. An Error handed over gives its class, name and code.
|
|
361
|
+
let firstError: unknown;
|
|
362
|
+
for (const a of args) {
|
|
363
|
+
if (a instanceof Error) {
|
|
364
|
+
firstError = a;
|
|
365
|
+
break;
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
const fields: OpsFields = { at: callsite(), ...(firstError ? errorFields(firstError) : {}) };
|
|
369
|
+
emit(level, opsLine(level, "console", fields));
|
|
370
|
+
};
|
|
371
|
+
console.log = fromConsole("info");
|
|
372
|
+
console.info = fromConsole("info");
|
|
373
|
+
console.debug = fromConsole("info");
|
|
374
|
+
console.trace = fromConsole("info");
|
|
375
|
+
console.warn = fromConsole("warn");
|
|
376
|
+
console.error = fromConsole("error");
|
|
377
|
+
|
|
378
|
+
// Anything else that writes to the streams — a dependency, Next.js, a
|
|
379
|
+
// warning — is counted, not passed on. The write contract is kept: the
|
|
380
|
+
// callback runs, and the answer is "keep writing".
|
|
381
|
+
const fromStream = (stream: "stdout" | "stderr") =>
|
|
382
|
+
function write(chunk: unknown, encoding?: unknown, cb?: unknown): boolean {
|
|
383
|
+
const done = typeof encoding === "function" ? encoding : cb;
|
|
384
|
+
const bytes = typeof chunk === "string" ? Buffer.byteLength(chunk) : chunk instanceof Uint8Array ? chunk.byteLength : 0;
|
|
385
|
+
emit(stream === "stdout" ? "info" : "error", opsLine(stream === "stdout" ? "info" : "error", "stream.raw", { stream, bytes, at: callsite() }));
|
|
386
|
+
if (typeof done === "function") queueMicrotask(() => (done as (e?: Error | null) => void)(null));
|
|
387
|
+
return true;
|
|
388
|
+
};
|
|
389
|
+
process.stdout.write = fromStream("stdout") as typeof process.stdout.write;
|
|
390
|
+
process.stderr.write = fromStream("stderr") as typeof process.stderr.write;
|
|
391
|
+
|
|
392
|
+
if (opts.exitOnUncaught) {
|
|
393
|
+
process.on("uncaughtException", (err) => {
|
|
394
|
+
opsError("process.uncaught_exception", err);
|
|
395
|
+
process.exit(1);
|
|
396
|
+
});
|
|
397
|
+
process.on("unhandledRejection", (err) => {
|
|
398
|
+
opsError("process.unhandled_rejection", err);
|
|
399
|
+
process.exit(1);
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
return true;
|
|
403
|
+
}
|
package/src/otel.ts
CHANGED
|
@@ -13,16 +13,42 @@
|
|
|
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
|
|
|
17
39
|
import crypto from "node:crypto";
|
|
18
|
-
import type
|
|
40
|
+
import { isSplicedRecord, type RunRecord, type StepRecord } from "./store.ts";
|
|
19
41
|
import { buildTraceTree, type TraceSpan } from "./trace-tree.ts";
|
|
42
|
+
import { errorClass, type ErrorClass } from "./ops-log.ts";
|
|
43
|
+
import { platformCause } from "./issues.ts";
|
|
20
44
|
|
|
21
45
|
export { parseTelemetry, telemetrySecretNames, telemetryHeaders, type TelemetryConfig } from "./otel-config.ts";
|
|
22
46
|
|
|
23
|
-
type AttrValue = { stringValue: string } | { intValue: string } | { doubleValue: number } | { boolValue: boolean };
|
|
47
|
+
type AttrValue = { stringValue: string } | { intValue: string } | { doubleValue: number } | { boolValue: boolean } | { arrayValue: { values: { stringValue: string }[] } };
|
|
24
48
|
type Attr = { key: string; value: AttrValue };
|
|
25
49
|
|
|
50
|
+
const strings = (key: string, v: readonly string[]): Attr[] => (v.length ? [{ key, value: { arrayValue: { values: v.map((x) => ({ stringValue: x })) } } }] : []);
|
|
51
|
+
|
|
26
52
|
const attr = (key: string, v: string | number | boolean | null | undefined): Attr[] => {
|
|
27
53
|
if (v === null || v === undefined || v === "") return [];
|
|
28
54
|
if (typeof v === "boolean") return [{ key, value: { boolValue: v } }];
|
|
@@ -36,6 +62,55 @@ const nanos = (msEpoch: number) => (BigInt(Math.round(msEpoch)) * BigInt(1_000_0
|
|
|
36
62
|
/** OTLP span kinds: INTERNAL, and CLIENT for a call that leaves the platform. */
|
|
37
63
|
const SPAN_KIND = { internal: 1, client: 3 } as const;
|
|
38
64
|
|
|
65
|
+
/** What `error.type` may say: one of the platform's error classes
|
|
66
|
+
* (ops-log.ts, FOL-121), or the spec's `_OTHER` when the words of the
|
|
67
|
+
* failure match none. The spec asks an instrumentation to document the
|
|
68
|
+
* list it reports; this is it. */
|
|
69
|
+
export const SPAN_ERROR_TYPES = ["timeout", "cancelled", "model_error", "oom", "disk_full", "network_error", "not_found", "policy_denied", "platform_error", "_OTHER"] as const;
|
|
70
|
+
export type SpanErrorType = (typeof SPAN_ERROR_TYPES)[number];
|
|
71
|
+
|
|
72
|
+
/** A failure's class from its words, the way an operator counts them.
|
|
73
|
+
* Only the class leaves: the words stay where they were. */
|
|
74
|
+
export function spanErrorType(text: string | null | undefined, stopped = false): SpanErrorType {
|
|
75
|
+
if (stopped) return "cancelled";
|
|
76
|
+
if (!text) return "_OTHER";
|
|
77
|
+
// What stopRun writes on the step it interrupted, and on the run.
|
|
78
|
+
if (/\b(stopped by a person|cancelled by .+) — sandbox destroyed|^run (stopped|cancelled)\b/.test(text)) return "cancelled";
|
|
79
|
+
const cause = platformCause(text)?.key;
|
|
80
|
+
if (cause === "model-auth" || cause === "model-cap" || cause === "model-busy") return "model_error";
|
|
81
|
+
if (cause === "sandbox" || cause === "worker") return "platform_error";
|
|
82
|
+
if (/\btimed out\b/i.test(text)) return "timeout";
|
|
83
|
+
const cls: ErrorClass = errorClass({ message: text });
|
|
84
|
+
return cls !== "platform_error" && (SPAN_ERROR_TYPES as readonly string[]).includes(cls) ? (cls as SpanErrorType) : "_OTHER";
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** The step that failed the run, by the runner's own rule (runner.ts: a
|
|
88
|
+
* failed step that is not optional, carried from an earlier run or a
|
|
89
|
+
* spliced record); else any failed one. */
|
|
90
|
+
const failingStep = (run: RunRecord) =>
|
|
91
|
+
run.steps.find((s) => s.status === "failed" && !s.optional && !s.carriedFrom && !isSplicedRecord(s)) ?? run.steps.find((s) => s.status === "failed");
|
|
92
|
+
|
|
93
|
+
const lastError = (s: StepRecord | undefined) => {
|
|
94
|
+
const errors = (s?.events ?? []).filter((e) => e.type === "error");
|
|
95
|
+
return errors[errors.length - 1]?.text ?? null;
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
/** gen_ai.provider.name — the spec's well-known value, only where the record
|
|
99
|
+
* says whose model it was: the platform's own Claude credential, or one of
|
|
100
|
+
* foldrun's models. An account's own provider: block could be anyone's, so
|
|
101
|
+
* it says nothing rather than guess. */
|
|
102
|
+
const PROVIDER: Record<string, string> = { anthropic: "anthropic", openai: "openai", gemini: "gcp.gemini", deepseek: "deepseek", moonshot: "moonshot_ai" };
|
|
103
|
+
function providerOf(step: StepRecord | undefined): string | null {
|
|
104
|
+
if (!step) return null;
|
|
105
|
+
// A refusal retried on the fallback supply (runner.ts) runs calls the
|
|
106
|
+
// step's `supply` does not describe; the record does not say which call
|
|
107
|
+
// went where, so none of them claims a provider.
|
|
108
|
+
if (step.events.some((e) => e.type === "info" && /retrying this step on the fallback provider/.test(e.text))) return null;
|
|
109
|
+
if (step.supply === "operator") return "anthropic";
|
|
110
|
+
if (step.supply === "foldrun" && step.supplyProvider) return PROVIDER[step.supplyProvider] ?? step.supplyProvider;
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
|
|
39
114
|
export interface TraceContext {
|
|
40
115
|
tenant: string;
|
|
41
116
|
workspace: string;
|
|
@@ -50,32 +125,72 @@ export function runToOtlp(run: RunRecord, ctx: TraceContext, now = Date.now()) {
|
|
|
50
125
|
const tree = buildTraceTree(run, now);
|
|
51
126
|
const traceId = hex(`foldrun-trace\0${ctx.tenant}\0${ctx.workspace}\0${run.id}`, 32);
|
|
52
127
|
const spans: unknown[] = [];
|
|
128
|
+
const adhoc = run.flow.startsWith("adhoc:");
|
|
53
129
|
const visit = (s: TraceSpan, parent: string | null, inherited: { start: number; agent?: string }) => {
|
|
54
130
|
const spanId = hex(`${traceId}\0${s.id}`, 16);
|
|
55
131
|
const start = s.start ?? inherited.start;
|
|
56
132
|
const end = Math.max(start, s.end ?? s.start ?? now);
|
|
57
133
|
const step = s.step !== undefined ? run.steps[s.step] : undefined;
|
|
58
134
|
const agent = s.kind === "step" ? step?.agent : inherited.agent;
|
|
135
|
+
const operation =
|
|
136
|
+
s.kind === "run" ? (adhoc ? null : "invoke_workflow") : s.kind === "step" ? "invoke_agent" : s.kind === "model" ? "chat" : s.kind === "tool" ? "execute_tool" : null;
|
|
137
|
+
const name =
|
|
138
|
+
s.kind === "run" ? (adhoc ? `run ${s.label}` : `invoke_workflow ${s.label}`)
|
|
139
|
+
: s.kind === "step" ? `invoke_agent ${s.label}`
|
|
140
|
+
: s.kind === "model" ? `chat ${s.model ?? s.label}`
|
|
141
|
+
: s.kind === "tool" ? `execute_tool ${s.label}`
|
|
142
|
+
: s.label;
|
|
143
|
+
// Why it failed, as a class: the run by its failing step, a step by its
|
|
144
|
+
// last error line, an error leaf by its own words. A failed tool call's
|
|
145
|
+
// record holds no words, only that it erred.
|
|
146
|
+
const failed = s.status === "error";
|
|
147
|
+
// A person (or a caller) stopping the run is why the run failed; a step
|
|
148
|
+
// that failed before the stop failed for its own reason — the step the
|
|
149
|
+
// stop interrupted is marked skipped, and its error line says cancelled.
|
|
150
|
+
const stopped = run.stopRequested === true && s.kind === "run";
|
|
151
|
+
const errorText = !failed ? null
|
|
152
|
+
: s.kind === "run" ? lastError(failingStep(run))
|
|
153
|
+
: s.kind === "step" ? lastError(step)
|
|
154
|
+
: s.text ?? null;
|
|
59
155
|
spans.push({
|
|
60
156
|
traceId,
|
|
61
157
|
spanId,
|
|
62
158
|
...(parent ? { parentSpanId: parent } : {}),
|
|
63
|
-
name
|
|
159
|
+
name,
|
|
64
160
|
kind: s.kind === "model" ? SPAN_KIND.client : SPAN_KIND.internal,
|
|
65
161
|
startTimeUnixNano: nanos(start),
|
|
66
162
|
endTimeUnixNano: nanos(end),
|
|
67
163
|
attributes: [
|
|
164
|
+
...attr("gen_ai.operation.name", operation),
|
|
68
165
|
...attr("foldrun.span.kind", s.kind),
|
|
69
166
|
...attr("foldrun.status", s.status),
|
|
70
|
-
...(s.kind === "
|
|
167
|
+
...(s.kind === "run" && !adhoc ? attr("gen_ai.workflow.name", s.label) : []),
|
|
168
|
+
...(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)] : []),
|
|
169
|
+
...(s.kind === "model" ? attr("gen_ai.provider.name", providerOf(step)) : []),
|
|
71
170
|
...attr("gen_ai.request.model", s.model),
|
|
72
|
-
...(s.tokens
|
|
171
|
+
...(s.tokens
|
|
172
|
+
? [
|
|
173
|
+
...attr("gen_ai.usage.input_tokens", s.tokens.input),
|
|
174
|
+
...attr("gen_ai.usage.output_tokens", s.tokens.output),
|
|
175
|
+
// The spec's names: "when available and non-zero".
|
|
176
|
+
...(s.tokens.cacheRead ? attr("gen_ai.usage.cache_read.input_tokens", s.tokens.cacheRead) : []),
|
|
177
|
+
...(s.tokens.cacheWrite ? attr("gen_ai.usage.cache_write.input_tokens", s.tokens.cacheWrite) : []),
|
|
178
|
+
// Deprecated (5 Nov 2026): the names this export sent before the
|
|
179
|
+
// spec named them. Kept for one release; read the ones above.
|
|
180
|
+
...attr("gen_ai.usage.cache_read_tokens", s.tokens.cacheRead),
|
|
181
|
+
...attr("gen_ai.usage.cache_write_tokens", s.tokens.cacheWrite),
|
|
182
|
+
]
|
|
183
|
+
: []),
|
|
184
|
+
...(s.stop ? strings("gen_ai.response.finish_reasons", [s.stop]) : []),
|
|
185
|
+
// Deprecated (5 Nov 2026): the singular this export sent before; the
|
|
186
|
+
// spec's is the array above. Kept for one release.
|
|
73
187
|
...attr("gen_ai.response.finish_reason", s.stop),
|
|
74
188
|
...(typeof s.costUsd === "number" ? attr("foldrun.cost_usd", s.costUsd) : []),
|
|
75
|
-
...(s.kind === "tool" ? [...attr("gen_ai.tool.name", s.label), ...attr("gen_ai.tool.call.id", s.call)] : []),
|
|
189
|
+
...(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)] : []),
|
|
76
190
|
...attr("foldrun.subagent", s.subagent),
|
|
191
|
+
...(failed ? attr("error.type", spanErrorType(errorText, stopped)) : []),
|
|
77
192
|
],
|
|
78
|
-
status:
|
|
193
|
+
status: failed ? { code: 2, ...(errorText ? { message: errorText.slice(0, 500) } : {}) } : { code: 0 },
|
|
79
194
|
});
|
|
80
195
|
for (const c of s.children) visit(c, spanId, { start, agent });
|
|
81
196
|
};
|