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
@@ -11,6 +11,7 @@ export class ChatModel {
11
11
  * holds back for the summary against this — a model that cannot emit 20k never needs 20k
12
12
  * reserved. */
13
13
  maxOutputTokens;
14
+ /** Loading a deferred tool mid-conversation keeps the request prefix: SearchTool mode. */
14
15
  supportsDeferredTools;
15
16
  piModel;
16
17
  runtime;
@@ -19,7 +20,7 @@ export class ChatModel {
19
20
  requestDefaults;
20
21
  constructor(spec) {
21
22
  this.runtime = spec.runtime ?? createModelRuntime();
22
- this.piModel = resolvePiModel(spec, this.runtime);
23
+ this.piModel = withAnthropicToolChanges(resolvePiModel(spec, this.runtime));
23
24
  this.requestDefaults = {
24
25
  ...(spec.apiKey !== undefined ? { apiKey: spec.apiKey } : {}),
25
26
  ...spec.connection,
@@ -43,7 +44,7 @@ export class ChatModel {
43
44
  const ctx = toContext(req);
44
45
  let first;
45
46
  try {
46
- first = await this.runtime.models.completeSimple(this.piModel, ctx, toOptions(req, call, this.requestDefaults));
47
+ first = await this.runtime.models.completeSimple(this.piModel, ctx, this.options(req, call));
47
48
  }
48
49
  catch (error) {
49
50
  first = this.errorMessage(messageOf(error));
@@ -54,12 +55,15 @@ export class ChatModel {
54
55
  try {
55
56
  if (!(await forceRefreshOAuth(this.runtime, this.provider, call?.signal)))
56
57
  return first;
57
- return await this.runtime.models.completeSimple(this.piModel, ctx, toOptions(req, call, this.requestDefaults));
58
+ return await this.runtime.models.completeSimple(this.piModel, ctx, this.options(req, call));
58
59
  }
59
60
  catch (error) {
60
61
  return this.errorMessage(messageOf(error));
61
62
  }
62
63
  }
64
+ options(req, call) {
65
+ return toOptions(req, call, this.requestDefaults);
66
+ }
63
67
  async streamWithAuthRetry(req, call, ctx, out) {
64
68
  const first = await this.runAttempt(req, call, ctx, out);
65
69
  if (first.resolved)
@@ -79,10 +83,10 @@ export class ChatModel {
79
83
  }
80
84
  const second = await this.runAttempt(req, call, ctx, out);
81
85
  if (!second.resolved)
82
- out.push(second.terminal); // retry also failed → machine
86
+ out.push(second.terminal); // retry also failed → environment
83
87
  return;
84
88
  }
85
- out.push(first.terminal); // not a refreshable auth error → machine
89
+ out.push(first.terminal); // not a refreshable auth error → environment
86
90
  }
87
91
  /** Stream one attempt. Non-terminal events are relayed live; the terminal event is held so
88
92
  * a clean pre-content failure can be retried instead of surfaced. */
@@ -90,7 +94,7 @@ export class ChatModel {
90
94
  let streamedContent = false;
91
95
  let terminal;
92
96
  try {
93
- for await (const event of this.runtime.models.streamSimple(this.piModel, ctx, toOptions(req, call, this.requestDefaults))) {
97
+ for await (const event of this.runtime.models.streamSimple(this.piModel, ctx, this.options(req, call))) {
94
98
  if (event.type === "done" || event.type === "error") {
95
99
  terminal = event;
96
100
  break;
@@ -107,7 +111,7 @@ export class ChatModel {
107
111
  return { resolved: true }; // (pi always emits a terminal)
108
112
  const errorMessage = terminalErrorMessage(terminal);
109
113
  if (errorMessage === undefined || streamedContent) {
110
- out.push(terminal); // success, or a mid-stream error we must not retry → machine
114
+ out.push(terminal); // success, or a mid-stream error we must not retry → environment
111
115
  return { resolved: true };
112
116
  }
113
117
  return { resolved: false, errorMessage, terminal };
@@ -178,31 +182,65 @@ export function tryGetPiModel(provider, model, runtime = createModelRuntime()) {
178
182
  return runtime.models.getModel(provider, model);
179
183
  }
180
184
  /**
181
- * Mirror pi's public model-compat gates so Operon only hides capability tools
182
- * when the selected wire can materialize `addedToolNames`. pi remains the
183
- * authority for serialization; this gate only decides whether SearchTool mode
184
- * is safe to enter.
185
+ * Mirror pi's gates for anchoring a `toolsAdded` system message in place, so Operon only
186
+ * hides capability tools when loading one will not rewrite the request prefix. Everywhere
187
+ * else pi collapses later system messages into the leading one — the whole current tool list
188
+ * at the top — which is exactly the per-load prefix rewrite deferral must not cause.
185
189
  */
186
190
  function supportsNativeDeferredTools(model) {
187
191
  const compat = model.compat;
188
- if (model.api === "openai-completions")
189
- return compat?.deferredToolsMode === "kimi";
190
- if (model.api === "openai-responses" || model.api === "openai-codex-responses") {
191
- return compat?.supportsToolSearch === true;
192
+ if (compat?.supportsMidConvoSystemMessages !== true)
193
+ return false;
194
+ switch (model.api) {
195
+ case "anthropic-messages":
196
+ return compat.supportsMidConvoToolChanges === true;
197
+ case "openai-responses":
198
+ case "azure-openai-responses":
199
+ case "openai-codex-responses":
200
+ return compat.supportsAdditionalTools === true || compat.supportsToolSearch === true;
201
+ case "openai-completions":
202
+ return compat.supportsMidConvoToolAdditions === true;
203
+ default:
204
+ return false;
192
205
  }
206
+ }
207
+ /**
208
+ * Anthropic accepts mid-conversation `tool_addition` blocks from Opus 4.8 on, Sonnet 5
209
+ * excepted (the API's own rejection text; Sonnet 5.5 verified through OpenRouter). pi's
210
+ * catalog flags only the models it verified and none reached through other gateways, so
211
+ * fill in the Anthropic-wire models it leaves unset. An explicit flag always wins.
212
+ */
213
+ function withAnthropicToolChanges(model) {
193
214
  if (model.api !== "anthropic-messages")
215
+ return model;
216
+ const compat = model.compat;
217
+ if (compat?.supportsMidConvoToolChanges !== undefined || !acceptsMidConvoToolChanges(model.id))
218
+ return model;
219
+ return {
220
+ ...model,
221
+ compat: {
222
+ ...compat,
223
+ supportsMidConvoSystemMessages: compat?.supportsMidConvoSystemMessages ?? true,
224
+ supportsMidConvoToolChanges: true,
225
+ },
226
+ };
227
+ }
228
+ /** `claude-opus-4-8`, `anthropic/claude-sonnet-5.5`, `claude-fable-5-20260101`, ... */
229
+ export function acceptsMidConvoToolChanges(modelId) {
230
+ const match = modelId
231
+ .replace(/^.*\//, "")
232
+ .replace(/\./g, "-")
233
+ .match(/^claude-(opus|sonnet|fable)-(\d+)(?:-(\d{1,2}))?(?:-|$)/);
234
+ if (match === null)
194
235
  return false;
195
- if (compat?.supportsToolReferences !== undefined)
196
- return compat.supportsToolReferences;
197
- // pi's Anthropic default: first-party Claude >= 4.5, excluding Haiku.
198
- if (model.provider !== "anthropic" || model.id.includes("haiku"))
199
- return false;
200
- const version = model.id.match(/^claude-(?:opus|sonnet|fable)-(\d+)(?:-(\d+))?(?:-|$)/);
201
- if (!version)
236
+ const family = match[1];
237
+ const major = Number(match[2]);
238
+ const minor = match[3] === undefined ? 0 : Number(match[3]);
239
+ if (family === "fable")
240
+ return true;
241
+ if (family === "sonnet" && major === 5 && minor === 0)
202
242
  return false;
203
- const major = Number(version[1]);
204
- const minor = version[2] && version[2].length < 8 ? Number(version[2]) : 0;
205
- return major > 4 || (major === 4 && minor >= 5);
243
+ return major > 4 || (major === 4 && minor >= 8);
206
244
  }
207
245
  function toContext(req) {
208
246
  return {
@@ -1,6 +1,7 @@
1
1
  export { streamResult } from "./model.ts";
2
2
  export type { LlmRequest, CallOptions, ModelSettings, RetryHint, ThinkingBudgets, ThinkingLevel, StreamResultOptions, } from "./model.ts";
3
3
  export { ChatModel, defineModel, tryGetPiModel } from "./define-model.ts";
4
+ export * from "./provider.ts";
4
5
  export type { ModelConnection, ModelSpec } from "./define-model.ts";
5
6
  export { createModelRuntime, forceRefreshOAuth } from "./runtime.ts";
6
7
  export type { ModelRuntime, CreateModelRuntimeOptions } from "./runtime.ts";
package/dist/llm/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  export { streamResult } from "./model.js";
2
2
  export { ChatModel, defineModel, tryGetPiModel } from "./define-model.js";
3
+ export * from "./provider.js";
3
4
  export { createModelRuntime, forceRefreshOAuth } from "./runtime.js";
4
5
  export { streamWithRetry, DEFAULT_MAX_RETRIES_PER_STEP } from "./retry.js";
5
6
  export { InMemoryCredentialStore, MemoryCredentialStore, FileCredentialStore, } from "./auth.js";
@@ -28,6 +28,8 @@ export interface ModelSettings {
28
28
  export interface LlmRequest {
29
29
  readonly system?: string;
30
30
  readonly messages: readonly Message[];
31
+ /** Top-level tools. Tools that become available later in the conversation are declared
32
+ * by `system` messages in `messages` (pi's `toolsAdded`). */
31
33
  readonly tools?: readonly ToolSchema[];
32
34
  readonly params?: ModelSettings;
33
35
  readonly providerOptions?: Readonly<Record<string, unknown>>;
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Building a model provider, for hosts that configure endpoints the built-in catalog does not
3
+ * know — a self-hosted server, a gateway, a proxy in front of a vendor.
4
+ *
5
+ * The kernel owns the pi boundary, so these are re-exported here rather than imported from pi
6
+ * directly by an outer ring. A provider is a URL, an auth rule, a set of model descriptors (static,
7
+ * fetched, or both) and the wire dialect it speaks; `MutableModels.setProvider` registers it on a
8
+ * runtime, and everything downstream — `defineModel`, `Models.getAvailable`, the harness's
9
+ * `registerProvider` — treats it exactly like a built-in one.
10
+ */
11
+ export { createProvider, createModels } from "@earendil-works/pi-ai";
12
+ export { envApiKeyAuth } from "@earendil-works/pi-ai";
13
+ export { lazyApi, lazyStream } from "@earendil-works/pi-ai";
14
+ export type { CreateProviderOptions, Models, MutableModels, ModelsRefreshOptions, ModelsRefreshResult, RefreshModelsContext, ModelsPublication, ModelsStore, ModelsStoreEntry, } from "@earendil-works/pi-ai";
15
+ export type { ProviderStreams, ModelCost } from "@earendil-works/pi-ai";
16
+ export type { ApiKeyAuth, ProviderAuth, Credential, AuthCheck, AuthResult } from "@earendil-works/pi-ai";
17
+ //# sourceMappingURL=provider.d.ts.map
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Building a model provider, for hosts that configure endpoints the built-in catalog does not
3
+ * know — a self-hosted server, a gateway, a proxy in front of a vendor.
4
+ *
5
+ * The kernel owns the pi boundary, so these are re-exported here rather than imported from pi
6
+ * directly by an outer ring. A provider is a URL, an auth rule, a set of model descriptors (static,
7
+ * fetched, or both) and the wire dialect it speaks; `MutableModels.setProvider` registers it on a
8
+ * runtime, and everything downstream — `defineModel`, `Models.getAvailable`, the harness's
9
+ * `registerProvider` — treats it exactly like a built-in one.
10
+ */
11
+ export { createProvider, createModels } from "@earendil-works/pi-ai";
12
+ export { envApiKeyAuth } from "@earendil-works/pi-ai";
13
+ export { lazyApi, lazyStream } from "@earendil-works/pi-ai";
14
+ //# sourceMappingURL=provider.js.map
package/dist/llm/retry.js CHANGED
@@ -31,7 +31,7 @@ export async function streamWithRetry(input) {
31
31
  const hint = model.classifyError(reason);
32
32
  if (!hint.retryable || attempt >= maxRetries) {
33
33
  logger.log("error", "llm error", { model: model.id, attempt, mode: attemptResult.mode, retryable: hint.retryable, reason: result.message.errorMessage });
34
- return result; // give up → machine error as the result
34
+ return result; // give up → environment error as the result
35
35
  }
36
36
  input.onDropPartial?.(result.message);
37
37
  if (attemptResult.surfaced) {
@@ -39,6 +39,8 @@ export declare class ConversationContext {
39
39
  /** Runtime provenance for live messages; replay rebuilds it from record origins. */
40
40
  private readonly origins;
41
41
  private writeChain;
42
+ /** Audit writes in flight (never rejects — see `audit`). */
43
+ private auditWrites;
42
44
  /** Errors from failed appendRecord calls, surfaced (and cleared) on the next flush(). */
43
45
  private writeErrors;
44
46
  constructor(options?: ConversationContextOptions);
@@ -54,6 +56,13 @@ export declare class ConversationContext {
54
56
  replaceHistory(messages: readonly Message[]): void;
55
57
  originOf(message: Message): PromptOrigin | undefined;
56
58
  record(body: AgentRecordBody): void;
59
+ /**
60
+ * Write `body` to the session's audit shard, about this context's shard — for what nothing
61
+ * restores or replays from (an approval, a dropped partial). Best effort and unordered against
62
+ * this context's own records: a failed audit write is swallowed, never a turn's failure.
63
+ * `flush` waits for it to land.
64
+ */
65
+ audit(body: AgentRecordBody): void;
57
66
  /**
58
67
  * Wait for all journaled records to finish writing. Throws (once) if any write in the
59
68
  * batch since the last flush failed — a failed record is never silently dropped from
@@ -61,9 +70,20 @@ export declare class ConversationContext {
61
70
  * own write attempt (see `journal`).
62
71
  */
63
72
  flush(): Promise<void>;
64
- /** Replace live state from a shard's records, WITHOUT re-journaling (resume). */
73
+ /**
74
+ * Replace live state from this context's shard, WITHOUT re-journaling (resume). Records of
75
+ * other addresses are skipped, so a caller may hand in the whole session log: the open-time
76
+ * pre-build does exactly that, and folding a subagent's shard into `main` would splice its
77
+ * turns between main's tool calls and results.
78
+ */
65
79
  loadFromRecords(records: readonly AgentRecord[]): void;
66
80
  private journal;
67
81
  }
68
82
  export declare function replayContext(store: SessionStore, address?: string, onHistoryChange?: HistoryChangeListener): Promise<ConversationContext>;
83
+ /**
84
+ * A shard's records from its newest checkpoint on — all a replay needs, since a checkpoint does
85
+ * not depend on what precedes it. A store that cannot locate the checkpoint returns the whole
86
+ * shard, which folds to the same result.
87
+ */
88
+ export declare function readShardTail(store: SessionStore, address?: string): Promise<AgentRecord[]>;
69
89
  //# sourceMappingURL=context.d.ts.map
@@ -1,4 +1,5 @@
1
- import { DEFAULT_ADDRESS, reduceHistory, summaryMessage, } from "../store/store.js";
1
+ import { appendAudit, compactionSummaryOrigin, DEFAULT_ADDRESS, reduceHistory, summaryMessage, } from "../store/store.js";
2
+ import { loadedToolsForCompaction } from "../tool/search/loaded.js";
2
3
  export { summaryMessage } from "../store/store.js";
3
4
  export class ConversationContext {
4
5
  _history;
@@ -8,6 +9,8 @@ export class ConversationContext {
8
9
  /** Runtime provenance for live messages; replay rebuilds it from record origins. */
9
10
  origins = new WeakMap();
10
11
  writeChain = Promise.resolve();
12
+ /** Audit writes in flight (never rejects — see `audit`). */
13
+ auditWrites = Promise.resolve();
11
14
  /** Errors from failed appendRecord calls, surfaced (and cleared) on the next flush(). */
12
15
  writeErrors = [];
13
16
  constructor(options = {}) {
@@ -42,19 +45,27 @@ export class ConversationContext {
42
45
  this.journal({ type: "context.append_message", message, origin });
43
46
  }
44
47
  applyCompaction(c) {
45
- // Every model-visible message is journaled, so replay drops the same prefix count as live.
48
+ // Deferred-tool definitions the removed prefix loaded for calls the tail keeps ride on the
49
+ // summary's origin (see `CompactionSummaryOrigin.loadedTools`), computed before the splice.
50
+ const loadedTools = loadedToolsForCompaction(this, c.compactedCount);
46
51
  const summary = summaryMessage(c.summary);
47
52
  this._history.splice(0, c.compactedCount, summary);
48
- this.origins.set(summary, { kind: "compaction_summary" });
53
+ this.origins.set(summary, compactionSummaryOrigin(loadedTools));
54
+ // The record carries the kept tail itself, so it is a checkpoint: replay can start here
55
+ // without the messages before it (see `isCheckpointRecord`).
56
+ const kept = this._history.slice(1);
57
+ const keptOrigins = kept.map((message) => this.origins.get(message) ?? null);
49
58
  this.journal({
50
59
  type: "context.apply_compaction",
51
60
  summary: c.summary,
52
61
  // Pinned so the summary message replay builds is identical to this one.
53
62
  summaryTimestamp: summary.timestamp,
54
- cutoff: c.compactedCount,
63
+ kept,
64
+ ...(keptOrigins.some((origin) => origin !== null) ? { keptOrigins } : {}),
55
65
  compactedCount: c.compactedCount,
56
66
  tokensBefore: c.tokensBefore,
57
67
  tokensAfter: c.tokensAfter,
68
+ ...(loadedTools.length > 0 ? { loadedTools } : {}),
58
69
  });
59
70
  }
60
71
  replaceHistory(messages) {
@@ -72,6 +83,18 @@ export class ConversationContext {
72
83
  record(body) {
73
84
  this.journal(body);
74
85
  }
86
+ /**
87
+ * Write `body` to the session's audit shard, about this context's shard — for what nothing
88
+ * restores or replays from (an approval, a dropped partial). Best effort and unordered against
89
+ * this context's own records: a failed audit write is swallowed, never a turn's failure.
90
+ * `flush` waits for it to land.
91
+ */
92
+ audit(body) {
93
+ if (this.store === undefined)
94
+ return;
95
+ const write = appendAudit(this.store, body, this.address).then(() => undefined, () => undefined);
96
+ this.auditWrites = Promise.all([this.auditWrites, write]).then(() => undefined);
97
+ }
75
98
  /**
76
99
  * Wait for all journaled records to finish writing. Throws (once) if any write in the
77
100
  * batch since the last flush failed — a failed record is never silently dropped from
@@ -80,14 +103,21 @@ export class ConversationContext {
80
103
  */
81
104
  async flush() {
82
105
  await this.writeChain;
106
+ await this.auditWrites;
83
107
  if (this.writeErrors.length > 0) {
84
108
  const errors = this.writeErrors.splice(0, this.writeErrors.length);
85
109
  throw new AggregateError(errors, `${String(errors.length)} record(s) failed to persist to the session store`);
86
110
  }
87
111
  }
88
- /** Replace live state from a shard's records, WITHOUT re-journaling (resume). */
112
+ /**
113
+ * Replace live state from this context's shard, WITHOUT re-journaling (resume). Records of
114
+ * other addresses are skipped, so a caller may hand in the whole session log: the open-time
115
+ * pre-build does exactly that, and folding a subagent's shard into `main` would splice its
116
+ * turns between main's tool calls and results.
117
+ */
89
118
  loadFromRecords(records) {
90
- const { messages, origins } = reduceHistory(records);
119
+ const own = records.filter((record) => (record.address ?? DEFAULT_ADDRESS) === this.address);
120
+ const { messages, origins } = reduceHistory(own);
91
121
  this._history.splice(0, this._history.length, ...messages);
92
122
  for (let i = 0; i < messages.length; i++) {
93
123
  const origin = origins[i];
@@ -120,10 +150,18 @@ export async function replayContext(store, address, onHistoryChange) {
120
150
  // bypasses `journal`, because replaying is not a new history change — a consumer that seeded
121
151
  // itself from the same log would otherwise see every message twice.
122
152
  const ctx = new ConversationContext({ store, address, ...(onHistoryChange !== undefined ? { onHistoryChange } : {}) });
153
+ ctx.loadFromRecords(await readShardTail(store, ctx.address));
154
+ return ctx;
155
+ }
156
+ /**
157
+ * A shard's records from its newest checkpoint on — all a replay needs, since a checkpoint does
158
+ * not depend on what precedes it. A store that cannot locate the checkpoint returns the whole
159
+ * shard, which folds to the same result.
160
+ */
161
+ export async function readShardTail(store, address = DEFAULT_ADDRESS) {
123
162
  const records = [];
124
- for await (const record of store.readRecords({ address }))
163
+ for await (const record of store.readRecords({ address, fromCheckpoint: true }))
125
164
  records.push(record);
126
- ctx.loadFromRecords(records);
127
- return ctx;
165
+ return records;
128
166
  }
129
167
  //# sourceMappingURL=context.js.map
@@ -9,6 +9,10 @@ import type { AgentEventBody } from "../events/events.ts";
9
9
  * pi-agent design, where the loop emits AgentEvents through a single sink.
10
10
  *
11
11
  * (The loop has no `state`, so it cannot add the envelope itself — that is the sink's job.)
12
+ *
13
+ * The returned promise resolves once the event is published. Most emitters fire and forget; one
14
+ * that must order something after delivery (a nested call announced before its approval is
15
+ * asked) awaits it.
12
16
  */
13
- export type LoopEventDispatcher = (event: AgentEventBody) => void;
17
+ export type LoopEventDispatcher = (event: AgentEventBody) => void | Promise<void>;
14
18
  //# sourceMappingURL=events.d.ts.map
@@ -1,8 +1,8 @@
1
1
  export type * from "./types.ts";
2
2
  export { addUsage, emptyUsage, subtractUsage } from "./usage.ts";
3
3
  export { MaxStepsExceededError, isMaxStepsExceededError, isAbortError } from "./errors.ts";
4
- export { SteerBus, renderSteerText, steerOriginToPromptOrigin } from "./steer.ts";
5
- export type { SteerOrigin, SteerMessage, SteerContent, SteerContentPart, SteerBusOptions, SteerChannel, SteerReceipt, NowFn } from "./steer.ts";
4
+ export { SteerBus, renderSteerText, steerOriginToPromptOrigin, buildSteerMessage, steerQueuedRecord, steerMessageFromRecord } from "./steer.ts";
5
+ export type { SteerOrigin, SteerMessage, SteerContent, SteerContentPart, SteerBusOptions, SteerChannel, SteerReceipt, SteerOptions, SteerEnqueueListener, NowFn } from "./steer.ts";
6
6
  export { INTERRUPTION_STATE_KEY, INTERRUPTION_STATE_VERSION, applyInterruptionAnswers, flattenPendingInterrupts, getInterruptionState, parseInterruptionState, } from "./interruption.ts";
7
7
  export type { AgentDefinitionReference, InterruptAnswer, InterruptionAnchor, InterruptionExecution, InterruptionFrame, InterruptionPhase, InterruptionState, PendingRunInterrupt, } from "./interruption.ts";
8
8
  export { ConversationContext, replayContext, summaryMessage } from "./context.ts";
@@ -1,6 +1,6 @@
1
1
  export { addUsage, emptyUsage, subtractUsage } from "./usage.js";
2
2
  export { MaxStepsExceededError, isMaxStepsExceededError, isAbortError } from "./errors.js";
3
- export { SteerBus, renderSteerText, steerOriginToPromptOrigin } from "./steer.js";
3
+ export { SteerBus, renderSteerText, steerOriginToPromptOrigin, buildSteerMessage, steerQueuedRecord, steerMessageFromRecord } from "./steer.js";
4
4
  export { INTERRUPTION_STATE_KEY, INTERRUPTION_STATE_VERSION, applyInterruptionAnswers, flattenPendingInterrupts, getInterruptionState, parseInterruptionState, } from "./interruption.js";
5
5
  // source of truth lives in the log; `replayContext` rebuilds it on resume.
6
6
  export { ConversationContext, replayContext, summaryMessage } from "./context.js";
@@ -9,10 +9,10 @@ export interface AgentDefinitionReference {
9
9
  readonly key: string;
10
10
  readonly name: string;
11
11
  }
12
- /** Locates and validates the assistant batch whose execution is being continued. */
12
+ /** Locates the assistant batch whose execution is being continued. Any one call id from
13
+ * the batch identifies it, since the batch is the message that emitted that call. */
13
14
  export interface InterruptionAnchor {
14
15
  readonly toolCallId: string;
15
- readonly assistantDigest: string;
16
16
  }
17
17
  export interface InterruptionExecution {
18
18
  readonly turns: number;
@@ -83,8 +83,13 @@ export interface ToolCallSuspension {
83
83
  }
84
84
  export declare function newInterruptionId(prefix?: "run" | "interrupt" | "frame" | "agent" | "handoff"): string;
85
85
  export declare function interruptionAnchor(message: AssistantMessage, preferredToolCallId?: string): InterruptionAnchor;
86
- export declare function digestAssistantToolCalls(message: AssistantMessage): string;
87
- /** Finds the exact assistant batch in a replayed shard and rejects stale/mismatched logs. */
86
+ /**
87
+ * Finds the anchored assistant batch in a replayed shard. The batch is matched by call id
88
+ * alone: the three history mutators in `ConversationContext` only append, drop a prefix, or
89
+ * swap tool-result bodies, so a message that still carries this call id still carries the
90
+ * arguments it was paused on. A store that hands back something else is a broken store, and
91
+ * the resume trusts it the same way every other read does.
92
+ */
88
93
  export declare function findAnchoredAssistant(messages: readonly Message[], anchor: InterruptionAnchor): AssistantMessage;
89
94
  export declare function parseInterruptionState(raw: unknown): InterruptionState;
90
95
  export declare function flattenPendingInterrupts(state: InterruptionState): PendingRunInterrupt[];
@@ -1,4 +1,4 @@
1
- import { createHash, randomBytes } from "node:crypto";
1
+ import { randomBytes } from "node:crypto";
2
2
  export const INTERRUPTION_STATE_KEY = "interrupt";
3
3
  export const INTERRUPTION_STATE_VERSION = 1;
4
4
  export function newInterruptionId(prefix = "interrupt") {
@@ -12,25 +12,22 @@ export function interruptionAnchor(message, preferredToolCallId) {
12
12
  if (!calls.some((call) => call.id === toolCallId)) {
13
13
  throw new Error(`Cannot interrupt: tool call "${toolCallId}" is not present in the assistant batch.`);
14
14
  }
15
- return { toolCallId, assistantDigest: digestAssistantToolCalls(message) };
15
+ return { toolCallId };
16
16
  }
17
- export function digestAssistantToolCalls(message) {
18
- const canonical = stableStringify(assistantToolCalls(message).map((call) => ({ id: call.id, name: call.name, arguments: call.arguments })));
19
- return createHash("sha256").update(canonical).digest("hex");
20
- }
21
- /** Finds the exact assistant batch in a replayed shard and rejects stale/mismatched logs. */
17
+ /**
18
+ * Finds the anchored assistant batch in a replayed shard. The batch is matched by call id
19
+ * alone: the three history mutators in `ConversationContext` only append, drop a prefix, or
20
+ * swap tool-result bodies, so a message that still carries this call id still carries the
21
+ * arguments it was paused on. A store that hands back something else is a broken store, and
22
+ * the resume trusts it the same way every other read does.
23
+ */
22
24
  export function findAnchoredAssistant(messages, anchor) {
23
25
  for (let i = messages.length - 1; i >= 0; i--) {
24
26
  const message = messages[i];
25
27
  if (message.role !== "assistant")
26
28
  continue;
27
- if (!assistantToolCalls(message).some((call) => call.id === anchor.toolCallId))
28
- continue;
29
- const digest = digestAssistantToolCalls(message);
30
- if (digest !== anchor.assistantDigest) {
31
- throw new Error(`Cannot resume: assistant batch for tool call "${anchor.toolCallId}" changed (digest mismatch).`);
32
- }
33
- return message;
29
+ if (assistantToolCalls(message).some((call) => call.id === anchor.toolCallId))
30
+ return message;
34
31
  }
35
32
  throw new Error(`Cannot resume: tool call "${anchor.toolCallId}" was not found in the replayed log.`);
36
33
  }
@@ -174,17 +171,6 @@ export function getInterruptionState(result) {
174
171
  function assistantToolCalls(message) {
175
172
  return message.content.filter((part) => part.type === "toolCall");
176
173
  }
177
- function stableStringify(value) {
178
- if (value === null || typeof value !== "object")
179
- return JSON.stringify(value) ?? "null";
180
- if (Array.isArray(value))
181
- return `[${value.map(stableStringify).join(",")}]`;
182
- const record = value;
183
- return `{${Object.keys(record)
184
- .sort()
185
- .map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`)
186
- .join(",")}}`;
187
- }
188
174
  function isRecord(value) {
189
175
  return typeof value === "object" && value !== null && !Array.isArray(value);
190
176
  }
@@ -1,13 +1,16 @@
1
+ import type { ApprovalResponse } from "../permission/types.ts";
1
2
  import type { ChatModel } from "../llm/define-model.ts";
3
+ import type { LlmRequest } from "../llm/model.ts";
2
4
  import type { AssistantMessage, Message, Usage } from "../protocol/index.ts";
3
5
  import type { PromptOrigin } from "../store/origin.ts";
4
6
  import type { Tool } from "../tool/types.ts";
5
- import type { Machine } from "../tool/machine.ts";
7
+ import type { Environment } from "../tool/environment.ts";
6
8
  import type { BackgroundSpawner } from "../tool/background.ts";
7
9
  import type { QuestionResponder } from "../tool/questions.ts";
8
10
  import { FileFreshnessLedger } from "../tool/file-freshness.ts";
9
11
  import type { Logger } from "../logging/index.ts";
10
12
  import { type RecordUsageResult } from "./turn-step.ts";
13
+ import { type ToolCatalogSnapshot } from "../tool/search/catalog.ts";
11
14
  import type { ConversationContext } from "./context.ts";
12
15
  import type { LoopEventDispatcher } from "./events.ts";
13
16
  import type { BatchResume, LoopHooks, OutputGuardrailMonitorFactory, TurnResult } from "./types.ts";
@@ -18,18 +21,26 @@ export interface RunTurnInput {
18
21
  readonly sessionId?: string;
19
22
  readonly signal: AbortSignal;
20
23
  readonly model: ChatModel;
21
- readonly machine: Machine;
24
+ readonly environment: Environment;
22
25
  readonly background?: BackgroundSpawner;
23
26
  /** Client interactive-question channel; forwarded to tool contexts (AskUserQuestion). */
24
27
  readonly responder?: QuestionResponder;
25
28
  /** Session-scoped file freshness ledger for this agent line; forwarded to tool contexts. */
26
29
  readonly fileLedger?: FileFreshnessLedger;
30
+ /** Host application context (`RunOptions.context`); forwarded to both tool contexts as `context`. */
31
+ readonly hostContext?: unknown;
27
32
  readonly system?: string;
28
- readonly params?: import("../llm/model.ts").LlmRequest["params"];
33
+ readonly params?: LlmRequest["params"];
29
34
  readonly context: ConversationContext;
30
35
  readonly tools?: readonly Tool[];
31
36
  /** Capability tools hidden until transcript load/use evidence activates them. */
32
37
  readonly deferredToolNames?: ReadonlySet<string>;
38
+ readonly deferEnabled?: boolean;
39
+ /** Snapshot after beforeStep, so a connection completed during a turn is seen next step. */
40
+ readonly refreshTools?: () => Promise<ToolCatalogSnapshot>;
41
+ readonly onToolsPrepared?: (tools: readonly Tool[]) => void;
42
+ /** Each step's request as it goes to the model, after every hook. */
43
+ readonly onRequestPrepared?: (request: LlmRequest) => void;
33
44
  readonly hooks?: LoopHooks;
34
45
  /** Per-step optimistic output guardrail adapter supplied by the active agent layer. */
35
46
  readonly createOutputGuardrailMonitor?: OutputGuardrailMonitorFactory;
@@ -44,6 +55,8 @@ export interface RunTurnInput {
44
55
  * by the re-run batch (suspended-call continuation and auto re-park). */
45
56
  readonly resume?: BatchResume;
46
57
  readonly drainSteering?: () => readonly SteeredInput[];
58
+ /** The run's approval answers by tool call id; see `ToolCallStepContext.answers`. */
59
+ readonly answers?: Record<string, ApprovalResponse>;
47
60
  }
48
61
  /** A steered message plus its structured origin, mapped by the caller (which owns the SteerBus). */
49
62
  export interface SteeredInput {
@@ -3,7 +3,7 @@ import { addUsage, emptyUsage } from "./usage.js";
3
3
  import { isAbortError, MaxStepsExceededError } from "./errors.js";
4
4
  import { APIContextOverflowError } from "../llm/errors.js";
5
5
  import { executeStep } from "./turn-step.js";
6
- import { activeDeferredTools } from "../tool/search/activation.js";
6
+ import { describeUnknownTool, prepareToolCatalog } from "../tool/search/catalog.js";
7
7
  import { runCalls } from "./tool-call.js";
8
8
  /**
9
9
  * Cap on `recoverStepError` claims per turn. A claimant that keeps "recovering" without
@@ -30,11 +30,14 @@ export async function runTurn(input) {
30
30
  try {
31
31
  // HITL resume — re-run the interrupted batch with pre-loaded answers first.
32
32
  if (input.resumeFrom) {
33
- const resumeTools = activeDeferredTools(toolList, deferredToolNames, input.context.messages);
33
+ const resumeSnapshot = input.refreshTools ? await input.refreshTools() : { tools: toolList, deferredToolNames, deferEnabled: input.deferEnabled };
34
+ const resumePrepared = prepareToolCatalog(input.context, resumeSnapshot, { announce: false });
35
+ const resumeTools = resumePrepared.tools;
36
+ input.onToolsPrepared?.(resumeTools);
34
37
  const resumeToolMap = new Map(resumeTools.map((tool) => [tool.schema.name, tool]));
35
38
  const completed = completedToolCallIds(input.context.messages, input.resumeFrom);
36
39
  const calls = input.resumeFrom.content.filter((p) => p.type === "toolCall" && !completed.has(p.id));
37
- const batch = await runCalls({ turnId: input.turnId, stepNumber: 0, address: input.address, signal: input.signal, model: input.model, machine: input.machine, background: input.background, responder: input.responder, fileLedger, tools: resumeToolMap, hooks: input.hooks, dispatchEvent: input.dispatchEvent, logger: input.logger, resume: input.resume }, calls);
40
+ const batch = await runCalls({ turnId: input.turnId, stepNumber: 0, address: input.address, signal: input.signal, model: input.model, environment: input.environment, background: input.background, responder: input.responder, fileLedger, hostContext: input.hostContext, tools: resumeToolMap, describeUnknownTool: (name) => describeUnknownTool(resumePrepared, name), hooks: input.hooks, dispatchEvent: input.dispatchEvent, logger: input.logger, answers: input.answers, resume: input.resume }, calls);
38
41
  // No hand-written `message.appended` here (or at the two drains below): appending
39
42
  // journals, and journaling broadcasts. See ConversationContext.onHistoryChange.
40
43
  for (const result of batch.results)
@@ -74,15 +77,20 @@ export async function runTurn(input) {
74
77
  sessionId: input.sessionId,
75
78
  signal: input.signal,
76
79
  model: input.model,
77
- machine: input.machine,
80
+ environment: input.environment,
78
81
  background: input.background,
79
82
  responder: input.responder,
80
83
  fileLedger,
84
+ hostContext: input.hostContext,
81
85
  system: input.system,
82
86
  context: input.context,
83
87
  params: input.params,
84
88
  tools: toolList,
85
89
  deferredToolNames,
90
+ deferEnabled: input.deferEnabled,
91
+ refreshTools: input.refreshTools,
92
+ onToolsPrepared: input.onToolsPrepared,
93
+ onRequestPrepared: input.onRequestPrepared,
86
94
  hooks: input.hooks,
87
95
  createOutputGuardrailMonitor: input.createOutputGuardrailMonitor,
88
96
  currentStep: steps,
@@ -90,6 +98,7 @@ export async function runTurn(input) {
90
98
  dispatchEvent: input.dispatchEvent,
91
99
  logger: input.logger,
92
100
  recordUsage,
101
+ answers: input.answers,
93
102
  });
94
103
  }
95
104
  catch (error) {