omniroute 2.8.0 → 2.8.1
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 +2 -2
- package/app/.next/prerender-manifest.json +3 -3
- package/app/.next/server/app/(dashboard)/dashboard/a2a/page_client-reference-manifest.js +1 -1
- 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-log/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/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/mcp/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/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/profile/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/translator/page_client-reference-manifest.js +1 -1
- package/app/.next/server/app/(dashboard)/dashboard/usage/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 +2 -2
- 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/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]__09c944b3._.js +1 -1
- package/app/.next/server/chunks/[root-of-the-server]__167585da._.js +1 -1
- package/app/.next/server/chunks/[root-of-the-server]__3972de72._.js +5 -5
- package/app/.next/server/chunks/[root-of-the-server]__64bd5d97._.js +1 -1
- package/app/.next/server/chunks/[root-of-the-server]__784fb7c5._.js +1 -1
- package/app/.next/server/chunks/[root-of-the-server]__7d9b23e7._.js +1 -1
- package/app/.next/server/chunks/[root-of-the-server]__80e3bfc3._.js +1 -1
- package/app/.next/server/chunks/[root-of-the-server]__84e445b2._.js +2 -2
- package/app/.next/server/chunks/[root-of-the-server]__92cb0def._.js +2 -2
- package/app/.next/server/chunks/[root-of-the-server]__a630d6ef._.js +5 -5
- package/app/.next/server/chunks/[root-of-the-server]__cb8a67d1._.js +1 -1
- package/app/.next/server/chunks/[root-of-the-server]__db2f9fe0._.js +1 -1
- package/app/.next/server/chunks/[root-of-the-server]__dc47ee64._.js +1 -1
- package/app/.next/server/chunks/[root-of-the-server]__f0f9eb3f._.js +2 -2
- package/app/.next/server/chunks/_05c48915._.js +1 -1
- package/app/.next/server/chunks/_1244636c._.js +5 -5
- package/app/.next/server/chunks/_2115d8de._.js +1 -1
- package/app/.next/server/chunks/_3ac953eb._.js +1 -1
- package/app/.next/server/chunks/_4b8fd853._.js +1 -1
- package/app/.next/server/chunks/_68683848._.js +1 -1
- package/app/.next/server/chunks/_ee9b677b._.js +1 -1
- package/app/.next/server/chunks/open-sse_translator_index_ts_f5fd0821._.js +9 -9
- package/app/.next/server/chunks/src_lib_a886ee1f._.js +1 -1
- package/app/.next/server/chunks/src_shared_validation_schemas_ts_4e63863a._.js +1 -1
- package/app/.next/server/chunks/ssr/[root-of-the-server]__9affb65e._.js +1 -1
- package/app/.next/server/chunks/ssr/[root-of-the-server]__a6942102._.js +1 -1
- package/app/.next/server/chunks/ssr/_5a9cd299._.js +1 -1
- package/app/.next/server/chunks/ssr/src_d3225e36._.js +1 -1
- package/app/.next/server/chunks/ssr/src_i18n_messages_zh-CN_json_f4112d90._.js +1 -1
- package/app/.next/server/pages/500.html +2 -2
- 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/02afac1b585d8219.css +1 -0
- package/app/.next/static/chunks/{d3cb88d181c61235.js → 4bed5b394f9dece9.js} +1 -1
- package/app/.next/static/chunks/{4f099d0f5b0f00d6.js → b5cc103e16794392.js} +1 -1
- package/app/.next/static/chunks/d19ab4efcaddd1db.js +1 -0
- package/app/CHANGELOG.md +20 -0
- package/app/docs/openapi.yaml +1 -1
- package/app/open-sse/executors/kiro.ts +5 -2
- package/app/open-sse/handlers/chatCore.ts +11 -3
- package/app/open-sse/translator/helpers/toolCallHelper.ts +58 -15
- package/app/open-sse/translator/index.ts +10 -3
- package/app/open-sse/utils/stream.ts +129 -19
- package/app/open-sse/utils/usageTracking.ts +3 -1
- package/app/package-lock.json +2 -2
- package/app/package.json +1 -1
- package/app/src/app/(dashboard)/dashboard/providers/[id]/page.tsx +22 -0
- package/app/src/app/api/keys/[id]/route.ts +26 -4
- package/app/src/app/api/provider-models/route.ts +3 -1
- package/app/src/i18n/messages/zh-CN.json +862 -787
- package/app/src/lib/db/models.ts +25 -0
- package/app/src/lib/usage/callLogs.ts +6 -2
- package/app/src/shared/components/RequestLoggerDetail.tsx +10 -10
- package/app/src/shared/validation/schemas.ts +1 -0
- package/app/src/sse/handlers/chat.ts +8 -3
- package/package.json +1 -1
- package/app/.next/static/chunks/194dbd564ba7150b.css +0 -1
- package/app/.next/static/chunks/3f3d822837a5ff5f.js +0 -1
- /package/app/.next/static/{Y1ARupD8_nbYoMt6WYrBO → JoLoKHY_9DVANe7Qs4D0K}/_buildManifest.js +0 -0
- /package/app/.next/static/{Y1ARupD8_nbYoMt6WYrBO → JoLoKHY_9DVANe7Qs4D0K}/_clientMiddlewareManifest.json +0 -0
- /package/app/.next/static/{Y1ARupD8_nbYoMt6WYrBO → JoLoKHY_9DVANe7Qs4D0K}/_ssgManifest.js +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,804730,t=>{t.v({name:"omniroute",version:"2.8.
|
|
1
|
+
(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,804730,t=>{t.v({name:"omniroute",version:"2.8.1",description:"Smart AI Router with auto fallback — route to FREE & cheap models, zero downtime. Works with Cursor, Cline, Claude Desktop, Codex, and any OpenAI-compatible tool.",type:"module",bin:{omniroute:"bin/omniroute.mjs","omniroute-reset-password":"bin/reset-password.mjs"},files:["bin/","app/","open-sse/mcp-server/","src/shared/contracts/","scripts/postinstall.mjs","scripts/native-binary-compat.mjs","README.md","LICENSE"],workspaces:["open-sse"],engines:{node:">=18.0.0 <24.0.0"},keywords:["ai","router","proxy","openai","claude","anthropic","gemini","fallback","cursor","cline","codex","llm","auto-fallback"],license:"MIT",author:"diegosouzapw",repository:{type:"git",url:"https://github.com/diegosouzapw/OmniRoute"},homepage:"https://omniroute.online",scripts:{dev:"node scripts/run-next.mjs dev",build:"next build","build:cli":"node scripts/prepublish.mjs",start:"node scripts/run-next.mjs start",lint:"eslint .","electron:dev":'concurrently "npm run dev" "wait-on http://localhost:20128 && cd electron && npm run dev"',"electron:build":"npm run build && cd electron && npm run build","electron:build:win":"npm run build && cd electron && npm run build:win","electron:build:mac":"npm run build && cd electron && npm run build:mac","electron:build:linux":"npm run build && cd electron && npm run build:linux",test:"node --import tsx/esm --test tests/unit/*.test.mjs","test:unit":"node --import tsx/esm --test tests/unit/*.test.mjs","test:plan3":"node --import tsx/esm --test tests/unit/plan3-p0.test.mjs","test:fixes":"node --import tsx/esm --test tests/unit/fixes-p1.test.mjs","test:security":"node --import tsx/esm --test tests/unit/security-fase01.test.mjs","check:cycles":"node scripts/check-cycles.mjs","check:route-validation:t06":"node scripts/check-route-validation.mjs","check:any-budget:t11":"node scripts/check-t11-any-budget.mjs","check:docs-sync":"node scripts/check-docs-sync.mjs","typecheck:core":"tsc --pretty false -p tsconfig.typecheck-core.json","typecheck:noimplicit:core":"tsc --pretty false -p tsconfig.typecheck-noimplicit-core.json","test:integration":"node --import tsx/esm --test tests/integration/*.test.mjs","test:e2e":"node scripts/run-playwright-tests.mjs test tests/e2e/*.spec.ts","test:protocols:e2e":"node scripts/run-protocol-clients-tests.mjs","test:vitest":"vitest run open-sse/mcp-server/__tests__/*.test.ts open-sse/services/autoCombo/__tests__/*.test.ts","test:ecosystem":"node scripts/run-ecosystem-tests.mjs","test:coverage":"npx c8 --exclude=open-sse --check-coverage --lines 50 --functions 50 --branches 50 node --import tsx/esm --test tests/unit/*.test.mjs","test:all":"npm run test:unit && npm run test:vitest && npm run test:ecosystem && npm run test:e2e",check:"npm run lint && npm run test",prepublishOnly:"npm run build:cli",postinstall:"node scripts/postinstall.mjs",prepare:"husky","system-info":"node scripts/system-info.mjs"},dependencies:{"@modelcontextprotocol/sdk":"^1.27.1","@monaco-editor/react":"^4.7.0",bcryptjs:"^3.0.3","better-sqlite3":"^12.6.2",bottleneck:"^2.19.5",dompurify:"^3.3.2",express:"^5.2.1","fetch-socks":"^1.3.2","http-proxy-middleware":"^3.0.5","https-proxy-agent":"^8.0.0",jose:"^6.1.3",lowdb:"^7.0.1","monaco-editor":"^0.55.1",next:"^16.1.6","next-intl":"^4.8.3","node-machine-id":"^1.1.12",open:"^11.0.0",ora:"^9.1.0",pino:"^10.3.1","pino-pretty":"^13.1.3",react:"19.2.4","react-dom":"19.2.4",recharts:"^3.7.0",selfsigned:"^5.5.0",tsx:"^4.21.0",undici:"^7.19.2",uuid:"^13.0.0","wreq-js":"^2.0.1",zod:"^4.3.6",zustand:"^5.0.10","@swc/helpers":"0.5.19"},devDependencies:{"@playwright/test":"^1.58.2","@tailwindcss/postcss":"^4.1.18","@types/bcryptjs":"^3.0.0","@types/better-sqlite3":"^7.6.13","@types/node":"^25.2.3","@types/react":"^19.2.14","@types/react-dom":"^19.2.3",concurrently:"^9.2.1","cross-env":"^10.1.0",eslint:"^9.39.2","eslint-config-next":"16.1.6",husky:"^9.1.7","lint-staged":"^16.2.7",prettier:"^3.8.1",tailwindcss:"^4",typescript:"^5.9.3","typescript-eslint":"^8.56.0",vitest:"^4.0.18","wait-on":"^9.0.4"},"lint-staged":{"*.{js,jsx,ts,tsx,mjs}":["prettier --write","eslint --fix --no-error-on-unmatched-pattern"],"*.{json,md,yml,yaml,css}":["prettier --write"]},pnpm:{onlyBuiltDependencies:["@parcel/watcher","@swc/core","better-sqlite3","esbuild","omniroute","sharp"]}})},175696,t=>{"use strict";var e=t.i(861745),s=t.i(843476);function n({locale:t,...n}){if(!t)throw Error(void 0);return(0,s.jsx)(e.IntlProvider,{locale:t,...n})}t.s(["default",()=>n])}]);
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,710864,e=>{"use strict";var t=e.i(843476),a=e.i(271645),r=e.i(627949),s=e.i(745009),i=e.i(618566),l=e.i(522016),o=e.i(657688),n=e.i(948148);e.i(565650);var d=e.i(11477),c=e.i(474078),p=e.i(628029),u=e.i(339971),m=e.i(87855),x=e.i(454149),h=e.i(116016),h=h,f=e.i(567955),f=f,g=e.i(419947),g=g,b=e.i(148943),y=e.i(961430),v=e.i(105370),j=e.i(623249);e.i(313705);var N=e.i(25230),C=e.i(556938);function k(e){let t=e&&"object"==typeof e&&!Array.isArray(e)?e:{};return{use5h:"boolean"!=typeof t.use5h||t.use5h,useWeekly:"boolean"!=typeof t.useWeekly||t.useWeekly}}function w(){let e=(0,i.useParams)(),s=(0,i.useRouter)(),p=e.id,[u,b]=(0,a.useState)([]),[y,w]=(0,a.useState)(!0),[P,E]=(0,a.useState)(null),[I,U]=(0,a.useState)(!1),[L,_]=(0,a.useState)(!1),[K,F]=(0,a.useState)(!1),[B,q]=(0,a.useState)(!1),[z,W]=(0,a.useState)(null),[J,V]=(0,a.useState)(null),[H,Y]=(0,a.useState)({}),[G,Q]=(0,a.useState)(!1),{copied:X,copy:Z}=(0,C.useCopyToClipboard)(),ee=(0,n.useTranslations)("providers"),et=(0,r.useNotificationStore)(),ea=(0,a.useRef)(!1),er=(0,a.useRef)(!1),[es,ei]=(0,a.useState)(null),[el,eo]=(0,a.useState)(null),[en,ed]=(0,a.useState)(!1),[ec,ep]=(0,a.useState)(!1),[eu,em]=(0,a.useState)({current:0,total:0,phase:"idle",status:"",logs:[],error:"",importedCount:0}),ex=P?{id:P.id,name:P.name||("anthropic-compatible"===P.type?ee("anthropicCompatibleName"):ee("openaiCompatibleName")),color:"anthropic-compatible"===P.type?"#D97757":"#10A37F",textIcon:"anthropic-compatible"===P.type?"AC":"OC",apiType:P.apiType,baseUrl:P.baseUrl,type:P.type}:j.FREE_PROVIDERS[p]||j.OAUTH_PROVIDERS[p]||j.APIKEY_PROVIDERS[p],eh=!!j.FREE_PROVIDERS[p]||!!j.OAUTH_PROVIDERS[p],ef=(0,N.getModelsByProviderId)(p),eg=(0,j.getProviderAlias)(p),eb=(0,j.isOpenAICompatibleProvider)(p),ey=(0,j.isAnthropicCompatibleProvider)(p),ev=eb||ey,ej=p.endsWith("-search"),eN=ev?p:eg,eC=ev?P?.prefix||p:eg,ek=(0,a.useCallback)(async()=>{try{let e=await fetch("/api/models/alias"),t=await e.json();e.ok&&Y(t.aliases||{})}catch(e){console.log("Error fetching aliases:",e)}},[]),ew=(0,a.useCallback)(async()=>{try{let[e,t]=await Promise.all([fetch("/api/providers",{cache:"no-store"}),fetch("/api/provider-nodes",{cache:"no-store"})]),a=await e.json(),r=await t.json();if(e.ok){let e=(a.connections||[]).filter(e=>e.provider===p);b(e)}if(t.ok){let e=(r.nodes||[]).find(e=>e.id===p)||null;if(!e&&ev)for(let t=0;t<3;t+=1){await new Promise(e=>setTimeout(e,150));let t=await fetch("/api/provider-nodes",{cache:"no-store"});if(t.ok&&(e=((await t.json()).nodes||[]).find(e=>e.id===p)||null))break}E(e)}}catch(e){console.log("Error fetching connections:",e)}finally{w(!1)}},[p,ev]),eS=async e=>{try{let t=await fetch(`/api/provider-nodes/${p}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),a=await t.json();t.ok&&(E(a.node),await ew(),q(!1))}catch(e){console.log("Error updating provider node:",e)}};(0,a.useEffect)(()=>{ew(),ek(),fetch("/api/settings/proxy").then(e=>e.ok?e.json():null).then(e=>eo(e)).catch(()=>{})},[ew,ek]),(0,a.useEffect)(()=>{y||0!==u.length||!ex||ev||ea.current||er.current||(ea.current=!0,eh?U(!0):_(!0))},[y]);let eT=async(e,t,a=eg)=>{let r=`${a}/${e}`;try{let e=await fetch("/api/models/alias",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:r,alias:t})});if(e.ok)await ek();else{let t=await e.json();alert(t.error||ee("failedSetAlias"))}}catch(e){console.log("Error setting alias:",e)}},eP=async e=>{try{(await fetch(`/api/models/alias?alias=${encodeURIComponent(e)}`,{method:"DELETE"})).ok&&await ek()}catch(e){console.log("Error deleting alias:",e)}},eA=async e=>{if(confirm(ee("deleteConnectionConfirm")))try{(await fetch(`/api/providers/${e}`,{method:"DELETE"})).ok&&b(u.filter(t=>t.id!==e))}catch(e){console.log("Error deleting connection:",e)}},eR=(0,a.useCallback)(()=>{ew(),U(!1)},[ew]),eE=async e=>{try{let t=await fetch("/api/providers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:p,...e})});if(t.ok)return await ew(),_(!1),null;let a=await t.json().catch(()=>({}));return a.error?.message||a.error||ee("failedSaveConnection")}catch(e){return console.log("Error saving connection:",e),ee("failedSaveConnectionRetry")}},eI=async e=>{try{let t=await fetch(`/api/providers/${z.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(t.ok)return await ew(),F(!1),null;let a=await t.json().catch(()=>({}));return a.error?.message||a.error||ee("failedSaveConnection")}catch(e){return console.log("Error updating connection:",e),ee("failedSaveConnectionRetry")}},eO=async(e,t)=>{try{(await fetch(`/api/providers/${e}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({isActive:t})})).ok&&b(a=>a.map(a=>a.id===e?{...a,isActive:t}:a))}catch(e){console.log("Error updating connection status:",e)}},eM=async(e,t)=>{try{(await fetch("/api/rate-limits",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({connectionId:e,enabled:t})})).ok&&b(a=>a.map(a=>a.id===e?{...a,rateLimitProtection:t}:a))}catch(e){console.error("Error toggling rate limit:",e)}},eU=async(e,t,a)=>{try{let r=u.find(t=>t.id===e);if(!r)return;let s=r.providerSpecificData&&"object"==typeof r.providerSpecificData?r.providerSpecificData:{},i=s.codexLimitPolicy&&"object"==typeof s.codexLimitPolicy?s.codexLimitPolicy:{},l={...k(i),[t]:a},o=await fetch(`/api/providers/${e}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerSpecificData:{...s,codexLimitPolicy:l}})});if(!o.ok){let e=await o.json().catch(()=>({}));et.error(e.error||"Failed to update Codex limit policy");return}b(t=>t.map(t=>t.id===e?{...t,providerSpecificData:{...t.providerSpecificData||{},codexLimitPolicy:l}}:t)),et.success("Codex limit policy updated")}catch(e){console.error("Error toggling Codex quota policy:",e),et.error("Failed to update Codex limit policy")}},eD=async e=>{if(e&&!J){V(e);try{let t=await fetch(`/api/providers/${e}/test`,{method:"POST"});if(!t.ok){let e=await t.json().catch(()=>({}));alert(e.error||ee("failedRetestConnection"));return}await ew()}catch(e){console.error("Error retesting connection:",e)}finally{V(null)}}},[e$,eL]=(0,a.useState)(null),e_=async e=>{if(!e$){eL(e);try{let t=await fetch(`/api/providers/${e}/refresh`,{method:"POST"}),a=await t.json().catch(()=>({}));t.ok&&a.success?(et.success(ee("tokenRefreshed")),await ew()):et.error(a.error||ee("tokenRefreshFailed"))}catch(e){console.error("Error refreshing token:",e),et.error(ee("tokenRefreshFailed"))}finally{eL(null)}}},eK=async(e,t)=>{if(e&&t)try{let a=t.priority,r=e.priority;a===r&&(a=u.indexOf(e)>u.indexOf(t)?t.priority-.5:t.priority+.5),await Promise.all([fetch(`/api/providers/${e.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({priority:a})}),fetch(`/api/providers/${t.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({priority:r})})]),await ew()}catch(e){console.log("Error swapping priority:",e)}},eF=async()=>{if(en)return;let e=u.find(e=>!1!==e.isActive);if(e){ed(!0),ep(!0),em({current:0,total:0,phase:"fetching",status:ee("fetchingModels"),logs:[],error:"",importedCount:0});try{let t=await fetch(`/api/providers/${e.id}/models`),a=await t.json();if(!t.ok)return void em(e=>({...e,phase:"error",status:ee("failedFetchModels"),error:a.error||ee("failedImportModels")}));let r=a.models||[];if(0===r.length)return void em(e=>({...e,phase:"done",status:ee("noModelsFound"),logs:[ee("noModelsReturnedFromEndpoint")]}));em(e=>({...e,phase:"importing",total:r.length,status:ee("importingModelsProgress",{current:0,total:r.length}),logs:[ee("foundModelsStartingImport",{count:r.length})]}));let s=0;for(let e=0;e<r.length;e++){let t=r[e],a=t.id||t.name||t.model;if(!a)continue;let i=a.split("/"),l=i[i.length-1];em(t=>({...t,current:e+1,status:ee("importingModelsProgress",{current:e+1,total:r.length}),logs:[...t.logs,ee("importingModelById",{modelId:a})]})),await fetch("/api/provider-models",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:p,modelId:a,modelName:t.name||a,source:"imported"})}),H[l]||await eT(a,l,eN),s+=1}await ek(),em(e=>({...e,phase:"done",current:r.length,status:s>0?ee("importSuccessCount",{count:s}):ee("noNewModelsAddedExisting"),logs:[...e.logs,s>0?ee("importDoneCount",{count:s}):ee("noNewModelsAdded")],importedCount:s})),s>0&&setTimeout(()=>{window.location.reload()},2e3)}catch(e){console.log("Error importing models:",e),em(t=>({...t,phase:"error",status:ee("importFailed"),error:e instanceof Error?e.message:ee("unexpectedErrorOccurred")}))}finally{ed(!1)}}},eB=async(e,t)=>{ep(!0),em({current:0,total:0,phase:"fetching",status:ee("fetchingModels"),logs:[],error:"",importedCount:0});try{let a=(await e()).models||[];if(0===a.length)return void em(e=>({...e,phase:"done",status:ee("noModelsFound"),logs:[ee("noModelsReturnedFromEndpoint")]}));em(e=>({...e,phase:"importing",total:a.length,status:ee("importingModelsProgress",{current:0,total:a.length}),logs:[ee("foundModelsStartingImport",{count:a.length})]}));let r=0;for(let e=0;e<a.length;e++){let s=a[e],i=s.id||s.name||s.model;i&&(em(t=>({...t,current:e+1,status:ee("importingModelsProgress",{current:e+1,total:a.length}),logs:[...t.logs,ee("importingModelById",{modelId:i})]})),await t(s)&&(r+=1))}em(e=>({...e,phase:"done",current:a.length,status:r>0?ee("importSuccessCount",{count:r}):ee("noNewModelsAdded"),logs:[...e.logs,r>0?ee("importDoneCount",{count:r}):ee("noNewModelsAdded")],importedCount:r})),r>0&&setTimeout(()=>{window.location.reload()},2e3)}catch(e){console.log("Error importing models:",e),em(t=>({...t,phase:"error",status:ee("importFailed"),error:e instanceof Error?e.message:ee("unexpectedErrorOccurred")}))}},eq=u.some(e=>!1!==e.isActive);return y?(0,t.jsxs)("div",{className:"flex flex-col gap-8",children:[(0,t.jsx)(x.CardSkeleton,{}),(0,t.jsx)(x.CardSkeleton,{})]}):ex?(0,t.jsxs)("div",{className:"flex flex-col gap-8",children:[(0,t.jsxs)("div",{children:[(0,t.jsxs)(l.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,t.jsx)("span",{className:"material-symbols-outlined text-lg",children:"arrow_back"}),ee("backToProviders")]}),(0,t.jsxs)("div",{className:"flex items-center gap-4",children:[(0,t.jsx)("div",{className:"rounded-lg flex items-center justify-center",style:{backgroundColor:`${ex.color}15`},children:G?(0,t.jsx)("span",{className:"text-sm font-bold",style:{color:ex.color},children:ex.textIcon||ex.id.slice(0,2).toUpperCase()}):(0,t.jsx)(o.default,{src:eb&&ex.apiType?"responses"===ex.apiType?"/providers/oai-r.png":"/providers/oai-cc.png":ey?"/providers/anthropic-m.png":`/providers/${ex.id}.png`,alt:ex.name,width:48,height:48,className:"object-contain rounded-lg max-w-[48px] max-h-[48px]",sizes:"48px",onError:()=>Q(!0)})}),(0,t.jsxs)("div",{children:[ex.website?(0,t.jsxs)("a",{href:ex.website,target:"_blank",rel:"noopener noreferrer",className:"text-3xl font-semibold tracking-tight hover:underline inline-flex items-center gap-2",style:{color:ex.color},children:[ex.name,(0,t.jsx)("span",{className:"material-symbols-outlined text-lg opacity-60",children:"open_in_new"})]}):(0,t.jsx)("h1",{className:"text-3xl font-semibold tracking-tight",children:ex.name}),(0,t.jsx)("p",{className:"text-text-muted",children:ee("connectionCountLabel",{count:u.length})})]})]})]}),ev&&P&&(0,t.jsxs)(d.Card,{children:[(0,t.jsxs)("div",{className:"flex items-center justify-between mb-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h2",{className:"text-lg font-semibold",children:ey?ee("anthropicCompatibleDetails"):ee("openaiCompatibleDetails")}),(0,t.jsxs)("p",{className:"text-sm text-text-muted",children:[ey?ee("messagesApi"):"responses"===P.apiType?ee("responsesApi"):ee("chatCompletions")," ","· ",(P.baseUrl||"").replace(/\/$/,""),"/",ey?ee("messagesPath"):"responses"===P.apiType?ee("responsesPath"):ee("chatCompletionsPath")]})]}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(c.Button,{size:"sm",icon:"add",onClick:()=>_(!0),disabled:u.length>0,children:ee("add")}),(0,t.jsx)(c.Button,{size:"sm",variant:"secondary",icon:"edit",onClick:()=>q(!0),children:ee("edit")}),(0,t.jsx)(c.Button,{size:"sm",variant:"secondary",icon:"delete",onClick:async()=>{if(confirm(ee("deleteCompatibleNodeConfirm",{type:ey?ee("anthropic"):ee("openai")})))try{(await fetch(`/api/provider-nodes/${p}`,{method:"DELETE"})).ok&&s.push("/dashboard/providers")}catch(e){console.log("Error deleting provider node:",e)}},children:ee("delete")})]})]}),u.length>0&&(0,t.jsx)("p",{className:"text-sm text-text-muted",children:ee("singleConnectionPerCompatible")})]}),(0,t.jsxs)(d.Card,{children:[(0,t.jsxs)("div",{className:"flex items-center justify-between mb-4",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)("h2",{className:"text-lg font-semibold",children:ee("connections")}),(0,t.jsxs)("button",{onClick:()=>ei({level:"provider",id:p,label:ex?.name||p}),className:`inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium transition-all ${el?.providers?.[p]?"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:el?.providers?.[p]?ee("providerProxyTitleConfigured",{host:el.providers[p].host||ee("configured")}):ee("providerProxyConfigureHint"),children:[(0,t.jsx)("span",{className:"material-symbols-outlined text-[14px]",children:"vpn_lock"}),el?.providers?.[p]&&el.providers[p].host||ee("providerProxy")]})]}),ev?0===u.length&&(0,t.jsx)(c.Button,{size:"sm",icon:"add",onClick:()=>_(!0),children:ee("add")}):(0,t.jsx)(c.Button,{size:"sm",icon:"add",onClick:()=>eh?U(!0):_(!0),children:ee("add")})]}),0===u.length?(0,t.jsxs)("div",{className:"text-center py-12",children:[(0,t.jsx)("div",{className:"inline-flex items-center justify-center w-16 h-16 rounded-full bg-primary/10 text-primary mb-4",children:(0,t.jsx)("span",{className:"material-symbols-outlined text-[32px]",children:eh?"lock":"key"})}),(0,t.jsx)("p",{className:"text-text-main font-medium mb-1",children:ee("noConnectionsYet")}),(0,t.jsx)("p",{className:"text-sm text-text-muted mb-4",children:ee("addFirstConnectionHint")}),!ev&&(0,t.jsx)(c.Button,{icon:"add",onClick:()=>eh?U(!0):_(!0),children:ee("addConnection")})]}):(0,t.jsx)("div",{className:"flex flex-col divide-y divide-black/[0.03] dark:divide-white/[0.03]",children:u.sort((e,t)=>(e.priority||0)-(t.priority||0)).map((e,a)=>(0,t.jsx)(O,{connection:e,isOAuth:eh,isFirst:0===a,isLast:a===u.length-1,onMoveUp:()=>eK(e,u[a-1]),onMoveDown:()=>eK(e,u[a+1]),onToggleActive:t=>eO(e.id,t),onToggleRateLimit:t=>eM(e.id,t),isCodex:"codex"===p,onToggleCodex5h:t=>eU(e.id,"use5h",t),onToggleCodexWeekly:t=>eU(e.id,"useWeekly",t),onRetest:()=>eD(e.id),isRetesting:J===e.id,onEdit:()=>{W(e),F(!0)},onDelete:()=>eA(e.id),onReauth:eh?()=>U(!0):void 0,onRefreshToken:eh?()=>e_(e.id):void 0,isRefreshing:e$===e.id,onProxy:()=>ei({level:"key",id:e.id,label:e.name||e.email||e.id}),hasProxy:!!(el?.keys?.[e.id]||el?.providers?.[p]||el?.global),proxySource:el?.keys?.[e.id]?"key":el?.providers?.[p]?"provider":el?.global?"global":null,proxyHost:(el?.keys?.[e.id]||el?.providers?.[p]||el?.global)?.host||null},e.id))})]}),!ej&&(0,t.jsxs)(d.Card,{children:[(0,t.jsx)("h2",{className:"text-lg font-semibold mb-4",children:ee("availableModels")}),(()=>{if(ev)return(0,t.jsx)(R,{providerStorageAlias:eN,providerDisplayAlias:eC,modelAliases:H,copied:X,onCopy:Z,onSetAlias:eT,onDeleteAlias:eP,connections:u,isAnthropic:ey,onImportWithProgress:eB});if(ex.passthroughModels)return(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 mb-4",children:[(0,t.jsx)(c.Button,{size:"sm",variant:"secondary",icon:"download",onClick:eF,disabled:!eq||en,children:en?ee("importingModels"):ee("importFromModels")}),!eq&&(0,t.jsx)("span",{className:"text-xs text-text-muted",children:ee("addConnectionToImport")})]}),(0,t.jsx)(T,{providerAlias:eg,modelAliases:H,copied:X,onCopy:Z,onSetAlias:eT,onDeleteAlias:eP})]});let e=(0,t.jsxs)("div",{className:"flex items-center gap-2 mb-4",children:[(0,t.jsx)(c.Button,{size:"sm",variant:"secondary",icon:"download",onClick:eF,disabled:!eq||en,children:en?ee("importingModels"):ee("importFromModels")}),!eq&&(0,t.jsx)("span",{className:"text-xs text-text-muted",children:ee("addConnectionToImport")})]});return 0===ef.length?(0,t.jsxs)("div",{children:[e,(0,t.jsx)("p",{className:"text-sm text-text-muted",children:ee("noModelsConfigured")})]}):(0,t.jsxs)("div",{children:[e,(0,t.jsx)("div",{className:"flex flex-wrap gap-3",children:ef.map(e=>{let a=`${eN}/${e.id}`,r=`${p}/${e.id}`,s=Object.entries(H).find(([,e])=>e===a||e===r)?.[0];return(0,t.jsx)(S,{model:e,fullModel:`${eC}/${e.id}`,alias:s,copied:X,onCopy:Z,onSetAlias:t=>eT(e.id,t,eN),onDeleteAlias:()=>eP(s)},e.id)})})]})})(),!ev&&(0,t.jsx)(A,{providerId:p,providerAlias:eC,copied:X,onCopy:Z})]}),ej&&(0,t.jsxs)(d.Card,{children:[(0,t.jsx)("h2",{className:"text-lg font-semibold mb-4",children:ee("searchProvider")||"Search Provider"}),(0,t.jsx)("p",{className:"text-sm text-text-muted",children:ee("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"===p&&(0,t.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,t.jsx)("span",{className:"material-symbols-outlined text-sm text-blue-400",children:"link"}),(0,t.jsxs)("p",{className:"text-xs text-blue-300",children:["Uses the same API key as ",(0,t.jsx)("strong",{children:"Perplexity"})," (chat provider). If you already have Perplexity configured, no additional setup is needed."]})]})]}),"kiro"===p?(0,t.jsx)(f.default,{isOpen:I,providerInfo:ex,onSuccess:eR,onClose:()=>{er.current=!0,U(!1)}}):"cursor"===p?(0,t.jsx)(g.default,{isOpen:I,onSuccess:eR,onClose:()=>{er.current=!0,U(!1)}}):(0,t.jsx)(h.default,{isOpen:I,provider:p,providerInfo:ex,onSuccess:eR,onClose:()=>{er.current=!0,U(!1)}}),(0,t.jsx)(M,{isOpen:L,provider:p,providerName:ex.name,isCompatible:ev,isAnthropic:ey,onSave:eE,onClose:()=>_(!1)}),(0,t.jsx)(D,{isOpen:K,connection:z,onSave:eI,onClose:()=>F(!1)}),ev&&(0,t.jsx)($,{isOpen:B,node:P,onSave:eS,onClose:()=>q(!1),isAnthropic:ey}),es&&(0,t.jsx)(v.ProxyConfigModal,{isOpen:!!es,onClose:()=>ei(null),level:es.level,levelId:es.id,levelLabel:es.label}),(0,t.jsx)(m.Modal,{isOpen:ec,onClose:()=>{("done"===eu.phase||"error"===eu.phase)&&ep(!1)},title:ee("importingModelsTitle"),size:"md",closeOnOverlay:!1,showCloseButton:"done"===eu.phase||"error"===eu.phase,children:(0,t.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3",children:["fetching"===eu.phase&&(0,t.jsx)("span",{className:"material-symbols-outlined text-primary animate-spin",children:"progress_activity"}),"importing"===eu.phase&&(0,t.jsx)("span",{className:"material-symbols-outlined text-primary animate-spin",children:"progress_activity"}),"done"===eu.phase&&(0,t.jsx)("span",{className:"material-symbols-outlined text-green-500",children:"check_circle"}),"error"===eu.phase&&(0,t.jsx)("span",{className:"material-symbols-outlined text-red-500",children:"error"}),(0,t.jsx)("span",{className:"text-sm font-medium text-text-main",children:eu.status})]}),("importing"===eu.phase||"done"===eu.phase)&&eu.total>0&&(0,t.jsxs)("div",{className:"w-full",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between mb-1",children:[(0,t.jsxs)("span",{className:"text-xs text-text-muted",children:[eu.current," / ",eu.total]}),(0,t.jsxs)("span",{className:"text-xs text-text-muted",children:[Math.round(eu.current/eu.total*100),"%"]})]}),(0,t.jsx)("div",{className:"w-full h-2.5 bg-black/10 dark:bg-white/10 rounded-full overflow-hidden",children:(0,t.jsx)("div",{className:"h-full rounded-full transition-all duration-300 ease-out",style:{width:`${eu.current/eu.total*100}%`,background:"done"===eu.phase?"linear-gradient(90deg, #22c55e, #16a34a)":"linear-gradient(90deg, var(--color-primary), var(--color-primary-hover, var(--color-primary)))"}})})]}),"fetching"===eu.phase&&(0,t.jsx)("div",{className:"w-full h-2.5 bg-black/10 dark:bg-white/10 rounded-full overflow-hidden",children:(0,t.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"===eu.phase&&eu.error&&(0,t.jsx)("div",{className:"p-3 rounded-lg bg-red-500/10 border border-red-500/20",children:(0,t.jsx)("p",{className:"text-sm text-red-400",children:eu.error})}),eu.logs.length>0&&(0,t.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,t.jsx)("div",{className:"flex flex-col gap-1",children:eu.logs.map((e,a)=>(0,t.jsx)("p",{className:`text-xs font-mono ${e.startsWith("✓")?"text-green-500 font-semibold":"text-text-muted"}`,children:e},a))})}),"done"===eu.phase&&eu.importedCount>0&&(0,t.jsx)("p",{className:"text-xs text-text-muted text-center animate-pulse",children:ee("pageAutoRefresh")})]})})]}):(0,t.jsxs)("div",{className:"text-center py-20",children:[(0,t.jsx)("p",{className:"text-text-muted",children:ee("providerNotFound")}),(0,t.jsx)(l.default,{href:"/dashboard/providers",className:"text-primary mt-4 inline-block",children:ee("backToProviders")})]})}function S({model:e,fullModel:a,alias:r,copied:s,onCopy:i,onSetAlias:l,onDeleteAlias:o}){let d=(0,n.useTranslations)("providers");return(0,t.jsxs)("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg border border-border hover:bg-sidebar/50",children:[(0,t.jsx)("span",{className:"material-symbols-outlined text-base text-text-muted",children:"smart_toy"}),(0,t.jsx)("code",{className:"text-xs text-text-muted font-mono bg-sidebar px-1.5 py-0.5 rounded",children:a}),(0,t.jsx)("button",{onClick:()=>i(a,`model-${e.id}`),className:"p-0.5 hover:bg-sidebar rounded text-text-muted hover:text-primary",title:d("copyModel"),children:(0,t.jsx)("span",{className:"material-symbols-outlined text-sm",children:s===`model-${e.id}`?"check":"content_copy"})})]})}function T({providerAlias:e,modelAliases:r,copied:s,onCopy:i,onSetAlias:l,onDeleteAlias:o}){let d=(0,n.useTranslations)("providers"),[p,u]=(0,a.useState)(""),[m,x]=(0,a.useState)(!1),h=Object.entries(r).filter(([,t])=>t.startsWith(`${e}/`)).map(([t,a])=>({modelId:a.replace(`${e}/`,""),fullModel:a,alias:t})),f=async()=>{let e;if(!p.trim()||m)return;let t=p.trim(),a=(e=t.split("/"))[e.length-1];if(r[a])return void alert(d("aliasExistsAlert",{alias:a}));x(!0);try{await l(t,a),u("")}catch(e){console.log("Error adding model:",e)}finally{x(!1)}};return(0,t.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,t.jsx)("p",{className:"text-sm text-text-muted",children:d("openRouterAnyModelHint")}),(0,t.jsxs)("div",{className:"flex items-end gap-2",children:[(0,t.jsxs)("div",{className:"flex-1",children:[(0,t.jsx)("label",{htmlFor:"new-model-input",className:"text-xs text-text-muted mb-1 block",children:d("modelIdFromOpenRouter")}),(0,t.jsx)("input",{id:"new-model-input",type:"text",value:p,onChange:e=>u(e.target.value),onKeyDown:e=>"Enter"===e.key&&f(),placeholder:d("openRouterModelPlaceholder"),className:"w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"})]}),(0,t.jsx)(c.Button,{size:"sm",icon:"add",onClick:f,disabled:!p.trim()||m,children:m?d("adding"):d("add")})]}),h.length>0&&(0,t.jsx)("div",{className:"flex flex-col gap-3",children:h.map(({modelId:e,fullModel:a,alias:r})=>(0,t.jsx)(P,{modelId:e,fullModel:a,copied:s,onCopy:i,onDeleteAlias:()=>o(r)},a))})]})}function P({modelId:e,fullModel:a,copied:r,onCopy:s,onDeleteAlias:i}){let l=(0,n.useTranslations)("providers");return(0,t.jsxs)("div",{className:"flex items-center gap-3 p-3 rounded-lg border border-border hover:bg-sidebar/50",children:[(0,t.jsx)("span",{className:"material-symbols-outlined text-base text-text-muted",children:"smart_toy"}),(0,t.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,t.jsx)("p",{className:"text-sm font-medium truncate",children:e}),(0,t.jsxs)("div",{className:"flex items-center gap-1 mt-1",children:[(0,t.jsx)("code",{className:"text-xs text-text-muted font-mono bg-sidebar px-1.5 py-0.5 rounded",children:a}),(0,t.jsx)("button",{onClick:()=>s(a,`model-${e}`),className:"p-0.5 hover:bg-sidebar rounded text-text-muted hover:text-primary",title:l("copyModel"),children:(0,t.jsx)("span",{className:"material-symbols-outlined text-sm",children:r===`model-${e}`?"check":"content_copy"})})]})]}),(0,t.jsx)("button",{onClick:i,className:"p-1 hover:bg-red-50 rounded text-red-500",title:l("removeModel"),children:(0,t.jsx)("span",{className:"material-symbols-outlined text-sm",children:"delete"})})]})}function A({providerId:e,providerAlias:s,copied:i,onCopy:l}){let o=(0,n.useTranslations)("providers"),d=(0,r.useNotificationStore)(),[p,u]=(0,a.useState)([]),[m,x]=(0,a.useState)(""),[h,f]=(0,a.useState)(""),[g,b]=(0,a.useState)("chat-completions"),[y,v]=(0,a.useState)(["chat"]),[j,N]=(0,a.useState)(!1),[C,k]=(0,a.useState)(!0),[w,S]=(0,a.useState)(null),[T,P]=(0,a.useState)("chat-completions"),[A,R]=(0,a.useState)(["chat"]),[E,I]=(0,a.useState)(!1),[O,M]=(0,a.useState)(null),U=(0,a.useCallback)(async()=>{try{let t=await fetch(`/api/provider-models?provider=${encodeURIComponent(e)}`);if(t.ok){let e=await t.json();u(e.models||[])}}catch(e){console.error("Failed to fetch custom models:",e)}finally{k(!1)}},[e]);(0,a.useEffect)(()=>{U()},[U]);let D=async()=>{if(m.trim()&&!j){N(!0);try{(await fetch("/api/provider-models",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:e,modelId:m.trim(),modelName:h.trim()||void 0,apiFormat:g,supportedEndpoints:y})})).ok&&(x(""),f(""),b("chat-completions"),v(["chat"]),await U())}catch(e){console.error("Failed to add custom model:",e)}finally{N(!1)}}},$=async t=>{try{await fetch(`/api/provider-models?provider=${encodeURIComponent(e)}&model=${encodeURIComponent(t)}`,{method:"DELETE"}),await U()}catch(e){console.error("Failed to remove custom model:",e)}},L=()=>{S(null),P("chat-completions"),R(["chat"]),I(!1),M(null)},_=async t=>{if(w&&w===t){if(!A.length)return void d.error("Select at least one supported endpoint");M(t);try{let a=p.find(e=>e.id===t);if(!(await fetch("/api/provider-models",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:e,modelId:t,modelName:a?.name||t,source:a?.source||"manual",apiFormat:T,supportedEndpoints:A,normalizeToolCallId:E})})).ok)throw Error("Failed to save model endpoint settings");await U(),d.success("Saved model endpoint settings"),L()}catch(e){console.error("Failed to save custom model:",e),d.error("Failed to save model endpoint settings")}finally{M(null)}}};return(0,t.jsxs)("div",{className:"mt-6 pt-6 border-t border-border",children:[(0,t.jsxs)("h3",{className:"text-sm font-semibold mb-3 flex items-center gap-2",children:[(0,t.jsx)("span",{className:"material-symbols-outlined text-base text-primary",children:"tune"}),o("customModels")]}),(0,t.jsx)("p",{className:"text-xs text-text-muted mb-3",children:o("customModelsHint")}),(0,t.jsxs)("div",{className:"flex flex-col gap-3 mb-3",children:[(0,t.jsxs)("div",{className:"flex items-end gap-2",children:[(0,t.jsxs)("div",{className:"flex-1",children:[(0,t.jsx)("label",{htmlFor:"custom-model-id",className:"text-xs text-text-muted mb-1 block",children:o("modelId")}),(0,t.jsx)("input",{id:"custom-model-id",type:"text",value:m,onChange:e=>x(e.target.value),onKeyDown:e=>"Enter"===e.key&&D(),placeholder:o("customModelPlaceholder"),className:"w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"})]}),(0,t.jsxs)("div",{className:"w-40",children:[(0,t.jsx)("label",{htmlFor:"custom-model-name",className:"text-xs text-text-muted mb-1 block",children:o("displayName")}),(0,t.jsx)("input",{id:"custom-model-name",type:"text",value:h,onChange:e=>f(e.target.value),onKeyDown:e=>"Enter"===e.key&&D(),placeholder:o("optional"),className:"w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"})]}),(0,t.jsx)(c.Button,{size:"sm",icon:"add",onClick:D,disabled:!m.trim()||j,children:j?o("adding"):o("add")})]}),(0,t.jsxs)("div",{className:"flex items-end gap-4 flex-wrap",children:[(0,t.jsxs)("div",{className:"w-48",children:[(0,t.jsx)("label",{htmlFor:"custom-api-format",className:"text-xs text-text-muted mb-1 block",children:"API Format"}),(0,t.jsxs)("select",{id:"custom-api-format",value:g,onChange:e=>b(e.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,t.jsx)("option",{value:"chat-completions",children:"Chat Completions"}),(0,t.jsx)("option",{value:"responses",children:"Responses API"})]})]}),(0,t.jsxs)("div",{className:"flex-1",children:[(0,t.jsx)("span",{className:"text-xs text-text-muted mb-1 block",children:"Supported Endpoints"}),(0,t.jsx)("div",{className:"flex items-center gap-3",children:["chat","embeddings","images","audio"].map(e=>(0,t.jsxs)("label",{className:"flex items-center gap-1.5 text-xs text-text-main cursor-pointer",children:[(0,t.jsx)("input",{type:"checkbox",checked:y.includes(e),onChange:t=>{t.target.checked?v(t=>[...t,e]):v(t=>t.filter(t=>t!==e))},className:"rounded border-border"}),"chat"===e?"💬 Chat":"embeddings"===e?"📐 Embeddings":"images"===e?"🖼️ Images":"🔊 Audio"]},e))})]})]})]}),C?(0,t.jsx)("p",{className:"text-xs text-text-muted",children:o("loading")}):p.length>0?(0,t.jsx)("div",{className:"flex flex-col gap-2",children:p.map(e=>{let a=`${s}/${e.id}`,r=`custom-${e.id}`;return(0,t.jsxs)("div",{className:"flex items-center gap-3 p-3 rounded-lg border border-border hover:bg-sidebar/50",children:[(0,t.jsx)("span",{className:"material-symbols-outlined text-base text-primary",children:"tune"}),(0,t.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,t.jsx)("p",{className:"text-sm font-medium truncate",children:e.name||e.id}),(0,t.jsxs)("div",{className:"flex items-center gap-1 mt-1 flex-wrap",children:[(0,t.jsx)("code",{className:"text-xs text-text-muted font-mono bg-sidebar px-1.5 py-0.5 rounded",children:a}),(0,t.jsx)("button",{onClick:()=>l(a,r),className:"p-0.5 hover:bg-sidebar rounded text-text-muted hover:text-primary",title:o("copyModel"),children:(0,t.jsx)("span",{className:"material-symbols-outlined text-sm",children:i===r?"check":"content_copy"})}),"responses"===e.apiFormat&&(0,t.jsx)("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-blue-500/15 text-blue-400 font-medium",children:"Responses"}),e.supportedEndpoints?.includes("embeddings")&&(0,t.jsx)("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-purple-500/15 text-purple-400 font-medium",children:"📐 Embed"}),e.supportedEndpoints?.includes("images")&&(0,t.jsx)("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-amber-500/15 text-amber-400 font-medium",children:"🖼️ Images"}),e.supportedEndpoints?.includes("audio")&&(0,t.jsx)("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-green-500/15 text-green-400 font-medium",children:"🔊 Audio"}),e.normalizeToolCallId&&(0,t.jsx)("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-slate-500/15 text-slate-400 font-medium",title:"9-char tool call ID (Mistral)",children:"ID×9"})]}),w===e.id&&(0,t.jsxs)("div",{className:"mt-3 p-3 rounded-lg border border-border bg-sidebar/40",children:[(0,t.jsxs)("div",{className:"flex items-end gap-3 flex-wrap",children:[(0,t.jsxs)("div",{className:"w-44",children:[(0,t.jsx)("label",{className:"text-xs text-text-muted mb-1 block",children:"API Format"}),(0,t.jsxs)("select",{value:T,onChange:e=>P(e.target.value),className:"w-full px-2.5 py-2 text-xs border border-border rounded-lg bg-background focus:outline-none focus:border-primary",children:[(0,t.jsx)("option",{value:"chat-completions",children:"Chat Completions"}),(0,t.jsx)("option",{value:"responses",children:"Responses API"})]})]}),(0,t.jsxs)("div",{className:"flex-1 min-w-[240px]",children:[(0,t.jsx)("span",{className:"text-xs text-text-muted mb-1 block",children:"Supported Endpoints"}),(0,t.jsx)("div",{className:"flex items-center gap-3 flex-wrap",children:["chat","embeddings","images","audio"].map(e=>(0,t.jsxs)("label",{className:"flex items-center gap-1.5 text-xs text-text-main cursor-pointer",children:[(0,t.jsx)("input",{type:"checkbox",checked:A.includes(e),onChange:t=>{t.target.checked?R(t=>t.includes(e)?t:[...t,e]):R(t=>t.filter(t=>t!==e))},className:"rounded border-border"}),"chat"===e?"💬 Chat":"embeddings"===e?"📐 Embeddings":"images"===e?"🖼️ Images":"🔊 Audio"]},e))})]}),(0,t.jsxs)("label",{className:"flex items-center gap-2 text-xs text-text-main cursor-pointer",children:[(0,t.jsx)("input",{type:"checkbox",checked:E,onChange:e=>I(e.target.checked),className:"rounded border-border"}),"Normalize Tool Call ID (9 chars, Mistral)"]})]}),(0,t.jsxs)("div",{className:"mt-3 flex items-center gap-2",children:[(0,t.jsx)(c.Button,{size:"sm",onClick:()=>_(e.id),disabled:O===e.id,children:O===e.id?o("saving"):o("save")}),(0,t.jsx)(c.Button,{size:"sm",variant:"ghost",onClick:L,children:o("cancel")})]})]})]}),(0,t.jsxs)("div",{className:"flex items-center gap-1",children:[(0,t.jsx)("button",{onClick:()=>{S(e.id),P(e.apiFormat||"chat-completions"),R(Array.isArray(e.supportedEndpoints)&&e.supportedEndpoints.length?e.supportedEndpoints:["chat"]),I(!!e.normalizeToolCallId)},className:"p-1 hover:bg-sidebar rounded text-text-muted hover:text-primary",title:o("edit"),children:(0,t.jsx)("span",{className:"material-symbols-outlined text-sm",children:"edit"})}),(0,t.jsx)("button",{onClick:()=>$(e.id),className:"p-1 hover:bg-red-50 rounded text-red-500",title:o("removeCustomModel"),children:(0,t.jsx)("span",{className:"material-symbols-outlined text-sm",children:"delete"})})]})]},e.id)})}):(0,t.jsx)("p",{className:"text-xs text-text-muted",children:o("noCustomModels")})]})}function R({providerStorageAlias:e,providerDisplayAlias:s,modelAliases:i,copied:l,onCopy:o,onSetAlias:d,onDeleteAlias:p,connections:u,isAnthropic:m,onImportWithProgress:x}){let h=(0,n.useTranslations)("providers"),[f,g]=(0,a.useState)(""),[b,y]=(0,a.useState)(!1),[v,j]=(0,a.useState)(!1),N=(0,r.useNotificationStore)(),C=Object.entries(i).filter(([,t])=>t.startsWith(`${e}/`)).map(([t,a])=>({modelId:a.replace(`${e}/`,""),fullModel:a,alias:t})),k=e=>{let t,a=(t=e.split("/"))[t.length-1];if(!i[a])return a;let r=`${s}-${a}`;return i[r]?null:r},w=async()=>{if(!f.trim()||b)return;let t=f.trim(),a=k(t);if(!a)return void N.error(h("allSuggestedAliasesExist"));y(!0);try{let r=await fetch("/api/provider-models",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:e,modelId:t,modelName:t,source:"manual"})});if(!r.ok){let e={};try{e=await r.json()}catch(e){console.error("Failed to parse error response from custom model API:",e)}throw Error(e.error?.message||h("failedSaveCustomModel"))}await d(t,a,e),g(""),N.success(h("modelAddedSuccess",{modelId:t}))}catch(e){console.error("Error adding model:",e),N.error(e instanceof Error?e.message:h("failedAddModelTryAgain"))}finally{y(!1)}},S=async()=>{if(v)return;let t=u.find(e=>!1!==e.isActive);if(t){j(!0);try{await x(async()=>{let e=await fetch(`/api/providers/${t.id}/models`),a=await e.json();if(!e.ok)throw Error(a.error||h("failedImportModels"));return a},async t=>{let a=t.id||t.name||t.model;if(!a)return!1;let r=k(a);return!!r&&((await fetch("/api/provider-models",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:e,modelId:a,modelName:t.name||a,source:"imported"})})).ok?(await d(a,r,e),!0):(N.error(h("failedSaveImportedModel")),!1))})}catch(e){console.error("Error importing models:",e),N.error(h("failedImportModelsTryAgain"))}finally{j(!1)}}},T=u.some(e=>!1!==e.isActive),A=async(t,a)=>{try{if(!(await fetch(`/api/provider-models?provider=${encodeURIComponent(e)}&model=${encodeURIComponent(t)}`,{method:"DELETE"})).ok)throw Error(h("failedRemoveModelFromDatabase"));await p(a),N.success(h("modelRemovedSuccess"))}catch(e){console.error("Error deleting model:",e),N.error(e instanceof Error?e.message:h("failedDeleteModelTryAgain"))}};return(0,t.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,t.jsx)("p",{className:"text-sm text-text-muted",children:h("compatibleModelsDescription",{type:m?h("anthropic"):h("openai")})}),(0,t.jsxs)("div",{className:"flex items-end gap-2 flex-wrap",children:[(0,t.jsxs)("div",{className:"flex-1 min-w-[240px]",children:[(0,t.jsx)("label",{htmlFor:"new-compatible-model-input",className:"text-xs text-text-muted mb-1 block",children:h("modelId")}),(0,t.jsx)("input",{id:"new-compatible-model-input",type:"text",value:f,onChange:e=>g(e.target.value),onKeyDown:e=>"Enter"===e.key&&w(),placeholder:m?h("anthropicCompatibleModelPlaceholder"):h("openaiCompatibleModelPlaceholder"),className:"w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"})]}),(0,t.jsx)(c.Button,{size:"sm",icon:"add",onClick:w,disabled:!f.trim()||b,children:b?h("adding"):h("add")}),(0,t.jsx)(c.Button,{size:"sm",variant:"secondary",icon:"download",onClick:S,disabled:!T||v,children:v?h("importingModels"):h("importFromModels")})]}),!T&&(0,t.jsx)("p",{className:"text-xs text-text-muted",children:h("addConnectionToImport")}),C.length>0&&(0,t.jsx)("div",{className:"flex flex-col gap-3",children:C.map(({modelId:e,fullModel:a,alias:r})=>(0,t.jsx)(P,{modelId:e,fullModel:`${s}/${e}`,copied:l,onCopy:o,onDeleteAlias:()=>A(e,r)},a))})]})}function E({until:e}){let[r,s]=(0,a.useState)("");return((0,a.useEffect)(()=>{let t=()=>{let t=new Date(e).getTime()-Date.now();if(t<=0)return void s("");let a=Math.floor(t/1e3);if(a<60)s(`${a}s`);else if(a<3600)s(`${Math.floor(a/60)}m ${a%60}s`);else{let e=Math.floor(a/3600),t=Math.floor(a%3600/60);s(`${e}h ${t}m`)}};t();let a=setInterval(t,1e3);return()=>clearInterval(a)},[e]),r)?(0,t.jsxs)("span",{className:"text-xs text-orange-500 font-mono",children:["⏱ ",r]}):null}S.propTypes={model:s.default.shape({id:s.default.string.isRequired}).isRequired,fullModel:s.default.string.isRequired,alias:s.default.string,copied:s.default.string,onCopy:s.default.func.isRequired},T.propTypes={providerAlias:s.default.string.isRequired,modelAliases:s.default.object.isRequired,copied:s.default.string,onCopy:s.default.func.isRequired,onSetAlias:s.default.func.isRequired,onDeleteAlias:s.default.func.isRequired},P.propTypes={modelId:s.default.string.isRequired,fullModel:s.default.string.isRequired,copied:s.default.string,onCopy:s.default.func.isRequired,onDeleteAlias:s.default.func.isRequired},A.propTypes={providerId:s.default.string.isRequired,providerAlias:s.default.string.isRequired,copied:s.default.string,onCopy:s.default.func.isRequired},R.propTypes={providerStorageAlias:s.default.string.isRequired,providerDisplayAlias:s.default.string.isRequired,modelAliases:s.default.object.isRequired,copied:s.default.string,onCopy:s.default.func.isRequired,onSetAlias:s.default.func.isRequired,onDeleteAlias:s.default.func.isRequired,connections:s.default.arrayOf(s.default.shape({id:s.default.string,isActive:s.default.bool})).isRequired,isAnthropic:s.default.bool,onImportWithProgress:s.default.func.isRequired},E.propTypes={until:s.default.string.isRequired};let I={runtime_error:{labelKey:"errorTypeRuntime",variant:"warning"},upstream_auth_error:{labelKey:"errorTypeUpstreamAuth",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"}};function O({connection:e,isOAuth:r,isCodex:s,isFirst:i,isLast:l,onMoveUp:o,onMoveDown:d,onToggleActive:u,onToggleRateLimit:m,onToggleCodex5h:x,onToggleCodexWeekly:h,onRetest:f,isRetesting:g,onEdit:y,onDelete:v,onReauth:j,onProxy:N,hasProxy:C,proxySource:w,proxyHost:S,onRefreshToken:T,isRefreshing:P}){let A,R=(0,n.useTranslations)("providers"),O=r?e.name||e.email||e.displayName||R("oauthAccount"):e.name,[M,U]=(0,a.useState)(!1),[D,$]=(0,a.useState)(()=>r&&e.expiresAt?Math.floor((new Date(e.expiresAt).getTime()-Date.now())/6e4):null);(0,a.useEffect)(()=>{if(!r||!e.expiresAt)return;let t=setInterval(()=>{$(Math.floor((new Date(e.expiresAt).getTime()-Date.now())/6e4))},3e4);return()=>clearInterval(t)},[r,e.expiresAt]),(0,a.useEffect)(()=>{let t=()=>{U(e.rateLimitedUntil&&new Date(e.rateLimitedUntil).getTime()>Date.now())};t();let a=e.rateLimitedUntil?setInterval(t,1e3):null;return()=>{a&&clearInterval(a)}},[e.rateLimitedUntil]);let L="unavailable"!==e.testStatus||M?e.testStatus:"active",_=function(e,t,a,r){if(!1===e.isActive)return{statusVariant:"default",statusLabel:r("statusDisabled"),errorType:null,errorBadge:null,errorTextClass:"text-text-muted"};if("active"===t||"success"===t)return{statusVariant:"success",statusLabel:r("statusConnected"),errorType:null,errorBadge:null,errorTextClass:"text-text-muted"};let s=function(e,t){if(t)return"upstream_rate_limited";if(e.lastErrorType)return e.lastErrorType;let a=Number(e.errorCode);if(401===a||403===a)return"upstream_auth_error";if(429===a)return"upstream_rate_limited";if(a>=500)return"upstream_unavailable";let r=(e.lastError||"").toLowerCase();return r?r.includes("runtime")||r.includes("not runnable")||r.includes("not installed")||r.includes("healthcheck")?"runtime_error":r.includes("refresh failed")?"token_refresh_failed":r.includes("token expired")||r.includes("expired")?"token_expired":r.includes("invalid api key")||r.includes("token invalid")||r.includes("revoked")||r.includes("access denied")||r.includes("unauthorized")?"upstream_auth_error":r.includes("rate limit")||r.includes("quota")||r.includes("too many requests")||r.includes("429")?"upstream_rate_limited":r.includes("fetch failed")||r.includes("network")||r.includes("timeout")||r.includes("econn")||r.includes("enotfound")?"network_error":r.includes("not supported")?"unsupported":"upstream_error":null}(e,a),i=s&&I[s]||null;return"runtime_error"===s?{statusVariant:"warning",statusLabel:r("statusRuntimeIssue"),errorType:s,errorBadge:i,errorTextClass:"text-yellow-600 dark:text-yellow-400"}:"upstream_auth_error"===s||"auth_missing"===s||"token_refresh_failed"===s||"token_expired"===s?{statusVariant:"error",statusLabel:r("statusAuthFailed"),errorType:s,errorBadge:i,errorTextClass:"text-red-500"}:"upstream_rate_limited"===s?{statusVariant:"warning",statusLabel:r("statusRateLimited"),errorType:s,errorBadge:i,errorTextClass:"text-yellow-600 dark:text-yellow-400"}:"network_error"===s?{statusVariant:"warning",statusLabel:r("statusNetworkIssue"),errorType:s,errorBadge:i,errorTextClass:"text-yellow-600 dark:text-yellow-400"}:"unsupported"===s?{statusVariant:"default",statusLabel:r("statusTestUnsupported"),errorType:s,errorBadge:i,errorTextClass:"text-text-muted"}:{statusVariant:"error",statusLabel:({unavailable:r("statusUnavailable"),failed:r("statusFailed"),error:r("statusError")})[t]||t||r("statusError"),errorType:s,errorBadge:i,errorTextClass:"text-red-500"}}(e,L,M,R),K=!!e.rateLimitProtection,F=k(e.providerSpecificData&&"object"==typeof e.providerSpecificData&&e.providerSpecificData.codexLimitPolicy&&"object"==typeof e.providerSpecificData.codexLimitPolicy?e.providerSpecificData.codexLimitPolicy:{}),B=F.use5h,q=F.useWeekly;return(0,t.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===e.isActive?"opacity-60":""}`,children:[(0,t.jsxs)("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[(0,t.jsxs)("div",{className:"flex flex-col",children:[(0,t.jsx)("button",{onClick:o,disabled:i,className:`p-0.5 rounded ${i?"text-text-muted/30 cursor-not-allowed":"hover:bg-sidebar text-text-muted hover:text-primary"}`,children:(0,t.jsx)("span",{className:"material-symbols-outlined text-sm",children:"keyboard_arrow_up"})}),(0,t.jsx)("button",{onClick:d,disabled:l,className:`p-0.5 rounded ${l?"text-text-muted/30 cursor-not-allowed":"hover:bg-sidebar text-text-muted hover:text-primary"}`,children:(0,t.jsx)("span",{className:"material-symbols-outlined text-sm",children:"keyboard_arrow_down"})})]}),(0,t.jsx)("span",{className:"material-symbols-outlined text-base text-text-muted",children:r?"lock":"key"}),(0,t.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,t.jsx)("p",{className:"text-sm font-medium truncate",children:O}),(0,t.jsxs)("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[(0,t.jsx)(p.Badge,{variant:_.statusVariant,size:"sm",dot:!0,children:_.statusLabel}),null!==D&&(D<0?(0,t.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: ${e.expiresAt}`,children:[(0,t.jsx)("span",{className:"material-symbols-outlined text-[11px]",children:"error"}),"expired"]}):D<30?(0,t.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 ${D}m`,children:[(0,t.jsx)("span",{className:"material-symbols-outlined text-[11px]",children:"warning"}),`~${D}m`]}):null),M&&!1!==e.isActive&&(0,t.jsx)(E,{until:e.rateLimitedUntil}),_.errorBadge&&!1!==e.isActive&&(0,t.jsx)(p.Badge,{variant:_.errorBadge.variant,size:"sm",children:R(_.errorBadge.labelKey)}),e.lastError&&!1!==e.isActive&&(0,t.jsx)("span",{className:`text-xs truncate max-w-[300px] ${_.errorTextClass}`,title:e.lastError,children:e.lastError}),(0,t.jsxs)("span",{className:"text-xs text-text-muted",children:["#",e.priority]}),e.globalPriority&&(0,t.jsx)("span",{className:"text-xs text-text-muted",children:R("autoPriority",{priority:e.globalPriority})}),(0,t.jsx)("span",{className:"text-text-muted/30 select-none",children:"|"}),(0,t.jsxs)("button",{onClick:()=>m(!K),className:`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs font-medium transition-all cursor-pointer ${K?"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:R(K?"disableRateLimitProtection":"enableRateLimitProtection"),children:[(0,t.jsx)("span",{className:"material-symbols-outlined text-[13px]",children:"shield"}),R(K?"rateLimitProtected":"rateLimitUnprotected")]}),s&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"text-text-muted/30 select-none",children:"|"}),(0,t.jsxs)("button",{onClick:()=>x?.(!B),className:`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs font-medium transition-all cursor-pointer ${B?"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,t.jsx)("span",{className:"material-symbols-outlined text-[13px]",children:"timer"}),"5h ",B?"ON":"OFF"]}),(0,t.jsxs)("button",{onClick:()=>h?.(!q),className:`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs font-medium transition-all cursor-pointer ${q?"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,t.jsx)("span",{className:"material-symbols-outlined text-[13px]",children:"date_range"}),"Weekly ",q?"ON":"OFF"]})]}),C&&(A=R("global"===w?"proxySourceGlobal":"provider"===w?"proxySourceProvider":"proxySourceKey"),(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("span",{className:"text-text-muted/30 select-none",children:"|"}),(0,t.jsxs)("span",{className:`inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded text-xs font-medium ${"global"===w?"bg-emerald-500/15 text-emerald-500":"provider"===w?"bg-amber-500/15 text-amber-500":"bg-blue-500/15 text-blue-500"}`,title:R("proxyConfiguredBySource",{source:A,host:S||R("configured")}),children:[(0,t.jsx)("span",{className:"material-symbols-outlined text-[13px]",children:"vpn_lock"}),S||R("proxy")]})]}))]})]})]}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(c.Button,{size:"sm",variant:"ghost",icon:"refresh",loading:g,disabled:!1===e.isActive,onClick:f,className:"!h-7 !px-2 text-xs",title:R("retestAuthentication"),children:R("retest")}),T&&(0,t.jsx)(c.Button,{size:"sm",variant:"ghost",icon:"token",loading:P,disabled:!1===e.isActive||P,onClick:T,className:"!h-7 !px-2 text-xs text-amber-500 hover:text-amber-400",title:"Refresh OAuth token manually",children:"Token"}),(0,t.jsx)(b.Toggle,{size:"sm",checked:e.isActive??!0,onChange:u,title:R(e.isActive??!0?"disableConnection":"enableConnection")}),(0,t.jsxs)("div",{className:"flex gap-1 ml-1 transition-opacity",children:[j&&(0,t.jsx)("button",{onClick:j,className:"p-2 hover:bg-amber-500/10 rounded text-amber-600 hover:text-amber-500",title:R("reauthenticateConnection"),children:(0,t.jsx)("span",{className:"material-symbols-outlined text-[18px]",children:"passkey"})}),(0,t.jsx)("button",{onClick:y,className:"p-2 hover:bg-black/5 dark:hover:bg-white/5 rounded text-text-muted hover:text-primary",title:R("edit"),children:(0,t.jsx)("span",{className:"material-symbols-outlined text-[18px]",children:"edit"})}),(0,t.jsx)("button",{onClick:N,className:"p-2 hover:bg-black/5 dark:hover:bg-white/5 rounded text-text-muted hover:text-primary",title:R("proxyConfig"),children:(0,t.jsx)("span",{className:"material-symbols-outlined text-[18px]",children:"vpn_lock"})}),(0,t.jsx)("button",{onClick:v,className:"p-2 hover:bg-red-500/10 rounded text-red-500",title:R("delete"),children:(0,t.jsx)("span",{className:"material-symbols-outlined text-[18px]",children:"delete"})})]})]})]})}function M({isOpen:e,provider:r,providerName:s,isCompatible:i,isAnthropic:l,onSave:o,onClose:d}){let x=(0,n.useTranslations)("providers"),h="bailian-coding-plan"===r,f="https://coding-intl.dashscope.aliyuncs.com/apps/anthropic/v1",[g,b]=(0,a.useState)({name:"",apiKey:"",priority:1,baseUrl:h?f:""}),[y,v]=(0,a.useState)(!1),[j,N]=(0,a.useState)(null),[C,k]=(0,a.useState)(!1),[w,S]=(0,a.useState)(null),T=async()=>{v(!0),S(null);try{let e=await fetch("/api/providers/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:r,apiKey:g.apiKey})}),t=await e.json();N(t.valid?"success":"failed")}catch{N("failed")}finally{v(!1)}},P=async()=>{if(r&&g.apiKey){k(!0),S(null);try{let e=null;if(h){let t=U(g.baseUrl,f);if(t.error)return void S(t.error);e=t.value}let t=!1;try{v(!0),N(null);let e=await fetch("/api/providers/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:r,apiKey:g.apiKey})});t=!!(await e.json()).valid,N(t?"success":"failed")}catch{N("failed")}finally{v(!1)}if(!t)return void S(x("apiKeyValidationFailed"));let a={name:g.name,apiKey:g.apiKey,priority:g.priority,testStatus:"active",providerSpecificData:void 0};h&&(a.providerSpecificData={baseUrl:e});let s=await o(a);s&&S("string"==typeof s?s:x("failedSaveConnection"))}finally{k(!1)}}};return r?(0,t.jsx)(m.Modal,{isOpen:e,title:x("addProviderApiKeyTitle",{provider:s||r}),onClose:d,children:(0,t.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,t.jsx)(u.Input,{label:x("nameLabel"),value:g.name,onChange:e=>b({...g,name:e.target.value}),placeholder:x("productionKey")}),(0,t.jsxs)("div",{className:"flex gap-2",children:[(0,t.jsx)(u.Input,{label:x("apiKeyLabel"),type:"password",value:g.apiKey,onChange:e=>b({...g,apiKey:e.target.value}),className:"flex-1"}),(0,t.jsx)("div",{className:"pt-6",children:(0,t.jsx)(c.Button,{onClick:T,disabled:!g.apiKey||y||C,variant:"secondary",children:y?x("checking"):x("check")})})]}),j&&(0,t.jsx)(p.Badge,{variant:"success"===j?"success":"error",children:"success"===j?x("valid"):x("invalid")}),w&&(0,t.jsx)("div",{className:"text-sm text-red-500 bg-red-500/10 border border-red-500/20 rounded-lg px-3 py-2",children:w}),i&&(0,t.jsx)("p",{className:"text-xs text-text-muted",children:l?x("validationChecksAnthropicCompatible",{provider:s||x("anthropicCompatibleName")}):x("validationChecksOpenAiCompatible",{provider:s||x("openaiCompatibleName")})}),(0,t.jsx)(u.Input,{label:x("priorityLabel"),type:"number",value:g.priority,onChange:e=>b({...g,priority:Number.parseInt(e.target.value)||1})}),h&&(0,t.jsx)(u.Input,{label:"Base URL",value:g.baseUrl,onChange:e=>b({...g,baseUrl:e.target.value}),placeholder:f,hint:"Optional: Custom base URL for bailian-coding-plan provider"}),(0,t.jsxs)("div",{className:"flex gap-2",children:[(0,t.jsx)(c.Button,{onClick:P,fullWidth:!0,disabled:!g.name||!g.apiKey||C,children:C?x("saving"):x("save")}),(0,t.jsx)(c.Button,{onClick:d,variant:"ghost",fullWidth:!0,children:x("cancel")})]})]})}):null}function U(e,t){let a=("string"==typeof e?e.trim():"")||t;try{let e=new URL(a);if("http:"!==e.protocol&&"https:"!==e.protocol)return{value:null,error:"Base URL must use http or https"};return{value:a,error:null}}catch{return{value:null,error:"Base URL must be a valid URL"}}}function D({isOpen:e,connection:r,onSave:s,onClose:i}){let l=(0,n.useTranslations)("providers"),[o,d]=(0,a.useState)({name:"",priority:1,apiKey:"",healthCheckInterval:60,baseUrl:""}),[x,h]=(0,a.useState)(!1),[f,g]=(0,a.useState)(null),[b,y]=(0,a.useState)(!1),[v,N]=(0,a.useState)(null),[C,k]=(0,a.useState)(!1),[w,S]=(0,a.useState)(null),[T,P]=(0,a.useState)([]),[A,R]=(0,a.useState)(""),E=r?.provider==="bailian-coding-plan",O="https://coding-intl.dashscope.aliyuncs.com/apps/anthropic/v1";(0,a.useEffect)(()=>{if(r){let e=r.providerSpecificData?.baseUrl;d({name:r.name||"",priority:r.priority||1,apiKey:"",healthCheckInterval:r.healthCheckInterval??60,baseUrl:e||(E?O:"")});let t=r.providerSpecificData?.extraApiKeys;P(Array.isArray(t)?t:[]),R(""),g(null),N(null),S(null)}},[r,E]);let M=async()=>{if(r?.provider){h(!0),g(null);try{let e=await fetch(`/api/providers/${r.id}/test`,{method:"POST"}),t=await e.json();g({valid:!!t.valid,diagnosis:t.diagnosis||null,message:t.error||null})}catch{g({valid:!1,diagnosis:{type:"network_error"},message:l("failedTestConnection")})}finally{h(!1)}}},D=async()=>{if(r?.provider&&o.apiKey){y(!0),N(null);try{let e=await fetch("/api/providers/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:r.provider,apiKey:o.apiKey})}),t=await e.json();N(t.valid?"success":"failed")}catch{N("failed")}finally{y(!1)}}},$=async()=>{k(!0),S(null);try{let e={name:o.name,priority:o.priority,healthCheckInterval:o.healthCheckInterval},t=null;if(E){let e=U(o.baseUrl,O);if(e.error)return void S(e.error);t=e.value}if(!L&&o.apiKey){e.apiKey=o.apiKey;let t="success"===v;if(!t)try{y(!0),N(null);let e=await fetch("/api/providers/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:r.provider,apiKey:o.apiKey})});t=!!(await e.json()).valid,N(t?"success":"failed")}catch{N("failed")}finally{y(!1)}t&&(e.testStatus="active",e.lastError=null,e.lastErrorAt=null,e.lastErrorType=null,e.lastErrorSource=null,e.errorCode=null,e.rateLimitedUntil=null)}!L&&(e.providerSpecificData={...r.providerSpecificData||{},extraApiKeys:T.filter(e=>e.trim().length>0)},E&&(e.providerSpecificData.baseUrl=t));let a=await s(e);a&&S("string"==typeof a?a:l("failedSaveConnection"))}finally{k(!1)}};if(!r)return null;let L="oauth"===r.authType,_=(0,j.isOpenAICompatibleProvider)(r.provider)||(0,j.isAnthropicCompatibleProvider)(r.provider),K=!f?.valid&&f?.diagnosis?.type&&I[f.diagnosis.type]||null;return(0,t.jsx)(m.Modal,{isOpen:e,title:l("editConnection"),onClose:i,children:(0,t.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,t.jsx)(u.Input,{label:l("nameLabel"),value:o.name,onChange:e=>d({...o,name:e.target.value}),placeholder:L?l("accountName"):l("productionKey")}),L&&r.email&&(0,t.jsxs)("div",{className:"bg-sidebar/50 p-3 rounded-lg",children:[(0,t.jsx)("p",{className:"text-sm text-text-muted mb-1",children:l("email")}),(0,t.jsx)("p",{className:"font-medium",children:r.email})]}),L&&(0,t.jsx)(u.Input,{label:l("healthCheckMinutes"),type:"number",value:o.healthCheckInterval,onChange:e=>d({...o,healthCheckInterval:Math.max(0,Number.parseInt(e.target.value)||0)}),hint:l("healthCheckHint")}),(0,t.jsx)(u.Input,{label:l("priorityLabel"),type:"number",value:o.priority,onChange:e=>d({...o,priority:Number.parseInt(e.target.value)||1})}),!L&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)("div",{className:"flex gap-2",children:[(0,t.jsx)(u.Input,{label:l("apiKeyLabel"),type:"password",value:o.apiKey,onChange:e=>d({...o,apiKey:e.target.value}),placeholder:l("enterNewApiKey"),hint:l("leaveBlankKeepCurrentApiKey"),className:"flex-1"}),(0,t.jsx)("div",{className:"pt-6",children:(0,t.jsx)(c.Button,{onClick:D,disabled:!o.apiKey||b||C,variant:"secondary",children:b?l("checking"):l("check")})})]}),v&&(0,t.jsx)(p.Badge,{variant:"success"===v?"success":"error",children:"success"===v?l("valid"):l("invalid")}),w&&(0,t.jsx)("div",{className:"text-sm text-red-500 bg-red-500/10 border border-red-500/20 rounded-lg px-3 py-2",children:w})]}),E&&(0,t.jsx)(u.Input,{label:"Base URL",value:o.baseUrl,onChange:e=>d({...o,baseUrl:e.target.value}),placeholder:O,hint:"Custom base URL for bailian-coding-plan provider"}),!L&&(0,t.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,t.jsxs)("label",{className:"text-sm font-medium text-text-main",children:["Extra API Keys",(0,t.jsx)("span",{className:"ml-2 text-[11px] font-normal text-text-muted",children:"(round-robin rotation — optional)"})]}),T.length>0&&(0,t.jsx)("div",{className:"flex flex-col gap-1.5",children:T.map((e,a)=>(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.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 #${a+2}: ${e.slice(0,6)}...${e.slice(-4)}`}),(0,t.jsx)("button",{onClick:()=>P(T.filter((e,t)=>t!==a)),className:"p-1.5 rounded hover:bg-red-500/10 text-red-400 hover:text-red-500",title:"Remove this key",children:(0,t.jsx)("span",{className:"material-symbols-outlined text-[16px]",children:"close"})})]},a))}),(0,t.jsxs)("div",{className:"flex gap-2",children:[(0,t.jsx)("input",{type:"password",value:A,onChange:e=>R(e.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:e=>{"Enter"===e.key&&A.trim()&&(P([...T,A.trim()]),R(""))}}),(0,t.jsx)("button",{onClick:()=>{A.trim()&&(P([...T,A.trim()]),R(""))},disabled:!A.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"})]}),T.length>0&&(0,t.jsxs)("p",{className:"text-[11px] text-text-muted",children:[T.length+1," keys total — rotating round-robin on each request."]})]}),!_&&(0,t.jsxs)("div",{className:"flex items-center gap-3",children:[(0,t.jsx)(c.Button,{onClick:M,variant:"secondary",disabled:x,children:x?l("testing"):l("testConnection")}),f&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(p.Badge,{variant:f.valid?"success":"error",children:f.valid?l("valid"):l("failed")}),K&&(0,t.jsx)(p.Badge,{variant:K.variant,children:l(K.labelKey)})]})]}),(0,t.jsxs)("div",{className:"flex gap-2",children:[(0,t.jsx)(c.Button,{onClick:$,fullWidth:!0,disabled:C,children:C?l("saving"):l("save")}),(0,t.jsx)(c.Button,{onClick:i,variant:"ghost",fullWidth:!0,children:l("cancel")})]})]})})}function $({isOpen:e,node:r,onSave:s,onClose:i,isAnthropic:l}){let o=(0,n.useTranslations)("providers"),[d,x]=(0,a.useState)({name:"",prefix:"",apiType:"chat",baseUrl:"https://api.openai.com/v1",chatPath:"",modelsPath:""}),[h,f]=(0,a.useState)(!1),[g,b]=(0,a.useState)(""),[v,j]=(0,a.useState)(!1),[N,C]=(0,a.useState)(null),[k,w]=(0,a.useState)(!1);(0,a.useEffect)(()=>{r&&(x({name:r.name||"",prefix:r.prefix||"",apiType:r.apiType||"chat",baseUrl:r.baseUrl||(l?"https://api.anthropic.com/v1":"https://api.openai.com/v1"),chatPath:r.chatPath||"",modelsPath:r.modelsPath||""}),w(!!(r.chatPath||r.modelsPath)))},[r,l]);let S=[{value:"chat",label:o("chatCompletions")},{value:"responses",label:o("responsesApi")}],T=async()=>{if(d.name.trim()&&d.prefix.trim()&&d.baseUrl.trim()){f(!0);try{let e={name:d.name,prefix:d.prefix,baseUrl:d.baseUrl,chatPath:d.chatPath||"",modelsPath:d.modelsPath||""};l||(e.apiType=d.apiType),await s(e)}finally{f(!1)}}},P=async()=>{j(!0);try{let e=await fetch("/api/provider-nodes/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({baseUrl:d.baseUrl,apiKey:g,type:l?"anthropic-compatible":"openai-compatible",modelsPath:d.modelsPath||""})}),t=await e.json();C(t.valid?"success":"failed")}catch{C("failed")}finally{j(!1)}};return r?(0,t.jsx)(m.Modal,{isOpen:e,title:o("editCompatibleTitle",{type:o(l?"anthropic":"openai")}),onClose:i,children:(0,t.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,t.jsx)(u.Input,{label:o("nameLabel"),value:d.name,onChange:e=>x({...d,name:e.target.value}),placeholder:o("compatibleProdPlaceholder",{type:o(l?"anthropic":"openai")}),hint:o("nameHint")}),(0,t.jsx)(u.Input,{label:o("prefixLabel"),value:d.prefix,onChange:e=>x({...d,prefix:e.target.value}),placeholder:o(l?"anthropicPrefixPlaceholder":"openaiPrefixPlaceholder"),hint:o("prefixHint")}),!l&&(0,t.jsx)(y.Select,{label:o("apiTypeLabel"),options:S,value:d.apiType,onChange:e=>x({...d,apiType:e.target.value})}),(0,t.jsx)(u.Input,{label:o("baseUrlLabel"),value:d.baseUrl,onChange:e=>x({...d,baseUrl:e.target.value}),placeholder:o(l?"anthropicBaseUrlPlaceholder":"openaiBaseUrlPlaceholder"),hint:o("compatibleBaseUrlHint",{type:o(l?"anthropic":"openai")})}),(0,t.jsxs)("button",{type:"button",className:"text-sm text-text-muted hover:text-text-primary flex items-center gap-1",onClick:()=>w(!k),"aria-expanded":k,"aria-controls":"advanced-settings",children:[(0,t.jsx)("span",{className:`transition-transform ${k?"rotate-90":""}`,"aria-hidden":"true",children:"▶"}),o("advancedSettings")]}),k&&(0,t.jsxs)("div",{id:"advanced-settings",className:"flex flex-col gap-3 pl-2 border-l-2 border-border",children:[(0,t.jsx)(u.Input,{label:o("chatPathLabel"),value:d.chatPath,onChange:e=>x({...d,chatPath:e.target.value}),placeholder:l?"/messages":o("chatPathPlaceholder"),hint:o("chatPathHint")}),(0,t.jsx)(u.Input,{label:o("modelsPathLabel"),value:d.modelsPath,onChange:e=>x({...d,modelsPath:e.target.value}),placeholder:o("modelsPathPlaceholder"),hint:o("modelsPathHint")})]}),(0,t.jsxs)("div",{className:"flex gap-2",children:[(0,t.jsx)(u.Input,{label:o("apiKeyForCheck"),type:"password",value:g,onChange:e=>b(e.target.value),className:"flex-1"}),(0,t.jsx)("div",{className:"pt-6",children:(0,t.jsx)(c.Button,{onClick:P,disabled:!g||v||!d.baseUrl.trim(),variant:"secondary",children:o(v?"checking":"check")})})]}),N&&(0,t.jsx)(p.Badge,{variant:"success"===N?"success":"error",children:o("success"===N?"valid":"invalid")}),(0,t.jsxs)("div",{className:"flex gap-2",children:[(0,t.jsx)(c.Button,{onClick:T,fullWidth:!0,disabled:!d.name.trim()||!d.prefix.trim()||!d.baseUrl.trim()||h,children:o(h?"saving":"save")}),(0,t.jsx)(c.Button,{onClick:i,variant:"ghost",fullWidth:!0,children:o("cancel")})]})]})}):null}O.propTypes={connection:s.default.shape({id:s.default.string,name:s.default.string,email:s.default.string,displayName:s.default.string,rateLimitedUntil:s.default.string,rateLimitProtection:s.default.bool,testStatus:s.default.string,isActive:s.default.bool,priority:s.default.number,lastError:s.default.string,lastErrorType:s.default.string,lastErrorSource:s.default.string,errorCode:s.default.oneOfType([s.default.string,s.default.number]),globalPriority:s.default.number,providerSpecificData:s.default.object}).isRequired,isOAuth:s.default.bool.isRequired,isCodex:s.default.bool,isFirst:s.default.bool.isRequired,isLast:s.default.bool.isRequired,onMoveUp:s.default.func.isRequired,onMoveDown:s.default.func.isRequired,onToggleActive:s.default.func.isRequired,onToggleRateLimit:s.default.func.isRequired,onToggleCodex5h:s.default.func,onToggleCodexWeekly:s.default.func,onRetest:s.default.func.isRequired,isRetesting:s.default.bool,onEdit:s.default.func.isRequired,onDelete:s.default.func.isRequired,onReauth:s.default.func},M.propTypes={isOpen:s.default.bool.isRequired,provider:s.default.string,providerName:s.default.string,isCompatible:s.default.bool,isAnthropic:s.default.bool,onSave:s.default.func.isRequired,onClose:s.default.func.isRequired},D.propTypes={isOpen:s.default.bool.isRequired,connection:s.default.shape({id:s.default.string,name:s.default.string,email:s.default.string,priority:s.default.number,authType:s.default.string,provider:s.default.string}),onSave:s.default.func.isRequired,onClose:s.default.func.isRequired},$.propTypes={isOpen:s.default.bool.isRequired,node:s.default.shape({id:s.default.string,name:s.default.string,prefix:s.default.string,apiType:s.default.string,baseUrl:s.default.string,chatPath:s.default.string,modelsPath:s.default.string}),onSave:s.default.func.isRequired,onClose:s.default.func.isRequired,isAnthropic:s.default.bool},e.s(["default",()=>w],710864)}]);
|
package/app/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,26 @@
|
|
|
4
4
|
|
|
5
5
|
---
|
|
6
6
|
|
|
7
|
+
## [2.8.1] — 2026-03-19
|
|
8
|
+
|
|
9
|
+
> Sprint: Five community PRs — streaming call log fixes, Kiro compatibility, cache token analytics, Chinese translation, and configurable tool call IDs.
|
|
10
|
+
|
|
11
|
+
### ✨ Features
|
|
12
|
+
|
|
13
|
+
- **feat(logs)**: Call log response content now correctly accumulated from raw provider chunks (OpenAI/Claude/Gemini) before translation, fixing empty response payloads in streaming mode (#470, @zhangqiang8vip)
|
|
14
|
+
- **feat(providers)**: Per-model configurable 9-char tool call ID normalization (Mistral-style) — only models with the option enabled get truncated IDs (#470)
|
|
15
|
+
- **feat(api)**: Key PATCH API expanded to support `allowedConnections`, `name`, `autoResolve`, `isActive`, and `accessSchedule` fields (#470)
|
|
16
|
+
- **feat(dashboard)**: Response-first layout in request log detail UI (#470)
|
|
17
|
+
- **feat(i18n)**: Improved Chinese (zh-CN) translation — complete retranslation (#475, @only4copilot)
|
|
18
|
+
|
|
19
|
+
### 🐛 Bug Fixes
|
|
20
|
+
|
|
21
|
+
- **fix(kiro)**: Strip injected `model` field from request body — Kiro API rejects unknown top-level fields (#478, @prakersh)
|
|
22
|
+
- **fix(usage)**: Include cache read + cache creation tokens in usage history input totals for accurate analytics (#477, @prakersh)
|
|
23
|
+
- **fix(callLogs)**: Support Claude format usage fields (`input_tokens`/`output_tokens`) alongside OpenAI format, include all cache token variants (#476, @prakersh)
|
|
24
|
+
|
|
25
|
+
---
|
|
26
|
+
|
|
7
27
|
## [2.8.0] — 2026-03-19
|
|
8
28
|
|
|
9
29
|
> Sprint: Bailian Coding Plan provider with editable base URLs, plus community contributions for Alibaba Cloud and Kimi Coding.
|
package/app/docs/openapi.yaml
CHANGED
|
@@ -77,10 +77,13 @@ export class KiroExecutor extends BaseExecutor {
|
|
|
77
77
|
}
|
|
78
78
|
|
|
79
79
|
transformRequest(model: string, body: unknown, stream: boolean, credentials: unknown): unknown {
|
|
80
|
-
void model;
|
|
81
80
|
void stream;
|
|
82
81
|
void credentials;
|
|
83
|
-
|
|
82
|
+
// Kiro uses conversationState.currentMessage.userInputMessage.modelId,
|
|
83
|
+
// not a top-level "model" field. chatCore injects translatedBody.model
|
|
84
|
+
// which Kiro API rejects as unknown top-level field.
|
|
85
|
+
const { model: _model, ...rest } = body as Record<string, unknown>;
|
|
86
|
+
return rest;
|
|
84
87
|
}
|
|
85
88
|
|
|
86
89
|
/**
|
|
@@ -23,6 +23,7 @@ import {
|
|
|
23
23
|
appendRequestLog,
|
|
24
24
|
saveCallLog,
|
|
25
25
|
} from "@/lib/usageDb";
|
|
26
|
+
import { getModelNormalizeToolCallId } from "@/lib/db/models";
|
|
26
27
|
import { getExecutor } from "../executors/index.ts";
|
|
27
28
|
import { translateNonStreamingResponse } from "./responseTranslator.ts";
|
|
28
29
|
import { extractUsageFromResponse } from "./usageExtractor.ts";
|
|
@@ -310,6 +311,7 @@ export async function handleChatCore({
|
|
|
310
311
|
}
|
|
311
312
|
}
|
|
312
313
|
|
|
314
|
+
const normalizeToolCallId = getModelNormalizeToolCallId(provider || "", model || "");
|
|
313
315
|
translatedBody = translateRequest(
|
|
314
316
|
sourceFormat,
|
|
315
317
|
targetFormat,
|
|
@@ -318,7 +320,8 @@ export async function handleChatCore({
|
|
|
318
320
|
stream,
|
|
319
321
|
credentials,
|
|
320
322
|
provider,
|
|
321
|
-
reqLogger
|
|
323
|
+
reqLogger,
|
|
324
|
+
{ normalizeToolCallId }
|
|
322
325
|
);
|
|
323
326
|
}
|
|
324
327
|
} catch (error) {
|
|
@@ -871,8 +874,12 @@ export async function handleChatCore({
|
|
|
871
874
|
// Create transform stream with logger for streaming response
|
|
872
875
|
let transformStream;
|
|
873
876
|
|
|
874
|
-
// Callback to save call log when stream completes (
|
|
875
|
-
const onStreamComplete = ({
|
|
877
|
+
// Callback to save call log when stream completes (include responseBody when provided by stream)
|
|
878
|
+
const onStreamComplete = ({
|
|
879
|
+
status: streamStatus,
|
|
880
|
+
usage: streamUsage,
|
|
881
|
+
responseBody: streamResponseBody,
|
|
882
|
+
}) => {
|
|
876
883
|
saveCallLog({
|
|
877
884
|
method: "POST",
|
|
878
885
|
path: clientRawRequest?.endpoint || "/v1/chat/completions",
|
|
@@ -883,6 +890,7 @@ export async function handleChatCore({
|
|
|
883
890
|
duration: Date.now() - startTime,
|
|
884
891
|
tokens: streamUsage || {},
|
|
885
892
|
requestBody: body,
|
|
893
|
+
responseBody: streamResponseBody ?? undefined,
|
|
886
894
|
sourceFormat,
|
|
887
895
|
targetFormat,
|
|
888
896
|
comboName,
|
|
@@ -1,26 +1,69 @@
|
|
|
1
1
|
// Tool call helper functions for translator
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
const ALPHANUM9 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
|
4
|
+
|
|
5
|
+
// Generate unique tool call ID (default long form)
|
|
4
6
|
export function generateToolCallId() {
|
|
5
7
|
return `call_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 9)}`;
|
|
6
8
|
}
|
|
7
9
|
|
|
8
|
-
//
|
|
9
|
-
|
|
10
|
+
// Generate 9-char [a-zA-Z0-9] id for providers that require it (e.g. Mistral)
|
|
11
|
+
function generateToolCallId9(): string {
|
|
12
|
+
let s = "";
|
|
13
|
+
for (let i = 0; i < 9; i++) {
|
|
14
|
+
s += ALPHANUM9[Math.floor(Math.random() * ALPHANUM9.length)];
|
|
15
|
+
}
|
|
16
|
+
return s;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** @param options.use9CharId - When true, normalize ids to 9-char [a-zA-Z0-9] (e.g. Mistral); when false, only fix type/arguments, leave ids as-is */
|
|
20
|
+
export function ensureToolCallIds(body, options?: { use9CharId?: boolean }) {
|
|
10
21
|
if (!body.messages || !Array.isArray(body.messages)) return body;
|
|
11
22
|
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
23
|
+
const use9CharId = options?.use9CharId === true;
|
|
24
|
+
|
|
25
|
+
for (let i = 0; i < body.messages.length; i++) {
|
|
26
|
+
const msg = body.messages[i];
|
|
27
|
+
if (msg.role !== "assistant" || !msg.tool_calls || !Array.isArray(msg.tool_calls)) continue;
|
|
28
|
+
|
|
29
|
+
const used9 = new Set<string>();
|
|
30
|
+
const newIdsInOrder: string[] = [];
|
|
31
|
+
|
|
32
|
+
for (const tc of msg.tool_calls) {
|
|
33
|
+
if (!tc.type) {
|
|
34
|
+
tc.type = "function";
|
|
35
|
+
}
|
|
36
|
+
if (tc.function?.arguments && typeof tc.function.arguments !== "string") {
|
|
37
|
+
tc.function.arguments = JSON.stringify(tc.function.arguments);
|
|
38
|
+
}
|
|
39
|
+
if (use9CharId) {
|
|
40
|
+
let newId: string;
|
|
41
|
+
do {
|
|
42
|
+
newId = generateToolCallId9();
|
|
43
|
+
} while (used9.has(newId));
|
|
44
|
+
used9.add(newId);
|
|
45
|
+
newIdsInOrder.push(newId);
|
|
46
|
+
tc.id = newId;
|
|
47
|
+
} else {
|
|
48
|
+
// Leave id as-is, only ensure it exists for later tool message matching
|
|
49
|
+
const id =
|
|
50
|
+
tc.id != null && String(tc.id).trim() !== "" ? String(tc.id) : generateToolCallId();
|
|
51
|
+
tc.id = id;
|
|
52
|
+
newIdsInOrder.push(id);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// Tool responses (role "tool") follow in same order as tool_calls; set tool_call_id by index.
|
|
57
|
+
// Stop when we hit another assistant so we only link tool messages that immediately follow this one.
|
|
58
|
+
if (newIdsInOrder.length > 0) {
|
|
59
|
+
let idx = 0;
|
|
60
|
+
for (let j = i + 1; j < body.messages.length; j++) {
|
|
61
|
+
const later = body.messages[j];
|
|
62
|
+
if (later.role === "assistant") break;
|
|
63
|
+
if (later.role !== "tool") continue;
|
|
64
|
+
if (idx < newIdsInOrder.length) {
|
|
65
|
+
later.tool_call_id = newIdsInOrder[idx];
|
|
66
|
+
idx++;
|
|
24
67
|
}
|
|
25
68
|
}
|
|
26
69
|
}
|
|
@@ -66,6 +66,7 @@ function normalizeOpenAIResponsesRequest(body) {
|
|
|
66
66
|
return normalized;
|
|
67
67
|
}
|
|
68
68
|
|
|
69
|
+
/** @param options.normalizeToolCallId - When true, use 9-char tool call ids (e.g. Mistral); when false, leave ids as-is */
|
|
69
70
|
// Translate request: source -> openai -> target
|
|
70
71
|
export function translateRequest(
|
|
71
72
|
sourceFormat,
|
|
@@ -75,9 +76,11 @@ export function translateRequest(
|
|
|
75
76
|
stream = true,
|
|
76
77
|
credentials = null,
|
|
77
78
|
provider = null,
|
|
78
|
-
reqLogger = null
|
|
79
|
+
reqLogger = null,
|
|
80
|
+
options?: { normalizeToolCallId?: boolean }
|
|
79
81
|
) {
|
|
80
82
|
let result = body;
|
|
83
|
+
const use9CharId = options?.normalizeToolCallId === true;
|
|
81
84
|
|
|
82
85
|
// Phase 2: Apply thinking budget control before normalization
|
|
83
86
|
result = applyThinkingBudget(result);
|
|
@@ -85,8 +88,8 @@ export function translateRequest(
|
|
|
85
88
|
// Normalize thinking config: remove if lastMessage is not user
|
|
86
89
|
normalizeThinkingConfig(result);
|
|
87
90
|
|
|
88
|
-
//
|
|
89
|
-
ensureToolCallIds(result);
|
|
91
|
+
// Ensure tool_calls have id; optionally normalize to 9-char for providers like Mistral
|
|
92
|
+
ensureToolCallIds(result, { use9CharId });
|
|
90
93
|
|
|
91
94
|
// Fix missing tool responses (insert empty tool_result if needed)
|
|
92
95
|
fixMissingToolResponses(result);
|
|
@@ -140,6 +143,10 @@ export function translateRequest(
|
|
|
140
143
|
result = normalizeOpenAIResponsesRequest(result);
|
|
141
144
|
}
|
|
142
145
|
|
|
146
|
+
// Ensure unique tool_call ids on final payload (translators may have introduced duplicates)
|
|
147
|
+
ensureToolCallIds(result, { use9CharId });
|
|
148
|
+
fixMissingToolResponses(result);
|
|
149
|
+
|
|
143
150
|
return result;
|
|
144
151
|
}
|
|
145
152
|
|