@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.
- package/dist/src/capture.js +2 -1
- package/dist/src/mail.js +2 -1
- package/dist/src/notify.js +12 -7
- package/dist/src/ops-log.d.ts +55 -0
- package/dist/src/ops-log.js +389 -0
- package/dist/src/runner.js +6 -4
- package/dist/src/secrets.js +4 -3
- 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/triggers.js +6 -5
- package/dist/src/webhook.js +3 -2
- package/package.json +1 -1
- package/src/capture.ts +2 -1
- package/src/mail.ts +2 -1
- package/src/notify.ts +12 -9
- package/src/ops-log.ts +399 -0
- package/src/runner.ts +6 -4
- package/src/secrets.ts +4 -5
- package/src/step-exec.ts +10 -4
- package/src/storage.ts +2 -1
- package/src/triggers.ts +6 -5
- package/src/webhook.ts +3 -2
package/dist/src/step-exec.js
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
// assembles the system prompt and builds MCP servers, then hands this the
|
|
8
8
|
// results. That is what lets the same function run somewhere the vault, the
|
|
9
9
|
// library and the account do not exist.
|
|
10
|
+
import { opsError } from "./ops-log.js";
|
|
10
11
|
import { judgeVerdict, JUDGE_VERDICT_INSTRUCTION } from "./judge-verdict.js";
|
|
11
12
|
import { runHook, runToolCallHooks, matchesTool, hookLine, resolveHooks } from "./hooks.js";
|
|
12
13
|
import fs from "node:fs";
|
|
@@ -1171,17 +1172,22 @@ function runVerify(agentDir, command, env, data, signal) {
|
|
|
1171
1172
|
* A model process's failure as a person should read it: one short line. The
|
|
1172
1173
|
* SDK's error for a CLI that died carries the CLI's stderr, which can be KBs
|
|
1173
1174
|
* of its minified bundle — internal prompt text included (FOL-107) — so that
|
|
1174
|
-
* part goes
|
|
1175
|
-
*
|
|
1175
|
+
* part goes neither to an eval result or a trace, nor to a hosted log
|
|
1176
|
+
* (FOL-121): there the log line is the failure's class and our frames. An
|
|
1177
|
+
* error that is already short (an API error the model answered) is kept as
|
|
1178
|
+
* it is.
|
|
1176
1179
|
*/
|
|
1177
1180
|
export function modelProcessError(err, where) {
|
|
1178
1181
|
const full = err instanceof Error ? err.message : String(err);
|
|
1179
1182
|
const at = full.indexOf(" stderr:");
|
|
1180
1183
|
if (at < 0 && full.length <= 500)
|
|
1181
1184
|
return err instanceof Error ? err : new Error(full);
|
|
1182
|
-
|
|
1185
|
+
// Inside the hosted boundary this is the class, name and our frames only:
|
|
1186
|
+
// the stderr is the CLI's, and can carry the prompt (FOL-107, FOL-121).
|
|
1187
|
+
// On a laptop the full text comes along, for the person it belongs to.
|
|
1188
|
+
opsError("model.process_failed", err, { where: where.replace(/\W+/g, "_").toLowerCase(), errorClass: "model_error" });
|
|
1183
1189
|
const head = (at >= 0 ? full.slice(0, at) : full.slice(0, 300)).trim().replace(/[.:]$/, "");
|
|
1184
|
-
return new Error(`${head} — the model process failed
|
|
1190
|
+
return new Error(`${head} — the model process failed`);
|
|
1185
1191
|
}
|
|
1186
1192
|
export function sdkEnv(base, extra = {}) {
|
|
1187
1193
|
return { ...(base ?? process.env), ...extra, ENABLE_CLAUDEAI_MCP_SERVERS: "false" };
|
package/dist/src/storage.js
CHANGED
|
@@ -47,6 +47,7 @@
|
|
|
47
47
|
// FOLDRUN_S3_PATH_STYLE default true — R2 speaks path style; false on S3
|
|
48
48
|
// FOLDRUN_STORAGE_MAX_MB per object, default 512
|
|
49
49
|
// FOLDRUN_STORAGE_QUOTA_MB per workspace, default 5120
|
|
50
|
+
import { opsError } from "./ops-log.js";
|
|
50
51
|
import fs from "node:fs";
|
|
51
52
|
import path from "node:path";
|
|
52
53
|
import crypto from "node:crypto";
|
|
@@ -563,7 +564,7 @@ async function announceFiles(tenant, workspace, paths, by) {
|
|
|
563
564
|
await fireStorageTriggers(tenant, workspace, paths, by);
|
|
564
565
|
}
|
|
565
566
|
catch (err) {
|
|
566
|
-
|
|
567
|
+
opsError("trigger.storage_failed", err, { tenant, workspace });
|
|
567
568
|
}
|
|
568
569
|
}
|
|
569
570
|
export async function putFile(tenant, workspace, rel, body, by) {
|
package/dist/src/triggers.js
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
// None of them evaluates anything. A flow that chains on another does not
|
|
12
12
|
// read that run's fields; it receives what the run concluded, as text, and
|
|
13
13
|
// an agent reads it — the same rule as every other handoff in the format.
|
|
14
|
+
import { opsLog, opsError } from "./ops-log.js";
|
|
14
15
|
import crypto from "node:crypto";
|
|
15
16
|
import { platform } from "./platform.js";
|
|
16
17
|
import { refusalCode } from "./trigger-log.js";
|
|
@@ -87,7 +88,7 @@ export async function fireChainedFlows(tenant, workspace, finished) {
|
|
|
87
88
|
try {
|
|
88
89
|
const gate = await platform.admitTrigger(tenant, workspace, flow, { body, tag: "previous_run", fields: chainFields(finished) });
|
|
89
90
|
if (!gate.admit) {
|
|
90
|
-
|
|
91
|
+
opsLog("info", "trigger.flow_not_started", { tenant, workspace, flow: flow.name, reason: gate.reason });
|
|
91
92
|
continue;
|
|
92
93
|
}
|
|
93
94
|
try {
|
|
@@ -97,7 +98,7 @@ export async function fireChainedFlows(tenant, workspace, finished) {
|
|
|
97
98
|
`after:${finished.flow}`,
|
|
98
99
|
], null, finished.test ? { test: true } : {});
|
|
99
100
|
started.push(run.id);
|
|
100
|
-
|
|
101
|
+
opsLog("info", "trigger.flow_started", { tenant, workspace, flow: flow.name, runId: run.id, kind: "previous_run", outcome: finished.status });
|
|
101
102
|
}
|
|
102
103
|
catch (err) {
|
|
103
104
|
await platform.rollbackTrigger(tenant, workspace, flow, { reason: err instanceof Error ? err.message : String(err), code: refusalCode(err) });
|
|
@@ -105,7 +106,7 @@ export async function fireChainedFlows(tenant, workspace, finished) {
|
|
|
105
106
|
}
|
|
106
107
|
}
|
|
107
108
|
catch (err) {
|
|
108
|
-
|
|
109
|
+
opsError("trigger.flow_failed", err, { tenant, workspace, flow: flow.name });
|
|
109
110
|
}
|
|
110
111
|
}
|
|
111
112
|
return started;
|
|
@@ -152,7 +153,7 @@ export async function fireStorageTriggers(tenant, workspace, paths, by) {
|
|
|
152
153
|
// forty runs — which is exactly what `debounce:` is for.
|
|
153
154
|
const gate = await platform.admitTrigger(tenant, workspace, flow, { body, tag: "storage_event", fields: { by, paths: hits } });
|
|
154
155
|
if (!gate.admit) {
|
|
155
|
-
|
|
156
|
+
opsLog("info", "trigger.storage_not_started", { tenant, workspace, flow: flow.name, reason: gate.reason });
|
|
156
157
|
continue;
|
|
157
158
|
}
|
|
158
159
|
try {
|
|
@@ -167,7 +168,7 @@ export async function fireStorageTriggers(tenant, workspace, paths, by) {
|
|
|
167
168
|
}
|
|
168
169
|
}
|
|
169
170
|
catch (err) {
|
|
170
|
-
|
|
171
|
+
opsError("trigger.storage_failed", err, { tenant, workspace, flow: flow.name });
|
|
171
172
|
}
|
|
172
173
|
}
|
|
173
174
|
return started;
|
package/dist/src/webhook.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// Per-flow webhook tokens, derived rather than stored: HMAC of the flow's
|
|
2
2
|
// identity under the install's secret key. Stable across restarts, unique
|
|
3
3
|
// per flow, and rotating FOLDRUN_SECRET_KEY invalidates every hook at once.
|
|
4
|
+
import { opsLog } from "./ops-log.js";
|
|
4
5
|
import fs from "node:fs";
|
|
5
6
|
import path from "node:path";
|
|
6
7
|
import { workspaceDir } from "./store.js";
|
|
@@ -171,8 +172,8 @@ function noteRefusal(tenant, workspace, delivery) {
|
|
|
171
172
|
seen.since++;
|
|
172
173
|
return;
|
|
173
174
|
}
|
|
174
|
-
|
|
175
|
-
|
|
175
|
+
// count: this one and those refused since the last note.
|
|
176
|
+
opsLog("warn", "webhook.delivery_refused", { tenant, workspace, flow: delivery.flow, outcome: delivery.outcome, count: (seen?.since ?? 0) + 1 });
|
|
176
177
|
refusalNotes.set(key, { at: now, since: 0 });
|
|
177
178
|
if (refusalNotes.size > 10_000)
|
|
178
179
|
refusalNotes.clear(); // bounded: a note lost beats memory
|
package/package.json
CHANGED
package/src/capture.ts
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
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
7
|
|
|
8
|
+
import { opsError } from "./ops-log.ts";
|
|
8
9
|
import { redactText } from "./scan.ts";
|
|
9
10
|
import { writeCapturedCall, CAPTURE_CAP } from "./store.ts";
|
|
10
11
|
import { isFileValue, fileContent, isApiValue, apiConfigOf, isClientCertValue, clientCertOf } from "./secrets.ts";
|
|
@@ -114,7 +115,7 @@ export function recordCallIo(
|
|
|
114
115
|
});
|
|
115
116
|
return true;
|
|
116
117
|
} catch (err) {
|
|
117
|
-
|
|
118
|
+
opsError("capture.write_failed", err, { tool, runId });
|
|
118
119
|
return false;
|
|
119
120
|
}
|
|
120
121
|
}
|
package/src/mail.ts
CHANGED
|
@@ -24,6 +24,7 @@
|
|
|
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
26
|
|
|
27
|
+
import { opsError } from "./ops-log.ts";
|
|
27
28
|
import crypto from "node:crypto";
|
|
28
29
|
import { platform } from "./platform.ts";
|
|
29
30
|
import { installKey, publicUrl } from "./webhook.ts";
|
|
@@ -247,7 +248,7 @@ export async function mailWanted(tenant: string, email: string, category: MailCa
|
|
|
247
248
|
} catch (err) {
|
|
248
249
|
// A preferences store that cannot be read sends: a missed alert is
|
|
249
250
|
// worse than one unwanted mail, and the next send asks again.
|
|
250
|
-
|
|
251
|
+
opsError("mail.preference_unreadable", err, { tenant, kind: category, outcome: "sent" }, "warn");
|
|
251
252
|
return true;
|
|
252
253
|
}
|
|
253
254
|
}
|
package/src/notify.ts
CHANGED
|
@@ -31,6 +31,7 @@
|
|
|
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
33
|
|
|
34
|
+
import { opsLog, opsError } from "./ops-log.ts";
|
|
34
35
|
import crypto from "node:crypto";
|
|
35
36
|
import { readAgentsMd } from "./runner.ts";
|
|
36
37
|
import { accountDir, workspaceDir, runCost, readFlow, runVerdict, type RunRecord } from "./store.ts";
|
|
@@ -179,9 +180,7 @@ export function signatureHeaders(
|
|
|
179
180
|
if (!config.signingSecret) return {};
|
|
180
181
|
const secret = getSecret(tenant, config.signingSecret, workspace);
|
|
181
182
|
if (!secret) {
|
|
182
|
-
|
|
183
|
-
`[foldrun] notify: signing_secret names ${signingSecretShown(config.signingSecret)}, which is not in the vault for ${tenant}/${workspace} — sending unsigned`,
|
|
184
|
-
);
|
|
183
|
+
opsLog("warn", "notify.signing_secret_missing", { tenant, workspace, outcome: "sent_unsigned" });
|
|
185
184
|
return {};
|
|
186
185
|
}
|
|
187
186
|
const timestamp = Math.floor(Date.now() / 1000).toString();
|
|
@@ -503,7 +502,7 @@ export async function sendPlainNotificationOutcome(
|
|
|
503
502
|
const r = await platform.deliverWebhook(tenant, workspace, { event: msg.event, body: JSON.stringify(body), retry: true });
|
|
504
503
|
return { ok: r.ok, retrying: r.retrying === true };
|
|
505
504
|
} catch (err) {
|
|
506
|
-
|
|
505
|
+
opsError("notify.event_failed", err, { tenant, workspace, kind: msg.event });
|
|
507
506
|
return no;
|
|
508
507
|
}
|
|
509
508
|
}
|
|
@@ -672,7 +671,9 @@ export async function sendRunNotification(
|
|
|
672
671
|
if (config.email) {
|
|
673
672
|
const mail = notifyMail(tenant, workspace);
|
|
674
673
|
if (!mail) {
|
|
675
|
-
|
|
674
|
+
// RESEND_API_KEY (and EMAIL_FROM) on the account, or
|
|
675
|
+
// FOLDRUN_RESEND_API_KEY on the platform.
|
|
676
|
+
opsLog("error", "notify.no_mail_credential", { tenant, workspace });
|
|
676
677
|
return false;
|
|
677
678
|
}
|
|
678
679
|
// A gate is its own category: a person may want failures and not
|
|
@@ -707,7 +708,9 @@ export async function sendRunNotification(
|
|
|
707
708
|
// Resend's body says WHY — "domain not verified", "can only send to
|
|
708
709
|
// your own address" — and a status alone sent someone to the wrong
|
|
709
710
|
// dashboard for twenty minutes on 2026-09-06.
|
|
710
|
-
|
|
711
|
+
// The provider's words stay out of our log (they quote what was
|
|
712
|
+
// sent); the status is what an operator can act on.
|
|
713
|
+
opsLog("error", "notify.email_failed", { tenant, workspace, status: r.status });
|
|
711
714
|
return false;
|
|
712
715
|
}
|
|
713
716
|
return true;
|
|
@@ -717,18 +720,18 @@ export async function sendRunNotification(
|
|
|
717
720
|
// vault instead of in a file that gets committed.
|
|
718
721
|
const target = webhookTarget(tenant, workspace, config);
|
|
719
722
|
if (!target.url) {
|
|
720
|
-
|
|
723
|
+
opsLog("error", "notify.no_webhook_url", { tenant, workspace, reason: target.refused ? "refused" : "secret_not_set" });
|
|
721
724
|
return false;
|
|
722
725
|
}
|
|
723
726
|
const event = blocked ? "blocked" : run.status;
|
|
724
727
|
const r = await platform.deliverWebhook(tenant, workspace, { event, body: JSON.stringify(body), retry: true });
|
|
725
728
|
if (!r.ok) {
|
|
726
|
-
|
|
729
|
+
opsLog("error", "notify.webhook_failed", { tenant, workspace, status: r.statusCode, retrying: r.retrying === true });
|
|
727
730
|
return false;
|
|
728
731
|
}
|
|
729
732
|
return true;
|
|
730
733
|
} catch (err) {
|
|
731
|
-
|
|
734
|
+
opsError("notify.failed", err, { tenant, workspace });
|
|
732
735
|
return false;
|
|
733
736
|
}
|
|
734
737
|
}
|
package/src/ops-log.ts
ADDED
|
@@ -0,0 +1,399 @@
|
|
|
1
|
+
// What the platform says about itself, in a shape that cannot carry an
|
|
2
|
+
// account's content (FOL-121).
|
|
3
|
+
//
|
|
4
|
+
// A hosted pod's stdout and stderr leave the cluster: they are our
|
|
5
|
+
// operations log (Grafana Cloud, through Alloy), read by us, not by the
|
|
6
|
+
// account whose run it was. An account's prompts, replies, files, tool
|
|
7
|
+
// arguments and the words of its errors belong in that account's own run
|
|
8
|
+
// trace — never here.
|
|
9
|
+
//
|
|
10
|
+
// FOL-107 is why. An eval judge's model process died, and modelProcessError
|
|
11
|
+
// did the right thing for the person (one short line in the eval result) and
|
|
12
|
+
// the wrong thing for the log: "the details are in the server log" meant
|
|
13
|
+
// 2 KB of the CLI's stderr, prompt text included, shipped out with every
|
|
14
|
+
// other platform line. Nothing about a string says whether it is content,
|
|
15
|
+
// so the rule here is structural, in three parts:
|
|
16
|
+
//
|
|
17
|
+
// 1. One writer. `opsLog(level, event, fields)` and `opsError(event, err,
|
|
18
|
+
// fields)` build a line from a CLOSED set of field names, each with a
|
|
19
|
+
// shape (FIELDS below): numbers, short lowercase words, ids with no
|
|
20
|
+
// whitespace, quotes, `/`, `:` or `@` — so no sentence, URL, path or
|
|
21
|
+
// email address fits. A value that does not fit is dropped, never
|
|
22
|
+
// truncated (a truncated prompt is still a prompt), and an unknown field
|
|
23
|
+
// name is counted, not echoed. An error is its class, its name, its
|
|
24
|
+
// code, its status and where in OUR code it was thrown — never its
|
|
25
|
+
// message, which is whatever the thrower put there.
|
|
26
|
+
// 2. One boundary. `installOpsBoundary()`, the first import of every
|
|
27
|
+
// hosted entry point (worker, egress, assistant, the web's
|
|
28
|
+
// instrumentation), replaces console.* and process.stdout/stderr.write.
|
|
29
|
+
// A raw console call becomes {"event":"console","at":"queue.ts:1511"}
|
|
30
|
+
// plus the class of an Error it was handed; a raw stream write becomes
|
|
31
|
+
// {"event":"stream.raw","bytes":n}. Its arguments are never formatted.
|
|
32
|
+
// Only the writer above reaches the real streams.
|
|
33
|
+
// 3. A guard on the source: `scripts/log-guard.mjs` refuses a new raw
|
|
34
|
+
// console call in server code that prints anything but a literal, and
|
|
35
|
+
// an opsLog/opsError whose event is not a literal.
|
|
36
|
+
//
|
|
37
|
+
// Outside a hosted process — the CLI on a laptop, `next dev`, the tests —
|
|
38
|
+
// no boundary is installed and the writer prints a readable line with the
|
|
39
|
+
// error's message: there the reader is the person whose content it is.
|
|
40
|
+
// FOLDRUN_LOG_MODE=raw keeps a process out of the boundary on purpose;
|
|
41
|
+
// infra's tests refuse it in any manifest.
|
|
42
|
+
|
|
43
|
+
import fs from "node:fs";
|
|
44
|
+
import os from "node:os";
|
|
45
|
+
|
|
46
|
+
/** Why something failed, in one word an operator can count. Small on
|
|
47
|
+
* purpose: a class is a bucket on a dashboard, not a diagnosis. */
|
|
48
|
+
export const ERROR_CLASSES = [
|
|
49
|
+
"policy_denied", // a rule said no: network, limits, a hook, a scope
|
|
50
|
+
"timeout", // ran out of time
|
|
51
|
+
"oom", // out of memory (OOMKilled, heap)
|
|
52
|
+
"disk_full", // ENOSPC, EDQUOT
|
|
53
|
+
"model_error", // the model or its process failed
|
|
54
|
+
"network_error", // a peer could not be reached (DNS, refused, reset)
|
|
55
|
+
"user_code_error", // the account's own code failed: a script, a tool, a hook
|
|
56
|
+
"not_found", // the thing named is not there
|
|
57
|
+
"cancelled", // stopped on purpose (a person, a shutdown, an abort)
|
|
58
|
+
"platform_error", // ours: everything else
|
|
59
|
+
] as const;
|
|
60
|
+
export type ErrorClass = (typeof ERROR_CLASSES)[number];
|
|
61
|
+
|
|
62
|
+
export function isErrorClass(v: unknown): v is ErrorClass {
|
|
63
|
+
return typeof v === "string" && (ERROR_CLASSES as readonly string[]).includes(v);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** The platform-wide failure causes an issue is grouped by (issues.ts
|
|
67
|
+
* PLATFORM_CAUSES keys), as a log field. */
|
|
68
|
+
export const CAUSES = ["sandbox", "model-auth", "model-cap", "model-busy", "worker"] as const;
|
|
69
|
+
|
|
70
|
+
/** A short lowercase word: an outcome, a role, a reason code. */
|
|
71
|
+
const WORD = /^[a-z][a-z0-9_-]{0,31}$/;
|
|
72
|
+
/** An id or a name: no whitespace, quotes, `/`, `:` or `@` — nothing a
|
|
73
|
+
* sentence, a URL, a path or an email address fits in. */
|
|
74
|
+
const ID = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/;
|
|
75
|
+
/** A code, as the field holds it: errno, SQLSTATE, an undici or Node code. */
|
|
76
|
+
const CODE = /^[A-Z0-9_]{2,40}$/;
|
|
77
|
+
/** A code an error may hand over. Not any upper-case word — an error's
|
|
78
|
+
* `code` is whatever its thrower set — but the system's errno names, a
|
|
79
|
+
* SQLSTATE (five characters, a digit first, or XX000), and Node's and
|
|
80
|
+
* undici's own `ERR_…` codes. */
|
|
81
|
+
const ERRNO = new Set(Object.keys(os.constants.errno));
|
|
82
|
+
function knownCode(code: string): boolean {
|
|
83
|
+
return ERRNO.has(code) || /^[0-9][0-9A-Z]{4}$/.test(code) || /^XX00[0-2]$/.test(code) || /^(UND_)?ERR_[A-Z0-9_]{2,36}$/.test(code);
|
|
84
|
+
}
|
|
85
|
+
/** An Error subclass's name, as the field holds it. */
|
|
86
|
+
const ERROR_NAME = /^[A-Z][A-Za-z0-9]{0,40}$/;
|
|
87
|
+
/** Names an error's `name` may give as they are; any other comes from its
|
|
88
|
+
* class (`constructor.name`) — our code's, since an account's code does
|
|
89
|
+
* not run in a platform process — because `name` is a settable string. */
|
|
90
|
+
const BUILTIN_NAMES = new Set(["Error", "TypeError", "RangeError", "SyntaxError", "ReferenceError", "EvalError", "URIError", "AggregateError", "AbortError", "TimeoutError", "SystemError"]);
|
|
91
|
+
/** Where in our code: a source file's base name and a line. */
|
|
92
|
+
const FRAME = /^[A-Za-z0-9_.-]{1,60}\.(ts|tsx|mts|js|mjs|cjs):\d{1,6}$/;
|
|
93
|
+
const EVENT = /^[a-z][a-z0-9_]*(\.[a-z0-9_]+){0,3}$/;
|
|
94
|
+
|
|
95
|
+
type Kind = "id" | "num" | "word" | "code" | "class" | "cause" | "errorName" | "frame" | "frames" | "bool";
|
|
96
|
+
|
|
97
|
+
/** Every field a platform log line may carry, and its shape. Adding one is
|
|
98
|
+
* a decision that its values can never be an account's content. */
|
|
99
|
+
export const FIELDS: Record<string, Kind> = {
|
|
100
|
+
// Who and what: ids, and the names an account gave its workspaces, flows,
|
|
101
|
+
// agents and evals (identifiers, by policy — never their contents).
|
|
102
|
+
tenant: "id", workspace: "id", flow: "id", agent: "id", eval: "id", tool: "id",
|
|
103
|
+
runId: "id", jobId: "id", taskId: "id", proposal: "id", lease: "id", pod: "id",
|
|
104
|
+
worker: "id", provider: "id", plan: "id", fingerprint: "id", invoice: "id", order: "id",
|
|
105
|
+
stripeEvent: "id", subscription: "id", migration: "id", housekeeping: "id",
|
|
106
|
+
// How many, how long, how much.
|
|
107
|
+
count: "num", ms: "num", secs: "num", bytes: "num", usd: "num", attempt: "num",
|
|
108
|
+
step: "num", port: "num", status: "num", exitCode: "num", percent: "num", tries: "num",
|
|
109
|
+
// What kind.
|
|
110
|
+
op: "word", role: "word", outcome: "word", reason: "word", stream: "word", kind: "word",
|
|
111
|
+
verdict: "word", phase: "word", signal: "code", where: "word",
|
|
112
|
+
// A failure.
|
|
113
|
+
errorClass: "class", errorName: "errorName", code: "code", syscall: "word", cause: "cause",
|
|
114
|
+
at: "frame", frames: "frames", retrying: "bool", ok: "bool",
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
export type OpsValue = string | number | boolean | null | undefined | readonly string[];
|
|
118
|
+
export type OpsFields = Record<string, OpsValue>;
|
|
119
|
+
export type OpsLevel = "info" | "warn" | "error";
|
|
120
|
+
|
|
121
|
+
/** Is this value one this kind of field may carry? */
|
|
122
|
+
function fits(kind: Kind, v: unknown): boolean {
|
|
123
|
+
switch (kind) {
|
|
124
|
+
case "num": return typeof v === "number" && Number.isFinite(v);
|
|
125
|
+
case "bool": return typeof v === "boolean";
|
|
126
|
+
case "id": return typeof v === "string" && ID.test(v);
|
|
127
|
+
case "word": return typeof v === "string" && WORD.test(v);
|
|
128
|
+
case "code": return typeof v === "string" && CODE.test(v);
|
|
129
|
+
case "class": return isErrorClass(v);
|
|
130
|
+
case "cause": return typeof v === "string" && (CAUSES as readonly string[]).includes(v);
|
|
131
|
+
case "errorName": return typeof v === "string" && ERROR_NAME.test(v);
|
|
132
|
+
case "frame": return typeof v === "string" && FRAME.test(v);
|
|
133
|
+
case "frames": return Array.isArray(v) && v.length <= 5 && v.every((f) => typeof f === "string" && FRAME.test(f));
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* The line as an object: the event, the fields that fit, and how many did
|
|
139
|
+
* not (by count — a refused field's name could itself be the content).
|
|
140
|
+
*/
|
|
141
|
+
export function opsLine(level: OpsLevel, event: string, fields: OpsFields = {}): Record<string, unknown> {
|
|
142
|
+
const line: Record<string, unknown> = { ops: 1, level, event: typeof event === "string" && event.length <= 64 && EVENT.test(event) ? event : "invalid_event" };
|
|
143
|
+
let dropped = 0;
|
|
144
|
+
for (const [k, v] of Object.entries(fields)) {
|
|
145
|
+
if (v === undefined || v === null) continue;
|
|
146
|
+
const kind = Object.prototype.hasOwnProperty.call(FIELDS, k) ? FIELDS[k] : undefined;
|
|
147
|
+
if (!kind || !fits(kind, v)) {
|
|
148
|
+
dropped += 1;
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
line[k] = v;
|
|
152
|
+
}
|
|
153
|
+
if (dropped) line.dropped = dropped;
|
|
154
|
+
return line;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// ------------------------------------------------------------------ writing
|
|
158
|
+
|
|
159
|
+
type Write = (text: string) => void;
|
|
160
|
+
/** The real streams, once the boundary holds them; null outside it. */
|
|
161
|
+
let real: { out: Write; err: Write } | null = null;
|
|
162
|
+
|
|
163
|
+
/** Is this process inside the boundary — a hosted pod? */
|
|
164
|
+
export function opsBoundaryInstalled(): boolean {
|
|
165
|
+
return real !== null;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function readable(level: OpsLevel, line: Record<string, unknown>, detail?: string): string {
|
|
169
|
+
const parts = Object.entries(line)
|
|
170
|
+
.filter(([k]) => k !== "ops" && k !== "level" && k !== "event")
|
|
171
|
+
.map(([k, v]) => `${k}=${Array.isArray(v) ? v.join(",") : String(v)}`);
|
|
172
|
+
return `[ops] ${line.event}${parts.length ? ` ${parts.join(" ")}` : ""}${detail ? ` — ${detail}` : ""}`;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function emit(level: OpsLevel, line: Record<string, unknown>, detail?: string): void {
|
|
176
|
+
if (real) {
|
|
177
|
+
(level === "info" ? real.out : real.err)(JSON.stringify(line) + "\n");
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
// No boundary: a laptop, a test, `next dev` — the reader is the person
|
|
181
|
+
// whose content it is, so the error's own words come along.
|
|
182
|
+
const text = readable(level, line, detail);
|
|
183
|
+
if (level === "info") console.log(text);
|
|
184
|
+
else if (level === "warn") console.warn(text);
|
|
185
|
+
else console.error(text);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** Say something about the platform: an event and its fields. */
|
|
189
|
+
export function opsLog(level: OpsLevel, event: string, fields: OpsFields = {}): void {
|
|
190
|
+
emit(level, opsLine(level, event, fields));
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// ------------------------------------------------------------------- errors
|
|
194
|
+
|
|
195
|
+
/** Which class an error belongs to — from its code, its name and its status;
|
|
196
|
+
* a few fixed markers our own code and the cluster write are matched in its
|
|
197
|
+
* message, which never leaves this function. */
|
|
198
|
+
export function errorClass(err: unknown): ErrorClass {
|
|
199
|
+
try {
|
|
200
|
+
if (!err || typeof err !== "object") return "platform_error";
|
|
201
|
+
const e = err as { name?: unknown; code?: unknown; status?: unknown; statusCode?: unknown; errorClass?: unknown; message?: unknown };
|
|
202
|
+
if (isErrorClass(e.errorClass)) return e.errorClass;
|
|
203
|
+
const code = typeof e.code === "string" ? e.code : typeof e.code === "number" ? String(e.code) : "";
|
|
204
|
+
const name = typeof e.name === "string" ? e.name : "";
|
|
205
|
+
const status = typeof e.status === "number" ? e.status : typeof e.statusCode === "number" ? e.statusCode : 0;
|
|
206
|
+
if (name === "TimeoutError" || ["ETIMEDOUT", "ESOCKETTIMEDOUT", "UND_ERR_HEADERS_TIMEOUT", "UND_ERR_BODY_TIMEOUT", "UND_ERR_CONNECT_TIMEOUT", "57014"].includes(code)) return "timeout";
|
|
207
|
+
if (name === "AbortError" || code === "ABORT_ERR") return "cancelled";
|
|
208
|
+
if (code === "ENOSPC" || code === "EDQUOT" || code === "53100") return "disk_full";
|
|
209
|
+
if (code === "ENOMEM" || code === "ERR_WORKER_OUT_OF_MEMORY" || code === "53200") return "oom";
|
|
210
|
+
if (["ECONNREFUSED", "ECONNRESET", "ENOTFOUND", "EAI_AGAIN", "EHOSTUNREACH", "ENETUNREACH", "EPIPE", "UND_ERR_SOCKET", "UND_ERR_CONNECT", "08000", "08001", "08003", "08006"].includes(code)) return "network_error";
|
|
211
|
+
if (code === "ENOENT" || code === "ENOTDIR" || status === 404) return "not_found";
|
|
212
|
+
if (code === "EACCES" || code === "EPERM" || status === 401 || status === 403 || status === 423) return "policy_denied";
|
|
213
|
+
if (status === 408 || status === 504) return "timeout";
|
|
214
|
+
const message = typeof e.message === "string" ? e.message.slice(0, 4000) : "";
|
|
215
|
+
if (/\bOOMKilled\b|JavaScript heap out of memory/.test(message)) return "oom";
|
|
216
|
+
if (/no space left on device/i.test(message)) return "disk_full";
|
|
217
|
+
if (/\b(Claude Code process|model process|api\.anthropic\.com)\b/.test(message)) return "model_error";
|
|
218
|
+
return "platform_error";
|
|
219
|
+
} catch {
|
|
220
|
+
return "platform_error";
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** Is this source path the platform's own code (core, platform, web, their
|
|
225
|
+
* dependencies), not something an account brought — and a file that is
|
|
226
|
+
* really there? A stack is a settable string; a frame naming a file that
|
|
227
|
+
* does not exist was written by someone, not by V8. */
|
|
228
|
+
const seenPaths = new Map<string, boolean>();
|
|
229
|
+
function ourPath(p: string): boolean {
|
|
230
|
+
if (/^node:[a-z_/]+$/.test(p)) return true;
|
|
231
|
+
// A checkout (the image runs core and platform from source), the web's
|
|
232
|
+
// build, or the published package (`node_modules/@foldrun/core/dist`).
|
|
233
|
+
if (!/\/foldrun-(core|platform|web)\/(src|server|app|lib|dist|\.next|node_modules|tests|scripts|instrumentation)|\/node_modules\/@foldrun\//.test(p)) return false;
|
|
234
|
+
let known = seenPaths.get(p);
|
|
235
|
+
if (known === undefined) {
|
|
236
|
+
try {
|
|
237
|
+
known = fs.statSync(p).isFile();
|
|
238
|
+
} catch {
|
|
239
|
+
known = false;
|
|
240
|
+
}
|
|
241
|
+
if (seenPaths.size > 2000) seenPaths.clear();
|
|
242
|
+
seenPaths.set(p, known);
|
|
243
|
+
}
|
|
244
|
+
return known;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** `file.ts:12` frames of our code from a stack, first `max` of them. The
|
|
248
|
+
* first line (the message) is never read, and function names are left
|
|
249
|
+
* out: only a base name and a line, which a sentence cannot be. */
|
|
250
|
+
export function stackFrames(stack: unknown, max = 5, skip = 0): string[] {
|
|
251
|
+
if (typeof stack !== "string") return [];
|
|
252
|
+
const out: string[] = [];
|
|
253
|
+
let seen = 0;
|
|
254
|
+
for (const raw of stack.slice(0, 20_000).split("\n")) {
|
|
255
|
+
const m = /^\s+at (?:.*? \()?(.+?):(\d+):\d+\)?$/.exec(raw);
|
|
256
|
+
if (!m) continue;
|
|
257
|
+
const where = m[1].replace(/^file:\/\//, "");
|
|
258
|
+
if (!ourPath(where)) continue;
|
|
259
|
+
if (seen++ < skip) continue;
|
|
260
|
+
const frame = `${where.split("/").pop()}:${m[2]}`;
|
|
261
|
+
if (FRAME.test(frame)) out.push(frame);
|
|
262
|
+
if (out.length >= max) break;
|
|
263
|
+
}
|
|
264
|
+
return out;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** The fields of an error a log line may carry. Never throws: a getter on a
|
|
268
|
+
* strange object is not allowed to take the log down with it. */
|
|
269
|
+
export function errorFields(err: unknown): OpsFields {
|
|
270
|
+
try {
|
|
271
|
+
const e = (err && typeof err === "object" ? err : {}) as { name?: unknown; code?: unknown; syscall?: unknown; status?: unknown; statusCode?: unknown; stack?: unknown; opsReason?: unknown };
|
|
272
|
+
const code = typeof e.code === "string" ? e.code : typeof e.code === "number" ? String(e.code) : undefined;
|
|
273
|
+
const status = typeof e.status === "number" ? e.status : typeof e.statusCode === "number" ? e.statusCode : undefined;
|
|
274
|
+
let errorName = "NotAnError";
|
|
275
|
+
if (err instanceof Error) {
|
|
276
|
+
const cls = (err as { constructor?: { name?: unknown } }).constructor?.name;
|
|
277
|
+
errorName = BUILTIN_NAMES.has(err.name) ? err.name : typeof cls === "string" && ERROR_NAME.test(cls) ? cls : "Error";
|
|
278
|
+
}
|
|
279
|
+
return {
|
|
280
|
+
errorClass: errorClass(err),
|
|
281
|
+
errorName,
|
|
282
|
+
code: code && CODE.test(code) && knownCode(code) ? code : undefined,
|
|
283
|
+
syscall: typeof e.syscall === "string" && WORD.test(e.syscall) ? e.syscall : undefined,
|
|
284
|
+
status,
|
|
285
|
+
// A reason our own code attached (`opsReason`: a word, by FIELDS).
|
|
286
|
+
reason: typeof e.opsReason === "string" && WORD.test(e.opsReason) ? e.opsReason : undefined,
|
|
287
|
+
frames: err instanceof Error ? stackFrames(e.stack) : [],
|
|
288
|
+
};
|
|
289
|
+
} catch {
|
|
290
|
+
return { errorClass: "platform_error", errorName: "Error" };
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** An Error whose message is for a person and whose `reason` — a word —
|
|
295
|
+
* is what a hosted log says instead: `throw withOpsReason(new Error("egress.ts
|
|
296
|
+
* needs FOLDRUN_EGRESS_URL…"), "no_egress_url")`. */
|
|
297
|
+
export function withOpsReason<E extends Error>(err: E, reason: string): E {
|
|
298
|
+
return Object.assign(err, { opsReason: reason });
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** The message an error would show, for the readable line outside the
|
|
302
|
+
* boundary only. */
|
|
303
|
+
function messageOf(err: unknown): string {
|
|
304
|
+
try {
|
|
305
|
+
return err instanceof Error ? err.message : String(err);
|
|
306
|
+
} catch {
|
|
307
|
+
return "";
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** A failure: its class and where it happened — never its words inside the
|
|
312
|
+
* boundary. A field the caller names (an `errorClass` it knows) wins. */
|
|
313
|
+
export function opsError(event: string, err: unknown, fields: OpsFields = {}, level: OpsLevel = "error"): void {
|
|
314
|
+
emit(level, opsLine(level, event, { ...errorFields(err), ...fields }), real ? undefined : messageOf(err));
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
// ----------------------------------------------------------------- boundary
|
|
318
|
+
|
|
319
|
+
/** Where in our code a raw console call was made: the first frame outside
|
|
320
|
+
* this file. From a stack we made, so it is a real code location. */
|
|
321
|
+
function callsite(): string | undefined {
|
|
322
|
+
const stack = new Error().stack ?? "";
|
|
323
|
+
for (const raw of stack.split("\n").slice(1)) {
|
|
324
|
+
const m = /^\s+at (?:.*? \()?(.+?):(\d+):\d+\)?$/.exec(raw);
|
|
325
|
+
if (!m || /\/ops-log\.(ts|js)$/.test(m[1])) continue;
|
|
326
|
+
const where = m[1].replace(/^file:\/\//, "");
|
|
327
|
+
if (!ourPath(where)) return undefined;
|
|
328
|
+
const frame = `${where.split("/").pop()}:${m[2]}`;
|
|
329
|
+
return FRAME.test(frame) ? frame : undefined;
|
|
330
|
+
}
|
|
331
|
+
return undefined;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
export interface BoundaryOptions {
|
|
335
|
+
/** On an uncaught exception or unhandled rejection: log its class and
|
|
336
|
+
* exit 1, as Node would — for processes with no handler of their own
|
|
337
|
+
* (the worker, egress, the assistant; Next.js has its own). */
|
|
338
|
+
exitOnUncaught?: boolean;
|
|
339
|
+
env?: NodeJS.ProcessEnv;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/**
|
|
343
|
+
* Put this process inside the boundary. Idempotent. Off only where
|
|
344
|
+
* FOLDRUN_LOG_MODE=raw or NODE_ENV=development (`next dev`).
|
|
345
|
+
*/
|
|
346
|
+
export function installOpsBoundary(opts: BoundaryOptions = {}): boolean {
|
|
347
|
+
const env = opts.env ?? process.env;
|
|
348
|
+
if (real) return true;
|
|
349
|
+
if (env.FOLDRUN_LOG_MODE === "raw" || (env.FOLDRUN_LOG_MODE !== "ops" && env.NODE_ENV === "development")) return false;
|
|
350
|
+
const outWrite = process.stdout.write.bind(process.stdout) as (s: string) => boolean;
|
|
351
|
+
const errWrite = process.stderr.write.bind(process.stderr) as (s: string) => boolean;
|
|
352
|
+
real = { out: (s) => void outWrite(s), err: (s) => void errWrite(s) };
|
|
353
|
+
|
|
354
|
+
const fromConsole = (level: OpsLevel) => (...args: unknown[]) => {
|
|
355
|
+
// Never formatted: an argument's text, its inspect() and its toJSON()
|
|
356
|
+
// are not read. An Error handed over gives its class, name and code.
|
|
357
|
+
let firstError: unknown;
|
|
358
|
+
for (const a of args) {
|
|
359
|
+
if (a instanceof Error) {
|
|
360
|
+
firstError = a;
|
|
361
|
+
break;
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
const fields: OpsFields = { at: callsite(), ...(firstError ? errorFields(firstError) : {}) };
|
|
365
|
+
emit(level, opsLine(level, "console", fields));
|
|
366
|
+
};
|
|
367
|
+
console.log = fromConsole("info");
|
|
368
|
+
console.info = fromConsole("info");
|
|
369
|
+
console.debug = fromConsole("info");
|
|
370
|
+
console.trace = fromConsole("info");
|
|
371
|
+
console.warn = fromConsole("warn");
|
|
372
|
+
console.error = fromConsole("error");
|
|
373
|
+
|
|
374
|
+
// Anything else that writes to the streams — a dependency, Next.js, a
|
|
375
|
+
// warning — is counted, not passed on. The write contract is kept: the
|
|
376
|
+
// callback runs, and the answer is "keep writing".
|
|
377
|
+
const fromStream = (stream: "stdout" | "stderr") =>
|
|
378
|
+
function write(chunk: unknown, encoding?: unknown, cb?: unknown): boolean {
|
|
379
|
+
const done = typeof encoding === "function" ? encoding : cb;
|
|
380
|
+
const bytes = typeof chunk === "string" ? Buffer.byteLength(chunk) : chunk instanceof Uint8Array ? chunk.byteLength : 0;
|
|
381
|
+
emit(stream === "stdout" ? "info" : "error", opsLine(stream === "stdout" ? "info" : "error", "stream.raw", { stream, bytes, at: callsite() }));
|
|
382
|
+
if (typeof done === "function") queueMicrotask(() => (done as (e?: Error | null) => void)(null));
|
|
383
|
+
return true;
|
|
384
|
+
};
|
|
385
|
+
process.stdout.write = fromStream("stdout") as typeof process.stdout.write;
|
|
386
|
+
process.stderr.write = fromStream("stderr") as typeof process.stderr.write;
|
|
387
|
+
|
|
388
|
+
if (opts.exitOnUncaught) {
|
|
389
|
+
process.on("uncaughtException", (err) => {
|
|
390
|
+
opsError("process.uncaught_exception", err);
|
|
391
|
+
process.exit(1);
|
|
392
|
+
});
|
|
393
|
+
process.on("unhandledRejection", (err) => {
|
|
394
|
+
opsError("process.unhandled_rejection", err);
|
|
395
|
+
process.exit(1);
|
|
396
|
+
});
|
|
397
|
+
}
|
|
398
|
+
return true;
|
|
399
|
+
}
|