@foldrun/core 0.4.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 (155) hide show
  1. package/dist/index.d.ts +3 -0
  2. package/dist/index.js +3 -0
  3. package/dist/src/account.d.ts +45 -0
  4. package/dist/src/account.js +130 -0
  5. package/dist/src/api-tools.d.ts +8 -0
  6. package/dist/src/api-tools.js +22 -4
  7. package/dist/src/browser-pod.d.ts +129 -0
  8. package/dist/src/browser-pod.js +284 -0
  9. package/dist/src/catalog.js +2 -1
  10. package/dist/src/clock.d.ts +49 -0
  11. package/dist/src/clock.js +121 -0
  12. package/dist/src/completions.js +17 -8
  13. package/dist/src/confine.d.ts +22 -0
  14. package/dist/src/confine.js +218 -3
  15. package/dist/src/deploy.d.ts +33 -0
  16. package/dist/src/deploy.js +145 -6
  17. package/dist/src/egress.d.ts +7 -0
  18. package/dist/src/egress.js +6 -0
  19. package/dist/src/eol.d.ts +2 -0
  20. package/dist/src/eol.js +7 -0
  21. package/dist/src/evals.d.ts +5 -0
  22. package/dist/src/evals.js +6 -2
  23. package/dist/src/flow-lint.d.ts +8 -0
  24. package/dist/src/flow-lint.js +223 -1
  25. package/dist/src/flow-patterns.d.ts +141 -0
  26. package/dist/src/flow-patterns.js +568 -0
  27. package/dist/src/gitrepo.d.ts +18 -0
  28. package/dist/src/gitrepo.js +49 -0
  29. package/dist/src/kinds.js +1 -1
  30. package/dist/src/language.d.ts +17 -0
  31. package/dist/src/language.js +55 -0
  32. package/dist/src/layout.d.ts +69 -0
  33. package/dist/src/layout.js +200 -0
  34. package/dist/src/library.d.ts +9 -0
  35. package/dist/src/library.js +30 -3
  36. package/dist/src/limits.d.ts +84 -0
  37. package/dist/src/limits.js +287 -0
  38. package/dist/src/locale.d.ts +47 -0
  39. package/dist/src/locale.js +177 -0
  40. package/dist/src/mail.d.ts +88 -0
  41. package/dist/src/mail.js +245 -0
  42. package/dist/src/model-probe.d.ts +3 -0
  43. package/dist/src/model-probe.js +1 -0
  44. package/dist/src/notify.d.ts +53 -7
  45. package/dist/src/notify.js +194 -126
  46. package/dist/src/openapi.js +5 -3
  47. package/dist/src/operator.d.ts +201 -0
  48. package/dist/src/operator.js +251 -0
  49. package/dist/src/paths.d.ts +28 -0
  50. package/dist/src/paths.js +55 -0
  51. package/dist/src/platform.d.ts +43 -3
  52. package/dist/src/platform.js +9 -1
  53. package/dist/src/provider-health.js +3 -2
  54. package/dist/src/providers.d.ts +481 -0
  55. package/dist/src/providers.js +1105 -6
  56. package/dist/src/refusal.d.ts +83 -0
  57. package/dist/src/refusal.js +281 -0
  58. package/dist/src/run-container.d.ts +149 -13
  59. package/dist/src/run-container.js +403 -42
  60. package/dist/src/runner.d.ts +142 -9
  61. package/dist/src/runner.js +1027 -122
  62. package/dist/src/runtime.d.ts +52 -0
  63. package/dist/src/runtime.js +493 -58
  64. package/dist/src/script-tools.d.ts +3 -2
  65. package/dist/src/script-tools.js +35 -3
  66. package/dist/src/secret-files.d.ts +6 -5
  67. package/dist/src/secret-files.js +24 -11
  68. package/dist/src/secret-health.d.ts +30 -6
  69. package/dist/src/secret-health.js +42 -20
  70. package/dist/src/secrets.d.ts +19 -0
  71. package/dist/src/secrets.js +155 -86
  72. package/dist/src/starter.d.ts +9 -0
  73. package/dist/src/starter.js +92 -11
  74. package/dist/src/step-exec.d.ts +61 -2
  75. package/dist/src/step-exec.js +414 -36
  76. package/dist/src/step-removal.d.ts +15 -0
  77. package/dist/src/step-removal.js +49 -0
  78. package/dist/src/storage.d.ts +23 -4
  79. package/dist/src/storage.js +125 -23
  80. package/dist/src/store.d.ts +218 -37
  81. package/dist/src/store.js +347 -60
  82. package/dist/src/subagents.d.ts +75 -0
  83. package/dist/src/subagents.js +149 -0
  84. package/dist/src/tool-names.d.ts +13 -1
  85. package/dist/src/tool-names.js +38 -11
  86. package/dist/src/tool-programs.d.ts +26 -0
  87. package/dist/src/tool-programs.js +172 -0
  88. package/dist/src/tool-test.js +104 -12
  89. package/dist/src/translator.d.ts +8 -2
  90. package/dist/src/translator.js +69 -23
  91. package/dist/src/trigger-log.d.ts +1 -1
  92. package/dist/src/triggers.d.ts +3 -0
  93. package/dist/src/triggers.js +10 -2
  94. package/dist/src/untrusted-fetch.d.ts +11 -0
  95. package/dist/src/untrusted-fetch.js +77 -0
  96. package/dist/src/web-actions.d.ts +91 -0
  97. package/dist/src/web-actions.js +199 -0
  98. package/dist/src/webhook.d.ts +4 -0
  99. package/dist/src/webhook.js +39 -0
  100. package/index.ts +3 -0
  101. package/package.json +3 -3
  102. package/src/account.ts +149 -0
  103. package/src/api-tools.ts +32 -4
  104. package/src/browser-pod.ts +313 -0
  105. package/src/catalog.ts +2 -1
  106. package/src/clock.ts +149 -0
  107. package/src/completions.ts +17 -8
  108. package/src/confine.ts +218 -3
  109. package/src/deploy.ts +137 -6
  110. package/src/egress.ts +13 -1
  111. package/src/eol.ts +7 -0
  112. package/src/evals.ts +11 -2
  113. package/src/flow-lint.ts +253 -1
  114. package/src/flow-patterns.ts +597 -0
  115. package/src/gitrepo.ts +48 -0
  116. package/src/kinds.ts +1 -1
  117. package/src/language.ts +62 -0
  118. package/src/layout.ts +228 -0
  119. package/src/library.ts +37 -3
  120. package/src/limits.ts +290 -0
  121. package/src/locale.ts +217 -0
  122. package/src/mail.ts +316 -0
  123. package/src/model-probe.ts +4 -0
  124. package/src/notify.ts +189 -103
  125. package/src/openapi.ts +5 -3
  126. package/src/operator.ts +300 -0
  127. package/src/paths.ts +54 -0
  128. package/src/platform.ts +52 -3
  129. package/src/provider-health.ts +3 -2
  130. package/src/providers.ts +1368 -6
  131. package/src/refusal.ts +320 -0
  132. package/src/run-container.ts +439 -43
  133. package/src/runner.ts +1050 -122
  134. package/src/runtime.ts +487 -55
  135. package/src/script-tools.ts +38 -5
  136. package/src/secret-files.ts +22 -10
  137. package/src/secret-health.ts +64 -19
  138. package/src/secrets.ts +149 -87
  139. package/src/starter.ts +93 -11
  140. package/src/step-exec.ts +429 -37
  141. package/src/step-removal.ts +59 -0
  142. package/src/storage.ts +141 -22
  143. package/src/store.ts +500 -68
  144. package/src/subagents.ts +189 -0
  145. package/src/tool-names.ts +40 -11
  146. package/src/tool-programs.ts +179 -0
  147. package/src/tool-test.ts +110 -12
  148. package/src/translator.ts +72 -22
  149. package/src/trigger-log.ts +1 -0
  150. package/src/triggers.ts +10 -2
  151. package/src/untrusted-fetch.ts +88 -0
  152. package/src/web-actions.ts +237 -0
  153. package/src/webhook.ts +41 -0
  154. package/templates/hello/agents/curator/agent.md +1 -1
  155. package/templates/hello/agents/notetaker/agent.md +1 -1
@@ -8,17 +8,39 @@
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
10
  import fs from "node:fs";
11
+ import os from "node:os";
11
12
  import path from "node:path";
12
13
  import { query } from "@anthropic-ai/claude-agent-sdk";
13
14
  import { spawn } from "node:child_process";
14
- import { checkPaths, checkBash, isFilesystemTool } from "./confine.js";
15
+ import { checkPaths, checkBash, isFilesystemTool, linkWorkspace, workspaceLinkEnv, resolveAgentPath, isWithin } from "./confine.js";
16
+ import { DELEGATE_TOOLS, subagentGuard, toAgentDefinitions } from "./subagents.js";
15
17
  import { hostSafeEnv } from "./host-env.js";
16
18
  import { validateSchema, describeSchemaErrors, looksLikeSchema } from "./json-schema.js";
19
+ import { CallCounter, limitKeysFor } from "./limits.js";
20
+ import { classifyCall, podAt, readPodEvents } from "./browser-pod.js";
17
21
  /** How often the stop flag is read while a step runs. */
18
22
  export const STOP_POLL_MS = 2000;
23
+ /** The least a `verify:` gets when the step used up most of its `timeout:` —
24
+ * capped by the timeout itself, so the step and its check together never
25
+ * run past timeout + this. Under the isolated path's backstop (+60 s). */
26
+ export const VERIFY_FLOOR_MS = 30_000;
27
+ /** How long a `verify:` may run: what is left of the step's `timeout:`,
28
+ * with a floor. Null when the flow set no timeout — `timeout:` is the only
29
+ * clock there is, and a stop still ends the check. */
30
+ export function verifyBudgetMs(timeoutSec, elapsedMs) {
31
+ if (!timeoutSec || timeoutSec <= 0)
32
+ return null;
33
+ const total = timeoutSec * 1000;
34
+ return Math.max(total - elapsedMs, Math.min(VERIFY_FLOOR_MS, total));
35
+ }
19
36
  /** After an interrupt is asked for, how long the model loop gets to wind
20
37
  * down on its own before the query is aborted outright. */
21
38
  export const INTERRUPT_GRACE_MS = 10_000;
39
+ /** The tag on every event a failed check writes — `verify:`, `output: json`,
40
+ * a schema — headline and detail alike. The runner's no-retry rule for
41
+ * outward steps reads it (actedThenFailedCheck); reading the wording of the
42
+ * last error missed a check whose detail line came after its headline. */
43
+ const CHECK = { check: true };
22
44
  /** Conservative per-token rates for a model nothing else can price — an
23
45
  * unknown id on a gateway with no catalogue. Opus-class, so a ceiling
24
46
  * still means something. Only ever reached when `knownPrice` below does
@@ -84,15 +106,19 @@ export function stepCeiling(budgetUsd, spentUsd, launching) {
84
106
  *
85
107
  * Two caps can apply to one step: the flow's `budget:` gives it an equal
86
108
  * share of what the run has left; the agent's own `budget:` is the most that
87
- * agent may spend in one run, less what its earlier steps in this run cost.
109
+ * agent may spend in one run, less what its steps in this run have cost or
110
+ * may still cost, shared across `sharing` — this step and the agent's steps
111
+ * launched with it that have not started yet. Without the share, twenty
112
+ * fan-out copies of one agent each got the whole remainder, because none of
113
+ * them has recorded a cent when the next one starts.
88
114
  * The tighter one wins, and the note says which, because "over budget" with
89
115
  * no line to go and raise is a message that sends someone to the wrong file.
90
116
  */
91
- export function stepCeilingFor(flowShareUsd, agentBudgetUsd, agentSpentUsd, agent) {
117
+ export function stepCeilingFor(flowShareUsd, agentBudgetUsd, agentSpentUsd, agent, sharing = 1) {
92
118
  const flow = { ceilingUsd: flowShareUsd, note: "budget: in the flow file" };
93
119
  if (!agentBudgetUsd || agentBudgetUsd <= 0)
94
120
  return flow;
95
- const left = Math.max(0, agentBudgetUsd - agentSpentUsd);
121
+ const left = Math.max(0, agentBudgetUsd - agentSpentUsd) / Math.max(1, sharing);
96
122
  if (flowShareUsd !== null && flowShareUsd <= left)
97
123
  return flow;
98
124
  return { ceilingUsd: left, note: `budget: on the ${agent} agent` };
@@ -101,10 +127,31 @@ export async function executeStep(opts,
101
127
  /** The model loop. Injected so the clock and the stop can be tested
102
128
  * without a model; production passes nothing and gets the SDK. */
103
129
  runQuery = query) {
130
+ // `workspace/…` for the shell, the scripts and a shell `verify:` — the
131
+ // file tools expand the prefix themselves. Held for the step, verify
132
+ // included, and gone before anyone reads the step's files back
133
+ // (confine.ts#linkWorkspace says why it is not permanent).
134
+ fs.mkdirSync(opts.agentDir, { recursive: true });
135
+ const link = linkWorkspace(opts.agentDir, opts.workspaceRoot);
136
+ if (link.note)
137
+ opts.emit("info", `workspace/: ${link.note}`);
138
+ try {
139
+ // And a Node program started through it is still its own main module
140
+ // (confine.ts#workspaceLinkEnv) — for the model's Bash, which inherits
141
+ // the SDK's env; the shell verify: and the scripts get it where they
142
+ // spawn.
143
+ return await executeStepInner({ ...opts, env: workspaceLinkEnv(opts.env, opts.agentDir) }, runQuery);
144
+ }
145
+ finally {
146
+ link.release();
147
+ }
148
+ }
149
+ async function executeStepInner(opts, runQuery) {
104
150
  const { agentDir, workspaceRoot, libraryRoot, emit } = opts;
105
151
  let status = "running";
106
152
  let costUsd = null;
107
153
  let usage = null;
154
+ let stopReason = null;
108
155
  const texts = [];
109
156
  fs.mkdirSync(path.join(agentDir, "outputs"), { recursive: true });
110
157
  fs.mkdirSync(path.join(agentDir, "memory"), { recursive: true });
@@ -112,6 +159,16 @@ runQuery = query) {
112
159
  // stop both ask the query to interrupt, and abort it outright if it has
113
160
  // not wound down within the grace period.
114
161
  const abort = new AbortController();
162
+ const subagents = opts.subagents?.length ? opts.subagents : null;
163
+ const guardSubagent = subagents ? subagentGuard(subagents) : null;
164
+ // A sub-agent's calls reach both the hook (which sees its id AND name) and
165
+ // canUseTool (which sees only the id). Remembered here so every refusal —
166
+ // its own list, a path outside the workspace, a shell command — names the
167
+ // agent that tried, not just the step.
168
+ const subagentNames = new Map();
169
+ // `limits:` — this step's counts. A new step, a retry of one, or a
170
+ // fan-out instance each start from zero.
171
+ const counter = new CallCounter(opts.limits);
115
172
  const q = runQuery({
116
173
  prompt: opts.prompt,
117
174
  options: {
@@ -124,6 +181,9 @@ runQuery = query) {
124
181
  ...(opts.effort ? { effort: opts.effort } : {}),
125
182
  systemPrompt: opts.systemPrompt,
126
183
  ...(opts.maxTurns ? { maxTurns: opts.maxTurns } : {}),
184
+ // Sub-agents: the SDK's own delegation. Every definition carries an
185
+ // explicit tool list (an absent one inherits all of ours).
186
+ ...(subagents ? { agents: toAgentDefinitions(subagents) } : {}),
127
187
  // Restrict the toolset itself, not just approval: an agent that
128
188
  // declares no tools gets none, instead of seeing the full Claude
129
189
  // Code toolset and burning turns on denied calls.
@@ -150,13 +210,96 @@ runQuery = query) {
150
210
  autoAllowBashIfSandboxed: false,
151
211
  failIfUnavailable: false,
152
212
  },
153
- env: opts.env,
213
+ // With sub-agents, the SDK would also offer its built-in ones
214
+ // (general-purpose has every tool the session has). Only the declared
215
+ // ones may run; the guard in the hook below refuses the rest as well.
216
+ env: subagents ? { ...(opts.env ?? process.env), CLAUDE_AGENT_SDK_DISABLE_BUILTIN_AGENTS: "1" } : opts.env,
154
217
  mcpServers: opts.mcpServers,
155
- canUseTool: async (toolName, input) => {
218
+ // canUseTool is only asked when the SDK wants permission, and it never
219
+ // asks for a read inside the cwd — so `Read workspace/storage/x` went
220
+ // to `<agentDir>/workspace/storage/x` unchecked and unrewritten. On
221
+ // 2026-09-24 that read a stray copy a broken write had left there,
222
+ // with no error. A PreToolUse hook runs on every call: expand the
223
+ // virtual prefix (and refuse an escape) here for every filesystem tool,
224
+ // and leave the rest of the decision to canUseTool.
225
+ hooks: {
226
+ PreToolUse: [{
227
+ hooks: [async (hookInput) => {
228
+ if (hookInput.hook_event_name !== "PreToolUse")
229
+ return {};
230
+ // A sub-agent's calls come through here too, tagged with its
231
+ // name; anything outside its own list — or from a sub-agent this
232
+ // step did not declare — is refused before the shared checks
233
+ // below (which apply to it unchanged). So is a delegation from
234
+ // the main thread to anything but a declared sub-agent.
235
+ const agentId = "agent_id" in hookInput && hookInput.agent_id ? String(hookInput.agent_id) : undefined;
236
+ const agentType = agentId ? hookInput.agent_type : undefined;
237
+ const via = agentId ? (agentType ?? "subagent") : undefined;
238
+ if (agentId && via)
239
+ subagentNames.set(agentId, via);
240
+ if (guardSubagent) {
241
+ const why = guardSubagent({ agentId, agentType, tool: hookInput.tool_name, input: (hookInput.tool_input ?? {}) });
242
+ if (why) {
243
+ emit("error", why, { subagent: via });
244
+ return { hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: why } };
245
+ }
246
+ }
247
+ const verdict = isFilesystemTool(hookInput.tool_name)
248
+ ? checkPaths(hookInput.tool_name, hookInput.tool_input, { agentDir, workspaceRoot, libraryRoot })
249
+ : null;
250
+ if (verdict && !verdict.ok) {
251
+ emit("error", verdict.reason, via ? { subagent: via } : undefined);
252
+ return { hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: verdict.reason } };
253
+ }
254
+ // `limits:` — last, so a call another check refused counts
255
+ // toward nothing. Every call passes here, the step's own and its
256
+ // sub-agents', so one count covers both. A call past a limit is
257
+ // refused before it runs: the tool, and any paid API behind it,
258
+ // never sees it.
259
+ if (counter.active) {
260
+ const refusal = counter.take(limitKeysFor(hookInput.tool_name, hookInput.tool_input, opts.toolOwners));
261
+ if (refusal) {
262
+ emit("info", `${refusal.message} (${hookInput.tool_name} refused)`, via ? { subagent: via } : undefined);
263
+ return { hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: refusal.message } };
264
+ }
265
+ }
266
+ if (!verdict?.updatedInput)
267
+ return {};
268
+ return { hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "allow", updatedInput: verdict.updatedInput } };
269
+ }],
270
+ }],
271
+ // A message a person sent into the running step reaches the model
272
+ // after its next tool call, as context — never as a change to what it
273
+ // may do. A model that is only writing, calling no tools, hears it at
274
+ // the next call it makes.
275
+ ...(opts.inbox
276
+ ? {
277
+ PostToolUse: [{
278
+ hooks: [async (hookInput) => {
279
+ if (hookInput.hook_event_name !== "PostToolUse")
280
+ return {};
281
+ // A sub-agent's call: the message is for the step's own
282
+ // model, and draining it here would hand it to a context
283
+ // that ends with the delegation — and lose it.
284
+ if ("agent_id" in hookInput && hookInput.agent_id)
285
+ return {};
286
+ const context = await opts.inbox().catch(() => null);
287
+ return context ? { hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext: context } } : {};
288
+ }],
289
+ }],
290
+ }
291
+ : {}),
292
+ },
293
+ canUseTool: async (toolName, input, options) => {
294
+ const via = options?.agentID ? (subagentNames.get(options.agentID) ?? "subagent") : undefined;
156
295
  // The toolset was already narrowed to what the agent declared, so
157
296
  // anything outside it is a denial with a reason the model can act on.
158
297
  const fromGrantedServer = opts.mcpNames.some((n) => toolName.startsWith(`mcp__${n}__`));
298
+ // A call the hook counted and this refuses never ran: give it back.
299
+ const refund = () => { if (counter.active)
300
+ counter.refund(limitKeysFor(toolName, input, opts.toolOwners)); };
159
301
  if (!opts.allowed.includes(toolName) && !fromGrantedServer) {
302
+ refund();
160
303
  return {
161
304
  behavior: "deny",
162
305
  message: `Tool ${toolName} is not enabled for this agent.`,
@@ -168,7 +311,8 @@ runQuery = query) {
168
311
  ? checkPaths(toolName, input, { agentDir, workspaceRoot, libraryRoot })
169
312
  : { ok: true };
170
313
  if (!verdict.ok) {
171
- emit("error", verdict.reason);
314
+ refund();
315
+ emit("error", verdict.reason, via ? { subagent: via } : undefined);
172
316
  return { behavior: "deny", message: verdict.reason };
173
317
  }
174
318
  return { behavior: "allow", updatedInput: verdict.updatedInput ?? input };
@@ -181,6 +325,7 @@ runQuery = query) {
181
325
  // was nothing to check it against. The backstop timer fires regardless,
182
326
  // and a stop is read on a clock rather than between groups.
183
327
  let ended = null;
328
+ const startedAt = Date.now();
184
329
  const timers = [];
185
330
  const endWith = (why) => {
186
331
  if (ended)
@@ -213,31 +358,136 @@ runQuery = query) {
213
358
  // that is the honest direction to be wrong in.
214
359
  const ceiling = typeof opts.budgetUsd === "number" && opts.budgetUsd > 0 ? opts.budgetUsd : null;
215
360
  let spentUsd = 0;
361
+ // Every turn's usage, by the model message's id. The SDK can emit one
362
+ // turn as several assistant messages that repeat the same usage, so a
363
+ // turn is counted once — and the sum is the step's cost whenever the
364
+ // closing `result` never arrives: a timeout or a stop ends the loop before
365
+ // it, and a step that made 193 model calls was recorded as $0 (lawyer-desk,
366
+ // 2026-09-25 09:00).
367
+ // Each with the rate it is priced at: a sub-agent with its own `model:`
368
+ // runs its turns on that model, and pricing them at the parent's put a
369
+ // max sub-agent under a fast parent at a fifth of its cost — against the
370
+ // ceiling and on the bill.
371
+ const turns = new Map();
372
+ let anonymousTurns = 0;
373
+ const specByName = new Map((subagents ?? []).map((s) => [s.name, s]));
374
+ const priceOf = (message) => {
375
+ const parent = message.parent_tool_use_id;
376
+ if (!parent)
377
+ return opts.price ?? null;
378
+ const declared = specByName.get(delegations.get(parent) ?? "")?.model;
379
+ if (declared === undefined || declared === "inherit" || declared === opts.model)
380
+ return opts.price ?? null;
381
+ const model = message.message?.model;
382
+ return knownPrice(typeof model === "string" ? model : undefined) ?? knownPrice(declared);
383
+ };
384
+ const turnsTotal = () => [...turns.values()].reduce((sum, t) => sum + priceTurn(t.u, t.price), 0);
385
+ const mixedModels = () => [...turns.values()].some((t) => t.price !== (opts.price ?? null));
216
386
  // Open tool calls, by the provider's id, so the result can be paired with
217
387
  // its call and the trace can say how long each tool ran.
218
388
  const openCalls = new Map();
389
+ // Delegations in flight: the parent's Agent call id → the sub-agent's name.
390
+ // The SDK tags every message a sub-agent produces with that call's id
391
+ // (parent_tool_use_id), which is how its tool calls are labelled here.
392
+ const delegations = new Map();
393
+ const subagentOf = (message) => {
394
+ const parent = message.parent_tool_use_id;
395
+ return parent ? (delegations.get(parent) ?? "subagent") : undefined;
396
+ };
397
+ // Slim browsing (browser-pod.ts): every call the step makes, read or
398
+ // write, in the order the model asked for them — the step's own and its
399
+ // sub-agents'. Classified when asked for, not when answered: a call in
400
+ // flight when the pod goes is counted as made. And the web tool's pod log,
401
+ // read after every tool result.
402
+ const pod = opts.browserPod ?? null;
403
+ const ledger = new Map();
404
+ const podState = { reconnects: 0, reconnected: 0 };
405
+ let podOffset = 0;
406
+ const readPod = (callId) => {
407
+ if (!pod)
408
+ return;
409
+ let text;
410
+ try {
411
+ text = fs.readFileSync(pod.events, "utf8");
412
+ }
413
+ catch {
414
+ return; // nothing written yet
415
+ }
416
+ const { events, next } = readPodEvents(text, podOffset);
417
+ podOffset = next;
418
+ let closedAgain = false;
419
+ for (const [i, e] of events.entries()) {
420
+ if (e.kind === "reconnect") {
421
+ podState.reconnects += 1;
422
+ // A reconnect that reached the pod, and then the call dropped again
423
+ // at once (the web tool's next line is "lost"), did not get
424
+ // through: the pod answered while it shut down. Live, 2026-10-01,
425
+ // "reconnected (try 1 of 3)" was followed by "lost after 1
426
+ // reconnect try" and the step read "1 got through".
427
+ closedAgain = !!e.ok && events[i + 1]?.kind === "lost";
428
+ if (closedAgain)
429
+ podState.closedAgain = (podState.closedAgain ?? 0) + 1;
430
+ else if (e.ok)
431
+ podState.reconnected += 1;
432
+ // `at` is when the try happened: these lines reach the run when the
433
+ // call returns, so the run's own stamps on them are all the same.
434
+ emit("info", `browser pod: ${e.ok ? "reconnected" : "reconnect failed"} (try ${e.attempt ?? "?"} of ${e.of ?? "?"}${podAt(e.at)})${!e.ok && e.error ? ` — ${e.error}` : ""}${closedAgain ? ", but the pod closed again" : ""}`);
435
+ }
436
+ else if (!podState.lost) {
437
+ // A call that never reached the pod changed nothing, whatever its
438
+ // arguments asked for.
439
+ if (e.ran === false)
440
+ ledger.delete(callId);
441
+ podState.lost = { cause: e.kind, detail: (e.kind === "needs-full" ? e.why : e.error) ?? "connection closed" };
442
+ emit("info", e.kind === "needs-full"
443
+ ? `browser pod: this call needs a browser in the step, which the slim image has not (${podState.lost.detail}) — stopping the step`
444
+ : closedAgain
445
+ ? `browser pod: lost — the call dropped again after the reconnect (${podState.lost.detail}${podAt(e.at)}) — stopping the step`
446
+ : `browser pod: lost after ${podState.reconnects} reconnect tr${podState.reconnects === 1 ? "y" : "ies"} (${podState.lost.detail}${podAt(e.at)}) — stopping the step`);
447
+ endWith("pod-lost");
448
+ }
449
+ }
450
+ };
219
451
  try {
220
452
  for await (const message of q) {
221
453
  if (ended)
222
454
  break;
223
455
  if (message.type === "assistant") {
224
- const u = message.message.usage;
456
+ const m = message.message;
457
+ const u = m.usage;
458
+ if (u)
459
+ turns.set(m.id ?? `turn-${anonymousTurns++}`, { u, price: priceOf(message) });
225
460
  if (ceiling && u) {
226
- spentUsd += priceTurn(u, opts.price ?? null);
461
+ spentUsd = turnsTotal();
227
462
  if (spentUsd >= ceiling) {
228
463
  emit("error", `over budget — this step reached $${spentUsd.toFixed(4)} of its $${ceiling.toFixed(4)} ceiling mid-turn and was stopped (${opts.budgetNote ?? "budget: in the flow file"})`);
229
464
  status = "failed";
230
465
  break;
231
466
  }
232
467
  }
468
+ const via = subagentOf(message);
233
469
  for (const block of message.message.content) {
234
470
  if (block.type === "text" && block.text.trim()) {
471
+ // A sub-agent's own words are its business; the parent's reply is
472
+ // the step's result. (The SDK forwards only tool blocks by default.)
473
+ if (via)
474
+ continue;
235
475
  texts.push(block.text);
236
476
  emit("text", block.text);
237
477
  }
238
478
  else if (block.type === "tool_use") {
239
- openCalls.set(block.id, { name: block.name, at: Date.now() });
240
- emit("tool", block.name, { call: block.id });
479
+ if (!via && DELEGATE_TOOLS.includes(block.name)) {
480
+ const input = block.input;
481
+ const to = String(input?.subagent_type ?? "subagent");
482
+ delegations.set(block.id, to);
483
+ // One line a person can read: who got the job, and what it was.
484
+ const job = String(input?.description ?? input?.prompt ?? "").replace(/\s+/g, " ").trim().slice(0, 160);
485
+ emit("info", `delegating to ${to}${job ? `: ${job}` : ""}`, { subagent: to });
486
+ }
487
+ openCalls.set(block.id, { name: block.name, at: Date.now(), ...(via ? { subagent: via } : {}) });
488
+ if (pod)
489
+ ledger.set(block.id, classifyCall(block.name, block.input, pod));
490
+ emit("tool", block.name, { call: block.id, ...(via ? { subagent: via } : {}) });
241
491
  }
242
492
  }
243
493
  }
@@ -257,7 +507,9 @@ runQuery = query) {
257
507
  call: block.tool_use_id,
258
508
  ms: Date.now() - open.at,
259
509
  ...(block.is_error ? { err: true } : {}),
510
+ ...(open.subagent ? { subagent: open.subagent } : {}),
260
511
  });
512
+ readPod(block.tool_use_id);
261
513
  }
262
514
  }
263
515
  }
@@ -267,6 +519,7 @@ runQuery = query) {
267
519
  emit("error", `stopped after ${opts.maxTurns ?? "its"} turns (max_turns: in the flow file) — the step did not finish`);
268
520
  }
269
521
  costUsd = "total_cost_usd" in message ? (message.total_cost_usd ?? null) : null;
522
+ stopReason = "stop_reason" in message && typeof message.stop_reason === "string" ? message.stop_reason : null;
270
523
  if ("usage" in message && message.usage) {
271
524
  const u = message.usage;
272
525
  usage = {
@@ -291,6 +544,27 @@ runQuery = query) {
291
544
  for (const t of timers)
292
545
  clearTimeout(t);
293
546
  }
547
+ // What the step used of each limit, on the trace whenever any is set —
548
+ // so "it stopped searching at 40" is read off the run, not guessed.
549
+ const limitLine = counter.summary();
550
+ if (limitLine)
551
+ emit("info", limitLine);
552
+ // No result message — a timeout, a stop, a budget stop, a stream that
553
+ // died — means no total from the SDK. The turns it did take were billed by
554
+ // the provider all the same, so the step's cost is their sum.
555
+ if (costUsd === null && turns.size) {
556
+ let input = 0;
557
+ let output = 0;
558
+ let priced = 0;
559
+ for (const { u: t, price } of turns.values()) {
560
+ input += (t.input_tokens ?? 0) + (t.cache_creation_input_tokens ?? 0) + (t.cache_read_input_tokens ?? 0);
561
+ output += t.output_tokens ?? 0;
562
+ priced += priceTurn(t, price);
563
+ }
564
+ costUsd = priced;
565
+ usage ??= { inputTokens: input, outputTokens: output };
566
+ emit("info", `cost from ${turns.size} model turn${turns.size === 1 ? "" : "s"}: $${priced.toFixed(4)} — the step ended before the model's closing total`);
567
+ }
294
568
  if (ended === "timeout") {
295
569
  emit("error", `timed out after ${opts.timeoutSec}s (timeout: in the flow file) — the step was stopped with the files it wrote so far kept`);
296
570
  status = "failed";
@@ -299,6 +573,17 @@ runQuery = query) {
299
573
  emit("error", "stopped by a person mid-step");
300
574
  status = "failed";
301
575
  }
576
+ else if (ended === "pod-lost") {
577
+ // The runner says what happens next — a re-run on the full image, or a
578
+ // failure naming what was written. Not an error of the step's own.
579
+ status = "failed";
580
+ }
581
+ if (pod) {
582
+ readPod("");
583
+ if (podState.lost) {
584
+ podState.writes = [...ledger.values()].flatMap((k) => (k.write ? [k.what] : []));
585
+ }
586
+ }
302
587
  // The SDK ends a healthy run with a `result` message. A stream that just
303
588
  // stops — subprocess OOM-killed, crashed, or torn down — used to fall
304
589
  // through as "completed", which reported a run that produced nothing as a
@@ -328,31 +613,83 @@ runQuery = query) {
328
613
  // failure as no value, and the message names the field.
329
614
  const errors = opts.schema !== undefined && looksLikeSchema(opts.schema) ? validateSchema(data, opts.schema) : [];
330
615
  if (errors.length) {
331
- emit("error", `schema: the value does not fit — ${describeSchemaErrors(errors)}`);
616
+ emit("error", `schema: the value does not fit — ${describeSchemaErrors(errors)}`, CHECK);
332
617
  status = "failed";
333
618
  }
334
619
  }
335
620
  else {
336
- emit("error", `output: json — ${extracted.reason}`);
621
+ emit("error", `output: json — ${extracted.reason}`, CHECK);
337
622
  status = "failed";
338
623
  }
339
624
  }
340
625
  // "Done" should mean a check passed, not that the model stopped talking.
626
+ // The loop's clocks are cleared by now, so the check gets its own: what is
627
+ // left of the step's `timeout:` (never less than VERIFY_FLOOR_MS of it),
628
+ // and a stop read on the same clock the loop used. No `timeout:`, no clock:
629
+ // it is the only one there is, here as in the loop. A `verify:` that hangs
630
+ // — a build waiting on a lock, a judge that never answers — used to hold
631
+ // the step, and the run, with nothing to end it.
341
632
  if (status === "completed" && opts.verify) {
342
- const verdict = await checkVerify(agentDir, opts.verify, {
343
- env: opts.verifyEnv ?? {},
344
- result,
345
- conclusion,
346
- data,
347
- modelEnv: opts.env,
348
- });
349
- emit(verdict.ok ? "info" : "error", `verify \`${opts.verify}\` → ${verdict.headline}`);
350
- if (verdict.detail.trim())
351
- emit(verdict.ok ? "info" : "error", verdict.detail.slice(0, 1000));
352
- if (!verdict.ok)
633
+ const verifyMs = verifyBudgetMs(opts.timeoutSec, Date.now() - startedAt);
634
+ const halt = new AbortController();
635
+ let cut = null;
636
+ const clocks = [];
637
+ if (verifyMs !== null) {
638
+ clocks.push(setTimeout(() => {
639
+ cut ??= "timeout";
640
+ halt.abort();
641
+ }, verifyMs));
642
+ }
643
+ if (opts.stopRequested) {
644
+ clocks.push(setInterval(() => {
645
+ try {
646
+ if (opts.stopRequested()) {
647
+ cut ??= "stopped";
648
+ halt.abort();
649
+ }
650
+ }
651
+ catch {
652
+ // an unreadable record is not a stop
653
+ }
654
+ }, STOP_POLL_MS));
655
+ }
656
+ let verdict;
657
+ try {
658
+ verdict = await checkVerify(agentDir, opts.verify, {
659
+ env: opts.verifyEnv ?? {},
660
+ result,
661
+ conclusion,
662
+ data,
663
+ modelEnv: opts.env,
664
+ signal: halt.signal,
665
+ });
666
+ }
667
+ finally {
668
+ for (const t of clocks)
669
+ clearTimeout(t);
670
+ }
671
+ if (cut === "timeout") {
672
+ emit("error", `verify \`${opts.verify}\` → timed out after ${Math.round(verifyMs / 1000)}s (what was left of timeout: in the flow file) — it was stopped`, CHECK);
673
+ status = "failed";
674
+ }
675
+ else if (cut === "stopped") {
676
+ emit("error", `verify \`${opts.verify}\` → stopped by a person mid-check`, CHECK);
353
677
  status = "failed";
678
+ }
679
+ else {
680
+ emit(verdict.ok ? "info" : "error", `verify \`${opts.verify}\` → ${verdict.headline}`, verdict.ok ? undefined : CHECK);
681
+ if (verdict.detail.trim())
682
+ emit(verdict.ok ? "info" : "error", verdict.detail.slice(0, 1000), verdict.ok ? undefined : CHECK);
683
+ if (!verdict.ok)
684
+ status = "failed";
685
+ }
354
686
  }
355
- return { status, result, conclusion, ...(opts.output ? { data } : {}), costUsd, usage };
687
+ return {
688
+ status, result, conclusion, ...(opts.output ? { data } : {}), costUsd, usage,
689
+ ...(mixedModels() ? { turnsCostUsd: turnsTotal() } : {}),
690
+ stopReason,
691
+ ...(pod ? { browserPod: podState } : {}),
692
+ };
356
693
  }
357
694
  // ------------------------------------------------------------ output: json
358
695
  /**
@@ -410,8 +747,21 @@ const VERIFY_ASSERTION = /^(contains|not-contains|matches|file|judge):\s*([\s\S]
410
747
  export async function checkVerify(agentDir, verify, ctx) {
411
748
  const m = verify.trim().match(VERIFY_ASSERTION);
412
749
  if (!m) {
413
- const { code, out } = await runVerify(agentDir, verify, ctx.env, ctx.data);
414
- return { ok: code === 0, headline: `exit ${code ?? "error"}`, detail: out };
750
+ // The step's final turn, as a file named in FOLDRUN_REPLY_FILE — so one
751
+ // command can check the reply and the artefact together
752
+ // (`grep -q '^READY' "$FOLDRUN_REPLY_FILE" && test -s out.json`). A step
753
+ // has one `verify:`, and a shell check that could not see the reply
754
+ // made authors choose between the two.
755
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "foldrun-reply-"));
756
+ const replyFile = path.join(dir, "reply.md");
757
+ fs.writeFileSync(replyFile, ctx.conclusion ?? ctx.result ?? "");
758
+ try {
759
+ const { code, out } = await runVerify(agentDir, verify, { ...ctx.env, FOLDRUN_REPLY_FILE: replyFile }, ctx.data, ctx.signal);
760
+ return { ok: code === 0, headline: `exit ${code ?? "error"}`, detail: out };
761
+ }
762
+ finally {
763
+ fs.rmSync(dir, { recursive: true, force: true });
764
+ }
415
765
  }
416
766
  const [, kind, rawValue] = m;
417
767
  const value = rawValue.trim().replace(/^["']|["']$/g, "");
@@ -436,15 +786,20 @@ export async function checkVerify(agentDir, verify, ctx) {
436
786
  }
437
787
  }
438
788
  case "file": {
439
- const target = path.resolve(agentDir, value);
440
- if (!target.startsWith(path.resolve(agentDir) + path.sep)) {
441
- return { ok: false, headline: "path escapes the agent directory", detail: "" };
789
+ // Agent-relative like every path in a flow, or `workspace/…` from the
790
+ // workspace root; confined to the workspace. It was confined to the
791
+ // agent's own folder, so the one place a step's deliverable belongs —
792
+ // `workspace/storage/x`, or `../../storage/x` — was always "escapes".
793
+ const workspaceRoot = path.resolve(agentDir, "..", "..");
794
+ const target = resolveAgentPath(workspaceRoot, agentDir, value);
795
+ if (!isWithin(workspaceRoot, target) || target === workspaceRoot) {
796
+ return { ok: false, headline: "path escapes the workspace", detail: "" };
442
797
  }
443
798
  const ok = fs.existsSync(target) && fs.statSync(target).size > 0;
444
799
  return { ok, headline: ok ? "present and non-empty" : `${value} is missing or empty`, detail: "" };
445
800
  }
446
801
  case "judge": {
447
- const verdict = await judgeReply(value, output, ctx.modelEnv ?? {});
802
+ const verdict = await judgeReply(value, output, ctx.modelEnv ?? {}, ctx.signal);
448
803
  const ok = /^\s*PASS\b/i.test(verdict);
449
804
  return { ok, headline: ok ? "PASS" : "FAIL", detail: verdict.slice(0, 300) };
450
805
  }
@@ -456,8 +811,12 @@ export async function checkVerify(agentDir, verify, ctx) {
456
811
  * Same shape as the eval judge, and answered with one word first so the
457
812
  * verdict is a prefix test rather than a reading.
458
813
  */
459
- async function judgeReply(rubric, output, env) {
814
+ async function judgeReply(rubric, output, env, signal) {
460
815
  const texts = [];
816
+ const abortController = new AbortController();
817
+ if (signal?.aborted)
818
+ abortController.abort();
819
+ signal?.addEventListener("abort", () => abortController.abort(), { once: true });
461
820
  try {
462
821
  const q = query({
463
822
  prompt: `You are grading a reply against one requirement. Answer with PASS or FAIL as the ` +
@@ -470,6 +829,7 @@ async function judgeReply(rubric, output, env) {
470
829
  settingSources: [],
471
830
  env,
472
831
  maxTurns: 1,
832
+ abortController,
473
833
  },
474
834
  });
475
835
  for await (const message of q) {
@@ -488,19 +848,37 @@ async function judgeReply(rubric, output, env) {
488
848
  }
489
849
  // Verification runs in the agent's directory with its secrets available, so
490
850
  // a check can be as simple as `npm run build` or `test -s outputs/report.md`.
491
- function runVerify(agentDir, command, env, data) {
851
+ function runVerify(agentDir, command, env, data, signal) {
492
852
  return new Promise((resolve) => {
493
- // No clock of the platform's: a verify like `npm run build` takes what
494
- // it takes, and the step's own `timeout:` is the bound if the flow set one.
853
+ // The clock is the caller's (executeStep): what is left of the step's
854
+ // `timeout:`, ended through `signal`, which a stop also fires.
495
855
  // The allowlisted host base plus what the caller passed: the step's
496
856
  // secrets and identifiers on the in-process path (runner.ts), the
497
857
  // container's own environment on the isolated one (run-container.ts).
498
858
  // Never process.env whole — see host-env.ts.
499
859
  const child = spawn("bash", ["-lc", command], {
500
860
  cwd: agentDir,
501
- env: { ...hostSafeEnv(), ...env },
861
+ // workspaceLinkEnv: `node workspace/tools/x/check.mjs` must run its
862
+ // check, not pass for having skipped it (confine.ts says how).
863
+ env: workspaceLinkEnv({ ...hostSafeEnv(), ...env }, agentDir),
502
864
  stdio: ["pipe", "pipe", "pipe"],
865
+ // Its own process group, so an abort ends what the shell started
866
+ // (`npm run build` and its children) and not only bash.
867
+ detached: true,
503
868
  });
869
+ const kill = () => {
870
+ try {
871
+ process.kill(-child.pid, "SIGKILL");
872
+ }
873
+ catch {
874
+ child.kill("SIGKILL");
875
+ }
876
+ };
877
+ if (signal?.aborted)
878
+ kill();
879
+ else
880
+ signal?.addEventListener("abort", kill, { once: true });
881
+ child.on("close", () => signal?.removeEventListener("abort", kill));
504
882
  // An `output: json` step's data arrives on stdin, so a check can be
505
883
  // `jq -e '.total > 0'` — arithmetic in a real tool, reading the value
506
884
  // the step actually returned rather than re-parsing its prose.