@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
package/src/scan.ts CHANGED
@@ -33,7 +33,9 @@ import { resolveNetwork } from "./network.ts";
33
33
  import { frontmatterProblems, schemaKindOf } from "./frontmatter-schema.ts";
34
34
  import { parseRemotes } from "./a2a-remotes.ts";
35
35
  import { isA2aPublished } from "./a2a-publish.ts";
36
+ import { a2aTree, flowSecretCode, type A2aTree } from "./a2a-reach.ts";
36
37
  import { parseFlow, resolveEffort, parseMaxOutputTokens, type FlowStep } from "./store.ts";
38
+ import { reservedEnvName } from "./env-names.ts";
37
39
 
38
40
  export type ScanLevel = "error" | "warn" | "info";
39
41
  export type ScanCategory = "secret" | "security" | "content" | "supply-chain" | "config";
@@ -154,14 +156,33 @@ export const SCAN_RULES: readonly ScanRule[] = [
154
156
  id: "security/published-flow-trifecta",
155
157
  category: "security",
156
158
  level: "warn",
157
- title: "A flow published over A2A runs an agent that holds private data and can send it out",
159
+ title: "A flow published over A2A runs an agent that holds private data — its answer, or its network, can carry it out",
158
160
  help:
159
- "An outside agent's message is untrusted input to every step of a published flow. A step whose agent also holds a secret, " +
160
- "an API or an MCP server, and can reach an open network, an outward tool or an API it may write to, can be told by the caller " +
161
- "where to send what it holds. Take a leg away from that agent (network: { level: trusted, allow: [...] }, split it, a hooks: gate), " +
162
- "or do not publish the flow.",
161
+ "An outside agent's message is untrusted input to every step of a published flow, and the flow's answer goes back to that caller — " +
162
+ "so the answer is a way out too (5 Nov 2026). A step whose agent holds a secret, an API or an MCP server can be told by the caller " +
163
+ "to put what it holds or reads in its answer, or to send it to an open network, an outward tool or an API it may write to. A hooks: " +
164
+ "gate guards tool calls, not the answer. Give that agent only what a stranger may see, move the private part to a flow that is not " +
165
+ "published, or do not publish the flow.",
163
166
  owasp: ["ASI01", "ASI02", "ASI03"],
164
167
  },
168
+ {
169
+ // 5 Nov 2026 (FOL-112): the answer is a way out. A published flow's last
170
+ // step answers the outside caller, and an agent that holds a secret in
171
+ // its sandbox and may run code can be told to put the secret in it —
172
+ // no network needed. The platform refuses to publish such a flow unless
173
+ // an admin names the agent under `a2a.accept_risk`; this is check's half.
174
+ id: "security/published-flow-secret-code",
175
+ category: "security",
176
+ level: "warn",
177
+ title: "A flow published over A2A runs an agent that holds a secret and can run code",
178
+ help:
179
+ "Its answer goes back to the outside caller, and code (Bash) can read every secret in the sandbox's environment — so a caller can ask " +
180
+ "for the secret in the reply. Take Bash away from that agent (disallowedTools: [Bash], or a step without code), take the secret away " +
181
+ "(or bind it to its sites with `foldrun secrets sites NAME host` so it never enters the sandbox), or have an admin accept the risk: " +
182
+ "`a2a: { accept_risk: [<agent>] }` (`foldrun a2a publish <flow> --accept-risk <agent>`). Until one of those, the platform refuses to " +
183
+ "publish the flow and refuses new A2A tasks for it.",
184
+ owasp: ["ASI01", "ASI03"],
185
+ },
165
186
  {
166
187
  id: "security/published-flow-ungated",
167
188
  category: "security",
@@ -349,6 +370,20 @@ export const SCAN_RULES: readonly ScanRule[] = [
349
370
  "and the value itself is deployed and versioned in plain text. Put it in the vault (`foldrun secrets set NAME`), write the name, and rotate it.",
350
371
  owasp: ["ASI03"],
351
372
  },
373
+ {
374
+ // 5 Nov 2026 (FOL-130): a secret is exported to the sandbox under its name.
375
+ id: "secret/reserved-env-name",
376
+ category: "security",
377
+ level: "warn",
378
+ title: "A secret named after a variable that steers every program",
379
+ help:
380
+ "A secret reaches the sandbox as an environment variable of the same name, so one called LD_PRELOAD, PATH, BASH_ENV, IFS, " +
381
+ "NODE_OPTIONS or PYTHONPATH replaces what every program the agent starts loads or looks up — almost never what was meant, and " +
382
+ "a value pointing into a folder the agent writes runs whatever is put there. Root's start-up never reads the step's environment, " +
383
+ "so this is the agent's own sandbox at stake, not the platform. Give the secret a name of its own (`STRIPE_KEY`, `CRM_TOKEN`) " +
384
+ "and have the script read that.",
385
+ owasp: ["ASI03", "ASI05"],
386
+ },
352
387
  {
353
388
  id: "check/ignore-needs-reason",
354
389
  category: "config",
@@ -759,6 +794,28 @@ function docKind(p: string): Kind {
759
794
  return null;
760
795
  }
761
796
 
797
+ // ── secret names that are not data ─────────────────────────────────────────
798
+
799
+ /** secret/reserved-env-name: an agent's or a tool's `secrets:` naming a
800
+ * variable that steers programs (env-names.ts). `${NAME}` reads as NAME. */
801
+ function scanSecretNames(f: ScanFile, data: Record<string, unknown>, lines: string[], push: Push): void {
802
+ const raw = data.secrets;
803
+ const names = (Array.isArray(raw) ? raw : typeof raw === "string" ? [raw] : [])
804
+ .filter((n): n is string => typeof n === "string")
805
+ .map((n) => n.trim().replace(/^\$\{(.*)\}$/, "$1"));
806
+ for (const name of new Set(names)) {
807
+ const why = reservedEnvName(name);
808
+ if (!why) continue;
809
+ const word = new RegExp(`(^|[^A-Za-z0-9_])${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}([^A-Za-z0-9_]|$)`);
810
+ const from = keyLine(lines, "secrets");
811
+ const at = from ? (lines.slice(from - 1).findIndex((l) => word.test(l)) + from) || from : undefined;
812
+ push(
813
+ "secret/reserved-env-name", f.path, at, `reserved-env ${name}`,
814
+ `secrets: ${name} — the secret is exported under that name, and ${why}. Rename it (and what reads it) to a name of its own`,
815
+ );
816
+ }
817
+ }
818
+
762
819
  // ── agents: what one can reach, taken together ─────────────────────────────
763
820
 
764
821
  const WRITE_METHODS = /\b(?:POST|PUT|PATCH|DELETE)\b/i;
@@ -882,28 +939,41 @@ function stepAgents(s: FlowStep): string[] {
882
939
  * what it holds (the trifecta, with the caller as the untrusted leg), and a
883
940
  * step that acts outside the workspace with no person before it.
884
941
  */
885
- function scanPublishedFlows(flows: FlowFacts[], legs: Map<string, AgentLegs>, push: Push) {
942
+ function scanPublishedFlows(flows: FlowFacts[], legs: Map<string, AgentLegs>, tree: A2aTree, push: Push) {
886
943
  for (const fl of flows) {
887
944
  let info: ReturnType<typeof parseFlow>;
888
945
  try {
889
- info = parseFlow(fl.file, fl.content);
946
+ info = parseFlow(fl.file.replace(/^.*\//, ""), fl.content); // named as the platform names it: leads, not flows/leads
890
947
  } catch {
891
948
  continue; // a flow that does not parse is check's finding
892
949
  }
893
950
  if (!isA2aPublished(info.a2a)) continue;
894
951
  const at = keyLine(fl.lines, "a2a");
895
- const said = new Set<string>();
896
- for (const step of info.steps) {
897
- for (const name of stepAgents(step)) {
898
- const l = legs.get(name);
899
- if (!l || said.has(name) || l.gated || !l.privateLeg.length || !l.outLeg.length) continue;
900
- said.add(name);
901
- push(
902
- "security/published-flow-trifecta", fl.file, step.line ?? at, `published trifecta ${name}`,
903
- `${info.name} is published over A2A, so what an outside caller sends reaches ${name}, which holds ${l.privateLeg.slice(0, 3).join(", ")}${l.privateLeg.length > 3 ? ", …" : ""} ` +
904
- `and can reach ${l.outLeg.slice(0, 2).join(" and ")} — a caller can tell it where to send what it holds. Take a leg away from ${name}, or do not publish the flow`,
905
- );
906
- }
952
+ // Each agent at the first step line that runs it; a sub-agent or a
953
+ // subflow's agent at the a2a: line.
954
+ const lineOf = (name: string) => info.steps.find((s) => !s.subflow && [s.agent, s.onFail, ...(s.delegate ?? [])].includes(name))?.line ?? at;
955
+ // The answer goes back to the caller (FOL-112): any private leg is
956
+ // enough, and a hooks: gate (which guards tool calls) does not close it.
957
+ for (const name of tree.flows.get(info.name)?.file === fl.file ? tree.agentsOf(info.name) : []) {
958
+ const l = legs.get(name);
959
+ if (!l || !l.privateLeg.length) continue;
960
+ const out = !l.gated && l.outLeg.length ? ` and can reach ${l.outLeg.slice(0, 2).join(" and ")}` : "";
961
+ push(
962
+ "security/published-flow-trifecta", fl.file, lineOf(name), `published trifecta ${name}`,
963
+ `${info.name} is published over A2A, so what an outside caller sends reaches ${name}, which holds ${l.privateLeg.slice(0, 3).join(", ")}${l.privateLeg.length > 3 ? ", …" : ""}${out} — ` +
964
+ `and the flow's answer goes back to that caller, so a caller can ask for what it holds. Give ${name} only what a stranger may see, or do not publish the flow`,
965
+ );
966
+ }
967
+ for (const e of flowSecretCode(tree, info.name)) {
968
+ const held = `${e.secrets.slice(0, 3).join(", ")}${e.secrets.length > 3 ? ", …" : ""}`;
969
+ push(
970
+ "security/published-flow-secret-code", fl.file, lineOf(e.agent), `published secret-code ${e.agent}`,
971
+ e.accepted
972
+ ? `${e.agent} holds ${held} and can run code, and ${info.name} is published over A2A — accepted by an admin (a2a: accept_risk: [${e.agent}])`
973
+ : `${e.agent} holds ${held} and can run code (Bash), and ${info.name} is published over A2A — its answer goes back to the outside caller, who can ask for the secret in it. ` +
974
+ `Take Bash or the secret away from ${e.agent}, or have an admin accept it (a2a: accept_risk: [${e.agent}]); until then the platform refuses new A2A tasks for ${info.name}`,
975
+ e.accepted ? "info" : undefined,
976
+ );
907
977
  }
908
978
  // Groups in order. A gate (an approval, or ask:, which is one with a
909
979
  // question) on any step of a group parks the run before ANY step of that
@@ -1237,6 +1307,7 @@ export function scanFiles(files: ScanFile[], options: ScanOptions = {}): ScanFin
1237
1307
  }
1238
1308
  const kind = docKind(f.path);
1239
1309
  if (!kind) continue;
1310
+ if (kind === "agent" || kind === "tool") scanSecretNames(f, data, lines, push);
1240
1311
  if (kind === "agent") {
1241
1312
  const rel = f.path.replace(/^library\//, "");
1242
1313
  const name = /^agents\/([^/]+)\//.exec(rel)?.[1] ?? rel.replace(/^.*\/|\.md$/g, "");
@@ -1252,7 +1323,7 @@ export function scanFiles(files: ScanFile[], options: ScanOptions = {}): ScanFin
1252
1323
  // project.md is the older name the runtime still reads (Codex review, FOL-58).
1253
1324
  const workspaceMd = files.find((f) => f.path === "AGENTS.md") ?? files.find((f) => f.path === "project.md");
1254
1325
  const legs = scanAgents(agents, outward, toolDefs, push, { account: options.accountNetwork, workspace: workspaceMd ? frontOf(workspaceMd.content, "AGENTS.md")?.network : undefined });
1255
- scanPublishedFlows(flows, legs, push);
1326
+ scanPublishedFlows(flows, legs, a2aTree(files.filter((f) => isText(f) && !RUNTIME_WRITTEN.test(f.path)), { accountNetwork: options.accountNetwork }), push);
1256
1327
  // A workspace that names its own provider: does not run on the account's
1257
1328
  // choice, so the account's models say nothing about its efforts.
1258
1329
  const ownWorkspaceProvider = Boolean(workspaceMd && frontOf(workspaceMd.content, "AGENTS.md")?.provider);
@@ -0,0 +1,116 @@
1
+ // Web search and `network:` (FOL-128, foldrun-docs/network.md#search).
2
+ //
3
+ // A step held to its list — restricted (trusted or none), enforced, on the
4
+ // k8s tier — runs in a `filtered` pod: Cilium lets it reach the egress proxy
5
+ // and nothing else, and (FOLDRUN_RUN_DNS_WALL) it has no DNS. The account's
6
+ // search pod (SearXNG, which has the world) is not reachable from there. A
7
+ // named search API (`web: {search: brave}`) already works: its host is a
8
+ // site the step declares, and its key is filled at the proxy. foldrun's own
9
+ // engine did not: the tool was pointed at an address the wall drops.
10
+ //
11
+ // The semantics chosen (owner, 5 Nov 2026: search should work there):
12
+ //
13
+ // - The account's engine is a platform service, not a site on the list.
14
+ // A held step reaches it through the egress proxy's search door
15
+ // (`/s/<lease>/search`), lease-authenticated, and only when this
16
+ // module says the step searches our engine (grant.search, which the
17
+ // runner writes and the pod cannot). Nothing is added to the list.
18
+ // - A query is a message out — to the public engines SearXNG asks — so
19
+ // the door holds what it may say: only a fixed set of index engines
20
+ // (none that fetches a URL named in the query, none that federates to
21
+ // instances a query could name), no engine or bang chosen inside the
22
+ // query, no URL and no `${NAME}` placeholder in it. Every query is a
23
+ // line in the run trace, so what left is on the record.
24
+ // - Results are data. Nothing in them widens the list: fetching a result
25
+ // is a CONNECT through the proxy, held to the list like any other.
26
+ //
27
+ // Everything else — a step whose list is open or only reported, a step on
28
+ // an executor that walls nothing — searches exactly as before.
29
+
30
+ import type { NetworkLevel } from "./network.ts";
31
+ import { readSearchSettings, resolveSearch } from "./providers.ts";
32
+ import { resolveActionApi } from "./web-actions.ts";
33
+
34
+ /** The `web` actions that ask a search engine when no provider answers them. */
35
+ export const SEARCHING_ACTIONS = ["search", "answer", "monitor"] as const;
36
+ export type SearchingAction = (typeof SEARCHING_ACTIONS)[number];
37
+
38
+ /** The searching actions a provider answers instead of our engine, from an
39
+ * agent's resolved `web:` block (webConfig(...).raw) — the runner's reading
40
+ * of it: a search API or a model provider's own search for `search`, an
41
+ * answer or monitor provider for those. */
42
+ export function searchProvided(raw: Record<string, unknown>): SearchingAction[] {
43
+ const out: SearchingAction[] = [];
44
+ const search = resolveSearch(readSearchSettings(raw.search).rest, "search");
45
+ if (search.provider && !search.error) out.push("search");
46
+ for (const a of ["answer", "monitor"] as const) if (resolveActionApi(a, raw[a]).provider) out.push(a);
47
+ return out;
48
+ }
49
+
50
+ /** What the proxy is told on the grant: the door is open for this step, and
51
+ * at most this many searches go through it. */
52
+ export interface SearchDoorGrant {
53
+ max?: number;
54
+ }
55
+
56
+ /**
57
+ * May this step search through the egress proxy's door? The runner asks,
58
+ * from its own resolved config — never the pod's environment — and after
59
+ * the lease, so `enforce` is the effective one (the install's switch too).
60
+ *
61
+ * Only a step held to a restricted list: the others reach the engine as
62
+ * before. Only the actions our engine answers. And where the list was made
63
+ * narrow on purpose — level `none` (only what the step declares) or
64
+ * `defaults: false` (no trusted list) — the action must be written out in
65
+ * `web: {actions: [...]}`: a bare `tools: [web]` does not open a way out for
66
+ * a query that the list's author never named. Every searching action gives
67
+ * any program in the step that same way out (curl can use the door too).
68
+ */
69
+ export function searchDoorWanted(o: {
70
+ level: NetworkLevel;
71
+ /** The trusted list is part of the step's list (network: defaults). */
72
+ defaults: boolean;
73
+ /** Will the proxy refuse a site off the list (the lease's enforce)? */
74
+ enforce: boolean;
75
+ /** The step has the web tool. */
76
+ web: boolean;
77
+ /** The `web: {actions: [...]}` in force, or null for all. */
78
+ actions: readonly string[] | null | undefined;
79
+ /** The searching actions a provider answers instead of our engine. */
80
+ provided: readonly SearchingAction[];
81
+ /** The step's `limits:` (cascaded), for the door's own count. */
82
+ limits?: Record<string, number>;
83
+ }): { door: SearchDoorGrant | null; line?: string } {
84
+ if (o.level === "open" || !o.enforce || !o.web) return { door: null };
85
+ const ours = SEARCHING_ACTIONS.filter((a) => (!o.actions || o.actions.includes(a)) && !o.provided.includes(a));
86
+ if (!ours.length) return { door: null };
87
+ if ((o.level === "none" || !o.defaults) && !o.actions) {
88
+ return { door: null, line: o.level === "none" ? SEARCH_NONE_UNNAMED : SEARCH_NO_DEFAULTS_UNNAMED };
89
+ }
90
+ // limits: — `web` bounds every action; else each searching action's own
91
+ // key, and only when every one this step may use has one.
92
+ const lim = o.limits ?? {};
93
+ const each = ours.map((a) => lim[`web.${a}`]);
94
+ const max = typeof lim.web === "number" ? lim.web : each.every((n) => typeof n === "number") ? each.reduce((s, n) => s + (n as number), 0) : undefined;
95
+ return { door: max !== undefined ? { max } : {}, line: SEARCH_DOOR_LINE };
96
+ }
97
+
98
+ /** The trace lines for a held step that is not given the door. */
99
+ export const SEARCH_NONE_UNNAMED =
100
+ "search: not offered — this step's network: none allows only what it declares, and its web: block names no actions, so search is not one of them. Write web: {actions: [search, …]} to let it search through the egress proxy.";
101
+ export const SEARCH_NO_DEFAULTS_UNNAMED =
102
+ "search: not offered — this step's network: drops the trusted list (defaults: false), and its web: block names no actions, so search is not one of them. Write web: {actions: [search, …]} to let it search through the egress proxy.";
103
+
104
+ /** The trace line a held step that searches carries, at its start. */
105
+ export const SEARCH_DOOR_LINE =
106
+ "search: through the egress proxy — the account's search engine answers this step's queries from a fixed set of engines; a query's words leave for those engines, and each query is a line in this trace; a result is data, and fetching it is held to network: like any other site";
107
+
108
+ /** On a held step's sandbox beside the door's address: the web tool reads
109
+ * it to keep the address's path and to mark results as outside content. */
110
+ export const SEARCH_HELD_ENV = "FOLDRUN_SEARCH_HELD";
111
+
112
+ /** The runner's word to the platform's driver: the search door's address
113
+ * for this step (its grant carries `search`). The driver takes it out of
114
+ * the sandbox's environment and, for a step it walls, points the web tool
115
+ * there (FOLDRUN_SEARCH_URL, with SEARCH_HELD_ENV). */
116
+ export const SEARCH_DOOR_ENV = "FOLDRUN_SEARCH_DOOR";
package/src/starter.ts CHANGED
@@ -342,6 +342,9 @@ agents reference them by name. Bind one to the sites it is for
342
342
  the egress proxy fills \`\${NAME}\` in requests to those sites alone. Which sites
343
343
  a sandbox may reach at all is \`network:\` — open for an agent that reads the web,
344
344
  the trusted list plus what it declares for every other (\`foldrun agent network\`).
345
+ A step held to its list still searches the web through the proxy's search door;
346
+ at \`none\` or \`defaults: false\` write it out — \`web: {actions: [search, fetch]}\` —
347
+ because a query's words leave (\`foldrun docs network\`).
345
348
 
346
349
  ## Talking to a deployed workspace
347
350
 
@@ -439,7 +442,7 @@ effort: low
439
442
  overlap: skip # skip | queue — what a second run does while one is live
440
443
  priority: normal # high | normal | low — where its runs stand in the queue
441
444
  compute: { vcpu: 4, memory: 8Gi, disk: 40Gi } # optional: what one run may hold at once
442
- a2a: { publish: false } # true: outside agents may call it over A2A (admin only; callers need an A2A key)
445
+ a2a: { publish: false } # true: outside agents may call it over A2A (admin only; callers need an A2A key; an agent with a secret and Bash needs accept_risk: [agent])
443
446
  ---
444
447
 
445
448
  1. [[researcher]] — Find three sources on {{topic}}.
package/src/store.ts CHANGED
@@ -53,10 +53,12 @@ import { checkFilter } from "./trigger-filter.ts";
53
53
  import { parseA2aPublish, type A2aPublication } from "./a2a-publish.ts";
54
54
  import { parseRemotes, remoteNetworkHosts, A2A_LIMIT_KEY, type RemoteSpec } from "./a2a-remotes.ts";
55
55
  import { parseBudget, budgetProblem } from "./budget.ts";
56
+ import { explainFailure, failureFactsOf, type FailureExplained, type FailureFacts } from "./failure.ts";
56
57
  import { timezoneProblem } from "./clock.ts";
57
58
  import { parseStepLimits, readLimits } from "./limits.ts";
58
59
  import { networkEnforceWanted, networkProblems, resolveNetwork, type NetworkPolicy } from "./network.ts";
59
60
  import { browseVendorOf } from "./browse-egress.ts";
61
+ import { searchProvided, type SearchingAction } from "./search-egress.ts";
60
62
  import { webProblems, webWarnings, runnerEngines, webConfig } from "./providers.ts";
61
63
  import { actionProblems } from "./web-actions.ts";
62
64
  import { languageProblem } from "./language.ts";
@@ -1053,7 +1055,16 @@ export interface AgentInfo {
1053
1055
  * its web providers' and its bound secrets' sites. */
1054
1056
  /** browses: the step may browse; enforceWanted and browseVendor are what
1055
1057
  * this folder says toward browseVerdict (FOL-110) — the install says the rest. */
1056
- network: NetworkPolicy & { readsWeb: boolean; browses: boolean; enforceWanted: boolean; browseVendor: string | null };
1058
+ /** search: this folder's half of search-egress.ts searchDoorWanted — the
1059
+ * web tool, the actions written in web: (null: all), and the searching
1060
+ * actions a provider answers (FOL-128). */
1061
+ network: NetworkPolicy & {
1062
+ readsWeb: boolean;
1063
+ browses: boolean;
1064
+ enforceWanted: boolean;
1065
+ browseVendor: string | null;
1066
+ search: { web: boolean; actions: string[] | null; provided: SearchingAction[] };
1067
+ };
1057
1068
  /** Tools this agent declares inline rather than in `tools:` — `apis:`,
1058
1069
  * `scripts:` and `mcpServers:` names — which a limit may also name. */
1059
1070
  inlineTools: string[];
@@ -1687,6 +1698,11 @@ export function listAgents(tenant: string, workspace: string): AgentInfo[] {
1687
1698
  enforceWanted: networkEnforceWanted(accountFront.network_enforce, workspaceFront.network_enforce),
1688
1699
  // The vendor its web.browse names, null for foldrun's own browser.
1689
1700
  browseVendor: browseVendorOf(webConfig(data, { ...accountFront, ...workspaceFront }).raw.browse),
1701
+ search: {
1702
+ web: tools.includes("web"),
1703
+ actions: actions ? [...actions] : null,
1704
+ provided: searchProvided(webConfig(data, { ...accountFront, ...workspaceFront }).raw),
1705
+ },
1690
1706
  };
1691
1707
  return {
1692
1708
  network,
@@ -3367,6 +3383,10 @@ export interface RunEvent {
3367
3383
  /** Set on a tool event a SUB-AGENT made (`subagents:`): its name. The
3368
3384
  * trace labels the call with it; cost stays the step's. */
3369
3385
  subagent?: string;
3386
+ /** Set on the error a platform security control wrote (failure.ts
3387
+ * securityStopEvent) — host-side only, never from a sandbox's output.
3388
+ * The customer is told the generic sentence and nothing else. */
3389
+ security?: true;
3370
3390
  /** Set on an error a failed check wrote — `verify:` (its headline and its
3371
3391
  * detail), `output: json`, a schema. What the runner reads to decline a
3372
3392
  * retry of an outward step whose tools already ran. */
@@ -3751,6 +3771,11 @@ export interface StepRecord {
3751
3771
  * #STARTUP_PHASES). Only the phases this step went through; null from
3752
3772
  * an executor that marks none, absent on steps from before 17 Oct 2026. */
3753
3773
  startup?: Record<string, number> | null;
3774
+ /** When the executor began the attempt those marks belong to — what they
3775
+ * count from, so a mark is an instant (FOL-122's run funnel). Set beside
3776
+ * `startup`; null where it is; absent before 5 Nov 2026, when readers
3777
+ * fall back to the attempt's own start, an estimate. */
3778
+ startupAt?: string | null;
3754
3779
  /** Which reservation class the sandbox held (small | large), and the
3755
3780
  * actual limits it held, as numbers. Facts of the step: a price is per
3756
3781
  * core-second, so what was reserved must come from the record, never
@@ -3758,6 +3783,10 @@ export interface StepRecord {
3758
3783
  * from before sizes existed — billing falls back to the flat rate. */
3759
3784
  size?: "small" | "large" | "heavy";
3760
3785
  reserved?: { cpus: number; memGiB: number; diskGiB?: number } | null;
3786
+ /** Only on a record rebuilt from the runs index (runFromSummary), for a
3787
+ * failed step: the figures and refused sites its failure message names,
3788
+ * which a full record carries in `reserved`, `actual` and its events. */
3789
+ failureFacts?: FailureFacts;
3761
3790
  /** The agent's `resources:` as applied (resources.ts), when it set any:
3762
3791
  * why `reserved` differs from the class's figures. Absent before 26 Oct
3763
3792
  * 2026 and on steps of an agent that wrote none. */
@@ -3988,16 +4017,22 @@ export function runFilePath(tenant: string, workspace: string, runId: string) {
3988
4017
  * the same append-only file the charge lives in. The balance is untouched;
3989
4018
  * the story is complete.
3990
4019
  */
3991
- export function deleteRun(tenant: string, workspace: string, runId: string): boolean {
4020
+ export function deleteRun(tenant: string, workspace: string, runId: string, opts: { pruned?: boolean } = {}): boolean {
3992
4021
  const file = runFilePath(tenant, workspace, runId);
3993
- if (!fs.existsSync(file)) return false;
4022
+ const dir = path.join(workspaceDir(tenant, workspace), "runs", runId);
4023
+ const had = fs.existsSync(file);
4024
+ if (!had && !fs.existsSync(dir)) return false;
4025
+ // The folder first (archived outputs, captured calls), the record last:
4026
+ // a delete that fails halfway leaves the record, so a retry finds the run
4027
+ // and finishes — the other order left the content with nothing pointing
4028
+ // at it (Codex review, FOL-124).
4029
+ fs.rmSync(dir, { recursive: true, force: true });
3994
4030
  fs.rmSync(file, { force: true });
3995
- fs.rmSync(path.join(workspaceDir(tenant, workspace), "runs", runId), {
3996
- recursive: true,
3997
- force: true,
3998
- });
3999
4031
  noteRunDeleted(path.dirname(file), runId);
4000
- onRunDeleted?.(tenant, workspace, runId);
4032
+ if (!had) return true;
4033
+ // The retention window's prune (`pruned`) is policy, not a person erasing
4034
+ // history: no per-run ledger note. The charge stands either way.
4035
+ if (!opts.pruned) onRunDeleted?.(tenant, workspace, runId);
4001
4036
  return true;
4002
4037
  }
4003
4038
 
@@ -4166,6 +4201,9 @@ export interface RunSummaryStep {
4166
4201
  skipReason?: string;
4167
4202
  /** The last error event, for a failed step — what runFailure reads. */
4168
4203
  error?: string;
4204
+ /** For a failed step: the figures and refused sites runFailure's message
4205
+ * names (failure.ts). Absent before 5 Nov 2026. */
4206
+ failureFacts?: FailureFacts;
4169
4207
  item?: string;
4170
4208
  waitFor?: "event";
4171
4209
  ask?: string;
@@ -4249,7 +4287,12 @@ export function summarizeRun(run: RunRecord): RunSummary {
4249
4287
  ...(run.a2a ? { a2a: run.a2a } : {}),
4250
4288
  awaitingApproval: run.steps.some((s) => s.status === "awaiting-approval" && s.waitFor !== "event"),
4251
4289
  steps: run.steps.map((s) => {
4252
- const error = s.status === "failed" ? s.events.filter((e) => e.type === "error").at(-1)?.text : undefined;
4290
+ // A failed step's last error — and, on a run that failed between
4291
+ // groups, the budget's error the runner wrote onto the step before
4292
+ // (runFailure reads it from there; FOL-124, Codex review).
4293
+ const last = s.events.filter((e) => e.type === "error").at(-1)?.text;
4294
+ const error = s.status === "failed" || (run.status === "failed" && last !== undefined && /^over budget/.test(last)) ? last : undefined;
4295
+ const failureFacts = s.status === "failed" ? failureFactsOf(s) : undefined;
4253
4296
  return {
4254
4297
  agent: s.agent,
4255
4298
  group: s.group,
@@ -4259,6 +4302,7 @@ export function summarizeRun(run: RunRecord): RunSummary {
4259
4302
  ...(s.computeSecs !== undefined ? { computeSecs: s.computeSecs } : {}),
4260
4303
  ...(s.skipReason ? { skipReason: s.skipReason } : {}),
4261
4304
  ...(error ? { error: error.slice(0, 500) } : {}),
4305
+ ...(failureFacts ? { failureFacts } : {}),
4262
4306
  ...(s.item ? { item: s.item } : {}),
4263
4307
  ...(s.waitFor ? { waitFor: s.waitFor } : {}),
4264
4308
  ...(s.ask ? { ask: s.ask } : {}),
@@ -4574,15 +4618,34 @@ export function runDurationSecs(run: RunRecord): number | null {
4574
4618
  * sentence — "failed" with no reason makes every diagnosis start by opening
4575
4619
  * the run, and the answer was sitting in the record all along.
4576
4620
  */
4577
- export function runFailure(run: RunRecord): { agent: string; reason: string } | null {
4621
+ export function runFailure(run: RunRecord): RunFailure | null {
4578
4622
  if (run.status !== "failed") return null;
4579
4623
  const step = run.steps.find((s) => s.status === "failed");
4580
- if (!step) return null;
4624
+ if (!step) {
4625
+ // A run can fail with no failed step: a budget hit or a stop between
4626
+ // groups writes its error onto the last step that ran (FOL-124).
4627
+ if (run.stopRequested) {
4628
+ const reason = `stopped by ${run.stoppedBy ?? "a person"}`;
4629
+ return { agent: run.steps.findLast((s) => s.status === "completed")?.agent ?? run.steps[0]?.agent ?? "run", reason, ...explainFailure(reason, null) };
4630
+ }
4631
+ const holder = run.steps.findLast((s) => s.events.some((e) => e.type === "error" && /^over budget/.test(e.text)));
4632
+ const text = holder?.events.filter((e) => e.type === "error" && /^over budget/.test(e.text)).at(-1)?.text;
4633
+ if (holder && text) return { agent: holder.agent, reason: text, ...explainFailure(text, null) };
4634
+ return null;
4635
+ }
4581
4636
  const errors = step.events.filter((e) => e.type === "error");
4582
4637
  const last = errors[errors.length - 1];
4583
- return { agent: step.agent, reason: last?.text ?? "failed without an error event" };
4638
+ const raw = last?.text ?? "failed without an error event";
4639
+ // The customer's sentence, its class and its fix (failure.ts, FOL-124).
4640
+ // A security stop's reason is that sentence too: nothing else is said.
4641
+ const explained = explainFailure(raw, step);
4642
+ return { agent: step.agent, reason: explained.kind === "security" ? explained.message : raw, ...explained };
4584
4643
  }
4585
4644
 
4645
+ /** Why a failed run failed: the step, its last error, and what that means
4646
+ * for the customer (failure.ts). */
4647
+ export type RunFailure = { agent: string; reason: string } & FailureExplained;
4648
+
4586
4649
  /**
4587
4650
  * The one-line outcome, pulled out of the reply that already says it.
4588
4651
  *