@fudrouter/fsrouter 0.6.107 → 0.6.108
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/routes/db/info/route.js +22 -0
- package/package.json +1 -1
- package/public/.vite/manifest.json +85 -85
- package/public/assets/EndpointPageClient.BN-D__UM.js +6 -0
- package/public/assets/Loading.BoU3gy5K.js +1 -0
- package/public/assets/NoAuthProxyCard.CLW2-XwE.js +89 -0
- package/public/assets/index.BO_pNnMt.js +89 -0
- package/public/assets/page.-P08pALK.js +6 -0
- package/public/assets/page.-PU2bgJe.js +1 -0
- package/public/assets/page.2bfZgPuP.js +1 -0
- package/public/assets/page.Asf9tesx.js +1 -0
- package/public/assets/page.B11lN3QC.js +1 -0
- package/public/assets/page.B1ZhgC-Y.js +1 -0
- package/public/assets/page.B28QUiM4.js +1 -0
- package/public/assets/page.BBnpNaQh.js +6 -0
- package/public/assets/page.BOy_Vt2f.js +1 -0
- package/public/assets/page.BRDONwuI.js +1 -0
- package/public/assets/page.BWFxAlAj.js +1 -0
- package/public/assets/page.BebFlAF6.js +1 -0
- package/public/assets/page.BqxsFxH_.js +2 -0
- package/public/assets/page.C1Z5-h5h.js +1 -0
- package/public/assets/page.CIxYSsJm.js +1 -0
- package/public/assets/page.CQLGTJxs.js +1 -0
- package/public/assets/page.CTO5ojlP.js +1 -0
- package/public/assets/page.CTx0rdSY.js +1 -0
- package/public/assets/page.CXAgJ2hd.js +1 -0
- package/public/assets/page.CdVrDM5I.js +1 -0
- package/public/assets/page.CgidHjOu.js +1 -0
- package/public/assets/page.CqPzqV4I.js +7 -0
- package/public/assets/page.Cr-bxDIh.js +4 -0
- package/public/assets/page.CsL3JXbA.js +1 -0
- package/public/assets/page.D6eEvzRr.js +5 -0
- package/public/assets/page.DHyqPTHy.js +1 -0
- package/public/assets/page.DS5iFEwr.js +31 -0
- package/public/assets/page.Dre9jdlU.js +1 -0
- package/public/assets/page.IyBPROCc.js +1 -0
- package/public/assets/page.KoOCODPg.js +5 -0
- package/public/assets/page.MP_9jcAE.js +1 -0
- package/public/assets/page.WAG7HQOU.js +2 -0
- package/public/assets/page.XKedaymF.js +1 -0
- package/public/assets/page.ZZHz9al1.js +64 -0
- package/public/assets/page.alTMqTdj.js +1 -0
- package/public/assets/page.tpebkgG7.js +1 -0
- package/public/assets/page.xIh7b02j.js +23 -0
- package/public/index.html +4 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{F as le,j as e,g as Y,n as k,B as q,o as oe}from"./index.BO_pNnMt.js";import{d as se,f as re,b as x}from"./router.Cjj1--8t.js";import{B as I,f as D,c as M,d as ie,P as de,U as ce,e as xe,C as V}from"./NoAuthProxyCard.CLW2-XwE.js";import{C as ae}from"./Loading.BoU3gy5K.js";import"./zustand.akaTi5uX.js";function Q(s){if(s==="leonardo"||s==="weavy")return!0;const t=Y[s];return t!=null&&t.serviceKinds?t.serviceKinds.includes("llm"):!0}function me(s){const t=Math.floor((Date.now()-new Date(s))/1e3);return t<60?`${t}s ago`:t<3600?`${Math.floor(t/60)}m ago`:t<86400?`${Math.floor(t/3600)}h ago`:`${Math.floor(t/86400)}d ago`}function ue({timestamp:s}){const[,t]=x.useState(0);return x.useEffect(()=>{const r=setInterval(()=>t(a=>a+1),1e3);return()=>clearInterval(r)},[]),e.jsx(e.Fragment,{children:me(s)})}function pe({requests:s=[]}){return e.jsxs(V,{className:"flex min-w-0 flex-col overflow-hidden",padding:"sm",style:{height:480},children:[e.jsx("div",{className:"px-1 py-2 border-b border-border shrink-0",children:e.jsx("span",{className:"text-xs font-semibold text-text-muted uppercase tracking-wide",children:"Recent Requests"})}),s.length?e.jsx("div",{className:"flex-1 overflow-y-auto",children:e.jsxs("table",{className:"w-full min-w-[300px] border-collapse text-xs",children:[e.jsx("thead",{className:"sticky top-0 bg-bg z-10",children:e.jsxs("tr",{className:"border-b border-border",children:[e.jsx("th",{className:"py-1.5 text-left font-semibold text-text-muted w-2"}),e.jsx("th",{className:"py-1.5 text-left font-semibold text-text-muted",children:"Model"}),e.jsx("th",{className:"py-1.5 text-right font-semibold text-text-muted whitespace-nowrap",children:"In / Out"}),e.jsx("th",{className:"py-1.5 text-right font-semibold text-text-muted",children:"When"})]})}),e.jsx("tbody",{className:"divide-y divide-border/50",children:s.map((t,r)=>{const a=t.status==="streaming",i=!t.status||t.status==="ok"||t.status==="success";return e.jsxs("tr",{className:"hover:bg-bg-subtle transition-colors",children:[e.jsx("td",{className:"py-1.5",children:a?e.jsx("span",{className:"block w-1.5 h-1.5 rounded-full bg-warning animate-pulse",title:"Streaming…"}):e.jsx("span",{className:`block w-1.5 h-1.5 rounded-full ${i?"bg-success":"bg-error"}`})}),e.jsx("td",{className:"py-1.5 font-mono truncate max-w-[120px]",title:t.model,children:t.model}),e.jsx("td",{className:"py-1.5 text-right whitespace-nowrap",children:a?e.jsx("span",{className:"text-warning italic text-[10px]",children:"streaming…"}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"text-primary",children:[D(t.promptTokens),"↑"]})," ",e.jsxs("span",{className:"text-success",children:[D(t.completionTokens),"↓"]})]})}),e.jsx("td",{className:"py-1.5 text-right text-text-muted whitespace-nowrap",children:e.jsx(ue,{timestamp:t.timestamp})})]},r)})})]})}):e.jsx("div",{className:"flex-1 flex items-center justify-center text-text-muted text-sm",children:"No requests yet."})]})}function _(s,t={},r,a){return Object.entries(s||{}).map(([i,o])=>{const n=(o.promptTokens||0)+(o.completionTokens||0),l=o.cost||0,b=n>0?(o.promptTokens||0)*(l/n):0,p=n>0?(o.completionTokens||0)*(l/n):0;return{...o,key:i,totalTokens:n,totalCost:l,inputCost:b,outputCost:p,pending:t[i]||0}}).sort((i,o)=>{let n=i[r],l=o[r];return typeof n=="string"&&(n=n.toLowerCase()),typeof l=="string"&&(l=l.toLowerCase()),n<l?a==="asc"?-1:1:n>l?a==="asc"?1:-1:0})}function he(s,t){var r;switch(t){case"rawModel":return s.rawModel||"Unknown Model";case"accountName":return s.accountName||`Account ${(r=s.connectionId)==null?void 0:r.slice(0,8)}...`||"Unknown Account";case"keyName":return s.keyName||"Unknown Key";case"endpoint":return s.endpoint||"Unknown Endpoint";default:return s[t]||"Unknown"}}function K(s,t){if(!Array.isArray(s))return[];const r={};return s.forEach(a=>{const i=he(a,t);r[i]||(r[i]={groupKey:i,summary:{requests:0,promptTokens:0,completionTokens:0,totalTokens:0,cost:0,inputCost:0,outputCost:0,lastUsed:null,pending:0},items:[]});const o=r[i].summary;o.requests+=a.requests||0,o.promptTokens+=a.promptTokens||0,o.completionTokens+=a.completionTokens||0,o.totalTokens+=a.totalTokens||0,o.cost+=a.cost||0,o.inputCost+=a.inputCost||0,o.outputCost+=a.outputCost||0,o.pending+=a.pending||0,a.lastUsed&&(!o.lastUsed||new Date(a.lastUsed)>new Date(o.lastUsed))&&(o.lastUsed=a.lastUsed),r[i].items.push(a)}),Object.values(r)}const fe=[{field:"rawModel",label:"Model"},{field:"provider",label:"Provider"},{field:"requests",label:"Requests",align:"right"},{field:"lastUsed",label:"Last Used",align:"right"}],be=[{field:"rawModel",label:"Model"},{field:"provider",label:"Provider"},{field:"accountName",label:"Account"},{field:"requests",label:"Requests",align:"right"},{field:"lastUsed",label:"Last Used",align:"right"}],ge=[{field:"keyName",label:"API Key Name"},{field:"rawModel",label:"Model"},{field:"provider",label:"Provider"},{field:"requests",label:"Requests",align:"right"},{field:"lastUsed",label:"Last Used",align:"right"}],je=[{field:"endpoint",label:"Endpoint"},{field:"rawModel",label:"Model"},{field:"provider",label:"Provider"},{field:"requests",label:"Requests",align:"right"},{field:"lastUsed",label:"Last Used",align:"right"}],ve=[{value:"model",label:"Usage by Model"},{value:"account",label:"Usage by Account"},{value:"apiKey",label:"Usage by API Key"},{value:"endpoint",label:"Usage by Endpoint"}],ye=[{value:"today",label:"Today"},{value:"24h",label:"24h"},{value:"7d",label:"7D"},{value:"30d",label:"30D"},{value:"60d",label:"60D"}];function X(s){if(!s)return s;const t={...s};if(t.byProvider&&(t.byProvider={...t.byProvider},t.byProvider.cb)){if(!t.byProvider.codebuddy)t.byProvider.codebuddy=t.byProvider.cb;else{const r=t.byProvider.cb,a=t.byProvider.codebuddy;t.byProvider.codebuddy={requests:(a.requests||0)+(r.requests||0),promptTokens:(a.promptTokens||0)+(r.promptTokens||0),completionTokens:(a.completionTokens||0)+(r.completionTokens||0),cost:(a.cost||0)+(r.cost||0)}}delete t.byProvider.cb}return t.byModel&&(t.byModel=Object.fromEntries(Object.entries(t.byModel).map(([r,a])=>r.endsWith(" (cb)")?[r.slice(0,-5)+" (codebuddy)",{...a,provider:"CodeBuddy"}]:[r,a]))),t.byAccount&&(t.byAccount=Object.fromEntries(Object.entries(t.byAccount).map(([r,a])=>a.provider==="cb"||a.provider==="Codebuddy"||a.provider==="codebuddy"?[r,{...a,provider:"CodeBuddy"}]:[r,a]))),Array.isArray(t.recentRequests)&&(t.recentRequests=t.recentRequests.map(r=>r.provider==="cb"?{...r,provider:"codebuddy"}:r)),t}function Ne({period:s,setPeriod:t,hidePeriodSelector:r=!1}={}){var E,c,w,C;const a=se(),[i]=re(),o=i.get("sortBy")||"rawModel",n=i.get("sortOrder")||"asc",[l,b]=x.useState(null),[p,j]=x.useState(!0),[f,P]=x.useState(!1),[y,h]=x.useState("model"),[N,L]=x.useState("costs"),[O,J]=x.useState([]),[G,W]=x.useState("today"),A=x.useRef(!0),T=s??G,F=t??W;x.useEffect(()=>{fetch("/api/providers").then(m=>m.ok?m.json():null).then(m=>{const v=new Set,d=((m==null?void 0:m.connections)||[]).filter(g=>g.isActive===!1||!Q(g.provider)||v.has(g.provider)?!1:(v.add(g.provider),!0)),u=Object.values(le).filter(g=>g.noAuth&&!v.has(g.id)&&Q(g.id)).map(g=>({provider:g.id,name:g.name}));J([...d,...u])}).catch(()=>{})},[]),x.useEffect(()=>{A.current?(A.current=!1,j(!0)):P(!0),fetch(`/api/usage/stats?period=${T}`).then(m=>m.ok?m.json():null).then(m=>{if(m){const v=X(m);b(d=>({...d,...v}))}}).catch(()=>{}).finally(()=>{j(!1),P(!1)})},[T]),x.useEffect(()=>{const m=new EventSource(`/api/usage/stream?period=${T}`);return m.onmessage=v=>{try{const d=JSON.parse(v.data),u=X(d);b(u),j(!1)}catch(d){console.error("[SSE CLIENT] parse error:",d)}},m.onerror=()=>j(!1),()=>m.close()},[T]);const $=x.useCallback((m,v)=>{const d=new URLSearchParams(i.toString());d.get("sortBy")===v?d.set("sortOrder",d.get("sortOrder")==="asc"?"desc":"asc"):(d.set("sortBy",v),d.set("sortOrder","asc")),a(`?${d.toString()}`,{scroll:!1})},[i,a]),S=x.useMemo(()=>{var m,v;if(!l)return null;switch(y){case"model":{const d=((m=l.pending)==null?void 0:m.byModel)||{};return{columns:fe,groupedData:K(_(l.byModel,d,o,n),"rawModel"),storageKey:"usage-stats:expanded-models",emptyMessage:"No usage recorded yet.",renderSummaryCells:u=>e.jsxs(e.Fragment,{children:[e.jsx("td",{className:"px-6 py-3 text-text-muted",children:"—"}),e.jsx("td",{className:"px-6 py-3 text-right",children:D(u.summary.requests)}),e.jsx("td",{className:"px-6 py-3 text-right text-text-muted whitespace-nowrap",children:M(u.summary.lastUsed)})]}),renderDetailCells:u=>e.jsxs(e.Fragment,{children:[e.jsx("td",{className:`px-6 py-3 font-medium transition-colors ${u.pending>0?"text-primary":""}`,children:u.rawModel}),e.jsx("td",{className:"px-6 py-3",children:e.jsx(I,{variant:u.pending>0?"primary":"neutral",size:"sm",children:u.provider})}),e.jsx("td",{className:"px-6 py-3 text-right",children:D(u.requests)}),e.jsx("td",{className:"px-6 py-3 text-right text-text-muted whitespace-nowrap",children:M(u.lastUsed)})]})}}case"account":{const d={};return(v=l==null?void 0:l.pending)!=null&&v.byAccount&&Object.entries(l.byAccount||{}).forEach(([u,g])=>{const H=l.pending.byAccount[g.connectionId];if(H){const ne=g.provider?`${g.rawModel} (${g.provider})`:g.rawModel;d[u]=H[ne]||0}}),{columns:be,groupedData:K(_(l.byAccount,d,o,n),"accountName"),storageKey:"usage-stats:expanded-accounts",emptyMessage:"No account-specific usage recorded yet.",renderSummaryCells:u=>e.jsxs(e.Fragment,{children:[e.jsx("td",{className:"px-6 py-3 text-text-muted",children:"—"}),e.jsx("td",{className:"px-6 py-3 text-text-muted",children:"—"}),e.jsx("td",{className:"px-6 py-3 text-right",children:D(u.summary.requests)}),e.jsx("td",{className:"px-6 py-3 text-right text-text-muted whitespace-nowrap",children:M(u.summary.lastUsed)})]}),renderDetailCells:u=>{var g;return e.jsxs(e.Fragment,{children:[e.jsx("td",{className:`px-6 py-3 font-medium transition-colors ${u.pending>0?"text-primary":""}`,children:u.accountName||`Account ${(g=u.connectionId)==null?void 0:g.slice(0,8)}...`}),e.jsx("td",{className:`px-6 py-3 font-medium transition-colors ${u.pending>0?"text-primary":""}`,children:u.rawModel}),e.jsx("td",{className:"px-6 py-3",children:e.jsx(I,{variant:u.pending>0?"primary":"neutral",size:"sm",children:u.provider})}),e.jsx("td",{className:"px-6 py-3 text-right",children:D(u.requests)}),e.jsx("td",{className:"px-6 py-3 text-right text-text-muted whitespace-nowrap",children:M(u.lastUsed)})]})}}}case"apiKey":return{columns:ge,groupedData:K(_(l.byApiKey,{},o,n),"keyName"),storageKey:"usage-stats:expanded-apikeys",emptyMessage:"No API key usage recorded yet.",renderSummaryCells:d=>e.jsxs(e.Fragment,{children:[e.jsx("td",{className:"px-6 py-3 text-text-muted",children:"—"}),e.jsx("td",{className:"px-6 py-3 text-text-muted",children:"—"}),e.jsx("td",{className:"px-6 py-3 text-right",children:D(d.summary.requests)}),e.jsx("td",{className:"px-6 py-3 text-right text-text-muted whitespace-nowrap",children:M(d.summary.lastUsed)})]}),renderDetailCells:d=>e.jsxs(e.Fragment,{children:[e.jsx("td",{className:"px-6 py-3 font-medium",children:d.keyName}),e.jsx("td",{className:"px-6 py-3",children:d.rawModel}),e.jsx("td",{className:"px-6 py-3",children:e.jsx(I,{variant:"neutral",size:"sm",children:d.provider})}),e.jsx("td",{className:"px-6 py-3 text-right",children:D(d.requests)}),e.jsx("td",{className:"px-6 py-3 text-right text-text-muted whitespace-nowrap",children:M(d.lastUsed)})]})};case"endpoint":default:return{columns:je,groupedData:K(_(l.byEndpoint,{},o,n),"endpoint"),storageKey:"usage-stats:expanded-endpoints",emptyMessage:"No endpoint usage recorded yet.",renderSummaryCells:d=>e.jsxs(e.Fragment,{children:[e.jsx("td",{className:"px-6 py-3 text-text-muted",children:"—"}),e.jsx("td",{className:"px-6 py-3 text-text-muted",children:"—"}),e.jsx("td",{className:"px-6 py-3 text-right",children:D(d.summary.requests)}),e.jsx("td",{className:"px-6 py-3 text-right text-text-muted whitespace-nowrap",children:M(d.summary.lastUsed)})]}),renderDetailCells:d=>e.jsxs(e.Fragment,{children:[e.jsx("td",{className:"px-6 py-3 font-medium font-mono text-sm",children:d.endpoint}),e.jsx("td",{className:"px-6 py-3",children:d.rawModel}),e.jsx("td",{className:"px-6 py-3",children:e.jsx(I,{variant:"neutral",size:"sm",children:d.provider})}),e.jsx("td",{className:"px-6 py-3 text-right",children:D(d.requests)}),e.jsx("td",{className:"px-6 py-3 text-right text-text-muted whitespace-nowrap",children:M(d.lastUsed)})]})}}},[l,y,o,n]);if(!l&&!p)return e.jsx("div",{className:"text-text-muted",children:"Failed to load usage statistics."});const R=e.jsx("div",{className:"flex items-center justify-center py-12 text-text-muted",children:e.jsx("span",{className:"material-symbols-outlined text-[32px] animate-spin",children:"progress_activity"})});return e.jsxs("div",{className:"flex min-w-0 flex-col gap-6",children:[!r&&e.jsxs("div",{className:"flex w-full items-center gap-2 sm:w-auto sm:self-end",children:[e.jsx("div",{className:"grid flex-1 grid-cols-5 items-center gap-1 rounded-lg border border-border bg-bg-subtle p-1 sm:flex sm:flex-none",children:ye.map(m=>e.jsx("button",{onClick:()=>F(m.value),disabled:f,className:`rounded-md px-3 py-1 text-sm font-medium transition-colors ${T===m.value?"bg-primary text-white shadow-sm":"text-text-muted hover:bg-bg-hover hover:text-text"}`,children:m.label},m.value))}),f&&e.jsx("span",{className:"material-symbols-outlined text-[16px] text-text-muted animate-spin",children:"progress_activity"})]}),p?R:e.jsx(ie,{stats:l}),p?R:e.jsxs("div",{className:"grid min-w-0 grid-cols-1 items-stretch gap-2 lg:grid-cols-[minmax(0,2fr)_minmax(280px,1fr)]",children:[e.jsx(de,{providers:O,activeRequests:l.activeRequests||[],lastProvider:((c=(E=l.recentRequests)==null?void 0:E[0])==null?void 0:c.provider)||"",errorProvider:l.errorProvider||""}),e.jsx(pe,{requests:l.recentRequests||[]})]}),p?R:e.jsx(ce,{period:T,lastRequestTime:(C=(w=l==null?void 0:l.recentRequests)==null?void 0:w[0])==null?void 0:C.timestamp}),e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("select",{value:y,onChange:m=>h(m.target.value),className:"w-full rounded-lg border border-border bg-surface px-3 py-1.5 text-sm font-medium text-text-main focus:outline-none focus:ring-2 focus:ring-primary/50 sm:w-auto",style:{colorScheme:"auto"},children:ve.map(m=>e.jsx("option",{value:m.value,children:m.label},m.value))}),e.jsxs("div",{className:"grid grid-cols-2 items-center gap-1 rounded-lg border border-border bg-bg-subtle p-1 sm:flex",children:[e.jsx("button",{onClick:()=>L("costs"),className:`px-3 py-1 rounded-md text-sm font-medium transition-colors ${N==="costs"?"bg-primary text-white shadow-sm":"text-text-muted hover:text-text hover:bg-bg-hover"}`,children:"Costs"}),e.jsx("button",{onClick:()=>L("tokens"),className:`px-3 py-1 rounded-md text-sm font-medium transition-colors ${N==="tokens"?"bg-primary text-white shadow-sm":"text-text-muted hover:text-text hover:bg-bg-hover"}`,children:"Tokens"})]})]}),p?R:S&&e.jsx(xe,{title:"",columns:S.columns,groupedData:S.groupedData,tableType:y,sortBy:o,sortOrder:n,onToggleSort:$,viewMode:N,storageKey:S.storageKey,renderSummaryCells:S.renderSummaryCells,renderDetailCells:S.renderDetailCells,emptyMessage:S.emptyMessage})]})]})}function we(){const[s,t]=x.useState([]),[r,a]=x.useState(!0),[i,o]=x.useState(!0);x.useEffect(()=>{n()},[]),x.useEffect(()=>{let l;return i&&(l=setInterval(()=>{n(!1)},3e3)),()=>clearInterval(l)},[i]);const n=async(l=!0)=>{l&&a(!0);try{const b=await fetch("/api/usage/request-logs");if(b.ok){const p=await b.json();t(p)}}catch(b){console.error("Failed to fetch logs:",b)}finally{l&&a(!1)}};return e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Request Logs"}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("label",{className:"text-sm font-medium text-text-muted flex items-center gap-2 cursor-pointer",children:[e.jsx("span",{children:"Auto Refresh (3s)"}),e.jsx("div",{onClick:()=>o(!i),className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors focus:outline-none ${i?"bg-primary":"bg-bg-subtle border border-border"}`,children:e.jsx("span",{className:`inline-block h-3 w-3 transform rounded-full bg-white transition-transform ${i?"translate-x-5":"translate-x-1"}`})})]})})]}),e.jsx(V,{className:"overflow-hidden bg-black/5 dark:bg-black/20",children:e.jsx("div",{className:"p-0 overflow-x-auto max-h-[600px] overflow-y-auto font-mono text-xs",children:r&&s.length===0?e.jsx("div",{className:"p-8 text-center text-text-muted",children:"Loading logs..."}):s.length===0?e.jsx("div",{className:"p-8 text-center text-text-muted",children:"No logs recorded yet."}):e.jsxs("table",{className:"w-full text-left border-collapse whitespace-nowrap",children:[e.jsx("thead",{className:"sticky top-0 bg-bg-subtle border-b border-border z-10",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2 border-r border-border",children:"DateTime"}),e.jsx("th",{className:"px-3 py-2 border-r border-border",children:"Model"}),e.jsx("th",{className:"px-3 py-2 border-r border-border",children:"Provider"}),e.jsx("th",{className:"px-3 py-2 border-r border-border",children:"Account"}),e.jsx("th",{className:"px-3 py-2 border-r border-border",children:"In"}),e.jsx("th",{className:"px-3 py-2 border-r border-border",children:"Out"}),e.jsx("th",{className:"px-3 py-2",children:"Status"})]})}),e.jsx("tbody",{className:"divide-y divide-border/50",children:s.map((l,b)=>{const p=l.split(" | ");if(p.length<7)return null;const j=p[6],f=j.includes("PENDING"),P=j.includes("FAILED"),y=j.includes("OK");return e.jsxs("tr",{className:`hover:bg-primary/5 transition-colors ${f?"bg-primary/5":""}`,children:[e.jsx("td",{className:"px-3 py-1.5 border-r border-border text-text-muted",children:p[0]}),e.jsx("td",{className:"px-3 py-1.5 border-r border-border font-medium",children:p[1]}),e.jsx("td",{className:"px-3 py-1.5 border-r border-border",children:e.jsx("span",{className:"px-1.5 py-0.5 rounded bg-bg-subtle border border-border text-[10px] uppercase font-bold",children:p[2]})}),e.jsx("td",{className:"px-3 py-1.5 border-r border-border truncate max-w-[150px]",title:p[3],children:p[3]}),e.jsx("td",{className:"px-3 py-1.5 border-r border-border text-right text-primary",children:p[4]}),e.jsx("td",{className:"px-3 py-1.5 border-r border-border text-right text-success",children:p[5]}),e.jsx("td",{className:`px-3 py-1.5 font-bold ${y?"text-success":P?"text-error":"text-primary animate-pulse"}`,children:j})]},b)})})]})})}),e.jsx("div",{className:"text-[10px] text-text-muted italic",children:"Logs are loaded from the request history database."})]})}function Z({options:s=[],value:t,onChange:r,size:a="md",className:i}){const o={sm:"h-7 text-xs",md:"h-9 text-sm",lg:"h-11 text-base"};return e.jsx("div",{className:k("inline-flex items-center p-1 rounded-[10px] overflow-x-auto","bg-surface-2",i),children:s.map(n=>e.jsxs("button",{onClick:()=>r(n.value),className:k("shrink-0 px-4 rounded-[8px] font-medium transition-all",o[a],t===n.value?"bg-surface text-text-main shadow-sm":"text-text-muted hover:text-text-main"),children:[n.icon&&e.jsx("span",{className:"material-symbols-outlined text-[16px] mr-1.5",children:n.icon}),n.label]},n.value))})}function ke({isOpen:s,onClose:t,title:r,children:a,width:i="md",className:o}){const n={sm:"w-[400px]",md:"w-[500px]",lg:"w-[600px]",xl:"w-[800px]",full:"w-full"};return x.useEffect(()=>(s?document.body.style.overflow="hidden":document.body.style.overflow="",()=>{document.body.style.overflow=""}),[s]),x.useEffect(()=>{const l=b=>{b.key==="Escape"&&s&&t()};return document.addEventListener("keydown",l),()=>document.removeEventListener("keydown",l)},[s,t]),s?e.jsxs("div",{className:"fixed inset-0 z-50",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50 backdrop-blur-[2px] fade-in cursor-pointer",onClick:t,"aria-hidden":"true"}),e.jsxs("div",{className:k("absolute right-0 top-0 h-full bg-surface flex flex-col","shadow-[var(--shadow-elev)]","slide-in-right","border-l border-border-subtle",n[i]||n.md,o),children:[e.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-border-subtle flex-shrink-0",children:[e.jsx("div",{className:"flex items-center gap-3",children:r&&e.jsx("h2",{className:"text-lg font-semibold text-text-main",children:r})}),e.jsx("button",{type:"button",onClick:t,className:"p-1.5 rounded-[10px] text-text-muted hover:bg-surface-2 hover:text-text-main transition-colors",children:e.jsx("span",{className:"material-symbols-outlined text-[20px]",children:"close"})})]}),e.jsx("div",{className:"flex-1 overflow-y-auto p-6 custom-scrollbar",children:a})]})]}):null}function Se({currentPage:s,pageSize:t,totalItems:r,onPageChange:a,onPageSizeChange:i,className:o}){const n=Math.ceil(r/t),l=r>0?(s-1)*t+1:0,b=Math.min(s*t,r),j=(()=>{const f=[];let y=Math.max(1,s-2),h=Math.min(n,y+5-1);h-y+1<5&&(y=Math.max(1,h-5+1));for(let N=y;N<=h;N++)f.push(N);return f})();return e.jsxs("div",{className:k("flex flex-col sm:flex-row items-center justify-between gap-4 py-4 px-2",o),children:[r>0&&e.jsxs("div",{className:"text-sm text-text-muted",children:["Showing ",e.jsx("span",{className:"font-medium text-text-main",children:l})," to"," ",e.jsx("span",{className:"font-medium text-text-main",children:b})," of"," ",e.jsx("span",{className:"font-medium text-text-main",children:r})," results"]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-2 sm:gap-4",children:[i&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-text-muted",children:"Rows:"}),e.jsx("select",{value:t,onChange:f=>i(Number(f.target.value)),className:k("h-9 rounded-lg border border-black/10 dark:border-white/10 bg-surface","text-sm text-text-main focus:outline-none focus:ring-2 focus:ring-primary/20","cursor-pointer"),style:{colorScheme:"auto"},children:[10,20,50].map(f=>e.jsx("option",{value:f,children:f},f))})]}),n>1&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(q,{variant:"outline",size:"sm",onClick:()=>a(s-1),disabled:s===1,className:"w-9 px-0",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"chevron_left"})}),j[0]>1&&e.jsxs(e.Fragment,{children:[e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>a(1),className:"w-9 px-0 hidden sm:inline-flex",children:"1"}),j[0]>2&&e.jsx("span",{className:"text-text-muted px-1 hidden sm:inline",children:"..."})]}),j.map(f=>e.jsx(q,{variant:s===f?"primary":"ghost",size:"sm",onClick:()=>a(f),className:k("w-9 px-0",s===f?"inline-flex":"hidden sm:inline-flex"),children:f},f)),j[j.length-1]<n&&e.jsxs(e.Fragment,{children:[j[j.length-1]<n-1&&e.jsx("span",{className:"text-text-muted px-1 hidden sm:inline",children:"..."}),e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>a(n),className:"w-9 px-0 hidden sm:inline-flex",children:n})]}),e.jsx(q,{variant:"outline",size:"sm",onClick:()=>a(s+1),disabled:s===n,className:"w-9 px-0",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"chevron_right"})})]})]})]})}let z=null,U=null;async function Ce(){if(z&&U)return{providerNameCache:z,providerNodesCache:U};const r=(await(await fetch("/api/provider-nodes")).json()).nodes||[];U={};for(const a of r)U[a.id]=a.name;return z={...Y,...U},{providerNameCache:z,providerNodesCache:U}}function ee(s,t){if(!s||!t)return s;const r=t[s];if(typeof r=="string")return r;if(r!=null&&r.name)return r.name;const a=oe(s)||Y[s];return(a==null?void 0:a.name)||s}function B({title:s,children:t,defaultOpen:r=!1,icon:a=null}){const[i,o]=x.useState(r);return e.jsxs("div",{className:"border border-black/5 dark:border-white/5 rounded-lg overflow-hidden",children:[e.jsxs("button",{type:"button",onClick:()=>o(!i),className:"w-full flex items-center justify-between p-3 bg-black/[0.02] dark:bg-white/[0.02] hover:bg-black/[0.04] dark:hover:bg-white/[0.04] transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[a&&e.jsx("span",{className:"material-symbols-outlined text-[18px] text-text-muted",children:a}),e.jsx("span",{className:"font-semibold text-sm text-text-main",children:s})]}),e.jsx("span",{className:k("material-symbols-outlined text-[20px] text-text-muted transition-transform duration-200",i?"rotate-90":""),children:"chevron_right"})]}),i&&e.jsx("div",{className:"p-4 border-t border-black/5 dark:border-white/5",children:t})]})}function te(s){const t=(s==null?void 0:s.prompt_tokens)||(s==null?void 0:s.input_tokens)||0,r=(s==null?void 0:s.cached_tokens)||(s==null?void 0:s.cache_read_input_tokens)||0;return t<r?r:t}function De(){var T,F,$,S,R,E;const[s,t]=x.useState([]),[r,a]=x.useState({page:1,pageSize:20,totalItems:0,totalPages:0}),[i,o]=x.useState(!1),[n,l]=x.useState(null),[b,p]=x.useState(!1),[j,f]=x.useState([]),[P,y]=x.useState(null),[h,N]=x.useState({provider:"",startDate:"",endDate:""}),L=x.useCallback(async()=>{try{const w=await(await fetch("/api/usage/providers")).json();f(w.providers||[]);const C=await Ce();y(C.providerNameCache)}catch(c){console.error("Failed to fetch providers:",c)}},[]),O=x.useCallback(async()=>{o(!0);try{const c=new URLSearchParams({page:r.page.toString(),pageSize:r.pageSize.toString()});h.provider&&c.append("provider",h.provider),h.startDate&&c.append("startDate",h.startDate),h.endDate&&c.append("endDate",h.endDate);const C=await(await fetch(`/api/usage/request-details?${c}`)).json();t(C.details||[]),a(m=>({...m,...C.pagination}))}catch(c){console.error("Failed to fetch request details:",c)}finally{o(!1)}},[r.page,r.pageSize,h]);x.useEffect(()=>{L()},[L]),x.useEffect(()=>{O()},[O]);const J=c=>{l(c),p(!0)},G=c=>{a(w=>({...w,page:c}))},W=c=>{a(w=>({...w,pageSize:c,page:1}))},A=()=>{N({provider:"",startDate:"",endDate:""})};return e.jsxs("div",{className:"flex min-w-0 flex-col gap-6",children:[e.jsx(V,{padding:"md",children:e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsxs("div",{className:"flex min-w-0 flex-col gap-2",children:[e.jsx("label",{htmlFor:"provider-filter",className:"text-sm font-medium text-text-main",children:"Provider"}),e.jsxs("select",{id:"provider-filter",value:h.provider,onChange:c=>N({...h,provider:c.target.value}),className:k("h-9 px-3 rounded-lg border border-black/10 dark:border-white/10 bg-surface","text-sm text-text-main focus:outline-none focus:ring-2 focus:ring-primary/20","w-full min-w-0 cursor-pointer"),style:{colorScheme:"auto"},children:[e.jsx("option",{value:"",children:"All Providers"}),j.map(c=>e.jsx("option",{value:c.id,children:c.name},c.id))]})]}),e.jsxs("div",{className:"flex min-w-0 flex-col gap-2",children:[e.jsx("label",{htmlFor:"start-date-filter",className:"text-sm font-medium text-text-main",children:"Start Date"}),e.jsx("input",{id:"start-date-filter",type:"datetime-local",value:h.startDate,onChange:c=>N({...h,startDate:c.target.value}),className:k("h-9 px-3 rounded-lg border border-black/10 dark:border-white/10 bg-surface","w-full min-w-0 text-sm text-text-main focus:outline-none focus:ring-2 focus:ring-primary/20")})]}),e.jsxs("div",{className:"flex min-w-0 flex-col gap-2",children:[e.jsx("label",{htmlFor:"end-date-filter",className:"text-sm font-medium text-text-main",children:"End Date"}),e.jsx("input",{id:"end-date-filter",type:"datetime-local",value:h.endDate,onChange:c=>N({...h,endDate:c.target.value}),className:k("h-9 px-3 rounded-lg border border-black/10 dark:border-white/10 bg-surface","w-full min-w-0 text-sm text-text-main focus:outline-none focus:ring-2 focus:ring-primary/20")})]}),e.jsxs("div",{className:"flex min-w-0 flex-col gap-2 sm:col-span-2 lg:col-span-1",children:[e.jsx("span",{className:"hidden text-sm font-medium text-text-main opacity-0 lg:block","aria-hidden":"true",children:"Clear"}),e.jsx(q,{variant:"ghost",onClick:A,disabled:!h.provider&&!h.startDate&&!h.endDate,className:"w-full",children:"Clear Filters"})]})]})}),e.jsxs(V,{padding:"none",children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full min-w-[880px]",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-black/5 dark:border-white/5",children:[e.jsx("th",{className:"text-left p-4 text-sm font-semibold text-text-main",children:"Timestamp"}),e.jsx("th",{className:"text-left p-4 text-sm font-semibold text-text-main",children:"Model"}),e.jsx("th",{className:"text-left p-4 text-sm font-semibold text-text-main",children:"Provider"}),e.jsx("th",{className:"text-right p-4 text-sm font-semibold text-text-main",children:"Input Tokens"}),e.jsx("th",{className:"text-right p-4 text-sm font-semibold text-text-main",children:"Output Tokens"}),e.jsx("th",{className:"text-left p-4 text-sm font-semibold text-text-main",children:"Latency"}),e.jsx("th",{className:"text-center p-4 text-sm font-semibold text-text-main",children:"Action"})]})}),e.jsx("tbody",{children:i?e.jsx("tr",{children:e.jsx("td",{colSpan:"7",className:"p-8 text-center text-text-muted",children:e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[e.jsx("span",{className:"material-symbols-outlined animate-spin text-[20px]",children:"progress_activity"}),"Loading..."]})})}):s.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:"7",className:"p-8 text-center text-text-muted",children:"No request details found"})}):s.map((c,w)=>{var C,m,v,d;return e.jsxs("tr",{className:"border-b border-black/5 dark:border-white/5 last:border-b-0 hover:bg-black/[0.02] dark:hover:bg-white/[0.02] transition-colors",children:[e.jsx("td",{className:"whitespace-nowrap p-4 text-sm text-text-main",children:new Date(c.timestamp).toLocaleString()}),e.jsx("td",{className:"max-w-[260px] truncate p-4 font-mono text-sm text-text-main",children:c.model}),e.jsx("td",{className:"max-w-[180px] truncate p-4 text-sm text-text-main",children:e.jsx("span",{className:"font-medium",children:ee(c.provider,P)})}),e.jsx("td",{className:"p-4 text-sm text-text-main text-right font-mono",children:te(c.tokens).toLocaleString()}),e.jsx("td",{className:"p-4 text-sm text-text-main text-right font-mono",children:((m=(C=c.tokens)==null?void 0:C.completion_tokens)==null?void 0:m.toLocaleString())||0}),e.jsx("td",{className:"p-4 text-sm text-text-muted",children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{children:["TTFT: ",e.jsxs("span",{className:"font-mono",children:[((v=c.latency)==null?void 0:v.ttft)||0,"ms"]})]}),e.jsxs("div",{children:["Total: ",e.jsxs("span",{className:"font-mono",children:[((d=c.latency)==null?void 0:d.total)||0,"ms"]})]})]})}),e.jsx("td",{className:"p-4 text-center",children:e.jsx(q,{variant:"outline",size:"sm",onClick:()=>J(c),children:"Detail"})})]},`${c.id}-${w}`)})})]})}),!i&&s.length>0&&e.jsx("div",{className:"border-t border-black/5 dark:border-white/5",children:e.jsx(Se,{currentPage:r.page,pageSize:r.pageSize,totalItems:r.totalItems,onPageChange:G,onPageSizeChange:W})})]}),e.jsx(ke,{isOpen:b,onClose:()=>p(!1),title:"Request Details",width:"lg",children:n&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid min-w-0 grid-cols-1 gap-4 text-sm sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted",children:"ID:"})," ",e.jsx("span",{className:"break-all font-mono text-text-main",children:n.id})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted",children:"Timestamp:"})," ",e.jsx("span",{className:"text-text-main",children:new Date(n.timestamp).toLocaleString()})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted",children:"Provider:"})," ",e.jsx("span",{className:"text-text-main font-medium",children:ee(n.provider,P)})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted",children:"Model:"})," ",e.jsx("span",{className:"text-text-main font-mono",children:n.model})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted",children:"Status:"})," ",e.jsx("span",{className:k("font-medium",n.status==="success"?"text-green-600":"text-red-600"),children:n.status})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted",children:"Latency:"})," ",e.jsxs("span",{className:"text-text-main font-mono",children:["TTFT ",((T=n.latency)==null?void 0:T.ttft)||0,"ms / Total ",((F=n.latency)==null?void 0:F.total)||0,"ms"]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted",children:"Input Tokens:"})," ",e.jsx("span",{className:"text-text-main font-mono",children:te(n.tokens).toLocaleString()})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-text-muted",children:"Output Tokens:"})," ",e.jsx("span",{className:"text-text-main font-mono",children:((S=($=n.tokens)==null?void 0:$.completion_tokens)==null?void 0:S.toLocaleString())||0})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(B,{title:"1. Client Request (Input)",defaultOpen:!0,icon:"input",children:e.jsx("pre",{className:"max-h-[300px] max-w-full overflow-auto rounded-lg border border-black/5 bg-black/5 p-3 font-mono text-xs text-text-main dark:border-white/5 dark:bg-white/5 sm:p-4",children:JSON.stringify(n.request,null,2)})}),n.providerRequest&&e.jsx(B,{title:"2. Provider Request (Translated)",icon:"translate",children:e.jsx("pre",{className:"max-h-[300px] max-w-full overflow-auto rounded-lg border border-black/5 bg-black/5 p-3 font-mono text-xs text-text-main dark:border-white/5 dark:bg-white/5 sm:p-4",children:JSON.stringify(n.providerRequest,null,2)})}),n.providerResponse&&e.jsx(B,{title:"3. Provider Response (Raw)",icon:"data_object",children:e.jsx("pre",{className:"max-h-[300px] max-w-full overflow-auto rounded-lg border border-black/5 bg-black/5 p-3 font-mono text-xs text-text-main dark:border-white/5 dark:bg-white/5 sm:p-4",children:typeof n.providerResponse=="object"?JSON.stringify(n.providerResponse,null,2):n.providerResponse})}),e.jsxs(B,{title:"4. Client Response (Final)",defaultOpen:!0,icon:"output",children:[((R=n.response)==null?void 0:R.thinking)&&e.jsxs("div",{className:"mb-4",children:[e.jsxs("h4",{className:"font-semibold text-text-main mb-2 flex items-center gap-2 text-xs uppercase tracking-wide opacity-70",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"psychology"}),"Thinking Process"]}),e.jsx("pre",{className:"max-h-[200px] max-w-full overflow-auto rounded-lg border border-amber-200 bg-amber-50 p-3 font-mono text-xs text-amber-900 dark:border-amber-800 dark:bg-amber-950/30 dark:text-amber-100 sm:p-4",children:n.response.thinking})]}),e.jsx("h4",{className:"font-semibold text-text-main mb-2 text-xs uppercase tracking-wide opacity-70",children:"Content"}),e.jsx("pre",{className:"max-h-[300px] max-w-full overflow-auto rounded-lg border border-black/5 bg-black/5 p-3 font-mono text-xs text-text-main dark:border-white/5 dark:bg-white/5 sm:p-4",children:((E=n.response)==null?void 0:E.content)||"[No content]"})]})]})]})})]})}const Te=[{value:"today",label:"Today"},{value:"24h",label:"24h"},{value:"7d",label:"7D"},{value:"30d",label:"30D"},{value:"60d",label:"60D"}];function Ee(){return e.jsx(x.Suspense,{fallback:e.jsx(ae,{}),children:e.jsx(Pe,{})})}function Pe(){const[s]=re(),t=se(),[r,a]=x.useState("today"),i=s.get("tab"),o=i&&["overview","logs","details"].includes(i)?i:"overview",n=l=>{if(l===o)return;const b=new URLSearchParams(s);b.set("tab",l),t(`/dashboard/usage?${b.toString()}`,{scroll:!1})};return e.jsxs("div",{className:"flex min-w-0 flex-col gap-6 px-1 sm:px-0",children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx(Z,{options:[{value:"overview",label:"Overview"},{value:"details",label:"Details"}],value:o,onChange:n,className:"w-full sm:w-auto"}),o==="overview"&&e.jsx(Z,{options:Te,value:r,onChange:a,size:"sm",className:"w-full sm:w-auto"})]}),o==="overview"&&e.jsx(x.Suspense,{fallback:e.jsx(ae,{}),children:e.jsx(Ne,{period:r,setPeriod:a,hidePeriodSelector:!0})}),o==="logs"&&e.jsx(we,{}),o==="details"&&e.jsx(De,{})]})}export{Ee as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{j as e,u}from"./index.BO_pNnMt.js";import{C as l,B as d}from"./NoAuthProxyCard.CLW2-XwE.js";import"./router.Cjj1--8t.js";import"./zustand.akaTi5uX.js";const c="nexusrouters/fsrouter",m="main",x="skills",h=`https://github.com/${c}`,f=`https://raw.githubusercontent.com/${c}/refs/heads/${m}/${x}`,b=`https://github.com/${c}/blob/${m}/${x}`,n=[{id:"fsrouter",name:"FSRouter (Entry)",description:"Setup + index of all capabilities. Start here — covers base URL, auth, model discovery, and links to every capability skill.",endpoint:null,icon:"hub",isEntry:!0},{id:"fsrouter-chat",name:"Chat",description:"Chat / code-gen via OpenAI or Anthropic format with streaming.",endpoint:"/v1/chat/completions",icon:"chat"},{id:"fsrouter-image",name:"Image Generation",description:"Text-to-image via DALL-E, Imagen, FLUX, MiniMax, SDWebUI…",endpoint:"/v1/images/generations",icon:"image"},{id:"fsrouter-tts",name:"Text-to-Speech",description:"OpenAI / ElevenLabs / Edge / Google / Deepgram voices.",endpoint:"/v1/audio/speech",icon:"record_voice_over"},{id:"fsrouter-stt",name:"Speech-to-Text",description:"Transcribe audio via OpenAI Whisper, Groq, Gemini, Deepgram, AssemblyAI…",endpoint:"/v1/audio/transcriptions",icon:"mic"},{id:"fsrouter-embeddings",name:"Embeddings",description:"Vectors for RAG / semantic search via OpenAI, Gemini, Mistral…",endpoint:"/v1/embeddings",icon:"scatter_plot"},{id:"fsrouter-web-search",name:"Web Search",description:"Tavily / Exa / Brave / Serper / SearXNG / Google PSE / You.com.",endpoint:"/v1/search",icon:"search"},{id:"fsrouter-web-fetch",name:"Web Fetch",description:"URL → markdown / text / HTML via Firecrawl, Jina, Tavily, Exa.",endpoint:"/v1/web/fetch",icon:"language"},{id:"using-superpowers",name:"Using Superpowers",description:"Use when starting any conversation — establishes how to find and use skills before ANY response.",endpoint:null,icon:"bolt"},{id:"multi-brain",name:"Multi-Brain Memory",description:"Share work and memory across Claude Code, OpenCode, Codex, and other agents via a two-level memory index.",endpoint:null,icon:"memory"}];function o(t){return`${f}/${t}/SKILL.md`}function g(t){return`${b}/${t}/SKILL.md`}function p({value:t,label:i="Copy link"}){const{copied:r,copy:s}=u(2e3);return e.jsxs("button",{onClick:()=>s(t),className:"px-2 py-1 rounded-md bg-primary text-white text-[11px] font-medium hover:bg-primary/90 transition-colors cursor-pointer shrink-0 inline-flex items-center gap-1",title:t,children:[e.jsx("span",{className:"material-symbols-outlined text-[12px]",children:r?"check":"content_copy"}),r?"Copied!":i]})}function a({skill:t}){const i=o(t.id);return e.jsxs("div",{className:`flex items-start gap-3 p-4 rounded-[14px] border shadow-[var(--shadow-soft)] transition-colors ${t.isEntry?"border-primary/40 bg-primary/5":"border-border-subtle bg-surface hover:bg-surface-2"}`,children:[e.jsx("div",{className:`size-9 rounded-lg flex items-center justify-center shrink-0 ${t.isEntry?"bg-primary text-white":"bg-primary/10 text-primary"}`,children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:t.icon})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h3",{className:"font-semibold text-sm text-text-main",children:t.name}),t.isEntry&&e.jsx(d,{variant:"primary",size:"sm",children:"START HERE"}),t.endpoint&&e.jsx(d,{variant:"default",size:"sm",children:e.jsx("code",{className:"text-[10px]",children:t.endpoint})})]}),e.jsx("p",{className:"text-xs text-text-muted mt-0.5",children:t.description}),e.jsxs("a",{href:g(t.id),target:"_blank",rel:"noreferrer",className:"text-[11px] text-text-muted hover:text-primary mt-1 inline-flex items-center gap-1 break-all",children:[i,e.jsx("span",{className:"material-symbols-outlined text-[12px]",children:"open_in_new"})]})]}),e.jsx(p,{value:i})]})}const y=["fsrouter-chat","fsrouter-image","fsrouter-tts","fsrouter-stt","fsrouter-embeddings","fsrouter-web-search","fsrouter-web-fetch"],j=["using-superpowers","multi-brain"];function L(){const t=n.find(s=>s.isEntry),i=n.filter(s=>y.includes(s.id)),r=n.filter(s=>j.includes(s.id));return e.jsxs("div",{className:"max-w-4xl mx-auto space-y-8",children:[e.jsx("div",{children:e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"size-10 rounded-xl bg-primary/10 flex items-center justify-center",children:e.jsx("span",{className:"material-symbols-outlined text-primary text-[22px]",children:"extension"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-bold text-text-main",children:"Agent Skills"}),e.jsx("p",{className:"text-sm text-text-muted",children:"Raw SKILL.md URLs to paste into any AI agent or coding assistant."})]})]})}),e.jsxs(l,{padding:"md",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px] text-primary",children:"rocket_launch"}),e.jsx("span",{className:"text-xs font-semibold text-text-main uppercase tracking-wide",children:"Quick Start — Paste this to your AI"})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("div",{className:"flex-1 px-3 py-2 rounded-lg bg-surface-2 font-mono text-[12px] text-text-main border border-border-subtle min-w-0 break-all",children:["Read this skill and use it: ",o("fsrouter")]}),e.jsx(p,{value:`Read this skill and use it: ${o("fsrouter")}`,label:"Copy prompt"})]}),e.jsx("p",{className:"text-[11px] text-text-muted mt-2",children:"This entry skill covers setup, authentication, model discovery, and links to all capability skills below."})]}),t&&e.jsxs("section",{className:"space-y-2",children:[e.jsx("h2",{className:"text-xs font-semibold text-text-muted uppercase tracking-wider px-1",children:"Entry Point"}),e.jsx(a,{skill:t})]}),e.jsxs("section",{className:"space-y-2",children:[e.jsx("h2",{className:"text-xs font-semibold text-text-muted uppercase tracking-wider px-1",children:"API Capabilities"}),e.jsx("div",{className:"space-y-2",children:i.map(s=>e.jsx(a,{skill:s},s.id))})]}),e.jsxs("section",{className:"space-y-2",children:[e.jsx("h2",{className:"text-xs font-semibold text-text-muted uppercase tracking-wider px-1",children:"Agent Workflow"}),e.jsx("div",{className:"space-y-2",children:r.map(s=>e.jsx(a,{skill:s},s.id))})]}),e.jsx(l,{padding:"md",children:e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-sm font-semibold text-text-main",children:"Browse on GitHub"}),e.jsx("p",{className:"text-xs text-text-muted mt-0.5",children:"View source, README, and full skill documentation."})]}),e.jsxs("a",{href:`${h}/tree/master/skills`,target:"_blank",rel:"noreferrer",className:"text-sm text-primary hover:underline inline-flex items-center gap-1 shrink-0",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"open_in_new"}),"View on GitHub"]})]})})]})}export{L as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{j as e}from"./index.BO_pNnMt.js";import{b as n}from"./router.Cjj1--8t.js";import"./zustand.akaTi5uX.js";function x(){const[s,a]=n.useState(null),[c,r]=n.useState(!1),i=async m=>{const o=m.target.files[0];if(!o)return;r(!0);const l=new FormData;l.append("file",o);try{const t=await fetch("/api/ocr",{method:"POST",body:l});a(await t.json())}catch(t){a({error:t.message})}r(!1)};return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"OCR"}),e.jsx("p",{className:"text-text-muted",children:"Extract text from images using Mistral OCR API"}),e.jsx("input",{type:"file",accept:"image/*,.pdf",onChange:i,className:"block"}),c&&e.jsx("p",{children:"Processing..."}),s&&e.jsx("pre",{className:"p-4 bg-black/5 rounded-lg text-sm overflow-auto max-h-96",children:JSON.stringify(s,null,2)})]})}export{x as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{j as e,B as I,y as te,h as ae,k as re,l as le}from"./index.BO_pNnMt.js";import{b as r}from"./router.Cjj1--8t.js";import{M as ie}from"./cliTools.CsdwAybi.js";import{C as Z,B,I as K,M as ne}from"./NoAuthProxyCard.CLW2-XwE.js";import"./zustand.akaTi5uX.js";const $=te();function oe({apiKeys:l,cloudEnabled:b,onStatusChange:y}){const[s,c]=r.useState(null),[x,v]=r.useState(!1),[D,N]=r.useState(!1),[T,p]=r.useState(""),[j,U]=r.useState(()=>{var a;return((a=l==null?void 0:l[0])==null?void 0:a.key)||""}),[E,h]=r.useState(null),[A,w]=r.useState(null),[_,S]=r.useState(null),[i,n]=r.useState($),[m,R]=r.useState(null),u=(s==null?void 0:s.isWin)===!0,q=u||(s==null?void 0:s.hasCachedPassword)||(s==null?void 0:s.needsSudoPassword)===!1,k=(s==null?void 0:s.isAdmin)!==!1;!k&&(u||!(s!=null&&s.hasCachedPassword)&&(s==null||s.needsSudoPassword));const g=r.useCallback(async()=>{try{const a=await fetch("/api/cli-tools/antigravity-mitm");if(a.ok){const d=await a.json();c(d),d.mitmRouterBaseUrl&&n(d.mitmRouterBaseUrl),y==null||y(d)}}catch{c({running:!1,certExists:!1,dnsStatus:{}})}},[y]);r.useEffect(()=>{queueMicrotask(()=>{g()})},[g]);const O=a=>{S(null),s&&(q?z(a,""):(h(a),N(!0),w(null)))},z=async(a,d,L=!1)=>{v(!0),S(null);try{let f;if(a==="trust-cert")f=await fetch("/api/cli-tools/antigravity-mitm",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"trust-cert",sudoPassword:d})});else if(a==="start"){const P=(j==null?void 0:j.trim())||((l==null?void 0:l.length)>0?l[0].key:null)||(b?null:"sk_fsrouter");f=await fetch("/api/cli-tools/antigravity-mitm",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:P,sudoPassword:d,mitmRouterBaseUrl:i.trim()||$,forceKillPort443:L})})}else f=await fetch("/api/cli-tools/antigravity-mitm",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({sudoPassword:d})});if(!f.ok){const P=await f.json().catch(()=>({}));if(P.code==="PORT_443_BUSY"&&P.portOwner){N(!1),R({owner:P.portOwner,password:d});return}S(P.error||`Failed to ${a} MITM server`);return}N(!1),p(""),R(null),await g()}catch(f){S(f.message||"Network error")}finally{v(!1),h(null)}},F=()=>{const a=(m==null?void 0:m.password)||"";z("start",a,!0)},M=()=>{if(!T.trim()){w("Sudo password is required");return}z(E,T)},C=s==null?void 0:s.running;return e.jsxs(e.Fragment,{children:[e.jsx(Z,{padding:"sm",className:"border-primary/20 bg-primary/5",children:e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[e.jsx("span",{className:"material-symbols-outlined text-primary text-[20px]",children:"security"}),e.jsx("span",{className:"font-semibold text-sm text-text-main",children:"MITM Server"}),C?e.jsx(B,{variant:"success",size:"sm",children:"Running"}):e.jsx(B,{variant:"default",size:"sm",children:"Stopped"})]}),e.jsx("div",{className:"flex flex-wrap items-center gap-1 text-xs text-text-muted","data-i18n-skip":"true",children:[{label:"Cert",ok:s==null?void 0:s.certExists},{label:"Trusted",ok:s==null?void 0:s.certTrusted},{label:"Server",ok:C}].map(({label:a,ok:d})=>e.jsxs("span",{className:`flex items-center gap-0.5 px-1.5 py-0.5 rounded ${d?"text-green-600":"text-text-muted"}`,children:[e.jsx("span",{className:"material-symbols-outlined text-[12px]",children:d?"check_circle":"cancel"}),a]},a))})]}),e.jsxs("div",{className:"px-2 py-2 rounded-lg bg-surface/50 border border-border/50 flex flex-col gap-2",children:[e.jsxs("p",{className:"text-[11px] text-text-muted leading-relaxed",children:[e.jsx("span",{className:"font-medium text-text-main",children:"Purpose:"})," Use Antigravity IDE & GitHub Copilot → with ANY provider/model from FSRouter"]}),e.jsxs("p",{className:"text-[11px] text-text-muted leading-relaxed",children:[e.jsx("span",{className:"font-medium text-text-main",children:"How it works:"})," Antigravity/Copilot IDE request → DNS redirect to localhost:443 → MITM proxy intercepts → FSRouter → response to Antigravity/Copilot"]})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"grid gap-1 sm:grid-cols-[8rem_auto_1fr] sm:items-center sm:gap-2",children:[e.jsx("span",{className:"text-xs font-semibold text-text-main sm:text-right sm:text-sm",children:"FSRouter Base URL"}),e.jsx("span",{className:"material-symbols-outlined hidden text-text-muted text-[14px] sm:inline",children:"arrow_forward"}),e.jsx("input",{type:"text",value:i,onChange:a=>n(a.target.value),placeholder:$,disabled:C,className:"flex-1 min-w-0 px-2 py-1.5 bg-surface rounded border border-border text-xs text-text-main focus:outline-none focus:ring-1 focus:ring-primary/50 disabled:opacity-50"})]}),!C&&e.jsxs("div",{className:"grid gap-1 sm:grid-cols-[8rem_auto_1fr] sm:items-center sm:gap-2",children:[e.jsx("span",{className:"text-xs font-semibold text-text-main sm:text-right sm:text-sm",children:"API Key"}),e.jsx("span",{className:"material-symbols-outlined hidden text-text-muted text-[14px] sm:inline",children:"arrow_forward"}),e.jsx("input",{type:"text",list:"mitm-api-keys",value:j,onChange:a=>U(a.target.value),placeholder:b?"Enter or pick API key":"sk_fsrouter (default)",className:"flex-1 min-w-0 px-2 py-1.5 bg-surface rounded border border-border text-xs text-text-main focus:outline-none focus:ring-1 focus:ring-primary/50"}),(l==null?void 0:l.length)>0&&e.jsx("datalist",{id:"mitm-api-keys",children:l.map(a=>e.jsx("option",{value:a.key,children:a.name||a.key},a.id))})]})]}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:flex-wrap sm:items-center","data-i18n-skip":"true",children:[(s==null?void 0:s.certExists)&&!(s!=null&&s.certTrusted)&&e.jsxs("button",{onClick:()=>O("trust-cert"),disabled:x,className:"flex w-full items-center justify-center gap-1.5 rounded-lg border border-yellow-500/30 bg-yellow-500/10 px-4 py-2 text-xs font-medium text-yellow-600 transition-colors hover:bg-yellow-500/20 disabled:opacity-50 sm:w-auto sm:py-1.5",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"verified_user"}),"Trust Cert"]}),C?e.jsxs("button",{onClick:()=>O("stop"),disabled:x,className:"flex w-full items-center justify-center gap-1.5 rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-2 text-xs font-medium text-red-500 transition-colors hover:bg-red-500/20 disabled:opacity-50 sm:w-auto sm:py-1.5",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"stop_circle"}),"Stop Server"]}):e.jsxs("button",{onClick:()=>O("start"),disabled:x||!s||u&&!k,title:u&&!k?"Administrator required":void 0,className:"flex w-full items-center justify-center gap-1.5 rounded-lg border border-primary/30 bg-primary/10 px-4 py-2 text-xs font-medium text-primary transition-colors hover:bg-primary/20 disabled:opacity-50 sm:w-auto sm:py-1.5",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"play_circle"}),"Start Server"]}),C&&e.jsx("p",{className:"text-xs text-text-muted",children:"Enable DNS per tool below to activate interception"})]}),_&&e.jsxs("div",{className:"flex items-start gap-2 px-2 py-1.5 rounded text-xs bg-red-500/10 text-red-600 dark:text-red-400 border border-red-500/20",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px] mt-0.5 shrink-0",children:"error"}),e.jsx("span",{children:_})]}),u&&!k&&e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 rounded text-xs bg-red-500/10 text-red-600 border border-red-500/20",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"shield_lock"}),e.jsx("span",{children:"Administrator required — restart FSRouter as Administrator to use MITM"})]})]})}),D&&e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm",children:e.jsxs("div",{className:"mx-4 flex w-full max-w-sm flex-col gap-4 rounded-xl border border-border bg-surface p-5 shadow-xl sm:p-6",children:[e.jsx("h3",{className:"font-semibold text-text-main",children:"Sudo Password Required"}),e.jsxs("div",{className:"flex items-start gap-3 p-3 bg-yellow-500/10 border border-yellow-500/30 rounded-lg",children:[e.jsx("span",{className:"material-symbols-outlined text-yellow-500 text-[20px]",children:"warning"}),e.jsx("p",{className:"text-xs text-text-muted",children:"Required for SSL certificate and server startup"})]}),e.jsx(K,{type:"password",placeholder:"Enter sudo password",value:T,onChange:a=>p(a.target.value),onKeyDown:a=>{a.key==="Enter"&&!x&&M()}}),A&&e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 rounded text-xs bg-red-500/10 text-red-600",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"error"}),e.jsx("span",{children:A})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{N(!1),p(""),w(null)},disabled:x,children:"Cancel"}),e.jsx(I,{variant:"primary",size:"sm",onClick:M,loading:x,children:"Confirm"})]})]})}),m&&e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm",children:e.jsxs("div",{className:"mx-4 flex w-full max-w-md flex-col gap-4 rounded-xl border border-border bg-surface p-5 shadow-xl sm:p-6",children:[e.jsx("h3",{className:"font-semibold text-text-main",children:"Port 443 Already In Use"}),e.jsxs("div",{className:"flex items-start gap-3 p-3 bg-yellow-500/10 border border-yellow-500/30 rounded-lg",children:[e.jsx("span",{className:"material-symbols-outlined text-yellow-500 text-[20px]",children:"warning"}),e.jsxs("div",{className:"flex flex-col gap-1 text-xs text-text-muted",children:[e.jsx("p",{children:"Port 443 is currently used by another process:"}),e.jsxs("p",{className:"font-mono text-text-main","data-i18n-skip":"true",children:[m.owner.name," (PID ",m.owner.pid,")"]}),e.jsx("p",{children:"Kill this process to start MITM Server?"})]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{R(null),v(!1)},disabled:x,children:"Cancel"}),e.jsx(I,{variant:"primary",size:"sm",onClick:F,loading:x,children:"Kill & Start"})]})]})})]})}const de={antigravity:["daily-cloudcode-pa.googleapis.com","cloudcode-pa.googleapis.com"],copilot:["api.individual.githubcopilot.com"],kiro:["q.us-east-1.amazonaws.com","codewhisperer.us-east-1.amazonaws.com"],cursor:["api2.cursor.sh"]};function ce({tool:l,isExpanded:b,onToggle:y,serverRunning:s,dnsActive:c,hasCachedPassword:x,needsSudoPassword:v,isWin:D,apiKeys:N,activeProviders:T,hasActiveProviders:p,modelAliases:j={},cloudEnabled:U,onDnsChange:E}){var Q,V;const[h,A]=r.useState(!1),[w,_]=r.useState(null),[S,i]=r.useState(!1),[n,m]=r.useState(""),[R,u]=r.useState(null),[q,k]=r.useState(null),[g,O]=r.useState({}),[z,F]=r.useState(!1),[M,C]=r.useState(null),a=de[l.id]??[],d=D||x||v===!1;r.useEffect(()=>{b&&L()},[b]);const L=async()=>{try{const t=await fetch(`/api/cli-tools/antigravity-mitm/alias?tool=${l.id}`);if(t.ok){const o=await t.json();Object.keys(o.aliases||{}).length>0&&O(o.aliases)}}catch{}},f=r.useCallback(async t=>{try{await fetch("/api/cli-tools/antigravity-mitm/alias",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool:l.id,mappings:t})})}catch{}},[l.id]),P=(t,o)=>{f({...g,[t]:o})},W=(t,o)=>{O(H=>({...H,[t]:o}))},ee=t=>{C(t),F(!0)},se=t=>{if(!M||t.isPlaceholder)return;const o={...g,[M]:t.value};O(o),f(o)},J=()=>{if(!s)return;const t=c?"disable":"enable";d?G(t,""):(u(t),i(!0),k(null))},G=async(t,o)=>{A(!0),_(null);try{const H=await fetch("/api/cli-tools/antigravity-mitm",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool:l.id,action:t,sudoPassword:o})}),X=await H.json();if(!H.ok)throw new Error(X.error||"Failed to toggle DNS");t==="enable"&&_(`Restart ${l.name} to apply changes`),i(!1),m(""),E==null||E(X)}catch{}finally{A(!1),u(null)}},Y=()=>{if(!n.trim()){k("Sudo password is required");return}G(R,n)};return e.jsxs(e.Fragment,{children:[e.jsxs(Z,{padding:"xs",className:"overflow-hidden",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 hover:cursor-pointer sm:items-center",onClick:y,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("img",{src:l.image,alt:l.name,width:32,height:32,className:"size-8 object-contain rounded-lg",onError:t=>{t.target.style.display="none"}}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("h3",{className:"font-medium text-sm",children:l.name}),s?c?e.jsx(B,{variant:"success",size:"sm",children:"Active"}):e.jsx(B,{variant:"warning",size:"sm",children:"DNS off"}):e.jsx(B,{variant:"default",size:"sm",children:"Server off"})]}),e.jsxs("p",{className:"text-xs text-text-muted sm:truncate",children:["Intercept ",l.name," requests via MITM proxy"]})]})]}),e.jsx("span",{className:`material-symbols-outlined text-text-muted text-[20px] transition-transform ${b?"rotate-180":""}`,children:"expand_more"})]}),b&&e.jsxs("div",{className:"mt-4 pt-4 border-t border-border flex flex-col gap-4",children:[a.length>0&&e.jsxs("div",{className:"mt-2 rounded-md border border-border bg-surface/50 px-2 py-1.5",children:[e.jsx("p",{className:"text-[10px] font-medium tracking-wide text-text-main/80 mb-1",children:"Edit hosts file manually to add the following entries:"}),e.jsx("ul",{className:"list-none space-y-0.5 font-mono text-[10px] text-text-muted break-all",children:a.map(t=>e.jsxs("li",{children:["127.0.0.1 ",t]},t))})]}),e.jsxs("div",{className:"flex flex-col gap-0.5 text-[11px] text-text-muted px-1",children:[e.jsxs("p",{children:["Toggle DNS to redirect ",l.name," traffic through FSRouter via MITM."]}),!c&&e.jsx("p",{className:"text-amber-600 text-[10px] mt-1",children:"⚠️ Enable DNS to edit model mappings"})]}),((Q=l.defaultModels)==null?void 0:Q.length)>0&&e.jsx("div",{className:"flex flex-col gap-2",children:l.defaultModels.map(t=>e.jsxs("div",{className:"grid grid-cols-1 gap-1.5 sm:grid-cols-[9rem_auto_1fr_auto] sm:items-center sm:gap-2",children:[e.jsx("span",{className:"text-xs font-semibold text-text-main sm:text-right",children:t.name}),e.jsx("span",{className:"material-symbols-outlined hidden text-text-muted text-[14px] sm:inline",children:"arrow_forward"}),e.jsxs("div",{className:"relative w-full min-w-0",children:[e.jsx("input",{type:"text",value:g[t.alias]||"",onChange:o=>W(t.alias,o.target.value),onBlur:o=>P(t.alias,o.target.value),placeholder:"provider/model-id",disabled:!c,className:`w-full min-w-0 pl-2 pr-7 py-2 bg-surface rounded border border-border text-xs focus:outline-none focus:ring-1 focus:ring-primary/50 sm:py-1.5 ${c?"":"opacity-50 cursor-not-allowed"}`}),g[t.alias]&&e.jsx("button",{onClick:()=>{W(t.alias,""),f({...g,[t.alias]:""})},className:"absolute right-1 top-1/2 -translate-y-1/2 p-0.5 text-text-muted hover:text-red-500 rounded transition-colors",title:"Clear",children:e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"close"})})]}),e.jsx("button",{onClick:()=>ee(t.alias),disabled:!p||!c,className:`rounded border px-2 py-2 text-xs transition-colors sm:py-1.5 ${p&&c?"bg-surface border-border hover:border-primary cursor-pointer":"opacity-50 cursor-not-allowed border-border"}`,children:"Select"})]},t.alias))}),((V=l.defaultModels)==null?void 0:V.length)===0&&e.jsx("p",{className:"text-xs text-text-muted px-1",children:"Model mappings will be available soon."}),e.jsxs("div",{className:"flex flex-col gap-2 sm:items-start",children:[c?e.jsxs("button",{onClick:J,disabled:!s||h,className:"flex w-full items-center justify-center gap-1.5 rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-2 text-xs font-medium text-red-500 transition-colors hover:bg-red-500/20 disabled:cursor-not-allowed disabled:opacity-50 sm:w-auto sm:py-1.5",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"stop_circle"}),"Stop DNS"]}):e.jsxs("button",{onClick:J,disabled:!s||h,className:"flex w-full items-center justify-center gap-1.5 rounded-lg border border-primary/30 bg-primary/10 px-4 py-2 text-xs font-medium text-primary transition-colors hover:bg-primary/20 disabled:cursor-not-allowed disabled:opacity-50 sm:w-auto sm:py-1.5",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"play_circle"}),"Start DNS"]}),w&&e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 rounded text-xs text-amber-500",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"warning"}),e.jsx("span",{children:w})]})]})]})]}),S&&e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm",children:e.jsxs("div",{className:"mx-4 flex w-full max-w-sm flex-col gap-4 rounded-xl border border-border bg-surface p-5 shadow-xl sm:p-6",children:[e.jsx("h3",{className:"font-semibold text-text-main",children:"Sudo Password Required"}),e.jsxs("div",{className:"flex items-start gap-3 p-3 bg-yellow-500/10 border border-yellow-500/30 rounded-lg",children:[e.jsx("span",{className:"material-symbols-outlined text-yellow-500 text-[20px]",children:"warning"}),e.jsx("p",{className:"text-xs text-text-muted",children:"Required to modify /etc/hosts and flush DNS cache"})]}),e.jsx(K,{type:"password",placeholder:"Enter sudo password",value:n,onChange:t=>m(t.target.value),onKeyDown:t=>{t.key==="Enter"&&!h&&Y()}}),q&&e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 rounded text-xs bg-red-500/10 text-red-600",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:"error"}),e.jsx("span",{children:q})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{i(!1),m(""),k(null)},disabled:h,children:"Cancel"}),e.jsx(I,{variant:"primary",size:"sm",onClick:Y,loading:h,children:"Confirm"})]})]})}),e.jsx(ne,{isOpen:z,onClose:()=>F(!1),onSelect:se,selectedModel:M?g[M]:null,activeProviders:T,modelAliases:j,title:`Select model for ${M}`})]})}function me(){const[l,b]=r.useState([]),[y,s]=r.useState([]),[c,x]=r.useState({}),[v,D]=r.useState(!1),[N,T]=r.useState(null),[p,j]=r.useState({running:!1,certExists:!1,dnsStatus:{},hasCachedPassword:!1});r.useEffect(()=>{U(),E(),h(),A()},[]);const U=async()=>{try{const i=await fetch("/api/providers");if(i.ok){const n=await i.json();b(n.connections||[])}}catch{}},E=async()=>{try{const i=await fetch("/api/keys");if(i.ok){const n=await i.json();s(n.keys||[])}}catch{}},h=async()=>{try{const i=await fetch("/api/models/alias");if(i.ok){const n=await i.json();x(n.aliases||{})}}catch{}},A=async()=>{try{const i=await fetch("/api/settings");if(i.ok){const n=await i.json();D(n.cloudEnabled||!1)}}catch{}},w=()=>l.filter(i=>i.isActive!==!1),_=()=>w().some(n=>ae(n.provider).length>0||re(n.provider)||le(n.provider)),S=Object.entries(ie);return e.jsxs("div",{className:"flex w-full flex-col gap-6",children:[e.jsxs("div",{className:"flex items-start gap-2 px-3 py-2 rounded-lg bg-yellow-500/10 border border-yellow-500/30",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px] text-yellow-500 mt-0.5 shrink-0",children:"warning"}),e.jsx("p",{className:"text-xs text-red-600 dark:text-yellow-400 leading-relaxed",children:"⚠️ MITM intercepts HTTPS traffic of IDE tools (Antigravity, GitHub Copilot, Kiro) via local CA to redirect requests to your providers. May violate ToS → account ban. Use at your own risk."})]}),e.jsx(oe,{apiKeys:y,cloudEnabled:v,onStatusChange:j}),e.jsx("div",{className:"grid gap-3 sm:gap-4",children:S.map(([i,n])=>{var m;return e.jsx(ce,{tool:n,isExpanded:N===i,onToggle:()=>T(N===i?null:i),serverRunning:p.running,dnsActive:((m=p.dnsStatus)==null?void 0:m[i])||!1,hasCachedPassword:p.hasCachedPassword||!1,needsSudoPassword:p.needsSudoPassword!==!1,isWin:p.isWin===!0,apiKeys:y,activeProviders:w(),hasActiveProviders:_(),modelAliases:c,cloudEnabled:v,onDnsChange:R=>j(u=>({...u,dnsStatus:R.dnsStatus??u.dnsStatus}))},i)})})]})}function ge(){return e.jsx(me,{})}export{ge as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{j as s,B as Be,k as je,l as Ie,h as Le}from"./index.BO_pNnMt.js";import{b as d}from"./router.Cjj1--8t.js";import{B as qe}from"./NoAuthProxyCard.CLW2-XwE.js";import"./zustand.akaTi5uX.js";const O={sessions:"basic-chat.sessions",activeSessionId:"basic-chat.activeSessionId",activeProviderId:"basic-chat.activeProviderId",draft:"basic-chat.draft"};function J(){var e;return(e=globalThis.crypto)!=null&&e.randomUUID?globalThis.crypto.randomUUID():`chat_${Date.now()}_${Math.random().toString(16).slice(2)}`}function Fe(e,a){try{return JSON.parse(e)}catch{return a}}function S(e){if(typeof e=="string")return e;if(e==null)return"";if(Array.isArray(e))return e.map(S).filter(Boolean).join(" ");if(typeof e=="object"){if(typeof e.message=="string")return e.message;if(typeof e.error=="string")return e.error;try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function He(e=""){return String(e).replace(/[-_]/g," ").replace(/\b\w/g,a=>a.toUpperCase()).trim()||"Unknown"}function Je(e){if(!e)return"Now";const a=new Date(e).getTime();if(Number.isNaN(a))return"Now";const m=Math.max(1,Math.round((Date.now()-a)/6e4));if(m<60)return`${m}m`;const u=Math.round(m/60);return u<24?`${u}h`:`${Math.round(u/24)}d`}function Ne(e=""){const a=S(e).replace(/\s+/g," ").trim();return a?a.length>52?`${a.slice(0,52).trimEnd()}…`:a:"New chat"}function Ke(e){const a=S(e.content).trim(),m=Array.isArray(e.attachments)?e.attachments:[];if(m.length===0)return a;const u=[];a&&u.push({type:"text",text:a});for(const w of m)w!=null&&w.dataUrl&&u.push({type:"image_url",image_url:{url:w.dataUrl}});return u.length>0?u:a}function We(e){var w,A;if(!e||typeof e!="object")return"";const a=(w=e.choices)==null?void 0:w[0];return[((a==null?void 0:a.delta)||{}).content,(A=a==null?void 0:a.message)==null?void 0:A.content,e.output_text,e.text].map(S).filter(Boolean)[0]||""}async function Ye(e){return await new Promise((a,m)=>{const u=new FileReader;u.onload=()=>a(String(u.result||"")),u.onerror=()=>m(u.error||new Error("Failed to read file")),u.readAsDataURL(e)})}function Ve(e){return{...e,messages:Array.isArray(e.messages)?e.messages.map(a=>({...a})):[]}}function de(e){return(e==null?void 0:e.name)||He((e==null?void 0:e.provider)||(e==null?void 0:e.id)||"provider")}function Ge(e,a){return e!=null&&e.id?{id:`${a.provider}/${e.id}`,requestModel:`${a.provider}/${e.id}`,name:e.name||e.id,providerId:a.provider,providerName:de(a),source:"static"}:null}function Qe(e,a){const m=typeof e=="string"?e:(e==null?void 0:e.id)||(e==null?void 0:e.name)||(e==null?void 0:e.model)||"";if(!m)return null;const u=typeof e=="string"?e:(e==null?void 0:e.name)||(e==null?void 0:e.displayName)||m;let w=m;return(je(a.provider)||Ie(a.provider))&&!m.includes("/")&&(w=`${a.provider}/${m}`),{id:w,requestModel:w,name:u,providerId:a.provider,providerName:de(a),source:"live"}}function Xe(e){return Array.isArray(e==null?void 0:e.models)?e.models:Array.isArray(e==null?void 0:e.data)?e.data:Array.isArray(e==null?void 0:e.results)?e.results:Array.isArray(e)?e:[]}function Ze(e){const a=new Map;for(const m of e)m!=null&&m.id&&(a.has(m.id)||a.set(m.id,m));return Array.from(a.values())}function et(){const[e,a]=d.useState([]),[m,u]=d.useState(!0),[w,A]=d.useState(""),[h,D]=d.useState(()=>{if(typeof window>"u")return[];try{const t=Fe(globalThis.localStorage.getItem(O.sessions),[]);return Array.isArray(t)?t.map(r=>({...r,messages:Array.isArray(r.messages)?r.messages:[]})):[]}catch{return[]}}),[g,M]=d.useState(()=>typeof window>"u"?"":globalThis.localStorage.getItem(O.activeSessionId)||""),[R,P]=d.useState(()=>typeof window>"u"?"":globalThis.localStorage.getItem(O.activeProviderId)||""),[I,U]=d.useState(""),[_,ce]=d.useState(()=>typeof window>"u"?"":globalThis.localStorage.getItem(O.draft)||""),[z,Q]=d.useState([]),[me,ue]=d.useState(!1),[Se,pe]=d.useState(""),[fe,X]=d.useState(""),[K,Ae]=d.useState(!1),[Me,Z]=d.useState(!1),[De,ee]=d.useState(!1),xe=d.useRef(null),B=d.useRef(null),te=d.useRef(!1),se=d.useRef(null),re=d.useRef(null);d.useEffect(()=>{Ae(!0)},[]),d.useEffect(()=>{let t=!1;async function r(){u(!0),A("");try{const n=await(await fetch("/api/providers",{cache:"no-store"})).json().catch(()=>({})),o=Array.isArray(n.connections)?n.connections.filter(c=>(c==null?void 0:c.isActive)!==!1):[];if(o.length===0){t||(a([]),A("No providers connected yet."));return}const x=new Map;for(const c of o){const p=c.provider||c.id,b=de(c),$=je(p)?"openai-compatible":Ie(p)?"anthropic-compatible":p;x.has(p)||x.set(p,{providerId:p,providerName:b,providerType:$,connections:[],models:[]});const N=x.get(p);N.providerName=N.providerName||b,N.providerType=N.providerType||$,N.connections.push(c);const W=Le(p).map(Y=>Ge(Y,c)).filter(Boolean);N.models.push(...W)}const k=await Promise.all(o.map(async c=>{try{const p=await fetch(`/api/providers/${c.id}/models`,{cache:"no-store"}),b=await p.json().catch(()=>({}));if(!p.ok)return{connection:c,models:[]};const $=Xe(b).map(N=>Qe(N,c)).filter(Boolean);return{connection:c,models:$}}catch{return{connection:c,models:[]}}}));for(const c of k){const p=c.connection.provider||c.connection.id,b=x.get(p);b&&b.models.push(...c.models)}const q=Array.from(x.values()).map(c=>({...c,models:Ze(c.models).sort((p,b)=>p.name.localeCompare(b.name))})).filter(c=>c.models.length>0).sort((c,p)=>c.providerName.localeCompare(p.providerName));t||(a(q),q.length===0&&A("Providers connected but no models available."))}catch(i){t||(A(S(i==null?void 0:i.message)||"Failed to load providers/models."),a([]))}finally{t||u(!1)}}return r(),()=>{t=!0}},[]),d.useEffect(()=>{const t=r=>{se.current&&!se.current.contains(r.target)&&Z(!1),re.current&&!re.current.contains(r.target)&&ee(!1)};return document.addEventListener("mousedown",t),()=>document.removeEventListener("mousedown",t)},[]);const y=d.useMemo(()=>{const t=new Map;for(const r of e)for(const i of r.models)t.set(i.id,{...i,providerId:r.providerId,providerName:r.providerName});return t},[e]),E=d.useMemo(()=>e.find(t=>t.providerId===R)||e[0]||null,[e,R]),v=d.useMemo(()=>{var t;if(I&&y.has(I))return y.get(I);if(g){const r=h.find(i=>i.id===g);if(r!=null&&r.modelId&&y.has(r.modelId))return y.get(r.modelId)}return((t=E==null?void 0:E.models)==null?void 0:t[0])||null},[I,y,E,h,g]),ie=d.useMemo(()=>h.find(t=>t.id===g)||null,[h,g]),he=(ie==null?void 0:ie.messages)||[],ge=d.useMemo(()=>[...h].sort((t,r)=>new Date(r.updatedAt).getTime()-new Date(t.updatedAt).getTime()),[h]),ae=!me&&!!v&&(_.trim().length>0||z.length>0);d.useEffect(()=>{if(K)try{globalThis.localStorage.setItem(O.sessions,JSON.stringify(h)),globalThis.localStorage.setItem(O.activeSessionId,g),globalThis.localStorage.setItem(O.activeProviderId,R),globalThis.localStorage.setItem(O.draft,_)}catch{}},[K,h,g,R,_]),d.useEffect(()=>{if(!K||m||te.current||e.length===0)return;const t=e.find(n=>n.providerId===R)||e[0],r=I&&y.has(I)?y.get(I):t.models[0];if(h.length>0){const n=h.find(x=>x.id===g)||h[0],o=n!=null&&n.modelId&&y.has(n.modelId)?y.get(n.modelId):r;te.current=!0,M(n.id),P((o==null?void 0:o.providerId)||t.providerId),U((o==null?void 0:o.id)||r.id);return}const i={id:J(),title:"New chat",providerId:t.providerId,providerName:t.providerName,modelId:r.id,modelName:r.name,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),messages:[]};te.current=!0,D([i]),M(i.id),P(t.providerId),U(r.id)},[K,m,e,y,h,g,R,I]);const L=(t,r)=>{D(i=>i.map(n=>n.id===t?r(Ve(n)):n))},ne=t=>t?{id:J(),title:"New chat",providerId:t.providerId,providerName:t.providerName,modelId:t.id,modelName:t.name,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),messages:[]}:null,ke=t=>{const r=h.find(i=>i.id===t);r&&(M(t),P(r.providerId||R),U(r.modelId||I),ee(!1))},Te=()=>{if(!g)return;const t=h.filter(i=>i.id!==g),r=t[0]||null;D(t),r?(M(r.id),P(r.providerId),U(r.modelId)):(M(""),P(""),U(""))},Ce=t=>{const r=y.get(t);if(!r)return;const i=h.find(n=>n.id===g);if(i&&i.messages.length>0){const n=ne(r);if(!n)return;D(o=>[n,...o]),M(n.id)}else if(i)D(n=>n.map(o=>o.id===i.id?{...o,providerId:r.providerId,providerName:r.providerName,modelId:r.id,modelName:r.name}:o)),M(i.id);else{const n=ne(r);if(!n)return;D(o=>[n,...o]),M(n.id)}P(r.providerId),U(r.id),Z(!1)},Oe=async t=>{const r=Array.from(t.target.files||[]);if(r.length===0)return;const i=r.filter(o=>o.type.startsWith("image/"));if(i.length===0){t.target.value="";return}const n=await Promise.all(i.map(async o=>({id:J(),name:o.name,type:o.type,size:o.size,dataUrl:await Ye(o)})));Q(o=>[...o,...n]),t.target.value=""},Re=t=>{Q(r=>r.filter(i=>i.id!==t))},Ee=()=>{var t;(t=B.current)==null||t.abort()},$e=(t,r)=>{const i=Ne(r);L(t,n=>({...n,title:n.title==="New chat"?i:n.title,updatedAt:new Date().toISOString()}))},we=async()=>{var p,b,$,N,W,Y;const t=v||((p=E==null?void 0:E.models)==null?void 0:p[0])||null;if(!t)return;const r=_.trim();if(!r&&z.length===0)return;let i=g,n=h.find(l=>l.id===i);if(!n){if(n=ne(t),!n)return;i=n.id,D(l=>[n,...l]),M(i)}const o={id:J(),role:"user",content:r,attachments:z.map(l=>({id:l.id,name:l.name,type:l.type,dataUrl:l.dataUrl})),createdAt:new Date().toISOString()},x=J(),k={id:x,role:"assistant",content:"",createdAt:new Date().toISOString(),status:"streaming"},q=[...n.messages||[],o,k];D(l=>l.map(j=>j.id===i?{...j,providerId:t.providerId,providerName:t.providerName,modelId:t.id,modelName:t.name,messages:q,updatedAt:new Date().toISOString(),title:j.title==="New chat"?Ne(r):j.title}:j)),ce(""),Q([]),ue(!0),pe(x),X(""),(b=B.current)==null||b.abort(),B.current=new AbortController;const c=q.filter(l=>!(l.role==="assistant"&&l.id===x)).map(l=>({role:l.role,content:l.role==="user"?Ke(l):l.content}));try{const l=await fetch("/api/dashboard/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream"},body:JSON.stringify({model:t.requestModel||t.id,messages:c,stream:!0}),signal:B.current.signal});if(!l.ok){const f=await l.json().catch(()=>({}));throw new Error(S(f.error||f.message||`Request failed (${l.status})`))}const j=($=l.body)==null?void 0:$.getReader();if(!j){const f=await l.json().catch(()=>({})),C=S(((Y=(W=(N=f==null?void 0:f.choices)==null?void 0:N[0])==null?void 0:W.message)==null?void 0:Y.content)||(f==null?void 0:f.output_text)||(f==null?void 0:f.error)||(f==null?void 0:f.message)||"");L(i,F=>({...F,messages:F.messages.map(H=>H.id===x?{...H,content:C,status:"done"}:H),updatedAt:new Date().toISOString()}));return}const V=new TextDecoder;let T="",G="";for(;;){const{value:f,done:C}=await j.read();if(C)break;T+=V.decode(f,{stream:!0});const F=T.split(/\r?\n/);T=F.pop()||"";for(const H of F){const ve=H.trim();if(!ve.startsWith("data:"))continue;const oe=ve.slice(5).trim();if(!(!oe||oe==="[DONE]"))try{const ze=JSON.parse(oe),be=We(ze);if(!be)continue;G+=be,X(G),L(i,ye=>({...ye,messages:ye.messages.map(le=>le.id===x?{...le,content:G,status:"streaming"}:le),updatedAt:new Date().toISOString()}))}catch{}}}L(i,f=>({...f,messages:f.messages.map(C=>C.id===x?{...C,content:G||C.content,status:"done"}:C),updatedAt:new Date().toISOString()})),$e(i,r)}catch(l){if(l.name!=="AbortError"){const j=S((l==null?void 0:l.message)||l);L(i,V=>({...V,messages:V.messages.map(T=>T.id===x?{...T,content:T.content||`Error: ${j}`,status:"error"}:T),updatedAt:new Date().toISOString()})),A(j||"Failed to send message.")}}finally{ue(!1),pe(""),X(""),B.current=null}},Pe=t=>{t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),ae&&we())},Ue=v?`${v.name}`:"Select model",_e=v?v.requestModel:"Choose from connected providers";return s.jsx("div",{className:"relative flex-1 flex flex-col h-full min-h-0 min-w-0 bg-[#212121] text-white overflow-hidden",children:s.jsxs("div",{className:"relative mx-auto flex flex-1 h-full min-h-0 w-full max-w-4xl flex-col",children:[s.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-3 px-4 py-3 lg:px-6",children:[s.jsxs("div",{ref:se,className:"relative",children:[s.jsx("button",{type:"button",onClick:()=>Z(t=>!t),className:"flex items-center gap-3 rounded-2xl border border-white/10 bg-white/5 px-4 py-3 text-left transition hover:bg-white/8",children:s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-sm font-semibold text-white",children:Ue}),s.jsx("span",{className:"material-symbols-outlined text-[18px] text-white/70",children:"expand_more"})]}),s.jsx("p",{className:"truncate text-xs text-white/55",children:_e})]})}),Me?s.jsxs("div",{className:"absolute left-0 top-[calc(100%+10px)] z-30 w-[min(520px,calc(100vw-2rem))] overflow-hidden rounded-[20px] border border-white/10 bg-[#262626] shadow-2xl shadow-black/50",children:[s.jsxs("div",{className:"border-b border-white/10 px-4 py-3",children:[s.jsx("p",{className:"text-xs uppercase tracking-[0.22em] text-white/45",children:"Models"}),s.jsx("p",{className:"text-sm text-white/75",children:"Only from connected providers"})]}),s.jsx("div",{className:"max-h-[60vh] overflow-y-auto p-2 custom-scrollbar",children:e.map(t=>s.jsxs("div",{className:"mb-2 rounded-[16px] border border-white/10 bg-black/20 p-2",children:[s.jsxs("div",{className:"flex items-center justify-between px-2 py-2",children:[s.jsx("p",{className:"text-sm font-semibold text-white",children:t.providerName}),s.jsx(qe,{size:"sm",variant:"default",children:t.models.length})]}),s.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:t.models.map(r=>{const i=r.id===I;return s.jsx("button",{type:"button",onClick:()=>Ce(r.id),className:`rounded-[14px] border px-3 py-3 text-left transition ${i?"border-blue-400/40 bg-blue-500/15":"border-white/10 bg-white/5 hover:bg-white/8"}`,children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("p",{className:"truncate text-sm font-medium text-white",children:r.name}),s.jsx("p",{className:"truncate text-[11px] text-white/45",children:r.requestModel})]}),i?s.jsx("span",{className:"material-symbols-outlined text-[18px] text-blue-300",children:"check_circle"}):null]})},r.id)})})]},t.providerId))})]}):null]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",onClick:()=>ee(t=>!t),className:"rounded-2xl border border-white/10 bg-white/5 px-4 py-3 text-sm text-white/80 transition hover:bg-white/8",children:"History"}),s.jsx(Be,{variant:"ghost",size:"sm",icon:"delete",onClick:Te,disabled:!g||h.length===0,children:"Clear"})]})]}),De?s.jsxs("div",{ref:re,className:"absolute right-4 top-[72px] z-20 w-[min(360px,calc(100vw-2rem))] rounded-[20px] border border-white/10 bg-[#262626] p-2 shadow-2xl shadow-black/50 lg:right-6",children:[s.jsx("div",{className:"px-3 py-2",children:s.jsx("p",{className:"text-xs uppercase tracking-[0.22em] text-white/45",children:"Recent chats"})}),s.jsx("div",{className:"max-h-[48vh] space-y-2 overflow-y-auto p-1 custom-scrollbar",children:ge.length===0?s.jsx("div",{className:"rounded-[16px] border border-dashed border-white/10 bg-white/5 p-4 text-sm text-white/55",children:"No conversations yet."}):ge.map(t=>{var n;const r=t.id===g,i=[...t.messages||[]].reverse().find(o=>o.role==="user")||((n=t.messages)==null?void 0:n[0]);return s.jsx("button",{type:"button",onClick:()=>ke(t.id),className:`w-full rounded-[16px] border px-3 py-3 text-left transition ${r?"border-blue-400/40 bg-blue-500/15":"border-white/10 bg-white/5 hover:bg-white/8"}`,children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"truncate text-sm font-medium text-white",children:t.title}),s.jsx("p",{className:"mt-1 truncate text-xs text-white/50",children:S(i==null?void 0:i.content)||"Empty chat"})]}),s.jsx("span",{className:"text-[10px] text-white/40 shrink-0",children:Je(t.updatedAt)})]})},t.id)})})]}):null,w?s.jsx("div",{className:"mt-4 rounded-[18px] border border-rose-500/20 bg-rose-500/10 px-4 py-3 text-rose-100",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("span",{className:"material-symbols-outlined text-[20px]",children:"error"}),s.jsx("p",{className:"text-sm leading-6",children:w})]})}):null,s.jsxs("div",{className:"flex flex-1 flex-col min-h-0",children:[s.jsxs("div",{className:"flex-1 overflow-y-auto py-4 custom-scrollbar",children:[he.length===0?s.jsx("div",{className:"flex min-h-[50vh] items-center justify-center px-4 text-center",children:s.jsxs("div",{className:"max-w-xl space-y-4",children:[s.jsx("div",{className:"mx-auto flex size-16 items-center justify-center rounded-[20px] border border-white/10 bg-white/5 text-white/80",children:s.jsx("span",{className:"material-symbols-outlined text-[30px]",children:"chat"})}),s.jsxs("div",{className:"space-y-2",children:[s.jsx("h2",{className:"text-2xl font-semibold text-white",children:"Start a conversation"}),s.jsx("p",{className:"text-sm leading-6 text-white/60",children:"Simple chat interface to interact with any AI model from connected providers. Select a model and start chatting!"})]})]})}):null,s.jsx("div",{className:"mx-auto flex w-full max-w-3xl flex-col gap-4 px-4",children:he.map(t=>{var x;const r=t.role==="user",i=t.role==="assistant",n=i&&t.id===Se&&t.status==="streaming",o=S(t.content)||(i?fe:"");return s.jsx("div",{className:`flex w-full ${r?"justify-end":"justify-start"} mb-6`,children:s.jsxs("div",{className:`max-w-[min(88%,42rem)] ${r?"rounded-3xl bg-[#2f2f2f] px-5 py-3.5 text-white":"text-white/90"}`,children:[s.jsx("div",{className:"mb-1 flex items-center justify-between gap-3",children:s.jsx("span",{className:"text-xs font-semibold",children:r?"You":(v==null?void 0:v.name)||"Assistant"})}),(x=t.attachments)!=null&&x.length?s.jsx("div",{className:"mb-3 grid grid-cols-2 gap-2 sm:grid-cols-3 mt-2",children:t.attachments.map(k=>s.jsx("a",{href:k.dataUrl,target:"_blank",rel:"noreferrer",className:"overflow-hidden rounded-[18px] border border-white/10 bg-black/20",children:s.jsx("img",{src:k.dataUrl,alt:k.name,className:"h-28 w-full object-cover"})},k.id))}):null,s.jsxs("div",{className:"whitespace-pre-wrap break-words text-[15px] leading-7",children:[o,i&&n&&!fe?s.jsx("span",{className:"inline-block animate-pulse",children:"▋"}):null]})]})},t.id)})})]}),s.jsxs("div",{className:"shrink-0 pt-2",children:[z.length>0?s.jsx("div",{className:"mx-auto mb-3 flex w-full max-w-3xl flex-wrap gap-2 px-4",children:z.map(t=>s.jsxs("div",{className:"flex items-center gap-2 rounded-full border border-white/10 bg-white/5 px-3 py-2",children:[s.jsx("span",{className:"text-xs text-white/80 max-w-[12rem] truncate",children:t.name}),s.jsx("button",{type:"button",onClick:()=>Re(t.id),className:"text-white/55 hover:text-white","aria-label":"Remove attachment",children:s.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"close"})})]},t.id))}):null,s.jsx("div",{className:"mx-auto w-full max-w-3xl px-4 pb-2",children:s.jsxs("div",{className:"rounded-[26px] bg-[#2f2f2f] px-3 pt-3 pb-2 shadow-[0_0_15px_rgba(0,0,0,0.10)] ring-1 ring-white/5",children:[s.jsx("textarea",{value:_,onChange:t=>ce(t.target.value),onKeyDown:Pe,placeholder:"Message AI",rows:1,className:"w-full resize-none bg-transparent px-2 text-[15px] leading-6 text-white outline-none placeholder:text-white/40 custom-scrollbar max-h-[25vh] overflow-y-auto"}),s.jsxs("div",{className:"mt-2 flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{var t;return(t=xe.current)==null?void 0:t.click()},disabled:!v||m,className:"p-2 text-white/50 hover:text-white transition rounded-full hover:bg-white/5",children:s.jsx("span",{className:"material-symbols-outlined text-[20px]",children:"attach_file"})}),s.jsx("input",{ref:xe,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:Oe}),s.jsx("span",{className:"text-xs font-medium text-white/30 truncate max-w-[120px]",children:v?v.name:"No model"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[me?s.jsx("button",{type:"button",onClick:Ee,className:"p-2 text-white bg-white/10 hover:bg-white/20 transition rounded-full h-8 w-8 flex items-center justify-center",children:s.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"stop"})}):null,s.jsx("button",{onClick:we,disabled:!ae,className:`h-8 w-8 rounded-full flex items-center justify-center transition ${ae?"bg-white text-black hover:opacity-90":"bg-white/10 text-white/30 cursor-not-allowed"}`,children:s.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"arrow_upward"})})]})]})]})})]}),s.jsx("p",{className:"mx-auto mt-2 max-w-3xl px-4 pb-4 text-center text-[11px] text-white/30",children:"Model list is filtered from connected providers."})]})]})})}function at(){return s.jsx(et,{})}export{at as default};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{j as t,B as C}from"./index.BO_pNnMt.js";import{b as r}from"./router.Cjj1--8t.js";import"./NoAuthProxyCard.CLW2-XwE.js";import"./zustand.akaTi5uX.js";function Z(){const[E,j]=r.useState(!1),[y,N]=r.useState(!1),[D,n]=r.useState(""),[L,w]=r.useState(""),[R,g]=r.useState(0),[F,S]=r.useState(""),[M,A]=r.useState([]),[T,J]=r.useState(""),[O,U]=r.useState(""),[k,q]=r.useState(null),[I,B]=r.useState(!1),$=r.useRef(null);r.useEffect(()=>{fetch("/api/db/info").then(e=>e.ok?e.json():null).then(e=>{e&&(q(e),U(e.examplePath||""))}).catch(()=>{})},[]);const s=r.useCallback((e,a="info")=>{A(u=>[...u.slice(-300),{msg:e,level:a,ts:new Date().toLocaleTimeString()}])},[]),_=r.useCallback(async()=>{N(!0),n(""),s("Memulai backup data (logical)...");try{const e=await fetch("/api/db");if(!e.ok)throw new Error(`HTTP ${e.status}`);const a=Number(e.headers.get("Content-Length"))||0,u=e.body.getReader(),o=new TextDecoder;let l=0,d="";for(;;){const{done:b,value:p}=await u.read();if(b)break;l+=p.length,a&&g(Math.min(99,Math.round(l/a*100))),d+=o.decode(p,{stream:!0})}const m=JSON.parse(d),x=new Blob([JSON.stringify(m,null,2)],{type:"application/json"}),h=URL.createObjectURL(x),f=document.createElement("a");f.href=h,f.download="fsrouter-backup.fud",f.click(),URL.revokeObjectURL(h),g(100),s("✓ Backup selesai: fsrouter-backup.fud","info")}catch(e){s("ERROR: "+e.message,"error"),n("Gagal backup: "+e.message)}finally{N(!1)}},[s]),G=r.useCallback(async()=>{N(!0),n(""),s("Memulai backup database mentah (.sqlite)...");try{const e=await fetch("/api/db/raw");if(!e.ok)throw new Error(`HTTP ${e.status}`);const a=Number(e.headers.get("Content-Length"))||0,u=e.body.getReader(),o=[];let l=0;for(;;){const{done:h,value:f}=await u.read();if(h)break;l+=f.length,a&&g(Math.min(99,Math.round(l/a*100))),o.push(f)}const d=new Blob(o,{type:"application/octet-stream"}),m=URL.createObjectURL(d),x=document.createElement("a");x.href=m,x.download=`fsrouter-db-raw-${Date.now()}.sqlite`,x.click(),URL.revokeObjectURL(m),g(100),s("✓ Backup mentah selesai","info")}catch(e){s("ERROR: "+e.message,"error"),n("Gagal backup mentah: "+e.message)}finally{N(!1)}},[s]),v=r.useCallback(async e=>{n(""),w(""),A([]),g(0),S("Memulai restore..."),j(!0);try{const a=await fetch("/api/db",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!a.ok||!a.body){const m=await a.json().catch(()=>({}));throw new Error(m.error||`HTTP ${a.status}`)}const u=a.body.getReader(),o=new TextDecoder;let l="",d=!1;for(;!d;){const{done:m,value:x}=await u.read();if(m)break;l+=o.decode(x,{stream:!0});const h=l.split(`
|
|
2
|
+
|
|
3
|
+
`);l=h.pop()||"";for(const f of h){const b=f.split(`
|
|
4
|
+
`);let p="message",c="";for(const P of b)P.startsWith("event:")?p=P.slice(6).trim():P.startsWith("data:")&&(c=P.slice(5).trim());if(!c)continue;let i;try{i=JSON.parse(c)}catch{continue}p==="progress"?(g(i.percent||0),S(i.label||""),s(`[${i.percent}%] ${i.label}`,"info")):p==="log"?s(i.message,i.level||"info"):p==="error"?(s(`ERROR: ${i.message}`,"error"),n(i.message)):p==="done"&&(s("✓ "+(i.message||"Selesai"),"info"),w("Restore berhasil! Server sedang merestart, harap tunggu beberapa saat..."),d=!0,setTimeout(()=>window.location.reload(),5e3))}}d||(w("Restore selesai. Server sedang merestart..."),setTimeout(()=>window.location.reload(),5e3))}catch(a){s("ERROR: "+(a.message||a),"error"),n(a.message||"File backup corrupt atau tidak valid."),j(!1)}},[s]),W=r.useCallback(async e=>{if(!e)return;if(!e.name.endsWith(".fud")&&!e.name.endsWith(".json")&&!e.name.endsWith(".sqlite")){n("Format tidak didukung (.fud / .json / .sqlite)");return}if(!window.confirm("PERINGATAN: Restore akan MENIMPA semua data saat ini! Lanjutkan?"))return;if(e.name.endsWith(".sqlite")){const u=await new Promise(o=>{const l=new FileReader;l.onload=()=>o(btoa(new Uint8Array(l.result).reduce((d,m)=>d+String.fromCharCode(m),""))),l.readAsArrayBuffer(e)});return v({signature:"FUDROUTER_BACKUP",version:1,files:{"db/data.sqlite":u}})}const a=new FileReader;a.onload=async u=>{try{const o=JSON.parse(u.target.result);await v(o)}catch{n("File backup corrupt atau tidak valid."),j(!1)}},a.readAsText(e)},[v]),H=e=>W(e.target.files[0]),z=r.useCallback(async()=>{if(!T.trim()){n("Textarea kosong.");return}if(window.confirm("PERINGATAN: Restore akan MENIMPA semua data saat ini! Lanjutkan?"))try{const e=JSON.parse(T);await v(e)}catch{n("JSON tidak valid."),j(!1)}},[T,v]),K=r.useCallback(async()=>{if(!O.trim()){n("Path kosong.");return}if(window.confirm("PERINGATAN: Restore akan MENIMPA semua data saat ini! Lanjutkan?"))try{const e=await fetch("/api/db/restore-path",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:O.trim()})});if(!e.ok||!e.body){const d=await e.json().catch(()=>({}));throw new Error(d.error||`HTTP ${e.status}`)}const a=e.body.getReader(),u=new TextDecoder;let o="",l=!1;for(n(""),w(""),A([]),g(0),S("Memulai restore dari path..."),j(!0);!l;){const{done:d,value:m}=await a.read();if(d)break;o+=u.decode(m,{stream:!0});const x=o.split(`
|
|
5
|
+
|
|
6
|
+
`);o=x.pop()||"";for(const h of x){const f=h.split(`
|
|
7
|
+
`);let b="message",p="";for(const i of f)i.startsWith("event:")?b=i.slice(6).trim():i.startsWith("data:")&&(p=i.slice(5).trim());if(!p)continue;let c;try{c=JSON.parse(p)}catch{continue}b==="progress"?(g(c.percent||0),S(c.label||""),s(`[${c.percent}%] ${c.label}`)):b==="log"?s(c.message,c.level||"info"):b==="error"?(s("ERROR: "+c.message,"error"),n(c.message)):b==="done"&&(s("✓ "+(c.message||"Selesai")),w("Restore berhasil! Server merestart..."),l=!0,setTimeout(()=>window.location.reload(),5e3))}}}catch(e){s("ERROR: "+(e.message||e),"error"),n(e.message||"Gagal restore dari path."),j(!1)}},[O,s]);return t.jsxs("div",{className:"max-w-4xl mx-auto p-4 space-y-6",children:[t.jsxs("div",{className:"flex flex-col gap-1",children:[t.jsxs("h1",{className:"text-2xl font-bold text-text-main flex items-center gap-2",children:[t.jsx("span",{className:"material-symbols-outlined text-[28px] text-primary",children:"backup"}),"Backup & Restore"]}),t.jsx("p",{className:"text-xs text-text-muted",children:"Amankan seluruh data FSRouter (provider, connections, akun automation, proxy, api keys) ke satu file, atau pulihkan dari file/teks/path."})]}),D&&t.jsxs("div",{className:"p-4 bg-red-500/10 border border-red-500/20 text-red-500 text-sm rounded-lg flex items-center gap-2",children:[t.jsx("span",{className:"material-symbols-outlined text-sm",children:"error"}),D]}),L&&t.jsxs("div",{className:"p-4 bg-green-500/10 border border-green-500/20 text-green-500 text-sm rounded-lg flex items-center gap-2",children:[t.jsx("span",{className:"material-symbols-outlined text-sm",children:"check_circle"}),L]}),t.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[t.jsxs("div",{className:"p-6 rounded-[14px] border border-border-subtle bg-surface flex flex-col gap-4",children:[t.jsxs("div",{className:"flex items-center gap-3 text-text-main",children:[t.jsx("div",{className:"size-10 rounded-full bg-blue-500/10 text-blue-500 flex items-center justify-center",children:t.jsx("span",{className:"material-symbols-outlined text-xl",children:"cloud_download"})}),t.jsxs("div",{children:[t.jsx("h2",{className:"text-sm font-semibold",children:"Buat Backup"}),t.jsx("p",{className:"text-[11px] text-text-muted",children:"Simpan data ke perangkat"})]})]}),t.jsx("div",{className:"text-xs text-text-muted leading-relaxed flex-1",children:t.jsxs("ul",{className:"list-disc list-inside space-y-1 ml-1",children:[t.jsxs("li",{children:[t.jsx("b",{children:"Portabel (.fud)"}),": semua data sebagai JSON — bisa dipulihkan di OS berbeda."]}),t.jsxs("li",{children:[t.jsx("b",{children:"Mentah (.sqlite)"}),": copy langsung file database — paling akurat, sama OS."]})]})}),t.jsx(C,{variant:"primary",fullWidth:!0,onClick:_,disabled:y,icon:"download",children:y?`Membackup... ${R}%`:"Download Backup (.fud)"}),t.jsx(C,{variant:"secondary",fullWidth:!0,onClick:G,disabled:y,icon:"storage",children:"Download Database Mentah (.sqlite)"}),y&&t.jsx("div",{className:"w-full h-2.5 rounded-full bg-sidebar overflow-hidden",children:t.jsx("div",{className:"h-full bg-gradient-to-r from-primary to-emerald-400 transition-all",style:{width:`${R}%`}})})]}),t.jsxs("div",{className:"p-6 rounded-[14px] border border-border-subtle bg-surface flex flex-col gap-4",children:[t.jsxs("div",{className:"flex items-center gap-3 text-text-main",children:[t.jsx("div",{className:"size-10 rounded-full bg-amber-500/10 text-amber-500 flex items-center justify-center",children:t.jsx("span",{className:"material-symbols-outlined text-xl",children:"restore"})}),t.jsxs("div",{children:[t.jsx("h2",{className:"text-sm font-semibold",children:"Pulihkan Backup"}),t.jsx("p",{className:"text-[11px] text-text-muted",children:"Timpa data dari file/teks/path"})]})]}),t.jsxs("div",{onDragOver:e=>{e.preventDefault(),B(!0)},onDragLeave:()=>B(!1),onDrop:e=>{e.preventDefault(),B(!1),W(e.dataTransfer.files[0])},onClick:()=>{var e;return(e=$.current)==null?void 0:e.click()},className:`border-2 border-dashed rounded-lg p-5 text-center cursor-pointer transition-colors ${I?"border-primary bg-primary/5":"border-border-subtle hover:border-primary/50"}`,children:[t.jsx("span",{className:"material-symbols-outlined text-3xl text-text-muted",children:"upload_file"}),t.jsx("p",{className:"text-xs text-text-muted mt-1",children:"Klik atau seret file .fud / .json / .sqlite ke sini"})]}),t.jsx("input",{type:"file",accept:".fud,.json,.sqlite",ref:$,onChange:H,className:"hidden"}),t.jsxs("div",{className:"space-y-1",children:[t.jsx("label",{className:"text-[11px] text-text-muted",children:"Atau tempel (paste) isi file backup JSON:"}),t.jsx("textarea",{value:T,onChange:e=>J(e.target.value),placeholder:'{ "signature": "FUDROUTER_BACKUP", ... }',className:"w-full h-20 text-[11px] font-mono bg-black/40 border border-border-subtle rounded p-2 text-text-main resize-none"}),t.jsx(C,{variant:"secondary",fullWidth:!0,onClick:z,disabled:E,icon:"content_paste",children:"Restore dari Teks"})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("label",{className:"text-[11px] text-text-muted",children:["Atau path file di server",k?` (${k.isWindows?"Windows":k.platform}):`:":"]}),t.jsx("input",{value:O,onChange:e=>U(e.target.value),placeholder:(k==null?void 0:k.examplePath)||"C:\\Users\\fud\\AppData\\Roaming\\fsrouter\\backups\\fsrouter-backup.fud",className:"w-full text-[11px] bg-black/40 border border-border-subtle rounded p-2 text-text-main"}),k&&t.jsxs("p",{className:"text-[10px] text-text-muted",children:["Folder backup default: ",t.jsx("code",{className:"text-primary",children:k.defaultBackupDir})]}),t.jsx(C,{variant:"secondary",fullWidth:!0,onClick:K,disabled:E,icon:"folder_open",children:"Restore dari Path"})]}),E&&t.jsxs("div",{className:"mt-2 space-y-3",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"flex justify-between text-[11px] text-text-muted mb-1",children:[t.jsx("span",{children:F||"Memproses..."}),t.jsxs("span",{children:[R,"%"]})]}),t.jsx("div",{className:"w-full h-2.5 rounded-full bg-sidebar overflow-hidden",children:t.jsx("div",{className:"h-full bg-gradient-to-r from-primary to-emerald-400 transition-all duration-300",style:{width:`${R}%`}})})]}),t.jsx("div",{className:"bg-black/80 rounded-lg p-3 h-48 overflow-y-auto font-mono text-[10px] leading-relaxed",children:M.length===0?t.jsx("div",{className:"text-text-muted",children:"Menunggu output restore..."}):M.map((e,a)=>t.jsxs("div",{className:e.level==="error"?"text-red-400":e.level==="warn"?"text-amber-400":"text-green-300",children:[t.jsxs("span",{className:"text-text-muted",children:["[",e.ts,"]"]})," ",e.msg]},a))})]})]})]})]})}export{Z as default};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{j as e,f as l,B as N,g as Ve,M as tt,u as _s,O as gt,A as bt,F as et,c as Ht,W as Fs,h as Ks,i as zs,k as qs,l as Vs,T as Bs,C as Qt,t as Ee}from"./index.BO_pNnMt.js";import{b as i,h as Gs,d as Js,L as Yt}from"./router.Cjj1--8t.js";import{B as Ue,T as st,I as ce,S as yt,C as Ne,N as Ws,K as Hs,a as Qs,G as Ys,O as Xs,b as Zs,E as ea}from"./NoAuthProxyCard.CLW2-XwE.js";import{L as ta,C as Xt}from"./Loading.BoU3gy5K.js";import"./zustand.akaTi5uX.js";const sa=600*1e3,Zt=new Map;async function aa(n){if(!(n!=null&&n.url)||!(n!=null&&n.type))return[];const c=Zt.get(n.url);if(c&&Date.now()<c.expiresAt)return c.data;try{const a=new URLSearchParams({url:n.url,type:n.type}),d=await fetch(`/api/providers/suggested-models?${a}`);if(!d.ok)return[];const u=(await d.json()).data??[];return Zt.set(n.url,{data:u,expiresAt:Date.now()+sa}),u}catch{return[]}}function vt({model:n,fullModel:c,alias:a,copied:d,onCopy:x,testStatus:u,isCustom:f,isFree:h,onDeleteAlias:o,onTest:b,isTesting:S,onDisable:C}){const R=u==="ok"?"border-green-500/40":u==="error"?"border-red-500/40":"border-border",L=u==="ok"?"#22c55e":u==="error"?"#ef4444":void 0;return e.jsx("div",{className:`group min-w-0 max-w-full rounded-lg border px-3 py-2 ${R} hover:bg-sidebar/50`,children:e.jsxs("div",{className:"flex min-w-0 items-start gap-2 sm:items-center",children:[e.jsx("span",{className:"material-symbols-outlined shrink-0 text-base",style:L?{color:L}:void 0,children:u==="ok"?"check_circle":u==="error"?"cancel":"smart_toy"}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[e.jsx("code",{className:"max-w-[72vw] truncate rounded bg-sidebar px-1.5 py-0.5 font-mono text-xs text-text-muted sm:max-w-[360px]",children:c}),n.name&&e.jsx("span",{className:"truncate pl-1 text-[9px] italic text-text-muted/70",children:n.name})]}),b&&e.jsxs("div",{className:"relative shrink-0 group/btn",children:[e.jsx("button",{onClick:b,disabled:S,className:`rounded p-0.5 text-text-muted transition-opacity hover:bg-sidebar hover:text-primary ${S?"opacity-100":"opacity-100 sm:opacity-0 sm:group-hover:opacity-100"}`,children:e.jsx("span",{className:"material-symbols-outlined text-sm",style:S?{animation:"spin 1s linear infinite"}:void 0,children:S?"progress_activity":"science"})}),e.jsx("span",{className:"pointer-events-none absolute mt-1 top-5 left-1/2 -translate-x-1/2 text-[10px] text-text-muted whitespace-nowrap opacity-0 group-hover/btn:opacity-100 transition-opacity",children:S?"Testing...":"Test"})]}),e.jsxs("div",{className:"relative shrink-0 group/btn",children:[e.jsx("button",{onClick:()=>x(c,`model-${n.id}`),className:"rounded p-0.5 text-text-muted hover:bg-sidebar hover:text-primary",children:e.jsx("span",{className:"material-symbols-outlined text-sm",children:d===`model-${n.id}`?"check":"content_copy"})}),e.jsx("span",{className:"pointer-events-none absolute mt-1 top-5 left-1/2 -translate-x-1/2 text-[10px] text-text-muted whitespace-nowrap opacity-0 group-hover/btn:opacity-100 transition-opacity",children:d===`model-${n.id}`?"Copied!":"Copy"})]}),f?e.jsx("button",{onClick:o,className:"ml-auto rounded p-0.5 text-text-muted opacity-100 transition-opacity hover:bg-red-500/10 hover:text-red-500 sm:opacity-0 sm:group-hover:opacity-100",title:"Remove custom model",children:e.jsx("span",{className:"material-symbols-outlined text-sm",children:"close"})}):C?e.jsx("button",{onClick:C,className:"ml-auto rounded p-0.5 text-text-muted opacity-100 transition-opacity hover:bg-red-500/10 hover:text-red-500 sm:opacity-0 sm:group-hover:opacity-100",title:"Disable this model",children:e.jsx("span",{className:"material-symbols-outlined text-sm",children:"close"})}):null]})})}vt.propTypes={model:l.shape({id:l.string.isRequired}).isRequired,fullModel:l.string.isRequired,alias:l.string,copied:l.string,onCopy:l.func.isRequired,testStatus:l.oneOf(["ok","error"]),isCustom:l.bool,isFree:l.bool,onDeleteAlias:l.func,onTest:l.func,isTesting:l.bool,onDisable:l.func};l.string.isRequired,l.string.isRequired,l.string,l.func.isRequired,l.func.isRequired,l.func,l.oneOf(["ok","error"]),l.bool;l.string.isRequired,l.object.isRequired,l.string,l.func.isRequired,l.func.isRequired,l.func.isRequired;function la({modelId:n,fullModel:c,copied:a,onCopy:d,onDeleteAlias:x,onTest:u,testStatus:f,isTesting:h}){const o=f==="ok"?"border-green-500/40":f==="error"?"border-red-500/40":"border-border",b=f==="ok"?"#22c55e":f==="error"?"#ef4444":void 0;return e.jsxs("div",{className:`flex items-center gap-3 p-3 rounded-lg border ${o} hover:bg-sidebar/50`,children:[e.jsx("span",{className:"material-symbols-outlined text-base text-text-muted",style:b?{color:b}:void 0,children:f==="ok"?"check_circle":f==="error"?"cancel":"smart_toy"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:n}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx("code",{className:"text-xs text-text-muted font-mono bg-sidebar px-1.5 py-0.5 rounded",children:c}),e.jsxs("div",{className:"relative group/btn",children:[e.jsx("button",{onClick:()=>d(c,`model-${n}`),className:"p-0.5 hover:bg-sidebar rounded text-text-muted hover:text-primary",children:e.jsx("span",{className:"material-symbols-outlined text-sm",children:a===`model-${n}`?"check":"content_copy"})}),e.jsx("span",{className:"pointer-events-none absolute top-5 left-1/2 -translate-x-1/2 text-[10px] text-text-muted whitespace-nowrap opacity-0 group-hover/btn:opacity-100 transition-opacity",children:a===`model-${n}`?"Copied!":"Copy"})]}),u&&e.jsxs("div",{className:"relative group/btn",children:[e.jsx("button",{onClick:u,disabled:h,className:"p-0.5 hover:bg-sidebar rounded text-text-muted hover:text-primary transition-colors",children:e.jsx("span",{className:"material-symbols-outlined text-sm",style:h?{animation:"spin 1s linear infinite"}:void 0,children:h?"progress_activity":"science"})}),e.jsx("span",{className:"pointer-events-none absolute top-5 left-1/2 -translate-x-1/2 text-[10px] text-text-muted whitespace-nowrap opacity-0 group-hover/btn:opacity-100 transition-opacity",children:h?"Testing...":"Test"})]})]})]}),e.jsx("button",{onClick:x,className:"p-1 hover:bg-red-50 rounded text-red-500",title:"Remove model",children:e.jsx("span",{className:"material-symbols-outlined text-sm",children:"delete"})})]})}function ls({providerStorageAlias:n,providerDisplayAlias:c,modelAliases:a,copied:d,onCopy:x,onSetAlias:u,onDeleteAlias:f,connections:h,isAnthropic:o}){const[b,S]=i.useState(""),[C,R]=i.useState(!1),[L,U]=i.useState(!1),[F,J]=i.useState(null),[X,E]=i.useState({}),Z=async y=>{if(!F){J(y);try{const B=await(await fetch("/api/models/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:`${n}/${y}`})})).json();E(te=>({...te,[y]:B.ok?"ok":"error"}))}catch{E($=>({...$,[y]:"error"}))}finally{J(null)}}},O=Object.entries(a).filter(([,y])=>y.startsWith(`${n}/`)).map(([y,$])=>({modelId:$.replace(`${n}/`,""),fullModel:$,alias:y})),P=y=>{const $=y.split("/");return $[$.length-1]},g=y=>{const $=`${n}/${y}`;if(Object.values(a).includes($))return null;const B=P(y);if(!a[B])return B;const te=`${c}-${B}`;return a[te]?null:te},_=async()=>{if(!b.trim()||C)return;const y=b.trim(),$=g(y);if(!$){alert("All suggested aliases already exist. Please choose a different model or remove conflicting aliases.");return}R(!0);try{await u(y,$,n),S("")}catch(B){console.log("Error adding model:",B)}finally{R(!1)}},z=async()=>{if(L)return;const y=h.find($=>$.isActive!==!1);if(y){U(!0);try{const $=await fetch(`/api/providers/${y.id}/models`),B=await $.json();if(!$.ok){alert(B.error||"Failed to import models");return}const te=B.models||[];if(te.length===0){alert("No models returned from /models.");return}let ie=0;for(const ne of te){const se=ne.id||ne.name||ne.model;if(!se)continue;const K=g(se);K&&(await u(se,K,n),ie+=1)}ie===0&&alert("No new models were added.")}catch($){console.log("Error importing models:",$)}finally{U(!1)}}},ee=h.some(y=>y.isActive!==!1);return e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("p",{className:"text-sm text-text-muted",children:["Add ",o?"Anthropic":"OpenAI","-compatible models manually or import them from the /models endpoint."]}),e.jsxs("div",{className:"flex items-end gap-2 flex-wrap",children:[e.jsxs("div",{className:"flex-1 min-w-[240px]",children:[e.jsx("label",{htmlFor:"new-compatible-model-input",className:"text-xs text-text-muted mb-1 block",children:"Model ID"}),e.jsx("input",{id:"new-compatible-model-input",type:"text",value:b,onChange:y=>S(y.target.value),onKeyDown:y=>y.key==="Enter"&&_(),placeholder:o?"claude-3-opus-20240229":"gpt-4o",className:"w-full px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary"})]}),e.jsx(N,{size:"sm",icon:"add",onClick:_,disabled:!b.trim()||C,children:C?"Adding...":"Add"}),e.jsx(N,{size:"sm",variant:"secondary",icon:"download",onClick:z,disabled:!ee||L,children:L?"Importing...":"Import from /models"})]}),!ee&&e.jsx("p",{className:"text-xs text-text-muted",children:"Add a connection to enable importing models."}),O.length>0&&e.jsx("div",{className:"flex flex-col gap-3",children:O.map(({modelId:y,fullModel:$,alias:B})=>e.jsx(la,{modelId:y,fullModel:`${c}/${y}`,copied:d,onCopy:x,onDeleteAlias:()=>f(B),onTest:h.length>0?()=>Z(y):void 0,testStatus:X[y],isTesting:F===y},$))})]})}ls.propTypes={providerStorageAlias:l.string.isRequired,providerDisplayAlias:l.string.isRequired,modelAliases:l.object.isRequired,copied:l.string,onCopy:l.func.isRequired,onSetAlias:l.func.isRequired,onDeleteAlias:l.func.isRequired,connections:l.arrayOf(l.shape({id:l.string,isActive:l.bool})).isRequired,isAnthropic:l.bool};function rs({until:n}){const[c,a]=i.useState("");return i.useEffect(()=>{const d=()=>{const u=new Date(n).getTime()-Date.now();if(u<=0){a("");return}const f=Math.floor(u/1e3);if(f<60)a(`${f}s`);else if(f<3600)a(`${Math.floor(f/60)}m ${f%60}s`);else{const h=Math.floor(f/3600),o=Math.floor(f%3600/60);a(`${h}h ${o}m`)}};d();const x=setInterval(d,1e3);return()=>clearInterval(x)},[n]),c?e.jsxs("span",{className:"text-xs text-orange-500 font-mono",children:["⏱ ",c]}):null}rs.propTypes={until:l.string.isRequired};function is({connection:n,proxyPools:c,isOAuth:a,isFirst:d,isLast:x,onMoveUp:u,onMoveDown:f,onToggleActive:h,onUpdateProxy:o,onEdit:b,onDelete:S,oneByOneStatus:C=null,isSelected:R,onSelect:L}){var pe,we,Ae,Me,ge,me,Ce;const[U,F]=i.useState(!1),[J,X]=i.useState(!1),E=i.useRef(null),Z=new Map((c||[]).map(T=>[T.id,T])),A=((pe=n.providerSpecificData)==null?void 0:pe.proxyPoolId)||null,O=A?Z.get(A):null,P=((we=n.providerSpecificData)==null?void 0:we.connectionProxyEnabled)===!0&&!!((Ae=n.providerSpecificData)!=null&&Ae.connectionProxyUrl),g=!!A||P,_=O?`Pool: ${O.name}`:A?`Pool: ${A} (inactive/missing)`:P?`Legacy: ${(Me=n.providerSpecificData)==null?void 0:Me.connectionProxyUrl}`:"";let z="";if(O!=null&&O.proxyUrl||(ge=n.providerSpecificData)!=null&&ge.connectionProxyUrl){const T=(O==null?void 0:O.proxyUrl)||((me=n.providerSpecificData)==null?void 0:me.connectionProxyUrl);try{const le=new URL(T);z=`${le.protocol}//${le.hostname}${le.port?`:${le.port}`:""}`}catch{z=T}}const ee=(O==null?void 0:O.noProxy)||((Ce=n.providerSpecificData)==null?void 0:Ce.connectionNoProxy)||"";let y="default";(O==null?void 0:O.isActive)===!0?y="success":(A||P)&&(y="error"),i.useEffect(()=>{if(!U)return;const T=le=>{E.current&&!E.current.contains(le.target)&&F(!1)};return document.addEventListener("mousedown",T),()=>document.removeEventListener("mousedown",T)},[U]);const $=async T=>{X(!0);try{await o(T==="__none__"?null:T)}finally{X(!1),F(!1)}},B=n.authType||(a?"oauth":"apikey"),te=B==="oauth",ie=B==="cookie",ne=ie?"cookie":te?"lock":"key",se=te?"OAuth":ie?"Cookie":"API Key",K=T=>typeof T=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(T),Q=te?K(n.email)?n.email:K(n.name)?n.name:n.name||n.email||n.displayName||"OAuth Account":n.name||n.email||n.displayName||"API Key",[oe,ue]=i.useState(!1),fe=Object.entries(n).filter(([T])=>T.startsWith("modelLock_")).map(([,T])=>T).filter(T=>!!T).sort()[0]||null;i.useEffect(()=>{const T=()=>{const v=Object.entries(n).filter(([Y])=>Y.startsWith("modelLock_")).map(([,Y])=>Y).filter(Y=>Y&&new Date(Y).getTime()>Date.now()).sort()[0]||null;ue(!!v)};T();const le=fe?setInterval(T,1e3):null;return()=>{le&&clearInterval(le)}},[fe]);const W=n.testStatus==="unavailable"&&!oe?"active":n.testStatus,be=()=>n.isActive===!1?"default":W==="active"||W==="success"?"success":W==="error"||W==="expired"||W==="unavailable"?"error":"default",ke=()=>C?C.state==="success"?"success":C.state==="failed"?"error":C.state==="testing"?"primary":"default":"default",ye=()=>C?C.state==="queued"?"queued":C.state==="testing"?"testing":C.state==="success"?"success":C.state==="failed"?C.error?`failed: ${C.error}`:"failed":null:null;return e.jsxs("div",{className:`group flex min-w-0 flex-col gap-3 rounded-lg p-2 transition-colors hover:bg-black/[0.02] dark:hover:bg-white/[0.02] sm:flex-row sm:items-center sm:justify-between ${n.isActive===!1?"opacity-60":""}`,children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-start gap-2 sm:items-center sm:gap-3",children:[L&&e.jsx("input",{type:"checkbox",checked:R,onChange:L,className:"mt-1 sm:mt-0 h-4 w-4 shrink-0 rounded border-black/20 text-primary focus:ring-primary dark:border-white/20 dark:bg-black"}),e.jsxs("div",{className:"flex shrink-0 flex-col",children:[e.jsx("button",{onClick:u,disabled:d,className:`p-0.5 rounded ${d?"text-text-muted/30 cursor-not-allowed":"hover:bg-sidebar text-text-muted hover:text-primary"}`,children:e.jsx("span",{className:"material-symbols-outlined text-sm",children:"keyboard_arrow_up"})}),e.jsx("button",{onClick:f,disabled:x,className:`p-0.5 rounded ${x?"text-text-muted/30 cursor-not-allowed":"hover:bg-sidebar text-text-muted hover:text-primary"}`,children:e.jsx("span",{className:"material-symbols-outlined text-sm",children:"keyboard_arrow_down"})})]}),e.jsx("span",{className:"material-symbols-outlined shrink-0 text-base text-text-muted",children:ne}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:Q}),e.jsxs("div",{className:"mt-1 flex min-w-0 flex-wrap items-center gap-1.5 sm:gap-2",children:[e.jsx(Ue,{variant:be(),size:"sm",dot:!0,children:n.isActive===!1?"disabled":W||"Unknown"}),e.jsx(Ue,{variant:"default",size:"sm",children:se}),g&&e.jsx(Ue,{variant:y,size:"sm",children:"Proxy"}),oe&&n.isActive!==!1&&e.jsx(rs,{until:fe}),n.lastError&&n.isActive!==!1&&e.jsx("span",{className:"max-w-full truncate text-xs text-red-500 sm:max-w-[300px]",title:n.lastError,children:n.lastError}),e.jsxs("span",{className:"text-xs text-text-muted",children:["#",n.priority]}),n.globalPriority&&e.jsxs("span",{className:"text-xs text-text-muted",children:["Auto: ",n.globalPriority]}),ye()&&e.jsx(Ue,{variant:ke(),size:"sm",children:ye()})]}),g&&e.jsxs("div",{className:"mt-1 flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"max-w-full truncate text-[11px] text-text-muted sm:max-w-[420px]",title:_,children:_}),z&&e.jsx("code",{className:"max-w-full truncate rounded bg-black/5 px-1 py-0.5 font-mono text-[10px] text-text-muted dark:bg-white/5 sm:max-w-[260px]",children:z}),ee&&e.jsxs("span",{className:"max-w-full truncate text-[11px] text-text-muted sm:max-w-[320px]",title:ee,children:["no_proxy: ",ee]})]})]})]}),e.jsxs("div",{className:"flex w-full items-center justify-between gap-2 sm:w-auto sm:justify-end",children:[e.jsxs("div",{className:"grid flex-1 grid-cols-3 gap-1 sm:flex sm:flex-none",children:[(c||[]).length>0&&e.jsxs("div",{className:"relative",ref:E,children:[e.jsxs("button",{onClick:()=>F(T=>!T),className:`flex w-full flex-col items-center rounded px-2 py-1 transition-colors hover:bg-black/5 dark:hover:bg-white/5 ${g?"text-primary":"text-text-muted hover:text-primary"}`,disabled:J,children:[e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:J?"progress_activity":"lan"}),e.jsx("span",{className:"text-[10px] leading-tight",children:"Proxy"})]}),U&&e.jsxs("div",{className:"absolute right-0 top-full z-50 mt-1 max-w-[78vw] min-w-[160px] rounded-lg border border-border bg-bg py-1 shadow-lg",children:[e.jsx("button",{onClick:()=>$("__none__"),className:`w-full text-left px-3 py-1.5 text-sm hover:bg-black/5 dark:hover:bg-white/5 ${A?"text-text-main":"text-primary font-medium"}`,children:"None"}),(c||[]).map(T=>e.jsx("button",{onClick:()=>$(T.id),className:`w-full text-left px-3 py-1.5 text-sm hover:bg-black/5 dark:hover:bg-white/5 ${A===T.id?"text-primary font-medium":"text-text-main"}`,children:T.name},T.id))]})]}),e.jsxs("button",{onClick:b,className:"flex flex-col items-center rounded px-2 py-1 text-text-muted hover:bg-black/5 hover:text-primary dark:hover:bg-white/5",children:[e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"edit"}),e.jsx("span",{className:"text-[10px] leading-tight",children:"Edit"})]}),e.jsxs("button",{onClick:S,className:"flex flex-col items-center rounded px-2 py-1 text-red-500 hover:bg-red-500/10",children:[e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"delete"}),e.jsx("span",{className:"text-[10px] leading-tight",children:"Delete"})]})]}),e.jsx(st,{size:"sm",checked:n.isActive??!0,onChange:h,title:n.isActive??!0?"Disable connection":"Enable connection"})]})]})}is.propTypes={connection:l.shape({id:l.string,name:l.string,email:l.string,displayName:l.string,modelLockUntil:l.string,testStatus:l.string,isActive:l.bool,lastError:l.string,priority:l.number,globalPriority:l.number}).isRequired,proxyPools:l.arrayOf(l.shape({id:l.string,name:l.string,proxyUrl:l.string,noProxy:l.string,isActive:l.bool})),isOAuth:l.bool.isRequired,isFirst:l.bool.isRequired,isLast:l.bool.isRequired,onMoveUp:l.func.isRequired,onMoveDown:l.func.isRequired,onToggleActive:l.func.isRequired,onUpdateProxy:l.func,onEdit:l.func.isRequired,onDelete:l.func.isRequired,oneByOneStatus:l.shape({state:l.string,error:l.string}),isSelected:l.bool,onSelect:l.func};const ra=`name1|sk-key1
|
|
2
|
+
name2|sk-key2
|
|
3
|
+
sk-key-only-auto-named`;function ns({isOpen:n,provider:c,providerName:a,isCompatible:d,isAnthropic:x,authType:u,authHint:f,website:h,proxyPools:o,error:b,onSave:S,onBulkDone:C,onClose:R}){var ge,me,Ce,T,le;const L="__none__",U=c==="ollama-local",F=u==="cookie",J=c==="xai"&&!F,X=F?"Cookie Value":"API Key",E=F?c==="grok-web"?"sso=xxxxx... or just the raw value":"eyJhbGciOi...":J?"xai-...":"",Z=c==="azure",A=c==="cloudflare-ai",O=((me=(ge=Ve)==null?void 0:ge[c])==null?void 0:me.regions)||null,P=((T=(Ce=Ve)==null?void 0:Ce[c])==null?void 0:T.defaultRegion)||((le=O==null?void 0:O[0])==null?void 0:le.id)||"",[g,_]=i.useState({name:"",apiKey:"",email:"",defaultModel:"",priority:1,proxyPoolId:L,ollamaHostUrl:""}),[z,ee]=i.useState({azureEndpoint:"",apiVersion:"2024-10-01-preview",deployment:"",organization:""}),[y,$]=i.useState({accountId:""}),[B,te]=i.useState(P),[ie,ne]=i.useState(!1),[se,K]=i.useState(null),[Q,oe]=i.useState(!1),[ue,fe]=i.useState("single"),[W,be]=i.useState(""),[ke,ye]=i.useState(null),pe=()=>{if(U&&g.ollamaHostUrl.trim())return{baseUrl:g.ollamaHostUrl.trim()};if(Z)return{azureEndpoint:z.azureEndpoint,apiVersion:z.apiVersion,deployment:z.deployment,organization:z.organization};if(A)return{accountId:y.accountId};if(O&&B)return{region:B}},we=async()=>{ne(!0);try{const Y=await(await fetch("/api/providers/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:c,apiKey:g.apiKey,providerSpecificData:pe()})})).json();K(Y.valid?"success":"failed")}catch{K("failed")}finally{ne(!1)}},Ae=async()=>{if(c&&!(!U&&!g.apiKey)&&!(!U&&!g.name)&&!(d&&!g.defaultModel.trim())){oe(!0);try{let v=!1;try{ne(!0),K(null),v=!!(await(await fetch("/api/providers/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:c,apiKey:g.apiKey,providerSpecificData:pe()})})).json()).valid,K(v?"success":"failed")}catch{K("failed")}finally{ne(!1)}await S({name:g.name||(U?"Ollama Local":""),apiKey:g.apiKey,email:c==="codebuddy"?g.email:void 0,defaultModel:d?g.defaultModel.trim():void 0,priority:g.priority,proxyPoolId:g.proxyPoolId===L?null:g.proxyPoolId,testStatus:v?"active":"unknown",providerSpecificData:pe()})}finally{oe(!1)}}},Me=async()=>{const v=W.split(`
|
|
4
|
+
`).map(s=>s.trim()).filter(Boolean);if(!v.length)return;oe(!0),ye(null);let Y=0,Re=0;for(let s=0;s<v.length;s++){const m=v[s];let k="",G="",xe="";if(c==="codebuddy"){const q=m.includes("|")?m.split("|"):m.split(":");q.length>=2?q.length===3?(xe=q[0].trim(),G=q[1].trim(),k=q[2].trim()):(G=q[0].trim(),k=q[1].trim(),xe=G):(k=q[0].trim(),xe=`Key ${s+1}`)}else{const q=m.split("|");k=q.length>=2?q.slice(1).join("|").trim():q[0].trim(),xe=`${q.length>=2?q[0].trim():"Key"} ${s+1}`}try{(await fetch("/api/providers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:c,apiKey:k,email:G||void 0,name:xe,priority:1,testStatus:"unknown"})})).ok?Y++:Re++}catch{Re++}}oe(!1),ye({success:Y,failed:Re}),Y>0&&C&&C()};return c?e.jsx(tt,{isOpen:n,title:`Add ${a||c} ${X}`,onClose:R,children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(N,{size:"sm",variant:ue==="single"?"primary":"ghost",onClick:()=>{fe("single"),ye(null)},children:"Single"}),e.jsx(N,{size:"sm",variant:ue==="bulk"?"primary":"ghost",onClick:()=>{fe("bulk"),ye(null)},children:"Bulk Add"})]}),ue==="bulk"&&e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx("p",{className:"text-xs text-text-muted",children:c==="codebuddy"?e.jsxs(e.Fragment,{children:["One key per line. Format: ",e.jsx("code",{children:"email:apiKey"})," or ",e.jsx("code",{children:"name|email|apiKey"}),"."]}):e.jsxs(e.Fragment,{children:["One key per line. Format: ",e.jsx("code",{children:"name|apiKey"})," or just ",e.jsx("code",{children:"apiKey"})," (auto-named by index)."]})}),e.jsx("textarea",{className:"w-full rounded border border-accent/30 bg-sidebar p-2 text-sm font-mono resize-y min-h-[140px] focus:outline-none focus:ring-1 focus:ring-primary",placeholder:ra,value:W,onChange:v=>be(v.target.value)}),ke&&e.jsxs("div",{className:`text-sm font-medium ${ke.failed>0?"text-yellow-400":"text-green-400"}`,children:["✓ ",ke.success," added",ke.failed>0?`, ✗ ${ke.failed} failed`:""]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(N,{onClick:Me,fullWidth:!0,disabled:Q||!W.trim(),children:Q?"Adding...":"Add All Keys"}),e.jsx(N,{onClick:R,variant:"ghost",fullWidth:!0,children:"Cancel"})]})]}),ue==="single"&&e.jsxs(e.Fragment,{children:[c==="codebuddy"&&e.jsx(ce,{label:"Email / Account ID",value:g.email,onChange:v=>_({...g,email:v.target.value}),placeholder:"your-codebuddy-email@example.com"}),e.jsx(ce,{label:"Name",value:g.name,onChange:v=>_({...g,name:v.target.value}),placeholder:U?"Ollama Local":"Production Key"}),U&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ce,{label:"Ollama Host URL",value:g.ollamaHostUrl,onChange:v=>_({...g,ollamaHostUrl:v.target.value}),placeholder:"http://localhost:11434",className:"flex-1"}),e.jsx("div",{className:"pt-6",children:e.jsx(N,{onClick:we,disabled:ie||Q,variant:"secondary",children:ie?"Checking...":"Check"})})]}),!U&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ce,{label:X,type:F?"text":"password",value:g.apiKey,onChange:v=>_({...g,apiKey:v.target.value}),placeholder:E,className:"flex-1"}),e.jsx("div",{className:"pt-6",children:e.jsx(N,{onClick:we,disabled:!g.apiKey||ie||Q,variant:"secondary",children:ie?"Checking...":"Check"})})]}),J&&e.jsx("p",{className:"text-xs text-text-muted",children:"Use a direct xAI API key from console.x.ai. This is separate from Grok Build OAuth."}),F&&f&&e.jsxs("p",{className:"text-xs text-text-muted",children:[f,h&&e.jsxs(e.Fragment,{children:[" ",e.jsxs("a",{href:h,target:"_blank",rel:"noopener noreferrer",className:"text-primary underline",children:["Open ",h.replace(/^https?:\/\//,"")]})]})]}),O&&e.jsx(yt,{label:"Region",value:B,onChange:v=>te(v.target.value),options:O.map(v=>({value:v.id,label:v.label}))}),d&&e.jsx(ce,{label:"Default Model",value:g.defaultModel,onChange:v=>_({...g,defaultModel:v.target.value}),placeholder:x?"claude-3-5-sonnet-latest":"gpt-4o-mini"}),U&&e.jsxs("p",{className:"text-xs text-text-muted",children:["Leave blank to use ",e.jsx("code",{children:"http://localhost:11434"}),". For remote Ollama, enter the full host URL (e.g. ",e.jsx("code",{children:"http://192.168.1.10:11434"}),")."]}),se&&e.jsx(Ue,{variant:se==="success"?"success":"error",children:se==="success"?"Valid":"Invalid"}),b&&e.jsx("p",{className:"text-xs text-red-500 break-words",children:b}),d&&e.jsx("p",{className:"text-xs text-text-muted",children:"Enter the model ID exactly as your compatible endpoint expects it. This model will be saved as the connection default."}),A&&e.jsxs("div",{className:"bg-sidebar/50 p-4 rounded-lg border border-accent/20",children:[e.jsx("h3",{className:"font-semibold mb-3 text-sm",children:"Cloudflare Workers AI"}),e.jsx(ce,{label:"Account ID",value:y.accountId,onChange:v=>$({...y,accountId:v.target.value}),placeholder:"abc123def456..."}),e.jsxs("p",{className:"text-xs text-text-muted mt-2",children:["Find your Account ID in the right sidebar of ",e.jsx("a",{href:"https://dash.cloudflare.com",target:"_blank",rel:"noopener noreferrer",className:"text-primary underline",children:"dash.cloudflare.com"})]})]}),Z&&e.jsxs("div",{className:"bg-sidebar/50 p-4 rounded-lg border border-accent/20",children:[e.jsx("h3",{className:"font-semibold mb-3 text-sm",children:"Azure OpenAI Configuration"}),e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx(ce,{label:"Azure Endpoint",value:z.azureEndpoint,onChange:v=>ee({...z,azureEndpoint:v.target.value}),placeholder:"https://your-resource.openai.azure.com"}),e.jsx(ce,{label:"Deployment Name",value:z.deployment,onChange:v=>ee({...z,deployment:v.target.value}),placeholder:"gpt-4"}),e.jsx(ce,{label:"API Version",value:z.apiVersion,onChange:v=>ee({...z,apiVersion:v.target.value}),placeholder:"2024-10-01-preview"}),e.jsx(ce,{label:"Organization",value:z.organization,onChange:v=>ee({...z,organization:v.target.value}),placeholder:"Organization ID"})]})]}),e.jsx(ce,{label:"Priority",type:"number",value:g.priority,onChange:v=>_({...g,priority:Number.parseInt(v.target.value)||1})}),e.jsx(yt,{label:"Proxy Pool",value:g.proxyPoolId,onChange:v=>_({...g,proxyPoolId:v.target.value}),options:[{value:L,label:"None"},...(o||[]).map(v=>({value:v.id,label:v.name}))],placeholder:"None"}),(o||[]).length===0&&e.jsx("p",{className:"text-xs text-text-muted",children:"No active proxy pools available. Create one in Proxy Pools page first."}),e.jsx("p",{className:"text-xs text-text-muted",children:"Legacy manual proxy fields are still accepted by API for backward compatibility."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(N,{onClick:Ae,fullWidth:!0,disabled:Q||!U&&(!g.name||!g.apiKey)||d&&!g.defaultModel.trim()||Z&&(!z.azureEndpoint||!z.deployment||!z.organization)||A&&!y.accountId,children:Q?"Saving...":"Save"}),e.jsx(N,{onClick:R,variant:"ghost",fullWidth:!0,children:"Cancel"})]})]})]})}):null}ns.propTypes={isOpen:l.bool.isRequired,provider:l.string,providerName:l.string,isCompatible:l.bool,isAnthropic:l.bool,authType:l.string,authHint:l.string,website:l.string,proxyPools:l.arrayOf(l.shape({id:l.string,name:l.string})),error:l.string,onSave:l.func.isRequired,onBulkDone:l.func,onClose:l.func.isRequired};function os({isOpen:n,node:c,onSave:a,onClose:d,isAnthropic:x}){const[u,f]=i.useState({name:"",prefix:"",apiType:"chat",baseUrl:"https://api.openai.com/v1"}),[h,o]=i.useState(!1),[b,S]=i.useState(""),[C,R]=i.useState(""),[L,U]=i.useState(!1),[F,J]=i.useState(null);i.useEffect(()=>{c&&f({name:c.name||"",prefix:c.prefix||"",apiType:c.apiType||"chat",baseUrl:c.baseUrl||(x?"https://api.anthropic.com/v1":"https://api.openai.com/v1")})},[c,x]);const X=[{value:"chat",label:"Chat Completions"},{value:"responses",label:"Responses API"}],E=async()=>{if(!(!u.name.trim()||!u.prefix.trim()||!u.baseUrl.trim())){o(!0);try{const A={name:u.name,prefix:u.prefix,baseUrl:u.baseUrl};x||(A.apiType=u.apiType),await a(A)}finally{o(!1)}}},Z=async()=>{U(!0);try{const O=await(await fetch("/api/provider-nodes/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({baseUrl:u.baseUrl,apiKey:b,type:x?"anthropic-compatible":"openai-compatible",modelId:C.trim()||void 0})})).json();J(O.valid?"success":"failed")}catch{J("failed")}finally{U(!1)}};return c?e.jsx(tt,{isOpen:n,title:`Edit ${x?"Anthropic":"OpenAI"} Compatible`,onClose:d,children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsx(ce,{label:"Name",value:u.name,onChange:A=>f({...u,name:A.target.value}),placeholder:`${x?"Anthropic":"OpenAI"} Compatible (Prod)`,hint:"Required. A friendly label for this node."}),e.jsx(ce,{label:"Prefix",value:u.prefix,onChange:A=>f({...u,prefix:A.target.value}),placeholder:x?"ac-prod":"oc-prod",hint:"Required. Used as the provider prefix for model IDs."}),!x&&e.jsx(yt,{label:"API Type",options:X,value:u.apiType,onChange:A=>f({...u,apiType:A.target.value})}),e.jsx(ce,{label:"Base URL",value:u.baseUrl,onChange:A=>f({...u,baseUrl:A.target.value}),placeholder:x?"https://api.anthropic.com/v1":"https://api.openai.com/v1",hint:`Use the base URL (ending in /v1) for your ${x?"Anthropic":"OpenAI"}-compatible API.`}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ce,{label:"API Key (for Check)",type:"password",value:b,onChange:A=>S(A.target.value),className:"flex-1"}),e.jsx("div",{className:"pt-6",children:e.jsx(N,{onClick:Z,disabled:!b||L||!u.baseUrl.trim(),variant:"secondary",children:L?"Checking...":"Check"})})]}),e.jsx(ce,{label:"Model ID (optional)",value:C,onChange:A=>R(A.target.value),placeholder:"e.g. my-model-id",hint:"If provider lacks /models endpoint, enter a model ID to validate via chat/completions instead."}),F&&e.jsx(Ue,{variant:F==="success"?"success":"error",children:F==="success"?"Valid":"Invalid"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(N,{onClick:E,fullWidth:!0,disabled:!u.name.trim()||!u.prefix.trim()||!u.baseUrl.trim()||h,children:h?"Saving...":"Save"}),e.jsx(N,{onClick:d,variant:"ghost",fullWidth:!0,children:"Cancel"})]})]})}):null}os.propTypes={isOpen:l.bool.isRequired,node:l.shape({id:l.string,name:l.string,prefix:l.string,apiType:l.string,baseUrl:l.string}),onSave:l.func.isRequired,onClose:l.func.isRequired,isAnthropic:l.bool};const ia={llm:{label:"LLM / Chat",icon:"smart_toy",color:"text-blue-400"},image:{label:"Image Generation",icon:"brush",color:"text-purple-400"},video:{label:"Video Generation",icon:"movie",color:"text-orange-400"}};function ds({isOpen:n,providerAlias:c,providerDisplayAlias:a,allowedKinds:d,onSave:x,onClose:u}){const f=d!=null&&d.length?d:["llm"],h=f.includes("llm")?"llm":f[0],[o,b]=i.useState(""),[S,C]=i.useState(h),[R,L]=i.useState(null),[U,F]=i.useState(""),[J,X]=i.useState(!1);i.useEffect(()=>{n&&(b(""),L(null),F(""),C(h))},[n,h]);const E=P=>{const g=`${c}/`;return P.startsWith(g)?P.slice(g.length):P},Z=async()=>{const P=E(o.trim());if(P){L("testing"),F("");try{const _=await(await fetch("/api/models/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:`${c}/${P}`})})).json();L(_.ok?"ok":"error"),F(_.error||"")}catch(g){L("error"),F(g.message)}}},A=async()=>{const P=E(o.trim());if(!(!P||J)){X(!0);try{await x(P,S)}finally{X(!1)}}},O=f.length>1;return e.jsx(tt,{isOpen:n,onClose:u,title:"Add Custom Model",children:e.jsxs("div",{className:"flex flex-col gap-4",children:[O&&e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-2 block",children:"Model Type"}),e.jsx("div",{className:"flex gap-2",children:f.map(P=>{const g=ia[P]||{label:P,icon:"category",color:"text-text-muted"},_=S===P;return e.jsxs("button",{onClick:()=>C(P),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-lg border text-xs font-medium transition-all ${_?"border-primary bg-primary/10 text-primary":"border-border bg-sidebar text-text-muted hover:border-primary/40 hover:text-primary"}`,children:[e.jsx("span",{className:`material-symbols-outlined text-sm ${_?"text-primary":g.color}`,children:g.icon}),g.label]},P)})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-1.5 block",children:"Model ID"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{type:"text",value:o,onChange:P=>{b(P.target.value),L(null),F("")},onKeyDown:P=>P.key==="Enter"&&Z(),placeholder:S==="image"?"e.g. leo-seedream":S==="video"?"e.g. leo-kling-3":"e.g. claude-opus-4-5",className:"flex-1 px-3 py-2 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary",autoFocus:!0}),S==="llm"&&e.jsx(N,{variant:"secondary",icon:"science",loading:R==="testing",onClick:Z,disabled:!o.trim()||R==="testing",children:R==="testing"?"Testing...":"Test"})]}),e.jsxs("p",{className:"text-xs text-text-muted mt-1",children:["Will be registered as:"," ",e.jsxs("code",{className:"font-mono bg-sidebar px-1 rounded",children:[a,"/",E(o.trim())||"model-id"]})]})]}),R==="ok"&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-green-500",children:[e.jsx("span",{className:"material-symbols-outlined text-base",children:"check_circle"}),"Model is reachable"]}),R==="error"&&e.jsxs("div",{className:"flex items-start gap-2 text-sm text-red-500",children:[e.jsx("span",{className:"material-symbols-outlined text-base shrink-0",children:"cancel"}),e.jsx("span",{children:U||"Model not reachable"})]}),e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsx(N,{onClick:u,variant:"ghost",fullWidth:!0,size:"sm",children:"Cancel"}),e.jsx(N,{onClick:A,fullWidth:!0,size:"sm",disabled:!o.trim()||J,children:J?"Adding...":"Add Model"})]})]})})}ds.propTypes={isOpen:l.bool.isRequired,providerAlias:l.string.isRequired,providerDisplayAlias:l.string.isRequired,allowedKinds:l.arrayOf(l.string),onSave:l.func.isRequired,onClose:l.func.isRequired};const na=[{pattern:/kling.*o3|kling-o3/,caps:{startFrame:!0,endFrame:!1,imageReference:!0,videoReference:!0,defaultImageReferenceStrength:"MID",durations:[5,10],defaultDuration:5,defaultResolution:"1080p",defaultAspectRatio:"16:9"},label:"Kling O3"},{pattern:/kling.*3\./,caps:{startFrame:!0,endFrame:!1,durations:[5,10,12],defaultDuration:10,defaultResolution:"720p",defaultAspectRatio:"16:9"},label:"Kling 3.x"},{pattern:/kling/,caps:{startFrame:!0,endFrame:!1,durations:[5,10],defaultDuration:5,defaultResolution:"1080p",defaultAspectRatio:"16:9"},label:"Kling 2.x"},{pattern:/seedance.*lite/,caps:{startFrame:!0,endFrame:!1,durations:[4,8],defaultDuration:4,defaultResolution:"480p",defaultAspectRatio:"16:9"},label:"Seedance Lite"},{pattern:/seedance/,caps:{startFrame:!0,endFrame:!0,durations:[4,8,10],defaultDuration:8,defaultResolution:"720p",defaultAspectRatio:"16:9"},label:"Seedance"},{pattern:/veo-3\.1|veo.*3\.1/,caps:{startFrame:!0,endFrame:!1,durations:[4,6,8],defaultDuration:8,defaultResolution:"720p",defaultAspectRatio:"16:9"},label:"Veo 3.1"},{pattern:/veo/,caps:{startFrame:!0,endFrame:!1,durations:[8],defaultDuration:8,defaultResolution:"720p",defaultAspectRatio:"16:9"},label:"Veo 3"},{pattern:/sora/,caps:{startFrame:!1,endFrame:!1,durations:[4,8,12],defaultDuration:8,defaultResolution:"720p",defaultAspectRatio:"16:9"},label:"Sora"},{pattern:/hailuo/,caps:{startFrame:!0,endFrame:!1,durations:[6,10],defaultDuration:6,defaultResolution:"768p",defaultAspectRatio:"16:9"},label:"Hailuo"},{pattern:/ltx/,caps:{startFrame:!0,endFrame:!0,durations:[6,8,10],defaultDuration:6,defaultResolution:"1080p",defaultAspectRatio:"16:9"},label:"LTX"},{pattern:/motion/,caps:{startFrame:!0,endFrame:!1,durations:[5],defaultDuration:5,defaultResolution:"720p",defaultAspectRatio:"16:9"},label:"Motion"}],oa=[{pattern:/seedream.*4\.5/,caps:{apiVersion:"v2",resolutionTiers:{SMALL:null,MEDIUM:{base:2048},LARGE:{base:4096}},defaultTier:"MEDIUM",imageReference:!0,refMethod:"guidances",maxRefs:6,strengthSupported:!0,defaultStrength:"MID",supportsStyleIds:!0},label:"Seedream 4.5"},{pattern:/seedream/,caps:{apiVersion:"v2",resolutionTiers:{SMALL:{base:1024},MEDIUM:{base:2048},LARGE:{base:4096}},defaultTier:"MEDIUM",imageReference:!0,refMethod:"guidances",maxRefs:6,strengthSupported:!0,defaultStrength:"MID",supportsStyleIds:!0},label:"Seedream"},{pattern:/flux-dev/,caps:{apiVersion:"v1",resolutionTiers:{SMALL:null,MEDIUM:null,LARGE:null},defaultTier:null,imageReference:!0,refMethod:"controlnets",maxRefs:1,strengthSupported:!0,defaultStrength:"MID",preprocessorId:233},label:"Flux Dev"},{pattern:/flux/,caps:{apiVersion:"v2",resolutionTiers:{SMALL:null,MEDIUM:{base:1024},LARGE:null},defaultTier:"MEDIUM",imageReference:!0,refMethod:"guidances",maxRefs:4,strengthSupported:!0,defaultStrength:"MID"},label:"Flux"},{pattern:/phoenix/,caps:{apiVersion:"v1",resolutionTiers:{SMALL:null,MEDIUM:null,LARGE:null},defaultTier:null,imageReference:!0,refMethod:"controlnets",maxRefs:1,strengthSupported:!0,defaultStrength:"MID",preprocessorId:364,supportsContrast:!0,supportsUltra:!0},label:"Phoenix"},{pattern:/ideogram/,caps:{apiVersion:"v2",resolutionTiers:{SMALL:null,MEDIUM:{base:1024},LARGE:null},defaultTier:"MEDIUM",qualityOptions:["TURBO","BALANCED","QUALITY"],defaultQuality:"BALANCED",imageReference:!0,refMethod:"guidances",maxRefs:6,strengthSupported:!0,defaultStrength:"MID"},label:"Ideogram"},{pattern:/gpt.image/,caps:{apiVersion:"v2",resolutionTiers:{SMALL:{base:1024},MEDIUM:{base:2048},LARGE:{base:2880}},defaultTier:"MEDIUM",qualityOptions:["LOW","MEDIUM","HIGH"],defaultQuality:"MEDIUM",imageReference:!0,refMethod:"guidances",maxRefs:6,strengthSupported:!1},label:"GPT Image"},{pattern:/recraft/,caps:{apiVersion:"v2",resolutionTiers:{SMALL:null,MEDIUM:{base:2048},LARGE:null},defaultTier:"MEDIUM",imageReference:!0,refMethod:"guidances",maxRefs:6,strengthSupported:!0,defaultStrength:"MID"},label:"Recraft"}];function da(n,c,a,d){const x=[c,a,d].filter(Boolean).join(" ").toLowerCase(),u=n==="video"?na:oa;for(const f of u)if(f.pattern.test(x))return f;return null}const ca=[4,5,6,8,10,12,15,20],ua=["Auto","480p","720p","768p","1080p","4K"],pa=["auto","16:9","9:16","1:1","4:3"],es=["SMALL","MEDIUM","LARGE"],ts={id:"",name:"",uuid:"",type:"image",apiModelName:"",quality:"",isPublic:!0,promptEnhance:"OFF",dimensions:{},capabilities:{apiVersion:"v2",resolutionTiers:{SMALL:null,MEDIUM:{base:1024},LARGE:null},defaultTier:"MEDIUM",qualityOptions:null,defaultQuality:null,imageReference:!0,refMethod:"guidances",maxRefs:6,strengthSupported:!0,defaultStrength:"MID",supportsStyleIds:!1,supportsContrast:!1,supportsUltra:!1,preprocessorId:null,startFrame:!1,endFrame:!1,videoReference:!1,defaultImageReferenceStrength:"MID",durations:[5,10],defaultDuration:5,defaultResolution:"720p",defaultAspectRatio:"16:9"}};function ma(){var Y,Re;const[n,c]=i.useState("models"),[a,d]=i.useState(null),[x,u]=i.useState(!0),[f,h]=i.useState(!1),[o,b]=i.useState(null),[S,C]=i.useState("all"),[R,L]=i.useState(""),[U,F]=i.useState(null),[J,X]=i.useState(!1),[E,Z]=i.useState(JSON.parse(JSON.stringify(ts))),[A,O]=i.useState(!1),[P,g]=i.useState([]),[_,z]=i.useState("leonardo"),[ee,y]=i.useState(""),[$,B]=i.useState(""),[te,ie]=i.useState(!1),[ne,se]=i.useState(""),K=(s,m)=>{b({type:s,text:m}),setTimeout(()=>b(null),4e3)},Q=async()=>{try{const m=await(await fetch("/api/automation/leonardo")).json();m.ok&&d(m.config)}catch(s){K("error","Gagal memuat config: "+s.message)}finally{u(!1)}},oe=async()=>{try{const s=await fetch("/api/providers"),m=await s.json();s.ok&&g(m.connections||[])}catch(s){console.error(s)}};i.useEffect(()=>{Q(),oe()},[]),i.useEffect(()=>{if(A||!E.id)return;const s=da(E.type,E.id,E.name,E.apiModelName);s&&Z(m=>({...m,capabilities:{...m.capabilities,...s.caps}}))},[E.id,E.name,E.apiModelName,E.type,A]);const ue=async(s,m={})=>(await fetch("/api/automation/leonardo",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:s,...m})})).json(),fe=async()=>{h(!0);try{const s=await ue("import-defaults");s.ok?(K("success",`✓ ${s.added} model diimport (${s.imageAdded} image, ${s.videoAdded} video)`),await Q()):K("error",s.error)}finally{h(!1)}},W=async()=>{if(confirm("Hapus SEMUA model dari config? Tindakan ini tidak bisa di-undo.")){h(!0);try{const s=await ue("delete-all-models");s.ok?(K("success",`${s.deleted} model dihapus`),await Q()):K("error",s.error)}finally{h(!1)}}},be=async s=>{if(!confirm(`Hapus model "${s}"?`))return;const m=await ue("delete-model",{id:s});m.ok?(K("success",`Model "${s}" dihapus`),await Q()):K("error",m.error)},ke=async()=>{var m,k;const s={...E};if(!((m=s.id)!=null&&m.trim())||!((k=s.name)!=null&&k.trim()))return K("error","Model ID dan Name wajib diisi");s.id.startsWith("leo-")||(s.id=`leo-${s.id}`),h(!0);try{const G=await ue("add-model",{model:s});G.ok?(K("success",`Model "${s.id}" berhasil ditambahkan`),Z(JSON.parse(JSON.stringify(ts))),O(!1),X(!1),await Q()):K("error",G.error)}finally{h(!1)}},ye=async(s,m)=>{const k=await ue("update-model",{id:s,model:m});k.ok?(K("success","Model diperbarui"),F(null),await Q()):K("error",k.error)},pe=async()=>{h(!0);try{const{failThreshold:s,coolingMinutes:m,autoDisableThreshold:k,imageTimeoutMs:G,videoTimeoutMs:xe}=a,q=await ue("save-settings",{failThreshold:s,coolingMinutes:m,autoDisableThreshold:k,imageTimeoutMs:G,videoTimeoutMs:xe});q.ok?K("success","Settings disimpan"):K("error",q.error)}finally{h(!1)}},we=async s=>{if(s.preventDefault(),!ee.trim()||!$.trim())return alert("Label dan Cookie wajib diisi");ie(!0);try{const m=await fetch("/api/providers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:_,apiKey:$.trim(),name:ee.trim(),email:ee.trim(),priority:1})}),k=await m.json();m.ok?(y(""),B(""),se("Cookie ditambahkan!"),await oe(),setTimeout(()=>se(""),3e3)):alert(k.error||"Gagal menambahkan")}finally{ie(!1)}},Ae=async s=>{confirm("Hapus connection ini?")&&(await fetch(`/api/providers/${s}`,{method:"DELETE"}),await oe())},Me=async s=>{await fetch(`/api/providers/${s.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({isActive:!s.isActive})}),await oe()},ge=async s=>{se("Testing...");const k=await(await fetch(`/api/providers/${s}/test`,{method:"POST"})).json();se(k.valid?"✓ Valid":`⚠ ${k.error||"Test gagal"}`),await oe(),setTimeout(()=>se(""),5e3)},me=P.filter(s=>s.provider===_),Ce=((a==null?void 0:a.models)||[]).filter(s=>!(S!=="all"&&s.type!==S||R&&![s.id,s.name,s.apiModelName].join(" ").toLowerCase().includes(R.toLowerCase()))),T=Ce.filter(s=>s.type==="image"),le=Ce.filter(s=>s.type==="video"),v=(s,m,k)=>e.jsxs("button",{onClick:()=>c(s),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold transition-all ${n===s?"bg-primary/15 text-primary":"text-text-muted hover:text-text-main hover:bg-surface"}`,children:[e.jsx("span",{className:"material-symbols-outlined text-[15px]",children:m}),k]});return x?e.jsx(Ne,{children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(ta,{})})}):e.jsx(Ne,{children:e.jsxs("div",{className:"space-y-5",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx("img",{src:"/providers/leonardo.png",alt:"Leonardo",className:"size-5 rounded object-contain"}),"Leonardo Admin"]})}),o&&e.jsxs("div",{className:`px-4 py-2.5 rounded-lg text-sm font-medium flex items-center gap-2 ${o.type==="success"?"bg-green-500/10 text-green-400 border border-green-500/20":"bg-red-500/10 text-red-400 border border-red-500/20"}`,children:[e.jsx("span",{className:"material-symbols-outlined text-base",children:o.type==="success"?"check_circle":"cancel"}),o.text]}),e.jsxs("div",{className:"flex items-center gap-2",children:[v("models","category",`Models (${((Y=a==null?void 0:a.models)==null?void 0:Y.length)||0})`),v("cookies","cookie",`Cookies (${me.length})`),v("config","tune","Settings")]}),n==="models"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ne,{padding:"sm",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx("input",{type:"text",placeholder:"Search models...",value:R,onChange:s=>L(s.target.value),className:"flex-1 min-w-[180px] text-xs px-3 py-2 border border-border rounded-lg bg-background focus:outline-none focus:border-primary"}),e.jsxs("select",{value:S,onChange:s=>C(s.target.value),className:"text-xs px-3 py-2 border border-border rounded-lg bg-background focus:outline-none focus:border-primary",children:[e.jsx("option",{value:"all",children:"All Types"}),e.jsx("option",{value:"image",children:"Image"}),e.jsx("option",{value:"video",children:"Video"})]}),e.jsx(N,{size:"sm",variant:"secondary",icon:"download",onClick:fe,disabled:f,children:"Import Defaults"}),e.jsx(N,{size:"sm",variant:"primary",icon:"add",onClick:()=>{X(s=>!s),O(!1)},children:"Add Model"}),e.jsx(N,{size:"sm",variant:"danger",icon:"delete_sweep",onClick:W,disabled:f,children:"Delete All"})]})}),J&&e.jsxs(Ne,{padding:"md",className:"border border-primary/30",children:[e.jsxs("h3",{className:"text-sm font-bold mb-4 flex items-center gap-2",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px] text-primary",children:"add_circle"}),"Add New Model"]}),e.jsx(as,{model:E,onChange:(s,m)=>{Z(k=>s.includes(".")?ss(k,s,m):{...k,[s]:m})},onCapsTouched:()=>O(!0)}),e.jsxs("div",{className:"flex gap-2 mt-4",children:[e.jsx(N,{size:"sm",variant:"ghost",onClick:()=>X(!1),children:"Cancel"}),e.jsx(N,{size:"sm",variant:"primary",onClick:ke,disabled:f,children:f?"Saving...":"+ Add Model"})]})]}),[{label:"Image Generation",icon:"brush",list:T},{label:"Video Generation",icon:"movie",list:le}].map(s=>s.list.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"material-symbols-outlined text-sm text-text-muted",children:s.icon}),e.jsx("span",{className:"text-xs font-bold text-text-muted uppercase tracking-wider",children:s.label}),e.jsx("span",{className:"text-[10px] text-text-muted/60 bg-sidebar px-1.5 py-0.5 rounded-full",children:s.list.length}),e.jsx("div",{className:"flex-1 h-px bg-border/40"})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-3",children:s.list.map(m=>{var k,G,xe,q;return e.jsxs("div",{className:"group relative rounded-xl border border-border bg-card hover:border-primary/30 transition-all p-3 flex flex-col gap-2",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-mono text-xs font-bold text-text-main truncate",title:m.id,children:m.id}),e.jsx("p",{className:"text-[11px] text-text-muted truncate",title:m.name,children:m.name})]}),e.jsxs("div",{className:"flex gap-1 shrink-0 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx("button",{onClick:()=>F(JSON.parse(JSON.stringify(m))),className:"p-1 rounded-lg hover:bg-primary/10 text-text-muted hover:text-primary transition-colors",title:"Edit model",children:e.jsx("span",{className:"material-symbols-outlined text-[15px]",children:"edit"})}),e.jsx("button",{onClick:()=>be(m.id),className:"p-1 rounded-lg hover:bg-red-500/10 text-text-muted hover:text-red-400 transition-colors",title:"Delete model",children:e.jsx("span",{className:"material-symbols-outlined text-[15px]",children:"delete"})})]})]}),m.apiModelName&&e.jsx("p",{className:"text-[10px] font-mono bg-sidebar px-2 py-0.5 rounded text-text-muted truncate",title:m.apiModelName,children:m.apiModelName}),e.jsxs("div",{className:"flex flex-wrap gap-1.5 mt-auto",children:[e.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded font-medium ${((k=m.capabilities)==null?void 0:k.apiVersion)==="v1"?"bg-orange-500/10 text-orange-400":"bg-blue-500/10 text-blue-400"}`,children:m.type==="image"?((G=m.capabilities)==null?void 0:G.apiVersion)||"v2":"video"}),e.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded ${m.isPublic?"bg-green-500/10 text-green-400":"bg-gray-500/10 text-gray-400"}`,children:m.isPublic?"public":"hidden"}),e.jsxs("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-sidebar text-text-muted",children:["✨ ",m.promptEnhance||"OFF"]}),m.type==="video"&&((xe=m.capabilities)==null?void 0:xe.durations)&&e.jsxs("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-sidebar text-text-muted",children:[m.capabilities.durations.join("/"),"s"]}),m.type==="video"&&((q=m.capabilities)==null?void 0:q.defaultResolution)&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-sidebar text-text-muted",children:m.capabilities.defaultResolution})]})]},m.id)})})]},s.label)),Ce.length===0&&e.jsx("div",{className:"rounded-xl border border-border bg-card p-8",children:e.jsx("p",{className:"text-center text-text-muted text-sm",children:((Re=a==null?void 0:a.models)==null?void 0:Re.length)===0?'Belum ada model. Klik "Import Defaults" untuk mengisi dari providerModels.js.':"Tidak ada model yang cocok dengan filter."})})]}),n==="cookies"&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-5",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs(Ne,{padding:"md",className:"space-y-3",children:[e.jsxs("h3",{className:"text-sm font-bold flex items-center gap-2",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"filter_list"}),"Filter Provider"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("img",{src:`/providers/${_}.png`,alt:_,className:"size-5 rounded object-contain",onError:s=>{s.target.style.display="none"}}),e.jsxs("select",{value:_,onChange:s=>z(s.target.value),className:"flex-1 text-xs px-3 py-2 border border-border rounded-lg bg-background focus:outline-none focus:border-primary",children:[e.jsx("option",{value:"leonardo",children:"Leonardo AI"}),e.jsx("option",{value:"grok-web",children:"Grok Web"}),e.jsx("option",{value:"perplexity-web",children:"Perplexity Web"})]})]}),e.jsxs("p",{className:"text-xs text-text-muted",children:[me.length," connections untuk ",_]})]}),e.jsxs(Ne,{padding:"md",className:"space-y-3",children:[e.jsxs("h3",{className:"text-sm font-bold flex items-center gap-2",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"add_circle"}),"Add Cookie"]}),e.jsxs("form",{onSubmit:we,className:"space-y-2.5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] text-text-muted block mb-1",children:"Label / Email"}),e.jsx("input",{type:"text",placeholder:"account@gmail.com",value:ee,onChange:s=>y(s.target.value),className:"w-full text-xs px-3 py-2 border border-border rounded-lg bg-background focus:outline-none focus:border-primary",required:!0})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] text-text-muted block mb-1",children:"Cookie Value"}),e.jsx("textarea",{placeholder:"Paste cookie string...",value:$,onChange:s=>B(s.target.value),rows:4,className:"w-full text-xs font-mono px-3 py-2 border border-border rounded-lg bg-background focus:outline-none focus:border-primary resize-y",required:!0})]}),e.jsx(N,{type:"submit",variant:"primary",size:"sm",fullWidth:!0,disabled:te,children:te?"Adding...":"Add Cookie Connection"})]}),ne&&e.jsx("p",{className:"text-xs text-primary italic",children:ne})]})]}),e.jsx("div",{className:"lg:col-span-2",children:e.jsxs(Ne,{padding:"md",className:"space-y-3",children:[e.jsxs("h3",{className:"text-sm font-bold flex items-center gap-2",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"list_alt"}),"Cookie Pool — ",_]}),e.jsx("div",{className:"border border-border rounded-xl overflow-hidden",children:e.jsxs("table",{className:"w-full text-xs text-left",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-sidebar text-text-muted border-b border-border font-semibold",children:[e.jsx("th",{className:"px-3 py-2.5",children:"Label"}),e.jsx("th",{className:"px-3 py-2.5",children:"Status"}),e.jsx("th",{className:"px-3 py-2.5",children:"Balance"}),e.jsx("th",{className:"px-3 py-2.5",children:"Fails"}),e.jsx("th",{className:"px-3 py-2.5",children:"Active"}),e.jsx("th",{className:"px-3 py-2.5 text-right",children:"Actions"})]})}),e.jsx("tbody",{children:me.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"px-3 py-8 text-center text-text-muted",children:"Tidak ada cookie untuk provider ini"})}):me.map(s=>{var m;return e.jsxs("tr",{className:"border-b border-border hover:bg-surface/50 transition-colors",children:[e.jsxs("td",{className:"px-3 py-2.5",children:[e.jsx("div",{className:"font-semibold text-text-main",children:s.name||s.email||"—"}),e.jsxs("div",{className:"text-[10px] text-text-muted font-mono",children:[(m=s.id)==null?void 0:m.slice(0,8),"..."]})]}),e.jsx("td",{className:"px-3 py-2.5",children:e.jsx(Ue,{variant:s.testStatus==="active"||s.testStatus==="ok"?"success":s.testStatus==="error"?"danger":"secondary",children:s.testStatus||"unknown"})}),e.jsx("td",{className:"px-3 py-2.5 text-text-main font-semibold",children:s.last_balance!==void 0&&s.last_balance!==null?`${s.last_balance} tok`:"—"}),e.jsx("td",{className:"px-3 py-2.5",children:e.jsx("span",{className:s.fail_count>0?"text-red-400":"text-text-muted",children:s.fail_count||0})}),e.jsx("td",{className:"px-3 py-2.5",children:e.jsx(st,{checked:s.isActive,onChange:()=>Me(s)})}),e.jsx("td",{className:"px-3 py-2.5 text-right",children:e.jsxs("div",{className:"flex gap-1.5 justify-end",children:[e.jsx(N,{size:"xs",variant:"secondary",onClick:()=>ge(s.id),children:"Test"}),e.jsx(N,{size:"xs",variant:"danger",onClick:()=>Ae(s.id),children:"Del"})]})})]},s.id)})})]})})]})})]}),n==="config"&&a&&e.jsxs(Ne,{padding:"md",className:"space-y-4 max-w-xl",children:[e.jsx("h3",{className:"text-sm font-bold",children:"Global Settings"}),[{key:"failThreshold",label:"Fail Threshold",help:"Berapa kali gagal sebelum masuk cooling"},{key:"coolingMinutes",label:"Cooling (menit)",help:"Durasi cooling period setelah fail threshold"},{key:"autoDisableThreshold",label:"Auto-disable Threshold",help:"Total failures sebelum cookie dinonaktifkan"},{key:"imageTimeoutMs",label:"Image Timeout (ms)",help:"Timeout generasi image"},{key:"videoTimeoutMs",label:"Video Timeout (ms)",help:"Timeout generasi video"}].map(({key:s,label:m,help:k})=>e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold block mb-1",children:m}),e.jsx("input",{type:"number",value:a[s]||0,onChange:G=>d(xe=>({...xe,[s]:Number(G.target.value)})),className:"w-full text-xs px-3 py-2 border border-border rounded-lg bg-background focus:outline-none focus:border-primary"}),e.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:k})]},s)),e.jsx(N,{variant:"primary",size:"sm",onClick:pe,disabled:f,children:f?"Saving...":"Save Settings"})]}),U&&e.jsx("div",{className:"fixed inset-0 z-50 bg-black/90 backdrop-blur-sm flex items-center justify-center p-4",onClick:s=>s.target===s.currentTarget&&F(null),children:e.jsxs("div",{className:"bg-background border border-border rounded-2xl shadow-2xl w-full max-w-2xl max-h-[90vh] overflow-y-auto p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{className:"font-bold text-base",children:["Edit Model — ",U.id]}),e.jsx("button",{onClick:()=>F(null),className:"text-text-muted hover:text-text-main",children:e.jsx("span",{className:"material-symbols-outlined",children:"close"})})]}),e.jsx(as,{model:U,onChange:(s,m)=>{F(k=>s.includes(".")?ss(k,s,m):{...k,[s]:m})},onCapsTouched:()=>{}}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(N,{size:"sm",variant:"ghost",onClick:()=>F(null),children:"Cancel"}),e.jsx(N,{size:"sm",variant:"primary",onClick:()=>ye(U.id,U),disabled:f,children:f?"Saving...":"Save Changes"})]})]})})]})})}function ss(n,c,a){const d=c.split("."),x={...n};let u=x;for(let f=0;f<d.length-1;f++)u[d[f]]={...u[d[f]]},u=u[d[f]];return u[d[d.length-1]]=a,x}function as({model:n,onChange:c,onCapsTouched:a}){const d=n.type==="video",x=n.capabilities||{},u=(o,b,S)=>e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] font-semibold text-text-muted block mb-1",children:o}),S]},b),f=(o,b="")=>e.jsx("input",{type:"text",value:n[o]||"",placeholder:b,onChange:S=>c(o,S.target.value),className:"w-full text-xs px-3 py-2 border border-border rounded-lg bg-background focus:outline-none focus:border-primary"}),h=(o,b)=>e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:!!x[o],onChange:S=>{a(),c(`capabilities.${o}`,S.target.checked)},className:"w-3.5 h-3.5 accent-primary"}),e.jsx("span",{className:"text-xs text-text-muted",children:b})]});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[u("Model ID (tanpa prefix leo-)","id",f("id","e.g. kling-3")),u("Display Name","name",f("name","e.g. Kling 3.0")),u("UUID (kosong untuk native v2)","uuid",f("uuid","xxxxxxxx-xxxx-xxxx...")),u("API Model Name","apiModelName",f("apiModelName","e.g. kling-3.0"))]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[u("Type","type",e.jsxs("select",{value:n.type||"image",onChange:o=>c("type",o.target.value),className:"w-full text-xs px-3 py-2 border border-border rounded-lg bg-background focus:outline-none focus:border-primary",children:[e.jsx("option",{value:"image",children:"Image"}),e.jsx("option",{value:"video",children:"Video"})]})),u("Prompt Enhance","promptEnhance",e.jsxs("select",{value:n.promptEnhance||"OFF",onChange:o=>c("promptEnhance",o.target.value),className:"w-full text-xs px-3 py-2 border border-border rounded-lg bg-background focus:outline-none focus:border-primary",children:[e.jsx("option",{value:"AUTO",children:"AUTO"}),e.jsx("option",{value:"ON",children:"ON"}),e.jsx("option",{value:"OFF",children:"OFF"})]})),u("Public","isPublic",e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx(st,{checked:!!n.isPublic,onChange:o=>c("isPublic",o)}),e.jsx("span",{className:"text-xs text-text-muted",children:n.isPublic?"Visible to users":"Hidden"})]}))]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-px flex-1 bg-border"}),e.jsx("span",{className:"text-[11px] font-bold text-text-muted uppercase tracking-wider",children:d?"Video Capabilities":"Image Capabilities"}),e.jsx("div",{className:"h-px flex-1 bg-border"})]}),d?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[u("Default Resolution","capabilities.defaultResolution",e.jsx("select",{value:x.defaultResolution||"720p",onChange:o=>{a(),c("capabilities.defaultResolution",o.target.value)},className:"w-full text-xs px-3 py-2 border border-border rounded-lg bg-background focus:outline-none focus:border-primary",children:ua.map(o=>e.jsx("option",{children:o},o))})),u("Default Aspect Ratio","capabilities.defaultAspectRatio",e.jsx("select",{value:x.defaultAspectRatio||"16:9",onChange:o=>{a(),c("capabilities.defaultAspectRatio",o.target.value)},className:"w-full text-xs px-3 py-2 border border-border rounded-lg bg-background focus:outline-none focus:border-primary",children:pa.map(o=>e.jsx("option",{children:o},o))}))]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] font-semibold text-text-muted block mb-2",children:"Supported Durations (seconds)"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:ca.map(o=>e.jsxs("label",{className:"flex items-center gap-1.5 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:(x.durations||[]).includes(o),onChange:b=>{a();const S=x.durations||[],C=b.target.checked?[...S,o].sort((R,L)=>R-L):S.filter(R=>R!==o);c("capabilities.durations",C),C.includes(x.defaultDuration)||c("capabilities.defaultDuration",C[0])},className:"w-3.5 h-3.5 accent-primary"}),e.jsxs("span",{className:"text-xs",children:[o,"s"]})]},o))})]}),(x.durations||[]).length>0&&u("Default Duration","capabilities.defaultDuration",e.jsx("select",{value:x.defaultDuration||"",onChange:o=>{a(),c("capabilities.defaultDuration",Number(o.target.value))},className:"w-full text-xs px-3 py-2 border border-border rounded-lg bg-background focus:outline-none focus:border-primary",children:(x.durations||[]).map(o=>e.jsxs("option",{value:o,children:[o,"s"]},o))})),e.jsxs("div",{className:"grid grid-cols-2 gap-x-4 gap-y-2 mt-1",children:[h("startFrame","Start Frame (first image)"),h("endFrame","End Frame (last image)"),h("imageReference","Image Reference (img2vid)"),h("videoReference","Video Reference")]}),x.imageReference&&u("Image Reference Strength","capabilities.defaultImageReferenceStrength",e.jsx("select",{value:x.defaultImageReferenceStrength||"MID",onChange:o=>{a(),c("capabilities.defaultImageReferenceStrength",o.target.value)},className:"w-full text-xs px-3 py-2 border border-border rounded-lg bg-background focus:outline-none focus:border-primary",children:["LOW","MID","HIGH"].map(o=>e.jsx("option",{children:o},o))}))]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[u("API Version","capabilities.apiVersion",e.jsxs("select",{value:x.apiVersion||"v2",onChange:o=>{a(),c("capabilities.apiVersion",o.target.value)},className:"w-full text-xs px-3 py-2 border border-border rounded-lg bg-background focus:outline-none focus:border-primary",children:[e.jsx("option",{value:"v2",children:"v2 (native)"}),e.jsx("option",{value:"v1",children:"v1 (legacy UUID)"})]})),u("Ref Method","capabilities.refMethod",e.jsxs("select",{value:x.refMethod||"guidances",onChange:o=>{a(),c("capabilities.refMethod",o.target.value)},className:"w-full text-xs px-3 py-2 border border-border rounded-lg bg-background focus:outline-none focus:border-primary",children:[e.jsx("option",{value:"guidances",children:"guidances (v2)"}),e.jsx("option",{value:"controlnets",children:"controlnets (v1)"})]}))]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] font-semibold text-text-muted block mb-2",children:"Resolution Tiers"}),e.jsx("div",{className:"space-y-2",children:es.map(o=>{var C;const b=(C=x.resolutionTiers)==null?void 0:C[o],S=!!b;return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("label",{className:"flex items-center gap-1.5 w-20 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:S,onChange:R=>{a();const L=x.resolutionTiers||{};c("capabilities.resolutionTiers",{...L,[o]:R.target.checked?{base:1024}:null})},className:"w-3.5 h-3.5 accent-primary"}),e.jsx("span",{className:"text-xs font-semibold",children:o})]}),S&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-[11px] text-text-muted",children:"base px:"}),e.jsx("input",{type:"number",value:(b==null?void 0:b.base)||1024,step:256,onChange:R=>{a();const L=x.resolutionTiers||{};c("capabilities.resolutionTiers",{...L,[o]:{base:Number(R.target.value)}})},className:"w-24 text-xs px-2 py-1 border border-border rounded-lg bg-background focus:outline-none focus:border-primary"})]})]},o)})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[u("Default Tier","capabilities.defaultTier",e.jsx("select",{value:x.defaultTier||"MEDIUM",onChange:o=>{a(),c("capabilities.defaultTier",o.target.value)},className:"w-full text-xs px-3 py-2 border border-border rounded-lg bg-background focus:outline-none focus:border-primary",children:es.map(o=>e.jsx("option",{children:o},o))})),u("Max Refs","capabilities.maxRefs",e.jsx("input",{type:"number",min:1,max:10,value:x.maxRefs||6,onChange:o=>{a(),c("capabilities.maxRefs",Number(o.target.value))},className:"w-full text-xs px-3 py-2 border border-border rounded-lg bg-background focus:outline-none focus:border-primary"}))]}),u("Quality Options (comma-separated, kosong = none)","capabilities.qualityOptions",e.jsx("input",{type:"text",value:(x.qualityOptions||[]).join(","),placeholder:"e.g. TURBO,BALANCED,QUALITY",onChange:o=>{a();const b=o.target.value?o.target.value.split(",").map(S=>S.trim()).filter(Boolean):null;c("capabilities.qualityOptions",b)},className:"w-full text-xs px-3 py-2 border border-border rounded-lg bg-background focus:outline-none focus:border-primary"})),u("Preprocessor ID (v1 only, kosong = none)","capabilities.preprocessorId",e.jsx("input",{type:"number",value:x.preprocessorId||"",placeholder:"e.g. 364",onChange:o=>{a(),c("capabilities.preprocessorId",o.target.value?Number(o.target.value):null)},className:"w-full text-xs px-3 py-2 border border-border rounded-lg bg-background focus:outline-none focus:border-primary"})),e.jsxs("div",{className:"grid grid-cols-2 gap-x-4 gap-y-2",children:[h("imageReference","Image Reference"),h("strengthSupported","Strength Supported"),h("supportsStyleIds","Supports Style IDs"),h("supportsContrast","Supports Contrast (v1)"),h("supportsUltra","Supports Ultra (v1)")]})]})]})}const xa=1e3;function ha(n){return new Promise(c=>setTimeout(c,n))}function ja(){var Lt,Ut,_t,Ft,Kt,zt,qt,Vt,Bt,Gt;const n=Gs(),c=Js(),a=n.id,[d,x]=i.useState([]),[u,f]=i.useState(!0),[h,o]=i.useState(null),[b,S]=i.useState([]),[C,R]=i.useState(!1),[L,U]=i.useState(!1),[F,J]=i.useState(!1),[X,E]=i.useState(""),[Z,A]=i.useState(!1),[O,P]=i.useState(!1),[g,_]=i.useState(!1),[z,ee]=i.useState(null),[y,$]=i.useState({}),[B,te]=i.useState(!1),[ie,ne]=i.useState({}),[se,K]=i.useState(""),[Q,oe]=i.useState(null),[ue,fe]=i.useState(!1),[W,be]=i.useState([]),[ke,ye]=i.useState("__none__"),[pe,we]=i.useState(!1),[Ae,Me]=i.useState(null),[ge,me]=i.useState(""),[Ce,T]=i.useState("auto"),[le,v]=i.useState([]),[Y,Re]=i.useState([]),[s,m]=i.useState([]),[k,G]=i.useState(null),[xe,q]=i.useState(!1),[$e,jt]=i.useState(!1),[Nt,at]=i.useState(!1),[lt,rt]=i.useState(null),[cs,Je]=i.useState({}),[_e,it]=i.useState(null),We=i.useRef(!1),[Be,kt]=i.useState(!1),[nt,us]=i.useState("overview"),{copied:ot,copy:dt}=_s(),wt="ag_risk_confirmed",Ct=()=>{R(!0)},ct=()=>{if(a==="antigravity"&&typeof window<"u"&&!(window.localStorage.getItem(wt)==="true")){q(!0);return}if(Fe){Ct();return}E(""),J(!0)},He=()=>{E(""),J(!0)},St=()=>{if(Fe){ct();return}He()},ps=()=>{if(typeof window<"u"&&window.localStorage.setItem(wt,"true"),q(!1),Fe){Ct();return}He()},j=h?{id:h.id,name:h.name||(h.type==="anthropic-compatible"?"Anthropic Compatible":"OpenAI Compatible"),color:h.type==="anthropic-compatible"?"#D97757":"#10A37F",textIcon:h.type==="anthropic-compatible"?"AC":"OC",apiType:h.apiType,baseUrl:h.baseUrl,type:h.type}:gt[a]||bt[a]||et[a]||Ht[a]||Fs[a],At=(j==null?void 0:j.authModes)||[],Fe=!!gt[a]||!!et[a]||At.includes("oauth"),ms=!!bt[a]||At.includes("apikey"),ut=!!((Lt=et[a])!=null&&Lt.noAuth),Le=Ks(a),pt=zs(a),Mt=qs(a),Te=Vs(a),he=Mt||Te,mt=!he&&Fe&&ms,xt=a==="xai"?"Grok Build OAuth":"OAuth",ht=a==="xai"?"xAI API Key":"API Key";(Ut=Ve[a])!=null&&Ut.thinkingConfig||Bs.extended;const ae=he?a:pt,Qe=he?(h==null?void 0:h.prefix)||a:pt,Ke=i.useCallback(async()=>{try{const t=await fetch(`/api/models/disabled?providerAlias=${encodeURIComponent(ae)}`,{cache:"no-store"}),r=await t.json();t.ok&&m(r.ids||[])}catch(t){console.log("Error fetching disabled models:",t)}},[ae]),xs=async t=>{try{(await fetch("/api/models/disabled",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerAlias:ae,ids:[t]})})).ok&&await Ke()}catch(r){console.log("Error disabling model:",r)}},hs=async t=>{try{(await fetch(`/api/models/disabled?providerAlias=${encodeURIComponent(ae)}&id=${encodeURIComponent(t)}`,{method:"DELETE"})).ok&&await Ke()}catch(r){console.log("Error enabling model:",r)}},fs=async t=>{t.length&&G({title:"Disable All Models",message:`Disable all ${t.length} model(s)?`,onConfirm:async()=>{G(null);try{(await fetch("/api/models/disabled",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerAlias:ae,ids:t})})).ok&&await Ke()}catch(r){console.log("Error disabling all models:",r)}}})},gs=async()=>{try{(await fetch(`/api/models/disabled?providerAlias=${encodeURIComponent(ae)}`,{method:"DELETE"})).ok&&await Ke()}catch(t){console.log("Error enabling all models:",t)}},Ye=i.useCallback(async()=>{try{const t=await fetch("/api/models/alias"),r=await t.json();t.ok&&$(r.aliases||{})}catch(t){console.log("Error fetching aliases:",t)}},[]);i.useEffect(()=>{a==="kilocode"&&fetch("/api/providers/kilo/free-models").then(t=>t.json()).then(t=>{var r;(r=t.models)!=null&&r.length&&Re(t.models)}).catch(()=>{})},[a]);const Se=i.useCallback(async()=>{try{const[t,r,p,M]=await Promise.all([fetch("/api/providers",{cache:"no-store"}),fetch("/api/provider-nodes",{cache:"no-store"}),fetch("/api/proxy-pools?isActive=true",{cache:"no-store"}),fetch("/api/settings",{cache:"no-store"})]),I=await t.json(),D=await r.json(),H=await p.json(),de=M.ok?await M.json():{};if(t.ok){const Ie=(I.connections||[]).filter(je=>je.provider===a);x(Ie)}p.ok&&S(H.proxyPools||[]);const ve=(de.providerStrategies||{})[a]||{};Me(ve.fallbackStrategy||null),me(ve.stickyRoundRobinLimit!=null?String(ve.stickyRoundRobinLimit):"1");const Oe=(de.providerThinking||{})[a]||{};if(T(Oe.mode||"auto"),r.ok){let Ie=(D.nodes||[]).find(je=>je.id===a)||null;if(!Ie&&he)for(let je=0;je<3;je+=1){await new Promise(qe=>setTimeout(qe,150));const ze=await fetch("/api/provider-nodes",{cache:"no-store"});if(!ze.ok)continue;if(Ie=((await ze.json()).nodes||[]).find(qe=>qe.id===a)||null,Ie)break}o(Ie)}}catch(t){console.log("Error fetching connections:",t)}finally{f(!1)}},[a,he]),bs=async t=>{try{const r=await fetch(`/api/provider-nodes/${a}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),p=await r.json();r.ok&&(o(p.node),await Se(),P(!1))}catch(r){console.log("Error updating provider node:",r)}},Rt=async(t,r)=>{try{const p=await fetch("/api/settings",{cache:"no-store"}),I=(p.ok?await p.json():{}).providerStrategies||{},D={};t&&(D.fallbackStrategy=t),t==="round-robin"&&r!==""&&(D.stickyRoundRobinLimit=Number(r)||3);const H={...I};Object.keys(D).length===0?delete H[a]:H[a]=D,await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerStrategies:H})})}catch(p){console.log("Error saving provider strategy:",p)}},ys=t=>{const r=t?"round-robin":null,p=t?ge||"1":ge;t&&!ge&&me("1"),Me(r),Rt(r,p)},vs=t=>{me(t),Rt("round-robin",t)};i.useEffect(()=>{Se(),Ye(),Ke()},[Se,Ye,Ke]),i.useEffect(()=>{var r;const t=(r=gt[a]||bt[a]||et[a]||Ht[a])==null?void 0:r.modelsFetcher;t&&aa(t).then(v)},[a]);const Ge=async(t,r,p=pt)=>{const M=`${p}/${t}`;try{const I=await fetch("/api/models/alias",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:M,alias:r})});if(I.ok)await Ye();else{const D=await I.json();alert(D.error||"Failed to set alias")}}catch(I){console.log("Error setting alias:",I)}},ft=async t=>{try{(await fetch(`/api/models/alias?alias=${encodeURIComponent(t)}`,{method:"DELETE"})).ok&&await Ye()}catch(r){console.log("Error deleting alias:",r)}},js=async()=>{if(Be)return;const t=d.find(r=>r.isActive!==!1);if(!t){alert(Ee("Please add an active Qoder connection first"));return}kt(!0);try{const r=await fetch(`/api/providers/${t.id}/models`),p=await r.json();if(!r.ok){alert(p.error||Ee("Failed to fetch models"));return}const M=p.models||[];if(M.length===0){alert(Ee("No models returned"));return}let I=0;for(const D of M){const H=D.id||D.name;if(!H)continue;const de=H.replace(/^qoder\//,""),ve=`${ae}/${de}`;if(Object.values(y).includes(ve))continue;const Oe=de;y[Oe]||(await Ge(de,Oe,ae),I+=1)}alert(I===0?Ee("All models already exist, no new models added"):Ee("Successfully added")+` ${I} `+Ee("models"))}catch(r){console.log("Error importing Qoder models:",r),alert(Ee("Error fetching models")+": "+r.message)}finally{kt(!1)}},Ns=async()=>{if($e||d.length===0)return;const t=Object.fromEntries(d.map(M=>[M.id,{state:"queued",error:null}]));We.current=!1,jt(!0),at(!1),rt(null),Je(t),it({total:d.length,completed:0,passed:0,failed:0,stopped:!1});let r=0,p=0;try{for(let M=0;M<d.length;M+=1){if(We.current){it({total:d.length,completed:M,passed:r,failed:p,stopped:!0});break}const I=d[M];rt(I.id),Je(D=>({...D,[I.id]:{state:"testing",error:null}}));try{const H=await(await fetch(`/api/providers/${I.id}/test`,{method:"POST"})).json(),de=!!H.valid;de?r+=1:p+=1,Je(ve=>({...ve,[I.id]:{state:de?"success":"failed",error:de?null:H.error||null}}))}catch(D){p+=1,Je(H=>({...H,[I.id]:{state:"failed",error:D.message||"Test failed"}}))}it({total:d.length,completed:M+1,passed:r,failed:p,stopped:!1}),M<d.length-1&&await ha(xa)}}finally{rt(null),jt(!1),at(!1),We.current=!1}},ks=()=>{$e&&(We.current=!0,at(!0))},ws=async t=>{G({title:"Delete Connection",message:"Delete this connection?",onConfirm:async()=>{G(null);try{(await fetch(`/api/providers/${t}`,{method:"DELETE"})).ok&&x(d.filter(p=>p.id!==t))}catch(r){console.log("Error deleting connection:",r)}}})},Xe=()=>{Se(),R(!1)},Cs=()=>{Se(),U(!1)},Ss=async t=>{E("");try{const r=await fetch("/api/providers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:a,...t})});let p=null;try{p=await r.json()}catch{p=null}if(r.ok){await Se(),J(!1);return}E((p==null?void 0:p.error)||"Failed to save connection")}catch(r){console.log("Error saving connection:",r),E("Failed to save connection")}},As=async t=>{try{(await fetch(`/api/providers/${z.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).ok&&(await Se(),A(!1))}catch(r){console.log("Error updating connection:",r)}},Ms=async(t,r)=>{try{(await fetch(`/api/providers/${t}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({isActive:r})})).ok&&x(M=>M.map(I=>I.id===t?{...I,isActive:r}:I))}catch(p){console.log("Error updating connection status:",p)}},Tt=async(t,r)=>{const p=[...d];[p[t],p[r]]=[p[r],p[t]],x(p);try{await Promise.all([fetch(`/api/providers/${p[t].id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({priority:t})}),fetch(`/api/providers/${p[r].id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({priority:r})})])}catch(M){console.log("Error swapping priority:",M),await Se()}},It=d.filter(t=>W.includes(t.id)),Dt=d.length>0&&W.length===d.length,Rs=t=>{be(r=>r.includes(t)?r.filter(p=>p!==t):[...r,t])},Ts=()=>{if(Dt){be([]);return}be(d.map(t=>t.id))},Is=()=>{be([]),ye("__none__")};i.useEffect(()=>{be(t=>t.filter(r=>d.some(p=>p.id===r)))},[d]),(()=>{if(It.length===0)return"";const t=new Set(It.map(r=>{var p;return((p=r.providerSpecificData)==null?void 0:p.proxyPoolId)||"__none__"}));if(t.size===1){const r=[...t][0];if(r==="__none__")return"All selected currently unbound";const p=b.find(M=>M.id===r);return`All selected currently bound to ${(p==null?void 0:p.name)||r}`}return"Selected connections have mixed proxy bindings"})();const Et=()=>{pe||_(!1)},Ot=async t=>{we(!0);try{let r=0;for(const{connectionId:p,proxyPoolId:M}of t)try{(await fetch(`/api/providers/${p}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({proxyPoolId:M})})).ok||(r+=1)}catch(I){console.log("Error applying proxy for",p,I),r+=1}r>0&&alert(`Updated with ${r} failed request(s).`),await Se(),_(!1)}finally{we(!1)}},Pt=t=>{const r=d.map(p=>({connectionId:p.id,proxyPoolId:t}));return Ot(r)},Ds=()=>{const t=b.filter(p=>p.isActive===!0);if(t.length===0){alert("No active proxy pools available.");return}const r=d.map((p,M)=>({connectionId:p.id,proxyPoolId:t[M%t.length].id}));return Ot(r)},Es=t=>W.includes(t),Os=e.jsx("div",{className:"flex min-w-0 flex-col divide-y divide-black/[0.03] dark:divide-white/[0.03]",children:d.map((t,r)=>e.jsx("div",{className:"flex min-w-0 items-stretch",children:e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(is,{connection:t,proxyPools:b,isOAuth:Fe,isFirst:r===0,isLast:r===d.length-1,onMoveUp:()=>Tt(r,r-1),onMoveDown:()=>Tt(r,r+1),onToggleActive:p=>Ms(t.id,p),onUpdateProxy:async p=>{try{(await fetch(`/api/providers/${t.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({proxyPoolId:p||null})})).ok&&x(I=>I.map(D=>D.id===t.id?{...D,providerSpecificData:{...D.providerSpecificData,proxyPoolId:p||null}}:D))}catch(M){console.log("Error updating proxy:",M)}},onEdit:()=>{ee(t),A(!0)},onDelete:()=>ws(t.id),oneByOneStatus:cs[t.id]||null,isSelected:Es(t.id),onSelect:()=>Rs(t.id)})})},t.id))}),Ps=b.filter(t=>t.isActive===!0),$s=e.jsx(tt,{isOpen:g,onClose:Et,title:`Apply Proxy (${d.length} connections)`,children:e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("button",{onClick:Ds,disabled:pe||Ps.length===0,className:"flex items-center gap-2 rounded-lg px-3 py-2 text-left transition-colors hover:bg-black/[0.04] dark:hover:bg-white/[0.04] disabled:cursor-not-allowed disabled:opacity-50",children:[e.jsx("span",{className:"material-symbols-outlined text-text-muted text-[18px]",children:"sync_alt"}),e.jsx("span",{className:"text-sm text-text-main",children:"One-to-one (rotate)"})]}),e.jsxs("button",{onClick:()=>Pt(null),disabled:pe,className:"flex items-center gap-2 rounded-lg px-3 py-2 text-left transition-colors hover:bg-black/[0.04] dark:hover:bg-white/[0.04] disabled:cursor-not-allowed disabled:opacity-50",children:[e.jsx("span",{className:"material-symbols-outlined text-text-muted text-[18px]",children:"link_off"}),e.jsx("span",{className:"text-sm text-text-main",children:"None (unbind all)"})]}),b.map(t=>e.jsxs("button",{onClick:()=>Pt(t.id),disabled:pe||t.isActive!==!0,className:"flex items-center gap-2 rounded-lg px-3 py-2 text-left transition-colors hover:bg-black/[0.04] dark:hover:bg-white/[0.04] disabled:cursor-not-allowed disabled:opacity-50",children:[e.jsx("span",{className:"material-symbols-outlined text-text-muted text-[18px]",children:"lan"}),e.jsx("span",{className:"truncate text-sm text-text-main",children:t.name}),t.isActive!==!0&&e.jsx("span",{className:"text-[10px] text-text-muted",children:"(inactive)"})]},t.id))]}),pe&&e.jsx("p",{className:"text-xs text-text-muted",children:"Applying..."}),e.jsx(N,{onClick:Et,variant:"ghost",fullWidth:!0,disabled:pe,children:"Cancel"})]})}),$t=async t=>{if(!Q){oe(t);try{const p=await(await fetch("/api/models/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:`${ae}/${t}`})})).json();ne(M=>({...M,[t]:p.ok?"ok":"error"})),K(p.ok?"":p.error||"Model not reachable")}catch{ne(r=>({...r,[t]:"error"})),K("Network error")}finally{oe(null)}}},Ls=()=>{var qe;if(he)return e.jsx(ls,{providerStorageAlias:ae,providerDisplayAlias:Qe,modelAliases:y,copied:ot,onCopy:dt,onSetAlias:Ge,onDeleteAlias:ft,connections:d,isAnthropic:Te});const t=((qe=Ve[a])==null?void 0:qe.serviceKinds)||["llm"],r=t.includes("llm"),p=[...Le,...Y.filter(w=>!Le.some(V=>V.id===w.id))].filter(w=>{const V=w.type||"llm";return r&&(!w.type||w.type==="llm")?!0:t.includes(V)}),M=new Set(s),I=p.filter(w=>!M.has(w.id)),D=p.filter(w=>M.has(w.id)),H=Object.entries(y).filter(([w,V])=>{const De=`${ae}/`;if(!V.startsWith(De))return!1;const re=V.slice(De.length);return j.passthroughModels?!Le.some(Pe=>Pe.id===re):!Le.some(Pe=>Pe.id===re)&&w===re}).map(([w,V])=>({id:V.slice(`${ae}/`.length),alias:w,fullModel:V})),de=t.length>1&&!t.every(w=>w==="llm"),ve=I.filter(w=>w.type==="image"),Oe=I.filter(w=>w.type==="video"),Ie=I.filter(w=>!w.type||w.type==="llm"),je=w=>w.map(V=>{var Wt;const De=`${ae}/${V.id}`,re=`${a}/${V.id}`,Pe=(Wt=Object.entries(y).find(([,Ze])=>Ze===De||Ze===re))==null?void 0:Wt[0];return e.jsx(vt,{model:V,fullModel:`${Qe}/${V.id}`,alias:Pe,copied:ot,onCopy:dt,onSetAlias:Ze=>Ge(V.id,Ze,ae),onDeleteAlias:()=>ft(Pe),testStatus:ie[V.id],onTest:d.length>0||ut?()=>$t(V.id):void 0,isTesting:Q===V.id,isFree:V.isFree,onDisable:()=>xs(V.id)},V.id)}),ze=({icon:w,label:V,count:De})=>e.jsxs("div",{className:"w-full flex items-center gap-2 mt-1 mb-1",children:[e.jsx("span",{className:"material-symbols-outlined text-base text-text-muted",children:w}),e.jsx("span",{className:"text-xs font-semibold text-text-muted uppercase tracking-wider",children:V}),e.jsx("span",{className:"text-[10px] text-text-muted/60 bg-sidebar px-1.5 py-0.5 rounded-full",children:De}),e.jsx("div",{className:"flex-1 h-px bg-border/40"})]}),Jt=e.jsxs("button",{onClick:()=>fe(!0),className:"flex w-full items-center justify-center gap-1.5 rounded-lg border border-dashed border-primary/40 px-3 py-2 text-xs text-primary transition-colors hover:border-primary hover:bg-primary/5 sm:w-auto",children:[e.jsx("span",{className:"material-symbols-outlined text-sm",children:"add"}),"Add Model"]});return e.jsxs("div",{className:"flex flex-col gap-2",children:[H.length>0&&e.jsxs(e.Fragment,{children:[de&&e.jsx(ze,{icon:"star",label:"Custom",count:H.length}),e.jsx("div",{className:"flex flex-wrap gap-3",children:H.map(w=>e.jsx(vt,{model:{id:w.id},fullModel:`${Qe}/${w.id}`,alias:w.alias,copied:ot,onCopy:dt,onSetAlias:()=>{},onDeleteAlias:()=>ft(w.alias),testStatus:ie[w.id],onTest:d.length>0||ut?()=>$t(w.id):void 0,isTesting:Q===w.id,isCustom:!0,isFree:!1},w.id))})]}),de&&ve.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(ze,{icon:"brush",label:"Image Generation",count:ve.length}),e.jsx("div",{className:"flex flex-wrap gap-3",children:je(ve)})]}),de&&Oe.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(ze,{icon:"movie",label:"Video Generation",count:Oe.length}),e.jsx("div",{className:"flex flex-wrap gap-3",children:je(Oe)})]}),(de?Ie:I).length>0&&e.jsx("div",{className:"flex flex-wrap gap-3",children:je(de?Ie:I)}),e.jsxs("div",{className:"flex flex-wrap gap-3 mt-1",children:[Jt,a==="qoder"&&d.some(w=>w.isActive!==!1)&&e.jsxs("button",{onClick:js,disabled:Be,className:"flex w-full items-center justify-center gap-1.5 rounded-lg border border-dashed border-blue-500/40 px-3 py-2 text-xs text-blue-600 dark:text-blue-400 transition-colors hover:border-blue-500 hover:bg-blue-500/5 sm:w-auto disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx("span",{className:"material-symbols-outlined text-sm",style:Be?{animation:"spin 1s linear infinite"}:void 0,children:Be?"progress_activity":"download"}),Be?Ee("Fetching..."):Ee("Fetch Qoder Models")]})]}),le.length>0&&(()=>{const w=new Set(Object.values(y)),V=new Set(Le.map(re=>re.id)),De=le.filter(re=>!w.has(`${ae}/${re.id}`)&&!V.has(re.id));return De.length===0?null:e.jsxs("div",{className:"w-full mt-2",children:[e.jsx("p",{className:"text-xs text-text-muted mb-2",children:"Suggested free models (≥200k context):"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:De.map(re=>e.jsxs("button",{onClick:async()=>{const Pe=re.id.split("/").pop();await Ge(re.id,Pe,ae)},className:"flex items-center gap-1 px-2.5 py-1.5 rounded-lg border border-black/10 dark:border-white/10 text-xs text-text-muted hover:text-primary hover:border-primary/40 hover:bg-primary/5 transition-colors",title:`${re.name} · ${(re.contextLength/1e3).toFixed(0)}k ctx`,children:[e.jsx("span",{className:"material-symbols-outlined text-[13px]",children:"add"}),re.id.split("/").pop()]},re.id))})]})})(),D.length>0&&e.jsxs("div",{className:"w-full mt-2",children:[e.jsxs("p",{className:"text-xs text-text-muted mb-2",children:["Disabled models (",D.length,"):"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:D.map(w=>e.jsxs("button",{onClick:()=>hs(w.id),className:"flex items-center gap-1 px-2.5 py-1.5 rounded-lg border border-dashed border-black/10 dark:border-white/10 text-xs text-text-muted hover:text-primary hover:border-primary/40 hover:bg-primary/5 transition-colors",title:"Restore model",children:[e.jsx("span",{className:"material-symbols-outlined text-[13px]",children:"add"}),w.id]},w.id))})]})]})};if(u)return e.jsxs("div",{className:"flex flex-col gap-8",children:[e.jsx(Xt,{}),e.jsx(Xt,{})]});if(!j)return e.jsxs("div",{className:"text-center py-20",children:[e.jsx("p",{className:"text-text-muted",children:"Provider not found"}),e.jsx(Yt,{to:"/dashboard/providers",className:"text-primary mt-4 inline-block",children:"Back to Providers"})]});const Us=()=>a==="codebuddy"||a==="cb"?"/providers/codebuddy.svg":Mt&&j.apiType?j.apiType==="responses"?"/providers/oai-r.png":"/providers/oai-cc.png":Te?"/providers/anthropic-m.png":a==="weavy"?"/providers/weavy.jpeg":`/providers/${j.id}.png`;return e.jsxs("div",{className:"flex min-w-0 flex-col gap-6 px-1 sm:gap-8 sm:px-0",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs(Yt,{to:"/dashboard/providers",className:"inline-flex items-center gap-1 text-sm text-text-muted hover:text-primary transition-colors mb-4",children:[e.jsx("span",{className:"material-symbols-outlined text-lg",children:"arrow_back"}),"Back to Providers"]}),e.jsxs("div",{className:"flex min-w-0 items-center gap-3 sm:gap-4",children:[e.jsx("div",{className:"flex size-12 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:`${j.color}15`},children:B?e.jsx("span",{className:"text-sm font-bold",style:{color:j.color},children:j.textIcon||j.id.slice(0,2).toUpperCase()}):e.jsx("img",{src:Us(),alt:j.name,width:48,height:48,className:"max-h-12 max-w-12 rounded-lg object-contain",onError:()=>te(!0)})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx("h1",{className:"truncate text-2xl font-semibold tracking-tight sm:text-3xl",children:j.name}),(((_t=j.notice)==null?void 0:_t.apiKeyUrl)||((Ft=j.notice)==null?void 0:Ft.signupUrl)||j.website)&&e.jsxs("a",{href:((Kt=j.notice)==null?void 0:Kt.apiKeyUrl)||((zt=j.notice)==null?void 0:zt.signupUrl)||j.website,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary hover:underline inline-flex items-center gap-1",children:[e.jsx("span",{className:"material-symbols-outlined text-sm",children:"open_in_new"}),(qt=j.notice)!=null&&qt.apiKeyUrl?"Get API Key":"Sign up / Learn more"]})]}),e.jsxs("p",{className:"text-text-muted",children:[d.length," connection",d.length===1?"":"s"]})]})]})]}),j.deprecated&&e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg bg-yellow-500/10 border border-yellow-500/30",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px] text-yellow-500 mt-0.5 shrink-0",children:"warning"}),e.jsx("p",{className:"text-xs text-red-600 dark:text-yellow-400 leading-relaxed",children:j.deprecationNotice})]}),((Vt=j.notice)==null?void 0:Vt.text)&&!j.deprecated&&e.jsxs("div",{className:"flex flex-col gap-2 rounded-lg border border-blue-500/30 bg-blue-500/10 px-3 py-2 sm:flex-row sm:items-center",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px] text-blue-500 shrink-0",children:"info"}),e.jsx("p",{className:"min-w-0 flex-1 text-xs leading-relaxed text-blue-600 dark:text-blue-400",children:j.notice.text}),j.notice.apiKeyUrl&&e.jsx("a",{href:j.notice.apiKeyUrl,target:"_blank",rel:"noopener noreferrer",className:"inline-flex justify-center rounded bg-blue-500 px-2 py-1 text-xs font-medium text-white transition-colors hover:bg-blue-600 sm:py-0.5",children:"Get API Key →"})]}),a==="leonardo"&&e.jsx("div",{className:"flex border-b border-border-subtle pb-px gap-6",children:[{id:"overview",icon:"dashboard",label:"Overview",useImage:!1},{id:"admin",icon:"tune",label:"Leonardo Admin",useImage:!0}].map(t=>e.jsxs("button",{onClick:()=>us(t.id),className:`flex items-center gap-2 pb-3 text-sm font-semibold transition-all border-b-2 cursor-pointer ${nt===t.id?"border-primary text-primary":"border-transparent text-text-muted hover:text-text-main"}`,children:[t.useImage?e.jsx("img",{src:"/providers/leonardo.png",alt:"Leonardo",className:"size-[18px] rounded object-contain"}):e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:t.icon}),t.label]},t.id))}),a==="leonardo"&&nt==="admin"&&e.jsx(ma,{}),a==="weavy"&&e.jsxs("div",{style:{marginBottom:16,padding:"12px 16px",background:"#0c1a2e",border:"1px solid #1e3a5f",borderRadius:8,display:"flex",alignItems:"center",justifyContent:"space-between"},children:[e.jsxs("div",{children:[e.jsx("div",{style:{fontWeight:600,fontSize:14,color:"#60a5fa"},children:"🪄 Weavy Token Pool"}),e.jsx("div",{style:{fontSize:12,color:"#6b7280",marginTop:2},children:"Copy firebase_refresh_token, firebase_api_key, dan JWT untuk dipakai di sistem lain (kliperspro, dll.)"})]}),e.jsx("a",{href:"/dashboard/providers/weavy/pool",style:{padding:"7px 16px",borderRadius:6,background:"#1e3a5f",border:"1px solid #2563eb",color:"#93c5fd",fontSize:13,fontWeight:600,textDecoration:"none",whiteSpace:"nowrap"},children:"Buka Token Pool →"})]}),(a!=="leonardo"||nt==="overview")&&e.jsxs(e.Fragment,{children:[he&&h&&e.jsx(Ne,{children:e.jsxs("div",{className:"mb-4 flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"text-lg font-semibold",children:Te?"Anthropic Compatible Details":"OpenAI Compatible Details"}),e.jsxs("p",{className:"break-all text-sm text-text-muted",children:[Te?"Messages API":h.apiType==="responses"?"Responses API":"Chat Completions"," · ",(h.baseUrl||"").replace(/\/$/,""),"/",Te?"messages":h.apiType==="responses"?"responses":"chat/completions"]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:flex sm:items-center",children:[e.jsx(N,{size:"sm",icon:"add",onClick:()=>{E(""),J(!0)},className:"w-full sm:w-auto",children:"Add API Key"}),e.jsx(N,{size:"sm",variant:"secondary",icon:"edit",onClick:()=>P(!0),className:"w-full sm:w-auto",children:"Edit"}),e.jsx(N,{size:"sm",variant:"secondary",icon:"delete",onClick:async()=>{G({title:"Delete Compatible Node",message:`Delete this ${Te?"Anthropic":"OpenAI"} Compatible node?`,onConfirm:async()=>{G(null);try{(await fetch(`/api/provider-nodes/${a}`,{method:"DELETE"})).ok&&c("/dashboard/providers")}catch(t){console.log("Error deleting provider node:",t)}}})},className:"w-full sm:w-auto",children:"Delete"})]})]})}),ut?e.jsx(Ws,{providerId:a}):e.jsxs(Ne,{children:[e.jsxs("div",{className:"mb-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Connections"}),e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:gap-4",children:[d.length>0&&b.length>0&&e.jsx(N,{size:"sm",variant:"secondary",icon:"lan",onClick:()=>_(!0),children:"Apply Proxy"}),d.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(N,{size:"sm",variant:"secondary",icon:"sync",onClick:Ns,disabled:$e,children:$e?"Testing Connection One-by-One...":"Test Connection One-by-One"}),$e&&e.jsx(N,{size:"sm",variant:"ghost",icon:"stop",onClick:ks,disabled:Nt,children:Nt?"Stopping...":"Stop"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-xs text-text-muted font-medium",children:"Round Robin"}),e.jsx(st,{checked:Ae==="round-robin",onChange:ys}),Ae==="round-robin"&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-xs text-text-muted",children:"Sticky:"}),e.jsx("input",{type:"number",min:1,value:ge,onChange:t=>vs(t.target.value),placeholder:"1",className:"w-14 px-2 py-1 text-xs border border-border rounded-md bg-background focus:outline-none focus:border-primary"})]})]})]})]}),d.length===0?e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"inline-flex items-center justify-center w-9 h-9 rounded-full bg-primary/10 text-primary shrink-0",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:Fe?"lock":"key"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm text-text-muted",children:"No connections yet"}),mt&&e.jsxs("p",{className:"text-xs text-text-muted",children:["Choose ",xt," or ",ht,"."]})]})]}),e.jsx("div",{className:"flex gap-2",children:mt?e.jsxs(e.Fragment,{children:[e.jsx(N,{size:"sm",icon:"lock",variant:"secondary",onClick:ct,children:xt}),e.jsx(N,{size:"sm",icon:"key",onClick:He,children:ht})]}):e.jsxs(e.Fragment,{children:[!he&&a==="iflow"&&e.jsx(N,{size:"sm",icon:"cookie",variant:"secondary",onClick:()=>U(!0),children:"Cookie"}),e.jsx(N,{size:"sm",icon:"add",onClick:St,children:he?"Add API Key":a==="iflow"?"OAuth":"Add Connection"})]})})]}):e.jsxs(e.Fragment,{children:[_e&&e.jsx("div",{className:"mb-4 rounded-lg border border-black/10 bg-black/[0.02] px-3 py-2 text-xs text-text-muted dark:border-white/10 dark:bg-white/[0.03]",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("span",{children:["Total: ",_e.total]}),e.jsxs("span",{children:["Completed: ",_e.completed]}),e.jsxs("span",{children:["Passed: ",_e.passed]}),e.jsxs("span",{children:["Failed: ",_e.failed]}),_e.stopped&&e.jsx("span",{className:"text-amber-600 dark:text-amber-400",children:"Stopped"}),$e&<&&e.jsxs("span",{children:["Running: ",((Bt=d.find(t=>t.id===lt))==null?void 0:Bt.name)||lt]})]})}),d.length>0&&e.jsxs("div",{className:"mb-2 flex items-center justify-between rounded-lg border border-black/5 bg-black/[0.02] px-3 py-2 dark:border-white/5 dark:bg-white/[0.02]",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"checkbox",checked:Dt,onChange:Ts,className:"h-4 w-4 rounded border-black/20 text-primary focus:ring-primary dark:border-white/20 dark:bg-black"}),e.jsxs("span",{className:"text-sm font-medium",children:["Select All (",W.length,"/",d.length,")"]})]}),W.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[b.length>0&&e.jsx(N,{size:"sm",variant:"secondary",icon:"lan",onClick:()=>_(!0),children:"Apply Proxy"}),e.jsx(N,{size:"sm",variant:"danger",icon:"delete",onClick:()=>{W.length!==0&&G({title:"Delete Connections",message:`Delete ${W.length} selected connection(s)?`,onConfirm:async()=>{G(null);try{await Promise.all(W.map(t=>fetch(`/api/providers/${t}`,{method:"DELETE"}))),x(d.filter(t=>!W.includes(t.id))),Is()}catch(t){console.log("Error deleting connections:",t)}}})},children:"Delete Selected"})]})]}),Os,!he&&e.jsxs("div",{className:"mt-4 grid grid-cols-1 gap-2 sm:flex",children:[a==="iflow"&&e.jsx(N,{size:"sm",icon:"cookie",variant:"secondary",onClick:()=>U(!0),title:"Add connection using browser cookie",className:"w-full sm:w-auto",children:"Cookie"}),mt?e.jsxs(e.Fragment,{children:[e.jsx(N,{size:"sm",icon:"lock",variant:"secondary",onClick:ct,className:"w-full sm:w-auto",children:xt}),e.jsx(N,{size:"sm",icon:"key",onClick:He,className:"w-full sm:w-auto",children:ht})]}):e.jsx(N,{size:"sm",icon:"add",onClick:St,className:"w-full sm:w-auto",children:"Add"})]})]})]}),e.jsxs(Ne,{children:[e.jsxs("div",{className:"mb-4 flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Available Models"}),!he&&(()=>{var I;const t=((I=Ve[a])==null?void 0:I.serviceKinds)||["llm"],r=t.includes("llm"),M=[...Le,...Y.filter(D=>!Le.some(H=>H.id===D.id))].filter(D=>{const H=D.type||"llm";return r&&(!D.type||D.type==="llm")?!0:t.includes(H)}).map(D=>D.id).filter(D=>!s.includes(D));return e.jsxs("div",{className:"flex gap-2",children:[s.length>0&&e.jsx(N,{size:"sm",variant:"secondary",icon:"restart_alt",onClick:gs,children:"Active All"}),M.length>0&&e.jsx(N,{size:"sm",variant:"secondary",icon:"block",onClick:()=>fs(M),children:"Disable All"})]})})()]}),!!se&&e.jsx("p",{className:"text-xs text-red-500 mb-3 break-words",children:se}),Ls()]}),$s]}),a==="kiro"?e.jsx(Hs,{isOpen:C,providerInfo:j,onSuccess:Xe,onClose:()=>R(!1)}):a==="cursor"?e.jsx(Qs,{isOpen:C,onSuccess:Xe,onClose:()=>R(!1)}):a==="gitlab"?e.jsx(Ys,{isOpen:C,providerInfo:j,onSuccess:Xe,onClose:()=>R(!1)}):e.jsx(Xs,{isOpen:C,provider:a,providerInfo:j,onSuccess:Xe,onClose:()=>R(!1),proxyPools:b}),a==="iflow"&&e.jsx(Zs,{isOpen:L,onSuccess:Cs,onClose:()=>U(!1)}),e.jsx(ns,{isOpen:F,provider:a,providerName:j.name,isCompatible:he,isAnthropic:Te,authType:j==null?void 0:j.authType,authHint:j==null?void 0:j.authHint,website:j==null?void 0:j.website,proxyPools:b,error:X,onSave:Ss,onBulkDone:Se,onClose:()=>{E(""),J(!1)}}),e.jsx(ea,{isOpen:Z,connection:z,proxyPools:b,onSave:As,onClose:()=>A(!1)}),he&&e.jsx(os,{isOpen:O,node:h,onSave:bs,onClose:()=>P(!1),isAnthropic:Te}),!he&&e.jsx(ds,{isOpen:ue,providerAlias:ae,providerDisplayAlias:Qe,allowedKinds:((Gt=Ve[a])==null?void 0:Gt.serviceKinds)||["llm"],onSave:async(t,r)=>{const p=j!=null&&j.passthroughModels?t.split("/").pop():t;await Ge(t,p,ae),fe(!1)},onClose:()=>fe(!1)}),e.jsx(Qt,{isOpen:xe,onClose:()=>q(!1),onConfirm:ps,title:"Risk Notice",message:j==null?void 0:j.deprecationNotice,confirmText:"I Understand, Continue",cancelText:"Cancel",variant:"danger"}),e.jsx(Qt,{isOpen:!!k,onClose:()=>G(null),onConfirm:k==null?void 0:k.onConfirm,title:(k==null?void 0:k.title)||"Confirm",message:k==null?void 0:k.message,variant:"danger"})]})}export{ja as default};
|