@foldrun/core 15.0.0 → 16.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/dist/src/a2a-publish.d.ts +7 -0
  2. package/dist/src/a2a-publish.js +15 -1
  3. package/dist/src/a2a-reach.d.ts +156 -0
  4. package/dist/src/a2a-reach.js +446 -0
  5. package/dist/src/browse-egress.d.ts +1 -1
  6. package/dist/src/browse-egress.js +7 -6
  7. package/dist/src/capture.js +2 -1
  8. package/dist/src/env-names.d.ts +12 -0
  9. package/dist/src/env-names.js +49 -0
  10. package/dist/src/failure.d.ts +92 -0
  11. package/dist/src/failure.js +294 -0
  12. package/dist/src/frontmatter-fields.js +1 -1
  13. package/dist/src/install-helper.js +10 -5
  14. package/dist/src/mail.js +2 -1
  15. package/dist/src/network.js +1 -1
  16. package/dist/src/notify.js +12 -7
  17. package/dist/src/ops-log.d.ts +55 -0
  18. package/dist/src/ops-log.js +393 -0
  19. package/dist/src/otel.d.ts +16 -1
  20. package/dist/src/otel.js +121 -5
  21. package/dist/src/run-container.d.ts +55 -3
  22. package/dist/src/run-container.js +109 -17
  23. package/dist/src/run-event.d.ts +179 -0
  24. package/dist/src/run-event.js +473 -0
  25. package/dist/src/runner.js +14 -5
  26. package/dist/src/runtime.d.ts +113 -16
  27. package/dist/src/runtime.js +528 -44
  28. package/dist/src/scan.js +80 -18
  29. package/dist/src/secrets.js +4 -3
  30. package/dist/src/starter.js +1 -1
  31. package/dist/src/step-exec.d.ts +4 -2
  32. package/dist/src/step-exec.js +10 -4
  33. package/dist/src/storage.js +2 -1
  34. package/dist/src/store.d.ts +25 -3
  35. package/dist/src/store.js +40 -10
  36. package/dist/src/triggers.js +6 -5
  37. package/dist/src/webhook.js +3 -2
  38. package/package.json +2 -1
  39. package/src/a2a-publish.ts +19 -1
  40. package/src/a2a-reach.ts +503 -0
  41. package/src/browse-egress.ts +8 -7
  42. package/src/capture.ts +2 -1
  43. package/src/env-names.ts +53 -0
  44. package/src/failure.ts +368 -0
  45. package/src/frontmatter-fields.ts +1 -1
  46. package/src/install-helper.ts +10 -5
  47. package/src/mail.ts +2 -1
  48. package/src/network.ts +1 -1
  49. package/src/notify.ts +12 -9
  50. package/src/ops-log.ts +403 -0
  51. package/src/otel.ts +122 -7
  52. package/src/run-container.ts +112 -21
  53. package/src/run-event.ts +563 -0
  54. package/src/runner.ts +14 -5
  55. package/src/runtime.ts +543 -45
  56. package/src/scan.ts +91 -20
  57. package/src/secrets.ts +4 -5
  58. package/src/starter.ts +1 -1
  59. package/src/step-exec.ts +10 -4
  60. package/src/storage.ts +2 -1
  61. package/src/store.ts +59 -11
  62. package/src/triggers.ts +6 -5
  63. package/src/webhook.ts +3 -2
@@ -0,0 +1,563 @@
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
+
38
+ import crypto from "node:crypto";
39
+ import { isSplicedRecord, runFailure, type RunRecord, type StepRecord } from "./store.ts";
40
+ import { ERROR_CLASSES, opsLine, type ErrorClass, type OpsFields } from "./ops-log.ts";
41
+ import { explainFailure, type FailureExplained, type FailureKind, type LimitScope } from "./failure.ts";
42
+ import { startupBreakdown, type StartupPhase } from "./startup.ts";
43
+
44
+ /** The funnel's marks, in order. */
45
+ export const FUNNEL = ["submitted", "queued", "eligible", "claimed", "scheduled", "podReady", "sandboxUp", "firstOutput", "finished"] as const;
46
+ export type FunnelMark = (typeof FUNNEL)[number];
47
+
48
+ /** Whether a finished run counts toward the success-rate SLI: `good`
49
+ * (completed), `bad` (failed, and the failure is ours, a provider's or the
50
+ * cluster's), or `excluded` (the customer's own code, settings or decision
51
+ * — sloOutcome). Null while the run is not finished. */
52
+ export type SloOutcome = "good" | "bad" | "excluded";
53
+
54
+ /** Why a failed run is excluded from the success rate, or why it is bad. */
55
+ export const SLO_REASONS = [
56
+ "completed",
57
+ // excluded
58
+ "cancelled", "customer_code", "customer_check", "customer_budget", "customer_security", "customer_network", "customer_credential", "customer_limit",
59
+ // bad
60
+ "platform", "model", "capacity", "deadline", "unexplained",
61
+ ] as const;
62
+ export type SloReason = (typeof SLO_REASONS)[number];
63
+
64
+ /** The SLO rule's version, on every row: a row says which rule judged it,
65
+ * so a change to the rule never silently rewrites history's meaning. */
66
+ export const SLO_RULES_VERSION = 1;
67
+
68
+ export interface RunWideEvent {
69
+ runId: string;
70
+ tenant: string;
71
+ workspace: string;
72
+ /** The flow's name, or the agent's for a direct agent run. */
73
+ flow: string;
74
+ kind: "flow" | "agent";
75
+ test: boolean;
76
+ status: RunRecord["status"];
77
+ errorClass: ErrorClass | null;
78
+ failureKind: FailureKind | null;
79
+ failureScope: LimitScope | null;
80
+ slo: SloOutcome | null;
81
+ sloReason: SloReason | null;
82
+ rulesVersion: number;
83
+ /** The funnel step's runner image, model (its first model call's, else
84
+ * the step's own setting) and size class. */
85
+ image: "full" | "slim" | null;
86
+ model: string | null;
87
+ size: string | null;
88
+ /** ISO instants; null where the run did not reach the mark, or the
89
+ * record does not say. */
90
+ at: Record<FunnelMark, string | null>;
91
+ /** The earliest model output of any step this run executed — with
92
+ * parallel steps, possibly not the funnel step's. */
93
+ earliestOutput: string | null;
94
+ /** The funnel step's index; its start-up marks, in seconds from `startupAt`
95
+ * (STARTUP_PHASES); and whether that origin is the executor's own
96
+ * (`exact`) or the attempt's start (`estimated`). */
97
+ funnelStep: number | null;
98
+ startup: Record<string, number> | null;
99
+ startupAt: string | null;
100
+ origin: "exact" | "estimated" | null;
101
+ /** Steps in the record (rescues and sub-agents included), how many ran in
102
+ * a sandbox, and attempts across the steps this run executed. */
103
+ steps: number;
104
+ sandboxedSteps: number;
105
+ attempts: number;
106
+ /** Summed over every attempt of every step this run executed. */
107
+ costUsd: number;
108
+ computeSecs: number;
109
+ /** The funnel step's sandbox start-up (step.startupSecs). */
110
+ startupSecs: number | null;
111
+ /** The largest any one step's sandbox held, and the most any one used —
112
+ * not the run's capacity (parallel steps add up), and the limit and the
113
+ * use may be two different steps'. Each step's last attempt. Disk used
114
+ * is not measured in the sandbox today: null, never estimated. CPU busy
115
+ * and throttled seconds are summed. */
116
+ cpuLimit: number | null;
117
+ cpuBusySecs: number | null;
118
+ cpuThrottledSecs: number | null;
119
+ memLimitGiB: number | null;
120
+ memPeakBytes: number | null;
121
+ diskLimitGiB: number | null;
122
+ diskUsedBytes: number | null;
123
+ }
124
+
125
+ /** What the queue knows that the record does not (the platform's row). */
126
+ export interface QueueFacts {
127
+ queuedAt?: string | null;
128
+ eligibleAt?: string | null;
129
+ claimedAt?: string | null;
130
+ }
131
+
132
+ const iso = (ms: number | null): string | null => (ms === null || !Number.isFinite(ms) ? null : new Date(ms).toISOString());
133
+ const msOf = (s: string | null | undefined): number | null => {
134
+ if (!s) return null;
135
+ const v = Date.parse(s);
136
+ return Number.isFinite(v) ? v : null;
137
+ };
138
+ const num = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) ? v : null);
139
+
140
+ /** A step this run executed itself: not carried from an earlier run, not a
141
+ * rescue or a sub-agent spliced in. */
142
+ const ownStep = (s: StepRecord) => !s.carriedFrom && !isSplicedRecord(s);
143
+ const hasMarks = (s: StepRecord) => !!s.startup && typeof s.startup === "object" && Object.keys(s.startup).length > 0;
144
+
145
+ /** When the step's marks count from, and whether that is the executor's
146
+ * own origin or the attempt's start. */
147
+ function originOf(step: StepRecord): { ms: number; exact: boolean } | null {
148
+ const exact = msOf(step.startupAt);
149
+ if (exact !== null) return { ms: exact, exact: true };
150
+ const est = msOf(step.tries?.at(-1)?.startedAt) ?? msOf(step.startedAt);
151
+ return est === null ? null : { ms: est, exact: false };
152
+ }
153
+
154
+ /** The step's own model: its first call's, else what the step asked for. */
155
+ function modelOf(step: StepRecord): string | null {
156
+ const call = step.calls?.find((c) => typeof c.model === "string" && c.model);
157
+ return call?.model ?? (typeof step.model === "string" && step.model ? step.model : null);
158
+ }
159
+
160
+ /** The step that failed the run, by the runner's rule (otel.ts uses the
161
+ * same): failed, not optional, not carried, not spliced; else any failed. */
162
+ const failingStep = (run: RunRecord) =>
163
+ run.steps.find((s) => s.status === "failed" && !s.optional && ownStep(s)) ?? run.steps.find((s) => s.status === "failed");
164
+
165
+ /**
166
+ * Why a failed run failed, for the wide event. runFailure (store.ts, the
167
+ * customer's view) reads the first failed step, an optional one included,
168
+ * and a stop only when no step failed; the funnel wants the run's own
169
+ * terminal cause: a stop first, then the step that failed the run.
170
+ */
171
+ export function terminalFailure(run: RunRecord): (FailureExplained & { text: string; step: StepRecord | null }) | null {
172
+ if (run.status !== "failed") return null;
173
+ if (run.stopRequested) {
174
+ const text = `stopped by ${run.stoppedBy ?? "a person"}`;
175
+ return { ...explainFailure(text, null), text, step: null };
176
+ }
177
+ const step = failingStep(run);
178
+ if (step) {
179
+ const text = step.events.filter((e) => e.type === "error").at(-1)?.text ?? "failed without an error event";
180
+ return { ...explainFailure(text, step), text, step };
181
+ }
182
+ const f = runFailure(run);
183
+ return f ? { ...f, text: f.reason, step: null } : null;
184
+ }
185
+
186
+ /** The scopes of a limit the customer sets or buys: their step's own
187
+ * (timeout:, size:, resources:), their flow's or workspace's pool, their
188
+ * plan's. The install's and the largest node's are ours. */
189
+ const CUSTOMER_SCOPES: readonly LimitScope[] = ["step", "run", "workspace", "account"];
190
+
191
+ /**
192
+ * Does this run count against the platform's success rate, and why?
193
+ *
194
+ * Excluded — the customer's own code, settings or decision:
195
+ * cancelled a person or a caller stopped it
196
+ * customer_code their script, tool or hook failed
197
+ * customer_check their verify:, output: json or schema: did not hold
198
+ * customer_budget their budget: ran out
199
+ * customer_security a platform security control stopped what their agent did
200
+ * customer_network the error IS the proxy refusing a site off their
201
+ * network: list (a refusal merely on the trail of a
202
+ * step that failed for another reason does not count)
203
+ * customer_credential their own model key was refused (supply `own`)
204
+ * customer_limit a limit whose scope is theirs (CUSTOMER_SCOPES)
205
+ * Bad — everything else: platform (ours, or a node short of memory or disk
206
+ * evicting it), model (a provider failing, the platform's key refused),
207
+ * capacity (the install's or the node's limit), deadline (a time limit with
208
+ * no scope of theirs), unexplained.
209
+ */
210
+ export function sloOutcome(run: RunRecord, failure = terminalFailure(run)): { slo: SloOutcome; reason: SloReason } | null {
211
+ if (run.status === "completed") return { slo: "good", reason: "completed" };
212
+ if (run.status !== "failed") return null;
213
+ const excluded = (reason: SloReason) => ({ slo: "excluded" as const, reason });
214
+ const bad = (reason: SloReason) => ({ slo: "bad" as const, reason });
215
+ if (!failure) return bad("unexplained");
216
+ switch (failure.kind) {
217
+ case "stopped":
218
+ return excluded("cancelled");
219
+ case "code":
220
+ return excluded("customer_code");
221
+ case "check":
222
+ return excluded("customer_check");
223
+ case "budget":
224
+ return excluded("customer_budget");
225
+ case "security":
226
+ return excluded("customer_security");
227
+ case "network": {
228
+ // explainFailure reads a refusal on the step's trail before a code
229
+ // error, for the customer's message. Here the cause has to be the
230
+ // refusal itself: the same step without its trail's refusals, and
231
+ // what that says is the cause.
232
+ const step = failure.step;
233
+ 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);
234
+ if (bare.kind === "network") return excluded("customer_network");
235
+ return sloOutcome(run, { ...bare, text: failure.text, step });
236
+ }
237
+ case "credential":
238
+ return failure.step?.supply === "own" ? excluded("customer_credential") : bad("model");
239
+ case "memory":
240
+ case "cpu":
241
+ case "disk":
242
+ case "timeout":
243
+ if (failure.scope && CUSTOMER_SCOPES.includes(failure.scope)) return excluded("customer_limit");
244
+ if (failure.scope) return bad("capacity");
245
+ return failure.kind === "timeout" ? bad("deadline") : bad("platform");
246
+ case "model":
247
+ return bad("model");
248
+ case "platform":
249
+ return bad("platform");
250
+ default:
251
+ return bad("unexplained");
252
+ }
253
+ }
254
+
255
+ /** The run's wide event. Pure: the record, and what the queue adds. */
256
+ export function runWideEvent(tenant: string, workspace: string, run: RunRecord, queue: QueueFacts = {}): RunWideEvent {
257
+ // The funnel step: of the steps this run executed in a sandbox, the one
258
+ // whose start-up began first (parallel steps start in any order).
259
+ let fi: number | null = null;
260
+ let fo: { ms: number; exact: boolean } | null = null;
261
+ let earliestOutput: number | null = null;
262
+ let sandboxed = 0;
263
+ run.steps.forEach((s, i) => {
264
+ if (!ownStep(s) || !hasMarks(s)) return;
265
+ sandboxed += 1;
266
+ const o = originOf(s);
267
+ if (!o) return;
268
+ if (!fo || o.ms < fo.ms) {
269
+ fi = i;
270
+ fo = o;
271
+ }
272
+ const m = num(s.startup?.model);
273
+ if (m !== null && (earliestOutput === null || o.ms + m * 1000 < earliestOutput)) earliestOutput = o.ms + m * 1000;
274
+ });
275
+ const fs = fi === null ? null : run.steps[fi]!;
276
+ const origin = fo as { ms: number; exact: boolean } | null;
277
+ const mark = (p: StartupPhase): number | null => {
278
+ const v = num(fs?.startup?.[p]);
279
+ return v === null || !origin ? null : origin.ms + v * 1000;
280
+ };
281
+
282
+ const submitted = msOf(run.startedAt);
283
+ const queued = msOf(queue.queuedAt) ?? submitted;
284
+ const eligible = msOf(queue.eligibleAt) ?? queued;
285
+ const finished = run.status === "completed" || run.status === "failed" ? msOf(run.finishedAt) : null;
286
+ const failure = terminalFailure(run);
287
+ const slo = sloOutcome(run, failure);
288
+
289
+ let attempts = 0;
290
+ let cost = 0;
291
+ let compute = 0;
292
+ let cpuLimit: number | null = null;
293
+ let memLimit: number | null = null;
294
+ let diskLimit: number | null = null;
295
+ let peak: number | null = null;
296
+ let busy: number | null = null;
297
+ let throttled: number | null = null;
298
+ const max = (a: number | null, b: unknown) => (num(b) === null ? a : a === null ? (b as number) : Math.max(a, b as number));
299
+ const add = (a: number | null, b: unknown) => (num(b) === null ? a : (a ?? 0) + (b as number));
300
+ for (const s of run.steps) {
301
+ // A step carried from an earlier run ran (and was billed) there.
302
+ if (s.carriedFrom) continue;
303
+ attempts += typeof s.attempts === "number" ? s.attempts : (s.tries?.length ?? 0);
304
+ cost += num(s.costUsd) ?? 0;
305
+ compute += num(s.computeSecs) ?? 0;
306
+ cpuLimit = max(cpuLimit, s.reserved?.cpus);
307
+ memLimit = max(memLimit, s.reserved?.memGiB);
308
+ diskLimit = max(diskLimit, s.reserved?.diskGiB);
309
+ peak = max(peak, s.actual?.peakMemBytes);
310
+ busy = add(busy, s.actual?.busyCpuSecs);
311
+ throttled = add(throttled, s.actual?.throttledSecs);
312
+ }
313
+
314
+ const adhoc = run.flow.startsWith("adhoc:");
315
+ return {
316
+ runId: run.id,
317
+ tenant,
318
+ workspace,
319
+ flow: adhoc ? run.flow.slice("adhoc:".length) : run.flow,
320
+ kind: adhoc ? "agent" : "flow",
321
+ test: run.test === true,
322
+ status: run.status,
323
+ errorClass: run.status === "failed" ? (failure?.class ?? "platform_error") : null,
324
+ failureKind: failure?.kind ?? null,
325
+ failureScope: failure?.scope ?? null,
326
+ slo: slo?.slo ?? null,
327
+ sloReason: slo?.reason ?? null,
328
+ rulesVersion: SLO_RULES_VERSION,
329
+ image: fs?.image?.variant ?? null,
330
+ model: fs ? modelOf(fs) : null,
331
+ size: fs?.size ?? null,
332
+ at: {
333
+ submitted: iso(submitted),
334
+ queued: iso(queued),
335
+ eligible: iso(eligible),
336
+ claimed: iso(msOf(queue.claimedAt)),
337
+ scheduled: iso(msOf(run.drivenAt)),
338
+ podReady: iso(mark("ready")),
339
+ sandboxUp: iso(mark("tools")),
340
+ firstOutput: iso(mark("model")),
341
+ finished: iso(finished),
342
+ },
343
+ earliestOutput: iso(earliestOutput),
344
+ funnelStep: fi,
345
+ startup: fs?.startup ? { ...fs.startup } : null,
346
+ startupAt: origin ? iso(origin.ms) : null,
347
+ origin: origin ? (origin.exact ? "exact" : "estimated") : null,
348
+ steps: run.steps.length,
349
+ sandboxedSteps: sandboxed,
350
+ attempts,
351
+ costUsd: Math.round(cost * 1e6) / 1e6,
352
+ computeSecs: Math.round(compute * 1000) / 1000,
353
+ startupSecs: num(fs?.startupSecs),
354
+ cpuLimit,
355
+ cpuBusySecs: busy,
356
+ cpuThrottledSecs: throttled,
357
+ memLimitGiB: memLimit,
358
+ memPeakBytes: peak,
359
+ diskLimitGiB: diskLimit,
360
+ diskUsedBytes: null,
361
+ };
362
+ }
363
+
364
+ /** Seconds between two marks of an event, or null when either is missing
365
+ * (or the later reads earlier: two clocks). */
366
+ export function funnelSecs(ev: Pick<RunWideEvent, "at">, from: FunnelMark, to: FunnelMark): number | null {
367
+ const a = msOf(ev.at[from]);
368
+ const b = msOf(ev.at[to]);
369
+ if (a === null || b === null || b < a) return null;
370
+ return (b - a) / 1000;
371
+ }
372
+
373
+ // ------------------------------------------------------------- ops trace
374
+ //
375
+ // The run's funnel as an OpenTelemetry trace for OUR operations stack — not
376
+ // the account's `telemetry:` export (otel.ts), which goes to the account's
377
+ // own collector under ids of its own. Three services, one trace:
378
+ //
379
+ // foldrun-web run submitted → finished (the root)
380
+ // ├ submit submitted → queued
381
+ // └ queue.wait eligible → scheduled
382
+ // foldrun-worker drive scheduled → finished
383
+ // └ pod.start the funnel step's start → pod ready
384
+ // foldrun-runner sandbox.start pod ready → sandbox up
385
+ // │ └ startup.<phase> each phase after the pod was ready
386
+ // └ first_output sandbox up (else pod ready) → first output
387
+ //
388
+ // RECONSTRUCTED, every span: built once, by the worker, when the run ends,
389
+ // from the run record and the platform's row. The run pod cannot reach a
390
+ // collector (its namespace's egress is locked), and no tier carries a W3C
391
+ // context to the next: what joins them is the trace id, which any tier can
392
+ // derive from (account, workspace, run).
393
+ //
394
+ // Every attribute is one of OPS_SPAN_FIELDS and goes through ops-log's
395
+ // opsLine: each value in its field's shape, anything else dropped — the
396
+ // rule a log line leaving the cluster keeps (FOL-121). Span names are
397
+ // fixed. No status message, no events, no links: a failure is its class
398
+ // (`error.type`, one of ERROR_CLASSES).
399
+
400
+ /** The ops-log fields an ops span may carry — the collector's allowlist
401
+ * (foldrun-infra alloy-config.yaml) is held to this list by its test. */
402
+ export const OPS_SPAN_FIELDS = [
403
+ "runId", "tenant", "workspace", "flow", "agent", "kind", "outcome", "errorClass", "verdict",
404
+ "reason", "image", "size", "model", "usd", "step", "attempt", "phase", "ms",
405
+ ] as const;
406
+
407
+ /** Every name an ops span may have. */
408
+ export const OPS_SPAN_NAMES = [
409
+ "run", "submit", "queue.wait", "drive", "pod.start", "sandbox.start", "first_output",
410
+ ...(["services", "room", "applied", "ready", "files", "go", "shim", "system", "driver", "imports", "tools"] as const).map((p) => `startup.${p}` as const),
411
+ ] as const;
412
+
413
+ export const OPS_SERVICES = ["foldrun-web", "foldrun-worker", "foldrun-runner"] as const;
414
+
415
+ type Attr = { key: string; value: { stringValue: string } | { intValue: string } | { doubleValue: number } | { boolValue: boolean } };
416
+
417
+ /** An ops span's fields as OTLP attributes, `foldrun.<field>`: only
418
+ * OPS_SPAN_FIELDS, only values opsLine lets through. */
419
+ export function opsAttributes(fields: OpsFields): Attr[] {
420
+ const allowed = new Set<string>(OPS_SPAN_FIELDS);
421
+ const line = opsLine("info", "span", Object.fromEntries(Object.entries(fields).filter(([k]) => allowed.has(k))));
422
+ const out: Attr[] = [];
423
+ for (const [k, v] of Object.entries(line)) {
424
+ if (!allowed.has(k)) continue; // ops, level, event, dropped
425
+ const key = `foldrun.${k}`;
426
+ if (typeof v === "boolean") out.push({ key, value: { boolValue: v } });
427
+ else if (typeof v === "number") out.push({ key, value: Number.isInteger(v) ? { intValue: String(v) } : { doubleValue: v } });
428
+ else if (typeof v === "string") out.push({ key, value: { stringValue: v } });
429
+ }
430
+ return out;
431
+ }
432
+
433
+ const hex = (s: string, len: number) => crypto.createHash("sha256").update(s).digest("hex").slice(0, len);
434
+ const nanos = (ms: number) => (BigInt(Math.round(ms)) * BigInt(1_000_000)).toString();
435
+
436
+ type OpsSpanName = (typeof OPS_SPAN_NAMES)[number];
437
+ interface OpsSpan {
438
+ service: (typeof OPS_SERVICES)[number];
439
+ name: OpsSpanName;
440
+ id: string;
441
+ parent: string | null;
442
+ start: number;
443
+ end: number;
444
+ fields: OpsFields;
445
+ error?: boolean;
446
+ }
447
+
448
+ /** The trace id of a run's ops trace — under a key of its own, never the
449
+ * account's trace id (otel.ts). */
450
+ export function opsTraceId(tenant: string, workspace: string, runId: string): string {
451
+ return hex(`foldrun-ops-trace\0${tenant}\0${workspace}\0${runId}`, 32);
452
+ }
453
+
454
+ /**
455
+ * The run's ops trace as an OTLP/HTTP JSON body, or null when the run has
456
+ * no start and end to draw between.
457
+ */
458
+ export function opsTrace(ev: RunWideEvent) {
459
+ const at = (m: FunnelMark) => msOf(ev.at[m]);
460
+ const submitted = at("submitted");
461
+ const finished = at("finished");
462
+ if (submitted === null || finished === null || finished < submitted) return null;
463
+ const traceId = opsTraceId(ev.tenant, ev.workspace, ev.runId);
464
+ const sid = (name: string) => hex(`${traceId}\0${name}`, 16);
465
+ const failed = ev.status === "failed";
466
+ const spans: OpsSpan[] = [];
467
+ /** A span, kept inside its parent's interval; none where it would be
468
+ * empty or backwards. */
469
+ const push = (s: Omit<OpsSpan, "id">, within?: { start: number; end: number }) => {
470
+ const start = within ? Math.max(s.start, within.start) : s.start;
471
+ const end = within ? Math.min(s.end, within.end) : s.end;
472
+ if (!(end >= start)) return null;
473
+ const span = { ...s, start, end, id: sid(s.name) };
474
+ spans.push(span);
475
+ return span;
476
+ };
477
+ const who: OpsFields = { runId: ev.runId };
478
+ const root = push({
479
+ service: "foldrun-web",
480
+ name: "run",
481
+ parent: null,
482
+ start: submitted,
483
+ end: finished,
484
+ fields: {
485
+ ...who,
486
+ tenant: ev.tenant,
487
+ workspace: ev.workspace,
488
+ ...(ev.kind === "agent" ? { agent: ev.flow } : { flow: ev.flow }),
489
+ kind: ev.kind,
490
+ outcome: ev.status,
491
+ errorClass: ev.errorClass,
492
+ verdict: ev.slo,
493
+ reason: ev.sloReason,
494
+ image: ev.image,
495
+ size: ev.size,
496
+ model: ev.model,
497
+ usd: ev.costUsd,
498
+ step: ev.steps,
499
+ attempt: ev.attempts,
500
+ },
501
+ error: failed,
502
+ })!;
503
+ const queued = at("queued");
504
+ const eligible = at("eligible");
505
+ const scheduled = at("scheduled");
506
+ if (queued !== null) push({ service: "foldrun-web", name: "submit", parent: root.id, start: submitted, end: queued, fields: who }, root);
507
+ if (eligible !== null && scheduled !== null) push({ service: "foldrun-web", name: "queue.wait", parent: root.id, start: eligible, end: scheduled, fields: who }, root);
508
+ const drive = scheduled !== null
509
+ ? push({ service: "foldrun-worker", name: "drive", parent: root.id, start: scheduled, end: finished, fields: { ...who, outcome: ev.status, errorClass: ev.errorClass }, error: failed }, root)
510
+ : null;
511
+ const host = drive ?? root;
512
+
513
+ const origin = at("podReady") !== null ? msOf(ev.startupAt) : null;
514
+ const podReady = at("podReady");
515
+ const sandboxUp = at("sandboxUp");
516
+ const firstOutput = at("firstOutput");
517
+ const step = ev.funnelStep ?? undefined;
518
+ if (origin !== null && podReady !== null) {
519
+ push({ service: "foldrun-worker", name: "pod.start", parent: host.id, start: origin, end: podReady, fields: { ...who, step, size: ev.size, image: ev.image } }, host);
520
+ if (sandboxUp !== null) {
521
+ const sandbox = push({ service: "foldrun-runner", name: "sandbox.start", parent: host.id, start: podReady, end: sandboxUp, fields: { ...who, step, image: ev.image } }, host);
522
+ // The phases after the pod was ready, as the run page draws them
523
+ // (overlap-aware), each inside sandbox.start.
524
+ if (sandbox) {
525
+ for (const span of startupBreakdown(ev.startup)) {
526
+ const end = origin + span.at * 1000;
527
+ if (span.phase === "model" || end <= podReady || end > sandbox.end) continue;
528
+ const name = `startup.${span.phase}` as OpsSpanName;
529
+ if (!(OPS_SPAN_NAMES as readonly string[]).includes(name)) continue;
530
+ 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);
531
+ }
532
+ }
533
+ }
534
+ if (firstOutput !== null) {
535
+ push({ service: "foldrun-runner", name: "first_output", parent: host.id, start: sandboxUp ?? podReady, end: firstOutput, fields: { ...who, step, model: ev.model } }, host);
536
+ }
537
+ }
538
+
539
+ const errorType = failed && ev.errorClass && (ERROR_CLASSES as readonly string[]).includes(ev.errorClass) ? ev.errorClass : null;
540
+ return {
541
+ resourceSpans: OPS_SERVICES.map((service) => ({
542
+ resource: { attributes: [{ key: "service.name", value: { stringValue: service } }, { key: "service.namespace", value: { stringValue: "foldrun" } }] },
543
+ scopeSpans: [
544
+ {
545
+ scope: { name: "foldrun-ops" },
546
+ spans: spans
547
+ .filter((s) => s.service === service)
548
+ .map((s) => ({
549
+ traceId,
550
+ spanId: s.id,
551
+ ...(s.parent ? { parentSpanId: s.parent } : {}),
552
+ name: s.name,
553
+ kind: 1,
554
+ startTimeUnixNano: nanos(s.start),
555
+ endTimeUnixNano: nanos(s.end),
556
+ attributes: [...opsAttributes(s.fields), ...(s.error && errorType ? [{ key: "error.type", value: { stringValue: errorType } }] : [])],
557
+ status: { code: s.error ? 2 : 0 },
558
+ })),
559
+ },
560
+ ],
561
+ })).filter((r) => r.scopeSpans[0]!.spans.length > 0),
562
+ };
563
+ }
package/src/runner.ts CHANGED
@@ -3,6 +3,7 @@
3
3
  // fail without failing the flow. A direct agent run is a one-step ad-hoc
4
4
  // flow, so there is a single execution path.
5
5
 
6
+ import { opsLog, opsError } from "./ops-log.ts";
6
7
  import { globMatch } from "./bounded-match.ts";
7
8
  import { latestRevisionId } from "./history.ts";
8
9
  import { recordCallIo, redactionsFor } from "./capture.ts";
@@ -2428,7 +2429,7 @@ async function runStep(
2428
2429
  const why = await platform.checkUntrustedUrl(r.card);
2429
2430
  if (why) {
2430
2431
  cardProblems.set(r.name, why);
2431
- console.warn(`[a2a] remotes: ${r.name} refused for ${tenant}/${path.basename(workspaceRootOf(agentDir))} (${step.agent}): ${why}`);
2432
+ opsLog("warn", "a2a.remote_refused", { tenant, workspace: path.basename(workspaceRootOf(agentDir)), agent: step.agent, tool: r.name });
2432
2433
  }
2433
2434
  }
2434
2435
  const stepRemotes: RemoteSpec[] = remotes.map((r) => {
@@ -3356,7 +3357,8 @@ async function runStep(
3356
3357
  size,
3357
3358
  limits,
3358
3359
  // The pod's network, for the executor's own wall (the k8s tier's
3359
- // network policy): a filtered pod reaches the proxy and DNS only.
3360
+ // network policy): a filtered pod reaches the proxy only (and DNS,
3361
+ // unless the platform walls that too).
3360
3362
  network: { level: network.level, enforced: forward?.enforce === true },
3361
3363
  // A test run's state/ and storage/ changes come out under the run.
3362
3364
  divert: testRun && runId ? divertFor(runId) : undefined,
@@ -3662,6 +3664,12 @@ async function runStep(
3662
3664
  step.startup = phases && Object.keys(phases).length
3663
3665
  ? Object.fromEntries(Object.entries(phases).map(([k, v]) => [k, secs(v)]))
3664
3666
  : null;
3667
+ // When those seconds count from (FOL-122): what places the marks on
3668
+ // the clock for the run's funnel. Beside the marks only — a resumed
3669
+ // driver reports none, and then neither.
3670
+ step.startupAt = phases && Object.keys(phases).length && typeof outcome.timing?.origin === "number"
3671
+ ? new Date(outcome.timing.origin).toISOString()
3672
+ : null;
3665
3673
  // Which reservation those seconds held — as numbers, because the bill
3666
3674
  // is per core-second and per GiB-second, and what was held must come
3667
3675
  // from the record, never from what the config says at billing time.
@@ -4287,7 +4295,8 @@ export function platformModelCredential(env: NodeJS.ProcessEnv = process.env): s
4287
4295
  // thing an operator needs to know about before the next step fails.
4288
4296
  if (!credentialFileWarned) {
4289
4297
  credentialFileWarned = true;
4290
- console.warn(`[model] FOLDRUN_MODEL_KEY_FILE=${file} could not be read; falling back to the environment`);
4298
+ // FOLDRUN_MODEL_KEY_FILE could not be read: the environment's key is used.
4299
+ opsLog("warn", "model.key_file_unreadable", { outcome: "environment" });
4291
4300
  }
4292
4301
  }
4293
4302
  }
@@ -6409,7 +6418,7 @@ export function reconcileRuns(tenant: string, now = Date.now(), live?: ReadonlyS
6409
6418
  const after = readRun(tenant, workspace.name, run.id);
6410
6419
  if (onEnd && after && (after.status === "completed" || after.status === "failed")) return onEnd(tenant, workspace.name, run.id);
6411
6420
  })
6412
- .catch((err) => console.error(`[foldrun] reconcile: ${tenant}/${workspace.name}/${run.id} after resume:`, err));
6421
+ .catch((err) => opsError("reconcile.after_resume_failed", err, { tenant, workspace: workspace.name, runId: run.id }));
6413
6422
  closed.push({
6414
6423
  runId: run.id,
6415
6424
  tenant,
@@ -6457,7 +6466,7 @@ export function reconcileRuns(tenant: string, now = Date.now(), live?: ReadonlyS
6457
6466
  if (onEnd) {
6458
6467
  void Promise.resolve()
6459
6468
  .then(() => onEnd(tenant, workspace.name, run.id))
6460
- .catch((err) => console.error(`[foldrun] reconcile: ${tenant}/${workspace.name}/${run.id} after close:`, err));
6469
+ .catch((err) => opsError("reconcile.after_close_failed", err, { tenant, workspace: workspace.name, runId: run.id }));
6461
6470
  }
6462
6471
  }
6463
6472
  }