stitchkit 0.93.0 → 0.94.1

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