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
@@ -2,31 +2,34 @@ import {
2
2
  AgentModelCatalogSchema2
3
3
  } from "../../index-refgnzy0.js";
4
4
  import {
5
+ NonNegativeInt,
6
+ NonNegativeNum,
7
+ Percentage,
8
+ Probability,
9
+ reportedInt,
10
+ reportedUsd,
11
+ computedUsd,
12
+ nonNegativeNumber,
13
+ buildProviderUsage,
5
14
  DEFAULT_MAX_ERROR_BODY_BYTES,
6
15
  DEFAULT_MAX_JSON_BODY_BYTES,
7
16
  redactProviderFailureText,
8
17
  headersToRecord,
9
- joinProviderUrl,
10
18
  assertNoExtraBodyClash,
11
19
  resolveProviderApiKey,
12
20
  extractProviderRequestId,
13
21
  buildProviderHttpError,
14
- postProviderStream,
22
+ readProviderStreamResponse,
15
23
  nonEmptyString2,
16
24
  recordField,
17
- reportedInt,
18
- reportedUsd,
19
- computedUsd,
20
- nonNegativeNumber,
21
- buildProviderUsage,
22
25
  normalizeProviderHistory,
23
26
  historyHasToolTraffic,
24
27
  parseSseStream,
25
28
  parseSseJson
26
- } from "../../index-ht71v1ag.js";
29
+ } from "../../index-32ew02z1.js";
27
30
  import {
28
31
  AgentCacheControlSchema2
29
- } from "../../index-vebzvse6.js";
32
+ } from "../../index-jy907kcs.js";
30
33
  import {
31
34
  openAiCompatibleUsage2
32
35
  } from "../../index-6t4c98gr.js";
@@ -37,9 +40,12 @@ import {
37
40
  assertValidCacheTtlOrder,
38
41
  budgetCacheBreakpoints
39
42
  } from "../../index-ws0awmzq.js";
43
+ import {
44
+ isLoopbackHostname
45
+ } from "../../index-s8af9jqw.js";
40
46
  import {
41
47
  normalizeOpenAiJsonSchema
42
- } from "../../index-z72vazf5.js";
48
+ } from "../../index-6y3eae97.js";
43
49
  import {
44
50
  sanitizeSurrogates,
45
51
  deterministicJson,
@@ -49,14 +55,16 @@ import {
49
55
  readPortableCacheControl,
50
56
  AgentProviderError2,
51
57
  AgentProviderStreamCutError2
52
- } from "../../index-vse7x1qt.js";
58
+ } from "../../index-knqye3gv.js";
53
59
  import {
54
- readBoundedBody2,
60
+ readBoundedChunks,
61
+ concatChunks,
55
62
  readBoundedText
56
63
  } from "../../index-f16b7rze.js";
57
64
  import {
58
65
  isPositiveSafeInteger,
59
- assertPositiveSafeInteger
66
+ assertPositiveSafeInteger,
67
+ assertNonNegativeSafeInteger
60
68
  } from "../../index-gr0kxymw.js";
61
69
  import {
62
70
  assertTimerMs,
@@ -195,90 +203,6 @@ function collectOpenRouterBenchmarks(artificialResult, designResult) {
195
203
 
196
204
  // src/agent-runtime/providers/openrouter-models.ts
197
205
  import { z as z2 } from "zod";
198
-
199
- // src/agent-runtime/providers/openrouter-url.ts
200
- var OPENROUTER_API_BASE_URL = "https://openrouter.ai/api/v1";
201
- var SCHEME_PREFIX = /^[a-z][a-z0-9+.-]*:/iu;
202
- var ENCODED_TRAVERSAL = /%(?:2e|2f|5c)/iu;
203
- function hasControlOrWhitespace(value) {
204
- for (let i = 0;i < value.length; i += 1) {
205
- const code = value.charCodeAt(i);
206
- if (code <= 32 || code === 127)
207
- return true;
208
- }
209
- return false;
210
- }
211
- function validateOpenRouterBaseUrl(raw) {
212
- const candidate = raw ?? OPENROUTER_API_BASE_URL;
213
- if (typeof candidate !== "string" || candidate.trim().length === 0 || !URL.canParse(candidate)) {
214
- throw new TypeError("Invalid OpenRouter baseUrl");
215
- }
216
- const url = new URL(candidate);
217
- if (url.protocol !== "http:" && url.protocol !== "https:") {
218
- throw new TypeError(`OpenRouter baseUrl must use http: or https: protocol (received "${url.protocol}")`);
219
- }
220
- if (url.username.length > 0 || url.password.length > 0) {
221
- throw new TypeError("OpenRouter baseUrl must not contain embedded credentials");
222
- }
223
- if (url.hash.length > 0) {
224
- throw new TypeError("OpenRouter baseUrl must not contain a URL fragment");
225
- }
226
- return url;
227
- }
228
- function assertOpenRouterHttpUrl(name, value) {
229
- if (typeof value !== "string" || value.trim().length === 0 || !URL.canParse(value)) {
230
- throw new TypeError(`${name} must be a valid http: or https: URL`);
231
- }
232
- const url = new URL(value);
233
- if (url.protocol !== "http:" && url.protocol !== "https:") {
234
- throw new TypeError(`${name} must use http: or https: protocol`);
235
- }
236
- if (url.username.length > 0 || url.password.length > 0) {
237
- throw new TypeError(`${name} must not contain embedded credentials`);
238
- }
239
- return value.trim();
240
- }
241
- function assertOpenRouterPathSegment(name, value) {
242
- const trimmed = typeof value === "string" ? value.trim() : "";
243
- if (trimmed.length === 0 || trimmed === "." || trimmed === ".." || trimmed.includes("/") || trimmed.includes("\\") || trimmed.includes("?") || trimmed.includes("#") || hasControlOrWhitespace(trimmed) || ENCODED_TRAVERSAL.test(trimmed)) {
244
- throw new TypeError(`Invalid OpenRouter ${name}`);
245
- }
246
- return trimmed;
247
- }
248
- function resolveOpenRouterUrl(baseUrl, path, query) {
249
- const base = validateOpenRouterBaseUrl(baseUrl);
250
- if (typeof path !== "string" || path.length === 0 || SCHEME_PREFIX.test(path) || path.startsWith("//") || path.includes("\\") || path.includes("?") || path.includes("#") || hasControlOrWhitespace(path) || ENCODED_TRAVERSAL.test(path)) {
251
- throw new TypeError("OpenRouter path must be a relative endpoint path without scheme or query");
252
- }
253
- const normalized = path.startsWith("/") ? path : `/${path}`;
254
- const segments = normalized.slice(1).split("/");
255
- if (segments.some((segment) => segment.length === 0 || segment === "." || segment === "..")) {
256
- throw new TypeError("OpenRouter path must not contain empty or traversal segments");
257
- }
258
- const basePath = base.pathname.replace(/\/+$/u, "");
259
- const resolved = new URL(base.toString());
260
- resolved.pathname = `${basePath}${normalized}`;
261
- if (resolved.origin !== base.origin || basePath.length > 0 && !resolved.pathname.startsWith(`${basePath}/`)) {
262
- throw new TypeError("OpenRouter path escaped baseUrl scope");
263
- }
264
- if (query instanceof URLSearchParams) {
265
- for (const [key, value] of query.entries()) {
266
- resolved.searchParams.append(key, value);
267
- }
268
- } else if (query !== undefined) {
269
- for (const [key, value] of Object.entries(query)) {
270
- if (value === undefined)
271
- continue;
272
- if (typeof value === "number" && !Number.isFinite(value)) {
273
- throw new TypeError(`OpenRouter query parameter "${key}" must be a finite number`);
274
- }
275
- resolved.searchParams.set(key, String(value));
276
- }
277
- }
278
- return resolved;
279
- }
280
-
281
- // src/agent-runtime/providers/openrouter-models.ts
282
206
  var OpenRouterModelSchema = z2.object({
283
207
  id: z2.string().min(1),
284
208
  canonical_slug: z2.string().min(1).nullish(),
@@ -289,15 +213,15 @@ var OpenRouterModelSchema = z2.object({
289
213
  slug: z2.string().min(1),
290
214
  name: z2.string().nullish()
291
215
  }).loose().nullish(),
292
- context_length: z2.int().nonnegative().nullish(),
216
+ context_length: NonNegativeInt.nullish(),
293
217
  architecture: z2.object({
294
218
  input_modalities: z2.array(z2.string()).nullish().transform((value) => value ?? []),
295
219
  output_modalities: z2.array(z2.string()).nullish(),
296
220
  tokenizer: z2.string().nullish()
297
221
  }).loose().nullish().transform((value) => value ?? { input_modalities: [] }),
298
222
  top_provider: z2.object({
299
- context_length: z2.int().nonnegative().nullish(),
300
- max_completion_tokens: z2.int().nonnegative().nullish()
223
+ context_length: NonNegativeInt.nullish(),
224
+ max_completion_tokens: NonNegativeInt.nullish()
301
225
  }).loose().nullish(),
302
226
  reasoning: z2.object({
303
227
  supported_efforts: z2.array(z2.string()).nullish(),
@@ -348,58 +272,6 @@ function withOpenRouterTimeout(timeoutMs, signal, requests) {
348
272
  assertTimerMs("timeoutMs", timeoutMs, { absent: "refused" });
349
273
  return withLinkedAbortSignals(signal, AbortSignal.timeout(timeoutMs), requests);
350
274
  }
351
- function assertValidStaticOpenRouterApiKey(apiKey) {
352
- if (apiKey === undefined || typeof apiKey === "function")
353
- return;
354
- if (typeof apiKey !== "string" || apiKey.trim().length === 0) {
355
- throw new TypeError("OpenRouter apiKey must be a non-empty string when provided");
356
- }
357
- }
358
- async function resolveOptionalOpenRouterApiKey(apiKey) {
359
- if (apiKey === undefined)
360
- return;
361
- const resolved = typeof apiKey === "function" ? await apiKey() : apiKey;
362
- if (typeof resolved !== "string") {
363
- throw new TypeError("OpenRouter apiKey must resolve to a non-empty string");
364
- }
365
- const trimmed = resolved.trim();
366
- if (trimmed.length === 0) {
367
- throw new TypeError("OpenRouter apiKey must be a non-empty string when provided");
368
- }
369
- return trimmed;
370
- }
371
- async function openRouterJson(input) {
372
- input.signal.throwIfAborted();
373
- const apiKey = input.apiKey !== undefined ? await resolveOptionalOpenRouterApiKey(input.apiKey) : undefined;
374
- input.signal.throwIfAborted();
375
- const response = await input.fetcher(input.url, {
376
- ...apiKey !== undefined && { headers: { Authorization: `Bearer ${apiKey}` } },
377
- redirect: "error",
378
- signal: input.signal
379
- });
380
- if (!response.ok) {
381
- await response.body?.cancel().catch(() => {
382
- return;
383
- });
384
- throw new OpenRouterHttpError(response.status, input.url.pathname);
385
- }
386
- const maxBytes = input.maxBytes ?? 16 * 1024 * 1024;
387
- const bytes = await readBoundedBody2(response.body, {
388
- maxBytes,
389
- signal: input.signal,
390
- limitError: () => new RangeError(`OpenRouter response exceeds ${maxBytes} bytes`)
391
- });
392
- return JSON.parse(new TextDecoder().decode(bytes));
393
- }
394
-
395
- class OpenRouterHttpError extends Error {
396
- status;
397
- constructor(status, path) {
398
- super(`OpenRouter request ${path} failed with HTTP ${status}`);
399
- this.status = status;
400
- this.name = "OpenRouterHttpError";
401
- }
402
- }
403
275
  var DECIMAL = /^(\d+(?:\.\d+)?)(?:e([+-]?\d+))?$/i;
404
276
  function usdPerMillion(perToken) {
405
277
  if (perToken === undefined || perToken === null)
@@ -421,18 +293,18 @@ function usd(value) {
421
293
  return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;
422
294
  }
423
295
  var MODEL_ID = /^~?[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._:-]*$/i;
424
- function openRouterEndpointsUrl(modelId, baseUrl) {
296
+ function openRouterEndpointsPath(modelId) {
425
297
  if (!MODEL_ID.test(modelId) || modelId.includes("..")) {
426
298
  throw new TypeError(`Not an OpenRouter model id: ${modelId}`);
427
299
  }
428
300
  const [author = "", slug = ""] = modelId.split("/");
429
- return resolveOpenRouterUrl(baseUrl, `/models/${encodeURIComponent(author)}/${encodeURIComponent(slug)}/endpoints`);
301
+ return `/models/${encodeURIComponent(author)}/${encodeURIComponent(slug)}/endpoints`;
430
302
  }
431
303
  function assertValidOpenRouterEndpointsFor(endpointsFor) {
432
304
  if (endpointsFor === undefined)
433
305
  return;
434
306
  for (const modelId of endpointsFor) {
435
- openRouterEndpointsUrl(modelId);
307
+ openRouterEndpointsPath(modelId);
436
308
  }
437
309
  }
438
310
  var PercentileMetricSchema = z2.object({ p50: z2.number().nullish() }).loose().nullish();
@@ -440,8 +312,8 @@ var OpenRouterEndpointsResponseSchema = z2.object({
440
312
  data: z2.object({
441
313
  endpoints: z2.array(z2.object({
442
314
  provider_name: z2.string().min(1),
443
- context_length: z2.int().nonnegative().nullish(),
444
- max_completion_tokens: z2.int().nonnegative().nullish(),
315
+ context_length: NonNegativeInt.nullish(),
316
+ max_completion_tokens: NonNegativeInt.nullish(),
445
317
  pricing: z2.object({
446
318
  prompt: z2.string().nullish(),
447
319
  completion: z2.string().nullish(),
@@ -755,6 +627,145 @@ function parseOpenRouterError(payload, rawText = "", status) {
755
627
  };
756
628
  }
757
629
 
630
+ // src/agent-runtime/providers/openrouter-request.ts
631
+ async function refuseRedirect(response) {
632
+ if (response.redirected || response.type === "opaqueredirect" || response.status >= 300 && response.status < 400) {
633
+ await response.body?.cancel().catch(() => {
634
+ return;
635
+ });
636
+ throw new AgentProviderError2(`OpenRouter redirected response refused (HTTP ${response.status})`, {
637
+ provider: "openrouter",
638
+ statusCode: response.status,
639
+ retryable: false,
640
+ responseHeaders: headersToRecord(response.headers)
641
+ });
642
+ }
643
+ }
644
+ async function sendOpenRouterRequest(exchange) {
645
+ const { signal } = exchange;
646
+ const fetch = exchange.fetch ?? globalThis.fetch;
647
+ const response = await raceAbort(fetch(exchange.url, {
648
+ method: exchange.method,
649
+ headers: exchange.headers,
650
+ ...exchange.body !== undefined && { body: exchange.body },
651
+ redirect: "error",
652
+ signal
653
+ }), signal, (late) => {
654
+ late.body?.cancel(abortReason(signal)).catch(() => {
655
+ return;
656
+ });
657
+ });
658
+ if (signal.aborted) {
659
+ await response.body?.cancel(abortReason(signal)).catch(() => {
660
+ return;
661
+ });
662
+ signal.throwIfAborted();
663
+ }
664
+ await refuseRedirect(response);
665
+ if (!response.ok) {
666
+ throw await buildProviderHttpError({
667
+ provider: "openrouter",
668
+ response,
669
+ signal,
670
+ parseError: parseOpenRouterError,
671
+ maxErrorBytes: exchange.maxErrorBytes ?? DEFAULT_MAX_ERROR_BODY_BYTES
672
+ });
673
+ }
674
+ return response;
675
+ }
676
+
677
+ // src/agent-runtime/providers/openrouter-url.ts
678
+ var OPENROUTER_API_BASE_URL = "https://openrouter.ai/api/v1";
679
+ var SCHEME_PREFIX = /^[a-z][a-z0-9+.-]*:/iu;
680
+ var ENCODED_TRAVERSAL = /%(?:2e|2f|5c)/iu;
681
+ var CHAT_ENDPOINT_SUFFIX = /\/chat\/completions\/*$/iu;
682
+ function hasControlOrWhitespace(value) {
683
+ for (let i = 0;i < value.length; i += 1) {
684
+ const code = value.charCodeAt(i);
685
+ if (code <= 32 || code === 127)
686
+ return true;
687
+ }
688
+ return false;
689
+ }
690
+ function validateOpenRouterBaseUrl(raw) {
691
+ const candidate = raw ?? OPENROUTER_API_BASE_URL;
692
+ if (typeof candidate !== "string" || candidate.trim().length === 0 || !URL.canParse(candidate)) {
693
+ throw new TypeError("Invalid OpenRouter baseUrl");
694
+ }
695
+ const url = new URL(candidate);
696
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
697
+ throw new TypeError(`OpenRouter baseUrl must use https: (or http: to a loopback host), received "${url.protocol}"`);
698
+ }
699
+ if (url.protocol === "http:" && !isLoopbackHostname(url.hostname)) {
700
+ throw new TypeError("OpenRouter baseUrl must use https: unless it names a loopback host (localhost, 127.0.0.0/8, [::1])");
701
+ }
702
+ if (url.username.length > 0 || url.password.length > 0) {
703
+ throw new TypeError("OpenRouter baseUrl must not contain embedded credentials");
704
+ }
705
+ if (url.href.includes("?")) {
706
+ throw new TypeError("OpenRouter baseUrl must not contain a query string");
707
+ }
708
+ if (url.href.includes("#")) {
709
+ throw new TypeError("OpenRouter baseUrl must not contain a URL fragment");
710
+ }
711
+ if (CHAT_ENDPOINT_SUFFIX.test(url.pathname)) {
712
+ throw new TypeError(`OpenRouter baseUrl must be the API root (such as ${OPENROUTER_API_BASE_URL}), not the /chat/completions endpoint: every path appends its own endpoint`);
713
+ }
714
+ return url;
715
+ }
716
+ function assertOpenRouterHttpUrl(name, value) {
717
+ if (typeof value !== "string" || value.trim().length === 0 || !URL.canParse(value)) {
718
+ throw new TypeError(`${name} must be a valid http: or https: URL`);
719
+ }
720
+ const url = new URL(value);
721
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
722
+ throw new TypeError(`${name} must use http: or https: protocol`);
723
+ }
724
+ if (url.username.length > 0 || url.password.length > 0) {
725
+ throw new TypeError(`${name} must not contain embedded credentials`);
726
+ }
727
+ return value.trim();
728
+ }
729
+ function assertOpenRouterPathSegment(name, value) {
730
+ const trimmed = typeof value === "string" ? value.trim() : "";
731
+ if (trimmed.length === 0 || trimmed === "." || trimmed === ".." || trimmed.includes("/") || trimmed.includes("\\") || trimmed.includes("?") || trimmed.includes("#") || hasControlOrWhitespace(trimmed) || ENCODED_TRAVERSAL.test(trimmed)) {
732
+ throw new TypeError(`Invalid OpenRouter ${name}`);
733
+ }
734
+ return trimmed;
735
+ }
736
+ function resolveOpenRouterUrl(baseUrl, path, query) {
737
+ const base = validateOpenRouterBaseUrl(baseUrl);
738
+ if (typeof path !== "string" || path.length === 0 || SCHEME_PREFIX.test(path) || path.startsWith("//") || path.includes("\\") || path.includes("?") || path.includes("#") || hasControlOrWhitespace(path) || ENCODED_TRAVERSAL.test(path)) {
739
+ throw new TypeError("OpenRouter path must be a relative endpoint path without scheme or query");
740
+ }
741
+ const normalized = path.startsWith("/") ? path : `/${path}`;
742
+ const segments = normalized.slice(1).split("/");
743
+ if (segments.some((segment) => segment.length === 0 || segment === "." || segment === "..")) {
744
+ throw new TypeError("OpenRouter path must not contain empty or traversal segments");
745
+ }
746
+ const basePath = base.pathname.replace(/\/+$/u, "");
747
+ const resolved = new URL(base.toString());
748
+ resolved.pathname = `${basePath}${normalized}`;
749
+ if (resolved.origin !== base.origin || basePath.length > 0 && !resolved.pathname.startsWith(`${basePath}/`)) {
750
+ throw new TypeError("OpenRouter path escaped baseUrl scope");
751
+ }
752
+ if (query instanceof URLSearchParams) {
753
+ for (const [key, value] of query.entries()) {
754
+ resolved.searchParams.append(key, value);
755
+ }
756
+ } else if (query !== undefined) {
757
+ for (const [key, value] of Object.entries(query)) {
758
+ if (value === undefined)
759
+ continue;
760
+ if (typeof value === "number" && !Number.isFinite(value)) {
761
+ throw new TypeError(`OpenRouter query parameter "${key}" must be a finite number`);
762
+ }
763
+ resolved.searchParams.set(key, String(value));
764
+ }
765
+ }
766
+ return resolved;
767
+ }
768
+
758
769
  // src/agent-runtime/providers/openrouter-http.ts
759
770
  var DEFAULT_OPENROUTER_REQUEST_TIMEOUT_MS = 30000;
760
771
  var JSON_CONTENT_TYPE = /^application\/(?:[a-z0-9.+-]+\+)?json(?:\s*;|$)/iu;
@@ -798,7 +809,7 @@ function assertValidOpenRouterApiKey(apiKey) {
798
809
  return;
799
810
  validateApiKeyString(apiKey);
800
811
  }
801
- async function resolveOptionalOpenRouterApiKey2(apiKey) {
812
+ async function resolveOptionalOpenRouterApiKey(apiKey) {
802
813
  if (apiKey === undefined)
803
814
  return;
804
815
  const resolved = typeof apiKey === "function" ? await apiKey() : apiKey;
@@ -809,9 +820,15 @@ function hasHeaderIgnoreCase(headers, targetLower) {
809
820
  return false;
810
821
  return Object.keys(headers).some((key) => key.toLowerCase() === targetLower);
811
822
  }
823
+ var OPENROUTER_API_HOST = new URL(OPENROUTER_API_BASE_URL).hostname;
824
+ function isForeignBaseUrl(baseUrl) {
825
+ if (baseUrl === undefined || !URL.canParse(baseUrl))
826
+ return baseUrl !== undefined;
827
+ return new URL(baseUrl).hostname.toLowerCase().replace(/\.$/u, "") !== OPENROUTER_API_HOST;
828
+ }
812
829
  function assertOpenRouterDirectAuth(input) {
813
- if (input.apiKey === undefined && input.fetch === undefined && input.baseUrl === undefined && !hasHeaderIgnoreCase(input.headers, "authorization")) {
814
- throw new TypeError("OpenRouter apiKey is required unless a custom fetch transport or baseUrl is provided");
830
+ if (input.apiKey === undefined && input.fetch === undefined && !isForeignBaseUrl(input.baseUrl) && !hasHeaderIgnoreCase(input.headers, "authorization")) {
831
+ throw new TypeError(`OpenRouter apiKey is required for ${OPENROUTER_API_HOST} unless an Authorization header, a custom fetch transport or a baseUrl on another host is provided`);
815
832
  }
816
833
  }
817
834
  function buildOpenRouterBaseHeaders(settings, apiKey) {
@@ -825,7 +842,7 @@ function buildOpenRouterBaseHeaders(settings, apiKey) {
825
842
  };
826
843
  }
827
844
  function prepareOpenRouterRequest(input) {
828
- const url = resolveOpenRouterUrl(input.baseUrl, input.path, input.query).toString();
845
+ const url = resolveOpenRouterUrl(input.baseUrl, input.path, input.query);
829
846
  const method = input.method ?? (input.body !== undefined ? "POST" : "GET");
830
847
  if (method === "GET" && input.body !== undefined) {
831
848
  throw new TypeError("OpenRouter GET request must not include a request body");
@@ -861,7 +878,7 @@ function prepareOpenRouterRequest(input) {
861
878
  ...serializedBody !== undefined && { serializedBody },
862
879
  timeoutMs,
863
880
  maxErrorBytes,
864
- fetcher: input.fetch ?? fetch
881
+ ...input.fetch !== undefined && { fetch: input.fetch }
865
882
  };
866
883
  }
867
884
  function assembleOpenRouterRequestHeaders(input, prepared, apiKey, defaultAccept) {
@@ -881,18 +898,16 @@ function assembleOpenRouterRequestHeaders(input, prepared, apiKey, defaultAccept
881
898
  }
882
899
  return headers;
883
900
  }
884
- async function assertNotRedirectedResponse(response) {
885
- if (response.redirected || response.type === "opaqueredirect" || response.status >= 300 && response.status < 400) {
886
- await response.body?.cancel().catch(() => {
887
- return;
888
- });
889
- throw new AgentProviderError2(`OpenRouter redirected response refused (HTTP ${response.status})`, {
890
- provider: "openrouter",
891
- statusCode: response.status,
892
- retryable: false,
893
- responseHeaders: headersToRecord(response.headers)
894
- });
895
- }
901
+ function openRouterExchange(prepared, headers, signal) {
902
+ return {
903
+ url: prepared.url,
904
+ method: prepared.method,
905
+ headers,
906
+ ...prepared.serializedBody !== undefined && { body: prepared.serializedBody },
907
+ signal,
908
+ ...prepared.fetch !== undefined && { fetch: prepared.fetch },
909
+ maxErrorBytes: prepared.maxErrorBytes
910
+ };
896
911
  }
897
912
  function extractOpenRouterGenerationId(headers, parsedBody) {
898
913
  const fromHeader = nonEmptyTrimmed(headers.get("x-generation-id"));
@@ -917,37 +932,11 @@ async function openRouterRequestJson(input) {
917
932
  const maxResponseBytes = input.maxResponseBytes ?? DEFAULT_MAX_JSON_BODY_BYTES;
918
933
  assertPositiveSafeInteger("maxResponseBytes", maxResponseBytes);
919
934
  input.signal?.throwIfAborted();
920
- const apiKey = await resolveOptionalOpenRouterApiKey2(input.apiKey);
935
+ const apiKey = await resolveOptionalOpenRouterApiKey(input.apiKey);
921
936
  input.signal?.throwIfAborted();
922
937
  return withSignalDeadline(prepared.timeoutMs, input.signal, () => abortError(`OpenRouter request ${input.path} timed out after ${prepared.timeoutMs} ms`, "TimeoutError"), async (signal) => {
923
938
  const headers = assembleOpenRouterRequestHeaders(input, prepared, apiKey, "application/json");
924
- const response = await raceAbort(prepared.fetcher(prepared.url, {
925
- method: prepared.method,
926
- headers,
927
- ...prepared.serializedBody !== undefined && { body: prepared.serializedBody },
928
- redirect: "error",
929
- signal
930
- }), signal, (late) => {
931
- late.body?.cancel(abortReason(signal)).catch(() => {
932
- return;
933
- });
934
- });
935
- if (signal.aborted) {
936
- await response.body?.cancel(abortReason(signal)).catch(() => {
937
- return;
938
- });
939
- signal.throwIfAborted();
940
- }
941
- await assertNotRedirectedResponse(response);
942
- if (!response.ok) {
943
- throw await buildProviderHttpError({
944
- provider: "openrouter",
945
- response,
946
- signal,
947
- parseError: parseOpenRouterError,
948
- maxErrorBytes: prepared.maxErrorBytes
949
- });
950
- }
939
+ const response = await sendOpenRouterRequest(openRouterExchange(prepared, headers, signal));
951
940
  const requestId = extractProviderRequestId(response.headers);
952
941
  const responseHeaders = headersToRecord(response.headers);
953
942
  const contentType = response.headers.get("content-type")?.trim() ?? "";
@@ -1065,12 +1054,11 @@ var OpenRouterReasoningEffortSchema = z3.enum([
1065
1054
  "xhigh",
1066
1055
  "max"
1067
1056
  ]);
1068
- var Usd = z3.number().nonnegative();
1069
1057
  var OpenRouterMaxPriceSchema = z3.strictObject({
1070
- promptUsdPerMillion: Usd.optional(),
1071
- completionUsdPerMillion: Usd.optional(),
1072
- requestUsd: Usd.optional(),
1073
- imageUsd: Usd.optional()
1058
+ promptUsdPerMillion: NonNegativeNum.optional(),
1059
+ completionUsdPerMillion: NonNegativeNum.optional(),
1060
+ requestUsd: NonNegativeNum.optional(),
1061
+ imageUsd: NonNegativeNum.optional()
1074
1062
  });
1075
1063
  var Slug = z3.string().min(1).max(128);
1076
1064
  var OpenRouterProviderRoutingSchema = z3.strictObject({
@@ -1082,7 +1070,8 @@ var OpenRouterProviderRoutingSchema = z3.strictObject({
1082
1070
  dataCollection: z3.enum(["allow", "deny"]).optional(),
1083
1071
  zdr: z3.boolean().optional(),
1084
1072
  sort: z3.enum(["price", "throughput", "latency"]).optional(),
1085
- quantizations: z3.array(z3.string().min(1).max(16)).min(1).optional()
1073
+ quantizations: z3.array(z3.string().min(1).max(16)).min(1).optional(),
1074
+ options: z3.record(Slug, z3.record(z3.string(), z3.json())).optional()
1086
1075
  });
1087
1076
  var OpenRouterReasoningPolicySchema = z3.strictObject({
1088
1077
  effort: OpenRouterReasoningEffortSchema.optional(),
@@ -1133,7 +1122,8 @@ function serializeOpenRouterProviderRouting(raw) {
1133
1122
  ...routing.dataCollection && { data_collection: routing.dataCollection },
1134
1123
  ...routing.zdr !== undefined && { zdr: routing.zdr },
1135
1124
  ...routing.sort && { sort: routing.sort },
1136
- ...routing.quantizations && { quantizations: routing.quantizations }
1125
+ ...routing.quantizations && { quantizations: routing.quantizations },
1126
+ ...routing.options && { options: routing.options }
1137
1127
  };
1138
1128
  return Object.keys(wire).length > 0 ? wire : undefined;
1139
1129
  }
@@ -1773,7 +1763,7 @@ function buildOpenAiChatRequestBody(input) {
1773
1763
  return body;
1774
1764
  }
1775
1765
 
1776
- // src/agent-runtime/providers/provider-openai-chat-sse.ts
1766
+ // src/agent-runtime/providers/provider-openai-chat-state.ts
1777
1767
  var MAX_TOOL_CALLS = 256;
1778
1768
 
1779
1769
  class DecodeState {
@@ -1807,53 +1797,6 @@ class DecodeState {
1807
1797
  this.explicitUsageMeta = explicitUsageMeta;
1808
1798
  }
1809
1799
  }
1810
- function mapOpenAiChatFinishReason(raw) {
1811
- if (raw === "stop" || raw === "length" || raw === "error")
1812
- return raw;
1813
- if (raw === "tool_calls" || raw === "function_call")
1814
- return "tool-calls";
1815
- return raw === "content_filter" ? "content-filter" : "other";
1816
- }
1817
- function mergeReasoningDetail(acc, d) {
1818
- const t = d.type;
1819
- if (t === "reasoning.encrypted") {
1820
- const hasId = (v) => typeof v === "string" && v.length > 0;
1821
- if (hasId(d.id)) {
1822
- const existing = acc.find((i) => i.type === t && i.format === d.format && i.id === d.id);
1823
- if (existing) {
1824
- if (typeof d.data === "string" && d.data.length > 0)
1825
- existing.data = d.data;
1826
- return;
1827
- }
1828
- acc.push({ ...d });
1829
- return;
1830
- }
1831
- const duplicate = acc.some((i) => i.type === t && i.format === d.format && !hasId(i.id) && i.data === d.data);
1832
- if (!duplicate)
1833
- acc.push({ ...d });
1834
- return;
1835
- }
1836
- const canMatch = t === "reasoning.text" || t === "reasoning.summary";
1837
- const m = canMatch ? acc.find((i) => i.type === t && i.format === d.format && i.index === d.index && i.id === d.id) : undefined;
1838
- if (!m) {
1839
- acc.push({ ...d });
1840
- return;
1841
- }
1842
- const add = (k, v) => {
1843
- if (typeof v === "string")
1844
- m[k] = `${typeof m[k] === "string" ? m[k] : ""}${v}`;
1845
- };
1846
- if (t === "reasoning.text") {
1847
- add("text", d.text);
1848
- if (typeof d.signature === "string" && d.signature.length > 0)
1849
- m.signature = d.signature;
1850
- } else if (t === "reasoning.summary")
1851
- add("summary", d.summary);
1852
- }
1853
- function makeProviderError(provider, parsed) {
1854
- const { message, ...rest } = parsed;
1855
- return new AgentProviderError2(redactProviderFailureText(message || `${provider} request failed`), { provider, ...rest });
1856
- }
1857
1800
  function* closeText(state) {
1858
1801
  if (!state.textOpen)
1859
1802
  return;
@@ -1917,6 +1860,55 @@ function* processToolCallDelta(tc, state, provider) {
1917
1860
  yield { type: "tool-input-delta", toolCallId: entry.id, delta: arg };
1918
1861
  }
1919
1862
  }
1863
+
1864
+ // src/agent-runtime/providers/provider-openai-chat-sse.ts
1865
+ function mapOpenAiChatFinishReason(raw) {
1866
+ if (raw === "stop" || raw === "length" || raw === "error")
1867
+ return raw;
1868
+ if (raw === "tool_calls" || raw === "function_call")
1869
+ return "tool-calls";
1870
+ return raw === "content_filter" ? "content-filter" : "other";
1871
+ }
1872
+ function mergeReasoningDetail(acc, d) {
1873
+ const t = d.type;
1874
+ if (t === "reasoning.encrypted") {
1875
+ const hasId = (v) => typeof v === "string" && v.length > 0;
1876
+ if (hasId(d.id)) {
1877
+ const existing = acc.find((i) => i.type === t && i.format === d.format && i.id === d.id);
1878
+ if (existing) {
1879
+ if (typeof d.data === "string" && d.data.length > 0)
1880
+ existing.data = d.data;
1881
+ return;
1882
+ }
1883
+ acc.push({ ...d });
1884
+ return;
1885
+ }
1886
+ const duplicate = acc.some((i) => i.type === t && i.format === d.format && !hasId(i.id) && i.data === d.data);
1887
+ if (!duplicate)
1888
+ acc.push({ ...d });
1889
+ return;
1890
+ }
1891
+ const canMatch = t === "reasoning.text" || t === "reasoning.summary";
1892
+ const m = canMatch ? acc.find((i) => i.type === t && i.format === d.format && i.index === d.index && i.id === d.id) : undefined;
1893
+ if (!m) {
1894
+ acc.push({ ...d });
1895
+ return;
1896
+ }
1897
+ const add = (k, v) => {
1898
+ if (typeof v === "string")
1899
+ m[k] = `${typeof m[k] === "string" ? m[k] : ""}${v}`;
1900
+ };
1901
+ if (t === "reasoning.text") {
1902
+ add("text", d.text);
1903
+ if (typeof d.signature === "string" && d.signature.length > 0)
1904
+ m.signature = d.signature;
1905
+ } else if (t === "reasoning.summary")
1906
+ add("summary", d.summary);
1907
+ }
1908
+ function makeProviderError(provider, parsed) {
1909
+ const { message, ...rest } = parsed;
1910
+ return new AgentProviderError2(redactProviderFailureText(message || `${provider} request failed`), { provider, ...rest });
1911
+ }
1920
1912
  function* decodeChunk(chunk, s, opts) {
1921
1913
  if (!isRecord(chunk))
1922
1914
  return;
@@ -2131,41 +2123,33 @@ async function* decodeOpenAiChatJsonResponse(body, options) {
2131
2123
 
2132
2124
  // src/agent-runtime/providers/openrouter.ts
2133
2125
  var EMPTY_WIRE_POLICY = { looseTools: false };
2134
- function catalogJson(fetcher, url, apiKey, signal) {
2135
- return openRouterJson({
2136
- fetcher,
2137
- url,
2138
- ...apiKey !== undefined && { apiKey },
2139
- signal
2126
+ async function catalogJson(options, timeoutMs, path, query, signal) {
2127
+ const response = await openRouterRequestJson({
2128
+ path,
2129
+ query,
2130
+ signal,
2131
+ timeoutMs,
2132
+ ...options.baseUrl !== undefined && { baseUrl: options.baseUrl },
2133
+ ...options.apiKey !== undefined && { apiKey: options.apiKey },
2134
+ ...options.fetch !== undefined && { fetch: options.fetch }
2140
2135
  });
2136
+ return response.data;
2141
2137
  }
2142
- function benchmarkOutcome(fetcher, url, apiKey, signal) {
2143
- return catalogJson(fetcher, url, apiKey, signal).then((value) => ({ outcome: "ok", value }), (error) => ({ outcome: "error", error }));
2138
+ function benchmarkOutcome(read) {
2139
+ return read.then((value) => ({ outcome: "ok", value }), (error) => ({ outcome: "error", error }));
2144
2140
  }
2145
2141
  function openRouterModelCatalog(options = {}) {
2146
- const fetcher = options.fetcher ?? fetch;
2147
2142
  const timeoutMs = options.timeoutMs ?? 1e4;
2148
2143
  assertTimerMs("timeoutMs", timeoutMs);
2149
- assertValidStaticOpenRouterApiKey(options.apiKey);
2144
+ assertValidOpenRouterApiKey(options.apiKey);
2150
2145
  validateOpenRouterBaseUrl(options.baseUrl);
2151
2146
  return {
2152
2147
  async load(input = {}) {
2153
- const modelsUrl = resolveOpenRouterUrl(options.baseUrl, "/models", {
2154
- supported_parameters: "tools",
2155
- output_modalities: "text",
2156
- sort: "top-weekly"
2157
- });
2158
- const artificialUrl = resolveOpenRouterUrl(options.baseUrl, "/benchmarks", {
2159
- source: "artificial-analysis"
2160
- });
2161
- const designUrl = resolveOpenRouterUrl(options.baseUrl, "/benchmarks", {
2162
- source: "design-arena",
2163
- arena: "agents"
2164
- });
2148
+ const read = (path, query, signal) => catalogJson(options, timeoutMs, path, query, signal);
2165
2149
  const [modelsRaw, artificialResult, designResult] = await withOpenRouterTimeout(timeoutMs, input.signal, (signal) => Promise.all([
2166
- catalogJson(fetcher, modelsUrl, options.apiKey, signal),
2167
- benchmarkOutcome(fetcher, artificialUrl, options.apiKey, signal),
2168
- benchmarkOutcome(fetcher, designUrl, options.apiKey, signal)
2150
+ read("/models", { supported_parameters: "tools", output_modalities: "text", sort: "top-weekly" }, signal),
2151
+ benchmarkOutcome(read("/benchmarks", { source: "artificial-analysis" }, signal)),
2152
+ benchmarkOutcome(read("/benchmarks", { source: "design-arena", arena: "agents" }, signal))
2169
2153
  ]));
2170
2154
  const observedAt = (options.now?.() ?? new Date).toISOString();
2171
2155
  const models = OpenRouterModelsResponseSchema.parse(modelsRaw).data;
@@ -2255,10 +2239,26 @@ function buildOpenRouterRequestBody(input) {
2255
2239
  }
2256
2240
  });
2257
2241
  }
2242
+ function chatHeaders(settings, apiKey, requestHeaders) {
2243
+ const headers = new Headers({
2244
+ "content-type": "application/json",
2245
+ accept: "text/event-stream"
2246
+ });
2247
+ for (const [k, v] of Object.entries(buildOpenRouterBaseHeaders(settings, apiKey))) {
2248
+ headers.set(k, v);
2249
+ }
2250
+ for (const [k, v] of Object.entries(settings.headers ?? {}))
2251
+ headers.set(k, v);
2252
+ for (const [k, v] of Object.entries(requestHeaders ?? {})) {
2253
+ if (k.toLowerCase() !== "content-type")
2254
+ headers.set(k, v);
2255
+ }
2256
+ return headers;
2257
+ }
2258
2258
  function openRouterProvider(settings, access = {}) {
2259
2259
  assertNoExtraBodyClash("openRouterProvider", settings.extraBody, OPENROUTER_POLICY_KEYS);
2260
2260
  const defaultPolicy = access.defaultPolicy !== undefined ? resolveOpenRouterWirePolicy(access.defaultPolicy) : EMPTY_WIRE_POLICY;
2261
- const endpoint = joinProviderUrl(settings.baseUrl ?? OPENROUTER_API_BASE_URL, "/chat/completions");
2261
+ const endpoint = resolveOpenRouterUrl(settings.baseUrl, "/chat/completions");
2262
2262
  const policyOf = (modelId) => {
2263
2263
  const resolved = access.resolvePolicy?.(modelId);
2264
2264
  return resolved !== undefined ? resolveOpenRouterWirePolicy(resolved) : defaultPolicy;
@@ -2278,16 +2278,17 @@ function openRouterProvider(settings, access = {}) {
2278
2278
  ...settings.extraBody !== undefined && { extraBody: settings.extraBody }
2279
2279
  });
2280
2280
  const apiKey = await resolveProviderApiKey(settings.apiKey);
2281
- const response = await postProviderStream({
2282
- provider: "openrouter",
2281
+ const answer = await sendOpenRouterRequest({
2283
2282
  url: endpoint,
2284
- headers: buildOpenRouterBaseHeaders(settings, apiKey),
2285
- ...settings.headers !== undefined && { extraHeaders: settings.headers },
2286
- ...request.headers !== undefined && { requestHeaders: request.headers },
2287
- body,
2283
+ method: "POST",
2284
+ headers: chatHeaders(settings, apiKey, request.headers),
2285
+ body: JSON.stringify(body),
2288
2286
  signal,
2289
- ...settings.fetch !== undefined && { fetcher: settings.fetch },
2290
- parseError: parseOpenRouterError
2287
+ ...settings.fetch !== undefined && { fetch: settings.fetch }
2288
+ });
2289
+ const response = await readProviderStreamResponse(answer, {
2290
+ provider: "openrouter",
2291
+ signal
2291
2292
  });
2292
2293
  const decodeOptions = {
2293
2294
  provider: "openrouter",
@@ -2308,9 +2309,6 @@ import { z as z7 } from "zod";
2308
2309
 
2309
2310
  // src/agent-runtime/providers/openrouter-catalog.ts
2310
2311
  import { z as z5 } from "zod";
2311
- var Price = z5.number().nonnegative();
2312
- var NonNegativeMetric = z5.number().nonnegative();
2313
- var Percentage = z5.number().min(0).max(100);
2314
2312
  var UnknownPricingFieldSchema = z5.enum([
2315
2313
  "prompt",
2316
2314
  "completion",
@@ -2321,23 +2319,23 @@ var UnknownPricingFieldSchema = z5.enum([
2321
2319
  "cacheWrite1h"
2322
2320
  ]);
2323
2321
  var ConditionalPricingCeilingSchema = z5.strictObject({
2324
- promptUsdPerMillion: Price.optional(),
2325
- completionUsdPerMillion: Price.optional(),
2326
- cacheReadUsdPerMillion: Price.optional(),
2327
- cacheWriteUsdPerMillion: Price.optional(),
2328
- cacheWrite1hUsdPerMillion: Price.optional(),
2329
- requestUsd: Price.optional(),
2330
- imageUsd: Price.optional()
2322
+ promptUsdPerMillion: NonNegativeNum.optional(),
2323
+ completionUsdPerMillion: NonNegativeNum.optional(),
2324
+ cacheReadUsdPerMillion: NonNegativeNum.optional(),
2325
+ cacheWriteUsdPerMillion: NonNegativeNum.optional(),
2326
+ cacheWrite1hUsdPerMillion: NonNegativeNum.optional(),
2327
+ requestUsd: NonNegativeNum.optional(),
2328
+ imageUsd: NonNegativeNum.optional()
2331
2329
  });
2332
2330
  var OpenRouterPricingTierSchema = z5.strictObject({
2333
2331
  minPromptTokens: z5.int().positive(),
2334
- promptUsdPerMillion: Price.optional(),
2335
- completionUsdPerMillion: Price.optional(),
2336
- cacheReadUsdPerMillion: Price.optional(),
2337
- cacheWriteUsdPerMillion: Price.optional(),
2338
- cacheWrite1hUsdPerMillion: Price.optional(),
2339
- requestUsd: Price.optional(),
2340
- imageUsd: Price.optional(),
2332
+ promptUsdPerMillion: NonNegativeNum.optional(),
2333
+ completionUsdPerMillion: NonNegativeNum.optional(),
2334
+ cacheReadUsdPerMillion: NonNegativeNum.optional(),
2335
+ cacheWriteUsdPerMillion: NonNegativeNum.optional(),
2336
+ cacheWrite1hUsdPerMillion: NonNegativeNum.optional(),
2337
+ requestUsd: NonNegativeNum.optional(),
2338
+ imageUsd: NonNegativeNum.optional(),
2341
2339
  unknownPricingFields: z5.array(UnknownPricingFieldSchema).min(1).optional()
2342
2340
  });
2343
2341
  var OpenRouterModelAliasTargetSchema = z5.strictObject({
@@ -2350,17 +2348,17 @@ var OpenRouterModelReasoningMetaSchema = z5.strictObject({
2350
2348
  });
2351
2349
  var OpenRouterEndpointSchema = z5.strictObject({
2352
2350
  provider: z5.string().min(1),
2353
- contextLength: z5.int().nonnegative().optional(),
2354
- maxCompletionTokens: z5.int().nonnegative().optional(),
2355
- promptUsdPerMillion: Price.optional(),
2356
- completionUsdPerMillion: Price.optional(),
2357
- cacheReadUsdPerMillion: Price.optional(),
2358
- cacheWriteUsdPerMillion: Price.optional(),
2359
- cacheWrite1hUsdPerMillion: Price.optional(),
2351
+ contextLength: NonNegativeInt.optional(),
2352
+ maxCompletionTokens: NonNegativeInt.optional(),
2353
+ promptUsdPerMillion: NonNegativeNum.optional(),
2354
+ completionUsdPerMillion: NonNegativeNum.optional(),
2355
+ cacheReadUsdPerMillion: NonNegativeNum.optional(),
2356
+ cacheWriteUsdPerMillion: NonNegativeNum.optional(),
2357
+ cacheWrite1hUsdPerMillion: NonNegativeNum.optional(),
2360
2358
  supportedParameters: z5.array(z5.string()),
2361
2359
  status: z5.int().optional(),
2362
- latencyP50Ms: NonNegativeMetric.optional(),
2363
- throughputP50: NonNegativeMetric.optional(),
2360
+ latencyP50Ms: NonNegativeNum.optional(),
2361
+ throughputP50: NonNegativeNum.optional(),
2364
2362
  uptime1d: Percentage.optional(),
2365
2363
  tag: z5.string().min(1).optional()
2366
2364
  });
@@ -2374,17 +2372,17 @@ var OpenRouterSnapshotModelSchema = z5.strictObject({
2374
2372
  inputModalities: z5.array(z5.string().min(1)).default([]),
2375
2373
  outputModalities: z5.array(z5.string().min(1)).optional(),
2376
2374
  tokenizer: z5.string().min(1).optional(),
2377
- contextLength: z5.int().nonnegative().optional(),
2378
- topProviderContextLength: z5.int().nonnegative().optional(),
2379
- maxCompletionTokens: z5.int().nonnegative().optional(),
2375
+ contextLength: NonNegativeInt.optional(),
2376
+ topProviderContextLength: NonNegativeInt.optional(),
2377
+ maxCompletionTokens: NonNegativeInt.optional(),
2380
2378
  reasoning: OpenRouterModelReasoningMetaSchema.optional(),
2381
- promptUsdPerMillion: Price.optional(),
2382
- completionUsdPerMillion: Price.optional(),
2383
- requestUsd: Price.optional(),
2384
- imageUsd: Price.optional(),
2385
- cacheReadUsdPerMillion: Price.optional(),
2386
- cacheWriteUsdPerMillion: Price.optional(),
2387
- cacheWrite1hUsdPerMillion: Price.optional(),
2379
+ promptUsdPerMillion: NonNegativeNum.optional(),
2380
+ completionUsdPerMillion: NonNegativeNum.optional(),
2381
+ requestUsd: NonNegativeNum.optional(),
2382
+ imageUsd: NonNegativeNum.optional(),
2383
+ cacheReadUsdPerMillion: NonNegativeNum.optional(),
2384
+ cacheWriteUsdPerMillion: NonNegativeNum.optional(),
2385
+ cacheWrite1hUsdPerMillion: NonNegativeNum.optional(),
2388
2386
  pricingTiers: z5.array(OpenRouterPricingTierSchema).optional(),
2389
2387
  hasConditionalPricing: z5.boolean().optional(),
2390
2388
  unknownPricingFields: z5.array(UnknownPricingFieldSchema).min(1).optional(),
@@ -2444,17 +2442,27 @@ function mapSnapshotModel(model, endpoints) {
2444
2442
  ...endpoints !== undefined && { endpoints: [...endpoints] }
2445
2443
  };
2446
2444
  }
2445
+ async function readOpenRouterCatalog(options, schema, path) {
2446
+ const timeoutMs = options.timeoutMs ?? 1e4;
2447
+ const response = await openRouterRequestJson({
2448
+ path,
2449
+ schema,
2450
+ timeoutMs,
2451
+ ...options.signal !== undefined && { signal: options.signal },
2452
+ ...options.baseUrl !== undefined && { baseUrl: options.baseUrl },
2453
+ ...options.apiKey !== undefined && { apiKey: options.apiKey },
2454
+ ...options.fetch !== undefined && { fetch: options.fetch },
2455
+ ...options.maxResponseBytes !== undefined && {
2456
+ maxResponseBytes: options.maxResponseBytes
2457
+ }
2458
+ });
2459
+ return response.data;
2460
+ }
2447
2461
  async function fetchOpenRouterModelEndpoints(modelId, options = {}) {
2448
- assertValidStaticOpenRouterApiKey(options.apiKey);
2462
+ assertValidOpenRouterApiKey(options.apiKey);
2449
2463
  validateOpenRouterBaseUrl(options.baseUrl);
2450
- const url = openRouterEndpointsUrl(modelId, options.baseUrl);
2451
- const parsed = OpenRouterEndpointsResponseSchema.parse(await withOpenRouterTimeout(options.timeoutMs ?? 1e4, options.signal, (signal) => openRouterJson({
2452
- fetcher: options.fetcher ?? fetch,
2453
- url,
2454
- ...options.apiKey !== undefined && { apiKey: options.apiKey },
2455
- signal,
2456
- ...options.maxResponseBytes !== undefined && { maxBytes: options.maxResponseBytes }
2457
- })));
2464
+ const path = openRouterEndpointsPath(modelId);
2465
+ const parsed = await readOpenRouterCatalog(options, OpenRouterEndpointsResponseSchema, path);
2458
2466
  return parsed.data.endpoints.map((endpoint) => {
2459
2467
  const prompt = usdPerMillion(endpoint.pricing?.prompt);
2460
2468
  const completion = usdPerMillion(endpoint.pricing?.completion);
@@ -2489,17 +2497,11 @@ async function loadOpenRouterCatalogSnapshot(options = {}) {
2489
2497
  const concurrency = options.concurrency ?? 4;
2490
2498
  if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > 16)
2491
2499
  throw new RangeError("concurrency must be an integer from 1 to 16");
2492
- assertValidStaticOpenRouterApiKey(options.apiKey);
2500
+ assertValidOpenRouterApiKey(options.apiKey);
2493
2501
  validateOpenRouterBaseUrl(options.baseUrl);
2494
2502
  assertValidOpenRouterEndpointsFor(options.endpointsFor);
2495
2503
  const observedAt = (options.now?.() ?? new Date).toISOString();
2496
- const listing = OpenRouterModelsResponseSchema.parse(await withOpenRouterTimeout(options.timeoutMs ?? 1e4, options.signal, (signal) => openRouterJson({
2497
- fetcher: options.fetcher ?? fetch,
2498
- url: resolveOpenRouterUrl(options.baseUrl, "/models"),
2499
- ...options.apiKey !== undefined && { apiKey: options.apiKey },
2500
- signal,
2501
- ...options.maxResponseBytes !== undefined && { maxBytes: options.maxResponseBytes }
2502
- }))).data;
2504
+ const listing = (await readOpenRouterCatalog(options, OpenRouterModelsResponseSchema, "/models")).data;
2503
2505
  const wanted = [...new Set(options.endpointsFor ?? [])];
2504
2506
  const endpoints = new Map;
2505
2507
  const stop = new AbortController;
@@ -2533,20 +2535,17 @@ async function loadOpenRouterCatalogSnapshot(options = {}) {
2533
2535
 
2534
2536
  // src/agent-runtime/providers/openrouter-catalog-query.ts
2535
2537
  import { z as z6 } from "zod";
2536
- var Price2 = z6.number().nonnegative();
2537
- var NonNegativeMetric2 = z6.number().nonnegative();
2538
- var Percentage2 = z6.number().min(0).max(100);
2539
2538
  var OpenRouterModelPricingCeilingSchema = z6.strictObject({
2540
- promptUsdPerMillion: Price2.optional(),
2541
- completionUsdPerMillion: Price2.optional(),
2542
- cacheWriteUsdPerMillion: Price2.optional(),
2543
- requestUsd: Price2.optional()
2539
+ promptUsdPerMillion: NonNegativeNum.optional(),
2540
+ completionUsdPerMillion: NonNegativeNum.optional(),
2541
+ cacheWriteUsdPerMillion: NonNegativeNum.optional(),
2542
+ requestUsd: NonNegativeNum.optional()
2544
2543
  });
2545
2544
  var OpenRouterEndpointSummarySchema = z6.strictObject({
2546
- providers: z6.int().nonnegative(),
2547
- latencyP50Ms: NonNegativeMetric2.optional(),
2548
- throughputP50: NonNegativeMetric2.optional(),
2549
- uptime1d: Percentage2.optional()
2545
+ providers: NonNegativeInt,
2546
+ latencyP50Ms: NonNegativeNum.optional(),
2547
+ throughputP50: NonNegativeNum.optional(),
2548
+ uptime1d: Percentage.optional()
2550
2549
  });
2551
2550
  function effectiveContextLength(model) {
2552
2551
  if (model.contextLength !== undefined && model.topProviderContextLength !== undefined) {
@@ -2851,15 +2850,14 @@ function listOpenRouterModels(snapshot, filter) {
2851
2850
  }
2852
2851
 
2853
2852
  // src/agent-runtime/providers/openrouter-admission.ts
2854
- var Usd2 = z7.number().nonnegative();
2855
2853
  var OpenRouterAdmissionPolicySchema = z7.strictObject({
2856
2854
  maxSnapshotAgeMs: z7.int().positive(),
2857
2855
  requiredParameters: z7.array(z7.string().min(1)).default([]),
2858
2856
  requiredInputModalities: z7.array(z7.string().min(1)).default([]),
2859
- minContextLength: z7.int().nonnegative().optional(),
2860
- maxPromptUsdPerMillion: Usd2.optional(),
2861
- maxCompletionUsdPerMillion: Usd2.optional(),
2862
- maxCacheWriteUsdPerMillion: Usd2.optional(),
2857
+ minContextLength: NonNegativeInt.optional(),
2858
+ maxPromptUsdPerMillion: NonNegativeNum.optional(),
2859
+ maxCompletionUsdPerMillion: NonNegativeNum.optional(),
2860
+ maxCacheWriteUsdPerMillion: NonNegativeNum.optional(),
2863
2861
  requireLiveEndpoint: z7.boolean().default(false)
2864
2862
  });
2865
2863
  var OpenRouterAdmissionReasonSchema = z7.enum([
@@ -2982,140 +2980,41 @@ function evaluateOpenRouterModelAdmission(input) {
2982
2980
  return { state: "admitted" };
2983
2981
  }
2984
2982
  // src/agent-runtime/providers/openrouter-audio.ts
2985
- import { z as z8 } from "zod";
2983
+ import { z as z9 } from "zod";
2986
2984
 
2987
- // src/agent-runtime/providers/openrouter-stream.ts
2988
- function wrapStreamWithCallerAbort(source, callerSignal, onRelease) {
2989
- if (!callerSignal) {
2990
- onRelease();
2991
- return source;
2992
- }
2993
- const reader = source.getReader();
2994
- let settled = false;
2995
- const detach = () => {
2996
- if (settled)
2997
- return;
2998
- settled = true;
2999
- callerSignal.removeEventListener("abort", onAbort);
3000
- onRelease();
3001
- };
3002
- const onAbort = () => {
3003
- detach();
3004
- reader.cancel(abortReason(callerSignal)).catch(() => {
3005
- return;
3006
- });
3007
- };
3008
- if (callerSignal.aborted) {
3009
- onAbort();
3010
- } else {
3011
- callerSignal.addEventListener("abort", onAbort, { once: true });
3012
- reader.closed.then(detach, detach);
3013
- }
3014
- return new ReadableStream({
3015
- async pull(controller) {
3016
- if (callerSignal.aborted) {
3017
- detach();
3018
- await reader.cancel(abortReason(callerSignal)).catch(() => {
3019
- return;
3020
- });
3021
- controller.error(abortReason(callerSignal));
3022
- return;
3023
- }
3024
- try {
3025
- const chunk = await raceAbort(reader.read(), callerSignal);
3026
- if (chunk.done) {
3027
- detach();
3028
- reader.releaseLock();
3029
- controller.close();
3030
- return;
3031
- }
3032
- controller.enqueue(chunk.value);
3033
- } catch (error) {
3034
- detach();
3035
- await reader.cancel(error).catch(() => {
3036
- return;
3037
- });
3038
- controller.error(error);
3039
- }
3040
- },
3041
- async cancel(reason) {
3042
- detach();
3043
- await reader.cancel(reason).catch(() => {
3044
- return;
3045
- });
3046
- }
3047
- });
3048
- }
3049
- async function openRouterRequestStream(input) {
3050
- const prepared = prepareOpenRouterRequest(input);
3051
- input.signal?.throwIfAborted();
3052
- const apiKey = await resolveOptionalOpenRouterApiKey2(input.apiKey);
3053
- input.signal?.throwIfAborted();
3054
- const deadline = new AbortController;
3055
- const timer = setTimeout(() => deadline.abort(abortError(`OpenRouter stream ${input.path} timed out after ${prepared.timeoutMs} ms`, "TimeoutError")), prepared.timeoutMs);
3056
- const openLink = linkAbortSignals(input.signal, deadline.signal);
3057
- const disarmOpenPhase = () => {
3058
- clearTimeout(timer);
3059
- openLink.release();
3060
- };
3061
- let response;
3062
- try {
3063
- const headers = assembleOpenRouterRequestHeaders(input, prepared, apiKey, undefined);
3064
- response = await raceAbort(prepared.fetcher(prepared.url, {
3065
- method: prepared.method,
3066
- headers,
3067
- ...prepared.serializedBody !== undefined && { body: prepared.serializedBody },
3068
- redirect: "error",
3069
- signal: openLink.signal
3070
- }), openLink.signal, (late) => {
3071
- late.body?.cancel(abortReason(openLink.signal)).catch(() => {
3072
- return;
3073
- });
3074
- });
3075
- if (openLink.signal.aborted) {
3076
- await response.body?.cancel(abortReason(openLink.signal)).catch(() => {
3077
- return;
3078
- });
3079
- openLink.signal.throwIfAborted();
3080
- }
3081
- await assertNotRedirectedResponse(response);
3082
- if (!response.ok) {
3083
- throw await buildProviderHttpError({
3084
- provider: "openrouter",
3085
- response,
3086
- signal: openLink.signal,
3087
- parseError: parseOpenRouterError,
3088
- maxErrorBytes: prepared.maxErrorBytes
3089
- });
3090
- }
3091
- } catch (error) {
3092
- disarmOpenPhase();
3093
- throw error;
3094
- }
3095
- clearTimeout(timer);
3096
- const requestId = extractProviderRequestId(response.headers);
3097
- const responseHeaders = headersToRecord(response.headers);
3098
- if (!response.body) {
3099
- openLink.release();
3100
- throw new AgentProviderError2("OpenRouter returned an empty streaming response body", {
3101
- provider: "openrouter",
3102
- statusCode: response.status,
3103
- retryable: false,
3104
- ...requestId !== undefined && { requestId },
3105
- responseHeaders
3106
- });
3107
- }
3108
- const generationId = extractOpenRouterGenerationId(response.headers);
3109
- const contentType = response.headers.get("content-type")?.trim() || "application/octet-stream";
2985
+ // src/agent-runtime/providers/openrouter-wire.ts
2986
+ import { z as z8 } from "zod";
2987
+ var OpenRouterUsageSchema = z8.object({
2988
+ prompt_tokens: NonNegativeInt.optional(),
2989
+ completion_tokens: NonNegativeInt.optional(),
2990
+ input_tokens: NonNegativeInt.optional(),
2991
+ output_tokens: NonNegativeInt.optional(),
2992
+ total_tokens: NonNegativeInt.optional(),
2993
+ seconds: NonNegativeNum.optional(),
2994
+ cost: NonNegativeNum.optional(),
2995
+ is_byok: z8.boolean().optional()
2996
+ }).loose();
2997
+ function responseMetaOf(response) {
3110
2998
  return {
3111
- body: wrapStreamWithCallerAbort(response.body, input.signal, openLink.release),
3112
- contentType,
3113
2999
  status: response.status,
3114
- ...generationId !== undefined && { generationId },
3115
- ...requestId !== undefined && { requestId },
3116
- headers: responseHeaders
3000
+ ...response.generationId !== undefined && { generationId: response.generationId },
3001
+ ...response.requestId !== undefined && { requestId: response.requestId },
3002
+ ...response.costUsd !== undefined && { costUsd: response.costUsd },
3003
+ headers: response.headers
3117
3004
  };
3118
3005
  }
3006
+ var RangedNumber = z8.custom((value) => typeof value === "number", {
3007
+ error: "expected a number"
3008
+ });
3009
+ var ExtraBodySchema = z8.record(z8.string(), z8.unknown()).readonly();
3010
+ function parseOpenRouterRequest(caller, schema, input) {
3011
+ const parsed = schema.safeParse(input);
3012
+ if (!parsed.success) {
3013
+ const issues = parsed.error.issues.map((issue) => `${issue.path.join(".") || "(input)"}: ${issue.message}`).join("; ");
3014
+ throw new TypeError(`${caller}: invalid request: ${issues}`, { cause: parsed.error });
3015
+ }
3016
+ return parsed.data;
3017
+ }
3119
3018
 
3120
3019
  // src/agent-runtime/providers/openrouter-audio.ts
3121
3020
  var STT_OWNED_KEYS = [
@@ -3132,48 +3031,57 @@ var STT_OWNED_KEYS = [
3132
3031
  "diarize",
3133
3032
  "provider"
3134
3033
  ];
3135
- var TTS_OWNED_KEYS = [
3136
- "model",
3137
- "input",
3138
- "voice",
3139
- "response_format",
3140
- "speed",
3141
- "output_delivery",
3142
- "provider"
3143
- ];
3144
- var NonNegativeNum = z8.number().nonnegative();
3145
- var NonNegativeInt = z8.int().nonnegative();
3146
- var TranscriptionSegmentSchema = z8.object({
3147
- id: z8.int().nonnegative().optional(),
3034
+ var SpeakerFields = {
3035
+ speaker: NonNegativeInt.optional(),
3036
+ speaker_label: z9.string().optional(),
3037
+ channel: NonNegativeInt.optional()
3038
+ };
3039
+ var TranscriptionSegmentSchema = z9.object({
3040
+ id: NonNegativeInt.optional(),
3148
3041
  start: NonNegativeNum,
3149
3042
  end: NonNegativeNum,
3150
- text: z8.string(),
3151
- speaker: z8.string().optional()
3043
+ text: z9.string(),
3044
+ ...SpeakerFields
3152
3045
  }).loose();
3153
- var TranscriptionWordSchema = z8.object({
3154
- word: z8.string(),
3046
+ var TranscriptionWordSchema = z9.object({
3047
+ word: z9.string(),
3155
3048
  start: NonNegativeNum,
3156
3049
  end: NonNegativeNum,
3157
- speaker: z8.string().optional()
3050
+ confidence: Probability.optional(),
3051
+ type: z9.enum(["word", "audio_event"]).optional(),
3052
+ ...SpeakerFields
3158
3053
  }).loose();
3159
- var TranscriptionUsageSchema = z8.object({
3160
- seconds: NonNegativeNum.optional(),
3161
- total_tokens: NonNegativeInt.optional(),
3162
- input_tokens: NonNegativeInt.optional(),
3163
- output_tokens: NonNegativeInt.optional(),
3164
- prompt_tokens: NonNegativeInt.optional(),
3165
- completion_tokens: NonNegativeInt.optional(),
3166
- cost: NonNegativeNum.optional()
3167
- }).loose();
3168
- var OpenRouterAudioTranscriptionResponseSchema = z8.object({
3169
- text: z8.string(),
3170
- task: z8.string().optional(),
3171
- language: z8.string().optional(),
3054
+ var OpenRouterAudioTranscriptionResponseSchema = z9.object({
3055
+ text: z9.string(),
3056
+ task: z9.string().optional(),
3057
+ language: z9.string().optional(),
3172
3058
  duration: NonNegativeNum.optional(),
3173
- segments: z8.array(TranscriptionSegmentSchema).optional(),
3174
- words: z8.array(TranscriptionWordSchema).optional(),
3175
- usage: TranscriptionUsageSchema.optional()
3059
+ segments: z9.array(TranscriptionSegmentSchema).optional(),
3060
+ words: z9.array(TranscriptionWordSchema).optional(),
3061
+ usage: OpenRouterUsageSchema.optional()
3176
3062
  }).loose();
3063
+ var AudioSourceSchema = z9.discriminatedUnion("kind", [
3064
+ z9.object({ kind: z9.literal("base64"), data: z9.string(), format: z9.string() }).readonly(),
3065
+ z9.object({ kind: z9.literal("url"), url: z9.string(), format: z9.string().optional() }).readonly(),
3066
+ z9.object({
3067
+ kind: z9.literal("file"),
3068
+ data: z9.union([z9.instanceof(Blob), z9.instanceof(Uint8Array), z9.instanceof(ArrayBuffer)]),
3069
+ filename: z9.string().optional(),
3070
+ mimeType: z9.string().optional()
3071
+ }).readonly()
3072
+ ]);
3073
+ var TranscriptionRequestSchema = z9.object({
3074
+ model: z9.string(),
3075
+ audio: AudioSourceSchema,
3076
+ language: z9.string().optional(),
3077
+ prompt: z9.string().optional(),
3078
+ temperature: RangedNumber.optional(),
3079
+ responseFormat: z9.enum(["json", "verbose_json"]).optional(),
3080
+ timestampGranularities: z9.array(z9.enum(["segment", "word"])).readonly().optional(),
3081
+ diarize: z9.boolean().optional(),
3082
+ provider: OpenRouterProviderRoutingSchema.optional(),
3083
+ extraBody: ExtraBodySchema.optional()
3084
+ });
3177
3085
  function toSafeBlob(data, mimeType) {
3178
3086
  if (data instanceof Blob) {
3179
3087
  return mimeType !== undefined && data.type !== mimeType ? new Blob([data], { type: mimeType }) : data;
@@ -3248,16 +3156,14 @@ function buildTranscriptionBody(input, model, provider) {
3248
3156
  appendFormExtraBody(form, input.extraBody);
3249
3157
  return form;
3250
3158
  }
3251
- const audioFields = input.audio.kind === "base64" ? {
3252
- input_audio: {
3253
- data: input.audio.data,
3254
- format: input.audio.format
3255
- }
3256
- } : { source_url: assertOpenRouterHttpUrl("audio.url", input.audio.url) };
3159
+ const inputAudio = input.audio.kind === "base64" ? { data: input.audio.data, format: input.audio.format } : {
3160
+ url: assertOpenRouterHttpUrl("audio.url", input.audio.url),
3161
+ ...input.audio.format !== undefined && { format: input.audio.format }
3162
+ };
3257
3163
  return {
3258
3164
  ...input.extraBody ?? {},
3259
3165
  model,
3260
- ...audioFields,
3166
+ input_audio: inputAudio,
3261
3167
  ...input.language !== undefined && { language: input.language },
3262
3168
  ...input.prompt !== undefined && { prompt: input.prompt },
3263
3169
  ...input.temperature !== undefined && { temperature: input.temperature },
@@ -3269,23 +3175,53 @@ function buildTranscriptionBody(input, model, provider) {
3269
3175
  ...provider !== undefined && { provider }
3270
3176
  };
3271
3177
  }
3178
+ function speakerOf(wire) {
3179
+ return {
3180
+ ...wire.speaker !== undefined && { speaker: wire.speaker },
3181
+ ...wire.speaker_label !== undefined && { speakerLabel: wire.speaker_label },
3182
+ ...wire.channel !== undefined && { channel: wire.channel }
3183
+ };
3184
+ }
3185
+ function toSegment(wire) {
3186
+ return {
3187
+ ...wire.id !== undefined && { id: wire.id },
3188
+ start: wire.start,
3189
+ end: wire.end,
3190
+ text: wire.text,
3191
+ ...speakerOf(wire)
3192
+ };
3193
+ }
3194
+ function toWord(wire) {
3195
+ return {
3196
+ word: wire.word,
3197
+ start: wire.start,
3198
+ end: wire.end,
3199
+ ...wire.confidence !== undefined && { confidence: wire.confidence },
3200
+ ...wire.type !== undefined && { type: wire.type },
3201
+ ...speakerOf(wire)
3202
+ };
3203
+ }
3272
3204
  async function openRouterAudioTranscription(input) {
3273
3205
  assertOpenRouterDirectAuth(input);
3274
- const model = assertNonEmptyOpenRouterField("openRouterAudioTranscription", "model", input.model);
3275
- if (input.audio.kind === "base64") {
3276
- if (input.audio.data.trim().length === 0 || input.audio.format.trim().length === 0) {
3206
+ const request = parseOpenRouterRequest("openRouterAudioTranscription", TranscriptionRequestSchema, input);
3207
+ const model = assertNonEmptyOpenRouterField("openRouterAudioTranscription", "model", request.model);
3208
+ if (request.audio.kind === "base64") {
3209
+ if (request.audio.data.trim().length === 0 || request.audio.format.trim().length === 0) {
3277
3210
  throw new TypeError("openRouterAudioTranscription: base64 audio requires non-empty data and format");
3278
3211
  }
3279
3212
  }
3280
- if (input.temperature !== undefined && (!Number.isFinite(input.temperature) || input.temperature < 0 || input.temperature > 1)) {
3213
+ if (request.audio.kind === "url" && request.audio.format?.trim().length === 0) {
3214
+ throw new TypeError("openRouterAudioTranscription: url audio format must be non-empty");
3215
+ }
3216
+ if (request.temperature !== undefined && (!Number.isFinite(request.temperature) || request.temperature < 0 || request.temperature > 1)) {
3281
3217
  throw new RangeError("openRouterAudioTranscription: temperature must be between 0 and 1");
3282
3218
  }
3283
- if (input.diarize === true && input.responseFormat !== "verbose_json") {
3219
+ if (request.diarize === true && request.responseFormat !== "verbose_json") {
3284
3220
  throw new TypeError('openRouterAudioTranscription: diarize requires responseFormat: "verbose_json"');
3285
3221
  }
3286
- assertNoExtraBodyClash("openRouterAudioTranscription", input.extraBody, STT_OWNED_KEYS);
3287
- const provider = input.provider !== undefined ? serializeOpenRouterProviderRouting(input.provider) : undefined;
3288
- const body = buildTranscriptionBody(input, model, provider);
3222
+ assertNoExtraBodyClash("openRouterAudioTranscription", request.extraBody, STT_OWNED_KEYS);
3223
+ const provider = request.provider !== undefined ? serializeOpenRouterProviderRouting(request.provider) : undefined;
3224
+ const body = buildTranscriptionBody(request, model, provider);
3289
3225
  const response = await openRouterRequestJson({
3290
3226
  ...pickOpenRouterTransport(input),
3291
3227
  path: "/audio/transcriptions",
@@ -3298,49 +3234,13 @@ async function openRouterAudioTranscription(input) {
3298
3234
  ...response.data.task !== undefined && { task: response.data.task },
3299
3235
  ...response.data.language !== undefined && { language: response.data.language },
3300
3236
  ...response.data.duration !== undefined && { duration: response.data.duration },
3301
- ...response.data.segments !== undefined && { segments: response.data.segments },
3302
- ...response.data.words !== undefined && { words: response.data.words },
3237
+ ...response.data.segments !== undefined && {
3238
+ segments: response.data.segments.map(toSegment)
3239
+ },
3240
+ ...response.data.words !== undefined && { words: response.data.words.map(toWord) },
3303
3241
  ...response.data.usage !== undefined && { usage: response.data.usage },
3304
3242
  raw: response.data,
3305
- status: response.status,
3306
- ...response.generationId !== undefined && { generationId: response.generationId },
3307
- ...response.requestId !== undefined && { requestId: response.requestId },
3308
- ...response.costUsd !== undefined && { costUsd: response.costUsd },
3309
- headers: response.headers
3310
- };
3311
- }
3312
- async function openRouterAudioSpeech(input) {
3313
- assertOpenRouterDirectAuth(input);
3314
- const model = assertNonEmptyOpenRouterField("openRouterAudioSpeech", "model", input.model);
3315
- assertNonEmptyOpenRouterField("openRouterAudioSpeech", "input", input.input);
3316
- const voice = assertNonEmptyOpenRouterField("openRouterAudioSpeech", "voice", input.voice);
3317
- if (input.speed !== undefined && (!Number.isFinite(input.speed) || input.speed <= 0)) {
3318
- throw new RangeError("openRouterAudioSpeech: speed must be a positive finite number");
3319
- }
3320
- assertNoExtraBodyClash("openRouterAudioSpeech", input.extraBody, TTS_OWNED_KEYS);
3321
- const provider = input.provider !== undefined ? serializeOpenRouterProviderRouting(input.provider) : undefined;
3322
- const body = {
3323
- ...input.extraBody ?? {},
3324
- model,
3325
- input: input.input,
3326
- voice,
3327
- ...input.responseFormat !== undefined && { response_format: input.responseFormat },
3328
- ...input.speed !== undefined && { speed: input.speed },
3329
- ...provider !== undefined && { provider }
3330
- };
3331
- const response = await openRouterRequestStream({
3332
- ...pickOpenRouterTransport(input),
3333
- path: "/audio/speech",
3334
- method: "POST",
3335
- body
3336
- });
3337
- return {
3338
- audio: response.body,
3339
- contentType: response.contentType,
3340
- status: response.status,
3341
- ...response.generationId !== undefined && { generationId: response.generationId },
3342
- ...response.requestId !== undefined && { requestId: response.requestId },
3343
- headers: response.headers
3243
+ ...responseMetaOf(response)
3344
3244
  };
3345
3245
  }
3346
3246
  // src/agent-runtime/providers/openrouter-catalog-cache.ts
@@ -3407,7 +3307,7 @@ function validateCacheOptions(options) {
3407
3307
  if (options.maxResponseBytes !== undefined) {
3408
3308
  assertPositiveSafeInteger("maxResponseBytes", options.maxResponseBytes, RangeError);
3409
3309
  }
3410
- assertValidStaticOpenRouterApiKey(options.apiKey);
3310
+ assertValidOpenRouterApiKey(options.apiKey);
3411
3311
  validateOpenRouterBaseUrl(options.baseUrl);
3412
3312
  assertValidOpenRouterEndpointsFor(options.endpointsFor);
3413
3313
  return {
@@ -3581,9 +3481,116 @@ function createOpenRouterCatalogCache(options = {}) {
3581
3481
  };
3582
3482
  }
3583
3483
  // src/agent-runtime/providers/openrouter-media.ts
3584
- import { z as z9 } from "zod";
3585
- var NonNegativeInt2 = z9.int().nonnegative();
3586
- var NonNegativeNum2 = z9.number().nonnegative();
3484
+ import { z as z10 } from "zod";
3485
+
3486
+ // src/agent-runtime/providers/openrouter-stream.ts
3487
+ function wrapStreamWithCallerAbort(source, callerSignal, onRelease) {
3488
+ if (!callerSignal) {
3489
+ onRelease();
3490
+ return source;
3491
+ }
3492
+ const reader = source.getReader();
3493
+ let settled = false;
3494
+ const detach = () => {
3495
+ if (settled)
3496
+ return;
3497
+ settled = true;
3498
+ callerSignal.removeEventListener("abort", onAbort);
3499
+ onRelease();
3500
+ };
3501
+ const onAbort = () => {
3502
+ detach();
3503
+ reader.cancel(abortReason(callerSignal)).catch(() => {
3504
+ return;
3505
+ });
3506
+ };
3507
+ if (callerSignal.aborted) {
3508
+ onAbort();
3509
+ } else {
3510
+ callerSignal.addEventListener("abort", onAbort, { once: true });
3511
+ reader.closed.then(detach, detach);
3512
+ }
3513
+ return new ReadableStream({
3514
+ async pull(controller) {
3515
+ if (callerSignal.aborted) {
3516
+ detach();
3517
+ await reader.cancel(abortReason(callerSignal)).catch(() => {
3518
+ return;
3519
+ });
3520
+ controller.error(abortReason(callerSignal));
3521
+ return;
3522
+ }
3523
+ try {
3524
+ const chunk = await raceAbort(reader.read(), callerSignal);
3525
+ if (chunk.done) {
3526
+ detach();
3527
+ reader.releaseLock();
3528
+ controller.close();
3529
+ return;
3530
+ }
3531
+ controller.enqueue(chunk.value);
3532
+ } catch (error) {
3533
+ detach();
3534
+ await reader.cancel(error).catch(() => {
3535
+ return;
3536
+ });
3537
+ controller.error(error);
3538
+ }
3539
+ },
3540
+ async cancel(reason) {
3541
+ detach();
3542
+ await reader.cancel(reason).catch(() => {
3543
+ return;
3544
+ });
3545
+ }
3546
+ });
3547
+ }
3548
+ async function openRouterRequestStream(input) {
3549
+ const prepared = prepareOpenRouterRequest(input);
3550
+ input.signal?.throwIfAborted();
3551
+ const apiKey = await resolveOptionalOpenRouterApiKey(input.apiKey);
3552
+ input.signal?.throwIfAborted();
3553
+ const deadline = new AbortController;
3554
+ const timer = setTimeout(() => deadline.abort(abortError(`OpenRouter stream ${input.path} timed out after ${prepared.timeoutMs} ms`, "TimeoutError")), prepared.timeoutMs);
3555
+ const openLink = linkAbortSignals(input.signal, deadline.signal);
3556
+ const disarmOpenPhase = () => {
3557
+ clearTimeout(timer);
3558
+ openLink.release();
3559
+ };
3560
+ let response;
3561
+ try {
3562
+ const headers = assembleOpenRouterRequestHeaders(input, prepared, apiKey, undefined);
3563
+ response = await sendOpenRouterRequest(openRouterExchange(prepared, headers, openLink.signal));
3564
+ } catch (error) {
3565
+ disarmOpenPhase();
3566
+ throw error;
3567
+ }
3568
+ clearTimeout(timer);
3569
+ const requestId = extractProviderRequestId(response.headers);
3570
+ const responseHeaders = headersToRecord(response.headers);
3571
+ if (!response.body) {
3572
+ openLink.release();
3573
+ throw new AgentProviderError2("OpenRouter returned an empty streaming response body", {
3574
+ provider: "openrouter",
3575
+ statusCode: response.status,
3576
+ retryable: false,
3577
+ ...requestId !== undefined && { requestId },
3578
+ responseHeaders
3579
+ });
3580
+ }
3581
+ const generationId = extractOpenRouterGenerationId(response.headers);
3582
+ const contentType = response.headers.get("content-type")?.trim() || "application/octet-stream";
3583
+ return {
3584
+ body: wrapStreamWithCallerAbort(response.body, input.signal, openLink.release),
3585
+ contentType,
3586
+ status: response.status,
3587
+ ...generationId !== undefined && { generationId },
3588
+ ...requestId !== undefined && { requestId },
3589
+ headers: responseHeaders
3590
+ };
3591
+ }
3592
+
3593
+ // src/agent-runtime/providers/openrouter-media.ts
3587
3594
  var IMAGE_OWNED_KEYS = [
3588
3595
  "model",
3589
3596
  "prompt",
@@ -3606,44 +3613,47 @@ var VIDEO_OWNED_KEYS = [
3606
3613
  "callback_url",
3607
3614
  "provider"
3608
3615
  ];
3609
- var ImageItemSchema = z9.object({
3610
- b64_json: z9.string().optional(),
3611
- url: z9.string().optional(),
3612
- media_type: z9.string().optional()
3613
- }).loose();
3614
- var MediaUsageSchema = z9.object({
3615
- prompt_tokens: NonNegativeInt2.optional(),
3616
- completion_tokens: NonNegativeInt2.optional(),
3617
- input_tokens: NonNegativeInt2.optional(),
3618
- output_tokens: NonNegativeInt2.optional(),
3619
- total_tokens: NonNegativeInt2.optional(),
3620
- cost: NonNegativeNum2.optional(),
3621
- is_byok: z9.boolean().optional()
3616
+ var ImageItemSchema = z10.object({
3617
+ b64_json: z10.string().optional(),
3618
+ url: z10.string().optional(),
3619
+ media_type: z10.string().optional()
3622
3620
  }).loose();
3623
- var OpenRouterImageGenerationResponseSchema = z9.object({
3624
- created: z9.int().nonnegative().optional(),
3625
- data: z9.array(ImageItemSchema),
3626
- expires_at: z9.int().nonnegative().optional(),
3627
- usage: MediaUsageSchema.optional()
3621
+ var OpenRouterImageGenerationResponseSchema = z10.object({
3622
+ created: NonNegativeInt.optional(),
3623
+ data: z10.array(ImageItemSchema),
3624
+ expires_at: NonNegativeInt.optional(),
3625
+ usage: OpenRouterUsageSchema.optional()
3628
3626
  }).loose();
3627
+ var ImageGenerationRequestSchema = z10.object({
3628
+ model: z10.string(),
3629
+ prompt: z10.string(),
3630
+ n: RangedNumber.optional(),
3631
+ aspectRatio: z10.string().optional(),
3632
+ resolution: z10.string().optional(),
3633
+ responseFormat: z10.enum(["b64_json", "url"]).optional(),
3634
+ inputReferences: z10.array(z10.unknown()).readonly().optional(),
3635
+ provider: OpenRouterProviderRoutingSchema.optional(),
3636
+ extraBody: ExtraBodySchema.optional()
3637
+ });
3629
3638
  async function openRouterGenerateImages(input) {
3630
3639
  assertOpenRouterDirectAuth(input);
3631
- const model = assertNonEmptyOpenRouterField("openRouterGenerateImages", "model", input.model);
3632
- assertNonEmptyOpenRouterField("openRouterGenerateImages", "prompt", input.prompt);
3633
- if (input.n !== undefined)
3634
- assertPositiveSafeInteger("n", input.n);
3635
- assertNoExtraBodyClash("openRouterGenerateImages", input.extraBody, IMAGE_OWNED_KEYS);
3636
- const provider = input.provider !== undefined ? serializeOpenRouterProviderRouting(input.provider) : undefined;
3640
+ const request = parseOpenRouterRequest("openRouterGenerateImages", ImageGenerationRequestSchema, input);
3641
+ const model = assertNonEmptyOpenRouterField("openRouterGenerateImages", "model", request.model);
3642
+ assertNonEmptyOpenRouterField("openRouterGenerateImages", "prompt", request.prompt);
3643
+ if (request.n !== undefined)
3644
+ assertPositiveSafeInteger("n", request.n);
3645
+ assertNoExtraBodyClash("openRouterGenerateImages", request.extraBody, IMAGE_OWNED_KEYS);
3646
+ const provider = request.provider !== undefined ? serializeOpenRouterProviderRouting(request.provider) : undefined;
3637
3647
  const body = {
3638
- ...input.extraBody ?? {},
3648
+ ...request.extraBody ?? {},
3639
3649
  model,
3640
- prompt: input.prompt,
3641
- ...input.n !== undefined && { n: input.n },
3642
- ...input.aspectRatio !== undefined && { aspect_ratio: input.aspectRatio },
3643
- ...input.resolution !== undefined && { resolution: input.resolution },
3644
- ...input.responseFormat !== undefined && { response_format: input.responseFormat },
3645
- ...input.inputReferences !== undefined && {
3646
- input_references: [...input.inputReferences]
3650
+ prompt: request.prompt,
3651
+ ...request.n !== undefined && { n: request.n },
3652
+ ...request.aspectRatio !== undefined && { aspect_ratio: request.aspectRatio },
3653
+ ...request.resolution !== undefined && { resolution: request.resolution },
3654
+ ...request.responseFormat !== undefined && { response_format: request.responseFormat },
3655
+ ...request.inputReferences !== undefined && {
3656
+ input_references: [...request.inputReferences]
3647
3657
  },
3648
3658
  ...provider !== undefined && { provider }
3649
3659
  };
@@ -3660,49 +3670,63 @@ async function openRouterGenerateImages(input) {
3660
3670
  ...response.data.expires_at !== undefined && { expiresAt: response.data.expires_at },
3661
3671
  ...response.data.usage !== undefined && { usage: response.data.usage },
3662
3672
  raw: response.data,
3663
- status: response.status,
3664
- ...response.generationId !== undefined && { generationId: response.generationId },
3665
- ...response.requestId !== undefined && { requestId: response.requestId },
3666
- ...response.costUsd !== undefined && { costUsd: response.costUsd },
3667
- headers: response.headers
3673
+ ...responseMetaOf(response)
3668
3674
  };
3669
3675
  }
3670
- var VideoSubmitResponseSchema = z9.object({
3671
- id: z9.string().min(1),
3672
- status: z9.string().min(1),
3673
- polling_url: z9.string().min(1).optional()
3676
+ var OpenRouterVideoSubmitResponseSchema = z10.object({
3677
+ id: z10.string().min(1),
3678
+ status: z10.string().min(1),
3679
+ polling_url: z10.string().min(1).optional()
3674
3680
  }).loose();
3675
- var VideoStatusResponseSchema = z9.object({
3676
- id: z9.string().min(1),
3677
- status: z9.string().min(1),
3678
- generation_id: z9.string().min(1).optional(),
3679
- urls: z9.array(z9.string()).optional(),
3680
- unsigned_urls: z9.array(z9.string()).optional(),
3681
- expires_at: z9.int().nonnegative().optional(),
3682
- usage: MediaUsageSchema.optional(),
3683
- error: z9.unknown().optional()
3681
+ var OpenRouterVideoStatusResponseSchema = z10.object({
3682
+ id: z10.string().min(1),
3683
+ status: z10.string().min(1),
3684
+ generation_id: z10.string().min(1).optional(),
3685
+ urls: z10.array(z10.string()).optional(),
3686
+ unsigned_urls: z10.array(z10.string()).optional(),
3687
+ expires_at: NonNegativeInt.optional(),
3688
+ usage: OpenRouterUsageSchema.optional(),
3689
+ error: z10.unknown().optional()
3684
3690
  }).loose();
3691
+ var VideoSubmitRequestSchema = z10.object({
3692
+ model: z10.string(),
3693
+ prompt: z10.string(),
3694
+ duration: RangedNumber.optional(),
3695
+ aspectRatio: z10.string().optional(),
3696
+ resolution: z10.string().optional(),
3697
+ generateAudio: z10.boolean().optional(),
3698
+ frameImages: z10.array(z10.unknown()).readonly().optional(),
3699
+ inputReferences: z10.array(z10.unknown()).readonly().optional(),
3700
+ callbackUrl: z10.string().optional(),
3701
+ provider: OpenRouterProviderRoutingSchema.optional(),
3702
+ extraBody: ExtraBodySchema.optional()
3703
+ });
3704
+ var VideoJobRequestSchema = z10.object({
3705
+ jobId: z10.string(),
3706
+ index: RangedNumber.optional()
3707
+ });
3685
3708
  async function openRouterSubmitVideo(input) {
3686
3709
  assertOpenRouterDirectAuth(input);
3687
- const model = assertNonEmptyOpenRouterField("openRouterSubmitVideo", "model", input.model);
3688
- assertNonEmptyOpenRouterField("openRouterSubmitVideo", "prompt", input.prompt);
3689
- if (input.duration !== undefined && (!Number.isFinite(input.duration) || input.duration <= 0)) {
3710
+ const request = parseOpenRouterRequest("openRouterSubmitVideo", VideoSubmitRequestSchema, input);
3711
+ const model = assertNonEmptyOpenRouterField("openRouterSubmitVideo", "model", request.model);
3712
+ assertNonEmptyOpenRouterField("openRouterSubmitVideo", "prompt", request.prompt);
3713
+ if (request.duration !== undefined && (!Number.isFinite(request.duration) || request.duration <= 0)) {
3690
3714
  throw new RangeError("openRouterSubmitVideo: duration must be a positive finite number");
3691
3715
  }
3692
- const callbackUrl = input.callbackUrl !== undefined ? assertOpenRouterHttpUrl("callbackUrl", input.callbackUrl) : undefined;
3693
- assertNoExtraBodyClash("openRouterSubmitVideo", input.extraBody, VIDEO_OWNED_KEYS);
3694
- const provider = input.provider !== undefined ? serializeOpenRouterProviderRouting(input.provider) : undefined;
3716
+ const callbackUrl = request.callbackUrl !== undefined ? assertOpenRouterHttpUrl("callbackUrl", request.callbackUrl) : undefined;
3717
+ assertNoExtraBodyClash("openRouterSubmitVideo", request.extraBody, VIDEO_OWNED_KEYS);
3718
+ const provider = request.provider !== undefined ? serializeOpenRouterProviderRouting(request.provider) : undefined;
3695
3719
  const body = {
3696
- ...input.extraBody ?? {},
3720
+ ...request.extraBody ?? {},
3697
3721
  model,
3698
- prompt: input.prompt,
3699
- ...input.duration !== undefined && { duration: input.duration },
3700
- ...input.aspectRatio !== undefined && { aspect_ratio: input.aspectRatio },
3701
- ...input.resolution !== undefined && { resolution: input.resolution },
3702
- ...input.generateAudio !== undefined && { generate_audio: input.generateAudio },
3703
- ...input.frameImages !== undefined && { frame_images: [...input.frameImages] },
3704
- ...input.inputReferences !== undefined && {
3705
- input_references: [...input.inputReferences]
3722
+ prompt: request.prompt,
3723
+ ...request.duration !== undefined && { duration: request.duration },
3724
+ ...request.aspectRatio !== undefined && { aspect_ratio: request.aspectRatio },
3725
+ ...request.resolution !== undefined && { resolution: request.resolution },
3726
+ ...request.generateAudio !== undefined && { generate_audio: request.generateAudio },
3727
+ ...request.frameImages !== undefined && { frame_images: [...request.frameImages] },
3728
+ ...request.inputReferences !== undefined && {
3729
+ input_references: [...request.inputReferences]
3706
3730
  },
3707
3731
  ...callbackUrl !== undefined && { callback_url: callbackUrl },
3708
3732
  ...provider !== undefined && { provider }
@@ -3712,28 +3736,25 @@ async function openRouterSubmitVideo(input) {
3712
3736
  path: "/videos",
3713
3737
  method: "POST",
3714
3738
  body,
3715
- schema: VideoSubmitResponseSchema
3739
+ schema: OpenRouterVideoSubmitResponseSchema
3716
3740
  });
3717
3741
  return {
3718
3742
  id: response.data.id,
3719
3743
  jobStatus: response.data.status,
3720
3744
  ...response.data.polling_url !== undefined && { pollingUrl: response.data.polling_url },
3721
3745
  raw: response.data,
3722
- status: response.status,
3723
- ...response.generationId !== undefined && { generationId: response.generationId },
3724
- ...response.requestId !== undefined && { requestId: response.requestId },
3725
- ...response.costUsd !== undefined && { costUsd: response.costUsd },
3726
- headers: response.headers
3746
+ ...responseMetaOf(response)
3727
3747
  };
3728
3748
  }
3729
3749
  async function openRouterGetVideo(input) {
3730
3750
  assertOpenRouterDirectAuth(input);
3731
- const jobId = assertOpenRouterPathSegment("jobId", input.jobId);
3751
+ const request = parseOpenRouterRequest("openRouterGetVideo", VideoJobRequestSchema, input);
3752
+ const jobId = assertOpenRouterPathSegment("jobId", request.jobId);
3732
3753
  const response = await openRouterRequestJson({
3733
3754
  ...pickOpenRouterTransport(input),
3734
3755
  path: `/videos/${encodeURIComponent(jobId)}`,
3735
3756
  method: "GET",
3736
- schema: VideoStatusResponseSchema
3757
+ schema: OpenRouterVideoStatusResponseSchema
3737
3758
  });
3738
3759
  return {
3739
3760
  id: response.data.id,
@@ -3746,26 +3767,25 @@ async function openRouterGetVideo(input) {
3746
3767
  ...response.data.usage !== undefined && { usage: response.data.usage },
3747
3768
  ...response.data.error !== undefined && { error: response.data.error },
3748
3769
  raw: response.data,
3749
- status: response.status,
3750
- ...response.generationId !== undefined && { generationId: response.generationId },
3751
- ...response.requestId !== undefined && { requestId: response.requestId },
3752
- ...response.costUsd !== undefined && { costUsd: response.costUsd },
3753
- headers: response.headers
3770
+ ...responseMetaOf(response)
3754
3771
  };
3755
3772
  }
3756
3773
  async function openRouterDownloadVideo(input) {
3757
3774
  assertOpenRouterDirectAuth(input);
3758
- const jobId = assertOpenRouterPathSegment("jobId", input.jobId);
3775
+ const request = parseOpenRouterRequest("openRouterDownloadVideo", VideoJobRequestSchema, input);
3776
+ const jobId = assertOpenRouterPathSegment("jobId", request.jobId);
3777
+ const index = request.index;
3778
+ assertNonNegativeSafeInteger("openRouterDownloadVideo: index", index, RangeError);
3759
3779
  return openRouterRequestStream({
3760
3780
  ...pickOpenRouterTransport(input),
3761
3781
  path: `/videos/${encodeURIComponent(jobId)}/content`,
3762
- method: "GET"
3782
+ method: "GET",
3783
+ ...index !== undefined && { query: { index } }
3763
3784
  });
3764
3785
  }
3786
+
3765
3787
  // src/agent-runtime/providers/openrouter-retrieval.ts
3766
- import { z as z10 } from "zod";
3767
- var NonNegativeInt3 = z10.int().nonnegative();
3768
- var NonNegativeNum3 = z10.number().nonnegative();
3788
+ import { z as z11 } from "zod";
3769
3789
  var EMBEDDINGS_OWNED_KEYS = [
3770
3790
  "model",
3771
3791
  "input",
@@ -3775,41 +3795,39 @@ var EMBEDDINGS_OWNED_KEYS = [
3775
3795
  "provider"
3776
3796
  ];
3777
3797
  var RERANK_OWNED_KEYS = ["model", "query", "documents", "top_n", "provider"];
3778
- var RetrievalUsageSchema = z10.object({
3779
- prompt_tokens: NonNegativeInt3.optional(),
3780
- completion_tokens: NonNegativeInt3.optional(),
3781
- input_tokens: NonNegativeInt3.optional(),
3782
- output_tokens: NonNegativeInt3.optional(),
3783
- total_tokens: NonNegativeInt3.optional(),
3784
- cost: NonNegativeNum3.optional(),
3785
- is_byok: z10.boolean().optional()
3786
- }).loose();
3787
- var EmbeddingDatumSchema = z10.object({
3788
- index: NonNegativeInt3,
3789
- embedding: z10.union([z10.array(z10.number()), z10.string()])
3798
+ var EmbeddingDatumSchema = z11.object({
3799
+ index: NonNegativeInt,
3800
+ embedding: z11.union([z11.array(z11.number()), z11.string()])
3790
3801
  }).loose();
3791
- var EmbeddingsResponseSchema = z10.object({
3792
- model: z10.string().min(1).optional(),
3793
- data: z10.array(EmbeddingDatumSchema),
3794
- usage: RetrievalUsageSchema.optional()
3802
+ var OpenRouterEmbeddingsResponseSchema = z11.object({
3803
+ model: z11.string().min(1).optional(),
3804
+ data: z11.array(EmbeddingDatumSchema),
3805
+ usage: OpenRouterUsageSchema.optional()
3795
3806
  }).loose();
3807
+ var EmbeddingsRequestSchema = z11.object({
3808
+ model: z11.string(),
3809
+ input: z11.union([z11.string(), z11.array(z11.string()).min(1).readonly()]),
3810
+ encodingFormat: z11.enum(["float", "base64"]).optional(),
3811
+ dimensions: RangedNumber.optional(),
3812
+ user: z11.string().optional(),
3813
+ provider: OpenRouterProviderRoutingSchema.optional(),
3814
+ extraBody: ExtraBodySchema.optional()
3815
+ });
3796
3816
  async function openRouterEmbeddings(input) {
3797
3817
  assertOpenRouterDirectAuth(input);
3798
- const model = assertNonEmptyOpenRouterField("openRouterEmbeddings", "model", input.model);
3799
- if (Array.isArray(input.input) && input.input.length === 0) {
3800
- throw new TypeError("openRouterEmbeddings: input array must not be empty");
3801
- }
3802
- if (input.dimensions !== undefined)
3803
- assertPositiveSafeInteger("dimensions", input.dimensions);
3804
- assertNoExtraBodyClash("openRouterEmbeddings", input.extraBody, EMBEDDINGS_OWNED_KEYS);
3805
- const provider = input.provider !== undefined ? serializeOpenRouterProviderRouting(input.provider) : undefined;
3818
+ const request = parseOpenRouterRequest("openRouterEmbeddings", EmbeddingsRequestSchema, input);
3819
+ const model = assertNonEmptyOpenRouterField("openRouterEmbeddings", "model", request.model);
3820
+ if (request.dimensions !== undefined)
3821
+ assertPositiveSafeInteger("dimensions", request.dimensions);
3822
+ assertNoExtraBodyClash("openRouterEmbeddings", request.extraBody, EMBEDDINGS_OWNED_KEYS);
3823
+ const provider = request.provider !== undefined ? serializeOpenRouterProviderRouting(request.provider) : undefined;
3806
3824
  const body = {
3807
- ...input.extraBody ?? {},
3825
+ ...request.extraBody ?? {},
3808
3826
  model,
3809
- input: Array.isArray(input.input) ? [...input.input] : input.input,
3810
- ...input.encodingFormat !== undefined && { encoding_format: input.encodingFormat },
3811
- ...input.dimensions !== undefined && { dimensions: input.dimensions },
3812
- ...input.user !== undefined && { user: input.user },
3827
+ input: typeof request.input === "string" ? request.input : [...request.input],
3828
+ ...request.encodingFormat !== undefined && { encoding_format: request.encodingFormat },
3829
+ ...request.dimensions !== undefined && { dimensions: request.dimensions },
3830
+ ...request.user !== undefined && { user: request.user },
3813
3831
  ...provider !== undefined && { provider }
3814
3832
  };
3815
3833
  const response = await openRouterRequestJson({
@@ -3817,47 +3835,62 @@ async function openRouterEmbeddings(input) {
3817
3835
  path: "/embeddings",
3818
3836
  method: "POST",
3819
3837
  body,
3820
- schema: EmbeddingsResponseSchema
3838
+ schema: OpenRouterEmbeddingsResponseSchema
3821
3839
  });
3822
3840
  return {
3823
3841
  ...response.data.model !== undefined && { model: response.data.model },
3824
3842
  data: response.data.data,
3825
3843
  ...response.data.usage !== undefined && { usage: response.data.usage },
3826
3844
  raw: response.data,
3827
- status: response.status,
3828
- ...response.generationId !== undefined && { generationId: response.generationId },
3829
- ...response.requestId !== undefined && { requestId: response.requestId },
3830
- ...response.costUsd !== undefined && { costUsd: response.costUsd },
3831
- headers: response.headers
3845
+ ...responseMetaOf(response)
3832
3846
  };
3833
3847
  }
3834
- var RerankResultItemSchema = z10.object({
3835
- index: NonNegativeInt3,
3836
- relevance_score: z10.number().finite(),
3837
- document: z10.object({ text: z10.string() }).loose().optional()
3848
+ var RerankDocumentSchema = z11.union([
3849
+ z11.string(),
3850
+ z11.strictObject({
3851
+ text: z11.string().optional(),
3852
+ image: z11.string().refine((value) => /^(?:https?:\/\/|data:image\/)/iu.test(value.trim()), {
3853
+ message: "image must be an http(s) URL or a data:image/ URI"
3854
+ }).optional()
3855
+ }).refine((value) => value.text !== undefined || value.image !== undefined, {
3856
+ message: "a rerank document object needs text or image"
3857
+ })
3858
+ ]);
3859
+ var RerankDocumentsSchema = z11.array(RerankDocumentSchema).min(1).readonly();
3860
+ var RerankResultDocumentSchema = z11.object({ text: z11.string().optional(), image: z11.string().optional() }).loose();
3861
+ var RerankResultItemSchema = z11.object({
3862
+ index: NonNegativeInt,
3863
+ relevance_score: z11.number().finite(),
3864
+ document: RerankResultDocumentSchema.optional()
3838
3865
  }).loose();
3839
- var RerankResponseSchema = z10.object({
3840
- results: z10.array(RerankResultItemSchema),
3841
- meta: z10.record(z10.string(), z10.unknown()).optional(),
3842
- usage: RetrievalUsageSchema.optional()
3866
+ var OpenRouterRerankResponseSchema = z11.object({
3867
+ results: z11.array(RerankResultItemSchema),
3868
+ meta: z11.record(z11.string(), z11.unknown()).optional(),
3869
+ usage: OpenRouterUsageSchema.optional()
3843
3870
  }).loose();
3871
+ var RerankRequestSchema = z11.object({
3872
+ model: z11.string(),
3873
+ query: z11.string(),
3874
+ documents: RerankDocumentsSchema,
3875
+ topN: RangedNumber.optional(),
3876
+ provider: OpenRouterProviderRoutingSchema.optional(),
3877
+ extraBody: ExtraBodySchema.optional()
3878
+ });
3844
3879
  async function openRouterRerank(input) {
3845
3880
  assertOpenRouterDirectAuth(input);
3846
- const model = assertNonEmptyOpenRouterField("openRouterRerank", "model", input.model);
3847
- assertNonEmptyOpenRouterField("openRouterRerank", "query", input.query);
3848
- if (input.documents.length === 0) {
3849
- throw new TypeError("openRouterRerank: documents must be a non-empty array");
3850
- }
3851
- if (input.topN !== undefined)
3852
- assertPositiveSafeInteger("topN", input.topN);
3853
- assertNoExtraBodyClash("openRouterRerank", input.extraBody, RERANK_OWNED_KEYS);
3854
- const provider = input.provider !== undefined ? serializeOpenRouterProviderRouting(input.provider) : undefined;
3881
+ const request = parseOpenRouterRequest("openRouterRerank", RerankRequestSchema, input);
3882
+ const model = assertNonEmptyOpenRouterField("openRouterRerank", "model", request.model);
3883
+ assertNonEmptyOpenRouterField("openRouterRerank", "query", request.query);
3884
+ if (request.topN !== undefined)
3885
+ assertPositiveSafeInteger("topN", request.topN);
3886
+ assertNoExtraBodyClash("openRouterRerank", request.extraBody, RERANK_OWNED_KEYS);
3887
+ const provider = request.provider !== undefined ? serializeOpenRouterProviderRouting(request.provider) : undefined;
3855
3888
  const body = {
3856
- ...input.extraBody ?? {},
3889
+ ...request.extraBody ?? {},
3857
3890
  model,
3858
- query: input.query,
3859
- documents: [...input.documents],
3860
- ...input.topN !== undefined && { top_n: input.topN },
3891
+ query: request.query,
3892
+ documents: [...request.documents],
3893
+ ...request.topN !== undefined && { top_n: request.topN },
3861
3894
  ...provider !== undefined && { provider }
3862
3895
  };
3863
3896
  const response = await openRouterRequestJson({
@@ -3865,7 +3898,7 @@ async function openRouterRerank(input) {
3865
3898
  path: "/rerank",
3866
3899
  method: "POST",
3867
3900
  body,
3868
- schema: RerankResponseSchema
3901
+ schema: OpenRouterRerankResponseSchema
3869
3902
  });
3870
3903
  return {
3871
3904
  results: response.data.results.map((item) => ({
@@ -3876,17 +3909,320 @@ async function openRouterRerank(input) {
3876
3909
  ...response.data.meta !== undefined && { meta: response.data.meta },
3877
3910
  ...response.data.usage !== undefined && { usage: response.data.usage },
3878
3911
  raw: response.data,
3912
+ ...responseMetaOf(response)
3913
+ };
3914
+ }
3915
+
3916
+ // src/agent-runtime/providers/openrouter-speech.ts
3917
+ import { z as z12 } from "zod";
3918
+ var TTS_OWNED_KEYS = [
3919
+ "model",
3920
+ "input",
3921
+ "voice",
3922
+ "instructions",
3923
+ "response_format",
3924
+ "speed",
3925
+ "output_delivery",
3926
+ "provider"
3927
+ ];
3928
+ var MAX_URL_DELIVERY_BYTES = 64 * 1024;
3929
+ var SpeechFormatSchema = z12.enum(["mp3", "pcm", "wav"]);
3930
+ var SpeechTurnSchema = z12.strictObject({
3931
+ text: z12.string().refine((text) => text.trim().length > 0, "turn text must be non-empty"),
3932
+ voice: z12.string().refine((voice) => voice.trim().length > 0, "turn voice must be non-empty").optional(),
3933
+ instructions: z12.string().optional()
3934
+ });
3935
+ var SpeechTurnsSchema = z12.array(SpeechTurnSchema).min(1).readonly();
3936
+ var OpenRouterSpeechUrlResponseSchema = z12.object({
3937
+ url: z12.url(),
3938
+ expires_at: NonNegativeInt,
3939
+ media_type: z12.string().min(1)
3940
+ }).loose();
3941
+ var SpeechRequestSchema = z12.object({
3942
+ model: z12.string(),
3943
+ input: z12.union([z12.string(), SpeechTurnsSchema]),
3944
+ voice: z12.string().optional(),
3945
+ instructions: z12.string().optional(),
3946
+ responseFormat: SpeechFormatSchema.optional(),
3947
+ outputDelivery: z12.enum(["stream", "url"]).optional(),
3948
+ speed: RangedNumber.optional(),
3949
+ provider: OpenRouterProviderRoutingSchema.optional(),
3950
+ extraBody: ExtraBodySchema.optional()
3951
+ });
3952
+ function speechBody(input, model) {
3953
+ const request = parseOpenRouterRequest("openRouterAudioSpeech", SpeechRequestSchema, input);
3954
+ const speechInput = typeof request.input === "string" ? assertNonEmptyOpenRouterField("openRouterAudioSpeech", "input", request.input) : [...request.input];
3955
+ const voice = request.voice !== undefined ? assertNonEmptyOpenRouterField("openRouterAudioSpeech", "voice", request.voice) : undefined;
3956
+ if (request.speed !== undefined && (!Number.isFinite(request.speed) || request.speed <= 0)) {
3957
+ throw new RangeError("openRouterAudioSpeech: speed must be a positive finite number");
3958
+ }
3959
+ assertNoExtraBodyClash("openRouterAudioSpeech", request.extraBody, TTS_OWNED_KEYS);
3960
+ const provider = request.provider !== undefined ? serializeOpenRouterProviderRouting(request.provider) : undefined;
3961
+ return {
3962
+ ...request.extraBody ?? {},
3963
+ model,
3964
+ input: speechInput,
3965
+ ...voice !== undefined && { voice },
3966
+ ...request.instructions !== undefined && { instructions: request.instructions },
3967
+ ...request.responseFormat !== undefined && { response_format: request.responseFormat },
3968
+ ...request.outputDelivery !== undefined && { output_delivery: request.outputDelivery },
3969
+ ...request.speed !== undefined && { speed: request.speed },
3970
+ ...provider !== undefined && { provider }
3971
+ };
3972
+ }
3973
+ async function readUrlDelivery(response, signal) {
3974
+ const failure = (message, cause) => new AgentProviderError2(message, {
3975
+ provider: "openrouter",
3976
+ statusCode: response.status,
3977
+ retryable: false,
3978
+ ...response.requestId !== undefined && { requestId: response.requestId },
3979
+ responseHeaders: response.headers,
3980
+ ...cause !== undefined && { cause }
3981
+ });
3982
+ const read = await readBoundedChunks(response.body, {
3983
+ maxBytes: MAX_URL_DELIVERY_BYTES,
3984
+ signal
3985
+ });
3986
+ if (read.kind === "over-limit") {
3987
+ throw failure(`OpenRouter speech URL response exceeded ${MAX_URL_DELIVERY_BYTES} byte limit`);
3988
+ }
3989
+ const text = new TextDecoder().decode(concatChunks(read.chunks, read.total));
3990
+ let parsed;
3991
+ try {
3992
+ parsed = JSON.parse(text);
3993
+ } catch (error) {
3994
+ throw failure(`OpenRouter returned invalid speech URL JSON: ${redactProviderFailureText(text, 256)}`, error);
3995
+ }
3996
+ const delivery = OpenRouterSpeechUrlResponseSchema.safeParse(parsed);
3997
+ if (!delivery.success) {
3998
+ throw failure(`OpenRouter speech URL response failed schema validation: ${redactProviderFailureText(delivery.error.message, 512)}`, delivery.error);
3999
+ }
4000
+ return {
4001
+ delivery: "url",
4002
+ url: delivery.data.url,
4003
+ expiresAt: delivery.data.expires_at,
4004
+ mediaType: delivery.data.media_type,
4005
+ status: response.status,
4006
+ ...response.generationId !== undefined && { generationId: response.generationId },
4007
+ ...response.requestId !== undefined && { requestId: response.requestId },
4008
+ headers: response.headers
4009
+ };
4010
+ }
4011
+ async function openRouterAudioSpeech(input) {
4012
+ assertOpenRouterDirectAuth(input);
4013
+ const model = assertNonEmptyOpenRouterField("openRouterAudioSpeech", "model", input.model);
4014
+ const body = speechBody(input, model);
4015
+ const timeoutMs = input.timeoutMs ?? DEFAULT_OPENROUTER_REQUEST_TIMEOUT_MS;
4016
+ const startedAt = Date.now();
4017
+ const response = await openRouterRequestStream({
4018
+ ...pickOpenRouterTransport(input),
4019
+ path: "/audio/speech",
4020
+ method: "POST",
4021
+ body
4022
+ });
4023
+ if (input.outputDelivery === "url" && JSON_CONTENT_TYPE.test(response.contentType)) {
4024
+ return withSignalDeadline(Math.max(1, timeoutMs - (Date.now() - startedAt)), input.signal, () => abortError(`OpenRouter stream /audio/speech timed out after ${timeoutMs} ms`, "TimeoutError"), (signal) => readUrlDelivery(response, signal));
4025
+ }
4026
+ return {
4027
+ delivery: "stream",
4028
+ audio: response.body,
4029
+ contentType: response.contentType,
3879
4030
  status: response.status,
3880
4031
  ...response.generationId !== undefined && { generationId: response.generationId },
3881
4032
  ...response.requestId !== undefined && { requestId: response.requestId },
3882
- ...response.costUsd !== undefined && { costUsd: response.costUsd },
3883
4033
  headers: response.headers
3884
4034
  };
3885
4035
  }
4036
+
4037
+ // src/agent-runtime/providers/openrouter-systemone.ts
4038
+ import { z as z13 } from "zod";
4039
+ var SYSTEMONE_OWNED_KEYS = [
4040
+ "model",
4041
+ "state",
4042
+ "questions",
4043
+ "assets",
4044
+ "provider",
4045
+ "session_id",
4046
+ "user",
4047
+ "response_format"
4048
+ ];
4049
+ var GuidanceSchema = z13.union([
4050
+ z13.string(),
4051
+ z13.record(z13.string(), z13.unknown()).readonly(),
4052
+ z13.array(z13.unknown()).readonly()
4053
+ ]);
4054
+ var SystemOneNoulQuestionSchema = z13.strictObject({
4055
+ type: z13.literal("noul"),
4056
+ instructions: GuidanceSchema.nullable().optional(),
4057
+ criteria: z13.strictObject({
4058
+ true: GuidanceSchema.nullable().optional(),
4059
+ false: GuidanceSchema.nullable().optional()
4060
+ }).optional()
4061
+ });
4062
+ var SystemOneChoiceQuestionSchema = z13.strictObject({
4063
+ type: z13.literal("choice"),
4064
+ instructions: GuidanceSchema.nullable().optional(),
4065
+ criteria: z13.record(z13.string().min(1), GuidanceSchema.nullable()).readonly()
4066
+ });
4067
+ var SystemOneScoreQuestionSchema = z13.strictObject({
4068
+ type: z13.literal("score"),
4069
+ instructions: GuidanceSchema.nullable().optional(),
4070
+ criteria: z13.array(GuidanceSchema).min(1).readonly()
4071
+ });
4072
+ var SystemOneBoxQuestionSchema = z13.strictObject({
4073
+ type: z13.literal("box"),
4074
+ instructions: GuidanceSchema
4075
+ });
4076
+ var SystemOneQuestionSchema = z13.discriminatedUnion("type", [
4077
+ SystemOneNoulQuestionSchema,
4078
+ SystemOneChoiceQuestionSchema,
4079
+ SystemOneScoreQuestionSchema,
4080
+ SystemOneBoxQuestionSchema
4081
+ ]);
4082
+ var SystemOneNoulAnswerSchema = z13.object({
4083
+ type: z13.literal("noul"),
4084
+ noul: Probability,
4085
+ confidence: Probability.optional()
4086
+ }).loose();
4087
+ var SystemOneChoiceAnswerSchema = z13.object({
4088
+ type: z13.literal("choice"),
4089
+ choice: z13.string(),
4090
+ confidence: Probability.optional(),
4091
+ probabilities: z13.record(z13.string(), Probability).optional()
4092
+ }).loose();
4093
+ var SystemOneScoreAnswerSchema = z13.object({
4094
+ type: z13.literal("score"),
4095
+ score: z13.number().finite(),
4096
+ confidence: Probability.optional(),
4097
+ legend: z13.record(z13.string(), GuidanceSchema).optional(),
4098
+ probabilities: z13.record(z13.string(), Probability).optional()
4099
+ }).loose();
4100
+ var SystemOneBoxAnswerSchema = z13.object({
4101
+ type: z13.literal("box"),
4102
+ box: z13.object({
4103
+ top: z13.number().finite(),
4104
+ bottom: z13.number().finite(),
4105
+ left: z13.number().finite(),
4106
+ right: z13.number().finite()
4107
+ }).loose(),
4108
+ confidence: Probability.optional()
4109
+ }).loose();
4110
+ var SystemOneRefusalAnswerSchema = z13.object({ type: z13.literal("refusal") }).loose();
4111
+ var SystemOneAnswerSchema = z13.discriminatedUnion("type", [
4112
+ SystemOneNoulAnswerSchema,
4113
+ SystemOneChoiceAnswerSchema,
4114
+ SystemOneScoreAnswerSchema,
4115
+ SystemOneBoxAnswerSchema,
4116
+ SystemOneRefusalAnswerSchema
4117
+ ]);
4118
+ var OpenRouterSystemOneResponseSchema = z13.object({
4119
+ id: z13.string().min(1).optional(),
4120
+ model: z13.string().min(1).optional(),
4121
+ answers: z13.record(z13.string(), SystemOneAnswerSchema),
4122
+ usage: OpenRouterUsageSchema.optional()
4123
+ }).loose();
4124
+ var SystemOneStateSchema = z13.union([z13.string(), z13.record(z13.string(), z13.unknown()).readonly(), z13.array(z13.unknown()).readonly()], { error: "state must be a string, a JSON object, or a JSON array" });
4125
+ var SystemOneQuestionsMapSchema = z13.record(z13.string().min(1), SystemOneQuestionSchema).readonly().refine((value) => Object.keys(value).length > 0, {
4126
+ message: "openRouterSystemOne requires at least one question"
4127
+ });
4128
+ var SystemOneImageAssetSchema = z13.strictObject({
4129
+ format: z13.enum(["png", "jpg", "jpeg"]),
4130
+ dataBase64: z13.base64().min(1)
4131
+ });
4132
+ var SystemOneRequestSchema = z13.object({
4133
+ model: z13.string(),
4134
+ state: SystemOneStateSchema,
4135
+ questions: SystemOneQuestionsMapSchema,
4136
+ assets: z13.record(z13.string().min(1), SystemOneImageAssetSchema).readonly().optional(),
4137
+ sessionId: z13.string().min(1).max(256).optional(),
4138
+ user: z13.string().min(1).max(256).optional(),
4139
+ provider: OpenRouterProviderRoutingSchema.optional(),
4140
+ extraBody: ExtraBodySchema.optional()
4141
+ });
4142
+ async function openRouterSystemOne(input) {
4143
+ assertOpenRouterDirectAuth(input);
4144
+ const request = parseOpenRouterRequest("openRouterSystemOne", SystemOneRequestSchema, input);
4145
+ const model = assertNonEmptyOpenRouterField("openRouterSystemOne", "model", request.model);
4146
+ assertNoExtraBodyClash("openRouterSystemOne", request.extraBody, SYSTEMONE_OWNED_KEYS);
4147
+ const provider = request.provider !== undefined ? serializeOpenRouterProviderRouting(request.provider) : undefined;
4148
+ const body = {
4149
+ ...request.extraBody ?? {},
4150
+ model,
4151
+ state: request.state,
4152
+ questions: request.questions,
4153
+ ...request.assets !== undefined && {
4154
+ assets: Object.fromEntries(Object.entries(request.assets).map(([key, asset]) => [
4155
+ key,
4156
+ { type: "image", format: asset.format, data_base64: asset.dataBase64 }
4157
+ ]))
4158
+ },
4159
+ ...provider !== undefined && { provider },
4160
+ ...request.sessionId !== undefined && { session_id: request.sessionId },
4161
+ ...request.user !== undefined && { user: request.user }
4162
+ };
4163
+ const response = await openRouterRequestJson({
4164
+ ...pickOpenRouterTransport(input),
4165
+ path: "/systemone",
4166
+ method: "POST",
4167
+ body,
4168
+ schema: OpenRouterSystemOneResponseSchema
4169
+ });
4170
+ return {
4171
+ ...response.data.model !== undefined && { model: response.data.model },
4172
+ answers: response.data.answers,
4173
+ ...response.data.usage !== undefined && { usage: response.data.usage },
4174
+ raw: response.data,
4175
+ ...responseMetaOf(response)
4176
+ };
4177
+ }
4178
+
4179
+ // src/agent-runtime/providers/openrouter-client.ts
4180
+ function underCall(defaults, input) {
4181
+ const headers = defaults.headers !== undefined && input.headers !== undefined ? { ...defaults.headers, ...input.headers } : input.headers ?? defaults.headers;
4182
+ const providerApiKeys = defaults.providerApiKeys !== undefined && input.providerApiKeys !== undefined ? { ...defaults.providerApiKeys, ...input.providerApiKeys } : input.providerApiKeys ?? defaults.providerApiKeys;
4183
+ return {
4184
+ ...defaults,
4185
+ ...input,
4186
+ ...headers !== undefined && { headers },
4187
+ ...providerApiKeys !== undefined && { providerApiKeys }
4188
+ };
4189
+ }
4190
+ function withDefaults(call, defaults) {
4191
+ return (input) => call(underCall(defaults, input));
4192
+ }
4193
+ function createOpenRouterClient(options = {}) {
4194
+ validateOpenRouterBaseUrl(options.baseUrl);
4195
+ assertValidOpenRouterApiKey(options.apiKey);
4196
+ const defaults = {
4197
+ ...options,
4198
+ ...options.headers !== undefined && { headers: { ...options.headers } },
4199
+ ...options.providerApiKeys !== undefined && {
4200
+ providerApiKeys: { ...options.providerApiKeys }
4201
+ }
4202
+ };
4203
+ function audioSpeech(input) {
4204
+ return openRouterAudioSpeech(underCall(defaults, input));
4205
+ }
4206
+ function requestJson(input) {
4207
+ const merged = underCall(defaults, input);
4208
+ return input.schema === undefined ? openRouterRequestJson({ ...merged, schema: undefined }) : openRouterRequestJson({ ...merged, schema: input.schema });
4209
+ }
4210
+ return {
4211
+ audioTranscription: withDefaults(openRouterAudioTranscription, defaults),
4212
+ audioSpeech,
4213
+ systemOne: withDefaults(openRouterSystemOne, defaults),
4214
+ generateImages: withDefaults(openRouterGenerateImages, defaults),
4215
+ submitVideo: withDefaults(openRouterSubmitVideo, defaults),
4216
+ getVideo: withDefaults(openRouterGetVideo, defaults),
4217
+ downloadVideo: withDefaults(openRouterDownloadVideo, defaults),
4218
+ embeddings: withDefaults(openRouterEmbeddings, defaults),
4219
+ rerank: withDefaults(openRouterRerank, defaults),
4220
+ requestJson,
4221
+ requestStream: withDefaults(openRouterRequestStream, defaults)
4222
+ };
4223
+ }
3886
4224
  // src/agent-runtime/providers/openrouter-spend.ts
3887
- import { z as z11 } from "zod";
3888
- var Count = z11.int().nonnegative();
3889
- var NonNegativeFinite = z11.number().nonnegative();
4225
+ import { z as z14 } from "zod";
3890
4226
  function readOptional(schema, value) {
3891
4227
  if (value === undefined || value === null)
3892
4228
  return;
@@ -3908,12 +4244,12 @@ var openRouterSpendFacts = {
3908
4244
  const usage = isRecord(value.usage) ? value.usage : undefined;
3909
4245
  const inputDetails = usage && isRecord(usage.input_tokens_details) ? usage.input_tokens_details : undefined;
3910
4246
  const outputDetails = usage && isRecord(usage.output_tokens_details) ? usage.output_tokens_details : undefined;
3911
- const inputTokens = restBase.inputTokens ?? readOptional(Count, usage?.input_tokens);
3912
- const outputTokens = restBase.outputTokens ?? readOptional(Count, usage?.output_tokens);
3913
- const cacheReadTokens = restBase.cacheReadTokens ?? readOptional(Count, inputDetails?.cached_tokens);
3914
- const cacheWriteTokens = restBase.cacheWriteTokens ?? readOptional(Count, inputDetails?.cache_write_tokens);
3915
- const reasoningTokens = restBase.reasoningTokens ?? readOptional(Count, outputDetails?.reasoning_tokens);
3916
- const seconds = readOptional(NonNegativeFinite, usage?.seconds);
4247
+ const inputTokens = restBase.inputTokens ?? readOptional(NonNegativeInt, usage?.input_tokens);
4248
+ const outputTokens = restBase.outputTokens ?? readOptional(NonNegativeInt, usage?.output_tokens);
4249
+ const cacheReadTokens = restBase.cacheReadTokens ?? readOptional(NonNegativeInt, inputDetails?.cached_tokens);
4250
+ const cacheWriteTokens = restBase.cacheWriteTokens ?? readOptional(NonNegativeInt, inputDetails?.cache_write_tokens);
4251
+ const reasoningTokens = restBase.reasoningTokens ?? readOptional(NonNegativeInt, outputDetails?.reasoning_tokens);
4252
+ const seconds = readOptional(NonNegativeNum, usage?.seconds);
3917
4253
  return {
3918
4254
  ...restBase,
3919
4255
  ...generationId !== undefined && { providerRequestId: generationId },
@@ -3935,18 +4271,17 @@ function openRouterSpendProvider(options) {
3935
4271
  facts: openRouterSpendFacts
3936
4272
  };
3937
4273
  }
3938
- var GenerationSchema = z11.object({
3939
- data: z11.object({
3940
- total_cost: z11.number().nonnegative().nullish(),
3941
- provider_name: z11.string().min(1).nullish(),
3942
- model: z11.string().min(1).nullish(),
3943
- native_tokens_prompt: z11.int().nonnegative().nullish(),
3944
- native_tokens_completion: z11.int().nonnegative().nullish(),
3945
- native_tokens_reasoning: z11.int().nonnegative().nullish()
4274
+ var GenerationSchema = z14.object({
4275
+ data: z14.object({
4276
+ total_cost: NonNegativeNum.nullish(),
4277
+ provider_name: z14.string().min(1).nullish(),
4278
+ model: z14.string().min(1).nullish(),
4279
+ native_tokens_prompt: NonNegativeInt.nullish(),
4280
+ native_tokens_completion: NonNegativeInt.nullish(),
4281
+ native_tokens_reasoning: NonNegativeInt.nullish()
3946
4282
  }).loose()
3947
4283
  });
3948
4284
  function createOpenRouterSpendReconciler(options) {
3949
- const fetcher = options.fetcher ?? fetch;
3950
4285
  const timeoutMs = options.timeoutMs ?? 1e4;
3951
4286
  assertTimerMs("timeoutMs", timeoutMs);
3952
4287
  validateOpenRouterBaseUrl(options.baseUrl);
@@ -3954,17 +4289,25 @@ function createOpenRouterSpendReconciler(options) {
3954
4289
  const id = record.receipt?.facts.providerRequestId;
3955
4290
  if (id === undefined)
3956
4291
  return { costStatus: "unknown", failureCode: "no-generation-id" };
3957
- const url = resolveOpenRouterUrl(options.baseUrl, "/generation", { id });
3958
- let body;
4292
+ let data;
3959
4293
  try {
3960
4294
  const apiKey = typeof options.apiKey === "string" ? options.apiKey : await options.apiKey(record);
3961
- body = await withOpenRouterTimeout(timeoutMs, undefined, (signal) => openRouterJson({ fetcher, url, apiKey, signal, maxBytes: 1024 * 1024 }));
4295
+ const response = await openRouterRequestJson({
4296
+ path: "/generation",
4297
+ query: { id },
4298
+ schema: GenerationSchema,
4299
+ apiKey,
4300
+ timeoutMs,
4301
+ maxResponseBytes: 1024 * 1024,
4302
+ ...options.baseUrl !== undefined && { baseUrl: options.baseUrl },
4303
+ ...options.fetch !== undefined && { fetch: options.fetch }
4304
+ });
4305
+ data = response.data.data;
3962
4306
  } catch (error) {
3963
- if (error instanceof OpenRouterHttpError && error.status === 404)
4307
+ if (error instanceof AgentProviderError2 && error.statusCode === 404)
3964
4308
  return;
3965
4309
  throw error;
3966
4310
  }
3967
- const { data } = GenerationSchema.parse(body);
3968
4311
  if (data.total_cost == null)
3969
4312
  return;
3970
4313
  return {
@@ -3982,123 +4325,15 @@ function createOpenRouterSpendReconciler(options) {
3982
4325
  };
3983
4326
  };
3984
4327
  }
3985
- // src/agent-runtime/providers/openrouter-systemone.ts
3986
- import { z as z12 } from "zod";
3987
- var SYSTEMONE_OWNED_KEYS = [
3988
- "model",
3989
- "state",
3990
- "questions",
3991
- "provider",
3992
- "response_format"
3993
- ];
3994
- var ProbabilitySchema = z12.number().min(0).max(1);
3995
- var NonNegativeInt4 = z12.int().nonnegative();
3996
- var NonNegativeNum4 = z12.number().nonnegative();
3997
- var SystemOneNoulQuestionSchema = z12.strictObject({
3998
- type: z12.literal("noul"),
3999
- instructions: z12.string().min(1),
4000
- criteria: z12.object({
4001
- true: z12.string().nullable().optional(),
4002
- false: z12.string().nullable().optional()
4003
- }).loose().optional()
4004
- });
4005
- var SystemOneChoiceQuestionSchema = z12.strictObject({
4006
- type: z12.literal("choice"),
4007
- instructions: z12.string().min(1),
4008
- criteria: z12.record(z12.string().min(1), z12.string().nullable()).refine((value) => Object.keys(value).length >= 2, {
4009
- message: "System One choice question requires at least 2 criteria entries"
4010
- })
4011
- });
4012
- var SystemOneScoreQuestionSchema = z12.strictObject({
4013
- type: z12.literal("score"),
4014
- instructions: z12.string().min(1),
4015
- criteria: z12.array(z12.string().min(1)).min(2)
4016
- });
4017
- var SystemOneQuestionSchema = z12.discriminatedUnion("type", [
4018
- SystemOneNoulQuestionSchema,
4019
- SystemOneChoiceQuestionSchema,
4020
- SystemOneScoreQuestionSchema
4021
- ]);
4022
- var SystemOneNoulAnswerSchema = z12.object({
4023
- type: z12.literal("noul"),
4024
- noul: ProbabilitySchema
4025
- }).loose();
4026
- var SystemOneChoiceAnswerSchema = z12.object({
4027
- type: z12.literal("choice"),
4028
- choice: z12.string(),
4029
- confidence: ProbabilitySchema.optional(),
4030
- probabilities: z12.record(z12.string(), ProbabilitySchema).optional()
4031
- }).loose();
4032
- var SystemOneScoreAnswerSchema = z12.object({
4033
- type: z12.literal("score"),
4034
- score: z12.number().finite(),
4035
- confidence: ProbabilitySchema.optional(),
4036
- legend: z12.union([z12.array(z12.string()), z12.record(z12.string(), z12.string())]).optional(),
4037
- probabilities: z12.record(z12.string(), ProbabilitySchema).optional()
4038
- }).loose();
4039
- var SystemOneAnswerSchema = z12.discriminatedUnion("type", [
4040
- SystemOneNoulAnswerSchema,
4041
- SystemOneChoiceAnswerSchema,
4042
- SystemOneScoreAnswerSchema
4043
- ]);
4044
- var SystemOneUsageSchema = z12.object({
4045
- input_tokens: NonNegativeInt4.optional(),
4046
- output_tokens: NonNegativeInt4.optional(),
4047
- prompt_tokens: NonNegativeInt4.optional(),
4048
- completion_tokens: NonNegativeInt4.optional(),
4049
- total_tokens: NonNegativeInt4.optional(),
4050
- cost: NonNegativeNum4.optional()
4051
- }).loose();
4052
- var OpenRouterSystemOneResponseSchema = z12.object({
4053
- id: z12.string().min(1).optional(),
4054
- model: z12.string().min(1).optional(),
4055
- answers: z12.record(z12.string(), SystemOneAnswerSchema),
4056
- usage: SystemOneUsageSchema.optional()
4057
- }).loose();
4058
- var SystemOneQuestionsMapSchema = z12.record(z12.string().min(1), SystemOneQuestionSchema).refine((value) => Object.keys(value).length > 0, {
4059
- message: "openRouterSystemOne requires at least one question"
4060
- });
4061
- async function openRouterSystemOne(input) {
4062
- assertOpenRouterDirectAuth(input);
4063
- const model = assertNonEmptyOpenRouterField("openRouterSystemOne", "model", input.model);
4064
- const questions = SystemOneQuestionsMapSchema.parse(input.questions);
4065
- assertNoExtraBodyClash("openRouterSystemOne", input.extraBody, SYSTEMONE_OWNED_KEYS);
4066
- const provider = input.provider !== undefined ? serializeOpenRouterProviderRouting(input.provider) : undefined;
4067
- const body = {
4068
- ...input.extraBody ?? {},
4069
- model,
4070
- state: input.state,
4071
- questions,
4072
- ...provider !== undefined && { provider }
4073
- };
4074
- const response = await openRouterRequestJson({
4075
- ...pickOpenRouterTransport(input),
4076
- path: "/systemone",
4077
- method: "POST",
4078
- body,
4079
- schema: OpenRouterSystemOneResponseSchema
4080
- });
4081
- return {
4082
- ...response.data.model !== undefined && { model: response.data.model },
4083
- answers: response.data.answers,
4084
- ...response.data.usage !== undefined && { usage: response.data.usage },
4085
- raw: response.data,
4086
- status: response.status,
4087
- ...response.generationId !== undefined && { generationId: response.generationId },
4088
- ...response.requestId !== undefined && { requestId: response.requestId },
4089
- ...response.costUsd !== undefined && { costUsd: response.costUsd },
4090
- headers: response.headers
4091
- };
4092
- }
4093
4328
  export {
4094
4329
  OPENROUTER_API_BASE_URL,
4095
4330
  OpenRouterAdmissionPolicySchema,
4096
4331
  OpenRouterAdmissionReasonSchema,
4097
4332
  OpenRouterAudioTranscriptionResponseSchema,
4098
4333
  OpenRouterCatalogSnapshotSchema,
4334
+ OpenRouterEmbeddingsResponseSchema,
4099
4335
  OpenRouterEndpointSchema,
4100
4336
  OpenRouterEndpointSummarySchema,
4101
- OpenRouterHttpError,
4102
4337
  OpenRouterImageGenerationResponseSchema,
4103
4338
  OpenRouterMaxPriceSchema,
4104
4339
  OpenRouterModelAdmissionSchema,
@@ -4109,11 +4344,17 @@ export {
4109
4344
  OpenRouterProviderRoutingSchema,
4110
4345
  OpenRouterReasoningEffortSchema,
4111
4346
  OpenRouterRequestPolicySchema,
4347
+ OpenRouterRerankResponseSchema,
4112
4348
  OpenRouterRoutePinSchema,
4113
4349
  OpenRouterSnapshotModelSchema,
4350
+ OpenRouterSpeechUrlResponseSchema,
4114
4351
  OpenRouterSystemOneResponseSchema,
4352
+ OpenRouterUsageSchema,
4353
+ OpenRouterVideoStatusResponseSchema,
4354
+ OpenRouterVideoSubmitResponseSchema,
4115
4355
  createMemoryOpenRouterRouteStore,
4116
4356
  createOpenRouterCatalogCache,
4357
+ createOpenRouterClient,
4117
4358
  createOpenRouterRouteResolver,
4118
4359
  createOpenRouterSpendReconciler,
4119
4360
  evaluateOpenRouterModelAdmission,