@foldrun/core 15.1.0 → 16.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/src/a2a-publish.d.ts +7 -0
  2. package/dist/src/a2a-publish.js +15 -1
  3. package/dist/src/a2a-reach.d.ts +156 -0
  4. package/dist/src/a2a-reach.js +446 -0
  5. package/dist/src/browse-egress.d.ts +1 -1
  6. package/dist/src/browse-egress.js +7 -6
  7. package/dist/src/env-names.d.ts +12 -0
  8. package/dist/src/env-names.js +49 -0
  9. package/dist/src/failure.d.ts +92 -0
  10. package/dist/src/failure.js +294 -0
  11. package/dist/src/frontmatter-fields.js +1 -1
  12. package/dist/src/install-helper.js +10 -5
  13. package/dist/src/network.js +1 -1
  14. package/dist/src/ops-log.js +4 -0
  15. package/dist/src/otel.d.ts +16 -1
  16. package/dist/src/otel.js +121 -5
  17. package/dist/src/run-container.d.ts +55 -3
  18. package/dist/src/run-container.js +109 -17
  19. package/dist/src/run-event.d.ts +179 -0
  20. package/dist/src/run-event.js +473 -0
  21. package/dist/src/runner.js +8 -1
  22. package/dist/src/runtime.d.ts +113 -16
  23. package/dist/src/runtime.js +528 -44
  24. package/dist/src/scan.js +80 -18
  25. package/dist/src/starter.js +1 -1
  26. package/dist/src/store.d.ts +25 -3
  27. package/dist/src/store.js +40 -10
  28. package/package.json +2 -1
  29. package/src/a2a-publish.ts +19 -1
  30. package/src/a2a-reach.ts +503 -0
  31. package/src/browse-egress.ts +8 -7
  32. package/src/env-names.ts +53 -0
  33. package/src/failure.ts +368 -0
  34. package/src/frontmatter-fields.ts +1 -1
  35. package/src/install-helper.ts +10 -5
  36. package/src/network.ts +1 -1
  37. package/src/ops-log.ts +4 -0
  38. package/src/otel.ts +122 -7
  39. package/src/run-container.ts +112 -21
  40. package/src/run-event.ts +563 -0
  41. package/src/runner.ts +8 -1
  42. package/src/runtime.ts +543 -45
  43. package/src/scan.ts +91 -20
  44. package/src/starter.ts +1 -1
  45. package/src/store.ts +59 -11
@@ -0,0 +1,503 @@
1
+ // What an agent behind a published flow can reach, and what a change to it
2
+ // widens (FOL-112, 5 Nov 2026).
3
+ //
4
+ // A flow published over A2A takes its first input from an outside caller,
5
+ // and the last step's answer goes back to that caller. So the answer is a way
6
+ // out: an agent that holds a secret in its sandbox and may run code can be
7
+ // told to `echo $TOKEN` into its reply, with no network at all. Kousha's A2A
8
+ // e2e on dev (v2026.11.01.6) found two gaps around that:
9
+ //
10
+ // N1 check said nothing about such a flow — only the model's refusal kept
11
+ // the test secret in. Now the scanner warns, and the platform refuses
12
+ // to publish a flow (or to make a published one) whose agent holds a
13
+ // secret and runs code, unless an admin lists that agent under the
14
+ // flow's `a2a.accept_risk` (an admin's key, like all of `a2a:`).
15
+ // N2 publishing is an admin's, but an editor could then give the agent
16
+ // behind the flow more tools, secrets or network. Now a change that
17
+ // widens an agent of a published flow is an admin's too.
18
+ //
19
+ // Pure — fronts in, facts out, no fs — so the scanner (files), the platform's
20
+ // write doors (before/after trees) and the dashboard read the same answer.
21
+
22
+ import { refList, refNames } from "./refs.ts";
23
+ import { TOOL_MAP, ownToolNames } from "./tool-names.ts";
24
+ import { resolveNetwork, type NetworkLevel } from "./network.ts";
25
+ import { parseRemotes } from "./a2a-remotes.ts";
26
+ import { isA2aPublished, parseA2aPublish } from "./a2a-publish.ts";
27
+ import { configMatter } from "./matter.ts";
28
+ import { readBrowseSettings, readSearchSettings, resolveSearch, webConfig } from "./providers.ts";
29
+ import { NEWER_ACTIONS, resolveActionApi } from "./web-actions.ts";
30
+ import { parseFlow, type FlowInfo } from "./store.ts";
31
+
32
+ /** What one agent may reach, as a run would grant it. Every list sorted. */
33
+ export interface AgentReach {
34
+ /** Tool names granted: built-in groups expanded to the SDK's names, the
35
+ * author's own tools by name; `disallowedTools` taken away (by the names
36
+ * it lists, against the expanded ones — the runner's order); a `{X: ask}`
37
+ * entry (approval mode) is not a grant. `permissionMode: plan` leaves the
38
+ * read group and the author's own tools (the runner keeps API and script
39
+ * tools in plan mode), never Bash. */
40
+ tools: string[];
41
+ /** Bash is granted: it can run any code in its sandbox — read its
42
+ * environment, the files, and put what it found in its answer. */
43
+ runsCode: boolean;
44
+ /** Secrets that reach its sandbox's environment, as runner.ts declares
45
+ * them: its own `secrets:`; the ones its `apis:` name as `${NAME}`; a
46
+ * granted folder tool's `secrets:` and `${NAME}`s, when that tool's file
47
+ * is known; and the key of a web provider its (or its workspace's) `web:`
48
+ * names — `web: {search: exa}` declares EXA_API_KEY. A secret bound to sites is
49
+ * still counted: the scanner cannot see binding, and the binding is the
50
+ * vault's, changed elsewhere. */
51
+ secrets: string[];
52
+ network: { level: NetworkLevel; hosts: string[] };
53
+ /** name → the spec as written (stable JSON): a changed spec can point
54
+ * somewhere new, so it counts as a change. */
55
+ apis: Record<string, string>;
56
+ mcpServers: Record<string, string>;
57
+ /** name → card URL. */
58
+ remotes: Record<string, string>;
59
+ /** name → the entry as written (stable JSON): a new script, or a changed
60
+ * command, is a change. */
61
+ scripts: Record<string, string>;
62
+ /** The author's own folder tools named in `tools:` → their definition as
63
+ * written (stable JSON), when the file is known: a changed base URL or
64
+ * MCP server is a change, as an inline API's is. */
65
+ toolSpecs: Record<string, string>;
66
+ subagents: string[];
67
+ /** Hooks that run at its tool calls — its own and its workspace's. Fewer
68
+ * is wider: a hook is a gate. */
69
+ hooks: string[];
70
+ /** permissionMode: plan — read-only until a person approves. */
71
+ plan: boolean;
72
+ /** sandbox: own — delegated to, it runs in its own sandbox with its own
73
+ * tools, secrets and network rather than inside its parent's caps. */
74
+ ownSandbox: boolean;
75
+ }
76
+
77
+ export interface ReachContext {
78
+ /** The workspace AGENTS.md frontmatter (network:, hooks:). */
79
+ workspace?: Record<string, unknown> | null;
80
+ /** The account AGENTS.md's `network:`. */
81
+ accountNetwork?: unknown;
82
+ /** A folder tool's frontmatter by name, when known — for its `secrets:`. */
83
+ toolDefs?: ReadonlyMap<string, Record<string, unknown>>;
84
+ }
85
+
86
+ const SECRET_NAME = /^[A-Z][A-Z0-9_]*$/;
87
+
88
+ /** Same value, whatever order a mapping's keys were written in. */
89
+ function stable(value: unknown): string {
90
+ if (value === undefined) return "undefined";
91
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
92
+ if (value instanceof Date) return JSON.stringify(value.toISOString());
93
+ if (Array.isArray(value)) return `[${value.map(stable).join(",")}]`;
94
+ const o = value as Record<string, unknown>;
95
+ return `{${Object.keys(o).sort().map((k) => `${JSON.stringify(k)}:${stable(o[k])}`).join(",")}}`;
96
+ }
97
+
98
+ const sorted = (xs: Iterable<string>) => [...new Set(xs)].sort();
99
+ const listOf = (v: unknown): string[] => (Array.isArray(v) ? v.map(String) : typeof v === "string" && v.trim() ? v.split(",").map((s) => s.trim()).filter(Boolean) : []);
100
+
101
+ /** What this agent's frontmatter grants, read the way runner.ts does. */
102
+ export function agentReach(front: Record<string, unknown>, ctx: ReachContext = {}): AgentReach {
103
+ const plan = front.permissionMode === "plan";
104
+ const denied = new Set(refNames(front.disallowedTools));
105
+ const granted: string[] = [];
106
+ const own: string[] = [];
107
+ for (const ref of refList(front.tools)) {
108
+ if (ref.mode === "ask") continue; // approval mode: the runner does not grant it
109
+ if (!ref.linked && TOOL_MAP[ref.name]) granted.push(...TOOL_MAP[ref.name]!);
110
+ else {
111
+ granted.push(ref.name);
112
+ if (ref.linked || !TOOL_MAP[ref.name]) own.push(ref.name);
113
+ }
114
+ }
115
+ // `install` is every agent's unless plan mode or disallowedTools: [install]
116
+ // takes it away (runner.ts, install-tool.ts): dropping that deny widens.
117
+ if (!plan) granted.push("install");
118
+ const tools = plan ? sorted([...TOOL_MAP.read!, ...own].filter((t) => !denied.has(t) && t !== "Bash" && t !== "install")) : sorted(granted.filter((t) => !denied.has(t)));
119
+ const runsCode = tools.includes("Bash");
120
+
121
+ const apis: Record<string, string> = {};
122
+ if (Array.isArray(front.apis)) {
123
+ front.apis.forEach((a, i) => {
124
+ const name = a && typeof a === "object" && typeof (a as { name?: unknown }).name === "string" ? (a as { name: string }).name : `#${i + 1}`;
125
+ apis[name] = stable(a);
126
+ });
127
+ }
128
+ const mcpServers: Record<string, string> = {};
129
+ if (front.mcpServers && typeof front.mcpServers === "object" && !Array.isArray(front.mcpServers)) {
130
+ for (const [k, v] of Object.entries(front.mcpServers as Record<string, unknown>)) mcpServers[k] = stable(v);
131
+ }
132
+ const remotes: Record<string, string> = {};
133
+ for (const r of parseRemotes(front.remotes)) remotes[r.name] = r.card;
134
+
135
+ const secrets = new Set(listOf(front.secrets));
136
+ const named = (v: unknown) => {
137
+ for (const m of (JSON.stringify(v ?? null) ?? "").matchAll(/\$\{([A-Z][A-Z0-9_]*)\}/g)) secrets.add(m[1]!);
138
+ };
139
+ named(front.apis);
140
+ // Every folder tool `tools:` names — ask-mode and disallowed ones too: the
141
+ // runner resolves them (ownToolNames) and loads their secrets into the
142
+ // step's environment before it filters what may be called (Codex review).
143
+ const toolSpecs: Record<string, string> = {};
144
+ for (const name of ownToolNames(front)) {
145
+ const def = ctx.toolDefs?.get(name);
146
+ if (!def) continue;
147
+ toolSpecs[name] = stable(def);
148
+ for (const s of listOf(def.secrets)) if (SECRET_NAME.test(s)) secrets.add(s);
149
+ named(def);
150
+ }
151
+ for (const s of webSecrets(front, ctx.workspace ?? undefined)) secrets.add(s);
152
+
153
+ const scripts: Record<string, string> = {};
154
+ for (const [i, e] of (Array.isArray(front.scripts) ? front.scripts : listOf(front.scripts)).entries()) {
155
+ const name = typeof e === "string" ? e : e && typeof e === "object" && typeof (e as { name?: unknown }).name === "string" ? (e as { name: string }).name : `#${i + 1}`;
156
+ scripts[name] = stable(e);
157
+ }
158
+
159
+ // The runner's own test (runner.ts, the network: lease): the web tool
160
+ // granted, and fetch or browse among its actions (all, when unsaid).
161
+ let actions: string[] | null = null;
162
+ try {
163
+ actions = webConfig(front, ctx.workspace ?? undefined).actions;
164
+ } catch {
165
+ actions = null;
166
+ }
167
+ const readsWeb = tools.includes("web") && (!actions || actions.some((a) => a === "fetch" || a === "browse"));
168
+ // Hosts a grant implies (an API's base, an MCP server's url, a remote's
169
+ // card): the runner adds them to the list, so a new one is a wider list.
170
+ const implied: string[] = [];
171
+ const hostOf = (u: unknown) => {
172
+ if (typeof u !== "string") return;
173
+ try {
174
+ implied.push(new URL(u).hostname);
175
+ } catch {
176
+ // not a URL: nothing implied
177
+ }
178
+ };
179
+ for (const a of Array.isArray(front.apis) ? front.apis : []) hostOf((a as { base?: unknown } | null)?.base);
180
+ for (const m of Object.values((front.mcpServers && typeof front.mcpServers === "object" ? front.mcpServers : {}) as Record<string, { url?: unknown } | null>)) hostOf(m?.url);
181
+ for (const r of Object.values(remotes)) hostOf(r);
182
+ for (const name of Object.keys(toolSpecs)) {
183
+ const def = ctx.toolDefs?.get(name);
184
+ hostOf(def?.base);
185
+ hostOf(def?.url);
186
+ }
187
+ const net = resolveNetwork({ account: ctx.accountNetwork, workspace: ctx.workspace?.network, agent: front.network, readsWeb, implied });
188
+
189
+ return {
190
+ tools,
191
+ runsCode,
192
+ secrets: sorted([...secrets].filter((s) => s.trim())),
193
+ network: { level: net.level, hosts: sorted(net.hosts) },
194
+ apis,
195
+ mcpServers,
196
+ remotes,
197
+ scripts,
198
+ toolSpecs,
199
+ subagents: sorted(refNames(front.subagents)),
200
+ hooks: sorted([...refNames(front.hooks), ...refNames(ctx.workspace?.hooks)]),
201
+ plan,
202
+ ownSandbox: front.sandbox === "own",
203
+ };
204
+ }
205
+
206
+ /** The vault names a `web:` block declares — runner.ts's `declared` list:
207
+ * a direct search, fetch or browse API's key, a newer action's provider
208
+ * key, your own proxy for a vendor's session. Read loosely: a block that
209
+ * does not resolve declares nothing (check reports it). */
210
+ function webSecrets(front: Record<string, unknown>, workspace?: Record<string, unknown>): string[] {
211
+ try {
212
+ const web = webConfig(front, workspace);
213
+ const out: string[] = [];
214
+ const browse = readBrowseSettings(web.raw.browse);
215
+ const proxy = (browse.settings as { vendor_session?: { proxy?: unknown } }).vendor_session?.proxy;
216
+ if (proxy && typeof proxy === "object" && typeof (proxy as { own?: unknown }).own === "string") out.push((proxy as { own: string }).own);
217
+ for (const c of [resolveSearch(readSearchSettings(web.raw.search).rest, "search"), resolveSearch(web.raw.fetch, "fetch"), resolveSearch(browse.rest, "browse")]) {
218
+ if (c.shape === "direct" && c.secret && !c.error) out.push(c.secret);
219
+ }
220
+ for (const action of NEWER_ACTIONS) {
221
+ const c = resolveActionApi(action, web.raw[action]) as { provider?: string | null; secret?: string };
222
+ if (c.provider && c.secret) out.push(c.secret);
223
+ }
224
+ return out.filter((n) => SECRET_NAME.test(n));
225
+ } catch {
226
+ return [];
227
+ }
228
+ }
229
+
230
+ const OPENNESS: Record<NetworkLevel, number> = { none: 0, trusted: 1, open: 2 };
231
+
232
+ /**
233
+ * What `after` can reach that `before` could not, one phrase each — empty
234
+ * when nothing widened. `before` null: the agent was not there (or not behind
235
+ * the flow), so everything it can reach is new.
236
+ */
237
+ export function reachWidening(before: AgentReach | null, after: AgentReach): string[] {
238
+ const out: string[] = [];
239
+ const added = (what: string, a: string[], b: string[]) => {
240
+ const extra = b.filter((x) => !a.includes(x));
241
+ if (extra.length) out.push(`${what} ${extra.join(", ")}`);
242
+ };
243
+ const b = before;
244
+ if (!b) {
245
+ if (after.tools.length) out.push(`tools ${after.tools.join(", ")}`);
246
+ if (after.secrets.length) out.push(`secrets ${after.secrets.join(", ")}`);
247
+ if (after.network.level !== "none") out.push(`network ${after.network.level}`);
248
+ for (const k of ["apis", "mcpServers", "remotes"] as const) if (Object.keys(after[k]).length) out.push(`${k} ${Object.keys(after[k]).sort().join(", ")}`);
249
+ if (Object.keys(after.scripts).length) out.push(`scripts ${Object.keys(after.scripts).sort().join(", ")}`);
250
+ if (after.subagents.length) out.push(`subagents ${after.subagents.join(", ")}`);
251
+ return out.length ? out : ["a new agent behind the flow"];
252
+ }
253
+ added("tools", b.tools, after.tools);
254
+ added("secrets", b.secrets, after.secrets);
255
+ if (OPENNESS[after.network.level] > OPENNESS[b.network.level]) out.push(`network ${b.network.level} → ${after.network.level}`);
256
+ else if (after.network.level !== "open") added("network sites", b.network.hosts, after.network.hosts);
257
+ for (const k of ["apis", "mcpServers", "remotes", "scripts", "toolSpecs"] as const) {
258
+ const changed = Object.keys(after[k]).filter((n) => b[k][n] !== after[k][n]).sort();
259
+ // A new folder tool is already a new tool above; here only a changed one.
260
+ const said = k === "toolSpecs" ? changed.filter((n) => n in b[k]) : changed;
261
+ if (said.length) out.push(`${k === "toolSpecs" ? "tools" : k} ${said.map((n) => (n in b[k] ? `${n} (changed)` : n)).join(", ")}`);
262
+ }
263
+ added("subagents", b.subagents, after.subagents);
264
+ const gone = b.hooks.filter((h) => !after.hooks.includes(h));
265
+ if (gone.length) out.push(`hooks removed: ${gone.join(", ")}`);
266
+ if (b.plan && !after.plan) out.push("permissionMode: plan removed");
267
+ if (!b.ownSandbox && after.ownSandbox) out.push("sandbox: own");
268
+ return out;
269
+ }
270
+
271
+ /**
272
+ * Every agent a run of this flow may put to work: each step's agent, its
273
+ * `on-fail:` rescuer and its `delegate:` choices; the steps of every
274
+ * `[[flow:…]]` it runs, all the way down; and the sub-agents each of those
275
+ * may delegate to. A sub-agent's tools are capped by its parent's in a shared
276
+ * sandbox but not with `sandbox: own`, so each one counts. `subagentsOf`
277
+ * names an agent's `subagents:` (null: no such agent); `flowOf` reads another
278
+ * flow by name (null: none). Sorted.
279
+ */
280
+ export function flowAgents(
281
+ flow: Pick<FlowInfo, "steps">,
282
+ subagentsOf: (agent: string) => string[] | null,
283
+ flowOf: (name: string) => Pick<FlowInfo, "steps"> | null = () => null,
284
+ ): string[] {
285
+ const seen = new Set<string>();
286
+ const queue: string[] = [];
287
+ const flowsSeen = new Set<string>();
288
+ const walk = (f: Pick<FlowInfo, "steps">) => {
289
+ for (const s of f.steps ?? []) {
290
+ if (s.subflow) {
291
+ if (flowsSeen.has(s.subflow)) continue;
292
+ flowsSeen.add(s.subflow);
293
+ const sub = flowOf(s.subflow);
294
+ if (sub) walk(sub);
295
+ continue;
296
+ }
297
+ for (const n of [s.agent, ...(s.onFail ? [s.onFail] : []), ...(s.delegate ?? [])]) if (n) queue.push(n);
298
+ }
299
+ };
300
+ walk(flow);
301
+ while (queue.length) {
302
+ const n = queue.shift()!;
303
+ if (seen.has(n)) continue;
304
+ seen.add(n);
305
+ for (const s of subagentsOf(n) ?? []) if (!seen.has(s)) queue.push(s);
306
+ }
307
+ return [...seen].sort();
308
+ }
309
+
310
+ /** The agents an admin accepted holding a secret while running code in this
311
+ * published flow (`a2a.accept_risk`). */
312
+ export function acceptedRisk(a2a: unknown): string[] {
313
+ return parseA2aPublish(a2a)?.acceptRisk ?? [];
314
+ }
315
+
316
+ /** Is this flow open to A2A callers? (Its parsed `a2a:`.) */
317
+ export function publishedFlow(flow: Pick<FlowInfo, "a2a">): boolean {
318
+ return isA2aPublished(flow.a2a);
319
+ }
320
+
321
+ /** One agent of a published flow that holds a secret and may run code. */
322
+ export interface SecretCodeExposure {
323
+ agent: string;
324
+ secrets: string[];
325
+ accepted: boolean;
326
+ }
327
+
328
+ /** The agents of a published flow that hold a secret and run code — each
329
+ * one a way for a caller to have the secret put in the answer. */
330
+ export function secretCodeExposures(agents: string[], reachOf: (agent: string) => AgentReach | null, accepted: string[]): SecretCodeExposure[] {
331
+ const out: SecretCodeExposure[] = [];
332
+ for (const a of agents) {
333
+ const r = reachOf(a);
334
+ if (!r || !r.runsCode || !r.secrets.length) continue;
335
+ out.push({ agent: a, secrets: r.secrets, accepted: accepted.includes(a) });
336
+ }
337
+ return out;
338
+ }
339
+
340
+ /** The sentence a refusal and the dashboard say about one exposure. */
341
+ export function secretCodeSentence(flow: string, e: Pick<SecretCodeExposure, "agent" | "secrets">): string {
342
+ const held = `${e.secrets.slice(0, 3).join(", ")}${e.secrets.length > 3 ? ", …" : ""}`;
343
+ return `${e.agent} holds ${held} and can run code (Bash), and ${flow} is published over A2A — its answer goes back to the outside caller, who can ask for the secret in it`;
344
+ }
345
+
346
+ // ── a whole tree: the scanner's files, a write's before and after ───────────
347
+
348
+ export interface TreeFile {
349
+ /** Workspace-relative (`agents/x/agent.md`), or `library/…` for the
350
+ * account's library. */
351
+ path: string;
352
+ content: string;
353
+ }
354
+
355
+ /** The A2A facts of one workspace tree. */
356
+ export interface A2aTree {
357
+ /** Every flow that parses, by name. */
358
+ flows: Map<string, { file: string; info: FlowInfo }>;
359
+ /** An agent's reach, or null when the tree has no such agent. */
360
+ reachOf: (agent: string) => AgentReach | null;
361
+ /** The agents a run of this flow may put to work (flowAgents). */
362
+ agentsOf: (flow: string) => string[];
363
+ }
364
+
365
+ /** Frontmatter as the runtime reads an agent, a flow or AGENTS.md (job
366
+ * blocks folded): null when there is none or YAML cannot read it. */
367
+ function frontOf(content: string): Record<string, unknown> | null {
368
+ if (!/^\uFEFF?---\r?\n/.test(content)) return null;
369
+ try {
370
+ const d = configMatter(content).data;
371
+ return d && typeof d === "object" && !Array.isArray(d) ? (d as Record<string, unknown>) : null;
372
+ } catch {
373
+ return null;
374
+ }
375
+ }
376
+
377
+ const AGENT_FILE = /^agents\/([^/]+)\/agent\.md$/;
378
+ const CLAUDE_AGENT = /^\.(?:claude|agents)\/agents\/([^/]+)\.md$/;
379
+ const FLOW_FILE = /^flows\/([^/]+)\.md$/;
380
+ const TOOL_FILE = /^(?:library\/)?tools\/(?:([^/]+)\/tool|([^/]+))\.md$/;
381
+
382
+ /**
383
+ * Read a workspace tree (and, mixed in under `library/`, the account's
384
+ * library tools) as A2A sees it. An agent at agents/<n>/agent.md wins over a
385
+ * Claude Code file of the same name, as a deploy imports it; a workspace
386
+ * tool wins over the library's.
387
+ */
388
+ export function a2aTree(files: TreeFile[], opts: { accountNetwork?: unknown } = {}): A2aTree {
389
+ const agents = new Map<string, Record<string, unknown>>();
390
+ const claude = new Map<string, Record<string, unknown>>();
391
+ const tools = new Map<string, Record<string, unknown>>();
392
+ const libTools = new Map<string, Record<string, unknown>>();
393
+ const flows = new Map<string, { file: string; info: FlowInfo }>();
394
+ let workspace: Record<string, unknown> | null = null;
395
+ let project: Record<string, unknown> | null = null;
396
+ for (const f of files) {
397
+ const rel = f.path.replaceAll("\\", "/").replace(/^\.\//, "");
398
+ let m: RegExpExecArray | null;
399
+ if (rel === "AGENTS.md") workspace = frontOf(f.content) ?? {};
400
+ else if (rel === "project.md") project = frontOf(f.content) ?? {};
401
+ else if ((m = AGENT_FILE.exec(rel))) agents.set(m[1]!, frontOf(f.content) ?? {});
402
+ else if ((m = CLAUDE_AGENT.exec(rel))) claude.set(m[1]!, frontOf(f.content) ?? {});
403
+ else if ((m = FLOW_FILE.exec(rel))) {
404
+ try {
405
+ const info = parseFlow(`${m[1]}.md`, f.content);
406
+ if (!flows.has(info.name)) flows.set(info.name, { file: rel, info });
407
+ } catch {
408
+ // a flow that does not parse runs nothing; check reports it
409
+ }
410
+ } else if ((m = TOOL_FILE.exec(rel))) {
411
+ const d = frontOf(f.content) ?? {};
412
+ const name = typeof d.name === "string" && d.name.trim() ? d.name.trim() : (m[1] ?? m[2])!;
413
+ (rel.startsWith("library/") ? libTools : tools).set(name, d);
414
+ }
415
+ }
416
+ for (const [n, d] of claude) if (!agents.has(n)) agents.set(n, d);
417
+ const toolDefs = new Map([...libTools, ...tools]);
418
+ const ws = workspace ?? project;
419
+ const reaches = new Map<string, AgentReach>();
420
+ const reachOf = (agent: string): AgentReach | null => {
421
+ const front = agents.get(agent);
422
+ if (!front) return null;
423
+ let r = reaches.get(agent);
424
+ if (!r) reaches.set(agent, (r = agentReach(front, { workspace: ws, accountNetwork: opts.accountNetwork, toolDefs })));
425
+ return r;
426
+ };
427
+ const agentsOf = (flow: string): string[] => {
428
+ const f = flows.get(flow);
429
+ if (!f) return [];
430
+ return flowAgents(f.info, (a) => (agents.has(a) ? reachOf(a)!.subagents : null), (n) => flows.get(n)?.info ?? null);
431
+ };
432
+ return { flows, reachOf, agentsOf };
433
+ }
434
+
435
+ /** One published flow's secret-and-code exposures in a tree (empty when it
436
+ * is not published, or has none). */
437
+ export function flowSecretCode(tree: A2aTree, flow: string): SecretCodeExposure[] {
438
+ const f = tree.flows.get(flow);
439
+ if (!f || !isA2aPublished(f.info.a2a)) return [];
440
+ return secretCodeExposures(tree.agentsOf(flow), tree.reachOf, f.info.a2a.acceptRisk ?? []);
441
+ }
442
+
443
+ /** What a write does to the flows published over A2A, compared tree to tree. */
444
+ export interface A2aWriteEffect {
445
+ /** An agent behind a flow published before or after the write that can
446
+ * reach more after it: an admin's change (N2). */
447
+ widened: { flow: string; agent: string; what: string[] }[];
448
+ /** An agent of a flow published after the write that holds a secret and
449
+ * runs code, with no `accept_risk` entry, and did not before the write
450
+ * (a new exposure): refused for everyone (N1). One already there is the
451
+ * serve path's to refuse, not a write's: a deploy that leaves it alone
452
+ * still goes through. */
453
+ unaccepted: { flow: string; agent: string; secrets: string[] }[];
454
+ /** `accept_risk` entries the write adds, with what each agent holds then —
455
+ * the audit's record of what was accepted. */
456
+ accepted: { flow: string; agent: string; secrets: string[] }[];
457
+ /** `accept_risk` names the write adds that no agent of the flow answers
458
+ * to: refused, so an entry never waits to cover whatever is given that
459
+ * name next. */
460
+ stale: { flow: string; agents: string[] }[];
461
+ }
462
+
463
+ export function a2aWriteEffect(before: A2aTree, after: A2aTree): A2aWriteEffect {
464
+ const out: A2aWriteEffect = { widened: [], unaccepted: [], accepted: [], stale: [] };
465
+ const names = [...new Set([...before.flows.keys(), ...after.flows.keys()])].sort();
466
+ for (const flow of names) {
467
+ const b = before.flows.get(flow);
468
+ const a = after.flows.get(flow);
469
+ const pubBefore = Boolean(b && isA2aPublished(b.info.a2a));
470
+ const pubAfter = Boolean(a && isA2aPublished(a.info.a2a));
471
+ if (!pubBefore && !pubAfter) continue;
472
+ const agentsBefore = pubBefore ? before.agentsOf(flow) : [];
473
+ const agentsAfter = a ? after.agentsOf(flow) : [];
474
+ // N2 — only a flow that was published already: publishing one is an
475
+ // admin's change by itself (a2a: is policy).
476
+ if (pubBefore && a) {
477
+ for (const agent of agentsAfter) {
478
+ const ra = after.reachOf(agent);
479
+ if (!ra) continue;
480
+ const rb = agentsBefore.includes(agent) ? before.reachOf(agent) : null;
481
+ const what = reachWidening(rb, ra);
482
+ if (what.length) out.widened.push({ flow, agent, what });
483
+ }
484
+ }
485
+ if (!pubAfter || !a) continue;
486
+ const accepted = a.info.a2a?.acceptRisk ?? [];
487
+ const acceptedBefore = pubBefore ? (b!.info.a2a?.acceptRisk ?? []) : [];
488
+ // Stale: a name the write adds that no agent of the flow answers to. One
489
+ // left behind when a step went is not refused — an editor may remove a
490
+ // step and cannot touch a2a: — and the next agent given that name behind
491
+ // a published flow is a widening, an admin's change by itself.
492
+ const listedBefore = b?.info.a2a?.acceptRisk ?? [];
493
+ const stale = accepted.filter((n) => !agentsAfter.includes(n) && !listedBefore.includes(n));
494
+ if (stale.length) out.stale.push({ flow, agents: stale });
495
+ const had = new Set(pubBefore ? secretCodeExposures(agentsBefore, before.reachOf, []).map((e) => e.agent) : []);
496
+ for (const e of secretCodeExposures(agentsAfter, after.reachOf, accepted)) {
497
+ if (e.accepted) {
498
+ if (!acceptedBefore.includes(e.agent)) out.accepted.push({ flow, agent: e.agent, secrets: e.secrets });
499
+ } else if (!had.has(e.agent)) out.unaccepted.push({ flow, agent: e.agent, secrets: e.secrets });
500
+ }
501
+ }
502
+ return out;
503
+ }
@@ -15,11 +15,12 @@
15
15
  // executor can wall the step's network (the k8s tier, with the install's
16
16
  // FOLDRUN_BROWSE_ENFORCE=1 — Platform.confinesBrowsing). Such a step gets the
17
17
  // forward proxy like any other, so its run pod is `filtered`: it reaches the
18
- // egress proxy and DNS and nothing else, and the browser runs inside it, in
19
- // the step's own pod. A client that sets another proxy, a CDP context with
20
- // its own proxyServer, a curl that ignores HTTPS_PROXY — each finds no route,
21
- // never a way round the list. Not covered: DNS lookups through the cluster's
22
- // resolver, which the wall admits and nothing here restricts. browseVerdict
18
+ // egress proxy and nothing else, and the browser runs inside it, in the
19
+ // step's own pod. A client that sets another proxy, a CDP context with its
20
+ // own proxyServer, a curl that ignores HTTPS_PROXY — each finds no route,
21
+ // never a way round the list. DNS is the platform's to wall too (FOL-128:
22
+ // foldrun-platform run-dns.ts, FOLDRUN_RUN_DNS_WALL), and its trace says on
23
+ // a `dns:` line whether this sandbox may look names up. browseVerdict
23
24
  // says, for one step, which of the three ways it goes; everywhere else (no
24
25
  // wall, an open or report-only list) the step browses as it did before
25
26
  // phase 3, and the trace says so.
@@ -59,7 +60,7 @@ export function browseTier(vendor: string | null | undefined): { tier: BrowseTie
59
60
  * report-only install, or an executor that cannot wall the
60
61
  * step's network.
61
62
  * hosted — enforced: the step gets the forward proxy, its pod is walled
62
- * to the egress proxy and DNS, and foldrun's browser runs in it.
63
+ * to the egress proxy, and foldrun's browser runs in it.
63
64
  * refuse — a vendor's browser under a restricted, enforced list on an
64
65
  * install that holds browsing: it browses from the vendor's
65
66
  * network, which nothing here can hold to the list, so the step
@@ -102,7 +103,7 @@ export function browseVerdict(o: {
102
103
  export function browseNetworkLine(policy: NetworkPolicy, vendor: string | null | undefined, opts: { hosted?: boolean } = {}): string {
103
104
  const what = networkLine(policy, true);
104
105
  if (opts.hosted) {
105
- return `${what} — enforced — hosted: the browser runs inside this step's sandbox, whose network reaches only the egress proxy (which holds the list) and DNS, so a page, a script or a changed proxy setting reaches no site off the list; DNS lookups themselves are not restricted.`;
106
+ return `${what} — enforced — hosted: the browser runs inside this step's sandbox, whose network reaches only the egress proxy (which holds the list), so a page, a script or a changed proxy setting reaches no site off the list.`;
106
107
  }
107
108
  const { tier, title } = browseTier(vendor);
108
109
  const now = " — not enforced in this step: it may browse, and browsing does not go through the egress proxy here, so the browser and every other program in this step reach sites directly";
@@ -0,0 +1,53 @@
1
+ // Environment names that steer what a program loads or runs rather than
2
+ // carry data (FOL-130). One list, read twice:
3
+ //
4
+ // - run-container.ts strips them from a run container's root shell before
5
+ // anything runs as root (ROOT_SHELL_GUARD_SH) — that shell's environment is
6
+ // the platform's own (the image's, the pod spec's), so this is a second
7
+ // lock, not the boundary: the step's environment never reaches root at all.
8
+ // - scan.ts warns when a `secrets:` entry is named after one of them
9
+ // (secret/reserved-env-name): a secret is exported to the sandbox under its
10
+ // own name, so a secret called LD_PRELOAD or PATH re-points every program
11
+ // the agent runs, which is almost never what its author meant.
12
+ //
13
+ // Pure data, no imports: both the shell snippet and the scanner load it.
14
+
15
+ /** Names that tell the dynamic loader, a shell or a language runtime what to
16
+ * load or run before the program's own code: prefixes end in `*`. */
17
+ export const LOADER_ENV: readonly string[] = [
18
+ "LD_*",
19
+ "GCONV_PATH",
20
+ "GLIBC_TUNABLES",
21
+ "BASH_ENV",
22
+ "ENV",
23
+ "CDPATH",
24
+ "NODE_OPTIONS",
25
+ "PYTHONPATH",
26
+ "PYTHONHOME",
27
+ "PYTHONSTARTUP",
28
+ "PYTHONUSERBASE",
29
+ "PERL5OPT",
30
+ "PERL5LIB",
31
+ "PERLLIB",
32
+ "RUBYOPT",
33
+ "RUBYLIB",
34
+ ];
35
+
36
+ /** Names every shell and program reads for where to look and who it is.
37
+ * The root shell keeps the image's values of these; a secret named after
38
+ * one still replaces it for every program the agent runs. */
39
+ export const SHELL_ENV: readonly string[] = ["PATH", "IFS", "HOME", "SHELL", "USER", "LOGNAME", "PWD"];
40
+
41
+ /** LOADER_ENV as the arms of a shell `case` (`LD_*|GCONV_PATH|…`). */
42
+ export const LOADER_ENV_CASE = LOADER_ENV.join("|");
43
+
44
+ const matches = (name: string, list: readonly string[]) =>
45
+ list.some((p) => (p.endsWith("*") ? name.startsWith(p.slice(0, -1)) : name === p));
46
+
47
+ /** Why an environment name is not one to give a secret, or null when it is
48
+ * an ordinary name. */
49
+ export function reservedEnvName(name: string): string | null {
50
+ if (matches(name, LOADER_ENV)) return "it tells the loader, the shell or a language runtime what to load into every program the agent starts";
51
+ if (matches(name, SHELL_ENV)) return "every shell and program in the sandbox reads it, and the secret's value replaces the sandbox's own";
52
+ return null;
53
+ }