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