@foldrun/core 15.1.0 → 17.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 (52) 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/egress.d.ts +9 -0
  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/network.js +1 -1
  15. package/dist/src/ops-log.js +4 -0
  16. package/dist/src/otel.d.ts +16 -1
  17. package/dist/src/otel.js +121 -5
  18. package/dist/src/platform.d.ts +8 -0
  19. package/dist/src/run-container.d.ts +88 -4
  20. package/dist/src/run-container.js +215 -26
  21. package/dist/src/run-event.d.ts +179 -0
  22. package/dist/src/run-event.js +473 -0
  23. package/dist/src/runner.js +35 -1
  24. package/dist/src/runtime.d.ts +116 -16
  25. package/dist/src/runtime.js +531 -44
  26. package/dist/src/scan.js +80 -18
  27. package/dist/src/search-egress.d.ts +58 -0
  28. package/dist/src/search-egress.js +88 -0
  29. package/dist/src/starter.js +4 -1
  30. package/dist/src/store.d.ts +34 -3
  31. package/dist/src/store.js +46 -10
  32. package/package.json +2 -1
  33. package/src/a2a-publish.ts +19 -1
  34. package/src/a2a-reach.ts +503 -0
  35. package/src/browse-egress.ts +8 -7
  36. package/src/egress.ts +7 -0
  37. package/src/env-names.ts +53 -0
  38. package/src/failure.ts +368 -0
  39. package/src/frontmatter-fields.ts +1 -1
  40. package/src/install-helper.ts +10 -5
  41. package/src/network.ts +1 -1
  42. package/src/ops-log.ts +4 -0
  43. package/src/otel.ts +122 -7
  44. package/src/platform.ts +8 -0
  45. package/src/run-container.ts +228 -29
  46. package/src/run-event.ts +563 -0
  47. package/src/runner.ts +32 -1
  48. package/src/runtime.ts +546 -45
  49. package/src/scan.ts +91 -20
  50. package/src/search-egress.ts +116 -0
  51. package/src/starter.ts +4 -1
  52. package/src/store.ts +75 -12
@@ -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
+ }
@@ -50,6 +50,7 @@ import { loadCatalog, checkModel, clampEffort, catalogCost, findModel, tokenPric
50
50
  import { resolveSecrets, getSecret, materializeSecrets, secretSites, isClientCertValue, clientCertOf, withoutHeldCerts, isIdentityValue, identityOf } from "./secrets.js";
51
51
  import { resolveNetwork, networkLine, networkEnforceWanted, proxyEnv, siteCovers, EGRESS_CA_ENV } from "./network.js";
52
52
  import { BROWSER_CONFINED_ENV, browseNetworkLine, browseVerdict } from "./browse-egress.js";
53
+ import { SEARCH_DOOR_ENV, searchDoorWanted, searchProvided } from "./search-egress.js";
53
54
  import { materializeFileSecrets, cleanupFileSecrets } from "./secret-files.js";
54
55
  import { buildApiTools, secretsUsedByApi } from "./api-tools.js";
55
56
  import { buildA2ATools } from "./a2a-tools.js";
@@ -2885,6 +2886,29 @@ mayDefer) {
2885
2886
  // A browsing step on an install with the door says whether it is held
2886
2887
  // to its list, and which tier its browser falls in (browse-egress.ts).
2887
2888
  push("info", browse ? browseNetworkLine(network, clockEnv.FOLDRUN_BROWSER_VENDOR, { hosted: browse.kind === "hosted" }) : networkLine(network, forward ? forward.enforce === true : null));
2889
+ // Web search under a held list (FOL-128, search-egress.ts): the
2890
+ // account's engine through the proxy's search door, for the actions
2891
+ // our engine answers — decided here, from this step's own config and
2892
+ // the lease's effective enforce, and carried on the grant, which the
2893
+ // pod cannot write. Only where the executor walls such a step (the
2894
+ // others reach the engine directly). Off a held list: nothing here.
2895
+ const searchDoor = forward && !!isolation && platform.wallsRestricted?.(isolation) === true
2896
+ ? searchDoorWanted({
2897
+ level: network.level,
2898
+ defaults: network.defaults,
2899
+ enforce: forward.enforce === true,
2900
+ web: scriptSpecs.some((sc) => sc.name === "web"),
2901
+ actions: web.actions ?? null,
2902
+ provided: searchProvided(web.raw),
2903
+ limits: stepLimits,
2904
+ })
2905
+ : { door: null };
2906
+ if (searchDoor.door)
2907
+ grant.search = searchDoor.door;
2908
+ else
2909
+ delete grant.search;
2910
+ if (searchDoor.line)
2911
+ push("info", searchDoor.line);
2888
2912
  const bound = forward ? Object.keys(boundSites).filter((name) => name in liveSecrets) : [];
2889
2913
  for (const name of bound) {
2890
2914
  for (const site of boundSites[name])
@@ -3113,6 +3137,9 @@ mayDefer) {
3113
3137
  // cannot go through it, and the platform starts no account
3114
3138
  // browser pod for it (browse-egress.ts, FOL-110 phase 3).
3115
3139
  ...(browse?.kind === "hosted" ? { [BROWSER_CONFINED_ENV]: "1" } : {}),
3140
+ // The search door's address, for the driver: a step it walls
3141
+ // searches there, with the tool told it is held (search-egress.ts).
3142
+ ...(grant.search && lease?.search ? { [SEARCH_DOOR_ENV]: lease.search } : {}),
3116
3143
  // Only a step with a bound secret has a site the proxy
3117
3144
  // intercepts, so only that step's TLS clients are pointed at a
3118
3145
  // bundle with the egress CA in it; every other step's are as
@@ -3143,7 +3170,8 @@ mayDefer) {
3143
3170
  size,
3144
3171
  limits,
3145
3172
  // 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.
3173
+ // network policy): a filtered pod reaches the proxy only (and DNS,
3174
+ // unless the platform walls that too).
3147
3175
  network: { level: network.level, enforced: forward?.enforce === true },
3148
3176
  // A test run's state/ and storage/ changes come out under the run.
3149
3177
  divert: testRun && runId ? divertFor(runId) : undefined,
@@ -3455,6 +3483,12 @@ mayDefer) {
3455
3483
  step.startup = phases && Object.keys(phases).length
3456
3484
  ? Object.fromEntries(Object.entries(phases).map(([k, v]) => [k, secs(v)]))
3457
3485
  : null;
3486
+ // When those seconds count from (FOL-122): what places the marks on
3487
+ // the clock for the run's funnel. Beside the marks only — a resumed
3488
+ // driver reports none, and then neither.
3489
+ step.startupAt = phases && Object.keys(phases).length && typeof outcome.timing?.origin === "number"
3490
+ ? new Date(outcome.timing.origin).toISOString()
3491
+ : null;
3458
3492
  // Which reservation those seconds held — as numbers, because the bill
3459
3493
  // is per core-second and per GiB-second, and what was held must come
3460
3494
  // from the record, never from what the config says at billing time.