stitchkit 0.135.0 → 0.136.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +117 -0
- package/README.md +25 -11
- package/dist/agent-executor/acp/v1-session-build.d.ts +51 -0
- package/dist/agent-executor/acp/v1-session-build.d.ts.map +1 -0
- package/dist/agent-executor/acp/v1-session.d.ts +1 -1
- package/dist/agent-executor/acp/v1-session.d.ts.map +1 -1
- package/dist/agent-executor/claude/classify.d.ts +1 -1
- package/dist/agent-executor/claude/classify.d.ts.map +1 -1
- package/dist/agent-executor/claude/events-wire.d.ts +13 -0
- package/dist/agent-executor/claude/events-wire.d.ts.map +1 -0
- package/dist/agent-executor/claude/events.d.ts +1 -11
- package/dist/agent-executor/claude/events.d.ts.map +1 -1
- package/dist/agent-executor/codex/protocol.d.ts +0 -143
- package/dist/agent-executor/codex/protocol.d.ts.map +1 -1
- package/dist/agent-executor/codex/request-answers.d.ts +1 -1
- package/dist/agent-executor/codex/request-answers.d.ts.map +1 -1
- package/dist/agent-executor/codex/server-requests.d.ts +150 -0
- package/dist/agent-executor/codex/server-requests.d.ts.map +1 -0
- package/dist/agent-executor/image-input.d.ts +10 -3
- package/dist/agent-executor/image-input.d.ts.map +1 -1
- package/dist/agent-executor/testing/replay-scenarios.d.ts.map +1 -1
- package/dist/agent-executor/testing/replay-transcript.d.ts.map +1 -1
- package/dist/agent-runtime/browser/browser-control-contract.d.ts +4 -0
- package/dist/agent-runtime/browser/browser-control-contract.d.ts.map +1 -1
- package/dist/agent-runtime/browser/control-schema.d.ts +4 -0
- package/dist/agent-runtime/browser/control-schema.d.ts.map +1 -1
- package/dist/agent-runtime/browser/control-view.d.ts.map +1 -1
- package/dist/agent-runtime/event-schema.d.ts +16 -3
- package/dist/agent-runtime/event-schema.d.ts.map +1 -1
- package/dist/agent-runtime/loop/deferred-tools.d.ts.map +1 -1
- package/dist/agent-runtime/loop/invocation-payload.d.ts.map +1 -1
- package/dist/agent-runtime/loop/invocation-stream.d.ts +9 -1
- package/dist/agent-runtime/loop/invocation-stream.d.ts.map +1 -1
- package/dist/agent-runtime/loop/provider-stream-parts.d.ts +6 -0
- package/dist/agent-runtime/loop/provider-stream-parts.d.ts.map +1 -1
- package/dist/agent-runtime/loop/provider-stream-segments.d.ts +1 -1
- package/dist/agent-runtime/loop/provider-stream-segments.d.ts.map +1 -1
- package/dist/agent-runtime/loop/run-acquisition.d.ts.map +1 -1
- package/dist/agent-runtime/loop/run-approval-signature.d.ts +34 -0
- package/dist/agent-runtime/loop/run-approval-signature.d.ts.map +1 -0
- package/dist/agent-runtime/loop/run-approval.d.ts +0 -28
- package/dist/agent-runtime/loop/run-approval.d.ts.map +1 -1
- package/dist/agent-runtime/loop/run-complete-port.d.ts +24 -0
- package/dist/agent-runtime/loop/run-complete-port.d.ts.map +1 -0
- package/dist/agent-runtime/loop/run-complete-stream.d.ts +7 -2
- package/dist/agent-runtime/loop/run-complete-stream.d.ts.map +1 -1
- package/dist/agent-runtime/loop/run-complete-types.d.ts +14 -1
- package/dist/agent-runtime/loop/run-complete-types.d.ts.map +1 -1
- package/dist/agent-runtime/loop/run-complete.d.ts +2 -2
- package/dist/agent-runtime/loop/run-complete.d.ts.map +1 -1
- package/dist/agent-runtime/loop/run-execution-state.d.ts +8 -0
- package/dist/agent-runtime/loop/run-execution-state.d.ts.map +1 -1
- package/dist/agent-runtime/loop/run-model-call.d.ts +44 -0
- package/dist/agent-runtime/loop/run-model-call.d.ts.map +1 -0
- package/dist/agent-runtime/loop/run-model-step.d.ts +25 -28
- package/dist/agent-runtime/loop/run-model-step.d.ts.map +1 -1
- package/dist/agent-runtime/loop/run-model-steps.d.ts +6 -0
- package/dist/agent-runtime/loop/run-model-steps.d.ts.map +1 -0
- package/dist/agent-runtime/loop/run-model-stream.d.ts +3 -1
- package/dist/agent-runtime/loop/run-model-stream.d.ts.map +1 -1
- package/dist/agent-runtime/loop/run-operation-lifecycle.d.ts +0 -2
- package/dist/agent-runtime/loop/run-operation-lifecycle.d.ts.map +1 -1
- package/dist/agent-runtime/loop/run-step-loop.d.ts +19 -0
- package/dist/agent-runtime/loop/run-step-loop.d.ts.map +1 -0
- package/dist/agent-runtime/loop/run-step-port.d.ts +175 -0
- package/dist/agent-runtime/loop/run-step-port.d.ts.map +1 -0
- package/dist/agent-runtime/loop/run-stream-parts.d.ts.map +1 -1
- package/dist/agent-runtime/loop/run-stream-step-text.d.ts.map +1 -1
- package/dist/agent-runtime/loop/run-tool-approval-flow.d.ts +2 -1
- package/dist/agent-runtime/loop/run-tool-approval-flow.d.ts.map +1 -1
- package/dist/agent-runtime/loop/run-tool-call-input.d.ts +39 -0
- package/dist/agent-runtime/loop/run-tool-call-input.d.ts.map +1 -0
- package/dist/agent-runtime/loop/run-tool-call.d.ts +2 -31
- package/dist/agent-runtime/loop/run-tool-call.d.ts.map +1 -1
- package/dist/agent-runtime/loop/run-tool-errors.d.ts +5 -0
- package/dist/agent-runtime/loop/run-tool-errors.d.ts.map +1 -1
- package/dist/agent-runtime/loop/run-tool-executor.d.ts +1 -1
- package/dist/agent-runtime/loop/run-tool-executor.d.ts.map +1 -1
- package/dist/agent-runtime/loop/run-tool-slots.d.ts +2 -1
- package/dist/agent-runtime/loop/run-tool-slots.d.ts.map +1 -1
- package/dist/agent-runtime/loop/runtime-state.d.ts.map +1 -1
- package/dist/agent-runtime/loop/runtime.d.ts +0 -5
- package/dist/agent-runtime/loop/runtime.d.ts.map +1 -1
- package/dist/agent-runtime/providers/ai-sdk-convert.d.ts +1 -5
- package/dist/agent-runtime/providers/ai-sdk-convert.d.ts.map +1 -1
- package/dist/agent-runtime/providers/ai-sdk-normalize.d.ts +11 -0
- package/dist/agent-runtime/providers/ai-sdk-normalize.d.ts.map +1 -0
- package/dist/agent-runtime/providers/ai-sdk-tools.d.ts +11 -0
- package/dist/agent-runtime/providers/ai-sdk-tools.d.ts.map +1 -0
- package/dist/agent-runtime/providers/ai-sdk.d.ts +1 -9
- package/dist/agent-runtime/providers/ai-sdk.d.ts.map +1 -1
- package/dist/agent-runtime/providers/anthropic-sse.d.ts.map +1 -1
- package/dist/agent-runtime/providers/openrouter-admission.d.ts.map +1 -1
- package/dist/agent-runtime/providers/openrouter-audio.d.ts +164 -0
- package/dist/agent-runtime/providers/openrouter-audio.d.ts.map +1 -0
- package/dist/agent-runtime/providers/openrouter-catalog-cache.d.ts.map +1 -1
- package/dist/agent-runtime/providers/openrouter-catalog-query.d.ts.map +1 -1
- package/dist/agent-runtime/providers/openrouter-catalog.d.ts +4 -2
- package/dist/agent-runtime/providers/openrouter-catalog.d.ts.map +1 -1
- package/dist/agent-runtime/providers/openrouter-client.d.ts +37 -0
- package/dist/agent-runtime/providers/openrouter-client.d.ts.map +1 -0
- package/dist/agent-runtime/providers/openrouter-http.d.ts +120 -0
- package/dist/agent-runtime/providers/openrouter-http.d.ts.map +1 -0
- package/dist/agent-runtime/providers/openrouter-media.d.ts +174 -0
- package/dist/agent-runtime/providers/openrouter-media.d.ts.map +1 -0
- package/dist/agent-runtime/providers/openrouter-models.d.ts +2 -23
- package/dist/agent-runtime/providers/openrouter-models.d.ts.map +1 -1
- package/dist/agent-runtime/providers/openrouter-options.d.ts +4 -0
- package/dist/agent-runtime/providers/openrouter-options.d.ts.map +1 -1
- package/dist/agent-runtime/providers/openrouter-request.d.ts +23 -0
- package/dist/agent-runtime/providers/openrouter-request.d.ts.map +1 -0
- package/dist/agent-runtime/providers/openrouter-response.d.ts.map +1 -1
- package/dist/agent-runtime/providers/openrouter-retrieval.d.ts +145 -0
- package/dist/agent-runtime/providers/openrouter-retrieval.d.ts.map +1 -0
- package/dist/agent-runtime/providers/openrouter-speech.d.ts +90 -0
- package/dist/agent-runtime/providers/openrouter-speech.d.ts.map +1 -0
- package/dist/agent-runtime/providers/openrouter-spend.d.ts +7 -3
- package/dist/agent-runtime/providers/openrouter-spend.d.ts.map +1 -1
- package/dist/agent-runtime/providers/openrouter-stream.d.ts +29 -0
- package/dist/agent-runtime/providers/openrouter-stream.d.ts.map +1 -0
- package/dist/agent-runtime/providers/openrouter-systemone.d.ts +137 -0
- package/dist/agent-runtime/providers/openrouter-systemone.d.ts.map +1 -0
- package/dist/agent-runtime/providers/openrouter-url.d.ts +19 -0
- package/dist/agent-runtime/providers/openrouter-url.d.ts.map +1 -0
- package/dist/agent-runtime/providers/openrouter-wire.d.ts +45 -0
- package/dist/agent-runtime/providers/openrouter-wire.d.ts.map +1 -0
- package/dist/agent-runtime/providers/openrouter.d.ts +5 -4
- package/dist/agent-runtime/providers/openrouter.d.ts.map +1 -1
- package/dist/agent-runtime/providers/provider-http.d.ts +29 -3
- package/dist/agent-runtime/providers/provider-http.d.ts.map +1 -1
- package/dist/agent-runtime/providers/provider-json-schema-strip.d.ts.map +1 -1
- package/dist/agent-runtime/providers/provider-json-schema.d.ts.map +1 -1
- package/dist/agent-runtime/providers/provider-openai-chat-sse.d.ts.map +1 -1
- package/dist/agent-runtime/providers/provider-openai-chat-state.d.ts +42 -0
- package/dist/agent-runtime/providers/provider-openai-chat-state.d.ts.map +1 -0
- package/dist/agent-runtime/providers/provider-usage.d.ts +9 -0
- package/dist/agent-runtime/providers/provider-usage.d.ts.map +1 -1
- package/dist/agent-runtime/sandbox/sandbox-bubblewrap-args.d.ts +9 -0
- package/dist/agent-runtime/sandbox/sandbox-bubblewrap-args.d.ts.map +1 -1
- package/dist/agent-runtime/sandbox/sandbox-bubblewrap.d.ts +6 -0
- package/dist/agent-runtime/sandbox/sandbox-bubblewrap.d.ts.map +1 -1
- package/dist/agent-runtime/sandbox/sandbox-contract.d.ts.map +1 -1
- package/dist/agent-runtime/sandbox/sandbox-process-linux.d.ts.map +1 -1
- package/dist/agent-runtime/sandbox/sandbox-process-spec.d.ts +5 -1
- package/dist/agent-runtime/sandbox/sandbox-process-spec.d.ts.map +1 -1
- package/dist/agent-runtime/sandbox/sandbox-process-wrapper.d.ts.map +1 -1
- package/dist/agent-runtime/stores/branch-messages.d.ts.map +1 -1
- package/dist/agent-runtime/stores/sql-rows.d.ts +10 -10
- package/dist/agent-runtime/terminal-commit.d.ts +10 -10
- package/dist/agent-runtime/testing/fault-bench.d.ts +5 -1
- package/dist/agent-runtime/testing/fault-bench.d.ts.map +1 -1
- package/dist/application/diagnostic-journal-contract.d.ts.map +1 -1
- package/dist/browser/client-executors.d.ts.map +1 -1
- package/dist/browser/client-url.d.ts.map +1 -1
- package/dist/contract/define.d.ts +3 -7
- package/dist/contract/define.d.ts.map +1 -1
- package/dist/contract/normalize.d.ts +17 -5
- package/dist/contract/normalize.d.ts.map +1 -1
- package/dist/entrypoints/agent-executor/acp.js +4 -2
- package/dist/entrypoints/agent-executor/claude-sdk.js +20 -20
- package/dist/entrypoints/agent-executor/claude.js +7 -7
- package/dist/entrypoints/agent-executor/codex.d.ts +2 -1
- package/dist/entrypoints/agent-executor/codex.d.ts.map +1 -1
- package/dist/entrypoints/agent-executor/codex.js +129 -35
- package/dist/entrypoints/agent-executor/testing/claude-sdk.js +2 -2
- package/dist/entrypoints/agent-executor/testing.js +17 -13
- package/dist/entrypoints/agent-executor.js +1 -1
- package/dist/entrypoints/agent-runtime/ai-sdk.d.ts +2 -1
- package/dist/entrypoints/agent-runtime/ai-sdk.d.ts.map +1 -1
- package/dist/entrypoints/agent-runtime/ai-sdk.js +10 -12
- package/dist/entrypoints/agent-runtime/anthropic.js +13 -10
- package/dist/entrypoints/agent-runtime/browser.js +8 -4
- package/dist/entrypoints/agent-runtime/harness.js +18 -19
- package/dist/entrypoints/agent-runtime/openai.js +5 -5
- package/dist/entrypoints/agent-runtime/openrouter.d.ts +11 -2
- package/dist/entrypoints/agent-runtime/openrouter.d.ts.map +1 -1
- package/dist/entrypoints/agent-runtime/openrouter.js +1940 -496
- package/dist/entrypoints/agent-runtime/postgres.js +2 -2
- package/dist/entrypoints/agent-runtime/realtime.js +5 -5
- package/dist/entrypoints/agent-runtime/sandbox.js +167 -139
- package/dist/entrypoints/agent-runtime/sqlite/bun.js +3 -3
- package/dist/entrypoints/agent-runtime/sqlite/node.js +3 -3
- package/dist/entrypoints/agent-runtime/testing.js +3 -3
- package/dist/entrypoints/agent-runtime.js +246 -360
- package/dist/entrypoints/application.js +2 -2
- package/dist/entrypoints/cli.js +36 -15
- package/dist/entrypoints/contract.js +12 -10
- package/dist/entrypoints/geo.js +1 -1
- package/dist/entrypoints/handler.js +5 -6
- package/dist/entrypoints/http.d.ts +2 -0
- package/dist/entrypoints/http.d.ts.map +1 -1
- package/dist/entrypoints/http.js +16 -4
- package/dist/entrypoints/index.js +26 -35
- package/dist/entrypoints/live.js +3 -3
- package/dist/entrypoints/node.js +7 -7
- package/dist/entrypoints/observability.js +9 -7
- package/dist/entrypoints/process.js +3 -3
- package/dist/entrypoints/remote.js +5 -5
- package/dist/entrypoints/server.js +29 -16
- package/dist/entrypoints/telegram/grammy.d.ts +1 -1
- package/dist/entrypoints/telegram/grammy.d.ts.map +1 -1
- package/dist/entrypoints/telegram/grammy.js +39 -5
- package/dist/entrypoints/telegram/screens.js +3 -0
- package/dist/entrypoints/telegram.d.ts +1 -1
- package/dist/entrypoints/telegram.d.ts.map +1 -1
- package/dist/entrypoints/telegram.js +19 -6
- package/dist/entrypoints/testing.js +10 -11
- package/dist/entrypoints/tools/agent.js +8 -9
- package/dist/entrypoints/tools/connections.js +27 -57
- package/dist/entrypoints/tools/contract.js +4 -4
- package/dist/entrypoints/tools/invoker.js +7 -8
- package/dist/entrypoints/tools/mcp.js +9 -10
- package/dist/entrypoints/tools/toolkit.js +11 -12
- package/dist/entrypoints/tools.js +20 -20
- package/dist/entrypoints/tracking/contract.js +1 -1
- package/dist/entrypoints/tracking/performance.js +1 -1
- package/dist/entrypoints/tracking.js +1 -1
- package/dist/{index-3czc3ykr.js → index-08a3qfr8.js} +1 -1
- package/dist/{index-grhhsrd5.js → index-1en7k3q5.js} +2 -1
- package/dist/{index-pdcbjd6a.js → index-1yky29qg.js} +6 -3
- package/dist/{index-b4c9dpzm.js → index-252den5a.js} +10 -11
- package/dist/{index-xtby8rj3.js → index-28kbdn63.js} +5 -47
- package/dist/{index-57sbckhv.js → index-36mtj8xm.js} +2 -2
- package/dist/{index-dm84tsd5.js → index-3kb8dw48.js} +1 -1
- package/dist/index-3tb82xr7.js +11 -0
- package/dist/{index-c24bj2r1.js → index-4243301z.js} +2 -2
- package/dist/{index-nr4fhfn4.js → index-4p2zx593.js} +2 -0
- package/dist/{index-q86qnzzf.js → index-54wp467c.js} +4 -4
- package/dist/{index-mcv7b2n0.js → index-63ctzjp4.js} +497 -495
- package/dist/{index-y0a4gt1s.js → index-65p8v81y.js} +3 -2
- package/dist/{index-z72vazf5.js → index-6y3eae97.js} +27 -83
- package/dist/{index-5awtbyns.js → index-9vj869rx.js} +1 -1
- package/dist/{index-5q0qpw3v.js → index-aqm7e864.js} +23 -8
- package/dist/{index-d4at0q09.js → index-b9mj31q7.js} +90 -88
- package/dist/{index-baba8ehy.js → index-bjrcbcn2.js} +2 -2
- package/dist/{index-fsw9wxk9.js → index-c9j8441q.js} +1 -103
- package/dist/{index-wdb5jhas.js → index-d1pdv8qc.js} +1 -1
- package/dist/{index-73wq9abg.js → index-df5xr2f9.js} +13 -59
- package/dist/{index-n9358ydy.js → index-dm50x3by.js} +1 -1
- package/dist/{index-zyyerdny.js → index-dmrx8xma.js} +3 -0
- package/dist/{index-78da4g74.js → index-dwq6a6sq.js} +17 -13
- package/dist/{index-9be3tf6r.js → index-e413q2cj.js} +49 -22
- package/dist/{index-g4gstmp1.js → index-ednf2cxs.js} +1 -1
- package/dist/{index-84tp547a.js → index-edpkm3k7.js} +29 -97
- package/dist/{index-gs0jw0hy.js → index-efbzm2se.js} +3 -3
- package/dist/{index-de7b0kvz.js → index-epwvp88y.js} +1 -1
- package/dist/{index-asnd4h2k.js → index-f0dzyskg.js} +27 -4
- package/dist/{index-xbb8ysmq.js → index-fatke81t.js} +2 -2
- package/dist/{index-6nzzj7qr.js → index-gq35s3bm.js} +1 -1
- package/dist/index-gvgtmt7a.js +102 -0
- package/dist/{index-m2b49tvc.js → index-h08xqfw9.js} +20 -21
- package/dist/{index-gk6dq9ay.js → index-ha1tv70k.js} +3 -26
- package/dist/{index-wsv11dhg.js → index-hberxns4.js} +1 -1
- package/dist/{index-rkphknhx.js → index-hpzhz1vm.js} +1 -1
- package/dist/{index-npfdymav.js → index-j5vzhj3d.js} +1 -1
- package/dist/{index-d3s070eh.js → index-jperyn0c.js} +1 -1
- package/dist/{index-yhwx4fwk.js → index-kzsetgh9.js} +1 -1
- package/dist/{index-x6sp5vpa.js → index-q4tr9vnf.js} +1 -1
- package/dist/{index-hce3hbdg.js → index-qj0sq69b.js} +6 -2
- package/dist/{index-v0j22shs.js → index-rg08syp1.js} +9 -6
- package/dist/{index-8vzh5wpv.js → index-rw1caff2.js} +14 -26
- package/dist/index-s8af9jqw.js +6 -0
- package/dist/{index-bgj9hbm3.js → index-sdppfbrh.js} +30 -16
- package/dist/{index-y0mwkgkf.js → index-shte29pg.js} +1086 -1055
- package/dist/{index-fec05c9k.js → index-ta0e2daw.js} +9 -7
- package/dist/{index-zfrysr1e.js → index-tb36xawm.js} +110 -75
- package/dist/{index-c0yym4a0.js → index-w7e402wx.js} +11 -105
- package/dist/{index-bvpevwt6.js → index-xnqab06h.js} +207 -202
- package/dist/index-xrbrvn15.js +147 -0
- package/dist/{index-ac3rfec5.js → index-y6wzzk2e.js} +21 -1
- package/dist/{index-3d2c45jn.js → index-yjx5jna7.js} +2 -2
- package/dist/internal/loopback-host.d.ts +8 -0
- package/dist/internal/loopback-host.d.ts.map +1 -0
- package/dist/internal/own-member.d.ts +7 -0
- package/dist/internal/own-member.d.ts.map +1 -0
- package/dist/internal/request.d.ts +17 -8
- package/dist/internal/request.d.ts.map +1 -1
- package/dist/internal/secret-shapes.d.ts +33 -4
- package/dist/internal/secret-shapes.d.ts.map +1 -1
- package/dist/json-schema/dialect.d.ts.map +1 -1
- package/dist/json-schema/keywords.d.ts +25 -6
- package/dist/json-schema/keywords.d.ts.map +1 -1
- package/dist/json-schema/string-format.d.ts.map +1 -1
- package/dist/live/events.d.ts.map +1 -1
- package/dist/live/watch-client.d.ts.map +1 -1
- package/dist/live/watch-delta.d.ts.map +1 -1
- package/dist/observability/context.d.ts +4 -3
- package/dist/observability/context.d.ts.map +1 -1
- package/dist/observability/sanitize.d.ts.map +1 -1
- package/dist/observability/secret-values.d.ts +0 -9
- package/dist/observability/secret-values.d.ts.map +1 -1
- package/dist/server/context.d.ts +3 -2
- package/dist/server/context.d.ts.map +1 -1
- package/dist/server/error-hook.d.ts +4 -3
- package/dist/server/error-hook.d.ts.map +1 -1
- package/dist/server/event-bus.d.ts.map +1 -1
- package/dist/server/file.d.ts +11 -3
- package/dist/server/file.d.ts.map +1 -1
- package/dist/server/handler-state.d.ts +2 -2
- package/dist/server/handler-state.d.ts.map +1 -1
- package/dist/server/middleware/jwt.d.ts +12 -1
- package/dist/server/middleware/jwt.d.ts.map +1 -1
- package/dist/server/middleware/trust-fence.d.ts +4 -0
- package/dist/server/middleware/trust-fence.d.ts.map +1 -1
- package/dist/server/multipart.d.ts +2 -3
- package/dist/server/multipart.d.ts.map +1 -1
- package/dist/server/raw.d.ts.map +1 -1
- package/dist/server/request-body.d.ts +12 -1
- package/dist/server/request-body.d.ts.map +1 -1
- package/dist/server/request-completion.d.ts.map +1 -1
- package/dist/server/types.d.ts +14 -9
- package/dist/server/types.d.ts.map +1 -1
- package/dist/telegram/crypto.d.ts.map +1 -1
- package/dist/telegram/init-data.d.ts +4 -4
- package/dist/telegram/init-data.d.ts.map +1 -1
- package/dist/telegram/outbound-cost.d.ts.map +1 -1
- package/dist/telegram/screens/test-chat.d.ts.map +1 -1
- package/dist/telegram/widget-api.d.ts +85 -13
- package/dist/telegram/widget-api.d.ts.map +1 -1
- package/dist/telegram/widget.d.ts +46 -2
- package/dist/telegram/widget.d.ts.map +1 -1
- package/dist/tools/cli/args-classify.d.ts +4 -74
- package/dist/tools/cli/args-classify.d.ts.map +1 -1
- package/dist/tools/cli/args-framework.d.ts +79 -0
- package/dist/tools/cli/args-framework.d.ts.map +1 -0
- package/dist/tools/cli/args-scan.d.ts.map +1 -1
- package/dist/tools/cli/args-tokens.d.ts.map +1 -1
- package/dist/tools/cli/checkpoint.d.ts +5 -0
- package/dist/tools/cli/checkpoint.d.ts.map +1 -1
- package/dist/tools/cli/stream.d.ts.map +1 -1
- package/dist/tools/connections/foreign-schema-join.d.ts.map +1 -1
- package/dist/tools/connections/openapi.d.ts.map +1 -1
- package/dist/tools/connections/runtime.d.ts.map +1 -1
- package/dist/tools/execute-handler.d.ts +24 -0
- package/dist/tools/execute-handler.d.ts.map +1 -0
- package/dist/tools/execute.d.ts.map +1 -1
- package/dist/tools/mcp/round.d.ts.map +1 -1
- package/dist/tools/schema/coerce.d.ts.map +1 -1
- package/dist/tools/schema/flatten.d.ts.map +1 -1
- package/dist/tools/schema/inline-references.d.ts.map +1 -1
- package/dist/tools/schema/nesting-limit.d.ts.map +1 -1
- package/dist/tools/schema/presentation.d.ts.map +1 -1
- package/dist/tracking/privacy.d.ts.map +1 -1
- package/llms/agent-runtime-openrouter.txt +14 -5
- package/llms/agent-runtime-sandbox.txt +50 -11
- package/llms/agent-runtime-testing.txt +1 -1
- package/llms/agent-runtime.2.txt +342 -230
- package/llms/agent-runtime.3.txt +225 -380
- package/llms/agent-runtime.4.txt +387 -158
- package/llms/agent-runtime.5.txt +157 -152
- package/llms/agent-runtime.6.txt +164 -0
- package/llms/agent-runtime.txt +307 -362
- package/llms/application.txt +3 -1
- package/llms/http.txt +1 -1
- package/llms/live.txt +3 -1
- package/llms/observability.txt +16 -9
- package/llms/server.2.txt +13 -8
- package/llms/server.4.txt +23 -11
- package/llms/server.5.txt +5 -5
- package/llms/server.txt +54 -1
- package/llms/spend.txt +18 -1
- package/llms/stitchkit.2.txt +4 -2
- package/llms/stitchkit.txt +113 -93
- package/llms/telegram-grammy.txt +3 -2
- package/llms/telegram.2.txt +3 -1
- package/llms/telegram.txt +35 -10
- package/llms/upgrading-0.128.0-0.129.0.txt +175 -0
- package/llms/{upgrading-0.128.0-0.135.0.txt → upgrading-0.130.0-0.136.0.txt} +353 -169
- package/llms/upgrading.txt +2 -1
- package/llms-full.txt +1035 -208
- package/llms.txt +14 -13
- package/package.json +6 -6
- package/dist/agent-runtime/loop/deferred-tools-internal.d.ts +0 -19
- package/dist/agent-runtime/loop/deferred-tools-internal.d.ts.map +0 -1
- package/dist/agent-runtime/loop/run-complete-retry.d.ts +0 -24
- package/dist/agent-runtime/loop/run-complete-retry.d.ts.map +0 -1
- package/dist/agent-runtime/loop/run-model-attempts.d.ts +0 -6
- package/dist/agent-runtime/loop/run-model-attempts.d.ts.map +0 -1
- package/dist/index-sznqf8fx.js +0 -20
- /package/dist/{index-fthw8dwa.js → index-4gbybjg6.js} +0 -0
|
@@ -2,26 +2,34 @@ import {
|
|
|
2
2
|
AgentModelCatalogSchema2
|
|
3
3
|
} from "../../index-refgnzy0.js";
|
|
4
4
|
import {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
joinProviderUrl,
|
|
10
|
-
assertNoExtraBodyClash,
|
|
11
|
-
resolveProviderApiKey,
|
|
12
|
-
postProviderStream,
|
|
13
|
-
nonEmptyString2,
|
|
14
|
-
recordField,
|
|
5
|
+
NonNegativeInt,
|
|
6
|
+
NonNegativeNum,
|
|
7
|
+
Percentage,
|
|
8
|
+
Probability,
|
|
15
9
|
reportedInt,
|
|
16
10
|
reportedUsd,
|
|
17
11
|
computedUsd,
|
|
18
12
|
nonNegativeNumber,
|
|
19
13
|
buildProviderUsage,
|
|
14
|
+
DEFAULT_MAX_ERROR_BODY_BYTES,
|
|
15
|
+
DEFAULT_MAX_JSON_BODY_BYTES,
|
|
16
|
+
redactProviderFailureText,
|
|
17
|
+
headersToRecord,
|
|
18
|
+
assertNoExtraBodyClash,
|
|
19
|
+
resolveProviderApiKey,
|
|
20
|
+
extractProviderRequestId,
|
|
21
|
+
buildProviderHttpError,
|
|
22
|
+
readProviderStreamResponse,
|
|
23
|
+
nonEmptyString2,
|
|
24
|
+
recordField,
|
|
20
25
|
normalizeProviderHistory,
|
|
21
26
|
historyHasToolTraffic,
|
|
22
27
|
parseSseStream,
|
|
23
28
|
parseSseJson
|
|
24
|
-
} from "../../index-
|
|
29
|
+
} from "../../index-tb36xawm.js";
|
|
30
|
+
import {
|
|
31
|
+
AgentCacheControlSchema2
|
|
32
|
+
} from "../../index-vebzvse6.js";
|
|
25
33
|
import {
|
|
26
34
|
openAiCompatibleUsage2
|
|
27
35
|
} from "../../index-6t4c98gr.js";
|
|
@@ -32,9 +40,12 @@ import {
|
|
|
32
40
|
assertValidCacheTtlOrder,
|
|
33
41
|
budgetCacheBreakpoints
|
|
34
42
|
} from "../../index-ws0awmzq.js";
|
|
43
|
+
import {
|
|
44
|
+
isLoopbackHostname
|
|
45
|
+
} from "../../index-s8af9jqw.js";
|
|
35
46
|
import {
|
|
36
47
|
normalizeOpenAiJsonSchema
|
|
37
|
-
} from "../../index-
|
|
48
|
+
} from "../../index-6y3eae97.js";
|
|
38
49
|
import {
|
|
39
50
|
sanitizeSurrogates,
|
|
40
51
|
deterministicJson,
|
|
@@ -46,14 +57,18 @@ import {
|
|
|
46
57
|
AgentProviderStreamCutError2
|
|
47
58
|
} from "../../index-vse7x1qt.js";
|
|
48
59
|
import {
|
|
49
|
-
|
|
60
|
+
readBoundedChunks,
|
|
61
|
+
concatChunks,
|
|
62
|
+
readBoundedText
|
|
50
63
|
} from "../../index-f16b7rze.js";
|
|
51
64
|
import {
|
|
52
65
|
isPositiveSafeInteger,
|
|
53
|
-
assertPositiveSafeInteger
|
|
66
|
+
assertPositiveSafeInteger,
|
|
67
|
+
assertNonNegativeSafeInteger
|
|
54
68
|
} from "../../index-gr0kxymw.js";
|
|
55
69
|
import {
|
|
56
|
-
assertTimerMs
|
|
70
|
+
assertTimerMs,
|
|
71
|
+
withSignalDeadline
|
|
57
72
|
} from "../../index-e1y74yra.js";
|
|
58
73
|
import {
|
|
59
74
|
abortReason,
|
|
@@ -61,6 +76,9 @@ import {
|
|
|
61
76
|
linkAbortSignals,
|
|
62
77
|
withLinkedAbortSignals
|
|
63
78
|
} from "../../index-rptj3qnc.js";
|
|
79
|
+
import {
|
|
80
|
+
abortError
|
|
81
|
+
} from "../../index-wz392jyz.js";
|
|
64
82
|
import {
|
|
65
83
|
isRecord
|
|
66
84
|
} from "../../index-ps3djm8d.js";
|
|
@@ -195,15 +213,15 @@ var OpenRouterModelSchema = z2.object({
|
|
|
195
213
|
slug: z2.string().min(1),
|
|
196
214
|
name: z2.string().nullish()
|
|
197
215
|
}).loose().nullish(),
|
|
198
|
-
context_length:
|
|
216
|
+
context_length: NonNegativeInt.nullish(),
|
|
199
217
|
architecture: z2.object({
|
|
200
218
|
input_modalities: z2.array(z2.string()).nullish().transform((value) => value ?? []),
|
|
201
219
|
output_modalities: z2.array(z2.string()).nullish(),
|
|
202
220
|
tokenizer: z2.string().nullish()
|
|
203
221
|
}).loose().nullish().transform((value) => value ?? { input_modalities: [] }),
|
|
204
222
|
top_provider: z2.object({
|
|
205
|
-
context_length:
|
|
206
|
-
max_completion_tokens:
|
|
223
|
+
context_length: NonNegativeInt.nullish(),
|
|
224
|
+
max_completion_tokens: NonNegativeInt.nullish()
|
|
207
225
|
}).loose().nullish(),
|
|
208
226
|
reasoning: z2.object({
|
|
209
227
|
supported_efforts: z2.array(z2.string()).nullish(),
|
|
@@ -254,58 +272,6 @@ function withOpenRouterTimeout(timeoutMs, signal, requests) {
|
|
|
254
272
|
assertTimerMs("timeoutMs", timeoutMs, { absent: "refused" });
|
|
255
273
|
return withLinkedAbortSignals(signal, AbortSignal.timeout(timeoutMs), requests);
|
|
256
274
|
}
|
|
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
|
-
}
|
|
277
|
-
async function openRouterJson(input) {
|
|
278
|
-
input.signal.throwIfAborted();
|
|
279
|
-
const apiKey = input.apiKey !== undefined ? await resolveOptionalOpenRouterApiKey(input.apiKey) : undefined;
|
|
280
|
-
input.signal.throwIfAborted();
|
|
281
|
-
const response = await input.fetcher(input.url, {
|
|
282
|
-
...apiKey !== undefined && { headers: { Authorization: `Bearer ${apiKey}` } },
|
|
283
|
-
redirect: "error",
|
|
284
|
-
signal: input.signal
|
|
285
|
-
});
|
|
286
|
-
if (!response.ok) {
|
|
287
|
-
await response.body?.cancel().catch(() => {
|
|
288
|
-
return;
|
|
289
|
-
});
|
|
290
|
-
throw new OpenRouterHttpError(response.status, input.url.pathname);
|
|
291
|
-
}
|
|
292
|
-
const maxBytes = input.maxBytes ?? 16 * 1024 * 1024;
|
|
293
|
-
const bytes = await readBoundedBody2(response.body, {
|
|
294
|
-
maxBytes,
|
|
295
|
-
signal: input.signal,
|
|
296
|
-
limitError: () => new RangeError(`OpenRouter response exceeds ${maxBytes} bytes`)
|
|
297
|
-
});
|
|
298
|
-
return JSON.parse(new TextDecoder().decode(bytes));
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
class OpenRouterHttpError extends Error {
|
|
302
|
-
status;
|
|
303
|
-
constructor(status, path) {
|
|
304
|
-
super(`OpenRouter request ${path} failed with HTTP ${status}`);
|
|
305
|
-
this.status = status;
|
|
306
|
-
this.name = "OpenRouterHttpError";
|
|
307
|
-
}
|
|
308
|
-
}
|
|
309
275
|
var DECIMAL = /^(\d+(?:\.\d+)?)(?:e([+-]?\d+))?$/i;
|
|
310
276
|
function usdPerMillion(perToken) {
|
|
311
277
|
if (perToken === undefined || perToken === null)
|
|
@@ -327,18 +293,18 @@ function usd(value) {
|
|
|
327
293
|
return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;
|
|
328
294
|
}
|
|
329
295
|
var MODEL_ID = /^~?[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._:-]*$/i;
|
|
330
|
-
function
|
|
296
|
+
function openRouterEndpointsPath(modelId) {
|
|
331
297
|
if (!MODEL_ID.test(modelId) || modelId.includes("..")) {
|
|
332
298
|
throw new TypeError(`Not an OpenRouter model id: ${modelId}`);
|
|
333
299
|
}
|
|
334
300
|
const [author = "", slug = ""] = modelId.split("/");
|
|
335
|
-
return
|
|
301
|
+
return `/models/${encodeURIComponent(author)}/${encodeURIComponent(slug)}/endpoints`;
|
|
336
302
|
}
|
|
337
303
|
function assertValidOpenRouterEndpointsFor(endpointsFor) {
|
|
338
304
|
if (endpointsFor === undefined)
|
|
339
305
|
return;
|
|
340
306
|
for (const modelId of endpointsFor) {
|
|
341
|
-
|
|
307
|
+
openRouterEndpointsPath(modelId);
|
|
342
308
|
}
|
|
343
309
|
}
|
|
344
310
|
var PercentileMetricSchema = z2.object({ p50: z2.number().nullish() }).loose().nullish();
|
|
@@ -346,8 +312,8 @@ var OpenRouterEndpointsResponseSchema = z2.object({
|
|
|
346
312
|
data: z2.object({
|
|
347
313
|
endpoints: z2.array(z2.object({
|
|
348
314
|
provider_name: z2.string().min(1),
|
|
349
|
-
context_length:
|
|
350
|
-
max_completion_tokens:
|
|
315
|
+
context_length: NonNegativeInt.nullish(),
|
|
316
|
+
max_completion_tokens: NonNegativeInt.nullish(),
|
|
351
317
|
pricing: z2.object({
|
|
352
318
|
prompt: z2.string().nullish(),
|
|
353
319
|
completion: z2.string().nullish(),
|
|
@@ -500,6 +466,562 @@ function parseOpenRouterWirePricing(pricing) {
|
|
|
500
466
|
};
|
|
501
467
|
}
|
|
502
468
|
|
|
469
|
+
// src/agent-runtime/providers/openrouter-response.ts
|
|
470
|
+
var GENERIC_ERROR_MESSAGES = new Set([
|
|
471
|
+
"OpenRouter request failed",
|
|
472
|
+
"Provider returned error"
|
|
473
|
+
]);
|
|
474
|
+
var EMPTY_RAW_SENTINELS = new Set(["null", "[]", "{}", '""']);
|
|
475
|
+
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;
|
|
476
|
+
var MAX_RAW_SNIPPET_CHARS = 512;
|
|
477
|
+
function readMetadataUsageRecord(metadata) {
|
|
478
|
+
if (!isRecord(metadata))
|
|
479
|
+
return;
|
|
480
|
+
const openrouter = recordField(metadata, "openrouter") ?? metadata;
|
|
481
|
+
return recordField(openrouter, "usage") ?? openrouter;
|
|
482
|
+
}
|
|
483
|
+
function readOpenRouterBaseCost(source, metadata) {
|
|
484
|
+
const direct = nonNegativeNumber(source.cost);
|
|
485
|
+
if (direct !== undefined)
|
|
486
|
+
return direct;
|
|
487
|
+
if (!isRecord(metadata))
|
|
488
|
+
return;
|
|
489
|
+
const openrouter = recordField(metadata, "openrouter") ?? metadata;
|
|
490
|
+
const top = nonNegativeNumber(openrouter.cost);
|
|
491
|
+
if (top !== undefined)
|
|
492
|
+
return top;
|
|
493
|
+
const nestedUsage = recordField(openrouter, "usage");
|
|
494
|
+
return nestedUsage ? nonNegativeNumber(nestedUsage.cost) : undefined;
|
|
495
|
+
}
|
|
496
|
+
function readBooleanField(record, key) {
|
|
497
|
+
return typeof record?.[key] === "boolean" ? record[key] : undefined;
|
|
498
|
+
}
|
|
499
|
+
function normalizeOpenRouterUsageDetails(usage, metadata) {
|
|
500
|
+
const source = isRecord(usage) ? recordField(usage, "raw") ?? usage : {};
|
|
501
|
+
const metaUsage = readMetadataUsageRecord(metadata);
|
|
502
|
+
const prompt = recordField(source, "prompt_tokens_details") ?? recordField(source, "input_tokens_details") ?? {};
|
|
503
|
+
const completion = recordField(source, "completion_tokens_details") ?? recordField(source, "output_tokens_details") ?? {};
|
|
504
|
+
const rawCostDetails = recordField(source, "cost_details") ?? (metaUsage ? recordField(metaUsage, "cost_details") : undefined);
|
|
505
|
+
const isByok = readBooleanField(source, "is_byok") ?? readBooleanField(metaUsage, "is_byok");
|
|
506
|
+
const promptCostUsd = nonNegativeNumber(rawCostDetails?.upstream_inference_prompt_cost) ?? nonNegativeNumber(rawCostDetails?.prompt_cost);
|
|
507
|
+
const outputCostUsd = nonNegativeNumber(rawCostDetails?.upstream_inference_completions_cost) ?? nonNegativeNumber(rawCostDetails?.completions_cost) ?? nonNegativeNumber(rawCostDetails?.completion_cost);
|
|
508
|
+
const upstreamInferenceCost = nonNegativeNumber(rawCostDetails?.upstream_inference_cost);
|
|
509
|
+
const baseCost = readOpenRouterBaseCost(source, metadata);
|
|
510
|
+
let cost;
|
|
511
|
+
if (isByok === true) {
|
|
512
|
+
const upstreamCost = upstreamInferenceCost ?? (promptCostUsd !== undefined || outputCostUsd !== undefined ? (promptCostUsd ?? 0) + (outputCostUsd ?? 0) : undefined);
|
|
513
|
+
cost = upstreamCost !== undefined ? computedUsd((baseCost ?? 0) + upstreamCost) : reportedUsd(baseCost);
|
|
514
|
+
} else {
|
|
515
|
+
cost = reportedUsd(baseCost);
|
|
516
|
+
}
|
|
517
|
+
const normalizedUsage = buildProviderUsage({
|
|
518
|
+
inputTokens: reportedInt(source.prompt_tokens ?? source.input_tokens),
|
|
519
|
+
outputTokens: reportedInt(source.completion_tokens ?? source.output_tokens),
|
|
520
|
+
reasoningTokens: reportedInt(completion.reasoning_tokens),
|
|
521
|
+
cacheReadTokens: reportedInt(prompt.cached_tokens),
|
|
522
|
+
cacheWriteTokens: reportedInt(prompt.cache_write_tokens),
|
|
523
|
+
cost
|
|
524
|
+
});
|
|
525
|
+
const costDetails = promptCostUsd !== undefined || outputCostUsd !== undefined || isByok !== undefined ? {
|
|
526
|
+
...promptCostUsd !== undefined && { promptCostUsd },
|
|
527
|
+
...outputCostUsd !== undefined && { outputCostUsd },
|
|
528
|
+
...isByok !== undefined && { isByok }
|
|
529
|
+
} : undefined;
|
|
530
|
+
return {
|
|
531
|
+
usage: normalizedUsage,
|
|
532
|
+
...costDetails !== undefined && { costDetails }
|
|
533
|
+
};
|
|
534
|
+
}
|
|
535
|
+
function normalizeOpenRouterUsage(usage, providerMetadata) {
|
|
536
|
+
return normalizeOpenRouterUsageDetails(usage, providerMetadata).usage;
|
|
537
|
+
}
|
|
538
|
+
function readHttpStatusNumber(value) {
|
|
539
|
+
return typeof value === "number" && Number.isInteger(value) && value >= 400 && value < 600 ? value : undefined;
|
|
540
|
+
}
|
|
541
|
+
function readCodeValue(value) {
|
|
542
|
+
return typeof value === "string" && value.length > 0 ? value : typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
543
|
+
}
|
|
544
|
+
function extractNestedError(payload, depth) {
|
|
545
|
+
if (depth > 4 || !isRecord(payload))
|
|
546
|
+
return {};
|
|
547
|
+
const err = recordField(payload, "error") ?? payload;
|
|
548
|
+
const outerMessage = nonEmptyString2(err.message);
|
|
549
|
+
const outerCode = readCodeValue(err.code);
|
|
550
|
+
const outerType = nonEmptyString2(err.type) ?? nonEmptyString2(err.status);
|
|
551
|
+
const outerStatus = readHttpStatusNumber(err.code) ?? readHttpStatusNumber(err.status);
|
|
552
|
+
const meta = recordField(err, "metadata");
|
|
553
|
+
const providerName = nonEmptyString2(meta?.provider_name);
|
|
554
|
+
const limitSource = nonEmptyString2(meta?.limit_source);
|
|
555
|
+
const reason = nonEmptyString2(meta?.reason);
|
|
556
|
+
const rawMeta = meta?.raw;
|
|
557
|
+
let nested = {};
|
|
558
|
+
let rawFallback;
|
|
559
|
+
let rawIsHtml = false;
|
|
560
|
+
if (typeof rawMeta === "string" && rawMeta.trim().length > 0) {
|
|
561
|
+
const trimmed = rawMeta.trim();
|
|
562
|
+
if (!EMPTY_RAW_SENTINELS.has(trimmed)) {
|
|
563
|
+
try {
|
|
564
|
+
const parsedRaw = JSON.parse(trimmed);
|
|
565
|
+
if (isRecord(parsedRaw))
|
|
566
|
+
nested = extractNestedError(parsedRaw, depth + 1);
|
|
567
|
+
else
|
|
568
|
+
rawFallback = redactProviderFailureText(trimmed, MAX_RAW_SNIPPET_CHARS);
|
|
569
|
+
} catch {
|
|
570
|
+
rawIsHtml = HTML_SNIPPET_PATTERN.test(trimmed);
|
|
571
|
+
rawFallback = redactProviderFailureText(trimmed, MAX_RAW_SNIPPET_CHARS);
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
} else if (isRecord(rawMeta)) {
|
|
575
|
+
nested = extractNestedError(rawMeta, depth + 1);
|
|
576
|
+
}
|
|
577
|
+
const nestedMessage = nested.message && !GENERIC_ERROR_MESSAGES.has(nested.message) ? nested.message : undefined;
|
|
578
|
+
const meaningfulOuter = outerMessage && !GENERIC_ERROR_MESSAGES.has(outerMessage) ? outerMessage : undefined;
|
|
579
|
+
const message = nestedMessage ?? (rawIsHtml && meaningfulOuter !== undefined ? meaningfulOuter : rawFallback) ?? outerMessage;
|
|
580
|
+
const code = typeof nested.code === "string" ? nested.code : outerCode !== undefined ? outerCode : nested.code;
|
|
581
|
+
const errorType = nested.errorType ?? outerType;
|
|
582
|
+
const statusCode = outerStatus ?? nested.statusCode;
|
|
583
|
+
return {
|
|
584
|
+
...message !== undefined && { message },
|
|
585
|
+
...code !== undefined && { code },
|
|
586
|
+
...errorType !== undefined && { errorType },
|
|
587
|
+
...statusCode !== undefined && { statusCode },
|
|
588
|
+
...(providerName ?? nested.providerName) !== undefined && {
|
|
589
|
+
providerName: providerName ?? nested.providerName
|
|
590
|
+
},
|
|
591
|
+
...(limitSource ?? nested.limitSource) !== undefined && {
|
|
592
|
+
limitSource: limitSource ?? nested.limitSource
|
|
593
|
+
},
|
|
594
|
+
...(reason ?? nested.reason) !== undefined && {
|
|
595
|
+
reason: reason ?? nested.reason
|
|
596
|
+
},
|
|
597
|
+
...nested.code !== undefined && { upstreamCode: nested.code },
|
|
598
|
+
...nested.statusCode !== undefined && { upstreamStatus: nested.statusCode }
|
|
599
|
+
};
|
|
600
|
+
}
|
|
601
|
+
function parseOpenRouterError(payload, rawText = "", status) {
|
|
602
|
+
const extracted = extractNestedError(payload, 0);
|
|
603
|
+
const trimmedRaw = rawText.trim();
|
|
604
|
+
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");
|
|
605
|
+
const prefixed = extracted.providerName && !baseMessage.startsWith(`[${extracted.providerName}] `) ? `[${extracted.providerName}] ${baseMessage}` : baseMessage;
|
|
606
|
+
const message = redactProviderFailureText(prefixed);
|
|
607
|
+
const errorMeta = {};
|
|
608
|
+
if (extracted.providerName !== undefined)
|
|
609
|
+
errorMeta.provider_name = extracted.providerName;
|
|
610
|
+
if (extracted.limitSource !== undefined)
|
|
611
|
+
errorMeta.limit_source = extracted.limitSource;
|
|
612
|
+
if (extracted.reason !== undefined)
|
|
613
|
+
errorMeta.reason = extracted.reason;
|
|
614
|
+
if (extracted.upstreamCode !== undefined)
|
|
615
|
+
errorMeta.upstream_code = extracted.upstreamCode;
|
|
616
|
+
if (extracted.upstreamStatus !== undefined)
|
|
617
|
+
errorMeta.upstream_status = extracted.upstreamStatus;
|
|
618
|
+
const statusCode = extracted.statusCode ?? (status !== undefined && status >= 400 ? status : undefined);
|
|
619
|
+
const failureReason = statusCode === 402 && extracted.limitSource === "openrouter_in_flight_budget" ? "overloaded" : undefined;
|
|
620
|
+
return {
|
|
621
|
+
message,
|
|
622
|
+
...extracted.code !== undefined && { code: extracted.code },
|
|
623
|
+
...extracted.errorType !== undefined && { errorType: extracted.errorType },
|
|
624
|
+
...statusCode !== undefined && { statusCode },
|
|
625
|
+
...failureReason !== undefined && { failureReason },
|
|
626
|
+
...Object.keys(errorMeta).length > 0 && { metadata: errorMeta }
|
|
627
|
+
};
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
// src/agent-runtime/providers/openrouter-request.ts
|
|
631
|
+
async function refuseRedirect(response) {
|
|
632
|
+
if (response.redirected || response.type === "opaqueredirect" || response.status >= 300 && response.status < 400) {
|
|
633
|
+
await response.body?.cancel().catch(() => {
|
|
634
|
+
return;
|
|
635
|
+
});
|
|
636
|
+
throw new AgentProviderError2(`OpenRouter redirected response refused (HTTP ${response.status})`, {
|
|
637
|
+
provider: "openrouter",
|
|
638
|
+
statusCode: response.status,
|
|
639
|
+
retryable: false,
|
|
640
|
+
responseHeaders: headersToRecord(response.headers)
|
|
641
|
+
});
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
async function sendOpenRouterRequest(exchange) {
|
|
645
|
+
const { signal } = exchange;
|
|
646
|
+
const fetch = exchange.fetch ?? globalThis.fetch;
|
|
647
|
+
const response = await raceAbort(fetch(exchange.url, {
|
|
648
|
+
method: exchange.method,
|
|
649
|
+
headers: exchange.headers,
|
|
650
|
+
...exchange.body !== undefined && { body: exchange.body },
|
|
651
|
+
redirect: "error",
|
|
652
|
+
signal
|
|
653
|
+
}), signal, (late) => {
|
|
654
|
+
late.body?.cancel(abortReason(signal)).catch(() => {
|
|
655
|
+
return;
|
|
656
|
+
});
|
|
657
|
+
});
|
|
658
|
+
if (signal.aborted) {
|
|
659
|
+
await response.body?.cancel(abortReason(signal)).catch(() => {
|
|
660
|
+
return;
|
|
661
|
+
});
|
|
662
|
+
signal.throwIfAborted();
|
|
663
|
+
}
|
|
664
|
+
await refuseRedirect(response);
|
|
665
|
+
if (!response.ok) {
|
|
666
|
+
throw await buildProviderHttpError({
|
|
667
|
+
provider: "openrouter",
|
|
668
|
+
response,
|
|
669
|
+
signal,
|
|
670
|
+
parseError: parseOpenRouterError,
|
|
671
|
+
maxErrorBytes: exchange.maxErrorBytes ?? DEFAULT_MAX_ERROR_BODY_BYTES
|
|
672
|
+
});
|
|
673
|
+
}
|
|
674
|
+
return response;
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
// src/agent-runtime/providers/openrouter-url.ts
|
|
678
|
+
var OPENROUTER_API_BASE_URL = "https://openrouter.ai/api/v1";
|
|
679
|
+
var SCHEME_PREFIX = /^[a-z][a-z0-9+.-]*:/iu;
|
|
680
|
+
var ENCODED_TRAVERSAL = /%(?:2e|2f|5c)/iu;
|
|
681
|
+
var CHAT_ENDPOINT_SUFFIX = /\/chat\/completions\/*$/iu;
|
|
682
|
+
function hasControlOrWhitespace(value) {
|
|
683
|
+
for (let i = 0;i < value.length; i += 1) {
|
|
684
|
+
const code = value.charCodeAt(i);
|
|
685
|
+
if (code <= 32 || code === 127)
|
|
686
|
+
return true;
|
|
687
|
+
}
|
|
688
|
+
return false;
|
|
689
|
+
}
|
|
690
|
+
function validateOpenRouterBaseUrl(raw) {
|
|
691
|
+
const candidate = raw ?? OPENROUTER_API_BASE_URL;
|
|
692
|
+
if (typeof candidate !== "string" || candidate.trim().length === 0 || !URL.canParse(candidate)) {
|
|
693
|
+
throw new TypeError("Invalid OpenRouter baseUrl");
|
|
694
|
+
}
|
|
695
|
+
const url = new URL(candidate);
|
|
696
|
+
if (url.protocol !== "https:" && url.protocol !== "http:") {
|
|
697
|
+
throw new TypeError(`OpenRouter baseUrl must use https: (or http: to a loopback host), received "${url.protocol}"`);
|
|
698
|
+
}
|
|
699
|
+
if (url.protocol === "http:" && !isLoopbackHostname(url.hostname)) {
|
|
700
|
+
throw new TypeError("OpenRouter baseUrl must use https: unless it names a loopback host (localhost, 127.0.0.0/8, [::1])");
|
|
701
|
+
}
|
|
702
|
+
if (url.username.length > 0 || url.password.length > 0) {
|
|
703
|
+
throw new TypeError("OpenRouter baseUrl must not contain embedded credentials");
|
|
704
|
+
}
|
|
705
|
+
if (url.href.includes("?")) {
|
|
706
|
+
throw new TypeError("OpenRouter baseUrl must not contain a query string");
|
|
707
|
+
}
|
|
708
|
+
if (url.href.includes("#")) {
|
|
709
|
+
throw new TypeError("OpenRouter baseUrl must not contain a URL fragment");
|
|
710
|
+
}
|
|
711
|
+
if (CHAT_ENDPOINT_SUFFIX.test(url.pathname)) {
|
|
712
|
+
throw new TypeError(`OpenRouter baseUrl must be the API root (such as ${OPENROUTER_API_BASE_URL}), not the /chat/completions endpoint: every path appends its own endpoint`);
|
|
713
|
+
}
|
|
714
|
+
return url;
|
|
715
|
+
}
|
|
716
|
+
function assertOpenRouterHttpUrl(name, value) {
|
|
717
|
+
if (typeof value !== "string" || value.trim().length === 0 || !URL.canParse(value)) {
|
|
718
|
+
throw new TypeError(`${name} must be a valid http: or https: URL`);
|
|
719
|
+
}
|
|
720
|
+
const url = new URL(value);
|
|
721
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
|
722
|
+
throw new TypeError(`${name} must use http: or https: protocol`);
|
|
723
|
+
}
|
|
724
|
+
if (url.username.length > 0 || url.password.length > 0) {
|
|
725
|
+
throw new TypeError(`${name} must not contain embedded credentials`);
|
|
726
|
+
}
|
|
727
|
+
return value.trim();
|
|
728
|
+
}
|
|
729
|
+
function assertOpenRouterPathSegment(name, value) {
|
|
730
|
+
const trimmed = typeof value === "string" ? value.trim() : "";
|
|
731
|
+
if (trimmed.length === 0 || trimmed === "." || trimmed === ".." || trimmed.includes("/") || trimmed.includes("\\") || trimmed.includes("?") || trimmed.includes("#") || hasControlOrWhitespace(trimmed) || ENCODED_TRAVERSAL.test(trimmed)) {
|
|
732
|
+
throw new TypeError(`Invalid OpenRouter ${name}`);
|
|
733
|
+
}
|
|
734
|
+
return trimmed;
|
|
735
|
+
}
|
|
736
|
+
function resolveOpenRouterUrl(baseUrl, path, query) {
|
|
737
|
+
const base = validateOpenRouterBaseUrl(baseUrl);
|
|
738
|
+
if (typeof path !== "string" || path.length === 0 || SCHEME_PREFIX.test(path) || path.startsWith("//") || path.includes("\\") || path.includes("?") || path.includes("#") || hasControlOrWhitespace(path) || ENCODED_TRAVERSAL.test(path)) {
|
|
739
|
+
throw new TypeError("OpenRouter path must be a relative endpoint path without scheme or query");
|
|
740
|
+
}
|
|
741
|
+
const normalized = path.startsWith("/") ? path : `/${path}`;
|
|
742
|
+
const segments = normalized.slice(1).split("/");
|
|
743
|
+
if (segments.some((segment) => segment.length === 0 || segment === "." || segment === "..")) {
|
|
744
|
+
throw new TypeError("OpenRouter path must not contain empty or traversal segments");
|
|
745
|
+
}
|
|
746
|
+
const basePath = base.pathname.replace(/\/+$/u, "");
|
|
747
|
+
const resolved = new URL(base.toString());
|
|
748
|
+
resolved.pathname = `${basePath}${normalized}`;
|
|
749
|
+
if (resolved.origin !== base.origin || basePath.length > 0 && !resolved.pathname.startsWith(`${basePath}/`)) {
|
|
750
|
+
throw new TypeError("OpenRouter path escaped baseUrl scope");
|
|
751
|
+
}
|
|
752
|
+
if (query instanceof URLSearchParams) {
|
|
753
|
+
for (const [key, value] of query.entries()) {
|
|
754
|
+
resolved.searchParams.append(key, value);
|
|
755
|
+
}
|
|
756
|
+
} else if (query !== undefined) {
|
|
757
|
+
for (const [key, value] of Object.entries(query)) {
|
|
758
|
+
if (value === undefined)
|
|
759
|
+
continue;
|
|
760
|
+
if (typeof value === "number" && !Number.isFinite(value)) {
|
|
761
|
+
throw new TypeError(`OpenRouter query parameter "${key}" must be a finite number`);
|
|
762
|
+
}
|
|
763
|
+
resolved.searchParams.set(key, String(value));
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
return resolved;
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
// src/agent-runtime/providers/openrouter-http.ts
|
|
770
|
+
var DEFAULT_OPENROUTER_REQUEST_TIMEOUT_MS = 30000;
|
|
771
|
+
var JSON_CONTENT_TYPE = /^application\/(?:[a-z0-9.+-]+\+)?json(?:\s*;|$)/iu;
|
|
772
|
+
function assertNonEmptyOpenRouterField(caller, name, value) {
|
|
773
|
+
const trimmed = typeof value === "string" ? value.trim() : "";
|
|
774
|
+
if (trimmed.length === 0) {
|
|
775
|
+
throw new TypeError(`${caller}: ${name} must be a non-empty string`);
|
|
776
|
+
}
|
|
777
|
+
return trimmed;
|
|
778
|
+
}
|
|
779
|
+
function pickOpenRouterTransport(input) {
|
|
780
|
+
return {
|
|
781
|
+
...input.apiKey !== undefined && { apiKey: input.apiKey },
|
|
782
|
+
...input.baseUrl !== undefined && { baseUrl: input.baseUrl },
|
|
783
|
+
...input.headers !== undefined && { headers: input.headers },
|
|
784
|
+
...input.appName !== undefined && { appName: input.appName },
|
|
785
|
+
...input.appUrl !== undefined && { appUrl: input.appUrl },
|
|
786
|
+
...input.providerApiKeys !== undefined && { providerApiKeys: input.providerApiKeys },
|
|
787
|
+
...input.fetch !== undefined && { fetch: input.fetch },
|
|
788
|
+
...input.signal !== undefined && { signal: input.signal },
|
|
789
|
+
...input.timeoutMs !== undefined && { timeoutMs: input.timeoutMs },
|
|
790
|
+
...input.maxErrorBytes !== undefined && { maxErrorBytes: input.maxErrorBytes },
|
|
791
|
+
...input.maxResponseBytes !== undefined && { maxResponseBytes: input.maxResponseBytes }
|
|
792
|
+
};
|
|
793
|
+
}
|
|
794
|
+
function validateApiKeyString(raw) {
|
|
795
|
+
if (typeof raw !== "string") {
|
|
796
|
+
throw new TypeError("OpenRouter apiKey must resolve to a non-empty string");
|
|
797
|
+
}
|
|
798
|
+
if (/[\r\n]/u.test(raw)) {
|
|
799
|
+
throw new TypeError("OpenRouter apiKey must not contain CR or LF characters");
|
|
800
|
+
}
|
|
801
|
+
const trimmed = raw.trim();
|
|
802
|
+
if (trimmed.length === 0) {
|
|
803
|
+
throw new TypeError("OpenRouter apiKey must be a non-empty string when provided");
|
|
804
|
+
}
|
|
805
|
+
return trimmed;
|
|
806
|
+
}
|
|
807
|
+
function assertValidOpenRouterApiKey(apiKey) {
|
|
808
|
+
if (apiKey === undefined || typeof apiKey === "function")
|
|
809
|
+
return;
|
|
810
|
+
validateApiKeyString(apiKey);
|
|
811
|
+
}
|
|
812
|
+
async function resolveOptionalOpenRouterApiKey(apiKey) {
|
|
813
|
+
if (apiKey === undefined)
|
|
814
|
+
return;
|
|
815
|
+
const resolved = typeof apiKey === "function" ? await apiKey() : apiKey;
|
|
816
|
+
return validateApiKeyString(resolved);
|
|
817
|
+
}
|
|
818
|
+
function hasHeaderIgnoreCase(headers, targetLower) {
|
|
819
|
+
if (!headers)
|
|
820
|
+
return false;
|
|
821
|
+
return Object.keys(headers).some((key) => key.toLowerCase() === targetLower);
|
|
822
|
+
}
|
|
823
|
+
var OPENROUTER_API_HOST = new URL(OPENROUTER_API_BASE_URL).hostname;
|
|
824
|
+
function isForeignBaseUrl(baseUrl) {
|
|
825
|
+
if (baseUrl === undefined || !URL.canParse(baseUrl))
|
|
826
|
+
return baseUrl !== undefined;
|
|
827
|
+
return new URL(baseUrl).hostname.toLowerCase().replace(/\.$/u, "") !== OPENROUTER_API_HOST;
|
|
828
|
+
}
|
|
829
|
+
function assertOpenRouterDirectAuth(input) {
|
|
830
|
+
if (input.apiKey === undefined && input.fetch === undefined && !isForeignBaseUrl(input.baseUrl) && !hasHeaderIgnoreCase(input.headers, "authorization")) {
|
|
831
|
+
throw new TypeError(`OpenRouter apiKey is required for ${OPENROUTER_API_HOST} unless an Authorization header, a custom fetch transport or a baseUrl on another host is provided`);
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
function buildOpenRouterBaseHeaders(settings, apiKey) {
|
|
835
|
+
return {
|
|
836
|
+
...apiKey !== undefined && { authorization: `Bearer ${apiKey}` },
|
|
837
|
+
...settings.appUrl !== undefined && { "HTTP-Referer": settings.appUrl },
|
|
838
|
+
...settings.appName !== undefined && { "X-OpenRouter-Title": settings.appName },
|
|
839
|
+
...settings.providerApiKeys !== undefined && {
|
|
840
|
+
"X-Provider-API-Keys": JSON.stringify(settings.providerApiKeys)
|
|
841
|
+
}
|
|
842
|
+
};
|
|
843
|
+
}
|
|
844
|
+
function prepareOpenRouterRequest(input) {
|
|
845
|
+
const url = resolveOpenRouterUrl(input.baseUrl, input.path, input.query);
|
|
846
|
+
const method = input.method ?? (input.body !== undefined ? "POST" : "GET");
|
|
847
|
+
if (method === "GET" && input.body !== undefined) {
|
|
848
|
+
throw new TypeError("OpenRouter GET request must not include a request body");
|
|
849
|
+
}
|
|
850
|
+
assertValidOpenRouterApiKey(input.apiKey);
|
|
851
|
+
if (input.apiKey !== undefined && hasHeaderIgnoreCase(input.headers, "authorization")) {
|
|
852
|
+
throw new TypeError("OpenRouter request cannot specify both apiKey and Authorization header");
|
|
853
|
+
}
|
|
854
|
+
const isFormData = typeof FormData === "function" && input.body instanceof FormData;
|
|
855
|
+
if (isFormData && hasHeaderIgnoreCase(input.headers, "content-type")) {
|
|
856
|
+
throw new TypeError("OpenRouter FormData request must not specify a Content-Type header (multipart boundary is generated automatically)");
|
|
857
|
+
}
|
|
858
|
+
const timeoutMs = input.timeoutMs ?? DEFAULT_OPENROUTER_REQUEST_TIMEOUT_MS;
|
|
859
|
+
assertTimerMs("timeoutMs", timeoutMs);
|
|
860
|
+
const maxErrorBytes = input.maxErrorBytes ?? DEFAULT_MAX_ERROR_BODY_BYTES;
|
|
861
|
+
assertPositiveSafeInteger("maxErrorBytes", maxErrorBytes);
|
|
862
|
+
let serializedBody;
|
|
863
|
+
if (input.body !== undefined) {
|
|
864
|
+
if (isFormData) {
|
|
865
|
+
serializedBody = input.body;
|
|
866
|
+
} else {
|
|
867
|
+
const encoded = JSON.stringify(input.body);
|
|
868
|
+
if (encoded === undefined) {
|
|
869
|
+
throw new TypeError("OpenRouter request body is not JSON-serializable");
|
|
870
|
+
}
|
|
871
|
+
serializedBody = encoded;
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
return {
|
|
875
|
+
url,
|
|
876
|
+
method,
|
|
877
|
+
isFormData,
|
|
878
|
+
...serializedBody !== undefined && { serializedBody },
|
|
879
|
+
timeoutMs,
|
|
880
|
+
maxErrorBytes,
|
|
881
|
+
...input.fetch !== undefined && { fetch: input.fetch }
|
|
882
|
+
};
|
|
883
|
+
}
|
|
884
|
+
function assembleOpenRouterRequestHeaders(input, prepared, apiKey, defaultAccept) {
|
|
885
|
+
const headers = new Headers;
|
|
886
|
+
if (defaultAccept !== undefined)
|
|
887
|
+
headers.set("accept", defaultAccept);
|
|
888
|
+
if (prepared.serializedBody !== undefined && !prepared.isFormData) {
|
|
889
|
+
headers.set("content-type", "application/json");
|
|
890
|
+
}
|
|
891
|
+
for (const [k, v] of Object.entries(buildOpenRouterBaseHeaders(input, apiKey))) {
|
|
892
|
+
headers.set(k, v);
|
|
893
|
+
}
|
|
894
|
+
if (input.headers) {
|
|
895
|
+
for (const [k, v] of Object.entries(input.headers)) {
|
|
896
|
+
headers.set(k, v);
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
return headers;
|
|
900
|
+
}
|
|
901
|
+
function openRouterExchange(prepared, headers, signal) {
|
|
902
|
+
return {
|
|
903
|
+
url: prepared.url,
|
|
904
|
+
method: prepared.method,
|
|
905
|
+
headers,
|
|
906
|
+
...prepared.serializedBody !== undefined && { body: prepared.serializedBody },
|
|
907
|
+
signal,
|
|
908
|
+
...prepared.fetch !== undefined && { fetch: prepared.fetch },
|
|
909
|
+
maxErrorBytes: prepared.maxErrorBytes
|
|
910
|
+
};
|
|
911
|
+
}
|
|
912
|
+
function extractOpenRouterGenerationId(headers, parsedBody) {
|
|
913
|
+
const fromHeader = nonEmptyTrimmed(headers.get("x-generation-id"));
|
|
914
|
+
if (fromHeader !== undefined)
|
|
915
|
+
return fromHeader;
|
|
916
|
+
if (!isRecord(parsedBody))
|
|
917
|
+
return;
|
|
918
|
+
const genId = nonEmptyTrimmed(typeof parsedBody.generation_id === "string" ? parsedBody.generation_id : undefined);
|
|
919
|
+
if (genId !== undefined)
|
|
920
|
+
return genId;
|
|
921
|
+
const bodyId = nonEmptyTrimmed(typeof parsedBody.id === "string" ? parsedBody.id : undefined);
|
|
922
|
+
return bodyId?.startsWith("gen-") ? bodyId : undefined;
|
|
923
|
+
}
|
|
924
|
+
function extractCostUsd(parsedBody) {
|
|
925
|
+
if (!isRecord(parsedBody))
|
|
926
|
+
return;
|
|
927
|
+
const cost = normalizeOpenRouterUsageDetails(parsedBody.usage).usage.cost;
|
|
928
|
+
return cost?.value;
|
|
929
|
+
}
|
|
930
|
+
async function openRouterRequestJson(input) {
|
|
931
|
+
const prepared = prepareOpenRouterRequest(input);
|
|
932
|
+
const maxResponseBytes = input.maxResponseBytes ?? DEFAULT_MAX_JSON_BODY_BYTES;
|
|
933
|
+
assertPositiveSafeInteger("maxResponseBytes", maxResponseBytes);
|
|
934
|
+
input.signal?.throwIfAborted();
|
|
935
|
+
const apiKey = await resolveOptionalOpenRouterApiKey(input.apiKey);
|
|
936
|
+
input.signal?.throwIfAborted();
|
|
937
|
+
return withSignalDeadline(prepared.timeoutMs, input.signal, () => abortError(`OpenRouter request ${input.path} timed out after ${prepared.timeoutMs} ms`, "TimeoutError"), async (signal) => {
|
|
938
|
+
const headers = assembleOpenRouterRequestHeaders(input, prepared, apiKey, "application/json");
|
|
939
|
+
const response = await sendOpenRouterRequest(openRouterExchange(prepared, headers, signal));
|
|
940
|
+
const requestId = extractProviderRequestId(response.headers);
|
|
941
|
+
const responseHeaders = headersToRecord(response.headers);
|
|
942
|
+
const contentType = response.headers.get("content-type")?.trim() ?? "";
|
|
943
|
+
if (contentType.length > 0 && !JSON_CONTENT_TYPE.test(contentType)) {
|
|
944
|
+
const preview = await readBoundedText(response, { maxBytes: 4096, signal }).catch(() => ({
|
|
945
|
+
kind: "complete",
|
|
946
|
+
text: ""
|
|
947
|
+
}));
|
|
948
|
+
if (signal.aborted)
|
|
949
|
+
signal.throwIfAborted();
|
|
950
|
+
const snippet = preview.kind === "complete" && preview.text.length > 0 ? `: ${redactProviderFailureText(preview.text, 256)}` : "";
|
|
951
|
+
throw new AgentProviderError2(`OpenRouter returned unexpected content-type "${redactProviderFailureText(contentType, 128)}"${snippet}`, {
|
|
952
|
+
provider: "openrouter",
|
|
953
|
+
statusCode: response.status,
|
|
954
|
+
retryable: false,
|
|
955
|
+
...requestId !== undefined && { requestId },
|
|
956
|
+
responseHeaders
|
|
957
|
+
});
|
|
958
|
+
}
|
|
959
|
+
const bodyResult = await readBoundedText(response, {
|
|
960
|
+
maxBytes: maxResponseBytes,
|
|
961
|
+
signal,
|
|
962
|
+
checkContentLength: true
|
|
963
|
+
});
|
|
964
|
+
if (signal.aborted)
|
|
965
|
+
signal.throwIfAborted();
|
|
966
|
+
if (bodyResult.kind === "over-limit") {
|
|
967
|
+
throw new AgentProviderError2(`OpenRouter JSON response exceeded ${maxResponseBytes} byte limit`, {
|
|
968
|
+
provider: "openrouter",
|
|
969
|
+
statusCode: response.status,
|
|
970
|
+
retryable: false,
|
|
971
|
+
...requestId !== undefined && { requestId },
|
|
972
|
+
responseHeaders
|
|
973
|
+
});
|
|
974
|
+
}
|
|
975
|
+
if (bodyResult.text.trim().length === 0) {
|
|
976
|
+
throw new AgentProviderError2("OpenRouter returned an empty JSON response body", {
|
|
977
|
+
provider: "openrouter",
|
|
978
|
+
statusCode: response.status,
|
|
979
|
+
retryable: false,
|
|
980
|
+
...requestId !== undefined && { requestId },
|
|
981
|
+
responseHeaders
|
|
982
|
+
});
|
|
983
|
+
}
|
|
984
|
+
let parsed;
|
|
985
|
+
try {
|
|
986
|
+
parsed = JSON.parse(bodyResult.text);
|
|
987
|
+
} catch (error) {
|
|
988
|
+
throw new AgentProviderError2(`OpenRouter returned invalid JSON body: ${redactProviderFailureText(bodyResult.text, 256)}`, {
|
|
989
|
+
provider: "openrouter",
|
|
990
|
+
statusCode: response.status,
|
|
991
|
+
retryable: false,
|
|
992
|
+
...requestId !== undefined && { requestId },
|
|
993
|
+
responseHeaders,
|
|
994
|
+
cause: error
|
|
995
|
+
});
|
|
996
|
+
}
|
|
997
|
+
let data = parsed;
|
|
998
|
+
if (input.schema !== undefined) {
|
|
999
|
+
const validated = input.schema.safeParse(parsed);
|
|
1000
|
+
if (!validated.success) {
|
|
1001
|
+
throw new AgentProviderError2(`OpenRouter response failed schema validation: ${redactProviderFailureText(validated.error.message, 512)}`, {
|
|
1002
|
+
provider: "openrouter",
|
|
1003
|
+
statusCode: response.status,
|
|
1004
|
+
retryable: false,
|
|
1005
|
+
...requestId !== undefined && { requestId },
|
|
1006
|
+
responseHeaders,
|
|
1007
|
+
cause: validated.error
|
|
1008
|
+
});
|
|
1009
|
+
}
|
|
1010
|
+
data = validated.data;
|
|
1011
|
+
}
|
|
1012
|
+
const generationId = extractOpenRouterGenerationId(response.headers, parsed);
|
|
1013
|
+
const costUsd = extractCostUsd(parsed);
|
|
1014
|
+
return {
|
|
1015
|
+
data,
|
|
1016
|
+
status: response.status,
|
|
1017
|
+
...generationId !== undefined && { generationId },
|
|
1018
|
+
...requestId !== undefined && { requestId },
|
|
1019
|
+
...costUsd !== undefined && { costUsd },
|
|
1020
|
+
headers: responseHeaders
|
|
1021
|
+
};
|
|
1022
|
+
});
|
|
1023
|
+
}
|
|
1024
|
+
|
|
503
1025
|
// src/agent-runtime/providers/openrouter-options.ts
|
|
504
1026
|
import { z as z3 } from "zod";
|
|
505
1027
|
var OPENROUTER_POLICY_KEYS = [
|
|
@@ -532,12 +1054,11 @@ var OpenRouterReasoningEffortSchema = z3.enum([
|
|
|
532
1054
|
"xhigh",
|
|
533
1055
|
"max"
|
|
534
1056
|
]);
|
|
535
|
-
var Usd = z3.number().nonnegative();
|
|
536
1057
|
var OpenRouterMaxPriceSchema = z3.strictObject({
|
|
537
|
-
promptUsdPerMillion:
|
|
538
|
-
completionUsdPerMillion:
|
|
539
|
-
requestUsd:
|
|
540
|
-
imageUsd:
|
|
1058
|
+
promptUsdPerMillion: NonNegativeNum.optional(),
|
|
1059
|
+
completionUsdPerMillion: NonNegativeNum.optional(),
|
|
1060
|
+
requestUsd: NonNegativeNum.optional(),
|
|
1061
|
+
imageUsd: NonNegativeNum.optional()
|
|
541
1062
|
});
|
|
542
1063
|
var Slug = z3.string().min(1).max(128);
|
|
543
1064
|
var OpenRouterProviderRoutingSchema = z3.strictObject({
|
|
@@ -549,7 +1070,8 @@ var OpenRouterProviderRoutingSchema = z3.strictObject({
|
|
|
549
1070
|
dataCollection: z3.enum(["allow", "deny"]).optional(),
|
|
550
1071
|
zdr: z3.boolean().optional(),
|
|
551
1072
|
sort: z3.enum(["price", "throughput", "latency"]).optional(),
|
|
552
|
-
quantizations: z3.array(z3.string().min(1).max(16)).min(1).optional()
|
|
1073
|
+
quantizations: z3.array(z3.string().min(1).max(16)).min(1).optional(),
|
|
1074
|
+
options: z3.record(Slug, z3.record(z3.string(), z3.json())).optional()
|
|
553
1075
|
});
|
|
554
1076
|
var OpenRouterReasoningPolicySchema = z3.strictObject({
|
|
555
1077
|
effort: OpenRouterReasoningEffortSchema.optional(),
|
|
@@ -587,9 +1109,27 @@ var OpenRouterRequestPolicySchema = z3.strictObject({
|
|
|
587
1109
|
message: "A request pins its route by sessionId or by provider.order, not both"
|
|
588
1110
|
});
|
|
589
1111
|
});
|
|
1112
|
+
function serializeOpenRouterProviderRouting(raw) {
|
|
1113
|
+
const routing = OpenRouterProviderRoutingSchema.parse(raw);
|
|
1114
|
+
const wire = {
|
|
1115
|
+
...routing.order && { order: routing.order },
|
|
1116
|
+
...routing.only && { only: routing.only },
|
|
1117
|
+
...routing.ignore && { ignore: routing.ignore },
|
|
1118
|
+
...routing.allowFallbacks !== undefined && { allow_fallbacks: routing.allowFallbacks },
|
|
1119
|
+
...routing.requireParameters !== undefined && {
|
|
1120
|
+
require_parameters: routing.requireParameters
|
|
1121
|
+
},
|
|
1122
|
+
...routing.dataCollection && { data_collection: routing.dataCollection },
|
|
1123
|
+
...routing.zdr !== undefined && { zdr: routing.zdr },
|
|
1124
|
+
...routing.sort && { sort: routing.sort },
|
|
1125
|
+
...routing.quantizations && { quantizations: routing.quantizations },
|
|
1126
|
+
...routing.options && { options: routing.options }
|
|
1127
|
+
};
|
|
1128
|
+
return Object.keys(wire).length > 0 ? wire : undefined;
|
|
1129
|
+
}
|
|
590
1130
|
function resolveOpenRouterWirePolicy(raw) {
|
|
591
1131
|
const policy = OpenRouterRequestPolicySchema.parse(raw);
|
|
592
|
-
const routing = policy.provider;
|
|
1132
|
+
const routing = policy.provider ? serializeOpenRouterProviderRouting(policy.provider) : undefined;
|
|
593
1133
|
const price = policy.maxPrice;
|
|
594
1134
|
const maxPrice = price && {
|
|
595
1135
|
...price.promptUsdPerMillion !== undefined && { prompt: price.promptUsdPerMillion },
|
|
@@ -599,254 +1139,81 @@ function resolveOpenRouterWirePolicy(raw) {
|
|
|
599
1139
|
...price.requestUsd !== undefined && { request: price.requestUsd },
|
|
600
1140
|
...price.imageUsd !== undefined && { image: price.imageUsd }
|
|
601
1141
|
};
|
|
602
|
-
const provider = routing || maxPrice ? {
|
|
603
|
-
...routing
|
|
604
|
-
...routing?.only && { only: routing.only },
|
|
605
|
-
...routing?.ignore && { ignore: routing.ignore },
|
|
606
|
-
...routing?.allowFallbacks !== undefined && {
|
|
607
|
-
allow_fallbacks: routing.allowFallbacks
|
|
608
|
-
},
|
|
609
|
-
...routing?.requireParameters !== undefined && {
|
|
610
|
-
require_parameters: routing.requireParameters
|
|
611
|
-
},
|
|
612
|
-
...routing?.dataCollection && { data_collection: routing.dataCollection },
|
|
613
|
-
...routing?.zdr !== undefined && { zdr: routing.zdr },
|
|
614
|
-
...routing?.sort && { sort: routing.sort },
|
|
615
|
-
...routing?.quantizations && { quantizations: routing.quantizations },
|
|
1142
|
+
const provider = routing || maxPrice && Object.keys(maxPrice).length > 0 ? {
|
|
1143
|
+
...routing,
|
|
616
1144
|
...maxPrice && Object.keys(maxPrice).length > 0 && { max_price: maxPrice }
|
|
617
1145
|
} : undefined;
|
|
618
1146
|
return {
|
|
619
1147
|
...provider && Object.keys(provider).length > 0 && { provider },
|
|
620
1148
|
...policy.reasoning && {
|
|
621
1149
|
reasoning: {
|
|
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 }
|
|
628
|
-
}
|
|
629
|
-
},
|
|
630
|
-
...policy.sessionId !== undefined && { sessionId: policy.sessionId },
|
|
631
|
-
looseTools: policy.looseTools === true,
|
|
632
|
-
...policy.cacheControl !== undefined && { cacheControl: policy.cacheControl }
|
|
633
|
-
};
|
|
634
|
-
}
|
|
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
|
-
}
|
|
676
|
-
return {
|
|
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 }
|
|
689
|
-
};
|
|
690
|
-
}
|
|
691
|
-
|
|
692
|
-
// src/agent-runtime/providers/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 }
|
|
1150
|
+
...policy.reasoning.effort !== undefined && { effort: policy.reasoning.effort },
|
|
1151
|
+
...policy.reasoning.maxTokens !== undefined && {
|
|
1152
|
+
max_tokens: policy.reasoning.maxTokens
|
|
1153
|
+
},
|
|
1154
|
+
...policy.reasoning.enabled !== undefined && { enabled: policy.reasoning.enabled },
|
|
1155
|
+
...policy.reasoning.exclude !== undefined && { exclude: policy.reasoning.exclude }
|
|
1156
|
+
}
|
|
1157
|
+
},
|
|
1158
|
+
...policy.sessionId !== undefined && { sessionId: policy.sessionId },
|
|
1159
|
+
looseTools: policy.looseTools === true,
|
|
1160
|
+
...policy.cacheControl !== undefined && { cacheControl: policy.cacheControl }
|
|
756
1161
|
};
|
|
757
1162
|
}
|
|
758
|
-
function
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
}
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
}
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
const
|
|
771
|
-
const
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
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);
|
|
1163
|
+
function mergeOpenRouterStepPolicy(base, providerOptions) {
|
|
1164
|
+
const reqOr = recordField(providerOptions, "openrouter");
|
|
1165
|
+
if (!reqOr || Object.keys(reqOr).length === 0) {
|
|
1166
|
+
return {
|
|
1167
|
+
...base.provider !== undefined && { provider: base.provider },
|
|
1168
|
+
...base.reasoning !== undefined && { reasoning: base.reasoning },
|
|
1169
|
+
...base.sessionId !== undefined && { baseSessionId: base.sessionId },
|
|
1170
|
+
looseTools: base.looseTools,
|
|
1171
|
+
...base.cacheControl !== undefined && { baseCacheControl: base.cacheControl }
|
|
1172
|
+
};
|
|
1173
|
+
}
|
|
1174
|
+
let stepExtraBody;
|
|
1175
|
+
const policyInput = {};
|
|
1176
|
+
for (const [key, value] of Object.entries(reqOr)) {
|
|
1177
|
+
if (key === "extraBody") {
|
|
1178
|
+
if (value !== undefined) {
|
|
1179
|
+
if (!isRecord(value)) {
|
|
1180
|
+
throw new TypeError("openRouterProvider: providerOptions.openrouter.extraBody must be a plain object");
|
|
1181
|
+
}
|
|
1182
|
+
assertNoExtraBodyClash("openRouterProvider", value, OPENROUTER_POLICY_KEYS);
|
|
1183
|
+
stepExtraBody = value;
|
|
795
1184
|
}
|
|
1185
|
+
continue;
|
|
796
1186
|
}
|
|
797
|
-
|
|
798
|
-
|
|
1187
|
+
policyInput[key] = value;
|
|
1188
|
+
}
|
|
1189
|
+
const parsedStep = OpenRouterRequestPolicySchema.parse(policyInput);
|
|
1190
|
+
const stepWire = resolveOpenRouterWirePolicy(parsedStep);
|
|
1191
|
+
let mergedProvider;
|
|
1192
|
+
if (base.provider || stepWire.provider) {
|
|
1193
|
+
const baseProvider = stepWire.sessionId !== undefined && base.provider ? Object.fromEntries(Object.entries(base.provider).filter(([k]) => k !== "order")) : base.provider;
|
|
1194
|
+
const baseMaxPrice = isRecord(baseProvider?.max_price) ? baseProvider.max_price : null;
|
|
1195
|
+
const stepMaxPrice = isRecord(stepWire.provider?.max_price) ? stepWire.provider.max_price : null;
|
|
1196
|
+
const combined = {
|
|
1197
|
+
...baseProvider,
|
|
1198
|
+
...stepWire.provider,
|
|
1199
|
+
...baseMaxPrice && stepMaxPrice && { max_price: { ...baseMaxPrice, ...stepMaxPrice } }
|
|
1200
|
+
};
|
|
1201
|
+
if (Object.keys(combined).length > 0)
|
|
1202
|
+
mergedProvider = combined;
|
|
799
1203
|
}
|
|
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
1204
|
return {
|
|
807
|
-
...
|
|
808
|
-
...
|
|
809
|
-
|
|
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
|
|
1205
|
+
...mergedProvider !== undefined && { provider: mergedProvider },
|
|
1206
|
+
...(stepWire.reasoning ?? base.reasoning) !== undefined && {
|
|
1207
|
+
reasoning: stepWire.reasoning ?? base.reasoning
|
|
816
1208
|
},
|
|
817
|
-
...
|
|
818
|
-
|
|
1209
|
+
...stepWire.sessionId !== undefined && { stepSessionId: stepWire.sessionId },
|
|
1210
|
+
...base.sessionId !== undefined && { baseSessionId: base.sessionId },
|
|
1211
|
+
looseTools: parsedStep.looseTools !== undefined ? stepWire.looseTools : base.looseTools,
|
|
1212
|
+
...stepWire.cacheControl !== undefined && {
|
|
1213
|
+
explicitCacheControl: stepWire.cacheControl
|
|
819
1214
|
},
|
|
820
|
-
...
|
|
821
|
-
...
|
|
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 }
|
|
1215
|
+
...base.cacheControl !== undefined && { baseCacheControl: base.cacheControl },
|
|
1216
|
+
...stepExtraBody !== undefined && { stepExtraBody }
|
|
850
1217
|
};
|
|
851
1218
|
}
|
|
852
1219
|
|
|
@@ -1396,7 +1763,7 @@ function buildOpenAiChatRequestBody(input) {
|
|
|
1396
1763
|
return body;
|
|
1397
1764
|
}
|
|
1398
1765
|
|
|
1399
|
-
// src/agent-runtime/providers/provider-openai-chat-
|
|
1766
|
+
// src/agent-runtime/providers/provider-openai-chat-state.ts
|
|
1400
1767
|
var MAX_TOOL_CALLS = 256;
|
|
1401
1768
|
|
|
1402
1769
|
class DecodeState {
|
|
@@ -1430,53 +1797,6 @@ class DecodeState {
|
|
|
1430
1797
|
this.explicitUsageMeta = explicitUsageMeta;
|
|
1431
1798
|
}
|
|
1432
1799
|
}
|
|
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
1800
|
function* closeText(state) {
|
|
1481
1801
|
if (!state.textOpen)
|
|
1482
1802
|
return;
|
|
@@ -1540,6 +1860,55 @@ function* processToolCallDelta(tc, state, provider) {
|
|
|
1540
1860
|
yield { type: "tool-input-delta", toolCallId: entry.id, delta: arg };
|
|
1541
1861
|
}
|
|
1542
1862
|
}
|
|
1863
|
+
|
|
1864
|
+
// src/agent-runtime/providers/provider-openai-chat-sse.ts
|
|
1865
|
+
function mapOpenAiChatFinishReason(raw) {
|
|
1866
|
+
if (raw === "stop" || raw === "length" || raw === "error")
|
|
1867
|
+
return raw;
|
|
1868
|
+
if (raw === "tool_calls" || raw === "function_call")
|
|
1869
|
+
return "tool-calls";
|
|
1870
|
+
return raw === "content_filter" ? "content-filter" : "other";
|
|
1871
|
+
}
|
|
1872
|
+
function mergeReasoningDetail(acc, d) {
|
|
1873
|
+
const t = d.type;
|
|
1874
|
+
if (t === "reasoning.encrypted") {
|
|
1875
|
+
const hasId = (v) => typeof v === "string" && v.length > 0;
|
|
1876
|
+
if (hasId(d.id)) {
|
|
1877
|
+
const existing = acc.find((i) => i.type === t && i.format === d.format && i.id === d.id);
|
|
1878
|
+
if (existing) {
|
|
1879
|
+
if (typeof d.data === "string" && d.data.length > 0)
|
|
1880
|
+
existing.data = d.data;
|
|
1881
|
+
return;
|
|
1882
|
+
}
|
|
1883
|
+
acc.push({ ...d });
|
|
1884
|
+
return;
|
|
1885
|
+
}
|
|
1886
|
+
const duplicate = acc.some((i) => i.type === t && i.format === d.format && !hasId(i.id) && i.data === d.data);
|
|
1887
|
+
if (!duplicate)
|
|
1888
|
+
acc.push({ ...d });
|
|
1889
|
+
return;
|
|
1890
|
+
}
|
|
1891
|
+
const canMatch = t === "reasoning.text" || t === "reasoning.summary";
|
|
1892
|
+
const m = canMatch ? acc.find((i) => i.type === t && i.format === d.format && i.index === d.index && i.id === d.id) : undefined;
|
|
1893
|
+
if (!m) {
|
|
1894
|
+
acc.push({ ...d });
|
|
1895
|
+
return;
|
|
1896
|
+
}
|
|
1897
|
+
const add = (k, v) => {
|
|
1898
|
+
if (typeof v === "string")
|
|
1899
|
+
m[k] = `${typeof m[k] === "string" ? m[k] : ""}${v}`;
|
|
1900
|
+
};
|
|
1901
|
+
if (t === "reasoning.text") {
|
|
1902
|
+
add("text", d.text);
|
|
1903
|
+
if (typeof d.signature === "string" && d.signature.length > 0)
|
|
1904
|
+
m.signature = d.signature;
|
|
1905
|
+
} else if (t === "reasoning.summary")
|
|
1906
|
+
add("summary", d.summary);
|
|
1907
|
+
}
|
|
1908
|
+
function makeProviderError(provider, parsed) {
|
|
1909
|
+
const { message, ...rest } = parsed;
|
|
1910
|
+
return new AgentProviderError2(redactProviderFailureText(message || `${provider} request failed`), { provider, ...rest });
|
|
1911
|
+
}
|
|
1543
1912
|
function* decodeChunk(chunk, s, opts) {
|
|
1544
1913
|
if (!isRecord(chunk))
|
|
1545
1914
|
return;
|
|
@@ -1753,39 +2122,34 @@ async function* decodeOpenAiChatJsonResponse(body, options) {
|
|
|
1753
2122
|
}
|
|
1754
2123
|
|
|
1755
2124
|
// src/agent-runtime/providers/openrouter.ts
|
|
1756
|
-
var DEFAULT_OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1";
|
|
1757
2125
|
var EMPTY_WIRE_POLICY = { looseTools: false };
|
|
1758
|
-
function catalogJson(
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
2126
|
+
async function catalogJson(options, timeoutMs, path, query, signal) {
|
|
2127
|
+
const response = await openRouterRequestJson({
|
|
2128
|
+
path,
|
|
2129
|
+
query,
|
|
2130
|
+
signal,
|
|
2131
|
+
timeoutMs,
|
|
2132
|
+
...options.baseUrl !== undefined && { baseUrl: options.baseUrl },
|
|
2133
|
+
...options.apiKey !== undefined && { apiKey: options.apiKey },
|
|
2134
|
+
...options.fetch !== undefined && { fetch: options.fetch }
|
|
1764
2135
|
});
|
|
2136
|
+
return response.data;
|
|
1765
2137
|
}
|
|
1766
|
-
function benchmarkOutcome(
|
|
1767
|
-
return
|
|
2138
|
+
function benchmarkOutcome(read) {
|
|
2139
|
+
return read.then((value) => ({ outcome: "ok", value }), (error) => ({ outcome: "error", error }));
|
|
1768
2140
|
}
|
|
1769
2141
|
function openRouterModelCatalog(options = {}) {
|
|
1770
|
-
const fetcher = options.fetcher ?? fetch;
|
|
1771
2142
|
const timeoutMs = options.timeoutMs ?? 1e4;
|
|
1772
2143
|
assertTimerMs("timeoutMs", timeoutMs);
|
|
1773
|
-
|
|
2144
|
+
assertValidOpenRouterApiKey(options.apiKey);
|
|
2145
|
+
validateOpenRouterBaseUrl(options.baseUrl);
|
|
1774
2146
|
return {
|
|
1775
2147
|
async load(input = {}) {
|
|
1776
|
-
const
|
|
1777
|
-
modelsUrl.searchParams.set("supported_parameters", "tools");
|
|
1778
|
-
modelsUrl.searchParams.set("output_modalities", "text");
|
|
1779
|
-
modelsUrl.searchParams.set("sort", "top-weekly");
|
|
1780
|
-
const artificialUrl = new URL("https://openrouter.ai/api/v1/benchmarks");
|
|
1781
|
-
artificialUrl.searchParams.set("source", "artificial-analysis");
|
|
1782
|
-
const designUrl = new URL("https://openrouter.ai/api/v1/benchmarks");
|
|
1783
|
-
designUrl.searchParams.set("source", "design-arena");
|
|
1784
|
-
designUrl.searchParams.set("arena", "agents");
|
|
2148
|
+
const read = (path, query, signal) => catalogJson(options, timeoutMs, path, query, signal);
|
|
1785
2149
|
const [modelsRaw, artificialResult, designResult] = await withOpenRouterTimeout(timeoutMs, input.signal, (signal) => Promise.all([
|
|
1786
|
-
|
|
1787
|
-
benchmarkOutcome(
|
|
1788
|
-
benchmarkOutcome(
|
|
2150
|
+
read("/models", { supported_parameters: "tools", output_modalities: "text", sort: "top-weekly" }, signal),
|
|
2151
|
+
benchmarkOutcome(read("/benchmarks", { source: "artificial-analysis" }, signal)),
|
|
2152
|
+
benchmarkOutcome(read("/benchmarks", { source: "design-arena", arena: "agents" }, signal))
|
|
1789
2153
|
]));
|
|
1790
2154
|
const observedAt = (options.now?.() ?? new Date).toISOString();
|
|
1791
2155
|
const models = OpenRouterModelsResponseSchema.parse(modelsRaw).data;
|
|
@@ -1835,17 +2199,7 @@ function openRouterModelCatalog(options = {}) {
|
|
|
1835
2199
|
}
|
|
1836
2200
|
];
|
|
1837
2201
|
})
|
|
1838
|
-
});
|
|
1839
|
-
}
|
|
1840
|
-
};
|
|
1841
|
-
}
|
|
1842
|
-
function buildBaseHeaders(settings, apiKey) {
|
|
1843
|
-
return {
|
|
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)
|
|
2202
|
+
});
|
|
1849
2203
|
}
|
|
1850
2204
|
};
|
|
1851
2205
|
}
|
|
@@ -1885,10 +2239,26 @@ function buildOpenRouterRequestBody(input) {
|
|
|
1885
2239
|
}
|
|
1886
2240
|
});
|
|
1887
2241
|
}
|
|
2242
|
+
function chatHeaders(settings, apiKey, requestHeaders) {
|
|
2243
|
+
const headers = new Headers({
|
|
2244
|
+
"content-type": "application/json",
|
|
2245
|
+
accept: "text/event-stream"
|
|
2246
|
+
});
|
|
2247
|
+
for (const [k, v] of Object.entries(buildOpenRouterBaseHeaders(settings, apiKey))) {
|
|
2248
|
+
headers.set(k, v);
|
|
2249
|
+
}
|
|
2250
|
+
for (const [k, v] of Object.entries(settings.headers ?? {}))
|
|
2251
|
+
headers.set(k, v);
|
|
2252
|
+
for (const [k, v] of Object.entries(requestHeaders ?? {})) {
|
|
2253
|
+
if (k.toLowerCase() !== "content-type")
|
|
2254
|
+
headers.set(k, v);
|
|
2255
|
+
}
|
|
2256
|
+
return headers;
|
|
2257
|
+
}
|
|
1888
2258
|
function openRouterProvider(settings, access = {}) {
|
|
1889
2259
|
assertNoExtraBodyClash("openRouterProvider", settings.extraBody, OPENROUTER_POLICY_KEYS);
|
|
1890
2260
|
const defaultPolicy = access.defaultPolicy !== undefined ? resolveOpenRouterWirePolicy(access.defaultPolicy) : EMPTY_WIRE_POLICY;
|
|
1891
|
-
const endpoint =
|
|
2261
|
+
const endpoint = resolveOpenRouterUrl(settings.baseUrl, "/chat/completions");
|
|
1892
2262
|
const policyOf = (modelId) => {
|
|
1893
2263
|
const resolved = access.resolvePolicy?.(modelId);
|
|
1894
2264
|
return resolved !== undefined ? resolveOpenRouterWirePolicy(resolved) : defaultPolicy;
|
|
@@ -1908,16 +2278,17 @@ function openRouterProvider(settings, access = {}) {
|
|
|
1908
2278
|
...settings.extraBody !== undefined && { extraBody: settings.extraBody }
|
|
1909
2279
|
});
|
|
1910
2280
|
const apiKey = await resolveProviderApiKey(settings.apiKey);
|
|
1911
|
-
const
|
|
1912
|
-
provider: "openrouter",
|
|
2281
|
+
const answer = await sendOpenRouterRequest({
|
|
1913
2282
|
url: endpoint,
|
|
1914
|
-
|
|
1915
|
-
|
|
1916
|
-
|
|
1917
|
-
body,
|
|
2283
|
+
method: "POST",
|
|
2284
|
+
headers: chatHeaders(settings, apiKey, request.headers),
|
|
2285
|
+
body: JSON.stringify(body),
|
|
1918
2286
|
signal,
|
|
1919
|
-
...settings.fetch !== undefined && {
|
|
1920
|
-
|
|
2287
|
+
...settings.fetch !== undefined && { fetch: settings.fetch }
|
|
2288
|
+
});
|
|
2289
|
+
const response = await readProviderStreamResponse(answer, {
|
|
2290
|
+
provider: "openrouter",
|
|
2291
|
+
signal
|
|
1921
2292
|
});
|
|
1922
2293
|
const decodeOptions = {
|
|
1923
2294
|
provider: "openrouter",
|
|
@@ -1938,9 +2309,6 @@ import { z as z7 } from "zod";
|
|
|
1938
2309
|
|
|
1939
2310
|
// src/agent-runtime/providers/openrouter-catalog.ts
|
|
1940
2311
|
import { z as z5 } from "zod";
|
|
1941
|
-
var Price = z5.number().nonnegative();
|
|
1942
|
-
var NonNegativeMetric = z5.number().nonnegative();
|
|
1943
|
-
var Percentage = z5.number().min(0).max(100);
|
|
1944
2312
|
var UnknownPricingFieldSchema = z5.enum([
|
|
1945
2313
|
"prompt",
|
|
1946
2314
|
"completion",
|
|
@@ -1951,23 +2319,23 @@ var UnknownPricingFieldSchema = z5.enum([
|
|
|
1951
2319
|
"cacheWrite1h"
|
|
1952
2320
|
]);
|
|
1953
2321
|
var ConditionalPricingCeilingSchema = z5.strictObject({
|
|
1954
|
-
promptUsdPerMillion:
|
|
1955
|
-
completionUsdPerMillion:
|
|
1956
|
-
cacheReadUsdPerMillion:
|
|
1957
|
-
cacheWriteUsdPerMillion:
|
|
1958
|
-
cacheWrite1hUsdPerMillion:
|
|
1959
|
-
requestUsd:
|
|
1960
|
-
imageUsd:
|
|
2322
|
+
promptUsdPerMillion: NonNegativeNum.optional(),
|
|
2323
|
+
completionUsdPerMillion: NonNegativeNum.optional(),
|
|
2324
|
+
cacheReadUsdPerMillion: NonNegativeNum.optional(),
|
|
2325
|
+
cacheWriteUsdPerMillion: NonNegativeNum.optional(),
|
|
2326
|
+
cacheWrite1hUsdPerMillion: NonNegativeNum.optional(),
|
|
2327
|
+
requestUsd: NonNegativeNum.optional(),
|
|
2328
|
+
imageUsd: NonNegativeNum.optional()
|
|
1961
2329
|
});
|
|
1962
2330
|
var OpenRouterPricingTierSchema = z5.strictObject({
|
|
1963
2331
|
minPromptTokens: z5.int().positive(),
|
|
1964
|
-
promptUsdPerMillion:
|
|
1965
|
-
completionUsdPerMillion:
|
|
1966
|
-
cacheReadUsdPerMillion:
|
|
1967
|
-
cacheWriteUsdPerMillion:
|
|
1968
|
-
cacheWrite1hUsdPerMillion:
|
|
1969
|
-
requestUsd:
|
|
1970
|
-
imageUsd:
|
|
2332
|
+
promptUsdPerMillion: NonNegativeNum.optional(),
|
|
2333
|
+
completionUsdPerMillion: NonNegativeNum.optional(),
|
|
2334
|
+
cacheReadUsdPerMillion: NonNegativeNum.optional(),
|
|
2335
|
+
cacheWriteUsdPerMillion: NonNegativeNum.optional(),
|
|
2336
|
+
cacheWrite1hUsdPerMillion: NonNegativeNum.optional(),
|
|
2337
|
+
requestUsd: NonNegativeNum.optional(),
|
|
2338
|
+
imageUsd: NonNegativeNum.optional(),
|
|
1971
2339
|
unknownPricingFields: z5.array(UnknownPricingFieldSchema).min(1).optional()
|
|
1972
2340
|
});
|
|
1973
2341
|
var OpenRouterModelAliasTargetSchema = z5.strictObject({
|
|
@@ -1980,17 +2348,17 @@ var OpenRouterModelReasoningMetaSchema = z5.strictObject({
|
|
|
1980
2348
|
});
|
|
1981
2349
|
var OpenRouterEndpointSchema = z5.strictObject({
|
|
1982
2350
|
provider: z5.string().min(1),
|
|
1983
|
-
contextLength:
|
|
1984
|
-
maxCompletionTokens:
|
|
1985
|
-
promptUsdPerMillion:
|
|
1986
|
-
completionUsdPerMillion:
|
|
1987
|
-
cacheReadUsdPerMillion:
|
|
1988
|
-
cacheWriteUsdPerMillion:
|
|
1989
|
-
cacheWrite1hUsdPerMillion:
|
|
2351
|
+
contextLength: NonNegativeInt.optional(),
|
|
2352
|
+
maxCompletionTokens: NonNegativeInt.optional(),
|
|
2353
|
+
promptUsdPerMillion: NonNegativeNum.optional(),
|
|
2354
|
+
completionUsdPerMillion: NonNegativeNum.optional(),
|
|
2355
|
+
cacheReadUsdPerMillion: NonNegativeNum.optional(),
|
|
2356
|
+
cacheWriteUsdPerMillion: NonNegativeNum.optional(),
|
|
2357
|
+
cacheWrite1hUsdPerMillion: NonNegativeNum.optional(),
|
|
1990
2358
|
supportedParameters: z5.array(z5.string()),
|
|
1991
2359
|
status: z5.int().optional(),
|
|
1992
|
-
latencyP50Ms:
|
|
1993
|
-
throughputP50:
|
|
2360
|
+
latencyP50Ms: NonNegativeNum.optional(),
|
|
2361
|
+
throughputP50: NonNegativeNum.optional(),
|
|
1994
2362
|
uptime1d: Percentage.optional(),
|
|
1995
2363
|
tag: z5.string().min(1).optional()
|
|
1996
2364
|
});
|
|
@@ -2004,17 +2372,17 @@ var OpenRouterSnapshotModelSchema = z5.strictObject({
|
|
|
2004
2372
|
inputModalities: z5.array(z5.string().min(1)).default([]),
|
|
2005
2373
|
outputModalities: z5.array(z5.string().min(1)).optional(),
|
|
2006
2374
|
tokenizer: z5.string().min(1).optional(),
|
|
2007
|
-
contextLength:
|
|
2008
|
-
topProviderContextLength:
|
|
2009
|
-
maxCompletionTokens:
|
|
2375
|
+
contextLength: NonNegativeInt.optional(),
|
|
2376
|
+
topProviderContextLength: NonNegativeInt.optional(),
|
|
2377
|
+
maxCompletionTokens: NonNegativeInt.optional(),
|
|
2010
2378
|
reasoning: OpenRouterModelReasoningMetaSchema.optional(),
|
|
2011
|
-
promptUsdPerMillion:
|
|
2012
|
-
completionUsdPerMillion:
|
|
2013
|
-
requestUsd:
|
|
2014
|
-
imageUsd:
|
|
2015
|
-
cacheReadUsdPerMillion:
|
|
2016
|
-
cacheWriteUsdPerMillion:
|
|
2017
|
-
cacheWrite1hUsdPerMillion:
|
|
2379
|
+
promptUsdPerMillion: NonNegativeNum.optional(),
|
|
2380
|
+
completionUsdPerMillion: NonNegativeNum.optional(),
|
|
2381
|
+
requestUsd: NonNegativeNum.optional(),
|
|
2382
|
+
imageUsd: NonNegativeNum.optional(),
|
|
2383
|
+
cacheReadUsdPerMillion: NonNegativeNum.optional(),
|
|
2384
|
+
cacheWriteUsdPerMillion: NonNegativeNum.optional(),
|
|
2385
|
+
cacheWrite1hUsdPerMillion: NonNegativeNum.optional(),
|
|
2018
2386
|
pricingTiers: z5.array(OpenRouterPricingTierSchema).optional(),
|
|
2019
2387
|
hasConditionalPricing: z5.boolean().optional(),
|
|
2020
2388
|
unknownPricingFields: z5.array(UnknownPricingFieldSchema).min(1).optional(),
|
|
@@ -2074,16 +2442,27 @@ function mapSnapshotModel(model, endpoints) {
|
|
|
2074
2442
|
...endpoints !== undefined && { endpoints: [...endpoints] }
|
|
2075
2443
|
};
|
|
2076
2444
|
}
|
|
2077
|
-
async function
|
|
2078
|
-
|
|
2079
|
-
const
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
|
|
2445
|
+
async function readOpenRouterCatalog(options, schema, path) {
|
|
2446
|
+
const timeoutMs = options.timeoutMs ?? 1e4;
|
|
2447
|
+
const response = await openRouterRequestJson({
|
|
2448
|
+
path,
|
|
2449
|
+
schema,
|
|
2450
|
+
timeoutMs,
|
|
2451
|
+
...options.signal !== undefined && { signal: options.signal },
|
|
2452
|
+
...options.baseUrl !== undefined && { baseUrl: options.baseUrl },
|
|
2083
2453
|
...options.apiKey !== undefined && { apiKey: options.apiKey },
|
|
2084
|
-
|
|
2085
|
-
...options.maxResponseBytes !== undefined && {
|
|
2086
|
-
|
|
2454
|
+
...options.fetch !== undefined && { fetch: options.fetch },
|
|
2455
|
+
...options.maxResponseBytes !== undefined && {
|
|
2456
|
+
maxResponseBytes: options.maxResponseBytes
|
|
2457
|
+
}
|
|
2458
|
+
});
|
|
2459
|
+
return response.data;
|
|
2460
|
+
}
|
|
2461
|
+
async function fetchOpenRouterModelEndpoints(modelId, options = {}) {
|
|
2462
|
+
assertValidOpenRouterApiKey(options.apiKey);
|
|
2463
|
+
validateOpenRouterBaseUrl(options.baseUrl);
|
|
2464
|
+
const path = openRouterEndpointsPath(modelId);
|
|
2465
|
+
const parsed = await readOpenRouterCatalog(options, OpenRouterEndpointsResponseSchema, path);
|
|
2087
2466
|
return parsed.data.endpoints.map((endpoint) => {
|
|
2088
2467
|
const prompt = usdPerMillion(endpoint.pricing?.prompt);
|
|
2089
2468
|
const completion = usdPerMillion(endpoint.pricing?.completion);
|
|
@@ -2118,16 +2497,11 @@ async function loadOpenRouterCatalogSnapshot(options = {}) {
|
|
|
2118
2497
|
const concurrency = options.concurrency ?? 4;
|
|
2119
2498
|
if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > 16)
|
|
2120
2499
|
throw new RangeError("concurrency must be an integer from 1 to 16");
|
|
2121
|
-
|
|
2500
|
+
assertValidOpenRouterApiKey(options.apiKey);
|
|
2501
|
+
validateOpenRouterBaseUrl(options.baseUrl);
|
|
2122
2502
|
assertValidOpenRouterEndpointsFor(options.endpointsFor);
|
|
2123
2503
|
const observedAt = (options.now?.() ?? new Date).toISOString();
|
|
2124
|
-
const listing =
|
|
2125
|
-
fetcher: options.fetcher ?? fetch,
|
|
2126
|
-
url: new URL("https://openrouter.ai/api/v1/models"),
|
|
2127
|
-
...options.apiKey !== undefined && { apiKey: options.apiKey },
|
|
2128
|
-
signal,
|
|
2129
|
-
...options.maxResponseBytes !== undefined && { maxBytes: options.maxResponseBytes }
|
|
2130
|
-
}))).data;
|
|
2504
|
+
const listing = (await readOpenRouterCatalog(options, OpenRouterModelsResponseSchema, "/models")).data;
|
|
2131
2505
|
const wanted = [...new Set(options.endpointsFor ?? [])];
|
|
2132
2506
|
const endpoints = new Map;
|
|
2133
2507
|
const stop = new AbortController;
|
|
@@ -2161,20 +2535,17 @@ async function loadOpenRouterCatalogSnapshot(options = {}) {
|
|
|
2161
2535
|
|
|
2162
2536
|
// src/agent-runtime/providers/openrouter-catalog-query.ts
|
|
2163
2537
|
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
2538
|
var OpenRouterModelPricingCeilingSchema = z6.strictObject({
|
|
2168
|
-
promptUsdPerMillion:
|
|
2169
|
-
completionUsdPerMillion:
|
|
2170
|
-
cacheWriteUsdPerMillion:
|
|
2171
|
-
requestUsd:
|
|
2539
|
+
promptUsdPerMillion: NonNegativeNum.optional(),
|
|
2540
|
+
completionUsdPerMillion: NonNegativeNum.optional(),
|
|
2541
|
+
cacheWriteUsdPerMillion: NonNegativeNum.optional(),
|
|
2542
|
+
requestUsd: NonNegativeNum.optional()
|
|
2172
2543
|
});
|
|
2173
2544
|
var OpenRouterEndpointSummarySchema = z6.strictObject({
|
|
2174
|
-
providers:
|
|
2175
|
-
latencyP50Ms:
|
|
2176
|
-
throughputP50:
|
|
2177
|
-
uptime1d:
|
|
2545
|
+
providers: NonNegativeInt,
|
|
2546
|
+
latencyP50Ms: NonNegativeNum.optional(),
|
|
2547
|
+
throughputP50: NonNegativeNum.optional(),
|
|
2548
|
+
uptime1d: Percentage.optional()
|
|
2178
2549
|
});
|
|
2179
2550
|
function effectiveContextLength(model) {
|
|
2180
2551
|
if (model.contextLength !== undefined && model.topProviderContextLength !== undefined) {
|
|
@@ -2479,15 +2850,14 @@ function listOpenRouterModels(snapshot, filter) {
|
|
|
2479
2850
|
}
|
|
2480
2851
|
|
|
2481
2852
|
// src/agent-runtime/providers/openrouter-admission.ts
|
|
2482
|
-
var Usd2 = z7.number().nonnegative();
|
|
2483
2853
|
var OpenRouterAdmissionPolicySchema = z7.strictObject({
|
|
2484
2854
|
maxSnapshotAgeMs: z7.int().positive(),
|
|
2485
2855
|
requiredParameters: z7.array(z7.string().min(1)).default([]),
|
|
2486
2856
|
requiredInputModalities: z7.array(z7.string().min(1)).default([]),
|
|
2487
|
-
minContextLength:
|
|
2488
|
-
maxPromptUsdPerMillion:
|
|
2489
|
-
maxCompletionUsdPerMillion:
|
|
2490
|
-
maxCacheWriteUsdPerMillion:
|
|
2857
|
+
minContextLength: NonNegativeInt.optional(),
|
|
2858
|
+
maxPromptUsdPerMillion: NonNegativeNum.optional(),
|
|
2859
|
+
maxCompletionUsdPerMillion: NonNegativeNum.optional(),
|
|
2860
|
+
maxCacheWriteUsdPerMillion: NonNegativeNum.optional(),
|
|
2491
2861
|
requireLiveEndpoint: z7.boolean().default(false)
|
|
2492
2862
|
});
|
|
2493
2863
|
var OpenRouterAdmissionReasonSchema = z7.enum([
|
|
@@ -2609,6 +2979,270 @@ function evaluateOpenRouterModelAdmission(input) {
|
|
|
2609
2979
|
}
|
|
2610
2980
|
return { state: "admitted" };
|
|
2611
2981
|
}
|
|
2982
|
+
// src/agent-runtime/providers/openrouter-audio.ts
|
|
2983
|
+
import { z as z9 } from "zod";
|
|
2984
|
+
|
|
2985
|
+
// src/agent-runtime/providers/openrouter-wire.ts
|
|
2986
|
+
import { z as z8 } from "zod";
|
|
2987
|
+
var OpenRouterUsageSchema = z8.object({
|
|
2988
|
+
prompt_tokens: NonNegativeInt.optional(),
|
|
2989
|
+
completion_tokens: NonNegativeInt.optional(),
|
|
2990
|
+
input_tokens: NonNegativeInt.optional(),
|
|
2991
|
+
output_tokens: NonNegativeInt.optional(),
|
|
2992
|
+
total_tokens: NonNegativeInt.optional(),
|
|
2993
|
+
seconds: NonNegativeNum.optional(),
|
|
2994
|
+
cost: NonNegativeNum.optional(),
|
|
2995
|
+
is_byok: z8.boolean().optional()
|
|
2996
|
+
}).loose();
|
|
2997
|
+
function responseMetaOf(response) {
|
|
2998
|
+
return {
|
|
2999
|
+
status: response.status,
|
|
3000
|
+
...response.generationId !== undefined && { generationId: response.generationId },
|
|
3001
|
+
...response.requestId !== undefined && { requestId: response.requestId },
|
|
3002
|
+
...response.costUsd !== undefined && { costUsd: response.costUsd },
|
|
3003
|
+
headers: response.headers
|
|
3004
|
+
};
|
|
3005
|
+
}
|
|
3006
|
+
var RangedNumber = z8.custom((value) => typeof value === "number", {
|
|
3007
|
+
error: "expected a number"
|
|
3008
|
+
});
|
|
3009
|
+
var ExtraBodySchema = z8.record(z8.string(), z8.unknown()).readonly();
|
|
3010
|
+
function parseOpenRouterRequest(caller, schema, input) {
|
|
3011
|
+
const parsed = schema.safeParse(input);
|
|
3012
|
+
if (!parsed.success) {
|
|
3013
|
+
const issues = parsed.error.issues.map((issue) => `${issue.path.join(".") || "(input)"}: ${issue.message}`).join("; ");
|
|
3014
|
+
throw new TypeError(`${caller}: invalid request: ${issues}`, { cause: parsed.error });
|
|
3015
|
+
}
|
|
3016
|
+
return parsed.data;
|
|
3017
|
+
}
|
|
3018
|
+
|
|
3019
|
+
// src/agent-runtime/providers/openrouter-audio.ts
|
|
3020
|
+
var STT_OWNED_KEYS = [
|
|
3021
|
+
"model",
|
|
3022
|
+
"file",
|
|
3023
|
+
"input_audio",
|
|
3024
|
+
"source_url",
|
|
3025
|
+
"language",
|
|
3026
|
+
"prompt",
|
|
3027
|
+
"temperature",
|
|
3028
|
+
"response_format",
|
|
3029
|
+
"timestamp_granularities",
|
|
3030
|
+
"timestamp_granularities[]",
|
|
3031
|
+
"diarize",
|
|
3032
|
+
"provider"
|
|
3033
|
+
];
|
|
3034
|
+
var SpeakerFields = {
|
|
3035
|
+
speaker: NonNegativeInt.optional(),
|
|
3036
|
+
speaker_label: z9.string().optional(),
|
|
3037
|
+
channel: NonNegativeInt.optional()
|
|
3038
|
+
};
|
|
3039
|
+
var TranscriptionSegmentSchema = z9.object({
|
|
3040
|
+
id: NonNegativeInt.optional(),
|
|
3041
|
+
start: NonNegativeNum,
|
|
3042
|
+
end: NonNegativeNum,
|
|
3043
|
+
text: z9.string(),
|
|
3044
|
+
...SpeakerFields
|
|
3045
|
+
}).loose();
|
|
3046
|
+
var TranscriptionWordSchema = z9.object({
|
|
3047
|
+
word: z9.string(),
|
|
3048
|
+
start: NonNegativeNum,
|
|
3049
|
+
end: NonNegativeNum,
|
|
3050
|
+
confidence: Probability.optional(),
|
|
3051
|
+
type: z9.enum(["word", "audio_event"]).optional(),
|
|
3052
|
+
...SpeakerFields
|
|
3053
|
+
}).loose();
|
|
3054
|
+
var OpenRouterAudioTranscriptionResponseSchema = z9.object({
|
|
3055
|
+
text: z9.string(),
|
|
3056
|
+
task: z9.string().optional(),
|
|
3057
|
+
language: z9.string().optional(),
|
|
3058
|
+
duration: NonNegativeNum.optional(),
|
|
3059
|
+
segments: z9.array(TranscriptionSegmentSchema).optional(),
|
|
3060
|
+
words: z9.array(TranscriptionWordSchema).optional(),
|
|
3061
|
+
usage: OpenRouterUsageSchema.optional()
|
|
3062
|
+
}).loose();
|
|
3063
|
+
var AudioSourceSchema = z9.discriminatedUnion("kind", [
|
|
3064
|
+
z9.object({ kind: z9.literal("base64"), data: z9.string(), format: z9.string() }).readonly(),
|
|
3065
|
+
z9.object({ kind: z9.literal("url"), url: z9.string(), format: z9.string().optional() }).readonly(),
|
|
3066
|
+
z9.object({
|
|
3067
|
+
kind: z9.literal("file"),
|
|
3068
|
+
data: z9.union([z9.instanceof(Blob), z9.instanceof(Uint8Array), z9.instanceof(ArrayBuffer)]),
|
|
3069
|
+
filename: z9.string().optional(),
|
|
3070
|
+
mimeType: z9.string().optional()
|
|
3071
|
+
}).readonly()
|
|
3072
|
+
]);
|
|
3073
|
+
var TranscriptionRequestSchema = z9.object({
|
|
3074
|
+
model: z9.string(),
|
|
3075
|
+
audio: AudioSourceSchema,
|
|
3076
|
+
language: z9.string().optional(),
|
|
3077
|
+
prompt: z9.string().optional(),
|
|
3078
|
+
temperature: RangedNumber.optional(),
|
|
3079
|
+
responseFormat: z9.enum(["json", "verbose_json"]).optional(),
|
|
3080
|
+
timestampGranularities: z9.array(z9.enum(["segment", "word"])).readonly().optional(),
|
|
3081
|
+
diarize: z9.boolean().optional(),
|
|
3082
|
+
provider: OpenRouterProviderRoutingSchema.optional(),
|
|
3083
|
+
extraBody: ExtraBodySchema.optional()
|
|
3084
|
+
});
|
|
3085
|
+
function toSafeBlob(data, mimeType) {
|
|
3086
|
+
if (data instanceof Blob) {
|
|
3087
|
+
return mimeType !== undefined && data.type !== mimeType ? new Blob([data], { type: mimeType }) : data;
|
|
3088
|
+
}
|
|
3089
|
+
const source = data instanceof Uint8Array ? data : new Uint8Array(data);
|
|
3090
|
+
const copy = new Uint8Array(source.byteLength);
|
|
3091
|
+
copy.set(source);
|
|
3092
|
+
return mimeType !== undefined ? new Blob([copy], { type: mimeType }) : new Blob([copy]);
|
|
3093
|
+
}
|
|
3094
|
+
function hasUnsafeFilenameChar(value) {
|
|
3095
|
+
for (let i = 0;i < value.length; i += 1) {
|
|
3096
|
+
const code = value.charCodeAt(i);
|
|
3097
|
+
const ch = value[i];
|
|
3098
|
+
if (code < 32 || code === 127 || ch === '"' || ch === "\\" || ch === "/")
|
|
3099
|
+
return true;
|
|
3100
|
+
}
|
|
3101
|
+
return false;
|
|
3102
|
+
}
|
|
3103
|
+
function validateFilename(filename) {
|
|
3104
|
+
const trimmed = filename.trim();
|
|
3105
|
+
if (trimmed.length === 0 || hasUnsafeFilenameChar(trimmed)) {
|
|
3106
|
+
throw new TypeError("openRouterAudioTranscription: filename must be non-empty and free of path separators, quotes, or control characters");
|
|
3107
|
+
}
|
|
3108
|
+
return trimmed;
|
|
3109
|
+
}
|
|
3110
|
+
function appendFormExtraBody(form, extraBody) {
|
|
3111
|
+
for (const [key, value] of Object.entries(extraBody)) {
|
|
3112
|
+
if (value === undefined)
|
|
3113
|
+
continue;
|
|
3114
|
+
if (value === null || typeof value === "function" || typeof value === "symbol") {
|
|
3115
|
+
throw new TypeError(`openRouterAudioTranscription: unsupported multipart extraBody value for "${key}"`);
|
|
3116
|
+
}
|
|
3117
|
+
if (typeof value === "number" && !Number.isFinite(value)) {
|
|
3118
|
+
throw new TypeError(`openRouterAudioTranscription: extraBody["${key}"] must be a finite number`);
|
|
3119
|
+
}
|
|
3120
|
+
if (value instanceof Blob) {
|
|
3121
|
+
form.append(key, value);
|
|
3122
|
+
} else if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
|
|
3123
|
+
form.append(key, String(value));
|
|
3124
|
+
} else if (Array.isArray(value) || isRecord(value)) {
|
|
3125
|
+
form.append(key, JSON.stringify(value));
|
|
3126
|
+
} else {
|
|
3127
|
+
throw new TypeError(`openRouterAudioTranscription: unsupported multipart extraBody value for "${key}"`);
|
|
3128
|
+
}
|
|
3129
|
+
}
|
|
3130
|
+
}
|
|
3131
|
+
function buildTranscriptionBody(input, model, provider) {
|
|
3132
|
+
if (input.audio.kind === "file") {
|
|
3133
|
+
const form = new FormData;
|
|
3134
|
+
const defaultName = typeof File === "function" && input.audio.data instanceof File && input.audio.data.name ? input.audio.data.name : "audio";
|
|
3135
|
+
const filename = validateFilename(input.audio.filename ?? defaultName);
|
|
3136
|
+
form.append("file", toSafeBlob(input.audio.data, input.audio.mimeType), filename);
|
|
3137
|
+
form.append("model", model);
|
|
3138
|
+
if (input.language !== undefined)
|
|
3139
|
+
form.append("language", input.language);
|
|
3140
|
+
if (input.prompt !== undefined)
|
|
3141
|
+
form.append("prompt", input.prompt);
|
|
3142
|
+
if (input.temperature !== undefined)
|
|
3143
|
+
form.append("temperature", String(input.temperature));
|
|
3144
|
+
if (input.responseFormat !== undefined)
|
|
3145
|
+
form.append("response_format", input.responseFormat);
|
|
3146
|
+
if (input.timestampGranularities !== undefined) {
|
|
3147
|
+
for (const granularity of input.timestampGranularities) {
|
|
3148
|
+
form.append("timestamp_granularities[]", granularity);
|
|
3149
|
+
}
|
|
3150
|
+
}
|
|
3151
|
+
if (input.diarize !== undefined)
|
|
3152
|
+
form.append("diarize", String(input.diarize));
|
|
3153
|
+
if (provider !== undefined)
|
|
3154
|
+
form.append("provider", JSON.stringify(provider));
|
|
3155
|
+
if (input.extraBody !== undefined)
|
|
3156
|
+
appendFormExtraBody(form, input.extraBody);
|
|
3157
|
+
return form;
|
|
3158
|
+
}
|
|
3159
|
+
const inputAudio = input.audio.kind === "base64" ? { data: input.audio.data, format: input.audio.format } : {
|
|
3160
|
+
url: assertOpenRouterHttpUrl("audio.url", input.audio.url),
|
|
3161
|
+
...input.audio.format !== undefined && { format: input.audio.format }
|
|
3162
|
+
};
|
|
3163
|
+
return {
|
|
3164
|
+
...input.extraBody ?? {},
|
|
3165
|
+
model,
|
|
3166
|
+
input_audio: inputAudio,
|
|
3167
|
+
...input.language !== undefined && { language: input.language },
|
|
3168
|
+
...input.prompt !== undefined && { prompt: input.prompt },
|
|
3169
|
+
...input.temperature !== undefined && { temperature: input.temperature },
|
|
3170
|
+
...input.responseFormat !== undefined && { response_format: input.responseFormat },
|
|
3171
|
+
...input.timestampGranularities !== undefined && {
|
|
3172
|
+
timestamp_granularities: [...input.timestampGranularities]
|
|
3173
|
+
},
|
|
3174
|
+
...input.diarize !== undefined && { diarize: input.diarize },
|
|
3175
|
+
...provider !== undefined && { provider }
|
|
3176
|
+
};
|
|
3177
|
+
}
|
|
3178
|
+
function speakerOf(wire) {
|
|
3179
|
+
return {
|
|
3180
|
+
...wire.speaker !== undefined && { speaker: wire.speaker },
|
|
3181
|
+
...wire.speaker_label !== undefined && { speakerLabel: wire.speaker_label },
|
|
3182
|
+
...wire.channel !== undefined && { channel: wire.channel }
|
|
3183
|
+
};
|
|
3184
|
+
}
|
|
3185
|
+
function toSegment(wire) {
|
|
3186
|
+
return {
|
|
3187
|
+
...wire.id !== undefined && { id: wire.id },
|
|
3188
|
+
start: wire.start,
|
|
3189
|
+
end: wire.end,
|
|
3190
|
+
text: wire.text,
|
|
3191
|
+
...speakerOf(wire)
|
|
3192
|
+
};
|
|
3193
|
+
}
|
|
3194
|
+
function toWord(wire) {
|
|
3195
|
+
return {
|
|
3196
|
+
word: wire.word,
|
|
3197
|
+
start: wire.start,
|
|
3198
|
+
end: wire.end,
|
|
3199
|
+
...wire.confidence !== undefined && { confidence: wire.confidence },
|
|
3200
|
+
...wire.type !== undefined && { type: wire.type },
|
|
3201
|
+
...speakerOf(wire)
|
|
3202
|
+
};
|
|
3203
|
+
}
|
|
3204
|
+
async function openRouterAudioTranscription(input) {
|
|
3205
|
+
assertOpenRouterDirectAuth(input);
|
|
3206
|
+
const request = parseOpenRouterRequest("openRouterAudioTranscription", TranscriptionRequestSchema, input);
|
|
3207
|
+
const model = assertNonEmptyOpenRouterField("openRouterAudioTranscription", "model", request.model);
|
|
3208
|
+
if (request.audio.kind === "base64") {
|
|
3209
|
+
if (request.audio.data.trim().length === 0 || request.audio.format.trim().length === 0) {
|
|
3210
|
+
throw new TypeError("openRouterAudioTranscription: base64 audio requires non-empty data and format");
|
|
3211
|
+
}
|
|
3212
|
+
}
|
|
3213
|
+
if (request.audio.kind === "url" && request.audio.format?.trim().length === 0) {
|
|
3214
|
+
throw new TypeError("openRouterAudioTranscription: url audio format must be non-empty");
|
|
3215
|
+
}
|
|
3216
|
+
if (request.temperature !== undefined && (!Number.isFinite(request.temperature) || request.temperature < 0 || request.temperature > 1)) {
|
|
3217
|
+
throw new RangeError("openRouterAudioTranscription: temperature must be between 0 and 1");
|
|
3218
|
+
}
|
|
3219
|
+
if (request.diarize === true && request.responseFormat !== "verbose_json") {
|
|
3220
|
+
throw new TypeError('openRouterAudioTranscription: diarize requires responseFormat: "verbose_json"');
|
|
3221
|
+
}
|
|
3222
|
+
assertNoExtraBodyClash("openRouterAudioTranscription", request.extraBody, STT_OWNED_KEYS);
|
|
3223
|
+
const provider = request.provider !== undefined ? serializeOpenRouterProviderRouting(request.provider) : undefined;
|
|
3224
|
+
const body = buildTranscriptionBody(request, model, provider);
|
|
3225
|
+
const response = await openRouterRequestJson({
|
|
3226
|
+
...pickOpenRouterTransport(input),
|
|
3227
|
+
path: "/audio/transcriptions",
|
|
3228
|
+
method: "POST",
|
|
3229
|
+
body,
|
|
3230
|
+
schema: OpenRouterAudioTranscriptionResponseSchema
|
|
3231
|
+
});
|
|
3232
|
+
return {
|
|
3233
|
+
text: response.data.text,
|
|
3234
|
+
...response.data.task !== undefined && { task: response.data.task },
|
|
3235
|
+
...response.data.language !== undefined && { language: response.data.language },
|
|
3236
|
+
...response.data.duration !== undefined && { duration: response.data.duration },
|
|
3237
|
+
...response.data.segments !== undefined && {
|
|
3238
|
+
segments: response.data.segments.map(toSegment)
|
|
3239
|
+
},
|
|
3240
|
+
...response.data.words !== undefined && { words: response.data.words.map(toWord) },
|
|
3241
|
+
...response.data.usage !== undefined && { usage: response.data.usage },
|
|
3242
|
+
raw: response.data,
|
|
3243
|
+
...responseMetaOf(response)
|
|
3244
|
+
};
|
|
3245
|
+
}
|
|
2612
3246
|
// src/agent-runtime/providers/openrouter-catalog-cache.ts
|
|
2613
3247
|
var DEFAULT_TIMEOUT_MS = 1e4;
|
|
2614
3248
|
var DEFAULT_FRESH_MS = 15 * 60000;
|
|
@@ -2673,7 +3307,8 @@ function validateCacheOptions(options) {
|
|
|
2673
3307
|
if (options.maxResponseBytes !== undefined) {
|
|
2674
3308
|
assertPositiveSafeInteger("maxResponseBytes", options.maxResponseBytes, RangeError);
|
|
2675
3309
|
}
|
|
2676
|
-
|
|
3310
|
+
assertValidOpenRouterApiKey(options.apiKey);
|
|
3311
|
+
validateOpenRouterBaseUrl(options.baseUrl);
|
|
2677
3312
|
assertValidOpenRouterEndpointsFor(options.endpointsFor);
|
|
2678
3313
|
return {
|
|
2679
3314
|
timeoutMs,
|
|
@@ -2845,46 +3480,834 @@ function createOpenRouterCatalogCache(options = {}) {
|
|
|
2845
3480
|
}
|
|
2846
3481
|
};
|
|
2847
3482
|
}
|
|
3483
|
+
// src/agent-runtime/providers/openrouter-media.ts
|
|
3484
|
+
import { z as z10 } from "zod";
|
|
3485
|
+
|
|
3486
|
+
// src/agent-runtime/providers/openrouter-stream.ts
|
|
3487
|
+
function wrapStreamWithCallerAbort(source, callerSignal, onRelease) {
|
|
3488
|
+
if (!callerSignal) {
|
|
3489
|
+
onRelease();
|
|
3490
|
+
return source;
|
|
3491
|
+
}
|
|
3492
|
+
const reader = source.getReader();
|
|
3493
|
+
let settled = false;
|
|
3494
|
+
const detach = () => {
|
|
3495
|
+
if (settled)
|
|
3496
|
+
return;
|
|
3497
|
+
settled = true;
|
|
3498
|
+
callerSignal.removeEventListener("abort", onAbort);
|
|
3499
|
+
onRelease();
|
|
3500
|
+
};
|
|
3501
|
+
const onAbort = () => {
|
|
3502
|
+
detach();
|
|
3503
|
+
reader.cancel(abortReason(callerSignal)).catch(() => {
|
|
3504
|
+
return;
|
|
3505
|
+
});
|
|
3506
|
+
};
|
|
3507
|
+
if (callerSignal.aborted) {
|
|
3508
|
+
onAbort();
|
|
3509
|
+
} else {
|
|
3510
|
+
callerSignal.addEventListener("abort", onAbort, { once: true });
|
|
3511
|
+
reader.closed.then(detach, detach);
|
|
3512
|
+
}
|
|
3513
|
+
return new ReadableStream({
|
|
3514
|
+
async pull(controller) {
|
|
3515
|
+
if (callerSignal.aborted) {
|
|
3516
|
+
detach();
|
|
3517
|
+
await reader.cancel(abortReason(callerSignal)).catch(() => {
|
|
3518
|
+
return;
|
|
3519
|
+
});
|
|
3520
|
+
controller.error(abortReason(callerSignal));
|
|
3521
|
+
return;
|
|
3522
|
+
}
|
|
3523
|
+
try {
|
|
3524
|
+
const chunk = await raceAbort(reader.read(), callerSignal);
|
|
3525
|
+
if (chunk.done) {
|
|
3526
|
+
detach();
|
|
3527
|
+
reader.releaseLock();
|
|
3528
|
+
controller.close();
|
|
3529
|
+
return;
|
|
3530
|
+
}
|
|
3531
|
+
controller.enqueue(chunk.value);
|
|
3532
|
+
} catch (error) {
|
|
3533
|
+
detach();
|
|
3534
|
+
await reader.cancel(error).catch(() => {
|
|
3535
|
+
return;
|
|
3536
|
+
});
|
|
3537
|
+
controller.error(error);
|
|
3538
|
+
}
|
|
3539
|
+
},
|
|
3540
|
+
async cancel(reason) {
|
|
3541
|
+
detach();
|
|
3542
|
+
await reader.cancel(reason).catch(() => {
|
|
3543
|
+
return;
|
|
3544
|
+
});
|
|
3545
|
+
}
|
|
3546
|
+
});
|
|
3547
|
+
}
|
|
3548
|
+
async function openRouterRequestStream(input) {
|
|
3549
|
+
const prepared = prepareOpenRouterRequest(input);
|
|
3550
|
+
input.signal?.throwIfAborted();
|
|
3551
|
+
const apiKey = await resolveOptionalOpenRouterApiKey(input.apiKey);
|
|
3552
|
+
input.signal?.throwIfAborted();
|
|
3553
|
+
const deadline = new AbortController;
|
|
3554
|
+
const timer = setTimeout(() => deadline.abort(abortError(`OpenRouter stream ${input.path} timed out after ${prepared.timeoutMs} ms`, "TimeoutError")), prepared.timeoutMs);
|
|
3555
|
+
const openLink = linkAbortSignals(input.signal, deadline.signal);
|
|
3556
|
+
const disarmOpenPhase = () => {
|
|
3557
|
+
clearTimeout(timer);
|
|
3558
|
+
openLink.release();
|
|
3559
|
+
};
|
|
3560
|
+
let response;
|
|
3561
|
+
try {
|
|
3562
|
+
const headers = assembleOpenRouterRequestHeaders(input, prepared, apiKey, undefined);
|
|
3563
|
+
response = await sendOpenRouterRequest(openRouterExchange(prepared, headers, openLink.signal));
|
|
3564
|
+
} catch (error) {
|
|
3565
|
+
disarmOpenPhase();
|
|
3566
|
+
throw error;
|
|
3567
|
+
}
|
|
3568
|
+
clearTimeout(timer);
|
|
3569
|
+
const requestId = extractProviderRequestId(response.headers);
|
|
3570
|
+
const responseHeaders = headersToRecord(response.headers);
|
|
3571
|
+
if (!response.body) {
|
|
3572
|
+
openLink.release();
|
|
3573
|
+
throw new AgentProviderError2("OpenRouter returned an empty streaming response body", {
|
|
3574
|
+
provider: "openrouter",
|
|
3575
|
+
statusCode: response.status,
|
|
3576
|
+
retryable: false,
|
|
3577
|
+
...requestId !== undefined && { requestId },
|
|
3578
|
+
responseHeaders
|
|
3579
|
+
});
|
|
3580
|
+
}
|
|
3581
|
+
const generationId = extractOpenRouterGenerationId(response.headers);
|
|
3582
|
+
const contentType = response.headers.get("content-type")?.trim() || "application/octet-stream";
|
|
3583
|
+
return {
|
|
3584
|
+
body: wrapStreamWithCallerAbort(response.body, input.signal, openLink.release),
|
|
3585
|
+
contentType,
|
|
3586
|
+
status: response.status,
|
|
3587
|
+
...generationId !== undefined && { generationId },
|
|
3588
|
+
...requestId !== undefined && { requestId },
|
|
3589
|
+
headers: responseHeaders
|
|
3590
|
+
};
|
|
3591
|
+
}
|
|
3592
|
+
|
|
3593
|
+
// src/agent-runtime/providers/openrouter-media.ts
|
|
3594
|
+
var IMAGE_OWNED_KEYS = [
|
|
3595
|
+
"model",
|
|
3596
|
+
"prompt",
|
|
3597
|
+
"n",
|
|
3598
|
+
"aspect_ratio",
|
|
3599
|
+
"resolution",
|
|
3600
|
+
"response_format",
|
|
3601
|
+
"input_references",
|
|
3602
|
+
"provider"
|
|
3603
|
+
];
|
|
3604
|
+
var VIDEO_OWNED_KEYS = [
|
|
3605
|
+
"model",
|
|
3606
|
+
"prompt",
|
|
3607
|
+
"duration",
|
|
3608
|
+
"aspect_ratio",
|
|
3609
|
+
"resolution",
|
|
3610
|
+
"generate_audio",
|
|
3611
|
+
"frame_images",
|
|
3612
|
+
"input_references",
|
|
3613
|
+
"callback_url",
|
|
3614
|
+
"provider"
|
|
3615
|
+
];
|
|
3616
|
+
var ImageItemSchema = z10.object({
|
|
3617
|
+
b64_json: z10.string().optional(),
|
|
3618
|
+
url: z10.string().optional(),
|
|
3619
|
+
media_type: z10.string().optional()
|
|
3620
|
+
}).loose();
|
|
3621
|
+
var OpenRouterImageGenerationResponseSchema = z10.object({
|
|
3622
|
+
created: NonNegativeInt.optional(),
|
|
3623
|
+
data: z10.array(ImageItemSchema),
|
|
3624
|
+
expires_at: NonNegativeInt.optional(),
|
|
3625
|
+
usage: OpenRouterUsageSchema.optional()
|
|
3626
|
+
}).loose();
|
|
3627
|
+
var ImageGenerationRequestSchema = z10.object({
|
|
3628
|
+
model: z10.string(),
|
|
3629
|
+
prompt: z10.string(),
|
|
3630
|
+
n: RangedNumber.optional(),
|
|
3631
|
+
aspectRatio: z10.string().optional(),
|
|
3632
|
+
resolution: z10.string().optional(),
|
|
3633
|
+
responseFormat: z10.enum(["b64_json", "url"]).optional(),
|
|
3634
|
+
inputReferences: z10.array(z10.unknown()).readonly().optional(),
|
|
3635
|
+
provider: OpenRouterProviderRoutingSchema.optional(),
|
|
3636
|
+
extraBody: ExtraBodySchema.optional()
|
|
3637
|
+
});
|
|
3638
|
+
async function openRouterGenerateImages(input) {
|
|
3639
|
+
assertOpenRouterDirectAuth(input);
|
|
3640
|
+
const request = parseOpenRouterRequest("openRouterGenerateImages", ImageGenerationRequestSchema, input);
|
|
3641
|
+
const model = assertNonEmptyOpenRouterField("openRouterGenerateImages", "model", request.model);
|
|
3642
|
+
assertNonEmptyOpenRouterField("openRouterGenerateImages", "prompt", request.prompt);
|
|
3643
|
+
if (request.n !== undefined)
|
|
3644
|
+
assertPositiveSafeInteger("n", request.n);
|
|
3645
|
+
assertNoExtraBodyClash("openRouterGenerateImages", request.extraBody, IMAGE_OWNED_KEYS);
|
|
3646
|
+
const provider = request.provider !== undefined ? serializeOpenRouterProviderRouting(request.provider) : undefined;
|
|
3647
|
+
const body = {
|
|
3648
|
+
...request.extraBody ?? {},
|
|
3649
|
+
model,
|
|
3650
|
+
prompt: request.prompt,
|
|
3651
|
+
...request.n !== undefined && { n: request.n },
|
|
3652
|
+
...request.aspectRatio !== undefined && { aspect_ratio: request.aspectRatio },
|
|
3653
|
+
...request.resolution !== undefined && { resolution: request.resolution },
|
|
3654
|
+
...request.responseFormat !== undefined && { response_format: request.responseFormat },
|
|
3655
|
+
...request.inputReferences !== undefined && {
|
|
3656
|
+
input_references: [...request.inputReferences]
|
|
3657
|
+
},
|
|
3658
|
+
...provider !== undefined && { provider }
|
|
3659
|
+
};
|
|
3660
|
+
const response = await openRouterRequestJson({
|
|
3661
|
+
...pickOpenRouterTransport(input),
|
|
3662
|
+
path: "/images",
|
|
3663
|
+
method: "POST",
|
|
3664
|
+
body,
|
|
3665
|
+
schema: OpenRouterImageGenerationResponseSchema
|
|
3666
|
+
});
|
|
3667
|
+
return {
|
|
3668
|
+
...response.data.created !== undefined && { created: response.data.created },
|
|
3669
|
+
images: response.data.data,
|
|
3670
|
+
...response.data.expires_at !== undefined && { expiresAt: response.data.expires_at },
|
|
3671
|
+
...response.data.usage !== undefined && { usage: response.data.usage },
|
|
3672
|
+
raw: response.data,
|
|
3673
|
+
...responseMetaOf(response)
|
|
3674
|
+
};
|
|
3675
|
+
}
|
|
3676
|
+
var OpenRouterVideoSubmitResponseSchema = z10.object({
|
|
3677
|
+
id: z10.string().min(1),
|
|
3678
|
+
status: z10.string().min(1),
|
|
3679
|
+
polling_url: z10.string().min(1).optional()
|
|
3680
|
+
}).loose();
|
|
3681
|
+
var OpenRouterVideoStatusResponseSchema = z10.object({
|
|
3682
|
+
id: z10.string().min(1),
|
|
3683
|
+
status: z10.string().min(1),
|
|
3684
|
+
generation_id: z10.string().min(1).optional(),
|
|
3685
|
+
urls: z10.array(z10.string()).optional(),
|
|
3686
|
+
unsigned_urls: z10.array(z10.string()).optional(),
|
|
3687
|
+
expires_at: NonNegativeInt.optional(),
|
|
3688
|
+
usage: OpenRouterUsageSchema.optional(),
|
|
3689
|
+
error: z10.unknown().optional()
|
|
3690
|
+
}).loose();
|
|
3691
|
+
var VideoSubmitRequestSchema = z10.object({
|
|
3692
|
+
model: z10.string(),
|
|
3693
|
+
prompt: z10.string(),
|
|
3694
|
+
duration: RangedNumber.optional(),
|
|
3695
|
+
aspectRatio: z10.string().optional(),
|
|
3696
|
+
resolution: z10.string().optional(),
|
|
3697
|
+
generateAudio: z10.boolean().optional(),
|
|
3698
|
+
frameImages: z10.array(z10.unknown()).readonly().optional(),
|
|
3699
|
+
inputReferences: z10.array(z10.unknown()).readonly().optional(),
|
|
3700
|
+
callbackUrl: z10.string().optional(),
|
|
3701
|
+
provider: OpenRouterProviderRoutingSchema.optional(),
|
|
3702
|
+
extraBody: ExtraBodySchema.optional()
|
|
3703
|
+
});
|
|
3704
|
+
var VideoJobRequestSchema = z10.object({
|
|
3705
|
+
jobId: z10.string(),
|
|
3706
|
+
index: RangedNumber.optional()
|
|
3707
|
+
});
|
|
3708
|
+
async function openRouterSubmitVideo(input) {
|
|
3709
|
+
assertOpenRouterDirectAuth(input);
|
|
3710
|
+
const request = parseOpenRouterRequest("openRouterSubmitVideo", VideoSubmitRequestSchema, input);
|
|
3711
|
+
const model = assertNonEmptyOpenRouterField("openRouterSubmitVideo", "model", request.model);
|
|
3712
|
+
assertNonEmptyOpenRouterField("openRouterSubmitVideo", "prompt", request.prompt);
|
|
3713
|
+
if (request.duration !== undefined && (!Number.isFinite(request.duration) || request.duration <= 0)) {
|
|
3714
|
+
throw new RangeError("openRouterSubmitVideo: duration must be a positive finite number");
|
|
3715
|
+
}
|
|
3716
|
+
const callbackUrl = request.callbackUrl !== undefined ? assertOpenRouterHttpUrl("callbackUrl", request.callbackUrl) : undefined;
|
|
3717
|
+
assertNoExtraBodyClash("openRouterSubmitVideo", request.extraBody, VIDEO_OWNED_KEYS);
|
|
3718
|
+
const provider = request.provider !== undefined ? serializeOpenRouterProviderRouting(request.provider) : undefined;
|
|
3719
|
+
const body = {
|
|
3720
|
+
...request.extraBody ?? {},
|
|
3721
|
+
model,
|
|
3722
|
+
prompt: request.prompt,
|
|
3723
|
+
...request.duration !== undefined && { duration: request.duration },
|
|
3724
|
+
...request.aspectRatio !== undefined && { aspect_ratio: request.aspectRatio },
|
|
3725
|
+
...request.resolution !== undefined && { resolution: request.resolution },
|
|
3726
|
+
...request.generateAudio !== undefined && { generate_audio: request.generateAudio },
|
|
3727
|
+
...request.frameImages !== undefined && { frame_images: [...request.frameImages] },
|
|
3728
|
+
...request.inputReferences !== undefined && {
|
|
3729
|
+
input_references: [...request.inputReferences]
|
|
3730
|
+
},
|
|
3731
|
+
...callbackUrl !== undefined && { callback_url: callbackUrl },
|
|
3732
|
+
...provider !== undefined && { provider }
|
|
3733
|
+
};
|
|
3734
|
+
const response = await openRouterRequestJson({
|
|
3735
|
+
...pickOpenRouterTransport(input),
|
|
3736
|
+
path: "/videos",
|
|
3737
|
+
method: "POST",
|
|
3738
|
+
body,
|
|
3739
|
+
schema: OpenRouterVideoSubmitResponseSchema
|
|
3740
|
+
});
|
|
3741
|
+
return {
|
|
3742
|
+
id: response.data.id,
|
|
3743
|
+
jobStatus: response.data.status,
|
|
3744
|
+
...response.data.polling_url !== undefined && { pollingUrl: response.data.polling_url },
|
|
3745
|
+
raw: response.data,
|
|
3746
|
+
...responseMetaOf(response)
|
|
3747
|
+
};
|
|
3748
|
+
}
|
|
3749
|
+
async function openRouterGetVideo(input) {
|
|
3750
|
+
assertOpenRouterDirectAuth(input);
|
|
3751
|
+
const request = parseOpenRouterRequest("openRouterGetVideo", VideoJobRequestSchema, input);
|
|
3752
|
+
const jobId = assertOpenRouterPathSegment("jobId", request.jobId);
|
|
3753
|
+
const response = await openRouterRequestJson({
|
|
3754
|
+
...pickOpenRouterTransport(input),
|
|
3755
|
+
path: `/videos/${encodeURIComponent(jobId)}`,
|
|
3756
|
+
method: "GET",
|
|
3757
|
+
schema: OpenRouterVideoStatusResponseSchema
|
|
3758
|
+
});
|
|
3759
|
+
return {
|
|
3760
|
+
id: response.data.id,
|
|
3761
|
+
jobStatus: response.data.status,
|
|
3762
|
+
...response.data.urls !== undefined && { urls: response.data.urls },
|
|
3763
|
+
...response.data.unsigned_urls !== undefined && {
|
|
3764
|
+
unsignedUrls: response.data.unsigned_urls
|
|
3765
|
+
},
|
|
3766
|
+
...response.data.expires_at !== undefined && { expiresAt: response.data.expires_at },
|
|
3767
|
+
...response.data.usage !== undefined && { usage: response.data.usage },
|
|
3768
|
+
...response.data.error !== undefined && { error: response.data.error },
|
|
3769
|
+
raw: response.data,
|
|
3770
|
+
...responseMetaOf(response)
|
|
3771
|
+
};
|
|
3772
|
+
}
|
|
3773
|
+
async function openRouterDownloadVideo(input) {
|
|
3774
|
+
assertOpenRouterDirectAuth(input);
|
|
3775
|
+
const request = parseOpenRouterRequest("openRouterDownloadVideo", VideoJobRequestSchema, input);
|
|
3776
|
+
const jobId = assertOpenRouterPathSegment("jobId", request.jobId);
|
|
3777
|
+
const index = request.index;
|
|
3778
|
+
assertNonNegativeSafeInteger("openRouterDownloadVideo: index", index, RangeError);
|
|
3779
|
+
return openRouterRequestStream({
|
|
3780
|
+
...pickOpenRouterTransport(input),
|
|
3781
|
+
path: `/videos/${encodeURIComponent(jobId)}/content`,
|
|
3782
|
+
method: "GET",
|
|
3783
|
+
...index !== undefined && { query: { index } }
|
|
3784
|
+
});
|
|
3785
|
+
}
|
|
3786
|
+
|
|
3787
|
+
// src/agent-runtime/providers/openrouter-retrieval.ts
|
|
3788
|
+
import { z as z11 } from "zod";
|
|
3789
|
+
var EMBEDDINGS_OWNED_KEYS = [
|
|
3790
|
+
"model",
|
|
3791
|
+
"input",
|
|
3792
|
+
"encoding_format",
|
|
3793
|
+
"dimensions",
|
|
3794
|
+
"user",
|
|
3795
|
+
"provider"
|
|
3796
|
+
];
|
|
3797
|
+
var RERANK_OWNED_KEYS = ["model", "query", "documents", "top_n", "provider"];
|
|
3798
|
+
var EmbeddingDatumSchema = z11.object({
|
|
3799
|
+
index: NonNegativeInt,
|
|
3800
|
+
embedding: z11.union([z11.array(z11.number()), z11.string()])
|
|
3801
|
+
}).loose();
|
|
3802
|
+
var OpenRouterEmbeddingsResponseSchema = z11.object({
|
|
3803
|
+
model: z11.string().min(1).optional(),
|
|
3804
|
+
data: z11.array(EmbeddingDatumSchema),
|
|
3805
|
+
usage: OpenRouterUsageSchema.optional()
|
|
3806
|
+
}).loose();
|
|
3807
|
+
var EmbeddingsRequestSchema = z11.object({
|
|
3808
|
+
model: z11.string(),
|
|
3809
|
+
input: z11.union([z11.string(), z11.array(z11.string()).min(1).readonly()]),
|
|
3810
|
+
encodingFormat: z11.enum(["float", "base64"]).optional(),
|
|
3811
|
+
dimensions: RangedNumber.optional(),
|
|
3812
|
+
user: z11.string().optional(),
|
|
3813
|
+
provider: OpenRouterProviderRoutingSchema.optional(),
|
|
3814
|
+
extraBody: ExtraBodySchema.optional()
|
|
3815
|
+
});
|
|
3816
|
+
async function openRouterEmbeddings(input) {
|
|
3817
|
+
assertOpenRouterDirectAuth(input);
|
|
3818
|
+
const request = parseOpenRouterRequest("openRouterEmbeddings", EmbeddingsRequestSchema, input);
|
|
3819
|
+
const model = assertNonEmptyOpenRouterField("openRouterEmbeddings", "model", request.model);
|
|
3820
|
+
if (request.dimensions !== undefined)
|
|
3821
|
+
assertPositiveSafeInteger("dimensions", request.dimensions);
|
|
3822
|
+
assertNoExtraBodyClash("openRouterEmbeddings", request.extraBody, EMBEDDINGS_OWNED_KEYS);
|
|
3823
|
+
const provider = request.provider !== undefined ? serializeOpenRouterProviderRouting(request.provider) : undefined;
|
|
3824
|
+
const body = {
|
|
3825
|
+
...request.extraBody ?? {},
|
|
3826
|
+
model,
|
|
3827
|
+
input: typeof request.input === "string" ? request.input : [...request.input],
|
|
3828
|
+
...request.encodingFormat !== undefined && { encoding_format: request.encodingFormat },
|
|
3829
|
+
...request.dimensions !== undefined && { dimensions: request.dimensions },
|
|
3830
|
+
...request.user !== undefined && { user: request.user },
|
|
3831
|
+
...provider !== undefined && { provider }
|
|
3832
|
+
};
|
|
3833
|
+
const response = await openRouterRequestJson({
|
|
3834
|
+
...pickOpenRouterTransport(input),
|
|
3835
|
+
path: "/embeddings",
|
|
3836
|
+
method: "POST",
|
|
3837
|
+
body,
|
|
3838
|
+
schema: OpenRouterEmbeddingsResponseSchema
|
|
3839
|
+
});
|
|
3840
|
+
return {
|
|
3841
|
+
...response.data.model !== undefined && { model: response.data.model },
|
|
3842
|
+
data: response.data.data,
|
|
3843
|
+
...response.data.usage !== undefined && { usage: response.data.usage },
|
|
3844
|
+
raw: response.data,
|
|
3845
|
+
...responseMetaOf(response)
|
|
3846
|
+
};
|
|
3847
|
+
}
|
|
3848
|
+
var RerankDocumentSchema = z11.union([
|
|
3849
|
+
z11.string(),
|
|
3850
|
+
z11.strictObject({
|
|
3851
|
+
text: z11.string().optional(),
|
|
3852
|
+
image: z11.string().refine((value) => /^(?:https?:\/\/|data:image\/)/iu.test(value.trim()), {
|
|
3853
|
+
message: "image must be an http(s) URL or a data:image/ URI"
|
|
3854
|
+
}).optional()
|
|
3855
|
+
}).refine((value) => value.text !== undefined || value.image !== undefined, {
|
|
3856
|
+
message: "a rerank document object needs text or image"
|
|
3857
|
+
})
|
|
3858
|
+
]);
|
|
3859
|
+
var RerankDocumentsSchema = z11.array(RerankDocumentSchema).min(1).readonly();
|
|
3860
|
+
var RerankResultDocumentSchema = z11.object({ text: z11.string().optional(), image: z11.string().optional() }).loose();
|
|
3861
|
+
var RerankResultItemSchema = z11.object({
|
|
3862
|
+
index: NonNegativeInt,
|
|
3863
|
+
relevance_score: z11.number().finite(),
|
|
3864
|
+
document: RerankResultDocumentSchema.optional()
|
|
3865
|
+
}).loose();
|
|
3866
|
+
var OpenRouterRerankResponseSchema = z11.object({
|
|
3867
|
+
results: z11.array(RerankResultItemSchema),
|
|
3868
|
+
meta: z11.record(z11.string(), z11.unknown()).optional(),
|
|
3869
|
+
usage: OpenRouterUsageSchema.optional()
|
|
3870
|
+
}).loose();
|
|
3871
|
+
var RerankRequestSchema = z11.object({
|
|
3872
|
+
model: z11.string(),
|
|
3873
|
+
query: z11.string(),
|
|
3874
|
+
documents: RerankDocumentsSchema,
|
|
3875
|
+
topN: RangedNumber.optional(),
|
|
3876
|
+
provider: OpenRouterProviderRoutingSchema.optional(),
|
|
3877
|
+
extraBody: ExtraBodySchema.optional()
|
|
3878
|
+
});
|
|
3879
|
+
async function openRouterRerank(input) {
|
|
3880
|
+
assertOpenRouterDirectAuth(input);
|
|
3881
|
+
const request = parseOpenRouterRequest("openRouterRerank", RerankRequestSchema, input);
|
|
3882
|
+
const model = assertNonEmptyOpenRouterField("openRouterRerank", "model", request.model);
|
|
3883
|
+
assertNonEmptyOpenRouterField("openRouterRerank", "query", request.query);
|
|
3884
|
+
if (request.topN !== undefined)
|
|
3885
|
+
assertPositiveSafeInteger("topN", request.topN);
|
|
3886
|
+
assertNoExtraBodyClash("openRouterRerank", request.extraBody, RERANK_OWNED_KEYS);
|
|
3887
|
+
const provider = request.provider !== undefined ? serializeOpenRouterProviderRouting(request.provider) : undefined;
|
|
3888
|
+
const body = {
|
|
3889
|
+
...request.extraBody ?? {},
|
|
3890
|
+
model,
|
|
3891
|
+
query: request.query,
|
|
3892
|
+
documents: [...request.documents],
|
|
3893
|
+
...request.topN !== undefined && { top_n: request.topN },
|
|
3894
|
+
...provider !== undefined && { provider }
|
|
3895
|
+
};
|
|
3896
|
+
const response = await openRouterRequestJson({
|
|
3897
|
+
...pickOpenRouterTransport(input),
|
|
3898
|
+
path: "/rerank",
|
|
3899
|
+
method: "POST",
|
|
3900
|
+
body,
|
|
3901
|
+
schema: OpenRouterRerankResponseSchema
|
|
3902
|
+
});
|
|
3903
|
+
return {
|
|
3904
|
+
results: response.data.results.map((item) => ({
|
|
3905
|
+
index: item.index,
|
|
3906
|
+
relevanceScore: item.relevance_score,
|
|
3907
|
+
...item.document !== undefined && { document: item.document }
|
|
3908
|
+
})),
|
|
3909
|
+
...response.data.meta !== undefined && { meta: response.data.meta },
|
|
3910
|
+
...response.data.usage !== undefined && { usage: response.data.usage },
|
|
3911
|
+
raw: response.data,
|
|
3912
|
+
...responseMetaOf(response)
|
|
3913
|
+
};
|
|
3914
|
+
}
|
|
3915
|
+
|
|
3916
|
+
// src/agent-runtime/providers/openrouter-speech.ts
|
|
3917
|
+
import { z as z12 } from "zod";
|
|
3918
|
+
var TTS_OWNED_KEYS = [
|
|
3919
|
+
"model",
|
|
3920
|
+
"input",
|
|
3921
|
+
"voice",
|
|
3922
|
+
"instructions",
|
|
3923
|
+
"response_format",
|
|
3924
|
+
"speed",
|
|
3925
|
+
"output_delivery",
|
|
3926
|
+
"provider"
|
|
3927
|
+
];
|
|
3928
|
+
var MAX_URL_DELIVERY_BYTES = 64 * 1024;
|
|
3929
|
+
var SpeechFormatSchema = z12.enum(["mp3", "pcm", "wav"]);
|
|
3930
|
+
var SpeechTurnSchema = z12.strictObject({
|
|
3931
|
+
text: z12.string().refine((text) => text.trim().length > 0, "turn text must be non-empty"),
|
|
3932
|
+
voice: z12.string().refine((voice) => voice.trim().length > 0, "turn voice must be non-empty").optional(),
|
|
3933
|
+
instructions: z12.string().optional()
|
|
3934
|
+
});
|
|
3935
|
+
var SpeechTurnsSchema = z12.array(SpeechTurnSchema).min(1).readonly();
|
|
3936
|
+
var OpenRouterSpeechUrlResponseSchema = z12.object({
|
|
3937
|
+
url: z12.url(),
|
|
3938
|
+
expires_at: NonNegativeInt,
|
|
3939
|
+
media_type: z12.string().min(1)
|
|
3940
|
+
}).loose();
|
|
3941
|
+
var SpeechRequestSchema = z12.object({
|
|
3942
|
+
model: z12.string(),
|
|
3943
|
+
input: z12.union([z12.string(), SpeechTurnsSchema]),
|
|
3944
|
+
voice: z12.string().optional(),
|
|
3945
|
+
instructions: z12.string().optional(),
|
|
3946
|
+
responseFormat: SpeechFormatSchema.optional(),
|
|
3947
|
+
outputDelivery: z12.enum(["stream", "url"]).optional(),
|
|
3948
|
+
speed: RangedNumber.optional(),
|
|
3949
|
+
provider: OpenRouterProviderRoutingSchema.optional(),
|
|
3950
|
+
extraBody: ExtraBodySchema.optional()
|
|
3951
|
+
});
|
|
3952
|
+
function speechBody(input, model) {
|
|
3953
|
+
const request = parseOpenRouterRequest("openRouterAudioSpeech", SpeechRequestSchema, input);
|
|
3954
|
+
const speechInput = typeof request.input === "string" ? assertNonEmptyOpenRouterField("openRouterAudioSpeech", "input", request.input) : [...request.input];
|
|
3955
|
+
const voice = request.voice !== undefined ? assertNonEmptyOpenRouterField("openRouterAudioSpeech", "voice", request.voice) : undefined;
|
|
3956
|
+
if (request.speed !== undefined && (!Number.isFinite(request.speed) || request.speed <= 0)) {
|
|
3957
|
+
throw new RangeError("openRouterAudioSpeech: speed must be a positive finite number");
|
|
3958
|
+
}
|
|
3959
|
+
assertNoExtraBodyClash("openRouterAudioSpeech", request.extraBody, TTS_OWNED_KEYS);
|
|
3960
|
+
const provider = request.provider !== undefined ? serializeOpenRouterProviderRouting(request.provider) : undefined;
|
|
3961
|
+
return {
|
|
3962
|
+
...request.extraBody ?? {},
|
|
3963
|
+
model,
|
|
3964
|
+
input: speechInput,
|
|
3965
|
+
...voice !== undefined && { voice },
|
|
3966
|
+
...request.instructions !== undefined && { instructions: request.instructions },
|
|
3967
|
+
...request.responseFormat !== undefined && { response_format: request.responseFormat },
|
|
3968
|
+
...request.outputDelivery !== undefined && { output_delivery: request.outputDelivery },
|
|
3969
|
+
...request.speed !== undefined && { speed: request.speed },
|
|
3970
|
+
...provider !== undefined && { provider }
|
|
3971
|
+
};
|
|
3972
|
+
}
|
|
3973
|
+
async function readUrlDelivery(response, signal) {
|
|
3974
|
+
const failure = (message, cause) => new AgentProviderError2(message, {
|
|
3975
|
+
provider: "openrouter",
|
|
3976
|
+
statusCode: response.status,
|
|
3977
|
+
retryable: false,
|
|
3978
|
+
...response.requestId !== undefined && { requestId: response.requestId },
|
|
3979
|
+
responseHeaders: response.headers,
|
|
3980
|
+
...cause !== undefined && { cause }
|
|
3981
|
+
});
|
|
3982
|
+
const read = await readBoundedChunks(response.body, {
|
|
3983
|
+
maxBytes: MAX_URL_DELIVERY_BYTES,
|
|
3984
|
+
signal
|
|
3985
|
+
});
|
|
3986
|
+
if (read.kind === "over-limit") {
|
|
3987
|
+
throw failure(`OpenRouter speech URL response exceeded ${MAX_URL_DELIVERY_BYTES} byte limit`);
|
|
3988
|
+
}
|
|
3989
|
+
const text = new TextDecoder().decode(concatChunks(read.chunks, read.total));
|
|
3990
|
+
let parsed;
|
|
3991
|
+
try {
|
|
3992
|
+
parsed = JSON.parse(text);
|
|
3993
|
+
} catch (error) {
|
|
3994
|
+
throw failure(`OpenRouter returned invalid speech URL JSON: ${redactProviderFailureText(text, 256)}`, error);
|
|
3995
|
+
}
|
|
3996
|
+
const delivery = OpenRouterSpeechUrlResponseSchema.safeParse(parsed);
|
|
3997
|
+
if (!delivery.success) {
|
|
3998
|
+
throw failure(`OpenRouter speech URL response failed schema validation: ${redactProviderFailureText(delivery.error.message, 512)}`, delivery.error);
|
|
3999
|
+
}
|
|
4000
|
+
return {
|
|
4001
|
+
delivery: "url",
|
|
4002
|
+
url: delivery.data.url,
|
|
4003
|
+
expiresAt: delivery.data.expires_at,
|
|
4004
|
+
mediaType: delivery.data.media_type,
|
|
4005
|
+
status: response.status,
|
|
4006
|
+
...response.generationId !== undefined && { generationId: response.generationId },
|
|
4007
|
+
...response.requestId !== undefined && { requestId: response.requestId },
|
|
4008
|
+
headers: response.headers
|
|
4009
|
+
};
|
|
4010
|
+
}
|
|
4011
|
+
async function openRouterAudioSpeech(input) {
|
|
4012
|
+
assertOpenRouterDirectAuth(input);
|
|
4013
|
+
const model = assertNonEmptyOpenRouterField("openRouterAudioSpeech", "model", input.model);
|
|
4014
|
+
const body = speechBody(input, model);
|
|
4015
|
+
const timeoutMs = input.timeoutMs ?? DEFAULT_OPENROUTER_REQUEST_TIMEOUT_MS;
|
|
4016
|
+
const startedAt = Date.now();
|
|
4017
|
+
const response = await openRouterRequestStream({
|
|
4018
|
+
...pickOpenRouterTransport(input),
|
|
4019
|
+
path: "/audio/speech",
|
|
4020
|
+
method: "POST",
|
|
4021
|
+
body
|
|
4022
|
+
});
|
|
4023
|
+
if (input.outputDelivery === "url" && JSON_CONTENT_TYPE.test(response.contentType)) {
|
|
4024
|
+
return withSignalDeadline(Math.max(1, timeoutMs - (Date.now() - startedAt)), input.signal, () => abortError(`OpenRouter stream /audio/speech timed out after ${timeoutMs} ms`, "TimeoutError"), (signal) => readUrlDelivery(response, signal));
|
|
4025
|
+
}
|
|
4026
|
+
return {
|
|
4027
|
+
delivery: "stream",
|
|
4028
|
+
audio: response.body,
|
|
4029
|
+
contentType: response.contentType,
|
|
4030
|
+
status: response.status,
|
|
4031
|
+
...response.generationId !== undefined && { generationId: response.generationId },
|
|
4032
|
+
...response.requestId !== undefined && { requestId: response.requestId },
|
|
4033
|
+
headers: response.headers
|
|
4034
|
+
};
|
|
4035
|
+
}
|
|
4036
|
+
|
|
4037
|
+
// src/agent-runtime/providers/openrouter-systemone.ts
|
|
4038
|
+
import { z as z13 } from "zod";
|
|
4039
|
+
var SYSTEMONE_OWNED_KEYS = [
|
|
4040
|
+
"model",
|
|
4041
|
+
"state",
|
|
4042
|
+
"questions",
|
|
4043
|
+
"assets",
|
|
4044
|
+
"provider",
|
|
4045
|
+
"session_id",
|
|
4046
|
+
"user",
|
|
4047
|
+
"response_format"
|
|
4048
|
+
];
|
|
4049
|
+
var GuidanceSchema = z13.union([
|
|
4050
|
+
z13.string(),
|
|
4051
|
+
z13.record(z13.string(), z13.unknown()).readonly(),
|
|
4052
|
+
z13.array(z13.unknown()).readonly()
|
|
4053
|
+
]);
|
|
4054
|
+
var SystemOneNoulQuestionSchema = z13.strictObject({
|
|
4055
|
+
type: z13.literal("noul"),
|
|
4056
|
+
instructions: GuidanceSchema.nullable().optional(),
|
|
4057
|
+
criteria: z13.strictObject({
|
|
4058
|
+
true: GuidanceSchema.nullable().optional(),
|
|
4059
|
+
false: GuidanceSchema.nullable().optional()
|
|
4060
|
+
}).optional()
|
|
4061
|
+
});
|
|
4062
|
+
var SystemOneChoiceQuestionSchema = z13.strictObject({
|
|
4063
|
+
type: z13.literal("choice"),
|
|
4064
|
+
instructions: GuidanceSchema.nullable().optional(),
|
|
4065
|
+
criteria: z13.record(z13.string().min(1), GuidanceSchema.nullable()).readonly()
|
|
4066
|
+
});
|
|
4067
|
+
var SystemOneScoreQuestionSchema = z13.strictObject({
|
|
4068
|
+
type: z13.literal("score"),
|
|
4069
|
+
instructions: GuidanceSchema.nullable().optional(),
|
|
4070
|
+
criteria: z13.array(GuidanceSchema).min(1).readonly()
|
|
4071
|
+
});
|
|
4072
|
+
var SystemOneBoxQuestionSchema = z13.strictObject({
|
|
4073
|
+
type: z13.literal("box"),
|
|
4074
|
+
instructions: GuidanceSchema
|
|
4075
|
+
});
|
|
4076
|
+
var SystemOneQuestionSchema = z13.discriminatedUnion("type", [
|
|
4077
|
+
SystemOneNoulQuestionSchema,
|
|
4078
|
+
SystemOneChoiceQuestionSchema,
|
|
4079
|
+
SystemOneScoreQuestionSchema,
|
|
4080
|
+
SystemOneBoxQuestionSchema
|
|
4081
|
+
]);
|
|
4082
|
+
var SystemOneNoulAnswerSchema = z13.object({
|
|
4083
|
+
type: z13.literal("noul"),
|
|
4084
|
+
noul: Probability,
|
|
4085
|
+
confidence: Probability.optional()
|
|
4086
|
+
}).loose();
|
|
4087
|
+
var SystemOneChoiceAnswerSchema = z13.object({
|
|
4088
|
+
type: z13.literal("choice"),
|
|
4089
|
+
choice: z13.string(),
|
|
4090
|
+
confidence: Probability.optional(),
|
|
4091
|
+
probabilities: z13.record(z13.string(), Probability).optional()
|
|
4092
|
+
}).loose();
|
|
4093
|
+
var SystemOneScoreAnswerSchema = z13.object({
|
|
4094
|
+
type: z13.literal("score"),
|
|
4095
|
+
score: z13.number().finite(),
|
|
4096
|
+
confidence: Probability.optional(),
|
|
4097
|
+
legend: z13.record(z13.string(), GuidanceSchema).optional(),
|
|
4098
|
+
probabilities: z13.record(z13.string(), Probability).optional()
|
|
4099
|
+
}).loose();
|
|
4100
|
+
var SystemOneBoxAnswerSchema = z13.object({
|
|
4101
|
+
type: z13.literal("box"),
|
|
4102
|
+
box: z13.object({
|
|
4103
|
+
top: z13.number().finite(),
|
|
4104
|
+
bottom: z13.number().finite(),
|
|
4105
|
+
left: z13.number().finite(),
|
|
4106
|
+
right: z13.number().finite()
|
|
4107
|
+
}).loose(),
|
|
4108
|
+
confidence: Probability.optional()
|
|
4109
|
+
}).loose();
|
|
4110
|
+
var SystemOneRefusalAnswerSchema = z13.object({ type: z13.literal("refusal") }).loose();
|
|
4111
|
+
var SystemOneAnswerSchema = z13.discriminatedUnion("type", [
|
|
4112
|
+
SystemOneNoulAnswerSchema,
|
|
4113
|
+
SystemOneChoiceAnswerSchema,
|
|
4114
|
+
SystemOneScoreAnswerSchema,
|
|
4115
|
+
SystemOneBoxAnswerSchema,
|
|
4116
|
+
SystemOneRefusalAnswerSchema
|
|
4117
|
+
]);
|
|
4118
|
+
var OpenRouterSystemOneResponseSchema = z13.object({
|
|
4119
|
+
id: z13.string().min(1).optional(),
|
|
4120
|
+
model: z13.string().min(1).optional(),
|
|
4121
|
+
answers: z13.record(z13.string(), SystemOneAnswerSchema),
|
|
4122
|
+
usage: OpenRouterUsageSchema.optional()
|
|
4123
|
+
}).loose();
|
|
4124
|
+
var SystemOneStateSchema = z13.union([z13.string(), z13.record(z13.string(), z13.unknown()).readonly(), z13.array(z13.unknown()).readonly()], { error: "state must be a string, a JSON object, or a JSON array" });
|
|
4125
|
+
var SystemOneQuestionsMapSchema = z13.record(z13.string().min(1), SystemOneQuestionSchema).readonly().refine((value) => Object.keys(value).length > 0, {
|
|
4126
|
+
message: "openRouterSystemOne requires at least one question"
|
|
4127
|
+
});
|
|
4128
|
+
var SystemOneImageAssetSchema = z13.strictObject({
|
|
4129
|
+
format: z13.enum(["png", "jpg", "jpeg"]),
|
|
4130
|
+
dataBase64: z13.base64().min(1)
|
|
4131
|
+
});
|
|
4132
|
+
var SystemOneRequestSchema = z13.object({
|
|
4133
|
+
model: z13.string(),
|
|
4134
|
+
state: SystemOneStateSchema,
|
|
4135
|
+
questions: SystemOneQuestionsMapSchema,
|
|
4136
|
+
assets: z13.record(z13.string().min(1), SystemOneImageAssetSchema).readonly().optional(),
|
|
4137
|
+
sessionId: z13.string().min(1).max(256).optional(),
|
|
4138
|
+
user: z13.string().min(1).max(256).optional(),
|
|
4139
|
+
provider: OpenRouterProviderRoutingSchema.optional(),
|
|
4140
|
+
extraBody: ExtraBodySchema.optional()
|
|
4141
|
+
});
|
|
4142
|
+
async function openRouterSystemOne(input) {
|
|
4143
|
+
assertOpenRouterDirectAuth(input);
|
|
4144
|
+
const request = parseOpenRouterRequest("openRouterSystemOne", SystemOneRequestSchema, input);
|
|
4145
|
+
const model = assertNonEmptyOpenRouterField("openRouterSystemOne", "model", request.model);
|
|
4146
|
+
assertNoExtraBodyClash("openRouterSystemOne", request.extraBody, SYSTEMONE_OWNED_KEYS);
|
|
4147
|
+
const provider = request.provider !== undefined ? serializeOpenRouterProviderRouting(request.provider) : undefined;
|
|
4148
|
+
const body = {
|
|
4149
|
+
...request.extraBody ?? {},
|
|
4150
|
+
model,
|
|
4151
|
+
state: request.state,
|
|
4152
|
+
questions: request.questions,
|
|
4153
|
+
...request.assets !== undefined && {
|
|
4154
|
+
assets: Object.fromEntries(Object.entries(request.assets).map(([key, asset]) => [
|
|
4155
|
+
key,
|
|
4156
|
+
{ type: "image", format: asset.format, data_base64: asset.dataBase64 }
|
|
4157
|
+
]))
|
|
4158
|
+
},
|
|
4159
|
+
...provider !== undefined && { provider },
|
|
4160
|
+
...request.sessionId !== undefined && { session_id: request.sessionId },
|
|
4161
|
+
...request.user !== undefined && { user: request.user }
|
|
4162
|
+
};
|
|
4163
|
+
const response = await openRouterRequestJson({
|
|
4164
|
+
...pickOpenRouterTransport(input),
|
|
4165
|
+
path: "/systemone",
|
|
4166
|
+
method: "POST",
|
|
4167
|
+
body,
|
|
4168
|
+
schema: OpenRouterSystemOneResponseSchema
|
|
4169
|
+
});
|
|
4170
|
+
return {
|
|
4171
|
+
...response.data.model !== undefined && { model: response.data.model },
|
|
4172
|
+
answers: response.data.answers,
|
|
4173
|
+
...response.data.usage !== undefined && { usage: response.data.usage },
|
|
4174
|
+
raw: response.data,
|
|
4175
|
+
...responseMetaOf(response)
|
|
4176
|
+
};
|
|
4177
|
+
}
|
|
4178
|
+
|
|
4179
|
+
// src/agent-runtime/providers/openrouter-client.ts
|
|
4180
|
+
function underCall(defaults, input) {
|
|
4181
|
+
const headers = defaults.headers !== undefined && input.headers !== undefined ? { ...defaults.headers, ...input.headers } : input.headers ?? defaults.headers;
|
|
4182
|
+
const providerApiKeys = defaults.providerApiKeys !== undefined && input.providerApiKeys !== undefined ? { ...defaults.providerApiKeys, ...input.providerApiKeys } : input.providerApiKeys ?? defaults.providerApiKeys;
|
|
4183
|
+
return {
|
|
4184
|
+
...defaults,
|
|
4185
|
+
...input,
|
|
4186
|
+
...headers !== undefined && { headers },
|
|
4187
|
+
...providerApiKeys !== undefined && { providerApiKeys }
|
|
4188
|
+
};
|
|
4189
|
+
}
|
|
4190
|
+
function withDefaults(call, defaults) {
|
|
4191
|
+
return (input) => call(underCall(defaults, input));
|
|
4192
|
+
}
|
|
4193
|
+
function createOpenRouterClient(options = {}) {
|
|
4194
|
+
validateOpenRouterBaseUrl(options.baseUrl);
|
|
4195
|
+
assertValidOpenRouterApiKey(options.apiKey);
|
|
4196
|
+
const defaults = {
|
|
4197
|
+
...options,
|
|
4198
|
+
...options.headers !== undefined && { headers: { ...options.headers } },
|
|
4199
|
+
...options.providerApiKeys !== undefined && {
|
|
4200
|
+
providerApiKeys: { ...options.providerApiKeys }
|
|
4201
|
+
}
|
|
4202
|
+
};
|
|
4203
|
+
function audioSpeech(input) {
|
|
4204
|
+
return openRouterAudioSpeech(underCall(defaults, input));
|
|
4205
|
+
}
|
|
4206
|
+
function requestJson(input) {
|
|
4207
|
+
const merged = underCall(defaults, input);
|
|
4208
|
+
return input.schema === undefined ? openRouterRequestJson({ ...merged, schema: undefined }) : openRouterRequestJson({ ...merged, schema: input.schema });
|
|
4209
|
+
}
|
|
4210
|
+
return {
|
|
4211
|
+
audioTranscription: withDefaults(openRouterAudioTranscription, defaults),
|
|
4212
|
+
audioSpeech,
|
|
4213
|
+
systemOne: withDefaults(openRouterSystemOne, defaults),
|
|
4214
|
+
generateImages: withDefaults(openRouterGenerateImages, defaults),
|
|
4215
|
+
submitVideo: withDefaults(openRouterSubmitVideo, defaults),
|
|
4216
|
+
getVideo: withDefaults(openRouterGetVideo, defaults),
|
|
4217
|
+
downloadVideo: withDefaults(openRouterDownloadVideo, defaults),
|
|
4218
|
+
embeddings: withDefaults(openRouterEmbeddings, defaults),
|
|
4219
|
+
rerank: withDefaults(openRouterRerank, defaults),
|
|
4220
|
+
requestJson,
|
|
4221
|
+
requestStream: withDefaults(openRouterRequestStream, defaults)
|
|
4222
|
+
};
|
|
4223
|
+
}
|
|
2848
4224
|
// src/agent-runtime/providers/openrouter-spend.ts
|
|
2849
|
-
import { z as
|
|
4225
|
+
import { z as z14 } from "zod";
|
|
4226
|
+
function readOptional(schema, value) {
|
|
4227
|
+
if (value === undefined || value === null)
|
|
4228
|
+
return;
|
|
4229
|
+
const parsed = schema.safeParse(value);
|
|
4230
|
+
return parsed.success ? parsed.data : undefined;
|
|
4231
|
+
}
|
|
4232
|
+
var openRouterSpendFacts = {
|
|
4233
|
+
headers(headers) {
|
|
4234
|
+
const generationId = nonEmptyTrimmed(headers.get("x-generation-id"));
|
|
4235
|
+
return generationId !== undefined ? { providerRequestId: generationId } : {};
|
|
4236
|
+
},
|
|
4237
|
+
event(value) {
|
|
4238
|
+
const base = openAiCompatibleUsage2.event?.(value) ?? {};
|
|
4239
|
+
const { providerRequestId: rawId, ...restBase } = base;
|
|
4240
|
+
if (!isRecord(value))
|
|
4241
|
+
return restBase;
|
|
4242
|
+
const trimmedRawId = nonEmptyTrimmed(rawId);
|
|
4243
|
+
const generationId = nonEmptyTrimmed(typeof value.generation_id === "string" ? value.generation_id : undefined) ?? (trimmedRawId?.startsWith("gen-") ? trimmedRawId : undefined);
|
|
4244
|
+
const usage = isRecord(value.usage) ? value.usage : undefined;
|
|
4245
|
+
const inputDetails = usage && isRecord(usage.input_tokens_details) ? usage.input_tokens_details : undefined;
|
|
4246
|
+
const outputDetails = usage && isRecord(usage.output_tokens_details) ? usage.output_tokens_details : undefined;
|
|
4247
|
+
const inputTokens = restBase.inputTokens ?? readOptional(NonNegativeInt, usage?.input_tokens);
|
|
4248
|
+
const outputTokens = restBase.outputTokens ?? readOptional(NonNegativeInt, usage?.output_tokens);
|
|
4249
|
+
const cacheReadTokens = restBase.cacheReadTokens ?? readOptional(NonNegativeInt, inputDetails?.cached_tokens);
|
|
4250
|
+
const cacheWriteTokens = restBase.cacheWriteTokens ?? readOptional(NonNegativeInt, inputDetails?.cache_write_tokens);
|
|
4251
|
+
const reasoningTokens = restBase.reasoningTokens ?? readOptional(NonNegativeInt, outputDetails?.reasoning_tokens);
|
|
4252
|
+
const seconds = readOptional(NonNegativeNum, usage?.seconds);
|
|
4253
|
+
return {
|
|
4254
|
+
...restBase,
|
|
4255
|
+
...generationId !== undefined && { providerRequestId: generationId },
|
|
4256
|
+
...inputTokens !== undefined && { inputTokens },
|
|
4257
|
+
...outputTokens !== undefined && { outputTokens },
|
|
4258
|
+
...cacheReadTokens !== undefined && { cacheReadTokens },
|
|
4259
|
+
...cacheWriteTokens !== undefined && { cacheWriteTokens },
|
|
4260
|
+
...reasoningTokens !== undefined && { reasoningTokens },
|
|
4261
|
+
...seconds !== undefined && { workUnit: "seconds", workAmount: seconds }
|
|
4262
|
+
};
|
|
4263
|
+
}
|
|
4264
|
+
};
|
|
2850
4265
|
function openRouterSpendProvider(options) {
|
|
4266
|
+
const origin = validateOpenRouterBaseUrl(options.baseUrl).origin;
|
|
2851
4267
|
return {
|
|
2852
4268
|
name: "openrouter",
|
|
2853
|
-
origin
|
|
4269
|
+
origin,
|
|
2854
4270
|
headers: async () => ({ authorization: `Bearer ${await options.apiKey()}` }),
|
|
2855
|
-
facts:
|
|
4271
|
+
facts: openRouterSpendFacts
|
|
2856
4272
|
};
|
|
2857
4273
|
}
|
|
2858
|
-
var GenerationSchema =
|
|
2859
|
-
data:
|
|
2860
|
-
total_cost:
|
|
2861
|
-
provider_name:
|
|
2862
|
-
model:
|
|
2863
|
-
native_tokens_prompt:
|
|
2864
|
-
native_tokens_completion:
|
|
2865
|
-
native_tokens_reasoning:
|
|
4274
|
+
var GenerationSchema = z14.object({
|
|
4275
|
+
data: z14.object({
|
|
4276
|
+
total_cost: NonNegativeNum.nullish(),
|
|
4277
|
+
provider_name: z14.string().min(1).nullish(),
|
|
4278
|
+
model: z14.string().min(1).nullish(),
|
|
4279
|
+
native_tokens_prompt: NonNegativeInt.nullish(),
|
|
4280
|
+
native_tokens_completion: NonNegativeInt.nullish(),
|
|
4281
|
+
native_tokens_reasoning: NonNegativeInt.nullish()
|
|
2866
4282
|
}).loose()
|
|
2867
4283
|
});
|
|
2868
4284
|
function createOpenRouterSpendReconciler(options) {
|
|
2869
|
-
const fetcher = options.fetcher ?? fetch;
|
|
2870
4285
|
const timeoutMs = options.timeoutMs ?? 1e4;
|
|
2871
4286
|
assertTimerMs("timeoutMs", timeoutMs);
|
|
4287
|
+
validateOpenRouterBaseUrl(options.baseUrl);
|
|
2872
4288
|
return async (record) => {
|
|
2873
4289
|
const id = record.receipt?.facts.providerRequestId;
|
|
2874
4290
|
if (id === undefined)
|
|
2875
4291
|
return { costStatus: "unknown", failureCode: "no-generation-id" };
|
|
2876
|
-
|
|
2877
|
-
url.searchParams.set("id", id);
|
|
2878
|
-
let body;
|
|
4292
|
+
let data;
|
|
2879
4293
|
try {
|
|
2880
4294
|
const apiKey = typeof options.apiKey === "string" ? options.apiKey : await options.apiKey(record);
|
|
2881
|
-
|
|
4295
|
+
const response = await openRouterRequestJson({
|
|
4296
|
+
path: "/generation",
|
|
4297
|
+
query: { id },
|
|
4298
|
+
schema: GenerationSchema,
|
|
4299
|
+
apiKey,
|
|
4300
|
+
timeoutMs,
|
|
4301
|
+
maxResponseBytes: 1024 * 1024,
|
|
4302
|
+
...options.baseUrl !== undefined && { baseUrl: options.baseUrl },
|
|
4303
|
+
...options.fetch !== undefined && { fetch: options.fetch }
|
|
4304
|
+
});
|
|
4305
|
+
data = response.data.data;
|
|
2882
4306
|
} catch (error) {
|
|
2883
|
-
if (error instanceof
|
|
4307
|
+
if (error instanceof AgentProviderError2 && error.statusCode === 404)
|
|
2884
4308
|
return;
|
|
2885
4309
|
throw error;
|
|
2886
4310
|
}
|
|
2887
|
-
const { data } = GenerationSchema.parse(body);
|
|
2888
4311
|
if (data.total_cost == null)
|
|
2889
4312
|
return;
|
|
2890
4313
|
return {
|
|
@@ -2903,12 +4326,15 @@ function createOpenRouterSpendReconciler(options) {
|
|
|
2903
4326
|
};
|
|
2904
4327
|
}
|
|
2905
4328
|
export {
|
|
4329
|
+
OPENROUTER_API_BASE_URL,
|
|
2906
4330
|
OpenRouterAdmissionPolicySchema,
|
|
2907
4331
|
OpenRouterAdmissionReasonSchema,
|
|
4332
|
+
OpenRouterAudioTranscriptionResponseSchema,
|
|
2908
4333
|
OpenRouterCatalogSnapshotSchema,
|
|
4334
|
+
OpenRouterEmbeddingsResponseSchema,
|
|
2909
4335
|
OpenRouterEndpointSchema,
|
|
2910
4336
|
OpenRouterEndpointSummarySchema,
|
|
2911
|
-
|
|
4337
|
+
OpenRouterImageGenerationResponseSchema,
|
|
2912
4338
|
OpenRouterMaxPriceSchema,
|
|
2913
4339
|
OpenRouterModelAdmissionSchema,
|
|
2914
4340
|
OpenRouterModelAliasTargetSchema,
|
|
@@ -2918,10 +4344,17 @@ export {
|
|
|
2918
4344
|
OpenRouterProviderRoutingSchema,
|
|
2919
4345
|
OpenRouterReasoningEffortSchema,
|
|
2920
4346
|
OpenRouterRequestPolicySchema,
|
|
4347
|
+
OpenRouterRerankResponseSchema,
|
|
2921
4348
|
OpenRouterRoutePinSchema,
|
|
2922
4349
|
OpenRouterSnapshotModelSchema,
|
|
4350
|
+
OpenRouterSpeechUrlResponseSchema,
|
|
4351
|
+
OpenRouterSystemOneResponseSchema,
|
|
4352
|
+
OpenRouterUsageSchema,
|
|
4353
|
+
OpenRouterVideoStatusResponseSchema,
|
|
4354
|
+
OpenRouterVideoSubmitResponseSchema,
|
|
2923
4355
|
createMemoryOpenRouterRouteStore,
|
|
2924
4356
|
createOpenRouterCatalogCache,
|
|
4357
|
+
createOpenRouterClient,
|
|
2925
4358
|
createOpenRouterRouteResolver,
|
|
2926
4359
|
createOpenRouterSpendReconciler,
|
|
2927
4360
|
evaluateOpenRouterModelAdmission,
|
|
@@ -2930,9 +4363,20 @@ export {
|
|
|
2930
4363
|
listOpenRouterModels,
|
|
2931
4364
|
loadOpenRouterCatalogSnapshot,
|
|
2932
4365
|
normalizeOpenRouterUsage,
|
|
4366
|
+
openRouterAudioSpeech,
|
|
4367
|
+
openRouterAudioTranscription,
|
|
4368
|
+
openRouterDownloadVideo,
|
|
4369
|
+
openRouterEmbeddings,
|
|
4370
|
+
openRouterGenerateImages,
|
|
4371
|
+
openRouterGetVideo,
|
|
2933
4372
|
openRouterModelCatalog,
|
|
2934
4373
|
openRouterProvider,
|
|
4374
|
+
openRouterRequestJson,
|
|
4375
|
+
openRouterRequestStream,
|
|
4376
|
+
openRouterRerank,
|
|
2935
4377
|
openRouterSpendProvider,
|
|
4378
|
+
openRouterSubmitVideo,
|
|
4379
|
+
openRouterSystemOne,
|
|
2936
4380
|
resolveOpenRouterModelCeiling,
|
|
2937
4381
|
summarizeOpenRouterEndpoints
|
|
2938
4382
|
};
|