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 @@
|
|
|
1
|
+
import{r as d,j as e}from"./react-vendor-xnYrwzsL.js";import{a as P}from"./query-vendor-DVevaSVS.js";import{d as De,p as Re,e as S,c as N,S as Ce,B as le,h as ie,i as Le,j as He,k as qe}from"./index-B6j-9zHy.js";import{H as $e}from"./Header-C_9Su9BF.js";import{u as ze,n as Fe,F as Ae,f as Ee,S as Z,a as Pe,g as oe,b as We}from"./currency-api-SV9CBf5e.js";import{S as Ie}from"./segmented-CqmEnQjZ.js";import{S as U}from"./skeleton-7uJDiIXe.js";import{F as ee,a as ce,b as te,c as ve}from"./frame-cUiti6Lq.js";import{T as Ue,a as _e,b as W,c as T,d as Ke,e as j}from"./table-D0M60Tu1.js";import{l as Oe}from"./admin-extras-api-CCdu5TFM.js";import{p as I}from"./live-mode-CHShLY4E.js";import{aa as de,a8 as me,a9 as ue,ab as Be,A as Qe}from"./icons-vendor-CUx7SB5V.js";import"./ui-vendor-BuM9f2NY.js";import"./motion-vendor-g5fpGzmJ.js";const Xe=De(t=>({stats:null,history:[],setStats:n=>t({stats:n}),setHistory:n=>t({history:n})})),Ye=[{value:"today",label:"Today"},{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"1y",label:"1y"}];function xe(t){switch(t){case"today":return 100;case"7d":return 250;case"30d":return 400;case"90d":return 500;case"1y":return 500;default:return 200}}function M(t){return Number.isFinite(t)?Math.round(t).toLocaleString("id-ID"):"0"}function Ne(t){return Number.isFinite(t)?Math.round(t).toLocaleString("id-ID"):"0"}function he(t){const n=t==null?void 0:t.trim();if(!n)return"—";const i=n.lastIndexOf("/");return i>=0?n.slice(i+1):n}function pe(t){return t.status==="ok"||t.status==="success"?"bg-emerald-500":t.status==="error"||t.error?"bg-red-500":t.status==="pending"||t.status==="processing"?"bg-amber-500":"bg-muted-foreground/64"}function fe(t){return t.status?t.status.toUpperCase():t.error?"ERROR":"—"}function G(t){if(!t)return"—";try{return new Date(t).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return t}}function ge(t,n=Date.now()){if(!t)return"—";const i=Date.parse(t);if(!Number.isFinite(i))return G(t);const o=Math.max(0,Math.floor((n-i)/1e3));if(o<1)return"now";if(o<60)return`${o}s ago`;const u=Math.floor(o/60);if(u<60)return`${u}m ago`;const h=Math.floor(u/60);if(h<24)return`${h}h ago`;const f=Math.floor(h/24);return f<7?`${f}d ago`:G(t)}function Ge(t,n,i,o){const u=Math.min(Math.max(t/n,0),1),h=o>0?Math.min(Math.max(i/o,0),1):u,f=(u+h)/2;return f<=0?"bg-muted/45":f<=.25?"bg-primary/30":f<=.5?"bg-primary/55":f<=.75?"bg-primary/80":"bg-primary"}function we(t){const n=new Date(`${t}T12:00:00`);return Number.isNaN(n.getTime())?t:n.toLocaleDateString(void 0,{weekday:"short",month:"short",day:"numeric",year:"numeric"})}function be(t,n){const i=new Date(`${t}T12:00:00`);return Number.isNaN(i.getTime())?t:(i.setDate(i.getDate()+n),[i.getFullYear(),String(i.getMonth()+1).padStart(2,"0"),String(i.getDate()).padStart(2,"0")].join("-"))}function je(t){return{date:t,key:t,requests:0,tokens:0,promptTokens:0,completionTokens:0,cachedTokens:0,cost:0,errors:0}}function Je(t){return`${we(t.date)} · ${Ne(t.requests)} requests · ${M(t.tokens)} total tokens`}function Ve(t){return e.jsxs("div",{className:"min-w-40 space-y-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold",children:we(t.date)}),e.jsxs("div",{className:"mt-0.5 text-[11px] text-muted-foreground",children:[Ne(t.requests)," requests"]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-x-4 gap-y-1 border-t border-border/70 pt-1.5 text-[11px]",children:[e.jsx("span",{className:"text-muted-foreground",children:"Total tokens"}),e.jsx("span",{className:"text-right font-semibold tabular-nums",children:M(t.tokens)})]})]})}function Ze({children:t}){const n=d.useRef(null),i=d.useRef(null),o=d.useRef(!1),[u,h]=d.useState({ratio:1,progress:0}),[f,C]=d.useState(!1),_=r=>{const l=r.scrollWidth,c=r.clientWidth,g=Math.max(l-c,0),w=l>0?Math.min(c/l,1):1,x=g>0?Math.min(Math.max(r.scrollLeft/g,0),1):0;h({ratio:w,progress:x})};d.useEffect(()=>{const r=n.current;if(!r)return;const l=()=>_(r);l();const c=new ResizeObserver(l);return c.observe(r),r.firstElementChild&&c.observe(r.firstElementChild),()=>c.disconnect()},[]);const L=r=>{const l=n.current,c=i.current;if(!l||!c)return;const g=l.scrollWidth,w=l.clientWidth,x=Math.max(g-w,0);if(!x)return;const H=c.clientWidth,q=Math.min(w/g,1),$=H*q,D=H-$;if(!D)return;const R=Math.min(Math.max(r-c.getBoundingClientRect().left-$/2,0),D);l.scrollLeft=R/D*x},K=r=>{o.current=!0,C(!0),r.currentTarget.setPointerCapture(r.pointerId),L(r.clientX)},O=r=>{o.current&&L(r.clientX)},y=r=>{o.current=!1,C(!1),r.currentTarget.hasPointerCapture(r.pointerId)&&r.currentTarget.releasePointerCapture(r.pointerId)},B=r=>{const l=n.current;if(!l)return;const c=Math.max(l.scrollWidth-l.clientWidth,0);if(!c)return;const g=Math.abs(r.deltaX)>Math.abs(r.deltaY)?r.deltaX:r.deltaY,w=r.deltaMode===1?g*16:g,x=Math.min(Math.max(l.scrollLeft+w,0),c);x!==l.scrollLeft&&(r.preventDefault(),l.scrollLeft=x)};return e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{ref:n,id:"router-activity-heatmap","data-custom-scrollbar":"true",className:"w-full min-w-0 max-w-full touch-pan-x overflow-x-auto overscroll-x-contain pb-1",onScroll:r=>_(r.currentTarget),onWheel:B,children:t}),u.ratio<1?e.jsx("div",{ref:i,role:"scrollbar","aria-label":"Router activity horizontal scroll","aria-controls":"router-activity-heatmap","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":Math.round(u.progress*100),"aria-orientation":"horizontal",tabIndex:0,className:N("relative mt-1.5 h-1.5 w-full cursor-grab touch-none select-none rounded-full active:cursor-grabbing",f?"bg-foreground/10":"bg-foreground/5"),onPointerDown:K,onPointerMove:O,onPointerUp:y,onPointerCancel:y,onKeyDown:r=>{const l=n.current;if(!l)return;const c=l.scrollWidth-l.clientWidth;r.key==="ArrowLeft"||r.key==="ArrowRight"?(r.preventDefault(),l.scrollLeft+=r.key==="ArrowLeft"?-96:96):r.key==="Home"?(r.preventDefault(),l.scrollLeft=0):r.key==="End"&&(r.preventDefault(),l.scrollLeft=c)},children:e.jsx("div",{className:N("absolute inset-y-0 left-0 rounded-full",f?"bg-foreground/20":"bg-foreground/10"),style:{width:`${u.ratio*100}%`,left:`${u.progress*(1-u.ratio)*100}%`}})}):null]})}const ye=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"];function Y({label:t,value:n,detail:i,loading:o}){return e.jsx(ee,{className:"h-full min-w-0 w-full rounded-xl p-0.5 sm:rounded-2xl sm:p-1",children:e.jsxs(ve,{className:"h-full min-w-0 rounded-lg p-2 sm:rounded-xl sm:p-4",children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-baseline justify-between gap-x-2 gap-y-1 sm:block",children:[e.jsx(te,{className:"min-w-0 truncate text-[10px] font-medium leading-tight text-muted-foreground sm:min-h-0 sm:text-[13px]",children:t}),e.jsx("div",{className:"min-w-0 max-w-full overflow-hidden text-ellipsis whitespace-nowrap text-lg font-semibold leading-none tracking-tight tabular-nums sm:mt-2 sm:text-[1.5rem]",children:o?e.jsx(U,{className:"h-6 w-16 sm:h-7 sm:w-20"}):n})]}),i?e.jsx("div",{className:"mt-1 min-h-4 min-w-0 text-[10px] leading-tight text-muted-foreground sm:mt-2 sm:min-h-0 sm:text-[12px]",children:i}):null]})})}function ht(){var se,re;const t=Xe(s=>s.setStats),[n,i]=d.useState("today"),[o,u]=d.useState(!1),[h,f]=d.useState(!1),[C,_]=d.useState(()=>Date.now());ze(),d.useEffect(()=>{const s=window.setInterval(()=>_(Date.now()),1e3);return()=>window.clearInterval(s)},[]);const L=P({queryKey:["usage-stats",n],queryFn:()=>Le({range:n}),enabled:I(),retry:!1}),K=P({queryKey:["currency-settings"],queryFn:We,enabled:I(),staleTime:720*60*1e3,retry:!1}),O=P({queryKey:["usage-heatmap","year"],queryFn:()=>He("year"),enabled:I(),retry:!1}),y=P({queryKey:["usage-history",n,xe(n)],queryFn:()=>qe({limit:xe(n),range:n}),enabled:I(),retry:!1}),B=P({queryKey:["nodes"],queryFn:Oe,enabled:I(),retry:!1}),r=L.data,l=y.data??[],c=L.isLoading,g=y.isLoading,w=O.isLoading,x=Fe((se=K.data)==null?void 0:se.currency),H=((re=K.data)==null?void 0:re.usdToIdr)??Ae,q=(r==null?void 0:r.totalCost)??0,$=Ee(q,x,H);d.useEffect(()=>{r&&t({total:r.total??0,totalCost:r.totalCost??0,byProvider:r.byProvider??{}})},[r,t]);const D=d.useMemo(()=>{const s=new Map;for(const a of B.data??[])s.set(a.id,a.name||a.id),a.prefix&&s.set(a.prefix,a.name||a.prefix);return a=>a?s.has(a)?s.get(a):Re(a)||a:"—"},[B.data]),R=d.useMemo(()=>l.slice(0,8),[l]),z=d.useMemo(()=>{const s=l.map(a=>a.latencyMs).filter(a=>typeof a=="number"&&Number.isFinite(a));return s.length?Math.round(s.reduce((a,m)=>a+m,0)/s.length):null},[l]),Q=d.useMemo(()=>z===null?null:z<1e3?{value:z,unit:"ms"}:{value:Number((z/1e3).toFixed(1)),unit:"s"},[z]),p=O.data??[],Se=d.useMemo(()=>Math.max(...p.map(s=>s.requests),1),[p]),ke=d.useMemo(()=>Math.max(...p.map(s=>s.tokens),1),[p]),J=d.useMemo(()=>{var ne;if(!p.length)return[];const s=new Date(`${p[0].date}T12:00:00`),a=p[0].date,m=Number.isNaN(s.getTime())?0:(s.getDay()+6)%7,k=[...Array.from({length:m},(v,A)=>je(be(a,A-m))),...p],b=((ne=p[p.length-1])==null?void 0:ne.date)||a;for(;k.length%7!==0;){const v=k.length-m-p.length+1;k.push(je(be(b,v)))}const X=new Set(p.map(v=>v.date));let F="";const ae=[];for(let v=0;v<k.length;v+=7){const A=k.slice(v,v+7),E=A.find(Me=>X.has(Me.date))||A[0],V=(E==null?void 0:E.date.slice(0,7))||"",Te=E&&V!==F?new Date(`${E.date}T12:00:00`).toLocaleDateString(void 0,{month:"short"}):"";V&&(F=V),ae.push({monthLabel:Te,cells:A})}return ae},[p]);return e.jsxs("div",{className:"flex w-full flex-col gap-2.5 pb-6 lg:h-full lg:min-h-0 lg:overflow-hidden lg:pb-0",children:[e.jsx($e,{className:"mb-0 sm:mb-0 shrink-0 gap-2 sm:items-end",title:"Dashboard",actions:e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.jsx("div",{className:"min-w-[16rem] sm:min-w-[18rem]",children:e.jsx(Ie,{size:"sm",value:n,onChange:i,options:Ye,className:"w-full"})})})}),e.jsxs("div",{className:"grid shrink-0 grid-cols-2 gap-2 sm:gap-2.5 lg:grid-cols-4",children:[e.jsx(Y,{label:"Requests",loading:c,value:e.jsx(Z,{value:(r==null?void 0:r.total)??0,decimals:0})}),e.jsx(Y,{label:"Total Tokens",loading:c,value:e.jsx("span",{className:"tabular-nums",children:M(((r==null?void 0:r.totalPromptTokens)??0)+((r==null?void 0:r.totalCompletionTokens)??0))})}),e.jsx(Y,{label:`Cost (${x})`,loading:c,value:e.jsx(S,{label:$,children:e.jsx("span",{className:"block min-w-0 max-w-full truncate",title:$,children:e.jsx(Z,{value:Pe(q,x,H),prefix:x==="IDR"?"Rp":"$",locale:x==="IDR"?"id-ID":"en-US",decimals:x==="IDR"?0:q<.01?4:2,className:"text-[clamp(1rem,4vw,1.5rem)]"})})})}),e.jsx(Y,{label:"Latency",loading:c,value:Q!==null?e.jsx(Z,{value:Q.value,decimals:Q.unit==="s"?1:0,suffix:` ${Q.unit}`}):"—"})]}),e.jsx("div",{className:"w-full min-w-0",children:e.jsxs(ee,{className:"flex min-w-0 shrink-0 flex-col overflow-hidden",children:[e.jsx(ce,{className:"gap-3 border-b border-border/80",children:e.jsx("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:e.jsx("div",{children:e.jsx(te,{className:"text-[15px] font-medium tracking-tight",children:"Router Activity"})})})}),e.jsxs(ve,{className:"flex min-w-0 flex-col overflow-hidden",children:[e.jsx("div",{className:"mb-1 flex shrink-0 flex-wrap items-center justify-end gap-2",children:e.jsxs("div",{className:"inline-flex items-center gap-2 text-[10px] text-muted-foreground","aria-label":"Activity intensity: less to more",children:[e.jsx("span",{children:"Less"}),e.jsxs("span",{className:"flex items-center gap-1","aria-hidden":"true",children:[e.jsx("span",{className:"size-3 rounded-[3px] border border-border/40 bg-muted/45"}),e.jsx("span",{className:"size-3 rounded-[3px] border border-border/40 bg-primary/30"}),e.jsx("span",{className:"size-3 rounded-[3px] border border-border/40 bg-primary/55"}),e.jsx("span",{className:"size-3 rounded-[3px] border border-border/40 bg-primary/80"}),e.jsx("span",{className:"size-3 rounded-[3px] border border-border/40 bg-primary"})]}),e.jsx("span",{children:"More"})]})}),e.jsx("div",{children:w?e.jsx(U,{className:"h-56 w-full rounded-xl"}):e.jsx("div",{className:"min-w-0 rounded-xl border border-border/70 bg-background/25 p-2.5 sm:p-3",children:e.jsx(Ze,{children:e.jsxs("div",{className:"grid w-max min-w-full grid-cols-[2.75rem_max-content] items-start 2xl:w-full 2xl:grid-cols-[2.75rem_minmax(0,1fr)]",style:{columnGap:"0.25rem"},children:[e.jsxs("div",{className:"sticky left-0 z-10 grid h-max w-[calc(100%+0.25rem)] grid-rows-[1rem_repeat(7,1rem)] gap-y-2 bg-background",children:[e.jsx("span",{className:"h-4","aria-hidden":"true"}),ye.map(s=>e.jsx("span",{className:"h-4 whitespace-nowrap pr-1 text-left font-sans font-semibold text-[9px] tabular-nums text-muted-foreground",children:s},s))]}),e.jsxs("div",{className:"grid w-max grid-cols-[repeat(var(--heatmap-columns),1.25rem)] items-center justify-items-center gap-x-1 gap-y-2 2xl:w-full 2xl:grid-cols-[repeat(var(--heatmap-columns),minmax(0,1fr))]",style:{"--heatmap-columns":J.length},children:[J.map((s,a)=>e.jsx("span",{className:"flex h-4 items-end justify-center font-sans font-semibold text-[9px] tabular-nums text-muted-foreground",children:s.monthLabel},`${s.monthLabel}-${a}`)),ye.map((s,a)=>e.jsx(d.Fragment,{children:J.map((m,k)=>{const b=m.cells[a],X=b.requests>0,F=X?Je(b):"No activity on this day";return e.jsx(S,{label:X?Ve(b):F,children:e.jsx("span",{role:"img","aria-label":F,className:N("size-4 rounded-[3px] border border-border/40",Ge((b==null?void 0:b.requests)||0,Se,(b==null?void 0:b.tokens)||0,ke))})},`${k}-${a}`)})},s))]})]})})})})]})]})}),e.jsxs(ee,{className:"flex min-h-[240px] w-full flex-col lg:min-h-0 lg:flex-1 lg:overflow-hidden",children:[e.jsx(ce,{className:"border-b border-border/80",children:e.jsx(te,{className:"text-[15px]",children:"Recent requests"})}),e.jsx("div",{className:"min-h-0 flex-1 pb-1",children:e.jsxs(Ce,{overscrollContain:!0,className:"h-full",children:[e.jsx("div",{className:"w-full min-w-0 divide-y divide-border/70 rounded-xl border border-border/70 bg-card sm:hidden",children:g?Array.from({length:5}).map((s,a)=>e.jsxs("div",{className:"px-3 py-3",children:[e.jsx(U,{className:"h-3.5 w-2/3"}),e.jsx(U,{className:"mt-2 h-3 w-full"})]},a)):y.isError?e.jsxs("div",{className:"flex flex-col items-center gap-2 px-4 py-10 text-center text-sm text-muted-foreground",children:[e.jsx("span",{children:"Unable to load recent requests."}),e.jsxs(le,{type:"button",size:"xs",variant:"outline",onClick:()=>void y.refetch(),children:[e.jsx(de,{"aria-hidden":!0}),"Retry"]})]}):R.length===0?e.jsx("div",{className:"px-4 py-10 text-center text-sm text-muted-foreground",children:"No requests yet"}):R.map((s,a)=>{const m=oe(s);return e.jsx("article",{className:"flex min-w-0 items-center gap-2.5 px-3 py-3",children:e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("p",{className:N("min-w-0 flex-1 truncate text-xs font-medium",o&&"font-normal italic text-muted-foreground"),children:o?"Hidden":D(s.provider)}),e.jsxs(ie,{variant:"outline",className:"shrink-0 text-[10px] font-normal",children:[e.jsx("span",{"aria-hidden":"true",className:N("size-1.5 rounded-full",pe(s))}),fe(s)]})]}),e.jsx("p",{className:"mt-0.5 max-w-full truncate font-mono text-[11px] text-muted-foreground",children:h?he(s.model):s.model||"—"}),e.jsxs("div",{className:"mt-1 flex min-w-0 items-center gap-1.5 truncate text-[10px] tabular-nums text-muted-foreground",children:[e.jsx(S,{label:G(s.timestamp),children:e.jsx("span",{className:"shrink-0",children:ge(s.timestamp,C)})}),e.jsx("span",{"aria-hidden":"true",children:"·"}),e.jsxs("span",{className:"shrink-0 text-success",children:["In ",M(s.promptTokens||0)]}),e.jsx("span",{"aria-hidden":"true",children:"·"}),e.jsxs("span",{className:"shrink-0 text-destructive",children:["Out ",M(s.completionTokens||0)]}),e.jsx("span",{"aria-hidden":"true",children:"·"}),e.jsx(S,{label:m.title,children:e.jsx("span",{className:N("shrink-0",m.hit?"text-warning":"text-muted-foreground"),children:m.label})})]})]})},s.id??`${s.timestamp}-${a}`)})}),e.jsx("div",{className:"hidden sm:block",children:e.jsxs(Ue,{variant:"card",className:"min-w-[32rem] text-[13px]",children:[e.jsx(_e,{children:e.jsxs(W,{children:[e.jsx(T,{className:"px-5 py-2.5",children:"Time"}),e.jsx(T,{className:"px-3 py-2.5",children:e.jsxs("div",{className:"group/column flex items-center gap-1.5",children:[e.jsx("span",{children:"Provider"}),e.jsx(S,{label:o?"Show provider names":"Hide provider names",children:e.jsx("button",{type:"button","aria-label":o?"Show provider names":"Hide provider names",onClick:()=>u(s=>!s),className:"inline-flex size-5 items-center justify-center rounded text-muted-foreground opacity-0 transition-opacity hover:bg-surface-hover hover:text-primary focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring group-hover/column:opacity-100",children:o?e.jsx(me,{className:"size-3.5","aria-hidden":"true"}):e.jsx(ue,{className:"size-3.5","aria-hidden":"true"})})})]})}),e.jsx(T,{className:"px-3 py-2.5",children:e.jsxs("div",{className:"group/column flex items-center gap-1.5",children:[e.jsx("span",{children:"Model"}),e.jsx(S,{label:h?"Show full model names":"Hide provider prefixes from models",children:e.jsx("button",{type:"button","aria-label":h?"Show full model names":"Hide provider prefixes from models",onClick:()=>f(s=>!s),className:"inline-flex size-5 items-center justify-center rounded text-muted-foreground opacity-0 transition-opacity hover:bg-surface-hover hover:text-primary focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring group-hover/column:opacity-100",children:h?e.jsx(me,{className:"size-3.5","aria-hidden":"true"}):e.jsx(ue,{className:"size-3.5","aria-hidden":"true"})})})]})}),e.jsx(T,{className:"px-3 py-2.5 text-success",children:"In"}),e.jsx(T,{className:"px-3 py-2.5 text-destructive",children:"Out"}),e.jsx(T,{className:"px-3 py-2.5",children:"Cache"}),e.jsx(T,{className:"px-5 py-2.5",children:"Status"})]})}),e.jsx(Ke,{children:g?Array.from({length:5}).map((s,a)=>e.jsx(W,{children:e.jsx(j,{colSpan:7,className:"px-5 py-3",children:e.jsx(U,{className:"h-4 w-full"})})},a)):y.isError?e.jsx(W,{children:e.jsx(j,{colSpan:7,className:"px-5 py-10 text-center text-muted-foreground",children:e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx("span",{children:"Unable to load recent requests."}),e.jsxs(le,{type:"button",size:"xs",variant:"outline",onClick:()=>void y.refetch(),children:[e.jsx(de,{"aria-hidden":!0}),"Retry"]})]})})}):R.length===0?e.jsx(W,{children:e.jsx(j,{colSpan:7,className:"px-5 py-12 text-center text-muted-foreground",children:"No requests yet"})}):R.map((s,a)=>e.jsxs(W,{children:[e.jsx(j,{className:"whitespace-nowrap px-5 py-2.5 text-muted-foreground",children:e.jsx(S,{label:G(s.timestamp),children:e.jsx("span",{children:ge(s.timestamp,C)})})}),e.jsx(j,{className:"whitespace-nowrap px-3 py-2.5 font-medium",children:(()=>{const m=D(s.provider);return e.jsx("span",{className:N("truncate",o&&"font-normal italic text-muted-foreground"),children:o?"Hidden":m})})()}),e.jsx(j,{className:"whitespace-nowrap px-3 py-2.5",children:(()=>{const m=s.model||"—";return e.jsx("span",{className:"block min-w-0 truncate font-mono text-[12px] text-muted-foreground",children:h?he(s.model):m})})()}),e.jsx(j,{className:"whitespace-nowrap px-3 py-2.5",children:e.jsxs("span",{className:"inline-flex items-center gap-1 tabular-nums text-success",children:[e.jsx(Be,{className:"h-3 w-3 shrink-0","aria-hidden":!0}),M(s.promptTokens||0)]})}),e.jsx(j,{className:"whitespace-nowrap px-3 py-2.5",children:e.jsxs("span",{className:"inline-flex items-center gap-1 tabular-nums text-destructive",children:[e.jsx(Qe,{className:"h-3 w-3 shrink-0","aria-hidden":!0}),M(s.completionTokens||0)]})}),e.jsx(j,{className:"whitespace-nowrap px-3 py-2.5",children:(()=>{const m=oe(s);return e.jsx(S,{label:m.title,children:e.jsx("span",{className:N("text-[11px] font-medium tabular-nums",m.hit?"text-warning":"text-muted-foreground"),children:m.label})})})()}),e.jsx(j,{className:"whitespace-nowrap px-5 py-2.5",children:e.jsxs(ie,{variant:"outline",className:"font-normal",children:[e.jsx("span",{"aria-hidden":"true",className:N("size-1.5 rounded-full",pe(s))}),fe(s)]})})]},s.id??`${s.timestamp}-${a}`))})]})})]})})]})]})}export{ht as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{j as e}from"./react-vendor-xnYrwzsL.js";import{c as x}from"./index-B6j-9zHy.js";function n({title:m,description:s,actions:t,className:l}){return e.jsxs("div",{className:x("mb-3 flex flex-col gap-2 sm:mb-4 sm:flex-row sm:items-center sm:justify-between",l),children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-xl font-semibold tracking-tight sm:text-2xl",children:m}),s?e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground sm:text-sm",children:s}):null]}),t?e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:t}):null]})}export{n as H};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as l,j as e}from"./react-vendor-xnYrwzsL.js";import{u as ne,a as ie}from"./query-vendor-DVevaSVS.js";import{H as le}from"./Header-C_9Su9BF.js";import{C as B}from"./copy-button-qBvM6H9z.js";import{F as oe}from"./flip-button-BGgkjtl0.js";import{R as d}from"./ripple-button-l8aMiVVG.js";import{S as q}from"./StatusBadge-1nAOyHU2.js";import{d as ce,I as V,c as U,e as F,D as b,m as N,n as k,o as w,s as _,q as C,t as m,g as K}from"./index-B6j-9zHy.js";import{S as de}from"./skeleton-7uJDiIXe.js";import{g as ue,c as me,u as xe,a as he,l as ye}from"./api-keys-api-ifAC2Ok3.js";import{p as pe}from"./live-mode-CHShLY4E.js";import{m as A}from"./tunnel-api-DDPsBaDV.js";import{ac as $,q as fe,ah as je,a8 as G,a9 as J,ad as ge,af as W}from"./icons-vendor-CUx7SB5V.js";import"./ui-vendor-BuM9f2NY.js";import"./motion-vendor-g5fpGzmJ.js";const ve=ce(n=>({keys:[],setKeys:i=>n({keys:i}),upsertKey:i=>n(u=>{const x=u.keys.findIndex(D=>D.id===i.id);if(x===-1)return{keys:[i,...u.keys]};const o=u.keys.slice();return o[x]={...o[x],...i},{keys:o}}),removeKey:i=>n(u=>({keys:u.keys.filter(x=>x.id!==i)}))}));function X(n){if(!n)return"—";try{return new Date(n).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}catch{return n}}function Ee(){const n=ne(),i=ve(s=>s.setKeys),[u,x]=l.useState(""),[o,D]=l.useState("active"),[Z,j]=l.useState(!1),[p,L]=l.useState(""),[h,g]=l.useState(!1),[S,I]=l.useState(null),[c,f]=l.useState(null),[a,v]=l.useState(null),[R,E]=l.useState(null),[P,ee]=l.useState(new Set),O=ie({queryKey:["api-keys",o],queryFn:()=>ye({includeRevoked:o==="paused"||o==="all"}),enabled:pe(),retry:!1}),y=O.data??[],se=O.isLoading;l.useEffect(()=>{i(y)},[y,i]);const Q=l.useMemo(()=>{const s=u.trim().toLowerCase();return y.filter(t=>{const r=t.isActive===!1;if(o==="active"&&r||o==="paused"&&!r)return!1;if(!s)return!0;const re=A(t.key||"");return t.name.toLowerCase().includes(s)||re.toLowerCase().includes(s)||(t.id||"").toLowerCase().includes(s)})},[y,u,o]);async function te(s){E(s.id);try{const t=await ue(s.id);if(!t){m.error("No stored secret for this key — create a new key to copy it.");return}await navigator.clipboard.writeText(t),m.success("Key copied to clipboard")}catch(t){m.error(K(t,"Failed to copy key"))}finally{E(null)}}function T(s){ee(t=>{const r=new Set(t);return r.has(s)?r.delete(s):r.add(s),r})}function H(){L(""),j(!0)}async function M(){if(p.trim()){g(!0);try{const s=await me({name:p.trim()});I(s.key.key||""),j(!1),await n.invalidateQueries({queryKey:["api-keys"]})}catch(s){m.error(K(s,"Failed to create key"))}finally{g(!1)}}}async function z(s){const t=!s.isActive;try{await xe(s.id,{isActive:t}),await n.invalidateQueries({queryKey:["api-keys"]}),m.success(t?"Key resumed":"Key paused")}catch(r){m.error(K(r,"Failed to update key"))}}async function ae(){if(c){g(!0);try{await he(c.id),await n.invalidateQueries({queryKey:["api-keys"]}),m.success("Key deleted"),f(null),(a==null?void 0:a.id)===c.id&&v(null)}catch(s){m.error(K(s,"Failed to delete key"))}finally{g(!1)}}}return e.jsxs("div",{className:"space-y-4",children:[e.jsx(le,{title:"API Keys",actions:y.length>0?e.jsxs(d,{size:"sm",onClick:H,children:[e.jsx($,{className:"h-4 w-4"}),"Create key"]}):null}),e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(fe,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(V,{value:u,onChange:s=>x(s.target.value),placeholder:"Search name, key, id…",className:"pl-9"})]}),e.jsx("div",{className:"flex gap-1 rounded-lg border border-border bg-surface p-1",children:[["all","All"],["active","Active"],["paused","Paused"]].map(([s,t])=>e.jsx("button",{type:"button",onClick:()=>D(s),className:U("rounded-md px-3 py-1.5 text-xs font-medium transition-colors",o===s?"bg-white/15 text-foreground":"text-muted-foreground hover:text-foreground"),children:t},s))})]}),se?e.jsx("div",{className:"space-y-2",children:Array.from({length:3}).map((s,t)=>e.jsx(de,{className:"h-24 w-full rounded-xl"},t))}):y.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 rounded-xl border border-border px-4 py-16 text-center",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"No API keys found"}),e.jsxs(d,{size:"sm",onClick:H,children:[e.jsx($,{className:"h-4 w-4"}),"Create first key"]})]}):Q.length===0?e.jsx("div",{className:"rounded-xl border border-border px-4 py-16 text-center text-sm text-muted-foreground",children:"No API keys match the current filter."}):e.jsx("div",{className:"space-y-2",children:Q.map(s=>{const t=s.isActive===!1,r=P.has(s.id);return e.jsx("div",{className:U("group rounded-xl border border-border bg-card transition-colors hover:bg-card/80",t&&"opacity-60"),children:e.jsxs("div",{className:"flex items-center gap-4 p-4",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-primary/10",children:e.jsx(je,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{type:"button",className:"truncate text-sm font-medium hover:underline",onClick:()=>v(s),children:s.name}),e.jsx(q,{tone:t?"warn":"ok",className:"shrink-0",children:t?"Paused":"Active"}),s.isDefault?e.jsx(q,{tone:"muted",className:"shrink-0",children:"Default"}):null]}),e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx("code",{className:"rounded bg-surface px-2 py-0.5 font-mono text-[11px] text-muted-foreground",children:r?s.key:A(s.key||"")}),e.jsx(F,{label:r?"Hide key":"Show key",children:e.jsx("button",{type:"button",onClick:()=>T(s.id),className:"rounded p-1 text-muted-foreground transition-colors hover:text-primary","aria-label":r?"Hide key":"Show key",children:r?e.jsx(G,{className:"h-3.5 w-3.5"}):e.jsx(J,{className:"h-3.5 w-3.5"})})}),e.jsx(F,{label:"Copy key",children:e.jsx("button",{type:"button",onClick:()=>void te(s),disabled:R===s.id,className:"rounded p-1 text-muted-foreground transition-colors hover:text-primary disabled:opacity-50","aria-label":"Copy key",children:R===s.id?e.jsx("span",{className:"text-[10px]",children:"…"}):e.jsx(ge,{className:"h-3.5 w-3.5"})})})]}),e.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["Created ",X(s.createdAt),s.machineId?` · machine ${s.machineId}`:""]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(oe,{active:!t,onToggle:()=>void z(s),activeLabel:"",inactiveLabel:""}),s.isDefault?null:e.jsx(F,{label:"Delete",children:e.jsx("button",{type:"button",className:"inline-flex h-7 w-7 items-center justify-center rounded-md border border-border text-muted-foreground hover:border-destructive/40 hover:bg-destructive/10 hover:text-destructive",onClick:()=>f(s),"aria-label":"Delete",children:e.jsx(W,{className:"h-3.5 w-3.5"})})})]})]})},s.id)})}),e.jsx(b,{open:Z,onOpenChange:s=>{s||j(!1)},children:e.jsxs(N,{children:[e.jsxs(k,{children:[e.jsx(w,{children:"Create API key"}),e.jsx(_,{children:"The full key is shown once after creation — store it securely."})]}),e.jsxs("label",{className:"block space-y-1.5",children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Key name"}),e.jsx(V,{value:p,onChange:s=>L(s.target.value),placeholder:"my-app",autoFocus:!0,onKeyDown:s=>{s.key==="Enter"&&p.trim()&&!h&&M()}})]}),e.jsxs(C,{children:[e.jsx(d,{variant:"outline",onClick:()=>j(!1),disabled:h,children:"Cancel"}),e.jsx(d,{onClick:()=>void M(),disabled:!p.trim()||h,children:h?"Creating…":"Create key"})]})]})}),e.jsx(b,{open:!!S,onOpenChange:()=>I(null),children:e.jsxs(N,{children:[e.jsx(k,{children:e.jsx(w,{children:"API Key Created"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-lg border border-warning/40 bg-warning/10 p-4",children:[e.jsx("p",{className:"mb-2 text-sm font-medium text-warning",children:"Save this key now!"}),e.jsx("p",{className:"text-sm text-warning/80",children:"This is the only time you will see the full key."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"min-w-0 flex-1 break-all rounded-md border border-border bg-surface px-3 py-2 font-mono text-sm",children:S}),e.jsx(B,{value:S||"",label:""})]}),e.jsx(C,{children:e.jsx(d,{onClick:()=>I(null),children:"Done"})})]})]})}),e.jsx(b,{open:!!c,onOpenChange:s=>{s||f(null)},children:e.jsxs(N,{children:[e.jsxs(k,{children:[e.jsx(w,{children:"Delete API key?"}),e.jsxs(_,{children:[e.jsx("span",{className:"font-medium text-foreground",children:c==null?void 0:c.name})," ","(",A((c==null?void 0:c.key)||""),") will be permanently removed."]})]}),e.jsxs(C,{children:[e.jsx(d,{variant:"outline",onClick:()=>f(null),disabled:h,children:"Cancel"}),e.jsx(d,{variant:"destructive",onClick:()=>void ae(),disabled:h,children:h?"Deleting…":"Delete permanently"})]})]})}),e.jsx(b,{open:!!a,onOpenChange:s=>{s||v(null)},children:e.jsx(N,{children:a?e.jsxs(e.Fragment,{children:[e.jsx(k,{children:e.jsxs(w,{className:"flex items-center gap-2",children:[a.name,e.jsx(q,{tone:a.isActive===!1?"warn":"ok",children:a.isActive===!1?"Paused":"Active"})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Y,{label:"Created",value:X(a.createdAt)}),e.jsx(Y,{label:"Machine",value:a.machineId||"—"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Key"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"min-w-0 flex-1 break-all rounded-md border border-border bg-surface px-3 py-2 font-mono text-xs",children:P.has(a.id)?a.key:A(a.key||"")}),e.jsx(d,{variant:"outline",size:"sm",onClick:()=>T(a.id),children:P.has(a.id)?e.jsx(G,{className:"h-3.5 w-3.5"}):e.jsx(J,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{value:a.key||"",label:"Copy key"}),e.jsx(d,{variant:"outline",size:"sm",onClick:()=>void z(a),children:a.isActive===!1?"Resume":"Pause"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'Use this key with the gateway endpoint to route LLM requests. Requests without a valid key are rejected when "Require API key" is on.'})]}),e.jsx(C,{children:a.isDefault?e.jsx("p",{className:"text-xs text-muted-foreground",children:"Default keys cannot be deleted. Revoke or rotate the secret instead."}):e.jsxs(d,{variant:"destructive",onClick:()=>{f(a),v(null)},children:[e.jsx(W,{className:"h-3.5 w-3.5"}),"Delete"]})})]}):null})})]})}function Y({label:n,value:i}){return e.jsxs("div",{className:"rounded-md border border-border bg-surface px-3 py-2",children:[e.jsx("div",{className:"text-[11px] text-muted-foreground",children:n}),e.jsx("div",{className:"truncate text-sm font-medium",children:i})]})}export{Ee as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{d as b,r as t,j as e}from"./react-vendor-xnYrwzsL.js";import{u as d,f as j,I as v,T as N,l as y,g as S}from"./index-B6j-9zHy.js";import{R as P}from"./ripple-button-l8aMiVVG.js";import{C as A,a as C,b as E,c as T}from"./card-CC0Omjcv.js";import{a8 as R,a9 as k}from"./icons-vendor-CUx7SB5V.js";import"./query-vendor-DVevaSVS.js";import"./ui-vendor-BuM9f2NY.js";import"./motion-vendor-g5fpGzmJ.js";function B(){const n=b(),m=d(s=>s.setToken),f=d(s=>s.setAuthMeta),[l,h]=t.useState(""),[a,x]=t.useState(!1),[i,c]=t.useState(!1),[o,u]=t.useState(null),[p,g]=t.useState(!1);t.useEffect(()=>{let s=!1;return j().then(r=>{s||g(r.defaultPasswordActive)}).catch(()=>{}),()=>{s=!0}},[]);async function w(s){s.preventDefault(),c(!0),u(null);try{if((await y(l)).mustChangePassword){n("/setup",{replace:!0});return}m("dashboard-session"),f({authenticated:!0,hasPassword:!0}),n("/dashboard",{replace:!0})}catch(r){u(S(r,"Login failed"))}finally{c(!1)}}return e.jsx("div",{className:"flex min-h-svh w-full items-center justify-center bg-background p-4",children:e.jsxs(A,{className:"w-full max-w-sm border-border bg-card",children:[e.jsxs(C,{className:"text-center",children:[e.jsx("img",{src:"/logo/sway.svg",alt:"Sway Router",className:"mx-auto mb-2 h-12 w-12 rounded-xl object-contain"}),e.jsx(E,{className:"text-xl",children:"Sway Router"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Dashboard login"})]}),e.jsx(T,{children:e.jsxs("form",{onSubmit:w,className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(v,{type:a?"text":"password",placeholder:"Password",value:l,onChange:s=>h(s.target.value),autoFocus:!0,required:!0,className:"pr-10"}),e.jsx("button",{type:"button",onClick:()=>x(!a),className:"absolute right-1 top-1/2 grid size-8 -translate-y-1/2 place-items-center rounded-md text-muted-foreground transition-colors hover:bg-surface-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":a?"Hide password":"Show password","aria-pressed":a,children:a?e.jsx(R,{className:"h-4 w-4"}):e.jsx(k,{className:"h-4 w-4"})})]}),p&&!o?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["First login? The default password is"," ",e.jsx("code",{className:"rounded bg-surface px-1 py-0.5 font-mono text-xs",children:"123456"}),". Set a new one after signing in."]}):null,o?e.jsx("p",{className:"text-sm text-destructive",children:o}):null,e.jsx(P,{type:"submit",className:"w-full",disabled:i,children:i?e.jsx(N,{children:"Authenticating…"}):"Login"})]})})]})})}export{B as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{j as e,r as i}from"./react-vendor-xnYrwzsL.js";import{u as se,a as te}from"./query-vendor-DVevaSVS.js";import{H as ae}from"./Header-C_9Su9BF.js";import{C as re}from"./copy-button-qBvM6H9z.js";import{F as ie}from"./flip-button-BGgkjtl0.js";import{R as c}from"./ripple-button-l8aMiVVG.js";import{S as M}from"./StatusBadge-1nAOyHU2.js";import{F as ne,a as le,b as oe,c as de}from"./frame-cUiti6Lq.js";import{c as z,e as h,D as C,m as K,n as A,o as k,I as ce,q as R,s as me,t as o,g as m}from"./index-B6j-9zHy.js";import{K as xe}from"./ui-vendor-BuM9f2NY.js";import{S as ue}from"./skeleton-7uJDiIXe.js";import{p as pe}from"./live-mode-CHShLY4E.js";import{d as he,c as ye,a as fe,u as je,r as ge,g as be,l as ve}from"./api-keys-api-ifAC2Ok3.js";import{ac as we,ad as Q,L as U,ae as Ne,af as Ce,a8 as Ke,a9 as Ae,ag as ke}from"./icons-vendor-CUx7SB5V.js";import"./motion-vendor-g5fpGzmJ.js";function Re({className:y,orientation:x="horizontal",...d}){return e.jsx(xe,{className:z("shrink-0 bg-border data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:w-px data-[orientation=vertical]:not-[[class^='h-']]:not-[[class*='_h-']]:self-stretch",y),"data-slot":"separator",orientation:x,...d})}function ze(){const y=se(),[x,d]=i.useState([]),[O,D]=i.useState(!0),[G,u]=i.useState(!1),[f,I]=i.useState(""),[b,j]=i.useState(null),[v,S]=i.useState(!1),[P,F]=i.useState(null),[r,l]=i.useState(null),[V,g]=i.useState(new Set),[w,L]=i.useState({}),[T,E]=i.useState(null),[N,q]=i.useState(null),[B,_]=i.useState("/v1"),p=te({queryKey:["api-keys-endpoint"],queryFn:()=>ve({includeRevoked:!0}),enabled:pe(),retry:!1});i.useEffect(()=>{typeof window<"u"&&_(`${window.location.origin}/v1`)},[]),i.useEffect(()=>{p.data?(d(p.data),D(!1)):p.isLoading&&D(!0)},[p.data,p.isLoading]);const J=async()=>{if(f.trim()){S(!0);try{const s=await ye({name:f.trim()});d(t=>[s.key,...t]),j(s.key.key||""),I(""),u(!1),await y.invalidateQueries({queryKey:["api-keys-endpoint"]})}catch(s){o.error(m(s,"Failed to create key"))}finally{S(!1)}}},W=s=>{if(s.isDefault){o.info("The default key cannot be deleted. Revoke or rotate it instead.");return}l({title:"Delete API key",message:`Permanently remove “${s.name}”? Any clients using it will stop working.`,confirmLabel:"Delete permanently",destructive:!0,onConfirm:async()=>{l(null);try{await fe(s.id),d(t=>t.filter(a=>a.id!==s.id))}catch(t){o.error(m(t,"Failed to delete key"))}}})},X=s=>l({title:s.isActive?"Revoke API key":"Restore API key",message:s.isActive?`Revoke “${s.name}”? Requests using this key will be rejected, but the key can be restored later.`:`Restore “${s.name}”? Requests using this key will be accepted again.`,confirmLabel:s.isActive?"Revoke key":"Restore key",destructive:s.isActive,onConfirm:async()=>{l(null);const t=!s.isActive;try{await je(s.id,{isActive:t}),d(a=>a.map(n=>n.id===s.id?{...n,isActive:t}:n))}catch(a){o.error(m(a,"Failed to update key"))}}}),Y=s=>l({title:"Rotate API key",message:`Generate a new secret for “${s.name}”? The old secret will stop working immediately while the key identity stays the same.`,confirmLabel:"Rotate secret",destructive:!0,onConfirm:async()=>{l(null),F(s.id);try{const t=await ge(s.id);d(a=>a.map(n=>n.id===s.id?t:n)),L(a=>{const n={...a};return delete n[s.id],n}),g(a=>{const n=new Set(a);return n.delete(s.id),n}),j(t.key||""),await y.invalidateQueries({queryKey:["api-keys-endpoint"]}),o.success("Key rotated — replace the old secret in your clients.")}catch(t){o.error(m(t,"Failed to rotate key"))}finally{F(null)}}}),H=async s=>{const t=await be(s.id);if(!t)throw new Error("This key has no stored secret.");return L(a=>({...a,[s.id]:t})),t},Z=async s=>{if(w[s.id]){g(t=>new Set(t).add(s.id));return}try{await H(s),g(t=>new Set(t).add(s.id))}catch(t){o.error(m(t,"Failed to reveal key"))}},ee=async s=>{q(s.id);try{await navigator.clipboard.writeText(w[s.id]||await H(s)),E(s.id),window.setTimeout(()=>E(null),1500)}catch(t){o.error(m(t,"Failed to copy key"))}finally{q(null)}};return e.jsxs("div",{className:"space-y-5",children:[e.jsx(ae,{title:"API Keys",actions:x.length>0?e.jsxs(c,{onClick:()=>u(!0),children:[e.jsx(we,{className:"h-4 w-4"}),"Create key"]}):null}),e.jsxs(ne,{className:"w-full",children:[e.jsx(le,{className:"px-3 py-3 sm:px-5 sm:py-4",children:e.jsx(oe,{children:"Manage API Keys"})}),e.jsxs(de,{className:"p-0",children:[e.jsxs("div",{className:"flex flex-col gap-2.5 p-3 sm:flex-row sm:items-center sm:justify-between sm:gap-4 sm:p-5",children:[e.jsx("div",{className:"min-w-0",children:e.jsx("p",{className:"text-sm font-semibold",children:"Base URL"})}),e.jsxs("div",{className:"flex min-w-0 items-center gap-2 rounded-lg border border-border bg-surface px-2.5 py-1.5 sm:px-3 sm:py-2",children:[e.jsx("code",{className:"min-w-0 flex-1 truncate font-mono text-[11px] sm:text-xs",children:B}),e.jsx(h,{label:"Copy gateway URL",children:e.jsx("button",{type:"button",onClick:()=>void navigator.clipboard.writeText(B),className:"shrink-0 rounded-md p-1.5 text-muted-foreground hover:bg-surface-hover hover:text-primary","aria-label":"Copy gateway URL",children:e.jsx(Q,{className:"h-3.5 w-3.5"})})})]})]}),e.jsx(Re,{}),e.jsxs("div",{className:"p-3 sm:p-5",children:[e.jsx("div",{className:"min-w-0",children:e.jsx("p",{className:"text-sm font-semibold",children:"List API Keys"})}),e.jsx("div",{className:"mt-3 sm:mt-4",children:O?e.jsx("div",{className:"space-y-2",children:[0,1].map(s=>e.jsx(ue,{className:"h-16 rounded-xl sm:h-20"},s))}):x.length===0?e.jsxs("div",{className:"rounded-lg border border-dashed border-border px-4 py-8 text-center sm:px-5 sm:py-10",children:[e.jsx("p",{className:"text-sm font-medium",children:"No API keys yet"}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground sm:text-sm",children:"Create an API key to connect your AI tools to this gateway."}),e.jsx(c,{className:"mt-4",size:"sm",onClick:()=>u(!0),children:"Create first key"})]}):e.jsx("div",{className:"space-y-1.5 sm:space-y-2",children:x.map(s=>{const t=s.isActive===!1,a=V.has(s.id);return e.jsxs("div",{className:z("rounded-lg border border-border bg-surface p-2.5 sm:p-3",t&&"opacity-65"),children:[e.jsxs("div",{className:"flex items-start justify-between gap-2.5 sm:gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 sm:gap-2",children:[e.jsx("p",{className:"truncate text-xs font-medium sm:text-sm",children:s.name}),s.isDefault?e.jsx(M,{tone:"muted",className:"text-[10px] sm:text-xs",children:"Default"}):null,e.jsx(M,{tone:t?"warn":"ok",className:"text-[10px] sm:text-xs",children:t?"Revoked":"Active"})]}),e.jsxs("p",{className:"mt-0.5 text-[10px] text-muted-foreground sm:mt-1 sm:text-xs",children:["Created ",new Date(s.createdAt||Date.now()).toLocaleDateString()]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-0.5 sm:gap-1",children:[e.jsx(ie,{active:!t,onToggle:()=>X(s)}),e.jsx(h,{label:"Rotate secret",children:e.jsx("button",{type:"button",onClick:()=>Y(s),disabled:P===s.id,className:"rounded-md p-1.5 text-muted-foreground hover:bg-surface-hover hover:text-primary disabled:opacity-50 sm:p-2","aria-label":"Rotate secret",children:P===s.id?e.jsx(U,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Ne,{className:"h-3.5 w-3.5"})})}),s.isDefault?null:e.jsx(h,{label:"Delete key",children:e.jsx("button",{type:"button",onClick:()=>W(s),className:"rounded-md p-1.5 text-muted-foreground hover:bg-destructive/10 hover:text-destructive sm:p-2","aria-label":"Delete key",children:e.jsx(Ce,{className:"h-3.5 w-3.5"})})})]})]}),e.jsxs("div",{className:"mt-2 flex items-center gap-1.5 rounded-md border border-border bg-background px-2 py-1 sm:mt-3 sm:gap-2 sm:px-2.5 sm:py-1.5",children:[e.jsx("code",{className:"min-w-0 flex-1 truncate font-mono text-[11px] text-muted-foreground sm:text-xs",children:a?w[s.id]||s.key:he(s)}),e.jsx(h,{label:a?"Hide key":"Show key",children:e.jsx("button",{type:"button",onClick:()=>a?g(n=>{const $=new Set(n);return $.delete(s.id),$}):void Z(s),className:"rounded-md p-1 text-muted-foreground hover:bg-surface-hover hover:text-primary sm:p-1.5","aria-label":a?"Hide key":"Show key",children:a?e.jsx(Ke,{className:"h-3.5 w-3.5"}):e.jsx(Ae,{className:"h-3.5 w-3.5"})})}),e.jsx(h,{label:N===s.id?"Copying key":T===s.id?"Copied":"Copy key",children:e.jsx("button",{type:"button",onClick:()=>void ee(s),disabled:N===s.id,className:"rounded-md p-1 text-muted-foreground hover:bg-surface-hover hover:text-primary sm:p-1.5","aria-label":"Copy key",children:N===s.id?e.jsx(U,{className:"h-3.5 w-3.5 animate-spin"}):T===s.id?e.jsx(ke,{className:"h-3.5 w-3.5 text-success"}):e.jsx(Q,{className:"h-3.5 w-3.5"})})})]})]},s.id)})})})]})]})]}),e.jsx(C,{open:G,onOpenChange:u,children:e.jsxs(K,{children:[e.jsx(A,{className:"pb-2",children:e.jsx(k,{children:"Create API key"})}),e.jsx("div",{className:"px-6 pb-2",children:e.jsxs("label",{className:"block space-y-1.5",children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Key name"}),e.jsx(ce,{value:f,onChange:s=>I(s.target.value),placeholder:"Production",autoFocus:!0})]})}),e.jsxs(R,{children:[e.jsx(c,{variant:"outline",onClick:()=>u(!1),disabled:v,children:"Cancel"}),e.jsx(c,{onClick:()=>void J(),disabled:!f.trim()||v,children:v?"Creating…":"Create"})]})]})}),e.jsx(C,{open:!!b,onOpenChange:()=>j(null),children:e.jsxs(K,{children:[e.jsxs(A,{children:[e.jsx(k,{children:"API key ready"}),e.jsx(me,{children:"Copy this secret now and update your clients. It is the current secret for this key."})]}),e.jsx("div",{className:"space-y-3 px-6 pb-2",children:e.jsxs("div",{className:"flex items-center gap-2 rounded-xl border border-primary/20 bg-primary/5 p-3",children:[e.jsx("code",{className:"min-w-0 flex-1 break-all font-mono text-sm",children:b}),e.jsx(re,{value:b||"",label:""})]})}),e.jsx(R,{children:e.jsx(c,{onClick:()=>j(null),children:"Done"})})]})}),e.jsx(C,{open:!!r,onOpenChange:s=>!s&&l(null),children:e.jsxs(K,{children:[e.jsx(A,{children:e.jsx(k,{children:(r==null?void 0:r.title)||"Confirm"})}),e.jsx("p",{className:"px-6 pb-3 text-sm leading-relaxed text-muted-foreground",children:r==null?void 0:r.message}),e.jsxs(R,{children:[e.jsx(c,{variant:"outline",onClick:()=>l(null),children:"Cancel"}),e.jsx(c,{variant:r!=null&&r.destructive?"destructive":"default",onClick:()=>r==null?void 0:r.onConfirm(),children:(r==null?void 0:r.confirmLabel)||"Confirm"})]})]})})]})}export{ze as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as i,j as r}from"./react-vendor-xnYrwzsL.js";import{C as A,b as S}from"./card-CC0Omjcv.js";import{r as O,p as R,b as P}from"./index-B6j-9zHy.js";import{p as D,r as f,s as E,c as I,a as M,g as T}from"./oauth-callback-CqYQzyd7.js";import{a as z,L}from"./icons-vendor-CUx7SB5V.js";import"./ui-vendor-BuM9f2NY.js";import"./query-vendor-DVevaSVS.js";import"./motion-vendor-g5fpGzmJ.js";const b=3e3;function v({className:e}){return r.jsx("svg",{viewBox:"0 0 18 18",className:e,fill:"none","aria-hidden":"true",children:r.jsx("path",{className:"oauth-checkmark",d:"M2.5 9.25 6.5 13.25 15.5 5",pathLength:"1"})})}function K(){const e=i.useMemo(()=>D(window.location.search),[]),[a,s]=i.useState("processing"),[j,o]=i.useState("Returning to Sway Router…"),[h,y]=i.useState(()=>e.provider||(e.state?f(e.state):void 0)),n=h?O(h):void 0,p=n?R(n):"OAuth",c=n?P(n):null;i.useEffect(()=>{const u=window.opener;if(!!!(e.code||e.error)){s("manual"),o("No OAuth result was returned. Close this tab and try again.");return}const l=e.provider||(e.state?f(e.state):void 0);l&&y(l);const g=l?{...e,provider:l}:e,x=E(g);if(e.state&&I(e.state),!u||u.closed){if(!x){s("manual"),o(e.errorDescription||e.error?"Authorization failed. Close this tab and retry from the provider dialog.":"Authorization completed. Close this tab and return to the provider dialog.");return}s(e.error?"error":"success"),o(e.errorDescription||e.error?e.errorDescription||e.error||"Authorization failed.":"You can close this window.");const m=window.setTimeout(()=>{window.closed||window.close()},b);return()=>window.clearTimeout(m)}try{const m=M(g),w=T(window.location.origin);if(w.length===0)throw new Error("Invalid callback origin");for(const k of w)u.postMessage(m,k);e.error?(s("error"),o(e.errorDescription||e.error||"Authorization failed.")):(s("success"),o("You can close this window."))}catch{if(!x){s("manual"),o("The callback could not reach the provider dialog. Close this tab and retry.");return}s(e.error?"error":"success"),o(e.errorDescription||e.error?e.errorDescription||e.error||"Authorization failed.":"You can close this window.")}const N=window.setTimeout(()=>{window.closed||window.close()},b);return()=>window.clearTimeout(N)},[e]);const C=a==="success"?"Connected successfully":a==="error"?"Connection could not be completed":a==="manual"?"Return to Sway Router":"Completing authorization",t=a==="success",d=a==="error";return r.jsx("div",{className:"flex min-h-svh w-full items-center justify-center bg-background p-4 text-foreground",children:r.jsxs(A,{className:"w-full max-w-[420px] items-stretch border-border bg-card p-4 text-center",children:[r.jsxs("div",{className:"inline-flex self-start items-center gap-2 text-[13px] font-semibold tracking-[0.01em] text-foreground",children:[r.jsx("img",{src:"/logo/sway.svg",alt:"Sway Router",className:"h-6 w-6 rounded-md object-contain"}),r.jsx("span",{children:"Sway Router"})]}),r.jsxs("div",{className:"relative mt-7 self-center",children:[r.jsx("div",{className:t&&c?"flex h-14 w-14 items-center justify-center rounded-2xl border border-white/30 bg-white outline outline-1 outline-white/15 outline-offset-2":`flex h-14 w-14 items-center justify-center rounded-2xl border ${d?"border-destructive/35 bg-destructive/10 text-destructive":t?"border-success/35 bg-success/10 text-success":"border-primary/35 bg-primary/10 text-primary"}`,"aria-label":t?p:void 0,children:t&&c?r.jsx("img",{src:c,alt:p,className:"h-8 w-8 object-contain invert"}):t?r.jsx(v,{className:"h-7 w-7"}):d?r.jsx(z,{className:"h-7 w-7","aria-hidden":"true"}):r.jsx(L,{className:"h-7 w-7 animate-spin","aria-hidden":"true"})}),t&&c?r.jsx("span",{className:"absolute -bottom-2 -right-2 flex h-6 w-6 items-center justify-center rounded-full border-2 border-card bg-[#16a34a] text-white",children:r.jsx(v,{className:"h-4.5 w-4.5"})}):null]}),r.jsx(S,{className:"mt-5 text-[21px] leading-tight tracking-[-0.02em]",children:C}),t?null:r.jsx("p",{className:"mt-2.5 text-sm leading-6 text-muted-foreground",children:j}),r.jsxs("div",{className:"mt-5 inline-flex self-center items-center gap-1.5 rounded-full border border-border bg-muted px-2.5 py-1.5 text-[11px] leading-none text-foreground",children:[r.jsx("span",{className:`relative top-px h-1.5 w-1.5 shrink-0 rounded-full ${d?"bg-destructive":t?"bg-success":"bg-primary"}`,"aria-hidden":"true"}),r.jsx("span",{className:"leading-4",children:"OAuth Success"})]}),r.jsx("p",{className:"mt-4 text-xs leading-5 text-muted-foreground/70",children:t?"You can close this window manually.":"Return to the provider dialog to continue."})]})})}export{K as default};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{j as e,r as o}from"./react-vendor-xnYrwzsL.js";import{u as Ss,a as ct,d as As,b as es}from"./query-vendor-DVevaSVS.js";import{H as Ts}from"./Header-C_9Su9BF.js";import{R as E}from"./ripple-button-l8aMiVVG.js";import{I as ne,T as ln,c as ce,D as Ut,m as $t,n as Qt,o as Vt,q as Wt,g as Z,v as kn,s as wn,b as Ms,e as ee,S as Jn,w as hs,h as Qn,x as Ps,y as Ct,z as Es,A as Ls,t as kt,C as _t,a as ts,E as Is}from"./index-B6j-9zHy.js";import{g as Ks,s as Rs,a as Os,r as Fs,b as ns,c as Ds,p as qs,d as fs,t as ss,e as zs,f as Bs,h as ps,u as _s,i as zn,j as Us,k as is,l as rs,m as $s,n as Bn,o as an,q as Qs,v as Vs,w as Ws,x as Js,y as Hs,z as Gs,A as Ys}from"./connections-api-_N54UD3S.js";import{a as Xs,c as Zs,u as ei,d as ti,l as ni}from"./admin-extras-api-CCdu5TFM.js";import{b as si,d as ii,v as as,e as ri,f as ai,a as oi,h as os,i as li}from"./oauth-callback-CqYQzyd7.js";import{S as Pe}from"./StatusBadge-1nAOyHU2.js";import{S as ci,a as di,b as ui,c as mi}from"./select-D8pUtMXp.js";import{S as jt}from"./segmented-CqmEnQjZ.js";import{ag as Sn,ad as Hn,L as cn,X as Gn,q as xs,ah as hi,ai as fi,aj as pi,ak as xi,a8 as gi,a9 as vi,ac as An,al as yi,am as bi,an as wi,ao as ki,af as jn,A as ji,ab as Ci,ap as Ni,aq as Si,h as gs}from"./icons-vendor-CUx7SB5V.js";import{A as Yn,m as dt}from"./motion-vendor-g5fpGzmJ.js";import{T as vs,a as ys,b as Cn,c as bs}from"./tabs-C6YkuulG.js";import{F as ws,a as ks,c as js}from"./frame-cUiti6Lq.js";import{S as Ai}from"./skeleton-7uJDiIXe.js";import{F as Ti}from"./flip-button-BGgkjtl0.js";import{C as Mi}from"./checkbox-7SZBrmbN.js";import"./ui-vendor-BuM9f2NY.js";function Tn(s,n){if(n)return"Connect";const i=(s||"apikey").toLowerCase();return i.includes("oauth")||i.includes("device")||i.includes("import")||i==="local"?"Connect":"Add connection"}function Pi(s,n){return Tn(s,n)==="Add connection"?"Add":"Connect"}const Ei=[{value:"builder-id",label:"Builder ID",mobileLabel:"Builder ID",description:"Personal AWS account"},{value:"iam",label:"AWS IAM",mobileLabel:"AWS IAM",description:"Enterprise AWS SSO"},{value:"api-key",label:"API Key",mobileLabel:"API Key",description:"Long-lived Kiro / CodeWhisperer key"},{value:"import-token",label:"Token",mobileLabel:"Token",description:"Paste a refresh token from Kiro"},{value:"cli-proxy",label:"CLIProxyAPI",mobileLabel:"CLI Proxy",description:"Paste auth JSON from CLIProxyAPI / Kiro"}];function Li({value:s,region:n,startUrl:i,onChange:a,onRegionChange:u,onStartUrlChange:c}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(jt,{size:"sm",value:s,onChange:a,options:Ei.map(h=>({value:h.value,label:h.label,mobileLabel:h.mobileLabel,hint:h.description})),className:"w-full"}),s==="iam"?e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[e.jsx(ne,{placeholder:"AWS region (default: us-east-1)",value:n,onChange:h=>u(h.target.value)}),e.jsx(ne,{placeholder:"AWS Start URL (https://...)",value:i,onChange:h=>c(h.target.value)})]}):null]})}function Ii({mode:s,refreshToken:n,clientId:i,clientSecret:a,profileArn:u,cliProxyJson:c,onRefreshTokenChange:h,onClientIdChange:y,onClientSecretChange:C,onProfileArnChange:N,onCliProxyJsonChange:K}){return s==="import-token"?e.jsxs("div",{className:"space-y-2",children:[e.jsx("textarea",{className:"min-h-28 w-full rounded-md border border-input bg-surface px-3 py-2 font-mono text-base focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring sm:text-sm",placeholder:"Kiro refresh token (aorAAAAAG...)",value:n,onChange:A=>h(A.target.value)}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[e.jsx(ne,{placeholder:"Client ID (optional for IAM)",value:i,onChange:A=>y(A.target.value)}),e.jsx(ne,{type:"password",placeholder:"Client secret (optional for IAM)",value:a,onChange:A=>C(A.target.value)})]}),e.jsx(ne,{placeholder:"Profile ARN (optional)",value:u,onChange:A=>N(A.target.value)})]}):s==="cli-proxy"?e.jsx("textarea",{className:"min-h-36 w-full rounded-md border border-input bg-surface px-3 py-2 font-mono text-base focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring sm:text-sm",placeholder:"Paste CLIProxyAPI Kiro auth JSON…",value:c,onChange:A=>K(A.target.value)}):null}function Ki({region:s,onChange:n}){return e.jsx(ne,{placeholder:"AWS region (default: us-east-1)",value:s,onChange:i=>n(i.target.value)})}function Ri({authLabel:s,apiKey:n,region:i,checking:a,keyValid:u,checkMsg:c,submitError:h,proxyPoolId:y,proxyOptions:C,showKiroRegion:N,onApiKeyChange:K,onRegionChange:A,onCheck:b,onProxyPoolChange:F}){var z;return e.jsxs("div",{className:"space-y-2",children:[N?e.jsx(Ki,{region:i,onChange:A}):null,e.jsx("label",{htmlFor:"connection-api-key",className:"text-xs font-medium text-muted-foreground",children:s}),e.jsx(ne,{id:"connection-api-key",type:"password",placeholder:"API Key",value:n,"aria-invalid":!!h,"aria-describedby":h?"connection-submit-error":void 0,onChange:T=>K(T.target.value)}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(E,{size:"sm",variant:"outline",disabled:!n.trim()||a,onClick:()=>void b(),children:a?e.jsx(ln,{children:"Checking…"}):"Check"}),u===!0?e.jsx(Pe,{tone:"ok",children:"Valid"}):u===!1?e.jsx(Pe,{tone:"err",children:"Invalid"}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"Validate before add"})]}),c&&u===!1?e.jsx("p",{className:ce("text-xs",u?"text-success":"text-destructive"),children:c}):null,e.jsxs("div",{children:[e.jsx("label",{className:"mb-1 block text-xs text-muted-foreground",children:"Proxy pool"}),e.jsxs(ci,{value:y,onValueChange:T=>F(T??"pool_none"),children:[e.jsx(di,{className:"w-full",children:e.jsx("span",{className:"truncate",children:((z=C.find(T=>T.id===y))==null?void 0:z.name)??"None (direct)"})}),e.jsx(ui,{children:C.map(T=>e.jsx(mi,{value:T.id,children:T.name},T.id))})]})]})]})}function Oi({isDeviceFlow:s,isOAuthFlow:n,isKiroIam:i,authLink:a,userCode:u,deviceStatus:c,deviceCode:h,bootLoading:y,linkCopied:C,oauthCode:N,kiroStartUrl:K,onStartKiroAuthorization:A,onOpenAuthLink:b,onCopyAuthLink:F,onOauthCodeChange:z}){return e.jsxs("div",{className:"space-y-2 rounded-lg border border-border bg-surface p-3",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:s?"Verification":"Authorize"}),a?e.jsx("code",{className:"block break-all rounded-md border border-border bg-background px-2.5 py-2 font-mono text-[11px] text-foreground",children:a}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"No auth URL yet"}),s&&u?e.jsxs("p",{className:"text-sm",children:["User code:"," ",e.jsx("span",{className:"font-mono text-base font-semibold tracking-wider text-foreground",children:u})]}):null,s&&c?e.jsx("p",{className:"text-xs text-muted-foreground",children:c}):null,e.jsxs("div",{className:"flex flex-wrap gap-2 pt-1",children:[i&&!h?e.jsx(E,{size:"sm",onClick:()=>void A(),disabled:y||!K.trim(),children:"Start authorization"}):null,e.jsx(E,{size:"sm",onClick:b,disabled:!a,children:"Open in browser"}),e.jsx(E,{size:"sm",variant:"outline",onClick:()=>void F(),disabled:!a,children:C?e.jsxs(e.Fragment,{children:[e.jsx(Sn,{className:"h-3.5 w-3.5"}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(Hn,{className:"h-3.5 w-3.5"}),"Copy link"]})})]}),n?e.jsxs("div",{className:"space-y-1.5 pt-1",children:[e.jsx("label",{className:"block text-xs text-muted-foreground",children:"Fallback: paste the authorization code manually if needed"}),e.jsx(ne,{className:"font-mono text-xs",placeholder:"code from /callback",value:N,onChange:T=>z(T.target.value)})]}):null,e.jsx("p",{className:"text-[11px] text-muted-foreground",children:n?"Open the link → finish sign-in. The callback auto-saves the connection and updates this dialog. Manual code paste is available if needed.":"Open the link, enter the user code, authorize — this dialog polls automatically."})]})}function Fi({value:s,modes:n,onChange:i,label:a}){return e.jsx(jt,{size:"sm",value:s,onChange:i,options:n.map(u=>({value:u,label:a(u)})),className:"w-full"})}function Di({value:s,onChange:n}){return e.jsx(vs,{value:s,onValueChange:i=>n(i),children:e.jsxs(ys,{className:"w-full",children:[e.jsx(Cn,{value:"single",className:"flex-1",children:"Single API Key"}),e.jsx(Cn,{value:"bulk",className:"flex-1",children:"Bulk API Key"})]})})}function qi({raw:s,rows:n,activeIndex:i,activeRow:a,checking:u,validCount:c,onRawChange:h,onCheck:y}){return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:["1 key per line; optionally use ",e.jsx("code",{children:"name|key"}),". Unnamed rows receive ",e.jsx("code",{children:"swayrouter-account1…N"})," automatically."]}),e.jsx("textarea",{id:"bulk-api-keys",className:"min-h-36 w-full rounded-md border border-input bg-surface px-3 py-2 font-mono text-base focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring sm:text-xs",placeholder:`name|sk-1
|
|
2
|
+
sk-2`,value:s,onChange:C=>h(C.target.value)}),u&&a?e.jsx("div",{className:"overflow-hidden px-1",role:"status","aria-live":"polite",children:e.jsx(Yn,{initial:!1,mode:"wait",children:e.jsxs(dt.div,{initial:{opacity:0,y:14},animate:{opacity:1,y:0},exit:{opacity:0,y:-14},transition:{duration:.32,ease:"easeOut"},className:"flex min-h-8 items-center gap-2 px-2 py-1 text-xs",children:[a.checking?e.jsx(cn,{className:"h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground"}):a.valid===!0?e.jsx(Sn,{className:"h-3.5 w-3.5 shrink-0 text-success"}):e.jsx(Gn,{className:"h-3.5 w-3.5 shrink-0 text-destructive"}),e.jsx("span",{className:"shrink-0 font-medium",children:a.checking?"Checking":a.valid===!0?"Valid":"Error"}),e.jsx("span",{className:"min-w-0 truncate font-medium",children:a.name}),e.jsxs("span",{className:"min-w-0 flex-1 truncate font-mono text-muted-foreground",children:[a.apiKey.slice(0,14),"…"]}),e.jsxs("span",{className:"shrink-0 text-muted-foreground",children:[(i??0)+1," / ",n.length]})]},`${i}-${a.checking?"checking":a.valid===!0?"valid":"error"}`)})}):!u&&n.length>0?e.jsxs(dt.div,{initial:{opacity:0,y:6},animate:{opacity:1,y:0},transition:{duration:.2,ease:"easeOut"},className:"flex flex-wrap items-center gap-2 px-0 py-0 text-xs",role:"status","aria-live":"polite",children:[e.jsxs(Pe,{tone:"ok",children:["Valid: ",c," API Key"]}),e.jsxs(Pe,{tone:"err",children:["Error: ",n.filter(C=>C.valid===!1).length," API Key"]})]}):null,e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.jsx(E,{size:"sm",variant:"outline",disabled:!s.trim()||u,onClick:()=>void y(),children:u?e.jsxs("span",{className:"inline-flex items-center gap-0.5",children:[e.jsx("span",{children:"Checking"}),e.jsxs("span",{className:"inline-flex w-3 justify-start","aria-hidden":"true",children:[e.jsx("span",{className:"animate-pulse",children:"."}),e.jsx("span",{className:"animate-pulse [animation-delay:150ms]",children:"."}),e.jsx("span",{className:"animate-pulse [animation-delay:300ms]",children:"."})]})]}):"Check all"})})]})}function zi({providerId:s,token:n,machineId:i,importing:a,message:u,hasError:c,onTokenChange:h,onMachineIdChange:y,onAutoImport:C}){return e.jsxs("div",{className:"space-y-2",children:[s==="cursor"?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(E,{size:"sm",variant:"outline",disabled:a,onClick:()=>void C(),children:a?e.jsx(ln,{children:"Detecting…"}):"Auto-detect from this device"}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Reads Cursor's local state.vscdb"})]}),u?e.jsx("p",{className:ce("text-xs",c?"text-destructive":"text-success"),role:"status",children:u}):null]}):null,e.jsx("textarea",{className:"min-h-28 w-full rounded-md border border-input bg-surface px-3 py-2 font-mono text-base focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring sm:text-sm",placeholder:"Access token…",value:n,onChange:N=>h(N.target.value)}),s==="cursor"?e.jsx(ne,{placeholder:"Machine ID (cursorAuth machine id)",value:i,onChange:N=>y(N.target.value)}):null]})}function Bi({raw:s,rows:n,activeIndex:i,activeRow:a,onRawChange:u,onCheck:c,validCount:h,checking:y}){return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:["One account per line. Supported formats: ",e.jsx("code",{children:"accessToken"}),", ",e.jsx("code",{children:"refreshToken"}),", or ",e.jsx("code",{children:"accessToken|refreshToken"}),". A single token is detected automatically. Multiple accounts receive automatic names."]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{htmlFor:"codebuddy-token",className:"text-xs font-medium text-muted-foreground",children:"Access / Refresh Tokens"}),e.jsx("textarea",{id:"codebuddy-token",className:"min-h-36 w-full resize-y overflow-x-auto whitespace-pre rounded-md border border-input bg-surface px-3 py-2 font-mono text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",placeholder:`access-token-1
|
|
3
|
+
refresh-token-2
|
|
4
|
+
access-token-3|refresh-token-3`,value:s,autoComplete:"off",spellCheck:!1,wrap:"off",onChange:C=>u(C.target.value)})]}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.jsx(E,{size:"sm",variant:"outline",disabled:!s.trim()||y,onClick:()=>void c(),children:y?e.jsx(ln,{children:"Checking…"}):"Check all"})}),y&&a?e.jsx("div",{className:"overflow-hidden px-1",role:"status","aria-live":"polite",children:e.jsx(Yn,{initial:!1,mode:"wait",children:e.jsxs(dt.div,{initial:{opacity:0,y:14},animate:{opacity:1,y:0},exit:{opacity:0,y:-14},transition:{duration:.2,ease:"easeOut"},className:"flex min-h-8 items-center gap-2 px-2 py-1 text-xs",children:[a.checking?e.jsx(cn,{className:"h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground"}):a.valid===!0?e.jsx(Sn,{className:"h-3.5 w-3.5 shrink-0 text-success"}):e.jsx(Gn,{className:"h-3.5 w-3.5 shrink-0 text-destructive"}),e.jsx("span",{className:"shrink-0 font-medium",children:a.checking?"Checking":a.valid===!0?"Valid":"Error"}),e.jsxs("span",{className:"min-w-0 flex-1 truncate",children:["Account ",(i??0)+1]}),e.jsxs("span",{className:"shrink-0 text-muted-foreground",children:[(i??0)+1," / ",n.length]})]},`${i}-${a.checking?"checking":a.valid===!0?"valid":"error"}`)})}):!y&&n.length>0?e.jsxs(dt.div,{initial:{opacity:0,y:6},animate:{opacity:1,y:0},transition:{duration:.2,ease:"easeOut"},className:"flex flex-wrap items-center gap-2 px-0 py-0 text-xs",role:"status","aria-live":"polite",children:[e.jsxs(Pe,{tone:"ok",children:["Valid: ",h," account",h===1?"":"s"]}),e.jsxs(Pe,{tone:"err",children:["Error: ",n.filter(C=>C.valid===!1).length," account",n.filter(C=>C.valid===!1).length===1?"":"s"]})]}):null,s.trim()?null:e.jsx("p",{className:"text-xs text-muted-foreground",role:"status",children:"At least one access token or refresh token is required."})]})}function _i(s){return s.split(/\r?\n/).map(n=>n.trim()).filter(Boolean).map(n=>{const i=n.split("|").map(a=>a.trim());return i.length===1&&i[0]?{credentialToken:i[0],valid:null}:i.length===2&&i[0]&&i[1]?{accessToken:i[0],refreshToken:i[1],valid:null}:{valid:!1,msg:"Use one token or accessToken|refreshToken"}})}const Ui=new Set(["claude","codex","xai"]),$i=200,Qi=1e3;function Vi({open:s,provider:n,flow:i,onOpenChange:a,onSubmit:u}){var yn;const[c,h]=o.useState(""),[y,C]=o.useState(""),[N,K]=o.useState(""),[A,b]=o.useState(""),[F,z]=o.useState(""),[T,G]=o.useState(""),[U,_]=o.useState("pool_none"),[Y,$]=o.useState(()=>[{id:"pool_none",name:"None (direct)"}]),[fe,R]=o.useState(!1),[Ee,Le]=o.useState(!1),[Ie,pe]=o.useState(null),[ze,te]=o.useState(null),[xe,B]=o.useState(null),[O,ie]=o.useState(null),[re,ge]=o.useState(null),[Ke,L]=o.useState(null),[S,ae]=o.useState(null),[ut,Qe]=o.useState(5),[Re,oe]=o.useState(null),[ke,Ve]=o.useState(null),[Ye,mt]=o.useState(null),[Xe,Nt]=o.useState(null),[me,St]=o.useState("builder-id"),[ht,At]=o.useState("us-east-1"),[Ht,Tt]=o.useState(""),[Gt,ft]=o.useState(""),[dn,Mt]=o.useState(""),[Ze,Oe]=o.useState(""),[Pt,Yt]=o.useState(""),[Et,Lt]=o.useState(""),[pt,Be]=o.useState(!1),[Mn,et]=o.useState(null),[Pn,tt]=o.useState(!1),[le,nt]=o.useState("single"),[xt,st]=o.useState(""),[It,je]=o.useState([]),[Kt,gt]=o.useState(!1),[Xt,ye]=o.useState(null),[Rt,Zt]=o.useState(!1),[Fe,We]=o.useState([]),[vt,De]=o.useState(!1),[it,Ce]=o.useState(null);function Ot(m,p){return p==="apikey"?m==="qoder"?"API Key (PAT)":"API Key":p==="device"?"Device Code":p==="import"?m==="codebuddy-cn"||m==="codebuddy-intl"?"AT/RT":"Import Token":p}const[Ft,de]=o.useState(null),[en,_e]=o.useState(!1),[Dt,Ne]=o.useState(!1),[P,rt]=o.useState(!1),H=o.useRef(!1),Je=o.useRef(null),be=o.useRef(!1),qt=o.useRef(null),d=o.useRef(null);function Se(m=!1){rt(m)}function se(){d.current&&(clearTimeout(d.current),d.current=null)}function we(){const m=qt.current;qt.current=null,m&&!m.closed&&m.close()}function He(m){const p=Je.current;!p||m&&p!==m||(Je.current=null,Se(!1),p&&Ds(p).catch(()=>{}))}const he=o.useRef(u);he.current=u;const Ae=o.useRef(c);Ae.current=c;const J=(n==null?void 0:n.id)==="kiro",yt=(n==null?void 0:n.id)==="codebuddy-cn"||(n==null?void 0:n.id)==="codebuddy-intl",ve=(yn=n==null?void 0:n.authModes)!=null&&yn.length?n.authModes:null,at=!!(ve&&ve.length>1),[tn,un]=o.useState((ve==null?void 0:ve[0])??"auto"),Te=J?me==="api-key"||me==="import-token"||me==="cli-proxy"?me==="api-key"?"apikey":"import":"device":ve&&ve.includes(tn)?tn:i??(ve!=null&&ve.includes("device")?"device":"apikey"),Ge=It.filter(m=>m.valid===!0),mn=Xt===null?null:It[Xt]??null,ot=Fe.filter(m=>m.valid===!0),En=it===null?null:Fe[it]??null;function zt(m){return m.split(/\r?\n/).map(p=>p.trim()).filter(Boolean).map(p=>{const w=p.includes("|")?p.split("|").map(x=>x.trim()):p.includes(",")?p.split(",").map(x=>x.trim()):[p];return{name:w.length>=2?w[0]:"",apiKey:w.length>=2?w[1]:w[0],valid:null,msg:void 0}})}async function hn(){if(!n)return;const m=zt(xt);if(!m.length)return;gt(!0);const p=m.map(x=>({...x,checking:!1})),w=new Set;je([...p]),ye(0);try{for(let x=0;x<p.length;x+=1){ye(x);const M=p[x].apiKey.trim();if(w.has(M)){p[x]={...p[x],valid:!1,checking:!1,msg:"Duplicate API key in this batch"},je([...p]);continue}w.add(M),p[x]={...p[x],checking:!0},je([...p]);try{const D=await ss({provider:n.id,apiKey:p[x].apiKey});p[x]={...p[x],valid:D.valid===!0,checking:!1,msg:D.valid===!0?"ok":D.error||"fail"}}catch(D){p[x]={...p[x],valid:!1,checking:!1,msg:Z(D,"error")}}je([...p]),await new Promise(D=>{window.setTimeout(D,Qi)})}}finally{ye(null),gt(!1)}}async function fn(){if(!(!n||!Ge.length)){Zt(!0),B(null);try{await u({name:n.name,authFlow:"apikey",bulkKeys:Ge.map(({name:m,apiKey:p},w)=>{const x=m.trim();return{name:x||`swayrouter-account${w+1}`,apiKey:p.trim(),autoName:!x}})})}catch(m){B(Z(m,"Failed to add connections"))}finally{Zt(!1)}}}const Q=Te,Ue=Q==="apikey"||!!(n!=null&&n.isCustom),$e=Q==="oauth",lt=Q==="device",nn=$e||lt,pn=Dt&&nn;function xn(m){H.current=!0,se(),St(m),nt("single"),pe(null),te(null),B(null),de(null),ge(null),L(null),ae(null),oe(null),ie(null)}async function gn(){if(!n||n.id!=="kiro")return;const m=me==="iam"?"idc":"builder-id",p=Ht.trim();if(m==="idc"&&!p){de("AWS IAM Identity Center requires a Start URL");return}H.current=!0,se(),Ne(!0),de(null),oe(null),ge(null),L(null),ae(null),ie(null);try{const w=await ns("kiro",{authMethod:m,region:ht.trim()||"us-east-1",startUrl:p||void 0}),x=typeof w.device_code=="string"&&w.device_code||typeof w.deviceCode=="string"&&w.deviceCode||null;if(!x)throw new Error("Kiro did not return a device code");const M=typeof w.user_code=="string"&&w.user_code||typeof w.userCode=="string"&&w.userCode||null,D=typeof w.verification_uri_complete=="string"&&w.verification_uri_complete||typeof w.verificationUriComplete=="string"&&w.verificationUriComplete||typeof w.verification_uri=="string"&&w.verification_uri||typeof w.verificationUri=="string"&&w.verificationUri||null;ge(x),ae(M),ie(D),L(typeof w.codeVerifier=="string"?w.codeVerifier:null),Qe(typeof w.interval=="number"&&w.interval>0?w.interval:5),oe("Waiting for you to authorize…")}catch(w){de(Z(w,"Failed to start Kiro authorization"))}finally{Ne(!1)}}if(o.useEffect(()=>{var m;s&&(un(((m=n==null?void 0:n.authModes)==null?void 0:m[0])??"auto"),St("builder-id"),At("us-east-1"),Tt(""),ft(""),Mt(""),Oe(""),Yt(""),Lt(""),b(""),te(null),Be(!1),et(null),tt(!1),nt("single"),st(""),je([]),ye(null),We([]),De(!1),Ce(null))},[s,n==null?void 0:n.id]),o.useEffect(()=>{if(!s)return;let m=!1;async function p(){try{const w=await Xs();if(m)return;$([{id:"pool_none",name:"None (direct)"},...w.map(x=>({id:x.id,name:String(x.name||x.id)}))])}catch{}}return p(),()=>{m=!0}},[s]),o.useEffect(()=>{if(!s||!n)return;h(""),C(""),K(""),z(""),G(""),_("pool_none"),R(!1),Ne(!1),Le(!1),pe(null),te(null),B(null),_e(!1),de(null),oe(null),ge(null),L(null),ae(null),Ve(null),mt(null),Nt(null),ie(null),nt("single"),st(""),je([]),ye(null),gt(!1),Zt(!1),H.current=!1;const m=n.id;let p=!1;async function w(){if(Q==="oauth"){Ne(!0);try{const x=Ks(m),M=await Rs(m,x);if(p)return;const D=M.authUrl||M.url||M.authorizeUrl||null,t=typeof M.state=="string"?M.state:null,r=typeof M.codeVerifier=="string"?M.codeVerifier:null,l=typeof M.redirectUri=="string"&&M.redirectUri?M.redirectUri:x;ie(typeof D=="string"?D:null),Ve(t),t&&si(t,m),mt(r),Nt(l),be.current=!1;const g=(typeof M.flowType=="string"?M.flowType:null)==="authorization_code_pkce"||Ui.has(m);if(!D||!t||!l||g&&!r)throw new Error("OAuth provider returned incomplete authorization data");if(m==="codex"||m==="xai"){const k=window.location.port||(window.location.protocol==="https:"?"443":"80");try{const f=t,j=r,V=l;if(!f||!j||!V)throw new Error("OAuth provider returned incomplete authorization data");const W=await Os(m,{appPort:k});if(!W.success)throw new Error(W.reason==="port_busy"?"The OAuth callback port is already in use":"The OAuth callback listener could not start");if(Je.current=m,Se(!1),(await Fs(m,{state:f,codeVerifier:j,redirectUri:V})).success!==!0)throw new Error("The OAuth session could not be registered");if(p)return;Se(!0)}catch(f){de(Z(f,"Automatic callback setup unavailable. Paste the browser callback code below.")),He(m)}}}catch(x){p||de(Z(x,"Failed to start OAuth"))}finally{p||Ne(!1)}return}if(Q==="device"){if(m==="kiro"){me==="builder-id"&&gn();return}Ne(!0);try{const x=await ns(n.id);if(p)return;const M=typeof x.device_code=="string"&&x.device_code||typeof x.deviceCode=="string"&&x.deviceCode||null,D=typeof x.user_code=="string"&&x.user_code||typeof x.userCode=="string"&&x.userCode||null,t=typeof x.verification_uri_complete=="string"&&x.verification_uri_complete||typeof x.verificationUriComplete=="string"&&x.verificationUriComplete||typeof x.verification_uri=="string"&&x.verification_uri||typeof x.verificationUri=="string"&&x.verificationUri||null;ge(M),ae(D),ie(t),L(typeof x.codeVerifier=="string"?x.codeVerifier:null);const r=typeof x.interval=="number"&&x.interval>0?x.interval:5;Qe(r),oe("Waiting for you to authorize…")}catch(x){p||de(Z(x,"Failed to start device code"))}finally{p||Ne(!1)}}}return w(),()=>{p=!0,H.current=!0,se(),we(),He(n.id)}},[s,n,Q,me]),o.useEffect(()=>{if(!s||!n||Q!=="oauth"||!P||!ke)return;let m=!1,p=0;const w=n.id,x=n.name,M=ke,D=200,t=async()=>{if(!(m||be.current)){p+=1;try{const r=await qs(w,M);if(m||be.current)return;if(r.status==="done"){be.current=!0,se(),we(),He(w),R(!0);try{await he.current({name:Ae.current.trim()||x,alreadySaved:!0})}catch{de("Connection saved, but the provider list could not refresh")}finally{R(!1)}return}if(r.status==="error"){be.current=!0,se(),we(),He(w),de(r.error||"OAuth sign-in failed");return}}catch{}!m&&!be.current&&p<D?d.current=setTimeout(()=>void t(),1500):!m&&!be.current&&(de("OAuth sign-in timed out. Use the manual code fallback."),He(w))}};return d.current=setTimeout(()=>void t(),750),()=>{m=!0,se()}},[s,n,Q,P,ke]),o.useEffect(()=>{if(!s||!n||Q!=="oauth")return;const m=n.id,p=n.name,w=ke;if(!w)return;let x=window.location.origin;if(Xe)try{x=new URL(Xe).origin}catch{return}const M=f=>as(oi(f),{origin:x,eventOrigin:x,expectedState:w,expectedProvider:m});function D(f){if(!be.current){if(f.error){f.state&&os(f.state),de(f.errorDescription||f.error||"OAuth sign-in failed");return}!f.code||!f.state||(os(f.state),be.current=!0,G(f.code),oe(null),R(!0),(async()=>{try{await he.current({name:Ae.current.trim()||p,authFlow:"oauth",oauthCode:f.code,oauthState:f.state,oauthCodeVerifier:Ye||void 0,oauthRedirectUri:Xe||void 0}),we()}catch(j){be.current=!1,de(Z(j,"OAuth sign-in completed, but the token exchange failed. Restart the connection flow and try again."))}finally{R(!1)}})())}}function t(f){const j=as(f.data,{origin:x,eventOrigin:f.origin,expectedState:w,expectedProvider:m,eventSource:f.source,expectedSource:qt.current});j&&D(j)}const r=w,l=li(r);function v(f){const j=f===void 0?ii(r):ai(f),V=j?M(j):null;V&&D(V)}function g(f){f.key===l&&v(f.newValue)}v(),window.addEventListener("message",t),window.addEventListener("storage",g);const k=window.setInterval(()=>v(),500);return()=>{window.removeEventListener("message",t),window.removeEventListener("storage",g),window.clearInterval(k)}},[s,n,Q,ke,Ye,Xe]),o.useEffect(()=>()=>{H.current=!0,se(),we(),He()},[]),o.useEffect(()=>{if(!s||!n||Q!=="device"||!re)return;H.current=!1;let m=null,p=!1;const w=n.id,x=n.name,M=Ke||void 0,D=Math.max(2,ut)*1e3;async function t(){if(!(p||H.current||!re)){try{const r=await fs(w,{deviceCode:re,codeVerifier:M,displayName:Ae.current.trim()||x});if(p||H.current)return;if(r.success){oe("Authorized — connection saved"),R(!0);try{await he.current({name:Ae.current.trim()||x,alreadySaved:!0})}catch{oe("Authorized — refresh the list if not visible")}finally{R(!1)}return}r.pending?oe("Still waiting for authorization…"):r.error&&oe(r.error)}catch(r){p||oe(Z(r,"Poll failed"))}!p&&!H.current&&(m=setTimeout(t,D))}}return m=setTimeout(t,D),()=>{p=!0,H.current=!0,m&&clearTimeout(m)}},[s,n==null?void 0:n.id,n==null?void 0:n.name,Q,re,Ke,ut]),o.useEffect(()=>{pe(null),te(null),B(null)},[y]),!n)return null;const Ln=Tn(n.authType,n.noAuth),In=Pi(n.authType,n.noAuth),bt=!fe&&!pn&&(Ue?Ie===!0&&y.trim().length>0:Q==="import"?yt?ot.length>0&&!vt:J?me==="import-token"?Gt.trim().length>0:Et.trim().length>0:N.trim().length>0&&((n==null?void 0:n.id)!=="cursor"||F.trim().length>0):Q==="oauth"?T.trim().length>0:Q==="device"?!!re:!0);async function vn(){if(!(!n||!y.trim())){Le(!0),te(null);try{const m=await ss({provider:n.id,apiKey:y.trim(),...J?{providerSpecificData:{region:ht.trim()||"us-east-1"}}:{}}),p=m.valid===!0;pe(p),te(p?"Key valid":m.error||"Key invalid")}catch(m){pe(!1),te(Z(m,"Check failed"))}finally{Le(!1)}}}async function Kn(){if(!n||!A.trim())return;const m=_i(A);if(!m.length)return;De(!0);const p=m.map(x=>({...x,checking:!1})),w=new Set;We([...p]),Ce(0);try{for(let x=0;x<p.length;x+=1){Ce(x);const M=p[x];if(M.valid===!1){We([...p]);continue}const D=M.credentialToken||`${M.accessToken}|${M.refreshToken}`;if(w.has(D)){p[x]={...M,valid:!1,checking:!1,msg:"Duplicate token pair in this batch"},We([...p]);continue}w.add(D),p[x]={...M,checking:!0},We([...p]);try{const t=await zs({provider:n.id,...M.credentialToken?{credentialToken:M.credentialToken}:{accessToken:M.accessToken,refreshToken:M.refreshToken}});p[x]={...M,valid:t.valid===!0,checking:!1,msg:t.valid===!0?"ok":t.error||"Token invalid"}}catch(t){p[x]={...M,valid:!1,checking:!1,msg:Z(t,"Token validation failed")}}We([...p]),x<p.length-1&&await new Promise(t=>{window.setTimeout(t,$i)})}}finally{Ce(null),De(!1)}}async function Rn(){if(!(!n||n.id!=="cursor")){Be(!0),et(null),tt(!1);try{const m=await Bs();if(!m.found||!m.accessToken||!m.machineId)throw new Error(m.error||"Cursor credentials were not found on this device");K(m.accessToken),z(m.machineId),et("Cursor token and Machine ID filled automatically")}catch(m){tt(!0),et(Z(m,"Could not detect Cursor credentials"))}finally{Be(!1)}}}async function On(){if(O)try{await navigator.clipboard.writeText(O),_e(!0),window.setTimeout(()=>_e(!1),1500)}catch{}}function Fn(){if(!O)return;const m=window.open(O,"sway-oauth","popup,width=600,height=700");qt.current=m,m||de("The browser blocked the authorization window. Open the URL above manually or allow popups for this dashboard.")}async function Dn(){if(!(!n||!bt)){R(!0),B(null);try{const m=c.trim(),p=$e?ri(T,ke):null;await u({name:m,autoName:Ue&&!m,authFlow:Q,apiKey:Ue&&y.trim()||void 0,importToken:Q==="import"&&!J&&!yt&&N.trim()||void 0,codeBuddyToken:Q==="import"&&yt&&ot.length===1&&ot[0].credentialToken||void 0,codeBuddyTokens:Q==="import"&&yt?ot.map((w,x)=>{const M=ot.length===1?m:"";return{...w.credentialToken?{credentialToken:w.credentialToken}:{accessToken:w.accessToken,refreshToken:w.refreshToken},name:M||`swayrouter-account${x+1}`,autoName:!M}}):void 0,machineId:Q==="import"&&F.trim()||void 0,kiroAuthMode:J?me:void 0,kiroRegion:J?ht.trim()||"us-east-1":void 0,kiroRefreshToken:J&&Gt.trim()||void 0,kiroClientId:J&&dn.trim()||void 0,kiroClientSecret:J&&Ze.trim()||void 0,kiroProfileArn:J&&Pt.trim()||void 0,kiroCliProxyJson:J&&Et.trim()||void 0,oauthCode:p==null?void 0:p.code,oauthState:p==null?void 0:p.state,oauthCodeVerifier:$e&&Ye||void 0,oauthRedirectUri:$e&&Xe||void 0,deviceCode:lt&&re||void 0,deviceCodeVerifier:lt&&Ke||void 0,proxyPoolId:Ue?U:null})}catch(m){B(Z(m,"Failed to add connection"))}finally{R(!1)}}}const qn=le==="bulk"&&Ue?"Add connections":Ln;return e.jsx(Ut,{open:s,onOpenChange:a,children:e.jsxs($t,{children:[e.jsx(Qt,{children:e.jsxs(Vt,{children:[qn," — ",n.name]})}),e.jsxs("div",{className:ce("px-6",Ue&&le==="bulk"?"space-y-2 pb-4":"space-y-3 pb-4"),children:[!J&&at&&ve?e.jsx(Fi,{value:tn,modes:ve,label:m=>Ot((n==null?void 0:n.id)??"",m),onChange:m=>{un(m),nt("single"),st(""),je([]),ye(null),B(null)}}):null,J?e.jsx(Li,{value:me,region:ht,startUrl:Ht,onChange:xn,onRegionChange:At,onStartUrlChange:Tt}):null,Ue&&!J?e.jsx(Di,{value:le,onChange:nt}):null,Ue&&!J&&le==="bulk"?e.jsx(qi,{raw:xt,rows:It,activeIndex:Xt,activeRow:mn,checking:Kt,validCount:Ge.length,onRawChange:m=>{st(m),je([]),ye(null),B(null)},onCheck:hn}):null,le==="single"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{htmlFor:"connection-account-name",className:"text-xs font-medium text-muted-foreground",children:["Account name ",e.jsx("span",{className:"font-normal text-muted-foreground/70",children:"(optional)"})]}),e.jsx(ne,{id:"connection-account-name",placeholder:"Auto: swayrouter-account",value:c,"aria-invalid":!!xe,"aria-describedby":xe?"connection-submit-error":void 0,onChange:m=>{h(m.target.value),B(null)}})]}),Ft?e.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-2.5 py-2 text-xs text-destructive",children:Ft}):null,pn?e.jsx("p",{className:"text-xs text-muted-foreground",children:e.jsx(ln,{children:"Starting auth flow…"})}):null,Q==="import"?yt?e.jsx(Bi,{raw:A,rows:Fe,activeIndex:it,activeRow:En,checking:vt,validCount:ot.length,onRawChange:m=>{b(m),We([]),Ce(null),B(null)},onCheck:Kn}):J?e.jsx(Ii,{mode:me,refreshToken:Gt,clientId:dn,clientSecret:Ze,profileArn:Pt,cliProxyJson:Et,onRefreshTokenChange:ft,onClientIdChange:Mt,onClientSecretChange:Oe,onProfileArnChange:Yt,onCliProxyJsonChange:Lt}):e.jsx(zi,{providerId:n.id,token:N,machineId:F,importing:pt,message:Mn,hasError:Pn,onTokenChange:K,onMachineIdChange:z,onAutoImport:Rn}):Q==="local"?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Local provider — no key required."}):nn?e.jsx(Oi,{isDeviceFlow:lt,isOAuthFlow:$e,isKiroIam:J&&me==="iam",authLink:O,userCode:S,deviceStatus:Re,deviceCode:re,bootLoading:Dt,linkCopied:en,oauthCode:T,kiroStartUrl:Ht,onStartKiroAuthorization:gn,onOpenAuthLink:Fn,onCopyAuthLink:On,onOauthCodeChange:G}):e.jsx(Ri,{authLabel:Ot(n.id,"apikey"),apiKey:y,region:ht,checking:Ee,keyValid:Ie,checkMsg:ze,submitError:xe,proxyPoolId:U,proxyOptions:Y,showKiroRegion:J,onApiKeyChange:m=>{C(m),B(null)},onRegionChange:At,onCheck:vn,onProxyPoolChange:_}),xe?e.jsx("p",{id:"connection-submit-error",className:"text-xs text-destructive",role:"alert",children:xe}):null]}):null]}),e.jsxs(Wt,{children:[e.jsx(E,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(E,{disabled:le==="bulk"?Rt||Kt||Ge.length===0:!bt,className:ce((le==="bulk"?Rt||Kt||Ge.length===0:!bt)&&"opacity-40"),onClick:()=>void(le==="bulk"?fn():Dn()),children:le==="bulk"?Rt?"Adding…":"Add":fe?e.jsx(ln,{children:lt||$e?"Waiting…":"Saving…"}):lt?"Poll now":$e&&!T.trim()?"Waiting for browser…":In})]})]})})}function ls({open:s,onOpenChange:n,onCreate:i,initial:a,submitLabel:u="Create"}){const[c,h]=o.useState(""),[y,C]=o.useState(""),[N,K]=o.useState(""),[A,b]=o.useState("openai-compatible"),[F,z]=o.useState("chat");o.useEffect(()=>{!s||!a||(h(a.name||""),C(a.alias||""),K(a.baseUrl||""),b(a.nodeType==="anthropic-compatible"?"anthropic-compatible":"openai-compatible"),z(a.apiType==="responses"?"responses":"chat"),Y(null),U(!1))},[s,a]);const T=!!a,[G,U]=o.useState(!1),[_,Y]=o.useState(null);return o.useEffect(()=>{s&&(a||(h(""),C(""),K(""),b("openai-compatible"),z("chat"),Y(null),U(!1)))},[s,a]),e.jsx(Ut,{open:s,onOpenChange:n,children:e.jsxs($t,{children:[e.jsx(Qt,{children:e.jsx(Vt,{children:T?"Edit custom provider":"Custom provider"})}),e.jsxs("div",{className:"space-y-3 px-6 pb-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{htmlFor:"custom-provider-name",className:"text-xs font-medium text-muted-foreground",children:"Name"}),e.jsx(ne,{id:"custom-provider-name",placeholder:"My provider",value:c,"aria-invalid":!!_,"aria-describedby":_?"custom-provider-error":void 0,onChange:$=>{h($.target.value),Y(null)}})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{htmlFor:"custom-provider-prefix",className:"text-xs font-medium text-muted-foreground",children:"Prefix"}),e.jsx(ne,{id:"custom-provider-prefix",placeholder:"my-llm",value:y,"aria-invalid":!!_,"aria-describedby":_?"custom-provider-error":void 0,onChange:$=>{C($.target.value),Y(null)}}),e.jsx("p",{className:"text-[10px] text-muted-foreground/70",children:"Must be unique across custom providers."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{htmlFor:"custom-provider-base-url",className:"text-xs font-medium text-muted-foreground",children:"Base URL"}),e.jsx(ne,{id:"custom-provider-base-url",placeholder:"https://api.example.com/v1",value:N,onChange:$=>K($.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"API format"}),e.jsx(jt,{size:"sm",value:A,onChange:b,options:[{value:"openai-compatible",label:"OpenAI"},{value:"anthropic-compatible",label:"Claude"}]})]}),A==="openai-compatible"?e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Endpoint style (OpenAI only)"}),e.jsx(jt,{size:"sm",value:F,onChange:z,options:[{value:"chat",label:"Chat"},{value:"responses",label:"Responses"}]})]}):e.jsx("p",{className:"rounded-md border border-border bg-surface px-3 py-2 text-xs text-muted-foreground",children:"Claude-compatible nodes use the Messages API only — no Chat / Responses toggle (BACKEND custom nodes)."}),_?e.jsx("p",{id:"custom-provider-error",className:"text-sm text-destructive",role:"alert",children:_}):null]}),e.jsxs(Wt,{children:[e.jsx(E,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(E,{disabled:G,onClick:()=>{if(!c.trim()||!y.trim()){Y("Name and prefix required");return}U(!0),i({name:c.trim(),prefix:y.trim().toLowerCase().replace(/\s+/g,"-"),baseUrl:N.trim()||void 0,type:A,apiType:A==="openai-compatible"?F:void 0}).catch($=>{Y(Z($,"Failed to save custom provider"))}).finally(()=>U(!1))},children:u})]})]})})}function _n({label:s,hint:n,children:i}){return e.jsxs("label",{className:"block space-y-1.5",children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:s}),i,n?e.jsx("span",{className:"block text-[10px] text-muted-foreground/70",children:n}):null]})}function Wi({conn:s,onOpenChange:n,onSave:i}){var $,fe;const[a,u]=o.useState(""),[c,h]=o.useState(!1),[y,C]=o.useState(""),[N,K]=o.useState(null),[A,b]=o.useState(!1);o.useEffect(()=>{s&&(u(s.name||""),C(""),K(null))},[s]);const F=String((s==null?void 0:s.authType)||"").trim().toLowerCase(),z=typeof(($=s==null?void 0:s.providerSpecificData)==null?void 0:$.authMethod)=="string"?s.providerSpecificData.authMethod.trim().toLowerCase():"",T=F||z,G=s?kn(s.provider):"apikey",U=T==="apikey"||T==="api_key"||T==="api-key"||!T&&G==="apikey",_=T.includes("oauth")||T==="access_token"||!T&&(G==="oauth"||G==="device")?"OAuth":T.includes("cookie")?"Cookie":T==="local"||T==="none"||!T&&G==="local"?"No authentication":T.includes("import")||T==="imported"?"Imported token":U?"API Key":T||"Managed credentials";async function Y(){if(s){b(!0),K(null);try{const R=await ps(s.id),Ee=R.valid===!0;K({label:Ee?"Active":R.error||"Failed",ok:Ee})}catch(R){K({label:Z(R,"Test failed"),ok:!1})}finally{b(!1)}}}return e.jsx(Ut,{open:!!s,onOpenChange:n,children:e.jsxs($t,{children:[e.jsxs(Qt,{children:[e.jsx(Vt,{children:"Edit connection"}),e.jsx(wn,{children:(s==null?void 0:s.name)||((fe=s==null?void 0:s.id)==null?void 0:fe.slice(0,8))})]}),e.jsxs("div",{className:"space-y-3 px-6",children:[e.jsx(_n,{label:"Name",children:e.jsx(ne,{value:a,onChange:R=>u(R.target.value)})}),U?e.jsxs(_n,{label:"API Key",hint:"Leave empty to keep current key",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ne,{type:"password",value:y,onChange:R=>C(R.target.value),placeholder:"sk-… or paste new key",className:"flex-1"}),e.jsx(E,{size:"sm",variant:"outline",disabled:A,"aria-busy":A,"aria-label":A?"Testing connection":"Test connection",className:"min-w-14 justify-center",onClick:()=>void Y(),children:A?e.jsx(cn,{className:"h-3.5 w-3.5 animate-spin","aria-hidden":"true"}):"Test"})]}),N?e.jsx("p",{className:ce("mt-1 text-[11px]",N.ok?"text-success":"text-destructive"),children:N.label}):null]}):e.jsxs(_n,{label:"Authentication",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border bg-muted/25 px-3 py-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:_}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Credentials are managed by this connection."})]}),e.jsx(E,{size:"sm",variant:"outline",disabled:A,"aria-busy":A,"aria-label":A?"Testing connection":"Test connection",className:"min-w-14 justify-center",onClick:()=>void Y(),children:A?e.jsx(cn,{className:"h-3.5 w-3.5 animate-spin","aria-hidden":"true"}):"Test"})]}),N?e.jsx("p",{className:ce("mt-1 text-[11px]",N.ok?"text-success":"text-destructive"),children:N.label}):null]})]}),e.jsxs(Wt,{children:[e.jsx(E,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(E,{disabled:c,onClick:()=>{h(!0),i(a.trim(),y).finally(()=>h(!1))},children:"Save"})]})]})})}function Cs({id:s,color:n,size:i=24,fallbackIcon:a}){const u=Ms(s);if(u){const c=Math.max(4,Math.round(i/5));return e.jsx("span",{"aria-hidden":"true",className:"block shrink-0",style:{width:i,height:i,borderRadius:c,backgroundColor:n||"currentColor",WebkitMaskImage:`url(${u})`,maskImage:`url(${u})`,WebkitMaskPosition:"center",maskPosition:"center",WebkitMaskRepeat:"no-repeat",maskRepeat:"no-repeat",WebkitMaskSize:"contain",maskSize:"contain"}})}return e.jsx(a,{className:"shrink-0",style:{width:i*.85,height:i*.85,color:n||void 0}})}function Ji({byProvider:s,filter:n,hiddenProviders:i,loading:a,query:u,providerListRef:c,selectedId:h,sorted:y,onFilterChange:C,onQueryChange:N,onSelectProvider:K,onToggleProviderHidden:A}){return e.jsxs(ws,{className:ce("flex shrink-0 flex-col overflow-hidden","w-full h-[24dvh] max-h-[24dvh] min-h-0 sm:h-[30dvh] sm:max-h-[30dvh] lg:h-full lg:max-h-none lg:min-h-0 lg:w-[300px] xl:w-[340px]"),children:[e.jsxs(ks,{className:"space-y-1.5 border-b border-border p-2.5 sm:space-y-2 sm:p-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(xs,{className:"pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(ne,{className:ce("pl-8",u?"pr-8":void 0),placeholder:"Search providers…",value:u,autoComplete:"off",autoCorrect:"off",autoCapitalize:"none",spellCheck:!1,"data-1p-ignore":"true","data-lpignore":"true",onChange:b=>N(b.target.value)}),u?e.jsx(ee,{label:"Clear search",children:e.jsx("button",{type:"button","aria-label":"Clear provider search",className:"absolute right-2.5 top-1/2 -translate-y-1/2 rounded p-0.5 text-muted-foreground transition-colors hover:bg-surface-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",onClick:()=>N(""),children:e.jsx(Gn,{className:"h-4 w-4"})})}):null]}),e.jsx(jt,{size:"sm",value:n,onChange:C,options:[{value:"all",label:"All"},{value:"active",label:"Active"},{value:"idle",label:"Idle"}]})]}),e.jsx(js,{className:"flex min-h-0 flex-1 flex-col overflow-hidden p-0",children:e.jsx(Jn,{overscrollContain:!0,scrollFade:!0,scrollbarGutter:!0,viewportRef:c,className:"min-h-0 flex-1",children:e.jsx("div",{className:"p-2",children:a?e.jsx("div",{className:"space-y-2 p-1",children:Array.from({length:6}).map((b,F)=>e.jsx(Ai,{className:"h-14 w-full rounded-lg"},F))}):y.length===0?e.jsx("p",{className:"p-6 text-center text-sm text-muted-foreground",children:"No providers match"}):e.jsx("ul",{className:"space-y-1",children:y.map(b=>{const F=s.get(b.id)||[],z=b.id===h?F.length:b.connected||0,T=b.id===h?F.filter(R=>R.isActive!==!1).length:z,G=b.id===h?F.length-T:0,U=h===b.id,_=i.includes(b.id),Y=hs(b.id),$=b.isCustom?"apikey":kn(b.id,b.authType,b.noAuth),fe=$==="apikey"?hi:$==="oauth"||$==="device"?fi:$==="import"?pi:xi;return e.jsx("li",{"data-provider-id":b.id,children:e.jsxs("div",{className:ce("group relative flex w-full items-center rounded-lg transition-colors duration-100",U?"text-foreground":"hover:bg-surface-hover/70",_&&"opacity-55"),children:[U?e.jsx(dt.span,{layoutId:"provider-highlight",className:"absolute inset-0 rounded-lg bg-white/15",transition:{type:"spring",stiffness:520,damping:36,mass:.4}}):null,e.jsxs("button",{type:"button",onClick:()=>K(b.id),className:ce("relative z-10 flex min-w-0 flex-1 items-center gap-2 rounded-lg px-2 py-2 text-left outline-none focus-visible:ring-1 focus-visible:ring-white/20 sm:gap-3 sm:px-3 sm:py-2.5"),children:[e.jsxs("span",{className:"relative z-10 flex size-7 shrink-0 items-center justify-center rounded-lg bg-white p-1.5 outline outline-1 outline-white/30 outline-offset-2 sm:size-8",children:[e.jsx(Cs,{id:b.id,color:"var(--background)",size:20,fallbackIcon:Y}),e.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 flex h-3.5 w-3.5 items-center justify-center rounded-full border border-border/60 bg-card/90 text-muted-foreground",children:e.jsx(fe,{className:"h-2 w-2"})})]}),e.jsxs("div",{className:"relative z-10 min-w-0 flex-1",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1 sm:gap-1.5",children:[e.jsx("span",{className:"truncate text-[13px] font-medium sm:text-sm",children:b.name}),e.jsx(Qn,{variant:"outline",size:"sm",className:"max-w-[5.5rem] truncate font-mono text-[9px] text-muted-foreground sm:max-w-none sm:text-[10px]",children:b.alias||b.id})]}),e.jsxs("div",{className:"mt-0.5 flex flex-wrap items-center gap-x-1.5 gap-y-0.5 text-[10px] text-muted-foreground sm:gap-x-2 sm:text-[11px]",children:[Ps(b.authType,b.noAuth,b.authModes).map(R=>e.jsxs("span",{className:"inline-flex items-center gap-0.5 rounded border border-border bg-background/50 px-1 py-px font-medium sm:gap-1 sm:px-1.5",children:[e.jsx(fe,{className:"h-2.5 w-2.5"}),R]},R)),z>0?e.jsxs(e.Fragment,{children:[G>0?e.jsxs("span",{className:"inline-flex items-center gap-0.5 rounded bg-muted px-1 py-px text-[10px] font-medium text-muted-foreground sm:gap-1 sm:px-1.5 sm:text-[11px]",children:[G," off"]}):null,e.jsxs(Pe,{tone:"ok",className:"text-[10px] font-medium sm:text-[11px]",children:[z," connection",z===1?"":"s"]})]}):e.jsx("span",{className:"text-muted-foreground/60",children:"no connections"})]})]})]}),e.jsx(ee,{label:_?"Show provider":"Hide provider",children:e.jsx("button",{type:"button","aria-label":_?`Show ${b.name}`:`Hide ${b.name}`,"aria-pressed":_,onClick:()=>A(b.id),className:"relative z-10 mr-1 flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-[background-color,opacity,color] hover:bg-surface-hover hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring group-hover:opacity-100 sm:mr-2",children:_?e.jsx(gi,{className:"size-3.5"}):e.jsx(vi,{className:"size-3.5"})})})]})},b.id)})})})})})]})}function Jt({busy:s,onTest:n,onStop:i,label:a="Test",disabled:u,compact:c}){return s?e.jsx(ee,{label:"Cancel test",disabled:!c,children:e.jsxs(E,{size:"sm",variant:"outline",onClick:i,"aria-label":c?"Cancel test":void 0,className:ce(c&&"h-7 w-7 p-0",!c&&"gap-1.5"),children:[e.jsx(cn,{className:"h-3.5 w-3.5 animate-spin"}),c?null:"Cancel"]})}):e.jsx(ee,{label:a,disabled:!c,children:e.jsx(E,{size:"sm",variant:"outline",disabled:u,onClick:n,"aria-label":c?a:void 0,className:c?"h-7 px-2 text-[11px]":void 0,children:a})})}function Nn(s,n){const i=String(s||"").trim();if(!i)return i;const a=String(n||"").trim().toLowerCase();if(!(a==="clinepass"||a==="cline-pass"||/^(?:clinepass|cline-pass)\//i.test(i)))return i;let c=i.replace(/^clinepass\//i,"").replace(/^cline-pass\//i,"");return c=c.replace(/^clinepass\//i,"").replace(/^cline-pass\//i,""),`clinepass/${c}`}const Hi=["vision","pdf","audioInput","videoInput","imageOutput","audioOutput","search","tools","reasoning"];function Vn(s){if(!s||typeof s!="object"||Array.isArray(s))return;const n=s,i={};for(const a of Hi)typeof n[a]=="boolean"&&(i[a]=n[a]);if((typeof n.thinkingFormat=="string"||n.thinkingFormat===null)&&(i.thinkingFormat=n.thinkingFormat),typeof n.thinkingCanDisable=="boolean"&&(i.thinkingCanDisable=n.thinkingCanDisable),n.thinkingRange&&typeof n.thinkingRange=="object"&&!Array.isArray(n.thinkingRange)){const a=n.thinkingRange,u={};Number.isFinite(Number(a.min))&&(u.min=Number(a.min)),Number.isFinite(Number(a.max))&&(u.max=Number(a.max)),i.thinkingRange=u}else n.thinkingRange===null&&(i.thinkingRange=null);for(const a of["contextWindow","maxOutput"])Number.isFinite(Number(n[a]))&&(i[a]=Number(n[a]));return Object.keys(i).length?i:void 0}const Gi=[["vision","Vision"],["pdf","PDF"],["audioInput","Audio"],["videoInput","Video"],["imageOutput","Image out"],["audioOutput","Audio out"],["search","Search"],["tools","Tools"],["reasoning","Reasoning"]];function Yi(s){return s?Gi.filter(([n])=>s[n]===!0).map(([n,i])=>({key:n,label:i})):[]}function Un(s,n){return Array.isArray(s)?s.flatMap(i=>{if(!i||typeof i!="object"||Array.isArray(i))return[];const a=i,u=typeof a.id=="string"?a.id.trim():typeof a.model=="string"?a.model.trim():"",c=Nn(u,n);if(!c)return[];const h=typeof a.name=="string"&&a.name.trim()?a.name.trim():c,y=Array.isArray(a.thinkingLevels)?a.thinkingLevels.filter(C=>typeof C=="string"):void 0;return[{id:c,name:h,caps:Vn(a.capabilities??a.caps),...y?{thinkingLevels:y}:{}}]}):[]}function cs(s,n){if(!s)return!0;const i=s.trim().toLowerCase(),a=n.trim().toLowerCase();return i===a||i===a.replace(/^clinepass\//,"")||/^cline-pass\//.test(i)||/^clinepass\/cline-pass\//.test(i)}function Xi(s,n){var a;const i=new Map;for(const u of s){const c=Nn(u.id,u.provider_alias||u.provider_id||u.owned_by||n);if(!c)continue;const h=c===u.id?u:{...u,id:c},y=i.get(c);if(!y){i.set(c,h);continue}const C=cs(y.name,c)&&!cs(h.name,c)?h.name:y.name||h.name;i.set(c,{...y,name:C,provider_alias:y.provider_alias||h.provider_alias,provider_id:y.provider_id||h.provider_id,owned_by:y.owned_by||h.owned_by,caps:{...h.caps,...y.caps},thinkingLevels:(a=y.thinkingLevels)!=null&&a.length?y.thinkingLevels:h.thinkingLevels})}return[...i.values()]}function Zi({selected:s,visibleModels:n,models:i,modelNames:a,modelsLoading:u,modelsUnavailable:c,importingModels:h,testConnId:y,batchKind:C,modelTestLock:N,testingModels:K,modelQuery:A,newModel:b,addingModel:F,modelResults:z,pinnedFor:T,copied:G,onImportModels:U,onTestAllModels:_,onStopTests:Y,onStopModel:$,onModelQueryChange:fe,onNewModelChange:R,onAddModel:Ee,onTogglePin:Le,onCopyModelId:Ie,onTestModel:pe,onRemoveModel:ze,disabledModelIds:te,onToggleDisabled:xe}){return e.jsx(bs,{value:"models",className:"min-h-0 flex-1 basis-0",children:e.jsx(Jn,{overscrollContain:!0,scrollFade:!0,scrollbarGutter:!0,className:"h-full",children:e.jsxs("div",{className:"space-y-3 p-3 sm:p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:[n.length," models"]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.id==="codebuddy-cn"||s.id==="codebuddy-intl"?e.jsx("span",{className:"self-center text-xs text-muted-foreground",children:"Add models manually"}):s.id!=="qoder"?e.jsx(ee,{label:y?"Fetch GET {base}/models with this connection’s key":"Needs a connection (API key) on this provider — or set base URL on a custom node",children:e.jsx(E,{size:"sm",variant:"outline",disabled:h,onClick:()=>void U(),children:h?"Importing…":"Import"})}):null,i.length>0?e.jsx(Jt,{busy:C==="model",label:"Test all",disabled:!y||N||C!==null&&C!=="model"||K.size>0&&C!=="model",onTest:()=>void _(),onStop:Y}):null]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ne,{placeholder:"Search models…",value:A,onChange:B=>fe(B.target.value),className:"min-w-0 flex-1"}),e.jsx(ne,{placeholder:"model-id",value:b,disabled:F,onChange:B=>R(B.target.value),onKeyDown:B=>{B.key==="Enter"&&Ee()},className:"min-w-0 flex-1"}),e.jsxs(E,{size:"sm",variant:"outline",disabled:F||!b.trim(),onClick:()=>void Ee(),children:[e.jsx(An,{className:"h-3.5 w-3.5"}),"Add"]})]}),u?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading models…"}):n.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:A.trim()?"No models match your search.":c?"Upstream model catalog unavailable — add a slug above or retry.":"No models — add a slug above."}):e.jsx(dt.div,{layout:!0,className:"space-y-1",children:n.map(B=>{const O=B.id,ie=z[O],re=K.has(O),ge=Yi(B.caps),Ke=C==="model"||re,L=T.includes(O),S=te.has(O);return e.jsx(dt.div,{layout:!0,transition:{layout:{type:"spring",stiffness:520,damping:36,mass:.4}},className:ce("rounded-md border border-border bg-background px-2.5 py-2 hover:border-foreground/30",S&&"border-warning/40 bg-warning/[0.03]"),children:e.jsxs("div",{className:"group flex flex-wrap items-center gap-1.5",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 flex-wrap items-center gap-1.5",children:[a.get(O)?e.jsx("span",{className:"min-w-0 max-w-[45%] truncate text-xs font-medium",children:a.get(O)}):null,e.jsx("code",{className:"min-w-0 flex-1 truncate font-mono text-[11px] text-muted-foreground",children:O}),S?e.jsx(Qn,{size:"sm",variant:"warning",children:"Disabled"}):null,re||ie?e.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[re?e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-[10px] text-foreground/90","aria-live":"polite","aria-label":`Checking ${O}`,children:[e.jsx("span",{children:"Checking"}),e.jsxs("span",{className:"inline-flex w-3 justify-start","aria-hidden":"true",children:[e.jsx("span",{className:"animate-pulse",children:"."}),e.jsx("span",{className:"animate-pulse [animation-delay:150ms]",children:"."}),e.jsx("span",{className:"animate-pulse [animation-delay:300ms]",children:"."})]})]}):null,ie?e.jsx(ee,{label:ie.message||ie.label,children:e.jsx(Pe,{tone:ie.ok?"ok":"err",className:"max-w-[9rem] truncate text-[10px]",children:ie.label})}):null]}):null,ge.length>0?e.jsx("div",{className:"order-last flex min-w-0 w-full shrink-0 flex-nowrap items-center gap-1 overflow-x-auto pb-0.5 sm:order-none sm:w-auto sm:flex-wrap sm:overflow-visible sm:pb-0","aria-label":"Model capabilities",children:ge.map(ae=>e.jsx(ee,{label:ae.label,children:e.jsx(Qn,{size:"sm",variant:"outline","aria-label":ae.label,className:"shrink-0",children:ae.label})},ae.key))}):null]}),e.jsxs("div",{className:"flex w-full shrink-0 items-center justify-end gap-1 border-t border-border/60 pt-1.5 sm:w-auto sm:justify-start sm:border-0 sm:pt-0",children:[e.jsx(ee,{label:L?"Unpin":"Pin to top",children:e.jsx("button",{type:"button","aria-label":L?"Unpin model":"Pin model to top",onClick:()=>Le(O),className:ce("inline-flex h-7 w-7 items-center justify-center rounded-md border p-0 transition-colors duration-150",L?"border-transparent bg-white/15 text-foreground":"border-transparent text-muted-foreground hover:border-border hover:bg-surface-hover hover:text-foreground"),children:e.jsx(Yn,{initial:!1,mode:"wait",children:e.jsx(dt.span,{initial:{opacity:0,scale:.7,rotate:-18},animate:{opacity:1,scale:1,rotate:0},exit:{opacity:0,scale:.7,rotate:18},transition:{duration:.14},className:"block",children:L?e.jsx(yi,{className:"h-3.5 w-3.5"}):e.jsx(bi,{className:"h-3.5 w-3.5"})},L?"pinned":"unpinned")})})}),e.jsx(ee,{label:G===O?"Copied":"Copy model ID",children:e.jsx("button",{type:"button","aria-label":"Copy model ID",className:"inline-flex h-7 w-7 items-center justify-center rounded-md p-0 text-muted-foreground transition-colors duration-100 hover:bg-surface-hover hover:text-foreground",onClick:()=>void Ie(O),children:G===O?e.jsx(Sn,{className:"h-3.5 w-3.5"}):e.jsx(Hn,{className:"h-3.5 w-3.5"})})}),e.jsx(ee,{label:S?"Enable routing for model":"Disable routing for model",children:e.jsx("button",{type:"button","aria-label":S?"Enable routing for model":"Disable routing for model","aria-pressed":S,onClick:()=>void xe(O),className:ce("inline-flex h-7 w-7 items-center justify-center rounded-md p-0 text-muted-foreground transition-colors hover:bg-surface-hover hover:text-foreground",S&&"text-warning hover:text-warning"),children:S?e.jsx(wi,{className:"h-3.5 w-3.5"}):e.jsx(ki,{className:"h-3.5 w-3.5"})})}),e.jsx("span",{className:"sm:hidden",children:e.jsx(Jt,{compact:!0,busy:Ke,disabled:!y||N||C==="conn"||!re&&K.size>=4,onTest:()=>void pe(O,y),onStop:()=>C==="model"?Y():$(O)})}),e.jsx("span",{className:"hidden sm:inline-flex",children:e.jsx(Jt,{busy:Ke,disabled:!y||N||C==="conn"||!re&&K.size>=4,onTest:()=>void pe(O,y),onStop:()=>C==="model"?Y():$(O)})}),e.jsx(ee,{label:"Remove",children:e.jsx("button",{type:"button","aria-label":"Remove model",className:"inline-flex h-7 w-7 items-center justify-center rounded-md p-0 text-muted-foreground transition-colors duration-100 hover:bg-surface-hover hover:text-destructive",onClick:()=>void ze(O),children:e.jsx(jn,{className:"h-3.5 w-3.5"})})})]})]})},O)})})]})})})}const er=["auto","low","medium","high","xhigh","max"],$n=["auto","low","medium","high","max"],tr={openai:er,claude:$n,deepseek:["auto","low","high","max"],groq:["auto","low","medium","high"],openrouter:$n,kimi:$n,glm:["auto","low","medium","high"],minimax:["auto","low","medium","high"],kiro:["auto","low","medium","high"],codex:["auto","low","medium","high","xhigh"],github:["auto","low","medium","high"],cursor:["auto","low","medium","high"],"gemini-cli":["auto","low","medium","high"],"grok-cli":["auto","low","medium","high"],"ollama-local":["auto","low","medium","high"],antigravity:["auto","low","medium","high"],qwen:["auto","low","medium","high"],"codebuddy-cn":["auto","low","medium","high"]},nr=["auto","none","on","off","thinking","minimal","low","medium","high","xhigh","max","ultra"],ds={"x-high":"xhigh",maximum:"max"};function Xn(s){const n=String(s||"").trim().toLowerCase();return n?n in ds?ds[n]:["auto","none","on","off","thinking","minimal","low","medium","high","xhigh","max","ultra"].includes(n)?n:null:null}function sr(s){if(!Array.isArray(s==null?void 0:s.options))return[];const n=s.options.flatMap(u=>{const c=Xn(u);return c?[c]:[]}),i=[...new Set(n)];if(!i.length)return[];const a=i.every(u=>["auto","on","off"].includes(u));return!i.includes("auto")&&!a&&i.unshift("auto"),i}function ir(s){return Array.isArray(s)?s.flatMap(n=>{const i=Xn(n);return i?[i]:[]}):[]}function rr(s,n,i){if((i==null?void 0:i.modelAware)===!1)return Wn(s,i);const a=n.map(c=>new Set(ir(c))).filter(c=>c.size>0);return a.length?["auto",...nr.filter(c=>c!=="auto"&&c!=="none"&&a.some(h=>h.has(c)))]:s.startsWith("openai-compatible-")||s.startsWith("anthropic-compatible-")?null:Wn(s,i)}function Wn(s,n){if(s.startsWith("openai-compatible-")||s.startsWith("anthropic-compatible-"))return["auto","low","medium","high","max"];const i=sr(n);return i.length>0?i:tr[s]||null}function ar(s,n){const i=Wn(s,n),a=Xn(n==null?void 0:n.defaultMode);return a&&(i!=null&&i.includes(a))?a:!(i!=null&&i.length)||i.includes("auto")?"auto":i.includes("high")?"high":i[0]}function or(s){return s==="auto"?"Auto":s==="xhigh"?"xHigh":s==="thinking"?"Thinking":s.charAt(0).toUpperCase()+s.slice(1)}function lr(s){if(!s)return null;const n=Date.parse(s);if(!Number.isFinite(n))return null;const i=Math.max(0,Math.floor((Date.now()-n)/1e3));if(i<10)return"just now";if(i<60)return`${i}s ago`;const a=Math.floor(i/60);if(a<60)return`${a}m ago`;const u=Math.floor(a/60);return u<24?`${u}h ago`:`${Math.floor(u/24)}d ago`}function cr({selected:s,connsAll:n,conns:i,strategy:a,strategyPending:u,stickyDraft:c,thinkingLevels:h,thinkingValue:y,thinkingPending:C,selectedKeys:N,connectionsCapped:K,totalConnections:A,batchKind:b,testingConnId:F,togglingConnId:z,connQuery:T,connListRef:G,connVirtualizer:U,connResults:_,onStrategyChange:Y,onStickyDraftChange:$,onSaveSticky:fe,onThinkingChange:R,onRequestBulkDelete:Ee,onClearSelection:Le,onToggleSelection:Ie,onSelectAll:pe,onTestConnections:ze,onTestConnection:te,onStopTests:xe,onConnQueryChange:B,onOpenAddConnection:O,onMovePriority:ie,onToggleConnection:re,onEditConnection:ge,onDeleteConnection:Ke}){return e.jsx(bs,{value:"connections",keepMounted:!0,className:"flex min-h-0 h-full flex-1 flex-col overflow-hidden p-1.5 sm:p-5",children:e.jsxs("div",{className:"flex min-h-0 h-full flex-1 flex-col gap-1.5 overflow-hidden sm:gap-3",children:[e.jsxs("div",{className:"flex shrink-0 flex-wrap items-end justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1 space-y-1.5 sm:space-y-2",children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1.5 sm:gap-x-3 sm:gap-y-2",children:[e.jsxs("div",{className:"flex min-w-0 basis-full items-center gap-1.5 sm:basis-auto sm:gap-2",children:[e.jsx("span",{className:"text-[11px] font-medium text-muted-foreground sm:hidden",children:"Routing"}),e.jsx("span",{className:"hidden whitespace-nowrap text-xs font-medium text-muted-foreground sm:inline",children:"Account routing:"}),e.jsx("div",{className:"min-w-0 flex-1 overflow-hidden sm:flex-none",children:e.jsx(jt,{size:"sm",className:"w-full min-w-0 sm:w-auto sm:min-w-[15rem] sm:flex-none",value:a,disabled:u,onChange:Y,options:[{value:"fill-first",label:"Fill-first",mobileLabel:"Fill"},{value:"round-robin",label:"Round-robin",mobileLabel:"Round"},{value:"least-inflight",label:"Least-inflight",mobileLabel:"Least"}]})})]}),e.jsxs("div",{className:ce("inline-flex items-center gap-1.5 sm:gap-1.5",a!=="round-robin"&&"hidden sm:inline-flex"),children:[e.jsx("label",{htmlFor:"provider-sticky-limit",className:"text-xs font-medium text-muted-foreground",children:"Sticky"}),e.jsx(ne,{id:"provider-sticky-limit",size:"sm",type:"number",min:1,value:c,disabled:u||a!=="round-robin",onChange:L=>$(L.target.value),className:"w-14 shrink-0"}),e.jsx(E,{size:"sm",variant:"outline",disabled:u||a!=="round-robin",onClick:fe,children:"Save"})]})]}),h&&h.length>0?e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[e.jsx("span",{className:"shrink-0 text-xs font-medium text-muted-foreground",children:"Thinking Mode:"}),e.jsx("div",{className:"w-full min-w-0 max-w-[26rem] overflow-hidden pb-0.5 sm:flex-none sm:overflow-visible sm:pb-0",children:e.jsx(jt,{size:"compact",value:y,disabled:C,onChange:R,options:h.map(L=>({value:L,label:or(L),compactLabel:L==="minimal"?"Min":L==="medium"?"Med":L==="thinking"?"Think":L==="ultra"?"Ultra":void 0})),className:"w-full min-w-0 gap-1 p-1"})})]}):null]}),n.length>0?e.jsx("div",{className:"flex w-full shrink-0 flex-wrap items-center justify-start gap-2 sm:justify-end xl:w-auto",children:N.size>0?e.jsxs(e.Fragment,{children:[e.jsxs(E,{size:"sm",variant:"destructive",onClick:Ee,children:[e.jsx(jn,{className:"h-3.5 w-3.5"}),"Delete selected"]}),e.jsx(E,{size:"sm",variant:"outline",onClick:Le,children:"Unselect"}),e.jsx(Jt,{busy:b==="conn"||i.some(L=>F===L.id),label:"Test selected",onTest:()=>void ze([...N]),onStop:xe})]}):e.jsxs(e.Fragment,{children:[e.jsx(E,{size:"sm",variant:"outline",onClick:pe,children:"Select all"}),e.jsx(Jt,{busy:b==="conn"||i.some(L=>F===L.id),label:"Test all",onTest:()=>void ze(i.map(L=>L.id)),onStop:xe})]})}):null]}),K?e.jsxs("div",{className:"shrink-0 rounded-md border border-warning/25 bg-warning/10 px-3 py-2 text-[11px] text-warning",children:["Showing the first ",n.length.toLocaleString()," of ",A.toLocaleString()," connections. Use search to find accounts beyond this limit."]}):null,n.length>0?e.jsxs("div",{className:"relative shrink-0",children:[e.jsx(xs,{className:"pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),e.jsx(ne,{className:"h-8 pl-8 text-xs",placeholder:"Search name, id, key hint…",value:T,autoComplete:"off",autoCorrect:"off",autoCapitalize:"none",spellCheck:!1,"data-1p-ignore":"true","data-lpignore":"true",onChange:L=>B(L.target.value)})]}):null,n.length===0?e.jsxs("div",{className:"rounded-lg border border-dashed border-border px-4 py-10 text-center text-sm text-muted-foreground",children:["No connections yet",e.jsx("div",{className:"mt-3",children:e.jsxs(E,{size:"sm",onClick:O,children:[e.jsx(An,{className:"h-3.5 w-3.5"}),Tn(s.authType,s.noAuth)]})})]}):i.length===0?e.jsxs("div",{className:"rounded-lg border border-dashed border-border px-4 py-8 text-center text-sm text-muted-foreground",children:['No matches for "',T,'"']}):e.jsx("div",{className:"relative min-h-0 flex-1 overflow-hidden",children:e.jsx(Jn,{overscrollContain:!0,scrollFade:!0,viewportRef:G,className:"absolute inset-0",children:e.jsx("div",{className:"touch-pan-y [-webkit-overflow-scrolling:touch]",children:e.jsx("div",{className:"relative w-full",style:{height:`${U.getTotalSize()}px`},children:U.getVirtualItems().map(L=>{const S=i[L.index];if(!S)return null;const ae=L.index,ut=N.has(S.id),Qe=_[S.id],Re=F===S.id,oe=S.isActive===!1,ke=S.testStatus==="stale"||S.testStatus==="expired",Ve=S.healthStatus&&S.healthStatus!=="unknown"?S.healthStatus:S.testStatus==="active"?"healthy":S.testStatus==="error"?"error":null,Ye=S.lastTested?lr(S.lastTested):null;return e.jsx("div",{"data-index":L.index,ref:U.measureElement,className:"absolute left-0 top-0 w-full pb-1",style:{transform:`translateY(${L.start}px)`},children:e.jsx("div",{className:ce("rounded-lg border bg-surface px-2 py-1.5 sm:p-3 transition-[border-color,background-color] duration-150 ease-out",ut?"border-foreground/40":oe?"border-border/70 bg-muted/30 text-muted-foreground opacity-60":"border-border hover:border-border/80 hover:bg-surface-hover/40"),children:e.jsxs("div",{className:"flex flex-nowrap items-center gap-1 sm:gap-3",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 flex-nowrap items-center gap-1.5 sm:gap-2.5",children:[e.jsx(Mi,{checked:ut,onCheckedChange:()=>{Ie(S.id)}}),e.jsxs("div",{className:"hidden shrink-0 flex-col gap-0.5 sm:flex",children:[e.jsx(ee,{label:"Move up",children:e.jsx("button",{type:"button",disabled:ae===0,onClick:()=>void ie(S.id,-1),"aria-label":"Move up",className:"rounded p-0.5 text-muted-foreground transition-colors duration-100 hover:bg-surface-hover hover:text-foreground disabled:opacity-30",children:e.jsx(ji,{className:"h-3.5 w-3.5"})})}),e.jsx(ee,{label:"Move down",children:e.jsx("button",{type:"button",disabled:ae===i.length-1,onClick:()=>void ie(S.id,1),"aria-label":"Move down",className:"rounded p-0.5 text-muted-foreground transition-colors duration-100 hover:bg-surface-hover hover:text-foreground disabled:opacity-30",children:e.jsx(Ci,{className:"h-3.5 w-3.5"})})})]}),e.jsxs("div",{className:"min-w-0 flex-1 overflow-hidden",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 sm:gap-2",children:[e.jsx("span",{className:"truncate text-[13px] font-medium leading-tight sm:text-sm",children:S.name||S.email||S.id.slice(0,8)}),Re?e.jsxs("span",{className:"inline-flex shrink-0 items-center gap-0.5 text-[10px] text-foreground/90","aria-live":"polite","aria-label":`Checking ${S.name||S.email||S.id}`,children:[e.jsx("span",{children:"Checking"}),e.jsxs("span",{className:"inline-flex w-3 justify-start","aria-hidden":"true",children:[e.jsx("span",{className:"animate-pulse",children:"."}),e.jsx("span",{className:"animate-pulse [animation-delay:150ms]",children:"."}),e.jsx("span",{className:"animate-pulse [animation-delay:300ms]",children:"."})]})]}):null,Qe&&!Qe.ok?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"max-w-[4.5rem] shrink truncate text-[10px] font-medium text-destructive sm:max-w-none",children:Qe.label}),e.jsx(ee,{label:"Copy full error",children:e.jsx("button",{type:"button",className:"hidden rounded p-0.5 text-muted-foreground hover:text-foreground sm:inline-flex","aria-label":"Copy full error",onClick:mt=>{mt.stopPropagation(),navigator.clipboard.writeText(Qe.message||"").catch(()=>{})},children:e.jsx(Hn,{className:"h-3 w-3"})})})]}):null]}),e.jsxs("div",{className:"mt-0.5 hidden flex-wrap items-center gap-x-1.5 text-[11px] text-muted-foreground sm:flex",children:[e.jsxs("span",{children:["#",ae+1]}),Ve?e.jsx(ee,{label:S.healthError||(Ve==="healthy"?"Connection is healthy":"Connection has an error"),children:e.jsx(Pe,{tone:Ve==="healthy"?"ok":"err",className:"max-w-[10rem] truncate text-[10px]",children:Ve==="healthy"?"OK":"Error"})}):null,Ye?e.jsxs("span",{children:["checked ",Ye]}):null,ke?e.jsx(ee,{label:S.lastError||"Credentials may be expired; reconnect this provider.",children:e.jsx(Pe,{tone:"warn",className:"max-w-[10rem] truncate text-[10px]",children:"Stale"})}):null,oe?e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"·"}),e.jsx("span",{children:"off"})]}):null]})]})]}),e.jsxs("div",{className:"ml-auto flex shrink-0 flex-nowrap items-center gap-0.5 sm:gap-1.5",children:[e.jsx(Ti,{active:S.isActive!==!1,disabled:z===S.id,onToggle:()=>void re(S.id),activeLabel:"",inactiveLabel:""}),e.jsx(ee,{label:Re?"Stop":"Test",children:e.jsx(E,{size:"icon-sm",variant:"outline",className:"h-7 w-7 sm:hidden","aria-label":Re?"Stop test":"Test connection",onClick:()=>Re?xe():void te(S.id),children:Re?e.jsx(Ni,{className:"h-3 w-3 fill-current"}):e.jsx(Si,{className:"h-3.5 w-3.5 fill-current"})})}),e.jsx("span",{className:"hidden sm:inline-flex [&>button]:h-7 [&>button]:text-sm",children:e.jsx(Jt,{busy:Re,onTest:()=>void te(S.id),onStop:xe})}),e.jsx(ee,{label:"Edit",children:e.jsxs(E,{size:"sm",variant:"outline",className:"h-7 w-7 px-0 sm:w-auto sm:px-3 sm:text-sm",onClick:()=>ge(S),"aria-label":"Edit connection",children:[e.jsx(gs,{className:"size-4 sm:hidden"}),e.jsx("span",{className:"hidden font-medium sm:inline",children:"Edit"})]})}),e.jsx(ee,{label:"Delete",children:e.jsxs(E,{size:"sm",variant:"outline",className:"h-7 w-7 px-0 sm:w-auto sm:px-3 sm:text-sm",onClick:()=>Ke(S.id),"aria-label":"Delete connection",children:[e.jsx(jn,{className:"size-4 sm:hidden"}),e.jsx("span",{className:"hidden font-medium sm:inline",children:"Delete"})]})})]})]})})},S.id)})})})})})]})})}function dr({selected:s,conns:n,activeConns:i,onEditCustom:a,onDeleteCustom:u,onAddConnection:c}){return e.jsxs(ks,{className:"flex shrink-0 flex-row flex-wrap items-start justify-between gap-2 border-b border-border p-3 sm:gap-3 sm:p-5",children:[e.jsxs("div",{className:"flex min-w-0 items-start gap-3",children:[e.jsx("span",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-xl bg-white p-1.5 outline outline-1 outline-white/30 outline-offset-2 sm:h-9 sm:w-9",children:e.jsx(Cs,{id:s.id,color:"var(--background)",size:24,fallbackIcon:hs(s.id)})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"truncate text-base font-semibold sm:text-lg",children:s.name}),e.jsxs("div",{className:"mt-0.5 flex flex-wrap items-center gap-1.5 text-xs text-muted-foreground sm:mt-1 sm:gap-2 sm:text-sm",children:[e.jsx("span",{className:"font-mono text-xs",children:s.alias||s.id}),n.length>0?e.jsx(Pe,{tone:"ok",children:"Active"}):e.jsx(Pe,{tone:"muted",children:"Idle"}),e.jsxs("span",{children:[n.length," connection",n.length===1?"":"s",n.filter(h=>h.healthStatus==="healthy").length>0?` · ${n.filter(h=>h.healthStatus==="healthy").length} OK`:"",n.filter(h=>h.healthStatus==="error").length>0?` · ${n.filter(h=>h.healthStatus==="error").length} error${n.filter(h=>h.healthStatus==="error").length===1?"":"s"}`:"",i.length<n.length?` · ${n.length-i.length} off`:""]}),s.isCustom&&s.baseUrl?e.jsx("span",{className:"hidden truncate text-xs sm:inline",children:s.baseUrl}):null]})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.isCustom?e.jsxs(e.Fragment,{children:[e.jsx(ee,{label:"Edit custom provider",children:e.jsxs(E,{size:"sm",variant:"outline",className:"px-2 sm:px-3","aria-label":"Edit custom provider",onClick:a,children:[e.jsx(gs,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:"Edit"})]})}),e.jsx(ee,{label:"Remove custom provider",children:e.jsxs(E,{size:"sm",variant:"destructive",className:"px-2 sm:px-3","aria-label":"Remove custom provider",onClick:u,children:[e.jsx(jn,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:"Remove"})]})})]}):null,e.jsx("div",{className:"flex flex-wrap gap-2",children:e.jsxs(E,{size:"sm",className:"px-2 sm:px-3",onClick:c,children:[e.jsx(An,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:Tn(s.authType,s.noAuth)}),e.jsx("span",{className:"sm:hidden",children:"Add"})]})})]})]})}function ur({deleteId:s,bulkDeleteIds:n,bulkDeleting:i,deleteProvider:a,connections:u,onCloseDelete:c,onDeleteConnection:h,onCloseBulkDelete:y,onDeleteSelectedConnections:C,onCloseProvider:N,onRemoveProvider:K}){const A=a?u.filter(b=>b.provider===a.id):[];return e.jsxs(e.Fragment,{children:[e.jsx(Ut,{open:!!s,onOpenChange:b=>!b&&c(),children:e.jsxs($t,{children:[e.jsxs(Qt,{children:[e.jsx(Vt,{children:"Delete connection?"}),e.jsx(wn,{children:"Removes this key / session."})]}),e.jsxs(Wt,{children:[e.jsx(E,{variant:"outline",onClick:c,children:"Cancel"}),e.jsx(E,{variant:"destructive",onClick:h,children:"Delete"})]})]})}),e.jsx(Ut,{open:!!n,onOpenChange:b=>{!b&&!i&&y()},children:e.jsxs($t,{children:[e.jsxs(Qt,{children:[e.jsxs(Vt,{children:["Delete ",(n==null?void 0:n.length)??0," selected connections?"]}),e.jsx(wn,{children:"This will remove the selected keys or sessions. This action cannot be undone."})]}),e.jsxs(Wt,{children:[e.jsx(E,{variant:"outline",disabled:i,onClick:y,children:"Cancel"}),e.jsx(E,{variant:"destructive",disabled:i,onClick:C,children:i?"Deleting…":"Delete"})]})]})}),e.jsx(Ut,{open:!!a,onOpenChange:b=>{b||N()},children:e.jsxs($t,{children:[e.jsxs(Qt,{children:[e.jsxs(Vt,{children:["Remove ",a==null?void 0:a.name,"?"]}),e.jsx(wn,{children:A.length>0?e.jsxs(e.Fragment,{children:["This provider has ",e.jsxs("strong",{children:[A.length," connection(s)"]})," that will also be deleted:",e.jsx("ul",{className:"mt-2 list-disc pl-4 text-xs",children:A.map(b=>e.jsx("li",{children:b.name||b.id},b.id))})]}):"This will remove the provider from the list."})]}),e.jsxs(Wt,{children:[e.jsx(E,{variant:"outline",onClick:N,children:"Cancel"}),e.jsx(E,{variant:"destructive",disabled:!a,onClick:()=>{a&&K(a)},children:"Remove"})]})]})})]})}async function Zn(s){const{data:n}=await Ct.get("/models/custom");return n.models??[]}async function mr(s,n){let i=0;for(const u of n)try{const c=typeof u=="string"?{id:u}:u,h=await Ns(s,c.id,c.name,c.capabilities);i+=h.added}catch{}const a=await Zn();return{added:i,total:a.length,models:a}}async function Ns(s,n,i,a){const{data:u}=await Ct.post("/models/custom",{providerAlias:s,id:n,name:i,capabilities:a}),c=await Zn();return{added:u.added===!0?1:0,total:c.length,models:c}}async function hr(s,n){const{data:i}=await Ct.delete("/models/custom",{params:{providerAlias:s,id:n}});return{success:i.success!==!1,removed:i.success!==!1}}async function fr(){const{data:s}=await Ct.get("/models/disabled");return s.disabled??{}}async function pr(s,n){await Ct.post("/models/disabled",{providerAlias:s,ids:n})}async function xr(s,n){await Ct.delete("/models/disabled",{params:{providerAlias:s,id:n}})}function gr(s,n){return s!==n}const vr=50,us=1e3;function Dr(s,n=42){let i=s.trim();if(!i)return"Failed";i=i.replace(/^\s*(?:error|err|failed?)\s*[:\-]\s*/i,""),i=i.replace(/^\s*status\s+\d{3}\s*[:\-]?\s*/i,"");try{const a=JSON.parse(i);if(a&&typeof a=="object"){const u=a,c=u.error??u.message??u.detail;if(typeof c=="string")i=c.trim();else if(c&&typeof c=="object"){const h=c;i=String(h.message??h.type??h.code??i).trim()}}}catch{}return i=i.replace(/\s+/g," ").replace(/[.。]+$/,""),i.length<=n?i:`${i.slice(0,Math.max(1,n-1)).trimEnd()}…`}function on(s){const n=s.status??null,i=(s.message||s.error||"").trim(),a=s.latencyMs!=null&&Number.isFinite(Number(s.latencyMs))?Math.round(Number(s.latencyMs)):null;if(s.ok){const h=a!=null?`OK · ${a}ms`:"OK";return{ok:!0,label:h,message:h,status:n,detail:null}}let u="";if(n!=null&&String(n).trim()!==""){const h=String(n).trim();isNaN(Number(h))||(u=h)}if(!u&&i){const h=i.match(/^(\d{3})[:\s]/);if(h)u=h[1];else{const y=i.match(/\bHTTP\s+(\d{3})\b/i);if(y)u=y[1];else if(i.startsWith("status ")){const C=i.replace(/^status\s+/,"").match(/^(\d{3})/);C&&(u=C[1])}}}const c=u?`Error ${u}`:"Error";return{ok:!1,label:c,message:i||c,status:n,detail:s.detail&&s.detail!==i?s.detail:null}}function ms(s){var n,i;if(_t.isAxiosError(s)){const a=s,u=((n=a.response)==null?void 0:n.status)??null,c=(i=a.response)==null?void 0:i.data;let h="";typeof(c==null?void 0:c.error)=="string"?h=c.error:c!=null&&c.error&&typeof c.error=="object"&&(h=c.error.message||c.error.type||c.error.code||"");const y=typeof(c==null?void 0:c.error)=="string"?c.error:"";h=(/^(?:test failed|internal server error)$/i.test(y)?c==null?void 0:c.message:y)||(c==null?void 0:c.message)||a.message||"Test failed";let N=null;try{c&&(N=JSON.stringify(c,null,2))}catch{N=null}return on({ok:!1,status:u,message:h,detail:N})}return on({ok:!1,message:Z(s,"Test failed")})}function qr(){var p,w,x,M,D;const s=Ss(),n="nr-selected-provider",[i,a]=o.useState(()=>{try{return localStorage.getItem(n)}catch{return null}});function u(t){if(gr(i,t)){vt(null),Fe([]),et({}),tt({}),te(new Set),a(t);try{t?localStorage.setItem(n,t):localStorage.removeItem(n)}catch{}}}const[c,h]=o.useState(""),[y,C]=o.useState("all"),[N,K]=o.useState(()=>{try{const t=JSON.parse(localStorage.getItem("nr-hidden-providers")||"[]");return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]}catch{return[]}}),[A,b]=o.useState(!1),[F,z]=o.useState(null),[T,G]=o.useState(null),[U,_]=o.useState(null),[Y,$]=o.useState(!1),[fe,R]=o.useState(null),[Ee,Le]=o.useState(!1),[Ie,pe]=o.useState(null),[ze,te]=o.useState(new Set),[xe,B]=o.useState(0),[O,ie]=o.useState({}),[re,ge]=o.useState(""),[Ke,L]=o.useState(!1),[S,ae]=o.useState(!1),[ut,Qe]=o.useState(()=>{try{return JSON.parse(localStorage.getItem("nr-pinned-models")||"{}")}catch{return{}}}),[Re,oe]=o.useState(()=>{try{return JSON.parse(localStorage.getItem("nr-hidden-models")||"{}")}catch{return{}}}),[ke,Ve]=o.useState("");function Ye(t,r){oe(l=>{const v={...l,[t]:Array.from(new Set([...l[t]||[],r]))};try{localStorage.setItem("nr-hidden-models",JSON.stringify(v))}catch{}return v})}function mt(t,r){r.length&&oe(l=>{const v=new Set(r.map(V=>V.trim()).filter(Boolean)),g=new Set([...v].map(V=>V.slice(V.lastIndexOf("/")+1))),f=(l[t]||[]).filter(V=>{const W=String(V),ue=W.slice(W.lastIndexOf("/")+1);return!v.has(W)&&!g.has(ue)}),j={...l};f.length?j[t]=f:delete j[t];try{localStorage.setItem("nr-hidden-models",JSON.stringify(j))}catch{}return j})}const[Xe,Nt]=o.useState(0),[me,St]=o.useState(""),[ht,At]=o.useState(null),[Ht,Tt]=o.useState(null),[Gt,ft]=o.useState(()=>new Set),[dn,Mt]=o.useState(!1),Ze=o.useRef(!1),Oe=o.useRef(new Map),Pt=4,[Yt,Et]=o.useState(null),[Lt,pt]=o.useState(null),Be=o.useRef(null),[Mn,et]=o.useState({}),[Pn,tt]=o.useState({}),[le,nt]=o.useState("connections"),xt=o.useRef(null),st=o.useRef(null),It=o.useRef(0),[je,Kt]=o.useState(""),[gt,Xt]=o.useState(""),[ye,Rt]=o.useState(1),[Zt,Fe]=o.useState([]),[We,vt]=o.useState(null);o.useEffect(()=>{const t=window.setTimeout(()=>{Xt(je.trim())},250);return()=>window.clearTimeout(t)},[je]);const De=ct({queryKey:["connections",i,ye,gt],queryFn:()=>Gs({provider:i,page:ye,pageSize:vr,search:gt||void 0}),enabled:!!i,retry:!1,refetchInterval:3e4});o.useEffect(()=>{Rt(1),vt(null),Fe([])},[i,gt]),o.useEffect(()=>{var r;const t=((r=De.data)==null?void 0:r.connections)??[];if(i){if(!t.length&&ye===1){Fe([]),vt(i);return}Fe(l=>{const v=ye===1?[]:l,g=new Set(v.map(k=>k.id));return[...v,...t.filter(k=>!g.has(k.id))].slice(0,us)}),vt(i)}},[De.data,ye,i]);const it=We===i?Zt:[],Ce=(p=De.data)==null?void 0:p.pagination,Ot=!!(Ce!=null&&Ce.hasNext&&it.length>=us);o.useEffect(()=>{const t=st.current;if(!t)return;const r=()=>{It.current=t.scrollTop};return t.addEventListener("scroll",r,{passive:!0}),()=>t.removeEventListener("scroll",r)},[]),o.useLayoutEffect(()=>{const t=st.current;t&&(t.scrollTop=It.current)},[i]),o.useEffect(()=>{const t=xt.current;if(!t||le!=="connections")return;const r=()=>{var v;const l=(v=De.data)==null?void 0:v.pagination;!(l!=null&&l.hasNext)||De.isFetching||Ot||t.scrollTop+t.clientHeight>=t.scrollHeight-240&&Rt(g=>g+1)};return t.addEventListener("scroll",r,{passive:!0}),()=>t.removeEventListener("scroll",r)},[Ot,(w=De.data)==null?void 0:w.pagination,De.isFetching,le]);const Ft=ct({queryKey:["providers-available"],queryFn:Ys,retry:!1}),de=ct({queryKey:["settings"],queryFn:Is,retry:!1}),en=ct({queryKey:["nodes"],queryFn:ni,retry:!1}),_e=ct({queryKey:["custom-models"],queryFn:()=>Zn(),enabled:!!i,staleTime:0,refetchOnMount:"always",retry:!1,placeholderData:t=>t}),Dt=ct({queryKey:["disabled-models"],queryFn:fr,retry:!1}),Ne=ct({queryKey:["available-models",Xe],queryFn:async()=>((await Ct.get("/models")).data.models??[]).map(r=>({id:Nn(r.routedModel||r.fullModel,r.provider),name:r.name||r.model,provider_alias:r.provider,provider_id:r.provider,owned_by:r.provider,caps:Vn(r.caps),thinkingLevels:Array.isArray(r.thinkingLevels)?r.thinkingLevels:void 0})),retry:!1});function P(t,r="default"){r==="success"?kt.success(t):r==="error"?kt.error(t):r==="warning"?kt.warning(t):kt(t)}const rt=o.useMemo(()=>{const t=Ft.data??[],r=new Set(t.map(g=>g.id)),l=en.data??[],v=[];for(const g of l)r.has(g.id)||v.push({id:g.id,alias:g.prefix||g.id,name:g.name||g.prefix||g.id,authType:"apikey",isCustom:!0,baseUrl:g.baseUrl,nodeType:g.type,apiType:g.apiType,icon:"sway",connected:0});return[...t,...v]},[Ft.data,en.data]),H=de.data,Je=o.useMemo(()=>{const t=new Map;return i&&t.set(i,it),t},[it,i]),be=o.useMemo(()=>{let t=[...rt];if(y==="active"?t=t.filter(r=>(r.connected||0)>0):y==="idle"&&(t=t.filter(r=>(r.connected||0)===0)),c.trim()){const r=c.toLowerCase();t=t.filter(l=>l.name.toLowerCase().includes(r)||l.id.toLowerCase().includes(r)||(l.alias||"").toLowerCase().includes(r))}return t.sort((r,l)=>{const v=N.includes(r.id)?1:0,g=N.includes(l.id)?1:0;if(v!==g)return v-g;const k=r.connected||0,f=l.connected||0;return(k>0?1:0)!=(f>0?1:0)?f-k:(r.name||r.id).localeCompare(l.name||l.id)}),t},[rt,Je,y,N,c]);function qt(t){K(r=>{const l=r.includes(t)?r.filter(v=>v!==t):[...r,t];try{localStorage.setItem("nr-hidden-providers",JSON.stringify(l))}catch{}return l})}o.useEffect(()=>{if(rt.length===0||i&&rt.some(r=>r.id===i))return;let t=null;try{t=localStorage.getItem(n)}catch{t=null}if(t&&rt.some(r=>r.id===t)){a(t);return}},[rt,Je,i]),o.useEffect(()=>{te(new Set),Kt(""),ge(""),nt("connections")},[i]),o.useEffect(()=>{const t=Es(H,i||"");St(String(t))},[i,H]);const d=be.find(t=>t.id===i)||null,Se=o.useMemo(()=>{const t=d?[...Je.get(d.id)||[]]:[];return t.sort((r,l)=>(r.priority??999)-(l.priority??999)||r.id.localeCompare(l.id)),t},[d,Je]),se=Se,we=As({count:se.length,getScrollElement:()=>xt.current,estimateSize:()=>typeof window<"u"&&window.matchMedia("(max-width: 639px)").matches?48:72,overscan:10,getItemKey:t=>{var r;return((r=se[t])==null?void 0:r.id)??t},enabled:le==="connections"});o.useEffect(()=>{if(le!=="connections")return;const t=requestAnimationFrame(()=>{we.measure()});return()=>cancelAnimationFrame(t)},[le,se.length,i,we]),o.useEffect(()=>{if(typeof window>"u")return;const t=window.matchMedia("(max-width: 639px)"),r=()=>{we.measure()};return t.addEventListener("change",r),()=>t.removeEventListener("change",r)},[we]),o.useEffect(()=>{const t=xt.current;if(!t||typeof ResizeObserver>"u")return;const r=new ResizeObserver(()=>{we.measure()});return r.observe(t),()=>r.disconnect()},[we,le,i]);const He=o.useMemo(()=>Se.filter(t=>t.isActive!==!1),[Se]),he=[...ze][0]||((x=He[0])==null?void 0:x.id)||((M=se[0])==null?void 0:M.id),Ae=_s(d),J=ct({queryKey:["connection-models",d==null?void 0:d.id,he,Xe],queryFn:async()=>{const t=await is(he);return Un(t.models,d==null?void 0:d.id)},enabled:!!(Ae&&he),retry:!1}),yt=d?Ls(H,d.id):"fill-first",ve={"qd/ultimate":"Ultimate","qd/auto":"Auto","qd/performance":"Performance","qd/efficient":"Efficient","qd/lite":"Lite","qd/qmodel_preview":"Qwen3.8-Max-Preview","qd/qmodel_latest":"Qwen3.7-Max","qd/qmodel":"Qwen3.7-Plus","qd/kmodel_latest":"Kimi-K3","qd/kmodel":"Kimi-K2.7-Code","qd/gm51model":"GLM-5.2","qd/dmodel":"DeepSeek-V4-Pro","qd/dfmodel":"DeepSeek-V4-Flash","qd/mmodel":"MiniMax-M3"},at=o.useMemo(()=>{if(!d)return[];const t=[],r=d.id,l=new Set([r,d.alias||""].filter(Boolean).map(g=>g.toLowerCase())),v=[..._e.data??[],...(O[r]??[]).map(g=>({providerAlias:r,id:g.id,name:g.name,capabilities:g.caps,thinkingLevels:g.thinkingLevels}))];for(const g of v)l.has(g.providerAlias.toLowerCase())&&t.push({id:Nn(g.id,g.providerAlias),name:g.name||g.id,caps:Vn(g.capabilities),thinkingLevels:Array.isArray(g.thinkingLevels)?g.thinkingLevels:void 0});if(Ae)t.push(...J.data??[]),!he&&(r==="codebuddy-cn"||r==="codebuddy-intl")&&t.push(...Un(d.models,r));else{const g=new Set([r,d.alias||""].map(k=>k.trim().toLowerCase()).filter(Boolean));for(const k of Ne.data??[])[k.provider_alias,k.provider_id,k.owned_by].filter(j=>!!j).map(j=>j.trim().toLowerCase()).some(j=>g.has(j))&&t.push(k)}return Xi(t,r)},[J.data,xe,_e.data,O,Ne.data,d,he,Ae]),tn=Ae?_e.isLoading||_e.isFetching||J.isLoading||J.isFetching:_e.isLoading||_e.isFetching||Ne.isLoading||Ne.isFetching,un=Ae&&!!J.error,Te=d?rr(d.id,at.map(t=>t.thinkingLevels),d.thinkingConfig):null,Ge=d?(D=H==null?void 0:H.providerThinking)==null?void 0:D[d.id]:void 0,mn=d?ar(d.id,d.thinkingConfig):"auto",ot=d?Ge&&(Te!=null&&Te.includes(Ge))?Ge:Te!=null&&Te.includes(mn)?mn:(Te==null?void 0:Te[0])||"auto":"auto",En=o.useMemo(()=>{const t=new Map(Object.entries(ve));for(const r of at)r.name&&t.set(r.id,r.name);return t},[at]),zt=d?ut[d.id]||[]:[],hn=o.useMemo(()=>{const t=ke.trim().toLowerCase(),r=new Set(d?Re[d.id]||[]:[]);let l=at.filter(f=>!r.has(f.id));if(t&&(l=l.filter(f=>f.id.toLowerCase().includes(t)||(f.name||"").toLowerCase().includes(t))),!zt.length)return[...l].sort((f,j)=>f.id.localeCompare(j.id));const v=new Set(zt),g=l.filter(f=>v.has(f.id)),k=l.filter(f=>!v.has(f.id)).sort((f,j)=>f.id.localeCompare(j.id));return[...g,...k]},[Re,at,ke,zt,d]),fn=o.useMemo(()=>{var r,l;if(!d)return new Set;const t=[...((r=Dt.data)==null?void 0:r[d.id])??[],...d.alias?((l=Dt.data)==null?void 0:l[d.alias])??[]:[]];return new Set(t)},[Dt.data,d]);async function Q(t){if(d)try{fn.has(t)?(await xr(d.id,t),P(`Enabled ${t.split("/").pop()}`)):(await pr(d.id,[t]),P(`Disabled ${t.split("/").pop()}`)),await s.invalidateQueries({queryKey:["disabled-models"]})}catch(r){P(Z(r,"Failed to update model availability"),"error")}}function Ue(t){d&&Qe(r=>{const l=r[d.id]||[],v=l.includes(t)?l.filter(k=>k!==t):[...l,t],g={...r,[d.id]:v};try{localStorage.setItem("nr-pinned-models",JSON.stringify(g))}catch{}return g})}function $e(){var t;(t=Be.current)==null||t.abort();for(const r of Oe.current.values())r.abort();Oe.current.clear(),Be.current=null,Ze.current=!1,Mt(!1),Tt(null),ft(new Set),pt(null),P("Tests stopped")}function lt(t){const r=Oe.current.get(t);r&&(r.abort(),P("Model test stopped"))}async function nn(t,r){Tt(t);try{const l=await ps(t,void 0,{signal:r}),v=l.valid===!0,g=l.testedAt||new Date().toISOString(),k={testStatus:v?"active":"error",lastTested:g,lastError:v?l.error||null:l.error||"Connection test failed",healthStatus:v?"healthy":"error",healthError:v?l.error||null:l.error||"Connection test failed",healthLatencyMs:l.latencyMs??0};return et(f=>({...f,[t]:on({ok:v,message:l.error||(v?"Valid":"Failed"),latencyMs:l.latencyMs})})),Fe(f=>f.map(j=>j.id===t?{...j,...k}:j)),s.setQueriesData({queryKey:["connections"]},f=>f&&{...f,connections:(f.connections||[]).map(j=>j.id===t?{...j,...k}:j)}),v}catch(l){if(_t.isCancel(l)||(l==null?void 0:l.code)==="ERR_CANCELED")return!1;const v=ms(l),g=new Date().toISOString();return et(k=>({...k,[t]:v})),Fe(k=>k.map(f=>f.id===t?{...f,testStatus:"error",lastTested:g,lastError:v.message,healthStatus:"error",healthError:v.message,healthLatencyMs:0}:f)),!1}finally{Tt(l=>l===t?null:l)}}async function pn(t){if(!t.length)return P("Nothing to test");const r=new AbortController;Be.current=r,pt("conn");let l=0;const v=4;for(let g=0;g<t.length&&!r.signal.aborted;g+=v){const k=t.slice(g,g+v),f=await Promise.all(k.map(j=>nn(j,r.signal)));l+=f.filter(Boolean).length}r.signal.aborted||P(`Connections: ${l}/${t.length} passed`),pt(null)}async function xn(t,r,l){if(!r)return P("Add a connection first"),!1;if(!l){if(Ze.current||Lt==="conn"||Oe.current.has(t))return!1;if(Oe.current.size>=Pt)return P(`Up to ${Pt} model tests can run at once`),!1}const v=l?null:new AbortController,g=l||v.signal;v&&Oe.current.set(t,v),ft(k=>{const f=new Set(k);return f.add(t),f});try{const k=await Us(r,{model:t,signal:g});if(!Array.isArray(k.results)){const W=k.message||k.error||"No model test results returned";return tt(ue=>({...ue,[t]:on({ok:!1,message:W})})),!1}const f=t.includes("/")?t.slice(t.lastIndexOf("/")+1):t,j=(k.results??[]).find(W=>{const ue=String(W.modelId||"");return ue===f||ue===t||t.endsWith(`/${ue}`)||ue.endsWith(`/${f}`)}),V=!!(j!=null&&j.ok);return tt(W=>({...W,[t]:on({ok:V,status:j==null?void 0:j.status,message:((j==null?void 0:j.error)||"").trim()||(V?"OK":"Failed"),latencyMs:j==null?void 0:j.latencyMs})})),V}catch(k){return _t.isCancel(k)||(k==null?void 0:k.code)==="ERR_CANCELED"||tt(f=>({...f,[t]:ms(k)})),!1}finally{ft(k=>{const f=new Set(k);return f.delete(t),f}),v&&Oe.current.delete(t)}}async function gn(){var t,r;if(d){if(d.id==="codebuddy-cn"||d.id==="codebuddy-intl"){P("CodeBuddy uses the static registry — add new models manually","default");return}ae(!0);try{const l={provider:d.id},v=new Set([d.id,d.alias].filter(Boolean).map(q=>q.trim().toLowerCase())),g=(en.data??[]).find(q=>q.id===d.id),k=(r=(t=Se.find(q=>{var I;return v.has(String(q.provider||"").trim().toLowerCase())&&typeof((I=q.providerSpecificData)==null?void 0:I.baseUrl)=="string"}))==null?void 0:t.providerSpecificData)==null?void 0:r.baseUrl,f=d.baseUrl||(g==null?void 0:g.baseUrl)||(typeof k=="string"?k:void 0);f&&(l.baseUrl=f);const j=q=>q.flatMap(I=>{if(!I||typeof I!="object")return[];const X=I,Me=typeof X.id=="string"?X.id:typeof X.name=="string"?X.name:"";if(!Me.trim())return[];const qe=X.capabilities??X.caps;return[{id:Me.trim(),...typeof X.name=="string"&&X.name.trim()?{name:X.name.trim()}:{},...qe&&typeof qe=="object"?{capabilities:qe}:{}}]}),V=async()=>{const q=await is(he,!0),I=String(q.provider||"").trim().toLowerCase();if(I&&!v.has(I))throw new Error(`Model catalog returned ${q.provider}, expected ${d.name}`);return{ok:!0,success:!0,models:j(q.models??[])}};let W;if(he)try{W=await V()}catch(q){if(!l.baseUrl||Ae||d.id==="clinepass"||d.id==="cline-pass")throw q;W=await rs(l)}else W=await rs(l);if(!W.ok&&!W.success){P(W.message||W.error||"Import failed","error");return}const ue=W.models??[];if(!ue.length){P(W.message||"No models returned","warning");return}const bn=ue.map(q=>typeof q=="string"?q:q.id);mt(d.id,bn);const{added:wt,models:sn}=await mr(d.id,ue),rn=sn.filter(q=>v.has(String(q.providerAlias||"").trim().toLowerCase())),Bt=rn.length;s.setQueryData(["custom-models"],sn),ie(q=>({...q,[d.id]:Un(rn,d.id)})),B(q=>q+1),Nt(q=>q+1),await s.invalidateQueries({queryKey:["custom-models"]}),await s.invalidateQueries({queryKey:["connection-models"]}),await s.invalidateQueries({queryKey:["available-models"]}),await s.invalidateQueries({queryKey:["sway-chat","models"]}),await s.refetchQueries({queryKey:["custom-models"],type:"active"}),await s.refetchQueries({queryKey:["connection-models"],type:"active"}),P(wt>0?`Imported ${wt} new ${wt===1?"model":"models"} · Total ${Bt} ${Bt===1?"Model":"Models"}`:`No new models · Total ${Bt} Models`,wt>0?"success":"default")}catch(l){P(Z(l,"Import failed"),"error")}finally{ae(!1)}}}async function Ln(){const t=re.trim();if(!(!d||!t||Ke)){L(!0);try{const r=await Ns(d.id,t);mt(d.id,[t]),s.setQueryData(["custom-models"],r.models),B(l=>l+1),Nt(l=>l+1),await s.invalidateQueries({queryKey:["custom-models"]}),await s.invalidateQueries({queryKey:["available-models"]}),await s.invalidateQueries({queryKey:["sway-chat","models"]}),ge(""),kt.success(`Added ${t}`)}catch(r){kt.error(Z(r,"Failed to add model"))}finally{L(!1)}}}async function In(){if(!he)return P("Add a connection first");if(Ze.current)return;if(Oe.current.size>0)return P("Stop individual model tests before running Test all");const t=hn.map(g=>g.id);if(!t.length)return P("No models");Ze.current=!0,Mt(!0),pt("model");const r=new AbortController;Be.current=r;const l=new Array(t.length);let v=0;try{const g=Math.min(Pt,t.length),k=async()=>{for(;;){const f=v++;if(f>=t.length||r.signal.aborted)return;l[f]=await xn(t[f],he,r.signal)}};if(await Promise.all(Array.from({length:g},()=>k())),!r.signal.aborted){const f=l.filter(V=>V!==void 0).length,j=l.filter(Boolean).length;P(`Models: ${j}/${f} passed`)}}catch(g){!_t.isCancel(g)&&(g==null?void 0:g.code)!=="ERR_CANCELED"&&P(Z(g,"Model test failed"),"error")}finally{ft(new Set),pt(null),Be.current===r&&(Be.current=null),Ze.current=!1,Mt(!1)}}const bt=es({mutationFn:async t=>{if(!d)return;const r=(H==null?void 0:H.providerStrategies)||{},l={...r[d.id]||{}};return t.strategy&&(l.fallbackStrategy=t.strategy),t.sticky&&(l.stickyRoundRobinLimit=t.sticky),ts({providerStrategies:{...r,[d.id]:l}})},onSuccess:()=>{s.invalidateQueries({queryKey:["settings"]})}}),vn=es({mutationFn:async t=>{if(d)return ts({providerThinking:{...(H==null?void 0:H.providerThinking)||{},[d.id]:t}})},onSuccess:()=>{s.invalidateQueries({queryKey:["settings"]})}});async function Kn(t){const r=it.find(l=>l.id===t);if(!(!r||Yt)){Et(t);try{const l=await $s(t,r.isActive!==!1);Fe(v=>v.map(g=>g.id===l.id?{...g,...l}:g)),s.invalidateQueries({queryKey:["connections"]}),s.invalidateQueries({queryKey:["providers-available"]}),P(`${l.name||r.name||"Connection"} ${l.isActive===!1?"disabled":"enabled"}`,"success")}catch(l){P(Z(l,"Failed to update connection"),"error")}finally{Et(null)}}}async function Rn(t,r){const l=se.findIndex(V=>V.id===t);if(l<0)return;const v=l+r;if(v<0||v>=se.length)return;const g=se[l],k=se[v],f=g.priority??(l+1)*10,j=k.priority??(v+1)*10;await Promise.all([zn(g.id,{priority:j}),zn(k.id,{priority:f})]),s.invalidateQueries({queryKey:["connections"]})}async function On(t){try{await Bn(t),s.invalidateQueries({queryKey:["connections"]}),s.invalidateQueries({queryKey:["providers-available"]}),G(null),P("Connection deleted","success")}catch(r){P(Z(r,"Failed to delete connection"),"error")}}async function Fn(){if(!(U!=null&&U.length)||Y)return;const t=U;$(!0);const r=[];try{for(const v of t)try{await Bn(v)}catch{r.push(v)}s.invalidateQueries({queryKey:["connections"]}),s.invalidateQueries({queryKey:["providers-available"]});const l=t.length-r.length;l===t.length?(te(new Set),_(null),P(`${l} connection${l===1?"":"s"} deleted`,"success")):l>0?(te(new Set(r)),_(null),P(`Deleted ${l} of ${t.length} connections`,"warning")):P("Could not delete the selected connections","error")}finally{$(!1)}}async function Dn(t){var v,g,k,f,j,V,W,ue,bn,wt,sn,rn,Bt,q;if(!d)return;if(t.alreadySaved){s.invalidateQueries({queryKey:["connections"]}),s.invalidateQueries({queryKey:["providers-available"]}),b(!1),P("Connection added");return}const r=t.proxyPoolId&&t.proxyPoolId!=="pool_none"?t.proxyPoolId:null;if((v=t.codeBuddyTokens)!=null&&v.length){if(d.id!=="codebuddy-cn"&&d.id!=="codebuddy-intl")throw new Error("Token batches are only supported for CodeBuddy");let I=0,X=0;for(const Me of t.codeBuddyTokens)try{await an({provider:d.id,credentialToken:Me.credentialToken,accessToken:Me.accessToken,refreshToken:Me.refreshToken,name:Me.name,autoName:Me.autoName,proxyPoolId:null}),I+=1}catch(qe){if(_t.isAxiosError(qe)&&((g=qe.response)==null?void 0:g.status)===409){X+=1;continue}throw qe}s.invalidateQueries({queryKey:["connections"]}),s.invalidateQueries({queryKey:["providers-available"]}),b(!1),P(X>0?`Added ${I} connections, skipped ${X} duplicates`:`Added ${I} connections`,X>0?"warning":"success");return}if((k=t.bulkKeys)!=null&&k.length){let I=0,X=0;for(const Me of t.bulkKeys)try{await an({provider:d.id,apiKey:Me.apiKey,name:Me.name,autoName:Me.autoName,proxyPoolId:r}),I+=1}catch(qe){if(_t.isAxiosError(qe)&&((f=qe.response)==null?void 0:f.status)===409){X+=1;continue}throw qe}s.invalidateQueries({queryKey:["connections"]}),s.invalidateQueries({queryKey:["providers-available"]}),b(!1),P(X>0?`Added ${I} connections, skipped ${X} duplicates`:`Added ${I} connections`,X>0?"warning":"success");return}const l=t.authFlow??kn(d.id,d.authType,d.noAuth);if(d.id==="kiro"&&t.kiroAuthMode==="api-key"){if(!((j=t.apiKey)!=null&&j.trim()))throw new Error("API key required");const I=await Qs({apiKey:t.apiKey.trim(),region:t.kiroRegion,name:t.name,autoName:t.autoName});if(!I.success)throw new Error(I.error||"Kiro API key validation failed")}else if(d.id==="kiro"&&t.kiroAuthMode==="import-token"){if(!((V=t.kiroRefreshToken)!=null&&V.trim()))throw new Error("Refresh token required");const I=await Vs({refreshToken:t.kiroRefreshToken.trim(),clientId:((W=t.kiroClientId)==null?void 0:W.trim())||void 0,clientSecret:((ue=t.kiroClientSecret)==null?void 0:ue.trim())||void 0,region:t.kiroRegion,profileArn:((bn=t.kiroProfileArn)==null?void 0:bn.trim())||void 0,name:t.name,autoName:t.autoName});if(!I.success)throw new Error(I.error||"Kiro token import failed")}else if(d.id==="kiro"&&t.kiroAuthMode==="cli-proxy"){if(!((wt=t.kiroCliProxyJson)!=null&&wt.trim()))throw new Error("CLIProxyAPI JSON required");let I;try{I=JSON.parse(t.kiroCliProxyJson)}catch{throw new Error("CLIProxyAPI JSON is invalid")}if(!I||typeof I!="object"||Array.isArray(I))throw new Error("CLIProxyAPI JSON must be an object");const X=await Ws({cliProxyAuth:I,name:t.name,autoName:t.autoName});if(!X.success)throw new Error(X.error||"CLIProxyAPI import failed")}else if(l==="import"&&(d.id==="codebuddy-cn"||d.id==="codebuddy-intl")){if(!((sn=t.codeBuddyToken)!=null&&sn.trim()))throw new Error("An access token or refresh token is required.");await an({provider:d.id,credentialToken:t.codeBuddyToken.trim(),name:t.name,autoName:t.autoName,proxyPoolId:null})}else if(l==="import"){if(!((rn=t.importToken)!=null&&rn.trim()))throw new Error("Access token required");const I=await Js(d.id,{accessToken:t.importToken.trim(),displayName:t.name,machineId:t.machineId});if(!I.success)throw new Error(I.error||"Token import failed")}else if(l==="oauth"){if(!((Bt=t.oauthCode)!=null&&Bt.trim()))throw new Error("Paste the OAuth code from the browser callback");await Hs(d.id,{code:t.oauthCode.trim(),state:t.oauthState,codeVerifier:t.oauthCodeVerifier,redirectUri:t.oauthRedirectUri,displayName:t.name})}else if(l==="device"){if(!t.deviceCode)throw new Error("Device code not started — wait for user code");const I=await fs(d.id,{deviceCode:t.deviceCode,codeVerifier:t.deviceCodeVerifier,displayName:t.name});if(I.pending)throw new Error("Still waiting for device authorization — keep polling");if(!I.success)throw new Error(I.error||"Device authorization failed")}else if(l==="local")await an({provider:d.id,name:t.name,autoName:t.autoName,proxyPoolId:r});else{if(!((q=t.apiKey)!=null&&q.trim()))throw new Error("API key required");await an({provider:d.id,apiKey:t.apiKey,name:t.name,autoName:t.autoName,proxyPoolId:r})}s.invalidateQueries({queryKey:["connections"]}),s.invalidateQueries({queryKey:["providers-available"]}),b(!1),P("Connection added")}function qn(t){const r=Se.filter(l=>l.provider===t.id);(async()=>{for(const l of r)try{await Bn(l.id)}catch{}ti(t.id).then(()=>{s.invalidateQueries({queryKey:["nodes"]}),s.invalidateQueries({queryKey:["providers-available"]}),s.invalidateQueries({queryKey:["connections"]}),P("Provider removed")})})(),R(null)}const yn=Ft.isLoading,m=d?d.isCustom?"apikey":kn(d.id,d.authType,d.noAuth):null;return e.jsxs("div",{className:ce("flex h-full w-full flex-col gap-1.5 overflow-hidden sm:gap-3 lg:gap-4"),children:[e.jsx(Ts,{className:"mb-0 sm:mb-0 shrink-0",title:"Providers",actions:e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.jsxs(E,{size:"sm",onClick:()=>Le(!0),children:[e.jsx(An,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:"Custom provider"}),e.jsx("span",{className:"sm:hidden",children:"Custom"})]})})}),e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-2 overflow-hidden sm:gap-3 lg:flex-row lg:gap-4",children:[e.jsx(Ji,{byProvider:Je,filter:y,hiddenProviders:N,loading:yn,query:c,providerListRef:st,selectedId:i,sorted:be,onFilterChange:C,onQueryChange:h,onSelectProvider:u,onToggleProviderHidden:qt}),e.jsx(ws,{className:"flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden",children:d?e.jsxs(e.Fragment,{children:[e.jsx(dr,{selected:d,conns:se,activeConns:He,onEditCustom:()=>pe(d),onDeleteCustom:()=>R(d),onAddConnection:()=>b(!0)}),e.jsx(js,{className:"flex min-h-0 flex-1 flex-col overflow-hidden p-0",children:e.jsxs(vs,{value:le,onValueChange:nt,defaultValue:"connections",className:"flex min-h-0 h-full flex-1 flex-col overflow-hidden",children:[e.jsx("div",{className:"shrink-0 border-b border-border px-2 py-2 sm:px-5 sm:py-3",children:e.jsxs(ys,{children:[e.jsx(Cn,{value:"connections",children:"Connection"}),e.jsx(Cn,{value:"models",children:"Models"})]})}),e.jsx(cr,{selected:d,connsAll:Se,conns:se,strategy:yt,strategyPending:bt.isPending,stickyDraft:me,thinkingLevels:Te,thinkingValue:ot,thinkingPending:vn.isPending,selectedKeys:ze,connectionsCapped:Ot,totalConnections:(Ce==null?void 0:Ce.totalItems)??Se.length,batchKind:Lt,testingConnId:Ht,togglingConnId:Yt,connQuery:je,connListRef:xt,connVirtualizer:we,connResults:Mn,onStrategyChange:t=>bt.mutate({strategy:t}),onStickyDraftChange:St,onSaveSticky:()=>{const t=Math.max(1,parseInt(me,10)||1);bt.mutate({sticky:t}),St(String(t))},onThinkingChange:t=>vn.mutate(t),onRequestBulkDelete:()=>_([...ze]),onClearSelection:()=>te(new Set),onToggleSelection:t=>{te(r=>{const l=new Set(r);return l.has(t)?l.delete(t):l.add(t),l})},onSelectAll:()=>te(new Set(se.map(t=>t.id))),onTestConnections:t=>pn(t),onTestConnection:t=>{nn(t)},onStopTests:$e,onConnQueryChange:Kt,onOpenAddConnection:()=>b(!0),onMovePriority:(t,r)=>Rn(t,r),onToggleConnection:t=>Kn(t),onEditConnection:z,onDeleteConnection:G}),e.jsx(Zi,{selected:d,visibleModels:hn,models:at,modelNames:En,modelsLoading:tn,modelsUnavailable:un,importingModels:S,testConnId:he,batchKind:Lt,modelTestLock:dn,testingModels:Gt,modelQuery:ke,newModel:re,addingModel:Ke,modelResults:Pn,pinnedFor:zt,copied:ht,onImportModels:()=>void gn(),onTestAllModels:()=>void In(),onStopTests:$e,onStopModel:lt,onModelQueryChange:Ve,onNewModelChange:ge,onAddModel:()=>void Ln(),onTogglePin:Ue,onCopyModelId:async t=>{await navigator.clipboard.writeText(t),At(t),window.setTimeout(()=>At(null),1e3)},onTestModel:(t,r)=>void xn(t,r),onRemoveModel:async t=>{let r=!1;try{const l=await hr(d.id,t);r=(l==null?void 0:l.removed)===!0}catch{}finally{Ye(d.id,t),B(l=>l+1),Nt(l=>l+1),s.invalidateQueries({queryKey:["sway-chat","models"]})}kt(`${r?"Removed":"Hidden"} ${t.split("/").pop()}`)},disabledModelIds:fn,onToggleDisabled:Q})]})})]}):e.jsx("div",{className:"flex flex-1 items-center justify-center p-6 text-sm text-muted-foreground",children:"Select a provider"})})]}),e.jsx(Vi,{open:A,provider:d,flow:m,onOpenChange:b,onSubmit:async t=>{try{await Dn(t)}catch(r){throw P(Z(r,"Add failed"),"error"),r}}}),e.jsx(Wi,{conn:F,onOpenChange:t=>!t&&z(null),onSave:async(t,r)=>{F&&(await zn(F.id,{name:t,...r.trim()?{apiKey:r.trim()}:{}}),s.invalidateQueries({queryKey:["connections"]}),z(null),P("Updated"))}}),e.jsx(ur,{deleteId:T,bulkDeleteIds:U,bulkDeleting:Y,deleteProvider:fe,connections:Se,onCloseDelete:()=>G(null),onDeleteConnection:()=>T?On(T):void 0,onCloseBulkDelete:()=>_(null),onDeleteSelectedConnections:Fn,onCloseProvider:()=>R(null),onRemoveProvider:qn}),e.jsx(ls,{open:Ee,onOpenChange:Le,onCreate:async t=>{const r=await Zs(t);s.invalidateQueries({queryKey:["nodes"]}),s.invalidateQueries({queryKey:["providers-available"]}),Le(!1),u(r.id),P("Custom provider created")}}),e.jsx(ls,{open:!!Ie,onOpenChange:t=>{t||pe(null)},initial:Ie,submitLabel:"Save",onCreate:async t=>{if(!Ie)return;const r=await ei(Ie.id,t);s.invalidateQueries({queryKey:["nodes"]}),s.invalidateQueries({queryKey:["providers-available"]}),s.invalidateQueries({queryKey:["connections"]}),pe(null),u(r.id),P("Custom provider updated")}})]})}export{Dr as compactErrorReason,qr as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as x,j as e}from"./react-vendor-xnYrwzsL.js";import{A as f,a as u,b as h,c as j}from"./accordion-DOOPDDgt.js";import{b as v,c as t,p as b}from"./index-B6j-9zHy.js";import{a3 as N}from"./icons-vendor-CUx7SB5V.js";function w({provider:o,className:a}){const s=v(o),[n,i]=x.useState(!1);return!n&&s?e.jsx("img",{"data-slot":"provider-model-icon",src:s,alt:"",width:20,height:20,className:t("shrink-0 rounded-[4px] object-contain",a),onError:()=>i(!0)}):e.jsx(N,{"aria-hidden":"true","data-slot":"provider-model-icon",className:t("shrink-0 text-muted-foreground",a)})}function k({groups:o,query:a="",empty:s,renderItem:n,className:i}){if(o.length===0)return s??null;const d=a.trim().toLowerCase(),c=!!d,m=o.map(r=>r.provider).join("|"),p=c?o.map(r=>r.provider):[o[0].provider];return e.jsx(f,{multiple:!0,defaultValue:p,className:t("w-full",i),children:o.map(r=>e.jsxs(u,{value:r.provider,className:"border-border/70 px-1 last:border-b-0",children:[e.jsx(h,{className:t("w-fit flex-none justify-start gap-1.5 py-2 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground","hover:text-foreground sm:py-2.5"),children:e.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[e.jsx(w,{provider:r.provider,className:"size-4"}),e.jsx("span",{className:"truncate",children:b(r.provider)}),e.jsx("span",{className:"rounded-full border border-border/70 px-1.5 py-0.5 text-[9px] font-normal normal-case tracking-normal text-muted-foreground/80",children:r.items.length})]})}),e.jsx(j,{className:"min-w-0 pb-1",children:e.jsx("ul",{className:"space-y-0.5",children:r.items.map(l=>e.jsx("li",{children:n(l,r.provider)},l.id))})})]},r.provider))},`${c?`search:${d}`:"browse"}:${m}`)}export{k as P,w as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as n,j as e}from"./react-vendor-xnYrwzsL.js";import{u as rs,a as me}from"./query-vendor-DVevaSVS.js";import{H as ns}from"./Header-C_9Su9BF.js";import{F as ls}from"./flip-button-BGgkjtl0.js";import{R as d}from"./ripple-button-l8aMiVVG.js";import{S as D}from"./StatusBadge-1nAOyHU2.js";import{C as xe}from"./checkbox-7SZBrmbN.js";import{I as v,e as A,D as H,m as V,n as G,o as X,s as ue,F as pe,q as he,g as w,p as os,t as fe}from"./index-B6j-9zHy.js";import{F as is,c as cs}from"./frame-cUiti6Lq.js";import{S as Me}from"./segmented-CqmEnQjZ.js";import{S as ds}from"./skeleton-7uJDiIXe.js";import{T as ms,a as xs,b as Qe,c as z,d as us,e as I}from"./table-D0M60Tu1.js";import{h as ps,i as hs,j as Le,t as fs,k as ys,a as js,l as gs}from"./admin-extras-api-CCdu5TFM.js";import{i as vs,z as bs}from"./connections-api-_N54UD3S.js";import{p as Ns}from"./live-mode-CHShLY4E.js";import{p as Ke,ac as Re,q as Cs,L as ye,aq as ws,ar as Ss,h as ks,af as Ps,a as Ts,ag as Ds}from"./icons-vendor-CUx7SB5V.js";import"./ui-vendor-BuM9f2NY.js";import"./motion-vendor-g5fpGzmJ.js";const Be=100,He=500;function Ve({pool:r,testing:x,onToggle:S,onTest:f,onManage:u,onEdit:b,onDelete:p}){return e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center justify-end gap-1.5",children:[e.jsx(ls,{active:r.isActive!==!1,onToggle:S,activeLabel:"",inactiveLabel:""}),e.jsx(A,{label:x?"Testing…":"Test",children:e.jsxs(d,{size:"sm",variant:"outline",disabled:x,onClick:f,"aria-label":x?"Testing proxy pool":"Test proxy pool",className:"h-7 w-7 px-0 sm:w-auto sm:px-3 sm:text-sm",children:[x?e.jsx(ye,{className:"size-4 animate-spin","aria-hidden":"true"}):e.jsx(ws,{className:"size-4 fill-current sm:hidden","aria-hidden":"true"}),e.jsx("span",{className:"hidden font-medium sm:inline",children:x?"Testing…":"Test"})]})}),e.jsx(A,{label:"Manage",children:e.jsxs(d,{size:"sm",variant:"outline",onClick:u,"aria-label":"Manage connections",className:"h-7 w-7 px-0 sm:w-auto sm:px-3 sm:text-sm",children:[e.jsx(Ss,{className:"size-4 sm:hidden","aria-hidden":"true"}),e.jsx("span",{className:"hidden font-medium sm:inline",children:"Manage"})]})}),e.jsx(A,{label:"Edit",children:e.jsxs(d,{size:"sm",variant:"outline",onClick:b,"aria-label":"Edit proxy pool",className:"h-7 w-7 px-0 sm:w-auto sm:px-3 sm:text-sm",children:[e.jsx(ks,{className:"size-4 sm:hidden","aria-hidden":"true"}),e.jsx("span",{className:"hidden font-medium sm:inline",children:"Edit"})]})}),e.jsx(A,{label:"Delete",children:e.jsxs(d,{size:"sm",variant:"destructive",onClick:p,"aria-label":"Delete proxy pool",className:"h-7 w-7 px-0 sm:w-auto sm:px-3 sm:text-sm",children:[e.jsx(Ps,{className:"size-4 sm:hidden","aria-hidden":"true"}),e.jsx("span",{className:"hidden font-medium sm:inline",children:"Delete"})]})})]})}function zs({progress:r}){const x=r.error?"Failed":r.completed?"Ready":`Step ${r.current+1} of ${r.steps.length}`;return e.jsxs("div",{className:"rounded-lg border border-border/70 bg-muted/10 p-3",role:"status","aria-live":"polite",children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-xs font-medium",children:"Deployment progress"}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:x})]}),e.jsx("ol",{className:"space-y-2.5",children:r.steps.map((S,f)=>{const u=r.completed||f<r.current,b=!!r.error&&f===r.current,p=!r.completed&&!r.error&&f===r.current,h=r.completed||f<r.current;return e.jsxs("li",{className:"relative flex min-h-5 items-start gap-2.5",children:[f<r.steps.length-1?e.jsx("span",{className:`absolute left-[7px] top-5 h-[calc(100%-4px)] w-px ${h?"bg-primary/70":"bg-border"}`,"aria-hidden":"true"}):null,e.jsx("span",{className:`relative z-10 flex size-4 shrink-0 items-center justify-center rounded-full border bg-background ${b?"border-destructive text-destructive":u?"border-primary bg-primary text-primary-foreground":p?"border-primary text-primary":"border-border text-muted-foreground"}`,children:b?e.jsx(Ts,{className:"size-3","aria-hidden":"true"}):u?e.jsx(Ds,{className:"size-3","aria-hidden":"true"}):p?e.jsx(ye,{className:"size-3 animate-spin","aria-hidden":"true"}):e.jsx("span",{className:"size-1.5 rounded-full bg-current","aria-hidden":"true"})}),e.jsx("span",{className:`pt-px text-xs ${b?"text-destructive":p?"font-medium text-foreground":u?"text-foreground":"text-muted-foreground"}`,children:S})]},S)})}),r.error?e.jsx("p",{className:"mt-3 text-xs text-destructive",children:r.error}):null]})}function Xs(){var $e,Fe;const r=rs(),[x,S]=n.useState(""),[f,u]=n.useState(!1),[b,p]=n.useState(!1),[h,je]=n.useState("vercel"),[Y,ge]=n.useState(""),[_,ve]=n.useState(""),[W,be]=n.useState(""),[k,Ne]=n.useState(!1),[Ce,q]=n.useState(null),[P,M]=n.useState(null),[Z,E]=n.useState(null),[we,Se]=n.useState(null),[N,T]=n.useState(!1),[m,ke]=n.useState(null),[y,O]=n.useState(new Set),[J,ee]=n.useState(""),[Pe,se]=n.useState(""),[Q,Te]=n.useState(!1);n.useEffect(()=>{const s=window.setTimeout(()=>{se(J.trim())},250);return()=>window.clearTimeout(s)},[J]),n.useEffect(()=>{if(!k)return;const s=window.setInterval(()=>{q(t=>{if(!t||t.completed||t.error)return t;const a=Math.max(0,t.steps.length-2);return t.current>=a?t:{...t,current:t.current+1}})},2500);return()=>window.clearInterval(s)},[k]);const[L,te]=n.useState(""),[K,ae]=n.useState(""),[re,ne]=n.useState(""),[le,oe]=n.useState("http"),[ie,ce]=n.useState(!1),De=me({queryKey:["proxy-pools"],queryFn:js,enabled:Ns(),retry:!1}),Ge=me({queryKey:["proxy-pool-provider-nodes"],queryFn:gs,enabled:!!m,retry:!1}),U=De.data??[],Xe=De.isLoading,j=me({queryKey:["proxy-pool-connections",Pe],queryFn:()=>bs({page:1,pageSize:Be,search:Pe||void 0}),enabled:!!m,retry:!1}),$=n.useMemo(()=>{var t;return[...((t=j.data)==null?void 0:t.connections)??[]].sort((a,o)=>{const i=a.provider.localeCompare(o.provider);return i||String(a.name||a.email||a.id).localeCompare(String(o.name||o.email||o.id))})},[j.data]),ze=n.useMemo(()=>{const s=new Map;for(const t of $){const a=s.get(t.provider)??[];a.push(t),s.set(t.provider,a)}return[...s.entries()]},[$]);function Ye(s,t){var i,l;const a=(Ge.data??[]).find(g=>g.id===s);if(a!=null&&a.name)return a.name;const o=(l=(i=t.find(g=>{var C;return typeof((C=g.providerSpecificData)==null?void 0:C.nodeName)=="string"}))==null?void 0:i.providerSpecificData)==null?void 0:l.nodeName;return typeof o=="string"&&o.trim()?o.trim():os(s)}const R=n.useMemo(()=>$.map(s=>s.id),[$]),We=R.filter(s=>y.has(s)).length,de=n.useMemo(()=>{const s=x.trim().toLowerCase();return s?U.filter(t=>(t.name||"").toLowerCase().includes(s)||(t.proxyUrl||"").toLowerCase().includes(s)||t.id.toLowerCase().includes(s)):U},[U,x]);function c(s,t="default"){t==="success"?fe.success(s):t==="error"?fe.error(s):fe(s)}function F(){te(""),ae(""),ne(""),oe("http"),ce(!1)}function B(){je("vercel"),ge(""),ve(""),be(""),q(null)}async function Ze(){if(h==="cloudflare"&&!W.trim())return c("Cloudflare Account ID required","error");if(!_.trim())return c("Deployment token required","error");q({steps:h==="vercel"?["Create deployment","Wait for deployment","Check relay","Save proxy pool"]:["Upload worker","Enable subdomain","Check relay","Save proxy pool"],current:0,completed:!1,error:null});let t;h==="vercel"?t={type:"vercel",vercelToken:_.trim(),projectName:Y.trim()||void 0}:t={type:"cloudflare",accountId:W.trim(),apiToken:_.trim(),projectName:Y.trim()||void 0},Ne(!0);try{await ps(t),await r.invalidateQueries({queryKey:["proxy-pools"]}),q(a=>a&&{...a,current:a.steps.length-1,completed:!0}),c(`${h[0].toUpperCase()}${h.slice(1)} relay deployed`,"success"),p(!1),B()}catch(a){const o=w(a,"Relay deployment failed");q(i=>i&&{...i,error:o}),c(o,"error")}finally{Ne(!1)}}function Ie(s){M(s),te(s.name||""),ae(s.proxyUrl||""),ne(s.noProxy||""),oe(s.type||"http"),ce(s.strictProxy===!0)}async function Je(){if(!L.trim()||!K.trim())return c("Name and proxy URL required","error");T(!0);try{const s={name:L.trim(),proxyUrl:K.trim(),noProxy:re.trim(),type:le,strictProxy:ie};await hs(s),await r.invalidateQueries({queryKey:["proxy-pools"]}),c("Pool created","success"),u(!1),F()}catch(s){c(w(s,"Create failed"),"error")}finally{T(!1)}}async function es(){if(P){T(!0);try{const s={name:L.trim(),proxyUrl:K.trim(),noProxy:re.trim(),type:le,strictProxy:ie};await Le(P.id,s),await r.invalidateQueries({queryKey:["proxy-pools"]}),c("Pool updated","success"),M(null),F()}catch(s){c(w(s,"Update failed"),"error")}finally{T(!1)}}}async function Ae(s){const t=s.isActive===!1;try{await Le(s.id,{isActive:t}),await r.invalidateQueries({queryKey:["proxy-pools"]})}catch(a){c(w(a,"Toggle failed"),"error")}}async function qe(s){Se(s);try{const t=await fs(s);await r.invalidateQueries({queryKey:["proxy-pools"]}),t.ok?c(`Proxy OK${t.ip?` · ${t.ip}`:""}`,"success"):c(t.error||"Proxy test failed","error")}catch(t){c(w(t,"Test failed"),"error")}finally{Se(null)}}function ss(s){var a;const t=(a=s.providerSpecificData)==null?void 0:a.proxyPoolId;return typeof t=="string"&&t.trim()?t:typeof s.proxyPoolId=="string"&&s.proxyPoolId.trim()?s.proxyPoolId:null}function Ee(s){ke(s),O(new Set),ee(""),se("")}function ts(s){O(t=>{const a=new Set(t);return a.has(s)?a.delete(s):a.add(s),a})}function Oe(s){s.length&&O(t=>{const a=new Set(t),o=s.every(i=>a.has(i));for(const i of s)o?a.delete(i):a.add(i);return a})}async function Ue(s){if(!y.size){c("Select at least one connection","error");return}if(y.size>He){c(`Assign up to ${He} connections at a time`,"error");return}Te(!0);const t=[...y],a=[];for(let l=0;l<t.length;l+=12){const g=t.slice(l,l+12);a.push(...await Promise.allSettled(g.map(C=>vs(C,{proxyPoolId:s}))))}const o=a.filter(l=>l.status==="fulfilled").length,i=a.length-o;await Promise.all([r.invalidateQueries({queryKey:["proxy-pool-connections"]}),r.invalidateQueries({queryKey:["proxy-pools"]}),r.invalidateQueries({queryKey:["connections"]})]),O(new Set),Te(!1),i?c(`${o} updated, ${i} failed`,"error"):c(s?`${o} connection(s) assigned`:`${o} connection(s) set to direct`,"success")}async function as(){if(Z){T(!0);try{await ys(Z),await r.invalidateQueries({queryKey:["proxy-pools"]}),c("Pool deleted","success"),E(null)}catch(s){c(w(s,"Delete failed"),"error")}finally{T(!1)}}}return e.jsxs("div",{className:"space-y-4",children:[e.jsx(ns,{title:"Proxy Pools",actions:U.length>0?e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[e.jsxs(d,{size:"sm",variant:"outline",onClick:()=>{B(),p(!0)},children:[e.jsx(Ke,{className:"h-4 w-4 fill-current"}),"Deploy"]}),e.jsxs(d,{size:"sm",onClick:()=>{F(),u(!0)},children:[e.jsx(Re,{className:"h-4 w-4"}),"Add pool"]})]}):null}),e.jsxs("div",{className:"relative max-w-md",children:[e.jsx("span",{className:"sr-only",children:"Search proxy pools"}),e.jsx(Cs,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(v,{value:x,onChange:s=>S(s.target.value),placeholder:"Search pools…",className:"pl-9"})]}),e.jsx(is,{className:"overflow-hidden",children:e.jsx(cs,{className:"p-0",children:e.jsx("div",{className:"min-w-0",children:Xe?e.jsx("div",{className:"space-y-2 p-4",children:Array.from({length:3}).map((s,t)=>e.jsx(ds,{className:"h-12 w-full"},t))}):U.length===0?e.jsxs("div",{className:"flex flex-col items-center gap-2 px-4 py-16 text-center",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"No proxy pools"}),e.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-2",children:[e.jsxs(d,{size:"sm",onClick:()=>{F(),u(!0)},children:[e.jsx(Re,{className:"h-4 w-4"}),"Add first pool"]}),e.jsxs(d,{size:"sm",variant:"outline",onClick:()=>{B(),p(!0)},children:[e.jsx(Ke,{className:"h-4 w-4 fill-current"}),"Deploy relay"]})]})]}):de.length===0?e.jsx("div",{className:"px-4 py-16 text-center text-sm text-muted-foreground",children:"No proxy pools match your search."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-hidden rounded-xl border border-border/70 bg-card sm:hidden",children:e.jsx("div",{className:"divide-y divide-border/70",children:de.map(s=>e.jsxs("article",{className:"min-w-0 space-y-2.5 p-3",children:[e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:"truncate text-sm font-medium",children:s.name||s.id}),s.isActive===!1?e.jsx(D,{tone:"muted",className:"shrink-0 text-[10px]",children:"Off"}):null]}),e.jsx(A,{label:s.proxyUrl||"—",children:e.jsx("p",{className:"mt-1 truncate font-mono text-[11px] text-muted-foreground",children:s.proxyUrl||"—"})})]}),e.jsx(D,{tone:s.testStatus==="ok"||s.testStatus==="active"?"ok":s.testStatus==="error"?"err":"muted",className:"shrink-0 text-[10px]",children:s.testStatus==="active"?"ok":s.testStatus||"unknown"})]}),e.jsxs("div",{className:"flex min-w-0 items-center gap-2 text-[11px] text-muted-foreground",children:[e.jsx("span",{className:"shrink-0 uppercase",children:s.type||"http"}),e.jsx("span",{"aria-hidden":"true",children:"·"}),e.jsxs("span",{className:"min-w-0 truncate",children:[s.boundConnectionCount??0," connections"]})]}),e.jsx(Ve,{pool:s,testing:we===s.id,onToggle:()=>void Ae(s),onTest:()=>void qe(s.id),onManage:()=>Ee(s),onEdit:()=>Ie(s),onDelete:()=>E(s.id)})]},s.id))})}),e.jsx("div",{className:"hidden min-w-0 sm:block",children:e.jsxs(ms,{variant:"card",className:"min-w-[44rem] text-[13px] [&_tbody]:before:hidden [&_tbody_tr_td]:!bg-transparent [&_tbody_tr:hover_td]:!bg-transparent [&_tbody_tr[data-state=selected]_td]:!bg-transparent",children:[e.jsx(xs,{className:"bg-transparent text-[10px] uppercase text-muted-foreground",children:e.jsxs(Qe,{className:"border-b border-border/80 bg-transparent hover:bg-transparent",children:[e.jsx(z,{className:"px-4 py-2 font-medium",children:"Name"}),e.jsx(z,{className:"px-3 py-2 font-medium",children:"URL"}),e.jsx(z,{className:"px-3 py-2 font-medium",children:"Type"}),e.jsx(z,{className:"px-3 py-2 font-medium",children:"Connections"}),e.jsx(z,{className:"px-3 py-2 font-medium",children:"Test"}),e.jsx(z,{className:"px-4 py-2 font-medium text-right",children:"Actions"})]})}),e.jsx(us,{children:de.map(s=>e.jsxs(Qe,{className:"border-b border-border/60 last:border-0 bg-transparent hover:bg-transparent data-[state=selected]:bg-transparent",children:[e.jsx(I,{className:"max-w-[14rem] bg-transparent px-4 py-2",children:e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:"truncate text-sm font-medium",children:s.name||s.id}),s.isActive===!1?e.jsx(D,{tone:"muted",className:"shrink-0 text-[10px]",children:"Off"}):null]})}),e.jsx(I,{className:"max-w-[24rem] truncate bg-transparent px-3 py-2 font-mono text-xs text-muted-foreground",children:e.jsx(A,{label:s.proxyUrl||"—",children:e.jsx("span",{className:"block truncate",children:s.proxyUrl||"—"})})}),e.jsx(I,{className:"bg-transparent px-3 py-2 text-xs uppercase text-muted-foreground",children:s.type||"http"}),e.jsx(I,{className:"bg-transparent px-3 py-2 text-xs text-muted-foreground",children:s.boundConnectionCount??0}),e.jsx(I,{className:"bg-transparent px-3 py-2",children:e.jsx(D,{tone:s.testStatus==="ok"||s.testStatus==="active"?"ok":s.testStatus==="error"?"err":"muted",className:"w-fit text-[10px]",children:s.testStatus==="active"?"ok":s.testStatus||"unknown"})}),e.jsx(I,{className:"bg-transparent px-4 py-2",children:e.jsx(Ve,{pool:s,testing:we===s.id,onToggle:()=>void Ae(s),onTest:()=>void qe(s.id),onManage:()=>Ee(s),onEdit:()=>Ie(s),onDelete:()=>E(s.id)})})]},s.id))})]})})]})})})}),e.jsx(H,{open:f||!!P,onOpenChange:s=>{s||(u(!1),M(null),F())},children:e.jsxs(V,{className:"max-h-[90vh]",children:[e.jsxs(G,{children:[e.jsx(X,{children:P?"Edit proxy pool":"Add proxy pool"}),e.jsx(ue,{children:"Used as connection outbound proxy."})]}),e.jsxs(pe,{className:"space-y-4",children:[e.jsxs("label",{className:"block space-y-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Name"}),e.jsx(v,{value:L,onChange:s=>te(s.target.value),placeholder:"US residential"})]}),e.jsxs("label",{className:"block space-y-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Proxy URL (HTTP/HTTPS/SOCKS5)"}),e.jsx(v,{value:K,onChange:s=>ae(s.target.value),placeholder:"http://user:pass@host:port or host:port"})]}),e.jsxs("label",{className:"block space-y-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"No-proxy"}),e.jsx(v,{value:re,onChange:s=>ne(s.target.value),placeholder:"localhost,127.0.0.1"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("span",{className:"block text-xs text-muted-foreground",children:"Type"}),e.jsx(Me,{size:"sm",value:le,onChange:oe,options:[{value:"http",label:"HTTP"},{value:"socks5",label:"SOCKS5"}]})]}),e.jsxs("label",{className:"flex items-start gap-2.5 rounded-lg border border-border/70 p-3",children:[e.jsx(xe,{checked:ie,onCheckedChange:s=>ce(s===!0),disabled:N,"aria-describedby":"strict-proxy-help"}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-sm font-medium",children:"Require proxy"}),e.jsx("span",{id:"strict-proxy-help",className:"mt-0.5 block text-xs text-muted-foreground",children:"Fail requests when this proxy is unavailable instead of falling back to a direct connection."})]})]})]}),e.jsxs(he,{children:[e.jsx(d,{variant:"outline",onClick:()=>{u(!1),M(null)},disabled:N,children:"Cancel"}),e.jsx(d,{onClick:()=>void(P?es():Je()),disabled:N,children:N?"Saving…":P?"Save":"Create"})]})]})}),e.jsx(H,{open:b,onOpenChange:s=>{p(s),s||B()},children:e.jsxs(V,{className:"max-h-[90vh]",children:[e.jsx(G,{children:e.jsx(X,{children:"Deploy relay"})}),e.jsxs(pe,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("span",{className:"block text-xs text-muted-foreground",children:"Platform"}),e.jsx(Me,{size:"sm",value:h,onChange:s=>je(s),options:[{value:"vercel",label:"Vercel"},{value:"cloudflare",label:"Cloudflare"}]})]}),e.jsxs("label",{className:"block space-y-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Project name (optional)"}),e.jsx(v,{value:Y,onChange:s=>ge(s.target.value),placeholder:"sway-router-relay",autoComplete:"off"})]}),h==="cloudflare"?e.jsxs("label",{className:"block space-y-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Account ID"}),e.jsx(v,{value:W,onChange:s=>be(s.target.value),placeholder:"Cloudflare account ID",autoComplete:"off"})]}):null,e.jsxs("label",{className:"block space-y-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:h==="vercel"?"Vercel API token":"Cloudflare API token"}),e.jsx(v,{type:"password",value:_,onChange:s=>ve(s.target.value),placeholder:"Token",autoComplete:"off"})]}),Ce?e.jsx(zs,{progress:Ce}):null]}),e.jsxs(he,{children:[e.jsx(d,{variant:"outline",onClick:()=>p(!1),disabled:k,children:"Cancel"}),e.jsxs(d,{onClick:()=>void Ze(),disabled:k,children:[k?e.jsx(ye,{className:"size-4 animate-spin"}):null,k?"Deploying…":"Deploy"]})]})]})}),e.jsx(H,{open:!!m,onOpenChange:s=>{s||(ke(null),O(new Set),ee(""),se(""))},children:e.jsxs(V,{className:"max-h-[90vh] max-w-3xl",children:[e.jsxs(G,{children:[e.jsxs(X,{children:["Manage ",(m==null?void 0:m.name)||"proxy pool"]}),e.jsx(ue,{children:"Assign existing provider connections to this pool without recreating their credentials."})]}),e.jsxs(pe,{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(v,{value:J,onChange:s=>ee(s.target.value),placeholder:"Search provider, name, email, or ID…",className:"min-w-[14rem] flex-1"}),e.jsx(d,{size:"sm",variant:"outline",disabled:!R.length||Q,onClick:()=>Oe(R),children:We===R.length?"Clear visible":"Select visible"})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:j.isLoading?"Loading connections…":`${(($e=j.data)==null?void 0:$e.pagination.totalItems)??$.length} connection(s) · ${y.size} selected`}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(d,{size:"sm",disabled:!y.size||Q,onClick:()=>void Ue((m==null?void 0:m.id)||null),children:Q?"Assigning…":"Assign selected"}),e.jsx(d,{size:"sm",variant:"outline",disabled:!y.size||Q,onClick:()=>void Ue(null),children:"Set direct"})]})]}),j.error?e.jsx("p",{className:"rounded-md border border-destructive/30 bg-destructive/10 p-3 text-sm text-destructive",children:w(j.error,"Failed to load connections")}):ze.length===0&&!j.isLoading?e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"No existing connections match this search."}):e.jsxs(e.Fragment,{children:[(Fe=j.data)!=null&&Fe.pagination.hasNext?e.jsxs("p",{className:"rounded-md border border-warning/25 bg-warning/10 px-3 py-2 text-xs text-warning",children:["Showing the first ",Be," matches. Use search to find other connections."]}):null,e.jsx("div",{className:"max-h-[50vh] space-y-2 overflow-y-auto pr-1",children:ze.map(([s,t])=>{const a=t.map(l=>l.id),o=a.filter(l=>y.has(l)).length,i=o===a.length;return e.jsxs("div",{className:"rounded-lg border border-border",children:[e.jsxs("div",{className:"flex items-center gap-2 border-b border-border/70 bg-muted/30 px-3 py-2",children:[e.jsx(xe,{checked:i,indeterminate:o>0&&!i,onCheckedChange:()=>Oe(a),"aria-label":`Select all ${s} connections`}),e.jsx("span",{className:"font-medium",children:Ye(s,t)}),e.jsx("span",{className:"font-mono text-[10px] text-muted-foreground",children:s}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[o,"/",a.length]})]}),e.jsx("div",{className:"divide-y divide-border/60",children:t.map(l=>{const g=ss(l),C=g===(m==null?void 0:m.id),_e=l.name||l.email||l.id.slice(0,8);return e.jsxs("label",{className:"flex cursor-pointer items-center gap-2 px-3 py-2 hover:bg-muted/20",children:[e.jsx(xe,{checked:y.has(l.id),onCheckedChange:()=>ts(l.id),"aria-label":`Select ${_e}`}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate text-sm font-medium",children:_e}),e.jsxs("span",{className:"block truncate text-xs text-muted-foreground",children:[l.email&&l.name?`${l.email} · `:"",l.authType||"connection"," · ",l.id.slice(0,8)]})]}),e.jsx(D,{tone:l.isActive===!1?"muted":C?"ok":"muted",className:"shrink-0 text-[10px]",children:C?"This pool":g?"Other pool":"Direct"}),l.isActive===!1?e.jsx(D,{tone:"muted",className:"shrink-0 text-[10px]",children:"Off"}):null]},l.id)})})]},s)})})]})]})]})}),e.jsx(H,{open:!!Z,onOpenChange:s=>{s||E(null)},children:e.jsxs(V,{children:[e.jsxs(G,{children:[e.jsx(X,{children:"Delete pool?"}),e.jsx(ue,{children:"Detach all connections using this pool before deleting it. Bound pools cannot be deleted."})]}),e.jsxs(he,{children:[e.jsx(d,{variant:"outline",onClick:()=>E(null),disabled:N,children:"Cancel"}),e.jsx(d,{variant:"destructive",onClick:as,disabled:N,children:N?"Deleting…":"Delete"})]})]})})]})}export{Xs as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as v,j as e,L as de}from"./react-vendor-xnYrwzsL.js";import{u as ce,a as ue,e as H}from"./query-vendor-DVevaSVS.js";import{g as G,c as C,P as me,Q as xe,C as he,p as Q,e as _,t as q,w as fe,R as pe,b as ge,h as ve}from"./index-B6j-9zHy.js";import{H as be}from"./Header-C_9Su9BF.js";import{R as z}from"./ripple-button-l8aMiVVG.js";import{S as y}from"./StatusBadge-1nAOyHU2.js";import{F as A,a as D,c as F,d as X}from"./frame-cUiti6Lq.js";import{S as N}from"./skeleton-7uJDiIXe.js";import{z as je,B as Ne}from"./connections-api-_N54UD3S.js";import{p as V}from"./live-mode-CHShLY4E.js";import{aa as B,i as Y,ay as we}from"./icons-vendor-CUx7SB5V.js";import"./ui-vendor-BuM9f2NY.js";import"./motion-vendor-g5fpGzmJ.js";const ye=new Set(["github","gemini-cli","antigravity","claude","codex","kiro","qoder","ollama","glm","glm-cn","minimax","minimax-cn","vercel-ai-gateway","codebuddy-cn","codebuddy-intl","grok-cli","kimi","deepseek"]),Ce=25,L=200,Ee=6,I=3,P=[];let O=0;function Z(){var t;for(;O<Ee&&P.length>0;){const r=P.shift();if(!r)return;if((t=r.signal)!=null&&t.aborted){r.cleanup(),r.reject(r.signal.reason??new DOMException("Quota request aborted","AbortError"));continue}O+=1,r.started=!0,r.run().then(r.resolve).catch(r.reject).finally(()=>{r.cleanup(),O-=1,Z()})}}function Re(t,r){return new Promise((n,a)=>{if(r!=null&&r.aborted){a(r.reason??new DOMException("Quota request aborted","AbortError"));return}const i={run:async()=>t(),resolve:n,reject:a,signal:r,started:!1,cleanup:()=>{}},l=()=>{if(i.started)return;const m=P.indexOf(i);m!==-1&&(P.splice(m,1),i.cleanup(),a((r==null?void 0:r.reason)??new DOMException("Quota request aborted","AbortError")))};r==null||r.addEventListener("abort",l,{once:!0}),i.cleanup=()=>r==null?void 0:r.removeEventListener("abort",l),P.push(i),Z()})}const T=["expired","authentication","unauthorized","401","re-authorize"];function Pe(t){if(!t)return!1;const r=t.toLowerCase();return T.some(n=>r.includes(n))}function Me(t){var n,a;if(he.isAxiosError(t)){if(((n=t.response)==null?void 0:n.status)===401)return!0;const i=(a=t.response)==null?void 0:a.data,l=(i==null?void 0:i.error)||(i==null?void 0:i.message)||"";if(T.some(m=>l.toLowerCase().includes(m)))return!0}const r=t instanceof Error?t.message:"";return T.some(i=>r.toLowerCase().includes(i))}function ke(t,r){return!r||r<=0?0:!t||t<0?100:t>=r?0:Math.round((r-t)/r*100)}function Qe(t,r){const n=r==null?void 0:r.quotas;if(!n||typeof n!="object")return[];const a=t.toLowerCase();return Object.entries(n).flatMap(([i,l])=>{const m=Number.isFinite(Number(l.used))?Number(l.used):0,c=Number.isFinite(Number(l.total))?Number(l.total):0,x=a==="codex"&&l.remaining!==void 0?Math.max(0,Math.round(Number(l.remaining))):l.remainingPercentage!==void 0?Math.max(0,Math.round(Number(l.remainingPercentage))):ke(m,c);return a==="qoder"&&i==="organization"&&c<=0?[]:[{name:a==="antigravity"?l.displayName||i:a==="qoder"?i==="user"?"Personal":i==="organization"?"Organization":i:i,used:m,total:c,remaining:x,resetAt:l.resetAt??null,recurring:l.recurring!==!1,unlimited:l.unlimited===!0||c<=0,unit:l.unit}]})}function Ae(t){if(!t)return null;const r=new Date(t).getTime()-Date.now();if(!Number.isFinite(r)||r<=0)return null;const n=Math.ceil(r/6e4);if(n<60)return`${n}m`;const a=Math.floor(n/60);return a<24?`${a}h ${n%60}m`:`${Math.floor(a/24)}d ${a%24}h ${n%60}m`}function j(t){return Number.isFinite(t)?Math.round(t).toLocaleString("id-ID"):"0"}function Fe(t){return t>70?{text:"text-success",bg:"bg-success",bgLight:"bg-success/10"}:t>=30?{text:"text-warning",bg:"bg-warning",bgLight:"bg-warning/10"}:{text:"text-destructive",bg:"bg-destructive",bgLight:"bg-destructive/10"}}function $e(t){if(t.loading)return null;if(t.authExpired)return e.jsx(y,{tone:"warn",children:"Auth expired"});if(t.error)return e.jsx(y,{tone:"err",children:"Error"});if(t.conn.isActive===!1)return e.jsx(y,{tone:"muted",children:"Disabled"});if(t.quotas.length===0)return e.jsx(y,{tone:"muted",children:"No quota"});const r=Math.min(...t.quotas.map(n=>n.remaining));return r<=0?e.jsx(y,{tone:"err",children:"Limit reached"}):r<30?e.jsx(y,{tone:"warn",children:"Low quota"}):e.jsx(y,{tone:"ok",children:"OK"})}function J({provider:t}){const r=fe(t),n=pe(t),a=ge(t);return e.jsx("span",{className:"grid h-9 w-9 shrink-0 place-items-center rounded-lg",style:{backgroundColor:`${n}1f`,color:n},children:a?e.jsx("span",{"aria-hidden":"true",className:"block h-4 w-4 shrink-0",style:{backgroundColor:n,WebkitMaskImage:`url(${a})`,maskImage:`url(${a})`,WebkitMaskPosition:"center",maskPosition:"center",WebkitMaskRepeat:"no-repeat",maskRepeat:"no-repeat",WebkitMaskSize:"contain",maskSize:"contain"}}):e.jsx(r,{className:"h-4 w-4"})})}function Xe(){const t=ce(),[r,n]=v.useState(null),[a,i]=v.useState({}),[,l]=v.useState(0);v.useEffect(()=>{const s=window.setInterval(()=>{l(o=>o+1)},6e4);return()=>window.clearInterval(s)},[]);const m=ue({queryKey:["quota-provider-counts"],queryFn:Ne,enabled:V(),retry:!1}),c=v.useMemo(()=>(m.data??[]).map(s=>({...s,provider:String(s.provider||"").trim()})).filter(s=>ye.has(s.provider)&&s.total>0),[m.data]);v.useEffect(()=>{i(s=>{const o={};for(const u of c)o[u.provider]=Math.max(1,s[u.provider]??1);return o})},[c]);const x=v.useMemo(()=>c.flatMap(s=>{const o=a[s.provider]??1;return Array.from({length:o},(u,d)=>({provider:s.provider,page:d+1}))}),[c,a]),f=H({queries:x.map(s=>({queryKey:["quota-connections",s.provider,s.page],queryFn:()=>je({provider:s.provider,page:s.page,pageSize:Ce}),enabled:V(),retry:!1,staleTime:3e4}))}),E=v.useMemo(()=>{const s=new Map;return x.forEach((o,u)=>{var b,h;const d=((h=(b=f[u])==null?void 0:b.data)==null?void 0:h.connections)??[],p=s.get(o.provider)??[],M=new Set(p.map(w=>w.id));s.set(o.provider,[...p,...d.filter(w=>!M.has(w.id))])}),s},[f,x]),ee=v.useMemo(()=>{var o,u,d;const s=new Map;for(const p of c){const b=x.map((g,le)=>g.provider===p.provider?le:-1).filter(g=>g>=0).map(g=>f[g]),h=b[b.length-1],w=(o=h==null?void 0:h.data)==null?void 0:o.pagination,k=((u=E.get(p.provider))==null?void 0:u.length)??0,W=k>=L&&k<p.total;s.set(p.provider,{loading:!!((d=b[0])!=null&&d.isPending),fetching:b.some(g=>g==null?void 0:g.isFetching),error:b.some(g=>g==null?void 0:g.isError),hasNext:!W&&(!!(w!=null&&w.hasNext)||k<p.total),capped:W,loaded:k})}return s},[f,E,x,c]),$=v.useMemo(()=>c.flatMap(s=>E.get(s.provider)??[]),[E,c]),S=H({queries:$.map(s=>({queryKey:["quota-usage",s.id],queryFn:({signal:o})=>Re(()=>xe(s.id,o),o),enabled:!!s.id,retry:!1,staleTime:3e4}))}),te=v.useMemo(()=>{const s=new Map;return $.forEach((o,u)=>{var b;const d=S[u];let p;if(!d||d.isPending)p={conn:o,loading:!0,fetching:!!(d!=null&&d.isFetching),error:null,authExpired:!1,usage:null,quotas:[],message:null,resetCredits:0,plan:null};else if(d.isError){const h=G(d.error,"Failed to fetch quota");p={conn:o,loading:!1,fetching:d.isFetching,error:h,authExpired:Me(d.error),usage:null,quotas:[],message:h,resetCredits:0,plan:null}}else{const h=d.data??{};p={conn:o,loading:!1,fetching:d.isFetching,error:null,authExpired:Pe(h.message),usage:h,quotas:Qe(o.provider,h),message:h.message??null,resetCredits:((b=h.resetCredits)==null?void 0:b.availableCount)??0,plan:h.plan??null}}const M=s.get(o.provider)??[];s.set(o.provider,[...M,p])}),s},[$,S]);function R(s,o="default"){o==="success"?q.success(s):o==="error"?q.error(s):q(s)}async function se(){await Promise.all([t.invalidateQueries({queryKey:["quota-provider-counts"]}),t.invalidateQueries({queryKey:["quota-connections"]}),t.invalidateQueries({queryKey:["quota-usage"]})]),R("Refreshed","success")}function re(s,o){Promise.all([t.invalidateQueries({queryKey:["quota-connections",s]}),...o.map(u=>t.invalidateQueries({queryKey:["quota-usage",u.conn.id]}))])}function ne(s){t.invalidateQueries({queryKey:["quota-usage",s]})}function oe(s){var u;if((((u=E.get(s))==null?void 0:u.length)??0)>=L){R(`Quota view is limited to ${j(L)} accounts per provider`);return}i(d=>({...d,[s]:(d[s]??1)+1}))}async function ie(s){if(!r){n(s.id);try{const o=await me(s.id);o.reset===!1||o.code==="no_credit"?R(o.message||"No Codex reset credits available","error"):R("Codex quota reset","success"),await t.invalidateQueries({queryKey:["quota-usage",s.id]})}catch(o){R(G(o,"Reset failed"),"error")}finally{n(null)}}}const K=m.isLoading,ae=!K&&c.length===0,U=m.isFetching||f.some(s=>s==null?void 0:s.isFetching)||S.some(s=>s==null?void 0:s.isFetching);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(be,{title:"Quota",actions:e.jsxs(z,{size:"sm",variant:"outline",disabled:U,onClick:()=>void se(),children:[e.jsx(B,{className:C("h-3.5 w-3.5",U&&"animate-spin")}),"Refresh"]})}),m.isError?e.jsx("div",{className:"rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive",children:"Unable to load live quota providers. Check your session and backend connection."}):null,K?e.jsx("div",{className:"space-y-4",children:["provider-skeleton-a","provider-skeleton-b"].map(s=>e.jsxs(A,{children:[e.jsxs(D,{className:"flex flex-row items-center gap-3 p-4",children:[e.jsx(N,{className:"h-9 w-9 rounded-lg"}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(N,{className:"h-4 w-28"}),e.jsx(N,{className:"h-3 w-44"})]})]}),e.jsx(F,{className:"grid gap-3 p-3 sm:grid-cols-2 xl:grid-cols-3",children:Array.from({length:3}).map((o,u)=>e.jsx(N,{className:"h-48 w-full rounded-xl"},u))})]},s))}):ae?e.jsx(A,{children:e.jsxs(F,{className:"p-10 text-center",children:[e.jsx("p",{className:"text-sm font-medium",children:"No providers connected"}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Connect an OAuth provider to track API quota limits and usage."})]})}):e.jsx("div",{className:"space-y-4",children:c.map(s=>{const o=te.get(s.provider)??[],u=ee.get(s.provider)??{loading:!0,fetching:!1,error:!1,hasNext:!1,capped:!1,loaded:0};return e.jsx(Se,{group:s,cards:o,pageState:u,onRefreshProvider:()=>re(s.provider,o),onRefreshCard:ne,onLoadMore:()=>oe(s.provider),onResetCodex:ie,resettingId:r},s.provider)})})]})}function Se({group:t,cards:r,pageState:n,onRefreshProvider:a,onRefreshCard:i,onLoadMore:l,onResetCodex:m,resettingId:c}){return e.jsxs(A,{children:[e.jsxs(D,{className:"flex flex-row items-start justify-between gap-3 p-4",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx(J,{provider:t.provider}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"truncate text-sm font-semibold",children:Q(t.provider)}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:n.loaded>0?`${n.loaded} of ${j(t.total)} accounts loaded`:`${j(t.total)} accounts`})]})]}),e.jsx(_,{label:`Refresh ${Q(t.provider)} quota`,children:e.jsx("button",{type:"button",onClick:a,disabled:n.fetching,className:"grid h-8 w-8 shrink-0 place-items-center rounded-md text-muted-foreground transition-colors hover:bg-surface-hover hover:text-foreground disabled:opacity-50","aria-label":`Refresh ${Q(t.provider)} quota`,children:e.jsx(B,{className:C("h-3.5 w-3.5",n.fetching&&"animate-spin")})})})]}),e.jsxs(F,{className:"p-3",children:[n.error?e.jsxs("div",{className:"mb-3 rounded-lg border border-destructive/25 bg-destructive/10 px-3 py-2 text-[11px] text-destructive",children:["Some ",Q(t.provider)," accounts could not be loaded. Refresh this section to retry."]}):null,n.loading&&r.length===0?e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-3",children:Array.from({length:3}).map((x,f)=>e.jsx(N,{className:"h-48 w-full rounded-xl"},f))}):r.length>0?e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-3",children:r.map(x=>e.jsx(qe,{card:x,onRefresh:()=>i(x.conn.id),onResetCodex:()=>m(x.conn),resetting:c===x.conn.id},x.conn.id))}):e.jsx("div",{className:"py-8 text-center text-[11px] text-muted-foreground",children:"No accounts available for this provider."})]}),n.hasNext||n.capped?e.jsxs(X,{className:"flex items-center justify-between gap-3 border-t border-border p-3",children:[e.jsx("span",{className:"text-[11px] tabular-nums text-muted-foreground",children:n.capped?`Showing ${j(n.loaded)} of ${j(t.total)} accounts. Quota loading is capped for performance.`:`Showing ${j(n.loaded)} of ${j(t.total)} accounts`}),n.hasNext?e.jsxs(z,{size:"sm",variant:"outline",onClick:l,disabled:n.fetching,children:[e.jsx(Y,{className:"h-3.5 w-3.5"}),n.fetching?"Loading…":"Load more"]}):null]}):null]})}function qe({card:t,onRefresh:r,onResetCodex:n,resetting:a}){const{conn:i}=t,[l,m]=v.useState(!1),c=t.authExpired?"Re-authorize the connection first":t.resetCredits<=0?"No Codex reset credits available":"Spend one Codex reset credit to reset the quota window",x=l?t.quotas:t.quotas.slice(0,I);return e.jsxs(A,{className:"flex flex-col",children:[e.jsxs(D,{className:"flex flex-row items-start justify-between gap-3 p-4",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(J,{provider:i.provider}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"truncate text-sm font-medium leading-tight",children:i.name||i.email||i.provider}),e.jsx("p",{className:"truncate text-[11px] text-muted-foreground",children:i.email&&i.name?i.email:`Connection ID · ${i.id}`})]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[$e(t),e.jsx(_,{label:"Refresh quota",children:e.jsx("button",{type:"button",onClick:r,disabled:t.fetching,className:"grid h-7 w-7 place-items-center rounded-md text-muted-foreground transition-colors hover:bg-surface-hover hover:text-foreground disabled:opacity-50","aria-label":t.fetching?"Refreshing quota":"Refresh quota",children:e.jsx(B,{className:C("h-3.5 w-3.5",t.fetching&&"animate-spin")})})})]})]}),e.jsxs(F,{className:"flex min-h-0 flex-1 flex-col gap-3 p-4",children:[t.plan?e.jsx(ve,{variant:"outline",className:"w-fit text-[10px]",children:t.plan}):null,e.jsx("div",{className:"min-h-[3.5rem] flex-1",children:t.loading?e.jsxs("div",{className:"space-y-2",children:[e.jsx(N,{className:"h-4 w-full"}),e.jsx(N,{className:"h-1.5 w-full"}),e.jsx(N,{className:"h-3 w-2/3"})]}):t.authExpired?e.jsxs("div",{className:"rounded-lg border border-warning/25 bg-warning/10 px-3 py-2",children:[e.jsx("p",{className:"text-xs font-medium text-warning",children:"Authentication expired"}),e.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:t.message||t.error}),e.jsx(de,{to:"/dashboard/provider",className:"mt-1.5 inline-block text-[11px] font-medium text-warning underline underline-offset-2",children:"Re-authorize in Providers"})]}):t.error?e.jsxs("div",{className:"rounded-lg border border-destructive/25 bg-destructive/10 px-3 py-2",children:[e.jsx("p",{className:"text-xs font-medium text-destructive",children:"Failed to load quota"}),e.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:t.error})]}):t.quotas.length>0?e.jsxs("div",{className:"space-y-3",children:[t.message?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:t.message}):null,x.map(f=>e.jsx(Le,{quota:f},`${f.name}-${f.unit??""}`)),t.quotas.length>I?e.jsxs("button",{type:"button",onClick:()=>m(f=>!f),className:"inline-flex items-center gap-1 text-[11px] font-medium text-muted-foreground transition-colors hover:text-foreground",children:[e.jsx(Y,{className:C("h-3 w-3 transition-transform",l&&"rotate-180")}),l?"Show less":`Show ${t.quotas.length-I} more`]}):null]}):t.message?e.jsx("div",{className:"rounded-lg border border-border bg-surface px-3 py-2 text-[11px] text-muted-foreground",children:t.message}):e.jsx("div",{className:"py-6 text-center text-[11px] text-muted-foreground",children:"No quota data available"})})]}),i.provider==="codex"?e.jsxs(X,{className:"flex items-center justify-between gap-2 border-t border-border p-4",children:[e.jsxs("span",{className:"text-[11px] tabular-nums text-muted-foreground",children:[t.resetCredits," reset credit",t.resetCredits===1?"":"s"]}),e.jsx(_,{label:c,children:e.jsxs(z,{size:"sm",variant:"outline",onClick:n,disabled:t.resetCredits<=0||t.authExpired||a||t.loading,children:[e.jsx(we,{className:"h-3.5 w-3.5"}),a?"Resetting…":"Reset quota"]})})]}):null]})}function Le({quota:t}){const r=Fe(t.remaining),n=Ae(t.resetAt),a=t.recurring?"Reset":"Expires";return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"min-w-0 truncate text-xs font-medium",children:t.name}),e.jsxs("span",{className:C("shrink-0 text-xs font-medium tabular-nums",r.text),children:[t.remaining,"%"]})]}),t.unlimited?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Unlimited"}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:C("h-1.5 overflow-hidden rounded-full",r.bgLight),children:e.jsx("div",{className:C("h-full rounded-full transition-all duration-300",r.bg),style:{width:`${Math.min(t.remaining,100)}%`}})}),e.jsxs("div",{className:"flex items-center justify-between gap-2 text-[10px] text-muted-foreground",children:[e.jsxs("span",{className:"tabular-nums",children:[j(t.used)," / ",t.total>0?j(t.total):"∞"]}),n?e.jsxs("span",{className:"tabular-nums",children:[a," in ",n]}):null]})]})]})}export{Xe as default};
|