operon-agents-core 0.1.0-alpha.2 → 0.1.0-alpha.21

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 (289) hide show
  1. package/dist/agent/agent.d.ts +8 -7
  2. package/dist/agent/compose-hooks.d.ts +10 -1
  3. package/dist/agent/compose-hooks.js +61 -6
  4. package/dist/agent/concurrency.js +1 -1
  5. package/dist/agent/context-report.d.ts +2 -2
  6. package/dist/agent/durable-state.d.ts +22 -0
  7. package/dist/agent/durable-state.js +54 -0
  8. package/dist/agent/index.d.ts +2 -2
  9. package/dist/agent/index.js +1 -1
  10. package/dist/agent/instruction-context.d.ts +6 -6
  11. package/dist/agent/instruction-context.js +23 -23
  12. package/dist/agent/profile-builtins.js +1 -1
  13. package/dist/agent/run-support.d.ts +1 -1
  14. package/dist/agent/run-support.js +6 -5
  15. package/dist/agent/runner.d.ts +25 -22
  16. package/dist/agent/runner.js +217 -121
  17. package/dist/agent/session.d.ts +262 -156
  18. package/dist/agent/session.js +590 -418
  19. package/dist/agent/subagent-tools.js +3 -3
  20. package/dist/agent/subagent.js +28 -13
  21. package/dist/agent/toolset.d.ts +1 -0
  22. package/dist/agent/toolset.js +13 -7
  23. package/dist/agent/workflow/journal.d.ts +2 -2
  24. package/dist/agent/workflow/journal.js +2 -2
  25. package/dist/agent/workflow/manager.d.ts +1 -1
  26. package/dist/agent/workflow/manager.js +1 -1
  27. package/dist/agent/workflow/prompt.js +2 -2
  28. package/dist/agent/workflow/sandbox.d.ts +1 -1
  29. package/dist/agent/workflow/sandbox.js +1 -1
  30. package/dist/agent/workflow/tool.js +30 -43
  31. package/dist/agent/worktree.d.ts +8 -8
  32. package/dist/agent/worktree.js +15 -15
  33. package/dist/capabilities/assembler.d.ts +29 -5
  34. package/dist/capabilities/assembler.js +85 -9
  35. package/dist/capabilities/background/code-task.d.ts +43 -0
  36. package/dist/capabilities/background/code-task.js +75 -0
  37. package/dist/capabilities/background/command-task.d.ts +9 -2
  38. package/dist/capabilities/background/command-task.js +22 -6
  39. package/dist/capabilities/background/index.d.ts +6 -1
  40. package/dist/capabilities/background/index.js +26 -20
  41. package/dist/capabilities/background/manager.d.ts +57 -1
  42. package/dist/capabilities/background/manager.js +210 -45
  43. package/dist/capabilities/background/persist-disk.d.ts +1 -1
  44. package/dist/capabilities/background/persist-disk.js +1 -1
  45. package/dist/capabilities/background/persist.js +4 -2
  46. package/dist/capabilities/background/projections.d.ts +16 -0
  47. package/dist/capabilities/background/projections.js +86 -0
  48. package/dist/capabilities/background/stall-watchdog.d.ts +41 -0
  49. package/dist/capabilities/background/stall-watchdog.js +85 -0
  50. package/dist/capabilities/background/task.d.ts +8 -7
  51. package/dist/capabilities/background/tools.js +33 -7
  52. package/dist/capabilities/capability-data.d.ts +52 -0
  53. package/dist/capabilities/capability-data.js +88 -0
  54. package/dist/capabilities/capability-state.d.ts +2 -4
  55. package/dist/capabilities/capability-state.js +5 -23
  56. package/dist/capabilities/capability.d.ts +203 -38
  57. package/dist/capabilities/compaction/index.js +10 -4
  58. package/dist/capabilities/compaction/service.d.ts +20 -5
  59. package/dist/capabilities/compaction/service.js +27 -11
  60. package/dist/capabilities/goal/goal-store.d.ts +76 -12
  61. package/dist/capabilities/goal/goal-store.js +137 -53
  62. package/dist/capabilities/goal/index.d.ts +1 -1
  63. package/dist/capabilities/goal/index.js +30 -7
  64. package/dist/capabilities/index.d.ts +9 -6
  65. package/dist/capabilities/index.js +4 -3
  66. package/dist/capabilities/plan/index.js +22 -5
  67. package/dist/capabilities/plan/plan-mode.d.ts +30 -9
  68. package/dist/capabilities/plan/plan-mode.js +57 -32
  69. package/dist/capabilities/plan/tools.js +1 -1
  70. package/dist/capabilities/skills/flow-provider.js +3 -3
  71. package/dist/capabilities/skills/index.d.ts +13 -1
  72. package/dist/capabilities/skills/index.js +30 -21
  73. package/dist/capabilities/skills/parser.d.ts +2 -2
  74. package/dist/capabilities/skills/parser.js +3 -3
  75. package/dist/capabilities/skills/registry.d.ts +5 -6
  76. package/dist/capabilities/skills/registry.js +6 -9
  77. package/dist/capabilities/skills/scanner.d.ts +3 -3
  78. package/dist/capabilities/skills/scanner.js +14 -14
  79. package/dist/capabilities/skills/service.d.ts +2 -1
  80. package/dist/capabilities/skills/service.js +3 -3
  81. package/dist/capabilities/skills/skill-tool.d.ts +2 -0
  82. package/dist/capabilities/skills/skill-tool.js +1 -1
  83. package/dist/capabilities/task/index.js +2 -1
  84. package/dist/capabilities/task/persist-disk.d.ts +1 -1
  85. package/dist/capabilities/task/persist-disk.js +1 -1
  86. package/dist/capabilities/task/persist.js +1 -1
  87. package/dist/capabilities/todo/index.js +11 -6
  88. package/dist/capabilities/todo/injector.js +2 -1
  89. package/dist/capabilities/todo/todo-store.d.ts +28 -7
  90. package/dist/capabilities/todo/todo-store.js +44 -11
  91. package/dist/capabilities/todo/tools.js +8 -3
  92. package/dist/capabilities/tool-provider.d.ts +3 -3
  93. package/dist/capabilities/user-hooks/engine.d.ts +3 -3
  94. package/dist/capabilities/user-hooks/engine.js +7 -7
  95. package/dist/capabilities/user-hooks/index.js +2 -1
  96. package/dist/capabilities/workflow/index.d.ts +5 -3
  97. package/dist/capabilities/workflow/index.js +3 -2
  98. package/dist/commands/index.js +34 -32
  99. package/dist/config/index.d.ts +1 -1
  100. package/dist/config/provider-manager.js +0 -28
  101. package/dist/config/schema.d.ts +53 -4
  102. package/dist/config/schema.js +53 -1
  103. package/dist/events/events.d.ts +43 -11
  104. package/dist/events/events.js +1 -0
  105. package/dist/events/index.d.ts +2 -2
  106. package/dist/events/index.js +1 -1
  107. package/dist/events/projection.d.ts +49 -1
  108. package/dist/events/projection.js +144 -19
  109. package/dist/events/publisher.js +2 -21
  110. package/dist/home.d.ts +1 -1
  111. package/dist/home.js +1 -1
  112. package/dist/index.d.ts +3 -2
  113. package/dist/index.js +2 -1
  114. package/dist/internal.d.ts +5 -2
  115. package/dist/internal.js +5 -2
  116. package/dist/llm/define-model.d.ts +4 -0
  117. package/dist/llm/define-model.js +63 -25
  118. package/dist/llm/index.d.ts +1 -0
  119. package/dist/llm/index.js +1 -0
  120. package/dist/llm/model.d.ts +2 -0
  121. package/dist/llm/provider.d.ts +17 -0
  122. package/dist/llm/provider.js +14 -0
  123. package/dist/llm/retry.js +1 -1
  124. package/dist/loop/context.d.ts +21 -1
  125. package/dist/loop/context.js +47 -9
  126. package/dist/loop/events.d.ts +5 -1
  127. package/dist/loop/index.d.ts +2 -2
  128. package/dist/loop/index.js +1 -1
  129. package/dist/loop/interruption.d.ts +9 -4
  130. package/dist/loop/interruption.js +11 -25
  131. package/dist/loop/run-turn.d.ts +16 -3
  132. package/dist/loop/run-turn.js +13 -4
  133. package/dist/loop/steer.d.ts +78 -12
  134. package/dist/loop/steer.js +101 -38
  135. package/dist/loop/tool-call.d.ts +13 -2
  136. package/dist/loop/tool-call.js +135 -5
  137. package/dist/loop/turn-step.d.ts +13 -2
  138. package/dist/loop/turn-step.js +29 -7
  139. package/dist/loop/types.d.ts +6 -0
  140. package/dist/mcp/auth-tool.d.ts +3 -1
  141. package/dist/mcp/auth-tool.js +2 -2
  142. package/dist/mcp/capability.d.ts +13 -0
  143. package/dist/mcp/capability.js +36 -17
  144. package/dist/mcp/config-loader.d.ts +5 -5
  145. package/dist/mcp/config-loader.js +17 -17
  146. package/dist/mcp/credentials.d.ts +35 -0
  147. package/dist/mcp/credentials.js +2 -0
  148. package/dist/mcp/filter.d.ts +2 -2
  149. package/dist/mcp/index.d.ts +4 -3
  150. package/dist/mcp/index.js +1 -1
  151. package/dist/mcp/manager.d.ts +108 -6
  152. package/dist/mcp/manager.js +262 -18
  153. package/dist/mcp/oauth/callback-server.d.ts +10 -1
  154. package/dist/mcp/oauth/callback-server.js +82 -16
  155. package/dist/mcp/oauth/index.d.ts +2 -2
  156. package/dist/mcp/oauth/provider.d.ts +18 -0
  157. package/dist/mcp/oauth/provider.js +31 -1
  158. package/dist/mcp/oauth/service.d.ts +9 -3
  159. package/dist/mcp/oauth/service.js +29 -4
  160. package/dist/mcp/sdk-transport.js +1 -1
  161. package/dist/mcp/server.js +1 -1
  162. package/dist/permission/auto-approver/prompts-data.d.ts +1 -1
  163. package/dist/permission/auto-approver/prompts-data.js +1 -1
  164. package/dist/permission/manager.d.ts +5 -3
  165. package/dist/permission/manager.js +7 -3
  166. package/dist/permission/policies.d.ts +2 -2
  167. package/dist/permission/policies.js +4 -4
  168. package/dist/plugins/fields.d.ts +14 -0
  169. package/dist/plugins/fields.js +30 -0
  170. package/dist/plugins/hooks.d.ts +2 -2
  171. package/dist/plugins/hooks.js +12 -12
  172. package/dist/plugins/index.js +1 -0
  173. package/dist/plugins/manager.d.ts +8 -3
  174. package/dist/plugins/manager.js +18 -7
  175. package/dist/plugins/manifest.d.ts +2 -2
  176. package/dist/plugins/manifest.js +101 -91
  177. package/dist/plugins/marketplace.js +76 -57
  178. package/dist/plugins/store.d.ts +3 -3
  179. package/dist/plugins/store.js +6 -6
  180. package/dist/protocol/index.d.ts +1 -1
  181. package/dist/store/catalog-store.d.ts +4 -1
  182. package/dist/store/catalog-store.js +5 -1
  183. package/dist/store/checkpointing-store.d.ts +41 -0
  184. package/dist/store/checkpointing-store.js +86 -0
  185. package/dist/store/disk-store.d.ts +8 -0
  186. package/dist/store/disk-store.js +127 -5
  187. package/dist/store/index.d.ts +3 -2
  188. package/dist/store/index.js +2 -1
  189. package/dist/store/log-store.d.ts +9 -1
  190. package/dist/store/log-store.js +68 -4
  191. package/dist/store/migrate.d.ts +8 -2
  192. package/dist/store/migrate.js +9 -2
  193. package/dist/store/origin.d.ts +31 -6
  194. package/dist/store/origin.js +0 -14
  195. package/dist/store/pg.d.ts +1 -0
  196. package/dist/store/pg.js +37 -2
  197. package/dist/store/redis.d.ts +1 -0
  198. package/dist/store/redis.js +30 -0
  199. package/dist/store/repository.d.ts +13 -1
  200. package/dist/store/repository.js +45 -2
  201. package/dist/store/session-catalog.d.ts +4 -0
  202. package/dist/store/session-catalog.js +6 -0
  203. package/dist/store/storage.js +3 -0
  204. package/dist/store/store.d.ts +97 -34
  205. package/dist/store/store.js +64 -10
  206. package/dist/telemetry/appender.d.ts +43 -0
  207. package/dist/telemetry/appender.js +46 -0
  208. package/dist/telemetry/events.d.ts +142 -0
  209. package/dist/telemetry/events.js +141 -0
  210. package/dist/telemetry/index.d.ts +10 -0
  211. package/dist/telemetry/index.js +6 -0
  212. package/dist/telemetry/projection.d.ts +23 -0
  213. package/dist/telemetry/projection.js +185 -0
  214. package/dist/telemetry/redact.d.ts +20 -0
  215. package/dist/telemetry/redact.js +40 -0
  216. package/dist/telemetry/service.d.ts +49 -0
  217. package/dist/telemetry/service.js +137 -0
  218. package/dist/testing.d.ts +58 -0
  219. package/dist/testing.js +123 -0
  220. package/dist/tool/background.d.ts +9 -6
  221. package/dist/tool/background.js +7 -1
  222. package/dist/tool/builtin/ask-user-question.js +6 -5
  223. package/dist/tool/builtin/bash.d.ts +6 -0
  224. package/dist/tool/builtin/bash.js +79 -42
  225. package/dist/tool/builtin/edit.js +82 -109
  226. package/dist/tool/builtin/glob.js +13 -13
  227. package/dist/tool/builtin/grep.js +13 -13
  228. package/dist/tool/builtin/read.js +25 -15
  229. package/dist/tool/builtin/write.js +49 -33
  230. package/dist/tool/define.d.ts +14 -8
  231. package/dist/tool/define.js +8 -2
  232. package/dist/tool/{machine-base.d.ts → environment-base.d.ts} +37 -37
  233. package/dist/tool/{machine-base.js → environment-base.js} +45 -119
  234. package/dist/tool/{machine-local.d.ts → environment-local.d.ts} +9 -8
  235. package/dist/tool/{machine-local.js → environment-local.js} +60 -81
  236. package/dist/tool/{machine-null.d.ts → environment-null.d.ts} +9 -9
  237. package/dist/tool/{machine-null.js → environment-null.js} +9 -9
  238. package/dist/tool/{machine-ssh.d.ts → environment-ssh.d.ts} +33 -18
  239. package/dist/tool/{machine-ssh.js → environment-ssh.js} +118 -149
  240. package/dist/tool/{machine.d.ts → environment.d.ts} +53 -82
  241. package/dist/tool/environment.js +2 -0
  242. package/dist/tool/file-freshness.d.ts +33 -19
  243. package/dist/tool/file-freshness.js +39 -30
  244. package/dist/tool/filesystem-tools.d.ts +1 -1
  245. package/dist/tool/filesystem-tools.js +1 -1
  246. package/dist/tool/git-context.d.ts +2 -2
  247. package/dist/tool/git-context.js +8 -8
  248. package/dist/tool/index.d.ts +12 -12
  249. package/dist/tool/index.js +12 -10
  250. package/dist/tool/policies/path-access.d.ts +4 -4
  251. package/dist/tool/policies/path-access.js +12 -12
  252. package/dist/tool/questions.d.ts +8 -0
  253. package/dist/tool/search/catalog.d.ts +37 -0
  254. package/dist/tool/search/catalog.js +182 -0
  255. package/dist/tool/search/deferral.d.ts +3 -2
  256. package/dist/tool/search/loaded.d.ts +32 -0
  257. package/dist/tool/search/loaded.js +96 -0
  258. package/dist/tool/search/search-tool.d.ts +2 -6
  259. package/dist/tool/search/search-tool.js +16 -15
  260. package/dist/tool/shell-env.js +4 -0
  261. package/dist/tool/support/bash-paths.js +38 -7
  262. package/dist/tool/support/{machine-ops.d.ts → environment-ops.d.ts} +12 -14
  263. package/dist/tool/support/{machine-ops.js → environment-ops.js} +21 -2
  264. package/dist/tool/support/git-worktree.d.ts +3 -3
  265. package/dist/tool/support/git-worktree.js +6 -6
  266. package/dist/tool/support/rg-locator.d.ts +6 -6
  267. package/dist/tool/support/rg-locator.js +6 -6
  268. package/dist/tool/support/ripgrep-run.d.ts +5 -5
  269. package/dist/tool/support/ripgrep-run.js +3 -3
  270. package/dist/tool/support/tool-path.d.ts +3 -3
  271. package/dist/tool/support/tool-path.js +7 -7
  272. package/dist/tool/types.d.ts +54 -10
  273. package/dist/tool/web/fetch-url.js +1 -1
  274. package/dist/tool/web/web-search.js +1 -1
  275. package/dist/tool/workspace-spec.d.ts +3 -3
  276. package/dist/tool/workspace-spec.js +27 -27
  277. package/dist/tracing/bridge.d.ts +9 -1
  278. package/dist/tracing/bridge.js +307 -77
  279. package/dist/tracing/index.d.ts +2 -2
  280. package/dist/tracing/otel.d.ts +28 -1
  281. package/dist/tracing/otel.js +150 -38
  282. package/dist/tracing/processor.d.ts +22 -0
  283. package/dist/tracing/processor.js +2 -0
  284. package/dist/tracing/spans.d.ts +54 -0
  285. package/dist/tracing/spans.js +5 -0
  286. package/package.json +6 -2
  287. package/dist/tool/machine.js +0 -15
  288. package/dist/tool/search/activation.d.ts +0 -13
  289. package/dist/tool/search/activation.js +0 -31
@@ -10,7 +10,7 @@
10
10
  */
11
11
  import { z } from "zod";
12
12
  import { addUsage, subtractUsage } from "../loop/usage.js";
13
- import { ConversationContext, replayContext } from "../loop/context.js";
13
+ import { ConversationContext } from "../loop/context.js";
14
14
  import { historyChangeEmitter } from "./run-support.js";
15
15
  import { SteerBus } from "../loop/steer.js";
16
16
  import { ToolInterruptionSignal, findAnchoredAssistant, getInterruptionState, } from "../loop/interruption.js";
@@ -221,7 +221,7 @@ export function buildAgentTool(spawner, parent) {
221
221
  const childState = spawner.derive({ address, signal: deadline.signal, parentToolCallId: ctx.toolCallId, steer: new SteerBus() });
222
222
  // Rebuild the subagent's context, validate the new prompt, then append it only
223
223
  // after acceptance. A rejected prompt is audit-only in the child shard.
224
- const childContext = await replayContext(parent.store, address);
224
+ const childContext = await parent.session.openFrameContext(address);
225
225
  const promptMessage = { role: "user", content: [{ type: "text", text: args.prompt }], timestamp: Date.now() };
226
226
  await guardSubagentInput(sub, [promptMessage], childState, spawner);
227
227
  childContext.appendMessage(promptMessage);
@@ -526,7 +526,7 @@ async function resumeInterruptedChild(root, frame, spawner, parent, parentToolCa
526
526
  resumeFrame: frame,
527
527
  steer: new SteerBus(),
528
528
  });
529
- const childContext = await replayContext(parent.store, frame.address);
529
+ const childContext = await parent.session.openFrameContext(frame.address);
530
530
  childState.session.setLiveContext(frame.address, childContext);
531
531
  const resumeFrom = findAnchoredAssistant(childContext.messages, frame.anchor);
532
532
  // Same contract as a fresh spawn: the resumed frame must be steerable at its address.
@@ -30,21 +30,36 @@ export function invalidAgentName(name) {
30
30
  */
31
31
  export const SUBAGENT_META = "subagent_meta";
32
32
  export async function readSubagentMeta(store, address) {
33
+ // The meta record is journaled when the shard is created, so it is among its first records:
34
+ // look at the head first (a range read on a seeking backend) and scan on only if it is not.
35
+ const head = await store.readRecordPage({ address, limit: 16 });
36
+ for (const { record } of head.data) {
37
+ const meta = subagentMetaOf(record);
38
+ if (meta !== undefined)
39
+ return meta;
40
+ }
41
+ if (head.next === undefined)
42
+ return undefined;
33
43
  for await (const record of store.readRecords({ address })) {
34
- if (record.type !== "custom" || record.name !== SUBAGENT_META)
35
- continue;
36
- const data = record.data;
37
- if (data !== undefined && typeof data.type === "string" && typeof data.agentId === "string") {
38
- return {
39
- agentId: data.agentId,
40
- type: data.type,
41
- description: data.description,
42
- background: data.background === true,
43
- parentAddress: data.parentAddress,
44
- parentToolCallId: data.parentToolCallId,
45
- };
46
- }
44
+ const meta = subagentMetaOf(record);
45
+ if (meta !== undefined)
46
+ return meta;
47
47
  }
48
48
  return undefined;
49
49
  }
50
+ function subagentMetaOf(record) {
51
+ if (record.type !== "custom" || record.name !== SUBAGENT_META)
52
+ return undefined;
53
+ const data = record.data;
54
+ if (data === undefined || typeof data.type !== "string" || typeof data.agentId !== "string")
55
+ return undefined;
56
+ return {
57
+ agentId: data.agentId,
58
+ type: data.type,
59
+ description: data.description,
60
+ background: data.background === true,
61
+ parentAddress: data.parentAddress,
62
+ parentToolCallId: data.parentToolCallId,
63
+ };
64
+ }
50
65
  //# sourceMappingURL=subagent.js.map
@@ -19,6 +19,7 @@ export type RunAgentFn<TContext> = SubagentSpawner<TContext>["run"];
19
19
  export interface RunToolset {
20
20
  readonly tools: readonly Tool[];
21
21
  readonly deferredToolNames: ReadonlySet<string>;
22
+ readonly deferEnabled: boolean;
22
23
  }
23
24
  export declare function buildRunTools<TContext>(active: Agent<TContext>, state: RunState<TContext>, runAgent: RunAgentFn<TContext>, model: ChatModel): Promise<RunToolset>;
24
25
  //# sourceMappingURL=toolset.d.ts.map
@@ -4,6 +4,7 @@ import { buildSearchTool } from "../tool/search/search-tool.js";
4
4
  import { findAgentByName } from "./graph.js";
5
5
  import { deriveChild, emitRunEvent, runCtxFor } from "./run-support.js";
6
6
  import { toolSource } from "../capabilities/tool-provider.js";
7
+ import { DEFAULT_ADDRESS } from "../store/index.js";
7
8
  export async function buildRunTools(active, state, runAgent, model) {
8
9
  // Capability (MCP) tools are the deferred-loading candidates. When the agent
9
10
  // opts in, they stay executable but are omitted from the model-facing schema
@@ -29,7 +30,7 @@ export async function buildRunTools(active, state, runAgent, model) {
29
30
  });
30
31
  return false;
31
32
  });
32
- const deferEnabled = active.deferTools === true && capTools.length > 0 && model.supportsDeferredTools;
33
+ const deferEnabled = active.deferTools !== false && model.supportsDeferredTools;
33
34
  const deferredToolNames = new Set(deferEnabled ? capTools.map((tool) => tool.schema.name) : []);
34
35
  const tools = [...active.tools, ...capTools];
35
36
  if (deferEnabled)
@@ -40,7 +41,7 @@ export async function buildRunTools(active, state, runAgent, model) {
40
41
  // (e.g. profile-loaded agents). The unified "Agent" tool spawns/resumes by type.
41
42
  const providerAgents = state.subagentProvider !== undefined ? [...(await state.subagentProvider.list())] : [];
42
43
  if (active.subagents.length === 0 && providerAgents.length === 0) {
43
- return finish(state, tools, deferredToolNames);
44
+ return finish(state, tools, deferredToolNames, deferEnabled);
44
45
  }
45
46
  // One spawner (the engine seam) shared by every subagent-spawning tool: the static
46
47
  // `agent_<name>` tools, the unified `Agent` tool, and `Workflow`.
@@ -55,21 +56,26 @@ export async function buildRunTools(active, state, runAgent, model) {
55
56
  if (state.workflowTool !== false && !tools.some((tool) => tool.schema.name === "Workflow")) {
56
57
  tools.push(buildWorkflowTool(spawner, state));
57
58
  }
58
- return finish(state, tools, deferredToolNames);
59
+ return finish(state, tools, deferredToolNames, deferEnabled);
59
60
  }
60
61
  /**
61
62
  * Last stop before the turn: let capabilities narrow the complete registry (the extension
62
63
  * runtime's `setActiveTools` rides this). Filtering happens AFTER assembly so a filter sees
63
64
  * handoff and subagent tools too, and the deferred-name set is pruned to whatever survived.
64
65
  */
65
- function finish(state, tools, deferredToolNames) {
66
- const filtered = state.capabilities.applyToolFilters(tools);
66
+ function finish(state, tools, deferredToolNames, deferEnabled) {
67
+ const filtered = state.capabilities.applyToolFilters(tools, {
68
+ address: state.address,
69
+ isRootAgent: state.address === DEFAULT_ADDRESS,
70
+ });
71
+ const enabled = deferEnabled && filtered.some((tool) => tool.schema.name === "SearchTool");
67
72
  if (filtered === tools)
68
- return { tools, deferredToolNames };
73
+ return { tools, deferredToolNames, deferEnabled: enabled };
69
74
  const surviving = new Set(filtered.map((tool) => tool.schema.name));
70
75
  return {
71
76
  tools: filtered,
72
- deferredToolNames: new Set([...deferredToolNames].filter((name) => surviving.has(name))),
77
+ deferredToolNames: new Set(enabled ? [...deferredToolNames].filter((name) => surviving.has(name)) : []),
78
+ deferEnabled: enabled,
73
79
  };
74
80
  }
75
81
  /**
@@ -19,7 +19,7 @@
19
19
  * Persistence is the SessionStore's append log under a per-run address
20
20
  * (`workflow:<runId>`): the journal is agent bookkeeping shaped exactly like the
21
21
  * log facet — crash-safe appends, replayed whole on load — so it never touches
22
- * the Machine or the host filesystem. `custom` entries are audit-only and
22
+ * the Environment or the host filesystem. `custom` entries are audit-only and
23
23
  * are never folded into a conversation.
24
24
  */
25
25
  import type { SessionStore } from "../../store/index.ts";
@@ -151,7 +151,7 @@ export declare class WorkflowJournal {
151
151
  * block included — because a resume re-parses it, and `parseWorkflow` strips that block off.
152
152
  *
153
153
  * Carries the script in full rather than a path:
154
- * a path points at the machine, which is a cache — the file can be edited, overwritten by
154
+ * a path points at the environment, which is a cache — the file can be edited, overwritten by
155
155
  * the next run of the same workflow, or vanish with a sandbox. Replay needs the exact bytes
156
156
  * that produced these keys, so the record holds them.
157
157
  */
@@ -19,7 +19,7 @@
19
19
  * Persistence is the SessionStore's append log under a per-run address
20
20
  * (`workflow:<runId>`): the journal is agent bookkeeping shaped exactly like the
21
21
  * log facet — crash-safe appends, replayed whole on load — so it never touches
22
- * the Machine or the host filesystem. `custom` entries are audit-only and
22
+ * the Environment or the host filesystem. `custom` entries are audit-only and
23
23
  * are never folded into a conversation.
24
24
  */
25
25
  import { createHash } from "node:crypto";
@@ -167,7 +167,7 @@ export class WorkflowJournal {
167
167
  * block included — because a resume re-parses it, and `parseWorkflow` strips that block off.
168
168
  *
169
169
  * Carries the script in full rather than a path:
170
- * a path points at the machine, which is a cache — the file can be edited, overwritten by
170
+ * a path points at the environment, which is a cache — the file can be edited, overwritten by
171
171
  * the next run of the same workflow, or vanish with a sandbox. Replay needs the exact bytes
172
172
  * that produced these keys, so the record holds them.
173
173
  */
@@ -6,7 +6,7 @@
6
6
  * session to get a run's journal.
7
7
  *
8
8
  * Run DISCOVERY is no longer here: a background workflow run is a task, so past runs
9
- * are listed from the durable task store via `session.listWorkflows()`. A foreground
9
+ * are listed from the durable task store via `session.background?.listWorkflows() ?? []`. A foreground
10
10
  * workflow is a plain `Workflow` tool call — its record is the conversation plus its
11
11
  * journal shard. This manager only owns the resume journal (`newJournal(runId)`).
12
12
  *
@@ -6,7 +6,7 @@
6
6
  * session to get a run's journal.
7
7
  *
8
8
  * Run DISCOVERY is no longer here: a background workflow run is a task, so past runs
9
- * are listed from the durable task store via `session.listWorkflows()`. A foreground
9
+ * are listed from the durable task store via `session.background?.listWorkflows() ?? []`. A foreground
10
10
  * workflow is a plain `Workflow` tool call — its record is the conversation plus its
11
11
  * journal shard. This manager only owns the resume journal (`newJournal(runId)`).
12
12
  *
@@ -6,7 +6,7 @@
6
6
  */
7
7
  export function workflowPrompt(availableAgents) {
8
8
  const agentList = availableAgents.length > 0 ? availableAgents.join(", ") : "(none configured)";
9
- return `Execute a workflow script that orchestrates multiple subagents deterministically. By default it runs to completion and returns the final value; pass run_in_background:true (recommended for long workflows) to get a task_id immediately and poll progress/result with BackgroundOutput. Live progress is reported either way. Pass tokenBudget to cap the run and enable budget.remaining()-guarded loops.
9
+ return `Execute a workflow script that orchestrates multiple subagents deterministically. By default it runs to completion and returns the final value; pass run_in_background:true (recommended for long workflows) to get a task_id immediately; a completion notice arrives on its own, and BackgroundOutput(task_id, block=false) reads progress/result meanwhile. Live progress is reported either way. Pass tokenBudget to cap the run and enable budget.remaining()-guarded loops.
10
10
 
11
11
  A workflow structures work across many agents — to be comprehensive (decompose and cover in parallel), to be confident (independent perspectives and adversarial checks before committing), or to take on scale one context can't hold (migrations, audits, broad sweeps). The script is where you encode that structure: what fans out, what verifies, what synthesizes.
12
12
 
@@ -35,7 +35,7 @@ Every script must begin with \`export const meta = {...}\`:
35
35
  The \`meta\` object must be a PURE LITERAL — no variables, function calls, spreads, or template interpolation. Required: \`name\`, \`description\`. Optional: \`title\`, \`whenToUse\`, \`phases\`. Use the SAME phase titles in meta.phases as in your phase() calls — titles are matched exactly.
36
36
 
37
37
  Script body hooks:
38
- - agent(prompt, opts?): Promise<any> — spawn one subagent and run it to completion. Without a schema, returns its final text as a string. With opts.schema (a JSON Schema), the subagent is forced to call a StructuredOutput tool whose argument matches the schema; agent() validates it and resolves the parsed object (nudging + retrying on mismatch). opts: { label?, phase?, schema?, model?, agentType? }. opts.label overrides the display label. opts.phase assigns this agent to a progress group — use it inside pipeline()/parallel() stages instead of relying on global phase() state. opts.model overrides the model for this one agent; omit it to inherit the default. opts.agentType selects which subagent type runs the agent. Available types: ${agentList}. Omit it to use the default. opts.isolation:'worktree' runs the agent in an isolated git worktree (a separate working copy, auto-removed if it makes no changes) — use it ONLY when agents mutate files in parallel and would otherwise conflict; it degrades to the shared workspace (with a logged note) when the machine can't provide one.
38
+ - agent(prompt, opts?): Promise<any> — spawn one subagent and run it to completion. Without a schema, returns its final text as a string. With opts.schema (a JSON Schema), the subagent is forced to call a StructuredOutput tool whose argument matches the schema; agent() validates it and resolves the parsed object (nudging + retrying on mismatch). opts: { label?, phase?, schema?, model?, agentType? }. opts.label overrides the display label. opts.phase assigns this agent to a progress group — use it inside pipeline()/parallel() stages instead of relying on global phase() state. opts.model overrides the model for this one agent; omit it to inherit the default. opts.agentType selects which subagent type runs the agent. Available types: ${agentList}. Omit it to use the default. opts.isolation:'worktree' runs the agent in an isolated git worktree (a separate working copy, auto-removed if it makes no changes) — use it ONLY when agents mutate files in parallel and would otherwise conflict; it degrades to the shared workspace (with a logged note) when the environment can't provide one.
39
39
  - parallel(thunks): Promise<any[]> — run () => agent(...) thunks concurrently. This is a BARRIER: it awaits all thunks. A thunk that throws resolves to null in the result array (the call never rejects), so .filter(Boolean) before using results. At most 4096 thunks per call.
40
40
  - pipeline(items, stage1, stage2, ...): Promise<any[]> — run each item through all stages independently, with NO barrier between stages. Item A can be in stage 3 while item B is still in stage 1. This is the DEFAULT for multi-stage work. Each stage callback receives (prevResult, originalItem, index). A stage that throws drops that item to null and skips its remaining stages. At most 4096 items per call.
41
41
  - phase(title): void — start a new phase; subsequent agent() calls are grouped under it.
@@ -3,7 +3,7 @@
3
3
  * - the async IIFE runs in `'use strict'`, so `with` is a SyntaxError and
4
4
  * silent-failure footguns become throws;
5
5
  * - dynamic `import()` is rejected (no importModuleDynamically callback is
6
- * provided to vm, so any import() throws — we machine a clear message).
6
+ * provided to vm, so any import() throws — we surface a clear message).
7
7
  *
8
8
  * Node's built-in `vm` is NOT a security sandbox on its own; the hardening here
9
9
  * covers the realistic failure modes: strip `constructor`/`prototype` off injected functions,
@@ -3,7 +3,7 @@
3
3
  * - the async IIFE runs in `'use strict'`, so `with` is a SyntaxError and
4
4
  * silent-failure footguns become throws;
5
5
  * - dynamic `import()` is rejected (no importModuleDynamically callback is
6
- * provided to vm, so any import() throws — we machine a clear message).
6
+ * provided to vm, so any import() throws — we surface a clear message).
7
7
  *
8
8
  * Node's built-in `vm` is NOT a security sandbox on its own; the hardening here
9
9
  * covers the realistic failure modes: strip `constructor`/`prototype` off injected functions,
@@ -8,14 +8,14 @@ import { SteerBus } from "../../loop/steer.js";
8
8
  import { defineTool } from "../../tool/define.js";
9
9
  import { ToolAccesses } from "../../tool/access.js";
10
10
  import { resolveToolPath } from "../../tool/support/tool-path.js";
11
- import { readTextFile, writeTextFile } from "../../tool/support/machine-ops.js";
11
+ import { readTextFile, writeTextFile } from "../../tool/support/environment-ops.js";
12
12
  import { joinAddress } from "../../events/index.js";
13
13
  import { WorkflowBackgroundTask } from "../../capabilities/background/workflow-task.js";
14
14
  import { asTaskRegistrar } from "../../capabilities/background/registrar.js";
15
15
  import { newAgentId } from "../subagent.js";
16
16
  import { guardSubagentInput } from "../subagent-tools.js";
17
17
  import { createWorktree } from "../worktree.js";
18
- import { runWorkflow, parseWorkflow, WorkflowJournal, journalAddress, WorkflowManager, workflowPrompt, makeStructuredOutputTool, cloneAgentWithTool, validateValue, structuredInstruction, WORKFLOW_AGENT_TIMEOUT_MS, } from "./index.js";
18
+ import { runWorkflow, parseWorkflow, WorkflowJournal, journalAddress, workflowPrompt, makeStructuredOutputTool, cloneAgentWithTool, validateValue, structuredInstruction, WORKFLOW_AGENT_TIMEOUT_MS, } from "./index.js";
19
19
  /**
20
20
  * The Workflow tool — a deterministic JS orchestration runtime over subagents.
21
21
  * The script runs in a hardened VM (see workflow/sandbox.ts); its agent() hook spawns
@@ -36,7 +36,7 @@ export function buildWorkflowTool(spawner, parent) {
36
36
  concurrency: Math.min(16, Math.max(2, os.cpus().length - 2)),
37
37
  abortSignal,
38
38
  budget: { total: tokenBudget, getTurnSpent: () => baseline },
39
- resolveWorkflowScript: (name) => readNamedWorkflow(parent.machine, name),
39
+ resolveWorkflowScript: (name) => readNamedWorkflow(parent.environment, name),
40
40
  emitProgress,
41
41
  runAgent: async ({ prompt, agentType, schema, isolation, signal, onStart }) => {
42
42
  const sub = await spawner.resolve(agentType ?? spawner.defaultType);
@@ -49,17 +49,17 @@ export function buildWorkflowTool(spawner, parent) {
49
49
  // event can be joined to this child's Session AgentEvents and interruption is resumable.
50
50
  onStart({ agentId, address });
51
51
  // Optional worktree isolation — degrade (with a log, never silently) if unsupported.
52
- let runMachine = parent.machine;
52
+ let runEnvironment = parent.environment;
53
53
  let cleanupWorktree;
54
54
  if (isolation === "worktree") {
55
- const wt = await createWorktree(parent.machine, { label: agentId });
55
+ const wt = await createWorktree(parent.environment, { label: agentId });
56
56
  if (wt) {
57
- runMachine = wt.machine;
57
+ runEnvironment = wt.environment;
58
58
  cleanupWorktree = wt.cleanup;
59
59
  emitProgress({ type: "log", message: `🌳 ${agentId}: isolated worktree at ${wt.cwd}` });
60
60
  }
61
61
  else {
62
- emitProgress({ type: "log", message: `isolation:'worktree' unavailable on machine '${parent.machine.name}' — running in the shared workspace` });
62
+ emitProgress({ type: "log", message: `isolation:'worktree' unavailable on environment '${parent.environment.name}' — running in the shared workspace` });
63
63
  }
64
64
  }
65
65
  // Per-agent abort: workflow signal OR an absolute stall timeout.
@@ -73,7 +73,7 @@ export function buildWorkflowTool(spawner, parent) {
73
73
  // Each concurrent subagent gets its OWN SteerBus: the parent's tracks a
74
74
  // single activeTurnId, so sharing it across parallel agents would corrupt
75
75
  // the parent turn's steering state. Subagents are ephemeral and take no steers.
76
- const childState = spawner.derive({ address, machine: runMachine, signal: controller.signal, steer: new SteerBus(), parentToolCallId });
76
+ const childState = spawner.derive({ address, environment: runEnvironment, signal: controller.signal, steer: new SteerBus(), parentToolCallId });
77
77
  const childContext = new ConversationContext({
78
78
  store: parent.store,
79
79
  address,
@@ -149,7 +149,7 @@ export function buildWorkflowTool(spawner, parent) {
149
149
  args: z.unknown().optional().describe("Value exposed to the script as the global `args` (pass real JSON, not a stringified value)."),
150
150
  resumeFromRunId: z.string().optional().describe("Resume a prior run; unchanged agent() calls return cached results instantly."),
151
151
  tokenBudget: z.number().optional().describe("Output-token target for the run; enables budget.remaining()-guarded loops in the script."),
152
- run_in_background: z.boolean().optional().describe("Run detached and return a task_id immediately (recommended for long workflows). Poll progress + result with BackgroundOutput. Requires a BackgroundManager."),
152
+ run_in_background: z.boolean().optional().describe("Run detached and return a task_id immediately (recommended for long workflows). A completion notice arrives on its own; BackgroundOutput(task_id, block=false) reads progress or the result meanwhile. Requires a BackgroundManager."),
153
153
  });
154
154
  return defineTool({
155
155
  name: "Workflow",
@@ -169,7 +169,7 @@ export function buildWorkflowTool(spawner, parent) {
169
169
  // The journal entry is what makes a resume self-contained. Every other source is a
170
170
  // path into the workspace — a file the model may have edited since, that a later run
171
171
  // of the same workflow may have replaced, and that does not exist at all if the
172
- // machine is a sandbox that has since been rebuilt. Resuming against a DIFFERENT
172
+ // environment is a sandbox that has since been rebuilt. Resuming against a DIFFERENT
173
173
  // script is worse than failing: the journal keys are chained hashes of each agent's
174
174
  // prompt, so one changed prompt misses every cache entry after it and silently
175
175
  // re-runs the whole workflow for real money.
@@ -179,7 +179,7 @@ export function buildWorkflowTool(spawner, parent) {
179
179
  (args.script === undefined || args.script.trim().length === 0) &&
180
180
  (args.name === undefined || args.name.length === 0);
181
181
  if (resumeId !== undefined && resumeId.length > 0 && noExplicitSource) {
182
- const priorJournal = (parent.session.workflow ?? fallbackWorkflowManagerFor(parent.session)).newJournal(resumeId, ctx.toolCallId);
182
+ const priorJournal = parent.session.newWorkflowJournal(resumeId, ctx.toolCallId);
183
183
  await priorJournal.load();
184
184
  const recorded = priorJournal.recordedScript();
185
185
  if (recorded === undefined) {
@@ -189,8 +189,8 @@ export function buildWorkflowTool(spawner, parent) {
189
189
  }
190
190
  else if (args.scriptPath !== undefined && args.scriptPath.length > 0) {
191
191
  try {
192
- const safePath = await resolveToolPath(args.scriptPath, ctx.machine, "read");
193
- script = await readTextFile(ctx.machine, safePath);
192
+ const safePath = await resolveToolPath(args.scriptPath, ctx.environment, "read");
193
+ script = await readTextFile(ctx.environment, safePath);
194
194
  }
195
195
  catch (err) {
196
196
  return errResult(`Could not read scriptPath: ${err instanceof Error ? err.message : String(err)}`);
@@ -200,7 +200,7 @@ export function buildWorkflowTool(spawner, parent) {
200
200
  script = args.script;
201
201
  }
202
202
  else if (args.name !== undefined && args.name.length > 0) {
203
- script = await readNamedWorkflow(ctx.machine, args.name);
203
+ script = await readNamedWorkflow(ctx.environment, args.name);
204
204
  if (script === null)
205
205
  return errResult(`No saved workflow named "${args.name}" in the workspace .agents/workflows/.`);
206
206
  }
@@ -215,16 +215,15 @@ export function buildWorkflowTool(spawner, parent) {
215
215
  const tokenBudget = args.tokenBudget ?? null;
216
216
  // Persist the resolved script to the workspace and hand back its path, so the
217
217
  // model can Write/Edit it and re-run via `scriptPath` instead of re-sending the whole
218
- // script. Goes through the Machine → on a server it lands in the sandbox, never the
218
+ // script. Goes through the Environment → on a server it lands in the sandbox, never the
219
219
  // host disk. Best-effort: a persist failure never fails the run (path is left undefined).
220
- const persistedScriptPath = await persistRunScript(ctx.machine, meta.name, runId, script);
221
- // Resume journals go through the workflow capability (session.workflow); with no
222
- // capability attached, a per-session fallback manager binds them to the session's
223
- // store (or in-memory when the session has none). Discovery needs no writes: the
224
- // tool results below carry the run's lifecycle in `details`, and the `/workflows`
225
- // list is a fold over the conversation (snapshot.ts).
226
- const wf = parent.session.workflow ?? fallbackWorkflowManagerFor(parent.session);
227
- const mkJournal = (id) => wf.newJournal(id, ctx.toolCallId);
220
+ const persistedScriptPath = await persistRunScript(ctx.environment, meta.name, runId, script);
221
+ // Resume journals come from the session port: the workflow capability's manager, or
222
+ // the in-memory fallback Session.open provides when no capability is attached — either
223
+ // way bound to the session's store. Discovery needs no writes: the tool results below
224
+ // carry the run's lifecycle in `details`, and the `/workflows` list is a fold over the
225
+ // conversation (snapshot.ts).
226
+ const mkJournal = (id) => parent.session.newWorkflowJournal(id, ctx.toolCallId);
228
227
  // Timestamps are stamped HOST-side (Date.now is banned only inside the sandbox).
229
228
  const startedAt = new Date().toISOString();
230
229
  const runDetails = (status, endedAt, outputTokens) => ({
@@ -483,13 +482,13 @@ const WORKFLOW_DIR = ".agents/workflows";
483
482
  const WORKFLOW_RUNS_DIR = ".agents/runs";
484
483
  /**
485
484
  * Persist the resolved script to `.agents/workflows/runs/<name>.js` in the workspace (via the
486
- * Machine — sandbox on a server, never the host disk) and return that path.
485
+ * Environment — sandbox on a server, never the host disk) and return that path.
487
486
  * Every invocation drops an editable copy so the model can Write/Edit it and re-run via
488
487
  * `scriptPath`. Best-effort — returns undefined (never throws) if the write fails, so persistence
489
488
  * never blocks a run. Keyed by workflow name (stable across iterations of the "same" workflow);
490
489
  * curated named workflows live one level up in `.agents/workflows/`, so `runs/` never shadows them.
491
490
  */
492
- async function persistRunScript(machine, name, runId, script) {
491
+ async function persistRunScript(environment, name, runId, script) {
493
492
  // Named per RUN, not per workflow. Sharing a filename across runs of the same workflow meant
494
493
  // the second run silently overwrote the first — taking with it any edit the model had made,
495
494
  // and leaving a `resumeFromRunId` for the older run pointed at a script whose prompts no
@@ -497,8 +496,8 @@ async function persistRunScript(machine, name, runId, script) {
497
496
  const safeName = name.replace(/[^a-zA-Z0-9._-]/g, "_").replace(/^\.+/, "") || "workflow";
498
497
  const rel = `${WORKFLOW_RUNS_DIR}/${safeName}.${runId}.js`;
499
498
  try {
500
- await machine.mkdir(await resolveToolPath(WORKFLOW_RUNS_DIR, machine, "write"), { parents: true, existOk: true });
501
- await writeTextFile(machine, await resolveToolPath(rel, machine, "write"), script);
499
+ await environment.mkdir(await resolveToolPath(WORKFLOW_RUNS_DIR, environment, "write"), { parents: true, existOk: true });
500
+ await writeTextFile(environment, await resolveToolPath(rel, environment, "write"), script);
502
501
  return rel;
503
502
  }
504
503
  catch {
@@ -507,17 +506,17 @@ async function persistRunScript(machine, name, runId, script) {
507
506
  }
508
507
  /**
509
508
  * Read a saved workflow by name from the workspace `.agents/workflows/` dir, VIA the
510
- * machine — so it resolves inside the sandbox workspace, never the host
509
+ * environment — so it resolves inside the sandbox workspace, never the host
511
510
  * filesystem (the model writes these with Write; it reads them back from the same
512
511
  * place). Tries `<name>`, `<name>.js`, `<name>.mjs`; returns null if none exist.
513
512
  */
514
- async function readNamedWorkflow(machine, name) {
513
+ async function readNamedWorkflow(environment, name) {
515
514
  if (!/^[a-zA-Z0-9._-]+$/.test(name) || name.includes(".."))
516
515
  return null;
517
516
  for (const ext of ["", ".js", ".mjs"]) {
518
517
  try {
519
- const safePath = await resolveToolPath(`${WORKFLOW_DIR}/${name}${ext}`, machine, "read");
520
- return await readTextFile(machine, safePath);
518
+ const safePath = await resolveToolPath(`${WORKFLOW_DIR}/${name}${ext}`, environment, "read");
519
+ return await readTextFile(environment, safePath);
521
520
  }
522
521
  catch {
523
522
  // not found / not this extension — try the next
@@ -554,16 +553,4 @@ function safeJsonStringify(value) {
554
553
  return String(value);
555
554
  }
556
555
  }
557
- // One fallback per session (not per run): resume journals of every workflow run in the
558
- // session must land in the same store. Keyed by the session object's identity (the port
559
- // is the same Session instance across every frame of a session).
560
- const fallbackWorkflowManagers = new WeakMap();
561
- function fallbackWorkflowManagerFor(session) {
562
- let manager = fallbackWorkflowManagers.get(session);
563
- if (manager === undefined) {
564
- manager = new WorkflowManager(session.store);
565
- fallbackWorkflowManagers.set(session, manager);
566
- }
567
- return manager;
568
- }
569
556
  //# sourceMappingURL=tool.js.map
@@ -1,12 +1,12 @@
1
- import type { Machine } from "../tool/machine.ts";
1
+ import type { Environment } from "../tool/environment.ts";
2
2
  /**
3
3
  * An isolated working copy handed to a subagent that mutates files, so parallel
4
- * agents don't clobber each other. `machine` is scoped to the copy (its getcwd()
4
+ * agents don't clobber each other. `environment` is scoped to the copy (its getcwd()
5
5
  * is `cwd`); `cleanup` tears it down (the worktree is removed only if the agent
6
6
  * left no changes — a dirty copy is kept for inspection).
7
7
  */
8
8
  export interface WorktreeHandle {
9
- readonly machine: Machine;
9
+ readonly environment: Environment;
10
10
  readonly cwd: string;
11
11
  cleanup(): Promise<void>;
12
12
  }
@@ -20,11 +20,11 @@ export interface WorktreeHandle {
20
20
  */
21
21
  export declare const WORKTREES_DIR = ".operon/worktrees";
22
22
  /**
23
- * Create an isolated git worktree for a subagent and return a machine scoped to it.
23
+ * Create an isolated git worktree for a subagent and return an environment scoped to it.
24
24
  *
25
- * This is workflow/orchestration policy built entirely on a machine's existing
26
- * capabilities — git runs through `machine.exec`, and the scoped machine comes from
27
- * `machine.withCwd`. It is therefore backend-agnostic: any machine whose target host
25
+ * This is workflow/orchestration policy built entirely on an environment's existing
26
+ * capabilities — git runs through `environment.exec`, and the scoped environment comes from
27
+ * `environment.withCwd`. It is therefore backend-agnostic: any environment whose target host
28
28
  * has git (local, ssh, sandbox) can isolate. Whether isolation happens is decided at
29
29
  * runtime by git itself — a host without git, or a cwd that isn't a repo, makes the
30
30
  * git command fail and we return `null`, and the caller degrades to the shared
@@ -32,7 +32,7 @@ export declare const WORKTREES_DIR = ".operon/worktrees";
32
32
  * Cleanup removes the worktree only if the agent left it clean; a dirty worktree is
33
33
  * kept for inspection.
34
34
  */
35
- export declare function createWorktree(machine: Machine, options?: {
35
+ export declare function createWorktree(environment: Environment, options?: {
36
36
  label?: string;
37
37
  }): Promise<WorktreeHandle | null>;
38
38
  //# sourceMappingURL=worktree.d.ts.map
@@ -9,11 +9,11 @@ import { randomBytes } from "node:crypto";
9
9
  */
10
10
  export const WORKTREES_DIR = ".operon/worktrees";
11
11
  /**
12
- * Create an isolated git worktree for a subagent and return a machine scoped to it.
12
+ * Create an isolated git worktree for a subagent and return an environment scoped to it.
13
13
  *
14
- * This is workflow/orchestration policy built entirely on a machine's existing
15
- * capabilities — git runs through `machine.exec`, and the scoped machine comes from
16
- * `machine.withCwd`. It is therefore backend-agnostic: any machine whose target host
14
+ * This is workflow/orchestration policy built entirely on an environment's existing
15
+ * capabilities — git runs through `environment.exec`, and the scoped environment comes from
16
+ * `environment.withCwd`. It is therefore backend-agnostic: any environment whose target host
17
17
  * has git (local, ssh, sandbox) can isolate. Whether isolation happens is decided at
18
18
  * runtime by git itself — a host without git, or a cwd that isn't a repo, makes the
19
19
  * git command fail and we return `null`, and the caller degrades to the shared
@@ -21,8 +21,8 @@ export const WORKTREES_DIR = ".operon/worktrees";
21
21
  * Cleanup removes the worktree only if the agent left it clean; a dirty worktree is
22
22
  * kept for inspection.
23
23
  */
24
- export async function createWorktree(machine, options) {
25
- const root = (await runGit(machine, ["-C", machine.getcwd(), "rev-parse", "--show-toplevel"])).ok?.trim();
24
+ export async function createWorktree(environment, options) {
25
+ const root = (await runGit(environment, ["-C", environment.getcwd(), "rev-parse", "--show-toplevel"])).ok?.trim();
26
26
  if (!root)
27
27
  return null; // no git, or cwd isn't a repo → no isolation available
28
28
  const id = randomBytes(4).toString("hex");
@@ -32,25 +32,25 @@ export async function createWorktree(machine, options) {
32
32
  // `.operon/` — the project's name. It was `.agent-framework/`, which this repo
33
33
  // has not been called for some time; the directory is created inside the user's
34
34
  // own repository, so the stale name was visible to every one of them.
35
- const wtPath = machine.normpath(`${root}/${WORKTREES_DIR}/${safeLabel}-${id}`);
36
- const added = await runGit(machine, ["-C", root, "worktree", "add", "--quiet", "-b", branch, wtPath, "HEAD"]);
35
+ const wtPath = environment.normpath(`${root}/${WORKTREES_DIR}/${safeLabel}-${id}`);
36
+ const added = await runGit(environment, ["-C", root, "worktree", "add", "--quiet", "-b", branch, wtPath, "HEAD"]);
37
37
  if (added.ok === undefined)
38
38
  return null; // creation failed → caller degrades to shared workspace
39
39
  const cleanup = async () => {
40
- const status = await runGit(machine, ["-C", wtPath, "status", "--porcelain"]);
40
+ const status = await runGit(environment, ["-C", wtPath, "status", "--porcelain"]);
41
41
  if (status.ok !== undefined && status.ok.trim() === "") {
42
- await runGit(machine, ["-C", root, "worktree", "remove", "--force", wtPath]);
43
- await runGit(machine, ["-C", root, "branch", "-D", branch]);
42
+ await runGit(environment, ["-C", root, "worktree", "remove", "--force", wtPath]);
43
+ await runGit(environment, ["-C", root, "branch", "-D", branch]);
44
44
  }
45
45
  // else: leave the dirty/locked worktree in place for inspection. Errors are
46
46
  // swallowed by runGit; cleanup is best-effort and never throws into the run.
47
47
  };
48
- return { machine: machine.withCwd(wtPath), cwd: wtPath, cleanup };
48
+ return { environment: environment.withCwd(wtPath), cwd: wtPath, cleanup };
49
49
  }
50
- /** Run `git <args>` on the machine's host; `ok` is stdout on exit 0, undefined otherwise. */
51
- async function runGit(machine, args) {
50
+ /** Run `git <args>` on the environment's host; `ok` is stdout on exit 0, undefined otherwise. */
51
+ async function runGit(environment, args) {
52
52
  // `.catch` covers git-not-found / the backend refusing to spawn at all.
53
- const result = await machine.run(["git", ...args]).catch(() => undefined);
53
+ const result = await environment.run(["git", ...args]).catch(() => undefined);
54
54
  return result?.exitCode === 0 ? { ok: result.stdout } : {};
55
55
  }
56
56
  //# sourceMappingURL=worktree.js.map
@@ -1,12 +1,19 @@
1
1
  import type { BeforeRunHook, LoopHooks, ShouldContinueAfterStopHook } from "../loop/types.ts";
2
2
  import type { Tool } from "../tool/types.ts";
3
- import type { AssembledGates, Capability, CapabilityContext, CapabilityDiagnostic } from "./capability.ts";
3
+ import type { AssembledGates, Capability, CapabilityProviderHooks, RunContext, CapabilityDiagnostic, ToolFilterContext } from "./capability.ts";
4
4
  import { InjectionManager } from "./injection.ts";
5
5
  export interface AssembleCapabilitiesOptions {
6
6
  /** Max time to wait for a single capability's start(). Default 10s. */
7
7
  readonly startTimeoutMs?: number;
8
8
  /** Max time to wait for a single capability's stop(). Default 5s. */
9
9
  readonly stopTimeoutMs?: number;
10
+ /**
11
+ * Where a diagnostic raised MID-RUN goes — a `detachable` hook that threw or overran. Such a
12
+ * failure is reported when it happens rather than at the end of the run, because the run may
13
+ * be long and the failure explains what it is doing now. Without a reporter it joins
14
+ * `diagnostics` like the rest.
15
+ */
16
+ readonly report?: (diagnostic: CapabilityDiagnostic) => void;
10
17
  }
11
18
  export declare class AssembledCapabilities {
12
19
  readonly diagnostics: CapabilityDiagnostic[];
@@ -14,26 +21,43 @@ export declare class AssembledCapabilities {
14
21
  readonly boundaryContinuations: ShouldContinueAfterStopHook[];
15
22
  readonly runStarts: BeforeRunHook[];
16
23
  /**
17
- * Stable arrays handed to `CapabilityContext.gates`. Capabilities are started and absorbed one
24
+ * Stable arrays handed to `RunContext.gates`. Capabilities are started and absorbed one
18
25
  * at a time, so a consumer that snapshotted at `start()` would miss every gate registered by a
19
26
  * capability ordered after it — reading through this live reference avoids depending on order.
20
27
  */
21
28
  readonly gates: AssembledGates;
22
29
  readonly injection: InjectionManager;
30
+ /** Every started capability's provider hooks, in order — already isolated when detachable. */
31
+ readonly providerHooks: CapabilityProviderHooks[];
23
32
  private readonly staticTools;
24
33
  private readonly toolProviders;
25
34
  private readonly toolFilters;
26
35
  private readonly started;
27
36
  private readonly ctx;
28
37
  private readonly stopTimeoutMs;
29
- constructor(ctx: CapabilityContext, options?: AssembleCapabilitiesOptions);
38
+ private readonly reporter;
39
+ constructor(base: Omit<RunContext, "injection" | "gates">, options?: AssembleCapabilitiesOptions);
40
+ /** The run context handed to every capability's `start` and tool provider. */
41
+ get context(): RunContext;
30
42
  listTools(): Promise<Tool[]>;
31
43
  /** Apply every capability's tool filter in registration order. A thrower is skipped. */
32
- applyToolFilters(tools: readonly Tool[]): readonly Tool[];
44
+ applyToolFilters(tools: readonly Tool[], ctx: ToolFilterContext): readonly Tool[];
33
45
  private absorb;
46
+ /**
47
+ * Wrap every hook of a `detachable` capability: each call gets the capability's budget, and a
48
+ * throw or an overrun becomes a warning plus "no opinion" (`undefined`) — which every hook slot
49
+ * already reads as "carry on unchanged". The overrunning call is not cancelled (a hook has no
50
+ * signal of its own); it is simply no longer waited for, and whatever it returns is dropped.
51
+ */
52
+ private isolate;
53
+ /** The same guard for the hooks below the loop. `response` never gets more than 1s. */
54
+ private isolateProvider;
55
+ /** One call, budgeted: a throw or an overrun is reported and becomes `undefined`. */
56
+ private guard;
57
+ private report;
34
58
  markStarted(capability: Capability): void;
35
59
  stop(): Promise<void>;
36
60
  _absorb(capability: Capability): void;
37
61
  }
38
- export declare function assembleCapabilities(capabilities: readonly Capability[], ctx: CapabilityContext, options?: AssembleCapabilitiesOptions): Promise<AssembledCapabilities>;
62
+ export declare function assembleCapabilities(capabilities: readonly Capability[], ctx: Omit<RunContext, "injection" | "gates">, options?: AssembleCapabilitiesOptions): Promise<AssembledCapabilities>;
39
63
  //# sourceMappingURL=assembler.d.ts.map