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
package/llms-full.txt CHANGED
@@ -47,87 +47,87 @@ own, recorded as an ADR.
47
47
 
48
48
  | Import | Use in | Maturity | Holds |
49
49
  |--------|--------|----------|-------|
50
- | `stitchkit` | browser **and** server | stable<br>_redefined in 6 of the 42 minors since 0.94.0, most recently 0.135.0_ | `defineContract`, `createClient`, `createHttpClient`, `createSocketIOClient`, `parseSSE`, the error model |
51
- | `stitchkit/http` | browser, React Native/Hermes **and** server | evolving<br>_redefined in 3 of the 42 minors since 0.94.0, most recently 0.135.0_ | typed HTTP client factories and `ApiError`, without optional realtime peers |
52
- | `stitchkit/realtime` | browser, React Native/Hermes **and** server | evolving<br>_redefined in 1 of the 42 minors since 0.94.0, most recently 0.127.0_ | typed realtime clients, binding to an existing socket and retained topics with a required explicit Socket.IO peer loader |
53
- | `stitchkit/device-relay` | browser, React Native/Hermes **and** server | evolving<br>_redefined in 0 of the 2 minors since 0.134.0_ | peer-free User Device Relay over realtime — `createDeviceRelayHub`, `createDeviceRelayAgent`, `createMemoryRelayBroker`, `deviceRelayRealtimeContract`, Fetch-compatible unary RPC and credit-paced cursor streams |
54
- | `stitchkit/contract` | browser **and** server | stable<br>_redefined in 5 of the 42 minors since 0.94.0, most recently 0.127.0_ | the contract layer alone — `defineContract`, errors, pagination |
55
- | `stitchkit/live` | browser **and** server | evolving<br>_redefined in 2 of the 42 minors since 0.94.0, most recently 0.127.0_ | `defineEvents` — topic declarations beside the operation contract — and watched reads: `createWatchClient`, the value/difference frame and its reassembly |
56
- | `stitchkit/primitives` | browser **and** server | evolving<br>_redefined in 0 of the 42 minors since 0.94.0_ | generic values and declarations for lifecycle, access, audit, delivery and exports, exact money and rounding tables |
57
- | `stitchkit/handler` | browser, React Native/Hermes **and** server | evolving<br>_redefined in 0 of the 9 minors since 0.127.0_ | portable `createHandler`, `implement`, errors and `serveBridge` over a string `postMessage` port, with no Node built-ins |
58
- | `stitchkit/server` | server (Bun) | stable<br>_redefined in 5 of the 42 minors since 0.94.0, most recently 0.127.0_ | `createServer`, `implement`, hooks, auth, Socket.IO server, server primitives |
59
- | `stitchkit/node` | server (Node ≥ 22.3) | stable<br>_redefined in 2 of the 42 minors since 0.94.0, most recently 0.127.0_ | `serveNode` + the runtime-agnostic core — the Node mirror of `/server` |
60
- | `stitchkit/tools` | server | stable<br>_redefined in 12 of the 42 minors since 0.94.0, most recently 0.135.0_ | the transport-neutral tool layer — `mountAgentTools`, `defineAgentTool`, registry, tool names and manifest, runtime tools, native tools, the OAuth provider, the durability engine; loads no optional peer at runtime |
61
- | `stitchkit/tools/mcp` | server (Bun or Node) | evolving<br>_redefined in 3 of the 42 minors since 0.94.0, most recently 0.127.0_ | the canonical MCP HTTP/stdio server, schemas and typed MCP presenters; only Zod and the MCP server SDK peers |
62
- | `stitchkit/tools/agent` | server (Bun or Node) | evolving<br>_redefined in 2 of the 42 minors since 0.94.0, most recently 0.134.0_ | `mountAgent` — thin AI SDK `ToolSet` adapter over `mountAgentTools` for apps driving their own SDK loop; only Zod and the `ai` peer |
63
- | `stitchkit/tools/toolkit` | server (Bun or Node) | evolving<br>_redefined in 2 of the 42 minors since 0.94.0, most recently 0.135.0_ | `createToolkit` — context-pinned MCP, peer-free agent (`mountAgentTools`), and CLI mounts; only the MCP server SDK peer (no `ai` peer) |
64
- | `stitchkit/tools/contract` | browser + server | evolving<br>_redefined in 2 of the 42 minors since 0.94.0, most recently 0.124.0_ | the shapes a tool surface speaks — async-operation contract, snapshot and cancel schemas, view-file input/output — without the runtime that serves them |
65
- | `stitchkit/tools/invoker` | server | stable<br>_redefined in 3 of the 42 minors since 0.94.0, most recently 0.127.0_ | peer-free `createToolInvoker` over the canonical contract tool runner |
66
- | `stitchkit/tools/connections` | server (Bun or Node) | evolving<br>_redefined in 3 of the 42 minors since 0.94.0, most recently 0.127.0_ | consume external MCP servers and a bounded OpenAPI subset — typed reauthorization, a per-request host fence and per-call credentials |
67
- | `stitchkit/cli` | server | stable<br>_redefined in 12 of the 42 minors since 0.94.0, most recently 0.128.0_ | `createCli` / `createCliInvoker` — runtime and strict NodeNext declarations without MCP SDK / `ai` |
68
- | `stitchkit/cli/publish` | build and release tooling (Bun or Node, POSIX) | evolving<br>_redefined in 0 of the 42 minors since 0.94.0_ | `publishCli` — commit a verified CLI distribution and move its public manifest last; see [CLI guide](cli.md#publishing-a-complete-version) |
69
- | `stitchkit/remote` | browser **and** server | stable<br>_redefined in 1 of the 42 minors since 0.94.0, most recently 0.104.0_ | peer-free `implementRemote` for thin HTTP proxy processes |
70
- | `stitchkit/process` | server (Bun or Node, POSIX) | evolving<br>_redefined in 4 of the 42 minors since 0.94.0, most recently 0.133.0_ | finite native commands, byte sinks, bounded capture, process-group cancellation and opt-in Linux/Darwin owner-loss cleanup; contract operations executed in one-call child processes |
71
- | `stitchkit/process/bootstrap` | bundled server entry (Bun, POSIX) | evolving<br>_redefined in 0 of the 3 minors since 0.133.0_ | narrow bootstrap that keeps the process runner lazy while carrying the package's own invocations — the owner-loss guard and the process root of launched work — in a single-file bundle |
72
- | `stitchkit/files/packaging` | build time (Bun or Node) | evolving<br>_redefined in 4 of the 42 minors since 0.94.0, most recently 0.133.0_ | installed native asset graph, integrity, Bun packaging plugin and the artifact loader check; a client bundled into one self-contained, hashed file; a typed client built into a proven npm package with several entries, declarations and external peers; no runtime install policy |
73
- | `stitchkit/files` | server (Bun or Node) | stable<br>_redefined in 5 of the 42 minors since 0.94.0, most recently 0.133.0_ | peer-free managed local-file boundary |
74
- | `stitchkit/spend` | server (Bun or Node) | evolving<br>_redefined in 0 of the 9 minors since 0.127.0_ | peer-free spend gateway for paid model APIs: the attempt recorded before the call and closed on every outcome, credentials only for the provider's origin, a spooled ledger, rank-merged receipts and a reconciler |
75
- | `stitchkit/spend/testing` | tests on Bun or Node | evolving<br>_redefined in 0 of the 9 minors since 0.127.0_ | the coverage guard: red on a model SDK import, a provider key or a provider host outside the gateway files |
76
- | `stitchkit/service-host` | server (Bun or Node) | evolving<br>_redefined in 0 of the 9 minors since 0.127.0_ | peer-free host service supervision — verified versioned artifact activation, Linux `systemd` and macOS `launchd` units (`plutil`, `bootout`/`bootstrap`, rollback), live process/Unix-socket identity verification, and an in-process config-watched reloader |
77
- | `stitchkit/service-host/macos` | server (Bun or Node, macOS) | evolving<br>_redefined in 0 of the 9 minors since 0.127.0_ | peer-free macOS daemon bundle toolkit — fail-closed Developer ID `codesign`, strict C11 launcher `.app` bundles with atomic `RENAME_SWAP` install/rollback, Apple 824×824 squircle `AppIcon.icns`, streaming `lsregister` maintenance, and TCC responsibility inspection |
78
- | `stitchkit/service-host/work` | server (Bun or Node; Linux with systemd ≥ 254, or a process root on Linux and macOS) | evolving<br>_redefined in 0 of the 3 minors since 0.133.0_ | peer-free launch of work in its own boundary with a declared owner — a transient systemd scope or a recorded process root, the typed owner record, the one inherited variable that names the boundary, and the membership check that asks the boundary; see [native I/O](native-io.md#work-in-its-own-boundary) |
79
- | `stitchkit/telegram` | server (Bun or Node) | evolving<br>_redefined in 8 of the 42 minors since 0.94.0, most recently 0.127.0_ | peer-free Telegram platform primitives — Mini App `initData` verification, widget limits and the `widget_query` and widget message schemas, send-failure classification, one outbound budget per bot token with weighted albums and per-chat 429 pauses, resumable broadcasts, the operator channel with dedupe, a Bot API transport that separates a request that never left from an unknown outcome, local Bot API files, the waveform of a voice message read from its PCM, webhook ownership and durable webhook update intake |
80
- | `stitchkit/telegram/grammy` | server (Bun or Node) | evolving<br>_redefined in 0 of the 42 minors since 0.94.0_ | the token's outbound budget as one grammY client transformer — a 429 that comes back as a response pauses its chat, and a cancelled wait is a request that never left; the widget methods over the same client |
81
- | `stitchkit/telegram/html` | browser and server | evolving<br>_redefined in 1 of the 42 minors since 0.94.0, most recently 0.127.0_ | Telegram's HTML as a tree — compile GFM Markdown to Telegram HTML with fence-aware splitting, clean any markup to what Telegram accepts, cut long text into valid parts by what the reader sees, check markup before it is sent |
82
- | `stitchkit/telegram/voice` | browser and server | evolving<br>_redefined in 0 of the 42 minors since 0.94.0_ | the waveform of a voice message as one format — packed for `sendVoice` the way Telegram Desktop scales it, unpacked to draw it, a `getMe` read of whether the server takes it |
83
- | `stitchkit/telegram/screens` | server (Bun or Node) | evolving<br>_redefined in 1 of the 42 minors since 0.94.0, most recently 0.127.0_ | a bot's menus as declared screens over grammY — typed paths, actions and input, message reconciliation, state in any `StorageAdapter`, a test chat |
84
- | `stitchkit/tracking` | browser **and** server | evolving<br>_redefined in 3 of the 42 minors since 0.94.0, most recently 0.127.0_ | visitor-tracking mechanics — `createTrackingClient`, the tab-shared outbox, the page-leave beacon, attribution, the contract factory; no event vocabulary, no React |
85
- | `stitchkit/tracking/contract` | browser **and** server | evolving<br>_redefined in 0 of the 42 minors since 0.94.0_ | the wire shapes — the contract factory, event and visit schemas, the performance sample and its trust threshold; brings `zod` |
86
- | `stitchkit/tracking/performance` | browser **and** server | evolving<br>_redefined in 1 of the 42 minors since 0.94.0, most recently 0.127.0_ | Web Vitals from real visitors, collected after load through the optional peer `web-vitals`; no `zod` |
87
- | `stitchkit/tracking/server` | server (Bun or Node) | evolving<br>_redefined in 0 of the 42 minors since 0.94.0_ | the decisions a tracking backend makes — dispositions, visit lease over an application-owned store, active intervals, presence; no database |
88
- | `stitchkit/release` | browser **and** server | evolving<br>_redefined in 1 of the 42 minors since 0.94.0, most recently 0.127.0_ | a page follows the release it was built for — `createReleaseMarker` on the server, `createReleaseWatcher` in the browser, the `X-Build-Id` header and a socket event between them |
89
- | `stitchkit/voice` | browser **and** server | evolving<br>_redefined in 0 of the 42 minors since 0.94.0_ | the mechanics of a live voice reply — `SentenceCutter`, `speakableText`, a `SpeechQueue` that synthesises ahead and stops on interruption, the conversation phases |
90
- | `stitchkit/sync` | browser **and** server | evolving<br>_redefined in 1 of the 9 minors since 0.127.0, most recently 0.132.0_ | the client half of an offline-first sync — which outbox rows leave next, pending edits on top of remote rows, deletes that win until acknowledged, the cursor session, the push and page wire with an open outcome vocabulary; no driver, runs in Hermes |
91
- | `stitchkit/sync/postgres` | server (Bun or Node) | evolving<br>_redefined in 0 of the 9 minors since 0.127.0_ | the server half — versions that commit in order, a ledger that runs each change once, a feed of what changed, inside the app's own transaction; a memory store and `checkSyncStore` |
92
- | `stitchkit/geo` | server (Bun or Node) | evolving<br>_redefined in 2 of the 42 minors since 0.94.0, most recently 0.127.0_ | managed GeoIP reader generations, last-known-good reload and the optional MaxMind adapter |
93
- | `stitchkit/geo/contract` | browser **and** server | evolving<br>_redefined in 0 of the 42 minors since 0.94.0_ | the place snapshot schema, for a shared contract that stores or sends `GeoAttribution`; brings `zod` |
94
- | `stitchkit/xlsx` | browser **and** server | evolving<br>_redefined in 0 of the 42 minors since 0.94.0_ | a workbook from rows and typed columns, with no dependency; text never runs as a formula |
95
- | `stitchkit/oauth` | browser **and** server | evolving<br>_redefined in 0 of the 42 minors since 0.94.0_ | provider-neutral Authorization Code + PKCE request and one-shot callback transaction mechanics |
96
- | `stitchkit/google` | server (Bun or Node) | evolving<br>_redefined in 1 of the 42 minors since 0.94.0, most recently 0.127.0_ | optional Google code exchange and verified OIDC identity adapter |
97
- | `stitchkit/observability` | server | stable<br>_redefined in 1 of the 42 minors since 0.94.0, most recently 0.127.0_ | request/tool event projections — `createObservability`, trace context, sanitisation |
98
- | `stitchkit/testing` | tests on Bun or Node | stable<br>_redefined in 3 of the 42 minors since 0.94.0, most recently 0.127.0_ | in-process generated clients over a real Fetch handler, the managed-resource conformance kit and manual time for schedules and retries |
99
- | `stitchkit/declaration` | browser + build and deployment tooling (Bun or Node) | evolving<br>_redefined in 1 of the 42 minors since 0.94.0, most recently 0.128.0_ | `ProjectDeclarationSchema` — the one machine-readable statement a repository makes about itself |
100
- | `stitchkit/react` | browser + server rendering | stable<br>_redefined in 2 of the 42 minors since 0.94.0, most recently 0.127.0_ | `createCursorQuery`, `createCacheBridge`, QueryClient and `ApiError` retry policy |
101
- | `stitchkit/react/keyboard` | browser | evolving<br>_redefined in 1 of the 42 minors since 0.94.0, most recently 0.115.0_ | which part of a screen gets a key — ordered layers, one Escape per level, list zones with real focus; see [keyboard guide](keyboard.md) |
102
- | `stitchkit/react/keyboard/testing` | server (Bun or Node) | evolving<br>_redefined in 0 of the 42 minors since 0.94.0_ | the keyboard layers and zones without a DOM — fakes for the window, elements and key events beside the two engines, to test the order of layers, `scope`/`inert` and the edges of a zone in milliseconds |
103
- | `stitchkit/agent-runtime` | server | evolving<br>_redefined in 11 of the 42 minors since 0.94.0, most recently 0.135.0_ | peer-free durable conversation/run loop over `AgentModelDriver`, stateless `completeText`/`completeObject`, driver composition, history, models, prompts, fencing and events |
104
- | `stitchkit/agent-runtime/sandbox` | server | evolving<br>_redefined in 0 of the 42 minors since 0.94.0_ | optional Linux Bubblewrap sessions, long-lived OS process sandboxes (`createProcessSandbox`, `probeProcessSandbox`, `buildSeatbeltProfile`), durable workspaces and a host HTTP credential gateway; see [sandbox guide](sandbox.md) |
105
- | `stitchkit/agent-runtime/testing` | tests on Bun or Node | evolving<br>_redefined in 3 of the 42 minors since 0.94.0, most recently 0.134.0_ | peer-free `createScriptedModelDriver`, credential-free replay, scripted provider faults, deterministic race controls and the agent-store conformance kit |
106
- | `stitchkit/agent-runtime/harness` | server | evolving<br>_redefined in 1 of the 42 minors since 0.94.0, most recently 0.134.0_ | peer-free resource-aware process-local facade over the canonical Agent runtime; supervision stays outside |
107
- | `stitchkit/agent-runtime/coding-tools` | server (Bun or Node) | evolving<br>_redefined in 3 of the 42 minors since 0.94.0, most recently 0.127.0_ | bounded host-authorized direct file and shell tools; a root boundary, not an OS sandbox |
108
- | `stitchkit/agent-runtime/openrouter` | server | evolving<br>_redefined in 3 of the 42 minors since 0.94.0, most recently 0.135.0_ | peer-free native OpenRouter Chat Completions SSE driver, catalog, admission, route pinning and spend reconciliation |
109
- | `stitchkit/agent-runtime/openai` | server | evolving<br>_redefined in 0 of the 2 minors since 0.134.0_ | peer-free native OpenAI Responses API (`POST /v1/responses`) driver, policy schemas and provenance-aware usage normalization |
110
- | `stitchkit/agent-runtime/anthropic` | server | evolving<br>_redefined in 0 of the 2 minors since 0.134.0_ | peer-free native Anthropic Messages API (`POST /v1/messages`) driver, thinking/cache policy schemas and provenance-aware usage normalization |
111
- | `stitchkit/agent-runtime/ai-sdk` | server | evolving<br>_redefined in 0 of the 2 minors since 0.134.0_ | thin optional-peer adapter (`fromAiSdkModel`, `fromAiSdkTools`) bridging AI SDK (`LanguageModelV4` from `ai@7`) models and `ToolSet`s onto `AgentModelDriver` and `AgentToolSet`; requires `ai` |
112
- | `stitchkit/agent-runtime/browser` | browser + server | evolving<br>_redefined in 2 of the 42 minors since 0.94.0, most recently 0.127.0_ | canonical agent records, events, reconnect cursor, interactive approval/input/permission-mode/host-status state (`deriveAgentConversationActivity`, `deriveAgentConversationState`, `delivery: 'unknown'` reconciliation) and optional conversation controller |
113
- | `stitchkit/agent-runtime/react` | browser + server | evolving<br>_redefined in 0 of the 42 minors since 0.94.0_ | React subscription to an application-owned agent controller |
114
- | `stitchkit/agent-runtime/realtime` | server (Bun or Node) | evolving<br>_redefined in 2 of the 42 minors since 0.94.0, most recently 0.127.0_ | authorized agent control over the existing Socket.IO server |
115
- | `stitchkit/agent-executor` | server (Bun or Node) | evolving<br>_redefined in 4 of the 9 minors since 0.127.0, most recently 0.133.0_ | the executor ↔ server contract for external coding agents (Claude Code, Codex, ACP): delta vocabulary (including `ExecutorPlanDelta`) over the shared message parts, thread leases with a fence, turn phases and their reports |
116
- | `stitchkit/agent-executor/claude` | server (Bun or Node) | evolving<br>_redefined in 0 of the 9 minors since 0.127.0_ | the Claude Code driver: the unmodified CLI over `stream-json`, permission requests answered by the host, reconcile by the input's id in the profile's transcript |
117
- | `stitchkit/agent-executor/claude-sdk` | server (Bun or Node) | evolving<br>_redefined in 1 of the 9 minors since 0.127.0, most recently 0.131.0_ | Claude through the Agent SDK: the application's `query` (optional peer `@anthropic-ai/claude-agent-sdk`), the CLI's classifier, `canUseTool` asked of the host |
118
- | `stitchkit/agent-executor/acp` | server (Bun or Node) | evolving<br>_redefined in 0 of the 9 minors since 0.127.0_ | an Agent Client Protocol v1 agent over stdio: settings by category, images, MCP servers, tool metadata (`title`/`kind`/`locations`), meaningful `tool_call_update` progress updates, typed `plan` deltas, `session/resume`/`load`/`list`, `session/cancel`; no reconcile |
119
- | `stitchkit/agent-executor/codex` | server (Bun or Node) | evolving<br>_redefined in 3 of the 9 minors since 0.127.0, most recently 0.133.0_ | the Codex driver: `codex app-server` over stdio or Unix-socket WebSocket (`unix-listen` / `unix-connect`), thread policy and live controls, approval and input requests answered by the host, unknown server requests refused, reconcile by the client id in `thread/turns/list` |
120
- | `stitchkit/agent-executor/testing` | server (Bun or Node) | evolving<br>_redefined in 1 of the 9 minors since 0.127.0, most recently 0.133.0_ | the engine conformance kit, deterministic replay driver, portable fake Codex app-server, fail-loud consumer stub factories, and schema-validated test fixtures; no optional peer |
121
- | `stitchkit/agent-executor/testing/claude-sdk` | server (Bun or Node) | evolving<br>_redefined in 0 of the 3 minors since 0.133.0_ | the multi-turn fake Claude SDK query harness and the Claude SDK session stub, typed by the optional peer `@anthropic-ai/claude-agent-sdk` |
122
- | `stitchkit/agent-runtime/postgres` | server (Bun or Node) | evolving<br>_redefined in 0 of the 9 minors since 0.127.0_ | the agent store, conversation reader and companion host on Postgres, over the application's own client (Bun SQL, Prisma, `pg`) |
123
- | `stitchkit/agent-runtime/sqlite/bun` | server (Bun) | evolving<br>_redefined in 1 of the 42 minors since 0.94.0, most recently 0.127.0_ | durable built-in SQLite store for the agent runtime |
124
- | `stitchkit/agent-runtime/sqlite/node` | server (Node ≥ 22.5) | evolving<br>_redefined in 1 of the 42 minors since 0.94.0, most recently 0.127.0_ | durable built-in SQLite store for the agent runtime |
50
+ | `stitchkit` | browser **and** server | stable<br>_redefined in 6 of the 43 minors since 0.94.0, most recently 0.135.0_ | `defineContract`, `createClient`, `createHttpClient`, `createSocketIOClient`, `parseSSE`, the error model |
51
+ | `stitchkit/http` | browser, React Native/Hermes **and** server | evolving<br>_redefined in 3 of the 43 minors since 0.94.0, most recently 0.135.0_ | typed HTTP client factories, `ApiError`, `readContractIdentity` and the stream line errors, without optional realtime peers |
52
+ | `stitchkit/realtime` | browser, React Native/Hermes **and** server | evolving<br>_redefined in 1 of the 43 minors since 0.94.0, most recently 0.127.0_ | typed realtime clients, binding to an existing socket and retained topics with a required explicit Socket.IO peer loader |
53
+ | `stitchkit/device-relay` | browser, React Native/Hermes **and** server | evolving<br>_redefined in 0 of the 3 minors since 0.134.0_ | peer-free User Device Relay over realtime — `createDeviceRelayHub`, `createDeviceRelayAgent`, `createMemoryRelayBroker`, `deviceRelayRealtimeContract`, Fetch-compatible unary RPC and credit-paced cursor streams |
54
+ | `stitchkit/contract` | browser **and** server | stable<br>_redefined in 6 of the 43 minors since 0.94.0, most recently 0.136.0_ | the contract layer alone — `defineContract`, errors, pagination |
55
+ | `stitchkit/live` | browser **and** server | evolving<br>_redefined in 2 of the 43 minors since 0.94.0, most recently 0.127.0_ | `defineEvents` — topic declarations beside the operation contract — and watched reads: `createWatchClient`, the value/difference frame and its reassembly |
56
+ | `stitchkit/primitives` | browser **and** server | evolving<br>_redefined in 0 of the 43 minors since 0.94.0_ | generic values and declarations for lifecycle, access, audit, delivery and exports, exact money and rounding tables |
57
+ | `stitchkit/handler` | browser, React Native/Hermes **and** server | evolving<br>_redefined in 1 of the 10 minors since 0.127.0, most recently 0.136.0_ | portable `createHandler`, `implement`, errors and `serveBridge` over a string `postMessage` port, with no Node built-ins |
58
+ | `stitchkit/server` | server (Bun) | stable<br>_redefined in 6 of the 43 minors since 0.94.0, most recently 0.136.0_ | `createServer`, `implement`, hooks, auth, Socket.IO server, server primitives |
59
+ | `stitchkit/node` | server (Node ≥ 22.3) | stable<br>_redefined in 3 of the 43 minors since 0.94.0, most recently 0.136.0_ | `serveNode` + the runtime-agnostic core — the Node mirror of `/server` |
60
+ | `stitchkit/tools` | server | stable<br>_redefined in 13 of the 43 minors since 0.94.0, most recently 0.136.0_ | the transport-neutral tool layer — `mountAgentTools`, `defineAgentTool`, registry, tool names and manifest, runtime tools, native tools, the OAuth provider, the durability engine; loads no optional peer at runtime |
61
+ | `stitchkit/tools/mcp` | server (Bun or Node) | evolving<br>_redefined in 3 of the 43 minors since 0.94.0, most recently 0.127.0_ | the canonical MCP HTTP/stdio server, schemas and typed MCP presenters; only Zod and the MCP server SDK peers |
62
+ | `stitchkit/tools/agent` | server (Bun or Node) | evolving<br>_redefined in 2 of the 43 minors since 0.94.0, most recently 0.134.0_ | `mountAgent` — thin AI SDK `ToolSet` adapter over `mountAgentTools` for apps driving their own SDK loop; only Zod and the `ai` peer |
63
+ | `stitchkit/tools/toolkit` | server (Bun or Node) | evolving<br>_redefined in 2 of the 43 minors since 0.94.0, most recently 0.135.0_ | `createToolkit` — context-pinned MCP, peer-free agent (`mountAgentTools`), and CLI mounts; only the MCP server SDK peer (no `ai` peer) |
64
+ | `stitchkit/tools/contract` | browser + server | evolving<br>_redefined in 2 of the 43 minors since 0.94.0, most recently 0.124.0_ | the shapes a tool surface speaks — async-operation contract, snapshot and cancel schemas, view-file input/output — without the runtime that serves them |
65
+ | `stitchkit/tools/invoker` | server | stable<br>_redefined in 3 of the 43 minors since 0.94.0, most recently 0.127.0_ | peer-free `createToolInvoker` over the canonical contract tool runner |
66
+ | `stitchkit/tools/connections` | server (Bun or Node) | evolving<br>_redefined in 3 of the 43 minors since 0.94.0, most recently 0.127.0_ | consume external MCP servers and a bounded OpenAPI subset — typed reauthorization, a per-request host fence and per-call credentials |
67
+ | `stitchkit/cli` | server | stable<br>_redefined in 12 of the 43 minors since 0.94.0, most recently 0.128.0_ | `createCli` / `createCliInvoker` — runtime and strict NodeNext declarations without MCP SDK / `ai` |
68
+ | `stitchkit/cli/publish` | build and release tooling (Bun or Node, POSIX) | evolving<br>_redefined in 0 of the 43 minors since 0.94.0_ | `publishCli` — commit a verified CLI distribution and move its public manifest last; see [CLI guide](cli.md#publishing-a-complete-version) |
69
+ | `stitchkit/remote` | browser **and** server | stable<br>_redefined in 1 of the 43 minors since 0.94.0, most recently 0.104.0_ | peer-free `implementRemote` for thin HTTP proxy processes |
70
+ | `stitchkit/process` | server (Bun or Node, POSIX) | evolving<br>_redefined in 4 of the 43 minors since 0.94.0, most recently 0.133.0_ | finite native commands, byte sinks, bounded capture, process-group cancellation and opt-in Linux/Darwin owner-loss cleanup; contract operations executed in one-call child processes |
71
+ | `stitchkit/process/bootstrap` | bundled server entry (Bun, POSIX) | evolving<br>_redefined in 0 of the 4 minors since 0.133.0_ | narrow bootstrap that keeps the process runner lazy while carrying the package's own invocations — the owner-loss guard and the process root of launched work — in a single-file bundle |
72
+ | `stitchkit/files/packaging` | build time (Bun or Node) | evolving<br>_redefined in 4 of the 43 minors since 0.94.0, most recently 0.133.0_ | installed native asset graph, integrity, Bun packaging plugin and the artifact loader check; a client bundled into one self-contained, hashed file; a typed client built into a proven npm package with several entries, declarations and external peers; no runtime install policy |
73
+ | `stitchkit/files` | server (Bun or Node) | stable<br>_redefined in 5 of the 43 minors since 0.94.0, most recently 0.133.0_ | peer-free managed local-file boundary |
74
+ | `stitchkit/spend` | server (Bun or Node) | evolving<br>_redefined in 0 of the 10 minors since 0.127.0_ | peer-free spend gateway for paid model APIs: the attempt recorded before the call and closed on every outcome, credentials only for the provider's origin, a spooled ledger, rank-merged receipts and a reconciler |
75
+ | `stitchkit/spend/testing` | tests on Bun or Node | evolving<br>_redefined in 0 of the 10 minors since 0.127.0_ | the coverage guard: red on a model SDK import, a provider key or a provider host outside the gateway files |
76
+ | `stitchkit/service-host` | server (Bun or Node) | evolving<br>_redefined in 0 of the 10 minors since 0.127.0_ | peer-free host service supervision — verified versioned artifact activation, Linux `systemd` and macOS `launchd` units (`plutil`, `bootout`/`bootstrap`, rollback), live process/Unix-socket identity verification, and an in-process config-watched reloader |
77
+ | `stitchkit/service-host/macos` | server (Bun or Node, macOS) | evolving<br>_redefined in 0 of the 10 minors since 0.127.0_ | peer-free macOS daemon bundle toolkit — fail-closed Developer ID `codesign`, strict C11 launcher `.app` bundles with atomic `RENAME_SWAP` install/rollback, Apple 824×824 squircle `AppIcon.icns`, streaming `lsregister` maintenance, and TCC responsibility inspection |
78
+ | `stitchkit/service-host/work` | server (Bun or Node; Linux with systemd ≥ 254, or a process root on Linux and macOS) | evolving<br>_redefined in 0 of the 4 minors since 0.133.0_ | peer-free launch of work in its own boundary with a declared owner — a transient systemd scope or a recorded process root, the typed owner record, the one inherited variable that names the boundary, and the membership check that asks the boundary; see [native I/O](native-io.md#work-in-its-own-boundary) |
79
+ | `stitchkit/telegram` | server (Bun or Node) | evolving<br>_redefined in 9 of the 43 minors since 0.94.0, most recently 0.136.0_ | peer-free Telegram platform primitives — Mini App `initData` verification, widget limits and the `widget_query`, `shared_widget_query` and widget message schemas, send-failure classification, one outbound budget per bot token with weighted albums and per-chat 429 pauses, resumable broadcasts, the operator channel with dedupe, a Bot API transport that separates a request that never left from an unknown outcome, local Bot API files, the waveform of a voice message read from its PCM, webhook ownership and durable webhook update intake |
80
+ | `stitchkit/telegram/grammy` | server (Bun or Node) | evolving<br>_redefined in 0 of the 43 minors since 0.94.0_ | the token's outbound budget as one grammY client transformer — a 429 that comes back as a response pauses its chat, and a cancelled wait is a request that never left; the widget methods over the same client |
81
+ | `stitchkit/telegram/html` | browser and server | evolving<br>_redefined in 1 of the 43 minors since 0.94.0, most recently 0.127.0_ | Telegram's HTML as a tree — compile GFM Markdown to Telegram HTML with fence-aware splitting, clean any markup to what Telegram accepts, cut long text into valid parts by what the reader sees, check markup before it is sent |
82
+ | `stitchkit/telegram/voice` | browser and server | evolving<br>_redefined in 0 of the 43 minors since 0.94.0_ | the waveform of a voice message as one format — packed for `sendVoice` the way Telegram Desktop scales it, unpacked to draw it, a `getMe` read of whether the server takes it |
83
+ | `stitchkit/telegram/screens` | server (Bun or Node) | evolving<br>_redefined in 1 of the 43 minors since 0.94.0, most recently 0.127.0_ | a bot's menus as declared screens over grammY — typed paths, actions and input, message reconciliation, state in any `StorageAdapter`, a test chat |
84
+ | `stitchkit/tracking` | browser **and** server | evolving<br>_redefined in 3 of the 43 minors since 0.94.0, most recently 0.127.0_ | visitor-tracking mechanics — `createTrackingClient`, the tab-shared outbox, the page-leave beacon, attribution, the contract factory; no event vocabulary, no React |
85
+ | `stitchkit/tracking/contract` | browser **and** server | evolving<br>_redefined in 0 of the 43 minors since 0.94.0_ | the wire shapes — the contract factory, event and visit schemas, the performance sample and its trust threshold; brings `zod` |
86
+ | `stitchkit/tracking/performance` | browser **and** server | evolving<br>_redefined in 1 of the 43 minors since 0.94.0, most recently 0.127.0_ | Web Vitals from real visitors, collected after load through the optional peer `web-vitals`; no `zod` |
87
+ | `stitchkit/tracking/server` | server (Bun or Node) | evolving<br>_redefined in 0 of the 43 minors since 0.94.0_ | the decisions a tracking backend makes — dispositions, visit lease over an application-owned store, active intervals, presence; no database |
88
+ | `stitchkit/release` | browser **and** server | evolving<br>_redefined in 1 of the 43 minors since 0.94.0, most recently 0.127.0_ | a page follows the release it was built for — `createReleaseMarker` on the server, `createReleaseWatcher` in the browser, the `X-Build-Id` header and a socket event between them |
89
+ | `stitchkit/voice` | browser **and** server | evolving<br>_redefined in 0 of the 43 minors since 0.94.0_ | the mechanics of a live voice reply — `SentenceCutter`, `speakableText`, a `SpeechQueue` that synthesises ahead and stops on interruption, the conversation phases |
90
+ | `stitchkit/sync` | browser **and** server | evolving<br>_redefined in 1 of the 10 minors since 0.127.0, most recently 0.132.0_ | the client half of an offline-first sync — which outbox rows leave next, pending edits on top of remote rows, deletes that win until acknowledged, the cursor session, the push and page wire with an open outcome vocabulary; no driver, runs in Hermes |
91
+ | `stitchkit/sync/postgres` | server (Bun or Node) | evolving<br>_redefined in 0 of the 10 minors since 0.127.0_ | the server half — versions that commit in order, a ledger that runs each change once, a feed of what changed, inside the app's own transaction; a memory store and `checkSyncStore` |
92
+ | `stitchkit/geo` | server (Bun or Node) | evolving<br>_redefined in 2 of the 43 minors since 0.94.0, most recently 0.127.0_ | managed GeoIP reader generations, last-known-good reload and the optional MaxMind adapter |
93
+ | `stitchkit/geo/contract` | browser **and** server | evolving<br>_redefined in 0 of the 43 minors since 0.94.0_ | the place snapshot schema, for a shared contract that stores or sends `GeoAttribution`; brings `zod` |
94
+ | `stitchkit/xlsx` | browser **and** server | evolving<br>_redefined in 0 of the 43 minors since 0.94.0_ | a workbook from rows and typed columns, with no dependency; text never runs as a formula |
95
+ | `stitchkit/oauth` | browser **and** server | evolving<br>_redefined in 0 of the 43 minors since 0.94.0_ | provider-neutral Authorization Code + PKCE request and one-shot callback transaction mechanics |
96
+ | `stitchkit/google` | server (Bun or Node) | evolving<br>_redefined in 1 of the 43 minors since 0.94.0, most recently 0.127.0_ | optional Google code exchange and verified OIDC identity adapter |
97
+ | `stitchkit/observability` | server | stable<br>_redefined in 2 of the 43 minors since 0.94.0, most recently 0.136.0_ | request/tool event projections — `createObservability`, trace context, sanitisation |
98
+ | `stitchkit/testing` | tests on Bun or Node | stable<br>_redefined in 3 of the 43 minors since 0.94.0, most recently 0.127.0_ | in-process generated clients over a real Fetch handler, the managed-resource conformance kit and manual time for schedules and retries |
99
+ | `stitchkit/declaration` | browser + build and deployment tooling (Bun or Node) | evolving<br>_redefined in 1 of the 43 minors since 0.94.0, most recently 0.128.0_ | `ProjectDeclarationSchema` — the one machine-readable statement a repository makes about itself |
100
+ | `stitchkit/react` | browser + server rendering | stable<br>_redefined in 3 of the 43 minors since 0.94.0, most recently 0.136.0_ | `createCursorQuery`, `createCacheBridge`, QueryClient and `ApiError` retry policy |
101
+ | `stitchkit/react/keyboard` | browser | evolving<br>_redefined in 1 of the 43 minors since 0.94.0, most recently 0.115.0_ | which part of a screen gets a key — ordered layers, one Escape per level, list zones with real focus; see [keyboard guide](keyboard.md) |
102
+ | `stitchkit/react/keyboard/testing` | server (Bun or Node) | evolving<br>_redefined in 0 of the 43 minors since 0.94.0_ | the keyboard layers and zones without a DOM — fakes for the window, elements and key events beside the two engines, to test the order of layers, `scope`/`inert` and the edges of a zone in milliseconds |
103
+ | `stitchkit/agent-runtime` | server | evolving<br>_redefined in 12 of the 43 minors since 0.94.0, most recently 0.136.0_ | peer-free durable conversation/run loop over `AgentModelDriver`, stateless `completeText`/`completeObject`, driver composition, history, models, prompts, fencing and events |
104
+ | `stitchkit/agent-runtime/sandbox` | server | evolving<br>_redefined in 1 of the 43 minors since 0.94.0, most recently 0.136.0_ | optional Linux Bubblewrap sessions, long-lived OS process sandboxes (`createProcessSandbox`, `probeProcessSandbox`, `buildSeatbeltProfile`), durable workspaces and a host HTTP credential gateway; see [sandbox guide](sandbox.md) |
105
+ | `stitchkit/agent-runtime/testing` | tests on Bun or Node | evolving<br>_redefined in 4 of the 43 minors since 0.94.0, most recently 0.136.0_ | peer-free `createScriptedModelDriver`, credential-free replay, scripted provider faults, deterministic race controls and the agent-store conformance kit |
106
+ | `stitchkit/agent-runtime/harness` | server | evolving<br>_redefined in 1 of the 43 minors since 0.94.0, most recently 0.134.0_ | peer-free resource-aware process-local facade over the canonical Agent runtime; supervision stays outside |
107
+ | `stitchkit/agent-runtime/coding-tools` | server (Bun or Node) | evolving<br>_redefined in 3 of the 43 minors since 0.94.0, most recently 0.127.0_ | bounded host-authorized direct file and shell tools; a root boundary, not an OS sandbox |
108
+ | `stitchkit/agent-runtime/openrouter` | server | evolving<br>_redefined in 4 of the 43 minors since 0.94.0, most recently 0.136.0_ | peer-free native OpenRouter Chat Completions SSE driver, catalog, admission, route pinning and spend reconciliation, plus typed non-chat clients (speech-to-text, text-to-speech, images, video, embeddings, rerank, System One, any endpoint through `openRouterRequestJson`) bound once by `createOpenRouterClient`; see [agent runtime guide](agent-runtime.md#openrouter-non-chat-endpoints-and-shared-transport) |
109
+ | `stitchkit/agent-runtime/openai` | server | evolving<br>_redefined in 0 of the 3 minors since 0.134.0_ | peer-free native OpenAI Responses API (`POST /v1/responses`) driver, policy schemas and provenance-aware usage normalization |
110
+ | `stitchkit/agent-runtime/anthropic` | server | evolving<br>_redefined in 0 of the 3 minors since 0.134.0_ | peer-free native Anthropic Messages API (`POST /v1/messages`) driver, thinking/cache policy schemas and provenance-aware usage normalization |
111
+ | `stitchkit/agent-runtime/ai-sdk` | server | evolving<br>_redefined in 0 of the 3 minors since 0.134.0_ | thin optional-peer adapter (`fromAiSdkModel`, `fromAiSdkTools`) bridging AI SDK (`LanguageModelV4` from `ai@7`) models and `ToolSet`s onto `AgentModelDriver` and `AgentToolSet`; requires `ai` |
112
+ | `stitchkit/agent-runtime/browser` | browser + server | evolving<br>_redefined in 2 of the 43 minors since 0.94.0, most recently 0.127.0_ | canonical agent records, events, reconnect cursor, interactive approval/input/permission-mode/host-status state (`deriveAgentConversationActivity`, `deriveAgentConversationState`, `delivery: 'unknown'` reconciliation) and optional conversation controller |
113
+ | `stitchkit/agent-runtime/react` | browser + server | evolving<br>_redefined in 0 of the 43 minors since 0.94.0_ | React subscription to an application-owned agent controller |
114
+ | `stitchkit/agent-runtime/realtime` | server (Bun or Node) | evolving<br>_redefined in 2 of the 43 minors since 0.94.0, most recently 0.127.0_ | authorized agent control over the existing Socket.IO server |
115
+ | `stitchkit/agent-executor` | server (Bun or Node) | evolving<br>_redefined in 4 of the 10 minors since 0.127.0, most recently 0.133.0_ | the executor ↔ server contract for external coding agents (Claude Code, Codex, ACP): delta vocabulary (including `ExecutorPlanDelta`) over the shared message parts, thread leases with a fence, turn phases and their reports |
116
+ | `stitchkit/agent-executor/claude` | server (Bun or Node) | evolving<br>_redefined in 0 of the 10 minors since 0.127.0_ | the Claude Code driver: the unmodified CLI over `stream-json`, permission requests answered by the host, reconcile by the input's id in the profile's transcript |
117
+ | `stitchkit/agent-executor/claude-sdk` | server (Bun or Node) | evolving<br>_redefined in 1 of the 10 minors since 0.127.0, most recently 0.131.0_ | Claude through the Agent SDK: the application's `query` (optional peer `@anthropic-ai/claude-agent-sdk`), the CLI's classifier, `canUseTool` asked of the host |
118
+ | `stitchkit/agent-executor/acp` | server (Bun or Node) | evolving<br>_redefined in 0 of the 10 minors since 0.127.0_ | an Agent Client Protocol v1 agent over stdio: settings by category, images, MCP servers, tool metadata (`title`/`kind`/`locations`), meaningful `tool_call_update` progress updates, typed `plan` deltas, `session/resume`/`load`/`list`, `session/cancel`; no reconcile |
119
+ | `stitchkit/agent-executor/codex` | server (Bun or Node) | evolving<br>_redefined in 3 of the 10 minors since 0.127.0, most recently 0.133.0_ | the Codex driver: `codex app-server` over stdio or Unix-socket WebSocket (`unix-listen` / `unix-connect`), thread policy and live controls, approval and input requests answered by the host, unknown server requests refused, reconcile by the client id in `thread/turns/list` |
120
+ | `stitchkit/agent-executor/testing` | server (Bun or Node) | evolving<br>_redefined in 1 of the 10 minors since 0.127.0, most recently 0.133.0_ | the engine conformance kit, deterministic replay driver, portable fake Codex app-server, fail-loud consumer stub factories, and schema-validated test fixtures; no optional peer |
121
+ | `stitchkit/agent-executor/testing/claude-sdk` | server (Bun or Node) | evolving<br>_redefined in 0 of the 4 minors since 0.133.0_ | the multi-turn fake Claude SDK query harness and the Claude SDK session stub, typed by the optional peer `@anthropic-ai/claude-agent-sdk` |
122
+ | `stitchkit/agent-runtime/postgres` | server (Bun or Node) | evolving<br>_redefined in 0 of the 10 minors since 0.127.0_ | the agent store, conversation reader and companion host on Postgres, over the application's own client (Bun SQL, Prisma, `pg`) |
123
+ | `stitchkit/agent-runtime/sqlite/bun` | server (Bun) | evolving<br>_redefined in 1 of the 43 minors since 0.94.0, most recently 0.127.0_ | durable built-in SQLite store for the agent runtime |
124
+ | `stitchkit/agent-runtime/sqlite/node` | server (Node ≥ 22.5) | evolving<br>_redefined in 1 of the 43 minors since 0.94.0, most recently 0.127.0_ | durable built-in SQLite store for the agent runtime |
125
125
  | `stitchkit-tui` | terminal (Bun) | evolving | optional official OpenTUI host over a caller-composed headless runtime |
126
- | `stitchkit/application` | browser + server | evolving<br>_redefined in 9 of the 42 minors since 0.94.0, most recently 0.127.0_ | managed resource graph, readiness, admission, schedules, subtree restart and bounded shutdown |
127
- | `stitchkit/application/grammy` | server | evolving<br>_redefined in 0 of the 42 minors since 0.94.0_ | a grammY bot as application resources — configuration, then polling with updates admitted by batch — and the webhook adapter |
128
- | `stitchkit/application/opentelemetry` | server | evolving<br>_redefined in 0 of the 42 minors since 0.94.0_ | maps application snapshots onto an injected OpenTelemetry `Meter` |
129
- | `stitchkit/application/diagnostic-journal` | server | evolving<br>_redefined in 3 of the 42 minors since 0.94.0, most recently 0.127.0_ | the local diagnostic journal — an exclusive bounded writer and snapshot reader with explicit anomalies |
130
- | `stitchkit/application/directory-inbox` | server | evolving<br>_redefined in 0 of the 42 minors since 0.94.0_ | the directory inbox — entries another program drops into a directory, delivered to the application at least once |
126
+ | `stitchkit/application` | browser + server | evolving<br>_redefined in 9 of the 43 minors since 0.94.0, most recently 0.127.0_ | managed resource graph, readiness, admission, schedules, subtree restart and bounded shutdown |
127
+ | `stitchkit/application/grammy` | server | evolving<br>_redefined in 0 of the 43 minors since 0.94.0_ | a grammY bot as application resources — configuration, then polling with updates admitted by batch — and the webhook adapter |
128
+ | `stitchkit/application/opentelemetry` | server | evolving<br>_redefined in 0 of the 43 minors since 0.94.0_ | maps application snapshots onto an injected OpenTelemetry `Meter` |
129
+ | `stitchkit/application/diagnostic-journal` | server | evolving<br>_redefined in 3 of the 43 minors since 0.94.0, most recently 0.127.0_ | the local diagnostic journal — an exclusive bounded writer and snapshot reader with explicit anomalies |
130
+ | `stitchkit/application/directory-inbox` | server | evolving<br>_redefined in 0 of the 43 minors since 0.94.0_ | the directory inbox — entries another program drops into a directory, delivered to the application at least once |
131
131
 
132
132
  Rule of thumb: browser code imports `stitchkit` and `stitchkit/react`; server
133
133
  code adds `stitchkit/server` (or `stitchkit/node` on Node) and opts into
@@ -167,18 +167,28 @@ export const notes = defineContract({ prefix: 'notes' }, {
167
167
 
168
168
  ```ts
169
169
  // src/server/index.ts
170
- import { implement, createServer } from 'stitchkit/server'
170
+ import { createServer, implement, notFound } from 'stitchkit/server'
171
171
  import { notes } from '../shared/contracts'
172
172
 
173
+ const db = new Map<string, { id: string; text: string }>() // your database here
174
+
173
175
  const service = implement(notes, {
174
- list: () => db.list(),
175
- create: (ctx) => db.create(ctx.input.text), // ctx.input is typed
176
- get: (ctx) => db.get(ctx.params.id), // ctx.params is typed
176
+ list: () => [...db.values()],
177
+ create: (ctx) => { // ctx.input is typed
178
+ const note = { id: String(db.size + 1), text: ctx.input.text }
179
+ db.set(note.id, note)
180
+ return note
181
+ },
182
+ get: (ctx) => db.get(ctx.params.id) ?? notFound(), // ctx.params is typed
177
183
  })
178
184
 
179
- createServer({ services: [service], port: 3000 })
185
+ const server = createServer({ services: [service], port: 3000 })
186
+ console.log(`Listening on ${server.url}`)
180
187
  ```
181
188
 
189
+ Each contract is served under its prefix: `notes` answers at `/notes` and
190
+ `/notes/:id`, with no other path in front.
191
+
182
192
  ### 3. Call it, typed
183
193
 
184
194
  ```ts
@@ -186,16 +196,19 @@ createServer({ services: [service], port: 3000 })
186
196
  import { createClient, createHttpClient } from 'stitchkit'
187
197
  import { notes } from '../shared/contracts'
188
198
 
189
- export const api = createClient(notes, createHttpClient({ baseUrl: '/api' }))
199
+ export const api = createClient(notes, createHttpClient({ baseUrl: 'http://localhost:3000' }))
190
200
 
191
- await api.list() // GET /notes → Note[]
192
- await api.create({ text: 'hi' }) // POST /notes → Note
193
- await api.get({ id: '1' }) // GET /notes/1 → Note
201
+ console.log(await api.create({ text: 'hi' })) // POST http://localhost:3000/notes → Note
202
+ console.log(await api.list()) // GET http://localhost:3000/notes → Note[]
203
+ console.log(await api.get({ id: '1' })) // GET http://localhost:3000/notes/1 → Note
194
204
  ```
195
205
 
196
- Run the server with `bun run src/server/index.ts`. The contract is the single
197
- source of truth — change it and both the handler and the client are re-typed at
198
- once.
206
+ Start the server with `bun run src/server/index.ts`, then run the client in a
207
+ second terminal with `bun run src/client/api.ts`. `baseUrl` is where the server
208
+ listens; a browser app served from the same origin can pass its own origin, or
209
+ mount the services under a prefix (`groups: [{ pathPrefix: '/api', services: [service] }]`)
210
+ and call `baseUrl: '/api'`. The contract is the single source of truth — change it
211
+ and both the handler and the client are re-typed at once.
199
212
 
200
213
  #### On Node
201
214
 
@@ -268,7 +281,7 @@ bun add socket.io @socket.io/bun-engine # e.g. the Socket.IO server on Bun
268
281
  Dynamic optional-peer adapters fail with an actionable error naming the package
269
282
  and install command. Static entrypoints such as `stitchkit/tools/mcp` fail during
270
283
  ESM resolution by naming the exact missing package; the feature-to-peer matrix
271
- below is the canonical install command.
284
+ above is the canonical install command.
272
285
 
273
286
  `stitchkit/tools` itself loads no optional peer, and `stitchkit/tools/toolkit`
274
287
  stays free of `ai` (ADR 0338). Install only the peer of the adapter you import:
@@ -310,6 +323,13 @@ durable SQLite history, lazy skills, direct coding tools, approval continuations
310
323
  and recovery stay framework-owned primitives, while model choice, permissions,
311
324
  executables and OS isolation remain application policy.
312
325
 
326
+ For a long-polling Telegram bot, run
327
+ `bun create stitchkit my-bot --template telegram-bot`, copy `.env.example` to
328
+ `.env`, set `BOT_TOKEN`, then run `bun run dev`. The bot is a managed
329
+ application (`stitchkit/application` with `stitchkit/application/grammy`): its
330
+ handlers live in `src/handlers.ts`, and the entry point turns signals and a
331
+ poller that ended on its own into a bounded shutdown.
332
+
313
333
 
314
334
  ==============================================================================
315
335
  # Guide: Release (docs/guide/release.md)
@@ -1430,8 +1450,10 @@ To type `ctx` with your app's extras (the user an auth hook injects), fix the
1430
1450
  context type once:
1431
1451
 
1432
1452
  ```ts
1453
+ import type { RuntimeContext } from 'stitchkit'
1433
1454
  import { createImplement } from 'stitchkit/server'
1434
1455
 
1456
+ interface User { id: string; name: string }
1435
1457
  interface AppContext extends RuntimeContext { user: User | null }
1436
1458
 
1437
1459
  export const implement = createImplement<AppContext>()
@@ -1447,7 +1469,20 @@ there. `createScopedImplement` types each handler by its endpoint's **effective*
1447
1469
  scope instead — the endpoint's own `scope`, else the contract's:
1448
1470
 
1449
1471
  ```ts
1472
+ import { defineContract } from 'stitchkit'
1450
1473
  import { createScopedImplement } from 'stitchkit/server'
1474
+ import { z } from 'zod'
1475
+
1476
+ const Post = z.object({ id: z.string(), title: z.string() })
1477
+
1478
+ const postsContract = defineContract({ prefix: 'posts', scope: 'user' }, {
1479
+ list: { method: 'GET', path: '/', desc: 'List my posts', output: z.array(Post) },
1480
+ purge: { method: 'DELETE', path: '/', desc: 'Purge all posts', scope: 'admin', output: z.array(Post) },
1481
+ ping: { method: 'GET', path: '/ping', desc: 'Health check', scope: 'public', output: z.object({ ok: z.boolean() }) },
1482
+ })
1483
+
1484
+ declare function listPosts(userId: string): Array<z.infer<typeof Post>>
1485
+ declare function purge(): Array<z.infer<typeof Post>>
1451
1486
 
1452
1487
  export const implementFor = createScopedImplement<{
1453
1488
  public: object // no extra fields
@@ -1623,7 +1658,7 @@ server. See [Testing & deployment](./testing-and-deployment.md).
1623
1658
  | `groups` | route groups — a shared path prefix and hooks (see below) |
1624
1659
  | `scopePrefixes` | `scope → path prefix` map — mount `services` by `service.scope` (see below) |
1625
1660
  | `rawRoutes` | non-contract routes (see below) |
1626
- | `maxJsonBodyBytes` | optional JSON body cap (bytes); per-route value overrides; unset preserves existing behaviour |
1661
+ | `maxJsonBodyBytes` | JSON body cap in bytes, **1 MiB by default**; a per-route value overrides it; a larger body is refused with `400 BAD_REQUEST` before it is buffered or parsed |
1627
1662
  | `port` / `hostname` | listen address — port defaults to `3000` |
1628
1663
  | `unix` | listen on a unix domain socket instead of TCP — `'/run/app.sock'` or `{ path, mode }` (see below) |
1629
1664
  | `cors` | CORS policy — `{ origin, credentials, methods, headers, exposeHeaders }`. `origin` is **required** when `cors` is present: pass an explicit origin (or list), or `'*'` to deliberately allow every origin — an origin-less config is a construction error, never a silent wildcard. `origin` may also be a function that answers each request origin with or without credentials ([below](#cors-decided-per-request)). Omit `cors` entirely to emit no CORS headers. |
@@ -1631,6 +1666,7 @@ server. See [Testing & deployment](./testing-and-deployment.md).
1631
1666
  | `logging` | `true` for built-in request logs, or a `LoggingConfig` (see below) |
1632
1667
  | `traceId` | override per-request trace-id resolution — may return `undefined` to fall back |
1633
1668
  | `wrapFetch` | compose wrappers around the finished handler (request context, audit) |
1669
+ | `trustProxy` | client IP behind proxies you run: `{ trustedPeer(address) }`; `x-forwarded-for` is read right to left from a trusted socket peer ([below](#client-ip-behind-a-proxy)); unset, `ctx.ipAddress` is the socket peer |
1634
1670
  | `proxyOrigin` | Bun TCP ingress policy: `{ trustedPeer(socketIp) }` restores the external scheme before all composition; independent of client-IP `trustProxy` |
1635
1671
  | `socket` | full StitchKit Socket.IO handle; route, default WebSocket handler and shutdown are mounted once |
1636
1672
  | `websocket` | custom Bun WebSocket handler; with `socket`, this is the explicit composed handler |
@@ -1681,6 +1717,43 @@ createServer({
1681
1717
  - A `safelistedBody` endpoint reads a `text/plain` body only from an origin
1682
1718
  granted with credentials ([below](#safelisted-request-bodies-beacons)).
1683
1719
 
1720
+ ### Client IP behind a proxy
1721
+
1722
+ Without `trustProxy`, `ctx.ipAddress` is the real socket peer and no header can
1723
+ change it. Behind a reverse proxy that peer is the proxy, so name the proxies you
1724
+ run:
1725
+
1726
+ ```ts
1727
+ import { createServer, isLoopbackAddress } from 'stitchkit/server'
1728
+
1729
+ const server = createServer({
1730
+ hostname: '127.0.0.1',
1731
+ trustProxy: { trustedPeer: isLoopbackAddress }, // nginx on this host
1732
+ services,
1733
+ })
1734
+ ```
1735
+
1736
+ `x-forwarded-for` is read only when the socket peer is a trusted proxy, and then
1737
+ from the **right**: each proxy appends the address it received the request from,
1738
+ so the rightmost entries are written by your proxies and the leftmost by the
1739
+ client. The first address `trustedPeer` does not accept is the client; when every
1740
+ hop is trusted, the leftmost one is. A hop that is not an IP address makes the
1741
+ client unknown (`ctx.ipAddress` is `undefined`), never a guess. `x-real-ip` is
1742
+ not read — it carries no chain to check.
1743
+
1744
+ The proxy must **append** (nginx: `proxy_set_header X-Forwarded-For
1745
+ $proxy_add_x_forwarded_for;`). For a chain of proxies, `trustedPeer` accepts each
1746
+ of them — a CIDR check for an internal network, for example. The same option
1747
+ exists on `wrapInRequestContext` and on `extractIp` / `getClientInfo`, which also
1748
+ need the real peer: pass `socketIp: resolveSocketIp(req, server)`; without it the
1749
+ header is ignored and the answer is `''`.
1750
+
1751
+ ⚠️ **A proxy on the same host makes every request loopback.** Without
1752
+ `trustProxy`, a server behind nginx on `127.0.0.1` sees `127.0.0.1` as the peer of
1753
+ every visitor, so a rule like `isLoopbackAddress(ctx.ipAddress)` admits the whole
1754
+ internet. Either configure `trustProxy` so the visitor's address is resolved, or
1755
+ listen where the proxy cannot forward the privileged operation.
1756
+
1684
1757
  ### External origin behind a trusted proxy
1685
1758
 
1686
1759
  An HTTPS ingress often forwards plain HTTP to Bun. `trustProxy` trusts client-IP
@@ -2300,7 +2373,7 @@ Runtime requirements and boundaries:
2300
2373
  - **Origin trust and navigation lock-down.** A `postMessage` bridge has no loopback `Host` header,
2301
2374
  so `createLocalHostGuard` does not apply. `serveBridge` validates the native container-reported
2302
2375
  `origin` against the exact `origins` allow-list, strips `host`, `origin`, `x-forwarded-for`,
2303
- `x-real-ip` and `forwarded` from every frame, refuses a handler with `trustProxy: true`, and
2376
+ `x-real-ip` and `forwarded` from every frame, refuses a handler configured with `trustProxy`, and
2304
2377
  optionally verifies a per-start `secret` in constant time. Refusal reasons are logged on the host
2305
2378
  and never disclosed to the window. Because any page a WebView navigates to receives
2306
2379
  `window.ReactNativeWebView`, always lock navigation down in the WebView itself
@@ -2344,8 +2417,8 @@ This endpoint is HTTP-only and cannot be multipart or exposed as a tool. The
2344
2417
  router sets `ctx.rawBody` before JSON/Zod validation, so `onError` can inspect it
2345
2418
  after malformed JSON or a schema failure. Endpoints without `rawBody: true` do
2346
2419
  not retain the text. `maxJsonBodyBytes` may also be set once on `createServer` /
2347
- `createHandler`; a route value wins. Both limits are opt-in and abort an
2348
- oversized stream before it is fully buffered. → ADR 0051
2420
+ `createHandler`; a route value wins. Without either the ceiling is 1 MiB; every
2421
+ limit aborts an oversized stream before it is fully buffered. → ADR 0051, ADR 0340
2349
2422
 
2350
2423
  ## Safelisted request bodies (beacons)
2351
2424
 
@@ -2649,11 +2722,16 @@ contract route does.
2649
2722
 
2650
2723
  ### Serving files & Range requests
2651
2724
 
2652
- `staticRoute(prefix, dir, { cacheControl })` serves a directory: it checks
2653
- containment, then answers the file through `serveFile`, so a static image or
2654
- video carries `ETag`, `Last-Modified` and `Accept-Ranges`, revalidates to `304`
2655
- and seeks with `206`. `cacheControl` sets `Cache-Control` on every answer; by
2656
- default none is sent.
2725
+ `staticRoute(prefix, dir, { cacheControl, allowedDotNames })` serves a directory:
2726
+ it checks containment, then answers the file through `serveFile`, so a static
2727
+ image or video carries `ETag`, `Last-Modified` and `Accept-Ranges`, revalidates
2728
+ to `304` and seeks with `206`. `cacheControl` sets `Cache-Control` on every
2729
+ answer; by default none is sent.
2730
+
2731
+ A path with a segment that starts with a dot — `/.env`, `/.git/config`,
2732
+ `/assets/.npmrc` — answers `404`, so a hidden file that ends up in the served
2733
+ directory never leaves it. Name the ones you mean to publish:
2734
+ `allowedDotNames: ['.well-known']`.
2657
2735
 
2658
2736
  ```ts
2659
2737
  import { createServer, staticRoute } from 'stitchkit/server'
@@ -3986,7 +4064,7 @@ call, over HTTP or a Unix socket alike:
3986
4064
  import { withContractIdentity } from 'stitchkit/server'
3987
4065
  createServer({ services: withContractIdentity(services) })
3988
4066
 
3989
- // client
4067
+ // client (`stitchkit/http` exports the same function for React Native/Hermes)
3990
4068
  import { readContractIdentity } from 'stitchkit'
3991
4069
  const { client, server } = await readContractIdentity(contracts, config)
3992
4070
  if (server === undefined) {
@@ -4323,7 +4401,9 @@ character split across chunks is never torn. A line that crosses `maxLineBytes`
4323
4401
  retains at most the limit, however long the line. With `finalLine: 'require-newline'`, a source
4324
4402
  that ends inside a line throws `StreamTruncatedLineError` (`lineBytes`) instead of yielding the
4325
4403
  fragment as a value — the right policy for a socket or a child process, where a missing newline
4326
- means the writer died. Both errors extend the `RangeError` / `SyntaxError` they replace.
4404
+ means the writer died. Both errors extend the `RangeError` / `SyntaxError` they replace, and
4405
+ both are exported from `stitchkit` and `stitchkit/http`, so a React Native client checks a contract
4406
+ stream's failure without importing the root entry.
4327
4407
 
4328
4408
  ## Reading a body up to a byte limit
4329
4409
 
@@ -6436,32 +6516,77 @@ bun add ai@^7
6436
6516
 
6437
6517
  ## Minimal composition
6438
6518
 
6519
+ The whole loop in one file: a protocol, a model, a prompt, contract tools and one turn. It runs
6520
+ as written — `createScriptedModelDriver` from `stitchkit/agent-runtime/testing` stands in for
6521
+ the provider, so `bun run agent.ts` needs no key and no network:
6522
+
6439
6523
  ```ts
6524
+ // agent.ts
6440
6525
  import { z } from 'zod'
6526
+ import { defineContract } from 'stitchkit'
6527
+ import { AppError, implement } from 'stitchkit/server'
6441
6528
  import {
6442
- AgentContextOverflowError,
6443
6529
  composeAgentPrompt,
6444
6530
  createAgentRuntime,
6445
6531
  createMemoryAgentRuntimeStore,
6446
6532
  defineAgentProtocol,
6447
6533
  defineModelRegistry,
6448
6534
  } from 'stitchkit/agent-runtime'
6449
- import { openRouterProvider } from 'stitchkit/agent-runtime/openrouter'
6450
- import { composeToolLifecycle, mountAgentTools } from 'stitchkit/tools'
6535
+ import { createScriptedModelDriver } from 'stitchkit/agent-runtime/testing'
6536
+ import { composeToolLifecycle, mountAgentTools, type ToolGate } from 'stitchkit/tools'
6537
+
6538
+ // The agent's tools are an ordinary contract; the endpoint `lookup` of `orders` is the tool `lookup_order`.
6539
+ const orders = defineContract({ prefix: 'orders' }, {
6540
+ lookup: {
6541
+ method: 'GET',
6542
+ path: '/:id',
6543
+ desc: 'Look up an order by id',
6544
+ params: z.object({ id: z.string() }),
6545
+ output: z.object({ id: z.string(), status: z.string() }),
6546
+ },
6547
+ })
6548
+ const service = implement(orders, {
6549
+ lookup: (ctx) => ({ id: ctx.params.id, status: 'shipped' }),
6550
+ })
6551
+
6552
+ // Who may call them: your auth rule as a tool gate (`createAuthHook` builds one too).
6553
+ const authLifecycle: ToolGate = {
6554
+ beforeHandle: (ctx) => {
6555
+ if (typeof ctx.userId !== 'string') throw new AppError('UNAUTHORIZED')
6556
+ },
6557
+ }
6451
6558
 
6452
6559
  const protocol = defineAgentProtocol({
6453
6560
  context: z.object({ userId: z.string() }),
6454
6561
  inputMetadata: z.object({}),
6455
6562
  })
6456
6563
 
6564
+ // Two scripted model steps: call the tool, then answer.
6565
+ const usage = (input: number, output: number) => ({
6566
+ inputTokens: { value: input, provenance: 'provider-reported' as const },
6567
+ outputTokens: { value: output, provenance: 'provider-reported' as const },
6568
+ })
6569
+ const scripted = createScriptedModelDriver({
6570
+ steps: [
6571
+ [
6572
+ { type: 'tool-call', toolCallId: 'call-1', toolName: 'lookup_order', input: '{"id":"42"}' },
6573
+ { type: 'finish', finishReason: 'tool-calls', usage: usage(20, 5) },
6574
+ ],
6575
+ [
6576
+ { type: 'text-delta', id: 'text-1', delta: 'Order 42 has shipped.' },
6577
+ { type: 'finish', finishReason: 'stop', usage: usage(40, 6) },
6578
+ ],
6579
+ ],
6580
+ })
6581
+
6457
6582
  const models = defineModelRegistry({
6458
6583
  providers: {
6459
- openrouter: openRouterProvider({ apiKey: env.OPENROUTER_API_KEY }),
6584
+ scripted: { create: () => scripted },
6460
6585
  },
6461
6586
  models: {
6462
6587
  fast: {
6463
- provider: 'openrouter',
6464
- modelId: 'provider/model',
6588
+ provider: 'scripted',
6589
+ modelId: 'scripted-model',
6465
6590
  contextWindow: 128_000,
6466
6591
  capabilities: ['tools'],
6467
6592
  },
@@ -6480,7 +6605,9 @@ const runtime = createAgentRuntime({
6480
6605
  protocol,
6481
6606
  store: createMemoryAgentRuntimeStore(),
6482
6607
  models: {
6483
- preflight: () => models.preflight('fast', ['tools']),
6608
+ preflight: () => {
6609
+ models.preflight('fast', ['tools']) // throws when the model cannot serve the turn
6610
+ },
6484
6611
  resolve: () => models.resolve('fast', ['tools']),
6485
6612
  },
6486
6613
  prompt: ({ context, signal, model }) =>
@@ -6503,16 +6630,14 @@ const runtime = createAgentRuntime({
6503
6630
  runs: { inputPolicy: 'interrupt', coalescePending: true },
6504
6631
  loop: {
6505
6632
  idleTimeoutMs: 60_000,
6506
- prepareStep: ({ context, steps }) => ({
6507
- activeTools: steps.some((step) => step.toolCalls.length > 0)
6508
- ? ['lookup']
6509
- : ['lookup', 'discover'],
6633
+ prepareStep: ({ context }) => ({
6634
+ activeTools: ['lookup_order'],
6510
6635
  instructions: `Current account: ${context.userId}`,
6511
6636
  }),
6512
6637
  stopPolicies: [
6513
6638
  {
6514
- name: 'repeated-tool-error',
6515
- when: ({ steps }) => hasRepeatedToolError(steps),
6639
+ name: 'too-many-tool-steps',
6640
+ when: ({ steps }) => steps.filter((step) => step.toolCalls.length > 0).length >= 5,
6516
6641
  },
6517
6642
  ],
6518
6643
  },
@@ -6522,7 +6647,7 @@ const ticket = runtime.submit({
6522
6647
  conversationId: 'conversation-id',
6523
6648
  idempotencyKey: 'request-id',
6524
6649
  context: { userId: 'user-id' },
6525
- parts: [{ type: 'text', text: 'Hello' }],
6650
+ parts: [{ type: 'text', text: 'Where is order 42?' }],
6526
6651
  recordIds: {
6527
6652
  inputMessageId: 'user-message-id',
6528
6653
  runId: 'run-id',
@@ -6530,11 +6655,36 @@ const ticket = runtime.submit({
6530
6655
  },
6531
6656
  })
6532
6657
 
6533
- const admission = await ticket.admission
6534
6658
  await ticket.accepted
6535
6659
  const terminal = await ticket.result
6660
+ console.log(terminal.reason, terminal.message.parts) // 'success', the tool call, its result, the answer
6661
+ await runtime.close()
6662
+ ```
6663
+
6664
+ For a real model, register its provider under the same key and keep everything else:
6665
+
6666
+ ```ts
6667
+ import { defineModelRegistry } from 'stitchkit/agent-runtime'
6668
+ import { openRouterProvider } from 'stitchkit/agent-runtime/openrouter'
6669
+
6670
+ const models = defineModelRegistry({
6671
+ providers: {
6672
+ openrouter: openRouterProvider({ apiKey: () => process.env.OPENROUTER_API_KEY ?? '' }),
6673
+ },
6674
+ models: {
6675
+ fast: {
6676
+ provider: 'openrouter',
6677
+ modelId: 'provider/model', // a live tool-capable model id from the OpenRouter catalog
6678
+ contextWindow: 128_000,
6679
+ capabilities: ['tools'],
6680
+ },
6681
+ },
6682
+ })
6536
6683
  ```
6537
6684
 
6685
+ Both blocks are type-checked, and the first one run, by
6686
+ `packages/core/tests/guide-first-path-snippets.test.ts`.
6687
+
6538
6688
  A stop policy's `when` receives the completed `AgentStepResult[]` steps so far together with the
6539
6689
  same run context `prepareStep` gets — `context`, `run`, `signal`, `toolFenceLifecycle` and
6540
6690
  `contextUsage` — typed by the runtime's `CONTEXT`. A rule that depends on its own run (a receipt
@@ -6542,6 +6692,40 @@ bound to the run's request, a per-tenant limit) reads it there; it needs no map
6542
6692
  by `runId`. The first policy to return `true` ends the run as `policy_stop` with its `name` as
6543
6693
  `policyName`.
6544
6694
 
6695
+ ### When a run ends `runtime_failure`
6696
+
6697
+ A run ends `runtime_failure` when the composition fails it — `tools`, `prompt` or a hook throws, a
6698
+ checkpoint cannot be written — and `provider_failure` when the model call does. The result a
6699
+ caller awaits says which, never why: `terminal.reason` and the failed message travel to clients,
6700
+ and a raw cause can carry a provider's response body, a path or another user's data. The cause goes
6701
+ to the operator channel, `observe`, and only to a sink that asks for it with `includeInternalCause`:
6702
+
6703
+ ```ts
6704
+ import { createAgentObservability, createAgentRuntime } from 'stitchkit/agent-runtime'
6705
+
6706
+ const observe = createAgentObservability({
6707
+ includeInternalCause: true, // operator-only: keep this sink's output away from clients
6708
+ write: (event) => {
6709
+ if (event.type === 'run-terminal' && event.internalCause !== undefined) {
6710
+ console.error(`run ${event.runId} ended ${event.terminalReason}:`, event.internalCause)
6711
+ }
6712
+ },
6713
+ })
6714
+
6715
+ const runtime = createAgentRuntime({
6716
+ ...composition, // protocol, store, models, prompt and tools, as in the minimal composition
6717
+ observe,
6718
+ })
6719
+
6720
+ const ticket = runtime.submit(input)
6721
+ const terminal = await ticket.result
6722
+ await observe.flush() // the sink is bounded and asynchronous; flush before reading it or exiting
6723
+ ```
6724
+
6725
+ Without `observe`, nothing reports the cause. A composition missing `protocol`, `store`,
6726
+ `models.resolve`, `prompt` or `tools` does not get that far: `createAgentRuntime` throws a
6727
+ `TypeError` naming them. `packages/core/tests/agent-runtime-failure-cause.test.ts` holds both.
6728
+
6545
6729
  ## Native model port, providers and driver composition
6546
6730
 
6547
6731
  Every model call crosses one single-step port — `AgentModelDriver.stream(request, signal)` — with
@@ -6577,6 +6761,14 @@ freshly per stream call and reporting server `response.timestamp` alongside `mod
6577
6761
  ≤ 4 cache breakpoints with TTL-order checks, `output_config.format` JSON Schema (refusing
6578
6762
  schemaless `json-object`), and retryable `529 overloaded_error` classification.
6579
6763
 
6764
+ A Chat Completions stream is complete only when it says so: `data: [DONE]`, or a usage chunk
6765
+ after `finish_reason` — the ending [OpenRouter's streaming reference](https://openrouter.ai/docs/api_reference/streaming)
6766
+ describes. An OpenAI-compatible server behind `openRouterProvider({ baseUrl })` that closes the
6767
+ connection after `finish_reason` with neither cannot be told apart from a cut that lost the usage
6768
+ chunk, so the step fails with a retryable `AgentProviderStreamCutError` instead of finishing with
6769
+ unreported usage. Such a server has to send `data: [DONE]` (or usage, e.g. on
6770
+ `stream_options.include_usage`); there is no option to accept the bare close.
6771
+
6580
6772
  For an existing AI SDK (`LanguageModelV4` from `ai@7`) model or `ToolSet`, import `fromAiSdkModel` and `fromAiSdkTools` from
6581
6773
  `stitchkit/agent-runtime/ai-sdk`. Both adapt directly onto `AgentModelDriver` and `AgentToolSet`
6582
6774
  (driving `model.doStream()` without importing `streamText` or `generateText`) and normalize legacy
@@ -6601,15 +6793,20 @@ const guarded = composeModelDrivers(base, [admissionDecorator, telemetryDecorato
6601
6793
  (`https://openrouter.ai/api/v1`), `OpenRouterFetch`, generic non-chat transport helpers
6602
6794
  (`openRouterRequestJson` and `openRouterRequestStream`), and typed modality clients — all
6603
6795
  peer-free, Web Fetch-clean, redirect-safe (`redirect: 'error'` plus response-level refusal), and
6604
- compatible with `gateway.fetchFor('openrouter')` and custom `baseUrl` overrides:
6605
-
6606
- - **Decision models (`POST /systemone`):** `openRouterSystemOne` sends `noul`, `choice`, and
6607
- `score` questions over text or structured `state` and returns calibrated probability answers plus
6608
- `generationId` and `costUsd`.
6796
+ compatible with `gateway.fetchFor('openrouter')` and custom `baseUrl` overrides. Chat, catalog,
6797
+ spend and every non-chat client share one transport: one `baseUrl` rule (`https:`, or `http:` to a
6798
+ loopback host only; no credentials, query or fragment; the API root, not an endpoint URL), one injected `fetch` option, and one error class,
6799
+ `AgentProviderError` with `statusCode`, for every non-2xx answer:
6800
+
6801
+ - **Decision models (`POST /systemone`):** `openRouterSystemOne` sends `noul`, `choice`,
6802
+ `score` and image `box` questions over text or structured `state` (with image `assets`,
6803
+ `sessionId` and `user`) and returns calibrated probability answers, bounding boxes and
6804
+ per-question refusals plus `generationId` and `costUsd`.
6609
6805
  - **Audio (`POST /audio/transcriptions` and `POST /audio/speech`):** `openRouterAudioTranscription`
6610
6806
  accepts `audio: { kind: 'base64' | 'url' | 'file' }` (JSON or automatic `FormData` multipart
6611
6807
  without manual `Content-Type`), `verbose_json`, `timestampGranularities`, and `diarize`;
6612
- `openRouterAudioSpeech` streams synthesized audio bytes (`ReadableStream<Uint8Array>`).
6808
+ `openRouterAudioSpeech` streams synthesized audio bytes (`ReadableStream<Uint8Array>`), takes
6809
+ text or multi-speaker turns, and with `outputDelivery: 'url'` returns a signed download URL instead.
6613
6810
  - **Images & Video (`POST /images` and `/videos`):** `openRouterGenerateImages` targets OpenRouter's
6614
6811
  Unified Image API (`b64_json` or signed `url`), while `openRouterSubmitVideo`,
6615
6812
  `openRouterGetVideo`, and `openRouterDownloadVideo` cover the async submit → poll → stream
@@ -6621,6 +6818,120 @@ compatible with `gateway.fetchFor('openrouter')` and custom `baseUrl` overrides:
6621
6818
  management or future endpoints (`/credits`, `/key`, `/responses`, `/images/models`, `/videos/models`)
6622
6819
  without custom wrappers.
6623
6820
 
6821
+ `createOpenRouterClient` states the key, `baseUrl`, `fetch`, headers and attribution once and returns
6822
+ every function above as a method of the same name (`audioTranscription`, `audioSpeech`, `systemOne`,
6823
+ `generateImages`, `submitVideo`, `getVideo`, `downloadVideo`, `embeddings`, `rerank`, `requestJson`,
6824
+ `requestStream`); a value passed to one call overrides the client's, except `headers` and
6825
+ `providerApiKeys`, which merge key by key with the call's entries winning. An invalid `baseUrl` or
6826
+ static `apiKey` is refused when the client is created. Every example below is
6827
+ type-checked against the current exports by `packages/core/tests/openrouter-guide-snippets.test.ts`.
6828
+
6829
+ Speech to text — inline audio, or a URL the provider downloads:
6830
+
6831
+ ```ts
6832
+ import { createOpenRouterClient } from 'stitchkit/agent-runtime/openrouter';
6833
+
6834
+ const openRouter = createOpenRouterClient({
6835
+ apiKey: () => process.env.OPENROUTER_API_KEY ?? '',
6836
+ appName: 'Minutes',
6837
+ });
6838
+
6839
+ const fromBytes = await openRouter.audioTranscription({
6840
+ model: 'openai/whisper-large-v3',
6841
+ audio: { kind: 'base64', data: 'UklGRiQA...', format: 'wav' },
6842
+ responseFormat: 'verbose_json',
6843
+ diarize: true,
6844
+ });
6845
+ for (const word of fromBytes.words ?? []) console.log(word.speaker, word.speakerLabel, word.word);
6846
+
6847
+ const fromUrl = await openRouter.audioTranscription({
6848
+ model: 'elevenlabs/scribe-v2',
6849
+ audio: { kind: 'url', url: 'https://example.com/meeting.mp3' },
6850
+ });
6851
+ console.log(fromUrl.text, fromUrl.costUsd);
6852
+ ```
6853
+
6854
+ Audio by URL depends on the model, and OpenRouter publishes which models accept it neither in the
6855
+ endpoints API nor in its documentation. A model that cannot fetch a URL answers HTTP 400 "The
6856
+ selected model does not support audio from a URL. Send the audio inline instead." before any charge;
6857
+ the call rejects with `AgentProviderError` (`statusCode: 400`) carrying that message. Checked on
6858
+ 2026-11-30: `elevenlabs/scribe-v2` transcribed a URL, while `openai/whisper-large-v3-turbo`,
6859
+ `deepgram/nova-3`, `mistralai/voxtral-mini-3b-2507` and `assemblyai/universal-3-5-pro` refused it —
6860
+ send their audio as `base64` or `file`.
6861
+
6862
+ Text to speech — streamed bytes, or a signed URL OpenRouter keeps for 24 hours:
6863
+
6864
+ ```ts
6865
+ import { createOpenRouterClient } from 'stitchkit/agent-runtime/openrouter';
6866
+
6867
+ const openRouter = createOpenRouterClient({ apiKey: () => process.env.OPENROUTER_API_KEY ?? '' });
6868
+
6869
+ const streamed = await openRouter.audioSpeech({
6870
+ model: 'mistralai/voxtral-mini-tts-2603',
6871
+ input: 'Hello world',
6872
+ voice: 'en_paul_neutral',
6873
+ responseFormat: 'mp3',
6874
+ });
6875
+ const mp3 = new Uint8Array(await new Response(streamed.audio).arrayBuffer());
6876
+
6877
+ const stored = await openRouter.audioSpeech({
6878
+ model: 'google/gemini-3.8-flash-lite-tts',
6879
+ input: [
6880
+ { text: "How's it going today, Jane?", voice: 'Kore' },
6881
+ { text: 'Not too bad, how about you?', voice: 'Puck', instructions: 'tired, yawning' },
6882
+ ],
6883
+ responseFormat: 'wav',
6884
+ outputDelivery: 'url',
6885
+ });
6886
+ console.log(mp3.byteLength);
6887
+ // Zero-data-retention makes OpenRouter stream even when a URL was asked for: read those bytes too.
6888
+ if (stored.delivery === 'url') console.log(stored.url, new Date(stored.expiresAt * 1000));
6889
+ else {
6890
+ const wav = new Uint8Array(await new Response(stored.audio).arrayBuffer());
6891
+ console.log(wav.byteLength, stored.contentType);
6892
+ }
6893
+ ```
6894
+
6895
+ Video — submit, poll, download:
6896
+
6897
+ ```ts
6898
+ import { createOpenRouterClient } from 'stitchkit/agent-runtime/openrouter';
6899
+
6900
+ const openRouter = createOpenRouterClient({ apiKey: () => process.env.OPENROUTER_API_KEY ?? '' });
6901
+
6902
+ const job = await openRouter.submitVideo({
6903
+ model: 'google/veo-3.1',
6904
+ prompt: 'A paper boat drifting down a rain gutter',
6905
+ duration: 4,
6906
+ });
6907
+ let state = await openRouter.getVideo({ jobId: job.id });
6908
+ while (state.jobStatus !== 'completed' && state.jobStatus !== 'failed') {
6909
+ await new Promise((resolve) => setTimeout(resolve, 5_000));
6910
+ state = await openRouter.getVideo({ jobId: job.id });
6911
+ }
6912
+ if (state.jobStatus === 'completed') {
6913
+ const video = await openRouter.downloadVideo({ jobId: job.id });
6914
+ console.log(video.contentType, state.costUsd);
6915
+ }
6916
+ ```
6917
+
6918
+ Any other endpoint — `requestJson` with a Zod `schema` types and validates the answer:
6919
+
6920
+ ```ts
6921
+ import { createOpenRouterClient } from 'stitchkit/agent-runtime/openrouter';
6922
+ import { z } from 'zod';
6923
+
6924
+ const openRouter = createOpenRouterClient({ apiKey: () => process.env.OPENROUTER_API_KEY ?? '' });
6925
+
6926
+ const credits = await openRouter.requestJson({
6927
+ path: '/credits',
6928
+ schema: z.object({
6929
+ data: z.object({ total_credits: z.number(), total_usage: z.number() }),
6930
+ }),
6931
+ });
6932
+ console.log(credits.data.data.total_credits - credits.data.data.total_usage);
6933
+ ```
6934
+
6624
6935
  ### OpenRouter catalog snapshots, pricing ceilings, and cache
6625
6936
 
6626
6937
  `stitchkit/agent-runtime/openrouter` also provides a peer-free, Web Fetch-clean catalog layer for
@@ -6693,13 +7004,13 @@ extraction, classification, a bounded tool loop, or standalone streaming — cal
6693
7004
  - Pass `onPart` on `completeText` / `completeObject` or use `streamComplete` to consume
6694
7005
  `text-delta`, `reasoning-delta`, `tool-input-start`, `tool-call`, `tool-result` (preliminary and
6695
7006
  final), `tool-error`, `attempt-reset`, `finish-step`, and `finish` events over a bounded async
6696
- iterable without a store. `streamComplete().parts` is single-use with a 64-part buffer: once
6697
- iterated (`for await` or `parts[Symbol.asyncIterator]()`), backpressure pauses the producer when
6698
- the buffer is full. If `parts` is never iterated, up to 64 parts buffer for late attachment and
6699
- any overflow clears the queue without blocking so awaiting `result` alone (with or without
6700
- `onPart`) completes in bounded memory; attempting to iterate `parts` after an unsubscribed
6701
- overflow waits for completion and then propagates the run failure or throws an overflow `Error`
6702
- instead of silently returning truncated parts.
7007
+ iterable without a store. How `streamComplete` is read is stated, never guessed from when
7008
+ `parts` is first touched. By default (`parts: 'iterate'`) `parts` is single-use with a 64-part
7009
+ buffer that backpressures from the first part: iteration may start late — after other awaits —
7010
+ and the run pauses at the full buffer until it does, losing nothing. Awaiting `result` alone in
7011
+ this mode waits while the buffer is full, so a caller that wants only the result says so with
7012
+ `parts: 'ignore'`: no buffer is kept, `result` (and `onPart`) carry the run, and iterating
7013
+ `parts` throws a `TypeError`. `completeText` with `onPart` is the same result-only path.
6703
7014
  - Standalone completions have no durable approval loop, so any tool with `needsApproval: true` (or
6704
7015
  a `needsApproval` predicate returning `true`) is preflighted across every validated call in the
6705
7016
  step and fails closed with `AgentToolApprovalError` (`reason: 'approval-unsupported'`) before any
@@ -6708,11 +7019,22 @@ extraction, classification, a bounded tool loop, or standalone streaming — cal
6708
7019
  `toolDependencies`, `onPredecessorFailure`) on `completeText` / `streamComplete` /
6709
7020
  `completeObject` to enforce the same batch-refusal, cap, and dependency-ordering policies as
6710
7021
  `createAgentRuntime` (durable stream-only `stepBarriers` keys fail fast with a `TypeError`).
6711
- - Pass `retry` (`AgentRetryPolicy`) and optional `onAttemptDiscarded` for stateless retry with
6712
- `Retry-After` handling; exhausting retries throws `AgentRetryExhaustedError` carrying every failed
6713
- attempt, `lastError`, and accumulated billable `usage`.
7022
+ - Pass `retry` (`AgentRetryPolicy`) and optional `onAttemptDiscarded` for stateless retry. As in
7023
+ `createAgentRuntime`, the unit of a retry is the model call of one step: earlier steps and the
7024
+ tools they ran stand, and a call whose stream already carried a provider-executed tool call or
7025
+ a tool result is not repeated. Exhausting retries throws `AgentRetryExhaustedError` carrying every failed attempt, `lastError`,
7026
+ and accumulated billable `usage`. The wait before each retry is exactly what `delayMs` returns:
7027
+ the runtime reads no `Retry-After` itself, so a policy that should honour one returns
7028
+ `failure.retryAfterMs` (the provider's `Retry-After` or `retry-after-ms`, in milliseconds) and
7029
+ bounds the total with `maxRetryDurationMs` — a retry whose wait would cross it is not scheduled.
7030
+ The same policy serves `loop.retry`. Example:
7031
+ [`packages/core/examples/agent-runtime/retry-after-policy.ts`](../../packages/core/examples/agent-runtime/retry-after-policy.ts).
6714
7032
  - Pass `stopPolicies` (`AgentCompleteStopPolicy[]`) and `idleTimeoutMs` to bound multi-step loops
6715
- and stalled streams (suspending the idle timer during local tool execution).
7033
+ and stalled streams (suspending the idle timer during local tool execution). A deadline that
7034
+ fires while your consumer holds a part — a full `streamComplete().parts` buffer nobody reads, a
7035
+ slow `onPart` — still ends the call with a `timeout` `AgentProviderError`, but one without
7036
+ provider origin: `retry` never calls the provider again for it. `idleTimeoutMs`
7037
+ defaults to 60 000, the runtime's default; `null` disables it.
6716
7038
 
6717
7039
  ```ts
6718
7040
  import { z } from 'zod'
@@ -6810,7 +7132,10 @@ const runtime = createAgentRuntime({
6810
7132
  context: runContext.context,
6811
7133
  access: { gate: composeToolLifecycle(authLifecycle, runContext.toolFenceLifecycle) },
6812
7134
  }),
6813
- loop: { prepareStep: deferred.prepareStep(applicationPrepareStep) },
7135
+ loop: {
7136
+ prepareStep: deferred.prepareStep(applicationPrepareStep),
7137
+ repairToolCall: deferred.repairToolCall(applicationRepairToolCall),
7138
+ },
6814
7139
  })
6815
7140
  ```
6816
7141
 
@@ -6829,9 +7154,11 @@ The latest valid same-run search replaces the earlier selection; parallel
6829
7154
  searches in one step merge in call order. Recovery reconstructs it, while a
6830
7155
  different run or finite surface cannot inherit it. Known inactive calls take a
6831
7156
  recoverable `SEARCH_REQUIRED` search round; unknown names still fail. Inactive-call
6832
- repair travels with the tool set returned by `deferred.mount()` — so wrapping
6833
- `deferred.prepareStep()` or calling `completeText` preserves it automatically — and can
6834
- also be composed explicitly with `deferred.repairToolCall(applicationRepairToolCall)`. The
7157
+ repair is the hook `deferred.repairToolCall(applicationRepairToolCall?)` returns, passed as
7158
+ `loop.repairToolCall` (runtime) or `repairToolCall` (`completeText` / `streamComplete`); the
7159
+ application's hook runs first. Nothing is attached to the mounted tools, so spreading them or a
7160
+ tool, or merging two surfaces' mounts, keeps repair exact: two surfaces compose as
7161
+ `first.repairToolCall(second.repairToolCall())`, each repairing only its own catalog. The
6835
7162
  runtime marks that round with `reason: 'inactive_call'` beside the exact tool
6836
7163
  name. The field is the runtime's to write; a model that sets it anyway gets
6837
7164
  the same `SEARCH_REQUIRED` answer with an exact name, and with a query in words
@@ -7315,12 +7642,15 @@ event cannot be rewritten after the fact.
7315
7642
 
7316
7643
  ### Retried provider streams
7317
7644
 
7318
- With `loop.retry` set, a provider stream that fails before any tool call in the
7319
- attempt is retried at the step boundary. Subscribers see `attempt-reset` for the
7320
- run before the next attempt's first delta and drop what the failed attempt
7321
- streamed; the durable draft is checkpointed after that output is discarded; an
7322
- input injected into the failed attempt is taken again by the retry; and the
7323
- failed attempt's reported usage stays in the run's spend. Transient events —
7645
+ With `loop.retry` set, a provider call that fails is repeated — the call of that
7646
+ step, with the request it was prepared with; earlier steps and the tools they ran
7647
+ stand, and `prepareStep` is not run again. A call whose stream already carried a
7648
+ provider-executed tool call or a tool result is not repeated. Subscribers see
7649
+ `attempt-reset` before the repeated call's first delta and drop what the failed
7650
+ call streamed; the durable draft is checkpointed after that output is cut; an
7651
+ input injected into the step stays in the repeated request; and the failed call's
7652
+ reported usage stays in the run's spend. `completeText` / `streamComplete` /
7653
+ `completeObject` repeat the same unit: both entries run one loop of model steps. Transient events —
7324
7654
  deltas, reasoning, `attempt-reset` — are numbered from 1 per run, counting only
7325
7655
  what was published, so a cursor sees no gap on an ordinary stream.
7326
7656
 
@@ -7597,8 +7927,8 @@ conversation of the run it is given.
7597
7927
  For credential-free failure tests, import `createFaultProviderServer` and
7598
7928
  `createReplayAgentProvider` from `stitchkit/agent-runtime/testing`. Runtime
7599
7929
  `loop.retry` applies an explicit `AgentRetryPolicy`: each decision is recorded
7600
- as `retry/scheduled`, each new attempt as `retry/started`, and an attempt that
7601
- has invoked a tool is never automatically replayed. Its `maxAttempts` is a
7930
+ as `retry/scheduled`, each repeated call as `retry/started`, and a tool that has
7931
+ run is never automatically replayed. Its `maxAttempts` is a
7602
7932
  positive safe integer, refused otherwise when the runtime is created and when
7603
7933
  `recordAgentRetryDecision` is given the policy (`TypeError`): `Infinity` would
7604
7934
  retry a paid failure without end, `NaN` or `0` would silently mean never. The
@@ -8137,8 +8467,15 @@ transaction. Drivers without this guarantee must leave the capability absent. Se
8137
8467
 
8138
8468
  A subscriber that switches over `event.type` handles one transient event
8139
8469
  beyond deltas and reasoning: `attempt-reset`, published when `loop.retry`
8140
- starts a new attempt, meaning everything this run streamed before it is
8141
- withdrawn. `reduceAgentControlEvent` does that; a hand-written reducer must,
8470
+ repeats a failed call, meaning what that call streamed is withdrawn. Its
8471
+ `withdrawn: { text, reasoning }` counts the characters of transient text and
8472
+ reasoning the cut call published — the tail of what the run streamed — so a
8473
+ subscriber drops that many from the end and keeps the rest (earlier steps, which
8474
+ stand). Counting from the end also holds for a subscriber that joined mid-run
8475
+ and holds only part of the run's deltas; an event without `withdrawn`
8476
+ withdraws everything the run streamed. It is published after the retry's
8477
+ backoff, together with the durable `retry/started`, so a run stopped during the
8478
+ pause records neither. `reduceAgentControlEvent` does that; a hand-written reducer must,
8142
8479
  or it keeps the failed attempt's partial text on screen.
8143
8480
 
8144
8481
  `publish` receives event classes with different guarantees:
@@ -8263,9 +8600,8 @@ replace the managed tool set or bypass its lifecycle fence.
8263
8600
 
8264
8601
  Override lifetimes in `prepareStep` follow two explicit rules:
8265
8602
 
8266
- - **`instructions` is sticky across the remaining steps of the current attempt**
8267
- (and resets to `initialInstructions` if a provider retry starts a fresh
8268
- attempt). Later steps receive the carried value in `instructions` alongside
8603
+ - **`instructions` is sticky across the remaining steps of the run** (a provider
8604
+ retry repeats the failed call with the instructions it was prepared with). Later steps receive the carried value in `instructions` alongside
8269
8605
  the unchanged `initialInstructions`, so a step can explicitly revert with
8270
8606
  `{ instructions: initialInstructions }`. One-shot `protocol.acceptTerminal`
8271
8607
  continuation instructions apply only to that continuation step and do not
@@ -9801,7 +10137,9 @@ bot.catch(({ error }) => logger.error('Telegram handler failed', { error }))
9801
10137
  const telegram = grammyBotResources({
9802
10138
  bot,
9803
10139
  dependsOn: [database, http], // what handlers need before the first update
9804
- configure: () => bot.api.setMyCommands([{ command: 'start', description: 'Start' }]),
10140
+ configure: async () => {
10141
+ await bot.api.setMyCommands([{ command: 'start', description: 'Start' }])
10142
+ },
9805
10143
  onEnded: ({ error }) => stopProcess(error), // see below
9806
10144
  })
9807
10145
 
@@ -10235,7 +10573,11 @@ reconnect, create the coding profile from the new handle; old tools remain stopp
10235
10573
  host services. `{ allow: [{ origin, headers }] }` retains that isolation and
10236
10574
  allows HTTP through a Unix-socket gateway only. Origins are exact HTTP(S) origins,
10237
10575
  including scheme and port; no wildcard, redirect, arbitrary TCP or CONNECT tunnel
10238
- is allowed. For HTTPS upstreams the **host** establishes TLS. Guests speak HTTP
10576
+ is allowed. An origin must be `https:`; plain `http:` is accepted only for a
10577
+ loopback host (`localhost`, `127.0.0.0/8`, `[::1]`), because the gateway would
10578
+ otherwise send the rule's headers and the guest's request in clear text. A policy
10579
+ naming any other `http:` origin is refused when it is parsed. For HTTPS upstreams
10580
+ the **host** establishes TLS. Guests speak HTTP
10239
10581
  over the socket with the upstream host in `Host`, for example:
10240
10582
 
10241
10583
  ```ts
@@ -10268,6 +10610,17 @@ state storage and other host sockets are not mounted. Each command gets ephemera
10268
10610
  directory belong to the trusted host. See the
10269
10611
  [Bubblewrap security model](https://github.com/containers/bubblewrap#system-security).
10270
10612
 
10613
+ Every Linux launch — this backend, `createProcessSandbox` and its probe — runs
10614
+ Bubblewrap with `--unshare-user --disable-userns`: a sandboxed process cannot
10615
+ create a nested user namespace (`unshare -U` fails with `ENOSPC`), so it cannot
10616
+ regain capabilities there and remount its view of the filesystem. Software that
10617
+ needs its own user namespace inside the sandbox — a nested `bwrap`, a browser's
10618
+ namespace sandbox — does not run there. On a host where Bubblewrap cannot create
10619
+ a user namespace, or with a setuid `bwrap`, which does not support
10620
+ `--disable-userns`, `probeProcessSandbox` reports the sandbox unavailable
10621
+ (`createProcessSandbox` refuses with `SANDBOX_UNAVAILABLE`) and backend commands
10622
+ fail at launch; neither falls back to a sandbox without the lock.
10623
+
10271
10624
  This is namespace isolation over the host kernel, not a VM. It does not impose
10272
10625
  memory, CPU, disk or process-count quotas. A host running mutually untrusted workloads
10273
10626
  must supply those bounds outside the namespace (for example, a delegated cgroup and
@@ -10317,19 +10670,43 @@ const driver = createCodexDriver({ wrapCommand: sandbox.wrapCommand });
10317
10670
  the platform is unsupported; there is no unsandboxed fallback.
10318
10671
  - **Symlink-safe `workspace-readonly` and `denyPaths`:** `ProcessSandboxSpecSchema` resolves
10319
10672
  symlinks via `realpathSync` so none of `writableDirs`, `privateTmpDir`, or `homeDir` can overlap
10320
- `workspace` through a symlink. Both Linux Bubblewrap and macOS Seatbelt resolve symlinks for
10321
- `denyPaths`: Linux maps each resolved target onto every host-backed mount (including symlinked
10322
- mounts, symlinked directories masked with `tmpfs`, and ancestor directories that cover descendant
10323
- mounts) and fails closed with `SandboxError('SANDBOX_UNAVAILABLE', ...)` on broken/dangling
10324
- symlinks or unresolvable symlink loops (`ELOOP`), while macOS emits deny rules for both the
10325
- lexical path and the symlink-resolved path (or deepest existing ancestor).
10673
+ `workspace` through a symlink. Both Linux Bubblewrap and macOS Seatbelt resolve every path the
10674
+ same way: through symlinks, or — only for an entry that does not exist yet — through its deepest
10675
+ existing ancestor. A path that exists but cannot be resolved — a dangling symlink, a symlink loop
10676
+ (`ELOOP`), a path through a regular file (`ENOTDIR`) or an unreadable directory (`EACCES`) —
10677
+ fails closed with `SandboxError('SANDBOX_UNAVAILABLE', ...)` naming the path and the error code
10678
+ on both platforms, rather than being matched by its spelling. Linux then compares each resolved
10679
+ `denyPaths` target with every host-backed mount, including symlinked mounts, while macOS emits
10680
+ deny rules for both the lexical path and the resolved path. On Linux the mount sources resolve
10681
+ the same way when `denyPaths` are planned, because Bubblewrap follows a source when it starts:
10682
+ an explicit mount through a dangling symlink or a regular file is refused, and a default
10683
+ optional system mount (`/lib64`, `/etc/ssl`, `/etc/resolv.conf`, ...) that is absent or a
10684
+ dangling symlink at plan time is planned as the path it would bind, so a covering deny masks it
10685
+ even if it appears before start.
10686
+ - **What a Linux deny guarantees, and what it refuses:** a Bubblewrap mask is a mount, and a mount
10687
+ sits on a directory entry. On a host directory that entry is replaced when the host renames a
10688
+ file over it (the usual atomic update of a token or `.env`) and does not exist for a file created
10689
+ after start, so a mask there would stop hiding the path while the sandboxed process keeps running.
10690
+ Linux therefore accepts only denies it can hold for the process's whole lifetime:
10691
+ - a deny that equals or contains a host-backed mount (`workspace`, `readOnlyPaths`,
10692
+ `writableDirs`, `privateTmpDir`, a `unixSockets` entry, a system root) replaces that mount with
10693
+ an empty `tmpfs` (directories) or `/dev/null` (files and sockets) — the host path is never
10694
+ bound, so renames and new files under it stay invisible;
10695
+ - a deny outside every mount needs no mask: nothing outside the mounts exists in the sandbox,
10696
+ including files created there later;
10697
+ - a deny strictly inside a mounted host directory — present at start or not — is refused with
10698
+ `SANDBOX_UNAVAILABLE` naming the path and the mount. Keep such secrets out of mounted trees
10699
+ (for example outside the workspace) or deny the whole mounted path.
10700
+
10701
+ macOS Seatbelt matches `denyPaths` by path on every access, so a path inside the workspace stays
10702
+ denied across renames and later creation there; that placement is accepted on macOS and refused
10703
+ on Linux.
10326
10704
  - **Platform read/write and IPC models differ:**
10327
10705
  - **Linux (`bwrap`):** mount-namespace allowlist — only mounted system roots, `workspace`,
10328
10706
  `readOnlyPaths`, `writableDirs`, `privateTmpDir`, `homeDir`, and `unixSockets` exist inside the
10329
- sandbox; unmounted host paths are absent, and `denyPaths` resolving into or above any
10330
- host-backed mount (including `/bin` and `/sbin`) are masked over `/dev/null` (for files and
10331
- sockets) or an empty `tmpfs` (for directories), while an isolated `tmpfs` `homeDir` is not
10332
- treated as host-backed. A `cwd` outside mounted roots (such as `driver.info()` /
10707
+ sandbox; unmounted host paths are absent, and `denyPaths` equal to or above a host-backed
10708
+ mount replace it as described above, while an isolated `tmpfs` `homeDir` is not treated as
10709
+ host-backed. A `cwd` outside mounted roots (such as `driver.info()` /
10333
10710
  `driver.status()`) falls back to `workspace`.
10334
10711
  - **macOS (`sandbox-exec` Seatbelt, compiled by `buildSeatbeltProfile`):** default-deny writes
10335
10712
  with default-allow reads — writes are denied globally except `privateTmpDir`, `workspace`
@@ -15459,7 +15836,9 @@ never runs.
15459
15836
  - **It does not gate operations.** "Only from this machine" is a property of an
15460
15837
  operation, and an operation is known after routing, not before it. Write it as
15461
15838
  an auth rule over `ctx.ipAddress` — `isLoopbackAddress` is exported for
15462
- exactly that — where it composes with your other rules.
15839
+ exactly that — where it composes with your other rules. Behind a proxy on the
15840
+ same host every peer is loopback: resolve the visitor with `trustProxy` first
15841
+ ([server guide](./server.md#client-ip-behind-a-proxy)).
15463
15842
  - **It does not re-check an open connection.** Both lanes check at admission.
15464
15843
  - **It does not see an `OPTIONS` preflight** when `cors` is configured; that is
15465
15844
  answered earlier. The preflight carries no operation and no body, and the
@@ -15780,7 +16159,11 @@ Use it as `createMcpHandler`'s `auth`, or inside `createAuthHook`'s `resolve`.
15780
16159
 
15781
16160
  `verifyJwt(token, secret)` verifies an HS256 JWT and returns its payload, or
15782
16161
  throws `unauthorized`. It pins the algorithm (the token's own `alg` can never
15783
- pick the scheme), and checks `exp` and `nbf`.
16162
+ pick the scheme), checks `exp` and `nbf`, and **requires `exp`**: a token
16163
+ without one would stay valid for as long as the secret does. Pass
16164
+ `expiration: 'optional'` only for tokens whose lifetime you bound elsewhere (a
16165
+ session row, a revocation list); a present `exp` is still enforced. Sign with
16166
+ `signJwt(payload, secret, { expiresInSec })`.
15784
16167
 
15785
16168
  ```ts
15786
16169
  import { verifyJwt, extractToken } from 'stitchkit/server'
@@ -15847,7 +16230,7 @@ import { env } from './env'
15847
16230
  const result = await verifyTelegramInitData({
15848
16231
  initData,
15849
16232
  botToken: env.BOT_TOKEN,
15850
- maxAgeSeconds: 3600, // a signed string is otherwise valid forever
16233
+ maxAgeSeconds: 3600, // default: one day
15851
16234
  })
15852
16235
  if (!result.valid) {
15853
16236
  // 'missing-hash' | 'signature-mismatch' | 'malformed' | 'expired'
@@ -15870,9 +16253,10 @@ A bot meets the same person as grammY's `ctx.from`, in Telegram's `snake_case`;
15870
16253
  `parseTelegramUser(ctx.from)` gives the same `TelegramUser`, so one
15871
16254
  `ensureAccount(user)` serves the Mini App and the chat.
15872
16255
 
15873
- `maxAgeSeconds` is optional and there is no default: only the application knows
15874
- how long its own session is worth. Omitting it means the string never expires,
15875
- which is a decision rather than an oversight.
16256
+ `maxAgeSeconds` defaults to one day (`86400`): a signed string is otherwise a
16257
+ credential that never expires, so there is no unbounded mode. Set the lifetime
16258
+ your session is worth — shorter for a sign-in exchange, longer for a Mini App
16259
+ kept open for days.
15876
16260
 
15877
16261
  The module is server-only and pulls in no bot library — the token never belongs
15878
16262
  in a browser bundle. `stitchkit/application/grammy` remains the lifecycle
@@ -16335,21 +16719,28 @@ const onError = createErrorHook({
16335
16719
  Synchronous callbacks and renderers that declare fewer parameters continue to
16336
16720
  work normally.
16337
16721
 
16338
- Invalid input (a `ZodError`) is classified as `VALIDATION_ERROR` 400 before it
16339
- reaches `render` — a client fault is an honest 400, not a 500 — and the
16722
+ Input that fails the contract's `params` / `input` schema reaches `render` as
16723
+ `VALIDATION_ERROR` 400 — a client fault is an honest 400, not a 500 — and the
16340
16724
  offending fields arrive as structured `info.details.issues`, so your `render`
16341
16725
  can surface them to a machine client without parsing the message.
16342
16726
 
16727
+ Only the contract boundary produces `VALIDATION_ERROR`. A `ZodError` your
16728
+ handler throws — parsing an upstream answer, a database row, a config value —
16729
+ is the server's own schema failing: it is answered as `INTERNAL_SERVER_ERROR`
16730
+ 500 with the generic message, and the `ZodError` text goes to the log and the
16731
+ audit row, never to the caller. To refuse the caller's input from inside a
16732
+ handler, throw `badRequest(message, details)` (or an `AppError`) yourself.
16733
+
16343
16734
  If you write a **bespoke** `onError` instead of using `createErrorHook`, run the
16344
- thrown value through the exported `normalizeError` to get the same classification
16345
- (a raw `ZodError` reaches your hook untouched, so the framework can inspect it —
16346
- call `zodIssues(err)` yourself if you want the structured fields):
16735
+ thrown value through the exported `normalizeError` to get the same classification.
16736
+ Invalid input reaches your hook as an `AppError` with code `VALIDATION_ERROR`,
16737
+ its `details.issues` and the `ZodError` as `cause`:
16347
16738
 
16348
16739
  ```ts
16349
16740
  import { normalizeError } from 'stitchkit/server'
16350
16741
 
16351
16742
  onError: (ctx, err) => {
16352
- const e = normalizeError(err) // ZodError → VALIDATION_ERROR 400, else generic 500
16743
+ const e = normalizeError(err) // AppError as is (VALIDATION_ERROR 400 for input), else generic 500
16353
16744
  return jsonError(e.code, e.status, e.message)
16354
16745
  }
16355
16746
  ```
@@ -17057,18 +17448,25 @@ each request.
17057
17448
  A payload goes into an audit row only after `sanitizePayload`:
17058
17449
 
17059
17450
  - **secret-named keys are masked** — a key whose words include a secret term is
17060
- redacted (`password`, `sessionToken`, `X-Api-Key`, `authorization`, `cookie`,
17061
- …), while identifiers that merely contain one (`authorId`, `sessionCount`,
17062
- `tokenizer`) survive. This applies wherever a key exists — an object field and
17451
+ redacted (`password`, `passphrase`, `sessionToken`, `X-Api-Key`, `accessKey`,
17452
+ `authorization`, `cookie`, …), a key written as one lowercase run that ends in
17453
+ one (`newpassword`, `accesstoken`), and a key that ENDS in `auth`, `signature`,
17454
+ `jwt`, `otp`, `pin` or `dsn` (`basicAuth`, `webhookSignature`, `SENTRY_DSN`),
17455
+ while identifiers that merely contain one (`authorId`, `sessionCount`,
17456
+ `tokenizer`, `pinned`) or only describe it (`signatureVersion`, `auth_date`,
17457
+ a model token count such as `maxTokens` or `usage.total_tokens`)
17458
+ survive. This applies wherever a key exists — an object field and
17063
17459
  a `Map` entry alike, at any depth. A `Set` member has no key, so nothing there
17064
17460
  is masked by name;
17065
17461
  - **secrets are masked by their shape** in every string, whatever key holds
17066
17462
  it — the secret half of a Telegram bot token (`123456:[redacted]`: the bot's
17067
17463
  id stays, it tells two bots apart), the password in
17068
- `postgresql://user:password@host` (user, host and path stay), and the value
17069
- of a query parameter named as a secret (`?access_token=`, `?api-key=`,
17070
- `?key=`, `?sig=`). A URL in an error message or a request log line is the
17071
- usual way a token reaches a journal;
17464
+ `postgresql://user:password@host` (user, host and path stay), the user of an
17465
+ `http(s)` / `ws(s)` address with no password (a Sentry DSN's key — a database
17466
+ or SSH user stays), the credential after `Bearer`, a provider key (`sk-…`, `or-v1-…`, `AIza…`), a
17467
+ JSON Web Token (`eyJ….eyJ….…`), and the value of a query parameter named as a
17468
+ secret (`?access_token=`, `?api-key=`, `?key=`, `?sig=`). A URL in an error
17469
+ message or a request log line is the usual way a token reaches a journal;
17072
17470
  - **an error keeps what it says about itself** — its own fields (`error_code`,
17073
17471
  `parameters`, a provider's `status`) are written beside `name`, `message`,
17074
17472
  `stack` and `cause`, masked by the same rules; a field holding a class
@@ -17247,8 +17645,8 @@ use; future optional fields do not change callback arity.
17247
17645
 
17248
17646
  `createObservability({ tools })` uses it already. Where the envelope was scrubbed to
17249
17647
  `INTERNAL_SERVER_ERROR`, the row's `errorMessage` becomes the real message
17250
- instead of the placeholder; a truthful envelope (a thrown `AppError`, a
17251
- `ZodError`) is left alone, `errorCode` and `errorDetail` are untouched, and the
17648
+ instead of the placeholder (a `ZodError` from handler code is one of these); a
17649
+ truthful envelope (a thrown `AppError`, invalid input) is left alone, `errorCode` and `errorDetail` are untouched, and the
17252
17650
  stack is not written — that is `onToolError`'s job, for a tracker that wants it.
17253
17651
  The caller still receives the scrubbed envelope in every case: the raw text
17254
17652
  reaches your server-side record, never the response. → ADR 0042
@@ -17471,6 +17869,7 @@ test('every model call goes through the spend gateway', async () => {
17471
17869
  module: 'stitchkit/agent-runtime/openrouter',
17472
17870
  symbols: [
17473
17871
  'openRouterProvider',
17872
+ 'createOpenRouterClient',
17474
17873
  'openRouterRequestJson',
17475
17874
  'openRouterRequestStream',
17476
17875
  'openRouterSystemOne',
@@ -19653,10 +20052,10 @@ local Bot API server, and it uses no proxy: where the network needs one, keep `f
19653
20052
  ## Widgets
19654
20053
 
19655
20054
  A widget (Bot API 10.4) is HTML that the Telegram app runs and draws inside a message, with data
19656
- of its own the bot changes and queries it sends to the bot. grammY 1.46 does not type the three
19657
- methods, and a bot that reaches for them tends to build a second client and with it a second
19658
- limiter. `telegramWidgetApi` takes the client the bot already has and calls the methods through
19659
- its `api.raw`, so the client's transformers — the outbound budget among them — run every call:
20055
+ of its own the bot changes and queries it sends to the bot. `telegramWidgetApi` takes the client
20056
+ the bot already has and calls the five widget methods through its `api.raw`, so the client's
20057
+ transformers — the outbound budget among them — run every call and no second client, with a
20058
+ second limiter, is built for them:
19660
20059
 
19661
20060
  ```ts
19662
20061
  import { telegramOutboundBudget } from 'stitchkit/telegram'
@@ -19676,8 +20075,10 @@ await widgets.editMessageWidgetData(
19676
20075
  await widgets.answerWidgetQuery({ widget_query_id: query.id, data: answer }, { signal })
19677
20076
  ```
19678
20077
 
19679
- The parameters are the Bot API's, by their Bot API names, so the call reads as the grammY call it
19680
- becomes once grammY types the method. A field is sent when it is not `undefined`: `chat_data: ''`
20078
+ The parameters are the Bot API's, by their Bot API names, so the call reads as the grammY call.
20079
+ Their types are written in this package rather than taken from grammY: the supported range starts at
20080
+ grammY 1.46, which types no widget method (1.48 types them all), and a type test holds each
20081
+ parameter type to the installed grammY's own field for field. A field is sent when it is not `undefined`: `chat_data: ''`
19681
20082
  reaches Telegram and removes the data, an omitted field keeps it. An edit names `chat_id` with
19682
20083
  `message_id`, or `inline_message_id`, and changes `chat_data`, `public_data` or both.
19683
20084
 
@@ -19704,15 +20105,38 @@ reaches Telegram and removes the data, an omitted field keeps it. An edit names
19704
20105
  returns — `true` where a message was due, as a grammY webhook reply gives — is an error with the
19705
20106
  parse failure as its `cause`: the request was sent and its outcome is unknown.
19706
20107
  - **Queries are answered at intake.** `widget_query` must be in the webhook's or polling's
19707
- `allowed_updates`; grammY's `Update` type does not name it yet, so read
20108
+ `allowed_updates`; grammY 1.46's `Update` type does not name it, so read
19708
20109
  `update.widget_query` with `parseTelegramWidgetQuery`. It returns `{ query }`, or `{ id, error }`
19709
20110
  for a query that does not parse — an unknown `type` or data outside 1–64 bytes — whose id is
19710
20111
  enough to answer it with a refusal rather than leave the widget waiting, or `undefined` without
19711
20112
  an id. Telegram's message, chat and query objects are parsed loosely: fields it adds later pass
19712
20113
  through.
19713
- - **Shared widgets are not here.** `is_shared`, `sendSharedWidget`, `editSharedWidgetData` and
19714
- `shared_widget_query` are outside this API; in production Telegram sends widgets to private
19715
- chats only.
20114
+
20115
+ ### Shared widgets
20116
+
20117
+ A shared widget is one widget shown by many messages with one `public_data`. `sendWidget` with
20118
+ `is_shared: true` creates it, and the message it returns carries its id in `widget.id`, typed as a
20119
+ `string` — an answer without one is an error whose outcome is unknown. `sendSharedWidget` sends the same widget to
20120
+ another chat; `editSharedWidgetData` changes the public data of every message with it at once:
20121
+
20122
+ ```ts
20123
+ const first = await widgets.sendWidget({ chat_id, html, public_data: board, is_shared: true })
20124
+ const widget_id = first.widget.id
20125
+ await widgets.sendSharedWidget({ chat_id: other, widget_id, chat_data: seat })
20126
+ await widgets.editSharedWidgetData({ widget_id, public_data: next, cache_time: 10 })
20127
+ ```
20128
+
20129
+ - **A shared send costs one message; a shared data edit costs none.** `sendSharedWidget` waits for
20130
+ the token's schedule like any send. `editSharedWidgetData` changes no message, so it waits for no
20131
+ slot; Telegram limits it to one edit per second per widget, which is the caller's to keep.
20132
+ `public_data: ''` removes the data; `cache_time` (5–3600 s, 30 by default) is how long an app may
20133
+ keep the old data.
20134
+ - **A forwarded shared widget asks through `shared_widget_query`.** Add it to `allowed_updates` and
20135
+ read it with `parseTelegramSharedWidgetQuery`: `{ query }` with the `widget_id`, no chat and no
20136
+ message, `{ id, error }` for one that does not parse, or `undefined` without an id. Answer it with
20137
+ `answerWidgetQuery` like any other query. A query from a shared widget in a message the bot sent
20138
+ arrives as an ordinary `widget_query` with `widget_id` set.
20139
+ - In production Telegram sends widgets to private chats only, and their content is protected.
19716
20140
 
19717
20141
  The installed
19718
20142
  [`telegram-widget-api.mjs`](../../packages/core/scripts/consumer-lane/fixtures/minimal/src/telegram-widget-api.mjs)
@@ -20679,6 +21103,340 @@ charts, no merged cells and no streaming: an application that needs them takes a
20679
21103
 
20680
21104
  # Upgrading stitchkit
20681
21105
 
21106
+ ## Released migration: 0.136.0
21107
+
21108
+ ### trusted-proxy-chain
21109
+
21110
+ **Who must act:** applications passing `trustProxy` to `createServer`, `createHandler`, `serveNode`, `wrapInRequestContext`, `extractIp` or `getClientInfo`.
21111
+
21112
+ `trustProxy: true` believed the leftmost `x-forwarded-for` entry, which the client writes, so any visitor could claim `127.0.0.1` and pass a loopback rule. `trustProxy` now names the proxies you run; the client IP is read from the right, past every trusted proxy, and only when the socket peer is one of them:
21113
+
21114
+ ```ts
21115
+ // Before
21116
+ createServer({ trustProxy: true, services })
21117
+
21118
+ // After — nginx on this host appends with $proxy_add_x_forwarded_for
21119
+ import { isLoopbackAddress } from 'stitchkit/server'
21120
+ createServer({ trustProxy: { trustedPeer: isLoopbackAddress }, services })
21121
+ ```
21122
+
21123
+ For proxies on an internal network, pass a predicate over their addresses (`(address) => address.startsWith('10.0.')`, or a CIDR check). The proxy must append to `X-Forwarded-For`; `x-real-ip` is no longer read.
21124
+
21125
+ Inside a handler, read `ctx.ipAddress` — the framework already resolved it with the server's policy. Outside one, `extractIp` / `getClientInfo` need the real peer; without `socketIp` the header is ignored and the address is `''`:
21126
+
21127
+ ```ts
21128
+ // Before
21129
+ getClientInfo(req, { trustProxy: true })
21130
+
21131
+ // After
21132
+ getClientInfo(req, { trustProxy: { trustedPeer: isLoopbackAddress }, socketIp: resolveSocketIp(req, server) })
21133
+ ```
21134
+
21135
+ `wrapInRequestContext(fetch, { trustProxy: { trustedPeer } })` takes the same policy.
21136
+
21137
+ ### json-body-default-limit
21138
+
21139
+ **Who must act:** applications whose endpoints accept JSON request bodies larger than 1 MiB without setting `maxJsonBodyBytes`.
21140
+
21141
+ An unset `maxJsonBodyBytes` used to mean "read the whole body", which let any client make the server buffer a body of its chosen size. It now means 1 MiB; a larger body is a `400 BAD_REQUEST` before the handler runs. Declare the size an endpoint really accepts:
21142
+
21143
+ ```ts
21144
+ // Before: no limit, any size accepted
21145
+ importItems: { method: 'POST', path: '/import', desc: 'Import items', input: ImportSchema, output: ResultSchema }
21146
+
21147
+ // After: the endpoint names its ceiling (or set it once on createServer / createHandler)
21148
+ importItems: { method: 'POST', path: '/import', desc: 'Import items', input: ImportSchema, output: ResultSchema, maxJsonBodyBytes: 8 * 1024 * 1024 }
21149
+ ```
21150
+
21151
+ A route value wins over the handler value. Uploads belong in `multipart`, which has its own per-file limits.
21152
+
21153
+ ### validation-error-is-input-only
21154
+
21155
+ **Who must act:** applications whose handlers throw a `ZodError` to refuse the caller's input, and applications whose own `onError` checks `instanceof ZodError`.
21156
+
21157
+ `VALIDATION_ERROR` 400 now comes only from the contract boundary — the endpoint's `params`, `input` and multipart fields. A `ZodError` thrown by handler code is answered as `INTERNAL_SERVER_ERROR` 500, because it is usually the server's own schema failing on an upstream answer or a stored row, and its paths are internal. To refuse the caller from inside a handler, say so:
21158
+
21159
+ ```ts
21160
+ // Before: a ZodError thrown here became a 400
21161
+ const extra = ExtraSchema.parse(input.extra)
21162
+
21163
+ // After
21164
+ const parsed = ExtraSchema.safeParse(input.extra)
21165
+ if (!parsed.success) badRequest('extra is invalid', { issues: zodIssues(parsed.error) })
21166
+ ```
21167
+
21168
+ A bespoke `onError` receives invalid input as an `AppError`, with the `ZodError` as `cause`:
21169
+
21170
+ ```ts
21171
+ // Before
21172
+ if (error instanceof ZodError) return validationFailed(zodIssues(error))
21173
+
21174
+ // After
21175
+ if (AppError.is(error) && error.code === 'VALIDATION_ERROR') return validationFailed(error.details?.issues)
21176
+ ```
21177
+
21178
+ ### safe-auth-defaults
21179
+
21180
+ **Who must act:** applications serving files whose names start with a dot through `staticRoute`, verifying JWTs that carry no `exp` with `verifyJwt`, or calling `verifyTelegramInitData` without `maxAgeSeconds` and accepting strings older than a day.
21181
+
21182
+ Three defaults stopped trusting what nobody bounded:
21183
+
21184
+ ```ts
21185
+ // staticRoute: dot segments answer 404 — name the ones you publish
21186
+ staticRoute('/', './public', { allowedDotNames: ['.well-known'] })
21187
+
21188
+ // verifyJwt: a token must carry exp — sign with a lifetime…
21189
+ await signJwt(claims, secret, { expiresInSec: 3600 })
21190
+ // …or accept a token whose lifetime you bound elsewhere
21191
+ await verifyJwt(token, secret, { expiration: 'optional' })
21192
+
21193
+ // verifyTelegramInitData: one day unless you say otherwise
21194
+ await verifyTelegramInitData({ initData, botToken, maxAgeSeconds: 7 * 86_400 })
21195
+ ```
21196
+
21197
+ There is no unbounded `maxAgeSeconds`: pass the longest lifetime your Mini App session needs.
21198
+
21199
+ ### react-query-floor
21200
+
21201
+ **Who must act:** applications importing `stitchkit/react` with `@tanstack/react-query` older than 5.103.0.
21202
+
21203
+ `stitchkit/react` needs `environmentManager` (exported by `@tanstack/react-query` from 5.91.0) and `MutationCacheConfig` (from 5.103.0); the declared `>=5` admitted versions on which the entry did not load. Raise the dependency:
21204
+
21205
+ ```sh
21206
+ bun add @tanstack/react-query@^5.103.0
21207
+ ```
21208
+
21209
+ ### openrouter-tts-formats
21210
+
21211
+ **Who must act:** applications passing `responseFormat: 'opus'`, `'aac'` or `'flac'` to `openRouterAudioSpeech` in `stitchkit/agent-runtime/openrouter`.
21212
+
21213
+ OpenRouter's `POST /audio/speech` accepts `mp3`, `pcm` (its default) and `wav` (Gemini TTS only); the other formats were typed but answered with a 400. `OpenRouterSpeechFormat` is now `'mp3' | 'pcm' | 'wav'`, and `openRouterAudioSpeech` refuses anything else before the request:
21214
+
21215
+ ```ts
21216
+ // Before (typed, rejected by OpenRouter)
21217
+ await openRouterAudioSpeech({ model, input, voice, responseFormat: 'flac' });
21218
+
21219
+ // After
21220
+ await openRouterAudioSpeech({ model, input, voice, responseFormat: 'mp3' });
21221
+ ```
21222
+
21223
+ ### openrouter-stt-integer-speaker
21224
+
21225
+ **Who must act:** applications reading diarized `segments` / `words` from `openRouterAudioTranscription` in `stitchkit/agent-runtime/openrouter`.
21226
+
21227
+ OpenRouter returns a diarized speaker as a zero-based integer `speaker` plus an optional `speaker_label`. `openRouterAudioTranscription` now parses that shape and returns `segments` / `words` as typed projections (`OpenRouterTranscriptionSegment`, `OpenRouterTranscriptionWord`); the full wire objects stay on `raw`:
21228
+
21229
+ ```ts
21230
+ // Before (string speaker, wire objects with snake_case extras)
21231
+ const who: string | undefined = result.words?.[0]?.speaker;
21232
+ const logprob = result.segments?.[0]?.avg_logprob;
21233
+
21234
+ // After (integer index, provider label, wire extras on raw)
21235
+ const who: number | undefined = result.words?.[0]?.speaker;
21236
+ const label: string | undefined = result.words?.[0]?.speakerLabel;
21237
+ const logprob = result.raw.segments?.[0]?.avg_logprob;
21238
+ ```
21239
+
21240
+ ### openrouter-base-url-rule
21241
+
21242
+ **Who must act:** applications whose OpenRouter `baseUrl` uses plain `http:` to a non-loopback host, names the `/chat/completions` endpoint instead of the API root, or carries credentials, a query string or a fragment, in `stitchkit/agent-runtime/openrouter`; tests that derive a provider `baseUrl` from `createFaultProviderServer().url` in `stitchkit/agent-runtime/testing`.
21243
+
21244
+ Every OpenRouter path — `openRouterProvider`, the catalog and its cache, the spend helpers and the non-chat clients — now applies one rule: `https:`, or `http:` only to `localhost`, `127.0.0.0/8` or `[::1]`; no `user:pass@`, `?…` or `#…`. Move a gateway behind TLS (or onto loopback), and send what the query carried as a header:
21245
+
21246
+ ```ts
21247
+ // Before (key in clear text to a remote host; the query rode along on every request)
21248
+ openRouterProvider({ apiKey, baseUrl: 'http://gateway.internal/api/v1?team=a' });
21249
+
21250
+ // After
21251
+ openRouterProvider({
21252
+ apiKey,
21253
+ baseUrl: 'https://gateway.internal/api/v1',
21254
+ headers: { 'x-team': 'a' },
21255
+ });
21256
+ ```
21257
+
21258
+ `baseUrl` is the API root: every path appends its own endpoint (`/chat/completions`, `/models`, `/audio/speech`, …), so a `baseUrl` ending in `/chat/completions` is refused with a `TypeError` when the provider or client is created. Pass the root:
21259
+
21260
+ ```ts
21261
+ // Before
21262
+ openRouterProvider({ apiKey, baseUrl: 'https://openrouter.ai/api/v1/chat/completions' });
21263
+
21264
+ // After
21265
+ openRouterProvider({ apiKey, baseUrl: 'https://openrouter.ai/api/v1' });
21266
+ ```
21267
+
21268
+ `createFaultProviderServer()` from `stitchkit/agent-runtime/testing` now answers `url` as that root (`http://127.0.0.1:<port>/v1`) instead of the `/v1/chat/completions` endpoint. Pass it to any provider as is; drop a path you derived from it:
21269
+
21270
+ ```ts
21271
+ // Before
21272
+ anthropicProvider({ apiKey: 'test-key', baseUrl: new URL('/v1', server.url).toString() });
21273
+
21274
+ // After
21275
+ anthropicProvider({ apiKey: 'test-key', baseUrl: server.url });
21276
+ ```
21277
+
21278
+ ### openrouter-one-transport
21279
+
21280
+ **Who must act:** applications that catch `OpenRouterHttpError`, type a fetch as `OpenRouterCatalogFetch`, read the request URL in a custom `OpenRouterFetch` as a string, catch the catalog's `RangeError` for an oversized body, or pass `fetcher` to `openRouterModelCatalog`, `loadOpenRouterCatalogSnapshot`, `fetchOpenRouterModelEndpoints`, `createOpenRouterCatalogCache` or `createOpenRouterSpendReconciler`, in `stitchkit/agent-runtime/openrouter`.
21281
+
21282
+ Chat, catalog, spend and non-chat clients share one transport and one error class. Check the status on `AgentProviderError`, use `OpenRouterFetch` everywhere, read its first argument as a `URL`, and pass it as `fetch` (the catalog, snapshot, cache and spend reconciler called it `fetcher`):
21283
+
21284
+ ```ts
21285
+ // Before
21286
+ import { OpenRouterHttpError, type OpenRouterCatalogFetch } from 'stitchkit/agent-runtime/openrouter';
21287
+ if (error instanceof OpenRouterHttpError && error.status === 404) return undefined;
21288
+ const fetcher: OpenRouterCatalogFetch = (url) => fetch(url);
21289
+ const custom: OpenRouterFetch = (input) => fetch((input as string).replace('/v1', '/v1beta'));
21290
+ await loadOpenRouterCatalogSnapshot({ apiKey, fetcher });
21291
+
21292
+ // After
21293
+ import { AgentProviderError } from 'stitchkit/agent-runtime';
21294
+ import type { OpenRouterFetch } from 'stitchkit/agent-runtime/openrouter';
21295
+ if (error instanceof AgentProviderError && error.statusCode === 404) return undefined;
21296
+ const fetcher: OpenRouterFetch = (url) => fetch(url);
21297
+ const custom: OpenRouterFetch = (url) => fetch(url.href.replace('/v1', '/v1beta'));
21298
+ await loadOpenRouterCatalogSnapshot({ apiKey, fetch: fetcher });
21299
+ ```
21300
+
21301
+ ### deferred-tools-explicit-repair
21302
+
21303
+ **Who must act:** applications using `createDeferredAgentToolSurface` from `stitchkit/agent-runtime` that relied on inactive-call repair without passing `repairToolCall`.
21304
+
21305
+ The repair used to ride on the mounted tool set as a hidden property, which a spread of the search tool lost and which, across two merged mounts, always resolved to the first surface. It is now only the hook the controller returns; pass it where the loop takes `repairToolCall`. Without it, a call to a known but inactive tool fails like an unknown one instead of taking the `SEARCH_REQUIRED` round:
21306
+
21307
+ ```ts
21308
+ // Before (repair found on the mounted tools)
21309
+ createAgentRuntime({
21310
+ tools: (runContext) => deferred.mount(runContext, mountConfig),
21311
+ loop: { prepareStep: deferred.prepareStep() },
21312
+ });
21313
+ await completeText({ driver, prompt, tools });
21314
+
21315
+ // After
21316
+ createAgentRuntime({
21317
+ tools: (runContext) => deferred.mount(runContext, mountConfig),
21318
+ loop: { prepareStep: deferred.prepareStep(), repairToolCall: deferred.repairToolCall() },
21319
+ });
21320
+ await completeText({ driver, prompt, tools, repairToolCall: deferred.repairToolCall() });
21321
+
21322
+ // Two surfaces, the application's hook first
21323
+ const repairToolCall = first.repairToolCall(second.repairToolCall(applicationRepairToolCall));
21324
+ ```
21325
+
21326
+ ### linux-deny-paths-inside-mounts
21327
+
21328
+ **Who must act:** Linux applications whose `createProcessSandbox` `denyPaths` name a path strictly inside a mounted directory (the workspace, `readOnlyPaths`, `writableDirs`, `privateTmpDir` or a system root such as `/usr`), in `stitchkit/agent-runtime/sandbox`.
21329
+
21330
+ Such a deny now fails `wrapCommand` with `SandboxError('SANDBOX_UNAVAILABLE')` naming the path and the mount: Bubblewrap could hide it only until the host renamed a file over it or created it after start. Move the secret out of every mounted tree, or deny a whole mounted path:
21331
+
21332
+ ```ts
21333
+ // Before (the mask was lost after an atomic rewrite of /srv/ws/.env on the host)
21334
+ createProcessSandbox({ profile: 'workspace-strict', workspace: '/srv/ws', denyPaths: ['/srv/ws/.env'] });
21335
+
21336
+ // After: the secret lives outside the mounted workspace, where nothing is visible
21337
+ createProcessSandbox({ profile: 'workspace-strict', workspace: '/srv/ws', denyPaths: ['/srv/secrets/.env'] });
21338
+
21339
+ // Or: deny the whole mounted directory, which is then replaced by an empty tmpfs
21340
+ createProcessSandbox({
21341
+ profile: 'workspace-strict',
21342
+ workspace: '/srv/ws',
21343
+ readOnlyPaths: ['/srv/shared'],
21344
+ denyPaths: ['/srv/shared'],
21345
+ });
21346
+ ```
21347
+
21348
+ macOS Seatbelt matches `denyPaths` by path and keeps accepting paths inside the workspace.
21349
+
21350
+ ### sandbox-gateway-https-origins
21351
+
21352
+ **Who must act:** applications whose sandbox network policy (`createBubblewrapSandboxBackend` `create({ network })`, `setNetworkPolicy`, `createSandboxSession`) allows a plain-`http:` origin on a host other than `localhost`, `127.0.0.0/8` or `[::1]`, in `stitchkit/agent-runtime/sandbox`.
21353
+
21354
+ Such a policy is now refused when it is parsed (a `ZodError` at `allow[i].origin`): the gateway would send the rule's headers and the guest's request in clear text. Point the rule at the upstream's `https:` origin; guests keep speaking HTTP to the gateway socket, and the host establishes TLS:
21355
+
21356
+ ```ts
21357
+ // Before
21358
+ await handle.session.setNetworkPolicy({
21359
+ allow: [{ origin: 'http://api.internal', headers: { authorization: hostCredential } }],
21360
+ });
21361
+
21362
+ // After
21363
+ await handle.session.setNetworkPolicy({
21364
+ allow: [{ origin: 'https://api.internal', headers: { authorization: hostCredential } }],
21365
+ });
21366
+ ```
21367
+
21368
+ An upstream without TLS stays reachable only through a loopback origin on the host (for example a local TLS-terminating proxy at `http://127.0.0.1:8080`).
21369
+
21370
+ ### bubblewrap-no-nested-user-namespaces
21371
+
21372
+ **Who must act:** Linux applications in `stitchkit/agent-runtime/sandbox` (`createBubblewrapSandboxBackend`, `createProcessSandbox`) that run software needing its own user namespace inside the sandbox, or whose hosts run a setuid `bwrap` or cannot give Bubblewrap a user namespace.
21373
+
21374
+ Bubblewrap now starts with `--unshare-user --disable-userns`, so `unshare -U`, a nested `bwrap` or a browser's namespace sandbox fails inside the sandbox (`ENOSPC`). Run such software with its own namespace sandbox turned off, or outside the StitchKit sandbox. On a host where `probeProcessSandbox` now reports `available: false`, install the non-setuid `bwrap` and allow it unprivileged user namespaces (for example the distribution's AppArmor profile for `bwrap`); the sandbox has no mode without the lock. Check a host with:
21375
+
21376
+ ```sh
21377
+ bwrap --unshare-all --unshare-user --disable-userns --ro-bind /usr /usr --ro-bind /lib /lib --ro-bind-try /lib64 /lib64 -- /usr/bin/true && echo ok
21378
+ ```
21379
+
21380
+ ### stream-complete-parts-mode
21381
+
21382
+ **Who must act:** applications in `stitchkit/agent-runtime` that await `streamComplete(...).result` without iterating `parts`.
21383
+
21384
+ `streamComplete` no longer infers whether `parts` will be read from whether it was read before 64 parts had passed. By default it backpressures from the first part, so a late `for await` gets every part instead of an overflow error — and a run nobody reads pauses at the full buffer. Say result-only explicitly:
21385
+
21386
+ ```ts
21387
+ // Before (buffer dropped silently after 64 parts)
21388
+ const { text } = await streamComplete({ driver, prompt, onPart }).result;
21389
+
21390
+ // After
21391
+ const { text } = await streamComplete({ driver, prompt, onPart, parts: 'ignore' }).result;
21392
+ // or, with no stream handle at all
21393
+ const { text } = await completeText({ driver, prompt, onPart });
21394
+ ```
21395
+
21396
+ ### one-model-step-loop
21397
+
21398
+ **Who must act:** applications in `stitchkit/agent-runtime` that use `loop.retry` and expect a retry to start the run's model steps over (or `prepareStep` to run again for it), subscribers with a hand-written `attempt-reset` reducer, and standalone completions that rely on having no idle deadline.
21399
+
21400
+ The runtime and the standalone completions run one loop of model steps. A retry repeats the failed call of one step with the request already prepared; earlier steps and their tools stand. Code that counted `prepareStep` calls or reset state in `onAttemptDiscarded` for a fresh start sees one call per step instead:
21401
+
21402
+ ```ts
21403
+ // Before: a 503 in step 2 after a tool ran in step 1 ended the run as provider_failure;
21404
+ // a 503 in step 0 re-ran prepareStep and every step from 0.
21405
+ // After: the failed call of that step is resent as prepared; attempt counts that step's calls.
21406
+ loop: {
21407
+ retry: { maxAttempts: 3, delayMs: () => 500 },
21408
+ onAttemptDiscarded: ({ attempt, reason }) => log.warn({ attempt, reason }),
21409
+ }
21410
+ ```
21411
+
21412
+ A subscriber with its own reducer drops only what an `attempt-reset` withdraws — the failed call's tail — and keeps the earlier steps instead of clearing the run. Count from the end: a subscriber that joined mid-run holds less than the whole run.
21413
+
21414
+ ```ts
21415
+ // Before
21416
+ case 'attempt-reset': return { text: '', reasoning: '' };
21417
+ // After
21418
+ case 'attempt-reset':
21419
+ return event.withdrawn === undefined
21420
+ ? { text: '', reasoning: '' }
21421
+ : {
21422
+ text: view.text.slice(0, Math.max(0, view.text.length - event.withdrawn.text)),
21423
+ reasoning: view.reasoning.slice(
21424
+ 0,
21425
+ Math.max(0, view.reasoning.length - event.withdrawn.reasoning),
21426
+ ),
21427
+ };
21428
+ ```
21429
+
21430
+ Standalone completions now stop a silent provider after 60 000 ms, as the runtime does:
21431
+
21432
+ ```ts
21433
+ // Before (no deadline unless passed)
21434
+ await completeText({ driver, prompt });
21435
+
21436
+ // After: same call, 60 s idle deadline; keep none explicitly
21437
+ await completeText({ driver, prompt, idleTimeoutMs: null });
21438
+ ```
21439
+
20682
21440
  ## Released migration: 0.135.0
20683
21441
 
20684
21442
  ### explicit-deadline-propagation
@@ -20740,6 +21498,21 @@ evaluateOpenRouterModelAdmission({
20740
21498
  listOpenRouterModels(snapshot, { maxPromptUsdPerMillion: 6, maxCacheWriteUsdPerMillion: 6 });
20741
21499
  ```
20742
21500
 
21501
+ ### openrouter-strict-chat-stream-end
21502
+
21503
+ **Who must act:** applications pointing `openRouterProvider({ baseUrl })` from `stitchkit/agent-runtime/openrouter` at an OpenAI-compatible server whose Chat Completions stream ends after `finish_reason` with neither a usage chunk nor `data: [DONE]`. OpenRouter itself and servers that end with `data: [DONE]` need no change.
21504
+
21505
+ Since 0.135.0 such an ending is a stream cut: the step fails with a retryable `AgentProviderStreamCutError` (`classifyProviderFailure` → `reason: 'stream-cut'`) instead of finishing with the usage silently missing, so a retry policy retries it and a server that always ends that way fails every step. Make the server terminate its stream:
21506
+
21507
+ ```text
21508
+ // Before (accepted by 0.134.x, a stream cut since 0.135.0)
21509
+ data: {"choices":[{"index":0,"delta":{"content":"Answer"},"finish_reason":"stop"}]}
21510
+
21511
+ // After (either ending completes the step)
21512
+ data: {"choices":[{"index":0,"delta":{"content":"Answer"},"finish_reason":"stop"}]}
21513
+ data: [DONE]
21514
+ ```
21515
+
20743
21516
  ## Released migration: 0.134.0
20744
21517
 
20745
21518
  ### agent-runtime-native-model-port
@@ -20751,7 +21524,7 @@ listOpenRouterModels(snapshot, { maxPromptUsdPerMillion: 6, maxCacheWriteUsdPerM
20751
21524
  #### Step 1 — Mechanical compatibility (keep existing AI SDK models and tools)
20752
21525
 
20753
21526
  1. Rename `AgentLanguageModelProvider` to `AgentModelDriverFactory` and `AgentResolvedModel.model` to `AgentResolvedModel.driver`.
20754
- 2. Wrap any AI SDK v4 `LanguageModel` with `fromAiSdkModel` and any AI SDK `ToolSet` (including `mountAgent(...)`) with `fromAiSdkTools` from `stitchkit/agent-runtime/ai-sdk`.
21527
+ 2. Wrap any AI SDK `LanguageModel` (`ai@7`, specification `v4`) with `fromAiSdkModel` and any AI SDK `ToolSet` (including `mountAgent(...)`) with `fromAiSdkTools` from `stitchkit/agent-runtime/ai-sdk`.
20755
21528
  3. Update `history.resolveFile` to return tagged `AgentModelFileData` (`{ type: 'data', data }`, `{ type: 'url', url }`, `{ type: 'reference', reference }`, or `{ type: 'text', text }`), and read `AgentGeneratedFile` (`file.mediaType`, `file.data`, `file.uint8Array`, `file.base64`, `file.url`) in `persistGeneratedFile`.
20756
21529
  4. Update `prepareStep` and `stopPolicies` to read peer-free `AgentStepResult` / `AgentModelMessage` / `AgentInstructions`. `AgentRuntimeStopPolicy<CONTEXT>` now takes a single `<CONTEXT>` generic (removing the unused first generic), and all tool events in `AgentModelStreamPart` and `CompleteStreamPart` use unified `toolCallId`.
20757
21530
 
@@ -28342,7 +29115,7 @@ Also re-exports the error helpers from `stitchkit/contract`.
28342
29115
  | `RegistryHandlers` | _type_ | exact backend handler registry inferred from a contract registry |
28343
29116
  | `ExactRegistryHandlers` | _type_ | fail-first handler shape that rejects extra registry and endpoint keys |
28344
29117
  | `staticRoute` | function | a raw route that serves a contained directory through `serveFile` (`Range` / `304` / validators) |
28345
- | `StaticRouteOptions` | _type_ | `{ cacheControl }` — what `staticRoute` adds to every file it serves |
29118
+ | `StaticRouteOptions` | _type_ | `{ cacheControl, allowedDotNames }` — what `staticRoute` adds to every file it serves, and which dot-segment names it serves (none by default) |
28346
29119
  | `serveFile` | function | serve a file with `Range` / `304` / `HEAD` — [guide](../guide/server.md#serving-files--range-requests) |
28347
29120
  | `parseByteRange` | function | parse a single `Range` header → range / `unsatisfiable` / `null` |
28348
29121
  | `isWithinDir` | function | path containment — `(root, resolvedTarget) => boolean`; call it before `serveFile` on any URL-derived path |
@@ -28351,7 +29124,7 @@ Also re-exports the error helpers from `stitchkit/contract`.
28351
29124
  | `ByteRange` | _type_ | an inclusive `{ start, end }` byte range |
28352
29125
  | `respondJson` | function | a raw route's JSON response (`204` for null/undefined) |
28353
29126
  | `errorResponse` | function | any thrown value → the framework error envelope + `x-request-id` |
28354
- | `normalizeError` | function | any thrown value → an `AppError` (`ZodError` → `VALIDATION_ERROR` 400 with structured `details.issues`, else generic 500) — the framework's canonical classification, for a bespoke `onError` |
29127
+ | `normalizeError` | function | any thrown value → an `AppError` (an `AppError` as is — contract input failures arrive as `VALIDATION_ERROR` 400 with structured `details.issues`; anything else, a `ZodError` from handler code included, generic 500) — the framework's canonical classification, for a bespoke `onError` |
28355
29128
  | `NormalizeErrorOptions` | _type_ | `logUnexpected` defaults to logging the raw server-side cause; tool adapters disable process dumps while their existing observers retain that cause |
28356
29129
  | `errorCode` | function | the stable error code for a thrown value (side-effect-free — for log attribution) |
28357
29130
  | `formatZodError` | function | a `ZodError` → a readable, field-summarised string |
@@ -28400,7 +29173,7 @@ Also re-exports the error helpers from `stitchkit/contract`.
28400
29173
  | `ResolvedError` | _type_ | the normalised error handed to `createErrorHook`'s `render` |
28401
29174
  | `createBearerResolver` | function | a bearer-token identity resolver |
28402
29175
  | `signJwt` | function | sign an HS256 JWT |
28403
- | `VerifyJwtOptions` | _type_ | options for `verifyJwt` |
29176
+ | `VerifyJwtOptions` | _type_ | options for `verifyJwt` — `leewaySeconds`, `issuer`, `audience`, `expiration` (`'required'` by default) |
28404
29177
  | `verifyJwt` | function | verify an HS256 JWT |
28405
29178
  | `signLink` / `SignLinkOptions` | function / _type_ | a short-lived link for a request that cannot carry a header (`<audio src>`, `<img src>`): appends `expires` and an HMAC-SHA-256 `signature` over the method, path and every query parameter — [guide](../guide/auth-and-errors.md#signed-links) |
28406
29179
  | `verifySignedLink` / `VerifySignedLinkOptions` | function / _type_ | check a request against its link (signature compared with a constant-time comparison, then expiry); call it from `createAuthHook`'s `resolve` or a raw route |
@@ -28511,11 +29284,11 @@ Also re-exports the error helpers from `stitchkit/contract`.
28511
29284
  | `resolveTraceId` | function | the default per-request trace-id resolver |
28512
29285
  | `extractIp` | function | the caller IP from a request |
28513
29286
  | `isPublicIp` | function | whether an address belongs to the public internet; anything unparseable is not |
28514
- | `resolveSocketIp` | function | the caller IP for a Socket.IO handshake (proxy-aware) |
29287
+ | `resolveSocketIp` | function | the real socket peer IP from the runtime (`server.requestIP` on Bun, `req.ip` under `srvx`); headers are not read |
28515
29288
  | `getClientInfo` | function | caller IP + user-agent |
28516
29289
  | `EventBus` | _type_ | the `createEventBus` handle |
28517
29290
  | `RateLimitConfig` | _type_ | config for `createRateLimiter` |
28518
- | `ClientIpOptions` | _type_ | trusted-proxy config for `extractIp` / `resolveSocketIp` |
29291
+ | `ClientIpOptions` | _type_ | socket peer and trusted-proxy config for `extractIp` / `getClientInfo` |
28519
29292
  | `StreamingRouteOptions` | _type_ | options for `streamingRoute` / `ndjsonRoute` / `sseRoute` |
28520
29293
  | `StreamingSourceContext` | _type_ | what a streaming source is given, including the cancellation `signal` |
28521
29294
  | `StreamingFormat` | _type_ | `'ndjson' \| 'sse'` |
@@ -29043,7 +29816,7 @@ the same native step execution without requiring a store. → ADR 0336.
29043
29816
  | `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`) |
29044
29817
  | `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 |
29045
29818
  | `AgentModelDriverDecorator` / `AgentModelDriverStreamOutcome` | _type_ | generic per-stream interceptor (`beforeStream`, `transformRequest`, `transformSignal`, `onPart`, `onClose`) and terminal stream outcome (`finished`, `errored`, `cancelled`) |
29046
- | `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 |
29819
+ | `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) |
29047
29820
  | `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 |
29048
29821
  | `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` |
29049
29822
  | `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` |
@@ -29271,7 +30044,7 @@ Peer-free, credential-free model drivers, provider fault servers, and concurrenc
29271
30044
  |--------|------|---------|
29272
30045
  | `createScriptedModelDriver` | function | deterministic peer-free `AgentModelDriver` for tests: replays scripted stream parts, records every `AgentModelRequest`, and supports per-step throws or async stream factories |
29273
30046
  | `ScriptedModelDriver` / `ScriptedModelDriverOptions` / `ScriptedModelStep` | _types_ | scripted driver handle (exposing `requests`), driver options (`provider`, `modelId`, `steps`, `onRequest`), and one scripted turn (`AgentModelStreamPart[]`, `{ throw }`, or stream function) |
29274
- | `createFaultProviderServer` | function | start an OpenAI-compatible local SSE endpoint with deterministic pass, connection-refused, timeout, stream-cut, HTTP, malformed JSON, slow-stream and missing-usage steps |
30047
+ | `createFaultProviderServer` | function | start an OpenAI-compatible local SSE endpoint with deterministic pass, connection-refused, timeout, stream-cut, HTTP, malformed JSON, slow-stream and missing-usage steps; its `url` is the API root (`…/v1`) a provider `baseUrl` takes |
29275
30048
  | `AgentFaultStepSchema` / `AgentFaultStep` | schema / _type_ | strict fault-plan step vocabulary |
29276
30049
  | `defineAgentFaultPlan` | function | validate a non-empty deterministic fault sequence |
29277
30050
  | `createReplayAgentProvider` | function | serve a declared sequence of credential-free `AgentModelDriver` fixtures per model ID |
@@ -29445,7 +30218,7 @@ Server-only, peer-free native OpenRouter provider over Web `fetch` and Chat Comp
29445
30218
  |--------|------|---------|
29446
30219
  | `openRouterProvider` / `OpenRouterProviderAccess` | function / _type_ | native peer-free `AgentModelDriverFactory` over OpenRouter Chat Completions SSE; the optional second argument shapes every request — `defaultPolicy`, `resolvePolicy(modelId)` from the application's own model table, and `sessionPerConversation` (`session_id` derived directly from `request.correlation.conversationId`, hashed when over 256 chars, without requiring `invocations`, yielding to explicit `provider.order`); a provider-level `extraBody` that would overwrite owned wire keys is refused |
29447
30220
  | `OpenRouterProviderSettings` | _type_ | `{ apiKey, baseUrl?, headers?, appName?, appUrl?, providerApiKeys?, fetch?, extraBody? }` — camelCase settings sending `HTTP-Referer`, `X-OpenRouter-Title`, and `X-Provider-API-Keys` with `redirect: 'error'` |
29448
- | `OpenRouterRequestPolicySchema` / `OpenRouterRequestPolicy` / `OpenRouterProviderRoutingSchema` / `OpenRouterProviderRouting` / `OpenRouterMaxPriceSchema` / `OpenRouterMaxPrice` / `OpenRouterReasoningEffortSchema` / `OpenRouterReasoningEffort` | schemas / _types_ | one request's policy: `sessionId` or `provider.order` (never both; an empty order is refused), routing (`allowFallbacks`, `requireParameters`, `dataCollection`, `zdr`, `only`, `ignore`, `sort`, `quantizations`), `maxPrice` in USD per million tokens or per request/image, `reasoning.effort` up to `max`, `looseTools` (`strict: false` while preserving explicit per-tool `strict: true`), and optional portable `cacheControl` (`AgentCacheControl`) |
30221
+ | `OpenRouterRequestPolicySchema` / `OpenRouterRequestPolicy` / `OpenRouterProviderRoutingSchema` / `OpenRouterProviderRouting` / `OpenRouterMaxPriceSchema` / `OpenRouterMaxPrice` / `OpenRouterReasoningEffortSchema` / `OpenRouterReasoningEffort` | schemas / _types_ | one request's policy: `sessionId` or `provider.order` (never both; an empty order is refused), routing (`allowFallbacks`, `requireParameters`, `dataCollection`, `zdr`, `only`, `ignore`, `sort`, `quantizations`) and provider-specific `options` keyed by provider slug (also accepted by every non-chat client's `provider`), `maxPrice` in USD per million tokens or per request/image, `reasoning.effort` up to `max`, `looseTools` (`strict: false` while preserving explicit per-tool `strict: true`), and optional portable `cacheControl` (`AgentCacheControl`) |
29449
30222
  | `normalizeOpenRouterUsage` | function | provenance-aware normalization of raw OpenRouter `usage` payloads (including BYOK `cost_details.upstream_inference_cost` with `computed` cost provenance; missing counters stay `unavailable`) |
29450
30223
  | `createOpenRouterRouteResolver` / `OpenRouterRouteResolver` / `createMemoryOpenRouterRouteStore` / `OpenRouterRouteStore` / `OpenRouterRoutePinSchema` / `OpenRouterRoutePin` | functions / _types_ / schema | keep a thread on one upstream outside the agent runtime: `session-sticky` (its `session_id`; a key over 256 characters is hashed) or `provider-order` (the upstream slug that answered first, from `record`, with `allowFallbacks: false` unless the base policy says otherwise); a pin replaces the base policy's route; the memory store is least-recently-used, bounded by `maxEntries` and `ttlMs` |
29451
30224
  | `loadOpenRouterCatalogSnapshot` / `fetchOpenRouterModelEndpoints` / `OpenRouterSnapshotOptions` / `OpenRouterCatalogSnapshotSchema` / `OpenRouterCatalogSnapshot` / `OpenRouterSnapshotModelSchema` / `OpenRouterSnapshotModel` / `OpenRouterEndpointSchema` / `OpenRouterEndpoint` / `OpenRouterPricingTierSchema` / `OpenRouterPricingTier` / `OpenRouterModelAliasTargetSchema` / `OpenRouterModelAliasTarget` / `OpenRouterModelReasoningMetaSchema` / `OpenRouterModelReasoningMeta` | functions / _types_ / schemas | a timestamped snapshot of `/models` (supporting unauthenticated public reads or static/async `apiKey`, full model metadata including `canonicalSlug`, `description`, `createdAt`, `aliasTarget`, `inputModalities`, `outputModalities`, `tokenizer`, `topProviderContextLength`, `maxCompletionTokens`, `reasoning`, per-million/request/image/cache prices including `cacheWrite1hUsdPerMillion` and conditional `pricingTiers` — distinguishing omitted keys from explicit `null`/`-1` unknowns, never treating unknown as zero — rejecting paginated truncation and duplicate ids) and per-model endpoints (including `cacheWrite1hUsdPerMillion`, `latencyP50Ms`, `throughputP50`, `uptime1d`, `tag`); ids are checked as `author/slug` (or `~author/slug`) before the network, endpoint requests run 1–16 at once and stop at the first failure, bodies are bounded, redirects refused |
@@ -29454,17 +30227,18 @@ Server-only, peer-free native OpenRouter provider over Web `fetch` and Chat Comp
29454
30227
  | `createOpenRouterCatalogCache` / `OpenRouterCatalogCache` / `OpenRouterCatalogCacheOptions` / `OpenRouterCatalogCacheReadResult` / `OpenRouterCatalogStore` | function / _types_ | Web Fetch-clean cached OpenRouter catalog reader with single-flight coalescing, per-caller `AbortSignal` isolation, `freshMs` TTL, `retryBackoffMs` stale fallback, optional pluggable persistence (`store`), and `read`/`refresh`/`getModel`/`listModels`; `OpenRouterCatalogCacheReadResult` is a discriminated union on `status` (`'current' \| 'stale' \| 'unavailable'`) narrowing `snapshot`, `observedAt`, `models`, and `lastError` without casts (use `read()` for admission/billing decisions; `getModel`/`listModels` map `'unavailable'` to `undefined`/`[]`) |
29455
30228
  | `evaluateOpenRouterModelAdmission` / `OpenRouterAdmissionPolicySchema` / `OpenRouterAdmissionPolicy` / `OpenRouterModelAdmissionSchema` / `OpenRouterModelAdmission` / `OpenRouterAdmissionReasonSchema` / `OpenRouterAdmissionReason` | function / schemas / _types_ | decide one model from a stored snapshot: `admitted`, `unverified` (stale or future-dated snapshot, `'context-unknown'`, `'price-unknown'`, `'endpoints-unknown'`) or `rejected` with a reason (`requiredParameters`, `requiredInputModalities`, effective context `min(contextLength, topProviderContextLength)`, separated worst-case pricing ceilings `maxPromptUsdPerMillion` / `maxCompletionUsdPerMillion` / `maxCacheWriteUsdPerMillion` via `resolveOpenRouterModelCeiling`, live endpoint); `~`, `-latest`, `:batch`, `stealth/`, `openrouter/auto`, `aliasOf`, and `aliasTarget` models are always refused as `'floating-alias'`; the result is a schema, so a stored decision reads back |
29456
30229
  | `openRouterSpendProvider` / `createOpenRouterSpendReconciler` | functions | OpenRouter for `stitchkit/spend`: the gateway provider (origin derived from optional `baseUrl` override, key read per call, chat + non-chat usage facts including `x-generation-id`, `input_tokens`/`output_tokens`, `generation_id`, and `usage.seconds` as `workUnit: 'seconds'`) and the reconciler that prices an attempt by its generation id (`GET /api/v1/generation`, optional `baseUrl` override; a 404 is "not yet"; `apiKey` may be a function of the record, since OpenRouter prices a generation only for the key that made it) |
29457
- | `OpenRouterHttpError` | class | a non-2xx answer from OpenRouter, with its `status` |
29458
30230
  | `openRouterModelCatalog` | function | complete tool-capable text catalog (`sort=top-weekly`) plus independent weekly popularity and available benchmark observations (optional static or async `apiKey` and `baseUrl` override); a `timeoutMs` that is not an integer from 1 to 2147483647 ms (the timer range) is refused when the catalog is created (`RangeError`) |
29459
- | `OpenRouterModelCatalogOptions` / `OpenRouterCatalogFetch` | _type_ | optional static/dynamic credential, `baseUrl` override, timeout, clock and injected fetch boundary for catalog loading |
29460
- | `OPENROUTER_API_BASE_URL` / `OpenRouterFetch` | const / _type_ | canonical default OpenRouter API v1 base URL (`https://openrouter.ai/api/v1`) and Web Fetch-compatible transport type shared by `openRouterProvider` and non-chat endpoint helpers |
30231
+ | `OpenRouterModelCatalogOptions` | _type_ | optional static/dynamic credential, `baseUrl` override, timeout, clock and injected `OpenRouterFetch` for catalog loading |
30232
+ | `OPENROUTER_API_BASE_URL` / `OpenRouterFetch` | const / _type_ | canonical default OpenRouter API v1 base URL (`https://openrouter.ai/api/v1`) and the one Web Fetch-compatible transport type (it receives the resolved `URL`) shared by `openRouterProvider`, catalog, spend and non-chat endpoint helpers |
29461
30233
  | `openRouterRequestJson` / `openRouterRequestStream` / `OpenRouterTransportOptions` / `OpenRouterRequestJsonOptions` / `OpenRouterRequestStreamOptions` / `OpenRouterJsonResponse` / `OpenRouterStreamResponse` / `OpenRouterHttpMethod` / `OpenRouterQueryParams` | functions / _types_ | peer-free, Web Fetch-clean transport for any OpenRouter API v1 JSON, multipart (`FormData`), or binary streaming endpoint: validates `baseUrl` and relative `path` against traversal or origin override, enforces `redirect: 'error'` plus defense-in-depth redirect refusal, bounds response/error bodies, throws redacted `AgentProviderError` on non-2xx or invalid JSON/schema, extracts `generationId`, `requestId`, and BYOK-aware `costUsd`, and disarms `openRouterRequestStream`'s open-phase `timeoutMs` once 2xx headers arrive while keeping caller `signal` linked to stream cancellation |
29462
- | `openRouterSystemOne` / `OpenRouterSystemOneInput` / `OpenRouterSystemOneQuestion` / `OpenRouterSystemOneResponseSchema` / `OpenRouterSystemOneResponse` / `OpenRouterSystemOneResult` | function / schema / _types_ | typed client for OpenRouter's `POST /systemone` decision endpoint (`noul`, `choice`, and `score` questions over text or structured `state`, optional `provider` routing and `extraBody`, calibrated probability answers plus `generationId` and `costUsd`) |
29463
- | `openRouterAudioTranscription` / `OpenRouterAudioTranscriptionInput` / `OpenRouterAudioSource` / `OpenRouterAudioTranscriptionResponseSchema` / `OpenRouterAudioTranscriptionResponse` / `OpenRouterAudioTranscriptionResult` | function / schema / _types_ | typed client for OpenRouter's `POST /audio/transcriptions` speech-to-text endpoint supporting `base64` JSON (`input_audio`), remote `url` (`source_url`), and multipart `file` uploads (`Blob` / `Uint8Array` / `ArrayBuffer`), `verbose_json`, `timestampGranularities`, `diarize` (enforcing `verbose_json`), `provider` routing, `generationId`, and `costUsd` |
29464
- | `openRouterAudioSpeech` / `OpenRouterAudioSpeechInput` / `OpenRouterSpeechFormat` / `OpenRouterAudioSpeechResult` | function / _types_ | streaming text-to-speech client for OpenRouter's `POST /audio/speech` endpoint returning binary audio `ReadableStream<Uint8Array>`, `contentType`, and `generationId` |
30234
+ | `openRouterSystemOne` / `OpenRouterSystemOneInput` / `OpenRouterSystemOneQuestion` / `OpenRouterSystemOneResponseSchema` / `OpenRouterSystemOneResponse` / `OpenRouterSystemOneResult` | function / schema / _types_ | typed client for OpenRouter's `POST /systemone` decision endpoint (`noul`, `choice`, `score` and image `box` questions over a `state` string, JSON object or JSON array, image `assets`, `sessionId`, `user`, optional `provider` routing and `extraBody`; calibrated probability answers, `box` answers and per-question `refusal` plus `generationId` and `costUsd`) |
30235
+ | `openRouterAudioTranscription` / `OpenRouterAudioTranscriptionInput` / `OpenRouterAudioSource` / `OpenRouterAudioTranscriptionResponseSchema` / `OpenRouterAudioTranscriptionResponse` / `OpenRouterAudioTranscriptionResult` / `OpenRouterTranscriptionSegment` / `OpenRouterTranscriptionWord` | function / schema / _types_ | typed client for OpenRouter's `POST /audio/transcriptions` speech-to-text endpoint supporting `base64` JSON (`input_audio: { data, format }`), remote `url` (`input_audio: { url, format? }`), and multipart `file` uploads (`Blob` / `Uint8Array` / `ArrayBuffer`), `verbose_json`, `timestampGranularities`, `diarize` (enforcing `verbose_json`; segments and words carry an integer `speaker` index and optional `speakerLabel`), `provider` routing, `generationId`, and `costUsd` |
30236
+ | `OpenRouterUsageSchema` / `OpenRouterUsage` / `OpenRouterResponseMeta` | schema / _types_ | what the non-chat clients share: one `usage` schema (tokens, `seconds`, `cost`, `is_byok`) on every non-chat response schema, and the result metadata (`status`, `generationId`, `requestId`, `costUsd`, `headers`) every non-chat result extends; each client validates its request fields with Zod before any request |
30237
+ | `createOpenRouterClient` / `OpenRouterClient` / `OpenRouterClientOptions` | function / _types_ | one client for the non-chat endpoints: transport settings (`apiKey`, `baseUrl`, `fetch`, `headers`, `appName`, `appUrl`, `providerApiKeys`, `timeoutMs`, `maxErrorBytes`) stated once; methods `audioTranscription`, `audioSpeech`, `systemOne`, `generateImages`, `submitVideo`, `getVideo`, `downloadVideo`, `embeddings`, `rerank`, `requestJson`, `requestStream` are the `openRouter*` functions of the same name with those settings under each call's own (`headers` and `providerApiKeys` merge key by key); an invalid `baseUrl` or static `apiKey` is refused at creation |
30238
+ | `openRouterAudioSpeech` / `OpenRouterAudioSpeechInput` / `OpenRouterSpeechFormat` / `OpenRouterSpeechTurn` / `OpenRouterAudioSpeechResult` / `OpenRouterAudioSpeechUrlResult` / `OpenRouterSpeechUrlResponseSchema` / `OpenRouterSpeechUrlResponse` | function / schema / _types_ | text-to-speech client for OpenRouter's `POST /audio/speech` endpoint: `input` as text or multi-speaker turns (`{ text, voice?, instructions? }`), optional `voice`, request-wide `instructions`, `responseFormat` `mp3` / `pcm` / `wav`; by default resolves `{ delivery: 'stream' }` with binary audio `ReadableStream<Uint8Array>`, `contentType`, and `generationId`, and with `outputDelivery: 'url'` resolves `{ delivery: 'url', url, expiresAt, mediaType }` or the byte stream when zero-data-retention applies |
29465
30239
  | `openRouterGenerateImages` / `OpenRouterImageGenerationInput` / `OpenRouterImageGenerationResponseSchema` / `OpenRouterImageGenerationResponse` / `OpenRouterImageGenerationResult` | function / schema / _types_ | typed client for OpenRouter's Unified Image API (`POST /images`) supporting `prompt`, `n`, `aspectRatio`, `resolution`, `responseFormat` (`'b64_json' \| 'url'`), `inputReferences`, `provider` routing, `generationId`, and `costUsd` |
29466
- | `openRouterSubmitVideo` / `openRouterGetVideo` / `openRouterDownloadVideo` / `OpenRouterVideoSubmitInput` / `OpenRouterVideoJobInput` / `OpenRouterVideoSubmitResponse` / `OpenRouterVideoSubmitResult` / `OpenRouterVideoStatusResponse` / `OpenRouterVideoStatusResult` | functions / _types_ | typed submit (`POST /videos`), status poll (`GET /videos/{jobId}`), and authenticated binary stream download (`GET /videos/{jobId}/content`) clients for OpenRouter's asynchronous Video Generation API with `jobId` path-segment validation, `frameImages`, `inputReferences`, `generateAudio`, `callbackUrl`, `generationId`, and `costUsd` |
29467
- | `openRouterEmbeddings` / `OpenRouterEmbeddingsInput` / `OpenRouterEmbeddingsResponse` / `OpenRouterEmbeddingsResult` / `openRouterRerank` / `OpenRouterRerankInput` / `OpenRouterRerankResponse` / `OpenRouterRerankResult` | functions / _types_ | typed clients for OpenRouter's `POST /embeddings` vector generation and `POST /rerank` document rescoring endpoints with `provider` routing, `generationId`, and `costUsd` |
30240
+ | `openRouterSubmitVideo` / `openRouterGetVideo` / `openRouterDownloadVideo` / `OpenRouterVideoSubmitInput` / `OpenRouterVideoJobInput` / `OpenRouterVideoSubmitResponseSchema` / `OpenRouterVideoSubmitResponse` / `OpenRouterVideoSubmitResult` / `OpenRouterVideoStatusResponseSchema` / `OpenRouterVideoStatusResponse` / `OpenRouterVideoStatusResult` | functions / schemas / _types_ | typed submit (`POST /videos`), status poll (`GET /videos/{jobId}`), and authenticated binary stream download (`GET /videos/{jobId}/content`, optional zero-based output `index`) clients for OpenRouter's asynchronous Video Generation API with `jobId` path-segment validation, `frameImages`, `inputReferences`, `generateAudio`, `callbackUrl`, `generationId`, and `costUsd` |
30241
+ | `openRouterEmbeddings` / `OpenRouterEmbeddingsInput` / `OpenRouterEmbeddingsResponseSchema` / `OpenRouterEmbeddingsResponse` / `OpenRouterEmbeddingsResult` / `openRouterRerank` / `OpenRouterRerankInput` / `OpenRouterRerankResponseSchema` / `OpenRouterRerankResponse` / `OpenRouterRerankResult` | functions / schemas / _types_ | typed clients for OpenRouter's `POST /embeddings` vector generation and `POST /rerank` document rescoring endpoints (string or `{ text?, image? }` documents, results echoing `text` and/or `image`) with `provider` routing, `generationId`, and `costUsd` |
29468
30242
 
29469
30243
  ## `stitchkit/agent-runtime/openai`
29470
30244
 
@@ -30656,7 +31430,9 @@ injected grammY bot. → ADR 0143, ADR 0201, ADR 0274 — [guide](../guide/teleg
30656
31430
  | `TelegramWidgetHtmlSchema` / `TelegramWidgetDataSchema` | schema | widget HTML (1–32768 bytes, at most 4096 compressed) and widget data (0–1024 bytes), counted in UTF-8 bytes; NUL and an unpaired surrogate are refused, an empty data string is a value |
30657
31431
  | `TelegramWidgetMessageSchema` / `TelegramWidgetMessage` | schema / _type_ | the message `sendWidget` returns — `message_id`, `chat`, `widget` with `html` and its data; parsed loosely, so fields Telegram adds pass through |
30658
31432
  | `TelegramWidgetQuerySchema` / `TelegramWidgetQuery` | schema / _type_ | `Update.widget_query`: `id`, `from`, `chat` with `message_id` or `inline_message_id`, `chat_instance`, `type` (`data` / `sign_data` / `sent_transaction`), `data` of 1–64 bytes, `widget_id` |
30659
- | `parseTelegramWidgetQuery` / `TelegramWidgetQueryParse` | function / _type_ | read `update.widget_query`: `{ query }`, or `{ id, error }` for a query that does not parse — its id is enough to answer it with a refusal — or `undefined` without an id |
31433
+ | `parseTelegramWidgetQuery` / `TelegramWidgetQueryParse` | function / _type_ | read `update.widget_query`: `{ query }`, or `{ id, error }` for a query that does not parse — its id is enough to answer it with a refusal — or `undefined` without an id; `TelegramWidgetQueryParse<Query>` is the same result for another query type |
31434
+ | `TelegramSharedWidgetQuerySchema` / `TelegramSharedWidgetQuery` | schema / _type_ | `Update.shared_widget_query`, a query from a forwarded shared widget: `id`, `from`, `type`, `data` of 1–64 bytes and the shared widget's `widget_id` — no chat and no message |
31435
+ | `parseTelegramSharedWidgetQuery` | function | read `update.shared_widget_query` as `parseTelegramWidgetQuery` reads `update.widget_query`: `{ query }`, `{ id, error }` or `undefined` |
30660
31436
 
30661
31437
  ---
30662
31438
 
@@ -30670,8 +31446,9 @@ declarations and is never imported at run time — the bot brings it. → ADR 02
30670
31446
  | Export | Kind | Summary |
30671
31447
  |--------|------|---------|
30672
31448
  | `telegramBudgetTransformer` | function | `bot.api.config.use(telegramBudgetTransformer(budget))`: every Bot API call runs under the token's `telegramOutboundBudget`; a 429 that comes back as a response pauses the token, a cancellation before the request was handed on throws `TelegramNotDispatchedError`, a cancellation in flight stays the client's own error; it never retries |
30673
- | `telegramWidgetApi` / `TelegramWidgetApi` | function / _type_ | `telegramWidgetApi(bot.api)`: `sendWidget`, `editMessageWidgetData` and `answerWidgetQuery` through the client's `api.raw`, so its transformers — the outbound budget among them — run each call; input over a limit throws `ZodError` before any request, an already aborted signal throws `TelegramNotDispatchedError`, a request is handed on once and never repeated, `message is not modified` is success, and an unexpected successful answer is an error whose outcome is unknown |
30674
- | `TelegramSendWidgetParams` / `TelegramEditMessageWidgetDataParams` / `TelegramAnswerWidgetQueryParams` | _type_ | the methods' Bot API parameters by their Bot API names; an edit names `chat_id` with `message_id` or `inline_message_id`, and `chat_data` or `public_data` (`''` removes it, an omitted field keeps it) |
31449
+ | `telegramWidgetApi` / `TelegramWidgetApi` | function / _type_ | `telegramWidgetApi(bot.api)`: `sendWidget`, `sendSharedWidget`, `editMessageWidgetData`, `editSharedWidgetData` and `answerWidgetQuery` through the client's `api.raw`, so its transformers — the outbound budget among them — run each call; input over a limit throws `ZodError` before any request, an already aborted signal throws `TelegramNotDispatchedError`, a request is handed on once and never repeated, `message is not modified` is success, and an unexpected successful answer is an error whose outcome is unknown |
31450
+ | `TelegramSendWidgetParams` / `TelegramEditMessageWidgetDataParams` / `TelegramAnswerWidgetQueryParams` | _type_ | the methods' Bot API parameters by their Bot API names; `is_shared: true` creates a shared widget, whose message must carry `widget.id`; an edit names `chat_id` with `message_id` or `inline_message_id`, and `chat_data` or `public_data` (`''` removes it, an omitted field keeps it) |
31451
+ | `TelegramSendSharedWidgetParams` / `TelegramEditSharedWidgetDataParams` | _type_ | `sendSharedWidget` sends an existing shared widget by `widget_id` again, costs one message, and its message must carry that id; `editSharedWidgetData` changes `public_data` (`''` removes it) of every message with the widget, with an optional `cache_time` of 5–3600 s, and costs no message |
30675
31452
  | `TelegramWidgetCallOptions` | _type_ | `signal` for one call: aborted before the request leaves, the call is not dispatched |
30676
31453
 
30677
31454
  ---
@@ -31415,7 +32192,7 @@ Portable Fetch handler and `postMessage` bridge host without Node built-ins; usa
31415
32192
 
31416
32193
  ## `stitchkit/http`
31417
32194
 
31418
- 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`.
32195
+ 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`.
31419
32196
 
31420
32197
  ```ts
31421
32198
  import { createClients, createHttpClient } from 'stitchkit/http';