stitchkit 0.92.0 → 0.94.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 (793) hide show
  1. package/CHANGELOG.md +191 -0
  2. package/README.md +5 -2
  3. package/dist/agent-runtime/children-control.d.ts +6 -0
  4. package/dist/agent-runtime/children-control.d.ts.map +1 -0
  5. package/dist/agent-runtime/children-spawn.d.ts +6 -0
  6. package/dist/agent-runtime/children-spawn.d.ts.map +1 -0
  7. package/dist/agent-runtime/children-state.d.ts +46 -0
  8. package/dist/agent-runtime/children-state.d.ts.map +1 -0
  9. package/dist/agent-runtime/children-usage.d.ts +8 -0
  10. package/dist/agent-runtime/children-usage.d.ts.map +1 -0
  11. package/dist/agent-runtime/children.d.ts +11 -14
  12. package/dist/agent-runtime/children.d.ts.map +1 -1
  13. package/dist/agent-runtime/coding-tool-contract.d.ts +2 -1
  14. package/dist/agent-runtime/coding-tool-contract.d.ts.map +1 -1
  15. package/dist/agent-runtime/deferred-tool-types.d.ts +2 -2
  16. package/dist/agent-runtime/deferred-tool-types.d.ts.map +1 -1
  17. package/dist/agent-runtime/events.d.ts +1 -1
  18. package/dist/agent-runtime/events.d.ts.map +1 -1
  19. package/dist/agent-runtime/managed-tools.d.ts +1 -1
  20. package/dist/agent-runtime/managed-tools.d.ts.map +1 -1
  21. package/dist/agent-runtime/observability.d.ts +1 -1
  22. package/dist/agent-runtime/observability.d.ts.map +1 -1
  23. package/dist/{agent-runtime-openrouter.d.ts → agent-runtime/openrouter.d.ts} +3 -3
  24. package/dist/agent-runtime/openrouter.d.ts.map +1 -0
  25. package/dist/agent-runtime/projections.d.ts +1 -1
  26. package/dist/agent-runtime/projections.d.ts.map +1 -1
  27. package/dist/agent-runtime/run-acquisition.d.ts +17 -0
  28. package/dist/agent-runtime/run-acquisition.d.ts.map +1 -0
  29. package/dist/agent-runtime/run-execution-state.d.ts +133 -0
  30. package/dist/agent-runtime/run-execution-state.d.ts.map +1 -0
  31. package/dist/agent-runtime/run-execution.d.ts +17 -33
  32. package/dist/agent-runtime/run-execution.d.ts.map +1 -1
  33. package/dist/agent-runtime/run-failure.d.ts +18 -0
  34. package/dist/agent-runtime/run-failure.d.ts.map +1 -0
  35. package/dist/agent-runtime/run-model-attempts.d.ts +6 -0
  36. package/dist/agent-runtime/run-model-attempts.d.ts.map +1 -0
  37. package/dist/agent-runtime/run-prompt-history.d.ts +58 -0
  38. package/dist/agent-runtime/run-prompt-history.d.ts.map +1 -0
  39. package/dist/agent-runtime/run-provider-ledger.d.ts +26 -0
  40. package/dist/agent-runtime/run-provider-ledger.d.ts.map +1 -0
  41. package/dist/agent-runtime/run-stream-parts.d.ts +17 -0
  42. package/dist/agent-runtime/run-stream-parts.d.ts.map +1 -0
  43. package/dist/agent-runtime/run-terminal.d.ts +11 -0
  44. package/dist/agent-runtime/run-terminal.d.ts.map +1 -0
  45. package/dist/agent-runtime/run-turn-preparation.d.ts +22 -0
  46. package/dist/agent-runtime/run-turn-preparation.d.ts.map +1 -0
  47. package/dist/agent-runtime/runtime-admission-gate.d.ts +29 -0
  48. package/dist/agent-runtime/runtime-admission-gate.d.ts.map +1 -0
  49. package/dist/agent-runtime/runtime-control.d.ts +9 -0
  50. package/dist/agent-runtime/runtime-control.d.ts.map +1 -0
  51. package/dist/agent-runtime/runtime-recovery.d.ts +10 -0
  52. package/dist/agent-runtime/runtime-recovery.d.ts.map +1 -0
  53. package/dist/agent-runtime/runtime-state.d.ts +36 -0
  54. package/dist/agent-runtime/runtime-state.d.ts.map +1 -0
  55. package/dist/agent-runtime/runtime-submit.d.ts +5 -0
  56. package/dist/agent-runtime/runtime-submit.d.ts.map +1 -0
  57. package/dist/agent-runtime/runtime.d.ts +9 -4
  58. package/dist/agent-runtime/runtime.d.ts.map +1 -1
  59. package/dist/{agent-runtime-sqlite-bun.d.ts → agent-runtime/sqlite-bun.d.ts} +5 -4
  60. package/dist/agent-runtime/sqlite-bun.d.ts.map +1 -0
  61. package/dist/agent-runtime/sqlite-events.d.ts +5 -0
  62. package/dist/agent-runtime/sqlite-events.d.ts.map +1 -0
  63. package/dist/agent-runtime/sqlite-history.d.ts +7 -0
  64. package/dist/agent-runtime/sqlite-history.d.ts.map +1 -0
  65. package/dist/agent-runtime/sqlite-ledger.d.ts +7 -0
  66. package/dist/agent-runtime/sqlite-ledger.d.ts.map +1 -0
  67. package/dist/{agent-runtime-sqlite-node.d.ts → agent-runtime/sqlite-node.d.ts} +5 -4
  68. package/dist/agent-runtime/sqlite-node.d.ts.map +1 -0
  69. package/dist/agent-runtime/sqlite-reads.d.ts +14 -0
  70. package/dist/agent-runtime/sqlite-reads.d.ts.map +1 -0
  71. package/dist/agent-runtime/sqlite-rows.d.ts +178 -0
  72. package/dist/agent-runtime/sqlite-rows.d.ts.map +1 -0
  73. package/dist/agent-runtime/sqlite-schema.d.ts +7 -0
  74. package/dist/agent-runtime/sqlite-schema.d.ts.map +1 -0
  75. package/dist/agent-runtime/sqlite-transactions.d.ts +25 -0
  76. package/dist/agent-runtime/sqlite-transactions.d.ts.map +1 -0
  77. package/dist/agent-runtime/sqlite.d.ts +10 -6
  78. package/dist/agent-runtime/sqlite.d.ts.map +1 -1
  79. package/dist/agent-runtime/store-archive.d.ts +16 -0
  80. package/dist/agent-runtime/store-archive.d.ts.map +1 -0
  81. package/dist/{testing/agent-store-conformance.d.ts → agent-runtime/store-conformance.d.ts} +2 -2
  82. package/dist/agent-runtime/store-conformance.d.ts.map +1 -0
  83. package/dist/agent-runtime/store-create.d.ts +11 -0
  84. package/dist/agent-runtime/store-create.d.ts.map +1 -0
  85. package/dist/agent-runtime/{store-driver.d.ts → store-driver-contract.d.ts} +7 -7
  86. package/dist/agent-runtime/store-driver-contract.d.ts.map +1 -0
  87. package/dist/agent-runtime/store-events.d.ts +7 -89
  88. package/dist/agent-runtime/store-events.d.ts.map +1 -1
  89. package/dist/agent-runtime/store-memory.d.ts +4 -0
  90. package/dist/agent-runtime/store-memory.d.ts.map +1 -0
  91. package/dist/agent-runtime/store-mutate.d.ts +13 -0
  92. package/dist/agent-runtime/store-mutate.d.ts.map +1 -0
  93. package/dist/agent-runtime/store-purge.d.ts +1 -1
  94. package/dist/agent-runtime/store-purge.d.ts.map +1 -1
  95. package/dist/agent-runtime/store-reads.d.ts +29 -0
  96. package/dist/agent-runtime/store-reads.d.ts.map +1 -0
  97. package/dist/agent-runtime/store-reduce-history.d.ts +10 -0
  98. package/dist/agent-runtime/store-reduce-history.d.ts.map +1 -0
  99. package/dist/agent-runtime/store-reduce-run.d.ts +14 -0
  100. package/dist/agent-runtime/store-reduce-run.d.ts.map +1 -0
  101. package/dist/agent-runtime/store-reduce-shared.d.ts +76 -0
  102. package/dist/agent-runtime/store-reduce-shared.d.ts.map +1 -0
  103. package/dist/agent-runtime/store-reduce-terminal.d.ts +6 -0
  104. package/dist/agent-runtime/store-reduce-terminal.d.ts.map +1 -0
  105. package/dist/agent-runtime/store-reducer.d.ts +24 -0
  106. package/dist/agent-runtime/store-reducer.d.ts.map +1 -0
  107. package/dist/agent-runtime/store-snapshot.d.ts +19 -0
  108. package/dist/agent-runtime/store-snapshot.d.ts.map +1 -0
  109. package/dist/agent-runtime/store.d.ts +1 -1
  110. package/dist/agent-runtime/store.d.ts.map +1 -1
  111. package/dist/application/admission.d.ts +1 -1
  112. package/dist/application/admission.d.ts.map +1 -1
  113. package/dist/application/events.d.ts +1 -1
  114. package/dist/application/events.d.ts.map +1 -1
  115. package/dist/{server → application}/file-state-store.d.ts +1 -1
  116. package/dist/application/file-state-store.d.ts.map +1 -0
  117. package/dist/application/health.d.ts +1 -1
  118. package/dist/application/health.d.ts.map +1 -1
  119. package/dist/application/kernel-admission.d.ts +8 -0
  120. package/dist/application/kernel-admission.d.ts.map +1 -0
  121. package/dist/application/kernel-contract.d.ts +142 -0
  122. package/dist/application/kernel-contract.d.ts.map +1 -0
  123. package/dist/application/kernel-resource-context.d.ts +24 -0
  124. package/dist/application/kernel-resource-context.d.ts.map +1 -0
  125. package/dist/application/kernel-restart.d.ts +5 -0
  126. package/dist/application/kernel-restart.d.ts.map +1 -0
  127. package/dist/application/kernel-rollback.d.ts +4 -0
  128. package/dist/application/kernel-rollback.d.ts.map +1 -0
  129. package/dist/application/kernel-shutdown.d.ts +6 -0
  130. package/dist/application/kernel-shutdown.d.ts.map +1 -0
  131. package/dist/application/kernel-start.d.ts +20 -0
  132. package/dist/application/kernel-start.d.ts.map +1 -0
  133. package/dist/application/kernel-state.d.ts +116 -0
  134. package/dist/application/kernel-state.d.ts.map +1 -0
  135. package/dist/application/kernel.d.ts +9 -140
  136. package/dist/application/kernel.d.ts.map +1 -1
  137. package/dist/application/latest-sink.d.ts +1 -1
  138. package/dist/application/latest-sink.d.ts.map +1 -1
  139. package/dist/application/opentelemetry.d.ts +1 -1
  140. package/dist/application/opentelemetry.d.ts.map +1 -1
  141. package/dist/application/watch-hub.d.ts +2 -2
  142. package/dist/application/watch-hub.d.ts.map +1 -1
  143. package/dist/browser/client-multipart.d.ts +1 -1
  144. package/dist/browser/client-multipart.d.ts.map +1 -1
  145. package/dist/browser/client-url.d.ts +1 -1
  146. package/dist/browser/client-url.d.ts.map +1 -1
  147. package/dist/browser/client.d.ts +1 -1
  148. package/dist/browser/client.d.ts.map +1 -1
  149. package/dist/browser/contract-stream.d.ts +1 -1
  150. package/dist/browser/contract-stream.d.ts.map +1 -1
  151. package/dist/browser/http.d.ts +1 -1
  152. package/dist/browser/http.d.ts.map +1 -1
  153. package/dist/browser/resumable.d.ts +1 -28
  154. package/dist/browser/resumable.d.ts.map +1 -1
  155. package/dist/browser/retained.d.ts.map +1 -0
  156. package/dist/browser/socket-io.d.ts +23 -1
  157. package/dist/browser/socket-io.d.ts.map +1 -1
  158. package/dist/browser/stream.d.ts +14 -2
  159. package/dist/browser/stream.d.ts.map +1 -1
  160. package/dist/contract/define.d.ts +72 -65
  161. package/dist/contract/define.d.ts.map +1 -1
  162. package/dist/{internal/errors.d.ts → contract/normalize.d.ts} +3 -39
  163. package/dist/contract/normalize.d.ts.map +1 -0
  164. package/dist/contract/tool-view.d.ts +135 -0
  165. package/dist/contract/tool-view.d.ts.map +1 -0
  166. package/dist/declaration/declaration.d.ts.map +1 -0
  167. package/dist/{agent-runtime/durability-contract.d.ts → durability/contract.d.ts} +2 -2
  168. package/dist/durability/contract.d.ts.map +1 -0
  169. package/dist/{agent-runtime/durability.d.ts → durability/engine.d.ts} +4 -4
  170. package/dist/durability/engine.d.ts.map +1 -0
  171. package/dist/durability/events.d.ts +101 -0
  172. package/dist/durability/events.d.ts.map +1 -0
  173. package/dist/{agent-runtime/durability-json.d.ts → durability/json.d.ts} +1 -1
  174. package/dist/durability/json.d.ts.map +1 -0
  175. package/dist/{agent-runtime/durability-ledger.d.ts → durability/ledger.d.ts} +2 -2
  176. package/dist/durability/ledger.d.ts.map +1 -0
  177. package/dist/{agent-runtime/durability-scheduler.d.ts → durability/scheduler.d.ts} +2 -2
  178. package/dist/durability/scheduler.d.ts.map +1 -0
  179. package/dist/entrypoints/agent-runtime/browser.d.ts +5 -0
  180. package/dist/entrypoints/agent-runtime/browser.d.ts.map +1 -0
  181. package/dist/{agent-runtime-browser.js → entrypoints/agent-runtime/browser.js} +3 -3
  182. package/dist/{agent-runtime-coding-tools.d.ts → entrypoints/agent-runtime/coding-tools.d.ts} +2 -2
  183. package/dist/entrypoints/agent-runtime/coding-tools.d.ts.map +1 -0
  184. package/dist/entrypoints/agent-runtime/coding-tools.js +22 -0
  185. package/dist/{agent-runtime-harness.d.ts → entrypoints/agent-runtime/harness.d.ts} +2 -2
  186. package/dist/entrypoints/agent-runtime/harness.d.ts.map +1 -0
  187. package/dist/{agent-runtime-harness.js → entrypoints/agent-runtime/harness.js} +24 -25
  188. package/dist/entrypoints/agent-runtime/openrouter.d.ts +2 -0
  189. package/dist/entrypoints/agent-runtime/openrouter.d.ts.map +1 -0
  190. package/dist/{agent-runtime-openrouter.js → entrypoints/agent-runtime/openrouter.js} +3 -3
  191. package/dist/{agent-runtime-sandbox.d.ts → entrypoints/agent-runtime/sandbox.d.ts} +5 -5
  192. package/dist/entrypoints/agent-runtime/sandbox.d.ts.map +1 -0
  193. package/dist/{agent-runtime-sandbox.js → entrypoints/agent-runtime/sandbox.js} +11 -12
  194. package/dist/entrypoints/agent-runtime/sqlite/bun.d.ts +2 -0
  195. package/dist/entrypoints/agent-runtime/sqlite/bun.d.ts.map +1 -0
  196. package/dist/{agent-runtime-sqlite-bun.js → entrypoints/agent-runtime/sqlite/bun.js} +8 -6
  197. package/dist/entrypoints/agent-runtime/sqlite/node.d.ts +2 -0
  198. package/dist/entrypoints/agent-runtime/sqlite/node.d.ts.map +1 -0
  199. package/dist/{agent-runtime-sqlite-node.js → entrypoints/agent-runtime/sqlite/node.js} +8 -6
  200. package/dist/entrypoints/agent-runtime/testing.d.ts +4 -0
  201. package/dist/entrypoints/agent-runtime/testing.d.ts.map +1 -0
  202. package/dist/entrypoints/agent-runtime/testing.js +1084 -0
  203. package/dist/{agent-runtime.d.ts → entrypoints/agent-runtime.d.ts} +41 -37
  204. package/dist/entrypoints/agent-runtime.d.ts.map +1 -0
  205. package/dist/{agent-runtime.js → entrypoints/agent-runtime.js} +408 -366
  206. package/dist/{application-diagnostic-journal.d.ts → entrypoints/application/diagnostic-journal.d.ts} +2 -2
  207. package/dist/entrypoints/application/diagnostic-journal.d.ts.map +1 -0
  208. package/dist/{application-diagnostic-journal.js → entrypoints/application/diagnostic-journal.js} +3 -3
  209. package/dist/{application-grammy.d.ts → entrypoints/application/grammy.d.ts} +2 -2
  210. package/dist/entrypoints/application/grammy.d.ts.map +1 -0
  211. package/dist/{application-grammy.js → entrypoints/application/grammy.js} +2 -2
  212. package/dist/{application-opentelemetry.d.ts → entrypoints/application/opentelemetry.d.ts} +2 -2
  213. package/dist/entrypoints/application/opentelemetry.d.ts.map +1 -0
  214. package/dist/{application-opentelemetry.js → entrypoints/application/opentelemetry.js} +4 -4
  215. package/dist/{application-schemas.d.ts → entrypoints/application/schemas.d.ts} +2 -2
  216. package/dist/entrypoints/application/schemas.d.ts.map +1 -0
  217. package/dist/{application-schemas.js → entrypoints/application/schemas.js} +2 -2
  218. package/dist/{application.d.ts → entrypoints/application.d.ts} +22 -21
  219. package/dist/entrypoints/application.d.ts.map +1 -0
  220. package/dist/{application.js → entrypoints/application.js} +24 -22
  221. package/dist/entrypoints/bin/upgrade-cli.d.ts.map +1 -0
  222. package/dist/{upgrade-cli.js → entrypoints/bin/upgrade-cli.js} +3 -3
  223. package/dist/{cli.d.ts → entrypoints/cli.d.ts} +15 -15
  224. package/dist/entrypoints/cli.d.ts.map +1 -0
  225. package/dist/{cli.js → entrypoints/cli.js} +37 -32
  226. package/dist/entrypoints/contract.d.ts +9 -0
  227. package/dist/entrypoints/contract.d.ts.map +1 -0
  228. package/dist/{contract/index.js → entrypoints/contract.js} +14 -6
  229. package/dist/entrypoints/declaration.d.ts +2 -0
  230. package/dist/entrypoints/declaration.d.ts.map +1 -0
  231. package/dist/{declaration.js → entrypoints/declaration.js} +1 -1
  232. package/dist/{files.d.ts → entrypoints/files.d.ts} +2 -2
  233. package/dist/entrypoints/files.d.ts.map +1 -0
  234. package/dist/{files.js → entrypoints/files.js} +3 -3
  235. package/dist/{geo.d.ts → entrypoints/geo.d.ts} +1 -1
  236. package/dist/entrypoints/geo.d.ts.map +1 -0
  237. package/dist/{geo.js → entrypoints/geo.js} +4 -4
  238. package/dist/entrypoints/google.d.ts +2 -0
  239. package/dist/entrypoints/google.d.ts.map +1 -0
  240. package/dist/{google.js → entrypoints/google.js} +1 -1
  241. package/dist/{index.d.ts → entrypoints/index.d.ts} +14 -13
  242. package/dist/entrypoints/index.d.ts.map +1 -0
  243. package/dist/{index.js → entrypoints/index.js} +99 -33
  244. package/dist/{live.d.ts → entrypoints/live.d.ts} +4 -4
  245. package/dist/entrypoints/live.d.ts.map +1 -0
  246. package/dist/{live.js → entrypoints/live.js} +6 -4
  247. package/dist/{node.d.ts → entrypoints/node.d.ts} +11 -11
  248. package/dist/entrypoints/node.d.ts.map +1 -0
  249. package/dist/{node.js → entrypoints/node.js} +20 -16
  250. package/dist/entrypoints/oauth.d.ts +2 -0
  251. package/dist/entrypoints/oauth.d.ts.map +1 -0
  252. package/dist/{oauth.js → entrypoints/oauth.js} +3 -3
  253. package/dist/{observability/index.d.ts → entrypoints/observability.d.ts} +11 -11
  254. package/dist/entrypoints/observability.d.ts.map +1 -0
  255. package/dist/{observability/index.js → entrypoints/observability.js} +9 -11
  256. package/dist/entrypoints/primitives.d.ts +3 -0
  257. package/dist/entrypoints/primitives.d.ts.map +1 -0
  258. package/dist/{primitives.js → entrypoints/primitives.js} +1 -6
  259. package/dist/{react.d.ts → entrypoints/react.d.ts} +4 -4
  260. package/dist/entrypoints/react.d.ts.map +1 -0
  261. package/dist/{react.js → entrypoints/react.js} +3 -3
  262. package/dist/{release.d.ts → entrypoints/release.d.ts} +4 -4
  263. package/dist/entrypoints/release.d.ts.map +1 -0
  264. package/dist/{release.js → entrypoints/release.js} +1 -1
  265. package/dist/{remote.d.ts → entrypoints/remote.d.ts} +1 -1
  266. package/dist/entrypoints/remote.d.ts.map +1 -0
  267. package/dist/entrypoints/remote.js +66 -0
  268. package/dist/{server/index.d.ts → entrypoints/server.d.ts} +35 -34
  269. package/dist/entrypoints/server.d.ts.map +1 -0
  270. package/dist/{server/index.js → entrypoints/server.js} +294 -244
  271. package/dist/{telegram.d.ts → entrypoints/telegram.d.ts} +2 -2
  272. package/dist/entrypoints/telegram.d.ts.map +1 -0
  273. package/dist/{telegram.js → entrypoints/telegram.js} +1 -1
  274. package/dist/entrypoints/testing.d.ts +9 -0
  275. package/dist/entrypoints/testing.d.ts.map +1 -0
  276. package/dist/{testing.js → entrypoints/testing.js} +107 -926
  277. package/dist/{tools/connections/index.d.ts → entrypoints/tools/connections.d.ts} +6 -7
  278. package/dist/entrypoints/tools/connections.d.ts.map +1 -0
  279. package/dist/{tools/connections/index.js → entrypoints/tools/connections.js} +7 -4
  280. package/dist/{tools-contract.d.ts → entrypoints/tools/contract.d.ts} +5 -5
  281. package/dist/entrypoints/tools/contract.d.ts.map +1 -0
  282. package/dist/{tools-contract.js → entrypoints/tools/contract.js} +4 -4
  283. package/dist/{tool-invoker.d.ts → entrypoints/tools/invoker.d.ts} +2 -2
  284. package/dist/entrypoints/tools/invoker.d.ts.map +1 -0
  285. package/dist/entrypoints/tools/invoker.js +20 -0
  286. package/dist/entrypoints/tools.d.ts +51 -0
  287. package/dist/entrypoints/tools.d.ts.map +1 -0
  288. package/dist/{tools.js → entrypoints/tools.js} +1787 -1751
  289. package/dist/{tracking-server.d.ts → entrypoints/tracking/server.d.ts} +8 -8
  290. package/dist/entrypoints/tracking/server.d.ts.map +1 -0
  291. package/dist/{tracking.d.ts → entrypoints/tracking.d.ts} +15 -15
  292. package/dist/entrypoints/tracking.d.ts.map +1 -0
  293. package/dist/{tracking.js → entrypoints/tracking.js} +5 -8
  294. package/dist/google/google.d.ts.map +1 -0
  295. package/dist/{index-a916km3r.js → index-0b1ess5e.js} +6 -13
  296. package/dist/{index-zwkgfq1s.js → index-1nd48tm9.js} +113 -118
  297. package/dist/{index-7zbps32p.js → index-1zbbzgfh.js} +2 -2
  298. package/dist/{index-mzvgxp0n.js → index-2cr1cqhn.js} +16 -4
  299. package/dist/{index-f9mb610r.js → index-35mh5bhj.js} +2 -2
  300. package/dist/index-48ffdxgk.js +6 -0
  301. package/dist/index-58k4fp34.js +1023 -0
  302. package/dist/{index-p13mwz16.js → index-83bdg97s.js} +1 -1
  303. package/dist/index-97ac4gph.js +3618 -0
  304. package/dist/{index-kw9t5ayn.js → index-cq4qfycf.js} +5 -5
  305. package/dist/{index-7gnkny4z.js → index-d9pk3td4.js} +1 -1
  306. package/dist/{index-e42wzzz5.js → index-dcpdvjsc.js} +7 -7
  307. package/dist/{index-h9etkkyk.js → index-dydjcp8z.js} +102 -25
  308. package/dist/{index-sr93cwf9.js → index-e2z3ahw9.js} +2 -2
  309. package/dist/{index-yewwh1w4.js → index-e87kakm4.js} +96 -11
  310. package/dist/{index-cby4ar3v.js → index-eqqvgdb3.js} +1 -1
  311. package/dist/index-fdp6hdxn.js +942 -0
  312. package/dist/{index-0a349c33.js → index-gyr48nzg.js} +125 -198
  313. package/dist/{index-wnfk50r0.js → index-h6eeys1v.js} +1 -1
  314. package/dist/{index-77fekveh.js → index-hffjpmq9.js} +1 -15
  315. package/dist/{index-yn8remb1.js → index-j05z5gn4.js} +50 -14
  316. package/dist/index-k5hsfc3j.js +31 -0
  317. package/dist/{index-fq77yfzc.js → index-kj2wbeta.js} +1 -1
  318. package/dist/index-kvj7f4hq.js +39 -0
  319. package/dist/{index-4fpa9dy2.js → index-m9zn6cpq.js} +2 -2
  320. package/dist/{index-2na0qrfn.js → index-mdzh02yc.js} +7 -7
  321. package/dist/{index-ywd0y6m1.js → index-mkm15s49.js} +1 -1
  322. package/dist/index-mp5sn43f.js +1084 -0
  323. package/dist/{index-7n145nbe.js → index-n6hxg8as.js} +530 -387
  324. package/dist/index-ngfhvfpd.js +30 -0
  325. package/dist/{index-e0znv5gn.js → index-p5r7qpdd.js} +2 -93
  326. package/dist/{index-n0f51dfn.js → index-p81267c2.js} +608 -549
  327. package/dist/{index-wc4x00bn.js → index-qwhynv6x.js} +1 -1
  328. package/dist/index-r7nmqpsg.js +154 -0
  329. package/dist/{index-bx75zwt7.js → index-rewkc2hj.js} +5 -4
  330. package/dist/{index-9f8ztey6.js → index-sees8yf8.js} +2 -2
  331. package/dist/{index-vjpvjqpn.js → index-v38qyerb.js} +16 -2
  332. package/dist/{index-2c2bjw3s.js → index-vcvkq30w.js} +3 -3
  333. package/dist/index-wqgjfstn.js +18 -0
  334. package/dist/{index-f477k430.js → index-x4799c19.js} +1 -1
  335. package/dist/{index-cxqhvq21.js → index-xnj9bgxe.js} +142 -129
  336. package/dist/index-xsqjkha9.js +281 -0
  337. package/dist/{index-6kyksz9y.js → index-yw4fzmdz.js} +1 -1
  338. package/dist/{index-3xwxfj4z.js → index-zeemqhqx.js} +1 -1
  339. package/dist/{index-tmwcrptx.js → index-zfrhfn82.js} +1 -1
  340. package/dist/index-znfs20ss.js +98 -0
  341. package/dist/internal/backoff.d.ts +29 -0
  342. package/dist/internal/backoff.d.ts.map +1 -0
  343. package/dist/internal/canonical-json.d.ts +21 -11
  344. package/dist/internal/canonical-json.d.ts.map +1 -1
  345. package/dist/internal/channel.d.ts.map +1 -0
  346. package/dist/internal/logger.d.ts.map +1 -0
  347. package/dist/internal/request.d.ts.map +1 -0
  348. package/dist/internal/secure-fetch.d.ts +12 -0
  349. package/dist/internal/secure-fetch.d.ts.map +1 -1
  350. package/dist/internal/stable-digest.d.ts +0 -43
  351. package/dist/internal/stable-digest.d.ts.map +1 -1
  352. package/dist/internal/typed.d.ts +0 -8
  353. package/dist/internal/typed.d.ts.map +1 -1
  354. package/dist/internal/zod-issues.d.ts +38 -0
  355. package/dist/internal/zod-issues.d.ts.map +1 -0
  356. package/dist/{tools/json-schema-dialect.d.ts → json-schema/dialect.d.ts} +1 -1
  357. package/dist/json-schema/dialect.d.ts.map +1 -0
  358. package/dist/json-schema/json-schema.d.ts.map +1 -0
  359. package/dist/live/watch-delta.d.ts.map +1 -1
  360. package/dist/{oauth.d.ts → oauth/authorization-code.d.ts} +1 -1
  361. package/dist/oauth/authorization-code.d.ts.map +1 -0
  362. package/dist/observability/audit.d.ts +2 -2
  363. package/dist/observability/audit.d.ts.map +1 -1
  364. package/dist/observability/bounded-logger.d.ts +1 -1
  365. package/dist/observability/bounded-logger.d.ts.map +1 -1
  366. package/dist/{internal/observability-sink.d.ts → observability/bounded-sink.d.ts} +2 -2
  367. package/dist/observability/bounded-sink.d.ts.map +1 -0
  368. package/dist/observability/context.d.ts +1 -1
  369. package/dist/observability/context.d.ts.map +1 -1
  370. package/dist/observability/event.d.ts +1 -1
  371. package/dist/observability/event.d.ts.map +1 -1
  372. package/dist/observability/work.d.ts +1 -1
  373. package/dist/observability/work.d.ts.map +1 -1
  374. package/dist/primitives/audit.d.ts +1 -1
  375. package/dist/primitives/audit.d.ts.map +1 -1
  376. package/dist/primitives/export-operation.d.ts +4 -2
  377. package/dist/primitives/export-operation.d.ts.map +1 -1
  378. package/dist/realtime/socket.d.ts +1 -1
  379. package/dist/realtime/socket.d.ts.map +1 -1
  380. package/dist/server/context-contribution.d.ts +1 -1
  381. package/dist/server/context-contribution.d.ts.map +1 -1
  382. package/dist/server/context.d.ts +2 -2
  383. package/dist/server/context.d.ts.map +1 -1
  384. package/dist/server/contract-method.d.ts +15 -0
  385. package/dist/server/contract-method.d.ts.map +1 -0
  386. package/dist/server/contract-stream.d.ts +1 -1
  387. package/dist/server/contract-stream.d.ts.map +1 -1
  388. package/dist/server/create.d.ts +8 -0
  389. package/dist/server/create.d.ts.map +1 -1
  390. package/dist/server/endpoint-dispatch.d.ts +10 -0
  391. package/dist/server/endpoint-dispatch.d.ts.map +1 -0
  392. package/dist/server/endpoint-response.d.ts +18 -0
  393. package/dist/server/endpoint-response.d.ts.map +1 -0
  394. package/dist/server/error-dispatch.d.ts +17 -1
  395. package/dist/server/error-dispatch.d.ts.map +1 -1
  396. package/dist/server/error-hook.d.ts +2 -2
  397. package/dist/server/error-hook.d.ts.map +1 -1
  398. package/dist/server/handler-state.d.ts +44 -0
  399. package/dist/server/handler-state.d.ts.map +1 -0
  400. package/dist/server/implement.d.ts +1 -1
  401. package/dist/server/implement.d.ts.map +1 -1
  402. package/dist/server/middleware/auth.d.ts +1 -1
  403. package/dist/server/middleware/auth.d.ts.map +1 -1
  404. package/dist/server/middleware/cors.d.ts +17 -0
  405. package/dist/server/middleware/cors.d.ts.map +1 -1
  406. package/dist/server/middleware/trust-fence.d.ts +1 -1
  407. package/dist/server/middleware/trust-fence.d.ts.map +1 -1
  408. package/dist/server/multipart.d.ts +1 -1
  409. package/dist/server/multipart.d.ts.map +1 -1
  410. package/dist/{tools/oauth-metadata.d.ts → server/oauth/metadata.d.ts} +2 -2
  411. package/dist/server/oauth/metadata.d.ts.map +1 -0
  412. package/dist/{tools/oauth-provider.d.ts → server/oauth/provider.d.ts} +2 -2
  413. package/dist/server/oauth/provider.d.ts.map +1 -0
  414. package/dist/server/realtime.d.ts +1 -1
  415. package/dist/server/realtime.d.ts.map +1 -1
  416. package/dist/server/request-completion.d.ts +16 -0
  417. package/dist/server/request-completion.d.ts.map +1 -0
  418. package/dist/server/response-metadata.d.ts +1 -1
  419. package/dist/server/response-metadata.d.ts.map +1 -1
  420. package/dist/server/route-table.d.ts +9 -0
  421. package/dist/server/route-table.d.ts.map +1 -0
  422. package/dist/server/stream.d.ts +0 -13
  423. package/dist/server/stream.d.ts.map +1 -1
  424. package/dist/server/types.d.ts +7 -4
  425. package/dist/server/types.d.ts.map +1 -1
  426. package/dist/testing/handler-clients.d.ts +31 -0
  427. package/dist/testing/handler-clients.d.ts.map +1 -0
  428. package/dist/testing/managed-resource-conformance-scenarios.d.ts.map +1 -1
  429. package/dist/testing/surface-conformance.d.ts +2 -1
  430. package/dist/testing/surface-conformance.d.ts.map +1 -1
  431. package/dist/testing/surface-manifest.d.ts +64 -5
  432. package/dist/testing/surface-manifest.d.ts.map +1 -1
  433. package/dist/tools/{cli-args.d.ts → cli/args.d.ts} +1 -1
  434. package/dist/tools/cli/args.d.ts.map +1 -0
  435. package/dist/tools/{cli-checkpoint.d.ts → cli/checkpoint.d.ts} +1 -1
  436. package/dist/tools/cli/checkpoint.d.ts.map +1 -0
  437. package/dist/tools/{cli-command.d.ts → cli/command.d.ts} +22 -4
  438. package/dist/tools/cli/command.d.ts.map +1 -0
  439. package/dist/tools/{cli.d.ts → cli/config.d.ts} +5 -12
  440. package/dist/tools/cli/config.d.ts.map +1 -0
  441. package/dist/tools/cli/create-cli.d.ts +36 -0
  442. package/dist/tools/cli/create-cli.d.ts.map +1 -0
  443. package/dist/tools/cli/download.d.ts +8 -0
  444. package/dist/tools/cli/download.d.ts.map +1 -0
  445. package/dist/tools/{cli-format.d.ts → cli/format.d.ts} +2 -2
  446. package/dist/tools/cli/format.d.ts.map +1 -0
  447. package/dist/tools/cli/help.d.ts +24 -0
  448. package/dist/tools/cli/help.d.ts.map +1 -0
  449. package/dist/tools/{cli-installer.d.ts → cli/installer.d.ts} +2 -2
  450. package/dist/tools/cli/installer.d.ts.map +1 -0
  451. package/dist/tools/{cli-invoke.d.ts → cli/invoke.d.ts} +35 -10
  452. package/dist/tools/cli/invoke.d.ts.map +1 -0
  453. package/dist/tools/cli/io.d.ts +10 -0
  454. package/dist/tools/cli/io.d.ts.map +1 -0
  455. package/dist/tools/cli/managed-surface.d.ts +30 -0
  456. package/dist/tools/cli/managed-surface.d.ts.map +1 -0
  457. package/dist/tools/{cli-manifest.d.ts → cli/manifest.d.ts} +1 -1
  458. package/dist/tools/cli/manifest.d.ts.map +1 -0
  459. package/dist/tools/{cli-policy.d.ts → cli/policy.d.ts} +2 -2
  460. package/dist/tools/cli/policy.d.ts.map +1 -0
  461. package/dist/tools/cli/prepare.d.ts +14 -0
  462. package/dist/tools/cli/prepare.d.ts.map +1 -0
  463. package/dist/tools/{cli-profile.d.ts → cli/profile.d.ts} +2 -2
  464. package/dist/tools/cli/profile.d.ts.map +1 -0
  465. package/dist/tools/cli/run-managed.d.ts +5 -0
  466. package/dist/tools/cli/run-managed.d.ts.map +1 -0
  467. package/dist/tools/cli/run-native.d.ts +9 -0
  468. package/dist/tools/cli/run-native.d.ts.map +1 -0
  469. package/dist/tools/cli/session.d.ts +40 -0
  470. package/dist/tools/cli/session.d.ts.map +1 -0
  471. package/dist/tools/{cli-signature.d.ts → cli/signature.d.ts} +2 -2
  472. package/dist/tools/cli/signature.d.ts.map +1 -0
  473. package/dist/tools/{cli-stream.d.ts → cli/stream.d.ts} +4 -4
  474. package/dist/tools/cli/stream.d.ts.map +1 -0
  475. package/dist/tools/{cli-update.d.ts → cli/update.d.ts} +3 -3
  476. package/dist/tools/cli/update.d.ts.map +1 -0
  477. package/dist/tools/{cli-view.d.ts → cli/view.d.ts} +2 -2
  478. package/dist/tools/cli/view.d.ts.map +1 -0
  479. package/dist/tools/{cli-wait.d.ts → cli/wait.d.ts} +2 -2
  480. package/dist/tools/cli/wait.d.ts.map +1 -0
  481. package/dist/tools/connections/runtime.d.ts +1 -1
  482. package/dist/tools/connections/runtime.d.ts.map +1 -1
  483. package/dist/tools/connections/types.d.ts +3 -3
  484. package/dist/tools/connections/types.d.ts.map +1 -1
  485. package/dist/tools/durability-context.d.ts +1 -1
  486. package/dist/tools/durability-context.d.ts.map +1 -1
  487. package/dist/tools/execute.d.ts +30 -3
  488. package/dist/tools/execute.d.ts.map +1 -1
  489. package/dist/tools/internal/surface-projector.d.ts +8 -6
  490. package/dist/tools/internal/surface-projector.d.ts.map +1 -1
  491. package/dist/tools/internal/tool-view.d.ts +41 -0
  492. package/dist/tools/internal/tool-view.d.ts.map +1 -0
  493. package/dist/tools/invoker.d.ts +11 -3
  494. package/dist/tools/invoker.d.ts.map +1 -1
  495. package/dist/tools/list-names.d.ts +3 -3
  496. package/dist/tools/list-names.d.ts.map +1 -1
  497. package/dist/tools/manifest.d.ts +2 -2
  498. package/dist/tools/manifest.d.ts.map +1 -1
  499. package/dist/tools/{mcp-app.d.ts → mcp/app.d.ts} +1 -1
  500. package/dist/tools/mcp/app.d.ts.map +1 -0
  501. package/dist/tools/{mcp-catalog.d.ts → mcp/catalog.d.ts} +2 -2
  502. package/dist/tools/mcp/catalog.d.ts.map +1 -0
  503. package/dist/tools/{mcp-handler.d.ts → mcp/handler.d.ts} +5 -5
  504. package/dist/tools/mcp/handler.d.ts.map +1 -0
  505. package/dist/tools/{mcp.d.ts → mcp/mount.d.ts} +9 -9
  506. package/dist/tools/mcp/mount.d.ts.map +1 -0
  507. package/dist/tools/{mcp-prepare.d.ts → mcp/prepare.d.ts} +9 -9
  508. package/dist/tools/mcp/prepare.d.ts.map +1 -0
  509. package/dist/tools/{mcp-progress.d.ts → mcp/progress.d.ts} +2 -2
  510. package/dist/tools/mcp/progress.d.ts.map +1 -0
  511. package/dist/tools/mcp/register.d.ts +35 -0
  512. package/dist/tools/mcp/register.d.ts.map +1 -0
  513. package/dist/tools/{mcp-round-policy.d.ts → mcp/round-policy.d.ts} +2 -2
  514. package/dist/tools/mcp/round-policy.d.ts.map +1 -0
  515. package/dist/tools/{mcp-round.d.ts → mcp/round.d.ts} +4 -4
  516. package/dist/tools/mcp/round.d.ts.map +1 -0
  517. package/dist/tools/mcp/runtime-tools.d.ts +24 -0
  518. package/dist/tools/mcp/runtime-tools.d.ts.map +1 -0
  519. package/dist/tools/{mcp-stdio-signals.d.ts → mcp/stdio-signals.d.ts} +3 -3
  520. package/dist/tools/mcp/stdio-signals.d.ts.map +1 -0
  521. package/dist/tools/{mcp-stdio.d.ts → mcp/stdio.d.ts} +4 -4
  522. package/dist/tools/mcp/stdio.d.ts.map +1 -0
  523. package/dist/tools/{mcp-trace.d.ts → mcp/trace.d.ts} +1 -1
  524. package/dist/tools/mcp/trace.d.ts.map +1 -0
  525. package/dist/tools/mount.d.ts +12 -7
  526. package/dist/tools/mount.d.ts.map +1 -1
  527. package/dist/tools/native-definition.d.ts +3 -3
  528. package/dist/tools/native-definition.d.ts.map +1 -1
  529. package/dist/tools/operations/async-operation-binding-types.d.ts +127 -0
  530. package/dist/tools/operations/async-operation-binding-types.d.ts.map +1 -0
  531. package/dist/tools/operations/async-operation-binding.d.ts +28 -0
  532. package/dist/tools/operations/async-operation-binding.d.ts.map +1 -0
  533. package/dist/tools/operations/async-operation-canonical-types.d.ts +110 -0
  534. package/dist/tools/operations/async-operation-canonical-types.d.ts.map +1 -0
  535. package/dist/tools/operations/async-operation-canonical.d.ts +7 -0
  536. package/dist/tools/operations/async-operation-canonical.d.ts.map +1 -0
  537. package/dist/tools/operations/async-operation-contract.d.ts.map +1 -0
  538. package/dist/tools/operations/async-operation-id.d.ts +23 -0
  539. package/dist/tools/operations/async-operation-id.d.ts.map +1 -0
  540. package/dist/tools/operations/async-operation-runtime-tools.d.ts +40 -0
  541. package/dist/tools/operations/async-operation-runtime-tools.d.ts.map +1 -0
  542. package/dist/tools/operations/async-operation-runtime-types.d.ts +68 -0
  543. package/dist/tools/operations/async-operation-runtime-types.d.ts.map +1 -0
  544. package/dist/tools/operations/async-operation-runtime.d.ts +5 -0
  545. package/dist/tools/operations/async-operation-runtime.d.ts.map +1 -0
  546. package/dist/tools/{define-wait-tool.d.ts → operations/define-wait-tool.d.ts} +2 -2
  547. package/dist/tools/operations/define-wait-tool.d.ts.map +1 -0
  548. package/dist/tools/operations/mount-wait.d.ts.map +1 -0
  549. package/dist/tools/operations/wait-core.d.ts.map +1 -0
  550. package/dist/tools/remote.d.ts +1 -1
  551. package/dist/tools/remote.d.ts.map +1 -1
  552. package/dist/tools/runtime-tool.d.ts +11 -4
  553. package/dist/tools/runtime-tool.d.ts.map +1 -1
  554. package/dist/tools/schema/coerce.d.ts.map +1 -0
  555. package/dist/tools/schema/flatten-join.d.ts.map +1 -0
  556. package/dist/tools/schema/flatten.d.ts.map +1 -0
  557. package/dist/tools/schema/portable-formats.d.ts.map +1 -0
  558. package/dist/tools/{presentation.d.ts → schema/presentation.d.ts} +2 -0
  559. package/dist/tools/schema/presentation.d.ts.map +1 -0
  560. package/dist/tools/schema/schema.d.ts.map +1 -0
  561. package/dist/tools/schema/untyped-properties.d.ts.map +1 -0
  562. package/dist/tools/surface.d.ts +2 -3
  563. package/dist/tools/surface.d.ts.map +1 -1
  564. package/dist/tools/toolkit.d.ts +4 -4
  565. package/dist/tools/toolkit.d.ts.map +1 -1
  566. package/dist/tools/{define-download-tool.d.ts → transfer/define-download-tool.d.ts} +4 -4
  567. package/dist/tools/transfer/define-download-tool.d.ts.map +1 -0
  568. package/dist/tools/{define-upload-tool.d.ts → transfer/define-upload-tool.d.ts} +3 -3
  569. package/dist/tools/transfer/define-upload-tool.d.ts.map +1 -0
  570. package/dist/tools/{define-view-file-tool.d.ts → transfer/define-view-file-tool.d.ts} +2 -2
  571. package/dist/tools/transfer/define-view-file-tool.d.ts.map +1 -0
  572. package/dist/tools/{download-core.d.ts → transfer/download-core.d.ts} +2 -2
  573. package/dist/tools/transfer/download-core.d.ts.map +1 -0
  574. package/dist/tools/{managed-file-error.d.ts → transfer/managed-file-error.d.ts} +1 -1
  575. package/dist/tools/transfer/managed-file-error.d.ts.map +1 -0
  576. package/dist/tools/{mount-download.d.ts → transfer/mount-download.d.ts} +1 -1
  577. package/dist/tools/transfer/mount-download.d.ts.map +1 -0
  578. package/dist/tools/{mount-upload.d.ts → transfer/mount-upload.d.ts} +1 -1
  579. package/dist/tools/transfer/mount-upload.d.ts.map +1 -0
  580. package/dist/tools/transfer/native-result.d.ts.map +1 -0
  581. package/dist/tools/{upload-core.d.ts → transfer/upload-core.d.ts} +1 -1
  582. package/dist/tools/transfer/upload-core.d.ts.map +1 -0
  583. package/dist/tools/transfer/view-file-contract.d.ts.map +1 -0
  584. package/dist/tools/{view-file.d.ts → transfer/view-file.d.ts} +1 -1
  585. package/dist/tools/transfer/view-file.d.ts.map +1 -0
  586. package/dist/tools/transports.d.ts +1 -1
  587. package/dist/tools/transports.d.ts.map +1 -1
  588. package/dist/tracking/contract.d.ts +1 -1
  589. package/dist/tracking/contract.d.ts.map +1 -1
  590. package/llms/agent-runtime-browser.txt +33 -0
  591. package/llms/agent-runtime-coding-tools.txt +58 -0
  592. package/llms/agent-runtime-harness.txt +45 -0
  593. package/llms/agent-runtime-openrouter.txt +22 -0
  594. package/llms/agent-runtime-sandbox.txt +159 -0
  595. package/llms/agent-runtime-sqlite-bun.txt +29 -0
  596. package/llms/agent-runtime-sqlite-node.txt +26 -0
  597. package/llms/agent-runtime-testing.txt +30 -0
  598. package/llms/agent-runtime.2.txt +550 -0
  599. package/llms/agent-runtime.3.txt +311 -0
  600. package/llms/agent-runtime.txt +893 -0
  601. package/llms/application-diagnostic-journal.txt +30 -0
  602. package/llms/application-grammy.txt +27 -0
  603. package/llms/application-opentelemetry.txt +27 -0
  604. package/llms/application-schemas.txt +42 -0
  605. package/llms/application.2.txt +223 -0
  606. package/llms/application.txt +1144 -0
  607. package/llms/cli.txt +977 -0
  608. package/llms/contract.txt +606 -0
  609. package/llms/declaration.txt +286 -0
  610. package/llms/files.txt +30 -0
  611. package/llms/geo.txt +114 -0
  612. package/llms/google.txt +27 -0
  613. package/llms/live.txt +471 -0
  614. package/llms/node.txt +43 -0
  615. package/llms/oauth.txt +136 -0
  616. package/llms/observability.txt +893 -0
  617. package/llms/primitives.txt +158 -0
  618. package/llms/react.txt +184 -0
  619. package/llms/release.txt +176 -0
  620. package/llms/remote.txt +25 -0
  621. package/llms/server.2.txt +361 -0
  622. package/llms/server.3.txt +1031 -0
  623. package/llms/server.4.txt +905 -0
  624. package/llms/server.5.txt +250 -0
  625. package/llms/server.txt +996 -0
  626. package/llms/stitchkit.2.txt +836 -0
  627. package/llms/stitchkit.3.txt +147 -0
  628. package/llms/stitchkit.txt +260 -0
  629. package/llms/telegram.txt +30 -0
  630. package/llms/testing.txt +676 -0
  631. package/llms/tools-connections.txt +45 -0
  632. package/llms/tools-contract.txt +9 -0
  633. package/llms/tools-invoker.txt +9 -0
  634. package/llms/tools.2.txt +838 -0
  635. package/llms/tools.txt +1004 -0
  636. package/llms/tracking-server.txt +32 -0
  637. package/llms/tracking.txt +263 -0
  638. package/llms/upgrading-0.37.0-0.50.0.txt +947 -0
  639. package/llms/upgrading-0.53.0-0.67.0.txt +1174 -0
  640. package/llms/upgrading-0.68.0-0.94.0.txt +1159 -0
  641. package/llms/upgrading.txt +215 -0
  642. package/llms-full.txt +305 -75
  643. package/llms.txt +54 -5
  644. package/package.json +84 -83
  645. package/dist/agent-runtime/durability-contract.d.ts.map +0 -1
  646. package/dist/agent-runtime/durability-json.d.ts.map +0 -1
  647. package/dist/agent-runtime/durability-ledger.d.ts.map +0 -1
  648. package/dist/agent-runtime/durability-scheduler.d.ts.map +0 -1
  649. package/dist/agent-runtime/durability.d.ts.map +0 -1
  650. package/dist/agent-runtime/store-driver.d.ts.map +0 -1
  651. package/dist/agent-runtime-browser.d.ts +0 -5
  652. package/dist/agent-runtime-browser.d.ts.map +0 -1
  653. package/dist/agent-runtime-coding-tools.d.ts.map +0 -1
  654. package/dist/agent-runtime-coding-tools.js +0 -23
  655. package/dist/agent-runtime-harness.d.ts.map +0 -1
  656. package/dist/agent-runtime-openrouter.d.ts.map +0 -1
  657. package/dist/agent-runtime-sandbox.d.ts.map +0 -1
  658. package/dist/agent-runtime-sqlite-bun.d.ts.map +0 -1
  659. package/dist/agent-runtime-sqlite-node.d.ts.map +0 -1
  660. package/dist/agent-runtime-testing.d.ts +0 -3
  661. package/dist/agent-runtime-testing.d.ts.map +0 -1
  662. package/dist/agent-runtime-testing.js +0 -156
  663. package/dist/agent-runtime.d.ts.map +0 -1
  664. package/dist/application/channel.d.ts.map +0 -1
  665. package/dist/application-diagnostic-journal.d.ts.map +0 -1
  666. package/dist/application-grammy.d.ts.map +0 -1
  667. package/dist/application-opentelemetry.d.ts.map +0 -1
  668. package/dist/application-schemas.d.ts.map +0 -1
  669. package/dist/application.d.ts.map +0 -1
  670. package/dist/cli.d.ts.map +0 -1
  671. package/dist/contract/index.d.ts +0 -8
  672. package/dist/contract/index.d.ts.map +0 -1
  673. package/dist/declaration.d.ts.map +0 -1
  674. package/dist/files.d.ts.map +0 -1
  675. package/dist/geo.d.ts.map +0 -1
  676. package/dist/google.d.ts.map +0 -1
  677. package/dist/index-0j3vcp5m.js +0 -28
  678. package/dist/index-a11g2kry.js +0 -866
  679. package/dist/index-cnyk6te3.js +0 -77
  680. package/dist/index-fadnxwna.js +0 -1046
  681. package/dist/index-hrbajay7.js +0 -1196
  682. package/dist/index-s8cnx02s.js +0 -90
  683. package/dist/index-v5573g1k.js +0 -142
  684. package/dist/index-vk3kq9sb.js +0 -3344
  685. package/dist/index.d.ts.map +0 -1
  686. package/dist/internal/errors.d.ts.map +0 -1
  687. package/dist/internal/observability-sink.d.ts.map +0 -1
  688. package/dist/live.d.ts.map +0 -1
  689. package/dist/logger.d.ts.map +0 -1
  690. package/dist/node.d.ts.map +0 -1
  691. package/dist/oauth.d.ts.map +0 -1
  692. package/dist/observability/index.d.ts.map +0 -1
  693. package/dist/primitives.d.ts +0 -3
  694. package/dist/primitives.d.ts.map +0 -1
  695. package/dist/react.d.ts.map +0 -1
  696. package/dist/release.d.ts.map +0 -1
  697. package/dist/remote.d.ts.map +0 -1
  698. package/dist/remote.js +0 -88
  699. package/dist/retained.d.ts.map +0 -1
  700. package/dist/server/file-state-store.d.ts.map +0 -1
  701. package/dist/server/index.d.ts.map +0 -1
  702. package/dist/server/request.d.ts.map +0 -1
  703. package/dist/telegram.d.ts.map +0 -1
  704. package/dist/testing/agent-store-conformance.d.ts.map +0 -1
  705. package/dist/testing.d.ts +0 -39
  706. package/dist/testing.d.ts.map +0 -1
  707. package/dist/tool-invoker.d.ts.map +0 -1
  708. package/dist/tool-invoker.js +0 -21
  709. package/dist/tools/async-operation-contract.d.ts.map +0 -1
  710. package/dist/tools/async-operation.d.ts +0 -332
  711. package/dist/tools/async-operation.d.ts.map +0 -1
  712. package/dist/tools/cli-args.d.ts.map +0 -1
  713. package/dist/tools/cli-checkpoint.d.ts.map +0 -1
  714. package/dist/tools/cli-command.d.ts.map +0 -1
  715. package/dist/tools/cli-format.d.ts.map +0 -1
  716. package/dist/tools/cli-installer.d.ts.map +0 -1
  717. package/dist/tools/cli-invoke.d.ts.map +0 -1
  718. package/dist/tools/cli-manifest.d.ts.map +0 -1
  719. package/dist/tools/cli-policy.d.ts.map +0 -1
  720. package/dist/tools/cli-profile.d.ts.map +0 -1
  721. package/dist/tools/cli-signature.d.ts.map +0 -1
  722. package/dist/tools/cli-stream.d.ts.map +0 -1
  723. package/dist/tools/cli-update.d.ts.map +0 -1
  724. package/dist/tools/cli-view.d.ts.map +0 -1
  725. package/dist/tools/cli-wait.d.ts.map +0 -1
  726. package/dist/tools/cli.d.ts.map +0 -1
  727. package/dist/tools/coerce.d.ts.map +0 -1
  728. package/dist/tools/connections/index.d.ts.map +0 -1
  729. package/dist/tools/define-download-tool.d.ts.map +0 -1
  730. package/dist/tools/define-upload-tool.d.ts.map +0 -1
  731. package/dist/tools/define-view-file-tool.d.ts.map +0 -1
  732. package/dist/tools/define-wait-tool.d.ts.map +0 -1
  733. package/dist/tools/download-core.d.ts.map +0 -1
  734. package/dist/tools/flatten-join.d.ts.map +0 -1
  735. package/dist/tools/flatten.d.ts.map +0 -1
  736. package/dist/tools/json-schema-dialect.d.ts.map +0 -1
  737. package/dist/tools/json-schema.d.ts.map +0 -1
  738. package/dist/tools/managed-file-error.d.ts.map +0 -1
  739. package/dist/tools/mcp-app.d.ts.map +0 -1
  740. package/dist/tools/mcp-catalog.d.ts.map +0 -1
  741. package/dist/tools/mcp-handler.d.ts.map +0 -1
  742. package/dist/tools/mcp-prepare.d.ts.map +0 -1
  743. package/dist/tools/mcp-progress.d.ts.map +0 -1
  744. package/dist/tools/mcp-round-policy.d.ts.map +0 -1
  745. package/dist/tools/mcp-round.d.ts.map +0 -1
  746. package/dist/tools/mcp-stdio-signals.d.ts.map +0 -1
  747. package/dist/tools/mcp-stdio.d.ts.map +0 -1
  748. package/dist/tools/mcp-trace.d.ts.map +0 -1
  749. package/dist/tools/mcp.d.ts.map +0 -1
  750. package/dist/tools/mount-download.d.ts.map +0 -1
  751. package/dist/tools/mount-upload.d.ts.map +0 -1
  752. package/dist/tools/mount-wait.d.ts.map +0 -1
  753. package/dist/tools/native-mcp.d.ts +0 -20
  754. package/dist/tools/native-mcp.d.ts.map +0 -1
  755. package/dist/tools/native-result.d.ts.map +0 -1
  756. package/dist/tools/oauth-metadata.d.ts.map +0 -1
  757. package/dist/tools/oauth-provider.d.ts.map +0 -1
  758. package/dist/tools/portable-formats.d.ts.map +0 -1
  759. package/dist/tools/presentation.d.ts.map +0 -1
  760. package/dist/tools/schema.d.ts.map +0 -1
  761. package/dist/tools/untyped-properties.d.ts.map +0 -1
  762. package/dist/tools/upload-core.d.ts.map +0 -1
  763. package/dist/tools/view-file-contract.d.ts.map +0 -1
  764. package/dist/tools/view-file.d.ts.map +0 -1
  765. package/dist/tools/wait-core.d.ts.map +0 -1
  766. package/dist/tools-contract.d.ts.map +0 -1
  767. package/dist/tools.d.ts +0 -50
  768. package/dist/tools.d.ts.map +0 -1
  769. package/dist/tracking-server.d.ts.map +0 -1
  770. package/dist/tracking.d.ts.map +0 -1
  771. package/dist/upgrade-cli.d.ts.map +0 -1
  772. package/dist/{retained.d.ts → browser/retained.d.ts} +0 -0
  773. package/dist/{declaration.d.ts → declaration/declaration.d.ts} +0 -0
  774. package/dist/{upgrade-cli.d.ts → entrypoints/bin/upgrade-cli.d.ts} +0 -0
  775. package/dist/{tracking-server.js → entrypoints/tracking/server.js} +0 -0
  776. package/dist/{google.d.ts → google/google.d.ts} +0 -0
  777. package/dist/{index-pq95qkbf.js → index-5jm36zv1.js} +0 -0
  778. package/dist/{index-actkayzn.js → index-70yj2ebz.js} +3 -3
  779. /package/dist/{application → internal}/channel.d.ts +0 -0
  780. /package/dist/{logger.d.ts → internal/logger.d.ts} +0 -0
  781. /package/dist/{server → internal}/request.d.ts +0 -0
  782. /package/dist/{tools → json-schema}/json-schema.d.ts +0 -0
  783. /package/dist/tools/{async-operation-contract.d.ts → operations/async-operation-contract.d.ts} +0 -0
  784. /package/dist/tools/{mount-wait.d.ts → operations/mount-wait.d.ts} +0 -0
  785. /package/dist/tools/{wait-core.d.ts → operations/wait-core.d.ts} +0 -0
  786. /package/dist/tools/{coerce.d.ts → schema/coerce.d.ts} +0 -0
  787. /package/dist/tools/{flatten-join.d.ts → schema/flatten-join.d.ts} +0 -0
  788. /package/dist/tools/{flatten.d.ts → schema/flatten.d.ts} +0 -0
  789. /package/dist/tools/{portable-formats.d.ts → schema/portable-formats.d.ts} +0 -0
  790. /package/dist/tools/{schema.d.ts → schema/schema.d.ts} +0 -0
  791. /package/dist/tools/{untyped-properties.d.ts → schema/untyped-properties.d.ts} +0 -0
  792. /package/dist/tools/{native-result.d.ts → transfer/native-result.d.ts} +0 -0
  793. /package/dist/tools/{view-file-contract.d.ts → transfer/view-file-contract.d.ts} +0 -0
@@ -1,3344 +0,0 @@
1
- import {
2
- messageOf
3
- } from "./index-p13mwz16.js";
4
- import {
5
- AgentRuntimeEventSchema,
6
- agentDurableEventId
7
- } from "./index-y64k3s0h.js";
8
- import {
9
- advanceToolChronology,
10
- assistantStatus,
11
- canProjectToolChronology,
12
- canonicalAgentJson,
13
- createToolChronology,
14
- isAssistantHistoryEvidence,
15
- isCompleteAgentHistoryTurn
16
- } from "./index-zwkgfq1s.js";
17
- import {
18
- AgentAssistantPlaceholderSchema,
19
- AgentJsonObjectSchema,
20
- AgentMessagePartSchema,
21
- AgentMessageSchema,
22
- AgentProvenanceSchema,
23
- AgentProviderResponseSchema,
24
- AgentRunOperationSchema,
25
- AgentRunSchema,
26
- AgentSnapshotSchema,
27
- runStateForTerminalReason
28
- } from "./index-gtj3zc53.js";
29
- import {
30
- createBoundedSinkManager
31
- } from "./index-wnfk50r0.js";
32
- import {
33
- createLocalStepDurability,
34
- createToolDurabilityContext,
35
- isAgentToolError
36
- } from "./index-kw9t5ayn.js";
37
- import {
38
- ToolExecutionControlError,
39
- isToolExecutionControlError
40
- } from "./index-yn8remb1.js";
41
- import {
42
- isRecord,
43
- transportResult
44
- } from "./index-77fekveh.js";
45
-
46
- // src/agent-runtime/terminal-commit.ts
47
- class AgentRuntimeConflictError extends Error {
48
- constructor(operation) {
49
- super(`Agent runtime store conflict during ${operation}`);
50
- this.name = "AgentRuntimeConflictError";
51
- }
52
- }
53
- function appliedSnapshot(result, operation) {
54
- if (result.outcome === "applied" || result.outcome === "duplicate")
55
- return result.snapshot;
56
- throw new AgentRuntimeConflictError(operation);
57
- }
58
- function viewOfSnapshot(snapshot, runId, retainedAssistant) {
59
- const run = snapshot.runs.find((candidate) => candidate.id === runId);
60
- const assistant = snapshot.messages.find((message) => message.id === run?.assistantMessageId) ?? retainedAssistant;
61
- return {
62
- snapshotVersion: snapshot.version,
63
- conversationId: snapshot.conversationId,
64
- ...run && { run },
65
- ...assistant && { assistant }
66
- };
67
- }
68
- function viewOfRun(view, conversationId) {
69
- return {
70
- snapshotVersion: view.snapshotVersion,
71
- conversationId,
72
- run: view.run,
73
- ...view.assistant && { assistant: view.assistant }
74
- };
75
- }
76
- function canonicalTerminal(view) {
77
- const { run, assistant } = view;
78
- if (!run?.terminalReason)
79
- return;
80
- if (view.conversationId !== run.conversationId || !assistant || assistant.id !== run.assistantMessageId || assistant.conversationId !== run.conversationId || assistant.runId !== run.id || assistant.role !== "assistant" || assistant.status !== assistantStatus(run.terminalReason)) {
81
- throw new AgentRuntimeConflictError("terminal result projection");
82
- }
83
- return {
84
- snapshotVersion: view.snapshotVersion,
85
- run,
86
- assistant,
87
- reason: run.terminalReason,
88
- committedByCaller: false,
89
- ...run.terminalPolicyName && { policyName: run.terminalPolicyName },
90
- ...run.usage && { usage: run.usage }
91
- };
92
- }
93
- function interruptedCandidate(candidate, run, now) {
94
- const reason = candidate.reason === "superseded" ? "superseded" : "interrupted";
95
- const hasInterruptControl = candidate.assistant.parts.some((part) => part.type === "control" && part.reason === "run-interrupted");
96
- const parts = hasInterruptControl ? candidate.assistant.parts : [
97
- ...candidate.assistant.parts,
98
- AgentMessagePartSchema.parse({ type: "control", reason: "run-interrupted" })
99
- ];
100
- return {
101
- ...candidate.usage && { usage: candidate.usage },
102
- run,
103
- assistant: AgentMessageSchema.parse({
104
- ...candidate.assistant,
105
- status: assistantStatus(reason),
106
- parts,
107
- updatedAt: now().toISOString()
108
- }),
109
- reason
110
- };
111
- }
112
- function canRetryTerminal(current, previous, runtimeEpoch) {
113
- return (current.state === "running" || current.state === "interrupt_requested") && current.ownerId === runtimeEpoch && current.fencingToken === previous.fencingToken;
114
- }
115
- var TERMINAL_COMMIT_ATTEMPTS = 32;
116
- async function commitAgentRunTerminal(input) {
117
- let candidate = input.candidate;
118
- for (let attempt = 0;attempt < TERMINAL_COMMIT_ATTEMPTS; attempt += 1) {
119
- const committed = await input.store.commitRunTerminal({
120
- conversationId: candidate.run.conversationId,
121
- runId: candidate.run.id,
122
- expectedRevision: candidate.run.revision,
123
- ownerId: input.runtimeEpoch,
124
- ...candidate.run.fencingToken !== undefined && {
125
- fencingToken: candidate.run.fencingToken
126
- },
127
- assistant: candidate.assistant,
128
- reason: candidate.reason,
129
- ...candidate.policyName && { policyName: candidate.policyName },
130
- ...candidate.usage && { usage: candidate.usage },
131
- ...candidate.absorb?.length && { absorb: candidate.absorb }
132
- });
133
- if (committed.outcome === "applied") {
134
- const terminal2 = canonicalTerminal(viewOfSnapshot(committed.snapshot, candidate.run.id));
135
- if (!terminal2)
136
- throw new AgentRuntimeConflictError("terminal result projection");
137
- const absorbed = committed.snapshot.runs.filter((run) => run.absorbedIntoRunId === candidate.run.id);
138
- return {
139
- ...terminal2,
140
- committedByCaller: true,
141
- ...absorbed.length > 0 && { absorbed }
142
- };
143
- }
144
- if (committed.outcome === "duplicate") {
145
- const terminal2 = canonicalTerminal(viewOfSnapshot(committed.snapshot, candidate.run.id, committed.assistant));
146
- if (!terminal2)
147
- throw new AgentRuntimeConflictError("terminal result projection");
148
- return terminal2;
149
- }
150
- if (committed.outcome !== "conflict") {
151
- throw new AgentRuntimeConflictError("terminal commit");
152
- }
153
- const latest = await input.store.loadRun({
154
- conversationId: candidate.run.conversationId,
155
- runId: candidate.run.id
156
- });
157
- const terminal = latest ? canonicalTerminal(viewOfRun(latest, candidate.run.conversationId)) : undefined;
158
- if (terminal)
159
- return terminal;
160
- const current = latest?.run;
161
- if (!current || !canRetryTerminal(current, candidate.run, input.runtimeEpoch)) {
162
- throw new AgentRuntimeConflictError("terminal commit");
163
- }
164
- candidate = current.state === "interrupt_requested" ? interruptedCandidate(candidate, current, input.now) : { ...candidate, run: current };
165
- }
166
- throw new AgentRuntimeConflictError("terminal commit");
167
- }
168
-
169
- // src/agent-runtime/context-refusal.ts
170
- class AgentContextOverflowError extends Error {
171
- name = "AgentContextOverflowError";
172
- constructor(message = "Agent context exceeds the configured model budget", options) {
173
- super(message, options);
174
- }
175
- }
176
-
177
- // src/agent-runtime/coordinator.ts
178
- function assertCloseBudgets(options) {
179
- for (const [name, value] of Object.entries(options)) {
180
- if (value !== undefined && (!Number.isSafeInteger(value) || value < 0)) {
181
- throw new TypeError(`${name} must be a non-negative safe integer`);
182
- }
183
- }
184
- }
185
- function createAgentSessionCoordinator() {
186
- const lanes = new Map;
187
- let closed = false;
188
- const waitWithin = async (settled, timeoutMs) => {
189
- if (timeoutMs === 0)
190
- return false;
191
- let timer;
192
- const timeout = new Promise((resolve) => {
193
- timer = setTimeout(() => resolve(false), timeoutMs);
194
- });
195
- const completed = settled.then(() => true);
196
- const result = await Promise.race([completed, timeout]);
197
- if (timer !== undefined)
198
- clearTimeout(timer);
199
- return result;
200
- };
201
- const laneFor = (key) => {
202
- const existing = lanes.get(key);
203
- if (existing)
204
- return existing;
205
- const created = { queue: [] };
206
- lanes.set(key, created);
207
- return created;
208
- };
209
- const startNext = (key, lane) => {
210
- if (lane.active)
211
- return;
212
- const next = lane.queue.shift();
213
- if (!next) {
214
- lanes.delete(key);
215
- return;
216
- }
217
- next.start();
218
- };
219
- return {
220
- submit(input) {
221
- const accepted = Promise.withResolvers();
222
- const result = Promise.withResolvers();
223
- if (closed) {
224
- const error = new Error("Agent session coordinator is closed");
225
- accepted.reject(error);
226
- result.reject(error);
227
- return { accepted: accepted.promise, result: result.promise };
228
- }
229
- const lane = laneFor(input.key);
230
- const pending = {
231
- priority: input.policy === "interrupt-next",
232
- reject(reason) {
233
- accepted.reject(reason);
234
- result.reject(reason);
235
- },
236
- async start() {
237
- const controller = new AbortController;
238
- const settlement = Promise.withResolvers();
239
- lane.active = { controller, settled: settlement.promise };
240
- try {
241
- const coordinated = await input.create(controller.signal);
242
- accepted.resolve();
243
- result.resolve(await coordinated.execute());
244
- } catch (error) {
245
- accepted.reject(error);
246
- result.reject(error);
247
- } finally {
248
- settlement.resolve();
249
- lane.active = undefined;
250
- startNext(input.key, lane);
251
- }
252
- }
253
- };
254
- if (input.policy === "interrupt" || input.policy === "interrupt-next") {
255
- lane.active?.controller.abort("user-interrupt");
256
- }
257
- if (input.policy === "supersede")
258
- lane.active?.controller.abort("supersede");
259
- if (pending.priority) {
260
- const firstOrdinary = lane.queue.findIndex((queued) => !queued.priority);
261
- if (firstOrdinary === -1)
262
- lane.queue.push(pending);
263
- else
264
- lane.queue.splice(firstOrdinary, 0, pending);
265
- } else {
266
- lane.queue.push(pending);
267
- }
268
- startNext(input.key, lane);
269
- return { accepted: accepted.promise, result: result.promise };
270
- },
271
- stop(key, reason = "user-interrupt") {
272
- const lane = lanes.get(key);
273
- if (!lane?.active)
274
- return false;
275
- lane.active.controller.abort(reason);
276
- return true;
277
- },
278
- async close(options = {}) {
279
- assertCloseBudgets(options);
280
- closed = true;
281
- const error = new Error("Agent session coordinator is closed");
282
- for (const lane of lanes.values()) {
283
- for (const pending of lane.queue.splice(0))
284
- pending.reject(error);
285
- }
286
- const active = [...lanes.values()].map((lane) => lane.active).filter((run) => run !== undefined);
287
- const settlements = active.map((run) => run.settled);
288
- const outstanding = new Set(settlements);
289
- for (const settled of settlements) {
290
- settled.then(() => {
291
- outstanding.delete(settled);
292
- });
293
- }
294
- const drain = Promise.all(settlements).then(() => {
295
- return;
296
- });
297
- const finished = () => ({
298
- settled: outstanding.size === 0,
299
- timedOut: outstanding.size > 0,
300
- remaining: outstanding.size
301
- });
302
- if (options.gracePeriodMs !== undefined && await waitWithin(drain, options.gracePeriodMs)) {
303
- return finished();
304
- }
305
- for (const run of active)
306
- run.controller.abort("shutdown");
307
- if (options.forceTimeoutMs === undefined) {
308
- await drain;
309
- return finished();
310
- }
311
- await waitWithin(drain, options.forceTimeoutMs);
312
- return finished();
313
- },
314
- isRunning(key) {
315
- return lanes.get(key)?.active !== undefined;
316
- }
317
- };
318
- }
319
-
320
- // src/agent-runtime/events.ts
321
- function createAgentRuntimeEventSink(config) {
322
- const manager = createBoundedSinkManager({
323
- write: config.write,
324
- ...config.maxPending !== undefined && { maxPending: config.maxPending },
325
- ...config.onSinkError && { onSinkError: config.onSinkError },
326
- ...config.onDrop && { onDrop: config.onDrop }
327
- });
328
- return {
329
- publish(rawEvent) {
330
- const event = AgentRuntimeEventSchema.parse(rawEvent);
331
- const projected = config.project?.(event) ?? (config.project ? undefined : event);
332
- if (projected)
333
- manager.submit(() => AgentRuntimeEventSchema.parse(projected));
334
- },
335
- flush: (bound) => manager.flush(bound),
336
- getStatus: () => manager.getStatus(),
337
- close: (bound) => manager.close(bound)
338
- };
339
- }
340
-
341
- // src/agent-runtime/history.ts
342
- import { modelMessageSchema as modelMessageSchema2 } from "ai";
343
-
344
- // src/internal/ai-sdk-typed.ts
345
- import { modelMessageSchema, streamText } from "ai";
346
- function streamAgentTextBoundary(options) {
347
- return streamText(options);
348
- }
349
- function modelMessageWithApprovalSignature(input) {
350
- const parsed = modelMessageSchema.parse(input);
351
- const rawContent = isRecord(input) ? input.content : undefined;
352
- if (parsed.role !== "assistant" || typeof parsed.content === "string" || !Array.isArray(rawContent)) {
353
- return parsed;
354
- }
355
- const content = parsed.content.map((part, index) => {
356
- const raw = rawContent[index];
357
- if (part.type !== "tool-approval-request" || !isRecord(raw) || typeof raw.signature !== "string") {
358
- return part;
359
- }
360
- return { ...part, signature: raw.signature };
361
- });
362
- return transportResult({ ...parsed, content });
363
- }
364
-
365
- // src/agent-runtime/history.ts
366
- function providerOptions(envelope) {
367
- if (!envelope)
368
- return;
369
- return envelope.provider === "ai-sdk" ? envelope.data : { [envelope.provider]: envelope.data };
370
- }
371
- function textContent(parts) {
372
- return parts.filter((part) => part.type === "text").map((part) => part.text).join(`
373
- `);
374
- }
375
- function unrepresented(parts, rendered) {
376
- const missing = new Set;
377
- for (const part of parts) {
378
- if (!rendered.has(part.type))
379
- missing.add(part.type);
380
- }
381
- return [...missing];
382
- }
383
- function decide(message, action, reason, rendered) {
384
- if (action === "omitted" || !rendered)
385
- return { messageId: message.id, action, reason };
386
- const omittedParts = unrepresented(message.parts, rendered);
387
- return {
388
- messageId: message.id,
389
- action,
390
- reason,
391
- ...omittedParts.length > 0 && { omittedParts }
392
- };
393
- }
394
- var INTERRUPTION_NOTE = "[interrupted: this turn was cut off before it finished]";
395
- var FAILURE_NOTE = "[failed: partial evidence from a run that did not complete successfully]";
396
- async function userMessage(message, options) {
397
- const rendered = new Set;
398
- const text = textContent(message.parts);
399
- const content = [];
400
- if (text) {
401
- content.push({ type: "text", text });
402
- rendered.add("text");
403
- }
404
- for (const part of message.parts) {
405
- if (part.type !== "file")
406
- continue;
407
- if (options.resolveFile) {
408
- content.push({
409
- type: "file",
410
- data: await options.resolveFile(part, message),
411
- mediaType: part.mediaType,
412
- ...part.filename && { filename: part.filename }
413
- });
414
- rendered.add("file");
415
- continue;
416
- }
417
- const fallback = options.unresolvedFile ?? "omit";
418
- if (fallback === "error") {
419
- throw new Error(`No history file resolver configured for ${part.reference}`);
420
- }
421
- if (fallback === "text") {
422
- const described = part.filename ?? part.mediaType;
423
- content.push({
424
- type: "text",
425
- text: described ? `[attachment: ${described}]` : "[attachment]"
426
- });
427
- rendered.add("file");
428
- }
429
- }
430
- if (content.length === 0)
431
- return { rendered };
432
- return { message: modelMessageSchema2.parse({ role: "user", content }), rendered };
433
- }
434
- function assistantMessages(message, marker) {
435
- const rendered = new Set;
436
- const messages = [];
437
- let role;
438
- let content = [];
439
- const flush = () => {
440
- if (!role || content.length === 0)
441
- return;
442
- messages.push(modelMessageWithApprovalSignature({ role, content }));
443
- content = [];
444
- };
445
- const append = (nextRole, part) => {
446
- if (role !== nextRole) {
447
- flush();
448
- role = nextRole;
449
- }
450
- content.push(part);
451
- };
452
- for (const part of message.parts) {
453
- if (part.type === "text") {
454
- append("assistant", { type: "text", text: part.text });
455
- rendered.add("text");
456
- }
457
- if (part.type === "reasoning") {
458
- append("assistant", {
459
- type: "reasoning",
460
- text: part.text,
461
- ...part.provider && { providerOptions: providerOptions(part.provider) }
462
- });
463
- rendered.add("reasoning");
464
- }
465
- if (part.type === "tool-call") {
466
- append("assistant", {
467
- type: "tool-call",
468
- toolCallId: part.callId,
469
- toolName: part.toolName,
470
- input: part.input,
471
- ...part.provider && { providerOptions: providerOptions(part.provider) }
472
- });
473
- rendered.add("tool-call");
474
- }
475
- if (part.type === "tool-result") {
476
- const output = part.outcome === "success" ? { type: "json", value: part.output ?? null } : { type: "error-json", value: part.output ?? { message: part.outcome } };
477
- append("tool", {
478
- type: "tool-result",
479
- toolCallId: part.callId,
480
- toolName: part.toolName,
481
- output
482
- });
483
- rendered.add("tool-result");
484
- }
485
- if (part.type === "tool-approval-request") {
486
- append("assistant", {
487
- type: "tool-approval-request",
488
- approvalId: part.approvalId,
489
- toolCallId: part.callId,
490
- ...part.isAutomatic !== undefined && { isAutomatic: part.isAutomatic },
491
- ...part.signature && { signature: part.signature }
492
- });
493
- rendered.add("tool-approval-request");
494
- }
495
- if (part.type === "tool-approval-response") {
496
- append("tool", {
497
- type: "tool-approval-response",
498
- approvalId: part.approvalId,
499
- approved: part.approved,
500
- ...part.reason && { reason: part.reason }
501
- });
502
- rendered.add("tool-approval-response");
503
- }
504
- }
505
- if (marker && (messages.length > 0 || content.length > 0)) {
506
- append("assistant", {
507
- type: "text",
508
- text: marker === "interrupted" ? INTERRUPTION_NOTE : FAILURE_NOTE
509
- });
510
- rendered.add("control");
511
- }
512
- flush();
513
- return { messages, rendered };
514
- }
515
- function interruptedSystemNote(message) {
516
- const rendered = new Set;
517
- const text = textContent(message.parts);
518
- if (!text)
519
- return { rendered };
520
- rendered.add("text");
521
- rendered.add("control");
522
- return { text: `[interrupted] partial response: ${text}`, rendered };
523
- }
524
- async function projectAgentHistoryDetailed(messages, options = {}) {
525
- const projected = [];
526
- const system = [];
527
- const decisions = [];
528
- const interruptedRule = options.interruptedAssistant ?? "assistant-marked";
529
- let observedUser = false;
530
- let chronology = createToolChronology();
531
- let conversationId;
532
- for (const message of messages) {
533
- if (message.conversationId !== conversationId) {
534
- conversationId = message.conversationId;
535
- chronology = createToolChronology();
536
- observedUser = false;
537
- }
538
- if (message.role === "assistant" && !isAssistantHistoryEvidence(message.status, options.evidencePolicy)) {
539
- decisions.push(decide(message, "omitted", message.status === "superseded" ? "superseded" : "draft-or-failed"));
540
- continue;
541
- }
542
- if (message.status === "streaming" || message.status === "failed" && options.evidencePolicy?.failedAssistant !== "assistant-marked") {
543
- decisions.push(decide(message, "omitted", "draft-or-failed"));
544
- continue;
545
- }
546
- if (message.role === "user") {
547
- const user = await userMessage(message, options);
548
- if (chronology.pending === 0)
549
- chronology = createToolChronology();
550
- observedUser = true;
551
- if (user.message) {
552
- projected.push(user.message);
553
- decisions.push(decide(message, "projected", "projected", user.rendered));
554
- } else {
555
- decisions.push(decide(message, "omitted", "empty"));
556
- }
557
- continue;
558
- }
559
- if (message.role === "system" || message.role === "summary") {
560
- const content = textContent(message.parts);
561
- if (content) {
562
- system.push(content);
563
- decisions.push(decide(message, "projected", "projected", new Set(["text"])));
564
- } else {
565
- decisions.push(decide(message, "omitted", "empty"));
566
- }
567
- continue;
568
- }
569
- if (!observedUser && options.leadingAssistant !== "allow") {
570
- if (options.leadingAssistant === "error") {
571
- throw new Error(`Assistant message ${message.id} precedes the first user message`);
572
- }
573
- decisions.push(decide(message, "omitted", "leading-assistant"));
574
- continue;
575
- }
576
- const interrupted = message.status === "interrupted";
577
- if (interrupted && interruptedRule === "omit") {
578
- decisions.push(decide(message, "omitted", "interrupted"));
579
- continue;
580
- }
581
- if (interrupted && interruptedRule === "system-note") {
582
- const note = interruptedSystemNote(message);
583
- if (note.text) {
584
- system.push(note.text);
585
- decisions.push(decide(message, "projected", "projected", note.rendered));
586
- } else {
587
- decisions.push(decide(message, "omitted", "empty"));
588
- }
589
- continue;
590
- }
591
- const nextChronology = advanceToolChronology(chronology, message.parts);
592
- if (!nextChronology || !canProjectToolChronology(nextChronology)) {
593
- if (options.incompleteToolTurn === "error") {
594
- throw new Error(`Assistant message ${message.id} has incomplete tool chronology`);
595
- }
596
- decisions.push(decide(message, "omitted", "incomplete-tool-turn"));
597
- continue;
598
- }
599
- const assistant = assistantMessages(message, interrupted ? "interrupted" : message.status === "failed" ? "failed" : undefined);
600
- chronology = nextChronology;
601
- projected.push(...assistant.messages);
602
- decisions.push(assistant.messages.length > 0 ? decide(message, "projected", "projected", assistant.rendered) : decide(message, "omitted", "empty"));
603
- }
604
- return { messages: projected, decisions, system };
605
- }
606
- async function projectAgentHistory(messages, options = {}) {
607
- return [...(await projectAgentHistoryDetailed(messages, options)).messages];
608
- }
609
-
610
- // src/agent-runtime/managed-tools.ts
611
- async function assertFence(config, input) {
612
- const rejected = await config.assertCurrent(input);
613
- if (rejected)
614
- throw new ToolExecutionControlError(rejected);
615
- }
616
- function createAgentToolFenceLifecycle(config) {
617
- const callContext = (ctx, endpoint) => ({
618
- runId: config.runId,
619
- ...config.context?.(ctx, endpoint)
620
- });
621
- return {
622
- async beforeHandle(ctx, endpoint) {
623
- await assertFence(config, callContext(ctx, endpoint));
624
- },
625
- async afterHandle(ctx, result, endpoint) {
626
- const current = callContext(ctx, endpoint);
627
- await assertFence(config, current);
628
- await config.onSettled?.(current);
629
- return result;
630
- }
631
- };
632
- }
633
-
634
- // src/agent-runtime/prompt.ts
635
- import { z } from "zod";
636
- var AgentTokenCountSchema = z.object({
637
- value: z.int().nonnegative().optional(),
638
- provenance: AgentProvenanceSchema.extract([
639
- "measured",
640
- "computed",
641
- "estimated",
642
- "unavailable"
643
- ])
644
- });
645
- function budgetTurns(messages, evidencePolicy) {
646
- const turns = [];
647
- let current = [];
648
- const flush = () => {
649
- if (current.length === 0)
650
- return;
651
- turns.push({
652
- messages: current,
653
- complete: isCompleteAgentHistoryTurn(current, evidencePolicy),
654
- protectedSystem: false
655
- });
656
- current = [];
657
- };
658
- for (const message of messages) {
659
- if (message.role === "system" || message.role === "summary") {
660
- flush();
661
- turns.push({ messages: [message], complete: true, protectedSystem: true });
662
- continue;
663
- }
664
- if (message.role === "user")
665
- flush();
666
- current.push(message);
667
- }
668
- flush();
669
- return turns;
670
- }
671
- async function selectAgentHistory(options) {
672
- if (!Number.isSafeInteger(options.availableTokens) || options.availableTokens < 0) {
673
- throw new TypeError("availableTokens must be a non-negative safe integer");
674
- }
675
- const keepRecentTurns = options.keepRecentTurns ?? 1;
676
- if (!Number.isSafeInteger(keepRecentTurns) || keepRecentTurns < 0) {
677
- throw new TypeError("keepRecentTurns must be a non-negative safe integer");
678
- }
679
- const spoken = options.messages.filter((message) => message.role !== "assistant" || isAssistantHistoryEvidence(message.status, options.evidencePolicy));
680
- const counts = new Map;
681
- let total = 0;
682
- let estimated = false;
683
- for (const message of spoken) {
684
- const count = AgentTokenCountSchema.parse(await options.estimateMessage(message));
685
- counts.set(message.id, count);
686
- const value = knownValue(count);
687
- if (value === undefined) {
688
- return {
689
- messages: [...spoken],
690
- decisions: options.messages.map((candidate) => ({
691
- messageId: candidate.id,
692
- action: candidate.role === "assistant" && !isAssistantHistoryEvidence(candidate.status, options.evidencePolicy) ? "removed" : "kept",
693
- reason: candidate.role === "assistant" && !isAssistantHistoryEvidence(candidate.status, options.evidencePolicy) ? "unspeakable" : "token-count-unavailable",
694
- tokens: counts.get(candidate.id) ?? { provenance: "unavailable" }
695
- })),
696
- totalTokens: { provenance: "unavailable" },
697
- outcome: "unavailable"
698
- };
699
- }
700
- total += value;
701
- if (count.provenance === "estimated")
702
- estimated = true;
703
- }
704
- const turns = budgetTurns(spoken, options.evidencePolicy);
705
- const completeIndexes = turns.map((turn, index) => ({ turn, index })).filter(({ turn }) => turn.complete && !turn.protectedSystem).map(({ index }) => index);
706
- const protectedRecent = new Set(completeIndexes.slice(-keepRecentTurns));
707
- const removed = new Set;
708
- for (let index = 0;index < turns.length && total > options.availableTokens; index += 1) {
709
- const turn = turns[index];
710
- if (!turn || turn.protectedSystem || !turn.complete || protectedRecent.has(index))
711
- continue;
712
- for (const message of turn.messages) {
713
- removed.add(message.id);
714
- total -= knownValue(counts.get(message.id) ?? { provenance: "unavailable" }) ?? 0;
715
- }
716
- }
717
- const messages = spoken.filter((message) => !removed.has(message.id));
718
- const decisions = options.messages.map((message) => {
719
- if (message.role === "assistant" && !isAssistantHistoryEvidence(message.status, options.evidencePolicy)) {
720
- return {
721
- messageId: message.id,
722
- action: "removed",
723
- reason: "unspeakable",
724
- tokens: { provenance: "unavailable" }
725
- };
726
- }
727
- const turnIndex = turns.findIndex((turn2) => turn2.messages.some((item) => item.id === message.id));
728
- const turn = turns[turnIndex];
729
- let reason = "within-budget";
730
- if (removed.has(message.id))
731
- reason = "oldest-eligible-turn";
732
- else if (turn?.protectedSystem)
733
- reason = "protected-system";
734
- else if (turn && !turn.complete)
735
- reason = "protected-incomplete-turn";
736
- else if (protectedRecent.has(turnIndex))
737
- reason = "protected-recent-turn";
738
- return {
739
- messageId: message.id,
740
- action: removed.has(message.id) ? "removed" : "kept",
741
- reason,
742
- tokens: counts.get(message.id) ?? { provenance: "unavailable" }
743
- };
744
- });
745
- return {
746
- messages,
747
- decisions,
748
- totalTokens: { value: total, provenance: estimated ? "estimated" : "computed" },
749
- outcome: total > options.availableTokens ? "oversized" : removed.size > 0 ? "truncated" : "fits"
750
- };
751
- }
752
- function knownValue(value) {
753
- return value.provenance === "unavailable" ? undefined : value.value;
754
- }
755
- function composeAgentPrompt(sections) {
756
- return async (options) => {
757
- const event = z.enum(["session.started", "turn.started"]).parse(options.event ?? "turn.started");
758
- const rendered = [];
759
- let systemTotal = 0;
760
- let userTotal = 0;
761
- let systemUnavailable = false;
762
- let userUnavailable = false;
763
- let systemEstimated = false;
764
- let userEstimated = false;
765
- for (const section of sections) {
766
- const role = section.role ?? "system";
767
- const text = await section.render({
768
- context: options.context,
769
- signal: options.signal,
770
- event
771
- });
772
- rendered.push({ name: section.name, stability: section.stability, role, text });
773
- let count;
774
- if (section.estimateTokens) {
775
- count = AgentTokenCountSchema.parse(await section.estimateTokens(text));
776
- } else if (options.estimateFallback) {
777
- count = AgentTokenCountSchema.parse(await options.estimateFallback(text));
778
- } else
779
- count = { provenance: "unavailable" };
780
- const value = knownValue(count);
781
- if (role === "user") {
782
- if (value === undefined)
783
- userUnavailable = true;
784
- else
785
- userTotal += value;
786
- if (count.provenance === "estimated")
787
- userEstimated = true;
788
- } else {
789
- if (value === undefined)
790
- systemUnavailable = true;
791
- else
792
- systemTotal += value;
793
- if (count.provenance === "estimated")
794
- systemEstimated = true;
795
- }
796
- }
797
- const instructionTokens = systemUnavailable ? { provenance: "unavailable" } : { value: systemTotal, provenance: systemEstimated ? "estimated" : "computed" };
798
- const userInstructionTokens = userUnavailable ? { provenance: "unavailable" } : { value: userTotal, provenance: userEstimated ? "estimated" : "computed" };
799
- let availableHistoryTokens;
800
- let contextDecision = "unavailable";
801
- if (options.budget) {
802
- if (!Number.isSafeInteger(options.budget.contextWindow) || options.budget.contextWindow < 0 || !Number.isSafeInteger(options.budget.reservedOutput) || options.budget.reservedOutput < 0) {
803
- throw new TypeError("contextWindow and reservedOutput must be non-negative safe integers");
804
- }
805
- const reserveValues = [
806
- options.budget.reservedOutput,
807
- knownValue(AgentTokenCountSchema.parse(options.budget.toolSchemas)),
808
- knownValue(AgentTokenCountSchema.parse(options.budget.attachments)),
809
- knownValue(AgentTokenCountSchema.parse(options.budget.providerOverhead)),
810
- knownValue(instructionTokens)
811
- ];
812
- if (reserveValues.every((value) => value !== undefined)) {
813
- availableHistoryTokens = options.budget.contextWindow - reserveValues.reduce((sum, value) => sum + (value ?? 0), 0);
814
- const historyTokens = options.historyTokens ? knownValue(AgentTokenCountSchema.parse(options.historyTokens)) : undefined;
815
- if (historyTokens !== undefined) {
816
- if (availableHistoryTokens < 0)
817
- contextDecision = "oversized";
818
- else if (historyTokens <= availableHistoryTokens)
819
- contextDecision = "fits";
820
- else
821
- contextDecision = options.oversizePolicy === "compact" ? "requires-compaction" : "oversized";
822
- }
823
- }
824
- }
825
- const instructionText = rendered.filter((section) => section.role === "system").map((section) => section.text).join(`
826
-
827
- `);
828
- const userInstructions = rendered.filter((section) => section.role === "user" && section.text.trim().length > 0).map((section) => ({ name: section.name, text: section.text }));
829
- return {
830
- instructions: options.adaptInstructions ? await options.adaptInstructions(instructionText) : instructionText,
831
- sections: rendered,
832
- userInstructions,
833
- instructionTokens,
834
- userInstructionTokens,
835
- finalizeSeed: (inserted) => {
836
- const seedTokens = inserted ? knownValue(userInstructionTokens) : 0;
837
- if (availableHistoryTokens === undefined || seedTokens === undefined)
838
- return { contextDecision: "unavailable" };
839
- const available = availableHistoryTokens - seedTokens;
840
- const history = options.historyTokens ? knownValue(options.historyTokens) : undefined;
841
- const decision = history === undefined ? "unavailable" : available < 0 ? "oversized" : history <= available ? "fits" : options.oversizePolicy === "compact" ? "requires-compaction" : "oversized";
842
- return { availableHistoryTokens: available, contextDecision: decision };
843
- },
844
- contextDecision,
845
- ...availableHistoryTokens !== undefined && { availableHistoryTokens }
846
- };
847
- };
848
- }
849
-
850
- // src/agent-runtime/provider-failure.ts
851
- var BY_STATUS = {
852
- 402: "insufficient-credits",
853
- 404: "model-unavailable",
854
- 408: "timeout",
855
- 413: "context-overflow",
856
- 429: "rate-limited"
857
- };
858
- var BY_MESSAGE = [
859
- [/insufficient|not enough credit|payment required|quota exceeded/i, "insufficient-credits"],
860
- [/rate.?limit|too many requests|slow down/i, "rate-limited"],
861
- [
862
- /no endpoints found|model not found|unknown model|no allowed providers/i,
863
- "model-unavailable"
864
- ],
865
- [/context length|maximum context|too many tokens|prompt is too long/i, "context-overflow"],
866
- [/timed? ?out|deadline exceeded|etimedout/i, "timeout"],
867
- [/abort|cancell?ed/i, "cancelled"]
868
- ];
869
- var RETRYABLE = new Set([
870
- "rate-limited",
871
- "timeout",
872
- "insufficient-credits",
873
- "stream-cut"
874
- ]);
875
-
876
- class AgentProviderStreamCutError extends Error {
877
- reason = "stream-cut";
878
- constructor(message = "Provider stream ended before a terminal part") {
879
- super(message);
880
- this.name = "AgentProviderStreamCutError";
881
- }
882
- }
883
- function statusOf(value) {
884
- if (!isRecord(value))
885
- return;
886
- for (const key of ["statusCode", "status", "code"]) {
887
- const candidate = value[key];
888
- if (typeof candidate === "number" && candidate >= 400 && candidate < 600)
889
- return candidate;
890
- }
891
- const nested = value.cause ?? value.response ?? value.error;
892
- return nested === value ? undefined : statusOf(nested);
893
- }
894
- function classifyProviderFailure(error) {
895
- if (error instanceof AgentProviderStreamCutError) {
896
- return { reason: "stream-cut", retryable: true, evidence: "none" };
897
- }
898
- const status = statusOf(error);
899
- const byStatus = status === undefined ? undefined : BY_STATUS[status];
900
- if (byStatus) {
901
- return {
902
- reason: byStatus,
903
- status,
904
- retryable: RETRYABLE.has(byStatus),
905
- evidence: "status"
906
- };
907
- }
908
- const message = messageOf(error);
909
- for (const [pattern, reason] of BY_MESSAGE) {
910
- if (pattern.test(message)) {
911
- return {
912
- reason,
913
- ...status !== undefined && { status },
914
- retryable: RETRYABLE.has(reason),
915
- evidence: "message"
916
- };
917
- }
918
- }
919
- return {
920
- reason: "unknown",
921
- ...status !== undefined && { status },
922
- retryable: false,
923
- evidence: "none"
924
- };
925
- }
926
- function isToolResultFailure(output) {
927
- const parsed = typeof output === "string" ? parseJson(output) : output;
928
- if (!isRecord(parsed))
929
- return false;
930
- if ("error" in parsed)
931
- return true;
932
- return isRecord(parsed.value) && "error" in parsed.value;
933
- }
934
- function parseJson(value) {
935
- try {
936
- return JSON.parse(value);
937
- } catch {
938
- return;
939
- }
940
- }
941
-
942
- // src/agent-runtime/retry-policy.ts
943
- async function recordAgentRetryDecision(input) {
944
- const retry = input.failure.retryable && input.attempt < input.policy.maxAttempts;
945
- const delayMs = retry ? input.policy.delayMs({ attempt: input.attempt, failure: input.failure }) : 0;
946
- if (!Number.isInteger(delayMs) || delayMs < 0) {
947
- throw new TypeError("Retry delay must be a non-negative integer");
948
- }
949
- if (retry) {
950
- await input.store.appendEvent({
951
- conversationId: input.conversationId,
952
- kind: "retry/scheduled",
953
- payload: { attempt: input.attempt + 1, delayMs, reason: input.failure.reason }
954
- });
955
- }
956
- return { retry, delayMs };
957
- }
958
-
959
- // src/agent-runtime/state-slots.ts
960
- import { z as z2 } from "zod";
961
- function defineStateSlot(input) {
962
- if (input.name.length === 0)
963
- throw new TypeError("State slot name must not be empty");
964
- const version = input.version ?? 1;
965
- if (!Number.isInteger(version) || version < 1) {
966
- throw new TypeError("State slot version must be a positive integer");
967
- }
968
- return {
969
- name: input.name,
970
- version,
971
- schema: input.schema,
972
- ...input.description && { description: input.description }
973
- };
974
- }
975
- var StateSetPayloadSchema = z2.object({
976
- name: z2.string().min(1),
977
- version: z2.int().positive(),
978
- value: z2.json(),
979
- actor: z2.enum(["agent", "human", "system"])
980
- }).strict();
981
- function slotRegistry(definitions) {
982
- const result = new Map;
983
- for (const definition of definitions) {
984
- if (result.has(definition.name))
985
- throw new TypeError(`Duplicate state slot: ${definition.name}`);
986
- result.set(definition.name, definition);
987
- }
988
- return result;
989
- }
990
- function createAgentStateSlotStore(input) {
991
- const definitions = slotRegistry(input.definitions);
992
- const set = async (request) => {
993
- const definition = definitions.get(request.name);
994
- if (!definition)
995
- throw new TypeError(`Unknown state slot: ${request.name}`);
996
- const value = definition.schema.parse(request.value);
997
- const payload = StateSetPayloadSchema.parse({
998
- name: definition.name,
999
- version: definition.version,
1000
- value,
1001
- actor: request.actor
1002
- });
1003
- const event = await input.store.appendEvent({
1004
- conversationId: request.conversationId,
1005
- kind: "state/set",
1006
- payload
1007
- });
1008
- return {
1009
- name: definition.name,
1010
- version: definition.version,
1011
- value,
1012
- updatedAt: event.occurredAt,
1013
- seq: event.seq
1014
- };
1015
- };
1016
- const list = async (conversationId) => {
1017
- const values = new Map;
1018
- let cursor = 1;
1019
- for (;; ) {
1020
- const page = await input.store.readEvents({
1021
- conversationId,
1022
- fromSeq: cursor,
1023
- limit: 1000
1024
- });
1025
- for (const event of page.items) {
1026
- if (event.kind !== "state/set")
1027
- continue;
1028
- const payload = StateSetPayloadSchema.parse(event.payload);
1029
- const definition = definitions.get(payload.name);
1030
- if (!definition || definition.version !== payload.version)
1031
- continue;
1032
- values.set(payload.name, {
1033
- name: payload.name,
1034
- version: payload.version,
1035
- value: definition.schema.parse(payload.value),
1036
- updatedAt: event.occurredAt,
1037
- seq: event.seq
1038
- });
1039
- }
1040
- if (page.nextSeq === undefined)
1041
- break;
1042
- cursor = page.nextSeq;
1043
- }
1044
- return [...values.values()].sort((left, right) => left.name.localeCompare(right.name));
1045
- };
1046
- const get = async (conversationId, name) => (await list(conversationId)).find((value) => value.name === name);
1047
- return { set, get, list };
1048
- }
1049
- function renderAgentStateSlots(values) {
1050
- if (values.length === 0)
1051
- return;
1052
- return [
1053
- "Durable conversation state (authoritative; newer than compacted history):",
1054
- ...values.map((slot) => `${slot.name}: ${JSON.stringify(slot.value)}`)
1055
- ].join(`
1056
- `);
1057
- }
1058
- var agentGoalStateSlot = defineStateSlot({
1059
- name: "goal",
1060
- description: "The durable objective and lifecycle of this conversation.",
1061
- schema: z2.object({
1062
- objective: z2.string().min(1),
1063
- status: z2.enum(["active", "complete", "blocked"])
1064
- }).strict()
1065
- });
1066
- var agentTodoStateSlot = defineStateSlot({
1067
- name: "todo",
1068
- description: "The durable ordered work plan for this conversation.",
1069
- schema: z2.object({
1070
- items: z2.array(z2.object({
1071
- step: z2.string().min(1),
1072
- status: z2.enum(["pending", "in_progress", "completed"])
1073
- }).strict())
1074
- }).strict()
1075
- });
1076
-
1077
- // src/agent-runtime/admission-lanes.ts
1078
- function createRuntimeAdmissionLanes() {
1079
- const lanes = new Map;
1080
- const admit = (runId) => {
1081
- const admission = { runId, completion: Promise.withResolvers() };
1082
- admission.completion.promise.catch(() => {
1083
- return;
1084
- });
1085
- return admission;
1086
- };
1087
- return {
1088
- reserve(key, runId) {
1089
- const existing = lanes.get(key);
1090
- const lane = existing ?? { acceptanceTail: Promise.resolve() };
1091
- if (!existing)
1092
- lanes.set(key, lane);
1093
- if (!lane.head) {
1094
- lane.head = admit(runId);
1095
- return { lane, admission: lane.head, shouldSchedule: true };
1096
- }
1097
- if (!lane.pending) {
1098
- lane.pending = admit(runId);
1099
- return { lane, admission: lane.pending, shouldSchedule: true };
1100
- }
1101
- return { lane, admission: lane.pending, shouldSchedule: false };
1102
- },
1103
- settle(key, admission) {
1104
- const lane = lanes.get(key);
1105
- if (!lane)
1106
- return;
1107
- if (lane.head?.runId === admission.runId) {
1108
- lane.head = lane.pending;
1109
- lane.pending = undefined;
1110
- } else if (lane.pending?.runId === admission.runId) {
1111
- lane.pending = undefined;
1112
- }
1113
- if (!lane.head && !lane.pending)
1114
- lanes.delete(key);
1115
- },
1116
- async waitForAcceptances(lane) {
1117
- while (true) {
1118
- const tail = lane.acceptanceTail;
1119
- await tail.catch(() => {
1120
- return;
1121
- });
1122
- if (tail === lane.acceptanceTail)
1123
- return;
1124
- }
1125
- }
1126
- };
1127
- }
1128
-
1129
- // src/agent-runtime/injection.ts
1130
- function createAgentInjectionRegistry() {
1131
- const offered = new Map;
1132
- return {
1133
- offer(key, entry) {
1134
- const existing = offered.get(key);
1135
- if (!existing) {
1136
- offered.set(key, [entry]);
1137
- return;
1138
- }
1139
- if (existing.some((candidate) => candidate.input.id === entry.input.id))
1140
- return;
1141
- existing.push(entry);
1142
- },
1143
- take(key, excludeRunId) {
1144
- const existing = offered.get(key);
1145
- if (!existing)
1146
- return [];
1147
- const taken = existing.filter((candidate) => candidate.runId !== excludeRunId);
1148
- const kept = existing.filter((candidate) => candidate.runId === excludeRunId);
1149
- if (kept.length === 0)
1150
- offered.delete(key);
1151
- else
1152
- offered.set(key, kept);
1153
- return taken;
1154
- },
1155
- withdraw(key, runId) {
1156
- const existing = offered.get(key);
1157
- if (!existing)
1158
- return;
1159
- const kept = existing.filter((candidate) => candidate.runId !== runId);
1160
- if (kept.length === 0)
1161
- offered.delete(key);
1162
- else
1163
- offered.set(key, kept);
1164
- },
1165
- clear() {
1166
- offered.clear();
1167
- }
1168
- };
1169
- }
1170
-
1171
- // src/agent-runtime/run-execution.ts
1172
- import { createHash } from "node:crypto";
1173
- import { setTimeout as delay } from "node:timers/promises";
1174
- import {
1175
- stepCountIs
1176
- } from "ai";
1177
-
1178
- // src/agent-runtime/deferred-tools-internal.ts
1179
- var repairs = new WeakMap;
1180
- var catalogs = new WeakMap;
1181
- function registerDeferredToolRepair(prepareStep, repair) {
1182
- repairs.set(prepareStep, repair);
1183
- }
1184
- function deferredToolRepair(prepareStep) {
1185
- return prepareStep ? repairs.get(prepareStep) : undefined;
1186
- }
1187
- function registerDeferredToolCatalog(tools, searchName, names) {
1188
- const search = tools[searchName];
1189
- if (search && typeof search === "object")
1190
- catalogs.set(search, names);
1191
- }
1192
- function deferredToolCatalog(tools, searchName) {
1193
- const search = tools[searchName];
1194
- return search && typeof search === "object" ? catalogs.get(search) : undefined;
1195
- }
1196
- function repairedSearchCall(toolCall, searchName) {
1197
- return {
1198
- ...toolCall,
1199
- toolName: searchName,
1200
- input: JSON.stringify({ query: toolCall.toolName, reason: "inactive_call" })
1201
- };
1202
- }
1203
-
1204
- // src/agent-runtime/owned-provider-stream.ts
1205
- var DEFAULT_CLEANUP_TIMEOUT_MS = 1000;
1206
- async function settleCleanup(operation, timeoutMs) {
1207
- let timeout;
1208
- const deadline = new Promise((_resolve, reject) => {
1209
- timeout = setTimeout(() => reject(new Error(`Provider stream cleanup exceeded ${timeoutMs} ms`)), timeoutMs);
1210
- });
1211
- try {
1212
- await Promise.race([operation, deadline]);
1213
- } finally {
1214
- if (timeout !== undefined)
1215
- clearTimeout(timeout);
1216
- }
1217
- }
1218
- async function* ownedProviderStream(input) {
1219
- const iterator = input.stream[Symbol.asyncIterator]();
1220
- let completed = false;
1221
- try {
1222
- for (;; ) {
1223
- const next = await iterator.next();
1224
- if (next.done) {
1225
- completed = true;
1226
- return;
1227
- }
1228
- yield next.value;
1229
- }
1230
- } finally {
1231
- if (!completed) {
1232
- input.abort();
1233
- const cleanup = iterator.return?.();
1234
- if (cleanup) {
1235
- try {
1236
- await settleCleanup(cleanup, input.cleanupTimeoutMs ?? DEFAULT_CLEANUP_TIMEOUT_MS);
1237
- } catch (error) {
1238
- input.onCleanupFailure(error);
1239
- }
1240
- }
1241
- }
1242
- }
1243
- }
1244
-
1245
- // src/agent-runtime/provider-origin.ts
1246
- import {
1247
- InvalidToolApprovalError,
1248
- InvalidToolApprovalSignatureError,
1249
- ToolCallNotFoundForApprovalError
1250
- } from "ai";
1251
- var providerOrigin = new WeakSet;
1252
- function isOwnInputRefusal(error) {
1253
- return InvalidToolApprovalSignatureError.isInstance(error) || InvalidToolApprovalError.isInstance(error) || ToolCallNotFoundForApprovalError.isInstance(error);
1254
- }
1255
- function markProviderOrigin(error) {
1256
- if (typeof error === "object" && error !== null)
1257
- providerOrigin.add(error);
1258
- return error;
1259
- }
1260
- function hasProviderOrigin(error) {
1261
- return typeof error === "object" && error !== null && providerOrigin.has(error);
1262
- }
1263
-
1264
- // src/agent-runtime/run-mutation-queue.ts
1265
- function createRunMutationQueue() {
1266
- let tail = Promise.resolve();
1267
- return (mutation) => {
1268
- const result = tail.then(mutation, mutation);
1269
- tail = result.then(() => {
1270
- return;
1271
- }, () => {
1272
- return;
1273
- });
1274
- return result;
1275
- };
1276
- }
1277
-
1278
- // src/agent-runtime/run-operation-lifecycle.ts
1279
- import { wrapLanguageModel } from "ai";
1280
-
1281
- // src/agent-runtime/runtime-internals.ts
1282
- import { z as z3 } from "zod";
1283
- function findRun(runs, runId) {
1284
- const run = runs.find((candidate) => candidate.id === runId);
1285
- if (!run)
1286
- throw new AgentRuntimeConflictError("run lookup");
1287
- return run;
1288
- }
1289
- function jsonValue(value) {
1290
- const parsed = z3.json().safeParse(value);
1291
- return parsed.success ? parsed.data : { message: "Non-JSON tool output omitted" };
1292
- }
1293
- function providerEnvelope(value) {
1294
- const parsed = AgentJsonObjectSchema.safeParse(value);
1295
- if (!parsed.success)
1296
- return;
1297
- return { schemaVersion: 1, provider: "ai-sdk", data: parsed.data };
1298
- }
1299
- function providerResponseIdentity(id, provider) {
1300
- return AgentProviderResponseSchema.parse({
1301
- id,
1302
- ...typeof provider === "string" && provider.length > 0 ? { provider } : {}
1303
- });
1304
- }
1305
- function appendText(parts, text) {
1306
- const previous = parts.at(-1);
1307
- if (previous?.type === "text") {
1308
- const next = AgentMessagePartSchema.parse({ ...previous, text: previous.text + text });
1309
- parts.splice(parts.length - 1, 1, next);
1310
- return;
1311
- }
1312
- parts.push(AgentMessagePartSchema.parse({ type: "text", text }));
1313
- }
1314
- function abortTerminalReason(signal) {
1315
- if (signal.reason === "shutdown")
1316
- return "shutdown";
1317
- if (signal.reason === "timeout")
1318
- return "timeout";
1319
- if (signal.reason === "supersede")
1320
- return "superseded";
1321
- return "interrupted";
1322
- }
1323
- function addUsage(total, step) {
1324
- const sum = (left, right) => {
1325
- if (left?.value === undefined && right?.value === undefined) {
1326
- return { provenance: "unavailable" };
1327
- }
1328
- if (left?.value === undefined)
1329
- return { ...right, provenance: "computed" };
1330
- if (right?.value === undefined)
1331
- return { ...left, provenance: "computed" };
1332
- return { value: left.value + right.value, provenance: "computed" };
1333
- };
1334
- const sumCost = (left, right) => {
1335
- if (left?.value === undefined || right?.value === undefined) {
1336
- return { provenance: "unavailable" };
1337
- }
1338
- if (left.currency !== right.currency)
1339
- return { provenance: "unavailable" };
1340
- return {
1341
- value: left.value + right.value,
1342
- ...left.currency && { currency: left.currency },
1343
- provenance: "computed"
1344
- };
1345
- };
1346
- if (!total)
1347
- return step;
1348
- const cost = sumCost(total.cost, step.cost);
1349
- return {
1350
- inputTokens: sum(total.inputTokens, step.inputTokens),
1351
- outputTokens: sum(total.outputTokens, step.outputTokens),
1352
- reasoningTokens: sum(total.reasoningTokens, step.reasoningTokens),
1353
- cacheReadTokens: sum(total.cacheReadTokens, step.cacheReadTokens),
1354
- cacheWriteTokens: sum(total.cacheWriteTokens, step.cacheWriteTokens),
1355
- ...cost && { cost }
1356
- };
1357
- }
1358
- function mergeModelTotals(sdkTotal, accumulated) {
1359
- const pick = (total, ours) => total?.value !== undefined ? { value: total.value, provenance: "computed" } : ours ?? { provenance: "unavailable" };
1360
- return {
1361
- inputTokens: pick(sdkTotal.inputTokens, accumulated?.inputTokens),
1362
- outputTokens: pick(sdkTotal.outputTokens, accumulated?.outputTokens),
1363
- reasoningTokens: pick(sdkTotal.reasoningTokens, accumulated?.reasoningTokens),
1364
- cacheReadTokens: pick(sdkTotal.cacheReadTokens, accumulated?.cacheReadTokens),
1365
- cacheWriteTokens: pick(sdkTotal.cacheWriteTokens, accumulated?.cacheWriteTokens),
1366
- cost: accumulated?.cost ?? { provenance: "unavailable" }
1367
- };
1368
- }
1369
- function statedUsage(usage) {
1370
- const stated = (value) => value ?? { provenance: "unavailable" };
1371
- if (!usage)
1372
- return unknownUsage();
1373
- return {
1374
- inputTokens: stated(usage.inputTokens),
1375
- outputTokens: stated(usage.outputTokens),
1376
- reasoningTokens: stated(usage.reasoningTokens),
1377
- cacheReadTokens: stated(usage.cacheReadTokens),
1378
- cacheWriteTokens: stated(usage.cacheWriteTokens),
1379
- cost: stated(usage.cost)
1380
- };
1381
- }
1382
- function unknownUsage() {
1383
- const nothing = { provenance: "unavailable" };
1384
- return {
1385
- inputTokens: nothing,
1386
- outputTokens: nothing,
1387
- reasoningTokens: nothing,
1388
- cacheReadTokens: nothing,
1389
- cacheWriteTokens: nothing,
1390
- cost: nothing
1391
- };
1392
- }
1393
- function normalizeSdkUsage(value) {
1394
- const reported = (tokens) => tokens === undefined || !Number.isSafeInteger(tokens) || tokens < 0 ? { provenance: "unavailable" } : { value: tokens, provenance: "provider-reported" };
1395
- return {
1396
- inputTokens: reported(value.inputTokens),
1397
- outputTokens: reported(value.outputTokens),
1398
- reasoningTokens: reported(value.outputTokenDetails.reasoningTokens),
1399
- cacheReadTokens: reported(value.inputTokenDetails.cacheReadTokens),
1400
- cacheWriteTokens: reported(value.inputTokenDetails.cacheWriteTokens)
1401
- };
1402
- }
1403
- function createIdleDeadline(parent, timeoutMs) {
1404
- if (timeoutMs === undefined) {
1405
- const noop = () => {
1406
- return;
1407
- };
1408
- return {
1409
- signal: parent,
1410
- touch: noop,
1411
- start: noop,
1412
- stop: noop,
1413
- suspend: noop,
1414
- resume: noop,
1415
- dispose: noop
1416
- };
1417
- }
1418
- const controller = new AbortController;
1419
- let timer;
1420
- let active = false;
1421
- let suspended = 0;
1422
- const clear = () => {
1423
- if (timer !== undefined)
1424
- clearTimeout(timer);
1425
- timer = undefined;
1426
- };
1427
- const touch = () => {
1428
- clear();
1429
- if (!active || suspended > 0 || controller.signal.aborted)
1430
- return;
1431
- timer = setTimeout(() => controller.abort("timeout"), timeoutMs);
1432
- };
1433
- return {
1434
- signal: AbortSignal.any([parent, controller.signal]),
1435
- touch,
1436
- start() {
1437
- active = true;
1438
- touch();
1439
- },
1440
- stop() {
1441
- active = false;
1442
- clear();
1443
- },
1444
- suspend() {
1445
- suspended += 1;
1446
- clear();
1447
- },
1448
- resume() {
1449
- suspended = Math.max(0, suspended - 1);
1450
- touch();
1451
- },
1452
- dispose() {
1453
- active = false;
1454
- clear();
1455
- }
1456
- };
1457
- }
1458
-
1459
- // src/agent-runtime/run-operation-lifecycle.ts
1460
- function createAgentRunOperationLifecycle(config) {
1461
- let active;
1462
- let providerCallId;
1463
- let checkpointedStep = -1;
1464
- const checkpointWaiters = new Map;
1465
- const record = (operation) => config.serialize(async () => {
1466
- const current = config.currentRun();
1467
- const snapshot = appliedSnapshot(await config.store.recordRunOperation({
1468
- conversationId: current.conversationId,
1469
- runId: current.id,
1470
- expectedRevision: current.revision,
1471
- ownerId: config.runtimeEpoch,
1472
- ...current.fencingToken !== undefined && { fencingToken: current.fencingToken },
1473
- operation
1474
- }), "run operation");
1475
- config.acceptSnapshot(snapshot);
1476
- const run = findRun(snapshot.runs, current.id);
1477
- active = operation;
1478
- await config.publish({
1479
- type: "run-operation",
1480
- eventId: agentDurableEventId("run-operation", run.id, snapshot.version),
1481
- conversationId: run.conversationId,
1482
- runId: run.id,
1483
- snapshotVersion: snapshot.version,
1484
- operation,
1485
- emittedAt: config.now().toISOString()
1486
- });
1487
- });
1488
- const startModelRequest = async (callId, step) => {
1489
- await record(AgentRunOperationSchema.parse({
1490
- operationId: `${callId}:${step}`,
1491
- kind: "model-request",
1492
- phase: "started",
1493
- step,
1494
- startedAt: config.now().toISOString()
1495
- }));
1496
- };
1497
- return {
1498
- noteProviderCall(callId) {
1499
- providerCallId = callId;
1500
- },
1501
- async prepareModel(model, step, fallbackCallId) {
1502
- if (step > checkpointedStep + 1) {
1503
- const waiter = checkpointWaiters.get(step - 1) ?? Promise.withResolvers();
1504
- checkpointWaiters.set(step - 1, waiter);
1505
- await waiter.promise;
1506
- }
1507
- if (typeof model === "string") {
1508
- await startModelRequest(fallbackCallId, step);
1509
- return model;
1510
- }
1511
- return wrapLanguageModel({
1512
- model,
1513
- middleware: {
1514
- specificationVersion: "v4",
1515
- wrapStream: async ({ doStream }) => {
1516
- const callId = providerCallId;
1517
- providerCallId = undefined;
1518
- if (!callId) {
1519
- throw new Error("AgentRuntime model call reached the provider without lifecycle identity");
1520
- }
1521
- await startModelRequest(callId, step);
1522
- try {
1523
- return await doStream();
1524
- } catch (error) {
1525
- throw isOwnInputRefusal(error) ? error : markProviderOrigin(error);
1526
- }
1527
- }
1528
- }
1529
- });
1530
- },
1531
- checkpointStep(step) {
1532
- checkpointedStep = Math.max(checkpointedStep, step);
1533
- for (const [waitingFor, waiter] of checkpointWaiters) {
1534
- if (waitingFor > checkpointedStep)
1535
- continue;
1536
- checkpointWaiters.delete(waitingFor);
1537
- waiter.resolve();
1538
- }
1539
- },
1540
- failStepCheckpoints(error) {
1541
- for (const waiter of checkpointWaiters.values())
1542
- waiter.reject(error);
1543
- checkpointWaiters.clear();
1544
- },
1545
- startCompaction(operationId) {
1546
- return record(AgentRunOperationSchema.parse({
1547
- operationId,
1548
- kind: "compaction",
1549
- phase: "started",
1550
- startedAt: config.now().toISOString()
1551
- }));
1552
- },
1553
- firstOutput() {
1554
- if (active?.kind !== "model-request" || active.phase !== "started") {
1555
- return Promise.resolve();
1556
- }
1557
- return record(AgentRunOperationSchema.parse({
1558
- ...active,
1559
- phase: "first-output",
1560
- firstOutputAt: config.now().toISOString()
1561
- }));
1562
- },
1563
- finish(phase) {
1564
- if (!active || ["completed", "failed", "cancelled"].includes(active.phase)) {
1565
- return Promise.resolve();
1566
- }
1567
- return record(AgentRunOperationSchema.parse({
1568
- ...active,
1569
- phase,
1570
- finishedAt: config.now().toISOString()
1571
- }));
1572
- }
1573
- };
1574
- }
1575
-
1576
- // src/agent-runtime/run-execution.ts
1577
- function snapshotForRunPrompt(snapshot, runId) {
1578
- const runIndex = snapshot.runs.findIndex((candidate) => candidate.id === runId);
1579
- if (runIndex < 0)
1580
- throw new AgentRuntimeConflictError("prompt run lookup");
1581
- const ownedIds = new Set(snapshot.runs.flatMap((candidate) => [
1582
- ...candidate.inputMessageIds,
1583
- candidate.assistantMessageId
1584
- ]));
1585
- const eligibleIds = new Set(snapshot.runs.slice(0, runIndex + 1).flatMap((candidate) => [...candidate.inputMessageIds, candidate.assistantMessageId]));
1586
- return AgentSnapshotSchema.parse({
1587
- ...snapshot,
1588
- messages: snapshot.messages.filter((message) => !ownedIds.has(message.id) || eligibleIds.has(message.id))
1589
- });
1590
- }
1591
- var USER_INSTRUCTION_SEED_KEY = "prompt.user-instructions";
1592
- function seededInstructionMessage(input) {
1593
- return AgentMessageSchema.parse({
1594
- schemaVersion: 1,
1595
- id: createHash("sha256").update(`${input.conversationId}\x00${input.seedKey}\x00${input.index}`).digest("hex"),
1596
- conversationId: input.conversationId,
1597
- role: "user",
1598
- status: "committed",
1599
- parts: [{ type: "text", text: input.text }],
1600
- createdAt: input.createdAt,
1601
- updatedAt: input.createdAt
1602
- });
1603
- }
1604
- function failureThisRuntimeOwns(error) {
1605
- if (error instanceof AgentContextOverflowError)
1606
- return "context_overflow";
1607
- if (error instanceof AgentRuntimeConflictError)
1608
- return "storage_conflict";
1609
- if (isOwnInputRefusal(error))
1610
- return "runtime_failure";
1611
- return;
1612
- }
1613
- function withoutBinaryParts(message) {
1614
- const reference = (value) => {
1615
- if (value instanceof Uint8Array || value instanceof ArrayBuffer) {
1616
- const bytes = value instanceof ArrayBuffer ? new Uint8Array(value) : value;
1617
- return {
1618
- binary: true,
1619
- sha256: createHash("sha256").update(bytes).digest("hex"),
1620
- bytes: bytes.byteLength
1621
- };
1622
- }
1623
- if (value instanceof URL)
1624
- return value.toString();
1625
- if (Array.isArray(value))
1626
- return value.map(reference);
1627
- if (value && typeof value === "object") {
1628
- return Object.fromEntries(Object.entries(value).map(([key, entry]) => [
1629
- key,
1630
- reference(entry)
1631
- ]));
1632
- }
1633
- return value;
1634
- };
1635
- return reference(message);
1636
- }
1637
- function createRunExecutor(dependencies) {
1638
- const {
1639
- config,
1640
- publish,
1641
- runtimeEpoch,
1642
- generateId,
1643
- now,
1644
- checkpointEveryEvents,
1645
- maxSteps,
1646
- idleTimeoutMs,
1647
- injection
1648
- } = dependencies;
1649
- return async function executeRun(input) {
1650
- injection?.withdraw(input.key, input.acceptedRun.id);
1651
- const queued = await config.store.loadRun({
1652
- conversationId: input.acceptedRun.conversationId,
1653
- runId: input.acceptedRun.id
1654
- });
1655
- if (!queued)
1656
- throw new AgentRuntimeConflictError("run lookup");
1657
- if (queued.run.terminalReason === "absorbed") {
1658
- const absorbing = queued.run.absorbedIntoRunId ? await config.store.loadRun({
1659
- conversationId: queued.run.conversationId,
1660
- runId: queued.run.absorbedIntoRunId
1661
- }) : undefined;
1662
- if (!absorbing?.assistant || !absorbing.run.terminalReason) {
1663
- throw new AgentRuntimeConflictError("absorbed run resolution");
1664
- }
1665
- input.onAcquired?.();
1666
- return {
1667
- run: absorbing.run,
1668
- message: absorbing.assistant,
1669
- reason: absorbing.run.terminalReason,
1670
- snapshotVersion: absorbing.snapshotVersion,
1671
- ...absorbing.run.terminalPolicyName && {
1672
- policyName: absorbing.run.terminalPolicyName
1673
- }
1674
- };
1675
- }
1676
- const queuedRun = queued.run;
1677
- const acquired = appliedSnapshot(await config.store.acquireRun({
1678
- conversationId: queuedRun.conversationId,
1679
- runId: queuedRun.id,
1680
- expectedRevision: queuedRun.revision,
1681
- ownerId: runtimeEpoch
1682
- }), "run acquisition");
1683
- let run = findRun(acquired.runs, input.acceptedRun.id);
1684
- input.onAcquired?.();
1685
- await publish({
1686
- type: "run-state",
1687
- eventId: agentDurableEventId("run-state", run.id, acquired.version),
1688
- conversationId: run.conversationId,
1689
- runId: run.id,
1690
- snapshotVersion: acquired.version,
1691
- state: run.state,
1692
- emittedAt: now().toISOString()
1693
- });
1694
- const trace = config.observe?.rootTrace();
1695
- const runStartedAt = performance.now();
1696
- config.observe?.emit({
1697
- schemaVersion: 1,
1698
- eventId: generateId(),
1699
- type: "run-started",
1700
- conversationId: run.conversationId,
1701
- runId: run.id,
1702
- traceId: trace?.traceId ?? generateId(),
1703
- spanId: trace?.spanId ?? generateId(),
1704
- ...trace?.parentSpanId && { parentSpanId: trace.parentSpanId },
1705
- state: run.state,
1706
- queueWaitMs: Math.max(0, now().getTime() - new Date(run.createdAt).getTime()),
1707
- emittedAt: now().toISOString()
1708
- });
1709
- let assistant = AgentMessageSchema.parse({
1710
- schemaVersion: 1,
1711
- id: run.assistantMessageId,
1712
- conversationId: run.conversationId,
1713
- runId: run.id,
1714
- role: "assistant",
1715
- status: "streaming",
1716
- parts: [],
1717
- createdAt: now().toISOString(),
1718
- updatedAt: now().toISOString()
1719
- });
1720
- let snapshot = appliedSnapshot(await config.store.checkpointRunAssistant({
1721
- conversationId: run.conversationId,
1722
- runId: run.id,
1723
- expectedRevision: run.revision,
1724
- ownerId: runtimeEpoch,
1725
- ...run.fencingToken !== undefined && { fencingToken: run.fencingToken },
1726
- assistant
1727
- }), "assistant draft");
1728
- run = findRun(snapshot.runs, run.id);
1729
- let observedVersion = snapshot.version;
1730
- const parts = [];
1731
- const absorbed = new Map;
1732
- let eventsSinceCheckpoint = 0;
1733
- let sequence = 0;
1734
- const transientSequence = () => {
1735
- sequence += 1;
1736
- return sequence;
1737
- };
1738
- let terminalReason = "success";
1739
- let nonModelUsage = input.acceptedRun.usage;
1740
- let modelUsage;
1741
- let abandonedUsage;
1742
- const billedUsage = () => abandonedUsage && modelUsage ? addUsage(abandonedUsage, modelUsage) : abandonedUsage ?? modelUsage;
1743
- let usage = nonModelUsage;
1744
- let sawProviderFinish = false;
1745
- let step = 0;
1746
- let selectedModel;
1747
- let internalCause;
1748
- let providerStreamCleanupFailure;
1749
- let reasoningPartIndex;
1750
- let firstOutputAt;
1751
- let terminalPolicyName;
1752
- const idleDeadline = createIdleDeadline(input.signal, idleTimeoutMs);
1753
- const executionSignal = idleDeadline.signal;
1754
- const serialize = createRunMutationQueue();
1755
- const operationLifecycle = createAgentRunOperationLifecycle({
1756
- store: config.store,
1757
- runtimeEpoch,
1758
- serialize,
1759
- currentRun: () => run,
1760
- acceptSnapshot: (next) => {
1761
- snapshot = next;
1762
- observedVersion = next.version;
1763
- run = findRun(next.runs, run.id);
1764
- },
1765
- publish,
1766
- now
1767
- });
1768
- const updateReasoning = (text, metadata) => {
1769
- const provider = providerEnvelope(metadata);
1770
- if (reasoningPartIndex === undefined) {
1771
- reasoningPartIndex = parts.length;
1772
- parts.push(AgentMessagePartSchema.parse({
1773
- type: "reasoning",
1774
- text,
1775
- ...provider && { provider }
1776
- }));
1777
- return;
1778
- }
1779
- const current = parts[reasoningPartIndex];
1780
- if (current?.type !== "reasoning") {
1781
- throw new AgentRuntimeConflictError("reasoning accumulator");
1782
- }
1783
- parts.splice(reasoningPartIndex, 1, AgentMessagePartSchema.parse({
1784
- ...current,
1785
- text: current.text + text,
1786
- ...provider && { provider }
1787
- }));
1788
- };
1789
- const checkpoint = () => serialize(async () => {
1790
- assistant = AgentMessageSchema.parse({
1791
- ...assistant,
1792
- parts,
1793
- updatedAt: now().toISOString()
1794
- });
1795
- snapshot = appliedSnapshot(await config.store.checkpointRunAssistant({
1796
- conversationId: run.conversationId,
1797
- runId: run.id,
1798
- expectedRevision: run.revision,
1799
- ownerId: runtimeEpoch,
1800
- ...run.fencingToken !== undefined && { fencingToken: run.fencingToken },
1801
- assistant,
1802
- usage: statedUsage(usage)
1803
- }), "assistant checkpoint");
1804
- observedVersion = snapshot.version;
1805
- run = findRun(snapshot.runs, run.id);
1806
- const checkpointMetrics = {
1807
- partial: true,
1808
- durationMs: performance.now() - runStartedAt,
1809
- usage: statedUsage(usage),
1810
- ...firstOutputAt !== undefined && { ttftMs: firstOutputAt - runStartedAt }
1811
- };
1812
- await publish({
1813
- type: "assistant-checkpoint",
1814
- eventId: agentDurableEventId("assistant-checkpoint", run.id, observedVersion),
1815
- conversationId: run.conversationId,
1816
- runId: run.id,
1817
- snapshotVersion: observedVersion,
1818
- message: assistant,
1819
- metrics: checkpointMetrics,
1820
- emittedAt: now().toISOString()
1821
- });
1822
- });
1823
- try {
1824
- if (config.history?.compact) {
1825
- await operationLifecycle.startCompaction(generateId());
1826
- let compacted;
1827
- try {
1828
- compacted = await config.history.compact({
1829
- conversationId: run.conversationId,
1830
- store: config.store,
1831
- signal: executionSignal
1832
- });
1833
- snapshot = compacted.snapshot;
1834
- observedVersion = snapshot.version;
1835
- run = findRun(snapshot.runs, run.id);
1836
- await operationLifecycle.finish("completed");
1837
- } catch (error) {
1838
- const latest = await config.store.loadRun({
1839
- conversationId: run.conversationId,
1840
- runId: run.id
1841
- });
1842
- if (latest?.run.ownerId === runtimeEpoch) {
1843
- observedVersion = latest.snapshotVersion;
1844
- run = latest.run;
1845
- }
1846
- await operationLifecycle.finish(executionSignal.aborted ? "cancelled" : "failed");
1847
- throw error;
1848
- }
1849
- if (compacted.usage) {
1850
- nonModelUsage = addUsage(nonModelUsage, compacted.usage);
1851
- const billed = billedUsage();
1852
- usage = billed ? addUsage(nonModelUsage, billed) : nonModelUsage;
1853
- }
1854
- }
1855
- const assertCurrent = async () => {
1856
- if (executionSignal.aborted)
1857
- return "run_interrupted";
1858
- const current = await config.store.loadRun({
1859
- conversationId: run.conversationId,
1860
- runId: run.id
1861
- });
1862
- const currentRun = current?.run;
1863
- if (!currentRun || currentRun.ownerId !== runtimeEpoch)
1864
- return "stale_run";
1865
- if (currentRun.fencingToken !== run.fencingToken)
1866
- return "stale_run";
1867
- if (currentRun.state === "interrupt_requested")
1868
- return "run_interrupted";
1869
- if (currentRun.state !== "running")
1870
- return "stale_run";
1871
- return;
1872
- };
1873
- const toolFenceLifecycle = createAgentToolFenceLifecycle({
1874
- runId: run.id,
1875
- assertCurrent,
1876
- context: () => ({
1877
- ...run.fencingToken !== undefined && { fencingToken: run.fencingToken }
1878
- })
1879
- });
1880
- let lastPromptTokens = { provenance: "unavailable" };
1881
- const runtimeContext = {
1882
- context: input.context,
1883
- run,
1884
- signal: executionSignal,
1885
- toolFenceLifecycle,
1886
- get contextUsage() {
1887
- const descriptor = selectedModel?.descriptor;
1888
- if (!descriptor)
1889
- return;
1890
- return { usedTokens: lastPromptTokens, contextWindow: descriptor.contextWindow };
1891
- }
1892
- };
1893
- selectedModel = await config.models.resolve({
1894
- context: input.context,
1895
- conversationId: run.conversationId,
1896
- run,
1897
- snapshot
1898
- });
1899
- let promptSnapshot = snapshotForRunPrompt(snapshot, run.id);
1900
- const [composedPrompt, tools] = await Promise.all([
1901
- config.prompt({
1902
- context: input.context,
1903
- signal: executionSignal,
1904
- event: promptSnapshot.runs[0]?.id === run.id ? "session.started" : "turn.started",
1905
- model: selectedModel,
1906
- snapshot: promptSnapshot
1907
- }),
1908
- config.tools(runtimeContext)
1909
- ]);
1910
- let prompt = composedPrompt;
1911
- let userInstructionsInserted = false;
1912
- if (prompt.userInstructions && prompt.userInstructions.length > 0) {
1913
- const seededAt = now().toISOString();
1914
- const seeded = await config.store.seedConversationInput({
1915
- conversationId: run.conversationId,
1916
- seedKey: USER_INSTRUCTION_SEED_KEY,
1917
- inputs: prompt.userInstructions.map((section, index) => seededInstructionMessage({
1918
- conversationId: run.conversationId,
1919
- seedKey: USER_INSTRUCTION_SEED_KEY,
1920
- index,
1921
- text: section.text,
1922
- createdAt: seededAt
1923
- }))
1924
- });
1925
- const seededSnapshot = appliedSnapshot(seeded, "user instruction seed");
1926
- const previousIds = new Set(snapshot.messages.map((message) => message.id));
1927
- userInstructionsInserted = seededSnapshot.messages.some((message) => !previousIds.has(message.id) && message.role === "user" && message.runId === undefined);
1928
- snapshot = seededSnapshot;
1929
- observedVersion = snapshot.version;
1930
- run = findRun(snapshot.runs, run.id);
1931
- promptSnapshot = snapshotForRunPrompt(snapshot, run.id);
1932
- }
1933
- if (prompt.finalizeSeed)
1934
- prompt = { ...prompt, ...prompt.finalizeSeed(userInstructionsInserted) };
1935
- if (prompt.contextDecision === "oversized") {
1936
- throw new AgentContextOverflowError;
1937
- }
1938
- if (prompt.contextDecision === "requires-compaction") {
1939
- throw new AgentContextOverflowError("Agent context still exceeds the model budget after compaction");
1940
- }
1941
- let carriedSystem = [];
1942
- let durableSystem = [];
1943
- if (config.stateSlots && config.stateSlots.length > 0) {
1944
- const slotValues = await createAgentStateSlotStore({
1945
- store: config.store,
1946
- definitions: config.stateSlots
1947
- }).list(run.conversationId);
1948
- const renderedSlots = renderAgentStateSlots(slotValues);
1949
- if (renderedSlots) {
1950
- durableSystem = [renderedSlots];
1951
- carriedSystem = durableSystem;
1952
- }
1953
- }
1954
- const projectHistory = async (source) => {
1955
- if (config.history?.project)
1956
- return config.history.project(source.messages);
1957
- const detailed = await projectAgentHistoryDetailed(source.messages, {
1958
- ...config.history?.resolveFile && { resolveFile: config.history.resolveFile },
1959
- ...config.history?.unresolvedFile && {
1960
- unresolvedFile: config.history.unresolvedFile
1961
- },
1962
- ...config.history?.interruptedAssistant && {
1963
- interruptedAssistant: config.history.interruptedAssistant
1964
- },
1965
- ...config.history?.evidencePolicy && {
1966
- evidencePolicy: config.history.evidencePolicy
1967
- }
1968
- });
1969
- for (const decision of detailed.decisions) {
1970
- if (decision.action === "omitted" && run.inputMessageIds.includes(decision.messageId) && source.messages.some((message) => message.id === decision.messageId && message.role === "tool")) {
1971
- throw new Error(`Invalid approval continuation ${decision.messageId}: ${decision.reason}`);
1972
- }
1973
- }
1974
- carriedSystem = [...durableSystem, ...detailed.system];
1975
- return [...detailed.messages];
1976
- };
1977
- const projectInputs = async (source) => {
1978
- if (config.history?.project)
1979
- return config.history.project(source);
1980
- const detailed = await projectAgentHistoryDetailed(source, {
1981
- ...config.history?.resolveFile && { resolveFile: config.history.resolveFile },
1982
- ...config.history?.unresolvedFile && {
1983
- unresolvedFile: config.history.unresolvedFile
1984
- },
1985
- ...config.history?.interruptedAssistant && {
1986
- interruptedAssistant: config.history.interruptedAssistant
1987
- },
1988
- ...config.history?.evidencePolicy && {
1989
- evidencePolicy: config.history.evidencePolicy
1990
- }
1991
- });
1992
- return [...detailed.messages];
1993
- };
1994
- const projectedHistory = await projectHistory(promptSnapshot);
1995
- const history = [...projectedHistory];
1996
- const withCarriedSystem = (instructions) => {
1997
- if (carriedSystem.length === 0)
1998
- return instructions;
1999
- const composed = typeof instructions === "string" ? [{ role: "system", content: instructions }] : Array.isArray(instructions) ? instructions : [instructions];
2000
- return [
2001
- ...composed,
2002
- ...carriedSystem.map((content) => ({ role: "system", content }))
2003
- ];
2004
- };
2005
- const maxStepCondition = stepCountIs(maxSteps);
2006
- const stopConditions = [
2007
- async (options) => {
2008
- const stopped = await maxStepCondition(options);
2009
- if (stopped && terminalPolicyName === undefined)
2010
- terminalPolicyName = "max-steps";
2011
- return stopped;
2012
- }
2013
- ];
2014
- for (const policy of config.loop?.stopPolicies ?? []) {
2015
- stopConditions.push(async (options) => {
2016
- const stopped = await policy.when(options);
2017
- if (stopped && terminalPolicyName === undefined)
2018
- terminalPolicyName = policy.name;
2019
- return stopped;
2020
- });
2021
- }
2022
- let takenThisAttempt = [];
2023
- const takeInjectedMessages = async () => {
2024
- const taken = injection?.take(input.key, run.id) ?? [];
2025
- if (taken.length === 0)
2026
- return [];
2027
- takenThisAttempt.push(...taken);
2028
- const messages = [];
2029
- for (const entry of taken) {
2030
- messages.push(...await projectInputs([entry.input]));
2031
- const ids = absorbed.get(entry.runId) ?? [];
2032
- ids.push(entry.input.id);
2033
- absorbed.set(entry.runId, ids);
2034
- }
2035
- return messages;
2036
- };
2037
- const fallbackModel = selectedModel.model;
2038
- const requestModelId = selectedModel.descriptor.modelId;
2039
- let retryAttempt = 1;
2040
- let instructionsOverride;
2041
- const knownMessageShas = new Set;
2042
- {
2043
- let fromSeq;
2044
- do {
2045
- const page = await config.store.readEvents({
2046
- conversationId: run.conversationId,
2047
- ...fromSeq && { fromSeq },
2048
- limit: 1e4
2049
- });
2050
- for (const event of page.items) {
2051
- if (event.kind !== "provider/message")
2052
- continue;
2053
- const sha = event.payload?.sha256;
2054
- if (typeof sha === "string")
2055
- knownMessageShas.add(sha);
2056
- }
2057
- fromSeq = page.nextSeq;
2058
- } while (fromSeq !== undefined);
2059
- }
2060
- const recordProviderRequest = async (request) => {
2061
- const messageShas = [];
2062
- for (const message of request.messages) {
2063
- const body = canonicalAgentJson(JSON.parse(JSON.stringify(withoutBinaryParts(message))));
2064
- const sha256 = createHash("sha256").update(body).digest("hex");
2065
- messageShas.push(sha256);
2066
- if (knownMessageShas.has(sha256))
2067
- continue;
2068
- await config.store.appendEvent({
2069
- conversationId: run.conversationId,
2070
- kind: "provider/message",
2071
- payload: { sha256, message: JSON.parse(body) }
2072
- });
2073
- knownMessageShas.add(sha256);
2074
- }
2075
- const instructionsSha256 = createHash("sha256").update(typeof request.instructions === "string" ? request.instructions : canonicalAgentJson(JSON.parse(JSON.stringify(withoutBinaryParts(request.instructions))))).digest("hex");
2076
- const bodySha256 = createHash("sha256").update(instructionsSha256).update(messageShas.join(",")).digest("hex");
2077
- await config.store.appendEvent({
2078
- conversationId: run.conversationId,
2079
- kind: "provider/request",
2080
- payload: {
2081
- runId: run.id,
2082
- attempt: request.attempt,
2083
- stepNumber: request.stepNumber,
2084
- modelId: requestModelId,
2085
- instructionsSha256,
2086
- messageShas,
2087
- bodySha256
2088
- }
2089
- });
2090
- };
2091
- const recordProviderResponse = async (response) => {
2092
- const identity = providerResponseIdentity(response.id, selectedModel?.resolveResponseProvider?.({
2093
- providerMetadata: response.providerMetadata
2094
- }));
2095
- await config.store.appendEvent({
2096
- conversationId: run.conversationId,
2097
- kind: "provider/response",
2098
- payload: {
2099
- runId: run.id,
2100
- attempt: response.attempt,
2101
- stepNumber: response.stepNumber,
2102
- response: identity
2103
- }
2104
- });
2105
- return identity;
2106
- };
2107
- for (;; ) {
2108
- const attemptPartStart = parts.length;
2109
- let retrying = false;
2110
- let draining = false;
2111
- const providerAttempt = retryAttempt;
2112
- const attemptAbort = new AbortController;
2113
- const attemptSignal = AbortSignal.any([executionSignal, attemptAbort.signal]);
2114
- const result = streamAgentTextBoundary({
2115
- model: fallbackModel,
2116
- tools,
2117
- ...config.durability && {
2118
- toolsContext: Object.fromEntries(Object.keys(tools).map((toolName) => [
2119
- toolName,
2120
- createToolDurabilityContext((toolCallId, signal) => {
2121
- const port = config.durability;
2122
- if (typeof port === "function")
2123
- return port({
2124
- store: config.store,
2125
- conversationId: run.conversationId,
2126
- runId: run.id,
2127
- toolName,
2128
- toolCallId,
2129
- signal
2130
- });
2131
- return createLocalStepDurability({
2132
- store: config.store,
2133
- conversationId: run.conversationId,
2134
- runId: JSON.stringify([run.id, toolName, toolCallId]),
2135
- signal
2136
- });
2137
- })
2138
- ]))
2139
- },
2140
- instructions: withCarriedSystem(prompt.instructions),
2141
- messages: history,
2142
- abortSignal: attemptSignal,
2143
- maxRetries: 0,
2144
- stopWhen: stopConditions,
2145
- onLanguageModelCallStart: (event) => {
2146
- idleDeadline.start();
2147
- operationLifecycle.noteProviderCall(event.callId);
2148
- },
2149
- onLanguageModelCallEnd: () => idleDeadline.stop(),
2150
- onToolExecutionStart: () => idleDeadline.suspend(),
2151
- onToolExecutionEnd: () => idleDeadline.resume(),
2152
- repairToolCall: deferredToolRepair(config.loop?.prepareStep),
2153
- ...config.loop?.toolApproval && {
2154
- toolApproval: config.loop.toolApproval,
2155
- runtimeContext: input.context
2156
- },
2157
- ...config.loop?.toolApprovalSecret && {
2158
- experimental_toolApprovalSecret: config.loop.toolApprovalSecret
2159
- },
2160
- prepareStep: async (options) => {
2161
- const previousStep = options.steps.at(-1);
2162
- if (previousStep) {
2163
- lastPromptTokens = selectedModel?.normalizeUsage?.({
2164
- usage: previousStep.usage,
2165
- providerMetadata: previousStep.providerMetadata
2166
- })?.inputTokens ?? normalizeSdkUsage(previousStep.usage).inputTokens;
2167
- }
2168
- const prepared = await config.loop?.prepareStep?.({
2169
- ...options,
2170
- ...runtimeContext
2171
- });
2172
- const injected = await takeInjectedMessages();
2173
- const preparedStep = injected.length === 0 ? prepared : {
2174
- ...prepared,
2175
- messages: [...prepared?.messages ?? options.messages, ...injected]
2176
- };
2177
- const providerMessages = preparedStep?.messages ?? options.messages;
2178
- const model = await operationLifecycle.prepareModel(preparedStep?.model ?? fallbackModel, options.stepNumber, generateId());
2179
- const override = preparedStep;
2180
- if (override?.instructions !== undefined)
2181
- instructionsOverride = override.instructions;
2182
- else if (override?.system !== undefined)
2183
- instructionsOverride = override.system;
2184
- await recordProviderRequest({
2185
- stepNumber: options.stepNumber,
2186
- attempt: providerAttempt,
2187
- instructions: instructionsOverride ?? withCarriedSystem(prompt.instructions),
2188
- messages: providerMessages
2189
- });
2190
- return { ...preparedStep, model };
2191
- }
2192
- });
2193
- for await (const part of ownedProviderStream({
2194
- stream: result.stream,
2195
- abort: () => attemptAbort.abort(new Error("Agent runtime released provider stream")),
2196
- onCleanupFailure: (error) => {
2197
- providerStreamCleanupFailure = error;
2198
- }
2199
- })) {
2200
- idleDeadline.touch();
2201
- if (draining) {
2202
- if (part.type === "finish-step") {
2203
- await recordProviderResponse({
2204
- id: part.response.id,
2205
- providerMetadata: part.providerMetadata,
2206
- stepNumber: step,
2207
- attempt: providerAttempt
2208
- });
2209
- const failedStepUsage = selectedModel.normalizeUsage?.({
2210
- usage: part.usage,
2211
- providerMetadata: part.providerMetadata
2212
- }) ?? normalizeSdkUsage(part.usage);
2213
- abandonedUsage = abandonedUsage ? addUsage(abandonedUsage, failedStepUsage) : failedStepUsage;
2214
- const billed = billedUsage();
2215
- usage = nonModelUsage && billed ? addUsage(nonModelUsage, billed) : billed ?? nonModelUsage;
2216
- }
2217
- continue;
2218
- }
2219
- eventsSinceCheckpoint += 1;
2220
- if (part.type === "error" && config.loop?.retry && failureThisRuntimeOwns(part.error) === undefined) {
2221
- const invokedTool = parts.slice(attemptPartStart).some((candidate) => candidate.type === "tool-call");
2222
- const decision = invokedTool ? { retry: false, delayMs: 0 } : await recordAgentRetryDecision({
2223
- store: config.store,
2224
- conversationId: run.conversationId,
2225
- attempt: retryAttempt,
2226
- failure: classifyProviderFailure(part.error),
2227
- policy: config.loop.retry
2228
- });
2229
- if (decision.retry) {
2230
- await operationLifecycle.finish("failed");
2231
- parts.splice(attemptPartStart);
2232
- for (const entry of takenThisAttempt) {
2233
- injection?.offer(input.key, entry);
2234
- const ids = absorbed.get(entry.runId);
2235
- if (ids) {
2236
- const kept = ids.filter((id) => id !== entry.input.id);
2237
- if (kept.length === 0)
2238
- absorbed.delete(entry.runId);
2239
- else
2240
- absorbed.set(entry.runId, kept);
2241
- }
2242
- }
2243
- takenThisAttempt = [];
2244
- await checkpoint();
2245
- eventsSinceCheckpoint = 0;
2246
- if (decision.delayMs > 0) {
2247
- await delay(decision.delayMs, undefined, { signal: executionSignal });
2248
- }
2249
- retryAttempt += 1;
2250
- await config.store.appendEvent({
2251
- conversationId: run.conversationId,
2252
- kind: "retry/started",
2253
- payload: { attempt: retryAttempt }
2254
- });
2255
- retrying = true;
2256
- draining = true;
2257
- continue;
2258
- }
2259
- }
2260
- if (firstOutputAt === undefined && (part.type === "text-delta" && part.text.length > 0 || part.type === "reasoning-delta" && part.text.length > 0 || part.type === "tool-input-delta" && part.delta.length > 0 || part.type === "tool-call")) {
2261
- firstOutputAt = performance.now();
2262
- }
2263
- if (part.type === "text-delta" && part.text.length > 0 || part.type === "reasoning-delta" && part.text.length > 0 || part.type === "tool-input-delta" && part.delta.length > 0 || part.type === "tool-call") {
2264
- await operationLifecycle.firstOutput();
2265
- }
2266
- if (part.type === "text-delta") {
2267
- appendText(parts, part.text);
2268
- await publish({
2269
- type: "assistant-delta",
2270
- conversationId: run.conversationId,
2271
- runId: run.id,
2272
- runtimeEpoch,
2273
- sequence: transientSequence(),
2274
- textDelta: part.text,
2275
- emittedAt: now().toISOString()
2276
- });
2277
- } else if (part.type === "reasoning-start") {
2278
- reasoningPartIndex = undefined;
2279
- updateReasoning("", part.providerMetadata);
2280
- const provider = providerEnvelope(part.providerMetadata);
2281
- await publish({
2282
- type: "reasoning-start",
2283
- conversationId: run.conversationId,
2284
- runId: run.id,
2285
- runtimeEpoch,
2286
- sequence: transientSequence(),
2287
- ...provider && { provider },
2288
- emittedAt: now().toISOString()
2289
- });
2290
- } else if (part.type === "reasoning-delta") {
2291
- updateReasoning(part.text, part.providerMetadata);
2292
- const provider = providerEnvelope(part.providerMetadata);
2293
- await publish({
2294
- type: "reasoning-delta",
2295
- conversationId: run.conversationId,
2296
- runId: run.id,
2297
- runtimeEpoch,
2298
- sequence: transientSequence(),
2299
- textDelta: part.text,
2300
- ...provider && { provider },
2301
- emittedAt: now().toISOString()
2302
- });
2303
- } else if (part.type === "reasoning-end") {
2304
- updateReasoning("", part.providerMetadata);
2305
- reasoningPartIndex = undefined;
2306
- const provider = providerEnvelope(part.providerMetadata);
2307
- await publish({
2308
- type: "reasoning-end",
2309
- conversationId: run.conversationId,
2310
- runId: run.id,
2311
- runtimeEpoch,
2312
- sequence: transientSequence(),
2313
- ...provider && { provider },
2314
- emittedAt: now().toISOString()
2315
- });
2316
- } else if (part.type === "tool-call") {
2317
- const provider = providerEnvelope(part.providerMetadata);
2318
- parts.push(AgentMessagePartSchema.parse({
2319
- type: "tool-call",
2320
- callId: part.toolCallId,
2321
- toolName: part.toolName,
2322
- input: jsonValue(part.input),
2323
- ...provider && { provider }
2324
- }));
2325
- await publish({
2326
- type: "tool-status",
2327
- conversationId: run.conversationId,
2328
- runId: run.id,
2329
- runtimeEpoch,
2330
- sequence: transientSequence(),
2331
- callId: part.toolCallId,
2332
- toolName: part.toolName,
2333
- status: "started",
2334
- input: jsonValue(part.input),
2335
- emittedAt: now().toISOString()
2336
- });
2337
- } else if (part.type === "tool-result") {
2338
- parts.push(AgentMessagePartSchema.parse({
2339
- type: "tool-result",
2340
- callId: part.toolCallId,
2341
- toolName: part.toolName,
2342
- outcome: "success",
2343
- output: jsonValue(part.output)
2344
- }));
2345
- await publish({
2346
- type: "tool-status",
2347
- conversationId: run.conversationId,
2348
- runId: run.id,
2349
- runtimeEpoch,
2350
- sequence: transientSequence(),
2351
- callId: part.toolCallId,
2352
- toolName: part.toolName,
2353
- status: "completed",
2354
- output: jsonValue(part.output),
2355
- emittedAt: now().toISOString()
2356
- });
2357
- } else if (part.type === "tool-error") {
2358
- internalCause = part.error;
2359
- if (isToolExecutionControlError(part.error)) {
2360
- await publish({
2361
- type: "tool-status",
2362
- conversationId: run.conversationId,
2363
- runId: run.id,
2364
- runtimeEpoch,
2365
- sequence: transientSequence(),
2366
- callId: part.toolCallId,
2367
- toolName: part.toolName,
2368
- status: "interrupted",
2369
- emittedAt: now().toISOString()
2370
- });
2371
- await checkpoint();
2372
- throw part.error;
2373
- }
2374
- const output = isAgentToolError(part.error) ? jsonValue(part.error.output) : { message: "Tool execution failed" };
2375
- parts.push(AgentMessagePartSchema.parse({
2376
- type: "tool-result",
2377
- callId: part.toolCallId,
2378
- toolName: part.toolName,
2379
- outcome: "error",
2380
- output
2381
- }));
2382
- await publish({
2383
- type: "tool-status",
2384
- conversationId: run.conversationId,
2385
- runId: run.id,
2386
- runtimeEpoch,
2387
- sequence: transientSequence(),
2388
- callId: part.toolCallId,
2389
- toolName: part.toolName,
2390
- status: "failed",
2391
- output,
2392
- emittedAt: now().toISOString()
2393
- });
2394
- } else if (part.type === "tool-output-denied") {
2395
- parts.push(AgentMessagePartSchema.parse({
2396
- type: "tool-result",
2397
- callId: part.toolCallId,
2398
- toolName: part.toolName,
2399
- outcome: "error",
2400
- output: { message: "Tool output denied" }
2401
- }));
2402
- await publish({
2403
- type: "tool-status",
2404
- conversationId: run.conversationId,
2405
- runId: run.id,
2406
- runtimeEpoch,
2407
- sequence: transientSequence(),
2408
- callId: part.toolCallId,
2409
- toolName: part.toolName,
2410
- status: "failed",
2411
- output: { message: "Tool output denied" },
2412
- emittedAt: now().toISOString()
2413
- });
2414
- } else if (part.type === "source") {
2415
- parts.push(AgentMessagePartSchema.parse({
2416
- type: "source",
2417
- sourceId: part.id,
2418
- ...part.sourceType === "url" && { url: part.url },
2419
- ...part.title && { title: part.title }
2420
- }));
2421
- } else if (part.type === "file" && config.persistGeneratedFile) {
2422
- const persisted = await config.persistGeneratedFile(part.file);
2423
- parts.push(AgentMessagePartSchema.parse({
2424
- type: "file",
2425
- mediaType: part.file.mediaType,
2426
- reference: persisted.reference,
2427
- ...persisted.filename && { filename: persisted.filename }
2428
- }));
2429
- } else if (part.type === "file") {
2430
- throw new Error("persistGeneratedFile is required for generated file output");
2431
- } else if (part.type === "reasoning-file" && config.persistGeneratedFile) {
2432
- const persisted = await config.persistGeneratedFile(part.file);
2433
- parts.push(AgentMessagePartSchema.parse({
2434
- type: "file",
2435
- mediaType: part.file.mediaType,
2436
- reference: persisted.reference,
2437
- ...persisted.filename && { filename: persisted.filename }
2438
- }));
2439
- } else if (part.type === "reasoning-file") {
2440
- throw new Error("persistGeneratedFile is required for generated reasoning files");
2441
- } else if (part.type === "tool-approval-request") {
2442
- parts.push(AgentMessagePartSchema.parse({
2443
- type: "tool-approval-request",
2444
- approvalId: part.approvalId,
2445
- callId: part.toolCall.toolCallId,
2446
- ...part.isAutomatic !== undefined && { isAutomatic: part.isAutomatic },
2447
- ...part.signature && { signature: part.signature }
2448
- }));
2449
- } else if (part.type === "tool-approval-response") {
2450
- parts.push(AgentMessagePartSchema.parse({
2451
- type: "tool-approval-response",
2452
- approvalId: part.approvalId,
2453
- approved: part.approved,
2454
- ...part.reason && { reason: part.reason }
2455
- }));
2456
- } else if (part.type === "custom") {
2457
- const provider = providerEnvelope(part.providerMetadata);
2458
- parts.push(AgentMessagePartSchema.parse({
2459
- type: "provider",
2460
- envelope: {
2461
- schemaVersion: 1,
2462
- provider: "ai-sdk-custom",
2463
- data: { kind: part.kind, ...provider && { provider: provider.data } }
2464
- }
2465
- }));
2466
- } else if (part.type === "raw") {
2467
- parts.push(AgentMessagePartSchema.parse({
2468
- type: "provider",
2469
- envelope: {
2470
- schemaVersion: 1,
2471
- provider: "ai-sdk-raw",
2472
- data: { value: jsonValue(part.rawValue) }
2473
- }
2474
- }));
2475
- } else if (part.type === "abort") {
2476
- terminalReason = "interrupted";
2477
- } else if (part.type === "error") {
2478
- terminalReason = failureThisRuntimeOwns(part.error) ?? "provider_failure";
2479
- internalCause = part.error;
2480
- } else if (part.type === "finish-step") {
2481
- const response = await recordProviderResponse({
2482
- id: part.response.id,
2483
- providerMetadata: part.providerMetadata,
2484
- stepNumber: step,
2485
- attempt: providerAttempt
2486
- });
2487
- await operationLifecycle.finish(part.finishReason === "error" ? "failed" : "completed");
2488
- const stepTrace = trace ? config.observe?.rootTrace(trace) : undefined;
2489
- const stepUsage = selectedModel.normalizeUsage?.({
2490
- usage: part.usage,
2491
- providerMetadata: part.providerMetadata
2492
- }) ?? normalizeSdkUsage(part.usage);
2493
- lastPromptTokens = stepUsage.inputTokens;
2494
- modelUsage = addUsage(modelUsage, stepUsage);
2495
- usage = nonModelUsage ? addUsage(nonModelUsage, billedUsage() ?? modelUsage) : billedUsage();
2496
- config.observe?.emit({
2497
- schemaVersion: 1,
2498
- eventId: generateId(),
2499
- type: "step-finished",
2500
- conversationId: run.conversationId,
2501
- runId: run.id,
2502
- traceId: stepTrace?.traceId ?? trace?.traceId ?? generateId(),
2503
- spanId: stepTrace?.spanId ?? generateId(),
2504
- ...stepTrace?.parentSpanId && { parentSpanId: stepTrace.parentSpanId },
2505
- state: run.state,
2506
- modelId: selectedModel.descriptor.modelId,
2507
- step,
2508
- usage: stepUsage,
2509
- response,
2510
- emittedAt: now().toISOString()
2511
- });
2512
- step += 1;
2513
- } else if (part.type === "finish" && part.finishReason !== "stop") {
2514
- if (terminalReason === "success") {
2515
- terminalReason = part.finishReason === "error" ? "provider_failure" : "provider_stop";
2516
- internalCause ??= { finishReason: part.finishReason };
2517
- }
2518
- }
2519
- if (part.type === "finish") {
2520
- sawProviderFinish = true;
2521
- modelUsage = mergeModelTotals(normalizeSdkUsage(part.totalUsage), modelUsage);
2522
- usage = nonModelUsage ? addUsage(nonModelUsage, billedUsage() ?? modelUsage) : billedUsage();
2523
- }
2524
- const structuralBoundary = [
2525
- "tool-call",
2526
- "tool-result",
2527
- "tool-error",
2528
- "tool-output-denied",
2529
- "tool-approval-request",
2530
- "tool-approval-response",
2531
- "finish-step"
2532
- ].includes(part.type);
2533
- if (structuralBoundary || eventsSinceCheckpoint >= checkpointEveryEvents) {
2534
- await checkpoint();
2535
- eventsSinceCheckpoint = 0;
2536
- if (part.type === "finish-step")
2537
- operationLifecycle.checkpointStep(step - 1);
2538
- }
2539
- }
2540
- if (retrying) {
2541
- await publish({
2542
- type: "attempt-reset",
2543
- conversationId: run.conversationId,
2544
- runId: run.id,
2545
- runtimeEpoch,
2546
- sequence: transientSequence(),
2547
- attempt: retryAttempt,
2548
- emittedAt: now().toISOString()
2549
- });
2550
- continue;
2551
- }
2552
- break;
2553
- }
2554
- await operationLifecycle.finish(executionSignal.aborted ? "cancelled" : terminalReason === "provider_failure" ? "failed" : "completed");
2555
- if (terminalPolicyName !== undefined)
2556
- terminalReason = "policy_stop";
2557
- if (executionSignal.aborted)
2558
- terminalReason = abortTerminalReason(executionSignal);
2559
- const awaitsApproval = parts.some((part) => part.type === "tool-approval-request");
2560
- if (!awaitsApproval && config.protocol.acceptTerminal && (terminalReason === "success" || terminalReason === "policy_stop" || terminalReason === "provider_stop")) {
2561
- const candidate = AgentMessageSchema.parse({
2562
- ...assistant,
2563
- status: assistantStatus(terminalReason),
2564
- parts,
2565
- updatedAt: now().toISOString()
2566
- });
2567
- if (!await config.protocol.acceptTerminal({
2568
- message: candidate,
2569
- reason: terminalReason,
2570
- ...terminalPolicyName && { policyName: terminalPolicyName }
2571
- })) {
2572
- terminalReason = "output_rejected";
2573
- internalCause = new Error("Agent terminal output was rejected by the protocol");
2574
- }
2575
- }
2576
- } catch (error) {
2577
- operationLifecycle.failStepCheckpoints(error);
2578
- internalCause = providerStreamCleanupFailure === undefined ? error : new AggregateError([error, providerStreamCleanupFailure], `${error instanceof Error ? error.message : String(error)} (provider stream cleanup also failed: ${providerStreamCleanupFailure instanceof Error ? providerStreamCleanupFailure.message : String(providerStreamCleanupFailure)})`);
2579
- const latest = await config.store.loadRun({
2580
- conversationId: run.conversationId,
2581
- runId: run.id
2582
- });
2583
- const latestRun = latest?.run;
2584
- const durableInterrupt = latestRun?.ownerId === runtimeEpoch && latestRun.state === "interrupt_requested";
2585
- if (durableInterrupt && latest && latestRun) {
2586
- observedVersion = latest.snapshotVersion;
2587
- run = latestRun;
2588
- }
2589
- const staleOwner = isToolExecutionControlError(error) && error.reason === "stale_run";
2590
- if (!staleOwner) {
2591
- await operationLifecycle.finish(executionSignal.aborted || durableInterrupt ? "cancelled" : "failed");
2592
- }
2593
- if (isToolExecutionControlError(error) || executionSignal.aborted || durableInterrupt) {
2594
- terminalReason = executionSignal.aborted ? abortTerminalReason(executionSignal) : "interrupted";
2595
- parts.push(AgentMessagePartSchema.parse({
2596
- type: "control",
2597
- reason: isToolExecutionControlError(error) && error.reason === "stale_run" ? "stale-run" : "run-interrupted"
2598
- }));
2599
- } else if (error instanceof AgentContextOverflowError) {
2600
- terminalReason = "context_overflow";
2601
- } else if (error instanceof AgentRuntimeConflictError) {
2602
- terminalReason = "storage_conflict";
2603
- } else {
2604
- terminalReason = failureThisRuntimeOwns(error) ?? (hasProviderOrigin(error) ? "provider_failure" : "runtime_failure");
2605
- }
2606
- } finally {
2607
- idleDeadline.dispose();
2608
- }
2609
- assistant = AgentMessageSchema.parse({
2610
- ...assistant,
2611
- status: assistantStatus(terminalReason),
2612
- parts,
2613
- updatedAt: now().toISOString()
2614
- });
2615
- const spent = statedUsage(usage);
2616
- const emitSpend = (report) => {
2617
- config.observe?.emit({
2618
- schemaVersion: 1,
2619
- eventId: report.eventId,
2620
- type: "run-terminal",
2621
- conversationId: run.conversationId,
2622
- runId: run.id,
2623
- traceId: trace?.traceId ?? generateId(),
2624
- spanId: trace?.spanId ?? generateId(),
2625
- ...trace?.parentSpanId && { parentSpanId: trace.parentSpanId },
2626
- state: report.state,
2627
- terminalReason: report.reason,
2628
- ...selectedModel && { modelId: selectedModel.descriptor.modelId },
2629
- durationMs: performance.now() - runStartedAt,
2630
- usage: spent,
2631
- ...internalCause !== undefined && { internalCause },
2632
- ...firstOutputAt !== undefined && { ttftMs: firstOutputAt - runStartedAt },
2633
- emittedAt: now().toISOString()
2634
- });
2635
- };
2636
- const unsettledEventId = (version) => agentDurableEventId("terminal", `${run.id}:${runtimeEpoch}`, version);
2637
- let terminal;
2638
- try {
2639
- terminal = await commitAgentRunTerminal({
2640
- store: config.store,
2641
- runtimeEpoch,
2642
- candidate: {
2643
- run,
2644
- assistant,
2645
- reason: terminalReason,
2646
- ...terminalPolicyName && { policyName: terminalPolicyName },
2647
- usage: spent,
2648
- ...absorbed.size > 0 && runStateForTerminalReason(terminalReason) === "completed" && {
2649
- absorb: [...absorbed].map(([runId, inputMessageIds]) => ({
2650
- runId,
2651
- inputMessageIds
2652
- }))
2653
- }
2654
- },
2655
- now
2656
- });
2657
- } catch (error) {
2658
- emitSpend({
2659
- eventId: unsettledEventId(observedVersion),
2660
- state: run.state,
2661
- reason: terminalReason
2662
- });
2663
- throw error;
2664
- }
2665
- observedVersion = terminal.snapshotVersion;
2666
- run = terminal.run;
2667
- assistant = terminal.assistant;
2668
- terminalReason = terminal.reason;
2669
- terminalPolicyName = terminal.policyName;
2670
- const terminalMetrics = terminal.committedByCaller ? {
2671
- partial: !sawProviderFinish,
2672
- durationMs: performance.now() - runStartedAt,
2673
- usage: spent,
2674
- ...firstOutputAt !== undefined && { ttftMs: firstOutputAt - runStartedAt }
2675
- } : undefined;
2676
- if (config.children && terminal.committedByCaller && (terminalReason === "interrupted" || terminalReason === "cancelled" || terminalReason === "timeout" || terminalReason === "shutdown")) {
2677
- try {
2678
- await config.children.stopChildren(run.conversationId);
2679
- } catch (error) {
2680
- internalCause ??= error;
2681
- }
2682
- }
2683
- emitSpend({
2684
- eventId: terminal.committedByCaller ? agentDurableEventId("terminal", run.id, observedVersion) : unsettledEventId(observedVersion),
2685
- state: run.state,
2686
- reason: terminalReason
2687
- });
2688
- for (const settled of terminal.absorbed ?? []) {
2689
- await publish({
2690
- type: "run-state",
2691
- eventId: agentDurableEventId("run-state", settled.id, observedVersion),
2692
- conversationId: settled.conversationId,
2693
- runId: settled.id,
2694
- snapshotVersion: observedVersion,
2695
- state: settled.state,
2696
- emittedAt: now().toISOString()
2697
- });
2698
- }
2699
- if (terminalMetrics) {
2700
- await publish({
2701
- type: "terminal",
2702
- eventId: agentDurableEventId("terminal", run.id, observedVersion),
2703
- conversationId: run.conversationId,
2704
- runId: run.id,
2705
- snapshotVersion: observedVersion,
2706
- reason: terminalReason,
2707
- ...terminalPolicyName && { policyName: terminalPolicyName },
2708
- message: assistant,
2709
- metrics: terminalMetrics,
2710
- emittedAt: now().toISOString()
2711
- });
2712
- }
2713
- return {
2714
- run,
2715
- message: assistant,
2716
- reason: terminalReason,
2717
- snapshotVersion: observedVersion,
2718
- ...terminalMetrics && { metrics: terminalMetrics },
2719
- ...terminalPolicyName && { policyName: terminalPolicyName }
2720
- };
2721
- };
2722
- }
2723
-
2724
- // src/agent-runtime/runtime.ts
2725
- function createAgentRuntime(config) {
2726
- const coordinator = createAgentSessionCoordinator();
2727
- const tickets = new Map;
2728
- const generateId = config.generateId ?? (() => crypto.randomUUID());
2729
- const now = config.now ?? (() => new Date);
2730
- const runtimeEpoch = generateId();
2731
- const admissionLanes = createRuntimeAdmissionLanes();
2732
- const injectionPossible = typeof config.runs?.inputPolicy === "function" || config.runs?.inputPolicy === "inject";
2733
- const injection = injectionPossible ? createAgentInjectionRegistry() : undefined;
2734
- const reserveAdmission = admissionLanes.reserve;
2735
- const settleAdmission = admissionLanes.settle;
2736
- const waitForAdmissionAcceptances = admissionLanes.waitForAcceptances;
2737
- const checkpointEveryEvents = config.loop?.checkpointEveryEvents ?? 20;
2738
- const maxSteps = config.loop?.maxSteps ?? 50;
2739
- const declaredIdleTimeoutMs = config.loop?.idleTimeoutMs;
2740
- const idleTimeoutMs = declaredIdleTimeoutMs === null ? undefined : declaredIdleTimeoutMs ?? 60000;
2741
- if (!Number.isSafeInteger(checkpointEveryEvents) || checkpointEveryEvents < 1) {
2742
- throw new TypeError("checkpointEveryEvents must be a positive safe integer");
2743
- }
2744
- if (!Number.isSafeInteger(maxSteps) || maxSteps < 1) {
2745
- throw new TypeError("maxSteps must be a positive safe integer");
2746
- }
2747
- if (idleTimeoutMs !== undefined && (!Number.isSafeInteger(idleTimeoutMs) || idleTimeoutMs < 1)) {
2748
- throw new TypeError("idleTimeoutMs must be a positive safe integer");
2749
- }
2750
- const policyNames = new Set(["max-steps"]);
2751
- for (const policy of config.loop?.stopPolicies ?? []) {
2752
- if (!policy.name || policyNames.has(policy.name)) {
2753
- throw new TypeError("Agent stop policy names must be non-empty and unique");
2754
- }
2755
- policyNames.add(policy.name);
2756
- }
2757
- const publish = async (event) => {
2758
- try {
2759
- await config.publish?.(event);
2760
- } catch (error) {
2761
- try {
2762
- await config.onPublishError?.({ event, error });
2763
- } catch {}
2764
- }
2765
- };
2766
- const executeRun = createRunExecutor({
2767
- config,
2768
- publish,
2769
- runtimeEpoch,
2770
- generateId,
2771
- now,
2772
- checkpointEveryEvents,
2773
- maxSteps,
2774
- ...idleTimeoutMs !== undefined && { idleTimeoutMs },
2775
- ...injection && { injection }
2776
- });
2777
- let admissionClosed = false;
2778
- const closedError = () => new Error("[stitchkit] agent runtime is closed and admits no further work");
2779
- const admissionsInFlight = new Set;
2780
- const beginAdmission = () => {
2781
- const handoff = Promise.withResolvers();
2782
- admissionsInFlight.add(handoff);
2783
- return () => {
2784
- if (admissionsInFlight.delete(handoff))
2785
- handoff.resolve();
2786
- };
2787
- };
2788
- const drainAdmissions = async (budgetMs) => {
2789
- const pending = [...admissionsInFlight].map((handoff) => handoff.promise);
2790
- if (pending.length === 0)
2791
- return 0;
2792
- let stranded = pending.length;
2793
- const settled = Promise.all(pending.map((promise) => promise.then(() => {
2794
- stranded -= 1;
2795
- })));
2796
- if (budgetMs === undefined) {
2797
- await settled;
2798
- return 0;
2799
- }
2800
- let timer;
2801
- await Promise.race([
2802
- settled,
2803
- new Promise((resolve) => {
2804
- timer = setTimeout(resolve, budgetMs);
2805
- })
2806
- ]);
2807
- if (timer !== undefined)
2808
- clearTimeout(timer);
2809
- return stranded;
2810
- };
2811
- const refuse = () => {
2812
- const error = closedError();
2813
- const accepted = Promise.reject(error);
2814
- const result = Promise.reject(error);
2815
- accepted.catch(() => {
2816
- return;
2817
- });
2818
- result.catch(() => {
2819
- return;
2820
- });
2821
- return { accepted, result };
2822
- };
2823
- const resume = (rawInput) => {
2824
- if (admissionClosed)
2825
- return refuse();
2826
- const context = config.protocol.parseContext(rawInput.context);
2827
- const accepted = Promise.withResolvers();
2828
- const result = Promise.withResolvers();
2829
- let acquisitionSettled = false;
2830
- const resolveAcquisition = () => {
2831
- acquisitionSettled = true;
2832
- accepted.resolve();
2833
- };
2834
- const rejectAcquisition = (error) => {
2835
- if (!acquisitionSettled)
2836
- accepted.reject(error);
2837
- };
2838
- const handedOff = beginAdmission();
2839
- (async () => {
2840
- try {
2841
- const recovered = await config.store.loadRun({
2842
- conversationId: rawInput.conversationId,
2843
- runId: rawInput.runId
2844
- });
2845
- if (!recovered)
2846
- throw new AgentRuntimeConflictError("run lookup");
2847
- const recoveredRun = recovered.run;
2848
- if (recoveredRun.state !== "queued") {
2849
- throw new Error("Only a queued recovered agent run can be resumed");
2850
- }
2851
- const ticket = coordinator.submit({
2852
- key: rawInput.conversationKey ?? rawInput.conversationId,
2853
- policy: "queue",
2854
- create: (signal) => ({
2855
- runId: recoveredRun.id,
2856
- execute: () => executeRun({
2857
- acceptedRun: recoveredRun,
2858
- context,
2859
- signal,
2860
- key: rawInput.conversationKey ?? rawInput.conversationId,
2861
- onAcquired: resolveAcquisition
2862
- })
2863
- })
2864
- });
2865
- ticket.accepted.catch(() => {
2866
- return;
2867
- });
2868
- ticket.result.then(result.resolve, (error) => {
2869
- rejectAcquisition(error);
2870
- result.reject(error);
2871
- });
2872
- } catch (error) {
2873
- rejectAcquisition(error);
2874
- result.reject(error);
2875
- } finally {
2876
- handedOff();
2877
- }
2878
- })();
2879
- return { accepted: accepted.promise, result: result.promise };
2880
- };
2881
- return {
2882
- submit(rawInput) {
2883
- if (admissionClosed) {
2884
- const refused = refuse();
2885
- const admission = Promise.reject(closedError());
2886
- admission.catch(() => {
2887
- return;
2888
- });
2889
- return { ...refused, admission };
2890
- }
2891
- const metadata = rawInput.metadata === undefined ? undefined : config.protocol.parseInputMetadata(rawInput.metadata);
2892
- const input = {
2893
- conversationId: rawInput.conversationId,
2894
- idempotencyKey: rawInput.idempotencyKey,
2895
- context: rawInput.context,
2896
- parts: rawInput.parts.map((part) => config.protocol.parsePart(part)),
2897
- role: rawInput.role ?? "user",
2898
- ...metadata !== undefined && { metadata }
2899
- };
2900
- if (input.role === "tool" && (input.parts.length === 0 || input.parts.some((part) => part.type !== "tool-approval-response"))) {
2901
- throw new TypeError("Tool-role Agent input only accepts approval responses");
2902
- }
2903
- const context = config.protocol.parseContext(input.context);
2904
- const conversationTickets = tickets.get(input.conversationId);
2905
- const existingTicket = conversationTickets?.get(input.idempotencyKey);
2906
- if (existingTicket)
2907
- return existingTicket;
2908
- const key = config.runs?.key?.(input) ?? input.conversationId;
2909
- const policy = typeof config.runs?.inputPolicy === "function" ? config.runs.inputPolicy(input) : config.runs?.inputPolicy ?? "queue";
2910
- const nowIso = now().toISOString();
2911
- const inputMessageId = rawInput.recordIds?.inputMessageId ?? generateId();
2912
- const runId = rawInput.recordIds?.runId ?? generateId();
2913
- const assistantMessageId = rawInput.recordIds?.assistantMessageId ?? generateId();
2914
- const userMessage2 = AgentMessageSchema.parse({
2915
- schemaVersion: 1,
2916
- id: inputMessageId,
2917
- conversationId: input.conversationId,
2918
- role: input.role,
2919
- status: "committed",
2920
- parts: input.parts,
2921
- ...input.metadata && { metadata: input.metadata },
2922
- createdAt: nowIso,
2923
- updatedAt: nowIso
2924
- });
2925
- const queuedRun = AgentRunSchema.parse({
2926
- schemaVersion: 1,
2927
- id: runId,
2928
- conversationId: input.conversationId,
2929
- inputMessageIds: [inputMessageId],
2930
- assistantMessageId,
2931
- state: "queued",
2932
- revision: 0,
2933
- ...policy === "interrupt-next" && { queuePriority: "interrupt-next" },
2934
- createdAt: nowIso,
2935
- updatedAt: nowIso
2936
- });
2937
- const outerAccepted = Promise.withResolvers();
2938
- outerAccepted.promise.catch(() => {
2939
- return;
2940
- });
2941
- const outerAdmission = Promise.withResolvers();
2942
- outerAdmission.promise.catch(() => {
2943
- return;
2944
- });
2945
- const outerResult = Promise.withResolvers();
2946
- const reservation = config.runs?.coalescePending && policy !== "interrupt-next" ? reserveAdmission(key, runId) : undefined;
2947
- const previousAcceptance = reservation?.lane.acceptanceTail ?? Promise.resolve();
2948
- const acceptanceDone = Promise.withResolvers();
2949
- if (reservation) {
2950
- reservation.lane.acceptanceTail = previousAcceptance.catch(() => {
2951
- return;
2952
- }).then(() => acceptanceDone.promise);
2953
- }
2954
- const publicTicket = {
2955
- accepted: outerAccepted.promise,
2956
- admission: outerAdmission.promise,
2957
- result: outerResult.promise
2958
- };
2959
- const currentConversationTickets = conversationTickets ?? new Map;
2960
- currentConversationTickets.set(input.idempotencyKey, publicTicket);
2961
- if (!conversationTickets)
2962
- tickets.set(input.conversationId, currentConversationTickets);
2963
- let offeredRunId;
2964
- const forgetTicket = () => {
2965
- if (offeredRunId !== undefined)
2966
- injection?.withdraw(key, offeredRunId);
2967
- if (currentConversationTickets.get(input.idempotencyKey) !== publicTicket)
2968
- return;
2969
- currentConversationTickets.delete(input.idempotencyKey);
2970
- if (currentConversationTickets.size === 0)
2971
- tickets.delete(input.conversationId);
2972
- };
2973
- outerResult.promise.then(forgetTicket, forgetTicket);
2974
- const handedOff = beginAdmission();
2975
- (async () => {
2976
- try {
2977
- await previousAcceptance.catch(() => {
2978
- return;
2979
- });
2980
- await config.models.preflight?.({
2981
- context,
2982
- conversationId: input.conversationId
2983
- });
2984
- if (admissionClosed)
2985
- throw closedError();
2986
- const acceptance = await config.store.acceptInputAndAssignRun({
2987
- idempotencyKey: input.idempotencyKey,
2988
- input: userMessage2,
2989
- run: queuedRun,
2990
- ...reservation && !reservation.shouldSchedule && {
2991
- coalesceIntoRunId: reservation.admission.runId
2992
- }
2993
- });
2994
- const acceptedSnapshot = appliedSnapshot(acceptance, "input acceptance");
2995
- const assignedRunId = acceptance.outcome === "duplicate" ? acceptance.runId : reservation?.admission.runId ?? runId;
2996
- const acceptedRun = acceptance.outcome === "duplicate" ? acceptance.run : findRun(acceptedSnapshot.runs, assignedRunId);
2997
- const actualInputMessageId = acceptance.outcome === "duplicate" ? acceptance.inputMessageId : userMessage2.id;
2998
- const acceptedInput = acceptance.outcome === "duplicate" ? acceptance.input : acceptedSnapshot.messages.find((candidate) => candidate.id === actualInputMessageId);
2999
- if (!acceptedInput) {
3000
- throw new AgentRuntimeConflictError("admission input projection");
3001
- }
3002
- const assistantPlaceholder = AgentAssistantPlaceholderSchema.parse({
3003
- schemaVersion: 1,
3004
- id: acceptedRun.assistantMessageId,
3005
- conversationId: acceptedRun.conversationId,
3006
- runId: acceptedRun.id,
3007
- status: "pending",
3008
- createdAt: acceptedRun.createdAt,
3009
- updatedAt: acceptedRun.updatedAt
3010
- });
3011
- const acceptedAssistant = acceptance.outcome === "duplicate" ? acceptance.assistant ?? assistantPlaceholder : assistantPlaceholder;
3012
- const admission = {
3013
- inputMessageId: acceptedInput.id,
3014
- runId: acceptedRun.id,
3015
- assistantMessageId: assistantPlaceholder.id,
3016
- input: acceptedInput,
3017
- run: acceptedRun,
3018
- assistant: acceptedAssistant,
3019
- snapshotVersion: acceptedSnapshot.version
3020
- };
3021
- outerAdmission.resolve(admission);
3022
- await publish({
3023
- type: "admission",
3024
- eventId: agentDurableEventId("admission", acceptedRun.id, acceptedSnapshot.version),
3025
- conversationId: acceptedRun.conversationId,
3026
- runId: acceptedRun.id,
3027
- snapshotVersion: acceptedSnapshot.version,
3028
- input: acceptedInput,
3029
- run: acceptedRun,
3030
- assistant: acceptedAssistant,
3031
- emittedAt: now().toISOString()
3032
- });
3033
- await publish({
3034
- type: "run-state",
3035
- eventId: agentDurableEventId("run-state", acceptedRun.id, acceptedSnapshot.version),
3036
- conversationId: acceptedRun.conversationId,
3037
- runId: acceptedRun.id,
3038
- snapshotVersion: acceptedSnapshot.version,
3039
- state: acceptedRun.state,
3040
- emittedAt: now().toISOString()
3041
- });
3042
- outerAccepted.resolve();
3043
- if (acceptance.outcome === "duplicate") {
3044
- if (!acceptedRun.terminalReason) {
3045
- const error = new Error("Duplicate input is already owned by another runtime execution");
3046
- outerResult.reject(error);
3047
- if (reservation?.shouldSchedule) {
3048
- reservation.admission.completion.reject(error);
3049
- settleAdmission(key, reservation.admission);
3050
- }
3051
- return;
3052
- }
3053
- const message = acceptance.assistant;
3054
- if (!message) {
3055
- const error = new Error("Duplicate terminal admission has no retained canonical assistant");
3056
- outerResult.reject(error);
3057
- if (reservation?.shouldSchedule) {
3058
- reservation.admission.completion.reject(error);
3059
- settleAdmission(key, reservation.admission);
3060
- }
3061
- return;
3062
- }
3063
- outerResult.resolve({
3064
- run: acceptedRun,
3065
- message,
3066
- reason: acceptedRun.terminalReason,
3067
- snapshotVersion: acceptedSnapshot.version,
3068
- ...acceptedRun.terminalPolicyName && {
3069
- policyName: acceptedRun.terminalPolicyName
3070
- }
3071
- });
3072
- if (reservation?.shouldSchedule) {
3073
- reservation.admission.completion.reject(new Error("Reserved run resolved to a duplicate durable input"));
3074
- settleAdmission(key, reservation.admission);
3075
- }
3076
- return;
3077
- }
3078
- if (policy === "inject") {
3079
- offeredRunId = acceptedRun.id;
3080
- injection?.offer(key, { runId: acceptedRun.id, input: acceptedInput });
3081
- }
3082
- if (reservation && !reservation.shouldSchedule) {
3083
- reservation.admission.completion.promise.then(outerResult.resolve, outerResult.reject);
3084
- return;
3085
- }
3086
- const ticket = coordinator.submit({
3087
- key,
3088
- policy,
3089
- create: async (signal) => {
3090
- if (reservation)
3091
- await waitForAdmissionAcceptances(reservation.lane);
3092
- return {
3093
- runId: acceptedRun.id,
3094
- execute: () => executeRun({ acceptedRun, context, signal, key })
3095
- };
3096
- }
3097
- });
3098
- ticket.accepted.catch(() => {
3099
- return;
3100
- });
3101
- if (reservation) {
3102
- ticket.result.then(reservation.admission.completion.resolve, reservation.admission.completion.reject);
3103
- reservation.admission.completion.promise.then((value) => {
3104
- settleAdmission(key, reservation.admission);
3105
- outerResult.resolve(value);
3106
- }, (error) => {
3107
- settleAdmission(key, reservation.admission);
3108
- outerResult.reject(error);
3109
- });
3110
- } else {
3111
- ticket.result.then(outerResult.resolve, outerResult.reject);
3112
- }
3113
- } catch (error) {
3114
- outerAccepted.reject(error);
3115
- outerAdmission.reject(error);
3116
- outerResult.reject(error);
3117
- if (reservation?.shouldSchedule) {
3118
- reservation.admission.completion.reject(error);
3119
- settleAdmission(key, reservation.admission);
3120
- }
3121
- } finally {
3122
- acceptanceDone.resolve();
3123
- handedOff();
3124
- }
3125
- })();
3126
- return publicTicket;
3127
- },
3128
- resume,
3129
- async interrupt(input) {
3130
- const view = await config.store.loadRun({
3131
- conversationId: input.conversationId,
3132
- runId: input.runId
3133
- });
3134
- if (!view)
3135
- throw new AgentRuntimeConflictError("run lookup");
3136
- const requested = await config.store.requestRunInterrupt({
3137
- conversationId: input.conversationId,
3138
- runId: input.runId,
3139
- expectedRevision: view.run.revision
3140
- });
3141
- if (requested.outcome === "applied") {
3142
- const interruptedRun = findRun(requested.snapshot.runs, input.runId);
3143
- await publish({
3144
- type: "run-state",
3145
- eventId: agentDurableEventId("run-state", interruptedRun.id, requested.snapshot.version),
3146
- conversationId: interruptedRun.conversationId,
3147
- runId: interruptedRun.id,
3148
- snapshotVersion: requested.snapshot.version,
3149
- state: interruptedRun.state,
3150
- emittedAt: now().toISOString()
3151
- });
3152
- coordinator.stop(input.conversationKey ?? input.conversationId, "user-interrupt");
3153
- }
3154
- return requested;
3155
- },
3156
- async abandon(input) {
3157
- if (input.staleOwner !== true) {
3158
- throw new TypeError("Abandoning a run requires explicit staleOwner evidence");
3159
- }
3160
- const releaseAdmission = beginAdmission();
3161
- try {
3162
- const abandoned = await config.store.recoverRun({
3163
- conversationId: input.conversationId,
3164
- runId: input.runId,
3165
- expectedRevision: input.expectedRevision,
3166
- action: "abandon"
3167
- });
3168
- if (abandoned.outcome === "applied") {
3169
- const abandonedRun = findRun(abandoned.snapshot.runs, input.runId);
3170
- await publish({
3171
- type: "run-state",
3172
- eventId: agentDurableEventId("run-state", abandonedRun.id, abandoned.snapshot.version),
3173
- conversationId: abandonedRun.conversationId,
3174
- runId: abandonedRun.id,
3175
- snapshotVersion: abandoned.snapshot.version,
3176
- state: abandonedRun.state,
3177
- emittedAt: now().toISOString()
3178
- });
3179
- }
3180
- return abandoned;
3181
- } finally {
3182
- releaseAdmission();
3183
- }
3184
- },
3185
- async recover(options) {
3186
- if (admissionClosed)
3187
- throw closedError();
3188
- const pageSize = options.pageSize ?? 100;
3189
- const maxRuns = options.maxRuns ?? 1000;
3190
- if (!Number.isSafeInteger(pageSize) || pageSize < 1 || pageSize > 1000) {
3191
- throw new TypeError("Recovery pageSize must be an integer between 1 and 1000");
3192
- }
3193
- if (!Number.isSafeInteger(maxRuns) || maxRuns < 1) {
3194
- throw new TypeError("Recovery maxRuns must be a positive safe integer");
3195
- }
3196
- const recoverable = [];
3197
- let cursor;
3198
- while (recoverable.length < maxRuns && !options.signal?.aborted && !admissionClosed) {
3199
- const page = await config.store.scanRecoverable({
3200
- ...cursor && { cursor },
3201
- limit: Math.min(pageSize, maxRuns - recoverable.length)
3202
- });
3203
- recoverable.push(...page.items);
3204
- cursor = page.nextCursor;
3205
- if (!cursor || page.items.length === 0)
3206
- break;
3207
- }
3208
- const grouped = new Map;
3209
- for (const item of recoverable) {
3210
- const items = grouped.get(item.conversationId) ?? [];
3211
- items.push(item);
3212
- grouped.set(item.conversationId, items);
3213
- }
3214
- const ordered = [];
3215
- for (const [conversationId, items] of grouped) {
3216
- const active = await config.store.listActiveRuns(conversationId);
3217
- const position = new Map(active.map((run, index) => [run.id, index]));
3218
- ordered.push(...items.sort((left, right) => {
3219
- const leftPosition = position.get(left.run.id);
3220
- const rightPosition = position.get(right.run.id);
3221
- if (leftPosition === undefined && rightPosition === undefined)
3222
- return 0;
3223
- if (leftPosition === undefined)
3224
- return 1;
3225
- if (rightPosition === undefined)
3226
- return -1;
3227
- return leftPosition - rightPosition;
3228
- }));
3229
- }
3230
- const outcomes = [];
3231
- const scheduledRuns = new Map;
3232
- for (const item of ordered) {
3233
- if (options.signal?.aborted)
3234
- break;
3235
- if (admissionClosed)
3236
- break;
3237
- const releaseAdmission = beginAdmission();
3238
- try {
3239
- const active = await config.store.listActiveRuns(item.conversationId);
3240
- const position = active.findIndex((run) => run.id === item.run.id);
3241
- const scheduled = scheduledRuns.get(item.conversationId) ?? new Set;
3242
- const blockedByUnscheduledPredecessor = position > 0 && active.slice(0, position).some((run) => !scheduled.has(run.id));
3243
- if (blockedByUnscheduledPredecessor) {
3244
- outcomes.push({
3245
- conversationId: item.conversationId,
3246
- runId: item.run.id,
3247
- outcome: "skipped"
3248
- });
3249
- continue;
3250
- }
3251
- const decision = await options.decide?.(item) ?? (item.run.state === "queued" ? { action: "resume" } : { action: "skip" });
3252
- if (admissionClosed)
3253
- throw closedError();
3254
- if (decision.action === "skip") {
3255
- outcomes.push({
3256
- conversationId: item.conversationId,
3257
- runId: item.run.id,
3258
- outcome: "skipped"
3259
- });
3260
- continue;
3261
- }
3262
- if (decision.action === "abandon") {
3263
- const abandoned = await config.store.recoverRun({
3264
- conversationId: item.conversationId,
3265
- runId: item.run.id,
3266
- expectedRevision: item.run.revision,
3267
- action: "abandon"
3268
- });
3269
- if (abandoned.outcome !== "applied") {
3270
- throw new AgentRuntimeConflictError("recovery abandon");
3271
- }
3272
- outcomes.push({
3273
- conversationId: item.conversationId,
3274
- runId: item.run.id,
3275
- outcome: "abandoned"
3276
- });
3277
- continue;
3278
- }
3279
- if (decision.action === "requeue") {
3280
- const requeued = await config.store.recoverRun({
3281
- conversationId: item.conversationId,
3282
- runId: item.run.id,
3283
- expectedRevision: item.run.revision,
3284
- action: "requeue",
3285
- replaySafe: true
3286
- });
3287
- if (requeued.outcome !== "applied") {
3288
- throw new AgentRuntimeConflictError("recovery requeue");
3289
- }
3290
- }
3291
- const context = await options.resolveContext(item);
3292
- const resumed = resume({
3293
- conversationId: item.conversationId,
3294
- runId: item.run.id,
3295
- context
3296
- });
3297
- resumed.result.catch(() => {
3298
- return;
3299
- });
3300
- await resumed.accepted;
3301
- scheduled.add(item.run.id);
3302
- scheduledRuns.set(item.conversationId, scheduled);
3303
- outcomes.push({
3304
- conversationId: item.conversationId,
3305
- runId: item.run.id,
3306
- outcome: decision.action === "requeue" ? "requeued" : "resumed",
3307
- result: resumed.result
3308
- });
3309
- } catch (error) {
3310
- outcomes.push({
3311
- conversationId: item.conversationId,
3312
- runId: item.run.id,
3313
- outcome: "failed",
3314
- error
3315
- });
3316
- } finally {
3317
- releaseAdmission();
3318
- }
3319
- }
3320
- return outcomes;
3321
- },
3322
- stop: (conversationKey, reason) => coordinator.stop(conversationKey, reason),
3323
- close: async (options = {}) => {
3324
- assertCloseBudgets(options);
3325
- admissionClosed = true;
3326
- const startedAt = performance.now();
3327
- injection?.clear();
3328
- const stranded = await drainAdmissions(options.forceTimeoutMs);
3329
- const spent = Math.max(0, Math.round(performance.now() - startedAt));
3330
- const remainingBudget = (value) => value === undefined ? undefined : Math.max(0, value - spent);
3331
- const grace = remainingBudget(options.gracePeriodMs);
3332
- const force = remainingBudget(options.forceTimeoutMs);
3333
- const result = await coordinator.close({
3334
- ...grace !== undefined && { gracePeriodMs: grace },
3335
- ...force !== undefined && { forceTimeoutMs: force }
3336
- });
3337
- if (stranded === 0)
3338
- return result;
3339
- return { settled: false, timedOut: true, remaining: result.remaining + stranded };
3340
- }
3341
- };
3342
- }
3343
-
3344
- export { AgentRuntimeConflictError, normalizeSdkUsage, AgentContextOverflowError, createAgentSessionCoordinator, registerDeferredToolRepair, registerDeferredToolCatalog, deferredToolCatalog, repairedSearchCall, createAgentRuntimeEventSink, projectAgentHistoryDetailed, projectAgentHistory, createAgentToolFenceLifecycle, AgentTokenCountSchema, selectAgentHistory, composeAgentPrompt, AgentProviderStreamCutError, classifyProviderFailure, isToolResultFailure, recordAgentRetryDecision, defineStateSlot, createAgentStateSlotStore, renderAgentStateSlots, agentGoalStateSlot, agentTodoStateSlot, createAgentRuntime };