stitchkit 0.134.2 → 0.135.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 (1126) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +1 -1
  3. package/dist/agent-executor/acp/v1-connect.d.ts +1 -1
  4. package/dist/agent-executor/acp/v1-connect.d.ts.map +1 -1
  5. package/dist/agent-executor/acp/v1-session.d.ts +1 -1
  6. package/dist/agent-executor/acp/v1-session.d.ts.map +1 -1
  7. package/dist/agent-executor/json-rpc-peer.d.ts +1 -1
  8. package/dist/agent-executor/json-rpc-peer.d.ts.map +1 -1
  9. package/dist/agent-runtime/browser/browser-control-contract.d.ts +1364 -0
  10. package/dist/agent-runtime/browser/browser-control-contract.d.ts.map +1 -0
  11. package/dist/agent-runtime/browser/browser-controller-view.d.ts +44 -0
  12. package/dist/agent-runtime/browser/browser-controller-view.d.ts.map +1 -0
  13. package/dist/agent-runtime/browser/browser-controller.d.ts +53 -0
  14. package/dist/agent-runtime/browser/browser-controller.d.ts.map +1 -0
  15. package/dist/agent-runtime/browser/control-interaction-schema.d.ts.map +1 -0
  16. package/dist/agent-runtime/browser/control-schema.d.ts +1378 -0
  17. package/dist/agent-runtime/browser/control-schema.d.ts.map +1 -0
  18. package/dist/agent-runtime/browser/control-view.d.ts +64 -0
  19. package/dist/agent-runtime/browser/control-view.d.ts.map +1 -0
  20. package/dist/agent-runtime/browser/react.d.ts.map +1 -0
  21. package/dist/agent-runtime/coding/coding-discovery.d.ts +25 -0
  22. package/dist/agent-runtime/coding/coding-discovery.d.ts.map +1 -0
  23. package/dist/agent-runtime/coding/coding-sandbox.d.ts +8 -0
  24. package/dist/agent-runtime/coding/coding-sandbox.d.ts.map +1 -0
  25. package/dist/agent-runtime/coding/coding-search-automaton.d.ts.map +1 -0
  26. package/dist/agent-runtime/coding/coding-search-case-fold.d.ts.map +1 -0
  27. package/dist/agent-runtime/coding/coding-search-class-ranges.d.ts.map +1 -0
  28. package/dist/agent-runtime/coding/coding-search-contract.d.ts.map +1 -0
  29. package/dist/agent-runtime/coding/coding-search-limits.d.ts.map +1 -0
  30. package/dist/agent-runtime/coding/coding-search-matcher.d.ts.map +1 -0
  31. package/dist/agent-runtime/coding/coding-search-output.d.ts.map +1 -0
  32. package/dist/agent-runtime/coding/coding-search-regex-syntax.d.ts.map +1 -0
  33. package/dist/agent-runtime/coding/coding-search-unit-classes.d.ts.map +1 -0
  34. package/dist/agent-runtime/coding/coding-shell-process.d.ts +36 -0
  35. package/dist/agent-runtime/coding/coding-shell-process.d.ts.map +1 -0
  36. package/dist/agent-runtime/coding/coding-tool-contract.d.ts +261 -0
  37. package/dist/agent-runtime/coding/coding-tool-contract.d.ts.map +1 -0
  38. package/dist/agent-runtime/coding/coding-tool-files.d.ts.map +1 -0
  39. package/dist/agent-runtime/coding/coding-tool-listing.d.ts.map +1 -0
  40. package/dist/agent-runtime/coding/coding-tool-paths.d.ts +53 -0
  41. package/dist/agent-runtime/coding/coding-tool-paths.d.ts.map +1 -0
  42. package/dist/agent-runtime/coding/coding-tool-refusals.d.ts.map +1 -0
  43. package/dist/agent-runtime/coding/coding-tool-search-patch.d.ts.map +1 -0
  44. package/dist/agent-runtime/coding/coding-tool-search.d.ts +113 -0
  45. package/dist/agent-runtime/coding/coding-tool-search.d.ts.map +1 -0
  46. package/dist/agent-runtime/coding/coding-tool-shell.d.ts.map +1 -0
  47. package/dist/agent-runtime/coding/coding-tool-utf8.d.ts.map +1 -0
  48. package/dist/agent-runtime/coding/coding-tools.d.ts.map +1 -0
  49. package/dist/agent-runtime/coding/contained-scan-budget.d.ts.map +1 -0
  50. package/dist/agent-runtime/coding/contained-scan-contract.d.ts.map +1 -0
  51. package/dist/agent-runtime/coding/contained-scan.d.ts +56 -0
  52. package/dist/agent-runtime/coding/contained-scan.d.ts.map +1 -0
  53. package/dist/agent-runtime/coding/workspace-glob.d.ts.map +1 -0
  54. package/dist/agent-runtime/context-issue.d.ts +1 -1
  55. package/dist/agent-runtime/context-issue.d.ts.map +1 -1
  56. package/dist/agent-runtime/deferred-tool-types.d.ts +3 -1
  57. package/dist/agent-runtime/deferred-tool-types.d.ts.map +1 -1
  58. package/dist/agent-runtime/harness/harness-contract.d.ts +206 -0
  59. package/dist/agent-runtime/harness/harness-contract.d.ts.map +1 -0
  60. package/dist/agent-runtime/harness/harness-control.d.ts +34 -0
  61. package/dist/agent-runtime/harness/harness-control.d.ts.map +1 -0
  62. package/dist/agent-runtime/harness/harness-file-resources.d.ts +33 -0
  63. package/dist/agent-runtime/harness/harness-file-resources.d.ts.map +1 -0
  64. package/dist/agent-runtime/harness/harness-resources.d.ts.map +1 -0
  65. package/dist/agent-runtime/harness/harness.d.ts +15 -0
  66. package/dist/agent-runtime/harness/harness.d.ts.map +1 -0
  67. package/dist/agent-runtime/history/compaction.d.ts +103 -0
  68. package/dist/agent-runtime/history/compaction.d.ts.map +1 -0
  69. package/dist/agent-runtime/history/history.d.ts +93 -0
  70. package/dist/agent-runtime/history/history.d.ts.map +1 -0
  71. package/dist/agent-runtime/history/run-history-parts.d.ts +14 -0
  72. package/dist/agent-runtime/history/run-history-parts.d.ts.map +1 -0
  73. package/dist/agent-runtime/loop/admission-lanes.d.ts +35 -0
  74. package/dist/agent-runtime/loop/admission-lanes.d.ts.map +1 -0
  75. package/dist/agent-runtime/loop/coordinator.d.ts.map +1 -0
  76. package/dist/agent-runtime/loop/deferred-tool-search.d.ts +9 -0
  77. package/dist/agent-runtime/loop/deferred-tool-search.d.ts.map +1 -0
  78. package/dist/agent-runtime/loop/deferred-tool-selection.d.ts +32 -0
  79. package/dist/agent-runtime/loop/deferred-tool-selection.d.ts.map +1 -0
  80. package/dist/agent-runtime/loop/deferred-tools-internal.d.ts +19 -0
  81. package/dist/agent-runtime/loop/deferred-tools-internal.d.ts.map +1 -0
  82. package/dist/agent-runtime/loop/deferred-tools.d.ts +4 -0
  83. package/dist/agent-runtime/loop/deferred-tools.d.ts.map +1 -0
  84. package/dist/agent-runtime/loop/injection.d.ts +28 -0
  85. package/dist/agent-runtime/loop/injection.d.ts.map +1 -0
  86. package/dist/agent-runtime/loop/invocation-attempt.d.ts +32 -0
  87. package/dist/agent-runtime/loop/invocation-attempt.d.ts.map +1 -0
  88. package/dist/agent-runtime/loop/invocation-failure.d.ts.map +1 -0
  89. package/dist/agent-runtime/loop/invocation-payload.d.ts +38 -0
  90. package/dist/agent-runtime/loop/invocation-payload.d.ts.map +1 -0
  91. package/dist/agent-runtime/loop/invocation-read.d.ts +134 -0
  92. package/dist/agent-runtime/loop/invocation-read.d.ts.map +1 -0
  93. package/dist/agent-runtime/loop/invocation-spend.d.ts +9 -0
  94. package/dist/agent-runtime/loop/invocation-spend.d.ts.map +1 -0
  95. package/dist/agent-runtime/loop/invocation-stream.d.ts +20 -0
  96. package/dist/agent-runtime/loop/invocation-stream.d.ts.map +1 -0
  97. package/dist/agent-runtime/loop/invocations.d.ts +63 -0
  98. package/dist/agent-runtime/loop/invocations.d.ts.map +1 -0
  99. package/dist/agent-runtime/loop/managed-tools.d.ts +20 -0
  100. package/dist/agent-runtime/loop/managed-tools.d.ts.map +1 -0
  101. package/dist/agent-runtime/loop/observability.d.ts +579 -0
  102. package/dist/agent-runtime/loop/observability.d.ts.map +1 -0
  103. package/dist/agent-runtime/loop/owned-provider-stream.d.ts.map +1 -0
  104. package/dist/agent-runtime/loop/provider-origin.d.ts +17 -0
  105. package/dist/agent-runtime/loop/provider-origin.d.ts.map +1 -0
  106. package/dist/agent-runtime/loop/provider-stream-parts.d.ts +5 -0
  107. package/dist/agent-runtime/loop/provider-stream-parts.d.ts.map +1 -0
  108. package/dist/agent-runtime/loop/provider-stream-segments.d.ts +63 -0
  109. package/dist/agent-runtime/loop/provider-stream-segments.d.ts.map +1 -0
  110. package/dist/agent-runtime/loop/retry-policy.d.ts +49 -0
  111. package/dist/agent-runtime/loop/retry-policy.d.ts.map +1 -0
  112. package/dist/agent-runtime/loop/run-acquisition.d.ts +24 -0
  113. package/dist/agent-runtime/loop/run-acquisition.d.ts.map +1 -0
  114. package/dist/agent-runtime/loop/run-approval.d.ts +82 -0
  115. package/dist/agent-runtime/loop/run-approval.d.ts.map +1 -0
  116. package/dist/agent-runtime/loop/run-complete-retry.d.ts +24 -0
  117. package/dist/agent-runtime/loop/run-complete-retry.d.ts.map +1 -0
  118. package/dist/agent-runtime/loop/run-complete-stream.d.ts +9 -0
  119. package/dist/agent-runtime/loop/run-complete-stream.d.ts.map +1 -0
  120. package/dist/agent-runtime/loop/run-complete-types.d.ts +171 -0
  121. package/dist/agent-runtime/loop/run-complete-types.d.ts.map +1 -0
  122. package/dist/agent-runtime/loop/run-complete.d.ts +25 -0
  123. package/dist/agent-runtime/loop/run-complete.d.ts.map +1 -0
  124. package/dist/agent-runtime/loop/run-driver-compose.d.ts +21 -0
  125. package/dist/agent-runtime/loop/run-driver-compose.d.ts.map +1 -0
  126. package/dist/agent-runtime/loop/run-execution-state.d.ts +177 -0
  127. package/dist/agent-runtime/loop/run-execution-state.d.ts.map +1 -0
  128. package/dist/agent-runtime/loop/run-execution.d.ts +22 -0
  129. package/dist/agent-runtime/loop/run-execution.d.ts.map +1 -0
  130. package/dist/agent-runtime/loop/run-failure.d.ts +21 -0
  131. package/dist/agent-runtime/loop/run-failure.d.ts.map +1 -0
  132. package/dist/agent-runtime/loop/run-loop-events.d.ts +126 -0
  133. package/dist/agent-runtime/loop/run-loop-events.d.ts.map +1 -0
  134. package/dist/agent-runtime/loop/run-model-attempts.d.ts +6 -0
  135. package/dist/agent-runtime/loop/run-model-attempts.d.ts.map +1 -0
  136. package/dist/agent-runtime/loop/run-model-messages.d.ts +9 -0
  137. package/dist/agent-runtime/loop/run-model-messages.d.ts.map +1 -0
  138. package/dist/agent-runtime/loop/run-model-step.d.ts +43 -0
  139. package/dist/agent-runtime/loop/run-model-step.d.ts.map +1 -0
  140. package/dist/agent-runtime/loop/run-model-stream.d.ts +27 -0
  141. package/dist/agent-runtime/loop/run-model-stream.d.ts.map +1 -0
  142. package/dist/agent-runtime/loop/run-operation-lifecycle.d.ts +32 -0
  143. package/dist/agent-runtime/loop/run-operation-lifecycle.d.ts.map +1 -0
  144. package/dist/agent-runtime/loop/run-prompt-history.d.ts +53 -0
  145. package/dist/agent-runtime/loop/run-prompt-history.d.ts.map +1 -0
  146. package/dist/agent-runtime/loop/run-provider-ledger.d.ts +32 -0
  147. package/dist/agent-runtime/loop/run-provider-ledger.d.ts.map +1 -0
  148. package/dist/agent-runtime/loop/run-step-barriers.d.ts +120 -0
  149. package/dist/agent-runtime/loop/run-step-barriers.d.ts.map +1 -0
  150. package/dist/agent-runtime/loop/run-step-helpers.d.ts +50 -0
  151. package/dist/agent-runtime/loop/run-step-helpers.d.ts.map +1 -0
  152. package/dist/agent-runtime/loop/run-step-prepare.d.ts +34 -0
  153. package/dist/agent-runtime/loop/run-step-prepare.d.ts.map +1 -0
  154. package/dist/agent-runtime/loop/run-step-spend.d.ts +394 -0
  155. package/dist/agent-runtime/loop/run-step-spend.d.ts.map +1 -0
  156. package/dist/agent-runtime/loop/run-stream-parts.d.ts +34 -0
  157. package/dist/agent-runtime/loop/run-stream-parts.d.ts.map +1 -0
  158. package/dist/agent-runtime/loop/run-stream-recorded.d.ts +8 -0
  159. package/dist/agent-runtime/loop/run-stream-recorded.d.ts.map +1 -0
  160. package/dist/agent-runtime/loop/run-stream-step-text.d.ts +47 -0
  161. package/dist/agent-runtime/loop/run-stream-step-text.d.ts.map +1 -0
  162. package/dist/agent-runtime/loop/run-terminal.d.ts +11 -0
  163. package/dist/agent-runtime/loop/run-terminal.d.ts.map +1 -0
  164. package/dist/agent-runtime/loop/run-tool-approval-flow.d.ts +36 -0
  165. package/dist/agent-runtime/loop/run-tool-approval-flow.d.ts.map +1 -0
  166. package/dist/agent-runtime/loop/run-tool-approval-records.d.ts +24 -0
  167. package/dist/agent-runtime/loop/run-tool-approval-records.d.ts.map +1 -0
  168. package/dist/agent-runtime/loop/run-tool-call.d.ts +119 -0
  169. package/dist/agent-runtime/loop/run-tool-call.d.ts.map +1 -0
  170. package/dist/agent-runtime/loop/run-tool-errors.d.ts.map +1 -0
  171. package/dist/agent-runtime/loop/run-tool-executor.d.ts +42 -0
  172. package/dist/agent-runtime/loop/run-tool-executor.d.ts.map +1 -0
  173. package/dist/agent-runtime/loop/run-tool-progress.d.ts +21 -0
  174. package/dist/agent-runtime/loop/run-tool-progress.d.ts.map +1 -0
  175. package/dist/agent-runtime/loop/run-tool-slots.d.ts +114 -0
  176. package/dist/agent-runtime/loop/run-tool-slots.d.ts.map +1 -0
  177. package/dist/agent-runtime/loop/run-turn-preparation.d.ts +25 -0
  178. package/dist/agent-runtime/loop/run-turn-preparation.d.ts.map +1 -0
  179. package/dist/agent-runtime/loop/run-unacquired.d.ts +19 -0
  180. package/dist/agent-runtime/loop/run-unacquired.d.ts.map +1 -0
  181. package/dist/agent-runtime/loop/runtime-admission-gate.d.ts.map +1 -0
  182. package/dist/agent-runtime/loop/runtime-control.d.ts +9 -0
  183. package/dist/agent-runtime/loop/runtime-control.d.ts.map +1 -0
  184. package/dist/agent-runtime/loop/runtime-recovery.d.ts +10 -0
  185. package/dist/agent-runtime/loop/runtime-recovery.d.ts.map +1 -0
  186. package/dist/agent-runtime/loop/runtime-state.d.ts +36 -0
  187. package/dist/agent-runtime/loop/runtime-state.d.ts.map +1 -0
  188. package/dist/agent-runtime/loop/runtime-submit.d.ts +5 -0
  189. package/dist/agent-runtime/loop/runtime-submit.d.ts.map +1 -0
  190. package/dist/agent-runtime/loop/runtime.d.ts +352 -0
  191. package/dist/agent-runtime/loop/runtime.d.ts.map +1 -0
  192. package/dist/agent-runtime/loop/state-slots.d.ts +48 -0
  193. package/dist/agent-runtime/loop/state-slots.d.ts.map +1 -0
  194. package/dist/agent-runtime/loop/state-tools.d.ts +117 -0
  195. package/dist/agent-runtime/loop/state-tools.d.ts.map +1 -0
  196. package/dist/agent-runtime/protocol.d.ts +1 -1
  197. package/dist/agent-runtime/protocol.d.ts.map +1 -1
  198. package/dist/agent-runtime/providers/ai-sdk-convert.d.ts +15 -0
  199. package/dist/agent-runtime/providers/ai-sdk-convert.d.ts.map +1 -0
  200. package/dist/agent-runtime/providers/ai-sdk.d.ts +31 -0
  201. package/dist/agent-runtime/providers/ai-sdk.d.ts.map +1 -0
  202. package/dist/agent-runtime/providers/anthropic-media.d.ts +11 -0
  203. package/dist/agent-runtime/providers/anthropic-media.d.ts.map +1 -0
  204. package/dist/agent-runtime/providers/anthropic-messages.d.ts +25 -0
  205. package/dist/agent-runtime/providers/anthropic-messages.d.ts.map +1 -0
  206. package/dist/agent-runtime/providers/anthropic-options.d.ts +80 -0
  207. package/dist/agent-runtime/providers/anthropic-options.d.ts.map +1 -0
  208. package/dist/agent-runtime/providers/anthropic-response.d.ts +19 -0
  209. package/dist/agent-runtime/providers/anthropic-response.d.ts.map +1 -0
  210. package/dist/agent-runtime/providers/anthropic-sse.d.ts.map +1 -0
  211. package/dist/agent-runtime/providers/anthropic.d.ts.map +1 -0
  212. package/dist/agent-runtime/providers/models-driver-step.d.ts +212 -0
  213. package/dist/agent-runtime/providers/models-driver-step.d.ts.map +1 -0
  214. package/dist/agent-runtime/providers/models-driver-telemetry.d.ts.map +1 -0
  215. package/dist/agent-runtime/providers/models-driver.d.ts +235 -0
  216. package/dist/agent-runtime/providers/models-driver.d.ts.map +1 -0
  217. package/dist/agent-runtime/providers/models.d.ts.map +1 -0
  218. package/dist/agent-runtime/providers/openai-messages.d.ts.map +1 -0
  219. package/dist/agent-runtime/providers/openai-options.d.ts +91 -0
  220. package/dist/agent-runtime/providers/openai-options.d.ts.map +1 -0
  221. package/dist/agent-runtime/providers/openai-response.d.ts +77 -0
  222. package/dist/agent-runtime/providers/openai-response.d.ts.map +1 -0
  223. package/dist/agent-runtime/providers/openai-sse-state.d.ts.map +1 -0
  224. package/dist/agent-runtime/providers/openai-sse.d.ts.map +1 -0
  225. package/dist/agent-runtime/providers/openai.d.ts.map +1 -0
  226. package/dist/agent-runtime/providers/openrouter-admission.d.ts +85 -0
  227. package/dist/agent-runtime/providers/openrouter-admission.d.ts.map +1 -0
  228. package/dist/agent-runtime/providers/openrouter-audio.d.ts +122 -0
  229. package/dist/agent-runtime/providers/openrouter-audio.d.ts.map +1 -0
  230. package/dist/agent-runtime/providers/openrouter-benchmarks.d.ts.map +1 -0
  231. package/dist/agent-runtime/providers/openrouter-catalog-cache.d.ts.map +1 -0
  232. package/dist/agent-runtime/providers/openrouter-catalog-query.d.ts +82 -0
  233. package/dist/agent-runtime/providers/openrouter-catalog-query.d.ts.map +1 -0
  234. package/dist/agent-runtime/providers/openrouter-catalog.d.ts +260 -0
  235. package/dist/agent-runtime/providers/openrouter-catalog.d.ts.map +1 -0
  236. package/dist/agent-runtime/providers/openrouter-http.d.ts +100 -0
  237. package/dist/agent-runtime/providers/openrouter-http.d.ts.map +1 -0
  238. package/dist/agent-runtime/providers/openrouter-media.d.ts +160 -0
  239. package/dist/agent-runtime/providers/openrouter-media.d.ts.map +1 -0
  240. package/dist/agent-runtime/providers/openrouter-models.d.ts +203 -0
  241. package/dist/agent-runtime/providers/openrouter-models.d.ts.map +1 -0
  242. package/dist/agent-runtime/providers/openrouter-options.d.ts +138 -0
  243. package/dist/agent-runtime/providers/openrouter-options.d.ts.map +1 -0
  244. package/dist/agent-runtime/providers/openrouter-response.d.ts +22 -0
  245. package/dist/agent-runtime/providers/openrouter-response.d.ts.map +1 -0
  246. package/dist/agent-runtime/providers/openrouter-retrieval.d.ts +114 -0
  247. package/dist/agent-runtime/providers/openrouter-retrieval.d.ts.map +1 -0
  248. package/dist/agent-runtime/providers/openrouter-route.d.ts.map +1 -0
  249. package/dist/agent-runtime/providers/openrouter-spend.d.ts +28 -0
  250. package/dist/agent-runtime/providers/openrouter-spend.d.ts.map +1 -0
  251. package/dist/agent-runtime/providers/openrouter-stream.d.ts +29 -0
  252. package/dist/agent-runtime/providers/openrouter-stream.d.ts.map +1 -0
  253. package/dist/agent-runtime/providers/openrouter-systemone.d.ts +82 -0
  254. package/dist/agent-runtime/providers/openrouter-systemone.d.ts.map +1 -0
  255. package/dist/agent-runtime/providers/openrouter-url.d.ts +13 -0
  256. package/dist/agent-runtime/providers/openrouter-url.d.ts.map +1 -0
  257. package/dist/agent-runtime/providers/openrouter.d.ts +50 -0
  258. package/dist/agent-runtime/providers/openrouter.d.ts.map +1 -0
  259. package/dist/agent-runtime/providers/provider-cache.d.ts +30 -0
  260. package/dist/agent-runtime/providers/provider-cache.d.ts.map +1 -0
  261. package/dist/agent-runtime/providers/provider-content.d.ts.map +1 -0
  262. package/dist/agent-runtime/providers/provider-failure.d.ts +97 -0
  263. package/dist/agent-runtime/providers/provider-failure.d.ts.map +1 -0
  264. package/dist/agent-runtime/providers/provider-history.d.ts +13 -0
  265. package/dist/agent-runtime/providers/provider-history.d.ts.map +1 -0
  266. package/dist/agent-runtime/providers/provider-http.d.ts +82 -0
  267. package/dist/agent-runtime/providers/provider-http.d.ts.map +1 -0
  268. package/dist/agent-runtime/providers/provider-journal.d.ts.map +1 -0
  269. package/dist/agent-runtime/providers/provider-json-schema-strip.d.ts.map +1 -0
  270. package/dist/agent-runtime/providers/provider-json-schema.d.ts +31 -0
  271. package/dist/agent-runtime/providers/provider-json-schema.d.ts.map +1 -0
  272. package/dist/agent-runtime/providers/provider-media.d.ts +49 -0
  273. package/dist/agent-runtime/providers/provider-media.d.ts.map +1 -0
  274. package/dist/agent-runtime/providers/provider-openai-chat-helpers.d.ts +27 -0
  275. package/dist/agent-runtime/providers/provider-openai-chat-helpers.d.ts.map +1 -0
  276. package/dist/agent-runtime/providers/provider-openai-chat-sse.d.ts +25 -0
  277. package/dist/agent-runtime/providers/provider-openai-chat-sse.d.ts.map +1 -0
  278. package/dist/agent-runtime/providers/provider-openai-chat.d.ts +27 -0
  279. package/dist/agent-runtime/providers/provider-openai-chat.d.ts.map +1 -0
  280. package/dist/agent-runtime/providers/provider-sse.d.ts.map +1 -0
  281. package/dist/agent-runtime/providers/provider-usage.d.ts +24 -0
  282. package/dist/agent-runtime/providers/provider-usage.d.ts.map +1 -0
  283. package/dist/agent-runtime/realtime/harness-realtime.d.ts +53 -0
  284. package/dist/agent-runtime/realtime/harness-realtime.d.ts.map +1 -0
  285. package/dist/agent-runtime/sandbox/sandbox-binding.d.ts.map +1 -0
  286. package/dist/agent-runtime/sandbox/sandbox-broker.d.ts.map +1 -0
  287. package/dist/agent-runtime/sandbox/sandbox-bubblewrap-args.d.ts.map +1 -0
  288. package/dist/agent-runtime/sandbox/sandbox-bubblewrap-storage.d.ts.map +1 -0
  289. package/dist/agent-runtime/sandbox/sandbox-bubblewrap.d.ts.map +1 -0
  290. package/dist/agent-runtime/sandbox/sandbox-coding-adapter.d.ts.map +1 -0
  291. package/dist/agent-runtime/sandbox/sandbox-contract.d.ts.map +1 -0
  292. package/dist/agent-runtime/sandbox/sandbox-process-linux.d.ts.map +1 -0
  293. package/dist/agent-runtime/sandbox/sandbox-process-macos.d.ts.map +1 -0
  294. package/dist/agent-runtime/sandbox/sandbox-process-owner.d.ts +19 -0
  295. package/dist/agent-runtime/sandbox/sandbox-process-owner.d.ts.map +1 -0
  296. package/dist/agent-runtime/sandbox/sandbox-process-spec.d.ts.map +1 -0
  297. package/dist/agent-runtime/sandbox/sandbox-process-wrapper.d.ts.map +1 -0
  298. package/dist/agent-runtime/sandbox/sandbox-process.d.ts +8 -0
  299. package/dist/agent-runtime/sandbox/sandbox-process.d.ts.map +1 -0
  300. package/dist/agent-runtime/sandbox/sandbox-session.d.ts.map +1 -0
  301. package/dist/agent-runtime/sandbox/sandbox.d.ts +125 -0
  302. package/dist/agent-runtime/sandbox/sandbox.d.ts.map +1 -0
  303. package/dist/agent-runtime/stores/archive-projection.d.ts.map +1 -0
  304. package/dist/agent-runtime/stores/archive-spill.d.ts.map +1 -0
  305. package/dist/agent-runtime/stores/branch-contract.d.ts.map +1 -0
  306. package/dist/agent-runtime/stores/branch-events.d.ts +25 -0
  307. package/dist/agent-runtime/stores/branch-events.d.ts.map +1 -0
  308. package/dist/agent-runtime/stores/branch-identities.d.ts +75 -0
  309. package/dist/agent-runtime/stores/branch-identities.d.ts.map +1 -0
  310. package/dist/agent-runtime/stores/branch-messages.d.ts +21 -0
  311. package/dist/agent-runtime/stores/branch-messages.d.ts.map +1 -0
  312. package/dist/agent-runtime/stores/branch-observations.d.ts.map +1 -0
  313. package/dist/agent-runtime/stores/branch-provider.d.ts.map +1 -0
  314. package/dist/agent-runtime/stores/branch-refusal.d.ts.map +1 -0
  315. package/dist/agent-runtime/stores/branch-replay.d.ts +456 -0
  316. package/dist/agent-runtime/stores/branch-replay.d.ts.map +1 -0
  317. package/dist/agent-runtime/stores/branch-runtime-tools.d.ts.map +1 -0
  318. package/dist/agent-runtime/stores/branch-source.d.ts +33 -0
  319. package/dist/agent-runtime/stores/branch-source.d.ts.map +1 -0
  320. package/dist/agent-runtime/stores/branch-transitions.d.ts.map +1 -0
  321. package/dist/agent-runtime/stores/child-blocking.d.ts.map +1 -0
  322. package/dist/agent-runtime/stores/child-budget-policy.d.ts +17 -0
  323. package/dist/agent-runtime/stores/child-budget-policy.d.ts.map +1 -0
  324. package/dist/agent-runtime/stores/child-tools.d.ts +144 -0
  325. package/dist/agent-runtime/stores/child-tools.d.ts.map +1 -0
  326. package/dist/agent-runtime/stores/children-contract.d.ts +236 -0
  327. package/dist/agent-runtime/stores/children-contract.d.ts.map +1 -0
  328. package/dist/agent-runtime/stores/children-control.d.ts.map +1 -0
  329. package/dist/agent-runtime/stores/children-spawn.d.ts.map +1 -0
  330. package/dist/agent-runtime/stores/children-state.d.ts.map +1 -0
  331. package/dist/agent-runtime/stores/children-usage.d.ts.map +1 -0
  332. package/dist/agent-runtime/stores/children.d.ts.map +1 -0
  333. package/dist/agent-runtime/stores/companion-host.d.ts +38 -0
  334. package/dist/agent-runtime/stores/companion-host.d.ts.map +1 -0
  335. package/dist/agent-runtime/stores/conversations.d.ts.map +1 -0
  336. package/dist/agent-runtime/stores/event-search-postgres.d.ts.map +1 -0
  337. package/dist/agent-runtime/stores/event-search-terms.d.ts.map +1 -0
  338. package/dist/agent-runtime/stores/event-search-tools.d.ts +190 -0
  339. package/dist/agent-runtime/stores/event-search-tools.d.ts.map +1 -0
  340. package/dist/agent-runtime/stores/event-search.d.ts.map +1 -0
  341. package/dist/agent-runtime/stores/postgres-schema.d.ts.map +1 -0
  342. package/dist/agent-runtime/stores/postgres-transactions.d.ts +54 -0
  343. package/dist/agent-runtime/stores/postgres-transactions.d.ts.map +1 -0
  344. package/dist/agent-runtime/stores/postgres.d.ts +72 -0
  345. package/dist/agent-runtime/stores/postgres.d.ts.map +1 -0
  346. package/dist/agent-runtime/stores/projections.d.ts +109 -0
  347. package/dist/agent-runtime/stores/projections.d.ts.map +1 -0
  348. package/dist/agent-runtime/stores/purge.d.ts.map +1 -0
  349. package/dist/agent-runtime/stores/schedule-contract.d.ts.map +1 -0
  350. package/dist/agent-runtime/stores/schedule-dispatch.d.ts.map +1 -0
  351. package/dist/agent-runtime/stores/schedule-records.d.ts.map +1 -0
  352. package/dist/agent-runtime/stores/schedule-tools.d.ts +76 -0
  353. package/dist/agent-runtime/stores/schedule-tools.d.ts.map +1 -0
  354. package/dist/agent-runtime/stores/schedules.d.ts.map +1 -0
  355. package/dist/agent-runtime/stores/spill.d.ts +26 -0
  356. package/dist/agent-runtime/stores/spill.d.ts.map +1 -0
  357. package/dist/agent-runtime/stores/sql-events.d.ts.map +1 -0
  358. package/dist/agent-runtime/stores/sql-history.d.ts.map +1 -0
  359. package/dist/agent-runtime/stores/sql-ledger.d.ts.map +1 -0
  360. package/dist/agent-runtime/stores/sql-purge.d.ts.map +1 -0
  361. package/dist/agent-runtime/stores/sql-reads.d.ts.map +1 -0
  362. package/dist/agent-runtime/stores/sql-rows.d.ts.map +1 -0
  363. package/dist/agent-runtime/stores/sql-session.d.ts.map +1 -0
  364. package/dist/agent-runtime/stores/sqlite-bun.d.ts.map +1 -0
  365. package/dist/agent-runtime/stores/sqlite-node.d.ts.map +1 -0
  366. package/dist/agent-runtime/stores/sqlite-purge.d.ts +6 -0
  367. package/dist/agent-runtime/stores/sqlite-purge.d.ts.map +1 -0
  368. package/dist/agent-runtime/stores/sqlite-schema.d.ts +7 -0
  369. package/dist/agent-runtime/stores/sqlite-schema.d.ts.map +1 -0
  370. package/dist/agent-runtime/stores/sqlite-transactions.d.ts +29 -0
  371. package/dist/agent-runtime/stores/sqlite-transactions.d.ts.map +1 -0
  372. package/dist/agent-runtime/stores/sqlite.d.ts +33 -0
  373. package/dist/agent-runtime/stores/sqlite.d.ts.map +1 -0
  374. package/dist/agent-runtime/stores/store-archive.d.ts.map +1 -0
  375. package/dist/agent-runtime/stores/store-branch.d.ts.map +1 -0
  376. package/dist/agent-runtime/stores/store-capabilities.d.ts.map +1 -0
  377. package/dist/agent-runtime/stores/store-create.d.ts.map +1 -0
  378. package/dist/agent-runtime/stores/store-driver-contract.d.ts +1016 -0
  379. package/dist/agent-runtime/stores/store-driver-contract.d.ts.map +1 -0
  380. package/dist/agent-runtime/stores/store-event-once.d.ts +37 -0
  381. package/dist/agent-runtime/stores/store-event-once.d.ts.map +1 -0
  382. package/dist/agent-runtime/stores/store-events.d.ts +2231 -0
  383. package/dist/agent-runtime/stores/store-events.d.ts.map +1 -0
  384. package/dist/agent-runtime/stores/store-memory-archive.d.ts.map +1 -0
  385. package/dist/agent-runtime/stores/store-memory-events.d.ts +7 -0
  386. package/dist/agent-runtime/stores/store-memory-events.d.ts.map +1 -0
  387. package/dist/agent-runtime/stores/store-memory.d.ts.map +1 -0
  388. package/dist/agent-runtime/stores/store-migrations/v1-to-v2.d.ts +6 -0
  389. package/dist/agent-runtime/stores/store-migrations/v1-to-v2.d.ts.map +1 -0
  390. package/dist/agent-runtime/stores/store-migrations/v2-to-v3.d.ts +14 -0
  391. package/dist/agent-runtime/stores/store-migrations/v2-to-v3.d.ts.map +1 -0
  392. package/dist/agent-runtime/stores/store-migrations/v3-to-v4.d.ts +4 -0
  393. package/dist/agent-runtime/stores/store-migrations/v3-to-v4.d.ts.map +1 -0
  394. package/dist/agent-runtime/stores/store-mutate.d.ts.map +1 -0
  395. package/dist/agent-runtime/stores/store-purge.d.ts.map +1 -0
  396. package/dist/agent-runtime/stores/store-reads.d.ts +29 -0
  397. package/dist/agent-runtime/stores/store-reads.d.ts.map +1 -0
  398. package/dist/agent-runtime/stores/store-reduce-history.d.ts +10 -0
  399. package/dist/agent-runtime/stores/store-reduce-history.d.ts.map +1 -0
  400. package/dist/agent-runtime/stores/store-reduce-run.d.ts +14 -0
  401. package/dist/agent-runtime/stores/store-reduce-run.d.ts.map +1 -0
  402. package/dist/agent-runtime/stores/store-reduce-shared.d.ts +78 -0
  403. package/dist/agent-runtime/stores/store-reduce-shared.d.ts.map +1 -0
  404. package/dist/agent-runtime/stores/store-reduce-terminal.d.ts +6 -0
  405. package/dist/agent-runtime/stores/store-reduce-terminal.d.ts.map +1 -0
  406. package/dist/agent-runtime/stores/store-reducer.d.ts +24 -0
  407. package/dist/agent-runtime/stores/store-reducer.d.ts.map +1 -0
  408. package/dist/agent-runtime/stores/store-replay.d.ts.map +1 -0
  409. package/dist/agent-runtime/stores/store-snapshot.d.ts +19 -0
  410. package/dist/agent-runtime/stores/store-snapshot.d.ts.map +1 -0
  411. package/dist/agent-runtime/stores/store.d.ts +3032 -0
  412. package/dist/agent-runtime/stores/store.d.ts.map +1 -0
  413. package/dist/agent-runtime/terminal-commit.d.ts +1 -1
  414. package/dist/agent-runtime/terminal-commit.d.ts.map +1 -1
  415. package/dist/agent-runtime/testing/fault-bench.d.ts.map +1 -0
  416. package/dist/agent-runtime/testing/run-assertions.d.ts +63 -0
  417. package/dist/agent-runtime/testing/run-assertions.d.ts.map +1 -0
  418. package/dist/agent-runtime/testing/store-conformance-branch.d.ts +7 -0
  419. package/dist/agent-runtime/testing/store-conformance-branch.d.ts.map +1 -0
  420. package/dist/agent-runtime/testing/store-conformance-capabilities.d.ts +6 -0
  421. package/dist/agent-runtime/testing/store-conformance-capabilities.d.ts.map +1 -0
  422. package/dist/agent-runtime/testing/store-conformance-event-once.d.ts +12 -0
  423. package/dist/agent-runtime/testing/store-conformance-event-once.d.ts.map +1 -0
  424. package/dist/agent-runtime/testing/store-conformance-lifecycle.d.ts +454 -0
  425. package/dist/agent-runtime/testing/store-conformance-lifecycle.d.ts.map +1 -0
  426. package/dist/agent-runtime/testing/store-conformance-ordering.d.ts +18 -0
  427. package/dist/agent-runtime/testing/store-conformance-ordering.d.ts.map +1 -0
  428. package/dist/agent-runtime/testing/store-conformance-seed.d.ts +8 -0
  429. package/dist/agent-runtime/testing/store-conformance-seed.d.ts.map +1 -0
  430. package/dist/agent-runtime/testing/store-conformance-support.d.ts +140 -0
  431. package/dist/agent-runtime/testing/store-conformance-support.d.ts.map +1 -0
  432. package/dist/agent-runtime/testing/store-conformance-terminal.d.ts +12 -0
  433. package/dist/agent-runtime/testing/store-conformance-terminal.d.ts.map +1 -0
  434. package/dist/agent-runtime/testing/store-conformance.d.ts +71 -0
  435. package/dist/agent-runtime/testing/store-conformance.d.ts.map +1 -0
  436. package/dist/agent-runtime/testing/testing.d.ts +46 -0
  437. package/dist/agent-runtime/testing/testing.d.ts.map +1 -0
  438. package/dist/browser/client-executors.d.ts.map +1 -1
  439. package/dist/browser/client.d.ts +3 -2
  440. package/dist/browser/client.d.ts.map +1 -1
  441. package/dist/browser/http.d.ts +6 -3
  442. package/dist/browser/http.d.ts.map +1 -1
  443. package/dist/contract/client-types.d.ts +4 -3
  444. package/dist/contract/client-types.d.ts.map +1 -1
  445. package/dist/entrypoints/agent-executor/acp.js +38 -12
  446. package/dist/entrypoints/agent-executor/claude-sdk.js +1 -1
  447. package/dist/entrypoints/agent-executor/codex.js +2 -2
  448. package/dist/entrypoints/agent-executor/testing/claude-sdk.js +3 -3
  449. package/dist/entrypoints/agent-executor/testing.js +3 -3
  450. package/dist/entrypoints/agent-executor.js +1 -1
  451. package/dist/entrypoints/agent-runtime/ai-sdk.d.ts +3 -3
  452. package/dist/entrypoints/agent-runtime/ai-sdk.d.ts.map +1 -1
  453. package/dist/entrypoints/agent-runtime/ai-sdk.js +9 -8
  454. package/dist/entrypoints/agent-runtime/anthropic.d.ts +3 -3
  455. package/dist/entrypoints/agent-runtime/anthropic.d.ts.map +1 -1
  456. package/dist/entrypoints/agent-runtime/anthropic.js +72 -18
  457. package/dist/entrypoints/agent-runtime/browser.d.ts +6 -6
  458. package/dist/entrypoints/agent-runtime/browser.d.ts.map +1 -1
  459. package/dist/entrypoints/agent-runtime/browser.js +39 -39
  460. package/dist/entrypoints/agent-runtime/coding-tools.d.ts +1 -1
  461. package/dist/entrypoints/agent-runtime/coding-tools.d.ts.map +1 -1
  462. package/dist/entrypoints/agent-runtime/coding-tools.js +2 -2
  463. package/dist/entrypoints/agent-runtime/harness.d.ts +1 -1
  464. package/dist/entrypoints/agent-runtime/harness.d.ts.map +1 -1
  465. package/dist/entrypoints/agent-runtime/harness.js +27 -28
  466. package/dist/entrypoints/agent-runtime/openai.d.ts +3 -3
  467. package/dist/entrypoints/agent-runtime/openai.d.ts.map +1 -1
  468. package/dist/entrypoints/agent-runtime/openai.js +9 -9
  469. package/dist/entrypoints/agent-runtime/openrouter.d.ts +17 -10
  470. package/dist/entrypoints/agent-runtime/openrouter.d.ts.map +1 -1
  471. package/dist/entrypoints/agent-runtime/openrouter.js +1657 -400
  472. package/dist/entrypoints/agent-runtime/postgres.d.ts +2 -2
  473. package/dist/entrypoints/agent-runtime/postgres.d.ts.map +1 -1
  474. package/dist/entrypoints/agent-runtime/postgres.js +8 -8
  475. package/dist/entrypoints/agent-runtime/react.d.ts +1 -1
  476. package/dist/entrypoints/agent-runtime/react.d.ts.map +1 -1
  477. package/dist/entrypoints/agent-runtime/react.js +1 -1
  478. package/dist/entrypoints/agent-runtime/realtime.d.ts +1 -1
  479. package/dist/entrypoints/agent-runtime/realtime.d.ts.map +1 -1
  480. package/dist/entrypoints/agent-runtime/realtime.js +5 -5
  481. package/dist/entrypoints/agent-runtime/sandbox.d.ts +9 -9
  482. package/dist/entrypoints/agent-runtime/sandbox.d.ts.map +1 -1
  483. package/dist/entrypoints/agent-runtime/sandbox.js +220 -93
  484. package/dist/entrypoints/agent-runtime/sqlite/bun.d.ts +1 -1
  485. package/dist/entrypoints/agent-runtime/sqlite/bun.d.ts.map +1 -1
  486. package/dist/entrypoints/agent-runtime/sqlite/bun.js +8 -8
  487. package/dist/entrypoints/agent-runtime/sqlite/node.d.ts +1 -1
  488. package/dist/entrypoints/agent-runtime/sqlite/node.d.ts.map +1 -1
  489. package/dist/entrypoints/agent-runtime/sqlite/node.js +8 -8
  490. package/dist/entrypoints/agent-runtime/testing.d.ts +4 -4
  491. package/dist/entrypoints/agent-runtime/testing.d.ts.map +1 -1
  492. package/dist/entrypoints/agent-runtime/testing.js +21 -21
  493. package/dist/entrypoints/agent-runtime.d.ts +50 -50
  494. package/dist/entrypoints/agent-runtime.d.ts.map +1 -1
  495. package/dist/entrypoints/agent-runtime.js +2853 -3107
  496. package/dist/entrypoints/cli.js +8 -9
  497. package/dist/entrypoints/http.js +2 -2
  498. package/dist/entrypoints/index.js +2 -2
  499. package/dist/entrypoints/react.js +1 -1
  500. package/dist/entrypoints/remote.js +2 -2
  501. package/dist/entrypoints/server.js +2 -2
  502. package/dist/entrypoints/testing.js +7 -9
  503. package/dist/entrypoints/tools/agent.js +476 -13
  504. package/dist/entrypoints/tools/connections.js +9 -7
  505. package/dist/entrypoints/tools/contract.js +4 -4
  506. package/dist/entrypoints/tools/invoker.js +7 -8
  507. package/dist/entrypoints/tools/mcp.js +9 -11
  508. package/dist/entrypoints/tools/toolkit.d.ts +6 -4
  509. package/dist/entrypoints/tools/toolkit.d.ts.map +1 -1
  510. package/dist/entrypoints/tools/toolkit.js +11 -18
  511. package/dist/entrypoints/tools.js +12 -13
  512. package/dist/index-125ks2ec.js +17 -0
  513. package/dist/index-1w69rj9f.js +224 -0
  514. package/dist/index-1zy31r3b.js +26 -0
  515. package/dist/index-3czc3ykr.js +53 -0
  516. package/dist/index-3d2c45jn.js +77 -0
  517. package/dist/index-57sbckhv.js +271 -0
  518. package/dist/index-64t6pheq.js +2872 -0
  519. package/dist/index-73wq9abg.js +367 -0
  520. package/dist/index-84tp547a.js +981 -0
  521. package/dist/index-9be3tf6r.js +196 -0
  522. package/dist/index-asnd4h2k.js +969 -0
  523. package/dist/index-b4c9dpzm.js +1210 -0
  524. package/dist/index-baba8ehy.js +53 -0
  525. package/dist/index-c24bj2r1.js +510 -0
  526. package/dist/index-cgjtj8zh.js +707 -0
  527. package/dist/index-d4at0q09.js +601 -0
  528. package/dist/index-de7b0kvz.js +215 -0
  529. package/dist/index-dm84tsd5.js +164 -0
  530. package/dist/index-fsw9wxk9.js +349 -0
  531. package/dist/index-gk6dq9ay.js +124 -0
  532. package/dist/index-gs0jw0hy.js +174 -0
  533. package/dist/index-hce3hbdg.js +121 -0
  534. package/dist/index-ht71v1ag.js +730 -0
  535. package/dist/index-mcv7b2n0.js +3545 -0
  536. package/dist/index-n9358ydy.js +63 -0
  537. package/dist/index-npfdymav.js +409 -0
  538. package/dist/index-p9cab61p.js +305 -0
  539. package/dist/index-q86qnzzf.js +231 -0
  540. package/dist/index-qcy8et93.js +698 -0
  541. package/dist/index-refgnzy0.js +158 -0
  542. package/dist/index-rkphknhx.js +40 -0
  543. package/dist/index-v0j22shs.js +3781 -0
  544. package/dist/index-vse7x1qt.js +460 -0
  545. package/dist/index-wdb5jhas.js +51 -0
  546. package/dist/index-ws0awmzq.js +47 -0
  547. package/dist/index-wsv11dhg.js +725 -0
  548. package/dist/index-xbb8ysmq.js +40 -0
  549. package/dist/index-y0mwkgkf.js +7812 -0
  550. package/dist/index-yhwx4fwk.js +295 -0
  551. package/dist/index-z72vazf5.js +502 -0
  552. package/dist/json-schema/dialect.d.ts.map +1 -1
  553. package/dist/json-schema/string-format.d.ts.map +1 -1
  554. package/dist/tools/agent-call-context.d.ts +23 -0
  555. package/dist/tools/agent-call-context.d.ts.map +1 -0
  556. package/dist/tools/agent.d.ts.map +1 -1
  557. package/dist/tools/schema/flatten.d.ts.map +1 -1
  558. package/dist/tools/toolkit.d.ts +8 -6
  559. package/dist/tools/toolkit.d.ts.map +1 -1
  560. package/llms/agent-runtime-ai-sdk.txt +2 -2
  561. package/llms/agent-runtime-anthropic.txt +8 -4
  562. package/llms/agent-runtime-openrouter.txt +14 -6
  563. package/llms/agent-runtime-sandbox.txt +20 -7
  564. package/llms/agent-runtime.2.txt +333 -224
  565. package/llms/agent-runtime.3.txt +225 -364
  566. package/llms/agent-runtime.4.txt +381 -158
  567. package/llms/agent-runtime.5.txt +157 -152
  568. package/llms/agent-runtime.6.txt +164 -0
  569. package/llms/agent-runtime.txt +50 -339
  570. package/llms/cli.2.txt +8 -5
  571. package/llms/contract.txt +1 -1
  572. package/llms/server.txt +10 -6
  573. package/llms/spend.txt +17 -1
  574. package/llms/stitchkit.2.txt +18 -11
  575. package/llms/stitchkit.txt +85 -85
  576. package/llms/tools-toolkit.txt +3 -6
  577. package/llms/tools.4.txt +3 -3
  578. package/llms/upgrading-0.128.0-0.135.0.txt +700 -0
  579. package/llms/upgrading.txt +1 -1
  580. package/llms-full.txt +317 -149
  581. package/llms.txt +13 -13
  582. package/package.json +1 -1
  583. package/dist/agent-runtime/admission-lanes.d.ts +0 -35
  584. package/dist/agent-runtime/admission-lanes.d.ts.map +0 -1
  585. package/dist/agent-runtime/ai-sdk-convert.d.ts +0 -15
  586. package/dist/agent-runtime/ai-sdk-convert.d.ts.map +0 -1
  587. package/dist/agent-runtime/ai-sdk.d.ts +0 -31
  588. package/dist/agent-runtime/ai-sdk.d.ts.map +0 -1
  589. package/dist/agent-runtime/anthropic-media.d.ts +0 -11
  590. package/dist/agent-runtime/anthropic-media.d.ts.map +0 -1
  591. package/dist/agent-runtime/anthropic-messages.d.ts +0 -24
  592. package/dist/agent-runtime/anthropic-messages.d.ts.map +0 -1
  593. package/dist/agent-runtime/anthropic-options.d.ts +0 -79
  594. package/dist/agent-runtime/anthropic-options.d.ts.map +0 -1
  595. package/dist/agent-runtime/anthropic-response.d.ts +0 -19
  596. package/dist/agent-runtime/anthropic-response.d.ts.map +0 -1
  597. package/dist/agent-runtime/anthropic-sse.d.ts.map +0 -1
  598. package/dist/agent-runtime/anthropic.d.ts.map +0 -1
  599. package/dist/agent-runtime/archive-projection.d.ts.map +0 -1
  600. package/dist/agent-runtime/archive-spill.d.ts.map +0 -1
  601. package/dist/agent-runtime/branch-contract.d.ts.map +0 -1
  602. package/dist/agent-runtime/branch-events.d.ts +0 -25
  603. package/dist/agent-runtime/branch-events.d.ts.map +0 -1
  604. package/dist/agent-runtime/branch-identities.d.ts +0 -75
  605. package/dist/agent-runtime/branch-identities.d.ts.map +0 -1
  606. package/dist/agent-runtime/branch-messages.d.ts +0 -21
  607. package/dist/agent-runtime/branch-messages.d.ts.map +0 -1
  608. package/dist/agent-runtime/branch-observations.d.ts.map +0 -1
  609. package/dist/agent-runtime/branch-provider.d.ts.map +0 -1
  610. package/dist/agent-runtime/branch-refusal.d.ts.map +0 -1
  611. package/dist/agent-runtime/branch-replay.d.ts +0 -456
  612. package/dist/agent-runtime/branch-replay.d.ts.map +0 -1
  613. package/dist/agent-runtime/branch-runtime-tools.d.ts.map +0 -1
  614. package/dist/agent-runtime/branch-source.d.ts +0 -33
  615. package/dist/agent-runtime/branch-source.d.ts.map +0 -1
  616. package/dist/agent-runtime/branch-transitions.d.ts.map +0 -1
  617. package/dist/agent-runtime/browser-control-contract.d.ts +0 -1364
  618. package/dist/agent-runtime/browser-control-contract.d.ts.map +0 -1
  619. package/dist/agent-runtime/browser-controller-view.d.ts +0 -44
  620. package/dist/agent-runtime/browser-controller-view.d.ts.map +0 -1
  621. package/dist/agent-runtime/browser-controller.d.ts +0 -53
  622. package/dist/agent-runtime/browser-controller.d.ts.map +0 -1
  623. package/dist/agent-runtime/child-blocking.d.ts.map +0 -1
  624. package/dist/agent-runtime/child-budget-policy.d.ts +0 -17
  625. package/dist/agent-runtime/child-budget-policy.d.ts.map +0 -1
  626. package/dist/agent-runtime/child-tools.d.ts +0 -144
  627. package/dist/agent-runtime/child-tools.d.ts.map +0 -1
  628. package/dist/agent-runtime/children-contract.d.ts +0 -236
  629. package/dist/agent-runtime/children-contract.d.ts.map +0 -1
  630. package/dist/agent-runtime/children-control.d.ts.map +0 -1
  631. package/dist/agent-runtime/children-spawn.d.ts.map +0 -1
  632. package/dist/agent-runtime/children-state.d.ts.map +0 -1
  633. package/dist/agent-runtime/children-usage.d.ts.map +0 -1
  634. package/dist/agent-runtime/children.d.ts.map +0 -1
  635. package/dist/agent-runtime/coding-discovery.d.ts +0 -25
  636. package/dist/agent-runtime/coding-discovery.d.ts.map +0 -1
  637. package/dist/agent-runtime/coding-sandbox.d.ts +0 -8
  638. package/dist/agent-runtime/coding-sandbox.d.ts.map +0 -1
  639. package/dist/agent-runtime/coding-search-automaton.d.ts.map +0 -1
  640. package/dist/agent-runtime/coding-search-case-fold.d.ts.map +0 -1
  641. package/dist/agent-runtime/coding-search-class-ranges.d.ts.map +0 -1
  642. package/dist/agent-runtime/coding-search-contract.d.ts.map +0 -1
  643. package/dist/agent-runtime/coding-search-limits.d.ts.map +0 -1
  644. package/dist/agent-runtime/coding-search-matcher.d.ts.map +0 -1
  645. package/dist/agent-runtime/coding-search-output.d.ts.map +0 -1
  646. package/dist/agent-runtime/coding-search-regex-syntax.d.ts.map +0 -1
  647. package/dist/agent-runtime/coding-search-unit-classes.d.ts.map +0 -1
  648. package/dist/agent-runtime/coding-shell-process.d.ts +0 -36
  649. package/dist/agent-runtime/coding-shell-process.d.ts.map +0 -1
  650. package/dist/agent-runtime/coding-tool-contract.d.ts +0 -261
  651. package/dist/agent-runtime/coding-tool-contract.d.ts.map +0 -1
  652. package/dist/agent-runtime/coding-tool-files.d.ts.map +0 -1
  653. package/dist/agent-runtime/coding-tool-listing.d.ts.map +0 -1
  654. package/dist/agent-runtime/coding-tool-paths.d.ts +0 -53
  655. package/dist/agent-runtime/coding-tool-paths.d.ts.map +0 -1
  656. package/dist/agent-runtime/coding-tool-refusals.d.ts.map +0 -1
  657. package/dist/agent-runtime/coding-tool-search-patch.d.ts.map +0 -1
  658. package/dist/agent-runtime/coding-tool-search.d.ts +0 -113
  659. package/dist/agent-runtime/coding-tool-search.d.ts.map +0 -1
  660. package/dist/agent-runtime/coding-tool-shell.d.ts.map +0 -1
  661. package/dist/agent-runtime/coding-tool-utf8.d.ts.map +0 -1
  662. package/dist/agent-runtime/coding-tools.d.ts.map +0 -1
  663. package/dist/agent-runtime/compaction.d.ts +0 -103
  664. package/dist/agent-runtime/compaction.d.ts.map +0 -1
  665. package/dist/agent-runtime/companion-host.d.ts +0 -38
  666. package/dist/agent-runtime/companion-host.d.ts.map +0 -1
  667. package/dist/agent-runtime/contained-scan-budget.d.ts.map +0 -1
  668. package/dist/agent-runtime/contained-scan-contract.d.ts.map +0 -1
  669. package/dist/agent-runtime/contained-scan.d.ts +0 -56
  670. package/dist/agent-runtime/contained-scan.d.ts.map +0 -1
  671. package/dist/agent-runtime/control-interaction-schema.d.ts.map +0 -1
  672. package/dist/agent-runtime/control-schema.d.ts +0 -1378
  673. package/dist/agent-runtime/control-schema.d.ts.map +0 -1
  674. package/dist/agent-runtime/control-view.d.ts +0 -64
  675. package/dist/agent-runtime/control-view.d.ts.map +0 -1
  676. package/dist/agent-runtime/conversations.d.ts.map +0 -1
  677. package/dist/agent-runtime/coordinator.d.ts.map +0 -1
  678. package/dist/agent-runtime/deferred-tool-search.d.ts +0 -9
  679. package/dist/agent-runtime/deferred-tool-search.d.ts.map +0 -1
  680. package/dist/agent-runtime/deferred-tool-selection.d.ts +0 -32
  681. package/dist/agent-runtime/deferred-tool-selection.d.ts.map +0 -1
  682. package/dist/agent-runtime/deferred-tools-internal.d.ts +0 -9
  683. package/dist/agent-runtime/deferred-tools-internal.d.ts.map +0 -1
  684. package/dist/agent-runtime/deferred-tools.d.ts +0 -4
  685. package/dist/agent-runtime/deferred-tools.d.ts.map +0 -1
  686. package/dist/agent-runtime/event-search-postgres.d.ts.map +0 -1
  687. package/dist/agent-runtime/event-search-terms.d.ts.map +0 -1
  688. package/dist/agent-runtime/event-search-tools.d.ts +0 -190
  689. package/dist/agent-runtime/event-search-tools.d.ts.map +0 -1
  690. package/dist/agent-runtime/event-search.d.ts.map +0 -1
  691. package/dist/agent-runtime/fault-bench.d.ts.map +0 -1
  692. package/dist/agent-runtime/harness-contract.d.ts +0 -206
  693. package/dist/agent-runtime/harness-contract.d.ts.map +0 -1
  694. package/dist/agent-runtime/harness-control.d.ts +0 -34
  695. package/dist/agent-runtime/harness-control.d.ts.map +0 -1
  696. package/dist/agent-runtime/harness-file-resources.d.ts +0 -33
  697. package/dist/agent-runtime/harness-file-resources.d.ts.map +0 -1
  698. package/dist/agent-runtime/harness-realtime.d.ts +0 -53
  699. package/dist/agent-runtime/harness-realtime.d.ts.map +0 -1
  700. package/dist/agent-runtime/harness-resources.d.ts.map +0 -1
  701. package/dist/agent-runtime/harness.d.ts +0 -15
  702. package/dist/agent-runtime/harness.d.ts.map +0 -1
  703. package/dist/agent-runtime/history.d.ts +0 -93
  704. package/dist/agent-runtime/history.d.ts.map +0 -1
  705. package/dist/agent-runtime/injection.d.ts +0 -28
  706. package/dist/agent-runtime/injection.d.ts.map +0 -1
  707. package/dist/agent-runtime/invocation-attempt.d.ts +0 -32
  708. package/dist/agent-runtime/invocation-attempt.d.ts.map +0 -1
  709. package/dist/agent-runtime/invocation-failure.d.ts.map +0 -1
  710. package/dist/agent-runtime/invocation-payload.d.ts +0 -38
  711. package/dist/agent-runtime/invocation-payload.d.ts.map +0 -1
  712. package/dist/agent-runtime/invocation-read.d.ts +0 -134
  713. package/dist/agent-runtime/invocation-read.d.ts.map +0 -1
  714. package/dist/agent-runtime/invocation-spend.d.ts +0 -9
  715. package/dist/agent-runtime/invocation-spend.d.ts.map +0 -1
  716. package/dist/agent-runtime/invocation-stream.d.ts +0 -20
  717. package/dist/agent-runtime/invocation-stream.d.ts.map +0 -1
  718. package/dist/agent-runtime/invocations.d.ts +0 -63
  719. package/dist/agent-runtime/invocations.d.ts.map +0 -1
  720. package/dist/agent-runtime/managed-tools.d.ts +0 -20
  721. package/dist/agent-runtime/managed-tools.d.ts.map +0 -1
  722. package/dist/agent-runtime/models-driver-step.d.ts +0 -212
  723. package/dist/agent-runtime/models-driver-step.d.ts.map +0 -1
  724. package/dist/agent-runtime/models-driver-telemetry.d.ts.map +0 -1
  725. package/dist/agent-runtime/models-driver.d.ts +0 -235
  726. package/dist/agent-runtime/models-driver.d.ts.map +0 -1
  727. package/dist/agent-runtime/models.d.ts.map +0 -1
  728. package/dist/agent-runtime/observability.d.ts +0 -579
  729. package/dist/agent-runtime/observability.d.ts.map +0 -1
  730. package/dist/agent-runtime/openai-messages.d.ts.map +0 -1
  731. package/dist/agent-runtime/openai-options.d.ts +0 -91
  732. package/dist/agent-runtime/openai-options.d.ts.map +0 -1
  733. package/dist/agent-runtime/openai-response.d.ts +0 -77
  734. package/dist/agent-runtime/openai-response.d.ts.map +0 -1
  735. package/dist/agent-runtime/openai-sse-state.d.ts.map +0 -1
  736. package/dist/agent-runtime/openai-sse.d.ts.map +0 -1
  737. package/dist/agent-runtime/openai.d.ts.map +0 -1
  738. package/dist/agent-runtime/openrouter-admission.d.ts +0 -84
  739. package/dist/agent-runtime/openrouter-admission.d.ts.map +0 -1
  740. package/dist/agent-runtime/openrouter-benchmarks.d.ts.map +0 -1
  741. package/dist/agent-runtime/openrouter-catalog-cache.d.ts.map +0 -1
  742. package/dist/agent-runtime/openrouter-catalog-query.d.ts +0 -57
  743. package/dist/agent-runtime/openrouter-catalog-query.d.ts.map +0 -1
  744. package/dist/agent-runtime/openrouter-catalog.d.ts +0 -258
  745. package/dist/agent-runtime/openrouter-catalog.d.ts.map +0 -1
  746. package/dist/agent-runtime/openrouter-models.d.ts +0 -203
  747. package/dist/agent-runtime/openrouter-models.d.ts.map +0 -1
  748. package/dist/agent-runtime/openrouter-options.d.ts +0 -136
  749. package/dist/agent-runtime/openrouter-options.d.ts.map +0 -1
  750. package/dist/agent-runtime/openrouter-response.d.ts +0 -22
  751. package/dist/agent-runtime/openrouter-response.d.ts.map +0 -1
  752. package/dist/agent-runtime/openrouter-route.d.ts.map +0 -1
  753. package/dist/agent-runtime/openrouter-spend.d.ts +0 -24
  754. package/dist/agent-runtime/openrouter-spend.d.ts.map +0 -1
  755. package/dist/agent-runtime/openrouter.d.ts +0 -47
  756. package/dist/agent-runtime/openrouter.d.ts.map +0 -1
  757. package/dist/agent-runtime/owned-provider-stream.d.ts.map +0 -1
  758. package/dist/agent-runtime/postgres-schema.d.ts.map +0 -1
  759. package/dist/agent-runtime/postgres-transactions.d.ts +0 -54
  760. package/dist/agent-runtime/postgres-transactions.d.ts.map +0 -1
  761. package/dist/agent-runtime/postgres.d.ts +0 -72
  762. package/dist/agent-runtime/postgres.d.ts.map +0 -1
  763. package/dist/agent-runtime/projections.d.ts +0 -109
  764. package/dist/agent-runtime/projections.d.ts.map +0 -1
  765. package/dist/agent-runtime/provider-cache.d.ts +0 -30
  766. package/dist/agent-runtime/provider-cache.d.ts.map +0 -1
  767. package/dist/agent-runtime/provider-content.d.ts.map +0 -1
  768. package/dist/agent-runtime/provider-failure.d.ts +0 -95
  769. package/dist/agent-runtime/provider-failure.d.ts.map +0 -1
  770. package/dist/agent-runtime/provider-history.d.ts +0 -13
  771. package/dist/agent-runtime/provider-history.d.ts.map +0 -1
  772. package/dist/agent-runtime/provider-http.d.ts +0 -68
  773. package/dist/agent-runtime/provider-http.d.ts.map +0 -1
  774. package/dist/agent-runtime/provider-journal.d.ts.map +0 -1
  775. package/dist/agent-runtime/provider-json-schema-strip.d.ts.map +0 -1
  776. package/dist/agent-runtime/provider-json-schema.d.ts +0 -28
  777. package/dist/agent-runtime/provider-json-schema.d.ts.map +0 -1
  778. package/dist/agent-runtime/provider-media.d.ts +0 -49
  779. package/dist/agent-runtime/provider-media.d.ts.map +0 -1
  780. package/dist/agent-runtime/provider-openai-chat-helpers.d.ts +0 -27
  781. package/dist/agent-runtime/provider-openai-chat-helpers.d.ts.map +0 -1
  782. package/dist/agent-runtime/provider-openai-chat-sse.d.ts +0 -25
  783. package/dist/agent-runtime/provider-openai-chat-sse.d.ts.map +0 -1
  784. package/dist/agent-runtime/provider-openai-chat.d.ts +0 -27
  785. package/dist/agent-runtime/provider-openai-chat.d.ts.map +0 -1
  786. package/dist/agent-runtime/provider-origin.d.ts +0 -10
  787. package/dist/agent-runtime/provider-origin.d.ts.map +0 -1
  788. package/dist/agent-runtime/provider-sse.d.ts.map +0 -1
  789. package/dist/agent-runtime/provider-stream-parts.d.ts +0 -5
  790. package/dist/agent-runtime/provider-stream-parts.d.ts.map +0 -1
  791. package/dist/agent-runtime/provider-stream-segments.d.ts +0 -63
  792. package/dist/agent-runtime/provider-stream-segments.d.ts.map +0 -1
  793. package/dist/agent-runtime/provider-usage.d.ts +0 -24
  794. package/dist/agent-runtime/provider-usage.d.ts.map +0 -1
  795. package/dist/agent-runtime/purge.d.ts.map +0 -1
  796. package/dist/agent-runtime/react.d.ts.map +0 -1
  797. package/dist/agent-runtime/retry-policy.d.ts +0 -49
  798. package/dist/agent-runtime/retry-policy.d.ts.map +0 -1
  799. package/dist/agent-runtime/run-acquisition.d.ts +0 -24
  800. package/dist/agent-runtime/run-acquisition.d.ts.map +0 -1
  801. package/dist/agent-runtime/run-approval.d.ts +0 -82
  802. package/dist/agent-runtime/run-approval.d.ts.map +0 -1
  803. package/dist/agent-runtime/run-assertions.d.ts +0 -63
  804. package/dist/agent-runtime/run-assertions.d.ts.map +0 -1
  805. package/dist/agent-runtime/run-complete-retry.d.ts +0 -24
  806. package/dist/agent-runtime/run-complete-retry.d.ts.map +0 -1
  807. package/dist/agent-runtime/run-complete-stream.d.ts +0 -9
  808. package/dist/agent-runtime/run-complete-stream.d.ts.map +0 -1
  809. package/dist/agent-runtime/run-complete-tools.d.ts +0 -21
  810. package/dist/agent-runtime/run-complete-tools.d.ts.map +0 -1
  811. package/dist/agent-runtime/run-complete-types.d.ts +0 -168
  812. package/dist/agent-runtime/run-complete-types.d.ts.map +0 -1
  813. package/dist/agent-runtime/run-complete.d.ts +0 -25
  814. package/dist/agent-runtime/run-complete.d.ts.map +0 -1
  815. package/dist/agent-runtime/run-driver-compose.d.ts +0 -21
  816. package/dist/agent-runtime/run-driver-compose.d.ts.map +0 -1
  817. package/dist/agent-runtime/run-execution-state.d.ts +0 -178
  818. package/dist/agent-runtime/run-execution-state.d.ts.map +0 -1
  819. package/dist/agent-runtime/run-execution.d.ts +0 -22
  820. package/dist/agent-runtime/run-execution.d.ts.map +0 -1
  821. package/dist/agent-runtime/run-failure.d.ts +0 -21
  822. package/dist/agent-runtime/run-failure.d.ts.map +0 -1
  823. package/dist/agent-runtime/run-history-parts.d.ts +0 -14
  824. package/dist/agent-runtime/run-history-parts.d.ts.map +0 -1
  825. package/dist/agent-runtime/run-loop-events.d.ts +0 -126
  826. package/dist/agent-runtime/run-loop-events.d.ts.map +0 -1
  827. package/dist/agent-runtime/run-model-attempts.d.ts +0 -6
  828. package/dist/agent-runtime/run-model-attempts.d.ts.map +0 -1
  829. package/dist/agent-runtime/run-model-messages.d.ts +0 -9
  830. package/dist/agent-runtime/run-model-messages.d.ts.map +0 -1
  831. package/dist/agent-runtime/run-model-step.d.ts +0 -43
  832. package/dist/agent-runtime/run-model-step.d.ts.map +0 -1
  833. package/dist/agent-runtime/run-model-stream.d.ts +0 -27
  834. package/dist/agent-runtime/run-model-stream.d.ts.map +0 -1
  835. package/dist/agent-runtime/run-operation-lifecycle.d.ts +0 -32
  836. package/dist/agent-runtime/run-operation-lifecycle.d.ts.map +0 -1
  837. package/dist/agent-runtime/run-prompt-history.d.ts +0 -53
  838. package/dist/agent-runtime/run-prompt-history.d.ts.map +0 -1
  839. package/dist/agent-runtime/run-provider-ledger.d.ts +0 -32
  840. package/dist/agent-runtime/run-provider-ledger.d.ts.map +0 -1
  841. package/dist/agent-runtime/run-step-barriers.d.ts +0 -114
  842. package/dist/agent-runtime/run-step-barriers.d.ts.map +0 -1
  843. package/dist/agent-runtime/run-step-helpers.d.ts +0 -49
  844. package/dist/agent-runtime/run-step-helpers.d.ts.map +0 -1
  845. package/dist/agent-runtime/run-step-prepare.d.ts +0 -34
  846. package/dist/agent-runtime/run-step-prepare.d.ts.map +0 -1
  847. package/dist/agent-runtime/run-step-spend.d.ts +0 -394
  848. package/dist/agent-runtime/run-step-spend.d.ts.map +0 -1
  849. package/dist/agent-runtime/run-stream-parts.d.ts +0 -34
  850. package/dist/agent-runtime/run-stream-parts.d.ts.map +0 -1
  851. package/dist/agent-runtime/run-stream-recorded.d.ts +0 -8
  852. package/dist/agent-runtime/run-stream-recorded.d.ts.map +0 -1
  853. package/dist/agent-runtime/run-stream-step-text.d.ts +0 -29
  854. package/dist/agent-runtime/run-stream-step-text.d.ts.map +0 -1
  855. package/dist/agent-runtime/run-terminal.d.ts +0 -11
  856. package/dist/agent-runtime/run-terminal.d.ts.map +0 -1
  857. package/dist/agent-runtime/run-tool-approval-flow.d.ts +0 -36
  858. package/dist/agent-runtime/run-tool-approval-flow.d.ts.map +0 -1
  859. package/dist/agent-runtime/run-tool-approval-records.d.ts +0 -24
  860. package/dist/agent-runtime/run-tool-approval-records.d.ts.map +0 -1
  861. package/dist/agent-runtime/run-tool-call.d.ts +0 -73
  862. package/dist/agent-runtime/run-tool-call.d.ts.map +0 -1
  863. package/dist/agent-runtime/run-tool-errors.d.ts.map +0 -1
  864. package/dist/agent-runtime/run-tool-executor.d.ts +0 -34
  865. package/dist/agent-runtime/run-tool-executor.d.ts.map +0 -1
  866. package/dist/agent-runtime/run-tool-progress.d.ts +0 -21
  867. package/dist/agent-runtime/run-tool-progress.d.ts.map +0 -1
  868. package/dist/agent-runtime/run-turn-preparation.d.ts +0 -25
  869. package/dist/agent-runtime/run-turn-preparation.d.ts.map +0 -1
  870. package/dist/agent-runtime/run-unacquired.d.ts +0 -19
  871. package/dist/agent-runtime/run-unacquired.d.ts.map +0 -1
  872. package/dist/agent-runtime/runtime-admission-gate.d.ts.map +0 -1
  873. package/dist/agent-runtime/runtime-control.d.ts +0 -9
  874. package/dist/agent-runtime/runtime-control.d.ts.map +0 -1
  875. package/dist/agent-runtime/runtime-recovery.d.ts +0 -10
  876. package/dist/agent-runtime/runtime-recovery.d.ts.map +0 -1
  877. package/dist/agent-runtime/runtime-state.d.ts +0 -36
  878. package/dist/agent-runtime/runtime-state.d.ts.map +0 -1
  879. package/dist/agent-runtime/runtime-submit.d.ts +0 -5
  880. package/dist/agent-runtime/runtime-submit.d.ts.map +0 -1
  881. package/dist/agent-runtime/runtime.d.ts +0 -352
  882. package/dist/agent-runtime/runtime.d.ts.map +0 -1
  883. package/dist/agent-runtime/sandbox-binding.d.ts.map +0 -1
  884. package/dist/agent-runtime/sandbox-broker.d.ts.map +0 -1
  885. package/dist/agent-runtime/sandbox-bubblewrap-args.d.ts.map +0 -1
  886. package/dist/agent-runtime/sandbox-bubblewrap-storage.d.ts.map +0 -1
  887. package/dist/agent-runtime/sandbox-bubblewrap.d.ts.map +0 -1
  888. package/dist/agent-runtime/sandbox-coding-adapter.d.ts.map +0 -1
  889. package/dist/agent-runtime/sandbox-contract.d.ts.map +0 -1
  890. package/dist/agent-runtime/sandbox-process-linux.d.ts.map +0 -1
  891. package/dist/agent-runtime/sandbox-process-macos.d.ts.map +0 -1
  892. package/dist/agent-runtime/sandbox-process-owner.d.ts +0 -19
  893. package/dist/agent-runtime/sandbox-process-owner.d.ts.map +0 -1
  894. package/dist/agent-runtime/sandbox-process-spec.d.ts.map +0 -1
  895. package/dist/agent-runtime/sandbox-process-wrapper.d.ts.map +0 -1
  896. package/dist/agent-runtime/sandbox-process.d.ts +0 -8
  897. package/dist/agent-runtime/sandbox-process.d.ts.map +0 -1
  898. package/dist/agent-runtime/sandbox-session.d.ts.map +0 -1
  899. package/dist/agent-runtime/sandbox.d.ts +0 -125
  900. package/dist/agent-runtime/sandbox.d.ts.map +0 -1
  901. package/dist/agent-runtime/schedule-contract.d.ts.map +0 -1
  902. package/dist/agent-runtime/schedule-dispatch.d.ts.map +0 -1
  903. package/dist/agent-runtime/schedule-records.d.ts.map +0 -1
  904. package/dist/agent-runtime/schedule-tools.d.ts +0 -76
  905. package/dist/agent-runtime/schedule-tools.d.ts.map +0 -1
  906. package/dist/agent-runtime/schedules.d.ts.map +0 -1
  907. package/dist/agent-runtime/spill.d.ts +0 -26
  908. package/dist/agent-runtime/spill.d.ts.map +0 -1
  909. package/dist/agent-runtime/sql-events.d.ts.map +0 -1
  910. package/dist/agent-runtime/sql-history.d.ts.map +0 -1
  911. package/dist/agent-runtime/sql-ledger.d.ts.map +0 -1
  912. package/dist/agent-runtime/sql-purge.d.ts.map +0 -1
  913. package/dist/agent-runtime/sql-reads.d.ts.map +0 -1
  914. package/dist/agent-runtime/sql-rows.d.ts.map +0 -1
  915. package/dist/agent-runtime/sql-session.d.ts.map +0 -1
  916. package/dist/agent-runtime/sqlite-bun.d.ts.map +0 -1
  917. package/dist/agent-runtime/sqlite-node.d.ts.map +0 -1
  918. package/dist/agent-runtime/sqlite-purge.d.ts +0 -6
  919. package/dist/agent-runtime/sqlite-purge.d.ts.map +0 -1
  920. package/dist/agent-runtime/sqlite-schema.d.ts +0 -7
  921. package/dist/agent-runtime/sqlite-schema.d.ts.map +0 -1
  922. package/dist/agent-runtime/sqlite-transactions.d.ts +0 -29
  923. package/dist/agent-runtime/sqlite-transactions.d.ts.map +0 -1
  924. package/dist/agent-runtime/sqlite.d.ts +0 -33
  925. package/dist/agent-runtime/sqlite.d.ts.map +0 -1
  926. package/dist/agent-runtime/state-slots.d.ts +0 -48
  927. package/dist/agent-runtime/state-slots.d.ts.map +0 -1
  928. package/dist/agent-runtime/state-tools.d.ts +0 -117
  929. package/dist/agent-runtime/state-tools.d.ts.map +0 -1
  930. package/dist/agent-runtime/store-archive.d.ts.map +0 -1
  931. package/dist/agent-runtime/store-branch.d.ts.map +0 -1
  932. package/dist/agent-runtime/store-capabilities.d.ts.map +0 -1
  933. package/dist/agent-runtime/store-conformance-branch.d.ts +0 -7
  934. package/dist/agent-runtime/store-conformance-branch.d.ts.map +0 -1
  935. package/dist/agent-runtime/store-conformance-capabilities.d.ts +0 -6
  936. package/dist/agent-runtime/store-conformance-capabilities.d.ts.map +0 -1
  937. package/dist/agent-runtime/store-conformance-event-once.d.ts +0 -12
  938. package/dist/agent-runtime/store-conformance-event-once.d.ts.map +0 -1
  939. package/dist/agent-runtime/store-conformance-lifecycle.d.ts +0 -454
  940. package/dist/agent-runtime/store-conformance-lifecycle.d.ts.map +0 -1
  941. package/dist/agent-runtime/store-conformance-ordering.d.ts +0 -18
  942. package/dist/agent-runtime/store-conformance-ordering.d.ts.map +0 -1
  943. package/dist/agent-runtime/store-conformance-seed.d.ts +0 -8
  944. package/dist/agent-runtime/store-conformance-seed.d.ts.map +0 -1
  945. package/dist/agent-runtime/store-conformance-support.d.ts +0 -140
  946. package/dist/agent-runtime/store-conformance-support.d.ts.map +0 -1
  947. package/dist/agent-runtime/store-conformance-terminal.d.ts +0 -12
  948. package/dist/agent-runtime/store-conformance-terminal.d.ts.map +0 -1
  949. package/dist/agent-runtime/store-conformance.d.ts +0 -71
  950. package/dist/agent-runtime/store-conformance.d.ts.map +0 -1
  951. package/dist/agent-runtime/store-create.d.ts.map +0 -1
  952. package/dist/agent-runtime/store-driver-contract.d.ts +0 -1016
  953. package/dist/agent-runtime/store-driver-contract.d.ts.map +0 -1
  954. package/dist/agent-runtime/store-event-once.d.ts +0 -37
  955. package/dist/agent-runtime/store-event-once.d.ts.map +0 -1
  956. package/dist/agent-runtime/store-events.d.ts +0 -2231
  957. package/dist/agent-runtime/store-events.d.ts.map +0 -1
  958. package/dist/agent-runtime/store-memory-archive.d.ts.map +0 -1
  959. package/dist/agent-runtime/store-memory-events.d.ts +0 -7
  960. package/dist/agent-runtime/store-memory-events.d.ts.map +0 -1
  961. package/dist/agent-runtime/store-memory.d.ts.map +0 -1
  962. package/dist/agent-runtime/store-migrations/v1-to-v2.d.ts +0 -6
  963. package/dist/agent-runtime/store-migrations/v1-to-v2.d.ts.map +0 -1
  964. package/dist/agent-runtime/store-migrations/v2-to-v3.d.ts +0 -14
  965. package/dist/agent-runtime/store-migrations/v2-to-v3.d.ts.map +0 -1
  966. package/dist/agent-runtime/store-migrations/v3-to-v4.d.ts +0 -4
  967. package/dist/agent-runtime/store-migrations/v3-to-v4.d.ts.map +0 -1
  968. package/dist/agent-runtime/store-mutate.d.ts.map +0 -1
  969. package/dist/agent-runtime/store-purge.d.ts.map +0 -1
  970. package/dist/agent-runtime/store-reads.d.ts +0 -29
  971. package/dist/agent-runtime/store-reads.d.ts.map +0 -1
  972. package/dist/agent-runtime/store-reduce-history.d.ts +0 -10
  973. package/dist/agent-runtime/store-reduce-history.d.ts.map +0 -1
  974. package/dist/agent-runtime/store-reduce-run.d.ts +0 -14
  975. package/dist/agent-runtime/store-reduce-run.d.ts.map +0 -1
  976. package/dist/agent-runtime/store-reduce-shared.d.ts +0 -78
  977. package/dist/agent-runtime/store-reduce-shared.d.ts.map +0 -1
  978. package/dist/agent-runtime/store-reduce-terminal.d.ts +0 -6
  979. package/dist/agent-runtime/store-reduce-terminal.d.ts.map +0 -1
  980. package/dist/agent-runtime/store-reducer.d.ts +0 -24
  981. package/dist/agent-runtime/store-reducer.d.ts.map +0 -1
  982. package/dist/agent-runtime/store-replay.d.ts.map +0 -1
  983. package/dist/agent-runtime/store-snapshot.d.ts +0 -19
  984. package/dist/agent-runtime/store-snapshot.d.ts.map +0 -1
  985. package/dist/agent-runtime/store.d.ts +0 -3032
  986. package/dist/agent-runtime/store.d.ts.map +0 -1
  987. package/dist/agent-runtime/testing.d.ts +0 -46
  988. package/dist/agent-runtime/testing.d.ts.map +0 -1
  989. package/dist/agent-runtime/workspace-glob.d.ts.map +0 -1
  990. package/dist/index-18pf56dq.js +0 -409
  991. package/dist/index-1gmgwfn3.js +0 -439
  992. package/dist/index-23wn8sgf.js +0 -47
  993. package/dist/index-27hck3z2.js +0 -307
  994. package/dist/index-27srek2g.js +0 -3781
  995. package/dist/index-360j58vb.js +0 -63
  996. package/dist/index-67pnt4bh.js +0 -174
  997. package/dist/index-6kpwkpgx.js +0 -415
  998. package/dist/index-6xw1wf4m.js +0 -969
  999. package/dist/index-6yb4stq3.js +0 -224
  1000. package/dist/index-76yhxa41.js +0 -725
  1001. package/dist/index-79vqbjcz.js +0 -26
  1002. package/dist/index-a84wj6y8.js +0 -510
  1003. package/dist/index-b23s6e2c.js +0 -158
  1004. package/dist/index-cb4nnvfr.js +0 -40
  1005. package/dist/index-ek9w11r0.js +0 -40
  1006. package/dist/index-er483f3w.js +0 -601
  1007. package/dist/index-fjac2w5e.js +0 -3543
  1008. package/dist/index-ga6avd48.js +0 -53
  1009. package/dist/index-hy4653g4.js +0 -345
  1010. package/dist/index-j903yhp4.js +0 -121
  1011. package/dist/index-jzdbkanz.js +0 -215
  1012. package/dist/index-k9g061ma.js +0 -164
  1013. package/dist/index-krekhmp7.js +0 -707
  1014. package/dist/index-ky79wwgs.js +0 -2872
  1015. package/dist/index-mgr0mdqp.js +0 -271
  1016. package/dist/index-mx2gya05.js +0 -465
  1017. package/dist/index-nfeafbzh.js +0 -7379
  1018. package/dist/index-ngwf1s3c.js +0 -51
  1019. package/dist/index-pjjh91vw.js +0 -53
  1020. package/dist/index-qv5v6w9c.js +0 -696
  1021. package/dist/index-rj32hkkp.js +0 -305
  1022. package/dist/index-t5zp1jjj.js +0 -77
  1023. package/dist/index-v5hmyef8.js +0 -951
  1024. package/dist/index-vv0hxrmy.js +0 -295
  1025. package/dist/index-vxm0ya3f.js +0 -707
  1026. package/dist/index-xtxxt87z.js +0 -349
  1027. package/dist/index-zag9sjpd.js +0 -1210
  1028. package/dist/index-zk839vzf.js +0 -231
  1029. package/llms/upgrading-0.128.0-0.134.0.txt +0 -639
  1030. /package/dist/agent-runtime/{control-interaction-schema.d.ts → browser/control-interaction-schema.d.ts} +0 -0
  1031. /package/dist/agent-runtime/{react.d.ts → browser/react.d.ts} +0 -0
  1032. /package/dist/agent-runtime/{coding-search-automaton.d.ts → coding/coding-search-automaton.d.ts} +0 -0
  1033. /package/dist/agent-runtime/{coding-search-case-fold.d.ts → coding/coding-search-case-fold.d.ts} +0 -0
  1034. /package/dist/agent-runtime/{coding-search-class-ranges.d.ts → coding/coding-search-class-ranges.d.ts} +0 -0
  1035. /package/dist/agent-runtime/{coding-search-contract.d.ts → coding/coding-search-contract.d.ts} +0 -0
  1036. /package/dist/agent-runtime/{coding-search-limits.d.ts → coding/coding-search-limits.d.ts} +0 -0
  1037. /package/dist/agent-runtime/{coding-search-matcher.d.ts → coding/coding-search-matcher.d.ts} +0 -0
  1038. /package/dist/agent-runtime/{coding-search-output.d.ts → coding/coding-search-output.d.ts} +0 -0
  1039. /package/dist/agent-runtime/{coding-search-regex-syntax.d.ts → coding/coding-search-regex-syntax.d.ts} +0 -0
  1040. /package/dist/agent-runtime/{coding-search-unit-classes.d.ts → coding/coding-search-unit-classes.d.ts} +0 -0
  1041. /package/dist/agent-runtime/{coding-tool-files.d.ts → coding/coding-tool-files.d.ts} +0 -0
  1042. /package/dist/agent-runtime/{coding-tool-listing.d.ts → coding/coding-tool-listing.d.ts} +0 -0
  1043. /package/dist/agent-runtime/{coding-tool-refusals.d.ts → coding/coding-tool-refusals.d.ts} +0 -0
  1044. /package/dist/agent-runtime/{coding-tool-search-patch.d.ts → coding/coding-tool-search-patch.d.ts} +0 -0
  1045. /package/dist/agent-runtime/{coding-tool-shell.d.ts → coding/coding-tool-shell.d.ts} +0 -0
  1046. /package/dist/agent-runtime/{coding-tool-utf8.d.ts → coding/coding-tool-utf8.d.ts} +0 -0
  1047. /package/dist/agent-runtime/{coding-tools.d.ts → coding/coding-tools.d.ts} +0 -0
  1048. /package/dist/agent-runtime/{contained-scan-budget.d.ts → coding/contained-scan-budget.d.ts} +0 -0
  1049. /package/dist/agent-runtime/{contained-scan-contract.d.ts → coding/contained-scan-contract.d.ts} +0 -0
  1050. /package/dist/agent-runtime/{workspace-glob.d.ts → coding/workspace-glob.d.ts} +0 -0
  1051. /package/dist/agent-runtime/{harness-resources.d.ts → harness/harness-resources.d.ts} +0 -0
  1052. /package/dist/agent-runtime/{coordinator.d.ts → loop/coordinator.d.ts} +0 -0
  1053. /package/dist/agent-runtime/{invocation-failure.d.ts → loop/invocation-failure.d.ts} +0 -0
  1054. /package/dist/agent-runtime/{owned-provider-stream.d.ts → loop/owned-provider-stream.d.ts} +0 -0
  1055. /package/dist/agent-runtime/{run-tool-errors.d.ts → loop/run-tool-errors.d.ts} +0 -0
  1056. /package/dist/agent-runtime/{runtime-admission-gate.d.ts → loop/runtime-admission-gate.d.ts} +0 -0
  1057. /package/dist/agent-runtime/{anthropic-sse.d.ts → providers/anthropic-sse.d.ts} +0 -0
  1058. /package/dist/agent-runtime/{anthropic.d.ts → providers/anthropic.d.ts} +0 -0
  1059. /package/dist/agent-runtime/{models-driver-telemetry.d.ts → providers/models-driver-telemetry.d.ts} +0 -0
  1060. /package/dist/agent-runtime/{models.d.ts → providers/models.d.ts} +0 -0
  1061. /package/dist/agent-runtime/{openai-messages.d.ts → providers/openai-messages.d.ts} +0 -0
  1062. /package/dist/agent-runtime/{openai-sse-state.d.ts → providers/openai-sse-state.d.ts} +0 -0
  1063. /package/dist/agent-runtime/{openai-sse.d.ts → providers/openai-sse.d.ts} +0 -0
  1064. /package/dist/agent-runtime/{openai.d.ts → providers/openai.d.ts} +0 -0
  1065. /package/dist/agent-runtime/{openrouter-benchmarks.d.ts → providers/openrouter-benchmarks.d.ts} +0 -0
  1066. /package/dist/agent-runtime/{openrouter-catalog-cache.d.ts → providers/openrouter-catalog-cache.d.ts} +0 -0
  1067. /package/dist/agent-runtime/{openrouter-route.d.ts → providers/openrouter-route.d.ts} +0 -0
  1068. /package/dist/agent-runtime/{provider-content.d.ts → providers/provider-content.d.ts} +0 -0
  1069. /package/dist/agent-runtime/{provider-journal.d.ts → providers/provider-journal.d.ts} +0 -0
  1070. /package/dist/agent-runtime/{provider-json-schema-strip.d.ts → providers/provider-json-schema-strip.d.ts} +0 -0
  1071. /package/dist/agent-runtime/{provider-sse.d.ts → providers/provider-sse.d.ts} +0 -0
  1072. /package/dist/agent-runtime/{sandbox-binding.d.ts → sandbox/sandbox-binding.d.ts} +0 -0
  1073. /package/dist/agent-runtime/{sandbox-broker.d.ts → sandbox/sandbox-broker.d.ts} +0 -0
  1074. /package/dist/agent-runtime/{sandbox-bubblewrap-args.d.ts → sandbox/sandbox-bubblewrap-args.d.ts} +0 -0
  1075. /package/dist/agent-runtime/{sandbox-bubblewrap-storage.d.ts → sandbox/sandbox-bubblewrap-storage.d.ts} +0 -0
  1076. /package/dist/agent-runtime/{sandbox-bubblewrap.d.ts → sandbox/sandbox-bubblewrap.d.ts} +0 -0
  1077. /package/dist/agent-runtime/{sandbox-coding-adapter.d.ts → sandbox/sandbox-coding-adapter.d.ts} +0 -0
  1078. /package/dist/agent-runtime/{sandbox-contract.d.ts → sandbox/sandbox-contract.d.ts} +0 -0
  1079. /package/dist/agent-runtime/{sandbox-process-linux.d.ts → sandbox/sandbox-process-linux.d.ts} +0 -0
  1080. /package/dist/agent-runtime/{sandbox-process-macos.d.ts → sandbox/sandbox-process-macos.d.ts} +0 -0
  1081. /package/dist/agent-runtime/{sandbox-process-spec.d.ts → sandbox/sandbox-process-spec.d.ts} +0 -0
  1082. /package/dist/agent-runtime/{sandbox-process-wrapper.d.ts → sandbox/sandbox-process-wrapper.d.ts} +0 -0
  1083. /package/dist/agent-runtime/{sandbox-session.d.ts → sandbox/sandbox-session.d.ts} +0 -0
  1084. /package/dist/agent-runtime/{archive-projection.d.ts → stores/archive-projection.d.ts} +0 -0
  1085. /package/dist/agent-runtime/{archive-spill.d.ts → stores/archive-spill.d.ts} +0 -0
  1086. /package/dist/agent-runtime/{branch-contract.d.ts → stores/branch-contract.d.ts} +0 -0
  1087. /package/dist/agent-runtime/{branch-observations.d.ts → stores/branch-observations.d.ts} +0 -0
  1088. /package/dist/agent-runtime/{branch-provider.d.ts → stores/branch-provider.d.ts} +0 -0
  1089. /package/dist/agent-runtime/{branch-refusal.d.ts → stores/branch-refusal.d.ts} +0 -0
  1090. /package/dist/agent-runtime/{branch-runtime-tools.d.ts → stores/branch-runtime-tools.d.ts} +0 -0
  1091. /package/dist/agent-runtime/{branch-transitions.d.ts → stores/branch-transitions.d.ts} +0 -0
  1092. /package/dist/agent-runtime/{child-blocking.d.ts → stores/child-blocking.d.ts} +0 -0
  1093. /package/dist/agent-runtime/{children-control.d.ts → stores/children-control.d.ts} +0 -0
  1094. /package/dist/agent-runtime/{children-spawn.d.ts → stores/children-spawn.d.ts} +0 -0
  1095. /package/dist/agent-runtime/{children-state.d.ts → stores/children-state.d.ts} +0 -0
  1096. /package/dist/agent-runtime/{children-usage.d.ts → stores/children-usage.d.ts} +0 -0
  1097. /package/dist/agent-runtime/{children.d.ts → stores/children.d.ts} +0 -0
  1098. /package/dist/agent-runtime/{conversations.d.ts → stores/conversations.d.ts} +0 -0
  1099. /package/dist/agent-runtime/{event-search-postgres.d.ts → stores/event-search-postgres.d.ts} +0 -0
  1100. /package/dist/agent-runtime/{event-search-terms.d.ts → stores/event-search-terms.d.ts} +0 -0
  1101. /package/dist/agent-runtime/{event-search.d.ts → stores/event-search.d.ts} +0 -0
  1102. /package/dist/agent-runtime/{postgres-schema.d.ts → stores/postgres-schema.d.ts} +0 -0
  1103. /package/dist/agent-runtime/{purge.d.ts → stores/purge.d.ts} +0 -0
  1104. /package/dist/agent-runtime/{schedule-contract.d.ts → stores/schedule-contract.d.ts} +0 -0
  1105. /package/dist/agent-runtime/{schedule-dispatch.d.ts → stores/schedule-dispatch.d.ts} +0 -0
  1106. /package/dist/agent-runtime/{schedule-records.d.ts → stores/schedule-records.d.ts} +0 -0
  1107. /package/dist/agent-runtime/{schedules.d.ts → stores/schedules.d.ts} +0 -0
  1108. /package/dist/agent-runtime/{sql-events.d.ts → stores/sql-events.d.ts} +0 -0
  1109. /package/dist/agent-runtime/{sql-history.d.ts → stores/sql-history.d.ts} +0 -0
  1110. /package/dist/agent-runtime/{sql-ledger.d.ts → stores/sql-ledger.d.ts} +0 -0
  1111. /package/dist/agent-runtime/{sql-purge.d.ts → stores/sql-purge.d.ts} +0 -0
  1112. /package/dist/agent-runtime/{sql-reads.d.ts → stores/sql-reads.d.ts} +0 -0
  1113. /package/dist/agent-runtime/{sql-rows.d.ts → stores/sql-rows.d.ts} +0 -0
  1114. /package/dist/agent-runtime/{sql-session.d.ts → stores/sql-session.d.ts} +0 -0
  1115. /package/dist/agent-runtime/{sqlite-bun.d.ts → stores/sqlite-bun.d.ts} +0 -0
  1116. /package/dist/agent-runtime/{sqlite-node.d.ts → stores/sqlite-node.d.ts} +0 -0
  1117. /package/dist/agent-runtime/{store-archive.d.ts → stores/store-archive.d.ts} +0 -0
  1118. /package/dist/agent-runtime/{store-branch.d.ts → stores/store-branch.d.ts} +0 -0
  1119. /package/dist/agent-runtime/{store-capabilities.d.ts → stores/store-capabilities.d.ts} +0 -0
  1120. /package/dist/agent-runtime/{store-create.d.ts → stores/store-create.d.ts} +0 -0
  1121. /package/dist/agent-runtime/{store-memory-archive.d.ts → stores/store-memory-archive.d.ts} +0 -0
  1122. /package/dist/agent-runtime/{store-memory.d.ts → stores/store-memory.d.ts} +0 -0
  1123. /package/dist/agent-runtime/{store-mutate.d.ts → stores/store-mutate.d.ts} +0 -0
  1124. /package/dist/agent-runtime/{store-purge.d.ts → stores/store-purge.d.ts} +0 -0
  1125. /package/dist/agent-runtime/{store-replay.d.ts → stores/store-replay.d.ts} +0 -0
  1126. /package/dist/agent-runtime/{fault-bench.d.ts → testing/fault-bench.d.ts} +0 -0
@@ -0,0 +1,3781 @@
1
+ import {
2
+ AgentRecordIdSchema2,
3
+ AgentStoreEventEnvelopeSchema2,
4
+ AppendAgentStoreEventSchema2,
5
+ ReadAgentStoreEventsSchema2,
6
+ AgentStoreEventPageSchema2,
7
+ AgentRecordVersionSchema2,
8
+ AgentTimestampSchema2,
9
+ AgentMessageSchema2
10
+ } from "./index-j3r7r1mh.js";
11
+ import {
12
+ AgentCodingToolAuthorizationSchema2,
13
+ ShellOutputSchema,
14
+ ArtifactReadInputSchema,
15
+ ArtifactReadOutputSchema,
16
+ ArtifactSearchInputSchema,
17
+ ArtifactSearchOutputSchema,
18
+ AgentSandboxRestrictionSchema2,
19
+ AgentSandboxGradeSchema2,
20
+ AGENT_CODING_TOOL_NAMES
21
+ } from "./index-64t6pheq.js";
22
+ import {
23
+ runStateForTerminalReason2,
24
+ AgentRunSchema2,
25
+ AgentSnapshotSchema2
26
+ } from "./index-pd9e8rz4.js";
27
+ import {
28
+ PurgeInvocationPayloadsInputSchema2,
29
+ PurgeInvocationPayloadsResultSchema2,
30
+ InvocationStartedSchema,
31
+ InvocationRequestSchema,
32
+ InvocationResponseSchema,
33
+ InvocationFinishedSchema,
34
+ InvocationPayloadReceiptSchema,
35
+ isModelInvocationRecord,
36
+ ProviderJournalMessageSchema,
37
+ ProviderJournalRequestSchema,
38
+ ProviderJournalResponseSchema,
39
+ AgentRunViewSchema2,
40
+ AcceptInputAndAssignRunSchema2,
41
+ AcquireAgentRunSchema2,
42
+ CheckpointRunAssistantSchema2,
43
+ RecordRunOperationSchema2,
44
+ CommitRunTerminalSchema2,
45
+ RequestRunInterruptSchema2,
46
+ RecoverAgentRunSchema2,
47
+ ReplaceCompactedRangeSchema2,
48
+ SeedConversationInputSchema2,
49
+ AgentRecoverablePageSchema2,
50
+ AgentStoreTransitionSchema2,
51
+ AgentStoreCheckpointRecordSchema,
52
+ agentStoreEventDraft,
53
+ canonicalAgentJson2,
54
+ encodeAgentConversationArchive2,
55
+ decodeAgentConversationArchive2,
56
+ conversationOfRun,
57
+ AgentRuntimeHeadSchema2,
58
+ AgentStoredRunSchema2,
59
+ AgentAdmissionReceiptSchema2,
60
+ AgentSeedReceiptSchema2,
61
+ isActiveRunState,
62
+ emptyHead
63
+ } from "./index-qcy8et93.js";
64
+ import {
65
+ StepEventPayloadSchema,
66
+ ParkEventPayloadSchema,
67
+ DeliveredEventPayloadSchema,
68
+ EffectEventPayloadSchema
69
+ } from "./index-snef22zr.js";
70
+ import {
71
+ assistantStatus
72
+ } from "./index-kgj8j7bv.js";
73
+ import {
74
+ assertPositiveSafeInteger
75
+ } from "./index-gr0kxymw.js";
76
+
77
+ // src/agent-runtime/deferred-tool-types.ts
78
+ import { z } from "zod";
79
+ var DeferredAgentToolSearchInputSchema2 = z.object({
80
+ query: z.string().min(1).describe("An exact tool name, or words describing the tool. Matched as one phrase first, then word by word."),
81
+ reason: z.enum(["inactive_call"]).optional().describe("Written by the runtime. Leave it out.")
82
+ });
83
+ var DeferredAgentToolMatchSchema2 = z.object({
84
+ name: z.string(),
85
+ description: z.string()
86
+ });
87
+ var DeferredAgentToolReceiptSchema2 = z.object({
88
+ schemaVersion: z.literal(1),
89
+ kind: z.literal("stitchkit.deferred-tool-selection"),
90
+ status: z.enum(["SELECTED", "SEARCH_REQUIRED", "NO_MATCH", "SELECTION_REFUSED"]),
91
+ runId: z.string(),
92
+ surfaceKey: z.string(),
93
+ selected: z.array(z.string()),
94
+ matches: z.array(DeferredAgentToolMatchSchema2),
95
+ truncated: z.boolean()
96
+ }).superRefine((receipt, context) => {
97
+ const selected = receipt.status === "SELECTED" || receipt.status === "SEARCH_REQUIRED";
98
+ if (selected !== receipt.selected.length > 0) {
99
+ context.addIssue({
100
+ code: "custom",
101
+ path: ["selected"],
102
+ message: `${receipt.status} receipt has inconsistent selected tools`
103
+ });
104
+ }
105
+ });
106
+
107
+ // src/agent-runtime/agent-tool.ts
108
+ function defineAgentToolDescriptor(descriptor) {
109
+ const identity = Object.freeze({
110
+ ...descriptor.identity,
111
+ ...descriptor.identity.meta !== undefined && {
112
+ meta: Object.freeze({ ...descriptor.identity.meta })
113
+ }
114
+ });
115
+ const expose = Object.freeze(["AGENT"]);
116
+ return Object.freeze({
117
+ ...descriptor,
118
+ identity,
119
+ expose
120
+ });
121
+ }
122
+ function bindAgentTool(descriptor, handler) {
123
+ return {
124
+ name: descriptor.name,
125
+ description: descriptor.description,
126
+ identity: {
127
+ ...descriptor.identity,
128
+ ...descriptor.identity.meta !== undefined && {
129
+ meta: { ...descriptor.identity.meta }
130
+ }
131
+ },
132
+ input: descriptor.input,
133
+ output: descriptor.output,
134
+ expose: descriptor.expose,
135
+ handler: (context) => handler(context)
136
+ };
137
+ }
138
+
139
+ // src/agent-runtime/stores/branch-contract.ts
140
+ import { z as z3 } from "zod";
141
+
142
+ // src/agent-runtime/stores/branch-refusal.ts
143
+ import { z as z2 } from "zod";
144
+ var AgentBranchRefusalCodeSchema2 = z2.enum([
145
+ "application-key-undeclared",
146
+ "application-key-source-identity",
147
+ "application-file-undeclared",
148
+ "artifact-authorization-missing",
149
+ "event-kind-unknown",
150
+ "integrity"
151
+ ]);
152
+ var AgentBranchRefusalSchema2 = z2.object({
153
+ code: AgentBranchRefusalCodeSchema2,
154
+ message: z2.string().min(1),
155
+ seq: z2.int().positive().optional(),
156
+ eventKind: z2.string().min(1).optional(),
157
+ messageId: z2.string().min(1).optional(),
158
+ toolName: z2.string().min(1).optional(),
159
+ key: z2.string().min(1).optional(),
160
+ path: z2.string().optional(),
161
+ reference: z2.string().min(1).optional()
162
+ }).strict();
163
+ var MAX_BRANCH_REFUSALS = 100;
164
+ function addressOf(refusal) {
165
+ const parts = [
166
+ refusal.seq !== undefined && `event ${refusal.seq}${refusal.eventKind ? ` ${refusal.eventKind}` : ""}`,
167
+ refusal.messageId !== undefined && `message ${refusal.messageId}`,
168
+ refusal.toolName !== undefined && `tool ${refusal.toolName}`
169
+ ].filter((part) => typeof part === "string");
170
+ return parts.length > 0 ? ` (${parts.join(", ")})` : "";
171
+ }
172
+
173
+ class AgentConversationBranchRefusedError2 extends TypeError {
174
+ refusals;
175
+ omittedRefusals;
176
+ constructor(refusals, omittedRefusals = 0) {
177
+ const [first] = refusals;
178
+ if (!first)
179
+ throw new TypeError("A branch refusal names at least one refusal");
180
+ const more = refusals.length - 1 + omittedRefusals;
181
+ super(`${first.message}${addressOf(first)}${more > 0 ? `; and ${more} more refusal${more === 1 ? "" : "s"}` : ""}`);
182
+ this.name = "AgentConversationBranchRefusedError";
183
+ this.refusals = refusals;
184
+ this.omittedRefusals = omittedRefusals;
185
+ }
186
+ }
187
+
188
+ // src/agent-runtime/stores/branch-contract.ts
189
+ var Hash = z3.string().regex(/^[a-f0-9]{64}$/);
190
+ var BranchApplicationFileSchema = z3.object({
191
+ reference: z3.string().min(1),
192
+ destinationReference: z3.string().min(1)
193
+ }).strict();
194
+ var BranchApplicationFilesSchema = z3.array(BranchApplicationFileSchema).superRefine((files, ctx) => {
195
+ for (const field of ["reference", "destinationReference"]) {
196
+ const values = files.map((file) => file[field]);
197
+ if (new Set(values).size !== values.length)
198
+ ctx.addIssue({
199
+ code: "custom",
200
+ message: `Branch application files repeat a ${field}`
201
+ });
202
+ }
203
+ });
204
+ var BRANCH_RUNTIME_REFERENCE_KEYS = [
205
+ "reference",
206
+ "conversationId",
207
+ "runId",
208
+ "messageId",
209
+ "callId",
210
+ "toolCallId",
211
+ "approvalId",
212
+ "operationId",
213
+ "artifactId"
214
+ ];
215
+ var BranchApplicationKeySchema = z3.object({
216
+ key: z3.enum(BRANCH_RUNTIME_REFERENCE_KEYS),
217
+ sourceIdentity: z3.enum(["refuse", "retain", "rekey-spill"]).default("refuse")
218
+ }).strict();
219
+ var BranchApplicationKeysSchema = z3.array(BranchApplicationKeySchema).superRefine((keys, ctx) => {
220
+ const names = keys.map((entry) => entry.key);
221
+ if (new Set(names).size !== names.length)
222
+ ctx.addIssue({ code: "custom", message: "Branch application keys repeat a key" });
223
+ });
224
+ var BranchAgentConversationInputSchema2 = z3.object({
225
+ requestKey: AgentRecordIdSchema2,
226
+ destinationConversationId: AgentRecordIdSchema2,
227
+ source: z3.discriminatedUnion("kind", [
228
+ z3.object({
229
+ kind: z3.literal("conversation"),
230
+ conversationId: AgentRecordIdSchema2,
231
+ throughRunId: AgentRecordIdSchema2.optional()
232
+ }).strict(),
233
+ z3.object({
234
+ kind: z3.literal("archive"),
235
+ bytes: z3.custom((value) => value instanceof Uint8Array)
236
+ }).strict()
237
+ ]),
238
+ artifactAuthorization: AgentCodingToolAuthorizationSchema2.optional(),
239
+ applicationFiles: BranchApplicationFilesSchema.optional(),
240
+ applicationKeys: BranchApplicationKeysSchema.optional()
241
+ }).strict();
242
+ var AgentConversationBranchReceiptSchema2 = z3.object({
243
+ schemaVersion: z3.literal(1),
244
+ requestKey: AgentRecordIdSchema2,
245
+ fingerprint: Hash,
246
+ conversationId: AgentRecordIdSchema2,
247
+ sourceConversationId: AgentRecordIdSchema2,
248
+ sourceKind: z3.enum(["conversation", "archive"]),
249
+ throughRunId: AgentRecordIdSchema2.optional(),
250
+ sourceSeq: z3.int().nonnegative(),
251
+ sourceVersion: z3.int().nonnegative(),
252
+ sourceDigest: Hash,
253
+ createdAt: AgentTimestampSchema2
254
+ }).strict();
255
+ var AgentConversationBranchResultSchema2 = z3.object({
256
+ outcome: z3.enum(["created", "duplicate"]),
257
+ receipt: AgentConversationBranchReceiptSchema2
258
+ }).strict();
259
+ var AgentConversationBranchPlanSchema2 = z3.object({
260
+ ready: z3.boolean(),
261
+ fingerprint: z3.string().regex(/^[a-f0-9]{64}$/),
262
+ sourceArchiveDigest: z3.string().regex(/^[a-f0-9]{64}$/),
263
+ refusals: z3.array(AgentBranchRefusalSchema2),
264
+ omittedRefusals: z3.int().nonnegative(),
265
+ applicationFiles: z3.array(z3.string().min(1)),
266
+ undeclaredKeys: z3.array(z3.string().min(1))
267
+ }).strict();
268
+
269
+ // src/agent-runtime/stores/children-contract.ts
270
+ import { z as z5 } from "zod";
271
+
272
+ // src/agent-runtime/stores/sql-rows.ts
273
+ import { z as z4 } from "zod";
274
+ var SqlIntegerSchema = z4.union([z4.number(), z4.bigint(), z4.string().regex(/^-?\d+$/)]).transform(Number).pipe(z4.int());
275
+ var SqlFlagSchema = SqlIntegerSchema.pipe(z4.union([z4.literal(0), z4.literal(1)]));
276
+ var HeadRowSchema = z4.object({
277
+ version: SqlIntegerSchema.pipe(z4.int().nonnegative())
278
+ });
279
+ var RunRowSchema = z4.object({
280
+ payload: z4.string(),
281
+ terminal_assistant_payload: z4.string().nullable()
282
+ });
283
+ var MessageRowSchema = z4.object({ payload: z4.string() });
284
+ var PositionedMessageRowSchema = z4.object({
285
+ position: SqlIntegerSchema.pipe(z4.int().nonnegative())
286
+ });
287
+ var CountRowSchema = z4.object({
288
+ count: SqlIntegerSchema.pipe(z4.int().nonnegative())
289
+ });
290
+ var FlagSchema = SqlFlagSchema;
291
+ var EventRowSchema = z4.object({
292
+ event_id: z4.string(),
293
+ conversation_id: z4.string(),
294
+ seq: SqlIntegerSchema.pipe(z4.int().positive()),
295
+ schema_version: SqlIntegerSchema.pipe(z4.int().positive()),
296
+ kind: z4.string(),
297
+ occurred_at: z4.string(),
298
+ ignorable: SqlFlagSchema,
299
+ payload: z4.string()
300
+ });
301
+ var EVENT_COLUMNS = "event_id, conversation_id, seq, schema_version, kind, occurred_at, ignorable, payload";
302
+ function parseJson(value) {
303
+ return JSON.parse(value);
304
+ }
305
+ function encodeJson(value) {
306
+ return JSON.stringify(value);
307
+ }
308
+ function missing(value) {
309
+ return value === null || value === undefined;
310
+ }
311
+ function placeholders(count) {
312
+ return Array.from({ length: count }, () => "?").join(", ");
313
+ }
314
+ function parseRunRow(value) {
315
+ const row = RunRowSchema.parse(value);
316
+ return AgentStoredRunSchema2.parse({
317
+ schemaVersion: 1,
318
+ run: AgentRunSchema2.parse(parseJson(row.payload)),
319
+ ...row.terminal_assistant_payload === null ? {} : {
320
+ terminalAssistant: AgentMessageSchema2.parse(parseJson(row.terminal_assistant_payload))
321
+ }
322
+ });
323
+ }
324
+ function parseEventRow(value) {
325
+ const row = EventRowSchema.parse(value);
326
+ return AgentStoreEventEnvelopeSchema2.parse({
327
+ schemaVersion: row.schema_version,
328
+ eventId: row.event_id,
329
+ conversationId: row.conversation_id,
330
+ seq: row.seq,
331
+ kind: row.kind,
332
+ occurredAt: row.occurred_at,
333
+ payload: parseJson(row.payload),
334
+ ...row.ignorable === 1 && { ignorable: true }
335
+ });
336
+ }
337
+ async function nextEventSeqByMaximum(dialect, session, conversationId) {
338
+ const row = await session.get(`SELECT COALESCE(MAX(seq), 0) AS count FROM ${dialect.tables.events} WHERE conversation_id = ?`, [conversationId]);
339
+ return CountRowSchema.parse(row).count + 1;
340
+ }
341
+
342
+ // src/agent-runtime/stores/children-contract.ts
343
+ var AgentChildBudgetSchema2 = z5.object({
344
+ usd: z5.number().positive().optional(),
345
+ tokens: z5.int().positive().optional(),
346
+ milliseconds: z5.int().positive().optional()
347
+ }).strict();
348
+ var AgentChildStateSchema2 = z5.enum([
349
+ "spawned",
350
+ "running",
351
+ "finished",
352
+ "stopped",
353
+ "lost"
354
+ ]);
355
+ var ChildUsageMetricsSchema = z5.object({
356
+ tokens: z5.int().nonnegative(),
357
+ usd: z5.number().nonnegative(),
358
+ milliseconds: z5.int().nonnegative()
359
+ }).strict();
360
+ var AgentChildRecordSchema2 = z5.object({
361
+ parentConversationId: z5.string().min(1),
362
+ childConversationId: z5.string().min(1),
363
+ seedUptoSeq: z5.int().nonnegative(),
364
+ state: AgentChildStateSchema2,
365
+ budget: AgentChildBudgetSchema2,
366
+ usage: ChildUsageMetricsSchema,
367
+ resultReference: z5.string().optional(),
368
+ createdAt: z5.string(),
369
+ updatedAt: z5.string()
370
+ }).strict();
371
+ var AgentChildBlockingKindSchema2 = z5.enum(["approval", "input"]);
372
+ var AgentChildBlockingSourceSchema2 = z5.object({
373
+ approvalId: z5.string().min(1),
374
+ callId: z5.string().min(1),
375
+ toolName: z5.string().min(1),
376
+ input: z5.json(),
377
+ kind: AgentChildBlockingKindSchema2.default("approval"),
378
+ batchId: z5.string().min(1).optional()
379
+ }).strict();
380
+ var AgentChildBlockingEventSchema2 = z5.object({
381
+ parentConversationId: z5.string().min(1),
382
+ childConversationId: z5.string().min(1),
383
+ kind: AgentChildBlockingKindSchema2,
384
+ approvalId: z5.string().min(1),
385
+ childApprovalId: z5.string().min(1),
386
+ callId: z5.string().min(1),
387
+ toolName: z5.string().min(1),
388
+ input: z5.json(),
389
+ batchId: z5.string().min(1),
390
+ presentedAt: z5.string()
391
+ }).strict();
392
+ var ChildBlockingDecisionSchema = z5.union([
393
+ z5.object({
394
+ approvalId: z5.string().min(1),
395
+ approved: z5.boolean(),
396
+ reason: z5.string().optional()
397
+ }).strict(),
398
+ z5.object({ approvalId: z5.string().min(1), value: z5.json() }).strict()
399
+ ]);
400
+ var ChildSpawnedEventPayloadSchema = z5.object({
401
+ childConversationId: z5.string().min(1),
402
+ seedUptoSeq: z5.int().nonnegative(),
403
+ budget: AgentChildBudgetSchema2
404
+ }).strict();
405
+ var ChildTransitionStateEventPayloadSchema = z5.object({
406
+ childConversationId: z5.string().min(1).optional(),
407
+ parentConversationId: z5.string().min(1).optional(),
408
+ state: AgentChildStateSchema2,
409
+ resultReference: z5.string().min(1).optional(),
410
+ reason: z5.string().optional(),
411
+ policyName: z5.string().min(1).optional(),
412
+ enforced: z5.boolean().optional(),
413
+ stopDurationMs: z5.number().nonnegative().optional(),
414
+ usage: ChildUsageMetricsSchema.optional(),
415
+ overrun: ChildUsageMetricsSchema.optional()
416
+ }).strict().refine((value) => value.childConversationId !== undefined || value.parentConversationId !== undefined, { message: "Child state event requires childConversationId or parentConversationId" });
417
+ var ChildMessageSentEventPayloadSchema = z5.object({
418
+ childConversationId: z5.string().min(1),
419
+ action: z5.literal("message-sent")
420
+ }).strict();
421
+ var ChildBlockingPresentedEventPayloadSchema = z5.object({
422
+ action: z5.literal("blocking-presented"),
423
+ childConversationId: z5.string().min(1),
424
+ approvalId: z5.string().min(1),
425
+ childApprovalId: z5.string().min(1),
426
+ kind: AgentChildBlockingKindSchema2,
427
+ callId: z5.string().min(1),
428
+ toolName: z5.string().min(1),
429
+ input: z5.json(),
430
+ batchId: z5.string().min(1),
431
+ presentedAt: z5.string()
432
+ }).strict();
433
+ var ChildBlockingResolvedApprovalEventPayloadSchema = z5.object({
434
+ action: z5.literal("blocking-resolved"),
435
+ childConversationId: z5.string().min(1),
436
+ approvalId: z5.string().min(1),
437
+ batchId: z5.string().min(1),
438
+ approved: z5.boolean()
439
+ }).strict();
440
+ var ChildBlockingResolvedInputEventPayloadSchema = z5.object({
441
+ action: z5.literal("blocking-resolved"),
442
+ childConversationId: z5.string().min(1),
443
+ approvalId: z5.string().min(1),
444
+ batchId: z5.string().min(1),
445
+ kind: z5.literal("input")
446
+ }).strict();
447
+ var ChildStateEventPayloadSchema = z5.union([
448
+ ChildTransitionStateEventPayloadSchema,
449
+ ChildMessageSentEventPayloadSchema,
450
+ ChildBlockingPresentedEventPayloadSchema,
451
+ ChildBlockingResolvedApprovalEventPayloadSchema,
452
+ ChildBlockingResolvedInputEventPayloadSchema
453
+ ]);
454
+ var ChildRowSchema = z5.object({
455
+ parent_conversation_id: z5.string(),
456
+ child_conversation_id: z5.string(),
457
+ seed_upto_seq: SqlIntegerSchema.pipe(z5.int().nonnegative()),
458
+ state: AgentChildStateSchema2,
459
+ budget_payload: z5.string(),
460
+ usage_payload: z5.string(),
461
+ result_reference: z5.string().nullable(),
462
+ created_at: z5.string(),
463
+ updated_at: z5.string()
464
+ });
465
+ function parseChild(raw) {
466
+ const row = ChildRowSchema.parse(raw);
467
+ return AgentChildRecordSchema2.parse({
468
+ parentConversationId: row.parent_conversation_id,
469
+ childConversationId: row.child_conversation_id,
470
+ seedUptoSeq: row.seed_upto_seq,
471
+ state: row.state,
472
+ budget: JSON.parse(row.budget_payload),
473
+ usage: JSON.parse(row.usage_payload),
474
+ ...row.result_reference && { resultReference: row.result_reference },
475
+ createdAt: row.created_at,
476
+ updatedAt: row.updated_at
477
+ });
478
+ }
479
+ function usageNumbers(usage) {
480
+ const inputTokens = usage.inputTokens.value;
481
+ const outputTokens = usage.outputTokens.value;
482
+ return {
483
+ ...inputTokens !== undefined && outputTokens !== undefined ? { tokens: inputTokens + outputTokens } : {},
484
+ ...usage.cost?.currency === "USD" && usage.cost.value !== undefined ? { usd: usage.cost.value } : {}
485
+ };
486
+ }
487
+
488
+ // src/agent-runtime/stores/purge.ts
489
+ import { z as z6 } from "zod";
490
+ var AgentConversationPurgeInputSchema2 = z6.strictObject({
491
+ conversationId: AgentRecordIdSchema2,
492
+ expectedVersion: AgentRecordVersionSchema2.optional()
493
+ });
494
+ var AgentConversationPurgeResultSchema2 = z6.discriminatedUnion("outcome", [
495
+ z6.strictObject({ outcome: z6.literal("purged") }),
496
+ z6.strictObject({ outcome: z6.literal("already_purged") }),
497
+ z6.strictObject({ outcome: z6.literal("unsupported") }),
498
+ z6.strictObject({
499
+ outcome: z6.literal("active"),
500
+ runIds: z6.array(AgentRecordIdSchema2).min(1)
501
+ }),
502
+ z6.strictObject({ outcome: z6.literal("conflict"), actualVersion: AgentRecordVersionSchema2 })
503
+ ]);
504
+
505
+ class AgentConversationPurgedError2 extends Error {
506
+ constructor() {
507
+ super("Agent conversation has been purged; use a new conversation ID");
508
+ this.name = "AgentConversationPurgedError";
509
+ }
510
+ }
511
+ async function purgeAgentConversation2(store, input) {
512
+ const parsed = AgentConversationPurgeInputSchema2.parse(input);
513
+ if (!store.purgeConversation)
514
+ return { outcome: "unsupported" };
515
+ return AgentConversationPurgeResultSchema2.parse(await store.purgeConversation(parsed));
516
+ }
517
+
518
+ // src/agent-runtime/stores/event-search.ts
519
+ import { z as z9 } from "zod";
520
+
521
+ // src/agent-runtime/stores/event-search-postgres.ts
522
+ import { z as z8 } from "zod";
523
+
524
+ // src/agent-runtime/stores/event-search-terms.ts
525
+ import { z as z7 } from "zod";
526
+ var MAX_SEARCH_TERMS = 64;
527
+ function extractSearchTerms(query) {
528
+ const terms = query.split(/\s+/u).filter((term) => /[\p{L}\p{N}]/u.test(term));
529
+ if (terms.length === 0)
530
+ throw new TypeError("Event search query must contain searchable terms");
531
+ if (terms.length > MAX_SEARCH_TERMS) {
532
+ throw new TypeError(`Event search query has ${terms.length} terms, at most ${MAX_SEARCH_TERMS} are searched`);
533
+ }
534
+ return terms;
535
+ }
536
+ var SearchRowSchema = z7.object({
537
+ conversation_id: z7.string(),
538
+ event_seq: SqlIntegerSchema.pipe(z7.int().positive()),
539
+ occurred_at: z7.string(),
540
+ snippet: z7.string()
541
+ });
542
+
543
+ // src/agent-runtime/stores/sql-session.ts
544
+ function agentSqlTables(prefix) {
545
+ return {
546
+ meta: `${prefix}_meta`,
547
+ heads: `${prefix}_heads`,
548
+ runs: `${prefix}_runs`,
549
+ admissions: `${prefix}_admissions`,
550
+ messages: `${prefix}_messages`,
551
+ seeds: `${prefix}_seeds`,
552
+ events: `${prefix}_events`,
553
+ eventSeq: `${prefix}_event_seq`,
554
+ projections: `${prefix}_projections`,
555
+ spills: `${prefix}_spills`,
556
+ schedules: `${prefix}_schedules`,
557
+ children: `${prefix}_children`,
558
+ purged: `${prefix}_purged`,
559
+ eventSearch: `${prefix}_event_search`,
560
+ eventSearchState: `${prefix}_event_search_state`
561
+ };
562
+ }
563
+ function toNumberedPlaceholders(sql) {
564
+ let out = "";
565
+ let index = 0;
566
+ let quote;
567
+ for (const char of sql) {
568
+ if (quote !== undefined) {
569
+ if (char === quote)
570
+ quote = undefined;
571
+ out += char;
572
+ continue;
573
+ }
574
+ if (char === "'" || char === '"') {
575
+ quote = char;
576
+ out += char;
577
+ continue;
578
+ }
579
+ if (char === "?") {
580
+ index += 1;
581
+ out += `$${index}`;
582
+ continue;
583
+ }
584
+ out += char;
585
+ }
586
+ return out;
587
+ }
588
+
589
+ // src/agent-runtime/stores/postgres-transactions.ts
590
+ var RETRYABLE = new Set(["40001", "40P01"]);
591
+ var MAX_ERROR_DEPTH = 6;
592
+ function* postgresErrorNodes(error, depth = 0, visited = new Set) {
593
+ if (depth >= MAX_ERROR_DEPTH || typeof error !== "object" || error === null)
594
+ return;
595
+ if (visited.has(error))
596
+ return;
597
+ visited.add(error);
598
+ yield error;
599
+ const meta = Reflect.get(error, "meta");
600
+ if (typeof meta === "object" && meta !== null) {
601
+ yield* postgresErrorNodes(Reflect.get(meta, "driverAdapterError"), depth + 1, visited);
602
+ yield* postgresErrorNodes(meta, depth + 1, visited);
603
+ }
604
+ yield* postgresErrorNodes(Reflect.get(error, "cause"), depth + 1, visited);
605
+ }
606
+ function nodeSqlState(node) {
607
+ for (const key of ["errno", "code", "originalCode", "sqlState"]) {
608
+ const field = Reflect.get(node, key);
609
+ if (typeof field === "string" && /^[0-9A-Z]{5}$/.test(field) && !/^P\d{4}$/.test(field)) {
610
+ return field;
611
+ }
612
+ }
613
+ return;
614
+ }
615
+ function p2010SqlState(node) {
616
+ if (Reflect.get(node, "code") !== "P2010")
617
+ return;
618
+ const message = Reflect.get(node, "message");
619
+ if (typeof message !== "string")
620
+ return;
621
+ const backticked = /Code:\s*`([0-9A-Z]{5})`/.exec(message);
622
+ if (backticked?.[1] !== undefined && !/^P\d{4}$/.test(backticked[1])) {
623
+ return backticked[1];
624
+ }
625
+ const retryable = /\b(40001|40P01)\b/.exec(message);
626
+ return retryable?.[1];
627
+ }
628
+ function postgresErrorState(error) {
629
+ let fromMessage;
630
+ for (const node of postgresErrorNodes(error)) {
631
+ const direct = nodeSqlState(node);
632
+ if (direct !== undefined)
633
+ return direct;
634
+ fromMessage ??= p2010SqlState(node);
635
+ }
636
+ return fromMessage;
637
+ }
638
+ function isRetryablePostgresConflict(error) {
639
+ const state = postgresErrorState(error);
640
+ if (state !== undefined && RETRYABLE.has(state))
641
+ return true;
642
+ for (const node of postgresErrorNodes(error)) {
643
+ if (Reflect.get(node, "code") === "P2034")
644
+ return true;
645
+ if (Reflect.get(node, "kind") === "TransactionWriteConflict")
646
+ return true;
647
+ }
648
+ return false;
649
+ }
650
+ var POSTGRES_ISOLATION = {
651
+ write: "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE",
652
+ read: "SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY"
653
+ };
654
+ function postgresSession(query, tx) {
655
+ const texts = new Map;
656
+ const text = (sql) => {
657
+ let numbered = texts.get(sql);
658
+ if (numbered === undefined) {
659
+ numbered = toNumberedPlaceholders(sql);
660
+ texts.set(sql, numbered);
661
+ }
662
+ return numbered;
663
+ };
664
+ return {
665
+ all: (sql, parameters = []) => query(tx, text(sql), parameters),
666
+ get: async (sql, parameters = []) => (await query(tx, text(sql), parameters))[0],
667
+ run: async (sql, parameters = []) => {
668
+ await query(tx, text(sql), parameters);
669
+ }
670
+ };
671
+ }
672
+ function backoff(attempt) {
673
+ const ceiling = Math.min(200, 2 ** attempt);
674
+ return new Promise((resolve) => setTimeout(resolve, Math.random() * ceiling));
675
+ }
676
+ async function setPostgresTransactionIsolation(session, statement) {
677
+ try {
678
+ await session.run(statement);
679
+ } catch (error) {
680
+ if (postgresErrorState(error) === "25001") {
681
+ throw new Error("The Postgres agent store opens its own transactions: `transaction` must start a new one, with no statement run in it before the store's", { cause: error });
682
+ }
683
+ throw error;
684
+ }
685
+ }
686
+ async function runPostgresTransaction(runner, access, work) {
687
+ for (let attempt = 1;; attempt += 1) {
688
+ try {
689
+ return await runner.transaction(async (tx) => {
690
+ const session = postgresSession(runner.query, tx);
691
+ await setPostgresTransactionIsolation(session, runner.isolation[access]);
692
+ return work(session);
693
+ });
694
+ } catch (error) {
695
+ if (attempt >= runner.maxAttempts || !runner.isRetryable(error))
696
+ throw error;
697
+ await backoff(attempt);
698
+ }
699
+ }
700
+ }
701
+
702
+ // src/agent-runtime/stores/event-search-postgres.ts
703
+ var BATCH = 500;
704
+ var EventRowSchema2 = z8.object({
705
+ seq: SqlIntegerSchema.pipe(z8.int().positive()),
706
+ occurred_at: z8.string(),
707
+ payload: z8.string()
708
+ });
709
+ var BehindRowSchema = z8.object({
710
+ conversation_id: z8.string(),
711
+ last_seq: SqlIntegerSchema,
712
+ indexed_seq: SqlIntegerSchema
713
+ });
714
+ var MetaRowSchema = z8.object({ value: z8.string() });
715
+ var IndexedRowSchema = z8.object({ indexed_seq: SqlIntegerSchema });
716
+ var CountSchema = z8.object({ count: SqlIntegerSchema });
717
+ function positive(name, value, fallback) {
718
+ assertPositiveSafeInteger(`Event search: ${name}`, value);
719
+ return value ?? fallback;
720
+ }
721
+ async function refuseOtherDiacriticsSettings(session, metaTable, diacritics) {
722
+ if (diacritics === "unaccent") {
723
+ const present = await session.get("SELECT 1 AS present FROM pg_extension WHERE extname = 'unaccent'");
724
+ if (present === undefined) {
725
+ throw new TypeError("Event search: diacritics 'unaccent' needs Postgres's unaccent extension (CREATE EXTENSION unaccent)");
726
+ }
727
+ }
728
+ const row = await session.get(`SELECT value FROM ${metaTable} WHERE key = 'event_search_diacritics'`);
729
+ if (row === undefined)
730
+ return false;
731
+ const recorded = MetaRowSchema.parse(row).value;
732
+ if (recorded !== diacritics) {
733
+ throw new TypeError(`Event search: the index was built with diacritics '${recorded}', this search asks for '${diacritics}'`);
734
+ }
735
+ return true;
736
+ }
737
+ function postgresEventSearchBackend(host, config = {}) {
738
+ const diacritics = config.diacritics ?? "preserve";
739
+ if (diacritics !== "preserve" && diacritics !== "unaccent") {
740
+ throw new TypeError("Event search: diacritics must be 'preserve' or 'unaccent'");
741
+ }
742
+ const maxIndexedChars = positive("maxIndexedChars", config.maxIndexedChars, 65536);
743
+ const maxSyncEvents = positive("maxSyncEvents", config.maxSyncEvents, 1e4);
744
+ const index = host.tables.eventSearch;
745
+ const state = host.tables.eventSearchState;
746
+ const fold = (expression) => diacritics === "unaccent" ? `unaccent(${expression})` : expression;
747
+ const refuseOtherSettings = (session) => refuseOtherDiacriticsSettings(session, host.tables.meta, diacritics);
748
+ const indexOne = async (session, conversationId, event) => {
749
+ for (let chars = maxIndexedChars;; chars = Math.floor(chars / 2)) {
750
+ await session.run("SAVEPOINT stitchkit_event_search");
751
+ try {
752
+ await session.run(`INSERT INTO ${index} (conversation_id, seq, occurred_at, body, document)
753
+ VALUES (?, ?, ?, left(?, ?), to_tsvector('simple', ${fold("left(?, ?)")}))
754
+ ON CONFLICT (conversation_id, seq) DO NOTHING`, [
755
+ conversationId,
756
+ event.seq,
757
+ event.occurred_at,
758
+ event.payload,
759
+ chars,
760
+ event.payload,
761
+ chars
762
+ ]);
763
+ await session.run("RELEASE SAVEPOINT stitchkit_event_search");
764
+ return;
765
+ } catch (error) {
766
+ try {
767
+ await session.run("ROLLBACK TO SAVEPOINT stitchkit_event_search");
768
+ } catch (rollbackError) {
769
+ throw new AggregateError([error, rollbackError], "Event search could not index an event, and its savepoint rollback failed too", { cause: error });
770
+ }
771
+ if (postgresErrorState(error) !== "54000" || chars === 0)
772
+ throw error;
773
+ }
774
+ }
775
+ };
776
+ const catchUp = (conversationId, budget) => host.transaction(conversationId, async (scope) => {
777
+ if (!await refuseOtherSettings(scope)) {
778
+ await scope.run(`INSERT INTO ${host.tables.meta} (key, value) VALUES ('event_search_diacritics', ?)
779
+ ON CONFLICT (key) DO NOTHING`, [diacritics]);
780
+ await refuseOtherSettings(scope);
781
+ }
782
+ const done = await scope.get(`SELECT indexed_seq FROM ${state} WHERE conversation_id = ?`, [conversationId]);
783
+ const from = done === undefined ? 0 : IndexedRowSchema.parse(done).indexed_seq;
784
+ const events = (await scope.all(`SELECT seq, occurred_at, payload FROM ${host.tables.events}
785
+ WHERE conversation_id = ? AND seq > ? ORDER BY seq LIMIT ?`, [conversationId, from, Math.min(budget, BATCH)])).map((row) => EventRowSchema2.parse(row));
786
+ for (const event of events)
787
+ await indexOne(scope, conversationId, event);
788
+ const last = events.at(-1);
789
+ if (last !== undefined) {
790
+ await scope.run(`INSERT INTO ${state} (conversation_id, indexed_seq) VALUES (?, ?)
791
+ ON CONFLICT (conversation_id) DO UPDATE SET indexed_seq = excluded.indexed_seq`, [conversationId, last.seq]);
792
+ }
793
+ return events.length;
794
+ }).catch((error) => {
795
+ if (error instanceof AgentConversationPurgedError2)
796
+ return 0;
797
+ throw error;
798
+ });
799
+ const behind = (target) => host.read(async (session) => (await session.all(`SELECT q.conversation_id, q.last_seq, COALESCE(s.indexed_seq, 0) AS indexed_seq
800
+ FROM ${host.tables.eventSeq} q LEFT JOIN ${state} s USING (conversation_id)
801
+ WHERE q.last_seq > COALESCE(s.indexed_seq, 0)
802
+ ${target === undefined ? "" : "AND q.conversation_id = ?"}
803
+ ORDER BY q.conversation_id`, target === undefined ? [] : [target])).map((row) => BehindRowSchema.parse(row)));
804
+ const sync = async (target) => {
805
+ let budget = maxSyncEvents;
806
+ const initial = await behind(target);
807
+ if (initial.length === 0)
808
+ return;
809
+ const watermarks = new Map(initial.map((row) => [row.conversation_id, row.last_seq]));
810
+ for (const conversation of initial) {
811
+ let pending = conversation.last_seq - conversation.indexed_seq;
812
+ while (pending > 0 && budget > 0) {
813
+ const indexed = await catchUp(conversation.conversation_id, budget);
814
+ if (indexed === 0)
815
+ break;
816
+ pending -= indexed;
817
+ budget -= indexed;
818
+ }
819
+ }
820
+ const left = (await behind(target)).reduce((sum, row) => {
821
+ const watermark = watermarks.get(row.conversation_id);
822
+ if (watermark === undefined)
823
+ return sum;
824
+ return sum + Math.max(0, watermark - row.indexed_seq);
825
+ }, 0);
826
+ if (left > 0) {
827
+ throw new TypeError(`Event search: the index is ${left} events behind after indexing ${maxSyncEvents - budget}; search again to continue`);
828
+ }
829
+ };
830
+ return {
831
+ async prepare(request) {
832
+ await host.read(async (session) => {
833
+ await refuseOtherSettings(session);
834
+ for (const term of request.terms) {
835
+ const row = await session.get(`SELECT numnode(phraseto_tsquery('simple', ${fold("?")})) AS count`, [term]);
836
+ if (CountSchema.parse(row).count === 0) {
837
+ throw new TypeError("Event search query must contain searchable terms");
838
+ }
839
+ }
840
+ });
841
+ await sync(request.target);
842
+ },
843
+ async candidates(request) {
844
+ return host.read(async (session) => {
845
+ const query = request.terms.map(() => `phraseto_tsquery('simple', ${fold("?")})`).join(" && ");
846
+ const values = [...request.terms];
847
+ if (request.target)
848
+ values.push(request.target);
849
+ if (request.since)
850
+ values.push(request.since);
851
+ const rows = await session.all(`SELECT s.conversation_id, s.seq AS event_seq, s.occurred_at,
852
+ ts_headline('simple', ${fold("s.body")}, q.query,
853
+ 'StartSel=[, StopSel=], MaxWords=24, MinWords=8, MaxFragments=2, FragmentDelimiter=" … "') AS snippet
854
+ FROM ${index} s, (SELECT ${query} AS query) q
855
+ WHERE s.document @@ q.query
856
+ ${request.target ? "AND s.conversation_id = ?" : ""}
857
+ ${request.since ? "AND s.occurred_at::timestamptz >= ?::timestamptz" : ""}
858
+ ORDER BY ts_rank_cd(s.document, q.query) DESC, s.occurred_at DESC, s.seq
859
+ LIMIT ? OFFSET ?`, [...values, request.limit, request.offset]);
860
+ return rows.map((row) => SearchRowSchema.parse(row));
861
+ });
862
+ }
863
+ };
864
+ }
865
+
866
+ // src/agent-runtime/stores/event-search.ts
867
+ var AgentEventSearchResultSchema2 = z9.object({
868
+ conversationId: z9.string().min(1),
869
+ seq: z9.int().positive(),
870
+ occurredAt: z9.string(),
871
+ snippet: z9.string()
872
+ }).strict();
873
+ function sqliteBackend(host) {
874
+ const fts = `${host.tables.events}_fts`;
875
+ return {
876
+ async candidates(request) {
877
+ const values = [
878
+ request.terms.map((term) => `"${term.replaceAll('"', '""')}"`).join(" AND ")
879
+ ];
880
+ if (request.target)
881
+ values.push(request.target);
882
+ if (request.since)
883
+ values.push(request.since);
884
+ const rows = await host.read((session) => session.all(`SELECT f.conversation_id, f.event_seq, f.occurred_at,
885
+ snippet(${fts}, 3, '[', ']', ' … ', 24) AS snippet
886
+ FROM ${fts} AS f
887
+ WHERE ${fts} MATCH ?
888
+ ${request.target ? "AND f.conversation_id = ?" : ""}
889
+ ${request.since ? "AND f.occurred_at >= ?" : ""}
890
+ ORDER BY bm25(${fts}), f.occurred_at DESC, f.rowid
891
+ LIMIT ? OFFSET ?`, [...values, request.limit, request.offset]));
892
+ return rows.map((row) => SearchRowSchema.parse(row));
893
+ }
894
+ };
895
+ }
896
+ function createAgentEventSearch2(input) {
897
+ const { host } = input;
898
+ if (host.dialect === "sqlite" && input.postgres !== undefined) {
899
+ throw new TypeError("Event search: `postgres` options apply to the Postgres store only");
900
+ }
901
+ const backend = host.dialect === "sqlite" ? sqliteBackend(host) : postgresEventSearchBackend(host, input.postgres);
902
+ return async (request) => {
903
+ if (request.query.trim().length === 0)
904
+ throw new TypeError("Event search query must not be empty");
905
+ const terms = extractSearchTerms(request.query);
906
+ if (request.limit !== undefined) {
907
+ assertPositiveSafeInteger("Event search limit", request.limit, TypeError);
908
+ }
909
+ const limit = Math.min(request.limit ?? 20, 200);
910
+ const target = request.conversationId ?? (input.authorizeConversation ? undefined : request.requestingConversationId);
911
+ const since = request.since ? z9.iso.datetime({ offset: true }).parse(request.since) : undefined;
912
+ await backend.prepare?.({ terms, ...target !== undefined && { target } });
913
+ const page = limit * 4;
914
+ const candidatesFrom = (offset) => backend.candidates({
915
+ terms,
916
+ ...target !== undefined && { target },
917
+ ...since !== undefined && { since },
918
+ limit: page,
919
+ offset
920
+ });
921
+ const authorization = new Map;
922
+ const results = [];
923
+ let offset = 0;
924
+ let candidates = await candidatesFrom(offset);
925
+ while (candidates.length > 0 && results.length < limit) {
926
+ for (const row of candidates) {
927
+ if (row.conversation_id !== request.requestingConversationId) {
928
+ let allowed = authorization.get(row.conversation_id);
929
+ if (allowed === undefined) {
930
+ allowed = input.authorizeConversation ? await input.authorizeConversation({
931
+ requestingConversationId: request.requestingConversationId,
932
+ targetConversationId: row.conversation_id
933
+ }) : false;
934
+ authorization.set(row.conversation_id, allowed);
935
+ }
936
+ if (!allowed)
937
+ continue;
938
+ }
939
+ results.push(AgentEventSearchResultSchema2.parse({
940
+ conversationId: row.conversation_id,
941
+ seq: row.event_seq,
942
+ occurredAt: row.occurred_at,
943
+ snippet: row.snippet
944
+ }));
945
+ if (results.length === limit)
946
+ break;
947
+ }
948
+ offset += page;
949
+ candidates = results.length < limit ? await candidatesFrom(offset) : [];
950
+ }
951
+ return results;
952
+ };
953
+ }
954
+
955
+ // src/agent-runtime/stores/event-search-tools.ts
956
+ import { z as z10 } from "zod";
957
+ var AGENT_EVENT_SEARCH_TOOL_NAMES = {
958
+ search: "session_search",
959
+ trace: "session_trace",
960
+ event: "session_event"
961
+ };
962
+ var EventAddressSchema = z10.object({ conversationId: z10.string(), seq: z10.int().positive() }).strict();
963
+ var EventOutputSchema = z10.object({
964
+ conversationId: z10.string(),
965
+ seq: z10.int().positive(),
966
+ kind: z10.string(),
967
+ occurredAt: z10.string(),
968
+ payload: z10.json()
969
+ }).strict();
970
+ var SearchInputSchema = z10.object({
971
+ query: z10.string().min(1),
972
+ conversationId: z10.string().min(1).optional(),
973
+ since: z10.iso.datetime({ offset: true }).optional(),
974
+ limit: z10.int().positive().max(200).optional()
975
+ }).strict();
976
+ var SearchOutputSchema = z10.object({ results: z10.array(AgentEventSearchResultSchema2) }).strict();
977
+ var TraceInputSchema = z10.object({
978
+ fromSeq: z10.int().positive().optional(),
979
+ toSeq: z10.int().positive().optional(),
980
+ limit: z10.int().positive().max(1000).default(100)
981
+ }).strict();
982
+ var TraceOutputSchema = z10.object({ events: z10.array(EventOutputSchema), nextSeq: z10.number().optional() }).strict();
983
+ var SEARCH_DESCRIPTOR = defineAgentToolDescriptor({
984
+ name: AGENT_EVENT_SEARCH_TOOL_NAMES.search,
985
+ description: "Search authorized durable conversation events and return exact addresses.",
986
+ identity: { serviceName: "agent-events", action: "search", method: "POST" },
987
+ input: SearchInputSchema,
988
+ output: SearchOutputSchema,
989
+ expose: ["AGENT"]
990
+ });
991
+ var TRACE_DESCRIPTOR = defineAgentToolDescriptor({
992
+ name: AGENT_EVENT_SEARCH_TOOL_NAMES.trace,
993
+ description: "Read a bounded contiguous slice of this conversation event trace.",
994
+ identity: { serviceName: "agent-events", action: "trace", method: "GET" },
995
+ input: TraceInputSchema,
996
+ output: TraceOutputSchema,
997
+ expose: ["AGENT"]
998
+ });
999
+ var EVENT_DESCRIPTOR = defineAgentToolDescriptor({
1000
+ name: AGENT_EVENT_SEARCH_TOOL_NAMES.event,
1001
+ description: "Read one durable event by exact conversation and sequence address.",
1002
+ identity: { serviceName: "agent-events", action: "read", method: "GET" },
1003
+ input: EventAddressSchema,
1004
+ output: EventOutputSchema,
1005
+ expose: ["AGENT"]
1006
+ });
1007
+ var AGENT_EVENT_SEARCH_TOOL_DESCRIPTORS2 = Object.freeze([
1008
+ SEARCH_DESCRIPTOR,
1009
+ TRACE_DESCRIPTOR,
1010
+ EVENT_DESCRIPTOR
1011
+ ]);
1012
+ var AGENT_EVENT_SEARCH_TOOL_SCHEMAS = {
1013
+ [SEARCH_DESCRIPTOR.name]: {
1014
+ input: SEARCH_DESCRIPTOR.input,
1015
+ output: SEARCH_DESCRIPTOR.output
1016
+ },
1017
+ [TRACE_DESCRIPTOR.name]: {
1018
+ input: TRACE_DESCRIPTOR.input,
1019
+ output: TRACE_DESCRIPTOR.output
1020
+ },
1021
+ [EVENT_DESCRIPTOR.name]: {
1022
+ input: EVENT_DESCRIPTOR.input,
1023
+ output: EVENT_DESCRIPTOR.output
1024
+ }
1025
+ };
1026
+ function createAgentEventSearchTools2(config) {
1027
+ const input = {
1028
+ ...config,
1029
+ conversationId: conversationOfRun(config.run, "createAgentEventSearchTools")
1030
+ };
1031
+ const readExact = async (address) => {
1032
+ if (address.conversationId !== input.conversationId) {
1033
+ const allowed = await input.authorizeConversation?.({
1034
+ requestingConversationId: input.conversationId,
1035
+ targetConversationId: address.conversationId
1036
+ });
1037
+ if (!allowed)
1038
+ throw new TypeError("Event address is outside the authorized conversation");
1039
+ }
1040
+ const page = await input.store.readEvents({
1041
+ conversationId: address.conversationId,
1042
+ fromSeq: address.seq,
1043
+ toSeq: address.seq,
1044
+ limit: 1
1045
+ });
1046
+ const event = page.items[0];
1047
+ if (!event || event.seq !== address.seq)
1048
+ throw new TypeError("Unknown event address");
1049
+ return {
1050
+ conversationId: event.conversationId,
1051
+ seq: event.seq,
1052
+ kind: event.kind,
1053
+ occurredAt: event.occurredAt,
1054
+ payload: event.payload
1055
+ };
1056
+ };
1057
+ return [
1058
+ bindAgentTool(SEARCH_DESCRIPTOR, async ({ input: request }) => ({
1059
+ results: [
1060
+ ...await input.search({
1061
+ requestingConversationId: input.conversationId,
1062
+ ...request
1063
+ })
1064
+ ]
1065
+ })),
1066
+ bindAgentTool(TRACE_DESCRIPTOR, async ({ input: request }) => {
1067
+ const page = await input.store.readEvents({
1068
+ conversationId: input.conversationId,
1069
+ ...request
1070
+ });
1071
+ return {
1072
+ events: page.items.map((event) => ({
1073
+ conversationId: event.conversationId,
1074
+ seq: event.seq,
1075
+ kind: event.kind,
1076
+ occurredAt: event.occurredAt,
1077
+ payload: event.payload
1078
+ })),
1079
+ ...page.nextSeq !== undefined && { nextSeq: page.nextSeq }
1080
+ };
1081
+ }),
1082
+ bindAgentTool(EVENT_DESCRIPTOR, ({ input: request }) => readExact(request))
1083
+ ];
1084
+ }
1085
+
1086
+ // src/agent-runtime/stores/store-capabilities.ts
1087
+ import { z as z11 } from "zod";
1088
+ var AgentStoreOptionalCapabilitySchema = z11.enum(["archive", "historyRestore"]);
1089
+ var AgentRuntimeStoreCapabilitiesSchema = z11.strictObject({
1090
+ archive: z11.boolean(),
1091
+ historyRestore: z11.boolean(),
1092
+ purge: z11.boolean()
1093
+ });
1094
+
1095
+ class AgentStoreUnsupportedCapabilityError2 extends TypeError {
1096
+ capability;
1097
+ constructor(capability, need) {
1098
+ super(`The agent store driver does not implement ${capability === "archive" ? "archive" : "history.restore"}: ${need}`);
1099
+ this.name = "AgentStoreUnsupportedCapabilityError";
1100
+ this.capability = capability;
1101
+ }
1102
+ }
1103
+ function driverCapabilities(driver) {
1104
+ const archive = driver.archive;
1105
+ if (archive !== undefined && (typeof archive.export !== "function" || typeof archive.import !== "function"))
1106
+ throw new TypeError("An agent store driver archive needs both export and import");
1107
+ if (driver.history.restore !== undefined && typeof driver.history.restore !== "function")
1108
+ throw new TypeError("An agent store driver history.restore must be a function");
1109
+ return Object.freeze(AgentRuntimeStoreCapabilitiesSchema.parse({
1110
+ archive: archive !== undefined,
1111
+ historyRestore: driver.history.restore !== undefined,
1112
+ purge: driver.conversations !== undefined
1113
+ }));
1114
+ }
1115
+ function assertSourceCapabilities(driver, source) {
1116
+ if (!driver.archive && source.spills > 0)
1117
+ throw new AgentStoreUnsupportedCapabilityError2("archive", "the source carries spills");
1118
+ if (!driver.archive && source.projections > 0)
1119
+ throw new AgentStoreUnsupportedCapabilityError2("archive", "the source carries companion projections");
1120
+ if (!driver.history.restore && source.compacted > 0)
1121
+ throw new AgentStoreUnsupportedCapabilityError2("historyRestore", "the source baseline carries compacted history");
1122
+ }
1123
+
1124
+ // src/agent-runtime/stores/store-create.ts
1125
+ import { z as z25 } from "zod";
1126
+
1127
+ // src/agent-runtime/stores/store-archive.ts
1128
+ import { z as z14 } from "zod";
1129
+
1130
+ // src/agent-runtime/stores/archive-projection.ts
1131
+ import { z as z12 } from "zod";
1132
+ var ArchiveProjectionSchema = z12.object({
1133
+ name: z12.string(),
1134
+ version: z12.int().positive(),
1135
+ uptoSeq: z12.int().nonnegative(),
1136
+ value: z12.json(),
1137
+ updatedAt: z12.string()
1138
+ }).strict();
1139
+ function isRuntimeSnapshotEntry(entry) {
1140
+ return typeof entry === "object" && entry !== null && !Array.isArray(entry) && Reflect.get(entry, "archiveType") === "runtime-snapshot" && "snapshot" in entry;
1141
+ }
1142
+
1143
+ // src/agent-runtime/stores/branch-replay.ts
1144
+ import { createHash as createHash2 } from "node:crypto";
1145
+ import { z as z13 } from "zod";
1146
+
1147
+ // src/agent-runtime/stores/store-reducer.ts
1148
+ import { createHash } from "node:crypto";
1149
+
1150
+ // src/agent-runtime/stores/store-snapshot.ts
1151
+ function historyPositions(messages) {
1152
+ const positions = new Map;
1153
+ messages.forEach((message, index) => {
1154
+ if (!positions.has(message.id))
1155
+ positions.set(message.id, index);
1156
+ });
1157
+ return (run) => {
1158
+ let earliest = Number.MAX_SAFE_INTEGER;
1159
+ for (const id of [...run.inputMessageIds, run.assistantMessageId]) {
1160
+ const position = positions.get(id);
1161
+ if (position !== undefined && position < earliest)
1162
+ earliest = position;
1163
+ }
1164
+ return earliest;
1165
+ };
1166
+ }
1167
+ function orderRuns(messages, runs) {
1168
+ const positionOf = historyPositions(messages);
1169
+ const fallback = (left, right) => left.createdAt.localeCompare(right.createdAt) || positionOf(left) - positionOf(right) || left.id.localeCompare(right.id);
1170
+ return [...runs].sort((left, right) => {
1171
+ if (left.executionSequence !== undefined && right.executionSequence !== undefined && left.executionSequence !== right.executionSequence) {
1172
+ return left.executionSequence - right.executionSequence;
1173
+ }
1174
+ const leftStarted = left.executionSequence !== undefined || left.state !== "queued";
1175
+ const rightStarted = right.executionSequence !== undefined || right.state !== "queued";
1176
+ if (leftStarted !== rightStarted)
1177
+ return leftStarted ? -1 : 1;
1178
+ if (!leftStarted && !rightStarted) {
1179
+ const priority = Number(right.queuePriority !== undefined) - Number(left.queuePriority !== undefined);
1180
+ if (priority !== 0)
1181
+ return priority;
1182
+ }
1183
+ return fallback(left, right);
1184
+ });
1185
+ }
1186
+ function orderRunMessages(messages, runs) {
1187
+ const byId = new Map(messages.map((message) => [message.id, message]));
1188
+ const ownedIds = new Set(runs.flatMap((run) => [...run.inputMessageIds, run.assistantMessageId]));
1189
+ const orderedOwned = runs.flatMap((run) => [...run.inputMessageIds, run.assistantMessageId].flatMap((id) => {
1190
+ const message = byId.get(id);
1191
+ return message ? [message] : [];
1192
+ }));
1193
+ let ownedIndex = 0;
1194
+ return messages.map((message) => {
1195
+ if (!ownedIds.has(message.id))
1196
+ return message;
1197
+ const ordered = orderedOwned[ownedIndex];
1198
+ if (!ordered)
1199
+ throw new TypeError("Stored agent history lost a run-owned message");
1200
+ ownedIndex += 1;
1201
+ return ordered;
1202
+ });
1203
+ }
1204
+ function snapshotOf(head, messages, records) {
1205
+ validateSnapshot(head, messages, records);
1206
+ const runs = orderRuns(messages, records.map((record) => record.run));
1207
+ return AgentSnapshotSchema2.parse({
1208
+ schemaVersion: 1,
1209
+ conversationId: head.conversationId,
1210
+ version: head.version,
1211
+ messages: orderRunMessages(messages, runs),
1212
+ runs
1213
+ });
1214
+ }
1215
+ function validateSnapshot(head, messages, records) {
1216
+ const runIds = new Set;
1217
+ const assistantIds = new Set;
1218
+ const messageIds = new Set;
1219
+ for (const record of records) {
1220
+ const run = record.run;
1221
+ if (run.conversationId !== head.conversationId || runIds.has(run.id) || assistantIds.has(run.assistantMessageId)) {
1222
+ throw new TypeError("Stored agent runs contain inconsistent identities");
1223
+ }
1224
+ if (record.terminalAssistant && (record.terminalAssistant.id !== run.assistantMessageId || record.terminalAssistant.conversationId !== run.conversationId || record.terminalAssistant.runId !== run.id || record.terminalAssistant.role !== "assistant" || run.terminalReason === undefined)) {
1225
+ throw new TypeError("Retained terminal assistant does not match its run");
1226
+ }
1227
+ runIds.add(run.id);
1228
+ assistantIds.add(run.assistantMessageId);
1229
+ }
1230
+ for (const message of messages) {
1231
+ if (message.conversationId !== head.conversationId || messageIds.has(message.id)) {
1232
+ throw new TypeError("Stored agent history contains inconsistent message identities");
1233
+ }
1234
+ messageIds.add(message.id);
1235
+ if (assistantIds.has(message.id) && message.runId === undefined) {
1236
+ throw new TypeError("Stored history occupies a reserved assistant identity");
1237
+ }
1238
+ if (message.runId !== undefined) {
1239
+ const run = records.find((candidate) => candidate.run.id === message.runId)?.run;
1240
+ if (!run || message.role !== "assistant" || run.assistantMessageId !== message.id) {
1241
+ throw new TypeError("Stored assistant history does not match its reserved run identity");
1242
+ }
1243
+ }
1244
+ }
1245
+ }
1246
+ function replaceRun(runs, next) {
1247
+ return runs.map((run) => run.id === next.id ? next : run);
1248
+ }
1249
+ function replaceMessage(messages, next) {
1250
+ return messages.some((message) => message.id === next.id) ? messages.map((message) => message.id === next.id ? next : message) : [...messages, next];
1251
+ }
1252
+ function mergeRunRecords(...groups) {
1253
+ const records = new Map;
1254
+ for (const group of groups) {
1255
+ for (const rawRecord of group) {
1256
+ const record = AgentStoredRunSchema2.parse(rawRecord);
1257
+ const previous = records.get(record.run.id);
1258
+ if (previous && previous.run.assistantMessageId !== record.run.assistantMessageId) {
1259
+ throw new TypeError("Stored agent run identity changed across normalized records");
1260
+ }
1261
+ records.set(record.run.id, record);
1262
+ }
1263
+ }
1264
+ return [...records.values()];
1265
+ }
1266
+ function referencedRunIds(messages) {
1267
+ return [...new Set(messages.flatMap((message) => message.runId ? [message.runId] : []))];
1268
+ }
1269
+
1270
+ // src/agent-runtime/stores/store-reduce-shared.ts
1271
+ function conflict(actualVersion) {
1272
+ return { outcome: "conflict", actualVersion };
1273
+ }
1274
+ function applied(current, input, effects) {
1275
+ const runs = input.runs ?? current.runs;
1276
+ const messages = input.messages ?? current.messages;
1277
+ return {
1278
+ outcome: "applied",
1279
+ snapshot: AgentSnapshotSchema2.parse({
1280
+ ...current,
1281
+ version: current.version + 1,
1282
+ runs,
1283
+ messages: orderRunMessages(messages, runs)
1284
+ }),
1285
+ ...effects?.runRecords?.length && { runRecords: effects.runRecords },
1286
+ ...effects?.admissionReceipt && { admissionReceipt: effects.admissionReceipt },
1287
+ ...effects?.seedReceipt && { seedReceipt: effects.seedReceipt },
1288
+ ...effects?.historyMutations?.length && { historyMutations: effects.historyMutations }
1289
+ };
1290
+ }
1291
+
1292
+ // src/agent-runtime/stores/store-reduce-history.ts
1293
+ function reduceAccept(current, input) {
1294
+ if (input.expectedVersion !== undefined && input.expectedVersion !== current.version) {
1295
+ return conflict(current.version);
1296
+ }
1297
+ const coalescedRun = input.coalesceIntoRunId ? current.runs.find((candidate) => candidate.id === input.coalesceIntoRunId) : undefined;
1298
+ if (input.coalesceIntoRunId !== undefined && (!coalescedRun || coalescedRun.conversationId !== input.input.conversationId || coalescedRun.state !== "queued" || coalescedRun.ownerId !== undefined || coalescedRun.terminalReason !== undefined)) {
1299
+ return coalescedRun ? conflict(coalescedRun.revision) : { outcome: "not_found" };
1300
+ }
1301
+ if (input.run.conversationId !== input.input.conversationId || input.run.inputMessageIds.length !== 1 || input.run.inputMessageIds[0] !== input.input.id || input.run.state !== "queued" || input.run.revision !== 0 || input.run.executionSequence !== undefined || input.run.ownerId !== undefined || input.run.terminalReason !== undefined || input.run.terminalPolicyName !== undefined || input.input.role !== "user" && input.input.role !== "tool" || input.input.status !== "committed" || input.input.runId !== undefined || current.messages.some((message) => message.id === input.input.id) || coalescedRun !== undefined && input.input.id === coalescedRun.assistantMessageId || !coalescedRun && (input.run.assistantMessageId === input.input.id || current.runs.some((candidate) => candidate.id === input.run.id) || current.runs.some((candidate) => candidate.assistantMessageId === input.run.assistantMessageId) || current.messages.some((message) => message.id === input.run.assistantMessageId))) {
1302
+ throw new TypeError("Input and queued run do not form one valid assignment");
1303
+ }
1304
+ const assignedRun = coalescedRun ? AgentRunSchema2.parse({
1305
+ ...coalescedRun,
1306
+ inputMessageIds: [...coalescedRun.inputMessageIds, input.input.id],
1307
+ revision: coalescedRun.revision + 1,
1308
+ updatedAt: new Date().toISOString()
1309
+ }) : input.run;
1310
+ const admissionReceipt = AgentAdmissionReceiptSchema2.parse({
1311
+ schemaVersion: 1,
1312
+ conversationId: input.input.conversationId,
1313
+ idempotencyKey: input.idempotencyKey,
1314
+ input: input.input,
1315
+ runId: assignedRun.id,
1316
+ assistantMessageId: assignedRun.assistantMessageId
1317
+ });
1318
+ return applied(current, {
1319
+ messages: [...current.messages, input.input],
1320
+ runs: coalescedRun ? replaceRun(current.runs, assignedRun) : [...current.runs, assignedRun]
1321
+ }, {
1322
+ runRecords: [AgentStoredRunSchema2.parse({ schemaVersion: 1, run: assignedRun })],
1323
+ admissionReceipt,
1324
+ historyMutations: [{ type: "admit", input: input.input }]
1325
+ });
1326
+ }
1327
+ function seedReceipt(input) {
1328
+ return AgentSeedReceiptSchema2.parse({
1329
+ schemaVersion: 1,
1330
+ conversationId: input.conversationId,
1331
+ seedKey: input.seedKey,
1332
+ messageIds: input.inputs.map((message) => message.id)
1333
+ });
1334
+ }
1335
+ function reduceSettledSeed(current, input) {
1336
+ for (const message of input.inputs) {
1337
+ if (message.conversationId !== input.conversationId || message.runId !== undefined || !(message.role === "user" && message.status === "committed" || message.role === "assistant" && message.status === "completed")) {
1338
+ throw new TypeError("A settled exchange must be committed user and completed assistant messages no run owns");
1339
+ }
1340
+ }
1341
+ const activeMessageIds = new Set(current.runs.filter((run) => isActiveRunState(run.state)).flatMap((run) => [...run.inputMessageIds, run.assistantMessageId]));
1342
+ const anchor = current.messages.find((message) => activeMessageIds.has(message.id));
1343
+ const at = anchor ? current.messages.indexOf(anchor) : current.messages.length;
1344
+ return applied(current, {
1345
+ messages: [
1346
+ ...current.messages.slice(0, at),
1347
+ ...input.inputs,
1348
+ ...current.messages.slice(at)
1349
+ ]
1350
+ }, {
1351
+ seedReceipt: seedReceipt(input),
1352
+ historyMutations: input.inputs.map((message) => ({
1353
+ type: "insert",
1354
+ message,
1355
+ ...anchor && { beforeMessageId: anchor.id }
1356
+ }))
1357
+ });
1358
+ }
1359
+ function reduceSeed(current, input) {
1360
+ const conversationId = input.conversationId;
1361
+ if (current.conversationId !== conversationId)
1362
+ return { outcome: "not_found" };
1363
+ if (input.placement === "after-settled")
1364
+ return reduceSettledSeed(current, input);
1365
+ for (const message of input.inputs) {
1366
+ if (message.conversationId !== conversationId || message.role !== "user" || message.status !== "committed" || message.runId !== undefined) {
1367
+ throw new TypeError("Seeded conversation input must be committed unowned user messages");
1368
+ }
1369
+ }
1370
+ return applied(current, { messages: [...input.inputs, ...current.messages] }, {
1371
+ seedReceipt: seedReceipt(input),
1372
+ historyMutations: [...input.inputs].reverse().map((message) => ({
1373
+ type: "seed",
1374
+ message
1375
+ }))
1376
+ });
1377
+ }
1378
+ function reduceCompact(current, input) {
1379
+ if (current.conversationId !== input.conversationId)
1380
+ return { outcome: "not_found" };
1381
+ if (current.version !== input.expectedVersion)
1382
+ return conflict(current.version);
1383
+ const replaced = new Set(input.replacedMessageIds);
1384
+ if (!input.replacedMessageIds.every((id) => current.messages.some((m) => m.id === id))) {
1385
+ return { outcome: "not_found" };
1386
+ }
1387
+ const liveAssistant = current.runs.find((candidate) => isActiveRunState(candidate.state) && replaced.has(candidate.assistantMessageId));
1388
+ if (liveAssistant) {
1389
+ throw new TypeError(`Compaction may not replace the assistant message of run ${liveAssistant.id}, which has not finished`);
1390
+ }
1391
+ const positions = current.messages.map((message, index) => replaced.has(message.id) ? index : undefined).filter((index) => index !== undefined);
1392
+ const first = positions[0];
1393
+ if (first === undefined || positions.some((position, offset) => position !== first + offset) || input.summary.conversationId !== input.conversationId || input.summary.runId !== undefined || input.summary.role !== "summary" || input.summary.status !== "committed" || current.messages.some((message) => message.id === input.summary.id) || current.runs.some((candidate) => candidate.assistantMessageId === input.summary.id)) {
1394
+ throw new TypeError("Compaction replacement must be one valid contiguous history range");
1395
+ }
1396
+ const messages = [
1397
+ ...current.messages.slice(0, first),
1398
+ input.summary,
1399
+ ...current.messages.slice(first + positions.length)
1400
+ ];
1401
+ return applied(current, { messages }, {
1402
+ historyMutations: [
1403
+ {
1404
+ type: "replace-compacted-range",
1405
+ replacedMessageIds: input.replacedMessageIds,
1406
+ summary: input.summary
1407
+ }
1408
+ ]
1409
+ });
1410
+ }
1411
+
1412
+ // src/agent-runtime/stores/store-reduce-run.ts
1413
+ function reduceAcquire(current, run, input) {
1414
+ const runPosition = current.runs.findIndex((candidate) => candidate.id === run.id);
1415
+ const acquisitionBlocked = current.runs.some((candidate, index) => candidate.id !== run.id && (candidate.state === "running" || candidate.state === "interrupt_requested" || index < runPosition && candidate.state === "queued"));
1416
+ if (run.revision !== input.expectedRevision || run.state !== "queued" || acquisitionBlocked) {
1417
+ return conflict(run.revision);
1418
+ }
1419
+ const next = AgentRunSchema2.parse({
1420
+ ...run,
1421
+ state: "running",
1422
+ executionSequence: run.executionSequence ?? current.version + 1,
1423
+ ownerId: input.ownerId,
1424
+ fencingToken: (run.fencingToken ?? 0) + 1,
1425
+ revision: run.revision + 1,
1426
+ updatedAt: new Date().toISOString()
1427
+ });
1428
+ return applied(current, { runs: replaceRun(current.runs, next) }, {
1429
+ runRecords: [AgentStoredRunSchema2.parse({ schemaVersion: 1, run: next })]
1430
+ });
1431
+ }
1432
+ function reduceCheckpoint(current, run, input) {
1433
+ if (run.revision !== input.expectedRevision || run.state !== "running" || run.ownerId !== input.ownerId || input.fencingToken !== undefined && run.fencingToken !== input.fencingToken || input.assistant.runId !== run.id || input.assistant.id !== run.assistantMessageId || input.assistant.conversationId !== run.conversationId || input.assistant.role !== "assistant" || input.assistant.status !== "streaming") {
1434
+ return conflict(run.revision);
1435
+ }
1436
+ const next = AgentRunSchema2.parse({
1437
+ ...run,
1438
+ ...input.usage && { usage: input.usage },
1439
+ revision: run.revision + 1,
1440
+ updatedAt: new Date().toISOString()
1441
+ });
1442
+ return applied(current, {
1443
+ runs: replaceRun(current.runs, next),
1444
+ messages: replaceMessage(current.messages, input.assistant)
1445
+ }, {
1446
+ runRecords: [AgentStoredRunSchema2.parse({ schemaVersion: 1, run: next })],
1447
+ historyMutations: [{ type: "upsert-assistant", message: input.assistant }]
1448
+ });
1449
+ }
1450
+ function reduceOperation(current, run, input) {
1451
+ if (run.revision !== input.expectedRevision || run.state !== "running" && run.state !== "interrupt_requested" || run.ownerId !== input.ownerId || input.fencingToken !== undefined && run.fencingToken !== input.fencingToken) {
1452
+ return conflict(run.revision);
1453
+ }
1454
+ const next = AgentRunSchema2.parse({
1455
+ ...run,
1456
+ lastOperation: input.operation,
1457
+ revision: run.revision + 1,
1458
+ updatedAt: new Date().toISOString()
1459
+ });
1460
+ return applied(current, { runs: replaceRun(current.runs, next) }, { runRecords: [AgentStoredRunSchema2.parse({ schemaVersion: 1, run: next })] });
1461
+ }
1462
+ function reduceInterrupt(current, run, input) {
1463
+ if (run.revision !== input.expectedRevision || run.state !== "running") {
1464
+ return conflict(run.revision);
1465
+ }
1466
+ const next = AgentRunSchema2.parse({
1467
+ ...run,
1468
+ state: "interrupt_requested",
1469
+ revision: run.revision + 1,
1470
+ updatedAt: new Date().toISOString()
1471
+ });
1472
+ return applied(current, { runs: replaceRun(current.runs, next) }, {
1473
+ runRecords: [AgentStoredRunSchema2.parse({ schemaVersion: 1, run: next })]
1474
+ });
1475
+ }
1476
+ function reduceRecover(current, run, input, retainedAssistant) {
1477
+ if (run.revision !== input.expectedRevision || !isActiveRunState(run.state)) {
1478
+ return conflict(run.revision);
1479
+ }
1480
+ if (input.action === "requeue" && run.state !== "queued" && input.replaySafe !== true) {
1481
+ throw new TypeError("Recovering an acquired run requires explicit replaySafe evidence");
1482
+ }
1483
+ const { ownerId: _released, ...carried } = run;
1484
+ const next = AgentRunSchema2.parse({
1485
+ ...carried,
1486
+ state: input.action === "requeue" ? "queued" : "abandoned",
1487
+ revision: run.revision + 1,
1488
+ ...input.action === "abandon" && { terminalReason: "abandoned" },
1489
+ updatedAt: new Date().toISOString()
1490
+ });
1491
+ if (input.action === "abandon") {
1492
+ if (retainedAssistant && (retainedAssistant.id !== run.assistantMessageId || retainedAssistant.conversationId !== run.conversationId || retainedAssistant.runId !== run.id || retainedAssistant.role !== "assistant" || retainedAssistant.status !== "failed"))
1493
+ throw new TypeError("Abandoned assistant does not match its run");
1494
+ const existingAssistant = current.messages.find((message) => message.id === run.assistantMessageId);
1495
+ const assistant = retainedAssistant ?? AgentMessageSchema2.parse({
1496
+ ...existingAssistant ?? {
1497
+ schemaVersion: 1,
1498
+ id: run.assistantMessageId,
1499
+ conversationId: run.conversationId,
1500
+ runId: run.id,
1501
+ role: "assistant",
1502
+ parts: [],
1503
+ createdAt: run.createdAt
1504
+ },
1505
+ status: "failed",
1506
+ updatedAt: new Date().toISOString()
1507
+ });
1508
+ return applied(current, {
1509
+ runs: replaceRun(current.runs, next),
1510
+ messages: replaceMessage(current.messages, assistant)
1511
+ }, {
1512
+ runRecords: [
1513
+ AgentStoredRunSchema2.parse({
1514
+ schemaVersion: 1,
1515
+ run: next,
1516
+ terminalAssistant: assistant
1517
+ })
1518
+ ],
1519
+ historyMutations: [{ type: "upsert-assistant", message: assistant }]
1520
+ });
1521
+ }
1522
+ return applied(current, { runs: replaceRun(current.runs, next) }, {
1523
+ runRecords: [AgentStoredRunSchema2.parse({ schemaVersion: 1, run: next })]
1524
+ });
1525
+ }
1526
+
1527
+ // src/agent-runtime/stores/store-reduce-terminal.ts
1528
+ function reduceTerminal(current, run, input) {
1529
+ if (input.reason === "absorbed") {
1530
+ throw new TypeError("A run is absorbed by another run, never terminalized as absorbed");
1531
+ }
1532
+ if (run.revision !== input.expectedRevision || run.state !== "running" && run.state !== "interrupt_requested" || run.ownerId !== input.ownerId || input.fencingToken !== undefined && run.fencingToken !== input.fencingToken || input.assistant.runId !== run.id || input.assistant.id !== run.assistantMessageId || input.assistant.conversationId !== run.conversationId || input.assistant.role !== "assistant" || input.assistant.status !== assistantStatus(input.reason)) {
1533
+ return conflict(run.revision);
1534
+ }
1535
+ if (input.absorb && runStateForTerminalReason2(input.reason) !== "completed") {
1536
+ throw new TypeError("Only a completing run may absorb a queued successor");
1537
+ }
1538
+ const named = new Set((input.absorb ?? []).map((entry) => entry.runId));
1539
+ if (named.size !== (input.absorb ?? []).length || named.has(run.id)) {
1540
+ throw new TypeError("An absorption names each successor once, and never the absorbing run");
1541
+ }
1542
+ const absorbable = (input.absorb ?? []).filter((entry) => {
1543
+ const candidate = current.runs.find((item) => item.id === entry.runId);
1544
+ return candidate !== undefined && candidate.id !== run.id && candidate.state === "queued" && candidate.conversationId === run.conversationId && candidate.inputMessageIds.length === entry.inputMessageIds.length && candidate.inputMessageIds.every((id, index) => id === entry.inputMessageIds[index]);
1545
+ });
1546
+ const absorbedIds = new Set(absorbable.flatMap((entry) => entry.inputMessageIds));
1547
+ const next = AgentRunSchema2.parse({
1548
+ ...run,
1549
+ state: runStateForTerminalReason2(input.reason),
1550
+ terminalReason: input.reason,
1551
+ ...input.policyName && { terminalPolicyName: input.policyName },
1552
+ ...input.usage && { usage: input.usage },
1553
+ ...absorbedIds.size > 0 && {
1554
+ inputMessageIds: [
1555
+ ...run.inputMessageIds,
1556
+ ...[...absorbedIds].filter((id) => !run.inputMessageIds.includes(id))
1557
+ ]
1558
+ },
1559
+ revision: run.revision + 1,
1560
+ updatedAt: new Date().toISOString()
1561
+ });
1562
+ const absorbedRuns = absorbable.map((entry) => {
1563
+ const candidate = current.runs.find((item) => item.id === entry.runId);
1564
+ if (!candidate)
1565
+ throw new TypeError("Absorbed run disappeared inside the reducer");
1566
+ return AgentRunSchema2.parse({
1567
+ ...candidate,
1568
+ state: runStateForTerminalReason2("absorbed"),
1569
+ terminalReason: "absorbed",
1570
+ absorbedIntoRunId: next.id,
1571
+ revision: candidate.revision + 1,
1572
+ updatedAt: new Date().toISOString()
1573
+ });
1574
+ });
1575
+ const runs = absorbedRuns.reduce((accumulated, absorbed) => replaceRun(accumulated, absorbed), replaceRun(current.runs, next));
1576
+ return applied(current, {
1577
+ runs,
1578
+ messages: replaceMessage(current.messages, input.assistant)
1579
+ }, {
1580
+ runRecords: [
1581
+ AgentStoredRunSchema2.parse({
1582
+ schemaVersion: 1,
1583
+ run: next,
1584
+ terminalAssistant: input.assistant
1585
+ }),
1586
+ ...absorbedRuns.map((absorbed) => AgentStoredRunSchema2.parse({ schemaVersion: 1, run: absorbed }))
1587
+ ],
1588
+ historyMutations: [{ type: "upsert-assistant", message: input.assistant }]
1589
+ });
1590
+ }
1591
+
1592
+ // src/agent-runtime/stores/store-reducer.ts
1593
+ function transitionRecord(operation, reduced) {
1594
+ if (operation.type === "recover" && operation.input.action === "abandon") {
1595
+ const record = reduced?.runRecords?.find((candidate) => candidate.run.id === operation.input.runId);
1596
+ const assistant = record?.terminalAssistant;
1597
+ const usage = record?.run.usage;
1598
+ if (assistant || usage) {
1599
+ return {
1600
+ ...operation,
1601
+ ...assistant && { assistant },
1602
+ ...usage && { usage }
1603
+ };
1604
+ }
1605
+ }
1606
+ if (operation.type !== "checkpoint")
1607
+ return operation;
1608
+ const { assistant, ...rest } = operation.input;
1609
+ const body = canonicalAgentJson2(assistant);
1610
+ return AgentStoreCheckpointRecordSchema.parse({
1611
+ type: operation.type,
1612
+ input: {
1613
+ ...rest,
1614
+ assistant: {
1615
+ id: assistant.id,
1616
+ status: assistant.status,
1617
+ sha256: createHash("sha256").update(body).digest("hex"),
1618
+ parts: assistant.parts.length,
1619
+ bytes: Buffer.byteLength(body)
1620
+ }
1621
+ }
1622
+ });
1623
+ }
1624
+ function reduceStore(current, operation) {
1625
+ if (operation.type === "accept")
1626
+ return reduceAccept(current, operation.input);
1627
+ if (operation.type === "seed")
1628
+ return reduceSeed(current, operation.input);
1629
+ if (operation.type === "compact")
1630
+ return reduceCompact(current, operation.input);
1631
+ const run = current.runs.find((candidate) => candidate.id === operation.input.runId);
1632
+ if (!run)
1633
+ return { outcome: "not_found" };
1634
+ switch (operation.type) {
1635
+ case "acquire":
1636
+ return reduceAcquire(current, run, operation.input);
1637
+ case "checkpoint":
1638
+ return reduceCheckpoint(current, run, operation.input);
1639
+ case "operation":
1640
+ return reduceOperation(current, run, operation.input);
1641
+ case "interrupt":
1642
+ return reduceInterrupt(current, run, operation.input);
1643
+ case "recover":
1644
+ return reduceRecover(current, run, operation.input, operation.assistant);
1645
+ case "terminal":
1646
+ return reduceTerminal(current, run, operation.input);
1647
+ }
1648
+ }
1649
+ function operationConversationId(operation) {
1650
+ return operation.type === "accept" ? operation.input.input.conversationId : operation.input.conversationId;
1651
+ }
1652
+
1653
+ // src/agent-runtime/stores/branch-replay.ts
1654
+ var BranchBaselineSchema = z13.object({
1655
+ migratedAt: z13.iso.datetime({ offset: true }),
1656
+ asOf: z13.iso.datetime({ offset: true }).optional(),
1657
+ head: AgentRuntimeHeadSchema2,
1658
+ messages: z13.array(AgentMessageSchema2),
1659
+ compacted: z13.array(z13.string().min(1)).optional(),
1660
+ runs: z13.array(AgentStoredRunSchema2),
1661
+ admissions: z13.array(AgentAdmissionReceiptSchema2)
1662
+ }).strict();
1663
+ function branchTransition(event) {
1664
+ const checkpoint = AgentStoreCheckpointRecordSchema.safeParse(event.payload);
1665
+ if (!checkpoint.success)
1666
+ return AgentStoreTransitionSchema2.parse(event.payload);
1667
+ const input = checkpoint.data.input;
1668
+ if (canonicalAgentJson2(checkpoint.data) !== canonicalAgentJson2(event.payload))
1669
+ throw new TypeError("Branch checkpoint contains an unknown opaque field");
1670
+ return AgentStoreTransitionSchema2.parse({
1671
+ type: "checkpoint",
1672
+ input: {
1673
+ ...input,
1674
+ assistant: {
1675
+ schemaVersion: 1,
1676
+ id: input.assistant.id,
1677
+ conversationId: input.conversationId,
1678
+ runId: input.runId,
1679
+ role: "assistant",
1680
+ status: "streaming",
1681
+ parts: [],
1682
+ createdAt: event.occurredAt,
1683
+ updatedAt: event.occurredAt
1684
+ }
1685
+ }
1686
+ });
1687
+ }
1688
+ function replayBranchEvents(conversationId, events, retainedSnapshot) {
1689
+ const result = {
1690
+ snapshot: AgentSnapshotSchema2.parse({
1691
+ schemaVersion: 1,
1692
+ conversationId,
1693
+ version: 0,
1694
+ messages: [],
1695
+ runs: []
1696
+ }),
1697
+ effects: [],
1698
+ unresolvedDrafts: new Set,
1699
+ retainedMessages: new Map
1700
+ };
1701
+ for (const event of events) {
1702
+ if (event.kind === "runtime/baseline") {
1703
+ if (event.seq !== 1 || result.snapshot.version !== 0)
1704
+ throw new TypeError("Branch baseline must be the first event");
1705
+ const baseline = BranchBaselineSchema.parse(event.payload);
1706
+ if (baseline.head.conversationId !== conversationId)
1707
+ throw new TypeError("Branch baseline has a foreign conversation");
1708
+ const compacted = new Set(baseline.compacted);
1709
+ snapshotOf(baseline.head, baseline.messages, baseline.runs);
1710
+ const keys = new Set;
1711
+ for (const record of baseline.runs) {
1712
+ if (record.run.inputMessageIds.some((id) => !baseline.messages.some((message) => message.id === id)))
1713
+ throw new TypeError("Branch baseline run references missing input");
1714
+ }
1715
+ for (const admission of baseline.admissions) {
1716
+ const run = baseline.runs.find((record) => record.run.id === admission.runId)?.run;
1717
+ if (keys.has(admission.idempotencyKey) || admission.conversationId !== conversationId || admission.input.conversationId !== conversationId || !run || !run.inputMessageIds.includes(admission.input.id) || run.assistantMessageId !== admission.assistantMessageId || !baseline.messages.some((message) => message.id === admission.input.id && canonicalAgentJson2(message) === canonicalAgentJson2(admission.input)))
1718
+ throw new TypeError("Branch baseline admission is inconsistent");
1719
+ keys.add(admission.idempotencyKey);
1720
+ }
1721
+ if (compacted.size !== (baseline.compacted?.length ?? 0) || [...compacted].some((id) => !baseline.messages.some((m) => m.id === id)))
1722
+ throw new TypeError("Branch baseline compacted identities are inconsistent");
1723
+ result.snapshot = snapshotOf(baseline.head, baseline.messages.filter((m) => !compacted.has(m.id)), baseline.runs);
1724
+ result.baseline = baseline;
1725
+ continue;
1726
+ }
1727
+ if (event.kind === "runtime/branched") {
1728
+ const receipt = AgentConversationBranchReceiptSchema2.parse(event.payload);
1729
+ if (receipt.conversationId !== conversationId)
1730
+ throw new TypeError("Branch receipt has a foreign conversation");
1731
+ result.snapshot = {
1732
+ ...result.snapshot,
1733
+ runs: result.snapshot.runs.map(({ ownerId: _owner, fencingToken: _fence, ...run }) => run)
1734
+ };
1735
+ continue;
1736
+ }
1737
+ if (event.kind !== "runtime/transition")
1738
+ continue;
1739
+ let operation = branchTransition(event);
1740
+ if (operation.type === "checkpoint" && retainedSnapshot) {
1741
+ const record = AgentStoreCheckpointRecordSchema.safeParse(event.payload);
1742
+ const assistantId = operation.input.assistant.id;
1743
+ const retained = retainedSnapshot.messages.find((message) => message.id === assistantId);
1744
+ if (record.success && retained && record.data.input.assistant.sha256 === createHash2("sha256").update(canonicalAgentJson2(retained)).digest("hex")) {
1745
+ operation = { ...operation, input: { ...operation.input, assistant: retained } };
1746
+ result.retainedMessages.set(event.eventId, retained);
1747
+ }
1748
+ }
1749
+ if (operation.type === "recover" && operation.input.action === "abandon" && !operation.assistant && retainedSnapshot) {
1750
+ const runId = operation.input.runId;
1751
+ const run = result.snapshot.runs.find((run) => run.id === runId);
1752
+ const retained = retainedSnapshot.messages.find((message) => message.id === run?.assistantMessageId && message.runId === runId && message.role === "assistant" && message.status === "failed");
1753
+ if (retained)
1754
+ operation = { ...operation, assistant: retained };
1755
+ }
1756
+ if (operation.type === "recover" && operation.input.action === "abandon" && !operation.assistant)
1757
+ throw new TypeError("Branch archive has no exact retained abandoned assistant");
1758
+ const inputConversation = operation.type === "accept" ? operation.input.input.conversationId : operation.input.conversationId;
1759
+ if (inputConversation !== conversationId)
1760
+ throw new TypeError("Branch transition has a foreign conversation");
1761
+ const reduced = reduceStore(result.snapshot, operation);
1762
+ if (reduced.outcome !== "applied")
1763
+ throw new TypeError(`Branch transition at sequence ${event.seq} is inconsistent: ${reduced.outcome}`);
1764
+ const runRecords = reduced.runRecords?.map((record) => ({
1765
+ ...record,
1766
+ run: { ...record.run, updatedAt: event.occurredAt }
1767
+ }));
1768
+ result.snapshot = {
1769
+ ...reduced.snapshot,
1770
+ runs: reduced.snapshot.runs.map((run) => runRecords?.find((record) => record.run.id === run.id)?.run ?? run)
1771
+ };
1772
+ const { snapshot: _snapshot, outcome: _outcome, ...effects } = reduced;
1773
+ result.effects.push({ ...effects, ...runRecords && { runRecords } });
1774
+ if (operation.type === "recover" && operation.input.action === "abandon") {
1775
+ const runId = operation.input.runId;
1776
+ const assistant = reduced.runRecords?.find((record) => record.run.id === runId)?.terminalAssistant;
1777
+ if (assistant)
1778
+ result.retainedMessages.set(event.eventId, assistant);
1779
+ if (operation.assistant)
1780
+ result.unresolvedDrafts.delete(runId);
1781
+ }
1782
+ if (operation.type === "checkpoint" && AgentStoreCheckpointRecordSchema.safeParse(event.payload).success)
1783
+ result.unresolvedDrafts.add(operation.input.runId);
1784
+ if (operation.type === "terminal")
1785
+ result.unresolvedDrafts.delete(operation.input.runId);
1786
+ }
1787
+ return result;
1788
+ }
1789
+
1790
+ // src/agent-runtime/stores/store-reads.ts
1791
+ async function snapshotIn(driver, transaction, conversationId) {
1792
+ const [stored, messages, activeRecords] = await Promise.all([
1793
+ driver.head.load(transaction, conversationId),
1794
+ driver.history.load(transaction, conversationId),
1795
+ driver.runs.listActive(transaction, conversationId)
1796
+ ]);
1797
+ const head = AgentRuntimeHeadSchema2.parse(stored ?? emptyHead(conversationId));
1798
+ const referencedRecords = await driver.runs.loadMany(transaction, {
1799
+ conversationId,
1800
+ runIds: referencedRunIds(messages)
1801
+ });
1802
+ return snapshotOf(head, messages, mergeRunRecords(activeRecords, referencedRecords));
1803
+ }
1804
+ function loadSnapshot(driver, conversationId) {
1805
+ return driver.transaction((transaction) => snapshotIn(driver, transaction, conversationId), {
1806
+ access: "read"
1807
+ });
1808
+ }
1809
+ function loadRun(driver, input) {
1810
+ return driver.transaction(async (transaction) => {
1811
+ const [stored, record] = await Promise.all([
1812
+ driver.head.load(transaction, input.conversationId),
1813
+ driver.runs.load(transaction, input)
1814
+ ]);
1815
+ if (!record)
1816
+ return;
1817
+ const parsed = AgentStoredRunSchema2.parse(record);
1818
+ if (parsed.run.conversationId !== input.conversationId || parsed.run.id !== input.runId) {
1819
+ throw new TypeError("Stored run does not match the identity it was loaded by");
1820
+ }
1821
+ const head = AgentRuntimeHeadSchema2.parse(stored ?? emptyHead(input.conversationId));
1822
+ return AgentRunViewSchema2.parse({
1823
+ snapshotVersion: head.version,
1824
+ run: parsed.run,
1825
+ ...parsed.terminalAssistant && { assistant: parsed.terminalAssistant }
1826
+ });
1827
+ }, { access: "read" });
1828
+ }
1829
+ function listActiveRuns(driver, conversationId) {
1830
+ return driver.transaction(async (transaction) => {
1831
+ const [records, messages] = await Promise.all([
1832
+ driver.runs.listActive(transaction, conversationId),
1833
+ driver.history.load(transaction, conversationId)
1834
+ ]);
1835
+ const runs = records.map((record) => AgentStoredRunSchema2.parse(record).run);
1836
+ for (const run of runs) {
1837
+ if (run.conversationId !== conversationId) {
1838
+ throw new TypeError("Active run belongs to another conversation");
1839
+ }
1840
+ if (!isActiveRunState(run.state)) {
1841
+ throw new TypeError("Active run listing returned a terminal run");
1842
+ }
1843
+ }
1844
+ return orderRuns(messages, runs);
1845
+ }, { access: "read" });
1846
+ }
1847
+ function appendEvent(driver, input) {
1848
+ const parsed = AppendAgentStoreEventSchema2.parse(input);
1849
+ return driver.transaction((transaction) => appendEventIn(driver, transaction, parsed));
1850
+ }
1851
+ async function appendEventIn(driver, transaction, parsed) {
1852
+ if (await driver.conversations?.isPurged(transaction, parsed.conversationId)) {
1853
+ throw new AgentConversationPurgedError2;
1854
+ }
1855
+ return driver.events.append(transaction, agentStoreEventDraft(parsed));
1856
+ }
1857
+ function readEvents(driver, input) {
1858
+ const parsed = ReadAgentStoreEventsSchema2.parse(input);
1859
+ return driver.transaction(async (transaction) => AgentStoreEventPageSchema2.parse(await driver.events.list(transaction, parsed)), { access: "read" });
1860
+ }
1861
+
1862
+ // src/agent-runtime/stores/store-replay.ts
1863
+ async function persistRuntimeReplay(driver, tx, replay) {
1864
+ if (replay.baseline) {
1865
+ const baseline = replay.baseline;
1866
+ for (const record of baseline.runs)
1867
+ await driver.runs.save(tx, record);
1868
+ if (driver.history.restore)
1869
+ await driver.history.restore(tx, {
1870
+ conversationId: baseline.head.conversationId,
1871
+ messages: baseline.messages,
1872
+ compactedMessageIds: baseline.compacted ?? []
1873
+ });
1874
+ else if (baseline.compacted?.length)
1875
+ throw new AgentStoreUnsupportedCapabilityError2("historyRestore", "the baseline carries compacted history");
1876
+ else
1877
+ for (const message of baseline.messages)
1878
+ await driver.history.apply(tx, { type: "admit", input: message });
1879
+ for (const receipt of baseline.admissions)
1880
+ await driver.admissions.create(tx, receipt);
1881
+ }
1882
+ for (const effect of replay.effects) {
1883
+ for (const record of effect.runRecords ?? [])
1884
+ await driver.runs.save(tx, record);
1885
+ if (effect.admissionReceipt)
1886
+ await driver.admissions.create(tx, effect.admissionReceipt);
1887
+ if (effect.seedReceipt)
1888
+ await driver.seeds.create(tx, effect.seedReceipt);
1889
+ for (const mutation of effect.historyMutations ?? [])
1890
+ await driver.history.apply(tx, mutation);
1891
+ }
1892
+ }
1893
+
1894
+ // src/agent-runtime/stores/store-archive.ts
1895
+ function exportConversation(driver, conversationId) {
1896
+ return driver.transaction(async (transaction) => {
1897
+ return exportConversationIn(driver, transaction, conversationId);
1898
+ }, { access: "read" });
1899
+ }
1900
+ async function importConversation(driver, bytes) {
1901
+ const archive = decodeAgentConversationArchive2(bytes);
1902
+ const snapshotEntry = archive.projections.find(isRuntimeSnapshotEntry);
1903
+ const snapshot = snapshotEntry === undefined ? undefined : AgentSnapshotSchema2.parse(snapshotEntry.snapshot);
1904
+ if (snapshot && snapshot.conversationId !== archive.conversationId) {
1905
+ throw new TypeError("Conversation archive snapshot belongs to another conversation");
1906
+ }
1907
+ const replay = snapshot && replayBranchEvents(archive.conversationId, archive.events, snapshot);
1908
+ assertSourceCapabilities(driver, {
1909
+ spills: archive.spills.length,
1910
+ projections: archive.projections.filter((entry) => !isRuntimeSnapshotEntry(entry)).length,
1911
+ compacted: replay?.baseline?.compacted?.length ?? 0
1912
+ });
1913
+ return driver.transaction(async (transaction) => {
1914
+ const existing = await driver.events.list(transaction, {
1915
+ conversationId: archive.conversationId,
1916
+ limit: 1
1917
+ });
1918
+ if (existing.items.length > 0) {
1919
+ throw new TypeError("Conversation event log must be empty before import");
1920
+ }
1921
+ for (const event of archive.events) {
1922
+ const appended = await driver.events.append(transaction, {
1923
+ schemaVersion: event.schemaVersion,
1924
+ eventId: event.eventId,
1925
+ conversationId: event.conversationId,
1926
+ kind: event.kind,
1927
+ occurredAt: event.occurredAt,
1928
+ payload: event.payload,
1929
+ ...event.ignorable && { ignorable: true }
1930
+ });
1931
+ if (appended.seq !== event.seq) {
1932
+ throw new TypeError("Conversation archive event sequence is not contiguous");
1933
+ }
1934
+ }
1935
+ if (snapshot && replay) {
1936
+ if (snapshot.version > 0 || snapshot.messages.length > 0 || snapshot.runs.length > 0) {
1937
+ const outcome = await driver.head.compareAndSwap(transaction, {
1938
+ conversationId: snapshot.conversationId,
1939
+ expectedVersion: 0,
1940
+ next: AgentRuntimeHeadSchema2.parse({
1941
+ schemaVersion: 1,
1942
+ conversationId: snapshot.conversationId,
1943
+ version: snapshot.version
1944
+ })
1945
+ });
1946
+ if (outcome.outcome !== "applied") {
1947
+ throw new TypeError("Conversation archive snapshot target is not empty");
1948
+ }
1949
+ }
1950
+ await persistRuntimeReplay(driver, transaction, replay);
1951
+ for (const run of snapshot.runs) {
1952
+ const terminalAssistant = snapshot.messages.find((message) => message.id === run.assistantMessageId);
1953
+ await driver.runs.save(transaction, AgentStoredRunSchema2.parse({
1954
+ schemaVersion: 1,
1955
+ run,
1956
+ ...terminalAssistant && { terminalAssistant }
1957
+ }));
1958
+ }
1959
+ const restoredIds = new Set((await driver.history.load(transaction, archive.conversationId)).map((message) => message.id));
1960
+ for (const message of snapshot.messages) {
1961
+ if (message.role === "assistant")
1962
+ await driver.history.apply(transaction, { type: "upsert-assistant", message });
1963
+ else if (!restoredIds.has(message.id))
1964
+ await driver.history.apply(transaction, { type: "admit", input: message });
1965
+ }
1966
+ }
1967
+ await driver.archive?.import(transaction, archive);
1968
+ return { conversationId: archive.conversationId, events: archive.events.length };
1969
+ });
1970
+ }
1971
+ async function exportConversationIn(driver, transaction, conversationId) {
1972
+ const events = [];
1973
+ let fromSeq;
1974
+ do {
1975
+ const page = AgentStoreEventPageSchema2.parse(await driver.events.list(transaction, ReadAgentStoreEventsSchema2.parse({
1976
+ conversationId,
1977
+ ...fromSeq && { fromSeq },
1978
+ limit: 1e4
1979
+ })));
1980
+ events.push(...page.items);
1981
+ fromSeq = page.nextSeq;
1982
+ } while (fromSeq !== undefined);
1983
+ const durable = await driver.archive?.export(transaction, conversationId) ?? {
1984
+ projections: [],
1985
+ spills: []
1986
+ };
1987
+ const snapshot = await snapshotIn(driver, transaction, conversationId);
1988
+ return encodeAgentConversationArchive2({
1989
+ format: "stitchkit.agent-conversation",
1990
+ formatVersion: 1,
1991
+ conversationId,
1992
+ events,
1993
+ projections: [
1994
+ { archiveType: "runtime-snapshot", snapshot: z14.json().parse(snapshot) },
1995
+ ...durable.projections
1996
+ ],
1997
+ spills: durable.spills
1998
+ });
1999
+ }
2000
+
2001
+ // src/agent-runtime/stores/store-branch.ts
2002
+ import { createHash as createHash7 } from "node:crypto";
2003
+ import { z as z23 } from "zod";
2004
+
2005
+ // src/agent-runtime/stores/branch-events.ts
2006
+ import { z as z20 } from "zod";
2007
+
2008
+ // src/agent-runtime/stores/branch-messages.ts
2009
+ import { z as z16 } from "zod";
2010
+
2011
+ // src/agent-runtime/stores/branch-runtime-tools.ts
2012
+ import { z as z15 } from "zod";
2013
+ function codingToolRecord(ids, name, value, output) {
2014
+ if (name === AGENT_CODING_TOOL_NAMES.readOutput || name === AGENT_CODING_TOOL_NAMES.searchOutput) {
2015
+ const schema = output ? name === AGENT_CODING_TOOL_NAMES.readOutput ? ArtifactReadOutputSchema : ArtifactSearchOutputSchema : name === AGENT_CODING_TOOL_NAMES.readOutput ? ArtifactReadInputSchema : ArtifactSearchInputSchema;
2016
+ const parsed = schema.safeParse(value);
2017
+ if (!parsed.success)
2018
+ return;
2019
+ return { ...parsed.data, reference: ids.reference("spill", parsed.data.reference) };
2020
+ }
2021
+ if (output && name === AGENT_CODING_TOOL_NAMES.runCommand) {
2022
+ const parsed = ShellOutputSchema.safeParse(value);
2023
+ if (!parsed.success)
2024
+ return;
2025
+ return {
2026
+ ...parsed.data,
2027
+ ...parsed.data.artifact && {
2028
+ artifact: {
2029
+ ...parsed.data.artifact,
2030
+ reference: ids.reference("spill", parsed.data.artifact.reference)
2031
+ }
2032
+ }
2033
+ };
2034
+ }
2035
+ return;
2036
+ }
2037
+ function selectionReceipt(ids, value) {
2038
+ const receipt = DeferredAgentToolReceiptSchema2.safeParse(value);
2039
+ if (!receipt.success || canonicalAgentJson2(receipt.data) !== canonicalAgentJson2(value))
2040
+ return;
2041
+ if (!ids.sourceIdentitiesOf(receipt.data.runId).has("run"))
2042
+ return;
2043
+ return { ...receipt.data, runId: ids.reference("run", receipt.data.runId) };
2044
+ }
2045
+ var PayloadEventSchema = z15.object({ kind: z15.literal("provider/payload"), payload: z15.json() }).passthrough();
2046
+ var PayloadObservationSchema = z15.object({
2047
+ kind: z15.literal("runtime/branch-observation"),
2048
+ payload: z15.object({ sourceKind: z15.literal("provider/payload"), payload: z15.json() })
2049
+ }).passthrough();
2050
+ function withoutPayloadBody(event) {
2051
+ const stripped = (payload) => {
2052
+ const receipt = InvocationPayloadReceiptSchema.safeParse(payload);
2053
+ if (!receipt.success)
2054
+ return payload;
2055
+ const { iv: _iv, tag: _tag, ciphertext: _body, ...rest } = receipt.data;
2056
+ return rest;
2057
+ };
2058
+ const raw = PayloadEventSchema.safeParse(event);
2059
+ if (raw.success)
2060
+ return { ...raw.data, payload: stripped(raw.data.payload) };
2061
+ const observed = PayloadObservationSchema.safeParse(event);
2062
+ if (observed.success)
2063
+ return {
2064
+ ...observed.data,
2065
+ payload: { ...observed.data.payload, payload: stripped(observed.data.payload.payload) }
2066
+ };
2067
+ return event;
2068
+ }
2069
+ function eventSearchSchemas(name) {
2070
+ return Object.entries(AGENT_EVENT_SEARCH_TOOL_SCHEMAS).find(([tool]) => tool === name)?.[1];
2071
+ }
2072
+ function eventSearchRecord(name, value, output) {
2073
+ const schemas = eventSearchSchemas(name);
2074
+ if (!schemas)
2075
+ return;
2076
+ if (!output) {
2077
+ const keys = Object.keys(schemas.input.shape);
2078
+ const isInput = value !== null && typeof value === "object" && !Array.isArray(value) && Object.keys(value).every((key) => keys.includes(key));
2079
+ return isInput ? value : undefined;
2080
+ }
2081
+ if (!schemas.output.safeParse(value).success)
2082
+ return;
2083
+ if (value === null || typeof value !== "object" || Array.isArray(value))
2084
+ return value;
2085
+ const events = value.events;
2086
+ if (Array.isArray(events))
2087
+ return { ...value, events: events.map(withoutPayloadBody) };
2088
+ return withoutPayloadBody(value);
2089
+ }
2090
+ function branchRuntimeToolRecord(ids, name, value, output) {
2091
+ return codingToolRecord(ids, name, value, output) ?? (output ? selectionReceipt(ids, value) : undefined) ?? eventSearchRecord(name, value, output);
2092
+ }
2093
+
2094
+ // src/agent-runtime/stores/branch-messages.ts
2095
+ var RETAINABLE = new Set(["conversation", "run", "message"]);
2096
+ var RUNTIME_REFERENCE_KEYS = new Set(BRANCH_RUNTIME_REFERENCE_KEYS);
2097
+ function branchOpaqueJson(ids, value, path = "") {
2098
+ if (Array.isArray(value)) {
2099
+ return value.map((entry, index) => branchOpaqueJson(ids, entry, `${path}[${index}]`));
2100
+ }
2101
+ if (value !== null && typeof value === "object") {
2102
+ return branchOpaqueRecord(ids, value, path);
2103
+ }
2104
+ return value;
2105
+ }
2106
+ function branchOpaqueRecord(ids, value, path = "") {
2107
+ const out = {};
2108
+ for (const [key, entry] of Object.entries(value)) {
2109
+ const at = path ? `${path}.${key}` : key;
2110
+ if (!RUNTIME_REFERENCE_KEYS.has(key)) {
2111
+ out[key] = branchOpaqueJson(ids, entry, at);
2112
+ continue;
2113
+ }
2114
+ const mode = ids.applicationKey(key);
2115
+ if (mode === undefined) {
2116
+ ids.refuse({
2117
+ code: "application-key-undeclared",
2118
+ message: `Branch cannot rekey an opaque payload containing ${key} at ${at}; declare it in applicationKeys if it is application data`,
2119
+ key,
2120
+ path: at
2121
+ });
2122
+ out[key] = branchOpaqueJson(ids, entry, at);
2123
+ continue;
2124
+ }
2125
+ if (mode === "rekey-spill") {
2126
+ if (typeof entry === "string") {
2127
+ const kinds = ids.sourceIdentitiesOf(entry);
2128
+ if (kinds.size === 1 && kinds.has("spill")) {
2129
+ out[key] = ids.reference("spill", entry);
2130
+ } else {
2131
+ ids.refuse({
2132
+ code: "application-key-source-identity",
2133
+ message: `Branch cannot rekey non-spill or foreign value under the application key ${key} at ${at}`,
2134
+ key,
2135
+ path: at
2136
+ });
2137
+ out[key] = entry;
2138
+ }
2139
+ } else {
2140
+ out[key] = branchOpaqueJson(ids, entry, at);
2141
+ }
2142
+ continue;
2143
+ }
2144
+ if (typeof entry === "string") {
2145
+ for (const kind of ids.sourceIdentitiesOf(entry)) {
2146
+ if (mode === "retain" && RETAINABLE.has(kind))
2147
+ continue;
2148
+ ids.refuse({
2149
+ code: "application-key-source-identity",
2150
+ message: mode === "retain" ? `Branch cannot carry a source ${kind} under the application key ${key} at ${at}` : `Branch cannot carry a source identity under the application key ${key} at ${at}`,
2151
+ key,
2152
+ path: at
2153
+ });
2154
+ break;
2155
+ }
2156
+ }
2157
+ out[key] = branchOpaqueJson(ids, entry, at);
2158
+ }
2159
+ return out;
2160
+ }
2161
+ function branchToolJson(ids, name, value, output) {
2162
+ return branchRuntimeToolRecord(ids, name, value, output) ?? branchOpaqueJson(ids, value);
2163
+ }
2164
+ function branchPart(ids, part) {
2165
+ return "toolName" in part && typeof part.toolName === "string" ? ids.within({ toolName: part.toolName }, () => branchPartAt(ids, part)) : branchPartAt(ids, part);
2166
+ }
2167
+ function branchPartAt(ids, part) {
2168
+ switch (part.type) {
2169
+ case "file":
2170
+ return { ...part, reference: ids.fileReference(part.reference) };
2171
+ case "tool-call":
2172
+ return {
2173
+ ...part,
2174
+ ...part.provider && {
2175
+ provider: { ...part.provider, data: branchOpaqueRecord(ids, part.provider.data) }
2176
+ },
2177
+ callId: ids.reference("call", part.callId),
2178
+ input: branchToolJson(ids, part.toolName, part.input, false)
2179
+ };
2180
+ case "tool-result":
2181
+ return {
2182
+ ...part,
2183
+ callId: ids.reference("call", part.callId),
2184
+ ...part.output !== undefined && {
2185
+ output: part.outcome === "success" ? branchToolJson(ids, part.toolName, part.output, true) : branchOpaqueJson(ids, part.output)
2186
+ }
2187
+ };
2188
+ case "tool-approval-request":
2189
+ return {
2190
+ type: part.type,
2191
+ approvalId: ids.reference("approval", part.approvalId),
2192
+ callId: ids.reference("call", part.callId)
2193
+ };
2194
+ case "tool-approval-response":
2195
+ return { ...part, approvalId: ids.reference("approval", part.approvalId) };
2196
+ case "provider":
2197
+ throw new TypeError("Branch cannot rekey an opaque provider part");
2198
+ case "reasoning":
2199
+ return part.provider ? {
2200
+ ...part,
2201
+ provider: { ...part.provider, data: branchOpaqueRecord(ids, part.provider.data) }
2202
+ } : part;
2203
+ default:
2204
+ return part;
2205
+ }
2206
+ }
2207
+ function branchMessage(ids, sourceConversationId, message) {
2208
+ if (message.conversationId !== sourceConversationId)
2209
+ throw new TypeError("Branch message belongs to another conversation");
2210
+ return ids.within({ messageId: message.id }, () => ({
2211
+ ...message,
2212
+ id: ids.reference("message", message.id),
2213
+ conversationId: ids.conversationId,
2214
+ ...message.runId && { runId: ids.reference("run", message.runId) },
2215
+ parts: message.parts.map((part) => branchPart(ids, part)),
2216
+ ...message.metadata && {
2217
+ metadata: z16.record(z16.string(), z16.json()).parse(branchOpaqueJson(ids, message.metadata))
2218
+ }
2219
+ }));
2220
+ }
2221
+ function branchRun(ids, sourceConversationId, run, settled) {
2222
+ if (run.conversationId !== sourceConversationId)
2223
+ throw new TypeError("Branch run belongs to another conversation");
2224
+ const { ownerId, fencingToken, ...record } = run;
2225
+ return {
2226
+ ...record,
2227
+ id: ids.reference("run", run.id),
2228
+ conversationId: ids.conversationId,
2229
+ inputMessageIds: run.inputMessageIds.map((id) => ids.reference("message", id)),
2230
+ assistantMessageId: ids.reference("message", run.assistantMessageId),
2231
+ ...run.absorbedIntoRunId && {
2232
+ absorbedIntoRunId: ids.reference("run", run.absorbedIntoRunId)
2233
+ },
2234
+ ...run.lastOperation && {
2235
+ lastOperation: {
2236
+ ...run.lastOperation,
2237
+ operationId: ids.reference("operation", run.lastOperation.operationId)
2238
+ }
2239
+ },
2240
+ ...!settled && ownerId && { ownerId: ids.define("owner", ownerId) },
2241
+ ...!settled && fencingToken !== undefined && { fencingToken }
2242
+ };
2243
+ }
2244
+
2245
+ // src/agent-runtime/stores/branch-observations.ts
2246
+ import { z as z17 } from "zod";
2247
+ var Id = z17.string().min(1);
2248
+ var Hash2 = z17.string().regex(/^[a-f0-9]{64}$/);
2249
+ var State = z17.object({
2250
+ name: Id,
2251
+ version: z17.int().positive(),
2252
+ value: z17.json(),
2253
+ actor: z17.enum(["agent", "human", "system"])
2254
+ }).strict();
2255
+ var Retry = z17.object({
2256
+ attempt: z17.int().positive(),
2257
+ delayMs: z17.number().nonnegative().optional(),
2258
+ reason: z17.string().optional()
2259
+ }).strict();
2260
+ var SpillEventPayloadSchema = z17.object({ reference: Id, bytes: z17.int().nonnegative(), sha256: Hash2.optional() }).strict();
2261
+ var Schedule = z17.object({
2262
+ id: Id,
2263
+ kind: z17.enum(["at", "after", "every"]).optional(),
2264
+ nextAt: z17.string().nullable().optional(),
2265
+ occurrence: z17.int().nonnegative().optional(),
2266
+ lateByMs: z17.number().nonnegative().optional(),
2267
+ state: z17.string().optional(),
2268
+ message: z17.string().optional(),
2269
+ attempts: z17.int().nonnegative().optional(),
2270
+ retryAt: z17.string().nullable().optional(),
2271
+ terminal: z17.boolean().optional(),
2272
+ skipped: z17.boolean().optional()
2273
+ }).strict();
2274
+ var Rejection = z17.object({ approvalId: Id, callId: Id, toolName: Id, reason: z17.string() }).strict();
2275
+ function durability(ids, raw, kind) {
2276
+ const value = kind === "durability/step" ? StepEventPayloadSchema.parse(raw) : kind === "durability/park" ? ParkEventPayloadSchema.parse(raw) : kind === "durability/event" ? DeliveredEventPayloadSchema.parse(raw) : EffectEventPayloadSchema.parse(raw);
2277
+ if (canonicalAgentJson2(value) !== canonicalAgentJson2(raw))
2278
+ throw new TypeError("Branch cannot rekey opaque durability payload");
2279
+ const encoded = "encoded" in value ? JSON.stringify(branchOpaqueJson(ids, z17.json().parse(JSON.parse(value.encoded)))) : undefined;
2280
+ return {
2281
+ ...value,
2282
+ ...encoded !== undefined && { encoded },
2283
+ runId: ids.reference("run", value.runId),
2284
+ ..."id" in value && { id: ids.define("key", value.id) }
2285
+ };
2286
+ }
2287
+ function spill(ids, raw) {
2288
+ const value = SpillEventPayloadSchema.parse(raw);
2289
+ return { ...value, reference: ids.reference("spill", value.reference) };
2290
+ }
2291
+ function schedule(ids, raw) {
2292
+ const value = Schedule.parse(raw);
2293
+ return { ...value, id: ids.define("schedule", value.id) };
2294
+ }
2295
+ function rekeyChildConversation(ids, conversationId) {
2296
+ return conversationId === ids.sourceConversationId ? ids.conversationId : ids.define("child", conversationId);
2297
+ }
2298
+ function childSpawned(ids, raw) {
2299
+ const value = ChildSpawnedEventPayloadSchema.parse(raw);
2300
+ return {
2301
+ ...value,
2302
+ childConversationId: rekeyChildConversation(ids, value.childConversationId)
2303
+ };
2304
+ }
2305
+ function childState(ids, raw) {
2306
+ const value = ChildStateEventPayloadSchema.parse(raw);
2307
+ if ("action" in value) {
2308
+ if (value.action === "blocking-presented") {
2309
+ return {
2310
+ ...value,
2311
+ input: branchOpaqueJson(ids, value.input),
2312
+ childConversationId: rekeyChildConversation(ids, value.childConversationId),
2313
+ approvalId: ids.define("approval", value.approvalId),
2314
+ childApprovalId: ids.define("approval", value.childApprovalId),
2315
+ callId: ids.define("call", value.callId),
2316
+ batchId: ids.define("key", value.batchId)
2317
+ };
2318
+ }
2319
+ if (value.action === "blocking-resolved") {
2320
+ return {
2321
+ ...value,
2322
+ childConversationId: rekeyChildConversation(ids, value.childConversationId),
2323
+ approvalId: ids.define("approval", value.approvalId),
2324
+ batchId: ids.define("key", value.batchId)
2325
+ };
2326
+ }
2327
+ return {
2328
+ ...value,
2329
+ childConversationId: rekeyChildConversation(ids, value.childConversationId)
2330
+ };
2331
+ }
2332
+ return {
2333
+ ...value,
2334
+ ...value.childConversationId && {
2335
+ childConversationId: rekeyChildConversation(ids, value.childConversationId)
2336
+ },
2337
+ ...value.parentConversationId && {
2338
+ parentConversationId: rekeyChildConversation(ids, value.parentConversationId)
2339
+ },
2340
+ ...value.resultReference && {
2341
+ resultReference: ids.reference("spill", value.resultReference)
2342
+ }
2343
+ };
2344
+ }
2345
+ function invocation(ids, value, inherited) {
2346
+ if (inherited)
2347
+ return value;
2348
+ if (value.conversationId !== ids.sourceConversationId)
2349
+ throw new TypeError("Branch invocation record belongs to another conversation");
2350
+ if (value.runId !== undefined)
2351
+ ids.reference("run", value.runId);
2352
+ return value;
2353
+ }
2354
+ function invocationPayload(ids, raw, inherited) {
2355
+ const {
2356
+ iv: _iv,
2357
+ tag: _tag,
2358
+ ciphertext: _body,
2359
+ ...receipt
2360
+ } = InvocationPayloadReceiptSchema.parse(raw);
2361
+ return invocation(ids, receipt, inherited);
2362
+ }
2363
+ var retry = (_ids, raw) => Retry.parse(raw);
2364
+ var OBSERVATION_RULES = {
2365
+ "durability/step": durability,
2366
+ "durability/park": durability,
2367
+ "durability/event": durability,
2368
+ "durability/effect": durability,
2369
+ "sandbox/probed": (_ids, raw) => z17.object({
2370
+ result: AgentSandboxGradeSchema2,
2371
+ required: z17.array(AgentSandboxRestrictionSchema2),
2372
+ missing: z17.array(AgentSandboxRestrictionSchema2)
2373
+ }).strict().parse(raw),
2374
+ "state/set": (ids, raw) => {
2375
+ const value = State.parse(raw);
2376
+ return { ...value, value: branchOpaqueJson(ids, value.value) };
2377
+ },
2378
+ "retry/scheduled": retry,
2379
+ "retry/started": retry,
2380
+ "spill/created": spill,
2381
+ "spill/deleted": spill,
2382
+ "schedule/set": schedule,
2383
+ "schedule/fired": schedule,
2384
+ "schedule/cancelled": schedule,
2385
+ "schedule/late": schedule,
2386
+ "schedule/failed": schedule,
2387
+ "child/spawned": childSpawned,
2388
+ "child/state": childState,
2389
+ "approval/response-rejected": (ids, raw) => {
2390
+ const value = Rejection.parse(raw);
2391
+ return {
2392
+ ...value,
2393
+ approvalId: ids.reference("approval", value.approvalId),
2394
+ callId: ids.reference("call", value.callId)
2395
+ };
2396
+ },
2397
+ "invocation/started": (ids, raw, _kind, inherited) => invocation(ids, InvocationStartedSchema.parse(raw), inherited),
2398
+ "invocation/finished": (ids, raw, _kind, inherited) => invocation(ids, InvocationFinishedSchema.parse(raw), inherited),
2399
+ "provider/request": (ids, raw, _kind, inherited) => invocation(ids, InvocationRequestSchema.parse(raw), inherited),
2400
+ "provider/response": (ids, raw, _kind, inherited) => invocation(ids, InvocationResponseSchema.parse(raw), inherited),
2401
+ "provider/payload": (ids, raw, _kind, inherited) => invocationPayload(ids, raw, inherited)
2402
+ };
2403
+ function isObservedKind(kind) {
2404
+ return Object.hasOwn(OBSERVATION_RULES, kind);
2405
+ }
2406
+ function branchObservation(ids, kind, raw, inherited = false) {
2407
+ if (!isObservedKind(kind)) {
2408
+ ids.refuse({
2409
+ code: "event-kind-unknown",
2410
+ message: `Branch cannot rekey opaque event kind ${kind}`
2411
+ });
2412
+ return raw;
2413
+ }
2414
+ return OBSERVATION_RULES[kind](ids, raw, kind, inherited);
2415
+ }
2416
+ var Defines = z17.object({
2417
+ id: Id.optional(),
2418
+ childConversationId: Id.optional(),
2419
+ parentConversationId: Id.optional(),
2420
+ approvalId: Id.optional(),
2421
+ childApprovalId: Id.optional(),
2422
+ callId: Id.optional(),
2423
+ batchId: Id.optional()
2424
+ }).passthrough();
2425
+ function collectObservationDefinitions(ids, kind, raw) {
2426
+ const value = Defines.safeParse(raw);
2427
+ if (!value.success)
2428
+ return;
2429
+ const {
2430
+ id,
2431
+ childConversationId,
2432
+ parentConversationId,
2433
+ approvalId,
2434
+ childApprovalId,
2435
+ callId,
2436
+ batchId
2437
+ } = value.data;
2438
+ if (kind.startsWith("durability/") && id)
2439
+ ids.define("key", id);
2440
+ if (kind.startsWith("schedule/") && id)
2441
+ ids.define("schedule", id);
2442
+ if (!kind.startsWith("child/"))
2443
+ return;
2444
+ for (const child of [childConversationId, parentConversationId])
2445
+ if (child && child !== ids.sourceConversationId)
2446
+ ids.define("child", child);
2447
+ if (approvalId)
2448
+ ids.define("approval", approvalId);
2449
+ if (childApprovalId)
2450
+ ids.define("approval", childApprovalId);
2451
+ if (callId)
2452
+ ids.define("call", callId);
2453
+ if (batchId)
2454
+ ids.define("key", batchId);
2455
+ }
2456
+ var BranchObservationSchema = z17.object({ sourceKind: Id, payload: z17.json() }).strict();
2457
+
2458
+ // src/agent-runtime/stores/branch-provider.ts
2459
+ import { createHash as createHash3 } from "node:crypto";
2460
+ import { z as z18 } from "zod";
2461
+ var ProviderOptionsRecordSchema = z18.record(z18.string(), z18.record(z18.string(), z18.json()));
2462
+ var ReferenceRecordSchema = z18.record(z18.string(), z18.string()).refine((value) => !("type" in value), "Provider reference cannot contain a file discriminator");
2463
+ function hash(value) {
2464
+ return createHash3("sha256").update(canonicalAgentJson2(value)).digest("hex");
2465
+ }
2466
+ function rekeyProviderOptions(ids, options) {
2467
+ return ProviderOptionsRecordSchema.parse(branchOpaqueJson(ids, options));
2468
+ }
2469
+ function rekeyReference(ids, value) {
2470
+ return ReferenceRecordSchema.parse(branchOpaqueJson(ids, value));
2471
+ }
2472
+ function rekeyContentFileData(ids, value) {
2473
+ if (value.type === "reference") {
2474
+ return { ...value, reference: rekeyReference(ids, value.reference) };
2475
+ }
2476
+ return value;
2477
+ }
2478
+ function isBinaryMarker(value) {
2479
+ return "binary" in value && value.binary === true;
2480
+ }
2481
+ function rekeyFilePartData(ids, value) {
2482
+ if (typeof value === "string")
2483
+ return value;
2484
+ if (isBinaryMarker(value))
2485
+ return value;
2486
+ if ("type" in value) {
2487
+ if (value.type === "reference" && "reference" in value && typeof value.reference === "object" && value.reference !== null) {
2488
+ return { type: "reference", reference: rekeyReference(ids, value.reference) };
2489
+ }
2490
+ return value;
2491
+ }
2492
+ return rekeyReference(ids, value);
2493
+ }
2494
+ function rekeyImagePartData(ids, value) {
2495
+ if (typeof value === "string")
2496
+ return value;
2497
+ if (isBinaryMarker(value))
2498
+ return value;
2499
+ return rekeyReference(ids, value);
2500
+ }
2501
+ function rekeyReasoningFileData(_ids, value) {
2502
+ return value;
2503
+ }
2504
+
2505
+ class BranchProvider {
2506
+ ids;
2507
+ digests = new Map;
2508
+ constructor(ids) {
2509
+ this.ids = ids;
2510
+ }
2511
+ rekey(kind, raw) {
2512
+ if (kind === "provider/message") {
2513
+ const value = ProviderJournalMessageSchema.parse(raw);
2514
+ if (hash(value.message) !== value.sha256)
2515
+ throw new TypeError("Branch provider message digest is inconsistent");
2516
+ const rekeyedMessageOptions = value.message.providerOptions ? rekeyProviderOptions(this.ids, value.message.providerOptions) : undefined;
2517
+ const message = {
2518
+ ...value.message,
2519
+ ...rekeyedMessageOptions !== undefined && { providerOptions: rekeyedMessageOptions },
2520
+ content: typeof value.message.content === "string" ? value.message.content : value.message.content.map((part) => this.rekeyPart(part))
2521
+ };
2522
+ const sha256 = hash(message);
2523
+ this.digests.set(value.sha256, sha256);
2524
+ return { sha256, message };
2525
+ }
2526
+ if (kind === "provider/request") {
2527
+ const value = ProviderJournalRequestSchema.parse(raw);
2528
+ const sourceHash = createHash3("sha256").update(value.instructionsSha256).update(value.messageShas.join(",")).digest("hex");
2529
+ if (sourceHash !== value.bodySha256)
2530
+ throw new TypeError("Branch provider request digest is inconsistent");
2531
+ const messageShas = value.messageShas.map((sha) => {
2532
+ const target = this.digests.get(sha);
2533
+ if (!target)
2534
+ throw new TypeError("Branch provider request references a missing message");
2535
+ return target;
2536
+ });
2537
+ return {
2538
+ ...value,
2539
+ runId: this.ids.reference("run", value.runId),
2540
+ messageShas,
2541
+ bodySha256: createHash3("sha256").update(value.instructionsSha256).update(messageShas.join(",")).digest("hex")
2542
+ };
2543
+ }
2544
+ const value = ProviderJournalResponseSchema.parse(raw);
2545
+ return { ...value, runId: this.ids.reference("run", value.runId) };
2546
+ }
2547
+ rekeyPart(part) {
2548
+ const providerOptions = "providerOptions" in part && part.providerOptions !== undefined ? rekeyProviderOptions(this.ids, part.providerOptions) : undefined;
2549
+ const base = providerOptions !== undefined ? { ...part, providerOptions } : part;
2550
+ if (base.type === "file") {
2551
+ return { ...base, data: rekeyFilePartData(this.ids, base.data) };
2552
+ }
2553
+ if (base.type === "reasoning-file") {
2554
+ return { ...base, data: rekeyReasoningFileData(this.ids, base.data) };
2555
+ }
2556
+ if (base.type === "image") {
2557
+ return { ...base, image: rekeyImagePartData(this.ids, base.image) };
2558
+ }
2559
+ if (base.type === "tool-call") {
2560
+ return {
2561
+ ...base,
2562
+ toolCallId: this.ids.reference("call", base.toolCallId),
2563
+ input: branchToolJson(this.ids, base.toolName, base.input, false)
2564
+ };
2565
+ }
2566
+ if (base.type === "tool-result") {
2567
+ return {
2568
+ ...base,
2569
+ toolCallId: this.ids.reference("call", base.toolCallId),
2570
+ output: this.rekeyToolResultOutput(base.toolName, base.output)
2571
+ };
2572
+ }
2573
+ if (base.type === "tool-approval-request") {
2574
+ return {
2575
+ type: base.type,
2576
+ approvalId: this.ids.reference("approval", base.approvalId),
2577
+ toolCallId: this.ids.reference("call", base.toolCallId),
2578
+ ...base.reason !== undefined && { reason: base.reason }
2579
+ };
2580
+ }
2581
+ if (base.type === "tool-approval-response") {
2582
+ return {
2583
+ ...base,
2584
+ approvalId: this.ids.reference("approval", base.approvalId)
2585
+ };
2586
+ }
2587
+ return base;
2588
+ }
2589
+ rekeyToolResultOutput(toolName, output) {
2590
+ const providerOptions = "providerOptions" in output && output.providerOptions !== undefined ? rekeyProviderOptions(this.ids, output.providerOptions) : undefined;
2591
+ if (output.type === "json") {
2592
+ return {
2593
+ ...output,
2594
+ ...providerOptions !== undefined && { providerOptions },
2595
+ value: branchToolJson(this.ids, toolName, output.value, true)
2596
+ };
2597
+ }
2598
+ if (output.type === "error-json") {
2599
+ return {
2600
+ ...output,
2601
+ ...providerOptions !== undefined && { providerOptions },
2602
+ value: branchOpaqueJson(this.ids, output.value)
2603
+ };
2604
+ }
2605
+ if (output.type === "content") {
2606
+ return {
2607
+ ...output,
2608
+ value: output.value.map((item) => {
2609
+ const itemOptions = item.providerOptions !== undefined ? rekeyProviderOptions(this.ids, item.providerOptions) : undefined;
2610
+ const next = itemOptions !== undefined ? { ...item, providerOptions: itemOptions } : item;
2611
+ if (next.type === "file") {
2612
+ return { ...next, data: rekeyContentFileData(this.ids, next.data) };
2613
+ }
2614
+ if (next.type === "file-reference" || next.type === "image-file-reference") {
2615
+ return {
2616
+ ...next,
2617
+ providerReference: rekeyReference(this.ids, next.providerReference)
2618
+ };
2619
+ }
2620
+ if ((next.type === "file-id" || next.type === "image-file-id") && typeof next.fileId !== "string") {
2621
+ return { ...next, fileId: rekeyReference(this.ids, next.fileId) };
2622
+ }
2623
+ return next;
2624
+ })
2625
+ };
2626
+ }
2627
+ return providerOptions !== undefined ? { ...output, providerOptions } : output;
2628
+ }
2629
+ }
2630
+
2631
+ // src/agent-runtime/stores/branch-transitions.ts
2632
+ import { z as z19 } from "zod";
2633
+ function rekeyBranchTransition(ids, source, operation) {
2634
+ const message = (value) => branchMessage(ids, source, value);
2635
+ const input = operation.input;
2636
+ switch (operation.type) {
2637
+ case "accept":
2638
+ return {
2639
+ type: operation.type,
2640
+ input: {
2641
+ ...operation.input,
2642
+ idempotencyKey: ids.define("key", operation.input.idempotencyKey),
2643
+ input: message(operation.input.input),
2644
+ run: branchRun(ids, source, operation.input.run, false),
2645
+ ...operation.input.coalesceIntoRunId && {
2646
+ coalesceIntoRunId: ids.reference("run", operation.input.coalesceIntoRunId)
2647
+ }
2648
+ }
2649
+ };
2650
+ case "seed":
2651
+ return {
2652
+ type: operation.type,
2653
+ input: {
2654
+ ...operation.input,
2655
+ conversationId: ids.conversationId,
2656
+ seedKey: ids.define("key", operation.input.seedKey),
2657
+ inputs: operation.input.inputs.map(message)
2658
+ }
2659
+ };
2660
+ case "compact":
2661
+ return {
2662
+ type: operation.type,
2663
+ input: {
2664
+ ...operation.input,
2665
+ conversationId: ids.conversationId,
2666
+ replacedMessageIds: operation.input.replacedMessageIds.map((id) => ids.reference("message", id)),
2667
+ summary: message(operation.input.summary)
2668
+ }
2669
+ };
2670
+ default: {
2671
+ if (!("runId" in input))
2672
+ throw new TypeError("Branch transition has no run identity");
2673
+ const common = {
2674
+ ...input,
2675
+ conversationId: ids.conversationId,
2676
+ runId: ids.reference("run", input.runId),
2677
+ ..."ownerId" in input && { ownerId: ids.define("owner", input.ownerId) }
2678
+ };
2679
+ return AgentStoreTransitionSchema2.parse({
2680
+ type: operation.type,
2681
+ ...operation.type === "recover" && operation.assistant && { assistant: message(operation.assistant) },
2682
+ ...operation.type === "recover" && operation.usage && { usage: operation.usage },
2683
+ input: {
2684
+ ...common,
2685
+ ...operation.type === "checkpoint" || operation.type === "terminal" ? { assistant: message(operation.input.assistant) } : {},
2686
+ ...operation.type === "operation" && {
2687
+ operation: {
2688
+ ...operation.input.operation,
2689
+ operationId: ids.reference("operation", operation.input.operation.operationId)
2690
+ }
2691
+ },
2692
+ ...operation.type === "terminal" && operation.input.absorb && {
2693
+ absorb: operation.input.absorb.map((entry) => ({
2694
+ runId: ids.reference("run", entry.runId),
2695
+ inputMessageIds: entry.inputMessageIds.map((id) => ids.reference("message", id))
2696
+ }))
2697
+ }
2698
+ }
2699
+ });
2700
+ }
2701
+ }
2702
+ }
2703
+ function branchJson(value) {
2704
+ return z19.json().parse(value);
2705
+ }
2706
+
2707
+ // src/agent-runtime/stores/branch-events.ts
2708
+ var Hash3 = z20.string().regex(/^[a-f0-9]{64}$/);
2709
+ function rekeyBranchEvents(ids, source, events, retainedMessages = new Map) {
2710
+ try {
2711
+ const hydrated = events.map((event) => atEvent(ids, event, () => {
2712
+ const assistant = retainedMessages.get(event.eventId);
2713
+ if (!assistant)
2714
+ return event;
2715
+ ids.collectMessage(assistant);
2716
+ const operation = event.kind === "runtime/transition" ? branchTransition(event) : undefined;
2717
+ if (operation?.type === "recover" && operation.input.action === "abandon" && !operation.assistant)
2718
+ return { ...event, payload: branchJson({ ...operation, assistant }) };
2719
+ return event;
2720
+ }));
2721
+ for (const event of hydrated)
2722
+ atEvent(ids, event, () => collectBranchEvent(ids, event));
2723
+ for (const event of hydrated) {
2724
+ const assistant = retainedMessages.get(event.eventId);
2725
+ if (assistant)
2726
+ atEvent(ids, event, () => branchMessage(ids, source, assistant));
2727
+ }
2728
+ const provider = new BranchProvider(ids);
2729
+ return hydrated.map((event) => atEvent(ids, event, () => rekeyBranchEvent(ids, source, event, provider)));
2730
+ } catch (error) {
2731
+ throw ids.integrityError(error);
2732
+ }
2733
+ }
2734
+ function atEvent(ids, event, work) {
2735
+ return ids.within({ seq: event.seq, eventKind: event.kind }, work);
2736
+ }
2737
+ function collectBranchEvent(ids, event) {
2738
+ ids.define("event", event.eventId);
2739
+ if (event.schemaVersion !== 1)
2740
+ throw new TypeError("Branch requires a supported event version");
2741
+ if (event.kind === "runtime/transition")
2742
+ ids.collectOperation(branchTransition(event));
2743
+ if (event.kind === "runtime/baseline") {
2744
+ const baseline = BranchBaselineSchema.parse(event.payload);
2745
+ if (canonicalAgentJson2(baseline) !== canonicalAgentJson2(event.payload))
2746
+ throw new TypeError("Branch baseline contains an unknown opaque field");
2747
+ for (const record of baseline.runs)
2748
+ ids.collectRun(record.run);
2749
+ for (const message of baseline.messages)
2750
+ ids.collectMessage(message);
2751
+ for (const receipt of baseline.admissions)
2752
+ ids.define("key", receipt.idempotencyKey);
2753
+ }
2754
+ if (event.kind === "runtime/branched")
2755
+ ids.define("key", AgentConversationBranchReceiptSchema2.parse(event.payload).requestKey);
2756
+ if (event.kind === "runtime/branch-observation") {
2757
+ const observation = BranchObservationSchema.parse(event.payload);
2758
+ collectObservationDefinitions(ids, observation.sourceKind, observation.payload);
2759
+ } else
2760
+ collectObservationDefinitions(ids, event.kind, event.payload);
2761
+ }
2762
+ function rekeyBranchEvent(ids, source, event, provider) {
2763
+ const envelope = {
2764
+ ...event,
2765
+ eventId: ids.reference("event", event.eventId),
2766
+ conversationId: ids.conversationId
2767
+ };
2768
+ const message = (value) => branchMessage(ids, source, value);
2769
+ if (event.kind === "runtime/transition") {
2770
+ const operation = branchTransition(event);
2771
+ const rekeyed = rekeyBranchTransition(ids, source, operation);
2772
+ const raw = z20.object({
2773
+ type: z20.string(),
2774
+ input: z20.object({
2775
+ assistant: z20.object({
2776
+ sha256: Hash3.optional(),
2777
+ sourceSha256: Hash3.optional(),
2778
+ bytes: z20.int(),
2779
+ parts: z20.int()
2780
+ }).passthrough()
2781
+ }).passthrough()
2782
+ }).passthrough().safeParse(event.payload);
2783
+ if (operation.type === "checkpoint" && raw.success && rekeyed.type === "checkpoint") {
2784
+ const draft = raw.data.input.assistant;
2785
+ return {
2786
+ ...envelope,
2787
+ payload: branchJson({
2788
+ type: "checkpoint",
2789
+ input: {
2790
+ ...rekeyed.input,
2791
+ assistant: {
2792
+ id: rekeyed.input.assistant.id,
2793
+ status: "streaming",
2794
+ sourceSha256: draft.sha256 ?? draft.sourceSha256,
2795
+ parts: draft.parts,
2796
+ bytes: draft.bytes
2797
+ }
2798
+ }
2799
+ })
2800
+ };
2801
+ }
2802
+ if (canonicalAgentJson2(operation) !== canonicalAgentJson2(event.payload))
2803
+ throw new TypeError("Branch transition contains an unknown opaque field");
2804
+ return { ...envelope, payload: branchJson(rekeyed) };
2805
+ }
2806
+ if (event.kind === "runtime/baseline") {
2807
+ const baseline = BranchBaselineSchema.parse(event.payload);
2808
+ return {
2809
+ ...envelope,
2810
+ payload: branchJson({
2811
+ ...baseline,
2812
+ head: { ...baseline.head, conversationId: ids.conversationId },
2813
+ messages: baseline.messages.map(message),
2814
+ ...baseline.compacted && {
2815
+ compacted: baseline.compacted.map((id) => ids.reference("message", id))
2816
+ },
2817
+ runs: baseline.runs.map((record) => ({
2818
+ ...record,
2819
+ run: branchRun(ids, source, record.run, false),
2820
+ ...record.terminalAssistant && {
2821
+ terminalAssistant: message(record.terminalAssistant)
2822
+ }
2823
+ })),
2824
+ admissions: baseline.admissions.map((receipt) => ({
2825
+ ...receipt,
2826
+ conversationId: ids.conversationId,
2827
+ idempotencyKey: ids.define("key", receipt.idempotencyKey),
2828
+ input: message(receipt.input),
2829
+ runId: ids.reference("run", receipt.runId),
2830
+ assistantMessageId: ids.reference("message", receipt.assistantMessageId)
2831
+ }))
2832
+ })
2833
+ };
2834
+ }
2835
+ if (event.kind === "runtime/branched") {
2836
+ const receipt = AgentConversationBranchReceiptSchema2.parse(event.payload);
2837
+ return {
2838
+ ...envelope,
2839
+ payload: branchJson({
2840
+ ...receipt,
2841
+ conversationId: ids.conversationId,
2842
+ requestKey: ids.define("key", receipt.requestKey)
2843
+ })
2844
+ };
2845
+ }
2846
+ if (event.kind === "provider/message" || (event.kind === "provider/request" || event.kind === "provider/response") && !isModelInvocationRecord(event.payload))
2847
+ return { ...envelope, payload: branchJson(provider.rekey(event.kind, event.payload)) };
2848
+ const observation = event.kind === "runtime/branch-observation" ? BranchObservationSchema.parse(event.payload) : { sourceKind: event.kind, payload: event.payload };
2849
+ return {
2850
+ ...envelope,
2851
+ kind: "runtime/branch-observation",
2852
+ payload: branchJson({
2853
+ sourceKind: observation.sourceKind,
2854
+ payload: branchObservation(ids, observation.sourceKind, observation.payload, event.kind === "runtime/branch-observation")
2855
+ })
2856
+ };
2857
+ }
2858
+
2859
+ // src/agent-runtime/stores/branch-identities.ts
2860
+ import { createHash as createHash4 } from "node:crypto";
2861
+ var raisedAt = new WeakMap;
2862
+
2863
+ class BranchIdentities {
2864
+ conversationId;
2865
+ requestKey;
2866
+ sourceConversationId;
2867
+ definitions = new Map;
2868
+ found = [];
2869
+ omitted = 0;
2870
+ address = {};
2871
+ files = new Set;
2872
+ references = new Map;
2873
+ applicationFiles = new Map;
2874
+ applicationKeys = new Map;
2875
+ constructor(conversationId, requestKey, sourceConversationId) {
2876
+ this.conversationId = conversationId;
2877
+ this.requestKey = requestKey;
2878
+ this.sourceConversationId = sourceConversationId;
2879
+ }
2880
+ define(kind, source) {
2881
+ const values = this.definitions.get(kind) ?? new Map;
2882
+ const target = values.get(source) ?? createHash4("sha256").update(JSON.stringify([this.conversationId, this.requestKey, kind, source])).digest("hex");
2883
+ values.set(source, target);
2884
+ this.definitions.set(kind, values);
2885
+ return target;
2886
+ }
2887
+ defineExpiredSpill(source) {
2888
+ return this.define("spill", source);
2889
+ }
2890
+ within(address, work) {
2891
+ const outer = this.address;
2892
+ this.address = { ...outer, ...address };
2893
+ try {
2894
+ return work();
2895
+ } catch (error) {
2896
+ if (typeof error === "object" && error !== null && !raisedAt.has(error))
2897
+ raisedAt.set(error, this.address);
2898
+ throw error;
2899
+ } finally {
2900
+ this.address = outer;
2901
+ }
2902
+ }
2903
+ refuse(refusal) {
2904
+ if (this.found.length >= MAX_BRANCH_REFUSALS) {
2905
+ this.omitted += 1;
2906
+ return;
2907
+ }
2908
+ this.found.push({ ...this.address, ...refusal });
2909
+ }
2910
+ refusedError() {
2911
+ return this.found.length > 0 ? new AgentConversationBranchRefusedError2(this.found, this.omitted) : undefined;
2912
+ }
2913
+ integrityError(error) {
2914
+ if (error instanceof AgentConversationBranchRefusedError2)
2915
+ return error;
2916
+ if (!(error instanceof Error))
2917
+ return error;
2918
+ if (error.name !== "TypeError" && error.name !== "ZodError")
2919
+ return error;
2920
+ const at = raisedAt.get(error) ?? this.address;
2921
+ return new AgentConversationBranchRefusedError2([...this.found, { ...at, code: "integrity", message: error.message }], this.omitted);
2922
+ }
2923
+ applicationFileReferences() {
2924
+ return [...this.files].sort();
2925
+ }
2926
+ reference(kind, source) {
2927
+ const target = this.definitions.get(kind)?.get(source);
2928
+ if (!target)
2929
+ throw new TypeError(`Branch contains a foreign or missing ${kind} reference`);
2930
+ const referenced = this.references.get(kind) ?? new Set;
2931
+ referenced.add(source);
2932
+ this.references.set(kind, referenced);
2933
+ return target;
2934
+ }
2935
+ declareApplicationFiles(files) {
2936
+ for (const file of files) {
2937
+ if (this.definitions.get("spill")?.has(file.reference))
2938
+ throw new TypeError("Branch application file reference is also a spill reference");
2939
+ this.applicationFiles.set(file.reference, file.destinationReference);
2940
+ }
2941
+ }
2942
+ declareApplicationKeys(keys) {
2943
+ for (const { key, sourceIdentity } of keys)
2944
+ this.applicationKeys.set(key, sourceIdentity);
2945
+ }
2946
+ applicationKey(key) {
2947
+ return this.applicationKeys.get(key);
2948
+ }
2949
+ sourceIdentitiesOf(value) {
2950
+ const kinds = new Set;
2951
+ if (value === this.sourceConversationId)
2952
+ kinds.add("conversation");
2953
+ for (const [kind, values] of this.definitions)
2954
+ if (values.has(value))
2955
+ kinds.add(kind);
2956
+ if (this.applicationFiles.has(value))
2957
+ kinds.add("file");
2958
+ return kinds;
2959
+ }
2960
+ fileReference(source) {
2961
+ if (this.definitions.get("spill")?.has(source))
2962
+ return this.reference("spill", source);
2963
+ this.files.add(source);
2964
+ const target = this.applicationFiles.get(source);
2965
+ if (target === undefined) {
2966
+ this.refuse({
2967
+ code: "application-file-undeclared",
2968
+ message: "Branch contains a foreign or missing file reference; declare it in applicationFiles if the application owns it",
2969
+ reference: source
2970
+ });
2971
+ return source;
2972
+ }
2973
+ return target;
2974
+ }
2975
+ referenced(kind) {
2976
+ return this.references.get(kind) ?? new Set;
2977
+ }
2978
+ collectMessage(message) {
2979
+ this.define("message", message.id);
2980
+ for (const part of message.parts) {
2981
+ if (part.type === "tool-call")
2982
+ this.define("call", part.callId);
2983
+ if (part.type === "tool-approval-request")
2984
+ this.define("approval", part.approvalId);
2985
+ }
2986
+ }
2987
+ collectRun(run) {
2988
+ this.define("run", run.id);
2989
+ if (run.ownerId)
2990
+ this.define("owner", run.ownerId);
2991
+ this.define("message", run.assistantMessageId);
2992
+ if (run.lastOperation)
2993
+ this.define("operation", run.lastOperation.operationId);
2994
+ }
2995
+ collectOperation(operation) {
2996
+ const input = operation.input;
2997
+ if ("ownerId" in input && typeof input.ownerId === "string")
2998
+ this.define("owner", input.ownerId);
2999
+ switch (operation.type) {
3000
+ case "accept":
3001
+ this.define("key", operation.input.idempotencyKey);
3002
+ this.collectRun(operation.input.run);
3003
+ this.collectMessage(operation.input.input);
3004
+ break;
3005
+ case "checkpoint":
3006
+ case "terminal":
3007
+ this.collectMessage(operation.input.assistant);
3008
+ break;
3009
+ case "recover":
3010
+ if (operation.assistant)
3011
+ this.collectMessage(operation.assistant);
3012
+ break;
3013
+ case "compact":
3014
+ this.collectMessage(operation.input.summary);
3015
+ break;
3016
+ case "seed":
3017
+ this.define("key", operation.input.seedKey);
3018
+ for (const message of operation.input.inputs)
3019
+ this.collectMessage(message);
3020
+ break;
3021
+ case "operation":
3022
+ this.define("operation", operation.input.operation.operationId);
3023
+ break;
3024
+ }
3025
+ }
3026
+ }
3027
+
3028
+ // src/agent-runtime/stores/branch-source.ts
3029
+ import { createHash as createHash6 } from "node:crypto";
3030
+ import { z as z22 } from "zod";
3031
+
3032
+ // src/agent-runtime/stores/archive-spill.ts
3033
+ import { createHash as createHash5 } from "node:crypto";
3034
+ import { z as z21 } from "zod";
3035
+ var ArchiveSpillSchema = z21.object({
3036
+ reference: z21.string().min(1),
3037
+ runId: z21.string().min(1).optional(),
3038
+ toolCallId: z21.string().min(1).optional(),
3039
+ mediaType: z21.string().min(1),
3040
+ bytes: z21.int().nonnegative(),
3041
+ sha256: z21.string().regex(/^[a-f0-9]{64}$/),
3042
+ createdAt: z21.iso.datetime({ offset: true }),
3043
+ expiresAt: z21.iso.datetime({ offset: true }).optional(),
3044
+ authorization: AgentCodingToolAuthorizationSchema2.optional(),
3045
+ base64: z21.string()
3046
+ }).strict().superRefine((spill, ctx) => {
3047
+ const bytes = Buffer.from(spill.base64, "base64");
3048
+ if (bytes.toString("base64") !== spill.base64 || bytes.byteLength !== spill.bytes || createHash5("sha256").update(bytes).digest("hex") !== spill.sha256) {
3049
+ ctx.addIssue({
3050
+ code: "custom",
3051
+ message: "Conversation archive spill bytes or digest are inconsistent"
3052
+ });
3053
+ }
3054
+ });
3055
+
3056
+ // src/agent-runtime/stores/branch-source.ts
3057
+ var SnapshotProjection = z22.object({ archiveType: z22.literal("runtime-snapshot"), snapshot: AgentSnapshotSchema2 }).strict();
3058
+ function branchHash(value) {
3059
+ return createHash6("sha256").update(canonicalAgentJson2(value)).digest("hex");
3060
+ }
3061
+ function visibleSnapshot(snapshot) {
3062
+ const referenced = new Set(snapshot.messages.flatMap((message) => message.runId ? [message.runId] : []));
3063
+ return {
3064
+ ...snapshot,
3065
+ runs: snapshot.runs.filter((run) => referenced.has(run.id) || isActiveRunState(run.state)).map(({ updatedAt: _time, ...run }) => run).sort((a, b) => a.id.localeCompare(b.id))
3066
+ };
3067
+ }
3068
+ function boundary(events, throughRunId) {
3069
+ if (!throughRunId)
3070
+ return events.length;
3071
+ for (const event of events) {
3072
+ if (event.kind !== "runtime/transition")
3073
+ continue;
3074
+ const candidate = z22.object({
3075
+ type: z22.string(),
3076
+ input: z22.object({
3077
+ runId: z22.string().optional(),
3078
+ reason: z22.string().optional(),
3079
+ action: z22.string().optional(),
3080
+ absorb: z22.array(z22.object({ runId: z22.string() })).optional()
3081
+ })
3082
+ }).safeParse(event.payload);
3083
+ if (!candidate.success)
3084
+ continue;
3085
+ const { type, input } = candidate.data;
3086
+ if (type === "terminal" && (input.runId === throughRunId || input.absorb?.some((entry) => entry.runId === throughRunId)) || type === "recover" && input.action === "abandon" && input.runId === throughRunId)
3087
+ return event.seq;
3088
+ }
3089
+ throw new TypeError("Branch boundary run has no exact settled event");
3090
+ }
3091
+ function integrityRefusal(message, address) {
3092
+ return new AgentConversationBranchRefusedError2([
3093
+ { ...address ?? {}, code: "integrity", message }
3094
+ ]);
3095
+ }
3096
+ function collectExpiredSpills(events, liveSpills) {
3097
+ const created = new Map;
3098
+ const deleted = new Map;
3099
+ for (const event of events) {
3100
+ let sourceKind = event.kind;
3101
+ let payload = event.payload;
3102
+ if (event.kind === "runtime/branch-observation") {
3103
+ const obs = BranchObservationSchema.safeParse(event.payload);
3104
+ if (!obs.success)
3105
+ continue;
3106
+ sourceKind = obs.data.sourceKind;
3107
+ payload = obs.data.payload;
3108
+ }
3109
+ if (sourceKind !== "spill/created" && sourceKind !== "spill/deleted")
3110
+ continue;
3111
+ const parsed = SpillEventPayloadSchema.safeParse(payload);
3112
+ if (!parsed.success) {
3113
+ throw integrityRefusal(`Branch archive has malformed ${sourceKind} payload`, {
3114
+ seq: event.seq,
3115
+ eventKind: event.kind
3116
+ });
3117
+ }
3118
+ const { reference, bytes, sha256 } = parsed.data;
3119
+ if (sourceKind === "spill/created") {
3120
+ if (created.has(reference)) {
3121
+ throw integrityRefusal("Branch archive has duplicate spill/created event", {
3122
+ seq: event.seq,
3123
+ eventKind: event.kind
3124
+ });
3125
+ }
3126
+ created.set(reference, { seq: event.seq, bytes, ...sha256 ? { sha256 } : {} });
3127
+ } else {
3128
+ if (deleted.has(reference)) {
3129
+ throw integrityRefusal("Branch archive has duplicate spill/deleted event", {
3130
+ seq: event.seq,
3131
+ eventKind: event.kind
3132
+ });
3133
+ }
3134
+ const origin = created.get(reference);
3135
+ if (!origin || event.seq <= origin.seq) {
3136
+ throw integrityRefusal("Branch archive has spill/deleted without prior spill/created", {
3137
+ seq: event.seq,
3138
+ eventKind: event.kind
3139
+ });
3140
+ }
3141
+ if (origin.bytes !== bytes || origin.sha256 !== undefined && sha256 !== undefined && origin.sha256 !== sha256) {
3142
+ throw integrityRefusal("Branch archive spill/deleted disagrees with spill/created", {
3143
+ seq: event.seq,
3144
+ eventKind: event.kind
3145
+ });
3146
+ }
3147
+ deleted.set(reference, {
3148
+ seq: event.seq,
3149
+ bytes,
3150
+ ...sha256 !== undefined ? { sha256 } : origin.sha256 !== undefined ? { sha256: origin.sha256 } : {}
3151
+ });
3152
+ }
3153
+ }
3154
+ const liveSet = new Set(liveSpills.map((spill) => spill.reference));
3155
+ for (const [ref, meta] of deleted) {
3156
+ if (liveSet.has(ref)) {
3157
+ throw integrityRefusal("Branch archive has both a live spill and spill/deleted", {
3158
+ seq: meta.seq,
3159
+ eventKind: "spill/deleted"
3160
+ });
3161
+ }
3162
+ }
3163
+ return {
3164
+ expiredSpills: [...deleted.keys()].sort(),
3165
+ deletedMeta: deleted
3166
+ };
3167
+ }
3168
+ function prepareBranchSource(bytes, {
3169
+ source,
3170
+ applicationFiles = [],
3171
+ applicationKeys = []
3172
+ }) {
3173
+ const archive = decodeAgentConversationArchive2(bytes);
3174
+ if (source.kind === "conversation" && source.conversationId !== archive.conversationId)
3175
+ throw new TypeError("Branch source identity changed");
3176
+ for (const [index, event] of archive.events.entries()) {
3177
+ if (event.seq !== index + 1)
3178
+ throw new TypeError("Branch source event sequence is incomplete");
3179
+ }
3180
+ const projections = archive.projections.map((value) => z22.union([SnapshotProjection, ArchiveProjectionSchema]).parse(value));
3181
+ if (projections.some((value, index) => canonicalAgentJson2(value) !== canonicalAgentJson2(archive.projections[index])))
3182
+ throw new TypeError("Branch archive snapshot contains an unknown opaque field");
3183
+ const snapshots = projections.filter((value) => ("archiveType" in value));
3184
+ if (snapshots.length !== 1)
3185
+ throw new TypeError("Branch archive requires exactly one runtime snapshot");
3186
+ const names = new Set;
3187
+ for (const projection of projections) {
3188
+ if (!("name" in projection))
3189
+ continue;
3190
+ if (names.has(projection.name) || projection.uptoSeq > archive.events.length)
3191
+ throw new TypeError("Branch companion projection has an inconsistent checkpoint");
3192
+ names.add(projection.name);
3193
+ }
3194
+ const expected = snapshots[0]?.snapshot;
3195
+ if (!expected || expected.conversationId !== archive.conversationId)
3196
+ throw new TypeError("Branch archive has a foreign snapshot");
3197
+ const allSpills = archive.spills.map((value) => ArchiveSpillSchema.parse(value));
3198
+ if (new Set(allSpills.map((spill) => spill.reference)).size !== allSpills.length)
3199
+ throw new TypeError("Branch archive has duplicate spill identities");
3200
+ const { expiredSpills: allExpiredSpills, deletedMeta } = collectExpiredSpills(archive.events, allSpills);
3201
+ const full = replayBranchEvents(archive.conversationId, archive.events, expected);
3202
+ const validationIds = new BranchIdentities("branch-validation", "branch-validation", archive.conversationId);
3203
+ for (const spill of allSpills)
3204
+ validationIds.define("spill", spill.reference);
3205
+ for (const expired of allExpiredSpills)
3206
+ validationIds.defineExpiredSpill(expired);
3207
+ validationIds.declareApplicationFiles(applicationFiles);
3208
+ validationIds.declareApplicationKeys(applicationKeys);
3209
+ rekeyBranchEvents(validationIds, archive.conversationId, archive.events, full.retainedMessages);
3210
+ for (const spill of allSpills) {
3211
+ if (spill.runId)
3212
+ validationIds.reference("run", spill.runId);
3213
+ if (spill.toolCallId)
3214
+ validationIds.reference("call", spill.toolCallId);
3215
+ }
3216
+ const refused = validationIds.refusedError();
3217
+ if (canonicalAgentJson2(visibleSnapshot(full.snapshot)) !== canonicalAgentJson2(visibleSnapshot(expected)))
3218
+ throw new TypeError("Branch archive snapshot disagrees with its event log");
3219
+ const seq = boundary(archive.events, source.kind === "conversation" ? source.throughRunId : undefined);
3220
+ const events = archive.events.slice(0, seq);
3221
+ const replay = seq === archive.events.length ? full : replayBranchEvents(archive.conversationId, events, expected);
3222
+ if (replay.snapshot.runs.some((run) => isActiveRunState(run.state)))
3223
+ throw new TypeError("Branch boundary is not settled");
3224
+ if (replay.unresolvedDrafts.size > 0)
3225
+ throw new TypeError("Branch boundary has no full terminal content for a hashed draft");
3226
+ const selectedIds = new BranchIdentities("branch-validation", "branch-validation", archive.conversationId);
3227
+ for (const spill of allSpills)
3228
+ selectedIds.define("spill", spill.reference);
3229
+ for (const expired of allExpiredSpills)
3230
+ selectedIds.defineExpiredSpill(expired);
3231
+ selectedIds.declareApplicationFiles(applicationFiles);
3232
+ selectedIds.declareApplicationKeys(applicationKeys);
3233
+ rekeyBranchEvents(selectedIds, archive.conversationId, events, replay.retainedMessages);
3234
+ const references = selectedIds.referenced("spill");
3235
+ const spills = allSpills.filter((spill) => references.has(spill.reference));
3236
+ const expiredSpills = allExpiredSpills.filter((ref) => references.has(ref));
3237
+ if (spills.length + expiredSpills.length !== references.size)
3238
+ throw integrityRefusal("Branch source is missing a referenced spill");
3239
+ const tailDeletedSpills = [];
3240
+ for (const ref of expiredSpills) {
3241
+ const meta = deletedMeta.get(ref);
3242
+ if (meta && meta.seq > seq) {
3243
+ tailDeletedSpills.push({
3244
+ reference: ref,
3245
+ bytes: meta.bytes,
3246
+ ...meta.sha256 !== undefined && { sha256: meta.sha256 }
3247
+ });
3248
+ }
3249
+ }
3250
+ return {
3251
+ conversationId: archive.conversationId,
3252
+ events,
3253
+ spills,
3254
+ expiredSpills,
3255
+ tailDeletedSpills,
3256
+ replay,
3257
+ ...refused && { refused },
3258
+ applicationFiles: validationIds.applicationFileReferences(),
3259
+ digest: branchHash({
3260
+ conversationId: archive.conversationId,
3261
+ events,
3262
+ spills,
3263
+ expiredSpills,
3264
+ snapshot: replay.snapshot
3265
+ })
3266
+ };
3267
+ }
3268
+
3269
+ // src/agent-runtime/stores/store-branch.ts
3270
+ async function destinationEvents(driver, tx, conversationId) {
3271
+ const events = [];
3272
+ let fromSeq;
3273
+ do {
3274
+ const page = await driver.events.list(tx, { conversationId, fromSeq, limit: 1e4 });
3275
+ events.push(...page.items);
3276
+ fromSeq = page.nextSeq;
3277
+ } while (fromSeq !== undefined);
3278
+ return events;
3279
+ }
3280
+ function branchRequest(raw) {
3281
+ const parsed = BranchAgentConversationInputSchema2.parse(raw);
3282
+ const input = {
3283
+ ...parsed,
3284
+ source: parsed.source.kind === "archive" ? { ...parsed.source, bytes: Uint8Array.from(parsed.source.bytes) } : parsed.source
3285
+ };
3286
+ const fingerprint = branchHash({
3287
+ ...input,
3288
+ ...input.applicationFiles && {
3289
+ applicationFiles: input.applicationFiles.toSorted((left, right) => left.reference.localeCompare(right.reference))
3290
+ },
3291
+ ...input.applicationKeys && {
3292
+ applicationKeys: input.applicationKeys.toSorted((left, right) => left.key.localeCompare(right.key))
3293
+ },
3294
+ source: input.source.kind === "archive" ? {
3295
+ kind: "archive",
3296
+ digest: createHash7("sha256").update(input.source.bytes).digest("hex")
3297
+ } : input.source
3298
+ });
3299
+ return { input, fingerprint };
3300
+ }
3301
+ async function sourceBytes(driver, tx, input) {
3302
+ if (input.source.kind === "archive")
3303
+ return input.source.bytes;
3304
+ if (await driver.conversations?.isPurged(tx, input.source.conversationId))
3305
+ throw new AgentConversationPurgedError2;
3306
+ if (!await driver.head.load(tx, input.source.conversationId) && (await driver.events.list(tx, { conversationId: input.source.conversationId, limit: 1 })).items.length === 0)
3307
+ throw new TypeError("Branch source conversation was not found");
3308
+ return exportConversationIn(driver, tx, input.source.conversationId);
3309
+ }
3310
+ function assertBranchDriverCapabilities(driver, source) {
3311
+ assertSourceCapabilities(driver, {
3312
+ spills: source.spills.length,
3313
+ projections: 0,
3314
+ compacted: source.replay.baseline?.compacted?.length ?? 0
3315
+ });
3316
+ }
3317
+ function requestRefusal(input, source) {
3318
+ const missingAuthorization = source.spills.length > 0 && !input.artifactAuthorization;
3319
+ if (!source.refused && !missingAuthorization)
3320
+ return;
3321
+ return new AgentConversationBranchRefusedError2([
3322
+ ...source.refused?.refusals ?? [],
3323
+ ...missingAuthorization ? [
3324
+ {
3325
+ code: "artifact-authorization-missing",
3326
+ message: "Branch spills require fresh destination artifact authorization"
3327
+ }
3328
+ ] : []
3329
+ ], source.refused?.omittedRefusals ?? 0);
3330
+ }
3331
+ async function planConversationBranch(driver, raw) {
3332
+ const { input, fingerprint } = branchRequest(raw);
3333
+ return driver.transaction(async (tx) => {
3334
+ const bytes = await sourceBytes(driver, tx, input);
3335
+ const sourceArchiveDigest = createHash7("sha256").update(bytes).digest("hex");
3336
+ let source;
3337
+ try {
3338
+ source = prepareBranchSource(bytes, input);
3339
+ } catch (error) {
3340
+ if (!(error instanceof AgentConversationBranchRefusedError2))
3341
+ throw error;
3342
+ return planOf(fingerprint, sourceArchiveDigest, error, []);
3343
+ }
3344
+ assertBranchDriverCapabilities(driver, source);
3345
+ return planOf(fingerprint, sourceArchiveDigest, requestRefusal(input, source), source.applicationFiles);
3346
+ }, { access: "read" });
3347
+ }
3348
+ function planOf(fingerprint, sourceArchiveDigest, refused, applicationFiles) {
3349
+ const refusals = refused?.refusals ?? [];
3350
+ return AgentConversationBranchPlanSchema2.parse({
3351
+ ready: refusals.length === 0,
3352
+ fingerprint,
3353
+ sourceArchiveDigest,
3354
+ refusals,
3355
+ omittedRefusals: refused?.omittedRefusals ?? 0,
3356
+ applicationFiles,
3357
+ undeclaredKeys: [
3358
+ ...new Set(refusals.flatMap((refusal) => refusal.code === "application-key-undeclared" && refusal.key ? [refusal.key] : []))
3359
+ ].sort()
3360
+ });
3361
+ }
3362
+ async function branchConversation(driver, raw) {
3363
+ const { input, fingerprint } = branchRequest(raw);
3364
+ return driver.transaction(async (tx) => {
3365
+ if (await driver.conversations?.isPurged(tx, input.destinationConversationId))
3366
+ throw new AgentConversationPurgedError2;
3367
+ const existing = await destinationEvents(driver, tx, input.destinationConversationId);
3368
+ const previous = existing.filter((event) => event.kind === "runtime/branched").at(-1);
3369
+ if (previous) {
3370
+ const receipt = AgentConversationBranchReceiptSchema2.parse(previous.payload);
3371
+ if (receipt.requestKey === input.requestKey && receipt.fingerprint === fingerprint && receipt.conversationId === input.destinationConversationId)
3372
+ return { outcome: "duplicate", receipt };
3373
+ throw new TypeError("Branch request conflicts with the destination receipt");
3374
+ }
3375
+ if (driver.conversations?.isEmpty && !await driver.conversations.isEmpty(tx, input.destinationConversationId) || existing.length > 0 || await driver.head.load(tx, input.destinationConversationId) || (await driver.history.load(tx, input.destinationConversationId)).length > 0)
3376
+ throw new TypeError("Branch destination must be empty");
3377
+ const bytes = await sourceBytes(driver, tx, input);
3378
+ const source = prepareBranchSource(bytes, input);
3379
+ if (source.conversationId === input.destinationConversationId)
3380
+ throw new TypeError("Branch requires a new conversation identity");
3381
+ assertBranchDriverCapabilities(driver, source);
3382
+ const refused = requestRefusal(input, source);
3383
+ if (refused)
3384
+ throw refused;
3385
+ const ids = new BranchIdentities(input.destinationConversationId, input.requestKey, source.conversationId);
3386
+ for (const spill of source.spills)
3387
+ ids.define("spill", spill.reference);
3388
+ for (const expired of source.expiredSpills)
3389
+ ids.defineExpiredSpill(expired);
3390
+ ids.declareApplicationFiles(input.applicationFiles ?? []);
3391
+ ids.declareApplicationKeys(input.applicationKeys ?? []);
3392
+ const events = rekeyBranchEvents(ids, source.conversationId, source.events, source.replay.retainedMessages);
3393
+ const late = ids.refusedError();
3394
+ if (late)
3395
+ throw late;
3396
+ const replay = replayBranchEvents(input.destinationConversationId, events);
3397
+ const spills = source.spills.map(({ authorization: _sourceAuthority, ...spill }) => ({
3398
+ ...spill,
3399
+ reference: ids.reference("spill", spill.reference),
3400
+ ...spill.runId && { runId: ids.reference("run", spill.runId) },
3401
+ ...spill.toolCallId && { toolCallId: ids.reference("call", spill.toolCallId) },
3402
+ authorization: input.artifactAuthorization
3403
+ }));
3404
+ const receipt = AgentConversationBranchReceiptSchema2.parse({
3405
+ schemaVersion: 1,
3406
+ requestKey: input.requestKey,
3407
+ fingerprint,
3408
+ conversationId: input.destinationConversationId,
3409
+ sourceConversationId: source.conversationId,
3410
+ sourceKind: input.source.kind,
3411
+ ...input.source.kind === "conversation" && input.source.throughRunId && { throughRunId: input.source.throughRunId },
3412
+ sourceSeq: source.events.at(-1)?.seq ?? 0,
3413
+ sourceVersion: source.replay.snapshot.version,
3414
+ sourceDigest: source.digest,
3415
+ createdAt: new Date().toISOString()
3416
+ });
3417
+ const next = {
3418
+ schemaVersion: 1,
3419
+ conversationId: input.destinationConversationId,
3420
+ version: replay.snapshot.version
3421
+ };
3422
+ const cas = await driver.head.compareAndSwap(tx, {
3423
+ conversationId: input.destinationConversationId,
3424
+ expectedVersion: 0,
3425
+ next
3426
+ });
3427
+ if (cas.outcome !== "applied")
3428
+ throw new TypeError("Branch destination changed");
3429
+ await persistRuntimeReplay(driver, tx, replay);
3430
+ for (const run of replay.snapshot.runs) {
3431
+ const stored = await driver.runs.load(tx, {
3432
+ conversationId: run.conversationId,
3433
+ runId: run.id
3434
+ });
3435
+ if (!stored)
3436
+ throw new TypeError("Branch lost a normalized terminal record");
3437
+ const { ownerId: _owner, fencingToken: _fence, ...settled } = stored.run;
3438
+ await driver.runs.save(tx, { ...stored, run: settled });
3439
+ }
3440
+ for (const event of events) {
3441
+ const appended = await driver.events.append(tx, event);
3442
+ if (appended.seq !== event.seq)
3443
+ throw new TypeError("Branch event sequence changed");
3444
+ }
3445
+ for (const tail of source.tailDeletedSpills) {
3446
+ await driver.events.append(tx, agentStoreEventDraft({
3447
+ conversationId: input.destinationConversationId,
3448
+ kind: "runtime/branch-observation",
3449
+ payload: {
3450
+ sourceKind: "spill/deleted",
3451
+ payload: {
3452
+ reference: ids.reference("spill", tail.reference),
3453
+ bytes: tail.bytes,
3454
+ ...tail.sha256 !== undefined && { sha256: tail.sha256 }
3455
+ }
3456
+ }
3457
+ }));
3458
+ }
3459
+ await driver.archive?.import(tx, {
3460
+ format: "stitchkit.agent-conversation",
3461
+ formatVersion: 1,
3462
+ conversationId: input.destinationConversationId,
3463
+ events: [],
3464
+ projections: [],
3465
+ spills: z23.array(z23.json()).parse(spills)
3466
+ });
3467
+ await driver.events.append(tx, agentStoreEventDraft({
3468
+ conversationId: input.destinationConversationId,
3469
+ kind: "runtime/branched",
3470
+ payload: z23.json().parse(receipt)
3471
+ }));
3472
+ return { outcome: "created", receipt };
3473
+ });
3474
+ }
3475
+
3476
+ // src/agent-runtime/stores/store-event-once.ts
3477
+ import { createHash as createHash8 } from "node:crypto";
3478
+ function eventOnceId(conversationId, kind, key) {
3479
+ if (!key)
3480
+ throw new TypeError("Event admission key must not be empty");
3481
+ return createHash8("sha256").update(JSON.stringify([conversationId, kind, key])).digest("hex");
3482
+ }
3483
+ function appendEventOnce(driver, input, key) {
3484
+ const parsed = AppendAgentStoreEventSchema2.parse(input);
3485
+ const eventId = eventOnceId(parsed.conversationId, parsed.kind, key);
3486
+ return driver.transaction(async (transaction) => {
3487
+ if (await driver.conversations?.isPurged(transaction, parsed.conversationId)) {
3488
+ throw new AgentConversationPurgedError2;
3489
+ }
3490
+ const previous = await driver.events.find(transaction, {
3491
+ conversationId: parsed.conversationId,
3492
+ eventId
3493
+ });
3494
+ if (previous)
3495
+ return { outcome: "duplicate", event: previous };
3496
+ const event = await driver.events.append(transaction, {
3497
+ ...agentStoreEventDraft(parsed),
3498
+ eventId
3499
+ });
3500
+ return { outcome: "applied", event };
3501
+ });
3502
+ }
3503
+ function findEventOnce(driver, input) {
3504
+ const eventId = eventOnceId(input.conversationId, input.kind, input.key);
3505
+ return driver.transaction((transaction) => driver.events.find(transaction, { conversationId: input.conversationId, eventId }), { access: "read" });
3506
+ }
3507
+
3508
+ // src/agent-runtime/stores/store-mutate.ts
3509
+ import { z as z24 } from "zod";
3510
+ function validateAdmissionReceipt(receipt, record, conversationId) {
3511
+ const input = receipt.input;
3512
+ const run = record.run;
3513
+ if (receipt.conversationId !== conversationId || input.conversationId !== conversationId || input.role !== "user" || input.status !== "committed" || input.runId !== undefined || receipt.runId !== run.id || receipt.assistantMessageId !== run.assistantMessageId || !run.inputMessageIds.includes(input.id)) {
3514
+ throw new TypeError("Admission receipt does not match its canonical run assignment");
3515
+ }
3516
+ }
3517
+ async function readForMutation(driver, transaction, operation) {
3518
+ const conversationId = operationConversationId(operation);
3519
+ if (await driver.conversations?.isPurged(transaction, conversationId)) {
3520
+ throw new AgentConversationPurgedError2;
3521
+ }
3522
+ const operationRunId = operation.type === "accept" ? operation.input.coalesceIntoRunId : operation.type === "compact" || operation.type === "seed" ? undefined : operation.input.runId;
3523
+ const [stored, messages, activeRecords, operationRecord, duplicateReceipt] = await Promise.all([
3524
+ driver.head.load(transaction, conversationId),
3525
+ driver.history.load(transaction, conversationId),
3526
+ driver.runs.listActive(transaction, conversationId),
3527
+ operationRunId ? driver.runs.load(transaction, { conversationId, runId: operationRunId }) : undefined,
3528
+ operation.type === "accept" ? driver.admissions.load(transaction, {
3529
+ conversationId,
3530
+ idempotencyKey: operation.input.idempotencyKey
3531
+ }) : undefined
3532
+ ]);
3533
+ const head = AgentRuntimeHeadSchema2.parse(stored ?? emptyHead(conversationId));
3534
+ const referencedRecords = await driver.runs.loadMany(transaction, {
3535
+ conversationId,
3536
+ runIds: referencedRunIds(messages)
3537
+ });
3538
+ const records = mergeRunRecords(activeRecords, referencedRecords, operationRecord ? [operationRecord] : []);
3539
+ const current = snapshotOf(head, messages, records);
3540
+ return { conversationId, head, messages, records, current, duplicateReceipt };
3541
+ }
3542
+ async function settledSeed(driver, transaction, read, input) {
3543
+ const { conversationId, current } = read;
3544
+ const existing = await driver.seeds.load(transaction, {
3545
+ conversationId,
3546
+ seedKey: input.seedKey
3547
+ });
3548
+ if (existing)
3549
+ return { outcome: "applied", snapshot: current };
3550
+ let collisions = 0;
3551
+ for (const message of input.inputs) {
3552
+ if (current.messages.some((candidate) => candidate.id === message.id) || await driver.history.hasMessage(transaction, {
3553
+ conversationId,
3554
+ messageId: message.id
3555
+ }))
3556
+ collisions++;
3557
+ }
3558
+ if (collisions > 0 && collisions < input.inputs.length) {
3559
+ throw new TypeError("Partial instruction seed collision: restore the complete seed before retrying");
3560
+ }
3561
+ if (collisions > 0) {
3562
+ await driver.seeds.create(transaction, AgentSeedReceiptSchema2.parse({
3563
+ schemaVersion: 1,
3564
+ conversationId,
3565
+ seedKey: input.seedKey,
3566
+ messageIds: input.inputs.map((message) => message.id)
3567
+ }));
3568
+ return { outcome: "applied", snapshot: current };
3569
+ }
3570
+ return;
3571
+ }
3572
+ async function duplicateAdmission(driver, transaction, read, duplicateReceipt) {
3573
+ const { conversationId, head, messages, records } = read;
3574
+ const duplicateRecord = await driver.runs.load(transaction, {
3575
+ conversationId,
3576
+ runId: duplicateReceipt.runId
3577
+ });
3578
+ if (!duplicateRecord) {
3579
+ throw new TypeError("Admission receipt points to a missing canonical run");
3580
+ }
3581
+ validateAdmissionReceipt(duplicateReceipt, duplicateRecord, conversationId);
3582
+ const answering = duplicateRecord.run.absorbedIntoRunId ? await driver.runs.load(transaction, {
3583
+ conversationId,
3584
+ runId: duplicateRecord.run.absorbedIntoRunId
3585
+ }) : undefined;
3586
+ if (duplicateRecord.run.absorbedIntoRunId && !answering) {
3587
+ throw new TypeError("Absorbed run points to a missing absorbing run");
3588
+ }
3589
+ const canonical = answering ?? duplicateRecord;
3590
+ return {
3591
+ outcome: "duplicate",
3592
+ input: duplicateReceipt.input,
3593
+ inputMessageId: duplicateReceipt.input.id,
3594
+ runId: canonical.run.id,
3595
+ assistantMessageId: canonical.run.assistantMessageId,
3596
+ run: canonical.run,
3597
+ ...canonical.terminalAssistant && {
3598
+ assistant: canonical.terminalAssistant
3599
+ },
3600
+ snapshot: snapshotOf(head, messages, mergeRunRecords(records, [duplicateRecord], answering ? [answering] : []))
3601
+ };
3602
+ }
3603
+ async function assertAdmissionIdentitiesFree(driver, transaction, conversationId, input) {
3604
+ const inputCollision = await driver.admissions.loadByInputMessageId(transaction, {
3605
+ conversationId,
3606
+ inputMessageId: input.input.id
3607
+ });
3608
+ if (inputCollision) {
3609
+ throw new TypeError("Input message identity is already assigned to an admission");
3610
+ }
3611
+ if (!input.coalesceIntoRunId) {
3612
+ const [runCollision, assistantCollision] = await Promise.all([
3613
+ driver.runs.load(transaction, {
3614
+ conversationId,
3615
+ runId: input.run.id
3616
+ }),
3617
+ driver.runs.loadByAssistantMessageId(transaction, {
3618
+ conversationId,
3619
+ assistantMessageId: input.run.assistantMessageId
3620
+ })
3621
+ ]);
3622
+ if (runCollision || assistantCollision) {
3623
+ throw new TypeError("Queued run identities are already reserved");
3624
+ }
3625
+ }
3626
+ }
3627
+ async function persistApplied(driver, transaction, read, operation, reduced) {
3628
+ const { conversationId, current } = read;
3629
+ const nextHead = AgentRuntimeHeadSchema2.parse({
3630
+ schemaVersion: 1,
3631
+ conversationId,
3632
+ version: reduced.snapshot.version
3633
+ });
3634
+ const outcome = await driver.head.compareAndSwap(transaction, {
3635
+ conversationId,
3636
+ expectedVersion: current.version,
3637
+ next: nextHead
3638
+ });
3639
+ if (outcome.outcome === "conflict")
3640
+ return conflict(outcome.actualVersion);
3641
+ for (const record of reduced.runRecords ?? []) {
3642
+ await driver.runs.save(transaction, record);
3643
+ }
3644
+ if (reduced.admissionReceipt) {
3645
+ await driver.admissions.create(transaction, reduced.admissionReceipt);
3646
+ }
3647
+ if (reduced.seedReceipt) {
3648
+ await driver.seeds.create(transaction, reduced.seedReceipt);
3649
+ }
3650
+ for (const mutation of reduced.historyMutations ?? []) {
3651
+ await driver.history.apply(transaction, mutation);
3652
+ }
3653
+ await driver.events.append(transaction, agentStoreEventDraft({
3654
+ conversationId,
3655
+ kind: "runtime/transition",
3656
+ payload: z24.json().parse(transitionRecord(operation, reduced))
3657
+ }));
3658
+ return { outcome: "applied", snapshot: reduced.snapshot };
3659
+ }
3660
+ function mutateStore(driver, operation) {
3661
+ return driver.transaction(async (transaction) => {
3662
+ const read = await readForMutation(driver, transaction, operation);
3663
+ if (operation.type === "seed") {
3664
+ const settled = await settledSeed(driver, transaction, read, operation.input);
3665
+ if (settled)
3666
+ return settled;
3667
+ }
3668
+ if (read.duplicateReceipt) {
3669
+ return duplicateAdmission(driver, transaction, read, read.duplicateReceipt);
3670
+ }
3671
+ if (operation.type === "accept") {
3672
+ await assertAdmissionIdentitiesFree(driver, transaction, read.conversationId, operation.input);
3673
+ }
3674
+ const reduced = reduceStore(read.current, operation);
3675
+ if (reduced.outcome !== "applied")
3676
+ return reduced;
3677
+ return persistApplied(driver, transaction, read, operation, reduced);
3678
+ });
3679
+ }
3680
+
3681
+ // src/agent-runtime/stores/store-purge.ts
3682
+ function createStoreConversationPurge(driver, conversations) {
3683
+ return async (input) => {
3684
+ const { conversationId, expectedVersion } = AgentConversationPurgeInputSchema2.parse(input);
3685
+ return driver.transaction(async (transaction) => {
3686
+ if (await conversations.isPurged(transaction, conversationId)) {
3687
+ return { outcome: "already_purged" };
3688
+ }
3689
+ const head = await driver.head.load(transaction, conversationId);
3690
+ const actualVersion = head?.version ?? 0;
3691
+ if (expectedVersion !== undefined && expectedVersion !== actualVersion) {
3692
+ return { outcome: "conflict", actualVersion };
3693
+ }
3694
+ const active = await driver.runs.listActive(transaction, conversationId);
3695
+ if (active.length > 0) {
3696
+ return { outcome: "active", runIds: active.map((record) => record.run.id) };
3697
+ }
3698
+ await conversations.remove(transaction, conversationId);
3699
+ return { outcome: "purged" };
3700
+ });
3701
+ };
3702
+ }
3703
+
3704
+ // src/agent-runtime/stores/store-create.ts
3705
+ var AgentRecoverableScanInputSchema = z25.object({
3706
+ cursor: z25.string().min(1).optional(),
3707
+ limit: z25.number().int().min(1).max(1000)
3708
+ });
3709
+ function createAgentRuntimeStore2(driver) {
3710
+ const capabilities = driverCapabilities(driver);
3711
+ const mutate = (operation) => mutateStore(driver, operation);
3712
+ return {
3713
+ capabilities,
3714
+ branchConversation: (input) => branchConversation(driver, input),
3715
+ planConversationBranch: (input) => planConversationBranch(driver, input),
3716
+ loadSnapshot: (conversationId) => loadSnapshot(driver, conversationId),
3717
+ loadRun: (input) => loadRun(driver, input),
3718
+ listActiveRuns: (conversationId) => listActiveRuns(driver, conversationId),
3719
+ appendEventOnce: (input, key) => appendEventOnce(driver, input, key),
3720
+ findEventOnce: (input) => findEventOnce(driver, input),
3721
+ appendEvent: (input) => appendEvent(driver, input),
3722
+ readEvents: (input) => readEvents(driver, input),
3723
+ exportConversation: (conversationId) => exportConversation(driver, conversationId),
3724
+ importConversation: (bytes) => importConversation(driver, bytes),
3725
+ ...driver.conversations && {
3726
+ purgeConversation: createStoreConversationPurge(driver, driver.conversations)
3727
+ },
3728
+ ...driver.events.redactExpiredPayloads && {
3729
+ async purgeExpiredPayloads(rawInput) {
3730
+ const parsed = PurgeInvocationPayloadsInputSchema2.parse(rawInput);
3731
+ const redact = driver.events.redactExpiredPayloads;
3732
+ if (!redact)
3733
+ throw new TypeError("Agent runtime store does not support payload purge");
3734
+ const before = new Date(Date.parse(parsed.before)).toISOString();
3735
+ const expiredAt = new Date().toISOString();
3736
+ const result = await driver.transaction((tx) => redact(tx, {
3737
+ before,
3738
+ expiredAt,
3739
+ ...parsed.conversationId !== undefined && {
3740
+ conversationId: parsed.conversationId
3741
+ },
3742
+ limit: parsed.limit ?? 1000
3743
+ }));
3744
+ return PurgeInvocationPayloadsResultSchema2.parse(result);
3745
+ }
3746
+ },
3747
+ acceptInputAndAssignRun: (input) => mutate({
3748
+ type: "accept",
3749
+ input: AcceptInputAndAssignRunSchema2.parse(input)
3750
+ }),
3751
+ acquireRun: (input) => mutate({ type: "acquire", input: AcquireAgentRunSchema2.parse(input) }),
3752
+ checkpointRunAssistant: (input) => mutate({
3753
+ type: "checkpoint",
3754
+ input: CheckpointRunAssistantSchema2.parse(input)
3755
+ }),
3756
+ recordRunOperation: (input) => mutate({
3757
+ type: "operation",
3758
+ input: RecordRunOperationSchema2.parse(input)
3759
+ }),
3760
+ requestRunInterrupt: (input) => mutate({
3761
+ type: "interrupt",
3762
+ input: RequestRunInterruptSchema2.parse(input)
3763
+ }),
3764
+ recoverRun: (input) => mutate({ type: "recover", input: RecoverAgentRunSchema2.parse(input) }),
3765
+ commitRunTerminal: (input) => mutate({ type: "terminal", input: CommitRunTerminalSchema2.parse(input) }),
3766
+ replaceCompactedRange: (input) => mutate({
3767
+ type: "compact",
3768
+ input: ReplaceCompactedRangeSchema2.parse(input)
3769
+ }),
3770
+ seedConversationInput: (input) => mutate({
3771
+ type: "seed",
3772
+ input: SeedConversationInputSchema2.parse(input)
3773
+ }),
3774
+ async scanRecoverable(input) {
3775
+ const parsed = AgentRecoverableScanInputSchema.parse(input);
3776
+ return AgentRecoverablePageSchema2.parse(await driver.scanRecoverable(parsed));
3777
+ }
3778
+ };
3779
+ }
3780
+
3781
+ export { DeferredAgentToolSearchInputSchema2, DeferredAgentToolMatchSchema2, DeferredAgentToolReceiptSchema2, defineAgentToolDescriptor, bindAgentTool, AgentBranchRefusalCodeSchema2, AgentBranchRefusalSchema2, AgentConversationBranchRefusedError2, BranchAgentConversationInputSchema2, AgentConversationBranchReceiptSchema2, AgentConversationBranchResultSchema2, AgentConversationBranchPlanSchema2, SqlIntegerSchema, HeadRowSchema, MessageRowSchema, PositionedMessageRowSchema, CountRowSchema, FlagSchema, EVENT_COLUMNS, parseJson, encodeJson, missing, placeholders, parseRunRow, parseEventRow, nextEventSeqByMaximum, AgentChildBudgetSchema2, AgentChildStateSchema2, AgentChildRecordSchema2, AgentChildBlockingKindSchema2, AgentChildBlockingSourceSchema2, AgentChildBlockingEventSchema2, ChildBlockingDecisionSchema, ChildSpawnedEventPayloadSchema, ChildStateEventPayloadSchema, parseChild, usageNumbers, AgentConversationPurgeInputSchema2, AgentConversationPurgeResultSchema2, AgentConversationPurgedError2, purgeAgentConversation2, agentSqlTables, isRetryablePostgresConflict, POSTGRES_ISOLATION, postgresSession, setPostgresTransactionIsolation, runPostgresTransaction, AgentEventSearchResultSchema2, createAgentEventSearch2, AGENT_EVENT_SEARCH_TOOL_DESCRIPTORS2, createAgentEventSearchTools2, AgentStoreUnsupportedCapabilityError2, ArchiveProjectionSchema, isRuntimeSnapshotEntry, replaceMessage, appendEventIn, ArchiveSpillSchema, createAgentRuntimeStore2 };