stitchkit 0.135.0 → 0.136.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (380) hide show
  1. package/CHANGELOG.md +117 -0
  2. package/README.md +25 -11
  3. package/dist/agent-executor/acp/v1-session-build.d.ts +51 -0
  4. package/dist/agent-executor/acp/v1-session-build.d.ts.map +1 -0
  5. package/dist/agent-executor/acp/v1-session.d.ts +1 -1
  6. package/dist/agent-executor/acp/v1-session.d.ts.map +1 -1
  7. package/dist/agent-executor/claude/classify.d.ts +1 -1
  8. package/dist/agent-executor/claude/classify.d.ts.map +1 -1
  9. package/dist/agent-executor/claude/events-wire.d.ts +13 -0
  10. package/dist/agent-executor/claude/events-wire.d.ts.map +1 -0
  11. package/dist/agent-executor/claude/events.d.ts +1 -11
  12. package/dist/agent-executor/claude/events.d.ts.map +1 -1
  13. package/dist/agent-executor/codex/protocol.d.ts +0 -143
  14. package/dist/agent-executor/codex/protocol.d.ts.map +1 -1
  15. package/dist/agent-executor/codex/request-answers.d.ts +1 -1
  16. package/dist/agent-executor/codex/request-answers.d.ts.map +1 -1
  17. package/dist/agent-executor/codex/server-requests.d.ts +150 -0
  18. package/dist/agent-executor/codex/server-requests.d.ts.map +1 -0
  19. package/dist/agent-executor/image-input.d.ts +10 -3
  20. package/dist/agent-executor/image-input.d.ts.map +1 -1
  21. package/dist/agent-executor/testing/replay-scenarios.d.ts.map +1 -1
  22. package/dist/agent-executor/testing/replay-transcript.d.ts.map +1 -1
  23. package/dist/agent-runtime/browser/browser-control-contract.d.ts +4 -0
  24. package/dist/agent-runtime/browser/browser-control-contract.d.ts.map +1 -1
  25. package/dist/agent-runtime/browser/control-schema.d.ts +4 -0
  26. package/dist/agent-runtime/browser/control-schema.d.ts.map +1 -1
  27. package/dist/agent-runtime/browser/control-view.d.ts.map +1 -1
  28. package/dist/agent-runtime/event-schema.d.ts +16 -3
  29. package/dist/agent-runtime/event-schema.d.ts.map +1 -1
  30. package/dist/agent-runtime/loop/deferred-tools.d.ts.map +1 -1
  31. package/dist/agent-runtime/loop/invocation-payload.d.ts.map +1 -1
  32. package/dist/agent-runtime/loop/invocation-stream.d.ts +9 -1
  33. package/dist/agent-runtime/loop/invocation-stream.d.ts.map +1 -1
  34. package/dist/agent-runtime/loop/provider-stream-parts.d.ts +6 -0
  35. package/dist/agent-runtime/loop/provider-stream-parts.d.ts.map +1 -1
  36. package/dist/agent-runtime/loop/provider-stream-segments.d.ts +1 -1
  37. package/dist/agent-runtime/loop/provider-stream-segments.d.ts.map +1 -1
  38. package/dist/agent-runtime/loop/run-acquisition.d.ts.map +1 -1
  39. package/dist/agent-runtime/loop/run-approval-signature.d.ts +34 -0
  40. package/dist/agent-runtime/loop/run-approval-signature.d.ts.map +1 -0
  41. package/dist/agent-runtime/loop/run-approval.d.ts +0 -28
  42. package/dist/agent-runtime/loop/run-approval.d.ts.map +1 -1
  43. package/dist/agent-runtime/loop/run-complete-port.d.ts +24 -0
  44. package/dist/agent-runtime/loop/run-complete-port.d.ts.map +1 -0
  45. package/dist/agent-runtime/loop/run-complete-stream.d.ts +7 -2
  46. package/dist/agent-runtime/loop/run-complete-stream.d.ts.map +1 -1
  47. package/dist/agent-runtime/loop/run-complete-types.d.ts +14 -1
  48. package/dist/agent-runtime/loop/run-complete-types.d.ts.map +1 -1
  49. package/dist/agent-runtime/loop/run-complete.d.ts +2 -2
  50. package/dist/agent-runtime/loop/run-complete.d.ts.map +1 -1
  51. package/dist/agent-runtime/loop/run-execution-state.d.ts +8 -0
  52. package/dist/agent-runtime/loop/run-execution-state.d.ts.map +1 -1
  53. package/dist/agent-runtime/loop/run-model-call.d.ts +44 -0
  54. package/dist/agent-runtime/loop/run-model-call.d.ts.map +1 -0
  55. package/dist/agent-runtime/loop/run-model-step.d.ts +25 -28
  56. package/dist/agent-runtime/loop/run-model-step.d.ts.map +1 -1
  57. package/dist/agent-runtime/loop/run-model-steps.d.ts +6 -0
  58. package/dist/agent-runtime/loop/run-model-steps.d.ts.map +1 -0
  59. package/dist/agent-runtime/loop/run-model-stream.d.ts +3 -1
  60. package/dist/agent-runtime/loop/run-model-stream.d.ts.map +1 -1
  61. package/dist/agent-runtime/loop/run-operation-lifecycle.d.ts +0 -2
  62. package/dist/agent-runtime/loop/run-operation-lifecycle.d.ts.map +1 -1
  63. package/dist/agent-runtime/loop/run-step-loop.d.ts +19 -0
  64. package/dist/agent-runtime/loop/run-step-loop.d.ts.map +1 -0
  65. package/dist/agent-runtime/loop/run-step-port.d.ts +175 -0
  66. package/dist/agent-runtime/loop/run-step-port.d.ts.map +1 -0
  67. package/dist/agent-runtime/loop/run-stream-parts.d.ts.map +1 -1
  68. package/dist/agent-runtime/loop/run-stream-step-text.d.ts.map +1 -1
  69. package/dist/agent-runtime/loop/run-tool-approval-flow.d.ts +2 -1
  70. package/dist/agent-runtime/loop/run-tool-approval-flow.d.ts.map +1 -1
  71. package/dist/agent-runtime/loop/run-tool-call-input.d.ts +39 -0
  72. package/dist/agent-runtime/loop/run-tool-call-input.d.ts.map +1 -0
  73. package/dist/agent-runtime/loop/run-tool-call.d.ts +2 -31
  74. package/dist/agent-runtime/loop/run-tool-call.d.ts.map +1 -1
  75. package/dist/agent-runtime/loop/run-tool-errors.d.ts +5 -0
  76. package/dist/agent-runtime/loop/run-tool-errors.d.ts.map +1 -1
  77. package/dist/agent-runtime/loop/run-tool-executor.d.ts +1 -1
  78. package/dist/agent-runtime/loop/run-tool-executor.d.ts.map +1 -1
  79. package/dist/agent-runtime/loop/run-tool-slots.d.ts +2 -1
  80. package/dist/agent-runtime/loop/run-tool-slots.d.ts.map +1 -1
  81. package/dist/agent-runtime/loop/runtime-state.d.ts.map +1 -1
  82. package/dist/agent-runtime/loop/runtime.d.ts +0 -5
  83. package/dist/agent-runtime/loop/runtime.d.ts.map +1 -1
  84. package/dist/agent-runtime/providers/ai-sdk-convert.d.ts +1 -5
  85. package/dist/agent-runtime/providers/ai-sdk-convert.d.ts.map +1 -1
  86. package/dist/agent-runtime/providers/ai-sdk-normalize.d.ts +11 -0
  87. package/dist/agent-runtime/providers/ai-sdk-normalize.d.ts.map +1 -0
  88. package/dist/agent-runtime/providers/ai-sdk-tools.d.ts +11 -0
  89. package/dist/agent-runtime/providers/ai-sdk-tools.d.ts.map +1 -0
  90. package/dist/agent-runtime/providers/ai-sdk.d.ts +1 -9
  91. package/dist/agent-runtime/providers/ai-sdk.d.ts.map +1 -1
  92. package/dist/agent-runtime/providers/anthropic-sse.d.ts.map +1 -1
  93. package/dist/agent-runtime/providers/openrouter-admission.d.ts.map +1 -1
  94. package/dist/agent-runtime/providers/openrouter-audio.d.ts +164 -0
  95. package/dist/agent-runtime/providers/openrouter-audio.d.ts.map +1 -0
  96. package/dist/agent-runtime/providers/openrouter-catalog-cache.d.ts.map +1 -1
  97. package/dist/agent-runtime/providers/openrouter-catalog-query.d.ts.map +1 -1
  98. package/dist/agent-runtime/providers/openrouter-catalog.d.ts +4 -2
  99. package/dist/agent-runtime/providers/openrouter-catalog.d.ts.map +1 -1
  100. package/dist/agent-runtime/providers/openrouter-client.d.ts +37 -0
  101. package/dist/agent-runtime/providers/openrouter-client.d.ts.map +1 -0
  102. package/dist/agent-runtime/providers/openrouter-http.d.ts +120 -0
  103. package/dist/agent-runtime/providers/openrouter-http.d.ts.map +1 -0
  104. package/dist/agent-runtime/providers/openrouter-media.d.ts +174 -0
  105. package/dist/agent-runtime/providers/openrouter-media.d.ts.map +1 -0
  106. package/dist/agent-runtime/providers/openrouter-models.d.ts +2 -23
  107. package/dist/agent-runtime/providers/openrouter-models.d.ts.map +1 -1
  108. package/dist/agent-runtime/providers/openrouter-options.d.ts +4 -0
  109. package/dist/agent-runtime/providers/openrouter-options.d.ts.map +1 -1
  110. package/dist/agent-runtime/providers/openrouter-request.d.ts +23 -0
  111. package/dist/agent-runtime/providers/openrouter-request.d.ts.map +1 -0
  112. package/dist/agent-runtime/providers/openrouter-response.d.ts.map +1 -1
  113. package/dist/agent-runtime/providers/openrouter-retrieval.d.ts +145 -0
  114. package/dist/agent-runtime/providers/openrouter-retrieval.d.ts.map +1 -0
  115. package/dist/agent-runtime/providers/openrouter-speech.d.ts +90 -0
  116. package/dist/agent-runtime/providers/openrouter-speech.d.ts.map +1 -0
  117. package/dist/agent-runtime/providers/openrouter-spend.d.ts +7 -3
  118. package/dist/agent-runtime/providers/openrouter-spend.d.ts.map +1 -1
  119. package/dist/agent-runtime/providers/openrouter-stream.d.ts +29 -0
  120. package/dist/agent-runtime/providers/openrouter-stream.d.ts.map +1 -0
  121. package/dist/agent-runtime/providers/openrouter-systemone.d.ts +137 -0
  122. package/dist/agent-runtime/providers/openrouter-systemone.d.ts.map +1 -0
  123. package/dist/agent-runtime/providers/openrouter-url.d.ts +19 -0
  124. package/dist/agent-runtime/providers/openrouter-url.d.ts.map +1 -0
  125. package/dist/agent-runtime/providers/openrouter-wire.d.ts +45 -0
  126. package/dist/agent-runtime/providers/openrouter-wire.d.ts.map +1 -0
  127. package/dist/agent-runtime/providers/openrouter.d.ts +5 -4
  128. package/dist/agent-runtime/providers/openrouter.d.ts.map +1 -1
  129. package/dist/agent-runtime/providers/provider-http.d.ts +29 -3
  130. package/dist/agent-runtime/providers/provider-http.d.ts.map +1 -1
  131. package/dist/agent-runtime/providers/provider-json-schema-strip.d.ts.map +1 -1
  132. package/dist/agent-runtime/providers/provider-json-schema.d.ts.map +1 -1
  133. package/dist/agent-runtime/providers/provider-openai-chat-sse.d.ts.map +1 -1
  134. package/dist/agent-runtime/providers/provider-openai-chat-state.d.ts +42 -0
  135. package/dist/agent-runtime/providers/provider-openai-chat-state.d.ts.map +1 -0
  136. package/dist/agent-runtime/providers/provider-usage.d.ts +9 -0
  137. package/dist/agent-runtime/providers/provider-usage.d.ts.map +1 -1
  138. package/dist/agent-runtime/sandbox/sandbox-bubblewrap-args.d.ts +9 -0
  139. package/dist/agent-runtime/sandbox/sandbox-bubblewrap-args.d.ts.map +1 -1
  140. package/dist/agent-runtime/sandbox/sandbox-bubblewrap.d.ts +6 -0
  141. package/dist/agent-runtime/sandbox/sandbox-bubblewrap.d.ts.map +1 -1
  142. package/dist/agent-runtime/sandbox/sandbox-contract.d.ts.map +1 -1
  143. package/dist/agent-runtime/sandbox/sandbox-process-linux.d.ts.map +1 -1
  144. package/dist/agent-runtime/sandbox/sandbox-process-spec.d.ts +5 -1
  145. package/dist/agent-runtime/sandbox/sandbox-process-spec.d.ts.map +1 -1
  146. package/dist/agent-runtime/sandbox/sandbox-process-wrapper.d.ts.map +1 -1
  147. package/dist/agent-runtime/stores/branch-messages.d.ts.map +1 -1
  148. package/dist/agent-runtime/stores/sql-rows.d.ts +10 -10
  149. package/dist/agent-runtime/terminal-commit.d.ts +10 -10
  150. package/dist/agent-runtime/testing/fault-bench.d.ts +5 -1
  151. package/dist/agent-runtime/testing/fault-bench.d.ts.map +1 -1
  152. package/dist/application/diagnostic-journal-contract.d.ts.map +1 -1
  153. package/dist/browser/client-executors.d.ts.map +1 -1
  154. package/dist/browser/client-url.d.ts.map +1 -1
  155. package/dist/contract/define.d.ts +3 -7
  156. package/dist/contract/define.d.ts.map +1 -1
  157. package/dist/contract/normalize.d.ts +17 -5
  158. package/dist/contract/normalize.d.ts.map +1 -1
  159. package/dist/entrypoints/agent-executor/acp.js +4 -2
  160. package/dist/entrypoints/agent-executor/claude-sdk.js +20 -20
  161. package/dist/entrypoints/agent-executor/claude.js +7 -7
  162. package/dist/entrypoints/agent-executor/codex.d.ts +2 -1
  163. package/dist/entrypoints/agent-executor/codex.d.ts.map +1 -1
  164. package/dist/entrypoints/agent-executor/codex.js +129 -35
  165. package/dist/entrypoints/agent-executor/testing/claude-sdk.js +2 -2
  166. package/dist/entrypoints/agent-executor/testing.js +17 -13
  167. package/dist/entrypoints/agent-executor.js +1 -1
  168. package/dist/entrypoints/agent-runtime/ai-sdk.d.ts +2 -1
  169. package/dist/entrypoints/agent-runtime/ai-sdk.d.ts.map +1 -1
  170. package/dist/entrypoints/agent-runtime/ai-sdk.js +10 -12
  171. package/dist/entrypoints/agent-runtime/anthropic.js +13 -10
  172. package/dist/entrypoints/agent-runtime/browser.js +8 -4
  173. package/dist/entrypoints/agent-runtime/harness.js +18 -19
  174. package/dist/entrypoints/agent-runtime/openai.js +5 -5
  175. package/dist/entrypoints/agent-runtime/openrouter.d.ts +11 -2
  176. package/dist/entrypoints/agent-runtime/openrouter.d.ts.map +1 -1
  177. package/dist/entrypoints/agent-runtime/openrouter.js +1940 -496
  178. package/dist/entrypoints/agent-runtime/postgres.js +2 -2
  179. package/dist/entrypoints/agent-runtime/realtime.js +5 -5
  180. package/dist/entrypoints/agent-runtime/sandbox.js +167 -139
  181. package/dist/entrypoints/agent-runtime/sqlite/bun.js +3 -3
  182. package/dist/entrypoints/agent-runtime/sqlite/node.js +3 -3
  183. package/dist/entrypoints/agent-runtime/testing.js +3 -3
  184. package/dist/entrypoints/agent-runtime.js +246 -360
  185. package/dist/entrypoints/application.js +2 -2
  186. package/dist/entrypoints/cli.js +36 -15
  187. package/dist/entrypoints/contract.js +12 -10
  188. package/dist/entrypoints/geo.js +1 -1
  189. package/dist/entrypoints/handler.js +5 -6
  190. package/dist/entrypoints/http.d.ts +2 -0
  191. package/dist/entrypoints/http.d.ts.map +1 -1
  192. package/dist/entrypoints/http.js +16 -4
  193. package/dist/entrypoints/index.js +26 -35
  194. package/dist/entrypoints/live.js +3 -3
  195. package/dist/entrypoints/node.js +7 -7
  196. package/dist/entrypoints/observability.js +9 -7
  197. package/dist/entrypoints/process.js +3 -3
  198. package/dist/entrypoints/remote.js +5 -5
  199. package/dist/entrypoints/server.js +29 -16
  200. package/dist/entrypoints/telegram/grammy.d.ts +1 -1
  201. package/dist/entrypoints/telegram/grammy.d.ts.map +1 -1
  202. package/dist/entrypoints/telegram/grammy.js +39 -5
  203. package/dist/entrypoints/telegram/screens.js +3 -0
  204. package/dist/entrypoints/telegram.d.ts +1 -1
  205. package/dist/entrypoints/telegram.d.ts.map +1 -1
  206. package/dist/entrypoints/telegram.js +19 -6
  207. package/dist/entrypoints/testing.js +10 -11
  208. package/dist/entrypoints/tools/agent.js +8 -9
  209. package/dist/entrypoints/tools/connections.js +27 -57
  210. package/dist/entrypoints/tools/contract.js +4 -4
  211. package/dist/entrypoints/tools/invoker.js +7 -8
  212. package/dist/entrypoints/tools/mcp.js +9 -10
  213. package/dist/entrypoints/tools/toolkit.js +11 -12
  214. package/dist/entrypoints/tools.js +20 -20
  215. package/dist/entrypoints/tracking/contract.js +1 -1
  216. package/dist/entrypoints/tracking/performance.js +1 -1
  217. package/dist/entrypoints/tracking.js +1 -1
  218. package/dist/{index-3czc3ykr.js → index-08a3qfr8.js} +1 -1
  219. package/dist/{index-grhhsrd5.js → index-1en7k3q5.js} +2 -1
  220. package/dist/{index-pdcbjd6a.js → index-1yky29qg.js} +6 -3
  221. package/dist/{index-b4c9dpzm.js → index-252den5a.js} +10 -11
  222. package/dist/{index-xtby8rj3.js → index-28kbdn63.js} +5 -47
  223. package/dist/{index-57sbckhv.js → index-36mtj8xm.js} +2 -2
  224. package/dist/{index-dm84tsd5.js → index-3kb8dw48.js} +1 -1
  225. package/dist/index-3tb82xr7.js +11 -0
  226. package/dist/{index-c24bj2r1.js → index-4243301z.js} +2 -2
  227. package/dist/{index-nr4fhfn4.js → index-4p2zx593.js} +2 -0
  228. package/dist/{index-q86qnzzf.js → index-54wp467c.js} +4 -4
  229. package/dist/{index-mcv7b2n0.js → index-63ctzjp4.js} +497 -495
  230. package/dist/{index-y0a4gt1s.js → index-65p8v81y.js} +3 -2
  231. package/dist/{index-z72vazf5.js → index-6y3eae97.js} +27 -83
  232. package/dist/{index-5awtbyns.js → index-9vj869rx.js} +1 -1
  233. package/dist/{index-5q0qpw3v.js → index-aqm7e864.js} +23 -8
  234. package/dist/{index-d4at0q09.js → index-b9mj31q7.js} +90 -88
  235. package/dist/{index-baba8ehy.js → index-bjrcbcn2.js} +2 -2
  236. package/dist/{index-fsw9wxk9.js → index-c9j8441q.js} +1 -103
  237. package/dist/{index-wdb5jhas.js → index-d1pdv8qc.js} +1 -1
  238. package/dist/{index-73wq9abg.js → index-df5xr2f9.js} +13 -59
  239. package/dist/{index-n9358ydy.js → index-dm50x3by.js} +1 -1
  240. package/dist/{index-zyyerdny.js → index-dmrx8xma.js} +3 -0
  241. package/dist/{index-78da4g74.js → index-dwq6a6sq.js} +17 -13
  242. package/dist/{index-9be3tf6r.js → index-e413q2cj.js} +49 -22
  243. package/dist/{index-g4gstmp1.js → index-ednf2cxs.js} +1 -1
  244. package/dist/{index-84tp547a.js → index-edpkm3k7.js} +29 -97
  245. package/dist/{index-gs0jw0hy.js → index-efbzm2se.js} +3 -3
  246. package/dist/{index-de7b0kvz.js → index-epwvp88y.js} +1 -1
  247. package/dist/{index-asnd4h2k.js → index-f0dzyskg.js} +27 -4
  248. package/dist/{index-xbb8ysmq.js → index-fatke81t.js} +2 -2
  249. package/dist/{index-6nzzj7qr.js → index-gq35s3bm.js} +1 -1
  250. package/dist/index-gvgtmt7a.js +102 -0
  251. package/dist/{index-m2b49tvc.js → index-h08xqfw9.js} +20 -21
  252. package/dist/{index-gk6dq9ay.js → index-ha1tv70k.js} +3 -26
  253. package/dist/{index-wsv11dhg.js → index-hberxns4.js} +1 -1
  254. package/dist/{index-rkphknhx.js → index-hpzhz1vm.js} +1 -1
  255. package/dist/{index-npfdymav.js → index-j5vzhj3d.js} +1 -1
  256. package/dist/{index-d3s070eh.js → index-jperyn0c.js} +1 -1
  257. package/dist/{index-yhwx4fwk.js → index-kzsetgh9.js} +1 -1
  258. package/dist/{index-x6sp5vpa.js → index-q4tr9vnf.js} +1 -1
  259. package/dist/{index-hce3hbdg.js → index-qj0sq69b.js} +6 -2
  260. package/dist/{index-v0j22shs.js → index-rg08syp1.js} +9 -6
  261. package/dist/{index-8vzh5wpv.js → index-rw1caff2.js} +14 -26
  262. package/dist/index-s8af9jqw.js +6 -0
  263. package/dist/{index-bgj9hbm3.js → index-sdppfbrh.js} +30 -16
  264. package/dist/{index-y0mwkgkf.js → index-shte29pg.js} +1086 -1055
  265. package/dist/{index-fec05c9k.js → index-ta0e2daw.js} +9 -7
  266. package/dist/{index-zfrysr1e.js → index-tb36xawm.js} +110 -75
  267. package/dist/{index-c0yym4a0.js → index-w7e402wx.js} +11 -105
  268. package/dist/{index-bvpevwt6.js → index-xnqab06h.js} +207 -202
  269. package/dist/index-xrbrvn15.js +147 -0
  270. package/dist/{index-ac3rfec5.js → index-y6wzzk2e.js} +21 -1
  271. package/dist/{index-3d2c45jn.js → index-yjx5jna7.js} +2 -2
  272. package/dist/internal/loopback-host.d.ts +8 -0
  273. package/dist/internal/loopback-host.d.ts.map +1 -0
  274. package/dist/internal/own-member.d.ts +7 -0
  275. package/dist/internal/own-member.d.ts.map +1 -0
  276. package/dist/internal/request.d.ts +17 -8
  277. package/dist/internal/request.d.ts.map +1 -1
  278. package/dist/internal/secret-shapes.d.ts +33 -4
  279. package/dist/internal/secret-shapes.d.ts.map +1 -1
  280. package/dist/json-schema/dialect.d.ts.map +1 -1
  281. package/dist/json-schema/keywords.d.ts +25 -6
  282. package/dist/json-schema/keywords.d.ts.map +1 -1
  283. package/dist/json-schema/string-format.d.ts.map +1 -1
  284. package/dist/live/events.d.ts.map +1 -1
  285. package/dist/live/watch-client.d.ts.map +1 -1
  286. package/dist/live/watch-delta.d.ts.map +1 -1
  287. package/dist/observability/context.d.ts +4 -3
  288. package/dist/observability/context.d.ts.map +1 -1
  289. package/dist/observability/sanitize.d.ts.map +1 -1
  290. package/dist/observability/secret-values.d.ts +0 -9
  291. package/dist/observability/secret-values.d.ts.map +1 -1
  292. package/dist/server/context.d.ts +3 -2
  293. package/dist/server/context.d.ts.map +1 -1
  294. package/dist/server/error-hook.d.ts +4 -3
  295. package/dist/server/error-hook.d.ts.map +1 -1
  296. package/dist/server/event-bus.d.ts.map +1 -1
  297. package/dist/server/file.d.ts +11 -3
  298. package/dist/server/file.d.ts.map +1 -1
  299. package/dist/server/handler-state.d.ts +2 -2
  300. package/dist/server/handler-state.d.ts.map +1 -1
  301. package/dist/server/middleware/jwt.d.ts +12 -1
  302. package/dist/server/middleware/jwt.d.ts.map +1 -1
  303. package/dist/server/middleware/trust-fence.d.ts +4 -0
  304. package/dist/server/middleware/trust-fence.d.ts.map +1 -1
  305. package/dist/server/multipart.d.ts +2 -3
  306. package/dist/server/multipart.d.ts.map +1 -1
  307. package/dist/server/raw.d.ts.map +1 -1
  308. package/dist/server/request-body.d.ts +12 -1
  309. package/dist/server/request-body.d.ts.map +1 -1
  310. package/dist/server/request-completion.d.ts.map +1 -1
  311. package/dist/server/types.d.ts +14 -9
  312. package/dist/server/types.d.ts.map +1 -1
  313. package/dist/telegram/crypto.d.ts.map +1 -1
  314. package/dist/telegram/init-data.d.ts +4 -4
  315. package/dist/telegram/init-data.d.ts.map +1 -1
  316. package/dist/telegram/outbound-cost.d.ts.map +1 -1
  317. package/dist/telegram/screens/test-chat.d.ts.map +1 -1
  318. package/dist/telegram/widget-api.d.ts +85 -13
  319. package/dist/telegram/widget-api.d.ts.map +1 -1
  320. package/dist/telegram/widget.d.ts +46 -2
  321. package/dist/telegram/widget.d.ts.map +1 -1
  322. package/dist/tools/cli/args-classify.d.ts +4 -74
  323. package/dist/tools/cli/args-classify.d.ts.map +1 -1
  324. package/dist/tools/cli/args-framework.d.ts +79 -0
  325. package/dist/tools/cli/args-framework.d.ts.map +1 -0
  326. package/dist/tools/cli/args-scan.d.ts.map +1 -1
  327. package/dist/tools/cli/args-tokens.d.ts.map +1 -1
  328. package/dist/tools/cli/checkpoint.d.ts +5 -0
  329. package/dist/tools/cli/checkpoint.d.ts.map +1 -1
  330. package/dist/tools/cli/stream.d.ts.map +1 -1
  331. package/dist/tools/connections/foreign-schema-join.d.ts.map +1 -1
  332. package/dist/tools/connections/openapi.d.ts.map +1 -1
  333. package/dist/tools/connections/runtime.d.ts.map +1 -1
  334. package/dist/tools/execute-handler.d.ts +24 -0
  335. package/dist/tools/execute-handler.d.ts.map +1 -0
  336. package/dist/tools/execute.d.ts.map +1 -1
  337. package/dist/tools/mcp/round.d.ts.map +1 -1
  338. package/dist/tools/schema/coerce.d.ts.map +1 -1
  339. package/dist/tools/schema/flatten.d.ts.map +1 -1
  340. package/dist/tools/schema/inline-references.d.ts.map +1 -1
  341. package/dist/tools/schema/nesting-limit.d.ts.map +1 -1
  342. package/dist/tools/schema/presentation.d.ts.map +1 -1
  343. package/dist/tracking/privacy.d.ts.map +1 -1
  344. package/llms/agent-runtime-openrouter.txt +14 -5
  345. package/llms/agent-runtime-sandbox.txt +50 -11
  346. package/llms/agent-runtime-testing.txt +1 -1
  347. package/llms/agent-runtime.2.txt +342 -230
  348. package/llms/agent-runtime.3.txt +225 -380
  349. package/llms/agent-runtime.4.txt +387 -158
  350. package/llms/agent-runtime.5.txt +157 -152
  351. package/llms/agent-runtime.6.txt +164 -0
  352. package/llms/agent-runtime.txt +307 -362
  353. package/llms/application.txt +3 -1
  354. package/llms/http.txt +1 -1
  355. package/llms/live.txt +3 -1
  356. package/llms/observability.txt +16 -9
  357. package/llms/server.2.txt +13 -8
  358. package/llms/server.4.txt +23 -11
  359. package/llms/server.5.txt +5 -5
  360. package/llms/server.txt +54 -1
  361. package/llms/spend.txt +18 -1
  362. package/llms/stitchkit.2.txt +4 -2
  363. package/llms/stitchkit.txt +113 -93
  364. package/llms/telegram-grammy.txt +3 -2
  365. package/llms/telegram.2.txt +3 -1
  366. package/llms/telegram.txt +35 -10
  367. package/llms/upgrading-0.128.0-0.129.0.txt +175 -0
  368. package/llms/{upgrading-0.128.0-0.135.0.txt → upgrading-0.130.0-0.136.0.txt} +353 -169
  369. package/llms/upgrading.txt +2 -1
  370. package/llms-full.txt +1035 -208
  371. package/llms.txt +14 -13
  372. package/package.json +6 -6
  373. package/dist/agent-runtime/loop/deferred-tools-internal.d.ts +0 -19
  374. package/dist/agent-runtime/loop/deferred-tools-internal.d.ts.map +0 -1
  375. package/dist/agent-runtime/loop/run-complete-retry.d.ts +0 -24
  376. package/dist/agent-runtime/loop/run-complete-retry.d.ts.map +0 -1
  377. package/dist/agent-runtime/loop/run-model-attempts.d.ts +0 -6
  378. package/dist/agent-runtime/loop/run-model-attempts.d.ts.map +0 -1
  379. package/dist/index-sznqf8fx.js +0 -20
  380. /package/dist/{index-fthw8dwa.js → index-4gbybjg6.js} +0 -0
@@ -1,4 +1,4 @@
1
- # stitchkit/agent-runtime — stitchkit docs slice, part 1 of 5
1
+ # stitchkit/agent-runtime — stitchkit docs slice, part 1 of 6
2
2
 
3
3
  > Generated from the `docs/` tree by `bun run gen:llms`. The index of all slices is
4
4
  > `llms.txt` in this package.
@@ -8,8 +8,9 @@ Parts of this slice:
8
8
  - `llms/agent-runtime.txt`: Guide: Agent application runtime (docs/guide/agent-runtime.md)
9
9
  - `llms/agent-runtime.2.txt`: Guide: Agent application runtime (docs/guide/agent-runtime.md)
10
10
  - `llms/agent-runtime.3.txt`: Guide: Agent application runtime (docs/guide/agent-runtime.md)
11
- - `llms/agent-runtime.4.txt`: Guide: Agent application runtime (docs/guide/agent-runtime.md) · API reference: `stitchkit/agent-runtime` (docs/api/reference.md)
12
- - `llms/agent-runtime.5.txt`: API reference: `stitchkit/agent-runtime` (docs/api/reference.md) · API reference: `stitchkit-tui` (docs/api/reference.md)
11
+ - `llms/agent-runtime.4.txt`: Guide: Agent application runtime (docs/guide/agent-runtime.md)
12
+ - `llms/agent-runtime.5.txt`: API reference: `stitchkit/agent-runtime` (docs/api/reference.md)
13
+ - `llms/agent-runtime.6.txt`: API reference: `stitchkit/agent-runtime` (docs/api/reference.md) · API reference: `stitchkit-tui` (docs/api/reference.md)
13
14
 
14
15
  ==============================================================================
15
16
  # Guide: Agent application runtime (docs/guide/agent-runtime.md)
@@ -74,32 +75,77 @@ bun add ai@^7
74
75
 
75
76
  ## Minimal composition
76
77
 
78
+ The whole loop in one file: a protocol, a model, a prompt, contract tools and one turn. It runs
79
+ as written — `createScriptedModelDriver` from `stitchkit/agent-runtime/testing` stands in for
80
+ the provider, so `bun run agent.ts` needs no key and no network:
81
+
77
82
  ```ts
83
+ // agent.ts
78
84
  import { z } from 'zod'
85
+ import { defineContract } from 'stitchkit'
86
+ import { AppError, implement } from 'stitchkit/server'
79
87
  import {
80
- AgentContextOverflowError,
81
88
  composeAgentPrompt,
82
89
  createAgentRuntime,
83
90
  createMemoryAgentRuntimeStore,
84
91
  defineAgentProtocol,
85
92
  defineModelRegistry,
86
93
  } from 'stitchkit/agent-runtime'
87
- import { openRouterProvider } from 'stitchkit/agent-runtime/openrouter'
88
- import { composeToolLifecycle, mountAgentTools } from 'stitchkit/tools'
94
+ import { createScriptedModelDriver } from 'stitchkit/agent-runtime/testing'
95
+ import { composeToolLifecycle, mountAgentTools, type ToolGate } from 'stitchkit/tools'
96
+
97
+ // The agent's tools are an ordinary contract; the endpoint `lookup` of `orders` is the tool `lookup_order`.
98
+ const orders = defineContract({ prefix: 'orders' }, {
99
+ lookup: {
100
+ method: 'GET',
101
+ path: '/:id',
102
+ desc: 'Look up an order by id',
103
+ params: z.object({ id: z.string() }),
104
+ output: z.object({ id: z.string(), status: z.string() }),
105
+ },
106
+ })
107
+ const service = implement(orders, {
108
+ lookup: (ctx) => ({ id: ctx.params.id, status: 'shipped' }),
109
+ })
110
+
111
+ // Who may call them: your auth rule as a tool gate (`createAuthHook` builds one too).
112
+ const authLifecycle: ToolGate = {
113
+ beforeHandle: (ctx) => {
114
+ if (typeof ctx.userId !== 'string') throw new AppError('UNAUTHORIZED')
115
+ },
116
+ }
89
117
 
90
118
  const protocol = defineAgentProtocol({
91
119
  context: z.object({ userId: z.string() }),
92
120
  inputMetadata: z.object({}),
93
121
  })
94
122
 
123
+ // Two scripted model steps: call the tool, then answer.
124
+ const usage = (input: number, output: number) => ({
125
+ inputTokens: { value: input, provenance: 'provider-reported' as const },
126
+ outputTokens: { value: output, provenance: 'provider-reported' as const },
127
+ })
128
+ const scripted = createScriptedModelDriver({
129
+ steps: [
130
+ [
131
+ { type: 'tool-call', toolCallId: 'call-1', toolName: 'lookup_order', input: '{"id":"42"}' },
132
+ { type: 'finish', finishReason: 'tool-calls', usage: usage(20, 5) },
133
+ ],
134
+ [
135
+ { type: 'text-delta', id: 'text-1', delta: 'Order 42 has shipped.' },
136
+ { type: 'finish', finishReason: 'stop', usage: usage(40, 6) },
137
+ ],
138
+ ],
139
+ })
140
+
95
141
  const models = defineModelRegistry({
96
142
  providers: {
97
- openrouter: openRouterProvider({ apiKey: env.OPENROUTER_API_KEY }),
143
+ scripted: { create: () => scripted },
98
144
  },
99
145
  models: {
100
146
  fast: {
101
- provider: 'openrouter',
102
- modelId: 'provider/model',
147
+ provider: 'scripted',
148
+ modelId: 'scripted-model',
103
149
  contextWindow: 128_000,
104
150
  capabilities: ['tools'],
105
151
  },
@@ -118,7 +164,9 @@ const runtime = createAgentRuntime({
118
164
  protocol,
119
165
  store: createMemoryAgentRuntimeStore(),
120
166
  models: {
121
- preflight: () => models.preflight('fast', ['tools']),
167
+ preflight: () => {
168
+ models.preflight('fast', ['tools']) // throws when the model cannot serve the turn
169
+ },
122
170
  resolve: () => models.resolve('fast', ['tools']),
123
171
  },
124
172
  prompt: ({ context, signal, model }) =>
@@ -141,16 +189,14 @@ const runtime = createAgentRuntime({
141
189
  runs: { inputPolicy: 'interrupt', coalescePending: true },
142
190
  loop: {
143
191
  idleTimeoutMs: 60_000,
144
- prepareStep: ({ context, steps }) => ({
145
- activeTools: steps.some((step) => step.toolCalls.length > 0)
146
- ? ['lookup']
147
- : ['lookup', 'discover'],
192
+ prepareStep: ({ context }) => ({
193
+ activeTools: ['lookup_order'],
148
194
  instructions: `Current account: ${context.userId}`,
149
195
  }),
150
196
  stopPolicies: [
151
197
  {
152
- name: 'repeated-tool-error',
153
- when: ({ steps }) => hasRepeatedToolError(steps),
198
+ name: 'too-many-tool-steps',
199
+ when: ({ steps }) => steps.filter((step) => step.toolCalls.length > 0).length >= 5,
154
200
  },
155
201
  ],
156
202
  },
@@ -160,7 +206,7 @@ const ticket = runtime.submit({
160
206
  conversationId: 'conversation-id',
161
207
  idempotencyKey: 'request-id',
162
208
  context: { userId: 'user-id' },
163
- parts: [{ type: 'text', text: 'Hello' }],
209
+ parts: [{ type: 'text', text: 'Where is order 42?' }],
164
210
  recordIds: {
165
211
  inputMessageId: 'user-message-id',
166
212
  runId: 'run-id',
@@ -168,11 +214,36 @@ const ticket = runtime.submit({
168
214
  },
169
215
  })
170
216
 
171
- const admission = await ticket.admission
172
217
  await ticket.accepted
173
218
  const terminal = await ticket.result
219
+ console.log(terminal.reason, terminal.message.parts) // 'success', the tool call, its result, the answer
220
+ await runtime.close()
174
221
  ```
175
222
 
223
+ For a real model, register its provider under the same key and keep everything else:
224
+
225
+ ```ts
226
+ import { defineModelRegistry } from 'stitchkit/agent-runtime'
227
+ import { openRouterProvider } from 'stitchkit/agent-runtime/openrouter'
228
+
229
+ const models = defineModelRegistry({
230
+ providers: {
231
+ openrouter: openRouterProvider({ apiKey: () => process.env.OPENROUTER_API_KEY ?? '' }),
232
+ },
233
+ models: {
234
+ fast: {
235
+ provider: 'openrouter',
236
+ modelId: 'provider/model', // a live tool-capable model id from the OpenRouter catalog
237
+ contextWindow: 128_000,
238
+ capabilities: ['tools'],
239
+ },
240
+ },
241
+ })
242
+ ```
243
+
244
+ Both blocks are type-checked, and the first one run, by
245
+ `packages/core/tests/guide-first-path-snippets.test.ts`.
246
+
176
247
  A stop policy's `when` receives the completed `AgentStepResult[]` steps so far together with the
177
248
  same run context `prepareStep` gets — `context`, `run`, `signal`, `toolFenceLifecycle` and
178
249
  `contextUsage` — typed by the runtime's `CONTEXT`. A rule that depends on its own run (a receipt
@@ -180,6 +251,40 @@ bound to the run's request, a per-tenant limit) reads it there; it needs no map
180
251
  by `runId`. The first policy to return `true` ends the run as `policy_stop` with its `name` as
181
252
  `policyName`.
182
253
 
254
+ ### When a run ends `runtime_failure`
255
+
256
+ A run ends `runtime_failure` when the composition fails it — `tools`, `prompt` or a hook throws, a
257
+ checkpoint cannot be written — and `provider_failure` when the model call does. The result a
258
+ caller awaits says which, never why: `terminal.reason` and the failed message travel to clients,
259
+ and a raw cause can carry a provider's response body, a path or another user's data. The cause goes
260
+ to the operator channel, `observe`, and only to a sink that asks for it with `includeInternalCause`:
261
+
262
+ ```ts
263
+ import { createAgentObservability, createAgentRuntime } from 'stitchkit/agent-runtime'
264
+
265
+ const observe = createAgentObservability({
266
+ includeInternalCause: true, // operator-only: keep this sink's output away from clients
267
+ write: (event) => {
268
+ if (event.type === 'run-terminal' && event.internalCause !== undefined) {
269
+ console.error(`run ${event.runId} ended ${event.terminalReason}:`, event.internalCause)
270
+ }
271
+ },
272
+ })
273
+
274
+ const runtime = createAgentRuntime({
275
+ ...composition, // protocol, store, models, prompt and tools, as in the minimal composition
276
+ observe,
277
+ })
278
+
279
+ const ticket = runtime.submit(input)
280
+ const terminal = await ticket.result
281
+ await observe.flush() // the sink is bounded and asynchronous; flush before reading it or exiting
282
+ ```
283
+
284
+ Without `observe`, nothing reports the cause. A composition missing `protocol`, `store`,
285
+ `models.resolve`, `prompt` or `tools` does not get that far: `createAgentRuntime` throws a
286
+ `TypeError` naming them. `packages/core/tests/agent-runtime-failure-cause.test.ts` holds both.
287
+
183
288
  ## Native model port, providers and driver composition
184
289
 
185
290
  Every model call crosses one single-step port — `AgentModelDriver.stream(request, signal)` — with
@@ -215,6 +320,14 @@ freshly per stream call and reporting server `response.timestamp` alongside `mod
215
320
  ≤ 4 cache breakpoints with TTL-order checks, `output_config.format` JSON Schema (refusing
216
321
  schemaless `json-object`), and retryable `529 overloaded_error` classification.
217
322
 
323
+ A Chat Completions stream is complete only when it says so: `data: [DONE]`, or a usage chunk
324
+ after `finish_reason` — the ending [OpenRouter's streaming reference](https://openrouter.ai/docs/api_reference/streaming)
325
+ describes. An OpenAI-compatible server behind `openRouterProvider({ baseUrl })` that closes the
326
+ connection after `finish_reason` with neither cannot be told apart from a cut that lost the usage
327
+ chunk, so the step fails with a retryable `AgentProviderStreamCutError` instead of finishing with
328
+ unreported usage. Such a server has to send `data: [DONE]` (or usage, e.g. on
329
+ `stream_options.include_usage`); there is no option to accept the bare close.
330
+
218
331
  For an existing AI SDK (`LanguageModelV4` from `ai@7`) model or `ToolSet`, import `fromAiSdkModel` and `fromAiSdkTools` from
219
332
  `stitchkit/agent-runtime/ai-sdk`. Both adapt directly onto `AgentModelDriver` and `AgentToolSet`
220
333
  (driving `model.doStream()` without importing `streamText` or `generateText`) and normalize legacy
@@ -233,6 +346,151 @@ const base = openAiProvider({ apiKey: env.OPENAI_API_KEY }).create('gpt-5')
233
346
  const guarded = composeModelDrivers(base, [admissionDecorator, telemetryDecorator])
234
347
  ```
235
348
 
349
+ ### OpenRouter non-chat endpoints and shared transport
350
+
351
+ `stitchkit/agent-runtime/openrouter` also exports the canonical `OPENROUTER_API_BASE_URL`
352
+ (`https://openrouter.ai/api/v1`), `OpenRouterFetch`, generic non-chat transport helpers
353
+ (`openRouterRequestJson` and `openRouterRequestStream`), and typed modality clients — all
354
+ peer-free, Web Fetch-clean, redirect-safe (`redirect: 'error'` plus response-level refusal), and
355
+ compatible with `gateway.fetchFor('openrouter')` and custom `baseUrl` overrides. Chat, catalog,
356
+ spend and every non-chat client share one transport: one `baseUrl` rule (`https:`, or `http:` to a
357
+ loopback host only; no credentials, query or fragment; the API root, not an endpoint URL), one injected `fetch` option, and one error class,
358
+ `AgentProviderError` with `statusCode`, for every non-2xx answer:
359
+
360
+ - **Decision models (`POST /systemone`):** `openRouterSystemOne` sends `noul`, `choice`,
361
+ `score` and image `box` questions over text or structured `state` (with image `assets`,
362
+ `sessionId` and `user`) and returns calibrated probability answers, bounding boxes and
363
+ per-question refusals plus `generationId` and `costUsd`.
364
+ - **Audio (`POST /audio/transcriptions` and `POST /audio/speech`):** `openRouterAudioTranscription`
365
+ accepts `audio: { kind: 'base64' | 'url' | 'file' }` (JSON or automatic `FormData` multipart
366
+ without manual `Content-Type`), `verbose_json`, `timestampGranularities`, and `diarize`;
367
+ `openRouterAudioSpeech` streams synthesized audio bytes (`ReadableStream<Uint8Array>`), takes
368
+ text or multi-speaker turns, and with `outputDelivery: 'url'` returns a signed download URL instead.
369
+ - **Images & Video (`POST /images` and `/videos`):** `openRouterGenerateImages` targets OpenRouter's
370
+ Unified Image API (`b64_json` or signed `url`), while `openRouterSubmitVideo`,
371
+ `openRouterGetVideo`, and `openRouterDownloadVideo` cover the async submit → poll → stream
372
+ download lifecycle.
373
+ - **Embeddings & Rerank (`POST /embeddings`, `POST /rerank`):** `openRouterEmbeddings` and
374
+ `openRouterRerank` provide typed RAG vector and rescoring calls.
375
+ - **Any other OpenRouter API v1 endpoint:** `openRouterRequestJson` (with optional Zod `schema`) and
376
+ `openRouterRequestStream` (with open-phase `timeoutMs` disarmed once 2xx headers arrive) handle
377
+ management or future endpoints (`/credits`, `/key`, `/responses`, `/images/models`, `/videos/models`)
378
+ without custom wrappers.
379
+
380
+ `createOpenRouterClient` states the key, `baseUrl`, `fetch`, headers and attribution once and returns
381
+ every function above as a method of the same name (`audioTranscription`, `audioSpeech`, `systemOne`,
382
+ `generateImages`, `submitVideo`, `getVideo`, `downloadVideo`, `embeddings`, `rerank`, `requestJson`,
383
+ `requestStream`); a value passed to one call overrides the client's, except `headers` and
384
+ `providerApiKeys`, which merge key by key with the call's entries winning. An invalid `baseUrl` or
385
+ static `apiKey` is refused when the client is created. Every example below is
386
+ type-checked against the current exports by `packages/core/tests/openrouter-guide-snippets.test.ts`.
387
+
388
+ Speech to text — inline audio, or a URL the provider downloads:
389
+
390
+ ```ts
391
+ import { createOpenRouterClient } from 'stitchkit/agent-runtime/openrouter';
392
+
393
+ const openRouter = createOpenRouterClient({
394
+ apiKey: () => process.env.OPENROUTER_API_KEY ?? '',
395
+ appName: 'Minutes',
396
+ });
397
+
398
+ const fromBytes = await openRouter.audioTranscription({
399
+ model: 'openai/whisper-large-v3',
400
+ audio: { kind: 'base64', data: 'UklGRiQA...', format: 'wav' },
401
+ responseFormat: 'verbose_json',
402
+ diarize: true,
403
+ });
404
+ for (const word of fromBytes.words ?? []) console.log(word.speaker, word.speakerLabel, word.word);
405
+
406
+ const fromUrl = await openRouter.audioTranscription({
407
+ model: 'elevenlabs/scribe-v2',
408
+ audio: { kind: 'url', url: 'https://example.com/meeting.mp3' },
409
+ });
410
+ console.log(fromUrl.text, fromUrl.costUsd);
411
+ ```
412
+
413
+ Audio by URL depends on the model, and OpenRouter publishes which models accept it neither in the
414
+ endpoints API nor in its documentation. A model that cannot fetch a URL answers HTTP 400 "The
415
+ selected model does not support audio from a URL. Send the audio inline instead." before any charge;
416
+ the call rejects with `AgentProviderError` (`statusCode: 400`) carrying that message. Checked on
417
+ 2026-11-30: `elevenlabs/scribe-v2` transcribed a URL, while `openai/whisper-large-v3-turbo`,
418
+ `deepgram/nova-3`, `mistralai/voxtral-mini-3b-2507` and `assemblyai/universal-3-5-pro` refused it —
419
+ send their audio as `base64` or `file`.
420
+
421
+ Text to speech — streamed bytes, or a signed URL OpenRouter keeps for 24 hours:
422
+
423
+ ```ts
424
+ import { createOpenRouterClient } from 'stitchkit/agent-runtime/openrouter';
425
+
426
+ const openRouter = createOpenRouterClient({ apiKey: () => process.env.OPENROUTER_API_KEY ?? '' });
427
+
428
+ const streamed = await openRouter.audioSpeech({
429
+ model: 'mistralai/voxtral-mini-tts-2603',
430
+ input: 'Hello world',
431
+ voice: 'en_paul_neutral',
432
+ responseFormat: 'mp3',
433
+ });
434
+ const mp3 = new Uint8Array(await new Response(streamed.audio).arrayBuffer());
435
+
436
+ const stored = await openRouter.audioSpeech({
437
+ model: 'google/gemini-3.8-flash-lite-tts',
438
+ input: [
439
+ { text: "How's it going today, Jane?", voice: 'Kore' },
440
+ { text: 'Not too bad, how about you?', voice: 'Puck', instructions: 'tired, yawning' },
441
+ ],
442
+ responseFormat: 'wav',
443
+ outputDelivery: 'url',
444
+ });
445
+ console.log(mp3.byteLength);
446
+ // Zero-data-retention makes OpenRouter stream even when a URL was asked for: read those bytes too.
447
+ if (stored.delivery === 'url') console.log(stored.url, new Date(stored.expiresAt * 1000));
448
+ else {
449
+ const wav = new Uint8Array(await new Response(stored.audio).arrayBuffer());
450
+ console.log(wav.byteLength, stored.contentType);
451
+ }
452
+ ```
453
+
454
+ Video — submit, poll, download:
455
+
456
+ ```ts
457
+ import { createOpenRouterClient } from 'stitchkit/agent-runtime/openrouter';
458
+
459
+ const openRouter = createOpenRouterClient({ apiKey: () => process.env.OPENROUTER_API_KEY ?? '' });
460
+
461
+ const job = await openRouter.submitVideo({
462
+ model: 'google/veo-3.1',
463
+ prompt: 'A paper boat drifting down a rain gutter',
464
+ duration: 4,
465
+ });
466
+ let state = await openRouter.getVideo({ jobId: job.id });
467
+ while (state.jobStatus !== 'completed' && state.jobStatus !== 'failed') {
468
+ await new Promise((resolve) => setTimeout(resolve, 5_000));
469
+ state = await openRouter.getVideo({ jobId: job.id });
470
+ }
471
+ if (state.jobStatus === 'completed') {
472
+ const video = await openRouter.downloadVideo({ jobId: job.id });
473
+ console.log(video.contentType, state.costUsd);
474
+ }
475
+ ```
476
+
477
+ Any other endpoint — `requestJson` with a Zod `schema` types and validates the answer:
478
+
479
+ ```ts
480
+ import { createOpenRouterClient } from 'stitchkit/agent-runtime/openrouter';
481
+ import { z } from 'zod';
482
+
483
+ const openRouter = createOpenRouterClient({ apiKey: () => process.env.OPENROUTER_API_KEY ?? '' });
484
+
485
+ const credits = await openRouter.requestJson({
486
+ path: '/credits',
487
+ schema: z.object({
488
+ data: z.object({ total_credits: z.number(), total_usage: z.number() }),
489
+ }),
490
+ });
491
+ console.log(credits.data.data.total_credits - credits.data.data.total_usage);
492
+ ```
493
+
236
494
  ### OpenRouter catalog snapshots, pricing ceilings, and cache
237
495
 
238
496
  `stitchkit/agent-runtime/openrouter` also provides a peer-free, Web Fetch-clean catalog layer for
@@ -305,13 +563,13 @@ extraction, classification, a bounded tool loop, or standalone streaming — cal
305
563
  - Pass `onPart` on `completeText` / `completeObject` or use `streamComplete` to consume
306
564
  `text-delta`, `reasoning-delta`, `tool-input-start`, `tool-call`, `tool-result` (preliminary and
307
565
  final), `tool-error`, `attempt-reset`, `finish-step`, and `finish` events over a bounded async
308
- iterable without a store. `streamComplete().parts` is single-use with a 64-part buffer: once
309
- iterated (`for await` or `parts[Symbol.asyncIterator]()`), backpressure pauses the producer when
310
- the buffer is full. If `parts` is never iterated, up to 64 parts buffer for late attachment and
311
- any overflow clears the queue without blocking so awaiting `result` alone (with or without
312
- `onPart`) completes in bounded memory; attempting to iterate `parts` after an unsubscribed
313
- overflow waits for completion and then propagates the run failure or throws an overflow `Error`
314
- instead of silently returning truncated parts.
566
+ iterable without a store. How `streamComplete` is read is stated, never guessed from when
567
+ `parts` is first touched. By default (`parts: 'iterate'`) `parts` is single-use with a 64-part
568
+ buffer that backpressures from the first part: iteration may start late — after other awaits —
569
+ and the run pauses at the full buffer until it does, losing nothing. Awaiting `result` alone in
570
+ this mode waits while the buffer is full, so a caller that wants only the result says so with
571
+ `parts: 'ignore'`: no buffer is kept, `result` (and `onPart`) carry the run, and iterating
572
+ `parts` throws a `TypeError`. `completeText` with `onPart` is the same result-only path.
315
573
  - Standalone completions have no durable approval loop, so any tool with `needsApproval: true` (or
316
574
  a `needsApproval` predicate returning `true`) is preflighted across every validated call in the
317
575
  step and fails closed with `AgentToolApprovalError` (`reason: 'approval-unsupported'`) before any
@@ -320,11 +578,22 @@ extraction, classification, a bounded tool loop, or standalone streaming — cal
320
578
  `toolDependencies`, `onPredecessorFailure`) on `completeText` / `streamComplete` /
321
579
  `completeObject` to enforce the same batch-refusal, cap, and dependency-ordering policies as
322
580
  `createAgentRuntime` (durable stream-only `stepBarriers` keys fail fast with a `TypeError`).
323
- - Pass `retry` (`AgentRetryPolicy`) and optional `onAttemptDiscarded` for stateless retry with
324
- `Retry-After` handling; exhausting retries throws `AgentRetryExhaustedError` carrying every failed
325
- attempt, `lastError`, and accumulated billable `usage`.
581
+ - Pass `retry` (`AgentRetryPolicy`) and optional `onAttemptDiscarded` for stateless retry. As in
582
+ `createAgentRuntime`, the unit of a retry is the model call of one step: earlier steps and the
583
+ tools they ran stand, and a call whose stream already carried a provider-executed tool call or
584
+ a tool result is not repeated. Exhausting retries throws `AgentRetryExhaustedError` carrying every failed attempt, `lastError`,
585
+ and accumulated billable `usage`. The wait before each retry is exactly what `delayMs` returns:
586
+ the runtime reads no `Retry-After` itself, so a policy that should honour one returns
587
+ `failure.retryAfterMs` (the provider's `Retry-After` or `retry-after-ms`, in milliseconds) and
588
+ bounds the total with `maxRetryDurationMs` — a retry whose wait would cross it is not scheduled.
589
+ The same policy serves `loop.retry`. Example:
590
+ [`packages/core/examples/agent-runtime/retry-after-policy.ts`](../../packages/core/examples/agent-runtime/retry-after-policy.ts).
326
591
  - Pass `stopPolicies` (`AgentCompleteStopPolicy[]`) and `idleTimeoutMs` to bound multi-step loops
327
- and stalled streams (suspending the idle timer during local tool execution).
592
+ and stalled streams (suspending the idle timer during local tool execution). A deadline that
593
+ fires while your consumer holds a part — a full `streamComplete().parts` buffer nobody reads, a
594
+ slow `onPart` — still ends the call with a `timeout` `AgentProviderError`, but one without
595
+ provider origin: `retry` never calls the provider again for it. `idleTimeoutMs`
596
+ defaults to 60 000, the runtime's default; `null` disables it.
328
597
 
329
598
  ```ts
330
599
  import { z } from 'zod'
@@ -422,7 +691,10 @@ const runtime = createAgentRuntime({
422
691
  context: runContext.context,
423
692
  access: { gate: composeToolLifecycle(authLifecycle, runContext.toolFenceLifecycle) },
424
693
  }),
425
- loop: { prepareStep: deferred.prepareStep(applicationPrepareStep) },
694
+ loop: {
695
+ prepareStep: deferred.prepareStep(applicationPrepareStep),
696
+ repairToolCall: deferred.repairToolCall(applicationRepairToolCall),
697
+ },
426
698
  })
427
699
  ```
428
700
 
@@ -441,9 +713,11 @@ The latest valid same-run search replaces the earlier selection; parallel
441
713
  searches in one step merge in call order. Recovery reconstructs it, while a
442
714
  different run or finite surface cannot inherit it. Known inactive calls take a
443
715
  recoverable `SEARCH_REQUIRED` search round; unknown names still fail. Inactive-call
444
- repair travels with the tool set returned by `deferred.mount()` — so wrapping
445
- `deferred.prepareStep()` or calling `completeText` preserves it automatically — and can
446
- also be composed explicitly with `deferred.repairToolCall(applicationRepairToolCall)`. The
716
+ repair is the hook `deferred.repairToolCall(applicationRepairToolCall?)` returns, passed as
717
+ `loop.repairToolCall` (runtime) or `repairToolCall` (`completeText` / `streamComplete`); the
718
+ application's hook runs first. Nothing is attached to the mounted tools, so spreading them or a
719
+ tool, or merging two surfaces' mounts, keeps repair exact: two surfaces compose as
720
+ `first.repairToolCall(second.repairToolCall())`, each repairing only its own catalog. The
447
721
  runtime marks that round with `reason: 'inactive_call'` beside the exact tool
448
722
  name. The field is the runtime's to write; a model that sets it anyway gets
449
723
  the same `SEARCH_REQUIRED` answer with an exact name, and with a query in words
@@ -459,332 +733,3 @@ comparison, but provider serialization and tokenization differ: use existing
459
733
  provider-reported input usage and cost to decide whether the extra search round
460
734
  is beneficial. Controller evidence intentionally omits query text, prompts,
461
735
  arguments and application context. → ADR 0129.
462
-
463
- ### Published headless harness and structured runner
464
-
465
- `stitchkit/agent-runtime/harness` publishes the resource-aware composition over
466
- `createAgentRuntime`. `createHeadlessAgentHarness` accepts the existing protocol and store,
467
- caller-provided model resolution, bounded instruction/skill/resource loading, direct tools and a
468
- prompt-budget callback. Resource names are unique; count, UTF-8 bytes and diagnostics are bounded.
469
- Invalid resources fail before a provider request. Diagnostics are evidence for the caller: their
470
- observer is isolated, and the loader decides whether a reported condition is fatal.
471
-
472
- `createAgentHarnessFileResources` is the optional filesystem implementation. It reads only
473
- caller-declared absolute roots, refuses symlinks and reports provenance as
474
- `rootId:relative/path`. Instructions enter the prompt immediately. Skills and ordinary resources
475
- enter as bounded name/description summaries; `read_resource` loads one exact body later as
476
- a normal direct typed tool. Custom loaders remain supported unchanged.
477
-
478
- Each run may resolve a different provider adapter without changing the harness. The
479
- `profile-applied` observation records the actual `AgentModelDescriptor`, resource kind/name/
480
- provenance and sorted direct tool names; it intentionally contains no resource text, prompts,
481
- arguments or credentials. Observer failure never changes the canonical run outcome.
482
-
483
- [`packages/core/examples/agent-runtime/headless-agent-runner.ts`](../../packages/core/examples/agent-runtime/headless-agent-runner.ts)
484
- is a reference structured control loop for `submit`, `interrupt`, `snapshot` and bounded `close`.
485
- It starts no process and chooses no framing, authentication or transport. Importing either example
486
- has no side effect; an external supervisor owns process placement and restart.
487
-
488
- | Concern | Public StitchKit composition | Boundary |
489
- | --- | --- | --- |
490
- | execution loop | `createAgentRuntime` | already available; do not copy a second loop |
491
- | model choice | `defineModelRegistry` and `models.resolve` | provider credentials/discovery stay application-owned |
492
- | resources | `createHeadlessAgentHarness` → `composeAgentPrompt` | paths, trust, precedence and watching stay application-owned |
493
- | tools | `mountAgentTools` + `createAgentToolFenceLifecycle` | auth and domain effects stay application-owned |
494
- | follow-up | `runs.inputPolicy: 'queue'` | durable FIFO after the current run |
495
- | interrupt | `interrupt` or `interrupt-next` | `interrupt-next` terminates the active run and gives the new durable admission next priority |
496
- | recovery | `runtime.recover` + `scanRecoverable` | replay safety and context reconstruction are explicit callbacks |
497
- | reconnect | canonical snapshot + `advanceAgentMultiSessionCursor` | conversation/run-scoped gaps require resync |
498
- | persistence | memory reference, public driver, or SQLite leaf | product rows/outbox remain outside the runtime store |
499
- | executable lifecycle | structured runner example | framing, auth, process placement, restart and OS isolation stay host-owned |
500
-
501
- `createAgentHarnessControlServer` adds transport-neutral correlated requests, shared observers and
502
- one exclusive controller lease per conversation. `close()` on a connection detaches only that
503
- client; it never closes the harness. A request the harness rejects answers `REQUEST_REJECTED`; its
504
- cause goes to the config's `onError` (else `console.error`), never to the client. Normal `event` delivery stays serialized. A bounded slow
505
- consumer is detached and receives `resync-required` through the required synchronous
506
- `onOverflow` callback; that callback closes/aborts the underlying transport, which then reconnects
507
- and requests a fresh snapshot. It never writes a second frame concurrently with a blocked
508
- `deliver`. Browser code uses `createAgentControlView`,
509
- `reduceAgentControlSnapshot` and `reduceAgentControlEvent`; the reducer owns no renderer and marks a
510
- conversation `resyncRequired` after a transient sequence gap.
511
-
512
- Configure `loop.toolApproval` for the runtime's native approval policy and
513
- `loop.toolApprovalSecret` to bind exact requests with WebCrypto HMAC-SHA256 signatures. A request
514
- is stored on the terminal assistant before any effect. `pendingApprovals()` derives unresolved
515
- requests from canonical messages; `respondToApproval()` writes one tool-role approval response and
516
- queues a successor. The native loop revalidates the signature/tool call/input once before any
517
- retry attempts and before the original direct tool reaches its existing fence. Reconnect and SQLite
518
- reopen require no promise registry. Remembered policy and a stronger cross-crash exactly-once
519
- guarantee remain application concerns.
520
-
521
- Approval requests suspend a call; they do not settle its result. History carries exact call and
522
- approval identity across assistant/tool records, so an approved result can precede the next signed
523
- request in a successor run. Automatic decisions follow the same chronology. Unknown/duplicate
524
- responses and results with a different call or tool name are invalid; dropping an invalid active
525
- approval input fails the run with a private diagnostic rather than starting a fresh model turn.
526
-
527
- `stitchkit/agent-runtime/coding-tools` returns ordinary direct runtime tools named `read_file`,
528
- `write_file`, `edit_file`, `list_directory`, `glob`, `search_files`, `run_command` and optional
529
- `read_output`. Every call passes a required host authorization callback. An optional async/sync
530
- `authorizePath({ path })` is the one operation-independent policy for direct file access and
531
- discovery: direct read/write/edit refuses a denied path, while listing, glob and search omit it.
532
- Denial is recursive on every surface — direct access asks about each named ancestor and the file,
533
- outermost first, stopping at the first refusal; discovery rooted at `.` also asks about `.`.
534
- Thus denying `credentials` denies everything
535
- under it. The comparison is segment-wise, so it does not deny `credentials-backup`, and a path of
536
- depth N costs N questions for direct access. Directory decisions happen before descent; file decisions and
537
- `search_files.include` happen before opening content. Incompatible glob directory prefixes are
538
- pruned before policy or directory opens. Requested paths use `/`: a backslash is
539
- refused rather than normalised, because the workspace walk reads it as a separator and every
540
- authorization callback would otherwise be asked about a different decomposition than the one opened. File paths are relative, bounded and contained after
541
- descriptor-relative resolution: each ancestor is opened without following symlinks. Reads and edits
542
- stay pinned through authorization; `write_file` plans before it and opens the parent after, because
543
- the parent it creates does not exist yet. Reads revalidate the pinned file identity;
544
- writes and patches revalidate the pinned parent identity; search and resource discovery descend
545
- only through opened directories. Every filesystem tool selects its root capability before operation or path authorization and retains
546
- that identity if a callback replaces the root path or configured alias. On Linux the ordinary
547
- command launcher spawns the command with the pinned directory's `/proc` descriptor link as its cwd;
548
- on macOS it inherits the pinned cwd through an isolated guard — one short-lived guard process per
549
- command, tens of milliseconds, outside `shellTimeoutMs`, which counts from the command's start. The
550
- application process never changes cwd. Where
551
- contained descriptors are unavailable (Windows), `run_command` accepts a cwd whose realpath is
552
- that same name under the root — a symlink segment refuses there too — and checks the directory's
553
- identity again immediately before launch, after every host decision.
554
- A custom sandbox launcher owns atomic cwd capture at its pathname handoff; the SDK refuses a
555
- changed identity after policy/prepare and immediately before that handoff. A path that changed
556
- during direct-access authorization refuses with `CONFLICT`.
557
- A path spelled differently from the name stored on disk refuses before any policy reads it, so on a
558
- case-insensitive volume a rule on `credentials` cannot be passed by asking for `CREDENTIALS`.
559
- NUL bytes are refused before either host policy sees a path.
560
- Reads and edits open file candidates without blocking on special files, then require a regular
561
- file. A writerless FIFO therefore refuses instead of occupying a filesystem worker. `write_file`
562
- supplies the exact missing-directory plan as `createsDirectories` to host authorization; the
563
- descriptor walk may create only those entries. An ancestor that disappears after approval refuses
564
- with `CONFLICT`, without expanding that plan. Linux traverses `/proc/self/fd`; macOS uses the package's
565
- architecture-specific Node-API `openat` backend. Unsupported platforms, including FreeBSD until a
566
- real backend is qualified, fail closed. The package needs no install-time compiler or script.
567
- Other platforms fail these filesystem operations closed because Node exposes no equivalent
568
- portable directory-handle-relative API. Writes/edits reject symlink targets, content is strict
569
- UTF-8 and retained bytes are finite. Shell accepts a finite alias mapped by the host to an absolute executable plus an
570
- argument array — never a shell command string — and uses only the explicitly supplied environment.
571
- Arguments, output and time are bounded, while cancellation terminates the child. The configured
572
- root and cwd are path boundaries, not a security sandbox: isolate the process when an executable
573
- must not access the rest of the machine. Path admission does not constrain `run_command`; an
574
- executable requires process isolation for that guarantee. → ADR 0172
575
-
576
- An absolute path is still refused. When it is inside the canonical workspace root, the refusal
577
- includes the exact workspace-relative `recoveryPath`; an absolute path outside the root has no
578
- suggested replacement. Applying the suggestion still passes the same descriptor-relative
579
- containment and symlink checks.
580
-
581
- `edit_file` replaces one exact snippet. It inserts `newText` literally in both single and
582
- `replaceAll` modes, including JavaScript replacement tokens such as `$$`, `$&`, `` $` `` and `$'`.
583
- `oldText` is itself the freshness guard for the region it changes, so the digest is the optional `expectedSha256` and an edit is one call; pass the digest
584
- `read_file` returned when you want the whole-file guarantee, and read the `sha256` it returns to
585
- chain the next edit without re-reading. The read, the occurrence count and the construction of the
586
- new content all happen inside one per-target lock, so two concurrent edits of different snippets in
587
- one file cannot each build a file from the same base and have the second erase the first — the lock
588
- is process-local, which covers many agents in one process and not two processes over one workspace.
589
- It authorizes the exact replacement count, result digest and byte size, and deliberately does not
590
- claim multi-file atomicity.
591
-
592
- `write_file` creates missing parent directories inside the root and names them in
593
- `createdDirectories`; the walk that finds them runs before authorization and reports them in the
594
- authorization payload, so no directory is created before a host approves it.
595
-
596
- **Every ordinary outcome is a refusal a model can act on** — a missing file is `NOT_FOUND`, an
597
- existing file without `overwrite` is `CONFLICT`, an ambiguous snippet is `CONFLICT` carrying its
598
- occurrence count, a path outside the root is `FORBIDDEN`, an unknown spilled-output reference is
599
- `SPILL_REFERENCE_UNKNOWN` — each with a `hint` naming the next move.
600
- Host-level causes stay scrubbed to `INTERNAL_SERVER_ERROR` and name nothing outside the workspace.
601
- Every refusal code is a member of `STITCH_ERROR_STATUS`, so its status survives an envelope that
602
- crosses a process boundary and is rebuilt from the wire.
603
- → ADR 0139
604
-
605
- `list_directory` marks excluded directories rather than hiding them, and `glob` reports
606
- `skippedDirectories` beside its matches: an empty result from a tree whose files all live under an
607
- excluded directory is not "no files", and a model told only "nothing found" concludes the wrong
608
- thing. `search_files` takes `regex`, `context` lines and an anchored `include` pattern matched
609
- against the whole workspace-relative path. `*` does not cross `/`, so files in subdirectories need
610
- `**/`; `scannedFiles` counts files admitted by both that filter and host authorization that reached
611
- comparison. One finite glob automaton matches files and prunes incompatible directory prefixes;
612
- `glob` also confines its walk to the requested path. A `hint` can explain include filtering or
613
- pruning, without counting files below unopened directories.
614
-
615
- Search processes one file at a time. List, glob and search share directory, entry, serialized-output,
616
- timeout and cancellation budgets, including canonical spelling checks before path authorization.
617
- `list_directory` caps raw enumeration at the smaller of `maxListEntries` and `maxSearchEntries`;
618
- its coverage scope lists symlinks while glob/search skip them. Glob patterns are limited to 4,096
619
- UTF-16 units. A scoped glob measures depth from its requested base directory. In addition to `maxSearchFiles` (10,000), `maxSearchDepth`
620
- (32), `maxSearchResults` (100) and `maxReadBytes` (262,144), hosts can configure
621
- `maxSearchDirectories` (1,000 directory-open attempts, root included), `maxSearchEntries`
622
- (20,000 entries observed by bounded readers), `maxSearchBytes` (16,777,216 aggregate content
623
- bytes, including rejected UTF-8), `maxSearchOutputBytes` (65,536 bytes for the entire serialized
624
- UTF-8 JSON, minimum 1,024) and `searchTimeoutMs` (5,000). An input whose minimum coverage
625
- envelope cannot fit the output ceiling refuses before filesystem access. Directory readers cap
626
- enumeration before materialization and sorting; reaching an entry or result ceiling is
627
- conservatively partial, without reading a lookahead entry or match.
628
-
629
- `list_directory`, `glob` and `search_files` return `coverage.complete` and `coverage.reasons`
630
- to distinguish full empty results from partial work. Glob `resultTruncated` conservatively marks
631
- the result ceiling even when no extra match was read.
632
- Coverage names the include/exclusion/symlink scope, directory and entry counters, actual content
633
- bytes and elapsed milliseconds. Limits, cancellation, denial, unreadable files and oversized
634
- lines are explicit reasons. `errors` names only a workspace-relative path, operation and safe code;
635
- `errorsTruncated` and `deniedTruncated` report shortened diagnostics. Excluded directories and
636
- symlinks are outside the declared search scope. The caller's signal and deadline reach host
637
- authorization, file reads and traversal; CPU checkpoints and asynchronous races stop further work.
638
- Late opened handles are closed, while already-running kernel calls may finish later. Directory
639
- enumeration and glob matching have internal checkpoints; cancellation stops their producer loops.
640
- Host policy and visitor exceptions propagate to error hooks with their original cause, rather
641
- than becoming filesystem diagnostics. Diagnostic byte admission is linear and checks the deadline
642
- even for an empty result.
643
-
644
- Regex searches use JavaScript `RegExp` syntax without flags — groups, alternation, classes,
645
- anchors, `\b`, quantifiers and `(?ims-ims:…)` modifiers — with bounded cost per line. A line
646
- whose backtracking work (paths × longest path × line length × (number of groups + 1), every
647
- repetition capped at the line length beyond the iterations it requires) stays within 2^24 steps runs on the native engine, so ordinary `.*` searches over code
648
- lines keep native speed and the deadline is observed between lines; any other line runs on a
649
- cached linear automaton, so `(a+)+$` on a long line costs the same as `a+` and the deadline is
650
- observed inside the line. Backreferences and
651
- lookaround refuse before I/O; lines over 8,192 UTF-8 bytes are skipped with incomplete coverage.
652
- Literal queries allow up to 8,192 UTF-16 units and include patterns up to 4,096.
653
-
654
- With an optional `AgentCodingArtifactStore`, shell output beyond the inline
655
- preview continues into an opaque bounded artifact and `read_output` reads slices without
656
- exposing a host path. Without a store, the previous finite output-limit behavior is unchanged.
657
-
658
- `run_command` treats every invocation as finite. `shellTimeoutMs` bounds normal execution and
659
- `shellTerminationGraceMs` bounds settlement after timeout, caller cancellation, output overflow or
660
- parent exit. POSIX hosts launch a dedicated process group and kill every descendant remaining in
661
- that group; a process that deliberately escapes the group is outside the guarantee. Node's
662
- portable Windows child-process API cannot kill a complete descendant tree without invoking a
663
- second host executable, so Windows kills the direct child, destroys retained pipes at the grace
664
- deadline and makes no descendant-cleanup claim. A signal already aborted before execution returns
665
- `cancelled` without spawning.
666
-
667
- Coding commands compose the shared native execution owner. Artifact retention and UTF-8
668
- previews remain coding-tool policy; normal leader exit still forcibly stops remaining POSIX
669
- group members before draining. A structural sandbox launcher uses the same settlement owner
670
- with a finite output queue. Sandbox shutdown waits for actual owned completion and surfaces
671
- cleanup refusal rather than treating it as successful teardown.
672
-
673
- One `createAgentHarnessFileResources` instance represents one immutable discovery generation:
674
- concurrent and repeated `load()` calls share it, so a direct resource read cannot cross into a
675
- new catalog unexpectedly. Discovery uses the same descriptor-anchored traversal as coding search;
676
- construct a new loader to refresh after filesystem changes.
677
-
678
- Runtime events preserve reasoning/text/tool lifecycle order. Durable admission,
679
- checkpoint, run-state and terminal events carry stable identities; transient
680
- deltas carry one runtime epoch and monotonic sequence. On a transient gap,
681
- reload the canonical snapshot and resume from the durable record instead of
682
- persisting deltas as a second history.
683
-
684
- Prompt `contextWindow` budgeting is a pre-request decision over the assembled
685
- context. `AgentRun.usage` is cumulative measured/provider-reported execution
686
- evidence across attempts and compaction. They answer different questions and
687
- must not be substituted for each other. TTFT and throughput require timestamps
688
- from the actual provider stream plus a provider-reported or tokenizer-measured
689
- token count; character counts cannot produce exact token or throughput figures.
690
-
691
- `recordIds` is optional. Supply stable application record IDs when an accepted-response transport must
692
- return durable placeholders before the run finishes. `ticket.admission` resolves after the store
693
- acceptance CAS and reports the canonical committed `input`, assigned `run`, a typed `pending`
694
- assistant projection, compatibility IDs and snapshot version.
695
- Those assigned IDs can differ from the proposal when an input coalesces into an existing queued
696
- successor. Reuse the same `inputMessageId` for retries carrying the same idempotency key; input
697
- identity is caller-stable, while the receipt reports the run/assistant identities that assignment
698
- may change. Await `admission` first on the immediate accepted-response path. `ticket.accepted`
699
- remains the signal-only compatibility surface and additionally waits for admission publication.
700
-
701
- The in-memory store is a reference adapter and has process-local durability
702
- only. Production applications normally call `createAgentRuntimeStore()` and
703
- provide one database transaction driver. Its `transaction` owns the retry of a
704
- serialization conflict, wherever the database reports it: on a statement or on
705
- `COMMIT`, which some clients surface in a different shape. Pass
706
- `commitConflict: { arm }` to `runAgentStoreConformance` to prove it (a single-writer
707
- engine declares `{ impossible: 'single-writer' }` instead):
708
-
709
- ```ts
710
- const store = createAgentRuntimeStore({
711
- transaction: (work, options) =>
712
- options?.access === 'read'
713
- ? db.readTransaction(tx => work(tx))
714
- : db.writeTransaction(tx => work(tx)),
715
- head: {
716
- load: (tx, conversationId) => loadRuntimeHead(tx, conversationId),
717
- compareAndSwap: (tx, operation) => casRuntimeHead(tx, operation),
718
- },
719
- runs: {
720
- load: (tx, identity) => loadRun(tx, identity),
721
- loadByAssistantMessageId: (tx, identity) => loadRunByAssistant(tx, identity),
722
- loadMany: (tx, identities) => loadRuns(tx, identities),
723
- listActive: (tx, conversationId) => listActiveRuns(tx, conversationId),
724
- save: (tx, record) => saveRun(tx, record),
725
- },
726
- admissions: {
727
- load: (tx, identity) => loadAdmission(tx, identity),
728
- loadByInputMessageId: (tx, identity) => loadAdmissionByInput(tx, identity),
729
- create: (tx, receipt) => createAdmission(tx, receipt),
730
- },
731
- seeds: {
732
- load: (tx, identity) => loadSeedReceipt(tx, identity),
733
- create: (tx, receipt) => createSeedReceipt(tx, receipt),
734
- },
735
- history: {
736
- load: (tx, conversationId) => loadCanonicalMessages(tx, conversationId),
737
- hasMessage: (tx, identity) => hasAnyMessage(tx, identity), // compacted rows too
738
- apply: (tx, mutation) => applyCanonicalHistoryMutation(tx, mutation),
739
- restore: (tx, baseline) => restoreBaseline(tx, baseline), // optional
740
- },
741
- events: {
742
- append: (tx, event) => appendEvent(tx, event),
743
- list: (tx, page) => listEvents(tx, page),
744
- find: (tx, identity) => findEvent(tx, identity), // a unique index on the event id
745
- },
746
- archive: { export: exportCompanions, import: importCompanions }, // optional
747
- scanRecoverable: page => scanRecoverableRuns(page),
748
- })
749
-
750
- await runAgentStoreConformance({
751
- createStore: () => store,
752
- capabilities: { branch: true, planBranch: true, archive: true, historyRestore: true },
753
- commitConflict: { arm: () => db.failNextCommitWithSerializationError() },
754
- })
755
- ```
756
-
757
- `archive` and `history.restore` are the driver's optional members, and
758
- `store.capabilities` (`{ archive, historyRestore, purge }`) says which this one
759
- has. A store without `archive` refuses an archive carrying spills or companion
760
- projections, and a branch source carrying spills; one without `history.restore`
761
- refuses a compacted baseline. Each refusal is an
762
- `AgentStoreUnsupportedCapabilityError` naming the `capability`, thrown before
763
- anything is written — never a silent drop of spills or a compacted row brought
764
- back as active history. The conformance kit compares the declared `capabilities`
765
- with `store.capabilities` and proves each by behaviour.
766
-
767
- Prompt budgeting keeps reservation deficits signed. If instructions,
768
- `reservedOutput`, tool schemas, attachments and provider overhead already exceed
769
- `contextWindow`, `composeAgentPrompt` returns `contextDecision: 'oversized'`
770
- and a negative `availableHistoryTokens` even when history is empty. A `compact`
771
- policy is returned only when removing history could actually make the prompt
772
- fit. Exact equality (including a zero window with zero reservations/history)
773
- fits; any unavailable component keeps the decision `unavailable`.
774
-
775
- The same opaque `tx` reaches head, run, admission and history callbacks. The adapter maps rows
776
- and supplies atomicity; StitchKit owns transition validation and revision
777
- arithmetic. The executable reference is
778
- [`examples/agent-store-prisma/adapter.ts`](../../examples/agent-store-prisma/adapter.ts).
779
- `compareAndSwap` returns either `{ outcome: 'applied' }` or
780
- `{ outcome: 'conflict', actualVersion }`. Decide that outcome by reading the
781
- version, comparing it and then writing unconditionally — inside the transaction
782
- the adapter supplies, that is atomic. A conditional upsert is the shorter thing
783
- to write and it is wrong twice: `ON CONFLICT ... WHERE` guards the update branch
784
- only, so the first write to a conversation applies whatever `expectedVersion` it
785
- was given, and the affected-row count that would report the outcome is the
786
- driver's, which need not be the rows the statement moved. The head contains only
787
- schema version, conversation identity and monotonic version. Runs and admission receipts are normalized records;
788
- recovery queries active run states directly instead of maintaining a second projection.
789
- An admission receipt retains its canonical input, and a terminal run retains its canonical
790
- assistant, so physical product-history compaction cannot break idempotent retries.