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,482 @@
|
|
|
1
|
+
import { checkFallbackError, formatRetryAfter } from "./accountFallback.js";
|
|
2
|
+
import { unavailableResponse } from "../utils/error.js";
|
|
3
|
+
import { getCapabilitiesForModel } from "../providers/capabilities.js";
|
|
4
|
+
import { extractTextContent } from "../translator/formats/gemini.js";
|
|
5
|
+
|
|
6
|
+
const HARD_CAPS = new Set(["vision", "pdf", "audioInput", "videoInput"]);
|
|
7
|
+
|
|
8
|
+
const TOOL_CALL_PREFIX = "[Called tools: ";
|
|
9
|
+
const TOOL_RESULT_PREFIX = "[Tool result: ";
|
|
10
|
+
|
|
11
|
+
function flattenToolHistory(messages) {
|
|
12
|
+
return messages
|
|
13
|
+
.filter((msg) => msg)
|
|
14
|
+
.map((msg) => {
|
|
15
|
+
if (msg.role === "tool" || msg.role === "function") {
|
|
16
|
+
return { role: "assistant", content: `${TOOL_RESULT_PREFIX}${extractTextContent(msg.content) || String(msg.content ?? "")}]` };
|
|
17
|
+
}
|
|
18
|
+
if (msg.role === "assistant" && Array.isArray(msg.tool_calls)) {
|
|
19
|
+
const { tool_calls, ...rest } = msg;
|
|
20
|
+
const names = tool_calls.map((c) => c?.function?.name || c?.name || "tool").join(", ");
|
|
21
|
+
const base = extractTextContent(rest.content) || (typeof rest.content === "string" ? rest.content : "");
|
|
22
|
+
return { ...rest, content: `${base}${base ? "\n" : ""}${TOOL_CALL_PREFIX}${names}]` };
|
|
23
|
+
}
|
|
24
|
+
if (Array.isArray(msg.content)) {
|
|
25
|
+
const hasToolUse = msg.content.some((c) => c.type === "tool_use");
|
|
26
|
+
const hasToolResult = msg.content.some((c) => c.type === "tool_result");
|
|
27
|
+
if (hasToolUse || hasToolResult) {
|
|
28
|
+
const textParts = [];
|
|
29
|
+
const toolNames = [];
|
|
30
|
+
const toolResults = [];
|
|
31
|
+
for (const block of msg.content) {
|
|
32
|
+
if (block.type === "text" && block.text) textParts.push(block.text);
|
|
33
|
+
if (block.type === "tool_use") toolNames.push(block.name || "tool");
|
|
34
|
+
if (block.type === "tool_result") toolResults.push(extractTextContent(block.content) || String(block.content ?? ""));
|
|
35
|
+
}
|
|
36
|
+
const { ...rest } = msg;
|
|
37
|
+
let newContent = textParts.join("\n");
|
|
38
|
+
if (toolNames.length > 0) {
|
|
39
|
+
newContent = `${newContent}${newContent ? "\n" : ""}${TOOL_CALL_PREFIX}${toolNames.join(", ")}]`;
|
|
40
|
+
}
|
|
41
|
+
if (toolResults.length > 0) {
|
|
42
|
+
newContent = `${newContent}${newContent ? "\n" : ""}${TOOL_RESULT_PREFIX}${toolResults.join("\n")}]`;
|
|
43
|
+
}
|
|
44
|
+
return { ...rest, content: newContent };
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return msg;
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function reorderByCapabilities(models, required) {
|
|
52
|
+
if (!required || required.size === 0 || !Array.isArray(models) || models.length <= 1) return models;
|
|
53
|
+
const hard = [...required].filter((c) => HARD_CAPS.has(c));
|
|
54
|
+
const soft = [...required].filter((c) => !HARD_CAPS.has(c));
|
|
55
|
+
|
|
56
|
+
const tierOf = (m) => {
|
|
57
|
+
const slash = typeof m === "string" ? m.indexOf("/") : -1;
|
|
58
|
+
const provider = slash > 0 ? m.slice(0, slash) : "";
|
|
59
|
+
const model = slash > 0 ? m.slice(slash + 1) : m;
|
|
60
|
+
const caps = getCapabilitiesForModel(provider, model);
|
|
61
|
+
if (!hard.every((c) => caps[c] === true)) return 2;
|
|
62
|
+
return soft.every((c) => caps[c] === true) ? 0 : 1;
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
return models
|
|
66
|
+
.map((m, i) => ({ m, i, t: tierOf(m) }))
|
|
67
|
+
.sort((a, b) => a.t - b.t || a.i - b.i)
|
|
68
|
+
.map((x) => x.m);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const comboRotationState = new Map();
|
|
72
|
+
|
|
73
|
+
function trailingUserItems(arr) {
|
|
74
|
+
if (!Array.isArray(arr) || arr.length === 0) return [];
|
|
75
|
+
const isAssistant = (r) => r === "assistant" || r === "model";
|
|
76
|
+
let i = arr.length - 1;
|
|
77
|
+
while (i >= 0 && !isAssistant(arr[i]?.role)) i--;
|
|
78
|
+
return arr.slice(i + 1);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function detectRequiredCapabilities(body) {
|
|
82
|
+
const required = new Set();
|
|
83
|
+
if (!body || typeof body !== "object") return required;
|
|
84
|
+
|
|
85
|
+
const addByMime = (mime) => {
|
|
86
|
+
if (typeof mime !== "string") return;
|
|
87
|
+
if (mime.startsWith("image/")) required.add("vision");
|
|
88
|
+
else if (mime === "application/pdf") required.add("pdf");
|
|
89
|
+
else if (mime.startsWith("audio/")) required.add("audioInput");
|
|
90
|
+
else if (mime.startsWith("video/")) required.add("videoInput");
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
const scanBlock = (b) => {
|
|
94
|
+
if (!b || typeof b !== "object") return;
|
|
95
|
+
const t = b.type;
|
|
96
|
+
if (t === "image_url" || t === "image" || t === "input_image") required.add("vision");
|
|
97
|
+
if (t === "input_audio" || t === "audio_url" || t === "audio") required.add("audioInput");
|
|
98
|
+
if (t === "input_video" || t === "video_url" || t === "video") required.add("videoInput");
|
|
99
|
+
if (t === "file" || t === "document" || t === "input_file") {
|
|
100
|
+
|
|
101
|
+
let fmime = null;
|
|
102
|
+
if (b.input_audio?.format) fmime = `audio/${b.input_audio.format}`;
|
|
103
|
+
else if (b.file?.file_data) fmime = String(b.file.file_data).match(/^data:([^;,]+)/)?.[1];
|
|
104
|
+
else if (b.source?.media_type) fmime = b.source.media_type;
|
|
105
|
+
else if (b.source?.data) fmime = String(b.source.data).match(/^data:([^;,]+)/)?.[1];
|
|
106
|
+
if (fmime) addByMime(fmime);
|
|
107
|
+
else required.add("pdf");
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
addByMime(b.inlineData?.mimeType || b.fileData?.mimeType);
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
const scanContent = (content) => {
|
|
114
|
+
if (Array.isArray(content)) for (const b of content) scanBlock(b);
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
for (const m of trailingUserItems(body.messages)) scanContent(m.content);
|
|
118
|
+
for (const it of trailingUserItems(body.input)) scanContent(it.content);
|
|
119
|
+
const contents = body.contents || body.request?.contents;
|
|
120
|
+
for (const c of trailingUserItems(contents)) scanContent(c.parts);
|
|
121
|
+
|
|
122
|
+
return required;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function normalizeStickyLimit(stickyLimit) {
|
|
126
|
+
const parsed = Number.parseInt(stickyLimit, 10);
|
|
127
|
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : 1;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function rotateModelsFromIndex(models, currentIndex) {
|
|
131
|
+
const rotatedModels = [...models];
|
|
132
|
+
for (let i = 0; i < currentIndex; i++) {
|
|
133
|
+
const moved = rotatedModels.shift();
|
|
134
|
+
rotatedModels.push(moved);
|
|
135
|
+
}
|
|
136
|
+
return rotatedModels;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export function getRotatedModels(models, comboName, strategy, stickyLimit = 1) {
|
|
140
|
+
if (!models || models.length <= 1 || strategy !== "round-robin") {
|
|
141
|
+
return models;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const rotationKey = comboName || "__default__";
|
|
145
|
+
const normalizedStickyLimit = normalizeStickyLimit(stickyLimit);
|
|
146
|
+
const existingState = comboRotationState.get(rotationKey);
|
|
147
|
+
const state = typeof existingState === "number"
|
|
148
|
+
? { index: existingState, consecutiveUseCount: 0 }
|
|
149
|
+
: (existingState || { index: 0, consecutiveUseCount: 0 });
|
|
150
|
+
|
|
151
|
+
const currentIndex = state.index % models.length;
|
|
152
|
+
const rotatedModels = rotateModelsFromIndex(models, currentIndex);
|
|
153
|
+
const nextUseCount = state.consecutiveUseCount + 1;
|
|
154
|
+
|
|
155
|
+
if (nextUseCount >= normalizedStickyLimit) {
|
|
156
|
+
comboRotationState.set(rotationKey, {
|
|
157
|
+
index: (currentIndex + 1) % models.length,
|
|
158
|
+
consecutiveUseCount: 0,
|
|
159
|
+
});
|
|
160
|
+
} else {
|
|
161
|
+
comboRotationState.set(rotationKey, {
|
|
162
|
+
index: currentIndex,
|
|
163
|
+
consecutiveUseCount: nextUseCount,
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
return rotatedModels;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export function resetComboRotation(comboName) {
|
|
171
|
+
if (comboName) comboRotationState.delete(comboName);
|
|
172
|
+
else comboRotationState.clear();
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export function getComboModelsFromData(modelStr, combosData) {
|
|
176
|
+
|
|
177
|
+
if (modelStr.includes("/")) return null;
|
|
178
|
+
|
|
179
|
+
const combos = Array.isArray(combosData) ? combosData : (combosData?.combos || []);
|
|
180
|
+
|
|
181
|
+
const combo = combos.find(c => c.name === modelStr);
|
|
182
|
+
if (combo && combo.models && combo.models.length > 0) {
|
|
183
|
+
return combo.models;
|
|
184
|
+
}
|
|
185
|
+
return null;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export async function handleComboChat({ body, models, handleSingleModel, log, comboName, comboStrategy, comboStickyLimit = 1, autoSwitch = true }) {
|
|
189
|
+
|
|
190
|
+
let rotatedModels = getRotatedModels(models, comboName, comboStrategy, comboStickyLimit);
|
|
191
|
+
|
|
192
|
+
if (autoSwitch) {
|
|
193
|
+
const required = detectRequiredCapabilities(body);
|
|
194
|
+
if (required.size > 0) {
|
|
195
|
+
const reordered = reorderByCapabilities(rotatedModels, required);
|
|
196
|
+
if (reordered[0] !== rotatedModels[0]) {
|
|
197
|
+
log.info("COMBO", `auto-switch for [${[...required].join(",")}] → ${reordered[0]}`);
|
|
198
|
+
}
|
|
199
|
+
rotatedModels = reordered;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
let lastError = null;
|
|
204
|
+
let earliestRetryAfter = null;
|
|
205
|
+
let lastStatus = null;
|
|
206
|
+
|
|
207
|
+
for (let i = 0; i < rotatedModels.length; i++) {
|
|
208
|
+
const modelStr = rotatedModels[i];
|
|
209
|
+
log.info("COMBO", `Trying model ${i + 1}/${rotatedModels.length}: ${modelStr}`);
|
|
210
|
+
|
|
211
|
+
try {
|
|
212
|
+
const result = await handleSingleModel(body, modelStr);
|
|
213
|
+
|
|
214
|
+
if (result.ok) {
|
|
215
|
+
log.info("COMBO", `Model ${modelStr} succeeded`);
|
|
216
|
+
return result;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
let errorText = result.statusText || "";
|
|
220
|
+
let retryAfter = null;
|
|
221
|
+
try {
|
|
222
|
+
const errorBody = await result.clone().json();
|
|
223
|
+
errorText = errorBody?.error?.message || errorBody?.error || errorBody?.message || errorText;
|
|
224
|
+
retryAfter = errorBody?.retryAfter || null;
|
|
225
|
+
} catch {
|
|
226
|
+
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
if (retryAfter && (!earliestRetryAfter || new Date(retryAfter) < new Date(earliestRetryAfter))) {
|
|
230
|
+
earliestRetryAfter = retryAfter;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
if (typeof errorText !== "string") {
|
|
234
|
+
try { errorText = JSON.stringify(errorText); } catch { errorText = String(errorText); }
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const { shouldFallback, cooldownMs } = checkFallbackError(result.status, errorText);
|
|
238
|
+
|
|
239
|
+
if (!shouldFallback) {
|
|
240
|
+
log.warn("COMBO", `Model ${modelStr} failed (no fallback)`, { status: result.status });
|
|
241
|
+
return result;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
if (cooldownMs && cooldownMs > 0 && cooldownMs <= 5000 &&
|
|
245
|
+
(result.status === 503 || result.status === 502 || result.status === 504)) {
|
|
246
|
+
log.info("COMBO", `Model ${modelStr} transient ${result.status}, waiting ${cooldownMs}ms before next`);
|
|
247
|
+
await new Promise(r => setTimeout(r, cooldownMs));
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
lastError = errorText || String(result.status);
|
|
251
|
+
if (!lastStatus) lastStatus = result.status;
|
|
252
|
+
log.warn("COMBO", `Model ${modelStr} failed, trying next`, { status: result.status });
|
|
253
|
+
} catch (error) {
|
|
254
|
+
|
|
255
|
+
lastError = error.message || String(error);
|
|
256
|
+
if (!lastStatus) lastStatus = 500;
|
|
257
|
+
log.warn("COMBO", `Model ${modelStr} threw error, trying next`, { error: lastError });
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
const allDisabled = lastError && lastError.toLowerCase().includes("no credentials");
|
|
262
|
+
const status = allDisabled ? 503 : (lastStatus || 503);
|
|
263
|
+
const msg = lastError || "All combo models unavailable";
|
|
264
|
+
|
|
265
|
+
if (earliestRetryAfter) {
|
|
266
|
+
const retryHuman = formatRetryAfter(earliestRetryAfter);
|
|
267
|
+
log.warn("COMBO", `All models failed | ${msg} (${retryHuman})`);
|
|
268
|
+
return unavailableResponse(status, msg, earliestRetryAfter, retryHuman);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
log.warn("COMBO", `All models failed | ${msg}`);
|
|
272
|
+
return new Response(
|
|
273
|
+
JSON.stringify({ error: { message: msg } }),
|
|
274
|
+
{ status, headers: { "Content-Type": "application/json" } }
|
|
275
|
+
);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function extractPanelText(json) {
|
|
279
|
+
if (!json || typeof json !== "object") return "";
|
|
280
|
+
|
|
281
|
+
const choice = json.choices?.[0];
|
|
282
|
+
if (choice) {
|
|
283
|
+
const msg = choice.message ?? choice.delta ?? {};
|
|
284
|
+
const t = extractTextContent(msg.content);
|
|
285
|
+
if (t.trim()) return t;
|
|
286
|
+
if (typeof choice.text === "string" && choice.text.trim()) return choice.text;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
const claudeText = extractTextContent(json.content);
|
|
290
|
+
if (claudeText.trim()) return claudeText;
|
|
291
|
+
|
|
292
|
+
const parts = json.candidates?.[0]?.content?.parts;
|
|
293
|
+
if (Array.isArray(parts)) {
|
|
294
|
+
const t = parts.map((p) => p?.text || "").join("");
|
|
295
|
+
if (t.trim()) return t;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
if (Array.isArray(json.output)) {
|
|
299
|
+
const t = json.output
|
|
300
|
+
.flatMap((o) => (Array.isArray(o.content) ? o.content.map((c) => c?.text || "") : []))
|
|
301
|
+
.join("");
|
|
302
|
+
if (t.trim()) return t;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
return "";
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function appendUserTurn(body, text) {
|
|
309
|
+
const next = { ...body };
|
|
310
|
+
if (Array.isArray(body.messages)) {
|
|
311
|
+
next.messages = [...body.messages, { role: "user", content: text }];
|
|
312
|
+
} else if (Array.isArray(body.input)) {
|
|
313
|
+
next.input = [...body.input, { role: "user", content: text }];
|
|
314
|
+
} else if (Array.isArray(body.contents)) {
|
|
315
|
+
next.contents = [...body.contents, { role: "user", parts: [{ text }] }];
|
|
316
|
+
} else {
|
|
317
|
+
next.messages = [{ role: "user", content: text }];
|
|
318
|
+
}
|
|
319
|
+
return next;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function buildJudgePrompt(answers) {
|
|
323
|
+
const panel = answers
|
|
324
|
+
.map((a, i) => `[Source ${i + 1}]\n${a.text}`)
|
|
325
|
+
.join("\n\n");
|
|
326
|
+
|
|
327
|
+
return [
|
|
328
|
+
`You are the JUDGE in a model-fusion panel. ${answers.length} expert models independently answered the user's most recent request. Their responses are below, anonymized by source.`,
|
|
329
|
+
"",
|
|
330
|
+
"Do NOT mention that multiple models were used, and do NOT refer to the sources. Produce ONE authoritative final answer addressed directly to the user.",
|
|
331
|
+
"",
|
|
332
|
+
"First, internally analyze the panel along these dimensions: consensus (points most sources agree on — treat as higher-confidence), contradictions (where they disagree — resolve with your own judgment), partial coverage, unique insights only one source surfaced, and blind spots every source missed. Then write the best possible final answer grounded in that analysis — more complete and correct than any single response, with no filler.",
|
|
333
|
+
"",
|
|
334
|
+
"=== PANEL RESPONSES ===",
|
|
335
|
+
panel,
|
|
336
|
+
"=== END PANEL RESPONSES ===",
|
|
337
|
+
"",
|
|
338
|
+
"Now write the final answer to the user's original request.",
|
|
339
|
+
].join("\n");
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
const FUSION_DEFAULTS = {
|
|
343
|
+
minPanel: 2,
|
|
344
|
+
stragglerGraceMs: 8000,
|
|
345
|
+
panelHardTimeoutMs: 90000,
|
|
346
|
+
};
|
|
347
|
+
|
|
348
|
+
function withTimeout(promise, ms, controller = null) {
|
|
349
|
+
return new Promise((resolve) => {
|
|
350
|
+
const t = setTimeout(() => {
|
|
351
|
+
controller?.abort("fusion panel timeout");
|
|
352
|
+
resolve({ __timeout: true });
|
|
353
|
+
}, ms);
|
|
354
|
+
Promise.resolve(promise)
|
|
355
|
+
.then((v) => { clearTimeout(t); resolve(v); })
|
|
356
|
+
.catch((e) => { clearTimeout(t); resolve({ __error: e }); });
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
function collectPanel(calls, { minPanel, stragglerGraceMs, panelHardTimeoutMs }, cancelPending = null, signal = null) {
|
|
361
|
+
return new Promise((resolve) => {
|
|
362
|
+
const out = new Array(calls.length);
|
|
363
|
+
let settled = 0;
|
|
364
|
+
let ok = 0;
|
|
365
|
+
let finished = false;
|
|
366
|
+
let graceTimer = null;
|
|
367
|
+
let abortHandler = null;
|
|
368
|
+
const finish = () => {
|
|
369
|
+
if (finished) return;
|
|
370
|
+
finished = true;
|
|
371
|
+
clearTimeout(hardTimer);
|
|
372
|
+
if (graceTimer) clearTimeout(graceTimer);
|
|
373
|
+
if (signal && abortHandler) signal.removeEventListener("abort", abortHandler);
|
|
374
|
+
cancelPending?.();
|
|
375
|
+
resolve(out);
|
|
376
|
+
};
|
|
377
|
+
const hardTimer = setTimeout(finish, panelHardTimeoutMs);
|
|
378
|
+
abortHandler = () => finish();
|
|
379
|
+
signal?.addEventListener("abort", abortHandler, { once: true });
|
|
380
|
+
calls.forEach((p, i) => {
|
|
381
|
+
Promise.resolve(p)
|
|
382
|
+
.then((v) => { out[i] = v; })
|
|
383
|
+
.catch((e) => { out[i] = { __error: e }; })
|
|
384
|
+
.finally(() => {
|
|
385
|
+
settled++;
|
|
386
|
+
if (out[i] && out[i].ok) ok++;
|
|
387
|
+
if (settled === calls.length) return finish();
|
|
388
|
+
if (ok >= minPanel && !graceTimer) graceTimer = setTimeout(finish, stragglerGraceMs);
|
|
389
|
+
});
|
|
390
|
+
});
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
export async function handleFusionChat({ body, models, handleSingleModel, log, comboName, judgeModel, tuning, signal = null }) {
|
|
395
|
+
const panel = Array.isArray(models) ? models.filter(Boolean) : [];
|
|
396
|
+
if (panel.length === 0) {
|
|
397
|
+
return new Response(
|
|
398
|
+
JSON.stringify({ error: { message: "Fusion combo has no models" } }),
|
|
399
|
+
{ status: 400, headers: { "Content-Type": "application/json" } }
|
|
400
|
+
);
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
if (panel.length === 1) {
|
|
404
|
+
return handleSingleModel(body, panel[0]);
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
const cfg = { ...FUSION_DEFAULTS, ...(tuning || {}) };
|
|
408
|
+
const minPanel = Math.min(Math.max(2, cfg.minPanel), panel.length);
|
|
409
|
+
const judge = judgeModel && judgeModel.trim() ? judgeModel.trim() : panel[0];
|
|
410
|
+
log.info("FUSION", `Combo "${comboName}" | panel=${panel.length} [${panel.join(", ")}] | judge=${judge} | quorum=${minPanel}`);
|
|
411
|
+
|
|
412
|
+
const { tools, tool_choice, ...rest } = body;
|
|
413
|
+
const panelBody = { ...rest, stream: false };
|
|
414
|
+
|
|
415
|
+
if (Array.isArray(panelBody.messages)) {
|
|
416
|
+
panelBody.messages = flattenToolHistory(panelBody.messages);
|
|
417
|
+
} else if (Array.isArray(panelBody.input)) {
|
|
418
|
+
panelBody.input = flattenToolHistory(panelBody.input);
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
const t0 = Date.now();
|
|
422
|
+
if (signal?.aborted) {
|
|
423
|
+
return new Response(
|
|
424
|
+
JSON.stringify({ error: { message: "Request aborted" } }),
|
|
425
|
+
{ status: 499, headers: { "Content-Type": "application/json" } },
|
|
426
|
+
);
|
|
427
|
+
}
|
|
428
|
+
const panelControllers = panel.map(() => new AbortController());
|
|
429
|
+
const abortPanels = () => panelControllers.forEach((controller) => controller.abort("fusion panel no longer needed"));
|
|
430
|
+
const calls = panel.map((m, index) => withTimeout(
|
|
431
|
+
handleSingleModel(panelBody, m, true, panelControllers[index].signal),
|
|
432
|
+
cfg.panelHardTimeoutMs,
|
|
433
|
+
panelControllers[index],
|
|
434
|
+
));
|
|
435
|
+
const settled = await collectPanel(calls, { ...cfg, minPanel }, abortPanels, signal);
|
|
436
|
+
log.info("FUSION", `fan-out collected in ${Date.now() - t0}ms`);
|
|
437
|
+
|
|
438
|
+
if (signal?.aborted) {
|
|
439
|
+
return new Response(
|
|
440
|
+
JSON.stringify({ error: { message: "Request aborted" } }),
|
|
441
|
+
{ status: 499, headers: { "Content-Type": "application/json" } },
|
|
442
|
+
);
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
const answers = [];
|
|
446
|
+
for (let i = 0; i < settled.length; i++) {
|
|
447
|
+
const res = settled[i];
|
|
448
|
+
const model = panel[i];
|
|
449
|
+
if (!res) { log.warn("FUSION", `Panel ${model} dropped (straggler/timeout)`); continue; }
|
|
450
|
+
if (res.__timeout) { log.warn("FUSION", `Panel ${model} timed out`); continue; }
|
|
451
|
+
if (res.__error) { log.warn("FUSION", `Panel ${model} threw`, { error: res.__error?.message || String(res.__error) }); continue; }
|
|
452
|
+
if (!res.ok) { log.warn("FUSION", `Panel ${model} failed`, { status: res.status }); continue; }
|
|
453
|
+
try {
|
|
454
|
+
const json = await res.clone().json();
|
|
455
|
+
const text = extractPanelText(json);
|
|
456
|
+
if (text) {
|
|
457
|
+
answers.push({ model, text });
|
|
458
|
+
log.info("FUSION", `Panel ${model} ok (${text.length} chars)`);
|
|
459
|
+
} else {
|
|
460
|
+
log.warn("FUSION", `Panel ${model} returned empty content`);
|
|
461
|
+
}
|
|
462
|
+
} catch (e) {
|
|
463
|
+
log.warn("FUSION", `Panel ${model} unparseable`, { error: e.message || String(e) });
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
if (answers.length === 0) {
|
|
468
|
+
log.warn("FUSION", "All panel models failed");
|
|
469
|
+
return new Response(
|
|
470
|
+
JSON.stringify({ error: { message: "All fusion panel models failed" } }),
|
|
471
|
+
{ status: 503, headers: { "Content-Type": "application/json" } }
|
|
472
|
+
);
|
|
473
|
+
}
|
|
474
|
+
if (answers.length === 1) {
|
|
475
|
+
log.info("FUSION", `Only ${answers[0].model} succeeded — answering directly (no fusion)`);
|
|
476
|
+
return handleSingleModel(body, answers[0].model);
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
const judgeBody = appendUserTurn(body, buildJudgePrompt(answers));
|
|
480
|
+
log.info("FUSION", `Judging ${answers.length} answers with ${judge}`);
|
|
481
|
+
return handleSingleModel(judgeBody, judge);
|
|
482
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { proxyAwareFetch } from "../utils/proxyFetch.js";
|
|
2
|
+
import { GITHUB_COPILOT } from "../config/appConstants.js";
|
|
3
|
+
import { refreshCopilotToken } from "./tokenRefresh.js";
|
|
4
|
+
|
|
5
|
+
const MODELS_URL = "https://api.githubcopilot.com/models";
|
|
6
|
+
const FETCH_TIMEOUT_MS = 10_000;
|
|
7
|
+
const CACHE_TTL_MS = 5 * 60 * 1000;
|
|
8
|
+
|
|
9
|
+
const catalogCache = new Map();
|
|
10
|
+
|
|
11
|
+
function cacheKey(credentials) {
|
|
12
|
+
return credentials?.providerSpecificData?.copilotToken
|
|
13
|
+
|| credentials?.accessToken
|
|
14
|
+
|| "copilot-anonymous";
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function buildHeaders(token) {
|
|
18
|
+
return {
|
|
19
|
+
"Authorization": `Bearer ${token}`,
|
|
20
|
+
"Content-Type": "application/json",
|
|
21
|
+
"Copilot-Integration-Id": "vscode-chat",
|
|
22
|
+
"editor-version": `vscode/${GITHUB_COPILOT.VSCODE_VERSION}`,
|
|
23
|
+
"editor-plugin-version": `copilot-chat/${GITHUB_COPILOT.COPILOT_CHAT_VERSION}`,
|
|
24
|
+
"user-agent": GITHUB_COPILOT.USER_AGENT,
|
|
25
|
+
"x-github-api-version": GITHUB_COPILOT.API_VERSION,
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
async function fetchCatalogRaw(token, signal) {
|
|
30
|
+
const controller = new AbortController();
|
|
31
|
+
const timeoutId = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
|
32
|
+
try {
|
|
33
|
+
const response = await proxyAwareFetch(MODELS_URL, {
|
|
34
|
+
method: "GET",
|
|
35
|
+
headers: buildHeaders(token),
|
|
36
|
+
cache: "no-store",
|
|
37
|
+
signal: signal || controller.signal,
|
|
38
|
+
});
|
|
39
|
+
if (!response.ok) {
|
|
40
|
+
const err = new Error(`Copilot /models returned ${response.status}`);
|
|
41
|
+
err.status = response.status;
|
|
42
|
+
throw err;
|
|
43
|
+
}
|
|
44
|
+
const data = await response.json();
|
|
45
|
+
return Array.isArray(data?.data) ? data.data : [];
|
|
46
|
+
} finally {
|
|
47
|
+
clearTimeout(timeoutId);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function expandCatalog(raw) {
|
|
52
|
+
const seen = new Set();
|
|
53
|
+
const models = [];
|
|
54
|
+
for (const m of raw) {
|
|
55
|
+
if (!m || typeof m !== "object") continue;
|
|
56
|
+
if (m.capabilities?.type !== "chat") continue;
|
|
57
|
+
if (m.policy && m.policy.state !== "enabled") continue;
|
|
58
|
+
const id = m.id;
|
|
59
|
+
if (!id || seen.has(id)) continue;
|
|
60
|
+
seen.add(id);
|
|
61
|
+
models.push({ id, name: m.name || id });
|
|
62
|
+
}
|
|
63
|
+
return models;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export async function resolveCopilotModels(credentials, options = {}) {
|
|
67
|
+
const token = credentials?.providerSpecificData?.copilotToken || credentials?.accessToken;
|
|
68
|
+
if (!token) {
|
|
69
|
+
options.log?.debug?.("COPILOT_MODELS", "No copilotToken/accessToken; skipping live fetch");
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const key = cacheKey(credentials);
|
|
74
|
+
const now = Date.now();
|
|
75
|
+
if (!options.forceRefresh) {
|
|
76
|
+
const cached = catalogCache.get(key);
|
|
77
|
+
if (cached && cached.expiresAt > now) {
|
|
78
|
+
return { models: cached.models };
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
let raw;
|
|
83
|
+
try {
|
|
84
|
+
raw = await fetchCatalogRaw(token, options.signal);
|
|
85
|
+
} catch (err) {
|
|
86
|
+
|
|
87
|
+
if (err && (err.status === 401 || err.status === 403) && credentials.accessToken) {
|
|
88
|
+
options.log?.info?.("COPILOT_MODELS", `Got ${err.status}; refreshing Copilot token`);
|
|
89
|
+
const refreshed = await refreshCopilotToken(credentials.accessToken);
|
|
90
|
+
if (refreshed?.token) {
|
|
91
|
+
if (typeof options.onCredentialsRefreshed === "function") {
|
|
92
|
+
try {
|
|
93
|
+
await options.onCredentialsRefreshed({
|
|
94
|
+
copilotToken: refreshed.token,
|
|
95
|
+
copilotTokenExpiresAt: refreshed.expiresAt,
|
|
96
|
+
});
|
|
97
|
+
} catch (e) {
|
|
98
|
+
options.log?.warn?.("COPILOT_MODELS", `onCredentialsRefreshed failed: ${e?.message || e}`);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
try {
|
|
102
|
+
raw = await fetchCatalogRaw(refreshed.token, options.signal);
|
|
103
|
+
} catch (err2) {
|
|
104
|
+
options.log?.warn?.("COPILOT_MODELS", `Retry after refresh failed: ${err2?.message || err2}`);
|
|
105
|
+
return null;
|
|
106
|
+
}
|
|
107
|
+
} else {
|
|
108
|
+
options.log?.warn?.("COPILOT_MODELS", "Token refresh did not return a token");
|
|
109
|
+
return null;
|
|
110
|
+
}
|
|
111
|
+
} else {
|
|
112
|
+
options.log?.warn?.("COPILOT_MODELS", `Live model fetch failed: ${err?.message || err}`);
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const models = expandCatalog(raw);
|
|
118
|
+
if (!models.length) return null;
|
|
119
|
+
|
|
120
|
+
catalogCache.set(key, { expiresAt: now + CACHE_TTL_MS, models });
|
|
121
|
+
return { models };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export function clearCopilotModelCache() {
|
|
125
|
+
catalogCache.clear();
|
|
126
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { fetchWithTimeout } from "./usage/shared.js";
|
|
2
|
+
|
|
3
|
+
const RATE_URL = "https://open.er-api.com/v6/latest/USD";
|
|
4
|
+
const FALLBACK_USD_TO_IDR = 16_500;
|
|
5
|
+
const RATE_CACHE_TTL_MS = 12 * 60 * 60 * 1000;
|
|
6
|
+
const RATE_REQUEST_TIMEOUT_MS = 5_000;
|
|
7
|
+
|
|
8
|
+
let cached = {
|
|
9
|
+
rate: FALLBACK_USD_TO_IDR,
|
|
10
|
+
updatedAt: null,
|
|
11
|
+
fetchedAt: 0,
|
|
12
|
+
source: "fallback",
|
|
13
|
+
};
|
|
14
|
+
let inFlight = null;
|
|
15
|
+
|
|
16
|
+
export async function getUsdToIdrRate() {
|
|
17
|
+
if (Date.now() - cached.fetchedAt < RATE_CACHE_TTL_MS) return cached;
|
|
18
|
+
if (inFlight) return inFlight;
|
|
19
|
+
|
|
20
|
+
inFlight = (async () => {
|
|
21
|
+
try {
|
|
22
|
+
const response = await fetchWithTimeout(
|
|
23
|
+
RATE_URL,
|
|
24
|
+
{ headers: { Accept: "application/json" } },
|
|
25
|
+
RATE_REQUEST_TIMEOUT_MS,
|
|
26
|
+
);
|
|
27
|
+
if (!response.ok) throw new Error(`Rate service returned ${response.status}`);
|
|
28
|
+
|
|
29
|
+
const payload = await response.json();
|
|
30
|
+
const rate = Number(payload?.rates?.IDR);
|
|
31
|
+
if (!Number.isFinite(rate) || rate <= 0) throw new Error("IDR rate is unavailable");
|
|
32
|
+
|
|
33
|
+
cached = {
|
|
34
|
+
rate,
|
|
35
|
+
updatedAt: typeof payload?.time_last_update_utc === "string"
|
|
36
|
+
? payload.time_last_update_utc
|
|
37
|
+
: new Date().toISOString(),
|
|
38
|
+
fetchedAt: Date.now(),
|
|
39
|
+
source: "ExchangeRate-API",
|
|
40
|
+
};
|
|
41
|
+
} catch (error) {
|
|
42
|
+
cached = { ...cached, fetchedAt: Date.now() };
|
|
43
|
+
console.warn(`[Currency] USD/IDR rate unavailable; using ${cached.source}: ${error.message}`);
|
|
44
|
+
}
|
|
45
|
+
return cached;
|
|
46
|
+
})().finally(() => {
|
|
47
|
+
inFlight = null;
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
return inFlight;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export const __test__ = {
|
|
54
|
+
FALLBACK_USD_TO_IDR,
|
|
55
|
+
RATE_CACHE_TTL_MS,
|
|
56
|
+
};
|