cartethyia 2.3.0 → 2.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +25 -0
- package/dist/dashboard/assets/{BannedPage-ClPA4nQv.js → BannedPage-BZQBIhxF.js} +1 -1
- package/dist/dashboard/assets/{CliToolDetailPage-Bevb0yY1.js → CliToolDetailPage-ChtDDIFA.js} +1 -1
- package/dist/dashboard/assets/{CliToolsPage-DsryPzyc.js → CliToolsPage-CfmolGV7.js} +1 -1
- package/dist/dashboard/assets/{ConsoleLogPage-CTzqdm6k.js → ConsoleLogPage-ZCwKyxxl.js} +1 -1
- package/dist/dashboard/assets/{CustomizationPage-CMxyDZej.js → CustomizationPage-WJejmVl_.js} +1 -1
- package/dist/dashboard/assets/{HealthEventsModal-CxkQ4JaG.js → HealthEventsModal-URh6wOhb.js} +1 -1
- package/dist/dashboard/assets/{LoginPage-CL2GR7wU.js → LoginPage-C5ib2ujx.js} +1 -1
- package/dist/dashboard/assets/{OverviewPage-b0Ggk2qb.js → OverviewPage-BwOb4p9C.js} +1 -1
- package/dist/dashboard/assets/{ProviderDetailPage-Y1Q4UPbO.js → ProviderDetailPage-w4o_xJlP.js} +1 -1
- package/dist/dashboard/assets/{ProvidersPage-C-GI5Qrf.js → ProvidersPage-6_WFzAGN.js} +1 -1
- package/dist/dashboard/assets/{ProxyPage-d7vbm79h.js → ProxyPage-DaGQsvht.js} +1 -1
- package/dist/dashboard/assets/{QuotaPage-BmLGXSiw.js → QuotaPage-BPPN7W5b.js} +1 -1
- package/dist/dashboard/assets/{SetupPage-BZ2NsM8f.js → SetupPage-CDqTXPe7.js} +1 -1
- package/dist/dashboard/assets/{StudioPage-txsvSOwb.js → StudioPage-CiGmv9Ju.js} +1 -1
- package/dist/dashboard/assets/{UsagePage-D8C_HZBY.js → UsagePage-CxrGngrm.js} +1 -1
- package/dist/dashboard/assets/{entry-DcX5sMzh.js → entry-C3M9aRLH.js} +3 -3
- package/dist/dashboard/assets/{index-By44uTGZ.js → index-BS-k3kIz.js} +2 -2
- package/dist/dashboard/index.html +1 -1
- package/package.json +2 -2
package/dist/dashboard/assets/{ProviderDetailPage-Y1Q4UPbO.js → ProviderDetailPage-w4o_xJlP.js}
RENAMED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{n as e,o as t,r as n,t as r}from"./jsx-runtime-CXUMngI_.js";import{i}from"./terminal-C9mZ4Ugm.js";import{t as a}from"./arrow-left-CpBxkoxI.js";import{n as o,t as s}from"./brain-Cwed_72z.js";import{n as c,t as l}from"./fingerprint-pattern-BWuHtbW4.js";import{t as u}from"./check-D69FzdvC.js";import{n as d,t as f}from"./select-CGUuTQmj.js";import{t as p}from"./circle-alert-CntYHV5v.js";import{t as m}from"./circle-check-BU3v_mFW.js";import{g as h,h as g,i as _,m as v,n as y,r as b,t as x}from"./toast-DKAdP2mo.js";import{t as S}from"./cog-CdWhsajs.js";import{t as C}from"./copy-ngmQ9zcZ.js";import{t as w}from"./download-A0SW9OCW.js";import{t as T}from"./eye-off-Bk5g2luF.js";import{t as E}from"./eye-C_hawfH4.js";import{t as D}from"./gauge-BbIMy7MB.js";import{t as O}from"./image-BPaouViG.js";import{a as ee,n as k,r as A,t as j}from"./state-DHKdg-pm.js";import{t as M}from"./key-round-UkavsGxp.js";import{t as te}from"./layers-2-glBbjl.js";import{n as N,t as P}from"./dialog-iocKA3jr.js";import{t as F}from"./pencil-768ysRAr.js";import{t as ne}from"./plus-DIdX_g-x.js";import{i as re,n as I}from"./privacy-mode-CQjbZ3xk.js";import{t as ie}from"./refresh-cw-BqJFk4sU.js";import{t as ae}from"./rotate-ccw-CufcqITi.js";import{t as oe}from"./search-JOKus9rb.js";import{t as se}from"./trash-Cppn5c3R.js";import{t as ce}from"./wrench-B6E1oEuY.js";import{w as le}from"./assert-Bwh6DJTK.js";import{a as ue,t as L}from"./query-keys-ROf-g1Wi.js";import{E as de,F as fe,S as pe,T as me,X as he,Y as ge,Z as _e,_ as ve,a as ye,b as be,c as R,d as xe,f as Se,g as Ce,h as we,l as Te,m as Ee,o as De,p as Oe,r as ke,t as Ae,u as z,v as je,w as Me,x as Ne,y as Pe}from"./entry-DcX5sMzh.js";import{n as B,r as Fe,t as V}from"./card-BTdbRFFg.js";import{n as Ie}from"./download-dRFo5_Wu.js";import{f as Le,i as H,l as Re,n as U,r as ze,s as Be}from"./tokens-DDxMbSRL.js";import{a as W}from"./numbers-CFL4_Dqc.js";import{t as G}from"./badge-BwmwEOgA.js";import{n as K}from"./input-Bn4_kNav.js";import{t as Ve}from"./ProviderIcon-paOCq8I0.js";import{t as q}from"./switch-DIDeAiz9.js";import{t as J}from"./stack-C1kTcOmP.js";import{n as Y,t as He}from"./inline-DCejSLlA.js";import{i as X}from"./quota-DZGyp0N5.js";import{t as Ue}from"./list-row-BLA0sldD.js";import{c as We,l as Ge,m as Z}from"./routing-jntw9-Ui.js";import{o as Ke,s as qe,t as Je}from"./HealthEventsModal-CxkQ4JaG.js";import{n as Ye,t as Xe}from"./AccountCooldown-ChpdzxRH.js";import{t as Ze}from"./use-timeout-BwcBBRrT.js";import{t as Qe}from"./banner-BKBfKTqn.js";var $e=e(`cable`,[[`path`,{d:`M17 19a1 1 0 0 1-1-1v-2a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2a1 1 0 0 1-1 1z`,key:`trhst0`}],[`path`,{d:`M17 21v-2`,key:`ds4u3f`}],[`path`,{d:`M19 14V6.5a1 1 0 0 0-7 0v11a1 1 0 0 1-7 0V10`,key:`1mo9zo`}],[`path`,{d:`M21 21v-2`,key:`eo0ou`}],[`path`,{d:`M3 5V3`,key:`1k5hjh`}],[`path`,{d:`M4 10a2 2 0 0 1-2-2V6a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2a2 2 0 0 1-2 2z`,key:`1dd30t`}],[`path`,{d:`M7 5V3`,key:`1t1388`}]]),et=e(`external-link`,[[`path`,{d:`M15 3h6v6`,key:`1q9fwt`}],[`path`,{d:`M10 14 21 3`,key:`gplh6r`}],[`path`,{d:`M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6`,key:`a6xqqp`}]]),tt=e(`info`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`M12 16v-4`,key:`1dtifu`}],[`path`,{d:`M12 8h.01`,key:`e9boi3`}]]),nt=e(`lock-open`,[[`rect`,{width:`18`,height:`11`,x:`3`,y:`11`,rx:`2`,ry:`2`,key:`1w4ew1`}],[`path`,{d:`M7 11V7a5 5 0 0 1 9.9-1`,key:`1mm8w8`}]]),rt=e(`package-x`,[[`path`,{d:`M12 22V12`,key:`d0xqtd`}],[`path`,{d:`m16.5 14.5 5 5`,key:`ozpm51`}],[`path`,{d:`m16.5 19.5 5-5`,key:`syf6b9`}],[`path`,{d:`M21 10.5V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.729l7 4a2 2 0 0 0 2 .001l.13-.074`,key:`isw6gs`}],[`path`,{d:`M3.29 7 12 12l8.71-5`,key:`19ckod`}],[`path`,{d:`m7.5 4.27 8.997 5.148`,key:`9yrvtv`}]]),it=e(`repeat`,[[`path`,{d:`m17 2 4 4-4 4`,key:`nntrym`}],[`path`,{d:`M3 11v-1a4 4 0 0 1 4-4h14`,key:`84bu3i`}],[`path`,{d:`m7 22-4-4 4-4`,key:`1wqhfi`}],[`path`,{d:`M21 13v1a4 4 0 0 1-4 4H3`,key:`1rx37r`}]]),at=e(`video`,[[`path`,{d:`m16 13 5.223 3.482a.5.5 0 0 0 .777-.416V7.87a.5.5 0 0 0-.752-.432L16 10.5`,key:`ftymec`}],[`rect`,{x:`2`,y:`6`,width:`14`,height:`12`,rx:`2`,key:`158x01`}]]),ot=e(`waypoints`,[[`path`,{d:`m10.586 5.414-5.172 5.172`,key:`4mc350`}],[`path`,{d:`m18.586 13.414-5.172 5.172`,key:`8c96vv`}],[`path`,{d:`M6 12h12`,key:`8npq4p`}],[`circle`,{cx:`12`,cy:`20`,r:`2`,key:`144qzu`}],[`circle`,{cx:`12`,cy:`4`,r:`2`,key:`muu5ef`}],[`circle`,{cx:`20`,cy:`12`,r:`2`,key:`1xzzfp`}],[`circle`,{cx:`4`,cy:`12`,r:`2`,key:`1hvhnz`}]]),st=[`auto`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function ct(e,t){return t===null?e:`${e}(${t})`}var Q=t(n(),1),$=r();function lt({to:e,label:t}){let n=ge();return(0,$.jsxs)(`button`,{type:`button`,onClick:()=>{window.history.length>1?n(-1):n(e)},className:`inline-flex items-center gap-3 text-accent text-caption bg-transparent border-0 p-0 cursor-pointer`,children:[(0,$.jsx)(a,{size:14,"aria-hidden":`true`}),t]})}function ut({title:e,description:t,icon:n,badges:r,actions:i,back:a}){return(0,$.jsxs)(`div`,{className:`flex flex-col gap-5`,children:[a?(0,$.jsx)(lt,{...a}):null,(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-6 flex-wrap`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-5 min-w-0`,children:[n?(0,$.jsx)(`div`,{className:`card-header-icon`,children:n}):null,(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-4 flex-wrap`,children:[(0,$.jsx)(`h1`,{className:`text-lead font-bold`,children:e}),r]}),t?(0,$.jsx)(`p`,{className:`mt-1 text-badge text-text-tertiary`,children:t}):null]})]}),i?(0,$.jsx)(`div`,{className:_(`flex items-center gap-4 flex-wrap min-w-0 max-w-full`),children:i}):null]})]})}function dt(e){return e.isBuiltIn&&e.requiresAccount&&e.oauthFlows===void 0&&!e.hasAdapterUserAgent}function ft(e,t=600){let n=(0,Q.useRef)(void 0);return(0,Q.useEffect)(()=>()=>clearTimeout(n.current),[]),r=>{clearTimeout(n.current),n.current=setTimeout(()=>e(r),t)}}var pt={fallback:`Failover`,roundRobin:`Round robin`},mt=new Set([`inferhub`,`cline`]);function ht(e,t){let n=Ge(e),r=Z(),[i,a]=(0,Q.useState)(`fallback`),[o,s]=(0,Q.useState)(1),[c,l]=(0,Q.useState)(null),[u,d]=(0,Q.useState)(null),[f,p]=(0,Q.useState)(null),[m,h]=(0,Q.useState)(`percent`),[g,_]=(0,Q.useState)(!1),[v,y]=(0,Q.useState)(``);(0,Q.useEffect)(()=>{n.data&&(a(n.data.strategy),s(n.data.rotateCount),l(n.data.maxInflight),d(n.data.maxInflightPerProxy??null),p(n.data.usageFloor),h(n.data.usageFloorUnit),_(n.data.skipProxy),y(n.data.userAgent))},[n.data]);let b=i=>{r.mutate({providerId:e,request:{enabled:!0,strategy:i.strategy,rotateCount:i.rotateCount,maxInflight:i.maxInflight,maxInflightPerProxy:i.maxInflightPerProxy,usageFloor:i.usageFloor,usageFloorUnit:i.usageFloorUnit,skipProxy:i.skipProxy,...t?{userAgent:i.userAgent}:{}}},{onError:()=>{n.data&&(a(n.data.strategy),s(n.data.rotateCount),l(n.data.maxInflight),d(n.data.maxInflightPerProxy??null),p(n.data.usageFloor),h(n.data.usageFloorUnit),_(n.data.skipProxy),y(n.data.userAgent))}})},x=ft(e=>b({strategy:i,rotateCount:o,maxInflight:e,maxInflightPerProxy:u,usageFloor:f,usageFloorUnit:m,skipProxy:g,userAgent:v})),S=ft(e=>b({strategy:i,rotateCount:o,maxInflight:c,maxInflightPerProxy:e,usageFloor:f,usageFloorUnit:m,skipProxy:g,userAgent:v})),C=ft(e=>b({strategy:i,rotateCount:e,maxInflight:c,maxInflightPerProxy:u,usageFloor:f,usageFloorUnit:m,skipProxy:g,userAgent:v})),w=ft(e=>b({strategy:i,rotateCount:o,maxInflight:c,maxInflightPerProxy:u,usageFloor:f,usageFloorUnit:m,skipProxy:g,userAgent:e}));return{strategy:i,maxInflight:c,maxInflightPerProxy:u,usageFloor:f,usageFloorUnit:m,setUsageFloor:(e,t)=>{p(e),h(t),b({strategy:i,rotateCount:o,maxInflight:c,maxInflightPerProxy:u,usageFloor:e,usageFloorUnit:t,skipProxy:g,userAgent:v})},skipProxy:g,userAgent:v,isLoading:n.isPending,isError:n.isError,isSaving:r.isPending,saveFailed:r.isError,refetch:()=>n.refetch(),setMaxInflight:e=>{l(e),x(e)},setMaxInflightPerProxy:e=>{d(e),S(e)},setUserAgent:e=>{y(e),w(e)},setSkipProxy:e=>{_(e),b({strategy:i,rotateCount:o,maxInflight:c,maxInflightPerProxy:u,usageFloor:f,usageFloorUnit:m,skipProxy:e,userAgent:v})},roundRobinEnabled:i===`round_robin`,setRoundRobinEnabled:e=>{let t=e?`round_robin`:`fallback`;a(t),b({strategy:t,rotateCount:o,maxInflight:c,maxInflightPerProxy:u,usageFloor:f,usageFloorUnit:m,skipProxy:g,userAgent:v})},rotateCount:o,setRotateCount:e=>{s(e),C(e)}}}var gt=50,_t=100;function vt(e,t,n){return[{value:``,label:`None`},{value:`Cartethyia/${e}`,label:`Cartethyia ${e}`},{value:`codex_cli_rs/${t}`,label:`Codex`},{value:`claude-cli/${n} (external, cli)`,label:`Claude Code`}]}function yt({children:e,action:t}){return(0,$.jsx)(Ue,{actions:t,children:e})}function bt({providerId:e,clientVersion:t,routeIdentityVersions:n,userAgentEditable:r}){let i=ht(e,r),[a,o]=(0,Q.useState)(!1),s=mt.has(e),c=vt(Ae,n.codex,n.claude),u=c.some(e=>e.value===i.userAgent)?c:[...c,{value:i.userAgent,label:`Custom`}];if(i.isLoading)return(0,$.jsx)(A,{label:`Loading routing...`});if(i.isError)return(0,$.jsx)(k,{message:`Failed to load routing`,onRetry:i.refetch});let d=i.roundRobinEnabled?`${pt.roundRobin} · ${i.rotateCount} account${i.rotateCount===1?``:`s`} per rotation`:pt.fallback,p=i.isSaving?`Saving...`:i.saveFailed?`Save failed — reverted to last saved value`:`Active: ${d}`,m=i.maxInflight===null,h=m?51:Math.min(51,Math.max(1,i.maxInflight)),g=m?`∞`:String(i.maxInflight),_=i.maxInflightPerProxy===null,v=_?51:Math.min(51,Math.max(1,i.maxInflightPerProxy)),b=_?`∞`:String(i.maxInflightPerProxy),S=i.skipProxy,C=e=>{i.setRotateCount(Math.min(1e3,Math.max(1,i.rotateCount+e)))},w=e=>{if(e===i.userAgent)return;i.setUserAgent(e);let t=u.find(t=>t.value===e)?.label??e;x.success(`Client identity updated`,t)},T=t?`${t.client} ${t.version}`:`Provider default`;return(0,$.jsxs)(V,{children:[(0,$.jsx)(Fe,{title:`Routing Strategy`,subtitle:p,icon:(0,$.jsx)(te,{size:16})}),(0,$.jsx)(B,{children:(0,$.jsxs)(`div`,{className:`grid gap-5 w-full min-w-0`,children:[(0,$.jsx)(yt,{action:(0,$.jsxs)($.Fragment,{children:[i.roundRobinEnabled?(0,$.jsxs)(`div`,{role:`group`,"aria-label":`Accounts per rotation`,className:`inline-flex items-center gap-1 rounded-control border border-inner-border bg-surface-1 p-1`,children:[(0,$.jsx)(`span`,{className:`px-2 text-badge text-text-secondary`,children:`Accounts/rotation`}),(0,$.jsx)(y,{variant:`ghost`,size:`icon`,className:`size-9 rounded-tiny`,"aria-label":`Decrease accounts per rotation`,disabled:i.rotateCount<=1,icon:(0,$.jsx)(N,{size:14}),onClick:()=>C(-1)}),(0,$.jsx)(`output`,{className:`min-w-8 text-center text-body font-semibold tabular-nums`,"aria-live":`polite`,children:i.rotateCount}),(0,$.jsx)(y,{variant:`ghost`,size:`icon`,className:`size-9 rounded-tiny`,"aria-label":`Increase accounts per rotation`,disabled:i.rotateCount>=1e3,icon:(0,$.jsx)(ne,{size:14}),onClick:()=>C(1)})]}):null,(0,$.jsx)(q,{checked:i.roundRobinEnabled,onChange:i.setRoundRobinEnabled,id:`routing-round-robin`})]}),children:(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`label`,{htmlFor:`routing-round-robin`,children:(0,$.jsxs)(Y,{gap:`6px`,className:`text-body font-semibold`,children:[(0,$.jsx)(it,{size:15,"aria-hidden":`true`,className:`shrink-0 ${i.roundRobinEnabled?`text-accent`:`text-text-tertiary`}`}),`Round robin`]})}),(0,$.jsx)(`div`,{className:`mt-1 text-badge text-text-tertiary`,children:`Off uses priority order with failover. On rotates requests across this provider's accounts.`})]})}),(0,$.jsx)(yt,{action:(0,$.jsx)(q,{checked:i.skipProxy,onChange:i.setSkipProxy,id:`routing-skip-proxy`}),children:(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`label`,{htmlFor:`routing-skip-proxy`,children:(0,$.jsxs)(Y,{gap:`6px`,className:`text-body font-semibold`,children:[(0,$.jsx)($e,{size:15,"aria-hidden":`true`,className:`shrink-0 ${i.skipProxy?`text-accent`:`text-text-tertiary`}`}),`Always direct`]})}),(0,$.jsx)(`div`,{className:`mt-1 text-badge text-text-tertiary`,children:`Bypass automatic proxy-pool routing for this provider and always dial direct`})]})}),(0,$.jsxs)(`div`,{className:`routing-controls-grid grid gap-5 min-w-0 w-full`,children:[(0,$.jsxs)(`div`,{className:`px-6 py-5 rounded-control border border-inner-border bg-surface-2 min-w-0`,children:[(0,$.jsxs)(Y,{gap:`6px`,className:`text-body font-semibold mb-3`,children:[(0,$.jsx)(l,{size:15,"aria-hidden":`true`,className:`text-text-tertiary shrink-0`}),`Client identity`]}),r?(0,$.jsx)(f,{id:`routing-user-agent-preset`,"aria-label":`Client identity`,value:i.userAgent,options:u,onValueChange:w}):(0,$.jsx)(f,{id:`routing-user-agent-fixed`,"aria-label":`Client identity`,disabled:!0,value:T,options:[{value:T,label:T}]}),(0,$.jsx)(`div`,{className:`text-badge text-text-tertiary mt-2`,children:r?`Sent when the provider has no identity of its own.`:`Set by the provider. It cannot be changed.`})]}),(0,$.jsxs)(`div`,{className:`px-6 py-5 rounded-control border border-inner-border bg-surface-2 min-w-0`,children:[(0,$.jsx)(`label`,{htmlFor:`routing-max-inflight`,className:`form-label`,children:(0,$.jsxs)(Y,{gap:`6px`,className:`text-body font-semibold`,children:[(0,$.jsx)(D,{size:15,"aria-hidden":`true`,className:`text-text-tertiary shrink-0`}),`Max inflight / account`]})}),(0,$.jsxs)(`div`,{className:`text-badge text-text-tertiary mb-3`,children:[`Shared provider ceiling. One step past `,gt,` is unlimited.`]}),(0,$.jsxs)(Y,{gap:`10px`,className:`mt-3`,children:[(0,$.jsx)(`input`,{id:`routing-max-inflight`,type:`range`,className:`routing-slider flex-1 min-w-0`,"data-unlimited":m?`true`:void 0,min:1,max:51,step:1,value:h,"aria-valuetext":m?`Unlimited`:String(i.maxInflight),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&i.setMaxInflight(t>gt?null:Math.round(t))},style:{"--slider-pct":`${h/51*100}%`}}),(0,$.jsx)(`input`,{type:`text`,inputMode:`numeric`,"aria-label":`Max inflight per account`,value:g,onChange:e=>{let t=e.target.value.trim();if(t===``||t===`∞`){i.setMaxInflight(null);return}let n=Number(t);Number.isFinite(n)&&n>=1&&i.setMaxInflight(Math.min(_t,Math.round(n)))},className:`form-input w-26 shrink-0 px-2 py-3 text-center text-body ${m?`text-status-success`:``}`})]})]})]}),(0,$.jsxs)(`div`,{className:`px-6 py-5 rounded-control border border-inner-border bg-surface-2 min-w-0${S?` opacity-60`:``}`,children:[(0,$.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,$.jsxs)(`label`,{htmlFor:`routing-max-inflight-per-proxy`,className:`min-w-0`,children:[(0,$.jsxs)(Y,{gap:`6px`,className:`text-body font-semibold`,children:[(0,$.jsx)(ot,{size:15,"aria-hidden":`true`,className:`text-text-tertiary shrink-0`}),`Max inflight / proxy`]}),(0,$.jsx)(`div`,{className:`mt-1 text-badge text-text-tertiary`,children:`Each proxy pool carries at most this many concurrent requests for this provider. Other providers on the same pool are unaffected.`})]}),(0,$.jsx)(y,{variant:`ghost`,size:`sm`,className:`shrink-0`,"aria-label":`How per-proxy limits work`,onClick:()=>o(!0),children:`How it works`})]}),(0,$.jsxs)(Y,{gap:`10px`,className:`mt-3`,children:[(0,$.jsx)(`input`,{id:`routing-max-inflight-per-proxy`,type:`range`,className:`routing-slider flex-1 min-w-0`,"data-unlimited":_?`true`:void 0,min:1,max:51,step:1,disabled:S,value:v,"aria-valuetext":_?`Unlimited`:String(i.maxInflightPerProxy),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&i.setMaxInflightPerProxy(t>gt?null:Math.round(t))},style:{"--slider-pct":`${v/51*100}%`}}),(0,$.jsx)(`input`,{type:`text`,inputMode:`numeric`,"aria-label":`Max inflight per proxy`,disabled:S,value:b,onChange:e=>{let t=e.target.value.trim();if(t===``||t===`∞`){i.setMaxInflightPerProxy(null);return}let n=Number(t);Number.isFinite(n)&&n>=1&&i.setMaxInflightPerProxy(Math.min(_t,Math.round(n)))},className:`form-input w-26 shrink-0 px-2 py-3 text-center text-body ${_?`text-status-success`:``}`})]}),(0,$.jsx)(`div`,{className:`mt-2 text-badge text-text-tertiary`,children:S?`Always direct is on, so this provider never dials a pool. The limit is kept for when a pool is used again.`:`One step past ${gt} is unlimited.`})]}),(0,$.jsx)(P,{open:a,onClose:()=>o(!1),title:`How concurrency limits stack`,size:`md`,children:(0,$.jsxs)(`div`,{className:`grid gap-4 text-body`,children:[(0,$.jsx)(`p`,{className:`text-text-secondary`,children:`Three limits apply at once. Each one bounds a different thing; none replaces another.`}),(0,$.jsxs)(`dl`,{className:`grid gap-3`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`font-semibold`,children:`Max inflight / account`}),(0,$.jsx)(`dd`,{className:`text-badge text-text-tertiary`,children:`One account of this provider, across every proxy. Set here, above.`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`font-semibold`,children:`Max inflight / proxy`}),(0,$.jsxs)(`dd`,{className:`text-badge text-text-tertiary`,children:[`One proxy pool's concurrent requests `,(0,$.jsx)(`em`,{children:`for this provider`}),`. The same number applies to every pool; each pool counts separately. This is the field above.`]})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`font-semibold`,children:`Pool capacity`}),(0,$.jsx)(`dd`,{className:`text-badge text-text-tertiary`,children:`Everything through one pool, all providers combined. Set on the proxy itself, on the Proxies page.`})]})]}),(0,$.jsxs)(`p`,{className:`text-badge text-text-tertiary`,children:[`A request must clear all three. When a pool is full for this provider, the request moves to another pool that still has room; it only fails with`,` `,(0,$.jsx)(`code`,{children:`429`}),` when every pool is full.`]}),(0,$.jsx)(`p`,{className:`text-badge text-text-tertiary`,children:`Unlimited means no counter is kept for this provider, so the limit costs nothing until you set one.`})]})}),s&&(0,$.jsxs)(Y,{gap:`6px`,align:`flex-start`,className:`mt-1 text-badge text-text-tertiary`,children:[(0,$.jsx)(tt,{size:12,className:`shrink-0 mt-0.5`}),(0,$.jsx)(`span`,{children:`This provider doesn't reliably work through a plain HTTP/S proxy — use a SOCKS5 or proxy pool instead if you need to route it.`})]})]})})]})}function xt({providerId:e}){let t=ht(e,!1),n=Ke(),r=We(e),i=(0,Q.useMemo)(()=>Ct(n.data?.accounts??[],e),[n.data,e]),a=(0,Q.useRef)(null),o=(0,Q.useMemo)(()=>[...r.data?.values()??[]].reduce((e,t)=>e+t,0),[r.data]);(0,Q.useEffect)(()=>{if(a.current===null){a.current=o;return}a.current!==o&&(a.current=o,n.refetch())},[o,n]);let[s,c]=(0,Q.useState)(`40`),[l,u]=(0,Q.useState)(`percent`),d=t.usageFloor!==null;(0,Q.useEffect)(()=>{t.usageFloor!==null&&c(String(t.usageFloor)),u(t.usageFloorUnit)},[t.usageFloor,t.usageFloorUnit]);let f=Number(s),p=Number.isInteger(f)&&f>=0&&f<=1e6,m=i===null||i.remaining<=0?`text-status-danger`:i.percent<=10?`text-status-warning`:`text-status-success`,h=(e,n)=>{(e===null||p)&&t.setUsageFloor(e,n)};return(0,$.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,$.jsxs)(`section`,{className:`usage-floor-panel flex flex-col gap-4 px-5 py-4 border border-inner-border rounded-narrow bg-surface-2`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-3 text-body font-semibold text-text-primary`,children:[(0,$.jsx)(D,{size:14}),(0,$.jsx)(`span`,{children:`Usage floor`}),(0,$.jsx)(`span`,{className:`badge border border-warning-line bg-surface-2 text-micro tracking-label text-status-warning`,children:`BETA`})]}),(0,$.jsx)(`p`,{className:`mt-0.5 text-badge leading-normal text-text-tertiary`,children:`Per account. Skip an account once its remaining allowance reaches this, and send the request to the next one.`})]}),(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-4`,children:[i!==null&&(0,$.jsxs)(`div`,{className:`flex min-h-24 min-w-0 flex-[1_1_20rem] flex-col justify-center gap-2 py-2`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1 text-micro font-semibold tracking-label uppercase text-text-tertiary`,children:[(0,$.jsx)(`span`,{children:`Pooled credits`}),(0,$.jsx)(`span`,{className:`text-text-primary`,children:i.accounts}),(0,$.jsx)(`span`,{children:i.accounts===1?`active account`:`active accounts`})]}),(0,$.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1 text-caption font-semibold tabular-nums text-text-primary`,title:`Combined allowance across active accounts; the usage floor is evaluated per account`,children:[(0,$.jsx)(`strong`,{className:`font-bold ${m}`,children:wt(i.remaining)}),(0,$.jsx)(`span`,{className:`font-medium text-text-secondary`,children:`credits available`}),(0,$.jsxs)(`span`,{className:`font-medium opacity-75`,children:[`of `,wt(i.total)]}),(0,$.jsxs)(`span`,{className:`font-bold ${m}`,children:[i.percent,`%`]})]}),(0,$.jsx)(`p`,{className:`text-micro leading-normal text-text-tertiary`,children:t.usageFloor===null?`Floor off · exhausted quota windows are still skipped`:`Floor ${wt(t.usageFloor)} ${t.usageFloorUnit===`credit`?`credits`:`%`} per account`})]}),i===null&&(0,$.jsxs)(`p`,{className:`flex min-h-24 min-w-0 flex-[1_1_20rem] flex-col justify-center gap-2 py-2 text-badge leading-normal text-text-tertiary`,children:[(0,$.jsx)(`span`,{children:`No combined credit balance is available. Separate quota windows are not added together, and exhausted windows are still skipped.`}),(0,$.jsx)(`span`,{className:`text-micro`,children:t.usageFloor===null?`Floor off · exhausted quota windows are still skipped`:`Floor ${wt(t.usageFloor)} ${t.usageFloorUnit===`credit`?`credits`:`%`} per account`})]}),(0,$.jsxs)(`div`,{className:`ml-auto flex max-w-full shrink-0 flex-col items-end justify-center gap-2`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center justify-end gap-x-3 gap-y-2`,children:[(0,$.jsx)(`span`,{className:`text-micro font-semibold tracking-label uppercase text-text-tertiary`,children:`Floor threshold`}),(0,$.jsxs)(`label`,{className:`flex h-12 max-w-full items-center overflow-hidden rounded-tiny border border-inner-border bg-surface-1 focus-within:border-text-tertiary`,children:[(0,$.jsx)(`input`,{type:`number`,min:0,max:1e6,value:d?s:``,placeholder:`40`,disabled:!d,"aria-label":`Usage floor amount`,className:`h-full w-24 border-0 bg-transparent px-3 text-right font-mono text-body font-semibold tabular-nums text-text-primary disabled:text-text-tertiary`,onChange:e=>c(e.target.value),onBlur:()=>{d&&h(f,l)}}),(0,$.jsxs)(`select`,{value:l,disabled:!d,"aria-label":`Usage floor unit`,className:`h-full border-0 border-l border-inner-border bg-hover px-3 text-body font-semibold text-text-secondary disabled:cursor-default disabled:opacity-60`,onChange:e=>{let t=e.target.value===`credit`?`credit`:`percent`;u(t),d&&h(f,t)},children:[(0,$.jsx)(`option`,{value:`percent`,children:`%`}),(0,$.jsx)(`option`,{value:`credit`,children:`credits`})]})]}),(0,$.jsx)(q,{checked:d,label:`Enabled`,"aria-label":`Usage floor`,className:`usage-floor-switch`,onChange:e=>h(e?p?f:40:null,l)})]}),t.saveFailed?(0,$.jsx)(`p`,{role:`alert`,className:`text-right text-micro leading-normal text-status-danger`,children:`Usage floor save failed. The last saved setting has been restored.`}):null]})]})]}),(0,$.jsx)(St,{providerId:e})]})}function St({providerId:e}){let{enabled:t,setEnabled:n}=I(e);return(0,$.jsxs)(`div`,{className:`flex items-center justify-between flex-wrap gap-6 px-6 py-5 border border-inner-border rounded-control bg-surface-2`,children:[(0,$.jsxs)(`div`,{className:`min-w-0 flex-auto basis-110`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-3 text-body font-semibold text-text-primary`,children:[(0,$.jsx)(T,{size:14}),(0,$.jsx)(`span`,{children:`Mysterious accounts`})]}),(0,$.jsx)(`p`,{className:`mt-0.5 text-badge leading-normal text-text-tertiary`,children:`Hide this provider's emails and usernames. Stored in this browser only.`})]}),(0,$.jsx)(`div`,{className:`flex items-center gap-4 shrink-0`,children:(0,$.jsx)(q,{checked:t,"aria-label":`Mysterious accounts`,onChange:n})})]})}function Ct(e,t){let n=0,r=0,i=0,a=!1;for(let o of e)if(o.provider===t&&o.active&&(i+=1,o.quota!==null))for(let e of o.quota.windows){if(e.accounting!==`pooled`)continue;let t=typeof e.limit==`number`&&Number.isFinite(e.limit)?e.limit:null;if(t===null)continue;let i=typeof e.remaining==`number`&&Number.isFinite(e.remaining)?e.remaining:typeof e.used==`number`&&Number.isFinite(e.used)?t-e.used:null;i!==null&&(n+=Math.min(t,Math.max(0,i)),r+=t,a=!0)}return i>0&&a?{accounts:i,remaining:n,total:r,percent:r>0?Math.round(n/r*100):0}:null}function wt(e){return e.toLocaleString(void 0,{maximumFractionDigits:1})}function Tt({provider:e}){let t=e.credentialUrl,n=e.credentialHint,r=e.operatorNotice;if(!t&&!n&&!r)return null;let i=e.oauthFlows?.browser===!0||e.oauthFlows?.device===!0,a=n??(i?`This provider authorizes through its own login flow; there is no key to paste.`:e.requiresAccount?`Create a credential on the provider site, then add it as an account below.`:`This provider needs no credential.`);return(0,$.jsx)(V,{density:`compact`,children:(0,$.jsx)(B,{children:(0,$.jsxs)(Y,{gap:`12px`,className:`items-center flex-wrap`,children:[(0,$.jsxs)(`span`,{className:`min-w-110 flex-1 text-caption text-text-secondary`,children:[a,r?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`br`,{}),r]}):null]}),t?(0,$.jsxs)(`a`,{href:t,target:`_blank`,rel:`noreferrer`,title:t,className:b({size:`sm`,className:`shrink-0 no-underline`}),children:[(0,$.jsx)(`span`,{className:`btn-icon-wrapper`,"aria-hidden":`true`,children:(0,$.jsx)(et,{size:13})}),i?`Sign in`:`Get API Key`]}):null]})})})}var Et={quota_fetch_failed:`Quota unreachable`,quota_exhausted:`Quota exhausted`,policy_blocked:`Policy blocked`,rate_limit_transient:`Rate limited`,missing_credential:`No credential`},Dt=new Set([`quota_fetch_failed`]);function Ot(e){return e===void 0||e.length===0?!1:!Dt.has(e)}function kt(e){return e===`oauth`?`Re-login required`:`Replace API key`}function At(e,t){return e===`auth_invalidated`?kt(t):Et[e]??e}async function jt(e,t,n){let r=Array(e.length),i=Math.max(1,Math.min(t,e.length)),a=0;return await Promise.all(Array.from({length:i},async()=>{for(;;){let t=a;if(t>=e.length)return;a+=1;try{r[t]={status:`fulfilled`,value:await n(e[t],t)}}catch(e){r[t]={status:`rejected`,reason:e}}}})),r}var Mt=[`access`,`accessToken`,`access_token`,`sessionToken`,`session_token`,`token`,`apiKey`,`api_key`,`key`,`credential`,`pat`,`secret`],Nt=[`refresh`,`refreshToken`,`refresh_token`],Pt=[`credentialKind`,`providerId`,`accessToken`],Ft=[`accounts`,`items`,`connections`],It=[`email`,`name`,`accountId`,`account_id`,`id`,`login`,`username`];function Lt(e){if(typeof e==`object`&&e&&!Array.isArray(e))return Object.fromEntries(Object.entries(e))}function Rt(e){let t=e.data;if(typeof t==`string`)try{return Lt(JSON.parse(t))}catch{return}return Lt(t)}function zt(e){for(let t of Mt){let n=e[t];if(typeof n==`string`&&n.trim().length>0)return{value:n.trim(),extracted:!0,source:t}}let t=Rt(e);if(t)for(let e of Mt){let n=t[e];if(typeof n==`string`&&n.trim().length>0)return{value:n.trim(),extracted:!0,source:`data.${e}`}}}function Bt(e){for(let t of It){let n=e[t];if(typeof n==`string`&&n.trim().length>0)return n.trim()}let t=Rt(e);if(t)for(let e of It){let n=t[e];if(typeof n==`string`&&n.trim().length>0)return n.trim()}}function Vt(e){let t=e=>Nt.some(t=>typeof e[t]==`string`||typeof e[t]==`number`);if(t(e))return!0;let n=Rt(e);return n?t(n):!1}function Ht(e){let t=e.trim().split(`.`);if(t.length===3)try{let e=t[1].replaceAll(`-`,`+`).replaceAll(`_`,`/`),n=e.padEnd(e.length+(4-e.length%4)%4,`=`);return Lt(JSON.parse(atob(n)))}catch{return}}function Ut(e){let t=Ht(e)?.exp;if(typeof t!=`number`||!Number.isFinite(t))return;let n=new Date(t*1e3);return Number.isFinite(n.getTime())?n.toISOString():void 0}function Wt(e){let t={},n=0;for(let r of e.split(/\r?\n/)){let e=/^\s*([A-Za-z_][\w-]*)\s*:\s*(.*)$/.exec(r),i=e?.[1],a=e?.[2];i!==void 0&&a!==void 0&&(t[i]=a.trim(),n+=1)}return n>0?t:void 0}function Gt(e){if(e.startsWith(`{`)||e.startsWith(`[`))try{return JSON.parse(e)}catch{return}}function Kt(e){let t=e.trim(),n=Lt(Gt(t))??Wt(t);return n&&Vt(n)?`oauth`:Ht((n?zt(n)?.value:void 0)??t)===void 0?`api_key`:`jwt`}function qt(e){return e.length!==0&&!!(e.some(e=>Array.isArray(e.cookies)&&(typeof e.domain==`string`||typeof e.originalUrl==`string`))||e.every(e=>typeof e.name==`string`&&typeof e.value==`string`&&(e.domain!==void 0||e.path!==void 0||e.expirationDate!==void 0)))}function Jt(e,t){let n,r=!1,i=(e,t)=>{let i=e.toLowerCase();(i===`userid`||i===`uid`||i===`accountid`||i===`cuserid`)&&(n||=t.replace(/^"|"$/g,``).trim()),(i.includes(`token`)||i.includes(`ph`)||i.includes(`auth`)||i.includes(`session`))&&(r=!0)};for(let e of t)if(Array.isArray(e.cookies)){for(let t of e.cookies)if(t&&typeof t==`object`){let e=t;typeof e.name==`string`&&typeof e.value==`string`&&i(e.name,e.value)}}else typeof e.name==`string`&&typeof e.value==`string`&&i(e.name,e.value);return{value:e,kind:r?`oauth`:`api_key`,...n?{identity:n}:{}}}function Yt(e){let t=e.credentialKind;if(typeof t==`string`&&typeof e.accessToken==`string`&&Pt.every(t=>t in e)){let n=typeof e.label==`string`&&e.label.trim().length>0?e.label.trim():void 0,r=e.accessToken,i=t===`oauth`&&Vt(e);return{value:i?JSON.stringify(e):r,kind:i?`oauth`:`api_key`,...n?{identity:n}:{}}}let n=zt(e),r=Vt(e)?`oauth`:Kt(n?.value??JSON.stringify(e)),i=r===`oauth`?JSON.stringify(e):n?.value??JSON.stringify(e),a=Bt(e);return a?{value:i,kind:r,identity:a}:{value:i,kind:r}}function Xt(e){for(let t of Ft){let n=e[t];if(!Array.isArray(n))continue;let r=n.map(e=>Lt(e)).filter(e=>e!==void 0);if(r.length>0)return r}}function Zt(e){let t=e.trim();if(!t)return[];let n=Gt(t);if(Array.isArray(n)){let e=n.map(e=>Lt(e)).filter(e=>e!==void 0);if(e.length>0)return qt(e)?[Jt(t,e)]:e.map(Yt)}else{let e=Lt(n);if(e){let t=Xt(e);return t?t.map(Yt):[Yt(e)]}}let r=t.split(/\r?\n/).map(e=>e.trim()).filter(e=>e.length>0);if(r.length===0)return[];if(r.length===1)return Qt(r[0]);let i=Wt(t);return i&&(zt(i)||Object.keys(i).length===r.length)?[Yt(i)]:r.flatMap(Qt)}function Qt(e){let t=Lt(Gt(e));if(t){let e=Xt(t);return e?e.map(Yt):[Yt(t)]}return[{value:e,kind:Kt(e)}]}function $t(e,t,n){let r=new Set(n),i=1;return e.map(e=>{let n=e.identity;if(!n){for(;r.has(`${t}-${i}`);)i+=1;n=`${t}-${i}`,i+=1}let a=n,o=2;for(;r.has(a);)a=`${n} (${o++})`;return r.add(a),a})}function en(e){return e===`active`?0:e===`cooldown`?2:3}function tn(e){if(e===void 0)return;let t=new Date(e).getTime();if(Number.isFinite(t))return t<=Date.now()?`Expired ${new Date(e).toLocaleDateString()}`:X(e,!1)}function nn({cooldowns:e,reason:t}){if(!e)return null;let n=X(e.until),r=`Soonest: ${e.modelId} — ${n}`;return(0,$.jsxs)(G,{tone:`warn`,dot:!0,title:t?`${t} — ${r}`:r,children:[e.count,` model`,e.count===1?``:`s`,` cooling · `,n]})}function rn(e){if(e.credentialKind===`oauth`)return`OAuth`;if(e.credentialMode===`jwt`)return`JWT`}function an(e){return e.credentialKind===`oauth`?`blue`:`ok`}function on({account:e}){let t=e.cooldownUntil?new Date(e.cooldownUntil).getTime():NaN,n=Number.isFinite(t)&&t>Date.now(),r=Xe(e);if(e.status===`disabled`){let t=rn(e),n=e.lastErrorCategory===`auth_invalidated`;return(0,$.jsxs)(Y,{gap:`4px`,children:[(0,$.jsxs)(G,{tone:`disabled`,dot:!0,title:e.lastError,children:[`Disabled`,t?` - ${t}`:``]}),n?(0,$.jsx)(G,{tone:`warn`,title:e.lastError,children:kt(e.credentialKind)}):Ot(e.lastErrorCategory)&&!(e.lastErrorCategory===`quota_exhausted`&&r)?(0,$.jsx)(G,{tone:`warn`,title:e.lastError??e.lastErrorCategory,children:At(e.lastErrorCategory,e.credentialKind)}):null,(0,$.jsx)(nn,{cooldowns:r,reason:e.lastErrorCategory===`quota_exhausted`?e.lastError:void 0})]})}return e.status===`active`?(0,$.jsxs)(Y,{gap:`4px`,children:[(0,$.jsxs)(G,{tone:an(e),dot:!0,children:[`Active`,rn(e)?` - ${rn(e)}`:``]}),Ot(e.lastErrorCategory)&&!(e.lastErrorCategory===`quota_exhausted`&&r)?(0,$.jsx)(G,{tone:`warn`,title:e.lastError??e.lastErrorCategory,children:At(e.lastErrorCategory,e.credentialKind)}):null,(0,$.jsx)(nn,{cooldowns:r,reason:e.lastErrorCategory===`quota_exhausted`?e.lastError:void 0})]}):e.status===`cooldown`||n?(0,$.jsxs)(Y,{gap:`4px`,children:[(0,$.jsxs)(G,{tone:`warn`,dot:!0,children:[`Cooldown`,rn(e)?` - ${rn(e)}`:``,` `,e.cooldownUntil?`(${X(e.cooldownUntil)})`:``]}),Ot(e.lastErrorCategory)&&!(e.lastErrorCategory===`quota_exhausted`&&r)?(0,$.jsx)(G,{tone:`warn`,title:e.lastError??e.lastErrorCategory,children:At(e.lastErrorCategory,e.credentialKind)}):null,(0,$.jsx)(nn,{cooldowns:r,reason:e.lastErrorCategory===`quota_exhausted`?e.lastError:void 0})]}):(0,$.jsx)(G,{tone:`disabled`,children:`Disabled`})}function sn({windows:e}){if(e===void 0||e.length===0)return null;let t=0,n=0,r=!1,i=null;for(let a of e){if(a.accounting!==`pooled`){typeof a.remainingPercent==`number`&&Number.isFinite(a.remainingPercent)&&(i=i===null?a.remainingPercent:Math.min(i,a.remainingPercent));continue}let e=typeof a.limit==`number`&&Number.isFinite(a.limit)?a.limit:null,o=typeof a.remaining==`number`&&Number.isFinite(a.remaining)?a.remaining:e!==null&&typeof a.used==`number`&&Number.isFinite(a.used)?e-a.used:null;o!==null&&e!==null&&(t+=Math.max(0,o),n+=e,r=!0)}let a=null;return r?a=`${cn(t)} of ${cn(n)}`:i!==null&&(a=`${Math.round(i)}% left`),a===null?null:(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-2.5 max-w-full px-3.5 py-1 border border-inner-border rounded-chip bg-surface-1 text-text-secondary text-badge leading-normal whitespace-nowrap`,"data-tone":r&&t<=0||(i??100)<=10?`warn`:void 0,title:r?`${cn(t)} credits available of ${cn(n)}`:`Lowest remaining percent across this account's quota windows`,children:[(0,$.jsx)(`span`,{className:`text-text-tertiary text-micro font-semibold uppercase tracking-label`,children:`Quota`}),a]})}function cn(e){return e.toLocaleString(void 0,{maximumFractionDigits:1})}function ln({providerId:e,account:t,onClose:n}){let r=de(),[i,a]=(0,Q.useState)(``),o=t.label||t.id.slice(0,8),s=r.isPending,c=i.trim().length>0&&!s,l=async()=>{try{a(await navigator.clipboard.readText())}catch{x.error(`Clipboard access denied`)}};return(0,$.jsx)(P,{open:!0,onClose:n,title:`Replace API key — ${o}`,width:560,footer:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(y,{variant:`secondary`,size:`sm`,onClick:n,disabled:s,children:`Cancel`}),(0,$.jsx)(y,{size:`sm`,variant:`primary`,disabled:!c,onClick:()=>{let a=i.trim();a&&r.mutate({providerId:e,accountId:t.id,request:{secret:a}},{onSuccess:()=>{x.success(`API key replaced`,o),n()},onError:e=>{let t=e instanceof Error?e.message:`Unable to update account`;x.error(`Failed to replace key`,t)}})},children:s?`Saving…`:`Replace key`})]}),children:(0,$.jsxs)(`div`,{className:`flex flex-col gap-5`,children:[(0,$.jsx)(`p`,{className:`m-0 text-caption text-text-secondary`,children:`Paste the new key for this account. The old key stops working immediately; the account keeps its label, history, and routing.`}),(0,$.jsxs)(J,{gap:`6px`,className:`min-w-0`,children:[(0,$.jsx)(`label`,{className:`text-caption font-semibold text-text-secondary`,children:`New API key`}),(0,$.jsx)(`textarea`,{value:i,onChange:e=>a(e.target.value),placeholder:`Paste the replacement key…`,rows:4,spellCheck:!1,autoFocus:!0,className:`font-mono tabular-nums w-full min-w-0 min-h-65 rounded-control border border-inner-border bg-input-bg px-6 py-5 text-caption text-text-primary resize-y box-border`}),(0,$.jsx)(Y,{gap:`8px`,className:`justify-end`,children:(0,$.jsx)(y,{variant:`secondary`,size:`sm`,onClick:()=>void l(),children:`Paste`})})]})]})})}function un({providerId:e,account:t,inflight:n,quota:r,selected:a,onToggleSelect:o,onDelete:s}){let c=de(),l=ve(),u=qe(t.id),d=t.status===`disabled`,f=t.cooldownUntil?new Date(t.cooldownUntil).getTime():NaN,p=Number.isFinite(f)&&f>Date.now(),m=t.status===`cooldown`||p,[g,_]=(0,Q.useState)(!1),[b,S]=(0,Q.useState)(!1),[,C]=(0,Q.useState)(0),[w,T]=(0,Q.useState)(!1),[E,D]=(0,Q.useState)(``),O=I(e),ee=(t.label?.match(/[^\s@]+@[^\s@]+/)?.[0]??t.label)||t.id.slice(0,8),k=O.enabled?`Mysterious accounts`:ee,A=tn(t.tokenExpiresAt),j=Ye(t),te=Math.max(p&&t.cooldownUntil?f:0,j??0);(0,Q.useEffect)(()=>{if(te<=Date.now())return;let e=setInterval(()=>C(e=>e+1),1e3);return()=>clearInterval(e)},[te]);let N=()=>{let n=E.trim();T(!1),n&&n!==(t.label??``)&&c.mutate({providerId:e,accountId:t.id,request:{label:n}},{onSuccess:()=>x.success(`Account renamed`,n),onError:e=>x.error(`Rename failed`,e.message??`Unable to rename account`)})};return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`account-row account-row-grid grid items-center gap-5 px-5 py-4 border rounded-control bg-surface-2 ${a?`border-accent`:`border-inner-border`} hover:bg-hover`,role:`listitem`,"data-selected":a?`true`:void 0,style:{opacity:d?.62:1},children:[(0,$.jsx)(`div`,{className:`flex items-center`,children:(0,$.jsx)(`input`,{type:`checkbox`,checked:a,onChange:e=>o(t.id,e.target.checked),"aria-label":`Select ${k}`,className:`cursor-pointer`})}),(0,$.jsxs)(`div`,{className:`min-w-0 flex flex-col gap-1.5`,children:[(0,$.jsx)(`div`,{className:`flex items-center gap-3 min-w-0`,children:w?(0,$.jsx)(K,{value:E,onChange:e=>D(e.target.value),onKeyDown:e=>{e.key===`Enter`&&N(),e.key===`Escape`&&T(!1)},onBlur:N,autoFocus:!0,"aria-label":`Account label`,className:`text-body max-w-120`}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`text-body font-semibold text-text-primary min-w-0 overflow-hidden text-ellipsis whitespace-nowrap`,title:t.label||t.id,children:k}),(0,$.jsx)(`button`,{type:`button`,className:`shrink-0 grid place-items-center w-10 h-10 p-0 border-0 bg-transparent text-text-tertiary cursor-pointer rounded-tiny hover:bg-inner-border hover:text-text-primary`,title:`Rename account`,"aria-label":`Rename ${k}`,onClick:()=>{D(t.label??``),T(!0)},children:(0,$.jsx)(F,{size:11})})]})}),(0,$.jsxs)(`div`,{className:`flex items-center flex-nowrap gap-2 min-w-0 overflow-hidden`,children:[(0,$.jsx)(on,{account:t}),A?(0,$.jsx)(`span`,{className:`inline-flex items-center gap-2.5 max-w-full px-3.5 py-1 border border-inner-border rounded-chip bg-surface-1 text-text-secondary text-badge leading-normal whitespace-nowrap`,title:A,children:A}):null]}),(0,$.jsxs)(`div`,{className:`flex items-center flex-wrap gap-2 min-w-0`,children:[(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-2.5 max-w-full px-3.5 py-1 border border-inner-border rounded-chip bg-surface-1 text-text-secondary text-badge leading-normal whitespace-nowrap`,title:`Today: ${t.usageToday.totalTokens.toLocaleString()} tokens, ${t.usageToday.requests.toLocaleString()} requests`,children:[(0,$.jsx)(`span`,{className:`text-text-tertiary text-micro font-semibold uppercase tracking-label`,children:`Today`}),t.usageToday.totalTokens.toLocaleString(),` tok · `,t.usageToday.requests.toLocaleString(),` req`]}),(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-2.5 max-w-full px-3.5 py-1 border border-inner-border rounded-chip bg-surface-1 text-text-secondary text-badge leading-normal whitespace-nowrap`,title:`Lifetime totals are backfilled from telemetry still retained when tracking starts; new totals survive telemetry cleanup.`,children:[(0,$.jsx)(`span`,{className:`text-text-tertiary text-micro font-semibold uppercase tracking-label`,children:`All time`}),t.usageAllTime.totalTokens.toLocaleString(),` tok · `,t.usageAllTime.requests.toLocaleString(),` req`]}),(0,$.jsx)(sn,{windows:r}),(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-2.5 max-w-full px-3.5 py-1 border border-inner-border rounded-chip bg-surface-1 text-text-secondary text-badge leading-normal whitespace-nowrap`,title:`Concurrency comes from this provider’s Routing Strategy; accounts no longer carry manual ceilings.`,children:[(0,$.jsx)(`span`,{className:`text-text-tertiary text-micro font-semibold uppercase tracking-label`,children:`In flight`}),n?.toLocaleString()??`—`]})]})]}),(0,$.jsxs)(`div`,{className:`account-row-actions flex items-center justify-end gap-3 flex-wrap`,children:[(0,$.jsx)(y,{size:`icon`,variant:`secondary`,icon:(0,$.jsx)(i,{size:12}),label:`Health`,"aria-label":`Health for ${k}`,onClick:()=>_(!0),title:`View Health & Error History`}),(0,$.jsx)(y,{size:`icon`,variant:`secondary`,icon:u.isPending?(0,$.jsx)(v,{size:12,className:`animate-spin`}):(0,$.jsx)(h,{size:12}),label:u.isPending?`Testing…`:`Test`,"aria-label":`Test ${k}`,disabled:u.isPending,onClick:()=>{u.mutate(void 0,{onSuccess:e=>{e?.ok?x.success(`Account test passed`,k):x.error(`Account test failed`,e?.message??`Provider reported an error`)},onError:e=>x.error(`Account test failed`,e.message??`Unable to test account`)})},title:`Refresh quota and health for this account`}),(0,$.jsx)(y,{size:`icon`,variant:`secondary`,icon:(0,$.jsx)(M,{size:12}),label:`Edit key`,"aria-label":`Replace API key for ${k}`,onClick:()=>S(!0),title:`Replace API key`}),(0,$.jsx)(y,{size:`icon`,variant:`secondary`,icon:d?(0,$.jsx)(nt,{size:12}):(0,$.jsx)(re,{size:12}),label:d?`Enable`:`Disable`,"aria-label":d?`Enable ${k}`:`Disable ${k}`,disabled:c.isPending,onClick:()=>{let n=d;c.mutate({providerId:e,accountId:t.id,request:{status:n?`active`:`disabled`}},{onSuccess:()=>x.success(n?`Account enabled`:`Account disabled`,k),onError:e=>x.error(`Update failed`,e.message??`Unable to update account`)})},title:d?`Enable account`:`Disable account`}),m?(0,$.jsx)(y,{size:`icon`,variant:`secondary`,icon:(0,$.jsx)(ae,{size:12,className:l.isPending?`animate-spin`:``}),label:l.isPending?`Recovering…`:`Recover`,"aria-label":`Recover ${k}`,disabled:l.isPending,onClick:()=>l.mutate({providerId:e,accountId:t.id}),title:`Clear cooldown / restore active status`}):null,(0,$.jsx)(y,{size:`icon`,variant:`danger`,icon:(0,$.jsx)(se,{size:12}),label:`Delete`,"aria-label":`Delete ${k}`,onClick:()=>s(t),title:`Delete account`})]})]}),g&&(0,$.jsx)(Je,{summary:{providerId:e,accountId:t.id,title:t.label||t.id.slice(0,8),status:t.status,errorCategory:t.lastErrorCategory??void 0,errorMessage:t.lastError??void 0,emptyMessage:`Status transitions, rate limits, and auto-recoveries will appear here.`,staticToken:t.staticToken===!0,credentialKind:t.credentialKind,credentialMode:t.credentialMode},onClose:()=>_(!1)}),b&&(0,$.jsx)(ln,{providerId:e,account:t,onClose:()=>S(!1)})]})}var dn=[{value:`added-asc`,label:`Added · oldest`},{value:`added-desc`,label:`Added · newest`},{value:`label-asc`,label:`Name · A–Z`},{value:`label-desc`,label:`Name · Z–A`},{value:`status-asc`,label:`Status · active first`},{value:`status-desc`,label:`Status · disabled first`},{value:`lastCheck-desc`,label:`Last check · newest`},{value:`lastCheck-asc`,label:`Last check · oldest`}];function fn(e,t,n){let r=(e,t)=>(e.label||e.id).localeCompare(t.label||t.id)||e.createdAt.localeCompare(t.createdAt)||e.id.localeCompare(t.id);if(n===`added`)return e.sortIndex-t.sortIndex||e.createdAt.localeCompare(t.createdAt)||e.id.localeCompare(t.id);if(n===`label`)return r(e,t);if(n===`status`){let n=en(e.status)-en(t.status);return n===0?r(e,t):n}let i=new Date(e.lastSuccessAt??e.createdAt).getTime();return new Date(t.lastSuccessAt??t.createdAt).getTime()-i||r(e,t)}function pn({providerId:e,accounts:t,onDelete:n,showGrokProbe:r=!1,grokProbePending:i=!1,onGrokProbe:a}){let o=le(),s=de(),c=ve(),l=Te(),u=We(e).data??new Map,p=Ke(),m=(0,Q.useMemo)(()=>{let t=new Map;for(let n of p.data?.accounts??[])n.provider===e&&n.quota&&t.set(n.id,n.quota.windows);return t},[p.data,e]),[g,_]=(0,Q.useState)(``),[v,b]=(0,Q.useState)(new Set),[S,C]=(0,Q.useState)(`added-asc`),[T,E]=(0,Q.useState)(!1),[D,O]=(0,Q.useState)(!1),[ee,k]=(0,Q.useState)(!1),A=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{if(!ee)return;let e=e=>{A.current&&!A.current.contains(e.target)&&k(!1)},t=e=>{e.key===`Escape`&&k(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[ee]);let j=g.trim().toLowerCase(),M=(0,Q.useMemo)(()=>j?t.filter(e=>{let t=`${e.label??``} ${e.id} ${e.credentialKind} ${e.status}`.toLowerCase();return j.split(/\s+/).every(e=>t.includes(e))}):t,[t,j]),te=(0,Q.useMemo)(()=>{let e=S.slice(0,S.lastIndexOf(`-`)),t=S.endsWith(`-desc`)?-1:1,n=[...M];return n.sort((n,r)=>t*fn(n,r,e)),n},[M,S]),N=(0,Q.useMemo)(()=>t.filter(e=>v.has(e.id)),[t,v]),P=M.length>0&&M.every(e=>v.has(e.id)),F=N.some(e=>e.status===`disabled`),ne=N.some(e=>e.status!==`disabled`),I=N.length===0,ie=(e,t)=>{b(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r})},ce=()=>{b(e=>{let t=new Set(e);if(P)for(let e of M)t.delete(e.id);else for(let e of M)t.add(e.id);return t})},pe=async(e,t)=>{if(N.length===0)return;E(!0);let n=await Promise.allSettled(N.map(e=>t(e))),r=n.filter(e=>e.status===`rejected`).length,i=n.length-r;E(!1),r===0?x.success(`${e} complete`,`${i} account${i===1?``:`s`}`):x.error(`${e} partially failed`,`${i} succeeded, ${r} failed`)},me=()=>pe(`Recover`,t=>c.mutateAsync({providerId:e,accountId:t.id})),he=async()=>{if(t.length===0)return;E(!0);let e=await jt(t,3,e=>ue(`/accounts/${encodeURIComponent(e.id)}/quota/refresh`,{method:`POST`})),n=0,r=0;for(let t of e)t.status===`fulfilled`&&t.value?.ok?n+=1:r+=1;await Promise.all([o.invalidateQueries({queryKey:L.quota.all}),o.invalidateQueries({queryKey:L.providers.all})]),E(!1),r===0?x.success(`Test complete`,`${n} passed`):n===0?x.error(`Test failed`,`${r} account${r===1?``:`s`} failed`):x.error(`Test partially failed`,`${n} passed, ${r} failed`)},ge=t=>pe(t?`Enable`:`Disable`,n=>s.mutateAsync({providerId:e,accountId:n.id,request:{status:t?`active`:`disabled`}})),_e=async()=>{if(N.length!==0){E(!0);try{let t=await l.mutateAsync({providerId:e,accountIds:N.map(e=>e.id)}),n=new Date().toISOString().replace(/[:.]/g,`-`);Ie(`${e}-accounts-${n}.json`,JSON.stringify(t,null,2),`application/json`),x.success(`Accounts exported`,`${t.accounts.length} account${t.accounts.length===1?``:`s`} — contains plaintext credentials`)}catch(e){x.error(`Export failed`,e.message??`Unable to export accounts`)}finally{E(!1)}}};return(0,$.jsxs)(J,{gap:`8px`,children:[(0,$.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-2 p-3 border border-inner-border rounded-control bg-surface-2`,children:[(0,$.jsxs)(`label`,{className:`relative min-w-20 flex-[1_1_10rem]`,children:[(0,$.jsx)(oe,{size:13,"aria-hidden":`true`,className:`pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-text-tertiary`}),(0,$.jsx)(K,{id:`accounts-search`,value:g,onChange:e=>_(e.target.value),placeholder:`Search accounts...`,"aria-label":`Search accounts`,className:`pl-9`})]}),(0,$.jsx)(y,{size:`sm`,variant:`primary`,icon:(0,$.jsx)(h,{size:12}),disabled:T||t.length===0,onClick:he,"aria-label":`Test all accounts`,title:`Test every account, regardless of selection or filters`,children:`Test all`}),(0,$.jsxs)(`div`,{ref:A,className:`relative`,children:[(0,$.jsxs)(y,{size:`sm`,variant:`secondary`,disabled:T||I,"aria-expanded":ee,"aria-haspopup":`menu`,"aria-label":I?`Select accounts to enable bulk actions`:`Bulk actions for ${N.length} selected accounts`,onClick:()=>k(e=>!e),children:[`Actions`,I?``:` (${N.length})`,(0,$.jsx)(d,{size:12,"aria-hidden":`true`,className:`transition-transform ${ee?`rotate-180`:``}`})]}),ee&&!I?(0,$.jsxs)(`div`,{role:`menu`,"aria-label":`Selected account actions`,className:`absolute left-0 top-full z-50 mt-1 flex w-64 popover-max flex-col gap-1 rounded-control border border-inner-border bg-popover-bg p-2 shadow-popout sm:left-auto sm:right-0`,children:[(0,$.jsx)(y,{role:`menuitem`,size:`sm`,variant:`ghost`,className:`w-full justify-start`,icon:(0,$.jsx)(ae,{size:12}),disabled:T,onClick:()=>{k(!1),me()},children:`Recover`}),F?(0,$.jsx)(y,{role:`menuitem`,size:`sm`,variant:`ghost`,className:`w-full justify-start`,icon:(0,$.jsx)(nt,{size:12}),disabled:T,onClick:()=>{k(!1),ge(!0)},children:`Enable`}):null,ne?(0,$.jsx)(y,{role:`menuitem`,size:`sm`,variant:`ghost`,className:`w-full justify-start`,icon:(0,$.jsx)(re,{size:12}),disabled:T,onClick:()=>{k(!1),ge(!1)},children:`Disable`}):null,(0,$.jsx)(y,{role:`menuitem`,size:`sm`,variant:`ghost`,className:`w-full justify-start`,icon:(0,$.jsx)(w,{size:12}),disabled:T,onClick:()=>{k(!1),_e()},children:`Export JSON`}),(0,$.jsx)(y,{role:`menuitem`,size:`sm`,variant:`danger`,className:`w-full justify-start`,icon:(0,$.jsx)(se,{size:12}),disabled:T,onClick:()=>{k(!1),O(!0)},children:`Delete`}),(0,$.jsx)(y,{role:`menuitem`,size:`sm`,variant:`ghost`,className:`w-full justify-start`,disabled:T,onClick:()=>{b(new Set),k(!1)},children:`Clear selection`})]}):null]}),(0,$.jsx)(`label`,{className:`inline-flex h-15 shrink-0 items-center gap-2 text-caption font-semibold text-text-secondary [&_.radix-select-trigger]:font-semibold [&_.radix-select-trigger]:bg-hover [&_.radix-select-trigger]:text-text-primary`,children:(0,$.jsx)(f,{size:`sm`,value:S,onValueChange:e=>C(e),options:dn,"aria-label":`Sort accounts by`})}),(0,$.jsxs)(`label`,{className:`inline-flex h-15 shrink-0 items-center gap-2 text-caption font-semibold text-text-secondary`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:P,onChange:ce,"aria-label":`Select accounts`}),(0,$.jsx)(`span`,{children:`Select`})]}),r?(0,$.jsx)(y,{size:`sm`,variant:`secondary`,icon:(0,$.jsx)(h,{size:12,className:i?`animate-spin`:``}),disabled:i||t.length===0,onClick:a,title:`Probe every Grok account with the live 407 streaming request`,children:i?`Testing…`:`Test 407`}):null]}),(0,$.jsx)(`div`,{className:`account-list flex flex-col gap-3 max-h-230 overflow-y-auto pr-1 [container-type:inline-size] [container-name:account-list]`,role:`list`,"aria-label":`Provider accounts`,children:te.map(t=>(0,$.jsx)(un,{providerId:e,account:t,inflight:u.get(t.id)??t.inflight,quota:m.get(t.id),selected:v.has(t.id),onToggleSelect:ie,onDelete:n},t.id))}),(0,$.jsx)(`div`,{className:`flex items-center justify-between text-badge text-text-tertiary`,children:(0,$.jsxs)(`span`,{children:[`Showing `,M.length,` account`,M.length===1?``:`s`,j?` (filtered from ${t.length})`:``]})}),(0,$.jsx)(fe,{open:D,onClose:()=>{T||O(!1)},onConfirm:async()=>{await pe(`Delete`,async e=>{let t=e.tenantId===null?`/global/accounts/${encodeURIComponent(e.id)}`:`/accounts/${encodeURIComponent(e.id)}`;await ue(t,{method:`DELETE`}),o.removeQueries({queryKey:L.quota.account(e.id),exact:!0})}),b(new Set),O(!1),await Promise.all([o.invalidateQueries({queryKey:L.providers.accounts(e)}),o.invalidateQueries({queryKey:L.providers.all}),o.invalidateQueries({queryKey:L.quota.all})])},title:`Delete ${N.length} account${N.length===1?``:`s`}?`,message:`This permanently removes the selected accounts and their credentials. This cannot be undone.`,confirmLabel:`Delete`,danger:!0})]})}var mn=2097152,hn=mn/1048576;function gn({providerId:e,accounts:t,onClose:n}){let r=ye(),i=De(),[a,o]=(0,Q.useState)(``),[s,c]=(0,Q.useState)(``),[l,u]=(0,Q.useState)(!1),[d,p]=(0,Q.useState)(`auto`),m=Zt(s),h=m.length>1,g=m.length===1?m[0]:void 0,_=d===`auto`?g?.kind:d,v=g&&_===`jwt`?Ut(g.value):void 0,S=t.map(e=>e.label),C=h?$t(m,e,S):[],w=e=>{let t=d===`auto`?e.kind===`jwt`?`jwt`:`auto`:d;return{credentialKind:t===`auto`&&e.kind===`oauth`?`oauth`:`api_key`,credentialMode:t,secret:e.value}},T=r.isPending||l,E=async()=>{try{let e=await navigator.clipboard.readText();c(e);let t=Zt(e);if(t.length>1)x.success(`Pasted from clipboard`,`Detected ${t.length} credentials`);else{let e=t[0]?.kind??`api_key`,n=e===`oauth`?`OAuth export`:e===`jwt`?`Static JWT`:`API key`;x.success(`Pasted from clipboard`,`Detected: ${n}`)}}catch{x.error(`Clipboard access denied`)}},D=e=>{if(e.size>mn){x.error(`File too large`,`Credential files must be ${hn} MB or smaller.`);return}let t=new FileReader;t.onload=()=>{let n=typeof t.result==`string`?t.result:``;c(n);let r=Zt(n);if(r.length===0){x.error(`Nothing to import`,`That file held no credential the gateway recognises.`);return}x.success(`Imported ${e.name}`,r.length>1?`Detected ${r.length} credentials`:r[0]?.kind===`oauth`?`Detected: OAuth export`:`Detected: API key`)},t.onerror=()=>x.error(`Could not read that file`),t.readAsText(e)},O=async()=>{if(m.length!==0){if(m.length===1){let t=m[0];r.mutate({providerId:e,request:{label:(a.trim()||t.identity)??void 0,...w(t)}},{onSuccess:()=>{x.success(`Account connected`,`New ${t.kind===`oauth`?`OAuth`:t.kind===`jwt`?`Static JWT`:`API key`} account registered successfully`),n()},onError:e=>x.error(`Failed to add account`,e.message??`Invalid credentials`)});return}u(!0);try{let t=await i.mutateAsync({providerId:e,accounts:m.map((e,t)=>({label:C[t],...w(e)}))}),r=t.results.filter(e=>!e.ok),a=t.created;if(a>0&&x.success(`${a} account${a===1?``:`s`} added`,r.length>0?`${r.length} skipped`:void 0),r.length>0){let e=r.slice(0,5).map(e=>`${C[e.index]??e.index}: ${e.error??`rejected`}`).join(`
|
|
1
|
+
import{n as e,o as t,r as n,t as r}from"./jsx-runtime-CXUMngI_.js";import{i}from"./terminal-C9mZ4Ugm.js";import{t as a}from"./arrow-left-CpBxkoxI.js";import{n as o,t as s}from"./brain-Cwed_72z.js";import{n as c,t as l}from"./fingerprint-pattern-BWuHtbW4.js";import{t as u}from"./check-D69FzdvC.js";import{n as d,t as f}from"./select-CGUuTQmj.js";import{t as p}from"./circle-alert-CntYHV5v.js";import{t as m}from"./circle-check-BU3v_mFW.js";import{g as h,h as g,i as _,m as v,n as y,r as b,t as x}from"./toast-DKAdP2mo.js";import{t as S}from"./cog-CdWhsajs.js";import{t as C}from"./copy-ngmQ9zcZ.js";import{t as w}from"./download-A0SW9OCW.js";import{t as T}from"./eye-off-Bk5g2luF.js";import{t as E}from"./eye-C_hawfH4.js";import{t as D}from"./gauge-BbIMy7MB.js";import{t as O}from"./image-BPaouViG.js";import{a as ee,n as k,r as A,t as j}from"./state-DHKdg-pm.js";import{t as M}from"./key-round-UkavsGxp.js";import{t as te}from"./layers-2-glBbjl.js";import{n as N,t as P}from"./dialog-iocKA3jr.js";import{t as F}from"./pencil-768ysRAr.js";import{t as ne}from"./plus-DIdX_g-x.js";import{i as re,n as I}from"./privacy-mode-CQjbZ3xk.js";import{t as ie}from"./refresh-cw-BqJFk4sU.js";import{t as ae}from"./rotate-ccw-CufcqITi.js";import{t as oe}from"./search-JOKus9rb.js";import{t as se}from"./trash-Cppn5c3R.js";import{t as ce}from"./wrench-B6E1oEuY.js";import{w as le}from"./assert-Bwh6DJTK.js";import{a as ue,t as L}from"./query-keys-ROf-g1Wi.js";import{E as de,F as fe,S as pe,T as me,X as he,Y as ge,Z as _e,_ as ve,a as ye,b as be,c as R,d as xe,f as Se,g as Ce,h as we,l as Te,m as Ee,o as De,p as Oe,r as ke,t as Ae,u as z,v as je,w as Me,x as Ne,y as Pe}from"./entry-C3M9aRLH.js";import{n as B,r as Fe,t as V}from"./card-BTdbRFFg.js";import{n as Ie}from"./download-dRFo5_Wu.js";import{f as Le,i as H,l as Re,n as U,r as ze,s as Be}from"./tokens-DDxMbSRL.js";import{a as W}from"./numbers-CFL4_Dqc.js";import{t as G}from"./badge-BwmwEOgA.js";import{n as K}from"./input-Bn4_kNav.js";import{t as Ve}from"./ProviderIcon-paOCq8I0.js";import{t as q}from"./switch-DIDeAiz9.js";import{t as J}from"./stack-C1kTcOmP.js";import{n as Y,t as He}from"./inline-DCejSLlA.js";import{i as X}from"./quota-DZGyp0N5.js";import{t as Ue}from"./list-row-BLA0sldD.js";import{c as We,l as Ge,m as Z}from"./routing-jntw9-Ui.js";import{o as Ke,s as qe,t as Je}from"./HealthEventsModal-URh6wOhb.js";import{n as Ye,t as Xe}from"./AccountCooldown-ChpdzxRH.js";import{t as Ze}from"./use-timeout-BwcBBRrT.js";import{t as Qe}from"./banner-BKBfKTqn.js";var $e=e(`cable`,[[`path`,{d:`M17 19a1 1 0 0 1-1-1v-2a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2a1 1 0 0 1-1 1z`,key:`trhst0`}],[`path`,{d:`M17 21v-2`,key:`ds4u3f`}],[`path`,{d:`M19 14V6.5a1 1 0 0 0-7 0v11a1 1 0 0 1-7 0V10`,key:`1mo9zo`}],[`path`,{d:`M21 21v-2`,key:`eo0ou`}],[`path`,{d:`M3 5V3`,key:`1k5hjh`}],[`path`,{d:`M4 10a2 2 0 0 1-2-2V6a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2a2 2 0 0 1-2 2z`,key:`1dd30t`}],[`path`,{d:`M7 5V3`,key:`1t1388`}]]),et=e(`external-link`,[[`path`,{d:`M15 3h6v6`,key:`1q9fwt`}],[`path`,{d:`M10 14 21 3`,key:`gplh6r`}],[`path`,{d:`M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6`,key:`a6xqqp`}]]),tt=e(`info`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`M12 16v-4`,key:`1dtifu`}],[`path`,{d:`M12 8h.01`,key:`e9boi3`}]]),nt=e(`lock-open`,[[`rect`,{width:`18`,height:`11`,x:`3`,y:`11`,rx:`2`,ry:`2`,key:`1w4ew1`}],[`path`,{d:`M7 11V7a5 5 0 0 1 9.9-1`,key:`1mm8w8`}]]),rt=e(`package-x`,[[`path`,{d:`M12 22V12`,key:`d0xqtd`}],[`path`,{d:`m16.5 14.5 5 5`,key:`ozpm51`}],[`path`,{d:`m16.5 19.5 5-5`,key:`syf6b9`}],[`path`,{d:`M21 10.5V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.729l7 4a2 2 0 0 0 2 .001l.13-.074`,key:`isw6gs`}],[`path`,{d:`M3.29 7 12 12l8.71-5`,key:`19ckod`}],[`path`,{d:`m7.5 4.27 8.997 5.148`,key:`9yrvtv`}]]),it=e(`repeat`,[[`path`,{d:`m17 2 4 4-4 4`,key:`nntrym`}],[`path`,{d:`M3 11v-1a4 4 0 0 1 4-4h14`,key:`84bu3i`}],[`path`,{d:`m7 22-4-4 4-4`,key:`1wqhfi`}],[`path`,{d:`M21 13v1a4 4 0 0 1-4 4H3`,key:`1rx37r`}]]),at=e(`video`,[[`path`,{d:`m16 13 5.223 3.482a.5.5 0 0 0 .777-.416V7.87a.5.5 0 0 0-.752-.432L16 10.5`,key:`ftymec`}],[`rect`,{x:`2`,y:`6`,width:`14`,height:`12`,rx:`2`,key:`158x01`}]]),ot=e(`waypoints`,[[`path`,{d:`m10.586 5.414-5.172 5.172`,key:`4mc350`}],[`path`,{d:`m18.586 13.414-5.172 5.172`,key:`8c96vv`}],[`path`,{d:`M6 12h12`,key:`8npq4p`}],[`circle`,{cx:`12`,cy:`20`,r:`2`,key:`144qzu`}],[`circle`,{cx:`12`,cy:`4`,r:`2`,key:`muu5ef`}],[`circle`,{cx:`20`,cy:`12`,r:`2`,key:`1xzzfp`}],[`circle`,{cx:`4`,cy:`12`,r:`2`,key:`1hvhnz`}]]),st=[`auto`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function ct(e,t){return t===null?e:`${e}(${t})`}var Q=t(n(),1),$=r();function lt({to:e,label:t}){let n=ge();return(0,$.jsxs)(`button`,{type:`button`,onClick:()=>{window.history.length>1?n(-1):n(e)},className:`inline-flex items-center gap-3 text-accent text-caption bg-transparent border-0 p-0 cursor-pointer`,children:[(0,$.jsx)(a,{size:14,"aria-hidden":`true`}),t]})}function ut({title:e,description:t,icon:n,badges:r,actions:i,back:a}){return(0,$.jsxs)(`div`,{className:`flex flex-col gap-5`,children:[a?(0,$.jsx)(lt,{...a}):null,(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-6 flex-wrap`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-5 min-w-0`,children:[n?(0,$.jsx)(`div`,{className:`card-header-icon`,children:n}):null,(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-4 flex-wrap`,children:[(0,$.jsx)(`h1`,{className:`text-lead font-bold`,children:e}),r]}),t?(0,$.jsx)(`p`,{className:`mt-1 text-badge text-text-tertiary`,children:t}):null]})]}),i?(0,$.jsx)(`div`,{className:_(`flex items-center gap-4 flex-wrap min-w-0 max-w-full`),children:i}):null]})]})}function dt(e){return e.isBuiltIn&&e.requiresAccount&&e.oauthFlows===void 0&&!e.hasAdapterUserAgent}function ft(e,t=600){let n=(0,Q.useRef)(void 0);return(0,Q.useEffect)(()=>()=>clearTimeout(n.current),[]),r=>{clearTimeout(n.current),n.current=setTimeout(()=>e(r),t)}}var pt={fallback:`Failover`,roundRobin:`Round robin`},mt=new Set([`inferhub`,`cline`]);function ht(e,t){let n=Ge(e),r=Z(),[i,a]=(0,Q.useState)(`fallback`),[o,s]=(0,Q.useState)(1),[c,l]=(0,Q.useState)(null),[u,d]=(0,Q.useState)(null),[f,p]=(0,Q.useState)(null),[m,h]=(0,Q.useState)(`percent`),[g,_]=(0,Q.useState)(!1),[v,y]=(0,Q.useState)(``);(0,Q.useEffect)(()=>{n.data&&(a(n.data.strategy),s(n.data.rotateCount),l(n.data.maxInflight),d(n.data.maxInflightPerProxy??null),p(n.data.usageFloor),h(n.data.usageFloorUnit),_(n.data.skipProxy),y(n.data.userAgent))},[n.data]);let b=i=>{r.mutate({providerId:e,request:{enabled:!0,strategy:i.strategy,rotateCount:i.rotateCount,maxInflight:i.maxInflight,maxInflightPerProxy:i.maxInflightPerProxy,usageFloor:i.usageFloor,usageFloorUnit:i.usageFloorUnit,skipProxy:i.skipProxy,...t?{userAgent:i.userAgent}:{}}},{onError:()=>{n.data&&(a(n.data.strategy),s(n.data.rotateCount),l(n.data.maxInflight),d(n.data.maxInflightPerProxy??null),p(n.data.usageFloor),h(n.data.usageFloorUnit),_(n.data.skipProxy),y(n.data.userAgent))}})},x=ft(e=>b({strategy:i,rotateCount:o,maxInflight:e,maxInflightPerProxy:u,usageFloor:f,usageFloorUnit:m,skipProxy:g,userAgent:v})),S=ft(e=>b({strategy:i,rotateCount:o,maxInflight:c,maxInflightPerProxy:e,usageFloor:f,usageFloorUnit:m,skipProxy:g,userAgent:v})),C=ft(e=>b({strategy:i,rotateCount:e,maxInflight:c,maxInflightPerProxy:u,usageFloor:f,usageFloorUnit:m,skipProxy:g,userAgent:v})),w=ft(e=>b({strategy:i,rotateCount:o,maxInflight:c,maxInflightPerProxy:u,usageFloor:f,usageFloorUnit:m,skipProxy:g,userAgent:e}));return{strategy:i,maxInflight:c,maxInflightPerProxy:u,usageFloor:f,usageFloorUnit:m,setUsageFloor:(e,t)=>{p(e),h(t),b({strategy:i,rotateCount:o,maxInflight:c,maxInflightPerProxy:u,usageFloor:e,usageFloorUnit:t,skipProxy:g,userAgent:v})},skipProxy:g,userAgent:v,isLoading:n.isPending,isError:n.isError,isSaving:r.isPending,saveFailed:r.isError,refetch:()=>n.refetch(),setMaxInflight:e=>{l(e),x(e)},setMaxInflightPerProxy:e=>{d(e),S(e)},setUserAgent:e=>{y(e),w(e)},setSkipProxy:e=>{_(e),b({strategy:i,rotateCount:o,maxInflight:c,maxInflightPerProxy:u,usageFloor:f,usageFloorUnit:m,skipProxy:e,userAgent:v})},roundRobinEnabled:i===`round_robin`,setRoundRobinEnabled:e=>{let t=e?`round_robin`:`fallback`;a(t),b({strategy:t,rotateCount:o,maxInflight:c,maxInflightPerProxy:u,usageFloor:f,usageFloorUnit:m,skipProxy:g,userAgent:v})},rotateCount:o,setRotateCount:e=>{s(e),C(e)}}}var gt=50,_t=100;function vt(e,t,n){return[{value:``,label:`None`},{value:`Cartethyia/${e}`,label:`Cartethyia ${e}`},{value:`codex_cli_rs/${t}`,label:`Codex`},{value:`claude-cli/${n} (external, cli)`,label:`Claude Code`}]}function yt({children:e,action:t}){return(0,$.jsx)(Ue,{actions:t,children:e})}function bt({providerId:e,clientVersion:t,routeIdentityVersions:n,userAgentEditable:r}){let i=ht(e,r),[a,o]=(0,Q.useState)(!1),s=mt.has(e),c=vt(Ae,n.codex,n.claude),u=c.some(e=>e.value===i.userAgent)?c:[...c,{value:i.userAgent,label:`Custom`}];if(i.isLoading)return(0,$.jsx)(A,{label:`Loading routing...`});if(i.isError)return(0,$.jsx)(k,{message:`Failed to load routing`,onRetry:i.refetch});let d=i.roundRobinEnabled?`${pt.roundRobin} · ${i.rotateCount} account${i.rotateCount===1?``:`s`} per rotation`:pt.fallback,p=i.isSaving?`Saving...`:i.saveFailed?`Save failed — reverted to last saved value`:`Active: ${d}`,m=i.maxInflight===null,h=m?51:Math.min(51,Math.max(1,i.maxInflight)),g=m?`∞`:String(i.maxInflight),_=i.maxInflightPerProxy===null,v=_?51:Math.min(51,Math.max(1,i.maxInflightPerProxy)),b=_?`∞`:String(i.maxInflightPerProxy),S=i.skipProxy,C=e=>{i.setRotateCount(Math.min(1e3,Math.max(1,i.rotateCount+e)))},w=e=>{if(e===i.userAgent)return;i.setUserAgent(e);let t=u.find(t=>t.value===e)?.label??e;x.success(`Client identity updated`,t)},T=t?`${t.client} ${t.version}`:`Provider default`;return(0,$.jsxs)(V,{children:[(0,$.jsx)(Fe,{title:`Routing Strategy`,subtitle:p,icon:(0,$.jsx)(te,{size:16})}),(0,$.jsx)(B,{children:(0,$.jsxs)(`div`,{className:`grid gap-5 w-full min-w-0`,children:[(0,$.jsx)(yt,{action:(0,$.jsxs)($.Fragment,{children:[i.roundRobinEnabled?(0,$.jsxs)(`div`,{role:`group`,"aria-label":`Accounts per rotation`,className:`inline-flex items-center gap-1 rounded-control border border-inner-border bg-surface-1 p-1`,children:[(0,$.jsx)(`span`,{className:`px-2 text-badge text-text-secondary`,children:`Accounts/rotation`}),(0,$.jsx)(y,{variant:`ghost`,size:`icon`,className:`size-9 rounded-tiny`,"aria-label":`Decrease accounts per rotation`,disabled:i.rotateCount<=1,icon:(0,$.jsx)(N,{size:14}),onClick:()=>C(-1)}),(0,$.jsx)(`output`,{className:`min-w-8 text-center text-body font-semibold tabular-nums`,"aria-live":`polite`,children:i.rotateCount}),(0,$.jsx)(y,{variant:`ghost`,size:`icon`,className:`size-9 rounded-tiny`,"aria-label":`Increase accounts per rotation`,disabled:i.rotateCount>=1e3,icon:(0,$.jsx)(ne,{size:14}),onClick:()=>C(1)})]}):null,(0,$.jsx)(q,{checked:i.roundRobinEnabled,onChange:i.setRoundRobinEnabled,id:`routing-round-robin`})]}),children:(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`label`,{htmlFor:`routing-round-robin`,children:(0,$.jsxs)(Y,{gap:`6px`,className:`text-body font-semibold`,children:[(0,$.jsx)(it,{size:15,"aria-hidden":`true`,className:`shrink-0 ${i.roundRobinEnabled?`text-accent`:`text-text-tertiary`}`}),`Round robin`]})}),(0,$.jsx)(`div`,{className:`mt-1 text-badge text-text-tertiary`,children:`Off uses priority order with failover. On rotates requests across this provider's accounts.`})]})}),(0,$.jsx)(yt,{action:(0,$.jsx)(q,{checked:i.skipProxy,onChange:i.setSkipProxy,id:`routing-skip-proxy`}),children:(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`label`,{htmlFor:`routing-skip-proxy`,children:(0,$.jsxs)(Y,{gap:`6px`,className:`text-body font-semibold`,children:[(0,$.jsx)($e,{size:15,"aria-hidden":`true`,className:`shrink-0 ${i.skipProxy?`text-accent`:`text-text-tertiary`}`}),`Always direct`]})}),(0,$.jsx)(`div`,{className:`mt-1 text-badge text-text-tertiary`,children:`Bypass automatic proxy-pool routing for this provider and always dial direct`})]})}),(0,$.jsxs)(`div`,{className:`routing-controls-grid grid gap-5 min-w-0 w-full`,children:[(0,$.jsxs)(`div`,{className:`px-6 py-5 rounded-control border border-inner-border bg-surface-2 min-w-0`,children:[(0,$.jsxs)(Y,{gap:`6px`,className:`text-body font-semibold mb-3`,children:[(0,$.jsx)(l,{size:15,"aria-hidden":`true`,className:`text-text-tertiary shrink-0`}),`Client identity`]}),r?(0,$.jsx)(f,{id:`routing-user-agent-preset`,"aria-label":`Client identity`,value:i.userAgent,options:u,onValueChange:w}):(0,$.jsx)(f,{id:`routing-user-agent-fixed`,"aria-label":`Client identity`,disabled:!0,value:T,options:[{value:T,label:T}]}),(0,$.jsx)(`div`,{className:`text-badge text-text-tertiary mt-2`,children:r?`Sent when the provider has no identity of its own.`:`Set by the provider. It cannot be changed.`})]}),(0,$.jsxs)(`div`,{className:`px-6 py-5 rounded-control border border-inner-border bg-surface-2 min-w-0`,children:[(0,$.jsx)(`label`,{htmlFor:`routing-max-inflight`,className:`form-label`,children:(0,$.jsxs)(Y,{gap:`6px`,className:`text-body font-semibold`,children:[(0,$.jsx)(D,{size:15,"aria-hidden":`true`,className:`text-text-tertiary shrink-0`}),`Max inflight / account`]})}),(0,$.jsxs)(`div`,{className:`text-badge text-text-tertiary mb-3`,children:[`Shared provider ceiling. One step past `,gt,` is unlimited.`]}),(0,$.jsxs)(Y,{gap:`10px`,className:`mt-3`,children:[(0,$.jsx)(`input`,{id:`routing-max-inflight`,type:`range`,className:`routing-slider flex-1 min-w-0`,"data-unlimited":m?`true`:void 0,min:1,max:51,step:1,value:h,"aria-valuetext":m?`Unlimited`:String(i.maxInflight),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&i.setMaxInflight(t>gt?null:Math.round(t))},style:{"--slider-pct":`${h/51*100}%`}}),(0,$.jsx)(`input`,{type:`text`,inputMode:`numeric`,"aria-label":`Max inflight per account`,value:g,onChange:e=>{let t=e.target.value.trim();if(t===``||t===`∞`){i.setMaxInflight(null);return}let n=Number(t);Number.isFinite(n)&&n>=1&&i.setMaxInflight(Math.min(_t,Math.round(n)))},className:`form-input w-26 shrink-0 px-2 py-3 text-center text-body ${m?`text-status-success`:``}`})]})]})]}),(0,$.jsxs)(`div`,{className:`px-6 py-5 rounded-control border border-inner-border bg-surface-2 min-w-0${S?` opacity-60`:``}`,children:[(0,$.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,$.jsxs)(`label`,{htmlFor:`routing-max-inflight-per-proxy`,className:`min-w-0`,children:[(0,$.jsxs)(Y,{gap:`6px`,className:`text-body font-semibold`,children:[(0,$.jsx)(ot,{size:15,"aria-hidden":`true`,className:`text-text-tertiary shrink-0`}),`Max inflight / proxy`]}),(0,$.jsx)(`div`,{className:`mt-1 text-badge text-text-tertiary`,children:`Each proxy pool carries at most this many concurrent requests for this provider. Other providers on the same pool are unaffected.`})]}),(0,$.jsx)(y,{variant:`ghost`,size:`sm`,className:`shrink-0`,"aria-label":`How per-proxy limits work`,onClick:()=>o(!0),children:`How it works`})]}),(0,$.jsxs)(Y,{gap:`10px`,className:`mt-3`,children:[(0,$.jsx)(`input`,{id:`routing-max-inflight-per-proxy`,type:`range`,className:`routing-slider flex-1 min-w-0`,"data-unlimited":_?`true`:void 0,min:1,max:51,step:1,disabled:S,value:v,"aria-valuetext":_?`Unlimited`:String(i.maxInflightPerProxy),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&i.setMaxInflightPerProxy(t>gt?null:Math.round(t))},style:{"--slider-pct":`${v/51*100}%`}}),(0,$.jsx)(`input`,{type:`text`,inputMode:`numeric`,"aria-label":`Max inflight per proxy`,disabled:S,value:b,onChange:e=>{let t=e.target.value.trim();if(t===``||t===`∞`){i.setMaxInflightPerProxy(null);return}let n=Number(t);Number.isFinite(n)&&n>=1&&i.setMaxInflightPerProxy(Math.min(_t,Math.round(n)))},className:`form-input w-26 shrink-0 px-2 py-3 text-center text-body ${_?`text-status-success`:``}`})]}),(0,$.jsx)(`div`,{className:`mt-2 text-badge text-text-tertiary`,children:S?`Always direct is on, so this provider never dials a pool. The limit is kept for when a pool is used again.`:`One step past ${gt} is unlimited.`})]}),(0,$.jsx)(P,{open:a,onClose:()=>o(!1),title:`How concurrency limits stack`,size:`md`,children:(0,$.jsxs)(`div`,{className:`grid gap-4 text-body`,children:[(0,$.jsx)(`p`,{className:`text-text-secondary`,children:`Three limits apply at once. Each one bounds a different thing; none replaces another.`}),(0,$.jsxs)(`dl`,{className:`grid gap-3`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`font-semibold`,children:`Max inflight / account`}),(0,$.jsx)(`dd`,{className:`text-badge text-text-tertiary`,children:`One account of this provider, across every proxy. Set here, above.`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`font-semibold`,children:`Max inflight / proxy`}),(0,$.jsxs)(`dd`,{className:`text-badge text-text-tertiary`,children:[`One proxy pool's concurrent requests `,(0,$.jsx)(`em`,{children:`for this provider`}),`. The same number applies to every pool; each pool counts separately. This is the field above.`]})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`font-semibold`,children:`Pool capacity`}),(0,$.jsx)(`dd`,{className:`text-badge text-text-tertiary`,children:`Everything through one pool, all providers combined. Set on the proxy itself, on the Proxies page.`})]})]}),(0,$.jsxs)(`p`,{className:`text-badge text-text-tertiary`,children:[`A request must clear all three. When a pool is full for this provider, the request moves to another pool that still has room; it only fails with`,` `,(0,$.jsx)(`code`,{children:`429`}),` when every pool is full.`]}),(0,$.jsx)(`p`,{className:`text-badge text-text-tertiary`,children:`Unlimited means no counter is kept for this provider, so the limit costs nothing until you set one.`})]})}),s&&(0,$.jsxs)(Y,{gap:`6px`,align:`flex-start`,className:`mt-1 text-badge text-text-tertiary`,children:[(0,$.jsx)(tt,{size:12,className:`shrink-0 mt-0.5`}),(0,$.jsx)(`span`,{children:`This provider doesn't reliably work through a plain HTTP/S proxy — use a SOCKS5 or proxy pool instead if you need to route it.`})]})]})})]})}function xt({providerId:e}){let t=ht(e,!1),n=Ke(),r=We(e),i=(0,Q.useMemo)(()=>Ct(n.data?.accounts??[],e),[n.data,e]),a=(0,Q.useRef)(null),o=(0,Q.useMemo)(()=>[...r.data?.values()??[]].reduce((e,t)=>e+t,0),[r.data]);(0,Q.useEffect)(()=>{if(a.current===null){a.current=o;return}a.current!==o&&(a.current=o,n.refetch())},[o,n]);let[s,c]=(0,Q.useState)(`40`),[l,u]=(0,Q.useState)(`percent`),d=t.usageFloor!==null;(0,Q.useEffect)(()=>{t.usageFloor!==null&&c(String(t.usageFloor)),u(t.usageFloorUnit)},[t.usageFloor,t.usageFloorUnit]);let f=Number(s),p=Number.isInteger(f)&&f>=0&&f<=1e6,m=i===null||i.remaining<=0?`text-status-danger`:i.percent<=10?`text-status-warning`:`text-status-success`,h=(e,n)=>{(e===null||p)&&t.setUsageFloor(e,n)};return(0,$.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,$.jsxs)(`section`,{className:`usage-floor-panel flex flex-col gap-4 px-5 py-4 border border-inner-border rounded-narrow bg-surface-2`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-3 text-body font-semibold text-text-primary`,children:[(0,$.jsx)(D,{size:14}),(0,$.jsx)(`span`,{children:`Usage floor`}),(0,$.jsx)(`span`,{className:`badge border border-warning-line bg-surface-2 text-micro tracking-label text-status-warning`,children:`BETA`})]}),(0,$.jsx)(`p`,{className:`mt-0.5 text-badge leading-normal text-text-tertiary`,children:`Per account. Skip an account once its remaining allowance reaches this, and send the request to the next one.`})]}),(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-4`,children:[i!==null&&(0,$.jsxs)(`div`,{className:`flex min-h-24 min-w-0 flex-[1_1_20rem] flex-col justify-center gap-2 py-2`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1 text-micro font-semibold tracking-label uppercase text-text-tertiary`,children:[(0,$.jsx)(`span`,{children:`Pooled credits`}),(0,$.jsx)(`span`,{className:`text-text-primary`,children:i.accounts}),(0,$.jsx)(`span`,{children:i.accounts===1?`active account`:`active accounts`})]}),(0,$.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1 text-caption font-semibold tabular-nums text-text-primary`,title:`Combined allowance across active accounts; the usage floor is evaluated per account`,children:[(0,$.jsx)(`strong`,{className:`font-bold ${m}`,children:wt(i.remaining)}),(0,$.jsx)(`span`,{className:`font-medium text-text-secondary`,children:`credits available`}),(0,$.jsxs)(`span`,{className:`font-medium opacity-75`,children:[`of `,wt(i.total)]}),(0,$.jsxs)(`span`,{className:`font-bold ${m}`,children:[i.percent,`%`]})]}),(0,$.jsx)(`p`,{className:`text-micro leading-normal text-text-tertiary`,children:t.usageFloor===null?`Floor off · exhausted quota windows are still skipped`:`Floor ${wt(t.usageFloor)} ${t.usageFloorUnit===`credit`?`credits`:`%`} per account`})]}),i===null&&(0,$.jsxs)(`p`,{className:`flex min-h-24 min-w-0 flex-[1_1_20rem] flex-col justify-center gap-2 py-2 text-badge leading-normal text-text-tertiary`,children:[(0,$.jsx)(`span`,{children:`No combined credit balance is available. Separate quota windows are not added together, and exhausted windows are still skipped.`}),(0,$.jsx)(`span`,{className:`text-micro`,children:t.usageFloor===null?`Floor off · exhausted quota windows are still skipped`:`Floor ${wt(t.usageFloor)} ${t.usageFloorUnit===`credit`?`credits`:`%`} per account`})]}),(0,$.jsxs)(`div`,{className:`ml-auto flex max-w-full shrink-0 flex-col items-end justify-center gap-2`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center justify-end gap-x-3 gap-y-2`,children:[(0,$.jsx)(`span`,{className:`text-micro font-semibold tracking-label uppercase text-text-tertiary`,children:`Floor threshold`}),(0,$.jsxs)(`label`,{className:`flex h-12 max-w-full items-center overflow-hidden rounded-tiny border border-inner-border bg-surface-1 focus-within:border-text-tertiary`,children:[(0,$.jsx)(`input`,{type:`number`,min:0,max:1e6,value:d?s:``,placeholder:`40`,disabled:!d,"aria-label":`Usage floor amount`,className:`h-full w-24 border-0 bg-transparent px-3 text-right font-mono text-body font-semibold tabular-nums text-text-primary disabled:text-text-tertiary`,onChange:e=>c(e.target.value),onBlur:()=>{d&&h(f,l)}}),(0,$.jsxs)(`select`,{value:l,disabled:!d,"aria-label":`Usage floor unit`,className:`h-full border-0 border-l border-inner-border bg-hover px-3 text-body font-semibold text-text-secondary disabled:cursor-default disabled:opacity-60`,onChange:e=>{let t=e.target.value===`credit`?`credit`:`percent`;u(t),d&&h(f,t)},children:[(0,$.jsx)(`option`,{value:`percent`,children:`%`}),(0,$.jsx)(`option`,{value:`credit`,children:`credits`})]})]}),(0,$.jsx)(q,{checked:d,label:`Enabled`,"aria-label":`Usage floor`,className:`usage-floor-switch`,onChange:e=>h(e?p?f:40:null,l)})]}),t.saveFailed?(0,$.jsx)(`p`,{role:`alert`,className:`text-right text-micro leading-normal text-status-danger`,children:`Usage floor save failed. The last saved setting has been restored.`}):null]})]})]}),(0,$.jsx)(St,{providerId:e})]})}function St({providerId:e}){let{enabled:t,setEnabled:n}=I(e);return(0,$.jsxs)(`div`,{className:`flex items-center justify-between flex-wrap gap-6 px-6 py-5 border border-inner-border rounded-control bg-surface-2`,children:[(0,$.jsxs)(`div`,{className:`min-w-0 flex-auto basis-110`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-3 text-body font-semibold text-text-primary`,children:[(0,$.jsx)(T,{size:14}),(0,$.jsx)(`span`,{children:`Mysterious accounts`})]}),(0,$.jsx)(`p`,{className:`mt-0.5 text-badge leading-normal text-text-tertiary`,children:`Hide this provider's emails and usernames. Stored in this browser only.`})]}),(0,$.jsx)(`div`,{className:`flex items-center gap-4 shrink-0`,children:(0,$.jsx)(q,{checked:t,"aria-label":`Mysterious accounts`,onChange:n})})]})}function Ct(e,t){let n=0,r=0,i=0,a=!1;for(let o of e)if(o.provider===t&&o.active&&(i+=1,o.quota!==null))for(let e of o.quota.windows){if(e.accounting!==`pooled`)continue;let t=typeof e.limit==`number`&&Number.isFinite(e.limit)?e.limit:null;if(t===null)continue;let i=typeof e.remaining==`number`&&Number.isFinite(e.remaining)?e.remaining:typeof e.used==`number`&&Number.isFinite(e.used)?t-e.used:null;i!==null&&(n+=Math.min(t,Math.max(0,i)),r+=t,a=!0)}return i>0&&a?{accounts:i,remaining:n,total:r,percent:r>0?Math.round(n/r*100):0}:null}function wt(e){return e.toLocaleString(void 0,{maximumFractionDigits:1})}function Tt({provider:e}){let t=e.credentialUrl,n=e.credentialHint,r=e.operatorNotice;if(!t&&!n&&!r)return null;let i=e.oauthFlows?.browser===!0||e.oauthFlows?.device===!0,a=n??(i?`This provider authorizes through its own login flow; there is no key to paste.`:e.requiresAccount?`Create a credential on the provider site, then add it as an account below.`:`This provider needs no credential.`);return(0,$.jsx)(V,{density:`compact`,children:(0,$.jsx)(B,{children:(0,$.jsxs)(Y,{gap:`12px`,className:`items-center flex-wrap`,children:[(0,$.jsxs)(`span`,{className:`min-w-110 flex-1 text-caption text-text-secondary`,children:[a,r?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`br`,{}),r]}):null]}),t?(0,$.jsxs)(`a`,{href:t,target:`_blank`,rel:`noreferrer`,title:t,className:b({size:`sm`,className:`shrink-0 no-underline`}),children:[(0,$.jsx)(`span`,{className:`btn-icon-wrapper`,"aria-hidden":`true`,children:(0,$.jsx)(et,{size:13})}),i?`Sign in`:`Get API Key`]}):null]})})})}var Et={quota_fetch_failed:`Quota unreachable`,quota_exhausted:`Quota exhausted`,policy_blocked:`Policy blocked`,rate_limit_transient:`Rate limited`,missing_credential:`No credential`},Dt=new Set([`quota_fetch_failed`]);function Ot(e){return e===void 0||e.length===0?!1:!Dt.has(e)}function kt(e){return e===`oauth`?`Re-login required`:`Replace API key`}function At(e,t){return e===`auth_invalidated`?kt(t):Et[e]??e}async function jt(e,t,n){let r=Array(e.length),i=Math.max(1,Math.min(t,e.length)),a=0;return await Promise.all(Array.from({length:i},async()=>{for(;;){let t=a;if(t>=e.length)return;a+=1;try{r[t]={status:`fulfilled`,value:await n(e[t],t)}}catch(e){r[t]={status:`rejected`,reason:e}}}})),r}var Mt=[`access`,`accessToken`,`access_token`,`sessionToken`,`session_token`,`token`,`apiKey`,`api_key`,`key`,`credential`,`pat`,`secret`],Nt=[`refresh`,`refreshToken`,`refresh_token`],Pt=[`credentialKind`,`providerId`,`accessToken`],Ft=[`accounts`,`items`,`connections`],It=[`email`,`name`,`accountId`,`account_id`,`id`,`login`,`username`];function Lt(e){if(typeof e==`object`&&e&&!Array.isArray(e))return Object.fromEntries(Object.entries(e))}function Rt(e){let t=e.data;if(typeof t==`string`)try{return Lt(JSON.parse(t))}catch{return}return Lt(t)}function zt(e){for(let t of Mt){let n=e[t];if(typeof n==`string`&&n.trim().length>0)return{value:n.trim(),extracted:!0,source:t}}let t=Rt(e);if(t)for(let e of Mt){let n=t[e];if(typeof n==`string`&&n.trim().length>0)return{value:n.trim(),extracted:!0,source:`data.${e}`}}}function Bt(e){for(let t of It){let n=e[t];if(typeof n==`string`&&n.trim().length>0)return n.trim()}let t=Rt(e);if(t)for(let e of It){let n=t[e];if(typeof n==`string`&&n.trim().length>0)return n.trim()}}function Vt(e){let t=e=>Nt.some(t=>typeof e[t]==`string`||typeof e[t]==`number`);if(t(e))return!0;let n=Rt(e);return n?t(n):!1}function Ht(e){let t=e.trim().split(`.`);if(t.length===3)try{let e=t[1].replaceAll(`-`,`+`).replaceAll(`_`,`/`),n=e.padEnd(e.length+(4-e.length%4)%4,`=`);return Lt(JSON.parse(atob(n)))}catch{return}}function Ut(e){let t=Ht(e)?.exp;if(typeof t!=`number`||!Number.isFinite(t))return;let n=new Date(t*1e3);return Number.isFinite(n.getTime())?n.toISOString():void 0}function Wt(e){let t={},n=0;for(let r of e.split(/\r?\n/)){let e=/^\s*([A-Za-z_][\w-]*)\s*:\s*(.*)$/.exec(r),i=e?.[1],a=e?.[2];i!==void 0&&a!==void 0&&(t[i]=a.trim(),n+=1)}return n>0?t:void 0}function Gt(e){if(e.startsWith(`{`)||e.startsWith(`[`))try{return JSON.parse(e)}catch{return}}function Kt(e){let t=e.trim(),n=Lt(Gt(t))??Wt(t);return n&&Vt(n)?`oauth`:Ht((n?zt(n)?.value:void 0)??t)===void 0?`api_key`:`jwt`}function qt(e){return e.length!==0&&!!(e.some(e=>Array.isArray(e.cookies)&&(typeof e.domain==`string`||typeof e.originalUrl==`string`))||e.every(e=>typeof e.name==`string`&&typeof e.value==`string`&&(e.domain!==void 0||e.path!==void 0||e.expirationDate!==void 0)))}function Jt(e,t){let n,r=!1,i=(e,t)=>{let i=e.toLowerCase();(i===`userid`||i===`uid`||i===`accountid`||i===`cuserid`)&&(n||=t.replace(/^"|"$/g,``).trim()),(i.includes(`token`)||i.includes(`ph`)||i.includes(`auth`)||i.includes(`session`))&&(r=!0)};for(let e of t)if(Array.isArray(e.cookies)){for(let t of e.cookies)if(t&&typeof t==`object`){let e=t;typeof e.name==`string`&&typeof e.value==`string`&&i(e.name,e.value)}}else typeof e.name==`string`&&typeof e.value==`string`&&i(e.name,e.value);return{value:e,kind:r?`oauth`:`api_key`,...n?{identity:n}:{}}}function Yt(e){let t=e.credentialKind;if(typeof t==`string`&&typeof e.accessToken==`string`&&Pt.every(t=>t in e)){let n=typeof e.label==`string`&&e.label.trim().length>0?e.label.trim():void 0,r=e.accessToken,i=t===`oauth`&&Vt(e);return{value:i?JSON.stringify(e):r,kind:i?`oauth`:`api_key`,...n?{identity:n}:{}}}let n=zt(e),r=Vt(e)?`oauth`:Kt(n?.value??JSON.stringify(e)),i=r===`oauth`?JSON.stringify(e):n?.value??JSON.stringify(e),a=Bt(e);return a?{value:i,kind:r,identity:a}:{value:i,kind:r}}function Xt(e){for(let t of Ft){let n=e[t];if(!Array.isArray(n))continue;let r=n.map(e=>Lt(e)).filter(e=>e!==void 0);if(r.length>0)return r}}function Zt(e){let t=e.trim();if(!t)return[];let n=Gt(t);if(Array.isArray(n)){let e=n.map(e=>Lt(e)).filter(e=>e!==void 0);if(e.length>0)return qt(e)?[Jt(t,e)]:e.map(Yt)}else{let e=Lt(n);if(e){let t=Xt(e);return t?t.map(Yt):[Yt(e)]}}let r=t.split(/\r?\n/).map(e=>e.trim()).filter(e=>e.length>0);if(r.length===0)return[];if(r.length===1)return Qt(r[0]);let i=Wt(t);return i&&(zt(i)||Object.keys(i).length===r.length)?[Yt(i)]:r.flatMap(Qt)}function Qt(e){let t=Lt(Gt(e));if(t){let e=Xt(t);return e?e.map(Yt):[Yt(t)]}return[{value:e,kind:Kt(e)}]}function $t(e,t,n){let r=new Set(n),i=1;return e.map(e=>{let n=e.identity;if(!n){for(;r.has(`${t}-${i}`);)i+=1;n=`${t}-${i}`,i+=1}let a=n,o=2;for(;r.has(a);)a=`${n} (${o++})`;return r.add(a),a})}function en(e){return e===`active`?0:e===`cooldown`?2:3}function tn(e){if(e===void 0)return;let t=new Date(e).getTime();if(Number.isFinite(t))return t<=Date.now()?`Expired ${new Date(e).toLocaleDateString()}`:X(e,!1)}function nn({cooldowns:e,reason:t}){if(!e)return null;let n=X(e.until),r=`Soonest: ${e.modelId} — ${n}`;return(0,$.jsxs)(G,{tone:`warn`,dot:!0,title:t?`${t} — ${r}`:r,children:[e.count,` model`,e.count===1?``:`s`,` cooling · `,n]})}function rn(e){if(e.credentialKind===`oauth`)return`OAuth`;if(e.credentialMode===`jwt`)return`JWT`}function an(e){return e.credentialKind===`oauth`?`blue`:`ok`}function on({account:e}){let t=e.cooldownUntil?new Date(e.cooldownUntil).getTime():NaN,n=Number.isFinite(t)&&t>Date.now(),r=Xe(e);if(e.status===`disabled`){let t=rn(e),n=e.lastErrorCategory===`auth_invalidated`;return(0,$.jsxs)(Y,{gap:`4px`,children:[(0,$.jsxs)(G,{tone:`disabled`,dot:!0,title:e.lastError,children:[`Disabled`,t?` - ${t}`:``]}),n?(0,$.jsx)(G,{tone:`warn`,title:e.lastError,children:kt(e.credentialKind)}):Ot(e.lastErrorCategory)&&!(e.lastErrorCategory===`quota_exhausted`&&r)?(0,$.jsx)(G,{tone:`warn`,title:e.lastError??e.lastErrorCategory,children:At(e.lastErrorCategory,e.credentialKind)}):null,(0,$.jsx)(nn,{cooldowns:r,reason:e.lastErrorCategory===`quota_exhausted`?e.lastError:void 0})]})}return e.status===`active`?(0,$.jsxs)(Y,{gap:`4px`,children:[(0,$.jsxs)(G,{tone:an(e),dot:!0,children:[`Active`,rn(e)?` - ${rn(e)}`:``]}),Ot(e.lastErrorCategory)&&!(e.lastErrorCategory===`quota_exhausted`&&r)?(0,$.jsx)(G,{tone:`warn`,title:e.lastError??e.lastErrorCategory,children:At(e.lastErrorCategory,e.credentialKind)}):null,(0,$.jsx)(nn,{cooldowns:r,reason:e.lastErrorCategory===`quota_exhausted`?e.lastError:void 0})]}):e.status===`cooldown`||n?(0,$.jsxs)(Y,{gap:`4px`,children:[(0,$.jsxs)(G,{tone:`warn`,dot:!0,children:[`Cooldown`,rn(e)?` - ${rn(e)}`:``,` `,e.cooldownUntil?`(${X(e.cooldownUntil)})`:``]}),Ot(e.lastErrorCategory)&&!(e.lastErrorCategory===`quota_exhausted`&&r)?(0,$.jsx)(G,{tone:`warn`,title:e.lastError??e.lastErrorCategory,children:At(e.lastErrorCategory,e.credentialKind)}):null,(0,$.jsx)(nn,{cooldowns:r,reason:e.lastErrorCategory===`quota_exhausted`?e.lastError:void 0})]}):(0,$.jsx)(G,{tone:`disabled`,children:`Disabled`})}function sn({windows:e}){if(e===void 0||e.length===0)return null;let t=0,n=0,r=!1,i=null;for(let a of e){if(a.accounting!==`pooled`){typeof a.remainingPercent==`number`&&Number.isFinite(a.remainingPercent)&&(i=i===null?a.remainingPercent:Math.min(i,a.remainingPercent));continue}let e=typeof a.limit==`number`&&Number.isFinite(a.limit)?a.limit:null,o=typeof a.remaining==`number`&&Number.isFinite(a.remaining)?a.remaining:e!==null&&typeof a.used==`number`&&Number.isFinite(a.used)?e-a.used:null;o!==null&&e!==null&&(t+=Math.max(0,o),n+=e,r=!0)}let a=null;return r?a=`${cn(t)} of ${cn(n)}`:i!==null&&(a=`${Math.round(i)}% left`),a===null?null:(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-2.5 max-w-full px-3.5 py-1 border border-inner-border rounded-chip bg-surface-1 text-text-secondary text-badge leading-normal whitespace-nowrap`,"data-tone":r&&t<=0||(i??100)<=10?`warn`:void 0,title:r?`${cn(t)} credits available of ${cn(n)}`:`Lowest remaining percent across this account's quota windows`,children:[(0,$.jsx)(`span`,{className:`text-text-tertiary text-micro font-semibold uppercase tracking-label`,children:`Quota`}),a]})}function cn(e){return e.toLocaleString(void 0,{maximumFractionDigits:1})}function ln({providerId:e,account:t,onClose:n}){let r=de(),[i,a]=(0,Q.useState)(``),o=t.label||t.id.slice(0,8),s=r.isPending,c=i.trim().length>0&&!s,l=async()=>{try{a(await navigator.clipboard.readText())}catch{x.error(`Clipboard access denied`)}};return(0,$.jsx)(P,{open:!0,onClose:n,title:`Replace API key — ${o}`,width:560,footer:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(y,{variant:`secondary`,size:`sm`,onClick:n,disabled:s,children:`Cancel`}),(0,$.jsx)(y,{size:`sm`,variant:`primary`,disabled:!c,onClick:()=>{let a=i.trim();a&&r.mutate({providerId:e,accountId:t.id,request:{secret:a}},{onSuccess:()=>{x.success(`API key replaced`,o),n()},onError:e=>{let t=e instanceof Error?e.message:`Unable to update account`;x.error(`Failed to replace key`,t)}})},children:s?`Saving…`:`Replace key`})]}),children:(0,$.jsxs)(`div`,{className:`flex flex-col gap-5`,children:[(0,$.jsx)(`p`,{className:`m-0 text-caption text-text-secondary`,children:`Paste the new key for this account. The old key stops working immediately; the account keeps its label, history, and routing.`}),(0,$.jsxs)(J,{gap:`6px`,className:`min-w-0`,children:[(0,$.jsx)(`label`,{className:`text-caption font-semibold text-text-secondary`,children:`New API key`}),(0,$.jsx)(`textarea`,{value:i,onChange:e=>a(e.target.value),placeholder:`Paste the replacement key…`,rows:4,spellCheck:!1,autoFocus:!0,className:`font-mono tabular-nums w-full min-w-0 min-h-65 rounded-control border border-inner-border bg-input-bg px-6 py-5 text-caption text-text-primary resize-y box-border`}),(0,$.jsx)(Y,{gap:`8px`,className:`justify-end`,children:(0,$.jsx)(y,{variant:`secondary`,size:`sm`,onClick:()=>void l(),children:`Paste`})})]})]})})}function un({providerId:e,account:t,inflight:n,quota:r,selected:a,onToggleSelect:o,onDelete:s}){let c=de(),l=ve(),u=qe(t.id),d=t.status===`disabled`,f=t.cooldownUntil?new Date(t.cooldownUntil).getTime():NaN,p=Number.isFinite(f)&&f>Date.now(),m=t.status===`cooldown`||p,[g,_]=(0,Q.useState)(!1),[b,S]=(0,Q.useState)(!1),[,C]=(0,Q.useState)(0),[w,T]=(0,Q.useState)(!1),[E,D]=(0,Q.useState)(``),O=I(e),ee=(t.label?.match(/[^\s@]+@[^\s@]+/)?.[0]??t.label)||t.id.slice(0,8),k=O.enabled?`Mysterious accounts`:ee,A=tn(t.tokenExpiresAt),j=Ye(t),te=Math.max(p&&t.cooldownUntil?f:0,j??0);(0,Q.useEffect)(()=>{if(te<=Date.now())return;let e=setInterval(()=>C(e=>e+1),1e3);return()=>clearInterval(e)},[te]);let N=()=>{let n=E.trim();T(!1),n&&n!==(t.label??``)&&c.mutate({providerId:e,accountId:t.id,request:{label:n}},{onSuccess:()=>x.success(`Account renamed`,n),onError:e=>x.error(`Rename failed`,e.message??`Unable to rename account`)})};return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`account-row account-row-grid grid items-center gap-5 px-5 py-4 border rounded-control bg-surface-2 ${a?`border-accent`:`border-inner-border`} hover:bg-hover`,role:`listitem`,"data-selected":a?`true`:void 0,style:{opacity:d?.62:1},children:[(0,$.jsx)(`div`,{className:`flex items-center`,children:(0,$.jsx)(`input`,{type:`checkbox`,checked:a,onChange:e=>o(t.id,e.target.checked),"aria-label":`Select ${k}`,className:`cursor-pointer`})}),(0,$.jsxs)(`div`,{className:`min-w-0 flex flex-col gap-1.5`,children:[(0,$.jsx)(`div`,{className:`flex items-center gap-3 min-w-0`,children:w?(0,$.jsx)(K,{value:E,onChange:e=>D(e.target.value),onKeyDown:e=>{e.key===`Enter`&&N(),e.key===`Escape`&&T(!1)},onBlur:N,autoFocus:!0,"aria-label":`Account label`,className:`text-body max-w-120`}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`text-body font-semibold text-text-primary min-w-0 overflow-hidden text-ellipsis whitespace-nowrap`,title:t.label||t.id,children:k}),(0,$.jsx)(`button`,{type:`button`,className:`shrink-0 grid place-items-center w-10 h-10 p-0 border-0 bg-transparent text-text-tertiary cursor-pointer rounded-tiny hover:bg-inner-border hover:text-text-primary`,title:`Rename account`,"aria-label":`Rename ${k}`,onClick:()=>{D(t.label??``),T(!0)},children:(0,$.jsx)(F,{size:11})})]})}),(0,$.jsxs)(`div`,{className:`flex items-center flex-nowrap gap-2 min-w-0 overflow-hidden`,children:[(0,$.jsx)(on,{account:t}),A?(0,$.jsx)(`span`,{className:`inline-flex items-center gap-2.5 max-w-full px-3.5 py-1 border border-inner-border rounded-chip bg-surface-1 text-text-secondary text-badge leading-normal whitespace-nowrap`,title:A,children:A}):null]}),(0,$.jsxs)(`div`,{className:`flex items-center flex-wrap gap-2 min-w-0`,children:[(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-2.5 max-w-full px-3.5 py-1 border border-inner-border rounded-chip bg-surface-1 text-text-secondary text-badge leading-normal whitespace-nowrap`,title:`Today: ${t.usageToday.totalTokens.toLocaleString()} tokens, ${t.usageToday.requests.toLocaleString()} requests`,children:[(0,$.jsx)(`span`,{className:`text-text-tertiary text-micro font-semibold uppercase tracking-label`,children:`Today`}),t.usageToday.totalTokens.toLocaleString(),` tok · `,t.usageToday.requests.toLocaleString(),` req`]}),(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-2.5 max-w-full px-3.5 py-1 border border-inner-border rounded-chip bg-surface-1 text-text-secondary text-badge leading-normal whitespace-nowrap`,title:`Lifetime totals are backfilled from telemetry still retained when tracking starts; new totals survive telemetry cleanup.`,children:[(0,$.jsx)(`span`,{className:`text-text-tertiary text-micro font-semibold uppercase tracking-label`,children:`All time`}),t.usageAllTime.totalTokens.toLocaleString(),` tok · `,t.usageAllTime.requests.toLocaleString(),` req`]}),(0,$.jsx)(sn,{windows:r}),(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-2.5 max-w-full px-3.5 py-1 border border-inner-border rounded-chip bg-surface-1 text-text-secondary text-badge leading-normal whitespace-nowrap`,title:`Concurrency comes from this provider’s Routing Strategy; accounts no longer carry manual ceilings.`,children:[(0,$.jsx)(`span`,{className:`text-text-tertiary text-micro font-semibold uppercase tracking-label`,children:`In flight`}),n?.toLocaleString()??`—`]})]})]}),(0,$.jsxs)(`div`,{className:`account-row-actions flex items-center justify-end gap-3 flex-wrap`,children:[(0,$.jsx)(y,{size:`icon`,variant:`secondary`,icon:(0,$.jsx)(i,{size:12}),label:`Health`,"aria-label":`Health for ${k}`,onClick:()=>_(!0),title:`View Health & Error History`}),(0,$.jsx)(y,{size:`icon`,variant:`secondary`,icon:u.isPending?(0,$.jsx)(v,{size:12,className:`animate-spin`}):(0,$.jsx)(h,{size:12}),label:u.isPending?`Testing…`:`Test`,"aria-label":`Test ${k}`,disabled:u.isPending,onClick:()=>{u.mutate(void 0,{onSuccess:e=>{e?.ok?x.success(`Account test passed`,k):x.error(`Account test failed`,e?.message??`Provider reported an error`)},onError:e=>x.error(`Account test failed`,e.message??`Unable to test account`)})},title:`Refresh quota and health for this account`}),(0,$.jsx)(y,{size:`icon`,variant:`secondary`,icon:(0,$.jsx)(M,{size:12}),label:`Edit key`,"aria-label":`Replace API key for ${k}`,onClick:()=>S(!0),title:`Replace API key`}),(0,$.jsx)(y,{size:`icon`,variant:`secondary`,icon:d?(0,$.jsx)(nt,{size:12}):(0,$.jsx)(re,{size:12}),label:d?`Enable`:`Disable`,"aria-label":d?`Enable ${k}`:`Disable ${k}`,disabled:c.isPending,onClick:()=>{let n=d;c.mutate({providerId:e,accountId:t.id,request:{status:n?`active`:`disabled`}},{onSuccess:()=>x.success(n?`Account enabled`:`Account disabled`,k),onError:e=>x.error(`Update failed`,e.message??`Unable to update account`)})},title:d?`Enable account`:`Disable account`}),m?(0,$.jsx)(y,{size:`icon`,variant:`secondary`,icon:(0,$.jsx)(ae,{size:12,className:l.isPending?`animate-spin`:``}),label:l.isPending?`Recovering…`:`Recover`,"aria-label":`Recover ${k}`,disabled:l.isPending,onClick:()=>l.mutate({providerId:e,accountId:t.id}),title:`Clear cooldown / restore active status`}):null,(0,$.jsx)(y,{size:`icon`,variant:`danger`,icon:(0,$.jsx)(se,{size:12}),label:`Delete`,"aria-label":`Delete ${k}`,onClick:()=>s(t),title:`Delete account`})]})]}),g&&(0,$.jsx)(Je,{summary:{providerId:e,accountId:t.id,title:t.label||t.id.slice(0,8),status:t.status,errorCategory:t.lastErrorCategory??void 0,errorMessage:t.lastError??void 0,emptyMessage:`Status transitions, rate limits, and auto-recoveries will appear here.`,staticToken:t.staticToken===!0,credentialKind:t.credentialKind,credentialMode:t.credentialMode},onClose:()=>_(!1)}),b&&(0,$.jsx)(ln,{providerId:e,account:t,onClose:()=>S(!1)})]})}var dn=[{value:`added-asc`,label:`Added · oldest`},{value:`added-desc`,label:`Added · newest`},{value:`label-asc`,label:`Name · A–Z`},{value:`label-desc`,label:`Name · Z–A`},{value:`status-asc`,label:`Status · active first`},{value:`status-desc`,label:`Status · disabled first`},{value:`lastCheck-desc`,label:`Last check · newest`},{value:`lastCheck-asc`,label:`Last check · oldest`}];function fn(e,t,n){let r=(e,t)=>(e.label||e.id).localeCompare(t.label||t.id)||e.createdAt.localeCompare(t.createdAt)||e.id.localeCompare(t.id);if(n===`added`)return e.sortIndex-t.sortIndex||e.createdAt.localeCompare(t.createdAt)||e.id.localeCompare(t.id);if(n===`label`)return r(e,t);if(n===`status`){let n=en(e.status)-en(t.status);return n===0?r(e,t):n}let i=new Date(e.lastSuccessAt??e.createdAt).getTime();return new Date(t.lastSuccessAt??t.createdAt).getTime()-i||r(e,t)}function pn({providerId:e,accounts:t,onDelete:n,showGrokProbe:r=!1,grokProbePending:i=!1,onGrokProbe:a}){let o=le(),s=de(),c=ve(),l=Te(),u=We(e).data??new Map,p=Ke(),m=(0,Q.useMemo)(()=>{let t=new Map;for(let n of p.data?.accounts??[])n.provider===e&&n.quota&&t.set(n.id,n.quota.windows);return t},[p.data,e]),[g,_]=(0,Q.useState)(``),[v,b]=(0,Q.useState)(new Set),[S,C]=(0,Q.useState)(`added-asc`),[T,E]=(0,Q.useState)(!1),[D,O]=(0,Q.useState)(!1),[ee,k]=(0,Q.useState)(!1),A=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{if(!ee)return;let e=e=>{A.current&&!A.current.contains(e.target)&&k(!1)},t=e=>{e.key===`Escape`&&k(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[ee]);let j=g.trim().toLowerCase(),M=(0,Q.useMemo)(()=>j?t.filter(e=>{let t=`${e.label??``} ${e.id} ${e.credentialKind} ${e.status}`.toLowerCase();return j.split(/\s+/).every(e=>t.includes(e))}):t,[t,j]),te=(0,Q.useMemo)(()=>{let e=S.slice(0,S.lastIndexOf(`-`)),t=S.endsWith(`-desc`)?-1:1,n=[...M];return n.sort((n,r)=>t*fn(n,r,e)),n},[M,S]),N=(0,Q.useMemo)(()=>t.filter(e=>v.has(e.id)),[t,v]),P=M.length>0&&M.every(e=>v.has(e.id)),F=N.some(e=>e.status===`disabled`),ne=N.some(e=>e.status!==`disabled`),I=N.length===0,ie=(e,t)=>{b(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r})},ce=()=>{b(e=>{let t=new Set(e);if(P)for(let e of M)t.delete(e.id);else for(let e of M)t.add(e.id);return t})},pe=async(e,t)=>{if(N.length===0)return;E(!0);let n=await Promise.allSettled(N.map(e=>t(e))),r=n.filter(e=>e.status===`rejected`).length,i=n.length-r;E(!1),r===0?x.success(`${e} complete`,`${i} account${i===1?``:`s`}`):x.error(`${e} partially failed`,`${i} succeeded, ${r} failed`)},me=()=>pe(`Recover`,t=>c.mutateAsync({providerId:e,accountId:t.id})),he=async()=>{if(t.length===0)return;E(!0);let e=await jt(t,3,e=>ue(`/accounts/${encodeURIComponent(e.id)}/quota/refresh`,{method:`POST`})),n=0,r=0;for(let t of e)t.status===`fulfilled`&&t.value?.ok?n+=1:r+=1;await Promise.all([o.invalidateQueries({queryKey:L.quota.all}),o.invalidateQueries({queryKey:L.providers.all})]),E(!1),r===0?x.success(`Test complete`,`${n} passed`):n===0?x.error(`Test failed`,`${r} account${r===1?``:`s`} failed`):x.error(`Test partially failed`,`${n} passed, ${r} failed`)},ge=t=>pe(t?`Enable`:`Disable`,n=>s.mutateAsync({providerId:e,accountId:n.id,request:{status:t?`active`:`disabled`}})),_e=async()=>{if(N.length!==0){E(!0);try{let t=await l.mutateAsync({providerId:e,accountIds:N.map(e=>e.id)}),n=new Date().toISOString().replace(/[:.]/g,`-`);Ie(`${e}-accounts-${n}.json`,JSON.stringify(t,null,2),`application/json`),x.success(`Accounts exported`,`${t.accounts.length} account${t.accounts.length===1?``:`s`} — contains plaintext credentials`)}catch(e){x.error(`Export failed`,e.message??`Unable to export accounts`)}finally{E(!1)}}};return(0,$.jsxs)(J,{gap:`8px`,children:[(0,$.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-2 p-3 border border-inner-border rounded-control bg-surface-2`,children:[(0,$.jsxs)(`label`,{className:`relative min-w-20 flex-[1_1_10rem]`,children:[(0,$.jsx)(oe,{size:13,"aria-hidden":`true`,className:`pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-text-tertiary`}),(0,$.jsx)(K,{id:`accounts-search`,value:g,onChange:e=>_(e.target.value),placeholder:`Search accounts...`,"aria-label":`Search accounts`,className:`pl-9`})]}),(0,$.jsx)(y,{size:`sm`,variant:`primary`,icon:(0,$.jsx)(h,{size:12}),disabled:T||t.length===0,onClick:he,"aria-label":`Test all accounts`,title:`Test every account, regardless of selection or filters`,children:`Test all`}),(0,$.jsxs)(`div`,{ref:A,className:`relative`,children:[(0,$.jsxs)(y,{size:`sm`,variant:`secondary`,disabled:T||I,"aria-expanded":ee,"aria-haspopup":`menu`,"aria-label":I?`Select accounts to enable bulk actions`:`Bulk actions for ${N.length} selected accounts`,onClick:()=>k(e=>!e),children:[`Actions`,I?``:` (${N.length})`,(0,$.jsx)(d,{size:12,"aria-hidden":`true`,className:`transition-transform ${ee?`rotate-180`:``}`})]}),ee&&!I?(0,$.jsxs)(`div`,{role:`menu`,"aria-label":`Selected account actions`,className:`absolute left-0 top-full z-50 mt-1 flex w-64 popover-max flex-col gap-1 rounded-control border border-inner-border bg-popover-bg p-2 shadow-popout sm:left-auto sm:right-0`,children:[(0,$.jsx)(y,{role:`menuitem`,size:`sm`,variant:`ghost`,className:`w-full justify-start`,icon:(0,$.jsx)(ae,{size:12}),disabled:T,onClick:()=>{k(!1),me()},children:`Recover`}),F?(0,$.jsx)(y,{role:`menuitem`,size:`sm`,variant:`ghost`,className:`w-full justify-start`,icon:(0,$.jsx)(nt,{size:12}),disabled:T,onClick:()=>{k(!1),ge(!0)},children:`Enable`}):null,ne?(0,$.jsx)(y,{role:`menuitem`,size:`sm`,variant:`ghost`,className:`w-full justify-start`,icon:(0,$.jsx)(re,{size:12}),disabled:T,onClick:()=>{k(!1),ge(!1)},children:`Disable`}):null,(0,$.jsx)(y,{role:`menuitem`,size:`sm`,variant:`ghost`,className:`w-full justify-start`,icon:(0,$.jsx)(w,{size:12}),disabled:T,onClick:()=>{k(!1),_e()},children:`Export JSON`}),(0,$.jsx)(y,{role:`menuitem`,size:`sm`,variant:`danger`,className:`w-full justify-start`,icon:(0,$.jsx)(se,{size:12}),disabled:T,onClick:()=>{k(!1),O(!0)},children:`Delete`}),(0,$.jsx)(y,{role:`menuitem`,size:`sm`,variant:`ghost`,className:`w-full justify-start`,disabled:T,onClick:()=>{b(new Set),k(!1)},children:`Clear selection`})]}):null]}),(0,$.jsx)(`label`,{className:`inline-flex h-15 shrink-0 items-center gap-2 text-caption font-semibold text-text-secondary [&_.radix-select-trigger]:font-semibold [&_.radix-select-trigger]:bg-hover [&_.radix-select-trigger]:text-text-primary`,children:(0,$.jsx)(f,{size:`sm`,value:S,onValueChange:e=>C(e),options:dn,"aria-label":`Sort accounts by`})}),(0,$.jsxs)(`label`,{className:`inline-flex h-15 shrink-0 items-center gap-2 text-caption font-semibold text-text-secondary`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:P,onChange:ce,"aria-label":`Select accounts`}),(0,$.jsx)(`span`,{children:`Select`})]}),r?(0,$.jsx)(y,{size:`sm`,variant:`secondary`,icon:(0,$.jsx)(h,{size:12,className:i?`animate-spin`:``}),disabled:i||t.length===0,onClick:a,title:`Probe every Grok account with the live 407 streaming request`,children:i?`Testing…`:`Test 407`}):null]}),(0,$.jsx)(`div`,{className:`account-list flex flex-col gap-3 max-h-230 overflow-y-auto pr-1 [container-type:inline-size] [container-name:account-list]`,role:`list`,"aria-label":`Provider accounts`,children:te.map(t=>(0,$.jsx)(un,{providerId:e,account:t,inflight:u.get(t.id)??t.inflight,quota:m.get(t.id),selected:v.has(t.id),onToggleSelect:ie,onDelete:n},t.id))}),(0,$.jsx)(`div`,{className:`flex items-center justify-between text-badge text-text-tertiary`,children:(0,$.jsxs)(`span`,{children:[`Showing `,M.length,` account`,M.length===1?``:`s`,j?` (filtered from ${t.length})`:``]})}),(0,$.jsx)(fe,{open:D,onClose:()=>{T||O(!1)},onConfirm:async()=>{await pe(`Delete`,async e=>{let t=e.tenantId===null?`/global/accounts/${encodeURIComponent(e.id)}`:`/accounts/${encodeURIComponent(e.id)}`;await ue(t,{method:`DELETE`}),o.removeQueries({queryKey:L.quota.account(e.id),exact:!0})}),b(new Set),O(!1),await Promise.all([o.invalidateQueries({queryKey:L.providers.accounts(e)}),o.invalidateQueries({queryKey:L.providers.all}),o.invalidateQueries({queryKey:L.quota.all})])},title:`Delete ${N.length} account${N.length===1?``:`s`}?`,message:`This permanently removes the selected accounts and their credentials. This cannot be undone.`,confirmLabel:`Delete`,danger:!0})]})}var mn=2097152,hn=mn/1048576;function gn({providerId:e,accounts:t,onClose:n}){let r=ye(),i=De(),[a,o]=(0,Q.useState)(``),[s,c]=(0,Q.useState)(``),[l,u]=(0,Q.useState)(!1),[d,p]=(0,Q.useState)(`auto`),m=Zt(s),h=m.length>1,g=m.length===1?m[0]:void 0,_=d===`auto`?g?.kind:d,v=g&&_===`jwt`?Ut(g.value):void 0,S=t.map(e=>e.label),C=h?$t(m,e,S):[],w=e=>{let t=d===`auto`?e.kind===`jwt`?`jwt`:`auto`:d;return{credentialKind:t===`auto`&&e.kind===`oauth`?`oauth`:`api_key`,credentialMode:t,secret:e.value}},T=r.isPending||l,E=async()=>{try{let e=await navigator.clipboard.readText();c(e);let t=Zt(e);if(t.length>1)x.success(`Pasted from clipboard`,`Detected ${t.length} credentials`);else{let e=t[0]?.kind??`api_key`,n=e===`oauth`?`OAuth export`:e===`jwt`?`Static JWT`:`API key`;x.success(`Pasted from clipboard`,`Detected: ${n}`)}}catch{x.error(`Clipboard access denied`)}},D=e=>{if(e.size>mn){x.error(`File too large`,`Credential files must be ${hn} MB or smaller.`);return}let t=new FileReader;t.onload=()=>{let n=typeof t.result==`string`?t.result:``;c(n);let r=Zt(n);if(r.length===0){x.error(`Nothing to import`,`That file held no credential the gateway recognises.`);return}x.success(`Imported ${e.name}`,r.length>1?`Detected ${r.length} credentials`:r[0]?.kind===`oauth`?`Detected: OAuth export`:`Detected: API key`)},t.onerror=()=>x.error(`Could not read that file`),t.readAsText(e)},O=async()=>{if(m.length!==0){if(m.length===1){let t=m[0];r.mutate({providerId:e,request:{label:(a.trim()||t.identity)??void 0,...w(t)}},{onSuccess:()=>{x.success(`Account connected`,`New ${t.kind===`oauth`?`OAuth`:t.kind===`jwt`?`Static JWT`:`API key`} account registered successfully`),n()},onError:e=>x.error(`Failed to add account`,e.message??`Invalid credentials`)});return}u(!0);try{let t=await i.mutateAsync({providerId:e,accounts:m.map((e,t)=>({label:C[t],...w(e)}))}),r=t.results.filter(e=>!e.ok),a=t.created;if(a>0&&x.success(`${a} account${a===1?``:`s`} added`,r.length>0?`${r.length} skipped`:void 0),r.length>0){let e=r.slice(0,5).map(e=>`${C[e.index]??e.index}: ${e.error??`rejected`}`).join(`
|
|
2
2
|
`);x.error(`${r.length} account${r.length===1?``:`s`} skipped`,e+(r.length>5?`\n…and ${r.length-5} more`:``))}a>0&&n()}finally{u(!1)}}};return(0,$.jsx)(P,{open:!0,onClose:n,title:`Add Account (API key / JSON)`,width:560,footer:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(y,{variant:`secondary`,size:`sm`,onClick:n,disabled:T,children:`Cancel`}),(0,$.jsx)(y,{size:`sm`,variant:`primary`,disabled:T||m.length===0,onClick:()=>void O(),children:T?`Connecting...`:h?`Add ${m.length} Accounts`:`Add Account`})]}),children:(0,$.jsxs)(`div`,{className:`flex flex-col gap-5`,children:[!h&&(0,$.jsx)(K,{label:`Account label (optional)`,value:a,onChange:e=>o(e.target.value),placeholder:g?.identity??`${e} account`}),(0,$.jsx)(f,{label:`Credential type`,id:`credential-mode`,value:d,onValueChange:e=>p(e===`jwt`||e===`api_key`?e:`auto`),options:[{value:`auto`,label:`Auto — detect JWT, OAuth, or API key`},{value:`jwt`,label:`JWT — static, no refresh`},{value:`api_key`,label:`API key — do not decode as JWT`}]}),(0,$.jsxs)(J,{gap:`6px`,className:`min-w-0`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,$.jsx)(`label`,{className:`text-caption font-semibold text-text-secondary`,children:`API key, OAuth token, or exported JSON — one or many`}),h?(0,$.jsxs)(G,{tone:`accent`,children:[`Detected: `,m.length,` accounts`]}):g?(0,$.jsxs)(G,{tone:_===`oauth`||_===`jwt`?`accent`:`default`,children:[`Detected:`,` `,_===`oauth`?`OAuth`:_===`jwt`?`Static JWT`:`API key`,g.identity?` · ${g.identity}`:``]}):null,g&&_===`jwt`?(0,$.jsxs)(`p`,{className:`text-micro text-text-tertiary`,children:[`Static JWT · no refresh token`,v?` · expires ${new Date(v).toLocaleString()}`:` · no expiry claim`]}):null]}),(0,$.jsx)(`textarea`,{value:s,onChange:e=>c(e.target.value),placeholder:`Paste one credential, or many — one per line, a JSON array, or newline-delimited OAuth exports. Kind and account naming are detected automatically…`,rows:6,spellCheck:!1,className:`font-mono tabular-nums w-full min-w-0 min-h-65 rounded-control border border-inner-border bg-input-bg px-6 py-5 text-caption text-text-primary resize-y box-border`}),(0,$.jsxs)(Y,{gap:`8px`,className:`justify-end`,children:[(0,$.jsx)(y,{variant:`secondary`,size:`sm`,onClick:()=>void E(),children:`Paste`}),(0,$.jsxs)(`label`,{className:b({size:`sm`,className:`cursor-pointer`}),children:[(0,$.jsx)(`input`,{type:`file`,accept:`.json,.txt,.jsonl,.ndjson,application/json,text/plain`,"aria-label":`Import credentials from a file`,className:`hidden`,onChange:e=>{let t=e.target.files?.[0];e.target.value=``,t&&D(t)}}),`Import file`]})]})]}),h&&(0,$.jsx)(`div`,{className:`flex flex-col gap-2 max-h-75 overflow-y-auto rounded-control border border-inner-border bg-surface-2 px-4 py-5`,children:m.map((e,t)=>(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-4 text-badge`,children:[(0,$.jsx)(`span`,{className:`truncate min-w-0`,children:C[t]}),(0,$.jsx)(G,{tone:e.kind===`oauth`?`accent`:`default`,children:e.kind===`oauth`?`OAuth`:`API key`})]},t))})]})})}function _n(e){let t=e.trim(),n=e=>{try{return new URL(e).searchParams}catch{return}},r=n(t)??new URLSearchParams(t.startsWith(`?`)?t.slice(1):t),i=r.get(`code`);if(i)return{code:i};let a=r.get(`error_description`)??r.get(`error`);return a?{error:`The provider refused the login: ${a}`}:n(t)!==void 0||t.startsWith(`?`)?{error:`That redirect URL carries no authorization code — copy the full URL from the address bar.`}:{code:t}}function vn({providerId:e,authorizeUrl:t,state:n,popup:r,onClose:i}){let[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)(``),l=ke(),d=Ze(),f=le(),p=Ee(e),m=(0,Q.useRef)(null),h=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{let t=setInterval(()=>{f.invalidateQueries({queryKey:L.providers.accounts(e)})},1500);return()=>clearInterval(t)},[f,e]),(0,Q.useEffect)(()=>{let e=p.data?.map(e=>e.id)??null;if(e!==null){if(m.current===null){m.current=new Set(e);return}h.current||e.find(e=>!m.current.has(e))!==void 0&&(h.current=!0,r.close(),x.success(`Account connected`,`OAuth login completed successfully`),i(!0))}},[p.data,r,i]);let g=()=>{r.close(),i(!1)},[_,b]=(0,Q.useState)(!1),S=()=>{b(!0),f.invalidateQueries({queryKey:L.providers.accounts(e)}).finally(()=>b(!1))},w=async()=>{try{let e=await navigator.clipboard.readText();if(!e.trim()){x.error(`Clipboard is empty`);return}c(e),x.success(`Pasted redirect URL`)}catch{x.error(`Clipboard unavailable on this origin`)}};return(0,$.jsx)(P,{open:!0,onClose:g,title:`Connect via OAuth`,size:`sm`,footer:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(y,{variant:`secondary`,size:`sm`,onClick:g,disabled:l.isPending,children:`Cancel`}),(0,$.jsx)(y,{variant:`secondary`,size:`sm`,onClick:S,disabled:l.isPending||_,title:`You already approved in the popup — check now instead of waiting`,children:_?`Checking…`:`Complete`}),(0,$.jsx)(y,{variant:`primary`,size:`sm`,disabled:l.isPending||s.trim().length===0,onClick:()=>{let t=_n(s);if(`error`in t){x.error(`OAuth callback failed`,t.error);return}l.mutate({providerId:e,code:t.code,state:n},{onSuccess:()=>{r.close(),x.success(`Account connected`,`OAuth login completed successfully`),i(!0)},onError:e=>x.error(`OAuth callback failed`,e.message??`Invalid or expired authorization code`)})},children:l.isPending?`Connecting…`:`Connect`})]}),children:(0,$.jsxs)(J,{gap:`14px`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2.5 px-3.5 py-2.5 rounded-card border border-inner-border bg-surface-2`,children:[(0,$.jsx)(v,{size:16,className:`animate-spin text-accent shrink-0`}),(0,$.jsx)(`span`,{className:`text-body font-semibold`,children:`Waiting for popup authorization…`})]}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,$.jsx)(`div`,{className:`text-body font-semibold text-text-primary`,children:`Step 1: Open this URL in your browser`}),(0,$.jsxs)(Y,{gap:`8px`,children:[(0,$.jsx)(`a`,{className:`min-w-0 flex-1 font-mono text-badge text-accent overflow-hidden text-ellipsis whitespace-nowrap px-2.5 py-2 rounded-control bg-input-bg border border-inner-border`,href:t,target:`_blank`,rel:`noreferrer`,title:t,children:t}),(0,$.jsx)(y,{variant:`secondary`,size:`sm`,icon:a?(0,$.jsx)(u,{size:12}):(0,$.jsx)(C,{size:12}),onClick:()=>{navigator.clipboard?.writeText(t),o(!0),d(()=>o(!1),1500)},className:`shrink-0`,children:a?`Copied`:`Copy`})]}),(0,$.jsx)(`p`,{className:`text-badge leading-snug text-text-tertiary`,children:`A popup should open automatically. If it was blocked, open the URL above manually.`})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2.5 text-micro font-bold uppercase tracking-label text-text-tertiary`,children:[(0,$.jsx)(`span`,{"aria-hidden":`true`,className:`flex-1 h-px bg-inner-border`}),(0,$.jsx)(`span`,{children:`Or complete manually`}),(0,$.jsx)(`span`,{"aria-hidden":`true`,className:`flex-1 h-px bg-inner-border`})]}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,$.jsx)(`div`,{className:`text-body font-semibold text-text-primary`,children:`Step 2: Paste the redirect URL here`}),(0,$.jsx)(`p`,{className:`text-badge leading-snug text-text-tertiary`,children:`If the redirect lands on an unreachable address, copy that page's full URL from your browser and paste it below — this works from any machine, not just localhost.`}),(0,$.jsxs)(Y,{gap:`8px`,align:`flex-start`,children:[(0,$.jsx)(`textarea`,{value:s,onChange:e=>c(e.target.value),placeholder:`http://127.0.0.1:59653/callback?code=…&state=… (or just the code)`,rows:2,spellCheck:!1,className:`w-full min-h-16 resize-y rounded-control border border-inner-border bg-input-bg px-2.5 py-2 font-mono text-badge text-text-primary box-border focus-visible:outline-2 focus-visible:outline-accent focus-visible:outline-offset-1 flex-1`}),(0,$.jsx)(y,{variant:`secondary`,size:`sm`,onClick:()=>void w(),className:`shrink-0`,children:`Paste`})]})]})]})})}function yn(e){try{return new URL(e).host}catch{return e}}function bn({providerId:e,parameters:t,onClose:n}){let r=Ne(),i=xe(),[a,o]=(0,Q.useState)(null),[s,c]=(0,Q.useState)(!1),[l,d]=(0,Q.useState)(!1),f=Ze();(0,Q.useEffect)(()=>{let i=!1;return r.mutate({providerId:e,...t===void 0||Object.keys(t).length===0?{}:{parameters:t}},{onSuccess:e=>{i||o(e)},onError:e=>{i||(x.error(`Failed to start device login`,e.message??`Unable to start device authorization`),n())}}),()=>{i=!0}},[]);let p=(0,Q.useRef)(null),[m,h]=(0,Q.useState)(!1);return(0,Q.useEffect)(()=>{if(!a)return;let e=window.open(a.verificationUri,`cartethyia-device`,`popup,width=720,height=820`);return e?p.current=e:h(!0),()=>{let e=p.current;p.current=null,e&&!e.closed&&e.close()}},[a]),(0,Q.useEffect)(()=>{if(!a)return;let t=Date.now(),r=Math.max(1,a.expiresInSeconds)*1e3,o=!1,s=Math.max(1,a.intervalSeconds)*1e3,c=!1,l=0,u=()=>window.clearTimeout(l),d=e=>{u(),l=window.setTimeout(f,e)},f=()=>{if(!c){if(Date.now()-t>r){u(),x.error(`Device login expired`,`Please try again.`),n();return}o||(o=!0,i.mutate({providerId:e,deviceAuthId:a.deviceAuthId},{onSuccess:e=>{if(o=!1,!c){if(e.status===`complete`){u();let e=p.current;e&&!e.closed&&e.close(),x.success(`OAuth account connected`,`Device authorization complete`),n()}else e.status===`failed`?(u(),x.error(`Device login failed`,e.reason),n()):e.status===`slow_down`?(s=(e.retryAfterSeconds===void 0?s+5e3:Math.max(1,e.retryAfterSeconds)*1e3)+1e3,d(s)):(e.status===`pending`&&e.retryAfterSeconds!==void 0&&(s=Math.max(1,e.retryAfterSeconds)*1e3+1e3),d(s))}},onError:()=>{o=!1,c||d(s)}}))}};return d(s+1e3),()=>{c=!0,u()}},[a]),(0,$.jsx)(P,{open:!0,onClose:n,title:`Login with OAuth (device code)`,size:`sm`,footer:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(y,{variant:`secondary`,size:`sm`,onClick:n,children:`Cancel`}),null]}),children:(0,$.jsx)(J,{gap:`14px`,children:a?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2.5 px-3.5 py-2.5 rounded-card border border-inner-border bg-surface-2`,children:[(0,$.jsx)(v,{size:16,className:`animate-spin text-accent shrink-0`}),(0,$.jsx)(`span`,{className:`text-body font-semibold`,children:`Waiting for authorization…`})]}),a.userCode?(0,$.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,$.jsx)(`div`,{className:`text-body font-semibold text-text-primary`,children:`Step 1: Enter this code`}),(0,$.jsxs)(`div`,{className:`rounded-card border border-inner-border bg-surface-2 p-3.5 flex flex-col gap-1.5 items-center text-center`,children:[(0,$.jsx)(`div`,{className:`text-micro font-bold uppercase tracking-label text-text-tertiary`,children:`Device code`}),(0,$.jsx)(`div`,{className:`font-mono text-display font-bold tracking-code text-text-primary`,children:a.userCode}),(0,$.jsx)(y,{variant:`secondary`,size:`sm`,icon:l?(0,$.jsx)(u,{size:12}):(0,$.jsx)(C,{size:12}),onClick:()=>{navigator.clipboard?.writeText(a.userCode),d(!0),f(()=>d(!1),1500)},children:l?`Copied`:`Copy code`})]})]}):null,(0,$.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,$.jsx)(`div`,{className:`text-body font-semibold text-text-primary`,children:a.userCode?`Step 2: Open the verification page`:`Open the verification page to authorize`}),(0,$.jsxs)(Y,{gap:`8px`,children:[(0,$.jsx)(`a`,{className:`min-w-0 flex-1 font-mono text-badge text-accent overflow-hidden text-ellipsis whitespace-nowrap px-2.5 py-2 rounded-control bg-input-bg border border-inner-border`,href:a.verificationUri,target:`_blank`,rel:`noreferrer`,title:a.verificationUri,children:yn(a.verificationUri)}),(0,$.jsx)(y,{variant:`primary`,size:`sm`,icon:(0,$.jsx)(et,{size:12}),onClick:()=>window.open(a.verificationUri,`_blank`,`noopener`),className:`shrink-0`,children:`Open`}),(0,$.jsx)(y,{variant:`secondary`,size:`sm`,icon:s?(0,$.jsx)(u,{size:12}):(0,$.jsx)(C,{size:12}),onClick:()=>{navigator.clipboard?.writeText(a.verificationUri),c(!0),f(()=>c(!1),1500)},className:`shrink-0`,children:s?`Copied`:`Copy`})]}),(0,$.jsx)(`p`,{className:`text-badge leading-snug text-text-tertiary`,children:m?`The popup was blocked — open the page with Open above, finish signing in there, then press Check now.`:`The page opened in a popup. Finish signing in there — this dialog closes automatically once the account connects, or press Check now.`})]})]}):(0,$.jsxs)(`div`,{className:`flex items-center gap-2.5 px-3.5 py-2.5 rounded-card border border-inner-border bg-surface-2`,children:[(0,$.jsx)(v,{size:16,className:`animate-spin text-accent shrink-0`}),(0,$.jsx)(`span`,{className:`text-body font-semibold`,children:`Starting device authorization…`})]})})})}function xn(e){let t={};for(let n of e)t[n.key]=n.defaultValue??``;return t}function Sn(e,t){return e.filter(e=>e.required===!0&&(t[e.key]??``).trim().length===0).map(e=>e.key)}function Cn({fields:e,values:t,onChange:n,idPrefix:r}){return e.length===0?null:(0,$.jsx)(J,{gap:`10px`,children:e.map(e=>{let i=`${r}-${e.key}`,a=t[e.key]??``;return e.options&&e.options.length>0?(0,$.jsx)(f,{id:i,label:e.label,value:a,onValueChange:t=>n(e.key,t),options:e.options.map(e=>({value:e.value,label:e.label}))},e.key):(0,$.jsx)(K,{id:i,label:e.label,value:a,placeholder:e.placeholder??``,type:e.secret===!0?`password`:`text`,autoComplete:`off`,onChange:t=>n(e.key,t.target.value)},e.key)})})}function wn({providerId:e,providerName:t,fields:n,onClose:r}){let i=z(),[a,o]=(0,Q.useState)(``),[s,c]=(0,Q.useState)(``),[l,u]=(0,Q.useState)(()=>xn(n)),d=(0,Q.useMemo)(()=>Sn(n,l),[n,l]);return(0,$.jsx)(P,{open:!0,onClose:r,title:`Import a ${t} credential`,size:`sm`,footer:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(y,{variant:`secondary`,size:`sm`,onClick:r,disabled:i.isPending,children:`Cancel`}),(0,$.jsx)(y,{variant:`primary`,size:`sm`,onClick:()=>{if(a.trim().length===0){x.error(`Credential required`,`Paste the token, key or exported JSON to import.`);return}if(d.length>0){x.error(`Missing required fields`,`Fill in: ${d.join(`, `)}`);return}i.mutate({providerId:e,credential:a.trim(),...Object.keys(l).length>0?{fields:l}:{},...s.trim().length>0?{accountLabel:s.trim()}:{}},{onSuccess:()=>{x.success(`Account imported`,`The credential was validated and saved`),r()},onError:e=>x.error(`Import failed`,e.message??`The provider rejected this credential`)})},disabled:i.isPending,icon:i.isPending?(0,$.jsx)(v,{size:13,className:`animate-spin`}):void 0,children:i.isPending?`Validating…`:`Import`})]}),children:(0,$.jsxs)(J,{gap:`12px`,children:[(0,$.jsxs)(`p`,{className:`text-badge leading-snug text-text-tertiary`,children:[`The credential is checked against `,t,` before it is saved, so one that no longer works is reported here instead of being stored.`]}),(0,$.jsx)(Cn,{fields:n,values:l,idPrefix:`import`,onChange:(e,t)=>u(n=>({...n,[e]:t}))}),(0,$.jsx)(K,{id:`import-account-label`,label:`Account label`,hint:`optional`,value:s,placeholder:e,onChange:e=>c(e.target.value)}),(0,$.jsx)(K,{id:`import-credential`,label:`Credential`,value:a,placeholder:`Paste the token, key, or exported JSON`,type:`password`,autoComplete:`off`,onChange:e=>o(e.target.value)})]})})}function Tn(e,t,n){let r=n?.trim()??``,i=r.indexOf(` — `),a=i>0?r.slice(0,i):``,o=i>0?r.slice(i+3):r;return{title:`${e}/${t} probe failed${a.length>0?` via ${a}`:``}`,detail:o.length>0?o:`Unknown error`}}function En(e,t,n){let{title:r,detail:i}=Tn(e,t,n);return[r,i]}function Dn(e){return e===`builtin`?`Built-in model`:e===`auto_free`?`Free tier, discovered from the provider`:e===`discovered`?`Fetched from provider`:`Added manually`}function On(e){return e===`auto_free`?`Free tier`:e===`discovered`?`Fetched`:`Manual`}var kn=[{key:`builtin`,label:`Built-in models`,hint:`Compiled catalog — can be disabled, not deleted`,matches:e=>e===null||e===`builtin`},{key:`auto_free`,label:`Free models (auto)`,hint:`Discovered from the provider's free tier`,matches:e=>e===`auto_free`},{key:`manual`,label:`Manually added`,hint:`Added by hand from the Add Model dialog`,matches:e=>e===`manual`},{key:`fetched`,label:`Fetched from provider`,hint:`Listed by the provider's /v1/models`,matches:e=>e!==null&&e!==`builtin`&&e!==`auto_free`&&e!==`manual`}],An={key:`disabled`,label:`Disabled models`,hint:`Turned off — not routable until re-enabled`};function jn(){return st.map(e=>({value:e,label:e===`auto`?`Thinking: auto`:e.charAt(0).toUpperCase()+e.slice(1)}))}function Mn({value:e,onChange:t,disabled:n,id:r=`probe-thinking-effort`}){return(0,$.jsx)(`div`,{title:`Reasoning effort every test in this section sends. Auto leaves the model's own reasoning default in place.`,className:`min-w-74 shrink-0`,children:(0,$.jsx)(f,{id:r,"aria-label":`Thinking effort`,value:e,disabled:n,onValueChange:e=>t(e),options:jn()})})}function Nn({providerId:e,provider:t,onClose:n}){let r=Oe(),i=je(),[a,o]=(0,Q.useState)(``),s=t?.supportedWireFamilies,c=t?.wireFamilyDefault!==void 0&&(s===void 0||s.includes(t.wireFamilyDefault))?t.wireFamilyDefault:s?.[0],l=(0,Q.useMemo)(()=>{let e=[`chat`,`responses`,`messages`],t=(s??[]).filter(t=>e.includes(t));return[...t,...e.filter(e=>!t.includes(e))]},[s]),[u,d]=(0,Q.useState)(c??`chat`),[p,m]=(0,Q.useState)(`auto`),[g,_]=(0,Q.useState)(`idle`),[b,S]=(0,Q.useState)(``),[C,w]=(0,Q.useState)(Ln),T=a.trim(),E=T.toLowerCase().startsWith(`${e.toLowerCase()}/`)&&T.length>e.length+1?T.slice(e.length+1):T,D=E!==T,O=()=>{E&&(_(`testing`),S(``),r.mutate({providerId:e,request:{modelId:E,wireFamily:u,reasoningEffort:p,serviceKind:`llm`}},{onSuccess:e=>{e.ok?_(`passed`):(_(`failed`),S(e.error??`Model probe failed`))},onError:e=>{_(`failed`),S(e.message??`Model probe failed`)}}))};return(0,$.jsx)(P,{open:!0,onClose:n,title:`Add Custom Model`,size:`sm`,footer:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(y,{variant:`secondary`,size:`sm`,onClick:n,disabled:i.isPending,children:`Cancel`}),(0,$.jsx)(y,{variant:`primary`,size:`sm`,disabled:i.isPending||E.length===0,onClick:()=>{if(!E)return;let t=Le(C.contextLimit),r=Le(C.outputLimit);if(t===null||r===null){x.error(`Invalid limits`,`Use a token count such as 512k, 200000, or 1.5m.`);return}i.mutate({providerId:e,modelIds:[E],wireFamily:u,metadata:{contextLimit:t??null,outputLimit:r??null,passthrough:C.passthrough,image:C.passthrough?!0:C.image,reasoning:C.passthrough?!0:C.reasoning,toolCall:C.passthrough?!0:C.toolCall}},{onSuccess:()=>{x.success(`Custom model added`,`Sent to ${e}/${E}`),n()},onError:e=>x.error(`Failed to add model`,e.message??`Unable to register model`)})},children:i.isPending?`Adding...`:`Add Model`})]}),children:(0,$.jsxs)(J,{gap:`10px`,children:[(0,$.jsxs)(Y,{gap:`8px`,align:`flex-end`,children:[(0,$.jsx)(K,{label:`Model ID`,autoFocus:!0,placeholder:`e.g. gpt-4o, free-model-id`,value:a,onChange:e=>{o(e.target.value),_(`idle`),S(``)},onKeyDown:e=>{e.key===`Enter`&&E.length>0&&O()},className:`flex-1`}),(0,$.jsx)(y,{variant:`secondary`,size:`sm`,icon:g===`testing`?(0,$.jsx)(v,{size:13,className:`animate-spin`}):(0,$.jsx)(h,{size:13}),disabled:r.isPending||E.length===0,onClick:O,className:`shrink-0`,children:g===`testing`?`Testing...`:`Test`})]}),D&&(0,$.jsxs)(`div`,{className:`mt-1 text-badge text-text-tertiary`,children:[`Using `,(0,$.jsx)(`span`,{className:`font-mono tabular-nums`,children:E}),` (provider prefix removed).`]}),(0,$.jsx)(f,{label:`Wire family`,id:`add-model-wire-family`,value:u,onValueChange:e=>{d(e),_(`idle`),S(``)},options:l.map(e=>({value:e,label:Un(e)}))}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`div`,{className:`text-badge font-semibold text-text-secondary mb-2`,children:`Thinking`}),(0,$.jsx)(Mn,{id:`add-model-thinking-effort`,value:p,onChange:e=>{m(e),_(`idle`),S(``)},disabled:r.isPending}),(0,$.jsx)(`div`,{className:`text-badge text-text-tertiary mt-2`,children:`Sent with the test. Auto leaves the model's own reasoning default in place.`})]}),(0,$.jsx)(Rn,{draft:C,onChange:w,idPrefix:`add-model`,disabled:i.isPending}),s!==void 0&&!s.includes(u)&&(0,$.jsxs)(`div`,{className:`mt-1 text-badge text-text-tertiary`,children:[`This provider does not declare the`,` `,(0,$.jsx)(`span`,{className:`font-mono tabular-nums`,children:Un(u)}),` wire. The request is sent as chosen; the upstream decides whether it answers.`]}),g===`passed`&&(0,$.jsx)(Qe,{tone:`success`,live:`status`,children:`Model test passed — ready to add.`}),g===`failed`&&(0,$.jsx)(Qe,{tone:`danger`,live:`alert`,children:b||`Model test failed.`})]})})}function Pn(){return{contextLimit:``,outputLimit:``,passthrough:!1,image:!0,reasoning:!0,toolCall:!0}}var Fn=String(ze),In=String(H);function Ln(){return{...Pn(),contextLimit:Fn,outputLimit:In}}function Rn({draft:e,onChange:t,idPrefix:n,disabled:r=!1}){let i=e.passthrough;return(0,$.jsxs)(J,{gap:`10px`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`div`,{className:`text-badge font-semibold text-text-secondary mb-2`,children:`Limits`}),(0,$.jsxs)(Y,{gap:`8px`,children:[(0,$.jsx)(K,{label:`Context`,id:`${n}-context`,placeholder:Fn,value:e.contextLimit,disabled:r,onChange:n=>t({...e,contextLimit:n.target.value}),className:`flex-1`}),(0,$.jsx)(K,{label:`Output`,id:`${n}-output`,placeholder:In,value:e.outputLimit,disabled:r,onChange:n=>t({...e,outputLimit:n.target.value}),className:`flex-1`})]}),(0,$.jsxs)(`label`,{className:`inline-flex items-center gap-2 mt-2 text-badge text-text-secondary cursor-pointer`,children:[(0,$.jsx)(`input`,{type:`checkbox`,id:`${n}-fallback-limits`,checked:e.contextLimit===Fn&&e.outputLimit===In,disabled:r,onChange:n=>t(n.target.checked?{...e,contextLimit:Fn,outputLimit:In}:{...e,contextLimit:``,outputLimit:``})}),`Use fallback — `,Re(ze),` ctx ·`,` `,Re(H),` out`]})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`div`,{className:`text-badge font-semibold text-text-secondary mb-2`,children:`Capabilities`}),(0,$.jsx)(J,{gap:`6px`,children:[[`image`,`Can image`,e.image],[`reasoning`,`Reasoning`,e.reasoning],[`toolCall`,`Tools`,e.toolCall]].map(([a,o,s])=>(0,$.jsxs)(`label`,{className:`inline-flex items-center gap-2 text-badge text-text-secondary`,style:i?{opacity:.5}:void 0,children:[(0,$.jsx)(`input`,{type:`checkbox`,id:`${n}-${a}`,checked:i?!0:s,disabled:r||i,onChange:n=>t({...e,[a]:n.target.checked})}),o]},a))}),(0,$.jsxs)(`label`,{className:`inline-flex items-center gap-2 mt-2 text-badge text-text-secondary cursor-pointer`,children:[(0,$.jsx)(`input`,{type:`checkbox`,id:`${n}-passthrough`,checked:e.passthrough,disabled:r,onChange:n=>t({...e,passthrough:n.target.checked})}),`Passthrough — accept every capability`]}),i?(0,$.jsx)(`div`,{className:`text-badge text-text-tertiary mt-2`,children:`Passthrough grants all of the above, so they are locked on. Uncheck it to restore your own choices.`}):null]})]})}function zn({providerId:e,model:t,onClose:n}){let r=me(),[i,a]=(0,Q.useState)(()=>({contextLimit:t.contextLimit?String(t.contextLimit):``,outputLimit:t.outputLimit?String(t.outputLimit):``,passthrough:!1,image:t.vision===!0,reasoning:t.reasoning===!0,toolCall:t.toolCall===!0}));return(0,$.jsx)(P,{open:!0,onClose:n,title:`Edit Model`,size:`sm`,footer:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(y,{variant:`secondary`,size:`sm`,onClick:n,disabled:r.isPending,children:`Cancel`}),(0,$.jsx)(y,{variant:`primary`,size:`sm`,disabled:r.isPending,onClick:()=>{let a=Le(i.contextLimit),o=Le(i.outputLimit);if(a===null||o===null){x.error(`Invalid limits`,`Use a token count such as 512k, 200000, or 1.5m.`);return}r.mutate({providerId:e,modelId:t.modelId,route:t.route??``,metadata:{contextLimit:a??null,outputLimit:o??null,passthrough:i.passthrough,image:i.passthrough?!0:i.image,reasoning:i.passthrough?!0:i.reasoning,toolCall:i.passthrough?!0:i.toolCall}},{onSuccess:()=>n(),onError:e=>x.error(`Failed to update model`,e.message??`Unable to update model`)})},children:r.isPending?`Saving...`:`Save`})]}),children:(0,$.jsxs)(J,{gap:`10px`,children:[(0,$.jsxs)(`div`,{className:`text-badge text-text-tertiary`,children:[`Editing `,(0,$.jsx)(`span`,{className:`font-mono tabular-nums`,children:t.modelId})]}),(0,$.jsx)(Rn,{draft:i,onChange:a,idPrefix:`edit-model`,disabled:r.isPending})]})})}function Bn({providerId:e,model:t,serviceKind:n,searchCapable:r,thinkingEffort:i,onDeleteRequest:a,onEditRequest:c,deletePending:l}){let d=Oe(),f=Pe(),[_,b]=(0,Q.useState)(!1),[w,T]=(0,Q.useState)(null),D=Ze(),O=n===`llm`?ct(t.modelId,i===`auto`?null:i):t.modelId,k=`${e}/${O}`,A=n===`websearch`?`Searching…`:`Thinking…`,j=()=>{d.mutate({providerId:e,request:{modelId:t.modelId,route:t.route,...n===`llm`?{reasoningEffort:i}:{},serviceKind:n}},{onSuccess:t=>{if(T({ok:t.ok,latencyMs:t.latencyMs}),!t.ok){let{title:n,detail:r}=Tn(e,O,t.error);x.error(n,r);return}let n=t.sample?.trim()??``,r=t.reportedModel?.trim()??``;x.successRich(`${O} · END ${W(t.latencyMs)}`,(0,$.jsxs)(`span`,{className:`grid gap-2 min-w-0`,children:[r?(0,$.jsxs)(Y,{gap:`6px`,align:`center`,className:`min-w-0`,children:[(0,$.jsx)(S,{size:12,"aria-hidden":`true`,className:`shrink-0 text-text-tertiary`}),(0,$.jsx)(`span`,{className:`truncate font-mono text-badge text-text-secondary`,title:r,children:r})]}):null,(0,$.jsx)(`span`,{children:n||`No sample text in the response.`})]}),[r,n].filter(Boolean).join(`
|
|
3
3
|
`)||`No sample text in the response.`)},onError:t=>{T({ok:!1,latencyMs:0}),x.error(...En(e,O,t.message))}})},M=()=>{let n=!t.enabled;f.mutate({providerId:e,request:{modelId:t.modelId,route:t.route,enabled:n}},{onSuccess:()=>x.success(n?`Model enabled`:`Model disabled`,t.modelId),onError:e=>x.error(`Failed to update model`,e.message??`Unable to update model`)})};return(0,$.jsx)($.Fragment,{children:(0,$.jsxs)(`div`,{className:`model-card box-border flex w-full min-w-0 flex-1-auto flex-col gap-5 rounded-panel border border-inner-border p-6 ${t.enabled?`bg-surface-2`:`bg-surface-1 opacity-72`}`,children:[(0,$.jsxs)(`div`,{className:`flex items-start gap-4 min-w-0`,children:[(0,$.jsx)(`span`,{className:`inline-flex items-center justify-center w-13 h-13 rounded-inset bg-teal-soft text-teal shrink-0`,children:(0,$.jsx)(o,{size:14})}),(0,$.jsxs)(`div`,{className:`flex-1 min-w-0 flex flex-col gap-1`,children:[(0,$.jsx)(`div`,{title:k,className:`font-mono tabular-nums min-w-0 truncate text-caption font-semibold leading-[1.35]`,children:O}),(0,$.jsxs)(`div`,{className:`flex items-center gap-3 min-w-0 text-micro text-text-tertiary`,children:[(0,$.jsx)(`span`,{title:`${t.wireFamily} · ${t.route??e}`,className:`shrink-0 rounded-pill px-3 py-0.5 text-micro font-bold tracking-[0.04em]`,style:{...Hn(t.wireFamily)},children:Un(t.wireFamily)}),t.source!==null&&t.source!==`builtin`?(0,$.jsx)(`span`,{title:Dn(t.source),className:`shrink-0 rounded-pill border border-teal-soft px-3 py-0.5 text-micro font-bold tracking-[0.04em] text-teal`,children:On(t.source)}):null,t.enabled?null:(0,$.jsx)(`span`,{className:`shrink-0 rounded-pill bg-red-soft px-3 py-0.5 text-micro font-bold tracking-[0.04em] text-red`,children:`Off`})]})]}),(0,$.jsx)(y,{variant:`ghost`,size:`sm`,icon:_?(0,$.jsx)(u,{size:12}):(0,$.jsx)(C,{size:12}),"aria-label":`Copy ${k}`,title:`Copy ${k}`,onClick:()=>{navigator.clipboard?.writeText(k),b(!0),D(()=>b(!1),1500)},className:`shrink-0 p-2 opacity-70`})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-3 min-w-0 text-badge text-text-secondary`,children:[(0,$.jsxs)(`span`,{className:`inline-flex gap-2.5`,children:[t.reasoning?(0,$.jsx)(`span`,{title:`Reasoning`,"aria-label":`Reasoning`,className:`inline-flex text-purple`,children:(0,$.jsx)(s,{size:12})}):null,t.vision?(0,$.jsx)(`span`,{title:`Vision`,"aria-label":`Vision`,className:`inline-flex text-status-info`,children:(0,$.jsx)(E,{size:12})}):null,t.toolCall?(0,$.jsx)(`span`,{title:`Tool calling`,"aria-label":`Tool calling`,className:`inline-flex text-orange`,children:(0,$.jsx)(ce,{size:12})}):null,r?(0,$.jsx)(`span`,{title:`Web search`,"aria-label":`Web search`,className:`inline-flex text-teal`,children:(0,$.jsx)(g,{size:12})}):null]}),(0,$.jsxs)(`span`,{className:`whitespace-nowrap`,children:[t.limitsEstimated?(0,$.jsx)(`span`,{title:U,"aria-label":`Limits are a fallback estimate`,className:`estimate-dot inline-flex items-center justify-center rounded-full border border-inner-border bg-surface-2 text-orange cursor-help mr-1 align-middle`,children:(0,$.jsx)(p,{size:9,"aria-hidden":`true`})}):null,t.contextLimit?`${Re(t.contextLimit)} ctx`:(0,$.jsx)(`span`,{title:Be,className:`cursor-help`,children:`n/a ctx`}),t.outputLimit?` · ${Re(t.outputLimit)} out`:(0,$.jsx)(`span`,{title:Be,className:`cursor-help`,children:` · n/a out`})]}),c?(0,$.jsx)(`button`,{type:`button`,className:`shrink-0 grid place-items-center w-6 h-6 p-0 border-0 bg-transparent text-text-tertiary cursor-pointer rounded-tiny hover:bg-inner-border hover:text-text-primary`,title:`Edit limits and capabilities`,"aria-label":`Edit ${t.modelId} limits and capabilities`,onClick:()=>c(t),children:(0,$.jsx)(F,{size:11})}):null]}),(0,$.jsxs)(`div`,{className:`flex gap-3 items-center flex-wrap`,children:[(0,$.jsx)(y,{variant:`secondary`,size:`sm`,disabled:d.isPending,onClick:j,"aria-label":`Test ${O}`,title:d.isPending?`Probing ${O}…`:w?.ok?`Last probe OK in ${W(w.latencyMs)} — click to re-test`:w?`Last probe failed — click to retry`:`Test ${O}`,className:`flex-1 justify-center`,icon:d.isPending?(0,$.jsx)(v,{size:12,className:`animate-spin`}):w?w.ok?(0,$.jsx)(`span`,{className:`inline-flex text-green`,children:(0,$.jsx)(m,{size:12})}):(0,$.jsx)(`span`,{className:`inline-flex text-red`,children:(0,$.jsx)(ee,{size:12})}):(0,$.jsx)(h,{size:12}),children:d.isPending?A:w?.ok?W(w.latencyMs):w?`Fail`:`Test`}),(0,$.jsx)(y,{variant:`ghost`,size:`sm`,disabled:f.isPending,onClick:M,icon:t.enabled?(0,$.jsx)(re,{size:12}):(0,$.jsx)(nt,{size:12}),"aria-label":t.enabled?`Disable ${t.modelId}`:`Enable ${t.modelId}`,title:t.enabled?`Disable model`:`Enable model`,className:`flex-1 justify-center ${t.enabled?`text-red`:`text-green`}`,children:t.enabled?`Disable`:`Enable`}),t.source===`builtin`?null:(0,$.jsx)(y,{variant:`ghost`,size:`sm`,disabled:l,onClick:()=>a(t),icon:(0,$.jsx)(se,{size:12}),"aria-label":`Delete ${t.modelId}`,title:`Delete model`,className:`model-card-delete shrink-0 px-4 py-3 text-text-tertiary`})]})]})})}var Vn=(0,Q.memo)(Bn);function Hn(e){return e===`responses`?{color:`var(--purple)`,background:`var(--purple-soft)`}:e===`messages`?{color:`var(--orange)`,background:`color-mix(in srgb, var(--orange) 14%, transparent)`}:{color:`var(--teal)`,background:`var(--teal-soft)`}}function Un(e){let t=e.toLowerCase();return t===`responses`?`Responses`:t===`messages`?`Messages`:`Chat`}function Wn({providerId:e,models:t,thinkingEffort:n,serviceKind:r=`llm`,searchCapable:i=!1}){let a=R(),[o,s]=(0,Q.useState)(null),[c,l]=(0,Q.useState)(null),u=e=>e.enabled!==!1,d=kn.map(e=>({...e,rows:t.filter(t=>u(t)&&e.matches(t.source))})).filter(e=>e.rows.length>0),f=t.filter(e=>!u(e)),p=t=>(0,$.jsx)(Vn,{providerId:e,model:t,serviceKind:r,searchCapable:i,thinkingEffort:n,deletePending:a.isPending,onDeleteRequest:s,onEditRequest:t.source===`builtin`?void 0:l},`${t.modelId}::${t.route}`);return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(J,{gap:`16px`,children:[d.map(e=>(0,$.jsxs)(`section`,{className:`flex flex-col gap-4`,children:[(0,$.jsxs)(`div`,{className:`flex items-baseline gap-4 min-w-0`,children:[(0,$.jsx)(`span`,{className:`text-caption font-bold text-text-secondary`,children:e.label}),(0,$.jsx)(`span`,{className:`mt-1 text-badge text-text-tertiary`,children:e.rows.length}),(0,$.jsxs)(`span`,{title:e.hint,className:`text-micro text-text-tertiary overflow-hidden truncate`,children:[`· `,e.hint]})]}),(0,$.jsx)(`div`,{className:`provider-grid grid gap-4 items-stretch`,children:e.rows.map(p)})]},e.key)),f.length===0?null:(0,$.jsxs)(`section`,{className:`flex flex-col gap-4`,children:[(0,$.jsxs)(`div`,{className:`flex items-baseline gap-4 min-w-0`,children:[(0,$.jsx)(`span`,{className:`text-caption font-bold text-text-secondary`,children:An.label}),(0,$.jsx)(`span`,{className:`mt-1 text-badge text-text-tertiary`,children:f.length}),(0,$.jsxs)(`span`,{title:An.hint,className:`text-micro text-text-tertiary overflow-hidden truncate`,children:[`· `,An.hint]})]}),(0,$.jsx)(`div`,{className:`provider-grid grid gap-4 items-stretch`,children:f.map(p)})]})]}),(0,$.jsx)(fe,{open:o!==null,onClose:()=>{a.isPending||s(null)},onConfirm:async()=>{o!==null&&(await a.mutateAsync({providerId:e,request:{modelId:o.modelId,route:o.route}}),x.success(`Model deleted`,`${e}/${o.modelId}`),s(null))},title:`Delete model?`,message:`Delete ${e}/${o?.modelId??``} from the provider catalog?`,confirmLabel:`Delete`,danger:!0}),c===null?null:(0,$.jsx)(zn,{providerId:e,model:c,onClose:()=>l(null)})]})}function Gn(e){return e===`llm`?`LLM`:e===`websearch`?`Search`:e===`imageGeneration`?`Image`:e===`videoGeneration`?`Video`:e}function Kn(e){let t=e.serviceKinds;return Array.isArray(t)&&t.length>0?t:[`llm`]}function qn(){let{providerId:e}=he(),[t]=_e(),n=e??``,r=t.get(`service`),[i,a]=(0,Q.useState)(r===`websearch`||r===`imageGeneration`||r===`videoGeneration`?r:`llm`),o=Ce(),s=we(n),l=Ee(n),u=pe(),d=pe({silent:!0}),[f,p]=(0,Q.useState)(!1),m=Se(),h=Me(),_=be(),v=le(),[b,S]=(0,Q.useState)(!1),[C,T]=(0,Q.useState)(!1),E=Oe(),[D,ee]=(0,Q.useState)(``),[te,N]=(0,Q.useState)(``),[F,I]=(0,Q.useState)(null),ae=e=>`cartethyia:provider:${e}:thinking-effort`,oe=e=>{if(typeof window>`u`||!window.localStorage)return`auto`;let t=window.localStorage.getItem(ae(e));if(t===null)return`auto`;let n=t.trim().toLowerCase();return st.includes(n)?n:`auto`},[ce,de]=(0,Q.useState)(()=>oe(n));(0,Q.useEffect)(()=>{if(!n)return;let e=oe(n);e!==ce&&de(e)},[n]),(0,Q.useEffect)(()=>{typeof window>`u`||!window.localStorage||!n||window.localStorage.setItem(ae(n),ce)},[n,ce]);let[me,ge]=(0,Q.useState)(!1),[ve,ye]=(0,Q.useState)(!1),[R,xe]=(0,Q.useState)(null),[Te,De]=(0,Q.useState)({}),[ke,Ae]=(0,Q.useState)({}),[z,je]=(0,Q.useState)(null),[Ne,Pe]=(0,Q.useState)(!1),[Ie,Le]=(0,Q.useState)(null),H=(0,Q.useRef)(null),Re=(0,Q.useRef)(null);(0,Q.useEffect)(()=>()=>{let e=H.current;H.current=null,e&&!e.closed&&e.close()},[]);let U=(o.data??[]).find(e=>e.providerId===n),ze=n===`opencode`||n===`cline`,Be=U===void 0?[`llm`]:Kn(U),W=[];for(let e of Be)(e===`llm`||e===`websearch`||e===`imageGeneration`||e===`videoGeneration`)&&W.push(e);(0,Q.useEffect)(()=>{if(U===void 0)return;let e=r===`websearch`||r===`imageGeneration`||r===`videoGeneration`||r===`llm`?r:void 0,t=W[0];if(e!==void 0&&W.includes(e)){i!==e&&a(e);return}!W.includes(i)&&t!==void 0&&a(t)},[U,r,i,W.join(`|`)]),(0,Q.useEffect)(()=>{ze&&U!==void 0&&U.supportsModelDiscovery!==!1&&Re.current!==n&&(Re.current=n,d.mutate(n))},[ze,d,n,U?.supportsModelDiscovery]);let G=l.data??[],K=s.data??[],q=(()=>{let e=new Map;for(let t of K){let n=`${t.serviceKind??`llm`}:${t.modelId}`,r=e.get(n);if(!r)e.set(n,t);else{let i=r.contextLimit??0;(t.contextLimit??0)>i&&e.set(n,t)}}return[...e.values()].sort((e,t)=>e.modelId.localeCompare(t.modelId))})(),X=q.filter(e=>e.serviceKind===`llm`||e.serviceKind===void 0),Ue=q.filter(e=>e.serviceKind===`websearch`),We=q.filter(e=>e.serviceKind===`imageGeneration`),Ge=q.filter(e=>e.serviceKind===`videoGeneration`),Z=W.includes(i)?i:W[0],Ke=te||Ue[0]?.modelId||``,qe=()=>{let e=D.trim();Ke&&e&&(I(null),E.mutate({providerId:n,request:{modelId:Ke,serviceKind:`websearch`,prompt:e}},{onSuccess:e=>I({ok:e.ok,latencyMs:e.latencyMs,...e.searchResults?{results:e.searchResults,count:e.searchResults.length}:{},...e.error?{error:e.error}:{}}),onError:e=>I({ok:!1,error:e instanceof Error?e.message:`Search test failed`})}))};if(o.isPending)return(0,$.jsx)(A,{label:`Loading provider...`});if(o.isError)return(0,$.jsx)(k,{title:`Unable to load providers`,message:`The provider catalog could not be read, so this page cannot resolve its provider.`,onRetry:()=>void o.refetch(),retrying:o.isFetching,action:(0,$.jsx)(lt,{to:`/providers`,label:`Back to providers`})});if(!U)return(0,$.jsx)(j,{icon:(0,$.jsx)(rt,{size:20}),title:`Provider not found`,message:`No provider named “${n}”. It may have been removed, or the link is stale.`,action:(0,$.jsx)(lt,{to:`/providers`,label:`Back to providers`})});let Je=G.filter(e=>e.status===`active`).length,Ye=e=>{let t=e===`browser`?U?.oauthFlows?.browserLoginFields??[]:U?.oauthFlows?.deviceLoginFields??[];if(t.length===0){e===`browser`?Ze():ge(!0);return}De(xn(t)),xe(e)},Xe=()=>{if(R===null)return;let e=Sn(R===`browser`?U?.oauthFlows?.browserLoginFields??[]:U?.oauthFlows?.deviceLoginFields??[],Te);if(e.length>0){x.error(`Missing required fields`,`Fill in: ${e.join(`, `)}`);return}let t=R;xe(null),t===`browser`?Ze(Te):(Ae(Te),ge(!0))},Ze=e=>{let t=window.open(`about:blank`,`cartethyia-oauth`,`popup,width=720,height=820`);t&&(t.opener=null,H.current=t),_.mutate({providerId:n,...e===void 0?{}:{parameters:e}},{onSuccess:({authorizeUrl:e,state:n})=>{let r=null;if(t&&!t.closed?(t.location.href=e,r=t):(r=window.open(e,`cartethyia-oauth`,`popup,width=720,height=820`),r&&(r.opener=null,H.current=r)),!r){x.error(`Popup blocked`,`Allow popups to complete OAuth login.`);return}Le({authorizeUrl:e,state:n,popup:r})},onError:e=>{t&&!t.closed&&t.close(),H.current===t&&(H.current=null),x.error(`Failed to start OAuth`,e.message??`Unable to start authorization`)}})};return(0,$.jsxs)(J,{gap:`16px`,children:[(0,$.jsx)(ut,{title:`${U.label||U.displayName}${Z?` (${Gn(Z)})`:``}`,description:`${U.providerId}/${U.baseUrl?` · ${U.baseUrl}`:``}`,icon:(0,$.jsx)(Ve,{icon:U.providerId,name:U.label||U.displayName,size:28}),back:{to:`/providers`,label:`Back to Providers`},actions:(0,$.jsx)(Y,{gap:`8px`,className:`flex-wrap w-full max-w-full min-w-0`,children:U.isBuiltIn?(0,$.jsx)(y,{variant:U.enabled?`danger`:`secondary`,icon:U.enabled?(0,$.jsx)(re,{size:13}):(0,$.jsx)(nt,{size:13}),loading:h.isPending,onClick:()=>h.mutate({providerId:n,enabled:!U.enabled},{onSuccess:e=>x.success(e.enabled?`Provider enabled`:`Provider disabled`,U.label||U.displayName),onError:e=>x.error(`Provider update failed`,e.message??`Unable to change provider availability`)}),title:U.enabled?`Disable provider globally`:`Enable provider globally`,children:U.enabled?`Disable`:`Enable`}):null})}),(0,$.jsx)(Tt,{provider:U}),Z===`llm`?(0,$.jsx)(bt,{providerId:n,clientVersion:U.clientVersion,routeIdentityVersions:U.routeIdentityVersions,userAgentEditable:dt(U)}):null,U.requiresAccount===!1?(0,$.jsxs)(V,{children:[(0,$.jsx)(Fe,{title:`Accounts`,icon:(0,$.jsx)($e,{size:16})}),(0,$.jsx)(B,{children:(0,$.jsx)(`p`,{className:`text-caption text-text-secondary`,children:`This provider is a public, unauthenticated route — no account or credential is needed. Routing already works without any setup here.`})})]}):(0,$.jsxs)(V,{children:[(0,$.jsx)(Fe,{title:`Accounts`,subtitle:`${G.length} total · ${Je} active · ${G.length-Je} disabled`,icon:(0,$.jsx)($e,{size:16}),action:(0,$.jsxs)(He,{children:[U.oauthFlows?.browser&&(0,$.jsx)(y,{variant:`secondary`,size:`sm`,icon:(0,$.jsx)(et,{size:13}),disabled:_.isPending,onClick:()=>Ye(`browser`),title:`Browser OAuth login — opens the provider authorize page in a popup`,children:_.isPending?`Starting...`:`Login with browser`}),U.oauthFlows?.device&&(0,$.jsx)(y,{variant:`secondary`,size:`sm`,icon:(0,$.jsx)(M,{size:13}),onClick:()=>Ye(`device`),title:`Device-code login — enter the shown code on the provider site`,children:`Login with device code`}),U.oauthFlows?.import&&(0,$.jsx)(y,{variant:`secondary`,size:`sm`,icon:(0,$.jsx)(w,{size:13}),onClick:()=>ye(!0),title:U.oauthFlows.browser||U.oauthFlows.device?`Import a credential you already hold — a refresh token, an exported auth blob, or an API key`:`Add and validate an API key`,children:U.oauthFlows.browser||U.oauthFlows.device?`Import credential`:`Add API key`}),(0,$.jsx)(y,{variant:`primary`,size:`sm`,icon:(0,$.jsx)(ne,{size:13}),onClick:()=>S(!0),children:`Add Account`})]})}),(0,$.jsxs)(B,{className:`flex flex-col gap-5`,children:[(0,$.jsx)(xt,{providerId:n}),l.isPending?(0,$.jsx)(A,{label:`Loading accounts...`}):l.isError?(0,$.jsx)(k,{message:`Failed to load accounts`,onRetry:()=>l.refetch()}):G.length===0?(0,$.jsx)(j,{title:`No accounts connected`,message:`Add an API key or OAuth credential to route requests to this provider.`}):(0,$.jsx)(pn,{providerId:n,accounts:G,onDelete:e=>je(e),showGrokProbe:Z===`llm`&&n===`grok`,grokProbePending:m.isPending,onGrokProbe:()=>{m.mutate({providerId:n,request:{modelId:`grok-4.6`,prompt:`reply my message with exact number 407`,stream:!0,serviceKind:`llm`}},{onSuccess:e=>{let t=e.results.filter(e=>e.ok).length,n=e.results.filter(e=>e.statusCode===202).length,r=e.results.length-t-n;x.success(`Grok account probe complete`,`${t} passed · ${n} returned 202 and were parked in cooldown · ${r} other failures`)},onError:e=>x.error(`Grok account probe failed`,e.message??`Unable to probe Grok accounts`)})}})]})]}),Z===`llm`?(0,$.jsx)($.Fragment,{children:(0,$.jsxs)(V,{children:[(0,$.jsx)(Fe,{title:`Models`,subtitle:`${X.length} model${X.length===1?``:`s`} registered`,icon:(0,$.jsx)(c,{size:16}),action:(0,$.jsxs)(Y,{gap:`6px`,className:`flex-wrap items-center`,children:[(0,$.jsx)(Mn,{id:`models-section-thinking-effort`,value:ce,onChange:de}),(0,$.jsx)(y,{variant:`secondary`,size:`sm`,icon:(0,$.jsx)(ie,{size:13,className:u.isPending||d.isPending?`animate-spin`:``}),disabled:u.isPending||d.isPending,onClick:()=>u.mutate(n),children:u.isPending||d.isPending?`Fetching...`:`Fetch models`}),(0,$.jsx)(y,{variant:`secondary`,size:`sm`,icon:(0,$.jsx)(se,{size:13,className:f?`animate-spin`:``}),disabled:u.isPending||d.isPending||f||X.filter(e=>e.source!==`builtin`&&e.source!==null).length===0,onClick:async()=>{let e=X.filter(e=>e.source!==`builtin`&&e.source!==null);if(e.length!==0&&confirm(`Delete ${e.length} fetched/manual model(s) for ${n}?`)){p(!0);try{let t=await ue(`/providers/${encodeURIComponent(n)}/models/bulk`,{method:`DELETE`,body:JSON.stringify({items:e.map(e=>({modelId:e.modelId,route:e.route}))})});await Promise.all([v.invalidateQueries({queryKey:L.providers.models(n)}),v.invalidateQueries({queryKey:L.providers.all})]);let r=t.failures.length;x.success(`Fetched models deleted`,r>0?`${t.deleted}/${t.total} removed, ${r} failed`:`${t.deleted}/${t.total} removed`)}catch(e){x.error(`Failed to delete fetched models`,e.message??`Unable to delete models`)}finally{p(!1)}}},children:f?`Deleting…`:`Delete fetched`}),(0,$.jsx)(y,{variant:`primary`,size:`sm`,icon:(0,$.jsx)(ne,{size:13}),onClick:()=>T(!0),children:`Add Model`})]})}),(0,$.jsx)(B,{className:`flex flex-col gap-8`,children:s.isPending?(0,$.jsx)(A,{label:`Loading models...`}):s.isError?(0,$.jsx)(k,{message:`Failed to load models`,onRetry:()=>s.refetch()}):X.length===0?(0,$.jsx)(j,{title:`No LLM models found`,message:`No LLM models published by this provider yet. Sync or add a custom model above.`}):(0,$.jsx)(Wn,{providerId:n,models:X,serviceKind:`llm`,thinkingEffort:ce,searchCapable:U?.supportsWebSearch===!0})})]})}):Z===`websearch`?(0,$.jsxs)(V,{children:[(0,$.jsx)(Fe,{title:`Web Search`,subtitle:`Run a real search request through the selected provider.`,icon:(0,$.jsx)(g,{size:16})}),(0,$.jsx)(B,{className:`flex flex-col gap-6`,children:s.isPending?(0,$.jsx)(A,{label:`Loading search models...`}):s.isError?(0,$.jsx)(k,{message:`Failed to load search models`,onRetry:()=>s.refetch()}):Ue.length===0?(0,$.jsx)(j,{title:`No Search models found`,message:`This provider advertises Search, but no websearch model is registered yet.`}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`label`,{className:`flex flex-col gap-2.5 text-badge text-text-secondary`,children:[`Search model`,(0,$.jsx)(`select`,{value:Ke,onChange:e=>{N(e.target.value),I(null)},className:`w-full min-h-17 rounded-inset border border-inner-border bg-surface-1 text-text-primary px-4.5 py-0`,children:Ue.map(e=>(0,$.jsx)(`option`,{value:e.modelId,children:e.modelId},`${e.modelId}:${e.route}`))})]}),(0,$.jsxs)(`label`,{className:`flex flex-col gap-2.5 text-badge text-text-secondary`,children:[`Query`,(0,$.jsx)(`input`,{value:D,onChange:e=>ee(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),qe())},placeholder:`What is the latest news about AI?`,className:`w-full min-h-17 rounded-inset border border-inner-border bg-surface-1 text-text-primary px-4.5 py-0`})]}),(0,$.jsxs)(Y,{gap:`8px`,className:`items-center flex-wrap`,children:[(0,$.jsx)(y,{variant:`primary`,size:`sm`,disabled:E.isPending||D.trim().length===0,loading:E.isPending,onClick:qe,children:`Test search`}),F?(0,$.jsx)(`span`,{className:`text-badge`,style:{color:F.ok?`var(--green)`:`var(--red)`},children:F.ok?`Search ok · ${F.latencyMs}ms · ${F.count??0} result(s)`:F.error??`Search failed.`}):null]}),F&&F.results&&F.results.length>0?(0,$.jsx)(`div`,{className:`flex max-h-110 flex-col gap-4 overflow-y-auto rounded-inset border border-inner-border bg-surface-1 p-4`,children:F.results.map((e,t)=>(0,$.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,$.jsx)(`a`,{href:e.url,target:`_blank`,rel:`noreferrer`,className:`text-caption text-text-primary font-semibold`,children:e.title||e.url}),(0,$.jsx)(`span`,{className:`text-badge text-text-tertiary break-all`,children:e.url}),e.snippet?(0,$.jsx)(`span`,{className:`text-badge text-text-secondary`,children:e.snippet}):null]},`${e.url}:${t}`))}):null]})})]}):Z===`imageGeneration`||Z===`videoGeneration`?(0,$.jsxs)(V,{children:[(0,$.jsx)(Fe,{title:Gn(Z),subtitle:Z===`imageGeneration`?`Models that return an image rather than text.`:`Models that return a video. Wired and routable; not yet verified against a live account.`,icon:Z===`imageGeneration`?(0,$.jsx)(O,{size:16}):(0,$.jsx)(at,{size:16})}),(0,$.jsx)(B,{className:`flex flex-col gap-6`,children:s.isPending?(0,$.jsx)(A,{label:`Loading ${Gn(Z).toLowerCase()} models...`}):s.isError?(0,$.jsx)(k,{message:`Failed to load ${Gn(Z).toLowerCase()} models`,onRetry:()=>s.refetch()}):(Z===`imageGeneration`?We:Ge).length===0?(0,$.jsx)(j,{title:`No ${Gn(Z)} models found`,message:`This provider advertises ${Gn(Z)}, but no ${Z} model is registered yet.`}):(0,$.jsx)(Wn,{providerId:n,models:Z===`imageGeneration`?We:Ge,serviceKind:`llm`,searchCapable:!1,thinkingEffort:`auto`})})]}):(0,$.jsx)(V,{children:(0,$.jsx)(B,{children:(0,$.jsx)(j,{title:`Service not available`,message:`This provider advertises ${Be.map(Gn).join(`, `)}, but the dashboard has no controls for the selected service yet.`})})}),b&&(0,$.jsx)(gn,{providerId:n,accounts:G,onClose:()=>S(!1)}),Z===`llm`&&C?(0,$.jsx)(Nn,{providerId:n,provider:U,onClose:()=>T(!1)}):null,(0,$.jsx)(fe,{open:z!==null,onClose:()=>{Ne||je(null)},onConfirm:async()=>{if(z){Pe(!0);try{let e=z.tenantId===null?`/global/accounts/${encodeURIComponent(z.id)}`:`/accounts/${encodeURIComponent(z.id)}`;await ue(e,{method:`DELETE`}),v.removeQueries({queryKey:L.quota.account(z.id),exact:!0}),await Promise.all([v.invalidateQueries({queryKey:L.providers.accounts(n)}),v.invalidateQueries({queryKey:L.providers.healthEvents(n,z.id)}),v.invalidateQueries({queryKey:L.providers.all}),v.invalidateQueries({queryKey:L.quota.all})]),x.success(`Account deleted`,z.label||z.id.slice(0,8)),je(null)}catch(e){throw x.error(`Failed to delete account`,e.message??`Unable to delete account`),e}finally{Pe(!1)}}},title:`Delete account?`,message:`Delete "${z?.label||z?.id.slice(0,8)}"? This cannot be undone.`,confirmLabel:`Delete`,danger:!0}),me&&(0,$.jsx)(bn,{providerId:n,parameters:ke,onClose:()=>{ge(!1),Ae({})}}),R!==null&&(0,$.jsx)(P,{open:!0,onClose:()=>xe(null),title:R===`browser`?`Sign in with`:`Device sign-in details`,size:`sm`,footer:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(y,{variant:`secondary`,size:`sm`,onClick:()=>xe(null),children:`Cancel`}),(0,$.jsx)(y,{variant:`primary`,size:`sm`,onClick:Xe,children:`Continue`})]}),children:(0,$.jsxs)(J,{gap:`12px`,children:[(0,$.jsx)(`p`,{className:`text-badge leading-snug text-text-tertiary`,children:R===`browser`?`Choose how ${U.label||U.displayName} should identify you, then continue to its sign-in page.`:`These decide which organization the device code is issued for.`}),(0,$.jsx)(Cn,{fields:R===`browser`?U?.oauthFlows?.browserLoginFields??[]:U?.oauthFlows?.deviceLoginFields??[],values:Te,idPrefix:`flow-${R}`,onChange:(e,t)=>De(n=>({...n,[e]:t}))})]})}),ve&&U?.oauthFlows?.import===!0&&(0,$.jsx)(wn,{providerId:n,providerName:U.label||U.displayName,fields:U.oauthFlows.importFields,onClose:()=>ye(!1)}),Ie&&(0,$.jsx)(vn,{providerId:n,authorizeUrl:Ie.authorizeUrl,state:Ie.state,popup:Ie.popup,onClose:e=>{H.current=null,Le(null),e&&v.invalidateQueries({queryKey:L.providers.accounts(n)})}})]})}export{qn as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{o as e,r as t,t as n}from"./jsx-runtime-CXUMngI_.js";import{n as r,t as i}from"./select-CGUuTQmj.js";import{i as a,n as o}from"./toast-DKAdP2mo.js";import{t as s}from"./eye-off-Bk5g2luF.js";import{t as c}from"./eye-C_hawfH4.js";import{n as l,r as u,t as d}from"./state-DHKdg-pm.js";import{t as f}from"./dialog-iocKA3jr.js";import{t as p}from"./plus-DIdX_g-x.js";import{t as m}from"./trash-Cppn5c3R.js";import{c as h}from"./query-keys-ROf-g1Wi.js";import{t as g}from"./dialog-actions-B1axpEg7.js";import{C as _,J as v,S as y,Z as b,a as x,et as S,g as C,h as w,i as T,m as E,s as D}from"./entry-DcX5sMzh.js";import{n as O,r as k,t as A}from"./card-BTdbRFFg.js";import{t as j}from"./badge-BwmwEOgA.js";import{n as M}from"./input-Bn4_kNav.js";import{t as N}from"./ProviderIcon-paOCq8I0.js";import{t as P}from"./switch-DIDeAiz9.js";import{t as F}from"./stack-C1kTcOmP.js";import{n as I}from"./inline-DCejSLlA.js";import{t as L}from"./list-row-BLA0sldD.js";import{r as R}from"./AccountCooldown-ChpdzxRH.js";var z=e(t(),1),B=n();function ee(e){let t={};for(let[n,r]of e)n.trim()&&(t[n.trim()]=r);return t}function te({pairs:e,onChange:t}){let n=(n,r)=>t(e.map((e,t)=>t===n?r:e)),r=n=>t(e.filter((e,t)=>t!==n));return(0,B.jsxs)(`div`,{className:`form-group`,children:[(0,B.jsxs)(`label`,{className:`form-label block`,children:[(0,B.jsx)(`span`,{className:`block`,children:`Custom Headers`}),(0,B.jsx)(`span`,{className:`form-hint block mt-1`,children:`Optional — sent with every request, override built-in headers on a name collision`})]}),(0,B.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[e.map(([e,t],i)=>(0,B.jsxs)(`div`,{className:`flex min-w-0 gap-3`,children:[(0,B.jsx)(M,{placeholder:`Header-Name`,value:e,onChange:e=>n(i,[e.target.value,t]),className:`font-mono tabular-nums min-w-0 flex-1 text-caption`}),(0,B.jsx)(M,{placeholder:`value`,value:t,onChange:t=>n(i,[e,t.target.value]),className:`font-mono tabular-nums min-w-0 flex-1 text-caption`}),(0,B.jsx)(o,{type:`button`,variant:`ghost`,size:`icon`,"aria-label":`Remove ${e||`header`}`,onClick:()=>r(i),children:(0,B.jsx)(m,{size:13})})]},i)),(0,B.jsxs)(o,{type:`button`,variant:`secondary`,size:`sm`,onClick:()=>t([...e,[``,``]]),children:[(0,B.jsx)(p,{size:13}),` Add header`]})]})]})}function V({children:e}){return(0,B.jsx)(`div`,{className:`provider-grid grid gap-6 w-full min-w-0`,children:e})}var H=a(`relative flex flex-col min-w-0 border border-inner-border rounded-card`,`transition-[transform,border-color,box-shadow]`),U=a(`block flex-1 p-6 no-underline text-inherit`),W=a(`text-body font-semibold overflow-hidden text-ellipsis whitespace-nowrap`);function G(e){let t=e.serviceKinds;return Array.isArray(t)&&t.length>0?t:[`llm`]}var K=/\/(?:v\d+\/)?(?:messages|chat\/completions|responses|completions|embeddings|images\/generations)$/;function ne(e){let t=e.trim().replace(/\/+$/,``);if(t===``)return null;let n,r;try{n=new URL(t),r=n.pathname.replace(/\/+$/,``)}catch{return null}return K.test(r)?n.origin:null}function q({variant:e,open:t,onClose:n}){let r=T(),s=x(),c=y(),l=_(),[u,d]=(0,z.useState)(``),[p,m]=(0,z.useState)(``),[g,v]=(0,z.useState)(``),[b,S]=(0,z.useState)(``),[C,w]=(0,z.useState)(!1),[E,D]=(0,z.useState)(!0),[O,k]=(0,z.useState)([]),[A,j]=(0,z.useState)(null),[N,F]=(0,z.useState)(!1),[R,V]=(0,z.useState)(null),[H,U]=(0,z.useState)(!1),W=e===`anthropic-compatible`,G=W?`messages`:`chat`,[K,q]=(0,z.useState)(G),J=(0,z.useMemo)(()=>ne(g),[g]);(0,z.useEffect)(()=>{t&&(d(``),S(``),q(G),v(``),w(!1),D(!0),k([]),j(null),V(null))},[t]);let Y=async e=>{try{let t=await navigator.clipboard.readText();t.trim()&&e(t.trim())}catch{j(`Clipboard access denied — paste manually instead.`)}},X=async()=>{if(!g.trim()){V({ok:!1,message:`Base URL is required to test the connection.`});return}U(!0),V(null),j(null);try{let e=ee(O),t=await l.mutateAsync({baseUrl:g.trim(),apiKey:b.trim(),wireFamily:K,cliIdentity:E,...Object.keys(e).length>0?{extraHeaders:e}:{}});if(t.ok){let e=typeof t.modelCount==`number`?` — upstream advertised ${t.modelCount} model(s)`:``;V({ok:!0,message:`Connected successfully (${t.latencyMs}ms)${e}.`,...t.warning===void 0?{}:{warning:t.warning}})}else V({ok:!1,message:t.error??`Connection failed.`,...t.warning===void 0?{}:{warning:t.warning}})}catch(e){V({ok:!1,message:h(e,`Connection test failed`)})}finally{U(!1)}};return(0,B.jsx)(f,{open:t,onClose:n,title:W?`Add Custom Anthropic Provider`:`Add Custom OpenAI Provider`,footer:(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(o,{variant:`secondary`,type:`button`,onClick:n,children:`Cancel`}),(0,B.jsx)(o,{variant:`primary`,type:`submit`,form:`add-compatible-provider`,disabled:N,children:N?`Creating...`:`Add Provider`})]}),children:(0,B.jsxs)(`form`,{id:`add-compatible-provider`,onSubmit:async e=>{if(e.preventDefault(),!u.trim()){j(`Display Name is required`);return}if(!p.trim()){j(`Provider ID (slug) is required`);return}if(!g.trim()){j(`Base URL is required`);return}let t=ee(O),i=p.trim().toLowerCase();F(!0),j(null);try{let e={providerId:i,label:u.trim(),baseUrl:g.trim(),wireFamily:K,compatibilityProfile:{cli_identity:E,...Object.keys(t).length>0?{extra_headers:t}:{}}};await r.mutateAsync(e),b.trim()&&await s.mutateAsync({providerId:i,request:{credentialKind:`api_key`,secret:b.trim()}}),C&&await c.mutateAsync(i),n()}catch(e){j(h(e,`Failed to create provider`))}finally{F(!1)}},className:`flex flex-col gap-6`,children:[A?(0,B.jsx)(`div`,{className:`text-red text-caption`,children:A}):null,(0,B.jsx)(M,{label:`Display Name`,hint:`Required. A friendly label for this node.`,id:`compat-label`,value:u,onChange:e=>d(e.target.value),placeholder:W?`Anthropic Compatible (Prod)`:`OpenAI Compatible (Prod)`,required:!0}),(0,B.jsx)(M,{label:`Provider ID / Slug`,hint:`Required. Used as the provider prefix for model IDs.`,id:`compat-slug`,value:p,onChange:e=>m(e.target.value),placeholder:W?`ac-prod`:`oc-prod`,required:!0}),(0,B.jsxs)(`div`,{className:`form-group`,children:[(0,B.jsxs)(`label`,{className:`form-label`,htmlFor:`compat-url`,children:[(0,B.jsx)(`span`,{children:`Base URL`}),(0,B.jsxs)(`span`,{className:`form-hint`,children:[`The root only. Do not paste the full endpoint — leave off`,W?" `/v1/messages`.":" `/chat/completions`."]})]}),(0,B.jsxs)(I,{gap:`8px`,children:[(0,B.jsx)(`div`,{className:`flex-1 min-w-0`,children:(0,B.jsx)(M,{id:`compat-url`,value:g,onChange:e=>v(e.target.value),placeholder:W?`https://api.anthropic.com/v1`:`https://api.openai.com/v1`,required:!0})}),(0,B.jsx)(o,{type:`button`,variant:`secondary`,onClick:()=>Y(v),children:`Paste`})]}),J===null?null:(0,B.jsxs)(`p`,{className:`mt-1.5 text-caption text-orange`,children:[`That looks like a full endpoint. Use`,` `,(0,B.jsx)(`code`,{className:`font-mono`,children:J}),` instead — Cartethyia appends the endpoint path itself.`]})]}),W?null:(0,B.jsx)(i,{id:`compat-wire`,label:`API format`,value:K,onValueChange:e=>q(e),options:[{value:`chat`,label:`Chat completions`},{value:`responses`,label:`Responses`}]}),(0,B.jsxs)(`div`,{className:`form-group`,children:[(0,B.jsxs)(`label`,{className:`form-label`,htmlFor:`compat-credential`,children:[(0,B.jsx)(`span`,{children:`API Key`}),(0,B.jsx)(`span`,{className:`form-hint`,children:`Optional — saved with this provider and used to authenticate every request.`})]}),(0,B.jsxs)(I,{gap:`8px`,children:[(0,B.jsx)(`div`,{className:`flex-1 min-w-0`,children:(0,B.jsx)(M,{id:`compat-credential`,type:`password`,placeholder:`sk-...`,value:b,onChange:e=>S(e.target.value)})}),(0,B.jsx)(o,{type:`button`,variant:`secondary`,disabled:H,onClick:()=>void X(),children:H?`Testing...`:`Test connection`}),(0,B.jsx)(o,{type:`button`,variant:`secondary`,onClick:()=>Y(S),children:`Paste`})]}),R?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`div`,{className:a(`mt-3 text-caption leading-[1.4] break-words`,R.ok?`text-green`:`text-red`),children:[R.ok?`✓ `:`✗ `,R.message]}),R.warning?(0,B.jsxs)(`div`,{className:`mt-2 text-caption leading-snug break-words text-orange`,children:[`⚠ `,R.warning]}):null]}):null]}),(0,B.jsx)(L,{actions:(0,B.jsx)(P,{checked:C,onChange:w,id:`compat-autofetch`}),children:(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`div`,{className:`text-body font-semibold`,children:`Auto-fetch models`}),(0,B.jsx)(`div`,{className:`mt-1 text-badge text-text-tertiary`,children:`Discover this provider's model list automatically after creation`})]})}),(0,B.jsx)(L,{actions:(0,B.jsx)(P,{checked:E,onChange:D,id:`compat-cli-identity`}),children:(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`div`,{className:`text-body font-semibold`,children:W?`Send request as Claude CLI`:`Send request as Codex CLI`}),(0,B.jsx)(`div`,{className:`mt-1 text-badge text-text-tertiary`,children:W?`Emits official Claude CLI User-Agent and Stainless headers to upstream`:`Emits official codex_cli_rs User-Agent and originator headers to upstream`})]})}),(0,B.jsx)(te,{pairs:O,onChange:k})]})})}function J({customProvider:e}){let t=D(),[n,r]=(0,z.useState)(!1),i=w(e.providerId),s=i.data?.length,c=E(e.providerId),l=c.data,u=ie(l??[]);return(0,B.jsxs)(A,{className:H,children:[(0,B.jsx)(oe,{clientVersion:e.clientVersion}),(0,B.jsx)(v,{to:`/providers/${encodeURIComponent(e.providerId)}`,className:a(U,`pr-20 min-h-38`),children:(0,B.jsxs)(I,{gap:`10px`,children:[(0,B.jsx)(N,{icon:e.wireFamilyDefault===`messages`?`anthropic`:`openai`,name:e.label||e.providerId,size:32,imageSize:24}),(0,B.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,B.jsx)(`div`,{className:W,children:e.label||e.providerId}),(0,B.jsxs)(`div`,{className:`mt-1.5 flex flex-wrap gap-2`,children:[l===void 0?(0,B.jsx)($,{kind:`accounts`,isPending:c.isPending,isError:c.isError,hasData:!1}):l.length===0?e.requiresAccount===!1?(0,B.jsx)(j,{tone:`ok`,children:`Free Endpoint`}):(0,B.jsx)(j,{children:`No connections`}):(0,B.jsx)(ae,{counts:u,total:l.length}),c.isError&&l!==void 0?(0,B.jsx)(j,{tone:`warn`,children:`Connections unavailable`}):null]})]}),(0,B.jsxs)(`div`,{className:`flex flex-col items-end gap-1.5 shrink-0`,children:[(0,B.jsxs)(`span`,{className:`font-mono tabular-nums text-micro font-semibold bg-kbd-bg px-2.5 py-0.5 rounded-chip text-text-secondary`,children:[e.providerId,`/`]}),s!==void 0&&s>0?(0,B.jsxs)(j,{tone:`info`,children:[s,` models`]}):null,i.isError?(0,B.jsx)(j,{tone:`warn`,children:`Models unavailable`}):s===void 0?(0,B.jsx)($,{kind:`models`,isPending:i.isPending,isError:!1,hasData:!1}):s===0?(0,B.jsx)($,{kind:`models`,isPending:!1,isError:!1,hasData:!0,isEmpty:!0}):null]})]})}),(0,B.jsx)(o,{variant:`ghost`,size:`sm`,icon:(0,B.jsx)(m,{size:12}),onClick:()=>r(!0),className:`absolute top-2 right-2 p-2 text-text-tertiary`,title:`Delete ${e.label||e.providerId}`}),(0,B.jsx)(f,{open:n,onClose:()=>r(!1),title:`Delete Custom Provider`,children:(0,B.jsxs)(F,{gap:`12px`,children:[(0,B.jsxs)(`p`,{className:`text-body text-text-secondary`,children:[`Are you sure you want to delete custom provider`,` `,(0,B.jsx)(`strong`,{children:e.label||e.providerId}),`? Its models, accounts, and routing preferences are deleted together, and requests to this provider will no longer route.`]}),t.isError?(0,B.jsx)(`p`,{className:`text-caption text-red`,children:h(t.error,`Delete failed`)}):null,(0,B.jsxs)(g,{children:[(0,B.jsx)(o,{variant:`secondary`,onClick:()=>r(!1),children:`Cancel`}),(0,B.jsx)(o,{variant:`danger`,onClick:()=>{t.mutate(e.providerId,{onSuccess:()=>r(!1),onError:()=>void 0})},disabled:t.isPending,children:t.isPending?`Deleting...`:`Delete Provider`})]})]})})]})}function Y({customProviders:e}){let[t,n]=(0,z.useState)(!1),[i,a]=(0,z.useState)(!1),[l,u]=(0,z.useState)(()=>{try{return window.localStorage.getItem(`cartethyia.customProvidersHidden`)===`1`}catch{return!1}});function d(){u(e=>{let t=!e;try{window.localStorage.setItem(`cartethyia.customProvidersHidden`,t?`1`:`0`)}catch{}return t})}return(0,B.jsxs)(`section`,{className:`flex flex-col gap-5`,children:[(0,B.jsxs)(`div`,{className:`flex items-center justify-between flex-wrap gap-4`,children:[(0,B.jsxs)(`button`,{type:`button`,onClick:d,"aria-expanded":!l,title:l?`Show custom providers`:`Hide custom providers`,className:`inline-flex items-center gap-3 bg-transparent border-none p-0 cursor-pointer text-inherit`,children:[(0,B.jsxs)(`h2`,{className:`text-body-lg font-bold tracking-[-0.01em]`,children:[`Custom Providers`,e.length>0?` (${e.length})`:``]}),(0,B.jsx)(r,{size:14,className:`text-text-tertiary transition-transform`,style:{transform:l?`rotate(-90deg)`:void 0}})]}),(0,B.jsxs)(I,{gap:`8px`,children:[(0,B.jsx)(o,{size:`sm`,variant:`ghost`,icon:l?(0,B.jsx)(c,{size:13}):(0,B.jsx)(s,{size:13}),onClick:d,title:l?`Show custom providers`:`Hide custom providers`,children:l?`Show`:`Hide`}),(0,B.jsx)(o,{size:`sm`,variant:`secondary`,icon:(0,B.jsx)(p,{size:13}),onClick:()=>n(!0),children:`Custom Anthropic`}),(0,B.jsx)(o,{size:`sm`,variant:`secondary`,icon:(0,B.jsx)(p,{size:13}),onClick:()=>a(!0),children:`Custom OpenAI`})]})]}),l?null:e.length===0?(0,B.jsx)(A,{children:(0,B.jsxs)(O,{className:`text-center px-7 py-10 border border-dashed border-inner-border rounded-card`,children:[(0,B.jsx)(`p`,{className:`text-body font-semibold text-text-primary`,children:`No custom providers yet`}),(0,B.jsx)(`p`,{className:`text-badge text-text-tertiary mt-1`,children:`Add an OpenAI- or Anthropic-compatible endpoint with the buttons above.`})]})}):(0,B.jsx)(V,{children:e.map(e=>(0,B.jsx)(J,{customProvider:e},e.providerId))}),(0,B.jsx)(q,{variant:`anthropic-compatible`,open:t,onClose:()=>n(!1)}),(0,B.jsx)(q,{variant:`openai-compatible`,open:i,onClose:()=>a(!1)})]})}var X=new Set([`inferhub`]),Z=new Set([`grok`,`opencode`,`cline`,`hermes`,`commandcode`,`kilo`]),re=new Set([`anthropic`,`openai`,`gemini`,`alibabacp`,`ollamacloud`,`opencode-zen`,`opencode-go`,`mistral`,`meta`,`deepseek`]);function Q(e){return e.oauthFlows?.browser===!0||e.oauthFlows?.device===!0}function ie(e){return{active:e.filter(e=>e.status===`active`).length,cooldown:e.filter(e=>e.status===`cooldown`).length,disabled:e.filter(e=>e.status===`disabled`).length,cooling:R(e)}}function ae({counts:e,total:t}){return e.active>0||e.cooldown>0||e.cooling>0||e.disabled>0?(0,B.jsxs)(B.Fragment,{children:[e.active>0?(0,B.jsxs)(j,{tone:`ok`,dot:!0,children:[e.active,` Healthy`]}):null,e.cooldown>0?(0,B.jsxs)(j,{tone:`warn`,dot:!0,children:[e.cooldown,` Cooldown`]}):null,e.cooling>0?(0,B.jsxs)(j,{tone:`warn`,dot:!0,children:[e.cooling,` Cooling`]}):null,e.disabled>0?(0,B.jsxs)(j,{tone:`warn`,dot:!0,children:[e.disabled,` Unhealthy`]}):null]}):(0,B.jsxs)(j,{tone:`warn`,dot:!0,children:[t,` Connected`]})}function $({kind:e,isPending:t,isError:n,hasData:r,isEmpty:i=!1}){let a=e===`models`?`Models`:`Connections`;return n?(0,B.jsxs)(j,{tone:`warn`,children:[a,` unavailable`]}):t&&!r?(0,B.jsxs)(j,{tone:`info`,children:[`Loading `,a.toLowerCase(),`…`]}):i?(0,B.jsx)(j,{children:e===`models`?`No models`:`No connections`}):null}function oe({clientVersion:e}){return e?(0,B.jsxs)(j,{className:`provider-version-badge absolute -top-4.5 left-5 right-auto z-chip max-w-[calc(100%-var(--spacing)*10)] truncate px-3 py-1 text-micro leading-[1.15] shadow-card max-small:left-4 max-small:max-w-[calc(100%-var(--spacing)*8)]`,tone:e.source===`latest`?`teal`:`default`,title:e.source===`latest`?`Latest discovered client version`:`Pinned fallback; background discovery has not succeeded yet`,children:[`v`,e.version,` · `,e.source]}):null}var se=(0,z.memo)(function({provider:e,serviceKind:t}){let n=X.has(e.providerId.toLowerCase()),r=e.label||e.displayName,i=w(e.providerId),o=i.data?.filter(e=>t===void 0||e.serviceKind===t||t===`llm`&&e.serviceKind===void 0).length,s=E(e.providerId),c=s.data,l=ie(c??[]);return(0,B.jsxs)(A,{className:H,children:[(0,B.jsx)(oe,{clientVersion:e.clientVersion}),n?(0,B.jsx)(`span`,{"aria-label":`Friend sponsor`,title:`Friend sponsor`,className:`absolute top-0 right-0 z-2 w-36 h-36 overflow-hidden pointer-events-none`,children:(0,B.jsx)(`span`,{className:a(`absolute top-9 -right-11 w-38 py-1 rotate-45 bg-accent-soft`,`text-accent text-micro font-extrabold tracking-tight leading-[1.05]`,`text-center uppercase shadow-ribbon`),children:`Friend`})}):null,(0,B.jsx)(v,{to:`/providers/${encodeURIComponent(e.providerId)}${t===void 0?``:`?service=${t}`}`,className:U,children:(0,B.jsxs)(I,{gap:`10px`,children:[(0,B.jsx)(N,{icon:e.providerId,name:r,size:32,imageSize:24}),(0,B.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,B.jsx)(`div`,{className:W,children:r}),(0,B.jsxs)(`div`,{className:`mt-1.5 flex flex-wrap gap-2`,children:[c===void 0?(0,B.jsx)($,{kind:`accounts`,isPending:s.isPending,isError:s.isError,hasData:!1}):c.length===0?e.requiresAccount===!1?(0,B.jsx)(j,{tone:`ok`,children:`Free Endpoint`}):(0,B.jsx)(j,{children:`No connections`}):(0,B.jsx)(ae,{counts:l,total:c.length}),s.isError&&c!==void 0?(0,B.jsx)(j,{tone:`warn`,children:`Connections unavailable`}):null]})]}),(0,B.jsxs)(`div`,{className:`flex flex-col items-end gap-1.5 shrink-0`,children:[(0,B.jsxs)(`span`,{className:`font-mono tabular-nums text-micro font-semibold bg-kbd-bg px-2.5 py-0.5 rounded-chip text-text-secondary`,children:[e.providerId,`/`]}),o!==void 0&&o>0?(0,B.jsxs)(j,{tone:`info`,children:[o,` models`]}):null,i.isError?(0,B.jsx)(j,{tone:`warn`,children:`Models unavailable`}):o===void 0?(0,B.jsx)($,{kind:`models`,isPending:i.isPending,isError:!1,hasData:!1}):o===0?(0,B.jsx)($,{kind:`models`,isPending:!1,isError:!1,hasData:!0,isEmpty:!0}):null]})]})})]})});function ce(e,t){let n=Number(!!t.configured)-Number(!!e.configured);return n===0?(e.label||e.displayName).localeCompare(t.label||t.displayName):n}var le=`cartethyia.providerSectionsCollapsed`;function ue(){try{let e=window.localStorage.getItem(le),t=e?JSON.parse(e):[];return new Set(Array.isArray(t)?t.filter(e=>typeof e==`string`):[])}catch{return new Set}}var de=[{title:`Founding Friend & Sponsors`,subtitle:`Super Cheap inference pool`,filter:e=>X.has(e.providerId.toLowerCase())},{title:`Free Limited Providers`,filter:e=>Z.has(e.providerId.toLowerCase())},{title:`OAuth & Agent Providers`,filter:e=>Q(e)&&!Z.has(e.providerId.toLowerCase())},{title:`Well Known API Key Providers`,subtitle:`The household names — sign up with a key and go`,filter:e=>e.isBuiltIn&&re.has(e.providerId.toLowerCase())&&!X.has(e.providerId.toLowerCase())&&!Z.has(e.providerId.toLowerCase())&&!Q(e)},{title:`Other API Key Providers`,subtitle:`Free tier friendly — no credit card`,filter:e=>e.isBuiltIn&&!re.has(e.providerId.toLowerCase())&&!X.has(e.providerId.toLowerCase())&&!Z.has(e.providerId.toLowerCase())&&!Q(e)}];function fe(){let[e,t]=(0,z.useState)(ue),n=C(),i=(0,z.useMemo)(()=>n.data??[],[n.data]),o=(0,z.useMemo)(()=>[...i.filter(e=>!e.isBuiltIn)].sort(ce),[i]),s=(0,z.useMemo)(()=>i.filter(e=>G(e).includes(`websearch`)),[i]),c=(0,z.useMemo)(()=>i.filter(e=>G(e).includes(`llm`)),[i]),[f,p]=b(),m=f.get(`tab`),g=m===`search`||m===`media`?m:`llm`,_=e=>{p(t=>{let n=new URLSearchParams(t);return e===`llm`?n.delete(`tab`):n.set(`tab`,e),n})},v=(0,z.useMemo)(()=>i.filter(e=>G(e).includes(`imageGeneration`)||G(e).includes(`videoGeneration`)),[i]),y=(0,z.useMemo)(()=>[...s].sort((e,t)=>(e.label||e.displayName).localeCompare(t.label||t.displayName)),[s]),x=(e,t)=>{let n=Number(!!t.configured)-Number(!!e.configured);return n===0?(e.label||e.displayName).localeCompare(t.label||t.displayName):n},w=(0,z.useMemo)(()=>{if(g===`media`)return[{title:`Media Generation`,subtitle:`Providers that can return an image or a video`,providers:v}].filter(e=>e.providers.length>0);if(g===`search`)return[{title:`Search Providers`,subtitle:`Providers that can answer a web search request`,providers:y}].filter(e=>e.providers.length>0);let e=c;return de.map(t=>({...t,providers:e.filter(t.filter).sort(x)})).filter(e=>e.providers.length>0)},[c,y,v,g]),T=n.isPending&&!n.data?(0,B.jsx)(u,{label:`Loading providers...`}):n.isError?(0,B.jsx)(l,{message:h(n.error,`Failed to load providers`),onRetry:()=>n.refetch()}):null;return T?(0,B.jsxs)(A,{children:[(0,B.jsx)(k,{title:`Providers`,icon:(0,B.jsx)(S,{size:16})}),(0,B.jsx)(O,{className:`flex flex-1`,children:T})]}):(0,B.jsx)(F,{gap:`24px`,children:(0,B.jsxs)(A,{children:[(0,B.jsx)(k,{title:`Providers`,subtitle:`Connected pinned first · A–Z`,icon:(0,B.jsx)(S,{size:16})}),(0,B.jsxs)(O,{className:`flex flex-col gap-8`,children:[(0,B.jsxs)(`div`,{className:`flex items-center gap-4 flex-wrap`,children:[(0,B.jsx)(`div`,{className:`flex gap-2`,children:[`llm`,`search`,`media`].map(e=>(0,B.jsxs)(`button`,{onClick:()=>_(e),className:a(`px-6 py-3 rounded-inset text-caption font-semibold border cursor-pointer`,g===e?`border-accent bg-accent-soft text-accent`:`border-inner-border bg-surface-1 text-text-secondary`),children:[e===`llm`?`LLM`:e===`search`?`Search`:`Media`,e===`search`?` (${s.length})`:e===`media`?` (${v.length})`:` (${c.length})`]},e))}),(0,B.jsx)(`span`,{className:`ml-auto text-micro text-text-tertiary`,children:g===`search`?`Fallback runs only when the model invokes Websearch`:g===`media`?`Image and video generation`:`Connected pinned first · A–Z`})]}),g===`llm`?(0,B.jsx)(Y,{customProviders:o}):null,w.length===0?(0,B.jsx)(A,{children:(0,B.jsx)(O,{children:(0,B.jsx)(d,{title:`No providers found`,message:`No providers available.`})})}):w.map(n=>{let i=e.has(n.title);return(0,B.jsxs)(`section`,{className:`flex flex-col gap-6`,children:[(0,B.jsxs)(`button`,{type:`button`,className:`flex items-start gap-4 border-0 bg-transparent p-0 text-left text-inherit`,"aria-expanded":!i,onClick:()=>t(e=>{let t=new Set(e);t.has(n.title)?t.delete(n.title):t.add(n.title);try{window.localStorage.setItem(le,JSON.stringify([...t]))}catch{}return t}),children:[(0,B.jsx)(r,{size:15,className:a(`mt-1 shrink-0 transition-transform`,i&&`-rotate-90`)}),(0,B.jsxs)(F,{gap:`1px`,children:[(0,B.jsxs)(`h2`,{className:`text-body font-bold tracking-[-0.01em]`,children:[n.title,` (`,n.providers.length,`)`,i?` (Hidden)`:``]}),!i&&n.subtitle?(0,B.jsx)(`p`,{className:`mt-1 text-badge text-text-tertiary`,children:n.subtitle}):null]})]}),i?null:(0,B.jsx)(V,{children:n.providers.map(e=>(0,B.jsx)(se,{provider:e,serviceKind:g===`search`?`websearch`:g===`media`?G(e).includes(`imageGeneration`)?`imageGeneration`:`videoGeneration`:`llm`},e.providerId))})]},n.title)})]})]})})}export{fe as default};
|
|
1
|
+
import{o as e,r as t,t as n}from"./jsx-runtime-CXUMngI_.js";import{n as r,t as i}from"./select-CGUuTQmj.js";import{i as a,n as o}from"./toast-DKAdP2mo.js";import{t as s}from"./eye-off-Bk5g2luF.js";import{t as c}from"./eye-C_hawfH4.js";import{n as l,r as u,t as d}from"./state-DHKdg-pm.js";import{t as f}from"./dialog-iocKA3jr.js";import{t as p}from"./plus-DIdX_g-x.js";import{t as m}from"./trash-Cppn5c3R.js";import{c as h}from"./query-keys-ROf-g1Wi.js";import{t as g}from"./dialog-actions-B1axpEg7.js";import{C as _,J as v,S as y,Z as b,a as x,et as S,g as C,h as w,i as T,m as E,s as D}from"./entry-C3M9aRLH.js";import{n as O,r as k,t as A}from"./card-BTdbRFFg.js";import{t as j}from"./badge-BwmwEOgA.js";import{n as M}from"./input-Bn4_kNav.js";import{t as N}from"./ProviderIcon-paOCq8I0.js";import{t as P}from"./switch-DIDeAiz9.js";import{t as F}from"./stack-C1kTcOmP.js";import{n as I}from"./inline-DCejSLlA.js";import{t as L}from"./list-row-BLA0sldD.js";import{r as R}from"./AccountCooldown-ChpdzxRH.js";var z=e(t(),1),B=n();function ee(e){let t={};for(let[n,r]of e)n.trim()&&(t[n.trim()]=r);return t}function te({pairs:e,onChange:t}){let n=(n,r)=>t(e.map((e,t)=>t===n?r:e)),r=n=>t(e.filter((e,t)=>t!==n));return(0,B.jsxs)(`div`,{className:`form-group`,children:[(0,B.jsxs)(`label`,{className:`form-label block`,children:[(0,B.jsx)(`span`,{className:`block`,children:`Custom Headers`}),(0,B.jsx)(`span`,{className:`form-hint block mt-1`,children:`Optional — sent with every request, override built-in headers on a name collision`})]}),(0,B.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[e.map(([e,t],i)=>(0,B.jsxs)(`div`,{className:`flex min-w-0 gap-3`,children:[(0,B.jsx)(M,{placeholder:`Header-Name`,value:e,onChange:e=>n(i,[e.target.value,t]),className:`font-mono tabular-nums min-w-0 flex-1 text-caption`}),(0,B.jsx)(M,{placeholder:`value`,value:t,onChange:t=>n(i,[e,t.target.value]),className:`font-mono tabular-nums min-w-0 flex-1 text-caption`}),(0,B.jsx)(o,{type:`button`,variant:`ghost`,size:`icon`,"aria-label":`Remove ${e||`header`}`,onClick:()=>r(i),children:(0,B.jsx)(m,{size:13})})]},i)),(0,B.jsxs)(o,{type:`button`,variant:`secondary`,size:`sm`,onClick:()=>t([...e,[``,``]]),children:[(0,B.jsx)(p,{size:13}),` Add header`]})]})]})}function V({children:e}){return(0,B.jsx)(`div`,{className:`provider-grid grid gap-6 w-full min-w-0`,children:e})}var H=a(`relative flex flex-col min-w-0 border border-inner-border rounded-card`,`transition-[transform,border-color,box-shadow]`),U=a(`block flex-1 p-6 no-underline text-inherit`),W=a(`text-body font-semibold overflow-hidden text-ellipsis whitespace-nowrap`);function G(e){let t=e.serviceKinds;return Array.isArray(t)&&t.length>0?t:[`llm`]}var K=/\/(?:v\d+\/)?(?:messages|chat\/completions|responses|completions|embeddings|images\/generations)$/;function ne(e){let t=e.trim().replace(/\/+$/,``);if(t===``)return null;let n,r;try{n=new URL(t),r=n.pathname.replace(/\/+$/,``)}catch{return null}return K.test(r)?n.origin:null}function q({variant:e,open:t,onClose:n}){let r=T(),s=x(),c=y(),l=_(),[u,d]=(0,z.useState)(``),[p,m]=(0,z.useState)(``),[g,v]=(0,z.useState)(``),[b,S]=(0,z.useState)(``),[C,w]=(0,z.useState)(!1),[E,D]=(0,z.useState)(!0),[O,k]=(0,z.useState)([]),[A,j]=(0,z.useState)(null),[N,F]=(0,z.useState)(!1),[R,V]=(0,z.useState)(null),[H,U]=(0,z.useState)(!1),W=e===`anthropic-compatible`,G=W?`messages`:`chat`,[K,q]=(0,z.useState)(G),J=(0,z.useMemo)(()=>ne(g),[g]);(0,z.useEffect)(()=>{t&&(d(``),S(``),q(G),v(``),w(!1),D(!0),k([]),j(null),V(null))},[t]);let Y=async e=>{try{let t=await navigator.clipboard.readText();t.trim()&&e(t.trim())}catch{j(`Clipboard access denied — paste manually instead.`)}},X=async()=>{if(!g.trim()){V({ok:!1,message:`Base URL is required to test the connection.`});return}U(!0),V(null),j(null);try{let e=ee(O),t=await l.mutateAsync({baseUrl:g.trim(),apiKey:b.trim(),wireFamily:K,cliIdentity:E,...Object.keys(e).length>0?{extraHeaders:e}:{}});if(t.ok){let e=typeof t.modelCount==`number`?` — upstream advertised ${t.modelCount} model(s)`:``;V({ok:!0,message:`Connected successfully (${t.latencyMs}ms)${e}.`,...t.warning===void 0?{}:{warning:t.warning}})}else V({ok:!1,message:t.error??`Connection failed.`,...t.warning===void 0?{}:{warning:t.warning}})}catch(e){V({ok:!1,message:h(e,`Connection test failed`)})}finally{U(!1)}};return(0,B.jsx)(f,{open:t,onClose:n,title:W?`Add Custom Anthropic Provider`:`Add Custom OpenAI Provider`,footer:(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(o,{variant:`secondary`,type:`button`,onClick:n,children:`Cancel`}),(0,B.jsx)(o,{variant:`primary`,type:`submit`,form:`add-compatible-provider`,disabled:N,children:N?`Creating...`:`Add Provider`})]}),children:(0,B.jsxs)(`form`,{id:`add-compatible-provider`,onSubmit:async e=>{if(e.preventDefault(),!u.trim()){j(`Display Name is required`);return}if(!p.trim()){j(`Provider ID (slug) is required`);return}if(!g.trim()){j(`Base URL is required`);return}let t=ee(O),i=p.trim().toLowerCase();F(!0),j(null);try{let e={providerId:i,label:u.trim(),baseUrl:g.trim(),wireFamily:K,compatibilityProfile:{cli_identity:E,...Object.keys(t).length>0?{extra_headers:t}:{}}};await r.mutateAsync(e),b.trim()&&await s.mutateAsync({providerId:i,request:{credentialKind:`api_key`,secret:b.trim()}}),C&&await c.mutateAsync(i),n()}catch(e){j(h(e,`Failed to create provider`))}finally{F(!1)}},className:`flex flex-col gap-6`,children:[A?(0,B.jsx)(`div`,{className:`text-red text-caption`,children:A}):null,(0,B.jsx)(M,{label:`Display Name`,hint:`Required. A friendly label for this node.`,id:`compat-label`,value:u,onChange:e=>d(e.target.value),placeholder:W?`Anthropic Compatible (Prod)`:`OpenAI Compatible (Prod)`,required:!0}),(0,B.jsx)(M,{label:`Provider ID / Slug`,hint:`Required. Used as the provider prefix for model IDs.`,id:`compat-slug`,value:p,onChange:e=>m(e.target.value),placeholder:W?`ac-prod`:`oc-prod`,required:!0}),(0,B.jsxs)(`div`,{className:`form-group`,children:[(0,B.jsxs)(`label`,{className:`form-label`,htmlFor:`compat-url`,children:[(0,B.jsx)(`span`,{children:`Base URL`}),(0,B.jsxs)(`span`,{className:`form-hint`,children:[`The root only. Do not paste the full endpoint — leave off`,W?" `/v1/messages`.":" `/chat/completions`."]})]}),(0,B.jsxs)(I,{gap:`8px`,children:[(0,B.jsx)(`div`,{className:`flex-1 min-w-0`,children:(0,B.jsx)(M,{id:`compat-url`,value:g,onChange:e=>v(e.target.value),placeholder:W?`https://api.anthropic.com/v1`:`https://api.openai.com/v1`,required:!0})}),(0,B.jsx)(o,{type:`button`,variant:`secondary`,onClick:()=>Y(v),children:`Paste`})]}),J===null?null:(0,B.jsxs)(`p`,{className:`mt-1.5 text-caption text-orange`,children:[`That looks like a full endpoint. Use`,` `,(0,B.jsx)(`code`,{className:`font-mono`,children:J}),` instead — Cartethyia appends the endpoint path itself.`]})]}),W?null:(0,B.jsx)(i,{id:`compat-wire`,label:`API format`,value:K,onValueChange:e=>q(e),options:[{value:`chat`,label:`Chat completions`},{value:`responses`,label:`Responses`}]}),(0,B.jsxs)(`div`,{className:`form-group`,children:[(0,B.jsxs)(`label`,{className:`form-label`,htmlFor:`compat-credential`,children:[(0,B.jsx)(`span`,{children:`API Key`}),(0,B.jsx)(`span`,{className:`form-hint`,children:`Optional — saved with this provider and used to authenticate every request.`})]}),(0,B.jsxs)(I,{gap:`8px`,children:[(0,B.jsx)(`div`,{className:`flex-1 min-w-0`,children:(0,B.jsx)(M,{id:`compat-credential`,type:`password`,placeholder:`sk-...`,value:b,onChange:e=>S(e.target.value)})}),(0,B.jsx)(o,{type:`button`,variant:`secondary`,disabled:H,onClick:()=>void X(),children:H?`Testing...`:`Test connection`}),(0,B.jsx)(o,{type:`button`,variant:`secondary`,onClick:()=>Y(S),children:`Paste`})]}),R?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`div`,{className:a(`mt-3 text-caption leading-[1.4] break-words`,R.ok?`text-green`:`text-red`),children:[R.ok?`✓ `:`✗ `,R.message]}),R.warning?(0,B.jsxs)(`div`,{className:`mt-2 text-caption leading-snug break-words text-orange`,children:[`⚠ `,R.warning]}):null]}):null]}),(0,B.jsx)(L,{actions:(0,B.jsx)(P,{checked:C,onChange:w,id:`compat-autofetch`}),children:(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`div`,{className:`text-body font-semibold`,children:`Auto-fetch models`}),(0,B.jsx)(`div`,{className:`mt-1 text-badge text-text-tertiary`,children:`Discover this provider's model list automatically after creation`})]})}),(0,B.jsx)(L,{actions:(0,B.jsx)(P,{checked:E,onChange:D,id:`compat-cli-identity`}),children:(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`div`,{className:`text-body font-semibold`,children:W?`Send request as Claude CLI`:`Send request as Codex CLI`}),(0,B.jsx)(`div`,{className:`mt-1 text-badge text-text-tertiary`,children:W?`Emits official Claude CLI User-Agent and Stainless headers to upstream`:`Emits official codex_cli_rs User-Agent and originator headers to upstream`})]})}),(0,B.jsx)(te,{pairs:O,onChange:k})]})})}function J({customProvider:e}){let t=D(),[n,r]=(0,z.useState)(!1),i=w(e.providerId),s=i.data?.length,c=E(e.providerId),l=c.data,u=ie(l??[]);return(0,B.jsxs)(A,{className:H,children:[(0,B.jsx)(oe,{clientVersion:e.clientVersion}),(0,B.jsx)(v,{to:`/providers/${encodeURIComponent(e.providerId)}`,className:a(U,`pr-20 min-h-38`),children:(0,B.jsxs)(I,{gap:`10px`,children:[(0,B.jsx)(N,{icon:e.wireFamilyDefault===`messages`?`anthropic`:`openai`,name:e.label||e.providerId,size:32,imageSize:24}),(0,B.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,B.jsx)(`div`,{className:W,children:e.label||e.providerId}),(0,B.jsxs)(`div`,{className:`mt-1.5 flex flex-wrap gap-2`,children:[l===void 0?(0,B.jsx)($,{kind:`accounts`,isPending:c.isPending,isError:c.isError,hasData:!1}):l.length===0?e.requiresAccount===!1?(0,B.jsx)(j,{tone:`ok`,children:`Free Endpoint`}):(0,B.jsx)(j,{children:`No connections`}):(0,B.jsx)(ae,{counts:u,total:l.length}),c.isError&&l!==void 0?(0,B.jsx)(j,{tone:`warn`,children:`Connections unavailable`}):null]})]}),(0,B.jsxs)(`div`,{className:`flex flex-col items-end gap-1.5 shrink-0`,children:[(0,B.jsxs)(`span`,{className:`font-mono tabular-nums text-micro font-semibold bg-kbd-bg px-2.5 py-0.5 rounded-chip text-text-secondary`,children:[e.providerId,`/`]}),s!==void 0&&s>0?(0,B.jsxs)(j,{tone:`info`,children:[s,` models`]}):null,i.isError?(0,B.jsx)(j,{tone:`warn`,children:`Models unavailable`}):s===void 0?(0,B.jsx)($,{kind:`models`,isPending:i.isPending,isError:!1,hasData:!1}):s===0?(0,B.jsx)($,{kind:`models`,isPending:!1,isError:!1,hasData:!0,isEmpty:!0}):null]})]})}),(0,B.jsx)(o,{variant:`ghost`,size:`sm`,icon:(0,B.jsx)(m,{size:12}),onClick:()=>r(!0),className:`absolute top-2 right-2 p-2 text-text-tertiary`,title:`Delete ${e.label||e.providerId}`}),(0,B.jsx)(f,{open:n,onClose:()=>r(!1),title:`Delete Custom Provider`,children:(0,B.jsxs)(F,{gap:`12px`,children:[(0,B.jsxs)(`p`,{className:`text-body text-text-secondary`,children:[`Are you sure you want to delete custom provider`,` `,(0,B.jsx)(`strong`,{children:e.label||e.providerId}),`? Its models, accounts, and routing preferences are deleted together, and requests to this provider will no longer route.`]}),t.isError?(0,B.jsx)(`p`,{className:`text-caption text-red`,children:h(t.error,`Delete failed`)}):null,(0,B.jsxs)(g,{children:[(0,B.jsx)(o,{variant:`secondary`,onClick:()=>r(!1),children:`Cancel`}),(0,B.jsx)(o,{variant:`danger`,onClick:()=>{t.mutate(e.providerId,{onSuccess:()=>r(!1),onError:()=>void 0})},disabled:t.isPending,children:t.isPending?`Deleting...`:`Delete Provider`})]})]})})]})}function Y({customProviders:e}){let[t,n]=(0,z.useState)(!1),[i,a]=(0,z.useState)(!1),[l,u]=(0,z.useState)(()=>{try{return window.localStorage.getItem(`cartethyia.customProvidersHidden`)===`1`}catch{return!1}});function d(){u(e=>{let t=!e;try{window.localStorage.setItem(`cartethyia.customProvidersHidden`,t?`1`:`0`)}catch{}return t})}return(0,B.jsxs)(`section`,{className:`flex flex-col gap-5`,children:[(0,B.jsxs)(`div`,{className:`flex items-center justify-between flex-wrap gap-4`,children:[(0,B.jsxs)(`button`,{type:`button`,onClick:d,"aria-expanded":!l,title:l?`Show custom providers`:`Hide custom providers`,className:`inline-flex items-center gap-3 bg-transparent border-none p-0 cursor-pointer text-inherit`,children:[(0,B.jsxs)(`h2`,{className:`text-body-lg font-bold tracking-[-0.01em]`,children:[`Custom Providers`,e.length>0?` (${e.length})`:``]}),(0,B.jsx)(r,{size:14,className:`text-text-tertiary transition-transform`,style:{transform:l?`rotate(-90deg)`:void 0}})]}),(0,B.jsxs)(I,{gap:`8px`,children:[(0,B.jsx)(o,{size:`sm`,variant:`ghost`,icon:l?(0,B.jsx)(c,{size:13}):(0,B.jsx)(s,{size:13}),onClick:d,title:l?`Show custom providers`:`Hide custom providers`,children:l?`Show`:`Hide`}),(0,B.jsx)(o,{size:`sm`,variant:`secondary`,icon:(0,B.jsx)(p,{size:13}),onClick:()=>n(!0),children:`Custom Anthropic`}),(0,B.jsx)(o,{size:`sm`,variant:`secondary`,icon:(0,B.jsx)(p,{size:13}),onClick:()=>a(!0),children:`Custom OpenAI`})]})]}),l?null:e.length===0?(0,B.jsx)(A,{children:(0,B.jsxs)(O,{className:`text-center px-7 py-10 border border-dashed border-inner-border rounded-card`,children:[(0,B.jsx)(`p`,{className:`text-body font-semibold text-text-primary`,children:`No custom providers yet`}),(0,B.jsx)(`p`,{className:`text-badge text-text-tertiary mt-1`,children:`Add an OpenAI- or Anthropic-compatible endpoint with the buttons above.`})]})}):(0,B.jsx)(V,{children:e.map(e=>(0,B.jsx)(J,{customProvider:e},e.providerId))}),(0,B.jsx)(q,{variant:`anthropic-compatible`,open:t,onClose:()=>n(!1)}),(0,B.jsx)(q,{variant:`openai-compatible`,open:i,onClose:()=>a(!1)})]})}var X=new Set([`inferhub`]),Z=new Set([`grok`,`opencode`,`cline`,`hermes`,`commandcode`,`kilo`]),re=new Set([`anthropic`,`openai`,`gemini`,`alibabacp`,`ollamacloud`,`opencode-zen`,`opencode-go`,`mistral`,`meta`,`deepseek`]);function Q(e){return e.oauthFlows?.browser===!0||e.oauthFlows?.device===!0}function ie(e){return{active:e.filter(e=>e.status===`active`).length,cooldown:e.filter(e=>e.status===`cooldown`).length,disabled:e.filter(e=>e.status===`disabled`).length,cooling:R(e)}}function ae({counts:e,total:t}){return e.active>0||e.cooldown>0||e.cooling>0||e.disabled>0?(0,B.jsxs)(B.Fragment,{children:[e.active>0?(0,B.jsxs)(j,{tone:`ok`,dot:!0,children:[e.active,` Healthy`]}):null,e.cooldown>0?(0,B.jsxs)(j,{tone:`warn`,dot:!0,children:[e.cooldown,` Cooldown`]}):null,e.cooling>0?(0,B.jsxs)(j,{tone:`warn`,dot:!0,children:[e.cooling,` Cooling`]}):null,e.disabled>0?(0,B.jsxs)(j,{tone:`warn`,dot:!0,children:[e.disabled,` Unhealthy`]}):null]}):(0,B.jsxs)(j,{tone:`warn`,dot:!0,children:[t,` Connected`]})}function $({kind:e,isPending:t,isError:n,hasData:r,isEmpty:i=!1}){let a=e===`models`?`Models`:`Connections`;return n?(0,B.jsxs)(j,{tone:`warn`,children:[a,` unavailable`]}):t&&!r?(0,B.jsxs)(j,{tone:`info`,children:[`Loading `,a.toLowerCase(),`…`]}):i?(0,B.jsx)(j,{children:e===`models`?`No models`:`No connections`}):null}function oe({clientVersion:e}){return e?(0,B.jsxs)(j,{className:`provider-version-badge absolute -top-4.5 left-5 right-auto z-chip max-w-[calc(100%-var(--spacing)*10)] truncate px-3 py-1 text-micro leading-[1.15] shadow-card max-small:left-4 max-small:max-w-[calc(100%-var(--spacing)*8)]`,tone:e.source===`latest`?`teal`:`default`,title:e.source===`latest`?`Latest discovered client version`:`Pinned fallback; background discovery has not succeeded yet`,children:[`v`,e.version,` · `,e.source]}):null}var se=(0,z.memo)(function({provider:e,serviceKind:t}){let n=X.has(e.providerId.toLowerCase()),r=e.label||e.displayName,i=w(e.providerId),o=i.data?.filter(e=>t===void 0||e.serviceKind===t||t===`llm`&&e.serviceKind===void 0).length,s=E(e.providerId),c=s.data,l=ie(c??[]);return(0,B.jsxs)(A,{className:H,children:[(0,B.jsx)(oe,{clientVersion:e.clientVersion}),n?(0,B.jsx)(`span`,{"aria-label":`Friend sponsor`,title:`Friend sponsor`,className:`absolute top-0 right-0 z-2 w-36 h-36 overflow-hidden pointer-events-none`,children:(0,B.jsx)(`span`,{className:a(`absolute top-9 -right-11 w-38 py-1 rotate-45 bg-accent-soft`,`text-accent text-micro font-extrabold tracking-tight leading-[1.05]`,`text-center uppercase shadow-ribbon`),children:`Friend`})}):null,(0,B.jsx)(v,{to:`/providers/${encodeURIComponent(e.providerId)}${t===void 0?``:`?service=${t}`}`,className:U,children:(0,B.jsxs)(I,{gap:`10px`,children:[(0,B.jsx)(N,{icon:e.providerId,name:r,size:32,imageSize:24}),(0,B.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,B.jsx)(`div`,{className:W,children:r}),(0,B.jsxs)(`div`,{className:`mt-1.5 flex flex-wrap gap-2`,children:[c===void 0?(0,B.jsx)($,{kind:`accounts`,isPending:s.isPending,isError:s.isError,hasData:!1}):c.length===0?e.requiresAccount===!1?(0,B.jsx)(j,{tone:`ok`,children:`Free Endpoint`}):(0,B.jsx)(j,{children:`No connections`}):(0,B.jsx)(ae,{counts:l,total:c.length}),s.isError&&c!==void 0?(0,B.jsx)(j,{tone:`warn`,children:`Connections unavailable`}):null]})]}),(0,B.jsxs)(`div`,{className:`flex flex-col items-end gap-1.5 shrink-0`,children:[(0,B.jsxs)(`span`,{className:`font-mono tabular-nums text-micro font-semibold bg-kbd-bg px-2.5 py-0.5 rounded-chip text-text-secondary`,children:[e.providerId,`/`]}),o!==void 0&&o>0?(0,B.jsxs)(j,{tone:`info`,children:[o,` models`]}):null,i.isError?(0,B.jsx)(j,{tone:`warn`,children:`Models unavailable`}):o===void 0?(0,B.jsx)($,{kind:`models`,isPending:i.isPending,isError:!1,hasData:!1}):o===0?(0,B.jsx)($,{kind:`models`,isPending:!1,isError:!1,hasData:!0,isEmpty:!0}):null]})]})})]})});function ce(e,t){let n=Number(!!t.configured)-Number(!!e.configured);return n===0?(e.label||e.displayName).localeCompare(t.label||t.displayName):n}var le=`cartethyia.providerSectionsCollapsed`;function ue(){try{let e=window.localStorage.getItem(le),t=e?JSON.parse(e):[];return new Set(Array.isArray(t)?t.filter(e=>typeof e==`string`):[])}catch{return new Set}}var de=[{title:`Founding Friend & Sponsors`,subtitle:`Super Cheap inference pool`,filter:e=>X.has(e.providerId.toLowerCase())},{title:`Free Limited Providers`,filter:e=>Z.has(e.providerId.toLowerCase())},{title:`OAuth & Agent Providers`,filter:e=>Q(e)&&!Z.has(e.providerId.toLowerCase())},{title:`Well Known API Key Providers`,subtitle:`The household names — sign up with a key and go`,filter:e=>e.isBuiltIn&&re.has(e.providerId.toLowerCase())&&!X.has(e.providerId.toLowerCase())&&!Z.has(e.providerId.toLowerCase())&&!Q(e)},{title:`Other API Key Providers`,subtitle:`Free tier friendly — no credit card`,filter:e=>e.isBuiltIn&&!re.has(e.providerId.toLowerCase())&&!X.has(e.providerId.toLowerCase())&&!Z.has(e.providerId.toLowerCase())&&!Q(e)}];function fe(){let[e,t]=(0,z.useState)(ue),n=C(),i=(0,z.useMemo)(()=>n.data??[],[n.data]),o=(0,z.useMemo)(()=>[...i.filter(e=>!e.isBuiltIn)].sort(ce),[i]),s=(0,z.useMemo)(()=>i.filter(e=>G(e).includes(`websearch`)),[i]),c=(0,z.useMemo)(()=>i.filter(e=>G(e).includes(`llm`)),[i]),[f,p]=b(),m=f.get(`tab`),g=m===`search`||m===`media`?m:`llm`,_=e=>{p(t=>{let n=new URLSearchParams(t);return e===`llm`?n.delete(`tab`):n.set(`tab`,e),n})},v=(0,z.useMemo)(()=>i.filter(e=>G(e).includes(`imageGeneration`)||G(e).includes(`videoGeneration`)),[i]),y=(0,z.useMemo)(()=>[...s].sort((e,t)=>(e.label||e.displayName).localeCompare(t.label||t.displayName)),[s]),x=(e,t)=>{let n=Number(!!t.configured)-Number(!!e.configured);return n===0?(e.label||e.displayName).localeCompare(t.label||t.displayName):n},w=(0,z.useMemo)(()=>{if(g===`media`)return[{title:`Media Generation`,subtitle:`Providers that can return an image or a video`,providers:v}].filter(e=>e.providers.length>0);if(g===`search`)return[{title:`Search Providers`,subtitle:`Providers that can answer a web search request`,providers:y}].filter(e=>e.providers.length>0);let e=c;return de.map(t=>({...t,providers:e.filter(t.filter).sort(x)})).filter(e=>e.providers.length>0)},[c,y,v,g]),T=n.isPending&&!n.data?(0,B.jsx)(u,{label:`Loading providers...`}):n.isError?(0,B.jsx)(l,{message:h(n.error,`Failed to load providers`),onRetry:()=>n.refetch()}):null;return T?(0,B.jsxs)(A,{children:[(0,B.jsx)(k,{title:`Providers`,icon:(0,B.jsx)(S,{size:16})}),(0,B.jsx)(O,{className:`flex flex-1`,children:T})]}):(0,B.jsx)(F,{gap:`24px`,children:(0,B.jsxs)(A,{children:[(0,B.jsx)(k,{title:`Providers`,subtitle:`Connected pinned first · A–Z`,icon:(0,B.jsx)(S,{size:16})}),(0,B.jsxs)(O,{className:`flex flex-col gap-8`,children:[(0,B.jsxs)(`div`,{className:`flex items-center gap-4 flex-wrap`,children:[(0,B.jsx)(`div`,{className:`flex gap-2`,children:[`llm`,`search`,`media`].map(e=>(0,B.jsxs)(`button`,{onClick:()=>_(e),className:a(`px-6 py-3 rounded-inset text-caption font-semibold border cursor-pointer`,g===e?`border-accent bg-accent-soft text-accent`:`border-inner-border bg-surface-1 text-text-secondary`),children:[e===`llm`?`LLM`:e===`search`?`Search`:`Media`,e===`search`?` (${s.length})`:e===`media`?` (${v.length})`:` (${c.length})`]},e))}),(0,B.jsx)(`span`,{className:`ml-auto text-micro text-text-tertiary`,children:g===`search`?`Fallback runs only when the model invokes Websearch`:g===`media`?`Image and video generation`:`Connected pinned first · A–Z`})]}),g===`llm`?(0,B.jsx)(Y,{customProviders:o}):null,w.length===0?(0,B.jsx)(A,{children:(0,B.jsx)(O,{children:(0,B.jsx)(d,{title:`No providers found`,message:`No providers available.`})})}):w.map(n=>{let i=e.has(n.title);return(0,B.jsxs)(`section`,{className:`flex flex-col gap-6`,children:[(0,B.jsxs)(`button`,{type:`button`,className:`flex items-start gap-4 border-0 bg-transparent p-0 text-left text-inherit`,"aria-expanded":!i,onClick:()=>t(e=>{let t=new Set(e);t.has(n.title)?t.delete(n.title):t.add(n.title);try{window.localStorage.setItem(le,JSON.stringify([...t]))}catch{}return t}),children:[(0,B.jsx)(r,{size:15,className:a(`mt-1 shrink-0 transition-transform`,i&&`-rotate-90`)}),(0,B.jsxs)(F,{gap:`1px`,children:[(0,B.jsxs)(`h2`,{className:`text-body font-bold tracking-[-0.01em]`,children:[n.title,` (`,n.providers.length,`)`,i?` (Hidden)`:``]}),!i&&n.subtitle?(0,B.jsx)(`p`,{className:`mt-1 text-badge text-text-tertiary`,children:n.subtitle}):null]})]}),i?null:(0,B.jsx)(V,{children:n.providers.map(e=>(0,B.jsx)(se,{provider:e,serviceKind:g===`search`?`websearch`:g===`media`?G(e).includes(`imageGeneration`)?`imageGeneration`:`videoGeneration`:`llm`},e.providerId))})]},n.title)})]})]})})}export{fe as default};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{n as e,o as t,r as n,t as r}from"./jsx-runtime-CXUMngI_.js";import{i}from"./terminal-C9mZ4Ugm.js";import{t as a}from"./select-CGUuTQmj.js";import{g as o,m as s,n as c,t as l}from"./toast-DKAdP2mo.js";import{t as u}from"./download-A0SW9OCW.js";import{t as d}from"./eye-off-Bk5g2luF.js";import{t as f}from"./eye-C_hawfH4.js";import{t as p}from"./gauge-BbIMy7MB.js";import{a as m,n as h,r as g,t as _}from"./state-DHKdg-pm.js";import{t as v}from"./dialog-iocKA3jr.js";import{t as y}from"./pencil-768ysRAr.js";import{t as b}from"./plus-DIdX_g-x.js";import{i as ee,r as x,t as S}from"./privacy-mode-CQjbZ3xk.js";import{t as C}from"./rotate-ccw-CufcqITi.js";import{t as w}from"./shield-check-DVS0Foqh.js";import{t as te}from"./trash-Cppn5c3R.js";import{S as T,_ as E,c as D,v as O,w as k}from"./assert-Bwh6DJTK.js";import{a as A,c as j,i as M,r as N,t as P}from"./query-keys-ROf-g1Wi.js";import{t as F}from"./useMutation-DVmwOKU-.js";import{F as ne,et as I}from"./entry-DcX5sMzh.js";import{n as re,r as ie,t as ae}from"./card-BTdbRFFg.js";import{n as oe}from"./download-dRFo5_Wu.js";import{t as L}from"./numbers-CFL4_Dqc.js";import{t as R}from"./badge-BwmwEOgA.js";import{n as z}from"./input-Bn4_kNav.js";import{t as B}from"./switch-DIDeAiz9.js";import{t as se}from"./stack-C1kTcOmP.js";import{n as ce}from"./inline-DCejSLlA.js";import{r as V,t as le}from"./layout-Bv-NxqZ5.js";import{n as H}from"./live-YlifPYox.js";var ue=e(`cloud`,[[`path`,{d:`M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z`,key:`p7xjir`}]]),de=e(`power`,[[`path`,{d:`M12 2v10`,key:`mnfbl`}],[`path`,{d:`M18.4 6.6a9 9 0 1 1-12.77.04`,key:`obofu9`}]]),fe=1e6,pe=1e8,me=5e6,he=`sin1`,ge=[{label:`Asia Pacific`,regions:[{id:`sin1`,label:`Singapore`},{id:`hkg1`,label:`Hong Kong`},{id:`icn1`,label:`Seoul`},{id:`hnd1`,label:`Tokyo`},{id:`kix1`,label:`Osaka`},{id:`bom1`,label:`Mumbai`},{id:`syd1`,label:`Sydney`}]},{label:`Europe`,regions:[{id:`fra1`,label:`Frankfurt`},{id:`cdg1`,label:`Paris`},{id:`lhr1`,label:`London`},{id:`arn1`,label:`Stockholm`},{id:`dub1`,label:`Dublin`}]},{label:`North America`,regions:[{id:`iad1`,label:`Washington, D.C.`},{id:`sfo1`,label:`San Francisco`},{id:`pdx1`,label:`Portland`},{id:`cle1`,label:`Cleveland`},{id:`yul1`,label:`Montréal`}]},{label:`Other`,regions:[{id:`gru1`,label:`São Paulo`},{id:`cpt1`,label:`Cape Town`},{id:`dxb1`,label:`Dubai`}]}];function _e(){return T({queryKey:P.network.pools,queryFn:e=>A(`/network/pools`,{signal:E(e)}).then(D),staleTime:N.staleTime,gcTime:N.gcTime})}function ve(){let e=k();return F({mutationFn:e=>A(`/network/pools`,{method:`POST`,body:JSON.stringify(e)}),onSuccess:async()=>{await e.invalidateQueries({queryKey:P.network.pools}),l.success(`Proxy pool created`)},onError:e=>{l.error(`Could not create the proxy pool.`,j(e))}})}function ye(){let e=k();return F({mutationFn:e=>A(`/network/pools/relay/deploy`,{method:`POST`,body:JSON.stringify(e)}),onSuccess:async()=>{await e.invalidateQueries({queryKey:P.network.pools})}})}function be(){return F({mutationFn:e=>A(`/network/pools/test-batch`,{method:`POST`,body:JSON.stringify({targets:e})})})}function xe(){let e=k();return F({mutationFn:({poolId:e,request:t})=>A(`/network/pools/${encodeURIComponent(e)}`,{method:`PATCH`,body:JSON.stringify(t)}),onSuccess:async()=>{await e.invalidateQueries({queryKey:P.network.pools}),l.success(`Proxy updated`)},onError:e=>{l.error(`Could not update the proxy pool.`,j(e))}})}function Se(e){return T({queryKey:[...P.network.pools,e,`health-events`],queryFn:t=>A(`/network/pools/${encodeURIComponent(e??``)}/health-events`,{signal:E(t)}),enabled:!!e,...N,refetchInterval:M.status})}function Ce(){let e=k();return F({mutationFn:e=>A(`/network/pools/${encodeURIComponent(e)}/recover`,{method:`POST`,body:`{}`}),onSuccess:async(t,n)=>{await Promise.all([e.invalidateQueries({queryKey:P.network.pools}),e.invalidateQueries({queryKey:[...P.network.pools,n,`health-events`]})]),l.success(`Proxy pool recovered`)},onError:e=>{l.error(`Could not recover the proxy pool.`,j(e))}})}function we(){let e=k();return F({mutationFn:e=>A(`/network/pools/${encodeURIComponent(e)}`,{method:`DELETE`}),onSuccess:async()=>{await e.invalidateQueries({queryKey:P.network.pools}),l.success(`Proxy pool deleted`)},onError:e=>{l.error(`Could not delete the proxy pool.`,j(e))}})}function Te(){let e=k();return F({mutationFn:({poolId:e,providerId:t})=>A(`/network/pools/${encodeURIComponent(e)}/provider-probe`,{method:`POST`,body:JSON.stringify({providerId:t})}),onSuccess:async()=>{await e.invalidateQueries({queryKey:P.network.pools})}})}function Ee(){return F({mutationFn:({providerId:e,targets:t})=>A(`/network/pools/test-batch/provider`,{method:`POST`,body:JSON.stringify({providerId:e,targets:t})})})}function De(){let e=k();return F({mutationFn:e=>A(`/network/pools/${encodeURIComponent(e)}/health-check`,{method:`POST`,body:`{}`}),onSuccess:async()=>{await e.invalidateQueries({queryKey:P.network.pools}),l.success(`Health check complete`)},onError:e=>{l.error(`Health check failed.`,j(e))}})}function Oe(){let e=k();return F({mutationFn:({poolId:e,bytes:t})=>A(`/network/pools/${encodeURIComponent(e)}/speed-test`,{method:`POST`,body:JSON.stringify({bytes:t})}),onSuccess:async()=>{await e.invalidateQueries({queryKey:P.network.pools})}})}function ke(){let e=k();return F({mutationFn:({poolId:e,providerId:t})=>A(`/network/pools/${encodeURIComponent(e)}/cooldowns/clear`,{method:`POST`,body:JSON.stringify(t?{providerId:t}:{})}),onSuccess:async()=>{await e.invalidateQueries({queryKey:P.network.pools}),l.success(`Provider cooldowns cleared`)},onError:e=>{l.error(`Could not clear provider cooldowns.`,j(e))}})}var U=t(n(),1),W=r(),G={cloudflare:{label:`Cloudflare Workers`,tokenLabel:`Cloudflare API token`,needsAccount:!0,host:`*.workers.dev`,hasRegion:!1},vercel:{label:`Vercel`,tokenLabel:`Vercel API token`,needsAccount:!1,host:`*.vercel.app`,hasRegion:!0},deno:{label:`Deno Deploy`,tokenLabel:`Deno Deploy token`,needsAccount:!1,host:`*.deno.dev`,hasRegion:!1}},Ae=ge.flatMap(e=>e.regions.map(t=>({value:t.id,label:`${e.label} — ${t.label}`})));function je({onClose:e}){let t=ye(),[n,r]=(0,U.useState)(`cloudflare`),[i,o]=(0,U.useState)(he),[s,u]=(0,U.useState)(``),[d,f]=(0,U.useState)(``),[p,h]=(0,U.useState)(``),[g,_]=(0,U.useState)(null),y=G[n],b=s.trim().length>0&&(!y.needsAccount||d.trim().length>0);return(0,W.jsx)(v,{open:!0,onClose:e,title:`Deploy Relay`,description:`Run outbound traffic through a hosted relay (Cloudflare, Vercel, Deno).`,size:`md`,children:(0,W.jsxs)(se,{gap:`12px`,children:[(0,W.jsxs)(`p`,{className:`text-badge text-text-tertiary m-0 flex gap-3`,children:[(0,W.jsx)(I,{size:13,className:`shrink-0 mt-0.5`}),(0,W.jsxs)(`span`,{children:[`Deploys a small relay worker to your own `,y.label,` account and registers its URL (`,(0,W.jsx)(`code`,{children:y.host}),`) as an active HTTP pool. Your API token is used only for the deploy and is never stored.`]})]}),(0,W.jsx)(a,{label:`Relay host`,id:`relay-target`,value:n,onValueChange:e=>r(e),options:O.map(e=>({value:e,label:G[e].label}))}),(0,W.jsx)(z,{label:y.tokenLabel,id:`relay-token`,type:`password`,value:s,placeholder:`Paste a deploy token`,onChange:e=>u(e.target.value)}),y.needsAccount?(0,W.jsx)(z,{label:`Account ID`,id:`relay-account`,value:d,placeholder:`Cloudflare account id`,onChange:e=>f(e.target.value)}):null,(0,W.jsx)(z,{label:`Project name (optional)`,id:`relay-project`,value:p,placeholder:`e.g. cartethyia-relay`,onChange:e=>h(e.target.value)}),y.hasRegion?(0,W.jsx)(a,{label:`Deploy region`,id:`relay-region`,value:i,onValueChange:e=>o(e),options:Ae}):null,y.hasRegion?(0,W.jsx)(`p`,{className:`text-badge text-text-tertiary m-0`,children:`Sets the region on the Vercel project, which is what decides the country outbound traffic leaves from. A region sent on the deployment alone is accepted but does not move the Function.`}):null,(0,W.jsxs)(`div`,{className:`flex items-center gap-5`,children:[(0,W.jsx)(c,{variant:`primary`,size:`sm`,onClick:()=>{b&&t.mutate({target:n,token:s.trim(),...y.needsAccount&&d.trim()?{accountId:d.trim()}:{},...p.trim()?{projectName:p.trim()}:{},...y.hasRegion?{region:i}:{}},{onSuccess:e=>{_(e.relayUrl),u(``),l.success(`Relay deployed to ${e.relayUrl} and registered as a pool.`)},onError:e=>l.error(j(e,`Relay deploy failed.`))})},disabled:!b||t.isPending,children:t.isPending?`Deploying…`:`Deploy relay`}),g?(0,W.jsxs)(`span`,{className:`mt-1 text-badge text-text-tertiary`,children:[`Registered pool at `,(0,W.jsx)(`code`,{children:g})]}):null]}),t.isError?(0,W.jsxs)(`p`,{className:`text-badge text-red m-0 flex gap-3`,children:[(0,W.jsx)(m,{size:13,className:`shrink-0 mt-0.5`}),(0,W.jsx)(`span`,{children:j(t.error,`Relay deploy failed.`)})]}):null]})})}function Me(e,t){if(e!==void 0)return e.endpoint===``||e.endpoint===(t??``)?e.result:void 0}function Ne(e,t,n){switch(t){case`name`:return(e.label||e.endpoint).toLowerCase();case`family`:return e.family===void 0||e.family===null||e.family===``?null:e.family.toLowerCase();case`address`:return e.egressIp??null;case`load`:return n??null}}function Pe(e,t,n,r){let i=n===`asc`?1:-1;return[...e].sort((e,n)=>{let a=Ne(e,t,r(e)),o=Ne(n,t,r(n));return a===null&&o===null?0:a===null?1:o===null?-1:typeof a==`number`&&typeof o==`number`?(a-o)*i:String(a).localeCompare(String(o))*i})}function K(e,t){let n=e.filter(e=>e.status===`active`),r=n.reduce((e,t)=>e+t.maxInflight,0),i=t===void 0?n.reduce((e,t)=>e+(t.inflight??0),0):n.reduce((e,n)=>e+(t.get(n.id)??0),0),a=0,o=0;for(let e of n)(t===void 0?e.inflight??0:t.get(e.id)??0)>=e.maxInflight?o+=1:a+=1;let s=null,c=Date.now(),l=e=>{if(!e)return;let t=Date.parse(e);if(Number.isNaN(t))return;let n=t-c;n<=0||(s===null||n<s)&&(s=n)};for(let t of e){l(t.cooldownUntil);for(let e of t.providerCooldowns??[])l(e.until)}let u=n.filter(e=>e.lastLatencyMs!==void 0&&Number.isFinite(e.lastLatencyMs)),d=u.length===0?null:Math.round(u.reduce((e,t)=>e+(t.lastLatencyMs??0),0)/u.length);return{totalPools:e.length,active:n.length,cooldown:e.filter(e=>e.status===`cooldown`).length,totalMaxConcurrency:r,usedInflight:i,availableCapacity:Math.max(0,r-i),routablePools:a,saturatedPools:o,soonestCooldownMs:s,avgLatencyMs:d,measuredPools:u.length}}var q=[`http`,`https`,`socks5`];function J(e){return/^[a-z][a-z0-9+.-]*:\/\//i.test(e.trim())}function Fe(e,t){let n=e.trim();return t===null||J(n)?n:`${t}://${n}`}function Y(e){return e.find(e=>e.trim()!==``)}function X(e){let t=e.trim().toLowerCase();return t.startsWith(`https://`)?`https`:t.startsWith(`socks5://`)||t.startsWith(`socks://`)?`socks5`:`http`}var Ie=1024**3;function Le(e){let t=e.trim();if(t===``)return null;let n=Number(t);return!Number.isFinite(n)||n<=0?null:Math.max(1,Math.round(n*Ie))}function Z(e,t,n){let r=new Map;if(t.trim().toLowerCase()===``||n<=0)return r;let i=Math.floor(e/n),a=e-i*n;for(let e=0;e<n;e+=1){let t=e===n-1?a:0;r.set(e,i+t)}return r}var Re=4,ze=`cartethyia_proxy_test_payload`,Be=`cartethyia_proxy_check_results`,Ve=[{value:`url`,label:`Test URL`},{value:`opencode`,label:`Test OpenCode`}],He=`opencode`,Ue=4,We=`Mysterious Proxy`;function Q(e){return e.avgLatencyMs===null?`no measurement yet`:`avg across ${e.measuredPools} enabled ${e.measuredPools===1?`pool`:`pools`}`}function Ge(e){let t=e.endpoint||``,n=t.includes(`://`)?t:`${e.kind}://${t}`,r={"https:":`443`,"http:":`80`,"socks5:":`1080`,"socks:":`1080`};try{let e=new URL(n),t=e.port||r[e.protocol]||``,i=`${e.hostname}${t?`:${t}`:``}`;return{name:i,endpoint:`${e.protocol}//${i}${e.pathname===`/`?``:e.pathname}${e.search}`}}catch{return{name:e.label||t,endpoint:t}}}function Ke(e){return e.label||Ge(e).name||e.id}var $=1024**3;function qe(e){if(e.lastSpeedtestStatus===void 0||e.lastSpeedtestAt===void 0)return;let t=e.lastSpeedtestDurationMs??0,n=e.lastSpeedtestBytes??0,r=t>0?n/(t/1e3):void 0;return{poolId:e.id,status:e.lastSpeedtestStatus,bytes:n,durationMs:t,...r===void 0?{}:{bytesPerSecond:r,megabitsPerSecond:r*8/1e6},...e.lastSpeedtestError?{errorMessage:e.lastSpeedtestError}:{},measuredAt:e.lastSpeedtestAt}}function Je(e,t){if(!e)return t;if(!t)return e;let n=e.measuredAt?new Date(e.measuredAt).getTime():0;return(t.measuredAt?new Date(t.measuredAt).getTime():0)>=n?t:e}var Ye=[{value:String(fe),label:`1 MB`},{value:String(me),label:`5 MB`},{value:`50000000`,label:`50 MB`},{value:String(pe),label:`100 MB`}];function Xe({pool:e,onClose:t,actionsRef:n}){let r=xe(),i=Ee(),a=De(),[u,d]=(0,U.useState)(e.label??``),[f,p]=(0,U.useState)(e.family??``),[m,h]=(0,U.useState)(e.endpoint??``),[g,_]=(0,U.useState)(String(e.maxInflight??10)),[v,y]=(0,U.useState)(String(e.weight??100)),[b,ee]=(0,U.useState)(e.quotaBytes?String(Math.round(e.quotaBytes/$*1e3)/1e3):``),[x,S]=(0,U.useState)(null),[C,w]=(0,U.useState)(!1),te=m.trim()===e.endpoint,T=async()=>{w(!0),S(null);try{if(te){let t=await a.mutateAsync(e.id),n=t.status===`healthy`||t.status===`reachable`;S({ok:n,message:t.status===`healthy`?`Connected in ${t.latencyMs??0}ms`:t.errorMessage??`Connection failed`});return}let t=[{kind:e.kind,endpoint:m.trim(),...e.family===null||e.family===void 0?{}:{family:e.family}}],[n]=await i.mutateAsync({providerId:He,targets:t}),r=n?.result;if(!r){S({ok:!1,message:`Probe returned no result`});return}let o=r.status===`allowed`||r.status===`throttled`;S({ok:o,message:r.reason??(r.status===`allowed`?`Reachable${r.latencyMs===void 0?``:` in ${r.latencyMs}ms`}`:r.status===`throttled`?`Reachable; rate limit spent`:`Probe could not complete`)})}catch(e){S({ok:!1,message:j(e,`Connection failed`)})}finally{w(!1)}},E=Le(b),D=async()=>{await r.mutateAsync({poolId:e.id,request:{...u.trim()===e.label?{}:{label:u.trim()||void 0},...f.trim()===(e.family??``)?{}:{family:f.trim()||null},...m.trim()!==e.endpoint&&m.trim()!==``?{endpoint:m.trim()}:{},...Number(g)===e.maxInflight?{}:{maxInflight:Number(g)},...Number(v)===e.weight?{}:{weight:Number(v)},...E===(e.quotaBytes??null)?{}:{quotaBytes:E}}}),l.success(`Proxy updated`),t()};return(0,U.useEffect)(()=>{n?.((0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(c,{variant:`secondary`,size:`sm`,onClick:t,children:`Cancel`}),(0,W.jsx)(c,{variant:`primary`,size:`sm`,disabled:r.isPending||!m.trim(),onClick:()=>void D(),children:`Save`})]}))}),(0,W.jsxs)(se,{gap:`12px`,children:[(0,W.jsx)(`div`,{children:(0,W.jsx)(z,{label:`Name`,value:u,onChange:e=>d(e.target.value)})}),(0,W.jsx)(`div`,{children:(0,W.jsx)(z,{label:`Family`,value:f,placeholder:`e.g. residential-id`,onChange:e=>p(e.target.value)})}),(0,W.jsx)(`div`,{children:(0,W.jsx)(z,{label:`Endpoint`,value:m,onChange:e=>h(e.target.value),className:`font-mono tabular-nums`})}),(0,W.jsxs)(`div`,{className:`grid grid-cols-2 gap-5`,children:[(0,W.jsx)(`div`,{children:(0,W.jsx)(z,{label:`Max concurrent`,type:`number`,min:1,value:g,onChange:e=>_(e.target.value)})}),(0,W.jsx)(`div`,{children:(0,W.jsx)(z,{label:`Weight`,type:`number`,min:1,value:v,onChange:e=>y(e.target.value)})})]}),(0,W.jsxs)(`div`,{children:[(0,W.jsx)(z,{label:`Bandwidth quota (GB, blank = unmetered)`,type:`number`,min:.001,step:`0.1`,value:b,onChange:e=>ee(e.target.value)}),(0,W.jsx)(`div`,{className:`text-micro text-text-tertiary mt-2`,children:E===null?`No quota — the bar shows a running total only.`:`Bar turns orange at 80% and red once ${L(E)} is exceeded.`})]}),x&&(0,W.jsx)(`div`,{className:`rounded-inset px-6 py-4 text-badge font-semibold ${x.ok?`bg-green-soft text-green`:`bg-red-soft text-red`}`,children:x.message}),(0,W.jsx)(`div`,{children:(0,W.jsx)(c,{variant:`secondary`,size:`sm`,disabled:C,icon:C?(0,W.jsx)(s,{size:13,className:`animate-spin`}):(0,W.jsx)(o,{size:13}),onClick:()=>void T(),children:C?`Testing…`:`Test connection`})})]})}function Ze({endpoint:e,chip:t,onChipChange:n}){return(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,role:`group`,"aria-label":`Scheme for the first endpoint`,children:[(0,W.jsx)(`span`,{className:`text-badge text-text-secondary`,children:`Scheme`}),q.map(r=>{let i=t===r;return(0,W.jsxs)(c,{type:`button`,variant:i?`primary`:`secondary`,size:`sm`,disabled:e===void 0,"aria-pressed":i,"data-scheme":r,onClick:()=>n(i?null:r),className:`font-mono`,children:[r,`://`]},r)}),t!==null&&(0,W.jsxs)(`span`,{className:`text-badge text-text-tertiary`,children:[`→ `,Fe(e??``,t)]})]})}function Qe({onClose:e,actionsRef:t,onProbeResult:n,onHealthResult:r}){let i=ve(),a=be(),o=Ee(),[s,u]=(0,U.useState)(``),[d,f]=(0,U.useState)(``),[p,m]=(0,U.useState)(``),[h,g]=(0,U.useState)(null),[_,v]=(0,U.useState)([]),[y,b]=(0,U.useState)({}),[ee,x]=(0,U.useState)({}),[S,C]=(0,U.useState)(!1),[w,te]=(0,U.useState)(null),T=s.split(`
|
|
1
|
+
import{n as e,o as t,r as n,t as r}from"./jsx-runtime-CXUMngI_.js";import{i}from"./terminal-C9mZ4Ugm.js";import{t as a}from"./select-CGUuTQmj.js";import{g as o,m as s,n as c,t as l}from"./toast-DKAdP2mo.js";import{t as u}from"./download-A0SW9OCW.js";import{t as d}from"./eye-off-Bk5g2luF.js";import{t as f}from"./eye-C_hawfH4.js";import{t as p}from"./gauge-BbIMy7MB.js";import{a as m,n as h,r as g,t as _}from"./state-DHKdg-pm.js";import{t as v}from"./dialog-iocKA3jr.js";import{t as y}from"./pencil-768ysRAr.js";import{t as b}from"./plus-DIdX_g-x.js";import{i as ee,r as x,t as S}from"./privacy-mode-CQjbZ3xk.js";import{t as C}from"./rotate-ccw-CufcqITi.js";import{t as w}from"./shield-check-DVS0Foqh.js";import{t as te}from"./trash-Cppn5c3R.js";import{S as T,_ as E,c as D,v as O,w as k}from"./assert-Bwh6DJTK.js";import{a as A,c as j,i as M,r as N,t as P}from"./query-keys-ROf-g1Wi.js";import{t as F}from"./useMutation-DVmwOKU-.js";import{F as ne,et as I}from"./entry-C3M9aRLH.js";import{n as re,r as ie,t as ae}from"./card-BTdbRFFg.js";import{n as oe}from"./download-dRFo5_Wu.js";import{t as L}from"./numbers-CFL4_Dqc.js";import{t as R}from"./badge-BwmwEOgA.js";import{n as z}from"./input-Bn4_kNav.js";import{t as B}from"./switch-DIDeAiz9.js";import{t as se}from"./stack-C1kTcOmP.js";import{n as ce}from"./inline-DCejSLlA.js";import{r as V,t as le}from"./layout-Bv-NxqZ5.js";import{n as H}from"./live-YlifPYox.js";var ue=e(`cloud`,[[`path`,{d:`M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z`,key:`p7xjir`}]]),de=e(`power`,[[`path`,{d:`M12 2v10`,key:`mnfbl`}],[`path`,{d:`M18.4 6.6a9 9 0 1 1-12.77.04`,key:`obofu9`}]]),fe=1e6,pe=1e8,me=5e6,he=`sin1`,ge=[{label:`Asia Pacific`,regions:[{id:`sin1`,label:`Singapore`},{id:`hkg1`,label:`Hong Kong`},{id:`icn1`,label:`Seoul`},{id:`hnd1`,label:`Tokyo`},{id:`kix1`,label:`Osaka`},{id:`bom1`,label:`Mumbai`},{id:`syd1`,label:`Sydney`}]},{label:`Europe`,regions:[{id:`fra1`,label:`Frankfurt`},{id:`cdg1`,label:`Paris`},{id:`lhr1`,label:`London`},{id:`arn1`,label:`Stockholm`},{id:`dub1`,label:`Dublin`}]},{label:`North America`,regions:[{id:`iad1`,label:`Washington, D.C.`},{id:`sfo1`,label:`San Francisco`},{id:`pdx1`,label:`Portland`},{id:`cle1`,label:`Cleveland`},{id:`yul1`,label:`Montréal`}]},{label:`Other`,regions:[{id:`gru1`,label:`São Paulo`},{id:`cpt1`,label:`Cape Town`},{id:`dxb1`,label:`Dubai`}]}];function _e(){return T({queryKey:P.network.pools,queryFn:e=>A(`/network/pools`,{signal:E(e)}).then(D),staleTime:N.staleTime,gcTime:N.gcTime})}function ve(){let e=k();return F({mutationFn:e=>A(`/network/pools`,{method:`POST`,body:JSON.stringify(e)}),onSuccess:async()=>{await e.invalidateQueries({queryKey:P.network.pools}),l.success(`Proxy pool created`)},onError:e=>{l.error(`Could not create the proxy pool.`,j(e))}})}function ye(){let e=k();return F({mutationFn:e=>A(`/network/pools/relay/deploy`,{method:`POST`,body:JSON.stringify(e)}),onSuccess:async()=>{await e.invalidateQueries({queryKey:P.network.pools})}})}function be(){return F({mutationFn:e=>A(`/network/pools/test-batch`,{method:`POST`,body:JSON.stringify({targets:e})})})}function xe(){let e=k();return F({mutationFn:({poolId:e,request:t})=>A(`/network/pools/${encodeURIComponent(e)}`,{method:`PATCH`,body:JSON.stringify(t)}),onSuccess:async()=>{await e.invalidateQueries({queryKey:P.network.pools}),l.success(`Proxy updated`)},onError:e=>{l.error(`Could not update the proxy pool.`,j(e))}})}function Se(e){return T({queryKey:[...P.network.pools,e,`health-events`],queryFn:t=>A(`/network/pools/${encodeURIComponent(e??``)}/health-events`,{signal:E(t)}),enabled:!!e,...N,refetchInterval:M.status})}function Ce(){let e=k();return F({mutationFn:e=>A(`/network/pools/${encodeURIComponent(e)}/recover`,{method:`POST`,body:`{}`}),onSuccess:async(t,n)=>{await Promise.all([e.invalidateQueries({queryKey:P.network.pools}),e.invalidateQueries({queryKey:[...P.network.pools,n,`health-events`]})]),l.success(`Proxy pool recovered`)},onError:e=>{l.error(`Could not recover the proxy pool.`,j(e))}})}function we(){let e=k();return F({mutationFn:e=>A(`/network/pools/${encodeURIComponent(e)}`,{method:`DELETE`}),onSuccess:async()=>{await e.invalidateQueries({queryKey:P.network.pools}),l.success(`Proxy pool deleted`)},onError:e=>{l.error(`Could not delete the proxy pool.`,j(e))}})}function Te(){let e=k();return F({mutationFn:({poolId:e,providerId:t})=>A(`/network/pools/${encodeURIComponent(e)}/provider-probe`,{method:`POST`,body:JSON.stringify({providerId:t})}),onSuccess:async()=>{await e.invalidateQueries({queryKey:P.network.pools})}})}function Ee(){return F({mutationFn:({providerId:e,targets:t})=>A(`/network/pools/test-batch/provider`,{method:`POST`,body:JSON.stringify({providerId:e,targets:t})})})}function De(){let e=k();return F({mutationFn:e=>A(`/network/pools/${encodeURIComponent(e)}/health-check`,{method:`POST`,body:`{}`}),onSuccess:async()=>{await e.invalidateQueries({queryKey:P.network.pools}),l.success(`Health check complete`)},onError:e=>{l.error(`Health check failed.`,j(e))}})}function Oe(){let e=k();return F({mutationFn:({poolId:e,bytes:t})=>A(`/network/pools/${encodeURIComponent(e)}/speed-test`,{method:`POST`,body:JSON.stringify({bytes:t})}),onSuccess:async()=>{await e.invalidateQueries({queryKey:P.network.pools})}})}function ke(){let e=k();return F({mutationFn:({poolId:e,providerId:t})=>A(`/network/pools/${encodeURIComponent(e)}/cooldowns/clear`,{method:`POST`,body:JSON.stringify(t?{providerId:t}:{})}),onSuccess:async()=>{await e.invalidateQueries({queryKey:P.network.pools}),l.success(`Provider cooldowns cleared`)},onError:e=>{l.error(`Could not clear provider cooldowns.`,j(e))}})}var U=t(n(),1),W=r(),G={cloudflare:{label:`Cloudflare Workers`,tokenLabel:`Cloudflare API token`,needsAccount:!0,host:`*.workers.dev`,hasRegion:!1},vercel:{label:`Vercel`,tokenLabel:`Vercel API token`,needsAccount:!1,host:`*.vercel.app`,hasRegion:!0},deno:{label:`Deno Deploy`,tokenLabel:`Deno Deploy token`,needsAccount:!1,host:`*.deno.dev`,hasRegion:!1}},Ae=ge.flatMap(e=>e.regions.map(t=>({value:t.id,label:`${e.label} — ${t.label}`})));function je({onClose:e}){let t=ye(),[n,r]=(0,U.useState)(`cloudflare`),[i,o]=(0,U.useState)(he),[s,u]=(0,U.useState)(``),[d,f]=(0,U.useState)(``),[p,h]=(0,U.useState)(``),[g,_]=(0,U.useState)(null),y=G[n],b=s.trim().length>0&&(!y.needsAccount||d.trim().length>0);return(0,W.jsx)(v,{open:!0,onClose:e,title:`Deploy Relay`,description:`Run outbound traffic through a hosted relay (Cloudflare, Vercel, Deno).`,size:`md`,children:(0,W.jsxs)(se,{gap:`12px`,children:[(0,W.jsxs)(`p`,{className:`text-badge text-text-tertiary m-0 flex gap-3`,children:[(0,W.jsx)(I,{size:13,className:`shrink-0 mt-0.5`}),(0,W.jsxs)(`span`,{children:[`Deploys a small relay worker to your own `,y.label,` account and registers its URL (`,(0,W.jsx)(`code`,{children:y.host}),`) as an active HTTP pool. Your API token is used only for the deploy and is never stored.`]})]}),(0,W.jsx)(a,{label:`Relay host`,id:`relay-target`,value:n,onValueChange:e=>r(e),options:O.map(e=>({value:e,label:G[e].label}))}),(0,W.jsx)(z,{label:y.tokenLabel,id:`relay-token`,type:`password`,value:s,placeholder:`Paste a deploy token`,onChange:e=>u(e.target.value)}),y.needsAccount?(0,W.jsx)(z,{label:`Account ID`,id:`relay-account`,value:d,placeholder:`Cloudflare account id`,onChange:e=>f(e.target.value)}):null,(0,W.jsx)(z,{label:`Project name (optional)`,id:`relay-project`,value:p,placeholder:`e.g. cartethyia-relay`,onChange:e=>h(e.target.value)}),y.hasRegion?(0,W.jsx)(a,{label:`Deploy region`,id:`relay-region`,value:i,onValueChange:e=>o(e),options:Ae}):null,y.hasRegion?(0,W.jsx)(`p`,{className:`text-badge text-text-tertiary m-0`,children:`Sets the region on the Vercel project, which is what decides the country outbound traffic leaves from. A region sent on the deployment alone is accepted but does not move the Function.`}):null,(0,W.jsxs)(`div`,{className:`flex items-center gap-5`,children:[(0,W.jsx)(c,{variant:`primary`,size:`sm`,onClick:()=>{b&&t.mutate({target:n,token:s.trim(),...y.needsAccount&&d.trim()?{accountId:d.trim()}:{},...p.trim()?{projectName:p.trim()}:{},...y.hasRegion?{region:i}:{}},{onSuccess:e=>{_(e.relayUrl),u(``),l.success(`Relay deployed to ${e.relayUrl} and registered as a pool.`)},onError:e=>l.error(j(e,`Relay deploy failed.`))})},disabled:!b||t.isPending,children:t.isPending?`Deploying…`:`Deploy relay`}),g?(0,W.jsxs)(`span`,{className:`mt-1 text-badge text-text-tertiary`,children:[`Registered pool at `,(0,W.jsx)(`code`,{children:g})]}):null]}),t.isError?(0,W.jsxs)(`p`,{className:`text-badge text-red m-0 flex gap-3`,children:[(0,W.jsx)(m,{size:13,className:`shrink-0 mt-0.5`}),(0,W.jsx)(`span`,{children:j(t.error,`Relay deploy failed.`)})]}):null]})})}function Me(e,t){if(e!==void 0)return e.endpoint===``||e.endpoint===(t??``)?e.result:void 0}function Ne(e,t,n){switch(t){case`name`:return(e.label||e.endpoint).toLowerCase();case`family`:return e.family===void 0||e.family===null||e.family===``?null:e.family.toLowerCase();case`address`:return e.egressIp??null;case`load`:return n??null}}function Pe(e,t,n,r){let i=n===`asc`?1:-1;return[...e].sort((e,n)=>{let a=Ne(e,t,r(e)),o=Ne(n,t,r(n));return a===null&&o===null?0:a===null?1:o===null?-1:typeof a==`number`&&typeof o==`number`?(a-o)*i:String(a).localeCompare(String(o))*i})}function K(e,t){let n=e.filter(e=>e.status===`active`),r=n.reduce((e,t)=>e+t.maxInflight,0),i=t===void 0?n.reduce((e,t)=>e+(t.inflight??0),0):n.reduce((e,n)=>e+(t.get(n.id)??0),0),a=0,o=0;for(let e of n)(t===void 0?e.inflight??0:t.get(e.id)??0)>=e.maxInflight?o+=1:a+=1;let s=null,c=Date.now(),l=e=>{if(!e)return;let t=Date.parse(e);if(Number.isNaN(t))return;let n=t-c;n<=0||(s===null||n<s)&&(s=n)};for(let t of e){l(t.cooldownUntil);for(let e of t.providerCooldowns??[])l(e.until)}let u=n.filter(e=>e.lastLatencyMs!==void 0&&Number.isFinite(e.lastLatencyMs)),d=u.length===0?null:Math.round(u.reduce((e,t)=>e+(t.lastLatencyMs??0),0)/u.length);return{totalPools:e.length,active:n.length,cooldown:e.filter(e=>e.status===`cooldown`).length,totalMaxConcurrency:r,usedInflight:i,availableCapacity:Math.max(0,r-i),routablePools:a,saturatedPools:o,soonestCooldownMs:s,avgLatencyMs:d,measuredPools:u.length}}var q=[`http`,`https`,`socks5`];function J(e){return/^[a-z][a-z0-9+.-]*:\/\//i.test(e.trim())}function Fe(e,t){let n=e.trim();return t===null||J(n)?n:`${t}://${n}`}function Y(e){return e.find(e=>e.trim()!==``)}function X(e){let t=e.trim().toLowerCase();return t.startsWith(`https://`)?`https`:t.startsWith(`socks5://`)||t.startsWith(`socks://`)?`socks5`:`http`}var Ie=1024**3;function Le(e){let t=e.trim();if(t===``)return null;let n=Number(t);return!Number.isFinite(n)||n<=0?null:Math.max(1,Math.round(n*Ie))}function Z(e,t,n){let r=new Map;if(t.trim().toLowerCase()===``||n<=0)return r;let i=Math.floor(e/n),a=e-i*n;for(let e=0;e<n;e+=1){let t=e===n-1?a:0;r.set(e,i+t)}return r}var Re=4,ze=`cartethyia_proxy_test_payload`,Be=`cartethyia_proxy_check_results`,Ve=[{value:`url`,label:`Test URL`},{value:`opencode`,label:`Test OpenCode`}],He=`opencode`,Ue=4,We=`Mysterious Proxy`;function Q(e){return e.avgLatencyMs===null?`no measurement yet`:`avg across ${e.measuredPools} enabled ${e.measuredPools===1?`pool`:`pools`}`}function Ge(e){let t=e.endpoint||``,n=t.includes(`://`)?t:`${e.kind}://${t}`,r={"https:":`443`,"http:":`80`,"socks5:":`1080`,"socks:":`1080`};try{let e=new URL(n),t=e.port||r[e.protocol]||``,i=`${e.hostname}${t?`:${t}`:``}`;return{name:i,endpoint:`${e.protocol}//${i}${e.pathname===`/`?``:e.pathname}${e.search}`}}catch{return{name:e.label||t,endpoint:t}}}function Ke(e){return e.label||Ge(e).name||e.id}var $=1024**3;function qe(e){if(e.lastSpeedtestStatus===void 0||e.lastSpeedtestAt===void 0)return;let t=e.lastSpeedtestDurationMs??0,n=e.lastSpeedtestBytes??0,r=t>0?n/(t/1e3):void 0;return{poolId:e.id,status:e.lastSpeedtestStatus,bytes:n,durationMs:t,...r===void 0?{}:{bytesPerSecond:r,megabitsPerSecond:r*8/1e6},...e.lastSpeedtestError?{errorMessage:e.lastSpeedtestError}:{},measuredAt:e.lastSpeedtestAt}}function Je(e,t){if(!e)return t;if(!t)return e;let n=e.measuredAt?new Date(e.measuredAt).getTime():0;return(t.measuredAt?new Date(t.measuredAt).getTime():0)>=n?t:e}var Ye=[{value:String(fe),label:`1 MB`},{value:String(me),label:`5 MB`},{value:`50000000`,label:`50 MB`},{value:String(pe),label:`100 MB`}];function Xe({pool:e,onClose:t,actionsRef:n}){let r=xe(),i=Ee(),a=De(),[u,d]=(0,U.useState)(e.label??``),[f,p]=(0,U.useState)(e.family??``),[m,h]=(0,U.useState)(e.endpoint??``),[g,_]=(0,U.useState)(String(e.maxInflight??10)),[v,y]=(0,U.useState)(String(e.weight??100)),[b,ee]=(0,U.useState)(e.quotaBytes?String(Math.round(e.quotaBytes/$*1e3)/1e3):``),[x,S]=(0,U.useState)(null),[C,w]=(0,U.useState)(!1),te=m.trim()===e.endpoint,T=async()=>{w(!0),S(null);try{if(te){let t=await a.mutateAsync(e.id),n=t.status===`healthy`||t.status===`reachable`;S({ok:n,message:t.status===`healthy`?`Connected in ${t.latencyMs??0}ms`:t.errorMessage??`Connection failed`});return}let t=[{kind:e.kind,endpoint:m.trim(),...e.family===null||e.family===void 0?{}:{family:e.family}}],[n]=await i.mutateAsync({providerId:He,targets:t}),r=n?.result;if(!r){S({ok:!1,message:`Probe returned no result`});return}let o=r.status===`allowed`||r.status===`throttled`;S({ok:o,message:r.reason??(r.status===`allowed`?`Reachable${r.latencyMs===void 0?``:` in ${r.latencyMs}ms`}`:r.status===`throttled`?`Reachable; rate limit spent`:`Probe could not complete`)})}catch(e){S({ok:!1,message:j(e,`Connection failed`)})}finally{w(!1)}},E=Le(b),D=async()=>{await r.mutateAsync({poolId:e.id,request:{...u.trim()===e.label?{}:{label:u.trim()||void 0},...f.trim()===(e.family??``)?{}:{family:f.trim()||null},...m.trim()!==e.endpoint&&m.trim()!==``?{endpoint:m.trim()}:{},...Number(g)===e.maxInflight?{}:{maxInflight:Number(g)},...Number(v)===e.weight?{}:{weight:Number(v)},...E===(e.quotaBytes??null)?{}:{quotaBytes:E}}}),l.success(`Proxy updated`),t()};return(0,U.useEffect)(()=>{n?.((0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(c,{variant:`secondary`,size:`sm`,onClick:t,children:`Cancel`}),(0,W.jsx)(c,{variant:`primary`,size:`sm`,disabled:r.isPending||!m.trim(),onClick:()=>void D(),children:`Save`})]}))}),(0,W.jsxs)(se,{gap:`12px`,children:[(0,W.jsx)(`div`,{children:(0,W.jsx)(z,{label:`Name`,value:u,onChange:e=>d(e.target.value)})}),(0,W.jsx)(`div`,{children:(0,W.jsx)(z,{label:`Family`,value:f,placeholder:`e.g. residential-id`,onChange:e=>p(e.target.value)})}),(0,W.jsx)(`div`,{children:(0,W.jsx)(z,{label:`Endpoint`,value:m,onChange:e=>h(e.target.value),className:`font-mono tabular-nums`})}),(0,W.jsxs)(`div`,{className:`grid grid-cols-2 gap-5`,children:[(0,W.jsx)(`div`,{children:(0,W.jsx)(z,{label:`Max concurrent`,type:`number`,min:1,value:g,onChange:e=>_(e.target.value)})}),(0,W.jsx)(`div`,{children:(0,W.jsx)(z,{label:`Weight`,type:`number`,min:1,value:v,onChange:e=>y(e.target.value)})})]}),(0,W.jsxs)(`div`,{children:[(0,W.jsx)(z,{label:`Bandwidth quota (GB, blank = unmetered)`,type:`number`,min:.001,step:`0.1`,value:b,onChange:e=>ee(e.target.value)}),(0,W.jsx)(`div`,{className:`text-micro text-text-tertiary mt-2`,children:E===null?`No quota — the bar shows a running total only.`:`Bar turns orange at 80% and red once ${L(E)} is exceeded.`})]}),x&&(0,W.jsx)(`div`,{className:`rounded-inset px-6 py-4 text-badge font-semibold ${x.ok?`bg-green-soft text-green`:`bg-red-soft text-red`}`,children:x.message}),(0,W.jsx)(`div`,{children:(0,W.jsx)(c,{variant:`secondary`,size:`sm`,disabled:C,icon:C?(0,W.jsx)(s,{size:13,className:`animate-spin`}):(0,W.jsx)(o,{size:13}),onClick:()=>void T(),children:C?`Testing…`:`Test connection`})})]})}function Ze({endpoint:e,chip:t,onChipChange:n}){return(0,W.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,role:`group`,"aria-label":`Scheme for the first endpoint`,children:[(0,W.jsx)(`span`,{className:`text-badge text-text-secondary`,children:`Scheme`}),q.map(r=>{let i=t===r;return(0,W.jsxs)(c,{type:`button`,variant:i?`primary`:`secondary`,size:`sm`,disabled:e===void 0,"aria-pressed":i,"data-scheme":r,onClick:()=>n(i?null:r),className:`font-mono`,children:[r,`://`]},r)}),t!==null&&(0,W.jsxs)(`span`,{className:`text-badge text-text-tertiary`,children:[`→ `,Fe(e??``,t)]})]})}function Qe({onClose:e,actionsRef:t,onProbeResult:n,onHealthResult:r}){let i=ve(),a=be(),o=Ee(),[s,u]=(0,U.useState)(``),[d,f]=(0,U.useState)(``),[p,m]=(0,U.useState)(``),[h,g]=(0,U.useState)(null),[_,v]=(0,U.useState)([]),[y,b]=(0,U.useState)({}),[ee,x]=(0,U.useState)({}),[S,C]=(0,U.useState)(!1),[w,te]=(0,U.useState)(null),T=s.split(`
|
|
2
2
|
`).map(e=>e.trim()).filter(Boolean),E=Y(T),D=(0,U.useMemo)(()=>w===null||E===void 0?T:T.map((e,t)=>e===E&&t===0?Fe(e,w):e),[T,w,E]),O=T.length>100,k=Le(p),A=(0,U.useMemo)(()=>D.map(e=>({kind:X(e),endpoint:e})),[D]),M=async()=>{try{let e=await navigator.clipboard.readText();e&&u(t=>t?`${t}\n${e}`:e)}catch{l.error(`Paste failed`,`Clipboard access denied`)}},N=async()=>{if(A.length!==0){v([`Testing ${A.length} proxy target(s)…`]);try{let e=await a.mutateAsync(A),t=e.map(e=>{let t=e.result.status===`healthy`||e.result.status===`reachable`,n=e.result.latencyMs===void 0?``:` · ${e.result.latencyMs}ms`,r=e.result.egressIp?` · ${e.result.egressIp}`:``,i=t?``:` · ${e.result.errorMessage??e.result.status}`;return`${t?`OK `:`FAIL`} ${e.endpoint}${n}${r}${i}`}),n=e.filter(e=>e.result.status===`healthy`||e.result.status===`reachable`).length;x(t=>{let n={...t};for(let t of e)n[t.endpoint]=t.result;return n}),v([`${n}/${e.length} reachable`,...t]),n===e.length?l.success(`All ${e.length} proxies reachable`):l.error(`${e.length-n} of ${e.length} proxies failed`)}catch(e){v([`Test failed: ${j(e,`batch probe failed`)}`]),l.error(`Test failed`,j(e,`batch probe failed`))}}},P=async()=>{if(A.length!==0){v([`Testing ${A.length} proxy target(s) against OpenCode…`]);try{let e=await o.mutateAsync({providerId:He,targets:A}),t=e.map(e=>{let{status:t,latencyMs:n,reason:r}=e.result,i=n===void 0?``:` · ${n}ms`,a=r===void 0?``:` · ${r}`;return`${t===`allowed`?`OK `:t===`blocked`?`BLOCK`:`FAIL`} ${e.endpoint}${i}${a}`});b(t=>{let n={...t};for(let t of e)n[t.endpoint]=t.result;return n});let n=e.filter(e=>e.result.status===`allowed`).length,r=e.filter(e=>e.result.status===`blocked`).length;v([`${n}/${e.length} allowed · ${r} blocked`,...t]),r===0&&n===e.length?l.success(`OpenCode accepted all ${e.length} proxies`):l.error(`OpenCode: ${n} allowed · ${r} blocked`)}catch(e){v([`Test failed: ${j(e,`provider probe failed`)}`]),l.error(`Test failed`,j(e,`provider probe failed`))}}};return(0,U.useEffect)(()=>{t?.((0,W.jsxs)(W.Fragment,{children:[(0,W.jsx)(c,{variant:`secondary`,type:`button`,onClick:e,children:`Cancel`}),(0,W.jsx)(c,{variant:`primary`,type:`submit`,form:`add-proxy-form`,disabled:S||T.length===0,children:S?`Adding…`:`Add ${T.length} Prox${T.length===1?`y`:`ies`}`})]}))},[t,S,T.length,e]),(0,W.jsxs)(`form`,{id:`add-proxy-form`,onSubmit:async t=>{if(t.preventDefault(),T.length!==0){g(null),C(!0);try{let t=k===null?new Map:Z(k,d,D.length),a=Array(T.length),o=0,s=async()=>{for(;o<T.length;){let e=o++,s=D[e];try{let o=await i.mutateAsync({kind:X(s),endpoint:s,...t.has(e)?{quotaBytes:t.get(e)}:{},...d.trim()===``?{}:{family:d.trim()}}),c=y[s],l=ee[s];o?.id&&(l!==void 0&&r?.(o.id,l),c!==void 0&&n?.(o.id,c)),a[e]={ok:!0}}catch(t){a[e]={ok:!1,error:j(t,`Proxy pool creation failed`)}}}};await Promise.all(Array.from({length:Math.min(Re,T.length)},()=>s()));let c=[],f=0;for(let[e,t]of a.entries())t.ok?f++:c.length<3&&c.push(`${T[e].slice(0,48)}…: ${t.error}`);let p=T.length-f,m=a.find(e=>!e.ok)?.error;f>0&&l.success(`Added ${f} proxy pool(s)`,p?`${p} failed: ${m??`see the import details`}`:void 0),p>0&&f===0&&l.error(`Failed to create pool`,m??`See the import details`),p>0&&g(c.join(`
|
|
3
3
|
`)),f>0&&(u(``),e())}finally{C(!1)}}},className:`flex flex-col gap-4`,children:[(0,W.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,W.jsx)(`label`,{htmlFor:`proxy-endpoints`,className:`text-caption font-semibold text-text-primary`,children:`Proxy endpoints`}),(0,W.jsx)(c,{variant:`secondary`,size:`sm`,type:`button`,onClick:M,children:`Paste`})]}),(0,W.jsx)(`textarea`,{id:`proxy-endpoints`,value:s,onChange:e=>u(e.target.value),placeholder:`http://proxy.example:8080
|
|
4
4
|
https://proxy.example:8443
|