stitchkit 0.135.1 → 0.136.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (436) hide show
  1. package/CHANGELOG.md +122 -0
  2. package/README.md +37 -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/executor-contract.d.ts.map +1 -1
  20. package/dist/agent-executor/image-input.d.ts +10 -3
  21. package/dist/agent-executor/image-input.d.ts.map +1 -1
  22. package/dist/agent-executor/testing/replay-scenarios.d.ts.map +1 -1
  23. package/dist/agent-executor/testing/replay-transcript.d.ts.map +1 -1
  24. package/dist/agent-executor/vocabulary.d.ts +80 -0
  25. package/dist/agent-executor/vocabulary.d.ts.map +1 -1
  26. package/dist/agent-parts/model.d.ts +94 -0
  27. package/dist/agent-parts/model.d.ts.map +1 -1
  28. package/dist/agent-parts/parts.d.ts +176 -0
  29. package/dist/agent-parts/parts.d.ts.map +1 -1
  30. package/dist/agent-runtime/browser/browser-control-contract.d.ts +444 -0
  31. package/dist/agent-runtime/browser/browser-control-contract.d.ts.map +1 -1
  32. package/dist/agent-runtime/browser/control-schema.d.ts +532 -0
  33. package/dist/agent-runtime/browser/control-schema.d.ts.map +1 -1
  34. package/dist/agent-runtime/browser/control-view.d.ts.map +1 -1
  35. package/dist/agent-runtime/event-schema.d.ts +720 -3
  36. package/dist/agent-runtime/event-schema.d.ts.map +1 -1
  37. package/dist/agent-runtime/history/run-history-parts.d.ts.map +1 -1
  38. package/dist/agent-runtime/loop/deferred-tools.d.ts.map +1 -1
  39. package/dist/agent-runtime/loop/invocation-payload.d.ts.map +1 -1
  40. package/dist/agent-runtime/loop/invocation-stream.d.ts +9 -1
  41. package/dist/agent-runtime/loop/invocation-stream.d.ts.map +1 -1
  42. package/dist/agent-runtime/loop/provider-stream-parts.d.ts +6 -0
  43. package/dist/agent-runtime/loop/provider-stream-parts.d.ts.map +1 -1
  44. package/dist/agent-runtime/loop/provider-stream-segments.d.ts +1 -3
  45. package/dist/agent-runtime/loop/provider-stream-segments.d.ts.map +1 -1
  46. package/dist/agent-runtime/loop/run-acquisition.d.ts.map +1 -1
  47. package/dist/agent-runtime/loop/run-approval-signature.d.ts +38 -0
  48. package/dist/agent-runtime/loop/run-approval-signature.d.ts.map +1 -0
  49. package/dist/agent-runtime/loop/run-approval.d.ts +0 -28
  50. package/dist/agent-runtime/loop/run-approval.d.ts.map +1 -1
  51. package/dist/agent-runtime/loop/run-complete-port.d.ts +24 -0
  52. package/dist/agent-runtime/loop/run-complete-port.d.ts.map +1 -0
  53. package/dist/agent-runtime/loop/run-complete-stream.d.ts +7 -2
  54. package/dist/agent-runtime/loop/run-complete-stream.d.ts.map +1 -1
  55. package/dist/agent-runtime/loop/run-complete-types.d.ts +14 -1
  56. package/dist/agent-runtime/loop/run-complete-types.d.ts.map +1 -1
  57. package/dist/agent-runtime/loop/run-complete.d.ts +2 -2
  58. package/dist/agent-runtime/loop/run-complete.d.ts.map +1 -1
  59. package/dist/agent-runtime/loop/run-execution-state.d.ts +8 -0
  60. package/dist/agent-runtime/loop/run-execution-state.d.ts.map +1 -1
  61. package/dist/agent-runtime/loop/run-loop-events.d.ts +6 -1
  62. package/dist/agent-runtime/loop/run-loop-events.d.ts.map +1 -1
  63. package/dist/agent-runtime/loop/run-model-call.d.ts +44 -0
  64. package/dist/agent-runtime/loop/run-model-call.d.ts.map +1 -0
  65. package/dist/agent-runtime/loop/run-model-step.d.ts +25 -28
  66. package/dist/agent-runtime/loop/run-model-step.d.ts.map +1 -1
  67. package/dist/agent-runtime/loop/run-model-steps.d.ts +6 -0
  68. package/dist/agent-runtime/loop/run-model-steps.d.ts.map +1 -0
  69. package/dist/agent-runtime/loop/run-model-stream.d.ts +3 -1
  70. package/dist/agent-runtime/loop/run-model-stream.d.ts.map +1 -1
  71. package/dist/agent-runtime/loop/run-operation-lifecycle.d.ts +0 -2
  72. package/dist/agent-runtime/loop/run-operation-lifecycle.d.ts.map +1 -1
  73. package/dist/agent-runtime/loop/run-step-loop.d.ts +19 -0
  74. package/dist/agent-runtime/loop/run-step-loop.d.ts.map +1 -0
  75. package/dist/agent-runtime/loop/run-step-port.d.ts +175 -0
  76. package/dist/agent-runtime/loop/run-step-port.d.ts.map +1 -0
  77. package/dist/agent-runtime/loop/run-stream-parts.d.ts.map +1 -1
  78. package/dist/agent-runtime/loop/run-stream-recorded.d.ts.map +1 -1
  79. package/dist/agent-runtime/loop/run-stream-step-text.d.ts.map +1 -1
  80. package/dist/agent-runtime/loop/run-tool-approval-flow.d.ts +2 -1
  81. package/dist/agent-runtime/loop/run-tool-approval-flow.d.ts.map +1 -1
  82. package/dist/agent-runtime/loop/run-tool-call-input.d.ts +39 -0
  83. package/dist/agent-runtime/loop/run-tool-call-input.d.ts.map +1 -0
  84. package/dist/agent-runtime/loop/run-tool-call.d.ts +13 -34
  85. package/dist/agent-runtime/loop/run-tool-call.d.ts.map +1 -1
  86. package/dist/agent-runtime/loop/run-tool-errors.d.ts +5 -0
  87. package/dist/agent-runtime/loop/run-tool-errors.d.ts.map +1 -1
  88. package/dist/agent-runtime/loop/run-tool-executor.d.ts +1 -1
  89. package/dist/agent-runtime/loop/run-tool-executor.d.ts.map +1 -1
  90. package/dist/agent-runtime/loop/run-tool-slots.d.ts +2 -1
  91. package/dist/agent-runtime/loop/run-tool-slots.d.ts.map +1 -1
  92. package/dist/agent-runtime/loop/runtime-state.d.ts.map +1 -1
  93. package/dist/agent-runtime/loop/runtime.d.ts +0 -5
  94. package/dist/agent-runtime/loop/runtime.d.ts.map +1 -1
  95. package/dist/agent-runtime/providers/ai-sdk-convert.d.ts +1 -5
  96. package/dist/agent-runtime/providers/ai-sdk-convert.d.ts.map +1 -1
  97. package/dist/agent-runtime/providers/ai-sdk-normalize.d.ts +15 -0
  98. package/dist/agent-runtime/providers/ai-sdk-normalize.d.ts.map +1 -0
  99. package/dist/agent-runtime/providers/ai-sdk-tools.d.ts +11 -0
  100. package/dist/agent-runtime/providers/ai-sdk-tools.d.ts.map +1 -0
  101. package/dist/agent-runtime/providers/ai-sdk.d.ts +1 -9
  102. package/dist/agent-runtime/providers/ai-sdk.d.ts.map +1 -1
  103. package/dist/agent-runtime/providers/anthropic-sse.d.ts.map +1 -1
  104. package/dist/agent-runtime/providers/openrouter-admission.d.ts.map +1 -1
  105. package/dist/agent-runtime/providers/openrouter-audio.d.ts +123 -81
  106. package/dist/agent-runtime/providers/openrouter-audio.d.ts.map +1 -1
  107. package/dist/agent-runtime/providers/openrouter-catalog-cache.d.ts.map +1 -1
  108. package/dist/agent-runtime/providers/openrouter-catalog-query.d.ts.map +1 -1
  109. package/dist/agent-runtime/providers/openrouter-catalog.d.ts +2 -2
  110. package/dist/agent-runtime/providers/openrouter-catalog.d.ts.map +1 -1
  111. package/dist/agent-runtime/providers/openrouter-client.d.ts +37 -0
  112. package/dist/agent-runtime/providers/openrouter-client.d.ts.map +1 -0
  113. package/dist/agent-runtime/providers/openrouter-http.d.ts +26 -6
  114. package/dist/agent-runtime/providers/openrouter-http.d.ts.map +1 -1
  115. package/dist/agent-runtime/providers/openrouter-media.d.ts +91 -77
  116. package/dist/agent-runtime/providers/openrouter-media.d.ts.map +1 -1
  117. package/dist/agent-runtime/providers/openrouter-models.d.ts +2 -23
  118. package/dist/agent-runtime/providers/openrouter-models.d.ts.map +1 -1
  119. package/dist/agent-runtime/providers/openrouter-options.d.ts +2 -0
  120. package/dist/agent-runtime/providers/openrouter-options.d.ts.map +1 -1
  121. package/dist/agent-runtime/providers/openrouter-request.d.ts +23 -0
  122. package/dist/agent-runtime/providers/openrouter-request.d.ts.map +1 -0
  123. package/dist/agent-runtime/providers/openrouter-retrieval.d.ts +86 -55
  124. package/dist/agent-runtime/providers/openrouter-retrieval.d.ts.map +1 -1
  125. package/dist/agent-runtime/providers/openrouter-speech.d.ts +90 -0
  126. package/dist/agent-runtime/providers/openrouter-speech.d.ts.map +1 -0
  127. package/dist/agent-runtime/providers/openrouter-spend.d.ts +2 -2
  128. package/dist/agent-runtime/providers/openrouter-spend.d.ts.map +1 -1
  129. package/dist/agent-runtime/providers/openrouter-stream.d.ts.map +1 -1
  130. package/dist/agent-runtime/providers/openrouter-systemone.d.ts +87 -32
  131. package/dist/agent-runtime/providers/openrouter-systemone.d.ts.map +1 -1
  132. package/dist/agent-runtime/providers/openrouter-url.d.ts +7 -1
  133. package/dist/agent-runtime/providers/openrouter-url.d.ts.map +1 -1
  134. package/dist/agent-runtime/providers/openrouter-wire.d.ts +45 -0
  135. package/dist/agent-runtime/providers/openrouter-wire.d.ts.map +1 -0
  136. package/dist/agent-runtime/providers/openrouter.d.ts +1 -3
  137. package/dist/agent-runtime/providers/openrouter.d.ts.map +1 -1
  138. package/dist/agent-runtime/providers/provider-http.d.ts +14 -2
  139. package/dist/agent-runtime/providers/provider-http.d.ts.map +1 -1
  140. package/dist/agent-runtime/providers/provider-json-schema-strip.d.ts.map +1 -1
  141. package/dist/agent-runtime/providers/provider-json-schema.d.ts.map +1 -1
  142. package/dist/agent-runtime/providers/provider-openai-chat-sse.d.ts.map +1 -1
  143. package/dist/agent-runtime/providers/provider-openai-chat-state.d.ts +42 -0
  144. package/dist/agent-runtime/providers/provider-openai-chat-state.d.ts.map +1 -0
  145. package/dist/agent-runtime/providers/provider-usage.d.ts +9 -0
  146. package/dist/agent-runtime/providers/provider-usage.d.ts.map +1 -1
  147. package/dist/agent-runtime/runtime-internals.d.ts +1 -3
  148. package/dist/agent-runtime/runtime-internals.d.ts.map +1 -1
  149. package/dist/agent-runtime/sandbox/sandbox-bubblewrap-args.d.ts +9 -0
  150. package/dist/agent-runtime/sandbox/sandbox-bubblewrap-args.d.ts.map +1 -1
  151. package/dist/agent-runtime/sandbox/sandbox-bubblewrap.d.ts +6 -0
  152. package/dist/agent-runtime/sandbox/sandbox-bubblewrap.d.ts.map +1 -1
  153. package/dist/agent-runtime/sandbox/sandbox-contract.d.ts.map +1 -1
  154. package/dist/agent-runtime/sandbox/sandbox-process-linux.d.ts.map +1 -1
  155. package/dist/agent-runtime/sandbox/sandbox-process-spec.d.ts +5 -1
  156. package/dist/agent-runtime/sandbox/sandbox-process-spec.d.ts.map +1 -1
  157. package/dist/agent-runtime/sandbox/sandbox-process-wrapper.d.ts.map +1 -1
  158. package/dist/agent-runtime/schemas-json-projection.d.ts +29 -0
  159. package/dist/agent-runtime/schemas-json-projection.d.ts.map +1 -0
  160. package/dist/agent-runtime/schemas-message.d.ts +88 -0
  161. package/dist/agent-runtime/schemas-message.d.ts.map +1 -1
  162. package/dist/agent-runtime/schemas-run.d.ts +88 -0
  163. package/dist/agent-runtime/schemas-run.d.ts.map +1 -1
  164. package/dist/agent-runtime/stores/branch-messages.d.ts.map +1 -1
  165. package/dist/agent-runtime/stores/branch-observations.d.ts +42 -42
  166. package/dist/agent-runtime/stores/branch-replay.d.ts +264 -0
  167. package/dist/agent-runtime/stores/branch-replay.d.ts.map +1 -1
  168. package/dist/agent-runtime/stores/conversations.d.ts +88 -0
  169. package/dist/agent-runtime/stores/conversations.d.ts.map +1 -1
  170. package/dist/agent-runtime/stores/sql-rows.d.ts +74 -10
  171. package/dist/agent-runtime/stores/sql-rows.d.ts.map +1 -1
  172. package/dist/agent-runtime/stores/store-driver-contract.d.ts +616 -0
  173. package/dist/agent-runtime/stores/store-driver-contract.d.ts.map +1 -1
  174. package/dist/agent-runtime/stores/store-events.d.ts +1056 -0
  175. package/dist/agent-runtime/stores/store-events.d.ts.map +1 -1
  176. package/dist/agent-runtime/stores/store.d.ts +1232 -0
  177. package/dist/agent-runtime/stores/store.d.ts.map +1 -1
  178. package/dist/agent-runtime/terminal-commit.d.ts +74 -10
  179. package/dist/agent-runtime/terminal-commit.d.ts.map +1 -1
  180. package/dist/agent-runtime/testing/fault-bench.d.ts +5 -1
  181. package/dist/agent-runtime/testing/fault-bench.d.ts.map +1 -1
  182. package/dist/agent-runtime/testing/store-conformance-lifecycle.d.ts +158 -30
  183. package/dist/agent-runtime/testing/store-conformance-lifecycle.d.ts.map +1 -1
  184. package/dist/agent-runtime/testing/store-conformance-support.d.ts +79 -15
  185. package/dist/agent-runtime/testing/store-conformance-support.d.ts.map +1 -1
  186. package/dist/application/diagnostic-journal-contract.d.ts.map +1 -1
  187. package/dist/application/diagnostic-journal-manager.d.ts +1 -1
  188. package/dist/application/diagnostic-journal-manager.d.ts.map +1 -1
  189. package/dist/application/notification-delivery.d.ts.map +1 -1
  190. package/dist/browser/client-executors.d.ts.map +1 -1
  191. package/dist/browser/client-url.d.ts.map +1 -1
  192. package/dist/contract/define.d.ts +3 -7
  193. package/dist/contract/define.d.ts.map +1 -1
  194. package/dist/contract/normalize.d.ts +17 -5
  195. package/dist/contract/normalize.d.ts.map +1 -1
  196. package/dist/entrypoints/agent-executor/acp.js +9 -6
  197. package/dist/entrypoints/agent-executor/claude-sdk.js +26 -25
  198. package/dist/entrypoints/agent-executor/claude.js +13 -12
  199. package/dist/entrypoints/agent-executor/codex.d.ts +2 -1
  200. package/dist/entrypoints/agent-executor/codex.d.ts.map +1 -1
  201. package/dist/entrypoints/agent-executor/codex.js +135 -40
  202. package/dist/entrypoints/agent-executor/testing/claude-sdk.js +5 -4
  203. package/dist/entrypoints/agent-executor/testing.js +23 -18
  204. package/dist/entrypoints/agent-executor.js +8 -8
  205. package/dist/entrypoints/agent-runtime/ai-sdk.d.ts +2 -1
  206. package/dist/entrypoints/agent-runtime/ai-sdk.d.ts.map +1 -1
  207. package/dist/entrypoints/agent-runtime/ai-sdk.js +34 -30
  208. package/dist/entrypoints/agent-runtime/anthropic.js +15 -12
  209. package/dist/entrypoints/agent-runtime/browser.js +13 -8
  210. package/dist/entrypoints/agent-runtime/harness.js +26 -27
  211. package/dist/entrypoints/agent-runtime/openai.js +7 -7
  212. package/dist/entrypoints/agent-runtime/openrouter.d.ts +7 -5
  213. package/dist/entrypoints/agent-runtime/openrouter.d.ts.map +1 -1
  214. package/dist/entrypoints/agent-runtime/openrouter.js +1097 -856
  215. package/dist/entrypoints/agent-runtime/postgres.js +9 -9
  216. package/dist/entrypoints/agent-runtime/realtime.js +9 -8
  217. package/dist/entrypoints/agent-runtime/sandbox.js +167 -139
  218. package/dist/entrypoints/agent-runtime/sqlite/bun.js +10 -10
  219. package/dist/entrypoints/agent-runtime/sqlite/node.js +10 -10
  220. package/dist/entrypoints/agent-runtime/testing.js +9 -9
  221. package/dist/entrypoints/agent-runtime.js +261 -375
  222. package/dist/entrypoints/application/diagnostic-journal.js +14 -10
  223. package/dist/entrypoints/application.js +18 -6
  224. package/dist/entrypoints/cli.js +36 -15
  225. package/dist/entrypoints/contract.js +12 -10
  226. package/dist/entrypoints/geo.js +1 -1
  227. package/dist/entrypoints/handler.js +5 -6
  228. package/dist/entrypoints/http.d.ts +2 -0
  229. package/dist/entrypoints/http.d.ts.map +1 -1
  230. package/dist/entrypoints/http.js +16 -4
  231. package/dist/entrypoints/index.js +26 -35
  232. package/dist/entrypoints/live.js +3 -3
  233. package/dist/entrypoints/node.js +7 -7
  234. package/dist/entrypoints/observability.js +9 -7
  235. package/dist/entrypoints/process.js +3 -3
  236. package/dist/entrypoints/remote.js +5 -5
  237. package/dist/entrypoints/server.js +29 -16
  238. package/dist/entrypoints/telegram/grammy.d.ts +1 -1
  239. package/dist/entrypoints/telegram/grammy.d.ts.map +1 -1
  240. package/dist/entrypoints/telegram/grammy.js +39 -5
  241. package/dist/entrypoints/telegram/screens.js +3 -0
  242. package/dist/entrypoints/telegram.d.ts +1 -1
  243. package/dist/entrypoints/telegram.d.ts.map +1 -1
  244. package/dist/entrypoints/telegram.js +19 -6
  245. package/dist/entrypoints/testing.js +10 -11
  246. package/dist/entrypoints/tools/agent.js +9 -10
  247. package/dist/entrypoints/tools/connections.js +27 -57
  248. package/dist/entrypoints/tools/contract.js +4 -4
  249. package/dist/entrypoints/tools/invoker.js +7 -8
  250. package/dist/entrypoints/tools/mcp.js +9 -10
  251. package/dist/entrypoints/tools/toolkit.js +11 -12
  252. package/dist/entrypoints/tools.js +24 -22
  253. package/dist/entrypoints/tracking/contract.js +1 -1
  254. package/dist/entrypoints/tracking/performance.js +1 -1
  255. package/dist/entrypoints/tracking.js +1 -1
  256. package/dist/{index-3czc3ykr.js → index-08a3qfr8.js} +1 -1
  257. package/dist/index-1psbyyhj.js +21 -0
  258. package/dist/{index-pdcbjd6a.js → index-1yky29qg.js} +6 -3
  259. package/dist/{index-b4c9dpzm.js → index-252den5a.js} +10 -11
  260. package/dist/{index-yhwx4fwk.js → index-26v8hjqm.js} +4 -4
  261. package/dist/{index-xtby8rj3.js → index-28kbdn63.js} +5 -47
  262. package/dist/{index-c24bj2r1.js → index-2wm9b9vs.js} +5 -5
  263. package/dist/{index-ht71v1ag.js → index-32ew02z1.js} +60 -45
  264. package/dist/{index-dm84tsd5.js → index-3kb8dw48.js} +1 -1
  265. package/dist/index-3tb82xr7.js +11 -0
  266. package/dist/{index-nr4fhfn4.js → index-4p2zx593.js} +2 -0
  267. package/dist/{index-grhhsrd5.js → index-4q9tmzea.js} +5 -4
  268. package/dist/{index-mcv7b2n0.js → index-63ctzjp4.js} +497 -495
  269. package/dist/{index-y0a4gt1s.js → index-65p8v81y.js} +3 -2
  270. package/dist/{index-z72vazf5.js → index-6y3eae97.js} +27 -83
  271. package/dist/{index-y0mwkgkf.js → index-8cnfgwg8.js} +1212 -1139
  272. package/dist/{index-mkmep637.js → index-9m1m92rg.js} +1 -1
  273. package/dist/{index-5awtbyns.js → index-9vj869rx.js} +1 -1
  274. package/dist/index-a1rjr381.js +114 -0
  275. package/dist/{index-6kwdfb9m.js → index-akesakvj.js} +23 -4
  276. package/dist/{index-5q0qpw3v.js → index-aqm7e864.js} +23 -8
  277. package/dist/{index-d4at0q09.js → index-b9mj31q7.js} +90 -88
  278. package/dist/{index-baba8ehy.js → index-bjrcbcn2.js} +2 -2
  279. package/dist/{index-fsw9wxk9.js → index-c9j8441q.js} +1 -103
  280. package/dist/{index-wdb5jhas.js → index-d1pdv8qc.js} +1 -1
  281. package/dist/{index-v0j22shs.js → index-d5mhgx72.js} +16 -11
  282. package/dist/{index-73wq9abg.js → index-df5xr2f9.js} +13 -59
  283. package/dist/{index-n9358ydy.js → index-dm50x3by.js} +1 -1
  284. package/dist/{index-zyyerdny.js → index-dmrx8xma.js} +3 -0
  285. package/dist/{index-78da4g74.js → index-dwq6a6sq.js} +17 -13
  286. package/dist/{index-9be3tf6r.js → index-e413q2cj.js} +49 -22
  287. package/dist/{index-57sbckhv.js → index-e4w0sfm1.js} +2 -2
  288. package/dist/{index-g4gstmp1.js → index-ednf2cxs.js} +1 -1
  289. package/dist/{index-84tp547a.js → index-edpkm3k7.js} +29 -97
  290. package/dist/{index-gs0jw0hy.js → index-efbzm2se.js} +3 -3
  291. package/dist/{index-asnd4h2k.js → index-f0dzyskg.js} +27 -4
  292. package/dist/{index-xbb8ysmq.js → index-fatke81t.js} +2 -2
  293. package/dist/{index-d3s070eh.js → index-gj4wdts6.js} +1 -1
  294. package/dist/{index-6nzzj7qr.js → index-gq35s3bm.js} +1 -1
  295. package/dist/index-gvgtmt7a.js +102 -0
  296. package/dist/{index-pd9e8rz4.js → index-gvv7y0s4.js} +1 -1
  297. package/dist/{index-m2b49tvc.js → index-h08xqfw9.js} +20 -21
  298. package/dist/{index-gk6dq9ay.js → index-ha1tv70k.js} +3 -26
  299. package/dist/{index-vebzvse6.js → index-jy907kcs.js} +24 -1
  300. package/dist/{index-q86qnzzf.js → index-k5azb3v3.js} +8 -25
  301. package/dist/{index-qcy8et93.js → index-kaq9nb7h.js} +6 -6
  302. package/dist/{index-vse7x1qt.js → index-knqye3gv.js} +1 -1
  303. package/dist/{index-tav72wz5.js → index-ks4rhtcc.js} +5 -0
  304. package/dist/{index-bvpevwt6.js → index-mtpcax6d.js} +210 -205
  305. package/dist/{index-7qza24g1.js → index-px9r6wv1.js} +1 -1
  306. package/dist/{index-x6sp5vpa.js → index-q4tr9vnf.js} +1 -1
  307. package/dist/{index-hce3hbdg.js → index-qj0sq69b.js} +6 -2
  308. package/dist/{index-de7b0kvz.js → index-r9w7wfgn.js} +2 -2
  309. package/dist/{index-8vzh5wpv.js → index-rw1caff2.js} +14 -26
  310. package/dist/index-s8af9jqw.js +6 -0
  311. package/dist/{index-bgj9hbm3.js → index-sdppfbrh.js} +30 -16
  312. package/dist/{index-aacwkve4.js → index-sjq4akrx.js} +3 -5
  313. package/dist/{index-fec05c9k.js → index-ta0e2daw.js} +9 -7
  314. package/dist/{index-5dxgx3yj.js → index-tcv71frn.js} +1 -1
  315. package/dist/{index-1zy31r3b.js → index-v92djygb.js} +1 -1
  316. package/dist/{index-c0yym4a0.js → index-w7e402wx.js} +11 -105
  317. package/dist/{index-9f60gnfn.js → index-xaa3603f.js} +4 -11
  318. package/dist/index-xrbrvn15.js +147 -0
  319. package/dist/{index-ac3rfec5.js → index-y6wzzk2e.js} +21 -1
  320. package/dist/{index-3d2c45jn.js → index-yjx5jna7.js} +2 -2
  321. package/dist/{index-j3r7r1mh.js → index-yv7d6tav.js} +1 -1
  322. package/dist/{index-wsv11dhg.js → index-zagc12j1.js} +5 -5
  323. package/dist/{index-npfdymav.js → index-zqc64g69.js} +3 -3
  324. package/dist/{index-rkphknhx.js → index-zthekmrt.js} +2 -2
  325. package/dist/internal/json-stringify.d.ts +37 -0
  326. package/dist/internal/json-stringify.d.ts.map +1 -0
  327. package/dist/internal/loopback-host.d.ts +8 -0
  328. package/dist/internal/loopback-host.d.ts.map +1 -0
  329. package/dist/internal/own-member.d.ts +7 -0
  330. package/dist/internal/own-member.d.ts.map +1 -0
  331. package/dist/internal/request.d.ts +17 -8
  332. package/dist/internal/request.d.ts.map +1 -1
  333. package/dist/internal/secret-shapes.d.ts +33 -4
  334. package/dist/internal/secret-shapes.d.ts.map +1 -1
  335. package/dist/json-schema/dialect.d.ts.map +1 -1
  336. package/dist/json-schema/keywords.d.ts +25 -6
  337. package/dist/json-schema/keywords.d.ts.map +1 -1
  338. package/dist/json-schema/string-format.d.ts.map +1 -1
  339. package/dist/live/events.d.ts.map +1 -1
  340. package/dist/live/watch-client.d.ts.map +1 -1
  341. package/dist/live/watch-delta.d.ts.map +1 -1
  342. package/dist/observability/context.d.ts +4 -3
  343. package/dist/observability/context.d.ts.map +1 -1
  344. package/dist/observability/sanitize.d.ts.map +1 -1
  345. package/dist/observability/secret-values.d.ts +0 -9
  346. package/dist/observability/secret-values.d.ts.map +1 -1
  347. package/dist/server/context.d.ts +3 -2
  348. package/dist/server/context.d.ts.map +1 -1
  349. package/dist/server/error-hook.d.ts +4 -3
  350. package/dist/server/error-hook.d.ts.map +1 -1
  351. package/dist/server/event-bus.d.ts.map +1 -1
  352. package/dist/server/file.d.ts +11 -3
  353. package/dist/server/file.d.ts.map +1 -1
  354. package/dist/server/handler-state.d.ts +2 -2
  355. package/dist/server/handler-state.d.ts.map +1 -1
  356. package/dist/server/middleware/jwt.d.ts +12 -1
  357. package/dist/server/middleware/jwt.d.ts.map +1 -1
  358. package/dist/server/middleware/trust-fence.d.ts +4 -0
  359. package/dist/server/middleware/trust-fence.d.ts.map +1 -1
  360. package/dist/server/multipart.d.ts +2 -3
  361. package/dist/server/multipart.d.ts.map +1 -1
  362. package/dist/server/raw.d.ts.map +1 -1
  363. package/dist/server/request-body.d.ts +12 -1
  364. package/dist/server/request-body.d.ts.map +1 -1
  365. package/dist/server/request-completion.d.ts.map +1 -1
  366. package/dist/server/types.d.ts +14 -9
  367. package/dist/server/types.d.ts.map +1 -1
  368. package/dist/telegram/crypto.d.ts.map +1 -1
  369. package/dist/telegram/init-data.d.ts +4 -4
  370. package/dist/telegram/init-data.d.ts.map +1 -1
  371. package/dist/telegram/outbound-cost.d.ts.map +1 -1
  372. package/dist/telegram/screens/test-chat.d.ts.map +1 -1
  373. package/dist/telegram/widget-api.d.ts +85 -13
  374. package/dist/telegram/widget-api.d.ts.map +1 -1
  375. package/dist/telegram/widget.d.ts +46 -2
  376. package/dist/telegram/widget.d.ts.map +1 -1
  377. package/dist/tools/cli/args-classify.d.ts +4 -74
  378. package/dist/tools/cli/args-classify.d.ts.map +1 -1
  379. package/dist/tools/cli/args-framework.d.ts +79 -0
  380. package/dist/tools/cli/args-framework.d.ts.map +1 -0
  381. package/dist/tools/cli/args-scan.d.ts.map +1 -1
  382. package/dist/tools/cli/args-tokens.d.ts.map +1 -1
  383. package/dist/tools/cli/checkpoint.d.ts +5 -0
  384. package/dist/tools/cli/checkpoint.d.ts.map +1 -1
  385. package/dist/tools/cli/stream.d.ts.map +1 -1
  386. package/dist/tools/connections/foreign-schema-join.d.ts.map +1 -1
  387. package/dist/tools/connections/openapi.d.ts.map +1 -1
  388. package/dist/tools/connections/runtime.d.ts.map +1 -1
  389. package/dist/tools/execute-handler.d.ts +24 -0
  390. package/dist/tools/execute-handler.d.ts.map +1 -0
  391. package/dist/tools/execute.d.ts.map +1 -1
  392. package/dist/tools/mcp/round.d.ts.map +1 -1
  393. package/dist/tools/schema/coerce.d.ts.map +1 -1
  394. package/dist/tools/schema/flatten.d.ts.map +1 -1
  395. package/dist/tools/schema/inline-references.d.ts.map +1 -1
  396. package/dist/tools/schema/nesting-limit.d.ts.map +1 -1
  397. package/dist/tools/schema/presentation.d.ts.map +1 -1
  398. package/dist/tracking/privacy.d.ts.map +1 -1
  399. package/llms/agent-runtime-openrouter.txt +10 -9
  400. package/llms/agent-runtime-sandbox.txt +50 -11
  401. package/llms/agent-runtime-testing.txt +1 -1
  402. package/llms/agent-runtime.2.txt +9 -6
  403. package/llms/agent-runtime.3.txt +2 -2
  404. package/llms/agent-runtime.4.txt +11 -5
  405. package/llms/agent-runtime.5.txt +2 -2
  406. package/llms/agent-runtime.txt +297 -36
  407. package/llms/application.2.txt +6 -3
  408. package/llms/application.3.txt +2 -1
  409. package/llms/application.txt +7 -2
  410. package/llms/http.txt +1 -1
  411. package/llms/live.txt +3 -1
  412. package/llms/observability.txt +16 -9
  413. package/llms/server.2.txt +13 -8
  414. package/llms/server.4.txt +23 -11
  415. package/llms/server.5.txt +5 -5
  416. package/llms/server.txt +54 -1
  417. package/llms/spend.txt +1 -0
  418. package/llms/stitchkit.2.txt +4 -2
  419. package/llms/stitchkit.txt +113 -93
  420. package/llms/telegram-grammy.txt +3 -2
  421. package/llms/telegram.2.txt +3 -1
  422. package/llms/telegram.txt +35 -10
  423. package/llms/upgrading-0.128.0-0.129.0.txt +175 -0
  424. package/llms/{upgrading-0.128.0-0.135.0.txt → upgrading-0.130.0-0.136.0.txt} +353 -169
  425. package/llms/upgrading.txt +2 -1
  426. package/llms-full.txt +1021 -223
  427. package/llms.txt +14 -13
  428. package/package.json +6 -6
  429. package/dist/agent-runtime/loop/deferred-tools-internal.d.ts +0 -19
  430. package/dist/agent-runtime/loop/deferred-tools-internal.d.ts.map +0 -1
  431. package/dist/agent-runtime/loop/run-complete-retry.d.ts +0 -24
  432. package/dist/agent-runtime/loop/run-complete-retry.d.ts.map +0 -1
  433. package/dist/agent-runtime/loop/run-model-attempts.d.ts +0 -6
  434. package/dist/agent-runtime/loop/run-model-attempts.d.ts.map +0 -1
  435. package/dist/index-sznqf8fx.js +0 -20
  436. /package/dist/{index-fthw8dwa.js → index-4gbybjg6.js} +0 -0
@@ -75,32 +75,77 @@ bun add ai@^7
75
75
 
76
76
  ## Minimal composition
77
77
 
78
+ The whole loop in one file: a protocol, a model, a prompt, contract tools and one turn. It runs
79
+ as written — `createScriptedModelDriver` from `stitchkit/agent-runtime/testing` stands in for
80
+ the provider, so `bun run agent.ts` needs no key and no network:
81
+
78
82
  ```ts
83
+ // agent.ts
79
84
  import { z } from 'zod'
85
+ import { defineContract } from 'stitchkit'
86
+ import { AppError, implement } from 'stitchkit/server'
80
87
  import {
81
- AgentContextOverflowError,
82
88
  composeAgentPrompt,
83
89
  createAgentRuntime,
84
90
  createMemoryAgentRuntimeStore,
85
91
  defineAgentProtocol,
86
92
  defineModelRegistry,
87
93
  } from 'stitchkit/agent-runtime'
88
- import { openRouterProvider } from 'stitchkit/agent-runtime/openrouter'
89
- import { composeToolLifecycle, mountAgentTools } from 'stitchkit/tools'
94
+ import { createScriptedModelDriver } from 'stitchkit/agent-runtime/testing'
95
+ import { composeToolLifecycle, mountAgentTools, type ToolGate } from 'stitchkit/tools'
96
+
97
+ // The agent's tools are an ordinary contract; the endpoint `lookup` of `orders` is the tool `lookup_order`.
98
+ const orders = defineContract({ prefix: 'orders' }, {
99
+ lookup: {
100
+ method: 'GET',
101
+ path: '/:id',
102
+ desc: 'Look up an order by id',
103
+ params: z.object({ id: z.string() }),
104
+ output: z.object({ id: z.string(), status: z.string() }),
105
+ },
106
+ })
107
+ const service = implement(orders, {
108
+ lookup: (ctx) => ({ id: ctx.params.id, status: 'shipped' }),
109
+ })
110
+
111
+ // Who may call them: your auth rule as a tool gate (`createAuthHook` builds one too).
112
+ const authLifecycle: ToolGate = {
113
+ beforeHandle: (ctx) => {
114
+ if (typeof ctx.userId !== 'string') throw new AppError('UNAUTHORIZED')
115
+ },
116
+ }
90
117
 
91
118
  const protocol = defineAgentProtocol({
92
119
  context: z.object({ userId: z.string() }),
93
120
  inputMetadata: z.object({}),
94
121
  })
95
122
 
123
+ // Two scripted model steps: call the tool, then answer.
124
+ const usage = (input: number, output: number) => ({
125
+ inputTokens: { value: input, provenance: 'provider-reported' as const },
126
+ outputTokens: { value: output, provenance: 'provider-reported' as const },
127
+ })
128
+ const scripted = createScriptedModelDriver({
129
+ steps: [
130
+ [
131
+ { type: 'tool-call', toolCallId: 'call-1', toolName: 'lookup_order', input: '{"id":"42"}' },
132
+ { type: 'finish', finishReason: 'tool-calls', usage: usage(20, 5) },
133
+ ],
134
+ [
135
+ { type: 'text-delta', id: 'text-1', delta: 'Order 42 has shipped.' },
136
+ { type: 'finish', finishReason: 'stop', usage: usage(40, 6) },
137
+ ],
138
+ ],
139
+ })
140
+
96
141
  const models = defineModelRegistry({
97
142
  providers: {
98
- openrouter: openRouterProvider({ apiKey: env.OPENROUTER_API_KEY }),
143
+ scripted: { create: () => scripted },
99
144
  },
100
145
  models: {
101
146
  fast: {
102
- provider: 'openrouter',
103
- modelId: 'provider/model',
147
+ provider: 'scripted',
148
+ modelId: 'scripted-model',
104
149
  contextWindow: 128_000,
105
150
  capabilities: ['tools'],
106
151
  },
@@ -119,7 +164,9 @@ const runtime = createAgentRuntime({
119
164
  protocol,
120
165
  store: createMemoryAgentRuntimeStore(),
121
166
  models: {
122
- preflight: () => models.preflight('fast', ['tools']),
167
+ preflight: () => {
168
+ models.preflight('fast', ['tools']) // throws when the model cannot serve the turn
169
+ },
123
170
  resolve: () => models.resolve('fast', ['tools']),
124
171
  },
125
172
  prompt: ({ context, signal, model }) =>
@@ -142,16 +189,14 @@ const runtime = createAgentRuntime({
142
189
  runs: { inputPolicy: 'interrupt', coalescePending: true },
143
190
  loop: {
144
191
  idleTimeoutMs: 60_000,
145
- prepareStep: ({ context, steps }) => ({
146
- activeTools: steps.some((step) => step.toolCalls.length > 0)
147
- ? ['lookup']
148
- : ['lookup', 'discover'],
192
+ prepareStep: ({ context }) => ({
193
+ activeTools: ['lookup_order'],
149
194
  instructions: `Current account: ${context.userId}`,
150
195
  }),
151
196
  stopPolicies: [
152
197
  {
153
- name: 'repeated-tool-error',
154
- when: ({ steps }) => hasRepeatedToolError(steps),
198
+ name: 'too-many-tool-steps',
199
+ when: ({ steps }) => steps.filter((step) => step.toolCalls.length > 0).length >= 5,
155
200
  },
156
201
  ],
157
202
  },
@@ -161,7 +206,7 @@ const ticket = runtime.submit({
161
206
  conversationId: 'conversation-id',
162
207
  idempotencyKey: 'request-id',
163
208
  context: { userId: 'user-id' },
164
- parts: [{ type: 'text', text: 'Hello' }],
209
+ parts: [{ type: 'text', text: 'Where is order 42?' }],
165
210
  recordIds: {
166
211
  inputMessageId: 'user-message-id',
167
212
  runId: 'run-id',
@@ -169,11 +214,36 @@ const ticket = runtime.submit({
169
214
  },
170
215
  })
171
216
 
172
- const admission = await ticket.admission
173
217
  await ticket.accepted
174
218
  const terminal = await ticket.result
219
+ console.log(terminal.reason, terminal.message.parts) // 'success', the tool call, its result, the answer
220
+ await runtime.close()
175
221
  ```
176
222
 
223
+ For a real model, register its provider under the same key and keep everything else:
224
+
225
+ ```ts
226
+ import { defineModelRegistry } from 'stitchkit/agent-runtime'
227
+ import { openRouterProvider } from 'stitchkit/agent-runtime/openrouter'
228
+
229
+ const models = defineModelRegistry({
230
+ providers: {
231
+ openrouter: openRouterProvider({ apiKey: () => process.env.OPENROUTER_API_KEY ?? '' }),
232
+ },
233
+ models: {
234
+ fast: {
235
+ provider: 'openrouter',
236
+ modelId: 'provider/model', // a live tool-capable model id from the OpenRouter catalog
237
+ contextWindow: 128_000,
238
+ capabilities: ['tools'],
239
+ },
240
+ },
241
+ })
242
+ ```
243
+
244
+ Both blocks are type-checked, and the first one run, by
245
+ `packages/core/tests/guide-first-path-snippets.test.ts`.
246
+
177
247
  A stop policy's `when` receives the completed `AgentStepResult[]` steps so far together with the
178
248
  same run context `prepareStep` gets — `context`, `run`, `signal`, `toolFenceLifecycle` and
179
249
  `contextUsage` — typed by the runtime's `CONTEXT`. A rule that depends on its own run (a receipt
@@ -181,6 +251,40 @@ bound to the run's request, a per-tenant limit) reads it there; it needs no map
181
251
  by `runId`. The first policy to return `true` ends the run as `policy_stop` with its `name` as
182
252
  `policyName`.
183
253
 
254
+ ### When a run ends `runtime_failure`
255
+
256
+ A run ends `runtime_failure` when the composition fails it — `tools`, `prompt` or a hook throws, a
257
+ checkpoint cannot be written — and `provider_failure` when the model call does. The result a
258
+ caller awaits says which, never why: `terminal.reason` and the failed message travel to clients,
259
+ and a raw cause can carry a provider's response body, a path or another user's data. The cause goes
260
+ to the operator channel, `observe`, and only to a sink that asks for it with `includeInternalCause`:
261
+
262
+ ```ts
263
+ import { createAgentObservability, createAgentRuntime } from 'stitchkit/agent-runtime'
264
+
265
+ const observe = createAgentObservability({
266
+ includeInternalCause: true, // operator-only: keep this sink's output away from clients
267
+ write: (event) => {
268
+ if (event.type === 'run-terminal' && event.internalCause !== undefined) {
269
+ console.error(`run ${event.runId} ended ${event.terminalReason}:`, event.internalCause)
270
+ }
271
+ },
272
+ })
273
+
274
+ const runtime = createAgentRuntime({
275
+ ...composition, // protocol, store, models, prompt and tools, as in the minimal composition
276
+ observe,
277
+ })
278
+
279
+ const ticket = runtime.submit(input)
280
+ const terminal = await ticket.result
281
+ await observe.flush() // the sink is bounded and asynchronous; flush before reading it or exiting
282
+ ```
283
+
284
+ Without `observe`, nothing reports the cause. A composition missing `protocol`, `store`,
285
+ `models.resolve`, `prompt` or `tools` does not get that far: `createAgentRuntime` throws a
286
+ `TypeError` naming them. `packages/core/tests/agent-runtime-failure-cause.test.ts` holds both.
287
+
184
288
  ## Native model port, providers and driver composition
185
289
 
186
290
  Every model call crosses one single-step port — `AgentModelDriver.stream(request, signal)` — with
@@ -216,6 +320,14 @@ freshly per stream call and reporting server `response.timestamp` alongside `mod
216
320
  ≤ 4 cache breakpoints with TTL-order checks, `output_config.format` JSON Schema (refusing
217
321
  schemaless `json-object`), and retryable `529 overloaded_error` classification.
218
322
 
323
+ A Chat Completions stream is complete only when it says so: `data: [DONE]`, or a usage chunk
324
+ after `finish_reason` — the ending [OpenRouter's streaming reference](https://openrouter.ai/docs/api_reference/streaming)
325
+ describes. An OpenAI-compatible server behind `openRouterProvider({ baseUrl })` that closes the
326
+ connection after `finish_reason` with neither cannot be told apart from a cut that lost the usage
327
+ chunk, so the step fails with a retryable `AgentProviderStreamCutError` instead of finishing with
328
+ unreported usage. Such a server has to send `data: [DONE]` (or usage, e.g. on
329
+ `stream_options.include_usage`); there is no option to accept the bare close.
330
+
219
331
  For an existing AI SDK (`LanguageModelV4` from `ai@7`) model or `ToolSet`, import `fromAiSdkModel` and `fromAiSdkTools` from
220
332
  `stitchkit/agent-runtime/ai-sdk`. Both adapt directly onto `AgentModelDriver` and `AgentToolSet`
221
333
  (driving `model.doStream()` without importing `streamText` or `generateText`) and normalize legacy
@@ -240,15 +352,20 @@ const guarded = composeModelDrivers(base, [admissionDecorator, telemetryDecorato
240
352
  (`https://openrouter.ai/api/v1`), `OpenRouterFetch`, generic non-chat transport helpers
241
353
  (`openRouterRequestJson` and `openRouterRequestStream`), and typed modality clients — all
242
354
  peer-free, Web Fetch-clean, redirect-safe (`redirect: 'error'` plus response-level refusal), and
243
- compatible with `gateway.fetchFor('openrouter')` and custom `baseUrl` overrides:
244
-
245
- - **Decision models (`POST /systemone`):** `openRouterSystemOne` sends `noul`, `choice`, and
246
- `score` questions over text or structured `state` and returns calibrated probability answers plus
247
- `generationId` and `costUsd`.
355
+ compatible with `gateway.fetchFor('openrouter')` and custom `baseUrl` overrides. Chat, catalog,
356
+ spend and every non-chat client share one transport: one `baseUrl` rule (`https:`, or `http:` to a
357
+ loopback host only; no credentials, query or fragment; the API root, not an endpoint URL), one injected `fetch` option, and one error class,
358
+ `AgentProviderError` with `statusCode`, for every non-2xx answer:
359
+
360
+ - **Decision models (`POST /systemone`):** `openRouterSystemOne` sends `noul`, `choice`,
361
+ `score` and image `box` questions over text or structured `state` (with image `assets`,
362
+ `sessionId` and `user`) and returns calibrated probability answers, bounding boxes and
363
+ per-question refusals plus `generationId` and `costUsd`.
248
364
  - **Audio (`POST /audio/transcriptions` and `POST /audio/speech`):** `openRouterAudioTranscription`
249
365
  accepts `audio: { kind: 'base64' | 'url' | 'file' }` (JSON or automatic `FormData` multipart
250
366
  without manual `Content-Type`), `verbose_json`, `timestampGranularities`, and `diarize`;
251
- `openRouterAudioSpeech` streams synthesized audio bytes (`ReadableStream<Uint8Array>`).
367
+ `openRouterAudioSpeech` streams synthesized audio bytes (`ReadableStream<Uint8Array>`), takes
368
+ text or multi-speaker turns, and with `outputDelivery: 'url'` returns a signed download URL instead.
252
369
  - **Images & Video (`POST /images` and `/videos`):** `openRouterGenerateImages` targets OpenRouter's
253
370
  Unified Image API (`b64_json` or signed `url`), while `openRouterSubmitVideo`,
254
371
  `openRouterGetVideo`, and `openRouterDownloadVideo` cover the async submit → poll → stream
@@ -260,6 +377,120 @@ compatible with `gateway.fetchFor('openrouter')` and custom `baseUrl` overrides:
260
377
  management or future endpoints (`/credits`, `/key`, `/responses`, `/images/models`, `/videos/models`)
261
378
  without custom wrappers.
262
379
 
380
+ `createOpenRouterClient` states the key, `baseUrl`, `fetch`, headers and attribution once and returns
381
+ every function above as a method of the same name (`audioTranscription`, `audioSpeech`, `systemOne`,
382
+ `generateImages`, `submitVideo`, `getVideo`, `downloadVideo`, `embeddings`, `rerank`, `requestJson`,
383
+ `requestStream`); a value passed to one call overrides the client's, except `headers` and
384
+ `providerApiKeys`, which merge key by key with the call's entries winning. An invalid `baseUrl` or
385
+ static `apiKey` is refused when the client is created. Every example below is
386
+ type-checked against the current exports by `packages/core/tests/openrouter-guide-snippets.test.ts`.
387
+
388
+ Speech to text — inline audio, or a URL the provider downloads:
389
+
390
+ ```ts
391
+ import { createOpenRouterClient } from 'stitchkit/agent-runtime/openrouter';
392
+
393
+ const openRouter = createOpenRouterClient({
394
+ apiKey: () => process.env.OPENROUTER_API_KEY ?? '',
395
+ appName: 'Minutes',
396
+ });
397
+
398
+ const fromBytes = await openRouter.audioTranscription({
399
+ model: 'openai/whisper-large-v3',
400
+ audio: { kind: 'base64', data: 'UklGRiQA...', format: 'wav' },
401
+ responseFormat: 'verbose_json',
402
+ diarize: true,
403
+ });
404
+ for (const word of fromBytes.words ?? []) console.log(word.speaker, word.speakerLabel, word.word);
405
+
406
+ const fromUrl = await openRouter.audioTranscription({
407
+ model: 'elevenlabs/scribe-v2',
408
+ audio: { kind: 'url', url: 'https://example.com/meeting.mp3' },
409
+ });
410
+ console.log(fromUrl.text, fromUrl.costUsd);
411
+ ```
412
+
413
+ Audio by URL depends on the model, and OpenRouter publishes which models accept it neither in the
414
+ endpoints API nor in its documentation. A model that cannot fetch a URL answers HTTP 400 "The
415
+ selected model does not support audio from a URL. Send the audio inline instead." before any charge;
416
+ the call rejects with `AgentProviderError` (`statusCode: 400`) carrying that message. Checked on
417
+ 2026-11-30: `elevenlabs/scribe-v2` transcribed a URL, while `openai/whisper-large-v3-turbo`,
418
+ `deepgram/nova-3`, `mistralai/voxtral-mini-3b-2507` and `assemblyai/universal-3-5-pro` refused it —
419
+ send their audio as `base64` or `file`.
420
+
421
+ Text to speech — streamed bytes, or a signed URL OpenRouter keeps for 24 hours:
422
+
423
+ ```ts
424
+ import { createOpenRouterClient } from 'stitchkit/agent-runtime/openrouter';
425
+
426
+ const openRouter = createOpenRouterClient({ apiKey: () => process.env.OPENROUTER_API_KEY ?? '' });
427
+
428
+ const streamed = await openRouter.audioSpeech({
429
+ model: 'mistralai/voxtral-mini-tts-2603',
430
+ input: 'Hello world',
431
+ voice: 'en_paul_neutral',
432
+ responseFormat: 'mp3',
433
+ });
434
+ const mp3 = new Uint8Array(await new Response(streamed.audio).arrayBuffer());
435
+
436
+ const stored = await openRouter.audioSpeech({
437
+ model: 'google/gemini-3.8-flash-lite-tts',
438
+ input: [
439
+ { text: "How's it going today, Jane?", voice: 'Kore' },
440
+ { text: 'Not too bad, how about you?', voice: 'Puck', instructions: 'tired, yawning' },
441
+ ],
442
+ responseFormat: 'wav',
443
+ outputDelivery: 'url',
444
+ });
445
+ console.log(mp3.byteLength);
446
+ // Zero-data-retention makes OpenRouter stream even when a URL was asked for: read those bytes too.
447
+ if (stored.delivery === 'url') console.log(stored.url, new Date(stored.expiresAt * 1000));
448
+ else {
449
+ const wav = new Uint8Array(await new Response(stored.audio).arrayBuffer());
450
+ console.log(wav.byteLength, stored.contentType);
451
+ }
452
+ ```
453
+
454
+ Video — submit, poll, download:
455
+
456
+ ```ts
457
+ import { createOpenRouterClient } from 'stitchkit/agent-runtime/openrouter';
458
+
459
+ const openRouter = createOpenRouterClient({ apiKey: () => process.env.OPENROUTER_API_KEY ?? '' });
460
+
461
+ const job = await openRouter.submitVideo({
462
+ model: 'google/veo-3.1',
463
+ prompt: 'A paper boat drifting down a rain gutter',
464
+ duration: 4,
465
+ });
466
+ let state = await openRouter.getVideo({ jobId: job.id });
467
+ while (state.jobStatus !== 'completed' && state.jobStatus !== 'failed') {
468
+ await new Promise((resolve) => setTimeout(resolve, 5_000));
469
+ state = await openRouter.getVideo({ jobId: job.id });
470
+ }
471
+ if (state.jobStatus === 'completed') {
472
+ const video = await openRouter.downloadVideo({ jobId: job.id });
473
+ console.log(video.contentType, state.costUsd);
474
+ }
475
+ ```
476
+
477
+ Any other endpoint — `requestJson` with a Zod `schema` types and validates the answer:
478
+
479
+ ```ts
480
+ import { createOpenRouterClient } from 'stitchkit/agent-runtime/openrouter';
481
+ import { z } from 'zod';
482
+
483
+ const openRouter = createOpenRouterClient({ apiKey: () => process.env.OPENROUTER_API_KEY ?? '' });
484
+
485
+ const credits = await openRouter.requestJson({
486
+ path: '/credits',
487
+ schema: z.object({
488
+ data: z.object({ total_credits: z.number(), total_usage: z.number() }),
489
+ }),
490
+ });
491
+ console.log(credits.data.data.total_credits - credits.data.data.total_usage);
492
+ ```
493
+
263
494
  ### OpenRouter catalog snapshots, pricing ceilings, and cache
264
495
 
265
496
  `stitchkit/agent-runtime/openrouter` also provides a peer-free, Web Fetch-clean catalog layer for
@@ -323,6 +554,20 @@ with `mountAgentTools` from `stitchkit/tools` (including the single-argument
323
554
  `mountAgentTools({ runtimeTools, access })` form when no HTTP service contracts are mounted). Both
324
555
  return `AgentTool` / `AgentToolSet` carrying JSON Schema 2020-12 `inputSchema`, Zod `parseInput`,
325
556
  optional `needsApproval`, `onInputAvailable`, and `toModelOutput` returning `AgentToolModelOutput`.
557
+ Without `toModelOutput`, a tool's output reaches the model, and every later turn that reads the run
558
+ back, as `JSON.stringify` writes it: a field left `undefined` drops its key and a `Date` becomes its
559
+ ISO string; a `toModelOutput` JSON value is read the same way. An output `JSON.stringify` cannot
560
+ write (a BigInt, a cycle, a throwing `toJSON`) fails the call with an `AgentToolError` naming the
561
+ tool and the field and saying the tool ran, so the model does not take it for a call that never
562
+ happened. That holds with `toModelOutput` too: a branch presents the result again from the
563
+ recorded output.
564
+
565
+ What `toModelOutput` showed the model is recorded beside the result (`tool-result.modelOutput`),
566
+ and a later turn sends that again rather than calling `toModelOutput` a second time: history is
567
+ what the model read, and it does not change when the function does. Three records are presented
568
+ anew, from the JSON form of the output — where a `Date` is its ISO string: one written before the
569
+ field existed, one whose model output held a `file` part, and a branched one. To present recorded
570
+ results differently on purpose, pass `resolveToolModelOutput` to the history projection.
326
571
 
327
572
  When an operation needs one or a few model steps without a durable conversation store — structured
328
573
  extraction, classification, a bounded tool loop, or standalone streaming — call `completeText`,
@@ -332,13 +577,13 @@ extraction, classification, a bounded tool loop, or standalone streaming — cal
332
577
  - Pass `onPart` on `completeText` / `completeObject` or use `streamComplete` to consume
333
578
  `text-delta`, `reasoning-delta`, `tool-input-start`, `tool-call`, `tool-result` (preliminary and
334
579
  final), `tool-error`, `attempt-reset`, `finish-step`, and `finish` events over a bounded async
335
- iterable without a store. `streamComplete().parts` is single-use with a 64-part buffer: once
336
- iterated (`for await` or `parts[Symbol.asyncIterator]()`), backpressure pauses the producer when
337
- the buffer is full. If `parts` is never iterated, up to 64 parts buffer for late attachment and
338
- any overflow clears the queue without blocking so awaiting `result` alone (with or without
339
- `onPart`) completes in bounded memory; attempting to iterate `parts` after an unsubscribed
340
- overflow waits for completion and then propagates the run failure or throws an overflow `Error`
341
- instead of silently returning truncated parts.
580
+ iterable without a store. How `streamComplete` is read is stated, never guessed from when
581
+ `parts` is first touched. By default (`parts: 'iterate'`) `parts` is single-use with a 64-part
582
+ buffer that backpressures from the first part: iteration may start late — after other awaits —
583
+ and the run pauses at the full buffer until it does, losing nothing. Awaiting `result` alone in
584
+ this mode waits while the buffer is full, so a caller that wants only the result says so with
585
+ `parts: 'ignore'`: no buffer is kept, `result` (and `onPart`) carry the run, and iterating
586
+ `parts` throws a `TypeError`. `completeText` with `onPart` is the same result-only path.
342
587
  - Standalone completions have no durable approval loop, so any tool with `needsApproval: true` (or
343
588
  a `needsApproval` predicate returning `true`) is preflighted across every validated call in the
344
589
  step and fails closed with `AgentToolApprovalError` (`reason: 'approval-unsupported'`) before any
@@ -347,11 +592,22 @@ extraction, classification, a bounded tool loop, or standalone streaming — cal
347
592
  `toolDependencies`, `onPredecessorFailure`) on `completeText` / `streamComplete` /
348
593
  `completeObject` to enforce the same batch-refusal, cap, and dependency-ordering policies as
349
594
  `createAgentRuntime` (durable stream-only `stepBarriers` keys fail fast with a `TypeError`).
350
- - Pass `retry` (`AgentRetryPolicy`) and optional `onAttemptDiscarded` for stateless retry with
351
- `Retry-After` handling; exhausting retries throws `AgentRetryExhaustedError` carrying every failed
352
- attempt, `lastError`, and accumulated billable `usage`.
595
+ - Pass `retry` (`AgentRetryPolicy`) and optional `onAttemptDiscarded` for stateless retry. As in
596
+ `createAgentRuntime`, the unit of a retry is the model call of one step: earlier steps and the
597
+ tools they ran stand, and a call whose stream already carried a provider-executed tool call or
598
+ a tool result is not repeated. Exhausting retries throws `AgentRetryExhaustedError` carrying every failed attempt, `lastError`,
599
+ and accumulated billable `usage`. The wait before each retry is exactly what `delayMs` returns:
600
+ the runtime reads no `Retry-After` itself, so a policy that should honour one returns
601
+ `failure.retryAfterMs` (the provider's `Retry-After` or `retry-after-ms`, in milliseconds) and
602
+ bounds the total with `maxRetryDurationMs` — a retry whose wait would cross it is not scheduled.
603
+ The same policy serves `loop.retry`. Example:
604
+ [`packages/core/examples/agent-runtime/retry-after-policy.ts`](../../packages/core/examples/agent-runtime/retry-after-policy.ts).
353
605
  - Pass `stopPolicies` (`AgentCompleteStopPolicy[]`) and `idleTimeoutMs` to bound multi-step loops
354
- and stalled streams (suspending the idle timer during local tool execution).
606
+ and stalled streams (suspending the idle timer during local tool execution). A deadline that
607
+ fires while your consumer holds a part — a full `streamComplete().parts` buffer nobody reads, a
608
+ slow `onPart` — still ends the call with a `timeout` `AgentProviderError`, but one without
609
+ provider origin: `retry` never calls the provider again for it. `idleTimeoutMs`
610
+ defaults to 60 000, the runtime's default; `null` disables it.
355
611
 
356
612
  ```ts
357
613
  import { z } from 'zod'
@@ -449,7 +705,10 @@ const runtime = createAgentRuntime({
449
705
  context: runContext.context,
450
706
  access: { gate: composeToolLifecycle(authLifecycle, runContext.toolFenceLifecycle) },
451
707
  }),
452
- loop: { prepareStep: deferred.prepareStep(applicationPrepareStep) },
708
+ loop: {
709
+ prepareStep: deferred.prepareStep(applicationPrepareStep),
710
+ repairToolCall: deferred.repairToolCall(applicationRepairToolCall),
711
+ },
453
712
  })
454
713
  ```
455
714
 
@@ -468,9 +727,11 @@ The latest valid same-run search replaces the earlier selection; parallel
468
727
  searches in one step merge in call order. Recovery reconstructs it, while a
469
728
  different run or finite surface cannot inherit it. Known inactive calls take a
470
729
  recoverable `SEARCH_REQUIRED` search round; unknown names still fail. Inactive-call
471
- repair travels with the tool set returned by `deferred.mount()` — so wrapping
472
- `deferred.prepareStep()` or calling `completeText` preserves it automatically — and can
473
- also be composed explicitly with `deferred.repairToolCall(applicationRepairToolCall)`. The
730
+ repair is the hook `deferred.repairToolCall(applicationRepairToolCall?)` returns, passed as
731
+ `loop.repairToolCall` (runtime) or `repairToolCall` (`completeText` / `streamComplete`); the
732
+ application's hook runs first. Nothing is attached to the mounted tools, so spreading them or a
733
+ tool, or merging two surfaces' mounts, keeps repair exact: two surfaces compose as
734
+ `first.repairToolCall(second.repairToolCall())`, each repairing only its own catalog. The
474
735
  runtime marks that round with `reason: 'inactive_call'` beside the exact tool
475
736
  name. The field is the runtime's to write; a model that sets it anyway gets
476
737
  the same `SEARCH_REQUIRED` answer with an exact name, and with a query in words
@@ -255,9 +255,12 @@ Opt into `delivery: { version, actions, project }` on `createNotificationOutbox`
255
255
  The pure `actions(payload)` selector runs at enqueue; the versioned plan remains
256
256
  fixed throughout retry. Each `send` receives its action and a stable idempotency
257
257
  key; return a small JSON receipt such as a remote message or uploaded object ID.
258
- An action that returned is confirmed and is never sent again: a result that is not
259
- JSON, or does not fit the state's byte budget, is kept as `receipt: null` with
260
- `unrecorded: 'not-json' | 'too-large'` and reported to `onError`.
258
+ The receipt is kept as `JSON.stringify` writes it: a field left `undefined` drops,
259
+ a `Date` becomes its ISO string. An action that returned is confirmed and is never
260
+ sent again: a result JSON cannot carry (a BigInt, a cycle), or one that does not fit
261
+ the state's byte budget, is kept as `receipt: null` with
262
+ `unrecorded: 'not-json' | 'too-large'` and reported to `onError`, naming the field
263
+ for `not-json`.
261
264
  `project(notification, receipts)` applies all confirmed results locally and must
262
265
  be idempotent. Checkpoints and the final projection timestamp live in the existing
263
266
  atomic StateStore; completed receipts retain them within retention/byte limits.
@@ -299,7 +299,8 @@ never trust a client-supplied owner ID as that scope.
299
299
  immutable executor `version`, pure `actions(payload)` plan selector (1–128 unique
300
300
  names, each at most 128 characters), and idempotent `project(notification, receipts)`.
301
301
  `send` receives optional `action` and stable `idempotencyKey`, and returns a JSON
302
- remote receipt (void becomes null). A result that is not JSON or does not fit the
302
+ remote receipt (void becomes null), kept as `JSON.stringify` writes it. A result JSON
303
+ cannot carry (a BigInt, a cycle; `onError` names the field) or that does not fit the
303
304
  byte budget is kept as `receipt: null` with `unrecorded: 'not-json' | 'too-large'`;
304
305
  the action stays confirmed and is not sent again. `retiredVersions` maps earlier
305
306
  plan versions to their `NotificationProjection` so queued items drain after an
@@ -642,7 +642,10 @@ if (result.outcome === 'refused') internalCounter.add(1, { reason: result.reason
642
642
  await journal.close({ timeoutMs: 5_000 })
643
643
  ```
644
644
 
645
- The owner schema and JSON serialization run synchronously before admission. Accepted frames carry
645
+ The owner schema and JSON serialization run synchronously before admission. An event is kept as
646
+ `JSON.stringify` writes it, and only if the schema reads that form back: an optional field left
647
+ `undefined` is accepted, while a cycle, a BigInt or a `Date` in a `z.date()` field is `invalid`.
648
+ Accepted frames carry
646
649
  a process epoch and contiguous sequence and retain their complete bytes inside both pending limits
647
650
  until their append attempt settles. Capacity, invalid, oversized, closed and terminal-failure
648
651
  refusals are explicit; accepted ordered frames are never evicted.
@@ -872,7 +875,9 @@ bot.catch(({ error }) => logger.error('Telegram handler failed', { error }))
872
875
  const telegram = grammyBotResources({
873
876
  bot,
874
877
  dependsOn: [database, http], // what handlers need before the first update
875
- configure: () => bot.api.setMyCommands([{ command: 'start', description: 'Start' }]),
878
+ configure: async () => {
879
+ await bot.api.setMyCommands([{ command: 'start', description: 'Start' }])
880
+ },
876
881
  onEnded: ({ error }) => stopProcess(error), // see below
877
882
  })
878
883
 
package/llms/http.txt CHANGED
@@ -14,7 +14,7 @@ Also read:
14
14
 
15
15
  ## `stitchkit/http`
16
16
 
17
- An HTTP-only entrypoint for browsers, React Native/Hermes and servers. It exports the same `createClient`, `createClients`, `createHttpClient`, URL builders, client configuration types and `ApiError` as the root, without loading its optional Socket.IO graph, plus the `postMessage` bridge `ClientFetch` adapter and envelope schemas. Import shared contracts from `stitchkit/contract`.
17
+ An HTTP-only entrypoint for browsers, React Native/Hermes and servers. It exports the same `createClient`, `createClients`, `createHttpClient`, URL builders, client configuration types, `ApiError`, `readContractIdentity` (with its `ContractIdentity` result) and the stream line errors `StreamLineLimitError` / `StreamTruncatedLineError` as the root, without loading its optional Socket.IO graph, plus the `postMessage` bridge `ClientFetch` adapter and envelope schemas. Import shared contracts from `stitchkit/contract`.
18
18
 
19
19
  ```ts
20
20
  import { createClients, createHttpClient } from 'stitchkit/http';
package/llms/live.txt CHANGED
@@ -432,7 +432,9 @@ never runs.
432
432
  - **It does not gate operations.** "Only from this machine" is a property of an
433
433
  operation, and an operation is known after routing, not before it. Write it as
434
434
  an auth rule over `ctx.ipAddress` — `isLoopbackAddress` is exported for
435
- exactly that — where it composes with your other rules.
435
+ exactly that — where it composes with your other rules. Behind a proxy on the
436
+ same host every peer is loopback: resolve the visitor with `trustProxy` first
437
+ ([server guide](./server.md#client-ip-behind-a-proxy)).
436
438
  - **It does not re-check an open connection.** Both lanes check at admission.
437
439
  - **It does not see an `OPTIONS` preflight** when `cors` is configured; that is
438
440
  answered earlier. The preflight carries no operation and no body, and the
@@ -601,18 +601,25 @@ each request.
601
601
  A payload goes into an audit row only after `sanitizePayload`:
602
602
 
603
603
  - **secret-named keys are masked** — a key whose words include a secret term is
604
- redacted (`password`, `sessionToken`, `X-Api-Key`, `authorization`, `cookie`,
605
- …), while identifiers that merely contain one (`authorId`, `sessionCount`,
606
- `tokenizer`) survive. This applies wherever a key exists — an object field and
604
+ redacted (`password`, `passphrase`, `sessionToken`, `X-Api-Key`, `accessKey`,
605
+ `authorization`, `cookie`, …), a key written as one lowercase run that ends in
606
+ one (`newpassword`, `accesstoken`), and a key that ENDS in `auth`, `signature`,
607
+ `jwt`, `otp`, `pin` or `dsn` (`basicAuth`, `webhookSignature`, `SENTRY_DSN`),
608
+ while identifiers that merely contain one (`authorId`, `sessionCount`,
609
+ `tokenizer`, `pinned`) or only describe it (`signatureVersion`, `auth_date`,
610
+ a model token count such as `maxTokens` or `usage.total_tokens`)
611
+ survive. This applies wherever a key exists — an object field and
607
612
  a `Map` entry alike, at any depth. A `Set` member has no key, so nothing there
608
613
  is masked by name;
609
614
  - **secrets are masked by their shape** in every string, whatever key holds
610
615
  it — the secret half of a Telegram bot token (`123456:[redacted]`: the bot's
611
616
  id stays, it tells two bots apart), the password in
612
- `postgresql://user:password@host` (user, host and path stay), and the value
613
- of a query parameter named as a secret (`?access_token=`, `?api-key=`,
614
- `?key=`, `?sig=`). A URL in an error message or a request log line is the
615
- usual way a token reaches a journal;
617
+ `postgresql://user:password@host` (user, host and path stay), the user of an
618
+ `http(s)` / `ws(s)` address with no password (a Sentry DSN's key — a database
619
+ or SSH user stays), the credential after `Bearer`, a provider key (`sk-…`, `or-v1-…`, `AIza…`), a
620
+ JSON Web Token (`eyJ….eyJ….…`), and the value of a query parameter named as a
621
+ secret (`?access_token=`, `?api-key=`, `?key=`, `?sig=`). A URL in an error
622
+ message or a request log line is the usual way a token reaches a journal;
616
623
  - **an error keeps what it says about itself** — its own fields (`error_code`,
617
624
  `parameters`, a provider's `status`) are written beside `name`, `message`,
618
625
  `stack` and `cause`, masked by the same rules; a field holding a class
@@ -791,8 +798,8 @@ use; future optional fields do not change callback arity.
791
798
 
792
799
  `createObservability({ tools })` uses it already. Where the envelope was scrubbed to
793
800
  `INTERNAL_SERVER_ERROR`, the row's `errorMessage` becomes the real message
794
- instead of the placeholder; a truthful envelope (a thrown `AppError`, a
795
- `ZodError`) is left alone, `errorCode` and `errorDetail` are untouched, and the
801
+ instead of the placeholder (a `ZodError` from handler code is one of these); a
802
+ truthful envelope (a thrown `AppError`, invalid input) is left alone, `errorCode` and `errorDetail` are untouched, and the
796
803
  stack is not written — that is `onToolError`'s job, for a tracker that wants it.
797
804
  The caller still receives the scrubbed envelope in every case: the raw text
798
805
  reaches your server-side record, never the response. → ADR 0042
package/llms/server.2.txt CHANGED
@@ -103,7 +103,7 @@ Runtime requirements and boundaries:
103
103
  - **Origin trust and navigation lock-down.** A `postMessage` bridge has no loopback `Host` header,
104
104
  so `createLocalHostGuard` does not apply. `serveBridge` validates the native container-reported
105
105
  `origin` against the exact `origins` allow-list, strips `host`, `origin`, `x-forwarded-for`,
106
- `x-real-ip` and `forwarded` from every frame, refuses a handler with `trustProxy: true`, and
106
+ `x-real-ip` and `forwarded` from every frame, refuses a handler configured with `trustProxy`, and
107
107
  optionally verifies a per-start `secret` in constant time. Refusal reasons are logged on the host
108
108
  and never disclosed to the window. Because any page a WebView navigates to receives
109
109
  `window.ReactNativeWebView`, always lock navigation down in the WebView itself
@@ -147,8 +147,8 @@ This endpoint is HTTP-only and cannot be multipart or exposed as a tool. The
147
147
  router sets `ctx.rawBody` before JSON/Zod validation, so `onError` can inspect it
148
148
  after malformed JSON or a schema failure. Endpoints without `rawBody: true` do
149
149
  not retain the text. `maxJsonBodyBytes` may also be set once on `createServer` /
150
- `createHandler`; a route value wins. Both limits are opt-in and abort an
151
- oversized stream before it is fully buffered. → ADR 0051
150
+ `createHandler`; a route value wins. Without either the ceiling is 1 MiB; every
151
+ limit aborts an oversized stream before it is fully buffered. → ADR 0051, ADR 0340
152
152
 
153
153
  ## Safelisted request bodies (beacons)
154
154
 
@@ -452,11 +452,16 @@ contract route does.
452
452
 
453
453
  ### Serving files & Range requests
454
454
 
455
- `staticRoute(prefix, dir, { cacheControl })` serves a directory: it checks
456
- containment, then answers the file through `serveFile`, so a static image or
457
- video carries `ETag`, `Last-Modified` and `Accept-Ranges`, revalidates to `304`
458
- and seeks with `206`. `cacheControl` sets `Cache-Control` on every answer; by
459
- default none is sent.
455
+ `staticRoute(prefix, dir, { cacheControl, allowedDotNames })` serves a directory:
456
+ it checks containment, then answers the file through `serveFile`, so a static
457
+ image or video carries `ETag`, `Last-Modified` and `Accept-Ranges`, revalidates
458
+ to `304` and seeks with `206`. `cacheControl` sets `Cache-Control` on every
459
+ answer; by default none is sent.
460
+
461
+ A path with a segment that starts with a dot — `/.env`, `/.git/config`,
462
+ `/assets/.npmrc` — answers `404`, so a hidden file that ends up in the served
463
+ directory never leaves it. Name the ones you mean to publish:
464
+ `allowedDotNames: ['.well-known']`.
460
465
 
461
466
  ```ts
462
467
  import { createServer, staticRoute } from 'stitchkit/server'