stitchkit 0.135.0 → 0.136.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (380) hide show
  1. package/CHANGELOG.md +117 -0
  2. package/README.md +25 -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/image-input.d.ts +10 -3
  20. package/dist/agent-executor/image-input.d.ts.map +1 -1
  21. package/dist/agent-executor/testing/replay-scenarios.d.ts.map +1 -1
  22. package/dist/agent-executor/testing/replay-transcript.d.ts.map +1 -1
  23. package/dist/agent-runtime/browser/browser-control-contract.d.ts +4 -0
  24. package/dist/agent-runtime/browser/browser-control-contract.d.ts.map +1 -1
  25. package/dist/agent-runtime/browser/control-schema.d.ts +4 -0
  26. package/dist/agent-runtime/browser/control-schema.d.ts.map +1 -1
  27. package/dist/agent-runtime/browser/control-view.d.ts.map +1 -1
  28. package/dist/agent-runtime/event-schema.d.ts +16 -3
  29. package/dist/agent-runtime/event-schema.d.ts.map +1 -1
  30. package/dist/agent-runtime/loop/deferred-tools.d.ts.map +1 -1
  31. package/dist/agent-runtime/loop/invocation-payload.d.ts.map +1 -1
  32. package/dist/agent-runtime/loop/invocation-stream.d.ts +9 -1
  33. package/dist/agent-runtime/loop/invocation-stream.d.ts.map +1 -1
  34. package/dist/agent-runtime/loop/provider-stream-parts.d.ts +6 -0
  35. package/dist/agent-runtime/loop/provider-stream-parts.d.ts.map +1 -1
  36. package/dist/agent-runtime/loop/provider-stream-segments.d.ts +1 -1
  37. package/dist/agent-runtime/loop/provider-stream-segments.d.ts.map +1 -1
  38. package/dist/agent-runtime/loop/run-acquisition.d.ts.map +1 -1
  39. package/dist/agent-runtime/loop/run-approval-signature.d.ts +34 -0
  40. package/dist/agent-runtime/loop/run-approval-signature.d.ts.map +1 -0
  41. package/dist/agent-runtime/loop/run-approval.d.ts +0 -28
  42. package/dist/agent-runtime/loop/run-approval.d.ts.map +1 -1
  43. package/dist/agent-runtime/loop/run-complete-port.d.ts +24 -0
  44. package/dist/agent-runtime/loop/run-complete-port.d.ts.map +1 -0
  45. package/dist/agent-runtime/loop/run-complete-stream.d.ts +7 -2
  46. package/dist/agent-runtime/loop/run-complete-stream.d.ts.map +1 -1
  47. package/dist/agent-runtime/loop/run-complete-types.d.ts +14 -1
  48. package/dist/agent-runtime/loop/run-complete-types.d.ts.map +1 -1
  49. package/dist/agent-runtime/loop/run-complete.d.ts +2 -2
  50. package/dist/agent-runtime/loop/run-complete.d.ts.map +1 -1
  51. package/dist/agent-runtime/loop/run-execution-state.d.ts +8 -0
  52. package/dist/agent-runtime/loop/run-execution-state.d.ts.map +1 -1
  53. package/dist/agent-runtime/loop/run-model-call.d.ts +44 -0
  54. package/dist/agent-runtime/loop/run-model-call.d.ts.map +1 -0
  55. package/dist/agent-runtime/loop/run-model-step.d.ts +25 -28
  56. package/dist/agent-runtime/loop/run-model-step.d.ts.map +1 -1
  57. package/dist/agent-runtime/loop/run-model-steps.d.ts +6 -0
  58. package/dist/agent-runtime/loop/run-model-steps.d.ts.map +1 -0
  59. package/dist/agent-runtime/loop/run-model-stream.d.ts +3 -1
  60. package/dist/agent-runtime/loop/run-model-stream.d.ts.map +1 -1
  61. package/dist/agent-runtime/loop/run-operation-lifecycle.d.ts +0 -2
  62. package/dist/agent-runtime/loop/run-operation-lifecycle.d.ts.map +1 -1
  63. package/dist/agent-runtime/loop/run-step-loop.d.ts +19 -0
  64. package/dist/agent-runtime/loop/run-step-loop.d.ts.map +1 -0
  65. package/dist/agent-runtime/loop/run-step-port.d.ts +175 -0
  66. package/dist/agent-runtime/loop/run-step-port.d.ts.map +1 -0
  67. package/dist/agent-runtime/loop/run-stream-parts.d.ts.map +1 -1
  68. package/dist/agent-runtime/loop/run-stream-step-text.d.ts.map +1 -1
  69. package/dist/agent-runtime/loop/run-tool-approval-flow.d.ts +2 -1
  70. package/dist/agent-runtime/loop/run-tool-approval-flow.d.ts.map +1 -1
  71. package/dist/agent-runtime/loop/run-tool-call-input.d.ts +39 -0
  72. package/dist/agent-runtime/loop/run-tool-call-input.d.ts.map +1 -0
  73. package/dist/agent-runtime/loop/run-tool-call.d.ts +2 -31
  74. package/dist/agent-runtime/loop/run-tool-call.d.ts.map +1 -1
  75. package/dist/agent-runtime/loop/run-tool-errors.d.ts +5 -0
  76. package/dist/agent-runtime/loop/run-tool-errors.d.ts.map +1 -1
  77. package/dist/agent-runtime/loop/run-tool-executor.d.ts +1 -1
  78. package/dist/agent-runtime/loop/run-tool-executor.d.ts.map +1 -1
  79. package/dist/agent-runtime/loop/run-tool-slots.d.ts +2 -1
  80. package/dist/agent-runtime/loop/run-tool-slots.d.ts.map +1 -1
  81. package/dist/agent-runtime/loop/runtime-state.d.ts.map +1 -1
  82. package/dist/agent-runtime/loop/runtime.d.ts +0 -5
  83. package/dist/agent-runtime/loop/runtime.d.ts.map +1 -1
  84. package/dist/agent-runtime/providers/ai-sdk-convert.d.ts +1 -5
  85. package/dist/agent-runtime/providers/ai-sdk-convert.d.ts.map +1 -1
  86. package/dist/agent-runtime/providers/ai-sdk-normalize.d.ts +11 -0
  87. package/dist/agent-runtime/providers/ai-sdk-normalize.d.ts.map +1 -0
  88. package/dist/agent-runtime/providers/ai-sdk-tools.d.ts +11 -0
  89. package/dist/agent-runtime/providers/ai-sdk-tools.d.ts.map +1 -0
  90. package/dist/agent-runtime/providers/ai-sdk.d.ts +1 -9
  91. package/dist/agent-runtime/providers/ai-sdk.d.ts.map +1 -1
  92. package/dist/agent-runtime/providers/anthropic-sse.d.ts.map +1 -1
  93. package/dist/agent-runtime/providers/openrouter-admission.d.ts.map +1 -1
  94. package/dist/agent-runtime/providers/openrouter-audio.d.ts +164 -0
  95. package/dist/agent-runtime/providers/openrouter-audio.d.ts.map +1 -0
  96. package/dist/agent-runtime/providers/openrouter-catalog-cache.d.ts.map +1 -1
  97. package/dist/agent-runtime/providers/openrouter-catalog-query.d.ts.map +1 -1
  98. package/dist/agent-runtime/providers/openrouter-catalog.d.ts +4 -2
  99. package/dist/agent-runtime/providers/openrouter-catalog.d.ts.map +1 -1
  100. package/dist/agent-runtime/providers/openrouter-client.d.ts +37 -0
  101. package/dist/agent-runtime/providers/openrouter-client.d.ts.map +1 -0
  102. package/dist/agent-runtime/providers/openrouter-http.d.ts +120 -0
  103. package/dist/agent-runtime/providers/openrouter-http.d.ts.map +1 -0
  104. package/dist/agent-runtime/providers/openrouter-media.d.ts +174 -0
  105. package/dist/agent-runtime/providers/openrouter-media.d.ts.map +1 -0
  106. package/dist/agent-runtime/providers/openrouter-models.d.ts +2 -23
  107. package/dist/agent-runtime/providers/openrouter-models.d.ts.map +1 -1
  108. package/dist/agent-runtime/providers/openrouter-options.d.ts +4 -0
  109. package/dist/agent-runtime/providers/openrouter-options.d.ts.map +1 -1
  110. package/dist/agent-runtime/providers/openrouter-request.d.ts +23 -0
  111. package/dist/agent-runtime/providers/openrouter-request.d.ts.map +1 -0
  112. package/dist/agent-runtime/providers/openrouter-response.d.ts.map +1 -1
  113. package/dist/agent-runtime/providers/openrouter-retrieval.d.ts +145 -0
  114. package/dist/agent-runtime/providers/openrouter-retrieval.d.ts.map +1 -0
  115. package/dist/agent-runtime/providers/openrouter-speech.d.ts +90 -0
  116. package/dist/agent-runtime/providers/openrouter-speech.d.ts.map +1 -0
  117. package/dist/agent-runtime/providers/openrouter-spend.d.ts +7 -3
  118. package/dist/agent-runtime/providers/openrouter-spend.d.ts.map +1 -1
  119. package/dist/agent-runtime/providers/openrouter-stream.d.ts +29 -0
  120. package/dist/agent-runtime/providers/openrouter-stream.d.ts.map +1 -0
  121. package/dist/agent-runtime/providers/openrouter-systemone.d.ts +137 -0
  122. package/dist/agent-runtime/providers/openrouter-systemone.d.ts.map +1 -0
  123. package/dist/agent-runtime/providers/openrouter-url.d.ts +19 -0
  124. package/dist/agent-runtime/providers/openrouter-url.d.ts.map +1 -0
  125. package/dist/agent-runtime/providers/openrouter-wire.d.ts +45 -0
  126. package/dist/agent-runtime/providers/openrouter-wire.d.ts.map +1 -0
  127. package/dist/agent-runtime/providers/openrouter.d.ts +5 -4
  128. package/dist/agent-runtime/providers/openrouter.d.ts.map +1 -1
  129. package/dist/agent-runtime/providers/provider-http.d.ts +29 -3
  130. package/dist/agent-runtime/providers/provider-http.d.ts.map +1 -1
  131. package/dist/agent-runtime/providers/provider-json-schema-strip.d.ts.map +1 -1
  132. package/dist/agent-runtime/providers/provider-json-schema.d.ts.map +1 -1
  133. package/dist/agent-runtime/providers/provider-openai-chat-sse.d.ts.map +1 -1
  134. package/dist/agent-runtime/providers/provider-openai-chat-state.d.ts +42 -0
  135. package/dist/agent-runtime/providers/provider-openai-chat-state.d.ts.map +1 -0
  136. package/dist/agent-runtime/providers/provider-usage.d.ts +9 -0
  137. package/dist/agent-runtime/providers/provider-usage.d.ts.map +1 -1
  138. package/dist/agent-runtime/sandbox/sandbox-bubblewrap-args.d.ts +9 -0
  139. package/dist/agent-runtime/sandbox/sandbox-bubblewrap-args.d.ts.map +1 -1
  140. package/dist/agent-runtime/sandbox/sandbox-bubblewrap.d.ts +6 -0
  141. package/dist/agent-runtime/sandbox/sandbox-bubblewrap.d.ts.map +1 -1
  142. package/dist/agent-runtime/sandbox/sandbox-contract.d.ts.map +1 -1
  143. package/dist/agent-runtime/sandbox/sandbox-process-linux.d.ts.map +1 -1
  144. package/dist/agent-runtime/sandbox/sandbox-process-spec.d.ts +5 -1
  145. package/dist/agent-runtime/sandbox/sandbox-process-spec.d.ts.map +1 -1
  146. package/dist/agent-runtime/sandbox/sandbox-process-wrapper.d.ts.map +1 -1
  147. package/dist/agent-runtime/stores/branch-messages.d.ts.map +1 -1
  148. package/dist/agent-runtime/stores/sql-rows.d.ts +10 -10
  149. package/dist/agent-runtime/terminal-commit.d.ts +10 -10
  150. package/dist/agent-runtime/testing/fault-bench.d.ts +5 -1
  151. package/dist/agent-runtime/testing/fault-bench.d.ts.map +1 -1
  152. package/dist/application/diagnostic-journal-contract.d.ts.map +1 -1
  153. package/dist/browser/client-executors.d.ts.map +1 -1
  154. package/dist/browser/client-url.d.ts.map +1 -1
  155. package/dist/contract/define.d.ts +3 -7
  156. package/dist/contract/define.d.ts.map +1 -1
  157. package/dist/contract/normalize.d.ts +17 -5
  158. package/dist/contract/normalize.d.ts.map +1 -1
  159. package/dist/entrypoints/agent-executor/acp.js +4 -2
  160. package/dist/entrypoints/agent-executor/claude-sdk.js +20 -20
  161. package/dist/entrypoints/agent-executor/claude.js +7 -7
  162. package/dist/entrypoints/agent-executor/codex.d.ts +2 -1
  163. package/dist/entrypoints/agent-executor/codex.d.ts.map +1 -1
  164. package/dist/entrypoints/agent-executor/codex.js +129 -35
  165. package/dist/entrypoints/agent-executor/testing/claude-sdk.js +2 -2
  166. package/dist/entrypoints/agent-executor/testing.js +17 -13
  167. package/dist/entrypoints/agent-executor.js +1 -1
  168. package/dist/entrypoints/agent-runtime/ai-sdk.d.ts +2 -1
  169. package/dist/entrypoints/agent-runtime/ai-sdk.d.ts.map +1 -1
  170. package/dist/entrypoints/agent-runtime/ai-sdk.js +10 -12
  171. package/dist/entrypoints/agent-runtime/anthropic.js +13 -10
  172. package/dist/entrypoints/agent-runtime/browser.js +8 -4
  173. package/dist/entrypoints/agent-runtime/harness.js +18 -19
  174. package/dist/entrypoints/agent-runtime/openai.js +5 -5
  175. package/dist/entrypoints/agent-runtime/openrouter.d.ts +11 -2
  176. package/dist/entrypoints/agent-runtime/openrouter.d.ts.map +1 -1
  177. package/dist/entrypoints/agent-runtime/openrouter.js +1940 -496
  178. package/dist/entrypoints/agent-runtime/postgres.js +2 -2
  179. package/dist/entrypoints/agent-runtime/realtime.js +5 -5
  180. package/dist/entrypoints/agent-runtime/sandbox.js +167 -139
  181. package/dist/entrypoints/agent-runtime/sqlite/bun.js +3 -3
  182. package/dist/entrypoints/agent-runtime/sqlite/node.js +3 -3
  183. package/dist/entrypoints/agent-runtime/testing.js +3 -3
  184. package/dist/entrypoints/agent-runtime.js +246 -360
  185. package/dist/entrypoints/application.js +2 -2
  186. package/dist/entrypoints/cli.js +36 -15
  187. package/dist/entrypoints/contract.js +12 -10
  188. package/dist/entrypoints/geo.js +1 -1
  189. package/dist/entrypoints/handler.js +5 -6
  190. package/dist/entrypoints/http.d.ts +2 -0
  191. package/dist/entrypoints/http.d.ts.map +1 -1
  192. package/dist/entrypoints/http.js +16 -4
  193. package/dist/entrypoints/index.js +26 -35
  194. package/dist/entrypoints/live.js +3 -3
  195. package/dist/entrypoints/node.js +7 -7
  196. package/dist/entrypoints/observability.js +9 -7
  197. package/dist/entrypoints/process.js +3 -3
  198. package/dist/entrypoints/remote.js +5 -5
  199. package/dist/entrypoints/server.js +29 -16
  200. package/dist/entrypoints/telegram/grammy.d.ts +1 -1
  201. package/dist/entrypoints/telegram/grammy.d.ts.map +1 -1
  202. package/dist/entrypoints/telegram/grammy.js +39 -5
  203. package/dist/entrypoints/telegram/screens.js +3 -0
  204. package/dist/entrypoints/telegram.d.ts +1 -1
  205. package/dist/entrypoints/telegram.d.ts.map +1 -1
  206. package/dist/entrypoints/telegram.js +19 -6
  207. package/dist/entrypoints/testing.js +10 -11
  208. package/dist/entrypoints/tools/agent.js +8 -9
  209. package/dist/entrypoints/tools/connections.js +27 -57
  210. package/dist/entrypoints/tools/contract.js +4 -4
  211. package/dist/entrypoints/tools/invoker.js +7 -8
  212. package/dist/entrypoints/tools/mcp.js +9 -10
  213. package/dist/entrypoints/tools/toolkit.js +11 -12
  214. package/dist/entrypoints/tools.js +20 -20
  215. package/dist/entrypoints/tracking/contract.js +1 -1
  216. package/dist/entrypoints/tracking/performance.js +1 -1
  217. package/dist/entrypoints/tracking.js +1 -1
  218. package/dist/{index-3czc3ykr.js → index-08a3qfr8.js} +1 -1
  219. package/dist/{index-grhhsrd5.js → index-1en7k3q5.js} +2 -1
  220. package/dist/{index-pdcbjd6a.js → index-1yky29qg.js} +6 -3
  221. package/dist/{index-b4c9dpzm.js → index-252den5a.js} +10 -11
  222. package/dist/{index-xtby8rj3.js → index-28kbdn63.js} +5 -47
  223. package/dist/{index-57sbckhv.js → index-36mtj8xm.js} +2 -2
  224. package/dist/{index-dm84tsd5.js → index-3kb8dw48.js} +1 -1
  225. package/dist/index-3tb82xr7.js +11 -0
  226. package/dist/{index-c24bj2r1.js → index-4243301z.js} +2 -2
  227. package/dist/{index-nr4fhfn4.js → index-4p2zx593.js} +2 -0
  228. package/dist/{index-q86qnzzf.js → index-54wp467c.js} +4 -4
  229. package/dist/{index-mcv7b2n0.js → index-63ctzjp4.js} +497 -495
  230. package/dist/{index-y0a4gt1s.js → index-65p8v81y.js} +3 -2
  231. package/dist/{index-z72vazf5.js → index-6y3eae97.js} +27 -83
  232. package/dist/{index-5awtbyns.js → index-9vj869rx.js} +1 -1
  233. package/dist/{index-5q0qpw3v.js → index-aqm7e864.js} +23 -8
  234. package/dist/{index-d4at0q09.js → index-b9mj31q7.js} +90 -88
  235. package/dist/{index-baba8ehy.js → index-bjrcbcn2.js} +2 -2
  236. package/dist/{index-fsw9wxk9.js → index-c9j8441q.js} +1 -103
  237. package/dist/{index-wdb5jhas.js → index-d1pdv8qc.js} +1 -1
  238. package/dist/{index-73wq9abg.js → index-df5xr2f9.js} +13 -59
  239. package/dist/{index-n9358ydy.js → index-dm50x3by.js} +1 -1
  240. package/dist/{index-zyyerdny.js → index-dmrx8xma.js} +3 -0
  241. package/dist/{index-78da4g74.js → index-dwq6a6sq.js} +17 -13
  242. package/dist/{index-9be3tf6r.js → index-e413q2cj.js} +49 -22
  243. package/dist/{index-g4gstmp1.js → index-ednf2cxs.js} +1 -1
  244. package/dist/{index-84tp547a.js → index-edpkm3k7.js} +29 -97
  245. package/dist/{index-gs0jw0hy.js → index-efbzm2se.js} +3 -3
  246. package/dist/{index-de7b0kvz.js → index-epwvp88y.js} +1 -1
  247. package/dist/{index-asnd4h2k.js → index-f0dzyskg.js} +27 -4
  248. package/dist/{index-xbb8ysmq.js → index-fatke81t.js} +2 -2
  249. package/dist/{index-6nzzj7qr.js → index-gq35s3bm.js} +1 -1
  250. package/dist/index-gvgtmt7a.js +102 -0
  251. package/dist/{index-m2b49tvc.js → index-h08xqfw9.js} +20 -21
  252. package/dist/{index-gk6dq9ay.js → index-ha1tv70k.js} +3 -26
  253. package/dist/{index-wsv11dhg.js → index-hberxns4.js} +1 -1
  254. package/dist/{index-rkphknhx.js → index-hpzhz1vm.js} +1 -1
  255. package/dist/{index-npfdymav.js → index-j5vzhj3d.js} +1 -1
  256. package/dist/{index-d3s070eh.js → index-jperyn0c.js} +1 -1
  257. package/dist/{index-yhwx4fwk.js → index-kzsetgh9.js} +1 -1
  258. package/dist/{index-x6sp5vpa.js → index-q4tr9vnf.js} +1 -1
  259. package/dist/{index-hce3hbdg.js → index-qj0sq69b.js} +6 -2
  260. package/dist/{index-v0j22shs.js → index-rg08syp1.js} +9 -6
  261. package/dist/{index-8vzh5wpv.js → index-rw1caff2.js} +14 -26
  262. package/dist/index-s8af9jqw.js +6 -0
  263. package/dist/{index-bgj9hbm3.js → index-sdppfbrh.js} +30 -16
  264. package/dist/{index-y0mwkgkf.js → index-shte29pg.js} +1086 -1055
  265. package/dist/{index-fec05c9k.js → index-ta0e2daw.js} +9 -7
  266. package/dist/{index-zfrysr1e.js → index-tb36xawm.js} +110 -75
  267. package/dist/{index-c0yym4a0.js → index-w7e402wx.js} +11 -105
  268. package/dist/{index-bvpevwt6.js → index-xnqab06h.js} +207 -202
  269. package/dist/index-xrbrvn15.js +147 -0
  270. package/dist/{index-ac3rfec5.js → index-y6wzzk2e.js} +21 -1
  271. package/dist/{index-3d2c45jn.js → index-yjx5jna7.js} +2 -2
  272. package/dist/internal/loopback-host.d.ts +8 -0
  273. package/dist/internal/loopback-host.d.ts.map +1 -0
  274. package/dist/internal/own-member.d.ts +7 -0
  275. package/dist/internal/own-member.d.ts.map +1 -0
  276. package/dist/internal/request.d.ts +17 -8
  277. package/dist/internal/request.d.ts.map +1 -1
  278. package/dist/internal/secret-shapes.d.ts +33 -4
  279. package/dist/internal/secret-shapes.d.ts.map +1 -1
  280. package/dist/json-schema/dialect.d.ts.map +1 -1
  281. package/dist/json-schema/keywords.d.ts +25 -6
  282. package/dist/json-schema/keywords.d.ts.map +1 -1
  283. package/dist/json-schema/string-format.d.ts.map +1 -1
  284. package/dist/live/events.d.ts.map +1 -1
  285. package/dist/live/watch-client.d.ts.map +1 -1
  286. package/dist/live/watch-delta.d.ts.map +1 -1
  287. package/dist/observability/context.d.ts +4 -3
  288. package/dist/observability/context.d.ts.map +1 -1
  289. package/dist/observability/sanitize.d.ts.map +1 -1
  290. package/dist/observability/secret-values.d.ts +0 -9
  291. package/dist/observability/secret-values.d.ts.map +1 -1
  292. package/dist/server/context.d.ts +3 -2
  293. package/dist/server/context.d.ts.map +1 -1
  294. package/dist/server/error-hook.d.ts +4 -3
  295. package/dist/server/error-hook.d.ts.map +1 -1
  296. package/dist/server/event-bus.d.ts.map +1 -1
  297. package/dist/server/file.d.ts +11 -3
  298. package/dist/server/file.d.ts.map +1 -1
  299. package/dist/server/handler-state.d.ts +2 -2
  300. package/dist/server/handler-state.d.ts.map +1 -1
  301. package/dist/server/middleware/jwt.d.ts +12 -1
  302. package/dist/server/middleware/jwt.d.ts.map +1 -1
  303. package/dist/server/middleware/trust-fence.d.ts +4 -0
  304. package/dist/server/middleware/trust-fence.d.ts.map +1 -1
  305. package/dist/server/multipart.d.ts +2 -3
  306. package/dist/server/multipart.d.ts.map +1 -1
  307. package/dist/server/raw.d.ts.map +1 -1
  308. package/dist/server/request-body.d.ts +12 -1
  309. package/dist/server/request-body.d.ts.map +1 -1
  310. package/dist/server/request-completion.d.ts.map +1 -1
  311. package/dist/server/types.d.ts +14 -9
  312. package/dist/server/types.d.ts.map +1 -1
  313. package/dist/telegram/crypto.d.ts.map +1 -1
  314. package/dist/telegram/init-data.d.ts +4 -4
  315. package/dist/telegram/init-data.d.ts.map +1 -1
  316. package/dist/telegram/outbound-cost.d.ts.map +1 -1
  317. package/dist/telegram/screens/test-chat.d.ts.map +1 -1
  318. package/dist/telegram/widget-api.d.ts +85 -13
  319. package/dist/telegram/widget-api.d.ts.map +1 -1
  320. package/dist/telegram/widget.d.ts +46 -2
  321. package/dist/telegram/widget.d.ts.map +1 -1
  322. package/dist/tools/cli/args-classify.d.ts +4 -74
  323. package/dist/tools/cli/args-classify.d.ts.map +1 -1
  324. package/dist/tools/cli/args-framework.d.ts +79 -0
  325. package/dist/tools/cli/args-framework.d.ts.map +1 -0
  326. package/dist/tools/cli/args-scan.d.ts.map +1 -1
  327. package/dist/tools/cli/args-tokens.d.ts.map +1 -1
  328. package/dist/tools/cli/checkpoint.d.ts +5 -0
  329. package/dist/tools/cli/checkpoint.d.ts.map +1 -1
  330. package/dist/tools/cli/stream.d.ts.map +1 -1
  331. package/dist/tools/connections/foreign-schema-join.d.ts.map +1 -1
  332. package/dist/tools/connections/openapi.d.ts.map +1 -1
  333. package/dist/tools/connections/runtime.d.ts.map +1 -1
  334. package/dist/tools/execute-handler.d.ts +24 -0
  335. package/dist/tools/execute-handler.d.ts.map +1 -0
  336. package/dist/tools/execute.d.ts.map +1 -1
  337. package/dist/tools/mcp/round.d.ts.map +1 -1
  338. package/dist/tools/schema/coerce.d.ts.map +1 -1
  339. package/dist/tools/schema/flatten.d.ts.map +1 -1
  340. package/dist/tools/schema/inline-references.d.ts.map +1 -1
  341. package/dist/tools/schema/nesting-limit.d.ts.map +1 -1
  342. package/dist/tools/schema/presentation.d.ts.map +1 -1
  343. package/dist/tracking/privacy.d.ts.map +1 -1
  344. package/llms/agent-runtime-openrouter.txt +14 -5
  345. package/llms/agent-runtime-sandbox.txt +50 -11
  346. package/llms/agent-runtime-testing.txt +1 -1
  347. package/llms/agent-runtime.2.txt +342 -230
  348. package/llms/agent-runtime.3.txt +225 -380
  349. package/llms/agent-runtime.4.txt +387 -158
  350. package/llms/agent-runtime.5.txt +157 -152
  351. package/llms/agent-runtime.6.txt +164 -0
  352. package/llms/agent-runtime.txt +307 -362
  353. package/llms/application.txt +3 -1
  354. package/llms/http.txt +1 -1
  355. package/llms/live.txt +3 -1
  356. package/llms/observability.txt +16 -9
  357. package/llms/server.2.txt +13 -8
  358. package/llms/server.4.txt +23 -11
  359. package/llms/server.5.txt +5 -5
  360. package/llms/server.txt +54 -1
  361. package/llms/spend.txt +18 -1
  362. package/llms/stitchkit.2.txt +4 -2
  363. package/llms/stitchkit.txt +113 -93
  364. package/llms/telegram-grammy.txt +3 -2
  365. package/llms/telegram.2.txt +3 -1
  366. package/llms/telegram.txt +35 -10
  367. package/llms/upgrading-0.128.0-0.129.0.txt +175 -0
  368. package/llms/{upgrading-0.128.0-0.135.0.txt → upgrading-0.130.0-0.136.0.txt} +353 -169
  369. package/llms/upgrading.txt +2 -1
  370. package/llms-full.txt +1035 -208
  371. package/llms.txt +14 -13
  372. package/package.json +6 -6
  373. package/dist/agent-runtime/loop/deferred-tools-internal.d.ts +0 -19
  374. package/dist/agent-runtime/loop/deferred-tools-internal.d.ts.map +0 -1
  375. package/dist/agent-runtime/loop/run-complete-retry.d.ts +0 -24
  376. package/dist/agent-runtime/loop/run-complete-retry.d.ts.map +0 -1
  377. package/dist/agent-runtime/loop/run-model-attempts.d.ts +0 -6
  378. package/dist/agent-runtime/loop/run-model-attempts.d.ts.map +0 -1
  379. package/dist/index-sznqf8fx.js +0 -20
  380. /package/dist/{index-fthw8dwa.js → index-4gbybjg6.js} +0 -0
@@ -45,7 +45,7 @@ import {
45
45
  import {
46
46
  ToolExecutionControlError2,
47
47
  isToolExecutionControlError2
48
- } from "./index-d4at0q09.js";
48
+ } from "./index-b9mj31q7.js";
49
49
  import {
50
50
  withStoreRetries,
51
51
  AgentRuntimeConflictError2,
@@ -65,7 +65,7 @@ import {
65
65
  import {
66
66
  AGENT_TOOL_PROGRESS_MESSAGE_MAX2,
67
67
  agentDurableEventId2
68
- } from "./index-grhhsrd5.js";
68
+ } from "./index-1en7k3q5.js";
69
69
  import {
70
70
  contractOperationEffects2
71
71
  } from "./index-werjqesf.js";
@@ -88,15 +88,18 @@ import {
88
88
  } from "./index-vse7x1qt.js";
89
89
  import {
90
90
  listContractToolNames2
91
- } from "./index-xbb8ysmq.js";
91
+ } from "./index-fatke81t.js";
92
92
  import {
93
93
  AgentToolError2,
94
94
  isAgentToolError2,
95
95
  finalizeAgentToolOutput
96
- } from "./index-q86qnzzf.js";
96
+ } from "./index-54wp467c.js";
97
97
  import {
98
98
  createMutationQueue
99
99
  } from "./index-sykb5ag7.js";
100
+ import {
101
+ setOwnMember
102
+ } from "./index-3tb82xr7.js";
100
103
  import {
101
104
  serializeCanonicalJson
102
105
  } from "./index-fmzg39a8.js";
@@ -108,6 +111,9 @@ import {
108
111
  assertTimerMs,
109
112
  withDeadline
110
113
  } from "./index-e1y74yra.js";
114
+ import {
115
+ sleep
116
+ } from "./index-h20qcyh5.js";
111
117
  import {
112
118
  raceAbort,
113
119
  linkAbortSignals
@@ -565,85 +571,6 @@ function createAgentSessionCoordinator2() {
565
571
  };
566
572
  }
567
573
 
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
574
  // src/agent-runtime/loop/invocation-attempt.ts
648
575
  import { AsyncLocalStorage } from "node:async_hooks";
649
576
  import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
@@ -727,7 +654,7 @@ function walkInvocationJson(value, ancestors, errors) {
727
654
  if (entry === undefined || typeof entry === "function" || typeof entry === "symbol") {
728
655
  continue;
729
656
  }
730
- out[key] = walkInvocationJson(entry, ancestors, errors);
657
+ setOwnMember(out, key, walkInvocationJson(entry, ancestors, errors));
731
658
  }
732
659
  return out;
733
660
  } finally {
@@ -1375,6 +1302,9 @@ function ensureTextSegment(acc, id, provider) {
1375
1302
  }
1376
1303
 
1377
1304
  // src/agent-runtime/loop/provider-stream-parts.ts
1305
+ function providerToolActed(part) {
1306
+ return part.type === "tool-call" && part.providerExecuted === true || part.type === "tool-result";
1307
+ }
1378
1308
  async function handleProviderToolResult(result, part, emit) {
1379
1309
  const matchingCall = result.rawToolCalls.find((call) => call.toolCallId === part.toolCallId);
1380
1310
  const matchingInput = matchingCall ? parseProviderToolInput(matchingCall.input) : {};
@@ -1743,37 +1673,43 @@ async function consumeStandaloneDriverStream(input) {
1743
1673
  };
1744
1674
  let errorPart;
1745
1675
  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;
1676
+ try {
1677
+ for await (const part of ownedProviderStream({
1678
+ stream: markProviderParts(input.modelStream.parts),
1679
+ abort: input.abortAttempt,
1680
+ onCleanupFailure: input.onCleanupFailure ?? (() => {
1681
+ return;
1682
+ })
1683
+ })) {
1684
+ input.onChunk?.();
1685
+ input.onProviderPart?.(part);
1686
+ if (sawError) {
1687
+ if (part.type === "finish") {
1688
+ await handleStreamPart(acc, part, noopEmit, async () => false);
1689
+ }
1765
1690
  continue;
1766
1691
  }
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) });
1692
+ if (part.type === "error") {
1693
+ if (input.captureErrorUsage) {
1694
+ sawError = true;
1695
+ errorPart = part.error;
1696
+ acc.result.sawErrorPart = true;
1697
+ continue;
1698
+ }
1699
+ throw markProviderOrigin(part.error);
1700
+ }
1701
+ if (part.type === "tool-call") {
1702
+ if (part.providerExecuted === true) {
1703
+ await input.onPart?.({ ...part, input: parseProviderToolInput(part.input) });
1704
+ }
1705
+ } else if (part.type !== "finish") {
1706
+ await input.onPart?.(part);
1772
1707
  }
1773
- } else if (part.type !== "finish") {
1774
- await input.onPart?.(part);
1708
+ await handleStreamPart(acc, part, noopEmit, async () => false);
1775
1709
  }
1776
- await handleStreamPart(acc, part, noopEmit, async () => false);
1710
+ } catch (error) {
1711
+ if (!sawError || input.signal?.aborted || !hasProviderOrigin(error))
1712
+ throw error;
1777
1713
  }
1778
1714
  return sawError ? { ...acc.result, errorPart } : acc.result;
1779
1715
  }
@@ -2411,29 +2347,7 @@ async function recordAgentRetryDecision2(input) {
2411
2347
  return decision;
2412
2348
  }
2413
2349
 
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
- }
2350
+ // src/agent-runtime/loop/run-approval-signature.ts
2437
2351
  var encoder = new TextEncoder;
2438
2352
  function assertToolApprovalSecret(secret) {
2439
2353
  if (secret === undefined)
@@ -2567,6 +2481,30 @@ async function verifyToolApprovalSignature(input) {
2567
2481
  return false;
2568
2482
  return crypto.subtle.verify("HMAC", key, sigCopy, new Uint8Array(legacy));
2569
2483
  }
2484
+
2485
+ // src/agent-runtime/loop/run-approval.ts
2486
+ class AgentToolApprovalError2 extends Error {
2487
+ reason;
2488
+ constructor(message, options) {
2489
+ super(message, options?.cause !== undefined ? { cause: options.cause } : undefined);
2490
+ this.name = "AgentToolApprovalError";
2491
+ this.reason = options?.reason ?? "input-validation-failed";
2492
+ }
2493
+ }
2494
+
2495
+ class AgentInvalidToolApprovalSignatureError2 extends AgentToolApprovalError2 {
2496
+ constructor(approvalId, detail = "Invalid or missing tool approval signature") {
2497
+ super(`${detail} for approval "${approvalId}"`, { reason: "invalid-signature" });
2498
+ this.name = "AgentInvalidToolApprovalSignatureError";
2499
+ }
2500
+ }
2501
+
2502
+ class AgentToolCallNotFoundForApprovalError2 extends AgentToolApprovalError2 {
2503
+ constructor(approvalId) {
2504
+ super(`Tool call not found for approval "${approvalId}"`, { reason: "call-not-found" });
2505
+ this.name = "AgentToolCallNotFoundForApprovalError";
2506
+ }
2507
+ }
2570
2508
  var APPROVAL_DECISION_TYPES = new Set([
2571
2509
  "approved",
2572
2510
  "denied",
@@ -2764,271 +2702,91 @@ async function collectApprovalContinuations(input) {
2764
2702
  return resolved.map((entry) => entry.item);
2765
2703
  }
2766
2704
 
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";
2705
+ // src/agent-runtime/loop/run-model-messages.ts
2706
+ function buildStepResponseMessages(consumed, toolExecution) {
2707
+ const assistantContent = [];
2708
+ for (const segment of consumed.segments) {
2709
+ if (segment.kind === "reasoning") {
2710
+ if (segment.text.length === 0 && segment.provider === undefined)
2711
+ continue;
2712
+ const options = envelopeToProviderOptions(segment.provider);
2713
+ assistantContent.push({
2714
+ type: "reasoning",
2715
+ text: segment.text,
2716
+ ...options && { providerOptions: options }
2717
+ });
2718
+ } else if (segment.kind === "text") {
2719
+ if (segment.text.length === 0 && segment.provider === undefined)
2720
+ continue;
2721
+ const options = envelopeToProviderOptions(segment.provider);
2722
+ assistantContent.push({
2723
+ type: "text",
2724
+ text: segment.text,
2725
+ ...options && { providerOptions: options }
2726
+ });
2727
+ } else if (segment.assistantPart !== undefined) {
2728
+ assistantContent.push(segment.assistantPart);
2729
+ }
2776
2730
  }
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");
2731
+ assistantContent.push(...toolExecution.assistantParts);
2732
+ const stepResponseMessages = [];
2733
+ if (assistantContent.length > 0) {
2734
+ stepResponseMessages.push({ role: "assistant", content: assistantContent });
2804
2735
  }
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`);
2736
+ if (toolExecution.toolParts.length > 0) {
2737
+ stepResponseMessages.push({ role: "tool", content: toolExecution.toolParts });
2738
+ }
2739
+ return stepResponseMessages;
2740
+ }
2741
+ function buildStepContent(consumed, toolExecution) {
2742
+ const content = [];
2743
+ for (const segment of consumed.segments) {
2744
+ if (segment.kind === "reasoning") {
2745
+ if (segment.text.length > 0 || segment.provider !== undefined) {
2746
+ content.push({ type: "reasoning", text: segment.text });
2747
+ }
2748
+ } else if (segment.kind === "text") {
2749
+ if (segment.text.length > 0) {
2750
+ content.push({ type: "text", text: segment.text });
2751
+ }
2752
+ } else if (segment.stepPart !== undefined) {
2753
+ content.push(segment.stepPart);
2808
2754
  }
2809
2755
  }
2810
- assertStepBarriers(barriers);
2756
+ content.push(...toolExecution.stepContent);
2757
+ return content;
2811
2758
  }
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
- });
2759
+
2760
+ // src/agent-runtime/loop/run-step-helpers.ts
2761
+ function buildActiveToolSpecs(tools, requestedActive) {
2762
+ const declared = Object.keys(tools);
2763
+ const activeSet = requestedActive ? new Set(requestedActive) : undefined;
2764
+ const activeNames = activeSet ? declared.filter((name) => activeSet.has(name)) : declared;
2765
+ const specs = [];
2766
+ for (const name of activeNames) {
2767
+ const tool = Object.hasOwn(tools, name) ? tools[name] : undefined;
2768
+ if (!tool)
2769
+ continue;
2770
+ specs.push({
2771
+ name,
2772
+ ...tool.description !== undefined && { description: tool.description },
2773
+ inputSchema: tool.inputSchema,
2774
+ ...tool.strict !== undefined && { strict: tool.strict },
2775
+ ...tool.cacheControl !== undefined && { cacheControl: tool.cacheControl },
2776
+ ...tool.providerOptions !== undefined && { providerOptions: tool.providerOptions }
2777
+ });
2778
+ }
2779
+ return { activeNames, specs };
2817
2780
  }
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 };
3022
- }
3023
- function mergeStepCallSettings(base, prepared) {
3024
- const maxOutputTokens = prepared?.maxOutputTokens ?? base?.maxOutputTokens;
3025
- const temperature = prepared?.temperature ?? base?.temperature;
3026
- const topP = prepared?.topP ?? base?.topP;
3027
- const topK = prepared?.topK ?? base?.topK;
3028
- const presencePenalty = prepared?.presencePenalty ?? base?.presencePenalty;
3029
- const frequencyPenalty = prepared?.frequencyPenalty ?? base?.frequencyPenalty;
3030
- const seed = prepared?.seed ?? base?.seed;
3031
- const stopSequences = prepared?.stopSequences ?? base?.stopSequences;
2781
+ function mergeStepCallSettings(base, prepared) {
2782
+ const maxOutputTokens = prepared?.maxOutputTokens ?? base?.maxOutputTokens;
2783
+ const temperature = prepared?.temperature ?? base?.temperature;
2784
+ const topP = prepared?.topP ?? base?.topP;
2785
+ const topK = prepared?.topK ?? base?.topK;
2786
+ const presencePenalty = prepared?.presencePenalty ?? base?.presencePenalty;
2787
+ const frequencyPenalty = prepared?.frequencyPenalty ?? base?.frequencyPenalty;
2788
+ const seed = prepared?.seed ?? base?.seed;
2789
+ const stopSequences = prepared?.stopSequences ?? base?.stopSequences;
3032
2790
  return {
3033
2791
  ...maxOutputTokens !== undefined && { maxOutputTokens },
3034
2792
  ...temperature !== undefined && { temperature },
@@ -3160,6 +2918,186 @@ function assembleStepResult(input) {
3160
2918
  return { resolvedResponseId, stepResponseMessages, stepResult };
3161
2919
  }
3162
2920
 
2921
+ // src/agent-runtime/loop/run-step-barriers.ts
2922
+ class AgentStepBarrierError2 extends Error {
2923
+ bound;
2924
+ action;
2925
+ constructor(bound, message, action = "abort") {
2926
+ super(message);
2927
+ this.bound = bound;
2928
+ this.action = action;
2929
+ this.name = "AgentStepBarrierError";
2930
+ }
2931
+ }
2932
+ function assertStepBarriers(barriers) {
2933
+ if (!barriers)
2934
+ return;
2935
+ assertPositiveSafeInteger("stepBarriers.maxToolCallsPerStep", barriers.maxToolCallsPerStep, RangeError);
2936
+ assertPositiveSafeInteger("stepBarriers.maxReasoningCharsPerStep", barriers.maxReasoningCharsPerStep, RangeError);
2937
+ if (barriers.onMaxReasoningChars !== undefined && !["abort", "finish-length"].includes(barriers.onMaxReasoningChars))
2938
+ throw new RangeError("stepBarriers.onMaxReasoningChars must be 'abort' or 'finish-length'");
2939
+ if (barriers.stepText !== undefined && !["immediate", "after-tools"].includes(barriers.stepText))
2940
+ throw new RangeError("stepBarriers.stepText must be 'immediate' or 'after-tools'");
2941
+ if (barriers.stepTextOnInterrupt !== undefined && !["drop", "flush"].includes(barriers.stepTextOnInterrupt))
2942
+ throw new RangeError("stepBarriers.stepTextOnInterrupt must be 'drop' or 'flush'");
2943
+ if (barriers.onPredecessorFailure !== undefined && !["run", "refuse"].includes(barriers.onPredecessorFailure))
2944
+ throw new RangeError("stepBarriers.onPredecessorFailure must be 'run' or 'refuse'");
2945
+ }
2946
+ var RUNTIME_ONLY_STEP_BARRIER_KEYS = [
2947
+ "stepText",
2948
+ "maxReasoningCharsPerStep",
2949
+ "onMaxReasoningChars",
2950
+ "stepTextOnInterrupt",
2951
+ "filterStepText"
2952
+ ];
2953
+ function assertStandaloneStepBarriers(barriers) {
2954
+ if (barriers === undefined)
2955
+ return;
2956
+ if (typeof barriers !== "object" || barriers === null) {
2957
+ throw new TypeError("stepBarriers must be an object");
2958
+ }
2959
+ for (const key of RUNTIME_ONLY_STEP_BARRIER_KEYS) {
2960
+ if (Object.hasOwn(barriers, key) && Reflect.get(barriers, key) !== undefined) {
2961
+ throw new TypeError(`stepBarriers.${key} is only supported by createAgentRuntime, not standalone completion`);
2962
+ }
2963
+ }
2964
+ assertStepBarriers(barriers);
2965
+ }
2966
+ function stepToolCallLimitRefusal(limit) {
2967
+ return new AgentToolError2({
2968
+ code: "STEP_TOOL_CALL_LIMIT",
2969
+ message: `Refused: a step may make at most ${limit} tool calls; make the rest in the next step`
2970
+ });
2971
+ }
2972
+ function createStepCallScheduler(barriers) {
2973
+ let count = 0;
2974
+ const entities = new Map;
2975
+ const limit = barriers?.maxToolCallsPerStep;
2976
+ const stateOf = (entity) => {
2977
+ const known = entities.get(entity);
2978
+ if (known)
2979
+ return known;
2980
+ const fresh = { reads: [] };
2981
+ entities.set(entity, fresh);
2982
+ return fresh;
2983
+ };
2984
+ const registerDependencies = (dependencies, ownPromise) => {
2985
+ const writes = new Set(dependencies.writes ?? []);
2986
+ const reads = new Set([...dependencies.reads ?? []].filter((entity) => !writes.has(entity)));
2987
+ const ahead = [];
2988
+ for (const entity of reads) {
2989
+ const state = stateOf(entity);
2990
+ if (state.write)
2991
+ ahead.push(state.write);
2992
+ state.reads.push(ownPromise);
2993
+ }
2994
+ for (const entity of writes) {
2995
+ const state = stateOf(entity);
2996
+ if (state.write)
2997
+ ahead.push(state.write);
2998
+ ahead.push(...state.reads);
2999
+ state.write = ownPromise;
3000
+ state.reads = [];
3001
+ }
3002
+ return ahead;
3003
+ };
3004
+ return {
3005
+ recordFailedPredecessor(toolName, input) {
3006
+ if (!barriers?.toolDependencies)
3007
+ return [];
3008
+ let dependencies;
3009
+ try {
3010
+ dependencies = barriers.toolDependencies({ toolName, input });
3011
+ } catch {
3012
+ return [];
3013
+ }
3014
+ if (!dependencies)
3015
+ return [];
3016
+ registerDependencies(dependencies, Promise.resolve(false));
3017
+ return [...dependencies.reads ?? [], ...dependencies.writes ?? []];
3018
+ },
3019
+ enter(toolName, input) {
3020
+ count += 1;
3021
+ const refused = limit !== undefined && count > limit;
3022
+ if (refused) {
3023
+ return {
3024
+ refused: true,
3025
+ limit,
3026
+ hasPredecessors: false,
3027
+ waitAhead: async () => {
3028
+ return;
3029
+ },
3030
+ settle: () => {
3031
+ return;
3032
+ }
3033
+ };
3034
+ }
3035
+ const dependencies = barriers?.toolDependencies?.({ toolName, input });
3036
+ if (!dependencies) {
3037
+ return {
3038
+ refused: false,
3039
+ hasPredecessors: false,
3040
+ waitAhead: async () => {
3041
+ return;
3042
+ },
3043
+ settle: () => {
3044
+ return;
3045
+ }
3046
+ };
3047
+ }
3048
+ const own = Promise.withResolvers();
3049
+ let settled = false;
3050
+ const settle = (ok = true) => {
3051
+ if (settled)
3052
+ return;
3053
+ settled = true;
3054
+ own.resolve(ok);
3055
+ };
3056
+ const ahead = registerDependencies(dependencies, own.promise);
3057
+ return {
3058
+ refused: false,
3059
+ hasPredecessors: ahead.length > 0,
3060
+ async waitAhead(signal) {
3061
+ if (ahead.length === 0)
3062
+ return;
3063
+ const all = Promise.all(ahead);
3064
+ const outcomes = await (signal ? raceAbort(all, signal) : all);
3065
+ if (barriers?.onPredecessorFailure === "refuse" && outcomes.some((ok) => ok === false)) {
3066
+ throw new AgentToolError2({
3067
+ code: "STEP_PREDECESSOR_FAILED",
3068
+ message: "Refused: an earlier tool call on the same entity failed in this step"
3069
+ });
3070
+ }
3071
+ },
3072
+ settle
3073
+ };
3074
+ }
3075
+ };
3076
+ }
3077
+ function createToolDependencyResolver2(input) {
3078
+ const effects = new Map;
3079
+ for (const contract of input.contracts ?? []) {
3080
+ const byEndpoint = contractOperationEffects2(contract);
3081
+ for (const entry of listContractToolNames2([contract])) {
3082
+ const effect = byEndpoint[entry.method];
3083
+ if (effect !== undefined)
3084
+ effects.set(entry.name, effect);
3085
+ }
3086
+ }
3087
+ for (const [toolName, effect] of Object.entries(input.effects ?? {})) {
3088
+ if (effects.has(toolName))
3089
+ throw new RangeError(`Tool "${toolName}" already has the effect of its contract endpoint`);
3090
+ effects.set(toolName, effect);
3091
+ }
3092
+ return ({ toolName, input: callInput }) => {
3093
+ const effect = effects.get(toolName);
3094
+ const entity = effect && input.entityOf(toolName, callInput);
3095
+ if (entity === undefined || effect === undefined)
3096
+ return;
3097
+ return effect === "write" ? { writes: [entity] } : { reads: [entity] };
3098
+ };
3099
+ }
3100
+
3163
3101
  // src/agent-runtime/loop/run-tool-approval-records.ts
3164
3102
  async function recordUserApprovalRequest(input) {
3165
3103
  const { execution, callId, toolName, parsedInput, callRecord, reason, emit, callSlot } = input;
@@ -3534,38 +3472,90 @@ async function flushHeldStepTextWithOutcome(execution, interrupted, context) {
3534
3472
  ...changed && { segmentOverrides: overrides }
3535
3473
  };
3536
3474
  }
3537
- let offset = 0;
3538
- for (const seg of surviving) {
3539
- const textPart = AgentMessagePartSchema2.parse({
3540
- type: "text",
3541
- text: seg.text,
3542
- ...seg.provider !== undefined && { provider: seg.provider }
3543
- });
3544
- const targetIndex = Math.min(seg.insertIndex + offset, state.parts.length);
3545
- state.parts.splice(targetIndex, 0, textPart);
3546
- offset += 1;
3475
+ let offset = 0;
3476
+ for (const seg of surviving) {
3477
+ const textPart = AgentMessagePartSchema2.parse({
3478
+ type: "text",
3479
+ text: seg.text,
3480
+ ...seg.provider !== undefined && { provider: seg.provider }
3481
+ });
3482
+ const targetIndex = Math.min(seg.insertIndex + offset, state.parts.length);
3483
+ state.parts.splice(targetIndex, 0, textPart);
3484
+ offset += 1;
3485
+ }
3486
+ if (state.firstOutputAt === undefined)
3487
+ state.firstOutputAt = performance.now();
3488
+ await execution.operationLifecycle.firstOutput();
3489
+ const { publish, now, runtimeEpoch } = execution.dependencies;
3490
+ for (const seg of surviving) {
3491
+ state.transientChars.text += seg.text.length;
3492
+ await publish({
3493
+ type: "assistant-delta",
3494
+ conversationId: state.run.conversationId,
3495
+ runId: state.run.id,
3496
+ runtimeEpoch,
3497
+ sequence: transientSequence(state),
3498
+ textDelta: seg.text,
3499
+ emittedAt: now().toISOString()
3500
+ });
3501
+ }
3502
+ return {
3503
+ hadHeldText: true,
3504
+ releasedText: surviving.map((seg) => seg.text).join(""),
3505
+ rawText,
3506
+ ...changed && { segmentOverrides: overrides }
3507
+ };
3508
+ }
3509
+
3510
+ // src/agent-runtime/loop/run-tool-errors.ts
3511
+ function formatSafeValidationIssues(cause) {
3512
+ if (!isRecord(cause) || !Array.isArray(cause.issues) || cause.issues.length === 0) {
3513
+ return;
3514
+ }
3515
+ const summaries = [];
3516
+ for (const issue of cause.issues.slice(0, 5)) {
3517
+ if (!isRecord(issue) || typeof issue.message !== "string")
3518
+ continue;
3519
+ const path = Array.isArray(issue.path) ? issue.path.filter((segment) => typeof segment === "string" || typeof segment === "number").join(".") : "";
3520
+ summaries.push(path.length > 0 ? `${path}: ${issue.message}` : issue.message);
3521
+ }
3522
+ if (summaries.length === 0)
3523
+ return;
3524
+ const suffix = cause.issues.length > 5 ? ` (+${cause.issues.length - 5} more)` : "";
3525
+ return `${summaries.join("; ")}${suffix}`;
3526
+ }
3527
+
3528
+ class AgentUnknownToolError2 extends Error {
3529
+ reason = "unknown-tool";
3530
+ toolName;
3531
+ activeTools;
3532
+ constructor(toolName, options) {
3533
+ super(`Unknown or inactive tool "${toolName}"`, options?.cause !== undefined ? { cause: options.cause } : undefined);
3534
+ this.name = "AgentUnknownToolError";
3535
+ this.toolName = toolName;
3536
+ if (options?.activeTools !== undefined) {
3537
+ this.activeTools = [...options.activeTools];
3538
+ }
3539
+ }
3540
+ }
3541
+
3542
+ class AgentInvalidToolInputError2 extends Error {
3543
+ toolName;
3544
+ reason;
3545
+ constructor(toolName, options) {
3546
+ const detail = options.reason === "validation-failed" ? formatSafeValidationIssues(options.cause) : undefined;
3547
+ 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}"`;
3548
+ super(message, options.cause !== undefined ? { cause: options.cause } : undefined);
3549
+ this.name = "AgentInvalidToolInputError";
3550
+ this.toolName = toolName;
3551
+ this.reason = options.reason;
3547
3552
  }
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
- });
3553
+ }
3554
+ function safeToolErrorMessage(error) {
3555
+ if (isAgentToolError2(error) || error instanceof AgentUnknownToolError2 || error instanceof AgentInvalidToolInputError2) {
3556
+ return error.message;
3562
3557
  }
3563
- return {
3564
- hadHeldText: true,
3565
- releasedText: surviving.map((seg) => seg.text).join(""),
3566
- rawText,
3567
- ...changed && { segmentOverrides: overrides }
3568
- };
3558
+ return "Tool execution failed";
3569
3559
  }
3570
3560
 
3571
3561
  // src/agent-runtime/loop/run-stream-parts.ts
@@ -3612,6 +3602,7 @@ async function applyTextPart(execution, part) {
3612
3602
  appendHeldStepTextDelta(state, part.id, part.text, part.provider);
3613
3603
  } else if (part.type === "text-delta") {
3614
3604
  updateTextBlock(state, part.text, part.provider, part.id);
3605
+ state.transientChars.text += part.text.length;
3615
3606
  await publish({
3616
3607
  type: "assistant-delta",
3617
3608
  ...transientHead(execution),
@@ -3649,6 +3640,7 @@ async function applyTextPart(execution, part) {
3649
3640
  throw new AgentStepBarrierError2("reasoning", `A step reasoned past its bound of ${limit} characters`, action);
3650
3641
  }
3651
3642
  updateReasoning(state, part.text, part.provider, part.id);
3643
+ state.transientChars.reasoning += part.text.length;
3652
3644
  await publish({
3653
3645
  type: "reasoning-delta",
3654
3646
  ...transientHead(execution),
@@ -3729,7 +3721,7 @@ async function applyToolPart(execution, part) {
3729
3721
  throw part.error;
3730
3722
  }
3731
3723
  state.stepGuard.toolFailed = true;
3732
- const output = isAgentToolError2(part.error) ? jsonValue(part.error.output) : { message: "Tool execution failed" };
3724
+ const output = isAgentToolError2(part.error) ? jsonValue(part.error.output) : { message: safeToolErrorMessage(part.error) };
3733
3725
  state.parts.push(AgentMessagePartSchema2.parse({
3734
3726
  type: "tool-result",
3735
3727
  callId: part.toolCallId,
@@ -3930,51 +3922,6 @@ async function classifyRunFailure(execution, error) {
3930
3922
  }
3931
3923
  }
3932
3924
 
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
3925
  // src/agent-runtime/loop/run-tool-progress.ts
3979
3926
  var TOOL_PROGRESS_MIN_INTERVAL_MS = 250;
3980
3927
  function finite(value) {
@@ -4016,22 +3963,6 @@ function createCallSlotResult() {
4016
3963
  toolResults: []
4017
3964
  };
4018
3965
  }
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
3966
  function defaultToolWireOutput(output) {
4036
3967
  if (typeof output === "string")
4037
3968
  return { type: "text", value: output };
@@ -4059,68 +3990,6 @@ function buildToolDurability(execution, toolName, toolCallId, signal) {
4059
3990
  signal
4060
3991
  });
4061
3992
  }
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
3993
  function resolveSingleToolHooks(input) {
4125
3994
  if (input.hooks !== undefined)
4126
3995
  return input.hooks;
@@ -4260,6 +4129,80 @@ async function preflightStandaloneApprovals(input) {
4260
4129
  }
4261
4130
  }
4262
4131
 
4132
+ // src/agent-runtime/loop/run-tool-call-input.ts
4133
+ function parseJsonArgs(raw) {
4134
+ const trimmed = raw.trim();
4135
+ if (trimmed.length === 0)
4136
+ return { ok: true, value: {} };
4137
+ try {
4138
+ return { ok: true, value: JSON.parse(trimmed) };
4139
+ } catch (error) {
4140
+ return { ok: false, error };
4141
+ }
4142
+ }
4143
+ async function resolveToolCallInput(input) {
4144
+ const activeSet = new Set(input.activeTools);
4145
+ const attemptResolve = async (name, rawArgs) => {
4146
+ const tool = activeSet.has(name) && Object.hasOwn(input.tools, name) ? input.tools[name] : undefined;
4147
+ if (!tool) {
4148
+ return {
4149
+ ok: false,
4150
+ kind: "unknown-tool",
4151
+ toolName: name,
4152
+ parsedInput: rawArgs,
4153
+ error: new AgentUnknownToolError2(name, { activeTools: input.activeTools })
4154
+ };
4155
+ }
4156
+ const json = parseJsonArgs(rawArgs);
4157
+ if (!json.ok) {
4158
+ return {
4159
+ ok: false,
4160
+ kind: "invalid-input",
4161
+ toolName: name,
4162
+ parsedInput: rawArgs,
4163
+ error: new AgentInvalidToolInputError2(name, {
4164
+ reason: "invalid-json",
4165
+ cause: json.error
4166
+ })
4167
+ };
4168
+ }
4169
+ if (tool.parseInput) {
4170
+ const checked = await tool.parseInput(json.value);
4171
+ if (!checked.ok) {
4172
+ return {
4173
+ ok: false,
4174
+ kind: "invalid-input",
4175
+ toolName: name,
4176
+ parsedInput: json.value,
4177
+ error: new AgentInvalidToolInputError2(name, {
4178
+ reason: "validation-failed",
4179
+ cause: checked.error
4180
+ })
4181
+ };
4182
+ }
4183
+ return { ok: true, toolName: name, tool, parsedInput: checked.value };
4184
+ }
4185
+ return { ok: true, toolName: name, tool, parsedInput: json.value };
4186
+ };
4187
+ const first = await attemptResolve(input.raw.toolName, input.raw.input);
4188
+ if (first.ok || !input.repairToolCall)
4189
+ return first;
4190
+ const repaired = await input.repairToolCall({
4191
+ toolCall: {
4192
+ toolCallId: input.raw.toolCallId,
4193
+ toolName: input.raw.toolName,
4194
+ input: input.raw.input
4195
+ },
4196
+ activeTools: input.activeTools,
4197
+ tools: input.tools,
4198
+ messages: input.messages,
4199
+ error: { kind: first.kind, toolName: first.toolName, cause: first.error }
4200
+ });
4201
+ if (!repaired)
4202
+ return first;
4203
+ return attemptResolve(repaired.toolName, repaired.input);
4204
+ }
4205
+
4263
4206
  // src/agent-runtime/loop/run-tool-slots.ts
4264
4207
  function emptyStepToolExecutionResult() {
4265
4208
  return collectStepToolExecutionResult([], 0, 0);
@@ -5066,11 +5009,262 @@ async function executeStepToolCalls(input) {
5066
5009
  if (collector.pendingExecutions.length > 0) {
5067
5010
  await Promise.allSettled(collector.pendingExecutions);
5068
5011
  }
5069
- stepSignalLink.release();
5070
- if (mode.kind === "durable")
5071
- mode.execution.idleDeadline.resume();
5012
+ stepSignalLink.release();
5013
+ if (mode.kind === "durable")
5014
+ mode.execution.idleDeadline.resume();
5015
+ }
5016
+ return collectStepToolExecutionResult(callSlots, clientCalls.length, collector.settledClientToolCount);
5017
+ }
5018
+
5019
+ // src/agent-runtime/loop/run-step-loop.ts
5020
+ async function callStepModel(port, state, step) {
5021
+ const windowStart = performance.now();
5022
+ const discarded = [];
5023
+ for (let attempt = 1;; attempt += 1) {
5024
+ port.signal.throwIfAborted();
5025
+ const callId = port.newCallId();
5026
+ const driver = await port.openCall({
5027
+ stepNumber: step.stepNumber,
5028
+ attempt,
5029
+ callId,
5030
+ stepModel: step.stepModel,
5031
+ driver: step.baseDriver,
5032
+ instructions: step.instructions,
5033
+ messages: state.currentMessages
5034
+ });
5035
+ const request = port.buildRequest({
5036
+ prepared: step.prepared,
5037
+ instructions: step.instructions,
5038
+ messages: state.currentMessages,
5039
+ specs: step.specs,
5040
+ callId,
5041
+ stepNumber: step.stepNumber
5042
+ });
5043
+ let decided;
5044
+ let refused = false;
5045
+ const decide = async (error) => {
5046
+ if (decided !== undefined)
5047
+ return true;
5048
+ if (refused || port.signal.aborted || !port.retry || port.callInvokedTool())
5049
+ return false;
5050
+ const failure = classifyProviderFailure2(error);
5051
+ const decision = await port.decideRetry({
5052
+ error,
5053
+ attempt,
5054
+ failure,
5055
+ elapsedMs: Math.max(0, performance.now() - windowStart)
5056
+ });
5057
+ if (!decision.retry) {
5058
+ refused = true;
5059
+ return false;
5060
+ }
5061
+ decided = { error, failure, delayMs: decision.delayMs };
5062
+ return true;
5063
+ };
5064
+ let usage;
5065
+ let failedError;
5066
+ try {
5067
+ const outcome = await port.streamCall({
5068
+ stepNumber: step.stepNumber,
5069
+ attempt,
5070
+ callId,
5071
+ driver,
5072
+ request,
5073
+ stepModel: step.stepModel,
5074
+ retryOnFailure: decide
5075
+ });
5076
+ if (outcome.kind === "ended")
5077
+ return outcome;
5078
+ if (outcome.kind === "finished") {
5079
+ if (outcome.consumed.finishPart)
5080
+ return { ...outcome, callId, request, driver };
5081
+ if (await port.missingFinish(outcome.consumed, driver) === "ended") {
5082
+ return { kind: "ended" };
5083
+ }
5084
+ } else {
5085
+ usage = outcome.usage;
5086
+ if (outcome.kind === "failed")
5087
+ failedError = outcome.error;
5088
+ }
5089
+ } catch (error) {
5090
+ if (port.signal.aborted || !hasProviderOrigin(error))
5091
+ throw error;
5092
+ failedError = error;
5093
+ }
5094
+ if (decided === undefined) {
5095
+ const error = failedError;
5096
+ if (!await decide(error)) {
5097
+ const failure = classifyProviderFailure2(error);
5098
+ const spent = state.discardedUsage !== undefined ? addUsage(state.stepUsage, state.discardedUsage) : state.stepUsage;
5099
+ throw port.refuseRetry({
5100
+ error,
5101
+ attempts: [
5102
+ ...discarded,
5103
+ { attempt, error, failure, ...usage !== undefined && { usage } }
5104
+ ],
5105
+ usage: usage !== undefined ? addUsage(spent, usage) : spent
5106
+ });
5107
+ }
5108
+ }
5109
+ if (decided === undefined)
5110
+ throw failedError;
5111
+ if (port.signal.aborted)
5112
+ return { kind: "ended" };
5113
+ const call = {
5114
+ attempt,
5115
+ error: decided.error,
5116
+ failure: decided.failure,
5117
+ ...usage !== undefined && { usage }
5118
+ };
5119
+ discarded.push(call);
5120
+ if (usage !== undefined)
5121
+ state.discardedUsage = addUsage(state.discardedUsage, usage);
5122
+ await port.discardCall(call);
5123
+ await port.onAttemptDiscarded?.({
5124
+ attempt,
5125
+ reason: call.failure.reason,
5126
+ ...usage !== undefined && { usage }
5127
+ });
5128
+ await port.announceDiscard(call);
5129
+ if (decided.delayMs > 0)
5130
+ await sleep(decided.delayMs, port.signal);
5131
+ if (port.signal.aborted)
5132
+ return { kind: "ended" };
5133
+ await port.announceRetry(call);
5134
+ }
5135
+ }
5136
+ async function runOneStep(port, state, stepNumber) {
5137
+ port.signal.throwIfAborted();
5138
+ await port.startStep();
5139
+ const defaultInstructions = state.continuationInstructions ?? state.carriedInstructions;
5140
+ state.continuationInstructions = undefined;
5141
+ const declaredTools = port.tools ? Object.keys(port.tools) : [];
5142
+ const prepared = await port.prepareStep({
5143
+ stepNumber,
5144
+ steps: state.steps,
5145
+ messages: state.currentMessages,
5146
+ responseMessages: state.responseMessages,
5147
+ initialMessages: port.initialMessages,
5148
+ initialInstructions: port.initialInstructions,
5149
+ instructions: defaultInstructions,
5150
+ driver: port.baseDriver,
5151
+ activeTools: declaredTools
5152
+ });
5153
+ const injected = await port.takeInjectedMessages();
5154
+ state.currentMessages = [...prepared?.messages ?? state.currentMessages, ...injected];
5155
+ if (prepared?.instructions !== undefined)
5156
+ state.carriedInstructions = prepared.instructions;
5157
+ const instructions = prepared?.instructions ?? defaultInstructions;
5158
+ const { activeNames, specs } = port.tools ? buildActiveToolSpecs(port.tools, prepared?.activeTools) : { activeNames: [], specs: [] };
5159
+ const baseDriver = prepared?.driver ?? port.baseDriver;
5160
+ const stepModel = port.stepModel(baseDriver);
5161
+ const call = await callStepModel(port, state, {
5162
+ stepNumber,
5163
+ prepared,
5164
+ instructions,
5165
+ specs,
5166
+ baseDriver,
5167
+ stepModel
5168
+ });
5169
+ if (call.kind === "ended")
5170
+ return "ended";
5171
+ const { consumed, stepStartedAt, responseFinishedAt } = call;
5172
+ const finishPart = consumed.finishPart;
5173
+ if (!finishPart)
5174
+ return "ended";
5175
+ const unsafeForClientTools = isStepUnsafeForClientTools(finishPart.finishReason, consumed.sawErrorPart);
5176
+ const runTools = !unsafeForClientTools && port.tools !== undefined;
5177
+ const toolStartedAt = performance.now();
5178
+ const toolExecution = runTools && port.tools ? await executeStepToolCalls({
5179
+ stepNumber,
5180
+ rawCalls: consumed.rawToolCalls,
5181
+ tools: port.tools,
5182
+ activeTools: activeNames,
5183
+ repairToolCall: port.repairToolCall,
5184
+ instructions: call.request.instructions,
5185
+ messages: state.currentMessages,
5186
+ signal: port.signal,
5187
+ mode: port.toolMode
5188
+ }) : emptyStepToolExecutionResult();
5189
+ const stepFinishedAt = performance.now();
5190
+ const timings = buildStepTimings({
5191
+ stepStartedAt,
5192
+ responseFinishedAt,
5193
+ stepFinishedAt,
5194
+ firstOutputAt: consumed.firstOutputAt,
5195
+ toolExecutionMs: runTools ? Math.max(0, stepFinishedAt - toolStartedAt) : 0,
5196
+ outputChunkTimestamps: consumed.outputChunkTimestamps
5197
+ });
5198
+ const stepTextOverrides = await port.stepTextOverrides({
5199
+ finishPart,
5200
+ consumed,
5201
+ toolExecution
5202
+ });
5203
+ const stepUsage = statedUsage(finishPart.usage);
5204
+ const { resolvedResponseId, stepResponseMessages, stepResult } = assembleStepResult({
5205
+ stepNumber,
5206
+ callId: call.callId,
5207
+ model: stepModel,
5208
+ consumed,
5209
+ finishPart,
5210
+ toolExecution,
5211
+ timings,
5212
+ stepUsage,
5213
+ ...stepTextOverrides !== undefined && { stepTextOverrides }
5214
+ });
5215
+ state.currentMessages = [...state.currentMessages, ...stepResponseMessages];
5216
+ state.responseMessages.push(...stepResponseMessages);
5217
+ state.stepUsage = addUsage(state.stepUsage, stepUsage);
5218
+ state.lastFinishReason = finishPart.finishReason;
5219
+ state.steps.push(stepResult);
5220
+ await port.finishStep({
5221
+ stepNumber,
5222
+ stepResult,
5223
+ resolvedResponseId,
5224
+ consumed,
5225
+ finishPart,
5226
+ timings,
5227
+ stepUsage
5228
+ });
5229
+ const canContinue = !unsafeForClientTools && toolExecution.clientToolCallCount > 0 && toolExecution.settledClientToolCount === toolExecution.clientToolCallCount;
5230
+ if (!canContinue)
5231
+ return "last";
5232
+ if (await port.shouldStop(state.steps))
5233
+ return "last";
5234
+ return "continue";
5235
+ }
5236
+ async function runModelStepLoop(port, state) {
5237
+ for (let stepNumber = 0;; stepNumber += 1) {
5238
+ const outcome = await runOneStep(port, state, stepNumber);
5239
+ if (outcome === "ended")
5240
+ return "ended";
5241
+ if (outcome === "continue")
5242
+ continue;
5243
+ const next = await port.afterLastStep(state);
5244
+ if (next.action === "stop")
5245
+ return "completed";
5246
+ state.currentMessages = [...state.currentMessages, next.message];
5247
+ state.responseMessages.push(next.message);
5248
+ state.continuationInstructions = next.instructions;
5072
5249
  }
5073
- return collectStepToolExecutionResult(callSlots, clientCalls.length, collector.settledClientToolCount);
5250
+ }
5251
+ function initialStepLoopState(messages, instructions) {
5252
+ return {
5253
+ currentMessages: [...messages],
5254
+ responseMessages: [],
5255
+ steps: [],
5256
+ stepUsage: undefined,
5257
+ discardedUsage: undefined,
5258
+ lastFinishReason: "stop",
5259
+ carriedInstructions: instructions,
5260
+ continuationInstructions: undefined
5261
+ };
5262
+ }
5263
+
5264
+ // src/agent-runtime/loop/run-step-port.ts
5265
+ var DEFAULT_IDLE_TIMEOUT_MS = 60000;
5266
+ function resolveIdleTimeoutMs(declared) {
5267
+ return declared === null ? undefined : declared ?? DEFAULT_IDLE_TIMEOUT_MS;
5074
5268
  }
5075
5269
 
5076
5270
  // src/agent-runtime/loop/runtime-control.ts
@@ -5519,9 +5713,6 @@ function createAgentRunOperationLifecycle(config) {
5519
5713
  checkpointStep(step) {
5520
5714
  checkpointedStep = Math.max(checkpointedStep, step);
5521
5715
  },
5522
- resetCheckpointStep() {
5523
- checkpointedStep = -1;
5524
- },
5525
5716
  startCompaction(operationId) {
5526
5717
  return record(AgentRunOperationSchema2.parse({
5527
5718
  operationId,
@@ -5617,6 +5808,7 @@ async function acquireRun(dependencies, input) {
5617
5808
  absorbed: new Map,
5618
5809
  eventsSinceCheckpoint: 0,
5619
5810
  sequence: 0,
5811
+ transientChars: { text: 0, reasoning: 0 },
5620
5812
  settledToolCalls: new Set,
5621
5813
  terminalReason: "success",
5622
5814
  nonModelUsage: input.acceptedRun.usage,
@@ -5699,9 +5891,6 @@ async function beginRunExecution(execution) {
5699
5891
  }), "assistant draft"));
5700
5892
  }
5701
5893
 
5702
- // src/agent-runtime/loop/run-model-attempts.ts
5703
- import { setTimeout as delay } from "node:timers/promises";
5704
-
5705
5894
  // src/agent-runtime/loop/run-model-stream.ts
5706
5895
  async function consumeModelStepStream(input) {
5707
5896
  const { execution, turn, ledger, modelStream, emit } = input;
@@ -5717,6 +5906,7 @@ async function consumeModelStepStream(input) {
5717
5906
  }
5718
5907
  })) {
5719
5908
  idleDeadline.touch();
5909
+ input.onProviderPart?.(part);
5720
5910
  if (input.isDraining()) {
5721
5911
  if (part.type === "finish") {
5722
5912
  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 +5978,10 @@ async function consumeModelStepStream(input) {
5788
5978
  return acc.result;
5789
5979
  }
5790
5980
 
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
5981
  // 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({
5982
+ function finishStepEvent(step) {
5983
+ const { consumed, finishPart, stepResult, resolvedResponseId, stepUsage, timings } = step;
5984
+ return {
5939
5985
  type: "finish-step",
5940
5986
  finishReason: finishPart.finishReason,
5941
5987
  ...finishPart.rawFinishReason !== undefined && {
@@ -5955,7 +6001,18 @@ async function recordCompletedStep(input) {
5955
6001
  usage: stepUsage,
5956
6002
  ...finishPart.costDetails !== undefined && { costDetails: finishPart.costDetails },
5957
6003
  timings
6004
+ };
6005
+ }
6006
+ async function settleHeldStepText(execution, input) {
6007
+ if (execution.dependencies.config.loop?.stepBarriers?.stepText !== "after-tools") {
6008
+ return;
6009
+ }
6010
+ const flushed = await flushHeldStepTextWithOutcome(execution, false, {
6011
+ finishReason: input.finishPart.finishReason,
6012
+ toolCalls: [...input.consumed.providerToolCalls, ...input.toolExecution.toolCalls],
6013
+ toolResults: [...input.consumed.providerToolResults, ...input.toolExecution.toolResults]
5958
6014
  });
6015
+ return flushed.segmentOverrides;
5959
6016
  }
5960
6017
  async function openStepStream(execution, driver, request, stepSignal) {
5961
6018
  execution.idleDeadline.start();
@@ -5985,6 +6042,7 @@ async function streamStepWithIsolatedAbort(input) {
5985
6042
  isDraining: input.isDraining,
5986
6043
  onErrorPart: input.onErrorPart,
5987
6044
  onAbandonedUsage: input.onAbandonedUsage,
6045
+ onProviderPart: input.onProviderPart,
5988
6046
  abortStepStream: () => stepAbort.abort(new Error("Agent runtime released step provider stream")),
5989
6047
  modelStream,
5990
6048
  emit: input.emit
@@ -5993,153 +6051,98 @@ async function streamStepWithIsolatedAbort(input) {
5993
6051
  stepLink.release();
5994
6052
  }
5995
6053
  }
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
6054
+
6055
+ // src/agent-runtime/loop/run-model-call.ts
6056
+ function startRuntimeCall(execution) {
6057
+ const { state } = execution;
6058
+ return {
6059
+ partStart: state.parts.length,
6060
+ retained: { ...state.transientChars },
6061
+ draining: false,
6062
+ usage: undefined,
6063
+ invokedTool: false
6043
6064
  };
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
- });
6065
+ }
6066
+ async function streamRuntimeCall(input) {
6067
+ const { execution, call, step } = input;
6065
6068
  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
6069
+ const retrying = () => ({
6070
+ kind: "retrying",
6071
+ ...call.usage !== undefined && { usage: call.usage }
6081
6072
  });
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",
6073
+ let consumed;
6074
+ try {
6075
+ consumed = await streamStepWithIsolatedAbort({
6110
6076
  execution,
6111
- toolApproval: turn.toolApproval,
6112
- emit
6077
+ turn: input.turn,
6078
+ ledger: input.ledger,
6079
+ effectiveDriver: step.driver,
6080
+ request: step.request,
6081
+ callId: step.callId,
6082
+ providerAttempt: step.attempt,
6083
+ stepStartedAt,
6084
+ stepModel: step.stepModel,
6085
+ attemptSignal: execution.executionSignal,
6086
+ isDraining: () => call.draining,
6087
+ onErrorPart: async (error) => {
6088
+ if (await step.retryOnFailure(error))
6089
+ call.draining = true;
6090
+ return call.draining;
6091
+ },
6092
+ onAbandonedUsage: (usage) => {
6093
+ call.usage = addUsage(call.usage, usage);
6094
+ },
6095
+ onProviderPart: (part) => {
6096
+ if (providerToolActed(part))
6097
+ call.invokedTool = true;
6098
+ },
6099
+ emit: input.emit
6100
+ });
6101
+ } catch (error) {
6102
+ if (!call.draining || execution.executionSignal.aborted || !hasProviderOrigin(error)) {
6103
+ throw error;
6113
6104
  }
6105
+ return retrying();
6106
+ }
6107
+ if (call.draining)
6108
+ return retrying();
6109
+ return { kind: "finished", consumed, stepStartedAt, responseFinishedAt: performance.now() };
6110
+ }
6111
+ async function withdrawRuntimeCall(execution, call) {
6112
+ const { state } = execution;
6113
+ await execution.operationLifecycle.finish("failed");
6114
+ state.parts.splice(call.partStart);
6115
+ state.stepGuard = { text: "", toolFailed: false, reasoningChars: 0 };
6116
+ resetStepTextTracking(state);
6117
+ state.reasoningPartIndex = undefined;
6118
+ state.reasoningPartIndexes.clear();
6119
+ state.textPartIndex = undefined;
6120
+ state.textPartIndexes.clear();
6121
+ await checkpoint(execution);
6122
+ state.eventsSinceCheckpoint = 0;
6123
+ }
6124
+ async function announceRuntimeRetry(execution, call, attempt) {
6125
+ const { config, publish, now, runtimeEpoch } = execution.dependencies;
6126
+ const { state } = execution;
6127
+ await config.store.appendEvent({
6128
+ conversationId: state.run.conversationId,
6129
+ kind: "retry/started",
6130
+ payload: { attempt }
6114
6131
  });
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
6132
+ await publish({
6133
+ type: "attempt-reset",
6134
+ conversationId: state.run.conversationId,
6135
+ runId: state.run.id,
6136
+ runtimeEpoch,
6137
+ sequence: transientSequence(state),
6138
+ attempt,
6139
+ withdrawn: {
6140
+ text: state.transientChars.text - call.retained.text,
6141
+ reasoning: state.transientChars.reasoning - call.retained.reasoning
6142
+ },
6143
+ emittedAt: now().toISOString()
6136
6144
  });
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";
6145
+ state.transientChars = { ...call.retained };
6143
6146
  }
6144
6147
 
6145
6148
  // src/agent-runtime/loop/run-provider-ledger.ts
@@ -6251,85 +6254,112 @@ async function createRunProviderLedger(input) {
6251
6254
  };
6252
6255
  }
6253
6256
 
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;
6257
+ // src/agent-runtime/loop/run-step-prepare.ts
6258
+ function buildStepRequest(input) {
6259
+ const { prepared } = input;
6260
+ return {
6261
+ instructions: normalizeAgentInstructions(input.instructions),
6262
+ messages: input.messages,
6263
+ tools: input.toolSpecs,
6264
+ ...prepared?.toolChoice !== undefined && { toolChoice: prepared.toolChoice },
6265
+ ...prepared?.responseFormat !== undefined && { responseFormat: prepared.responseFormat },
6266
+ ...prepared?.cacheControl !== undefined && { cacheControl: prepared.cacheControl },
6267
+ settings: mergeStepCallSettings(undefined, prepared),
6268
+ ...prepared?.providerOptions !== undefined && {
6269
+ providerOptions: prepared.providerOptions
6270
+ },
6271
+ ...prepared?.headers !== undefined && { headers: prepared.headers },
6272
+ correlation: {
6273
+ conversationId: input.conversationId,
6274
+ runId: input.runId,
6275
+ attemptId: input.attemptId,
6276
+ step: input.stepNumber
6277
+ }
6278
+ };
6279
+ }
6280
+ async function evaluateStopPolicies(execution, turn, steps) {
6281
+ const { config, maxSteps } = execution.dependencies;
6258
6282
  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);
6283
+ if (steps.length >= maxSteps) {
6284
+ state.terminalPolicyName ??= "max-steps";
6285
+ return true;
6269
6286
  }
6270
- return messages;
6287
+ for (const policy of config.loop?.stopPolicies ?? []) {
6288
+ if (await policy.when({ steps, ...turn.runtimeContext })) {
6289
+ state.terminalPolicyName ??= policy.name;
6290
+ return true;
6291
+ }
6292
+ }
6293
+ return false;
6271
6294
  }
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;
6295
+ function hasPendingApproval(parts) {
6296
+ const responded = new Set;
6297
+ for (const part of parts) {
6298
+ if (part.type === "tool-approval-response")
6299
+ responded.add(part.approvalId);
6279
6300
  }
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)
6301
+ return parts.some((part) => part.type === "tool-approval-request" && !responded.has(part.approvalId));
6302
+ }
6303
+ async function evaluateTerminalContinuation(input) {
6304
+ const {
6305
+ execution,
6306
+ lastFinishReason,
6307
+ steps,
6308
+ continuations,
6309
+ maxContinuations,
6310
+ attemptSignal
6311
+ } = input;
6312
+ const { config, now, maxSteps } = execution.dependencies;
6313
+ const { state } = execution;
6314
+ const acceptTerminal = config.protocol.acceptTerminal;
6315
+ if (!acceptTerminal || attemptSignal.aborted || hasPendingApproval(state.parts)) {
6316
+ return { action: "stop" };
6317
+ }
6318
+ const candidateReason = state.terminalPolicyName !== undefined ? "policy_stop" : state.terminalReason !== "success" ? state.terminalReason : lastFinishReason === "stop" ? "success" : lastFinishReason === "error" ? "provider_failure" : "provider_stop";
6319
+ if (candidateReason !== "success" && candidateReason !== "policy_stop" && candidateReason !== "provider_stop") {
6320
+ return { action: "stop" };
6321
+ }
6322
+ const candidate = AgentMessageSchema2.parse({
6323
+ ...state.assistant,
6324
+ status: assistantStatus(candidateReason),
6325
+ parts: state.parts,
6326
+ updatedAt: now().toISOString()
6294
6327
  });
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);
6328
+ const verdict = await acceptTerminal({
6329
+ message: candidate,
6330
+ reason: candidateReason,
6331
+ ...state.terminalPolicyName && { policyName: state.terminalPolicyName },
6332
+ steps,
6333
+ continuations
6334
+ });
6335
+ if (verdict === true || typeof verdict === "object" && verdict.action === "accept") {
6336
+ state.terminalDecision = "accepted";
6337
+ return { action: "stop" };
6302
6338
  }
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
- }
6339
+ if (verdict === false || typeof verdict === "object" && verdict.action === "reject") {
6340
+ state.terminalDecision = "rejected";
6341
+ state.terminalReason = "output_rejected";
6342
+ state.internalCause = new Error("Agent terminal output was rejected by the protocol");
6343
+ return { action: "stop" };
6318
6344
  }
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;
6345
+ if (continuations >= maxContinuations || steps.length >= maxSteps) {
6346
+ state.terminalDecision = "rejected";
6347
+ state.terminalReason = "output_rejected";
6348
+ state.internalCause = new Error(continuations >= maxContinuations ? `Agent terminal continuation exceeded maxContinuations (${maxContinuations})` : `Agent terminal continuation exceeded maxSteps (${maxSteps})`);
6349
+ return { action: "stop" };
6328
6350
  }
6329
- return true;
6351
+ state.terminalDecision = undefined;
6352
+ state.terminalPolicyName = undefined;
6353
+ return {
6354
+ action: "continue",
6355
+ message: verdict.message,
6356
+ ...verdict.instructions !== undefined && { instructions: verdict.instructions }
6357
+ };
6330
6358
  }
6331
- async function dispatchLoopEvent(context, scope, part) {
6332
- const { execution } = context;
6359
+
6360
+ // src/agent-runtime/loop/run-model-steps.ts
6361
+ var DEFAULT_MAX_CONTINUATIONS = 3;
6362
+ async function dispatchLoopEvent(execution, scope, part) {
6333
6363
  const { checkpointEveryEvents } = execution.dependencies;
6334
6364
  const { state, operationLifecycle } = execution;
6335
6365
  state.eventsSinceCheckpoint += 1;
@@ -6353,113 +6383,139 @@ async function dispatchLoopEvent(context, scope, part) {
6353
6383
  operationLifecycle.checkpointStep(state.step - 1);
6354
6384
  }
6355
6385
  }
6356
- async function runSingleAttempt(context, attempt, attemptSignal) {
6357
- const { execution, turn, ledger } = context;
6358
- const { config } = execution.dependencies;
6386
+ async function takeInjectedMessages(execution, turn) {
6387
+ const { state } = execution;
6388
+ const taken = execution.dependencies.injection?.take(execution.input.key, state.run.id) ?? [];
6389
+ const messages = [];
6390
+ for (const entry of taken) {
6391
+ messages.push(...await turn.projection.projectInputs([entry.input]));
6392
+ const ids = state.absorbed.get(entry.runId) ?? [];
6393
+ ids.push(entry.input.id);
6394
+ state.absorbed.set(entry.runId, ids);
6395
+ }
6396
+ return messages;
6397
+ }
6398
+ function createRuntimeStepPort(execution, turn, ledger, baseMessages) {
6399
+ const { config, generateId } = execution.dependencies;
6400
+ const { state, operationLifecycle, executionSignal } = execution;
6359
6401
  const scope = {
6360
6402
  selectedModel: turn.selectedModel,
6361
6403
  ledger,
6362
- providerAttempt: attempt.providerAttempt
6404
+ providerAttempt: 1
6363
6405
  };
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));
6406
+ const emit = (event) => dispatchLoopEvent(execution, scope, event);
6407
+ let call = startRuntimeCall(execution);
6368
6408
  const maxContinuations = config.loop?.maxContinuations ?? DEFAULT_MAX_CONTINUATIONS;
6369
6409
  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,
6410
+ const retry = config.loop?.retry;
6411
+ const onAttemptDiscarded = config.loop?.onAttemptDiscarded;
6412
+ const port = {
6413
+ tools: turn.tools,
6414
+ baseDriver: turn.selectedModel.driver,
6415
+ initialMessages: baseMessages,
6416
+ initialInstructions: turn.projection.withCarriedSystem(turn.prompt.instructions),
6417
+ signal: executionSignal,
6418
+ repairToolCall: config.loop?.repairToolCall,
6419
+ retry,
6420
+ ...onAttemptDiscarded !== undefined && { onAttemptDiscarded },
6421
+ toolMode: { kind: "durable", execution, toolApproval: turn.toolApproval, emit },
6422
+ startStep: () => emit({ type: "start-step" }),
6423
+ prepareStep: async (input) => await config.loop?.prepareStep?.({ ...input, ...turn.runtimeContext }) ?? undefined,
6424
+ takeInjectedMessages: () => takeInjectedMessages(execution, turn),
6425
+ stepModel: (driver) => {
6426
+ const stepModel = driver !== turn.selectedModel.driver ? { modelId: driver.modelId, provider: driver.provider } : {
6427
+ modelId: turn.selectedModel.descriptor.modelId,
6428
+ provider: turn.selectedModel.descriptor.provider
6429
+ };
6430
+ scope.stepModel = stepModel;
6431
+ return stepModel;
6432
+ },
6433
+ newCallId: generateId,
6434
+ openCall: async ({
6435
+ stepNumber,
6436
+ attempt,
6437
+ callId,
6438
+ stepModel,
6439
+ driver,
6440
+ instructions,
6441
+ messages
6442
+ }) => {
6443
+ call = startRuntimeCall(execution);
6444
+ scope.providerAttempt = attempt;
6445
+ await ledger.recordRequest({
6400
6446
  stepNumber,
6401
- initialInstructions,
6402
- declaredToolNames,
6403
- repairToolCall,
6404
- runState
6447
+ attempt,
6448
+ modelId: stepModel.modelId,
6449
+ instructions,
6450
+ messages
6405
6451
  });
6406
- } catch (error) {
6407
- if (hasProviderOrigin(error)) {
6408
- const retried = await retryAfterProviderError(context, attempt, error, runState.attemptTotalUsage);
6409
- if (retried)
6410
- return;
6452
+ await operationLifecycle.admitModelRequest(stepNumber, callId);
6453
+ return execution.invocation ? execution.invocation.wrap(turn.selectedModel, stepNumber, driver) : driver;
6454
+ },
6455
+ buildRequest: ({ prepared, instructions, messages, specs, callId, stepNumber }) => buildStepRequest({
6456
+ instructions,
6457
+ messages,
6458
+ toolSpecs: specs,
6459
+ prepared,
6460
+ conversationId: state.run.conversationId,
6461
+ runId: state.run.id,
6462
+ attemptId: callId,
6463
+ stepNumber
6464
+ }),
6465
+ streamCall: (step) => streamRuntimeCall({ execution, turn, ledger, call, step, emit }),
6466
+ callInvokedTool: () => call.invokedTool,
6467
+ missingFinish: async (consumed, driver) => {
6468
+ if (executionSignal.aborted) {
6469
+ await emit({ type: "abort" });
6470
+ return "ended";
6411
6471
  }
6412
- throw error;
6413
- }
6414
- if (stepOutcome === "return")
6472
+ if (consumed.sawErrorPart)
6473
+ return "ended";
6474
+ throw markProviderOrigin(new AgentProviderStreamCutError2("Provider stream ended without a finish event", {
6475
+ provider: driver.provider
6476
+ }));
6477
+ },
6478
+ decideRetry: async ({ error, attempt, failure, elapsedMs }) => retry && failureThisRuntimeOwns(error) === undefined ? recordAgentRetryDecision2({
6479
+ store: config.store,
6480
+ conversationId: state.run.conversationId,
6481
+ attempt,
6482
+ failure,
6483
+ policy: retry,
6484
+ elapsedMs
6485
+ }) : { retry: false, delayMs: 0 },
6486
+ discardCall: () => withdrawRuntimeCall(execution, call),
6487
+ announceDiscard: async () => {
6415
6488
  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;
6489
+ },
6490
+ announceRetry: ({ attempt }) => announceRuntimeRetry(execution, call, attempt + 1),
6491
+ refuseRetry: ({ error }) => error,
6492
+ stepTextOverrides: (input) => settleHeldStepText(execution, input),
6493
+ finishStep: (step) => emit(finishStepEvent(step)),
6494
+ shouldStop: (steps) => evaluateStopPolicies(execution, turn, steps),
6495
+ afterLastStep: async (loopState) => {
6496
+ const verdict = await evaluateTerminalContinuation({
6497
+ execution,
6498
+ lastFinishReason: loopState.lastFinishReason,
6499
+ steps: loopState.steps,
6500
+ continuations,
6501
+ maxContinuations,
6502
+ attemptSignal: executionSignal
6503
+ });
6504
+ if (verdict.action === "continue")
6505
+ continuations += 1;
6506
+ return verdict;
6432
6507
  }
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
6508
  };
6509
+ return { port, emit };
6510
+ }
6511
+ async function runModelSteps(execution, turn) {
6449
6512
  const ledger = await createRunProviderLedger({
6450
- store: config.store,
6451
- state,
6513
+ store: execution.dependencies.config.store,
6514
+ state: execution.state,
6452
6515
  selectedModel: turn.selectedModel,
6453
6516
  audited: execution.invocation !== undefined
6454
6517
  });
6455
6518
  const baseMessages = [...turn.history];
6456
- const context = {
6457
- execution,
6458
- turn,
6459
- loop,
6460
- ledger,
6461
- baseMessages
6462
- };
6463
6519
  const continuationScope = {
6464
6520
  selectedModel: turn.selectedModel,
6465
6521
  ledger,
@@ -6471,54 +6527,17 @@ async function runModelAttempts(execution, turn) {
6471
6527
  toolApproval: turn.toolApproval,
6472
6528
  messages: baseMessages,
6473
6529
  signal: execution.executionSignal,
6474
- emit: (event) => dispatchLoopEvent(context, continuationScope, event)
6530
+ emit: (event) => dispatchLoopEvent(execution, continuationScope, event)
6531
+ });
6532
+ const { port, emit } = createRuntimeStepPort(execution, turn, ledger, baseMessages);
6533
+ const state = initialStepLoopState(baseMessages, port.initialInstructions);
6534
+ if (await runModelStepLoop(port, state) === "ended")
6535
+ return;
6536
+ await emit({
6537
+ type: "finish",
6538
+ finishReason: state.lastFinishReason,
6539
+ totalUsage: state.stepUsage ?? unknownUsage()
6475
6540
  });
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
6541
  }
6523
6542
 
6524
6543
  // src/agent-runtime/loop/run-terminal.ts
@@ -7178,7 +7197,7 @@ function createRunExecutor(dependencies) {
7178
7197
  execution.invocation = await beginAgentInvocation(invocations.ledger, dependencies.config.store, { run: execution.state.run, trace }, input.context);
7179
7198
  }
7180
7199
  const turn = await prepareTurn(execution);
7181
- await runModelAttempts(execution, turn);
7200
+ await runModelSteps(execution, turn);
7182
7201
  await settleStreamOutcome(execution);
7183
7202
  } catch (error) {
7184
7203
  await classifyRunFailure(execution, error);
@@ -7210,8 +7229,7 @@ function createRunExecutor(dependencies) {
7210
7229
  function resolveLoopLimits(config) {
7211
7230
  const checkpointEveryEvents = config.loop?.checkpointEveryEvents ?? 20;
7212
7231
  const maxSteps = config.loop?.maxSteps ?? 50;
7213
- const declaredIdleTimeoutMs = config.loop?.idleTimeoutMs;
7214
- const idleTimeoutMs = declaredIdleTimeoutMs === null ? undefined : declaredIdleTimeoutMs ?? 60000;
7232
+ const idleTimeoutMs = resolveIdleTimeoutMs(config.loop?.idleTimeoutMs);
7215
7233
  const declaredMaxDurationMs = config.loop?.maxDurationMs;
7216
7234
  const maxDurationMs = declaredMaxDurationMs === null ? undefined : declaredMaxDurationMs;
7217
7235
  const stepSpendTimeoutMs = config.stepSpendTimeoutMs ?? DEFAULT_STEP_SPEND_TIMEOUT_MS;
@@ -7579,7 +7597,20 @@ function handOffToCoordinator(state, submission, acceptedRun) {
7579
7597
  }
7580
7598
 
7581
7599
  // src/agent-runtime/loop/runtime.ts
7600
+ function assertRuntimeComposition(config) {
7601
+ const missing = [
7602
+ typeof config.protocol === "object" && config.protocol !== null ? undefined : "protocol",
7603
+ typeof config.store === "object" && config.store !== null ? undefined : "store",
7604
+ typeof config.models?.resolve === "function" ? undefined : "models.resolve",
7605
+ typeof config.prompt === "function" ? undefined : "prompt",
7606
+ typeof config.tools === "function" ? undefined : "tools"
7607
+ ].filter((name) => name !== undefined);
7608
+ if (missing.length > 0) {
7609
+ throw new TypeError(`createAgentRuntime: missing ${missing.join(", ")}`);
7610
+ }
7611
+ }
7582
7612
  function createAgentRuntime2(config) {
7613
+ assertRuntimeComposition(config);
7583
7614
  assertNonNegativeSafeInteger("loop.maxContinuations", config.loop?.maxContinuations, RangeError);
7584
7615
  const state = createAgentRuntimeState(config);
7585
7616
  return {
@@ -7809,4 +7840,4 @@ function composeAgentPrompt2(sections) {
7809
7840
  };
7810
7841
  }
7811
7842
 
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 };
7843
+ 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 };