stitchkit 0.125.0 → 0.127.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (1249) hide show
  1. package/CHANGELOG.md +1707 -1
  2. package/README.md +12 -4
  3. package/dist/agent-executor/acp/scenarios.d.ts +4 -0
  4. package/dist/agent-executor/acp/scenarios.d.ts.map +1 -0
  5. package/dist/agent-executor/acp/v1-connect.d.ts +89 -0
  6. package/dist/agent-executor/acp/v1-connect.d.ts.map +1 -0
  7. package/dist/agent-executor/acp/v1-driver.d.ts +31 -0
  8. package/dist/agent-executor/acp/v1-driver.d.ts.map +1 -0
  9. package/dist/agent-executor/acp/v1-map.d.ts +41 -0
  10. package/dist/agent-executor/acp/v1-map.d.ts.map +1 -0
  11. package/dist/agent-executor/acp/v1-protocol.d.ts +270 -0
  12. package/dist/agent-executor/acp/v1-protocol.d.ts.map +1 -0
  13. package/dist/agent-executor/acp/v1-session.d.ts +22 -0
  14. package/dist/agent-executor/acp/v1-session.d.ts.map +1 -0
  15. package/dist/agent-executor/acp/v1-turn.d.ts +25 -0
  16. package/dist/agent-executor/acp/v1-turn.d.ts.map +1 -0
  17. package/dist/agent-executor/claude/classify.d.ts +54 -0
  18. package/dist/agent-executor/claude/classify.d.ts.map +1 -0
  19. package/dist/agent-executor/claude/cli-driver.d.ts +27 -0
  20. package/dist/agent-executor/claude/cli-driver.d.ts.map +1 -0
  21. package/dist/agent-executor/claude/limits.d.ts +8 -0
  22. package/dist/agent-executor/claude/limits.d.ts.map +1 -0
  23. package/dist/agent-executor/claude/protocol.d.ts +188 -0
  24. package/dist/agent-executor/claude/protocol.d.ts.map +1 -0
  25. package/dist/agent-executor/claude/scenarios.d.ts +4 -0
  26. package/dist/agent-executor/claude/scenarios.d.ts.map +1 -0
  27. package/dist/agent-executor/claude/session.d.ts +22 -0
  28. package/dist/agent-executor/claude/session.d.ts.map +1 -0
  29. package/dist/agent-executor/claude/transcript.d.ts +33 -0
  30. package/dist/agent-executor/claude/transcript.d.ts.map +1 -0
  31. package/dist/agent-executor/claude-sdk/driver.d.ts +31 -0
  32. package/dist/agent-executor/claude-sdk/driver.d.ts.map +1 -0
  33. package/dist/agent-executor/claude-sdk/session.d.ts +10 -0
  34. package/dist/agent-executor/claude-sdk/session.d.ts.map +1 -0
  35. package/dist/agent-executor/codex/classify.d.ts +28 -0
  36. package/dist/agent-executor/codex/classify.d.ts.map +1 -0
  37. package/dist/agent-executor/codex/driver.d.ts +23 -0
  38. package/dist/agent-executor/codex/driver.d.ts.map +1 -0
  39. package/dist/agent-executor/codex/limits.d.ts +4 -0
  40. package/dist/agent-executor/codex/limits.d.ts.map +1 -0
  41. package/dist/agent-executor/codex/protocol.d.ts +152 -0
  42. package/dist/agent-executor/codex/protocol.d.ts.map +1 -0
  43. package/dist/agent-executor/codex/scenarios.d.ts +4 -0
  44. package/dist/agent-executor/codex/scenarios.d.ts.map +1 -0
  45. package/dist/agent-executor/codex/session.d.ts +41 -0
  46. package/dist/agent-executor/codex/session.d.ts.map +1 -0
  47. package/dist/agent-executor/contract.d.ts +454 -0
  48. package/dist/agent-executor/contract.d.ts.map +1 -0
  49. package/dist/agent-executor/dispatch.d.ts +41 -0
  50. package/dist/agent-executor/dispatch.d.ts.map +1 -0
  51. package/dist/agent-executor/engine-process.d.ts +45 -0
  52. package/dist/agent-executor/engine-process.d.ts.map +1 -0
  53. package/dist/agent-executor/engine-requests.d.ts +63 -0
  54. package/dist/agent-executor/engine-requests.d.ts.map +1 -0
  55. package/dist/agent-executor/engine.d.ts +64 -0
  56. package/dist/agent-executor/engine.d.ts.map +1 -0
  57. package/dist/agent-executor/executor-contract.d.ts +387 -0
  58. package/dist/agent-executor/executor-contract.d.ts.map +1 -0
  59. package/dist/agent-executor/executor-machine.d.ts +50 -0
  60. package/dist/agent-executor/executor-machine.d.ts.map +1 -0
  61. package/dist/agent-executor/hello.d.ts +235 -0
  62. package/dist/agent-executor/hello.d.ts.map +1 -0
  63. package/dist/agent-executor/json-rpc-peer.d.ts +48 -0
  64. package/dist/agent-executor/json-rpc-peer.d.ts.map +1 -0
  65. package/dist/agent-executor/leases.d.ts +159 -0
  66. package/dist/agent-executor/leases.d.ts.map +1 -0
  67. package/dist/agent-executor/plan-limits.d.ts +25 -0
  68. package/dist/agent-executor/plan-limits.d.ts.map +1 -0
  69. package/dist/agent-executor/profile.d.ts +52 -0
  70. package/dist/agent-executor/profile.d.ts.map +1 -0
  71. package/dist/agent-executor/projection.d.ts +14 -0
  72. package/dist/agent-executor/projection.d.ts.map +1 -0
  73. package/dist/agent-executor/session-primitives.d.ts +72 -0
  74. package/dist/agent-executor/session-primitives.d.ts.map +1 -0
  75. package/dist/agent-executor/testing/conformance.d.ts +55 -0
  76. package/dist/agent-executor/testing/conformance.d.ts.map +1 -0
  77. package/dist/agent-executor/testing/fake-claude-engine.d.ts +18 -0
  78. package/dist/agent-executor/testing/fake-claude-engine.d.ts.map +1 -0
  79. package/dist/agent-executor/testing/fake-engine.d.ts +52 -0
  80. package/dist/agent-executor/testing/fake-engine.d.ts.map +1 -0
  81. package/dist/agent-executor/turn-phases.d.ts +10 -0
  82. package/dist/agent-executor/turn-phases.d.ts.map +1 -0
  83. package/dist/agent-executor/vocabulary.d.ts +353 -0
  84. package/dist/agent-executor/vocabulary.d.ts.map +1 -0
  85. package/dist/agent-parts/parts.d.ts +160 -0
  86. package/dist/agent-parts/parts.d.ts.map +1 -0
  87. package/dist/agent-runtime/agent-tool.d.ts +1 -1
  88. package/dist/agent-runtime/agent-tool.d.ts.map +1 -1
  89. package/dist/agent-runtime/archive-projection.d.ts +5 -0
  90. package/dist/agent-runtime/archive-projection.d.ts.map +1 -1
  91. package/dist/agent-runtime/branch-contract.d.ts +63 -1
  92. package/dist/agent-runtime/branch-contract.d.ts.map +1 -1
  93. package/dist/agent-runtime/branch-events.d.ts +7 -0
  94. package/dist/agent-runtime/branch-events.d.ts.map +1 -1
  95. package/dist/agent-runtime/branch-identities.d.ts +53 -1
  96. package/dist/agent-runtime/branch-identities.d.ts.map +1 -1
  97. package/dist/agent-runtime/branch-messages.d.ts +15 -26
  98. package/dist/agent-runtime/branch-messages.d.ts.map +1 -1
  99. package/dist/agent-runtime/branch-observations.d.ts +138 -28
  100. package/dist/agent-runtime/branch-observations.d.ts.map +1 -1
  101. package/dist/agent-runtime/branch-provider.d.ts +32 -51
  102. package/dist/agent-runtime/branch-provider.d.ts.map +1 -1
  103. package/dist/agent-runtime/branch-refusal.d.ts +60 -0
  104. package/dist/agent-runtime/branch-refusal.d.ts.map +1 -0
  105. package/dist/agent-runtime/branch-runtime-tools.d.ts +14 -0
  106. package/dist/agent-runtime/branch-runtime-tools.d.ts.map +1 -0
  107. package/dist/agent-runtime/branch-source.d.ts +7 -2
  108. package/dist/agent-runtime/branch-source.d.ts.map +1 -1
  109. package/dist/agent-runtime/branch-transitions.d.ts.map +1 -1
  110. package/dist/agent-runtime/browser-control-contract.d.ts +2 -2
  111. package/dist/agent-runtime/browser-controller.d.ts.map +1 -1
  112. package/dist/agent-runtime/child-blocking.d.ts +17 -6
  113. package/dist/agent-runtime/child-blocking.d.ts.map +1 -1
  114. package/dist/agent-runtime/child-budget-policy.d.ts +4 -9
  115. package/dist/agent-runtime/child-budget-policy.d.ts.map +1 -1
  116. package/dist/agent-runtime/child-tools.d.ts +19 -8
  117. package/dist/agent-runtime/child-tools.d.ts.map +1 -1
  118. package/dist/agent-runtime/children-contract.d.ts +84 -3
  119. package/dist/agent-runtime/children-contract.d.ts.map +1 -1
  120. package/dist/agent-runtime/children-control.d.ts +23 -2
  121. package/dist/agent-runtime/children-control.d.ts.map +1 -1
  122. package/dist/agent-runtime/children-spawn.d.ts +9 -0
  123. package/dist/agent-runtime/children-spawn.d.ts.map +1 -1
  124. package/dist/agent-runtime/children-state.d.ts +121 -19
  125. package/dist/agent-runtime/children-state.d.ts.map +1 -1
  126. package/dist/agent-runtime/children-usage.d.ts +10 -1
  127. package/dist/agent-runtime/children-usage.d.ts.map +1 -1
  128. package/dist/agent-runtime/children.d.ts +3 -3
  129. package/dist/agent-runtime/children.d.ts.map +1 -1
  130. package/dist/agent-runtime/{sandbox-coding.d.ts → coding-sandbox.d.ts} +2 -9
  131. package/dist/agent-runtime/coding-sandbox.d.ts.map +1 -0
  132. package/dist/agent-runtime/coding-shell-process.d.ts +2 -0
  133. package/dist/agent-runtime/coding-shell-process.d.ts.map +1 -1
  134. package/dist/agent-runtime/coding-tool-contract.d.ts +32 -1
  135. package/dist/agent-runtime/coding-tool-contract.d.ts.map +1 -1
  136. package/dist/agent-runtime/coding-tool-shell.d.ts.map +1 -1
  137. package/dist/agent-runtime/coding-tools.d.ts.map +1 -1
  138. package/dist/agent-runtime/compaction.d.ts.map +1 -1
  139. package/dist/agent-runtime/companion-host.d.ts +38 -0
  140. package/dist/agent-runtime/companion-host.d.ts.map +1 -0
  141. package/dist/agent-runtime/context-issue.d.ts +5 -0
  142. package/dist/agent-runtime/context-issue.d.ts.map +1 -0
  143. package/dist/agent-runtime/control-schema.d.ts +2 -2
  144. package/dist/agent-runtime/control-schema.d.ts.map +1 -1
  145. package/dist/agent-runtime/conversations.d.ts.map +1 -1
  146. package/dist/agent-runtime/coordinator.d.ts.map +1 -1
  147. package/dist/agent-runtime/deferred-tool-types.d.ts +17 -5
  148. package/dist/agent-runtime/deferred-tool-types.d.ts.map +1 -1
  149. package/dist/agent-runtime/deferred-tools-internal.d.ts +2 -0
  150. package/dist/agent-runtime/deferred-tools-internal.d.ts.map +1 -1
  151. package/dist/agent-runtime/deferred-tools.d.ts.map +1 -1
  152. package/dist/agent-runtime/event-durability.d.ts +8 -0
  153. package/dist/agent-runtime/event-durability.d.ts.map +1 -0
  154. package/dist/agent-runtime/event-schema.d.ts +13 -5
  155. package/dist/agent-runtime/event-schema.d.ts.map +1 -1
  156. package/dist/agent-runtime/event-search-postgres.d.ts +38 -0
  157. package/dist/agent-runtime/event-search-postgres.d.ts.map +1 -0
  158. package/dist/agent-runtime/event-search-terms.d.ts +37 -0
  159. package/dist/agent-runtime/event-search-terms.d.ts.map +1 -0
  160. package/dist/agent-runtime/event-search-tools.d.ts +64 -4
  161. package/dist/agent-runtime/event-search-tools.d.ts.map +1 -1
  162. package/dist/agent-runtime/event-search.d.ts +16 -3
  163. package/dist/agent-runtime/event-search.d.ts.map +1 -1
  164. package/dist/agent-runtime/fault-bench.d.ts.map +1 -1
  165. package/dist/agent-runtime/harness-control.d.ts +8 -0
  166. package/dist/agent-runtime/harness-control.d.ts.map +1 -1
  167. package/dist/agent-runtime/harness-realtime.d.ts +0 -2
  168. package/dist/agent-runtime/harness-realtime.d.ts.map +1 -1
  169. package/dist/agent-runtime/invocation-read.d.ts.map +1 -1
  170. package/dist/agent-runtime/invocation-schema.d.ts +23 -0
  171. package/dist/agent-runtime/invocation-schema.d.ts.map +1 -1
  172. package/dist/agent-runtime/invocation-spend.d.ts +9 -0
  173. package/dist/agent-runtime/invocation-spend.d.ts.map +1 -0
  174. package/dist/agent-runtime/invocations.d.ts.map +1 -1
  175. package/dist/agent-runtime/managed-tools.d.ts +2 -2
  176. package/dist/agent-runtime/managed-tools.d.ts.map +1 -1
  177. package/dist/agent-runtime/observability.d.ts +42 -4
  178. package/dist/agent-runtime/observability.d.ts.map +1 -1
  179. package/dist/agent-runtime/openrouter-admission.d.ts +81 -0
  180. package/dist/agent-runtime/openrouter-admission.d.ts.map +1 -0
  181. package/dist/agent-runtime/openrouter-catalog.d.ts +83 -0
  182. package/dist/agent-runtime/openrouter-catalog.d.ts.map +1 -0
  183. package/dist/agent-runtime/openrouter-models.d.ts +66 -0
  184. package/dist/agent-runtime/openrouter-models.d.ts.map +1 -0
  185. package/dist/agent-runtime/openrouter-options.d.ts +106 -0
  186. package/dist/agent-runtime/openrouter-options.d.ts.map +1 -0
  187. package/dist/agent-runtime/openrouter-route.d.ts +50 -0
  188. package/dist/agent-runtime/openrouter-route.d.ts.map +1 -0
  189. package/dist/agent-runtime/openrouter-spend.d.ts +24 -0
  190. package/dist/agent-runtime/openrouter-spend.d.ts.map +1 -0
  191. package/dist/agent-runtime/openrouter.d.ts +23 -2
  192. package/dist/agent-runtime/openrouter.d.ts.map +1 -1
  193. package/dist/agent-runtime/owned-provider-stream.d.ts.map +1 -1
  194. package/dist/agent-runtime/postgres-schema.d.ts +34 -0
  195. package/dist/agent-runtime/postgres-schema.d.ts.map +1 -0
  196. package/dist/agent-runtime/postgres-transactions.d.ts +54 -0
  197. package/dist/agent-runtime/postgres-transactions.d.ts.map +1 -0
  198. package/dist/agent-runtime/postgres.d.ts +72 -0
  199. package/dist/agent-runtime/postgres.d.ts.map +1 -0
  200. package/dist/agent-runtime/projections.d.ts +57 -17
  201. package/dist/agent-runtime/projections.d.ts.map +1 -1
  202. package/dist/agent-runtime/provider-journal.d.ts +57 -0
  203. package/dist/agent-runtime/provider-journal.d.ts.map +1 -1
  204. package/dist/agent-runtime/purge.d.ts.map +1 -1
  205. package/dist/agent-runtime/retry-policy.d.ts +6 -0
  206. package/dist/agent-runtime/retry-policy.d.ts.map +1 -1
  207. package/dist/agent-runtime/run-acquisition.d.ts.map +1 -1
  208. package/dist/agent-runtime/run-execution-state.d.ts +26 -2
  209. package/dist/agent-runtime/run-execution-state.d.ts.map +1 -1
  210. package/dist/agent-runtime/run-execution.d.ts.map +1 -1
  211. package/dist/agent-runtime/run-failure.d.ts.map +1 -1
  212. package/dist/agent-runtime/run-model-attempts.d.ts.map +1 -1
  213. package/dist/agent-runtime/run-provider-ledger.d.ts +2 -0
  214. package/dist/agent-runtime/run-provider-ledger.d.ts.map +1 -1
  215. package/dist/agent-runtime/run-step-barriers.d.ts +72 -0
  216. package/dist/agent-runtime/run-step-barriers.d.ts.map +1 -0
  217. package/dist/agent-runtime/run-step-spend.d.ts +319 -0
  218. package/dist/agent-runtime/run-step-spend.d.ts.map +1 -0
  219. package/dist/agent-runtime/run-stream-parts.d.ts +2 -0
  220. package/dist/agent-runtime/run-stream-parts.d.ts.map +1 -1
  221. package/dist/agent-runtime/{tool-progress.d.ts → run-tool-progress.d.ts} +1 -1
  222. package/dist/agent-runtime/run-tool-progress.d.ts.map +1 -0
  223. package/dist/agent-runtime/run-turn-preparation.d.ts +3 -1
  224. package/dist/agent-runtime/run-turn-preparation.d.ts.map +1 -1
  225. package/dist/agent-runtime/runtime-admission-gate.d.ts +0 -14
  226. package/dist/agent-runtime/runtime-admission-gate.d.ts.map +1 -1
  227. package/dist/agent-runtime/runtime-internals.d.ts +6 -0
  228. package/dist/agent-runtime/runtime-internals.d.ts.map +1 -1
  229. package/dist/agent-runtime/runtime-state.d.ts.map +1 -1
  230. package/dist/agent-runtime/runtime.d.ts +31 -2
  231. package/dist/agent-runtime/runtime.d.ts.map +1 -1
  232. package/dist/agent-runtime/sandbox-binding.d.ts +10 -0
  233. package/dist/agent-runtime/sandbox-binding.d.ts.map +1 -0
  234. package/dist/agent-runtime/sandbox-bubblewrap-storage.d.ts.map +1 -1
  235. package/dist/agent-runtime/sandbox-contract.d.ts +1 -1
  236. package/dist/agent-runtime/sandbox-contract.d.ts.map +1 -1
  237. package/dist/agent-runtime/sandbox.d.ts +5 -0
  238. package/dist/agent-runtime/sandbox.d.ts.map +1 -1
  239. package/dist/agent-runtime/schedule-contract.d.ts +3 -2
  240. package/dist/agent-runtime/schedule-contract.d.ts.map +1 -1
  241. package/dist/agent-runtime/schedule-dispatch.d.ts +3 -2
  242. package/dist/agent-runtime/schedule-dispatch.d.ts.map +1 -1
  243. package/dist/agent-runtime/schedule-records.d.ts +6 -6
  244. package/dist/agent-runtime/schedule-records.d.ts.map +1 -1
  245. package/dist/agent-runtime/schedule-tools.d.ts +19 -8
  246. package/dist/agent-runtime/schedule-tools.d.ts.map +1 -1
  247. package/dist/agent-runtime/schedules.d.ts +13 -3
  248. package/dist/agent-runtime/schedules.d.ts.map +1 -1
  249. package/dist/agent-runtime/schemas-message.d.ts +118 -0
  250. package/dist/agent-runtime/schemas-message.d.ts.map +1 -0
  251. package/dist/agent-runtime/schemas-provider.d.ts +8 -0
  252. package/dist/agent-runtime/schemas-provider.d.ts.map +1 -0
  253. package/dist/agent-runtime/schemas-records.d.ts +5 -0
  254. package/dist/agent-runtime/schemas-records.d.ts.map +1 -0
  255. package/dist/agent-runtime/schemas-run.d.ts +487 -0
  256. package/dist/agent-runtime/schemas-run.d.ts.map +1 -0
  257. package/dist/agent-runtime/schemas-usage.d.ts +129 -0
  258. package/dist/agent-runtime/schemas-usage.d.ts.map +1 -0
  259. package/dist/agent-runtime/schemas.d.ts +11 -886
  260. package/dist/agent-runtime/schemas.d.ts.map +1 -1
  261. package/dist/agent-runtime/spill.d.ts +9 -7
  262. package/dist/agent-runtime/spill.d.ts.map +1 -1
  263. package/dist/agent-runtime/sql-events.d.ts +6 -0
  264. package/dist/agent-runtime/sql-events.d.ts.map +1 -0
  265. package/dist/agent-runtime/sql-history.d.ts +8 -0
  266. package/dist/agent-runtime/sql-history.d.ts.map +1 -0
  267. package/dist/agent-runtime/sql-ledger.d.ts +5 -0
  268. package/dist/agent-runtime/sql-ledger.d.ts.map +1 -0
  269. package/dist/agent-runtime/sql-purge.d.ts +13 -0
  270. package/dist/agent-runtime/sql-purge.d.ts.map +1 -0
  271. package/dist/agent-runtime/sql-reads.d.ts +16 -0
  272. package/dist/agent-runtime/sql-reads.d.ts.map +1 -0
  273. package/dist/agent-runtime/{sqlite-rows.d.ts → sql-rows.d.ts} +24 -10
  274. package/dist/agent-runtime/sql-rows.d.ts.map +1 -0
  275. package/dist/agent-runtime/sql-session.d.ts +71 -0
  276. package/dist/agent-runtime/sql-session.d.ts.map +1 -0
  277. package/dist/agent-runtime/sqlite-bun.d.ts +1 -1
  278. package/dist/agent-runtime/sqlite-bun.d.ts.map +1 -1
  279. package/dist/agent-runtime/sqlite-node.d.ts +1 -1
  280. package/dist/agent-runtime/sqlite-node.d.ts.map +1 -1
  281. package/dist/agent-runtime/sqlite-purge.d.ts +2 -3
  282. package/dist/agent-runtime/sqlite-purge.d.ts.map +1 -1
  283. package/dist/agent-runtime/sqlite-schema.d.ts +1 -1
  284. package/dist/agent-runtime/sqlite-schema.d.ts.map +1 -1
  285. package/dist/agent-runtime/sqlite-transactions.d.ts +10 -6
  286. package/dist/agent-runtime/sqlite-transactions.d.ts.map +1 -1
  287. package/dist/agent-runtime/sqlite.d.ts +10 -29
  288. package/dist/agent-runtime/sqlite.d.ts.map +1 -1
  289. package/dist/agent-runtime/state-tools.d.ts +8 -4
  290. package/dist/agent-runtime/state-tools.d.ts.map +1 -1
  291. package/dist/agent-runtime/store-archive.d.ts.map +1 -1
  292. package/dist/agent-runtime/store-branch.d.ts +6 -1
  293. package/dist/agent-runtime/store-branch.d.ts.map +1 -1
  294. package/dist/agent-runtime/store-capabilities.d.ts +42 -0
  295. package/dist/agent-runtime/store-capabilities.d.ts.map +1 -0
  296. package/dist/agent-runtime/store-conformance-branch.d.ts +5 -2
  297. package/dist/agent-runtime/store-conformance-branch.d.ts.map +1 -1
  298. package/dist/agent-runtime/store-conformance-capabilities.d.ts +6 -0
  299. package/dist/agent-runtime/store-conformance-capabilities.d.ts.map +1 -0
  300. package/dist/agent-runtime/store-conformance-event-once.d.ts +12 -0
  301. package/dist/agent-runtime/store-conformance-event-once.d.ts.map +1 -0
  302. package/dist/agent-runtime/store-conformance-lifecycle.d.ts +20 -20
  303. package/dist/agent-runtime/store-conformance-seed.d.ts +8 -0
  304. package/dist/agent-runtime/store-conformance-seed.d.ts.map +1 -0
  305. package/dist/agent-runtime/store-conformance.d.ts +31 -8
  306. package/dist/agent-runtime/store-conformance.d.ts.map +1 -1
  307. package/dist/agent-runtime/store-create.d.ts +1 -1
  308. package/dist/agent-runtime/store-create.d.ts.map +1 -1
  309. package/dist/agent-runtime/store-driver-contract.d.ts +15 -8
  310. package/dist/agent-runtime/store-driver-contract.d.ts.map +1 -1
  311. package/dist/agent-runtime/store-event-once.d.ts.map +1 -1
  312. package/dist/agent-runtime/store-events.d.ts +114 -0
  313. package/dist/agent-runtime/store-events.d.ts.map +1 -1
  314. package/dist/agent-runtime/store-memory-archive.d.ts +2 -0
  315. package/dist/agent-runtime/store-memory-archive.d.ts.map +1 -1
  316. package/dist/agent-runtime/store-memory.d.ts +2 -2
  317. package/dist/agent-runtime/store-memory.d.ts.map +1 -1
  318. package/dist/agent-runtime/store-mutate.d.ts.map +1 -1
  319. package/dist/agent-runtime/store-reduce-shared.d.ts +2 -1
  320. package/dist/agent-runtime/store-reduce-shared.d.ts.map +1 -1
  321. package/dist/agent-runtime/store-reducer.d.ts.map +1 -1
  322. package/dist/agent-runtime/store-replay.d.ts.map +1 -1
  323. package/dist/agent-runtime/store.d.ts +15 -2
  324. package/dist/agent-runtime/store.d.ts.map +1 -1
  325. package/dist/agent-runtime/terminal-commit.d.ts +10 -10
  326. package/dist/application/admission-run.d.ts.map +1 -1
  327. package/dist/application/admission.d.ts.map +1 -1
  328. package/dist/application/change-subscription.d.ts.map +1 -1
  329. package/dist/application/decisions.d.ts.map +1 -1
  330. package/dist/application/diagnostic-journal-lock-format.d.ts +9 -0
  331. package/dist/application/diagnostic-journal-lock-format.d.ts.map +1 -0
  332. package/dist/application/diagnostic-journal-manager.d.ts.map +1 -1
  333. package/dist/application/directory-inbox-delivery.d.ts.map +1 -1
  334. package/dist/application/grammy-update-admission.d.ts.map +1 -1
  335. package/dist/application/health.d.ts.map +1 -1
  336. package/dist/application/kernel-admission.d.ts.map +1 -1
  337. package/dist/application/kernel-contract.d.ts.map +1 -1
  338. package/dist/application/kernel-restart.d.ts.map +1 -1
  339. package/dist/application/kernel-rollback.d.ts.map +1 -1
  340. package/dist/application/kernel-shutdown.d.ts.map +1 -1
  341. package/dist/application/kernel-state.d.ts.map +1 -1
  342. package/dist/application/notification-outbox-state.d.ts.map +1 -1
  343. package/dist/application/notification-outbox.d.ts +1 -1
  344. package/dist/application/notification-outbox.d.ts.map +1 -1
  345. package/dist/application/revision-signal.d.ts.map +1 -1
  346. package/dist/application/schedule-run.d.ts.map +1 -1
  347. package/dist/application/schedule.d.ts.map +1 -1
  348. package/dist/application/sqlite-migrations.d.ts +104 -0
  349. package/dist/application/sqlite-migrations.d.ts.map +1 -0
  350. package/dist/application/watch-hub-core.d.ts +2 -1
  351. package/dist/application/watch-hub-core.d.ts.map +1 -1
  352. package/dist/application/watch-hub-source.d.ts +2 -0
  353. package/dist/application/watch-hub-source.d.ts.map +1 -1
  354. package/dist/application/watch-hub.d.ts +20 -1
  355. package/dist/application/watch-hub.d.ts.map +1 -1
  356. package/dist/browser/bridge-errors.d.ts +24 -0
  357. package/dist/browser/bridge-errors.d.ts.map +1 -0
  358. package/dist/browser/bridge-fetch.d.ts +30 -0
  359. package/dist/browser/bridge-fetch.d.ts.map +1 -0
  360. package/dist/browser/bridge-inbound.d.ts +28 -0
  361. package/dist/browser/bridge-inbound.d.ts.map +1 -0
  362. package/dist/browser/cancellation.d.ts +10 -2
  363. package/dist/browser/cancellation.d.ts.map +1 -1
  364. package/dist/browser/chunked-upload.d.ts +1 -1
  365. package/dist/browser/chunked-upload.d.ts.map +1 -1
  366. package/dist/browser/client-call-arguments.d.ts +31 -0
  367. package/dist/browser/client-call-arguments.d.ts.map +1 -0
  368. package/dist/browser/client-executors.d.ts +6 -0
  369. package/dist/browser/client-executors.d.ts.map +1 -1
  370. package/dist/browser/client.d.ts +9 -0
  371. package/dist/browser/client.d.ts.map +1 -1
  372. package/dist/browser/http.d.ts +17 -2
  373. package/dist/browser/http.d.ts.map +1 -1
  374. package/dist/browser/realtime-client.d.ts +0 -5
  375. package/dist/browser/realtime-client.d.ts.map +1 -1
  376. package/dist/browser/session-credentials-storage.d.ts +48 -0
  377. package/dist/browser/session-credentials-storage.d.ts.map +1 -0
  378. package/dist/browser/session-credentials.d.ts +26 -5
  379. package/dist/browser/session-credentials.d.ts.map +1 -1
  380. package/dist/browser/session-refresh-policy.d.ts +124 -0
  381. package/dist/browser/session-refresh-policy.d.ts.map +1 -0
  382. package/dist/browser/session-refresh-timer.d.ts +30 -0
  383. package/dist/browser/session-refresh-timer.d.ts.map +1 -0
  384. package/dist/browser/session.d.ts.map +1 -1
  385. package/dist/browser/socket-io-connection.d.ts.map +1 -1
  386. package/dist/browser/socket-io-explicit-peer.d.ts +0 -1
  387. package/dist/browser/socket-io-explicit-peer.d.ts.map +1 -1
  388. package/dist/browser/stream.d.ts +1 -1
  389. package/dist/browser/stream.d.ts.map +1 -1
  390. package/dist/browser/upload-progress.d.ts +3 -0
  391. package/dist/browser/upload-progress.d.ts.map +1 -1
  392. package/dist/contract/bridge-envelope.d.ts +155 -0
  393. package/dist/contract/bridge-envelope.d.ts.map +1 -0
  394. package/dist/contract/define-validation.d.ts +2 -0
  395. package/dist/contract/define-validation.d.ts.map +1 -1
  396. package/dist/contract/define.d.ts +3 -0
  397. package/dist/contract/define.d.ts.map +1 -1
  398. package/dist/contract/errors.d.ts +4 -4
  399. package/dist/contract/errors.d.ts.map +1 -1
  400. package/dist/contract/normalize.d.ts +3 -1
  401. package/dist/contract/normalize.d.ts.map +1 -1
  402. package/dist/contract/operation-effect.d.ts +29 -0
  403. package/dist/contract/operation-effect.d.ts.map +1 -0
  404. package/dist/contract/runtime-context.d.ts +2 -0
  405. package/dist/contract/runtime-context.d.ts.map +1 -1
  406. package/dist/contract/tool-options.d.ts +7 -0
  407. package/dist/contract/tool-options.d.ts.map +1 -1
  408. package/dist/declaration/command.d.ts +26 -0
  409. package/dist/declaration/command.d.ts.map +1 -0
  410. package/dist/declaration/declaration.d.ts +4 -22
  411. package/dist/declaration/declaration.d.ts.map +1 -1
  412. package/dist/declaration/machine-names.d.ts +11 -0
  413. package/dist/declaration/machine-names.d.ts.map +1 -0
  414. package/dist/durability/effect.d.ts.map +1 -1
  415. package/dist/durability/engine.d.ts.map +1 -1
  416. package/dist/durability/events.d.ts +5 -8
  417. package/dist/durability/events.d.ts.map +1 -1
  418. package/dist/durability/parks.d.ts +0 -5
  419. package/dist/durability/parks.d.ts.map +1 -1
  420. package/dist/durability/scheduler.d.ts +5 -0
  421. package/dist/durability/scheduler.d.ts.map +1 -1
  422. package/dist/entrypoints/agent-executor/acp.d.ts +4 -0
  423. package/dist/entrypoints/agent-executor/acp.d.ts.map +1 -0
  424. package/dist/entrypoints/agent-executor/acp.js +910 -0
  425. package/dist/entrypoints/agent-executor/claude-sdk.d.ts +2 -0
  426. package/dist/entrypoints/agent-executor/claude-sdk.d.ts.map +1 -0
  427. package/dist/entrypoints/agent-executor/claude-sdk.js +309 -0
  428. package/dist/entrypoints/agent-executor/claude.d.ts +5 -0
  429. package/dist/entrypoints/agent-executor/claude.d.ts.map +1 -0
  430. package/dist/entrypoints/agent-executor/claude.js +403 -0
  431. package/dist/entrypoints/agent-executor/codex.d.ts +4 -0
  432. package/dist/entrypoints/agent-executor/codex.d.ts.map +1 -0
  433. package/dist/entrypoints/agent-executor/codex.js +798 -0
  434. package/dist/entrypoints/agent-executor/testing.d.ts +4 -0
  435. package/dist/entrypoints/agent-executor/testing.d.ts.map +1 -0
  436. package/dist/entrypoints/agent-executor/testing.js +375 -0
  437. package/dist/entrypoints/agent-executor.d.ts +15 -0
  438. package/dist/entrypoints/agent-executor.d.ts.map +1 -0
  439. package/dist/entrypoints/agent-executor.js +455 -0
  440. package/dist/entrypoints/agent-runtime/browser.d.ts +1 -0
  441. package/dist/entrypoints/agent-runtime/browser.d.ts.map +1 -1
  442. package/dist/entrypoints/agent-runtime/browser.js +60 -30
  443. package/dist/entrypoints/agent-runtime/coding-tools.js +9 -12
  444. package/dist/entrypoints/agent-runtime/harness.js +35 -22
  445. package/dist/entrypoints/agent-runtime/openrouter.d.ts +6 -0
  446. package/dist/entrypoints/agent-runtime/openrouter.d.ts.map +1 -1
  447. package/dist/entrypoints/agent-runtime/openrouter.js +675 -45
  448. package/dist/entrypoints/agent-runtime/postgres.d.ts +4 -0
  449. package/dist/entrypoints/agent-runtime/postgres.d.ts.map +1 -0
  450. package/dist/entrypoints/agent-runtime/postgres.js +330 -0
  451. package/dist/entrypoints/agent-runtime/realtime.js +46 -49
  452. package/dist/entrypoints/agent-runtime/sandbox.d.ts +3 -1
  453. package/dist/entrypoints/agent-runtime/sandbox.d.ts.map +1 -1
  454. package/dist/entrypoints/agent-runtime/sandbox.js +74 -67
  455. package/dist/entrypoints/agent-runtime/sqlite/bun.js +18 -18
  456. package/dist/entrypoints/agent-runtime/sqlite/node.js +18 -18
  457. package/dist/entrypoints/agent-runtime/testing.d.ts +1 -1
  458. package/dist/entrypoints/agent-runtime/testing.d.ts.map +1 -1
  459. package/dist/entrypoints/agent-runtime/testing.js +419 -96
  460. package/dist/entrypoints/agent-runtime.d.ts +21 -13
  461. package/dist/entrypoints/agent-runtime.d.ts.map +1 -1
  462. package/dist/entrypoints/agent-runtime.js +1280 -1086
  463. package/dist/entrypoints/application/diagnostic-journal.js +16 -11
  464. package/dist/entrypoints/application/directory-inbox.js +20 -14
  465. package/dist/entrypoints/application/grammy.js +11 -8
  466. package/dist/entrypoints/application/opentelemetry.js +3 -3
  467. package/dist/entrypoints/application.d.ts +5 -3
  468. package/dist/entrypoints/application.d.ts.map +1 -1
  469. package/dist/entrypoints/application.js +464 -116
  470. package/dist/entrypoints/bin/upgrade-cli.d.ts +0 -12
  471. package/dist/entrypoints/bin/upgrade-cli.d.ts.map +1 -1
  472. package/dist/entrypoints/bin/upgrade-cli.js +13 -7
  473. package/dist/entrypoints/cli/publish.js +10 -9
  474. package/dist/entrypoints/cli.d.ts +10 -3
  475. package/dist/entrypoints/cli.d.ts.map +1 -1
  476. package/dist/entrypoints/cli.js +91 -29
  477. package/dist/entrypoints/contract.d.ts +2 -1
  478. package/dist/entrypoints/contract.d.ts.map +1 -1
  479. package/dist/entrypoints/contract.js +13 -7
  480. package/dist/entrypoints/declaration.d.ts +2 -0
  481. package/dist/entrypoints/declaration.d.ts.map +1 -1
  482. package/dist/entrypoints/declaration.js +55 -44
  483. package/dist/entrypoints/files/packaging.js +8 -5
  484. package/dist/entrypoints/files.d.ts +5 -0
  485. package/dist/entrypoints/files.d.ts.map +1 -1
  486. package/dist/entrypoints/files.js +236 -47
  487. package/dist/entrypoints/geo.js +9 -4
  488. package/dist/entrypoints/google.js +14 -13
  489. package/dist/entrypoints/handler.d.ts +12 -0
  490. package/dist/entrypoints/handler.d.ts.map +1 -0
  491. package/dist/entrypoints/handler.js +350 -0
  492. package/dist/entrypoints/http.d.ts +4 -0
  493. package/dist/entrypoints/http.d.ts.map +1 -1
  494. package/dist/entrypoints/http.js +411 -5
  495. package/dist/entrypoints/index.d.ts +2 -0
  496. package/dist/entrypoints/index.d.ts.map +1 -1
  497. package/dist/entrypoints/index.js +664 -91
  498. package/dist/entrypoints/live.js +22 -12
  499. package/dist/entrypoints/node.d.ts +2 -1
  500. package/dist/entrypoints/node.d.ts.map +1 -1
  501. package/dist/entrypoints/node.js +34 -24
  502. package/dist/entrypoints/observability.d.ts +2 -0
  503. package/dist/entrypoints/observability.d.ts.map +1 -1
  504. package/dist/entrypoints/observability.js +205 -131
  505. package/dist/entrypoints/primitives.js +152 -14
  506. package/dist/entrypoints/process/owner-loss.js +2 -2
  507. package/dist/entrypoints/process.js +18 -92
  508. package/dist/entrypoints/react.js +6 -5
  509. package/dist/entrypoints/realtime.d.ts +1 -0
  510. package/dist/entrypoints/realtime.d.ts.map +1 -1
  511. package/dist/entrypoints/realtime.js +6 -3
  512. package/dist/entrypoints/release.js +4 -0
  513. package/dist/entrypoints/remote.js +7 -6
  514. package/dist/entrypoints/server.d.ts +4 -2
  515. package/dist/entrypoints/server.d.ts.map +1 -1
  516. package/dist/entrypoints/server.js +300 -199
  517. package/dist/entrypoints/service-host/macos.d.ts +16 -0
  518. package/dist/entrypoints/service-host/macos.d.ts.map +1 -0
  519. package/dist/entrypoints/service-host/macos.js +1998 -0
  520. package/dist/entrypoints/service-host.d.ts +23 -0
  521. package/dist/entrypoints/service-host.d.ts.map +1 -0
  522. package/dist/entrypoints/service-host.js +2544 -0
  523. package/dist/entrypoints/spend/testing.d.ts +2 -0
  524. package/dist/entrypoints/spend/testing.d.ts.map +1 -0
  525. package/dist/entrypoints/spend/testing.js +442 -0
  526. package/dist/entrypoints/spend.d.ts +8 -0
  527. package/dist/entrypoints/spend.d.ts.map +1 -0
  528. package/dist/entrypoints/spend.js +593 -0
  529. package/dist/entrypoints/sync/postgres.d.ts +12 -0
  530. package/dist/entrypoints/sync/postgres.d.ts.map +1 -0
  531. package/dist/entrypoints/sync/postgres.js +737 -0
  532. package/dist/entrypoints/sync.d.ts +12 -0
  533. package/dist/entrypoints/sync.d.ts.map +1 -0
  534. package/dist/entrypoints/sync.js +782 -0
  535. package/dist/entrypoints/telegram/grammy.js +5 -5
  536. package/dist/entrypoints/telegram/html.d.ts +2 -0
  537. package/dist/entrypoints/telegram/html.d.ts.map +1 -1
  538. package/dist/entrypoints/telegram/html.js +839 -2
  539. package/dist/entrypoints/telegram/screens.js +13 -15
  540. package/dist/entrypoints/telegram.d.ts +1 -1
  541. package/dist/entrypoints/telegram.d.ts.map +1 -1
  542. package/dist/entrypoints/telegram.js +286 -76
  543. package/dist/entrypoints/testing.js +33 -41
  544. package/dist/entrypoints/tools/agent.js +12 -9
  545. package/dist/entrypoints/tools/connections.js +664 -63
  546. package/dist/entrypoints/tools/contract.d.ts +2 -2
  547. package/dist/entrypoints/tools/contract.js +4 -1
  548. package/dist/entrypoints/tools/invoker.js +9 -7
  549. package/dist/entrypoints/tools/mcp.js +16 -11
  550. package/dist/entrypoints/tools/toolkit.js +21 -16
  551. package/dist/entrypoints/tools.d.ts +3 -1
  552. package/dist/entrypoints/tools.d.ts.map +1 -1
  553. package/dist/entrypoints/tools.js +107 -94
  554. package/dist/entrypoints/tracking/contract.js +2 -1
  555. package/dist/entrypoints/tracking/performance.js +4 -0
  556. package/dist/entrypoints/tracking.js +6 -1
  557. package/dist/entrypoints/voice.js +3 -3
  558. package/dist/entrypoints/xlsx.js +1 -1
  559. package/dist/files/boundary.d.ts.map +1 -1
  560. package/dist/files/chunk-spool.d.ts +27 -0
  561. package/dist/files/chunk-spool.d.ts.map +1 -1
  562. package/dist/files/directory-appearance.d.ts +44 -0
  563. package/dist/files/directory-appearance.d.ts.map +1 -0
  564. package/dist/files/file-io.d.ts.map +1 -1
  565. package/dist/files/file-stamp.d.ts +35 -0
  566. package/dist/files/file-stamp.d.ts.map +1 -0
  567. package/dist/files/json-file-reading.d.ts +37 -0
  568. package/dist/files/json-file-reading.d.ts.map +1 -0
  569. package/dist/files/native-packaging.d.ts.map +1 -1
  570. package/dist/files/polled-json.d.ts +121 -0
  571. package/dist/files/polled-json.d.ts.map +1 -0
  572. package/dist/files/regular-file.d.ts +125 -0
  573. package/dist/files/regular-file.d.ts.map +1 -0
  574. package/dist/geo/index.d.ts +2 -1
  575. package/dist/geo/index.d.ts.map +1 -1
  576. package/dist/geo/resolver.d.ts.map +1 -1
  577. package/dist/geo/types.d.ts +0 -1
  578. package/dist/geo/types.d.ts.map +1 -1
  579. package/dist/google/google.d.ts +6 -0
  580. package/dist/google/google.d.ts.map +1 -1
  581. package/dist/{index-w0eqdhyd.js → index-09f7w2qq.js} +6 -1
  582. package/dist/index-0djnptn8.js +501 -0
  583. package/dist/index-0hdm5sx6.js +1457 -0
  584. package/dist/{index-t05a2ry4.js → index-0p0s5hrj.js} +8 -14
  585. package/dist/{index-1c945ten.js → index-0r15pkjq.js} +1 -1
  586. package/dist/{index-v1swr26p.js → index-0tyt97nk.js} +2 -2
  587. package/dist/{index-332d0m9g.js → index-0x4mnwg5.js} +4 -0
  588. package/dist/index-118aebbg.js +48 -0
  589. package/dist/index-1q0n6zek.js +184 -0
  590. package/dist/index-27hck3z2.js +307 -0
  591. package/dist/index-2rf33y2h.js +77 -0
  592. package/dist/index-360j58vb.js +63 -0
  593. package/dist/{index-tt30h7mr.js → index-39n02e0q.js} +1 -1
  594. package/dist/index-3agqmmrg.js +42 -0
  595. package/dist/{index-n6hvd1r2.js → index-3b31z0pc.js} +22 -15
  596. package/dist/index-3djgv3ch.js +472 -0
  597. package/dist/{index-mfntvj58.js → index-3dq8466w.js} +1 -1
  598. package/dist/index-3gwp8ez6.js +200 -0
  599. package/dist/{index-x2d51zay.js → index-3ypvpkwr.js} +309 -345
  600. package/dist/index-4gk6k3zc.js +248 -0
  601. package/dist/index-4qvyhn23.js +40 -0
  602. package/dist/index-4s2w4g37.js +647 -0
  603. package/dist/index-4ynw5ktx.js +78 -0
  604. package/dist/index-5awtbyns.js +19 -0
  605. package/dist/{index-kxff9e9w.js → index-5e0zsbf7.js} +5 -4
  606. package/dist/{index-nz06qw5a.js → index-5jyjb4s0.js} +1 -1
  607. package/dist/{index-7q05ag0z.js → index-5ptwb6ka.js} +1 -1
  608. package/dist/{index-w3nv6kr8.js → index-5q0qpw3v.js} +54 -9
  609. package/dist/{index-mm89hd8v.js → index-5t4fpdct.js} +1 -1
  610. package/dist/{index-0v9xb8pz.js → index-5y7j383h.js} +5 -5
  611. package/dist/index-5zwac8ft.js +221 -0
  612. package/dist/{index-v62cpkx3.js → index-6g85s734.js} +1 -1
  613. package/dist/{index-sqc6ezrb.js → index-6kec3b14.js} +17 -4
  614. package/dist/{index-kqnd6a85.js → index-7416mhyh.js} +1 -1
  615. package/dist/{index-m0wsfmrc.js → index-7csn6pva.js} +37 -24
  616. package/dist/{index-dqpesdck.js → index-7grgs8cx.js} +25 -5
  617. package/dist/{index-gdqawggb.js → index-7kfcb576.js} +143 -39
  618. package/dist/{index-cvjddnvd.js → index-7xp05h20.js} +19 -10
  619. package/dist/{index-fgzbc06j.js → index-83n766x4.js} +91 -50
  620. package/dist/{index-ss67fxhj.js → index-877e9y8r.js} +7 -7
  621. package/dist/{index-aw6kx2e6.js → index-8gmmdz7k.js} +1 -1
  622. package/dist/{index-wt6rw7rf.js → index-8xr2eq99.js} +29 -21
  623. package/dist/{index-rz3z13e9.js → index-97q9kykw.js} +1 -1
  624. package/dist/index-97rp94ff.js +8 -0
  625. package/dist/{index-0w0hxp7n.js → index-9pv126eh.js} +3 -9
  626. package/dist/{index-x2rvpbtj.js → index-9wh98cpa.js} +110 -16
  627. package/dist/{index-egg0yp2j.js → index-9xr44d2g.js} +86 -210
  628. package/dist/{index-b2sey031.js → index-9y0afd5f.js} +24 -23
  629. package/dist/index-a725ayvz.js +405 -0
  630. package/dist/{index-nmaqxdx7.js → index-ac5rj3d4.js} +203 -90
  631. package/dist/{index-wqzw3qg9.js → index-agy5fqgf.js} +32 -13
  632. package/dist/index-ajmtxsky.js +193 -0
  633. package/dist/{index-ndjzbt2v.js → index-akf0xkrm.js} +4 -3
  634. package/dist/index-akfgymyr.js +8 -0
  635. package/dist/index-apv5xfef.js +13 -0
  636. package/dist/index-ax3wns1a.js +93 -0
  637. package/dist/{index-0sg3wnzr.js → index-bbzvrq66.js} +1670 -340
  638. package/dist/index-bh4pmtr9.js +317 -0
  639. package/dist/{index-fa53vygr.js → index-bmaz3jzy.js} +3 -3
  640. package/dist/{index-8kzct1d6.js → index-bn2baakz.js} +143 -143
  641. package/dist/{index-m8ddk770.js → index-brhhaygm.js} +1 -1
  642. package/dist/index-caywx1c0.js +199 -0
  643. package/dist/index-cbhxhma2.js +90 -0
  644. package/dist/index-cfnmvcq8.js +11 -0
  645. package/dist/index-cv9b7fz2.js +42 -0
  646. package/dist/index-d4svrknj.js +156 -0
  647. package/dist/{index-a3z56mtn.js → index-d96c1n1q.js} +5 -3
  648. package/dist/{index-3ymcmpa9.js → index-dvd1qdwa.js} +33 -163
  649. package/dist/{index-v7rbjatr.js → index-dwa6pskj.js} +1837 -1151
  650. package/dist/{index-ne4j9998.js → index-e06z0tkb.js} +123 -94
  651. package/dist/{index-99nnsz39.js → index-en8e5zsj.js} +15 -135
  652. package/dist/index-fcw255hd.js +929 -0
  653. package/dist/{index-20hn8pbh.js → index-fmzg39a8.js} +1 -1
  654. package/dist/{index-fvd6pvw3.js → index-g1q7fwn9.js} +2 -2
  655. package/dist/index-g56ht6qf.js +98 -0
  656. package/dist/{index-f56ct5gb.js → index-gj1rjf78.js} +4 -3
  657. package/dist/{index-g6a3na27.js → index-gnjgkecx.js} +7 -3
  658. package/dist/index-hy4653g4.js +345 -0
  659. package/dist/index-j13gzgdv.js +403 -0
  660. package/dist/{index-r8swbw1x.js → index-j516jaaz.js} +37 -11
  661. package/dist/{index-t8jz0e20.js → index-j903yhp4.js} +30 -38
  662. package/dist/{index-9ypczvpj.js → index-jb4m241t.js} +2 -0
  663. package/dist/index-jrka9029.js +177 -0
  664. package/dist/{index-cjzaj7ev.js → index-jxtg307y.js} +23 -21
  665. package/dist/index-kmbpej2y.js +1152 -0
  666. package/dist/{index-bz9cmnqq.js → index-kt6dh1n6.js} +4 -4
  667. package/dist/index-ky3ardqn.js +80 -0
  668. package/dist/index-kyejf658.js +14 -0
  669. package/dist/{index-zyc64nbh.js → index-kynwa08q.js} +52 -47
  670. package/dist/index-kzavdze2.js +15 -0
  671. package/dist/{index-pq7rkwkk.js → index-mbd92r1w.js} +67 -12
  672. package/dist/index-mxt0wfjy.js +58 -0
  673. package/dist/{index-9cxxfkhb.js → index-n20tybgk.js} +14 -9
  674. package/dist/index-nbv44x0x.js +250 -0
  675. package/dist/index-ngwf1s3c.js +51 -0
  676. package/dist/{index-zfncctjp.js → index-nk0cy9g1.js} +5 -4
  677. package/dist/index-p1m9djt6.js +108 -0
  678. package/dist/{index-hs76yzt7.js → index-paff5y0r.js} +17 -11
  679. package/dist/{index-qaet40b2.js → index-prf6ayhf.js} +5 -7
  680. package/dist/{index-hkxgennw.js → index-ps3djm8d.js} +7 -1
  681. package/dist/{index-1v3k5zgx.js → index-qnzhmk2s.js} +528 -1129
  682. package/dist/{index-3bzk2645.js → index-r9kq5ark.js} +1 -1
  683. package/dist/{index-hkw233vx.js → index-rbd2rq3z.js} +2 -2
  684. package/dist/{index-r0xr7y4m.js → index-rhb33thr.js} +138 -33
  685. package/dist/{index-kffm4r8w.js → index-rj32hkkp.js} +2 -2
  686. package/dist/index-rptj3qnc.js +96 -0
  687. package/dist/{index-hqsbtvta.js → index-rpyn7geq.js} +11 -3
  688. package/dist/{index-m9hb9wnk.js → index-sfzfd2m2.js} +2 -2
  689. package/dist/{index-sqkttz7z.js → index-sv5svtq7.js} +1 -1
  690. package/dist/{index-srs8hj9c.js → index-sx3g49y2.js} +5 -1
  691. package/dist/{index-9mjrnqxs.js → index-t1a2jrg7.js} +21 -91
  692. package/dist/{index-568w258r.js → index-tazm4dxf.js} +1 -1
  693. package/dist/{index-b51tzcgh.js → index-tf70nm22.js} +2 -2
  694. package/dist/index-ttexdtjj.js +28 -0
  695. package/dist/{index-gbj964dt.js → index-v37b2cd6.js} +1970 -3142
  696. package/dist/{index-0ndz5r8z.js → index-v59pxmf1.js} +17 -9
  697. package/dist/{index-rfkh44ss.js → index-vgytj9wp.js} +1 -1
  698. package/dist/{index-tnnmekgb.js → index-wa6h4tz6.js} +3 -3
  699. package/dist/{index-8wzhmgpa.js → index-wavv538x.js} +211 -196
  700. package/dist/{index-1szhrfsf.js → index-wbnpa8z6.js} +7 -5
  701. package/dist/index-werjqesf.js +43 -0
  702. package/dist/{index-7qyv50r4.js → index-wv8dqy7q.js} +2 -2
  703. package/dist/index-wz392jyz.js +10 -0
  704. package/dist/{index-1d7s7da0.js → index-x6sp5vpa.js} +36 -5
  705. package/dist/{index-bqzgaj57.js → index-x90w78yz.js} +183 -61
  706. package/dist/index-xgae0bn7.js +37 -0
  707. package/dist/index-xmr47znh.js +160 -0
  708. package/dist/{index-ftk3838x.js → index-xq4s9mka.js} +7 -2
  709. package/dist/{index-ww3gss55.js → index-xrgn784x.js} +1 -1
  710. package/dist/{index-fpwbskp2.js → index-xtby8rj3.js} +1 -1
  711. package/dist/index-xtkw9866.js +107 -0
  712. package/dist/{index-btjwc7xr.js → index-xypxnzhp.js} +15 -14
  713. package/dist/{index-yex7eg1v.js → index-y7sy1xdp.js} +6 -2
  714. package/dist/index-z4k0hqp9.js +476 -0
  715. package/dist/{index-a7ebd769.js → index-zwgwyvdt.js} +3 -3
  716. package/dist/internal/abort-error.d.ts +9 -0
  717. package/dist/internal/abort-error.d.ts.map +1 -0
  718. package/dist/internal/abort-race.d.ts +47 -4
  719. package/dist/internal/abort-race.d.ts.map +1 -1
  720. package/dist/internal/atomic-file.d.ts +19 -0
  721. package/dist/internal/atomic-file.d.ts.map +1 -1
  722. package/dist/internal/backoff.d.ts.map +1 -1
  723. package/dist/internal/bounded-body.d.ts +37 -1
  724. package/dist/internal/bounded-body.d.ts.map +1 -1
  725. package/dist/internal/bounded-file-read.d.ts +31 -15
  726. package/dist/internal/bounded-file-read.d.ts.map +1 -1
  727. package/dist/internal/bun-command.d.ts +11 -0
  728. package/dist/internal/bun-command.d.ts.map +1 -1
  729. package/dist/internal/channel.d.ts.map +1 -1
  730. package/dist/internal/coalesced-task.d.ts +14 -2
  731. package/dist/internal/coalesced-task.d.ts.map +1 -1
  732. package/dist/internal/darwin-binding-error.d.ts.map +1 -1
  733. package/dist/internal/darwin-binding.d.ts +10 -0
  734. package/dist/internal/darwin-binding.d.ts.map +1 -1
  735. package/dist/internal/deadline.d.ts +22 -2
  736. package/dist/internal/deadline.d.ts.map +1 -1
  737. package/dist/internal/exclusive-lock-owner.d.ts +20 -1
  738. package/dist/internal/exclusive-lock-owner.d.ts.map +1 -1
  739. package/dist/internal/exclusive-lock-read.d.ts +2 -0
  740. package/dist/internal/exclusive-lock-read.d.ts.map +1 -1
  741. package/dist/internal/exclusive-lock.d.ts +26 -0
  742. package/dist/internal/exclusive-lock.d.ts.map +1 -1
  743. package/dist/internal/file-observation.d.ts +49 -0
  744. package/dist/internal/file-observation.d.ts.map +1 -1
  745. package/dist/internal/json-response.d.ts +10 -0
  746. package/dist/internal/json-response.d.ts.map +1 -0
  747. package/dist/internal/open-descriptors.d.ts +5 -0
  748. package/dist/internal/open-descriptors.d.ts.map +1 -1
  749. package/dist/internal/optional-peer.d.ts.map +1 -1
  750. package/dist/internal/pinned-http.d.ts.map +1 -1
  751. package/dist/internal/positive-integer.d.ts +14 -6
  752. package/dist/internal/positive-integer.d.ts.map +1 -1
  753. package/dist/internal/postgres-query.d.ts +16 -0
  754. package/dist/internal/postgres-query.d.ts.map +1 -0
  755. package/dist/internal/process-identity.d.ts +21 -1
  756. package/dist/internal/process-identity.d.ts.map +1 -1
  757. package/dist/internal/process-instance.d.ts +6 -0
  758. package/dist/internal/process-instance.d.ts.map +1 -1
  759. package/dist/internal/request.d.ts +4 -0
  760. package/dist/internal/request.d.ts.map +1 -1
  761. package/dist/internal/secret-equal.d.ts +11 -0
  762. package/dist/internal/secret-equal.d.ts.map +1 -0
  763. package/dist/internal/secure-fetch.d.ts.map +1 -1
  764. package/dist/internal/sqlite.d.ts +8 -0
  765. package/dist/internal/sqlite.d.ts.map +1 -1
  766. package/dist/internal/timers.d.ts +20 -0
  767. package/dist/internal/timers.d.ts.map +1 -1
  768. package/dist/internal/typed.d.ts +11 -0
  769. package/dist/internal/typed.d.ts.map +1 -1
  770. package/dist/internal/unix-client-error.d.ts +21 -0
  771. package/dist/internal/unix-client-error.d.ts.map +1 -0
  772. package/dist/internal/unix-socket-lock.d.ts +23 -0
  773. package/dist/internal/unix-socket-lock.d.ts.map +1 -0
  774. package/dist/internal/unix-socket.d.ts +60 -0
  775. package/dist/internal/unix-socket.d.ts.map +1 -1
  776. package/dist/internal/upgrade-affects.d.ts +3 -3
  777. package/dist/internal/upgrade-affects.d.ts.map +1 -1
  778. package/dist/internal/upgrade-plan.d.ts.map +1 -1
  779. package/dist/json-schema/dialect.d.ts +0 -6
  780. package/dist/json-schema/dialect.d.ts.map +1 -1
  781. package/dist/json-schema/keywords.d.ts +116 -0
  782. package/dist/json-schema/keywords.d.ts.map +1 -0
  783. package/dist/json-schema/string-format.d.ts.map +1 -1
  784. package/dist/live/events.d.ts.map +1 -1
  785. package/dist/live/watch-client.d.ts.map +1 -1
  786. package/dist/observability/bounded-logger.d.ts +3 -0
  787. package/dist/observability/bounded-logger.d.ts.map +1 -1
  788. package/dist/observability/bounded-sink.d.ts.map +1 -1
  789. package/dist/observability/context.d.ts +12 -2
  790. package/dist/observability/context.d.ts.map +1 -1
  791. package/dist/observability/event-loop-delay.d.ts +62 -0
  792. package/dist/observability/event-loop-delay.d.ts.map +1 -0
  793. package/dist/observability/json-logger.d.ts.map +1 -1
  794. package/dist/observability/log-repeat.d.ts +44 -0
  795. package/dist/observability/log-repeat.d.ts.map +1 -0
  796. package/dist/observability/spool-core.d.ts +95 -0
  797. package/dist/observability/spool-core.d.ts.map +1 -0
  798. package/dist/observability/spool-file.d.ts +46 -0
  799. package/dist/observability/spool-file.d.ts.map +1 -0
  800. package/dist/observability/spool.d.ts +14 -8
  801. package/dist/observability/spool.d.ts.map +1 -1
  802. package/dist/observability/trace.d.ts.map +1 -1
  803. package/dist/observability/work.d.ts.map +1 -1
  804. package/dist/primitives/index.d.ts +1 -0
  805. package/dist/primitives/index.d.ts.map +1 -1
  806. package/dist/primitives/order-key.d.ts +37 -0
  807. package/dist/primitives/order-key.d.ts.map +1 -0
  808. package/dist/process/bun-child.d.ts.map +1 -1
  809. package/dist/process/command-owner.d.ts.map +1 -1
  810. package/dist/process/contract.d.ts +4 -3
  811. package/dist/process/contract.d.ts.map +1 -1
  812. package/dist/process/group-presence.d.ts.map +1 -1
  813. package/dist/process/group-settlement.d.ts +2 -0
  814. package/dist/process/group-settlement.d.ts.map +1 -1
  815. package/dist/process/group.d.ts +5 -1
  816. package/dist/process/group.d.ts.map +1 -1
  817. package/dist/process/launch.d.ts +5 -3
  818. package/dist/process/launch.d.ts.map +1 -1
  819. package/dist/process/owner-loss-guard.d.ts.map +1 -1
  820. package/dist/react/cache-bridge.d.ts.map +1 -1
  821. package/dist/release/watcher.d.ts.map +1 -1
  822. package/dist/server/bridge-host.d.ts +51 -0
  823. package/dist/server/bridge-host.d.ts.map +1 -0
  824. package/dist/server/bun.d.ts +4 -4
  825. package/dist/server/bun.d.ts.map +1 -1
  826. package/dist/server/context-contribution.d.ts.map +1 -1
  827. package/dist/server/context.d.ts +2 -2
  828. package/dist/server/context.d.ts.map +1 -1
  829. package/dist/server/contract-method.d.ts.map +1 -1
  830. package/dist/server/create.d.ts +1 -0
  831. package/dist/server/create.d.ts.map +1 -1
  832. package/dist/server/endpoint-dispatch.d.ts.map +1 -1
  833. package/dist/server/endpoint-response.d.ts.map +1 -1
  834. package/dist/server/error-dispatch.d.ts +4 -0
  835. package/dist/server/error-dispatch.d.ts.map +1 -1
  836. package/dist/server/error-hook.d.ts +2 -0
  837. package/dist/server/error-hook.d.ts.map +1 -1
  838. package/dist/server/handler-state.d.ts +16 -2
  839. package/dist/server/handler-state.d.ts.map +1 -1
  840. package/dist/server/implement.d.ts +1 -0
  841. package/dist/server/implement.d.ts.map +1 -1
  842. package/dist/server/local-host.d.ts +47 -0
  843. package/dist/server/local-host.d.ts.map +1 -0
  844. package/dist/server/logger.d.ts +20 -3
  845. package/dist/server/logger.d.ts.map +1 -1
  846. package/dist/server/logging.d.ts +2 -1
  847. package/dist/server/logging.d.ts.map +1 -1
  848. package/dist/server/middleware/cors.d.ts +49 -3
  849. package/dist/server/middleware/cors.d.ts.map +1 -1
  850. package/dist/server/middleware/signed-link.d.ts +42 -0
  851. package/dist/server/middleware/signed-link.d.ts.map +1 -0
  852. package/dist/server/multipart-reader.d.ts +3 -1
  853. package/dist/server/multipart-reader.d.ts.map +1 -1
  854. package/dist/server/multipart.d.ts.map +1 -1
  855. package/dist/server/oauth/cimd.d.ts.map +1 -1
  856. package/dist/server/oauth/endpoints.d.ts.map +1 -1
  857. package/dist/server/openapi.d.ts.map +1 -1
  858. package/dist/server/protocol-outcome.d.ts +17 -0
  859. package/dist/server/protocol-outcome.d.ts.map +1 -0
  860. package/dist/server/raw.d.ts.map +1 -1
  861. package/dist/server/request-completion.d.ts +3 -1
  862. package/dist/server/request-completion.d.ts.map +1 -1
  863. package/dist/server/shutdown.d.ts.map +1 -1
  864. package/dist/server/socket-io-config.d.ts +1 -1
  865. package/dist/server/socket-io-config.d.ts.map +1 -1
  866. package/dist/server/streaming-route.d.ts.map +1 -1
  867. package/dist/server/types.d.ts +20 -11
  868. package/dist/server/types.d.ts.map +1 -1
  869. package/dist/server/unix-client-body.d.ts +4 -1
  870. package/dist/server/unix-client-body.d.ts.map +1 -1
  871. package/dist/server/unix-client-bun.d.ts.map +1 -1
  872. package/dist/server/unix-client.d.ts +1 -1
  873. package/dist/server/unix-client.d.ts.map +1 -1
  874. package/dist/service-host/artifact-activation.d.ts +58 -0
  875. package/dist/service-host/artifact-activation.d.ts.map +1 -0
  876. package/dist/service-host/artifact-manifest.d.ts +68 -0
  877. package/dist/service-host/artifact-manifest.d.ts.map +1 -0
  878. package/dist/service-host/artifact.d.ts +43 -0
  879. package/dist/service-host/artifact.d.ts.map +1 -0
  880. package/dist/service-host/config-reloader-contract.d.ts +66 -0
  881. package/dist/service-host/config-reloader-contract.d.ts.map +1 -0
  882. package/dist/service-host/config-reloader-helpers.d.ts +32 -0
  883. package/dist/service-host/config-reloader-helpers.d.ts.map +1 -0
  884. package/dist/service-host/config-reloader-source.d.ts +47 -0
  885. package/dist/service-host/config-reloader-source.d.ts.map +1 -0
  886. package/dist/service-host/config-reloader.d.ts +6 -0
  887. package/dist/service-host/config-reloader.d.ts.map +1 -0
  888. package/dist/service-host/host-adapter.d.ts +72 -0
  889. package/dist/service-host/host-adapter.d.ts.map +1 -0
  890. package/dist/service-host/identity-unix-socket.d.ts +101 -0
  891. package/dist/service-host/identity-unix-socket.d.ts.map +1 -0
  892. package/dist/service-host/identity.d.ts +117 -0
  893. package/dist/service-host/identity.d.ts.map +1 -0
  894. package/dist/service-host/launchd-plist.d.ts +77 -0
  895. package/dist/service-host/launchd-plist.d.ts.map +1 -0
  896. package/dist/service-host/launchd-render.d.ts +91 -0
  897. package/dist/service-host/launchd-render.d.ts.map +1 -0
  898. package/dist/service-host/launchd.d.ts +82 -0
  899. package/dist/service-host/launchd.d.ts.map +1 -0
  900. package/dist/service-host/macos/bundle-plist.d.ts +50 -0
  901. package/dist/service-host/macos/bundle-plist.d.ts.map +1 -0
  902. package/dist/service-host/macos/bundle.d.ts +66 -0
  903. package/dist/service-host/macos/bundle.d.ts.map +1 -0
  904. package/dist/service-host/macos/codesign.d.ts +95 -0
  905. package/dist/service-host/macos/codesign.d.ts.map +1 -0
  906. package/dist/service-host/macos/icon.d.ts +93 -0
  907. package/dist/service-host/macos/icon.d.ts.map +1 -0
  908. package/dist/service-host/macos/launch-services.d.ts +88 -0
  909. package/dist/service-host/macos/launch-services.d.ts.map +1 -0
  910. package/dist/service-host/macos/launcher.d.ts +59 -0
  911. package/dist/service-host/macos/launcher.d.ts.map +1 -0
  912. package/dist/service-host/macos/responsibility.d.ts +90 -0
  913. package/dist/service-host/macos/responsibility.d.ts.map +1 -0
  914. package/dist/service-host/macos/runner.d.ts +69 -0
  915. package/dist/service-host/macos/runner.d.ts.map +1 -0
  916. package/dist/service-host/plist-xml.d.ts +48 -0
  917. package/dist/service-host/plist-xml.d.ts.map +1 -0
  918. package/dist/service-host/process-evidence.d.ts +17 -0
  919. package/dist/service-host/process-evidence.d.ts.map +1 -0
  920. package/dist/service-host/systemd-inspect.d.ts +126 -0
  921. package/dist/service-host/systemd-inspect.d.ts.map +1 -0
  922. package/dist/service-host/systemd-links.d.ts +23 -0
  923. package/dist/service-host/systemd-links.d.ts.map +1 -0
  924. package/dist/service-host/systemd-render.d.ts +93 -0
  925. package/dist/service-host/systemd-render.d.ts.map +1 -0
  926. package/dist/service-host/systemd.d.ts +50 -0
  927. package/dist/service-host/systemd.d.ts.map +1 -0
  928. package/dist/spend/attribution.d.ts +17 -0
  929. package/dist/spend/attribution.d.ts.map +1 -0
  930. package/dist/spend/coverage-guard.d.ts +60 -0
  931. package/dist/spend/coverage-guard.d.ts.map +1 -0
  932. package/dist/spend/coverage-lexer.d.ts +20 -0
  933. package/dist/spend/coverage-lexer.d.ts.map +1 -0
  934. package/dist/spend/facts.d.ts +23 -0
  935. package/dist/spend/facts.d.ts.map +1 -0
  936. package/dist/spend/gateway-stream.d.ts +25 -0
  937. package/dist/spend/gateway-stream.d.ts.map +1 -0
  938. package/dist/spend/gateway.d.ts +64 -0
  939. package/dist/spend/gateway.d.ts.map +1 -0
  940. package/dist/spend/receipt-merge.d.ts +13 -0
  941. package/dist/spend/receipt-merge.d.ts.map +1 -0
  942. package/dist/spend/receipt-spool.d.ts +35 -0
  943. package/dist/spend/receipt-spool.d.ts.map +1 -0
  944. package/dist/spend/reconcile.d.ts +45 -0
  945. package/dist/spend/reconcile.d.ts.map +1 -0
  946. package/dist/spend/schemas.d.ts +249 -0
  947. package/dist/spend/schemas.d.ts.map +1 -0
  948. package/dist/sync/outbox.d.ts +131 -0
  949. package/dist/sync/outbox.d.ts.map +1 -0
  950. package/dist/sync/overlay.d.ts +59 -0
  951. package/dist/sync/overlay.d.ts.map +1 -0
  952. package/dist/sync/protocol.d.ts +132 -0
  953. package/dist/sync/protocol.d.ts.map +1 -0
  954. package/dist/sync/server-store-check.d.ts +10 -0
  955. package/dist/sync/server-store-check.d.ts.map +1 -0
  956. package/dist/sync/server-store-memory.d.ts +14 -0
  957. package/dist/sync/server-store-memory.d.ts.map +1 -0
  958. package/dist/sync/server-store-postgres.d.ts +25 -0
  959. package/dist/sync/server-store-postgres.d.ts.map +1 -0
  960. package/dist/sync/server-store.d.ts +139 -0
  961. package/dist/sync/server-store.d.ts.map +1 -0
  962. package/dist/sync/session-machine.d.ts +79 -0
  963. package/dist/sync/session-machine.d.ts.map +1 -0
  964. package/dist/sync/session-snapshot.d.ts +19 -0
  965. package/dist/sync/session-snapshot.d.ts.map +1 -0
  966. package/dist/sync/session-steps.d.ts +15 -0
  967. package/dist/sync/session-steps.d.ts.map +1 -0
  968. package/dist/sync/session.d.ts +142 -0
  969. package/dist/sync/session.d.ts.map +1 -0
  970. package/dist/sync/tombstones.d.ts +53 -0
  971. package/dist/sync/tombstones.d.ts.map +1 -0
  972. package/dist/telegram/bot-api.d.ts.map +1 -1
  973. package/dist/telegram/broadcast-failure.d.ts.map +1 -1
  974. package/dist/telegram/budget-transformer.d.ts.map +1 -1
  975. package/dist/telegram/crypto.d.ts +2 -10
  976. package/dist/telegram/crypto.d.ts.map +1 -1
  977. package/dist/telegram/html/markdown-inline.d.ts +19 -0
  978. package/dist/telegram/html/markdown-inline.d.ts.map +1 -0
  979. package/dist/telegram/html/markdown-lines.d.ts +51 -0
  980. package/dist/telegram/html/markdown-lines.d.ts.map +1 -0
  981. package/dist/telegram/html/markdown-split.d.ts +49 -0
  982. package/dist/telegram/html/markdown-split.d.ts.map +1 -0
  983. package/dist/telegram/html/markdown.d.ts +14 -0
  984. package/dist/telegram/html/markdown.d.ts.map +1 -0
  985. package/dist/telegram/html/nodes.d.ts +26 -4
  986. package/dist/telegram/html/nodes.d.ts.map +1 -1
  987. package/dist/telegram/html/parse.d.ts.map +1 -1
  988. package/dist/telegram/html/render.d.ts.map +1 -1
  989. package/dist/telegram/init-data.d.ts.map +1 -1
  990. package/dist/telegram/local-files.d.ts.map +1 -1
  991. package/dist/telegram/operator-channel.d.ts +15 -2
  992. package/dist/telegram/operator-channel.d.ts.map +1 -1
  993. package/dist/telegram/outbound-budget.d.ts.map +1 -1
  994. package/dist/telegram/outbound-cost.d.ts +9 -1
  995. package/dist/telegram/outbound-cost.d.ts.map +1 -1
  996. package/dist/telegram/outbound-queue.d.ts +2 -1
  997. package/dist/telegram/outbound-queue.d.ts.map +1 -1
  998. package/dist/telegram/screens/outcome.d.ts.map +1 -1
  999. package/dist/telegram/send-failure.d.ts.map +1 -1
  1000. package/dist/telegram/transport-connect.d.ts.map +1 -1
  1001. package/dist/telegram/transport.d.ts.map +1 -1
  1002. package/dist/telegram/update-intake.d.ts.map +1 -1
  1003. package/dist/telegram/update-store-postgres.d.ts +2 -2
  1004. package/dist/telegram/update-store-postgres.d.ts.map +1 -1
  1005. package/dist/telegram/webhook.d.ts.map +1 -1
  1006. package/dist/testing/managed-resource-conformance.d.ts.map +1 -1
  1007. package/dist/testing/surface-conformance.d.ts.map +1 -1
  1008. package/dist/testing/surface-manifest.d.ts +2 -0
  1009. package/dist/testing/surface-manifest.d.ts.map +1 -1
  1010. package/dist/tools/access.d.ts +34 -0
  1011. package/dist/tools/access.d.ts.map +1 -0
  1012. package/dist/tools/agent.d.ts +14 -6
  1013. package/dist/tools/agent.d.ts.map +1 -1
  1014. package/dist/tools/cli/args-classify.d.ts +154 -0
  1015. package/dist/tools/cli/args-classify.d.ts.map +1 -0
  1016. package/dist/tools/cli/args-fields.d.ts +14 -7
  1017. package/dist/tools/cli/args-fields.d.ts.map +1 -1
  1018. package/dist/tools/cli/args-json.d.ts +1 -1
  1019. package/dist/tools/cli/args-json.d.ts.map +1 -1
  1020. package/dist/tools/cli/args-route.d.ts +4 -48
  1021. package/dist/tools/cli/args-route.d.ts.map +1 -1
  1022. package/dist/tools/cli/args-scan.d.ts +70 -0
  1023. package/dist/tools/cli/args-scan.d.ts.map +1 -0
  1024. package/dist/tools/cli/args-tokens.d.ts +2 -1
  1025. package/dist/tools/cli/args-tokens.d.ts.map +1 -1
  1026. package/dist/tools/cli/args.d.ts +31 -19
  1027. package/dist/tools/cli/args.d.ts.map +1 -1
  1028. package/dist/tools/cli/checkpoint.d.ts.map +1 -1
  1029. package/dist/tools/cli/command-shape.d.ts +5 -0
  1030. package/dist/tools/cli/command-shape.d.ts.map +1 -1
  1031. package/dist/tools/cli/command.d.ts +57 -2
  1032. package/dist/tools/cli/command.d.ts.map +1 -1
  1033. package/dist/tools/cli/config.d.ts +15 -58
  1034. package/dist/tools/cli/config.d.ts.map +1 -1
  1035. package/dist/tools/cli/create-cli.d.ts +7 -3
  1036. package/dist/tools/cli/create-cli.d.ts.map +1 -1
  1037. package/dist/tools/cli/format.d.ts.map +1 -1
  1038. package/dist/tools/cli/help.d.ts.map +1 -1
  1039. package/dist/tools/cli/invoke.d.ts +70 -20
  1040. package/dist/tools/cli/invoke.d.ts.map +1 -1
  1041. package/dist/tools/cli/io.d.ts.map +1 -1
  1042. package/dist/tools/cli/managed-surface.d.ts.map +1 -1
  1043. package/dist/tools/cli/notices.d.ts.map +1 -1
  1044. package/dist/tools/cli/policy.d.ts +66 -10
  1045. package/dist/tools/cli/policy.d.ts.map +1 -1
  1046. package/dist/tools/cli/prepare.d.ts +5 -4
  1047. package/dist/tools/cli/prepare.d.ts.map +1 -1
  1048. package/dist/tools/cli/run-managed.d.ts.map +1 -1
  1049. package/dist/tools/cli/run-native.d.ts.map +1 -1
  1050. package/dist/tools/cli/run-stream.d.ts.map +1 -1
  1051. package/dist/tools/cli/runner.d.ts +28 -0
  1052. package/dist/tools/cli/runner.d.ts.map +1 -0
  1053. package/dist/tools/cli/session.d.ts +12 -6
  1054. package/dist/tools/cli/session.d.ts.map +1 -1
  1055. package/dist/tools/cli/stream-surface.d.ts.map +1 -1
  1056. package/dist/tools/cli/stream.d.ts.map +1 -1
  1057. package/dist/tools/cli/unavailable.d.ts +2 -0
  1058. package/dist/tools/cli/unavailable.d.ts.map +1 -1
  1059. package/dist/tools/cli/unix-outcome.d.ts +8 -0
  1060. package/dist/tools/cli/unix-outcome.d.ts.map +1 -0
  1061. package/dist/tools/cli/update.d.ts.map +1 -1
  1062. package/dist/tools/cli/view-columns.d.ts +18 -0
  1063. package/dist/tools/cli/view-columns.d.ts.map +1 -0
  1064. package/dist/tools/cli/view.d.ts.map +1 -1
  1065. package/dist/tools/connections/define.d.ts.map +1 -1
  1066. package/dist/tools/connections/foreign-schema-join.d.ts +28 -0
  1067. package/dist/tools/connections/foreign-schema-join.d.ts.map +1 -0
  1068. package/dist/tools/connections/foreign-schema.d.ts +9 -0
  1069. package/dist/tools/connections/foreign-schema.d.ts.map +1 -0
  1070. package/dist/tools/connections/limits.d.ts +1 -1
  1071. package/dist/tools/connections/limits.d.ts.map +1 -1
  1072. package/dist/tools/connections/mcp-client.d.ts.map +1 -1
  1073. package/dist/tools/connections/mcp.d.ts.map +1 -1
  1074. package/dist/tools/connections/openapi.d.ts.map +1 -1
  1075. package/dist/tools/connections/runtime.d.ts +18 -6
  1076. package/dist/tools/connections/runtime.d.ts.map +1 -1
  1077. package/dist/tools/connections/sse-session.d.ts.map +1 -1
  1078. package/dist/tools/connections/types.d.ts +12 -2
  1079. package/dist/tools/connections/types.d.ts.map +1 -1
  1080. package/dist/tools/execute.d.ts.map +1 -1
  1081. package/dist/tools/internal/expose.d.ts +6 -0
  1082. package/dist/tools/internal/expose.d.ts.map +1 -0
  1083. package/dist/tools/internal/json-projection.d.ts +17 -0
  1084. package/dist/tools/internal/json-projection.d.ts.map +1 -0
  1085. package/dist/tools/internal/surface-projector.d.ts +18 -4
  1086. package/dist/tools/internal/surface-projector.d.ts.map +1 -1
  1087. package/dist/tools/invoker.d.ts +9 -2
  1088. package/dist/tools/invoker.d.ts.map +1 -1
  1089. package/dist/tools/lifecycle.d.ts +8 -2
  1090. package/dist/tools/lifecycle.d.ts.map +1 -1
  1091. package/dist/tools/list-names.d.ts +1 -1
  1092. package/dist/tools/list-names.d.ts.map +1 -1
  1093. package/dist/tools/manifest.d.ts +2 -0
  1094. package/dist/tools/manifest.d.ts.map +1 -1
  1095. package/dist/tools/mcp/handler.d.ts.map +1 -1
  1096. package/dist/tools/mcp/mount.d.ts +26 -14
  1097. package/dist/tools/mcp/mount.d.ts.map +1 -1
  1098. package/dist/tools/mcp/prepare.d.ts +2 -0
  1099. package/dist/tools/mcp/prepare.d.ts.map +1 -1
  1100. package/dist/tools/mcp/register.d.ts.map +1 -1
  1101. package/dist/tools/mcp/runtime-tools.d.ts +1 -1
  1102. package/dist/tools/mcp/runtime-tools.d.ts.map +1 -1
  1103. package/dist/tools/mcp/stdio.d.ts.map +1 -1
  1104. package/dist/tools/mount.d.ts +7 -2
  1105. package/dist/tools/mount.d.ts.map +1 -1
  1106. package/dist/tools/native-definition.d.ts +1 -1
  1107. package/dist/tools/native-definition.d.ts.map +1 -1
  1108. package/dist/tools/operations/async-operation-runtime-tools.d.ts +2 -2
  1109. package/dist/tools/operations/async-operation-runtime-tools.d.ts.map +1 -1
  1110. package/dist/tools/operations/async-operation-runtime-types.d.ts +1 -1
  1111. package/dist/tools/operations/async-operation-runtime-types.d.ts.map +1 -1
  1112. package/dist/tools/operations/define-wait-tool.d.ts.map +1 -1
  1113. package/dist/tools/operations/mount-wait.d.ts.map +1 -1
  1114. package/dist/tools/operations/wait-core.d.ts.map +1 -1
  1115. package/dist/tools/read-operation.d.ts +6 -4
  1116. package/dist/tools/read-operation.d.ts.map +1 -1
  1117. package/dist/tools/registry.d.ts.map +1 -1
  1118. package/dist/tools/runtime-tool-declaration.d.ts +4 -1
  1119. package/dist/tools/runtime-tool-declaration.d.ts.map +1 -1
  1120. package/dist/tools/runtime-tool.d.ts +6 -1
  1121. package/dist/tools/runtime-tool.d.ts.map +1 -1
  1122. package/dist/tools/schema/coerce.d.ts.map +1 -1
  1123. package/dist/tools/schema/inline-references.d.ts +7 -0
  1124. package/dist/tools/schema/inline-references.d.ts.map +1 -0
  1125. package/dist/tools/schema/json-schema-origin.d.ts +1 -1
  1126. package/dist/tools/schema/json-schema-origin.d.ts.map +1 -1
  1127. package/dist/tools/schema/presentation.d.ts +6 -0
  1128. package/dist/tools/schema/presentation.d.ts.map +1 -1
  1129. package/dist/tools/schema/schema.d.ts +2 -0
  1130. package/dist/tools/schema/schema.d.ts.map +1 -1
  1131. package/dist/tools/schema/untyped-properties.d.ts.map +1 -1
  1132. package/dist/tools/surface.d.ts.map +1 -1
  1133. package/dist/tools/toolkit.d.ts +6 -3
  1134. package/dist/tools/toolkit.d.ts.map +1 -1
  1135. package/dist/tools/transfer/define-download-tool.d.ts.map +1 -1
  1136. package/dist/tools/transfer/define-upload-tool.d.ts.map +1 -1
  1137. package/dist/tools/transfer/define-view-file-tool.d.ts +2 -1
  1138. package/dist/tools/transfer/define-view-file-tool.d.ts.map +1 -1
  1139. package/dist/tools/transfer/mount-download.d.ts.map +1 -1
  1140. package/dist/tools/transfer/view-file-contract.d.ts +2 -2
  1141. package/dist/tools/transfer/view-file.d.ts +1 -2
  1142. package/dist/tools/transfer/view-file.d.ts.map +1 -1
  1143. package/dist/tracking/client.d.ts +0 -13
  1144. package/dist/tracking/client.d.ts.map +1 -1
  1145. package/dist/tracking/delivery.d.ts.map +1 -1
  1146. package/dist/tracking/performance/collector.d.ts.map +1 -1
  1147. package/llms/agent-executor-acp.txt +51 -0
  1148. package/llms/agent-executor-claude-sdk.txt +31 -0
  1149. package/llms/agent-executor-claude.txt +29 -0
  1150. package/llms/agent-executor-codex.txt +25 -0
  1151. package/llms/agent-executor-testing.txt +26 -0
  1152. package/llms/agent-executor.txt +40 -0
  1153. package/llms/agent-runtime-harness.txt +68 -5
  1154. package/llms/agent-runtime-openrouter.txt +8 -2
  1155. package/llms/agent-runtime-postgres.txt +30 -0
  1156. package/llms/agent-runtime-react.txt +1 -1
  1157. package/llms/agent-runtime-realtime.txt +1 -1
  1158. package/llms/agent-runtime-sandbox.txt +5 -2
  1159. package/llms/agent-runtime-sqlite-bun.txt +2 -2
  1160. package/llms/agent-runtime-sqlite-node.txt +2 -2
  1161. package/llms/agent-runtime-testing.txt +2 -1
  1162. package/llms/agent-runtime.2.txt +475 -496
  1163. package/llms/agent-runtime.3.txt +229 -267
  1164. package/llms/agent-runtime.4.txt +23 -242
  1165. package/llms/agent-runtime.5.txt +1 -1
  1166. package/llms/agent-runtime.txt +551 -2
  1167. package/llms/application-diagnostic-journal.txt +2 -0
  1168. package/llms/application.2.txt +3 -0
  1169. package/llms/application.3.txt +30 -7
  1170. package/llms/application.txt +4 -1
  1171. package/llms/cli.2.txt +259 -99
  1172. package/llms/cli.3.txt +90 -0
  1173. package/llms/cli.txt +95 -184
  1174. package/llms/contract.txt +7 -6
  1175. package/llms/declaration.txt +1 -1
  1176. package/llms/files.txt +11 -0
  1177. package/llms/handler.txt +25 -0
  1178. package/llms/http.txt +18 -1
  1179. package/llms/live.txt +28 -1
  1180. package/llms/node.txt +3 -2
  1181. package/llms/observability.2.txt +105 -0
  1182. package/llms/observability.txt +14 -90
  1183. package/llms/primitives.txt +27 -0
  1184. package/llms/process.2.txt +2 -2
  1185. package/llms/process.txt +10 -9
  1186. package/llms/realtime.txt +11 -0
  1187. package/llms/server.2.txt +355 -0
  1188. package/llms/server.3.txt +2 -1
  1189. package/llms/server.4.txt +45 -6
  1190. package/llms/server.5.txt +9 -2
  1191. package/llms/server.txt +185 -255
  1192. package/llms/service-host-macos.txt +53 -0
  1193. package/llms/service-host.txt +69 -0
  1194. package/llms/spend-testing.txt +21 -0
  1195. package/llms/spend.txt +173 -0
  1196. package/llms/stitchkit.2.txt +368 -42
  1197. package/llms/stitchkit.3.txt +164 -13
  1198. package/llms/stitchkit.txt +95 -417
  1199. package/llms/sync-postgres.txt +31 -0
  1200. package/llms/sync.txt +396 -0
  1201. package/llms/telegram-html.txt +4 -1
  1202. package/llms/telegram.2.txt +4 -4
  1203. package/llms/telegram.txt +105 -14
  1204. package/llms/testing.txt +4 -3
  1205. package/llms/tools-connections.txt +4 -4
  1206. package/llms/tools.2.txt +78 -17
  1207. package/llms/tools.3.txt +12 -8
  1208. package/llms/tools.txt +85 -78
  1209. package/llms/{upgrading-0.106.0-0.125.0.txt → upgrading-0.106.0-0.126.0.txt} +42 -3
  1210. package/llms/upgrading-0.127.0.txt +1059 -0
  1211. package/llms/upgrading.txt +2 -1
  1212. package/llms-full.txt +3692 -518
  1213. package/llms.txt +45 -29
  1214. package/native/darwin-arm64.node +0 -0
  1215. package/native/darwin-x64.node +0 -0
  1216. package/native-assets.json +4 -4
  1217. package/package.json +69 -11
  1218. package/dist/agent-runtime/sandbox-coding.d.ts.map +0 -1
  1219. package/dist/agent-runtime/sqlite-events.d.ts +0 -5
  1220. package/dist/agent-runtime/sqlite-events.d.ts.map +0 -1
  1221. package/dist/agent-runtime/sqlite-history.d.ts +0 -7
  1222. package/dist/agent-runtime/sqlite-history.d.ts.map +0 -1
  1223. package/dist/agent-runtime/sqlite-ledger.d.ts +0 -7
  1224. package/dist/agent-runtime/sqlite-ledger.d.ts.map +0 -1
  1225. package/dist/agent-runtime/sqlite-reads.d.ts +0 -14
  1226. package/dist/agent-runtime/sqlite-reads.d.ts.map +0 -1
  1227. package/dist/agent-runtime/sqlite-rows.d.ts.map +0 -1
  1228. package/dist/agent-runtime/tool-progress.d.ts.map +0 -1
  1229. package/dist/entrypoints/application/schemas.d.ts +0 -15
  1230. package/dist/entrypoints/application/schemas.d.ts.map +0 -1
  1231. package/dist/entrypoints/application/schemas.js +0 -27
  1232. package/dist/index-0s4xebbg.js +0 -8
  1233. package/dist/index-5dmk54h9.js +0 -256
  1234. package/dist/index-7cn66qdk.js +0 -92
  1235. package/dist/index-8x0q6yfb.js +0 -247
  1236. package/dist/index-a5qr2rj6.js +0 -26
  1237. package/dist/index-b0kddvzw.js +0 -35
  1238. package/dist/index-cj5f0x4y.js +0 -1150
  1239. package/dist/index-drcjjhy1.js +0 -40
  1240. package/dist/index-eemvahkc.js +0 -21
  1241. package/dist/index-gfk7nrht.js +0 -0
  1242. package/dist/index-jp2qd9jb.js +0 -108
  1243. package/dist/index-nx6eazt0.js +0 -160
  1244. package/dist/index-wxadzdb7.js +0 -55
  1245. package/dist/internal/until-aborted.d.ts +0 -9
  1246. package/dist/internal/until-aborted.d.ts.map +0 -1
  1247. package/dist/server/unix-client-error.d.ts +0 -9
  1248. package/dist/server/unix-client-error.d.ts.map +0 -1
  1249. package/llms/application-schemas.txt +0 -42
@@ -1,33 +1,21 @@
1
- import {
2
- AgentSandboxRestrictionSchema2,
3
- AgentSandboxGradeSchema2,
4
- probeAgentProcessSandbox2,
5
- missingSandboxRestrictions2,
6
- recordAgentSandboxProbe2,
7
- refuseUnknownSpillReference
8
- } from "../index-8wzhmgpa.js";
9
1
  import {
10
2
  AgentRecordIdSchema2,
3
+ AgentStoreEventKindSchema2,
4
+ AgentStoreEventEnvelopeSchema2,
5
+ AppendAgentStoreEventSchema2,
6
+ ReadAgentStoreEventsSchema2,
7
+ AgentStoreEventPageSchema2,
11
8
  AgentRecordVersionSchema2,
12
9
  AgentTimestampSchema2,
13
10
  AgentJsonObjectSchema2,
14
- AgentProviderEnvelopeSchema2,
15
- AgentProviderResponseSchema2,
16
- AgentTextPartSchema2,
17
- AgentReasoningPartSchema2,
18
- AgentFilePartSchema2,
19
- AgentSourcePartSchema2,
20
- AgentToolCallPartSchema2,
21
- AgentToolResultPartSchema2,
22
- AgentToolApprovalRequestPartSchema2,
23
- AgentToolApprovalResponsePartSchema2,
24
- AgentOpaquePartSchema2,
25
- AgentControlPartSchema2,
26
- AgentMessagePartSchema2,
27
11
  AgentMessageRoleSchema2,
28
12
  AgentMessageStatusSchema2,
29
13
  AgentMessageSchema2,
30
14
  AgentAssistantPlaceholderSchema2,
15
+ AgentProvenanceSchema2,
16
+ AgentUsageValueSchema2,
17
+ AgentCostValueSchema2,
18
+ AgentUsageSchema2,
31
19
  AgentRunStateSchema2,
32
20
  AgentRunQueuePrioritySchema2,
33
21
  AgentRunOperationKindSchema2,
@@ -35,30 +23,72 @@ import {
35
23
  AgentRunOperationSchema2,
36
24
  AgentTerminalReasonSchema2,
37
25
  runStateForTerminalReason2,
38
- AgentProvenanceSchema2,
39
- AgentUsageValueSchema2,
40
- AgentCostValueSchema2,
41
- AgentUsageSchema2,
42
26
  AgentRunSchema2,
43
27
  AgentSnapshotSchema2,
44
28
  AgentRunMetricsSchema2
45
- } from "../index-8kzct1d6.js";
29
+ } from "../index-bn2baakz.js";
46
30
  import {
31
+ AgentBranchRefusalCodeSchema2,
32
+ AgentBranchRefusalSchema2,
33
+ AgentConversationBranchRefusedError2,
47
34
  BranchAgentConversationInputSchema2,
48
35
  AgentConversationBranchReceiptSchema2,
49
36
  AgentConversationBranchResultSchema2,
37
+ AgentConversationBranchPlanSchema2,
38
+ defineAgentTool,
39
+ SqlIntegerSchema,
40
+ AgentChildBudgetSchema2,
41
+ AgentChildStateSchema2,
42
+ AgentChildRecordSchema2,
43
+ AgentChildBlockingKindSchema2,
44
+ AgentChildBlockingSourceSchema2,
45
+ AgentChildBlockingEventSchema2,
46
+ ChildBlockingDecisionSchema,
47
+ ChildSpawnedEventPayloadSchema,
48
+ ChildStateEventPayloadSchema,
49
+ parseChild,
50
+ usageNumbers,
50
51
  AgentConversationPurgeInputSchema2,
51
52
  AgentConversationPurgeResultSchema2,
52
53
  AgentConversationPurgedError2,
53
54
  purgeAgentConversation2,
55
+ DeferredAgentToolSearchInputSchema2,
56
+ DeferredAgentToolMatchSchema2,
57
+ DeferredAgentToolReceiptSchema2,
58
+ AgentEventSearchResultSchema2,
59
+ createAgentEventSearch2,
60
+ createAgentEventSearchTools2,
61
+ AgentStoreUnsupportedCapabilityError2,
54
62
  createAgentRuntimeStore2
55
- } from "../index-0sg3wnzr.js";
63
+ } from "../index-bbzvrq66.js";
56
64
  import {
57
- AgentStoreEventKindSchema2,
58
- AgentStoreEventEnvelopeSchema2,
59
- AppendAgentStoreEventSchema2,
60
- ReadAgentStoreEventsSchema2,
61
- AgentStoreEventPageSchema2,
65
+ AgentCodingToolAuthorizationSchema2,
66
+ refuseUnknownSpillReference
67
+ } from "../index-wavv538x.js";
68
+ import {
69
+ AgentProviderEnvelopeSchema2,
70
+ AgentTextPartSchema2,
71
+ AgentReasoningPartSchema2,
72
+ AgentFilePartSchema2,
73
+ AgentSourcePartSchema2,
74
+ AgentToolCallPartSchema2,
75
+ AgentToolResultPartSchema2,
76
+ AgentToolApprovalRequestPartSchema2,
77
+ AgentToolApprovalResponsePartSchema2,
78
+ AgentOpaquePartSchema2,
79
+ AgentControlPartSchema2,
80
+ AgentMessagePartSchema2
81
+ } from "../index-2rf33y2h.js";
82
+ import {
83
+ AgentProviderResponseSchema2
84
+ } from "../index-97rp94ff.js";
85
+ import {
86
+ AgentRuntimeHeadSchema2,
87
+ AgentStoredRunSchema2,
88
+ AgentAdmissionReceiptSchema2,
89
+ AgentSeedReceiptSchema2,
90
+ AgentHistoryMutationSchema2,
91
+ ACTIVE_AGENT_RUN_STATES2,
62
92
  AgentStoreConflictSchema2,
63
93
  AgentStoreNotFoundSchema2,
64
94
  AgentStoreAppliedSchema2,
@@ -83,67 +113,21 @@ import {
83
113
  AgentConversationArchiveSchema2,
84
114
  encodeAgentConversationArchive2,
85
115
  decodeAgentConversationArchive2,
86
- isAssistantHistoryEvidence2,
87
- isCompleteAgentHistoryTurn,
88
- AgentRuntimeHeadSchema2,
89
- AgentStoredRunSchema2,
90
- AgentAdmissionReceiptSchema2,
91
- AgentSeedReceiptSchema2,
92
- AgentHistoryMutationSchema2,
93
- ACTIVE_AGENT_RUN_STATES2
94
- } from "../index-egg0yp2j.js";
95
- import"../index-m8ddk770.js";
116
+ conversationOfRun
117
+ } from "../index-9xr44d2g.js";
118
+ import"../index-brhhaygm.js";
96
119
  import {
97
- AgentRuntimeConflictError2,
98
- AgentRunUnsettledError2,
99
- normalizeSdkUsage,
100
- AgentContextOverflowError2,
101
- createAgentSessionCoordinator2,
102
- registerDeferredToolRepair,
103
- registerDeferredToolCatalog,
104
- deferredToolCatalog,
105
- repairedSearchCall,
106
- projectAgentHistoryDetailed2,
107
- projectAgentHistory2,
108
120
  ModelInvocationTraceSchema2,
109
121
  CompletionInvocationInputSchema2,
122
+ InvocationResponseSchema,
110
123
  ModelInvocationRecordSchema2,
111
- currentModelInvocationAttempt2,
112
- createModelInvocationLedger2,
113
- createAgentToolFenceLifecycle2,
114
- AgentTokenCountSchema2,
115
- selectAgentHistory2,
116
- composeAgentPrompt2,
117
- AgentProviderStreamCutError2,
118
- classifyProviderFailure2,
119
- isToolResultFailure2,
120
- recordAgentRetryDecision2,
121
- defineStateSlot2,
122
- createAgentStateSlotStore2,
123
- renderAgentStateSlots2,
124
- agentGoalStateSlot2,
125
- agentTodoStateSlot2,
126
- createAgentRuntime2
127
- } from "../index-1v3k5zgx.js";
128
- import {
129
- AgentConversationSummarySchema2,
130
- AgentConversationPageSchema2,
131
- AgentConversationMessagePageSchema2
132
- } from "../index-kqnd6a85.js";
133
- import"../index-ndjzbt2v.js";
134
- import"../index-dsa676h8.js";
135
- import"../index-t8jz0e20.js";
136
- import"../index-5dmk54h9.js";
137
- import"../index-x2d51zay.js";
138
- import"../index-x2rvpbtj.js";
139
- import"../index-yt1gg11x.js";
140
- import"../index-7cn66qdk.js";
141
- import {
142
- mountAgent2
143
- } from "../index-n6hvd1r2.js";
124
+ isModelInvocationRecord,
125
+ isAssistantHistoryEvidence2,
126
+ isCompleteAgentHistoryTurn
127
+ } from "../index-ajmtxsky.js";
144
128
  import {
145
129
  createBoundedSinkManager
146
- } from "../index-qaet40b2.js";
130
+ } from "../index-prf6ayhf.js";
147
131
  import {
148
132
  AgentAdmissionEventSchema2,
149
133
  AgentTransientDeltaEventSchema2,
@@ -161,8 +145,18 @@ import {
161
145
  AgentRuntimeEventCursorSchema2,
162
146
  advanceAgentRuntimeEventCursor2,
163
147
  agentDurableEventId2
164
- } from "../index-hs76yzt7.js";
148
+ } from "../index-paff5y0r.js";
165
149
  import {
150
+ AgentRuntimeConflictError2,
151
+ AgentRunUnsettledError2,
152
+ addUsage,
153
+ statedUsage,
154
+ unknownUsage,
155
+ AgentStepSpendPhaseSchema2,
156
+ AgentStepSpendProviderSchema,
157
+ AgentStepSpendSchema2,
158
+ normalizeStepUsage,
159
+ currentModelInvocationAttempt2,
166
160
  AgentModelCapabilitySchema2,
167
161
  AgentModelDescriptorSchema2,
168
162
  AgentModelRegistrySnapshotSchema2,
@@ -178,7 +172,54 @@ import {
178
172
  createMemoryAgentModelSelectionStore2,
179
173
  defineModelRegistry2,
180
174
  validateAgentModelSnapshot2
181
- } from "../index-nx6eazt0.js";
175
+ } from "../index-kmbpej2y.js";
176
+ import {
177
+ AgentConversationSummarySchema2,
178
+ AgentConversationPageSchema2,
179
+ AgentConversationMessagePageSchema2
180
+ } from "../index-7416mhyh.js";
181
+ import"../index-akf0xkrm.js";
182
+ import"../index-dsa676h8.js";
183
+ import"../index-27hck3z2.js";
184
+ import"../index-ngwf1s3c.js";
185
+ import"../index-360j58vb.js";
186
+ import"../index-j903yhp4.js";
187
+ import"../index-9wh98cpa.js";
188
+ import"../index-yt1gg11x.js";
189
+ import"../index-3ypvpkwr.js";
190
+ import"../index-werjqesf.js";
191
+ import {
192
+ mountAgent2
193
+ } from "../index-3b31z0pc.js";
194
+ import {
195
+ AgentContextOverflowError2,
196
+ createAgentSessionCoordinator2,
197
+ registerDeferredToolRepair,
198
+ registerDeferredToolCatalog,
199
+ deferredToolCatalog,
200
+ repairedSearchCall,
201
+ projectAgentHistoryDetailed2,
202
+ projectAgentHistory2,
203
+ createModelInvocationLedger2,
204
+ createAgentToolFenceLifecycle2,
205
+ AgentTokenCountSchema2,
206
+ selectAgentHistory2,
207
+ composeAgentPrompt2,
208
+ AgentProviderStreamCutError2,
209
+ classifyProviderFailure2,
210
+ isToolResultFailure2,
211
+ recordAgentRetryDecision2,
212
+ AgentStepBarrierError2,
213
+ createToolDependencyResolver2,
214
+ defineStateSlot2,
215
+ createAgentStateSlotStore2,
216
+ renderAgentStateSlots2,
217
+ agentGoalStateSlot2,
218
+ agentTodoStateSlot2,
219
+ createAgentRuntime2
220
+ } from "../index-qnzhmk2s.js";
221
+ import"../index-m38ej7e5.js";
222
+ import"../index-d4svrknj.js";
182
223
  import {
183
224
  DURABILITY_STEP_EVENT_KIND2,
184
225
  StepResultDecodeError2,
@@ -187,313 +228,161 @@ import {
187
228
  ParkRecordDecodeError2,
188
229
  ParkAbortedError2
189
230
  } from "../index-snef22zr.js";
190
- import"../index-zyc64nbh.js";
191
- import"../index-sqc6ezrb.js";
192
- import"../index-0ndz5r8z.js";
193
- import"../index-gdqawggb.js";
231
+ import"../index-kynwa08q.js";
232
+ import"../index-6kec3b14.js";
233
+ import"../index-v59pxmf1.js";
234
+ import"../index-7kfcb576.js";
194
235
  import {
195
236
  createMemoryAgentRuntimeStore2
196
- } from "../index-r8swbw1x.js";
237
+ } from "../index-j516jaaz.js";
197
238
  import {
198
239
  createAgentRuntimeEventSink2
199
- } from "../index-7qyv50r4.js";
200
- import"../index-kffm4r8w.js";
201
- import"../index-fa53vygr.js";
202
- import"../index-ww3gss55.js";
240
+ } from "../index-wv8dqy7q.js";
241
+ import"../index-rj32hkkp.js";
242
+ import"../index-bmaz3jzy.js";
243
+ import"../index-xrgn784x.js";
203
244
  import {
204
245
  buildToolManifest2
205
- } from "../index-a3z56mtn.js";
206
- import"../index-kxff9e9w.js";
246
+ } from "../index-d96c1n1q.js";
247
+ import"../index-3agqmmrg.js";
248
+ import"../index-wa6h4tz6.js";
249
+ import"../index-jb4m241t.js";
250
+ import"../index-5e0zsbf7.js";
251
+ import {
252
+ resolveToolAccess
253
+ } from "../index-ax3wns1a.js";
207
254
  import {
208
255
  defineRuntimeTool2,
209
256
  executableAgentRuntimeTools
210
- } from "../index-m0wsfmrc.js";
257
+ } from "../index-7csn6pva.js";
258
+ import"../index-hy4653g4.js";
211
259
  import {
212
- MAX_TIMER_MS
213
- } from "../index-eemvahkc.js";
260
+ createTraceContext2,
261
+ childSpan2
262
+ } from "../index-y7sy1xdp.js";
214
263
  import {
215
264
  assertPositiveSafeInteger
216
- } from "../index-0s4xebbg.js";
265
+ } from "../index-kzavdze2.js";
217
266
  import {
218
- createTraceContext2,
219
- childSpan2
220
- } from "../index-yex7eg1v.js";
267
+ withDeadline
268
+ } from "../index-agy5fqgf.js";
269
+ import {
270
+ scheduleAt
271
+ } from "../index-mxt0wfjy.js";
272
+ import {
273
+ abortReason
274
+ } from "../index-rptj3qnc.js";
221
275
  // src/agent-runtime/child-tools.ts
222
- import { z as z2 } from "zod";
223
-
224
- // src/agent-runtime/agent-tool.ts
225
- function defineAgentTool(definition) {
226
- return {
227
- ...definition,
228
- handler: (context) => definition.handler(context)
229
- };
230
- }
231
-
232
- // src/agent-runtime/children-contract.ts
233
- import { z } from "zod";
234
- var AgentChildBudgetSchema = z.object({
235
- usd: z.number().positive().optional(),
236
- tokens: z.int().positive().optional(),
237
- milliseconds: z.int().positive().optional()
238
- }).strict();
239
- var AgentChildStateSchema = z.enum([
240
- "spawned",
241
- "running",
242
- "finished",
243
- "stopped",
244
- "lost"
245
- ]);
246
- var AgentChildRecordSchema = z.object({
247
- parentConversationId: z.string().min(1),
248
- childConversationId: z.string().min(1),
249
- seedUptoSeq: z.int().nonnegative(),
250
- state: AgentChildStateSchema,
251
- budget: AgentChildBudgetSchema,
252
- usage: z.object({
253
- tokens: z.int().nonnegative(),
254
- usd: z.number().nonnegative(),
255
- milliseconds: z.int().nonnegative()
256
- }).strict(),
257
- resultReference: z.string().optional(),
258
- createdAt: z.string(),
259
- updatedAt: z.string()
260
- }).strict();
261
- var AgentChildBlockingKindSchema = z.enum(["approval", "input"]);
262
- var AgentChildBlockingSourceSchema = z.object({
263
- approvalId: z.string().min(1),
264
- callId: z.string().min(1),
265
- toolName: z.string().min(1),
266
- input: z.json(),
267
- kind: AgentChildBlockingKindSchema.default("approval"),
268
- batchId: z.string().min(1).optional()
269
- }).strict();
270
- var AgentChildBlockingEventSchema = z.object({
271
- parentConversationId: z.string().min(1),
272
- childConversationId: z.string().min(1),
273
- kind: AgentChildBlockingKindSchema,
274
- approvalId: z.string().min(1),
275
- childApprovalId: z.string().min(1),
276
- callId: z.string().min(1),
277
- toolName: z.string().min(1),
278
- input: z.json(),
279
- batchId: z.string().min(1),
280
- presentedAt: z.string()
281
- }).strict();
282
- var ChildBlockingDecisionSchema = z.union([
283
- z.object({
284
- approvalId: z.string().min(1),
285
- approved: z.boolean(),
286
- reason: z.string().optional()
287
- }).strict(),
288
- z.object({ approvalId: z.string().min(1), value: z.json() }).strict()
289
- ]);
290
- var ChildRowSchema = z.object({
291
- parent_conversation_id: z.string(),
292
- child_conversation_id: z.string(),
293
- seed_upto_seq: z.int().nonnegative(),
294
- state: AgentChildStateSchema,
295
- budget_payload: z.string(),
296
- usage_payload: z.string(),
297
- result_reference: z.string().nullable(),
298
- created_at: z.string(),
299
- updated_at: z.string()
300
- });
301
- function parseChild(raw) {
302
- const row = ChildRowSchema.parse(raw);
303
- return AgentChildRecordSchema.parse({
304
- parentConversationId: row.parent_conversation_id,
305
- childConversationId: row.child_conversation_id,
306
- seedUptoSeq: row.seed_upto_seq,
307
- state: row.state,
308
- budget: JSON.parse(row.budget_payload),
309
- usage: JSON.parse(row.usage_payload),
310
- ...row.result_reference && { resultReference: row.result_reference },
311
- createdAt: row.created_at,
312
- updatedAt: row.updated_at
313
- });
314
- }
315
- function usageNumbers(usage) {
316
- const inputTokens = usage.inputTokens.value;
317
- const outputTokens = usage.outputTokens.value;
318
- return {
319
- ...inputTokens !== undefined && outputTokens !== undefined ? { tokens: inputTokens + outputTokens } : {},
320
- ...usage.cost?.currency === "USD" && usage.cost.value !== undefined ? { usd: usage.cost.value } : {}
321
- };
322
- }
323
-
324
- // src/agent-runtime/child-blocking.ts
325
- function createChildBlockingRelay(input) {
326
- const { store, now, handles, listChildren, activeChild, bounded } = input;
327
- const presentedBlocking = new Map;
328
- const retiredBlocking = new Set;
329
- let blockingQueue = Promise.resolve();
330
- const serializeBlocking = (work) => {
331
- const run = blockingQueue.then(work, work);
332
- blockingQueue = run.then(() => {
333
- return;
334
- }, () => {
335
- return;
336
- });
337
- return run;
338
- };
339
- const childScopedBlockingId = (childConversationId, childApprovalId) => `${encodeURIComponent(childConversationId)}:${encodeURIComponent(childApprovalId)}`;
340
- const retireChildBlocking = (childConversationId) => {
341
- for (const [id, entry] of presentedBlocking) {
342
- if (entry.event.childConversationId === childConversationId) {
343
- presentedBlocking.delete(id);
344
- retiredBlocking.add(id);
345
- }
346
- }
347
- };
348
- const listChildBlockingInner = async (parentConversationId) => {
349
- const live = listChildren(parentConversationId).filter((record) => record.state === "spawned" || record.state === "running");
350
- for (const record of live) {
351
- const handle = handles.get(record.childConversationId);
352
- if (!handle?.blockingEvents)
353
- continue;
354
- const reported = await bounded(Promise.resolve(handle.blockingEvents()), []);
355
- const fresh = reported.map((source) => AgentChildBlockingSourceSchema.parse(source)).filter((source) => {
356
- const id = childScopedBlockingId(record.childConversationId, source.approvalId);
357
- return !presentedBlocking.has(id) && !retiredBlocking.has(id);
358
- });
359
- if (fresh.length === 0)
360
- continue;
361
- const presentedAt = now().toISOString();
362
- for (const source of fresh) {
363
- const approvalId = childScopedBlockingId(record.childConversationId, source.approvalId);
364
- const batchId = source.batchId ? `${record.childConversationId}:${source.batchId}` : approvalId;
365
- const event = AgentChildBlockingEventSchema.parse({
366
- parentConversationId,
367
- childConversationId: record.childConversationId,
368
- kind: source.kind,
369
- approvalId,
370
- childApprovalId: source.approvalId,
371
- callId: source.callId,
372
- toolName: source.toolName,
373
- input: source.input,
374
- batchId,
375
- presentedAt
376
- });
377
- await store.appendEvent({
378
- conversationId: parentConversationId,
379
- kind: "child/state",
380
- occurredAt: presentedAt,
381
- payload: {
382
- action: "blocking-presented",
383
- childConversationId: event.childConversationId,
384
- approvalId: event.approvalId,
385
- childApprovalId: event.childApprovalId,
386
- kind: event.kind,
387
- callId: event.callId,
388
- toolName: event.toolName,
389
- input: event.input,
390
- batchId: event.batchId,
391
- presentedAt
392
- }
393
- });
394
- presentedBlocking.set(approvalId, { event, batchId });
395
- }
396
- }
397
- return [...presentedBlocking.values()].map((entry) => entry.event).filter((event) => event.parentConversationId === parentConversationId);
398
- };
399
- const listChildBlocking = (parentConversationId) => serializeBlocking(() => listChildBlockingInner(parentConversationId));
400
- const respondToChildBlockingInner = async (parentConversationId, decision) => {
401
- const entry = presentedBlocking.get(decision.approvalId);
402
- if (!entry || entry.event.parentConversationId !== parentConversationId) {
403
- throw new TypeError("Child blocking request is missing, stale or already answered");
404
- }
405
- const { handle } = activeChild(parentConversationId, entry.event.childConversationId);
406
- if (!handle.respondToBlocking) {
407
- throw new TypeError("Child host cannot answer blocking requests");
408
- }
409
- const parsed = ChildBlockingDecisionSchema.parse(decision);
410
- if (entry.event.kind === "input" !== "value" in parsed)
411
- throw new TypeError("Child response kind does not match the pending request");
412
- await handle.respondToBlocking({ ...parsed, approvalId: entry.event.childApprovalId });
413
- presentedBlocking.delete(decision.approvalId);
414
- retiredBlocking.add(decision.approvalId);
415
- await store.appendEvent({
416
- conversationId: parentConversationId,
417
- kind: "child/state",
418
- payload: {
419
- action: "blocking-resolved",
420
- childConversationId: entry.event.childConversationId,
421
- approvalId: entry.event.approvalId,
422
- batchId: entry.batchId,
423
- ..."approved" in parsed ? { approved: parsed.approved } : { kind: "input" }
424
- }
425
- });
426
- };
427
- const respondToChildBlocking = (parentConversationId, decision) => serializeBlocking(() => respondToChildBlockingInner(parentConversationId, decision));
428
- return { retireChildBlocking, listChildBlocking, respondToChildBlocking };
429
- }
276
+ import { z as z3 } from "zod";
430
277
 
431
278
  // src/agent-runtime/children-state.ts
279
+ import { z } from "zod";
432
280
  function createChildManagerState(config) {
281
+ if (typeof config.remainingBudget !== "function")
282
+ throw new TypeError("createAgentChildManager requires remainingBudget");
283
+ if (config.maxActiveChildren === undefined)
284
+ throw new TypeError("createAgentChildManager requires maxActiveChildren");
285
+ assertPositiveSafeInteger("maxActiveChildren", config.maxActiveChildren);
433
286
  return {
434
287
  config,
435
- database: config.sqlite.database,
436
- store: config.sqlite.store,
288
+ host: config.host,
289
+ store: config.store,
437
290
  now: config.now ?? (() => new Date),
438
291
  handles: new Map,
439
- settlements: new Map
292
+ settlements: new Map,
293
+ spawning: new Map
440
294
  };
441
295
  }
442
- function currentState(state, childConversationId) {
443
- const raw = state.database.prepare("SELECT state FROM stitchkit_agent_runtime_children WHERE child_conversation_id = ?").get(childConversationId);
444
- return raw === null || raw === undefined ? undefined : AgentChildStateSchema.parse(raw.state);
445
- }
446
- function isLive(state, childConversationId) {
447
- const current = currentState(state, childConversationId);
448
- return current === "spawned" || current === "running";
296
+ var CHILD_HOST_BOUND_MS = 1e4;
297
+ async function bounded(work, fallback) {
298
+ const outcome = await withDeadline(Promise.resolve(work), CHILD_HOST_BOUND_MS);
299
+ return outcome.settled ? outcome.value : fallback;
300
+ }
301
+ async function askChildHost(what, work, onUnanswered) {
302
+ const answer = Promise.resolve().then(work);
303
+ const outcome = await withDeadline(answer.then((value) => ({ answered: true, value }), (cause) => ({ answered: false, cause })), CHILD_HOST_BOUND_MS);
304
+ if (!outcome.settled) {
305
+ onUnanswered?.(answer);
306
+ throw new Error(`The child host did not answer ${what} within ${CHILD_HOST_BOUND_MS} ms`);
307
+ }
308
+ if (!outcome.value.answered)
309
+ throw outcome.value.cause;
310
+ return outcome.value.value;
311
+ }
312
+ var stopsInFlight = new WeakMap;
313
+ function stopHandle(handle, policy) {
314
+ const inFlight = stopsInFlight.get(handle);
315
+ if (inFlight)
316
+ return inFlight;
317
+ const delivery = deliverStop(handle, policy);
318
+ stopsInFlight.set(handle, delivery);
319
+ delivery.finally(() => {
320
+ if (stopsInFlight.get(handle) === delivery)
321
+ stopsInFlight.delete(handle);
322
+ });
323
+ return delivery;
449
324
  }
450
- function settleable(state, childConversationId) {
451
- const current = currentState(state, childConversationId);
452
- return current === undefined || current === "spawned" || current === "running";
325
+ function deliverStop(handle, policy) {
326
+ return bounded(Promise.resolve().then(() => handle.stopPolicy(policy)).then(() => ({ stopped: true }), (cause) => ({ stopped: false, reason: "stop-failed", cause })), {
327
+ stopped: false,
328
+ reason: "stop-timeout",
329
+ cause: new Error(`The child host did not answer the stop within ${CHILD_HOST_BOUND_MS} ms`)
330
+ });
453
331
  }
454
- var STOP_BOUND_MS = 1e4;
455
- async function bounded(work, fallback) {
456
- let timer;
332
+ async function writeWithPurgeFallback(write) {
457
333
  try {
458
- return await Promise.race([
459
- Promise.resolve(work),
460
- new Promise((resolve) => {
461
- timer = setTimeout(() => resolve(fallback), STOP_BOUND_MS);
462
- })
463
- ]);
464
- } finally {
465
- if (timer)
466
- clearTimeout(timer);
334
+ return await write("both");
335
+ } catch (error) {
336
+ if (!(error instanceof AgentConversationPurgedError2))
337
+ throw error;
338
+ let wrote = false;
339
+ for (const side of ["parent", "child"]) {
340
+ try {
341
+ wrote = await write(side) || wrote;
342
+ } catch (inner) {
343
+ if (!(inner instanceof AgentConversationPurgedError2))
344
+ throw inner;
345
+ }
346
+ }
347
+ return wrote;
467
348
  }
468
349
  }
350
+ var CHILD_COLUMNS = `parent_conversation_id, child_conversation_id, seed_upto_seq, state,
351
+ budget_payload, usage_payload, result_reference, created_at, updated_at`;
469
352
  function listChildren(state, parentConversationId) {
470
- return state.database.prepare(`
471
- SELECT parent_conversation_id, child_conversation_id, seed_upto_seq, state,
472
- budget_payload, usage_payload, result_reference, created_at, updated_at
473
- FROM stitchkit_agent_runtime_children
474
- WHERE parent_conversation_id = ? ORDER BY created_at, child_conversation_id
475
- `).all(parentConversationId).map(parseChild);
476
- }
477
- async function updateState(state, record, next, resultReference, details = {}) {
353
+ return state.host.read(async (session) => (await session.all(`SELECT ${CHILD_COLUMNS} FROM ${state.host.tables.children}
354
+ WHERE parent_conversation_id = ? ORDER BY created_at, child_conversation_id`, [parentConversationId])).map(parseChild));
355
+ }
356
+ var LIVE_CHILD_STATES = ["spawned", "running"];
357
+ var StateRowSchema = z.object({ state: AgentChildStateSchema2 });
358
+ function transitionChild(state, record, next, options) {
359
+ const { from, absent, resultReference, details = {} } = options;
478
360
  const updatedAt = state.now().toISOString();
479
- const payload = {
361
+ const payload = ChildStateEventPayloadSchema.parse({
480
362
  childConversationId: record.childConversationId,
481
363
  state: next,
482
364
  ...resultReference && { resultReference },
483
365
  ...details
484
- };
485
- const childPayload = {
366
+ });
367
+ const childPayload = ChildStateEventPayloadSchema.parse({
486
368
  parentConversationId: record.parentConversationId,
487
369
  state: next,
488
370
  ...resultReference && { resultReference },
489
371
  ...details
490
- };
491
- const write = (audience) => state.config.sqlite.transaction(async (scope) => {
492
- scope.database.prepare(`
493
- UPDATE stitchkit_agent_runtime_children
494
- SET state = ?, result_reference = ?, updated_at = ? WHERE child_conversation_id = ?
495
- `).run(next, resultReference ?? null, updatedAt, record.childConversationId);
496
- if (audience === "both") {
372
+ });
373
+ const table = state.host.tables.children;
374
+ const write = (audience) => state.host.transaction(audience === "child" ? record.childConversationId : record.parentConversationId, async (scope) => {
375
+ const row = await scope.get(`SELECT state FROM ${table} WHERE child_conversation_id = ?`, [record.childConversationId]);
376
+ if (row === undefined) {
377
+ if (absent === "skip")
378
+ return false;
379
+ } else {
380
+ if (!from.includes(StateRowSchema.parse(row).state))
381
+ return false;
382
+ await scope.run(`UPDATE ${table} SET state = ?, result_reference = ?, updated_at = ?
383
+ WHERE child_conversation_id = ? AND state IN (${from.map(() => "?").join(", ")})`, [next, resultReference ?? null, updatedAt, record.childConversationId, ...from]);
384
+ }
385
+ if (audience === "both" || audience === "parent") {
497
386
  await scope.appendEvent({
498
387
  conversationId: record.parentConversationId,
499
388
  kind: "child/state",
@@ -501,7 +390,7 @@ async function updateState(state, record, next, resultReference, details = {}) {
501
390
  payload
502
391
  });
503
392
  }
504
- if (audience !== "row") {
393
+ if (audience === "both" || audience === "child") {
505
394
  await scope.appendEvent({
506
395
  conversationId: record.childConversationId,
507
396
  kind: "child/state",
@@ -509,87 +398,291 @@ async function updateState(state, record, next, resultReference, details = {}) {
509
398
  payload: childPayload
510
399
  });
511
400
  }
512
- });
513
- try {
514
- await write("both");
515
- } catch (error) {
516
- if (!(error instanceof AgentConversationPurgedError2))
517
- throw error;
518
- try {
519
- await write("child");
520
- } catch (inner) {
521
- if (!(inner instanceof AgentConversationPurgedError2))
522
- throw inner;
523
- await write("row");
401
+ return true;
402
+ });
403
+ return writeWithPurgeFallback(write);
404
+ }
405
+ async function activeChild(state, parentConversationId, childConversationId) {
406
+ const child = (await listChildren(state, parentConversationId)).find((record) => record.childConversationId === childConversationId);
407
+ if (!child)
408
+ throw new TypeError("Unknown child conversation for this parent");
409
+ if (child.state !== "running" && child.state !== "spawned") {
410
+ throw new TypeError("Child conversation is not active");
411
+ }
412
+ const handle = state.handles.get(childConversationId);
413
+ if (!handle)
414
+ throw new TypeError("Child host handle is unavailable");
415
+ return { child, handle };
416
+ }
417
+
418
+ // src/agent-runtime/child-blocking.ts
419
+ function askChild(bounded, handle, blockingEvents) {
420
+ return bounded(Promise.resolve().then(() => blockingEvents.call(handle)).then((reported) => ({
421
+ answered: true,
422
+ sources: reported.map((source) => AgentChildBlockingSourceSchema2.parse(source))
423
+ })).catch((cause) => ({
424
+ answered: false,
425
+ reason: "failed",
426
+ cause
427
+ })), { answered: false, reason: "timeout" });
428
+ }
429
+ function childScopedBlockingId(childConversationId, childApprovalId) {
430
+ return `${encodeURIComponent(childConversationId)}:${encodeURIComponent(childApprovalId)}`;
431
+ }
432
+ function createParentQueues() {
433
+ const queues = new Map;
434
+ return (parentConversationId, work) => {
435
+ const run = (queues.get(parentConversationId) ?? Promise.resolve()).then(work);
436
+ const tail = run.then(() => {
437
+ return;
438
+ }, () => {
439
+ return;
440
+ });
441
+ queues.set(parentConversationId, tail);
442
+ tail.then(() => {
443
+ if (queues.get(parentConversationId) === tail)
444
+ queues.delete(parentConversationId);
445
+ });
446
+ return run;
447
+ };
448
+ }
449
+ async function presentBlocking(store, parentConversationId, record, source, presentedAt) {
450
+ const approvalId = childScopedBlockingId(record.childConversationId, source.approvalId);
451
+ const batchId = source.batchId ? `${record.childConversationId}:${source.batchId}` : approvalId;
452
+ const event = AgentChildBlockingEventSchema2.parse({
453
+ parentConversationId,
454
+ childConversationId: record.childConversationId,
455
+ kind: source.kind,
456
+ approvalId,
457
+ childApprovalId: source.approvalId,
458
+ callId: source.callId,
459
+ toolName: source.toolName,
460
+ input: source.input,
461
+ batchId,
462
+ presentedAt
463
+ });
464
+ await store.appendEvent({
465
+ conversationId: parentConversationId,
466
+ kind: "child/state",
467
+ occurredAt: presentedAt,
468
+ payload: ChildStateEventPayloadSchema.parse({
469
+ action: "blocking-presented",
470
+ childConversationId: event.childConversationId,
471
+ approvalId: event.approvalId,
472
+ childApprovalId: event.childApprovalId,
473
+ kind: event.kind,
474
+ callId: event.callId,
475
+ toolName: event.toolName,
476
+ input: event.input,
477
+ batchId: event.batchId,
478
+ presentedAt
479
+ })
480
+ });
481
+ return { event, batchId };
482
+ }
483
+ function createChildBlockingRelay(input) {
484
+ const { store, now, handles, listChildren, activeChild, bounded } = input;
485
+ const presentedBlocking = new Map;
486
+ const retiredBlocking = new Map;
487
+ const answersWithHost = new Map;
488
+ const serializeBlocking = createParentQueues();
489
+ const retireChildBlocking = (childConversationId) => {
490
+ for (const [id, entry] of presentedBlocking) {
491
+ if (entry.event.childConversationId === childConversationId)
492
+ presentedBlocking.delete(id);
493
+ }
494
+ retiredBlocking.delete(childConversationId);
495
+ for (const [id, child] of answersWithHost) {
496
+ if (child === childConversationId)
497
+ answersWithHost.delete(id);
498
+ }
499
+ };
500
+ const isRetired = (childConversationId, id) => retiredBlocking.get(childConversationId)?.has(id) ?? false;
501
+ const listChildBlockingInner = async (parentConversationId) => {
502
+ const live = (await listChildren(parentConversationId)).filter((record) => record.state === "spawned" || record.state === "running");
503
+ const unavailable = [];
504
+ for (const record of live) {
505
+ const handle = handles.get(record.childConversationId);
506
+ if (!handle?.blockingEvents)
507
+ continue;
508
+ const report = await askChild(bounded, handle, handle.blockingEvents);
509
+ if (!report.answered) {
510
+ const { childConversationId } = record;
511
+ unavailable.push(report.reason === "timeout" ? { childConversationId, reason: "timeout" } : { childConversationId, reason: "failed", cause: report.cause });
512
+ continue;
513
+ }
514
+ const fresh = report.sources.filter((source) => {
515
+ const id = childScopedBlockingId(record.childConversationId, source.approvalId);
516
+ return !presentedBlocking.has(id) && !isRetired(record.childConversationId, id);
517
+ });
518
+ if (fresh.length === 0)
519
+ continue;
520
+ const presentedAt = now().toISOString();
521
+ for (const source of fresh) {
522
+ const entry = await presentBlocking(store, parentConversationId, record, source, presentedAt);
523
+ presentedBlocking.set(entry.event.approvalId, entry);
524
+ }
525
+ }
526
+ const pending = [...presentedBlocking.values()].map((entry) => entry.event).filter((event) => event.parentConversationId === parentConversationId);
527
+ return { pending, unavailable };
528
+ };
529
+ const listChildBlocking = (parentConversationId) => serializeBlocking(parentConversationId, () => listChildBlockingInner(parentConversationId));
530
+ const respondToChildBlockingInner = async (parentConversationId, decision) => {
531
+ const entry = presentedBlocking.get(decision.approvalId);
532
+ if (!entry || entry.event.parentConversationId !== parentConversationId) {
533
+ throw new TypeError("Child blocking request is missing, stale or already answered");
524
534
  }
525
- }
526
- }
527
- function activeChild(state, parentConversationId, childConversationId) {
528
- const child = listChildren(state, parentConversationId).find((record) => record.childConversationId === childConversationId);
529
- if (!child)
530
- throw new TypeError("Unknown child conversation for this parent");
531
- if (child.state !== "running" && child.state !== "spawned") {
532
- throw new TypeError("Child conversation is not active");
533
- }
534
- const handle = state.handles.get(childConversationId);
535
- if (!handle)
536
- throw new TypeError("Child host handle is unavailable");
537
- return { child, handle };
535
+ const { handle } = await activeChild(parentConversationId, entry.event.childConversationId);
536
+ const respond = handle.respondToBlocking;
537
+ if (!respond) {
538
+ throw new TypeError("Child host cannot answer blocking requests");
539
+ }
540
+ const parsed = ChildBlockingDecisionSchema.parse(decision);
541
+ if (entry.event.kind === "input" !== "value" in parsed)
542
+ throw new TypeError("Child response kind does not match the pending request");
543
+ if (answersWithHost.has(decision.approvalId))
544
+ throw new TypeError("The child host has not answered the first response to this request: an earlier answer is still with the child host");
545
+ await askChildHost("the blocking response", () => respond.call(handle, { ...parsed, approvalId: entry.event.childApprovalId }), (answer) => {
546
+ answersWithHost.set(decision.approvalId, entry.event.childConversationId);
547
+ answer.then(() => serializeBlocking(parentConversationId, async () => {
548
+ if (presentedBlocking.get(decision.approvalId) === entry)
549
+ await recordAnswered(parentConversationId, decision.approvalId, entry, parsed);
550
+ }), () => {
551
+ return;
552
+ }).catch(() => {
553
+ return;
554
+ }).finally(() => answersWithHost.delete(decision.approvalId));
555
+ });
556
+ await recordAnswered(parentConversationId, decision.approvalId, entry, parsed);
557
+ };
558
+ const recordAnswered = async (parentConversationId, approvalId, entry, parsed) => {
559
+ presentedBlocking.delete(approvalId);
560
+ const childConversationId = entry.event.childConversationId;
561
+ const retired = retiredBlocking.get(childConversationId) ?? new Set;
562
+ retired.add(approvalId);
563
+ retiredBlocking.set(childConversationId, retired);
564
+ await store.appendEvent({
565
+ conversationId: parentConversationId,
566
+ kind: "child/state",
567
+ payload: ChildStateEventPayloadSchema.parse({
568
+ action: "blocking-resolved",
569
+ childConversationId: entry.event.childConversationId,
570
+ approvalId: entry.event.approvalId,
571
+ batchId: entry.batchId,
572
+ ..."approved" in parsed ? { approved: parsed.approved } : { kind: "input" }
573
+ })
574
+ });
575
+ };
576
+ const respondToChildBlocking = (parentConversationId, decision) => serializeBlocking(parentConversationId, () => respondToChildBlockingInner(parentConversationId, decision));
577
+ return {
578
+ retireChildBlocking,
579
+ listChildBlocking,
580
+ respondToChildBlocking,
581
+ retained: { presented: presentedBlocking, retired: retiredBlocking }
582
+ };
538
583
  }
539
584
 
540
585
  // src/agent-runtime/children-control.ts
586
+ function isReachable(handle) {
587
+ const probe = handle.reachable;
588
+ if (!probe)
589
+ return Promise.resolve(true);
590
+ return bounded(Promise.resolve().then(() => probe.call(handle)).then((value) => Boolean(value), () => false), false);
591
+ }
592
+ function requestPendingStops(state, parentConversationId) {
593
+ const pending = [...state.spawning.values()].filter((spawn) => spawn.parentConversationId === parentConversationId);
594
+ for (const spawn of pending)
595
+ spawn.stopRequested = true;
596
+ return pending;
597
+ }
541
598
  async function stopChildren(state, retireChildBlocking, parentConversationId) {
542
- const records = listChildren(state, parentConversationId).filter((record) => record.state === "spawned" || record.state === "running");
543
- await Promise.all(records.map((record) => stopChild(state, retireChildBlocking, record)));
599
+ requestPendingStops(state, parentConversationId);
600
+ const records = (await listChildren(state, parentConversationId)).filter((record) => record.state === "spawned" || record.state === "running");
601
+ const pending = requestPendingStops(state, parentConversationId);
602
+ const registered = records.filter((record) => !state.spawning.has(record.childConversationId));
603
+ await Promise.all([
604
+ ...registered.map((record) => stopChild(state, retireChildBlocking, record)),
605
+ ...pending.map((spawn) => bounded(spawn.done, undefined))
606
+ ]);
544
607
  }
545
608
  async function stopChild(state, retireChildBlocking, record) {
546
609
  const startedAt = performance.now();
547
610
  const handle = state.handles.get(record.childConversationId);
548
- const reachable = handle ? handle.reachable ? await bounded(handle.reachable(), false) : true : false;
549
- if (!reachable) {
550
- if (isLive(state, record.childConversationId)) {
551
- await updateState(state, record, "lost", undefined, {
552
- stopDurationMs: Math.max(0, performance.now() - startedAt)
553
- });
554
- }
555
- retireChildBlocking(record.childConversationId);
556
- return;
557
- }
558
- await bounded(Promise.resolve(handle?.stopPolicy("parent-stopped")).then(() => true), false);
559
- if (!isLive(state, record.childConversationId))
560
- return;
561
- await updateState(state, record, "stopped", undefined, {
611
+ const reachable = handle ? await isReachable(handle) : false;
612
+ const outcome = handle && reachable ? await stopHandle(handle, "parent-stopped") : { stopped: false, reason: "unreachable" };
613
+ await recordStop(state, retireChildBlocking, record, outcome, {
562
614
  stopDurationMs: Math.max(0, performance.now() - startedAt)
563
615
  });
564
- retireChildBlocking(record.childConversationId);
565
616
  }
617
+ async function recordStop(state, retireChildBlocking, record, outcome, details) {
618
+ const { childConversationId } = record;
619
+ const settlement = state.settlements.get(childConversationId);
620
+ if (settlement?.arrived)
621
+ await Promise.allSettled([settlement.settled]);
622
+ await transitionChild(state, record, outcome.stopped ? "stopped" : "lost", {
623
+ from: LIVE_CHILD_STATES,
624
+ absent: "skip",
625
+ details: { ...details, ...!outcome.stopped && { reason: outcome.reason } }
626
+ });
627
+ settlement?.endedByStop();
628
+ if (state.settlements.get(childConversationId) === settlement)
629
+ state.settlements.delete(childConversationId);
630
+ state.handles.delete(childConversationId);
631
+ retireChildBlocking(childConversationId);
632
+ }
633
+ var messagesWithHost = new WeakMap;
566
634
  async function sendMessage(state, parentConversationId, childConversationId, message) {
567
- const { handle } = activeChild(state, parentConversationId, childConversationId);
568
- if (!handle.sendMessage)
635
+ const { handle } = await activeChild(state, parentConversationId, childConversationId);
636
+ const send = handle.sendMessage;
637
+ if (!send)
569
638
  throw new TypeError("Child host does not support messages");
570
- await handle.sendMessage(message);
571
- await state.store.appendEvent({
639
+ if ((messagesWithHost.get(handle) ?? 0) > 0)
640
+ throw new TypeError("The child host has not answered an earlier message to this child: an earlier message is still with the child host");
641
+ const journal = () => state.store.appendEvent({
572
642
  conversationId: parentConversationId,
573
643
  kind: "child/state",
574
- payload: { childConversationId, action: "message-sent" }
644
+ payload: ChildStateEventPayloadSchema.parse({
645
+ childConversationId,
646
+ action: "message-sent"
647
+ })
648
+ });
649
+ await askChildHost("the message", () => send.call(handle, message), (answer) => {
650
+ messagesWithHost.set(handle, (messagesWithHost.get(handle) ?? 0) + 1);
651
+ answer.then(journal, () => {
652
+ return;
653
+ }).catch(() => {
654
+ return;
655
+ }).finally(() => {
656
+ const left = (messagesWithHost.get(handle) ?? 1) - 1;
657
+ if (left > 0)
658
+ messagesWithHost.set(handle, left);
659
+ else
660
+ messagesWithHost.delete(handle);
661
+ });
575
662
  });
663
+ await journal();
576
664
  }
577
665
  async function interruptChild(state, retireChildBlocking, parentConversationId, childConversationId) {
578
- const { child, handle } = activeChild(state, parentConversationId, childConversationId);
666
+ const { child, handle } = await activeChild(state, parentConversationId, childConversationId);
579
667
  const startedAt = performance.now();
580
- await handle.stopPolicy("parent-interrupt");
581
- await updateState(state, child, "stopped", undefined, {
668
+ const outcome = await stopHandle(handle, "parent-interrupt");
669
+ await recordStop(state, retireChildBlocking, child, outcome, {
582
670
  policyName: "parent-interrupt",
583
671
  stopDurationMs: Math.max(0, performance.now() - startedAt)
584
672
  });
585
- retireChildBlocking(childConversationId);
586
673
  }
587
674
 
588
675
  // src/agent-runtime/children-spawn.ts
589
676
  import { randomUUID } from "node:crypto";
677
+ import { z as z2 } from "zod";
678
+ var RemainingBudgetSchema = z2.object({
679
+ usd: z2.number().nonnegative().optional(),
680
+ tokens: z2.int().nonnegative().optional(),
681
+ milliseconds: z2.int().nonnegative().optional()
682
+ }).strict();
590
683
  async function grantedBudget(state, request) {
591
- const requestedBudget = AgentChildBudgetSchema.parse(request.budget);
592
- const remaining = state.config.remainingBudget ? AgentChildBudgetSchema.parse(await state.config.remainingBudget(request.parentConversationId)) : undefined;
684
+ const requestedBudget = AgentChildBudgetSchema2.parse(request.budget);
685
+ const remaining = RemainingBudgetSchema.parse(await state.config.remainingBudget(request.parentConversationId));
593
686
  const bounded = (requested, available) => {
594
687
  if (requested === undefined)
595
688
  return available;
@@ -597,15 +690,28 @@ async function grantedBudget(state, request) {
597
690
  return requested;
598
691
  return Math.min(requested, available);
599
692
  };
600
- const usd = bounded(requestedBudget.usd, remaining?.usd);
601
- const tokens = bounded(requestedBudget.tokens, remaining?.tokens);
602
- const milliseconds = bounded(requestedBudget.milliseconds, remaining?.milliseconds);
603
- return AgentChildBudgetSchema.parse({
693
+ const usd = bounded(requestedBudget.usd, remaining.usd);
694
+ const tokens = bounded(requestedBudget.tokens, remaining.tokens);
695
+ const milliseconds = bounded(requestedBudget.milliseconds, remaining.milliseconds);
696
+ const granted = { usd, tokens, milliseconds };
697
+ const spent = Object.entries(granted).filter(([, value]) => value === 0);
698
+ if (spent.length > 0)
699
+ throw new TypeError(`The parent has no child budget left in ${spent.map(([name]) => name).join(", ")}`);
700
+ if (usd === undefined && tokens === undefined && milliseconds === undefined)
701
+ throw new TypeError("A child budget names at least one limit; the parent remainder and the request name none");
702
+ return AgentChildBudgetSchema2.parse({
604
703
  ...usd !== undefined && { usd },
605
704
  ...tokens !== undefined && { tokens },
606
705
  ...milliseconds !== undefined && { milliseconds }
607
706
  });
608
707
  }
708
+ var ActiveRowSchema = z2.object({ active: SqlIntegerSchema });
709
+ async function refuseOverLimit(state, session, parentConversationId) {
710
+ const { active } = ActiveRowSchema.parse(await session.get(`SELECT COUNT(*) AS active FROM ${state.host.tables.children}
711
+ WHERE parent_conversation_id = ? AND state IN ('spawned', 'running')`, [parentConversationId]));
712
+ if (active >= state.config.maxActiveChildren)
713
+ throw new TypeError(`The parent already has ${active} active children, the limit is ${state.config.maxActiveChildren}`);
714
+ }
609
715
  async function readSeedEvents(state, request) {
610
716
  const events = [];
611
717
  let cursor = 1;
@@ -625,70 +731,112 @@ async function readSeedEvents(state, request) {
625
731
  }
626
732
  async function persistSpawn(state, record, handle) {
627
733
  const { childConversationId, createdAt } = record;
734
+ let inserted = false;
628
735
  try {
629
- await state.config.sqlite.transaction(async (scope) => {
630
- scope.database.prepare(`
631
- INSERT INTO stitchkit_agent_runtime_children (
632
- parent_conversation_id, child_conversation_id, seed_upto_seq, state,
633
- budget_payload, usage_payload, result_reference, created_at, updated_at
634
- ) VALUES (?, ?, ?, ?, ?, ?, NULL, ?, ?)
635
- `).run(record.parentConversationId, record.childConversationId, record.seedUptoSeq, record.state, JSON.stringify(record.budget), JSON.stringify(record.usage), createdAt, createdAt);
736
+ await state.host.transaction(record.parentConversationId, async (scope) => {
737
+ await refuseOverLimit(state, scope, record.parentConversationId);
738
+ await scope.run(`INSERT INTO ${state.host.tables.children} (
739
+ parent_conversation_id, child_conversation_id, seed_upto_seq, state,
740
+ budget_payload, usage_payload, result_reference, created_at, updated_at
741
+ ) VALUES (?, ?, ?, ?, ?, ?, NULL, ?, ?)`, [
742
+ record.parentConversationId,
743
+ record.childConversationId,
744
+ record.seedUptoSeq,
745
+ record.state,
746
+ JSON.stringify(record.budget),
747
+ JSON.stringify(record.usage),
748
+ createdAt,
749
+ createdAt
750
+ ]);
636
751
  await scope.appendEvent({
637
752
  conversationId: record.parentConversationId,
638
753
  kind: "child/spawned",
639
754
  occurredAt: createdAt,
640
- payload: {
755
+ payload: ChildSpawnedEventPayloadSchema.parse({
641
756
  childConversationId,
642
757
  seedUptoSeq: record.seedUptoSeq,
643
758
  budget: record.budget
644
- }
759
+ })
645
760
  });
646
761
  });
647
- await updateState(state, record, "running");
762
+ inserted = true;
763
+ await transitionChild(state, record, "running", { from: ["spawned"], absent: "skip" });
648
764
  } catch (cause) {
649
- try {
650
- await handle.stopPolicy("spawn-persistence-failed");
651
- } catch (cleanup) {
652
- throw new AggregateError([cause, cleanup], "Child persistence and stop both failed");
653
- }
654
- try {
655
- if (isLive(state, childConversationId))
656
- await updateState(state, record, "lost", undefined, {
657
- reason: "spawn-persistence-failed"
765
+ const failures = [];
766
+ const stop = await stopHandle(handle, "spawn-persistence-failed");
767
+ if (!stop.stopped)
768
+ failures.push(stop.cause);
769
+ if (inserted) {
770
+ try {
771
+ await transitionChild(state, record, "lost", {
772
+ from: LIVE_CHILD_STATES,
773
+ absent: "skip",
774
+ details: { reason: "spawn-persistence-failed" }
658
775
  });
659
- } catch (cleanup) {
660
- throw new AggregateError([cause, cleanup], "Child stopped but persistence reconciliation failed");
776
+ } catch (cleanup) {
777
+ failures.push(cleanup);
778
+ }
661
779
  }
780
+ if (failures.length > 0)
781
+ throw new AggregateError([cause, ...failures], `Child ${childConversationId} could not be recorded, and its cleanup failed too`, { cause });
662
782
  throw cause;
663
783
  }
664
784
  }
665
785
  function watchSettlement(state, record, handle, retireChildBlocking) {
666
786
  const { childConversationId } = record;
667
787
  state.handles.set(childConversationId, handle);
668
- const settlement = handle.result.then(async (result) => {
788
+ const settle = async (next, resultReference) => {
789
+ entry.arrived = true;
669
790
  state.handles.delete(childConversationId);
670
791
  retireChildBlocking(childConversationId);
671
- if (settleable(state, childConversationId)) {
672
- await updateState(state, record, "finished", result.resultReference);
792
+ await transitionChild(state, record, next, {
793
+ from: LIVE_CHILD_STATES,
794
+ absent: "record",
795
+ ...resultReference !== undefined && { resultReference }
796
+ });
797
+ };
798
+ const settled = handle.result.then((result) => settle("finished", result.resultReference), () => settle("stopped")).finally(() => {
799
+ if (state.settlements.get(childConversationId) === entry) {
800
+ state.settlements.delete(childConversationId);
673
801
  }
674
- }, async () => {
675
- state.handles.delete(childConversationId);
676
- retireChildBlocking(childConversationId);
677
- if (settleable(state, childConversationId))
678
- await updateState(state, record, "stopped");
679
802
  });
680
- state.settlements.set(childConversationId, settlement);
681
- settlement.catch(() => {
803
+ const stopped = Promise.withResolvers();
804
+ const entry = {
805
+ settled,
806
+ ended: Promise.race([settled, stopped.promise]),
807
+ endedByStop: () => stopped.resolve(),
808
+ arrived: false
809
+ };
810
+ state.settlements.set(childConversationId, entry);
811
+ settled.catch(() => {
682
812
  return;
683
813
  });
684
814
  }
685
815
  async function spawnChild(state, retireChildBlocking, request) {
816
+ const childConversationId = request.childConversationId ?? randomUUID();
817
+ if (state.spawning.has(childConversationId))
818
+ throw new TypeError(`Child ${childConversationId} is already being spawned`);
819
+ const done = Promise.withResolvers();
820
+ const pending = {
821
+ parentConversationId: request.parentConversationId,
822
+ stopRequested: false,
823
+ done: done.promise
824
+ };
825
+ state.spawning.set(childConversationId, pending);
826
+ try {
827
+ await state.host.read((session) => refuseOverLimit(state, session, request.parentConversationId));
828
+ return await spawnAdmitted(state, retireChildBlocking, request, childConversationId, pending);
829
+ } finally {
830
+ state.spawning.delete(childConversationId);
831
+ done.resolve();
832
+ }
833
+ }
834
+ async function spawnAdmitted(state, retireChildBlocking, request, childConversationId, pending) {
686
835
  const budget = await grantedBudget(state, request);
687
836
  const events = await readSeedEvents(state, request);
688
837
  const seedUptoSeq = events.at(-1)?.seq ?? 0;
689
- const childConversationId = request.childConversationId ?? randomUUID();
690
838
  const createdAt = state.now().toISOString();
691
- const record = AgentChildRecordSchema.parse({
839
+ const record = AgentChildRecordSchema2.parse({
692
840
  parentConversationId: request.parentConversationId,
693
841
  childConversationId,
694
842
  seedUptoSeq,
@@ -706,6 +854,8 @@ async function spawnChild(state, retireChildBlocking, request) {
706
854
  projections: [],
707
855
  spills: []
708
856
  });
857
+ if (pending.stopRequested)
858
+ throw new Error(`The parent ${record.parentConversationId} was stopped before child ${childConversationId} started; no child was spawned`);
709
859
  const handle = await state.config.spawn({
710
860
  parentConversationId: record.parentConversationId,
711
861
  childConversationId,
@@ -718,67 +868,148 @@ async function spawnChild(state, retireChildBlocking, request) {
718
868
  });
719
869
  await persistSpawn(state, record, handle);
720
870
  watchSettlement(state, record, handle, retireChildBlocking);
721
- return { ...record, state: "running", updatedAt: state.now().toISOString() };
871
+ const running = {
872
+ ...record,
873
+ state: "running",
874
+ updatedAt: state.now().toISOString()
875
+ };
876
+ if (!pending.stopRequested)
877
+ return running;
878
+ await stopChild(state, retireChildBlocking, running);
879
+ const stopped = (await listChildren(state, record.parentConversationId)).find((child) => child.childConversationId === childConversationId);
880
+ if (!stopped)
881
+ throw new TypeError(`Child ${childConversationId} was stopped and its record is gone`);
882
+ return stopped;
722
883
  }
723
884
 
724
885
  // src/agent-runtime/children-usage.ts
725
- async function recordStepUsage(state, request) {
726
- const { database, handles, now } = state;
727
- const raw = database.prepare(`
728
- SELECT parent_conversation_id, child_conversation_id, seed_upto_seq, state,
729
- budget_payload, usage_payload, result_reference, created_at, updated_at
730
- FROM stitchkit_agent_runtime_children WHERE child_conversation_id = ?
731
- `).get(request.childConversationId);
732
- if (raw === null || raw === undefined)
733
- throw new TypeError("Unknown child conversation");
734
- const record = parseChild(raw);
735
- const measured = usageNumbers(request.usage);
736
- if (record.budget.tokens !== undefined && measured.tokens === undefined) {
737
- throw new TypeError("Cannot enforce child token budget without measured token usage");
738
- }
739
- if (record.budget.usd !== undefined && measured.usd === undefined) {
740
- throw new TypeError("Cannot enforce child USD budget without USD usage");
741
- }
886
+ function accumulate(record, measured, elapsedMs) {
742
887
  const usage = {
743
888
  tokens: record.usage.tokens + (measured.tokens ?? 0),
744
889
  usd: record.usage.usd + (measured.usd ?? 0),
745
- milliseconds: record.usage.milliseconds + request.elapsedMs
890
+ milliseconds: record.usage.milliseconds + elapsedMs
746
891
  };
747
- const updatedAt = now().toISOString();
748
892
  const overrun = {
749
893
  tokens: Math.max(0, usage.tokens - (record.budget.tokens ?? Number.POSITIVE_INFINITY)),
750
894
  usd: Math.max(0, usage.usd - (record.budget.usd ?? Number.POSITIVE_INFINITY)),
751
895
  milliseconds: Math.max(0, usage.milliseconds - (record.budget.milliseconds ?? Number.POSITIVE_INFINITY))
752
896
  };
753
897
  const stop = record.budget.tokens !== undefined && usage.tokens >= record.budget.tokens || record.budget.usd !== undefined && usage.usd >= record.budget.usd || record.budget.milliseconds !== undefined && usage.milliseconds >= record.budget.milliseconds;
898
+ return { usage, overrun, stop };
899
+ }
900
+ async function recordStepUsage(state, retireChildBlocking, request) {
901
+ const { host, handles, now } = state;
902
+ const select = `SELECT ${CHILD_COLUMNS} FROM ${host.tables.children} WHERE child_conversation_id = ?`;
903
+ const raw = await host.read((session) => session.get(select, [request.childConversationId]));
904
+ if (raw === undefined)
905
+ throw new TypeError("Unknown child conversation");
906
+ const before = parseChild(raw);
907
+ const measured = usageNumbers(request.usage);
908
+ if (before.budget.tokens !== undefined && measured.tokens === undefined) {
909
+ throw new TypeError("Cannot enforce child token budget without measured token usage");
910
+ }
911
+ if (before.budget.usd !== undefined && measured.usd === undefined) {
912
+ throw new TypeError("Cannot enforce child USD budget without USD usage");
913
+ }
914
+ const planned = accumulate(before, measured, request.elapsedMs);
754
915
  const handle = handles.get(request.childConversationId);
755
916
  let enforced = false;
756
- if (stop && handle) {
757
- enforced = await bounded(Promise.resolve().then(() => handle.stopPolicy("child-budget")).then(() => true, () => false), false);
758
- }
759
- const payload = {
760
- childConversationId: record.childConversationId,
761
- state: "running",
762
- usage,
763
- overrun,
764
- ...stop && { policyName: "child-budget", enforced }
917
+ let attemptedStop = false;
918
+ let stopDurationMs = 0;
919
+ const deliverStop = async (target) => {
920
+ attemptedStop = true;
921
+ const startedAt = performance.now();
922
+ const delivered = (await stopHandle(target, "child-budget")).stopped;
923
+ stopDurationMs = Math.max(0, performance.now() - startedAt);
924
+ return delivered;
765
925
  };
766
- await state.config.sqlite.transaction(async (scope) => {
767
- scope.database.prepare("UPDATE stitchkit_agent_runtime_children SET usage_payload = ?, updated_at = ? WHERE child_conversation_id = ?").run(JSON.stringify(usage), updatedAt, request.childConversationId);
926
+ if (planned.stop && handle)
927
+ enforced = await deliverStop(handle);
928
+ const updatedAt = now().toISOString();
929
+ const result = await host.transaction(before.parentConversationId, async (scope) => {
930
+ const current = await scope.get(select, [request.childConversationId]);
931
+ if (current === undefined)
932
+ throw new TypeError("Unknown child conversation");
933
+ const row = parseChild(current);
934
+ const { usage, overrun, stop } = accumulate(row, measured, request.elapsedMs);
935
+ const delivered = stop && enforced;
936
+ await scope.run(`UPDATE ${host.tables.children} SET usage_payload = ?, updated_at = ? WHERE child_conversation_id = ?`, [JSON.stringify(usage), updatedAt, request.childConversationId]);
937
+ const payload = ChildStateEventPayloadSchema.parse({
938
+ childConversationId: before.childConversationId,
939
+ state: row.state,
940
+ usage,
941
+ overrun,
942
+ ...stop && { policyName: "child-budget", enforced: delivered }
943
+ });
944
+ const childPayload = ChildStateEventPayloadSchema.parse({
945
+ parentConversationId: before.parentConversationId,
946
+ ...payload
947
+ });
768
948
  await scope.appendEvent({
769
- conversationId: record.parentConversationId,
949
+ conversationId: before.parentConversationId,
770
950
  kind: "child/state",
771
951
  occurredAt: updatedAt,
772
952
  payload
773
953
  });
774
954
  await scope.appendEvent({
775
- conversationId: record.childConversationId,
955
+ conversationId: before.childConversationId,
776
956
  kind: "child/state",
777
957
  occurredAt: updatedAt,
778
- payload: { parentConversationId: record.parentConversationId, ...payload }
958
+ payload: childPayload
779
959
  });
960
+ return { stop, enforced: delivered, usage, overrun, state: row.state };
961
+ });
962
+ let finalEnforced = result.enforced;
963
+ const postHandle = handles.get(request.childConversationId);
964
+ if (result.stop && !attemptedStop && postHandle) {
965
+ finalEnforced = await deliverStop(postHandle);
966
+ if (finalEnforced) {
967
+ await recordBudgetEnforced(state, before, result);
968
+ }
969
+ }
970
+ if (finalEnforced) {
971
+ await recordStop(state, retireChildBlocking, before, { stopped: true }, { policyName: "child-budget", stopDurationMs });
972
+ }
973
+ return {
974
+ stop: result.stop,
975
+ enforced: finalEnforced,
976
+ ...result.stop && { policyName: "child-budget" },
977
+ overrun: result.overrun
978
+ };
979
+ }
980
+ async function recordBudgetEnforced(state, record, recorded) {
981
+ const occurredAt = state.now().toISOString();
982
+ const payload = ChildStateEventPayloadSchema.parse({
983
+ childConversationId: record.childConversationId,
984
+ state: recorded.state,
985
+ usage: recorded.usage,
986
+ overrun: recorded.overrun,
987
+ policyName: "child-budget",
988
+ enforced: true
989
+ });
990
+ const childPayload = ChildStateEventPayloadSchema.parse({
991
+ parentConversationId: record.parentConversationId,
992
+ ...payload
780
993
  });
781
- return { stop, enforced, ...stop && { policyName: "child-budget" }, overrun };
994
+ await writeWithPurgeFallback((audience) => state.host.transaction(audience === "child" ? record.childConversationId : record.parentConversationId, async (scope) => {
995
+ if (audience === "both" || audience === "parent") {
996
+ await scope.appendEvent({
997
+ conversationId: record.parentConversationId,
998
+ kind: "child/state",
999
+ occurredAt,
1000
+ payload
1001
+ });
1002
+ }
1003
+ if (audience === "both" || audience === "child") {
1004
+ await scope.appendEvent({
1005
+ conversationId: record.childConversationId,
1006
+ kind: "child/state",
1007
+ occurredAt,
1008
+ payload: childPayload
1009
+ });
1010
+ }
1011
+ return true;
1012
+ }));
782
1013
  }
783
1014
  // src/agent-runtime/child-budget-policy.ts
784
1015
  function agentChildBudgetStopPolicy(input) {
@@ -786,18 +1017,17 @@ function agentChildBudgetStopPolicy(input) {
786
1017
  let lastBoundary = performance.now();
787
1018
  return {
788
1019
  name: "child-budget",
789
- when: async ({ steps }) => {
1020
+ when: async ({ steps, selectedModel }) => {
790
1021
  const step = steps.at(-1);
791
1022
  if (!step || steps.length <= stepsSeen)
792
1023
  return false;
793
1024
  stepsSeen = steps.length;
794
- const elapsedMs = Math.max(0, performance.now() - lastBoundary);
1025
+ const elapsedMs = Math.round(Math.max(0, performance.now() - lastBoundary));
795
1026
  lastBoundary = performance.now();
796
- const usage = normalizeSdkUsage(step.usage);
797
- const cost = input.cost?.({ usage: step.usage });
1027
+ const usage = normalizeStepUsage(selectedModel, step.usage, step.providerMetadata);
798
1028
  const boundary = await input.manager.recordStepUsage({
799
1029
  childConversationId: input.childConversationId,
800
- usage: { ...usage, ...cost && { cost } },
1030
+ usage,
801
1031
  elapsedMs
802
1032
  });
803
1033
  return boundary.stop;
@@ -806,7 +1036,7 @@ function agentChildBudgetStopPolicy(input) {
806
1036
  }
807
1037
 
808
1038
  // src/agent-runtime/children.ts
809
- function createSqliteAgentChildManager(input) {
1039
+ function createAgentChildManager(input) {
810
1040
  const state = createChildManagerState(input);
811
1041
  const list = (parentConversationId) => listChildren(state, parentConversationId);
812
1042
  const { retireChildBlocking, listChildBlocking, respondToChildBlocking } = createChildBlockingRelay({
@@ -820,12 +1050,12 @@ function createSqliteAgentChildManager(input) {
820
1050
  return {
821
1051
  spawnChild: (request) => spawnChild(state, retireChildBlocking, request),
822
1052
  listChildren: list,
823
- recordStepUsage: (request) => recordStepUsage(state, request),
1053
+ recordStepUsage: (request) => recordStepUsage(state, retireChildBlocking, request),
824
1054
  stopChildren: (parentConversationId) => stopChildren(state, retireChildBlocking, parentConversationId),
825
1055
  sendMessage: (parentConversationId, childConversationId, message) => sendMessage(state, parentConversationId, childConversationId, message),
826
1056
  interruptChild: (parentConversationId, childConversationId) => interruptChild(state, retireChildBlocking, parentConversationId, childConversationId),
827
1057
  waitChild: async (childConversationId) => {
828
- await state.settlements.get(childConversationId);
1058
+ await state.settlements.get(childConversationId)?.ended;
829
1059
  },
830
1060
  listChildBlocking,
831
1061
  respondToChildBlocking
@@ -833,7 +1063,7 @@ function createSqliteAgentChildManager(input) {
833
1063
  }
834
1064
 
835
1065
  // src/agent-runtime/child-tools.ts
836
- function childTool(manager, fork) {
1066
+ function childTool({ manager, run }, conversationId, fork) {
837
1067
  return defineAgentTool({
838
1068
  name: fork ? "subagent_fork" : "subagent",
839
1069
  description: fork ? "Run a child conversation seeded from the parent through one exact event sequence." : "Run a child conversation seeded from the current durable parent history.",
@@ -842,30 +1072,30 @@ function childTool(manager, fork) {
842
1072
  action: fork ? "fork" : "spawn",
843
1073
  method: "POST"
844
1074
  },
845
- input: z2.object({
846
- parentConversationId: z2.string().min(1),
847
- childInput: z2.json(),
848
- budget: AgentChildBudgetSchema,
849
- seedUptoSeq: z2.int().positive().optional()
1075
+ input: z3.object({
1076
+ childInput: z3.json(),
1077
+ budget: AgentChildBudgetSchema2,
1078
+ seedUptoSeq: z3.int().positive().optional()
850
1079
  }).strict(),
851
- output: z2.object({
852
- childConversationId: z2.string(),
853
- state: z2.string(),
854
- resultReference: z2.string().optional()
1080
+ output: z3.object({
1081
+ childConversationId: z3.string(),
1082
+ state: z3.string(),
1083
+ resultReference: z3.string().optional()
855
1084
  }),
856
- transports: ["AGENT"],
1085
+ expose: ["AGENT"],
857
1086
  handler: async ({ input }) => {
858
1087
  if (fork && input.seedUptoSeq === undefined) {
859
1088
  throw new TypeError("subagent_fork requires seedUptoSeq");
860
1089
  }
1090
+ run.signal.throwIfAborted();
861
1091
  const child = await manager.spawnChild({
862
- parentConversationId: input.parentConversationId,
1092
+ parentConversationId: conversationId,
863
1093
  childInput: input.childInput,
864
1094
  budget: input.budget,
865
1095
  ...input.seedUptoSeq !== undefined && { seedUptoSeq: input.seedUptoSeq }
866
1096
  });
867
1097
  await manager.waitChild(child.childConversationId);
868
- const finished = manager.listChildren(input.parentConversationId).find((record) => record.childConversationId === child.childConversationId);
1098
+ const finished = (await manager.listChildren(conversationId)).find((record) => record.childConversationId === child.childConversationId);
869
1099
  if (!finished)
870
1100
  throw new Error("Child record disappeared after settlement");
871
1101
  return {
@@ -876,34 +1106,33 @@ function childTool(manager, fork) {
876
1106
  }
877
1107
  });
878
1108
  }
879
- function createAgentChildTools(manager) {
1109
+ function createAgentChildTools(config) {
1110
+ const { manager } = config;
1111
+ const conversationId = conversationOfRun(config.run, "createAgentChildTools");
880
1112
  return [
881
- childTool(manager, false),
882
- childTool(manager, true),
1113
+ childTool(config, conversationId, false),
1114
+ childTool(config, conversationId, true),
883
1115
  defineAgentTool({
884
1116
  name: "list_agents",
885
- description: "List the durable child graph for one parent conversation.",
1117
+ description: "List the durable child graph of this conversation.",
886
1118
  identity: { serviceName: "agent-children", action: "list", method: "GET" },
887
- input: z2.object({ parentConversationId: z2.string().min(1) }).strict(),
888
- output: z2.object({ children: z2.array(AgentChildRecordSchema) }),
889
- transports: ["AGENT"],
890
- handler: ({ input }) => ({
891
- children: [...manager.listChildren(input.parentConversationId)]
892
- })
1119
+ input: z3.object({}).strict(),
1120
+ output: z3.object({ children: z3.array(AgentChildRecordSchema2) }),
1121
+ expose: ["AGENT"],
1122
+ handler: async () => ({ children: [...await manager.listChildren(conversationId)] })
893
1123
  }),
894
1124
  defineAgentTool({
895
1125
  name: "send_message",
896
1126
  description: "Send one follow-up input to an active child conversation.",
897
1127
  identity: { serviceName: "agent-children", action: "message", method: "POST" },
898
- input: z2.object({
899
- parentConversationId: z2.string().min(1),
900
- childConversationId: z2.string().min(1),
901
- input: z2.json()
1128
+ input: z3.object({
1129
+ childConversationId: z3.string().min(1),
1130
+ input: z3.json()
902
1131
  }).strict(),
903
- output: z2.object({ sent: z2.literal(true) }),
904
- transports: ["AGENT"],
1132
+ output: z3.object({ sent: z3.literal(true) }),
1133
+ expose: ["AGENT"],
905
1134
  handler: async ({ input }) => {
906
- await manager.sendMessage(input.parentConversationId, input.childConversationId, input.input);
1135
+ await manager.sendMessage(conversationId, input.childConversationId, input.input);
907
1136
  return { sent: true };
908
1137
  }
909
1138
  }),
@@ -911,14 +1140,11 @@ function createAgentChildTools(manager) {
911
1140
  name: "interrupt_agent",
912
1141
  description: "Stop one active child conversation at a durable policy boundary.",
913
1142
  identity: { serviceName: "agent-children", action: "interrupt", method: "POST" },
914
- input: z2.object({
915
- parentConversationId: z2.string().min(1),
916
- childConversationId: z2.string().min(1)
917
- }).strict(),
918
- output: z2.object({ interrupted: z2.literal(true) }),
919
- transports: ["AGENT"],
1143
+ input: z3.object({ childConversationId: z3.string().min(1) }).strict(),
1144
+ output: z3.object({ interrupted: z3.literal(true) }),
1145
+ expose: ["AGENT"],
920
1146
  handler: async ({ input }) => {
921
- await manager.interruptChild(input.parentConversationId, input.childConversationId);
1147
+ await manager.interruptChild(conversationId, input.childConversationId);
922
1148
  return { interrupted: true };
923
1149
  }
924
1150
  })
@@ -999,7 +1225,7 @@ function structuredCompaction(config) {
999
1225
  });
1000
1226
  const summary = config.schema.parse(rawSummary);
1001
1227
  if (input.signal.aborted)
1002
- throw input.signal.reason;
1228
+ throw abortReason(input.signal);
1003
1229
  const summaryMessage = config.createSummaryMessage({
1004
1230
  conversationId: input.conversationId,
1005
1231
  summary,
@@ -1024,36 +1250,6 @@ function structuredCompaction(config) {
1024
1250
  return { outcome: "conflict", snapshot: lastSnapshot, attempts: maxAttempts };
1025
1251
  };
1026
1252
  }
1027
- // src/agent-runtime/deferred-tool-types.ts
1028
- import { z as z3 } from "zod";
1029
- var DeferredAgentToolSearchInputSchema = z3.object({
1030
- query: z3.string().min(1).describe("An exact tool name, or words describing the tool. Matched as one phrase first, then word by word."),
1031
- reason: z3.enum(["inactive_call"]).optional().describe("Written by the runtime. Leave it out.")
1032
- });
1033
- var DeferredAgentToolMatchSchema = z3.object({
1034
- name: z3.string(),
1035
- description: z3.string()
1036
- });
1037
- var DeferredAgentToolReceiptSchema = z3.object({
1038
- schemaVersion: z3.literal(1),
1039
- kind: z3.literal("stitchkit.deferred-tool-selection"),
1040
- status: z3.enum(["SELECTED", "SEARCH_REQUIRED", "NO_MATCH", "SELECTION_REFUSED"]),
1041
- runId: z3.string(),
1042
- surfaceKey: z3.string(),
1043
- selected: z3.array(z3.string()),
1044
- matches: z3.array(DeferredAgentToolMatchSchema),
1045
- truncated: z3.boolean()
1046
- }).superRefine((receipt, context) => {
1047
- const selected = receipt.status === "SELECTED" || receipt.status === "SEARCH_REQUIRED";
1048
- if (selected !== receipt.selected.length > 0) {
1049
- context.addIssue({
1050
- code: "custom",
1051
- path: ["selected"],
1052
- message: `${receipt.status} receipt has inconsistent selected tools`
1053
- });
1054
- }
1055
- });
1056
-
1057
1253
  // src/agent-runtime/deferred-tool-selection.ts
1058
1254
  var encoder = new TextEncoder;
1059
1255
  function utf8Bytes(value) {
@@ -1122,7 +1318,7 @@ function latestSelection(messages, searchName, runId, surface, maxSelectedTools)
1122
1318
  continue;
1123
1319
  if (part.output.type !== "json")
1124
1320
  continue;
1125
- const parsed = DeferredAgentToolReceiptSchema.safeParse(part.output.value);
1321
+ const parsed = DeferredAgentToolReceiptSchema2.safeParse(part.output.value);
1126
1322
  if (!parsed.success || parsed.data.runId !== runId || parsed.data.surfaceKey !== surface.key)
1127
1323
  continue;
1128
1324
  const known = uniqueKnown(parsed.data.selected, surface);
@@ -1149,9 +1345,9 @@ function placeholderDeferredSearch(name) {
1149
1345
  name,
1150
1346
  description,
1151
1347
  identity: { serviceName: "agent-runtime", action: "deferred-tool-search", method: "POST" },
1152
- input: DeferredAgentToolSearchInputSchema,
1153
- output: DeferredAgentToolReceiptSchema,
1154
- transports: ["AGENT"],
1348
+ input: DeferredAgentToolSearchInputSchema2,
1349
+ output: DeferredAgentToolReceiptSchema2,
1350
+ expose: ["AGENT"],
1155
1351
  handler: () => ({
1156
1352
  schemaVersion: 1,
1157
1353
  kind: "stitchkit.deferred-tool-selection",
@@ -1169,9 +1365,9 @@ function createDeferredSearchTool(config, runContext, surface) {
1169
1365
  name: config.search.name,
1170
1366
  description,
1171
1367
  identity: { serviceName: "agent-runtime", action: "deferred-tool-search", method: "POST" },
1172
- input: DeferredAgentToolSearchInputSchema,
1173
- output: DeferredAgentToolReceiptSchema,
1174
- transports: ["AGENT"],
1368
+ input: DeferredAgentToolSearchInputSchema2,
1369
+ output: DeferredAgentToolReceiptSchema2,
1370
+ expose: ["AGENT"],
1175
1371
  handler: async ({ input }) => {
1176
1372
  const queryOversized = utf8Bytes(input.query) > config.search.maxQueryBytes;
1177
1373
  const inactiveCall = input.reason === "inactive_call" && surface.byName.has(input.query);
@@ -1266,14 +1462,33 @@ function resolveSurface(config, surfaces, runContext) {
1266
1462
  throw new Error(`Unknown deferred Agent tool surface "${key}"`);
1267
1463
  return surface;
1268
1464
  }
1269
- function resolveAllSurfaces(config) {
1465
+ var PROJECTION_KEYS = ["extend", "flattenUnionInput", "inputRecursionDepth"];
1466
+ function surfaceProjection(config) {
1467
+ return {
1468
+ ...config.extend !== undefined && { extend: config.extend },
1469
+ ...config.flattenUnionInput !== undefined && {
1470
+ flattenUnionInput: config.flattenUnionInput
1471
+ },
1472
+ ...config.inputRecursionDepth !== undefined && {
1473
+ inputRecursionDepth: config.inputRecursionDepth
1474
+ }
1475
+ };
1476
+ }
1477
+ function refuseMountProjection(mountConfig) {
1478
+ for (const key of PROJECTION_KEYS) {
1479
+ if (key in mountConfig)
1480
+ throw new TypeError(`createDeferredAgentToolSurface.mount: ${key} belongs to createDeferredAgentToolSurface, where maxSchemaBytes measures the schemas it shapes`);
1481
+ }
1482
+ }
1483
+ function resolveAllSurfaces(config, projection) {
1270
1484
  const placeholderSearch = placeholderDeferredSearch(config.search.name);
1271
1485
  const surfaces = new Map;
1272
1486
  for (const [key, definition] of Object.entries(configuredSurfaces(config))) {
1273
1487
  const runtimeTools = executableAgentRuntimeTools(definition.runtimeTools ?? []);
1274
1488
  const fullManifest = buildToolManifest2({
1275
- ...definition,
1489
+ ...definition.services && { services: definition.services },
1276
1490
  runtimeTools: [...runtimeTools, placeholderSearch],
1491
+ ...projection,
1277
1492
  transport: "AGENT"
1278
1493
  });
1279
1494
  const searchEntry = fullManifest.find((entry) => entry.name === config.search.name);
@@ -1339,10 +1554,13 @@ function createDeferredAgentToolSurface(config) {
1339
1554
  positive("activation.maxSelectedTools", config.activation.maxSelectedTools);
1340
1555
  positive("activation.maxActiveTools", config.activation.maxActiveTools);
1341
1556
  positive("activation.maxSchemaBytes", config.activation.maxSchemaBytes);
1342
- const surfaces = resolveAllSurfaces(config);
1557
+ const projection = surfaceProjection(config);
1558
+ const surfaces = resolveAllSurfaces(config, projection);
1343
1559
  assertConstructionBudgets(config, surfaces);
1344
1560
  return {
1345
- mount(runContext, mountConfig = {}) {
1561
+ mount(runContext, mountConfig) {
1562
+ resolveToolAccess("createDeferredAgentToolSurface.mount", mountConfig);
1563
+ refuseMountProjection(mountConfig);
1346
1564
  const surface = resolveSurface(config, surfaces, runContext);
1347
1565
  const runtimeTools = [
1348
1566
  ...executableAgentRuntimeTools(surface.definition.runtimeTools ?? []),
@@ -1350,6 +1568,7 @@ function createDeferredAgentToolSurface(config) {
1350
1568
  ];
1351
1569
  const tools = mountAgent2([...surface.definition.services ?? []], {
1352
1570
  ...mountConfig,
1571
+ ...projection,
1353
1572
  runtimeTools
1354
1573
  });
1355
1574
  registerDeferredToolCatalog(tools, config.search.name, new Set(surface.byName.keys()));
@@ -1399,213 +1618,75 @@ function createDeferredAgentToolSurface(config) {
1399
1618
  }
1400
1619
  };
1401
1620
  }
1402
- // src/agent-runtime/event-search.ts
1403
- import { z as z4 } from "zod";
1404
- var AgentEventSearchResultSchema = z4.object({
1405
- conversationId: z4.string().min(1),
1406
- seq: z4.int().positive(),
1407
- occurredAt: z4.string(),
1408
- snippet: z4.string()
1409
- }).strict();
1410
- var SearchRowSchema = z4.object({
1411
- conversation_id: z4.string(),
1412
- event_seq: z4.int().positive(),
1413
- occurred_at: z4.string(),
1414
- snippet: z4.string()
1415
- });
1416
- function literalFtsQuery(query) {
1417
- const terms = query.split(/\s+/u).filter((term) => /[\p{L}\p{N}]/u.test(term));
1418
- if (terms.length === 0)
1419
- throw new TypeError("Event search query must contain searchable terms");
1420
- return terms.map((term) => `"${term.replaceAll('"', '""')}"`).join(" AND ");
1421
- }
1422
- function createSqliteAgentEventSearch(input) {
1423
- return async (request) => {
1424
- if (request.query.trim().length === 0)
1425
- throw new TypeError("Event search query must not be empty");
1426
- const limit = Math.min(request.limit ?? 20, 200);
1427
- const target = request.conversationId ?? (input.authorizeConversation ? undefined : request.requestingConversationId);
1428
- const values = [literalFtsQuery(request.query)];
1429
- const targetClause = target ? "AND f.conversation_id = ?" : "";
1430
- if (target)
1431
- values.push(target);
1432
- const sinceClause = request.since ? "AND f.occurred_at >= ?" : "";
1433
- if (request.since)
1434
- values.push(z4.iso.datetime({ offset: true }).parse(request.since));
1435
- const page = limit * 4;
1436
- const candidatesFrom = (offset) => input.database.prepare(`
1437
- SELECT f.conversation_id, f.event_seq, f.occurred_at,
1438
- snippet(stitchkit_agent_runtime_events_fts, 3, '[', ']', ' … ', 24) AS snippet
1439
- FROM stitchkit_agent_runtime_events_fts AS f
1440
- WHERE stitchkit_agent_runtime_events_fts MATCH ? ${targetClause} ${sinceClause}
1441
- ORDER BY bm25(stitchkit_agent_runtime_events_fts), f.occurred_at DESC, f.rowid
1442
- LIMIT ? OFFSET ?
1443
- `).all(...values, page, offset).map((row) => SearchRowSchema.parse(row));
1444
- const authorization = new Map;
1445
- const results = [];
1446
- let offset = 0;
1447
- let candidates = candidatesFrom(offset);
1448
- while (candidates.length > 0 && results.length < limit) {
1449
- for (const row of candidates) {
1450
- if (row.conversation_id !== request.requestingConversationId) {
1451
- let allowed = authorization.get(row.conversation_id);
1452
- if (allowed === undefined) {
1453
- allowed = input.authorizeConversation ? await input.authorizeConversation({
1454
- requestingConversationId: request.requestingConversationId,
1455
- targetConversationId: row.conversation_id
1456
- }) : false;
1457
- authorization.set(row.conversation_id, allowed);
1458
- }
1459
- if (!allowed)
1460
- continue;
1461
- }
1462
- results.push(AgentEventSearchResultSchema.parse({
1463
- conversationId: row.conversation_id,
1464
- seq: row.event_seq,
1465
- occurredAt: row.occurred_at,
1466
- snippet: row.snippet
1467
- }));
1468
- if (results.length === limit)
1469
- break;
1470
- }
1471
- offset += page;
1472
- candidates = results.length < limit ? candidatesFrom(offset) : [];
1473
- }
1474
- return results;
1475
- };
1476
- }
1477
- // src/agent-runtime/event-search-tools.ts
1478
- import { z as z5 } from "zod";
1479
- function createAgentEventSearchTools(input) {
1480
- const EventAddressSchema = z5.object({ conversationId: z5.string(), seq: z5.int().positive() }).strict();
1481
- const EventOutputSchema = z5.object({
1482
- conversationId: z5.string(),
1483
- seq: z5.int().positive(),
1484
- kind: z5.string(),
1485
- occurredAt: z5.string(),
1486
- payload: z5.json()
1487
- }).strict();
1488
- const readExact = async (address) => {
1489
- if (address.conversationId !== input.conversationId) {
1490
- const allowed = await input.authorizeConversation?.({
1491
- requestingConversationId: input.conversationId,
1492
- targetConversationId: address.conversationId
1493
- });
1494
- if (!allowed)
1495
- throw new TypeError("Event address is outside the authorized conversation");
1496
- }
1497
- const page = await input.store.readEvents({
1498
- conversationId: address.conversationId,
1499
- fromSeq: address.seq,
1500
- toSeq: address.seq,
1501
- limit: 1
1502
- });
1503
- const event = page.items[0];
1504
- if (!event || event.seq !== address.seq)
1505
- throw new TypeError("Unknown event address");
1506
- return {
1507
- conversationId: event.conversationId,
1508
- seq: event.seq,
1509
- kind: event.kind,
1510
- occurredAt: event.occurredAt,
1511
- payload: event.payload
1512
- };
1621
+ // src/agent-runtime/invocation-spend.ts
1622
+ function modelInvocationSpendAttribution() {
1623
+ const attempt = currentModelInvocationAttempt2();
1624
+ if (!attempt)
1625
+ return;
1626
+ return {
1627
+ conversationId: attempt.conversationId,
1628
+ invocationId: attempt.invocationId,
1629
+ invocationAttemptId: attempt.attemptId,
1630
+ step: attempt.step,
1631
+ ...attempt.runId !== undefined && { runId: attempt.runId }
1513
1632
  };
1514
- return [
1515
- defineAgentTool({
1516
- name: "session_search",
1517
- description: "Search authorized durable conversation events and return exact addresses.",
1518
- identity: { serviceName: "agent-events", action: "search", method: "POST" },
1519
- input: z5.object({
1520
- query: z5.string().min(1),
1521
- conversationId: z5.string().min(1).optional(),
1522
- since: z5.iso.datetime({ offset: true }).optional(),
1523
- limit: z5.int().positive().max(200).optional()
1524
- }).strict(),
1525
- output: z5.object({ results: z5.array(AgentEventSearchResultSchema) }).strict(),
1526
- transports: ["AGENT"],
1527
- handler: async ({ input: request }) => ({
1528
- results: [
1529
- ...await input.search({
1530
- requestingConversationId: input.conversationId,
1531
- ...request
1532
- })
1533
- ]
1534
- })
1535
- }),
1536
- defineAgentTool({
1537
- name: "session_trace",
1538
- description: "Read a bounded contiguous slice of this conversation event trace.",
1539
- identity: { serviceName: "agent-events", action: "trace", method: "GET" },
1540
- input: z5.object({
1541
- fromSeq: z5.int().positive().optional(),
1542
- toSeq: z5.int().positive().optional(),
1543
- limit: z5.int().positive().max(1000).default(100)
1544
- }).strict(),
1545
- output: z5.object({ events: z5.array(EventOutputSchema), nextSeq: z5.number().optional() }),
1546
- transports: ["AGENT"],
1547
- handler: async ({ input: request }) => {
1548
- const page = await input.store.readEvents({
1549
- conversationId: input.conversationId,
1550
- ...request
1551
- });
1552
- return {
1553
- events: page.items.map((event) => ({
1554
- conversationId: event.conversationId,
1555
- seq: event.seq,
1556
- kind: event.kind,
1557
- occurredAt: event.occurredAt,
1558
- payload: event.payload
1559
- })),
1560
- ...page.nextSeq !== undefined && { nextSeq: page.nextSeq }
1561
- };
1562
- }
1563
- }),
1564
- defineAgentTool({
1565
- name: "session_event",
1566
- description: "Read one durable event by exact conversation and sequence address.",
1567
- identity: { serviceName: "agent-events", action: "read", method: "GET" },
1568
- input: EventAddressSchema,
1569
- output: EventOutputSchema,
1570
- transports: ["AGENT"],
1571
- handler: ({ input: request }) => readExact(request)
1572
- })
1573
- ];
1574
1633
  }
1575
1634
  // src/agent-runtime/observability.ts
1576
- import { z as z6 } from "zod";
1577
- var AgentRunEventBaseSchema = z6.object({
1578
- schemaVersion: z6.literal(1),
1635
+ import { z as z4 } from "zod";
1636
+ var AgentRunEventBaseSchema = z4.object({
1637
+ schemaVersion: z4.literal(1),
1579
1638
  eventId: AgentRecordIdSchema2,
1580
1639
  conversationId: AgentRecordIdSchema2,
1581
1640
  runId: AgentRecordIdSchema2,
1582
- traceId: z6.string().min(1),
1583
- spanId: z6.string().min(1),
1584
- parentSpanId: z6.string().min(1).optional(),
1641
+ traceId: z4.string().min(1),
1642
+ spanId: z4.string().min(1),
1643
+ parentSpanId: z4.string().min(1).optional(),
1585
1644
  state: AgentRunStateSchema2,
1586
- modelId: z6.string().min(1).optional(),
1587
- durationMs: z6.number().nonnegative().optional(),
1645
+ modelId: z4.string().min(1).optional(),
1646
+ durationMs: z4.number().nonnegative().optional(),
1588
1647
  emittedAt: AgentTimestampSchema2
1589
1648
  });
1590
1649
  var AgentRunStartedEventSchema = AgentRunEventBaseSchema.extend({
1591
- type: z6.literal("run-started"),
1592
- queueWaitMs: z6.number().nonnegative().optional()
1650
+ type: z4.literal("run-started"),
1651
+ queueWaitMs: z4.number().nonnegative().optional()
1593
1652
  });
1594
1653
  var AgentStepFinishedEventSchema = AgentRunEventBaseSchema.extend({
1595
- type: z6.literal("step-finished"),
1596
- step: z6.int().nonnegative(),
1597
- ttftMs: z6.number().nonnegative().optional(),
1654
+ type: z4.literal("step-finished"),
1655
+ step: z4.int().nonnegative(),
1656
+ attempt: z4.int().nonnegative(),
1657
+ phase: AgentStepSpendPhaseSchema2,
1658
+ provider: AgentStepSpendProviderSchema.optional(),
1659
+ ttftMs: z4.number().nonnegative().optional(),
1598
1660
  usage: AgentUsageSchema2,
1599
- response: AgentProviderResponseSchema2
1661
+ response: AgentProviderResponseSchema2.optional(),
1662
+ spendHookError: z4.strictObject({
1663
+ code: z4.enum(["hook_error", "hook_timeout"]),
1664
+ cause: z4.unknown().optional(),
1665
+ reportFailed: z4.literal(true).optional(),
1666
+ reportError: z4.unknown().optional()
1667
+ }).optional()
1668
+ }).check((ctx) => {
1669
+ const event = ctx.value;
1670
+ const answered = event.phase !== "compaction";
1671
+ for (const field of ["modelId", "provider", "response"]) {
1672
+ if (event[field] !== undefined === answered)
1673
+ continue;
1674
+ ctx.issues.push({
1675
+ code: "custom",
1676
+ input: event[field],
1677
+ path: [field],
1678
+ message: answered ? `A ${event.phase} spend names its ${field}` : `A compaction has no ${field}`
1679
+ });
1680
+ }
1600
1681
  });
1601
1682
  var AgentRunTerminalEventSchema = AgentRunEventBaseSchema.extend({
1602
- type: z6.literal("run-terminal"),
1683
+ type: z4.literal("run-terminal"),
1603
1684
  terminalReason: AgentTerminalReasonSchema2,
1604
- ttftMs: z6.number().nonnegative().optional(),
1605
- internalCause: z6.unknown().optional(),
1685
+ ttftMs: z4.number().nonnegative().optional(),
1686
+ internalCause: z4.unknown().optional(),
1606
1687
  usage: AgentUsageSchema2
1607
1688
  });
1608
- var AgentRunEventSchema = z6.discriminatedUnion("type", [
1689
+ var AgentRunEventSchema = z4.discriminatedUnion("type", [
1609
1690
  AgentRunStartedEventSchema,
1610
1691
  AgentStepFinishedEventSchema,
1611
1692
  AgentRunTerminalEventSchema
@@ -1643,9 +1724,19 @@ function createAgentObservability(config) {
1643
1724
  manager.submit(() => {
1644
1725
  if (config.includeInternalCause)
1645
1726
  return parsed;
1646
- if (parsed.type !== "run-terminal")
1647
- return parsed;
1648
- return AgentRunTerminalEventSchema.omit({ internalCause: true }).parse(parsed);
1727
+ if (parsed.type === "run-terminal") {
1728
+ return AgentRunTerminalEventSchema.omit({ internalCause: true }).parse(parsed);
1729
+ }
1730
+ if (parsed.type === "step-finished" && parsed.spendHookError !== undefined) {
1731
+ return AgentStepFinishedEventSchema.parse({
1732
+ ...parsed,
1733
+ spendHookError: {
1734
+ code: parsed.spendHookError.code,
1735
+ ...parsed.spendHookError.reportFailed && { reportFailed: true }
1736
+ }
1737
+ });
1738
+ }
1739
+ return parsed;
1649
1740
  });
1650
1741
  },
1651
1742
  flush: (bound) => manager.flush(bound),
@@ -1654,7 +1745,7 @@ function createAgentObservability(config) {
1654
1745
  };
1655
1746
  }
1656
1747
  // src/agent-runtime/projections.ts
1657
- import { z as z7 } from "zod";
1748
+ import { z as z5 } from "zod";
1658
1749
  function defineAgentProjection(definition) {
1659
1750
  if (definition.name.length === 0)
1660
1751
  throw new TypeError("Projection name must not be empty");
@@ -1674,26 +1765,23 @@ function createAgentProjectionRegistry(definitions) {
1674
1765
  }
1675
1766
  return registry;
1676
1767
  }
1677
- var ProjectionRowSchema = z7.object({
1678
- conversation_id: z7.string().optional(),
1679
- version: z7.int().positive(),
1680
- upto_seq: z7.int().nonnegative(),
1681
- payload: z7.string(),
1682
- updated_at: z7.string()
1768
+ var ProjectionRowSchema = z5.object({
1769
+ conversation_id: z5.string().optional(),
1770
+ version: SqlIntegerSchema.pipe(z5.int().positive()),
1771
+ upto_seq: SqlIntegerSchema.pipe(z5.int().nonnegative()),
1772
+ payload: z5.string(),
1773
+ updated_at: z5.string()
1683
1774
  });
1684
1775
  function projectionPayload(value) {
1685
1776
  return JSON.parse(value);
1686
1777
  }
1687
- function createSqliteAgentProjectionStore(input) {
1688
- const database = input.sqlite.database;
1689
- const store = input.sqlite.store;
1690
- const load = (conversationId, definition) => {
1691
- const raw = database.prepare(`
1692
- SELECT version, upto_seq, payload, updated_at
1693
- FROM stitchkit_agent_runtime_projections
1694
- WHERE conversation_id = ? AND name = ?
1695
- `).get(conversationId, definition.name);
1696
- if (raw === null || raw === undefined)
1778
+ function createAgentProjectionStore(input) {
1779
+ const { host, store } = input;
1780
+ const projections = host.tables.projections;
1781
+ const load = async (conversationId, definition) => {
1782
+ const raw = await host.read((session) => session.get(`SELECT version, upto_seq, payload, updated_at FROM ${projections}
1783
+ WHERE conversation_id = ? AND name = ?`, [conversationId, definition.name]));
1784
+ if (raw === undefined)
1697
1785
  return;
1698
1786
  const row = ProjectionRowSchema.parse(raw);
1699
1787
  if (row.version !== definition.version)
@@ -1707,7 +1795,7 @@ function createSqliteAgentProjectionStore(input) {
1707
1795
  };
1708
1796
  };
1709
1797
  const advance = async (conversationId, definition) => {
1710
- const current = load(conversationId, definition);
1798
+ const current = await load(conversationId, definition);
1711
1799
  let value = current?.value ?? definition.initial();
1712
1800
  let uptoSeq = current?.uptoSeq ?? 0;
1713
1801
  let cursor = uptoSeq + 1;
@@ -1727,25 +1815,29 @@ function createSqliteAgentProjectionStore(input) {
1727
1815
  break;
1728
1816
  cursor = page.nextSeq;
1729
1817
  }
1730
- await input.sqlite.transaction(async (scope) => {
1731
- scope.database.prepare(`
1732
- INSERT INTO stitchkit_agent_runtime_projections
1733
- (conversation_id, name, version, upto_seq, payload, updated_at)
1734
- VALUES (?, ?, ?, ?, ?, ?)
1735
- ON CONFLICT (conversation_id, name) DO UPDATE SET
1736
- version = excluded.version,
1737
- upto_seq = excluded.upto_seq,
1738
- payload = excluded.payload,
1739
- updated_at = excluded.updated_at
1740
- `).run(conversationId, definition.name, definition.version, uptoSeq, JSON.stringify(value), updatedAt);
1818
+ await host.transaction(conversationId, async (scope) => {
1819
+ await scope.run(`INSERT INTO ${projections}
1820
+ (conversation_id, name, version, upto_seq, payload, updated_at)
1821
+ VALUES (?, ?, ?, ?, ?, ?)
1822
+ ON CONFLICT (conversation_id, name) DO UPDATE SET
1823
+ version = excluded.version,
1824
+ upto_seq = excluded.upto_seq,
1825
+ payload = excluded.payload,
1826
+ updated_at = excluded.updated_at
1827
+ WHERE ${projections}.version <> excluded.version
1828
+ OR excluded.upto_seq >= ${projections}.upto_seq`, [
1829
+ conversationId,
1830
+ definition.name,
1831
+ definition.version,
1832
+ uptoSeq,
1833
+ JSON.stringify(value),
1834
+ updatedAt
1835
+ ]);
1741
1836
  });
1742
1837
  return { name: definition.name, version: definition.version, uptoSeq, updatedAt, value };
1743
1838
  };
1744
- const list = (definition) => database.prepare(`
1745
- SELECT conversation_id, version, upto_seq, payload, updated_at
1746
- FROM stitchkit_agent_runtime_projections
1747
- WHERE name = ? AND version = ? ORDER BY updated_at DESC, conversation_id
1748
- `).all(definition.name, definition.version).map((raw) => {
1839
+ const list = async (definition) => (await host.read((session) => session.all(`SELECT conversation_id, version, upto_seq, payload, updated_at FROM ${projections}
1840
+ WHERE name = ? AND version = ? ORDER BY updated_at DESC, conversation_id`, [definition.name, definition.version]))).map((raw) => {
1749
1841
  const row = ProjectionRowSchema.parse(raw);
1750
1842
  if (!row.conversation_id)
1751
1843
  throw new TypeError("Projection list row has no conversation id");
@@ -1762,10 +1854,10 @@ function createSqliteAgentProjectionStore(input) {
1762
1854
  });
1763
1855
  return { load, advance, list };
1764
1856
  }
1765
- var ConversationCardSchema = z7.object({
1766
- eventCount: z7.int().nonnegative(),
1767
- lastKind: z7.string().optional(),
1768
- lastOccurredAt: z7.string().optional()
1857
+ var ConversationCardSchema = z5.object({
1858
+ eventCount: z5.int().nonnegative(),
1859
+ lastKind: z5.string().optional(),
1860
+ lastOccurredAt: z5.string().optional()
1769
1861
  });
1770
1862
  var agentConversationCardProjection = defineAgentProjection({
1771
1863
  name: "conversation-card",
@@ -1778,7 +1870,7 @@ var agentConversationCardProjection = defineAgentProjection({
1778
1870
  lastOccurredAt: event.occurredAt
1779
1871
  })
1780
1872
  });
1781
- var StateSlotsProjectionSchema = z7.record(z7.string(), z7.json());
1873
+ var StateSlotsProjectionSchema = z5.record(z5.string(), z5.json());
1782
1874
  var agentStateSlotsProjection = defineAgentProjection({
1783
1875
  name: "state-slots",
1784
1876
  version: 1,
@@ -1787,15 +1879,15 @@ var agentStateSlotsProjection = defineAgentProjection({
1787
1879
  fold: (state, event) => {
1788
1880
  if (event.kind !== "state/set")
1789
1881
  return state;
1790
- const payload = z7.object({ name: z7.string().min(1), value: z7.json() }).passthrough().parse(event.payload);
1882
+ const payload = z5.looseObject({ name: z5.string().min(1), value: z5.json() }).parse(event.payload);
1791
1883
  return { ...state, [payload.name]: payload.value };
1792
1884
  }
1793
1885
  });
1794
- var ScheduleSummarySchema = z7.object({
1795
- scheduled: z7.int().nonnegative(),
1796
- fired: z7.int().nonnegative(),
1797
- cancelled: z7.int().nonnegative(),
1798
- late: z7.int().nonnegative()
1886
+ var ScheduleSummarySchema = z5.object({
1887
+ scheduled: z5.int().nonnegative(),
1888
+ fired: z5.int().nonnegative(),
1889
+ cancelled: z5.int().nonnegative(),
1890
+ late: z5.int().nonnegative()
1799
1891
  });
1800
1892
  var agentScheduleSummaryProjection = defineAgentProjection({
1801
1893
  name: "schedule-summary",
@@ -1814,12 +1906,12 @@ var agentScheduleSummaryProjection = defineAgentProjection({
1814
1906
  return state;
1815
1907
  }
1816
1908
  });
1817
- var RuntimeSummarySchema = z7.object({
1818
- eventCount: z7.int().nonnegative(),
1819
- lastSeq: z7.int().nonnegative(),
1820
- lastKind: z7.string().optional(),
1821
- lastOccurredAt: z7.string().optional(),
1822
- lastModelId: z7.string().optional()
1909
+ var RuntimeSummarySchema = z5.object({
1910
+ eventCount: z5.int().nonnegative(),
1911
+ lastSeq: z5.int().nonnegative(),
1912
+ lastKind: z5.string().optional(),
1913
+ lastOccurredAt: z5.string().optional(),
1914
+ lastModelId: z5.string().optional()
1823
1915
  }).strict();
1824
1916
  var agentSummaryProjection = defineAgentProjection({
1825
1917
  name: "summary",
@@ -1827,10 +1919,10 @@ var agentSummaryProjection = defineAgentProjection({
1827
1919
  schema: RuntimeSummarySchema,
1828
1920
  initial: () => ({ eventCount: 0, lastSeq: 0 }),
1829
1921
  fold: (state, event) => {
1830
- const request = event.kind === "provider/request" ? z7.object({
1831
- modelId: z7.string().optional(),
1832
- sent: z7.object({ modelId: z7.string() }).passthrough().optional()
1833
- }).passthrough().transform((payload) => ({ modelId: payload.modelId ?? payload.sent?.modelId })).safeParse(event.payload) : undefined;
1922
+ const request = event.kind === "provider/request" ? z5.looseObject({
1923
+ modelId: z5.string().optional(),
1924
+ sent: z5.looseObject({ modelId: z5.string() }).optional()
1925
+ }).transform((payload) => ({ modelId: payload.modelId ?? payload.sent?.modelId })).safeParse(event.payload) : undefined;
1834
1926
  return {
1835
1927
  eventCount: state.eventCount + 1,
1836
1928
  lastSeq: event.seq,
@@ -1840,40 +1932,78 @@ var agentSummaryProjection = defineAgentProjection({
1840
1932
  };
1841
1933
  }
1842
1934
  });
1843
- var RuntimeUsageSchema = z7.object({
1844
- inputTokens: z7.number().nonnegative(),
1845
- outputTokens: z7.number().nonnegative(),
1846
- cost: z7.number().nonnegative(),
1847
- sources: z7.array(z7.string())
1848
- }).strict();
1935
+ function hasMeasuredUsage(usage) {
1936
+ if (!usage)
1937
+ return false;
1938
+ return usage.inputTokens.value !== undefined || usage.outputTokens.value !== undefined || usage.reasoningTokens?.value !== undefined || usage.cacheReadTokens?.value !== undefined || usage.cacheWriteTokens?.value !== undefined || usage.cost?.value !== undefined;
1939
+ }
1940
+ var TerminalUsageTransitionSchema = z5.looseObject({
1941
+ type: z5.literal("terminal"),
1942
+ input: z5.looseObject({
1943
+ reason: AgentTerminalReasonSchema2.optional(),
1944
+ usage: AgentUsageSchema2.optional(),
1945
+ assistant: z5.looseObject({ parts: z5.array(z5.unknown()) }).optional()
1946
+ })
1947
+ });
1948
+ var RecoverUsageTransitionSchema = z5.looseObject({
1949
+ type: z5.literal("recover"),
1950
+ input: z5.looseObject({ action: z5.literal("abandon") }),
1951
+ usage: AgentUsageSchema2.optional()
1952
+ });
1953
+ function eventUsage(event) {
1954
+ if (event.kind === "runtime/transition") {
1955
+ const terminal = TerminalUsageTransitionSchema.safeParse(event.payload);
1956
+ if (terminal.success) {
1957
+ const { assistant, reason, usage } = terminal.data.input;
1958
+ const answered = reason === undefined || runStateForTerminalReason2(reason) === "completed" || assistant === undefined || assistant.parts.length > 0;
1959
+ if (!answered && !hasMeasuredUsage(usage))
1960
+ return;
1961
+ return statedUsage(usage);
1962
+ }
1963
+ const abandoned = RecoverUsageTransitionSchema.safeParse(event.payload);
1964
+ if (abandoned.success && hasMeasuredUsage(abandoned.data.usage)) {
1965
+ return statedUsage(abandoned.data.usage);
1966
+ }
1967
+ return;
1968
+ }
1969
+ if (event.kind === "provider/response" && isModelInvocationRecord(event.payload)) {
1970
+ const parsed = InvocationResponseSchema.safeParse(event.payload);
1971
+ if (!parsed.success || parsed.data.runId !== undefined)
1972
+ return;
1973
+ if (parsed.data.status !== "succeeded" && !hasMeasuredUsage(parsed.data.usage)) {
1974
+ return;
1975
+ }
1976
+ return parsed.data.usage;
1977
+ }
1978
+ return;
1979
+ }
1980
+ var RuntimeUsageSchema = z5.strictObject({
1981
+ records: z5.int().nonnegative(),
1982
+ usage: AgentUsageSchema2
1983
+ });
1849
1984
  var agentUsageProjection = defineAgentProjection({
1850
1985
  name: "usage",
1851
- version: 1,
1986
+ version: 2,
1852
1987
  schema: RuntimeUsageSchema,
1853
- initial: () => ({ inputTokens: 0, outputTokens: 0, cost: 0, sources: [] }),
1988
+ initial: () => ({
1989
+ records: 0,
1990
+ usage: unknownUsage()
1991
+ }),
1854
1992
  fold: (state, event) => {
1855
- const parsed = z7.object({
1856
- inputTokens: z7.number().nonnegative().optional(),
1857
- outputTokens: z7.number().nonnegative().optional(),
1858
- cost: z7.number().nonnegative().optional(),
1859
- source: z7.string().min(1).optional()
1860
- }).passthrough().safeParse(event.payload);
1861
- if (!parsed.success)
1993
+ const usage = eventUsage(event);
1994
+ if (!usage)
1862
1995
  return state;
1863
- const source = parsed.data.source;
1864
1996
  return {
1865
- inputTokens: state.inputTokens + (parsed.data.inputTokens ?? 0),
1866
- outputTokens: state.outputTokens + (parsed.data.outputTokens ?? 0),
1867
- cost: state.cost + (parsed.data.cost ?? 0),
1868
- sources: source && !state.sources.includes(source) ? [...state.sources, source] : state.sources
1997
+ records: state.records + 1,
1998
+ usage: statedUsage(addUsage(state.records === 0 ? undefined : state.usage, usage))
1869
1999
  };
1870
2000
  }
1871
2001
  });
1872
- var RuntimeOutlineSchema = z7.object({
1873
- requests: z7.array(z7.object({
1874
- seq: z7.int().positive(),
1875
- occurredAt: z7.string(),
1876
- runId: z7.string().optional()
2002
+ var RuntimeOutlineSchema = z5.object({
2003
+ requests: z5.array(z5.object({
2004
+ seq: z5.int().positive(),
2005
+ occurredAt: z5.string(),
2006
+ runId: z5.string().optional()
1877
2007
  }).strict())
1878
2008
  }).strict();
1879
2009
  var agentOutlineProjection = defineAgentProjection({
@@ -1884,7 +2014,7 @@ var agentOutlineProjection = defineAgentProjection({
1884
2014
  fold: (state, event) => {
1885
2015
  if (event.kind !== "provider/request")
1886
2016
  return state;
1887
- const payload = z7.object({ runId: z7.string().optional() }).passthrough().parse(event.payload);
2017
+ const payload = z5.looseObject({ runId: z5.string().optional() }).parse(event.payload);
1888
2018
  return {
1889
2019
  requests: [
1890
2020
  ...state.requests,
@@ -1925,38 +2055,38 @@ function defineAgentProtocol(config) {
1925
2055
  };
1926
2056
  }
1927
2057
  // src/agent-runtime/schedule-contract.ts
1928
- import { z as z8 } from "zod";
1929
- var AgentScheduleSchema = z8.object({
1930
- id: z8.string().min(1),
1931
- conversationId: z8.string().min(1),
1932
- kind: z8.enum(["at", "after", "every"]),
1933
- nextAt: z8.iso.datetime({ offset: true }),
1934
- intervalMs: z8.int().positive().optional(),
1935
- timeZone: z8.string().min(1).optional(),
1936
- input: z8.json(),
1937
- state: z8.enum(["scheduled", "cancelled", "completed", "failed"]),
1938
- occurrence: z8.int().nonnegative(),
1939
- attempts: z8.int().nonnegative().optional(),
1940
- retryAt: z8.iso.datetime({ offset: true }).optional(),
1941
- lastError: z8.string().optional(),
1942
- createdAt: z8.iso.datetime({ offset: true }),
1943
- updatedAt: z8.iso.datetime({ offset: true })
2058
+ import { z as z6 } from "zod";
2059
+ var AgentScheduleSchema = z6.object({
2060
+ id: z6.string().min(1),
2061
+ conversationId: z6.string().min(1),
2062
+ kind: z6.enum(["at", "after", "every"]),
2063
+ nextAt: z6.iso.datetime({ offset: true }),
2064
+ intervalMs: z6.int().positive().optional(),
2065
+ timeZone: z6.string().min(1).optional(),
2066
+ input: z6.json(),
2067
+ state: z6.enum(["scheduled", "cancelled", "completed", "failed"]),
2068
+ occurrence: z6.int().nonnegative(),
2069
+ attempts: z6.int().nonnegative().optional(),
2070
+ retryAt: z6.iso.datetime({ offset: true }).optional(),
2071
+ lastError: z6.string().optional(),
2072
+ createdAt: z6.iso.datetime({ offset: true }),
2073
+ updatedAt: z6.iso.datetime({ offset: true })
1944
2074
  }).strict();
1945
- var ScheduleRowSchema = z8.object({
1946
- id: z8.string(),
1947
- conversation_id: z8.string(),
1948
- kind: z8.enum(["at", "after", "every"]),
1949
- next_at: z8.string(),
1950
- interval_ms: z8.number().int().positive().nullable(),
1951
- time_zone: z8.string().nullable(),
1952
- input_payload: z8.string(),
1953
- state: z8.enum(["scheduled", "cancelled", "completed", "failed"]),
1954
- occurrence: z8.int().nonnegative(),
1955
- attempts: z8.int().nonnegative(),
1956
- retry_at: z8.string().nullable(),
1957
- last_error: z8.string().nullable(),
1958
- created_at: z8.string(),
1959
- updated_at: z8.string()
2075
+ var ScheduleRowSchema = z6.object({
2076
+ id: z6.string(),
2077
+ conversation_id: z6.string(),
2078
+ kind: z6.enum(["at", "after", "every"]),
2079
+ next_at: z6.string(),
2080
+ interval_ms: SqlIntegerSchema.pipe(z6.int().positive()).nullable(),
2081
+ time_zone: z6.string().nullable(),
2082
+ input_payload: z6.string(),
2083
+ state: z6.enum(["scheduled", "cancelled", "completed", "failed"]),
2084
+ occurrence: SqlIntegerSchema.pipe(z6.int().nonnegative()),
2085
+ attempts: SqlIntegerSchema.pipe(z6.int().nonnegative()),
2086
+ retry_at: z6.string().nullable(),
2087
+ last_error: z6.string().nullable(),
2088
+ created_at: z6.string(),
2089
+ updated_at: z6.string()
1960
2090
  });
1961
2091
  function parseSchedule(raw) {
1962
2092
  const row = ScheduleRowSchema.parse(raw);
@@ -1977,17 +2107,17 @@ function parseSchedule(raw) {
1977
2107
  updatedAt: row.updated_at
1978
2108
  });
1979
2109
  }
1980
- var AgentScheduleDeliveryOutcomeSchema = z8.discriminatedUnion("status", [
1981
- z8.object({ status: z8.literal("retry"), reason: z8.string().min(1) }).strict(),
1982
- z8.object({ status: z8.literal("terminal"), reason: z8.string().min(1) }).strict()
2110
+ var AgentScheduleDeliveryOutcomeSchema = z6.discriminatedUnion("status", [
2111
+ z6.object({ status: z6.literal("retry"), reason: z6.string().min(1) }).strict(),
2112
+ z6.object({ status: z6.literal("terminal"), reason: z6.string().min(1) }).strict()
1983
2113
  ]);
1984
2114
  // src/agent-runtime/schedule-tools.ts
1985
- import { z as z9 } from "zod";
1986
- var ScheduledOutputSchema = z9.object({ scheduleId: z9.string(), nextAt: z9.string() }).strict();
1987
- var ConversationInputSchema = z9.object({ conversationId: z9.string().min(1) }).strict();
1988
- function createAgentScheduleTools(service) {
2115
+ import { z as z7 } from "zod";
2116
+ var ScheduledOutputSchema = z7.object({ scheduleId: z7.string(), nextAt: z7.string() }).strict();
2117
+ function createAgentScheduleTools({ service, run }) {
2118
+ const conversationId = conversationOfRun(run, "createAgentScheduleTools");
1989
2119
  const schedule = async (request) => {
1990
- const result = await service.scheduleInput(request);
2120
+ const result = await service.scheduleInput({ ...request, conversationId });
1991
2121
  return { scheduleId: result.id, nextAt: result.nextAt };
1992
2122
  };
1993
2123
  return [
@@ -1995,71 +2125,67 @@ function createAgentScheduleTools(service) {
1995
2125
  name: "schedule_after",
1996
2126
  description: "Schedule durable input after a relative delay.",
1997
2127
  identity: { serviceName: "agent-schedules", action: "after", method: "POST" },
1998
- input: z9.object({
1999
- conversationId: z9.string().min(1),
2000
- input: z9.json(),
2001
- afterMs: z9.int().positive()
2128
+ input: z7.object({
2129
+ input: z7.json(),
2130
+ afterMs: z7.int().positive()
2002
2131
  }).strict(),
2003
2132
  output: ScheduledOutputSchema,
2004
- transports: ["AGENT"],
2133
+ expose: ["AGENT"],
2005
2134
  handler: ({ input }) => schedule(input)
2006
2135
  }),
2007
2136
  defineAgentTool({
2008
2137
  name: "schedule_at",
2009
2138
  description: "Schedule durable input at an absolute timestamp with an explicit offset.",
2010
2139
  identity: { serviceName: "agent-schedules", action: "at", method: "POST" },
2011
- input: z9.object({ conversationId: z9.string().min(1), input: z9.json(), at: z9.string().min(1) }).strict(),
2140
+ input: z7.object({ input: z7.json(), at: z7.string().min(1) }).strict(),
2012
2141
  output: ScheduledOutputSchema,
2013
- transports: ["AGENT"],
2142
+ expose: ["AGENT"],
2014
2143
  handler: ({ input }) => schedule(input)
2015
2144
  }),
2016
2145
  defineAgentTool({
2017
2146
  name: "schedule_every",
2018
2147
  description: "Schedule recurring durable input in an explicit conversation timezone.",
2019
2148
  identity: { serviceName: "agent-schedules", action: "every", method: "POST" },
2020
- input: z9.object({
2021
- conversationId: z9.string().min(1),
2022
- input: z9.json(),
2023
- everyMs: z9.int().positive(),
2024
- timeZone: z9.string().min(1)
2149
+ input: z7.object({
2150
+ input: z7.json(),
2151
+ everyMs: z7.int().positive(),
2152
+ timeZone: z7.string().min(1)
2025
2153
  }).strict(),
2026
2154
  output: ScheduledOutputSchema,
2027
- transports: ["AGENT"],
2155
+ expose: ["AGENT"],
2028
2156
  handler: ({ input }) => schedule(input)
2029
2157
  }),
2030
2158
  defineAgentTool({
2031
2159
  name: "schedule_list",
2032
- description: "List durable schedules for one conversation.",
2160
+ description: "List the durable schedules of this conversation.",
2033
2161
  identity: { serviceName: "agent-schedules", action: "list", method: "GET" },
2034
- input: ConversationInputSchema,
2035
- output: z9.object({ schedules: z9.array(z9.json()) }).strict(),
2036
- transports: ["AGENT"],
2037
- handler: ({ input }) => ({
2038
- schedules: [...service.listSchedules(input.conversationId)]
2039
- })
2162
+ input: z7.object({}).strict(),
2163
+ output: z7.object({ schedules: z7.array(z7.json()) }).strict(),
2164
+ expose: ["AGENT"],
2165
+ handler: async () => ({ schedules: [...await service.listSchedules(conversationId)] })
2040
2166
  }),
2041
2167
  defineAgentTool({
2042
2168
  name: "schedule_cancel",
2043
2169
  description: "Cancel one durable deferred-input schedule.",
2044
2170
  identity: { serviceName: "agent-schedules", action: "cancel", method: "POST" },
2045
- input: z9.object({ conversationId: z9.string().min(1), scheduleId: z9.string().min(1) }).strict(),
2046
- output: z9.object({ cancelled: z9.boolean() }).strict(),
2047
- transports: ["AGENT"],
2171
+ input: z7.object({ scheduleId: z7.string().min(1) }).strict(),
2172
+ output: z7.object({ cancelled: z7.boolean() }).strict(),
2173
+ expose: ["AGENT"],
2048
2174
  handler: async ({ input }) => ({
2049
- cancelled: await service.cancelSchedule(input.conversationId, input.scheduleId)
2175
+ cancelled: await service.cancelSchedule(conversationId, input.scheduleId)
2050
2176
  })
2051
2177
  })
2052
2178
  ];
2053
2179
  }
2054
2180
  // src/agent-runtime/schedules.ts
2055
- import { z as z11 } from "zod";
2181
+ import { z as z9 } from "zod";
2056
2182
 
2057
2183
  // src/agent-runtime/schedule-dispatch.ts
2058
2184
  import { randomUUID as randomUUID3 } from "node:crypto";
2059
2185
 
2060
2186
  // src/agent-runtime/schedule-records.ts
2061
2187
  import { randomUUID as randomUUID2 } from "node:crypto";
2062
- import { z as z10 } from "zod";
2188
+ import { z as z8 } from "zod";
2063
2189
  function newSchedule(request, observedAt) {
2064
2190
  const modes = [
2065
2191
  request.at !== undefined,
@@ -2082,7 +2208,7 @@ function newSchedule(request, observedAt) {
2082
2208
  const intervalMs = request.everyMs;
2083
2209
  const delay = request.afterMs ?? request.everyMs;
2084
2210
  assertPositiveSafeInteger("Schedule delay", delay);
2085
- const nextAt = request.at ? new Date(z10.iso.datetime({ offset: true }).parse(request.at)).toISOString() : new Date(observedAt.getTime() + (delay ?? 0)).toISOString();
2211
+ const nextAt = request.at ? new Date(z8.iso.datetime({ offset: true }).parse(request.at)).toISOString() : new Date(observedAt.getTime() + (delay ?? 0)).toISOString();
2086
2212
  const schedule = AgentScheduleSchema.parse({
2087
2213
  id: randomUUID2(),
2088
2214
  conversationId: request.conversationId,
@@ -2090,7 +2216,7 @@ function newSchedule(request, observedAt) {
2090
2216
  nextAt,
2091
2217
  ...intervalMs !== undefined && { intervalMs },
2092
2218
  ...request.timeZone && { timeZone: request.timeZone },
2093
- input: z10.json().parse(request.input),
2219
+ input: z8.json().parse(request.input),
2094
2220
  state: "scheduled",
2095
2221
  occurrence: 0,
2096
2222
  createdAt: observedAt.toISOString(),
@@ -2098,14 +2224,30 @@ function newSchedule(request, observedAt) {
2098
2224
  });
2099
2225
  return schedule;
2100
2226
  }
2101
- async function insertSchedule(sqlite, schedule) {
2102
- await sqlite.transaction(async (scope) => {
2103
- scope.database.prepare(`
2104
- INSERT INTO stitchkit_agent_runtime_schedules (
2227
+ async function insertSchedule(host, schedule, maxActivePerConversation) {
2228
+ await host.transaction(schedule.conversationId, async (scope) => {
2229
+ const active = z8.object({ active: SqlIntegerSchema }).parse(await scope.get(`
2230
+ SELECT COUNT(*) AS active FROM ${host.tables.schedules}
2231
+ WHERE conversation_id = ? AND state = 'scheduled'
2232
+ `, [schedule.conversationId])).active;
2233
+ if (active >= maxActivePerConversation)
2234
+ throw new TypeError(`The conversation already holds ${active} active schedules, the limit is ${maxActivePerConversation}`);
2235
+ await scope.run(`
2236
+ INSERT INTO ${host.tables.schedules} (
2105
2237
  id, conversation_id, kind, next_at, interval_ms, time_zone,
2106
2238
  input_payload, state, occurrence, created_at, updated_at
2107
2239
  ) VALUES (?, ?, ?, ?, ?, ?, ?, 'scheduled', 0, ?, ?)
2108
- `).run(schedule.id, schedule.conversationId, schedule.kind, schedule.nextAt, schedule.intervalMs ?? null, schedule.timeZone ?? null, JSON.stringify(schedule.input), schedule.createdAt, schedule.updatedAt);
2240
+ `, [
2241
+ schedule.id,
2242
+ schedule.conversationId,
2243
+ schedule.kind,
2244
+ schedule.nextAt,
2245
+ schedule.intervalMs ?? null,
2246
+ schedule.timeZone ?? null,
2247
+ JSON.stringify(schedule.input),
2248
+ schedule.createdAt,
2249
+ schedule.updatedAt
2250
+ ]);
2109
2251
  await scope.appendEvent({
2110
2252
  conversationId: schedule.conversationId,
2111
2253
  kind: "schedule/set",
@@ -2117,12 +2259,12 @@ async function insertSchedule(sqlite, schedule) {
2117
2259
  function holdsClaim(raw, firing, at) {
2118
2260
  if (raw === null || raw === undefined)
2119
2261
  return false;
2120
- const row = z10.object({
2121
- state: z10.string(),
2122
- claim_owner: z10.string().nullable(),
2123
- claim_until: z10.string().nullable(),
2124
- occurrence: z10.int(),
2125
- next_at: z10.string()
2262
+ const row = z8.object({
2263
+ state: z8.string(),
2264
+ claim_owner: z8.string().nullable(),
2265
+ claim_until: z8.string().nullable(),
2266
+ occurrence: SqlIntegerSchema,
2267
+ next_at: z8.string()
2126
2268
  }).parse(raw);
2127
2269
  return row.state === "scheduled" && row.claim_owner === firing.owner && row.claim_until !== null && row.claim_until > at && row.occurrence === firing.schedule.occurrence && row.next_at === firing.schedule.nextAt;
2128
2270
  }
@@ -2132,27 +2274,27 @@ function nextSlot(schedule, observedAt, intervalMs) {
2132
2274
  const slots = Math.max(1, Math.floor((observedAt.getTime() - due) / intervalMs) + 1);
2133
2275
  return new Date(due + slots * intervalMs).toISOString();
2134
2276
  }
2135
- async function recordDispatchFailure(sqlite, firing, reason, maxAttempts, explicitlyTerminal = false) {
2277
+ async function recordDispatchFailure(host, firing, reason, maxAttempts, explicitlyTerminal = false) {
2136
2278
  const { schedule, occurrence } = firing;
2137
2279
  const characters = Array.from(reason);
2138
2280
  const message = characters.length > MAX_FAILURE_REASON ? `${characters.slice(0, MAX_FAILURE_REASON).join("")}…` : reason;
2139
- await sqlite.transaction(async (scope) => {
2281
+ await host.transaction(schedule.conversationId, async (scope) => {
2140
2282
  const at = firing.now().toISOString();
2141
- const raw = scope.database.prepare(`
2283
+ const raw = await scope.get(`
2142
2284
  SELECT state, claim_owner, claim_until, occurrence, next_at
2143
- FROM stitchkit_agent_runtime_schedules WHERE id = ?
2144
- `).get(schedule.id);
2285
+ FROM ${host.tables.schedules} WHERE id = ?
2286
+ `, [schedule.id]);
2145
2287
  if (!holdsClaim(raw, firing, at))
2146
2288
  return;
2147
2289
  const attempts = Math.min((schedule.attempts ?? 0) + 1, Number.MAX_SAFE_INTEGER);
2148
2290
  const exhausted = !explicitlyTerminal && attempts >= maxAttempts;
2149
2291
  if (exhausted && schedule.kind === "every" && schedule.intervalMs) {
2150
2292
  const nextAt = nextSlot(schedule, firing.now(), schedule.intervalMs);
2151
- scope.database.prepare(`
2152
- UPDATE stitchkit_agent_runtime_schedules
2293
+ await scope.run(`
2294
+ UPDATE ${host.tables.schedules}
2153
2295
  SET state = 'scheduled', occurrence = ?, next_at = ?, retry_at = NULL, attempts = 0,
2154
2296
  last_error = ?, claim_owner = NULL, claim_until = NULL, updated_at = ? WHERE id = ?
2155
- `).run(occurrence, nextAt, message, at, schedule.id);
2297
+ `, [occurrence, nextAt, message, at, schedule.id]);
2156
2298
  await scope.appendEvent({
2157
2299
  conversationId: schedule.conversationId,
2158
2300
  kind: "schedule/failed",
@@ -2172,11 +2314,11 @@ async function recordDispatchFailure(sqlite, firing, reason, maxAttempts, explic
2172
2314
  }
2173
2315
  const terminal = explicitlyTerminal || exhausted;
2174
2316
  const retryAt = terminal ? null : new Date(new Date(at).getTime() + Math.min(60000, 1000 * 2 ** Math.min(attempts - 1, 6))).toISOString();
2175
- scope.database.prepare(`
2176
- UPDATE stitchkit_agent_runtime_schedules
2317
+ await scope.run(`
2318
+ UPDATE ${host.tables.schedules}
2177
2319
  SET state = ?, retry_at = ?, attempts = ?, last_error = ?,
2178
2320
  claim_owner = NULL, claim_until = NULL, updated_at = ? WHERE id = ?
2179
- `).run(terminal ? "failed" : "scheduled", retryAt, attempts, message, at, schedule.id);
2321
+ `, [terminal ? "failed" : "scheduled", retryAt, attempts, message, at, schedule.id]);
2180
2322
  await scope.appendEvent({
2181
2323
  conversationId: schedule.conversationId,
2182
2324
  kind: "schedule/failed",
@@ -2185,25 +2327,25 @@ async function recordDispatchFailure(sqlite, firing, reason, maxAttempts, explic
2185
2327
  });
2186
2328
  });
2187
2329
  }
2188
- async function settleFiring(sqlite, firing, lateByMs) {
2330
+ async function settleFiring(host, firing, lateByMs) {
2189
2331
  const { schedule, occurrence } = firing;
2190
2332
  const state = schedule.kind === "every" ? "scheduled" : "completed";
2191
- await sqlite.transaction(async (scope) => {
2333
+ await host.transaction(schedule.conversationId, async (scope) => {
2192
2334
  const observedAt = firing.now();
2193
2335
  const at = observedAt.toISOString();
2194
2336
  const nextAt = schedule.kind === "every" && schedule.intervalMs ? nextSlot(schedule, observedAt, schedule.intervalMs) : schedule.nextAt;
2195
- const raw = scope.database.prepare(`
2337
+ const raw = await scope.get(`
2196
2338
  SELECT state, claim_owner, claim_until, occurrence, next_at
2197
- FROM stitchkit_agent_runtime_schedules WHERE id = ?
2198
- `).get(schedule.id);
2339
+ FROM ${host.tables.schedules} WHERE id = ?
2340
+ `, [schedule.id]);
2199
2341
  if (!holdsClaim(raw, firing, at))
2200
2342
  return;
2201
- scope.database.prepare(`
2202
- UPDATE stitchkit_agent_runtime_schedules
2343
+ await scope.run(`
2344
+ UPDATE ${host.tables.schedules}
2203
2345
  SET state = ?, occurrence = ?, next_at = ?, updated_at = ?,
2204
2346
  claim_owner = NULL, claim_until = NULL, retry_at = NULL, attempts = 0, last_error = NULL
2205
2347
  WHERE id = ?
2206
- `).run(state, occurrence, nextAt, at, schedule.id);
2348
+ `, [state, occurrence, nextAt, at, schedule.id]);
2207
2349
  if (lateByMs > 0) {
2208
2350
  await scope.appendEvent({
2209
2351
  conversationId: schedule.conversationId,
@@ -2220,26 +2362,30 @@ async function settleFiring(sqlite, firing, lateByMs) {
2220
2362
  });
2221
2363
  });
2222
2364
  }
2223
- function claimSchedule(sqlite, owner, schedule, now) {
2224
- return sqlite.transaction(async (scope) => {
2365
+ function claimSchedule(host, owner, schedule, now) {
2366
+ return host.transaction(schedule.conversationId, async (scope) => {
2225
2367
  const observedAt = now();
2226
2368
  const at = observedAt.toISOString();
2227
2369
  const until = new Date(observedAt.getTime() + 60000).toISOString();
2228
- const raw = scope.database.prepare(`
2229
- SELECT occurrence, next_at, attempts FROM stitchkit_agent_runtime_schedules
2370
+ const raw = await scope.get(`
2371
+ SELECT occurrence, next_at, attempts FROM ${host.tables.schedules}
2230
2372
  WHERE id = ? AND state = 'scheduled' AND eligible_at <= ?
2231
- `).get(schedule.id, at);
2373
+ `, [schedule.id, at]);
2232
2374
  if (raw === null || raw === undefined)
2233
2375
  return false;
2234
- const row = z10.object({ occurrence: z10.int(), next_at: z10.string(), attempts: z10.int() }).parse(raw);
2376
+ const row = z8.object({
2377
+ occurrence: SqlIntegerSchema,
2378
+ next_at: z8.string(),
2379
+ attempts: SqlIntegerSchema
2380
+ }).parse(raw);
2235
2381
  if (row.attempts !== (schedule.attempts ?? 0))
2236
2382
  return false;
2237
2383
  if (row.occurrence !== schedule.occurrence || row.next_at !== schedule.nextAt)
2238
2384
  return false;
2239
- scope.database.prepare(`
2240
- UPDATE stitchkit_agent_runtime_schedules
2385
+ await scope.run(`
2386
+ UPDATE ${host.tables.schedules}
2241
2387
  SET claim_owner = ?, claim_until = ?, updated_at = ? WHERE id = ?
2242
- `).run(owner, until, at, schedule.id);
2388
+ `, [owner, until, at, schedule.id]);
2243
2389
  return true;
2244
2390
  });
2245
2391
  }
@@ -2249,7 +2395,7 @@ async function dispatchSchedule(context, schedule) {
2249
2395
  if (context.signal.aborted)
2250
2396
  return;
2251
2397
  const owner = randomUUID3();
2252
- if (!await claimSchedule(context.sqlite, owner, schedule, context.now))
2398
+ if (!await claimSchedule(context.host, owner, schedule, context.now))
2253
2399
  return;
2254
2400
  const observedAt = context.now();
2255
2401
  const occurrence = schedule.occurrence + 1;
@@ -2282,13 +2428,13 @@ async function dispatchSchedule(context, schedule) {
2282
2428
  const firing = { schedule, occurrence, now: context.now, owner };
2283
2429
  const failure = AgentScheduleDeliveryOutcomeSchema.safeParse(outcome);
2284
2430
  if (!failure.success) {
2285
- await settleFiring(context.sqlite, firing, lateByMs);
2431
+ await settleFiring(context.host, firing, lateByMs);
2286
2432
  } else {
2287
- await recordDispatchFailure(context.sqlite, firing, failure.data.reason, context.maxAttempts, failure.data.status === "terminal");
2433
+ await recordDispatchFailure(context.host, firing, failure.data.reason, context.maxAttempts, failure.data.status === "terminal");
2288
2434
  }
2289
2435
  } catch (error) {
2290
2436
  if (!context.signal.aborted) {
2291
- await recordDispatchFailure(context.sqlite, { schedule, occurrence, now: context.now, owner }, error instanceof Error ? error.message : String(error), context.maxAttempts);
2437
+ await recordDispatchFailure(context.host, { schedule, occurrence, now: context.now, owner }, error instanceof Error ? error.message : String(error), context.maxAttempts);
2292
2438
  }
2293
2439
  } finally {
2294
2440
  context.clearTimer(timer);
@@ -2297,17 +2443,40 @@ async function dispatchSchedule(context, schedule) {
2297
2443
  }
2298
2444
 
2299
2445
  // src/agent-runtime/schedules.ts
2446
+ function serviceClock(now, setTimer, clearTimer) {
2447
+ return {
2448
+ now: () => now().getTime(),
2449
+ schedule(callback, delayMs) {
2450
+ const handle = setTimer(callback, delayMs);
2451
+ return { cancel: () => clearTimer(handle) };
2452
+ }
2453
+ };
2454
+ }
2300
2455
  function createAgentScheduleService(input) {
2301
- const maxAttempts = z11.number().int().min(1).parse(input.maxAttempts ?? 1000);
2456
+ for (const name of ["maxActivePerConversation", "minIntervalMs"]) {
2457
+ if (input[name] === undefined)
2458
+ throw new TypeError(`createAgentScheduleService requires ${name}`);
2459
+ assertPositiveSafeInteger(name, input[name]);
2460
+ }
2461
+ const limits = {
2462
+ maxActivePerConversation: input.maxActivePerConversation,
2463
+ minIntervalMs: input.minIntervalMs
2464
+ };
2465
+ const maxAttempts = z9.number().int().min(1).parse(input.maxAttempts ?? 1000);
2302
2466
  const now = input.now ?? (() => new Date);
2303
- const database = input.sqlite.database;
2467
+ const host = input.host;
2304
2468
  const setTimer = input.setTimer ?? ((callback, delay) => setTimeout(callback, delay));
2305
2469
  const clearTimer = input.clearTimer ?? clearTimeout;
2306
2470
  const onError = input.onError ?? ((error) => {
2307
2471
  console.error("[stitchkit] agent schedule tick failed", error);
2308
2472
  });
2309
2473
  const lifecycle = new AbortController;
2474
+ const clock = serviceClock(now, setTimer, clearTimer);
2310
2475
  let timer;
2476
+ const cancelTimer = () => {
2477
+ timer?.cancel();
2478
+ timer = undefined;
2479
+ };
2311
2480
  let ticking;
2312
2481
  let recoveryAt = 0;
2313
2482
  let storageFailures = 0;
@@ -2316,47 +2485,49 @@ function createAgentScheduleService(input) {
2316
2485
  recoveryAt = now().getTime() + Math.min(60000, 1000 * 2 ** Math.min(storageFailures - 1, 6));
2317
2486
  onError(error);
2318
2487
  };
2319
- const listSchedules = (conversationId) => database.prepare(`
2320
- SELECT * FROM stitchkit_agent_runtime_schedules
2321
- WHERE conversation_id = ? ORDER BY created_at, id
2322
- `).all(conversationId).map(parseSchedule);
2323
- const arm = () => {
2324
- if (timer !== undefined)
2325
- clearTimer(timer);
2326
- timer = undefined;
2488
+ const listSchedules = (conversationId) => host.read(async (session) => (await session.all(`SELECT * FROM ${host.tables.schedules} WHERE conversation_id = ? ORDER BY created_at, id`, [conversationId])).map(parseSchedule));
2489
+ let armGeneration = 0;
2490
+ const nextDueAt = () => host.read(async (session) => {
2491
+ const raw = await session.get(`SELECT eligible_at FROM ${host.tables.schedules}
2492
+ WHERE state = 'scheduled' ORDER BY eligible_at, id LIMIT 1`);
2493
+ if (raw === undefined)
2494
+ return;
2495
+ return new Date(z9.object({ eligible_at: z9.string() }).parse(raw).eligible_at).getTime();
2496
+ });
2497
+ const arm = async () => {
2498
+ cancelTimer();
2327
2499
  if (lifecycle.signal.aborted || ticking)
2328
2500
  return;
2501
+ const generation = ++armGeneration;
2329
2502
  let dueAt;
2330
2503
  if (recoveryAt > now().getTime()) {
2331
2504
  dueAt = recoveryAt;
2332
2505
  } else {
2333
2506
  try {
2334
- const raw = database.prepare(`
2335
- SELECT eligible_at FROM stitchkit_agent_runtime_schedules
2336
- WHERE state = 'scheduled' ORDER BY eligible_at, id LIMIT 1
2337
- `).get();
2338
- if (raw === null || raw === undefined)
2507
+ const next = await nextDueAt();
2508
+ if (next === undefined)
2339
2509
  return;
2340
- dueAt = new Date(z11.object({ eligible_at: z11.string() }).parse(raw).eligible_at).getTime();
2510
+ dueAt = next;
2341
2511
  } catch (error) {
2342
2512
  reportStorageFailure(error);
2343
2513
  dueAt = recoveryAt;
2344
2514
  }
2345
2515
  }
2346
- timer = setTimer(() => {
2516
+ if (generation !== armGeneration || lifecycle.signal.aborted || ticking)
2517
+ return;
2518
+ cancelTimer();
2519
+ timer = scheduleAt(clock, dueAt, () => {
2347
2520
  timer = undefined;
2348
2521
  tick();
2349
- }, Math.min(Math.max(0, dueAt - now().getTime()), MAX_TIMER_MS));
2522
+ });
2350
2523
  };
2351
2524
  const runTick = async () => {
2352
2525
  if (lifecycle.signal.aborted || now().getTime() < recoveryAt)
2353
2526
  return;
2354
- const due = database.prepare(`
2355
- SELECT * FROM stitchkit_agent_runtime_schedules
2356
- WHERE state = 'scheduled' AND eligible_at <= ? ORDER BY eligible_at, id LIMIT 32
2357
- `).all(now().toISOString()).map(parseSchedule);
2527
+ const due = await host.read(async (session) => (await session.all(`SELECT * FROM ${host.tables.schedules}
2528
+ WHERE state = 'scheduled' AND eligible_at <= ? ORDER BY eligible_at, id LIMIT 32`, [now().toISOString()])).map(parseSchedule));
2358
2529
  const results = await Promise.allSettled(due.map((schedule) => dispatchSchedule({
2359
- sqlite: input.sqlite,
2530
+ host,
2360
2531
  dispatch: input.dispatch,
2361
2532
  now,
2362
2533
  setTimer,
@@ -2373,36 +2544,39 @@ function createAgentScheduleService(input) {
2373
2544
  const tick = () => {
2374
2545
  if (ticking)
2375
2546
  return ticking;
2376
- if (timer !== undefined)
2377
- clearTimer(timer);
2378
- timer = undefined;
2379
- ticking = runTick().catch(reportStorageFailure).finally(() => {
2380
- ticking = undefined;
2381
- arm();
2382
- });
2383
- return ticking;
2547
+ cancelTimer();
2548
+ const current = (async () => {
2549
+ try {
2550
+ await runTick();
2551
+ } catch (error) {
2552
+ reportStorageFailure(error);
2553
+ } finally {
2554
+ ticking = undefined;
2555
+ }
2556
+ await arm();
2557
+ })();
2558
+ ticking = current;
2559
+ return current;
2384
2560
  };
2385
2561
  const scheduleInput = async (request) => {
2386
2562
  const schedule = newSchedule(request, now());
2387
- await insertSchedule(input.sqlite, schedule);
2388
- arm();
2563
+ if (schedule.intervalMs !== undefined && schedule.intervalMs < limits.minIntervalMs)
2564
+ throw new TypeError(`A repeating schedule fires at most every ${limits.minIntervalMs} ms, received everyMs ${schedule.intervalMs}`);
2565
+ await insertSchedule(host, schedule, limits.maxActivePerConversation);
2566
+ await arm();
2389
2567
  return schedule;
2390
2568
  };
2391
2569
  const cancelSchedule = async (conversationId, id) => {
2392
2570
  const observedAt = now().toISOString();
2393
- const changed = await input.sqlite.transaction(async (scope) => {
2394
- const raw = scope.database.prepare(`
2395
- SELECT state FROM stitchkit_agent_runtime_schedules WHERE id = ? AND conversation_id = ?
2396
- `).get(id, conversationId);
2397
- if (raw === null || raw === undefined)
2571
+ const changed = await host.transaction(conversationId, async (scope) => {
2572
+ const raw = await scope.get(`SELECT state FROM ${host.tables.schedules} WHERE id = ? AND conversation_id = ?`, [id, conversationId]);
2573
+ if (raw === undefined)
2398
2574
  return false;
2399
- if (z11.object({ state: z11.string() }).parse(raw).state !== "scheduled")
2575
+ if (z9.object({ state: z9.string() }).parse(raw).state !== "scheduled")
2400
2576
  return false;
2401
- scope.database.prepare(`
2402
- UPDATE stitchkit_agent_runtime_schedules
2403
- SET state = 'cancelled', updated_at = ?, claim_owner = NULL, claim_until = NULL
2404
- WHERE id = ? AND conversation_id = ?
2405
- `).run(observedAt, id, conversationId);
2577
+ await scope.run(`UPDATE ${host.tables.schedules}
2578
+ SET state = 'cancelled', updated_at = ?, claim_owner = NULL, claim_until = NULL
2579
+ WHERE id = ? AND conversation_id = ?`, [observedAt, id, conversationId]);
2406
2580
  await scope.appendEvent({
2407
2581
  conversationId,
2408
2582
  kind: "schedule/cancelled",
@@ -2412,7 +2586,7 @@ function createAgentScheduleService(input) {
2412
2586
  return true;
2413
2587
  });
2414
2588
  if (changed)
2415
- arm();
2589
+ await arm();
2416
2590
  return changed;
2417
2591
  };
2418
2592
  return {
@@ -2423,56 +2597,63 @@ function createAgentScheduleService(input) {
2423
2597
  start: arm,
2424
2598
  close() {
2425
2599
  lifecycle.abort();
2426
- if (timer !== undefined)
2427
- clearTimer(timer);
2428
- timer = undefined;
2600
+ cancelTimer();
2429
2601
  }
2430
2602
  };
2431
2603
  }
2432
2604
  // src/agent-runtime/spill.ts
2433
2605
  import { createHash, randomUUID as randomUUID4 } from "node:crypto";
2434
- import { z as z12 } from "zod";
2435
- var SpillRowSchema = z12.object({
2436
- payload: z12.instanceof(Uint8Array),
2437
- bytes: z12.int().nonnegative(),
2438
- authorization_payload: z12.string().nullable()
2606
+ import { z as z10 } from "zod";
2607
+ var SpillRowSchema = z10.object({
2608
+ payload: z10.instanceof(Uint8Array),
2609
+ bytes: SqlIntegerSchema.pipe(z10.int().nonnegative()),
2610
+ authorization_payload: z10.string().nullable()
2439
2611
  });
2440
- var SpillMetadataRowSchema = z12.object({
2441
- reference_id: z12.string(),
2442
- bytes: z12.int().nonnegative(),
2443
- created_at: z12.string()
2612
+ var SpillMetadataRowSchema = z10.object({
2613
+ reference_id: z10.string(),
2614
+ bytes: SqlIntegerSchema.pipe(z10.int().nonnegative()),
2615
+ created_at: z10.string()
2444
2616
  });
2445
2617
  function decodeAuthorization(value) {
2446
2618
  if (value === null)
2447
2619
  return;
2448
- return JSON.parse(value);
2620
+ return AgentCodingToolAuthorizationSchema2.parse(JSON.parse(value));
2449
2621
  }
2450
- function createSqliteAgentSpillStore(input) {
2622
+ function createAgentSpillStore(input) {
2451
2623
  const now = input.now ?? (() => new Date);
2452
- const database = input.sqlite.database;
2453
- const rowFor = (reference) => {
2454
- const raw = database.prepare(`
2455
- SELECT payload, bytes, authorization_payload
2456
- FROM stitchkit_agent_runtime_spills
2457
- WHERE reference_id = ? AND conversation_id = ?
2458
- `).get(reference, input.conversationId);
2459
- if (raw === null || raw === undefined)
2624
+ const { host } = input;
2625
+ const spills = host.tables.spills;
2626
+ const rowFor = async (reference) => {
2627
+ const raw = await host.read((session) => session.get(`SELECT payload, bytes, authorization_payload FROM ${spills}
2628
+ WHERE reference_id = ? AND conversation_id = ?`, [reference, input.conversationId]));
2629
+ if (raw === undefined)
2460
2630
  refuseUnknownSpillReference(reference);
2461
2631
  return SpillRowSchema.parse(raw);
2462
2632
  };
2463
- const authorization = (reference) => decodeAuthorization(rowFor(reference).authorization_payload);
2633
+ const authorization = async (reference) => decodeAuthorization((await rowFor(reference)).authorization_payload);
2464
2634
  const write = async (request) => {
2635
+ const spillAuthorization = request.authorization === undefined ? undefined : AgentCodingToolAuthorizationSchema2.parse(request.authorization);
2465
2636
  const reference = randomUUID4();
2466
2637
  const createdAt = now();
2467
2638
  const expiresAt = input.retentionMs ? new Date(createdAt.getTime() + input.retentionMs).toISOString() : null;
2468
2639
  const sha256 = createHash("sha256").update(request.data).digest("hex");
2469
- await input.sqlite.transaction(async (scope) => {
2470
- scope.database.prepare(`
2471
- INSERT INTO stitchkit_agent_runtime_spills (
2472
- reference_id, conversation_id, run_id, tool_call_id, media_type,
2473
- bytes, sha256, created_at, expires_at, payload, authorization_payload
2474
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2475
- `).run(reference, input.conversationId, input.runId ?? null, input.toolCallId ?? null, request.mediaType, request.data.byteLength, sha256, createdAt.toISOString(), expiresAt, request.data, request.authorization ? JSON.stringify(request.authorization) : null);
2640
+ await host.transaction(input.conversationId, async (scope) => {
2641
+ await scope.run(`INSERT INTO ${spills} (
2642
+ reference_id, conversation_id, run_id, tool_call_id, media_type,
2643
+ bytes, sha256, created_at, expires_at, payload, authorization_payload
2644
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
2645
+ reference,
2646
+ input.conversationId,
2647
+ input.runId ?? null,
2648
+ request.toolCallId ?? null,
2649
+ request.mediaType,
2650
+ request.data.byteLength,
2651
+ sha256,
2652
+ createdAt.toISOString(),
2653
+ expiresAt,
2654
+ request.data,
2655
+ spillAuthorization !== undefined ? JSON.stringify(spillAuthorization) : null
2656
+ ]);
2476
2657
  await scope.appendEvent({
2477
2658
  conversationId: input.conversationId,
2478
2659
  kind: "spill/created",
@@ -2483,17 +2664,16 @@ function createSqliteAgentSpillStore(input) {
2483
2664
  return { reference };
2484
2665
  };
2485
2666
  const read = async (request) => {
2486
- const row = rowFor(request.reference);
2667
+ const row = await rowFor(request.reference);
2668
+ const rowAuthorization = decodeAuthorization(row.authorization_payload);
2487
2669
  return {
2488
2670
  data: row.payload.slice(request.offset, request.offset + request.maxBytes),
2489
2671
  totalBytes: row.bytes,
2490
- ...decodeAuthorization(row.authorization_payload) && {
2491
- authorization: decodeAuthorization(row.authorization_payload)
2492
- }
2672
+ ...rowAuthorization !== undefined && { authorization: rowAuthorization }
2493
2673
  };
2494
2674
  };
2495
- const search = (request) => {
2496
- const row = rowFor(request.reference);
2675
+ const search = async (request) => {
2676
+ const row = await rowFor(request.reference);
2497
2677
  const matches = [];
2498
2678
  new TextDecoder("utf-8", { fatal: true }).decode(row.payload).split(`
2499
2679
  `).forEach((text, index) => {
@@ -2504,39 +2684,48 @@ function createSqliteAgentSpillStore(input) {
2504
2684
  return matches;
2505
2685
  };
2506
2686
  const cleanup = async () => {
2507
- const expired = database.prepare(`
2508
- SELECT reference_id, bytes, created_at
2509
- FROM stitchkit_agent_runtime_spills
2510
- WHERE conversation_id = ? AND expires_at IS NOT NULL AND expires_at <= ?
2511
- ORDER BY created_at, reference_id
2512
- `).all(input.conversationId, now().toISOString()).map((row) => SpillMetadataRowSchema.parse(row));
2687
+ const expired = (await host.read((session) => session.all(`SELECT reference_id, bytes, created_at FROM ${spills}
2688
+ WHERE conversation_id = ? AND expires_at IS NOT NULL AND expires_at <= ?
2689
+ ORDER BY created_at, reference_id`, [input.conversationId, now().toISOString()]))).map((row) => SpillMetadataRowSchema.parse(row));
2690
+ let deleted = 0;
2513
2691
  let bytes = 0;
2514
2692
  for (const spill of expired) {
2515
- await input.sqlite.transaction(async (scope) => {
2516
- scope.database.prepare("DELETE FROM stitchkit_agent_runtime_spills WHERE reference_id = ?").run(spill.reference_id);
2693
+ const removed = await host.transaction(input.conversationId, async (scope) => {
2694
+ const existing = await scope.get(`SELECT reference_id FROM ${spills} WHERE reference_id = ? AND conversation_id = ?`, [spill.reference_id, input.conversationId]);
2695
+ if (existing === undefined)
2696
+ return false;
2697
+ await scope.run(`DELETE FROM ${spills} WHERE reference_id = ? AND conversation_id = ?`, [spill.reference_id, input.conversationId]);
2517
2698
  await scope.appendEvent({
2518
2699
  conversationId: input.conversationId,
2519
2700
  kind: "spill/deleted",
2520
2701
  payload: { reference: spill.reference_id, bytes: spill.bytes }
2521
2702
  });
2703
+ return true;
2522
2704
  });
2523
- bytes += spill.bytes;
2705
+ if (removed) {
2706
+ deleted += 1;
2707
+ bytes += spill.bytes;
2708
+ }
2524
2709
  }
2525
- return { deleted: expired.length, bytes };
2710
+ return { deleted, bytes };
2526
2711
  };
2527
2712
  return { authorization, write, read, search, cleanup };
2528
2713
  }
2529
2714
  // src/agent-runtime/state-tools.ts
2530
- import { z as z13 } from "zod";
2531
- var GoalSchema = z13.object({
2532
- objective: z13.string().min(1),
2533
- status: z13.enum(["active", "complete", "blocked"])
2715
+ import { z as z11 } from "zod";
2716
+ var GoalSchema = z11.object({
2717
+ objective: z11.string().min(1),
2718
+ status: z11.enum(["active", "complete", "blocked"])
2534
2719
  }).strict();
2535
- var TodoItemSchema = z13.object({
2536
- step: z13.string().min(1),
2537
- status: z13.enum(["pending", "in_progress", "completed"])
2720
+ var TodoItemSchema = z11.object({
2721
+ step: z11.string().min(1),
2722
+ status: z11.enum(["pending", "in_progress", "completed"])
2538
2723
  }).strict();
2539
- function createAgentStateTools(input) {
2724
+ function createAgentStateTools(config) {
2725
+ const input = {
2726
+ state: config.state,
2727
+ conversationId: conversationOfRun(config.run, "createAgentStateTools")
2728
+ };
2540
2729
  const writeGoal = async (value) => {
2541
2730
  const stored = await input.state.set({
2542
2731
  conversationId: input.conversationId,
@@ -2551,9 +2740,9 @@ function createAgentStateTools(input) {
2551
2740
  name: "create_goal",
2552
2741
  description: "Create the durable objective for this conversation.",
2553
2742
  identity: { serviceName: "agent-state", action: "create-goal", method: "POST" },
2554
- input: z13.object({ objective: z13.string().min(1) }).strict(),
2743
+ input: z11.object({ objective: z11.string().min(1) }).strict(),
2555
2744
  output: GoalSchema,
2556
- transports: ["AGENT"],
2745
+ expose: ["AGENT"],
2557
2746
  handler: async ({ input: request }) => {
2558
2747
  if (await input.state.get(input.conversationId, "goal")) {
2559
2748
  throw new TypeError("A durable goal already exists for this conversation");
@@ -2565,14 +2754,14 @@ function createAgentStateTools(input) {
2565
2754
  name: "update_goal",
2566
2755
  description: "Update the durable objective or lifecycle status.",
2567
2756
  identity: { serviceName: "agent-state", action: "update-goal", method: "POST" },
2568
- input: z13.object({
2569
- objective: z13.string().min(1).optional(),
2570
- status: z13.enum(["active", "complete", "blocked"]).optional()
2757
+ input: z11.object({
2758
+ objective: z11.string().min(1).optional(),
2759
+ status: z11.enum(["active", "complete", "blocked"]).optional()
2571
2760
  }).strict().refine((request) => request.objective !== undefined || request.status !== undefined, {
2572
2761
  message: "At least one goal field must be supplied"
2573
2762
  }),
2574
2763
  output: GoalSchema,
2575
- transports: ["AGENT"],
2764
+ expose: ["AGENT"],
2576
2765
  handler: async ({ input: request }) => {
2577
2766
  const current = await input.state.get(input.conversationId, "goal");
2578
2767
  if (!current)
@@ -2585,9 +2774,9 @@ function createAgentStateTools(input) {
2585
2774
  name: "get_goal",
2586
2775
  description: "Read the durable objective for this conversation.",
2587
2776
  identity: { serviceName: "agent-state", action: "get-goal", method: "GET" },
2588
- input: z13.object({}).strict(),
2589
- output: z13.object({ goal: GoalSchema.optional() }).strict(),
2590
- transports: ["AGENT"],
2777
+ input: z11.object({}).strict(),
2778
+ output: z11.object({ goal: GoalSchema.optional() }).strict(),
2779
+ expose: ["AGENT"],
2591
2780
  handler: async () => {
2592
2781
  const current = await input.state.get(input.conversationId, "goal");
2593
2782
  return { ...current && { goal: GoalSchema.parse(current.value) } };
@@ -2597,9 +2786,9 @@ function createAgentStateTools(input) {
2597
2786
  name: "todo_write",
2598
2787
  description: "Replace the durable ordered work plan for this conversation.",
2599
2788
  identity: { serviceName: "agent-state", action: "write-todo", method: "POST" },
2600
- input: z13.object({ items: z13.array(TodoItemSchema) }).strict(),
2601
- output: z13.object({ items: z13.array(TodoItemSchema) }).strict(),
2602
- transports: ["AGENT"],
2789
+ input: z11.object({ items: z11.array(TodoItemSchema) }).strict(),
2790
+ output: z11.object({ items: z11.array(TodoItemSchema) }).strict(),
2791
+ expose: ["AGENT"],
2603
2792
  handler: async ({ input: request }) => {
2604
2793
  const stored = await input.state.set({
2605
2794
  conversationId: input.conversationId,
@@ -2607,7 +2796,7 @@ function createAgentStateTools(input) {
2607
2796
  value: request,
2608
2797
  actor: "agent"
2609
2798
  });
2610
- return z13.object({ items: z13.array(TodoItemSchema) }).strict().parse(stored.value);
2799
+ return z11.object({ items: z11.array(TodoItemSchema) }).strict().parse(stored.value);
2611
2800
  }
2612
2801
  })
2613
2802
  ];
@@ -2620,17 +2809,21 @@ export {
2620
2809
  AgentAdmissionReceiptSchema2 as AgentAdmissionReceiptSchema,
2621
2810
  AgentAssistantPlaceholderSchema2 as AgentAssistantPlaceholderSchema,
2622
2811
  AgentAttemptResetEventSchema2 as AgentAttemptResetEventSchema,
2812
+ AgentBranchRefusalCodeSchema2 as AgentBranchRefusalCodeSchema,
2813
+ AgentBranchRefusalSchema2 as AgentBranchRefusalSchema,
2623
2814
  AgentCheckpointEventSchema2 as AgentCheckpointEventSchema,
2624
- AgentChildBlockingEventSchema,
2625
- AgentChildBlockingKindSchema,
2626
- AgentChildBlockingSourceSchema,
2627
- AgentChildBudgetSchema,
2628
- AgentChildRecordSchema,
2629
- AgentChildStateSchema,
2815
+ AgentChildBlockingEventSchema2 as AgentChildBlockingEventSchema,
2816
+ AgentChildBlockingKindSchema2 as AgentChildBlockingKindSchema,
2817
+ AgentChildBlockingSourceSchema2 as AgentChildBlockingSourceSchema,
2818
+ AgentChildBudgetSchema2 as AgentChildBudgetSchema,
2819
+ AgentChildRecordSchema2 as AgentChildRecordSchema,
2820
+ AgentChildStateSchema2 as AgentChildStateSchema,
2630
2821
  AgentContextOverflowError2 as AgentContextOverflowError,
2631
2822
  AgentControlPartSchema2 as AgentControlPartSchema,
2632
2823
  AgentConversationArchiveSchema2 as AgentConversationArchiveSchema,
2824
+ AgentConversationBranchPlanSchema2 as AgentConversationBranchPlanSchema,
2633
2825
  AgentConversationBranchReceiptSchema2 as AgentConversationBranchReceiptSchema,
2826
+ AgentConversationBranchRefusedError2 as AgentConversationBranchRefusedError,
2634
2827
  AgentConversationBranchResultSchema2 as AgentConversationBranchResultSchema,
2635
2828
  AgentConversationMessagePageSchema2 as AgentConversationMessagePageSchema,
2636
2829
  AgentConversationPageSchema2 as AgentConversationPageSchema,
@@ -2639,7 +2832,7 @@ export {
2639
2832
  AgentConversationPurgedError2 as AgentConversationPurgedError,
2640
2833
  AgentConversationSummarySchema2 as AgentConversationSummarySchema,
2641
2834
  AgentCostValueSchema2 as AgentCostValueSchema,
2642
- AgentEventSearchResultSchema,
2835
+ AgentEventSearchResultSchema2 as AgentEventSearchResultSchema,
2643
2836
  AgentFilePartSchema2 as AgentFilePartSchema,
2644
2837
  AgentHistoryMutationSchema2 as AgentHistoryMutationSchema,
2645
2838
  AgentJsonObjectSchema2 as AgentJsonObjectSchema,
@@ -2689,14 +2882,15 @@ export {
2689
2882
  AgentRuntimeEventCursorSchema2 as AgentRuntimeEventCursorSchema,
2690
2883
  AgentRuntimeEventSchema2 as AgentRuntimeEventSchema,
2691
2884
  AgentRuntimeHeadSchema2 as AgentRuntimeHeadSchema,
2692
- AgentSandboxGradeSchema2 as AgentSandboxGradeSchema,
2693
- AgentSandboxRestrictionSchema2 as AgentSandboxRestrictionSchema,
2694
2885
  AgentScheduleDeliveryOutcomeSchema,
2695
2886
  AgentScheduleSchema,
2696
2887
  AgentSeedReceiptSchema2 as AgentSeedReceiptSchema,
2697
2888
  AgentSnapshotSchema2 as AgentSnapshotSchema,
2698
2889
  AgentSourcePartSchema2 as AgentSourcePartSchema,
2890
+ AgentStepBarrierError2 as AgentStepBarrierError,
2699
2891
  AgentStepFinishedEventSchema,
2892
+ AgentStepSpendPhaseSchema2 as AgentStepSpendPhaseSchema,
2893
+ AgentStepSpendSchema2 as AgentStepSpendSchema,
2700
2894
  AgentStoreAppliedSchema2 as AgentStoreAppliedSchema,
2701
2895
  AgentStoreConflictSchema2 as AgentStoreConflictSchema,
2702
2896
  AgentStoreDuplicateSchema2 as AgentStoreDuplicateSchema,
@@ -2707,6 +2901,7 @@ export {
2707
2901
  AgentStoreNotFoundSchema2 as AgentStoreNotFoundSchema,
2708
2902
  AgentStoreTransitionRecordSchema2 as AgentStoreTransitionRecordSchema,
2709
2903
  AgentStoreTransitionSchema2 as AgentStoreTransitionSchema,
2904
+ AgentStoreUnsupportedCapabilityError2 as AgentStoreUnsupportedCapabilityError,
2710
2905
  AgentStoredRunSchema2 as AgentStoredRunSchema,
2711
2906
  AgentTerminalEventSchema2 as AgentTerminalEventSchema,
2712
2907
  AgentTerminalReasonSchema2 as AgentTerminalReasonSchema,
@@ -2728,9 +2923,9 @@ export {
2728
2923
  CommitRunTerminalSchema2 as CommitRunTerminalSchema,
2729
2924
  CompletionInvocationInputSchema2 as CompletionInvocationInputSchema,
2730
2925
  DURABILITY_STEP_EVENT_KIND2 as DURABILITY_STEP_EVENT_KIND,
2731
- DeferredAgentToolMatchSchema,
2732
- DeferredAgentToolReceiptSchema,
2733
- DeferredAgentToolSearchInputSchema,
2926
+ DeferredAgentToolMatchSchema2 as DeferredAgentToolMatchSchema,
2927
+ DeferredAgentToolReceiptSchema2 as DeferredAgentToolReceiptSchema,
2928
+ DeferredAgentToolSearchInputSchema2 as DeferredAgentToolSearchInputSchema,
2734
2929
  ModelInvocationRecordSchema2 as ModelInvocationRecordSchema,
2735
2930
  ModelInvocationTraceSchema2 as ModelInvocationTraceSchema,
2736
2931
  ParkAbortedError2 as ParkAbortedError,
@@ -2758,16 +2953,20 @@ export {
2758
2953
  canonicalAgentJson2 as canonicalAgentJson,
2759
2954
  classifyProviderFailure2 as classifyProviderFailure,
2760
2955
  composeAgentPrompt2 as composeAgentPrompt,
2956
+ createAgentChildManager,
2761
2957
  createAgentChildTools,
2762
- createAgentEventSearchTools,
2958
+ createAgentEventSearch2 as createAgentEventSearch,
2959
+ createAgentEventSearchTools2 as createAgentEventSearchTools,
2763
2960
  createAgentObservability,
2764
2961
  createAgentProjectionRegistry,
2962
+ createAgentProjectionStore,
2765
2963
  createAgentRuntime2 as createAgentRuntime,
2766
2964
  createAgentRuntimeEventSink2 as createAgentRuntimeEventSink,
2767
2965
  createAgentRuntimeStore2 as createAgentRuntimeStore,
2768
2966
  createAgentScheduleService,
2769
2967
  createAgentScheduleTools,
2770
2968
  createAgentSessionCoordinator2 as createAgentSessionCoordinator,
2969
+ createAgentSpillStore,
2771
2970
  createAgentStateSlotStore2 as createAgentStateSlotStore,
2772
2971
  createAgentStateTools,
2773
2972
  createAgentToolFenceLifecycle2 as createAgentToolFenceLifecycle,
@@ -2775,10 +2974,7 @@ export {
2775
2974
  createMemoryAgentModelSelectionStore2 as createMemoryAgentModelSelectionStore,
2776
2975
  createMemoryAgentRuntimeStore2 as createMemoryAgentRuntimeStore,
2777
2976
  createModelInvocationLedger2 as createModelInvocationLedger,
2778
- createSqliteAgentChildManager,
2779
- createSqliteAgentEventSearch,
2780
- createSqliteAgentProjectionStore,
2781
- createSqliteAgentSpillStore,
2977
+ createToolDependencyResolver2 as createToolDependencyResolver,
2782
2978
  currentModelInvocationAttempt2 as currentModelInvocationAttempt,
2783
2979
  decodeAgentConversationArchive2 as decodeAgentConversationArchive,
2784
2980
  decodeAgentStoreEvent2 as decodeAgentStoreEvent,
@@ -2790,13 +2986,11 @@ export {
2790
2986
  hasAgentTerminalOutput,
2791
2987
  isAssistantHistoryEvidence2 as isAssistantHistoryEvidence,
2792
2988
  isToolResultFailure2 as isToolResultFailure,
2793
- missingSandboxRestrictions2 as missingSandboxRestrictions,
2794
- probeAgentProcessSandbox2 as probeAgentProcessSandbox,
2989
+ modelInvocationSpendAttribution,
2795
2990
  projectAgentHistory2 as projectAgentHistory,
2796
2991
  projectAgentHistoryDetailed2 as projectAgentHistoryDetailed,
2797
2992
  purgeAgentConversation2 as purgeAgentConversation,
2798
2993
  recordAgentRetryDecision2 as recordAgentRetryDecision,
2799
- recordAgentSandboxProbe2 as recordAgentSandboxProbe,
2800
2994
  renderAgentStateSlots2 as renderAgentStateSlots,
2801
2995
  runStateForTerminalReason2 as runStateForTerminalReason,
2802
2996
  searchAgentModelCatalog2 as searchAgentModelCatalog,