stitchkit 0.135.1 → 0.136.1

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 (436) hide show
  1. package/CHANGELOG.md +122 -0
  2. package/README.md +37 -11
  3. package/dist/agent-executor/acp/v1-session-build.d.ts +51 -0
  4. package/dist/agent-executor/acp/v1-session-build.d.ts.map +1 -0
  5. package/dist/agent-executor/acp/v1-session.d.ts +1 -1
  6. package/dist/agent-executor/acp/v1-session.d.ts.map +1 -1
  7. package/dist/agent-executor/claude/classify.d.ts +1 -1
  8. package/dist/agent-executor/claude/classify.d.ts.map +1 -1
  9. package/dist/agent-executor/claude/events-wire.d.ts +13 -0
  10. package/dist/agent-executor/claude/events-wire.d.ts.map +1 -0
  11. package/dist/agent-executor/claude/events.d.ts +1 -11
  12. package/dist/agent-executor/claude/events.d.ts.map +1 -1
  13. package/dist/agent-executor/codex/protocol.d.ts +0 -143
  14. package/dist/agent-executor/codex/protocol.d.ts.map +1 -1
  15. package/dist/agent-executor/codex/request-answers.d.ts +1 -1
  16. package/dist/agent-executor/codex/request-answers.d.ts.map +1 -1
  17. package/dist/agent-executor/codex/server-requests.d.ts +150 -0
  18. package/dist/agent-executor/codex/server-requests.d.ts.map +1 -0
  19. package/dist/agent-executor/executor-contract.d.ts.map +1 -1
  20. package/dist/agent-executor/image-input.d.ts +10 -3
  21. package/dist/agent-executor/image-input.d.ts.map +1 -1
  22. package/dist/agent-executor/testing/replay-scenarios.d.ts.map +1 -1
  23. package/dist/agent-executor/testing/replay-transcript.d.ts.map +1 -1
  24. package/dist/agent-executor/vocabulary.d.ts +80 -0
  25. package/dist/agent-executor/vocabulary.d.ts.map +1 -1
  26. package/dist/agent-parts/model.d.ts +94 -0
  27. package/dist/agent-parts/model.d.ts.map +1 -1
  28. package/dist/agent-parts/parts.d.ts +176 -0
  29. package/dist/agent-parts/parts.d.ts.map +1 -1
  30. package/dist/agent-runtime/browser/browser-control-contract.d.ts +444 -0
  31. package/dist/agent-runtime/browser/browser-control-contract.d.ts.map +1 -1
  32. package/dist/agent-runtime/browser/control-schema.d.ts +532 -0
  33. package/dist/agent-runtime/browser/control-schema.d.ts.map +1 -1
  34. package/dist/agent-runtime/browser/control-view.d.ts.map +1 -1
  35. package/dist/agent-runtime/event-schema.d.ts +720 -3
  36. package/dist/agent-runtime/event-schema.d.ts.map +1 -1
  37. package/dist/agent-runtime/history/run-history-parts.d.ts.map +1 -1
  38. package/dist/agent-runtime/loop/deferred-tools.d.ts.map +1 -1
  39. package/dist/agent-runtime/loop/invocation-payload.d.ts.map +1 -1
  40. package/dist/agent-runtime/loop/invocation-stream.d.ts +9 -1
  41. package/dist/agent-runtime/loop/invocation-stream.d.ts.map +1 -1
  42. package/dist/agent-runtime/loop/provider-stream-parts.d.ts +6 -0
  43. package/dist/agent-runtime/loop/provider-stream-parts.d.ts.map +1 -1
  44. package/dist/agent-runtime/loop/provider-stream-segments.d.ts +1 -3
  45. package/dist/agent-runtime/loop/provider-stream-segments.d.ts.map +1 -1
  46. package/dist/agent-runtime/loop/run-acquisition.d.ts.map +1 -1
  47. package/dist/agent-runtime/loop/run-approval-signature.d.ts +38 -0
  48. package/dist/agent-runtime/loop/run-approval-signature.d.ts.map +1 -0
  49. package/dist/agent-runtime/loop/run-approval.d.ts +0 -28
  50. package/dist/agent-runtime/loop/run-approval.d.ts.map +1 -1
  51. package/dist/agent-runtime/loop/run-complete-port.d.ts +24 -0
  52. package/dist/agent-runtime/loop/run-complete-port.d.ts.map +1 -0
  53. package/dist/agent-runtime/loop/run-complete-stream.d.ts +7 -2
  54. package/dist/agent-runtime/loop/run-complete-stream.d.ts.map +1 -1
  55. package/dist/agent-runtime/loop/run-complete-types.d.ts +14 -1
  56. package/dist/agent-runtime/loop/run-complete-types.d.ts.map +1 -1
  57. package/dist/agent-runtime/loop/run-complete.d.ts +2 -2
  58. package/dist/agent-runtime/loop/run-complete.d.ts.map +1 -1
  59. package/dist/agent-runtime/loop/run-execution-state.d.ts +8 -0
  60. package/dist/agent-runtime/loop/run-execution-state.d.ts.map +1 -1
  61. package/dist/agent-runtime/loop/run-loop-events.d.ts +6 -1
  62. package/dist/agent-runtime/loop/run-loop-events.d.ts.map +1 -1
  63. package/dist/agent-runtime/loop/run-model-call.d.ts +44 -0
  64. package/dist/agent-runtime/loop/run-model-call.d.ts.map +1 -0
  65. package/dist/agent-runtime/loop/run-model-step.d.ts +25 -28
  66. package/dist/agent-runtime/loop/run-model-step.d.ts.map +1 -1
  67. package/dist/agent-runtime/loop/run-model-steps.d.ts +6 -0
  68. package/dist/agent-runtime/loop/run-model-steps.d.ts.map +1 -0
  69. package/dist/agent-runtime/loop/run-model-stream.d.ts +3 -1
  70. package/dist/agent-runtime/loop/run-model-stream.d.ts.map +1 -1
  71. package/dist/agent-runtime/loop/run-operation-lifecycle.d.ts +0 -2
  72. package/dist/agent-runtime/loop/run-operation-lifecycle.d.ts.map +1 -1
  73. package/dist/agent-runtime/loop/run-step-loop.d.ts +19 -0
  74. package/dist/agent-runtime/loop/run-step-loop.d.ts.map +1 -0
  75. package/dist/agent-runtime/loop/run-step-port.d.ts +175 -0
  76. package/dist/agent-runtime/loop/run-step-port.d.ts.map +1 -0
  77. package/dist/agent-runtime/loop/run-stream-parts.d.ts.map +1 -1
  78. package/dist/agent-runtime/loop/run-stream-recorded.d.ts.map +1 -1
  79. package/dist/agent-runtime/loop/run-stream-step-text.d.ts.map +1 -1
  80. package/dist/agent-runtime/loop/run-tool-approval-flow.d.ts +2 -1
  81. package/dist/agent-runtime/loop/run-tool-approval-flow.d.ts.map +1 -1
  82. package/dist/agent-runtime/loop/run-tool-call-input.d.ts +39 -0
  83. package/dist/agent-runtime/loop/run-tool-call-input.d.ts.map +1 -0
  84. package/dist/agent-runtime/loop/run-tool-call.d.ts +13 -34
  85. package/dist/agent-runtime/loop/run-tool-call.d.ts.map +1 -1
  86. package/dist/agent-runtime/loop/run-tool-errors.d.ts +5 -0
  87. package/dist/agent-runtime/loop/run-tool-errors.d.ts.map +1 -1
  88. package/dist/agent-runtime/loop/run-tool-executor.d.ts +1 -1
  89. package/dist/agent-runtime/loop/run-tool-executor.d.ts.map +1 -1
  90. package/dist/agent-runtime/loop/run-tool-slots.d.ts +2 -1
  91. package/dist/agent-runtime/loop/run-tool-slots.d.ts.map +1 -1
  92. package/dist/agent-runtime/loop/runtime-state.d.ts.map +1 -1
  93. package/dist/agent-runtime/loop/runtime.d.ts +0 -5
  94. package/dist/agent-runtime/loop/runtime.d.ts.map +1 -1
  95. package/dist/agent-runtime/providers/ai-sdk-convert.d.ts +1 -5
  96. package/dist/agent-runtime/providers/ai-sdk-convert.d.ts.map +1 -1
  97. package/dist/agent-runtime/providers/ai-sdk-normalize.d.ts +15 -0
  98. package/dist/agent-runtime/providers/ai-sdk-normalize.d.ts.map +1 -0
  99. package/dist/agent-runtime/providers/ai-sdk-tools.d.ts +11 -0
  100. package/dist/agent-runtime/providers/ai-sdk-tools.d.ts.map +1 -0
  101. package/dist/agent-runtime/providers/ai-sdk.d.ts +1 -9
  102. package/dist/agent-runtime/providers/ai-sdk.d.ts.map +1 -1
  103. package/dist/agent-runtime/providers/anthropic-sse.d.ts.map +1 -1
  104. package/dist/agent-runtime/providers/openrouter-admission.d.ts.map +1 -1
  105. package/dist/agent-runtime/providers/openrouter-audio.d.ts +123 -81
  106. package/dist/agent-runtime/providers/openrouter-audio.d.ts.map +1 -1
  107. package/dist/agent-runtime/providers/openrouter-catalog-cache.d.ts.map +1 -1
  108. package/dist/agent-runtime/providers/openrouter-catalog-query.d.ts.map +1 -1
  109. package/dist/agent-runtime/providers/openrouter-catalog.d.ts +2 -2
  110. package/dist/agent-runtime/providers/openrouter-catalog.d.ts.map +1 -1
  111. package/dist/agent-runtime/providers/openrouter-client.d.ts +37 -0
  112. package/dist/agent-runtime/providers/openrouter-client.d.ts.map +1 -0
  113. package/dist/agent-runtime/providers/openrouter-http.d.ts +26 -6
  114. package/dist/agent-runtime/providers/openrouter-http.d.ts.map +1 -1
  115. package/dist/agent-runtime/providers/openrouter-media.d.ts +91 -77
  116. package/dist/agent-runtime/providers/openrouter-media.d.ts.map +1 -1
  117. package/dist/agent-runtime/providers/openrouter-models.d.ts +2 -23
  118. package/dist/agent-runtime/providers/openrouter-models.d.ts.map +1 -1
  119. package/dist/agent-runtime/providers/openrouter-options.d.ts +2 -0
  120. package/dist/agent-runtime/providers/openrouter-options.d.ts.map +1 -1
  121. package/dist/agent-runtime/providers/openrouter-request.d.ts +23 -0
  122. package/dist/agent-runtime/providers/openrouter-request.d.ts.map +1 -0
  123. package/dist/agent-runtime/providers/openrouter-retrieval.d.ts +86 -55
  124. package/dist/agent-runtime/providers/openrouter-retrieval.d.ts.map +1 -1
  125. package/dist/agent-runtime/providers/openrouter-speech.d.ts +90 -0
  126. package/dist/agent-runtime/providers/openrouter-speech.d.ts.map +1 -0
  127. package/dist/agent-runtime/providers/openrouter-spend.d.ts +2 -2
  128. package/dist/agent-runtime/providers/openrouter-spend.d.ts.map +1 -1
  129. package/dist/agent-runtime/providers/openrouter-stream.d.ts.map +1 -1
  130. package/dist/agent-runtime/providers/openrouter-systemone.d.ts +87 -32
  131. package/dist/agent-runtime/providers/openrouter-systemone.d.ts.map +1 -1
  132. package/dist/agent-runtime/providers/openrouter-url.d.ts +7 -1
  133. package/dist/agent-runtime/providers/openrouter-url.d.ts.map +1 -1
  134. package/dist/agent-runtime/providers/openrouter-wire.d.ts +45 -0
  135. package/dist/agent-runtime/providers/openrouter-wire.d.ts.map +1 -0
  136. package/dist/agent-runtime/providers/openrouter.d.ts +1 -3
  137. package/dist/agent-runtime/providers/openrouter.d.ts.map +1 -1
  138. package/dist/agent-runtime/providers/provider-http.d.ts +14 -2
  139. package/dist/agent-runtime/providers/provider-http.d.ts.map +1 -1
  140. package/dist/agent-runtime/providers/provider-json-schema-strip.d.ts.map +1 -1
  141. package/dist/agent-runtime/providers/provider-json-schema.d.ts.map +1 -1
  142. package/dist/agent-runtime/providers/provider-openai-chat-sse.d.ts.map +1 -1
  143. package/dist/agent-runtime/providers/provider-openai-chat-state.d.ts +42 -0
  144. package/dist/agent-runtime/providers/provider-openai-chat-state.d.ts.map +1 -0
  145. package/dist/agent-runtime/providers/provider-usage.d.ts +9 -0
  146. package/dist/agent-runtime/providers/provider-usage.d.ts.map +1 -1
  147. package/dist/agent-runtime/runtime-internals.d.ts +1 -3
  148. package/dist/agent-runtime/runtime-internals.d.ts.map +1 -1
  149. package/dist/agent-runtime/sandbox/sandbox-bubblewrap-args.d.ts +9 -0
  150. package/dist/agent-runtime/sandbox/sandbox-bubblewrap-args.d.ts.map +1 -1
  151. package/dist/agent-runtime/sandbox/sandbox-bubblewrap.d.ts +6 -0
  152. package/dist/agent-runtime/sandbox/sandbox-bubblewrap.d.ts.map +1 -1
  153. package/dist/agent-runtime/sandbox/sandbox-contract.d.ts.map +1 -1
  154. package/dist/agent-runtime/sandbox/sandbox-process-linux.d.ts.map +1 -1
  155. package/dist/agent-runtime/sandbox/sandbox-process-spec.d.ts +5 -1
  156. package/dist/agent-runtime/sandbox/sandbox-process-spec.d.ts.map +1 -1
  157. package/dist/agent-runtime/sandbox/sandbox-process-wrapper.d.ts.map +1 -1
  158. package/dist/agent-runtime/schemas-json-projection.d.ts +29 -0
  159. package/dist/agent-runtime/schemas-json-projection.d.ts.map +1 -0
  160. package/dist/agent-runtime/schemas-message.d.ts +88 -0
  161. package/dist/agent-runtime/schemas-message.d.ts.map +1 -1
  162. package/dist/agent-runtime/schemas-run.d.ts +88 -0
  163. package/dist/agent-runtime/schemas-run.d.ts.map +1 -1
  164. package/dist/agent-runtime/stores/branch-messages.d.ts.map +1 -1
  165. package/dist/agent-runtime/stores/branch-observations.d.ts +42 -42
  166. package/dist/agent-runtime/stores/branch-replay.d.ts +264 -0
  167. package/dist/agent-runtime/stores/branch-replay.d.ts.map +1 -1
  168. package/dist/agent-runtime/stores/conversations.d.ts +88 -0
  169. package/dist/agent-runtime/stores/conversations.d.ts.map +1 -1
  170. package/dist/agent-runtime/stores/sql-rows.d.ts +74 -10
  171. package/dist/agent-runtime/stores/sql-rows.d.ts.map +1 -1
  172. package/dist/agent-runtime/stores/store-driver-contract.d.ts +616 -0
  173. package/dist/agent-runtime/stores/store-driver-contract.d.ts.map +1 -1
  174. package/dist/agent-runtime/stores/store-events.d.ts +1056 -0
  175. package/dist/agent-runtime/stores/store-events.d.ts.map +1 -1
  176. package/dist/agent-runtime/stores/store.d.ts +1232 -0
  177. package/dist/agent-runtime/stores/store.d.ts.map +1 -1
  178. package/dist/agent-runtime/terminal-commit.d.ts +74 -10
  179. package/dist/agent-runtime/terminal-commit.d.ts.map +1 -1
  180. package/dist/agent-runtime/testing/fault-bench.d.ts +5 -1
  181. package/dist/agent-runtime/testing/fault-bench.d.ts.map +1 -1
  182. package/dist/agent-runtime/testing/store-conformance-lifecycle.d.ts +158 -30
  183. package/dist/agent-runtime/testing/store-conformance-lifecycle.d.ts.map +1 -1
  184. package/dist/agent-runtime/testing/store-conformance-support.d.ts +79 -15
  185. package/dist/agent-runtime/testing/store-conformance-support.d.ts.map +1 -1
  186. package/dist/application/diagnostic-journal-contract.d.ts.map +1 -1
  187. package/dist/application/diagnostic-journal-manager.d.ts +1 -1
  188. package/dist/application/diagnostic-journal-manager.d.ts.map +1 -1
  189. package/dist/application/notification-delivery.d.ts.map +1 -1
  190. package/dist/browser/client-executors.d.ts.map +1 -1
  191. package/dist/browser/client-url.d.ts.map +1 -1
  192. package/dist/contract/define.d.ts +3 -7
  193. package/dist/contract/define.d.ts.map +1 -1
  194. package/dist/contract/normalize.d.ts +17 -5
  195. package/dist/contract/normalize.d.ts.map +1 -1
  196. package/dist/entrypoints/agent-executor/acp.js +9 -6
  197. package/dist/entrypoints/agent-executor/claude-sdk.js +26 -25
  198. package/dist/entrypoints/agent-executor/claude.js +13 -12
  199. package/dist/entrypoints/agent-executor/codex.d.ts +2 -1
  200. package/dist/entrypoints/agent-executor/codex.d.ts.map +1 -1
  201. package/dist/entrypoints/agent-executor/codex.js +135 -40
  202. package/dist/entrypoints/agent-executor/testing/claude-sdk.js +5 -4
  203. package/dist/entrypoints/agent-executor/testing.js +23 -18
  204. package/dist/entrypoints/agent-executor.js +8 -8
  205. package/dist/entrypoints/agent-runtime/ai-sdk.d.ts +2 -1
  206. package/dist/entrypoints/agent-runtime/ai-sdk.d.ts.map +1 -1
  207. package/dist/entrypoints/agent-runtime/ai-sdk.js +34 -30
  208. package/dist/entrypoints/agent-runtime/anthropic.js +15 -12
  209. package/dist/entrypoints/agent-runtime/browser.js +13 -8
  210. package/dist/entrypoints/agent-runtime/harness.js +26 -27
  211. package/dist/entrypoints/agent-runtime/openai.js +7 -7
  212. package/dist/entrypoints/agent-runtime/openrouter.d.ts +7 -5
  213. package/dist/entrypoints/agent-runtime/openrouter.d.ts.map +1 -1
  214. package/dist/entrypoints/agent-runtime/openrouter.js +1097 -856
  215. package/dist/entrypoints/agent-runtime/postgres.js +9 -9
  216. package/dist/entrypoints/agent-runtime/realtime.js +9 -8
  217. package/dist/entrypoints/agent-runtime/sandbox.js +167 -139
  218. package/dist/entrypoints/agent-runtime/sqlite/bun.js +10 -10
  219. package/dist/entrypoints/agent-runtime/sqlite/node.js +10 -10
  220. package/dist/entrypoints/agent-runtime/testing.js +9 -9
  221. package/dist/entrypoints/agent-runtime.js +261 -375
  222. package/dist/entrypoints/application/diagnostic-journal.js +14 -10
  223. package/dist/entrypoints/application.js +18 -6
  224. package/dist/entrypoints/cli.js +36 -15
  225. package/dist/entrypoints/contract.js +12 -10
  226. package/dist/entrypoints/geo.js +1 -1
  227. package/dist/entrypoints/handler.js +5 -6
  228. package/dist/entrypoints/http.d.ts +2 -0
  229. package/dist/entrypoints/http.d.ts.map +1 -1
  230. package/dist/entrypoints/http.js +16 -4
  231. package/dist/entrypoints/index.js +26 -35
  232. package/dist/entrypoints/live.js +3 -3
  233. package/dist/entrypoints/node.js +7 -7
  234. package/dist/entrypoints/observability.js +9 -7
  235. package/dist/entrypoints/process.js +3 -3
  236. package/dist/entrypoints/remote.js +5 -5
  237. package/dist/entrypoints/server.js +29 -16
  238. package/dist/entrypoints/telegram/grammy.d.ts +1 -1
  239. package/dist/entrypoints/telegram/grammy.d.ts.map +1 -1
  240. package/dist/entrypoints/telegram/grammy.js +39 -5
  241. package/dist/entrypoints/telegram/screens.js +3 -0
  242. package/dist/entrypoints/telegram.d.ts +1 -1
  243. package/dist/entrypoints/telegram.d.ts.map +1 -1
  244. package/dist/entrypoints/telegram.js +19 -6
  245. package/dist/entrypoints/testing.js +10 -11
  246. package/dist/entrypoints/tools/agent.js +9 -10
  247. package/dist/entrypoints/tools/connections.js +27 -57
  248. package/dist/entrypoints/tools/contract.js +4 -4
  249. package/dist/entrypoints/tools/invoker.js +7 -8
  250. package/dist/entrypoints/tools/mcp.js +9 -10
  251. package/dist/entrypoints/tools/toolkit.js +11 -12
  252. package/dist/entrypoints/tools.js +24 -22
  253. package/dist/entrypoints/tracking/contract.js +1 -1
  254. package/dist/entrypoints/tracking/performance.js +1 -1
  255. package/dist/entrypoints/tracking.js +1 -1
  256. package/dist/{index-3czc3ykr.js → index-08a3qfr8.js} +1 -1
  257. package/dist/index-1psbyyhj.js +21 -0
  258. package/dist/{index-pdcbjd6a.js → index-1yky29qg.js} +6 -3
  259. package/dist/{index-b4c9dpzm.js → index-252den5a.js} +10 -11
  260. package/dist/{index-yhwx4fwk.js → index-26v8hjqm.js} +4 -4
  261. package/dist/{index-xtby8rj3.js → index-28kbdn63.js} +5 -47
  262. package/dist/{index-c24bj2r1.js → index-2wm9b9vs.js} +5 -5
  263. package/dist/{index-ht71v1ag.js → index-32ew02z1.js} +60 -45
  264. package/dist/{index-dm84tsd5.js → index-3kb8dw48.js} +1 -1
  265. package/dist/index-3tb82xr7.js +11 -0
  266. package/dist/{index-nr4fhfn4.js → index-4p2zx593.js} +2 -0
  267. package/dist/{index-grhhsrd5.js → index-4q9tmzea.js} +5 -4
  268. package/dist/{index-mcv7b2n0.js → index-63ctzjp4.js} +497 -495
  269. package/dist/{index-y0a4gt1s.js → index-65p8v81y.js} +3 -2
  270. package/dist/{index-z72vazf5.js → index-6y3eae97.js} +27 -83
  271. package/dist/{index-y0mwkgkf.js → index-8cnfgwg8.js} +1212 -1139
  272. package/dist/{index-mkmep637.js → index-9m1m92rg.js} +1 -1
  273. package/dist/{index-5awtbyns.js → index-9vj869rx.js} +1 -1
  274. package/dist/index-a1rjr381.js +114 -0
  275. package/dist/{index-6kwdfb9m.js → index-akesakvj.js} +23 -4
  276. package/dist/{index-5q0qpw3v.js → index-aqm7e864.js} +23 -8
  277. package/dist/{index-d4at0q09.js → index-b9mj31q7.js} +90 -88
  278. package/dist/{index-baba8ehy.js → index-bjrcbcn2.js} +2 -2
  279. package/dist/{index-fsw9wxk9.js → index-c9j8441q.js} +1 -103
  280. package/dist/{index-wdb5jhas.js → index-d1pdv8qc.js} +1 -1
  281. package/dist/{index-v0j22shs.js → index-d5mhgx72.js} +16 -11
  282. package/dist/{index-73wq9abg.js → index-df5xr2f9.js} +13 -59
  283. package/dist/{index-n9358ydy.js → index-dm50x3by.js} +1 -1
  284. package/dist/{index-zyyerdny.js → index-dmrx8xma.js} +3 -0
  285. package/dist/{index-78da4g74.js → index-dwq6a6sq.js} +17 -13
  286. package/dist/{index-9be3tf6r.js → index-e413q2cj.js} +49 -22
  287. package/dist/{index-57sbckhv.js → index-e4w0sfm1.js} +2 -2
  288. package/dist/{index-g4gstmp1.js → index-ednf2cxs.js} +1 -1
  289. package/dist/{index-84tp547a.js → index-edpkm3k7.js} +29 -97
  290. package/dist/{index-gs0jw0hy.js → index-efbzm2se.js} +3 -3
  291. package/dist/{index-asnd4h2k.js → index-f0dzyskg.js} +27 -4
  292. package/dist/{index-xbb8ysmq.js → index-fatke81t.js} +2 -2
  293. package/dist/{index-d3s070eh.js → index-gj4wdts6.js} +1 -1
  294. package/dist/{index-6nzzj7qr.js → index-gq35s3bm.js} +1 -1
  295. package/dist/index-gvgtmt7a.js +102 -0
  296. package/dist/{index-pd9e8rz4.js → index-gvv7y0s4.js} +1 -1
  297. package/dist/{index-m2b49tvc.js → index-h08xqfw9.js} +20 -21
  298. package/dist/{index-gk6dq9ay.js → index-ha1tv70k.js} +3 -26
  299. package/dist/{index-vebzvse6.js → index-jy907kcs.js} +24 -1
  300. package/dist/{index-q86qnzzf.js → index-k5azb3v3.js} +8 -25
  301. package/dist/{index-qcy8et93.js → index-kaq9nb7h.js} +6 -6
  302. package/dist/{index-vse7x1qt.js → index-knqye3gv.js} +1 -1
  303. package/dist/{index-tav72wz5.js → index-ks4rhtcc.js} +5 -0
  304. package/dist/{index-bvpevwt6.js → index-mtpcax6d.js} +210 -205
  305. package/dist/{index-7qza24g1.js → index-px9r6wv1.js} +1 -1
  306. package/dist/{index-x6sp5vpa.js → index-q4tr9vnf.js} +1 -1
  307. package/dist/{index-hce3hbdg.js → index-qj0sq69b.js} +6 -2
  308. package/dist/{index-de7b0kvz.js → index-r9w7wfgn.js} +2 -2
  309. package/dist/{index-8vzh5wpv.js → index-rw1caff2.js} +14 -26
  310. package/dist/index-s8af9jqw.js +6 -0
  311. package/dist/{index-bgj9hbm3.js → index-sdppfbrh.js} +30 -16
  312. package/dist/{index-aacwkve4.js → index-sjq4akrx.js} +3 -5
  313. package/dist/{index-fec05c9k.js → index-ta0e2daw.js} +9 -7
  314. package/dist/{index-5dxgx3yj.js → index-tcv71frn.js} +1 -1
  315. package/dist/{index-1zy31r3b.js → index-v92djygb.js} +1 -1
  316. package/dist/{index-c0yym4a0.js → index-w7e402wx.js} +11 -105
  317. package/dist/{index-9f60gnfn.js → index-xaa3603f.js} +4 -11
  318. package/dist/index-xrbrvn15.js +147 -0
  319. package/dist/{index-ac3rfec5.js → index-y6wzzk2e.js} +21 -1
  320. package/dist/{index-3d2c45jn.js → index-yjx5jna7.js} +2 -2
  321. package/dist/{index-j3r7r1mh.js → index-yv7d6tav.js} +1 -1
  322. package/dist/{index-wsv11dhg.js → index-zagc12j1.js} +5 -5
  323. package/dist/{index-npfdymav.js → index-zqc64g69.js} +3 -3
  324. package/dist/{index-rkphknhx.js → index-zthekmrt.js} +2 -2
  325. package/dist/internal/json-stringify.d.ts +37 -0
  326. package/dist/internal/json-stringify.d.ts.map +1 -0
  327. package/dist/internal/loopback-host.d.ts +8 -0
  328. package/dist/internal/loopback-host.d.ts.map +1 -0
  329. package/dist/internal/own-member.d.ts +7 -0
  330. package/dist/internal/own-member.d.ts.map +1 -0
  331. package/dist/internal/request.d.ts +17 -8
  332. package/dist/internal/request.d.ts.map +1 -1
  333. package/dist/internal/secret-shapes.d.ts +33 -4
  334. package/dist/internal/secret-shapes.d.ts.map +1 -1
  335. package/dist/json-schema/dialect.d.ts.map +1 -1
  336. package/dist/json-schema/keywords.d.ts +25 -6
  337. package/dist/json-schema/keywords.d.ts.map +1 -1
  338. package/dist/json-schema/string-format.d.ts.map +1 -1
  339. package/dist/live/events.d.ts.map +1 -1
  340. package/dist/live/watch-client.d.ts.map +1 -1
  341. package/dist/live/watch-delta.d.ts.map +1 -1
  342. package/dist/observability/context.d.ts +4 -3
  343. package/dist/observability/context.d.ts.map +1 -1
  344. package/dist/observability/sanitize.d.ts.map +1 -1
  345. package/dist/observability/secret-values.d.ts +0 -9
  346. package/dist/observability/secret-values.d.ts.map +1 -1
  347. package/dist/server/context.d.ts +3 -2
  348. package/dist/server/context.d.ts.map +1 -1
  349. package/dist/server/error-hook.d.ts +4 -3
  350. package/dist/server/error-hook.d.ts.map +1 -1
  351. package/dist/server/event-bus.d.ts.map +1 -1
  352. package/dist/server/file.d.ts +11 -3
  353. package/dist/server/file.d.ts.map +1 -1
  354. package/dist/server/handler-state.d.ts +2 -2
  355. package/dist/server/handler-state.d.ts.map +1 -1
  356. package/dist/server/middleware/jwt.d.ts +12 -1
  357. package/dist/server/middleware/jwt.d.ts.map +1 -1
  358. package/dist/server/middleware/trust-fence.d.ts +4 -0
  359. package/dist/server/middleware/trust-fence.d.ts.map +1 -1
  360. package/dist/server/multipart.d.ts +2 -3
  361. package/dist/server/multipart.d.ts.map +1 -1
  362. package/dist/server/raw.d.ts.map +1 -1
  363. package/dist/server/request-body.d.ts +12 -1
  364. package/dist/server/request-body.d.ts.map +1 -1
  365. package/dist/server/request-completion.d.ts.map +1 -1
  366. package/dist/server/types.d.ts +14 -9
  367. package/dist/server/types.d.ts.map +1 -1
  368. package/dist/telegram/crypto.d.ts.map +1 -1
  369. package/dist/telegram/init-data.d.ts +4 -4
  370. package/dist/telegram/init-data.d.ts.map +1 -1
  371. package/dist/telegram/outbound-cost.d.ts.map +1 -1
  372. package/dist/telegram/screens/test-chat.d.ts.map +1 -1
  373. package/dist/telegram/widget-api.d.ts +85 -13
  374. package/dist/telegram/widget-api.d.ts.map +1 -1
  375. package/dist/telegram/widget.d.ts +46 -2
  376. package/dist/telegram/widget.d.ts.map +1 -1
  377. package/dist/tools/cli/args-classify.d.ts +4 -74
  378. package/dist/tools/cli/args-classify.d.ts.map +1 -1
  379. package/dist/tools/cli/args-framework.d.ts +79 -0
  380. package/dist/tools/cli/args-framework.d.ts.map +1 -0
  381. package/dist/tools/cli/args-scan.d.ts.map +1 -1
  382. package/dist/tools/cli/args-tokens.d.ts.map +1 -1
  383. package/dist/tools/cli/checkpoint.d.ts +5 -0
  384. package/dist/tools/cli/checkpoint.d.ts.map +1 -1
  385. package/dist/tools/cli/stream.d.ts.map +1 -1
  386. package/dist/tools/connections/foreign-schema-join.d.ts.map +1 -1
  387. package/dist/tools/connections/openapi.d.ts.map +1 -1
  388. package/dist/tools/connections/runtime.d.ts.map +1 -1
  389. package/dist/tools/execute-handler.d.ts +24 -0
  390. package/dist/tools/execute-handler.d.ts.map +1 -0
  391. package/dist/tools/execute.d.ts.map +1 -1
  392. package/dist/tools/mcp/round.d.ts.map +1 -1
  393. package/dist/tools/schema/coerce.d.ts.map +1 -1
  394. package/dist/tools/schema/flatten.d.ts.map +1 -1
  395. package/dist/tools/schema/inline-references.d.ts.map +1 -1
  396. package/dist/tools/schema/nesting-limit.d.ts.map +1 -1
  397. package/dist/tools/schema/presentation.d.ts.map +1 -1
  398. package/dist/tracking/privacy.d.ts.map +1 -1
  399. package/llms/agent-runtime-openrouter.txt +10 -9
  400. package/llms/agent-runtime-sandbox.txt +50 -11
  401. package/llms/agent-runtime-testing.txt +1 -1
  402. package/llms/agent-runtime.2.txt +9 -6
  403. package/llms/agent-runtime.3.txt +2 -2
  404. package/llms/agent-runtime.4.txt +11 -5
  405. package/llms/agent-runtime.5.txt +2 -2
  406. package/llms/agent-runtime.txt +297 -36
  407. package/llms/application.2.txt +6 -3
  408. package/llms/application.3.txt +2 -1
  409. package/llms/application.txt +7 -2
  410. package/llms/http.txt +1 -1
  411. package/llms/live.txt +3 -1
  412. package/llms/observability.txt +16 -9
  413. package/llms/server.2.txt +13 -8
  414. package/llms/server.4.txt +23 -11
  415. package/llms/server.5.txt +5 -5
  416. package/llms/server.txt +54 -1
  417. package/llms/spend.txt +1 -0
  418. package/llms/stitchkit.2.txt +4 -2
  419. package/llms/stitchkit.txt +113 -93
  420. package/llms/telegram-grammy.txt +3 -2
  421. package/llms/telegram.2.txt +3 -1
  422. package/llms/telegram.txt +35 -10
  423. package/llms/upgrading-0.128.0-0.129.0.txt +175 -0
  424. package/llms/{upgrading-0.128.0-0.135.0.txt → upgrading-0.130.0-0.136.0.txt} +353 -169
  425. package/llms/upgrading.txt +2 -1
  426. package/llms-full.txt +1021 -223
  427. package/llms.txt +14 -13
  428. package/package.json +6 -6
  429. package/dist/agent-runtime/loop/deferred-tools-internal.d.ts +0 -19
  430. package/dist/agent-runtime/loop/deferred-tools-internal.d.ts.map +0 -1
  431. package/dist/agent-runtime/loop/run-complete-retry.d.ts +0 -24
  432. package/dist/agent-runtime/loop/run-complete-retry.d.ts.map +0 -1
  433. package/dist/agent-runtime/loop/run-model-attempts.d.ts +0 -6
  434. package/dist/agent-runtime/loop/run-model-attempts.d.ts.map +0 -1
  435. package/dist/index-sznqf8fx.js +0 -20
  436. /package/dist/{index-fthw8dwa.js → index-4gbybjg6.js} +0 -0
@@ -1,28 +1,29 @@
1
1
  import {
2
2
  AgentToolModelOutputSchema2,
3
+ AgentRecordedToolModelOutputSchema,
3
4
  normalizeAgentInstructions,
4
5
  AgentModelMessageSchema2,
5
6
  createAgentGeneratedFile
6
- } from "./index-vebzvse6.js";
7
+ } from "./index-jy907kcs.js";
7
8
  import {
8
9
  AgentMessagePartSchema2
9
- } from "./index-tav72wz5.js";
10
+ } from "./index-ks4rhtcc.js";
10
11
  import {
11
12
  AgentRecordIdSchema2,
12
13
  AgentMessageSchema2,
13
14
  AgentAssistantPlaceholderSchema2,
14
15
  AgentProvenanceSchema2,
15
16
  AgentUsageSchema2
16
- } from "./index-j3r7r1mh.js";
17
+ } from "./index-yv7d6tav.js";
17
18
  import {
18
19
  AgentProviderResponseSchema2
19
- } from "./index-7qza24g1.js";
20
+ } from "./index-px9r6wv1.js";
20
21
  import {
21
22
  AgentRunOperationSchema2,
22
23
  runStateForTerminalReason2,
23
24
  AgentRunSchema2,
24
25
  AgentSnapshotSchema2
25
- } from "./index-pd9e8rz4.js";
26
+ } from "./index-gvv7y0s4.js";
26
27
  import {
27
28
  InvocationPayloadSchema,
28
29
  InvocationExpiredPayloadSchema,
@@ -41,11 +42,21 @@ import {
41
42
  canonicalAgentJson2,
42
43
  issueRunContext,
43
44
  isActiveRunState
44
- } from "./index-qcy8et93.js";
45
+ } from "./index-kaq9nb7h.js";
45
46
  import {
46
47
  ToolExecutionControlError2,
47
48
  isToolExecutionControlError2
48
- } from "./index-d4at0q09.js";
49
+ } from "./index-b9mj31q7.js";
50
+ import {
51
+ AGENT_TOOL_PROGRESS_MESSAGE_MAX2,
52
+ agentDurableEventId2
53
+ } from "./index-4q9tmzea.js";
54
+ import {
55
+ contractOperationEffects2
56
+ } from "./index-werjqesf.js";
57
+ import {
58
+ createLocalStepDurability2
59
+ } from "./index-xrsryvd2.js";
49
60
  import {
50
61
  withStoreRetries,
51
62
  AgentRuntimeConflictError2,
@@ -55,23 +66,17 @@ import {
55
66
  terminalOfRunView,
56
67
  commitAgentRunTerminal,
57
68
  findRun,
58
- jsonValue,
59
69
  providerResponseIdentity,
60
70
  abortTerminalReason,
61
71
  addUsage,
62
72
  mergeModelTotals,
63
73
  createIdleDeadline
64
- } from "./index-9f60gnfn.js";
65
- import {
66
- AGENT_TOOL_PROGRESS_MESSAGE_MAX2,
67
- agentDurableEventId2
68
- } from "./index-grhhsrd5.js";
74
+ } from "./index-xaa3603f.js";
69
75
  import {
70
- contractOperationEffects2
71
- } from "./index-werjqesf.js";
72
- import {
73
- createLocalStepDurability2
74
- } from "./index-xrsryvd2.js";
76
+ describeJsonRefusal,
77
+ projectJson,
78
+ recordedJson
79
+ } from "./index-a1rjr381.js";
75
80
  import {
76
81
  createToolChronology,
77
82
  advanceToolChronology,
@@ -85,18 +90,23 @@ import {
85
90
  AgentProviderStreamCutError2,
86
91
  classifyProviderFailure2,
87
92
  isToolResultFailure2
88
- } from "./index-vse7x1qt.js";
93
+ } from "./index-knqye3gv.js";
89
94
  import {
90
95
  listContractToolNames2
91
- } from "./index-xbb8ysmq.js";
96
+ } from "./index-fatke81t.js";
92
97
  import {
93
- AgentToolError2,
94
- isAgentToolError2,
95
98
  finalizeAgentToolOutput
96
- } from "./index-q86qnzzf.js";
99
+ } from "./index-k5azb3v3.js";
100
+ import {
101
+ AgentToolError2,
102
+ isAgentToolError2
103
+ } from "./index-1psbyyhj.js";
97
104
  import {
98
105
  createMutationQueue
99
106
  } from "./index-sykb5ag7.js";
107
+ import {
108
+ setOwnMember
109
+ } from "./index-3tb82xr7.js";
100
110
  import {
101
111
  serializeCanonicalJson
102
112
  } from "./index-fmzg39a8.js";
@@ -108,6 +118,9 @@ import {
108
118
  assertTimerMs,
109
119
  withDeadline
110
120
  } from "./index-e1y74yra.js";
121
+ import {
122
+ sleep
123
+ } from "./index-h20qcyh5.js";
111
124
  import {
112
125
  raceAbort,
113
126
  linkAbortSignals
@@ -151,6 +164,40 @@ function statedUsage(usage) {
151
164
  };
152
165
  }
153
166
 
167
+ // src/agent-runtime/schemas-json-projection.ts
168
+ function projectToolOutput(toolName, output, what = "output") {
169
+ const projected = projectJson(output);
170
+ if (projected.ok)
171
+ return projected.value;
172
+ throw new AgentToolError2({
173
+ message: `Tool "${toolName}" ran, but its ${what} cannot be sent as JSON: ${describeJsonRefusal(projected.refusal)}`
174
+ });
175
+ }
176
+ function projectModelOutput(toolName, output) {
177
+ if (output.type !== "json" && output.type !== "error-json")
178
+ return output;
179
+ return {
180
+ ...output,
181
+ value: projectToolOutput(toolName, output.value, "toModelOutput value")
182
+ };
183
+ }
184
+ function defaultToolWireOutput(output) {
185
+ if (typeof output === "string")
186
+ return { type: "text", value: output };
187
+ return { type: "json", value: output };
188
+ }
189
+ function recordedModelOutput(output) {
190
+ const json = projectJson(output);
191
+ if (!json.ok)
192
+ return;
193
+ const parsed = AgentRecordedToolModelOutputSchema.safeParse(json.value);
194
+ return parsed.success ? parsed.data : undefined;
195
+ }
196
+ function agentToolErrorDetail(error) {
197
+ const detail = projectJson(error.output);
198
+ return detail.ok ? detail.value : { message: error.message };
199
+ }
200
+
154
201
  // src/agent-runtime/history/run-history-parts.ts
155
202
  var INTERRUPTION_NOTE = "[interrupted: this turn was cut off before it finished]";
156
203
  var FAILURE_NOTE = "[failed: partial evidence from a run that did not complete successfully]";
@@ -210,20 +257,24 @@ async function projectToolResultOutput(part, callInput, options) {
210
257
  output: part.output,
211
258
  outcome: part.outcome
212
259
  });
213
- if (resolved !== undefined)
214
- return AgentToolModelOutputSchema2.parse(resolved);
260
+ if (resolved !== undefined) {
261
+ return AgentToolModelOutputSchema2.parse(projectModelOutput(part.toolName, resolved));
262
+ }
215
263
  }
264
+ if (part.outcome === "success" && part.modelOutput)
265
+ return part.modelOutput;
216
266
  if (part.outcome === "success" && options.tools && Object.hasOwn(options.tools, part.toolName)) {
217
267
  const tool = options.tools[part.toolName];
218
268
  if (tool?.toModelOutput) {
219
- return AgentToolModelOutputSchema2.parse(await tool.toModelOutput({
269
+ const output = await tool.toModelOutput({
220
270
  toolCallId: part.callId,
221
271
  input: callInput,
222
272
  output: part.output
223
- }));
273
+ });
274
+ return AgentToolModelOutputSchema2.parse(projectModelOutput(part.toolName, output));
224
275
  }
225
276
  }
226
- return part.outcome === "success" ? { type: "json", value: part.output ?? null } : { type: "error-json", value: part.output ?? { message: part.outcome } };
277
+ return part.outcome === "success" ? defaultToolWireOutput(part.output ?? null) : { type: "error-json", value: part.output ?? { message: part.outcome } };
227
278
  }
228
279
  async function projectAssistantMessages(message, marker, options, callInputsById) {
229
280
  const rendered = new Set;
@@ -565,85 +616,6 @@ function createAgentSessionCoordinator2() {
565
616
  };
566
617
  }
567
618
 
568
- // src/agent-runtime/loop/deferred-tools-internal.ts
569
- var DEFERRED_REPAIR_SYMBOL = Symbol.for("stitchkit.agent-runtime.deferred-repair");
570
- var DEFERRED_REPAIR_BASE_SYMBOL = Symbol.for("stitchkit.agent-runtime.deferred-repair-base");
571
- var DEFERRED_CATALOG_SYMBOL = Symbol.for("stitchkit.agent-runtime.deferred-catalog");
572
- function registerDeferredToolRepair(tools, repair, searchName) {
573
- Object.defineProperty(tools, DEFERRED_REPAIR_SYMBOL, {
574
- value: repair,
575
- enumerable: false,
576
- configurable: true
577
- });
578
- if (searchName !== undefined) {
579
- const search = tools[searchName];
580
- if (search && typeof search === "object") {
581
- Object.defineProperty(search, DEFERRED_REPAIR_SYMBOL, {
582
- value: repair,
583
- enumerable: false,
584
- configurable: true
585
- });
586
- }
587
- }
588
- }
589
- function deferredToolRepair(tools) {
590
- if (!tools)
591
- return;
592
- const direct = Reflect.get(tools, DEFERRED_REPAIR_SYMBOL);
593
- if (typeof direct === "function")
594
- return direct;
595
- for (const tool of Object.values(tools)) {
596
- if (tool && typeof tool === "object") {
597
- const candidate = Reflect.get(tool, DEFERRED_REPAIR_SYMBOL);
598
- if (typeof candidate === "function")
599
- return candidate;
600
- }
601
- }
602
- return;
603
- }
604
- function markDeferredRepairWrapper(wrapper, base) {
605
- Object.defineProperty(wrapper, DEFERRED_REPAIR_BASE_SYMBOL, {
606
- value: base,
607
- enumerable: false,
608
- configurable: true
609
- });
610
- return wrapper;
611
- }
612
- function chainRepairHooks(primary, secondary) {
613
- if (!primary)
614
- return secondary;
615
- if (!secondary)
616
- return primary;
617
- if (primary === secondary || Reflect.get(primary, DEFERRED_REPAIR_BASE_SYMBOL) === secondary) {
618
- return primary;
619
- }
620
- return async (input) => await primary(input) ?? secondary(input);
621
- }
622
- function registerDeferredToolCatalog(tools, searchName, names) {
623
- const search = tools[searchName];
624
- if (search && typeof search === "object") {
625
- Object.defineProperty(search, DEFERRED_CATALOG_SYMBOL, {
626
- value: names,
627
- enumerable: false,
628
- configurable: true
629
- });
630
- }
631
- }
632
- function deferredToolCatalog(tools, searchName) {
633
- const search = tools[searchName];
634
- if (!search || typeof search !== "object")
635
- return;
636
- const candidate = Reflect.get(search, DEFERRED_CATALOG_SYMBOL);
637
- return candidate instanceof Set ? candidate : undefined;
638
- }
639
- function repairedSearchCall(toolCall, searchName) {
640
- return {
641
- ...toolCall,
642
- toolName: searchName,
643
- input: JSON.stringify({ query: toolCall.toolName, reason: "inactive_call" })
644
- };
645
- }
646
-
647
619
  // src/agent-runtime/loop/invocation-attempt.ts
648
620
  import { AsyncLocalStorage } from "node:async_hooks";
649
621
  import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
@@ -727,7 +699,7 @@ function walkInvocationJson(value, ancestors, errors) {
727
699
  if (entry === undefined || typeof entry === "function" || typeof entry === "symbol") {
728
700
  continue;
729
701
  }
730
- out[key] = walkInvocationJson(entry, ancestors, errors);
702
+ setOwnMember(out, key, walkInvocationJson(entry, ancestors, errors));
731
703
  }
732
704
  return out;
733
705
  } finally {
@@ -1137,7 +1109,7 @@ function streamEvidence(limit) {
1137
1109
  // src/agent-runtime/loop/invocations.ts
1138
1110
  import { randomUUID as randomUUID3 } from "node:crypto";
1139
1111
  import { hostname } from "node:os";
1140
- import { z as z4 } from "zod";
1112
+ import { z as z3 } from "zod";
1141
1113
 
1142
1114
  // src/agent-runtime/loop/invocation-read.ts
1143
1115
  import { z as z2 } from "zod";
@@ -1258,7 +1230,6 @@ async function* ownedProviderStream(input) {
1258
1230
  }
1259
1231
 
1260
1232
  // src/agent-runtime/loop/provider-stream-segments.ts
1261
- import { z as z3 } from "zod";
1262
1233
  var MAX_CHUNK_TIMESTAMPS = 32768;
1263
1234
  function parseProviderToolInput(raw) {
1264
1235
  const trimmed = raw.trim();
@@ -1270,10 +1241,6 @@ function parseProviderToolInput(raw) {
1270
1241
  return raw;
1271
1242
  }
1272
1243
  }
1273
- function safeJsonValue(value) {
1274
- const parsed = z3.json().safeParse(value);
1275
- return parsed.success ? parsed.data : { message: "Non-JSON tool output omitted" };
1276
- }
1277
1244
  function toProviderToolError(result) {
1278
1245
  if (isAgentToolError2(result))
1279
1246
  return result;
@@ -1375,6 +1342,9 @@ function ensureTextSegment(acc, id, provider) {
1375
1342
  }
1376
1343
 
1377
1344
  // src/agent-runtime/loop/provider-stream-parts.ts
1345
+ function providerToolActed(part) {
1346
+ return part.type === "tool-call" && part.providerExecuted === true || part.type === "tool-result";
1347
+ }
1378
1348
  async function handleProviderToolResult(result, part, emit) {
1379
1349
  const matchingCall = result.rawToolCalls.find((call) => call.toolCallId === part.toolCallId);
1380
1350
  const matchingInput = matchingCall ? parseProviderToolInput(matchingCall.input) : {};
@@ -1405,7 +1375,7 @@ async function handleProviderToolResult(result, part, emit) {
1405
1375
  type: "tool-result",
1406
1376
  toolCallId: part.toolCallId,
1407
1377
  toolName: part.toolName,
1408
- output: { type: "error-json", value: safeJsonValue(part.result ?? null) },
1378
+ output: { type: "error-json", value: agentToolErrorDetail(providerError) },
1409
1379
  ...providerOptions && { providerOptions }
1410
1380
  },
1411
1381
  stepPart: {
@@ -1418,12 +1388,14 @@ async function handleProviderToolResult(result, part, emit) {
1418
1388
  });
1419
1389
  return;
1420
1390
  }
1391
+ const recorded = recordedJson(part.result);
1421
1392
  await emit({
1422
1393
  type: "tool-result",
1423
1394
  toolCallId: part.toolCallId,
1424
1395
  toolName: part.toolName,
1425
1396
  input: matchingInput,
1426
1397
  output: part.result,
1398
+ recorded,
1427
1399
  ...part.preliminary !== undefined && { preliminary: part.preliminary },
1428
1400
  ...part.provider && { provider: part.provider }
1429
1401
  });
@@ -1444,7 +1416,7 @@ async function handleProviderToolResult(result, part, emit) {
1444
1416
  type: "tool-result",
1445
1417
  toolCallId: part.toolCallId,
1446
1418
  toolName: part.toolName,
1447
- output: { type: "json", value: safeJsonValue(part.result ?? null) },
1419
+ output: { type: "json", value: recorded },
1448
1420
  ...providerOptions && { providerOptions }
1449
1421
  },
1450
1422
  stepPart: stepResult
@@ -1743,37 +1715,43 @@ async function consumeStandaloneDriverStream(input) {
1743
1715
  };
1744
1716
  let errorPart;
1745
1717
  let sawError = false;
1746
- for await (const part of ownedProviderStream({
1747
- stream: markProviderParts(input.modelStream.parts),
1748
- abort: input.abortAttempt,
1749
- onCleanupFailure: input.onCleanupFailure ?? (() => {
1750
- return;
1751
- })
1752
- })) {
1753
- input.onChunk?.();
1754
- if (sawError) {
1755
- if (part.type === "finish") {
1756
- await handleStreamPart(acc, part, noopEmit, async () => false);
1757
- }
1758
- continue;
1759
- }
1760
- if (part.type === "error") {
1761
- if (input.captureErrorUsage) {
1762
- sawError = true;
1763
- errorPart = part.error;
1764
- acc.result.sawErrorPart = true;
1718
+ try {
1719
+ for await (const part of ownedProviderStream({
1720
+ stream: markProviderParts(input.modelStream.parts),
1721
+ abort: input.abortAttempt,
1722
+ onCleanupFailure: input.onCleanupFailure ?? (() => {
1723
+ return;
1724
+ })
1725
+ })) {
1726
+ input.onChunk?.();
1727
+ input.onProviderPart?.(part);
1728
+ if (sawError) {
1729
+ if (part.type === "finish") {
1730
+ await handleStreamPart(acc, part, noopEmit, async () => false);
1731
+ }
1765
1732
  continue;
1766
1733
  }
1767
- throw markProviderOrigin(part.error);
1768
- }
1769
- if (part.type === "tool-call") {
1770
- if (part.providerExecuted === true) {
1771
- await input.onPart?.({ ...part, input: parseProviderToolInput(part.input) });
1734
+ if (part.type === "error") {
1735
+ if (input.captureErrorUsage) {
1736
+ sawError = true;
1737
+ errorPart = part.error;
1738
+ acc.result.sawErrorPart = true;
1739
+ continue;
1740
+ }
1741
+ throw markProviderOrigin(part.error);
1742
+ }
1743
+ if (part.type === "tool-call") {
1744
+ if (part.providerExecuted === true) {
1745
+ await input.onPart?.({ ...part, input: parseProviderToolInput(part.input) });
1746
+ }
1747
+ } else if (part.type !== "finish") {
1748
+ await input.onPart?.(part);
1772
1749
  }
1773
- } else if (part.type !== "finish") {
1774
- await input.onPart?.(part);
1750
+ await handleStreamPart(acc, part, noopEmit, async () => false);
1775
1751
  }
1776
- await handleStreamPart(acc, part, noopEmit, async () => false);
1752
+ } catch (error) {
1753
+ if (!sawError || input.signal?.aborted || !hasProviderOrigin(error))
1754
+ throw error;
1777
1755
  }
1778
1756
  return sawError ? { ...acc.result, errorPart } : acc.result;
1779
1757
  }
@@ -1899,7 +1877,7 @@ function createModelInvocationLedger2(config) {
1899
1877
  const appendOnce = store.appendEventOnce?.bind(store);
1900
1878
  if (!appendOnce)
1901
1879
  throw new TypeError("Model invocations require atomic store.appendEventOnce");
1902
- const maxPayloadBytes = z4.int().min(1024).max(64 * 1024 * 1024).parse(config.maxPayloadBytes ?? 4 * 1024 * 1024);
1880
+ const maxPayloadBytes = z3.int().min(1024).max(64 * 1024 * 1024).parse(config.maxPayloadBytes ?? 4 * 1024 * 1024);
1903
1881
  const payloads = createInvocationPayloads(store, config.payloadKey, maxPayloadBytes);
1904
1882
  const authorize = async (input) => InvocationCallerSchema.parse(await config.authorize(input));
1905
1883
  const start = async (input) => {
@@ -2047,8 +2025,8 @@ function createAgentToolFenceLifecycle2(config) {
2047
2025
  }
2048
2026
 
2049
2027
  // src/agent-runtime/providers/models-driver-telemetry.ts
2050
- import { z as z5 } from "zod";
2051
- var AgentModelFinishReasonSchema = z5.enum([
2028
+ import { z as z4 } from "zod";
2029
+ var AgentModelFinishReasonSchema = z4.enum([
2052
2030
  "stop",
2053
2031
  "length",
2054
2032
  "tool-calls",
@@ -2057,29 +2035,29 @@ var AgentModelFinishReasonSchema = z5.enum([
2057
2035
  "interrupted",
2058
2036
  "other"
2059
2037
  ]);
2060
- var AgentModelCostDetailsSchema = z5.strictObject({
2061
- promptCostUsd: z5.number().nonnegative().optional(),
2062
- outputCostUsd: z5.number().nonnegative().optional(),
2063
- isByok: z5.boolean().optional()
2038
+ var AgentModelCostDetailsSchema = z4.strictObject({
2039
+ promptCostUsd: z4.number().nonnegative().optional(),
2040
+ outputCostUsd: z4.number().nonnegative().optional(),
2041
+ isByok: z4.boolean().optional()
2064
2042
  });
2065
- var AgentStepChunkIntervalsSchema = z5.strictObject({
2066
- min: z5.number().nonnegative(),
2067
- p10: z5.number().nonnegative(),
2068
- median: z5.number().nonnegative(),
2069
- avg: z5.number().nonnegative(),
2070
- p90: z5.number().nonnegative(),
2071
- max: z5.number().nonnegative()
2043
+ var AgentStepChunkIntervalsSchema = z4.strictObject({
2044
+ min: z4.number().nonnegative(),
2045
+ p10: z4.number().nonnegative(),
2046
+ median: z4.number().nonnegative(),
2047
+ avg: z4.number().nonnegative(),
2048
+ p90: z4.number().nonnegative(),
2049
+ max: z4.number().nonnegative()
2072
2050
  });
2073
- var AgentStepTimingsSchema = z5.strictObject({
2074
- stepTimeMs: z5.number().nonnegative(),
2075
- responseTimeMs: z5.number().nonnegative(),
2076
- toolExecutionMs: z5.number().nonnegative(),
2077
- ttftMs: z5.number().nonnegative().optional(),
2051
+ var AgentStepTimingsSchema = z4.strictObject({
2052
+ stepTimeMs: z4.number().nonnegative(),
2053
+ responseTimeMs: z4.number().nonnegative(),
2054
+ toolExecutionMs: z4.number().nonnegative(),
2055
+ ttftMs: z4.number().nonnegative().optional(),
2078
2056
  chunkIntervalsMs: AgentStepChunkIntervalsSchema.optional()
2079
2057
  });
2080
2058
 
2081
2059
  // src/agent-runtime/loop/run-step-spend.ts
2082
- import { z as z6 } from "zod";
2060
+ import { z as z5 } from "zod";
2083
2061
 
2084
2062
  // src/agent-runtime/loop/run-execution-state.ts
2085
2063
  function adoptSnapshot(state, next) {
@@ -2216,34 +2194,34 @@ function checkpoint(execution, toolStatus) {
2216
2194
 
2217
2195
  // src/agent-runtime/loop/run-step-spend.ts
2218
2196
  var DEFAULT_STEP_SPEND_TIMEOUT_MS = 5000;
2219
- var AgentStepSpendPhaseSchema2 = z6.enum(["step", "abandoned-attempt", "compaction"]);
2220
- var AgentStepSpendProviderSchema = z6.strictObject({
2221
- key: z6.string().min(1),
2222
- upstream: z6.string().min(1).optional()
2197
+ var AgentStepSpendPhaseSchema2 = z5.enum(["step", "abandoned-attempt", "compaction"]);
2198
+ var AgentStepSpendProviderSchema = z5.strictObject({
2199
+ key: z5.string().min(1),
2200
+ upstream: z5.string().min(1).optional()
2223
2201
  });
2224
2202
  var StepSpendBaseShape = {
2225
2203
  conversationId: AgentRecordIdSchema2,
2226
2204
  runId: AgentRecordIdSchema2,
2227
- step: z6.int().nonnegative(),
2228
- attempt: z6.int().nonnegative(),
2205
+ step: z5.int().nonnegative(),
2206
+ attempt: z5.int().nonnegative(),
2229
2207
  usage: AgentUsageSchema2,
2230
2208
  trace: ModelInvocationTraceSchema2.optional()
2231
2209
  };
2232
2210
  var ModelStepSpendShape = {
2233
2211
  ...StepSpendBaseShape,
2234
- model: z6.string().min(1),
2212
+ model: z5.string().min(1),
2235
2213
  provider: AgentStepSpendProviderSchema,
2236
2214
  response: AgentProviderResponseSchema2,
2237
2215
  finishReason: AgentModelFinishReasonSchema.optional(),
2238
- rawFinishReason: z6.string().min(1).optional(),
2239
- toolCallCount: z6.int().nonnegative().optional(),
2216
+ rawFinishReason: z5.string().min(1).optional(),
2217
+ toolCallCount: z5.int().nonnegative().optional(),
2240
2218
  costDetails: AgentModelCostDetailsSchema.optional(),
2241
2219
  timings: AgentStepTimingsSchema.optional()
2242
2220
  };
2243
- var AgentStepSpendSchema2 = z6.discriminatedUnion("phase", [
2244
- z6.strictObject({ ...ModelStepSpendShape, phase: z6.literal("step") }),
2245
- z6.strictObject({ ...ModelStepSpendShape, phase: z6.literal("abandoned-attempt") }),
2246
- z6.strictObject({ ...StepSpendBaseShape, phase: z6.literal("compaction") })
2221
+ var AgentStepSpendSchema2 = z5.discriminatedUnion("phase", [
2222
+ z5.strictObject({ ...ModelStepSpendShape, phase: z5.literal("step") }),
2223
+ z5.strictObject({ ...ModelStepSpendShape, phase: z5.literal("abandoned-attempt") }),
2224
+ z5.strictObject({ ...StepSpendBaseShape, phase: z5.literal("compaction") })
2247
2225
  ]);
2248
2226
  async function callStepSpendHook(name, timeoutMs, call) {
2249
2227
  let pending;
@@ -2411,29 +2389,7 @@ async function recordAgentRetryDecision2(input) {
2411
2389
  return decision;
2412
2390
  }
2413
2391
 
2414
- // src/agent-runtime/loop/run-approval.ts
2415
- class AgentToolApprovalError2 extends Error {
2416
- reason;
2417
- constructor(message, options) {
2418
- super(message, options?.cause !== undefined ? { cause: options.cause } : undefined);
2419
- this.name = "AgentToolApprovalError";
2420
- this.reason = options?.reason ?? "input-validation-failed";
2421
- }
2422
- }
2423
-
2424
- class AgentInvalidToolApprovalSignatureError2 extends AgentToolApprovalError2 {
2425
- constructor(approvalId, detail = "Invalid or missing tool approval signature") {
2426
- super(`${detail} for approval "${approvalId}"`, { reason: "invalid-signature" });
2427
- this.name = "AgentInvalidToolApprovalSignatureError";
2428
- }
2429
- }
2430
-
2431
- class AgentToolCallNotFoundForApprovalError2 extends AgentToolApprovalError2 {
2432
- constructor(approvalId) {
2433
- super(`Tool call not found for approval "${approvalId}"`, { reason: "call-not-found" });
2434
- this.name = "AgentToolCallNotFoundForApprovalError";
2435
- }
2436
- }
2392
+ // src/agent-runtime/loop/run-approval-signature.ts
2437
2393
  var encoder = new TextEncoder;
2438
2394
  function assertToolApprovalSecret(secret) {
2439
2395
  if (secret === undefined)
@@ -2453,14 +2409,7 @@ function assertToolApprovalSecret(secret) {
2453
2409
  throw new TypeError("loop.toolApprovalSecret must be a non-empty string or Uint8Array");
2454
2410
  }
2455
2411
  function normalizePersistedToolInput(value) {
2456
- if (value === undefined)
2457
- return null;
2458
- try {
2459
- const serialized = JSON.stringify(value);
2460
- if (serialized !== undefined)
2461
- return jsonValue(JSON.parse(serialized));
2462
- } catch {}
2463
- return jsonValue(value);
2412
+ return recordedJson(value);
2464
2413
  }
2465
2414
  function bytesToBase64Url(bytes) {
2466
2415
  let binary = "";
@@ -2567,6 +2516,30 @@ async function verifyToolApprovalSignature(input) {
2567
2516
  return false;
2568
2517
  return crypto.subtle.verify("HMAC", key, sigCopy, new Uint8Array(legacy));
2569
2518
  }
2519
+
2520
+ // src/agent-runtime/loop/run-approval.ts
2521
+ class AgentToolApprovalError2 extends Error {
2522
+ reason;
2523
+ constructor(message, options) {
2524
+ super(message, options?.cause !== undefined ? { cause: options.cause } : undefined);
2525
+ this.name = "AgentToolApprovalError";
2526
+ this.reason = options?.reason ?? "input-validation-failed";
2527
+ }
2528
+ }
2529
+
2530
+ class AgentInvalidToolApprovalSignatureError2 extends AgentToolApprovalError2 {
2531
+ constructor(approvalId, detail = "Invalid or missing tool approval signature") {
2532
+ super(`${detail} for approval "${approvalId}"`, { reason: "invalid-signature" });
2533
+ this.name = "AgentInvalidToolApprovalSignatureError";
2534
+ }
2535
+ }
2536
+
2537
+ class AgentToolCallNotFoundForApprovalError2 extends AgentToolApprovalError2 {
2538
+ constructor(approvalId) {
2539
+ super(`Tool call not found for approval "${approvalId}"`, { reason: "call-not-found" });
2540
+ this.name = "AgentToolCallNotFoundForApprovalError";
2541
+ }
2542
+ }
2570
2543
  var APPROVAL_DECISION_TYPES = new Set([
2571
2544
  "approved",
2572
2545
  "denied",
@@ -2764,261 +2737,81 @@ async function collectApprovalContinuations(input) {
2764
2737
  return resolved.map((entry) => entry.item);
2765
2738
  }
2766
2739
 
2767
- // src/agent-runtime/loop/run-step-barriers.ts
2768
- class AgentStepBarrierError2 extends Error {
2769
- bound;
2770
- action;
2771
- constructor(bound, message, action = "abort") {
2772
- super(message);
2773
- this.bound = bound;
2774
- this.action = action;
2775
- this.name = "AgentStepBarrierError";
2740
+ // src/agent-runtime/loop/run-model-messages.ts
2741
+ function buildStepResponseMessages(consumed, toolExecution) {
2742
+ const assistantContent = [];
2743
+ for (const segment of consumed.segments) {
2744
+ if (segment.kind === "reasoning") {
2745
+ if (segment.text.length === 0 && segment.provider === undefined)
2746
+ continue;
2747
+ const options = envelopeToProviderOptions(segment.provider);
2748
+ assistantContent.push({
2749
+ type: "reasoning",
2750
+ text: segment.text,
2751
+ ...options && { providerOptions: options }
2752
+ });
2753
+ } else if (segment.kind === "text") {
2754
+ if (segment.text.length === 0 && segment.provider === undefined)
2755
+ continue;
2756
+ const options = envelopeToProviderOptions(segment.provider);
2757
+ assistantContent.push({
2758
+ type: "text",
2759
+ text: segment.text,
2760
+ ...options && { providerOptions: options }
2761
+ });
2762
+ } else if (segment.assistantPart !== undefined) {
2763
+ assistantContent.push(segment.assistantPart);
2764
+ }
2776
2765
  }
2777
- }
2778
- function assertStepBarriers(barriers) {
2779
- if (!barriers)
2780
- return;
2781
- assertPositiveSafeInteger("stepBarriers.maxToolCallsPerStep", barriers.maxToolCallsPerStep, RangeError);
2782
- assertPositiveSafeInteger("stepBarriers.maxReasoningCharsPerStep", barriers.maxReasoningCharsPerStep, RangeError);
2783
- if (barriers.onMaxReasoningChars !== undefined && !["abort", "finish-length"].includes(barriers.onMaxReasoningChars))
2784
- throw new RangeError("stepBarriers.onMaxReasoningChars must be 'abort' or 'finish-length'");
2785
- if (barriers.stepText !== undefined && !["immediate", "after-tools"].includes(barriers.stepText))
2786
- throw new RangeError("stepBarriers.stepText must be 'immediate' or 'after-tools'");
2787
- if (barriers.stepTextOnInterrupt !== undefined && !["drop", "flush"].includes(barriers.stepTextOnInterrupt))
2788
- throw new RangeError("stepBarriers.stepTextOnInterrupt must be 'drop' or 'flush'");
2789
- if (barriers.onPredecessorFailure !== undefined && !["run", "refuse"].includes(barriers.onPredecessorFailure))
2790
- throw new RangeError("stepBarriers.onPredecessorFailure must be 'run' or 'refuse'");
2791
- }
2792
- var RUNTIME_ONLY_STEP_BARRIER_KEYS = [
2793
- "stepText",
2794
- "maxReasoningCharsPerStep",
2795
- "onMaxReasoningChars",
2796
- "stepTextOnInterrupt",
2797
- "filterStepText"
2798
- ];
2799
- function assertStandaloneStepBarriers(barriers) {
2800
- if (barriers === undefined)
2801
- return;
2802
- if (typeof barriers !== "object" || barriers === null) {
2803
- throw new TypeError("stepBarriers must be an object");
2766
+ assistantContent.push(...toolExecution.assistantParts);
2767
+ const stepResponseMessages = [];
2768
+ if (assistantContent.length > 0) {
2769
+ stepResponseMessages.push({ role: "assistant", content: assistantContent });
2804
2770
  }
2805
- for (const key of RUNTIME_ONLY_STEP_BARRIER_KEYS) {
2806
- if (Object.hasOwn(barriers, key) && Reflect.get(barriers, key) !== undefined) {
2807
- throw new TypeError(`stepBarriers.${key} is only supported by createAgentRuntime, not standalone completion`);
2771
+ if (toolExecution.toolParts.length > 0) {
2772
+ stepResponseMessages.push({ role: "tool", content: toolExecution.toolParts });
2773
+ }
2774
+ return stepResponseMessages;
2775
+ }
2776
+ function buildStepContent(consumed, toolExecution) {
2777
+ const content = [];
2778
+ for (const segment of consumed.segments) {
2779
+ if (segment.kind === "reasoning") {
2780
+ if (segment.text.length > 0 || segment.provider !== undefined) {
2781
+ content.push({ type: "reasoning", text: segment.text });
2782
+ }
2783
+ } else if (segment.kind === "text") {
2784
+ if (segment.text.length > 0) {
2785
+ content.push({ type: "text", text: segment.text });
2786
+ }
2787
+ } else if (segment.stepPart !== undefined) {
2788
+ content.push(segment.stepPart);
2808
2789
  }
2809
2790
  }
2810
- assertStepBarriers(barriers);
2791
+ content.push(...toolExecution.stepContent);
2792
+ return content;
2811
2793
  }
2812
- function stepToolCallLimitRefusal(limit) {
2813
- return new AgentToolError2({
2814
- code: "STEP_TOOL_CALL_LIMIT",
2815
- message: `Refused: a step may make at most ${limit} tool calls; make the rest in the next step`
2816
- });
2817
- }
2818
- function createStepCallScheduler(barriers) {
2819
- let count = 0;
2820
- const entities = new Map;
2821
- const limit = barriers?.maxToolCallsPerStep;
2822
- const stateOf = (entity) => {
2823
- const known = entities.get(entity);
2824
- if (known)
2825
- return known;
2826
- const fresh = { reads: [] };
2827
- entities.set(entity, fresh);
2828
- return fresh;
2829
- };
2830
- const registerDependencies = (dependencies, ownPromise) => {
2831
- const writes = new Set(dependencies.writes ?? []);
2832
- const reads = new Set([...dependencies.reads ?? []].filter((entity) => !writes.has(entity)));
2833
- const ahead = [];
2834
- for (const entity of reads) {
2835
- const state = stateOf(entity);
2836
- if (state.write)
2837
- ahead.push(state.write);
2838
- state.reads.push(ownPromise);
2839
- }
2840
- for (const entity of writes) {
2841
- const state = stateOf(entity);
2842
- if (state.write)
2843
- ahead.push(state.write);
2844
- ahead.push(...state.reads);
2845
- state.write = ownPromise;
2846
- state.reads = [];
2847
- }
2848
- return ahead;
2849
- };
2850
- return {
2851
- recordFailedPredecessor(toolName, input) {
2852
- if (!barriers?.toolDependencies)
2853
- return [];
2854
- let dependencies;
2855
- try {
2856
- dependencies = barriers.toolDependencies({ toolName, input });
2857
- } catch {
2858
- return [];
2859
- }
2860
- if (!dependencies)
2861
- return [];
2862
- registerDependencies(dependencies, Promise.resolve(false));
2863
- return [...dependencies.reads ?? [], ...dependencies.writes ?? []];
2864
- },
2865
- enter(toolName, input) {
2866
- count += 1;
2867
- const refused = limit !== undefined && count > limit;
2868
- if (refused) {
2869
- return {
2870
- refused: true,
2871
- limit,
2872
- hasPredecessors: false,
2873
- waitAhead: async () => {
2874
- return;
2875
- },
2876
- settle: () => {
2877
- return;
2878
- }
2879
- };
2880
- }
2881
- const dependencies = barriers?.toolDependencies?.({ toolName, input });
2882
- if (!dependencies) {
2883
- return {
2884
- refused: false,
2885
- hasPredecessors: false,
2886
- waitAhead: async () => {
2887
- return;
2888
- },
2889
- settle: () => {
2890
- return;
2891
- }
2892
- };
2893
- }
2894
- const own = Promise.withResolvers();
2895
- let settled = false;
2896
- const settle = (ok = true) => {
2897
- if (settled)
2898
- return;
2899
- settled = true;
2900
- own.resolve(ok);
2901
- };
2902
- const ahead = registerDependencies(dependencies, own.promise);
2903
- return {
2904
- refused: false,
2905
- hasPredecessors: ahead.length > 0,
2906
- async waitAhead(signal) {
2907
- if (ahead.length === 0)
2908
- return;
2909
- const all = Promise.all(ahead);
2910
- const outcomes = await (signal ? raceAbort(all, signal) : all);
2911
- if (barriers?.onPredecessorFailure === "refuse" && outcomes.some((ok) => ok === false)) {
2912
- throw new AgentToolError2({
2913
- code: "STEP_PREDECESSOR_FAILED",
2914
- message: "Refused: an earlier tool call on the same entity failed in this step"
2915
- });
2916
- }
2917
- },
2918
- settle
2919
- };
2920
- }
2921
- };
2922
- }
2923
- function createToolDependencyResolver2(input) {
2924
- const effects = new Map;
2925
- for (const contract of input.contracts ?? []) {
2926
- const byEndpoint = contractOperationEffects2(contract);
2927
- for (const entry of listContractToolNames2([contract])) {
2928
- const effect = byEndpoint[entry.method];
2929
- if (effect !== undefined)
2930
- effects.set(entry.name, effect);
2931
- }
2932
- }
2933
- for (const [toolName, effect] of Object.entries(input.effects ?? {})) {
2934
- if (effects.has(toolName))
2935
- throw new RangeError(`Tool "${toolName}" already has the effect of its contract endpoint`);
2936
- effects.set(toolName, effect);
2937
- }
2938
- return ({ toolName, input: callInput }) => {
2939
- const effect = effects.get(toolName);
2940
- const entity = effect && input.entityOf(toolName, callInput);
2941
- if (entity === undefined || effect === undefined)
2942
- return;
2943
- return effect === "write" ? { writes: [entity] } : { reads: [entity] };
2944
- };
2945
- }
2946
-
2947
- // src/agent-runtime/loop/run-model-messages.ts
2948
- function buildStepResponseMessages(consumed, toolExecution) {
2949
- const assistantContent = [];
2950
- for (const segment of consumed.segments) {
2951
- if (segment.kind === "reasoning") {
2952
- if (segment.text.length === 0 && segment.provider === undefined)
2953
- continue;
2954
- const options = envelopeToProviderOptions(segment.provider);
2955
- assistantContent.push({
2956
- type: "reasoning",
2957
- text: segment.text,
2958
- ...options && { providerOptions: options }
2959
- });
2960
- } else if (segment.kind === "text") {
2961
- if (segment.text.length === 0 && segment.provider === undefined)
2962
- continue;
2963
- const options = envelopeToProviderOptions(segment.provider);
2964
- assistantContent.push({
2965
- type: "text",
2966
- text: segment.text,
2967
- ...options && { providerOptions: options }
2968
- });
2969
- } else if (segment.assistantPart !== undefined) {
2970
- assistantContent.push(segment.assistantPart);
2971
- }
2972
- }
2973
- assistantContent.push(...toolExecution.assistantParts);
2974
- const stepResponseMessages = [];
2975
- if (assistantContent.length > 0) {
2976
- stepResponseMessages.push({ role: "assistant", content: assistantContent });
2977
- }
2978
- if (toolExecution.toolParts.length > 0) {
2979
- stepResponseMessages.push({ role: "tool", content: toolExecution.toolParts });
2980
- }
2981
- return stepResponseMessages;
2982
- }
2983
- function buildStepContent(consumed, toolExecution) {
2984
- const content = [];
2985
- for (const segment of consumed.segments) {
2986
- if (segment.kind === "reasoning") {
2987
- if (segment.text.length > 0 || segment.provider !== undefined) {
2988
- content.push({ type: "reasoning", text: segment.text });
2989
- }
2990
- } else if (segment.kind === "text") {
2991
- if (segment.text.length > 0) {
2992
- content.push({ type: "text", text: segment.text });
2993
- }
2994
- } else if (segment.stepPart !== undefined) {
2995
- content.push(segment.stepPart);
2996
- }
2997
- }
2998
- content.push(...toolExecution.stepContent);
2999
- return content;
3000
- }
3001
-
3002
- // src/agent-runtime/loop/run-step-helpers.ts
3003
- function buildActiveToolSpecs(tools, requestedActive) {
3004
- const declared = Object.keys(tools);
3005
- const activeSet = requestedActive ? new Set(requestedActive) : undefined;
3006
- const activeNames = activeSet ? declared.filter((name) => activeSet.has(name)) : declared;
3007
- const specs = [];
3008
- for (const name of activeNames) {
3009
- const tool = Object.hasOwn(tools, name) ? tools[name] : undefined;
3010
- if (!tool)
3011
- continue;
3012
- specs.push({
3013
- name,
3014
- ...tool.description !== undefined && { description: tool.description },
3015
- inputSchema: tool.inputSchema,
3016
- ...tool.strict !== undefined && { strict: tool.strict },
3017
- ...tool.cacheControl !== undefined && { cacheControl: tool.cacheControl },
3018
- ...tool.providerOptions !== undefined && { providerOptions: tool.providerOptions }
3019
- });
3020
- }
3021
- return { activeNames, specs };
2794
+
2795
+ // src/agent-runtime/loop/run-step-helpers.ts
2796
+ function buildActiveToolSpecs(tools, requestedActive) {
2797
+ const declared = Object.keys(tools);
2798
+ const activeSet = requestedActive ? new Set(requestedActive) : undefined;
2799
+ const activeNames = activeSet ? declared.filter((name) => activeSet.has(name)) : declared;
2800
+ const specs = [];
2801
+ for (const name of activeNames) {
2802
+ const tool = Object.hasOwn(tools, name) ? tools[name] : undefined;
2803
+ if (!tool)
2804
+ continue;
2805
+ specs.push({
2806
+ name,
2807
+ ...tool.description !== undefined && { description: tool.description },
2808
+ inputSchema: tool.inputSchema,
2809
+ ...tool.strict !== undefined && { strict: tool.strict },
2810
+ ...tool.cacheControl !== undefined && { cacheControl: tool.cacheControl },
2811
+ ...tool.providerOptions !== undefined && { providerOptions: tool.providerOptions }
2812
+ });
2813
+ }
2814
+ return { activeNames, specs };
3022
2815
  }
3023
2816
  function mergeStepCallSettings(base, prepared) {
3024
2817
  const maxOutputTokens = prepared?.maxOutputTokens ?? base?.maxOutputTokens;
@@ -3160,6 +2953,186 @@ function assembleStepResult(input) {
3160
2953
  return { resolvedResponseId, stepResponseMessages, stepResult };
3161
2954
  }
3162
2955
 
2956
+ // src/agent-runtime/loop/run-step-barriers.ts
2957
+ class AgentStepBarrierError2 extends Error {
2958
+ bound;
2959
+ action;
2960
+ constructor(bound, message, action = "abort") {
2961
+ super(message);
2962
+ this.bound = bound;
2963
+ this.action = action;
2964
+ this.name = "AgentStepBarrierError";
2965
+ }
2966
+ }
2967
+ function assertStepBarriers(barriers) {
2968
+ if (!barriers)
2969
+ return;
2970
+ assertPositiveSafeInteger("stepBarriers.maxToolCallsPerStep", barriers.maxToolCallsPerStep, RangeError);
2971
+ assertPositiveSafeInteger("stepBarriers.maxReasoningCharsPerStep", barriers.maxReasoningCharsPerStep, RangeError);
2972
+ if (barriers.onMaxReasoningChars !== undefined && !["abort", "finish-length"].includes(barriers.onMaxReasoningChars))
2973
+ throw new RangeError("stepBarriers.onMaxReasoningChars must be 'abort' or 'finish-length'");
2974
+ if (barriers.stepText !== undefined && !["immediate", "after-tools"].includes(barriers.stepText))
2975
+ throw new RangeError("stepBarriers.stepText must be 'immediate' or 'after-tools'");
2976
+ if (barriers.stepTextOnInterrupt !== undefined && !["drop", "flush"].includes(barriers.stepTextOnInterrupt))
2977
+ throw new RangeError("stepBarriers.stepTextOnInterrupt must be 'drop' or 'flush'");
2978
+ if (barriers.onPredecessorFailure !== undefined && !["run", "refuse"].includes(barriers.onPredecessorFailure))
2979
+ throw new RangeError("stepBarriers.onPredecessorFailure must be 'run' or 'refuse'");
2980
+ }
2981
+ var RUNTIME_ONLY_STEP_BARRIER_KEYS = [
2982
+ "stepText",
2983
+ "maxReasoningCharsPerStep",
2984
+ "onMaxReasoningChars",
2985
+ "stepTextOnInterrupt",
2986
+ "filterStepText"
2987
+ ];
2988
+ function assertStandaloneStepBarriers(barriers) {
2989
+ if (barriers === undefined)
2990
+ return;
2991
+ if (typeof barriers !== "object" || barriers === null) {
2992
+ throw new TypeError("stepBarriers must be an object");
2993
+ }
2994
+ for (const key of RUNTIME_ONLY_STEP_BARRIER_KEYS) {
2995
+ if (Object.hasOwn(barriers, key) && Reflect.get(barriers, key) !== undefined) {
2996
+ throw new TypeError(`stepBarriers.${key} is only supported by createAgentRuntime, not standalone completion`);
2997
+ }
2998
+ }
2999
+ assertStepBarriers(barriers);
3000
+ }
3001
+ function stepToolCallLimitRefusal(limit) {
3002
+ return new AgentToolError2({
3003
+ code: "STEP_TOOL_CALL_LIMIT",
3004
+ message: `Refused: a step may make at most ${limit} tool calls; make the rest in the next step`
3005
+ });
3006
+ }
3007
+ function createStepCallScheduler(barriers) {
3008
+ let count = 0;
3009
+ const entities = new Map;
3010
+ const limit = barriers?.maxToolCallsPerStep;
3011
+ const stateOf = (entity) => {
3012
+ const known = entities.get(entity);
3013
+ if (known)
3014
+ return known;
3015
+ const fresh = { reads: [] };
3016
+ entities.set(entity, fresh);
3017
+ return fresh;
3018
+ };
3019
+ const registerDependencies = (dependencies, ownPromise) => {
3020
+ const writes = new Set(dependencies.writes ?? []);
3021
+ const reads = new Set([...dependencies.reads ?? []].filter((entity) => !writes.has(entity)));
3022
+ const ahead = [];
3023
+ for (const entity of reads) {
3024
+ const state = stateOf(entity);
3025
+ if (state.write)
3026
+ ahead.push(state.write);
3027
+ state.reads.push(ownPromise);
3028
+ }
3029
+ for (const entity of writes) {
3030
+ const state = stateOf(entity);
3031
+ if (state.write)
3032
+ ahead.push(state.write);
3033
+ ahead.push(...state.reads);
3034
+ state.write = ownPromise;
3035
+ state.reads = [];
3036
+ }
3037
+ return ahead;
3038
+ };
3039
+ return {
3040
+ recordFailedPredecessor(toolName, input) {
3041
+ if (!barriers?.toolDependencies)
3042
+ return [];
3043
+ let dependencies;
3044
+ try {
3045
+ dependencies = barriers.toolDependencies({ toolName, input });
3046
+ } catch {
3047
+ return [];
3048
+ }
3049
+ if (!dependencies)
3050
+ return [];
3051
+ registerDependencies(dependencies, Promise.resolve(false));
3052
+ return [...dependencies.reads ?? [], ...dependencies.writes ?? []];
3053
+ },
3054
+ enter(toolName, input) {
3055
+ count += 1;
3056
+ const refused = limit !== undefined && count > limit;
3057
+ if (refused) {
3058
+ return {
3059
+ refused: true,
3060
+ limit,
3061
+ hasPredecessors: false,
3062
+ waitAhead: async () => {
3063
+ return;
3064
+ },
3065
+ settle: () => {
3066
+ return;
3067
+ }
3068
+ };
3069
+ }
3070
+ const dependencies = barriers?.toolDependencies?.({ toolName, input });
3071
+ if (!dependencies) {
3072
+ return {
3073
+ refused: false,
3074
+ hasPredecessors: false,
3075
+ waitAhead: async () => {
3076
+ return;
3077
+ },
3078
+ settle: () => {
3079
+ return;
3080
+ }
3081
+ };
3082
+ }
3083
+ const own = Promise.withResolvers();
3084
+ let settled = false;
3085
+ const settle = (ok = true) => {
3086
+ if (settled)
3087
+ return;
3088
+ settled = true;
3089
+ own.resolve(ok);
3090
+ };
3091
+ const ahead = registerDependencies(dependencies, own.promise);
3092
+ return {
3093
+ refused: false,
3094
+ hasPredecessors: ahead.length > 0,
3095
+ async waitAhead(signal) {
3096
+ if (ahead.length === 0)
3097
+ return;
3098
+ const all = Promise.all(ahead);
3099
+ const outcomes = await (signal ? raceAbort(all, signal) : all);
3100
+ if (barriers?.onPredecessorFailure === "refuse" && outcomes.some((ok) => ok === false)) {
3101
+ throw new AgentToolError2({
3102
+ code: "STEP_PREDECESSOR_FAILED",
3103
+ message: "Refused: an earlier tool call on the same entity failed in this step"
3104
+ });
3105
+ }
3106
+ },
3107
+ settle
3108
+ };
3109
+ }
3110
+ };
3111
+ }
3112
+ function createToolDependencyResolver2(input) {
3113
+ const effects = new Map;
3114
+ for (const contract of input.contracts ?? []) {
3115
+ const byEndpoint = contractOperationEffects2(contract);
3116
+ for (const entry of listContractToolNames2([contract])) {
3117
+ const effect = byEndpoint[entry.method];
3118
+ if (effect !== undefined)
3119
+ effects.set(entry.name, effect);
3120
+ }
3121
+ }
3122
+ for (const [toolName, effect] of Object.entries(input.effects ?? {})) {
3123
+ if (effects.has(toolName))
3124
+ throw new RangeError(`Tool "${toolName}" already has the effect of its contract endpoint`);
3125
+ effects.set(toolName, effect);
3126
+ }
3127
+ return ({ toolName, input: callInput }) => {
3128
+ const effect = effects.get(toolName);
3129
+ const entity = effect && input.entityOf(toolName, callInput);
3130
+ if (entity === undefined || effect === undefined)
3131
+ return;
3132
+ return effect === "write" ? { writes: [entity] } : { reads: [entity] };
3133
+ };
3134
+ }
3135
+
3163
3136
  // src/agent-runtime/loop/run-tool-approval-records.ts
3164
3137
  async function recordUserApprovalRequest(input) {
3165
3138
  const { execution, callId, toolName, parsedInput, callRecord, reason, emit, callSlot } = input;
@@ -3365,7 +3338,7 @@ async function applyRecordedPart(execution, part) {
3365
3338
  envelope: {
3366
3339
  schemaVersion: 1,
3367
3340
  provider: "raw",
3368
- data: { value: jsonValue(part.rawValue) }
3341
+ data: { value: recordedJson(part.rawValue) }
3369
3342
  }
3370
3343
  }));
3371
3344
  }
@@ -3545,27 +3518,79 @@ async function flushHeldStepTextWithOutcome(execution, interrupted, context) {
3545
3518
  state.parts.splice(targetIndex, 0, textPart);
3546
3519
  offset += 1;
3547
3520
  }
3548
- if (state.firstOutputAt === undefined)
3549
- state.firstOutputAt = performance.now();
3550
- await execution.operationLifecycle.firstOutput();
3551
- const { publish, now, runtimeEpoch } = execution.dependencies;
3552
- for (const seg of surviving) {
3553
- await publish({
3554
- type: "assistant-delta",
3555
- conversationId: state.run.conversationId,
3556
- runId: state.run.id,
3557
- runtimeEpoch,
3558
- sequence: transientSequence(state),
3559
- textDelta: seg.text,
3560
- emittedAt: now().toISOString()
3561
- });
3521
+ if (state.firstOutputAt === undefined)
3522
+ state.firstOutputAt = performance.now();
3523
+ await execution.operationLifecycle.firstOutput();
3524
+ const { publish, now, runtimeEpoch } = execution.dependencies;
3525
+ for (const seg of surviving) {
3526
+ state.transientChars.text += seg.text.length;
3527
+ await publish({
3528
+ type: "assistant-delta",
3529
+ conversationId: state.run.conversationId,
3530
+ runId: state.run.id,
3531
+ runtimeEpoch,
3532
+ sequence: transientSequence(state),
3533
+ textDelta: seg.text,
3534
+ emittedAt: now().toISOString()
3535
+ });
3536
+ }
3537
+ return {
3538
+ hadHeldText: true,
3539
+ releasedText: surviving.map((seg) => seg.text).join(""),
3540
+ rawText,
3541
+ ...changed && { segmentOverrides: overrides }
3542
+ };
3543
+ }
3544
+
3545
+ // src/agent-runtime/loop/run-tool-errors.ts
3546
+ function formatSafeValidationIssues(cause) {
3547
+ if (!isRecord(cause) || !Array.isArray(cause.issues) || cause.issues.length === 0) {
3548
+ return;
3549
+ }
3550
+ const summaries = [];
3551
+ for (const issue of cause.issues.slice(0, 5)) {
3552
+ if (!isRecord(issue) || typeof issue.message !== "string")
3553
+ continue;
3554
+ const path = Array.isArray(issue.path) ? issue.path.filter((segment) => typeof segment === "string" || typeof segment === "number").join(".") : "";
3555
+ summaries.push(path.length > 0 ? `${path}: ${issue.message}` : issue.message);
3556
+ }
3557
+ if (summaries.length === 0)
3558
+ return;
3559
+ const suffix = cause.issues.length > 5 ? ` (+${cause.issues.length - 5} more)` : "";
3560
+ return `${summaries.join("; ")}${suffix}`;
3561
+ }
3562
+
3563
+ class AgentUnknownToolError2 extends Error {
3564
+ reason = "unknown-tool";
3565
+ toolName;
3566
+ activeTools;
3567
+ constructor(toolName, options) {
3568
+ super(`Unknown or inactive tool "${toolName}"`, options?.cause !== undefined ? { cause: options.cause } : undefined);
3569
+ this.name = "AgentUnknownToolError";
3570
+ this.toolName = toolName;
3571
+ if (options?.activeTools !== undefined) {
3572
+ this.activeTools = [...options.activeTools];
3573
+ }
3574
+ }
3575
+ }
3576
+
3577
+ class AgentInvalidToolInputError2 extends Error {
3578
+ toolName;
3579
+ reason;
3580
+ constructor(toolName, options) {
3581
+ const detail = options.reason === "validation-failed" ? formatSafeValidationIssues(options.cause) : undefined;
3582
+ const message = options.reason === "invalid-json" ? `Invalid JSON arguments for tool "${toolName}"` : detail !== undefined ? `Invalid input for tool "${toolName}": ${detail}` : `Invalid input for tool "${toolName}"`;
3583
+ super(message, options.cause !== undefined ? { cause: options.cause } : undefined);
3584
+ this.name = "AgentInvalidToolInputError";
3585
+ this.toolName = toolName;
3586
+ this.reason = options.reason;
3562
3587
  }
3563
- return {
3564
- hadHeldText: true,
3565
- releasedText: surviving.map((seg) => seg.text).join(""),
3566
- rawText,
3567
- ...changed && { segmentOverrides: overrides }
3568
- };
3588
+ }
3589
+ function safeToolErrorMessage(error) {
3590
+ if (isAgentToolError2(error) || error instanceof AgentUnknownToolError2 || error instanceof AgentInvalidToolInputError2) {
3591
+ return error.message;
3592
+ }
3593
+ return "Tool execution failed";
3569
3594
  }
3570
3595
 
3571
3596
  // src/agent-runtime/loop/run-stream-parts.ts
@@ -3612,6 +3637,7 @@ async function applyTextPart(execution, part) {
3612
3637
  appendHeldStepTextDelta(state, part.id, part.text, part.provider);
3613
3638
  } else if (part.type === "text-delta") {
3614
3639
  updateTextBlock(state, part.text, part.provider, part.id);
3640
+ state.transientChars.text += part.text.length;
3615
3641
  await publish({
3616
3642
  type: "assistant-delta",
3617
3643
  ...transientHead(execution),
@@ -3649,6 +3675,7 @@ async function applyTextPart(execution, part) {
3649
3675
  throw new AgentStepBarrierError2("reasoning", `A step reasoned past its bound of ${limit} characters`, action);
3650
3676
  }
3651
3677
  updateReasoning(state, part.text, part.provider, part.id);
3678
+ state.transientChars.reasoning += part.text.length;
3652
3679
  await publish({
3653
3680
  type: "reasoning-delta",
3654
3681
  ...transientHead(execution),
@@ -3703,19 +3730,21 @@ async function applyToolPart(execution, part) {
3703
3730
  input: part.input,
3704
3731
  output: part.output
3705
3732
  });
3733
+ const output = part.recorded ?? recordedJson(part.output);
3706
3734
  state.parts.push(AgentMessagePartSchema2.parse({
3707
3735
  type: "tool-result",
3708
3736
  callId: part.toolCallId,
3709
3737
  toolName: part.toolName,
3710
3738
  outcome: "success",
3711
- output: jsonValue(part.output),
3739
+ output,
3740
+ ...part.modelOutput && { modelOutput: part.modelOutput },
3712
3741
  ...part.provider && { provider: part.provider }
3713
3742
  }));
3714
3743
  await checkpoint(execution, {
3715
3744
  callId: part.toolCallId,
3716
3745
  toolName: part.toolName,
3717
3746
  status: "completed",
3718
- output: jsonValue(part.output)
3747
+ output
3719
3748
  });
3720
3749
  } else if (part.type === "tool-error") {
3721
3750
  state.settledToolCalls.add(part.toolCallId);
@@ -3729,7 +3758,7 @@ async function applyToolPart(execution, part) {
3729
3758
  throw part.error;
3730
3759
  }
3731
3760
  state.stepGuard.toolFailed = true;
3732
- const output = isAgentToolError2(part.error) ? jsonValue(part.error.output) : { message: "Tool execution failed" };
3761
+ const output = isAgentToolError2(part.error) ? agentToolErrorDetail(part.error) : { message: safeToolErrorMessage(part.error) };
3733
3762
  state.parts.push(AgentMessagePartSchema2.parse({
3734
3763
  type: "tool-result",
3735
3764
  callId: part.toolCallId,
@@ -3930,51 +3959,6 @@ async function classifyRunFailure(execution, error) {
3930
3959
  }
3931
3960
  }
3932
3961
 
3933
- // src/agent-runtime/loop/run-tool-errors.ts
3934
- function formatSafeValidationIssues(cause) {
3935
- if (!isRecord(cause) || !Array.isArray(cause.issues) || cause.issues.length === 0) {
3936
- return;
3937
- }
3938
- const summaries = [];
3939
- for (const issue of cause.issues.slice(0, 5)) {
3940
- if (!isRecord(issue) || typeof issue.message !== "string")
3941
- continue;
3942
- const path = Array.isArray(issue.path) ? issue.path.filter((segment) => typeof segment === "string" || typeof segment === "number").join(".") : "";
3943
- summaries.push(path.length > 0 ? `${path}: ${issue.message}` : issue.message);
3944
- }
3945
- if (summaries.length === 0)
3946
- return;
3947
- const suffix = cause.issues.length > 5 ? ` (+${cause.issues.length - 5} more)` : "";
3948
- return `${summaries.join("; ")}${suffix}`;
3949
- }
3950
-
3951
- class AgentUnknownToolError2 extends Error {
3952
- reason = "unknown-tool";
3953
- toolName;
3954
- activeTools;
3955
- constructor(toolName, options) {
3956
- super(`Unknown or inactive tool "${toolName}"`, options?.cause !== undefined ? { cause: options.cause } : undefined);
3957
- this.name = "AgentUnknownToolError";
3958
- this.toolName = toolName;
3959
- if (options?.activeTools !== undefined) {
3960
- this.activeTools = [...options.activeTools];
3961
- }
3962
- }
3963
- }
3964
-
3965
- class AgentInvalidToolInputError2 extends Error {
3966
- toolName;
3967
- reason;
3968
- constructor(toolName, options) {
3969
- const detail = options.reason === "validation-failed" ? formatSafeValidationIssues(options.cause) : undefined;
3970
- const message = options.reason === "invalid-json" ? `Invalid JSON arguments for tool "${toolName}"` : detail !== undefined ? `Invalid input for tool "${toolName}": ${detail}` : `Invalid input for tool "${toolName}"`;
3971
- super(message, options.cause !== undefined ? { cause: options.cause } : undefined);
3972
- this.name = "AgentInvalidToolInputError";
3973
- this.toolName = toolName;
3974
- this.reason = options.reason;
3975
- }
3976
- }
3977
-
3978
3962
  // src/agent-runtime/loop/run-tool-progress.ts
3979
3963
  var TOOL_PROGRESS_MIN_INTERVAL_MS = 250;
3980
3964
  function finite(value) {
@@ -4016,27 +4000,6 @@ function createCallSlotResult() {
4016
4000
  toolResults: []
4017
4001
  };
4018
4002
  }
4019
- function safeToolErrorMessage(error) {
4020
- if (isAgentToolError2(error) || error instanceof AgentUnknownToolError2 || error instanceof AgentInvalidToolInputError2) {
4021
- return error.message;
4022
- }
4023
- return "Tool execution failed";
4024
- }
4025
- function parseJsonArgs(raw) {
4026
- const trimmed = raw.trim();
4027
- if (trimmed.length === 0)
4028
- return { ok: true, value: {} };
4029
- try {
4030
- return { ok: true, value: JSON.parse(trimmed) };
4031
- } catch (error) {
4032
- return { ok: false, error };
4033
- }
4034
- }
4035
- function defaultToolWireOutput(output) {
4036
- if (typeof output === "string")
4037
- return { type: "text", value: output };
4038
- return { type: "json", value: jsonValue(output ?? null) };
4039
- }
4040
4003
  function buildToolDurability(execution, toolName, toolCallId, signal) {
4041
4004
  const { config } = execution.dependencies;
4042
4005
  if (!config.durability)
@@ -4059,68 +4022,6 @@ function buildToolDurability(execution, toolName, toolCallId, signal) {
4059
4022
  signal
4060
4023
  });
4061
4024
  }
4062
- async function resolveToolCallInput(input) {
4063
- const activeSet = new Set(input.activeTools);
4064
- const attemptResolve = async (name, rawArgs) => {
4065
- const tool = activeSet.has(name) && Object.hasOwn(input.tools, name) ? input.tools[name] : undefined;
4066
- if (!tool) {
4067
- return {
4068
- ok: false,
4069
- kind: "unknown-tool",
4070
- toolName: name,
4071
- parsedInput: rawArgs,
4072
- error: new AgentUnknownToolError2(name, { activeTools: input.activeTools })
4073
- };
4074
- }
4075
- const json = parseJsonArgs(rawArgs);
4076
- if (!json.ok) {
4077
- return {
4078
- ok: false,
4079
- kind: "invalid-input",
4080
- toolName: name,
4081
- parsedInput: rawArgs,
4082
- error: new AgentInvalidToolInputError2(name, {
4083
- reason: "invalid-json",
4084
- cause: json.error
4085
- })
4086
- };
4087
- }
4088
- if (tool.parseInput) {
4089
- const checked = await tool.parseInput(json.value);
4090
- if (!checked.ok) {
4091
- return {
4092
- ok: false,
4093
- kind: "invalid-input",
4094
- toolName: name,
4095
- parsedInput: json.value,
4096
- error: new AgentInvalidToolInputError2(name, {
4097
- reason: "validation-failed",
4098
- cause: checked.error
4099
- })
4100
- };
4101
- }
4102
- return { ok: true, toolName: name, tool, parsedInput: checked.value };
4103
- }
4104
- return { ok: true, toolName: name, tool, parsedInput: json.value };
4105
- };
4106
- const first = await attemptResolve(input.raw.toolName, input.raw.input);
4107
- if (first.ok || !input.repairToolCall)
4108
- return first;
4109
- const repaired = await input.repairToolCall({
4110
- toolCall: {
4111
- toolCallId: input.raw.toolCallId,
4112
- toolName: input.raw.toolName,
4113
- input: input.raw.input
4114
- },
4115
- activeTools: input.activeTools,
4116
- tools: input.tools,
4117
- messages: input.messages,
4118
- error: { kind: first.kind, toolName: first.toolName, cause: first.error }
4119
- });
4120
- if (!repaired)
4121
- return first;
4122
- return attemptResolve(repaired.toolName, repaired.input);
4123
- }
4124
4025
  function resolveSingleToolHooks(input) {
4125
4026
  if (input.hooks !== undefined)
4126
4027
  return input.hooks;
@@ -4145,12 +4046,14 @@ function resolveSingleToolHooks(input) {
4145
4046
  output: chunk,
4146
4047
  preliminary: true
4147
4048
  }),
4148
- onResult: (output) => emit({
4049
+ onResult: ({ output, recorded, modelOutput }) => emit({
4149
4050
  type: "tool-result",
4150
4051
  toolCallId,
4151
4052
  toolName,
4152
4053
  input: parsedInput,
4153
4054
  output,
4055
+ recorded,
4056
+ ...modelOutput && { modelOutput },
4154
4057
  preliminary: false
4155
4058
  }),
4156
4059
  onError: (error) => emit({
@@ -4204,10 +4107,18 @@ async function runSingleToolExecution(input) {
4204
4107
  finalValue = last;
4205
4108
  }
4206
4109
  finalValue = finalizeAgentToolOutput(tool, finalValue, wasAsyncIterable);
4207
- const wireOutput = tool.toModelOutput ? await tool.toModelOutput({ toolCallId, input: parsedInput, output: finalValue }) : defaultToolWireOutput(finalValue);
4110
+ const recorded = projectToolOutput(toolName, finalValue);
4111
+ const wireOutput = tool.toModelOutput ? projectModelOutput(toolName, await tool.toModelOutput({ toolCallId, input: parsedInput, output: finalValue })) : defaultToolWireOutput(recorded);
4208
4112
  signal.throwIfAborted();
4209
4113
  succeeded = !isToolResultFailure2(finalValue);
4210
- outcome = { ok: true, output: finalValue, wireOutput };
4114
+ const modelOutput = tool.toModelOutput ? recordedModelOutput(wireOutput) : undefined;
4115
+ outcome = {
4116
+ ok: true,
4117
+ output: finalValue,
4118
+ recorded,
4119
+ ...modelOutput && { modelOutput },
4120
+ wireOutput
4121
+ };
4211
4122
  } catch (error) {
4212
4123
  if (emitFailed || signal.aborted || isToolExecutionControlError2(error) || hooks.isFatalError?.(error) === true) {
4213
4124
  if (!emitFailed && isToolExecutionControlError2(error)) {
@@ -4225,7 +4136,7 @@ async function runSingleToolExecution(input) {
4225
4136
  }
4226
4137
  signal.throwIfAborted();
4227
4138
  if (outcome.ok) {
4228
- await hooks.onResult(outcome.output);
4139
+ await hooks.onResult(outcome);
4229
4140
  } else {
4230
4141
  await hooks.onError(outcome.error);
4231
4142
  }
@@ -4260,6 +4171,80 @@ async function preflightStandaloneApprovals(input) {
4260
4171
  }
4261
4172
  }
4262
4173
 
4174
+ // src/agent-runtime/loop/run-tool-call-input.ts
4175
+ function parseJsonArgs(raw) {
4176
+ const trimmed = raw.trim();
4177
+ if (trimmed.length === 0)
4178
+ return { ok: true, value: {} };
4179
+ try {
4180
+ return { ok: true, value: JSON.parse(trimmed) };
4181
+ } catch (error) {
4182
+ return { ok: false, error };
4183
+ }
4184
+ }
4185
+ async function resolveToolCallInput(input) {
4186
+ const activeSet = new Set(input.activeTools);
4187
+ const attemptResolve = async (name, rawArgs) => {
4188
+ const tool = activeSet.has(name) && Object.hasOwn(input.tools, name) ? input.tools[name] : undefined;
4189
+ if (!tool) {
4190
+ return {
4191
+ ok: false,
4192
+ kind: "unknown-tool",
4193
+ toolName: name,
4194
+ parsedInput: rawArgs,
4195
+ error: new AgentUnknownToolError2(name, { activeTools: input.activeTools })
4196
+ };
4197
+ }
4198
+ const json = parseJsonArgs(rawArgs);
4199
+ if (!json.ok) {
4200
+ return {
4201
+ ok: false,
4202
+ kind: "invalid-input",
4203
+ toolName: name,
4204
+ parsedInput: rawArgs,
4205
+ error: new AgentInvalidToolInputError2(name, {
4206
+ reason: "invalid-json",
4207
+ cause: json.error
4208
+ })
4209
+ };
4210
+ }
4211
+ if (tool.parseInput) {
4212
+ const checked = await tool.parseInput(json.value);
4213
+ if (!checked.ok) {
4214
+ return {
4215
+ ok: false,
4216
+ kind: "invalid-input",
4217
+ toolName: name,
4218
+ parsedInput: json.value,
4219
+ error: new AgentInvalidToolInputError2(name, {
4220
+ reason: "validation-failed",
4221
+ cause: checked.error
4222
+ })
4223
+ };
4224
+ }
4225
+ return { ok: true, toolName: name, tool, parsedInput: checked.value };
4226
+ }
4227
+ return { ok: true, toolName: name, tool, parsedInput: json.value };
4228
+ };
4229
+ const first = await attemptResolve(input.raw.toolName, input.raw.input);
4230
+ if (first.ok || !input.repairToolCall)
4231
+ return first;
4232
+ const repaired = await input.repairToolCall({
4233
+ toolCall: {
4234
+ toolCallId: input.raw.toolCallId,
4235
+ toolName: input.raw.toolName,
4236
+ input: input.raw.input
4237
+ },
4238
+ activeTools: input.activeTools,
4239
+ tools: input.tools,
4240
+ messages: input.messages,
4241
+ error: { kind: first.kind, toolName: first.toolName, cause: first.error }
4242
+ });
4243
+ if (!repaired)
4244
+ return first;
4245
+ return attemptResolve(repaired.toolName, repaired.input);
4246
+ }
4247
+
4263
4248
  // src/agent-runtime/loop/run-tool-slots.ts
4264
4249
  function emptyStepToolExecutionResult() {
4265
4250
  return collectStepToolExecutionResult([], 0, 0);
@@ -4289,7 +4274,7 @@ function createStandaloneToolHooks(sink, toolCallId, toolName, parsedInput) {
4289
4274
  output: chunk,
4290
4275
  preliminary: true
4291
4276
  }),
4292
- onResult: (output) => sink.onToolResult({
4277
+ onResult: ({ output }) => sink.onToolResult({
4293
4278
  toolCallId,
4294
4279
  toolName,
4295
4280
  input: parsedInput,
@@ -5066,11 +5051,262 @@ async function executeStepToolCalls(input) {
5066
5051
  if (collector.pendingExecutions.length > 0) {
5067
5052
  await Promise.allSettled(collector.pendingExecutions);
5068
5053
  }
5069
- stepSignalLink.release();
5070
- if (mode.kind === "durable")
5071
- mode.execution.idleDeadline.resume();
5054
+ stepSignalLink.release();
5055
+ if (mode.kind === "durable")
5056
+ mode.execution.idleDeadline.resume();
5057
+ }
5058
+ return collectStepToolExecutionResult(callSlots, clientCalls.length, collector.settledClientToolCount);
5059
+ }
5060
+
5061
+ // src/agent-runtime/loop/run-step-loop.ts
5062
+ async function callStepModel(port, state, step) {
5063
+ const windowStart = performance.now();
5064
+ const discarded = [];
5065
+ for (let attempt = 1;; attempt += 1) {
5066
+ port.signal.throwIfAborted();
5067
+ const callId = port.newCallId();
5068
+ const driver = await port.openCall({
5069
+ stepNumber: step.stepNumber,
5070
+ attempt,
5071
+ callId,
5072
+ stepModel: step.stepModel,
5073
+ driver: step.baseDriver,
5074
+ instructions: step.instructions,
5075
+ messages: state.currentMessages
5076
+ });
5077
+ const request = port.buildRequest({
5078
+ prepared: step.prepared,
5079
+ instructions: step.instructions,
5080
+ messages: state.currentMessages,
5081
+ specs: step.specs,
5082
+ callId,
5083
+ stepNumber: step.stepNumber
5084
+ });
5085
+ let decided;
5086
+ let refused = false;
5087
+ const decide = async (error) => {
5088
+ if (decided !== undefined)
5089
+ return true;
5090
+ if (refused || port.signal.aborted || !port.retry || port.callInvokedTool())
5091
+ return false;
5092
+ const failure = classifyProviderFailure2(error);
5093
+ const decision = await port.decideRetry({
5094
+ error,
5095
+ attempt,
5096
+ failure,
5097
+ elapsedMs: Math.max(0, performance.now() - windowStart)
5098
+ });
5099
+ if (!decision.retry) {
5100
+ refused = true;
5101
+ return false;
5102
+ }
5103
+ decided = { error, failure, delayMs: decision.delayMs };
5104
+ return true;
5105
+ };
5106
+ let usage;
5107
+ let failedError;
5108
+ try {
5109
+ const outcome = await port.streamCall({
5110
+ stepNumber: step.stepNumber,
5111
+ attempt,
5112
+ callId,
5113
+ driver,
5114
+ request,
5115
+ stepModel: step.stepModel,
5116
+ retryOnFailure: decide
5117
+ });
5118
+ if (outcome.kind === "ended")
5119
+ return outcome;
5120
+ if (outcome.kind === "finished") {
5121
+ if (outcome.consumed.finishPart)
5122
+ return { ...outcome, callId, request, driver };
5123
+ if (await port.missingFinish(outcome.consumed, driver) === "ended") {
5124
+ return { kind: "ended" };
5125
+ }
5126
+ } else {
5127
+ usage = outcome.usage;
5128
+ if (outcome.kind === "failed")
5129
+ failedError = outcome.error;
5130
+ }
5131
+ } catch (error) {
5132
+ if (port.signal.aborted || !hasProviderOrigin(error))
5133
+ throw error;
5134
+ failedError = error;
5135
+ }
5136
+ if (decided === undefined) {
5137
+ const error = failedError;
5138
+ if (!await decide(error)) {
5139
+ const failure = classifyProviderFailure2(error);
5140
+ const spent = state.discardedUsage !== undefined ? addUsage(state.stepUsage, state.discardedUsage) : state.stepUsage;
5141
+ throw port.refuseRetry({
5142
+ error,
5143
+ attempts: [
5144
+ ...discarded,
5145
+ { attempt, error, failure, ...usage !== undefined && { usage } }
5146
+ ],
5147
+ usage: usage !== undefined ? addUsage(spent, usage) : spent
5148
+ });
5149
+ }
5150
+ }
5151
+ if (decided === undefined)
5152
+ throw failedError;
5153
+ if (port.signal.aborted)
5154
+ return { kind: "ended" };
5155
+ const call = {
5156
+ attempt,
5157
+ error: decided.error,
5158
+ failure: decided.failure,
5159
+ ...usage !== undefined && { usage }
5160
+ };
5161
+ discarded.push(call);
5162
+ if (usage !== undefined)
5163
+ state.discardedUsage = addUsage(state.discardedUsage, usage);
5164
+ await port.discardCall(call);
5165
+ await port.onAttemptDiscarded?.({
5166
+ attempt,
5167
+ reason: call.failure.reason,
5168
+ ...usage !== undefined && { usage }
5169
+ });
5170
+ await port.announceDiscard(call);
5171
+ if (decided.delayMs > 0)
5172
+ await sleep(decided.delayMs, port.signal);
5173
+ if (port.signal.aborted)
5174
+ return { kind: "ended" };
5175
+ await port.announceRetry(call);
5176
+ }
5177
+ }
5178
+ async function runOneStep(port, state, stepNumber) {
5179
+ port.signal.throwIfAborted();
5180
+ await port.startStep();
5181
+ const defaultInstructions = state.continuationInstructions ?? state.carriedInstructions;
5182
+ state.continuationInstructions = undefined;
5183
+ const declaredTools = port.tools ? Object.keys(port.tools) : [];
5184
+ const prepared = await port.prepareStep({
5185
+ stepNumber,
5186
+ steps: state.steps,
5187
+ messages: state.currentMessages,
5188
+ responseMessages: state.responseMessages,
5189
+ initialMessages: port.initialMessages,
5190
+ initialInstructions: port.initialInstructions,
5191
+ instructions: defaultInstructions,
5192
+ driver: port.baseDriver,
5193
+ activeTools: declaredTools
5194
+ });
5195
+ const injected = await port.takeInjectedMessages();
5196
+ state.currentMessages = [...prepared?.messages ?? state.currentMessages, ...injected];
5197
+ if (prepared?.instructions !== undefined)
5198
+ state.carriedInstructions = prepared.instructions;
5199
+ const instructions = prepared?.instructions ?? defaultInstructions;
5200
+ const { activeNames, specs } = port.tools ? buildActiveToolSpecs(port.tools, prepared?.activeTools) : { activeNames: [], specs: [] };
5201
+ const baseDriver = prepared?.driver ?? port.baseDriver;
5202
+ const stepModel = port.stepModel(baseDriver);
5203
+ const call = await callStepModel(port, state, {
5204
+ stepNumber,
5205
+ prepared,
5206
+ instructions,
5207
+ specs,
5208
+ baseDriver,
5209
+ stepModel
5210
+ });
5211
+ if (call.kind === "ended")
5212
+ return "ended";
5213
+ const { consumed, stepStartedAt, responseFinishedAt } = call;
5214
+ const finishPart = consumed.finishPart;
5215
+ if (!finishPart)
5216
+ return "ended";
5217
+ const unsafeForClientTools = isStepUnsafeForClientTools(finishPart.finishReason, consumed.sawErrorPart);
5218
+ const runTools = !unsafeForClientTools && port.tools !== undefined;
5219
+ const toolStartedAt = performance.now();
5220
+ const toolExecution = runTools && port.tools ? await executeStepToolCalls({
5221
+ stepNumber,
5222
+ rawCalls: consumed.rawToolCalls,
5223
+ tools: port.tools,
5224
+ activeTools: activeNames,
5225
+ repairToolCall: port.repairToolCall,
5226
+ instructions: call.request.instructions,
5227
+ messages: state.currentMessages,
5228
+ signal: port.signal,
5229
+ mode: port.toolMode
5230
+ }) : emptyStepToolExecutionResult();
5231
+ const stepFinishedAt = performance.now();
5232
+ const timings = buildStepTimings({
5233
+ stepStartedAt,
5234
+ responseFinishedAt,
5235
+ stepFinishedAt,
5236
+ firstOutputAt: consumed.firstOutputAt,
5237
+ toolExecutionMs: runTools ? Math.max(0, stepFinishedAt - toolStartedAt) : 0,
5238
+ outputChunkTimestamps: consumed.outputChunkTimestamps
5239
+ });
5240
+ const stepTextOverrides = await port.stepTextOverrides({
5241
+ finishPart,
5242
+ consumed,
5243
+ toolExecution
5244
+ });
5245
+ const stepUsage = statedUsage(finishPart.usage);
5246
+ const { resolvedResponseId, stepResponseMessages, stepResult } = assembleStepResult({
5247
+ stepNumber,
5248
+ callId: call.callId,
5249
+ model: stepModel,
5250
+ consumed,
5251
+ finishPart,
5252
+ toolExecution,
5253
+ timings,
5254
+ stepUsage,
5255
+ ...stepTextOverrides !== undefined && { stepTextOverrides }
5256
+ });
5257
+ state.currentMessages = [...state.currentMessages, ...stepResponseMessages];
5258
+ state.responseMessages.push(...stepResponseMessages);
5259
+ state.stepUsage = addUsage(state.stepUsage, stepUsage);
5260
+ state.lastFinishReason = finishPart.finishReason;
5261
+ state.steps.push(stepResult);
5262
+ await port.finishStep({
5263
+ stepNumber,
5264
+ stepResult,
5265
+ resolvedResponseId,
5266
+ consumed,
5267
+ finishPart,
5268
+ timings,
5269
+ stepUsage
5270
+ });
5271
+ const canContinue = !unsafeForClientTools && toolExecution.clientToolCallCount > 0 && toolExecution.settledClientToolCount === toolExecution.clientToolCallCount;
5272
+ if (!canContinue)
5273
+ return "last";
5274
+ if (await port.shouldStop(state.steps))
5275
+ return "last";
5276
+ return "continue";
5277
+ }
5278
+ async function runModelStepLoop(port, state) {
5279
+ for (let stepNumber = 0;; stepNumber += 1) {
5280
+ const outcome = await runOneStep(port, state, stepNumber);
5281
+ if (outcome === "ended")
5282
+ return "ended";
5283
+ if (outcome === "continue")
5284
+ continue;
5285
+ const next = await port.afterLastStep(state);
5286
+ if (next.action === "stop")
5287
+ return "completed";
5288
+ state.currentMessages = [...state.currentMessages, next.message];
5289
+ state.responseMessages.push(next.message);
5290
+ state.continuationInstructions = next.instructions;
5072
5291
  }
5073
- return collectStepToolExecutionResult(callSlots, clientCalls.length, collector.settledClientToolCount);
5292
+ }
5293
+ function initialStepLoopState(messages, instructions) {
5294
+ return {
5295
+ currentMessages: [...messages],
5296
+ responseMessages: [],
5297
+ steps: [],
5298
+ stepUsage: undefined,
5299
+ discardedUsage: undefined,
5300
+ lastFinishReason: "stop",
5301
+ carriedInstructions: instructions,
5302
+ continuationInstructions: undefined
5303
+ };
5304
+ }
5305
+
5306
+ // src/agent-runtime/loop/run-step-port.ts
5307
+ var DEFAULT_IDLE_TIMEOUT_MS = 60000;
5308
+ function resolveIdleTimeoutMs(declared) {
5309
+ return declared === null ? undefined : declared ?? DEFAULT_IDLE_TIMEOUT_MS;
5074
5310
  }
5075
5311
 
5076
5312
  // src/agent-runtime/loop/runtime-control.ts
@@ -5519,9 +5755,6 @@ function createAgentRunOperationLifecycle(config) {
5519
5755
  checkpointStep(step) {
5520
5756
  checkpointedStep = Math.max(checkpointedStep, step);
5521
5757
  },
5522
- resetCheckpointStep() {
5523
- checkpointedStep = -1;
5524
- },
5525
5758
  startCompaction(operationId) {
5526
5759
  return record(AgentRunOperationSchema2.parse({
5527
5760
  operationId,
@@ -5617,6 +5850,7 @@ async function acquireRun(dependencies, input) {
5617
5850
  absorbed: new Map,
5618
5851
  eventsSinceCheckpoint: 0,
5619
5852
  sequence: 0,
5853
+ transientChars: { text: 0, reasoning: 0 },
5620
5854
  settledToolCalls: new Set,
5621
5855
  terminalReason: "success",
5622
5856
  nonModelUsage: input.acceptedRun.usage,
@@ -5699,9 +5933,6 @@ async function beginRunExecution(execution) {
5699
5933
  }), "assistant draft"));
5700
5934
  }
5701
5935
 
5702
- // src/agent-runtime/loop/run-model-attempts.ts
5703
- import { setTimeout as delay } from "node:timers/promises";
5704
-
5705
5936
  // src/agent-runtime/loop/run-model-stream.ts
5706
5937
  async function consumeModelStepStream(input) {
5707
5938
  const { execution, turn, ledger, modelStream, emit } = input;
@@ -5717,6 +5948,7 @@ async function consumeModelStepStream(input) {
5717
5948
  }
5718
5949
  })) {
5719
5950
  idleDeadline.touch();
5951
+ input.onProviderPart?.(part);
5720
5952
  if (input.isDraining()) {
5721
5953
  if (part.type === "finish") {
5722
5954
  const fallbackId = part.response?.id && part.response.id.length > 0 ? part.response.id : acc.result.responseId.length > 0 ? acc.result.responseId : input.callId;
@@ -5788,154 +6020,10 @@ async function consumeModelStepStream(input) {
5788
6020
  return acc.result;
5789
6021
  }
5790
6022
 
5791
- // src/agent-runtime/loop/run-step-prepare.ts
5792
- function buildStepRequest(input) {
5793
- const { prepared } = input;
5794
- return {
5795
- instructions: normalizeAgentInstructions(input.instructions),
5796
- messages: input.messages,
5797
- tools: input.toolSpecs,
5798
- ...prepared?.toolChoice !== undefined && { toolChoice: prepared.toolChoice },
5799
- ...prepared?.responseFormat !== undefined && { responseFormat: prepared.responseFormat },
5800
- ...prepared?.cacheControl !== undefined && { cacheControl: prepared.cacheControl },
5801
- settings: mergeStepCallSettings(undefined, prepared),
5802
- ...prepared?.providerOptions !== undefined && {
5803
- providerOptions: prepared.providerOptions
5804
- },
5805
- ...prepared?.headers !== undefined && { headers: prepared.headers },
5806
- correlation: {
5807
- conversationId: input.conversationId,
5808
- runId: input.runId,
5809
- attemptId: input.attemptId,
5810
- step: input.stepNumber
5811
- }
5812
- };
5813
- }
5814
- async function evaluateStopPolicies(execution, turn, steps) {
5815
- const { config, maxSteps } = execution.dependencies;
5816
- const { state } = execution;
5817
- if (steps.length >= maxSteps) {
5818
- state.terminalPolicyName ??= "max-steps";
5819
- return true;
5820
- }
5821
- for (const policy of config.loop?.stopPolicies ?? []) {
5822
- if (await policy.when({ steps, ...turn.runtimeContext })) {
5823
- state.terminalPolicyName ??= policy.name;
5824
- return true;
5825
- }
5826
- }
5827
- return false;
5828
- }
5829
- function hasPendingApproval(parts) {
5830
- const responded = new Set;
5831
- for (const part of parts) {
5832
- if (part.type === "tool-approval-response")
5833
- responded.add(part.approvalId);
5834
- }
5835
- return parts.some((part) => part.type === "tool-approval-request" && !responded.has(part.approvalId));
5836
- }
5837
- async function evaluateTerminalContinuation(input) {
5838
- const {
5839
- execution,
5840
- lastFinishReason,
5841
- steps,
5842
- continuations,
5843
- maxContinuations,
5844
- attemptSignal
5845
- } = input;
5846
- const { config, now, maxSteps } = execution.dependencies;
5847
- const { state } = execution;
5848
- const acceptTerminal = config.protocol.acceptTerminal;
5849
- if (!acceptTerminal || attemptSignal.aborted || hasPendingApproval(state.parts)) {
5850
- return { action: "stop" };
5851
- }
5852
- const candidateReason = state.terminalPolicyName !== undefined ? "policy_stop" : state.terminalReason !== "success" ? state.terminalReason : lastFinishReason === "stop" ? "success" : lastFinishReason === "error" ? "provider_failure" : "provider_stop";
5853
- if (candidateReason !== "success" && candidateReason !== "policy_stop" && candidateReason !== "provider_stop") {
5854
- return { action: "stop" };
5855
- }
5856
- const candidate = AgentMessageSchema2.parse({
5857
- ...state.assistant,
5858
- status: assistantStatus(candidateReason),
5859
- parts: state.parts,
5860
- updatedAt: now().toISOString()
5861
- });
5862
- const verdict = await acceptTerminal({
5863
- message: candidate,
5864
- reason: candidateReason,
5865
- ...state.terminalPolicyName && { policyName: state.terminalPolicyName },
5866
- steps,
5867
- continuations
5868
- });
5869
- if (verdict === true || typeof verdict === "object" && verdict.action === "accept") {
5870
- state.terminalDecision = "accepted";
5871
- return { action: "stop" };
5872
- }
5873
- if (verdict === false || typeof verdict === "object" && verdict.action === "reject") {
5874
- state.terminalDecision = "rejected";
5875
- state.terminalReason = "output_rejected";
5876
- state.internalCause = new Error("Agent terminal output was rejected by the protocol");
5877
- return { action: "stop" };
5878
- }
5879
- if (continuations >= maxContinuations || steps.length >= maxSteps) {
5880
- state.terminalDecision = "rejected";
5881
- state.terminalReason = "output_rejected";
5882
- state.internalCause = new Error(continuations >= maxContinuations ? `Agent terminal continuation exceeded maxContinuations (${maxContinuations})` : `Agent terminal continuation exceeded maxSteps (${maxSteps})`);
5883
- return { action: "stop" };
5884
- }
5885
- state.terminalDecision = undefined;
5886
- state.terminalPolicyName = undefined;
5887
- return {
5888
- action: "continue",
5889
- message: verdict.message,
5890
- ...verdict.instructions !== undefined && { instructions: verdict.instructions }
5891
- };
5892
- }
5893
-
5894
6023
  // src/agent-runtime/loop/run-model-step.ts
5895
- async function recordCompletedStep(input) {
5896
- const {
5897
- execution,
5898
- stepNumber,
5899
- callId,
5900
- stepModel,
5901
- consumed,
5902
- finishPart,
5903
- toolExecution,
5904
- timings,
5905
- runState,
5906
- emit
5907
- } = input;
5908
- const stepToolCalls = [...consumed.providerToolCalls, ...toolExecution.toolCalls];
5909
- const stepToolResults = [...consumed.providerToolResults, ...toolExecution.toolResults];
5910
- let stepTextOverrides;
5911
- if (execution.dependencies.config.loop?.stepBarriers?.stepText === "after-tools") {
5912
- const flushed = await flushHeldStepTextWithOutcome(execution, false, {
5913
- finishReason: finishPart.finishReason,
5914
- toolCalls: stepToolCalls,
5915
- toolResults: stepToolResults
5916
- });
5917
- if (flushed.segmentOverrides !== undefined) {
5918
- stepTextOverrides = flushed.segmentOverrides;
5919
- }
5920
- }
5921
- const stepUsage = statedUsage(finishPart.usage);
5922
- const { resolvedResponseId, stepResponseMessages, stepResult } = assembleStepResult({
5923
- stepNumber,
5924
- callId,
5925
- model: stepModel,
5926
- consumed,
5927
- finishPart,
5928
- toolExecution,
5929
- timings,
5930
- stepUsage,
5931
- ...stepTextOverrides !== undefined && { stepTextOverrides }
5932
- });
5933
- runState.currentMessages = [...runState.currentMessages, ...stepResponseMessages];
5934
- runState.responseMessages.push(...stepResponseMessages);
5935
- runState.attemptTotalUsage = addUsage(runState.attemptTotalUsage, stepUsage);
5936
- runState.lastFinishReason = finishPart.finishReason;
5937
- runState.steps.push(stepResult);
5938
- await emit({
6024
+ function finishStepEvent(step) {
6025
+ const { consumed, finishPart, stepResult, resolvedResponseId, stepUsage, timings } = step;
6026
+ return {
5939
6027
  type: "finish-step",
5940
6028
  finishReason: finishPart.finishReason,
5941
6029
  ...finishPart.rawFinishReason !== undefined && {
@@ -5955,7 +6043,18 @@ async function recordCompletedStep(input) {
5955
6043
  usage: stepUsage,
5956
6044
  ...finishPart.costDetails !== undefined && { costDetails: finishPart.costDetails },
5957
6045
  timings
6046
+ };
6047
+ }
6048
+ async function settleHeldStepText(execution, input) {
6049
+ if (execution.dependencies.config.loop?.stepBarriers?.stepText !== "after-tools") {
6050
+ return;
6051
+ }
6052
+ const flushed = await flushHeldStepTextWithOutcome(execution, false, {
6053
+ finishReason: input.finishPart.finishReason,
6054
+ toolCalls: [...input.consumed.providerToolCalls, ...input.toolExecution.toolCalls],
6055
+ toolResults: [...input.consumed.providerToolResults, ...input.toolExecution.toolResults]
5958
6056
  });
6057
+ return flushed.segmentOverrides;
5959
6058
  }
5960
6059
  async function openStepStream(execution, driver, request, stepSignal) {
5961
6060
  execution.idleDeadline.start();
@@ -5985,6 +6084,7 @@ async function streamStepWithIsolatedAbort(input) {
5985
6084
  isDraining: input.isDraining,
5986
6085
  onErrorPart: input.onErrorPart,
5987
6086
  onAbandonedUsage: input.onAbandonedUsage,
6087
+ onProviderPart: input.onProviderPart,
5988
6088
  abortStepStream: () => stepAbort.abort(new Error("Agent runtime released step provider stream")),
5989
6089
  modelStream,
5990
6090
  emit: input.emit
@@ -5993,153 +6093,98 @@ async function streamStepWithIsolatedAbort(input) {
5993
6093
  stepLink.release();
5994
6094
  }
5995
6095
  }
5996
- async function executeOneModelStep(input) {
5997
- const {
5998
- execution,
5999
- turn,
6000
- ledger,
6001
- baseMessages,
6002
- attemptSignal,
6003
- emit,
6004
- stepNumber,
6005
- initialInstructions,
6006
- declaredToolNames,
6007
- repairToolCall,
6008
- runState
6009
- } = input;
6010
- const { config, generateId } = execution.dependencies;
6011
- const { state, operationLifecycle } = execution;
6012
- attemptSignal.throwIfAborted();
6013
- await emit({ type: "start-step" });
6014
- const defaultInstructions = runState.continuationInstructions ?? runState.carriedInstructions;
6015
- runState.continuationInstructions = undefined;
6016
- const prepared = await config.loop?.prepareStep?.({
6017
- stepNumber,
6018
- steps: runState.steps,
6019
- messages: runState.currentMessages,
6020
- responseMessages: runState.responseMessages,
6021
- initialMessages: baseMessages,
6022
- initialInstructions,
6023
- instructions: defaultInstructions,
6024
- driver: turn.selectedModel.driver,
6025
- activeTools: declaredToolNames,
6026
- ...turn.runtimeContext
6027
- }) ?? undefined;
6028
- const injected = await input.takeInjectedMessages();
6029
- runState.currentMessages = [
6030
- ...prepared?.messages ?? runState.currentMessages,
6031
- ...injected
6032
- ];
6033
- if (prepared?.instructions !== undefined) {
6034
- runState.carriedInstructions = prepared.instructions;
6035
- }
6036
- const stepInstructions = prepared?.instructions ?? defaultInstructions;
6037
- const { activeNames, specs: toolSpecs } = buildActiveToolSpecs(turn.tools, prepared?.activeTools);
6038
- const baseDriver = prepared?.driver ?? turn.selectedModel.driver;
6039
- const switchedDriver = baseDriver !== turn.selectedModel.driver;
6040
- const stepModel = switchedDriver ? { modelId: baseDriver.modelId, provider: baseDriver.provider } : {
6041
- modelId: turn.selectedModel.descriptor.modelId,
6042
- provider: turn.selectedModel.descriptor.provider
6096
+
6097
+ // src/agent-runtime/loop/run-model-call.ts
6098
+ function startRuntimeCall(execution) {
6099
+ const { state } = execution;
6100
+ return {
6101
+ partStart: state.parts.length,
6102
+ retained: { ...state.transientChars },
6103
+ draining: false,
6104
+ usage: undefined,
6105
+ invokedTool: false
6043
6106
  };
6044
- input.onStepDriver?.(stepModel);
6045
- const callId = generateId();
6046
- await ledger.recordRequest({
6047
- stepNumber,
6048
- attempt: input.providerAttempt,
6049
- modelId: stepModel.modelId,
6050
- instructions: stepInstructions,
6051
- messages: runState.currentMessages
6052
- });
6053
- await operationLifecycle.admitModelRequest(stepNumber, callId);
6054
- const effectiveDriver = execution.invocation ? execution.invocation.wrap(turn.selectedModel, stepNumber, baseDriver) : baseDriver;
6055
- const request = buildStepRequest({
6056
- instructions: stepInstructions,
6057
- messages: runState.currentMessages,
6058
- toolSpecs,
6059
- prepared,
6060
- conversationId: state.run.conversationId,
6061
- runId: state.run.id,
6062
- attemptId: callId,
6063
- stepNumber
6064
- });
6107
+ }
6108
+ async function streamRuntimeCall(input) {
6109
+ const { execution, call, step } = input;
6065
6110
  const stepStartedAt = performance.now();
6066
- const consumed = await streamStepWithIsolatedAbort({
6067
- execution,
6068
- turn,
6069
- ledger,
6070
- effectiveDriver,
6071
- request,
6072
- callId,
6073
- providerAttempt: input.providerAttempt,
6074
- stepStartedAt,
6075
- stepModel,
6076
- attemptSignal,
6077
- isDraining: input.isDraining,
6078
- onErrorPart: input.onErrorPart,
6079
- onAbandonedUsage: input.onAbandonedUsage,
6080
- emit
6111
+ const retrying = () => ({
6112
+ kind: "retrying",
6113
+ ...call.usage !== undefined && { usage: call.usage }
6081
6114
  });
6082
- if (input.isRetrying())
6083
- return "return";
6084
- const responseFinishedAt = performance.now();
6085
- if (!consumed.finishPart) {
6086
- if (attemptSignal.aborted) {
6087
- await emit({ type: "abort" });
6088
- return "return";
6089
- }
6090
- if (consumed.sawErrorPart)
6091
- return "return";
6092
- throw markProviderOrigin(new AgentProviderStreamCutError2("Provider stream ended without a finish event", {
6093
- provider: effectiveDriver.provider
6094
- }));
6095
- }
6096
- const finishPart = consumed.finishPart;
6097
- const unsafeForClientTools = isStepUnsafeForClientTools(finishPart.finishReason, consumed.sawErrorPart);
6098
- const toolStartedAt = performance.now();
6099
- const toolExecution = unsafeForClientTools ? emptyStepToolExecutionResult() : await executeStepToolCalls({
6100
- stepNumber,
6101
- rawCalls: consumed.rawToolCalls,
6102
- tools: turn.tools,
6103
- activeTools: activeNames,
6104
- repairToolCall,
6105
- instructions: request.instructions,
6106
- messages: runState.currentMessages,
6107
- signal: attemptSignal,
6108
- mode: {
6109
- kind: "durable",
6115
+ let consumed;
6116
+ try {
6117
+ consumed = await streamStepWithIsolatedAbort({
6110
6118
  execution,
6111
- toolApproval: turn.toolApproval,
6112
- emit
6119
+ turn: input.turn,
6120
+ ledger: input.ledger,
6121
+ effectiveDriver: step.driver,
6122
+ request: step.request,
6123
+ callId: step.callId,
6124
+ providerAttempt: step.attempt,
6125
+ stepStartedAt,
6126
+ stepModel: step.stepModel,
6127
+ attemptSignal: execution.executionSignal,
6128
+ isDraining: () => call.draining,
6129
+ onErrorPart: async (error) => {
6130
+ if (await step.retryOnFailure(error))
6131
+ call.draining = true;
6132
+ return call.draining;
6133
+ },
6134
+ onAbandonedUsage: (usage) => {
6135
+ call.usage = addUsage(call.usage, usage);
6136
+ },
6137
+ onProviderPart: (part) => {
6138
+ if (providerToolActed(part))
6139
+ call.invokedTool = true;
6140
+ },
6141
+ emit: input.emit
6142
+ });
6143
+ } catch (error) {
6144
+ if (!call.draining || execution.executionSignal.aborted || !hasProviderOrigin(error)) {
6145
+ throw error;
6113
6146
  }
6147
+ return retrying();
6148
+ }
6149
+ if (call.draining)
6150
+ return retrying();
6151
+ return { kind: "finished", consumed, stepStartedAt, responseFinishedAt: performance.now() };
6152
+ }
6153
+ async function withdrawRuntimeCall(execution, call) {
6154
+ const { state } = execution;
6155
+ await execution.operationLifecycle.finish("failed");
6156
+ state.parts.splice(call.partStart);
6157
+ state.stepGuard = { text: "", toolFailed: false, reasoningChars: 0 };
6158
+ resetStepTextTracking(state);
6159
+ state.reasoningPartIndex = undefined;
6160
+ state.reasoningPartIndexes.clear();
6161
+ state.textPartIndex = undefined;
6162
+ state.textPartIndexes.clear();
6163
+ await checkpoint(execution);
6164
+ state.eventsSinceCheckpoint = 0;
6165
+ }
6166
+ async function announceRuntimeRetry(execution, call, attempt) {
6167
+ const { config, publish, now, runtimeEpoch } = execution.dependencies;
6168
+ const { state } = execution;
6169
+ await config.store.appendEvent({
6170
+ conversationId: state.run.conversationId,
6171
+ kind: "retry/started",
6172
+ payload: { attempt }
6114
6173
  });
6115
- const stepFinishedAt = performance.now();
6116
- const toolExecutionMs = unsafeForClientTools ? 0 : Math.max(0, stepFinishedAt - toolStartedAt);
6117
- const timings = buildStepTimings({
6118
- stepStartedAt,
6119
- responseFinishedAt,
6120
- stepFinishedAt,
6121
- firstOutputAt: consumed.firstOutputAt,
6122
- toolExecutionMs,
6123
- outputChunkTimestamps: consumed.outputChunkTimestamps
6124
- });
6125
- await recordCompletedStep({
6126
- execution,
6127
- stepNumber,
6128
- callId,
6129
- stepModel,
6130
- consumed,
6131
- finishPart,
6132
- toolExecution,
6133
- timings,
6134
- runState,
6135
- emit
6174
+ await publish({
6175
+ type: "attempt-reset",
6176
+ conversationId: state.run.conversationId,
6177
+ runId: state.run.id,
6178
+ runtimeEpoch,
6179
+ sequence: transientSequence(state),
6180
+ attempt,
6181
+ withdrawn: {
6182
+ text: state.transientChars.text - call.retained.text,
6183
+ reasoning: state.transientChars.reasoning - call.retained.reasoning
6184
+ },
6185
+ emittedAt: now().toISOString()
6136
6186
  });
6137
- const canContinue = !unsafeForClientTools && toolExecution.clientToolCallCount > 0 && toolExecution.settledClientToolCount === toolExecution.clientToolCallCount;
6138
- if (!canContinue)
6139
- return "break";
6140
- if (await evaluateStopPolicies(execution, turn, runState.steps))
6141
- return "break";
6142
- return "continue";
6187
+ state.transientChars = { ...call.retained };
6143
6188
  }
6144
6189
 
6145
6190
  // src/agent-runtime/loop/run-provider-ledger.ts
@@ -6251,85 +6296,112 @@ async function createRunProviderLedger(input) {
6251
6296
  };
6252
6297
  }
6253
6298
 
6254
- // src/agent-runtime/loop/run-model-attempts.ts
6255
- var DEFAULT_MAX_CONTINUATIONS = 3;
6256
- async function takeInjectedMessages(context) {
6257
- const { execution, turn, loop } = context;
6299
+ // src/agent-runtime/loop/run-step-prepare.ts
6300
+ function buildStepRequest(input) {
6301
+ const { prepared } = input;
6302
+ return {
6303
+ instructions: normalizeAgentInstructions(input.instructions),
6304
+ messages: input.messages,
6305
+ tools: input.toolSpecs,
6306
+ ...prepared?.toolChoice !== undefined && { toolChoice: prepared.toolChoice },
6307
+ ...prepared?.responseFormat !== undefined && { responseFormat: prepared.responseFormat },
6308
+ ...prepared?.cacheControl !== undefined && { cacheControl: prepared.cacheControl },
6309
+ settings: mergeStepCallSettings(undefined, prepared),
6310
+ ...prepared?.providerOptions !== undefined && {
6311
+ providerOptions: prepared.providerOptions
6312
+ },
6313
+ ...prepared?.headers !== undefined && { headers: prepared.headers },
6314
+ correlation: {
6315
+ conversationId: input.conversationId,
6316
+ runId: input.runId,
6317
+ attemptId: input.attemptId,
6318
+ step: input.stepNumber
6319
+ }
6320
+ };
6321
+ }
6322
+ async function evaluateStopPolicies(execution, turn, steps) {
6323
+ const { config, maxSteps } = execution.dependencies;
6258
6324
  const { state } = execution;
6259
- const taken = execution.dependencies.injection?.take(execution.input.key, state.run.id) ?? [];
6260
- if (taken.length === 0)
6261
- return [];
6262
- loop.takenThisAttempt.push(...taken);
6263
- const messages = [];
6264
- for (const entry of taken) {
6265
- messages.push(...await turn.projection.projectInputs([entry.input]));
6266
- const ids = state.absorbed.get(entry.runId) ?? [];
6267
- ids.push(entry.input.id);
6268
- state.absorbed.set(entry.runId, ids);
6325
+ if (steps.length >= maxSteps) {
6326
+ state.terminalPolicyName ??= "max-steps";
6327
+ return true;
6269
6328
  }
6270
- return messages;
6329
+ for (const policy of config.loop?.stopPolicies ?? []) {
6330
+ if (await policy.when({ steps, ...turn.runtimeContext })) {
6331
+ state.terminalPolicyName ??= policy.name;
6332
+ return true;
6333
+ }
6334
+ }
6335
+ return false;
6271
6336
  }
6272
- async function retryAfterProviderError(context, attempt, error, attemptTotalUsage) {
6273
- const { execution, loop } = context;
6274
- const { config, injection } = execution.dependencies;
6275
- const { state, executionSignal } = execution;
6276
- const retry = config.loop?.retry;
6277
- if (executionSignal.aborted || failureThisRuntimeOwns(error) !== undefined) {
6278
- return false;
6337
+ function hasPendingApproval(parts) {
6338
+ const responded = new Set;
6339
+ for (const part of parts) {
6340
+ if (part.type === "tool-approval-response")
6341
+ responded.add(part.approvalId);
6279
6342
  }
6280
- if (attempt.retryDecided)
6281
- return attempt.retrying;
6282
- if (!retry)
6283
- return false;
6284
- attempt.retryDecided = true;
6285
- const invokedTool = state.parts.slice(attempt.attemptPartStart).some((candidate) => candidate.type === "tool-call" || candidate.type === "tool-result");
6286
- const failure = classifyProviderFailure2(error);
6287
- const decision = invokedTool ? { retry: false, delayMs: 0 } : await recordAgentRetryDecision2({
6288
- store: config.store,
6289
- conversationId: state.run.conversationId,
6290
- attempt: loop.retryAttempt,
6291
- failure,
6292
- policy: retry,
6293
- elapsedMs: Math.max(0, performance.now() - loop.retryWindowStart)
6343
+ return parts.some((part) => part.type === "tool-approval-request" && !responded.has(part.approvalId));
6344
+ }
6345
+ async function evaluateTerminalContinuation(input) {
6346
+ const {
6347
+ execution,
6348
+ lastFinishReason,
6349
+ steps,
6350
+ continuations,
6351
+ maxContinuations,
6352
+ attemptSignal
6353
+ } = input;
6354
+ const { config, now, maxSteps } = execution.dependencies;
6355
+ const { state } = execution;
6356
+ const acceptTerminal = config.protocol.acceptTerminal;
6357
+ if (!acceptTerminal || attemptSignal.aborted || hasPendingApproval(state.parts)) {
6358
+ return { action: "stop" };
6359
+ }
6360
+ const candidateReason = state.terminalPolicyName !== undefined ? "policy_stop" : state.terminalReason !== "success" ? state.terminalReason : lastFinishReason === "stop" ? "success" : lastFinishReason === "error" ? "provider_failure" : "provider_stop";
6361
+ if (candidateReason !== "success" && candidateReason !== "policy_stop" && candidateReason !== "provider_stop") {
6362
+ return { action: "stop" };
6363
+ }
6364
+ const candidate = AgentMessageSchema2.parse({
6365
+ ...state.assistant,
6366
+ status: assistantStatus(candidateReason),
6367
+ parts: state.parts,
6368
+ updatedAt: now().toISOString()
6294
6369
  });
6295
- if (!decision.retry)
6296
- return false;
6297
- await execution.operationLifecycle.finish("failed");
6298
- if (state.modelUsage !== undefined) {
6299
- state.abandonedUsage = state.abandonedUsage ? addUsage(state.abandonedUsage, state.modelUsage) : state.modelUsage;
6300
- state.modelUsage = undefined;
6301
- state.usage = runUsage(state);
6370
+ const verdict = await acceptTerminal({
6371
+ message: candidate,
6372
+ reason: candidateReason,
6373
+ ...state.terminalPolicyName && { policyName: state.terminalPolicyName },
6374
+ steps,
6375
+ continuations
6376
+ });
6377
+ if (verdict === true || typeof verdict === "object" && verdict.action === "accept") {
6378
+ state.terminalDecision = "accepted";
6379
+ return { action: "stop" };
6302
6380
  }
6303
- state.parts.splice(attempt.attemptPartStart);
6304
- state.reasoningPartIndex = undefined;
6305
- state.reasoningPartIndexes.clear();
6306
- state.textPartIndex = undefined;
6307
- state.textPartIndexes.clear();
6308
- for (const entry of loop.takenThisAttempt) {
6309
- injection?.offer(execution.input.key, entry);
6310
- const ids = state.absorbed.get(entry.runId);
6311
- if (ids) {
6312
- const kept = ids.filter((id) => id !== entry.input.id);
6313
- if (kept.length === 0)
6314
- state.absorbed.delete(entry.runId);
6315
- else
6316
- state.absorbed.set(entry.runId, kept);
6317
- }
6381
+ if (verdict === false || typeof verdict === "object" && verdict.action === "reject") {
6382
+ state.terminalDecision = "rejected";
6383
+ state.terminalReason = "output_rejected";
6384
+ state.internalCause = new Error("Agent terminal output was rejected by the protocol");
6385
+ return { action: "stop" };
6318
6386
  }
6319
- loop.takenThisAttempt = [];
6320
- await checkpoint(execution);
6321
- state.eventsSinceCheckpoint = 0;
6322
- attempt.retrying = true;
6323
- attempt.draining = true;
6324
- attempt.retryDelayMs = decision.delayMs;
6325
- attempt.discardReason = failure.reason;
6326
- if (attemptTotalUsage !== undefined) {
6327
- attempt.discardUsage = attempt.discardUsage ? addUsage(attempt.discardUsage, attemptTotalUsage) : attemptTotalUsage;
6387
+ if (continuations >= maxContinuations || steps.length >= maxSteps) {
6388
+ state.terminalDecision = "rejected";
6389
+ state.terminalReason = "output_rejected";
6390
+ state.internalCause = new Error(continuations >= maxContinuations ? `Agent terminal continuation exceeded maxContinuations (${maxContinuations})` : `Agent terminal continuation exceeded maxSteps (${maxSteps})`);
6391
+ return { action: "stop" };
6328
6392
  }
6329
- return true;
6393
+ state.terminalDecision = undefined;
6394
+ state.terminalPolicyName = undefined;
6395
+ return {
6396
+ action: "continue",
6397
+ message: verdict.message,
6398
+ ...verdict.instructions !== undefined && { instructions: verdict.instructions }
6399
+ };
6330
6400
  }
6331
- async function dispatchLoopEvent(context, scope, part) {
6332
- const { execution } = context;
6401
+
6402
+ // src/agent-runtime/loop/run-model-steps.ts
6403
+ var DEFAULT_MAX_CONTINUATIONS = 3;
6404
+ async function dispatchLoopEvent(execution, scope, part) {
6333
6405
  const { checkpointEveryEvents } = execution.dependencies;
6334
6406
  const { state, operationLifecycle } = execution;
6335
6407
  state.eventsSinceCheckpoint += 1;
@@ -6353,113 +6425,139 @@ async function dispatchLoopEvent(context, scope, part) {
6353
6425
  operationLifecycle.checkpointStep(state.step - 1);
6354
6426
  }
6355
6427
  }
6356
- async function runSingleAttempt(context, attempt, attemptSignal) {
6357
- const { execution, turn, ledger } = context;
6358
- const { config } = execution.dependencies;
6428
+ async function takeInjectedMessages(execution, turn) {
6429
+ const { state } = execution;
6430
+ const taken = execution.dependencies.injection?.take(execution.input.key, state.run.id) ?? [];
6431
+ const messages = [];
6432
+ for (const entry of taken) {
6433
+ messages.push(...await turn.projection.projectInputs([entry.input]));
6434
+ const ids = state.absorbed.get(entry.runId) ?? [];
6435
+ ids.push(entry.input.id);
6436
+ state.absorbed.set(entry.runId, ids);
6437
+ }
6438
+ return messages;
6439
+ }
6440
+ function createRuntimeStepPort(execution, turn, ledger, baseMessages) {
6441
+ const { config, generateId } = execution.dependencies;
6442
+ const { state, operationLifecycle, executionSignal } = execution;
6359
6443
  const scope = {
6360
6444
  selectedModel: turn.selectedModel,
6361
6445
  ledger,
6362
- providerAttempt: attempt.providerAttempt
6446
+ providerAttempt: 1
6363
6447
  };
6364
- const emit = (event) => dispatchLoopEvent(context, scope, event);
6365
- const initialInstructions = turn.projection.withCarriedSystem(turn.prompt.instructions);
6366
- const declaredToolNames = Object.keys(turn.tools);
6367
- const repairToolCall = chainRepairHooks(config.loop?.repairToolCall, deferredToolRepair(turn.tools));
6448
+ const emit = (event) => dispatchLoopEvent(execution, scope, event);
6449
+ let call = startRuntimeCall(execution);
6368
6450
  const maxContinuations = config.loop?.maxContinuations ?? DEFAULT_MAX_CONTINUATIONS;
6369
6451
  let continuations = 0;
6370
- const runState = {
6371
- currentMessages: [...context.baseMessages],
6372
- responseMessages: [],
6373
- steps: [],
6374
- attemptTotalUsage: undefined,
6375
- lastFinishReason: "stop",
6376
- continuationInstructions: undefined,
6377
- carriedInstructions: initialInstructions
6378
- };
6379
- for (let stepNumber = 0;; stepNumber += 1) {
6380
- let stepOutcome;
6381
- try {
6382
- stepOutcome = await executeOneModelStep({
6383
- execution,
6384
- turn,
6385
- ledger,
6386
- baseMessages: context.baseMessages,
6387
- providerAttempt: attempt.providerAttempt,
6388
- isRetrying: () => attempt.retrying,
6389
- isDraining: () => attempt.draining,
6390
- onErrorPart: (error) => retryAfterProviderError(context, attempt, error, runState.attemptTotalUsage),
6391
- onAbandonedUsage: (usage) => {
6392
- attempt.discardUsage = attempt.discardUsage ? addUsage(attempt.discardUsage, usage) : usage;
6393
- },
6394
- onStepDriver: (stepModel) => {
6395
- scope.stepModel = stepModel;
6396
- },
6397
- takeInjectedMessages: () => takeInjectedMessages(context),
6398
- attemptSignal,
6399
- emit,
6452
+ const retry = config.loop?.retry;
6453
+ const onAttemptDiscarded = config.loop?.onAttemptDiscarded;
6454
+ const port = {
6455
+ tools: turn.tools,
6456
+ baseDriver: turn.selectedModel.driver,
6457
+ initialMessages: baseMessages,
6458
+ initialInstructions: turn.projection.withCarriedSystem(turn.prompt.instructions),
6459
+ signal: executionSignal,
6460
+ repairToolCall: config.loop?.repairToolCall,
6461
+ retry,
6462
+ ...onAttemptDiscarded !== undefined && { onAttemptDiscarded },
6463
+ toolMode: { kind: "durable", execution, toolApproval: turn.toolApproval, emit },
6464
+ startStep: () => emit({ type: "start-step" }),
6465
+ prepareStep: async (input) => await config.loop?.prepareStep?.({ ...input, ...turn.runtimeContext }) ?? undefined,
6466
+ takeInjectedMessages: () => takeInjectedMessages(execution, turn),
6467
+ stepModel: (driver) => {
6468
+ const stepModel = driver !== turn.selectedModel.driver ? { modelId: driver.modelId, provider: driver.provider } : {
6469
+ modelId: turn.selectedModel.descriptor.modelId,
6470
+ provider: turn.selectedModel.descriptor.provider
6471
+ };
6472
+ scope.stepModel = stepModel;
6473
+ return stepModel;
6474
+ },
6475
+ newCallId: generateId,
6476
+ openCall: async ({
6477
+ stepNumber,
6478
+ attempt,
6479
+ callId,
6480
+ stepModel,
6481
+ driver,
6482
+ instructions,
6483
+ messages
6484
+ }) => {
6485
+ call = startRuntimeCall(execution);
6486
+ scope.providerAttempt = attempt;
6487
+ await ledger.recordRequest({
6400
6488
  stepNumber,
6401
- initialInstructions,
6402
- declaredToolNames,
6403
- repairToolCall,
6404
- runState
6489
+ attempt,
6490
+ modelId: stepModel.modelId,
6491
+ instructions,
6492
+ messages
6405
6493
  });
6406
- } catch (error) {
6407
- if (hasProviderOrigin(error)) {
6408
- const retried = await retryAfterProviderError(context, attempt, error, runState.attemptTotalUsage);
6409
- if (retried)
6410
- return;
6494
+ await operationLifecycle.admitModelRequest(stepNumber, callId);
6495
+ return execution.invocation ? execution.invocation.wrap(turn.selectedModel, stepNumber, driver) : driver;
6496
+ },
6497
+ buildRequest: ({ prepared, instructions, messages, specs, callId, stepNumber }) => buildStepRequest({
6498
+ instructions,
6499
+ messages,
6500
+ toolSpecs: specs,
6501
+ prepared,
6502
+ conversationId: state.run.conversationId,
6503
+ runId: state.run.id,
6504
+ attemptId: callId,
6505
+ stepNumber
6506
+ }),
6507
+ streamCall: (step) => streamRuntimeCall({ execution, turn, ledger, call, step, emit }),
6508
+ callInvokedTool: () => call.invokedTool,
6509
+ missingFinish: async (consumed, driver) => {
6510
+ if (executionSignal.aborted) {
6511
+ await emit({ type: "abort" });
6512
+ return "ended";
6411
6513
  }
6412
- throw error;
6413
- }
6414
- if (stepOutcome === "return")
6514
+ if (consumed.sawErrorPart)
6515
+ return "ended";
6516
+ throw markProviderOrigin(new AgentProviderStreamCutError2("Provider stream ended without a finish event", {
6517
+ provider: driver.provider
6518
+ }));
6519
+ },
6520
+ decideRetry: async ({ error, attempt, failure, elapsedMs }) => retry && failureThisRuntimeOwns(error) === undefined ? recordAgentRetryDecision2({
6521
+ store: config.store,
6522
+ conversationId: state.run.conversationId,
6523
+ attempt,
6524
+ failure,
6525
+ policy: retry,
6526
+ elapsedMs
6527
+ }) : { retry: false, delayMs: 0 },
6528
+ discardCall: () => withdrawRuntimeCall(execution, call),
6529
+ announceDiscard: async () => {
6415
6530
  return;
6416
- if (stepOutcome === "continue")
6417
- continue;
6418
- const terminalVerdict = await evaluateTerminalContinuation({
6419
- execution,
6420
- lastFinishReason: runState.lastFinishReason,
6421
- steps: runState.steps,
6422
- continuations,
6423
- maxContinuations,
6424
- attemptSignal
6425
- });
6426
- if (terminalVerdict.action === "continue") {
6427
- continuations += 1;
6428
- runState.currentMessages = [...runState.currentMessages, terminalVerdict.message];
6429
- runState.responseMessages.push(terminalVerdict.message);
6430
- runState.continuationInstructions = terminalVerdict.instructions;
6431
- continue;
6531
+ },
6532
+ announceRetry: ({ attempt }) => announceRuntimeRetry(execution, call, attempt + 1),
6533
+ refuseRetry: ({ error }) => error,
6534
+ stepTextOverrides: (input) => settleHeldStepText(execution, input),
6535
+ finishStep: (step) => emit(finishStepEvent(step)),
6536
+ shouldStop: (steps) => evaluateStopPolicies(execution, turn, steps),
6537
+ afterLastStep: async (loopState) => {
6538
+ const verdict = await evaluateTerminalContinuation({
6539
+ execution,
6540
+ lastFinishReason: loopState.lastFinishReason,
6541
+ steps: loopState.steps,
6542
+ continuations,
6543
+ maxContinuations,
6544
+ attemptSignal: executionSignal
6545
+ });
6546
+ if (verdict.action === "continue")
6547
+ continuations += 1;
6548
+ return verdict;
6432
6549
  }
6433
- break;
6434
- }
6435
- await emit({
6436
- type: "finish",
6437
- finishReason: runState.lastFinishReason,
6438
- totalUsage: runState.attemptTotalUsage ?? unknownUsage()
6439
- });
6440
- }
6441
- async function runModelAttempts(execution, turn) {
6442
- const { config, publish, now } = execution.dependencies;
6443
- const { state } = execution;
6444
- const loop = {
6445
- retryAttempt: 1,
6446
- retryWindowStart: performance.now(),
6447
- takenThisAttempt: []
6448
6550
  };
6551
+ return { port, emit };
6552
+ }
6553
+ async function runModelSteps(execution, turn) {
6449
6554
  const ledger = await createRunProviderLedger({
6450
- store: config.store,
6451
- state,
6555
+ store: execution.dependencies.config.store,
6556
+ state: execution.state,
6452
6557
  selectedModel: turn.selectedModel,
6453
6558
  audited: execution.invocation !== undefined
6454
6559
  });
6455
6560
  const baseMessages = [...turn.history];
6456
- const context = {
6457
- execution,
6458
- turn,
6459
- loop,
6460
- ledger,
6461
- baseMessages
6462
- };
6463
6561
  const continuationScope = {
6464
6562
  selectedModel: turn.selectedModel,
6465
6563
  ledger,
@@ -6471,54 +6569,17 @@ async function runModelAttempts(execution, turn) {
6471
6569
  toolApproval: turn.toolApproval,
6472
6570
  messages: baseMessages,
6473
6571
  signal: execution.executionSignal,
6474
- emit: (event) => dispatchLoopEvent(context, continuationScope, event)
6572
+ emit: (event) => dispatchLoopEvent(execution, continuationScope, event)
6573
+ });
6574
+ const { port, emit } = createRuntimeStepPort(execution, turn, ledger, baseMessages);
6575
+ const state = initialStepLoopState(baseMessages, port.initialInstructions);
6576
+ if (await runModelStepLoop(port, state) === "ended")
6577
+ return;
6578
+ await emit({
6579
+ type: "finish",
6580
+ finishReason: state.lastFinishReason,
6581
+ totalUsage: state.stepUsage ?? unknownUsage()
6475
6582
  });
6476
- for (;; ) {
6477
- const attempt = {
6478
- providerAttempt: loop.retryAttempt,
6479
- attemptPartStart: state.parts.length,
6480
- retryDecided: false,
6481
- retrying: false,
6482
- draining: false,
6483
- retryDelayMs: 0
6484
- };
6485
- await runSingleAttempt(context, attempt, execution.executionSignal);
6486
- if (!attempt.retrying || execution.executionSignal.aborted)
6487
- break;
6488
- await config.loop?.onAttemptDiscarded?.({
6489
- attempt: attempt.providerAttempt,
6490
- reason: attempt.discardReason ?? "unknown",
6491
- ...attempt.discardUsage !== undefined && { usage: attempt.discardUsage }
6492
- });
6493
- if (attempt.retryDelayMs > 0) {
6494
- await delay(attempt.retryDelayMs, undefined, { signal: execution.executionSignal });
6495
- }
6496
- if (execution.executionSignal.aborted)
6497
- break;
6498
- loop.retryAttempt += 1;
6499
- await config.store.appendEvent({
6500
- conversationId: state.run.conversationId,
6501
- kind: "retry/started",
6502
- payload: { attempt: loop.retryAttempt }
6503
- });
6504
- state.step = 0;
6505
- execution.operationLifecycle.resetCheckpointStep();
6506
- state.lastPromptTokens = { provenance: "unavailable" };
6507
- state.terminalDecision = undefined;
6508
- state.terminalPolicyName = undefined;
6509
- state.textPartIndex = undefined;
6510
- state.stepGuard = { text: "", toolFailed: false, reasoningChars: 0 };
6511
- resetStepTextTracking(state);
6512
- await publish({
6513
- type: "attempt-reset",
6514
- conversationId: state.run.conversationId,
6515
- runId: state.run.id,
6516
- runtimeEpoch: execution.dependencies.runtimeEpoch,
6517
- sequence: transientSequence(state),
6518
- attempt: loop.retryAttempt,
6519
- emittedAt: now().toISOString()
6520
- });
6521
- }
6522
6583
  }
6523
6584
 
6524
6585
  // src/agent-runtime/loop/run-terminal.ts
@@ -6688,7 +6749,7 @@ async function commitRunTerminal(execution) {
6688
6749
  import { createHash as createHash4 } from "node:crypto";
6689
6750
 
6690
6751
  // src/agent-runtime/loop/state-slots.ts
6691
- import { z as z7 } from "zod";
6752
+ import { z as z6 } from "zod";
6692
6753
  function defineStateSlot2(input) {
6693
6754
  if (input.name.length === 0)
6694
6755
  throw new TypeError("State slot name must not be empty");
@@ -6703,11 +6764,11 @@ function defineStateSlot2(input) {
6703
6764
  ...input.description && { description: input.description }
6704
6765
  };
6705
6766
  }
6706
- var StateSetPayloadSchema = z7.object({
6707
- name: z7.string().min(1),
6708
- version: z7.int().positive(),
6709
- value: z7.json(),
6710
- actor: z7.enum(["agent", "human", "system"])
6767
+ var StateSetPayloadSchema = z6.object({
6768
+ name: z6.string().min(1),
6769
+ version: z6.int().positive(),
6770
+ value: z6.json(),
6771
+ actor: z6.enum(["agent", "human", "system"])
6711
6772
  }).strict();
6712
6773
  function slotRegistry(definitions) {
6713
6774
  const result = new Map;
@@ -6789,18 +6850,18 @@ function renderAgentStateSlots2(values) {
6789
6850
  var agentGoalStateSlot2 = defineStateSlot2({
6790
6851
  name: "goal",
6791
6852
  description: "The durable objective and lifecycle of this conversation.",
6792
- schema: z7.object({
6793
- objective: z7.string().min(1),
6794
- status: z7.enum(["active", "complete", "blocked"])
6853
+ schema: z6.object({
6854
+ objective: z6.string().min(1),
6855
+ status: z6.enum(["active", "complete", "blocked"])
6795
6856
  }).strict()
6796
6857
  });
6797
6858
  var agentTodoStateSlot2 = defineStateSlot2({
6798
6859
  name: "todo",
6799
6860
  description: "The durable ordered work plan for this conversation.",
6800
- schema: z7.object({
6801
- items: z7.array(z7.object({
6802
- step: z7.string().min(1),
6803
- status: z7.enum(["pending", "in_progress", "completed"])
6861
+ schema: z6.object({
6862
+ items: z6.array(z6.object({
6863
+ step: z6.string().min(1),
6864
+ status: z6.enum(["pending", "in_progress", "completed"])
6804
6865
  }).strict())
6805
6866
  }).strict()
6806
6867
  });
@@ -7178,7 +7239,7 @@ function createRunExecutor(dependencies) {
7178
7239
  execution.invocation = await beginAgentInvocation(invocations.ledger, dependencies.config.store, { run: execution.state.run, trace }, input.context);
7179
7240
  }
7180
7241
  const turn = await prepareTurn(execution);
7181
- await runModelAttempts(execution, turn);
7242
+ await runModelSteps(execution, turn);
7182
7243
  await settleStreamOutcome(execution);
7183
7244
  } catch (error) {
7184
7245
  await classifyRunFailure(execution, error);
@@ -7210,8 +7271,7 @@ function createRunExecutor(dependencies) {
7210
7271
  function resolveLoopLimits(config) {
7211
7272
  const checkpointEveryEvents = config.loop?.checkpointEveryEvents ?? 20;
7212
7273
  const maxSteps = config.loop?.maxSteps ?? 50;
7213
- const declaredIdleTimeoutMs = config.loop?.idleTimeoutMs;
7214
- const idleTimeoutMs = declaredIdleTimeoutMs === null ? undefined : declaredIdleTimeoutMs ?? 60000;
7274
+ const idleTimeoutMs = resolveIdleTimeoutMs(config.loop?.idleTimeoutMs);
7215
7275
  const declaredMaxDurationMs = config.loop?.maxDurationMs;
7216
7276
  const maxDurationMs = declaredMaxDurationMs === null ? undefined : declaredMaxDurationMs;
7217
7277
  const stepSpendTimeoutMs = config.stepSpendTimeoutMs ?? DEFAULT_STEP_SPEND_TIMEOUT_MS;
@@ -7579,7 +7639,20 @@ function handOffToCoordinator(state, submission, acceptedRun) {
7579
7639
  }
7580
7640
 
7581
7641
  // src/agent-runtime/loop/runtime.ts
7642
+ function assertRuntimeComposition(config) {
7643
+ const missing = [
7644
+ typeof config.protocol === "object" && config.protocol !== null ? undefined : "protocol",
7645
+ typeof config.store === "object" && config.store !== null ? undefined : "store",
7646
+ typeof config.models?.resolve === "function" ? undefined : "models.resolve",
7647
+ typeof config.prompt === "function" ? undefined : "prompt",
7648
+ typeof config.tools === "function" ? undefined : "tools"
7649
+ ].filter((name) => name !== undefined);
7650
+ if (missing.length > 0) {
7651
+ throw new TypeError(`createAgentRuntime: missing ${missing.join(", ")}`);
7652
+ }
7653
+ }
7582
7654
  function createAgentRuntime2(config) {
7655
+ assertRuntimeComposition(config);
7583
7656
  assertNonNegativeSafeInteger("loop.maxContinuations", config.loop?.maxContinuations, RangeError);
7584
7657
  const state = createAgentRuntimeState(config);
7585
7658
  return {
@@ -7594,9 +7667,9 @@ function createAgentRuntime2(config) {
7594
7667
  }
7595
7668
 
7596
7669
  // src/agent-runtime/prompt.ts
7597
- import { z as z8 } from "zod";
7598
- var AgentTokenCountSchema2 = z8.object({
7599
- value: z8.int().nonnegative().optional(),
7670
+ import { z as z7 } from "zod";
7671
+ var AgentTokenCountSchema2 = z7.object({
7672
+ value: z7.int().nonnegative().optional(),
7600
7673
  provenance: AgentProvenanceSchema2.extract([
7601
7674
  "measured",
7602
7675
  "computed",
@@ -7716,7 +7789,7 @@ function knownValue(value) {
7716
7789
  }
7717
7790
  function composeAgentPrompt2(sections) {
7718
7791
  return async (options) => {
7719
- const event = z8.enum(["session.started", "turn.started"]).parse(options.event ?? "turn.started");
7792
+ const event = z7.enum(["session.started", "turn.started"]).parse(options.event ?? "turn.started");
7720
7793
  const rendered = [];
7721
7794
  let systemTotal = 0;
7722
7795
  let userTotal = 0;
@@ -7809,4 +7882,4 @@ function composeAgentPrompt2(sections) {
7809
7882
  };
7810
7883
  }
7811
7884
 
7812
- export { AgentContextOverflowError2, unknownUsage, statedUsage, projectAgentHistoryDetailed2, projectAgentHistory2, createAgentSessionCoordinator2, registerDeferredToolRepair, deferredToolRepair, markDeferredRepairWrapper, chainRepairHooks, registerDeferredToolCatalog, deferredToolCatalog, repairedSearchCall, InvocationPayloadTooLargeError2, markProviderOrigin, hasProviderOrigin, currentModelInvocationAttempt2, consumeStandaloneDriverStream, createModelInvocationLedger2, createAgentToolFenceLifecycle2, AgentModelFinishReasonSchema, AgentModelCostDetailsSchema, AgentStepTimingsSchema, AgentStepSpendPhaseSchema2, AgentStepSpendProviderSchema, AgentStepSpendSchema2, assertAgentRetryPolicy, resolveAgentRetryDecision, recordAgentRetryDecision2, AgentToolApprovalError2, AgentInvalidToolApprovalSignatureError2, AgentToolCallNotFoundForApprovalError2, AgentStepBarrierError2, assertStandaloneStepBarriers, createToolDependencyResolver2, buildActiveToolSpecs, mergeStepCallSettings, isStepUnsafeForClientTools, buildStepTimings, assembleStepResult, AgentUnknownToolError2, AgentInvalidToolInputError2, emptyStepToolExecutionResult, executeStepToolCalls, defineStateSlot2, createAgentStateSlotStore2, renderAgentStateSlots2, agentGoalStateSlot2, agentTodoStateSlot2, createAgentRuntime2, AgentTokenCountSchema2, selectAgentHistory2, composeAgentPrompt2 };
7885
+ export { AgentContextOverflowError2, unknownUsage, statedUsage, projectAgentHistoryDetailed2, projectAgentHistory2, createAgentSessionCoordinator2, InvocationPayloadTooLargeError2, markProviderOrigin, hasProviderOrigin, currentModelInvocationAttempt2, providerToolActed, consumeStandaloneDriverStream, createModelInvocationLedger2, createAgentToolFenceLifecycle2, AgentModelFinishReasonSchema, AgentModelCostDetailsSchema, AgentStepTimingsSchema, AgentStepSpendPhaseSchema2, AgentStepSpendProviderSchema, AgentStepSpendSchema2, assertAgentRetryPolicy, resolveAgentRetryDecision, recordAgentRetryDecision2, AgentToolApprovalError2, AgentInvalidToolApprovalSignatureError2, AgentToolCallNotFoundForApprovalError2, mergeStepCallSettings, AgentStepBarrierError2, assertStandaloneStepBarriers, createToolDependencyResolver2, AgentUnknownToolError2, AgentInvalidToolInputError2, runModelStepLoop, initialStepLoopState, resolveIdleTimeoutMs, defineStateSlot2, createAgentStateSlotStore2, renderAgentStateSlots2, agentGoalStateSlot2, agentTodoStateSlot2, createAgentRuntime2, AgentTokenCountSchema2, selectAgentHistory2, composeAgentPrompt2 };