omniroute 3.4.7 → 3.4.8
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/app/.next/BUILD_ID +1 -1
- package/app/.next/build-manifest.json +3 -3
- package/app/.next/prerender-manifest.json +3 -3
- package/app/.next/server/app/(dashboard)/dashboard/agents/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/analytics/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/api-manager/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/audit/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/auto-combo/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/cache/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/cli-tools/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/combos/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/costs/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/endpoint/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/health/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/limits/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/logs/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/media/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/memory/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/onboarding/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/playground/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/providers/[id]/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/providers/new/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/providers/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/search-tools/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/settings/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/settings/pricing/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/skills/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/translator/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/400/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/401/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/403/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/408/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/429/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/500/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/502/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/503/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/_global-error.html +1 -1
- package/app/.next/server/app/_global-error.rsc +1 -1
- package/app/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
- package/app/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/app/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
- package/app/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
- package/app/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/app/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/api/system/version/route.js.nft.json +1 -1
- package/app/.next/server/app/api/v1/api/chat/route.js +15 -15
- package/app/.next/server/app/api/v1/api/chat/route.js.nft.json +1 -1
- package/app/.next/server/app/api/v1/audio/speech/route.js +11 -11
- package/app/.next/server/app/api/v1/audio/speech/route.js.nft.json +1 -1
- package/app/.next/server/app/api/v1/audio/transcriptions/route.js +5 -5
- package/app/.next/server/app/api/v1/audio/transcriptions/route.js.nft.json +1 -1
- package/app/.next/server/app/api/v1/chat/completions/route.js +14 -14
- package/app/.next/server/app/api/v1/chat/completions/route.js.nft.json +1 -1
- package/app/.next/server/app/api/v1/completions/route.js +14 -14
- package/app/.next/server/app/api/v1/completions/route.js.nft.json +1 -1
- package/app/.next/server/app/api/v1/images/generations/route.js +10 -10
- package/app/.next/server/app/api/v1/images/generations/route.js.nft.json +1 -1
- package/app/.next/server/app/api/v1/messages/route.js +16 -16
- package/app/.next/server/app/api/v1/messages/route.js.nft.json +1 -1
- package/app/.next/server/app/api/v1/models/route.js +5 -5
- package/app/.next/server/app/api/v1/models/route.js.nft.json +1 -1
- package/app/.next/server/app/api/v1/moderations/route.js +9 -9
- package/app/.next/server/app/api/v1/moderations/route.js.nft.json +1 -1
- package/app/.next/server/app/api/v1/music/generations/route.js +10 -10
- package/app/.next/server/app/api/v1/providers/[provider]/chat/completions/route.js +16 -16
- package/app/.next/server/app/api/v1/providers/[provider]/chat/completions/route.js.nft.json +1 -1
- package/app/.next/server/app/api/v1/providers/[provider]/embeddings/route.js +7 -7
- package/app/.next/server/app/api/v1/providers/[provider]/embeddings/route.js.nft.json +1 -1
- package/app/.next/server/app/api/v1/providers/[provider]/images/generations/route.js +10 -10
- package/app/.next/server/app/api/v1/providers/[provider]/images/generations/route.js.nft.json +1 -1
- package/app/.next/server/app/api/v1/rerank/route.js +9 -9
- package/app/.next/server/app/api/v1/rerank/route.js.nft.json +1 -1
- package/app/.next/server/app/api/v1/responses/[...path]/route.js +16 -16
- package/app/.next/server/app/api/v1/responses/[...path]/route.js.nft.json +1 -1
- package/app/.next/server/app/api/v1/responses/route.js +16 -16
- package/app/.next/server/app/api/v1/responses/route.js.nft.json +1 -1
- package/app/.next/server/app/api/v1/route.js +5 -5
- package/app/.next/server/app/api/v1/route.js.nft.json +1 -1
- package/app/.next/server/app/api/v1/search/analytics/route.js +7 -7
- package/app/.next/server/app/api/v1/search/analytics/route.js.nft.json +1 -1
- package/app/.next/server/app/api/v1/videos/generations/route.js +10 -10
- package/app/.next/server/app/api/v1beta/models/[...path]/route.js +14 -14
- package/app/.next/server/app/api/v1beta/models/[...path]/route.js.nft.json +1 -1
- package/app/.next/server/app/callback/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/docs/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/forbidden/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/forgot-password/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/landing/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/login/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/maintenance/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/offline/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/privacy/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/status/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/terms/page_client-reference-manifest.js +1 -1
- package/app/.next/server/chunks/{[root-of-the-server]__0nxyldc._.js → [root-of-the-server]__0-zca2p._.js} +1 -1
- package/app/.next/server/chunks/{[root-of-the-server]__0urvs3.._.js → [root-of-the-server]__01hbf~_._.js} +1 -1
- package/app/.next/server/chunks/[root-of-the-server]__01ojood._.js +1 -1
- package/app/.next/server/chunks/[root-of-the-server]__030_-af._.js +1 -1
- package/app/.next/server/chunks/{[root-of-the-server]__0j~-yu1._.js → [root-of-the-server]__03l6k3k._.js} +1 -1
- package/app/.next/server/chunks/{[root-of-the-server]__01b8762._.js → [root-of-the-server]__05~jdzu._.js} +1 -1
- package/app/.next/server/chunks/{[root-of-the-server]__07eee_s._.js → [root-of-the-server]__08~6j3q._.js} +1 -1
- package/app/.next/server/chunks/[root-of-the-server]__0a8ozdb._.js +1 -1
- package/app/.next/server/chunks/[root-of-the-server]__0bd4ccn._.js +2 -2
- package/app/.next/server/chunks/{[root-of-the-server]__0_a98vk._.js → [root-of-the-server]__0d6bqbw._.js} +1 -1
- package/app/.next/server/chunks/{[root-of-the-server]__0_c_.ye._.js → [root-of-the-server]__0f2rz58._.js} +1 -1
- package/app/.next/server/chunks/[root-of-the-server]__0jp3yj4._.js +1 -1
- package/app/.next/server/chunks/{[root-of-the-server]__06stuoz._.js → [root-of-the-server]__0jvnjwl._.js} +1 -1
- package/app/.next/server/chunks/[root-of-the-server]__0mj7x5~._.js +1 -1
- package/app/.next/server/chunks/[root-of-the-server]__0n-~kvf._.js +1 -1
- package/app/.next/server/chunks/{[root-of-the-server]__0-y3k-t._.js → [root-of-the-server]__0nzi7ym._.js} +1 -1
- package/app/.next/server/chunks/[root-of-the-server]__0ofxxzh._.js +2 -2
- package/app/.next/server/chunks/{[root-of-the-server]__0uu3t5x._.js → [root-of-the-server]__0pd~24c._.js} +2 -2
- package/app/.next/server/chunks/[root-of-the-server]__0s1dq3.._.js +1 -1
- package/app/.next/server/chunks/[root-of-the-server]__0tsl88m._.js +1 -1
- package/app/.next/server/chunks/[root-of-the-server]__0u5-mph._.js +1 -1
- package/app/.next/server/chunks/{[root-of-the-server]__0vi3.0k._.js → [root-of-the-server]__0uryxsh._.js} +1 -1
- package/app/.next/server/chunks/{[root-of-the-server]__0lwc40h._.js → [root-of-the-server]__0v1kwmx._.js} +1 -1
- package/app/.next/server/chunks/{[root-of-the-server]__04y3b4q._.js → [root-of-the-server]__0vt49c9._.js} +1 -1
- package/app/.next/server/chunks/{[root-of-the-server]__0pylsu2._.js → [root-of-the-server]__0vy97gy._.js} +2 -2
- package/app/.next/server/chunks/{[root-of-the-server]__0~s45~f._.js → [root-of-the-server]__0wd~o5b._.js} +1 -1
- package/app/.next/server/chunks/[root-of-the-server]__0x5yxjy._.js +2 -2
- package/app/.next/server/chunks/{[root-of-the-server]__0vmajf6._.js → [root-of-the-server]__0x_hqjb._.js} +1 -1
- package/app/.next/server/chunks/[root-of-the-server]__0~0hd.s._.js +2 -2
- package/app/.next/server/chunks/{[root-of-the-server]__10~-ypp._.js → [root-of-the-server]__11ptf~3._.js} +1 -1
- package/app/.next/server/chunks/_00.pgsp._.js +1 -1
- package/app/.next/server/chunks/_013gowh._.js +1 -1
- package/app/.next/server/chunks/{_0ucpa5q._.js → _02._8wx._.js} +1 -1
- package/app/.next/server/chunks/_036lxbr._.js +1 -1
- package/app/.next/server/chunks/_05reh6o._.js +1 -1
- package/app/.next/server/chunks/{_0-~thzo._.js → _083_x9z._.js} +2 -2
- package/app/.next/server/chunks/_083a5zg._.js +1 -1
- package/app/.next/server/chunks/{_004r3br._.js → _08cwbl2._.js} +2 -2
- package/app/.next/server/chunks/_0a3.3sc._.js +1 -1
- package/app/.next/server/chunks/_0c.abwr._.js +1 -1
- package/app/.next/server/chunks/_0dfpto1._.js +1 -1
- package/app/.next/server/chunks/_0due8oe._.js +1 -1
- package/app/.next/server/chunks/_0h-j8c2._.js +1 -1
- package/app/.next/server/chunks/_0vx-r0i._.js +2 -2
- package/app/.next/server/chunks/_0w4f3bm._.js +1 -1
- package/app/.next/server/chunks/_10.rw9f._.js +1 -1
- package/app/.next/server/chunks/open-sse_0dawtxk._.js +2 -2
- package/app/.next/server/chunks/open-sse_0p~.88y._.js +1 -1
- package/app/.next/server/chunks/open-sse_0sthby3._.js +1 -1
- package/app/.next/server/chunks/src_0cbm0~g._.js +1 -1
- package/app/.next/server/chunks/src_shared_utils_apiKey_ts_0gzf59_._.js +1 -1
- package/app/.next/server/chunks/src_shared_utils_apiKey_ts_12~h.oz._.js +1 -1
- package/app/.next/server/chunks/ssr/_008ht2n._.js +1 -1
- package/app/.next/server/chunks/ssr/_0oo1f90._.js +1 -1
- package/app/.next/server/chunks/ssr/src_04s-8a5._.js +1 -1
- package/app/.next/server/chunks/ssr/src_0vjsxxr._.js +1 -1
- package/app/.next/server/chunks/ssr/src_shared_utils_apiKey_ts_0l8g1z8._.js +1 -1
- package/app/.next/server/middleware-build-manifest.js +3 -3
- package/app/.next/server/pages/500.html +1 -1
- package/app/.next/server/server-reference-manifest.js +1 -1
- package/app/.next/server/server-reference-manifest.json +1 -1
- package/app/.next/static/chunks/0ipwpwjb2g0uv.js +1 -0
- package/app/.next/static/chunks/0~c--kcvaumm~.js +1 -0
- package/app/.next/static/chunks/{02q7h~xz7j6i3.js → 0~v1trn07bitv.js} +1 -1
- package/app/CHANGELOG.md +12 -0
- package/app/bin/reset-password.mjs +3 -1
- package/app/docs/openapi.yaml +1 -1
- package/app/open-sse/config/registryUtils.ts +1 -0
- package/app/open-sse/config/videoRegistry.ts +1 -3
- package/app/open-sse/executors/antigravity.ts +22 -12
- package/app/open-sse/executors/gemini-cli.ts +3 -1
- package/app/open-sse/executors/qoder.ts +1 -8
- package/app/open-sse/handlers/audioSpeech.ts +1 -0
- package/app/open-sse/handlers/chatCore.ts +2 -1
- package/app/open-sse/handlers/embeddings.ts +1 -0
- package/app/open-sse/handlers/imageGeneration.ts +6 -2
- package/app/open-sse/handlers/musicGeneration.ts +9 -2
- package/app/open-sse/handlers/search.ts +1 -0
- package/app/open-sse/handlers/videoGeneration.ts +11 -3
- package/app/open-sse/mcp-server/index.ts +0 -1
- package/app/open-sse/package.json +1 -1
- package/app/open-sse/services/claudeCodeCompatible.ts +2 -2
- package/app/open-sse/services/modelCapabilities.ts +3 -4
- package/app/open-sse/services/qoderCli.ts +5 -2
- package/app/open-sse/services/tokenRefresh.ts +3 -1
- package/app/open-sse/services/usage.ts +13 -9
- package/app/open-sse/services/workflowFSM.ts +298 -61
- package/app/open-sse/translator/index.ts +5 -1
- package/app/open-sse/translator/response/gemini-to-openai.ts +5 -1
- package/app/open-sse/utils/progressTracker.ts +4 -1
- package/app/open-sse/utils/stream.ts +7 -1
- package/app/open-sse/utils/streamPayloadCollector.ts +5 -1
- package/app/package-lock.json +3 -3
- package/app/package.json +1 -1
- package/app/scripts/check-route-validation.mjs +3 -1
- package/app/scripts/i18n/apply-priority-overrides.mjs +7 -1
- package/app/scripts/prepublish.mjs +2 -2
- package/app/scripts/run-protocol-clients-tests.mjs +7 -1
- package/app/src/app/(dashboard)/dashboard/analytics/components/DiversityScoreCard.tsx +1 -1
- package/app/src/app/(dashboard)/dashboard/auto-combo/page.tsx +0 -1
- package/app/src/app/(dashboard)/dashboard/media/MediaPageClient.tsx +9 -3
- package/app/src/app/(dashboard)/dashboard/providers/[id]/page.tsx +25 -23
- package/app/src/app/(dashboard)/dashboard/search-tools/components/SearchHistory.tsx +3 -1
- package/app/src/app/api/auth/status/route.ts +1 -3
- package/app/src/app/api/mcp/sse/route.ts +2 -2
- package/app/src/app/api/mcp/status/route.ts +1 -2
- package/app/src/app/api/mcp/stream/route.ts +5 -3
- package/app/src/app/api/openapi/spec/route.ts +4 -1
- package/app/src/app/api/openapi/try/route.ts +4 -1
- package/app/src/app/api/providers/[id]/models/route.ts +4 -4
- package/app/src/app/api/providers/[id]/sync-models/route.ts +9 -3
- package/app/src/app/api/settings/auto-disable-accounts/route.ts +6 -1
- package/app/src/app/api/skills/[id]/route.ts +4 -1
- package/app/src/app/api/v1/issues/report/route.ts +9 -1
- package/app/src/app/api/v1beta/models/route.ts +8 -6
- package/app/src/app/api/webhooks/[id]/route.ts +9 -7
- package/app/src/domain/fallbackPolicy.ts +0 -1
- package/app/src/domain/modelAvailability.ts +0 -1
- package/app/src/domain/providerExpiration.ts +2 -6
- package/app/src/lib/db/models.ts +23 -13
- package/app/src/lib/evals/evalRunner.ts +0 -1
- package/app/src/lib/evals/scheduler.ts +2 -6
- package/app/src/lib/oauth/services/antigravity.ts +6 -1
- package/app/src/lib/oauth/services/kiro.ts +12 -2
- package/app/src/lib/oauth/services/oauth.ts +10 -2
- package/app/src/lib/oauth/utils/server.ts +4 -1
- package/app/src/lib/plugins/index.ts +2 -8
- package/app/src/lib/usageAnalytics.ts +5 -1
- package/app/src/mitm/manager.js +1 -1
- package/app/src/mitm/manager.ts +1 -1
- package/app/src/shared/components/Button.tsx +0 -1
- package/app/src/shared/components/Card.tsx +0 -2
- package/app/src/shared/components/FilterBar.tsx +4 -12
- package/app/src/shared/components/Input.tsx +1 -1
- package/app/src/shared/components/Modal.tsx +0 -1
- package/app/src/shared/components/NotificationToast.tsx +1 -3
- package/app/src/shared/components/Select.tsx +1 -1
- package/app/src/shared/components/Sidebar.tsx +3 -3
- package/app/src/shared/components/ThemeToggle.tsx +7 -1
- package/app/src/shared/constants/cliCompatProviders.ts +0 -1
- package/app/src/shared/constants/errorCodes.ts +114 -19
- package/app/src/shared/utils/apiKey.ts +2 -4
- package/app/src/shared/utils/fetchTimeout.ts +0 -1
- package/app/src/shared/utils/inputSanitizer.ts +8 -4
- package/app/src/shared/utils/requestTimeout.ts +5 -1
- package/app/src/sse/handlers/chat.ts +1 -0
- package/app/src/sse/services/auth.ts +8 -3
- package/app/src/sse/services/streamState.ts +5 -1
- package/app/src/store/notificationStore.ts +3 -7
- package/app/tests/unit/t20-t22-provider-headers.test.mjs +3 -1
- package/bin/reset-password.mjs +3 -1
- package/open-sse/mcp-server/__tests__/glmCodingProviderConfig.test.ts +5 -1
- package/open-sse/mcp-server/index.ts +0 -1
- package/package.json +1 -1
- package/app/.next/server/chunks/_0-jnvci._.js +0 -19
- package/app/.next/static/chunks/0l88mho31mflv.js +0 -1
- package/app/.next/static/chunks/0wt-4zl7_gil8.js +0 -1
- /package/app/.next/static/{ri1SkwBU-ygQ2qIDe8jf2 → 1dZBzAZ8QsddVCQRQtqjg}/_buildManifest.js +0 -0
- /package/app/.next/static/{ri1SkwBU-ygQ2qIDe8jf2 → 1dZBzAZ8QsddVCQRQtqjg}/_clientMiddlewareManifest.js +0 -0
- /package/app/.next/static/{ri1SkwBU-ygQ2qIDe8jf2 → 1dZBzAZ8QsddVCQRQtqjg}/_ssgManifest.js +0 -0
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
module.exports=[460176,a=>{"use strict";var b=a.i(743442);a.s(["OAuthModal",()=>b.default])},202373,a=>{"use strict";var b=a.i(394093);a.s(["KiroOAuthWrapper",()=>b.default])},182527,a=>{"use strict";var b=a.i(296193);a.s(["CursorAuthModal",()=>b.default])},794711,a=>{"use strict";a.s(["MODEL_COMPAT_PROTOCOL_KEYS",0,["openai","openai-responses","claude"]])},333474,a=>{"use strict";a.s(["resolveManagedModelAlias",0,function({modelId:a,fullModel:b,providerDisplayAlias:c,existingAliases:d}){let e=function(a){let b=a.trim();if(!b)return"";let c=b.split("/").map(a=>a.trim()).filter(Boolean);return c[c.length-1]||b}(a);if(!e)return null;for(let[a,c]of Object.entries(d))if(c===b)return a;let f=c.trim(),g=[],h=new Set,i=a=>{let b=a.trim();!b||h.has(b)||(h.add(b),g.push(b))};for(let a of(i(e),f&&i(`${f}-${e}`),g))if(!(a in d)||d[a]===b)return a;for(let a=2;a<=5e3;a+=1){if(f){let c=`${f}-${e}-${a}`;if(!(c in d)||d[c]===b)return c}let c=`${e}-${a}`;if(!(c in d)||d[c]===b)return c}return null}])},755235,a=>a.a(async(b,c)=>{try{var d=a.i(187924),e=a.i(572131),f=a.i(935112),g=a.i(240246),h=a.i(341212),i=a.i(50944),j=a.i(238246),k=a.i(571987),l=a.i(415925),m=a.i(442308),n=a.i(292216),o=a.i(294023),p=a.i(818465),q=a.i(489108),r=a.i(563203),s=a.i(831097),t=a.i(460176),u=a.i(202373),v=a.i(182527),w=a.i(709918),x=a.i(525290),y=a.i(248172),z=a.i(662073),A=a.i(867933),B=a.i(911655),C=a.i(455407),D=a.i(386592),E=a.i(794711),F=a.i(333474),G=b([m,z,A,C]);function H(a){let b=new Map;for(let c of a)c.id&&b.set(c.id,c);return b}function I(a,b,c){return a?.compatByProtocol?.[c]??b?.compatByProtocol?.[c]}function J(a,b,c,d){let e=c.get(a),f=d.get(a),g=I(e,f,b);return g&&Object.prototype.hasOwnProperty.call(g,"normalizeToolCallId")?!!g.normalizeToolCallId:!!e?.normalizeToolCallId||!!f?.normalizeToolCallId}function K(a,b,c,d){let e=c.get(a),f=d.get(a),g=I(e,f,b);return g&&Object.prototype.hasOwnProperty.call(g,"preserveOpenAIDeveloperRole")?!!g.preserveOpenAIDeveloperRole:e&&Object.prototype.hasOwnProperty.call(e,"preserveOpenAIDeveloperRole")?!!e.preserveOpenAIDeveloperRole:!(f&&Object.prototype.hasOwnProperty.call(f,"preserveOpenAIDeveloperRole"))||!!f.preserveOpenAIDeveloperRole}async function L(a){try{let b=await a.json(),c=b?.error;if(Array.isArray(c?.details)&&c.details.length>0)return c.details.map(a=>{let b="string"==typeof a.field&&a.field?a.field:"?",c="string"==typeof a.message?a.message:"";return c?`${b}: ${c}`:b}).join("; ");if("string"==typeof c?.message&&c.message.trim())return c.message.trim()}catch{}return a.statusText?.trim()||`HTTP ${a.status}`}function M(a,b,c,d){let e=c.get(a),f=d.get(a),g={};e?.upstreamHeaders&&"object"==typeof e.upstreamHeaders?Object.assign(g,e.upstreamHeaders):f?.upstreamHeaders&&"object"==typeof f.upstreamHeaders&&Object.assign(g,f.upstreamHeaders);let h=I(e,f,b);return h?.upstreamHeaders&&"object"==typeof h.upstreamHeaders&&Object.assign(g,h.upstreamHeaders),g}[m,z,A,C]=G.then?(await G)():G;let $="CC Compatible",_="CC Compatible Details",aa="/v1/messages?beta=true";function N(a){let b=a&&"object"==typeof a&&!Array.isArray(a)?a:{};return{use5h:"boolean"!=typeof b.use5h||b.use5h,useWeekly:"boolean"!=typeof b.useWeekly||b.useWeekly}}function O({t:a,effectiveModelNormalize:b,effectiveModelPreserveDeveloper:c,getUpstreamHeadersRecord:g,onCompatPatch:h,showDeveloperToggle:i=!0,disabled:j}){let[k,l]=(0,e.useState)(!1),[m,n]=(0,e.useState)(E.MODEL_COMPAT_PROTOCOL_KEYS[0]),[o,p]=(0,e.useState)([]),[r,s]=(0,e.useState)(null),[t,u]=(0,e.useState)(null),v=(0,e.useRef)(null),x=(0,e.useRef)(null),[y,z]=(0,e.useState)(null),A=(0,e.useRef)(0),B=(0,e.useRef)([]);B.current=o;let C=()=>(A.current+=1,`uh-${A.current}`),D=b(m),F=c(m),G=i&&"claude"!==m,H=(0,e.useCallback)(a=>{let b,c,d=function(a){let b={};for(let c of a){let a=c.name.trim();a&&(b[a]=c.value)}return b}(a),e=g(m);b=Object.keys(d).sort(),c=Object.keys(e).sort(),b.length===c.length&&b.every((a,b)=>a===c[b]&&d[a]===e[a])||h(m,{upstreamHeaders:d})},[g,h,m]),I=(0,e.useCallback)(()=>{queueMicrotask(()=>H(B.current))},[H]);(0,e.useEffect)(()=>{if(k)return()=>{H(B.current)}},[k,H]),(0,e.useEffect)(()=>{let a;if(!k)return;let b=g(m);p((a=Object.entries(b).filter(([a])=>a.trim()),0===a.length?[{id:C(),name:"",value:""}]:a.map(([a,b])=>({id:C(),name:a,value:b}))))},[k,m]),(0,e.useEffect)(()=>{s(null),u(null)},[k,m]);let J=o.filter(a=>a.name.trim()).length<16,K=(a,b)=>{p(c=>c.map(c=>c.id===a?{...c,...b}:c))};(0,e.useEffect)(()=>{if(!k)return;let a=a=>{let b=a.target,c=v.current?.contains(b),d=x.current?.contains(b);c||d||l(!1)};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[k]);let L=(0,e.useCallback)(()=>{if(!k||!v.current)return;let a=v.current.getBoundingClientRect(),b=Math.min(window.innerWidth-20,384),c=a.right-b;c=Math.max(10,Math.min(c,window.innerWidth-b-10)),z({top:a.bottom+8,left:c,width:b})},[k]);return(0,e.useLayoutEffect)(()=>k?(L(),window.addEventListener("resize",L),window.addEventListener("scroll",L,!0),()=>{window.removeEventListener("resize",L),window.removeEventListener("scroll",L,!0)}):void z(null),[k,L]),(0,d.jsxs)("div",{className:"relative inline-flex",ref:v,children:[(0,d.jsxs)("button",{type:"button",onClick:()=>l(a=>!a),disabled:j,className:"inline-flex items-center gap-1.5 px-2.5 py-1.5 text-xs font-medium rounded-lg border border-border bg-background text-text-muted hover:bg-muted hover:text-text-main disabled:opacity-50 transition-colors",title:a("compatAdjustmentsTitle"),children:[(0,d.jsx)("span",{className:"material-symbols-outlined text-base leading-none",children:"tune"}),a("compatButtonLabel")]}),k&&"u">typeof document&&y&&(0,f.createPortal)((0,d.jsxs)("div",{ref:x,className:"flex max-h-[min(82vh,42rem)] flex-col overflow-hidden rounded-xl border-2 border-zinc-200 bg-white shadow-2xl dark:border-zinc-600 dark:bg-zinc-950",style:{position:"fixed",top:y.top,left:y.left,width:y.width,zIndex:10040},children:[(0,d.jsxs)("div",{className:"shrink-0 border-b-2 border-zinc-200 bg-zinc-100 px-3 py-2.5 dark:border-zinc-600 dark:bg-zinc-900",children:[(0,d.jsx)("p",{className:"text-xs font-semibold text-text-main",children:a("compatAdjustmentsTitle")}),(0,d.jsx)("p",{className:"text-[11px] text-text-muted mt-1 leading-relaxed",children:a("compatProtocolHint")})]}),(0,d.jsxs)("div",{className:"min-h-0 flex-1 overflow-x-hidden overflow-y-auto bg-white p-3 [scrollbar-gutter:stable] [scrollbar-width:thin] dark:bg-zinc-950",children:[(0,d.jsx)("label",{className:"block text-[11px] font-medium text-text-muted mb-1.5",children:a("compatProtocolLabel")}),(0,d.jsx)("select",{value:m,onChange:a=>n(a.target.value),disabled:j,className:"mb-4 w-full rounded-lg border border-zinc-200 bg-white px-2.5 py-2 text-xs text-text-main focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/30 dark:border-zinc-600 dark:bg-zinc-900",children:E.MODEL_COMPAT_PROTOCOL_KEYS.map(b=>(0,d.jsx)("option",{value:b,children:a("openai"===b?"compatProtocolOpenAI":"openai-responses"===b?"compatProtocolOpenAIResponses":"claude"===b?"compatProtocolClaude":"compatProtocolOpenAI")},b))}),(0,d.jsxs)("div",{className:"flex flex-col gap-3.5",children:[(0,d.jsx)(w.Toggle,{size:"sm",label:a("compatToolIdShort"),title:a("normalizeToolCallIdLabel"),checked:D,onChange:a=>h(m,{normalizeToolCallId:a}),disabled:j}),G&&(0,d.jsx)(w.Toggle,{size:"sm",label:a("compatDoNotPreserveDeveloper"),title:a("preserveDeveloperRoleLabel"),checked:!1===F,onChange:a=>h(m,{preserveOpenAIDeveloperRole:!a}),disabled:j})]}),(0,d.jsxs)("div",{className:"mt-4 rounded-lg border-2 border-zinc-200 bg-zinc-100 p-3 dark:border-zinc-600 dark:bg-zinc-900",children:[(0,d.jsx)("label",{className:"block text-[11px] font-semibold text-text-main mb-1",children:a("compatUpstreamHeadersLabel")}),(0,d.jsx)("p",{className:"text-[11px] text-text-muted mb-3 leading-relaxed",children:a("compatUpstreamHeadersHint")}),(0,d.jsxs)("div",{className:"space-y-2",children:[(0,d.jsxs)("div",{className:"grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)_auto] gap-1.5 items-end text-[10px] font-medium uppercase tracking-wide text-text-muted px-0.5",children:[(0,d.jsx)("span",{children:a("compatUpstreamHeaderName")}),(0,d.jsx)("span",{className:"col-span-1",children:a("compatUpstreamHeaderValue")}),(0,d.jsx)("span",{className:"w-8 shrink-0","aria-hidden":!0})]}),o.map(b=>(0,d.jsxs)("div",{className:"grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)_auto] gap-1.5 items-center",children:[(0,d.jsx)(q.Input,{value:b.name,onChange:a=>K(b.id,{name:a.target.value}),onBlur:I,disabled:j,placeholder:"Authentication",className:"gap-0 min-w-0",inputClassName:"h-9 bg-white py-1.5 px-2 text-xs font-mono dark:bg-zinc-900",autoComplete:"off"}),(0,d.jsx)("div",{className:"min-w-0",onMouseEnter:()=>s(b.id),onMouseLeave:()=>s(a=>a===b.id?null:a),children:(0,d.jsx)(q.Input,{type:r===b.id||t===b.id?"text":"password",value:b.value,onChange:a=>K(b.id,{value:a.target.value}),onFocus:()=>u(b.id),onBlur:()=>{u(a=>a===b.id?null:a),I()},disabled:j,placeholder:"•••",className:"gap-0 min-w-0",inputClassName:"h-9 bg-white py-1.5 px-2 text-xs dark:bg-zinc-900",autoComplete:"off",spellCheck:!1})}),(0,d.jsx)("button",{type:"button",disabled:j||o.length<=1,onClick:()=>{var a;return a=b.id,void p(b=>{let c=b.filter(b=>b.id!==a),d=0===c.length?[{id:C(),name:"",value:""}]:c;return queueMicrotask(()=>H(d)),d})},title:a("compatUpstreamRemoveRow"),className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg border border-border/80 text-text-muted hover:bg-red-500/10 hover:text-red-600 dark:hover:text-red-400 disabled:opacity-30 disabled:hover:bg-transparent disabled:hover:text-text-muted transition-colors",children:(0,d.jsx)("span",{className:"material-symbols-outlined text-lg leading-none",children:"close"})})]},b.id))]}),(0,d.jsxs)("button",{type:"button",disabled:j||!J,onClick:()=>{J&&p(a=>[...a,{id:C(),name:"",value:""}])},className:"mt-3 flex w-full items-center justify-center gap-1.5 rounded-lg border border-dashed border-border py-2 text-xs font-medium text-primary hover:bg-primary/5 disabled:opacity-40 disabled:hover:bg-transparent transition-colors",children:[(0,d.jsx)("span",{className:"material-symbols-outlined text-base leading-none",children:"add"}),a("compatUpstreamAddRow")]})]})]})]}),document.body)]})}function P({model:a,fullModel:b,copied:c,onCopy:e,t:f,showDeveloperToggle:g=!0,effectiveModelNormalize:h,effectiveModelPreserveDeveloper:i,getUpstreamHeadersRecord:j,saveModelCompatFlags:k,compatDisabled:l}){return(0,d.jsxs)("div",{className:"flex min-w-[220px] max-w-md items-center gap-2 rounded-lg border border-border px-3 py-2 hover:bg-sidebar/50",children:[(0,d.jsxs)("div",{className:"flex min-w-0 flex-1 flex-wrap items-center gap-2",children:[(0,d.jsx)("span",{className:"material-symbols-outlined shrink-0 text-base text-text-muted",children:"smart_toy"}),(0,d.jsx)("code",{className:"rounded bg-sidebar px-1.5 py-0.5 font-mono text-xs text-text-muted",children:b}),(0,d.jsx)("button",{onClick:()=>e(b,`model-${a.id}`),className:"rounded p-0.5 text-text-muted hover:bg-sidebar hover:text-primary",title:f("copyModel"),children:(0,d.jsx)("span",{className:"material-symbols-outlined text-sm",children:c===`model-${a.id}`?"check":"content_copy"})})]}),(0,d.jsx)("div",{className:"shrink-0",children:(0,d.jsx)(O,{t:f,effectiveModelNormalize:b=>h(a.id,b),effectiveModelPreserveDeveloper:b=>i(a.id,b),getUpstreamHeadersRecord:j,onCompatPatch:(b,c)=>k(a.id,{compatByProtocol:{[b]:c}}),showDeveloperToggle:g,disabled:l})})]})}function Q({providerAlias:a,modelAliases:b,copied:c,onCopy:f,onSetAlias:g,onDeleteAlias:h,t:i,effectiveModelNormalize:j,effectiveModelPreserveDeveloper:k,getUpstreamHeadersRecord:l,saveModelCompatFlags:m,compatSavingModelId:n}){let[p,q]=(0,e.useState)(""),[r,s]=(0,e.useState)(!1),t=Object.entries(b).filter(([,b])=>b.startsWith(`${a}/`)).map(([b,c])=>({modelId:c.replace(`${a}/`,""),fullModel:c,alias:b})),u=async()=>{let a;if(!p.trim()||r)return;let c=p.trim(),d=(a=c.split("/"))[a.length-1];if(b[d])return void alert(i("aliasExistsAlert",{alias:d}));s(!0);try{await g(c,d),q("")}catch(a){console.log("Error adding model:",a)}finally{s(!1)}};return(0,d.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,d.jsx)("p",{className:"text-sm text-text-muted",children:i("openRouterAnyModelHint")}),(0,d.jsxs)("div",{className:"flex items-end gap-2",children:[(0,d.jsxs)("div",{className:"flex-1",children:[(0,d.jsx)("label",{htmlFor:"new-model-input",className:"text-xs text-text-muted mb-1 block",children:i("modelIdFromOpenRouter")}),(0,d.jsx)("input",{id:"new-model-input",type:"text",value:p,onChange:a=>q(a.target.value),onKeyDown:a=>"Enter"===a.key&&u(),placeholder:i("openRouterModelPlaceholder"),className:"w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"})]}),(0,d.jsx)(o.Button,{size:"sm",icon:"add",onClick:u,disabled:!p.trim()||r,children:r?i("adding"):i("add")})]}),t.length>0&&(0,d.jsx)("div",{className:"flex flex-col gap-3",children:t.map(({modelId:a,fullModel:b,alias:e})=>(0,d.jsx)(R,{modelId:a,fullModel:b,copied:c,onCopy:f,onDeleteAlias:()=>h(e),t:i,showDeveloperToggle:!0,effectiveModelNormalize:j,effectiveModelPreserveDeveloper:k,getUpstreamHeadersRecord:b=>l(a,b),saveModelCompatFlags:m,compatDisabled:n===a},b))})]})}function R({modelId:a,fullModel:b,copied:c,onCopy:e,onDeleteAlias:f,t:g,showDeveloperToggle:h=!0,effectiveModelNormalize:i,effectiveModelPreserveDeveloper:j,getUpstreamHeadersRecord:k,saveModelCompatFlags:l,compatDisabled:m}){return(0,d.jsxs)("div",{className:"flex gap-0 rounded-lg border border-border p-3 hover:bg-sidebar/50",children:[(0,d.jsxs)("div",{className:"flex min-w-0 flex-1 items-start gap-3",children:[(0,d.jsx)("span",{className:"material-symbols-outlined shrink-0 text-base text-text-muted",children:"smart_toy"}),(0,d.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,d.jsx)("p",{className:"truncate text-sm font-medium",children:a}),(0,d.jsxs)("div",{className:"mt-1 flex flex-wrap items-center gap-1",children:[(0,d.jsx)("code",{className:"rounded bg-sidebar px-1.5 py-0.5 font-mono text-xs text-text-muted",children:b}),(0,d.jsx)("button",{onClick:()=>e(b,`model-${a}`),className:"rounded p-0.5 text-text-muted hover:bg-sidebar hover:text-primary",title:g("copyModel"),children:(0,d.jsx)("span",{className:"material-symbols-outlined text-sm",children:c===`model-${a}`?"check":"content_copy"})})]})]})]}),(0,d.jsxs)("div",{className:"flex shrink-0 items-center gap-1 self-start",children:[(0,d.jsx)(O,{t:g,effectiveModelNormalize:b=>i(a,b),effectiveModelPreserveDeveloper:b=>j(a,b),getUpstreamHeadersRecord:k,onCompatPatch:(b,c)=>l(a,{compatByProtocol:{[b]:c}}),showDeveloperToggle:h,disabled:m}),(0,d.jsx)("button",{onClick:f,className:"rounded p-1 text-red-500 hover:bg-red-50",title:g("removeModel"),children:(0,d.jsx)("span",{className:"material-symbols-outlined text-sm",children:"delete"})})]})]})}function S({providerId:a,providerAlias:b,copied:c,onCopy:f,onModelsChanged:h}){let i=(0,l.useTranslations)("providers"),j=(0,g.useNotificationStore)(),[k,m]=(0,e.useState)([]),[n,p]=(0,e.useState)([]),[q,r]=(0,e.useState)(""),[s,t]=(0,e.useState)(""),[u,v]=(0,e.useState)("chat-completions"),[w,x]=(0,e.useState)(["chat"]),[y,z]=(0,e.useState)(!1),[A,B]=(0,e.useState)(!0),[C,D]=(0,e.useState)(null),[F,G]=(0,e.useState)("chat-completions"),[N,P]=(0,e.useState)(["chat"]),[Q,R]=(0,e.useState)(null),T=(0,e.useMemo)(()=>H(k),[k]),U=(0,e.useMemo)(()=>H(n),[n]),V=(0,e.useCallback)(async()=>{try{let b=await fetch(`/api/provider-models?provider=${encodeURIComponent(a)}`);if(b.ok){let a=await b.json();m(a.models||[]),p(a.modelCompatOverrides||[])}}catch(a){console.error("Failed to fetch custom models:",a)}finally{B(!1)}},[a]);(0,e.useEffect)(()=>{V()},[V]);let W=async()=>{if(q.trim()&&!y){z(!0);try{(await fetch("/api/provider-models",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:a,modelId:q.trim(),modelName:s.trim()||void 0,apiFormat:u,supportedEndpoints:w})})).ok&&(r(""),t(""),v("chat-completions"),x(["chat"]),await V(),h?.())}catch(a){console.error("Failed to add custom model:",a)}finally{z(!1)}}},X=async b=>{try{await fetch(`/api/provider-models?provider=${encodeURIComponent(a)}&model=${encodeURIComponent(b)}`,{method:"DELETE"}),await V(),h?.()}catch(a){console.error("Failed to remove custom model:",a)}},Y=()=>{D(null),G("chat-completions"),P(["chat"]),R(null)},Z=async(b,c)=>{R(b);try{let d=await fetch("/api/provider-models",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:a,modelId:b,...c})});if(!d.ok){let a=await L(d);j.error(a?`${i("failedSaveCustomModel")} — ${a}`:i("failedSaveCustomModel"));return}}catch{j.error(i("failedSaveCustomModel"));return}finally{R(null)}try{await V(),h?.()}catch{}},$=async b=>{if(C&&C===b){if(!N.length)return void j.error("Select at least one supported endpoint");R(b);try{let c=k.find(a=>a.id===b),d=await fetch("/api/provider-models",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:a,modelId:b,modelName:c?.name||b,source:c?.source||"manual",apiFormat:F,supportedEndpoints:N})});if(!d.ok){let a=await L(d);throw Error(a||"Failed to save model endpoint settings")}await V(),h?.(),j.success("Saved model endpoint settings"),Y()}catch(a){console.error("Failed to save custom model:",a),j.error(a instanceof Error&&a.message?a.message:"Failed to save model endpoint settings")}finally{R(null)}}};return(0,d.jsxs)("div",{className:"mt-6 pt-6 border-t border-border",children:[(0,d.jsxs)("h3",{className:"text-sm font-semibold mb-3 flex items-center gap-2",children:[(0,d.jsx)("span",{className:"material-symbols-outlined text-base text-primary",children:"tune"}),i("customModels")]}),(0,d.jsx)("p",{className:"text-xs text-text-muted mb-3",children:i("customModelsHint")}),(0,d.jsxs)("div",{className:"flex flex-col gap-3 mb-3",children:[(0,d.jsxs)("div",{className:"flex items-end gap-2",children:[(0,d.jsxs)("div",{className:"flex-1",children:[(0,d.jsx)("label",{htmlFor:"custom-model-id",className:"text-xs text-text-muted mb-1 block",children:i("modelId")}),(0,d.jsx)("input",{id:"custom-model-id",type:"text",value:q,onChange:a=>r(a.target.value),onKeyDown:a=>"Enter"===a.key&&W(),placeholder:i("customModelPlaceholder"),className:"w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"})]}),(0,d.jsxs)("div",{className:"w-40",children:[(0,d.jsx)("label",{htmlFor:"custom-model-name",className:"text-xs text-text-muted mb-1 block",children:i("displayName")}),(0,d.jsx)("input",{id:"custom-model-name",type:"text",value:s,onChange:a=>t(a.target.value),onKeyDown:a=>"Enter"===a.key&&W(),placeholder:i("optional"),className:"w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"})]}),(0,d.jsx)(o.Button,{size:"sm",icon:"add",onClick:W,disabled:!q.trim()||y,children:y?i("adding"):i("add")})]}),(0,d.jsxs)("div",{className:"flex items-end gap-4 flex-wrap",children:[(0,d.jsxs)("div",{className:"w-48",children:[(0,d.jsx)("label",{htmlFor:"custom-api-format",className:"text-xs text-text-muted mb-1 block",children:"API Format"}),(0,d.jsxs)("select",{id:"custom-api-format",value:u,onChange:a=>v(a.target.value),className:"w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary",children:[(0,d.jsx)("option",{value:"chat-completions",children:"Chat Completions"}),(0,d.jsx)("option",{value:"responses",children:"Responses API"})]})]}),(0,d.jsxs)("div",{className:"flex-1",children:[(0,d.jsx)("span",{className:"text-xs text-text-muted mb-1 block",children:"Supported Endpoints"}),(0,d.jsx)("div",{className:"flex items-center gap-3",children:["chat","embeddings","images","audio"].map(a=>(0,d.jsxs)("label",{className:"flex items-center gap-1.5 text-xs text-text-main cursor-pointer",children:[(0,d.jsx)("input",{type:"checkbox",checked:w.includes(a),onChange:b=>{b.target.checked?x(b=>[...b,a]):x(b=>b.filter(b=>b!==a))},className:"rounded border-border"}),"chat"===a?"💬 Chat":"embeddings"===a?"📐 Embeddings":"images"===a?"🖼️ Images":"🔊 Audio"]},a))})]})]})]}),A?(0,d.jsx)("p",{className:"text-xs text-text-muted",children:i("loading")}):k.length>0?(0,d.jsx)("div",{className:"flex flex-col gap-2",children:k.map(a=>{let e=`${b}/${a.id}`,g=`custom-${a.id}`;return(0,d.jsxs)("div",{className:"flex items-center gap-3 rounded-lg border border-border p-3 hover:bg-sidebar/50",children:[C!==a.id&&(0,d.jsx)("span",{className:"material-symbols-outlined text-base text-primary shrink-0",children:"tune"}),(0,d.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,d.jsx)("p",{className:"text-sm font-medium truncate",children:a.name||a.id}),(0,d.jsxs)("div",{className:"flex items-center gap-1 mt-1 flex-wrap",children:[(0,d.jsx)("code",{className:"text-xs text-text-muted font-mono bg-sidebar px-1.5 py-0.5 rounded",children:e}),(0,d.jsx)("button",{onClick:()=>f(e,g),className:"p-0.5 hover:bg-sidebar rounded text-text-muted hover:text-primary",title:i("copyModel"),children:(0,d.jsx)("span",{className:"material-symbols-outlined text-sm",children:c===g?"check":"content_copy"})}),"responses"===a.apiFormat&&(0,d.jsx)("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-blue-500/15 text-blue-400 font-medium",children:"Responses"}),a.supportedEndpoints?.includes("embeddings")&&(0,d.jsx)("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-purple-500/15 text-purple-400 font-medium",children:"📐 Embed"}),a.supportedEndpoints?.includes("images")&&(0,d.jsx)("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-amber-500/15 text-amber-400 font-medium",children:"🖼️ Images"}),a.supportedEndpoints?.includes("audio")&&(0,d.jsx)("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-green-500/15 text-green-400 font-medium",children:"🔊 Audio"}),function(a,b,c){let d=b.get(a),e=c.get(a);if(d?.normalizeToolCallId||e?.normalizeToolCallId)return!0;for(let a of E.MODEL_COMPAT_PROTOCOL_KEYS){let b=I(d,e,a);if(b?.normalizeToolCallId)return!0}return!1}(a.id,T,U)&&(0,d.jsx)("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-slate-500/15 text-slate-400 font-medium",title:i("normalizeToolCallIdLabel"),children:"ID×9"}),function(a,b,c){let d=b.get(a),e=c.get(a);if(d&&Object.prototype.hasOwnProperty.call(d,"preserveOpenAIDeveloperRole")&&!1===d.preserveOpenAIDeveloperRole||e&&Object.prototype.hasOwnProperty.call(e,"preserveOpenAIDeveloperRole")&&!1===e.preserveOpenAIDeveloperRole)return!0;for(let a of E.MODEL_COMPAT_PROTOCOL_KEYS){let b=I(d,e,a);if(b&&Object.prototype.hasOwnProperty.call(b,"preserveOpenAIDeveloperRole")&&!1===b.preserveOpenAIDeveloperRole)return!0}return!1}(a.id,T,U)&&(0,d.jsx)("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-cyan-500/15 text-cyan-400 font-medium",title:i("compatDoNotPreserveDeveloper"),children:i("compatBadgeNoPreserve")}),function(a,b,c){let d=b.get(a),e=c.get(a),f=a=>a&&"object"==typeof a&&!Array.isArray(a)&&Object.keys(a).length>0;if(f(d?.upstreamHeaders)||f(e?.upstreamHeaders))return!0;for(let a of E.MODEL_COMPAT_PROTOCOL_KEYS){let b=I(d,e,a);if(f(b?.upstreamHeaders))return!0}return!1}(a.id,T,U)&&(0,d.jsx)("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-violet-500/15 text-violet-400 font-medium",title:i("compatUpstreamHeadersLabel"),children:i("compatBadgeUpstreamHeaders")})]}),C===a.id&&(0,d.jsx)("div",{className:"mt-3 min-w-0 max-w-full rounded-lg border border-border bg-muted p-3 dark:bg-zinc-900",children:(0,d.jsxs)("div",{className:"flex min-w-0 flex-wrap items-end gap-x-3 gap-y-2",children:[(0,d.jsxs)("div",{className:"w-[11rem] shrink-0 min-w-0",children:[(0,d.jsx)("label",{className:"text-xs text-text-muted mb-1 block",children:"API Format"}),(0,d.jsxs)("select",{value:F,onChange:a=>G(a.target.value),className:"w-full px-2.5 py-2 text-xs border border-border rounded-lg bg-background text-text-main focus:outline-none focus:border-primary",children:[(0,d.jsx)("option",{value:"chat-completions",children:"Chat Completions"}),(0,d.jsx)("option",{value:"responses",children:"Responses API"})]})]}),(0,d.jsxs)("div",{className:"flex min-w-0 flex-1 flex-wrap items-center gap-x-3 gap-y-1 overflow-x-auto overflow-y-visible [scrollbar-width:thin]",children:[(0,d.jsx)("span",{className:"text-xs text-text-muted shrink-0",children:"Supported Endpoints"}),(0,d.jsx)("div",{className:"flex flex-wrap items-center gap-x-2 sm:gap-x-3 gap-y-1 min-w-0",children:["chat","embeddings","images","audio"].map(a=>(0,d.jsxs)("label",{className:"flex items-center gap-1.5 text-xs text-text-main cursor-pointer whitespace-nowrap",children:[(0,d.jsx)("input",{type:"checkbox",checked:N.includes(a),onChange:b=>{b.target.checked?P(b=>b.includes(a)?b:[...b,a]):P(b=>b.filter(b=>b!==a))},className:"rounded border-border"}),"chat"===a?"💬 Chat":"embeddings"===a?"📐 Embeddings":"images"===a?"🖼️ Images":"🔊 Audio"]},a))})]}),(0,d.jsxs)("div",{className:"flex shrink-0 flex-wrap items-center gap-2 pb-0.5",children:[(0,d.jsx)(o.Button,{size:"sm",onClick:()=>$(a.id),disabled:Q===a.id,children:Q===a.id?i("saving"):i("save")}),(0,d.jsx)(o.Button,{size:"sm",variant:"ghost",onClick:Y,children:i("cancel")})]})]})})]}),(0,d.jsxs)("div",{className:"flex shrink-0 items-center gap-1",children:[(0,d.jsx)("button",{onClick:()=>{D(a.id),G(a.apiFormat||"chat-completions"),P(Array.isArray(a.supportedEndpoints)&&a.supportedEndpoints.length?a.supportedEndpoints:["chat"])},className:"rounded p-1 text-text-muted hover:bg-sidebar hover:text-primary",title:i("edit"),children:(0,d.jsx)("span",{className:"material-symbols-outlined text-sm",children:"edit"})}),(0,d.jsx)(O,{t:i,effectiveModelNormalize:b=>J(a.id,b,T,U),effectiveModelPreserveDeveloper:b=>K(a.id,b,T,U),getUpstreamHeadersRecord:b=>M(a.id,b,T,U),onCompatPatch:(b,c)=>Z(a.id,{compatByProtocol:{[b]:c}}),showDeveloperToggle:!0,disabled:Q===a.id}),(0,d.jsx)("button",{onClick:()=>X(a.id),className:"rounded p-1 text-red-500 hover:bg-red-50",title:i("removeCustomModel"),children:(0,d.jsx)("span",{className:"material-symbols-outlined text-sm",children:"delete"})})]})]},a.id)})}):(0,d.jsx)("p",{className:"text-xs text-text-muted",children:i("noCustomModels")})]})}function T({providerStorageAlias:a,providerDisplayAlias:b,modelAliases:c,fallbackModels:f=[],description:h,inputLabel:i,inputPlaceholder:j,copied:k,onCopy:l,onSetAlias:m,onDeleteAlias:n,connections:p,isAnthropic:q,onImportWithProgress:r,t:s,effectiveModelNormalize:t,effectiveModelPreserveDeveloper:u,getUpstreamHeadersRecord:v,saveModelCompatFlags:w,compatSavingModelId:x,onModelsChanged:y,allowImport:z}){let[A,B]=(0,e.useState)(""),[C,D]=(0,e.useState)(!1),[E,G]=(0,e.useState)(!1),H=(0,g.useNotificationStore)(),I=(0,e.useMemo)(()=>Object.entries(c).filter(([,b])=>b.startsWith(`${a}/`)),[c,a]),J=(0,e.useMemo)(()=>{let b=I.map(([b,c])=>({modelId:c.replace(`${a}/`,""),alias:b})),c=new Set(b.map(a=>a.modelId));for(let a of f)!a?.id||c.has(a.id)||(b.push({modelId:a.id,alias:null}),c.add(a.id));return b},[f,I,a]),K=(0,e.useCallback)((c,d)=>(0,F.resolveManagedModelAlias)({modelId:c,fullModel:`${a}/${c}`,providerDisplayAlias:b,existingAliases:d}),[b,a]),L=async()=>{if(!A.trim()||C)return;let b=A.trim(),d=K(b,c);if(!d)return void H.error(s("allSuggestedAliasesExist"));D(!0);try{let c=await fetch("/api/provider-models",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:a,modelId:b,modelName:b,source:"manual"})});if(!c.ok){let a={};try{a=await c.json()}catch(a){console.error("Failed to parse error response from custom model API:",a)}throw Error(a.error?.message||s("failedSaveCustomModel"))}await m(b,d,a),B(""),H.success(s("modelAddedSuccess",{modelId:b})),y?.()}catch(a){console.error("Error adding model:",a),H.error(a instanceof Error?a.message:s("failedAddModelTryAgain"))}finally{D(!1)}},M=async()=>{if(!z||E)return;let b=p.find(a=>!1!==a.isActive);if(b){G(!0);try{let d={...c};await r(async()=>{let a=await fetch(`/api/providers/${b.id}/models`),c=await a.json();if(!a.ok)throw Error(c.error||s("failedImportModels"));return c},async b=>{let c=b.id||b.name||b.model;if(!c)return!1;let e=K(c,d);return!!e&&((await fetch("/api/provider-models",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:a,modelId:c,modelName:b.name||c,source:"imported"})})).ok?(await m(c,e,a),d[e]=`${a}/${c}`,!0):(H.error(s("failedSaveImportedModel")),!1))})}catch(a){console.error("Error importing models:",a),H.error(s("failedImportModelsTryAgain"))}finally{G(!1)}}},N=p.some(a=>!1!==a.isActive),O=async(b,c)=>{try{if(!(await fetch(`/api/provider-models?provider=${encodeURIComponent(a)}&model=${encodeURIComponent(b)}`,{method:"DELETE"})).ok)throw Error(s("failedRemoveModelFromDatabase"));c&&await n(c),H.success(s("modelRemovedSuccess")),y?.()}catch(a){console.error("Error deleting model:",a),H.error(a instanceof Error?a.message:s("failedDeleteModelTryAgain"))}};return(0,d.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,d.jsx)("p",{className:"text-sm text-text-muted",children:h}),(0,d.jsxs)("div",{className:"flex items-end gap-2 flex-wrap",children:[(0,d.jsxs)("div",{className:"flex-1 min-w-[240px]",children:[(0,d.jsx)("label",{htmlFor:"new-compatible-model-input",className:"text-xs text-text-muted mb-1 block",children:i}),(0,d.jsx)("input",{id:"new-compatible-model-input",type:"text",value:A,onChange:a=>B(a.target.value),onKeyDown:a=>"Enter"===a.key&&L(),placeholder:j,className:"w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"})]}),(0,d.jsx)(o.Button,{size:"sm",icon:"add",onClick:L,disabled:!A.trim()||C,children:C?s("adding"):s("add")}),z&&(0,d.jsx)(o.Button,{size:"sm",variant:"secondary",icon:"download",onClick:M,disabled:!N||E,children:E?s("importingModels"):s("importFromModels")})]}),z&&!N&&(0,d.jsx)("p",{className:"text-xs text-text-muted",children:s("addConnectionToImport")}),J.length>0&&(0,d.jsx)("div",{className:"flex flex-col gap-3",children:J.map(({modelId:c,alias:e})=>(0,d.jsx)(R,{modelId:c,fullModel:`${b}/${c}`,copied:k,onCopy:l,onDeleteAlias:()=>O(c,e),t:s,showDeveloperToggle:!q,effectiveModelNormalize:t,effectiveModelPreserveDeveloper:u,getUpstreamHeadersRecord:a=>v(c,a),saveModelCompatFlags:w,compatDisabled:x===c},`${a}:${c}`))})]})}function U({until:a}){let[b,c]=(0,e.useState)("");return((0,e.useEffect)(()=>{let b=()=>{let b=new Date(a).getTime()-Date.now();if(b<=0)return void c("");let d=Math.floor(b/1e3);if(d<60)c(`${d}s`);else if(d<3600)c(`${Math.floor(d/60)}m ${d%60}s`);else{let a=Math.floor(d/3600),b=Math.floor(d%3600/60);c(`${a}h ${b}m`)}};b();let d=setInterval(b,1e3);return()=>clearInterval(d)},[a]),b)?(0,d.jsxs)("span",{className:"text-xs text-orange-500 font-mono",children:["⏱ ",b]}):null}P.propTypes={model:h.default.shape({id:h.default.string.isRequired}).isRequired,fullModel:h.default.string.isRequired,copied:h.default.string,onCopy:h.default.func.isRequired,t:h.default.func,showDeveloperToggle:h.default.bool,effectiveModelNormalize:h.default.func.isRequired,effectiveModelPreserveDeveloper:h.default.func.isRequired,getUpstreamHeadersRecord:h.default.func.isRequired,saveModelCompatFlags:h.default.func.isRequired,compatDisabled:h.default.bool},Q.propTypes={providerAlias:h.default.string.isRequired,modelAliases:h.default.object.isRequired,copied:h.default.string,onCopy:h.default.func.isRequired,onSetAlias:h.default.func.isRequired,onDeleteAlias:h.default.func.isRequired,t:h.default.func.isRequired,effectiveModelNormalize:h.default.func.isRequired,effectiveModelPreserveDeveloper:h.default.func.isRequired,getUpstreamHeadersRecord:h.default.func.isRequired,saveModelCompatFlags:h.default.func.isRequired,compatSavingModelId:h.default.string},R.propTypes={modelId:h.default.string.isRequired,fullModel:h.default.string.isRequired,copied:h.default.string,onCopy:h.default.func.isRequired,onDeleteAlias:h.default.func.isRequired,t:h.default.func,showDeveloperToggle:h.default.bool,effectiveModelNormalize:h.default.func.isRequired,effectiveModelPreserveDeveloper:h.default.func.isRequired,getUpstreamHeadersRecord:h.default.func.isRequired,saveModelCompatFlags:h.default.func.isRequired,compatDisabled:h.default.bool},S.propTypes={providerId:h.default.string.isRequired,providerAlias:h.default.string.isRequired,copied:h.default.string,onCopy:h.default.func.isRequired,onModelsChanged:h.default.func},T.propTypes={providerStorageAlias:h.default.string.isRequired,providerDisplayAlias:h.default.string.isRequired,modelAliases:h.default.object.isRequired,fallbackModels:h.default.array,description:h.default.string.isRequired,inputLabel:h.default.string.isRequired,inputPlaceholder:h.default.string.isRequired,copied:h.default.string,onCopy:h.default.func.isRequired,onSetAlias:h.default.func.isRequired,onDeleteAlias:h.default.func.isRequired,connections:h.default.arrayOf(h.default.shape({id:h.default.string,isActive:h.default.bool})).isRequired,isAnthropic:h.default.bool,onImportWithProgress:h.default.func.isRequired,t:h.default.func.isRequired,effectiveModelNormalize:h.default.func.isRequired,effectiveModelPreserveDeveloper:h.default.func.isRequired,getUpstreamHeadersRecord:h.default.func.isRequired,saveModelCompatFlags:h.default.func.isRequired,compatSavingModelId:h.default.string,onModelsChanged:h.default.func,allowImport:h.default.bool.isRequired},U.propTypes={until:h.default.string.isRequired};let ab={runtime_error:{labelKey:"errorTypeRuntime",variant:"warning"},upstream_auth_error:{labelKey:"errorTypeUpstreamAuth",variant:"error"},account_deactivated:{labelKey:"Account Deactivated",variant:"error"},auth_missing:{labelKey:"errorTypeMissingCredential",variant:"warning"},token_refresh_failed:{labelKey:"errorTypeRefreshFailed",variant:"warning"},token_expired:{labelKey:"errorTypeTokenExpired",variant:"warning"},upstream_rate_limited:{labelKey:"errorTypeRateLimited",variant:"warning"},upstream_unavailable:{labelKey:"errorTypeUpstreamUnavailable",variant:"error"},network_error:{labelKey:"errorTypeNetworkError",variant:"warning"},unsupported:{labelKey:"errorTypeTestUnsupported",variant:"default"},upstream_error:{labelKey:"errorTypeUpstreamError",variant:"error"},banned:{labelKey:"403 Banned",variant:"error"},credits_exhausted:{labelKey:"No Credits",variant:"warning"}};function V({connection:a,isOAuth:b,isCodex:c,isFirst:f,isLast:g,onMoveUp:h,onMoveDown:i,onToggleActive:j,onToggleRateLimit:k,onToggleCodex5h:m,onToggleCodexWeekly:n,onRetest:q,isRetesting:r,onEdit:s,onDelete:t,onReauth:u,onProxy:v,hasProxy:x,proxySource:y,proxyHost:z,onRefreshToken:A,isRefreshing:B,onApplyCodexAuthLocal:C,isApplyingCodexAuthLocal:D,onExportCodexAuthFile:E,isExportingCodexAuthFile:F}){let G,H=(0,l.useTranslations)("providers"),I=b?a.name||a.email||a.displayName||H("oauthAccount"):a.name,J="function"==typeof H.has&&H.has("applyCodexAuthLocal")?H("applyCodexAuthLocal"):"Apply auth",K="function"==typeof H.has&&H.has("exportCodexAuthFile")?H("exportCodexAuthFile"):"Export auth",[L,M]=(0,e.useState)(!1),[O,P]=(0,e.useState)(()=>{if(!b||!a.expiresAt)return null;let c=new Date(a.expiresAt).getTime();return Math.floor((c-Date.now())/6e4)});(0,e.useEffect)(()=>{if(!b||!a.expiresAt)return;let c=setInterval(()=>{let b=new Date(a.expiresAt).getTime();P(Math.floor((b-Date.now())/6e4))},3e4);return()=>clearInterval(c)},[b,a.expiresAt]),(0,e.useEffect)(()=>{let b=()=>{let b=a.rateLimitedUntil&&new Date(a.rateLimitedUntil).getTime()>Date.now();M(b)};b();let c=a.rateLimitedUntil?setInterval(b,1e3):null;return()=>{c&&clearInterval(c)}},[a.rateLimitedUntil]);let Q="unavailable"!==a.testStatus||L?a.testStatus:"active",R=function(a,b,c,d){if(!1===a.isActive)return{statusVariant:"default",statusLabel:d("statusDisabled"),errorType:null,errorBadge:null,errorTextClass:"text-text-muted"};if("active"===b||"success"===b)return{statusVariant:"success",statusLabel:d("statusConnected"),errorType:null,errorBadge:null,errorTextClass:"text-text-muted"};let e=function(a,b){if(b)return"upstream_rate_limited";if("banned"===a.testStatus)return"banned";if("credits_exhausted"===a.testStatus)return"credits_exhausted";if(a.lastErrorType)return a.lastErrorType;let c=Number(a.errorCode);if(401===c||403===c)return"upstream_auth_error";if(429===c)return"upstream_rate_limited";if(c>=500)return"upstream_unavailable";let d=(a.lastError||"").toLowerCase();return d?d.includes("runtime")||d.includes("not runnable")||d.includes("not installed")||d.includes("healthcheck")?"runtime_error":d.includes("refresh failed")?"token_refresh_failed":d.includes("token expired")||d.includes("expired")?"token_expired":d.includes("invalid api key")||d.includes("token invalid")||d.includes("revoked")||d.includes("access denied")||d.includes("unauthorized")?"upstream_auth_error":d.includes("rate limit")||d.includes("quota")||d.includes("too many requests")||d.includes("429")?"upstream_rate_limited":d.includes("fetch failed")||d.includes("network")||d.includes("timeout")||d.includes("econn")||d.includes("enotfound")?"network_error":d.includes("not supported")?"unsupported":"upstream_error":null}(a,c),f=e&&ab[e]||null;if("runtime_error"===e)return{statusVariant:"warning",statusLabel:d("statusRuntimeIssue"),errorType:e,errorBadge:f,errorTextClass:"text-yellow-600 dark:text-yellow-400"};if("account_deactivated"===e)return{statusVariant:"error",statusLabel:d("statusDeactivated","Deactivated"),errorType:e,errorBadge:f,errorTextClass:"text-red-600 font-bold"};if("upstream_auth_error"===e||"auth_missing"===e||"token_refresh_failed"===e||"token_expired"===e)return{statusVariant:"error",statusLabel:d("statusAuthFailed"),errorType:e,errorBadge:f,errorTextClass:"text-red-500"};if("upstream_rate_limited"===e)return{statusVariant:"warning",statusLabel:d("statusRateLimited"),errorType:e,errorBadge:f,errorTextClass:"text-yellow-600 dark:text-yellow-400"};if("network_error"===e)return{statusVariant:"warning",statusLabel:d("statusNetworkIssue"),errorType:e,errorBadge:f,errorTextClass:"text-yellow-600 dark:text-yellow-400"};if("unsupported"===e)return{statusVariant:"default",statusLabel:d("statusTestUnsupported"),errorType:e,errorBadge:f,errorTextClass:"text-text-muted"};if("banned"===e)return{statusVariant:"error",statusLabel:d("statusBanned","Banned (403)"),errorType:e,errorBadge:f,errorTextClass:"text-red-600 font-bold"};if("credits_exhausted"===e)return{statusVariant:"warning",statusLabel:d("statusCreditsExhausted","Out of Credits"),errorType:e,errorBadge:f,errorTextClass:"text-amber-500"};let g={unavailable:d("statusUnavailable"),failed:d("statusFailed"),error:d("statusError")};return{statusVariant:"error",statusLabel:g[b]||b||d("statusError"),errorType:e,errorBadge:f,errorTextClass:"text-red-500"}}(a,Q,L,H),S=!!a.rateLimitProtection,T=a.providerSpecificData&&"object"==typeof a.providerSpecificData&&a.providerSpecificData.codexLimitPolicy&&"object"==typeof a.providerSpecificData.codexLimitPolicy?a.providerSpecificData.codexLimitPolicy:{},W=N(T),X=W.use5h,Y=W.useWeekly;return(0,d.jsxs)("div",{className:`group flex items-center justify-between p-3 rounded-lg hover:bg-black/[0.02] dark:hover:bg-white/[0.02] transition-colors ${!1===a.isActive?"opacity-60":""}`,children:[(0,d.jsxs)("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[(0,d.jsxs)("div",{className:"flex flex-col",children:[(0,d.jsx)("button",{onClick:h,disabled:f,className:`p-0.5 rounded ${f?"text-text-muted/30 cursor-not-allowed":"hover:bg-sidebar text-text-muted hover:text-primary"}`,children:(0,d.jsx)("span",{className:"material-symbols-outlined text-sm",children:"keyboard_arrow_up"})}),(0,d.jsx)("button",{onClick:i,disabled:g,className:`p-0.5 rounded ${g?"text-text-muted/30 cursor-not-allowed":"hover:bg-sidebar text-text-muted hover:text-primary"}`,children:(0,d.jsx)("span",{className:"material-symbols-outlined text-sm",children:"keyboard_arrow_down"})})]}),(0,d.jsx)("span",{className:"material-symbols-outlined text-base text-text-muted",children:b?"lock":"key"}),(0,d.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,d.jsx)("p",{className:"text-sm font-medium truncate",children:I}),(0,d.jsxs)("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[(0,d.jsx)(p.Badge,{variant:R.statusVariant,size:"sm",dot:!0,children:R.statusLabel}),null!==O&&(O<0?(0,d.jsxs)("span",{className:"inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded text-xs font-medium bg-red-500/15 text-red-500",title:`Token expired: ${a.expiresAt}`,children:[(0,d.jsx)("span",{className:"material-symbols-outlined text-[11px]",children:"error"}),"expired"]}):O<30?(0,d.jsxs)("span",{className:"inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded text-xs font-medium bg-amber-500/15 text-amber-500",title:`Token expires in ${O}m`,children:[(0,d.jsx)("span",{className:"material-symbols-outlined text-[11px]",children:"warning"}),`~${O}m`]}):null),L&&!1!==a.isActive&&(0,d.jsx)(U,{until:a.rateLimitedUntil}),R.errorBadge&&!1!==a.isActive&&(0,d.jsx)(p.Badge,{variant:R.errorBadge.variant,size:"sm",children:H(R.errorBadge.labelKey)}),a.lastError&&!1!==a.isActive&&(0,d.jsx)("span",{className:`text-xs truncate max-w-[300px] ${R.errorTextClass}`,title:a.lastError.replace(/<[^>]*>?/gm,""),dangerouslySetInnerHTML:{__html:a.lastError}}),(0,d.jsxs)("span",{className:"text-xs text-text-muted",children:["#",a.priority]}),a.globalPriority&&(0,d.jsx)("span",{className:"text-xs text-text-muted",children:H("autoPriority",{priority:a.globalPriority})}),(0,d.jsx)("span",{className:"text-text-muted/30 select-none",children:"|"}),(0,d.jsxs)("button",{onClick:()=>k(!S),className:`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs font-medium transition-all cursor-pointer ${S?"bg-emerald-500/15 text-emerald-500 hover:bg-emerald-500/25":"bg-black/[0.03] dark:bg-white/[0.03] text-text-muted/50 hover:text-text-muted hover:bg-black/[0.06] dark:hover:bg-white/[0.06]"}`,title:H(S?"disableRateLimitProtection":"enableRateLimitProtection"),children:[(0,d.jsx)("span",{className:"material-symbols-outlined text-[13px]",children:"shield"}),H(S?"rateLimitProtected":"rateLimitUnprotected")]}),c&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("span",{className:"text-text-muted/30 select-none",children:"|"}),(0,d.jsxs)("button",{onClick:()=>m?.(!X),className:`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs font-medium transition-all cursor-pointer ${X?"bg-blue-500/15 text-blue-500 hover:bg-blue-500/25":"bg-black/[0.03] dark:bg-white/[0.03] text-text-muted/50 hover:text-text-muted hover:bg-black/[0.06] dark:hover:bg-white/[0.06]"}`,title:"Toggle Codex 5h limit policy",children:[(0,d.jsx)("span",{className:"material-symbols-outlined text-[13px]",children:"timer"}),"5h ",X?"ON":"OFF"]}),(0,d.jsxs)("button",{onClick:()=>n?.(!Y),className:`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs font-medium transition-all cursor-pointer ${Y?"bg-violet-500/15 text-violet-500 hover:bg-violet-500/25":"bg-black/[0.03] dark:bg-white/[0.03] text-text-muted/50 hover:text-text-muted hover:bg-black/[0.06] dark:hover:bg-white/[0.06]"}`,title:"Toggle Codex weekly limit policy",children:[(0,d.jsx)("span",{className:"material-symbols-outlined text-[13px]",children:"date_range"}),"Weekly ",Y?"ON":"OFF"]})]}),x&&(G=H("global"===y?"proxySourceGlobal":"provider"===y?"proxySourceProvider":"proxySourceKey"),(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("span",{className:"text-text-muted/30 select-none",children:"|"}),(0,d.jsxs)("span",{className:`inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded text-xs font-medium ${"global"===y?"bg-emerald-500/15 text-emerald-500":"provider"===y?"bg-amber-500/15 text-amber-500":"bg-blue-500/15 text-blue-500"}`,title:H("proxyConfiguredBySource",{source:G,host:z||H("configured")}),children:[(0,d.jsx)("span",{className:"material-symbols-outlined text-[13px]",children:"vpn_lock"}),z||H("proxy")]})]}))]})]})]}),(0,d.jsxs)("div",{className:"flex items-center gap-2",children:[(0,d.jsx)(o.Button,{size:"sm",variant:"ghost",icon:"refresh",loading:r,disabled:!1===a.isActive,onClick:q,className:"!h-7 !px-2 text-xs",title:H("retestAuthentication"),children:H("retest")}),A&&(0,d.jsx)(o.Button,{size:"sm",variant:"ghost",icon:"token",loading:B,disabled:!1===a.isActive||B,onClick:A,className:"!h-7 !px-2 text-xs text-amber-500 hover:text-amber-400",title:"Refresh OAuth token manually",children:"Token"}),c&&C&&(0,d.jsx)(o.Button,{size:"sm",variant:"ghost",icon:"download_done",loading:D,disabled:D,onClick:C,className:"!h-7 !px-2 text-xs text-emerald-500 hover:text-emerald-400",title:J,children:J}),c&&E&&(0,d.jsx)(o.Button,{size:"sm",variant:"ghost",icon:"download",loading:F,disabled:F,onClick:E,className:"!h-7 !px-2 text-xs text-sky-500 hover:text-sky-400",title:K,children:K}),(0,d.jsx)(w.Toggle,{size:"sm",checked:a.isActive??!0,onChange:j,title:H(a.isActive??!0?"disableConnection":"enableConnection")}),(0,d.jsxs)("div",{className:"flex gap-1 ml-1 transition-opacity",children:[u&&(0,d.jsx)("button",{onClick:u,className:"p-2 hover:bg-amber-500/10 rounded text-amber-600 hover:text-amber-500",title:H("reauthenticateConnection"),children:(0,d.jsx)("span",{className:"material-symbols-outlined text-[18px]",children:"passkey"})}),(0,d.jsx)("button",{onClick:s,className:"p-2 hover:bg-black/5 dark:hover:bg-white/5 rounded text-text-muted hover:text-primary",title:H("edit"),children:(0,d.jsx)("span",{className:"material-symbols-outlined text-[18px]",children:"edit"})}),(0,d.jsx)("button",{onClick:v,className:"p-2 hover:bg-black/5 dark:hover:bg-white/5 rounded text-text-muted hover:text-primary",title:H("proxyConfig"),children:(0,d.jsx)("span",{className:"material-symbols-outlined text-[18px]",children:"vpn_lock"})}),(0,d.jsx)("button",{onClick:t,className:"p-2 hover:bg-red-500/10 rounded text-red-500",title:H("delete"),children:(0,d.jsx)("span",{className:"material-symbols-outlined text-[18px]",children:"delete"})})]})]})]})}function W({isOpen:a,provider:b,providerName:c,isCompatible:f,isAnthropic:g,isCcCompatible:h,onSave:i,onClose:j}){let k=(0,l.useTranslations)("providers"),m="bailian-coding-plan"===b,n="https://coding-intl.dashscope.aliyuncs.com/apps/anthropic/v1",s="vertex"===b,t="us-central1",u="glm"===b,v="qoder"===b,[w,x]=(0,e.useState)({name:"",apiKey:"",priority:1,baseUrl:m?n:"",region:s?t:"",apiRegion:"international",validationModelId:""}),[y,z]=(0,e.useState)(!1),[A,B]=(0,e.useState)(null),[C,D]=(0,e.useState)(!1),[E,F]=(0,e.useState)(null),G=async()=>{z(!0),F(null);try{let a=await fetch("/api/providers/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:b,apiKey:w.apiKey,validationModelId:w.validationModelId||void 0})}),c=await a.json();B(c.valid?"success":"failed")}catch{B("failed")}finally{z(!1)}},H=async()=>{if(b&&w.apiKey){D(!0),F(null);try{let a=null;if(m){let b=X(w.baseUrl,n);if(b.error)return void F(b.error);a=b.value}let c=!1;try{z(!0),B(null);let a=await fetch("/api/providers/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:b,apiKey:w.apiKey,validationModelId:w.validationModelId||void 0})});c=!!(await a.json()).valid,B(c?"success":"failed")}catch{B("failed")}finally{z(!1)}if(!c)return void F(k("apiKeyValidationFailed"));let d={name:w.name,apiKey:w.apiKey,priority:w.priority,testStatus:"active",providerSpecificData:void 0};m?d.providerSpecificData={baseUrl:a}:s?d.providerSpecificData={region:w.region}:u&&(d.providerSpecificData={apiRegion:w.apiRegion});let e=await i(d);e&&F("string"==typeof e?e:k("failedSaveConnection"))}finally{D(!1)}}};return b?(0,d.jsx)(r.Modal,{isOpen:a,title:k("addProviderApiKeyTitle",{provider:c||b}),onClose:j,children:(0,d.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,d.jsx)(q.Input,{label:k("nameLabel"),value:w.name,onChange:a=>x({...w,name:a.target.value}),placeholder:v?"Qoder PAT":k("productionKey")}),(0,d.jsxs)("div",{className:"flex gap-2",children:[(0,d.jsx)(q.Input,{label:v?"Personal Access Token":k("apiKeyLabel"),type:"password",value:w.apiKey,onChange:a=>x({...w,apiKey:a.target.value}),className:"flex-1",placeholder:s?"Cole o Service Account JSON aqui":v?"Paste your Qoder Personal Access Token":void 0,hint:v?"Supported path: PAT via qodercli. Browser OAuth remains experimental.":void 0}),(0,d.jsx)("div",{className:"pt-6",children:(0,d.jsx)(o.Button,{onClick:G,disabled:!w.apiKey||y||C,variant:"secondary",children:y?k("checking"):k("check")})})]}),A&&(0,d.jsx)(p.Badge,{variant:"success"===A?"success":"error",children:"success"===A?k("valid"):k("invalid")}),E&&(0,d.jsx)("div",{className:"text-sm text-red-500 bg-red-500/10 border border-red-500/20 rounded-lg px-3 py-2",children:E}),f&&(0,d.jsx)("p",{className:"text-xs text-text-muted",children:h?"Validation uses the strict Claude Code-compatible bridge request for this provider.":g?k("validationChecksAnthropicCompatible",{provider:c||k("anthropicCompatibleName")}):k("validationChecksOpenAiCompatible",{provider:c||k("openaiCompatibleName")})}),(0,d.jsx)(q.Input,{label:"Model ID (opcional)",placeholder:"ex: grok-3 ou meta-llama/Llama-3.1-8B-Instruct",value:w.validationModelId,onChange:a=>x({...w,validationModelId:a.target.value}),hint:"Usado como fallback se a listagem de models não estiver disponível"}),(0,d.jsx)(q.Input,{label:k("priorityLabel"),type:"number",value:w.priority,onChange:a=>x({...w,priority:Number.parseInt(a.target.value)||1})}),m&&(0,d.jsx)(q.Input,{label:"Base URL",value:w.baseUrl,onChange:a=>x({...w,baseUrl:a.target.value}),placeholder:n,hint:"Optional: Custom base URL for bailian-coding-plan provider"}),s&&(0,d.jsx)(q.Input,{label:"Região (Region)",value:w.region,onChange:a=>x({...w,region:a.target.value}),placeholder:t,hint:"ex: us-central1 ou europe-west4. Partner models usam a região global automaticamente."}),u&&(0,d.jsxs)("div",{children:[(0,d.jsx)("label",{className:"text-sm font-medium text-text-main mb-1 block",children:"API Region"}),(0,d.jsxs)("select",{value:w.apiRegion,onChange:a=>x({...w,apiRegion:a.target.value}),className:"w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary",children:[(0,d.jsx)("option",{value:"international",children:"International (api.z.ai)"}),(0,d.jsx)("option",{value:"china",children:"China Mainland (open.bigmodel.cn)"})]}),(0,d.jsx)("p",{className:"text-xs text-text-muted mt-1",children:"Select the endpoint region for API access and quota tracking."})]}),(0,d.jsxs)("div",{className:"flex gap-2",children:[(0,d.jsx)(o.Button,{onClick:H,fullWidth:!0,disabled:!w.name||!w.apiKey||C,children:C?k("saving"):k("save")}),(0,d.jsx)(o.Button,{onClick:j,variant:"ghost",fullWidth:!0,children:k("cancel")})]})]})}):null}function X(a,b){let c=("string"==typeof a?a.trim():"")||b;try{let a=new URL(c);if("http:"!==a.protocol&&"https:"!==a.protocol)return{value:null,error:"Base URL must use http or https"};return{value:c,error:null}}catch{return{value:null,error:"Base URL must be a valid URL"}}}function Y({isOpen:a,connection:b,onSave:c,onClose:f}){let g=(0,l.useTranslations)("providers"),[h,i]=(0,e.useState)({name:"",priority:1,apiKey:"",healthCheckInterval:60,baseUrl:"",region:"",apiRegion:"international",validationModelId:"",tag:""}),[j,k]=(0,e.useState)(!1),[m,n]=(0,e.useState)(null),[s,t]=(0,e.useState)(!1),[u,v]=(0,e.useState)(null),[w,x]=(0,e.useState)(!1),[y,A]=(0,e.useState)(null),[B,C]=(0,e.useState)([]),[D,E]=(0,e.useState)(""),F=b?.provider==="bailian-coding-plan",G="https://coding-intl.dashscope.aliyuncs.com/apps/anthropic/v1",H=b?.provider==="vertex",I=b?.provider==="glm",J="us-central1";(0,e.useEffect)(()=>{if(b){let a=b.providerSpecificData?.baseUrl,c=b.providerSpecificData?.region;i({name:b.name||"",priority:b.priority||1,apiKey:"",healthCheckInterval:b.healthCheckInterval??60,baseUrl:("string"==typeof a?a:"")||(F?G:""),region:("string"==typeof c?c:"")||(H?J:""),apiRegion:b.providerSpecificData?.apiRegion||"international",validationModelId:b.providerSpecificData?.validationModelId||"",tag:b.providerSpecificData?.tag||""});let d=b.providerSpecificData?.extraApiKeys;C(Array.isArray(d)?d:[]),E(""),n(null),v(null),A(null)}},[b,F,H]);let K=async()=>{if(b?.provider){k(!0),n(null);try{let a=await fetch(`/api/providers/${b.id}/test`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({validationModelId:h.validationModelId||void 0})}),c=await a.json();n({valid:!!c.valid,diagnosis:c.diagnosis||null,message:c.error||null})}catch{n({valid:!1,diagnosis:{type:"network_error"},message:g("failedTestConnection")})}finally{k(!1)}}},L=async()=>{if(b?.provider&&h.apiKey){t(!0),v(null);try{let a=await fetch("/api/providers/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:b.provider,apiKey:h.apiKey,validationModelId:h.validationModelId||void 0})}),c=await a.json();v(c.valid?"success":"failed")}catch{v("failed")}finally{t(!1)}}},M=async()=>{x(!0),A(null);try{let a={name:h.name,priority:h.priority,healthCheckInterval:h.healthCheckInterval},d=null;if(F){let a=X(h.baseUrl,G);if(a.error)return void A(a.error);d=a.value}if(!N&&h.apiKey){a.apiKey=h.apiKey;let c="success"===u;if(!c)try{t(!0),v(null);let a=await fetch("/api/providers/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:b.provider,apiKey:h.apiKey,validationModelId:h.validationModelId||void 0})});c=!!(await a.json()).valid,v(c?"success":"failed")}catch{v("failed")}finally{t(!1)}c&&(a.testStatus="active",a.lastError=null,a.lastErrorAt=null,a.lastErrorType=null,a.lastErrorSource=null,a.errorCode=null,a.rateLimitedUntil=null)}N?a.providerSpecificData={...b.providerSpecificData||{},tag:h.tag.trim()||void 0}:(a.providerSpecificData={...b.providerSpecificData||{},extraApiKeys:B.filter(a=>a.trim().length>0),tag:h.tag.trim()||void 0},h.validationModelId&&(a.providerSpecificData.validationModelId=h.validationModelId),F?a.providerSpecificData.baseUrl=d:H?a.providerSpecificData.region=h.region:I&&(a.providerSpecificData.apiRegion=h.apiRegion));let e=await c(a);e&&A("string"==typeof e?e:g("failedSaveConnection"))}finally{x(!1)}};if(!b)return null;let N="oauth"===b.authType,O=(0,z.isOpenAICompatibleProvider)(b.provider)||(0,z.isAnthropicCompatibleProvider)(b.provider),P=!m?.valid&&m?.diagnosis?.type&&ab[m.diagnosis.type]||null;return(0,d.jsx)(r.Modal,{isOpen:a,title:g("editConnection"),onClose:f,children:(0,d.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,d.jsx)(q.Input,{label:g("nameLabel"),value:h.name,onChange:a=>i({...h,name:a.target.value}),placeholder:N?g("accountName"):g("productionKey")}),(0,d.jsx)(q.Input,{label:"Tag / Group",value:h.tag,onChange:a=>i({...h,tag:a.target.value}),placeholder:"e.g. personal, work, team-a",hint:"Used to group accounts in the provider view"}),N&&b.email&&(0,d.jsxs)("div",{className:"bg-sidebar/50 p-3 rounded-lg",children:[(0,d.jsx)("p",{className:"text-sm text-text-muted mb-1",children:g("email")}),(0,d.jsx)("p",{className:"font-medium",children:b.email})]}),N&&(0,d.jsx)(q.Input,{label:g("healthCheckMinutes"),type:"number",value:h.healthCheckInterval,onChange:a=>i({...h,healthCheckInterval:Math.max(0,Number.parseInt(a.target.value)||0)}),hint:g("healthCheckHint")}),(0,d.jsx)(q.Input,{label:g("priorityLabel"),type:"number",value:h.priority,onChange:a=>i({...h,priority:Number.parseInt(a.target.value)||1})}),!N&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("div",{className:"flex gap-2",children:[(0,d.jsx)(q.Input,{label:g("apiKeyLabel"),type:"password",value:h.apiKey,onChange:a=>i({...h,apiKey:a.target.value}),placeholder:H?"Cole o Service Account JSON aqui":g("enterNewApiKey"),hint:g("leaveBlankKeepCurrentApiKey"),className:"flex-1"}),(0,d.jsx)("div",{className:"pt-6",children:(0,d.jsx)(o.Button,{onClick:L,disabled:!h.apiKey||s||w,variant:"secondary",children:s?g("checking"):g("check")})})]}),u&&(0,d.jsx)(p.Badge,{variant:"success"===u?"success":"error",children:"success"===u?g("valid"):g("invalid")}),y&&(0,d.jsx)("div",{className:"text-sm text-red-500 bg-red-500/10 border border-red-500/20 rounded-lg px-3 py-2",children:y}),(0,d.jsx)(q.Input,{label:"Model ID (opcional)",placeholder:"ex: grok-3 ou meta-llama/Llama-3.1-8B-Instruct",value:h.validationModelId,onChange:a=>i({...h,validationModelId:a.target.value}),hint:"Usado como fallback se a listagem de models não estiver disponível"})]}),F&&(0,d.jsx)(q.Input,{label:"Base URL",value:h.baseUrl,onChange:a=>i({...h,baseUrl:a.target.value}),placeholder:G,hint:"Custom base URL for bailian-coding-plan provider"}),H&&(0,d.jsx)(q.Input,{label:"Região (Region)",value:h.region,onChange:a=>i({...h,region:a.target.value}),placeholder:J,hint:"ex: us-central1 ou europe-west4. Partner models usam a região global automaticamente."}),I&&(0,d.jsxs)("div",{children:[(0,d.jsx)("label",{className:"text-sm font-medium text-text-main mb-1 block",children:"API Region"}),(0,d.jsxs)("select",{value:h.apiRegion,onChange:a=>i({...h,apiRegion:a.target.value}),className:"w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary",children:[(0,d.jsx)("option",{value:"international",children:"International (api.z.ai)"}),(0,d.jsx)("option",{value:"china",children:"China Mainland (open.bigmodel.cn)"})]}),(0,d.jsx)("p",{className:"text-xs text-text-muted mt-1",children:"Select the endpoint region for API access and quota tracking."})]}),!N&&(0,d.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,d.jsxs)("label",{className:"text-sm font-medium text-text-main",children:["Extra API Keys",(0,d.jsx)("span",{className:"ml-2 text-[11px] font-normal text-text-muted",children:"(round-robin rotation — optional)"})]}),B.length>0&&(0,d.jsx)("div",{className:"flex flex-col gap-1.5",children:B.map((a,b)=>(0,d.jsxs)("div",{className:"flex items-center gap-2",children:[(0,d.jsx)("span",{className:"flex-1 font-mono text-xs bg-sidebar/50 px-3 py-2 rounded border border-border text-text-muted truncate",children:`Key #${b+2}: ${a.slice(0,6)}...${a.slice(-4)}`}),(0,d.jsx)("button",{onClick:()=>C(B.filter((a,c)=>c!==b)),className:"p-1.5 rounded hover:bg-red-500/10 text-red-400 hover:text-red-500",title:"Remove this key",children:(0,d.jsx)("span",{className:"material-symbols-outlined text-[16px]",children:"close"})})]},b))}),(0,d.jsxs)("div",{className:"flex gap-2",children:[(0,d.jsx)("input",{type:"password",value:D,onChange:a=>E(a.target.value),placeholder:"Add another API key...",className:"flex-1 text-sm bg-sidebar/50 border border-border rounded px-3 py-2 text-text-main placeholder:text-text-muted focus:ring-1 focus:ring-primary outline-none",onKeyDown:a=>{"Enter"===a.key&&D.trim()&&(C([...B,D.trim()]),E(""))}}),(0,d.jsx)("button",{onClick:()=>{D.trim()&&(C([...B,D.trim()]),E(""))},disabled:!D.trim(),className:"px-3 py-2 rounded bg-primary/10 text-primary hover:bg-primary/20 disabled:opacity-40 text-sm font-medium",children:"Add"})]}),B.length>0&&(0,d.jsxs)("p",{className:"text-[11px] text-text-muted",children:[B.length+1," keys total — rotating round-robin on each request."]})]}),!O&&(0,d.jsxs)("div",{className:"flex items-center gap-3",children:[(0,d.jsx)(o.Button,{onClick:K,variant:"secondary",disabled:j,children:j?g("testing"):g("testConnection")}),m&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(p.Badge,{variant:m.valid?"success":"error",children:m.valid?g("valid"):g("failed")}),P&&(0,d.jsx)(p.Badge,{variant:P.variant,children:g(P.labelKey)})]})]}),(0,d.jsxs)("div",{className:"flex gap-2",children:[(0,d.jsx)(o.Button,{onClick:M,fullWidth:!0,disabled:w,children:w?g("saving"):g("save")}),(0,d.jsx)(o.Button,{onClick:f,variant:"ghost",fullWidth:!0,children:g("cancel")})]})]})})}function Z({isOpen:a,node:b,onSave:c,onClose:f,isAnthropic:g,isCcCompatible:h}){let i=(0,l.useTranslations)("providers"),[j,k]=(0,e.useState)({name:"",prefix:"",apiType:"chat",baseUrl:"https://api.openai.com/v1",chatPath:"",modelsPath:""}),[m,n]=(0,e.useState)(!1),[s,t]=(0,e.useState)(""),[u,v]=(0,e.useState)(!1),[w,y]=(0,e.useState)(null),[z,A]=(0,e.useState)(!1);(0,e.useEffect)(()=>{b&&(k({name:b.name||"",prefix:b.prefix||"",apiType:b.apiType||"chat",baseUrl:b.baseUrl||(h?"https://api.anthropic.com":g?"https://api.anthropic.com/v1":"https://api.openai.com/v1"),chatPath:b.chatPath||(h?aa:""),modelsPath:h?"":b.modelsPath||""}),A(!!(b.chatPath||!h&&b.modelsPath||h&&!b.chatPath)))},[b,g,h]);let B=[{value:"chat",label:i("chatCompletions")},{value:"responses",label:i("responsesApi")}],C=async()=>{if(j.name.trim()&&j.prefix.trim()&&j.baseUrl.trim()){n(!0);try{let a={name:j.name,prefix:j.prefix,baseUrl:j.baseUrl,chatPath:j.chatPath||(h?aa:""),modelsPath:h?"":j.modelsPath};g||(a.apiType=j.apiType),await c(a)}finally{n(!1)}}},D=async()=>{v(!0);try{let a=await fetch("/api/provider-nodes/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({baseUrl:j.baseUrl,apiKey:s,type:g?"anthropic-compatible":"openai-compatible",compatMode:h?"cc":void 0,chatPath:j.chatPath||(h?aa:""),modelsPath:h?"":j.modelsPath})}),b=await a.json();y(b.valid?"success":"failed")}catch{y("failed")}finally{v(!1)}};return b?(0,d.jsx)(r.Modal,{isOpen:a,title:h?_:i("editCompatibleTitle",{type:i(g?"anthropic":"openai")}),onClose:f,children:(0,d.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,d.jsx)(q.Input,{label:h?"Name":i("nameLabel"),value:j.name,onChange:a=>k({...j,name:a.target.value}),placeholder:h?"CC Compatible Production":i("compatibleProdPlaceholder",{type:i(g?"anthropic":"openai")}),hint:h?"Display name for this provider":i("nameHint")}),(0,d.jsx)(q.Input,{label:h?"Prefix":i("prefixLabel"),value:j.prefix,onChange:a=>k({...j,prefix:a.target.value}),placeholder:h?"cc":i(g?"anthropicPrefixPlaceholder":"openaiPrefixPlaceholder"),hint:h?"Used for aliases such as prefix/model-id":i("prefixHint")}),!g&&(0,d.jsx)(x.Select,{label:i("apiTypeLabel"),options:B,value:j.apiType,onChange:a=>k({...j,apiType:a.target.value})}),(0,d.jsx)(q.Input,{label:h?"Base URL":i("baseUrlLabel"),value:j.baseUrl,onChange:a=>k({...j,baseUrl:a.target.value}),placeholder:h?"https://example.com/v1":i(g?"anthropicBaseUrlPlaceholder":"openaiBaseUrlPlaceholder"),hint:h?"Base URL for the CC-compatible site. Do not include /messages.":i("compatibleBaseUrlHint",{type:i(g?"anthropic":"openai")})}),(0,d.jsxs)("button",{type:"button",className:"text-sm text-text-muted hover:text-text-primary flex items-center gap-1",onClick:()=>A(!z),"aria-expanded":z,"aria-controls":"advanced-settings",children:[(0,d.jsx)("span",{className:`transition-transform ${z?"rotate-90":""}`,"aria-hidden":"true",children:"▶"}),i("advancedSettings")]}),z&&(0,d.jsxs)("div",{id:"advanced-settings",className:"flex flex-col gap-3 pl-2 border-l-2 border-border",children:[(0,d.jsx)(q.Input,{label:h?"Chat Path":i("chatPathLabel"),value:j.chatPath,onChange:a=>k({...j,chatPath:a.target.value}),placeholder:h?aa:g?"/messages":i("chatPathPlaceholder"),hint:h?"Defaults to the strict Claude Code-compatible messages path":i("chatPathHint")}),!h&&(0,d.jsx)(q.Input,{label:i("modelsPathLabel"),value:j.modelsPath,onChange:a=>k({...j,modelsPath:a.target.value}),placeholder:i("modelsPathPlaceholder"),hint:i("modelsPathHint")})]}),(0,d.jsxs)("div",{className:"flex gap-2",children:[(0,d.jsx)(q.Input,{label:i("apiKeyForCheck"),type:"password",value:s,onChange:a=>t(a.target.value),className:"flex-1"}),(0,d.jsx)("div",{className:"pt-6",children:(0,d.jsx)(o.Button,{onClick:D,disabled:!s||u||!j.baseUrl.trim(),variant:"secondary",children:i(u?"checking":"check")})})]}),w&&(0,d.jsx)(p.Badge,{variant:"success"===w?"success":"error",children:i("success"===w?"valid":"invalid")}),(0,d.jsxs)("div",{className:"flex gap-2",children:[(0,d.jsx)(o.Button,{onClick:C,fullWidth:!0,disabled:!j.name.trim()||!j.prefix.trim()||!j.baseUrl.trim()||m,children:i(m?"saving":"save")}),(0,d.jsx)(o.Button,{onClick:f,variant:"ghost",fullWidth:!0,children:i("cancel")})]})]})}):null}V.propTypes={connection:h.default.shape({id:h.default.string,name:h.default.string,email:h.default.string,displayName:h.default.string,rateLimitedUntil:h.default.string,rateLimitProtection:h.default.bool,testStatus:h.default.string,isActive:h.default.bool,priority:h.default.number,lastError:h.default.string,lastErrorType:h.default.string,lastErrorSource:h.default.string,errorCode:h.default.oneOfType([h.default.string,h.default.number]),globalPriority:h.default.number,providerSpecificData:h.default.object}).isRequired,isOAuth:h.default.bool.isRequired,isCodex:h.default.bool,isFirst:h.default.bool.isRequired,isLast:h.default.bool.isRequired,onMoveUp:h.default.func.isRequired,onMoveDown:h.default.func.isRequired,onToggleActive:h.default.func.isRequired,onToggleRateLimit:h.default.func.isRequired,onToggleCodex5h:h.default.func,onToggleCodexWeekly:h.default.func,onRetest:h.default.func.isRequired,isRetesting:h.default.bool,onEdit:h.default.func.isRequired,onDelete:h.default.func.isRequired,onReauth:h.default.func,onApplyCodexAuthLocal:h.default.func,isApplyingCodexAuthLocal:h.default.bool,onExportCodexAuthFile:h.default.func,isExportingCodexAuthFile:h.default.bool},W.propTypes={isOpen:h.default.bool.isRequired,provider:h.default.string,providerName:h.default.string,isCompatible:h.default.bool,isAnthropic:h.default.bool,isCcCompatible:h.default.bool,onSave:h.default.func.isRequired,onClose:h.default.func.isRequired},Y.propTypes={isOpen:h.default.bool.isRequired,connection:h.default.shape({id:h.default.string,name:h.default.string,email:h.default.string,priority:h.default.number,authType:h.default.string,provider:h.default.string}),onSave:h.default.func.isRequired,onClose:h.default.func.isRequired},Z.propTypes={isOpen:h.default.bool.isRequired,node:h.default.shape({id:h.default.string,name:h.default.string,prefix:h.default.string,apiType:h.default.string,baseUrl:h.default.string,chatPath:h.default.string,modelsPath:h.default.string}),onSave:h.default.func.isRequired,onClose:h.default.func.isRequired,isAnthropic:h.default.bool,isCcCompatible:h.default.bool},a.s(["default",0,function(){let a=(0,i.useParams)(),b=(0,i.useRouter)(),c=a.id,[f,h]=(0,e.useState)([]),[m,p]=(0,e.useState)(!0),[q,w]=(0,e.useState)(null),[x,A]=(0,e.useState)(!1),[F,G]=(0,e.useState)(!1),[I,O]=(0,e.useState)(!1),[R,U]=(0,e.useState)(!1),[X,ab]=(0,e.useState)(null),[ac,ad]=(0,e.useState)(null),[ae,af]=(0,e.useState)(!1),[ag,ah]=(0,e.useState)(null),[ai,aj]=(0,e.useState)({}),[ak,al]=(0,e.useState)(!1),{copied:am,copy:an}=(0,D.useCopyToClipboard)(),ao=(0,l.useTranslations)("providers"),ap=(0,g.useNotificationStore)(),[aq,ar]=(0,e.useState)(null),[as,at]=(0,e.useState)(null),[au,av]=(0,e.useState)({}),[aw,ax]=(0,e.useState)(!1),[ay,az]=(0,e.useState)(!1),[aA,aB]=(0,e.useState)({current:0,total:0,phase:"idle",status:"",logs:[],error:"",importedCount:0}),[aC,aD]=(0,e.useState)({customModels:[],modelCompatOverrides:[]}),[aE,aF]=(0,e.useState)([]),[aG,aH]=(0,e.useState)(null),[aI,aJ]=(0,e.useState)(null),[aK,aL]=(0,e.useState)(null),aM=(0,z.isOpenAICompatibleProvider)(c),aN=(0,z.isClaudeCodeCompatibleProvider)(c),aO=(0,z.isAnthropicCompatibleProvider)(c)&&!(0,z.isClaudeCodeCompatibleProvider)(c),aP=aM||aO||aN,aQ=aO||aN,aR=q?{id:q.id,name:q.name||(aN?$:"anthropic-compatible"===q.type?ao("anthropicCompatibleName"):ao("openaiCompatibleName")),color:aN?"#B45309":"anthropic-compatible"===q.type?"#D97757":"#10A37F",textIcon:aN?"CC":"anthropic-compatible"===q.type?"AC":"OC",apiType:q.apiType,baseUrl:q.baseUrl,type:q.type}:z.FREE_PROVIDERS[c]||z.OAUTH_PROVIDERS[c]||z.APIKEY_PROVIDERS[c],aS=!!z.FREE_PROVIDERS[c]||!!z.OAUTH_PROVIDERS[c],aT=(0,z.supportsApiKeyOnFreeProvider)(c),aU=aS&&!aT,aV=(0,B.getModelsByProviderId)(c),aW="gemini"===c?aE:aV,aX=(0,z.getProviderAlias)(c),aY=aP||"openrouter"===c,aZ=c.endsWith("-search"),a$=(0,C.compatibleProviderSupportsModelImport)(c),a_=aP?c:aX,a0=aP?q?.prefix||c:aX,a1=(0,e.useCallback)(async()=>{try{let a=await fetch("/api/models/alias"),b=await a.json();a.ok&&aj(b.aliases||{})}catch(a){console.log("Error fetching aliases:",a)}},[]),a2=(0,e.useCallback)(async()=>{if(!aZ)try{let a=await fetch(`/api/provider-models?provider=${encodeURIComponent(c)}`,{cache:"no-store"});if(!a.ok)return;let b=await a.json();if(aD({customModels:b.models||[],modelCompatOverrides:b.modelCompatOverrides||[]}),"gemini"===c)try{let a=await fetch("/api/synced-available-models?provider=gemini",{cache:"no-store"});if(a.ok){let b=await a.json();aF(b.models||[])}}catch{}}catch(a){console.error("fetchProviderModelMeta",a)}},[c,aZ]),a3=(0,e.useCallback)(async()=>{try{let[a,b]=await Promise.all([fetch("/api/providers",{cache:"no-store"}),fetch("/api/provider-nodes",{cache:"no-store"})]),d=await a.json(),e=await b.json();if(a.ok){let a=(d.connections||[]).filter(a=>a.provider===c);h(a)}if(b.ok){let a=(e.nodes||[]).find(a=>a.id===c)||null;if(!a&&aP)for(let b=0;b<3;b+=1){await new Promise(a=>setTimeout(a,150));let b=await fetch("/api/provider-nodes",{cache:"no-store"});if(b.ok&&(a=((await b.json()).nodes||[]).find(a=>a.id===c)||null))break}w(a)}}catch(a){console.log("Error fetching connections:",a)}finally{p(!1)}},[c,aP]),a4=async a=>{try{let b=await fetch(`/api/provider-nodes/${c}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)}),d=await b.json();b.ok&&(w(d.node),await a3(),U(!1))}catch(a){console.log("Error updating provider node:",a)}};(0,e.useEffect)(()=>{a3(),a1(),fetch("/api/settings/proxy").then(a=>a.ok?a.json():null).then(a=>at(a)).catch(()=>{})},[a3,a1]);let a5=(0,e.useCallback)(async a=>{if(a.length)try{let b=await Promise.all(a.filter(a=>a.id).map(a=>fetch(`/api/settings/proxy?resolve=${encodeURIComponent(a.id)}`,{cache:"no-store"}).then(a=>a.ok?a.json():null).then(b=>[a.id,b]).catch(()=>[a.id,null]))),c={};for(let[a,d]of b)c[a]=d?.proxy?d:null;av(c)}catch{}},[]);(0,e.useEffect)(()=>{m||aZ||a2()},[m,aZ,a2]),(0,e.useEffect)(()=>{!m&&f.length>0&&a5(f)},[m,f,a5]);let a6=async(a,b,c=aX)=>{let d=`${c}/${a}`;try{let a=await fetch("/api/models/alias",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:d,alias:b})});if(a.ok)await a1();else{let b=await a.json();alert(b.error||ao("failedSetAlias"))}}catch(a){console.log("Error setting alias:",a)}},a7=async a=>{try{(await fetch(`/api/models/alias?alias=${encodeURIComponent(a)}`,{method:"DELETE"})).ok&&await a1()}catch(a){console.log("Error deleting alias:",a)}},a8=async a=>{if(confirm(ao("deleteConnectionConfirm")))try{(await fetch(`/api/providers/${a}`,{method:"DELETE"})).ok&&(h(f.filter(b=>b.id!==a)),"gemini"===c&&await a2())}catch(a){console.log("Error deleting connection:",a)}},a9=(0,e.useCallback)(()=>{a3(),A(!1)},[a3]),ba=(0,e.useCallback)(()=>{aU?A(!0):G(!0)},[aU]),bb=async a=>{try{let b=await fetch("/api/providers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:c,...a})});if(b.ok){let a=await b.json(),d=a?.connection;if(await a3(),G(!1),"gemini"===c&&d?.id){az(!0),aB({current:0,total:0,phase:"fetching",status:ao("fetchingModels"),logs:[],error:"",importedCount:0});try{let a=await fetch(`/api/providers/${d.id}/sync-models`,{method:"POST",signal:AbortSignal.timeout(3e4)}),b=await a.json();if(!a.ok||b.error)return aB(a=>({...a,phase:"error",status:ao("failedFetchModels"),error:b.error?.message||b.error||ao("failedImportModels")})),null;let c=b.syncedModels||0,e=b.models||[],f=[];if(e.length>0)for(let a of(f.push(`✓ ${c} models available`),f.push(""),e))f.push(` ${a.name||a.id}`);aB(a=>({...a,phase:"done",status:ao("modelsImported",{count:c}),total:c,current:c,importedCount:c,logs:f})),await a2()}catch(a){aB(b=>({...b,phase:"error",status:ao("failedFetchModels"),error:String(a)}))}}return null}let d=await b.json().catch(()=>({}));return d.error?.message||d.error||ao("failedSaveConnection")}catch(a){return console.log("Error saving connection:",a),ao("failedSaveConnectionRetry")}},bc=async a=>{try{let b=await fetch(`/api/providers/${X.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(b.ok)return await a3(),O(!1),null;let c=await b.json().catch(()=>({}));return c.error?.message||c.error||ao("failedSaveConnection")}catch(a){return console.log("Error updating connection:",a),ao("failedSaveConnectionRetry")}},bd=async(a,b)=>{try{(await fetch(`/api/providers/${a}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({isActive:b})})).ok&&h(c=>c.map(c=>c.id===a?{...c,isActive:b}:c))}catch(a){console.log("Error updating connection status:",a)}},be=async(a,b)=>{try{(await fetch("/api/rate-limits",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({connectionId:a,enabled:b})})).ok&&h(c=>c.map(c=>c.id===a?{...c,rateLimitProtection:b}:c))}catch(a){console.error("Error toggling rate limit:",a)}},bf=async(a,b,c)=>{try{let d=f.find(b=>b.id===a);if(!d)return;let e=d.providerSpecificData&&"object"==typeof d.providerSpecificData?d.providerSpecificData:{},g=e.codexLimitPolicy&&"object"==typeof e.codexLimitPolicy?e.codexLimitPolicy:{},i={...N(g),[b]:c},j=await fetch(`/api/providers/${a}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerSpecificData:{...e,codexLimitPolicy:i}})});if(!j.ok){let a=await j.json().catch(()=>({}));ap.error(a.error||"Failed to update Codex limit policy");return}h(b=>b.map(b=>b.id===a?{...b,providerSpecificData:{...b.providerSpecificData||{},codexLimitPolicy:i}}:b)),ap.success("Codex limit policy updated")}catch(a){console.error("Error toggling Codex quota policy:",a),ap.error("Failed to update Codex limit policy")}},bg=async a=>{if(a&&!ac){ad(a);try{let b=await fetch(`/api/providers/${a}/test`,{method:"POST"});if(!b.ok){let a=await b.json().catch(()=>({}));alert(a.error||ao("failedRetestConnection"));return}await a3()}catch(a){console.error("Error retesting connection:",a)}finally{ad(null)}}},bh=async()=>{if(ae||0===f.length)return;af(!0),ah(null);let a=new AbortController,b=setTimeout(()=>a.abort(),12e4);try{let b,d=await fetch("/api/providers/test-batch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:"provider",providerId:c}),signal:a.signal});try{b=await d.json()}catch{b={error:ao("providerTestFailed"),results:[],summary:null}}if(ah({...b,error:b.error?"object"==typeof b.error?b.error.message||b.error.error||JSON.stringify(b.error):String(b.error):null}),b?.summary){let{passed:a,failed:c,total:d}=b.summary;0===c?ap.success(ao("allTestsPassed",{total:d})):ap.warning(ao("testSummary",{passed:a,failed:c,total:d}))}await a3()}catch(b){let a=b?.name==="AbortError"?ao("providerTestTimeout"):ao("providerTestFailed");ah({error:a,results:[],summary:null}),ap.error(a)}finally{clearTimeout(b),af(!1)}},[bi,bj]=(0,e.useState)(null),bk=async(a,b)=>{if((a.headers.get("content-type")||"").includes("application/json")){let b=await a.json().catch(()=>({}));if("string"==typeof b?.error&&b.error.trim())return b.error;if(b?.error?.message)return b.error.message}return(await a.text().catch(()=>"")).trim()||b},bl=async a=>{if(!bi){bj(a);try{let b=await fetch(`/api/providers/${a}/refresh`,{method:"POST"}),c=await b.json().catch(()=>({}));b.ok&&c.success?(ap.success(ao("tokenRefreshed")),await a3()):ap.error(c.error||ao("tokenRefreshFailed"))}catch(a){console.error("Error refreshing token:",a),ap.error(ao("tokenRefreshFailed"))}finally{bj(null)}}},bm=async a=>{if(aI)return;aJ(a);let b="function"==typeof ao.has&&ao.has("codexAuthAppliedLocal")?ao("codexAuthAppliedLocal"):"Codex auth.json applied locally",c="function"==typeof ao.has&&ao.has("codexAuthApplyFailed")?ao("codexAuthApplyFailed"):"Failed to apply Codex auth.json locally";try{let d=await fetch(`/api/providers/${a}/codex-auth/apply-local`,{method:"POST"});if(!d.ok)return void ap.error(await bk(d,c));ap.success(b)}catch(a){console.error("Error applying Codex auth locally:",a),ap.error(c)}finally{aJ(null)}},bn=async a=>{if(aK)return;aL(a);let b="function"==typeof ao.has&&ao.has("codexAuthExported")?ao("codexAuthExported"):"Codex auth.json exported",c="function"==typeof ao.has&&ao.has("codexAuthExportFailed")?ao("codexAuthExportFailed"):"Failed to export Codex auth.json";try{let d=await fetch(`/api/providers/${a}/codex-auth/export`,{method:"POST"});if(!d.ok)return void ap.error(await bk(d,c));let e=await d.blob(),f=((a,b)=>{let c=a.headers.get("content-disposition")||"",d=c.match(/filename\*=UTF-8''([^;]+)/i);if(d?.[1])return decodeURIComponent(d[1]);let e=c.match(/filename="([^"]+)"/i);return e?.[1]?e[1]:b})(d,"codex-auth.json"),g=window.URL.createObjectURL(e),h=document.createElement("a");h.href=g,h.download=f,document.body.appendChild(h),h.click(),document.body.removeChild(h),window.setTimeout(()=>window.URL.revokeObjectURL(g),1e3),ap.success(b)}catch(a){console.error("Error exporting Codex auth file:",a),ap.error(c)}finally{aL(null)}},bo=async(a,b)=>{if(a&&b)try{let c=b.priority,d=a.priority;c===d&&(c=f.indexOf(a)>f.indexOf(b)?b.priority-.5:b.priority+.5),await Promise.all([fetch(`/api/providers/${a.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({priority:c})}),fetch(`/api/providers/${b.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({priority:d})})]),await a3()}catch(a){console.log("Error swapping priority:",a)}},bp=async()=>{if(aw)return;let a=f.find(a=>!1!==a.isActive);if(a){ax(!0),az(!0),aB({current:0,total:0,phase:"fetching",status:ao("fetchingModels"),logs:[],error:"",importedCount:0});try{let b=await fetch(`/api/providers/${a.id}/models`),d=await b.json();if(!b.ok)return void aB(a=>({...a,phase:"error",status:ao("failedFetchModels"),error:d.error||ao("failedImportModels")}));let e=d.models||[];if(0===e.length)return void aB(a=>({...a,phase:"done",status:ao("noModelsFound"),logs:[ao("noModelsReturnedFromEndpoint")]}));let f=new Set([...(aC.customModels||[]).map(a=>a.id),...aW.map(a=>a.id)]),g=e.filter(a=>!f.has(a.id||a.name||a.model));if(0===g.length)return void aB(a=>({...a,phase:"done",status:ao("allModelsAlreadyImported")||"All models already imported",logs:[ao("noNewModelsToImport")||"No new models to import"],importedCount:0,total:0,current:0}));aB(a=>({...a,phase:"importing",total:g.length,current:0,status:ao("importingModelsProgress",{current:0,total:g.length}),logs:[ao("foundModelsStartingImport",{count:g.length}),...g.length<e.length?[ao("skippingExistingModels",{count:e.length-g.length})||`Skipping ${e.length-g.length} existing models`]:[]]}));let h=0;for(let a=0;a<g.length;a++){let b=g[a],d=b.id||b.name||b.model;if(!d)continue;let e=d.split("/"),f=e[e.length-1];aB(b=>({...b,current:a+1,status:ao("importingModelsProgress",{current:a+1,total:g.length}),logs:[...b.logs,ao("importingModelById",{modelId:d})]})),await fetch("/api/provider-models",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:c,modelId:d,modelName:b.name||d,source:"imported"})}),ai[f]||await a6(d,f,a_),h+=1}await a1(),aB(a=>({...a,phase:"done",current:g.length,status:h>0?ao("importSuccessCount",{count:h}):ao("noNewModelsAddedExisting"),logs:[...a.logs,h>0?ao("importDoneCount",{count:h}):ao("noNewModelsAdded")],importedCount:h})),h>0&&setTimeout(()=>{window.location.reload()},2e3)}catch(a){console.log("Error importing models:",a),aB(b=>({...b,phase:"error",status:ao("importFailed"),error:a instanceof Error?a.message:ao("unexpectedErrorOccurred")}))}finally{ax(!1)}}},bq=async(a,b)=>{az(!0),aB({current:0,total:0,phase:"fetching",status:ao("fetchingModels"),logs:[],error:"",importedCount:0});try{let c=(await a()).models||[];if(0===c.length)return void aB(a=>({...a,phase:"done",status:ao("noModelsFound"),logs:[ao("noModelsReturnedFromEndpoint")]}));aB(a=>({...a,phase:"importing",total:c.length,status:ao("importingModelsProgress",{current:0,total:c.length}),logs:[ao("foundModelsStartingImport",{count:c.length})]}));let d=0;for(let a=0;a<c.length;a++){let e=c[a],f=e.id||e.name||e.model;f&&(aB(b=>({...b,current:a+1,status:ao("importingModelsProgress",{current:a+1,total:c.length}),logs:[...b.logs,ao("importingModelById",{modelId:f})]})),await b(e)&&(d+=1))}aB(a=>({...a,phase:"done",current:c.length,status:d>0?ao("importSuccessCount",{count:d}):ao("noNewModelsAdded"),logs:[...a.logs,d>0?ao("importDoneCount",{count:d}):ao("noNewModelsAdded")],importedCount:d})),d>0&&setTimeout(()=>{window.location.reload()},2e3)}catch(a){console.log("Error importing models:",a),aB(b=>({...b,phase:"error",status:ao("importFailed"),error:a instanceof Error?a.message:ao("unexpectedErrorOccurred")}))}},br=f.some(a=>!1!==a.isActive),bs=f.find(a=>!1!==a.isActive),bt=!!bs?.providerSpecificData?.autoSync,[bu,bv]=(0,e.useState)(!1),bw=async()=>{if(bs&&!bu){bv(!0);try{let a=!bt;await fetch(`/api/providers/${bs.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerSpecificData:{autoSync:a}})}),await a3(),ap[a?"success":"info"](a?ao("autoSyncEnabled"):ao("autoSyncDisabled"))}catch(a){console.log("Error toggling auto-sync:",a),ap.error(ao("autoSyncToggleFailed"))}finally{bv(!1)}}},[bx,by]=(0,e.useState)(!1),bz=(0,e.useMemo)(()=>Object.entries(ai).filter(([,a])=>a.startsWith(`${a_}/`)),[ai,a_]),bA=async()=>{if(!bx&&confirm(ao("clearAllModelsConfirm"))){by(!0);try{(await fetch(`/api/provider-models?provider=${encodeURIComponent(a_)}&all=true`,{method:"DELETE"})).ok?(await Promise.all(bz.map(([a])=>fetch(`/api/models/alias?alias=${encodeURIComponent(a)}`,{method:"DELETE"}).catch(()=>{}))),await a2(),await a1(),ap.success(ao("clearAllModelsSuccess"))):ap.error(ao("clearAllModelsFailed"))}catch{ap.error(ao("clearAllModelsFailed"))}finally{by(!1)}}},bB=(0,e.useMemo)(()=>H(aC.customModels),[aC.customModels]),bC=(0,e.useMemo)(()=>H(aC.modelCompatOverrides),[aC.modelCompatOverrides]),bD=(0,e.useMemo)(()=>(0,C.getCompatibleFallbackModels)(c,aC.customModels),[c,aC.customModels]),bE=(a,b=E.MODEL_COMPAT_PROTOCOL_KEYS[0])=>J(a,b,bB,bC),bF=(a,b=E.MODEL_COMPAT_PROTOCOL_KEYS[0])=>K(a,b,bB,bC),bG=(0,e.useCallback)((a,b)=>M(a,b,bB,bC),[bB,bC]),bH=async(a,b)=>{aH(a);try{let d,e=bB.get(a),f=b.compatByProtocol&&void 0===b.normalizeToolCallId&&void 0===b.preserveOpenAIDeveloperRole&&!("upstreamHeaders"in b);e?f?d={provider:c,modelId:a,compatByProtocol:b.compatByProtocol}:(d={provider:c,modelId:a,modelName:e.name||a,source:e.source||"manual",apiFormat:e.apiFormat||"chat-completions",supportedEndpoints:Array.isArray(e.supportedEndpoints)&&e.supportedEndpoints.length?e.supportedEndpoints:["chat"],normalizeToolCallId:void 0!==b.normalizeToolCallId?b.normalizeToolCallId:!!e.normalizeToolCallId,preserveOpenAIDeveloperRole:void 0!==b.preserveOpenAIDeveloperRole?b.preserveOpenAIDeveloperRole:!Object.prototype.hasOwnProperty.call(e,"preserveOpenAIDeveloperRole")||!!e.preserveOpenAIDeveloperRole},b.compatByProtocol&&(d.compatByProtocol=b.compatByProtocol)):d={provider:c,modelId:a,...b};let g=await fetch("/api/provider-models",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)});if(!g.ok){let a=await L(g);ap.error(a?`${ao("failedSaveCustomModel")} — ${a}`:ao("failedSaveCustomModel"));return}}catch{ap.error(ao("failedSaveCustomModel"));return}finally{aH(null)}try{await a2()}catch{}};return m?(0,d.jsxs)("div",{className:"flex flex-col gap-8",children:[(0,d.jsx)(s.CardSkeleton,{}),(0,d.jsx)(s.CardSkeleton,{})]}):aR?(0,d.jsxs)("div",{className:"flex flex-col gap-8",children:[(0,d.jsxs)("div",{children:[(0,d.jsxs)(j.default,{href:"/dashboard/providers",className:"inline-flex items-center gap-1 text-sm text-text-muted hover:text-primary transition-colors mb-4",children:[(0,d.jsx)("span",{className:"material-symbols-outlined text-lg",children:"arrow_back"}),ao("backToProviders")]}),(0,d.jsxs)("div",{className:"flex items-center gap-4",children:[(0,d.jsx)("div",{className:"rounded-lg flex items-center justify-center",style:{backgroundColor:`${aR.color}15`},children:ak?(0,d.jsx)("span",{className:"text-sm font-bold",style:{color:aR.color},children:aR.textIcon||aR.id.slice(0,2).toUpperCase()}):(0,d.jsx)(k.default,{src:aM&&aR.apiType?"responses"===aR.apiType?"/providers/oai-r.png":"/providers/oai-cc.png":aQ?"/providers/anthropic-m.png":`/providers/${aR.id}.png`,alt:aR.name,width:48,height:48,className:"object-contain rounded-lg max-w-[48px] max-h-[48px]",sizes:"48px",onError:()=>al(!0)})}),(0,d.jsxs)("div",{children:[aR.website?(0,d.jsxs)("a",{href:aR.website,target:"_blank",rel:"noopener noreferrer",className:"text-3xl font-semibold tracking-tight hover:underline inline-flex items-center gap-2",style:{color:aR.color},children:[aR.name,(0,d.jsx)("span",{className:"material-symbols-outlined text-lg opacity-60",children:"open_in_new"})]}):(0,d.jsx)("h1",{className:"text-3xl font-semibold tracking-tight",children:aR.name}),(0,d.jsx)("p",{className:"text-text-muted",children:ao("connectionCountLabel",{count:f.length})})]})]})]}),aP&&q&&(0,d.jsxs)(n.Card,{children:[(0,d.jsxs)("div",{className:"flex items-center justify-between mb-4",children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("h2",{className:"text-lg font-semibold",children:aN?_:aO?ao("anthropicCompatibleDetails"):ao("openaiCompatibleDetails")}),(0,d.jsxs)("p",{className:"text-sm text-text-muted",children:[aQ?ao("messagesApi"):"responses"===q.apiType?ao("responsesApi"):ao("chatCompletions")," ","· ",(q.baseUrl||"").replace(/\/$/,""),"/",aN?(q.chatPath||aa).replace(/^\//,""):aO?(q.chatPath||"/messages").replace(/^\//,""):"responses"===q.apiType?(q.chatPath||"/responses").replace(/^\//,""):(q.chatPath||"/chat/completions").replace(/^\//,"")]})]}),(0,d.jsxs)("div",{className:"flex items-center gap-2",children:[(0,d.jsx)(o.Button,{size:"sm",icon:"add",onClick:()=>G(!0),disabled:f.length>0,children:ao("add")}),(0,d.jsx)(o.Button,{size:"sm",variant:"secondary",icon:"edit",onClick:()=>U(!0),children:ao("edit")}),(0,d.jsx)(o.Button,{size:"sm",variant:"secondary",icon:"delete",onClick:async()=>{if(confirm(ao("deleteCompatibleNodeConfirm",{type:aN?$:aO?ao("anthropic"):ao("openai")})))try{(await fetch(`/api/provider-nodes/${c}`,{method:"DELETE"})).ok&&b.push("/dashboard/providers")}catch(a){console.log("Error deleting provider node:",a)}},children:ao("delete")})]})]}),f.length>0&&(0,d.jsx)("p",{className:"text-sm text-text-muted",children:ao("singleConnectionPerCompatible")})]}),(0,d.jsxs)(n.Card,{children:[(0,d.jsxs)("div",{className:"flex items-center justify-between mb-4",children:[(0,d.jsxs)("div",{className:"flex items-center gap-3",children:[(0,d.jsx)("h2",{className:"text-lg font-semibold",children:ao("connections")}),(0,d.jsxs)("button",{onClick:()=>ar({level:"provider",id:c,label:aR?.name||c}),className:`inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium transition-all ${as?.providers?.[c]?"bg-amber-500/15 text-amber-500 hover:bg-amber-500/25":"bg-black/[0.03] dark:bg-white/[0.03] text-text-muted/50 hover:text-text-muted hover:bg-black/[0.06] dark:hover:bg-white/[0.06]"}`,title:as?.providers?.[c]?ao("providerProxyTitleConfigured",{host:as.providers[c].host||ao("configured")}):ao("providerProxyConfigureHint"),children:[(0,d.jsx)("span",{className:"material-symbols-outlined text-[14px]",children:"vpn_lock"}),as?.providers?.[c]&&as.providers[c].host||ao("providerProxy")]})]}),f.length>1&&(0,d.jsxs)("button",{onClick:bh,disabled:ae||!!ac,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium border transition-colors ${ae?"bg-primary/20 border-primary/40 text-primary animate-pulse":"bg-bg-subtle border-border text-text-muted hover:text-text-primary hover:border-primary/40"}`,title:ao("testAll"),"aria-label":ao("testAll"),children:[(0,d.jsx)("span",{className:"material-symbols-outlined text-[14px]",children:ae?"sync":"play_arrow"}),ae?ao("testing"):ao("testAll")]}),aP?0===f.length&&(0,d.jsx)(o.Button,{size:"sm",icon:"add",onClick:()=>G(!0),children:ao("add")}):(0,d.jsxs)("div",{className:"flex items-center gap-2",children:[(0,d.jsx)(o.Button,{size:"sm",icon:"add",onClick:ba,children:aT?"Add PAT":ao("add")}),"qoder"===c&&(0,d.jsx)(o.Button,{size:"sm",variant:"secondary",onClick:()=>A(!0),children:"Experimental OAuth"})]})]}),0===f.length?(0,d.jsxs)("div",{className:"text-center py-12",children:[(0,d.jsx)("div",{className:"inline-flex items-center justify-center w-16 h-16 rounded-full bg-primary/10 text-primary mb-4",children:(0,d.jsx)("span",{className:"material-symbols-outlined text-[32px]",children:aU?"lock":"key"})}),(0,d.jsx)("p",{className:"text-text-main font-medium mb-1",children:ao("noConnectionsYet")}),(0,d.jsx)("p",{className:"text-sm text-text-muted mb-4",children:ao("addFirstConnectionHint")}),!aP&&(0,d.jsxs)("div",{className:"flex items-center justify-center gap-2",children:[(0,d.jsx)(o.Button,{icon:"add",onClick:ba,children:aT?"Add PAT":ao("addConnection")}),"qoder"===c&&(0,d.jsx)(o.Button,{variant:"secondary",onClick:()=>A(!0),children:"Experimental OAuth"})]})]}):(()=>{let a=[...f].sort((a,b)=>(a.priority||0)-(b.priority||0));if(!a.some(a=>a.providerSpecificData?.tag))return(0,d.jsx)("div",{className:"flex flex-col divide-y divide-black/[0.03] dark:divide-white/[0.03]",children:a.map((b,e)=>(0,d.jsx)(V,{connection:b,isOAuth:"oauth"===b.authType,isFirst:0===e,isLast:e===a.length-1,onMoveUp:()=>bo(b,a[e-1]),onMoveDown:()=>bo(b,a[e+1]),onToggleActive:a=>bd(b.id,a),onToggleRateLimit:a=>be(b.id,a),isCodex:"codex"===c,onToggleCodex5h:a=>bf(b.id,"use5h",a),onToggleCodexWeekly:a=>bf(b.id,"useWeekly",a),onRetest:()=>bg(b.id),isRetesting:ac===b.id,onEdit:()=>{ab(b),O(!0)},onDelete:()=>a8(b.id),onReauth:"oauth"===b.authType?()=>A(!0):void 0,onRefreshToken:"oauth"===b.authType?()=>bl(b.id):void 0,isRefreshing:bi===b.id,onApplyCodexAuthLocal:"codex"===c?()=>bm(b.id):void 0,isApplyingCodexAuthLocal:aI===b.id,onExportCodexAuthFile:"codex"===c?()=>bn(b.id):void 0,isExportingCodexAuthFile:aK===b.id,onProxy:()=>ar({level:"key",id:b.id,label:b.name||b.email||b.id}),hasProxy:!!au[b.id]?.proxy,proxySource:au[b.id]?.level||null,proxyHost:au[b.id]?.proxy?.host||null},b.id))});let b=new Map;for(let c of a){let a=c.providerSpecificData?.tag?.trim()||"";b.has(a)||b.set(a,[]),b.get(a).push(c)}let e=Array.from(b.keys()).sort((a,b)=>""===a?-1:""===b?1:a.localeCompare(b));return(0,d.jsx)("div",{className:"flex flex-col gap-0",children:e.map((f,g)=>{let h=b.get(f);return(0,d.jsxs)("div",{className:g>0?"border-t border-black/[0.06] dark:border-white/[0.06] mt-1 pt-1":"",children:[f&&(0,d.jsxs)("div",{className:"flex items-center gap-2 px-3 pt-2 pb-1",children:[(0,d.jsx)("span",{className:"material-symbols-outlined text-[13px] text-text-muted/50",children:"label"}),(0,d.jsx)("span",{className:"text-[11px] font-semibold uppercase tracking-widest text-text-muted/60 select-none",children:f}),(0,d.jsx)("div",{className:"flex-1 h-px bg-black/[0.04] dark:bg-white/[0.04]"}),(0,d.jsx)("span",{className:"text-[10px] text-text-muted/40",children:h.length})]}),(0,d.jsx)("div",{className:"flex flex-col divide-y divide-black/[0.03] dark:divide-white/[0.03]",children:h.map((b,f)=>(0,d.jsx)(V,{connection:b,isOAuth:"oauth"===b.authType,isFirst:0===g&&0===f,isLast:g===e.length-1&&f===h.length-1,onMoveUp:()=>bo(b,a[a.indexOf(b)-1]),onMoveDown:()=>bo(b,a[a.indexOf(b)+1]),onToggleActive:a=>bd(b.id,a),onToggleRateLimit:a=>be(b.id,a),isCodex:"codex"===c,onToggleCodex5h:a=>bf(b.id,"use5h",a),onToggleCodexWeekly:a=>bf(b.id,"useWeekly",a),onRetest:()=>bg(b.id),isRetesting:ac===b.id,onEdit:()=>{ab(b),O(!0)},onDelete:()=>a8(b.id),onReauth:"oauth"===b.authType?()=>A(!0):void 0,onRefreshToken:"oauth"===b.authType?()=>bl(b.id):void 0,isRefreshing:bi===b.id,onApplyCodexAuthLocal:"codex"===c?()=>bm(b.id):void 0,isApplyingCodexAuthLocal:aI===b.id,onExportCodexAuthFile:"codex"===c?()=>bn(b.id):void 0,isExportingCodexAuthFile:aK===b.id,onProxy:()=>ar({level:"key",id:b.id,label:b.name||b.email||b.id}),hasProxy:!!au[b.id]?.proxy,proxySource:au[b.id]?.level||null,proxyHost:au[b.id]?.proxy?.host||null},b.id))})]},f||"__untagged__")})})})()]}),!aZ&&(0,d.jsxs)(n.Card,{children:[(0,d.jsx)("h2",{className:"text-lg font-semibold mb-4",children:ao("availableModels")}),(()=>{let a=a$&&br&&(0,d.jsxs)("button",{onClick:bw,disabled:bu,className:"flex items-center gap-1.5 px-2.5 py-1 rounded-lg border border-border bg-transparent cursor-pointer text-[12px] disabled:opacity-50 disabled:cursor-not-allowed",title:ao("autoSyncTooltip"),children:[(0,d.jsx)("span",{className:"material-symbols-outlined text-[16px]",style:{color:bt?"#22c55e":"var(--color-text-muted)"},children:bt?"toggle_on":"toggle_off"}),(0,d.jsx)("span",{className:"text-text-main",children:ao("autoSync")})]}),b=(aC.customModels.length>0||bz.length>0)&&(0,d.jsxs)("button",{onClick:bA,disabled:bx,className:"flex items-center gap-1.5 px-2.5 py-1 rounded-lg border border-red-300 dark:border-red-800 bg-transparent cursor-pointer text-[12px] text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 disabled:opacity-50 disabled:cursor-not-allowed",title:ao("clearAllModels"),children:[(0,d.jsx)("span",{className:"material-symbols-outlined text-[16px]",children:"delete_sweep"}),(0,d.jsx)("span",{children:ao("clearAllModels")})]});if(aY){let e="openrouter"===c?ao("openRouterAnyModelHint"):aN?"CC Compatible available models mirror the OAuth Claude Code provider list.":ao("compatibleModelsDescription",{type:aO?ao("anthropic"):ao("openai")}),g="openrouter"===c?ao("modelIdFromOpenRouter"):ao("modelId"),h="openrouter"===c?ao("openRouterModelPlaceholder"):aN?"claude-sonnet-4-6":aO?ao("anthropicCompatibleModelPlaceholder"):ao("openaiCompatibleModelPlaceholder");return(0,d.jsxs)("div",{children:[(0,d.jsxs)("div",{className:"flex items-center gap-2 mb-4",children:[a,b]}),(0,d.jsx)(T,{providerStorageAlias:a_,providerDisplayAlias:a0,modelAliases:ai,fallbackModels:bD,description:e,inputLabel:g,inputPlaceholder:h,copied:am,onCopy:an,onSetAlias:a6,onDeleteAlias:a7,connections:f,isAnthropic:aQ,onImportWithProgress:bq,t:ao,effectiveModelNormalize:bE,effectiveModelPreserveDeveloper:bF,getUpstreamHeadersRecord:bG,saveModelCompatFlags:bH,compatSavingModelId:aG,onModelsChanged:a2,allowImport:a$})]})}if(aR.passthroughModels)return(0,d.jsxs)("div",{children:[(0,d.jsxs)("div",{className:"flex items-center gap-2 mb-4",children:[(0,d.jsx)(o.Button,{size:"sm",variant:"secondary",icon:"download",onClick:bp,disabled:!br||aw,children:aw?ao("importingModels"):ao("importFromModels")}),a,b,!br&&(0,d.jsx)("span",{className:"text-xs text-text-muted",children:ao("addConnectionToImport")})]}),(0,d.jsx)(Q,{providerAlias:aX,modelAliases:ai,copied:am,onCopy:an,onSetAlias:a6,onDeleteAlias:a7,t:ao,effectiveModelNormalize:bE,effectiveModelPreserveDeveloper:bF,getUpstreamHeadersRecord:bG,saveModelCompatFlags:bH,compatSavingModelId:aG})]});let e="gemini"===c?null:(0,d.jsxs)("div",{className:"flex items-center gap-2 mb-4",children:[(0,d.jsx)(o.Button,{size:"sm",variant:"secondary",icon:"download",onClick:bp,disabled:!br||aw,children:aw?ao("importingModels"):ao("importFromModels")}),a,!br&&(0,d.jsx)("span",{className:"text-xs text-text-muted",children:ao("addConnectionToImport")})]});return 0===aW.length?(0,d.jsxs)("div",{children:[e,(0,d.jsx)("p",{className:"text-sm text-text-muted",children:ao("noModelsConfigured")})]}):(0,d.jsxs)("div",{children:[e,(0,d.jsx)("div",{className:"flex flex-wrap gap-3",children:aW.map(a=>(0,d.jsx)(P,{model:a,fullModel:`${a0}/${a.id}`,copied:am,onCopy:an,t:ao,showDeveloperToggle:!0,effectiveModelNormalize:bE,effectiveModelPreserveDeveloper:bF,getUpstreamHeadersRecord:b=>bG(a.id,b),saveModelCompatFlags:bH,compatDisabled:aG===a.id},a.id))})]})})(),!aY&&"gemini"!==c&&(0,d.jsx)(S,{providerId:c,providerAlias:a0,copied:am,onCopy:an,onModelsChanged:a2})]}),aZ&&(0,d.jsxs)(n.Card,{children:[(0,d.jsx)("h2",{className:"text-lg font-semibold mb-4",children:ao("searchProvider")||"Search Provider"}),(0,d.jsx)("p",{className:"text-sm text-text-muted",children:ao("searchProviderDesc")||"This provider is used for web search via POST /v1/search. No model configuration needed — search providers are ready to use once an API key is connected."}),"perplexity-search"===c&&(0,d.jsxs)("div",{className:"mt-3 flex items-center gap-2 px-3 py-2 rounded-lg bg-blue-500/10 border border-blue-500/20",children:[(0,d.jsx)("span",{className:"material-symbols-outlined text-sm text-blue-400",children:"link"}),(0,d.jsxs)("p",{className:"text-xs text-blue-300",children:["Uses the same API key as ",(0,d.jsx)("strong",{children:"Perplexity"})," (chat provider). If you already have Perplexity configured, no additional setup is needed."]})]})]}),"kiro"===c?(0,d.jsx)(u.KiroOAuthWrapper,{isOpen:x,providerInfo:aR,onSuccess:a9,onClose:()=>{A(!1)}}):"cursor"===c?(0,d.jsx)(v.CursorAuthModal,{isOpen:x,onSuccess:a9,onClose:()=>{A(!1)}}):(0,d.jsx)(t.OAuthModal,{isOpen:x,provider:c,providerInfo:aR,onSuccess:a9,onClose:()=>{A(!1)}}),(0,d.jsx)(W,{isOpen:F,provider:c,providerName:aR.name,isCompatible:aP,isAnthropic:aQ,isCcCompatible:aN,onSave:bb,onClose:()=>G(!1)}),(0,d.jsx)(Y,{isOpen:I,connection:X,onSave:bc,onClose:()=>O(!1)}),aP&&(0,d.jsx)(Z,{isOpen:R,node:q,onSave:a4,onClose:()=>U(!1),isAnthropic:aQ,isCcCompatible:aN}),ag&&(0,d.jsxs)("div",{className:"fixed inset-0 z-50 flex items-start justify-center pt-[10vh]",onClick:()=>ah(null),children:[(0,d.jsx)("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),(0,d.jsxs)("div",{className:"relative bg-bg-primary border border-border rounded-xl w-full max-w-[600px] max-h-[80vh] overflow-y-auto shadow-2xl",onClick:a=>a.stopPropagation(),children:[(0,d.jsxs)("div",{className:"sticky top-0 z-10 flex items-center justify-between px-5 py-3 border-b border-border bg-bg-primary/95 backdrop-blur-sm rounded-t-xl",children:[(0,d.jsx)("h3",{className:"font-semibold",children:ao("testResults")}),(0,d.jsx)("button",{onClick:()=>ah(null),className:"p-1 rounded-lg hover:bg-bg-subtle text-text-muted hover:text-text-primary transition-colors","aria-label":"Close",children:(0,d.jsx)("span",{className:"material-symbols-outlined text-lg",children:"close"})})]}),(0,d.jsx)("div",{className:"p-5",children:ag.error&&(!ag.results||0===ag.results.length)?(0,d.jsxs)("div",{className:"text-center py-6",children:[(0,d.jsx)("span",{className:"material-symbols-outlined text-red-500 text-[32px] mb-2 block",children:"error"}),(0,d.jsx)("p",{className:"text-sm text-red-400",children:String(ag.error)})]}):(0,d.jsxs)("div",{className:"flex flex-col gap-3",children:[ag.summary&&(0,d.jsxs)("div",{className:"flex items-center gap-3 text-xs mb-1",children:[(0,d.jsx)("span",{className:"text-text-muted",children:aR?.name||c}),(0,d.jsx)("span",{className:"px-2 py-0.5 rounded bg-emerald-500/15 text-emerald-400 font-medium",children:ao("passedCount",{count:ag.summary.passed})}),ag.summary.failed>0&&(0,d.jsx)("span",{className:"px-2 py-0.5 rounded bg-red-500/15 text-red-400 font-medium",children:ao("failedCount",{count:ag.summary.failed})}),(0,d.jsx)("span",{className:"text-text-muted ml-auto",children:ao("testedCount",{count:ag.summary.total})})]}),(ag.results||[]).map((a,b)=>(0,d.jsxs)("div",{className:"flex items-center gap-2 text-xs px-3 py-2 rounded-lg bg-black/[0.03] dark:bg-white/[0.03]",children:[(0,d.jsx)("span",{className:`material-symbols-outlined text-[16px] ${a.valid?"text-emerald-500":"text-red-500"}`,children:a.valid?"check_circle":"error"}),(0,d.jsx)("div",{className:"flex-1 min-w-0",children:(0,d.jsx)("span",{className:"font-medium",children:a.connectionName})}),void 0!==a.latencyMs&&(0,d.jsx)("span",{className:"text-text-muted font-mono tabular-nums",children:ao("millisecondsAbbr",{value:a.latencyMs})}),(0,d.jsx)("span",{className:`text-[10px] uppercase font-bold px-1.5 py-0.5 rounded ${a.valid?"bg-emerald-500/15 text-emerald-400":"bg-red-500/15 text-red-400"}`,children:a.valid?ao("okShort"):a.diagnosis?.type||ao("errorShort")})]},a.connectionId||b)),(!ag.results||0===ag.results.length)&&(0,d.jsx)("div",{className:"text-center py-4 text-text-muted text-sm",children:ao("noActiveConnectionsInGroup")})]})})]})]}),aq&&(0,d.jsx)(y.ProxyConfigModal,{isOpen:!!aq,onClose:()=>ar(null),level:aq.level,levelId:aq.id,levelLabel:aq.label,onSaved:()=>void a5(f)}),(0,d.jsx)(r.Modal,{isOpen:ay,onClose:()=>{("done"===aA.phase||"error"===aA.phase)&&az(!1)},title:ao("importingModelsTitle"),size:"md",closeOnOverlay:!1,showCloseButton:"done"===aA.phase||"error"===aA.phase,children:(0,d.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,d.jsxs)("div",{className:"flex items-center gap-3",children:["fetching"===aA.phase&&(0,d.jsx)("span",{className:"material-symbols-outlined text-primary animate-spin",children:"progress_activity"}),"importing"===aA.phase&&(0,d.jsx)("span",{className:"material-symbols-outlined text-primary animate-spin",children:"progress_activity"}),"done"===aA.phase&&(0,d.jsx)("span",{className:"material-symbols-outlined text-green-500",children:"check_circle"}),"error"===aA.phase&&(0,d.jsx)("span",{className:"material-symbols-outlined text-red-500",children:"error"}),(0,d.jsx)("span",{className:"text-sm font-medium text-text-main",children:aA.status})]}),("importing"===aA.phase||"done"===aA.phase)&&aA.total>0&&(0,d.jsxs)("div",{className:"w-full",children:[(0,d.jsxs)("div",{className:"flex items-center justify-between mb-1",children:[(0,d.jsxs)("span",{className:"text-xs text-text-muted",children:[aA.current," / ",aA.total]}),(0,d.jsxs)("span",{className:"text-xs text-text-muted",children:[Math.round(aA.current/aA.total*100),"%"]})]}),(0,d.jsx)("div",{className:"w-full h-2.5 bg-black/10 dark:bg-white/10 rounded-full overflow-hidden",children:(0,d.jsx)("div",{className:"h-full rounded-full transition-all duration-300 ease-out",style:{width:`${aA.current/aA.total*100}%`,background:"done"===aA.phase?"linear-gradient(90deg, #22c55e, #16a34a)":"linear-gradient(90deg, var(--color-primary), var(--color-primary-hover, var(--color-primary)))"}})})]}),"fetching"===aA.phase&&(0,d.jsx)("div",{className:"w-full h-2.5 bg-black/10 dark:bg-white/10 rounded-full overflow-hidden",children:(0,d.jsx)("div",{className:"h-full rounded-full animate-pulse",style:{width:"60%",background:"linear-gradient(90deg, var(--color-primary), var(--color-primary-hover, var(--color-primary)))"}})}),"error"===aA.phase&&aA.error&&(0,d.jsx)("div",{className:"p-3 rounded-lg bg-red-500/10 border border-red-500/20",children:(0,d.jsx)("p",{className:"text-sm text-red-400",children:aA.error})}),aA.logs.length>0&&(0,d.jsx)("div",{className:"max-h-48 overflow-y-auto rounded-lg bg-black/5 dark:bg-white/5 p-3 border border-black/5 dark:border-white/5",children:(0,d.jsx)("div",{className:"flex flex-col gap-1",children:aA.logs.map((a,b)=>(0,d.jsx)("p",{className:`text-xs font-mono ${a.startsWith("✓")?"text-green-500 font-semibold":"text-text-muted"}`,children:a},b))})}),"done"===aA.phase&&(0,d.jsx)("div",{className:"flex justify-center",children:(0,d.jsx)("button",{onClick:()=>az(!1),className:"px-4 py-2 text-sm font-medium rounded-lg bg-primary text-white hover:opacity-90 transition-opacity",children:ao("close")||"Close"})})]})})]}):(0,d.jsxs)("div",{className:"text-center py-20",children:[(0,d.jsx)("p",{className:"text-text-muted",children:ao("providerNotFound")}),(0,d.jsx)(j.default,{href:"/dashboard/providers",className:"text-primary mt-4 inline-block",children:ao("backToProviders")})]})}]),c()}catch(a){c(a)}},!1)];
|
|
1
|
+
module.exports=[460176,a=>{"use strict";var b=a.i(743442);a.s(["OAuthModal",()=>b.default])},202373,a=>{"use strict";var b=a.i(394093);a.s(["KiroOAuthWrapper",()=>b.default])},182527,a=>{"use strict";var b=a.i(296193);a.s(["CursorAuthModal",()=>b.default])},794711,a=>{"use strict";a.s(["MODEL_COMPAT_PROTOCOL_KEYS",0,["openai","openai-responses","claude"]])},333474,a=>{"use strict";a.s(["resolveManagedModelAlias",0,function({modelId:a,fullModel:b,providerDisplayAlias:c,existingAliases:d}){let e=function(a){let b=a.trim();if(!b)return"";let c=b.split("/").map(a=>a.trim()).filter(Boolean);return c[c.length-1]||b}(a);if(!e)return null;for(let[a,c]of Object.entries(d))if(c===b)return a;let f=c.trim(),g=[],h=new Set,i=a=>{let b=a.trim();!b||h.has(b)||(h.add(b),g.push(b))};for(let a of(i(e),f&&i(`${f}-${e}`),g))if(!(a in d)||d[a]===b)return a;for(let a=2;a<=5e3;a+=1){if(f){let c=`${f}-${e}-${a}`;if(!(c in d)||d[c]===b)return c}let c=`${e}-${a}`;if(!(c in d)||d[c]===b)return c}return null}])},755235,a=>a.a(async(b,c)=>{try{var d=a.i(187924),e=a.i(572131),f=a.i(935112),g=a.i(240246),h=a.i(341212),i=a.i(50944),j=a.i(238246),k=a.i(571987),l=a.i(415925),m=a.i(442308),n=a.i(292216),o=a.i(294023),p=a.i(818465),q=a.i(489108),r=a.i(563203),s=a.i(831097),t=a.i(460176),u=a.i(202373),v=a.i(182527),w=a.i(709918),x=a.i(525290),y=a.i(248172),z=a.i(662073),A=a.i(867933),B=a.i(911655),C=a.i(455407),D=a.i(386592),E=a.i(794711),F=a.i(333474),G=b([m,z,A,C]);function H(a){let b=new Map;for(let c of a)c.id&&b.set(c.id,c);return b}function I(a,b,c){return a?.compatByProtocol?.[c]??b?.compatByProtocol?.[c]}function J(a,b,c,d){let e=c.get(a),f=d.get(a),g=I(e,f,b);return g&&Object.prototype.hasOwnProperty.call(g,"normalizeToolCallId")?!!g.normalizeToolCallId:!!e?.normalizeToolCallId||!!f?.normalizeToolCallId}function K(a,b,c,d){let e=c.get(a),f=d.get(a),g=I(e,f,b);return g&&Object.prototype.hasOwnProperty.call(g,"preserveOpenAIDeveloperRole")?!!g.preserveOpenAIDeveloperRole:e&&Object.prototype.hasOwnProperty.call(e,"preserveOpenAIDeveloperRole")?!!e.preserveOpenAIDeveloperRole:!(f&&Object.prototype.hasOwnProperty.call(f,"preserveOpenAIDeveloperRole"))||!!f.preserveOpenAIDeveloperRole}async function L(a){try{let b=await a.json(),c=b?.error;if(Array.isArray(c?.details)&&c.details.length>0)return c.details.map(a=>{let b="string"==typeof a.field&&a.field?a.field:"?",c="string"==typeof a.message?a.message:"";return c?`${b}: ${c}`:b}).join("; ");if("string"==typeof c?.message&&c.message.trim())return c.message.trim()}catch{}return a.statusText?.trim()||`HTTP ${a.status}`}function M(a,b,c,d){let e=c.get(a),f=d.get(a),g={};e?.upstreamHeaders&&"object"==typeof e.upstreamHeaders?Object.assign(g,e.upstreamHeaders):f?.upstreamHeaders&&"object"==typeof f.upstreamHeaders&&Object.assign(g,f.upstreamHeaders);let h=I(e,f,b);return h?.upstreamHeaders&&"object"==typeof h.upstreamHeaders&&Object.assign(g,h.upstreamHeaders),g}[m,z,A,C]=G.then?(await G)():G;let $="CC Compatible",_="CC Compatible Details",aa="/v1/messages?beta=true";function N(a){let b=a&&"object"==typeof a&&!Array.isArray(a)?a:{};return{use5h:"boolean"!=typeof b.use5h||b.use5h,useWeekly:"boolean"!=typeof b.useWeekly||b.useWeekly}}function O({t:a,effectiveModelNormalize:b,effectiveModelPreserveDeveloper:c,getUpstreamHeadersRecord:g,onCompatPatch:h,showDeveloperToggle:i=!0,disabled:j}){let[k,l]=(0,e.useState)(!1),[m,n]=(0,e.useState)(E.MODEL_COMPAT_PROTOCOL_KEYS[0]),[o,p]=(0,e.useState)([]),[r,s]=(0,e.useState)(null),[t,u]=(0,e.useState)(null),v=(0,e.useRef)(null),x=(0,e.useRef)(null),[y,z]=(0,e.useState)(null),A=(0,e.useRef)(0),B=(0,e.useRef)([]);B.current=o;let C=()=>(A.current+=1,`uh-${A.current}`),D=b(m),F=c(m),G=i&&"claude"!==m,H=(0,e.useCallback)(a=>{let b,c,d=function(a){let b={};for(let c of a){let a=c.name.trim();a&&(b[a]=c.value)}return b}(a),e=g(m);b=Object.keys(d).sort(),c=Object.keys(e).sort(),b.length===c.length&&b.every((a,b)=>a===c[b]&&d[a]===e[a])||h(m,{upstreamHeaders:d})},[g,h,m]),I=(0,e.useCallback)(()=>{queueMicrotask(()=>H(B.current))},[H]);(0,e.useEffect)(()=>{if(k)return()=>{H(B.current)}},[k,H]),(0,e.useEffect)(()=>{let a;if(!k)return;let b=g(m);p((a=Object.entries(b).filter(([a])=>a.trim()),0===a.length?[{id:C(),name:"",value:""}]:a.map(([a,b])=>({id:C(),name:a,value:b}))))},[k,m]),(0,e.useEffect)(()=>{s(null),u(null)},[k,m]);let J=o.filter(a=>a.name.trim()).length<16,K=(a,b)=>{p(c=>c.map(c=>c.id===a?{...c,...b}:c))};(0,e.useEffect)(()=>{if(!k)return;let a=a=>{let b=a.target,c=v.current?.contains(b),d=x.current?.contains(b);c||d||l(!1)};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[k]);let L=(0,e.useCallback)(()=>{if(!k||!v.current)return;let a=v.current.getBoundingClientRect(),b=Math.min(window.innerWidth-20,384),c=a.right-b;c=Math.max(10,Math.min(c,window.innerWidth-b-10)),z({top:a.bottom+8,left:c,width:b})},[k]);return(0,e.useLayoutEffect)(()=>k?(L(),window.addEventListener("resize",L),window.addEventListener("scroll",L,!0),()=>{window.removeEventListener("resize",L),window.removeEventListener("scroll",L,!0)}):void z(null),[k,L]),(0,d.jsxs)("div",{className:"relative inline-flex",ref:v,children:[(0,d.jsxs)("button",{type:"button",onClick:()=>l(a=>!a),disabled:j,className:"inline-flex items-center gap-1.5 px-2.5 py-1.5 text-xs font-medium rounded-lg border border-border bg-background text-text-muted hover:bg-muted hover:text-text-main disabled:opacity-50 transition-colors",title:a("compatAdjustmentsTitle"),children:[(0,d.jsx)("span",{className:"material-symbols-outlined text-base leading-none",children:"tune"}),a("compatButtonLabel")]}),k&&"u">typeof document&&y&&(0,f.createPortal)((0,d.jsxs)("div",{ref:x,className:"flex max-h-[min(82vh,42rem)] flex-col overflow-hidden rounded-xl border-2 border-zinc-200 bg-white shadow-2xl dark:border-zinc-600 dark:bg-zinc-950",style:{position:"fixed",top:y.top,left:y.left,width:y.width,zIndex:10040},children:[(0,d.jsxs)("div",{className:"shrink-0 border-b-2 border-zinc-200 bg-zinc-100 px-3 py-2.5 dark:border-zinc-600 dark:bg-zinc-900",children:[(0,d.jsx)("p",{className:"text-xs font-semibold text-text-main",children:a("compatAdjustmentsTitle")}),(0,d.jsx)("p",{className:"text-[11px] text-text-muted mt-1 leading-relaxed",children:a("compatProtocolHint")})]}),(0,d.jsxs)("div",{className:"min-h-0 flex-1 overflow-x-hidden overflow-y-auto bg-white p-3 [scrollbar-gutter:stable] [scrollbar-width:thin] dark:bg-zinc-950",children:[(0,d.jsx)("label",{className:"block text-[11px] font-medium text-text-muted mb-1.5",children:a("compatProtocolLabel")}),(0,d.jsx)("select",{value:m,onChange:a=>n(a.target.value),disabled:j,className:"mb-4 w-full rounded-lg border border-zinc-200 bg-white px-2.5 py-2 text-xs text-text-main focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/30 dark:border-zinc-600 dark:bg-zinc-900",children:E.MODEL_COMPAT_PROTOCOL_KEYS.map(b=>(0,d.jsx)("option",{value:b,children:a("openai"===b?"compatProtocolOpenAI":"openai-responses"===b?"compatProtocolOpenAIResponses":"claude"===b?"compatProtocolClaude":"compatProtocolOpenAI")},b))}),(0,d.jsxs)("div",{className:"flex flex-col gap-3.5",children:[(0,d.jsx)(w.Toggle,{size:"sm",label:a("compatToolIdShort"),title:a("normalizeToolCallIdLabel"),checked:D,onChange:a=>h(m,{normalizeToolCallId:a}),disabled:j}),G&&(0,d.jsx)(w.Toggle,{size:"sm",label:a("compatDoNotPreserveDeveloper"),title:a("preserveDeveloperRoleLabel"),checked:!1===F,onChange:a=>h(m,{preserveOpenAIDeveloperRole:!a}),disabled:j})]}),(0,d.jsxs)("div",{className:"mt-4 rounded-lg border-2 border-zinc-200 bg-zinc-100 p-3 dark:border-zinc-600 dark:bg-zinc-900",children:[(0,d.jsx)("label",{className:"block text-[11px] font-semibold text-text-main mb-1",children:a("compatUpstreamHeadersLabel")}),(0,d.jsx)("p",{className:"text-[11px] text-text-muted mb-3 leading-relaxed",children:a("compatUpstreamHeadersHint")}),(0,d.jsxs)("div",{className:"space-y-2",children:[(0,d.jsxs)("div",{className:"grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)_auto] gap-1.5 items-end text-[10px] font-medium uppercase tracking-wide text-text-muted px-0.5",children:[(0,d.jsx)("span",{children:a("compatUpstreamHeaderName")}),(0,d.jsx)("span",{className:"col-span-1",children:a("compatUpstreamHeaderValue")}),(0,d.jsx)("span",{className:"w-8 shrink-0","aria-hidden":!0})]}),o.map(b=>(0,d.jsxs)("div",{className:"grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)_auto] gap-1.5 items-center",children:[(0,d.jsx)(q.Input,{value:b.name,onChange:a=>K(b.id,{name:a.target.value}),onBlur:I,disabled:j,placeholder:"Authentication",className:"gap-0 min-w-0",inputClassName:"h-9 bg-white py-1.5 px-2 text-xs font-mono dark:bg-zinc-900",autoComplete:"off"}),(0,d.jsx)("div",{className:"min-w-0",onMouseEnter:()=>s(b.id),onMouseLeave:()=>s(a=>a===b.id?null:a),children:(0,d.jsx)(q.Input,{type:r===b.id||t===b.id?"text":"password",value:b.value,onChange:a=>K(b.id,{value:a.target.value}),onFocus:()=>u(b.id),onBlur:()=>{u(a=>a===b.id?null:a),I()},disabled:j,placeholder:"•••",className:"gap-0 min-w-0",inputClassName:"h-9 bg-white py-1.5 px-2 text-xs dark:bg-zinc-900",autoComplete:"off",spellCheck:!1})}),(0,d.jsx)("button",{type:"button",disabled:j||o.length<=1,onClick:()=>{var a;return a=b.id,void p(b=>{let c=b.filter(b=>b.id!==a),d=0===c.length?[{id:C(),name:"",value:""}]:c;return queueMicrotask(()=>H(d)),d})},title:a("compatUpstreamRemoveRow"),className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg border border-border/80 text-text-muted hover:bg-red-500/10 hover:text-red-600 dark:hover:text-red-400 disabled:opacity-30 disabled:hover:bg-transparent disabled:hover:text-text-muted transition-colors",children:(0,d.jsx)("span",{className:"material-symbols-outlined text-lg leading-none",children:"close"})})]},b.id))]}),(0,d.jsxs)("button",{type:"button",disabled:j||!J,onClick:()=>{J&&p(a=>[...a,{id:C(),name:"",value:""}])},className:"mt-3 flex w-full items-center justify-center gap-1.5 rounded-lg border border-dashed border-border py-2 text-xs font-medium text-primary hover:bg-primary/5 disabled:opacity-40 disabled:hover:bg-transparent transition-colors",children:[(0,d.jsx)("span",{className:"material-symbols-outlined text-base leading-none",children:"add"}),a("compatUpstreamAddRow")]})]})]})]}),document.body)]})}function P({model:a,fullModel:b,copied:c,onCopy:e,t:f,showDeveloperToggle:g=!0,effectiveModelNormalize:h,effectiveModelPreserveDeveloper:i,getUpstreamHeadersRecord:j,saveModelCompatFlags:k,compatDisabled:l}){return(0,d.jsxs)("div",{className:"flex min-w-[220px] max-w-md items-center gap-2 rounded-lg border border-border px-3 py-2 hover:bg-sidebar/50",children:[(0,d.jsxs)("div",{className:"flex min-w-0 flex-1 flex-wrap items-center gap-2",children:[(0,d.jsx)("span",{className:"material-symbols-outlined shrink-0 text-base text-text-muted",children:"smart_toy"}),(0,d.jsx)("code",{className:"rounded bg-sidebar px-1.5 py-0.5 font-mono text-xs text-text-muted",children:b}),(0,d.jsx)("button",{onClick:()=>e(b,`model-${a.id}`),className:"rounded p-0.5 text-text-muted hover:bg-sidebar hover:text-primary",title:f("copyModel"),children:(0,d.jsx)("span",{className:"material-symbols-outlined text-sm",children:c===`model-${a.id}`?"check":"content_copy"})})]}),(0,d.jsx)("div",{className:"shrink-0",children:(0,d.jsx)(O,{t:f,effectiveModelNormalize:b=>h(a.id,b),effectiveModelPreserveDeveloper:b=>i(a.id,b),getUpstreamHeadersRecord:j,onCompatPatch:(b,c)=>k(a.id,{compatByProtocol:{[b]:c}}),showDeveloperToggle:g,disabled:l})})]})}function Q({providerAlias:a,modelAliases:b,copied:c,onCopy:f,onSetAlias:g,onDeleteAlias:h,t:i,effectiveModelNormalize:j,effectiveModelPreserveDeveloper:k,getUpstreamHeadersRecord:l,saveModelCompatFlags:m,compatSavingModelId:n}){let[p,q]=(0,e.useState)(""),[r,s]=(0,e.useState)(!1),t=Object.entries(b).filter(([,b])=>b.startsWith(`${a}/`)).map(([b,c])=>({modelId:c.replace(`${a}/`,""),fullModel:c,alias:b})),u=async()=>{let a;if(!p.trim()||r)return;let c=p.trim(),d=(a=c.split("/"))[a.length-1];if(b[d])return void alert(i("aliasExistsAlert",{alias:d}));s(!0);try{await g(c,d),q("")}catch(a){console.log("Error adding model:",a)}finally{s(!1)}};return(0,d.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,d.jsx)("p",{className:"text-sm text-text-muted",children:i("openRouterAnyModelHint")}),(0,d.jsxs)("div",{className:"flex items-end gap-2",children:[(0,d.jsxs)("div",{className:"flex-1",children:[(0,d.jsx)("label",{htmlFor:"new-model-input",className:"text-xs text-text-muted mb-1 block",children:i("modelIdFromOpenRouter")}),(0,d.jsx)("input",{id:"new-model-input",type:"text",value:p,onChange:a=>q(a.target.value),onKeyDown:a=>"Enter"===a.key&&u(),placeholder:i("openRouterModelPlaceholder"),className:"w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"})]}),(0,d.jsx)(o.Button,{size:"sm",icon:"add",onClick:u,disabled:!p.trim()||r,children:r?i("adding"):i("add")})]}),t.length>0&&(0,d.jsx)("div",{className:"flex flex-col gap-3",children:t.map(({modelId:a,fullModel:b,alias:e})=>(0,d.jsx)(R,{modelId:a,fullModel:b,copied:c,onCopy:f,onDeleteAlias:()=>h(e),t:i,showDeveloperToggle:!0,effectiveModelNormalize:j,effectiveModelPreserveDeveloper:k,getUpstreamHeadersRecord:b=>l(a,b),saveModelCompatFlags:m,compatDisabled:n===a},b))})]})}function R({modelId:a,fullModel:b,copied:c,onCopy:e,onDeleteAlias:f,t:g,showDeveloperToggle:h=!0,effectiveModelNormalize:i,effectiveModelPreserveDeveloper:j,getUpstreamHeadersRecord:k,saveModelCompatFlags:l,compatDisabled:m}){return(0,d.jsxs)("div",{className:"flex gap-0 rounded-lg border border-border p-3 hover:bg-sidebar/50",children:[(0,d.jsxs)("div",{className:"flex min-w-0 flex-1 items-start gap-3",children:[(0,d.jsx)("span",{className:"material-symbols-outlined shrink-0 text-base text-text-muted",children:"smart_toy"}),(0,d.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,d.jsx)("p",{className:"truncate text-sm font-medium",children:a}),(0,d.jsxs)("div",{className:"mt-1 flex flex-wrap items-center gap-1",children:[(0,d.jsx)("code",{className:"rounded bg-sidebar px-1.5 py-0.5 font-mono text-xs text-text-muted",children:b}),(0,d.jsx)("button",{onClick:()=>e(b,`model-${a}`),className:"rounded p-0.5 text-text-muted hover:bg-sidebar hover:text-primary",title:g("copyModel"),children:(0,d.jsx)("span",{className:"material-symbols-outlined text-sm",children:c===`model-${a}`?"check":"content_copy"})})]})]})]}),(0,d.jsxs)("div",{className:"flex shrink-0 items-center gap-1 self-start",children:[(0,d.jsx)(O,{t:g,effectiveModelNormalize:b=>i(a,b),effectiveModelPreserveDeveloper:b=>j(a,b),getUpstreamHeadersRecord:k,onCompatPatch:(b,c)=>l(a,{compatByProtocol:{[b]:c}}),showDeveloperToggle:h,disabled:m}),(0,d.jsx)("button",{onClick:f,className:"rounded p-1 text-red-500 hover:bg-red-50",title:g("removeModel"),children:(0,d.jsx)("span",{className:"material-symbols-outlined text-sm",children:"delete"})})]})]})}function S({providerId:a,providerAlias:b,copied:c,onCopy:f,onModelsChanged:h}){let i=(0,l.useTranslations)("providers"),j=(0,g.useNotificationStore)(),[k,m]=(0,e.useState)([]),[n,p]=(0,e.useState)([]),[q,r]=(0,e.useState)(""),[s,t]=(0,e.useState)(""),[u,v]=(0,e.useState)("chat-completions"),[w,x]=(0,e.useState)(["chat"]),[y,z]=(0,e.useState)(!1),[A,B]=(0,e.useState)(!0),[C,D]=(0,e.useState)(null),[F,G]=(0,e.useState)("chat-completions"),[N,P]=(0,e.useState)(["chat"]),[Q,R]=(0,e.useState)(null),T=(0,e.useMemo)(()=>H(k),[k]),U=(0,e.useMemo)(()=>H(n),[n]),V=(0,e.useCallback)(async()=>{try{let b=await fetch(`/api/provider-models?provider=${encodeURIComponent(a)}`);if(b.ok){let a=await b.json();m(a.models||[]),p(a.modelCompatOverrides||[])}}catch(a){console.error("Failed to fetch custom models:",a)}finally{B(!1)}},[a]);(0,e.useEffect)(()=>{V()},[V]);let W=async()=>{if(q.trim()&&!y){z(!0);try{(await fetch("/api/provider-models",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:a,modelId:q.trim(),modelName:s.trim()||void 0,apiFormat:u,supportedEndpoints:w})})).ok&&(r(""),t(""),v("chat-completions"),x(["chat"]),await V(),h?.())}catch(a){console.error("Failed to add custom model:",a)}finally{z(!1)}}},X=async b=>{try{await fetch(`/api/provider-models?provider=${encodeURIComponent(a)}&model=${encodeURIComponent(b)}`,{method:"DELETE"}),await V(),h?.()}catch(a){console.error("Failed to remove custom model:",a)}},Y=()=>{D(null),G("chat-completions"),P(["chat"]),R(null)},Z=async(b,c)=>{R(b);try{let d=await fetch("/api/provider-models",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:a,modelId:b,...c})});if(!d.ok){let a=await L(d);j.error(a?`${i("failedSaveCustomModel")} — ${a}`:i("failedSaveCustomModel"));return}}catch{j.error(i("failedSaveCustomModel"));return}finally{R(null)}try{await V(),h?.()}catch{}},$=async b=>{if(C&&C===b){if(!N.length)return void j.error("Select at least one supported endpoint");R(b);try{let c=k.find(a=>a.id===b),d=await fetch("/api/provider-models",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:a,modelId:b,modelName:c?.name||b,source:c?.source||"manual",apiFormat:F,supportedEndpoints:N})});if(!d.ok){let a=await L(d);throw Error(a||"Failed to save model endpoint settings")}await V(),h?.(),j.success("Saved model endpoint settings"),Y()}catch(a){console.error("Failed to save custom model:",a),j.error(a instanceof Error&&a.message?a.message:"Failed to save model endpoint settings")}finally{R(null)}}};return(0,d.jsxs)("div",{className:"mt-6 pt-6 border-t border-border",children:[(0,d.jsxs)("h3",{className:"text-sm font-semibold mb-3 flex items-center gap-2",children:[(0,d.jsx)("span",{className:"material-symbols-outlined text-base text-primary",children:"tune"}),i("customModels")]}),(0,d.jsx)("p",{className:"text-xs text-text-muted mb-3",children:i("customModelsHint")}),(0,d.jsxs)("div",{className:"flex flex-col gap-3 mb-3",children:[(0,d.jsxs)("div",{className:"flex items-end gap-2",children:[(0,d.jsxs)("div",{className:"flex-1",children:[(0,d.jsx)("label",{htmlFor:"custom-model-id",className:"text-xs text-text-muted mb-1 block",children:i("modelId")}),(0,d.jsx)("input",{id:"custom-model-id",type:"text",value:q,onChange:a=>r(a.target.value),onKeyDown:a=>"Enter"===a.key&&W(),placeholder:i("customModelPlaceholder"),className:"w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"})]}),(0,d.jsxs)("div",{className:"w-40",children:[(0,d.jsx)("label",{htmlFor:"custom-model-name",className:"text-xs text-text-muted mb-1 block",children:i("displayName")}),(0,d.jsx)("input",{id:"custom-model-name",type:"text",value:s,onChange:a=>t(a.target.value),onKeyDown:a=>"Enter"===a.key&&W(),placeholder:i("optional"),className:"w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"})]}),(0,d.jsx)(o.Button,{size:"sm",icon:"add",onClick:W,disabled:!q.trim()||y,children:y?i("adding"):i("add")})]}),(0,d.jsxs)("div",{className:"flex items-end gap-4 flex-wrap",children:[(0,d.jsxs)("div",{className:"w-48",children:[(0,d.jsx)("label",{htmlFor:"custom-api-format",className:"text-xs text-text-muted mb-1 block",children:"API Format"}),(0,d.jsxs)("select",{id:"custom-api-format",value:u,onChange:a=>v(a.target.value),className:"w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary",children:[(0,d.jsx)("option",{value:"chat-completions",children:"Chat Completions"}),(0,d.jsx)("option",{value:"responses",children:"Responses API"})]})]}),(0,d.jsxs)("div",{className:"flex-1",children:[(0,d.jsx)("span",{className:"text-xs text-text-muted mb-1 block",children:"Supported Endpoints"}),(0,d.jsx)("div",{className:"flex items-center gap-3",children:["chat","embeddings","images","audio"].map(a=>(0,d.jsxs)("label",{className:"flex items-center gap-1.5 text-xs text-text-main cursor-pointer",children:[(0,d.jsx)("input",{type:"checkbox",checked:w.includes(a),onChange:b=>{b.target.checked?x(b=>[...b,a]):x(b=>b.filter(b=>b!==a))},className:"rounded border-border"}),"chat"===a?"💬 Chat":"embeddings"===a?"📐 Embeddings":"images"===a?"🖼️ Images":"🔊 Audio"]},a))})]})]})]}),A?(0,d.jsx)("p",{className:"text-xs text-text-muted",children:i("loading")}):k.length>0?(0,d.jsx)("div",{className:"flex flex-col gap-2",children:k.map(a=>{let e=`${b}/${a.id}`,g=`custom-${a.id}`;return(0,d.jsxs)("div",{className:"flex items-center gap-3 rounded-lg border border-border p-3 hover:bg-sidebar/50",children:[C!==a.id&&(0,d.jsx)("span",{className:"material-symbols-outlined text-base text-primary shrink-0",children:"tune"}),(0,d.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,d.jsx)("p",{className:"text-sm font-medium truncate",children:a.name||a.id}),(0,d.jsxs)("div",{className:"flex items-center gap-1 mt-1 flex-wrap",children:[(0,d.jsx)("code",{className:"text-xs text-text-muted font-mono bg-sidebar px-1.5 py-0.5 rounded",children:e}),(0,d.jsx)("button",{onClick:()=>f(e,g),className:"p-0.5 hover:bg-sidebar rounded text-text-muted hover:text-primary",title:i("copyModel"),children:(0,d.jsx)("span",{className:"material-symbols-outlined text-sm",children:c===g?"check":"content_copy"})}),"responses"===a.apiFormat&&(0,d.jsx)("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-blue-500/15 text-blue-400 font-medium",children:"Responses"}),a.supportedEndpoints?.includes("embeddings")&&(0,d.jsx)("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-purple-500/15 text-purple-400 font-medium",children:"📐 Embed"}),a.supportedEndpoints?.includes("images")&&(0,d.jsx)("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-amber-500/15 text-amber-400 font-medium",children:"🖼️ Images"}),a.supportedEndpoints?.includes("audio")&&(0,d.jsx)("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-green-500/15 text-green-400 font-medium",children:"🔊 Audio"}),function(a,b,c){let d=b.get(a),e=c.get(a);if(d?.normalizeToolCallId||e?.normalizeToolCallId)return!0;for(let a of E.MODEL_COMPAT_PROTOCOL_KEYS){let b=I(d,e,a);if(b?.normalizeToolCallId)return!0}return!1}(a.id,T,U)&&(0,d.jsx)("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-slate-500/15 text-slate-400 font-medium",title:i("normalizeToolCallIdLabel"),children:"ID×9"}),function(a,b,c){let d=b.get(a),e=c.get(a);if(d&&Object.prototype.hasOwnProperty.call(d,"preserveOpenAIDeveloperRole")&&!1===d.preserveOpenAIDeveloperRole||e&&Object.prototype.hasOwnProperty.call(e,"preserveOpenAIDeveloperRole")&&!1===e.preserveOpenAIDeveloperRole)return!0;for(let a of E.MODEL_COMPAT_PROTOCOL_KEYS){let b=I(d,e,a);if(b&&Object.prototype.hasOwnProperty.call(b,"preserveOpenAIDeveloperRole")&&!1===b.preserveOpenAIDeveloperRole)return!0}return!1}(a.id,T,U)&&(0,d.jsx)("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-cyan-500/15 text-cyan-400 font-medium",title:i("compatDoNotPreserveDeveloper"),children:i("compatBadgeNoPreserve")}),function(a,b,c){let d=b.get(a),e=c.get(a),f=a=>a&&"object"==typeof a&&!Array.isArray(a)&&Object.keys(a).length>0;if(f(d?.upstreamHeaders)||f(e?.upstreamHeaders))return!0;for(let a of E.MODEL_COMPAT_PROTOCOL_KEYS){let b=I(d,e,a);if(f(b?.upstreamHeaders))return!0}return!1}(a.id,T,U)&&(0,d.jsx)("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-violet-500/15 text-violet-400 font-medium",title:i("compatUpstreamHeadersLabel"),children:i("compatBadgeUpstreamHeaders")})]}),C===a.id&&(0,d.jsx)("div",{className:"mt-3 min-w-0 max-w-full rounded-lg border border-border bg-muted p-3 dark:bg-zinc-900",children:(0,d.jsxs)("div",{className:"flex min-w-0 flex-wrap items-end gap-x-3 gap-y-2",children:[(0,d.jsxs)("div",{className:"w-[11rem] shrink-0 min-w-0",children:[(0,d.jsx)("label",{className:"text-xs text-text-muted mb-1 block",children:"API Format"}),(0,d.jsxs)("select",{value:F,onChange:a=>G(a.target.value),className:"w-full px-2.5 py-2 text-xs border border-border rounded-lg bg-background text-text-main focus:outline-none focus:border-primary",children:[(0,d.jsx)("option",{value:"chat-completions",children:"Chat Completions"}),(0,d.jsx)("option",{value:"responses",children:"Responses API"})]})]}),(0,d.jsxs)("div",{className:"flex min-w-0 flex-1 flex-wrap items-center gap-x-3 gap-y-1 overflow-x-auto overflow-y-visible [scrollbar-width:thin]",children:[(0,d.jsx)("span",{className:"text-xs text-text-muted shrink-0",children:"Supported Endpoints"}),(0,d.jsx)("div",{className:"flex flex-wrap items-center gap-x-2 sm:gap-x-3 gap-y-1 min-w-0",children:["chat","embeddings","images","audio"].map(a=>(0,d.jsxs)("label",{className:"flex items-center gap-1.5 text-xs text-text-main cursor-pointer whitespace-nowrap",children:[(0,d.jsx)("input",{type:"checkbox",checked:N.includes(a),onChange:b=>{b.target.checked?P(b=>b.includes(a)?b:[...b,a]):P(b=>b.filter(b=>b!==a))},className:"rounded border-border"}),"chat"===a?"💬 Chat":"embeddings"===a?"📐 Embeddings":"images"===a?"🖼️ Images":"🔊 Audio"]},a))})]}),(0,d.jsxs)("div",{className:"flex shrink-0 flex-wrap items-center gap-2 pb-0.5",children:[(0,d.jsx)(o.Button,{size:"sm",onClick:()=>$(a.id),disabled:Q===a.id,children:Q===a.id?i("saving"):i("save")}),(0,d.jsx)(o.Button,{size:"sm",variant:"ghost",onClick:Y,children:i("cancel")})]})]})})]}),(0,d.jsxs)("div",{className:"flex shrink-0 items-center gap-1",children:[(0,d.jsx)("button",{onClick:()=>{D(a.id),G(a.apiFormat||"chat-completions"),P(Array.isArray(a.supportedEndpoints)&&a.supportedEndpoints.length?a.supportedEndpoints:["chat"])},className:"rounded p-1 text-text-muted hover:bg-sidebar hover:text-primary",title:i("edit"),children:(0,d.jsx)("span",{className:"material-symbols-outlined text-sm",children:"edit"})}),(0,d.jsx)(O,{t:i,effectiveModelNormalize:b=>J(a.id,b,T,U),effectiveModelPreserveDeveloper:b=>K(a.id,b,T,U),getUpstreamHeadersRecord:b=>M(a.id,b,T,U),onCompatPatch:(b,c)=>Z(a.id,{compatByProtocol:{[b]:c}}),showDeveloperToggle:!0,disabled:Q===a.id}),(0,d.jsx)("button",{onClick:()=>X(a.id),className:"rounded p-1 text-red-500 hover:bg-red-50",title:i("removeCustomModel"),children:(0,d.jsx)("span",{className:"material-symbols-outlined text-sm",children:"delete"})})]})]},a.id)})}):(0,d.jsx)("p",{className:"text-xs text-text-muted",children:i("noCustomModels")})]})}function T({providerStorageAlias:a,providerDisplayAlias:b,modelAliases:c,fallbackModels:f=[],description:h,inputLabel:i,inputPlaceholder:j,copied:k,onCopy:l,onSetAlias:m,onDeleteAlias:n,connections:p,isAnthropic:q,onImportWithProgress:r,t:s,effectiveModelNormalize:t,effectiveModelPreserveDeveloper:u,getUpstreamHeadersRecord:v,saveModelCompatFlags:w,compatSavingModelId:x,onModelsChanged:y,allowImport:z}){let[A,B]=(0,e.useState)(""),[C,D]=(0,e.useState)(!1),[E,G]=(0,e.useState)(!1),H=(0,g.useNotificationStore)(),I=(0,e.useMemo)(()=>Object.entries(c).filter(([,b])=>b.startsWith(`${a}/`)),[c,a]),J=(0,e.useMemo)(()=>{let b=I.map(([b,c])=>({modelId:c.replace(`${a}/`,""),alias:b})),c=new Set(b.map(a=>a.modelId));for(let a of f)!a?.id||c.has(a.id)||(b.push({modelId:a.id,alias:null}),c.add(a.id));return b},[f,I,a]),K=(0,e.useCallback)((c,d)=>(0,F.resolveManagedModelAlias)({modelId:c,fullModel:`${a}/${c}`,providerDisplayAlias:b,existingAliases:d}),[b,a]),L=async()=>{if(!A.trim()||C)return;let b=A.trim(),d=K(b,c);if(!d)return void H.error(s("allSuggestedAliasesExist"));D(!0);try{let c=await fetch("/api/provider-models",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:a,modelId:b,modelName:b,source:"manual"})});if(!c.ok){let a={};try{a=await c.json()}catch(a){console.error("Failed to parse error response from custom model API:",a)}throw Error(a.error?.message||s("failedSaveCustomModel"))}await m(b,d,a),B(""),H.success(s("modelAddedSuccess",{modelId:b})),y?.()}catch(a){console.error("Error adding model:",a),H.error(a instanceof Error?a.message:s("failedAddModelTryAgain"))}finally{D(!1)}},M=async()=>{if(!z||E)return;let b=p.find(a=>!1!==a.isActive);if(b){G(!0);try{let d={...c};await r(async()=>{let a=await fetch(`/api/providers/${b.id}/models`),c=await a.json();if(!a.ok)throw Error(c.error||s("failedImportModels"));return c},async b=>{let c=b.id||b.name||b.model;if(!c)return!1;let e=K(c,d);return!!e&&((await fetch("/api/provider-models",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:a,modelId:c,modelName:b.name||c,source:"imported"})})).ok?(await m(c,e,a),d[e]=`${a}/${c}`,!0):(H.error(s("failedSaveImportedModel")),!1))})}catch(a){console.error("Error importing models:",a),H.error(s("failedImportModelsTryAgain"))}finally{G(!1)}}},N=p.some(a=>!1!==a.isActive),O=async(b,c)=>{try{if(!(await fetch(`/api/provider-models?provider=${encodeURIComponent(a)}&model=${encodeURIComponent(b)}`,{method:"DELETE"})).ok)throw Error(s("failedRemoveModelFromDatabase"));c&&await n(c),H.success(s("modelRemovedSuccess")),y?.()}catch(a){console.error("Error deleting model:",a),H.error(a instanceof Error?a.message:s("failedDeleteModelTryAgain"))}};return(0,d.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,d.jsx)("p",{className:"text-sm text-text-muted",children:h}),(0,d.jsxs)("div",{className:"flex items-end gap-2 flex-wrap",children:[(0,d.jsxs)("div",{className:"flex-1 min-w-[240px]",children:[(0,d.jsx)("label",{htmlFor:"new-compatible-model-input",className:"text-xs text-text-muted mb-1 block",children:i}),(0,d.jsx)("input",{id:"new-compatible-model-input",type:"text",value:A,onChange:a=>B(a.target.value),onKeyDown:a=>"Enter"===a.key&&L(),placeholder:j,className:"w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"})]}),(0,d.jsx)(o.Button,{size:"sm",icon:"add",onClick:L,disabled:!A.trim()||C,children:C?s("adding"):s("add")}),z&&(0,d.jsx)(o.Button,{size:"sm",variant:"secondary",icon:"download",onClick:M,disabled:!N||E,children:E?s("importingModels"):s("importFromModels")})]}),z&&!N&&(0,d.jsx)("p",{className:"text-xs text-text-muted",children:s("addConnectionToImport")}),J.length>0&&(0,d.jsx)("div",{className:"flex flex-col gap-3",children:J.map(({modelId:c,alias:e})=>(0,d.jsx)(R,{modelId:c,fullModel:`${b}/${c}`,copied:k,onCopy:l,onDeleteAlias:()=>O(c,e),t:s,showDeveloperToggle:!q,effectiveModelNormalize:t,effectiveModelPreserveDeveloper:u,getUpstreamHeadersRecord:a=>v(c,a),saveModelCompatFlags:w,compatDisabled:x===c},`${a}:${c}`))})]})}function U({until:a}){let[b,c]=(0,e.useState)("");return((0,e.useEffect)(()=>{let b=()=>{let b=new Date(a).getTime()-Date.now();if(b<=0)return void c("");let d=Math.floor(b/1e3);if(d<60)c(`${d}s`);else if(d<3600)c(`${Math.floor(d/60)}m ${d%60}s`);else{let a=Math.floor(d/3600),b=Math.floor(d%3600/60);c(`${a}h ${b}m`)}};b();let d=setInterval(b,1e3);return()=>clearInterval(d)},[a]),b)?(0,d.jsxs)("span",{className:"text-xs text-orange-500 font-mono",children:["⏱ ",b]}):null}P.propTypes={model:h.default.shape({id:h.default.string.isRequired}).isRequired,fullModel:h.default.string.isRequired,copied:h.default.string,onCopy:h.default.func.isRequired,t:h.default.func,showDeveloperToggle:h.default.bool,effectiveModelNormalize:h.default.func.isRequired,effectiveModelPreserveDeveloper:h.default.func.isRequired,getUpstreamHeadersRecord:h.default.func.isRequired,saveModelCompatFlags:h.default.func.isRequired,compatDisabled:h.default.bool},Q.propTypes={providerAlias:h.default.string.isRequired,modelAliases:h.default.object.isRequired,copied:h.default.string,onCopy:h.default.func.isRequired,onSetAlias:h.default.func.isRequired,onDeleteAlias:h.default.func.isRequired,t:h.default.func.isRequired,effectiveModelNormalize:h.default.func.isRequired,effectiveModelPreserveDeveloper:h.default.func.isRequired,getUpstreamHeadersRecord:h.default.func.isRequired,saveModelCompatFlags:h.default.func.isRequired,compatSavingModelId:h.default.string},R.propTypes={modelId:h.default.string.isRequired,fullModel:h.default.string.isRequired,copied:h.default.string,onCopy:h.default.func.isRequired,onDeleteAlias:h.default.func.isRequired,t:h.default.func,showDeveloperToggle:h.default.bool,effectiveModelNormalize:h.default.func.isRequired,effectiveModelPreserveDeveloper:h.default.func.isRequired,getUpstreamHeadersRecord:h.default.func.isRequired,saveModelCompatFlags:h.default.func.isRequired,compatDisabled:h.default.bool},S.propTypes={providerId:h.default.string.isRequired,providerAlias:h.default.string.isRequired,copied:h.default.string,onCopy:h.default.func.isRequired,onModelsChanged:h.default.func},T.propTypes={providerStorageAlias:h.default.string.isRequired,providerDisplayAlias:h.default.string.isRequired,modelAliases:h.default.object.isRequired,fallbackModels:h.default.array,description:h.default.string.isRequired,inputLabel:h.default.string.isRequired,inputPlaceholder:h.default.string.isRequired,copied:h.default.string,onCopy:h.default.func.isRequired,onSetAlias:h.default.func.isRequired,onDeleteAlias:h.default.func.isRequired,connections:h.default.arrayOf(h.default.shape({id:h.default.string,isActive:h.default.bool})).isRequired,isAnthropic:h.default.bool,onImportWithProgress:h.default.func.isRequired,t:h.default.func.isRequired,effectiveModelNormalize:h.default.func.isRequired,effectiveModelPreserveDeveloper:h.default.func.isRequired,getUpstreamHeadersRecord:h.default.func.isRequired,saveModelCompatFlags:h.default.func.isRequired,compatSavingModelId:h.default.string,onModelsChanged:h.default.func,allowImport:h.default.bool.isRequired},U.propTypes={until:h.default.string.isRequired};let ab={runtime_error:{labelKey:"errorTypeRuntime",variant:"warning"},upstream_auth_error:{labelKey:"errorTypeUpstreamAuth",variant:"error"},account_deactivated:{labelKey:"Account Deactivated",variant:"error"},auth_missing:{labelKey:"errorTypeMissingCredential",variant:"warning"},token_refresh_failed:{labelKey:"errorTypeRefreshFailed",variant:"warning"},token_expired:{labelKey:"errorTypeTokenExpired",variant:"warning"},upstream_rate_limited:{labelKey:"errorTypeRateLimited",variant:"warning"},upstream_unavailable:{labelKey:"errorTypeUpstreamUnavailable",variant:"error"},network_error:{labelKey:"errorTypeNetworkError",variant:"warning"},unsupported:{labelKey:"errorTypeTestUnsupported",variant:"default"},upstream_error:{labelKey:"errorTypeUpstreamError",variant:"error"},banned:{labelKey:"403 Banned",variant:"error"},credits_exhausted:{labelKey:"No Credits",variant:"warning"}};function V({connection:a,isOAuth:b,isCodex:c,isFirst:f,isLast:g,onMoveUp:h,onMoveDown:i,onToggleActive:j,onToggleRateLimit:k,onToggleCodex5h:m,onToggleCodexWeekly:n,onRetest:q,isRetesting:r,onEdit:s,onDelete:t,onReauth:u,onProxy:v,hasProxy:x,proxySource:y,proxyHost:z,onRefreshToken:A,isRefreshing:B,onApplyCodexAuthLocal:C,isApplyingCodexAuthLocal:D,onExportCodexAuthFile:E,isExportingCodexAuthFile:F}){let G,H=(0,l.useTranslations)("providers"),I=b?a.name||a.email||a.displayName||H("oauthAccount"):a.name,J="function"==typeof H.has&&H.has("applyCodexAuthLocal")?H("applyCodexAuthLocal"):"Apply auth",K="function"==typeof H.has&&H.has("exportCodexAuthFile")?H("exportCodexAuthFile"):"Export auth",[L,M]=(0,e.useState)(!1),[O,P]=(0,e.useState)(()=>{if(!b||!a.expiresAt)return null;let c=new Date(a.expiresAt).getTime();return Math.floor((c-Date.now())/6e4)});(0,e.useEffect)(()=>{if(!b||!a.expiresAt)return;let c=setInterval(()=>{let b=new Date(a.expiresAt).getTime();P(Math.floor((b-Date.now())/6e4))},3e4);return()=>clearInterval(c)},[b,a.expiresAt]),(0,e.useEffect)(()=>{let b=()=>{let b=a.rateLimitedUntil&&new Date(a.rateLimitedUntil).getTime()>Date.now();M(b)};b();let c=a.rateLimitedUntil?setInterval(b,1e3):null;return()=>{c&&clearInterval(c)}},[a.rateLimitedUntil]);let Q="unavailable"!==a.testStatus||L?a.testStatus:"active",R=function(a,b,c,d){if(!1===a.isActive)return{statusVariant:"default",statusLabel:d("statusDisabled"),errorType:null,errorBadge:null,errorTextClass:"text-text-muted"};if("active"===b||"success"===b)return{statusVariant:"success",statusLabel:d("statusConnected"),errorType:null,errorBadge:null,errorTextClass:"text-text-muted"};let e=function(a,b){if(b)return"upstream_rate_limited";if("banned"===a.testStatus)return"banned";if("credits_exhausted"===a.testStatus)return"credits_exhausted";if(a.lastErrorType)return a.lastErrorType;let c=Number(a.errorCode);if(401===c||403===c)return"upstream_auth_error";if(429===c)return"upstream_rate_limited";if(c>=500)return"upstream_unavailable";let d=(a.lastError||"").toLowerCase();return d?d.includes("runtime")||d.includes("not runnable")||d.includes("not installed")||d.includes("healthcheck")?"runtime_error":d.includes("refresh failed")?"token_refresh_failed":d.includes("token expired")||d.includes("expired")?"token_expired":d.includes("invalid api key")||d.includes("token invalid")||d.includes("revoked")||d.includes("access denied")||d.includes("unauthorized")?"upstream_auth_error":d.includes("rate limit")||d.includes("quota")||d.includes("too many requests")||d.includes("429")?"upstream_rate_limited":d.includes("fetch failed")||d.includes("network")||d.includes("timeout")||d.includes("econn")||d.includes("enotfound")?"network_error":d.includes("not supported")?"unsupported":"upstream_error":null}(a,c),f=e&&ab[e]||null;if("runtime_error"===e)return{statusVariant:"warning",statusLabel:d("statusRuntimeIssue"),errorType:e,errorBadge:f,errorTextClass:"text-yellow-600 dark:text-yellow-400"};if("account_deactivated"===e)return{statusVariant:"error",statusLabel:d("statusDeactivated","Deactivated"),errorType:e,errorBadge:f,errorTextClass:"text-red-600 font-bold"};if("upstream_auth_error"===e||"auth_missing"===e||"token_refresh_failed"===e||"token_expired"===e)return{statusVariant:"error",statusLabel:d("statusAuthFailed"),errorType:e,errorBadge:f,errorTextClass:"text-red-500"};if("upstream_rate_limited"===e)return{statusVariant:"warning",statusLabel:d("statusRateLimited"),errorType:e,errorBadge:f,errorTextClass:"text-yellow-600 dark:text-yellow-400"};if("network_error"===e)return{statusVariant:"warning",statusLabel:d("statusNetworkIssue"),errorType:e,errorBadge:f,errorTextClass:"text-yellow-600 dark:text-yellow-400"};if("unsupported"===e)return{statusVariant:"default",statusLabel:d("statusTestUnsupported"),errorType:e,errorBadge:f,errorTextClass:"text-text-muted"};if("banned"===e)return{statusVariant:"error",statusLabel:d("statusBanned","Banned (403)"),errorType:e,errorBadge:f,errorTextClass:"text-red-600 font-bold"};if("credits_exhausted"===e)return{statusVariant:"warning",statusLabel:d("statusCreditsExhausted","Out of Credits"),errorType:e,errorBadge:f,errorTextClass:"text-amber-500"};let g={unavailable:d("statusUnavailable"),failed:d("statusFailed"),error:d("statusError")};return{statusVariant:"error",statusLabel:g[b]||b||d("statusError"),errorType:e,errorBadge:f,errorTextClass:"text-red-500"}}(a,Q,L,H),S=!!a.rateLimitProtection,T=a.providerSpecificData&&"object"==typeof a.providerSpecificData&&a.providerSpecificData.codexLimitPolicy&&"object"==typeof a.providerSpecificData.codexLimitPolicy?a.providerSpecificData.codexLimitPolicy:{},W=N(T),X=W.use5h,Y=W.useWeekly;return(0,d.jsxs)("div",{className:`group flex items-center justify-between p-3 rounded-lg hover:bg-black/[0.02] dark:hover:bg-white/[0.02] transition-colors ${!1===a.isActive?"opacity-60":""}`,children:[(0,d.jsxs)("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[(0,d.jsxs)("div",{className:"flex flex-col",children:[(0,d.jsx)("button",{onClick:h,disabled:f,className:`p-0.5 rounded ${f?"text-text-muted/30 cursor-not-allowed":"hover:bg-sidebar text-text-muted hover:text-primary"}`,children:(0,d.jsx)("span",{className:"material-symbols-outlined text-sm",children:"keyboard_arrow_up"})}),(0,d.jsx)("button",{onClick:i,disabled:g,className:`p-0.5 rounded ${g?"text-text-muted/30 cursor-not-allowed":"hover:bg-sidebar text-text-muted hover:text-primary"}`,children:(0,d.jsx)("span",{className:"material-symbols-outlined text-sm",children:"keyboard_arrow_down"})})]}),(0,d.jsx)("span",{className:"material-symbols-outlined text-base text-text-muted",children:b?"lock":"key"}),(0,d.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,d.jsx)("p",{className:"text-sm font-medium truncate",children:I}),(0,d.jsxs)("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[(0,d.jsx)(p.Badge,{variant:R.statusVariant,size:"sm",dot:!0,children:R.statusLabel}),null!==O&&(O<0?(0,d.jsxs)("span",{className:"inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded text-xs font-medium bg-red-500/15 text-red-500",title:`Token expired: ${a.expiresAt}`,children:[(0,d.jsx)("span",{className:"material-symbols-outlined text-[11px]",children:"error"}),"expired"]}):O<30?(0,d.jsxs)("span",{className:"inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded text-xs font-medium bg-amber-500/15 text-amber-500",title:`Token expires in ${O}m`,children:[(0,d.jsx)("span",{className:"material-symbols-outlined text-[11px]",children:"warning"}),`~${O}m`]}):null),L&&!1!==a.isActive&&(0,d.jsx)(U,{until:a.rateLimitedUntil}),R.errorBadge&&!1!==a.isActive&&(0,d.jsx)(p.Badge,{variant:R.errorBadge.variant,size:"sm",children:H(R.errorBadge.labelKey)}),a.lastError&&!1!==a.isActive&&(0,d.jsx)("span",{className:`text-xs truncate max-w-[300px] ${R.errorTextClass}`,title:a.lastError.replace(/<[^>]*>?/gm,""),children:a.lastError.replace(/<[^>]*>?/gm,"")}),(0,d.jsxs)("span",{className:"text-xs text-text-muted",children:["#",a.priority]}),a.globalPriority&&(0,d.jsx)("span",{className:"text-xs text-text-muted",children:H("autoPriority",{priority:a.globalPriority})}),(0,d.jsx)("span",{className:"text-text-muted/30 select-none",children:"|"}),(0,d.jsxs)("button",{onClick:()=>k(!S),className:`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs font-medium transition-all cursor-pointer ${S?"bg-emerald-500/15 text-emerald-500 hover:bg-emerald-500/25":"bg-black/[0.03] dark:bg-white/[0.03] text-text-muted/50 hover:text-text-muted hover:bg-black/[0.06] dark:hover:bg-white/[0.06]"}`,title:H(S?"disableRateLimitProtection":"enableRateLimitProtection"),children:[(0,d.jsx)("span",{className:"material-symbols-outlined text-[13px]",children:"shield"}),H(S?"rateLimitProtected":"rateLimitUnprotected")]}),c&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("span",{className:"text-text-muted/30 select-none",children:"|"}),(0,d.jsxs)("button",{onClick:()=>m?.(!X),className:`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs font-medium transition-all cursor-pointer ${X?"bg-blue-500/15 text-blue-500 hover:bg-blue-500/25":"bg-black/[0.03] dark:bg-white/[0.03] text-text-muted/50 hover:text-text-muted hover:bg-black/[0.06] dark:hover:bg-white/[0.06]"}`,title:"Toggle Codex 5h limit policy",children:[(0,d.jsx)("span",{className:"material-symbols-outlined text-[13px]",children:"timer"}),"5h ",X?"ON":"OFF"]}),(0,d.jsxs)("button",{onClick:()=>n?.(!Y),className:`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs font-medium transition-all cursor-pointer ${Y?"bg-violet-500/15 text-violet-500 hover:bg-violet-500/25":"bg-black/[0.03] dark:bg-white/[0.03] text-text-muted/50 hover:text-text-muted hover:bg-black/[0.06] dark:hover:bg-white/[0.06]"}`,title:"Toggle Codex weekly limit policy",children:[(0,d.jsx)("span",{className:"material-symbols-outlined text-[13px]",children:"date_range"}),"Weekly ",Y?"ON":"OFF"]})]}),x&&(G=H("global"===y?"proxySourceGlobal":"provider"===y?"proxySourceProvider":"proxySourceKey"),(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("span",{className:"text-text-muted/30 select-none",children:"|"}),(0,d.jsxs)("span",{className:`inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded text-xs font-medium ${"global"===y?"bg-emerald-500/15 text-emerald-500":"provider"===y?"bg-amber-500/15 text-amber-500":"bg-blue-500/15 text-blue-500"}`,title:H("proxyConfiguredBySource",{source:G,host:z||H("configured")}),children:[(0,d.jsx)("span",{className:"material-symbols-outlined text-[13px]",children:"vpn_lock"}),z||H("proxy")]})]}))]})]})]}),(0,d.jsxs)("div",{className:"flex items-center gap-2",children:[(0,d.jsx)(o.Button,{size:"sm",variant:"ghost",icon:"refresh",loading:r,disabled:!1===a.isActive,onClick:q,className:"!h-7 !px-2 text-xs",title:H("retestAuthentication"),children:H("retest")}),A&&(0,d.jsx)(o.Button,{size:"sm",variant:"ghost",icon:"token",loading:B,disabled:!1===a.isActive||B,onClick:A,className:"!h-7 !px-2 text-xs text-amber-500 hover:text-amber-400",title:"Refresh OAuth token manually",children:"Token"}),c&&C&&(0,d.jsx)(o.Button,{size:"sm",variant:"ghost",icon:"download_done",loading:D,disabled:D,onClick:C,className:"!h-7 !px-2 text-xs text-emerald-500 hover:text-emerald-400",title:J,children:J}),c&&E&&(0,d.jsx)(o.Button,{size:"sm",variant:"ghost",icon:"download",loading:F,disabled:F,onClick:E,className:"!h-7 !px-2 text-xs text-sky-500 hover:text-sky-400",title:K,children:K}),(0,d.jsx)(w.Toggle,{size:"sm",checked:a.isActive??!0,onChange:j,title:H(a.isActive??!0?"disableConnection":"enableConnection")}),(0,d.jsxs)("div",{className:"flex gap-1 ml-1 transition-opacity",children:[u&&(0,d.jsx)("button",{onClick:u,className:"p-2 hover:bg-amber-500/10 rounded text-amber-600 hover:text-amber-500",title:H("reauthenticateConnection"),children:(0,d.jsx)("span",{className:"material-symbols-outlined text-[18px]",children:"passkey"})}),(0,d.jsx)("button",{onClick:s,className:"p-2 hover:bg-black/5 dark:hover:bg-white/5 rounded text-text-muted hover:text-primary",title:H("edit"),children:(0,d.jsx)("span",{className:"material-symbols-outlined text-[18px]",children:"edit"})}),(0,d.jsx)("button",{onClick:v,className:"p-2 hover:bg-black/5 dark:hover:bg-white/5 rounded text-text-muted hover:text-primary",title:H("proxyConfig"),children:(0,d.jsx)("span",{className:"material-symbols-outlined text-[18px]",children:"vpn_lock"})}),(0,d.jsx)("button",{onClick:t,className:"p-2 hover:bg-red-500/10 rounded text-red-500",title:H("delete"),children:(0,d.jsx)("span",{className:"material-symbols-outlined text-[18px]",children:"delete"})})]})]})]})}function W({isOpen:a,provider:b,providerName:c,isCompatible:f,isAnthropic:g,isCcCompatible:h,onSave:i,onClose:j}){let k=(0,l.useTranslations)("providers"),m="bailian-coding-plan"===b,n="https://coding-intl.dashscope.aliyuncs.com/apps/anthropic/v1",s="vertex"===b,t="us-central1",u="glm"===b,v="qoder"===b,[w,x]=(0,e.useState)({name:"",apiKey:"",priority:1,baseUrl:m?n:"",region:s?t:"",apiRegion:"international",validationModelId:""}),[y,z]=(0,e.useState)(!1),[A,B]=(0,e.useState)(null),[C,D]=(0,e.useState)(!1),[E,F]=(0,e.useState)(null),G=async()=>{z(!0),F(null);try{let a=await fetch("/api/providers/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:b,apiKey:w.apiKey,validationModelId:w.validationModelId||void 0})}),c=await a.json();B(c.valid?"success":"failed")}catch{B("failed")}finally{z(!1)}},H=async()=>{if(b&&w.apiKey){D(!0),F(null);try{let a=null;if(m){let b=X(w.baseUrl,n);if(b.error)return void F(b.error);a=b.value}let c=!1;try{z(!0),B(null);let a=await fetch("/api/providers/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:b,apiKey:w.apiKey,validationModelId:w.validationModelId||void 0})});c=!!(await a.json()).valid,B(c?"success":"failed")}catch{B("failed")}finally{z(!1)}if(!c)return void F(k("apiKeyValidationFailed"));let d={name:w.name,apiKey:w.apiKey,priority:w.priority,testStatus:"active",providerSpecificData:void 0};m?d.providerSpecificData={baseUrl:a}:s?d.providerSpecificData={region:w.region}:u&&(d.providerSpecificData={apiRegion:w.apiRegion});let e=await i(d);e&&F("string"==typeof e?e:k("failedSaveConnection"))}finally{D(!1)}}};return b?(0,d.jsx)(r.Modal,{isOpen:a,title:k("addProviderApiKeyTitle",{provider:c||b}),onClose:j,children:(0,d.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,d.jsx)(q.Input,{label:k("nameLabel"),value:w.name,onChange:a=>x({...w,name:a.target.value}),placeholder:v?"Qoder PAT":k("productionKey")}),(0,d.jsxs)("div",{className:"flex gap-2",children:[(0,d.jsx)(q.Input,{label:v?"Personal Access Token":k("apiKeyLabel"),type:"password",value:w.apiKey,onChange:a=>x({...w,apiKey:a.target.value}),className:"flex-1",placeholder:s?"Cole o Service Account JSON aqui":v?"Paste your Qoder Personal Access Token":void 0,hint:v?"Supported path: PAT via qodercli. Browser OAuth remains experimental.":void 0}),(0,d.jsx)("div",{className:"pt-6",children:(0,d.jsx)(o.Button,{onClick:G,disabled:!w.apiKey||y||C,variant:"secondary",children:y?k("checking"):k("check")})})]}),A&&(0,d.jsx)(p.Badge,{variant:"success"===A?"success":"error",children:"success"===A?k("valid"):k("invalid")}),E&&(0,d.jsx)("div",{className:"text-sm text-red-500 bg-red-500/10 border border-red-500/20 rounded-lg px-3 py-2",children:E}),f&&(0,d.jsx)("p",{className:"text-xs text-text-muted",children:h?"Validation uses the strict Claude Code-compatible bridge request for this provider.":g?k("validationChecksAnthropicCompatible",{provider:c||k("anthropicCompatibleName")}):k("validationChecksOpenAiCompatible",{provider:c||k("openaiCompatibleName")})}),(0,d.jsx)(q.Input,{label:"Model ID (opcional)",placeholder:"ex: grok-3 ou meta-llama/Llama-3.1-8B-Instruct",value:w.validationModelId,onChange:a=>x({...w,validationModelId:a.target.value}),hint:"Usado como fallback se a listagem de models não estiver disponível"}),(0,d.jsx)(q.Input,{label:k("priorityLabel"),type:"number",value:w.priority,onChange:a=>x({...w,priority:Number.parseInt(a.target.value)||1})}),m&&(0,d.jsx)(q.Input,{label:"Base URL",value:w.baseUrl,onChange:a=>x({...w,baseUrl:a.target.value}),placeholder:n,hint:"Optional: Custom base URL for bailian-coding-plan provider"}),s&&(0,d.jsx)(q.Input,{label:"Região (Region)",value:w.region,onChange:a=>x({...w,region:a.target.value}),placeholder:t,hint:"ex: us-central1 ou europe-west4. Partner models usam a região global automaticamente."}),u&&(0,d.jsxs)("div",{children:[(0,d.jsx)("label",{className:"text-sm font-medium text-text-main mb-1 block",children:"API Region"}),(0,d.jsxs)("select",{value:w.apiRegion,onChange:a=>x({...w,apiRegion:a.target.value}),className:"w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary",children:[(0,d.jsx)("option",{value:"international",children:"International (api.z.ai)"}),(0,d.jsx)("option",{value:"china",children:"China Mainland (open.bigmodel.cn)"})]}),(0,d.jsx)("p",{className:"text-xs text-text-muted mt-1",children:"Select the endpoint region for API access and quota tracking."})]}),(0,d.jsxs)("div",{className:"flex gap-2",children:[(0,d.jsx)(o.Button,{onClick:H,fullWidth:!0,disabled:!w.name||!w.apiKey||C,children:C?k("saving"):k("save")}),(0,d.jsx)(o.Button,{onClick:j,variant:"ghost",fullWidth:!0,children:k("cancel")})]})]})}):null}function X(a,b){let c=("string"==typeof a?a.trim():"")||b;try{let a=new URL(c);if("http:"!==a.protocol&&"https:"!==a.protocol)return{value:null,error:"Base URL must use http or https"};return{value:c,error:null}}catch{return{value:null,error:"Base URL must be a valid URL"}}}function Y({isOpen:a,connection:b,onSave:c,onClose:f}){let g=(0,l.useTranslations)("providers"),[h,i]=(0,e.useState)({name:"",priority:1,apiKey:"",healthCheckInterval:60,baseUrl:"",region:"",apiRegion:"international",validationModelId:"",tag:""}),[j,k]=(0,e.useState)(!1),[m,n]=(0,e.useState)(null),[s,t]=(0,e.useState)(!1),[u,v]=(0,e.useState)(null),[w,x]=(0,e.useState)(!1),[y,A]=(0,e.useState)(null),[B,C]=(0,e.useState)([]),[D,E]=(0,e.useState)(""),F=b?.provider==="bailian-coding-plan",G="https://coding-intl.dashscope.aliyuncs.com/apps/anthropic/v1",H=b?.provider==="vertex",I=b?.provider==="glm",J="us-central1";(0,e.useEffect)(()=>{if(b){let a=b.providerSpecificData?.baseUrl,c=b.providerSpecificData?.region;i({name:b.name||"",priority:b.priority||1,apiKey:"",healthCheckInterval:b.healthCheckInterval??60,baseUrl:("string"==typeof a?a:"")||(F?G:""),region:("string"==typeof c?c:"")||(H?J:""),apiRegion:b.providerSpecificData?.apiRegion||"international",validationModelId:b.providerSpecificData?.validationModelId||"",tag:b.providerSpecificData?.tag||""});let d=b.providerSpecificData?.extraApiKeys;C(Array.isArray(d)?d:[]),E(""),n(null),v(null),A(null)}},[b,F,H]);let K=async()=>{if(b?.provider){k(!0),n(null);try{let a=await fetch(`/api/providers/${b.id}/test`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({validationModelId:h.validationModelId||void 0})}),c=await a.json();n({valid:!!c.valid,diagnosis:c.diagnosis||null,message:c.error||null})}catch{n({valid:!1,diagnosis:{type:"network_error"},message:g("failedTestConnection")})}finally{k(!1)}}},L=async()=>{if(b?.provider&&h.apiKey){t(!0),v(null);try{let a=await fetch("/api/providers/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:b.provider,apiKey:h.apiKey,validationModelId:h.validationModelId||void 0})}),c=await a.json();v(c.valid?"success":"failed")}catch{v("failed")}finally{t(!1)}}},M=async()=>{x(!0),A(null);try{let a={name:h.name,priority:h.priority,healthCheckInterval:h.healthCheckInterval},d=null;if(F){let a=X(h.baseUrl,G);if(a.error)return void A(a.error);d=a.value}if(!N&&h.apiKey){a.apiKey=h.apiKey;let c="success"===u;if(!c)try{t(!0),v(null);let a=await fetch("/api/providers/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:b.provider,apiKey:h.apiKey,validationModelId:h.validationModelId||void 0})});c=!!(await a.json()).valid,v(c?"success":"failed")}catch{v("failed")}finally{t(!1)}c&&(a.testStatus="active",a.lastError=null,a.lastErrorAt=null,a.lastErrorType=null,a.lastErrorSource=null,a.errorCode=null,a.rateLimitedUntil=null)}N?a.providerSpecificData={...b.providerSpecificData||{},tag:h.tag.trim()||void 0}:(a.providerSpecificData={...b.providerSpecificData||{},extraApiKeys:B.filter(a=>a.trim().length>0),tag:h.tag.trim()||void 0},h.validationModelId&&(a.providerSpecificData.validationModelId=h.validationModelId),F?a.providerSpecificData.baseUrl=d:H?a.providerSpecificData.region=h.region:I&&(a.providerSpecificData.apiRegion=h.apiRegion));let e=await c(a);e&&A("string"==typeof e?e:g("failedSaveConnection"))}finally{x(!1)}};if(!b)return null;let N="oauth"===b.authType,O=(0,z.isOpenAICompatibleProvider)(b.provider)||(0,z.isAnthropicCompatibleProvider)(b.provider),P=!m?.valid&&m?.diagnosis?.type&&ab[m.diagnosis.type]||null;return(0,d.jsx)(r.Modal,{isOpen:a,title:g("editConnection"),onClose:f,children:(0,d.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,d.jsx)(q.Input,{label:g("nameLabel"),value:h.name,onChange:a=>i({...h,name:a.target.value}),placeholder:N?g("accountName"):g("productionKey")}),(0,d.jsx)(q.Input,{label:"Tag / Group",value:h.tag,onChange:a=>i({...h,tag:a.target.value}),placeholder:"e.g. personal, work, team-a",hint:"Used to group accounts in the provider view"}),N&&b.email&&(0,d.jsxs)("div",{className:"bg-sidebar/50 p-3 rounded-lg",children:[(0,d.jsx)("p",{className:"text-sm text-text-muted mb-1",children:g("email")}),(0,d.jsx)("p",{className:"font-medium",children:b.email})]}),N&&(0,d.jsx)(q.Input,{label:g("healthCheckMinutes"),type:"number",value:h.healthCheckInterval,onChange:a=>i({...h,healthCheckInterval:Math.max(0,Number.parseInt(a.target.value)||0)}),hint:g("healthCheckHint")}),(0,d.jsx)(q.Input,{label:g("priorityLabel"),type:"number",value:h.priority,onChange:a=>i({...h,priority:Number.parseInt(a.target.value)||1})}),!N&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("div",{className:"flex gap-2",children:[(0,d.jsx)(q.Input,{label:g("apiKeyLabel"),type:"password",value:h.apiKey,onChange:a=>i({...h,apiKey:a.target.value}),placeholder:H?"Cole o Service Account JSON aqui":g("enterNewApiKey"),hint:g("leaveBlankKeepCurrentApiKey"),className:"flex-1"}),(0,d.jsx)("div",{className:"pt-6",children:(0,d.jsx)(o.Button,{onClick:L,disabled:!h.apiKey||s||w,variant:"secondary",children:s?g("checking"):g("check")})})]}),u&&(0,d.jsx)(p.Badge,{variant:"success"===u?"success":"error",children:"success"===u?g("valid"):g("invalid")}),y&&(0,d.jsx)("div",{className:"text-sm text-red-500 bg-red-500/10 border border-red-500/20 rounded-lg px-3 py-2",children:y}),(0,d.jsx)(q.Input,{label:"Model ID (opcional)",placeholder:"ex: grok-3 ou meta-llama/Llama-3.1-8B-Instruct",value:h.validationModelId,onChange:a=>i({...h,validationModelId:a.target.value}),hint:"Usado como fallback se a listagem de models não estiver disponível"})]}),F&&(0,d.jsx)(q.Input,{label:"Base URL",value:h.baseUrl,onChange:a=>i({...h,baseUrl:a.target.value}),placeholder:G,hint:"Custom base URL for bailian-coding-plan provider"}),H&&(0,d.jsx)(q.Input,{label:"Região (Region)",value:h.region,onChange:a=>i({...h,region:a.target.value}),placeholder:J,hint:"ex: us-central1 ou europe-west4. Partner models usam a região global automaticamente."}),I&&(0,d.jsxs)("div",{children:[(0,d.jsx)("label",{className:"text-sm font-medium text-text-main mb-1 block",children:"API Region"}),(0,d.jsxs)("select",{value:h.apiRegion,onChange:a=>i({...h,apiRegion:a.target.value}),className:"w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary",children:[(0,d.jsx)("option",{value:"international",children:"International (api.z.ai)"}),(0,d.jsx)("option",{value:"china",children:"China Mainland (open.bigmodel.cn)"})]}),(0,d.jsx)("p",{className:"text-xs text-text-muted mt-1",children:"Select the endpoint region for API access and quota tracking."})]}),!N&&(0,d.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,d.jsxs)("label",{className:"text-sm font-medium text-text-main",children:["Extra API Keys",(0,d.jsx)("span",{className:"ml-2 text-[11px] font-normal text-text-muted",children:"(round-robin rotation — optional)"})]}),B.length>0&&(0,d.jsx)("div",{className:"flex flex-col gap-1.5",children:B.map((a,b)=>(0,d.jsxs)("div",{className:"flex items-center gap-2",children:[(0,d.jsx)("span",{className:"flex-1 font-mono text-xs bg-sidebar/50 px-3 py-2 rounded border border-border text-text-muted truncate",children:`Key #${b+2}: ${a.slice(0,6)}...${a.slice(-4)}`}),(0,d.jsx)("button",{onClick:()=>C(B.filter((a,c)=>c!==b)),className:"p-1.5 rounded hover:bg-red-500/10 text-red-400 hover:text-red-500",title:"Remove this key",children:(0,d.jsx)("span",{className:"material-symbols-outlined text-[16px]",children:"close"})})]},b))}),(0,d.jsxs)("div",{className:"flex gap-2",children:[(0,d.jsx)("input",{type:"password",value:D,onChange:a=>E(a.target.value),placeholder:"Add another API key...",className:"flex-1 text-sm bg-sidebar/50 border border-border rounded px-3 py-2 text-text-main placeholder:text-text-muted focus:ring-1 focus:ring-primary outline-none",onKeyDown:a=>{"Enter"===a.key&&D.trim()&&(C([...B,D.trim()]),E(""))}}),(0,d.jsx)("button",{onClick:()=>{D.trim()&&(C([...B,D.trim()]),E(""))},disabled:!D.trim(),className:"px-3 py-2 rounded bg-primary/10 text-primary hover:bg-primary/20 disabled:opacity-40 text-sm font-medium",children:"Add"})]}),B.length>0&&(0,d.jsxs)("p",{className:"text-[11px] text-text-muted",children:[B.length+1," keys total — rotating round-robin on each request."]})]}),!O&&(0,d.jsxs)("div",{className:"flex items-center gap-3",children:[(0,d.jsx)(o.Button,{onClick:K,variant:"secondary",disabled:j,children:j?g("testing"):g("testConnection")}),m&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(p.Badge,{variant:m.valid?"success":"error",children:m.valid?g("valid"):g("failed")}),P&&(0,d.jsx)(p.Badge,{variant:P.variant,children:g(P.labelKey)})]})]}),(0,d.jsxs)("div",{className:"flex gap-2",children:[(0,d.jsx)(o.Button,{onClick:M,fullWidth:!0,disabled:w,children:w?g("saving"):g("save")}),(0,d.jsx)(o.Button,{onClick:f,variant:"ghost",fullWidth:!0,children:g("cancel")})]})]})})}function Z({isOpen:a,node:b,onSave:c,onClose:f,isAnthropic:g,isCcCompatible:h}){let i=(0,l.useTranslations)("providers"),[j,k]=(0,e.useState)({name:"",prefix:"",apiType:"chat",baseUrl:"https://api.openai.com/v1",chatPath:"",modelsPath:""}),[m,n]=(0,e.useState)(!1),[s,t]=(0,e.useState)(""),[u,v]=(0,e.useState)(!1),[w,y]=(0,e.useState)(null),[z,A]=(0,e.useState)(!1);(0,e.useEffect)(()=>{b&&(k({name:b.name||"",prefix:b.prefix||"",apiType:b.apiType||"chat",baseUrl:b.baseUrl||(h?"https://api.anthropic.com":g?"https://api.anthropic.com/v1":"https://api.openai.com/v1"),chatPath:b.chatPath||(h?aa:""),modelsPath:h?"":b.modelsPath||""}),A(!!(b.chatPath||!h&&b.modelsPath||h&&!b.chatPath)))},[b,g,h]);let B=[{value:"chat",label:i("chatCompletions")},{value:"responses",label:i("responsesApi")}],C=async()=>{if(j.name.trim()&&j.prefix.trim()&&j.baseUrl.trim()){n(!0);try{let a={name:j.name,prefix:j.prefix,baseUrl:j.baseUrl,chatPath:j.chatPath||(h?aa:""),modelsPath:h?"":j.modelsPath};g||(a.apiType=j.apiType),await c(a)}finally{n(!1)}}},D=async()=>{v(!0);try{let a=await fetch("/api/provider-nodes/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({baseUrl:j.baseUrl,apiKey:s,type:g?"anthropic-compatible":"openai-compatible",compatMode:h?"cc":void 0,chatPath:j.chatPath||(h?aa:""),modelsPath:h?"":j.modelsPath})}),b=await a.json();y(b.valid?"success":"failed")}catch{y("failed")}finally{v(!1)}};return b?(0,d.jsx)(r.Modal,{isOpen:a,title:h?_:i("editCompatibleTitle",{type:i(g?"anthropic":"openai")}),onClose:f,children:(0,d.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,d.jsx)(q.Input,{label:h?"Name":i("nameLabel"),value:j.name,onChange:a=>k({...j,name:a.target.value}),placeholder:h?"CC Compatible Production":i("compatibleProdPlaceholder",{type:i(g?"anthropic":"openai")}),hint:h?"Display name for this provider":i("nameHint")}),(0,d.jsx)(q.Input,{label:h?"Prefix":i("prefixLabel"),value:j.prefix,onChange:a=>k({...j,prefix:a.target.value}),placeholder:h?"cc":i(g?"anthropicPrefixPlaceholder":"openaiPrefixPlaceholder"),hint:h?"Used for aliases such as prefix/model-id":i("prefixHint")}),!g&&(0,d.jsx)(x.Select,{label:i("apiTypeLabel"),options:B,value:j.apiType,onChange:a=>k({...j,apiType:a.target.value})}),(0,d.jsx)(q.Input,{label:h?"Base URL":i("baseUrlLabel"),value:j.baseUrl,onChange:a=>k({...j,baseUrl:a.target.value}),placeholder:h?"https://example.com/v1":i(g?"anthropicBaseUrlPlaceholder":"openaiBaseUrlPlaceholder"),hint:h?"Base URL for the CC-compatible site. Do not include /messages.":i("compatibleBaseUrlHint",{type:i(g?"anthropic":"openai")})}),(0,d.jsxs)("button",{type:"button",className:"text-sm text-text-muted hover:text-text-primary flex items-center gap-1",onClick:()=>A(!z),"aria-expanded":z,"aria-controls":"advanced-settings",children:[(0,d.jsx)("span",{className:`transition-transform ${z?"rotate-90":""}`,"aria-hidden":"true",children:"▶"}),i("advancedSettings")]}),z&&(0,d.jsxs)("div",{id:"advanced-settings",className:"flex flex-col gap-3 pl-2 border-l-2 border-border",children:[(0,d.jsx)(q.Input,{label:h?"Chat Path":i("chatPathLabel"),value:j.chatPath,onChange:a=>k({...j,chatPath:a.target.value}),placeholder:h?aa:g?"/messages":i("chatPathPlaceholder"),hint:h?"Defaults to the strict Claude Code-compatible messages path":i("chatPathHint")}),!h&&(0,d.jsx)(q.Input,{label:i("modelsPathLabel"),value:j.modelsPath,onChange:a=>k({...j,modelsPath:a.target.value}),placeholder:i("modelsPathPlaceholder"),hint:i("modelsPathHint")})]}),(0,d.jsxs)("div",{className:"flex gap-2",children:[(0,d.jsx)(q.Input,{label:i("apiKeyForCheck"),type:"password",value:s,onChange:a=>t(a.target.value),className:"flex-1"}),(0,d.jsx)("div",{className:"pt-6",children:(0,d.jsx)(o.Button,{onClick:D,disabled:!s||u||!j.baseUrl.trim(),variant:"secondary",children:i(u?"checking":"check")})})]}),w&&(0,d.jsx)(p.Badge,{variant:"success"===w?"success":"error",children:i("success"===w?"valid":"invalid")}),(0,d.jsxs)("div",{className:"flex gap-2",children:[(0,d.jsx)(o.Button,{onClick:C,fullWidth:!0,disabled:!j.name.trim()||!j.prefix.trim()||!j.baseUrl.trim()||m,children:i(m?"saving":"save")}),(0,d.jsx)(o.Button,{onClick:f,variant:"ghost",fullWidth:!0,children:i("cancel")})]})]})}):null}V.propTypes={connection:h.default.shape({id:h.default.string,name:h.default.string,email:h.default.string,displayName:h.default.string,rateLimitedUntil:h.default.string,rateLimitProtection:h.default.bool,testStatus:h.default.string,isActive:h.default.bool,priority:h.default.number,lastError:h.default.string,lastErrorType:h.default.string,lastErrorSource:h.default.string,errorCode:h.default.oneOfType([h.default.string,h.default.number]),globalPriority:h.default.number,providerSpecificData:h.default.object}).isRequired,isOAuth:h.default.bool.isRequired,isCodex:h.default.bool,isFirst:h.default.bool.isRequired,isLast:h.default.bool.isRequired,onMoveUp:h.default.func.isRequired,onMoveDown:h.default.func.isRequired,onToggleActive:h.default.func.isRequired,onToggleRateLimit:h.default.func.isRequired,onToggleCodex5h:h.default.func,onToggleCodexWeekly:h.default.func,onRetest:h.default.func.isRequired,isRetesting:h.default.bool,onEdit:h.default.func.isRequired,onDelete:h.default.func.isRequired,onReauth:h.default.func,onApplyCodexAuthLocal:h.default.func,isApplyingCodexAuthLocal:h.default.bool,onExportCodexAuthFile:h.default.func,isExportingCodexAuthFile:h.default.bool},W.propTypes={isOpen:h.default.bool.isRequired,provider:h.default.string,providerName:h.default.string,isCompatible:h.default.bool,isAnthropic:h.default.bool,isCcCompatible:h.default.bool,onSave:h.default.func.isRequired,onClose:h.default.func.isRequired},Y.propTypes={isOpen:h.default.bool.isRequired,connection:h.default.shape({id:h.default.string,name:h.default.string,email:h.default.string,priority:h.default.number,authType:h.default.string,provider:h.default.string}),onSave:h.default.func.isRequired,onClose:h.default.func.isRequired},Z.propTypes={isOpen:h.default.bool.isRequired,node:h.default.shape({id:h.default.string,name:h.default.string,prefix:h.default.string,apiType:h.default.string,baseUrl:h.default.string,chatPath:h.default.string,modelsPath:h.default.string}),onSave:h.default.func.isRequired,onClose:h.default.func.isRequired,isAnthropic:h.default.bool,isCcCompatible:h.default.bool},a.s(["default",0,function(){let a=(0,i.useParams)(),b=(0,i.useRouter)(),c=a.id,[f,h]=(0,e.useState)([]),[m,p]=(0,e.useState)(!0),[q,w]=(0,e.useState)(null),[x,A]=(0,e.useState)(!1),[F,G]=(0,e.useState)(!1),[I,O]=(0,e.useState)(!1),[R,U]=(0,e.useState)(!1),[X,ab]=(0,e.useState)(null),[ac,ad]=(0,e.useState)(null),[ae,af]=(0,e.useState)(!1),[ag,ah]=(0,e.useState)(null),[ai,aj]=(0,e.useState)({}),[ak,al]=(0,e.useState)(!1),{copied:am,copy:an}=(0,D.useCopyToClipboard)(),ao=(0,l.useTranslations)("providers"),ap=(0,g.useNotificationStore)(),[aq,ar]=(0,e.useState)(null),[as,at]=(0,e.useState)(null),[au,av]=(0,e.useState)({}),[aw,ax]=(0,e.useState)(!1),[ay,az]=(0,e.useState)(!1),[aA,aB]=(0,e.useState)({current:0,total:0,phase:"idle",status:"",logs:[],error:"",importedCount:0}),[aC,aD]=(0,e.useState)({customModels:[],modelCompatOverrides:[]}),[aE,aF]=(0,e.useState)([]),[aG,aH]=(0,e.useState)(null),[aI,aJ]=(0,e.useState)(null),[aK,aL]=(0,e.useState)(null),aM=(0,z.isOpenAICompatibleProvider)(c),aN=(0,z.isClaudeCodeCompatibleProvider)(c),aO=(0,z.isAnthropicCompatibleProvider)(c)&&!(0,z.isClaudeCodeCompatibleProvider)(c),aP=aM||aO||aN,aQ=aO||aN,aR=q?{id:q.id,name:q.name||(aN?$:"anthropic-compatible"===q.type?ao("anthropicCompatibleName"):ao("openaiCompatibleName")),color:aN?"#B45309":"anthropic-compatible"===q.type?"#D97757":"#10A37F",textIcon:aN?"CC":"anthropic-compatible"===q.type?"AC":"OC",apiType:q.apiType,baseUrl:q.baseUrl,type:q.type}:z.FREE_PROVIDERS[c]||z.OAUTH_PROVIDERS[c]||z.APIKEY_PROVIDERS[c],aS=!!z.FREE_PROVIDERS[c]||!!z.OAUTH_PROVIDERS[c],aT=(0,z.supportsApiKeyOnFreeProvider)(c),aU=aS&&!aT,aV=(0,B.getModelsByProviderId)(c),aW="gemini"===c?aE:aV,aX=(0,z.getProviderAlias)(c),aY=aP||"openrouter"===c,aZ=c.endsWith("-search"),a$=(0,C.compatibleProviderSupportsModelImport)(c),a_=aP?c:aX,a0=aP?q?.prefix||c:aX,a1=(0,e.useCallback)(async()=>{try{let a=await fetch("/api/models/alias"),b=await a.json();a.ok&&aj(b.aliases||{})}catch(a){console.log("Error fetching aliases:",a)}},[]),a2=(0,e.useCallback)(async()=>{if(!aZ)try{let a=await fetch(`/api/provider-models?provider=${encodeURIComponent(c)}`,{cache:"no-store"});if(!a.ok)return;let b=await a.json();if(aD({customModels:b.models||[],modelCompatOverrides:b.modelCompatOverrides||[]}),"gemini"===c)try{let a=await fetch("/api/synced-available-models?provider=gemini",{cache:"no-store"});if(a.ok){let b=await a.json();aF(b.models||[])}}catch{}}catch(a){console.error("fetchProviderModelMeta",a)}},[c,aZ]),a3=(0,e.useCallback)(async()=>{try{let[a,b]=await Promise.all([fetch("/api/providers",{cache:"no-store"}),fetch("/api/provider-nodes",{cache:"no-store"})]),d=await a.json(),e=await b.json();if(a.ok){let a=(d.connections||[]).filter(a=>a.provider===c);h(a)}if(b.ok){let a=(e.nodes||[]).find(a=>a.id===c)||null;if(!a&&aP)for(let b=0;b<3;b+=1){await new Promise(a=>setTimeout(a,150));let b=await fetch("/api/provider-nodes",{cache:"no-store"});if(b.ok&&(a=((await b.json()).nodes||[]).find(a=>a.id===c)||null))break}w(a)}}catch(a){console.log("Error fetching connections:",a)}finally{p(!1)}},[c,aP]),a4=async a=>{try{let b=await fetch(`/api/provider-nodes/${c}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)}),d=await b.json();b.ok&&(w(d.node),await a3(),U(!1))}catch(a){console.log("Error updating provider node:",a)}};(0,e.useEffect)(()=>{a3(),a1(),fetch("/api/settings/proxy").then(a=>a.ok?a.json():null).then(a=>at(a)).catch(()=>{})},[a3,a1]);let a5=(0,e.useCallback)(async a=>{if(a.length)try{let b=await Promise.all(a.filter(a=>a.id).map(a=>fetch(`/api/settings/proxy?resolve=${encodeURIComponent(a.id)}`,{cache:"no-store"}).then(a=>a.ok?a.json():null).then(b=>[a.id,b]).catch(()=>[a.id,null]))),c={};for(let[a,d]of b)c[a]=d?.proxy?d:null;av(c)}catch{}},[]);(0,e.useEffect)(()=>{m||aZ||a2()},[m,aZ,a2]),(0,e.useEffect)(()=>{!m&&f.length>0&&a5(f)},[m,f,a5]);let a6=async(a,b,c=aX)=>{let d=`${c}/${a}`;try{let a=await fetch("/api/models/alias",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:d,alias:b})});if(a.ok)await a1();else{let b=await a.json();alert(b.error||ao("failedSetAlias"))}}catch(a){console.log("Error setting alias:",a)}},a7=async a=>{try{(await fetch(`/api/models/alias?alias=${encodeURIComponent(a)}`,{method:"DELETE"})).ok&&await a1()}catch(a){console.log("Error deleting alias:",a)}},a8=async a=>{if(confirm(ao("deleteConnectionConfirm")))try{(await fetch(`/api/providers/${a}`,{method:"DELETE"})).ok&&(h(f.filter(b=>b.id!==a)),"gemini"===c&&await a2())}catch(a){console.log("Error deleting connection:",a)}},a9=(0,e.useCallback)(()=>{a3(),A(!1)},[a3]),ba=(0,e.useCallback)(()=>{aU?A(!0):G(!0)},[aU]),bb=async a=>{try{let b=await fetch("/api/providers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:c,...a})});if(b.ok){let a=await b.json(),d=a?.connection;if(await a3(),G(!1),"gemini"===c&&d?.id){az(!0),aB({current:0,total:0,phase:"fetching",status:ao("fetchingModels"),logs:[],error:"",importedCount:0});try{let a=await fetch(`/api/providers/${d.id}/sync-models`,{method:"POST",signal:AbortSignal.timeout(3e4)}),b=await a.json();if(!a.ok||b.error)return aB(a=>({...a,phase:"error",status:ao("failedFetchModels"),error:b.error?.message||b.error||ao("failedImportModels")})),null;let c=b.syncedModels||0,e=b.models||[],f=[];if(e.length>0)for(let a of(f.push(`✓ ${c} models available`),f.push(""),e))f.push(` ${a.name||a.id}`);aB(a=>({...a,phase:"done",status:ao("modelsImported",{count:c}),total:c,current:c,importedCount:c,logs:f})),await a2()}catch(a){aB(b=>({...b,phase:"error",status:ao("failedFetchModels"),error:String(a)}))}}return null}let d=await b.json().catch(()=>({}));return d.error?.message||d.error||ao("failedSaveConnection")}catch(a){return console.log("Error saving connection:",a),ao("failedSaveConnectionRetry")}},bc=async a=>{try{let b=await fetch(`/api/providers/${X.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(b.ok)return await a3(),O(!1),null;let c=await b.json().catch(()=>({}));return c.error?.message||c.error||ao("failedSaveConnection")}catch(a){return console.log("Error updating connection:",a),ao("failedSaveConnectionRetry")}},bd=async(a,b)=>{try{(await fetch(`/api/providers/${a}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({isActive:b})})).ok&&h(c=>c.map(c=>c.id===a?{...c,isActive:b}:c))}catch(a){console.log("Error updating connection status:",a)}},be=async(a,b)=>{try{(await fetch("/api/rate-limits",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({connectionId:a,enabled:b})})).ok&&h(c=>c.map(c=>c.id===a?{...c,rateLimitProtection:b}:c))}catch(a){console.error("Error toggling rate limit:",a)}},bf=async(a,b,c)=>{try{let d=f.find(b=>b.id===a);if(!d)return;let e=d.providerSpecificData&&"object"==typeof d.providerSpecificData?d.providerSpecificData:{},g=e.codexLimitPolicy&&"object"==typeof e.codexLimitPolicy?e.codexLimitPolicy:{},i={...N(g),[b]:c},j=await fetch(`/api/providers/${a}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerSpecificData:{...e,codexLimitPolicy:i}})});if(!j.ok){let a=await j.json().catch(()=>({}));ap.error(a.error||"Failed to update Codex limit policy");return}h(b=>b.map(b=>b.id===a?{...b,providerSpecificData:{...b.providerSpecificData||{},codexLimitPolicy:i}}:b)),ap.success("Codex limit policy updated")}catch(a){console.error("Error toggling Codex quota policy:",a),ap.error("Failed to update Codex limit policy")}},bg=async a=>{if(a&&!ac){ad(a);try{let b=await fetch(`/api/providers/${a}/test`,{method:"POST"});if(!b.ok){let a=await b.json().catch(()=>({}));alert(a.error||ao("failedRetestConnection"));return}await a3()}catch(a){console.error("Error retesting connection:",a)}finally{ad(null)}}},bh=async()=>{if(ae||0===f.length)return;af(!0),ah(null);let a=new AbortController,b=setTimeout(()=>a.abort(),12e4);try{let b,d=await fetch("/api/providers/test-batch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:"provider",providerId:c}),signal:a.signal});try{b=await d.json()}catch{b={error:ao("providerTestFailed"),results:[],summary:null}}if(ah({...b,error:b.error?"object"==typeof b.error?b.error.message||b.error.error||JSON.stringify(b.error):String(b.error):null}),b?.summary){let{passed:a,failed:c,total:d}=b.summary;0===c?ap.success(ao("allTestsPassed",{total:d})):ap.warning(ao("testSummary",{passed:a,failed:c,total:d}))}await a3()}catch(b){let a=b?.name==="AbortError"?ao("providerTestTimeout"):ao("providerTestFailed");ah({error:a,results:[],summary:null}),ap.error(a)}finally{clearTimeout(b),af(!1)}},[bi,bj]=(0,e.useState)(null),bk=async(a,b)=>{if((a.headers.get("content-type")||"").includes("application/json")){let b=await a.json().catch(()=>({}));if("string"==typeof b?.error&&b.error.trim())return b.error;if(b?.error?.message)return b.error.message}return(await a.text().catch(()=>"")).trim()||b},bl=async a=>{if(!bi){bj(a);try{let b=await fetch(`/api/providers/${a}/refresh`,{method:"POST"}),c=await b.json().catch(()=>({}));b.ok&&c.success?(ap.success(ao("tokenRefreshed")),await a3()):ap.error(c.error||ao("tokenRefreshFailed"))}catch(a){console.error("Error refreshing token:",a),ap.error(ao("tokenRefreshFailed"))}finally{bj(null)}}},bm=async a=>{if(aI)return;aJ(a);let b="function"==typeof ao.has&&ao.has("codexAuthAppliedLocal")?ao("codexAuthAppliedLocal"):"Codex auth.json applied locally",c="function"==typeof ao.has&&ao.has("codexAuthApplyFailed")?ao("codexAuthApplyFailed"):"Failed to apply Codex auth.json locally";try{let d=await fetch(`/api/providers/${a}/codex-auth/apply-local`,{method:"POST"});if(!d.ok)return void ap.error(await bk(d,c));ap.success(b)}catch(a){console.error("Error applying Codex auth locally:",a),ap.error(c)}finally{aJ(null)}},bn=async a=>{if(aK)return;aL(a);let b="function"==typeof ao.has&&ao.has("codexAuthExported")?ao("codexAuthExported"):"Codex auth.json exported",c="function"==typeof ao.has&&ao.has("codexAuthExportFailed")?ao("codexAuthExportFailed"):"Failed to export Codex auth.json";try{let d=await fetch(`/api/providers/${a}/codex-auth/export`,{method:"POST"});if(!d.ok)return void ap.error(await bk(d,c));let e=await d.blob(),f=((a,b)=>{let c=a.headers.get("content-disposition")||"",d=c.match(/filename\*=UTF-8''([^;]+)/i);if(d?.[1])return decodeURIComponent(d[1]);let e=c.match(/filename="([^"]+)"/i);return e?.[1]?e[1]:b})(d,"codex-auth.json"),g=window.URL.createObjectURL(e),h=document.createElement("a");h.href=g,h.download=f,document.body.appendChild(h),h.click(),document.body.removeChild(h),window.setTimeout(()=>window.URL.revokeObjectURL(g),1e3),ap.success(b)}catch(a){console.error("Error exporting Codex auth file:",a),ap.error(c)}finally{aL(null)}},bo=async(a,b)=>{if(a&&b)try{let c=b.priority,d=a.priority;c===d&&(c=f.indexOf(a)>f.indexOf(b)?b.priority-.5:b.priority+.5),await Promise.all([fetch(`/api/providers/${a.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({priority:c})}),fetch(`/api/providers/${b.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({priority:d})})]),await a3()}catch(a){console.log("Error swapping priority:",a)}},bp=async()=>{if(aw)return;let a=f.find(a=>!1!==a.isActive);if(a){ax(!0),az(!0),aB({current:0,total:0,phase:"fetching",status:ao("fetchingModels"),logs:[],error:"",importedCount:0});try{let b=await fetch(`/api/providers/${a.id}/models`),d=await b.json();if(!b.ok)return void aB(a=>({...a,phase:"error",status:ao("failedFetchModels"),error:d.error||ao("failedImportModels")}));let e=d.models||[];if(0===e.length)return void aB(a=>({...a,phase:"done",status:ao("noModelsFound"),logs:[ao("noModelsReturnedFromEndpoint")]}));let f=new Set([...(aC.customModels||[]).map(a=>a.id),...aW.map(a=>a.id)]),g=e.filter(a=>!f.has(a.id||a.name||a.model));if(0===g.length)return void aB(a=>({...a,phase:"done",status:ao("allModelsAlreadyImported")||"All models already imported",logs:[ao("noNewModelsToImport")||"No new models to import"],importedCount:0,total:0,current:0}));aB(a=>({...a,phase:"importing",total:g.length,current:0,status:ao("importingModelsProgress",{current:0,total:g.length}),logs:[ao("foundModelsStartingImport",{count:g.length}),...g.length<e.length?[ao("skippingExistingModels",{count:e.length-g.length})||`Skipping ${e.length-g.length} existing models`]:[]]}));let h=0;for(let a=0;a<g.length;a++){let b=g[a],d=b.id||b.name||b.model;if(!d)continue;let e=d.split("/"),f=e[e.length-1];aB(b=>({...b,current:a+1,status:ao("importingModelsProgress",{current:a+1,total:g.length}),logs:[...b.logs,ao("importingModelById",{modelId:d})]})),await fetch("/api/provider-models",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:c,modelId:d,modelName:b.name||d,source:"imported"})}),ai[f]||await a6(d,f,a_),h+=1}await a1(),aB(a=>({...a,phase:"done",current:g.length,status:h>0?ao("importSuccessCount",{count:h}):ao("noNewModelsAddedExisting"),logs:[...a.logs,h>0?ao("importDoneCount",{count:h}):ao("noNewModelsAdded")],importedCount:h})),h>0&&setTimeout(()=>{window.location.reload()},2e3)}catch(a){console.log("Error importing models:",a),aB(b=>({...b,phase:"error",status:ao("importFailed"),error:a instanceof Error?a.message:ao("unexpectedErrorOccurred")}))}finally{ax(!1)}}},bq=async(a,b)=>{az(!0),aB({current:0,total:0,phase:"fetching",status:ao("fetchingModels"),logs:[],error:"",importedCount:0});try{let c=(await a()).models||[];if(0===c.length)return void aB(a=>({...a,phase:"done",status:ao("noModelsFound"),logs:[ao("noModelsReturnedFromEndpoint")]}));aB(a=>({...a,phase:"importing",total:c.length,status:ao("importingModelsProgress",{current:0,total:c.length}),logs:[ao("foundModelsStartingImport",{count:c.length})]}));let d=0;for(let a=0;a<c.length;a++){let e=c[a],f=e.id||e.name||e.model;f&&(aB(b=>({...b,current:a+1,status:ao("importingModelsProgress",{current:a+1,total:c.length}),logs:[...b.logs,ao("importingModelById",{modelId:f})]})),await b(e)&&(d+=1))}aB(a=>({...a,phase:"done",current:c.length,status:d>0?ao("importSuccessCount",{count:d}):ao("noNewModelsAdded"),logs:[...a.logs,d>0?ao("importDoneCount",{count:d}):ao("noNewModelsAdded")],importedCount:d})),d>0&&setTimeout(()=>{window.location.reload()},2e3)}catch(a){console.log("Error importing models:",a),aB(b=>({...b,phase:"error",status:ao("importFailed"),error:a instanceof Error?a.message:ao("unexpectedErrorOccurred")}))}},br=f.some(a=>!1!==a.isActive),bs=f.find(a=>!1!==a.isActive),bt=!!bs?.providerSpecificData?.autoSync,[bu,bv]=(0,e.useState)(!1),bw=async()=>{if(bs&&!bu){bv(!0);try{let a=!bt;await fetch(`/api/providers/${bs.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerSpecificData:{autoSync:a}})}),await a3(),ap[a?"success":"info"](a?ao("autoSyncEnabled"):ao("autoSyncDisabled"))}catch(a){console.log("Error toggling auto-sync:",a),ap.error(ao("autoSyncToggleFailed"))}finally{bv(!1)}}},[bx,by]=(0,e.useState)(!1),bz=(0,e.useMemo)(()=>Object.entries(ai).filter(([,a])=>a.startsWith(`${a_}/`)),[ai,a_]),bA=async()=>{if(!bx&&confirm(ao("clearAllModelsConfirm"))){by(!0);try{(await fetch(`/api/provider-models?provider=${encodeURIComponent(a_)}&all=true`,{method:"DELETE"})).ok?(await Promise.all(bz.map(([a])=>fetch(`/api/models/alias?alias=${encodeURIComponent(a)}`,{method:"DELETE"}).catch(()=>{}))),await a2(),await a1(),ap.success(ao("clearAllModelsSuccess"))):ap.error(ao("clearAllModelsFailed"))}catch{ap.error(ao("clearAllModelsFailed"))}finally{by(!1)}}},bB=(0,e.useMemo)(()=>H(aC.customModels),[aC.customModels]),bC=(0,e.useMemo)(()=>H(aC.modelCompatOverrides),[aC.modelCompatOverrides]),bD=(0,e.useMemo)(()=>(0,C.getCompatibleFallbackModels)(c,aC.customModels),[c,aC.customModels]),bE=(a,b=E.MODEL_COMPAT_PROTOCOL_KEYS[0])=>J(a,b,bB,bC),bF=(a,b=E.MODEL_COMPAT_PROTOCOL_KEYS[0])=>K(a,b,bB,bC),bG=(0,e.useCallback)((a,b)=>M(a,b,bB,bC),[bB,bC]),bH=async(a,b)=>{aH(a);try{let d,e=bB.get(a),f=b.compatByProtocol&&void 0===b.normalizeToolCallId&&void 0===b.preserveOpenAIDeveloperRole&&!("upstreamHeaders"in b);e?f?d={provider:c,modelId:a,compatByProtocol:b.compatByProtocol}:(d={provider:c,modelId:a,modelName:e.name||a,source:e.source||"manual",apiFormat:e.apiFormat||"chat-completions",supportedEndpoints:Array.isArray(e.supportedEndpoints)&&e.supportedEndpoints.length?e.supportedEndpoints:["chat"],normalizeToolCallId:void 0!==b.normalizeToolCallId?b.normalizeToolCallId:!!e.normalizeToolCallId,preserveOpenAIDeveloperRole:void 0!==b.preserveOpenAIDeveloperRole?b.preserveOpenAIDeveloperRole:!Object.prototype.hasOwnProperty.call(e,"preserveOpenAIDeveloperRole")||!!e.preserveOpenAIDeveloperRole},b.compatByProtocol&&(d.compatByProtocol=b.compatByProtocol)):d={provider:c,modelId:a,...b};let g=await fetch("/api/provider-models",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)});if(!g.ok){let a=await L(g);ap.error(a?`${ao("failedSaveCustomModel")} — ${a}`:ao("failedSaveCustomModel"));return}}catch{ap.error(ao("failedSaveCustomModel"));return}finally{aH(null)}try{await a2()}catch{}};return m?(0,d.jsxs)("div",{className:"flex flex-col gap-8",children:[(0,d.jsx)(s.CardSkeleton,{}),(0,d.jsx)(s.CardSkeleton,{})]}):aR?(0,d.jsxs)("div",{className:"flex flex-col gap-8",children:[(0,d.jsxs)("div",{children:[(0,d.jsxs)(j.default,{href:"/dashboard/providers",className:"inline-flex items-center gap-1 text-sm text-text-muted hover:text-primary transition-colors mb-4",children:[(0,d.jsx)("span",{className:"material-symbols-outlined text-lg",children:"arrow_back"}),ao("backToProviders")]}),(0,d.jsxs)("div",{className:"flex items-center gap-4",children:[(0,d.jsx)("div",{className:"rounded-lg flex items-center justify-center",style:{backgroundColor:`${aR.color}15`},children:ak?(0,d.jsx)("span",{className:"text-sm font-bold",style:{color:aR.color},children:aR.textIcon||aR.id.slice(0,2).toUpperCase()}):(0,d.jsx)(k.default,{src:aM&&aR.apiType?"responses"===aR.apiType?"/providers/oai-r.png":"/providers/oai-cc.png":aQ?"/providers/anthropic-m.png":`/providers/${aR.id}.png`,alt:aR.name,width:48,height:48,className:"object-contain rounded-lg max-w-[48px] max-h-[48px]",sizes:"48px",onError:()=>al(!0)})}),(0,d.jsxs)("div",{children:[aR.website?(0,d.jsxs)("a",{href:aR.website,target:"_blank",rel:"noopener noreferrer",className:"text-3xl font-semibold tracking-tight hover:underline inline-flex items-center gap-2",style:{color:aR.color},children:[aR.name,(0,d.jsx)("span",{className:"material-symbols-outlined text-lg opacity-60",children:"open_in_new"})]}):(0,d.jsx)("h1",{className:"text-3xl font-semibold tracking-tight",children:aR.name}),(0,d.jsx)("p",{className:"text-text-muted",children:ao("connectionCountLabel",{count:f.length})})]})]})]}),aP&&q&&(0,d.jsxs)(n.Card,{children:[(0,d.jsxs)("div",{className:"flex items-center justify-between mb-4",children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("h2",{className:"text-lg font-semibold",children:aN?_:aO?ao("anthropicCompatibleDetails"):ao("openaiCompatibleDetails")}),(0,d.jsxs)("p",{className:"text-sm text-text-muted",children:[aQ?ao("messagesApi"):"responses"===q.apiType?ao("responsesApi"):ao("chatCompletions")," ","· ",(q.baseUrl||"").replace(/\/$/,""),"/",aN?(q.chatPath||aa).replace(/^\//,""):aO?(q.chatPath||"/messages").replace(/^\//,""):"responses"===q.apiType?(q.chatPath||"/responses").replace(/^\//,""):(q.chatPath||"/chat/completions").replace(/^\//,"")]})]}),(0,d.jsxs)("div",{className:"flex items-center gap-2",children:[(0,d.jsx)(o.Button,{size:"sm",icon:"add",onClick:()=>G(!0),disabled:f.length>0,children:ao("add")}),(0,d.jsx)(o.Button,{size:"sm",variant:"secondary",icon:"edit",onClick:()=>U(!0),children:ao("edit")}),(0,d.jsx)(o.Button,{size:"sm",variant:"secondary",icon:"delete",onClick:async()=>{if(confirm(ao("deleteCompatibleNodeConfirm",{type:aN?$:aO?ao("anthropic"):ao("openai")})))try{(await fetch(`/api/provider-nodes/${c}`,{method:"DELETE"})).ok&&b.push("/dashboard/providers")}catch(a){console.log("Error deleting provider node:",a)}},children:ao("delete")})]})]}),f.length>0&&(0,d.jsx)("p",{className:"text-sm text-text-muted",children:ao("singleConnectionPerCompatible")})]}),(0,d.jsxs)(n.Card,{children:[(0,d.jsxs)("div",{className:"flex items-center justify-between mb-4",children:[(0,d.jsxs)("div",{className:"flex items-center gap-3",children:[(0,d.jsx)("h2",{className:"text-lg font-semibold",children:ao("connections")}),(0,d.jsxs)("button",{onClick:()=>ar({level:"provider",id:c,label:aR?.name||c}),className:`inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium transition-all ${as?.providers?.[c]?"bg-amber-500/15 text-amber-500 hover:bg-amber-500/25":"bg-black/[0.03] dark:bg-white/[0.03] text-text-muted/50 hover:text-text-muted hover:bg-black/[0.06] dark:hover:bg-white/[0.06]"}`,title:as?.providers?.[c]?ao("providerProxyTitleConfigured",{host:as.providers[c].host||ao("configured")}):ao("providerProxyConfigureHint"),children:[(0,d.jsx)("span",{className:"material-symbols-outlined text-[14px]",children:"vpn_lock"}),as?.providers?.[c]&&as.providers[c].host||ao("providerProxy")]})]}),f.length>1&&(0,d.jsxs)("button",{onClick:bh,disabled:ae||!!ac,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium border transition-colors ${ae?"bg-primary/20 border-primary/40 text-primary animate-pulse":"bg-bg-subtle border-border text-text-muted hover:text-text-primary hover:border-primary/40"}`,title:ao("testAll"),"aria-label":ao("testAll"),children:[(0,d.jsx)("span",{className:"material-symbols-outlined text-[14px]",children:ae?"sync":"play_arrow"}),ae?ao("testing"):ao("testAll")]}),aP?0===f.length&&(0,d.jsx)(o.Button,{size:"sm",icon:"add",onClick:()=>G(!0),children:ao("add")}):(0,d.jsxs)("div",{className:"flex items-center gap-2",children:[(0,d.jsx)(o.Button,{size:"sm",icon:"add",onClick:ba,children:aT?"Add PAT":ao("add")}),"qoder"===c&&(0,d.jsx)(o.Button,{size:"sm",variant:"secondary",onClick:()=>A(!0),children:"Experimental OAuth"})]})]}),0===f.length?(0,d.jsxs)("div",{className:"text-center py-12",children:[(0,d.jsx)("div",{className:"inline-flex items-center justify-center w-16 h-16 rounded-full bg-primary/10 text-primary mb-4",children:(0,d.jsx)("span",{className:"material-symbols-outlined text-[32px]",children:aU?"lock":"key"})}),(0,d.jsx)("p",{className:"text-text-main font-medium mb-1",children:ao("noConnectionsYet")}),(0,d.jsx)("p",{className:"text-sm text-text-muted mb-4",children:ao("addFirstConnectionHint")}),!aP&&(0,d.jsxs)("div",{className:"flex items-center justify-center gap-2",children:[(0,d.jsx)(o.Button,{icon:"add",onClick:ba,children:aT?"Add PAT":ao("addConnection")}),"qoder"===c&&(0,d.jsx)(o.Button,{variant:"secondary",onClick:()=>A(!0),children:"Experimental OAuth"})]})]}):(()=>{let a=[...f].sort((a,b)=>(a.priority||0)-(b.priority||0));if(!a.some(a=>a.providerSpecificData?.tag))return(0,d.jsx)("div",{className:"flex flex-col divide-y divide-black/[0.03] dark:divide-white/[0.03]",children:a.map((b,e)=>(0,d.jsx)(V,{connection:b,isOAuth:"oauth"===b.authType,isFirst:0===e,isLast:e===a.length-1,onMoveUp:()=>bo(b,a[e-1]),onMoveDown:()=>bo(b,a[e+1]),onToggleActive:a=>bd(b.id,a),onToggleRateLimit:a=>be(b.id,a),isCodex:"codex"===c,onToggleCodex5h:a=>bf(b.id,"use5h",a),onToggleCodexWeekly:a=>bf(b.id,"useWeekly",a),onRetest:()=>bg(b.id),isRetesting:ac===b.id,onEdit:()=>{ab(b),O(!0)},onDelete:()=>a8(b.id),onReauth:"oauth"===b.authType?()=>A(!0):void 0,onRefreshToken:"oauth"===b.authType?()=>bl(b.id):void 0,isRefreshing:bi===b.id,onApplyCodexAuthLocal:"codex"===c?()=>bm(b.id):void 0,isApplyingCodexAuthLocal:aI===b.id,onExportCodexAuthFile:"codex"===c?()=>bn(b.id):void 0,isExportingCodexAuthFile:aK===b.id,onProxy:()=>ar({level:"key",id:b.id,label:b.name||b.email||b.id}),hasProxy:!!au[b.id]?.proxy,proxySource:au[b.id]?.level||null,proxyHost:au[b.id]?.proxy?.host||null},b.id))});let b=new Map;for(let c of a){let a=c.providerSpecificData?.tag?.trim()||"";b.has(a)||b.set(a,[]),b.get(a).push(c)}let e=Array.from(b.keys()).sort((a,b)=>""===a?-1:""===b?1:a.localeCompare(b));return(0,d.jsx)("div",{className:"flex flex-col gap-0",children:e.map((f,g)=>{let h=b.get(f);return(0,d.jsxs)("div",{className:g>0?"border-t border-black/[0.06] dark:border-white/[0.06] mt-1 pt-1":"",children:[f&&(0,d.jsxs)("div",{className:"flex items-center gap-2 px-3 pt-2 pb-1",children:[(0,d.jsx)("span",{className:"material-symbols-outlined text-[13px] text-text-muted/50",children:"label"}),(0,d.jsx)("span",{className:"text-[11px] font-semibold uppercase tracking-widest text-text-muted/60 select-none",children:f}),(0,d.jsx)("div",{className:"flex-1 h-px bg-black/[0.04] dark:bg-white/[0.04]"}),(0,d.jsx)("span",{className:"text-[10px] text-text-muted/40",children:h.length})]}),(0,d.jsx)("div",{className:"flex flex-col divide-y divide-black/[0.03] dark:divide-white/[0.03]",children:h.map((b,f)=>(0,d.jsx)(V,{connection:b,isOAuth:"oauth"===b.authType,isFirst:0===g&&0===f,isLast:g===e.length-1&&f===h.length-1,onMoveUp:()=>bo(b,a[a.indexOf(b)-1]),onMoveDown:()=>bo(b,a[a.indexOf(b)+1]),onToggleActive:a=>bd(b.id,a),onToggleRateLimit:a=>be(b.id,a),isCodex:"codex"===c,onToggleCodex5h:a=>bf(b.id,"use5h",a),onToggleCodexWeekly:a=>bf(b.id,"useWeekly",a),onRetest:()=>bg(b.id),isRetesting:ac===b.id,onEdit:()=>{ab(b),O(!0)},onDelete:()=>a8(b.id),onReauth:"oauth"===b.authType?()=>A(!0):void 0,onRefreshToken:"oauth"===b.authType?()=>bl(b.id):void 0,isRefreshing:bi===b.id,onApplyCodexAuthLocal:"codex"===c?()=>bm(b.id):void 0,isApplyingCodexAuthLocal:aI===b.id,onExportCodexAuthFile:"codex"===c?()=>bn(b.id):void 0,isExportingCodexAuthFile:aK===b.id,onProxy:()=>ar({level:"key",id:b.id,label:b.name||b.email||b.id}),hasProxy:!!au[b.id]?.proxy,proxySource:au[b.id]?.level||null,proxyHost:au[b.id]?.proxy?.host||null},b.id))})]},f||"__untagged__")})})})()]}),!aZ&&(0,d.jsxs)(n.Card,{children:[(0,d.jsx)("h2",{className:"text-lg font-semibold mb-4",children:ao("availableModels")}),(()=>{let a=a$&&br&&(0,d.jsxs)("button",{onClick:bw,disabled:bu,className:"flex items-center gap-1.5 px-2.5 py-1 rounded-lg border border-border bg-transparent cursor-pointer text-[12px] disabled:opacity-50 disabled:cursor-not-allowed",title:ao("autoSyncTooltip"),children:[(0,d.jsx)("span",{className:"material-symbols-outlined text-[16px]",style:{color:bt?"#22c55e":"var(--color-text-muted)"},children:bt?"toggle_on":"toggle_off"}),(0,d.jsx)("span",{className:"text-text-main",children:ao("autoSync")})]}),b=(aC.customModels.length>0||bz.length>0)&&(0,d.jsxs)("button",{onClick:bA,disabled:bx,className:"flex items-center gap-1.5 px-2.5 py-1 rounded-lg border border-red-300 dark:border-red-800 bg-transparent cursor-pointer text-[12px] text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 disabled:opacity-50 disabled:cursor-not-allowed",title:ao("clearAllModels"),children:[(0,d.jsx)("span",{className:"material-symbols-outlined text-[16px]",children:"delete_sweep"}),(0,d.jsx)("span",{children:ao("clearAllModels")})]});if(aY){let e="openrouter"===c?ao("openRouterAnyModelHint"):aN?"CC Compatible available models mirror the OAuth Claude Code provider list.":ao("compatibleModelsDescription",{type:aO?ao("anthropic"):ao("openai")}),g="openrouter"===c?ao("modelIdFromOpenRouter"):ao("modelId"),h="openrouter"===c?ao("openRouterModelPlaceholder"):aN?"claude-sonnet-4-6":aO?ao("anthropicCompatibleModelPlaceholder"):ao("openaiCompatibleModelPlaceholder");return(0,d.jsxs)("div",{children:[(0,d.jsxs)("div",{className:"flex items-center gap-2 mb-4",children:[a,b]}),(0,d.jsx)(T,{providerStorageAlias:a_,providerDisplayAlias:a0,modelAliases:ai,fallbackModels:bD,description:e,inputLabel:g,inputPlaceholder:h,copied:am,onCopy:an,onSetAlias:a6,onDeleteAlias:a7,connections:f,isAnthropic:aQ,onImportWithProgress:bq,t:ao,effectiveModelNormalize:bE,effectiveModelPreserveDeveloper:bF,getUpstreamHeadersRecord:bG,saveModelCompatFlags:bH,compatSavingModelId:aG,onModelsChanged:a2,allowImport:a$})]})}if(aR.passthroughModels)return(0,d.jsxs)("div",{children:[(0,d.jsxs)("div",{className:"flex items-center gap-2 mb-4",children:[(0,d.jsx)(o.Button,{size:"sm",variant:"secondary",icon:"download",onClick:bp,disabled:!br||aw,children:aw?ao("importingModels"):ao("importFromModels")}),a,b,!br&&(0,d.jsx)("span",{className:"text-xs text-text-muted",children:ao("addConnectionToImport")})]}),(0,d.jsx)(Q,{providerAlias:aX,modelAliases:ai,copied:am,onCopy:an,onSetAlias:a6,onDeleteAlias:a7,t:ao,effectiveModelNormalize:bE,effectiveModelPreserveDeveloper:bF,getUpstreamHeadersRecord:bG,saveModelCompatFlags:bH,compatSavingModelId:aG})]});let e="gemini"===c?null:(0,d.jsxs)("div",{className:"flex items-center gap-2 mb-4",children:[(0,d.jsx)(o.Button,{size:"sm",variant:"secondary",icon:"download",onClick:bp,disabled:!br||aw,children:aw?ao("importingModels"):ao("importFromModels")}),a,!br&&(0,d.jsx)("span",{className:"text-xs text-text-muted",children:ao("addConnectionToImport")})]});return 0===aW.length?(0,d.jsxs)("div",{children:[e,(0,d.jsx)("p",{className:"text-sm text-text-muted",children:ao("noModelsConfigured")})]}):(0,d.jsxs)("div",{children:[e,(0,d.jsx)("div",{className:"flex flex-wrap gap-3",children:aW.map(a=>(0,d.jsx)(P,{model:a,fullModel:`${a0}/${a.id}`,copied:am,onCopy:an,t:ao,showDeveloperToggle:!0,effectiveModelNormalize:bE,effectiveModelPreserveDeveloper:bF,getUpstreamHeadersRecord:b=>bG(a.id,b),saveModelCompatFlags:bH,compatDisabled:aG===a.id},a.id))})]})})(),!aY&&"gemini"!==c&&(0,d.jsx)(S,{providerId:c,providerAlias:a0,copied:am,onCopy:an,onModelsChanged:a2})]}),aZ&&(0,d.jsxs)(n.Card,{children:[(0,d.jsx)("h2",{className:"text-lg font-semibold mb-4",children:ao("searchProvider")||"Search Provider"}),(0,d.jsx)("p",{className:"text-sm text-text-muted",children:ao("searchProviderDesc")||"This provider is used for web search via POST /v1/search. No model configuration needed — search providers are ready to use once an API key is connected."}),"perplexity-search"===c&&(0,d.jsxs)("div",{className:"mt-3 flex items-center gap-2 px-3 py-2 rounded-lg bg-blue-500/10 border border-blue-500/20",children:[(0,d.jsx)("span",{className:"material-symbols-outlined text-sm text-blue-400",children:"link"}),(0,d.jsxs)("p",{className:"text-xs text-blue-300",children:["Uses the same API key as ",(0,d.jsx)("strong",{children:"Perplexity"})," (chat provider). If you already have Perplexity configured, no additional setup is needed."]})]})]}),"kiro"===c?(0,d.jsx)(u.KiroOAuthWrapper,{isOpen:x,providerInfo:aR,onSuccess:a9,onClose:()=>{A(!1)}}):"cursor"===c?(0,d.jsx)(v.CursorAuthModal,{isOpen:x,onSuccess:a9,onClose:()=>{A(!1)}}):(0,d.jsx)(t.OAuthModal,{isOpen:x,provider:c,providerInfo:aR,onSuccess:a9,onClose:()=>{A(!1)}}),(0,d.jsx)(W,{isOpen:F,provider:c,providerName:aR.name,isCompatible:aP,isAnthropic:aQ,isCcCompatible:aN,onSave:bb,onClose:()=>G(!1)}),(0,d.jsx)(Y,{isOpen:I,connection:X,onSave:bc,onClose:()=>O(!1)}),aP&&(0,d.jsx)(Z,{isOpen:R,node:q,onSave:a4,onClose:()=>U(!1),isAnthropic:aQ,isCcCompatible:aN}),ag&&(0,d.jsxs)("div",{className:"fixed inset-0 z-50 flex items-start justify-center pt-[10vh]",onClick:()=>ah(null),children:[(0,d.jsx)("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),(0,d.jsxs)("div",{className:"relative bg-bg-primary border border-border rounded-xl w-full max-w-[600px] max-h-[80vh] overflow-y-auto shadow-2xl",onClick:a=>a.stopPropagation(),children:[(0,d.jsxs)("div",{className:"sticky top-0 z-10 flex items-center justify-between px-5 py-3 border-b border-border bg-bg-primary/95 backdrop-blur-sm rounded-t-xl",children:[(0,d.jsx)("h3",{className:"font-semibold",children:ao("testResults")}),(0,d.jsx)("button",{onClick:()=>ah(null),className:"p-1 rounded-lg hover:bg-bg-subtle text-text-muted hover:text-text-primary transition-colors","aria-label":"Close",children:(0,d.jsx)("span",{className:"material-symbols-outlined text-lg",children:"close"})})]}),(0,d.jsx)("div",{className:"p-5",children:ag.error&&(!ag.results||0===ag.results.length)?(0,d.jsxs)("div",{className:"text-center py-6",children:[(0,d.jsx)("span",{className:"material-symbols-outlined text-red-500 text-[32px] mb-2 block",children:"error"}),(0,d.jsx)("p",{className:"text-sm text-red-400",children:String(ag.error)})]}):(0,d.jsxs)("div",{className:"flex flex-col gap-3",children:[ag.summary&&(0,d.jsxs)("div",{className:"flex items-center gap-3 text-xs mb-1",children:[(0,d.jsx)("span",{className:"text-text-muted",children:aR?.name||c}),(0,d.jsx)("span",{className:"px-2 py-0.5 rounded bg-emerald-500/15 text-emerald-400 font-medium",children:ao("passedCount",{count:ag.summary.passed})}),ag.summary.failed>0&&(0,d.jsx)("span",{className:"px-2 py-0.5 rounded bg-red-500/15 text-red-400 font-medium",children:ao("failedCount",{count:ag.summary.failed})}),(0,d.jsx)("span",{className:"text-text-muted ml-auto",children:ao("testedCount",{count:ag.summary.total})})]}),(ag.results||[]).map((a,b)=>(0,d.jsxs)("div",{className:"flex items-center gap-2 text-xs px-3 py-2 rounded-lg bg-black/[0.03] dark:bg-white/[0.03]",children:[(0,d.jsx)("span",{className:`material-symbols-outlined text-[16px] ${a.valid?"text-emerald-500":"text-red-500"}`,children:a.valid?"check_circle":"error"}),(0,d.jsx)("div",{className:"flex-1 min-w-0",children:(0,d.jsx)("span",{className:"font-medium",children:a.connectionName})}),void 0!==a.latencyMs&&(0,d.jsx)("span",{className:"text-text-muted font-mono tabular-nums",children:ao("millisecondsAbbr",{value:a.latencyMs})}),(0,d.jsx)("span",{className:`text-[10px] uppercase font-bold px-1.5 py-0.5 rounded ${a.valid?"bg-emerald-500/15 text-emerald-400":"bg-red-500/15 text-red-400"}`,children:a.valid?ao("okShort"):a.diagnosis?.type||ao("errorShort")})]},a.connectionId||b)),(!ag.results||0===ag.results.length)&&(0,d.jsx)("div",{className:"text-center py-4 text-text-muted text-sm",children:ao("noActiveConnectionsInGroup")})]})})]})]}),aq&&(0,d.jsx)(y.ProxyConfigModal,{isOpen:!!aq,onClose:()=>ar(null),level:aq.level,levelId:aq.id,levelLabel:aq.label,onSaved:()=>void a5(f)}),(0,d.jsx)(r.Modal,{isOpen:ay,onClose:()=>{("done"===aA.phase||"error"===aA.phase)&&az(!1)},title:ao("importingModelsTitle"),size:"md",closeOnOverlay:!1,showCloseButton:"done"===aA.phase||"error"===aA.phase,children:(0,d.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,d.jsxs)("div",{className:"flex items-center gap-3",children:["fetching"===aA.phase&&(0,d.jsx)("span",{className:"material-symbols-outlined text-primary animate-spin",children:"progress_activity"}),"importing"===aA.phase&&(0,d.jsx)("span",{className:"material-symbols-outlined text-primary animate-spin",children:"progress_activity"}),"done"===aA.phase&&(0,d.jsx)("span",{className:"material-symbols-outlined text-green-500",children:"check_circle"}),"error"===aA.phase&&(0,d.jsx)("span",{className:"material-symbols-outlined text-red-500",children:"error"}),(0,d.jsx)("span",{className:"text-sm font-medium text-text-main",children:aA.status})]}),("importing"===aA.phase||"done"===aA.phase)&&aA.total>0&&(0,d.jsxs)("div",{className:"w-full",children:[(0,d.jsxs)("div",{className:"flex items-center justify-between mb-1",children:[(0,d.jsxs)("span",{className:"text-xs text-text-muted",children:[aA.current," / ",aA.total]}),(0,d.jsxs)("span",{className:"text-xs text-text-muted",children:[Math.round(aA.current/aA.total*100),"%"]})]}),(0,d.jsx)("div",{className:"w-full h-2.5 bg-black/10 dark:bg-white/10 rounded-full overflow-hidden",children:(0,d.jsx)("div",{className:"h-full rounded-full transition-all duration-300 ease-out",style:{width:`${aA.current/aA.total*100}%`,background:"done"===aA.phase?"linear-gradient(90deg, #22c55e, #16a34a)":"linear-gradient(90deg, var(--color-primary), var(--color-primary-hover, var(--color-primary)))"}})})]}),"fetching"===aA.phase&&(0,d.jsx)("div",{className:"w-full h-2.5 bg-black/10 dark:bg-white/10 rounded-full overflow-hidden",children:(0,d.jsx)("div",{className:"h-full rounded-full animate-pulse",style:{width:"60%",background:"linear-gradient(90deg, var(--color-primary), var(--color-primary-hover, var(--color-primary)))"}})}),"error"===aA.phase&&aA.error&&(0,d.jsx)("div",{className:"p-3 rounded-lg bg-red-500/10 border border-red-500/20",children:(0,d.jsx)("p",{className:"text-sm text-red-400",children:aA.error})}),aA.logs.length>0&&(0,d.jsx)("div",{className:"max-h-48 overflow-y-auto rounded-lg bg-black/5 dark:bg-white/5 p-3 border border-black/5 dark:border-white/5",children:(0,d.jsx)("div",{className:"flex flex-col gap-1",children:aA.logs.map((a,b)=>(0,d.jsx)("p",{className:`text-xs font-mono ${a.startsWith("✓")?"text-green-500 font-semibold":"text-text-muted"}`,children:a},b))})}),"done"===aA.phase&&(0,d.jsx)("div",{className:"flex justify-center",children:(0,d.jsx)("button",{onClick:()=>az(!1),className:"px-4 py-2 text-sm font-medium rounded-lg bg-primary text-white hover:opacity-90 transition-opacity",children:ao("close")||"Close"})})]})})]}):(0,d.jsxs)("div",{className:"text-center py-20",children:[(0,d.jsx)("p",{className:"text-text-muted",children:ao("providerNotFound")}),(0,d.jsx)(j.default,{href:"/dashboard/providers",className:"text-primary mt-4 inline-block",children:ao("backToProviders")})]})}]),c()}catch(a){c(a)}},!1)];
|
|
2
2
|
|
|
3
3
|
//# sourceMappingURL=src_0vjsxxr._.js.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
module.exports=[44403,a=>{"use strict";var b=a.i(254799);process.env.API_KEY_SECRET||console.error("[SECURITY] API_KEY_SECRET is not set. API key CRC validation is disabled."),a.s(["generateApiKeyWithMachine",0,function(a){let c,d=
|
|
1
|
+
module.exports=[44403,a=>{"use strict";var b=a.i(254799);process.env.API_KEY_SECRET||console.error("[SECURITY] API_KEY_SECRET is not set. API key CRC validation is disabled."),a.s(["generateApiKeyWithMachine",0,function(a){let c,d=b.default.randomBytes(3).toString("hex"),e=(c=function(){let a=process.env.API_KEY_SECRET||"omniroute-default-insecure-api-key-secret";if(!a||""===a.trim())throw Error("API_KEY_SECRET is required for API key CRC operations");return a}(),b.default.createHmac("sha256",c).update(a+d).digest("hex").slice(0,8));return{key:`sk-${a}-${d}-${e}`,keyId:d}}])}];
|
|
2
2
|
|
|
3
3
|
//# sourceMappingURL=src_shared_utils_apiKey_ts_0l8g1z8._.js.map
|