stitchkit 0.135.1 → 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 +109 -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 +123 -81
  95. package/dist/agent-runtime/providers/openrouter-audio.d.ts.map +1 -1
  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 +2 -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 +26 -6
  103. package/dist/agent-runtime/providers/openrouter-http.d.ts.map +1 -1
  104. package/dist/agent-runtime/providers/openrouter-media.d.ts +91 -77
  105. package/dist/agent-runtime/providers/openrouter-media.d.ts.map +1 -1
  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 +2 -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-retrieval.d.ts +86 -55
  113. package/dist/agent-runtime/providers/openrouter-retrieval.d.ts.map +1 -1
  114. package/dist/agent-runtime/providers/openrouter-speech.d.ts +90 -0
  115. package/dist/agent-runtime/providers/openrouter-speech.d.ts.map +1 -0
  116. package/dist/agent-runtime/providers/openrouter-spend.d.ts +2 -2
  117. package/dist/agent-runtime/providers/openrouter-spend.d.ts.map +1 -1
  118. package/dist/agent-runtime/providers/openrouter-stream.d.ts.map +1 -1
  119. package/dist/agent-runtime/providers/openrouter-systemone.d.ts +87 -32
  120. package/dist/agent-runtime/providers/openrouter-systemone.d.ts.map +1 -1
  121. package/dist/agent-runtime/providers/openrouter-url.d.ts +7 -1
  122. package/dist/agent-runtime/providers/openrouter-url.d.ts.map +1 -1
  123. package/dist/agent-runtime/providers/openrouter-wire.d.ts +45 -0
  124. package/dist/agent-runtime/providers/openrouter-wire.d.ts.map +1 -0
  125. package/dist/agent-runtime/providers/openrouter.d.ts +1 -3
  126. package/dist/agent-runtime/providers/openrouter.d.ts.map +1 -1
  127. package/dist/agent-runtime/providers/provider-http.d.ts +14 -2
  128. package/dist/agent-runtime/providers/provider-http.d.ts.map +1 -1
  129. package/dist/agent-runtime/providers/provider-json-schema-strip.d.ts.map +1 -1
  130. package/dist/agent-runtime/providers/provider-json-schema.d.ts.map +1 -1
  131. package/dist/agent-runtime/providers/provider-openai-chat-sse.d.ts.map +1 -1
  132. package/dist/agent-runtime/providers/provider-openai-chat-state.d.ts +42 -0
  133. package/dist/agent-runtime/providers/provider-openai-chat-state.d.ts.map +1 -0
  134. package/dist/agent-runtime/providers/provider-usage.d.ts +9 -0
  135. package/dist/agent-runtime/providers/provider-usage.d.ts.map +1 -1
  136. package/dist/agent-runtime/sandbox/sandbox-bubblewrap-args.d.ts +9 -0
  137. package/dist/agent-runtime/sandbox/sandbox-bubblewrap-args.d.ts.map +1 -1
  138. package/dist/agent-runtime/sandbox/sandbox-bubblewrap.d.ts +6 -0
  139. package/dist/agent-runtime/sandbox/sandbox-bubblewrap.d.ts.map +1 -1
  140. package/dist/agent-runtime/sandbox/sandbox-contract.d.ts.map +1 -1
  141. package/dist/agent-runtime/sandbox/sandbox-process-linux.d.ts.map +1 -1
  142. package/dist/agent-runtime/sandbox/sandbox-process-spec.d.ts +5 -1
  143. package/dist/agent-runtime/sandbox/sandbox-process-spec.d.ts.map +1 -1
  144. package/dist/agent-runtime/sandbox/sandbox-process-wrapper.d.ts.map +1 -1
  145. package/dist/agent-runtime/stores/branch-messages.d.ts.map +1 -1
  146. package/dist/agent-runtime/stores/branch-observations.d.ts +42 -42
  147. package/dist/agent-runtime/stores/sql-rows.d.ts +10 -10
  148. package/dist/agent-runtime/terminal-commit.d.ts +10 -10
  149. package/dist/agent-runtime/testing/fault-bench.d.ts +5 -1
  150. package/dist/agent-runtime/testing/fault-bench.d.ts.map +1 -1
  151. package/dist/agent-runtime/testing/store-conformance-lifecycle.d.ts +20 -20
  152. package/dist/agent-runtime/testing/store-conformance-support.d.ts +10 -10
  153. package/dist/application/diagnostic-journal-contract.d.ts.map +1 -1
  154. package/dist/browser/client-executors.d.ts.map +1 -1
  155. package/dist/browser/client-url.d.ts.map +1 -1
  156. package/dist/contract/define.d.ts +3 -7
  157. package/dist/contract/define.d.ts.map +1 -1
  158. package/dist/contract/normalize.d.ts +17 -5
  159. package/dist/contract/normalize.d.ts.map +1 -1
  160. package/dist/entrypoints/agent-executor/acp.js +4 -2
  161. package/dist/entrypoints/agent-executor/claude-sdk.js +20 -20
  162. package/dist/entrypoints/agent-executor/claude.js +7 -7
  163. package/dist/entrypoints/agent-executor/codex.d.ts +2 -1
  164. package/dist/entrypoints/agent-executor/codex.d.ts.map +1 -1
  165. package/dist/entrypoints/agent-executor/codex.js +129 -35
  166. package/dist/entrypoints/agent-executor/testing/claude-sdk.js +2 -2
  167. package/dist/entrypoints/agent-executor/testing.js +17 -13
  168. package/dist/entrypoints/agent-executor.js +1 -1
  169. package/dist/entrypoints/agent-runtime/ai-sdk.d.ts +2 -1
  170. package/dist/entrypoints/agent-runtime/ai-sdk.d.ts.map +1 -1
  171. package/dist/entrypoints/agent-runtime/ai-sdk.js +10 -12
  172. package/dist/entrypoints/agent-runtime/anthropic.js +13 -10
  173. package/dist/entrypoints/agent-runtime/browser.js +8 -4
  174. package/dist/entrypoints/agent-runtime/harness.js +18 -19
  175. package/dist/entrypoints/agent-runtime/openai.js +5 -5
  176. package/dist/entrypoints/agent-runtime/openrouter.d.ts +7 -5
  177. package/dist/entrypoints/agent-runtime/openrouter.d.ts.map +1 -1
  178. package/dist/entrypoints/agent-runtime/openrouter.js +1095 -854
  179. package/dist/entrypoints/agent-runtime/postgres.js +2 -2
  180. package/dist/entrypoints/agent-runtime/realtime.js +5 -5
  181. package/dist/entrypoints/agent-runtime/sandbox.js +167 -139
  182. package/dist/entrypoints/agent-runtime/sqlite/bun.js +3 -3
  183. package/dist/entrypoints/agent-runtime/sqlite/node.js +3 -3
  184. package/dist/entrypoints/agent-runtime/testing.js +3 -3
  185. package/dist/entrypoints/agent-runtime.js +246 -360
  186. package/dist/entrypoints/application.js +2 -2
  187. package/dist/entrypoints/cli.js +36 -15
  188. package/dist/entrypoints/contract.js +12 -10
  189. package/dist/entrypoints/geo.js +1 -1
  190. package/dist/entrypoints/handler.js +5 -6
  191. package/dist/entrypoints/http.d.ts +2 -0
  192. package/dist/entrypoints/http.d.ts.map +1 -1
  193. package/dist/entrypoints/http.js +16 -4
  194. package/dist/entrypoints/index.js +26 -35
  195. package/dist/entrypoints/live.js +3 -3
  196. package/dist/entrypoints/node.js +7 -7
  197. package/dist/entrypoints/observability.js +9 -7
  198. package/dist/entrypoints/process.js +3 -3
  199. package/dist/entrypoints/remote.js +5 -5
  200. package/dist/entrypoints/server.js +29 -16
  201. package/dist/entrypoints/telegram/grammy.d.ts +1 -1
  202. package/dist/entrypoints/telegram/grammy.d.ts.map +1 -1
  203. package/dist/entrypoints/telegram/grammy.js +39 -5
  204. package/dist/entrypoints/telegram/screens.js +3 -0
  205. package/dist/entrypoints/telegram.d.ts +1 -1
  206. package/dist/entrypoints/telegram.d.ts.map +1 -1
  207. package/dist/entrypoints/telegram.js +19 -6
  208. package/dist/entrypoints/testing.js +10 -11
  209. package/dist/entrypoints/tools/agent.js +8 -9
  210. package/dist/entrypoints/tools/connections.js +27 -57
  211. package/dist/entrypoints/tools/contract.js +4 -4
  212. package/dist/entrypoints/tools/invoker.js +7 -8
  213. package/dist/entrypoints/tools/mcp.js +9 -10
  214. package/dist/entrypoints/tools/toolkit.js +11 -12
  215. package/dist/entrypoints/tools.js +20 -20
  216. package/dist/entrypoints/tracking/contract.js +1 -1
  217. package/dist/entrypoints/tracking/performance.js +1 -1
  218. package/dist/entrypoints/tracking.js +1 -1
  219. package/dist/{index-3czc3ykr.js → index-08a3qfr8.js} +1 -1
  220. package/dist/{index-grhhsrd5.js → index-1en7k3q5.js} +2 -1
  221. package/dist/{index-pdcbjd6a.js → index-1yky29qg.js} +6 -3
  222. package/dist/{index-b4c9dpzm.js → index-252den5a.js} +10 -11
  223. package/dist/{index-xtby8rj3.js → index-28kbdn63.js} +5 -47
  224. package/dist/{index-57sbckhv.js → index-36mtj8xm.js} +2 -2
  225. package/dist/{index-dm84tsd5.js → index-3kb8dw48.js} +1 -1
  226. package/dist/index-3tb82xr7.js +11 -0
  227. package/dist/{index-c24bj2r1.js → index-4243301z.js} +2 -2
  228. package/dist/{index-nr4fhfn4.js → index-4p2zx593.js} +2 -0
  229. package/dist/{index-q86qnzzf.js → index-54wp467c.js} +4 -4
  230. package/dist/{index-mcv7b2n0.js → index-63ctzjp4.js} +497 -495
  231. package/dist/{index-y0a4gt1s.js → index-65p8v81y.js} +3 -2
  232. package/dist/{index-z72vazf5.js → index-6y3eae97.js} +27 -83
  233. package/dist/{index-5awtbyns.js → index-9vj869rx.js} +1 -1
  234. package/dist/{index-5q0qpw3v.js → index-aqm7e864.js} +23 -8
  235. package/dist/{index-d4at0q09.js → index-b9mj31q7.js} +90 -88
  236. package/dist/{index-baba8ehy.js → index-bjrcbcn2.js} +2 -2
  237. package/dist/{index-fsw9wxk9.js → index-c9j8441q.js} +1 -103
  238. package/dist/{index-wdb5jhas.js → index-d1pdv8qc.js} +1 -1
  239. package/dist/{index-73wq9abg.js → index-df5xr2f9.js} +13 -59
  240. package/dist/{index-n9358ydy.js → index-dm50x3by.js} +1 -1
  241. package/dist/{index-zyyerdny.js → index-dmrx8xma.js} +3 -0
  242. package/dist/{index-78da4g74.js → index-dwq6a6sq.js} +17 -13
  243. package/dist/{index-9be3tf6r.js → index-e413q2cj.js} +49 -22
  244. package/dist/{index-g4gstmp1.js → index-ednf2cxs.js} +1 -1
  245. package/dist/{index-84tp547a.js → index-edpkm3k7.js} +29 -97
  246. package/dist/{index-gs0jw0hy.js → index-efbzm2se.js} +3 -3
  247. package/dist/{index-de7b0kvz.js → index-epwvp88y.js} +1 -1
  248. package/dist/{index-asnd4h2k.js → index-f0dzyskg.js} +27 -4
  249. package/dist/{index-xbb8ysmq.js → index-fatke81t.js} +2 -2
  250. package/dist/{index-6nzzj7qr.js → index-gq35s3bm.js} +1 -1
  251. package/dist/index-gvgtmt7a.js +102 -0
  252. package/dist/{index-m2b49tvc.js → index-h08xqfw9.js} +20 -21
  253. package/dist/{index-gk6dq9ay.js → index-ha1tv70k.js} +3 -26
  254. package/dist/{index-wsv11dhg.js → index-hberxns4.js} +1 -1
  255. package/dist/{index-rkphknhx.js → index-hpzhz1vm.js} +1 -1
  256. package/dist/{index-npfdymav.js → index-j5vzhj3d.js} +1 -1
  257. package/dist/{index-d3s070eh.js → index-jperyn0c.js} +1 -1
  258. package/dist/{index-yhwx4fwk.js → index-kzsetgh9.js} +1 -1
  259. package/dist/{index-x6sp5vpa.js → index-q4tr9vnf.js} +1 -1
  260. package/dist/{index-hce3hbdg.js → index-qj0sq69b.js} +6 -2
  261. package/dist/{index-v0j22shs.js → index-rg08syp1.js} +9 -6
  262. package/dist/{index-8vzh5wpv.js → index-rw1caff2.js} +14 -26
  263. package/dist/index-s8af9jqw.js +6 -0
  264. package/dist/{index-bgj9hbm3.js → index-sdppfbrh.js} +30 -16
  265. package/dist/{index-y0mwkgkf.js → index-shte29pg.js} +1086 -1055
  266. package/dist/{index-fec05c9k.js → index-ta0e2daw.js} +9 -7
  267. package/dist/{index-ht71v1ag.js → index-tb36xawm.js} +59 -44
  268. package/dist/{index-c0yym4a0.js → index-w7e402wx.js} +11 -105
  269. package/dist/{index-bvpevwt6.js → index-xnqab06h.js} +207 -202
  270. package/dist/index-xrbrvn15.js +147 -0
  271. package/dist/{index-ac3rfec5.js → index-y6wzzk2e.js} +21 -1
  272. package/dist/{index-3d2c45jn.js → index-yjx5jna7.js} +2 -2
  273. package/dist/internal/loopback-host.d.ts +8 -0
  274. package/dist/internal/loopback-host.d.ts.map +1 -0
  275. package/dist/internal/own-member.d.ts +7 -0
  276. package/dist/internal/own-member.d.ts.map +1 -0
  277. package/dist/internal/request.d.ts +17 -8
  278. package/dist/internal/request.d.ts.map +1 -1
  279. package/dist/internal/secret-shapes.d.ts +33 -4
  280. package/dist/internal/secret-shapes.d.ts.map +1 -1
  281. package/dist/json-schema/dialect.d.ts.map +1 -1
  282. package/dist/json-schema/keywords.d.ts +25 -6
  283. package/dist/json-schema/keywords.d.ts.map +1 -1
  284. package/dist/json-schema/string-format.d.ts.map +1 -1
  285. package/dist/live/events.d.ts.map +1 -1
  286. package/dist/live/watch-client.d.ts.map +1 -1
  287. package/dist/live/watch-delta.d.ts.map +1 -1
  288. package/dist/observability/context.d.ts +4 -3
  289. package/dist/observability/context.d.ts.map +1 -1
  290. package/dist/observability/sanitize.d.ts.map +1 -1
  291. package/dist/observability/secret-values.d.ts +0 -9
  292. package/dist/observability/secret-values.d.ts.map +1 -1
  293. package/dist/server/context.d.ts +3 -2
  294. package/dist/server/context.d.ts.map +1 -1
  295. package/dist/server/error-hook.d.ts +4 -3
  296. package/dist/server/error-hook.d.ts.map +1 -1
  297. package/dist/server/event-bus.d.ts.map +1 -1
  298. package/dist/server/file.d.ts +11 -3
  299. package/dist/server/file.d.ts.map +1 -1
  300. package/dist/server/handler-state.d.ts +2 -2
  301. package/dist/server/handler-state.d.ts.map +1 -1
  302. package/dist/server/middleware/jwt.d.ts +12 -1
  303. package/dist/server/middleware/jwt.d.ts.map +1 -1
  304. package/dist/server/middleware/trust-fence.d.ts +4 -0
  305. package/dist/server/middleware/trust-fence.d.ts.map +1 -1
  306. package/dist/server/multipart.d.ts +2 -3
  307. package/dist/server/multipart.d.ts.map +1 -1
  308. package/dist/server/raw.d.ts.map +1 -1
  309. package/dist/server/request-body.d.ts +12 -1
  310. package/dist/server/request-body.d.ts.map +1 -1
  311. package/dist/server/request-completion.d.ts.map +1 -1
  312. package/dist/server/types.d.ts +14 -9
  313. package/dist/server/types.d.ts.map +1 -1
  314. package/dist/telegram/crypto.d.ts.map +1 -1
  315. package/dist/telegram/init-data.d.ts +4 -4
  316. package/dist/telegram/init-data.d.ts.map +1 -1
  317. package/dist/telegram/outbound-cost.d.ts.map +1 -1
  318. package/dist/telegram/screens/test-chat.d.ts.map +1 -1
  319. package/dist/telegram/widget-api.d.ts +85 -13
  320. package/dist/telegram/widget-api.d.ts.map +1 -1
  321. package/dist/telegram/widget.d.ts +46 -2
  322. package/dist/telegram/widget.d.ts.map +1 -1
  323. package/dist/tools/cli/args-classify.d.ts +4 -74
  324. package/dist/tools/cli/args-classify.d.ts.map +1 -1
  325. package/dist/tools/cli/args-framework.d.ts +79 -0
  326. package/dist/tools/cli/args-framework.d.ts.map +1 -0
  327. package/dist/tools/cli/args-scan.d.ts.map +1 -1
  328. package/dist/tools/cli/args-tokens.d.ts.map +1 -1
  329. package/dist/tools/cli/checkpoint.d.ts +5 -0
  330. package/dist/tools/cli/checkpoint.d.ts.map +1 -1
  331. package/dist/tools/cli/stream.d.ts.map +1 -1
  332. package/dist/tools/connections/foreign-schema-join.d.ts.map +1 -1
  333. package/dist/tools/connections/openapi.d.ts.map +1 -1
  334. package/dist/tools/connections/runtime.d.ts.map +1 -1
  335. package/dist/tools/execute-handler.d.ts +24 -0
  336. package/dist/tools/execute-handler.d.ts.map +1 -0
  337. package/dist/tools/execute.d.ts.map +1 -1
  338. package/dist/tools/mcp/round.d.ts.map +1 -1
  339. package/dist/tools/schema/coerce.d.ts.map +1 -1
  340. package/dist/tools/schema/flatten.d.ts.map +1 -1
  341. package/dist/tools/schema/inline-references.d.ts.map +1 -1
  342. package/dist/tools/schema/nesting-limit.d.ts.map +1 -1
  343. package/dist/tools/schema/presentation.d.ts.map +1 -1
  344. package/dist/tracking/privacy.d.ts.map +1 -1
  345. package/llms/agent-runtime-openrouter.txt +10 -9
  346. package/llms/agent-runtime-sandbox.txt +50 -11
  347. package/llms/agent-runtime-testing.txt +1 -1
  348. package/llms/agent-runtime.2.txt +9 -6
  349. package/llms/agent-runtime.3.txt +2 -2
  350. package/llms/agent-runtime.4.txt +11 -5
  351. package/llms/agent-runtime.5.txt +1 -1
  352. package/llms/agent-runtime.txt +283 -36
  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 +1 -0
  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 +994 -217
  371. package/llms.txt +13 -12
  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
@@ -20,8 +20,15 @@ Parts of this slice:
20
20
 
21
21
  A subscriber that switches over `event.type` handles one transient event
22
22
  beyond deltas and reasoning: `attempt-reset`, published when `loop.retry`
23
- starts a new attempt, meaning everything this run streamed before it is
24
- withdrawn. `reduceAgentControlEvent` does that; a hand-written reducer must,
23
+ repeats a failed call, meaning what that call streamed is withdrawn. Its
24
+ `withdrawn: { text, reasoning }` counts the characters of transient text and
25
+ reasoning the cut call published — the tail of what the run streamed — so a
26
+ subscriber drops that many from the end and keeps the rest (earlier steps, which
27
+ stand). Counting from the end also holds for a subscriber that joined mid-run
28
+ and holds only part of the run's deltas; an event without `withdrawn`
29
+ withdraws everything the run streamed. It is published after the retry's
30
+ backoff, together with the durable `retry/started`, so a run stopped during the
31
+ pause records neither. `reduceAgentControlEvent` does that; a hand-written reducer must,
25
32
  or it keeps the failed attempt's partial text on screen.
26
33
 
27
34
  `publish` receives event classes with different guarantees:
@@ -146,9 +153,8 @@ replace the managed tool set or bypass its lifecycle fence.
146
153
 
147
154
  Override lifetimes in `prepareStep` follow two explicit rules:
148
155
 
149
- - **`instructions` is sticky across the remaining steps of the current attempt**
150
- (and resets to `initialInstructions` if a provider retry starts a fresh
151
- attempt). Later steps receive the carried value in `instructions` alongside
156
+ - **`instructions` is sticky across the remaining steps of the run** (a provider
157
+ retry repeats the failed call with the instructions it was prepared with). Later steps receive the carried value in `instructions` alongside
152
158
  the unchanged `initialInstructions`, so a step can explicitly revert with
153
159
  `{ instructions: initialInstructions }`. One-shot `protocol.acceptTerminal`
154
160
  continuation instructions apply only to that continuation step and do not
@@ -150,7 +150,7 @@ the same native step execution without requiring a store. → ADR 0336.
150
150
  | `AgentModelFinishReason` / `AgentModelResponseMetadata` / `AgentModelCostDetails` / `AgentStepTimings` / `AgentStepChunkIntervals` | _type_ | normalized step finish reason, response metadata (including server `modelId` and `timestamp`), optional provider-reported cost/BYOK breakdown (`promptCostUsd`, `outputCostUsd`, `isByok`), and measured step/response/tool/TTFT timings with optional inter-chunk interval percentiles (`min`, `p10`, `median`, `avg`, `p90`, `max`) |
151
151
  | `wrapModelDriver` / `composeModelDrivers` | function | wrap one `AgentModelDriver` with one or an ordered outer-to-inner list of lifecycle decorators whose `onClose` runs once on finish, error, early stream cancellation, or abort |
152
152
  | `AgentModelDriverDecorator` / `AgentModelDriverStreamOutcome` | _type_ | generic per-stream interceptor (`beforeStream`, `transformRequest`, `transformSignal`, `onPart`, `onClose`) and terminal stream outcome (`finished`, `errored`, `cancelled`) |
153
- | `completeText` / `streamComplete` / `CompleteTextInput` / `CompleteTextOptions` / `CompletePromptInput` / `CompleteTextResult` / `CompleteTextStream` / `CompleteStreamPart` / `CompletePrepareStep` / `AgentCompleteStopPolicy` | functions / _types_ | peer-free single- or multi-step completion and standalone async-iterable streaming over any `AgentModelDriver` (no store required), with compile-time XOR on `prompt` vs `messages`, `retry`, `stopPolicies`, `idleTimeoutMs`, `onPart`, `headers`, tools, `prepareStep`, `repairToolCall`, timings and usage |
153
+ | `completeText` / `streamComplete` / `CompleteTextInput` / `StreamCompleteInput` / `CompleteTextOptions` / `CompletePromptInput` / `CompleteTextResult` / `CompleteTextStream` / `CompleteStreamPart` / `CompletePrepareStep` / `AgentCompleteStopPolicy` | functions / _types_ | peer-free single- or multi-step completion and standalone async-iterable streaming over any `AgentModelDriver` (no store required), with compile-time XOR on `prompt` vs `messages`, `retry`, `stopPolicies`, `idleTimeoutMs`, `onPart`, `headers`, tools, `prepareStep`, `repairToolCall`, timings and usage; `streamComplete` takes `parts: 'iterate'` (default, backpressured from the first part however late it is read) or `parts: 'ignore'` (result only, no buffer) |
154
154
  | `completeObject` / `CompleteObjectInput` / `CompleteObjectResult` | function / _types_ | peer-free structured-output completion emitting strict JSON Schema (`draft-2020-12` via `toJsonSchema(..., 'input')`), stripping strict-mode optional `null`s prior to Zod validation, and supporting multi-step tool loops |
155
155
  | `AgentStructuredOutputError` / `AgentStructuredOutputErrorReason` / `AgentStructuredOutputErrorDetails` | class / _types_ | typed error thrown by `completeObject` with `reason` (`'truncated' \| 'tool-calls' \| 'content-filter' \| 'provider-error' \| 'interrupted' \| 'empty' \| 'invalid-json' \| 'schema-mismatch'`), `finishReason`, `rawText`, `steps`, and `usage` |
156
156
  | `AgentRetryExhaustedError` / `AgentRetryExhaustedErrorDetails` / `AgentRetryAttemptRecord` | class / _types_ | typed error thrown when stateless completion retries exhaust `retry.maxAttempts` or `maxRetryDurationMs`, carrying every failed attempt, `lastError`, and accumulated billable `usage` |
@@ -75,32 +75,77 @@ bun add ai@^7
75
75
 
76
76
  ## Minimal composition
77
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
+
78
82
  ```ts
83
+ // agent.ts
79
84
  import { z } from 'zod'
85
+ import { defineContract } from 'stitchkit'
86
+ import { AppError, implement } from 'stitchkit/server'
80
87
  import {
81
- AgentContextOverflowError,
82
88
  composeAgentPrompt,
83
89
  createAgentRuntime,
84
90
  createMemoryAgentRuntimeStore,
85
91
  defineAgentProtocol,
86
92
  defineModelRegistry,
87
93
  } from 'stitchkit/agent-runtime'
88
- import { openRouterProvider } from 'stitchkit/agent-runtime/openrouter'
89
- 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
+ }
90
117
 
91
118
  const protocol = defineAgentProtocol({
92
119
  context: z.object({ userId: z.string() }),
93
120
  inputMetadata: z.object({}),
94
121
  })
95
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
+
96
141
  const models = defineModelRegistry({
97
142
  providers: {
98
- openrouter: openRouterProvider({ apiKey: env.OPENROUTER_API_KEY }),
143
+ scripted: { create: () => scripted },
99
144
  },
100
145
  models: {
101
146
  fast: {
102
- provider: 'openrouter',
103
- modelId: 'provider/model',
147
+ provider: 'scripted',
148
+ modelId: 'scripted-model',
104
149
  contextWindow: 128_000,
105
150
  capabilities: ['tools'],
106
151
  },
@@ -119,7 +164,9 @@ const runtime = createAgentRuntime({
119
164
  protocol,
120
165
  store: createMemoryAgentRuntimeStore(),
121
166
  models: {
122
- preflight: () => models.preflight('fast', ['tools']),
167
+ preflight: () => {
168
+ models.preflight('fast', ['tools']) // throws when the model cannot serve the turn
169
+ },
123
170
  resolve: () => models.resolve('fast', ['tools']),
124
171
  },
125
172
  prompt: ({ context, signal, model }) =>
@@ -142,16 +189,14 @@ const runtime = createAgentRuntime({
142
189
  runs: { inputPolicy: 'interrupt', coalescePending: true },
143
190
  loop: {
144
191
  idleTimeoutMs: 60_000,
145
- prepareStep: ({ context, steps }) => ({
146
- activeTools: steps.some((step) => step.toolCalls.length > 0)
147
- ? ['lookup']
148
- : ['lookup', 'discover'],
192
+ prepareStep: ({ context }) => ({
193
+ activeTools: ['lookup_order'],
149
194
  instructions: `Current account: ${context.userId}`,
150
195
  }),
151
196
  stopPolicies: [
152
197
  {
153
- name: 'repeated-tool-error',
154
- when: ({ steps }) => hasRepeatedToolError(steps),
198
+ name: 'too-many-tool-steps',
199
+ when: ({ steps }) => steps.filter((step) => step.toolCalls.length > 0).length >= 5,
155
200
  },
156
201
  ],
157
202
  },
@@ -161,7 +206,7 @@ const ticket = runtime.submit({
161
206
  conversationId: 'conversation-id',
162
207
  idempotencyKey: 'request-id',
163
208
  context: { userId: 'user-id' },
164
- parts: [{ type: 'text', text: 'Hello' }],
209
+ parts: [{ type: 'text', text: 'Where is order 42?' }],
165
210
  recordIds: {
166
211
  inputMessageId: 'user-message-id',
167
212
  runId: 'run-id',
@@ -169,11 +214,36 @@ const ticket = runtime.submit({
169
214
  },
170
215
  })
171
216
 
172
- const admission = await ticket.admission
173
217
  await ticket.accepted
174
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()
175
221
  ```
176
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
+
177
247
  A stop policy's `when` receives the completed `AgentStepResult[]` steps so far together with the
178
248
  same run context `prepareStep` gets — `context`, `run`, `signal`, `toolFenceLifecycle` and
179
249
  `contextUsage` — typed by the runtime's `CONTEXT`. A rule that depends on its own run (a receipt
@@ -181,6 +251,40 @@ bound to the run's request, a per-tenant limit) reads it there; it needs no map
181
251
  by `runId`. The first policy to return `true` ends the run as `policy_stop` with its `name` as
182
252
  `policyName`.
183
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
+
184
288
  ## Native model port, providers and driver composition
185
289
 
186
290
  Every model call crosses one single-step port — `AgentModelDriver.stream(request, signal)` — with
@@ -216,6 +320,14 @@ freshly per stream call and reporting server `response.timestamp` alongside `mod
216
320
  ≤ 4 cache breakpoints with TTL-order checks, `output_config.format` JSON Schema (refusing
217
321
  schemaless `json-object`), and retryable `529 overloaded_error` classification.
218
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
+
219
331
  For an existing AI SDK (`LanguageModelV4` from `ai@7`) model or `ToolSet`, import `fromAiSdkModel` and `fromAiSdkTools` from
220
332
  `stitchkit/agent-runtime/ai-sdk`. Both adapt directly onto `AgentModelDriver` and `AgentToolSet`
221
333
  (driving `model.doStream()` without importing `streamText` or `generateText`) and normalize legacy
@@ -240,15 +352,20 @@ const guarded = composeModelDrivers(base, [admissionDecorator, telemetryDecorato
240
352
  (`https://openrouter.ai/api/v1`), `OpenRouterFetch`, generic non-chat transport helpers
241
353
  (`openRouterRequestJson` and `openRouterRequestStream`), and typed modality clients — all
242
354
  peer-free, Web Fetch-clean, redirect-safe (`redirect: 'error'` plus response-level refusal), and
243
- compatible with `gateway.fetchFor('openrouter')` and custom `baseUrl` overrides:
244
-
245
- - **Decision models (`POST /systemone`):** `openRouterSystemOne` sends `noul`, `choice`, and
246
- `score` questions over text or structured `state` and returns calibrated probability answers plus
247
- `generationId` and `costUsd`.
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`.
248
364
  - **Audio (`POST /audio/transcriptions` and `POST /audio/speech`):** `openRouterAudioTranscription`
249
365
  accepts `audio: { kind: 'base64' | 'url' | 'file' }` (JSON or automatic `FormData` multipart
250
366
  without manual `Content-Type`), `verbose_json`, `timestampGranularities`, and `diarize`;
251
- `openRouterAudioSpeech` streams synthesized audio bytes (`ReadableStream<Uint8Array>`).
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.
252
369
  - **Images & Video (`POST /images` and `/videos`):** `openRouterGenerateImages` targets OpenRouter's
253
370
  Unified Image API (`b64_json` or signed `url`), while `openRouterSubmitVideo`,
254
371
  `openRouterGetVideo`, and `openRouterDownloadVideo` cover the async submit → poll → stream
@@ -260,6 +377,120 @@ compatible with `gateway.fetchFor('openrouter')` and custom `baseUrl` overrides:
260
377
  management or future endpoints (`/credits`, `/key`, `/responses`, `/images/models`, `/videos/models`)
261
378
  without custom wrappers.
262
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
+
263
494
  ### OpenRouter catalog snapshots, pricing ceilings, and cache
264
495
 
265
496
  `stitchkit/agent-runtime/openrouter` also provides a peer-free, Web Fetch-clean catalog layer for
@@ -332,13 +563,13 @@ extraction, classification, a bounded tool loop, or standalone streaming — cal
332
563
  - Pass `onPart` on `completeText` / `completeObject` or use `streamComplete` to consume
333
564
  `text-delta`, `reasoning-delta`, `tool-input-start`, `tool-call`, `tool-result` (preliminary and
334
565
  final), `tool-error`, `attempt-reset`, `finish-step`, and `finish` events over a bounded async
335
- iterable without a store. `streamComplete().parts` is single-use with a 64-part buffer: once
336
- iterated (`for await` or `parts[Symbol.asyncIterator]()`), backpressure pauses the producer when
337
- the buffer is full. If `parts` is never iterated, up to 64 parts buffer for late attachment and
338
- any overflow clears the queue without blocking so awaiting `result` alone (with or without
339
- `onPart`) completes in bounded memory; attempting to iterate `parts` after an unsubscribed
340
- overflow waits for completion and then propagates the run failure or throws an overflow `Error`
341
- 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.
342
573
  - Standalone completions have no durable approval loop, so any tool with `needsApproval: true` (or
343
574
  a `needsApproval` predicate returning `true`) is preflighted across every validated call in the
344
575
  step and fails closed with `AgentToolApprovalError` (`reason: 'approval-unsupported'`) before any
@@ -347,11 +578,22 @@ extraction, classification, a bounded tool loop, or standalone streaming — cal
347
578
  `toolDependencies`, `onPredecessorFailure`) on `completeText` / `streamComplete` /
348
579
  `completeObject` to enforce the same batch-refusal, cap, and dependency-ordering policies as
349
580
  `createAgentRuntime` (durable stream-only `stepBarriers` keys fail fast with a `TypeError`).
350
- - Pass `retry` (`AgentRetryPolicy`) and optional `onAttemptDiscarded` for stateless retry with
351
- `Retry-After` handling; exhausting retries throws `AgentRetryExhaustedError` carrying every failed
352
- 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).
353
591
  - Pass `stopPolicies` (`AgentCompleteStopPolicy[]`) and `idleTimeoutMs` to bound multi-step loops
354
- 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.
355
597
 
356
598
  ```ts
357
599
  import { z } from 'zod'
@@ -449,7 +691,10 @@ const runtime = createAgentRuntime({
449
691
  context: runContext.context,
450
692
  access: { gate: composeToolLifecycle(authLifecycle, runContext.toolFenceLifecycle) },
451
693
  }),
452
- loop: { prepareStep: deferred.prepareStep(applicationPrepareStep) },
694
+ loop: {
695
+ prepareStep: deferred.prepareStep(applicationPrepareStep),
696
+ repairToolCall: deferred.repairToolCall(applicationRepairToolCall),
697
+ },
453
698
  })
454
699
  ```
455
700
 
@@ -468,9 +713,11 @@ The latest valid same-run search replaces the earlier selection; parallel
468
713
  searches in one step merge in call order. Recovery reconstructs it, while a
469
714
  different run or finite surface cannot inherit it. Known inactive calls take a
470
715
  recoverable `SEARCH_REQUIRED` search round; unknown names still fail. Inactive-call
471
- repair travels with the tool set returned by `deferred.mount()` — so wrapping
472
- `deferred.prepareStep()` or calling `completeText` preserves it automatically — and can
473
- 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
474
721
  runtime marks that round with `reason: 'inactive_call'` beside the exact tool
475
722
  name. The field is the runtime's to write; a model that sets it anyway gets
476
723
  the same `SEARCH_REQUIRED` answer with an exact name, and with a query in words
@@ -872,7 +872,9 @@ bot.catch(({ error }) => logger.error('Telegram handler failed', { error }))
872
872
  const telegram = grammyBotResources({
873
873
  bot,
874
874
  dependsOn: [database, http], // what handlers need before the first update
875
- configure: () => bot.api.setMyCommands([{ command: 'start', description: 'Start' }]),
875
+ configure: async () => {
876
+ await bot.api.setMyCommands([{ command: 'start', description: 'Start' }])
877
+ },
876
878
  onEnded: ({ error }) => stopProcess(error), // see below
877
879
  })
878
880
 
package/llms/http.txt CHANGED
@@ -14,7 +14,7 @@ Also read:
14
14
 
15
15
  ## `stitchkit/http`
16
16
 
17
- An HTTP-only entrypoint for browsers, React Native/Hermes and servers. It exports the same `createClient`, `createClients`, `createHttpClient`, URL builders, client configuration types and `ApiError` as the root, without loading its optional Socket.IO graph, plus the `postMessage` bridge `ClientFetch` adapter and envelope schemas. Import shared contracts from `stitchkit/contract`.
17
+ An HTTP-only entrypoint for browsers, React Native/Hermes and servers. It exports the same `createClient`, `createClients`, `createHttpClient`, URL builders, client configuration types, `ApiError`, `readContractIdentity` (with its `ContractIdentity` result) and the stream line errors `StreamLineLimitError` / `StreamTruncatedLineError` as the root, without loading its optional Socket.IO graph, plus the `postMessage` bridge `ClientFetch` adapter and envelope schemas. Import shared contracts from `stitchkit/contract`.
18
18
 
19
19
  ```ts
20
20
  import { createClients, createHttpClient } from 'stitchkit/http';
package/llms/live.txt CHANGED
@@ -432,7 +432,9 @@ never runs.
432
432
  - **It does not gate operations.** "Only from this machine" is a property of an
433
433
  operation, and an operation is known after routing, not before it. Write it as
434
434
  an auth rule over `ctx.ipAddress` — `isLoopbackAddress` is exported for
435
- exactly that — where it composes with your other rules.
435
+ exactly that — where it composes with your other rules. Behind a proxy on the
436
+ same host every peer is loopback: resolve the visitor with `trustProxy` first
437
+ ([server guide](./server.md#client-ip-behind-a-proxy)).
436
438
  - **It does not re-check an open connection.** Both lanes check at admission.
437
439
  - **It does not see an `OPTIONS` preflight** when `cors` is configured; that is
438
440
  answered earlier. The preflight carries no operation and no body, and the
@@ -601,18 +601,25 @@ each request.
601
601
  A payload goes into an audit row only after `sanitizePayload`:
602
602
 
603
603
  - **secret-named keys are masked** — a key whose words include a secret term is
604
- redacted (`password`, `sessionToken`, `X-Api-Key`, `authorization`, `cookie`,
605
- …), while identifiers that merely contain one (`authorId`, `sessionCount`,
606
- `tokenizer`) survive. This applies wherever a key exists — an object field and
604
+ redacted (`password`, `passphrase`, `sessionToken`, `X-Api-Key`, `accessKey`,
605
+ `authorization`, `cookie`, …), a key written as one lowercase run that ends in
606
+ one (`newpassword`, `accesstoken`), and a key that ENDS in `auth`, `signature`,
607
+ `jwt`, `otp`, `pin` or `dsn` (`basicAuth`, `webhookSignature`, `SENTRY_DSN`),
608
+ while identifiers that merely contain one (`authorId`, `sessionCount`,
609
+ `tokenizer`, `pinned`) or only describe it (`signatureVersion`, `auth_date`,
610
+ a model token count such as `maxTokens` or `usage.total_tokens`)
611
+ survive. This applies wherever a key exists — an object field and
607
612
  a `Map` entry alike, at any depth. A `Set` member has no key, so nothing there
608
613
  is masked by name;
609
614
  - **secrets are masked by their shape** in every string, whatever key holds
610
615
  it — the secret half of a Telegram bot token (`123456:[redacted]`: the bot's
611
616
  id stays, it tells two bots apart), the password in
612
- `postgresql://user:password@host` (user, host and path stay), and the value
613
- of a query parameter named as a secret (`?access_token=`, `?api-key=`,
614
- `?key=`, `?sig=`). A URL in an error message or a request log line is the
615
- usual way a token reaches a journal;
617
+ `postgresql://user:password@host` (user, host and path stay), the user of an
618
+ `http(s)` / `ws(s)` address with no password (a Sentry DSN's key — a database
619
+ or SSH user stays), the credential after `Bearer`, a provider key (`sk-…`, `or-v1-…`, `AIza…`), a
620
+ JSON Web Token (`eyJ….eyJ….…`), and the value of a query parameter named as a
621
+ secret (`?access_token=`, `?api-key=`, `?key=`, `?sig=`). A URL in an error
622
+ message or a request log line is the usual way a token reaches a journal;
616
623
  - **an error keeps what it says about itself** — its own fields (`error_code`,
617
624
  `parameters`, a provider's `status`) are written beside `name`, `message`,
618
625
  `stack` and `cause`, masked by the same rules; a field holding a class
@@ -791,8 +798,8 @@ use; future optional fields do not change callback arity.
791
798
 
792
799
  `createObservability({ tools })` uses it already. Where the envelope was scrubbed to
793
800
  `INTERNAL_SERVER_ERROR`, the row's `errorMessage` becomes the real message
794
- instead of the placeholder; a truthful envelope (a thrown `AppError`, a
795
- `ZodError`) is left alone, `errorCode` and `errorDetail` are untouched, and the
801
+ instead of the placeholder (a `ZodError` from handler code is one of these); a
802
+ truthful envelope (a thrown `AppError`, invalid input) is left alone, `errorCode` and `errorDetail` are untouched, and the
796
803
  stack is not written — that is `onToolError`'s job, for a tracker that wants it.
797
804
  The caller still receives the scrubbed envelope in every case: the raw text
798
805
  reaches your server-side record, never the response. → ADR 0042
package/llms/server.2.txt CHANGED
@@ -103,7 +103,7 @@ Runtime requirements and boundaries:
103
103
  - **Origin trust and navigation lock-down.** A `postMessage` bridge has no loopback `Host` header,
104
104
  so `createLocalHostGuard` does not apply. `serveBridge` validates the native container-reported
105
105
  `origin` against the exact `origins` allow-list, strips `host`, `origin`, `x-forwarded-for`,
106
- `x-real-ip` and `forwarded` from every frame, refuses a handler with `trustProxy: true`, and
106
+ `x-real-ip` and `forwarded` from every frame, refuses a handler configured with `trustProxy`, and
107
107
  optionally verifies a per-start `secret` in constant time. Refusal reasons are logged on the host
108
108
  and never disclosed to the window. Because any page a WebView navigates to receives
109
109
  `window.ReactNativeWebView`, always lock navigation down in the WebView itself
@@ -147,8 +147,8 @@ This endpoint is HTTP-only and cannot be multipart or exposed as a tool. The
147
147
  router sets `ctx.rawBody` before JSON/Zod validation, so `onError` can inspect it
148
148
  after malformed JSON or a schema failure. Endpoints without `rawBody: true` do
149
149
  not retain the text. `maxJsonBodyBytes` may also be set once on `createServer` /
150
- `createHandler`; a route value wins. Both limits are opt-in and abort an
151
- oversized stream before it is fully buffered. → ADR 0051
150
+ `createHandler`; a route value wins. Without either the ceiling is 1 MiB; every
151
+ limit aborts an oversized stream before it is fully buffered. → ADR 0051, ADR 0340
152
152
 
153
153
  ## Safelisted request bodies (beacons)
154
154
 
@@ -452,11 +452,16 @@ contract route does.
452
452
 
453
453
  ### Serving files & Range requests
454
454
 
455
- `staticRoute(prefix, dir, { cacheControl })` serves a directory: it checks
456
- containment, then answers the file through `serveFile`, so a static image or
457
- video carries `ETag`, `Last-Modified` and `Accept-Ranges`, revalidates to `304`
458
- and seeks with `206`. `cacheControl` sets `Cache-Control` on every answer; by
459
- default none is sent.
455
+ `staticRoute(prefix, dir, { cacheControl, allowedDotNames })` serves a directory:
456
+ it checks containment, then answers the file through `serveFile`, so a static
457
+ image or video carries `ETag`, `Last-Modified` and `Accept-Ranges`, revalidates
458
+ to `304` and seeks with `206`. `cacheControl` sets `Cache-Control` on every
459
+ answer; by default none is sent.
460
+
461
+ A path with a segment that starts with a dot — `/.env`, `/.git/config`,
462
+ `/assets/.npmrc` — answers `404`, so a hidden file that ends up in the served
463
+ directory never leaves it. Name the ones you mean to publish:
464
+ `allowedDotNames: ['.well-known']`.
460
465
 
461
466
  ```ts
462
467
  import { createServer, staticRoute } from 'stitchkit/server'