stitchkit 0.133.2 → 0.134.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (616) hide show
  1. package/CHANGELOG.md +115 -0
  2. package/README.md +14 -11
  3. package/dist/agent-executor/acp/v1-connect.d.ts +3 -0
  4. package/dist/agent-executor/acp/v1-connect.d.ts.map +1 -1
  5. package/dist/agent-executor/acp/v1-map.d.ts +13 -3
  6. package/dist/agent-executor/acp/v1-map.d.ts.map +1 -1
  7. package/dist/agent-executor/acp/v1-protocol.d.ts +59 -0
  8. package/dist/agent-executor/acp/v1-protocol.d.ts.map +1 -1
  9. package/dist/agent-executor/codex/connect.d.ts +2 -0
  10. package/dist/agent-executor/codex/connect.d.ts.map +1 -1
  11. package/dist/agent-executor/codex/driver.d.ts +3 -0
  12. package/dist/agent-executor/codex/driver.d.ts.map +1 -1
  13. package/dist/agent-executor/contract.d.ts +42 -0
  14. package/dist/agent-executor/contract.d.ts.map +1 -1
  15. package/dist/agent-executor/engine-process.d.ts +20 -0
  16. package/dist/agent-executor/engine-process.d.ts.map +1 -1
  17. package/dist/agent-executor/executor-contract.d.ts +42 -0
  18. package/dist/agent-executor/executor-contract.d.ts.map +1 -1
  19. package/dist/agent-executor/handoff-schemas.d.ts +30 -0
  20. package/dist/agent-executor/handoff-schemas.d.ts.map +1 -1
  21. package/dist/agent-executor/projection.d.ts.map +1 -1
  22. package/dist/agent-executor/session-primitives.d.ts +4 -1
  23. package/dist/agent-executor/session-primitives.d.ts.map +1 -1
  24. package/dist/agent-executor/vocabulary.d.ts +100 -0
  25. package/dist/agent-executor/vocabulary.d.ts.map +1 -1
  26. package/dist/agent-parts/model.d.ts +1559 -0
  27. package/dist/agent-parts/model.d.ts.map +1 -0
  28. package/dist/agent-parts/parts.d.ts +21 -0
  29. package/dist/agent-parts/parts.d.ts.map +1 -1
  30. package/dist/agent-runtime/ai-sdk-convert.d.ts +15 -0
  31. package/dist/agent-runtime/ai-sdk-convert.d.ts.map +1 -0
  32. package/dist/agent-runtime/ai-sdk.d.ts +31 -0
  33. package/dist/agent-runtime/ai-sdk.d.ts.map +1 -0
  34. package/dist/agent-runtime/anthropic-media.d.ts +11 -0
  35. package/dist/agent-runtime/anthropic-media.d.ts.map +1 -0
  36. package/dist/agent-runtime/anthropic-messages.d.ts +24 -0
  37. package/dist/agent-runtime/anthropic-messages.d.ts.map +1 -0
  38. package/dist/agent-runtime/anthropic-options.d.ts +79 -0
  39. package/dist/agent-runtime/anthropic-options.d.ts.map +1 -0
  40. package/dist/agent-runtime/anthropic-response.d.ts +19 -0
  41. package/dist/agent-runtime/anthropic-response.d.ts.map +1 -0
  42. package/dist/agent-runtime/anthropic-sse.d.ts +4 -0
  43. package/dist/agent-runtime/anthropic-sse.d.ts.map +1 -0
  44. package/dist/agent-runtime/anthropic.d.ts +27 -0
  45. package/dist/agent-runtime/anthropic.d.ts.map +1 -0
  46. package/dist/agent-runtime/branch-observations.d.ts +25 -25
  47. package/dist/agent-runtime/branch-provider.d.ts +86 -0
  48. package/dist/agent-runtime/branch-provider.d.ts.map +1 -1
  49. package/dist/agent-runtime/branch-replay.d.ts +30 -0
  50. package/dist/agent-runtime/branch-replay.d.ts.map +1 -1
  51. package/dist/agent-runtime/browser-control-contract.d.ts +204 -0
  52. package/dist/agent-runtime/browser-control-contract.d.ts.map +1 -1
  53. package/dist/agent-runtime/browser-controller-view.d.ts +44 -0
  54. package/dist/agent-runtime/browser-controller-view.d.ts.map +1 -0
  55. package/dist/agent-runtime/browser-controller.d.ts +12 -8
  56. package/dist/agent-runtime/browser-controller.d.ts.map +1 -1
  57. package/dist/agent-runtime/child-budget-policy.d.ts +2 -3
  58. package/dist/agent-runtime/child-budget-policy.d.ts.map +1 -1
  59. package/dist/agent-runtime/compaction.d.ts +27 -10
  60. package/dist/agent-runtime/compaction.d.ts.map +1 -1
  61. package/dist/agent-runtime/control-interaction-schema.d.ts +157 -0
  62. package/dist/agent-runtime/control-interaction-schema.d.ts.map +1 -0
  63. package/dist/agent-runtime/control-schema.d.ts +183 -27
  64. package/dist/agent-runtime/control-schema.d.ts.map +1 -1
  65. package/dist/agent-runtime/control-view.d.ts +64 -0
  66. package/dist/agent-runtime/control-view.d.ts.map +1 -0
  67. package/dist/agent-runtime/conversations.d.ts +10 -0
  68. package/dist/agent-runtime/conversations.d.ts.map +1 -1
  69. package/dist/agent-runtime/deferred-tool-selection.d.ts +2 -2
  70. package/dist/agent-runtime/deferred-tool-selection.d.ts.map +1 -1
  71. package/dist/agent-runtime/deferred-tool-types.d.ts +2 -2
  72. package/dist/agent-runtime/deferred-tool-types.d.ts.map +1 -1
  73. package/dist/agent-runtime/deferred-tools-internal.d.ts +8 -11
  74. package/dist/agent-runtime/deferred-tools-internal.d.ts.map +1 -1
  75. package/dist/agent-runtime/deferred-tools.d.ts.map +1 -1
  76. package/dist/agent-runtime/event-schema.d.ts +80 -0
  77. package/dist/agent-runtime/event-schema.d.ts.map +1 -1
  78. package/dist/agent-runtime/harness-contract.d.ts +2 -2
  79. package/dist/agent-runtime/harness-contract.d.ts.map +1 -1
  80. package/dist/agent-runtime/harness-control.d.ts.map +1 -1
  81. package/dist/agent-runtime/harness-realtime.d.ts.map +1 -1
  82. package/dist/agent-runtime/harness.d.ts +2 -2
  83. package/dist/agent-runtime/harness.d.ts.map +1 -1
  84. package/dist/agent-runtime/history.d.ts +25 -16
  85. package/dist/agent-runtime/history.d.ts.map +1 -1
  86. package/dist/agent-runtime/invocation-attempt.d.ts +7 -3
  87. package/dist/agent-runtime/invocation-attempt.d.ts.map +1 -1
  88. package/dist/agent-runtime/invocation-payload.d.ts +13 -7
  89. package/dist/agent-runtime/invocation-payload.d.ts.map +1 -1
  90. package/dist/agent-runtime/invocation-stream.d.ts +20 -0
  91. package/dist/agent-runtime/invocation-stream.d.ts.map +1 -0
  92. package/dist/agent-runtime/invocations.d.ts +2 -2
  93. package/dist/agent-runtime/invocations.d.ts.map +1 -1
  94. package/dist/agent-runtime/models-driver-step.d.ts +212 -0
  95. package/dist/agent-runtime/models-driver-step.d.ts.map +1 -0
  96. package/dist/agent-runtime/models-driver-telemetry.d.ts +42 -0
  97. package/dist/agent-runtime/models-driver-telemetry.d.ts.map +1 -0
  98. package/dist/agent-runtime/models-driver.d.ts +235 -0
  99. package/dist/agent-runtime/models-driver.d.ts.map +1 -0
  100. package/dist/agent-runtime/models.d.ts +3 -26
  101. package/dist/agent-runtime/models.d.ts.map +1 -1
  102. package/dist/agent-runtime/observability.d.ts +64 -0
  103. package/dist/agent-runtime/observability.d.ts.map +1 -1
  104. package/dist/agent-runtime/openai-messages.d.ts +11 -0
  105. package/dist/agent-runtime/openai-messages.d.ts.map +1 -0
  106. package/dist/agent-runtime/openai-options.d.ts +91 -0
  107. package/dist/agent-runtime/openai-options.d.ts.map +1 -0
  108. package/dist/agent-runtime/openai-response.d.ts +77 -0
  109. package/dist/agent-runtime/openai-response.d.ts.map +1 -0
  110. package/dist/agent-runtime/openai-sse-state.d.ts +54 -0
  111. package/dist/agent-runtime/openai-sse-state.d.ts.map +1 -0
  112. package/dist/agent-runtime/openai-sse.d.ts +4 -0
  113. package/dist/agent-runtime/openai-sse.d.ts.map +1 -0
  114. package/dist/agent-runtime/openai.d.ts +31 -0
  115. package/dist/agent-runtime/openai.d.ts.map +1 -0
  116. package/dist/agent-runtime/openrouter-admission.d.ts +3 -0
  117. package/dist/agent-runtime/openrouter-admission.d.ts.map +1 -1
  118. package/dist/agent-runtime/openrouter-benchmarks.d.ts +17 -0
  119. package/dist/agent-runtime/openrouter-benchmarks.d.ts.map +1 -0
  120. package/dist/agent-runtime/openrouter-catalog-cache.d.ts +70 -0
  121. package/dist/agent-runtime/openrouter-catalog-cache.d.ts.map +1 -0
  122. package/dist/agent-runtime/openrouter-catalog-query.d.ts +57 -0
  123. package/dist/agent-runtime/openrouter-catalog-query.d.ts.map +1 -0
  124. package/dist/agent-runtime/openrouter-catalog.d.ts +189 -14
  125. package/dist/agent-runtime/openrouter-catalog.d.ts.map +1 -1
  126. package/dist/agent-runtime/openrouter-models.d.ts +168 -31
  127. package/dist/agent-runtime/openrouter-models.d.ts.map +1 -1
  128. package/dist/agent-runtime/openrouter-options.d.ts +45 -15
  129. package/dist/agent-runtime/openrouter-options.d.ts.map +1 -1
  130. package/dist/agent-runtime/openrouter-response.d.ts +22 -0
  131. package/dist/agent-runtime/openrouter-response.d.ts.map +1 -0
  132. package/dist/agent-runtime/openrouter.d.ts +21 -24
  133. package/dist/agent-runtime/openrouter.d.ts.map +1 -1
  134. package/dist/agent-runtime/owned-provider-stream.d.ts +4 -4
  135. package/dist/agent-runtime/owned-provider-stream.d.ts.map +1 -1
  136. package/dist/agent-runtime/prompt.d.ts +3 -3
  137. package/dist/agent-runtime/prompt.d.ts.map +1 -1
  138. package/dist/agent-runtime/protocol.d.ts +28 -3
  139. package/dist/agent-runtime/protocol.d.ts.map +1 -1
  140. package/dist/agent-runtime/provider-cache.d.ts +30 -0
  141. package/dist/agent-runtime/provider-cache.d.ts.map +1 -0
  142. package/dist/agent-runtime/provider-content.d.ts +147 -0
  143. package/dist/agent-runtime/provider-content.d.ts.map +1 -1
  144. package/dist/agent-runtime/provider-failure.d.ts +51 -26
  145. package/dist/agent-runtime/provider-failure.d.ts.map +1 -1
  146. package/dist/agent-runtime/provider-history.d.ts +13 -0
  147. package/dist/agent-runtime/provider-history.d.ts.map +1 -0
  148. package/dist/agent-runtime/provider-http.d.ts +68 -0
  149. package/dist/agent-runtime/provider-http.d.ts.map +1 -0
  150. package/dist/agent-runtime/provider-journal.d.ts +149 -0
  151. package/dist/agent-runtime/provider-journal.d.ts.map +1 -1
  152. package/dist/agent-runtime/provider-json-schema-strip.d.ts +8 -0
  153. package/dist/agent-runtime/provider-json-schema-strip.d.ts.map +1 -0
  154. package/dist/agent-runtime/provider-json-schema.d.ts +28 -0
  155. package/dist/agent-runtime/provider-json-schema.d.ts.map +1 -0
  156. package/dist/agent-runtime/provider-media.d.ts +49 -0
  157. package/dist/agent-runtime/provider-media.d.ts.map +1 -0
  158. package/dist/agent-runtime/provider-openai-chat-helpers.d.ts +27 -0
  159. package/dist/agent-runtime/provider-openai-chat-helpers.d.ts.map +1 -0
  160. package/dist/agent-runtime/provider-openai-chat-sse.d.ts +25 -0
  161. package/dist/agent-runtime/provider-openai-chat-sse.d.ts.map +1 -0
  162. package/dist/agent-runtime/provider-openai-chat.d.ts +27 -0
  163. package/dist/agent-runtime/provider-openai-chat.d.ts.map +1 -0
  164. package/dist/agent-runtime/provider-origin.d.ts +3 -12
  165. package/dist/agent-runtime/provider-origin.d.ts.map +1 -1
  166. package/dist/agent-runtime/provider-sse.d.ts +30 -0
  167. package/dist/agent-runtime/provider-sse.d.ts.map +1 -0
  168. package/dist/agent-runtime/provider-stream-parts.d.ts +5 -0
  169. package/dist/agent-runtime/provider-stream-parts.d.ts.map +1 -0
  170. package/dist/agent-runtime/provider-stream-segments.d.ts +63 -0
  171. package/dist/agent-runtime/provider-stream-segments.d.ts.map +1 -0
  172. package/dist/agent-runtime/provider-usage.d.ts +24 -0
  173. package/dist/agent-runtime/provider-usage.d.ts.map +1 -0
  174. package/dist/agent-runtime/retry-policy.d.ts +19 -3
  175. package/dist/agent-runtime/retry-policy.d.ts.map +1 -1
  176. package/dist/agent-runtime/run-acquisition.d.ts +4 -4
  177. package/dist/agent-runtime/run-acquisition.d.ts.map +1 -1
  178. package/dist/agent-runtime/run-approval.d.ts +82 -0
  179. package/dist/agent-runtime/run-approval.d.ts.map +1 -0
  180. package/dist/agent-runtime/run-complete-retry.d.ts +24 -0
  181. package/dist/agent-runtime/run-complete-retry.d.ts.map +1 -0
  182. package/dist/agent-runtime/run-complete-stream.d.ts +9 -0
  183. package/dist/agent-runtime/run-complete-stream.d.ts.map +1 -0
  184. package/dist/agent-runtime/run-complete-tools.d.ts +21 -0
  185. package/dist/agent-runtime/run-complete-tools.d.ts.map +1 -0
  186. package/dist/agent-runtime/run-complete-types.d.ts +168 -0
  187. package/dist/agent-runtime/run-complete-types.d.ts.map +1 -0
  188. package/dist/agent-runtime/run-complete.d.ts +25 -0
  189. package/dist/agent-runtime/run-complete.d.ts.map +1 -0
  190. package/dist/agent-runtime/run-driver-compose.d.ts +21 -0
  191. package/dist/agent-runtime/run-driver-compose.d.ts.map +1 -0
  192. package/dist/agent-runtime/run-execution-state.d.ts +23 -10
  193. package/dist/agent-runtime/run-execution-state.d.ts.map +1 -1
  194. package/dist/agent-runtime/run-execution.d.ts +2 -2
  195. package/dist/agent-runtime/run-execution.d.ts.map +1 -1
  196. package/dist/agent-runtime/run-failure.d.ts +2 -2
  197. package/dist/agent-runtime/run-failure.d.ts.map +1 -1
  198. package/dist/agent-runtime/run-history-parts.d.ts +14 -0
  199. package/dist/agent-runtime/run-history-parts.d.ts.map +1 -0
  200. package/dist/agent-runtime/run-loop-events.d.ts +126 -0
  201. package/dist/agent-runtime/run-loop-events.d.ts.map +1 -0
  202. package/dist/agent-runtime/run-model-attempts.d.ts +2 -2
  203. package/dist/agent-runtime/run-model-attempts.d.ts.map +1 -1
  204. package/dist/agent-runtime/run-model-messages.d.ts +9 -0
  205. package/dist/agent-runtime/run-model-messages.d.ts.map +1 -0
  206. package/dist/agent-runtime/run-model-step.d.ts +43 -0
  207. package/dist/agent-runtime/run-model-step.d.ts.map +1 -0
  208. package/dist/agent-runtime/run-model-stream.d.ts +27 -0
  209. package/dist/agent-runtime/run-model-stream.d.ts.map +1 -0
  210. package/dist/agent-runtime/run-operation-lifecycle.d.ts +8 -4
  211. package/dist/agent-runtime/run-operation-lifecycle.d.ts.map +1 -1
  212. package/dist/agent-runtime/run-prompt-history.d.ts +8 -13
  213. package/dist/agent-runtime/run-prompt-history.d.ts.map +1 -1
  214. package/dist/agent-runtime/run-provider-ledger.d.ts +7 -4
  215. package/dist/agent-runtime/run-provider-ledger.d.ts.map +1 -1
  216. package/dist/agent-runtime/run-step-barriers.d.ts +58 -16
  217. package/dist/agent-runtime/run-step-barriers.d.ts.map +1 -1
  218. package/dist/agent-runtime/run-step-helpers.d.ts +49 -0
  219. package/dist/agent-runtime/run-step-helpers.d.ts.map +1 -0
  220. package/dist/agent-runtime/run-step-prepare.d.ts +34 -0
  221. package/dist/agent-runtime/run-step-prepare.d.ts.map +1 -0
  222. package/dist/agent-runtime/run-step-spend.d.ts +85 -10
  223. package/dist/agent-runtime/run-step-spend.d.ts.map +1 -1
  224. package/dist/agent-runtime/run-stream-parts.d.ts +13 -9
  225. package/dist/agent-runtime/run-stream-parts.d.ts.map +1 -1
  226. package/dist/agent-runtime/run-stream-recorded.d.ts +8 -0
  227. package/dist/agent-runtime/run-stream-recorded.d.ts.map +1 -0
  228. package/dist/agent-runtime/run-stream-step-text.d.ts +29 -0
  229. package/dist/agent-runtime/run-stream-step-text.d.ts.map +1 -0
  230. package/dist/agent-runtime/run-terminal.d.ts +3 -3
  231. package/dist/agent-runtime/run-terminal.d.ts.map +1 -1
  232. package/dist/agent-runtime/run-tool-approval-flow.d.ts +36 -0
  233. package/dist/agent-runtime/run-tool-approval-flow.d.ts.map +1 -0
  234. package/dist/agent-runtime/run-tool-approval-records.d.ts +24 -0
  235. package/dist/agent-runtime/run-tool-approval-records.d.ts.map +1 -0
  236. package/dist/agent-runtime/run-tool-call.d.ts +73 -0
  237. package/dist/agent-runtime/run-tool-call.d.ts.map +1 -0
  238. package/dist/agent-runtime/run-tool-errors.d.ts +29 -0
  239. package/dist/agent-runtime/run-tool-errors.d.ts.map +1 -0
  240. package/dist/agent-runtime/run-tool-executor.d.ts +34 -0
  241. package/dist/agent-runtime/run-tool-executor.d.ts.map +1 -0
  242. package/dist/agent-runtime/run-tool-progress.d.ts +2 -2
  243. package/dist/agent-runtime/run-tool-progress.d.ts.map +1 -1
  244. package/dist/agent-runtime/run-turn-preparation.d.ts +7 -6
  245. package/dist/agent-runtime/run-turn-preparation.d.ts.map +1 -1
  246. package/dist/agent-runtime/run-unacquired.d.ts +2 -2
  247. package/dist/agent-runtime/run-unacquired.d.ts.map +1 -1
  248. package/dist/agent-runtime/runtime-control.d.ts +4 -4
  249. package/dist/agent-runtime/runtime-control.d.ts.map +1 -1
  250. package/dist/agent-runtime/runtime-internals.d.ts +35 -44
  251. package/dist/agent-runtime/runtime-internals.d.ts.map +1 -1
  252. package/dist/agent-runtime/runtime-recovery.d.ts +3 -3
  253. package/dist/agent-runtime/runtime-recovery.d.ts.map +1 -1
  254. package/dist/agent-runtime/runtime-state.d.ts +3 -3
  255. package/dist/agent-runtime/runtime-state.d.ts.map +1 -1
  256. package/dist/agent-runtime/runtime-submit.d.ts +2 -2
  257. package/dist/agent-runtime/runtime-submit.d.ts.map +1 -1
  258. package/dist/agent-runtime/runtime.d.ts +51 -16
  259. package/dist/agent-runtime/runtime.d.ts.map +1 -1
  260. package/dist/agent-runtime/sandbox-process-linux.d.ts +8 -0
  261. package/dist/agent-runtime/sandbox-process-linux.d.ts.map +1 -0
  262. package/dist/agent-runtime/sandbox-process-macos.d.ts +21 -0
  263. package/dist/agent-runtime/sandbox-process-macos.d.ts.map +1 -0
  264. package/dist/agent-runtime/sandbox-process-spec.d.ts +114 -0
  265. package/dist/agent-runtime/sandbox-process-spec.d.ts.map +1 -0
  266. package/dist/agent-runtime/sandbox-process-wrapper.d.ts +19 -0
  267. package/dist/agent-runtime/sandbox-process-wrapper.d.ts.map +1 -0
  268. package/dist/agent-runtime/schemas-message.d.ts +10 -0
  269. package/dist/agent-runtime/schemas-message.d.ts.map +1 -1
  270. package/dist/agent-runtime/schemas-provider.d.ts +2 -0
  271. package/dist/agent-runtime/schemas-provider.d.ts.map +1 -1
  272. package/dist/agent-runtime/schemas-run.d.ts +10 -0
  273. package/dist/agent-runtime/schemas-run.d.ts.map +1 -1
  274. package/dist/agent-runtime/schemas-usage-state.d.ts +6 -0
  275. package/dist/agent-runtime/schemas-usage-state.d.ts.map +1 -0
  276. package/dist/agent-runtime/schemas-usage.d.ts +8 -0
  277. package/dist/agent-runtime/schemas-usage.d.ts.map +1 -1
  278. package/dist/agent-runtime/sql-rows.d.ts +20 -10
  279. package/dist/agent-runtime/sql-rows.d.ts.map +1 -1
  280. package/dist/agent-runtime/store-conformance-lifecycle.d.ts +40 -20
  281. package/dist/agent-runtime/store-conformance-lifecycle.d.ts.map +1 -1
  282. package/dist/agent-runtime/store-conformance-support.d.ts +20 -10
  283. package/dist/agent-runtime/store-conformance-support.d.ts.map +1 -1
  284. package/dist/agent-runtime/store-driver-contract.d.ts +70 -0
  285. package/dist/agent-runtime/store-driver-contract.d.ts.map +1 -1
  286. package/dist/agent-runtime/store-events.d.ts +120 -0
  287. package/dist/agent-runtime/store-events.d.ts.map +1 -1
  288. package/dist/agent-runtime/store.d.ts +140 -0
  289. package/dist/agent-runtime/store.d.ts.map +1 -1
  290. package/dist/agent-runtime/terminal-commit.d.ts +10 -0
  291. package/dist/agent-runtime/terminal-commit.d.ts.map +1 -1
  292. package/dist/agent-runtime/testing.d.ts +20 -0
  293. package/dist/agent-runtime/testing.d.ts.map +1 -1
  294. package/dist/browser/client-call-arguments.d.ts.map +1 -1
  295. package/dist/browser/client-executors.d.ts.map +1 -1
  296. package/dist/browser/client-url.d.ts.map +1 -1
  297. package/dist/browser/client.d.ts +6 -0
  298. package/dist/browser/client.d.ts.map +1 -1
  299. package/dist/browser/device-presence-client.d.ts +42 -0
  300. package/dist/browser/device-presence-client.d.ts.map +1 -0
  301. package/dist/browser/device-presence-ops.d.ts +47 -0
  302. package/dist/browser/device-presence-ops.d.ts.map +1 -0
  303. package/dist/browser/device-presence-relay-adapter.d.ts +37 -0
  304. package/dist/browser/device-presence-relay-adapter.d.ts.map +1 -0
  305. package/dist/browser/http-fetch.d.ts +7 -2
  306. package/dist/browser/http-fetch.d.ts.map +1 -1
  307. package/dist/browser/http-helpers.d.ts +15 -0
  308. package/dist/browser/http-helpers.d.ts.map +1 -0
  309. package/dist/browser/http.d.ts +8 -0
  310. package/dist/browser/http.d.ts.map +1 -1
  311. package/dist/contract/client-types.d.ts +8 -0
  312. package/dist/contract/client-types.d.ts.map +1 -1
  313. package/dist/contract/runtime-context.d.ts +13 -1
  314. package/dist/contract/runtime-context.d.ts.map +1 -1
  315. package/dist/device-relay/agent-handlers.d.ts +45 -0
  316. package/dist/device-relay/agent-handlers.d.ts.map +1 -0
  317. package/dist/device-relay/agent.d.ts +80 -0
  318. package/dist/device-relay/agent.d.ts.map +1 -0
  319. package/dist/device-relay/broker.d.ts +49 -0
  320. package/dist/device-relay/broker.d.ts.map +1 -0
  321. package/dist/device-relay/contract.d.ts +614 -0
  322. package/dist/device-relay/contract.d.ts.map +1 -0
  323. package/dist/device-relay/encoding.d.ts +30 -0
  324. package/dist/device-relay/encoding.d.ts.map +1 -0
  325. package/dist/device-relay/hub-connection.d.ts +43 -0
  326. package/dist/device-relay/hub-connection.d.ts.map +1 -0
  327. package/dist/device-relay/hub-dispatch.d.ts +19 -0
  328. package/dist/device-relay/hub-dispatch.d.ts.map +1 -0
  329. package/dist/device-relay/hub-handshake.d.ts +20 -0
  330. package/dist/device-relay/hub-handshake.d.ts.map +1 -0
  331. package/dist/device-relay/hub-shared-streams.d.ts +24 -0
  332. package/dist/device-relay/hub-shared-streams.d.ts.map +1 -0
  333. package/dist/device-relay/hub-streams.d.ts +57 -0
  334. package/dist/device-relay/hub-streams.d.ts.map +1 -0
  335. package/dist/device-relay/hub.d.ts +117 -0
  336. package/dist/device-relay/hub.d.ts.map +1 -0
  337. package/dist/entrypoints/agent-executor/acp.d.ts +1 -1
  338. package/dist/entrypoints/agent-executor/acp.d.ts.map +1 -1
  339. package/dist/entrypoints/agent-executor/acp.js +183 -29
  340. package/dist/entrypoints/agent-executor/claude-sdk.js +15 -15
  341. package/dist/entrypoints/agent-executor/claude.js +13 -15
  342. package/dist/entrypoints/agent-executor/codex.js +88 -48
  343. package/dist/entrypoints/agent-executor/testing/claude-sdk.js +5 -5
  344. package/dist/entrypoints/agent-executor/testing.js +31 -30
  345. package/dist/entrypoints/agent-executor.d.ts +2 -2
  346. package/dist/entrypoints/agent-executor.d.ts.map +1 -1
  347. package/dist/entrypoints/agent-executor.js +23 -17
  348. package/dist/entrypoints/agent-runtime/ai-sdk.d.ts +9 -0
  349. package/dist/entrypoints/agent-runtime/ai-sdk.d.ts.map +1 -0
  350. package/dist/entrypoints/agent-runtime/ai-sdk.js +821 -0
  351. package/dist/entrypoints/agent-runtime/anthropic.d.ts +4 -0
  352. package/dist/entrypoints/agent-runtime/anthropic.d.ts.map +1 -0
  353. package/dist/entrypoints/agent-runtime/anthropic.js +1260 -0
  354. package/dist/entrypoints/agent-runtime/browser.d.ts +4 -1
  355. package/dist/entrypoints/agent-runtime/browser.d.ts.map +1 -1
  356. package/dist/entrypoints/agent-runtime/browser.js +449 -50
  357. package/dist/entrypoints/agent-runtime/coding-tools.js +3 -3
  358. package/dist/entrypoints/agent-runtime/harness.js +24 -19
  359. package/dist/entrypoints/agent-runtime/openai.d.ts +4 -0
  360. package/dist/entrypoints/agent-runtime/openai.d.ts.map +1 -0
  361. package/dist/entrypoints/agent-runtime/openai.js +1246 -0
  362. package/dist/entrypoints/agent-runtime/openrouter.d.ts +5 -2
  363. package/dist/entrypoints/agent-runtime/openrouter.d.ts.map +1 -1
  364. package/dist/entrypoints/agent-runtime/openrouter.js +2355 -371
  365. package/dist/entrypoints/agent-runtime/postgres.js +12 -10
  366. package/dist/entrypoints/agent-runtime/realtime.js +11 -10
  367. package/dist/entrypoints/agent-runtime/sandbox.d.ts +3 -0
  368. package/dist/entrypoints/agent-runtime/sandbox.d.ts.map +1 -1
  369. package/dist/entrypoints/agent-runtime/sandbox.js +530 -7
  370. package/dist/entrypoints/agent-runtime/sqlite/bun.js +13 -11
  371. package/dist/entrypoints/agent-runtime/sqlite/node.js +13 -11
  372. package/dist/entrypoints/agent-runtime/testing.d.ts +1 -1
  373. package/dist/entrypoints/agent-runtime/testing.d.ts.map +1 -1
  374. package/dist/entrypoints/agent-runtime/testing.js +56 -15
  375. package/dist/entrypoints/agent-runtime.d.ts +14 -6
  376. package/dist/entrypoints/agent-runtime.d.ts.map +1 -1
  377. package/dist/entrypoints/agent-runtime.js +1412 -115
  378. package/dist/entrypoints/application/diagnostic-journal.js +6 -6
  379. package/dist/entrypoints/application/directory-inbox.js +6 -6
  380. package/dist/entrypoints/application/opentelemetry.js +3 -3
  381. package/dist/entrypoints/application.js +17 -17
  382. package/dist/entrypoints/cli/publish.js +8 -8
  383. package/dist/entrypoints/cli.js +14 -15
  384. package/dist/entrypoints/contract.d.ts +1 -0
  385. package/dist/entrypoints/contract.d.ts.map +1 -1
  386. package/dist/entrypoints/contract.js +13 -9
  387. package/dist/entrypoints/device-relay.d.ts +10 -0
  388. package/dist/entrypoints/device-relay.d.ts.map +1 -0
  389. package/dist/entrypoints/device-relay.js +2517 -0
  390. package/dist/entrypoints/files/packaging.js +3 -3
  391. package/dist/entrypoints/files.js +11 -11
  392. package/dist/entrypoints/geo.js +5 -5
  393. package/dist/entrypoints/google.js +1 -1
  394. package/dist/entrypoints/handler.js +6 -6
  395. package/dist/entrypoints/http.js +9 -9
  396. package/dist/entrypoints/index.js +21 -17
  397. package/dist/entrypoints/live.js +4 -4
  398. package/dist/entrypoints/node.js +13 -13
  399. package/dist/entrypoints/observability.js +9 -9
  400. package/dist/entrypoints/process/bootstrap.js +1 -1
  401. package/dist/entrypoints/process.js +5 -5
  402. package/dist/entrypoints/react.js +4 -4
  403. package/dist/entrypoints/realtime.d.ts +3 -0
  404. package/dist/entrypoints/realtime.d.ts.map +1 -1
  405. package/dist/entrypoints/realtime.js +413 -4
  406. package/dist/entrypoints/release.js +1 -1
  407. package/dist/entrypoints/remote.js +10 -10
  408. package/dist/entrypoints/server.d.ts +1 -0
  409. package/dist/entrypoints/server.d.ts.map +1 -1
  410. package/dist/entrypoints/server.js +546 -40
  411. package/dist/entrypoints/service-host/macos.js +10 -10
  412. package/dist/entrypoints/service-host/work.js +7 -7
  413. package/dist/entrypoints/service-host.js +15 -15
  414. package/dist/entrypoints/spend.js +3 -3
  415. package/dist/entrypoints/sync.js +4 -4
  416. package/dist/entrypoints/telegram/screens.js +6 -6
  417. package/dist/entrypoints/telegram.js +20 -20
  418. package/dist/entrypoints/testing.js +14 -14
  419. package/dist/entrypoints/tools/agent.d.ts +2 -1
  420. package/dist/entrypoints/tools/agent.d.ts.map +1 -1
  421. package/dist/entrypoints/tools/agent.js +8 -7
  422. package/dist/entrypoints/tools/connections.js +5 -5
  423. package/dist/entrypoints/tools/invoker.js +3 -4
  424. package/dist/entrypoints/tools/mcp.js +8 -9
  425. package/dist/entrypoints/tools/toolkit.js +32 -13
  426. package/dist/entrypoints/tools.d.ts +3 -1
  427. package/dist/entrypoints/tools.d.ts.map +1 -1
  428. package/dist/entrypoints/tools.js +37 -35
  429. package/dist/entrypoints/tracking/contract.js +1 -1
  430. package/dist/entrypoints/tracking/performance.js +4 -4
  431. package/dist/entrypoints/tracking.js +3 -3
  432. package/dist/{index-09f7w2qq.js → index-02kdtrcd.js} +1 -1
  433. package/dist/{index-y53cqwke.js → index-033tyx59.js} +1 -1
  434. package/dist/{index-9ft4n9j1.js → index-05b65gj4.js} +2 -2
  435. package/dist/{index-d04w81fz.js → index-0sxj3y45.js} +1 -1
  436. package/dist/{index-dm6nxkn1.js → index-18pf56dq.js} +4 -6
  437. package/dist/index-1gmgwfn3.js +439 -0
  438. package/dist/index-23wn8sgf.js +47 -0
  439. package/dist/{index-tqjamnax.js → index-27srek2g.js} +15 -13
  440. package/dist/{index-2nwvn7m2.js → index-29v1p1f4.js} +2 -2
  441. package/dist/index-36dmtzjr.js +194 -0
  442. package/dist/{index-ycr4pk0z.js → index-42n9jycn.js} +3 -3
  443. package/dist/{index-ke02kxsr.js → index-43k180c2.js} +1 -1
  444. package/dist/{index-pbekeqzm.js → index-5c4m8zdf.js} +2 -2
  445. package/dist/{index-qggqqja2.js → index-5dxgx3yj.js} +1 -1
  446. package/dist/{index-x5ayy5bn.js → index-5gdexvke.js} +3 -1
  447. package/dist/{index-t1a2jrg7.js → index-5xsxvk2x.js} +1 -1
  448. package/dist/{index-mbd92r1w.js → index-654rhe5d.js} +1 -1
  449. package/dist/{index-2dzc7mv9.js → index-67pnt4bh.js} +1 -1
  450. package/dist/index-6kpwkpgx.js +415 -0
  451. package/dist/{index-s43tr4my.js → index-6kwdfb9m.js} +18 -3
  452. package/dist/{index-1qwd54n3.js → index-6nzzj7qr.js} +1 -1
  453. package/dist/{index-rkjfzs0a.js → index-6p5pshcd.js} +2 -2
  454. package/dist/{index-118aebbg.js → index-6t4c98gr.js} +1 -1
  455. package/dist/{index-pws5c3x6.js → index-6xw1wf4m.js} +51 -32
  456. package/dist/{index-kwsr7j5k.js → index-6yb4stq3.js} +1 -1
  457. package/dist/{index-8jf4bt7v.js → index-76yhxa41.js} +8 -8
  458. package/dist/{index-7416mhyh.js → index-79vqbjcz.js} +1 -1
  459. package/dist/{index-13wmzpa6.js → index-7an2fs5h.js} +1 -1
  460. package/dist/index-7qza24g1.js +14 -0
  461. package/dist/{index-gtaaxe9d.js → index-8cek82ar.js} +1 -1
  462. package/dist/index-9f60gnfn.js +393 -0
  463. package/dist/{index-stpy56r3.js → index-aacwkve4.js} +209 -10
  464. package/dist/{index-rpyn7geq.js → index-ac3rfec5.js} +2 -2
  465. package/dist/{index-d2drhb9c.js → index-b0mh2t9x.js} +2 -2
  466. package/dist/index-b23s6e2c.js +158 -0
  467. package/dist/{index-an7vcmwf.js → index-bvpevwt6.js} +5 -5
  468. package/dist/{index-msxf2r8x.js → index-by8w2461.js} +1 -1
  469. package/dist/{index-8t9dr41h.js → index-c0yym4a0.js} +4 -4
  470. package/dist/{index-wddcfbng.js → index-c7fj4yw9.js} +1 -1
  471. package/dist/{index-tf70nm22.js → index-cb4nnvfr.js} +8 -6
  472. package/dist/{index-205456mf.js → index-d3s070eh.js} +2 -2
  473. package/dist/{index-apf5g7y9.js → index-dz6tstcp.js} +2 -2
  474. package/dist/{index-agy5fqgf.js → index-e1y74yra.js} +15 -8
  475. package/dist/index-edtg4tak.js +55 -0
  476. package/dist/{index-pq6g1k9t.js → index-ek9w11r0.js} +2 -2
  477. package/dist/{index-x46y9z26.js → index-epyj7ptp.js} +7 -5
  478. package/dist/{index-6kmjcm81.js → index-er483f3w.js} +93 -4
  479. package/dist/{index-827bgv33.js → index-f16b7rze.js} +1 -1
  480. package/dist/{index-gbhj370g.js → index-fec05c9k.js} +21 -21
  481. package/dist/{index-9wdrwx3b.js → index-fjac2w5e.js} +20 -22
  482. package/dist/{index-6918kxbf.js → index-fthw8dwa.js} +1 -0
  483. package/dist/{index-2mz8hj58.js → index-g04hszcm.js} +1 -1
  484. package/dist/{index-rw8ze745.js → index-ga6avd48.js} +1 -1
  485. package/dist/{index-paff5y0r.js → index-grhhsrd5.js} +9 -7
  486. package/dist/{index-mxt0wfjy.js → index-h20qcyh5.js} +5 -2
  487. package/dist/index-j3r7r1mh.js +150 -0
  488. package/dist/{index-vgytj9wp.js → index-jmaw365j.js} +1 -1
  489. package/dist/{index-cjytermm.js → index-jzdbkanz.js} +3 -3
  490. package/dist/index-k137ezb6.js +79 -0
  491. package/dist/{index-tazm4dxf.js → index-kdw0n92g.js} +1 -1
  492. package/dist/{index-wh70tmpd.js → index-ke6jtxkd.js} +1 -1
  493. package/dist/index-kgj8j7bv.js +83 -0
  494. package/dist/{index-9kpxz49v.js → index-kgkevngs.js} +1 -1
  495. package/dist/{index-hab790s6.js → index-kp1j7cc8.js} +4 -4
  496. package/dist/{index-jcge9tx3.js → index-krekhmp7.js} +142 -123
  497. package/dist/{index-3y2tzhr8.js → index-ky79wwgs.js} +4 -4
  498. package/dist/{index-39rmc00v.js → index-mfe9a266.js} +1 -1
  499. package/dist/{index-qpzyahe3.js → index-mgr0mdqp.js} +5 -2
  500. package/dist/{index-n20tybgk.js → index-mh3jdb25.js} +2 -2
  501. package/dist/{index-g5fgeb6v.js → index-mkmep637.js} +1 -1
  502. package/dist/{index-02r5sq9p.js → index-mrng24wq.js} +19 -21
  503. package/dist/index-mx2gya05.js +465 -0
  504. package/dist/{index-8yt3rwe7.js → index-n2t87ggz.js} +5 -5
  505. package/dist/index-nfeafbzh.js +7379 -0
  506. package/dist/{index-j0ef04jw.js → index-nfm15ej7.js} +4 -4
  507. package/dist/index-pd9e8rz4.js +193 -0
  508. package/dist/{index-zwgwyvdt.js → index-pdcbjd6a.js} +1 -1
  509. package/dist/{index-q427q23r.js → index-pjjh91vw.js} +2 -2
  510. package/dist/{index-gnjgkecx.js → index-q46b16xz.js} +1 -1
  511. package/dist/{index-9xr44d2g.js → index-qv5v6w9c.js} +330 -106
  512. package/dist/{index-tmv3ez1h.js → index-qymek778.js} +69 -12
  513. package/dist/{index-yrr3n391.js → index-ry8m2mhg.js} +2 -2
  514. package/dist/{index-93n6jwy0.js → index-s0n0nnz5.js} +3 -3
  515. package/dist/{index-1p8q0yrt.js → index-t5zp1jjj.js} +5 -7
  516. package/dist/{index-2rf33y2h.js → index-tav72wz5.js} +4 -2
  517. package/dist/{index-jpecjm30.js → index-tgehj4bp.js} +1 -1
  518. package/dist/{index-ma26mfnt.js → index-v5hmyef8.js} +1 -1
  519. package/dist/index-vebzvse6.js +230 -0
  520. package/dist/index-vv0hxrmy.js +295 -0
  521. package/dist/index-vxm0ya3f.js +707 -0
  522. package/dist/{index-t3qcac2a.js → index-w3s79kcb.js} +1 -1
  523. package/dist/{index-r97ppg0g.js → index-x1r7kxzd.js} +1 -1
  524. package/dist/{index-kynwa08q.js → index-xrsryvd2.js} +2 -2
  525. package/dist/{index-3mcbr8sx.js → index-xtxxt87z.js} +1 -1
  526. package/dist/index-zk839vzf.js +231 -0
  527. package/dist/{index-9c76vfxf.js → index-zyyerdny.js} +4 -4
  528. package/dist/internal/base64.d.ts +9 -0
  529. package/dist/internal/base64.d.ts.map +1 -0
  530. package/dist/internal/deadline-budget.d.ts +57 -0
  531. package/dist/internal/deadline-budget.d.ts.map +1 -0
  532. package/dist/internal/deadline.d.ts.map +1 -1
  533. package/dist/internal/timers.d.ts +2 -0
  534. package/dist/internal/timers.d.ts.map +1 -1
  535. package/dist/realtime/device-presence-contract.d.ts +194 -0
  536. package/dist/realtime/device-presence-contract.d.ts.map +1 -0
  537. package/dist/server/context-contribution.d.ts.map +1 -1
  538. package/dist/server/contract-method.d.ts.map +1 -1
  539. package/dist/server/device-presence-handlers.d.ts +54 -0
  540. package/dist/server/device-presence-handlers.d.ts.map +1 -0
  541. package/dist/server/device-presence-registry.d.ts +35 -0
  542. package/dist/server/device-presence-registry.d.ts.map +1 -0
  543. package/dist/server/device-presence.d.ts +45 -0
  544. package/dist/server/device-presence.d.ts.map +1 -0
  545. package/dist/server/endpoint-dispatch.d.ts.map +1 -1
  546. package/dist/server/middleware/cors.d.ts +3 -1
  547. package/dist/server/middleware/cors.d.ts.map +1 -1
  548. package/dist/server/types.d.ts +4 -11
  549. package/dist/server/types.d.ts.map +1 -1
  550. package/dist/service-host/systemd-render-shared.d.ts.map +1 -1
  551. package/dist/tools/agent-messages.d.ts +6 -0
  552. package/dist/tools/agent-messages.d.ts.map +1 -0
  553. package/dist/tools/agent-tool-error.d.ts +2 -2
  554. package/dist/tools/agent-tools.d.ts +153 -0
  555. package/dist/tools/agent-tools.d.ts.map +1 -0
  556. package/dist/tools/agent.d.ts +6 -56
  557. package/dist/tools/agent.d.ts.map +1 -1
  558. package/dist/tools/runtime-tool.d.ts +3 -4
  559. package/dist/tools/runtime-tool.d.ts.map +1 -1
  560. package/dist/tools/toolkit.d.ts +3 -1
  561. package/dist/tools/toolkit.d.ts.map +1 -1
  562. package/dist/tools/transfer/define-view-file-tool.d.ts.map +1 -1
  563. package/llms/agent-executor-acp.txt +2 -2
  564. package/llms/agent-executor-codex.txt +1 -1
  565. package/llms/agent-executor.txt +7 -3
  566. package/llms/agent-runtime-ai-sdk.txt +26 -0
  567. package/llms/agent-runtime-anthropic.txt +33 -0
  568. package/llms/agent-runtime-browser.txt +22 -8
  569. package/llms/agent-runtime-harness.txt +2 -2
  570. package/llms/agent-runtime-openai.txt +31 -0
  571. package/llms/agent-runtime-openrouter.txt +17 -7
  572. package/llms/agent-runtime-sandbox.txt +53 -1
  573. package/llms/agent-runtime-testing.txt +4 -2
  574. package/llms/agent-runtime.2.txt +158 -271
  575. package/llms/agent-runtime.3.txt +289 -243
  576. package/llms/agent-runtime.4.txt +273 -216
  577. package/llms/agent-runtime.5.txt +209 -2
  578. package/llms/agent-runtime.txt +238 -181
  579. package/llms/contract.txt +2 -1
  580. package/llms/device-relay.txt +34 -0
  581. package/llms/realtime.txt +20 -0
  582. package/llms/server.2.txt +125 -1
  583. package/llms/server.3.txt +111 -122
  584. package/llms/server.4.txt +1 -1
  585. package/llms/server.5.txt +3 -1
  586. package/llms/server.txt +31 -1
  587. package/llms/spend.txt +11 -6
  588. package/llms/stitchkit.2.txt +21 -43
  589. package/llms/stitchkit.3.txt +43 -0
  590. package/llms/stitchkit.txt +93 -84
  591. package/llms/tools-agent.txt +7 -5
  592. package/llms/tools-toolkit.txt +1 -1
  593. package/llms/tools.4.txt +7 -2
  594. package/llms/{upgrading-0.128.0-0.133.0.txt → upgrading-0.128.0-0.134.0.txt} +173 -3
  595. package/llms/upgrading.txt +1 -1
  596. package/llms-full.txt +981 -210
  597. package/llms.txt +21 -17
  598. package/package.json +18 -7
  599. package/dist/index-0p0s5hrj.js +0 -249
  600. package/dist/index-1dn2wjq6.js +0 -135
  601. package/dist/index-1psbyyhj.js +0 -21
  602. package/dist/index-34k82crg.js +0 -3961
  603. package/dist/index-5n3a8hd8.js +0 -102
  604. package/dist/index-97rp94ff.js +0 -8
  605. package/dist/index-bn2baakz.js +0 -336
  606. package/dist/index-eh71zr32.js +0 -14
  607. package/dist/index-emgrmavr.js +0 -1193
  608. package/dist/index-fzd477xk.js +0 -135
  609. package/dist/index-vgzhw2zk.js +0 -304
  610. package/dist/internal/ai-sdk-typed.d.ts +0 -14
  611. package/dist/internal/ai-sdk-typed.d.ts.map +0 -1
  612. package/dist/tools/runtime-call-context.d.ts +0 -15
  613. package/dist/tools/runtime-call-context.d.ts.map +0 -1
  614. package/dist/{index-vmbxj75t.js → index-jwtmw39p.js} +0 -0
  615. package/dist/{index-877e9y8r.js → index-sk03xe0n.js} +3 -3
  616. package/dist/{index-21cfxc4z.js → index-vh4291qh.js} +3 -3
@@ -1,65 +1,285 @@
1
- import"../../index-2rf33y2h.js";
2
- import"../../index-bn2baakz.js";
3
- import"../../index-97rp94ff.js";
4
- import"../../index-vgzhw2zk.js";
5
1
  import {
6
- currentModelInvocationAttempt2,
7
2
  AgentModelCatalogSchema2
8
- } from "../../index-emgrmavr.js";
9
- import"../../index-paff5y0r.js";
3
+ } from "../../index-b23s6e2c.js";
4
+ import {
5
+ AgentCacheControlSchema2
6
+ } from "../../index-vebzvse6.js";
7
+ import {
8
+ redactProviderFailureText,
9
+ joinProviderUrl,
10
+ assertNoExtraBodyClash,
11
+ resolveProviderApiKey,
12
+ postProviderStream,
13
+ nonEmptyString2,
14
+ recordField,
15
+ reportedInt,
16
+ reportedUsd,
17
+ computedUsd,
18
+ nonNegativeNumber,
19
+ buildProviderUsage,
20
+ normalizeProviderHistory,
21
+ historyHasToolTraffic,
22
+ parseSseStream,
23
+ parseSseJson
24
+ } from "../../index-vxm0ya3f.js";
10
25
  import {
11
26
  openAiCompatibleUsage2
12
- } from "../../index-118aebbg.js";
27
+ } from "../../index-6t4c98gr.js";
28
+ import {
29
+ MAX_CACHE_BREAKPOINTS,
30
+ openRouterAllowsInlineCacheControl,
31
+ toWireCacheControl,
32
+ assertValidCacheTtlOrder,
33
+ budgetCacheBreakpoints
34
+ } from "../../index-23wn8sgf.js";
35
+ import {
36
+ normalizeOpenAiJsonSchema
37
+ } from "../../index-1gmgwfn3.js";
38
+ import {
39
+ sanitizeSurrogates,
40
+ deterministicJson,
41
+ resolveFilePayload,
42
+ normalizeMime,
43
+ fallbackFilenameForMediaType,
44
+ readPortableCacheControl,
45
+ AgentProviderError2,
46
+ AgentProviderStreamCutError2
47
+ } from "../../index-6kpwkpgx.js";
13
48
  import {
14
49
  readBoundedBody2
15
- } from "../../index-827bgv33.js";
50
+ } from "../../index-f16b7rze.js";
16
51
  import {
52
+ isPositiveSafeInteger,
17
53
  assertPositiveSafeInteger
18
54
  } from "../../index-gr0kxymw.js";
19
- import {
20
- isRecord
21
- } from "../../index-ps3djm8d.js";
22
55
  import {
23
56
  assertTimerMs
24
- } from "../../index-agy5fqgf.js";
57
+ } from "../../index-e1y74yra.js";
25
58
  import {
59
+ abortReason,
60
+ raceAbort,
26
61
  linkAbortSignals,
27
62
  withLinkedAbortSignals
28
63
  } from "../../index-rptj3qnc.js";
29
-
30
- // src/agent-runtime/openrouter.ts
31
64
  import {
32
- createOpenRouter
33
- } from "@openrouter/ai-sdk-provider";
34
- import { z as z4 } from "zod";
65
+ isRecord
66
+ } from "../../index-ps3djm8d.js";
35
67
 
36
- // src/agent-runtime/openrouter-models.ts
68
+ // src/agent-runtime/openrouter-benchmarks.ts
37
69
  import { z } from "zod";
38
- var OpenRouterModelSchema = z.object({
39
- id: z.string().min(1),
40
- canonical_slug: z.string().min(1).optional(),
41
- name: z.string().min(1),
42
- description: z.string().optional(),
43
- context_length: z.int().nonnegative(),
44
- architecture: z.object({ input_modalities: z.array(z.string()).default([]) }).loose(),
45
- pricing: z.object({
46
- prompt: z.string().optional(),
47
- completion: z.string().optional(),
48
- request: z.string().optional(),
49
- image: z.string().optional()
50
- }).loose(),
51
- supported_parameters: z.array(z.string()).default([])
70
+ var OpenRouterBenchmarkMetaSchema = z.object({ as_of: z.iso.datetime({ offset: true }) }).loose();
71
+ var OpenRouterArtificialAnalysisRowSchema = z.object({
72
+ source: z.literal("artificial-analysis"),
73
+ model_permaslug: z.string().min(1),
74
+ intelligence_index: z.number().nullish(),
75
+ coding_index: z.number().nullish(),
76
+ agentic_index: z.number().nullish()
77
+ }).loose();
78
+ var OpenRouterDesignArenaRowSchema = z.object({
79
+ source: z.literal("design-arena"),
80
+ model_permaslug: z.string().min(1),
81
+ arena: z.string().min(1),
82
+ category: z.string().min(1).optional(),
83
+ elo: z.number().nullish(),
84
+ win_rate: z.number().nullish(),
85
+ avg_generation_time_ms: z.number().nullish()
86
+ }).loose();
87
+ var OpenRouterArtificialAnalysisResponseSchema = z.object({
88
+ data: z.array(OpenRouterArtificialAnalysisRowSchema),
89
+ meta: OpenRouterBenchmarkMetaSchema
90
+ });
91
+ var OpenRouterDesignArenaResponseSchema = z.object({
92
+ data: z.array(OpenRouterDesignArenaRowSchema),
93
+ meta: OpenRouterBenchmarkMetaSchema
94
+ });
95
+ function openRouterCapabilities(model) {
96
+ const values = ["tools"];
97
+ if (model.architecture.input_modalities.includes("image"))
98
+ values.push("vision");
99
+ if (model.architecture.input_modalities.includes("file"))
100
+ values.push("files");
101
+ if (model.supported_parameters.includes("reasoning") || model.supported_parameters.includes("include_reasoning")) {
102
+ values.push("reasoning");
103
+ }
104
+ return values;
105
+ }
106
+ function artificialMetrics(row, observedAt) {
107
+ return [
108
+ ["intelligence", row.intelligence_index],
109
+ ["coding", row.coding_index],
110
+ ["agentic", row.agentic_index]
111
+ ].flatMap(([metric, value]) => typeof metric === "string" && typeof value === "number" ? [
112
+ {
113
+ metric,
114
+ value,
115
+ unit: "index",
116
+ source: row.source,
117
+ observedAt
118
+ }
119
+ ] : []);
120
+ }
121
+ function designMetrics(row, observedAt) {
122
+ const suffix = `${row.arena}${row.category ? `:${row.category}` : ""}`;
123
+ const metrics = [];
124
+ if (typeof row.elo === "number") {
125
+ metrics.push({
126
+ metric: `design-arena:${suffix}:elo`,
127
+ value: row.elo,
128
+ unit: "elo",
129
+ source: row.source,
130
+ observedAt
131
+ });
132
+ }
133
+ if (typeof row.win_rate === "number") {
134
+ metrics.push({
135
+ metric: `design-arena:${suffix}:win-rate`,
136
+ value: row.win_rate,
137
+ unit: "percent",
138
+ source: row.source,
139
+ observedAt
140
+ });
141
+ }
142
+ if (typeof row.avg_generation_time_ms === "number") {
143
+ metrics.push({
144
+ metric: `design-arena:${suffix}:generation-time`,
145
+ value: row.avg_generation_time_ms,
146
+ unit: "milliseconds",
147
+ source: row.source,
148
+ observedAt
149
+ });
150
+ }
151
+ return metrics;
152
+ }
153
+ function collectOpenRouterBenchmarks(artificialResult, designResult) {
154
+ const metrics = new Map;
155
+ const diagnostics = [];
156
+ if (artificialResult.outcome === "ok") {
157
+ const parsed = OpenRouterArtificialAnalysisResponseSchema.safeParse(artificialResult.value);
158
+ if (parsed.success) {
159
+ for (const row of parsed.data.data) {
160
+ metrics.set(row.model_permaslug, artificialMetrics(row, parsed.data.meta.as_of));
161
+ }
162
+ } else {
163
+ diagnostics.push("Artificial Analysis benchmark data is malformed");
164
+ }
165
+ } else {
166
+ diagnostics.push("Artificial Analysis benchmark data is unavailable");
167
+ }
168
+ if (designResult.outcome === "ok") {
169
+ const parsed = OpenRouterDesignArenaResponseSchema.safeParse(designResult.value);
170
+ if (parsed.success) {
171
+ for (const row of parsed.data.data) {
172
+ metrics.set(row.model_permaslug, [
173
+ ...metrics.get(row.model_permaslug) ?? [],
174
+ ...designMetrics(row, parsed.data.meta.as_of)
175
+ ]);
176
+ }
177
+ } else {
178
+ diagnostics.push("Design Arena benchmark data is malformed");
179
+ }
180
+ } else {
181
+ diagnostics.push("Design Arena benchmark data is unavailable");
182
+ }
183
+ return { metrics, diagnostics };
184
+ }
185
+
186
+ // src/agent-runtime/openrouter-models.ts
187
+ import { z as z2 } from "zod";
188
+ var OpenRouterModelSchema = z2.object({
189
+ id: z2.string().min(1),
190
+ canonical_slug: z2.string().min(1).nullish(),
191
+ name: z2.string().nullish(),
192
+ description: z2.string().nullish(),
193
+ created: z2.number().nullish(),
194
+ alias_target: z2.object({
195
+ slug: z2.string().min(1),
196
+ name: z2.string().nullish()
197
+ }).loose().nullish(),
198
+ context_length: z2.int().nonnegative().nullish(),
199
+ architecture: z2.object({
200
+ input_modalities: z2.array(z2.string()).nullish().transform((value) => value ?? []),
201
+ output_modalities: z2.array(z2.string()).nullish(),
202
+ tokenizer: z2.string().nullish()
203
+ }).loose().nullish().transform((value) => value ?? { input_modalities: [] }),
204
+ top_provider: z2.object({
205
+ context_length: z2.int().nonnegative().nullish(),
206
+ max_completion_tokens: z2.int().nonnegative().nullish()
207
+ }).loose().nullish(),
208
+ reasoning: z2.object({
209
+ supported_efforts: z2.array(z2.string()).nullish(),
210
+ default_effort: z2.string().nullish()
211
+ }).loose().nullish(),
212
+ pricing: z2.object({
213
+ prompt: z2.string().nullish(),
214
+ completion: z2.string().nullish(),
215
+ request: z2.string().nullish(),
216
+ image: z2.string().nullish(),
217
+ input_cache_read: z2.string().nullish(),
218
+ input_cache_write: z2.string().nullish(),
219
+ input_cache_write_1h: z2.string().nullish(),
220
+ overrides: z2.array(z2.unknown()).nullish()
221
+ }).loose().nullish(),
222
+ supported_parameters: z2.array(z2.string()).nullish().transform((value) => value ?? [])
52
223
  }).loose();
53
- var OpenRouterModelsResponseSchema = z.object({
54
- data: z.array(OpenRouterModelSchema)
224
+ var OpenRouterModelsResponseSchema = z2.object({
225
+ data: z2.array(OpenRouterModelSchema),
226
+ links: z2.object({
227
+ next: z2.string().nullable().optional()
228
+ }).loose().optional()
229
+ }).superRefine((value, ctx) => {
230
+ if (typeof value.links?.next === "string" && value.links.next.trim().length > 0) {
231
+ ctx.addIssue({
232
+ code: "custom",
233
+ path: ["links", "next"],
234
+ message: "Incomplete OpenRouter catalog response (paginated next link present)"
235
+ });
236
+ }
237
+ const seen = new Set;
238
+ for (let index = 0;index < value.data.length; index += 1) {
239
+ const id = value.data[index]?.id;
240
+ if (id === undefined)
241
+ continue;
242
+ if (seen.has(id)) {
243
+ ctx.addIssue({
244
+ code: "custom",
245
+ path: ["data", index, "id"],
246
+ message: `Duplicate OpenRouter model id: ${id}`
247
+ });
248
+ } else {
249
+ seen.add(id);
250
+ }
251
+ }
55
252
  });
56
253
  function withOpenRouterTimeout(timeoutMs, signal, requests) {
57
254
  assertTimerMs("timeoutMs", timeoutMs, { absent: "refused" });
58
255
  return withLinkedAbortSignals(signal, AbortSignal.timeout(timeoutMs), requests);
59
256
  }
257
+ function assertValidStaticOpenRouterApiKey(apiKey) {
258
+ if (apiKey === undefined || typeof apiKey === "function")
259
+ return;
260
+ if (typeof apiKey !== "string" || apiKey.trim().length === 0) {
261
+ throw new TypeError("OpenRouter apiKey must be a non-empty string when provided");
262
+ }
263
+ }
264
+ async function resolveOptionalOpenRouterApiKey(apiKey) {
265
+ if (apiKey === undefined)
266
+ return;
267
+ const resolved = typeof apiKey === "function" ? await apiKey() : apiKey;
268
+ if (typeof resolved !== "string") {
269
+ throw new TypeError("OpenRouter apiKey must resolve to a non-empty string");
270
+ }
271
+ const trimmed = resolved.trim();
272
+ if (trimmed.length === 0) {
273
+ throw new TypeError("OpenRouter apiKey must be a non-empty string when provided");
274
+ }
275
+ return trimmed;
276
+ }
60
277
  async function openRouterJson(input) {
278
+ input.signal.throwIfAborted();
279
+ const apiKey = input.apiKey !== undefined ? await resolveOptionalOpenRouterApiKey(input.apiKey) : undefined;
280
+ input.signal.throwIfAborted();
61
281
  const response = await input.fetcher(input.url, {
62
- headers: { Authorization: `Bearer ${input.apiKey}` },
282
+ ...apiKey !== undefined && { headers: { Authorization: `Bearer ${apiKey}` } },
63
283
  redirect: "error",
64
284
  signal: input.signal
65
285
  });
@@ -86,21 +306,224 @@ class OpenRouterHttpError extends Error {
86
306
  this.name = "OpenRouterHttpError";
87
307
  }
88
308
  }
309
+ var DECIMAL = /^(\d+(?:\.\d+)?)(?:e([+-]?\d+))?$/i;
89
310
  function usdPerMillion(perToken) {
90
- const value = usd(perToken);
91
- return value === undefined ? undefined : value * 1e6;
311
+ if (perToken === undefined || perToken === null)
312
+ return;
313
+ const match = DECIMAL.exec(perToken.trim());
314
+ if (!match)
315
+ return;
316
+ const mantissa = match[1];
317
+ const exponent = match[2] !== undefined ? Number(match[2]) : 0;
318
+ if (mantissa === undefined || !Number.isSafeInteger(exponent))
319
+ return;
320
+ const parsed = Number(`${mantissa}e${exponent + 6}`);
321
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;
92
322
  }
93
- var DECIMAL = /^\d+(?:\.\d+)?(?:e-?\d+)?$/i;
94
323
  function usd(value) {
95
324
  if (value === undefined || value === null || !DECIMAL.test(value.trim()))
96
325
  return;
97
326
  const parsed = Number(value);
98
327
  return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;
99
328
  }
329
+ var MODEL_ID = /^~?[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._:-]*$/i;
330
+ function openRouterEndpointsUrl(modelId) {
331
+ if (!MODEL_ID.test(modelId) || modelId.includes("..")) {
332
+ throw new TypeError(`Not an OpenRouter model id: ${modelId}`);
333
+ }
334
+ const [author = "", slug = ""] = modelId.split("/");
335
+ return new URL(`https://openrouter.ai/api/v1/models/${encodeURIComponent(author)}/${encodeURIComponent(slug)}/endpoints`);
336
+ }
337
+ function assertValidOpenRouterEndpointsFor(endpointsFor) {
338
+ if (endpointsFor === undefined)
339
+ return;
340
+ for (const modelId of endpointsFor) {
341
+ openRouterEndpointsUrl(modelId);
342
+ }
343
+ }
344
+ var PercentileMetricSchema = z2.object({ p50: z2.number().nullish() }).loose().nullish();
345
+ var OpenRouterEndpointsResponseSchema = z2.object({
346
+ data: z2.object({
347
+ endpoints: z2.array(z2.object({
348
+ provider_name: z2.string().min(1),
349
+ context_length: z2.int().nonnegative().nullish(),
350
+ max_completion_tokens: z2.int().nonnegative().nullish(),
351
+ pricing: z2.object({
352
+ prompt: z2.string().nullish(),
353
+ completion: z2.string().nullish(),
354
+ input_cache_read: z2.string().nullish(),
355
+ input_cache_write: z2.string().nullish(),
356
+ input_cache_write_1h: z2.string().nullish()
357
+ }).loose().nullish(),
358
+ supported_parameters: z2.array(z2.string()).nullish(),
359
+ status: z2.int().nullish(),
360
+ latency_last_30m: PercentileMetricSchema,
361
+ throughput_last_30m: PercentileMetricSchema,
362
+ uptime_last_1d: z2.number().nullish(),
363
+ tag: z2.string().nullish()
364
+ }).loose())
365
+ }).loose()
366
+ });
367
+ function nonNegativeFinite(value) {
368
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
369
+ }
370
+ function percentageMetric(value) {
371
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 100 ? value : undefined;
372
+ }
373
+ function nonEmptyTrimmed(value) {
374
+ if (typeof value !== "string")
375
+ return;
376
+ const trimmed = value.trim();
377
+ return trimmed.length > 0 ? trimmed : undefined;
378
+ }
379
+ function nonEmptyStrings(values) {
380
+ if (!values)
381
+ return [];
382
+ const result = [];
383
+ for (const value of values) {
384
+ const trimmed = value.trim();
385
+ if (trimmed.length > 0)
386
+ result.push(trimmed);
387
+ }
388
+ return result;
389
+ }
390
+ function parseUnixSecondsIso(created) {
391
+ if (typeof created !== "number" || !Number.isFinite(created) || created <= 0)
392
+ return;
393
+ const date = new Date(created * 1000);
394
+ return Number.isFinite(date.getTime()) ? date.toISOString() : undefined;
395
+ }
396
+ var KNOWN_CONDITION_KEYS = new Set([
397
+ "min_prompt_tokens",
398
+ "utc_start",
399
+ "utc_end",
400
+ "utc_days"
401
+ ]);
402
+ var WIRE_PRICE_SPECS = [
403
+ ["prompt", "promptUsdPerMillion", "prompt", usdPerMillion],
404
+ ["completion", "completionUsdPerMillion", "completion", usdPerMillion],
405
+ ["request", "requestUsd", "request", usd],
406
+ ["image", "imageUsd", "image", usd],
407
+ ["input_cache_read", "cacheReadUsdPerMillion", "cacheRead", usdPerMillion],
408
+ ["input_cache_write", "cacheWriteUsdPerMillion", "cacheWrite", usdPerMillion],
409
+ ["input_cache_write_1h", "cacheWrite1hUsdPerMillion", "cacheWrite1h", usdPerMillion]
410
+ ];
411
+ var hasOwnDefined = (obj, key) => Object.hasOwn(obj, key) && obj[key] !== undefined;
412
+ function parsePriceRecord(source, defaultOmittedRequestZero) {
413
+ const rates = {};
414
+ const unknown = [];
415
+ for (const [wireKey, outKey, field, parse] of WIRE_PRICE_SPECS) {
416
+ if (!hasOwnDefined(source, wireKey)) {
417
+ if (wireKey === "request" && defaultOmittedRequestZero)
418
+ rates.requestUsd = 0;
419
+ continue;
420
+ }
421
+ const raw = source[wireKey];
422
+ const parsed = typeof raw === "string" ? parse(raw) : undefined;
423
+ if (parsed !== undefined)
424
+ rates[outKey] = parsed;
425
+ else
426
+ unknown.push(field);
427
+ }
428
+ return { rates, unknown };
429
+ }
430
+ function mergeRateCeilings(current, next) {
431
+ const merged = { ...current };
432
+ for (const [, key] of WIRE_PRICE_SPECS) {
433
+ const candidate = next[key];
434
+ if (candidate === undefined)
435
+ continue;
436
+ const prev = merged[key];
437
+ merged[key] = prev === undefined ? candidate : Math.max(prev, candidate);
438
+ }
439
+ return merged;
440
+ }
441
+ function parseOverrideCondition(raw) {
442
+ if (hasOwnDefined(raw, "condition") && !isRecord(raw.condition) || hasOwnDefined(raw, "pricing") && !isRecord(raw.pricing)) {
443
+ return;
444
+ }
445
+ const cond = isRecord(raw.condition) ? raw.condition : raw;
446
+ const prices = isRecord(raw.pricing) ? raw.pricing : raw;
447
+ if (isRecord(raw.condition) && Object.keys(raw.condition).some((k) => !KNOWN_CONDITION_KEYS.has(k))) {
448
+ return;
449
+ }
450
+ const threshold = cond.min_prompt_tokens;
451
+ const validThreshold = isPositiveSafeInteger(threshold);
452
+ const utcOk = (v) => v === 0 || isPositiveSafeInteger(v) && v <= 2400;
453
+ const daysOk = (v) => Array.isArray(v) && v.length > 0 && v.every((d) => typeof d === "string" && d.trim().length > 0);
454
+ const hasUtc = hasOwnDefined(cond, "utc_start") || hasOwnDefined(cond, "utc_end") || hasOwnDefined(cond, "utc_days");
455
+ if (hasOwnDefined(cond, "min_prompt_tokens") && !validThreshold || hasOwnDefined(cond, "utc_start") && !utcOk(cond.utc_start) || hasOwnDefined(cond, "utc_end") && !utcOk(cond.utc_end) || hasOwnDefined(cond, "utc_days") && !daysOk(cond.utc_days) || !validThreshold && !hasUtc) {
456
+ return;
457
+ }
458
+ return validThreshold && !hasUtc ? { threshold, prices } : { prices };
459
+ }
460
+ function parseOpenRouterWirePricing(pricing) {
461
+ const base = pricing != null ? parsePriceRecord(pricing, true) : undefined;
462
+ const unknownSet = new Set(base?.unknown ?? []);
463
+ const rawOverrides = Array.isArray(pricing?.overrides) ? pricing.overrides : [];
464
+ const tiers = [];
465
+ const seenThresholds = new Set;
466
+ let conditionalCeiling;
467
+ let hasUnverified = false;
468
+ for (const raw of rawOverrides) {
469
+ const condition = isRecord(raw) ? parseOverrideCondition(raw) : undefined;
470
+ if (condition === undefined) {
471
+ hasUnverified = true;
472
+ continue;
473
+ }
474
+ const parsed = parsePriceRecord(condition.prices, false);
475
+ if (condition.threshold !== undefined) {
476
+ if (seenThresholds.has(condition.threshold)) {
477
+ hasUnverified = true;
478
+ continue;
479
+ }
480
+ seenThresholds.add(condition.threshold);
481
+ tiers.push({
482
+ minPromptTokens: condition.threshold,
483
+ ...parsed.rates,
484
+ ...parsed.unknown.length > 0 && { unknownPricingFields: parsed.unknown }
485
+ });
486
+ } else {
487
+ conditionalCeiling = mergeRateCeilings(conditionalCeiling, parsed.rates);
488
+ for (const field of parsed.unknown)
489
+ unknownSet.add(field);
490
+ }
491
+ }
492
+ tiers.sort((left, right) => left.minPromptTokens - right.minPromptTokens);
493
+ return {
494
+ ...base !== undefined && { base: base.rates },
495
+ hasConditionalPricing: rawOverrides.length > 0,
496
+ ...tiers.length > 0 && { pricingTiers: tiers },
497
+ ...conditionalCeiling !== undefined && { conditionalPricingCeiling: conditionalCeiling },
498
+ unknownPricingFields: [...unknownSet],
499
+ hasUnverifiedPricingOverrides: hasUnverified
500
+ };
501
+ }
100
502
 
101
503
  // src/agent-runtime/openrouter-options.ts
102
- import { z as z2 } from "zod";
103
- var OpenRouterReasoningEffortSchema = z2.enum([
504
+ import { z as z3 } from "zod";
505
+ var OPENROUTER_POLICY_KEYS = [
506
+ "provider",
507
+ "reasoning",
508
+ "session_id",
509
+ "usage",
510
+ "cache_control",
511
+ "model",
512
+ "stream",
513
+ "messages",
514
+ "response_format",
515
+ "tools",
516
+ "tool_choice",
517
+ "max_tokens",
518
+ "temperature",
519
+ "top_p",
520
+ "top_k",
521
+ "presence_penalty",
522
+ "frequency_penalty",
523
+ "seed",
524
+ "stop"
525
+ ];
526
+ var OpenRouterReasoningEffortSchema = z3.enum([
104
527
  "none",
105
528
  "minimal",
106
529
  "low",
@@ -109,34 +532,53 @@ var OpenRouterReasoningEffortSchema = z2.enum([
109
532
  "xhigh",
110
533
  "max"
111
534
  ]);
112
- var Usd = z2.number().nonnegative().finite();
113
- var OpenRouterMaxPriceSchema = z2.strictObject({
535
+ var Usd = z3.number().nonnegative();
536
+ var OpenRouterMaxPriceSchema = z3.strictObject({
114
537
  promptUsdPerMillion: Usd.optional(),
115
538
  completionUsdPerMillion: Usd.optional(),
116
539
  requestUsd: Usd.optional(),
117
540
  imageUsd: Usd.optional()
118
541
  });
119
- var Slug = z2.string().min(1).max(128);
120
- var OpenRouterProviderRoutingSchema = z2.strictObject({
121
- order: z2.array(Slug).min(1).optional(),
122
- only: z2.array(Slug).min(1).optional(),
123
- ignore: z2.array(Slug).min(1).optional(),
124
- allowFallbacks: z2.boolean().optional(),
125
- requireParameters: z2.boolean().optional(),
126
- dataCollection: z2.enum(["allow", "deny"]).optional(),
127
- zdr: z2.boolean().optional(),
128
- sort: z2.enum(["price", "throughput", "latency"]).optional(),
129
- quantizations: z2.array(z2.string().min(1).max(16)).min(1).optional()
542
+ var Slug = z3.string().min(1).max(128);
543
+ var OpenRouterProviderRoutingSchema = z3.strictObject({
544
+ order: z3.array(Slug).min(1).optional(),
545
+ only: z3.array(Slug).min(1).optional(),
546
+ ignore: z3.array(Slug).min(1).optional(),
547
+ allowFallbacks: z3.boolean().optional(),
548
+ requireParameters: z3.boolean().optional(),
549
+ dataCollection: z3.enum(["allow", "deny"]).optional(),
550
+ zdr: z3.boolean().optional(),
551
+ sort: z3.enum(["price", "throughput", "latency"]).optional(),
552
+ quantizations: z3.array(z3.string().min(1).max(16)).min(1).optional()
553
+ });
554
+ var OpenRouterReasoningPolicySchema = z3.strictObject({
555
+ effort: OpenRouterReasoningEffortSchema.optional(),
556
+ maxTokens: z3.int().positive().optional(),
557
+ enabled: z3.boolean().optional(),
558
+ exclude: z3.boolean().optional()
559
+ }).superRefine((reasoning, context) => {
560
+ if (reasoning.effort !== undefined && reasoning.maxTokens !== undefined) {
561
+ context.addIssue({
562
+ code: "custom",
563
+ path: ["maxTokens"],
564
+ message: "Specify reasoning.effort or reasoning.maxTokens, not both"
565
+ });
566
+ }
567
+ if (reasoning.effort === undefined && reasoning.maxTokens === undefined && reasoning.enabled === undefined) {
568
+ context.addIssue({
569
+ code: "custom",
570
+ path: ["effort"],
571
+ message: "Specify at least one of reasoning.effort, reasoning.maxTokens, or reasoning.enabled"
572
+ });
573
+ }
130
574
  });
131
- var OpenRouterRequestPolicySchema = z2.strictObject({
132
- sessionId: z2.string().min(1).max(256).optional(),
133
- reasoning: z2.strictObject({
134
- effort: OpenRouterReasoningEffortSchema,
135
- exclude: z2.boolean().optional()
136
- }).optional(),
575
+ var OpenRouterRequestPolicySchema = z3.strictObject({
576
+ sessionId: z3.string().min(1).max(256).optional(),
577
+ reasoning: OpenRouterReasoningPolicySchema.optional(),
137
578
  provider: OpenRouterProviderRoutingSchema.optional(),
138
579
  maxPrice: OpenRouterMaxPriceSchema.optional(),
139
- looseTools: z2.boolean().optional()
580
+ looseTools: z3.boolean().optional(),
581
+ cacheControl: AgentCacheControlSchema2.optional()
140
582
  }).superRefine((policy, context) => {
141
583
  if (policy.sessionId !== undefined && policy.provider?.order !== undefined)
142
584
  context.addIssue({
@@ -145,7 +587,7 @@ var OpenRouterRequestPolicySchema = z2.strictObject({
145
587
  message: "A request pins its route by sessionId or by provider.order, not both"
146
588
  });
147
589
  });
148
- function buildOpenRouterChatSettings(raw) {
590
+ function resolveOpenRouterWirePolicy(raw) {
149
591
  const policy = OpenRouterRequestPolicySchema.parse(raw);
150
592
  const routing = policy.provider;
151
593
  const price = policy.maxPrice;
@@ -171,66 +613,249 @@ function buildOpenRouterChatSettings(raw) {
171
613
  ...routing?.zdr !== undefined && { zdr: routing.zdr },
172
614
  ...routing?.sort && { sort: routing.sort },
173
615
  ...routing?.quantizations && { quantizations: routing.quantizations },
174
- ...maxPrice && { max_price: maxPrice }
616
+ ...maxPrice && Object.keys(maxPrice).length > 0 && { max_price: maxPrice }
175
617
  } : undefined;
176
- const reasoning = policy.reasoning;
177
- const rawReasoning = reasoning?.effort === "max" ? {
178
- reasoning: {
179
- effort: "max",
180
- ...reasoning.exclude !== undefined && { exclude: reasoning.exclude }
181
- }
182
- } : undefined;
183
- const extraBody = {
184
- ...rawReasoning,
185
- ...policy.sessionId !== undefined && { session_id: policy.sessionId }
186
- };
187
618
  return {
188
- usage: { include: true },
189
- ...provider && { provider },
190
- ...reasoning && reasoning.effort !== "max" && {
619
+ ...provider && Object.keys(provider).length > 0 && { provider },
620
+ ...policy.reasoning && {
191
621
  reasoning: {
192
- effort: reasoning.effort,
193
- ...reasoning.exclude !== undefined && { exclude: reasoning.exclude }
622
+ ...policy.reasoning.effort !== undefined && { effort: policy.reasoning.effort },
623
+ ...policy.reasoning.maxTokens !== undefined && {
624
+ max_tokens: policy.reasoning.maxTokens
625
+ },
626
+ ...policy.reasoning.enabled !== undefined && { enabled: policy.reasoning.enabled },
627
+ ...policy.reasoning.exclude !== undefined && { exclude: policy.reasoning.exclude }
194
628
  }
195
629
  },
196
- ...Object.keys(extraBody).length > 0 && { extraBody },
197
- ...policy.looseTools && { structuredOutputs: { strict: false } }
630
+ ...policy.sessionId !== undefined && { sessionId: policy.sessionId },
631
+ looseTools: policy.looseTools === true,
632
+ ...policy.cacheControl !== undefined && { cacheControl: policy.cacheControl }
198
633
  };
199
634
  }
200
- function withOpenRouterLooseTools(body) {
201
- if (!isRecord(body) || !Array.isArray(body.tools))
202
- return body;
635
+ function mergeOpenRouterStepPolicy(base, providerOptions) {
636
+ const reqOr = recordField(providerOptions, "openrouter");
637
+ if (!reqOr || Object.keys(reqOr).length === 0) {
638
+ return {
639
+ ...base.provider !== undefined && { provider: base.provider },
640
+ ...base.reasoning !== undefined && { reasoning: base.reasoning },
641
+ ...base.sessionId !== undefined && { baseSessionId: base.sessionId },
642
+ looseTools: base.looseTools,
643
+ ...base.cacheControl !== undefined && { baseCacheControl: base.cacheControl }
644
+ };
645
+ }
646
+ let stepExtraBody;
647
+ const policyInput = {};
648
+ for (const [key, value] of Object.entries(reqOr)) {
649
+ if (key === "extraBody") {
650
+ if (value !== undefined) {
651
+ if (!isRecord(value)) {
652
+ throw new TypeError("openRouterProvider: providerOptions.openrouter.extraBody must be a plain object");
653
+ }
654
+ assertNoExtraBodyClash("openRouterProvider", value, OPENROUTER_POLICY_KEYS);
655
+ stepExtraBody = value;
656
+ }
657
+ continue;
658
+ }
659
+ policyInput[key] = value;
660
+ }
661
+ const parsedStep = OpenRouterRequestPolicySchema.parse(policyInput);
662
+ const stepWire = resolveOpenRouterWirePolicy(parsedStep);
663
+ let mergedProvider;
664
+ if (base.provider || stepWire.provider) {
665
+ const baseProvider = stepWire.sessionId !== undefined && base.provider ? Object.fromEntries(Object.entries(base.provider).filter(([k]) => k !== "order")) : base.provider;
666
+ const baseMaxPrice = isRecord(baseProvider?.max_price) ? baseProvider.max_price : null;
667
+ const stepMaxPrice = isRecord(stepWire.provider?.max_price) ? stepWire.provider.max_price : null;
668
+ const combined = {
669
+ ...baseProvider,
670
+ ...stepWire.provider,
671
+ ...baseMaxPrice && stepMaxPrice && { max_price: { ...baseMaxPrice, ...stepMaxPrice } }
672
+ };
673
+ if (Object.keys(combined).length > 0)
674
+ mergedProvider = combined;
675
+ }
203
676
  return {
204
- ...body,
205
- tools: body.tools.map((tool) => isRecord(tool) && tool.type === "function" && isRecord(tool.function) ? { ...tool, function: { ...tool.function, strict: false } } : tool)
677
+ ...mergedProvider !== undefined && { provider: mergedProvider },
678
+ ...(stepWire.reasoning ?? base.reasoning) !== undefined && {
679
+ reasoning: stepWire.reasoning ?? base.reasoning
680
+ },
681
+ ...stepWire.sessionId !== undefined && { stepSessionId: stepWire.sessionId },
682
+ ...base.sessionId !== undefined && { baseSessionId: base.sessionId },
683
+ looseTools: parsedStep.looseTools !== undefined ? stepWire.looseTools : base.looseTools,
684
+ ...stepWire.cacheControl !== undefined && {
685
+ explicitCacheControl: stepWire.cacheControl
686
+ },
687
+ ...base.cacheControl !== undefined && { baseCacheControl: base.cacheControl },
688
+ ...stepExtraBody !== undefined && { stepExtraBody }
206
689
  };
207
690
  }
208
- function rewriteOpenRouterBodyFetch(inner, rewrite) {
209
- const wrapped = async (input, init) => {
210
- const fromRequest = input instanceof Request && init?.body === undefined;
211
- const text = fromRequest ? await input.clone().text() : init?.body;
212
- if (typeof text !== "string" || text.length === 0)
213
- return inner(input, init);
214
- let parsed;
215
- try {
216
- parsed = JSON.parse(text);
217
- } catch {
218
- return inner(input, init);
691
+
692
+ // src/agent-runtime/openrouter-response.ts
693
+ var GENERIC_ERROR_MESSAGES = new Set([
694
+ "OpenRouter request failed",
695
+ "Provider returned error"
696
+ ]);
697
+ var EMPTY_RAW_SENTINELS = new Set(["null", "[]", "{}", '""']);
698
+ var HTML_SNIPPET_PATTERN = /^\s*(?:<!doctype\s+html\b|<html\b|<head\b|<body\b|<title\b|<h1\b|<div\b|<p\b|<pre\b)/iu;
699
+ var MAX_RAW_SNIPPET_CHARS = 512;
700
+ function readMetadataUsageRecord(metadata) {
701
+ if (!isRecord(metadata))
702
+ return;
703
+ const openrouter = recordField(metadata, "openrouter") ?? metadata;
704
+ return recordField(openrouter, "usage") ?? openrouter;
705
+ }
706
+ function readOpenRouterBaseCost(source, metadata) {
707
+ const direct = nonNegativeNumber(source.cost);
708
+ if (direct !== undefined)
709
+ return direct;
710
+ if (!isRecord(metadata))
711
+ return;
712
+ const openrouter = recordField(metadata, "openrouter") ?? metadata;
713
+ const top = nonNegativeNumber(openrouter.cost);
714
+ if (top !== undefined)
715
+ return top;
716
+ const nestedUsage = recordField(openrouter, "usage");
717
+ return nestedUsage ? nonNegativeNumber(nestedUsage.cost) : undefined;
718
+ }
719
+ function readBooleanField(record, key) {
720
+ return typeof record?.[key] === "boolean" ? record[key] : undefined;
721
+ }
722
+ function normalizeOpenRouterUsageDetails(usage, metadata) {
723
+ const source = isRecord(usage) ? recordField(usage, "raw") ?? usage : {};
724
+ const metaUsage = readMetadataUsageRecord(metadata);
725
+ const prompt = recordField(source, "prompt_tokens_details") ?? {};
726
+ const completion = recordField(source, "completion_tokens_details") ?? {};
727
+ const rawCostDetails = recordField(source, "cost_details") ?? (metaUsage ? recordField(metaUsage, "cost_details") : undefined);
728
+ const isByok = readBooleanField(source, "is_byok") ?? readBooleanField(metaUsage, "is_byok");
729
+ const promptCostUsd = nonNegativeNumber(rawCostDetails?.upstream_inference_prompt_cost) ?? nonNegativeNumber(rawCostDetails?.prompt_cost);
730
+ const outputCostUsd = nonNegativeNumber(rawCostDetails?.upstream_inference_completions_cost) ?? nonNegativeNumber(rawCostDetails?.completions_cost) ?? nonNegativeNumber(rawCostDetails?.completion_cost);
731
+ const upstreamInferenceCost = nonNegativeNumber(rawCostDetails?.upstream_inference_cost);
732
+ const baseCost = readOpenRouterBaseCost(source, metadata);
733
+ let cost;
734
+ if (isByok === true) {
735
+ const upstreamCost = upstreamInferenceCost ?? (promptCostUsd !== undefined || outputCostUsd !== undefined ? (promptCostUsd ?? 0) + (outputCostUsd ?? 0) : undefined);
736
+ cost = upstreamCost !== undefined ? computedUsd((baseCost ?? 0) + upstreamCost) : reportedUsd(baseCost);
737
+ } else {
738
+ cost = reportedUsd(baseCost);
739
+ }
740
+ const normalizedUsage = buildProviderUsage({
741
+ inputTokens: reportedInt(source.prompt_tokens),
742
+ outputTokens: reportedInt(source.completion_tokens),
743
+ reasoningTokens: reportedInt(completion.reasoning_tokens),
744
+ cacheReadTokens: reportedInt(prompt.cached_tokens),
745
+ cacheWriteTokens: reportedInt(prompt.cache_write_tokens),
746
+ cost
747
+ });
748
+ const costDetails = promptCostUsd !== undefined || outputCostUsd !== undefined || isByok !== undefined ? {
749
+ ...promptCostUsd !== undefined && { promptCostUsd },
750
+ ...outputCostUsd !== undefined && { outputCostUsd },
751
+ ...isByok !== undefined && { isByok }
752
+ } : undefined;
753
+ return {
754
+ usage: normalizedUsage,
755
+ ...costDetails !== undefined && { costDetails }
756
+ };
757
+ }
758
+ function normalizeOpenRouterUsage(usage, providerMetadata) {
759
+ return normalizeOpenRouterUsageDetails(usage, providerMetadata).usage;
760
+ }
761
+ function readHttpStatusNumber(value) {
762
+ return typeof value === "number" && Number.isInteger(value) && value >= 400 && value < 600 ? value : undefined;
763
+ }
764
+ function readCodeValue(value) {
765
+ return typeof value === "string" && value.length > 0 ? value : typeof value === "number" && Number.isFinite(value) ? value : undefined;
766
+ }
767
+ function extractNestedError(payload, depth) {
768
+ if (depth > 4 || !isRecord(payload))
769
+ return {};
770
+ const err = recordField(payload, "error") ?? payload;
771
+ const outerMessage = nonEmptyString2(err.message);
772
+ const outerCode = readCodeValue(err.code);
773
+ const outerType = nonEmptyString2(err.type) ?? nonEmptyString2(err.status);
774
+ const outerStatus = readHttpStatusNumber(err.code) ?? readHttpStatusNumber(err.status);
775
+ const meta = recordField(err, "metadata");
776
+ const providerName = nonEmptyString2(meta?.provider_name);
777
+ const limitSource = nonEmptyString2(meta?.limit_source);
778
+ const reason = nonEmptyString2(meta?.reason);
779
+ const rawMeta = meta?.raw;
780
+ let nested = {};
781
+ let rawFallback;
782
+ let rawIsHtml = false;
783
+ if (typeof rawMeta === "string" && rawMeta.trim().length > 0) {
784
+ const trimmed = rawMeta.trim();
785
+ if (!EMPTY_RAW_SENTINELS.has(trimmed)) {
786
+ try {
787
+ const parsedRaw = JSON.parse(trimmed);
788
+ if (isRecord(parsedRaw))
789
+ nested = extractNestedError(parsedRaw, depth + 1);
790
+ else
791
+ rawFallback = redactProviderFailureText(trimmed, MAX_RAW_SNIPPET_CHARS);
792
+ } catch {
793
+ rawIsHtml = HTML_SNIPPET_PATTERN.test(trimmed);
794
+ rawFallback = redactProviderFailureText(trimmed, MAX_RAW_SNIPPET_CHARS);
795
+ }
219
796
  }
220
- const body = JSON.stringify(rewrite(parsed));
221
- if (fromRequest)
222
- return inner(new Request(input, { body }), init);
223
- return inner(input, { ...init, body });
797
+ } else if (isRecord(rawMeta)) {
798
+ nested = extractNestedError(rawMeta, depth + 1);
799
+ }
800
+ const nestedMessage = nested.message && !GENERIC_ERROR_MESSAGES.has(nested.message) ? nested.message : undefined;
801
+ const meaningfulOuter = outerMessage && !GENERIC_ERROR_MESSAGES.has(outerMessage) ? outerMessage : undefined;
802
+ const message = nestedMessage ?? (rawIsHtml && meaningfulOuter !== undefined ? meaningfulOuter : rawFallback) ?? outerMessage;
803
+ const code = typeof nested.code === "string" ? nested.code : outerCode !== undefined ? outerCode : nested.code;
804
+ const errorType = nested.errorType ?? outerType;
805
+ const statusCode = outerStatus ?? nested.statusCode;
806
+ return {
807
+ ...message !== undefined && { message },
808
+ ...code !== undefined && { code },
809
+ ...errorType !== undefined && { errorType },
810
+ ...statusCode !== undefined && { statusCode },
811
+ ...(providerName ?? nested.providerName) !== undefined && {
812
+ providerName: providerName ?? nested.providerName
813
+ },
814
+ ...(limitSource ?? nested.limitSource) !== undefined && {
815
+ limitSource: limitSource ?? nested.limitSource
816
+ },
817
+ ...(reason ?? nested.reason) !== undefined && {
818
+ reason: reason ?? nested.reason
819
+ },
820
+ ...nested.code !== undefined && { upstreamCode: nested.code },
821
+ ...nested.statusCode !== undefined && { upstreamStatus: nested.statusCode }
822
+ };
823
+ }
824
+ function parseOpenRouterError(payload, rawText = "", status) {
825
+ const extracted = extractNestedError(payload, 0);
826
+ const trimmedRaw = rawText.trim();
827
+ const baseMessage = extracted.message ?? (trimmedRaw.length > 0 ? status !== undefined ? `OpenRouter HTTP ${status}: ${redactProviderFailureText(trimmedRaw, MAX_RAW_SNIPPET_CHARS)}` : redactProviderFailureText(trimmedRaw, MAX_RAW_SNIPPET_CHARS) : status !== undefined ? `OpenRouter HTTP ${status}` : "OpenRouter request failed");
828
+ const prefixed = extracted.providerName && !baseMessage.startsWith(`[${extracted.providerName}] `) ? `[${extracted.providerName}] ${baseMessage}` : baseMessage;
829
+ const message = redactProviderFailureText(prefixed);
830
+ const errorMeta = {};
831
+ if (extracted.providerName !== undefined)
832
+ errorMeta.provider_name = extracted.providerName;
833
+ if (extracted.limitSource !== undefined)
834
+ errorMeta.limit_source = extracted.limitSource;
835
+ if (extracted.reason !== undefined)
836
+ errorMeta.reason = extracted.reason;
837
+ if (extracted.upstreamCode !== undefined)
838
+ errorMeta.upstream_code = extracted.upstreamCode;
839
+ if (extracted.upstreamStatus !== undefined)
840
+ errorMeta.upstream_status = extracted.upstreamStatus;
841
+ const statusCode = extracted.statusCode ?? (status !== undefined && status >= 400 ? status : undefined);
842
+ const failureReason = statusCode === 402 && extracted.limitSource === "openrouter_in_flight_budget" ? "overloaded" : undefined;
843
+ return {
844
+ message,
845
+ ...extracted.code !== undefined && { code: extracted.code },
846
+ ...extracted.errorType !== undefined && { errorType: extracted.errorType },
847
+ ...statusCode !== undefined && { statusCode },
848
+ ...failureReason !== undefined && { failureReason },
849
+ ...Object.keys(errorMeta).length > 0 && { metadata: errorMeta }
224
850
  };
225
- return Object.assign(wrapped, { preconnect: inner.preconnect });
226
851
  }
227
852
 
228
853
  // src/agent-runtime/openrouter-route.ts
229
854
  import { createHash } from "node:crypto";
230
- import { z as z3 } from "zod";
231
- var OpenRouterRoutePinSchema = z3.discriminatedUnion("kind", [
232
- z3.strictObject({ kind: z3.literal("session-sticky"), sessionId: z3.string().min(1).max(256) }),
233
- z3.strictObject({ kind: z3.literal("provider-order"), provider: z3.string().min(1).max(128) })
855
+ import { z as z4 } from "zod";
856
+ var OpenRouterRoutePinSchema = z4.discriminatedUnion("kind", [
857
+ z4.strictObject({ kind: z4.literal("session-sticky"), sessionId: z4.string().min(1).max(256) }),
858
+ z4.strictObject({ kind: z4.literal("provider-order"), provider: z4.string().min(1).max(128) })
234
859
  ]);
235
860
  function createMemoryOpenRouterRouteStore(options = {}) {
236
861
  const maxEntries = options.maxEntries ?? 1e4;
@@ -300,96 +925,852 @@ function createOpenRouterRouteResolver(options) {
300
925
  };
301
926
  }
302
927
 
303
- // src/agent-runtime/openrouter.ts
304
- var OpenRouterBenchmarkMetaSchema = z4.object({ as_of: z4.iso.datetime({ offset: true }) }).loose();
305
- var OpenRouterArtificialAnalysisRowSchema = z4.object({
306
- source: z4.literal("artificial-analysis"),
307
- model_permaslug: z4.string().min(1),
308
- intelligence_index: z4.number().nullish(),
309
- coding_index: z4.number().nullish(),
310
- agentic_index: z4.number().nullish()
311
- }).loose();
312
- var OpenRouterDesignArenaRowSchema = z4.object({
313
- source: z4.literal("design-arena"),
314
- model_permaslug: z4.string().min(1),
315
- arena: z4.string().min(1),
316
- category: z4.string().min(1).optional(),
317
- elo: z4.number().nullish(),
318
- win_rate: z4.number().nullish(),
319
- avg_generation_time_ms: z4.number().nullish()
320
- }).loose();
321
- var OpenRouterArtificialAnalysisResponseSchema = z4.object({
322
- data: z4.array(OpenRouterArtificialAnalysisRowSchema),
323
- meta: OpenRouterBenchmarkMetaSchema
324
- });
325
- var OpenRouterDesignArenaResponseSchema = z4.object({
326
- data: z4.array(OpenRouterDesignArenaRowSchema),
327
- meta: OpenRouterBenchmarkMetaSchema
328
- });
329
- function catalogJson(fetcher, url, apiKey, signal) {
330
- return openRouterJson({ fetcher, url, apiKey, signal });
928
+ // src/agent-runtime/provider-openai-chat-helpers.ts
929
+ var AUDIO_FORMAT_ALIASES = {
930
+ "audio/wave": "wav",
931
+ "audio/x-wav": "wav",
932
+ "audio/mpeg": "mp3",
933
+ "audio/mp4": "m4a"
934
+ };
935
+ function encodeChatFilePart(data, mediaType, filename, providerKey) {
936
+ const payload = resolveFilePayload(data, mediaType);
937
+ if (payload.kind === "text")
938
+ return { type: "text", text: payload.text };
939
+ if (payload.kind === "reference") {
940
+ const fileId = payload.reference[providerKey] ?? Object.values(payload.reference)[0];
941
+ return typeof fileId === "string" && fileId.length > 0 ? { type: "file", file: { file_id: fileId } } : { type: "text", text: `[file:${mediaType}]` };
942
+ }
943
+ const mime = normalizeMime(payload.kind === "base64" ? payload.mediaType : mediaType);
944
+ const url = payload.kind === "url" ? payload.url : `data:${mime};base64,${payload.base64}`;
945
+ if (mime.startsWith("image/"))
946
+ return { type: "image_url", image_url: { url } };
947
+ if (mime.startsWith("video/"))
948
+ return { type: "video_url", video_url: { url } };
949
+ if (mime.startsWith("audio/")) {
950
+ if (payload.kind === "url") {
951
+ throw new TypeError("OpenAI Chat input_audio requires base64 audio bytes, not an HTTP(S) URL");
952
+ }
953
+ const format = AUDIO_FORMAT_ALIASES[mime] ?? mime.slice("audio/".length);
954
+ return { type: "input_audio", input_audio: { data: payload.base64, format } };
955
+ }
956
+ const name = filename ? sanitizeSurrogates(filename) : fallbackFilenameForMediaType(mime);
957
+ return { type: "file", file: { filename: name, file_data: url } };
331
958
  }
332
- function capabilities(model) {
333
- const values = ["tools"];
334
- if (model.architecture.input_modalities.includes("image"))
335
- values.push("vision");
336
- if (model.architecture.input_modalities.includes("file"))
337
- values.push("files");
338
- if (model.supported_parameters.includes("reasoning"))
339
- values.push("reasoning");
340
- return values;
959
+ function collectChatReasoningDetails(optionsList, providerKey) {
960
+ const collected = [];
961
+ const seen = new Set;
962
+ for (const options of optionsList) {
963
+ const ns = options && isRecord(options[providerKey]) ? options[providerKey] : undefined;
964
+ if (!Array.isArray(ns?.reasoning_details))
965
+ continue;
966
+ for (const item of ns.reasoning_details) {
967
+ if (!isRecord(item))
968
+ continue;
969
+ if (item.type === "reasoning.text") {
970
+ const fmt = typeof item.format === "string" ? item.format : undefined;
971
+ if ((fmt === "anthropic-claude-v1" || fmt === "google-gemini-v1") && (typeof item.signature !== "string" || item.signature.length === 0)) {
972
+ continue;
973
+ }
974
+ }
975
+ const key = deterministicJson(item);
976
+ if (seen.has(key))
977
+ continue;
978
+ seen.add(key);
979
+ collected.push({ ...item });
980
+ }
981
+ }
982
+ return collected;
983
+ }
984
+ function extractChatToolExtraContent(options, providerKey) {
985
+ if (!options)
986
+ return;
987
+ const ns = isRecord(options[providerKey]) ? options[providerKey] : undefined;
988
+ if (isRecord(ns?.extra_content))
989
+ return ns.extra_content;
990
+ const orNs = providerKey !== "openrouter" && isRecord(options.openrouter) ? options.openrouter : null;
991
+ if (isRecord(orNs?.extra_content))
992
+ return orNs.extra_content;
993
+ const google = isRecord(options.google) ? options.google : undefined;
994
+ const sig = google?.thought_signature ?? google?.thoughtSignature;
995
+ return typeof sig === "string" && sig.length > 0 ? { google: { thought_signature: sig } } : undefined;
996
+ }
997
+ function encodeChatResponseFormat(format, normalize) {
998
+ if (!format || format.type === "text")
999
+ return;
1000
+ if (format.type === "json-object")
1001
+ return { type: "json_object" };
1002
+ const strict = format.strict ?? true;
1003
+ const schema = normalize ? normalizeOpenAiJsonSchema(format.schema, strict) : format.schema;
1004
+ const jsonSchema = { name: format.name, schema, strict };
1005
+ if (format.description !== undefined) {
1006
+ jsonSchema.description = sanitizeSurrogates(format.description);
1007
+ }
1008
+ return { type: "json_schema", json_schema: jsonSchema };
1009
+ }
1010
+ function toChatJsonRecord(record) {
1011
+ const toVal = (v) => {
1012
+ if (v === null || typeof v === "string" || typeof v === "boolean")
1013
+ return v;
1014
+ if (typeof v === "number" && Number.isFinite(v))
1015
+ return v;
1016
+ return Array.isArray(v) ? v.map(toVal) : isRecord(v) ? toChatJsonRecord(v) : String(v);
1017
+ };
1018
+ const out = {};
1019
+ for (const [k, v] of Object.entries(record))
1020
+ if (v !== undefined)
1021
+ out[k] = toVal(v);
1022
+ return out;
1023
+ }
1024
+ function mergeChatRecord(prev, next) {
1025
+ if (!prev)
1026
+ return { ...next };
1027
+ const out = { ...prev };
1028
+ for (const [k, v] of Object.entries(next)) {
1029
+ const cur = out[k];
1030
+ if (isRecord(cur) && isRecord(v))
1031
+ out[k] = mergeChatRecord(cur, v);
1032
+ else if (v !== undefined)
1033
+ out[k] = v;
1034
+ }
1035
+ return out;
1036
+ }
1037
+ function buildChatEnvelope(provider, details, extraContent) {
1038
+ const data = {};
1039
+ if (details.length > 0)
1040
+ data.reasoning_details = details.map(toChatJsonRecord);
1041
+ if (extraContent !== undefined)
1042
+ data.extra_content = toChatJsonRecord(extraContent);
1043
+ return Object.keys(data).length > 0 ? { schemaVersion: 1, provider, data } : undefined;
1044
+ }
1045
+ var ABNORMAL_NATIVE_FINISH_REASONS = new Set([
1046
+ "MALFORMED_RESPONSE",
1047
+ "MALFORMED_FUNCTION_CALL",
1048
+ "OTHER",
1049
+ "INSUFFICIENT_SYSTEM_RESOURCE",
1050
+ "ERROR",
1051
+ "UNEXPECTED_TOOL_CALL",
1052
+ "RECITATION"
1053
+ ]);
1054
+ function isAbnormalNativeFinishReason(native) {
1055
+ return native !== undefined && ABNORMAL_NATIVE_FINISH_REASONS.has(native.trim().toUpperCase());
1056
+ }
1057
+ function isCompleteJsonObject(raw) {
1058
+ const trimmed = raw.trim();
1059
+ if (!trimmed.startsWith("{") || !trimmed.endsWith("}"))
1060
+ return false;
1061
+ try {
1062
+ return isRecord(JSON.parse(trimmed));
1063
+ } catch {
1064
+ return false;
1065
+ }
1066
+ }
1067
+ function isToolCallSlotCollision(input) {
1068
+ const { prev, rawId, name, arg } = input;
1069
+ const startsNewJsonObject = arg.trimStart().startsWith("{") && isCompleteJsonObject(prev.arguments);
1070
+ const sameIdAndName = rawId !== undefined && prev.rawId === rawId && (name === undefined || prev.name.length === 0 || name === prev.name);
1071
+ if (sameIdAndName)
1072
+ return startsNewJsonObject;
1073
+ if (rawId !== undefined && prev.rawId !== undefined && prev.rawId !== rawId)
1074
+ return true;
1075
+ return prev.name.length > 0 && name !== undefined && (name !== prev.name || rawId !== undefined || startsNewJsonObject);
1076
+ }
1077
+ function* decodeChatMediaAndSources(delta, onOutput) {
1078
+ for (const img of Array.isArray(delta.images) ? delta.images : []) {
1079
+ const url = isRecord(img) && isRecord(img.image_url) ? nonEmptyString2(img.image_url.url) : null;
1080
+ if (!url)
1081
+ continue;
1082
+ const m = /^data:([^;,]+);base64,([\s\S]+)$/u.exec(url);
1083
+ if (m?.[1] && m[2]) {
1084
+ onOutput();
1085
+ yield { type: "file", mediaType: m[1], data: { type: "data", data: m[2] } };
1086
+ } else if (/^https?:\/\//u.test(url) && URL.canParse(url)) {
1087
+ onOutput();
1088
+ const mt = nonEmptyString2(isRecord(img) ? img.media_type : null) ?? "image/png";
1089
+ yield { type: "file", mediaType: mt, data: { type: "url", url: new URL(url) } };
1090
+ }
1091
+ }
1092
+ for (const ann of Array.isArray(delta.annotations) ? delta.annotations : []) {
1093
+ if (!isRecord(ann) || ann.type !== "url_citation" || !isRecord(ann.url_citation))
1094
+ continue;
1095
+ const c = ann.url_citation;
1096
+ const url = nonEmptyString2(c.url);
1097
+ if (!url || !URL.canParse(url))
1098
+ continue;
1099
+ const title = typeof c.title === "string" ? c.title : undefined;
1100
+ yield {
1101
+ type: "source",
1102
+ source: { type: "source", sourceId: crypto.randomUUID(), url, ...title && { title } }
1103
+ };
1104
+ }
1105
+ }
1106
+
1107
+ // src/agent-runtime/provider-openai-chat.ts
1108
+ class EncodeContext {
1109
+ hooks;
1110
+ planned = [];
1111
+ constructor(hooks) {
1112
+ this.hooks = hooks;
1113
+ }
1114
+ ccOf(item) {
1115
+ return readPortableCacheControl(item.cacheControl, item.providerOptions, this.hooks.providerKey);
1116
+ }
1117
+ plan(slot, cc, target) {
1118
+ if (cc !== undefined)
1119
+ this.planned.push({ slot, control: cc, target });
1120
+ }
1121
+ planText(slot, cc, msg, text) {
1122
+ if (text.length > 0)
1123
+ this.plan(slot, cc, (w) => {
1124
+ msg.content = [{ type: "text", text, cache_control: w }];
1125
+ });
1126
+ }
1127
+ }
1128
+ function attachFallbackPartCache(parts, cc, ctx) {
1129
+ const rev = [...parts].reverse();
1130
+ const chosen = rev.find((p) => !p.hasCache && p.isNonEmptyText) ?? rev.find((p) => !p.hasCache && p.canAttachCache);
1131
+ if (!chosen)
1132
+ return;
1133
+ chosen.hasCache = true;
1134
+ ctx.plan("message", cc, (wireCc) => {
1135
+ chosen.wire.cache_control = wireCc;
1136
+ });
1137
+ }
1138
+ function encodePartList(items, allowPartCache, ctx) {
1139
+ const out = [];
1140
+ for (const part of items) {
1141
+ const wire = part.type === "text" ? { type: "text", text: part.text } : part.type === "file" ? encodeChatFilePart(part.data, part.mediaType, part.filename, ctx.hooks.providerKey) : { type: "text", text: deterministicJson(part) };
1142
+ const isText = wire.type === "text";
1143
+ const isNonEmptyText = isText && typeof wire.text === "string" && wire.text.length > 0;
1144
+ if (isText && !isNonEmptyText)
1145
+ continue;
1146
+ const entry = {
1147
+ wire,
1148
+ isNonEmptyText,
1149
+ canAttachCache: !isText || isNonEmptyText,
1150
+ hasCache: false
1151
+ };
1152
+ const partCc = allowPartCache ? ctx.ccOf(part) : undefined;
1153
+ if (partCc !== undefined && entry.canAttachCache) {
1154
+ entry.hasCache = true;
1155
+ ctx.plan("message", partCc, (wireCc) => {
1156
+ entry.wire.cache_control = wireCc;
1157
+ });
1158
+ }
1159
+ out.push(entry);
1160
+ }
1161
+ return out;
1162
+ }
1163
+ function encodeUserMessage(msg, ctx) {
1164
+ const msgCc = ctx.ccOf(msg);
1165
+ if (typeof msg.content === "string") {
1166
+ const wire = { role: "user", content: msg.content };
1167
+ ctx.planText("message", msgCc, wire, msg.content);
1168
+ return wire;
1169
+ }
1170
+ const only = msg.content.length === 1 && msg.content[0]?.type === "text" ? msg.content[0] : null;
1171
+ if (only) {
1172
+ const wire = { role: "user", content: only.text };
1173
+ ctx.planText("message", ctx.ccOf(only) ?? msgCc, wire, only.text);
1174
+ return wire;
1175
+ }
1176
+ const parts = encodePartList(msg.content, true, ctx);
1177
+ if (msgCc && parts.length > 0)
1178
+ attachFallbackPartCache(parts, msgCc, ctx);
1179
+ return { role: "user", content: parts.length > 0 ? parts.map((p) => p.wire) : "" };
1180
+ }
1181
+ function encodeAssistantMessage(msg, ctx) {
1182
+ const { hooks } = ctx;
1183
+ const msgCc = ctx.ccOf(msg);
1184
+ if (typeof msg.content === "string") {
1185
+ if (msg.content.length === 0)
1186
+ return;
1187
+ const wire = { role: "assistant", content: msg.content };
1188
+ ctx.planText("message", msgCc, wire, msg.content);
1189
+ return wire;
1190
+ }
1191
+ const blocks = [];
1192
+ let reasoning = "";
1193
+ const toolCalls = [];
1194
+ const allOptions = [msg.providerOptions];
1195
+ const msgWire = { role: "assistant", content: null };
1196
+ const markBlock = (block, cc) => {
1197
+ if (cc === undefined || block.hasCache)
1198
+ return;
1199
+ block.hasCache = true;
1200
+ ctx.plan("message", cc, (wireCc) => {
1201
+ block.wire.cache_control = wireCc;
1202
+ msgWire.content = blocks.map((b) => b.wire);
1203
+ });
1204
+ };
1205
+ for (const part of msg.content) {
1206
+ if ("providerOptions" in part)
1207
+ allOptions.push(part.providerOptions);
1208
+ if (part.type === "text" && part.text.length > 0) {
1209
+ const block = {
1210
+ wire: { type: "text", text: part.text },
1211
+ text: part.text,
1212
+ hasCache: false
1213
+ };
1214
+ blocks.push(block);
1215
+ markBlock(block, ctx.ccOf(part));
1216
+ } else if (part.type === "reasoning") {
1217
+ reasoning += part.text;
1218
+ } else if (part.type === "tool-call" && part.providerExecuted !== true) {
1219
+ const id = hooks.mapToolCallId ? hooks.mapToolCallId(part.toolCallId) : part.toolCallId;
1220
+ const extra = hooks.supportsToolExtraContent ? extractChatToolExtraContent(part.providerOptions, hooks.providerKey) : undefined;
1221
+ const args = typeof part.input === "string" ? sanitizeSurrogates(part.input) : deterministicJson(part.input ?? {});
1222
+ toolCalls.push({
1223
+ id,
1224
+ type: "function",
1225
+ function: { name: part.toolName, arguments: args },
1226
+ ...extra !== undefined && { extra_content: extra }
1227
+ });
1228
+ }
1229
+ }
1230
+ const details = hooks.supportsReasoningDetails ? collectChatReasoningDetails(allOptions, hooks.providerKey) : [];
1231
+ if (blocks.length === 0 && toolCalls.length === 0 && details.length === 0)
1232
+ return;
1233
+ msgWire.content = blocks.length > 0 ? blocks.map((b) => b.text).join("") : toolCalls.length > 0 ? null : "";
1234
+ if (toolCalls.length > 0)
1235
+ msgWire.tool_calls = toolCalls;
1236
+ if (details.length > 0) {
1237
+ msgWire.reasoning_details = details;
1238
+ if (reasoning.length > 0)
1239
+ msgWire.reasoning = reasoning;
1240
+ }
1241
+ const last = blocks.at(-1);
1242
+ if (last)
1243
+ markBlock(last, msgCc);
1244
+ return msgWire;
1245
+ }
1246
+ function encodeToolMessage(msg, ctx) {
1247
+ const results = msg.content.filter((p) => p.type === "tool-result");
1248
+ if (results.length === 0)
1249
+ return [];
1250
+ let turnCc;
1251
+ for (const part of results)
1252
+ turnCc = ctx.ccOf(part) ?? ctx.ccOf(part.output) ?? turnCc;
1253
+ const effectiveCc = turnCc ?? ctx.ccOf(msg);
1254
+ return results.map((part, index) => {
1255
+ const isLast = index === results.length - 1;
1256
+ const id = ctx.hooks.mapToolCallId ? ctx.hooks.mapToolCallId(part.toolCallId) : part.toolCallId;
1257
+ const out = part.output;
1258
+ let content;
1259
+ let parts;
1260
+ if (out.type === "text" || out.type === "error-text")
1261
+ content = out.value;
1262
+ else if (out.type === "json" || out.type === "error-json")
1263
+ content = deterministicJson(out.value);
1264
+ else if (out.type === "execution-denied")
1265
+ content = out.reason ?? "Tool execution denied";
1266
+ else {
1267
+ parts = encodePartList(out.value, isLast, ctx);
1268
+ content = parts.length === 0 ? "(no tool output)" : parts.map((p) => p.wire);
1269
+ }
1270
+ const wire = {
1271
+ role: "tool",
1272
+ tool_call_id: id,
1273
+ name: part.toolName,
1274
+ content
1275
+ };
1276
+ if (isLast && effectiveCc !== undefined) {
1277
+ if (typeof content === "string")
1278
+ ctx.planText("message", effectiveCc, wire, content);
1279
+ else if (parts && parts.length > 0)
1280
+ attachFallbackPartCache(parts, effectiveCc, ctx);
1281
+ }
1282
+ return wire;
1283
+ });
1284
+ }
1285
+ function encodeMessages(request, normalized, ctx) {
1286
+ const wire = [];
1287
+ const pushSys = (text, item) => {
1288
+ if (!text)
1289
+ return;
1290
+ const msg = { role: "system", content: text };
1291
+ ctx.planText("system", ctx.ccOf(item), msg, text);
1292
+ wire.push(msg);
1293
+ };
1294
+ for (const sys of request.instructions)
1295
+ pushSys(sanitizeSurrogates(sys.content), sys);
1296
+ for (const msg of normalized) {
1297
+ if (msg.role === "system")
1298
+ pushSys(msg.content, msg);
1299
+ else if (msg.role === "user")
1300
+ wire.push(encodeUserMessage(msg, ctx));
1301
+ else if (msg.role === "assistant") {
1302
+ const encoded = encodeAssistantMessage(msg, ctx);
1303
+ if (encoded)
1304
+ wire.push(encoded);
1305
+ } else
1306
+ wire.push(...encodeToolMessage(msg, ctx));
1307
+ }
1308
+ return wire;
1309
+ }
1310
+ function encodeTools(specs, normalized, ctx) {
1311
+ if (specs.length === 0)
1312
+ return historyHasToolTraffic(normalized) ? [] : undefined;
1313
+ return specs.map((spec) => {
1314
+ if (spec.type === "provider") {
1315
+ throw new TypeError(`${ctx.hooks.providerKey}: unsupported provider tool "${spec.id}" (type: "provider")`);
1316
+ }
1317
+ const strict = spec.strict ?? (ctx.hooks.looseTools ? false : undefined);
1318
+ const params = ctx.hooks.normalizeJsonSchema ? normalizeOpenAiJsonSchema(spec.inputSchema, strict === true) : spec.inputSchema;
1319
+ const fn = { name: spec.name, parameters: params };
1320
+ if (spec.description !== undefined)
1321
+ fn.description = sanitizeSurrogates(spec.description);
1322
+ if (strict !== undefined)
1323
+ fn.strict = strict;
1324
+ const toolWire = { type: "function", function: fn };
1325
+ ctx.plan("tools", ctx.ccOf(spec), (w) => {
1326
+ toolWire.cache_control = w;
1327
+ });
1328
+ return toolWire;
1329
+ });
1330
+ }
1331
+ function buildOpenAiChatRequestBody(input) {
1332
+ const { modelId, request, hooks } = input;
1333
+ const normalized = normalizeProviderHistory(request.messages);
1334
+ const ctx = new EncodeContext(hooks);
1335
+ const tools = encodeTools(request.tools, normalized, ctx);
1336
+ const messages = encodeMessages(request, normalized, ctx);
1337
+ const responseFormat = encodeChatResponseFormat(request.responseFormat, hooks.normalizeJsonSchema === true);
1338
+ let topLevelCache;
1339
+ let topLevelCacheControl;
1340
+ if (hooks.explicitTopLevelCacheControl !== undefined) {
1341
+ topLevelCacheControl = hooks.explicitTopLevelCacheControl;
1342
+ topLevelCache = toWireCacheControl(hooks.explicitTopLevelCacheControl);
1343
+ } else if (hooks.autoTopLevelCacheControl !== undefined && (hooks.supportsAnthropicCacheControlOnMessages ? hooks.supportsAnthropicCacheControlOnMessages(modelId) : hooks.supportsInlineCacheControl === true)) {
1344
+ topLevelCacheControl = hooks.autoTopLevelCacheControl;
1345
+ topLevelCache = toWireCacheControl(hooks.autoTopLevelCacheControl);
1346
+ }
1347
+ const keptBreakpoints = hooks.supportsInlineCacheControl !== false && ctx.planned.length > 0 ? budgetCacheBreakpoints(ctx.planned, topLevelCache ? MAX_CACHE_BREAKPOINTS - 1 : MAX_CACHE_BREAKPOINTS) : [];
1348
+ const wireControls = [
1349
+ ...keptBreakpoints.map((bp) => bp.control),
1350
+ ...topLevelCacheControl !== undefined ? [topLevelCacheControl] : []
1351
+ ];
1352
+ if (wireControls.length > 0) {
1353
+ assertValidCacheTtlOrder(wireControls, hooks.providerKey);
1354
+ }
1355
+ for (const bp of keptBreakpoints) {
1356
+ bp.target(toWireCacheControl(bp.control));
1357
+ }
1358
+ const s = request.settings;
1359
+ const maxTokensKey = hooks.maxTokensField ?? "max_tokens";
1360
+ const body = {
1361
+ ...hooks.extraBody ?? {},
1362
+ ...hooks.extraFields ?? {},
1363
+ model: modelId,
1364
+ stream: true,
1365
+ messages
1366
+ };
1367
+ if (hooks.usageInclusion === "openrouter")
1368
+ body.usage = { include: true };
1369
+ else if (hooks.usageInclusion === "stream-options")
1370
+ body.stream_options = { include_usage: true };
1371
+ if (tools !== undefined)
1372
+ body.tools = tools;
1373
+ if (request.tools.length > 0 && request.toolChoice !== undefined) {
1374
+ body.tool_choice = typeof request.toolChoice === "string" ? request.toolChoice : { type: "function", function: { name: request.toolChoice.toolName } };
1375
+ }
1376
+ if (responseFormat !== undefined)
1377
+ body.response_format = responseFormat;
1378
+ if (s.maxOutputTokens !== undefined)
1379
+ body[maxTokensKey] = s.maxOutputTokens;
1380
+ if (s.temperature !== undefined)
1381
+ body.temperature = s.temperature;
1382
+ if (s.topP !== undefined)
1383
+ body.top_p = s.topP;
1384
+ if (hooks.supportsTopK !== false && s.topK !== undefined)
1385
+ body.top_k = s.topK;
1386
+ if (s.presencePenalty !== undefined)
1387
+ body.presence_penalty = s.presencePenalty;
1388
+ if (s.frequencyPenalty !== undefined)
1389
+ body.frequency_penalty = s.frequencyPenalty;
1390
+ if (s.seed !== undefined)
1391
+ body.seed = s.seed;
1392
+ if (s.stopSequences !== undefined)
1393
+ body.stop = [...s.stopSequences];
1394
+ if (topLevelCache !== undefined)
1395
+ body.cache_control = topLevelCache;
1396
+ return body;
1397
+ }
1398
+
1399
+ // src/agent-runtime/provider-openai-chat-sse.ts
1400
+ var MAX_TOOL_CALLS = 256;
1401
+
1402
+ class DecodeState {
1403
+ streamDeltas;
1404
+ explicitUsageMeta;
1405
+ responseId;
1406
+ responseModelId;
1407
+ responseTimestamp;
1408
+ responseProvider;
1409
+ metadataEmitted = false;
1410
+ textOpen = false;
1411
+ producedOutput = false;
1412
+ sawRefusal = false;
1413
+ reasoningOpen = false;
1414
+ reasoningBlock = 0;
1415
+ reasoningDirty = false;
1416
+ finishReason = "other";
1417
+ rawFinishReason;
1418
+ nativeFinishReason;
1419
+ sawFinish = false;
1420
+ sawDone = false;
1421
+ sawError = false;
1422
+ rawUsage;
1423
+ reasoningDetails = [];
1424
+ toolCalls = new Map;
1425
+ activeSlotByWireIndex = new Map;
1426
+ lastSlot;
1427
+ seenIds = new Set;
1428
+ constructor(streamDeltas, explicitUsageMeta) {
1429
+ this.streamDeltas = streamDeltas;
1430
+ this.explicitUsageMeta = explicitUsageMeta;
1431
+ }
1432
+ }
1433
+ function mapOpenAiChatFinishReason(raw) {
1434
+ if (raw === "stop" || raw === "length" || raw === "error")
1435
+ return raw;
1436
+ if (raw === "tool_calls" || raw === "function_call")
1437
+ return "tool-calls";
1438
+ return raw === "content_filter" ? "content-filter" : "other";
1439
+ }
1440
+ function mergeReasoningDetail(acc, d) {
1441
+ const t = d.type;
1442
+ if (t === "reasoning.encrypted") {
1443
+ const hasId = (v) => typeof v === "string" && v.length > 0;
1444
+ if (hasId(d.id)) {
1445
+ const existing = acc.find((i) => i.type === t && i.format === d.format && i.id === d.id);
1446
+ if (existing) {
1447
+ if (typeof d.data === "string" && d.data.length > 0)
1448
+ existing.data = d.data;
1449
+ return;
1450
+ }
1451
+ acc.push({ ...d });
1452
+ return;
1453
+ }
1454
+ const duplicate = acc.some((i) => i.type === t && i.format === d.format && !hasId(i.id) && i.data === d.data);
1455
+ if (!duplicate)
1456
+ acc.push({ ...d });
1457
+ return;
1458
+ }
1459
+ const canMatch = t === "reasoning.text" || t === "reasoning.summary";
1460
+ const m = canMatch ? acc.find((i) => i.type === t && i.format === d.format && i.index === d.index && i.id === d.id) : undefined;
1461
+ if (!m) {
1462
+ acc.push({ ...d });
1463
+ return;
1464
+ }
1465
+ const add = (k, v) => {
1466
+ if (typeof v === "string")
1467
+ m[k] = `${typeof m[k] === "string" ? m[k] : ""}${v}`;
1468
+ };
1469
+ if (t === "reasoning.text") {
1470
+ add("text", d.text);
1471
+ if (typeof d.signature === "string" && d.signature.length > 0)
1472
+ m.signature = d.signature;
1473
+ } else if (t === "reasoning.summary")
1474
+ add("summary", d.summary);
1475
+ }
1476
+ function makeProviderError(provider, parsed) {
1477
+ const { message, ...rest } = parsed;
1478
+ return new AgentProviderError2(redactProviderFailureText(message || `${provider} request failed`), { provider, ...rest });
1479
+ }
1480
+ function* closeText(state) {
1481
+ if (!state.textOpen)
1482
+ return;
1483
+ state.textOpen = false;
1484
+ yield { type: "text-end", id: "text-0" };
1485
+ }
1486
+ function* closeReasoning(state, provider) {
1487
+ const env = buildChatEnvelope(provider, state.reasoningDetails);
1488
+ if (!state.reasoningOpen && !(env && state.reasoningDirty))
1489
+ return;
1490
+ const id = `reasoning-${state.reasoningBlock}`;
1491
+ state.reasoningBlock += 1;
1492
+ state.reasoningDirty = false;
1493
+ if (!state.reasoningOpen)
1494
+ yield { type: "reasoning-start", id };
1495
+ state.reasoningOpen = false;
1496
+ yield { type: "reasoning-end", id, ...env && { provider: env } };
1497
+ }
1498
+ function* processToolCallDelta(tc, state, provider) {
1499
+ const fn = isRecord(tc.function) ? tc.function : undefined;
1500
+ const rawId = nonEmptyString2(tc.id);
1501
+ const name = nonEmptyString2(fn?.name);
1502
+ const arg = typeof fn?.arguments === "string" ? fn.arguments : "";
1503
+ const wireIndex = typeof tc.index === "number" && Number.isInteger(tc.index) && tc.index >= 0 ? tc.index : undefined;
1504
+ let slot = wireIndex !== undefined ? state.activeSlotByWireIndex.get(wireIndex) ?? wireIndex : state.lastSlot ?? 0;
1505
+ const prev = state.toolCalls.get(slot);
1506
+ if (prev !== undefined && isToolCallSlotCollision({ prev, rawId, name, arg })) {
1507
+ slot = 0;
1508
+ while (state.toolCalls.has(slot))
1509
+ slot += 1;
1510
+ }
1511
+ if (wireIndex !== undefined)
1512
+ state.activeSlotByWireIndex.set(wireIndex, slot);
1513
+ state.lastSlot = slot;
1514
+ let entry = state.toolCalls.get(slot);
1515
+ if (!entry) {
1516
+ if (state.toolCalls.size >= MAX_TOOL_CALLS) {
1517
+ throw new AgentProviderError2(`${provider} exceeded maximum tool calls per step (${MAX_TOOL_CALLS})`, { provider });
1518
+ }
1519
+ const id = rawId && !state.seenIds.has(rawId) ? rawId : crypto.randomUUID();
1520
+ state.seenIds.add(id);
1521
+ entry = { id, ...rawId && { rawId }, name: name ?? "", arguments: "", started: false };
1522
+ state.toolCalls.set(slot, entry);
1523
+ } else {
1524
+ if (rawId && !entry.rawId)
1525
+ entry.rawId = rawId;
1526
+ if (name && !entry.name)
1527
+ entry.name = name;
1528
+ }
1529
+ if (isRecord(tc.extra_content))
1530
+ entry.extraContent = mergeChatRecord(entry.extraContent, tc.extra_content);
1531
+ if (state.streamDeltas && !entry.started && entry.name.trim()) {
1532
+ entry.started = true;
1533
+ yield { type: "tool-input-start", toolCallId: entry.id, toolName: entry.name };
1534
+ if (entry.arguments)
1535
+ yield { type: "tool-input-delta", toolCallId: entry.id, delta: entry.arguments };
1536
+ }
1537
+ if (arg) {
1538
+ entry.arguments += arg;
1539
+ if (state.streamDeltas && entry.started)
1540
+ yield { type: "tool-input-delta", toolCallId: entry.id, delta: arg };
1541
+ }
1542
+ }
1543
+ function* decodeChunk(chunk, s, opts) {
1544
+ if (!isRecord(chunk))
1545
+ return;
1546
+ s.responseId = nonEmptyString2(chunk.id) ?? s.responseId;
1547
+ s.responseModelId = nonEmptyString2(chunk.model) ?? s.responseModelId;
1548
+ if (s.responseTimestamp === undefined && typeof chunk.created === "number" && Number.isFinite(chunk.created) && chunk.created >= 0) {
1549
+ s.responseTimestamp = new Date(chunk.created * 1000);
1550
+ }
1551
+ s.responseProvider = nonEmptyString2(chunk.provider) ?? s.responseProvider;
1552
+ if (chunk.usage !== undefined && chunk.usage !== null)
1553
+ s.rawUsage = chunk.usage;
1554
+ if ("error" in chunk && chunk.error !== undefined && chunk.error !== null) {
1555
+ s.sawError = true;
1556
+ s.finishReason = "error";
1557
+ yield { type: "error", error: makeProviderError(opts.provider, opts.parseError(chunk)) };
1558
+ return;
1559
+ }
1560
+ if (!s.metadataEmitted && (s.responseId || s.responseModelId || s.responseTimestamp)) {
1561
+ s.metadataEmitted = true;
1562
+ yield {
1563
+ type: "response-metadata",
1564
+ ...s.responseId && { id: s.responseId },
1565
+ ...s.responseModelId && { modelId: s.responseModelId },
1566
+ ...s.responseTimestamp && { timestamp: s.responseTimestamp }
1567
+ };
1568
+ }
1569
+ const choice = Array.isArray(chunk.choices) && isRecord(chunk.choices[0]) ? chunk.choices[0] : null;
1570
+ if (!choice)
1571
+ return;
1572
+ const finish = nonEmptyString2(choice.finish_reason);
1573
+ if (finish) {
1574
+ s.rawFinishReason = finish;
1575
+ s.finishReason = mapOpenAiChatFinishReason(finish);
1576
+ s.sawFinish = true;
1577
+ }
1578
+ s.nativeFinishReason = nonEmptyString2(choice.native_finish_reason) ?? s.nativeFinishReason;
1579
+ const delta = isRecord(choice.delta) ? choice.delta : null;
1580
+ if (!delta)
1581
+ return;
1582
+ const rChunks = [];
1583
+ for (const item of Array.isArray(delta.reasoning_details) ? delta.reasoning_details : []) {
1584
+ if (!isRecord(item))
1585
+ continue;
1586
+ mergeReasoningDetail(s.reasoningDetails, item);
1587
+ s.reasoningDirty = true;
1588
+ const text = item.type === "reasoning.text" ? nonEmptyString2(item.text) : item.type === "reasoning.summary" ? nonEmptyString2(item.summary) : undefined;
1589
+ if (text)
1590
+ rChunks.push(text);
1591
+ }
1592
+ if (rChunks.length === 0) {
1593
+ const plain = nonEmptyString2(delta.reasoning) ?? nonEmptyString2(delta.reasoning_content);
1594
+ if (plain)
1595
+ rChunks.push(plain);
1596
+ }
1597
+ for (const text of rChunks) {
1598
+ const id = `reasoning-${s.reasoningBlock}`;
1599
+ if (!s.reasoningOpen) {
1600
+ s.reasoningOpen = true;
1601
+ yield { type: "reasoning-start", id };
1602
+ }
1603
+ yield { type: "reasoning-delta", id, delta: text };
1604
+ }
1605
+ if (nonEmptyString2(delta.refusal) !== undefined) {
1606
+ s.sawRefusal = true;
1607
+ }
1608
+ const content = nonEmptyString2(delta.content);
1609
+ if (content) {
1610
+ yield* closeReasoning(s, opts.provider);
1611
+ s.producedOutput = true;
1612
+ if (!s.textOpen) {
1613
+ s.textOpen = true;
1614
+ yield { type: "text-start", id: "text-0" };
1615
+ }
1616
+ yield { type: "text-delta", id: "text-0", delta: content };
1617
+ }
1618
+ yield* decodeChatMediaAndSources(delta, () => {
1619
+ s.producedOutput = true;
1620
+ });
1621
+ if (Array.isArray(delta.tool_calls)) {
1622
+ yield* closeReasoning(s, opts.provider);
1623
+ yield* closeText(s);
1624
+ for (const tc of delta.tool_calls)
1625
+ if (isRecord(tc))
1626
+ yield* processToolCallDelta(tc, s, opts.provider);
1627
+ }
341
1628
  }
342
- function artificialMetrics(row, observedAt) {
343
- return [
344
- ["intelligence", row.intelligence_index],
345
- ["coding", row.coding_index],
346
- ["agentic", row.agentic_index]
347
- ].flatMap(([metric, value]) => typeof metric === "string" && typeof value === "number" ? [
348
- {
349
- metric,
350
- value,
351
- unit: "index",
352
- source: row.source,
353
- observedAt
1629
+ function finishPart(s, finishReason, ur, env) {
1630
+ const rawFinishReason = s.nativeFinishReason ?? s.rawFinishReason;
1631
+ const response = s.responseId || s.responseModelId || s.responseTimestamp ? {
1632
+ ...s.responseId && { id: s.responseId },
1633
+ ...s.responseModelId && { modelId: s.responseModelId },
1634
+ ...s.responseTimestamp && { timestamp: s.responseTimestamp }
1635
+ } : undefined;
1636
+ return {
1637
+ type: "finish",
1638
+ finishReason,
1639
+ ...rawFinishReason && { rawFinishReason },
1640
+ usage: ur.usage,
1641
+ ...ur.costDetails && { costDetails: ur.costDetails },
1642
+ ...s.responseProvider && { responseProvider: s.responseProvider },
1643
+ ...response && { response },
1644
+ ...env && { provider: env }
1645
+ };
1646
+ }
1647
+ function* flushState(s, opts) {
1648
+ if (!s.sawDone && !s.sawFinish && !s.sawError) {
1649
+ throw new AgentProviderStreamCutError2(`${opts.provider} SSE stream ended before completion`, { provider: opts.provider });
1650
+ }
1651
+ const meta = s.explicitUsageMeta ?? { [opts.provider]: { usage: s.rawUsage } };
1652
+ if (s.sawError) {
1653
+ if (s.rawUsage === undefined)
1654
+ return;
1655
+ if (s.reasoningOpen)
1656
+ yield { type: "reasoning-end", id: `reasoning-${s.reasoningBlock}` };
1657
+ yield* closeText(s);
1658
+ yield finishPart(s, "error", opts.normalizeUsage(s.rawUsage, meta));
1659
+ return;
1660
+ }
1661
+ yield* closeText(s);
1662
+ yield* closeReasoning(s, opts.provider);
1663
+ const calls = [...s.toolCalls.entries()].sort((a, b) => a[0] - b[0]).map(([, c]) => c).filter((c) => c.name.trim().length > 0);
1664
+ let attached = false;
1665
+ for (const call of calls) {
1666
+ if (call.started)
1667
+ yield { type: "tool-input-end", toolCallId: call.id };
1668
+ const env = buildChatEnvelope(opts.provider, attached ? [] : s.reasoningDetails, call.extraContent);
1669
+ if (!attached && s.reasoningDetails.length > 0)
1670
+ attached = true;
1671
+ yield {
1672
+ type: "tool-call",
1673
+ toolCallId: call.id,
1674
+ toolName: call.name,
1675
+ input: call.arguments.trim().length > 0 ? call.arguments : "{}",
1676
+ ...env && { provider: env }
1677
+ };
1678
+ }
1679
+ const usageResult = opts.normalizeUsage(s.rawUsage, meta);
1680
+ const native = s.nativeFinishReason;
1681
+ if (!s.producedOutput && !s.sawRefusal && calls.length === 0 && s.finishReason === "stop" && isAbnormalNativeFinishReason(native)) {
1682
+ yield {
1683
+ type: "error",
1684
+ error: new AgentProviderError2(`${opts.provider} returned an empty response with native_finish_reason "${native}"`, {
1685
+ provider: opts.provider,
1686
+ code: native,
1687
+ failureReason: "stream-cut",
1688
+ metadata: { native_finish_reason: native }
1689
+ })
1690
+ };
1691
+ if (s.rawUsage !== undefined && s.rawUsage !== null)
1692
+ yield finishPart(s, "error", usageResult);
1693
+ return;
1694
+ }
1695
+ const reason = calls.length > 0 && (s.finishReason === "stop" || s.finishReason === "other") ? "tool-calls" : s.sawRefusal && !s.producedOutput && calls.length === 0 ? "content-filter" : s.finishReason;
1696
+ yield finishPart(s, reason, usageResult, buildChatEnvelope(opts.provider, s.reasoningDetails));
1697
+ }
1698
+ async function* decodeOpenAiChatSseStream(body, options) {
1699
+ const state = new DecodeState(true);
1700
+ try {
1701
+ for await (const frame of parseSseStream(body, {
1702
+ provider: options.provider,
1703
+ ...options.signal && { signal: options.signal }
1704
+ })) {
1705
+ if (frame.kind === "ping")
1706
+ yield { type: "ping" };
1707
+ else if (frame.data.trim() === "[DONE]")
1708
+ state.sawDone = true;
1709
+ else
1710
+ yield* decodeChunk(parseSseJson(options.provider, frame.data.trim()), state, options);
354
1711
  }
355
- ] : []);
1712
+ } catch (error) {
1713
+ if (options.signal?.aborted || error instanceof AgentProviderError2 || error instanceof AgentProviderStreamCutError2 || error instanceof Error && error.name === "AbortError") {
1714
+ throw error;
1715
+ }
1716
+ throw new AgentProviderStreamCutError2(`${options.provider} SSE stream disconnected before completion`, { provider: options.provider, cause: error });
1717
+ }
1718
+ yield* flushState(state, options);
356
1719
  }
357
- function designMetrics(row, observedAt) {
358
- const suffix = `${row.arena}${row.category ? `:${row.category}` : ""}`;
359
- const metrics = [];
360
- if (typeof row.elo === "number") {
361
- metrics.push({
362
- metric: `design-arena:${suffix}:elo`,
363
- value: row.elo,
364
- unit: "elo",
365
- source: row.source,
366
- observedAt
1720
+ async function* decodeOpenAiChatJsonResponse(body, options) {
1721
+ if (!isRecord(body)) {
1722
+ throw new AgentProviderError2(`${options.provider} returned an invalid JSON response`, {
1723
+ provider: options.provider
367
1724
  });
368
1725
  }
369
- if (typeof row.win_rate === "number") {
370
- metrics.push({
371
- metric: `design-arena:${suffix}:win-rate`,
372
- value: row.win_rate,
373
- unit: "percent",
374
- source: row.source,
375
- observedAt
376
- });
1726
+ if ("error" in body && body.error !== undefined && body.error !== null) {
1727
+ throw makeProviderError(options.provider, options.parseError(body));
377
1728
  }
378
- if (typeof row.avg_generation_time_ms === "number") {
379
- metrics.push({
380
- metric: `design-arena:${suffix}:generation-time`,
381
- value: row.avg_generation_time_ms,
382
- unit: "milliseconds",
383
- source: row.source,
384
- observedAt
385
- });
1729
+ const first = Array.isArray(body.choices) && isRecord(body.choices[0]) ? body.choices[0] : null;
1730
+ const state = new DecodeState(false, body);
1731
+ state.finishReason = "stop";
1732
+ state.sawDone = true;
1733
+ const normalizedMessage = isRecord(first?.message) ? { ...first.message } : {};
1734
+ if (Array.isArray(normalizedMessage.tool_calls)) {
1735
+ normalizedMessage.tool_calls = normalizedMessage.tool_calls.map((tc, idx) => isRecord(tc) && typeof tc.index !== "number" ? { ...tc, index: idx } : tc);
386
1736
  }
387
- return metrics;
1737
+ const choices = first ? [
1738
+ {
1739
+ delta: normalizedMessage,
1740
+ finish_reason: first.finish_reason,
1741
+ native_finish_reason: first.native_finish_reason
1742
+ }
1743
+ ] : [];
1744
+ yield* decodeChunk({
1745
+ id: body.id,
1746
+ model: body.model,
1747
+ created: body.created,
1748
+ provider: body.provider,
1749
+ usage: body.usage,
1750
+ choices
1751
+ }, state, options);
1752
+ yield* flushState(state, options);
1753
+ }
1754
+
1755
+ // src/agent-runtime/openrouter.ts
1756
+ var DEFAULT_OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1";
1757
+ var EMPTY_WIRE_POLICY = { looseTools: false };
1758
+ function catalogJson(fetcher, url, apiKey, signal) {
1759
+ return openRouterJson({
1760
+ fetcher,
1761
+ url,
1762
+ ...apiKey !== undefined && { apiKey },
1763
+ signal
1764
+ });
1765
+ }
1766
+ function benchmarkOutcome(fetcher, url, apiKey, signal) {
1767
+ return catalogJson(fetcher, url, apiKey, signal).then((value) => ({ outcome: "ok", value }), (error) => ({ outcome: "error", error }));
388
1768
  }
389
- function openRouterModelCatalog(options) {
1769
+ function openRouterModelCatalog(options = {}) {
390
1770
  const fetcher = options.fetcher ?? fetch;
391
1771
  const timeoutMs = options.timeoutMs ?? 1e4;
392
1772
  assertTimerMs("timeoutMs", timeoutMs);
1773
+ assertValidStaticOpenRouterApiKey(options.apiKey);
393
1774
  return {
394
1775
  async load(input = {}) {
395
1776
  const modelsUrl = new URL("https://openrouter.ai/api/v1/models");
@@ -403,39 +1784,12 @@ function openRouterModelCatalog(options) {
403
1784
  designUrl.searchParams.set("arena", "agents");
404
1785
  const [modelsRaw, artificialResult, designResult] = await withOpenRouterTimeout(timeoutMs, input.signal, (signal) => Promise.all([
405
1786
  catalogJson(fetcher, modelsUrl, options.apiKey, signal),
406
- catalogJson(fetcher, artificialUrl, options.apiKey, signal).then((value) => ({ outcome: "ok", value }), (error) => ({ outcome: "error", error })),
407
- catalogJson(fetcher, designUrl, options.apiKey, signal).then((value) => ({ outcome: "ok", value }), (error) => ({ outcome: "error", error }))
1787
+ benchmarkOutcome(fetcher, artificialUrl, options.apiKey, signal),
1788
+ benchmarkOutcome(fetcher, designUrl, options.apiKey, signal)
408
1789
  ]));
409
1790
  const observedAt = (options.now?.() ?? new Date).toISOString();
410
1791
  const models = OpenRouterModelsResponseSchema.parse(modelsRaw).data;
411
- const metrics = new Map;
412
- const diagnostics = [];
413
- if (artificialResult.outcome === "ok") {
414
- const parsed = OpenRouterArtificialAnalysisResponseSchema.safeParse(artificialResult.value);
415
- if (parsed.success) {
416
- for (const row of parsed.data.data) {
417
- metrics.set(row.model_permaslug, artificialMetrics(row, parsed.data.meta.as_of));
418
- }
419
- } else {
420
- diagnostics.push("Artificial Analysis benchmark data is malformed");
421
- }
422
- } else
423
- diagnostics.push("Artificial Analysis benchmark data is unavailable");
424
- if (designResult.outcome === "ok") {
425
- const parsed = OpenRouterDesignArenaResponseSchema.safeParse(designResult.value);
426
- if (parsed.success) {
427
- for (const row of parsed.data.data) {
428
- metrics.set(row.model_permaslug, [
429
- ...metrics.get(row.model_permaslug) ?? [],
430
- ...designMetrics(row, parsed.data.meta.as_of)
431
- ]);
432
- }
433
- } else {
434
- diagnostics.push("Design Arena benchmark data is malformed");
435
- }
436
- } else
437
- diagnostics.push("Design Arena benchmark data is unavailable");
438
- const seen = new Set;
1792
+ const { metrics, diagnostics } = collectOpenRouterBenchmarks(artificialResult, designResult);
439
1793
  return AgentModelCatalogSchema2.parse({
440
1794
  schemaVersion: 1,
441
1795
  source: "openrouter",
@@ -443,35 +1797,32 @@ function openRouterModelCatalog(options) {
443
1797
  completeness: diagnostics.length === 0 ? "complete" : "partial",
444
1798
  diagnostics,
445
1799
  models: models.flatMap((model, index) => {
446
- if (model.context_length === 0)
1800
+ const contextWindow = model.context_length != null && model.context_length > 0 ? model.context_length : model.top_provider?.context_length != null && model.top_provider.context_length > 0 ? model.top_provider.context_length : undefined;
1801
+ if (contextWindow === undefined)
447
1802
  return [];
448
- if (seen.has(model.id))
449
- return [];
450
- seen.add(model.id);
451
1803
  const canonical = model.canonical_slug ?? model.id;
1804
+ const name = nonEmptyTrimmed(model.name) ?? model.id;
1805
+ const promptPrice = typeof model.pricing?.prompt === "string" && usd(model.pricing.prompt) !== undefined ? model.pricing.prompt : undefined;
1806
+ const completionPrice = typeof model.pricing?.completion === "string" && usd(model.pricing.completion) !== undefined ? model.pricing.completion : undefined;
452
1807
  return [
453
1808
  {
454
1809
  id: model.id,
455
- name: model.name,
1810
+ name,
456
1811
  descriptor: {
457
1812
  provider: "openrouter",
458
1813
  modelId: model.id,
459
- contextWindow: model.context_length,
460
- capabilities: capabilities(model),
1814
+ contextWindow,
1815
+ capabilities: openRouterCapabilities(model),
461
1816
  observedAt,
462
1817
  source: "openrouter-models",
463
1818
  availability: "available"
464
1819
  },
465
1820
  ...model.description && { description: model.description },
466
- ...(usd(model.pricing.prompt) !== undefined || usd(model.pricing.completion) !== undefined) && {
1821
+ ...(promptPrice !== undefined || completionPrice !== undefined) && {
467
1822
  price: {
468
1823
  currency: "USD",
469
- ...usd(model.pricing.prompt) !== undefined && {
470
- inputPerToken: model.pricing.prompt
471
- },
472
- ...usd(model.pricing.completion) !== undefined && {
473
- outputPerToken: model.pricing.completion
474
- }
1824
+ ...promptPrice !== undefined && { inputPerToken: promptPrice },
1825
+ ...completionPrice !== undefined && { outputPerToken: completionPrice }
475
1826
  }
476
1827
  },
477
1828
  popularity: {
@@ -488,94 +1839,187 @@ function openRouterModelCatalog(options) {
488
1839
  }
489
1840
  };
490
1841
  }
491
- var POLICY_KEYS = ["provider", "reasoning", "session_id", "usage"];
492
- function openRouterProvider(settings, access = {}) {
493
- const clash = POLICY_KEYS.filter((key) => settings.extraBody?.[key] !== undefined);
494
- if (clash.length > 0)
495
- throw new TypeError(`openRouterProvider: extraBody sets ${clash.join(", ")}, which the request policy owns; put it in the policy`);
496
- const policyOf = (modelId) => access.resolvePolicy?.(modelId) ?? access.defaultPolicy ?? {};
497
- const rewrite = (body) => {
498
- if (!isRecord(body))
499
- return body;
500
- const policy = typeof body.model === "string" ? policyOf(body.model) : {};
501
- const loosened = policy.looseTools ? withOpenRouterLooseTools(body) : body;
502
- const conversation = currentModelInvocationAttempt2()?.conversationId;
503
- const pinned = isRecord(body.provider) && Array.isArray(body.provider.order);
504
- return access.sessionPerConversation && conversation !== undefined && isRecord(loosened) && loosened.session_id === undefined && !pinned ? { ...loosened, session_id: openRouterSessionKey(conversation) } : loosened;
505
- };
506
- const needsWire = access.sessionPerConversation || access.resolvePolicy !== undefined || access.defaultPolicy?.looseTools;
507
- const provider = createOpenRouter({
508
- ...settings,
509
- ...needsWire && { fetch: rewriteOpenRouterBodyFetch(settings.fetch ?? fetch, rewrite) }
510
- });
1842
+ function buildBaseHeaders(settings, apiKey) {
511
1843
  return {
512
- create: (modelId) => provider.chat(modelId, buildOpenRouterChatSettings(policyOf(modelId))),
513
- normalizeUsage: ({ usage, providerMetadata }) => normalizeOpenRouterUsage(usage, providerMetadata),
514
- resolveResponseProvider: ({ providerMetadata }) => readUpstreamProvider(providerMetadata)
1844
+ authorization: `Bearer ${apiKey}`,
1845
+ ...settings.appUrl !== undefined && { "HTTP-Referer": settings.appUrl },
1846
+ ...settings.appName !== undefined && { "X-OpenRouter-Title": settings.appName },
1847
+ ...settings.providerApiKeys !== undefined && {
1848
+ "X-Provider-API-Keys": JSON.stringify(settings.providerApiKeys)
1849
+ }
515
1850
  };
516
1851
  }
517
- function readUpstreamProvider(metadata) {
518
- if (!isRecord(metadata))
519
- return;
520
- const openrouter = metadata.openrouter;
521
- if (!isRecord(openrouter))
522
- return;
523
- const name = openrouter.provider;
524
- return typeof name === "string" && name.length > 0 ? name : undefined;
525
- }
526
- function reported(value) {
527
- return typeof value !== "number" || !Number.isSafeInteger(value) || value < 0 ? { provenance: "unavailable" } : { value, provenance: "provider-reported" };
528
- }
529
- function reportedUsd(value) {
530
- return value === undefined || !Number.isFinite(value) || value < 0 ? { provenance: "unavailable" } : { value, currency: "USD", provenance: "provider-reported" };
531
- }
532
- function readCost(metadata) {
533
- if (!isRecord(metadata))
534
- return;
535
- const openrouter = metadata.openrouter;
536
- if (!isRecord(openrouter))
537
- return;
538
- if (typeof openrouter.cost === "number" && openrouter.cost >= 0)
539
- return openrouter.cost;
540
- const usage = openrouter.usage;
541
- return isRecord(usage) && typeof usage.cost === "number" && usage.cost >= 0 ? usage.cost : undefined;
1852
+ function buildOpenRouterRequestBody(input) {
1853
+ const { modelId, request, policy, sessionPerConversation, extraBody } = input;
1854
+ const merged = mergeOpenRouterStepPolicy(policy, request.providerOptions);
1855
+ const pinnedOrder = isRecord(merged.provider) && Array.isArray(merged.provider.order) && merged.provider.order.length > 0;
1856
+ const effectiveSessionId = pinnedOrder ? undefined : merged.stepSessionId !== undefined ? openRouterSessionKey(merged.stepSessionId) : merged.baseSessionId !== undefined ? merged.baseSessionId : sessionPerConversation ? openRouterSessionKey(request.correlation.conversationId) : undefined;
1857
+ const autoTopLevelCacheControl = request.cacheControl ?? merged.baseCacheControl;
1858
+ const extraFields = { ...merged.stepExtraBody ?? {} };
1859
+ if (merged.provider !== undefined)
1860
+ extraFields.provider = merged.provider;
1861
+ if (merged.reasoning !== undefined)
1862
+ extraFields.reasoning = merged.reasoning;
1863
+ if (effectiveSessionId !== undefined)
1864
+ extraFields.session_id = effectiveSessionId;
1865
+ return buildOpenAiChatRequestBody({
1866
+ modelId,
1867
+ request,
1868
+ hooks: {
1869
+ providerKey: "openrouter",
1870
+ looseTools: merged.looseTools,
1871
+ supportsInlineCacheControl: true,
1872
+ supportsAnthropicCacheControlOnMessages: openRouterAllowsInlineCacheControl,
1873
+ normalizeJsonSchema: true,
1874
+ ...merged.explicitCacheControl !== undefined && {
1875
+ explicitTopLevelCacheControl: merged.explicitCacheControl
1876
+ },
1877
+ ...autoTopLevelCacheControl !== undefined && { autoTopLevelCacheControl },
1878
+ usageInclusion: "openrouter",
1879
+ maxTokensField: "max_tokens",
1880
+ supportsTopK: true,
1881
+ supportsReasoningDetails: true,
1882
+ supportsToolExtraContent: true,
1883
+ ...extraBody !== undefined && { extraBody },
1884
+ ...Object.keys(extraFields).length > 0 && { extraFields }
1885
+ }
1886
+ });
542
1887
  }
543
- function normalizeOpenRouterUsage(usage, providerMetadata) {
544
- const raw = isRecord(usage.raw) ? usage.raw : {};
545
- const prompt = isRecord(raw.prompt_tokens_details) ? raw.prompt_tokens_details : {};
546
- const completion = isRecord(raw.completion_tokens_details) ? raw.completion_tokens_details : {};
1888
+ function openRouterProvider(settings, access = {}) {
1889
+ assertNoExtraBodyClash("openRouterProvider", settings.extraBody, OPENROUTER_POLICY_KEYS);
1890
+ const defaultPolicy = access.defaultPolicy !== undefined ? resolveOpenRouterWirePolicy(access.defaultPolicy) : EMPTY_WIRE_POLICY;
1891
+ const endpoint = joinProviderUrl(settings.baseUrl ?? DEFAULT_OPENROUTER_BASE_URL, "/chat/completions");
1892
+ const policyOf = (modelId) => {
1893
+ const resolved = access.resolvePolicy?.(modelId);
1894
+ return resolved !== undefined ? resolveOpenRouterWirePolicy(resolved) : defaultPolicy;
1895
+ };
547
1896
  return {
548
- inputTokens: reported(raw.prompt_tokens),
549
- outputTokens: reported(raw.completion_tokens),
550
- reasoningTokens: reported(completion.reasoning_tokens),
551
- cacheReadTokens: reported(prompt.cached_tokens),
552
- cacheWriteTokens: reported(prompt.cache_write_tokens),
553
- cost: reportedUsd(readCost(providerMetadata))
1897
+ create(modelId) {
1898
+ return {
1899
+ provider: "openrouter",
1900
+ modelId,
1901
+ async stream(request, signal) {
1902
+ const policy = policyOf(modelId);
1903
+ const body = buildOpenRouterRequestBody({
1904
+ modelId,
1905
+ request,
1906
+ policy,
1907
+ sessionPerConversation: access.sessionPerConversation === true,
1908
+ ...settings.extraBody !== undefined && { extraBody: settings.extraBody }
1909
+ });
1910
+ const apiKey = await resolveProviderApiKey(settings.apiKey);
1911
+ const response = await postProviderStream({
1912
+ provider: "openrouter",
1913
+ url: endpoint,
1914
+ headers: buildBaseHeaders(settings, apiKey),
1915
+ ...settings.headers !== undefined && { extraHeaders: settings.headers },
1916
+ ...request.headers !== undefined && { requestHeaders: request.headers },
1917
+ body,
1918
+ signal,
1919
+ ...settings.fetch !== undefined && { fetcher: settings.fetch },
1920
+ parseError: parseOpenRouterError
1921
+ });
1922
+ const decodeOptions = {
1923
+ provider: "openrouter",
1924
+ signal,
1925
+ parseError: (payload) => parseOpenRouterError(payload),
1926
+ normalizeUsage: normalizeOpenRouterUsageDetails
1927
+ };
1928
+ return {
1929
+ parts: response.kind === "json" ? decodeOpenAiChatJsonResponse(response.json, decodeOptions) : decodeOpenAiChatSseStream(response.body, decodeOptions)
1930
+ };
1931
+ }
1932
+ };
1933
+ }
554
1934
  };
555
1935
  }
556
1936
  // src/agent-runtime/openrouter-admission.ts
557
- import { z as z6 } from "zod";
1937
+ import { z as z7 } from "zod";
558
1938
 
559
1939
  // src/agent-runtime/openrouter-catalog.ts
560
1940
  import { z as z5 } from "zod";
561
- var Price = z5.number().nonnegative().finite();
1941
+ var Price = z5.number().nonnegative();
1942
+ var NonNegativeMetric = z5.number().nonnegative();
1943
+ var Percentage = z5.number().min(0).max(100);
1944
+ var UnknownPricingFieldSchema = z5.enum([
1945
+ "prompt",
1946
+ "completion",
1947
+ "request",
1948
+ "image",
1949
+ "cacheRead",
1950
+ "cacheWrite",
1951
+ "cacheWrite1h"
1952
+ ]);
1953
+ var ConditionalPricingCeilingSchema = z5.strictObject({
1954
+ promptUsdPerMillion: Price.optional(),
1955
+ completionUsdPerMillion: Price.optional(),
1956
+ cacheReadUsdPerMillion: Price.optional(),
1957
+ cacheWriteUsdPerMillion: Price.optional(),
1958
+ cacheWrite1hUsdPerMillion: Price.optional(),
1959
+ requestUsd: Price.optional(),
1960
+ imageUsd: Price.optional()
1961
+ });
1962
+ var OpenRouterPricingTierSchema = z5.strictObject({
1963
+ minPromptTokens: z5.int().positive(),
1964
+ promptUsdPerMillion: Price.optional(),
1965
+ completionUsdPerMillion: Price.optional(),
1966
+ cacheReadUsdPerMillion: Price.optional(),
1967
+ cacheWriteUsdPerMillion: Price.optional(),
1968
+ cacheWrite1hUsdPerMillion: Price.optional(),
1969
+ requestUsd: Price.optional(),
1970
+ imageUsd: Price.optional(),
1971
+ unknownPricingFields: z5.array(UnknownPricingFieldSchema).min(1).optional()
1972
+ });
1973
+ var OpenRouterModelAliasTargetSchema = z5.strictObject({
1974
+ id: z5.string().min(1),
1975
+ name: z5.string().min(1).optional()
1976
+ });
1977
+ var OpenRouterModelReasoningMetaSchema = z5.strictObject({
1978
+ supportedEfforts: z5.array(z5.string().min(1)),
1979
+ defaultEffort: z5.string().min(1).optional()
1980
+ });
562
1981
  var OpenRouterEndpointSchema = z5.strictObject({
563
1982
  provider: z5.string().min(1),
564
1983
  contextLength: z5.int().nonnegative().optional(),
1984
+ maxCompletionTokens: z5.int().nonnegative().optional(),
565
1985
  promptUsdPerMillion: Price.optional(),
566
1986
  completionUsdPerMillion: Price.optional(),
1987
+ cacheReadUsdPerMillion: Price.optional(),
1988
+ cacheWriteUsdPerMillion: Price.optional(),
1989
+ cacheWrite1hUsdPerMillion: Price.optional(),
567
1990
  supportedParameters: z5.array(z5.string()),
568
- status: z5.int().optional()
1991
+ status: z5.int().optional(),
1992
+ latencyP50Ms: NonNegativeMetric.optional(),
1993
+ throughputP50: NonNegativeMetric.optional(),
1994
+ uptime1d: Percentage.optional(),
1995
+ tag: z5.string().min(1).optional()
569
1996
  });
570
1997
  var OpenRouterSnapshotModelSchema = z5.strictObject({
571
1998
  id: z5.string().min(1),
572
1999
  name: z5.string().min(1).optional(),
573
2000
  canonicalSlug: z5.string().min(1).optional(),
2001
+ description: z5.string().min(1).optional(),
2002
+ createdAt: z5.iso.datetime({ offset: true }).optional(),
2003
+ aliasTarget: OpenRouterModelAliasTargetSchema.optional(),
574
2004
  inputModalities: z5.array(z5.string().min(1)).default([]),
575
- contextLength: z5.int().nonnegative(),
2005
+ outputModalities: z5.array(z5.string().min(1)).optional(),
2006
+ tokenizer: z5.string().min(1).optional(),
2007
+ contextLength: z5.int().nonnegative().optional(),
2008
+ topProviderContextLength: z5.int().nonnegative().optional(),
2009
+ maxCompletionTokens: z5.int().nonnegative().optional(),
2010
+ reasoning: OpenRouterModelReasoningMetaSchema.optional(),
576
2011
  promptUsdPerMillion: Price.optional(),
577
2012
  completionUsdPerMillion: Price.optional(),
578
2013
  requestUsd: Price.optional(),
2014
+ imageUsd: Price.optional(),
2015
+ cacheReadUsdPerMillion: Price.optional(),
2016
+ cacheWriteUsdPerMillion: Price.optional(),
2017
+ cacheWrite1hUsdPerMillion: Price.optional(),
2018
+ pricingTiers: z5.array(OpenRouterPricingTierSchema).optional(),
2019
+ hasConditionalPricing: z5.boolean().optional(),
2020
+ unknownPricingFields: z5.array(UnknownPricingFieldSchema).min(1).optional(),
2021
+ conditionalPricingCeiling: ConditionalPricingCeilingSchema.optional(),
2022
+ hasUnverifiedPricingOverrides: z5.boolean().optional(),
579
2023
  supportedParameters: z5.array(z5.string()),
580
2024
  aliasOf: z5.string().min(1).optional(),
581
2025
  endpoints: z5.array(OpenRouterEndpointSchema).optional()
@@ -585,55 +2029,102 @@ var OpenRouterCatalogSnapshotSchema = z5.strictObject({
585
2029
  observedAt: z5.iso.datetime({ offset: true }),
586
2030
  models: z5.array(OpenRouterSnapshotModelSchema)
587
2031
  });
588
- var MODEL_ID = /^[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._:-]*$/i;
589
- function endpointsUrl(modelId) {
590
- if (!MODEL_ID.test(modelId) || modelId.includes(".."))
591
- throw new TypeError(`Not an OpenRouter model id: ${modelId}`);
592
- const [author = "", slug = ""] = modelId.split("/");
593
- return new URL(`https://openrouter.ai/api/v1/models/${encodeURIComponent(author)}/${encodeURIComponent(slug)}/endpoints`);
2032
+ function mapSnapshotModel(model, endpoints) {
2033
+ const pricing = parseOpenRouterWirePricing(model.pricing);
2034
+ const createdAt = parseUnixSecondsIso(model.created);
2035
+ const name = model.name != null && model.name.trim().length > 0 ? model.name : model.id;
2036
+ const description = model.description != null && model.description.trim().length > 0 ? model.description : undefined;
2037
+ const canonicalSlug = nonEmptyTrimmed(model.canonical_slug);
2038
+ const aliasTargetName = nonEmptyTrimmed(model.alias_target?.name);
2039
+ const aliasTarget = model.alias_target ? { id: model.alias_target.slug, ...aliasTargetName && { name: aliasTargetName } } : undefined;
2040
+ const outputModalities = model.architecture.output_modalities != null ? nonEmptyStrings(model.architecture.output_modalities) : undefined;
2041
+ const tokenizer = nonEmptyTrimmed(model.architecture.tokenizer);
2042
+ const supportedEfforts = nonEmptyStrings(model.reasoning?.supported_efforts);
2043
+ const defaultEffort = nonEmptyTrimmed(model.reasoning?.default_effort);
2044
+ const reasoning = supportedEfforts.length > 0 || defaultEffort !== undefined ? { supportedEfforts, ...defaultEffort && { defaultEffort } } : undefined;
2045
+ return {
2046
+ id: model.id,
2047
+ name,
2048
+ ...canonicalSlug && { canonicalSlug },
2049
+ ...description && { description },
2050
+ ...createdAt && { createdAt },
2051
+ ...aliasTarget && { aliasTarget },
2052
+ inputModalities: nonEmptyStrings(model.architecture.input_modalities),
2053
+ ...outputModalities !== undefined && { outputModalities },
2054
+ ...tokenizer && { tokenizer },
2055
+ ...model.context_length != null && { contextLength: model.context_length },
2056
+ ...model.top_provider?.context_length != null && {
2057
+ topProviderContextLength: model.top_provider.context_length
2058
+ },
2059
+ ...model.top_provider?.max_completion_tokens != null && {
2060
+ maxCompletionTokens: model.top_provider.max_completion_tokens
2061
+ },
2062
+ ...reasoning && { reasoning },
2063
+ ...pricing.base,
2064
+ ...pricing.pricingTiers && { pricingTiers: pricing.pricingTiers },
2065
+ ...pricing.hasConditionalPricing && { hasConditionalPricing: true },
2066
+ ...pricing.unknownPricingFields.length > 0 && {
2067
+ unknownPricingFields: pricing.unknownPricingFields
2068
+ },
2069
+ ...pricing.conditionalPricingCeiling !== undefined && {
2070
+ conditionalPricingCeiling: pricing.conditionalPricingCeiling
2071
+ },
2072
+ ...pricing.hasUnverifiedPricingOverrides && { hasUnverifiedPricingOverrides: true },
2073
+ supportedParameters: model.supported_parameters,
2074
+ ...endpoints !== undefined && { endpoints: [...endpoints] }
2075
+ };
594
2076
  }
595
- var EndpointsResponseSchema = z5.object({
596
- data: z5.object({
597
- endpoints: z5.array(z5.object({
598
- provider_name: z5.string().min(1),
599
- context_length: z5.int().nonnegative().nullish(),
600
- pricing: z5.object({ prompt: z5.string().optional(), completion: z5.string().optional() }).loose().nullish(),
601
- supported_parameters: z5.array(z5.string()).nullish(),
602
- status: z5.int().nullish()
603
- }).loose())
604
- }).loose()
605
- });
606
- async function fetchOpenRouterModelEndpoints(modelId, options) {
607
- const url = endpointsUrl(modelId);
608
- const parsed = EndpointsResponseSchema.parse(await withOpenRouterTimeout(options.timeoutMs ?? 1e4, options.signal, (signal) => openRouterJson({
2077
+ async function fetchOpenRouterModelEndpoints(modelId, options = {}) {
2078
+ assertValidStaticOpenRouterApiKey(options.apiKey);
2079
+ const url = openRouterEndpointsUrl(modelId);
2080
+ const parsed = OpenRouterEndpointsResponseSchema.parse(await withOpenRouterTimeout(options.timeoutMs ?? 1e4, options.signal, (signal) => openRouterJson({
609
2081
  fetcher: options.fetcher ?? fetch,
610
2082
  url,
611
- apiKey: options.apiKey,
2083
+ ...options.apiKey !== undefined && { apiKey: options.apiKey },
612
2084
  signal,
613
2085
  ...options.maxResponseBytes !== undefined && { maxBytes: options.maxResponseBytes }
614
2086
  })));
615
2087
  return parsed.data.endpoints.map((endpoint) => {
616
2088
  const prompt = usdPerMillion(endpoint.pricing?.prompt);
617
2089
  const completion = usdPerMillion(endpoint.pricing?.completion);
2090
+ const cacheRead = usdPerMillion(endpoint.pricing?.input_cache_read);
2091
+ const cacheWrite = usdPerMillion(endpoint.pricing?.input_cache_write);
2092
+ const cacheWrite1h = usdPerMillion(endpoint.pricing?.input_cache_write_1h);
2093
+ const latencyP50Ms = nonNegativeFinite(endpoint.latency_last_30m?.p50);
2094
+ const throughputP50 = nonNegativeFinite(endpoint.throughput_last_30m?.p50);
2095
+ const uptime1d = percentageMetric(endpoint.uptime_last_1d);
2096
+ const tag = nonEmptyTrimmed(endpoint.tag);
618
2097
  return OpenRouterEndpointSchema.parse({
619
2098
  provider: endpoint.provider_name,
620
2099
  ...endpoint.context_length != null && { contextLength: endpoint.context_length },
2100
+ ...endpoint.max_completion_tokens != null && {
2101
+ maxCompletionTokens: endpoint.max_completion_tokens
2102
+ },
621
2103
  ...prompt !== undefined && { promptUsdPerMillion: prompt },
622
2104
  ...completion !== undefined && { completionUsdPerMillion: completion },
2105
+ ...cacheRead !== undefined && { cacheReadUsdPerMillion: cacheRead },
2106
+ ...cacheWrite !== undefined && { cacheWriteUsdPerMillion: cacheWrite },
2107
+ ...cacheWrite1h !== undefined && { cacheWrite1hUsdPerMillion: cacheWrite1h },
623
2108
  supportedParameters: endpoint.supported_parameters ?? [],
624
- ...endpoint.status != null && { status: endpoint.status }
2109
+ ...endpoint.status != null && { status: endpoint.status },
2110
+ ...latencyP50Ms !== undefined && { latencyP50Ms },
2111
+ ...throughputP50 !== undefined && { throughputP50 },
2112
+ ...uptime1d !== undefined && { uptime1d },
2113
+ ...tag && { tag }
625
2114
  });
626
2115
  });
627
2116
  }
628
- async function loadOpenRouterCatalogSnapshot(options) {
2117
+ async function loadOpenRouterCatalogSnapshot(options = {}) {
629
2118
  const concurrency = options.concurrency ?? 4;
630
2119
  if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > 16)
631
2120
  throw new RangeError("concurrency must be an integer from 1 to 16");
2121
+ assertValidStaticOpenRouterApiKey(options.apiKey);
2122
+ assertValidOpenRouterEndpointsFor(options.endpointsFor);
632
2123
  const observedAt = (options.now?.() ?? new Date).toISOString();
633
2124
  const listing = OpenRouterModelsResponseSchema.parse(await withOpenRouterTimeout(options.timeoutMs ?? 1e4, options.signal, (signal) => openRouterJson({
634
2125
  fetcher: options.fetcher ?? fetch,
635
2126
  url: new URL("https://openrouter.ai/api/v1/models"),
636
- apiKey: options.apiKey,
2127
+ ...options.apiKey !== undefined && { apiKey: options.apiKey },
637
2128
  signal,
638
2129
  ...options.maxResponseBytes !== undefined && { maxBytes: options.maxResponseBytes }
639
2130
  }))).data;
@@ -664,60 +2155,255 @@ async function loadOpenRouterCatalogSnapshot(options) {
664
2155
  return OpenRouterCatalogSnapshotSchema.parse({
665
2156
  schemaVersion: 1,
666
2157
  observedAt,
667
- models: listing.map((model) => {
668
- const prompt = usdPerMillion(model.pricing.prompt);
669
- const completion = usdPerMillion(model.pricing.completion);
670
- const request = usd(model.pricing.request);
671
- return {
672
- id: model.id,
673
- name: model.name,
674
- ...model.canonical_slug && { canonicalSlug: model.canonical_slug },
675
- inputModalities: model.architecture.input_modalities,
676
- contextLength: model.context_length,
677
- ...prompt !== undefined && { promptUsdPerMillion: prompt },
678
- ...completion !== undefined && { completionUsdPerMillion: completion },
679
- ...request !== undefined && { requestUsd: request },
680
- supportedParameters: model.supported_parameters,
681
- ...endpoints.has(model.id) && { endpoints: endpoints.get(model.id) }
682
- };
683
- })
2158
+ models: listing.map((model) => mapSnapshotModel(model, endpoints.get(model.id)))
684
2159
  });
685
2160
  }
686
2161
 
2162
+ // src/agent-runtime/openrouter-catalog-query.ts
2163
+ import { z as z6 } from "zod";
2164
+ var Price2 = z6.number().nonnegative();
2165
+ var NonNegativeMetric2 = z6.number().nonnegative();
2166
+ var Percentage2 = z6.number().min(0).max(100);
2167
+ var OpenRouterModelPricingCeilingSchema = z6.strictObject({
2168
+ promptUsdPerMillion: Price2.optional(),
2169
+ completionUsdPerMillion: Price2.optional(),
2170
+ requestUsd: Price2.optional()
2171
+ });
2172
+ var OpenRouterEndpointSummarySchema = z6.strictObject({
2173
+ providers: z6.int().nonnegative(),
2174
+ latencyP50Ms: NonNegativeMetric2.optional(),
2175
+ throughputP50: NonNegativeMetric2.optional(),
2176
+ uptime1d: Percentage2.optional()
2177
+ });
2178
+ function effectiveContextLength(model) {
2179
+ if (model.contextLength !== undefined && model.topProviderContextLength !== undefined) {
2180
+ return Math.min(model.contextLength, model.topProviderContextLength);
2181
+ }
2182
+ return model.contextLength ?? model.topProviderContextLength;
2183
+ }
2184
+ function summarizeOpenRouterEndpoints(endpoints) {
2185
+ const providers = new Set;
2186
+ let latencyP50Ms;
2187
+ let throughputP50;
2188
+ let uptime1d;
2189
+ for (const endpoint of endpoints) {
2190
+ providers.add(endpoint.provider);
2191
+ if (endpoint.latencyP50Ms !== undefined) {
2192
+ latencyP50Ms = latencyP50Ms === undefined ? endpoint.latencyP50Ms : Math.min(latencyP50Ms, endpoint.latencyP50Ms);
2193
+ }
2194
+ if (endpoint.throughputP50 !== undefined) {
2195
+ throughputP50 = throughputP50 === undefined ? endpoint.throughputP50 : Math.max(throughputP50, endpoint.throughputP50);
2196
+ }
2197
+ if (endpoint.uptime1d !== undefined) {
2198
+ uptime1d = uptime1d === undefined ? endpoint.uptime1d : Math.max(uptime1d, endpoint.uptime1d);
2199
+ }
2200
+ }
2201
+ return {
2202
+ providers: providers.size,
2203
+ ...latencyP50Ms !== undefined && { latencyP50Ms },
2204
+ ...throughputP50 !== undefined && { throughputP50 },
2205
+ ...uptime1d !== undefined && { uptime1d }
2206
+ };
2207
+ }
2208
+ function resolveOpenRouterModelCeiling(model) {
2209
+ if (model.hasUnverifiedPricingOverrides === true)
2210
+ return {};
2211
+ const tiers = model.pricingTiers ?? [];
2212
+ const conditionalCeiling = model.conditionalPricingCeiling;
2213
+ const conditional = model.hasConditionalPricing === true || tiers.length > 0 || conditionalCeiling !== undefined;
2214
+ if (conditional && tiers.length === 0 && conditionalCeiling === undefined)
2215
+ return {};
2216
+ const unknown = new Set(model.unknownPricingFields ?? []);
2217
+ for (const tier of tiers) {
2218
+ for (const field of tier.unknownPricingFields ?? [])
2219
+ unknown.add(field);
2220
+ }
2221
+ let promptCeiling;
2222
+ if (model.promptUsdPerMillion !== undefined && !unknown.has("prompt") && !unknown.has("cacheWrite") && !unknown.has("cacheWrite1h")) {
2223
+ let current = Math.max(model.promptUsdPerMillion, model.cacheWriteUsdPerMillion ?? model.promptUsdPerMillion, model.cacheWrite1hUsdPerMillion ?? model.promptUsdPerMillion);
2224
+ for (const tier of tiers) {
2225
+ if (tier.promptUsdPerMillion !== undefined) {
2226
+ current = Math.max(current, tier.promptUsdPerMillion);
2227
+ }
2228
+ if (tier.cacheWriteUsdPerMillion !== undefined) {
2229
+ current = Math.max(current, tier.cacheWriteUsdPerMillion);
2230
+ }
2231
+ if (tier.cacheWrite1hUsdPerMillion !== undefined) {
2232
+ current = Math.max(current, tier.cacheWrite1hUsdPerMillion);
2233
+ }
2234
+ }
2235
+ if (conditionalCeiling !== undefined) {
2236
+ if (conditionalCeiling.promptUsdPerMillion !== undefined) {
2237
+ current = Math.max(current, conditionalCeiling.promptUsdPerMillion);
2238
+ }
2239
+ if (conditionalCeiling.cacheWriteUsdPerMillion !== undefined) {
2240
+ current = Math.max(current, conditionalCeiling.cacheWriteUsdPerMillion);
2241
+ }
2242
+ if (conditionalCeiling.cacheWrite1hUsdPerMillion !== undefined) {
2243
+ current = Math.max(current, conditionalCeiling.cacheWrite1hUsdPerMillion);
2244
+ }
2245
+ }
2246
+ promptCeiling = current;
2247
+ }
2248
+ let completionCeiling;
2249
+ if (model.completionUsdPerMillion !== undefined && !unknown.has("completion")) {
2250
+ let current = model.completionUsdPerMillion;
2251
+ for (const tier of tiers) {
2252
+ if (tier.completionUsdPerMillion !== undefined) {
2253
+ current = Math.max(current, tier.completionUsdPerMillion);
2254
+ }
2255
+ }
2256
+ if (conditionalCeiling?.completionUsdPerMillion !== undefined) {
2257
+ current = Math.max(current, conditionalCeiling.completionUsdPerMillion);
2258
+ }
2259
+ completionCeiling = current;
2260
+ }
2261
+ let requestCeiling;
2262
+ if (!unknown.has("request")) {
2263
+ let current = model.requestUsd;
2264
+ for (const tier of tiers) {
2265
+ if (tier.requestUsd !== undefined) {
2266
+ current = current === undefined ? tier.requestUsd : Math.max(current, tier.requestUsd);
2267
+ }
2268
+ }
2269
+ if (conditionalCeiling?.requestUsd !== undefined) {
2270
+ current = current === undefined ? conditionalCeiling.requestUsd : Math.max(current, conditionalCeiling.requestUsd);
2271
+ }
2272
+ requestCeiling = current;
2273
+ }
2274
+ return {
2275
+ ...promptCeiling !== undefined && { promptUsdPerMillion: promptCeiling },
2276
+ ...completionCeiling !== undefined && { completionUsdPerMillion: completionCeiling },
2277
+ ...requestCeiling !== undefined && { requestUsd: requestCeiling }
2278
+ };
2279
+ }
2280
+ function hasNonZeroRate(rates) {
2281
+ return (rates.promptUsdPerMillion ?? 0) > 0 || (rates.completionUsdPerMillion ?? 0) > 0 || (rates.cacheReadUsdPerMillion ?? 0) > 0 || (rates.cacheWriteUsdPerMillion ?? 0) > 0 || (rates.cacheWrite1hUsdPerMillion ?? 0) > 0 || (rates.requestUsd ?? 0) > 0 || (rates.imageUsd ?? 0) > 0;
2282
+ }
2283
+ function isFreeModel(model) {
2284
+ if (model.promptUsdPerMillion !== 0 || model.completionUsdPerMillion !== 0)
2285
+ return false;
2286
+ if ((model.unknownPricingFields?.length ?? 0) > 0)
2287
+ return false;
2288
+ if (hasNonZeroRate(model))
2289
+ return false;
2290
+ const tiers = model.pricingTiers ?? [];
2291
+ const conditionalCeiling = model.conditionalPricingCeiling;
2292
+ const hasConditional = model.hasConditionalPricing === true || tiers.length > 0 || conditionalCeiling !== undefined || model.hasUnverifiedPricingOverrides === true;
2293
+ if (!hasConditional)
2294
+ return true;
2295
+ if (model.hasUnverifiedPricingOverrides === true)
2296
+ return false;
2297
+ if (tiers.length === 0 && conditionalCeiling === undefined)
2298
+ return false;
2299
+ for (const tier of tiers) {
2300
+ if ((tier.unknownPricingFields?.length ?? 0) > 0 || hasNonZeroRate(tier))
2301
+ return false;
2302
+ }
2303
+ if (conditionalCeiling !== undefined && hasNonZeroRate(conditionalCeiling))
2304
+ return false;
2305
+ const ceiling = resolveOpenRouterModelCeiling(model);
2306
+ return ceiling.promptUsdPerMillion === 0 && ceiling.completionUsdPerMillion === 0 && (ceiling.requestUsd ?? 0) === 0;
2307
+ }
2308
+ function validateOpenRouterModelFilter(filter) {
2309
+ if (!filter)
2310
+ return;
2311
+ const checks = [
2312
+ ["minContextLength", filter.minContextLength],
2313
+ ["maxPromptUsdPerMillion", filter.maxPromptUsdPerMillion],
2314
+ ["maxCompletionUsdPerMillion", filter.maxCompletionUsdPerMillion]
2315
+ ];
2316
+ for (const [name, value] of checks) {
2317
+ if (value === undefined)
2318
+ continue;
2319
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
2320
+ throw new RangeError(`${name} must be a non-negative finite number`);
2321
+ }
2322
+ }
2323
+ }
2324
+ function matchesFilter(model, filter) {
2325
+ if (filter.tools !== undefined && model.supportedParameters.includes("tools") !== filter.tools) {
2326
+ return false;
2327
+ }
2328
+ if (filter.reasoning !== undefined) {
2329
+ const supportsReasoning = model.supportedParameters.includes("reasoning") || model.supportedParameters.includes("include_reasoning") || model.reasoning !== undefined && (model.reasoning.supportedEfforts.length > 0 || model.reasoning.defaultEffort !== undefined);
2330
+ if (supportsReasoning !== filter.reasoning)
2331
+ return false;
2332
+ }
2333
+ if (filter.inputModalities !== undefined && !filter.inputModalities.every((modality) => model.inputModalities.includes(modality))) {
2334
+ return false;
2335
+ }
2336
+ if (filter.outputModalities !== undefined && filter.outputModalities.length > 0) {
2337
+ if (model.outputModalities === undefined || !filter.outputModalities.every((modality) => model.outputModalities?.includes(modality))) {
2338
+ return false;
2339
+ }
2340
+ }
2341
+ if (filter.minContextLength !== undefined) {
2342
+ const contextLength = effectiveContextLength(model);
2343
+ if (contextLength === undefined || !(contextLength >= filter.minContextLength))
2344
+ return false;
2345
+ }
2346
+ if (filter.maxPromptUsdPerMillion !== undefined && (model.promptUsdPerMillion === undefined || !(model.promptUsdPerMillion <= filter.maxPromptUsdPerMillion))) {
2347
+ return false;
2348
+ }
2349
+ if (filter.maxCompletionUsdPerMillion !== undefined && (model.completionUsdPerMillion === undefined || !(model.completionUsdPerMillion <= filter.maxCompletionUsdPerMillion))) {
2350
+ return false;
2351
+ }
2352
+ if (filter.freeOnly === true && !isFreeModel(model))
2353
+ return false;
2354
+ if (filter.author !== undefined) {
2355
+ const slash = model.id.indexOf("/");
2356
+ const author = slash === -1 ? "" : model.id.slice(0, slash);
2357
+ if (author.toLowerCase() !== filter.author.trim().toLowerCase())
2358
+ return false;
2359
+ }
2360
+ return true;
2361
+ }
2362
+ function findOpenRouterModel(snapshot, idOrSlug) {
2363
+ return snapshot.models.find((model) => model.id === idOrSlug) ?? snapshot.models.find((model) => model.canonicalSlug === idOrSlug);
2364
+ }
2365
+ function listOpenRouterModels(snapshot, filter) {
2366
+ validateOpenRouterModelFilter(filter);
2367
+ if (!filter)
2368
+ return [...snapshot.models];
2369
+ return snapshot.models.filter((model) => matchesFilter(model, filter));
2370
+ }
2371
+
687
2372
  // src/agent-runtime/openrouter-admission.ts
688
- var Usd2 = z6.number().nonnegative().finite();
689
- var OpenRouterAdmissionPolicySchema = z6.strictObject({
690
- maxSnapshotAgeMs: z6.int().positive(),
691
- requiredParameters: z6.array(z6.string().min(1)).default([]),
692
- requiredInputModalities: z6.array(z6.string().min(1)).default([]),
693
- minContextLength: z6.int().nonnegative().optional(),
2373
+ var Usd2 = z7.number().nonnegative();
2374
+ var OpenRouterAdmissionPolicySchema = z7.strictObject({
2375
+ maxSnapshotAgeMs: z7.int().positive(),
2376
+ requiredParameters: z7.array(z7.string().min(1)).default([]),
2377
+ requiredInputModalities: z7.array(z7.string().min(1)).default([]),
2378
+ minContextLength: z7.int().nonnegative().optional(),
694
2379
  maxPromptUsdPerMillion: Usd2.optional(),
695
2380
  maxCompletionUsdPerMillion: Usd2.optional(),
696
- requireLiveEndpoint: z6.boolean().default(false)
2381
+ requireLiveEndpoint: z7.boolean().default(false)
697
2382
  });
698
- var OpenRouterAdmissionReasonSchema = z6.enum([
2383
+ var OpenRouterAdmissionReasonSchema = z7.enum([
699
2384
  "floating-alias",
700
2385
  "unknown-model",
701
2386
  "stale-snapshot",
702
2387
  "missing-parameter",
703
2388
  "missing-modality",
2389
+ "context-unknown",
704
2390
  "context-too-small",
705
2391
  "price-unknown",
706
2392
  "over-price",
707
2393
  "no-live-endpoint",
708
2394
  "endpoints-unknown"
709
2395
  ]);
710
- var OpenRouterModelAdmissionSchema = z6.discriminatedUnion("state", [
711
- z6.strictObject({ state: z6.literal("admitted") }),
712
- z6.strictObject({
713
- state: z6.literal("unverified"),
2396
+ var OpenRouterModelAdmissionSchema = z7.discriminatedUnion("state", [
2397
+ z7.strictObject({ state: z7.literal("admitted") }),
2398
+ z7.strictObject({
2399
+ state: z7.literal("unverified"),
714
2400
  reason: OpenRouterAdmissionReasonSchema,
715
- detail: z6.string()
2401
+ detail: z7.string()
716
2402
  }),
717
- z6.strictObject({
718
- state: z6.literal("rejected"),
2403
+ z7.strictObject({
2404
+ state: z7.literal("rejected"),
719
2405
  reason: OpenRouterAdmissionReasonSchema,
720
- detail: z6.string()
2406
+ detail: z7.string()
721
2407
  })
722
2408
  ]);
723
2409
  function floatingAlias(modelId) {
@@ -733,26 +2419,63 @@ function floatingAlias(modelId) {
733
2419
  return "a `stealth/` model has no stated identity";
734
2420
  return;
735
2421
  }
2422
+ function highestObservedPrice(model, side) {
2423
+ const values = [];
2424
+ const add = (value) => {
2425
+ if (value !== undefined)
2426
+ values.push(value);
2427
+ };
2428
+ if (side === "prompt") {
2429
+ add(model.promptUsdPerMillion);
2430
+ add(model.cacheWriteUsdPerMillion);
2431
+ add(model.cacheWrite1hUsdPerMillion);
2432
+ for (const tier of model.pricingTiers ?? []) {
2433
+ add(tier.promptUsdPerMillion);
2434
+ add(tier.cacheWriteUsdPerMillion);
2435
+ add(tier.cacheWrite1hUsdPerMillion);
2436
+ }
2437
+ add(model.conditionalPricingCeiling?.promptUsdPerMillion);
2438
+ add(model.conditionalPricingCeiling?.cacheWriteUsdPerMillion);
2439
+ add(model.conditionalPricingCeiling?.cacheWrite1hUsdPerMillion);
2440
+ } else {
2441
+ add(model.completionUsdPerMillion);
2442
+ for (const tier of model.pricingTiers ?? [])
2443
+ add(tier.completionUsdPerMillion);
2444
+ add(model.conditionalPricingCeiling?.completionUsdPerMillion);
2445
+ }
2446
+ return values.length > 0 ? Math.max(...values) : undefined;
2447
+ }
736
2448
  function priceCheck(model, policy) {
2449
+ const ceiling = resolveOpenRouterModelCeiling(model);
737
2450
  let unknown;
738
- for (const [limit, price, side] of [
739
- [policy.maxPromptUsdPerMillion, model.promptUsdPerMillion, "prompt"],
740
- [policy.maxCompletionUsdPerMillion, model.completionUsdPerMillion, "completion"]
741
- ]) {
2451
+ const checks = [
2452
+ [policy.maxPromptUsdPerMillion, ceiling.promptUsdPerMillion, "prompt"],
2453
+ [policy.maxCompletionUsdPerMillion, ceiling.completionUsdPerMillion, "completion"]
2454
+ ];
2455
+ for (const [limit, ceilingPrice, side] of checks) {
742
2456
  if (limit === undefined)
743
2457
  continue;
744
- if (price === undefined)
2458
+ const observed = highestObservedPrice(model, side);
2459
+ if (observed !== undefined && observed > limit) {
2460
+ return {
2461
+ state: "rejected",
2462
+ reason: "over-price",
2463
+ detail: `the ${side} price ${observed} USD per million exceeds ${limit}`
2464
+ };
2465
+ }
2466
+ if (ceilingPrice === undefined) {
745
2467
  unknown ??= {
746
2468
  state: "unverified",
747
2469
  reason: "price-unknown",
748
- detail: `the ${side} price is not stated`
2470
+ detail: `the ${side} price ceiling is not stated`
749
2471
  };
750
- else if (price > limit)
2472
+ } else if (ceilingPrice > limit) {
751
2473
  return {
752
2474
  state: "rejected",
753
2475
  reason: "over-price",
754
- detail: `the ${side} price ${price} USD per million exceeds ${limit}`
2476
+ detail: `the ${side} price ${ceilingPrice} USD per million exceeds ${limit}`
755
2477
  };
2478
+ }
756
2479
  }
757
2480
  return unknown;
758
2481
  }
@@ -782,6 +2505,12 @@ function evaluateOpenRouterModelAdmission(input) {
782
2505
  reason: "floating-alias",
783
2506
  detail: `${model.id} stands for ${model.aliasOf}`
784
2507
  };
2508
+ if (model.aliasTarget)
2509
+ return {
2510
+ state: "rejected",
2511
+ reason: "floating-alias",
2512
+ detail: `${model.id} aliases ${model.aliasTarget.id}`
2513
+ };
785
2514
  const missing = policy.requiredParameters.filter((name) => !model.supportedParameters.includes(name));
786
2515
  if (missing.length > 0)
787
2516
  return {
@@ -796,12 +2525,21 @@ function evaluateOpenRouterModelAdmission(input) {
796
2525
  reason: "missing-modality",
797
2526
  detail: `does not accept ${modalities.join(", ")} input`
798
2527
  };
799
- if (policy.minContextLength !== undefined && model.contextLength < policy.minContextLength)
800
- return {
801
- state: "rejected",
802
- reason: "context-too-small",
803
- detail: `context ${model.contextLength} is under ${policy.minContextLength}`
804
- };
2528
+ if (policy.minContextLength !== undefined) {
2529
+ const contextLength = effectiveContextLength(model);
2530
+ if (contextLength === undefined)
2531
+ return {
2532
+ state: "unverified",
2533
+ reason: "context-unknown",
2534
+ detail: "the context length is not stated"
2535
+ };
2536
+ if (contextLength < policy.minContextLength)
2537
+ return {
2538
+ state: "rejected",
2539
+ reason: "context-too-small",
2540
+ detail: `context ${contextLength} is under ${policy.minContextLength}`
2541
+ };
2542
+ }
805
2543
  const price = priceCheck(model, policy);
806
2544
  if (price)
807
2545
  return price;
@@ -817,8 +2555,244 @@ function evaluateOpenRouterModelAdmission(input) {
817
2555
  }
818
2556
  return { state: "admitted" };
819
2557
  }
2558
+ // src/agent-runtime/openrouter-catalog-cache.ts
2559
+ var DEFAULT_TIMEOUT_MS = 1e4;
2560
+ var DEFAULT_FRESH_MS = 15 * 60000;
2561
+ var DEFAULT_RETRY_BACKOFF_MS = 60000;
2562
+ var DEFAULT_CONCURRENCY = 4;
2563
+ async function waitForCatalogFlight(flight, signal, onOrphanCancel) {
2564
+ flight.waiters += 1;
2565
+ let released = false;
2566
+ const detach = (cancelReason) => {
2567
+ if (released)
2568
+ return;
2569
+ released = true;
2570
+ flight.waiters -= 1;
2571
+ if (flight.waiters === 0 && cancelReason !== undefined) {
2572
+ onOrphanCancel(flight, cancelReason);
2573
+ }
2574
+ };
2575
+ if (!signal) {
2576
+ try {
2577
+ return await flight.promise;
2578
+ } finally {
2579
+ detach();
2580
+ }
2581
+ }
2582
+ const onAbort = () => {
2583
+ detach(abortReason(signal));
2584
+ };
2585
+ signal.addEventListener("abort", onAbort, { once: true });
2586
+ try {
2587
+ return await raceAbort(flight.promise, signal);
2588
+ } finally {
2589
+ signal.removeEventListener("abort", onAbort);
2590
+ detach();
2591
+ }
2592
+ }
2593
+ async function readStoredSnapshot(store, notifyError) {
2594
+ try {
2595
+ const raw = await store.read();
2596
+ if (raw === null || raw === undefined)
2597
+ return null;
2598
+ const parsed = OpenRouterCatalogSnapshotSchema.safeParse(raw);
2599
+ if (parsed.success)
2600
+ return parsed.data;
2601
+ notifyError(parsed.error);
2602
+ return null;
2603
+ } catch (error) {
2604
+ notifyError(error);
2605
+ return null;
2606
+ }
2607
+ }
2608
+ function validateCacheOptions(options) {
2609
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
2610
+ const freshMs = options.freshMs ?? DEFAULT_FRESH_MS;
2611
+ const retryBackoffMs = options.retryBackoffMs ?? DEFAULT_RETRY_BACKOFF_MS;
2612
+ const concurrency = options.concurrency ?? DEFAULT_CONCURRENCY;
2613
+ assertTimerMs("timeoutMs", timeoutMs, { absent: "refused" });
2614
+ assertTimerMs("freshMs", freshMs, { absent: "refused" });
2615
+ assertTimerMs("retryBackoffMs", retryBackoffMs, { absent: "refused" });
2616
+ if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > 16) {
2617
+ throw new RangeError("concurrency must be an integer from 1 to 16");
2618
+ }
2619
+ if (options.maxResponseBytes !== undefined) {
2620
+ assertPositiveSafeInteger("maxResponseBytes", options.maxResponseBytes, RangeError);
2621
+ }
2622
+ assertValidStaticOpenRouterApiKey(options.apiKey);
2623
+ assertValidOpenRouterEndpointsFor(options.endpointsFor);
2624
+ return {
2625
+ timeoutMs,
2626
+ freshMs,
2627
+ retryBackoffMs,
2628
+ concurrency,
2629
+ ...options.endpointsFor !== undefined && { endpointsFor: [...options.endpointsFor] }
2630
+ };
2631
+ }
2632
+ function createOpenRouterCatalogCache(options = {}) {
2633
+ const { timeoutMs, freshMs, retryBackoffMs, concurrency, endpointsFor } = validateCacheOptions(options);
2634
+ const now = options.now ?? (() => new Date);
2635
+ let snapshot = null;
2636
+ let hasLastError = false;
2637
+ let lastError;
2638
+ let nextRetryAtMs = null;
2639
+ let hydrated = false;
2640
+ let hydrationPromise = null;
2641
+ let inFlight = null;
2642
+ let latestGeneration = 0;
2643
+ let committedGeneration = 0;
2644
+ let writeChain = Promise.resolve();
2645
+ const notifyError = (error) => {
2646
+ try {
2647
+ options.onError?.(error);
2648
+ } catch {}
2649
+ };
2650
+ const isSnapshotFresh = (candidate, nowMs) => {
2651
+ const ageMs = nowMs - Date.parse(candidate.observedAt);
2652
+ return ageMs >= 0 && ageMs < freshMs;
2653
+ };
2654
+ const buildResult = (forceCurrent = false) => {
2655
+ if (snapshot === null) {
2656
+ return {
2657
+ status: "unavailable",
2658
+ observedAt: null,
2659
+ snapshot: null,
2660
+ models: [],
2661
+ ...hasLastError && { lastError }
2662
+ };
2663
+ }
2664
+ const current = forceCurrent || !hasLastError && isSnapshotFresh(snapshot, now().getTime());
2665
+ return current ? {
2666
+ status: "current",
2667
+ observedAt: snapshot.observedAt,
2668
+ snapshot,
2669
+ models: snapshot.models
2670
+ } : {
2671
+ status: "stale",
2672
+ observedAt: snapshot.observedAt,
2673
+ snapshot,
2674
+ models: snapshot.models,
2675
+ ...hasLastError && { lastError }
2676
+ };
2677
+ };
2678
+ const ensureHydrated = (signal) => {
2679
+ if (hydrated)
2680
+ return Promise.resolve();
2681
+ const store = options.store;
2682
+ if (!store) {
2683
+ hydrated = true;
2684
+ return Promise.resolve();
2685
+ }
2686
+ hydrationPromise ??= readStoredSnapshot(store, notifyError).then((loaded) => {
2687
+ if (loaded !== null && snapshot === null)
2688
+ snapshot = loaded;
2689
+ }).finally(() => {
2690
+ hydrated = true;
2691
+ hydrationPromise = null;
2692
+ });
2693
+ return signal ? raceAbort(hydrationPromise, signal) : hydrationPromise;
2694
+ };
2695
+ const persistSnapshot = (generation, loaded) => {
2696
+ const store = options.store;
2697
+ if (!store)
2698
+ return Promise.resolve();
2699
+ const writeStep = writeChain.then(async () => {
2700
+ if (generation < committedGeneration)
2701
+ return;
2702
+ try {
2703
+ await store.write(loaded);
2704
+ } catch (storeError) {
2705
+ notifyError(storeError);
2706
+ }
2707
+ });
2708
+ writeChain = writeStep;
2709
+ return writeStep;
2710
+ };
2711
+ const startFlight = () => {
2712
+ latestGeneration += 1;
2713
+ const generation = latestGeneration;
2714
+ const controller = new AbortController;
2715
+ const flight = {
2716
+ controller,
2717
+ waiters: 0,
2718
+ promise: Promise.resolve().then(async () => {
2719
+ try {
2720
+ const loaded = await loadOpenRouterCatalogSnapshot({
2721
+ ...options,
2722
+ timeoutMs,
2723
+ concurrency,
2724
+ ...endpointsFor !== undefined && { endpointsFor },
2725
+ signal: controller.signal,
2726
+ now
2727
+ });
2728
+ if (controller.signal.aborted || generation < committedGeneration) {
2729
+ return { succeeded: false };
2730
+ }
2731
+ committedGeneration = generation;
2732
+ snapshot = loaded;
2733
+ hasLastError = false;
2734
+ lastError = undefined;
2735
+ nextRetryAtMs = null;
2736
+ await persistSnapshot(generation, loaded);
2737
+ return { succeeded: true };
2738
+ } catch (error) {
2739
+ if (!controller.signal.aborted && generation >= committedGeneration) {
2740
+ hasLastError = true;
2741
+ lastError = error;
2742
+ nextRetryAtMs = now().getTime() + retryBackoffMs;
2743
+ notifyError(error);
2744
+ }
2745
+ return { succeeded: false };
2746
+ } finally {
2747
+ if (inFlight === flight)
2748
+ inFlight = null;
2749
+ }
2750
+ })
2751
+ };
2752
+ inFlight = flight;
2753
+ return flight;
2754
+ };
2755
+ const cancelOrphanedFlight = (flight, reason) => {
2756
+ if (inFlight === flight)
2757
+ inFlight = null;
2758
+ flight.controller.abort(reason);
2759
+ };
2760
+ const read = async (input = {}) => {
2761
+ if (input.signal?.aborted)
2762
+ throw abortReason(input.signal);
2763
+ await ensureHydrated(input.signal);
2764
+ if (input.signal?.aborted)
2765
+ throw abortReason(input.signal);
2766
+ const forceRefresh = input.forceRefresh === true;
2767
+ const nowMs = now().getTime();
2768
+ if (!forceRefresh) {
2769
+ if (snapshot !== null && !hasLastError && isSnapshotFresh(snapshot, nowMs)) {
2770
+ return buildResult();
2771
+ }
2772
+ if (inFlight === null && nextRetryAtMs !== null && nowMs < nextRetryAtMs) {
2773
+ return buildResult();
2774
+ }
2775
+ }
2776
+ const flight = inFlight ?? startFlight();
2777
+ const outcome = await waitForCatalogFlight(flight, input.signal, cancelOrphanedFlight);
2778
+ return buildResult(outcome.succeeded);
2779
+ };
2780
+ return {
2781
+ read,
2782
+ refresh: (input) => read({ ...input, forceRefresh: true }),
2783
+ async getModel(idOrSlug, input) {
2784
+ const result = await read(input);
2785
+ return result.status !== "unavailable" ? findOpenRouterModel(result.snapshot, idOrSlug) : undefined;
2786
+ },
2787
+ async listModels(filter, input) {
2788
+ validateOpenRouterModelFilter(filter);
2789
+ const result = await read(input);
2790
+ return result.status !== "unavailable" ? listOpenRouterModels(result.snapshot, filter) : [];
2791
+ }
2792
+ };
2793
+ }
820
2794
  // src/agent-runtime/openrouter-spend.ts
821
- import { z as z7 } from "zod";
2795
+ import { z as z8 } from "zod";
822
2796
  function openRouterSpendProvider(options) {
823
2797
  return {
824
2798
  name: "openrouter",
@@ -827,14 +2801,14 @@ function openRouterSpendProvider(options) {
827
2801
  facts: openAiCompatibleUsage2
828
2802
  };
829
2803
  }
830
- var GenerationSchema = z7.object({
831
- data: z7.object({
832
- total_cost: z7.number().nonnegative().finite().nullish(),
833
- provider_name: z7.string().min(1).nullish(),
834
- model: z7.string().min(1).nullish(),
835
- native_tokens_prompt: z7.int().nonnegative().nullish(),
836
- native_tokens_completion: z7.int().nonnegative().nullish(),
837
- native_tokens_reasoning: z7.int().nonnegative().nullish()
2804
+ var GenerationSchema = z8.object({
2805
+ data: z8.object({
2806
+ total_cost: z8.number().nonnegative().nullish(),
2807
+ provider_name: z8.string().min(1).nullish(),
2808
+ model: z8.string().min(1).nullish(),
2809
+ native_tokens_prompt: z8.int().nonnegative().nullish(),
2810
+ native_tokens_completion: z8.int().nonnegative().nullish(),
2811
+ native_tokens_reasoning: z8.int().nonnegative().nullish()
838
2812
  }).loose()
839
2813
  });
840
2814
  function createOpenRouterSpendReconciler(options) {
@@ -879,22 +2853,32 @@ export {
879
2853
  OpenRouterAdmissionReasonSchema,
880
2854
  OpenRouterCatalogSnapshotSchema,
881
2855
  OpenRouterEndpointSchema,
2856
+ OpenRouterEndpointSummarySchema,
882
2857
  OpenRouterHttpError,
883
2858
  OpenRouterMaxPriceSchema,
884
2859
  OpenRouterModelAdmissionSchema,
2860
+ OpenRouterModelAliasTargetSchema,
2861
+ OpenRouterModelPricingCeilingSchema,
2862
+ OpenRouterModelReasoningMetaSchema,
2863
+ OpenRouterPricingTierSchema,
885
2864
  OpenRouterProviderRoutingSchema,
886
2865
  OpenRouterReasoningEffortSchema,
887
2866
  OpenRouterRequestPolicySchema,
888
2867
  OpenRouterRoutePinSchema,
889
2868
  OpenRouterSnapshotModelSchema,
890
2869
  createMemoryOpenRouterRouteStore,
2870
+ createOpenRouterCatalogCache,
891
2871
  createOpenRouterRouteResolver,
892
2872
  createOpenRouterSpendReconciler,
893
2873
  evaluateOpenRouterModelAdmission,
894
2874
  fetchOpenRouterModelEndpoints,
2875
+ findOpenRouterModel,
2876
+ listOpenRouterModels,
895
2877
  loadOpenRouterCatalogSnapshot,
896
2878
  normalizeOpenRouterUsage,
897
2879
  openRouterModelCatalog,
898
2880
  openRouterProvider,
899
- openRouterSpendProvider
2881
+ openRouterSpendProvider,
2882
+ resolveOpenRouterModelCeiling,
2883
+ summarizeOpenRouterEndpoints
900
2884
  };