@foldrun/core 0.3.0 → 0.5.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 (175) hide show
  1. package/README.md +27 -10
  2. package/dist/index.d.ts +3 -0
  3. package/dist/index.js +3 -0
  4. package/dist/src/account.d.ts +45 -0
  5. package/dist/src/account.js +130 -0
  6. package/dist/src/api-tools.d.ts +8 -0
  7. package/dist/src/api-tools.js +22 -4
  8. package/dist/src/approvals.d.ts +104 -1
  9. package/dist/src/approvals.js +192 -2
  10. package/dist/src/browser-pod.d.ts +129 -0
  11. package/dist/src/browser-pod.js +284 -0
  12. package/dist/src/budget.d.ts +32 -0
  13. package/dist/src/budget.js +177 -0
  14. package/dist/src/catalog.js +3 -1
  15. package/dist/src/clock.d.ts +49 -0
  16. package/dist/src/clock.js +121 -0
  17. package/dist/src/completions.js +17 -8
  18. package/dist/src/confine.d.ts +22 -0
  19. package/dist/src/confine.js +224 -4
  20. package/dist/src/deploy.d.ts +33 -0
  21. package/dist/src/deploy.js +145 -6
  22. package/dist/src/egress.d.ts +26 -2
  23. package/dist/src/egress.js +8 -1
  24. package/dist/src/eol.d.ts +2 -0
  25. package/dist/src/eol.js +7 -0
  26. package/dist/src/evals.d.ts +9 -0
  27. package/dist/src/evals.js +26 -13
  28. package/dist/src/flow-lint.d.ts +12 -0
  29. package/dist/src/flow-lint.js +331 -1
  30. package/dist/src/flow-patterns.d.ts +141 -0
  31. package/dist/src/flow-patterns.js +568 -0
  32. package/dist/src/gitrepo.d.ts +18 -0
  33. package/dist/src/gitrepo.js +49 -0
  34. package/dist/src/host-env.d.ts +8 -0
  35. package/dist/src/host-env.js +48 -0
  36. package/dist/src/json-schema.d.ts +12 -0
  37. package/dist/src/json-schema.js +202 -0
  38. package/dist/src/kinds.js +1 -1
  39. package/dist/src/language.d.ts +17 -0
  40. package/dist/src/language.js +55 -0
  41. package/dist/src/layout.d.ts +69 -0
  42. package/dist/src/layout.js +200 -0
  43. package/dist/src/library.d.ts +9 -0
  44. package/dist/src/library.js +43 -4
  45. package/dist/src/limits.d.ts +84 -0
  46. package/dist/src/limits.js +287 -0
  47. package/dist/src/locale.d.ts +47 -0
  48. package/dist/src/locale.js +177 -0
  49. package/dist/src/mail.d.ts +88 -0
  50. package/dist/src/mail.js +245 -0
  51. package/dist/src/model-probe.d.ts +3 -0
  52. package/dist/src/model-probe.js +1 -0
  53. package/dist/src/notify.d.ts +132 -8
  54. package/dist/src/notify.js +360 -58
  55. package/dist/src/openapi.js +5 -3
  56. package/dist/src/operator.d.ts +201 -0
  57. package/dist/src/operator.js +251 -0
  58. package/dist/src/paths.d.ts +33 -0
  59. package/dist/src/paths.js +87 -0
  60. package/dist/src/platform.d.ts +144 -4
  61. package/dist/src/platform.js +27 -3
  62. package/dist/src/provider-health.d.ts +55 -0
  63. package/dist/src/provider-health.js +233 -0
  64. package/dist/src/providers.d.ts +481 -0
  65. package/dist/src/providers.js +1105 -6
  66. package/dist/src/refusal.d.ts +83 -0
  67. package/dist/src/refusal.js +281 -0
  68. package/dist/src/run-container.d.ts +206 -17
  69. package/dist/src/run-container.js +547 -80
  70. package/dist/src/runner.d.ts +179 -10
  71. package/dist/src/runner.js +1423 -169
  72. package/dist/src/runtime.d.ts +52 -0
  73. package/dist/src/runtime.js +493 -58
  74. package/dist/src/script-tools.d.ts +15 -2
  75. package/dist/src/script-tools.js +44 -4
  76. package/dist/src/secret-files.d.ts +6 -5
  77. package/dist/src/secret-files.js +24 -11
  78. package/dist/src/secret-health.d.ts +83 -0
  79. package/dist/src/secret-health.js +177 -0
  80. package/dist/src/secrets.d.ts +38 -1
  81. package/dist/src/secrets.js +197 -96
  82. package/dist/src/starter.d.ts +9 -0
  83. package/dist/src/starter.js +95 -11
  84. package/dist/src/step-exec.d.ts +106 -1
  85. package/dist/src/step-exec.js +558 -85
  86. package/dist/src/step-removal.d.ts +15 -0
  87. package/dist/src/step-removal.js +49 -0
  88. package/dist/src/storage.d.ts +23 -4
  89. package/dist/src/storage.js +125 -23
  90. package/dist/src/store.d.ts +492 -38
  91. package/dist/src/store.js +882 -69
  92. package/dist/src/subagents.d.ts +75 -0
  93. package/dist/src/subagents.js +149 -0
  94. package/dist/src/tar.js +2 -1
  95. package/dist/src/test-mode.d.ts +111 -0
  96. package/dist/src/test-mode.js +285 -0
  97. package/dist/src/tool-names.d.ts +13 -1
  98. package/dist/src/tool-names.js +38 -11
  99. package/dist/src/tool-programs.d.ts +26 -0
  100. package/dist/src/tool-programs.js +172 -0
  101. package/dist/src/tool-test.js +152 -33
  102. package/dist/src/translator.d.ts +8 -2
  103. package/dist/src/translator.js +71 -24
  104. package/dist/src/trigger-log.d.ts +43 -0
  105. package/dist/src/trigger-log.js +122 -0
  106. package/dist/src/triggers.d.ts +23 -0
  107. package/dist/src/triggers.js +101 -12
  108. package/dist/src/untrusted-fetch.d.ts +11 -0
  109. package/dist/src/untrusted-fetch.js +77 -0
  110. package/dist/src/web-actions.d.ts +91 -0
  111. package/dist/src/web-actions.js +199 -0
  112. package/dist/src/webhook.d.ts +19 -3
  113. package/dist/src/webhook.js +50 -11
  114. package/index.ts +3 -0
  115. package/package.json +5 -5
  116. package/src/account.ts +149 -0
  117. package/src/api-tools.ts +32 -4
  118. package/src/approvals.ts +253 -2
  119. package/src/browser-pod.ts +313 -0
  120. package/src/budget.ts +178 -0
  121. package/src/catalog.ts +3 -1
  122. package/src/clock.ts +149 -0
  123. package/src/completions.ts +17 -8
  124. package/src/confine.ts +224 -4
  125. package/src/deploy.ts +137 -6
  126. package/src/egress.ts +32 -4
  127. package/src/eol.ts +7 -0
  128. package/src/evals.ts +36 -11
  129. package/src/flow-lint.ts +371 -1
  130. package/src/flow-patterns.ts +597 -0
  131. package/src/gitrepo.ts +48 -0
  132. package/src/host-env.ts +51 -0
  133. package/src/json-schema.ts +184 -0
  134. package/src/kinds.ts +1 -1
  135. package/src/language.ts +62 -0
  136. package/src/layout.ts +228 -0
  137. package/src/library.ts +50 -4
  138. package/src/limits.ts +290 -0
  139. package/src/locale.ts +217 -0
  140. package/src/mail.ts +316 -0
  141. package/src/model-probe.ts +4 -0
  142. package/src/notify.ts +391 -44
  143. package/src/openapi.ts +5 -3
  144. package/src/operator.ts +300 -0
  145. package/src/paths.ts +83 -0
  146. package/src/platform.ts +158 -5
  147. package/src/provider-health.ts +275 -0
  148. package/src/providers.ts +1368 -6
  149. package/src/refusal.ts +320 -0
  150. package/src/run-container.ts +611 -76
  151. package/src/runner.ts +1463 -165
  152. package/src/runtime.ts +487 -55
  153. package/src/script-tools.ts +55 -6
  154. package/src/secret-files.ts +22 -10
  155. package/src/secret-health.ts +230 -0
  156. package/src/secrets.ts +191 -95
  157. package/src/starter.ts +96 -11
  158. package/src/step-exec.ts +548 -41
  159. package/src/step-removal.ts +59 -0
  160. package/src/storage.ts +149 -24
  161. package/src/store.ts +1227 -74
  162. package/src/subagents.ts +189 -0
  163. package/src/tar.ts +2 -1
  164. package/src/test-mode.ts +311 -0
  165. package/src/tool-names.ts +40 -11
  166. package/src/tool-programs.ts +179 -0
  167. package/src/tool-test.ts +159 -32
  168. package/src/translator.ts +74 -23
  169. package/src/trigger-log.ts +160 -0
  170. package/src/triggers.ts +102 -12
  171. package/src/untrusted-fetch.ts +88 -0
  172. package/src/web-actions.ts +237 -0
  173. package/src/webhook.ts +58 -11
  174. package/templates/hello/agents/curator/agent.md +1 -1
  175. package/templates/hello/agents/notetaker/agent.md +1 -1
@@ -0,0 +1,75 @@
1
+ /** Plain JSON: this crosses into the run container. */
2
+ export interface SubagentSpec {
3
+ name: string;
4
+ description: string;
5
+ prompt: string;
6
+ /** Always explicit — never absent, never inherited. */
7
+ tools: string[];
8
+ disallowedTools: string[];
9
+ /** A model alias (haiku/sonnet/opus, remapped by the step's provider like
10
+ * the step's own) or "inherit". */
11
+ model: string;
12
+ }
13
+ /** The SDK's delegation tool, under both names it has had. Never granted to a
14
+ * sub-agent: that is what makes the depth one. */
15
+ export declare const DELEGATE_TOOLS: readonly ["Agent", "Task"];
16
+ export declare const DELEGATE_TOOL = "Agent";
17
+ /** The named sub-agents' folders, host-side. Unknown names are reported. */
18
+ export declare function gatherSubagents(workspaceRoot: string, names: unknown): {
19
+ found: {
20
+ name: string;
21
+ dir: string;
22
+ }[];
23
+ missing: string[];
24
+ };
25
+ /**
26
+ * A sub-agent's tools: its own, only where the parent holds them too. An MCP
27
+ * tool is held when the parent holds that exact name or its whole server
28
+ * (`mcp__<server>` / `mcp__<server>__*`). The delegate tool never passes.
29
+ */
30
+ export declare function subagentTools(own: string[], parent: string[]): string[];
31
+ /** The sub-agent's system prompt: its own prose, told where it stands. It
32
+ * works in the PARENT's directory — the SDK shares the session's cwd. */
33
+ export declare function subagentPrompt(o: {
34
+ body: string;
35
+ name: string;
36
+ parent: string;
37
+ workspace: string;
38
+ shared?: string | null;
39
+ }): string;
40
+ /** SDK definitions. `tools` is always set — an absent list inherits every
41
+ * tool the parent has, which is the one thing this module exists to stop. */
42
+ export declare function toAgentDefinitions(specs: SubagentSpec[]): Record<string, {
43
+ description: string;
44
+ prompt: string;
45
+ tools: string[];
46
+ disallowedTools: string[];
47
+ model: string;
48
+ }>;
49
+ /** One tool call as the parent's PreToolUse hook sees it. */
50
+ export interface GuardedCall {
51
+ /** The SDK's agent_id: set when the call comes from inside a sub-agent. */
52
+ agentId?: string;
53
+ /** The SDK's agent_type: which sub-agent. */
54
+ agentType?: string;
55
+ tool: string;
56
+ input: Record<string, unknown>;
57
+ }
58
+ /**
59
+ * For the parent's PreToolUse hook, on a step that has sub-agents: a reason
60
+ * to refuse the call — or null.
61
+ *
62
+ * Only DECLARED sub-agents may run. The SDK also offers its built-ins
63
+ * (general-purpose and the rest, with every tool the session has); they are
64
+ * switched off in executeStep, and refused here too. A call from inside a
65
+ * sub-agent whose type is missing or not declared used to pass unjudged —
66
+ * `general-purpose` was a way round every sub-agent's own list.
67
+ */
68
+ export declare function subagentGuard(specs: SubagentSpec[]): (call: GuardedCall) => string | null;
69
+ /**
70
+ * What `foldrun check` can say without running anything: the SDK and built-in
71
+ * tool names two `tools:` lists grant, and their overlap. Own tools compare by
72
+ * name. Used to warn when a sub-agent would be left with nothing.
73
+ */
74
+ export declare function grantedNames(tools: string[]): Set<string>;
75
+ export declare function checkOverlap(parentTools: string[], subTools: string[]): string[];
@@ -0,0 +1,149 @@
1
+ // Sub-agents: delegate a job to a colleague with its OWN context and its own
2
+ // tools, inside the step that asked.
3
+ //
4
+ // agents: [editor] # consult: a quick opinion, no tools (agent-tools.ts)
5
+ // subagents: [researcher] # delegate: own context, own tools
6
+ //
7
+ // Built on the Agent SDK's native sub-agents (query()'s `agents` option and
8
+ // its Agent tool), so a delegation behaves as it does in Claude Code: a fresh
9
+ // context does the work — reads forty pages, runs the checks — and hands back
10
+ // a summary, keeping the parent's context on its own job.
11
+ //
12
+ // What keeps it the platform's and not a second, wider agent:
13
+ // - never wider than the parent: a sub-agent's tools are its own `tools:`
14
+ // resolved exactly as a step's, INTERSECTED with what the parent step
15
+ // holds — and always an explicit list: the SDK gives a definition with
16
+ // no `tools` every tool the parent has
17
+ // - depth one: the Agent/Task tool is never in a sub-agent's list, so it
18
+ // cannot delegate again
19
+ // - the same step: same sandbox, files, secrets, egress lease, and the
20
+ // parent's hooks — the SDK runs a sub-agent's tool calls through the
21
+ // session's PreToolUse and canUseTool (tagged agent_id/agent_type), so
22
+ // confinement applies unchanged; subagentGuard() below refuses anything
23
+ // outside the sub-agent's own list there too, belt and braces
24
+ // - cost and trace land on the parent step; flows still decide what runs
25
+ // next — a sub-agent is a helper inside one step, never a step.
26
+ import fs from "node:fs";
27
+ import path from "node:path";
28
+ import { refNames } from "./refs.js";
29
+ import { TOOL_MAP } from "./tool-names.js";
30
+ /** The SDK's delegation tool, under both names it has had. Never granted to a
31
+ * sub-agent: that is what makes the depth one. */
32
+ export const DELEGATE_TOOLS = ["Agent", "Task"];
33
+ export const DELEGATE_TOOL = "Agent";
34
+ const NAME = /^[a-z0-9]+(-[a-z0-9]+)*$/;
35
+ /** The named sub-agents' folders, host-side. Unknown names are reported. */
36
+ export function gatherSubagents(workspaceRoot, names) {
37
+ const found = [];
38
+ const missing = [];
39
+ for (const name of refNames(names)) {
40
+ const dir = path.join(workspaceRoot, "agents", name);
41
+ if (!NAME.test(name) || !fs.existsSync(path.join(dir, "agent.md")))
42
+ missing.push(name);
43
+ else if (!found.some((f) => f.name === name))
44
+ found.push({ name, dir });
45
+ }
46
+ return { found, missing };
47
+ }
48
+ /**
49
+ * A sub-agent's tools: its own, only where the parent holds them too. An MCP
50
+ * tool is held when the parent holds that exact name or its whole server
51
+ * (`mcp__<server>` / `mcp__<server>__*`). The delegate tool never passes.
52
+ */
53
+ export function subagentTools(own, parent) {
54
+ const held = new Set(parent);
55
+ const servers = new Set(parent.filter((t) => /^mcp__[^_]/.test(t)).map((t) => t.replace(/__\*$/, "")).filter((t) => !t.slice(5).includes("__")));
56
+ const out = [];
57
+ for (const t of own) {
58
+ if (DELEGATE_TOOLS.includes(t) || out.includes(t))
59
+ continue;
60
+ const server = /^mcp__([^_].*?)__/.exec(t)?.[1];
61
+ if (held.has(t) || (server && servers.has(`mcp__${server}`)))
62
+ out.push(t);
63
+ }
64
+ return out;
65
+ }
66
+ /** The sub-agent's system prompt: its own prose, told where it stands. It
67
+ * works in the PARENT's directory — the SDK shares the session's cwd. */
68
+ export function subagentPrompt(o) {
69
+ return [
70
+ o.body.trim(),
71
+ `# Where you are\n\n` +
72
+ `You are ${o.name}, a sub-agent started by ${o.parent} to do one job and report back. ` +
73
+ `You work in ${o.parent}'s directory, \`agents/${o.parent}/\` in the \`${o.workspace}\` workspace: ` +
74
+ `\`../../\` is the workspace root, its knowledge is at \`../../knowledge/\`, and absolute paths are refused. ` +
75
+ `You have only the tools listed for you. When the job is done, reply with what you found or made — ` +
76
+ `your reply is all ${o.parent} sees of your work, so put the facts and file paths in it.`,
77
+ ...(o.shared?.trim() ? [o.shared.trim()] : []),
78
+ ].join("\n\n");
79
+ }
80
+ /** SDK definitions. `tools` is always set — an absent list inherits every
81
+ * tool the parent has, which is the one thing this module exists to stop. */
82
+ export function toAgentDefinitions(specs) {
83
+ const out = {};
84
+ for (const s of specs) {
85
+ out[s.name] = {
86
+ description: s.description,
87
+ prompt: s.prompt,
88
+ tools: [...s.tools],
89
+ disallowedTools: [...new Set([...s.disallowedTools, ...DELEGATE_TOOLS])],
90
+ model: s.model || "inherit",
91
+ };
92
+ }
93
+ return out;
94
+ }
95
+ /**
96
+ * For the parent's PreToolUse hook, on a step that has sub-agents: a reason
97
+ * to refuse the call — or null.
98
+ *
99
+ * Only DECLARED sub-agents may run. The SDK also offers its built-ins
100
+ * (general-purpose and the rest, with every tool the session has); they are
101
+ * switched off in executeStep, and refused here too. A call from inside a
102
+ * sub-agent whose type is missing or not declared used to pass unjudged —
103
+ * `general-purpose` was a way round every sub-agent's own list.
104
+ */
105
+ export function subagentGuard(specs) {
106
+ const by = new Map(specs.map((s) => [s.name, s]));
107
+ const declared = specs.map((s) => s.name).join(", ");
108
+ const isDelegate = (tool) => DELEGATE_TOOLS.includes(tool);
109
+ return ({ agentId, agentType, tool, input }) => {
110
+ if (!agentId) {
111
+ // The main thread: its tools are canUseTool's business — except the
112
+ // delegation itself, which may name only a declared sub-agent.
113
+ if (!isDelegate(tool))
114
+ return null;
115
+ const to = typeof input.subagent_type === "string" ? input.subagent_type : "";
116
+ if (by.has(to))
117
+ return null;
118
+ return `${to ? `"${to}" is not a sub-agent this step declared` : "name the sub-agent to delegate to"} — subagent_type must be one of: ${declared}`;
119
+ }
120
+ const s = agentType ? by.get(agentType) : undefined;
121
+ if (!s)
122
+ return `${agentType ? `"${agentType}"` : "an unnamed sub-agent"} is not declared in subagents: for this step (only ${declared}) — its calls are refused`;
123
+ if (isDelegate(tool)) {
124
+ return `${s.name} is a sub-agent and cannot start another — do the work with your own tools`;
125
+ }
126
+ if (s.disallowedTools.includes(tool))
127
+ return `${tool} is disallowed for ${s.name}`;
128
+ if (subagentTools([tool], s.tools).length === 0)
129
+ return `${tool} is not one of ${s.name}'s tools`;
130
+ return null;
131
+ };
132
+ }
133
+ /**
134
+ * What `foldrun check` can say without running anything: the SDK and built-in
135
+ * tool names two `tools:` lists grant, and their overlap. Own tools compare by
136
+ * name. Used to warn when a sub-agent would be left with nothing.
137
+ */
138
+ export function grantedNames(tools) {
139
+ const out = new Set();
140
+ for (const t of tools) {
141
+ for (const n of TOOL_MAP[t] ?? [t])
142
+ out.add(n);
143
+ }
144
+ return out;
145
+ }
146
+ export function checkOverlap(parentTools, subTools) {
147
+ const parent = grantedNames(parentTools);
148
+ return [...grantedNames(subTools)].filter((t) => parent.has(t) && !DELEGATE_TOOLS.includes(t));
149
+ }
package/dist/src/tar.js CHANGED
@@ -9,6 +9,7 @@
9
9
  // 512-byte blocks with an octal size field, and a reader is shorter than the
10
10
  // argument about which library to add.
11
11
  import zlib from "node:zlib";
12
+ import { trimSlashes } from "./paths.js";
12
13
  const BLOCK = 512;
13
14
  const str = (b, off, len) => {
14
15
  const raw = b.subarray(off, off + len);
@@ -86,7 +87,7 @@ export function stripRoot(entries) {
86
87
  * case, since a repo usually holds more than one thing.
87
88
  */
88
89
  export function filesFromTarball(gz, subdir = "") {
89
- const prefix = subdir.replace(/^\/+|\/+$/g, "");
90
+ const prefix = trimSlashes(subdir, "both");
90
91
  const out = [];
91
92
  for (const entry of stripRoot(readTarGz(gz))) {
92
93
  let rel = entry.path;
@@ -0,0 +1,111 @@
1
+ /** Where a test run's email actually goes — Resend's delivered sink. */
2
+ export declare const TEST_SINK_EMAIL = "delivered@resend.dev";
3
+ /** Prefixed to every subject a test run sends, so the sink is readable. */
4
+ export declare const TEST_SUBJECT_PREFIX = "[TEST] ";
5
+ /** What a withheld secret's env var reads as inside the sandbox. */
6
+ export declare const WITHHELD = "TEST_MODE_WITHHELD";
7
+ /** Both are set to "1" in a test run's sandbox: the first is what a script
8
+ * checks, the second is the run-level spelling for verifies and flows. */
9
+ export declare const TEST_MODE_ENV = "FOLDRUN_TEST_MODE";
10
+ export declare const RUN_TEST_ENV = "FOLDRUN_RUN_TEST";
11
+ /** Under runs/<id>/, where diverted state/ and storage/ writes land. */
12
+ export declare const TEST_WRITES_DIR = "test-writes";
13
+ /** The workspace directories a test run may not write for real. */
14
+ export declare const TEST_DIVERTED_DIRS: readonly ["state", "storage"];
15
+ /** What a test run did instead of the real thing — one per intervention,
16
+ * on the run event that reports it, so the run page can list them. */
17
+ export interface TestEffect {
18
+ kind: "refused" | "redirected" | "diverted" | "withheld";
19
+ host?: string;
20
+ method?: string;
21
+ path?: string;
22
+ summary: string;
23
+ }
24
+ /**
25
+ * Secret names that can make something happen outside. Matched by name
26
+ * because the name is all the runner knows before the value is used: the
27
+ * vault does not say what a key can do, and the provider hosts are only
28
+ * known for http tools, not for the scripts these are withheld from.
29
+ */
30
+ export declare const SEND_CAPABLE_SECRETS: RegExp[];
31
+ export declare function isSendCapableSecret(name: string): boolean;
32
+ /**
33
+ * The secrets a test-run sandbox is handed, and which were withheld.
34
+ *
35
+ * `outward` — the step grants a script tool whose file says `outward: true`:
36
+ * then every secret is withheld, because a tool that declared itself a
37
+ * sender is not one to hand anything real. `allow` — a script tool said
38
+ * `test_mode: allow` (a reader that happens to use a listed key): the list
39
+ * is not applied. Outward wins over allow, because a step that has both
40
+ * has a sender in it.
41
+ */
42
+ export declare function withholdSecrets(secrets: Record<string, string>, opts?: {
43
+ outward?: boolean;
44
+ allow?: boolean;
45
+ }): {
46
+ env: Record<string, string>;
47
+ withheld: string[];
48
+ };
49
+ /**
50
+ * Hosts an outward write may reach on a test run: model providers (the run
51
+ * cannot happen without them, and nothing there is a send), and read-only
52
+ * services whose POSTs are queries. A host is matched exactly, or by a
53
+ * leading `*.` for its subdomains. The list is deliberately short — the
54
+ * default is refusal, and a host earns its place here by having no way to
55
+ * reach a customer.
56
+ */
57
+ export declare const READ_SAFE_HOSTS: string[];
58
+ export declare function isReadSafeHost(host: string): boolean;
59
+ export type TestPolicy = {
60
+ action: "allow";
61
+ } | {
62
+ action: "refuse";
63
+ } | {
64
+ action: "rewrite";
65
+ rewrite: "resend-email";
66
+ };
67
+ /**
68
+ * What the proxy does with one request on a test lease. Pure: method, host
69
+ * and path in, a verdict out. Reads always pass — a test run has to be able
70
+ * to look at the world it is not allowed to change.
71
+ */
72
+ export declare function testPolicy(method: string, host: string, path: string): TestPolicy;
73
+ /**
74
+ * A Resend `POST /emails` body with its recipients pointed at the sink and
75
+ * the subject marked. Returns the recipients it replaced, for the trace.
76
+ * Null when the body is not a JSON object — then there is nothing safe to
77
+ * rewrite, and the caller refuses instead.
78
+ */
79
+ export declare function rewriteResendEmail(body: string): {
80
+ body: string;
81
+ to: string[];
82
+ } | null;
83
+ /** The first `max` characters of a body, whitespace collapsed — enough to
84
+ * say what would have gone out, not enough to be the thing itself. The
85
+ * caller redacts; this only cuts. */
86
+ export declare function bodySummary(body: string, max?: number): string;
87
+ /** The recipient field of a body, if it has one — for `would_have.to`. */
88
+ export declare function recipientsOf(body: string): string | string[] | null;
89
+ /** The 403 a refused write is answered with. JSON, so a script that parses
90
+ * the error sees `test_mode` and can say so instead of retrying. */
91
+ export declare function refusalBody(method: string, host: string, path: string, body: string): string;
92
+ /** Is this workspace-relative path one a test run diverts? */
93
+ export declare function isDivertedPath(rel: string): boolean;
94
+ /** The line the trace and the run page show for one diverted write. */
95
+ export declare function divertedSummary(rel: string, was: Buffer | null, next: Buffer): string;
96
+ /**
97
+ * The in-process path has no copy-in and copy-out — a step writes the
98
+ * workspace directly — so a test run there snapshots state/ and storage/
99
+ * before the step and, after it, moves what changed under the run and
100
+ * puts the originals back. Same outcome as the sandbox's divert, reached
101
+ * from the other side. Used by `foldrun run --test`.
102
+ */
103
+ export declare function snapshotDivertedDirs(wsRoot: string): Map<string, Buffer>;
104
+ /** Undo a step's writes to the diverted directories, keeping each changed
105
+ * or new file under `to` by its workspace-relative path. Deletions are
106
+ * undone too — the original is put back. Returns what was set aside. */
107
+ export declare function restoreDivertedDirs(wsRoot: string, before: Map<string, Buffer>, to: string, note: (rel: string, summary: string) => void): string[];
108
+ /** `[test] ` in front of a headline, once. */
109
+ export declare function testHeadline(summary: string): string;
110
+ /** The env every test-run sandbox gets, beside its secrets. */
111
+ export declare function testModeEnv(): Record<string, string>;
@@ -0,0 +1,285 @@
1
+ // Test mode: a run that exercises everything and changes nothing outside.
2
+ //
3
+ // Every desk that sends — email, SMS, orders, posts — grew its own test
4
+ // switch inside its own script: a `test_to` address here, a `mode: test`
5
+ // there. On 2026-09-14 a send step edited its own gate file to get past a
6
+ // script's guard and texted 25 customers. A guard the script can reach is a
7
+ // guard the script can move; this one lives where the script cannot: on the
8
+ // run record, at the egress proxy, and in what the sandbox is handed.
9
+ //
10
+ // The rule has one table (below) so it is testable without a server, and
11
+ // three enforcement points that all read it:
12
+ //
13
+ // - the egress proxy: on a test lease, an outward write to a host that is
14
+ // not read-safe or a model provider is refused with 403 and a JSON body
15
+ // naming what would have been sent; Resend's sink address is the one
16
+ // exception, so a desk still gets a real message id back
17
+ // - the runner: send-capable secrets never enter the sandbox as values on
18
+ // a test run; the env var says TEST_MODE_WITHHELD instead, so a script
19
+ // that forgot to check fails at the provider with an auth error
20
+ // - the write-back: state/ and storage/ go INTO the sandbox as usual and
21
+ // come out into runs/<id>/test-writes/ instead of the real directories
22
+ //
23
+ // Nothing here weakens a live run: every function is a no-op unless the run
24
+ // says `test: true`.
25
+ import fs from "node:fs";
26
+ import path from "node:path";
27
+ /** Where a test run's email actually goes — Resend's delivered sink. */
28
+ export const TEST_SINK_EMAIL = "delivered@resend.dev";
29
+ /** Prefixed to every subject a test run sends, so the sink is readable. */
30
+ export const TEST_SUBJECT_PREFIX = "[TEST] ";
31
+ /** What a withheld secret's env var reads as inside the sandbox. */
32
+ export const WITHHELD = "TEST_MODE_WITHHELD";
33
+ /** Both are set to "1" in a test run's sandbox: the first is what a script
34
+ * checks, the second is the run-level spelling for verifies and flows. */
35
+ export const TEST_MODE_ENV = "FOLDRUN_TEST_MODE";
36
+ export const RUN_TEST_ENV = "FOLDRUN_RUN_TEST";
37
+ /** Under runs/<id>/, where diverted state/ and storage/ writes land. */
38
+ export const TEST_WRITES_DIR = "test-writes";
39
+ /** The workspace directories a test run may not write for real. */
40
+ export const TEST_DIVERTED_DIRS = ["state", "storage"];
41
+ // ---------------------------------------------------------------- secrets
42
+ /**
43
+ * Secret names that can make something happen outside. Matched by name
44
+ * because the name is all the runner knows before the value is used: the
45
+ * vault does not say what a key can do, and the provider hosts are only
46
+ * known for http tools, not for the scripts these are withheld from.
47
+ */
48
+ export const SEND_CAPABLE_SECRETS = [
49
+ /^RESEND_API_KEY$/,
50
+ /^TWILIO_/,
51
+ /^GETREACH_API_KEY$/,
52
+ /^GITHUB_TOKEN$/,
53
+ /^MONDAY_API_TOKEN$/,
54
+ /^OI_CRM_API_KEY$/,
55
+ /^CLOUDFLARE_/,
56
+ /^LINKEDIN_/,
57
+ /^MEDIUM_COOKIES$/,
58
+ /^TIKTOK_/,
59
+ ];
60
+ export function isSendCapableSecret(name) {
61
+ return SEND_CAPABLE_SECRETS.some((re) => re.test(name));
62
+ }
63
+ /**
64
+ * The secrets a test-run sandbox is handed, and which were withheld.
65
+ *
66
+ * `outward` — the step grants a script tool whose file says `outward: true`:
67
+ * then every secret is withheld, because a tool that declared itself a
68
+ * sender is not one to hand anything real. `allow` — a script tool said
69
+ * `test_mode: allow` (a reader that happens to use a listed key): the list
70
+ * is not applied. Outward wins over allow, because a step that has both
71
+ * has a sender in it.
72
+ */
73
+ export function withholdSecrets(secrets, opts = {}) {
74
+ const env = {};
75
+ const withheld = [];
76
+ for (const [name, value] of Object.entries(secrets)) {
77
+ const hold = opts.outward || (!opts.allow && isSendCapableSecret(name));
78
+ env[name] = hold ? WITHHELD : value;
79
+ if (hold)
80
+ withheld.push(name);
81
+ }
82
+ return { env, withheld };
83
+ }
84
+ // ---------------------------------------------------------------- the proxy
85
+ /** Methods that read. Anything else is a write until the host says otherwise. */
86
+ const READ_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
87
+ /**
88
+ * Hosts an outward write may reach on a test run: model providers (the run
89
+ * cannot happen without them, and nothing there is a send), and read-only
90
+ * services whose POSTs are queries. A host is matched exactly, or by a
91
+ * leading `*.` for its subdomains. The list is deliberately short — the
92
+ * default is refusal, and a host earns its place here by having no way to
93
+ * reach a customer.
94
+ */
95
+ export const READ_SAFE_HOSTS = [
96
+ // model providers
97
+ "api.anthropic.com",
98
+ "openrouter.ai",
99
+ "api.openai.com",
100
+ "generativelanguage.googleapis.com",
101
+ "api.groq.com",
102
+ "api.mistral.ai",
103
+ "api.together.xyz",
104
+ "api.deepseek.com",
105
+ "api.x.ai",
106
+ "api.fireworks.ai",
107
+ "api.cerebras.ai",
108
+ "api.perplexity.ai",
109
+ "*.openai.azure.com",
110
+ // queries that are POSTs
111
+ "api.dataforseo.com",
112
+ "*.dataforseo.com",
113
+ "*.svc.cluster.local",
114
+ ];
115
+ export function isReadSafeHost(host) {
116
+ const h = host.toLowerCase().replace(/:\d+$/, "");
117
+ return READ_SAFE_HOSTS.some((rule) => rule.startsWith("*.") ? h.endsWith(rule.slice(1)) && h !== rule.slice(2) : h === rule);
118
+ }
119
+ /**
120
+ * What the proxy does with one request on a test lease. Pure: method, host
121
+ * and path in, a verdict out. Reads always pass — a test run has to be able
122
+ * to look at the world it is not allowed to change.
123
+ */
124
+ export function testPolicy(method, host, path) {
125
+ const m = method.toUpperCase();
126
+ if (READ_METHODS.has(m))
127
+ return { action: "allow" };
128
+ const h = host.toLowerCase().replace(/:\d+$/, "");
129
+ // Resend's sink: the message really goes out, to an address that keeps
130
+ // it, with the subject marked — so the desk sees a real id and a real
131
+ // 200, and nobody receives anything.
132
+ if (h === "api.resend.com" && /^\/emails(\/|$|\?)/.test(path))
133
+ return { action: "rewrite", rewrite: "resend-email" };
134
+ if (isReadSafeHost(h))
135
+ return { action: "allow" };
136
+ return { action: "refuse" };
137
+ }
138
+ /**
139
+ * A Resend `POST /emails` body with its recipients pointed at the sink and
140
+ * the subject marked. Returns the recipients it replaced, for the trace.
141
+ * Null when the body is not a JSON object — then there is nothing safe to
142
+ * rewrite, and the caller refuses instead.
143
+ */
144
+ export function rewriteResendEmail(body) {
145
+ let parsed;
146
+ try {
147
+ parsed = JSON.parse(body);
148
+ }
149
+ catch {
150
+ return null;
151
+ }
152
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
153
+ return null;
154
+ const mail = parsed;
155
+ const to = [];
156
+ for (const field of ["to", "cc", "bcc"]) {
157
+ const v = mail[field];
158
+ if (v === undefined || v === null)
159
+ continue;
160
+ for (const addr of Array.isArray(v) ? v : [v])
161
+ to.push(String(addr));
162
+ // One sink address for the lot: two copies of the same test mail teach
163
+ // nobody anything, and cc/bcc to the sink would be exactly that.
164
+ if (field === "to")
165
+ mail[field] = [TEST_SINK_EMAIL];
166
+ else
167
+ delete mail[field];
168
+ }
169
+ if (!Array.isArray(mail.to) || mail.to.length === 0)
170
+ mail.to = [TEST_SINK_EMAIL];
171
+ const subject = typeof mail.subject === "string" ? mail.subject : "";
172
+ mail.subject = subject.startsWith(TEST_SUBJECT_PREFIX) ? subject : `${TEST_SUBJECT_PREFIX}${subject}`;
173
+ return { body: JSON.stringify(mail), to };
174
+ }
175
+ /** The first `max` characters of a body, whitespace collapsed — enough to
176
+ * say what would have gone out, not enough to be the thing itself. The
177
+ * caller redacts; this only cuts. */
178
+ export function bodySummary(body, max = 200) {
179
+ const flat = body.replace(/\s+/g, " ").trim();
180
+ return flat.length > max ? `${flat.slice(0, max)}…` : flat;
181
+ }
182
+ /** The recipient field of a body, if it has one — for `would_have.to`. */
183
+ export function recipientsOf(body) {
184
+ try {
185
+ const parsed = JSON.parse(body);
186
+ if (parsed && typeof parsed === "object") {
187
+ for (const key of ["to", "To", "recipient", "phone", "email"]) {
188
+ const v = parsed[key];
189
+ if (typeof v === "string" || Array.isArray(v))
190
+ return v;
191
+ }
192
+ }
193
+ }
194
+ catch {
195
+ // a form body: Twilio's Messages endpoint
196
+ const m = body.match(/(?:^|&)To=([^&]*)/);
197
+ if (m)
198
+ return decodeURIComponent(m[1].replace(/\+/g, " "));
199
+ }
200
+ return null;
201
+ }
202
+ /** The 403 a refused write is answered with. JSON, so a script that parses
203
+ * the error sees `test_mode` and can say so instead of retrying. */
204
+ export function refusalBody(method, host, path, body) {
205
+ return JSON.stringify({
206
+ test_mode: true,
207
+ error: { type: "test_mode", message: `test run: ${method} ${host}${path} refused — nothing was sent` },
208
+ would_have: { method, host, path, to: recipientsOf(body), body: bodySummary(body) },
209
+ });
210
+ }
211
+ // ---------------------------------------------------------------- write-back
212
+ /** Is this workspace-relative path one a test run diverts? */
213
+ export function isDivertedPath(rel) {
214
+ const norm = rel.replaceAll("\\", "/");
215
+ return TEST_DIVERTED_DIRS.some((d) => norm === d || norm.startsWith(`${d}/`));
216
+ }
217
+ /** The line the trace and the run page show for one diverted write. */
218
+ export function divertedSummary(rel, was, next) {
219
+ if (was === null)
220
+ return `would have created ${rel} (${next.length} bytes)`;
221
+ const before = was.toString("utf8").split("\n").length;
222
+ const after = next.toString("utf8").split("\n").length;
223
+ const delta = after - before;
224
+ return `would have written ${rel}${delta > 0 ? `, +${delta} line${delta === 1 ? "" : "s"}` : delta < 0 ? `, ${delta} lines` : ""}`;
225
+ }
226
+ /**
227
+ * The in-process path has no copy-in and copy-out — a step writes the
228
+ * workspace directly — so a test run there snapshots state/ and storage/
229
+ * before the step and, after it, moves what changed under the run and
230
+ * puts the originals back. Same outcome as the sandbox's divert, reached
231
+ * from the other side. Used by `foldrun run --test`.
232
+ */
233
+ export function snapshotDivertedDirs(wsRoot) {
234
+ const snap = new Map();
235
+ for (const dir of TEST_DIVERTED_DIRS) {
236
+ const root = path.join(wsRoot, dir);
237
+ if (!fs.existsSync(root))
238
+ continue;
239
+ for (const entry of fs.readdirSync(root, { recursive: true, withFileTypes: true })) {
240
+ if (!entry.isFile())
241
+ continue;
242
+ const abs = path.join(entry.parentPath, entry.name);
243
+ snap.set(path.relative(wsRoot, abs).replaceAll("\\", "/"), fs.readFileSync(abs));
244
+ }
245
+ }
246
+ return snap;
247
+ }
248
+ /** Undo a step's writes to the diverted directories, keeping each changed
249
+ * or new file under `to` by its workspace-relative path. Deletions are
250
+ * undone too — the original is put back. Returns what was set aside. */
251
+ export function restoreDivertedDirs(wsRoot, before, to, note) {
252
+ const now = snapshotDivertedDirs(wsRoot);
253
+ const aside = [];
254
+ for (const [rel, next] of now) {
255
+ const was = before.get(rel) ?? null;
256
+ if (was && was.equals(next))
257
+ continue;
258
+ const dest = path.join(to, rel);
259
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
260
+ fs.writeFileSync(dest, next);
261
+ aside.push(rel);
262
+ note(rel, divertedSummary(rel, was, next));
263
+ if (was)
264
+ fs.writeFileSync(path.join(wsRoot, rel), was);
265
+ else
266
+ fs.rmSync(path.join(wsRoot, rel), { force: true });
267
+ }
268
+ for (const [rel, was] of before) {
269
+ if (now.has(rel))
270
+ continue;
271
+ fs.mkdirSync(path.dirname(path.join(wsRoot, rel)), { recursive: true });
272
+ fs.writeFileSync(path.join(wsRoot, rel), was);
273
+ note(rel, `would have deleted ${rel}`);
274
+ aside.push(rel);
275
+ }
276
+ return aside;
277
+ }
278
+ /** `[test] ` in front of a headline, once. */
279
+ export function testHeadline(summary) {
280
+ return summary.startsWith("[test]") ? summary : `[test] ${summary}`;
281
+ }
282
+ /** The env every test-run sandbox gets, beside its secrets. */
283
+ export function testModeEnv() {
284
+ return { [TEST_MODE_ENV]: "1", [RUN_TEST_ENV]: "1" };
285
+ }
@@ -1,9 +1,16 @@
1
1
  import { type Ref } from "./refs.ts";
2
2
  /** Groups: one word an author can hold in their head, expanded to SDK names. */
3
3
  export declare const TOOL_MAP: Record<string, string[]>;
4
+ /** Names an author may no longer write, and what to write instead. They are
5
+ * still granted, so nothing deployed breaks; `check` and the run log say the
6
+ * rewrite. */
7
+ export declare const RETIRED_TOOLS: Record<string, string>;
4
8
  /** Exact SDK tool names, accepted alongside the group aliases so a Claude Code
5
9
  * subagent's `tools: Read, Grep` works unchanged. The aliases exist because
6
- * vendors rename tools; `web` survives a rename that `WebSearch` would not. */
10
+ * vendors rename tools; `write` survives a rename that `Write` would not.
11
+ * The SDK's WebSearch and WebFetch are not here: the web is our `web` tool,
12
+ * and a model provider's own search (`web: {search: zai}`) is the runtime's
13
+ * to swap in, not the author's to name. */
7
14
  export declare const BUILTIN_TOOLS: Set<string>;
8
15
  /** The platform's own groups, served in-process rather than by the SDK. */
9
16
  export declare const PLATFORM_GROUPS: Set<string>;
@@ -34,6 +41,11 @@ export declare function ownToolNames(front: ToolFrontmatter): string[];
34
41
  /** What a file still says under the removed `use:` key — nothing is granted
35
42
  * for these; they exist so the error can quote the exact `tools:` line. */
36
43
  export declare function legacyUseNames(front: ToolFrontmatter): string[];
44
+ /** Retired names written bare in `tools:`, deduped. A `[[link]]` is the
45
+ * author's own file, so it is never one of these. */
46
+ export declare function retiredToolNames(front: ToolFrontmatter): string[];
47
+ /** The one sentence every reader of a retired name says. */
48
+ export declare function retiredToolError(name: string): string;
37
49
  /** The one sentence every reader of a `use:` key says. */
38
50
  export declare function legacyUseError(names: string[]): string;
39
51
  export {};