@foldrun/core 15.1.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 (45) 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/env-names.d.ts +12 -0
  8. package/dist/src/env-names.js +49 -0
  9. package/dist/src/failure.d.ts +92 -0
  10. package/dist/src/failure.js +294 -0
  11. package/dist/src/frontmatter-fields.js +1 -1
  12. package/dist/src/install-helper.js +10 -5
  13. package/dist/src/network.js +1 -1
  14. package/dist/src/ops-log.js +4 -0
  15. package/dist/src/otel.d.ts +16 -1
  16. package/dist/src/otel.js +121 -5
  17. package/dist/src/run-container.d.ts +55 -3
  18. package/dist/src/run-container.js +109 -17
  19. package/dist/src/run-event.d.ts +179 -0
  20. package/dist/src/run-event.js +473 -0
  21. package/dist/src/runner.js +8 -1
  22. package/dist/src/runtime.d.ts +113 -16
  23. package/dist/src/runtime.js +528 -44
  24. package/dist/src/scan.js +80 -18
  25. package/dist/src/starter.js +1 -1
  26. package/dist/src/store.d.ts +25 -3
  27. package/dist/src/store.js +40 -10
  28. package/package.json +2 -1
  29. package/src/a2a-publish.ts +19 -1
  30. package/src/a2a-reach.ts +503 -0
  31. package/src/browse-egress.ts +8 -7
  32. package/src/env-names.ts +53 -0
  33. package/src/failure.ts +368 -0
  34. package/src/frontmatter-fields.ts +1 -1
  35. package/src/install-helper.ts +10 -5
  36. package/src/network.ts +1 -1
  37. package/src/ops-log.ts +4 -0
  38. package/src/otel.ts +122 -7
  39. package/src/run-container.ts +112 -21
  40. package/src/run-event.ts +563 -0
  41. package/src/runner.ts +8 -1
  42. package/src/runtime.ts +543 -45
  43. package/src/scan.ts +91 -20
  44. package/src/starter.ts +1 -1
  45. package/src/store.ts +59 -11
@@ -0,0 +1,179 @@
1
+ import { type RunRecord, type StepRecord } from "./store.ts";
2
+ import { type ErrorClass, type OpsFields } from "./ops-log.ts";
3
+ import { type FailureExplained, type FailureKind, type LimitScope } from "./failure.ts";
4
+ /** The funnel's marks, in order. */
5
+ export declare const FUNNEL: readonly ["submitted", "queued", "eligible", "claimed", "scheduled", "podReady", "sandboxUp", "firstOutput", "finished"];
6
+ export type FunnelMark = (typeof FUNNEL)[number];
7
+ /** Whether a finished run counts toward the success-rate SLI: `good`
8
+ * (completed), `bad` (failed, and the failure is ours, a provider's or the
9
+ * cluster's), or `excluded` (the customer's own code, settings or decision
10
+ * — sloOutcome). Null while the run is not finished. */
11
+ export type SloOutcome = "good" | "bad" | "excluded";
12
+ /** Why a failed run is excluded from the success rate, or why it is bad. */
13
+ export declare const SLO_REASONS: readonly ["completed", "cancelled", "customer_code", "customer_check", "customer_budget", "customer_security", "customer_network", "customer_credential", "customer_limit", "platform", "model", "capacity", "deadline", "unexplained"];
14
+ export type SloReason = (typeof SLO_REASONS)[number];
15
+ /** The SLO rule's version, on every row: a row says which rule judged it,
16
+ * so a change to the rule never silently rewrites history's meaning. */
17
+ export declare const SLO_RULES_VERSION = 1;
18
+ export interface RunWideEvent {
19
+ runId: string;
20
+ tenant: string;
21
+ workspace: string;
22
+ /** The flow's name, or the agent's for a direct agent run. */
23
+ flow: string;
24
+ kind: "flow" | "agent";
25
+ test: boolean;
26
+ status: RunRecord["status"];
27
+ errorClass: ErrorClass | null;
28
+ failureKind: FailureKind | null;
29
+ failureScope: LimitScope | null;
30
+ slo: SloOutcome | null;
31
+ sloReason: SloReason | null;
32
+ rulesVersion: number;
33
+ /** The funnel step's runner image, model (its first model call's, else
34
+ * the step's own setting) and size class. */
35
+ image: "full" | "slim" | null;
36
+ model: string | null;
37
+ size: string | null;
38
+ /** ISO instants; null where the run did not reach the mark, or the
39
+ * record does not say. */
40
+ at: Record<FunnelMark, string | null>;
41
+ /** The earliest model output of any step this run executed — with
42
+ * parallel steps, possibly not the funnel step's. */
43
+ earliestOutput: string | null;
44
+ /** The funnel step's index; its start-up marks, in seconds from `startupAt`
45
+ * (STARTUP_PHASES); and whether that origin is the executor's own
46
+ * (`exact`) or the attempt's start (`estimated`). */
47
+ funnelStep: number | null;
48
+ startup: Record<string, number> | null;
49
+ startupAt: string | null;
50
+ origin: "exact" | "estimated" | null;
51
+ /** Steps in the record (rescues and sub-agents included), how many ran in
52
+ * a sandbox, and attempts across the steps this run executed. */
53
+ steps: number;
54
+ sandboxedSteps: number;
55
+ attempts: number;
56
+ /** Summed over every attempt of every step this run executed. */
57
+ costUsd: number;
58
+ computeSecs: number;
59
+ /** The funnel step's sandbox start-up (step.startupSecs). */
60
+ startupSecs: number | null;
61
+ /** The largest any one step's sandbox held, and the most any one used —
62
+ * not the run's capacity (parallel steps add up), and the limit and the
63
+ * use may be two different steps'. Each step's last attempt. Disk used
64
+ * is not measured in the sandbox today: null, never estimated. CPU busy
65
+ * and throttled seconds are summed. */
66
+ cpuLimit: number | null;
67
+ cpuBusySecs: number | null;
68
+ cpuThrottledSecs: number | null;
69
+ memLimitGiB: number | null;
70
+ memPeakBytes: number | null;
71
+ diskLimitGiB: number | null;
72
+ diskUsedBytes: number | null;
73
+ }
74
+ /** What the queue knows that the record does not (the platform's row). */
75
+ export interface QueueFacts {
76
+ queuedAt?: string | null;
77
+ eligibleAt?: string | null;
78
+ claimedAt?: string | null;
79
+ }
80
+ /**
81
+ * Why a failed run failed, for the wide event. runFailure (store.ts, the
82
+ * customer's view) reads the first failed step, an optional one included,
83
+ * and a stop only when no step failed; the funnel wants the run's own
84
+ * terminal cause: a stop first, then the step that failed the run.
85
+ */
86
+ export declare function terminalFailure(run: RunRecord): (FailureExplained & {
87
+ text: string;
88
+ step: StepRecord | null;
89
+ }) | null;
90
+ /**
91
+ * Does this run count against the platform's success rate, and why?
92
+ *
93
+ * Excluded — the customer's own code, settings or decision:
94
+ * cancelled a person or a caller stopped it
95
+ * customer_code their script, tool or hook failed
96
+ * customer_check their verify:, output: json or schema: did not hold
97
+ * customer_budget their budget: ran out
98
+ * customer_security a platform security control stopped what their agent did
99
+ * customer_network the error IS the proxy refusing a site off their
100
+ * network: list (a refusal merely on the trail of a
101
+ * step that failed for another reason does not count)
102
+ * customer_credential their own model key was refused (supply `own`)
103
+ * customer_limit a limit whose scope is theirs (CUSTOMER_SCOPES)
104
+ * Bad — everything else: platform (ours, or a node short of memory or disk
105
+ * evicting it), model (a provider failing, the platform's key refused),
106
+ * capacity (the install's or the node's limit), deadline (a time limit with
107
+ * no scope of theirs), unexplained.
108
+ */
109
+ export declare function sloOutcome(run: RunRecord, failure?: (FailureExplained & {
110
+ text: string;
111
+ step: StepRecord | null;
112
+ }) | null): {
113
+ slo: SloOutcome;
114
+ reason: SloReason;
115
+ } | null;
116
+ /** The run's wide event. Pure: the record, and what the queue adds. */
117
+ export declare function runWideEvent(tenant: string, workspace: string, run: RunRecord, queue?: QueueFacts): RunWideEvent;
118
+ /** Seconds between two marks of an event, or null when either is missing
119
+ * (or the later reads earlier: two clocks). */
120
+ export declare function funnelSecs(ev: Pick<RunWideEvent, "at">, from: FunnelMark, to: FunnelMark): number | null;
121
+ /** The ops-log fields an ops span may carry — the collector's allowlist
122
+ * (foldrun-infra alloy-config.yaml) is held to this list by its test. */
123
+ export declare const OPS_SPAN_FIELDS: readonly ["runId", "tenant", "workspace", "flow", "agent", "kind", "outcome", "errorClass", "verdict", "reason", "image", "size", "model", "usd", "step", "attempt", "phase", "ms"];
124
+ /** Every name an ops span may have. */
125
+ export declare const OPS_SPAN_NAMES: readonly ["run", "submit", "queue.wait", "drive", "pod.start", "sandbox.start", "first_output", ...("startup.applied" | "startup.driver" | "startup.files" | "startup.go" | "startup.imports" | "startup.ready" | "startup.room" | "startup.services" | "startup.shim" | "startup.system" | "startup.tools")[]];
126
+ export declare const OPS_SERVICES: readonly ["foldrun-web", "foldrun-worker", "foldrun-runner"];
127
+ type Attr = {
128
+ key: string;
129
+ value: {
130
+ stringValue: string;
131
+ } | {
132
+ intValue: string;
133
+ } | {
134
+ doubleValue: number;
135
+ } | {
136
+ boolValue: boolean;
137
+ };
138
+ };
139
+ /** An ops span's fields as OTLP attributes, `foldrun.<field>`: only
140
+ * OPS_SPAN_FIELDS, only values opsLine lets through. */
141
+ export declare function opsAttributes(fields: OpsFields): Attr[];
142
+ /** The trace id of a run's ops trace — under a key of its own, never the
143
+ * account's trace id (otel.ts). */
144
+ export declare function opsTraceId(tenant: string, workspace: string, runId: string): string;
145
+ /**
146
+ * The run's ops trace as an OTLP/HTTP JSON body, or null when the run has
147
+ * no start and end to draw between.
148
+ */
149
+ export declare function opsTrace(ev: RunWideEvent): {
150
+ resourceSpans: {
151
+ resource: {
152
+ attributes: {
153
+ key: string;
154
+ value: {
155
+ stringValue: string;
156
+ };
157
+ }[];
158
+ };
159
+ scopeSpans: {
160
+ scope: {
161
+ name: string;
162
+ };
163
+ spans: {
164
+ traceId: string;
165
+ spanId: string;
166
+ parentSpanId?: string | undefined;
167
+ name: "drive" | "first_output" | "pod.start" | "queue.wait" | "run" | "sandbox.start" | "startup.applied" | "startup.driver" | "startup.files" | "startup.go" | "startup.imports" | "startup.ready" | "startup.room" | "startup.services" | "startup.shim" | "startup.system" | "startup.tools" | "submit";
168
+ kind: number;
169
+ startTimeUnixNano: string;
170
+ endTimeUnixNano: string;
171
+ attributes: Attr[];
172
+ status: {
173
+ code: number;
174
+ };
175
+ }[];
176
+ }[];
177
+ }[];
178
+ } | null;
179
+ export {};
@@ -0,0 +1,473 @@
1
+ // One run as one record: its funnel, what it held and used, what it cost,
2
+ // and how it ended (FOL-122) — the platform's wide event, built from the
3
+ // run record (and what the queue adds) by one pure function, so every
4
+ // writer and every test reads the same answer.
5
+ //
6
+ // submitted → queued → scheduled → pod ready → sandbox up → first output → finished
7
+ //
8
+ // · submitted the record was created (run.startedAt; status `queued`)
9
+ // · queued its job first went into the queue (the platform's
10
+ // run_events row, written at enqueue; else submitted)
11
+ // · eligible when that job could first be claimed: the later of queued
12
+ // and its `not_before` (a wait: is not queue wait)
13
+ // · claimed a worker first claimed the job — which can still hand it
14
+ // back (overlap:, the account's cap, a pause)
15
+ // · scheduled a worker began driving the run (run.drivenAt): queue wait
16
+ // is eligible → scheduled, what the customer waited
17
+ // · pod ready the funnel step's pod was Running (startup `ready`)
18
+ // · sandbox up its runtime and tools were built (`tools`)
19
+ // · first output the funnel step's model's first text or tool call
20
+ // (`model`) — the same step's, so pod ready → first output
21
+ // is one sandbox's cold start; the run's earliest output of
22
+ // any step is kept beside it (earliestOutput)
23
+ // · finished run.finishedAt
24
+ //
25
+ // The FUNNEL STEP is the step (not one carried from an earlier run, not a
26
+ // rescue or a sub-agent) whose start-up began first. Its marks are its last
27
+ // attempt's — the record keeps no earlier attempt's — placed on the clock
28
+ // from `startupAt` (the executor's own origin, 5 Nov 2026 on), else from
29
+ // the attempt's start: then `origin` says "estimated". The queue wait is the
30
+ // FIRST enqueue's; a run resumed later waits again, and that is not in it.
31
+ //
32
+ // What it may hold (FOL-121): the record's metadata only — ids, names,
33
+ // counts, durations, figures, classes. Never an instruction, a reply, an
34
+ // error's words or a file: those stay in the account's own run record.
35
+ // The ops trace built from it (opsTrace, below) is stricter still: every
36
+ // attribute goes through ops-log's field shapes.
37
+ import crypto from "node:crypto";
38
+ import { isSplicedRecord, runFailure } from "./store.js";
39
+ import { ERROR_CLASSES, opsLine } from "./ops-log.js";
40
+ import { explainFailure } from "./failure.js";
41
+ import { startupBreakdown } from "./startup.js";
42
+ /** The funnel's marks, in order. */
43
+ export const FUNNEL = ["submitted", "queued", "eligible", "claimed", "scheduled", "podReady", "sandboxUp", "firstOutput", "finished"];
44
+ /** Why a failed run is excluded from the success rate, or why it is bad. */
45
+ export const SLO_REASONS = [
46
+ "completed",
47
+ // excluded
48
+ "cancelled", "customer_code", "customer_check", "customer_budget", "customer_security", "customer_network", "customer_credential", "customer_limit",
49
+ // bad
50
+ "platform", "model", "capacity", "deadline", "unexplained",
51
+ ];
52
+ /** The SLO rule's version, on every row: a row says which rule judged it,
53
+ * so a change to the rule never silently rewrites history's meaning. */
54
+ export const SLO_RULES_VERSION = 1;
55
+ const iso = (ms) => (ms === null || !Number.isFinite(ms) ? null : new Date(ms).toISOString());
56
+ const msOf = (s) => {
57
+ if (!s)
58
+ return null;
59
+ const v = Date.parse(s);
60
+ return Number.isFinite(v) ? v : null;
61
+ };
62
+ const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : null);
63
+ /** A step this run executed itself: not carried from an earlier run, not a
64
+ * rescue or a sub-agent spliced in. */
65
+ const ownStep = (s) => !s.carriedFrom && !isSplicedRecord(s);
66
+ const hasMarks = (s) => !!s.startup && typeof s.startup === "object" && Object.keys(s.startup).length > 0;
67
+ /** When the step's marks count from, and whether that is the executor's
68
+ * own origin or the attempt's start. */
69
+ function originOf(step) {
70
+ const exact = msOf(step.startupAt);
71
+ if (exact !== null)
72
+ return { ms: exact, exact: true };
73
+ const est = msOf(step.tries?.at(-1)?.startedAt) ?? msOf(step.startedAt);
74
+ return est === null ? null : { ms: est, exact: false };
75
+ }
76
+ /** The step's own model: its first call's, else what the step asked for. */
77
+ function modelOf(step) {
78
+ const call = step.calls?.find((c) => typeof c.model === "string" && c.model);
79
+ return call?.model ?? (typeof step.model === "string" && step.model ? step.model : null);
80
+ }
81
+ /** The step that failed the run, by the runner's rule (otel.ts uses the
82
+ * same): failed, not optional, not carried, not spliced; else any failed. */
83
+ const failingStep = (run) => run.steps.find((s) => s.status === "failed" && !s.optional && ownStep(s)) ?? run.steps.find((s) => s.status === "failed");
84
+ /**
85
+ * Why a failed run failed, for the wide event. runFailure (store.ts, the
86
+ * customer's view) reads the first failed step, an optional one included,
87
+ * and a stop only when no step failed; the funnel wants the run's own
88
+ * terminal cause: a stop first, then the step that failed the run.
89
+ */
90
+ export function terminalFailure(run) {
91
+ if (run.status !== "failed")
92
+ return null;
93
+ if (run.stopRequested) {
94
+ const text = `stopped by ${run.stoppedBy ?? "a person"}`;
95
+ return { ...explainFailure(text, null), text, step: null };
96
+ }
97
+ const step = failingStep(run);
98
+ if (step) {
99
+ const text = step.events.filter((e) => e.type === "error").at(-1)?.text ?? "failed without an error event";
100
+ return { ...explainFailure(text, step), text, step };
101
+ }
102
+ const f = runFailure(run);
103
+ return f ? { ...f, text: f.reason, step: null } : null;
104
+ }
105
+ /** The scopes of a limit the customer sets or buys: their step's own
106
+ * (timeout:, size:, resources:), their flow's or workspace's pool, their
107
+ * plan's. The install's and the largest node's are ours. */
108
+ const CUSTOMER_SCOPES = ["step", "run", "workspace", "account"];
109
+ /**
110
+ * Does this run count against the platform's success rate, and why?
111
+ *
112
+ * Excluded — the customer's own code, settings or decision:
113
+ * cancelled a person or a caller stopped it
114
+ * customer_code their script, tool or hook failed
115
+ * customer_check their verify:, output: json or schema: did not hold
116
+ * customer_budget their budget: ran out
117
+ * customer_security a platform security control stopped what their agent did
118
+ * customer_network the error IS the proxy refusing a site off their
119
+ * network: list (a refusal merely on the trail of a
120
+ * step that failed for another reason does not count)
121
+ * customer_credential their own model key was refused (supply `own`)
122
+ * customer_limit a limit whose scope is theirs (CUSTOMER_SCOPES)
123
+ * Bad — everything else: platform (ours, or a node short of memory or disk
124
+ * evicting it), model (a provider failing, the platform's key refused),
125
+ * capacity (the install's or the node's limit), deadline (a time limit with
126
+ * no scope of theirs), unexplained.
127
+ */
128
+ export function sloOutcome(run, failure = terminalFailure(run)) {
129
+ if (run.status === "completed")
130
+ return { slo: "good", reason: "completed" };
131
+ if (run.status !== "failed")
132
+ return null;
133
+ const excluded = (reason) => ({ slo: "excluded", reason });
134
+ const bad = (reason) => ({ slo: "bad", reason });
135
+ if (!failure)
136
+ return bad("unexplained");
137
+ switch (failure.kind) {
138
+ case "stopped":
139
+ return excluded("cancelled");
140
+ case "code":
141
+ return excluded("customer_code");
142
+ case "check":
143
+ return excluded("customer_check");
144
+ case "budget":
145
+ return excluded("customer_budget");
146
+ case "security":
147
+ return excluded("customer_security");
148
+ case "network": {
149
+ // explainFailure reads a refusal on the step's trail before a code
150
+ // error, for the customer's message. Here the cause has to be the
151
+ // refusal itself: the same step without its trail's refusals, and
152
+ // what that says is the cause.
153
+ const step = failure.step;
154
+ const bare = explainFailure(failure.text, step ? { ...step, events: step.events.filter((e) => e.type === "error"), failureFacts: step.failureFacts ? { ...step.failureFacts, refusedHosts: undefined, secretHosts: undefined } : undefined } : null);
155
+ if (bare.kind === "network")
156
+ return excluded("customer_network");
157
+ return sloOutcome(run, { ...bare, text: failure.text, step });
158
+ }
159
+ case "credential":
160
+ return failure.step?.supply === "own" ? excluded("customer_credential") : bad("model");
161
+ case "memory":
162
+ case "cpu":
163
+ case "disk":
164
+ case "timeout":
165
+ if (failure.scope && CUSTOMER_SCOPES.includes(failure.scope))
166
+ return excluded("customer_limit");
167
+ if (failure.scope)
168
+ return bad("capacity");
169
+ return failure.kind === "timeout" ? bad("deadline") : bad("platform");
170
+ case "model":
171
+ return bad("model");
172
+ case "platform":
173
+ return bad("platform");
174
+ default:
175
+ return bad("unexplained");
176
+ }
177
+ }
178
+ /** The run's wide event. Pure: the record, and what the queue adds. */
179
+ export function runWideEvent(tenant, workspace, run, queue = {}) {
180
+ // The funnel step: of the steps this run executed in a sandbox, the one
181
+ // whose start-up began first (parallel steps start in any order).
182
+ let fi = null;
183
+ let fo = null;
184
+ let earliestOutput = null;
185
+ let sandboxed = 0;
186
+ run.steps.forEach((s, i) => {
187
+ if (!ownStep(s) || !hasMarks(s))
188
+ return;
189
+ sandboxed += 1;
190
+ const o = originOf(s);
191
+ if (!o)
192
+ return;
193
+ if (!fo || o.ms < fo.ms) {
194
+ fi = i;
195
+ fo = o;
196
+ }
197
+ const m = num(s.startup?.model);
198
+ if (m !== null && (earliestOutput === null || o.ms + m * 1000 < earliestOutput))
199
+ earliestOutput = o.ms + m * 1000;
200
+ });
201
+ const fs = fi === null ? null : run.steps[fi];
202
+ const origin = fo;
203
+ const mark = (p) => {
204
+ const v = num(fs?.startup?.[p]);
205
+ return v === null || !origin ? null : origin.ms + v * 1000;
206
+ };
207
+ const submitted = msOf(run.startedAt);
208
+ const queued = msOf(queue.queuedAt) ?? submitted;
209
+ const eligible = msOf(queue.eligibleAt) ?? queued;
210
+ const finished = run.status === "completed" || run.status === "failed" ? msOf(run.finishedAt) : null;
211
+ const failure = terminalFailure(run);
212
+ const slo = sloOutcome(run, failure);
213
+ let attempts = 0;
214
+ let cost = 0;
215
+ let compute = 0;
216
+ let cpuLimit = null;
217
+ let memLimit = null;
218
+ let diskLimit = null;
219
+ let peak = null;
220
+ let busy = null;
221
+ let throttled = null;
222
+ const max = (a, b) => (num(b) === null ? a : a === null ? b : Math.max(a, b));
223
+ const add = (a, b) => (num(b) === null ? a : (a ?? 0) + b);
224
+ for (const s of run.steps) {
225
+ // A step carried from an earlier run ran (and was billed) there.
226
+ if (s.carriedFrom)
227
+ continue;
228
+ attempts += typeof s.attempts === "number" ? s.attempts : (s.tries?.length ?? 0);
229
+ cost += num(s.costUsd) ?? 0;
230
+ compute += num(s.computeSecs) ?? 0;
231
+ cpuLimit = max(cpuLimit, s.reserved?.cpus);
232
+ memLimit = max(memLimit, s.reserved?.memGiB);
233
+ diskLimit = max(diskLimit, s.reserved?.diskGiB);
234
+ peak = max(peak, s.actual?.peakMemBytes);
235
+ busy = add(busy, s.actual?.busyCpuSecs);
236
+ throttled = add(throttled, s.actual?.throttledSecs);
237
+ }
238
+ const adhoc = run.flow.startsWith("adhoc:");
239
+ return {
240
+ runId: run.id,
241
+ tenant,
242
+ workspace,
243
+ flow: adhoc ? run.flow.slice("adhoc:".length) : run.flow,
244
+ kind: adhoc ? "agent" : "flow",
245
+ test: run.test === true,
246
+ status: run.status,
247
+ errorClass: run.status === "failed" ? (failure?.class ?? "platform_error") : null,
248
+ failureKind: failure?.kind ?? null,
249
+ failureScope: failure?.scope ?? null,
250
+ slo: slo?.slo ?? null,
251
+ sloReason: slo?.reason ?? null,
252
+ rulesVersion: SLO_RULES_VERSION,
253
+ image: fs?.image?.variant ?? null,
254
+ model: fs ? modelOf(fs) : null,
255
+ size: fs?.size ?? null,
256
+ at: {
257
+ submitted: iso(submitted),
258
+ queued: iso(queued),
259
+ eligible: iso(eligible),
260
+ claimed: iso(msOf(queue.claimedAt)),
261
+ scheduled: iso(msOf(run.drivenAt)),
262
+ podReady: iso(mark("ready")),
263
+ sandboxUp: iso(mark("tools")),
264
+ firstOutput: iso(mark("model")),
265
+ finished: iso(finished),
266
+ },
267
+ earliestOutput: iso(earliestOutput),
268
+ funnelStep: fi,
269
+ startup: fs?.startup ? { ...fs.startup } : null,
270
+ startupAt: origin ? iso(origin.ms) : null,
271
+ origin: origin ? (origin.exact ? "exact" : "estimated") : null,
272
+ steps: run.steps.length,
273
+ sandboxedSteps: sandboxed,
274
+ attempts,
275
+ costUsd: Math.round(cost * 1e6) / 1e6,
276
+ computeSecs: Math.round(compute * 1000) / 1000,
277
+ startupSecs: num(fs?.startupSecs),
278
+ cpuLimit,
279
+ cpuBusySecs: busy,
280
+ cpuThrottledSecs: throttled,
281
+ memLimitGiB: memLimit,
282
+ memPeakBytes: peak,
283
+ diskLimitGiB: diskLimit,
284
+ diskUsedBytes: null,
285
+ };
286
+ }
287
+ /** Seconds between two marks of an event, or null when either is missing
288
+ * (or the later reads earlier: two clocks). */
289
+ export function funnelSecs(ev, from, to) {
290
+ const a = msOf(ev.at[from]);
291
+ const b = msOf(ev.at[to]);
292
+ if (a === null || b === null || b < a)
293
+ return null;
294
+ return (b - a) / 1000;
295
+ }
296
+ // ------------------------------------------------------------- ops trace
297
+ //
298
+ // The run's funnel as an OpenTelemetry trace for OUR operations stack — not
299
+ // the account's `telemetry:` export (otel.ts), which goes to the account's
300
+ // own collector under ids of its own. Three services, one trace:
301
+ //
302
+ // foldrun-web run submitted → finished (the root)
303
+ // ├ submit submitted → queued
304
+ // └ queue.wait eligible → scheduled
305
+ // foldrun-worker drive scheduled → finished
306
+ // └ pod.start the funnel step's start → pod ready
307
+ // foldrun-runner sandbox.start pod ready → sandbox up
308
+ // │ └ startup.<phase> each phase after the pod was ready
309
+ // └ first_output sandbox up (else pod ready) → first output
310
+ //
311
+ // RECONSTRUCTED, every span: built once, by the worker, when the run ends,
312
+ // from the run record and the platform's row. The run pod cannot reach a
313
+ // collector (its namespace's egress is locked), and no tier carries a W3C
314
+ // context to the next: what joins them is the trace id, which any tier can
315
+ // derive from (account, workspace, run).
316
+ //
317
+ // Every attribute is one of OPS_SPAN_FIELDS and goes through ops-log's
318
+ // opsLine: each value in its field's shape, anything else dropped — the
319
+ // rule a log line leaving the cluster keeps (FOL-121). Span names are
320
+ // fixed. No status message, no events, no links: a failure is its class
321
+ // (`error.type`, one of ERROR_CLASSES).
322
+ /** The ops-log fields an ops span may carry — the collector's allowlist
323
+ * (foldrun-infra alloy-config.yaml) is held to this list by its test. */
324
+ export const OPS_SPAN_FIELDS = [
325
+ "runId", "tenant", "workspace", "flow", "agent", "kind", "outcome", "errorClass", "verdict",
326
+ "reason", "image", "size", "model", "usd", "step", "attempt", "phase", "ms",
327
+ ];
328
+ /** Every name an ops span may have. */
329
+ export const OPS_SPAN_NAMES = [
330
+ "run", "submit", "queue.wait", "drive", "pod.start", "sandbox.start", "first_output",
331
+ ...["services", "room", "applied", "ready", "files", "go", "shim", "system", "driver", "imports", "tools"].map((p) => `startup.${p}`),
332
+ ];
333
+ export const OPS_SERVICES = ["foldrun-web", "foldrun-worker", "foldrun-runner"];
334
+ /** An ops span's fields as OTLP attributes, `foldrun.<field>`: only
335
+ * OPS_SPAN_FIELDS, only values opsLine lets through. */
336
+ export function opsAttributes(fields) {
337
+ const allowed = new Set(OPS_SPAN_FIELDS);
338
+ const line = opsLine("info", "span", Object.fromEntries(Object.entries(fields).filter(([k]) => allowed.has(k))));
339
+ const out = [];
340
+ for (const [k, v] of Object.entries(line)) {
341
+ if (!allowed.has(k))
342
+ continue; // ops, level, event, dropped
343
+ const key = `foldrun.${k}`;
344
+ if (typeof v === "boolean")
345
+ out.push({ key, value: { boolValue: v } });
346
+ else if (typeof v === "number")
347
+ out.push({ key, value: Number.isInteger(v) ? { intValue: String(v) } : { doubleValue: v } });
348
+ else if (typeof v === "string")
349
+ out.push({ key, value: { stringValue: v } });
350
+ }
351
+ return out;
352
+ }
353
+ const hex = (s, len) => crypto.createHash("sha256").update(s).digest("hex").slice(0, len);
354
+ const nanos = (ms) => (BigInt(Math.round(ms)) * BigInt(1_000_000)).toString();
355
+ /** The trace id of a run's ops trace — under a key of its own, never the
356
+ * account's trace id (otel.ts). */
357
+ export function opsTraceId(tenant, workspace, runId) {
358
+ return hex(`foldrun-ops-trace\0${tenant}\0${workspace}\0${runId}`, 32);
359
+ }
360
+ /**
361
+ * The run's ops trace as an OTLP/HTTP JSON body, or null when the run has
362
+ * no start and end to draw between.
363
+ */
364
+ export function opsTrace(ev) {
365
+ const at = (m) => msOf(ev.at[m]);
366
+ const submitted = at("submitted");
367
+ const finished = at("finished");
368
+ if (submitted === null || finished === null || finished < submitted)
369
+ return null;
370
+ const traceId = opsTraceId(ev.tenant, ev.workspace, ev.runId);
371
+ const sid = (name) => hex(`${traceId}\0${name}`, 16);
372
+ const failed = ev.status === "failed";
373
+ const spans = [];
374
+ /** A span, kept inside its parent's interval; none where it would be
375
+ * empty or backwards. */
376
+ const push = (s, within) => {
377
+ const start = within ? Math.max(s.start, within.start) : s.start;
378
+ const end = within ? Math.min(s.end, within.end) : s.end;
379
+ if (!(end >= start))
380
+ return null;
381
+ const span = { ...s, start, end, id: sid(s.name) };
382
+ spans.push(span);
383
+ return span;
384
+ };
385
+ const who = { runId: ev.runId };
386
+ const root = push({
387
+ service: "foldrun-web",
388
+ name: "run",
389
+ parent: null,
390
+ start: submitted,
391
+ end: finished,
392
+ fields: {
393
+ ...who,
394
+ tenant: ev.tenant,
395
+ workspace: ev.workspace,
396
+ ...(ev.kind === "agent" ? { agent: ev.flow } : { flow: ev.flow }),
397
+ kind: ev.kind,
398
+ outcome: ev.status,
399
+ errorClass: ev.errorClass,
400
+ verdict: ev.slo,
401
+ reason: ev.sloReason,
402
+ image: ev.image,
403
+ size: ev.size,
404
+ model: ev.model,
405
+ usd: ev.costUsd,
406
+ step: ev.steps,
407
+ attempt: ev.attempts,
408
+ },
409
+ error: failed,
410
+ });
411
+ const queued = at("queued");
412
+ const eligible = at("eligible");
413
+ const scheduled = at("scheduled");
414
+ if (queued !== null)
415
+ push({ service: "foldrun-web", name: "submit", parent: root.id, start: submitted, end: queued, fields: who }, root);
416
+ if (eligible !== null && scheduled !== null)
417
+ push({ service: "foldrun-web", name: "queue.wait", parent: root.id, start: eligible, end: scheduled, fields: who }, root);
418
+ const drive = scheduled !== null
419
+ ? push({ service: "foldrun-worker", name: "drive", parent: root.id, start: scheduled, end: finished, fields: { ...who, outcome: ev.status, errorClass: ev.errorClass }, error: failed }, root)
420
+ : null;
421
+ const host = drive ?? root;
422
+ const origin = at("podReady") !== null ? msOf(ev.startupAt) : null;
423
+ const podReady = at("podReady");
424
+ const sandboxUp = at("sandboxUp");
425
+ const firstOutput = at("firstOutput");
426
+ const step = ev.funnelStep ?? undefined;
427
+ if (origin !== null && podReady !== null) {
428
+ push({ service: "foldrun-worker", name: "pod.start", parent: host.id, start: origin, end: podReady, fields: { ...who, step, size: ev.size, image: ev.image } }, host);
429
+ if (sandboxUp !== null) {
430
+ const sandbox = push({ service: "foldrun-runner", name: "sandbox.start", parent: host.id, start: podReady, end: sandboxUp, fields: { ...who, step, image: ev.image } }, host);
431
+ // The phases after the pod was ready, as the run page draws them
432
+ // (overlap-aware), each inside sandbox.start.
433
+ if (sandbox) {
434
+ for (const span of startupBreakdown(ev.startup)) {
435
+ const end = origin + span.at * 1000;
436
+ if (span.phase === "model" || end <= podReady || end > sandbox.end)
437
+ continue;
438
+ const name = `startup.${span.phase}`;
439
+ if (!OPS_SPAN_NAMES.includes(name))
440
+ continue;
441
+ push({ service: "foldrun-runner", name, parent: sandbox.id, start: origin + span.from * 1000, end, fields: { ...who, phase: span.phase, ms: Math.round(span.took * 1000) } }, sandbox);
442
+ }
443
+ }
444
+ }
445
+ if (firstOutput !== null) {
446
+ push({ service: "foldrun-runner", name: "first_output", parent: host.id, start: sandboxUp ?? podReady, end: firstOutput, fields: { ...who, step, model: ev.model } }, host);
447
+ }
448
+ }
449
+ const errorType = failed && ev.errorClass && ERROR_CLASSES.includes(ev.errorClass) ? ev.errorClass : null;
450
+ return {
451
+ resourceSpans: OPS_SERVICES.map((service) => ({
452
+ resource: { attributes: [{ key: "service.name", value: { stringValue: service } }, { key: "service.namespace", value: { stringValue: "foldrun" } }] },
453
+ scopeSpans: [
454
+ {
455
+ scope: { name: "foldrun-ops" },
456
+ spans: spans
457
+ .filter((s) => s.service === service)
458
+ .map((s) => ({
459
+ traceId,
460
+ spanId: s.id,
461
+ ...(s.parent ? { parentSpanId: s.parent } : {}),
462
+ name: s.name,
463
+ kind: 1,
464
+ startTimeUnixNano: nanos(s.start),
465
+ endTimeUnixNano: nanos(s.end),
466
+ attributes: [...opsAttributes(s.fields), ...(s.error && errorType ? [{ key: "error.type", value: { stringValue: errorType } }] : [])],
467
+ status: { code: s.error ? 2 : 0 },
468
+ })),
469
+ },
470
+ ],
471
+ })).filter((r) => r.scopeSpans[0].spans.length > 0),
472
+ };
473
+ }
@@ -3143,7 +3143,8 @@ mayDefer) {
3143
3143
  size,
3144
3144
  limits,
3145
3145
  // The pod's network, for the executor's own wall (the k8s tier's
3146
- // network policy): a filtered pod reaches the proxy and DNS only.
3146
+ // network policy): a filtered pod reaches the proxy only (and DNS,
3147
+ // unless the platform walls that too).
3147
3148
  network: { level: network.level, enforced: forward?.enforce === true },
3148
3149
  // A test run's state/ and storage/ changes come out under the run.
3149
3150
  divert: testRun && runId ? divertFor(runId) : undefined,
@@ -3455,6 +3456,12 @@ mayDefer) {
3455
3456
  step.startup = phases && Object.keys(phases).length
3456
3457
  ? Object.fromEntries(Object.entries(phases).map(([k, v]) => [k, secs(v)]))
3457
3458
  : null;
3459
+ // When those seconds count from (FOL-122): what places the marks on
3460
+ // the clock for the run's funnel. Beside the marks only — a resumed
3461
+ // driver reports none, and then neither.
3462
+ step.startupAt = phases && Object.keys(phases).length && typeof outcome.timing?.origin === "number"
3463
+ ? new Date(outcome.timing.origin).toISOString()
3464
+ : null;
3458
3465
  // Which reservation those seconds held — as numbers, because the bill
3459
3466
  // is per core-second and per GiB-second, and what was held must come
3460
3467
  // from the record, never from what the config says at billing time.