@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
package/dist/src/scan.js CHANGED
@@ -32,7 +32,9 @@ import { resolveNetwork } from "./network.js";
32
32
  import { frontmatterProblems, schemaKindOf } from "./frontmatter-schema.js";
33
33
  import { parseRemotes } from "./a2a-remotes.js";
34
34
  import { isA2aPublished } from "./a2a-publish.js";
35
+ import { a2aTree, flowSecretCode } from "./a2a-reach.js";
35
36
  import { parseFlow, resolveEffort, parseMaxOutputTokens } from "./store.js";
37
+ import { reservedEnvName } from "./env-names.js";
36
38
  export const OWASP_URL = "https://genai.owasp.org/resource/owasp-top-10-for-agentic-applications-for-2026";
37
39
  export const SCAN_RULES = [
38
40
  {
@@ -90,13 +92,31 @@ export const SCAN_RULES = [
90
92
  id: "security/published-flow-trifecta",
91
93
  category: "security",
92
94
  level: "warn",
93
- title: "A flow published over A2A runs an agent that holds private data and can send it out",
94
- help: "An outside agent's message is untrusted input to every step of a published flow. A step whose agent also holds a secret, " +
95
- "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 " +
96
- "where to send what it holds. Take a leg away from that agent (network: { level: trusted, allow: [...] }, split it, a hooks: gate), " +
97
- "or do not publish the flow.",
95
+ title: "A flow published over A2A runs an agent that holds private data — its answer, or its network, can carry it out",
96
+ help: "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 — " +
97
+ "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 " +
98
+ "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: " +
99
+ "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 " +
100
+ "published, or do not publish the flow.",
98
101
  owasp: ["ASI01", "ASI02", "ASI03"],
99
102
  },
103
+ {
104
+ // 5 Nov 2026 (FOL-112): the answer is a way out. A published flow's last
105
+ // step answers the outside caller, and an agent that holds a secret in
106
+ // its sandbox and may run code can be told to put the secret in it —
107
+ // no network needed. The platform refuses to publish such a flow unless
108
+ // an admin names the agent under `a2a.accept_risk`; this is check's half.
109
+ id: "security/published-flow-secret-code",
110
+ category: "security",
111
+ level: "warn",
112
+ title: "A flow published over A2A runs an agent that holds a secret and can run code",
113
+ help: "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 " +
114
+ "for the secret in the reply. Take Bash away from that agent (disallowedTools: [Bash], or a step without code), take the secret away " +
115
+ "(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: " +
116
+ "`a2a: { accept_risk: [<agent>] }` (`foldrun a2a publish <flow> --accept-risk <agent>`). Until one of those, the platform refuses to " +
117
+ "publish the flow and refuses new A2A tasks for it.",
118
+ owasp: ["ASI01", "ASI03"],
119
+ },
100
120
  {
101
121
  id: "security/published-flow-ungated",
102
122
  category: "security",
@@ -267,6 +287,19 @@ export const SCAN_RULES = [
267
287
  "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.",
268
288
  owasp: ["ASI03"],
269
289
  },
290
+ {
291
+ // 5 Nov 2026 (FOL-130): a secret is exported to the sandbox under its name.
292
+ id: "secret/reserved-env-name",
293
+ category: "security",
294
+ level: "warn",
295
+ title: "A secret named after a variable that steers every program",
296
+ help: "A secret reaches the sandbox as an environment variable of the same name, so one called LD_PRELOAD, PATH, BASH_ENV, IFS, " +
297
+ "NODE_OPTIONS or PYTHONPATH replaces what every program the agent starts loads or looks up — almost never what was meant, and " +
298
+ "a value pointing into a folder the agent writes runs whatever is put there. Root's start-up never reads the step's environment, " +
299
+ "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`) " +
300
+ "and have the script read that.",
301
+ owasp: ["ASI03", "ASI05"],
302
+ },
270
303
  {
271
304
  id: "check/ignore-needs-reason",
272
305
  category: "config",
@@ -689,6 +722,24 @@ function docKind(p) {
689
722
  return "tool";
690
723
  return null;
691
724
  }
725
+ // ── secret names that are not data ─────────────────────────────────────────
726
+ /** secret/reserved-env-name: an agent's or a tool's `secrets:` naming a
727
+ * variable that steers programs (env-names.ts). `${NAME}` reads as NAME. */
728
+ function scanSecretNames(f, data, lines, push) {
729
+ const raw = data.secrets;
730
+ const names = (Array.isArray(raw) ? raw : typeof raw === "string" ? [raw] : [])
731
+ .filter((n) => typeof n === "string")
732
+ .map((n) => n.trim().replace(/^\$\{(.*)\}$/, "$1"));
733
+ for (const name of new Set(names)) {
734
+ const why = reservedEnvName(name);
735
+ if (!why)
736
+ continue;
737
+ const word = new RegExp(`(^|[^A-Za-z0-9_])${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}([^A-Za-z0-9_]|$)`);
738
+ const from = keyLine(lines, "secrets");
739
+ const at = from ? (lines.slice(from - 1).findIndex((l) => word.test(l)) + from) || from : undefined;
740
+ push("secret/reserved-env-name", f.path, at, `reserved-env ${name}`, `secrets: ${name} — the secret is exported under that name, and ${why}. Rename it (and what reads it) to a name of its own`);
741
+ }
742
+ }
692
743
  // ── agents: what one can reach, taken together ─────────────────────────────
693
744
  const WRITE_METHODS = /\b(?:POST|PUT|PATCH|DELETE)\b/i;
694
745
  function scanAgents(agents, outward, toolDefs, push, networks) {
@@ -771,11 +822,11 @@ function stepAgents(s) {
771
822
  * what it holds (the trifecta, with the caller as the untrusted leg), and a
772
823
  * step that acts outside the workspace with no person before it.
773
824
  */
774
- function scanPublishedFlows(flows, legs, push) {
825
+ function scanPublishedFlows(flows, legs, tree, push) {
775
826
  for (const fl of flows) {
776
827
  let info;
777
828
  try {
778
- info = parseFlow(fl.file, fl.content);
829
+ info = parseFlow(fl.file.replace(/^.*\//, ""), fl.content); // named as the platform names it: leads, not flows/leads
779
830
  }
780
831
  catch {
781
832
  continue; // a flow that does not parse is check's finding
@@ -783,16 +834,25 @@ function scanPublishedFlows(flows, legs, push) {
783
834
  if (!isA2aPublished(info.a2a))
784
835
  continue;
785
836
  const at = keyLine(fl.lines, "a2a");
786
- const said = new Set();
787
- for (const step of info.steps) {
788
- for (const name of stepAgents(step)) {
789
- const l = legs.get(name);
790
- if (!l || said.has(name) || l.gated || !l.privateLeg.length || !l.outLeg.length)
791
- continue;
792
- said.add(name);
793
- push("security/published-flow-trifecta", fl.file, step.line ?? at, `published trifecta ${name}`, `${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 ? ", …" : ""} ` +
794
- `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`);
795
- }
837
+ // Each agent at the first step line that runs it; a sub-agent or a
838
+ // subflow's agent at the a2a: line.
839
+ const lineOf = (name) => info.steps.find((s) => !s.subflow && [s.agent, s.onFail, ...(s.delegate ?? [])].includes(name))?.line ?? at;
840
+ // The answer goes back to the caller (FOL-112): any private leg is
841
+ // enough, and a hooks: gate (which guards tool calls) does not close it.
842
+ for (const name of tree.flows.get(info.name)?.file === fl.file ? tree.agentsOf(info.name) : []) {
843
+ const l = legs.get(name);
844
+ if (!l || !l.privateLeg.length)
845
+ continue;
846
+ const out = !l.gated && l.outLeg.length ? ` and can reach ${l.outLeg.slice(0, 2).join(" and ")}` : "";
847
+ push("security/published-flow-trifecta", fl.file, lineOf(name), `published trifecta ${name}`, `${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} — ` +
848
+ `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`);
849
+ }
850
+ for (const e of flowSecretCode(tree, info.name)) {
851
+ const held = `${e.secrets.slice(0, 3).join(", ")}${e.secrets.length > 3 ? ", …" : ""}`;
852
+ push("security/published-flow-secret-code", fl.file, lineOf(e.agent), `published secret-code ${e.agent}`, e.accepted
853
+ ? `${e.agent} holds ${held} and can run code, and ${info.name} is published over A2A — accepted by an admin (a2a: accept_risk: [${e.agent}])`
854
+ : `${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. ` +
855
+ `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}`, e.accepted ? "info" : undefined);
796
856
  }
797
857
  // Groups in order. A gate (an approval, or ask:, which is one with a
798
858
  // question) on any step of a group parks the run before ANY step of that
@@ -1114,6 +1174,8 @@ export function scanFiles(files, options = {}) {
1114
1174
  const kind = docKind(f.path);
1115
1175
  if (!kind)
1116
1176
  continue;
1177
+ if (kind === "agent" || kind === "tool")
1178
+ scanSecretNames(f, data, lines, push);
1117
1179
  if (kind === "agent") {
1118
1180
  const rel = f.path.replace(/^library\//, "");
1119
1181
  const name = /^agents\/([^/]+)\//.exec(rel)?.[1] ?? rel.replace(/^.*\/|\.md$/g, "");
@@ -1133,7 +1195,7 @@ export function scanFiles(files, options = {}) {
1133
1195
  // project.md is the older name the runtime still reads (Codex review, FOL-58).
1134
1196
  const workspaceMd = files.find((f) => f.path === "AGENTS.md") ?? files.find((f) => f.path === "project.md");
1135
1197
  const legs = scanAgents(agents, outward, toolDefs, push, { account: options.accountNetwork, workspace: workspaceMd ? frontOf(workspaceMd.content, "AGENTS.md")?.network : undefined });
1136
- scanPublishedFlows(flows, legs, push);
1198
+ scanPublishedFlows(flows, legs, a2aTree(files.filter((f) => isText(f) && !RUNTIME_WRITTEN.test(f.path)), { accountNetwork: options.accountNetwork }), push);
1137
1199
  // A workspace that names its own provider: does not run on the account's
1138
1200
  // choice, so the account's models say nothing about its efforts.
1139
1201
  const ownWorkspaceProvider = Boolean(workspaceMd && frontOf(workspaceMd.content, "AGENTS.md")?.provider);
@@ -18,6 +18,7 @@
18
18
  //
19
19
  // Secrets are injected as environment variables into the agent's tools at run
20
20
  // time and are never returned by the API.
21
+ import { opsLog, withOpsReason } from "./ops-log.js";
21
22
  import fs from "node:fs";
22
23
  import path from "node:path";
23
24
  import { dataRoot } from "./paths.js";
@@ -63,7 +64,7 @@ export function installKeyMaterial() {
63
64
  // so; without this, asking for it would quietly mint a NEW random key on
64
65
  // the shared data volume — a second root key nobody chose.
65
66
  if (process.env.FOLDRUN_INSTALL_KEY_ABSENT === "1") {
66
- throw new Error("this process runs without the install key (FOLDRUN_INSTALL_KEY_ABSENT=1) — whatever asked for it belongs in the worker");
67
+ throw withOpsReason(new Error("this process runs without the install key (FOLDRUN_INSTALL_KEY_ABSENT=1) — whatever asked for it belongs in the worker"), "install_key_absent");
67
68
  }
68
69
  fs.mkdirSync(dataRoot(), { recursive: true });
69
70
  if (!fs.existsSync(keyFile())) {
@@ -475,8 +476,8 @@ function decrypt(tenant, rec, aad) {
475
476
  // "no such secret" — a process that forgot to load the account keys
476
477
  // would look exactly like an account that never set one, which is the
477
478
  // most expensive kind of wrong answer to debug.
478
- console.error(`[secrets] ${tenant} has account-keyed secrets but no key is loaded — ` +
479
- `call loadTenantKeys() before reading, or the value will read as absent`);
479
+ // loadTenantKeys() was not called before reading: the value reads as absent.
480
+ opsLog("error", "secrets.account_key_not_loaded", { tenant });
480
481
  return null;
481
482
  }
482
483
  key = own;
@@ -423,7 +423,7 @@ effort: low
423
423
  overlap: skip # skip | queue — what a second run does while one is live
424
424
  priority: normal # high | normal | low — where its runs stand in the queue
425
425
  compute: { vcpu: 4, memory: 8Gi, disk: 40Gi } # optional: what one run may hold at once
426
- a2a: { publish: false } # true: outside agents may call it over A2A (admin only; callers need an A2A key)
426
+ 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])
427
427
  ---
428
428
 
429
429
  1. [[researcher]] — Find three sources on {{topic}}.
@@ -336,8 +336,10 @@ export declare function judgePrompt(rubric: string, reply: string, work: string)
336
336
  * A model process's failure as a person should read it: one short line. The
337
337
  * SDK's error for a CLI that died carries the CLI's stderr, which can be KBs
338
338
  * of its minified bundle — internal prompt text included (FOL-107) — so that
339
- * part goes to the server log, never to an eval result or a trace. An error
340
- * that is already short (an API error the model answered) is kept as it is.
339
+ * part goes neither to an eval result or a trace, nor to a hosted log
340
+ * (FOL-121): there the log line is the failure's class and our frames. An
341
+ * error that is already short (an API error the model answered) is kept as
342
+ * it is.
341
343
  */
342
344
  export declare function modelProcessError(err: unknown, where: string): Error;
343
345
  export declare function sdkEnv(base: Record<string, string | undefined> | undefined, extra?: Record<string, string>): Record<string, string | undefined>;
@@ -7,6 +7,7 @@
7
7
  // assembles the system prompt and builds MCP servers, then hands this the
8
8
  // results. That is what lets the same function run somewhere the vault, the
9
9
  // library and the account do not exist.
10
+ import { opsError } from "./ops-log.js";
10
11
  import { judgeVerdict, JUDGE_VERDICT_INSTRUCTION } from "./judge-verdict.js";
11
12
  import { runHook, runToolCallHooks, matchesTool, hookLine, resolveHooks } from "./hooks.js";
12
13
  import fs from "node:fs";
@@ -1171,17 +1172,22 @@ function runVerify(agentDir, command, env, data, signal) {
1171
1172
  * A model process's failure as a person should read it: one short line. The
1172
1173
  * SDK's error for a CLI that died carries the CLI's stderr, which can be KBs
1173
1174
  * of its minified bundle — internal prompt text included (FOL-107) — so that
1174
- * part goes to the server log, never to an eval result or a trace. An error
1175
- * that is already short (an API error the model answered) is kept as it is.
1175
+ * part goes neither to an eval result or a trace, nor to a hosted log
1176
+ * (FOL-121): there the log line is the failure's class and our frames. An
1177
+ * error that is already short (an API error the model answered) is kept as
1178
+ * it is.
1176
1179
  */
1177
1180
  export function modelProcessError(err, where) {
1178
1181
  const full = err instanceof Error ? err.message : String(err);
1179
1182
  const at = full.indexOf(" stderr:");
1180
1183
  if (at < 0 && full.length <= 500)
1181
1184
  return err instanceof Error ? err : new Error(full);
1182
- console.error(`[foldrun] ${where}: ${full}`);
1185
+ // Inside the hosted boundary this is the class, name and our frames only:
1186
+ // the stderr is the CLI's, and can carry the prompt (FOL-107, FOL-121).
1187
+ // On a laptop the full text comes along, for the person it belongs to.
1188
+ opsError("model.process_failed", err, { where: where.replace(/\W+/g, "_").toLowerCase(), errorClass: "model_error" });
1183
1189
  const head = (at >= 0 ? full.slice(0, at) : full.slice(0, 300)).trim().replace(/[.:]$/, "");
1184
- return new Error(`${head} — the model process failed; the details are in the server log`);
1190
+ return new Error(`${head} — the model process failed`);
1185
1191
  }
1186
1192
  export function sdkEnv(base, extra = {}) {
1187
1193
  return { ...(base ?? process.env), ...extra, ENABLE_CLAUDEAI_MCP_SERVERS: "false" };
@@ -47,6 +47,7 @@
47
47
  // FOLDRUN_S3_PATH_STYLE default true — R2 speaks path style; false on S3
48
48
  // FOLDRUN_STORAGE_MAX_MB per object, default 512
49
49
  // FOLDRUN_STORAGE_QUOTA_MB per workspace, default 5120
50
+ import { opsError } from "./ops-log.js";
50
51
  import fs from "node:fs";
51
52
  import path from "node:path";
52
53
  import crypto from "node:crypto";
@@ -563,7 +564,7 @@ async function announceFiles(tenant, workspace, paths, by) {
563
564
  await fireStorageTriggers(tenant, workspace, paths, by);
564
565
  }
565
566
  catch (err) {
566
- console.error(`[foldrun] storage trigger ${tenant}/${workspace}:`, err instanceof Error ? err.message : err);
567
+ opsError("trigger.storage_failed", err, { tenant, workspace });
567
568
  }
568
569
  }
569
570
  export async function putFile(tenant, workspace, rel, body, by) {
@@ -16,6 +16,7 @@ import { frontmatterErrorText } from "./matter.ts";
16
16
  export declare function readFrontmatter(file: string): Record<string, unknown>;
17
17
  import { type A2aPublication } from "./a2a-publish.ts";
18
18
  import { type RemoteSpec } from "./a2a-remotes.ts";
19
+ import { type FailureExplained, type FailureFacts } from "./failure.ts";
19
20
  import { type NetworkPolicy } from "./network.ts";
20
21
  import { type WireFormat, type AuthShape } from "./providers.ts";
21
22
  /**
@@ -1015,6 +1016,10 @@ export interface RunEvent {
1015
1016
  /** Set on a tool event a SUB-AGENT made (`subagents:`): its name. The
1016
1017
  * trace labels the call with it; cost stays the step's. */
1017
1018
  subagent?: string;
1019
+ /** Set on the error a platform security control wrote (failure.ts
1020
+ * securityStopEvent) — host-side only, never from a sandbox's output.
1021
+ * The customer is told the generic sentence and nothing else. */
1022
+ security?: true;
1018
1023
  /** Set on an error a failed check wrote — `verify:` (its headline and its
1019
1024
  * detail), `output: json`, a schema. What the runner reads to decline a
1020
1025
  * retry of an outward step whose tools already ran. */
@@ -1398,6 +1403,11 @@ export interface StepRecord {
1398
1403
  * #STARTUP_PHASES). Only the phases this step went through; null from
1399
1404
  * an executor that marks none, absent on steps from before 17 Oct 2026. */
1400
1405
  startup?: Record<string, number> | null;
1406
+ /** When the executor began the attempt those marks belong to — what they
1407
+ * count from, so a mark is an instant (FOL-122's run funnel). Set beside
1408
+ * `startup`; null where it is; absent before 5 Nov 2026, when readers
1409
+ * fall back to the attempt's own start, an estimate. */
1410
+ startupAt?: string | null;
1401
1411
  /** Which reservation class the sandbox held (small | large), and the
1402
1412
  * actual limits it held, as numbers. Facts of the step: a price is per
1403
1413
  * core-second, so what was reserved must come from the record, never
@@ -1409,6 +1419,10 @@ export interface StepRecord {
1409
1419
  memGiB: number;
1410
1420
  diskGiB?: number;
1411
1421
  } | null;
1422
+ /** Only on a record rebuilt from the runs index (runFromSummary), for a
1423
+ * failed step: the figures and refused sites its failure message names,
1424
+ * which a full record carries in `reserved`, `actual` and its events. */
1425
+ failureFacts?: FailureFacts;
1412
1426
  /** The agent's `resources:` as applied (resources.ts), when it set any:
1413
1427
  * why `reserved` differs from the class's figures. Absent before 26 Oct
1414
1428
  * 2026 and on steps of an agent that wrote none. */
@@ -1619,7 +1633,9 @@ export declare function runFilePath(tenant: string, workspace: string, runId: st
1619
1633
  * the same append-only file the charge lives in. The balance is untouched;
1620
1634
  * the story is complete.
1621
1635
  */
1622
- export declare function deleteRun(tenant: string, workspace: string, runId: string): boolean;
1636
+ export declare function deleteRun(tenant: string, workspace: string, runId: string, opts?: {
1637
+ pruned?: boolean;
1638
+ }): boolean;
1623
1639
  /** ledger.ts registers here — store cannot import it without a cycle, and
1624
1640
  * money must not depend on one. */
1625
1641
  declare let onRunDeleted: ((tenant: string, workspace: string, runId: string) => void) | undefined;
@@ -1683,6 +1699,9 @@ export interface RunSummaryStep {
1683
1699
  skipReason?: string;
1684
1700
  /** The last error event, for a failed step — what runFailure reads. */
1685
1701
  error?: string;
1702
+ /** For a failed step: the figures and refused sites runFailure's message
1703
+ * names (failure.ts). Absent before 5 Nov 2026. */
1704
+ failureFacts?: FailureFacts;
1686
1705
  item?: string;
1687
1706
  waitFor?: "event";
1688
1707
  ask?: string;
@@ -1818,10 +1837,13 @@ export declare function runDurationSecs(run: RunRecord): number | null;
1818
1837
  * sentence — "failed" with no reason makes every diagnosis start by opening
1819
1838
  * the run, and the answer was sitting in the record all along.
1820
1839
  */
1821
- export declare function runFailure(run: RunRecord): {
1840
+ export declare function runFailure(run: RunRecord): RunFailure | null;
1841
+ /** Why a failed run failed: the step, its last error, and what that means
1842
+ * for the customer (failure.ts). */
1843
+ export type RunFailure = {
1822
1844
  agent: string;
1823
1845
  reason: string;
1824
- } | null;
1846
+ } & FailureExplained;
1825
1847
  /**
1826
1848
  * The one-line outcome, pulled out of the reply that already says it.
1827
1849
  *
package/dist/src/store.js CHANGED
@@ -48,6 +48,7 @@ import { checkFilter } from "./trigger-filter.js";
48
48
  import { parseA2aPublish } from "./a2a-publish.js";
49
49
  import { parseRemotes, remoteNetworkHosts, A2A_LIMIT_KEY } from "./a2a-remotes.js";
50
50
  import { parseBudget, budgetProblem } from "./budget.js";
51
+ import { explainFailure, failureFactsOf } from "./failure.js";
51
52
  import { timezoneProblem } from "./clock.js";
52
53
  import { parseStepLimits, readLimits } from "./limits.js";
53
54
  import { networkEnforceWanted, networkProblems, resolveNetwork } from "./network.js";
@@ -2916,17 +2917,25 @@ export function runFilePath(tenant, workspace, runId) {
2916
2917
  * the same append-only file the charge lives in. The balance is untouched;
2917
2918
  * the story is complete.
2918
2919
  */
2919
- export function deleteRun(tenant, workspace, runId) {
2920
+ export function deleteRun(tenant, workspace, runId, opts = {}) {
2920
2921
  const file = runFilePath(tenant, workspace, runId);
2921
- if (!fs.existsSync(file))
2922
+ const dir = path.join(workspaceDir(tenant, workspace), "runs", runId);
2923
+ const had = fs.existsSync(file);
2924
+ if (!had && !fs.existsSync(dir))
2922
2925
  return false;
2926
+ // The folder first (archived outputs, captured calls), the record last:
2927
+ // a delete that fails halfway leaves the record, so a retry finds the run
2928
+ // and finishes — the other order left the content with nothing pointing
2929
+ // at it (Codex review, FOL-124).
2930
+ fs.rmSync(dir, { recursive: true, force: true });
2923
2931
  fs.rmSync(file, { force: true });
2924
- fs.rmSync(path.join(workspaceDir(tenant, workspace), "runs", runId), {
2925
- recursive: true,
2926
- force: true,
2927
- });
2928
2932
  noteRunDeleted(path.dirname(file), runId);
2929
- onRunDeleted?.(tenant, workspace, runId);
2933
+ if (!had)
2934
+ return true;
2935
+ // The retention window's prune (`pruned`) is policy, not a person erasing
2936
+ // history: no per-run ledger note. The charge stands either way.
2937
+ if (!opts.pruned)
2938
+ onRunDeleted?.(tenant, workspace, runId);
2930
2939
  return true;
2931
2940
  }
2932
2941
  /** ledger.ts registers here — store cannot import it without a cycle, and
@@ -3082,7 +3091,12 @@ export function summarizeRun(run) {
3082
3091
  ...(run.a2a ? { a2a: run.a2a } : {}),
3083
3092
  awaitingApproval: run.steps.some((s) => s.status === "awaiting-approval" && s.waitFor !== "event"),
3084
3093
  steps: run.steps.map((s) => {
3085
- const error = s.status === "failed" ? s.events.filter((e) => e.type === "error").at(-1)?.text : undefined;
3094
+ // A failed step's last error — and, on a run that failed between
3095
+ // groups, the budget's error the runner wrote onto the step before
3096
+ // (runFailure reads it from there; FOL-124, Codex review).
3097
+ const last = s.events.filter((e) => e.type === "error").at(-1)?.text;
3098
+ const error = s.status === "failed" || (run.status === "failed" && last !== undefined && /^over budget/.test(last)) ? last : undefined;
3099
+ const failureFacts = s.status === "failed" ? failureFactsOf(s) : undefined;
3086
3100
  return {
3087
3101
  agent: s.agent,
3088
3102
  group: s.group,
@@ -3092,6 +3106,7 @@ export function summarizeRun(run) {
3092
3106
  ...(s.computeSecs !== undefined ? { computeSecs: s.computeSecs } : {}),
3093
3107
  ...(s.skipReason ? { skipReason: s.skipReason } : {}),
3094
3108
  ...(error ? { error: error.slice(0, 500) } : {}),
3109
+ ...(failureFacts ? { failureFacts } : {}),
3095
3110
  ...(s.item ? { item: s.item } : {}),
3096
3111
  ...(s.waitFor ? { waitFor: s.waitFor } : {}),
3097
3112
  ...(s.ask ? { ask: s.ask } : {}),
@@ -3405,11 +3420,26 @@ export function runFailure(run) {
3405
3420
  if (run.status !== "failed")
3406
3421
  return null;
3407
3422
  const step = run.steps.find((s) => s.status === "failed");
3408
- if (!step)
3423
+ if (!step) {
3424
+ // A run can fail with no failed step: a budget hit or a stop between
3425
+ // groups writes its error onto the last step that ran (FOL-124).
3426
+ if (run.stopRequested) {
3427
+ const reason = `stopped by ${run.stoppedBy ?? "a person"}`;
3428
+ return { agent: run.steps.findLast((s) => s.status === "completed")?.agent ?? run.steps[0]?.agent ?? "run", reason, ...explainFailure(reason, null) };
3429
+ }
3430
+ const holder = run.steps.findLast((s) => s.events.some((e) => e.type === "error" && /^over budget/.test(e.text)));
3431
+ const text = holder?.events.filter((e) => e.type === "error" && /^over budget/.test(e.text)).at(-1)?.text;
3432
+ if (holder && text)
3433
+ return { agent: holder.agent, reason: text, ...explainFailure(text, null) };
3409
3434
  return null;
3435
+ }
3410
3436
  const errors = step.events.filter((e) => e.type === "error");
3411
3437
  const last = errors[errors.length - 1];
3412
- return { agent: step.agent, reason: last?.text ?? "failed without an error event" };
3438
+ const raw = last?.text ?? "failed without an error event";
3439
+ // The customer's sentence, its class and its fix (failure.ts, FOL-124).
3440
+ // A security stop's reason is that sentence too: nothing else is said.
3441
+ const explained = explainFailure(raw, step);
3442
+ return { agent: step.agent, reason: explained.kind === "security" ? explained.message : raw, ...explained };
3413
3443
  }
3414
3444
  /**
3415
3445
  * The one-line outcome, pulled out of the reply that already says it.
@@ -11,6 +11,7 @@
11
11
  // None of them evaluates anything. A flow that chains on another does not
12
12
  // read that run's fields; it receives what the run concluded, as text, and
13
13
  // an agent reads it — the same rule as every other handoff in the format.
14
+ import { opsLog, opsError } from "./ops-log.js";
14
15
  import crypto from "node:crypto";
15
16
  import { platform } from "./platform.js";
16
17
  import { refusalCode } from "./trigger-log.js";
@@ -87,7 +88,7 @@ export async function fireChainedFlows(tenant, workspace, finished) {
87
88
  try {
88
89
  const gate = await platform.admitTrigger(tenant, workspace, flow, { body, tag: "previous_run", fields: chainFields(finished) });
89
90
  if (!gate.admit) {
90
- console.log(`[foldrun] trigger: flow — ${tenant}/${workspace}/${flow.name} not started: ${gate.detail}`);
91
+ opsLog("info", "trigger.flow_not_started", { tenant, workspace, flow: flow.name, reason: gate.reason });
91
92
  continue;
92
93
  }
93
94
  try {
@@ -97,7 +98,7 @@ export async function fireChainedFlows(tenant, workspace, finished) {
97
98
  `after:${finished.flow}`,
98
99
  ], null, finished.test ? { test: true } : {});
99
100
  started.push(run.id);
100
- console.log(`[foldrun] trigger: flow — ${tenant}/${workspace}/${flow.name} started after ${finished.flow} ${finished.status}`);
101
+ opsLog("info", "trigger.flow_started", { tenant, workspace, flow: flow.name, runId: run.id, kind: "previous_run", outcome: finished.status });
101
102
  }
102
103
  catch (err) {
103
104
  await platform.rollbackTrigger(tenant, workspace, flow, { reason: err instanceof Error ? err.message : String(err), code: refusalCode(err) });
@@ -105,7 +106,7 @@ export async function fireChainedFlows(tenant, workspace, finished) {
105
106
  }
106
107
  }
107
108
  catch (err) {
108
- console.error(`[foldrun] trigger: flow — ${tenant}/${workspace}/${flow.name}:`, err instanceof Error ? err.message : err);
109
+ opsError("trigger.flow_failed", err, { tenant, workspace, flow: flow.name });
109
110
  }
110
111
  }
111
112
  return started;
@@ -152,7 +153,7 @@ export async function fireStorageTriggers(tenant, workspace, paths, by) {
152
153
  // forty runs — which is exactly what `debounce:` is for.
153
154
  const gate = await platform.admitTrigger(tenant, workspace, flow, { body, tag: "storage_event", fields: { by, paths: hits } });
154
155
  if (!gate.admit) {
155
- console.log(`[foldrun] trigger: storage — ${tenant}/${workspace}/${flow.name} not started: ${gate.detail}`);
156
+ opsLog("info", "trigger.storage_not_started", { tenant, workspace, flow: flow.name, reason: gate.reason });
156
157
  continue;
157
158
  }
158
159
  try {
@@ -167,7 +168,7 @@ export async function fireStorageTriggers(tenant, workspace, paths, by) {
167
168
  }
168
169
  }
169
170
  catch (err) {
170
- console.error(`[foldrun] trigger: storage — ${tenant}/${workspace}/${flow.name}:`, err instanceof Error ? err.message : err);
171
+ opsError("trigger.storage_failed", err, { tenant, workspace, flow: flow.name });
171
172
  }
172
173
  }
173
174
  return started;
@@ -1,6 +1,7 @@
1
1
  // Per-flow webhook tokens, derived rather than stored: HMAC of the flow's
2
2
  // identity under the install's secret key. Stable across restarts, unique
3
3
  // per flow, and rotating FOLDRUN_SECRET_KEY invalidates every hook at once.
4
+ import { opsLog } from "./ops-log.js";
4
5
  import fs from "node:fs";
5
6
  import path from "node:path";
6
7
  import { workspaceDir } from "./store.js";
@@ -171,8 +172,8 @@ function noteRefusal(tenant, workspace, delivery) {
171
172
  seen.since++;
172
173
  return;
173
174
  }
174
- const more = seen?.since ? ` (and ${seen.since} more since the last note)` : "";
175
- console.warn(`[hooks] refused a delivery to ${key}/${delivery.flow}: ${delivery.outcome}${more}`);
175
+ // count: this one and those refused since the last note.
176
+ opsLog("warn", "webhook.delivery_refused", { tenant, workspace, flow: delivery.flow, outcome: delivery.outcome, count: (seen?.since ?? 0) + 1 });
176
177
  refusalNotes.set(key, { at: now, since: 0 });
177
178
  if (refusalNotes.size > 10_000)
178
179
  refusalNotes.clear(); // bounded: a note lost beats memory
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foldrun/core",
3
- "version": "15.0.0",
3
+ "version": "16.0.0",
4
4
  "description": "Agents are just folders. The format, the runner, the checks.",
5
5
  "license": "FSL-1.1-ALv2",
6
6
  "type": "module",
@@ -19,6 +19,7 @@
19
19
  ".",
20
20
  "./a2a-client",
21
21
  "./a2a-publish",
22
+ "./a2a-reach",
22
23
  "./a2a-remotes",
23
24
  "./agents-md",
24
25
  "./browser-pod",
@@ -8,6 +8,7 @@
8
8
  // examples: ["Leads for dentists in Perth"]
9
9
  // public_card: false # true: the card is readable without a key
10
10
  // input: { type: object, required: [city], properties: { city: { type: string } } }
11
+ // accept_risk: [researcher] # agents an admin accepted holding a secret while running code
11
12
  //
12
13
  // Publishing is the owner's decision, so it is written in the flow and nowhere
13
14
  // else, and changing it needs workspace:manage (foldrun-web
@@ -31,6 +32,11 @@ export interface A2aPublication {
31
32
  publicCard: boolean;
32
33
  /** A JSON Schema the request's data part must satisfy; null = any (or none). */
33
34
  input: Record<string, unknown> | boolean | null;
35
+ /** The agents of this flow an admin accepted holding a secret while they
36
+ * can run code (FOL-112): their answer goes back to the caller, so the
37
+ * platform refuses to publish such a flow unless each is named here.
38
+ * Absent when the block does not say `accept_risk:`. */
39
+ acceptRisk?: string[];
34
40
  }
35
41
 
36
42
  /** The bounds on what is published, and on what a caller may send. */
@@ -48,9 +54,14 @@ export const A2A_LIMITS = {
48
54
  /** What a task's answer carries back. */
49
55
  resultChars: 64_000,
50
56
  resultDataBytes: 256_000,
57
+ /** Agents named under accept_risk. */
58
+ acceptRisk: 50,
51
59
  } as const;
52
60
 
53
- const KEYS = ["publish", "name", "description", "examples", "public_card", "input"] as const;
61
+ /** One agent name: one path segment, as an agent's folder is. */
62
+ const ONE_NAME = /^[^/\\\0\s]+$/;
63
+
64
+ const KEYS = ["publish", "name", "description", "examples", "public_card", "input", "accept_risk"] as const;
54
65
 
55
66
  /** What is wrong with an `a2a:` value, each as a sentence. Empty: fine (or absent). */
56
67
  export function a2aPublishProblems(v: unknown): string[] {
@@ -88,6 +99,11 @@ export function a2aPublishProblems(v: unknown): string[] {
88
99
  if (size > A2A_LIMITS.inputSchemaBytes) out.push(`\`input\` is larger than ${A2A_LIMITS.inputSchemaBytes} bytes as JSON`);
89
100
  }
90
101
  }
102
+ if (o.accept_risk !== undefined && o.accept_risk !== null) {
103
+ const v = o.accept_risk;
104
+ if (!Array.isArray(v) || v.some((e) => typeof e !== "string" || !ONE_NAME.test(e.trim()))) out.push("`accept_risk` should be a list of agent names — the agents an admin accepted holding a secret while they can run code");
105
+ else if (v.length > A2A_LIMITS.acceptRisk) out.push(`\`accept_risk\` names more than ${A2A_LIMITS.acceptRisk} agents`);
106
+ }
91
107
  return out;
92
108
  }
93
109
 
@@ -111,6 +127,8 @@ export function parseA2aPublish(v: unknown): A2aPublication | null {
111
127
  examples: Array.isArray(o.examples) ? (o.examples as string[]).map((e) => e.trim()) : [],
112
128
  publicCard: o.public_card === true,
113
129
  input: o.input === undefined || o.input === null ? null : (o.input as Record<string, unknown> | boolean),
130
+ // Only when written: a block without it reads as it did before 5 Nov 2026.
131
+ ...(Array.isArray(o.accept_risk) ? { acceptRisk: [...new Set((o.accept_risk as string[]).map((e) => e.trim()))] } : {}),
114
132
  };
115
133
  }
116
134