swayrouter 1.0.2 → 1.0.4

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.
Files changed (62) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dashboard/dist/assets/{CliTools-Ch3gKuNw.js → CliTools-5DLXOz1A.js} +1 -1
  3. package/dashboard/dist/assets/{Combo-BBCldjWi.js → Combo-BCvuw7s2.js} +1 -1
  4. package/dashboard/dist/assets/{ConsoleLog-wywAYcPT.js → ConsoleLog-BwgJ9V8I.js} +4 -4
  5. package/dashboard/dist/assets/{Dashboard-DxzyF41b.js → Dashboard-B-tNs8a1.js} +1 -1
  6. package/dashboard/dist/assets/{Header-C_9Su9BF.js → Header-9KXz4S67.js} +1 -1
  7. package/dashboard/dist/assets/{Keys-D0ufgcsc.js → Keys-DE32cEsn.js} +1 -1
  8. package/dashboard/dist/assets/Login-z7dbRqrR.js +1 -0
  9. package/dashboard/dist/assets/{ManageApiKey-CVXsmW2B.js → ManageApiKey-DF3A1CXL.js} +1 -1
  10. package/dashboard/dist/assets/{OAuthCallback-D_UZYcF6.js → OAuthCallback-I8fzY5zi.js} +1 -1
  11. package/dashboard/dist/assets/Provider-Caq5lvsq.js +4 -0
  12. package/dashboard/dist/assets/{ProviderModelAccordion-BAifkfVR.js → ProviderModelAccordion-GZSOrZZu.js} +1 -1
  13. package/dashboard/dist/assets/{Proxy-CU15VJ--.js → Proxy-DJVhsf4E.js} +1 -1
  14. package/dashboard/dist/assets/QuotaMonitor-BA4GOxkV.js +1 -0
  15. package/dashboard/dist/assets/{Settings-Dt4y2dC0.js → Settings-eEpS37LF.js} +1 -1
  16. package/dashboard/dist/assets/{Setup-DSDUwU7N.js → Setup-D9G2dVUf.js} +1 -1
  17. package/dashboard/dist/assets/{StatusBadge-1nAOyHU2.js → StatusBadge-DClAYX7v.js} +1 -1
  18. package/dashboard/dist/assets/{SwayChat-Bup7up6D.js → SwayChat-DS0GBQKQ.js} +2 -2
  19. package/dashboard/dist/assets/Usage-CRQCq5jc.js +4 -0
  20. package/dashboard/dist/assets/{accordion-DOOPDDgt.js → accordion-BkSdf_dl.js} +1 -1
  21. package/dashboard/dist/assets/{admin-extras-api-CCdu5TFM.js → admin-extras-api-ppLkXcD9.js} +1 -1
  22. package/dashboard/dist/assets/{api-keys-api-ifAC2Ok3.js → api-keys-api-CsdHmg2W.js} +1 -1
  23. package/dashboard/dist/assets/{card-CC0Omjcv.js → card-BOVhvx7W.js} +1 -1
  24. package/dashboard/dist/assets/{checkbox-7SZBrmbN.js → checkbox-DU_0LpXJ.js} +1 -1
  25. package/dashboard/dist/assets/{connections-api-_N54UD3S.js → connections-api-CQHf0Hwe.js} +1 -1
  26. package/dashboard/dist/assets/{copy-button-qBvM6H9z.js → copy-button-nPFbNAXf.js} +1 -1
  27. package/dashboard/dist/assets/{currency-api-SV9CBf5e.js → currency-api-CDXu9UhW.js} +1 -1
  28. package/dashboard/dist/assets/{flip-button-BGgkjtl0.js → flip-button-C_PNv8Iq.js} +1 -1
  29. package/dashboard/dist/assets/{frame-cUiti6Lq.js → frame-BLwA8c3u.js} +1 -1
  30. package/dashboard/dist/assets/index-CN-Y5gO6.css +1 -0
  31. package/dashboard/dist/assets/index-x5tLD3Ye.js +10 -0
  32. package/dashboard/dist/assets/{ripple-button-l8aMiVVG.js → ripple-button-BV_KcZ7W.js} +1 -1
  33. package/dashboard/dist/assets/{segmented-CqmEnQjZ.js → segmented-BBSMiP-0.js} +1 -1
  34. package/dashboard/dist/assets/select-DELc8FMO.js +1 -0
  35. package/dashboard/dist/assets/{skeleton-7uJDiIXe.js → skeleton-CFSSp0e0.js} +1 -1
  36. package/dashboard/dist/assets/{table-D0M60Tu1.js → table-lcAgAODE.js} +1 -1
  37. package/dashboard/dist/assets/{tabs-C6YkuulG.js → tabs-CSBJRjaH.js} +1 -1
  38. package/dashboard/dist/assets/{tunnel-api-DDPsBaDV.js → tunnel-api-CdE1F_Ct.js} +1 -1
  39. package/dashboard/dist/index.html +2 -2
  40. package/package.json +1 -1
  41. package/src/executors/index.js +3 -2
  42. package/src/executors/opencode-go.js +46 -39
  43. package/src/executors/opencode.js +54 -31
  44. package/src/handlers/chatCore.js +3 -2
  45. package/src/providers/registry/index.js +5 -4
  46. package/src/providers/registry/opencode-go.js +16 -22
  47. package/src/providers/registry/opencode-zen.js +34 -0
  48. package/src/providers/registry/opencode.js +16 -12
  49. package/src/routes/api/providers/[id]/models/route.js +28 -0
  50. package/src/routes/api/providers/[id]/test/testUtils.js +15 -6
  51. package/src/routes/api/providers/catalog/route.js +3 -1
  52. package/src/routes/api/providers/suggested-models/filters.js +7 -2
  53. package/src/routes/api/providers/validate/route.js +14 -11
  54. package/src/types/provider.ts +1 -1
  55. package/src/utils/opencode.js +225 -0
  56. package/dashboard/dist/assets/Login-BeKpipS_.js +0 -1
  57. package/dashboard/dist/assets/Provider-BU7JfTqm.js +0 -4
  58. package/dashboard/dist/assets/QuotaMonitor-HzGK7bcc.js +0 -1
  59. package/dashboard/dist/assets/Usage-eWnrPQ_v.js +0 -4
  60. package/dashboard/dist/assets/index-B6j-9zHy.js +0 -10
  61. package/dashboard/dist/assets/index-C-_l0yYz.css +0 -1
  62. package/dashboard/dist/assets/select-D8pUtMXp.js +0 -1
@@ -0,0 +1,225 @@
1
+ import crypto from "node:crypto";
2
+ import { ANTHROPIC_API_VERSION } from "../providers/shared.js";
3
+
4
+ export const OPENCODE_VERSION = "1.18.31";
5
+ export const OPENCODE_USER_AGENT = `opencode/${OPENCODE_VERSION}`;
6
+
7
+ const OPENCODE_ID_PATTERN = /^(ses|msg)_[0-9a-f]{12}[0-9A-Za-z]{14}$/;
8
+ const TOOL_NAMES = ["bash", "glob", "grep", "read"];
9
+ const TOOL_NAME_SET = new Set(TOOL_NAMES);
10
+ const SESSION_CACHE_TTL_MS = 30 * 60 * 1000;
11
+ const MAX_SESSION_CACHE_SIZE = 5000;
12
+ const sessionCache = new Map();
13
+ let idCounter = 0;
14
+ let lastTimestamp = 0;
15
+
16
+ function readHeader(headers, name) {
17
+ if (!headers || typeof headers !== "object") return "";
18
+ const wanted = name.toLowerCase();
19
+ const key = Object.keys(headers).find((candidate) => candidate.toLowerCase() === wanted);
20
+ const value = key ? headers[key] : "";
21
+ return typeof value === "string" ? value.trim() : "";
22
+ }
23
+
24
+ function createOpenCodeId(prefix) {
25
+ const now = Date.now();
26
+ if (now === lastTimestamp) idCounter += 1;
27
+ else {
28
+ lastTimestamp = now;
29
+ idCounter = 1;
30
+ }
31
+
32
+ const current = BigInt(now) * 0x1000n + BigInt(idCounter);
33
+ const value = (~current) & ((1n << 48n) - 1n);
34
+ const timestamp = Array.from({ length: 6 }, (_, index) =>
35
+ Number((value >> BigInt(40 - index * 8)) & 0xffn).toString(16).padStart(2, "0"),
36
+ ).join("");
37
+ const random = crypto.randomBytes(14).toString("base64url").replace(/[-_]/g, "").slice(0, 14);
38
+ return `${prefix}${timestamp}${random.padEnd(14, "0")}`;
39
+ }
40
+
41
+ function trimSessionCache() {
42
+ const now = Date.now();
43
+ for (const [key, entry] of sessionCache) {
44
+ if (now - entry.at > SESSION_CACHE_TTL_MS) sessionCache.delete(key);
45
+ }
46
+ while (sessionCache.size > MAX_SESSION_CACHE_SIZE) {
47
+ sessionCache.delete(sessionCache.keys().next().value);
48
+ }
49
+ }
50
+
51
+ export function isOpenCodeId(value, prefix = null) {
52
+ if (typeof value !== "string" || !OPENCODE_ID_PATTERN.test(value)) return false;
53
+ return !prefix || value.startsWith(`${prefix}_`);
54
+ }
55
+
56
+ export function resolveOpenCodeSession(credentials = {}) {
57
+ const rawHeaders = credentials.rawHeaders || {};
58
+ const supplied = readHeader(rawHeaders, "x-opencode-session");
59
+ if (isOpenCodeId(supplied, "ses")) return supplied;
60
+
61
+ trimSessionCache();
62
+ const source = supplied || credentials._clientSessionId || "default";
63
+ const key = `${credentials.connectionId || credentials.id || "public"}:${source}`;
64
+ const existing = sessionCache.get(key);
65
+ if (existing) {
66
+ existing.at = Date.now();
67
+ return existing.value;
68
+ }
69
+
70
+ const value = createOpenCodeId("ses_");
71
+ sessionCache.set(key, { value, at: Date.now() });
72
+ return value;
73
+ }
74
+
75
+ export function buildOpenCodeHeaders(credentials = {}, stream = true, { authorization = "public", format = "openai" } = {}) {
76
+ const rawHeaders = credentials.rawHeaders || {};
77
+ const providerSpecificData = credentials.providerSpecificData || {};
78
+ const token = credentials.apiKey || credentials.accessToken || authorization;
79
+ const project = readHeader(rawHeaders, "x-opencode-project") || providerSpecificData.projectId;
80
+ const headers = {
81
+ "Content-Type": "application/json",
82
+ Authorization: `Bearer ${token || "public"}`,
83
+ "User-Agent": OPENCODE_USER_AGENT,
84
+ "x-opencode-client": "desktop",
85
+ "x-opencode-session": resolveOpenCodeSession(credentials),
86
+ "x-opencode-request": createOpenCodeId("msg_"),
87
+ };
88
+
89
+ if (format === "claude") headers["anthropic-version"] = ANTHROPIC_API_VERSION;
90
+ if (project) headers["x-opencode-project"] = String(project);
91
+ if (stream) headers.Accept = "text/event-stream";
92
+ return headers;
93
+ }
94
+
95
+ function toolName(tool) {
96
+ return typeof tool?.function?.name === "string"
97
+ ? tool.function.name
98
+ : typeof tool?.name === "string"
99
+ ? tool.name
100
+ : "";
101
+ }
102
+
103
+ function normalizedToolName(name) {
104
+ const normalized = typeof name === "string" ? name.trim().toLowerCase() : "";
105
+ return TOOL_NAME_SET.has(normalized) ? normalized : "";
106
+ }
107
+
108
+ function renameTool(tool, name, format) {
109
+ if (format === "claude") return { ...tool, name };
110
+ if (format === "responses") return { ...tool, name };
111
+ return {
112
+ ...tool,
113
+ function: { ...(tool.function || {}), name },
114
+ };
115
+ }
116
+
117
+ function decoyTool(name, format) {
118
+ const description = "OpenCode compatibility tool";
119
+ const parameters = { type: "object", properties: {} };
120
+ if (format === "claude") return { name, description, input_schema: parameters };
121
+ if (format === "responses") return { type: "function", name, description, parameters };
122
+ return { type: "function", function: { name, description, parameters } };
123
+ }
124
+
125
+ function toolChoiceName(choice, format) {
126
+ if (format === "claude") return choice?.name || "";
127
+ if (format === "responses") return choice?.name || "";
128
+ return choice?.function?.name || (typeof choice === "string" ? choice : "");
129
+ }
130
+
131
+ function renameToolChoice(choice, name, format) {
132
+ if (typeof choice === "string") return name;
133
+ if (!choice || typeof choice !== "object") return choice;
134
+ if (format === "claude" || format === "responses") return { ...choice, name };
135
+ return { ...choice, function: { ...(choice.function || {}), name } };
136
+ }
137
+
138
+ function normalizeTools(tools, format) {
139
+ const normalized = [];
140
+ const seen = new Set();
141
+ for (const tool of Array.isArray(tools) ? tools : []) {
142
+ if (!tool || typeof tool !== "object") continue;
143
+ const compatibilityName = normalizedToolName(toolName(tool));
144
+ const next = compatibilityName ? renameTool(tool, compatibilityName, format) : tool;
145
+ const identity = toolName(next) || JSON.stringify(next);
146
+ if (seen.has(identity)) continue;
147
+ seen.add(identity);
148
+ normalized.push(next);
149
+ }
150
+
151
+ for (const name of TOOL_NAMES) {
152
+ if (!normalized.some((tool) => toolName(tool) === name)) normalized.push(decoyTool(name, format));
153
+ }
154
+
155
+ return normalized.sort((left, right) => toolName(left).localeCompare(toolName(right)));
156
+ }
157
+
158
+ function stripEncryptedReasoning(value) {
159
+ if (!value || typeof value !== "object") return;
160
+ if (Array.isArray(value)) {
161
+ value.forEach(stripEncryptedReasoning);
162
+ return;
163
+ }
164
+ delete value.encrypted_content;
165
+ delete value.reasoning_encrypted_content;
166
+ Object.values(value).forEach(stripEncryptedReasoning);
167
+ }
168
+
169
+ export function applyOpenCodeFingerprint(body, format = "openai", { forceStream = false } = {}) {
170
+ const next = body && typeof body === "object" ? body : {};
171
+ const hadCallerTools = Array.isArray(next.tools) && next.tools.length > 0;
172
+ const tools = normalizeTools(next.tools, format);
173
+ next.tools = tools;
174
+
175
+ if (format === "responses") {
176
+ if (forceStream) next.stream = true;
177
+ next.store = false;
178
+ stripEncryptedReasoning(next.input);
179
+ if (!next.tool_choice) next.tool_choice = "auto";
180
+ } else if (format === "claude") {
181
+ if (forceStream) next.stream = true;
182
+ if (!next.tool_choice) next.tool_choice = { type: "auto" };
183
+ } else {
184
+ if (forceStream) next.stream = true;
185
+ if (!hadCallerTools && !next.tool_choice) next.tool_choice = "none";
186
+ }
187
+
188
+ const currentChoiceName = toolChoiceName(next.tool_choice, format);
189
+ const normalizedChoiceName = normalizedToolName(currentChoiceName);
190
+ if (normalizedChoiceName && currentChoiceName !== normalizedChoiceName) {
191
+ next.tool_choice = renameToolChoice(next.tool_choice, normalizedChoiceName, format);
192
+ }
193
+ return next;
194
+ }
195
+
196
+ export const OPENCODE_FREE_MODELS = [
197
+ { id: "mimo-v2.5-free", name: "MiMo V2.5 Free" },
198
+ { id: "ling-3.0-flash-fin-free", name: "Ling 3.0 Flash Fin Free" },
199
+ { id: "nemotron-3-ultra-free", name: "Nemotron 3 Ultra Free" },
200
+ { id: "nemotron-3.5-lightning-free", name: "Nemotron 3.5 Lightning Free" },
201
+ { id: "muse-spark-1.3-contributor-free", name: "Muse Spark 1.3 Contributor Free", targetFormat: "openai-responses" },
202
+ { id: "muse-spark-1.2-contributor-free", name: "Muse Spark 1.2 Contributor Free", targetFormat: "openai-responses" },
203
+ { id: "big-pickle", name: "Big Pickle" },
204
+ ];
205
+
206
+ export const OPENCODE_GO_MODELS = [
207
+ { id: "grok-4.5", name: "Grok 4.5", targetFormat: "openai-responses" },
208
+ { id: "glm-5.3", name: "GLM 5.3" },
209
+ { id: "glm-5.2", name: "GLM 5.2" },
210
+ { id: "glm-5.1", name: "GLM 5.1" },
211
+ { id: "gpt-5.6-luna", name: "GPT 5.6 Luna" },
212
+ { id: "kimi-k3", name: "Kimi K3" },
213
+ { id: "kimi-k2.7", name: "Kimi K2.7" },
214
+ { id: "kimi-k2.6", name: "Kimi K2.6" },
215
+ { id: "mimo-v2.5", name: "MiMo V2.5" },
216
+ { id: "mimo-v2.5-pro", name: "MiMo V2.5 Pro" },
217
+ { id: "minimax-m3", name: "MiniMax M3", targetFormat: "claude" },
218
+ { id: "minimax-m2.7", name: "MiniMax M2.7", targetFormat: "claude" },
219
+ { id: "qwen3.8", name: "Qwen 3.8" },
220
+ { id: "qwen3.7", name: "Qwen 3.7" },
221
+ { id: "qwen3.6", name: "Qwen 3.6" },
222
+ { id: "deepseek-v4-pro", name: "DeepSeek V4 Pro" },
223
+ { id: "deepseek-v4-flash", name: "DeepSeek V4 Flash" },
224
+ { id: "hy3", name: "Hy3" },
225
+ ];
@@ -1 +0,0 @@
1
- import{d as b,r as t,j as e}from"./react-vendor-xnYrwzsL.js";import{u as d,f as j,I as v,T as N,l as y,g as S}from"./index-B6j-9zHy.js";import{R as P}from"./ripple-button-l8aMiVVG.js";import{C as A,a as C,b as E,c as T}from"./card-CC0Omjcv.js";import{a8 as R,a9 as k}from"./icons-vendor-CUx7SB5V.js";import"./query-vendor-DVevaSVS.js";import"./ui-vendor-BuM9f2NY.js";import"./motion-vendor-g5fpGzmJ.js";function B(){const n=b(),m=d(s=>s.setToken),f=d(s=>s.setAuthMeta),[l,h]=t.useState(""),[a,x]=t.useState(!1),[i,c]=t.useState(!1),[o,u]=t.useState(null),[p,g]=t.useState(!1);t.useEffect(()=>{let s=!1;return j().then(r=>{s||g(r.defaultPasswordActive)}).catch(()=>{}),()=>{s=!0}},[]);async function w(s){s.preventDefault(),c(!0),u(null);try{if((await y(l)).mustChangePassword){n("/setup",{replace:!0});return}m("dashboard-session"),f({authenticated:!0,hasPassword:!0}),n("/dashboard",{replace:!0})}catch(r){u(S(r,"Login failed"))}finally{c(!1)}}return e.jsx("div",{className:"flex min-h-svh w-full items-center justify-center bg-background p-4",children:e.jsxs(A,{className:"w-full max-w-sm border-border bg-card",children:[e.jsxs(C,{className:"text-center",children:[e.jsx("img",{src:"/logo/sway.svg",alt:"Sway Router",className:"mx-auto mb-2 h-12 w-12 rounded-xl object-contain"}),e.jsx(E,{className:"text-xl",children:"Sway Router"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Dashboard login"})]}),e.jsx(T,{children:e.jsxs("form",{onSubmit:w,className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(v,{type:a?"text":"password",placeholder:"Password",value:l,onChange:s=>h(s.target.value),autoFocus:!0,required:!0,className:"pr-10"}),e.jsx("button",{type:"button",onClick:()=>x(!a),className:"absolute right-1 top-1/2 grid size-8 -translate-y-1/2 place-items-center rounded-md text-muted-foreground transition-colors hover:bg-surface-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":a?"Hide password":"Show password","aria-pressed":a,children:a?e.jsx(R,{className:"h-4 w-4"}):e.jsx(k,{className:"h-4 w-4"})})]}),p&&!o?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["First login? The default password is"," ",e.jsx("code",{className:"rounded bg-surface px-1 py-0.5 font-mono text-xs",children:"123456"}),". Set a new one after signing in."]}):null,o?e.jsx("p",{className:"text-sm text-destructive",children:o}):null,e.jsx(P,{type:"submit",className:"w-full",disabled:i,children:i?e.jsx(N,{children:"Authenticating…"}):"Login"})]})})]})})}export{B as default};
@@ -1,4 +0,0 @@
1
- import{j as e,r as o}from"./react-vendor-xnYrwzsL.js";import{u as Ss,a as ct,d as As,b as es}from"./query-vendor-DVevaSVS.js";import{H as Ts}from"./Header-C_9Su9BF.js";import{R as E}from"./ripple-button-l8aMiVVG.js";import{I as ne,T as ln,c as ce,D as Ut,m as $t,n as Qt,o as Vt,q as Wt,g as Z,v as kn,s as wn,b as Ms,e as ee,S as Jn,w as hs,h as Qn,x as Ps,y as Ct,z as Es,A as Ls,t as kt,C as _t,a as ts,E as Is}from"./index-B6j-9zHy.js";import{g as Ks,s as Rs,a as Os,r as Fs,b as ns,c as Ds,p as qs,d as fs,t as ss,e as zs,f as Bs,h as ps,u as _s,i as zn,j as Us,k as is,l as rs,m as $s,n as Bn,o as an,q as Qs,v as Vs,w as Ws,x as Js,y as Hs,z as Gs,A as Ys}from"./connections-api-_N54UD3S.js";import{a as Xs,c as Zs,u as ei,d as ti,l as ni}from"./admin-extras-api-CCdu5TFM.js";import{b as si,d as ii,v as as,e as ri,f as ai,a as oi,h as os,i as li}from"./oauth-callback-CqYQzyd7.js";import{S as Pe}from"./StatusBadge-1nAOyHU2.js";import{S as ci,a as di,b as ui,c as mi}from"./select-D8pUtMXp.js";import{S as jt}from"./segmented-CqmEnQjZ.js";import{ag as Sn,ad as Hn,L as cn,X as Gn,q as xs,ah as hi,ai as fi,aj as pi,ak as xi,a8 as gi,a9 as vi,ac as An,al as yi,am as bi,an as wi,ao as ki,af as jn,A as ji,ab as Ci,ap as Ni,aq as Si,h as gs}from"./icons-vendor-CUx7SB5V.js";import{A as Yn,m as dt}from"./motion-vendor-g5fpGzmJ.js";import{T as vs,a as ys,b as Cn,c as bs}from"./tabs-C6YkuulG.js";import{F as ws,a as ks,c as js}from"./frame-cUiti6Lq.js";import{S as Ai}from"./skeleton-7uJDiIXe.js";import{F as Ti}from"./flip-button-BGgkjtl0.js";import{C as Mi}from"./checkbox-7SZBrmbN.js";import"./ui-vendor-BuM9f2NY.js";function Tn(s,n){if(n)return"Connect";const i=(s||"apikey").toLowerCase();return i.includes("oauth")||i.includes("device")||i.includes("import")||i==="local"?"Connect":"Add connection"}function Pi(s,n){return Tn(s,n)==="Add connection"?"Add":"Connect"}const Ei=[{value:"builder-id",label:"Builder ID",mobileLabel:"Builder ID",description:"Personal AWS account"},{value:"iam",label:"AWS IAM",mobileLabel:"AWS IAM",description:"Enterprise AWS SSO"},{value:"api-key",label:"API Key",mobileLabel:"API Key",description:"Long-lived Kiro / CodeWhisperer key"},{value:"import-token",label:"Token",mobileLabel:"Token",description:"Paste a refresh token from Kiro"},{value:"cli-proxy",label:"CLIProxyAPI",mobileLabel:"CLI Proxy",description:"Paste auth JSON from CLIProxyAPI / Kiro"}];function Li({value:s,region:n,startUrl:i,onChange:a,onRegionChange:u,onStartUrlChange:c}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(jt,{size:"sm",value:s,onChange:a,options:Ei.map(h=>({value:h.value,label:h.label,mobileLabel:h.mobileLabel,hint:h.description})),className:"w-full"}),s==="iam"?e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[e.jsx(ne,{placeholder:"AWS region (default: us-east-1)",value:n,onChange:h=>u(h.target.value)}),e.jsx(ne,{placeholder:"AWS Start URL (https://...)",value:i,onChange:h=>c(h.target.value)})]}):null]})}function Ii({mode:s,refreshToken:n,clientId:i,clientSecret:a,profileArn:u,cliProxyJson:c,onRefreshTokenChange:h,onClientIdChange:y,onClientSecretChange:C,onProfileArnChange:N,onCliProxyJsonChange:K}){return s==="import-token"?e.jsxs("div",{className:"space-y-2",children:[e.jsx("textarea",{className:"min-h-28 w-full rounded-md border border-input bg-surface px-3 py-2 font-mono text-base focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring sm:text-sm",placeholder:"Kiro refresh token (aorAAAAAG...)",value:n,onChange:A=>h(A.target.value)}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[e.jsx(ne,{placeholder:"Client ID (optional for IAM)",value:i,onChange:A=>y(A.target.value)}),e.jsx(ne,{type:"password",placeholder:"Client secret (optional for IAM)",value:a,onChange:A=>C(A.target.value)})]}),e.jsx(ne,{placeholder:"Profile ARN (optional)",value:u,onChange:A=>N(A.target.value)})]}):s==="cli-proxy"?e.jsx("textarea",{className:"min-h-36 w-full rounded-md border border-input bg-surface px-3 py-2 font-mono text-base focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring sm:text-sm",placeholder:"Paste CLIProxyAPI Kiro auth JSON…",value:c,onChange:A=>K(A.target.value)}):null}function Ki({region:s,onChange:n}){return e.jsx(ne,{placeholder:"AWS region (default: us-east-1)",value:s,onChange:i=>n(i.target.value)})}function Ri({authLabel:s,apiKey:n,region:i,checking:a,keyValid:u,checkMsg:c,submitError:h,proxyPoolId:y,proxyOptions:C,showKiroRegion:N,onApiKeyChange:K,onRegionChange:A,onCheck:b,onProxyPoolChange:F}){var z;return e.jsxs("div",{className:"space-y-2",children:[N?e.jsx(Ki,{region:i,onChange:A}):null,e.jsx("label",{htmlFor:"connection-api-key",className:"text-xs font-medium text-muted-foreground",children:s}),e.jsx(ne,{id:"connection-api-key",type:"password",placeholder:"API Key",value:n,"aria-invalid":!!h,"aria-describedby":h?"connection-submit-error":void 0,onChange:T=>K(T.target.value)}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(E,{size:"sm",variant:"outline",disabled:!n.trim()||a,onClick:()=>void b(),children:a?e.jsx(ln,{children:"Checking…"}):"Check"}),u===!0?e.jsx(Pe,{tone:"ok",children:"Valid"}):u===!1?e.jsx(Pe,{tone:"err",children:"Invalid"}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"Validate before add"})]}),c&&u===!1?e.jsx("p",{className:ce("text-xs",u?"text-success":"text-destructive"),children:c}):null,e.jsxs("div",{children:[e.jsx("label",{className:"mb-1 block text-xs text-muted-foreground",children:"Proxy pool"}),e.jsxs(ci,{value:y,onValueChange:T=>F(T??"pool_none"),children:[e.jsx(di,{className:"w-full",children:e.jsx("span",{className:"truncate",children:((z=C.find(T=>T.id===y))==null?void 0:z.name)??"None (direct)"})}),e.jsx(ui,{children:C.map(T=>e.jsx(mi,{value:T.id,children:T.name},T.id))})]})]})]})}function Oi({isDeviceFlow:s,isOAuthFlow:n,isKiroIam:i,authLink:a,userCode:u,deviceStatus:c,deviceCode:h,bootLoading:y,linkCopied:C,oauthCode:N,kiroStartUrl:K,onStartKiroAuthorization:A,onOpenAuthLink:b,onCopyAuthLink:F,onOauthCodeChange:z}){return e.jsxs("div",{className:"space-y-2 rounded-lg border border-border bg-surface p-3",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:s?"Verification":"Authorize"}),a?e.jsx("code",{className:"block break-all rounded-md border border-border bg-background px-2.5 py-2 font-mono text-[11px] text-foreground",children:a}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"No auth URL yet"}),s&&u?e.jsxs("p",{className:"text-sm",children:["User code:"," ",e.jsx("span",{className:"font-mono text-base font-semibold tracking-wider text-foreground",children:u})]}):null,s&&c?e.jsx("p",{className:"text-xs text-muted-foreground",children:c}):null,e.jsxs("div",{className:"flex flex-wrap gap-2 pt-1",children:[i&&!h?e.jsx(E,{size:"sm",onClick:()=>void A(),disabled:y||!K.trim(),children:"Start authorization"}):null,e.jsx(E,{size:"sm",onClick:b,disabled:!a,children:"Open in browser"}),e.jsx(E,{size:"sm",variant:"outline",onClick:()=>void F(),disabled:!a,children:C?e.jsxs(e.Fragment,{children:[e.jsx(Sn,{className:"h-3.5 w-3.5"}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(Hn,{className:"h-3.5 w-3.5"}),"Copy link"]})})]}),n?e.jsxs("div",{className:"space-y-1.5 pt-1",children:[e.jsx("label",{className:"block text-xs text-muted-foreground",children:"Fallback: paste the authorization code manually if needed"}),e.jsx(ne,{className:"font-mono text-xs",placeholder:"code from /callback",value:N,onChange:T=>z(T.target.value)})]}):null,e.jsx("p",{className:"text-[11px] text-muted-foreground",children:n?"Open the link → finish sign-in. The callback auto-saves the connection and updates this dialog. Manual code paste is available if needed.":"Open the link, enter the user code, authorize — this dialog polls automatically."})]})}function Fi({value:s,modes:n,onChange:i,label:a}){return e.jsx(jt,{size:"sm",value:s,onChange:i,options:n.map(u=>({value:u,label:a(u)})),className:"w-full"})}function Di({value:s,onChange:n}){return e.jsx(vs,{value:s,onValueChange:i=>n(i),children:e.jsxs(ys,{className:"w-full",children:[e.jsx(Cn,{value:"single",className:"flex-1",children:"Single API Key"}),e.jsx(Cn,{value:"bulk",className:"flex-1",children:"Bulk API Key"})]})})}function qi({raw:s,rows:n,activeIndex:i,activeRow:a,checking:u,validCount:c,onRawChange:h,onCheck:y}){return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:["1 key per line; optionally use ",e.jsx("code",{children:"name|key"}),". Unnamed rows receive ",e.jsx("code",{children:"swayrouter-account1…N"})," automatically."]}),e.jsx("textarea",{id:"bulk-api-keys",className:"min-h-36 w-full rounded-md border border-input bg-surface px-3 py-2 font-mono text-base focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring sm:text-xs",placeholder:`name|sk-1
2
- sk-2`,value:s,onChange:C=>h(C.target.value)}),u&&a?e.jsx("div",{className:"overflow-hidden px-1",role:"status","aria-live":"polite",children:e.jsx(Yn,{initial:!1,mode:"wait",children:e.jsxs(dt.div,{initial:{opacity:0,y:14},animate:{opacity:1,y:0},exit:{opacity:0,y:-14},transition:{duration:.32,ease:"easeOut"},className:"flex min-h-8 items-center gap-2 px-2 py-1 text-xs",children:[a.checking?e.jsx(cn,{className:"h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground"}):a.valid===!0?e.jsx(Sn,{className:"h-3.5 w-3.5 shrink-0 text-success"}):e.jsx(Gn,{className:"h-3.5 w-3.5 shrink-0 text-destructive"}),e.jsx("span",{className:"shrink-0 font-medium",children:a.checking?"Checking":a.valid===!0?"Valid":"Error"}),e.jsx("span",{className:"min-w-0 truncate font-medium",children:a.name}),e.jsxs("span",{className:"min-w-0 flex-1 truncate font-mono text-muted-foreground",children:[a.apiKey.slice(0,14),"…"]}),e.jsxs("span",{className:"shrink-0 text-muted-foreground",children:[(i??0)+1," / ",n.length]})]},`${i}-${a.checking?"checking":a.valid===!0?"valid":"error"}`)})}):!u&&n.length>0?e.jsxs(dt.div,{initial:{opacity:0,y:6},animate:{opacity:1,y:0},transition:{duration:.2,ease:"easeOut"},className:"flex flex-wrap items-center gap-2 px-0 py-0 text-xs",role:"status","aria-live":"polite",children:[e.jsxs(Pe,{tone:"ok",children:["Valid: ",c," API Key"]}),e.jsxs(Pe,{tone:"err",children:["Error: ",n.filter(C=>C.valid===!1).length," API Key"]})]}):null,e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.jsx(E,{size:"sm",variant:"outline",disabled:!s.trim()||u,onClick:()=>void y(),children:u?e.jsxs("span",{className:"inline-flex items-center gap-0.5",children:[e.jsx("span",{children:"Checking"}),e.jsxs("span",{className:"inline-flex w-3 justify-start","aria-hidden":"true",children:[e.jsx("span",{className:"animate-pulse",children:"."}),e.jsx("span",{className:"animate-pulse [animation-delay:150ms]",children:"."}),e.jsx("span",{className:"animate-pulse [animation-delay:300ms]",children:"."})]})]}):"Check all"})})]})}function zi({providerId:s,token:n,machineId:i,importing:a,message:u,hasError:c,onTokenChange:h,onMachineIdChange:y,onAutoImport:C}){return e.jsxs("div",{className:"space-y-2",children:[s==="cursor"?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(E,{size:"sm",variant:"outline",disabled:a,onClick:()=>void C(),children:a?e.jsx(ln,{children:"Detecting…"}):"Auto-detect from this device"}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Reads Cursor's local state.vscdb"})]}),u?e.jsx("p",{className:ce("text-xs",c?"text-destructive":"text-success"),role:"status",children:u}):null]}):null,e.jsx("textarea",{className:"min-h-28 w-full rounded-md border border-input bg-surface px-3 py-2 font-mono text-base focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring sm:text-sm",placeholder:"Access token…",value:n,onChange:N=>h(N.target.value)}),s==="cursor"?e.jsx(ne,{placeholder:"Machine ID (cursorAuth machine id)",value:i,onChange:N=>y(N.target.value)}):null]})}function Bi({raw:s,rows:n,activeIndex:i,activeRow:a,onRawChange:u,onCheck:c,validCount:h,checking:y}){return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:["One account per line. Supported formats: ",e.jsx("code",{children:"accessToken"}),", ",e.jsx("code",{children:"refreshToken"}),", or ",e.jsx("code",{children:"accessToken|refreshToken"}),". A single token is detected automatically. Multiple accounts receive automatic names."]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{htmlFor:"codebuddy-token",className:"text-xs font-medium text-muted-foreground",children:"Access / Refresh Tokens"}),e.jsx("textarea",{id:"codebuddy-token",className:"min-h-36 w-full resize-y overflow-x-auto whitespace-pre rounded-md border border-input bg-surface px-3 py-2 font-mono text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",placeholder:`access-token-1
3
- refresh-token-2
4
- access-token-3|refresh-token-3`,value:s,autoComplete:"off",spellCheck:!1,wrap:"off",onChange:C=>u(C.target.value)})]}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.jsx(E,{size:"sm",variant:"outline",disabled:!s.trim()||y,onClick:()=>void c(),children:y?e.jsx(ln,{children:"Checking…"}):"Check all"})}),y&&a?e.jsx("div",{className:"overflow-hidden px-1",role:"status","aria-live":"polite",children:e.jsx(Yn,{initial:!1,mode:"wait",children:e.jsxs(dt.div,{initial:{opacity:0,y:14},animate:{opacity:1,y:0},exit:{opacity:0,y:-14},transition:{duration:.2,ease:"easeOut"},className:"flex min-h-8 items-center gap-2 px-2 py-1 text-xs",children:[a.checking?e.jsx(cn,{className:"h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground"}):a.valid===!0?e.jsx(Sn,{className:"h-3.5 w-3.5 shrink-0 text-success"}):e.jsx(Gn,{className:"h-3.5 w-3.5 shrink-0 text-destructive"}),e.jsx("span",{className:"shrink-0 font-medium",children:a.checking?"Checking":a.valid===!0?"Valid":"Error"}),e.jsxs("span",{className:"min-w-0 flex-1 truncate",children:["Account ",(i??0)+1]}),e.jsxs("span",{className:"shrink-0 text-muted-foreground",children:[(i??0)+1," / ",n.length]})]},`${i}-${a.checking?"checking":a.valid===!0?"valid":"error"}`)})}):!y&&n.length>0?e.jsxs(dt.div,{initial:{opacity:0,y:6},animate:{opacity:1,y:0},transition:{duration:.2,ease:"easeOut"},className:"flex flex-wrap items-center gap-2 px-0 py-0 text-xs",role:"status","aria-live":"polite",children:[e.jsxs(Pe,{tone:"ok",children:["Valid: ",h," account",h===1?"":"s"]}),e.jsxs(Pe,{tone:"err",children:["Error: ",n.filter(C=>C.valid===!1).length," account",n.filter(C=>C.valid===!1).length===1?"":"s"]})]}):null,s.trim()?null:e.jsx("p",{className:"text-xs text-muted-foreground",role:"status",children:"At least one access token or refresh token is required."})]})}function _i(s){return s.split(/\r?\n/).map(n=>n.trim()).filter(Boolean).map(n=>{const i=n.split("|").map(a=>a.trim());return i.length===1&&i[0]?{credentialToken:i[0],valid:null}:i.length===2&&i[0]&&i[1]?{accessToken:i[0],refreshToken:i[1],valid:null}:{valid:!1,msg:"Use one token or accessToken|refreshToken"}})}const Ui=new Set(["claude","codex","xai"]),$i=200,Qi=1e3;function Vi({open:s,provider:n,flow:i,onOpenChange:a,onSubmit:u}){var yn;const[c,h]=o.useState(""),[y,C]=o.useState(""),[N,K]=o.useState(""),[A,b]=o.useState(""),[F,z]=o.useState(""),[T,G]=o.useState(""),[U,_]=o.useState("pool_none"),[Y,$]=o.useState(()=>[{id:"pool_none",name:"None (direct)"}]),[fe,R]=o.useState(!1),[Ee,Le]=o.useState(!1),[Ie,pe]=o.useState(null),[ze,te]=o.useState(null),[xe,B]=o.useState(null),[O,ie]=o.useState(null),[re,ge]=o.useState(null),[Ke,L]=o.useState(null),[S,ae]=o.useState(null),[ut,Qe]=o.useState(5),[Re,oe]=o.useState(null),[ke,Ve]=o.useState(null),[Ye,mt]=o.useState(null),[Xe,Nt]=o.useState(null),[me,St]=o.useState("builder-id"),[ht,At]=o.useState("us-east-1"),[Ht,Tt]=o.useState(""),[Gt,ft]=o.useState(""),[dn,Mt]=o.useState(""),[Ze,Oe]=o.useState(""),[Pt,Yt]=o.useState(""),[Et,Lt]=o.useState(""),[pt,Be]=o.useState(!1),[Mn,et]=o.useState(null),[Pn,tt]=o.useState(!1),[le,nt]=o.useState("single"),[xt,st]=o.useState(""),[It,je]=o.useState([]),[Kt,gt]=o.useState(!1),[Xt,ye]=o.useState(null),[Rt,Zt]=o.useState(!1),[Fe,We]=o.useState([]),[vt,De]=o.useState(!1),[it,Ce]=o.useState(null);function Ot(m,p){return p==="apikey"?m==="qoder"?"API Key (PAT)":"API Key":p==="device"?"Device Code":p==="import"?m==="codebuddy-cn"||m==="codebuddy-intl"?"AT/RT":"Import Token":p}const[Ft,de]=o.useState(null),[en,_e]=o.useState(!1),[Dt,Ne]=o.useState(!1),[P,rt]=o.useState(!1),H=o.useRef(!1),Je=o.useRef(null),be=o.useRef(!1),qt=o.useRef(null),d=o.useRef(null);function Se(m=!1){rt(m)}function se(){d.current&&(clearTimeout(d.current),d.current=null)}function we(){const m=qt.current;qt.current=null,m&&!m.closed&&m.close()}function He(m){const p=Je.current;!p||m&&p!==m||(Je.current=null,Se(!1),p&&Ds(p).catch(()=>{}))}const he=o.useRef(u);he.current=u;const Ae=o.useRef(c);Ae.current=c;const J=(n==null?void 0:n.id)==="kiro",yt=(n==null?void 0:n.id)==="codebuddy-cn"||(n==null?void 0:n.id)==="codebuddy-intl",ve=(yn=n==null?void 0:n.authModes)!=null&&yn.length?n.authModes:null,at=!!(ve&&ve.length>1),[tn,un]=o.useState((ve==null?void 0:ve[0])??"auto"),Te=J?me==="api-key"||me==="import-token"||me==="cli-proxy"?me==="api-key"?"apikey":"import":"device":ve&&ve.includes(tn)?tn:i??(ve!=null&&ve.includes("device")?"device":"apikey"),Ge=It.filter(m=>m.valid===!0),mn=Xt===null?null:It[Xt]??null,ot=Fe.filter(m=>m.valid===!0),En=it===null?null:Fe[it]??null;function zt(m){return m.split(/\r?\n/).map(p=>p.trim()).filter(Boolean).map(p=>{const w=p.includes("|")?p.split("|").map(x=>x.trim()):p.includes(",")?p.split(",").map(x=>x.trim()):[p];return{name:w.length>=2?w[0]:"",apiKey:w.length>=2?w[1]:w[0],valid:null,msg:void 0}})}async function hn(){if(!n)return;const m=zt(xt);if(!m.length)return;gt(!0);const p=m.map(x=>({...x,checking:!1})),w=new Set;je([...p]),ye(0);try{for(let x=0;x<p.length;x+=1){ye(x);const M=p[x].apiKey.trim();if(w.has(M)){p[x]={...p[x],valid:!1,checking:!1,msg:"Duplicate API key in this batch"},je([...p]);continue}w.add(M),p[x]={...p[x],checking:!0},je([...p]);try{const D=await ss({provider:n.id,apiKey:p[x].apiKey});p[x]={...p[x],valid:D.valid===!0,checking:!1,msg:D.valid===!0?"ok":D.error||"fail"}}catch(D){p[x]={...p[x],valid:!1,checking:!1,msg:Z(D,"error")}}je([...p]),await new Promise(D=>{window.setTimeout(D,Qi)})}}finally{ye(null),gt(!1)}}async function fn(){if(!(!n||!Ge.length)){Zt(!0),B(null);try{await u({name:n.name,authFlow:"apikey",bulkKeys:Ge.map(({name:m,apiKey:p},w)=>{const x=m.trim();return{name:x||`swayrouter-account${w+1}`,apiKey:p.trim(),autoName:!x}})})}catch(m){B(Z(m,"Failed to add connections"))}finally{Zt(!1)}}}const Q=Te,Ue=Q==="apikey"||!!(n!=null&&n.isCustom),$e=Q==="oauth",lt=Q==="device",nn=$e||lt,pn=Dt&&nn;function xn(m){H.current=!0,se(),St(m),nt("single"),pe(null),te(null),B(null),de(null),ge(null),L(null),ae(null),oe(null),ie(null)}async function gn(){if(!n||n.id!=="kiro")return;const m=me==="iam"?"idc":"builder-id",p=Ht.trim();if(m==="idc"&&!p){de("AWS IAM Identity Center requires a Start URL");return}H.current=!0,se(),Ne(!0),de(null),oe(null),ge(null),L(null),ae(null),ie(null);try{const w=await ns("kiro",{authMethod:m,region:ht.trim()||"us-east-1",startUrl:p||void 0}),x=typeof w.device_code=="string"&&w.device_code||typeof w.deviceCode=="string"&&w.deviceCode||null;if(!x)throw new Error("Kiro did not return a device code");const M=typeof w.user_code=="string"&&w.user_code||typeof w.userCode=="string"&&w.userCode||null,D=typeof w.verification_uri_complete=="string"&&w.verification_uri_complete||typeof w.verificationUriComplete=="string"&&w.verificationUriComplete||typeof w.verification_uri=="string"&&w.verification_uri||typeof w.verificationUri=="string"&&w.verificationUri||null;ge(x),ae(M),ie(D),L(typeof w.codeVerifier=="string"?w.codeVerifier:null),Qe(typeof w.interval=="number"&&w.interval>0?w.interval:5),oe("Waiting for you to authorize…")}catch(w){de(Z(w,"Failed to start Kiro authorization"))}finally{Ne(!1)}}if(o.useEffect(()=>{var m;s&&(un(((m=n==null?void 0:n.authModes)==null?void 0:m[0])??"auto"),St("builder-id"),At("us-east-1"),Tt(""),ft(""),Mt(""),Oe(""),Yt(""),Lt(""),b(""),te(null),Be(!1),et(null),tt(!1),nt("single"),st(""),je([]),ye(null),We([]),De(!1),Ce(null))},[s,n==null?void 0:n.id]),o.useEffect(()=>{if(!s)return;let m=!1;async function p(){try{const w=await Xs();if(m)return;$([{id:"pool_none",name:"None (direct)"},...w.map(x=>({id:x.id,name:String(x.name||x.id)}))])}catch{}}return p(),()=>{m=!0}},[s]),o.useEffect(()=>{if(!s||!n)return;h(""),C(""),K(""),z(""),G(""),_("pool_none"),R(!1),Ne(!1),Le(!1),pe(null),te(null),B(null),_e(!1),de(null),oe(null),ge(null),L(null),ae(null),Ve(null),mt(null),Nt(null),ie(null),nt("single"),st(""),je([]),ye(null),gt(!1),Zt(!1),H.current=!1;const m=n.id;let p=!1;async function w(){if(Q==="oauth"){Ne(!0);try{const x=Ks(m),M=await Rs(m,x);if(p)return;const D=M.authUrl||M.url||M.authorizeUrl||null,t=typeof M.state=="string"?M.state:null,r=typeof M.codeVerifier=="string"?M.codeVerifier:null,l=typeof M.redirectUri=="string"&&M.redirectUri?M.redirectUri:x;ie(typeof D=="string"?D:null),Ve(t),t&&si(t,m),mt(r),Nt(l),be.current=!1;const g=(typeof M.flowType=="string"?M.flowType:null)==="authorization_code_pkce"||Ui.has(m);if(!D||!t||!l||g&&!r)throw new Error("OAuth provider returned incomplete authorization data");if(m==="codex"||m==="xai"){const k=window.location.port||(window.location.protocol==="https:"?"443":"80");try{const f=t,j=r,V=l;if(!f||!j||!V)throw new Error("OAuth provider returned incomplete authorization data");const W=await Os(m,{appPort:k});if(!W.success)throw new Error(W.reason==="port_busy"?"The OAuth callback port is already in use":"The OAuth callback listener could not start");if(Je.current=m,Se(!1),(await Fs(m,{state:f,codeVerifier:j,redirectUri:V})).success!==!0)throw new Error("The OAuth session could not be registered");if(p)return;Se(!0)}catch(f){de(Z(f,"Automatic callback setup unavailable. Paste the browser callback code below.")),He(m)}}}catch(x){p||de(Z(x,"Failed to start OAuth"))}finally{p||Ne(!1)}return}if(Q==="device"){if(m==="kiro"){me==="builder-id"&&gn();return}Ne(!0);try{const x=await ns(n.id);if(p)return;const M=typeof x.device_code=="string"&&x.device_code||typeof x.deviceCode=="string"&&x.deviceCode||null,D=typeof x.user_code=="string"&&x.user_code||typeof x.userCode=="string"&&x.userCode||null,t=typeof x.verification_uri_complete=="string"&&x.verification_uri_complete||typeof x.verificationUriComplete=="string"&&x.verificationUriComplete||typeof x.verification_uri=="string"&&x.verification_uri||typeof x.verificationUri=="string"&&x.verificationUri||null;ge(M),ae(D),ie(t),L(typeof x.codeVerifier=="string"?x.codeVerifier:null);const r=typeof x.interval=="number"&&x.interval>0?x.interval:5;Qe(r),oe("Waiting for you to authorize…")}catch(x){p||de(Z(x,"Failed to start device code"))}finally{p||Ne(!1)}}}return w(),()=>{p=!0,H.current=!0,se(),we(),He(n.id)}},[s,n,Q,me]),o.useEffect(()=>{if(!s||!n||Q!=="oauth"||!P||!ke)return;let m=!1,p=0;const w=n.id,x=n.name,M=ke,D=200,t=async()=>{if(!(m||be.current)){p+=1;try{const r=await qs(w,M);if(m||be.current)return;if(r.status==="done"){be.current=!0,se(),we(),He(w),R(!0);try{await he.current({name:Ae.current.trim()||x,alreadySaved:!0})}catch{de("Connection saved, but the provider list could not refresh")}finally{R(!1)}return}if(r.status==="error"){be.current=!0,se(),we(),He(w),de(r.error||"OAuth sign-in failed");return}}catch{}!m&&!be.current&&p<D?d.current=setTimeout(()=>void t(),1500):!m&&!be.current&&(de("OAuth sign-in timed out. Use the manual code fallback."),He(w))}};return d.current=setTimeout(()=>void t(),750),()=>{m=!0,se()}},[s,n,Q,P,ke]),o.useEffect(()=>{if(!s||!n||Q!=="oauth")return;const m=n.id,p=n.name,w=ke;if(!w)return;let x=window.location.origin;if(Xe)try{x=new URL(Xe).origin}catch{return}const M=f=>as(oi(f),{origin:x,eventOrigin:x,expectedState:w,expectedProvider:m});function D(f){if(!be.current){if(f.error){f.state&&os(f.state),de(f.errorDescription||f.error||"OAuth sign-in failed");return}!f.code||!f.state||(os(f.state),be.current=!0,G(f.code),oe(null),R(!0),(async()=>{try{await he.current({name:Ae.current.trim()||p,authFlow:"oauth",oauthCode:f.code,oauthState:f.state,oauthCodeVerifier:Ye||void 0,oauthRedirectUri:Xe||void 0}),we()}catch(j){be.current=!1,de(Z(j,"OAuth sign-in completed, but the token exchange failed. Restart the connection flow and try again."))}finally{R(!1)}})())}}function t(f){const j=as(f.data,{origin:x,eventOrigin:f.origin,expectedState:w,expectedProvider:m,eventSource:f.source,expectedSource:qt.current});j&&D(j)}const r=w,l=li(r);function v(f){const j=f===void 0?ii(r):ai(f),V=j?M(j):null;V&&D(V)}function g(f){f.key===l&&v(f.newValue)}v(),window.addEventListener("message",t),window.addEventListener("storage",g);const k=window.setInterval(()=>v(),500);return()=>{window.removeEventListener("message",t),window.removeEventListener("storage",g),window.clearInterval(k)}},[s,n,Q,ke,Ye,Xe]),o.useEffect(()=>()=>{H.current=!0,se(),we(),He()},[]),o.useEffect(()=>{if(!s||!n||Q!=="device"||!re)return;H.current=!1;let m=null,p=!1;const w=n.id,x=n.name,M=Ke||void 0,D=Math.max(2,ut)*1e3;async function t(){if(!(p||H.current||!re)){try{const r=await fs(w,{deviceCode:re,codeVerifier:M,displayName:Ae.current.trim()||x});if(p||H.current)return;if(r.success){oe("Authorized — connection saved"),R(!0);try{await he.current({name:Ae.current.trim()||x,alreadySaved:!0})}catch{oe("Authorized — refresh the list if not visible")}finally{R(!1)}return}r.pending?oe("Still waiting for authorization…"):r.error&&oe(r.error)}catch(r){p||oe(Z(r,"Poll failed"))}!p&&!H.current&&(m=setTimeout(t,D))}}return m=setTimeout(t,D),()=>{p=!0,H.current=!0,m&&clearTimeout(m)}},[s,n==null?void 0:n.id,n==null?void 0:n.name,Q,re,Ke,ut]),o.useEffect(()=>{pe(null),te(null),B(null)},[y]),!n)return null;const Ln=Tn(n.authType,n.noAuth),In=Pi(n.authType,n.noAuth),bt=!fe&&!pn&&(Ue?Ie===!0&&y.trim().length>0:Q==="import"?yt?ot.length>0&&!vt:J?me==="import-token"?Gt.trim().length>0:Et.trim().length>0:N.trim().length>0&&((n==null?void 0:n.id)!=="cursor"||F.trim().length>0):Q==="oauth"?T.trim().length>0:Q==="device"?!!re:!0);async function vn(){if(!(!n||!y.trim())){Le(!0),te(null);try{const m=await ss({provider:n.id,apiKey:y.trim(),...J?{providerSpecificData:{region:ht.trim()||"us-east-1"}}:{}}),p=m.valid===!0;pe(p),te(p?"Key valid":m.error||"Key invalid")}catch(m){pe(!1),te(Z(m,"Check failed"))}finally{Le(!1)}}}async function Kn(){if(!n||!A.trim())return;const m=_i(A);if(!m.length)return;De(!0);const p=m.map(x=>({...x,checking:!1})),w=new Set;We([...p]),Ce(0);try{for(let x=0;x<p.length;x+=1){Ce(x);const M=p[x];if(M.valid===!1){We([...p]);continue}const D=M.credentialToken||`${M.accessToken}|${M.refreshToken}`;if(w.has(D)){p[x]={...M,valid:!1,checking:!1,msg:"Duplicate token pair in this batch"},We([...p]);continue}w.add(D),p[x]={...M,checking:!0},We([...p]);try{const t=await zs({provider:n.id,...M.credentialToken?{credentialToken:M.credentialToken}:{accessToken:M.accessToken,refreshToken:M.refreshToken}});p[x]={...M,valid:t.valid===!0,checking:!1,msg:t.valid===!0?"ok":t.error||"Token invalid"}}catch(t){p[x]={...M,valid:!1,checking:!1,msg:Z(t,"Token validation failed")}}We([...p]),x<p.length-1&&await new Promise(t=>{window.setTimeout(t,$i)})}}finally{Ce(null),De(!1)}}async function Rn(){if(!(!n||n.id!=="cursor")){Be(!0),et(null),tt(!1);try{const m=await Bs();if(!m.found||!m.accessToken||!m.machineId)throw new Error(m.error||"Cursor credentials were not found on this device");K(m.accessToken),z(m.machineId),et("Cursor token and Machine ID filled automatically")}catch(m){tt(!0),et(Z(m,"Could not detect Cursor credentials"))}finally{Be(!1)}}}async function On(){if(O)try{await navigator.clipboard.writeText(O),_e(!0),window.setTimeout(()=>_e(!1),1500)}catch{}}function Fn(){if(!O)return;const m=window.open(O,"sway-oauth","popup,width=600,height=700");qt.current=m,m||de("The browser blocked the authorization window. Open the URL above manually or allow popups for this dashboard.")}async function Dn(){if(!(!n||!bt)){R(!0),B(null);try{const m=c.trim(),p=$e?ri(T,ke):null;await u({name:m,autoName:Ue&&!m,authFlow:Q,apiKey:Ue&&y.trim()||void 0,importToken:Q==="import"&&!J&&!yt&&N.trim()||void 0,codeBuddyToken:Q==="import"&&yt&&ot.length===1&&ot[0].credentialToken||void 0,codeBuddyTokens:Q==="import"&&yt?ot.map((w,x)=>{const M=ot.length===1?m:"";return{...w.credentialToken?{credentialToken:w.credentialToken}:{accessToken:w.accessToken,refreshToken:w.refreshToken},name:M||`swayrouter-account${x+1}`,autoName:!M}}):void 0,machineId:Q==="import"&&F.trim()||void 0,kiroAuthMode:J?me:void 0,kiroRegion:J?ht.trim()||"us-east-1":void 0,kiroRefreshToken:J&&Gt.trim()||void 0,kiroClientId:J&&dn.trim()||void 0,kiroClientSecret:J&&Ze.trim()||void 0,kiroProfileArn:J&&Pt.trim()||void 0,kiroCliProxyJson:J&&Et.trim()||void 0,oauthCode:p==null?void 0:p.code,oauthState:p==null?void 0:p.state,oauthCodeVerifier:$e&&Ye||void 0,oauthRedirectUri:$e&&Xe||void 0,deviceCode:lt&&re||void 0,deviceCodeVerifier:lt&&Ke||void 0,proxyPoolId:Ue?U:null})}catch(m){B(Z(m,"Failed to add connection"))}finally{R(!1)}}}const qn=le==="bulk"&&Ue?"Add connections":Ln;return e.jsx(Ut,{open:s,onOpenChange:a,children:e.jsxs($t,{children:[e.jsx(Qt,{children:e.jsxs(Vt,{children:[qn," — ",n.name]})}),e.jsxs("div",{className:ce("px-6",Ue&&le==="bulk"?"space-y-2 pb-4":"space-y-3 pb-4"),children:[!J&&at&&ve?e.jsx(Fi,{value:tn,modes:ve,label:m=>Ot((n==null?void 0:n.id)??"",m),onChange:m=>{un(m),nt("single"),st(""),je([]),ye(null),B(null)}}):null,J?e.jsx(Li,{value:me,region:ht,startUrl:Ht,onChange:xn,onRegionChange:At,onStartUrlChange:Tt}):null,Ue&&!J?e.jsx(Di,{value:le,onChange:nt}):null,Ue&&!J&&le==="bulk"?e.jsx(qi,{raw:xt,rows:It,activeIndex:Xt,activeRow:mn,checking:Kt,validCount:Ge.length,onRawChange:m=>{st(m),je([]),ye(null),B(null)},onCheck:hn}):null,le==="single"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{htmlFor:"connection-account-name",className:"text-xs font-medium text-muted-foreground",children:["Account name ",e.jsx("span",{className:"font-normal text-muted-foreground/70",children:"(optional)"})]}),e.jsx(ne,{id:"connection-account-name",placeholder:"Auto: swayrouter-account",value:c,"aria-invalid":!!xe,"aria-describedby":xe?"connection-submit-error":void 0,onChange:m=>{h(m.target.value),B(null)}})]}),Ft?e.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-2.5 py-2 text-xs text-destructive",children:Ft}):null,pn?e.jsx("p",{className:"text-xs text-muted-foreground",children:e.jsx(ln,{children:"Starting auth flow…"})}):null,Q==="import"?yt?e.jsx(Bi,{raw:A,rows:Fe,activeIndex:it,activeRow:En,checking:vt,validCount:ot.length,onRawChange:m=>{b(m),We([]),Ce(null),B(null)},onCheck:Kn}):J?e.jsx(Ii,{mode:me,refreshToken:Gt,clientId:dn,clientSecret:Ze,profileArn:Pt,cliProxyJson:Et,onRefreshTokenChange:ft,onClientIdChange:Mt,onClientSecretChange:Oe,onProfileArnChange:Yt,onCliProxyJsonChange:Lt}):e.jsx(zi,{providerId:n.id,token:N,machineId:F,importing:pt,message:Mn,hasError:Pn,onTokenChange:K,onMachineIdChange:z,onAutoImport:Rn}):Q==="local"?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Local provider — no key required."}):nn?e.jsx(Oi,{isDeviceFlow:lt,isOAuthFlow:$e,isKiroIam:J&&me==="iam",authLink:O,userCode:S,deviceStatus:Re,deviceCode:re,bootLoading:Dt,linkCopied:en,oauthCode:T,kiroStartUrl:Ht,onStartKiroAuthorization:gn,onOpenAuthLink:Fn,onCopyAuthLink:On,onOauthCodeChange:G}):e.jsx(Ri,{authLabel:Ot(n.id,"apikey"),apiKey:y,region:ht,checking:Ee,keyValid:Ie,checkMsg:ze,submitError:xe,proxyPoolId:U,proxyOptions:Y,showKiroRegion:J,onApiKeyChange:m=>{C(m),B(null)},onRegionChange:At,onCheck:vn,onProxyPoolChange:_}),xe?e.jsx("p",{id:"connection-submit-error",className:"text-xs text-destructive",role:"alert",children:xe}):null]}):null]}),e.jsxs(Wt,{children:[e.jsx(E,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(E,{disabled:le==="bulk"?Rt||Kt||Ge.length===0:!bt,className:ce((le==="bulk"?Rt||Kt||Ge.length===0:!bt)&&"opacity-40"),onClick:()=>void(le==="bulk"?fn():Dn()),children:le==="bulk"?Rt?"Adding…":"Add":fe?e.jsx(ln,{children:lt||$e?"Waiting…":"Saving…"}):lt?"Poll now":$e&&!T.trim()?"Waiting for browser…":In})]})]})})}function ls({open:s,onOpenChange:n,onCreate:i,initial:a,submitLabel:u="Create"}){const[c,h]=o.useState(""),[y,C]=o.useState(""),[N,K]=o.useState(""),[A,b]=o.useState("openai-compatible"),[F,z]=o.useState("chat");o.useEffect(()=>{!s||!a||(h(a.name||""),C(a.alias||""),K(a.baseUrl||""),b(a.nodeType==="anthropic-compatible"?"anthropic-compatible":"openai-compatible"),z(a.apiType==="responses"?"responses":"chat"),Y(null),U(!1))},[s,a]);const T=!!a,[G,U]=o.useState(!1),[_,Y]=o.useState(null);return o.useEffect(()=>{s&&(a||(h(""),C(""),K(""),b("openai-compatible"),z("chat"),Y(null),U(!1)))},[s,a]),e.jsx(Ut,{open:s,onOpenChange:n,children:e.jsxs($t,{children:[e.jsx(Qt,{children:e.jsx(Vt,{children:T?"Edit custom provider":"Custom provider"})}),e.jsxs("div",{className:"space-y-3 px-6 pb-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{htmlFor:"custom-provider-name",className:"text-xs font-medium text-muted-foreground",children:"Name"}),e.jsx(ne,{id:"custom-provider-name",placeholder:"My provider",value:c,"aria-invalid":!!_,"aria-describedby":_?"custom-provider-error":void 0,onChange:$=>{h($.target.value),Y(null)}})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{htmlFor:"custom-provider-prefix",className:"text-xs font-medium text-muted-foreground",children:"Prefix"}),e.jsx(ne,{id:"custom-provider-prefix",placeholder:"my-llm",value:y,"aria-invalid":!!_,"aria-describedby":_?"custom-provider-error":void 0,onChange:$=>{C($.target.value),Y(null)}}),e.jsx("p",{className:"text-[10px] text-muted-foreground/70",children:"Must be unique across custom providers."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{htmlFor:"custom-provider-base-url",className:"text-xs font-medium text-muted-foreground",children:"Base URL"}),e.jsx(ne,{id:"custom-provider-base-url",placeholder:"https://api.example.com/v1",value:N,onChange:$=>K($.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"API format"}),e.jsx(jt,{size:"sm",value:A,onChange:b,options:[{value:"openai-compatible",label:"OpenAI"},{value:"anthropic-compatible",label:"Claude"}]})]}),A==="openai-compatible"?e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Endpoint style (OpenAI only)"}),e.jsx(jt,{size:"sm",value:F,onChange:z,options:[{value:"chat",label:"Chat"},{value:"responses",label:"Responses"}]})]}):e.jsx("p",{className:"rounded-md border border-border bg-surface px-3 py-2 text-xs text-muted-foreground",children:"Claude-compatible nodes use the Messages API only — no Chat / Responses toggle (BACKEND custom nodes)."}),_?e.jsx("p",{id:"custom-provider-error",className:"text-sm text-destructive",role:"alert",children:_}):null]}),e.jsxs(Wt,{children:[e.jsx(E,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(E,{disabled:G,onClick:()=>{if(!c.trim()||!y.trim()){Y("Name and prefix required");return}U(!0),i({name:c.trim(),prefix:y.trim().toLowerCase().replace(/\s+/g,"-"),baseUrl:N.trim()||void 0,type:A,apiType:A==="openai-compatible"?F:void 0}).catch($=>{Y(Z($,"Failed to save custom provider"))}).finally(()=>U(!1))},children:u})]})]})})}function _n({label:s,hint:n,children:i}){return e.jsxs("label",{className:"block space-y-1.5",children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:s}),i,n?e.jsx("span",{className:"block text-[10px] text-muted-foreground/70",children:n}):null]})}function Wi({conn:s,onOpenChange:n,onSave:i}){var $,fe;const[a,u]=o.useState(""),[c,h]=o.useState(!1),[y,C]=o.useState(""),[N,K]=o.useState(null),[A,b]=o.useState(!1);o.useEffect(()=>{s&&(u(s.name||""),C(""),K(null))},[s]);const F=String((s==null?void 0:s.authType)||"").trim().toLowerCase(),z=typeof(($=s==null?void 0:s.providerSpecificData)==null?void 0:$.authMethod)=="string"?s.providerSpecificData.authMethod.trim().toLowerCase():"",T=F||z,G=s?kn(s.provider):"apikey",U=T==="apikey"||T==="api_key"||T==="api-key"||!T&&G==="apikey",_=T.includes("oauth")||T==="access_token"||!T&&(G==="oauth"||G==="device")?"OAuth":T.includes("cookie")?"Cookie":T==="local"||T==="none"||!T&&G==="local"?"No authentication":T.includes("import")||T==="imported"?"Imported token":U?"API Key":T||"Managed credentials";async function Y(){if(s){b(!0),K(null);try{const R=await ps(s.id),Ee=R.valid===!0;K({label:Ee?"Active":R.error||"Failed",ok:Ee})}catch(R){K({label:Z(R,"Test failed"),ok:!1})}finally{b(!1)}}}return e.jsx(Ut,{open:!!s,onOpenChange:n,children:e.jsxs($t,{children:[e.jsxs(Qt,{children:[e.jsx(Vt,{children:"Edit connection"}),e.jsx(wn,{children:(s==null?void 0:s.name)||((fe=s==null?void 0:s.id)==null?void 0:fe.slice(0,8))})]}),e.jsxs("div",{className:"space-y-3 px-6",children:[e.jsx(_n,{label:"Name",children:e.jsx(ne,{value:a,onChange:R=>u(R.target.value)})}),U?e.jsxs(_n,{label:"API Key",hint:"Leave empty to keep current key",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ne,{type:"password",value:y,onChange:R=>C(R.target.value),placeholder:"sk-… or paste new key",className:"flex-1"}),e.jsx(E,{size:"sm",variant:"outline",disabled:A,"aria-busy":A,"aria-label":A?"Testing connection":"Test connection",className:"min-w-14 justify-center",onClick:()=>void Y(),children:A?e.jsx(cn,{className:"h-3.5 w-3.5 animate-spin","aria-hidden":"true"}):"Test"})]}),N?e.jsx("p",{className:ce("mt-1 text-[11px]",N.ok?"text-success":"text-destructive"),children:N.label}):null]}):e.jsxs(_n,{label:"Authentication",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border bg-muted/25 px-3 py-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:_}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Credentials are managed by this connection."})]}),e.jsx(E,{size:"sm",variant:"outline",disabled:A,"aria-busy":A,"aria-label":A?"Testing connection":"Test connection",className:"min-w-14 justify-center",onClick:()=>void Y(),children:A?e.jsx(cn,{className:"h-3.5 w-3.5 animate-spin","aria-hidden":"true"}):"Test"})]}),N?e.jsx("p",{className:ce("mt-1 text-[11px]",N.ok?"text-success":"text-destructive"),children:N.label}):null]})]}),e.jsxs(Wt,{children:[e.jsx(E,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(E,{disabled:c,onClick:()=>{h(!0),i(a.trim(),y).finally(()=>h(!1))},children:"Save"})]})]})})}function Cs({id:s,color:n,size:i=24,fallbackIcon:a}){const u=Ms(s);if(u){const c=Math.max(4,Math.round(i/5));return e.jsx("span",{"aria-hidden":"true",className:"block shrink-0",style:{width:i,height:i,borderRadius:c,backgroundColor:n||"currentColor",WebkitMaskImage:`url(${u})`,maskImage:`url(${u})`,WebkitMaskPosition:"center",maskPosition:"center",WebkitMaskRepeat:"no-repeat",maskRepeat:"no-repeat",WebkitMaskSize:"contain",maskSize:"contain"}})}return e.jsx(a,{className:"shrink-0",style:{width:i*.85,height:i*.85,color:n||void 0}})}function Ji({byProvider:s,filter:n,hiddenProviders:i,loading:a,query:u,providerListRef:c,selectedId:h,sorted:y,onFilterChange:C,onQueryChange:N,onSelectProvider:K,onToggleProviderHidden:A}){return e.jsxs(ws,{className:ce("flex shrink-0 flex-col overflow-hidden","w-full h-[24dvh] max-h-[24dvh] min-h-0 sm:h-[30dvh] sm:max-h-[30dvh] lg:h-full lg:max-h-none lg:min-h-0 lg:w-[300px] xl:w-[340px]"),children:[e.jsxs(ks,{className:"space-y-1.5 border-b border-border p-2.5 sm:space-y-2 sm:p-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(xs,{className:"pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(ne,{className:ce("pl-8",u?"pr-8":void 0),placeholder:"Search providers…",value:u,autoComplete:"off",autoCorrect:"off",autoCapitalize:"none",spellCheck:!1,"data-1p-ignore":"true","data-lpignore":"true",onChange:b=>N(b.target.value)}),u?e.jsx(ee,{label:"Clear search",children:e.jsx("button",{type:"button","aria-label":"Clear provider search",className:"absolute right-2.5 top-1/2 -translate-y-1/2 rounded p-0.5 text-muted-foreground transition-colors hover:bg-surface-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",onClick:()=>N(""),children:e.jsx(Gn,{className:"h-4 w-4"})})}):null]}),e.jsx(jt,{size:"sm",value:n,onChange:C,options:[{value:"all",label:"All"},{value:"active",label:"Active"},{value:"idle",label:"Idle"}]})]}),e.jsx(js,{className:"flex min-h-0 flex-1 flex-col overflow-hidden p-0",children:e.jsx(Jn,{overscrollContain:!0,scrollFade:!0,scrollbarGutter:!0,viewportRef:c,className:"min-h-0 flex-1",children:e.jsx("div",{className:"p-2",children:a?e.jsx("div",{className:"space-y-2 p-1",children:Array.from({length:6}).map((b,F)=>e.jsx(Ai,{className:"h-14 w-full rounded-lg"},F))}):y.length===0?e.jsx("p",{className:"p-6 text-center text-sm text-muted-foreground",children:"No providers match"}):e.jsx("ul",{className:"space-y-1",children:y.map(b=>{const F=s.get(b.id)||[],z=b.id===h?F.length:b.connected||0,T=b.id===h?F.filter(R=>R.isActive!==!1).length:z,G=b.id===h?F.length-T:0,U=h===b.id,_=i.includes(b.id),Y=hs(b.id),$=b.isCustom?"apikey":kn(b.id,b.authType,b.noAuth),fe=$==="apikey"?hi:$==="oauth"||$==="device"?fi:$==="import"?pi:xi;return e.jsx("li",{"data-provider-id":b.id,children:e.jsxs("div",{className:ce("group relative flex w-full items-center rounded-lg transition-colors duration-100",U?"text-foreground":"hover:bg-surface-hover/70",_&&"opacity-55"),children:[U?e.jsx(dt.span,{layoutId:"provider-highlight",className:"absolute inset-0 rounded-lg bg-white/15",transition:{type:"spring",stiffness:520,damping:36,mass:.4}}):null,e.jsxs("button",{type:"button",onClick:()=>K(b.id),className:ce("relative z-10 flex min-w-0 flex-1 items-center gap-2 rounded-lg px-2 py-2 text-left outline-none focus-visible:ring-1 focus-visible:ring-white/20 sm:gap-3 sm:px-3 sm:py-2.5"),children:[e.jsxs("span",{className:"relative z-10 flex size-7 shrink-0 items-center justify-center rounded-lg bg-white p-1.5 outline outline-1 outline-white/30 outline-offset-2 sm:size-8",children:[e.jsx(Cs,{id:b.id,color:"var(--background)",size:20,fallbackIcon:Y}),e.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 flex h-3.5 w-3.5 items-center justify-center rounded-full border border-border/60 bg-card/90 text-muted-foreground",children:e.jsx(fe,{className:"h-2 w-2"})})]}),e.jsxs("div",{className:"relative z-10 min-w-0 flex-1",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1 sm:gap-1.5",children:[e.jsx("span",{className:"truncate text-[13px] font-medium sm:text-sm",children:b.name}),e.jsx(Qn,{variant:"outline",size:"sm",className:"max-w-[5.5rem] truncate font-mono text-[9px] text-muted-foreground sm:max-w-none sm:text-[10px]",children:b.alias||b.id})]}),e.jsxs("div",{className:"mt-0.5 flex flex-wrap items-center gap-x-1.5 gap-y-0.5 text-[10px] text-muted-foreground sm:gap-x-2 sm:text-[11px]",children:[Ps(b.authType,b.noAuth,b.authModes).map(R=>e.jsxs("span",{className:"inline-flex items-center gap-0.5 rounded border border-border bg-background/50 px-1 py-px font-medium sm:gap-1 sm:px-1.5",children:[e.jsx(fe,{className:"h-2.5 w-2.5"}),R]},R)),z>0?e.jsxs(e.Fragment,{children:[G>0?e.jsxs("span",{className:"inline-flex items-center gap-0.5 rounded bg-muted px-1 py-px text-[10px] font-medium text-muted-foreground sm:gap-1 sm:px-1.5 sm:text-[11px]",children:[G," off"]}):null,e.jsxs(Pe,{tone:"ok",className:"text-[10px] font-medium sm:text-[11px]",children:[z," connection",z===1?"":"s"]})]}):e.jsx("span",{className:"text-muted-foreground/60",children:"no connections"})]})]})]}),e.jsx(ee,{label:_?"Show provider":"Hide provider",children:e.jsx("button",{type:"button","aria-label":_?`Show ${b.name}`:`Hide ${b.name}`,"aria-pressed":_,onClick:()=>A(b.id),className:"relative z-10 mr-1 flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-[background-color,opacity,color] hover:bg-surface-hover hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring group-hover:opacity-100 sm:mr-2",children:_?e.jsx(gi,{className:"size-3.5"}):e.jsx(vi,{className:"size-3.5"})})})]})},b.id)})})})})})]})}function Jt({busy:s,onTest:n,onStop:i,label:a="Test",disabled:u,compact:c}){return s?e.jsx(ee,{label:"Cancel test",disabled:!c,children:e.jsxs(E,{size:"sm",variant:"outline",onClick:i,"aria-label":c?"Cancel test":void 0,className:ce(c&&"h-7 w-7 p-0",!c&&"gap-1.5"),children:[e.jsx(cn,{className:"h-3.5 w-3.5 animate-spin"}),c?null:"Cancel"]})}):e.jsx(ee,{label:a,disabled:!c,children:e.jsx(E,{size:"sm",variant:"outline",disabled:u,onClick:n,"aria-label":c?a:void 0,className:c?"h-7 px-2 text-[11px]":void 0,children:a})})}function Nn(s,n){const i=String(s||"").trim();if(!i)return i;const a=String(n||"").trim().toLowerCase();if(!(a==="clinepass"||a==="cline-pass"||/^(?:clinepass|cline-pass)\//i.test(i)))return i;let c=i.replace(/^clinepass\//i,"").replace(/^cline-pass\//i,"");return c=c.replace(/^clinepass\//i,"").replace(/^cline-pass\//i,""),`clinepass/${c}`}const Hi=["vision","pdf","audioInput","videoInput","imageOutput","audioOutput","search","tools","reasoning"];function Vn(s){if(!s||typeof s!="object"||Array.isArray(s))return;const n=s,i={};for(const a of Hi)typeof n[a]=="boolean"&&(i[a]=n[a]);if((typeof n.thinkingFormat=="string"||n.thinkingFormat===null)&&(i.thinkingFormat=n.thinkingFormat),typeof n.thinkingCanDisable=="boolean"&&(i.thinkingCanDisable=n.thinkingCanDisable),n.thinkingRange&&typeof n.thinkingRange=="object"&&!Array.isArray(n.thinkingRange)){const a=n.thinkingRange,u={};Number.isFinite(Number(a.min))&&(u.min=Number(a.min)),Number.isFinite(Number(a.max))&&(u.max=Number(a.max)),i.thinkingRange=u}else n.thinkingRange===null&&(i.thinkingRange=null);for(const a of["contextWindow","maxOutput"])Number.isFinite(Number(n[a]))&&(i[a]=Number(n[a]));return Object.keys(i).length?i:void 0}const Gi=[["vision","Vision"],["pdf","PDF"],["audioInput","Audio"],["videoInput","Video"],["imageOutput","Image out"],["audioOutput","Audio out"],["search","Search"],["tools","Tools"],["reasoning","Reasoning"]];function Yi(s){return s?Gi.filter(([n])=>s[n]===!0).map(([n,i])=>({key:n,label:i})):[]}function Un(s,n){return Array.isArray(s)?s.flatMap(i=>{if(!i||typeof i!="object"||Array.isArray(i))return[];const a=i,u=typeof a.id=="string"?a.id.trim():typeof a.model=="string"?a.model.trim():"",c=Nn(u,n);if(!c)return[];const h=typeof a.name=="string"&&a.name.trim()?a.name.trim():c,y=Array.isArray(a.thinkingLevels)?a.thinkingLevels.filter(C=>typeof C=="string"):void 0;return[{id:c,name:h,caps:Vn(a.capabilities??a.caps),...y?{thinkingLevels:y}:{}}]}):[]}function cs(s,n){if(!s)return!0;const i=s.trim().toLowerCase(),a=n.trim().toLowerCase();return i===a||i===a.replace(/^clinepass\//,"")||/^cline-pass\//.test(i)||/^clinepass\/cline-pass\//.test(i)}function Xi(s,n){var a;const i=new Map;for(const u of s){const c=Nn(u.id,u.provider_alias||u.provider_id||u.owned_by||n);if(!c)continue;const h=c===u.id?u:{...u,id:c},y=i.get(c);if(!y){i.set(c,h);continue}const C=cs(y.name,c)&&!cs(h.name,c)?h.name:y.name||h.name;i.set(c,{...y,name:C,provider_alias:y.provider_alias||h.provider_alias,provider_id:y.provider_id||h.provider_id,owned_by:y.owned_by||h.owned_by,caps:{...h.caps,...y.caps},thinkingLevels:(a=y.thinkingLevels)!=null&&a.length?y.thinkingLevels:h.thinkingLevels})}return[...i.values()]}function Zi({selected:s,visibleModels:n,models:i,modelNames:a,modelsLoading:u,modelsUnavailable:c,importingModels:h,testConnId:y,batchKind:C,modelTestLock:N,testingModels:K,modelQuery:A,newModel:b,addingModel:F,modelResults:z,pinnedFor:T,copied:G,onImportModels:U,onTestAllModels:_,onStopTests:Y,onStopModel:$,onModelQueryChange:fe,onNewModelChange:R,onAddModel:Ee,onTogglePin:Le,onCopyModelId:Ie,onTestModel:pe,onRemoveModel:ze,disabledModelIds:te,onToggleDisabled:xe}){return e.jsx(bs,{value:"models",className:"min-h-0 flex-1 basis-0",children:e.jsx(Jn,{overscrollContain:!0,scrollFade:!0,scrollbarGutter:!0,className:"h-full",children:e.jsxs("div",{className:"space-y-3 p-3 sm:p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:[n.length," models"]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.id==="codebuddy-cn"||s.id==="codebuddy-intl"?e.jsx("span",{className:"self-center text-xs text-muted-foreground",children:"Add models manually"}):s.id!=="qoder"?e.jsx(ee,{label:y?"Fetch GET {base}/models with this connection’s key":"Needs a connection (API key) on this provider — or set base URL on a custom node",children:e.jsx(E,{size:"sm",variant:"outline",disabled:h,onClick:()=>void U(),children:h?"Importing…":"Import"})}):null,i.length>0?e.jsx(Jt,{busy:C==="model",label:"Test all",disabled:!y||N||C!==null&&C!=="model"||K.size>0&&C!=="model",onTest:()=>void _(),onStop:Y}):null]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ne,{placeholder:"Search models…",value:A,onChange:B=>fe(B.target.value),className:"min-w-0 flex-1"}),e.jsx(ne,{placeholder:"model-id",value:b,disabled:F,onChange:B=>R(B.target.value),onKeyDown:B=>{B.key==="Enter"&&Ee()},className:"min-w-0 flex-1"}),e.jsxs(E,{size:"sm",variant:"outline",disabled:F||!b.trim(),onClick:()=>void Ee(),children:[e.jsx(An,{className:"h-3.5 w-3.5"}),"Add"]})]}),u?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading models…"}):n.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:A.trim()?"No models match your search.":c?"Upstream model catalog unavailable — add a slug above or retry.":"No models — add a slug above."}):e.jsx(dt.div,{layout:!0,className:"space-y-1",children:n.map(B=>{const O=B.id,ie=z[O],re=K.has(O),ge=Yi(B.caps),Ke=C==="model"||re,L=T.includes(O),S=te.has(O);return e.jsx(dt.div,{layout:!0,transition:{layout:{type:"spring",stiffness:520,damping:36,mass:.4}},className:ce("rounded-md border border-border bg-background px-2.5 py-2 hover:border-foreground/30",S&&"border-warning/40 bg-warning/[0.03]"),children:e.jsxs("div",{className:"group flex flex-wrap items-center gap-1.5",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 flex-wrap items-center gap-1.5",children:[a.get(O)?e.jsx("span",{className:"min-w-0 max-w-[45%] truncate text-xs font-medium",children:a.get(O)}):null,e.jsx("code",{className:"min-w-0 flex-1 truncate font-mono text-[11px] text-muted-foreground",children:O}),S?e.jsx(Qn,{size:"sm",variant:"warning",children:"Disabled"}):null,re||ie?e.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[re?e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-[10px] text-foreground/90","aria-live":"polite","aria-label":`Checking ${O}`,children:[e.jsx("span",{children:"Checking"}),e.jsxs("span",{className:"inline-flex w-3 justify-start","aria-hidden":"true",children:[e.jsx("span",{className:"animate-pulse",children:"."}),e.jsx("span",{className:"animate-pulse [animation-delay:150ms]",children:"."}),e.jsx("span",{className:"animate-pulse [animation-delay:300ms]",children:"."})]})]}):null,ie?e.jsx(ee,{label:ie.message||ie.label,children:e.jsx(Pe,{tone:ie.ok?"ok":"err",className:"max-w-[9rem] truncate text-[10px]",children:ie.label})}):null]}):null,ge.length>0?e.jsx("div",{className:"order-last flex min-w-0 w-full shrink-0 flex-nowrap items-center gap-1 overflow-x-auto pb-0.5 sm:order-none sm:w-auto sm:flex-wrap sm:overflow-visible sm:pb-0","aria-label":"Model capabilities",children:ge.map(ae=>e.jsx(ee,{label:ae.label,children:e.jsx(Qn,{size:"sm",variant:"outline","aria-label":ae.label,className:"shrink-0",children:ae.label})},ae.key))}):null]}),e.jsxs("div",{className:"flex w-full shrink-0 items-center justify-end gap-1 border-t border-border/60 pt-1.5 sm:w-auto sm:justify-start sm:border-0 sm:pt-0",children:[e.jsx(ee,{label:L?"Unpin":"Pin to top",children:e.jsx("button",{type:"button","aria-label":L?"Unpin model":"Pin model to top",onClick:()=>Le(O),className:ce("inline-flex h-7 w-7 items-center justify-center rounded-md border p-0 transition-colors duration-150",L?"border-transparent bg-white/15 text-foreground":"border-transparent text-muted-foreground hover:border-border hover:bg-surface-hover hover:text-foreground"),children:e.jsx(Yn,{initial:!1,mode:"wait",children:e.jsx(dt.span,{initial:{opacity:0,scale:.7,rotate:-18},animate:{opacity:1,scale:1,rotate:0},exit:{opacity:0,scale:.7,rotate:18},transition:{duration:.14},className:"block",children:L?e.jsx(yi,{className:"h-3.5 w-3.5"}):e.jsx(bi,{className:"h-3.5 w-3.5"})},L?"pinned":"unpinned")})})}),e.jsx(ee,{label:G===O?"Copied":"Copy model ID",children:e.jsx("button",{type:"button","aria-label":"Copy model ID",className:"inline-flex h-7 w-7 items-center justify-center rounded-md p-0 text-muted-foreground transition-colors duration-100 hover:bg-surface-hover hover:text-foreground",onClick:()=>void Ie(O),children:G===O?e.jsx(Sn,{className:"h-3.5 w-3.5"}):e.jsx(Hn,{className:"h-3.5 w-3.5"})})}),e.jsx(ee,{label:S?"Enable routing for model":"Disable routing for model",children:e.jsx("button",{type:"button","aria-label":S?"Enable routing for model":"Disable routing for model","aria-pressed":S,onClick:()=>void xe(O),className:ce("inline-flex h-7 w-7 items-center justify-center rounded-md p-0 text-muted-foreground transition-colors hover:bg-surface-hover hover:text-foreground",S&&"text-warning hover:text-warning"),children:S?e.jsx(wi,{className:"h-3.5 w-3.5"}):e.jsx(ki,{className:"h-3.5 w-3.5"})})}),e.jsx("span",{className:"sm:hidden",children:e.jsx(Jt,{compact:!0,busy:Ke,disabled:!y||N||C==="conn"||!re&&K.size>=4,onTest:()=>void pe(O,y),onStop:()=>C==="model"?Y():$(O)})}),e.jsx("span",{className:"hidden sm:inline-flex",children:e.jsx(Jt,{busy:Ke,disabled:!y||N||C==="conn"||!re&&K.size>=4,onTest:()=>void pe(O,y),onStop:()=>C==="model"?Y():$(O)})}),e.jsx(ee,{label:"Remove",children:e.jsx("button",{type:"button","aria-label":"Remove model",className:"inline-flex h-7 w-7 items-center justify-center rounded-md p-0 text-muted-foreground transition-colors duration-100 hover:bg-surface-hover hover:text-destructive",onClick:()=>void ze(O),children:e.jsx(jn,{className:"h-3.5 w-3.5"})})})]})]})},O)})})]})})})}const er=["auto","low","medium","high","xhigh","max"],$n=["auto","low","medium","high","max"],tr={openai:er,claude:$n,deepseek:["auto","low","high","max"],groq:["auto","low","medium","high"],openrouter:$n,kimi:$n,glm:["auto","low","medium","high"],minimax:["auto","low","medium","high"],kiro:["auto","low","medium","high"],codex:["auto","low","medium","high","xhigh"],github:["auto","low","medium","high"],cursor:["auto","low","medium","high"],"gemini-cli":["auto","low","medium","high"],"grok-cli":["auto","low","medium","high"],"ollama-local":["auto","low","medium","high"],antigravity:["auto","low","medium","high"],qwen:["auto","low","medium","high"],"codebuddy-cn":["auto","low","medium","high"]},nr=["auto","none","on","off","thinking","minimal","low","medium","high","xhigh","max","ultra"],ds={"x-high":"xhigh",maximum:"max"};function Xn(s){const n=String(s||"").trim().toLowerCase();return n?n in ds?ds[n]:["auto","none","on","off","thinking","minimal","low","medium","high","xhigh","max","ultra"].includes(n)?n:null:null}function sr(s){if(!Array.isArray(s==null?void 0:s.options))return[];const n=s.options.flatMap(u=>{const c=Xn(u);return c?[c]:[]}),i=[...new Set(n)];if(!i.length)return[];const a=i.every(u=>["auto","on","off"].includes(u));return!i.includes("auto")&&!a&&i.unshift("auto"),i}function ir(s){return Array.isArray(s)?s.flatMap(n=>{const i=Xn(n);return i?[i]:[]}):[]}function rr(s,n,i){if((i==null?void 0:i.modelAware)===!1)return Wn(s,i);const a=n.map(c=>new Set(ir(c))).filter(c=>c.size>0);return a.length?["auto",...nr.filter(c=>c!=="auto"&&c!=="none"&&a.some(h=>h.has(c)))]:s.startsWith("openai-compatible-")||s.startsWith("anthropic-compatible-")?null:Wn(s,i)}function Wn(s,n){if(s.startsWith("openai-compatible-")||s.startsWith("anthropic-compatible-"))return["auto","low","medium","high","max"];const i=sr(n);return i.length>0?i:tr[s]||null}function ar(s,n){const i=Wn(s,n),a=Xn(n==null?void 0:n.defaultMode);return a&&(i!=null&&i.includes(a))?a:!(i!=null&&i.length)||i.includes("auto")?"auto":i.includes("high")?"high":i[0]}function or(s){return s==="auto"?"Auto":s==="xhigh"?"xHigh":s==="thinking"?"Thinking":s.charAt(0).toUpperCase()+s.slice(1)}function lr(s){if(!s)return null;const n=Date.parse(s);if(!Number.isFinite(n))return null;const i=Math.max(0,Math.floor((Date.now()-n)/1e3));if(i<10)return"just now";if(i<60)return`${i}s ago`;const a=Math.floor(i/60);if(a<60)return`${a}m ago`;const u=Math.floor(a/60);return u<24?`${u}h ago`:`${Math.floor(u/24)}d ago`}function cr({selected:s,connsAll:n,conns:i,strategy:a,strategyPending:u,stickyDraft:c,thinkingLevels:h,thinkingValue:y,thinkingPending:C,selectedKeys:N,connectionsCapped:K,totalConnections:A,batchKind:b,testingConnId:F,togglingConnId:z,connQuery:T,connListRef:G,connVirtualizer:U,connResults:_,onStrategyChange:Y,onStickyDraftChange:$,onSaveSticky:fe,onThinkingChange:R,onRequestBulkDelete:Ee,onClearSelection:Le,onToggleSelection:Ie,onSelectAll:pe,onTestConnections:ze,onTestConnection:te,onStopTests:xe,onConnQueryChange:B,onOpenAddConnection:O,onMovePriority:ie,onToggleConnection:re,onEditConnection:ge,onDeleteConnection:Ke}){return e.jsx(bs,{value:"connections",keepMounted:!0,className:"flex min-h-0 h-full flex-1 flex-col overflow-hidden p-1.5 sm:p-5",children:e.jsxs("div",{className:"flex min-h-0 h-full flex-1 flex-col gap-1.5 overflow-hidden sm:gap-3",children:[e.jsxs("div",{className:"flex shrink-0 flex-wrap items-end justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1 space-y-1.5 sm:space-y-2",children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1.5 sm:gap-x-3 sm:gap-y-2",children:[e.jsxs("div",{className:"flex min-w-0 basis-full items-center gap-1.5 sm:basis-auto sm:gap-2",children:[e.jsx("span",{className:"text-[11px] font-medium text-muted-foreground sm:hidden",children:"Routing"}),e.jsx("span",{className:"hidden whitespace-nowrap text-xs font-medium text-muted-foreground sm:inline",children:"Account routing:"}),e.jsx("div",{className:"min-w-0 flex-1 overflow-hidden sm:flex-none",children:e.jsx(jt,{size:"sm",className:"w-full min-w-0 sm:w-auto sm:min-w-[15rem] sm:flex-none",value:a,disabled:u,onChange:Y,options:[{value:"fill-first",label:"Fill-first",mobileLabel:"Fill"},{value:"round-robin",label:"Round-robin",mobileLabel:"Round"},{value:"least-inflight",label:"Least-inflight",mobileLabel:"Least"}]})})]}),e.jsxs("div",{className:ce("inline-flex items-center gap-1.5 sm:gap-1.5",a!=="round-robin"&&"hidden sm:inline-flex"),children:[e.jsx("label",{htmlFor:"provider-sticky-limit",className:"text-xs font-medium text-muted-foreground",children:"Sticky"}),e.jsx(ne,{id:"provider-sticky-limit",size:"sm",type:"number",min:1,value:c,disabled:u||a!=="round-robin",onChange:L=>$(L.target.value),className:"w-14 shrink-0"}),e.jsx(E,{size:"sm",variant:"outline",disabled:u||a!=="round-robin",onClick:fe,children:"Save"})]})]}),h&&h.length>0?e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[e.jsx("span",{className:"shrink-0 text-xs font-medium text-muted-foreground",children:"Thinking Mode:"}),e.jsx("div",{className:"w-full min-w-0 max-w-[26rem] overflow-hidden pb-0.5 sm:flex-none sm:overflow-visible sm:pb-0",children:e.jsx(jt,{size:"compact",value:y,disabled:C,onChange:R,options:h.map(L=>({value:L,label:or(L),compactLabel:L==="minimal"?"Min":L==="medium"?"Med":L==="thinking"?"Think":L==="ultra"?"Ultra":void 0})),className:"w-full min-w-0 gap-1 p-1"})})]}):null]}),n.length>0?e.jsx("div",{className:"flex w-full shrink-0 flex-wrap items-center justify-start gap-2 sm:justify-end xl:w-auto",children:N.size>0?e.jsxs(e.Fragment,{children:[e.jsxs(E,{size:"sm",variant:"destructive",onClick:Ee,children:[e.jsx(jn,{className:"h-3.5 w-3.5"}),"Delete selected"]}),e.jsx(E,{size:"sm",variant:"outline",onClick:Le,children:"Unselect"}),e.jsx(Jt,{busy:b==="conn"||i.some(L=>F===L.id),label:"Test selected",onTest:()=>void ze([...N]),onStop:xe})]}):e.jsxs(e.Fragment,{children:[e.jsx(E,{size:"sm",variant:"outline",onClick:pe,children:"Select all"}),e.jsx(Jt,{busy:b==="conn"||i.some(L=>F===L.id),label:"Test all",onTest:()=>void ze(i.map(L=>L.id)),onStop:xe})]})}):null]}),K?e.jsxs("div",{className:"shrink-0 rounded-md border border-warning/25 bg-warning/10 px-3 py-2 text-[11px] text-warning",children:["Showing the first ",n.length.toLocaleString()," of ",A.toLocaleString()," connections. Use search to find accounts beyond this limit."]}):null,n.length>0?e.jsxs("div",{className:"relative shrink-0",children:[e.jsx(xs,{className:"pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),e.jsx(ne,{className:"h-8 pl-8 text-xs",placeholder:"Search name, id, key hint…",value:T,autoComplete:"off",autoCorrect:"off",autoCapitalize:"none",spellCheck:!1,"data-1p-ignore":"true","data-lpignore":"true",onChange:L=>B(L.target.value)})]}):null,n.length===0?e.jsxs("div",{className:"rounded-lg border border-dashed border-border px-4 py-10 text-center text-sm text-muted-foreground",children:["No connections yet",e.jsx("div",{className:"mt-3",children:e.jsxs(E,{size:"sm",onClick:O,children:[e.jsx(An,{className:"h-3.5 w-3.5"}),Tn(s.authType,s.noAuth)]})})]}):i.length===0?e.jsxs("div",{className:"rounded-lg border border-dashed border-border px-4 py-8 text-center text-sm text-muted-foreground",children:['No matches for "',T,'"']}):e.jsx("div",{className:"relative min-h-0 flex-1 overflow-hidden",children:e.jsx(Jn,{overscrollContain:!0,scrollFade:!0,viewportRef:G,className:"absolute inset-0",children:e.jsx("div",{className:"touch-pan-y [-webkit-overflow-scrolling:touch]",children:e.jsx("div",{className:"relative w-full",style:{height:`${U.getTotalSize()}px`},children:U.getVirtualItems().map(L=>{const S=i[L.index];if(!S)return null;const ae=L.index,ut=N.has(S.id),Qe=_[S.id],Re=F===S.id,oe=S.isActive===!1,ke=S.testStatus==="stale"||S.testStatus==="expired",Ve=S.healthStatus&&S.healthStatus!=="unknown"?S.healthStatus:S.testStatus==="active"?"healthy":S.testStatus==="error"?"error":null,Ye=S.lastTested?lr(S.lastTested):null;return e.jsx("div",{"data-index":L.index,ref:U.measureElement,className:"absolute left-0 top-0 w-full pb-1",style:{transform:`translateY(${L.start}px)`},children:e.jsx("div",{className:ce("rounded-lg border bg-surface px-2 py-1.5 sm:p-3 transition-[border-color,background-color] duration-150 ease-out",ut?"border-foreground/40":oe?"border-border/70 bg-muted/30 text-muted-foreground opacity-60":"border-border hover:border-border/80 hover:bg-surface-hover/40"),children:e.jsxs("div",{className:"flex flex-nowrap items-center gap-1 sm:gap-3",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 flex-nowrap items-center gap-1.5 sm:gap-2.5",children:[e.jsx(Mi,{checked:ut,onCheckedChange:()=>{Ie(S.id)}}),e.jsxs("div",{className:"hidden shrink-0 flex-col gap-0.5 sm:flex",children:[e.jsx(ee,{label:"Move up",children:e.jsx("button",{type:"button",disabled:ae===0,onClick:()=>void ie(S.id,-1),"aria-label":"Move up",className:"rounded p-0.5 text-muted-foreground transition-colors duration-100 hover:bg-surface-hover hover:text-foreground disabled:opacity-30",children:e.jsx(ji,{className:"h-3.5 w-3.5"})})}),e.jsx(ee,{label:"Move down",children:e.jsx("button",{type:"button",disabled:ae===i.length-1,onClick:()=>void ie(S.id,1),"aria-label":"Move down",className:"rounded p-0.5 text-muted-foreground transition-colors duration-100 hover:bg-surface-hover hover:text-foreground disabled:opacity-30",children:e.jsx(Ci,{className:"h-3.5 w-3.5"})})})]}),e.jsxs("div",{className:"min-w-0 flex-1 overflow-hidden",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 sm:gap-2",children:[e.jsx("span",{className:"truncate text-[13px] font-medium leading-tight sm:text-sm",children:S.name||S.email||S.id.slice(0,8)}),Re?e.jsxs("span",{className:"inline-flex shrink-0 items-center gap-0.5 text-[10px] text-foreground/90","aria-live":"polite","aria-label":`Checking ${S.name||S.email||S.id}`,children:[e.jsx("span",{children:"Checking"}),e.jsxs("span",{className:"inline-flex w-3 justify-start","aria-hidden":"true",children:[e.jsx("span",{className:"animate-pulse",children:"."}),e.jsx("span",{className:"animate-pulse [animation-delay:150ms]",children:"."}),e.jsx("span",{className:"animate-pulse [animation-delay:300ms]",children:"."})]})]}):null,Qe&&!Qe.ok?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"max-w-[4.5rem] shrink truncate text-[10px] font-medium text-destructive sm:max-w-none",children:Qe.label}),e.jsx(ee,{label:"Copy full error",children:e.jsx("button",{type:"button",className:"hidden rounded p-0.5 text-muted-foreground hover:text-foreground sm:inline-flex","aria-label":"Copy full error",onClick:mt=>{mt.stopPropagation(),navigator.clipboard.writeText(Qe.message||"").catch(()=>{})},children:e.jsx(Hn,{className:"h-3 w-3"})})})]}):null]}),e.jsxs("div",{className:"mt-0.5 hidden flex-wrap items-center gap-x-1.5 text-[11px] text-muted-foreground sm:flex",children:[e.jsxs("span",{children:["#",ae+1]}),Ve?e.jsx(ee,{label:S.healthError||(Ve==="healthy"?"Connection is healthy":"Connection has an error"),children:e.jsx(Pe,{tone:Ve==="healthy"?"ok":"err",className:"max-w-[10rem] truncate text-[10px]",children:Ve==="healthy"?"OK":"Error"})}):null,Ye?e.jsxs("span",{children:["checked ",Ye]}):null,ke?e.jsx(ee,{label:S.lastError||"Credentials may be expired; reconnect this provider.",children:e.jsx(Pe,{tone:"warn",className:"max-w-[10rem] truncate text-[10px]",children:"Stale"})}):null,oe?e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"·"}),e.jsx("span",{children:"off"})]}):null]})]})]}),e.jsxs("div",{className:"ml-auto flex shrink-0 flex-nowrap items-center gap-0.5 sm:gap-1.5",children:[e.jsx(Ti,{active:S.isActive!==!1,disabled:z===S.id,onToggle:()=>void re(S.id),activeLabel:"",inactiveLabel:""}),e.jsx(ee,{label:Re?"Stop":"Test",children:e.jsx(E,{size:"icon-sm",variant:"outline",className:"h-7 w-7 sm:hidden","aria-label":Re?"Stop test":"Test connection",onClick:()=>Re?xe():void te(S.id),children:Re?e.jsx(Ni,{className:"h-3 w-3 fill-current"}):e.jsx(Si,{className:"h-3.5 w-3.5 fill-current"})})}),e.jsx("span",{className:"hidden sm:inline-flex [&>button]:h-7 [&>button]:text-sm",children:e.jsx(Jt,{busy:Re,onTest:()=>void te(S.id),onStop:xe})}),e.jsx(ee,{label:"Edit",children:e.jsxs(E,{size:"sm",variant:"outline",className:"h-7 w-7 px-0 sm:w-auto sm:px-3 sm:text-sm",onClick:()=>ge(S),"aria-label":"Edit connection",children:[e.jsx(gs,{className:"size-4 sm:hidden"}),e.jsx("span",{className:"hidden font-medium sm:inline",children:"Edit"})]})}),e.jsx(ee,{label:"Delete",children:e.jsxs(E,{size:"sm",variant:"outline",className:"h-7 w-7 px-0 sm:w-auto sm:px-3 sm:text-sm",onClick:()=>Ke(S.id),"aria-label":"Delete connection",children:[e.jsx(jn,{className:"size-4 sm:hidden"}),e.jsx("span",{className:"hidden font-medium sm:inline",children:"Delete"})]})})]})]})})},S.id)})})})})})]})})}function dr({selected:s,conns:n,activeConns:i,onEditCustom:a,onDeleteCustom:u,onAddConnection:c}){return e.jsxs(ks,{className:"flex shrink-0 flex-row flex-wrap items-start justify-between gap-2 border-b border-border p-3 sm:gap-3 sm:p-5",children:[e.jsxs("div",{className:"flex min-w-0 items-start gap-3",children:[e.jsx("span",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-xl bg-white p-1.5 outline outline-1 outline-white/30 outline-offset-2 sm:h-9 sm:w-9",children:e.jsx(Cs,{id:s.id,color:"var(--background)",size:24,fallbackIcon:hs(s.id)})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"truncate text-base font-semibold sm:text-lg",children:s.name}),e.jsxs("div",{className:"mt-0.5 flex flex-wrap items-center gap-1.5 text-xs text-muted-foreground sm:mt-1 sm:gap-2 sm:text-sm",children:[e.jsx("span",{className:"font-mono text-xs",children:s.alias||s.id}),n.length>0?e.jsx(Pe,{tone:"ok",children:"Active"}):e.jsx(Pe,{tone:"muted",children:"Idle"}),e.jsxs("span",{children:[n.length," connection",n.length===1?"":"s",n.filter(h=>h.healthStatus==="healthy").length>0?` · ${n.filter(h=>h.healthStatus==="healthy").length} OK`:"",n.filter(h=>h.healthStatus==="error").length>0?` · ${n.filter(h=>h.healthStatus==="error").length} error${n.filter(h=>h.healthStatus==="error").length===1?"":"s"}`:"",i.length<n.length?` · ${n.length-i.length} off`:""]}),s.isCustom&&s.baseUrl?e.jsx("span",{className:"hidden truncate text-xs sm:inline",children:s.baseUrl}):null]})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.isCustom?e.jsxs(e.Fragment,{children:[e.jsx(ee,{label:"Edit custom provider",children:e.jsxs(E,{size:"sm",variant:"outline",className:"px-2 sm:px-3","aria-label":"Edit custom provider",onClick:a,children:[e.jsx(gs,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:"Edit"})]})}),e.jsx(ee,{label:"Remove custom provider",children:e.jsxs(E,{size:"sm",variant:"destructive",className:"px-2 sm:px-3","aria-label":"Remove custom provider",onClick:u,children:[e.jsx(jn,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:"Remove"})]})})]}):null,e.jsx("div",{className:"flex flex-wrap gap-2",children:e.jsxs(E,{size:"sm",className:"px-2 sm:px-3",onClick:c,children:[e.jsx(An,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:Tn(s.authType,s.noAuth)}),e.jsx("span",{className:"sm:hidden",children:"Add"})]})})]})]})}function ur({deleteId:s,bulkDeleteIds:n,bulkDeleting:i,deleteProvider:a,connections:u,onCloseDelete:c,onDeleteConnection:h,onCloseBulkDelete:y,onDeleteSelectedConnections:C,onCloseProvider:N,onRemoveProvider:K}){const A=a?u.filter(b=>b.provider===a.id):[];return e.jsxs(e.Fragment,{children:[e.jsx(Ut,{open:!!s,onOpenChange:b=>!b&&c(),children:e.jsxs($t,{children:[e.jsxs(Qt,{children:[e.jsx(Vt,{children:"Delete connection?"}),e.jsx(wn,{children:"Removes this key / session."})]}),e.jsxs(Wt,{children:[e.jsx(E,{variant:"outline",onClick:c,children:"Cancel"}),e.jsx(E,{variant:"destructive",onClick:h,children:"Delete"})]})]})}),e.jsx(Ut,{open:!!n,onOpenChange:b=>{!b&&!i&&y()},children:e.jsxs($t,{children:[e.jsxs(Qt,{children:[e.jsxs(Vt,{children:["Delete ",(n==null?void 0:n.length)??0," selected connections?"]}),e.jsx(wn,{children:"This will remove the selected keys or sessions. This action cannot be undone."})]}),e.jsxs(Wt,{children:[e.jsx(E,{variant:"outline",disabled:i,onClick:y,children:"Cancel"}),e.jsx(E,{variant:"destructive",disabled:i,onClick:C,children:i?"Deleting…":"Delete"})]})]})}),e.jsx(Ut,{open:!!a,onOpenChange:b=>{b||N()},children:e.jsxs($t,{children:[e.jsxs(Qt,{children:[e.jsxs(Vt,{children:["Remove ",a==null?void 0:a.name,"?"]}),e.jsx(wn,{children:A.length>0?e.jsxs(e.Fragment,{children:["This provider has ",e.jsxs("strong",{children:[A.length," connection(s)"]})," that will also be deleted:",e.jsx("ul",{className:"mt-2 list-disc pl-4 text-xs",children:A.map(b=>e.jsx("li",{children:b.name||b.id},b.id))})]}):"This will remove the provider from the list."})]}),e.jsxs(Wt,{children:[e.jsx(E,{variant:"outline",onClick:N,children:"Cancel"}),e.jsx(E,{variant:"destructive",disabled:!a,onClick:()=>{a&&K(a)},children:"Remove"})]})]})})]})}async function Zn(s){const{data:n}=await Ct.get("/models/custom");return n.models??[]}async function mr(s,n){let i=0;for(const u of n)try{const c=typeof u=="string"?{id:u}:u,h=await Ns(s,c.id,c.name,c.capabilities);i+=h.added}catch{}const a=await Zn();return{added:i,total:a.length,models:a}}async function Ns(s,n,i,a){const{data:u}=await Ct.post("/models/custom",{providerAlias:s,id:n,name:i,capabilities:a}),c=await Zn();return{added:u.added===!0?1:0,total:c.length,models:c}}async function hr(s,n){const{data:i}=await Ct.delete("/models/custom",{params:{providerAlias:s,id:n}});return{success:i.success!==!1,removed:i.success!==!1}}async function fr(){const{data:s}=await Ct.get("/models/disabled");return s.disabled??{}}async function pr(s,n){await Ct.post("/models/disabled",{providerAlias:s,ids:n})}async function xr(s,n){await Ct.delete("/models/disabled",{params:{providerAlias:s,id:n}})}function gr(s,n){return s!==n}const vr=50,us=1e3;function Dr(s,n=42){let i=s.trim();if(!i)return"Failed";i=i.replace(/^\s*(?:error|err|failed?)\s*[:\-]\s*/i,""),i=i.replace(/^\s*status\s+\d{3}\s*[:\-]?\s*/i,"");try{const a=JSON.parse(i);if(a&&typeof a=="object"){const u=a,c=u.error??u.message??u.detail;if(typeof c=="string")i=c.trim();else if(c&&typeof c=="object"){const h=c;i=String(h.message??h.type??h.code??i).trim()}}}catch{}return i=i.replace(/\s+/g," ").replace(/[.。]+$/,""),i.length<=n?i:`${i.slice(0,Math.max(1,n-1)).trimEnd()}…`}function on(s){const n=s.status??null,i=(s.message||s.error||"").trim(),a=s.latencyMs!=null&&Number.isFinite(Number(s.latencyMs))?Math.round(Number(s.latencyMs)):null;if(s.ok){const h=a!=null?`OK · ${a}ms`:"OK";return{ok:!0,label:h,message:h,status:n,detail:null}}let u="";if(n!=null&&String(n).trim()!==""){const h=String(n).trim();isNaN(Number(h))||(u=h)}if(!u&&i){const h=i.match(/^(\d{3})[:\s]/);if(h)u=h[1];else{const y=i.match(/\bHTTP\s+(\d{3})\b/i);if(y)u=y[1];else if(i.startsWith("status ")){const C=i.replace(/^status\s+/,"").match(/^(\d{3})/);C&&(u=C[1])}}}const c=u?`Error ${u}`:"Error";return{ok:!1,label:c,message:i||c,status:n,detail:s.detail&&s.detail!==i?s.detail:null}}function ms(s){var n,i;if(_t.isAxiosError(s)){const a=s,u=((n=a.response)==null?void 0:n.status)??null,c=(i=a.response)==null?void 0:i.data;let h="";typeof(c==null?void 0:c.error)=="string"?h=c.error:c!=null&&c.error&&typeof c.error=="object"&&(h=c.error.message||c.error.type||c.error.code||"");const y=typeof(c==null?void 0:c.error)=="string"?c.error:"";h=(/^(?:test failed|internal server error)$/i.test(y)?c==null?void 0:c.message:y)||(c==null?void 0:c.message)||a.message||"Test failed";let N=null;try{c&&(N=JSON.stringify(c,null,2))}catch{N=null}return on({ok:!1,status:u,message:h,detail:N})}return on({ok:!1,message:Z(s,"Test failed")})}function qr(){var p,w,x,M,D;const s=Ss(),n="nr-selected-provider",[i,a]=o.useState(()=>{try{return localStorage.getItem(n)}catch{return null}});function u(t){if(gr(i,t)){vt(null),Fe([]),et({}),tt({}),te(new Set),a(t);try{t?localStorage.setItem(n,t):localStorage.removeItem(n)}catch{}}}const[c,h]=o.useState(""),[y,C]=o.useState("all"),[N,K]=o.useState(()=>{try{const t=JSON.parse(localStorage.getItem("nr-hidden-providers")||"[]");return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]}catch{return[]}}),[A,b]=o.useState(!1),[F,z]=o.useState(null),[T,G]=o.useState(null),[U,_]=o.useState(null),[Y,$]=o.useState(!1),[fe,R]=o.useState(null),[Ee,Le]=o.useState(!1),[Ie,pe]=o.useState(null),[ze,te]=o.useState(new Set),[xe,B]=o.useState(0),[O,ie]=o.useState({}),[re,ge]=o.useState(""),[Ke,L]=o.useState(!1),[S,ae]=o.useState(!1),[ut,Qe]=o.useState(()=>{try{return JSON.parse(localStorage.getItem("nr-pinned-models")||"{}")}catch{return{}}}),[Re,oe]=o.useState(()=>{try{return JSON.parse(localStorage.getItem("nr-hidden-models")||"{}")}catch{return{}}}),[ke,Ve]=o.useState("");function Ye(t,r){oe(l=>{const v={...l,[t]:Array.from(new Set([...l[t]||[],r]))};try{localStorage.setItem("nr-hidden-models",JSON.stringify(v))}catch{}return v})}function mt(t,r){r.length&&oe(l=>{const v=new Set(r.map(V=>V.trim()).filter(Boolean)),g=new Set([...v].map(V=>V.slice(V.lastIndexOf("/")+1))),f=(l[t]||[]).filter(V=>{const W=String(V),ue=W.slice(W.lastIndexOf("/")+1);return!v.has(W)&&!g.has(ue)}),j={...l};f.length?j[t]=f:delete j[t];try{localStorage.setItem("nr-hidden-models",JSON.stringify(j))}catch{}return j})}const[Xe,Nt]=o.useState(0),[me,St]=o.useState(""),[ht,At]=o.useState(null),[Ht,Tt]=o.useState(null),[Gt,ft]=o.useState(()=>new Set),[dn,Mt]=o.useState(!1),Ze=o.useRef(!1),Oe=o.useRef(new Map),Pt=4,[Yt,Et]=o.useState(null),[Lt,pt]=o.useState(null),Be=o.useRef(null),[Mn,et]=o.useState({}),[Pn,tt]=o.useState({}),[le,nt]=o.useState("connections"),xt=o.useRef(null),st=o.useRef(null),It=o.useRef(0),[je,Kt]=o.useState(""),[gt,Xt]=o.useState(""),[ye,Rt]=o.useState(1),[Zt,Fe]=o.useState([]),[We,vt]=o.useState(null);o.useEffect(()=>{const t=window.setTimeout(()=>{Xt(je.trim())},250);return()=>window.clearTimeout(t)},[je]);const De=ct({queryKey:["connections",i,ye,gt],queryFn:()=>Gs({provider:i,page:ye,pageSize:vr,search:gt||void 0}),enabled:!!i,retry:!1,refetchInterval:3e4});o.useEffect(()=>{Rt(1),vt(null),Fe([])},[i,gt]),o.useEffect(()=>{var r;const t=((r=De.data)==null?void 0:r.connections)??[];if(i){if(!t.length&&ye===1){Fe([]),vt(i);return}Fe(l=>{const v=ye===1?[]:l,g=new Set(v.map(k=>k.id));return[...v,...t.filter(k=>!g.has(k.id))].slice(0,us)}),vt(i)}},[De.data,ye,i]);const it=We===i?Zt:[],Ce=(p=De.data)==null?void 0:p.pagination,Ot=!!(Ce!=null&&Ce.hasNext&&it.length>=us);o.useEffect(()=>{const t=st.current;if(!t)return;const r=()=>{It.current=t.scrollTop};return t.addEventListener("scroll",r,{passive:!0}),()=>t.removeEventListener("scroll",r)},[]),o.useLayoutEffect(()=>{const t=st.current;t&&(t.scrollTop=It.current)},[i]),o.useEffect(()=>{const t=xt.current;if(!t||le!=="connections")return;const r=()=>{var v;const l=(v=De.data)==null?void 0:v.pagination;!(l!=null&&l.hasNext)||De.isFetching||Ot||t.scrollTop+t.clientHeight>=t.scrollHeight-240&&Rt(g=>g+1)};return t.addEventListener("scroll",r,{passive:!0}),()=>t.removeEventListener("scroll",r)},[Ot,(w=De.data)==null?void 0:w.pagination,De.isFetching,le]);const Ft=ct({queryKey:["providers-available"],queryFn:Ys,retry:!1}),de=ct({queryKey:["settings"],queryFn:Is,retry:!1}),en=ct({queryKey:["nodes"],queryFn:ni,retry:!1}),_e=ct({queryKey:["custom-models"],queryFn:()=>Zn(),enabled:!!i,staleTime:0,refetchOnMount:"always",retry:!1,placeholderData:t=>t}),Dt=ct({queryKey:["disabled-models"],queryFn:fr,retry:!1}),Ne=ct({queryKey:["available-models",Xe],queryFn:async()=>((await Ct.get("/models")).data.models??[]).map(r=>({id:Nn(r.routedModel||r.fullModel,r.provider),name:r.name||r.model,provider_alias:r.provider,provider_id:r.provider,owned_by:r.provider,caps:Vn(r.caps),thinkingLevels:Array.isArray(r.thinkingLevels)?r.thinkingLevels:void 0})),retry:!1});function P(t,r="default"){r==="success"?kt.success(t):r==="error"?kt.error(t):r==="warning"?kt.warning(t):kt(t)}const rt=o.useMemo(()=>{const t=Ft.data??[],r=new Set(t.map(g=>g.id)),l=en.data??[],v=[];for(const g of l)r.has(g.id)||v.push({id:g.id,alias:g.prefix||g.id,name:g.name||g.prefix||g.id,authType:"apikey",isCustom:!0,baseUrl:g.baseUrl,nodeType:g.type,apiType:g.apiType,icon:"sway",connected:0});return[...t,...v]},[Ft.data,en.data]),H=de.data,Je=o.useMemo(()=>{const t=new Map;return i&&t.set(i,it),t},[it,i]),be=o.useMemo(()=>{let t=[...rt];if(y==="active"?t=t.filter(r=>(r.connected||0)>0):y==="idle"&&(t=t.filter(r=>(r.connected||0)===0)),c.trim()){const r=c.toLowerCase();t=t.filter(l=>l.name.toLowerCase().includes(r)||l.id.toLowerCase().includes(r)||(l.alias||"").toLowerCase().includes(r))}return t.sort((r,l)=>{const v=N.includes(r.id)?1:0,g=N.includes(l.id)?1:0;if(v!==g)return v-g;const k=r.connected||0,f=l.connected||0;return(k>0?1:0)!=(f>0?1:0)?f-k:(r.name||r.id).localeCompare(l.name||l.id)}),t},[rt,Je,y,N,c]);function qt(t){K(r=>{const l=r.includes(t)?r.filter(v=>v!==t):[...r,t];try{localStorage.setItem("nr-hidden-providers",JSON.stringify(l))}catch{}return l})}o.useEffect(()=>{if(rt.length===0||i&&rt.some(r=>r.id===i))return;let t=null;try{t=localStorage.getItem(n)}catch{t=null}if(t&&rt.some(r=>r.id===t)){a(t);return}},[rt,Je,i]),o.useEffect(()=>{te(new Set),Kt(""),ge(""),nt("connections")},[i]),o.useEffect(()=>{const t=Es(H,i||"");St(String(t))},[i,H]);const d=be.find(t=>t.id===i)||null,Se=o.useMemo(()=>{const t=d?[...Je.get(d.id)||[]]:[];return t.sort((r,l)=>(r.priority??999)-(l.priority??999)||r.id.localeCompare(l.id)),t},[d,Je]),se=Se,we=As({count:se.length,getScrollElement:()=>xt.current,estimateSize:()=>typeof window<"u"&&window.matchMedia("(max-width: 639px)").matches?48:72,overscan:10,getItemKey:t=>{var r;return((r=se[t])==null?void 0:r.id)??t},enabled:le==="connections"});o.useEffect(()=>{if(le!=="connections")return;const t=requestAnimationFrame(()=>{we.measure()});return()=>cancelAnimationFrame(t)},[le,se.length,i,we]),o.useEffect(()=>{if(typeof window>"u")return;const t=window.matchMedia("(max-width: 639px)"),r=()=>{we.measure()};return t.addEventListener("change",r),()=>t.removeEventListener("change",r)},[we]),o.useEffect(()=>{const t=xt.current;if(!t||typeof ResizeObserver>"u")return;const r=new ResizeObserver(()=>{we.measure()});return r.observe(t),()=>r.disconnect()},[we,le,i]);const He=o.useMemo(()=>Se.filter(t=>t.isActive!==!1),[Se]),he=[...ze][0]||((x=He[0])==null?void 0:x.id)||((M=se[0])==null?void 0:M.id),Ae=_s(d),J=ct({queryKey:["connection-models",d==null?void 0:d.id,he,Xe],queryFn:async()=>{const t=await is(he);return Un(t.models,d==null?void 0:d.id)},enabled:!!(Ae&&he),retry:!1}),yt=d?Ls(H,d.id):"fill-first",ve={"qd/ultimate":"Ultimate","qd/auto":"Auto","qd/performance":"Performance","qd/efficient":"Efficient","qd/lite":"Lite","qd/qmodel_preview":"Qwen3.8-Max-Preview","qd/qmodel_latest":"Qwen3.7-Max","qd/qmodel":"Qwen3.7-Plus","qd/kmodel_latest":"Kimi-K3","qd/kmodel":"Kimi-K2.7-Code","qd/gm51model":"GLM-5.2","qd/dmodel":"DeepSeek-V4-Pro","qd/dfmodel":"DeepSeek-V4-Flash","qd/mmodel":"MiniMax-M3"},at=o.useMemo(()=>{if(!d)return[];const t=[],r=d.id,l=new Set([r,d.alias||""].filter(Boolean).map(g=>g.toLowerCase())),v=[..._e.data??[],...(O[r]??[]).map(g=>({providerAlias:r,id:g.id,name:g.name,capabilities:g.caps,thinkingLevels:g.thinkingLevels}))];for(const g of v)l.has(g.providerAlias.toLowerCase())&&t.push({id:Nn(g.id,g.providerAlias),name:g.name||g.id,caps:Vn(g.capabilities),thinkingLevels:Array.isArray(g.thinkingLevels)?g.thinkingLevels:void 0});if(Ae)t.push(...J.data??[]),!he&&(r==="codebuddy-cn"||r==="codebuddy-intl")&&t.push(...Un(d.models,r));else{const g=new Set([r,d.alias||""].map(k=>k.trim().toLowerCase()).filter(Boolean));for(const k of Ne.data??[])[k.provider_alias,k.provider_id,k.owned_by].filter(j=>!!j).map(j=>j.trim().toLowerCase()).some(j=>g.has(j))&&t.push(k)}return Xi(t,r)},[J.data,xe,_e.data,O,Ne.data,d,he,Ae]),tn=Ae?_e.isLoading||_e.isFetching||J.isLoading||J.isFetching:_e.isLoading||_e.isFetching||Ne.isLoading||Ne.isFetching,un=Ae&&!!J.error,Te=d?rr(d.id,at.map(t=>t.thinkingLevels),d.thinkingConfig):null,Ge=d?(D=H==null?void 0:H.providerThinking)==null?void 0:D[d.id]:void 0,mn=d?ar(d.id,d.thinkingConfig):"auto",ot=d?Ge&&(Te!=null&&Te.includes(Ge))?Ge:Te!=null&&Te.includes(mn)?mn:(Te==null?void 0:Te[0])||"auto":"auto",En=o.useMemo(()=>{const t=new Map(Object.entries(ve));for(const r of at)r.name&&t.set(r.id,r.name);return t},[at]),zt=d?ut[d.id]||[]:[],hn=o.useMemo(()=>{const t=ke.trim().toLowerCase(),r=new Set(d?Re[d.id]||[]:[]);let l=at.filter(f=>!r.has(f.id));if(t&&(l=l.filter(f=>f.id.toLowerCase().includes(t)||(f.name||"").toLowerCase().includes(t))),!zt.length)return[...l].sort((f,j)=>f.id.localeCompare(j.id));const v=new Set(zt),g=l.filter(f=>v.has(f.id)),k=l.filter(f=>!v.has(f.id)).sort((f,j)=>f.id.localeCompare(j.id));return[...g,...k]},[Re,at,ke,zt,d]),fn=o.useMemo(()=>{var r,l;if(!d)return new Set;const t=[...((r=Dt.data)==null?void 0:r[d.id])??[],...d.alias?((l=Dt.data)==null?void 0:l[d.alias])??[]:[]];return new Set(t)},[Dt.data,d]);async function Q(t){if(d)try{fn.has(t)?(await xr(d.id,t),P(`Enabled ${t.split("/").pop()}`)):(await pr(d.id,[t]),P(`Disabled ${t.split("/").pop()}`)),await s.invalidateQueries({queryKey:["disabled-models"]})}catch(r){P(Z(r,"Failed to update model availability"),"error")}}function Ue(t){d&&Qe(r=>{const l=r[d.id]||[],v=l.includes(t)?l.filter(k=>k!==t):[...l,t],g={...r,[d.id]:v};try{localStorage.setItem("nr-pinned-models",JSON.stringify(g))}catch{}return g})}function $e(){var t;(t=Be.current)==null||t.abort();for(const r of Oe.current.values())r.abort();Oe.current.clear(),Be.current=null,Ze.current=!1,Mt(!1),Tt(null),ft(new Set),pt(null),P("Tests stopped")}function lt(t){const r=Oe.current.get(t);r&&(r.abort(),P("Model test stopped"))}async function nn(t,r){Tt(t);try{const l=await ps(t,void 0,{signal:r}),v=l.valid===!0,g=l.testedAt||new Date().toISOString(),k={testStatus:v?"active":"error",lastTested:g,lastError:v?l.error||null:l.error||"Connection test failed",healthStatus:v?"healthy":"error",healthError:v?l.error||null:l.error||"Connection test failed",healthLatencyMs:l.latencyMs??0};return et(f=>({...f,[t]:on({ok:v,message:l.error||(v?"Valid":"Failed"),latencyMs:l.latencyMs})})),Fe(f=>f.map(j=>j.id===t?{...j,...k}:j)),s.setQueriesData({queryKey:["connections"]},f=>f&&{...f,connections:(f.connections||[]).map(j=>j.id===t?{...j,...k}:j)}),v}catch(l){if(_t.isCancel(l)||(l==null?void 0:l.code)==="ERR_CANCELED")return!1;const v=ms(l),g=new Date().toISOString();return et(k=>({...k,[t]:v})),Fe(k=>k.map(f=>f.id===t?{...f,testStatus:"error",lastTested:g,lastError:v.message,healthStatus:"error",healthError:v.message,healthLatencyMs:0}:f)),!1}finally{Tt(l=>l===t?null:l)}}async function pn(t){if(!t.length)return P("Nothing to test");const r=new AbortController;Be.current=r,pt("conn");let l=0;const v=4;for(let g=0;g<t.length&&!r.signal.aborted;g+=v){const k=t.slice(g,g+v),f=await Promise.all(k.map(j=>nn(j,r.signal)));l+=f.filter(Boolean).length}r.signal.aborted||P(`Connections: ${l}/${t.length} passed`),pt(null)}async function xn(t,r,l){if(!r)return P("Add a connection first"),!1;if(!l){if(Ze.current||Lt==="conn"||Oe.current.has(t))return!1;if(Oe.current.size>=Pt)return P(`Up to ${Pt} model tests can run at once`),!1}const v=l?null:new AbortController,g=l||v.signal;v&&Oe.current.set(t,v),ft(k=>{const f=new Set(k);return f.add(t),f});try{const k=await Us(r,{model:t,signal:g});if(!Array.isArray(k.results)){const W=k.message||k.error||"No model test results returned";return tt(ue=>({...ue,[t]:on({ok:!1,message:W})})),!1}const f=t.includes("/")?t.slice(t.lastIndexOf("/")+1):t,j=(k.results??[]).find(W=>{const ue=String(W.modelId||"");return ue===f||ue===t||t.endsWith(`/${ue}`)||ue.endsWith(`/${f}`)}),V=!!(j!=null&&j.ok);return tt(W=>({...W,[t]:on({ok:V,status:j==null?void 0:j.status,message:((j==null?void 0:j.error)||"").trim()||(V?"OK":"Failed"),latencyMs:j==null?void 0:j.latencyMs})})),V}catch(k){return _t.isCancel(k)||(k==null?void 0:k.code)==="ERR_CANCELED"||tt(f=>({...f,[t]:ms(k)})),!1}finally{ft(k=>{const f=new Set(k);return f.delete(t),f}),v&&Oe.current.delete(t)}}async function gn(){var t,r;if(d){if(d.id==="codebuddy-cn"||d.id==="codebuddy-intl"){P("CodeBuddy uses the static registry — add new models manually","default");return}ae(!0);try{const l={provider:d.id},v=new Set([d.id,d.alias].filter(Boolean).map(q=>q.trim().toLowerCase())),g=(en.data??[]).find(q=>q.id===d.id),k=(r=(t=Se.find(q=>{var I;return v.has(String(q.provider||"").trim().toLowerCase())&&typeof((I=q.providerSpecificData)==null?void 0:I.baseUrl)=="string"}))==null?void 0:t.providerSpecificData)==null?void 0:r.baseUrl,f=d.baseUrl||(g==null?void 0:g.baseUrl)||(typeof k=="string"?k:void 0);f&&(l.baseUrl=f);const j=q=>q.flatMap(I=>{if(!I||typeof I!="object")return[];const X=I,Me=typeof X.id=="string"?X.id:typeof X.name=="string"?X.name:"";if(!Me.trim())return[];const qe=X.capabilities??X.caps;return[{id:Me.trim(),...typeof X.name=="string"&&X.name.trim()?{name:X.name.trim()}:{},...qe&&typeof qe=="object"?{capabilities:qe}:{}}]}),V=async()=>{const q=await is(he,!0),I=String(q.provider||"").trim().toLowerCase();if(I&&!v.has(I))throw new Error(`Model catalog returned ${q.provider}, expected ${d.name}`);return{ok:!0,success:!0,models:j(q.models??[])}};let W;if(he)try{W=await V()}catch(q){if(!l.baseUrl||Ae||d.id==="clinepass"||d.id==="cline-pass")throw q;W=await rs(l)}else W=await rs(l);if(!W.ok&&!W.success){P(W.message||W.error||"Import failed","error");return}const ue=W.models??[];if(!ue.length){P(W.message||"No models returned","warning");return}const bn=ue.map(q=>typeof q=="string"?q:q.id);mt(d.id,bn);const{added:wt,models:sn}=await mr(d.id,ue),rn=sn.filter(q=>v.has(String(q.providerAlias||"").trim().toLowerCase())),Bt=rn.length;s.setQueryData(["custom-models"],sn),ie(q=>({...q,[d.id]:Un(rn,d.id)})),B(q=>q+1),Nt(q=>q+1),await s.invalidateQueries({queryKey:["custom-models"]}),await s.invalidateQueries({queryKey:["connection-models"]}),await s.invalidateQueries({queryKey:["available-models"]}),await s.invalidateQueries({queryKey:["sway-chat","models"]}),await s.refetchQueries({queryKey:["custom-models"],type:"active"}),await s.refetchQueries({queryKey:["connection-models"],type:"active"}),P(wt>0?`Imported ${wt} new ${wt===1?"model":"models"} · Total ${Bt} ${Bt===1?"Model":"Models"}`:`No new models · Total ${Bt} Models`,wt>0?"success":"default")}catch(l){P(Z(l,"Import failed"),"error")}finally{ae(!1)}}}async function Ln(){const t=re.trim();if(!(!d||!t||Ke)){L(!0);try{const r=await Ns(d.id,t);mt(d.id,[t]),s.setQueryData(["custom-models"],r.models),B(l=>l+1),Nt(l=>l+1),await s.invalidateQueries({queryKey:["custom-models"]}),await s.invalidateQueries({queryKey:["available-models"]}),await s.invalidateQueries({queryKey:["sway-chat","models"]}),ge(""),kt.success(`Added ${t}`)}catch(r){kt.error(Z(r,"Failed to add model"))}finally{L(!1)}}}async function In(){if(!he)return P("Add a connection first");if(Ze.current)return;if(Oe.current.size>0)return P("Stop individual model tests before running Test all");const t=hn.map(g=>g.id);if(!t.length)return P("No models");Ze.current=!0,Mt(!0),pt("model");const r=new AbortController;Be.current=r;const l=new Array(t.length);let v=0;try{const g=Math.min(Pt,t.length),k=async()=>{for(;;){const f=v++;if(f>=t.length||r.signal.aborted)return;l[f]=await xn(t[f],he,r.signal)}};if(await Promise.all(Array.from({length:g},()=>k())),!r.signal.aborted){const f=l.filter(V=>V!==void 0).length,j=l.filter(Boolean).length;P(`Models: ${j}/${f} passed`)}}catch(g){!_t.isCancel(g)&&(g==null?void 0:g.code)!=="ERR_CANCELED"&&P(Z(g,"Model test failed"),"error")}finally{ft(new Set),pt(null),Be.current===r&&(Be.current=null),Ze.current=!1,Mt(!1)}}const bt=es({mutationFn:async t=>{if(!d)return;const r=(H==null?void 0:H.providerStrategies)||{},l={...r[d.id]||{}};return t.strategy&&(l.fallbackStrategy=t.strategy),t.sticky&&(l.stickyRoundRobinLimit=t.sticky),ts({providerStrategies:{...r,[d.id]:l}})},onSuccess:()=>{s.invalidateQueries({queryKey:["settings"]})}}),vn=es({mutationFn:async t=>{if(d)return ts({providerThinking:{...(H==null?void 0:H.providerThinking)||{},[d.id]:t}})},onSuccess:()=>{s.invalidateQueries({queryKey:["settings"]})}});async function Kn(t){const r=it.find(l=>l.id===t);if(!(!r||Yt)){Et(t);try{const l=await $s(t,r.isActive!==!1);Fe(v=>v.map(g=>g.id===l.id?{...g,...l}:g)),s.invalidateQueries({queryKey:["connections"]}),s.invalidateQueries({queryKey:["providers-available"]}),P(`${l.name||r.name||"Connection"} ${l.isActive===!1?"disabled":"enabled"}`,"success")}catch(l){P(Z(l,"Failed to update connection"),"error")}finally{Et(null)}}}async function Rn(t,r){const l=se.findIndex(V=>V.id===t);if(l<0)return;const v=l+r;if(v<0||v>=se.length)return;const g=se[l],k=se[v],f=g.priority??(l+1)*10,j=k.priority??(v+1)*10;await Promise.all([zn(g.id,{priority:j}),zn(k.id,{priority:f})]),s.invalidateQueries({queryKey:["connections"]})}async function On(t){try{await Bn(t),s.invalidateQueries({queryKey:["connections"]}),s.invalidateQueries({queryKey:["providers-available"]}),G(null),P("Connection deleted","success")}catch(r){P(Z(r,"Failed to delete connection"),"error")}}async function Fn(){if(!(U!=null&&U.length)||Y)return;const t=U;$(!0);const r=[];try{for(const v of t)try{await Bn(v)}catch{r.push(v)}s.invalidateQueries({queryKey:["connections"]}),s.invalidateQueries({queryKey:["providers-available"]});const l=t.length-r.length;l===t.length?(te(new Set),_(null),P(`${l} connection${l===1?"":"s"} deleted`,"success")):l>0?(te(new Set(r)),_(null),P(`Deleted ${l} of ${t.length} connections`,"warning")):P("Could not delete the selected connections","error")}finally{$(!1)}}async function Dn(t){var v,g,k,f,j,V,W,ue,bn,wt,sn,rn,Bt,q;if(!d)return;if(t.alreadySaved){s.invalidateQueries({queryKey:["connections"]}),s.invalidateQueries({queryKey:["providers-available"]}),b(!1),P("Connection added");return}const r=t.proxyPoolId&&t.proxyPoolId!=="pool_none"?t.proxyPoolId:null;if((v=t.codeBuddyTokens)!=null&&v.length){if(d.id!=="codebuddy-cn"&&d.id!=="codebuddy-intl")throw new Error("Token batches are only supported for CodeBuddy");let I=0,X=0;for(const Me of t.codeBuddyTokens)try{await an({provider:d.id,credentialToken:Me.credentialToken,accessToken:Me.accessToken,refreshToken:Me.refreshToken,name:Me.name,autoName:Me.autoName,proxyPoolId:null}),I+=1}catch(qe){if(_t.isAxiosError(qe)&&((g=qe.response)==null?void 0:g.status)===409){X+=1;continue}throw qe}s.invalidateQueries({queryKey:["connections"]}),s.invalidateQueries({queryKey:["providers-available"]}),b(!1),P(X>0?`Added ${I} connections, skipped ${X} duplicates`:`Added ${I} connections`,X>0?"warning":"success");return}if((k=t.bulkKeys)!=null&&k.length){let I=0,X=0;for(const Me of t.bulkKeys)try{await an({provider:d.id,apiKey:Me.apiKey,name:Me.name,autoName:Me.autoName,proxyPoolId:r}),I+=1}catch(qe){if(_t.isAxiosError(qe)&&((f=qe.response)==null?void 0:f.status)===409){X+=1;continue}throw qe}s.invalidateQueries({queryKey:["connections"]}),s.invalidateQueries({queryKey:["providers-available"]}),b(!1),P(X>0?`Added ${I} connections, skipped ${X} duplicates`:`Added ${I} connections`,X>0?"warning":"success");return}const l=t.authFlow??kn(d.id,d.authType,d.noAuth);if(d.id==="kiro"&&t.kiroAuthMode==="api-key"){if(!((j=t.apiKey)!=null&&j.trim()))throw new Error("API key required");const I=await Qs({apiKey:t.apiKey.trim(),region:t.kiroRegion,name:t.name,autoName:t.autoName});if(!I.success)throw new Error(I.error||"Kiro API key validation failed")}else if(d.id==="kiro"&&t.kiroAuthMode==="import-token"){if(!((V=t.kiroRefreshToken)!=null&&V.trim()))throw new Error("Refresh token required");const I=await Vs({refreshToken:t.kiroRefreshToken.trim(),clientId:((W=t.kiroClientId)==null?void 0:W.trim())||void 0,clientSecret:((ue=t.kiroClientSecret)==null?void 0:ue.trim())||void 0,region:t.kiroRegion,profileArn:((bn=t.kiroProfileArn)==null?void 0:bn.trim())||void 0,name:t.name,autoName:t.autoName});if(!I.success)throw new Error(I.error||"Kiro token import failed")}else if(d.id==="kiro"&&t.kiroAuthMode==="cli-proxy"){if(!((wt=t.kiroCliProxyJson)!=null&&wt.trim()))throw new Error("CLIProxyAPI JSON required");let I;try{I=JSON.parse(t.kiroCliProxyJson)}catch{throw new Error("CLIProxyAPI JSON is invalid")}if(!I||typeof I!="object"||Array.isArray(I))throw new Error("CLIProxyAPI JSON must be an object");const X=await Ws({cliProxyAuth:I,name:t.name,autoName:t.autoName});if(!X.success)throw new Error(X.error||"CLIProxyAPI import failed")}else if(l==="import"&&(d.id==="codebuddy-cn"||d.id==="codebuddy-intl")){if(!((sn=t.codeBuddyToken)!=null&&sn.trim()))throw new Error("An access token or refresh token is required.");await an({provider:d.id,credentialToken:t.codeBuddyToken.trim(),name:t.name,autoName:t.autoName,proxyPoolId:null})}else if(l==="import"){if(!((rn=t.importToken)!=null&&rn.trim()))throw new Error("Access token required");const I=await Js(d.id,{accessToken:t.importToken.trim(),displayName:t.name,machineId:t.machineId});if(!I.success)throw new Error(I.error||"Token import failed")}else if(l==="oauth"){if(!((Bt=t.oauthCode)!=null&&Bt.trim()))throw new Error("Paste the OAuth code from the browser callback");await Hs(d.id,{code:t.oauthCode.trim(),state:t.oauthState,codeVerifier:t.oauthCodeVerifier,redirectUri:t.oauthRedirectUri,displayName:t.name})}else if(l==="device"){if(!t.deviceCode)throw new Error("Device code not started — wait for user code");const I=await fs(d.id,{deviceCode:t.deviceCode,codeVerifier:t.deviceCodeVerifier,displayName:t.name});if(I.pending)throw new Error("Still waiting for device authorization — keep polling");if(!I.success)throw new Error(I.error||"Device authorization failed")}else if(l==="local")await an({provider:d.id,name:t.name,autoName:t.autoName,proxyPoolId:r});else{if(!((q=t.apiKey)!=null&&q.trim()))throw new Error("API key required");await an({provider:d.id,apiKey:t.apiKey,name:t.name,autoName:t.autoName,proxyPoolId:r})}s.invalidateQueries({queryKey:["connections"]}),s.invalidateQueries({queryKey:["providers-available"]}),b(!1),P("Connection added")}function qn(t){const r=Se.filter(l=>l.provider===t.id);(async()=>{for(const l of r)try{await Bn(l.id)}catch{}ti(t.id).then(()=>{s.invalidateQueries({queryKey:["nodes"]}),s.invalidateQueries({queryKey:["providers-available"]}),s.invalidateQueries({queryKey:["connections"]}),P("Provider removed")})})(),R(null)}const yn=Ft.isLoading,m=d?d.isCustom?"apikey":kn(d.id,d.authType,d.noAuth):null;return e.jsxs("div",{className:ce("flex h-full w-full flex-col gap-1.5 overflow-hidden sm:gap-3 lg:gap-4"),children:[e.jsx(Ts,{className:"mb-0 sm:mb-0 shrink-0",title:"Providers",actions:e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.jsxs(E,{size:"sm",onClick:()=>Le(!0),children:[e.jsx(An,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:"Custom provider"}),e.jsx("span",{className:"sm:hidden",children:"Custom"})]})})}),e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-2 overflow-hidden sm:gap-3 lg:flex-row lg:gap-4",children:[e.jsx(Ji,{byProvider:Je,filter:y,hiddenProviders:N,loading:yn,query:c,providerListRef:st,selectedId:i,sorted:be,onFilterChange:C,onQueryChange:h,onSelectProvider:u,onToggleProviderHidden:qt}),e.jsx(ws,{className:"flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden",children:d?e.jsxs(e.Fragment,{children:[e.jsx(dr,{selected:d,conns:se,activeConns:He,onEditCustom:()=>pe(d),onDeleteCustom:()=>R(d),onAddConnection:()=>b(!0)}),e.jsx(js,{className:"flex min-h-0 flex-1 flex-col overflow-hidden p-0",children:e.jsxs(vs,{value:le,onValueChange:nt,defaultValue:"connections",className:"flex min-h-0 h-full flex-1 flex-col overflow-hidden",children:[e.jsx("div",{className:"shrink-0 border-b border-border px-2 py-2 sm:px-5 sm:py-3",children:e.jsxs(ys,{children:[e.jsx(Cn,{value:"connections",children:"Connection"}),e.jsx(Cn,{value:"models",children:"Models"})]})}),e.jsx(cr,{selected:d,connsAll:Se,conns:se,strategy:yt,strategyPending:bt.isPending,stickyDraft:me,thinkingLevels:Te,thinkingValue:ot,thinkingPending:vn.isPending,selectedKeys:ze,connectionsCapped:Ot,totalConnections:(Ce==null?void 0:Ce.totalItems)??Se.length,batchKind:Lt,testingConnId:Ht,togglingConnId:Yt,connQuery:je,connListRef:xt,connVirtualizer:we,connResults:Mn,onStrategyChange:t=>bt.mutate({strategy:t}),onStickyDraftChange:St,onSaveSticky:()=>{const t=Math.max(1,parseInt(me,10)||1);bt.mutate({sticky:t}),St(String(t))},onThinkingChange:t=>vn.mutate(t),onRequestBulkDelete:()=>_([...ze]),onClearSelection:()=>te(new Set),onToggleSelection:t=>{te(r=>{const l=new Set(r);return l.has(t)?l.delete(t):l.add(t),l})},onSelectAll:()=>te(new Set(se.map(t=>t.id))),onTestConnections:t=>pn(t),onTestConnection:t=>{nn(t)},onStopTests:$e,onConnQueryChange:Kt,onOpenAddConnection:()=>b(!0),onMovePriority:(t,r)=>Rn(t,r),onToggleConnection:t=>Kn(t),onEditConnection:z,onDeleteConnection:G}),e.jsx(Zi,{selected:d,visibleModels:hn,models:at,modelNames:En,modelsLoading:tn,modelsUnavailable:un,importingModels:S,testConnId:he,batchKind:Lt,modelTestLock:dn,testingModels:Gt,modelQuery:ke,newModel:re,addingModel:Ke,modelResults:Pn,pinnedFor:zt,copied:ht,onImportModels:()=>void gn(),onTestAllModels:()=>void In(),onStopTests:$e,onStopModel:lt,onModelQueryChange:Ve,onNewModelChange:ge,onAddModel:()=>void Ln(),onTogglePin:Ue,onCopyModelId:async t=>{await navigator.clipboard.writeText(t),At(t),window.setTimeout(()=>At(null),1e3)},onTestModel:(t,r)=>void xn(t,r),onRemoveModel:async t=>{let r=!1;try{const l=await hr(d.id,t);r=(l==null?void 0:l.removed)===!0}catch{}finally{Ye(d.id,t),B(l=>l+1),Nt(l=>l+1),s.invalidateQueries({queryKey:["sway-chat","models"]})}kt(`${r?"Removed":"Hidden"} ${t.split("/").pop()}`)},disabledModelIds:fn,onToggleDisabled:Q})]})})]}):e.jsx("div",{className:"flex flex-1 items-center justify-center p-6 text-sm text-muted-foreground",children:"Select a provider"})})]}),e.jsx(Vi,{open:A,provider:d,flow:m,onOpenChange:b,onSubmit:async t=>{try{await Dn(t)}catch(r){throw P(Z(r,"Add failed"),"error"),r}}}),e.jsx(Wi,{conn:F,onOpenChange:t=>!t&&z(null),onSave:async(t,r)=>{F&&(await zn(F.id,{name:t,...r.trim()?{apiKey:r.trim()}:{}}),s.invalidateQueries({queryKey:["connections"]}),z(null),P("Updated"))}}),e.jsx(ur,{deleteId:T,bulkDeleteIds:U,bulkDeleting:Y,deleteProvider:fe,connections:Se,onCloseDelete:()=>G(null),onDeleteConnection:()=>T?On(T):void 0,onCloseBulkDelete:()=>_(null),onDeleteSelectedConnections:Fn,onCloseProvider:()=>R(null),onRemoveProvider:qn}),e.jsx(ls,{open:Ee,onOpenChange:Le,onCreate:async t=>{const r=await Zs(t);s.invalidateQueries({queryKey:["nodes"]}),s.invalidateQueries({queryKey:["providers-available"]}),Le(!1),u(r.id),P("Custom provider created")}}),e.jsx(ls,{open:!!Ie,onOpenChange:t=>{t||pe(null)},initial:Ie,submitLabel:"Save",onCreate:async t=>{if(!Ie)return;const r=await ei(Ie.id,t);s.invalidateQueries({queryKey:["nodes"]}),s.invalidateQueries({queryKey:["providers-available"]}),s.invalidateQueries({queryKey:["connections"]}),pe(null),u(r.id),P("Custom provider updated")}})]})}export{Dr as compactErrorReason,qr as default};
@@ -1 +0,0 @@
1
- import{r as v,j as e,L as de}from"./react-vendor-xnYrwzsL.js";import{u as ce,a as ue,e as H}from"./query-vendor-DVevaSVS.js";import{g as G,c as C,P as me,Q as xe,C as he,p as Q,e as _,t as q,w as fe,R as pe,b as ge,h as ve}from"./index-B6j-9zHy.js";import{H as be}from"./Header-C_9Su9BF.js";import{R as z}from"./ripple-button-l8aMiVVG.js";import{S as y}from"./StatusBadge-1nAOyHU2.js";import{F as A,a as D,c as F,d as X}from"./frame-cUiti6Lq.js";import{S as N}from"./skeleton-7uJDiIXe.js";import{z as je,B as Ne}from"./connections-api-_N54UD3S.js";import{p as V}from"./live-mode-CHShLY4E.js";import{aa as B,i as Y,ay as we}from"./icons-vendor-CUx7SB5V.js";import"./ui-vendor-BuM9f2NY.js";import"./motion-vendor-g5fpGzmJ.js";const ye=new Set(["github","gemini-cli","antigravity","claude","codex","kiro","qoder","ollama","glm","glm-cn","minimax","minimax-cn","vercel-ai-gateway","codebuddy-cn","codebuddy-intl","grok-cli","kimi","deepseek"]),Ce=25,L=200,Ee=6,I=3,P=[];let O=0;function Z(){var t;for(;O<Ee&&P.length>0;){const r=P.shift();if(!r)return;if((t=r.signal)!=null&&t.aborted){r.cleanup(),r.reject(r.signal.reason??new DOMException("Quota request aborted","AbortError"));continue}O+=1,r.started=!0,r.run().then(r.resolve).catch(r.reject).finally(()=>{r.cleanup(),O-=1,Z()})}}function Re(t,r){return new Promise((n,a)=>{if(r!=null&&r.aborted){a(r.reason??new DOMException("Quota request aborted","AbortError"));return}const i={run:async()=>t(),resolve:n,reject:a,signal:r,started:!1,cleanup:()=>{}},l=()=>{if(i.started)return;const m=P.indexOf(i);m!==-1&&(P.splice(m,1),i.cleanup(),a((r==null?void 0:r.reason)??new DOMException("Quota request aborted","AbortError")))};r==null||r.addEventListener("abort",l,{once:!0}),i.cleanup=()=>r==null?void 0:r.removeEventListener("abort",l),P.push(i),Z()})}const T=["expired","authentication","unauthorized","401","re-authorize"];function Pe(t){if(!t)return!1;const r=t.toLowerCase();return T.some(n=>r.includes(n))}function Me(t){var n,a;if(he.isAxiosError(t)){if(((n=t.response)==null?void 0:n.status)===401)return!0;const i=(a=t.response)==null?void 0:a.data,l=(i==null?void 0:i.error)||(i==null?void 0:i.message)||"";if(T.some(m=>l.toLowerCase().includes(m)))return!0}const r=t instanceof Error?t.message:"";return T.some(i=>r.toLowerCase().includes(i))}function ke(t,r){return!r||r<=0?0:!t||t<0?100:t>=r?0:Math.round((r-t)/r*100)}function Qe(t,r){const n=r==null?void 0:r.quotas;if(!n||typeof n!="object")return[];const a=t.toLowerCase();return Object.entries(n).flatMap(([i,l])=>{const m=Number.isFinite(Number(l.used))?Number(l.used):0,c=Number.isFinite(Number(l.total))?Number(l.total):0,x=a==="codex"&&l.remaining!==void 0?Math.max(0,Math.round(Number(l.remaining))):l.remainingPercentage!==void 0?Math.max(0,Math.round(Number(l.remainingPercentage))):ke(m,c);return a==="qoder"&&i==="organization"&&c<=0?[]:[{name:a==="antigravity"?l.displayName||i:a==="qoder"?i==="user"?"Personal":i==="organization"?"Organization":i:i,used:m,total:c,remaining:x,resetAt:l.resetAt??null,recurring:l.recurring!==!1,unlimited:l.unlimited===!0||c<=0,unit:l.unit}]})}function Ae(t){if(!t)return null;const r=new Date(t).getTime()-Date.now();if(!Number.isFinite(r)||r<=0)return null;const n=Math.ceil(r/6e4);if(n<60)return`${n}m`;const a=Math.floor(n/60);return a<24?`${a}h ${n%60}m`:`${Math.floor(a/24)}d ${a%24}h ${n%60}m`}function j(t){return Number.isFinite(t)?Math.round(t).toLocaleString("id-ID"):"0"}function Fe(t){return t>70?{text:"text-success",bg:"bg-success",bgLight:"bg-success/10"}:t>=30?{text:"text-warning",bg:"bg-warning",bgLight:"bg-warning/10"}:{text:"text-destructive",bg:"bg-destructive",bgLight:"bg-destructive/10"}}function $e(t){if(t.loading)return null;if(t.authExpired)return e.jsx(y,{tone:"warn",children:"Auth expired"});if(t.error)return e.jsx(y,{tone:"err",children:"Error"});if(t.conn.isActive===!1)return e.jsx(y,{tone:"muted",children:"Disabled"});if(t.quotas.length===0)return e.jsx(y,{tone:"muted",children:"No quota"});const r=Math.min(...t.quotas.map(n=>n.remaining));return r<=0?e.jsx(y,{tone:"err",children:"Limit reached"}):r<30?e.jsx(y,{tone:"warn",children:"Low quota"}):e.jsx(y,{tone:"ok",children:"OK"})}function J({provider:t}){const r=fe(t),n=pe(t),a=ge(t);return e.jsx("span",{className:"grid h-9 w-9 shrink-0 place-items-center rounded-lg",style:{backgroundColor:`${n}1f`,color:n},children:a?e.jsx("span",{"aria-hidden":"true",className:"block h-4 w-4 shrink-0",style:{backgroundColor:n,WebkitMaskImage:`url(${a})`,maskImage:`url(${a})`,WebkitMaskPosition:"center",maskPosition:"center",WebkitMaskRepeat:"no-repeat",maskRepeat:"no-repeat",WebkitMaskSize:"contain",maskSize:"contain"}}):e.jsx(r,{className:"h-4 w-4"})})}function Xe(){const t=ce(),[r,n]=v.useState(null),[a,i]=v.useState({}),[,l]=v.useState(0);v.useEffect(()=>{const s=window.setInterval(()=>{l(o=>o+1)},6e4);return()=>window.clearInterval(s)},[]);const m=ue({queryKey:["quota-provider-counts"],queryFn:Ne,enabled:V(),retry:!1}),c=v.useMemo(()=>(m.data??[]).map(s=>({...s,provider:String(s.provider||"").trim()})).filter(s=>ye.has(s.provider)&&s.total>0),[m.data]);v.useEffect(()=>{i(s=>{const o={};for(const u of c)o[u.provider]=Math.max(1,s[u.provider]??1);return o})},[c]);const x=v.useMemo(()=>c.flatMap(s=>{const o=a[s.provider]??1;return Array.from({length:o},(u,d)=>({provider:s.provider,page:d+1}))}),[c,a]),f=H({queries:x.map(s=>({queryKey:["quota-connections",s.provider,s.page],queryFn:()=>je({provider:s.provider,page:s.page,pageSize:Ce}),enabled:V(),retry:!1,staleTime:3e4}))}),E=v.useMemo(()=>{const s=new Map;return x.forEach((o,u)=>{var b,h;const d=((h=(b=f[u])==null?void 0:b.data)==null?void 0:h.connections)??[],p=s.get(o.provider)??[],M=new Set(p.map(w=>w.id));s.set(o.provider,[...p,...d.filter(w=>!M.has(w.id))])}),s},[f,x]),ee=v.useMemo(()=>{var o,u,d;const s=new Map;for(const p of c){const b=x.map((g,le)=>g.provider===p.provider?le:-1).filter(g=>g>=0).map(g=>f[g]),h=b[b.length-1],w=(o=h==null?void 0:h.data)==null?void 0:o.pagination,k=((u=E.get(p.provider))==null?void 0:u.length)??0,W=k>=L&&k<p.total;s.set(p.provider,{loading:!!((d=b[0])!=null&&d.isPending),fetching:b.some(g=>g==null?void 0:g.isFetching),error:b.some(g=>g==null?void 0:g.isError),hasNext:!W&&(!!(w!=null&&w.hasNext)||k<p.total),capped:W,loaded:k})}return s},[f,E,x,c]),$=v.useMemo(()=>c.flatMap(s=>E.get(s.provider)??[]),[E,c]),S=H({queries:$.map(s=>({queryKey:["quota-usage",s.id],queryFn:({signal:o})=>Re(()=>xe(s.id,o),o),enabled:!!s.id,retry:!1,staleTime:3e4}))}),te=v.useMemo(()=>{const s=new Map;return $.forEach((o,u)=>{var b;const d=S[u];let p;if(!d||d.isPending)p={conn:o,loading:!0,fetching:!!(d!=null&&d.isFetching),error:null,authExpired:!1,usage:null,quotas:[],message:null,resetCredits:0,plan:null};else if(d.isError){const h=G(d.error,"Failed to fetch quota");p={conn:o,loading:!1,fetching:d.isFetching,error:h,authExpired:Me(d.error),usage:null,quotas:[],message:h,resetCredits:0,plan:null}}else{const h=d.data??{};p={conn:o,loading:!1,fetching:d.isFetching,error:null,authExpired:Pe(h.message),usage:h,quotas:Qe(o.provider,h),message:h.message??null,resetCredits:((b=h.resetCredits)==null?void 0:b.availableCount)??0,plan:h.plan??null}}const M=s.get(o.provider)??[];s.set(o.provider,[...M,p])}),s},[$,S]);function R(s,o="default"){o==="success"?q.success(s):o==="error"?q.error(s):q(s)}async function se(){await Promise.all([t.invalidateQueries({queryKey:["quota-provider-counts"]}),t.invalidateQueries({queryKey:["quota-connections"]}),t.invalidateQueries({queryKey:["quota-usage"]})]),R("Refreshed","success")}function re(s,o){Promise.all([t.invalidateQueries({queryKey:["quota-connections",s]}),...o.map(u=>t.invalidateQueries({queryKey:["quota-usage",u.conn.id]}))])}function ne(s){t.invalidateQueries({queryKey:["quota-usage",s]})}function oe(s){var u;if((((u=E.get(s))==null?void 0:u.length)??0)>=L){R(`Quota view is limited to ${j(L)} accounts per provider`);return}i(d=>({...d,[s]:(d[s]??1)+1}))}async function ie(s){if(!r){n(s.id);try{const o=await me(s.id);o.reset===!1||o.code==="no_credit"?R(o.message||"No Codex reset credits available","error"):R("Codex quota reset","success"),await t.invalidateQueries({queryKey:["quota-usage",s.id]})}catch(o){R(G(o,"Reset failed"),"error")}finally{n(null)}}}const K=m.isLoading,ae=!K&&c.length===0,U=m.isFetching||f.some(s=>s==null?void 0:s.isFetching)||S.some(s=>s==null?void 0:s.isFetching);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(be,{title:"Quota",actions:e.jsxs(z,{size:"sm",variant:"outline",disabled:U,onClick:()=>void se(),children:[e.jsx(B,{className:C("h-3.5 w-3.5",U&&"animate-spin")}),"Refresh"]})}),m.isError?e.jsx("div",{className:"rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive",children:"Unable to load live quota providers. Check your session and backend connection."}):null,K?e.jsx("div",{className:"space-y-4",children:["provider-skeleton-a","provider-skeleton-b"].map(s=>e.jsxs(A,{children:[e.jsxs(D,{className:"flex flex-row items-center gap-3 p-4",children:[e.jsx(N,{className:"h-9 w-9 rounded-lg"}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(N,{className:"h-4 w-28"}),e.jsx(N,{className:"h-3 w-44"})]})]}),e.jsx(F,{className:"grid gap-3 p-3 sm:grid-cols-2 xl:grid-cols-3",children:Array.from({length:3}).map((o,u)=>e.jsx(N,{className:"h-48 w-full rounded-xl"},u))})]},s))}):ae?e.jsx(A,{children:e.jsxs(F,{className:"p-10 text-center",children:[e.jsx("p",{className:"text-sm font-medium",children:"No providers connected"}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Connect an OAuth provider to track API quota limits and usage."})]})}):e.jsx("div",{className:"space-y-4",children:c.map(s=>{const o=te.get(s.provider)??[],u=ee.get(s.provider)??{loading:!0,fetching:!1,error:!1,hasNext:!1,capped:!1,loaded:0};return e.jsx(Se,{group:s,cards:o,pageState:u,onRefreshProvider:()=>re(s.provider,o),onRefreshCard:ne,onLoadMore:()=>oe(s.provider),onResetCodex:ie,resettingId:r},s.provider)})})]})}function Se({group:t,cards:r,pageState:n,onRefreshProvider:a,onRefreshCard:i,onLoadMore:l,onResetCodex:m,resettingId:c}){return e.jsxs(A,{children:[e.jsxs(D,{className:"flex flex-row items-start justify-between gap-3 p-4",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx(J,{provider:t.provider}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"truncate text-sm font-semibold",children:Q(t.provider)}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:n.loaded>0?`${n.loaded} of ${j(t.total)} accounts loaded`:`${j(t.total)} accounts`})]})]}),e.jsx(_,{label:`Refresh ${Q(t.provider)} quota`,children:e.jsx("button",{type:"button",onClick:a,disabled:n.fetching,className:"grid h-8 w-8 shrink-0 place-items-center rounded-md text-muted-foreground transition-colors hover:bg-surface-hover hover:text-foreground disabled:opacity-50","aria-label":`Refresh ${Q(t.provider)} quota`,children:e.jsx(B,{className:C("h-3.5 w-3.5",n.fetching&&"animate-spin")})})})]}),e.jsxs(F,{className:"p-3",children:[n.error?e.jsxs("div",{className:"mb-3 rounded-lg border border-destructive/25 bg-destructive/10 px-3 py-2 text-[11px] text-destructive",children:["Some ",Q(t.provider)," accounts could not be loaded. Refresh this section to retry."]}):null,n.loading&&r.length===0?e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-3",children:Array.from({length:3}).map((x,f)=>e.jsx(N,{className:"h-48 w-full rounded-xl"},f))}):r.length>0?e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-3",children:r.map(x=>e.jsx(qe,{card:x,onRefresh:()=>i(x.conn.id),onResetCodex:()=>m(x.conn),resetting:c===x.conn.id},x.conn.id))}):e.jsx("div",{className:"py-8 text-center text-[11px] text-muted-foreground",children:"No accounts available for this provider."})]}),n.hasNext||n.capped?e.jsxs(X,{className:"flex items-center justify-between gap-3 border-t border-border p-3",children:[e.jsx("span",{className:"text-[11px] tabular-nums text-muted-foreground",children:n.capped?`Showing ${j(n.loaded)} of ${j(t.total)} accounts. Quota loading is capped for performance.`:`Showing ${j(n.loaded)} of ${j(t.total)} accounts`}),n.hasNext?e.jsxs(z,{size:"sm",variant:"outline",onClick:l,disabled:n.fetching,children:[e.jsx(Y,{className:"h-3.5 w-3.5"}),n.fetching?"Loading…":"Load more"]}):null]}):null]})}function qe({card:t,onRefresh:r,onResetCodex:n,resetting:a}){const{conn:i}=t,[l,m]=v.useState(!1),c=t.authExpired?"Re-authorize the connection first":t.resetCredits<=0?"No Codex reset credits available":"Spend one Codex reset credit to reset the quota window",x=l?t.quotas:t.quotas.slice(0,I);return e.jsxs(A,{className:"flex flex-col",children:[e.jsxs(D,{className:"flex flex-row items-start justify-between gap-3 p-4",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(J,{provider:i.provider}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"truncate text-sm font-medium leading-tight",children:i.name||i.email||i.provider}),e.jsx("p",{className:"truncate text-[11px] text-muted-foreground",children:i.email&&i.name?i.email:`Connection ID · ${i.id}`})]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[$e(t),e.jsx(_,{label:"Refresh quota",children:e.jsx("button",{type:"button",onClick:r,disabled:t.fetching,className:"grid h-7 w-7 place-items-center rounded-md text-muted-foreground transition-colors hover:bg-surface-hover hover:text-foreground disabled:opacity-50","aria-label":t.fetching?"Refreshing quota":"Refresh quota",children:e.jsx(B,{className:C("h-3.5 w-3.5",t.fetching&&"animate-spin")})})})]})]}),e.jsxs(F,{className:"flex min-h-0 flex-1 flex-col gap-3 p-4",children:[t.plan?e.jsx(ve,{variant:"outline",className:"w-fit text-[10px]",children:t.plan}):null,e.jsx("div",{className:"min-h-[3.5rem] flex-1",children:t.loading?e.jsxs("div",{className:"space-y-2",children:[e.jsx(N,{className:"h-4 w-full"}),e.jsx(N,{className:"h-1.5 w-full"}),e.jsx(N,{className:"h-3 w-2/3"})]}):t.authExpired?e.jsxs("div",{className:"rounded-lg border border-warning/25 bg-warning/10 px-3 py-2",children:[e.jsx("p",{className:"text-xs font-medium text-warning",children:"Authentication expired"}),e.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:t.message||t.error}),e.jsx(de,{to:"/dashboard/provider",className:"mt-1.5 inline-block text-[11px] font-medium text-warning underline underline-offset-2",children:"Re-authorize in Providers"})]}):t.error?e.jsxs("div",{className:"rounded-lg border border-destructive/25 bg-destructive/10 px-3 py-2",children:[e.jsx("p",{className:"text-xs font-medium text-destructive",children:"Failed to load quota"}),e.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:t.error})]}):t.quotas.length>0?e.jsxs("div",{className:"space-y-3",children:[t.message?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:t.message}):null,x.map(f=>e.jsx(Le,{quota:f},`${f.name}-${f.unit??""}`)),t.quotas.length>I?e.jsxs("button",{type:"button",onClick:()=>m(f=>!f),className:"inline-flex items-center gap-1 text-[11px] font-medium text-muted-foreground transition-colors hover:text-foreground",children:[e.jsx(Y,{className:C("h-3 w-3 transition-transform",l&&"rotate-180")}),l?"Show less":`Show ${t.quotas.length-I} more`]}):null]}):t.message?e.jsx("div",{className:"rounded-lg border border-border bg-surface px-3 py-2 text-[11px] text-muted-foreground",children:t.message}):e.jsx("div",{className:"py-6 text-center text-[11px] text-muted-foreground",children:"No quota data available"})})]}),i.provider==="codex"?e.jsxs(X,{className:"flex items-center justify-between gap-2 border-t border-border p-4",children:[e.jsxs("span",{className:"text-[11px] tabular-nums text-muted-foreground",children:[t.resetCredits," reset credit",t.resetCredits===1?"":"s"]}),e.jsx(_,{label:c,children:e.jsxs(z,{size:"sm",variant:"outline",onClick:n,disabled:t.resetCredits<=0||t.authExpired||a||t.loading,children:[e.jsx(we,{className:"h-3.5 w-3.5"}),a?"Resetting…":"Reset quota"]})})]}):null]})}function Le({quota:t}){const r=Fe(t.remaining),n=Ae(t.resetAt),a=t.recurring?"Reset":"Expires";return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"min-w-0 truncate text-xs font-medium",children:t.name}),e.jsxs("span",{className:C("shrink-0 text-xs font-medium tabular-nums",r.text),children:[t.remaining,"%"]})]}),t.unlimited?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Unlimited"}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:C("h-1.5 overflow-hidden rounded-full",r.bgLight),children:e.jsx("div",{className:C("h-full rounded-full transition-all duration-300",r.bg),style:{width:`${Math.min(t.remaining,100)}%`}})}),e.jsxs("div",{className:"flex items-center justify-between gap-2 text-[10px] text-muted-foreground",children:[e.jsxs("span",{className:"tabular-nums",children:[j(t.used)," / ",t.total>0?j(t.total):"∞"]}),n?e.jsxs("span",{className:"tabular-nums",children:[a," in ",n]}):null]})]})]})}export{Xe as default};