swayrouter 1.0.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/.env.example +43 -0
- package/CHANGELOG.md +132 -0
- package/LICENSE +30 -0
- package/README.id.md +633 -0
- package/README.md +628 -0
- package/cli/cli.js +388 -0
- package/cli/package.json +4 -0
- package/cli/src/cli/commands/xaiVideo.js +280 -0
- package/cli/src/cli/tray/SwayAvatar.svg +20 -0
- package/cli/src/cli/tray/autostart.js +351 -0
- package/cli/src/cli/tray/icon.ico +0 -0
- package/cli/src/cli/tray/icon.png +0 -0
- package/cli/src/cli/tray/tray.js +258 -0
- package/cli/src/cli/tray/tray.ps1 +129 -0
- package/cli/src/cli/tray/trayHost.js +157 -0
- package/cli/src/cli/tray/trayWin.js +83 -0
- package/cli/src/cli/utils/display.js +123 -0
- package/cli/src/cli/utils/input.js +138 -0
- package/cli/src/runtime/discover.js +153 -0
- package/cli/src/runtime/lifecycle.js +333 -0
- package/cli/src/runtime/runMenu.js +250 -0
- package/cli/src/runtime/uiAdapters.js +12 -0
- package/cli/src/runtime/update.js +130 -0
- package/dashboard/dist/assets/CliTools-Ch3gKuNw.js +24 -0
- package/dashboard/dist/assets/Combo-BBCldjWi.js +1 -0
- package/dashboard/dist/assets/ConsoleLog-wywAYcPT.js +6 -0
- package/dashboard/dist/assets/Dashboard-DxzyF41b.js +1 -0
- package/dashboard/dist/assets/Header-C_9Su9BF.js +1 -0
- package/dashboard/dist/assets/Keys-D0ufgcsc.js +1 -0
- package/dashboard/dist/assets/Login-BeKpipS_.js +1 -0
- package/dashboard/dist/assets/ManageApiKey-CVXsmW2B.js +1 -0
- package/dashboard/dist/assets/OAuthCallback-D_UZYcF6.js +1 -0
- package/dashboard/dist/assets/Provider-BU7JfTqm.js +4 -0
- package/dashboard/dist/assets/ProviderModelAccordion-BAifkfVR.js +1 -0
- package/dashboard/dist/assets/Proxy-CU15VJ--.js +1 -0
- package/dashboard/dist/assets/QuotaMonitor-HzGK7bcc.js +1 -0
- package/dashboard/dist/assets/Settings-Dt4y2dC0.js +1 -0
- package/dashboard/dist/assets/Setup-DSDUwU7N.js +1 -0
- package/dashboard/dist/assets/StatusBadge-1nAOyHU2.js +1 -0
- package/dashboard/dist/assets/SwayChat-Bup7up6D.js +10 -0
- package/dashboard/dist/assets/Usage-eWnrPQ_v.js +4 -0
- package/dashboard/dist/assets/accordion-DOOPDDgt.js +1 -0
- package/dashboard/dist/assets/admin-extras-api-CCdu5TFM.js +1 -0
- package/dashboard/dist/assets/api-keys-api-ifAC2Ok3.js +1 -0
- package/dashboard/dist/assets/card-CC0Omjcv.js +1 -0
- package/dashboard/dist/assets/chatStudio-C0zPz_Z_.js +2 -0
- package/dashboard/dist/assets/checkbox-7SZBrmbN.js +1 -0
- package/dashboard/dist/assets/connections-api-_N54UD3S.js +1 -0
- package/dashboard/dist/assets/copy-button-qBvM6H9z.js +1 -0
- package/dashboard/dist/assets/currency-api-SV9CBf5e.js +1 -0
- package/dashboard/dist/assets/flip-button-BGgkjtl0.js +1 -0
- package/dashboard/dist/assets/frame-cUiti6Lq.js +1 -0
- package/dashboard/dist/assets/icons-vendor-CUx7SB5V.js +541 -0
- package/dashboard/dist/assets/index-B6j-9zHy.js +10 -0
- package/dashboard/dist/assets/index-C-_l0yYz.css +1 -0
- package/dashboard/dist/assets/live-mode-CHShLY4E.js +1 -0
- package/dashboard/dist/assets/markdown-vendor-BY8e1gQ8.js +29 -0
- package/dashboard/dist/assets/motion-vendor-g5fpGzmJ.js +9 -0
- package/dashboard/dist/assets/oauth-callback-CqYQzyd7.js +1 -0
- package/dashboard/dist/assets/query-vendor-DVevaSVS.js +1 -0
- package/dashboard/dist/assets/react-vendor-xnYrwzsL.js +61 -0
- package/dashboard/dist/assets/ripple-button-l8aMiVVG.js +1 -0
- package/dashboard/dist/assets/segmented-CqmEnQjZ.js +1 -0
- package/dashboard/dist/assets/select-D8pUtMXp.js +1 -0
- package/dashboard/dist/assets/skeleton-7uJDiIXe.js +1 -0
- package/dashboard/dist/assets/table-D0M60Tu1.js +1 -0
- package/dashboard/dist/assets/tabs-C6YkuulG.js +1 -0
- package/dashboard/dist/assets/tunnel-api-DDPsBaDV.js +1 -0
- package/dashboard/dist/assets/ui-vendor-BuM9f2NY.js +17 -0
- package/dashboard/dist/image2/SwayAvatar.svg +20 -0
- package/dashboard/dist/index.html +32 -0
- package/dashboard/dist/logo/avatar.svg +1 -0
- package/dashboard/dist/logo/sway.svg +20 -0
- package/dashboard/dist/logo/swaychat.svg +20 -0
- package/dashboard/dist/providers/SwayCustom.svg +19 -0
- package/dashboard/dist/providers/alicode.svg +12 -0
- package/dashboard/dist/providers/anthropic.svg +11 -0
- package/dashboard/dist/providers/antigravity.svg +3 -0
- package/dashboard/dist/providers/azure.svg +5 -0
- package/dashboard/dist/providers/baidu.svg +3 -0
- package/dashboard/dist/providers/blackbox.svg +5 -0
- package/dashboard/dist/providers/byteplus.svg +3 -0
- package/dashboard/dist/providers/cerebras.svg +4 -0
- package/dashboard/dist/providers/chutes.svg +4 -0
- package/dashboard/dist/providers/claude.svg +3 -0
- package/dashboard/dist/providers/cline.svg +11 -0
- package/dashboard/dist/providers/cloudflare-ai.svg +4 -0
- package/dashboard/dist/providers/codebuddy.svg +11 -0
- package/dashboard/dist/providers/codex.svg +10 -0
- package/dashboard/dist/providers/commandcode.svg +3 -0
- package/dashboard/dist/providers/cursor.svg +3 -0
- package/dashboard/dist/providers/deepseek.svg +10 -0
- package/dashboard/dist/providers/featherless.svg +3 -0
- package/dashboard/dist/providers/fireworks.svg +3 -0
- package/dashboard/dist/providers/gemini.svg +3 -0
- package/dashboard/dist/providers/geminicli.svg +11 -0
- package/dashboard/dist/providers/github.svg +3 -0
- package/dashboard/dist/providers/grok.svg +3 -0
- package/dashboard/dist/providers/groq.svg +3 -0
- package/dashboard/dist/providers/hermesagent.svg +1 -0
- package/dashboard/dist/providers/kilocode.svg +15 -0
- package/dashboard/dist/providers/kimchi.svg +3 -0
- package/dashboard/dist/providers/kimi.svg +4 -0
- package/dashboard/dist/providers/kiro.svg +10 -0
- package/dashboard/dist/providers/meta.svg +3 -0
- package/dashboard/dist/providers/mimo.svg +10 -0
- package/dashboard/dist/providers/minimax.svg +3 -0
- package/dashboard/dist/providers/mistral.svg +3 -0
- package/dashboard/dist/providers/morph.svg +3 -0
- package/dashboard/dist/providers/nebius.svg +4 -0
- package/dashboard/dist/providers/nvidia.svg +3 -0
- package/dashboard/dist/providers/ollama.svg +3 -0
- package/dashboard/dist/providers/omp.svg +5 -0
- package/dashboard/dist/providers/openai.svg +3 -0
- package/dashboard/dist/providers/opencode.svg +3 -0
- package/dashboard/dist/providers/openrouter.svg +3 -0
- package/dashboard/dist/providers/perplexity.svg +3 -0
- package/dashboard/dist/providers/poolside.svg +36 -0
- package/dashboard/dist/providers/qoder.svg +11 -0
- package/dashboard/dist/providers/sumopod.svg +3 -0
- package/dashboard/dist/providers/tencent.svg +5 -0
- package/dashboard/dist/providers/together.svg +12 -0
- package/dashboard/dist/providers/trae.svg +3 -0
- package/dashboard/dist/providers/venice.svg +4 -0
- package/dashboard/dist/providers/vercel.svg +3 -0
- package/dashboard/dist/providers/vertex.svg +17 -0
- package/dashboard/dist/providers/windsurf.svg +10 -0
- package/dashboard/dist/providers/zai.svg +3 -0
- package/dashboard/tsconfig.json +13 -0
- package/package.json +87 -0
- package/src/config/appConstants.js +153 -0
- package/src/config/defaultThinkingSignature.js +7 -0
- package/src/config/errorConfig.js +117 -0
- package/src/config/grokCli.js +9 -0
- package/src/config/kiroConstants.js +235 -0
- package/src/config/mediaConfig.js +20 -0
- package/src/config/ollamaModels.js +18 -0
- package/src/config/providerModels.js +109 -0
- package/src/config/providers.js +17 -0
- package/src/config/runtimeConfig.js +84 -0
- package/src/dashboardGuard.js +254 -0
- package/src/executors/antigravity.js +389 -0
- package/src/executors/azure.js +49 -0
- package/src/executors/base.js +225 -0
- package/src/executors/codebuddy-cn.js +23 -0
- package/src/executors/codebuddy-intl.js +60 -0
- package/src/executors/codex.js +436 -0
- package/src/executors/commandcode.js +83 -0
- package/src/executors/cursor.js +1075 -0
- package/src/executors/default.js +294 -0
- package/src/executors/gemini-cli.js +88 -0
- package/src/executors/github.js +393 -0
- package/src/executors/grok-cli.js +510 -0
- package/src/executors/grok-web.js +342 -0
- package/src/executors/index.js +86 -0
- package/src/executors/kimchi.js +116 -0
- package/src/executors/kiro.js +1155 -0
- package/src/executors/ollama-local.js +14 -0
- package/src/executors/opencode-go.js +47 -0
- package/src/executors/opencode.js +31 -0
- package/src/executors/qoder.js +433 -0
- package/src/executors/trae.js +318 -0
- package/src/executors/vertex.js +151 -0
- package/src/executors/windsurf.js +555 -0
- package/src/executors/xiaomi-tokenplan.js +16 -0
- package/src/handlers/chatCore/nonStreamingHandler.js +370 -0
- package/src/handlers/chatCore/requestDetail.js +130 -0
- package/src/handlers/chatCore/sseToJsonHandler.js +318 -0
- package/src/handlers/chatCore/streamingHandler.js +250 -0
- package/src/handlers/chatCore.js +652 -0
- package/src/lib/auth/dashboardSession.js +83 -0
- package/src/lib/auth/loginLimiter.js +99 -0
- package/src/lib/cache/ttlCache.js +153 -0
- package/src/lib/consoleLogBuffer.js +127 -0
- package/src/lib/dataDir.js +45 -0
- package/src/lib/db/adapters/betterSqliteAdapter.js +36 -0
- package/src/lib/db/adapters/bunSqliteAdapter.js +47 -0
- package/src/lib/db/adapters/nodeSqliteAdapter.js +65 -0
- package/src/lib/db/adapters/runtimeHelpers.js +23 -0
- package/src/lib/db/adapters/sqljsAdapter.js +103 -0
- package/src/lib/db/backup.js +75 -0
- package/src/lib/db/driver.js +110 -0
- package/src/lib/db/helpers/jsonCol.js +18 -0
- package/src/lib/db/helpers/kvStore.js +48 -0
- package/src/lib/db/helpers/metaStore.js +32 -0
- package/src/lib/db/index.js +473 -0
- package/src/lib/db/migrate.js +267 -0
- package/src/lib/db/migrations/001-initial.js +12 -0
- package/src/lib/db/migrations/002-prune-headroom-pxpipe-settings.js +32 -0
- package/src/lib/db/migrations/004-request-details-trace-id.js +12 -0
- package/src/lib/db/migrations/005-request-details-payload-capture.js +11 -0
- package/src/lib/db/migrations/007-headroom-readd-settings.js +35 -0
- package/src/lib/db/migrations/008-account-model-locks.js +22 -0
- package/src/lib/db/migrations/009-warp-pool-lifecycle.js +5 -0
- package/src/lib/db/migrations/010-api-key-file-permissions.js +7 -0
- package/src/lib/db/migrations/011-remove-upstream-user-agent-profile.js +41 -0
- package/src/lib/db/migrations/012-remove-headroom-settings.js +33 -0
- package/src/lib/db/migrations/013-default-fill-first-routing.js +20 -0
- package/src/lib/db/migrations/014-normalize-fill-first-routing.js +37 -0
- package/src/lib/db/migrations/015-remove-ip-ban-tables.js +8 -0
- package/src/lib/db/migrations/016-prune-legacy-codebuddy-intl-models.js +25 -0
- package/src/lib/db/migrations/index.js +20 -0
- package/src/lib/db/nineRouterMigration.js +785 -0
- package/src/lib/db/paths.js +23 -0
- package/src/lib/db/repos/accountModelLocksRepo.js +74 -0
- package/src/lib/db/repos/aliasRepo.js +108 -0
- package/src/lib/db/repos/apiKeysRepo.js +204 -0
- package/src/lib/db/repos/combosRepo.js +85 -0
- package/src/lib/db/repos/connectionsRepo.js +522 -0
- package/src/lib/db/repos/disabledModelsRepo.js +63 -0
- package/src/lib/db/repos/nodesRepo.js +127 -0
- package/src/lib/db/repos/pricingRepo.js +108 -0
- package/src/lib/db/repos/proxyPoolsRepo.js +104 -0
- package/src/lib/db/repos/requestDetailsRepo.js +345 -0
- package/src/lib/db/repos/settingsRepo.js +135 -0
- package/src/lib/db/repos/usageRepo.js +1335 -0
- package/src/lib/db/schema.js +179 -0
- package/src/lib/db/version.js +32 -0
- package/src/lib/db/writeBehind.js +174 -0
- package/src/lib/disabledModelsDb.js +3 -0
- package/src/lib/env.ts +175 -0
- package/src/lib/errors/publicError.js +18 -0
- package/src/lib/grokBuildConfig.js +243 -0
- package/src/lib/guardRequest.js +51 -0
- package/src/lib/localDb.js +21 -0
- package/src/lib/mcp/stdioSseBridge.js +174 -0
- package/src/lib/network/connectionProxy.js +200 -0
- package/src/lib/network/proxyTest.js +158 -0
- package/src/lib/network/proxyUrl.js +76 -0
- package/src/lib/network/relay.js +71 -0
- package/src/lib/oauth/constants/oauth.js +152 -0
- package/src/lib/oauth/constants/xai.js +43 -0
- package/src/lib/oauth/kiroExternalIdp.js +167 -0
- package/src/lib/oauth/providerHelpers.js +90 -0
- package/src/lib/oauth/providers/_shared.js +12 -0
- package/src/lib/oauth/providers/antigravity.js +126 -0
- package/src/lib/oauth/providers/claude.js +60 -0
- package/src/lib/oauth/providers/cline.js +62 -0
- package/src/lib/oauth/providers/clinepass.js +62 -0
- package/src/lib/oauth/providers/codebuddy-cn.js +75 -0
- package/src/lib/oauth/providers/codebuddy-intl.js +73 -0
- package/src/lib/oauth/providers/codex.js +72 -0
- package/src/lib/oauth/providers/cursor.js +18 -0
- package/src/lib/oauth/providers/gemini-cli.js +84 -0
- package/src/lib/oauth/providers/github.js +96 -0
- package/src/lib/oauth/providers/grok-cli.js +123 -0
- package/src/lib/oauth/providers/index.js +233 -0
- package/src/lib/oauth/providers/kilocode.js +60 -0
- package/src/lib/oauth/providers/kimchi.js +79 -0
- package/src/lib/oauth/providers/kimi.js +79 -0
- package/src/lib/oauth/providers/kiro.js +147 -0
- package/src/lib/oauth/providers/qoder.js +90 -0
- package/src/lib/oauth/providers/trae.js +244 -0
- package/src/lib/oauth/providers/windsurf.js +123 -0
- package/src/lib/oauth/providers/xai.js +95 -0
- package/src/lib/oauth/providers.js +16 -0
- package/src/lib/oauth/services/cursor.js +132 -0
- package/src/lib/oauth/services/kiro.js +351 -0
- package/src/lib/oauth/services/oauth.js +135 -0
- package/src/lib/oauth/services/qoder.js +151 -0
- package/src/lib/oauth/services/xai.js +204 -0
- package/src/lib/oauth/utils/ideDetect.js +55 -0
- package/src/lib/oauth/utils/pkce.js +25 -0
- package/src/lib/oauth/utils/server.js +732 -0
- package/src/lib/oauth/utils/ui.js +43 -0
- package/src/lib/providerNormalization.js +40 -0
- package/src/lib/qoder/constants.js +1 -0
- package/src/lib/requestDetailsDb.js +3 -0
- package/src/lib/resourceProfile.ts +124 -0
- package/src/lib/runtimeSecrets.ts +130 -0
- package/src/lib/security/payloadCapture.js +87 -0
- package/src/lib/tunnel/cloudflare/cloudflared.js +436 -0
- package/src/lib/tunnel/cloudflare/config.js +8 -0
- package/src/lib/tunnel/cloudflare/healthCheck.js +37 -0
- package/src/lib/tunnel/cloudflare/manager.js +149 -0
- package/src/lib/tunnel/cloudflare/pid.js +31 -0
- package/src/lib/tunnel/cloudflare/publicUrl.js +41 -0
- package/src/lib/tunnel/cloudflare/requirements.js +12 -0
- package/src/lib/tunnel/index.js +26 -0
- package/src/lib/tunnel/shared/dnsResolver.js +16 -0
- package/src/lib/tunnel/shared/internetCheck.js +30 -0
- package/src/lib/tunnel/shared/state.js +45 -0
- package/src/lib/tunnel/shared/watchdogConfig.js +6 -0
- package/src/lib/update/installer.js +52 -0
- package/src/lib/update/version.js +116 -0
- package/src/lib/usageDb.js +6 -0
- package/src/lib/usageRefresh.js +88 -0
- package/src/lifecycle/appLifecycle.ts +99 -0
- package/src/models.js +36 -0
- package/src/next/headers.js +12 -0
- package/src/next/server.js +74 -0
- package/src/observability/metrics.js +439 -0
- package/src/observability/tracing.js +107 -0
- package/src/open-sse-index.js +70 -0
- package/src/providers/capabilities.js +299 -0
- package/src/providers/display.ts +142 -0
- package/src/providers/index.js +27 -0
- package/src/providers/models/helpers.js +19 -0
- package/src/providers/models/namePatterns.js +27 -0
- package/src/providers/models/schema.js +32 -0
- package/src/providers/pricing.js +248 -0
- package/src/providers/registry/agentrouter.js +52 -0
- package/src/providers/registry/alicode-intl.js +32 -0
- package/src/providers/registry/alicode.js +33 -0
- package/src/providers/registry/alims-intl.js +30 -0
- package/src/providers/registry/anthropic.js +29 -0
- package/src/providers/registry/antigravity.js +139 -0
- package/src/providers/registry/azure.js +23 -0
- package/src/providers/registry/baidu.js +35 -0
- package/src/providers/registry/blackbox.js +41 -0
- package/src/providers/registry/byteplus.js +36 -0
- package/src/providers/registry/cerebras.js +33 -0
- package/src/providers/registry/chutes.js +26 -0
- package/src/providers/registry/claude.js +80 -0
- package/src/providers/registry/cline.js +53 -0
- package/src/providers/registry/clinepass.js +62 -0
- package/src/providers/registry/cloudflare-ai.js +84 -0
- package/src/providers/registry/codebuddy-cn.js +95 -0
- package/src/providers/registry/codebuddy-intl.js +91 -0
- package/src/providers/registry/codex.js +145 -0
- package/src/providers/registry/commandcode.js +45 -0
- package/src/providers/registry/cursor.js +61 -0
- package/src/providers/registry/deepseek.js +55 -0
- package/src/providers/registry/featherless.js +36 -0
- package/src/providers/registry/fireworks.js +34 -0
- package/src/providers/registry/gemini-cli.js +59 -0
- package/src/providers/registry/gemini.js +76 -0
- package/src/providers/registry/github.js +131 -0
- package/src/providers/registry/glm-cn.js +35 -0
- package/src/providers/registry/glm.js +58 -0
- package/src/providers/registry/grok-cli.js +87 -0
- package/src/providers/registry/grok-web.js +41 -0
- package/src/providers/registry/groq.js +38 -0
- package/src/providers/registry/index.js +77 -0
- package/src/providers/registry/kilo-gateway.js +34 -0
- package/src/providers/registry/kilocode.js +48 -0
- package/src/providers/registry/kimchi.js +49 -0
- package/src/providers/registry/kimi.js +82 -0
- package/src/providers/registry/kiro.js +132 -0
- package/src/providers/registry/meta.js +34 -0
- package/src/providers/registry/minimax-cn.js +90 -0
- package/src/providers/registry/minimax.js +90 -0
- package/src/providers/registry/mistral.js +36 -0
- package/src/providers/registry/morph.js +31 -0
- package/src/providers/registry/nebius.js +26 -0
- package/src/providers/registry/nvidia.js +55 -0
- package/src/providers/registry/ollama-local.js +18 -0
- package/src/providers/registry/ollama.js +38 -0
- package/src/providers/registry/openai.js +114 -0
- package/src/providers/registry/opencode-go.js +41 -0
- package/src/providers/registry/opencode.js +26 -0
- package/src/providers/registry/openrouter.js +36 -0
- package/src/providers/registry/perplexity.js +56 -0
- package/src/providers/registry/poolside.js +30 -0
- package/src/providers/registry/qoder.js +58 -0
- package/src/providers/registry/sumopod.js +84 -0
- package/src/providers/registry/tencent.js +29 -0
- package/src/providers/registry/together.js +38 -0
- package/src/providers/registry/trae.js +71 -0
- package/src/providers/registry/venice.js +69 -0
- package/src/providers/registry/vercel-ai-gateway.js +37 -0
- package/src/providers/registry/vertex-partner.js +31 -0
- package/src/providers/registry/vertex.js +33 -0
- package/src/providers/registry/windsurf.js +129 -0
- package/src/providers/registry/xai.js +46 -0
- package/src/providers/registry/xiaomi-mimo.js +66 -0
- package/src/providers/registry/xiaomi-tokenplan.js +58 -0
- package/src/providers/registryEntry.js +3 -0
- package/src/providers/schema.js +33 -0
- package/src/providers/shared.js +114 -0
- package/src/providers/thinkingLevels.js +49 -0
- package/src/routes/api/auth/login/route.js +82 -0
- package/src/routes/api/auth/logout/route.js +9 -0
- package/src/routes/api/auth/reset-password/route.js +12 -0
- package/src/routes/api/auth/status/route.js +33 -0
- package/src/routes/api/auth/verify-password/route.js +39 -0
- package/src/routes/api/chat/tools/curl/route.js +100 -0
- package/src/routes/api/chat/tools/router/route.js +215 -0
- package/src/routes/api/chat/tools/search/route.js +362 -0
- package/src/routes/api/chat/tools/shell/route.js +228 -0
- package/src/routes/api/cli-tools/all-statuses/route.js +37 -0
- package/src/routes/api/cli-tools/claude-settings/route.js +261 -0
- package/src/routes/api/cli-tools/codex-settings/route.js +220 -0
- package/src/routes/api/cli-tools/cowork-mcp-registry/route.js +80 -0
- package/src/routes/api/cli-tools/cowork-mcp-tools/route.js +96 -0
- package/src/routes/api/cli-tools/cowork-settings/route.js +380 -0
- package/src/routes/api/cli-tools/grok-build-settings/route.js +152 -0
- package/src/routes/api/cli-tools/hermes-settings/route.js +169 -0
- package/src/routes/api/cli-tools/kilo-settings/route.js +131 -0
- package/src/routes/api/cli-tools/model-mappings/route.js +43 -0
- package/src/routes/api/cli-tools/omp-settings/route.js +266 -0
- package/src/routes/api/cli-tools/opencode-settings/route.js +243 -0
- package/src/routes/api/combos/[id]/route.js +73 -0
- package/src/routes/api/combos/route.js +43 -0
- package/src/routes/api/health/live/route.js +7 -0
- package/src/routes/api/health/ready/route.js +19 -0
- package/src/routes/api/health/route.js +17 -0
- package/src/routes/api/inflight/stream/route.js +24 -0
- package/src/routes/api/init/route.js +3 -0
- package/src/routes/api/keys/[id]/route.js +71 -0
- package/src/routes/api/keys/route.js +41 -0
- package/src/routes/api/logs/route.js +19 -0
- package/src/routes/api/mcp/[plugin]/message/route.js +23 -0
- package/src/routes/api/mcp/[plugin]/sse/route.js +35 -0
- package/src/routes/api/models/availability/route.js +104 -0
- package/src/routes/api/models/custom/route.js +58 -0
- package/src/routes/api/models/disabled/route.js +47 -0
- package/src/routes/api/models/route.js +64 -0
- package/src/routes/api/models/test/ping.js +236 -0
- package/src/routes/api/models/test/route.js +14 -0
- package/src/routes/api/oauth/[provider]/[action]/route.js +491 -0
- package/src/routes/api/oauth/codex/bulk-import/route.js +105 -0
- package/src/routes/api/oauth/codex/import-token/route.js +82 -0
- package/src/routes/api/oauth/cursor/auto-import/route.js +250 -0
- package/src/routes/api/oauth/cursor/import/route.js +86 -0
- package/src/routes/api/oauth/kiro/api-key/route.js +60 -0
- package/src/routes/api/oauth/kiro/auto-import/route.js +120 -0
- package/src/routes/api/oauth/kiro/import/route.js +72 -0
- package/src/routes/api/oauth/kiro/import-cli-proxy/route.js +42 -0
- package/src/routes/api/oauth/kiro/social-authorize/route.js +40 -0
- package/src/routes/api/oauth/kiro/social-exchange/route.js +62 -0
- package/src/routes/api/pricing/route.js +96 -0
- package/src/routes/api/provider-nodes/[id]/route.js +106 -0
- package/src/routes/api/provider-nodes/route.js +110 -0
- package/src/routes/api/provider-nodes/validate/route.js +197 -0
- package/src/routes/api/providers/[id]/models/route.js +716 -0
- package/src/routes/api/providers/[id]/route.js +195 -0
- package/src/routes/api/providers/[id]/test/route.js +27 -0
- package/src/routes/api/providers/[id]/test/testUtils.js +912 -0
- package/src/routes/api/providers/[id]/test-models/route.js +211 -0
- package/src/routes/api/providers/catalog/route.js +58 -0
- package/src/routes/api/providers/client/route.js +133 -0
- package/src/routes/api/providers/counts/route.js +43 -0
- package/src/routes/api/providers/kilo/free-models/route.js +58 -0
- package/src/routes/api/providers/route.js +361 -0
- package/src/routes/api/providers/suggested-models/filters.js +24 -0
- package/src/routes/api/providers/suggested-models/route.js +34 -0
- package/src/routes/api/providers/test-batch/route.js +145 -0
- package/src/routes/api/providers/validate/route.js +633 -0
- package/src/routes/api/proxy-pools/[id]/route.js +129 -0
- package/src/routes/api/proxy-pools/[id]/test/route.js +64 -0
- package/src/routes/api/proxy-pools/cloudflare-deploy/route.js +183 -0
- package/src/routes/api/proxy-pools/route.js +85 -0
- package/src/routes/api/proxy-pools/vercel-deploy/route.js +181 -0
- package/src/routes/api/settings/currency/route.js +29 -0
- package/src/routes/api/settings/database/path/route.js +8 -0
- package/src/routes/api/settings/database/route.js +89 -0
- package/src/routes/api/settings/migrate-9router/route.js +81 -0
- package/src/routes/api/settings/require-login/route.js +14 -0
- package/src/routes/api/settings/route.js +186 -0
- package/src/routes/api/shutdown/route.js +25 -0
- package/src/routes/api/tags/route.js +17 -0
- package/src/routes/api/translator/console-logs/route.js +28 -0
- package/src/routes/api/translator/console-logs/stream/route.js +95 -0
- package/src/routes/api/tunnel/disable/route.js +18 -0
- package/src/routes/api/tunnel/enable/route.js +32 -0
- package/src/routes/api/tunnel/status/route.js +23 -0
- package/src/routes/api/update/route.js +42 -0
- package/src/routes/api/usage/[connectionId]/codex-reset-credits/route.js +169 -0
- package/src/routes/api/usage/[connectionId]/route.js +222 -0
- package/src/routes/api/usage/chart/route.js +27 -0
- package/src/routes/api/usage/history/route.js +94 -0
- package/src/routes/api/usage/logs/route.js +14 -0
- package/src/routes/api/usage/providers/route.js +36 -0
- package/src/routes/api/usage/request-details/route.js +61 -0
- package/src/routes/api/usage/request-logs/route.js +15 -0
- package/src/routes/api/usage/stats/route.js +23 -0
- package/src/routes/api/usage/stream/route.js +78 -0
- package/src/routes/api/v1/api/chat/route.js +36 -0
- package/src/routes/api/v1/chat/completions/route.js +28 -0
- package/src/routes/api/v1/images/edits/route.js +70 -0
- package/src/routes/api/v1/images/generations/route.js +50 -0
- package/src/routes/api/v1/images/imageValidation.js +45 -0
- package/src/routes/api/v1/messages/count_tokens/route.js +87 -0
- package/src/routes/api/v1/messages/route.js +26 -0
- package/src/routes/api/v1/models/route.js +440 -0
- package/src/routes/api/v1/responses/compact/route.js +34 -0
- package/src/routes/api/v1/responses/route.js +26 -0
- package/src/routes/api/v1/route.js +1 -0
- package/src/routes/api/version/route.js +11 -0
- package/src/routes/table.js +1141 -0
- package/src/rtk/applyFilter.js +13 -0
- package/src/rtk/autodetect.js +104 -0
- package/src/rtk/caveman.js +6 -0
- package/src/rtk/cavemanPrompts.js +107 -0
- package/src/rtk/constants.js +51 -0
- package/src/rtk/filters/buildOutput.js +120 -0
- package/src/rtk/filters/dedupLog.js +43 -0
- package/src/rtk/filters/find.js +47 -0
- package/src/rtk/filters/gitDiff.js +90 -0
- package/src/rtk/filters/gitLog.js +88 -0
- package/src/rtk/filters/gitStatus.js +101 -0
- package/src/rtk/filters/grep.js +45 -0
- package/src/rtk/filters/ls.js +73 -0
- package/src/rtk/filters/readNumbered.js +22 -0
- package/src/rtk/filters/searchList.js +49 -0
- package/src/rtk/filters/smartTruncate.js +13 -0
- package/src/rtk/filters/tree.js +28 -0
- package/src/rtk/index.js +143 -0
- package/src/rtk/ponytail.js +6 -0
- package/src/rtk/ponytailPrompt.js +49 -0
- package/src/rtk/systemInject.js +89 -0
- package/src/server.ts +474 -0
- package/src/services/accountFallback.js +241 -0
- package/src/services/accountPool.js +389 -0
- package/src/services/capacityAdapter.js +140 -0
- package/src/services/cliModelMapping.js +84 -0
- package/src/services/clinepassModels.js +60 -0
- package/src/services/codebuddyModels.js +250 -0
- package/src/services/combo.js +482 -0
- package/src/services/copilotModels.js +126 -0
- package/src/services/currencyRate.js +56 -0
- package/src/services/cursorModels.js +197 -0
- package/src/services/grokCliModels.js +130 -0
- package/src/services/kimchiModels.js +175 -0
- package/src/services/kiroModels.js +246 -0
- package/src/services/model.js +83 -0
- package/src/services/oauthCredentialManager.js +153 -0
- package/src/services/projectId.js +240 -0
- package/src/services/provider.js +145 -0
- package/src/services/qoderModels.js +274 -0
- package/src/services/tokenRefresh/dedup.js +70 -0
- package/src/services/tokenRefresh/providers.js +626 -0
- package/src/services/tokenRefresh.js +274 -0
- package/src/services/usage/claude.js +134 -0
- package/src/services/usage/codebuddy-cn.js +212 -0
- package/src/services/usage/codex.js +193 -0
- package/src/services/usage/deepseek.js +103 -0
- package/src/services/usage/github.js +94 -0
- package/src/services/usage/google.js +218 -0
- package/src/services/usage/grok-cli.js +368 -0
- package/src/services/usage/grokCliQuotaFrame.js +170 -0
- package/src/services/usage/kimi.js +185 -0
- package/src/services/usage/kiro.js +172 -0
- package/src/services/usage/minimax.js +215 -0
- package/src/services/usage/misc.js +264 -0
- package/src/services/usage/shared.js +59 -0
- package/src/services/usage.js +56 -0
- package/src/shared/clineAuth.js +37 -0
- package/src/shared/constants/config.js +80 -0
- package/src/shared/constants/coworkPlugins.js +69 -0
- package/src/shared/constants/models.js +41 -0
- package/src/shared/constants/providers.js +128 -0
- package/src/shared/constants/providersDisplay.js +1 -0
- package/src/shared/qoder/constants.js +50 -0
- package/src/shared/qoder/cosy.js +134 -0
- package/src/shared/qoder/encoding.js +36 -0
- package/src/shared/services/initializeApp.js +226 -0
- package/src/shared/services/quotaAutoPing.js +310 -0
- package/src/shared/utils/apiKey.js +65 -0
- package/src/shared/utils/clineAuth.js +1 -0
- package/src/shared/utils/index.js +3 -0
- package/src/shared/utils/machineId.js +60 -0
- package/src/shared/utils/ssrfGuard.js +280 -0
- package/src/sse/handlers/chat.js +426 -0
- package/src/sse/oauthLease.js +32 -0
- package/src/sse/recovery.js +235 -0
- package/src/sse/services/auth.js +489 -0
- package/src/sse/services/backgroundTokenRefresh.js +173 -0
- package/src/sse/services/model.js +129 -0
- package/src/sse/services/requestCancellation.js +4 -0
- package/src/sse/services/tokenRefresh.js +264 -0
- package/src/sse/utils/logger.js +142 -0
- package/src/staticServe.ts +95 -0
- package/src/transformer/streamToJsonConverter.js +87 -0
- package/src/translator/canonical.js +81 -0
- package/src/translator/concerns/chunk.js +9 -0
- package/src/translator/concerns/compatFallback.js +147 -0
- package/src/translator/concerns/finishReason.js +59 -0
- package/src/translator/concerns/image.js +105 -0
- package/src/translator/concerns/json.js +4 -0
- package/src/translator/concerns/kiroConversation.js +428 -0
- package/src/translator/concerns/message.js +5 -0
- package/src/translator/concerns/modality.js +134 -0
- package/src/translator/concerns/paramSupport.js +97 -0
- package/src/translator/concerns/prefetch.js +86 -0
- package/src/translator/concerns/reasoning.js +18 -0
- package/src/translator/concerns/thinking.js +40 -0
- package/src/translator/concerns/thinkingUnified.js +319 -0
- package/src/translator/concerns/toolCall.js +134 -0
- package/src/translator/concerns/usage.js +61 -0
- package/src/translator/detection.js +42 -0
- package/src/translator/formats/claude.js +323 -0
- package/src/translator/formats/gemini.js +366 -0
- package/src/translator/formats/maxTokens.js +19 -0
- package/src/translator/formats/openai.js +116 -0
- package/src/translator/formats/responsesApi.js +117 -0
- package/src/translator/formats.js +28 -0
- package/src/translator/index.js +237 -0
- package/src/translator/request/antigravity-to-openai.js +217 -0
- package/src/translator/request/claude-to-kiro.js +288 -0
- package/src/translator/request/claude-to-openai.js +199 -0
- package/src/translator/request/gemini-to-openai.js +142 -0
- package/src/translator/request/openai-responses.js +373 -0
- package/src/translator/request/openai-to-claude.js +260 -0
- package/src/translator/request/openai-to-commandcode.js +161 -0
- package/src/translator/request/openai-to-cursor.js +175 -0
- package/src/translator/request/openai-to-gemini.js +422 -0
- package/src/translator/request/openai-to-kiro.js +360 -0
- package/src/translator/request/openai-to-ollama.js +152 -0
- package/src/translator/request/openai-to-vertex.js +36 -0
- package/src/translator/response/claude-to-openai.js +185 -0
- package/src/translator/response/commandcode-to-openai.js +164 -0
- package/src/translator/response/cursor-to-openai.js +18 -0
- package/src/translator/response/gemini-to-openai.js +127 -0
- package/src/translator/response/kiro-to-claude.js +230 -0
- package/src/translator/response/kiro-to-openai.js +136 -0
- package/src/translator/response/ollama-to-openai.js +106 -0
- package/src/translator/response/openai-responses.js +534 -0
- package/src/translator/response/openai-to-antigravity.js +107 -0
- package/src/translator/response/openai-to-claude.js +231 -0
- package/src/translator/schema/blocks.js +40 -0
- package/src/translator/schema/defaults.js +3 -0
- package/src/translator/schema/finishReasons.js +22 -0
- package/src/translator/schema/index.js +7 -0
- package/src/translator/schema/roles.js +12 -0
- package/src/transport/requestBoundary.ts +223 -0
- package/src/transport/routerAdmission.ts +380 -0
- package/src/types/provider.ts +59 -0
- package/src/utils/bypassHandler.js +272 -0
- package/src/utils/claudeCloaking.js +10 -0
- package/src/utils/claudeSignature.js +35 -0
- package/src/utils/clientDetector.js +183 -0
- package/src/utils/cursorChecksum.js +104 -0
- package/src/utils/cursorProtobuf.js +801 -0
- package/src/utils/debugLog.js +12 -0
- package/src/utils/error.js +120 -0
- package/src/utils/inflight.js +127 -0
- package/src/utils/kiroSessionReplay.js +139 -0
- package/src/utils/ollamaTransform.js +83 -0
- package/src/utils/proxyFetch.js +308 -0
- package/src/utils/reasoningContentInjector.js +71 -0
- package/src/utils/requestLogger.js +272 -0
- package/src/utils/responsesStreamHelpers.js +46 -0
- package/src/utils/sessionManager.js +205 -0
- package/src/utils/sse.js +13 -0
- package/src/utils/sseConstants.js +21 -0
- package/src/utils/stream.js +511 -0
- package/src/utils/streamHandler.js +256 -0
- package/src/utils/streamHelpers.js +113 -0
- package/src/utils/toolDeduper.js +44 -0
- package/src/utils/usageTracking.js +329 -0
- package/tsconfig.json +45 -0
|
@@ -0,0 +1,426 @@
|
|
|
1
|
+
import "../../open-sse-index.js";
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
getProviderCredentials,
|
|
5
|
+
markAccountUnavailable,
|
|
6
|
+
clearAccountError,
|
|
7
|
+
extractApiKey,
|
|
8
|
+
isValidApiKey,
|
|
9
|
+
} from "../services/auth.js";
|
|
10
|
+
import { extractCacheKey } from "../../services/accountFallback.js";
|
|
11
|
+
import { getSettings, getProviderConnectionById } from "@/lib/localDb";
|
|
12
|
+
import { getModelInfo, getComboModels } from "../services/model.js";
|
|
13
|
+
import { handleChatCore } from "../../handlers/chatCore.js";
|
|
14
|
+
import { errorResponse, unavailableResponse } from "../../utils/error.js";
|
|
15
|
+
import { handleComboChat, handleFusionChat, detectRequiredCapabilities } from "../../services/combo.js";
|
|
16
|
+
import { augmentModelsWithCapacityAdapter, withCapacityAdapterStripping, getActiveAdapterStrategy } from "../../services/capacityAdapter.js";
|
|
17
|
+
import { handleBypassRequest } from "../../utils/bypassHandler.js";
|
|
18
|
+
import { HTTP_STATUS } from "../../config/runtimeConfig.js";
|
|
19
|
+
import { detectFormatByEndpoint } from "../../translator/formats.js";
|
|
20
|
+
import * as log from "../utils/logger.js";
|
|
21
|
+
import { updateProviderCredentials, checkAndRefreshToken } from "../services/tokenRefresh.js";
|
|
22
|
+
import { getProjectIdForConnection } from "../../services/projectId.js";
|
|
23
|
+
import { getConsistentMachineId } from "@/shared/utils/machineId";
|
|
24
|
+
import { isCallerCancellation } from "../services/requestCancellation.js";
|
|
25
|
+
import { env } from "@/lib/env";
|
|
26
|
+
|
|
27
|
+
const INTERNAL_CLI_TOKEN_HEADER = "x-swayrouter-cli-token";
|
|
28
|
+
const INTERNAL_CONNECTION_HEADER = "x-swayrouter-connection-id";
|
|
29
|
+
const INTERNAL_CLI_TOKEN_SALT = "swayrouter-cli-auth";
|
|
30
|
+
|
|
31
|
+
function attachAccountLease(response, release) {
|
|
32
|
+
if (!response || typeof release !== "function") return response;
|
|
33
|
+
|
|
34
|
+
let released = false;
|
|
35
|
+
const releaseOnce = () => {
|
|
36
|
+
if (released) return;
|
|
37
|
+
released = true;
|
|
38
|
+
release();
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
const contentType = response.headers?.get("content-type") || "";
|
|
42
|
+
if (!response.body || !contentType.toLowerCase().includes("text/event-stream")) {
|
|
43
|
+
releaseOnce();
|
|
44
|
+
return response;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const reader = response.body.getReader();
|
|
48
|
+
const body = new ReadableStream({
|
|
49
|
+
async pull(controller) {
|
|
50
|
+
try {
|
|
51
|
+
const { done, value } = await reader.read();
|
|
52
|
+
if (done) {
|
|
53
|
+
releaseOnce();
|
|
54
|
+
controller.close();
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
controller.enqueue(value);
|
|
58
|
+
} catch (error) {
|
|
59
|
+
releaseOnce();
|
|
60
|
+
try { controller.error(error); } catch { }
|
|
61
|
+
}
|
|
62
|
+
},
|
|
63
|
+
cancel(reason) {
|
|
64
|
+
releaseOnce();
|
|
65
|
+
return reader.cancel(reason);
|
|
66
|
+
},
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
return new Response(body, {
|
|
70
|
+
status: response.status,
|
|
71
|
+
statusText: response.statusText,
|
|
72
|
+
headers: new Headers(response.headers),
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async function getPreferredConnectionId(request) {
|
|
77
|
+
const connectionId = request?.headers?.get(INTERNAL_CONNECTION_HEADER) || "";
|
|
78
|
+
if (!connectionId || !/^[a-zA-Z0-9_-]{8,128}$/.test(connectionId)) return null;
|
|
79
|
+
|
|
80
|
+
const presentedToken = request.headers.get(INTERNAL_CLI_TOKEN_HEADER) || "";
|
|
81
|
+
if (!presentedToken) return null;
|
|
82
|
+
try {
|
|
83
|
+
const expectedToken = await getConsistentMachineId(INTERNAL_CLI_TOKEN_SALT);
|
|
84
|
+
if (!expectedToken || presentedToken !== expectedToken) return null;
|
|
85
|
+
const connection = await getProviderConnectionById(connectionId);
|
|
86
|
+
return connection?.isActive === true ? connectionId : null;
|
|
87
|
+
} catch {
|
|
88
|
+
return null;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function validateChatBody(body, pathname) {
|
|
93
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) {
|
|
94
|
+
return "Request body must be a JSON object";
|
|
95
|
+
}
|
|
96
|
+
if (typeof body.model !== "string" || !body.model.trim()) {
|
|
97
|
+
return "Missing model";
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const path = String(pathname || "").replace(/\/$/, "");
|
|
101
|
+
const requiresMessages = path.endsWith("/chat/completions") || path.endsWith("/messages");
|
|
102
|
+
if (requiresMessages && !Array.isArray(body.messages)) {
|
|
103
|
+
return "messages must be a non-empty array";
|
|
104
|
+
}
|
|
105
|
+
if (Array.isArray(body.messages)) {
|
|
106
|
+
if (body.messages.length === 0 && requiresMessages) return "messages must be a non-empty array";
|
|
107
|
+
for (const message of body.messages) {
|
|
108
|
+
if (!message || typeof message !== "object" || Array.isArray(message) || typeof message.role !== "string" || !message.role.trim()) {
|
|
109
|
+
return "Each message must be an object with a non-empty role";
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export async function handleChat(request, clientRawRequest = null) {
|
|
117
|
+
let body;
|
|
118
|
+
try {
|
|
119
|
+
body = await request.json();
|
|
120
|
+
} catch {
|
|
121
|
+
log.warn("CHAT", "Invalid JSON body");
|
|
122
|
+
return errorResponse(HTTP_STATUS.BAD_REQUEST, "Invalid JSON body");
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const validationError = validateChatBody(body, new URL(request.url).pathname);
|
|
126
|
+
if (validationError) {
|
|
127
|
+
log.warn("CHAT", validationError);
|
|
128
|
+
return errorResponse(HTTP_STATUS.BAD_REQUEST, validationError);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
if (!clientRawRequest) {
|
|
132
|
+
const url = new URL(request.url);
|
|
133
|
+
clientRawRequest = {
|
|
134
|
+
endpoint: url.pathname,
|
|
135
|
+
body,
|
|
136
|
+
headers: Object.fromEntries(request.headers.entries())
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
const modelStr = body.model.trim();
|
|
140
|
+
body.model = modelStr;
|
|
141
|
+
const preferredConnectionId = await getPreferredConnectionId(request);
|
|
142
|
+
const isTrustedInternalRequest = Boolean(preferredConnectionId);
|
|
143
|
+
|
|
144
|
+
const authHeader = request.headers.get("Authorization");
|
|
145
|
+
const apiKey = extractApiKey(request);
|
|
146
|
+
if (authHeader && apiKey) {
|
|
147
|
+
const masked = log.maskKey(apiKey);
|
|
148
|
+
log.debug("AUTH", `API Key: ${masked}`);
|
|
149
|
+
} else {
|
|
150
|
+
log.debug("AUTH", "No API key provided (local mode)");
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const settings = await getSettings();
|
|
154
|
+
|
|
155
|
+
if (settings.requireApiKey || env.nodeEnv === "production") {
|
|
156
|
+
if (!isTrustedInternalRequest && !apiKey) {
|
|
157
|
+
log.warn("AUTH", "Missing API key (requireApiKey=true)");
|
|
158
|
+
return errorResponse(HTTP_STATUS.UNAUTHORIZED, "Missing API key");
|
|
159
|
+
}
|
|
160
|
+
if (!isTrustedInternalRequest && !(await isValidApiKey(apiKey))) {
|
|
161
|
+
log.warn("AUTH", "Invalid API key (requireApiKey=true)");
|
|
162
|
+
return errorResponse(HTTP_STATUS.UNAUTHORIZED, "Invalid API key");
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
if (!modelStr) {
|
|
167
|
+
log.warn("CHAT", "Missing model");
|
|
168
|
+
return errorResponse(HTTP_STATUS.BAD_REQUEST, "Missing model");
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const userAgent = request?.headers?.get("user-agent") || "";
|
|
172
|
+
const bypassResponse = handleBypassRequest(body, modelStr, userAgent, !!settings.ccFilterNaming);
|
|
173
|
+
if (bypassResponse) return bypassResponse.response || bypassResponse;
|
|
174
|
+
|
|
175
|
+
const requiredCapabilities = detectRequiredCapabilities(body);
|
|
176
|
+
|
|
177
|
+
const comboModels = await getComboModels(modelStr);
|
|
178
|
+
if (comboModels) {
|
|
179
|
+
|
|
180
|
+
const comboStrategies = settings.comboStrategies || {};
|
|
181
|
+
const comboSpecificStrategy = comboStrategies[modelStr]?.fallbackStrategy;
|
|
182
|
+
const comboStrategy = comboSpecificStrategy || settings.comboStrategy || "fallback";
|
|
183
|
+
const augmentedModels = augmentModelsWithCapacityAdapter(comboModels, requiredCapabilities, settings);
|
|
184
|
+
const adapterAdded = augmentedModels.filter((m) => !comboModels.includes(m));
|
|
185
|
+
|
|
186
|
+
if (comboStrategy === "fusion") {
|
|
187
|
+
log.info("CHAT", `Combo "${modelStr}" with ${comboModels.length} models (strategy: fusion)`);
|
|
188
|
+
return handleFusionChat({
|
|
189
|
+
body,
|
|
190
|
+
models: comboModels,
|
|
191
|
+
handleSingleModel: (b, m, isPanel, panelSignal) => {
|
|
192
|
+
let cleanRawReq = clientRawRequest;
|
|
193
|
+
if (isPanel && clientRawRequest) {
|
|
194
|
+
const { tools, tool_choice, ...cleanBody } = clientRawRequest.body || {};
|
|
195
|
+
cleanRawReq = { ...clientRawRequest, body: cleanBody };
|
|
196
|
+
}
|
|
197
|
+
return handleSingleModelChat(b, m, cleanRawReq, request, apiKey, preferredConnectionId, isPanel ? panelSignal : request?.signal);
|
|
198
|
+
},
|
|
199
|
+
log,
|
|
200
|
+
comboName: modelStr,
|
|
201
|
+
judgeModel: comboStrategies[modelStr]?.judgeModel,
|
|
202
|
+
tuning: comboStrategies[modelStr]?.fusionTuning,
|
|
203
|
+
signal: request?.signal,
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const comboStickyLimit = settings.comboStickyRoundRobinLimit;
|
|
208
|
+
log.info("CHAT", `Combo "${modelStr}" with ${augmentedModels.length} models (strategy: ${comboStrategy}, sticky: ${comboStickyLimit})`);
|
|
209
|
+
return handleComboChat({
|
|
210
|
+
body,
|
|
211
|
+
models: augmentedModels,
|
|
212
|
+
handleSingleModel: withCapacityAdapterStripping(
|
|
213
|
+
(b, m) => handleSingleModelChat(b, m, clientRawRequest, request, apiKey, preferredConnectionId, request?.signal),
|
|
214
|
+
adapterAdded
|
|
215
|
+
),
|
|
216
|
+
log,
|
|
217
|
+
comboName: modelStr,
|
|
218
|
+
comboStrategy,
|
|
219
|
+
comboStickyLimit
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
const soloAugmented = augmentModelsWithCapacityAdapter([modelStr], requiredCapabilities, settings);
|
|
224
|
+
if (soloAugmented.length > 1) {
|
|
225
|
+
const adapterAdded = soloAugmented.filter((m) => m !== modelStr);
|
|
226
|
+
log.info("CHAT", `Capacity adapter for [${[...requiredCapabilities].join(",")}] on "${modelStr}" → trying ${soloAugmented.join(", ")}`);
|
|
227
|
+
return handleComboChat({
|
|
228
|
+
body,
|
|
229
|
+
models: soloAugmented,
|
|
230
|
+
handleSingleModel: withCapacityAdapterStripping(
|
|
231
|
+
(b, m) => handleSingleModelChat(b, m, clientRawRequest, request, apiKey, preferredConnectionId, request?.signal),
|
|
232
|
+
adapterAdded
|
|
233
|
+
),
|
|
234
|
+
log,
|
|
235
|
+
comboName: modelStr,
|
|
236
|
+
comboStrategy: getActiveAdapterStrategy(requiredCapabilities, settings)
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
return handleSingleModelChat(body, modelStr, clientRawRequest, request, apiKey, preferredConnectionId, request?.signal);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
async function handleSingleModelChat(body, modelStr, clientRawRequest = null, request = null, apiKey = null, preferredConnectionId = null, requestSignal = null) {
|
|
244
|
+
requestSignal ||= request?.signal || null;
|
|
245
|
+
if (requestSignal?.aborted) return errorResponse(499, "Request aborted");
|
|
246
|
+
const incomingClient = clientRawRequest?.headers
|
|
247
|
+
? Object.fromEntries(clientRawRequest.headers.entries?.() || [])
|
|
248
|
+
: {};
|
|
249
|
+
const settings = await getSettings();
|
|
250
|
+
const { resolveCliModelMapping } = await import("../../services/cliModelMapping.js");
|
|
251
|
+
const { detectClient } = await import("../../utils/clientDetector.js");
|
|
252
|
+
const clientMeta = detectClient(incomingClient, body, { path: clientRawRequest?.endpoint || "" });
|
|
253
|
+
const mappedModelStr = resolveCliModelMapping(clientMeta.id, modelStr, settings.cliModelMappings);
|
|
254
|
+
const modelInfo = await getModelInfo(mappedModelStr);
|
|
255
|
+
|
|
256
|
+
if (!modelInfo.provider) {
|
|
257
|
+
const comboModels = await getComboModels(modelStr);
|
|
258
|
+
if (comboModels) {
|
|
259
|
+
const chatSettings = await getSettings();
|
|
260
|
+
|
|
261
|
+
const comboStrategies = chatSettings.comboStrategies || {};
|
|
262
|
+
const comboSpecificStrategy = comboStrategies[modelStr]?.fallbackStrategy;
|
|
263
|
+
const comboStrategy = comboSpecificStrategy || chatSettings.comboStrategy || "fallback";
|
|
264
|
+
const requiredCapabilities = detectRequiredCapabilities(body);
|
|
265
|
+
const augmentedModels = augmentModelsWithCapacityAdapter(comboModels, requiredCapabilities, chatSettings);
|
|
266
|
+
const adapterAdded = augmentedModels.filter((m) => !comboModels.includes(m));
|
|
267
|
+
|
|
268
|
+
if (comboStrategy === "fusion") {
|
|
269
|
+
log.info("CHAT", `Combo "${modelStr}" with ${comboModels.length} models (strategy: fusion)`);
|
|
270
|
+
return handleFusionChat({
|
|
271
|
+
body,
|
|
272
|
+
models: comboModels,
|
|
273
|
+
handleSingleModel: (b, m, isPanel, panelSignal) => {
|
|
274
|
+
let cleanRawReq = clientRawRequest;
|
|
275
|
+
if (isPanel && clientRawRequest) {
|
|
276
|
+
const { tools, tool_choice, ...cleanBody } = clientRawRequest.body || {};
|
|
277
|
+
cleanRawReq = { ...clientRawRequest, body: cleanBody };
|
|
278
|
+
}
|
|
279
|
+
return handleSingleModelChat(b, m, cleanRawReq, request, apiKey, preferredConnectionId, isPanel ? panelSignal : request?.signal);
|
|
280
|
+
},
|
|
281
|
+
log,
|
|
282
|
+
comboName: modelStr,
|
|
283
|
+
judgeModel: comboStrategies[modelStr]?.judgeModel,
|
|
284
|
+
tuning: comboStrategies[modelStr]?.fusionTuning,
|
|
285
|
+
signal: request?.signal,
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
const comboStickyLimit = chatSettings.comboStickyRoundRobinLimit;
|
|
290
|
+
log.info("CHAT", `Combo "${modelStr}" with ${augmentedModels.length} models (strategy: ${comboStrategy}, sticky: ${comboStickyLimit})`);
|
|
291
|
+
return handleComboChat({
|
|
292
|
+
body,
|
|
293
|
+
models: augmentedModels,
|
|
294
|
+
handleSingleModel: withCapacityAdapterStripping(
|
|
295
|
+
(b, m) => handleSingleModelChat(b, m, clientRawRequest, request, apiKey, preferredConnectionId, request?.signal),
|
|
296
|
+
adapterAdded
|
|
297
|
+
),
|
|
298
|
+
log,
|
|
299
|
+
comboName: modelStr,
|
|
300
|
+
comboStrategy,
|
|
301
|
+
comboStickyLimit
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
log.warn("CHAT", "Invalid model format", { model: modelStr });
|
|
305
|
+
return errorResponse(HTTP_STATUS.BAD_REQUEST, "Invalid model format");
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
const { provider, model } = modelInfo;
|
|
309
|
+
|
|
310
|
+
const userAgent = request?.headers?.get("user-agent") || "";
|
|
311
|
+
|
|
312
|
+
const excludeConnectionIds = new Set();
|
|
313
|
+
let lastError = null;
|
|
314
|
+
let lastStatus = null;
|
|
315
|
+
|
|
316
|
+
const cacheKey = extractCacheKey(body);
|
|
317
|
+
let retryCount = 0;
|
|
318
|
+
|
|
319
|
+
while (true) {
|
|
320
|
+
const credentials = await getProviderCredentials(provider, excludeConnectionIds, model, {
|
|
321
|
+
cacheKey,
|
|
322
|
+
preferredConnectionId,
|
|
323
|
+
signal: requestSignal,
|
|
324
|
+
});
|
|
325
|
+
|
|
326
|
+
if (!credentials || credentials.allRateLimited) {
|
|
327
|
+
if (credentials?.allRateLimited) {
|
|
328
|
+
const status = lastStatus || Number(credentials.lastErrorCode) || HTTP_STATUS.SERVICE_UNAVAILABLE;
|
|
329
|
+
const retryMessage = "All provider accounts are temporarily unavailable";
|
|
330
|
+
log.warn("CHAT", `[${provider}/${model}] ${lastError || credentials.lastError || "Unavailable"} (${credentials.retryAfterHuman})`);
|
|
331
|
+
return unavailableResponse(status, retryMessage, credentials.retryAfter, credentials.retryAfterHuman);
|
|
332
|
+
}
|
|
333
|
+
if (excludeConnectionIds.size === 0) {
|
|
334
|
+
log.warn("AUTH", `No active credentials for provider: ${provider}`);
|
|
335
|
+
return errorResponse(HTTP_STATUS.NOT_FOUND, "No active credentials available");
|
|
336
|
+
}
|
|
337
|
+
log.warn("CHAT", "No more accounts available", { provider });
|
|
338
|
+
return errorResponse(lastStatus || HTTP_STATUS.SERVICE_UNAVAILABLE, "All provider accounts are unavailable");
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
if (credentials.allBusy) {
|
|
342
|
+
if (credentials.reason === "aborted" || requestSignal?.aborted) {
|
|
343
|
+
return errorResponse(499, "Request aborted");
|
|
344
|
+
}
|
|
345
|
+
return unavailableResponse(
|
|
346
|
+
HTTP_STATUS.SERVICE_UNAVAILABLE,
|
|
347
|
+
"Provider account pool is busy",
|
|
348
|
+
credentials.retryAfter,
|
|
349
|
+
credentials.retryAfterHuman || "retry shortly",
|
|
350
|
+
);
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
const releaseAccountSlot = credentials.releaseAccountSlot;
|
|
354
|
+
let result;
|
|
355
|
+
try {
|
|
356
|
+
const refreshedCredentials = await checkAndRefreshToken(provider, credentials);
|
|
357
|
+
|
|
358
|
+
if ((provider === "antigravity" || provider === "gemini-cli") && !refreshedCredentials.projectId) {
|
|
359
|
+
const pid = await getProjectIdForConnection(credentials.connectionId, refreshedCredentials.accessToken, provider);
|
|
360
|
+
if (pid) {
|
|
361
|
+
refreshedCredentials.projectId = pid;
|
|
362
|
+
|
|
363
|
+
updateProviderCredentials(credentials.connectionId, { projectId: pid }).catch(() => { });
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
const chatSettings = await getSettings();
|
|
368
|
+
const providerThinking = (chatSettings.providerThinking || {})[provider] || null;
|
|
369
|
+
result = await handleChatCore({
|
|
370
|
+
body: { ...body, model: `${provider}/${model}` },
|
|
371
|
+
modelInfo: { provider, model, modelCapabilities: modelInfo.modelCapabilities },
|
|
372
|
+
credentials: refreshedCredentials,
|
|
373
|
+
log,
|
|
374
|
+
clientRawRequest,
|
|
375
|
+
connectionId: credentials.connectionId,
|
|
376
|
+
userAgent,
|
|
377
|
+
apiKey,
|
|
378
|
+
ccFilterNaming: !!chatSettings.ccFilterNaming,
|
|
379
|
+
rtkEnabled: !!chatSettings.rtkEnabled,
|
|
380
|
+
cavemanEnabled: !!chatSettings.cavemanEnabled,
|
|
381
|
+
cavemanLevel: chatSettings.cavemanLevel || "full",
|
|
382
|
+
ponytailEnabled: !!chatSettings.ponytailEnabled,
|
|
383
|
+
ponytailLevel: chatSettings.ponytailLevel || "full",
|
|
384
|
+
providerThinking,
|
|
385
|
+
requestSignal,
|
|
386
|
+
|
|
387
|
+
sourceFormatOverride: request?.url ? detectFormatByEndpoint(new URL(request.url).pathname, body) : null,
|
|
388
|
+
onCredentialsRefreshed: async (newCreds) => {
|
|
389
|
+
await updateProviderCredentials(credentials.connectionId, {
|
|
390
|
+
...newCreds,
|
|
391
|
+
existingProviderSpecificData: credentials.providerSpecificData,
|
|
392
|
+
testStatus: "active"
|
|
393
|
+
});
|
|
394
|
+
},
|
|
395
|
+
onRequestSuccess: async () => {
|
|
396
|
+
await clearAccountError(credentials.connectionId, credentials, model);
|
|
397
|
+
}
|
|
398
|
+
});
|
|
399
|
+
} catch (error) {
|
|
400
|
+
|
|
401
|
+
releaseAccountSlot?.();
|
|
402
|
+
throw error;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
if (result.success) return attachAccountLease(result.response, releaseAccountSlot);
|
|
406
|
+
|
|
407
|
+
releaseAccountSlot?.();
|
|
408
|
+
|
|
409
|
+
if (isCallerCancellation({ requestSignal, status: result.status })) {
|
|
410
|
+
return result.response;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
const { shouldFallback } = await markAccountUnavailable(credentials.connectionId, result.status, result.error, provider, model, result.resetsAtMs, { retryCount });
|
|
414
|
+
|
|
415
|
+
if (shouldFallback) {
|
|
416
|
+
log.warn("FALLBACK", `⇄ ACC:${credentials.connectionName} UNAVAILABLE (${result.status}) → NEXT ACCOUNT`);
|
|
417
|
+
excludeConnectionIds.add(credentials.connectionId);
|
|
418
|
+
lastError = result.error;
|
|
419
|
+
lastStatus = result.status;
|
|
420
|
+
retryCount += 1;
|
|
421
|
+
continue;
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
return result.response;
|
|
425
|
+
}
|
|
426
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { getAccessToken } from "../services/tokenRefresh.js";
|
|
2
|
+
|
|
3
|
+
const LEASES = new Map();
|
|
4
|
+
|
|
5
|
+
export async function forceRefreshOAuth(provider, credentials, log, options = {}) {
|
|
6
|
+
if (options.signal?.aborted) return null;
|
|
7
|
+
const leaseKey = `${provider}:${credentials?.connectionId || "anon"}`;
|
|
8
|
+
|
|
9
|
+
const inflight = LEASES.get(leaseKey);
|
|
10
|
+
if (inflight) {
|
|
11
|
+
log?.debug?.("A4.3", `coalescing in-flight refresh · ${leaseKey}`);
|
|
12
|
+
return inflight;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const refreshPromise = (async () => {
|
|
16
|
+
try {
|
|
17
|
+
const result = await getAccessToken(provider, credentials, log, options);
|
|
18
|
+
if (options.signal?.aborted) return null;
|
|
19
|
+
return result;
|
|
20
|
+
} finally {
|
|
21
|
+
|
|
22
|
+
setTimeout(() => { LEASES.delete(leaseKey); }, 5000);
|
|
23
|
+
}
|
|
24
|
+
})();
|
|
25
|
+
|
|
26
|
+
LEASES.set(leaseKey, refreshPromise);
|
|
27
|
+
return refreshPromise;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function __resetOAuthLeasesForTests() {
|
|
31
|
+
LEASES.clear();
|
|
32
|
+
}
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
import { parseSSELine, hasValuableContent } from "../utils/streamHelpers.js";
|
|
2
|
+
import { isGracefulNetworkClose } from "../utils/streamHandler.js";
|
|
3
|
+
import { FORMATS } from "../translator/formats.js";
|
|
4
|
+
|
|
5
|
+
const DEFAULT_MAX_EVENTS = 8;
|
|
6
|
+
const DEFAULT_MAX_BYTES = 16384;
|
|
7
|
+
const DEFAULT_DEADLINE_MS = 20000;
|
|
8
|
+
|
|
9
|
+
export function classifySSEEvent(parsed, sourceFormat) {
|
|
10
|
+
if (!parsed) return "neutral";
|
|
11
|
+
|
|
12
|
+
if (parsed.done === true) return "neutral";
|
|
13
|
+
|
|
14
|
+
if (parsed.error) return "error";
|
|
15
|
+
if (parsed.type === "error") return "error";
|
|
16
|
+
if (parsed.error_code || parsed.error_message) return "error";
|
|
17
|
+
|
|
18
|
+
if (parsed.candidates?.[0]?.finishReason &&
|
|
19
|
+
parsed.candidates[0].finishReason !== "STOP" &&
|
|
20
|
+
parsed.candidates[0].finishReason !== "FINISH_REASON_UNSPECIFIED") {
|
|
21
|
+
return "error";
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
if (hasValuableContent(parsed, sourceFormat)) return "content";
|
|
25
|
+
|
|
26
|
+
return "neutral";
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function isAuthError(parsed) {
|
|
30
|
+
if (!parsed) return false;
|
|
31
|
+
const errObj = parsed.error;
|
|
32
|
+
if (!errObj || typeof errObj !== "object") return false;
|
|
33
|
+
|
|
34
|
+
const code = String(errObj.code || errObj.type || "").toLowerCase();
|
|
35
|
+
const msg = String(errObj.message || "").toLowerCase();
|
|
36
|
+
|
|
37
|
+
return (
|
|
38
|
+
code.includes("auth") ||
|
|
39
|
+
code.includes("401") ||
|
|
40
|
+
code.includes("unauthorized") ||
|
|
41
|
+
msg.includes("unauthorized") ||
|
|
42
|
+
msg.includes("401") ||
|
|
43
|
+
msg.includes("expired") ||
|
|
44
|
+
msg.includes("invalid_token") ||
|
|
45
|
+
msg.includes("token_expired") ||
|
|
46
|
+
msg.includes("expired_token")
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function createReplayStream(prefixChunks, restReader, pendingRead = null) {
|
|
51
|
+
let prefixIndex = 0;
|
|
52
|
+
let reading = false;
|
|
53
|
+
let settled = false;
|
|
54
|
+
let firstRead = pendingRead;
|
|
55
|
+
|
|
56
|
+
const close = (controller) => {
|
|
57
|
+
if (settled) return;
|
|
58
|
+
settled = true;
|
|
59
|
+
try { controller.close(); } catch { }
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
const readRest = () => {
|
|
63
|
+
if (firstRead) {
|
|
64
|
+
const read = firstRead;
|
|
65
|
+
firstRead = null;
|
|
66
|
+
return read;
|
|
67
|
+
}
|
|
68
|
+
return restReader.read();
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
return new ReadableStream({
|
|
72
|
+
async pull(controller) {
|
|
73
|
+
if (settled || reading) return;
|
|
74
|
+
|
|
75
|
+
if (prefixIndex < prefixChunks.length) {
|
|
76
|
+
try {
|
|
77
|
+
controller.enqueue(prefixChunks[prefixIndex++]);
|
|
78
|
+
} catch {
|
|
79
|
+
settled = true;
|
|
80
|
+
}
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
reading = true;
|
|
85
|
+
try {
|
|
86
|
+
const { done, value } = await readRest();
|
|
87
|
+
if (settled) return;
|
|
88
|
+
if (done) {
|
|
89
|
+
close(controller);
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
try { controller.enqueue(value); } catch { settled = true; }
|
|
93
|
+
} catch (err) {
|
|
94
|
+
if (settled) return;
|
|
95
|
+
settled = true;
|
|
96
|
+
try { controller.error(err); } catch { }
|
|
97
|
+
} finally {
|
|
98
|
+
reading = false;
|
|
99
|
+
}
|
|
100
|
+
},
|
|
101
|
+
cancel() {
|
|
102
|
+
settled = true;
|
|
103
|
+
firstRead = null;
|
|
104
|
+
restReader.cancel().catch(() => {});
|
|
105
|
+
},
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export async function previewSSEPrefix(providerResponse, sourceFormat, opts = {}) {
|
|
110
|
+
const maxEvents = opts.maxEvents ?? DEFAULT_MAX_EVENTS;
|
|
111
|
+
const maxBytes = opts.maxBytes ?? DEFAULT_MAX_BYTES;
|
|
112
|
+
const deadlineMs = opts.deadlineMs ?? DEFAULT_DEADLINE_MS;
|
|
113
|
+
const log = opts.log ?? null;
|
|
114
|
+
const reqTag = opts.reqTag ?? "";
|
|
115
|
+
const callerSignal = opts.signal ?? null;
|
|
116
|
+
|
|
117
|
+
const body = providerResponse.body;
|
|
118
|
+
if (!body) return _verdict("streamClosed", { eventsSeen: 0, bytesRead: 0 });
|
|
119
|
+
|
|
120
|
+
const reader = body.getReader();
|
|
121
|
+
const decoder = new TextDecoder();
|
|
122
|
+
const prefixChunks = [];
|
|
123
|
+
|
|
124
|
+
let lineBuffer = "";
|
|
125
|
+
let eventLines = [];
|
|
126
|
+
let totalBytes = 0;
|
|
127
|
+
let eventsSeen = 0;
|
|
128
|
+
let committed = false;
|
|
129
|
+
let errorEvent = null;
|
|
130
|
+
let errorIsAuth = false;
|
|
131
|
+
let deadlineTimer = null;
|
|
132
|
+
let deadlineHit = false;
|
|
133
|
+
let pendingRead = null;
|
|
134
|
+
|
|
135
|
+
const deadline = new Promise((resolve) => {
|
|
136
|
+
deadlineTimer = setTimeout(() => { deadlineHit = true; resolve("deadline"); }, deadlineMs);
|
|
137
|
+
});
|
|
138
|
+
const abortPromise = callerSignal
|
|
139
|
+
? new Promise((resolve) => {
|
|
140
|
+
if (callerSignal.aborted) resolve("caller-abort");
|
|
141
|
+
else callerSignal.addEventListener("abort", () => resolve("caller-abort"), { once: true });
|
|
142
|
+
})
|
|
143
|
+
: null;
|
|
144
|
+
|
|
145
|
+
try {
|
|
146
|
+
while (eventsSeen < maxEvents && totalBytes < maxBytes && !committed && !errorEvent) {
|
|
147
|
+
pendingRead = reader.read();
|
|
148
|
+
const readResult = await Promise.race([pendingRead, deadline, abortPromise].filter(Boolean));
|
|
149
|
+
|
|
150
|
+
if (readResult === "caller-abort") {
|
|
151
|
+
reader.cancel().catch(() => {});
|
|
152
|
+
return _verdict("callerAbort", { eventsSeen, bytesRead: totalBytes });
|
|
153
|
+
}
|
|
154
|
+
if (readResult === "deadline") break;
|
|
155
|
+
pendingRead = null;
|
|
156
|
+
|
|
157
|
+
const { done, value } = readResult;
|
|
158
|
+
if (done) break;
|
|
159
|
+
|
|
160
|
+
prefixChunks.push(value);
|
|
161
|
+
totalBytes += value.byteLength;
|
|
162
|
+
|
|
163
|
+
lineBuffer += decoder.decode(value, { stream: true });
|
|
164
|
+
const lines = lineBuffer.split("\n");
|
|
165
|
+
lineBuffer = lines.pop() ?? "";
|
|
166
|
+
|
|
167
|
+
for (const line of lines) {
|
|
168
|
+
if (line === "") {
|
|
169
|
+
|
|
170
|
+
eventsSeen += 1;
|
|
171
|
+
for (const eline of eventLines) {
|
|
172
|
+
const parsed = parseSSELine(eline, sourceFormat);
|
|
173
|
+
const cls = classifySSEEvent(parsed, sourceFormat);
|
|
174
|
+
|
|
175
|
+
if (cls === "content") {
|
|
176
|
+
committed = true;
|
|
177
|
+
break;
|
|
178
|
+
}
|
|
179
|
+
if (cls === "error") {
|
|
180
|
+
errorEvent = parsed;
|
|
181
|
+
errorIsAuth = isAuthError(parsed);
|
|
182
|
+
break;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
eventLines = [];
|
|
186
|
+
if (committed || errorEvent) break;
|
|
187
|
+
} else {
|
|
188
|
+
eventLines.push(line);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
if (committed || errorEvent) break;
|
|
192
|
+
}
|
|
193
|
+
} catch (error) {
|
|
194
|
+
if (callerSignal?.aborted) {
|
|
195
|
+
reader.cancel().catch(() => {});
|
|
196
|
+
pendingRead?.catch?.(() => {});
|
|
197
|
+
return _verdict("callerAbort", { eventsSeen, bytesRead: totalBytes });
|
|
198
|
+
}
|
|
199
|
+
if (isGracefulNetworkClose(error)) {
|
|
200
|
+
reader.cancel().catch(() => {});
|
|
201
|
+
return _verdict("networkError", {
|
|
202
|
+
committed,
|
|
203
|
+
eventsSeen,
|
|
204
|
+
bytesRead: totalBytes,
|
|
205
|
+
error: error?.message || "upstream stream closed",
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
throw error;
|
|
209
|
+
} finally {
|
|
210
|
+
if (deadlineTimer) clearTimeout(deadlineTimer);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const events = eventsSeen;
|
|
214
|
+
log?.debug?.("A4.3", `preview: events=${eventsSeen} bytes=${totalBytes} kind=${committed ? "committed" : errorEvent ? "error" : deadlineHit ? "timeout" : "streamClosed"} auth=${errorIsAuth}`);
|
|
215
|
+
|
|
216
|
+
if (errorEvent && !committed) {
|
|
217
|
+
|
|
218
|
+
reader.cancel().catch(() => {});
|
|
219
|
+
return _verdict("error", { committed: false, splicedResponse: null, isAuthError: errorIsAuth, errorEvent, eventsSeen, bytesRead: totalBytes });
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
const replayBody = createReplayStream(prefixChunks, reader, pendingRead);
|
|
223
|
+
const splicedResponse = new Response(replayBody, {
|
|
224
|
+
status: providerResponse.status,
|
|
225
|
+
statusText: providerResponse.statusText,
|
|
226
|
+
headers: providerResponse.headers,
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
const kind = committed ? "committed" : deadlineHit ? "timeout" : "streamClosed";
|
|
230
|
+
return _verdict(kind, { committed, splicedResponse, isAuthError: errorIsAuth, errorEvent, eventsSeen, bytesRead: totalBytes });
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function _verdict(kind, rest) {
|
|
234
|
+
return { kind, committed: rest.committed ?? false, splicedResponse: rest.splicedResponse ?? null, isAuthError: rest.isAuthError ?? false, errorEvent: rest.errorEvent ?? null, eventsSeen: rest.eventsSeen ?? 0, bytesRead: rest.bytesRead ?? 0 };
|
|
235
|
+
}
|