@bitkyc08/opencodex 2.53.0-preview.20260913 → 2.54.0-preview.20260914
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/gui/dist/assets/{index-D7ynYo2K.js → index-B4VYfZcY.js} +2 -2
- package/gui/dist/index.html +1 -1
- package/package.json +1 -1
- package/src/adapters/devin.ts +39 -7
- package/src/cli/capabilities.ts +4 -2
- package/src/cli/catalog.ts +39 -10
- package/src/cli/dispatch.ts +19 -64
- package/src/cli/doctor.ts +1 -1
- package/src/cli/internal-command.ts +44 -0
- package/src/cli/registry.ts +9 -7
- package/src/cli/restart-scope.ts +184 -0
- package/src/codex/app-server-processes.ts +20 -5
- package/src/codex/app-server-restart-service.ts +29 -0
- package/src/codex/catalog/provider-fetch.ts +13 -5
- package/src/codex/catalog/sync.ts +12 -3
- package/src/codex/desktop-app/darwin.ts +268 -0
- package/src/codex/desktop-app/handoff.ts +303 -0
- package/src/codex/desktop-app/linux.ts +388 -0
- package/src/codex/desktop-app/lock.ts +226 -0
- package/src/codex/desktop-app/types.ts +141 -0
- package/src/codex/desktop-app/windows.ts +239 -0
- package/src/codex/desktop-app-restart.ts +264 -279
- package/src/codex/inject.ts +83 -21
- package/src/codex/sync.ts +16 -22
- package/src/generated/compatibility-version.json +58 -22
- package/src/lib/codex-restart-contract.ts +31 -0
- package/src/providers/registry.ts +13 -12
- package/src/server/responses/core.ts +62 -4
- package/src/server/responses/encrypted-payload.ts +161 -0
- package/src/server/responses.ts +1 -1
- package/src/types/provider.ts +6 -5
- package/src/web-search/index.ts +14 -67
- package/src/web-search/passthrough-bridge.ts +256 -32
- package/src/web-search/sidecar-providers.ts +76 -0
|
@@ -78,7 +78,7 @@ Değişiklikler yeni oturumlara uygulanır.`,"dash.multiAgent":`Alt Ajan`,"model
|
|
|
78
78
|
|
|
79
79
|
`))&&(async()=>{u(null),g(typeof r?.pid==`number`?r.pid:null),c(`draining`);try{if(!(await fetch(`${e}/api/system/restart`,{method:`POST`})).ok)throw Error(`restart_failed`)}catch{c(`error`),g(null),u(n(`dash.mem.restartFailed`))}})()};if(a&&!r&&s===`idle`)return(0,Y.jsxs)(`div`,{className:`panel`,style:{marginBottom:24},children:[(0,Y.jsxs)(`div`,{className:`font-semibold`,style:{display:`flex`,alignItems:`center`,gap:8},children:[(0,Y.jsx)(oe,{width:16,height:16,"aria-hidden":`true`}),n(`dash.mem.title`)]}),(0,Y.jsx)(`div`,{className:`muted text-control`,style:{marginTop:8},children:n(`dash.mem.unavailable`)})]});let y=r?.watchdog?lr(r.watchdog.samples):null,b=r?r.observedBytes??r.watchdog?.observedBytes??sr(r):null,x=r?cr(r):null,S=(()=>{let e=r?.watchdog?.warnThresholdBytes;if(y===null||y<=0||b===null||!e)return;let t=e-b;if(t<=0)return`danger`;let n=t/y;if(n<=1)return`danger`;if(n<=8)return`warn`})(),C=r?.responseState,w=r?.activeTurnCount,T=s===`draining`||s===`reconnecting`;return(0,Y.jsxs)(`div`,{className:`panel`,style:{marginBottom:24},children:[(0,Y.jsxs)(`div`,{className:`mem-head`,children:[(0,Y.jsxs)(`div`,{className:`font-semibold mem-head-title`,children:[(0,Y.jsx)(oe,{width:16,height:16,"aria-hidden":`true`}),n(`dash.mem.title`)]}),p&&(0,Y.jsxs)(`div`,{className:`mem-head-actions`,children:[(0,Y.jsxs)(`span`,{className:`mem-inflight`,children:[(0,Y.jsx)(`span`,{className:`mem-inflight-label`,children:n(`dash.mem.inFlight`)}),(0,Y.jsx)(`span`,{className:`mem-inflight-value mono`,children:typeof w==`number`?ir(t).format(w):`—`})]}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:T,onClick:v,children:n(`dash.mem.restart`)})]})]}),(0,Y.jsx)(dr,{observedBytes:b,thresholdBytes:r?.watchdog?.warnThresholdBytes??null,metric:x,locale:t,t:n}),(0,Y.jsxs)(`div`,{className:`stat-row mem-stats`,children:[(0,Y.jsx)(ur,{label:n(`dash.mem.rss`),value:r?ar(r.rss,t):`—`}),(0,Y.jsx)(ur,{label:n(`dash.mem.jsHeap`),value:r?ar(r.heapUsed,t):`—`,sub:r?n(`dash.mem.jsHeapArena`,{total:ar(r.heapTotal,t)}):void 0}),(0,Y.jsx)(ur,{label:n(`dash.mem.jscHeap`),value:r?.jscHeap?ar(r.jscHeap.heapSize,t):`—`}),(0,Y.jsx)(ur,{label:n(`dash.mem.growth`),value:y===null?`—`:`${y>=0?`+`:`−`}${ar(Math.abs(y),t)}${n(`dash.mem.perHour`)}`,tone:S})]}),(0,Y.jsxs)(`details`,{style:{marginTop:10},children:[(0,Y.jsx)(`summary`,{className:`muted text-label`,style:{cursor:`pointer`,padding:`2px 2px`},children:n(`dash.mem.details`)}),(0,Y.jsx)(`div`,{className:`muted text-control`,style:{margin:`8px 0 0`},children:n(`dash.mem.hint`)}),(0,Y.jsx)(`div`,{className:`muted text-label`,style:{margin:`14px 0 6px`},children:n(`dash.mem.runtime`)}),(0,Y.jsxs)(`div`,{className:`stat-row`,children:[(0,Y.jsx)(ur,{label:n(`dash.mem.observed`),value:b===null?`—`:`${ar(b,t)} (${x})`}),(0,Y.jsx)(ur,{label:n(`dash.mem.external`),value:r?.external===void 0?`—`:ar(r.external,t)}),(0,Y.jsx)(ur,{label:n(`dash.mem.arrayBuffers`),value:r?.arrayBuffers===void 0?`—`:ar(r.arrayBuffers,t)})]}),(0,Y.jsx)(`div`,{className:`muted text-label`,style:{margin:`14px 0 6px`},children:n(`dash.mem.store`)}),(0,Y.jsx)(`div`,{className:`muted text-control`,style:{marginBottom:10},children:n(`dash.mem.storeHint`)}),(0,Y.jsxs)(`div`,{className:`stat-row`,children:[(0,Y.jsx)(ur,{label:n(`dash.mem.storeEntries`),value:C?ir(t).format(C.count):`—`}),(0,Y.jsx)(ur,{label:n(`dash.mem.storeTotal`),value:C?ar(C.totalBytes,t):`—`}),(0,Y.jsx)(ur,{label:n(`dash.mem.storeLargest`),value:C?ar(C.largestBytes,t):`—`}),(0,Y.jsx)(ur,{label:n(`dash.mem.storeOldest`),value:C?C.count===0?`—`:or(C.oldestAgeMs,t):`—`})]}),r?.watchdog&&(0,Y.jsxs)(`div`,{className:`stat-row`,style:{marginTop:16},children:[(0,Y.jsx)(ur,{label:n(`dash.mem.threshold`),value:ar(r.watchdog.warnThresholdBytes,t)}),(0,Y.jsx)(ur,{label:n(`dash.mem.lastWarn`),value:r.watchdog.lastWarnAt?new Date(r.watchdog.lastWarnAt).toLocaleString(t):n(`dash.mem.never`)})]})]}),p&&(0,Y.jsxs)(`div`,{className:`mem-status`,"aria-live":`polite`,children:[s===`draining`&&(0,Y.jsx)(`span`,{className:`muted text-control`,children:n(`dash.mem.draining`,{count:typeof w==`number`?w:0})}),s===`reconnecting`&&(0,Y.jsx)(`span`,{className:`muted text-control`,children:n(`dash.mem.reconnecting`)}),s===`error`&&l&&(0,Y.jsx)(`span`,{className:`text-control`,style:{color:`var(--danger, #c44)`},children:l}),d&&s===`idle`&&(0,Y.jsx)(`span`,{className:`muted text-control`,children:n(`dash.mem.restartNoSupervisor`)})]})]})}function gr({apiBase:e,d:t}){let{t:n,maMode:r,maModeResolved:i,effortCapHelpTriggerRef:a,effortCapHelpOpen:o,setEffortCapHelpOpen:s,effortCap:c,subagentEffortCap:l,effortCapSaving:u,setEffortCap:d,setSubagentEffortCap:f,setEffortCapSaving:p}=t;return!i||r===`v1`?null:(0,Y.jsx)(`div`,{className:`panel dash-effort-panel`,children:(0,Y.jsxs)(`div`,{className:`injection-head`,children:[(0,Y.jsxs)(`span`,{className:`injection-label`,style:{display:`inline-flex`,alignItems:`center`,gap:6},children:[n(`dash.effortCapLabel`),(0,Y.jsx)(`button`,{ref:a,type:`button`,className:`btn btn-ghost btn-sm`,style:{width:22,height:22,minWidth:22,padding:0,borderRadius:`var(--radius-pill)`,color:`var(--muted)`},onClick:()=>s(e=>!e),"aria-label":n(`dash.effortCapLabel`),"aria-expanded":o,"aria-haspopup":`dialog`,"aria-controls":`effort-cap-help-dialog`,children:(0,Y.jsx)(ve,{width:13,height:13,"aria-hidden":`true`})})]}),(0,Y.jsxs)(`div`,{className:`dash-effort-controls`,children:[(0,Y.jsx)(kt,{value:c,options:[{value:``,label:n(`dash.effortCapNone`)},...qt.map(e=>({value:e,label:e}))],onChange:async t=>{if(!u){p(!0);try{let n=await Kt(await fetch(`${e}/api/effort-caps`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({effortCap:t||null})}));d(n.effortCap??``),f(n.subagentEffortCap??``)}catch{}finally{p(!1)}}},disabled:u,label:n(`dash.effortCapLabel`),align:`right`}),(0,Y.jsx)(kt,{value:l,options:[{value:``,label:n(`dash.effortCapNone`)},...qt.map(e=>({value:e,label:e}))],onChange:async t=>{if(!u){p(!0);try{let n=await Kt(await fetch(`${e}/api/effort-caps`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({subagentEffortCap:t||null})}));d(n.effortCap??``),f(n.subagentEffortCap??``)}catch{}finally{p(!1)}}},disabled:u,label:n(`dash.subagentEffortCapLabel`),align:`right`})]})]})})}function _r({d:e}){let{t,injectionModel:n,injectionEffort:r,injectionEfforts:i,injectionAvailable:a,injectionSaving:o,saveInjection:s}=e;return(0,Y.jsxs)(`div`,{className:`panel dash-delegation-summary`,children:[(0,Y.jsx)(`div`,{className:`font-semibold`,children:t(`dash.injectionLabel`)}),(0,Y.jsxs)(`div`,{className:`dash-delegation-controls`,children:[(0,Y.jsx)(kt,{value:n,options:[{value:``,label:t(`dash.injectionNone`)},...a.map(e=>({value:e.namespaced,label:Bn(`${e.provider}/${e.model}`,t)}))],onChange:e=>{s({model:e||null,effort:r||null})},disabled:o,label:t(`dash.injectionLabel`),align:`right`}),n&&i.length>0&&(0,Y.jsx)(kt,{value:r,options:[{value:``,label:t(`dash.injectionEffortNone`)},...i.map(e=>({value:e,label:e}))],onChange:e=>{s({model:n||null,effort:e||null})},disabled:o,label:t(`dash.injectionEffortLabel`),align:`right`}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>ht(`#subagents`),children:t(`dash.injectionManage`)})]})]})}function vr({d:e}){let{t,runSync:n,syncing:r,settingsSaving:i,updateTriggerRef:a,openUpdateDialog:o,updateLoading:s,updateOpen:c,syncResult:l,syncError:u,updateJob:d,reconnecting:f,clearSyncFeedback:p}=e,m=!!l&&(!!l.warning||!!l.nativeSubagentDefaultsWarning||!!l.staleAppServerHint),[h,g]=(0,_.useState)(!1),v=(0,_.useRef)(null);(0,_.useEffect)(()=>(v.current&&=(clearTimeout(v.current),null),(l||u)&&!m&&(v.current=setTimeout(()=>{v.current=null,g(!0),p()},u?8e3:6e3)),()=>{v.current&&clearTimeout(v.current)}),[l,u,m,p]);let y=()=>{g(!1),n()},b=()=>{g(!0),p()};return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{className:`panel maintenance-panel`,children:[(0,Y.jsxs)(`div`,{className:`dash-sync-summary`,children:[(0,Y.jsxs)(`div`,{className:`dash-sync-copy`,children:[(0,Y.jsx)(`div`,{className:`font-semibold`,children:t(`dash.syncModels`)}),(0,Y.jsx)(`div`,{className:`muted text-control dash-sync-hint`,children:t(`dash.syncModelsHint`)})]}),(0,Y.jsxs)(`div`,{className:`maintenance-actions`,children:[(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:y,disabled:r||i,children:[(0,Y.jsx)(de,{className:r?`spin-icon`:void 0}),` `,t(r?`dash.syncing`:`dash.syncRun`)]}),(0,Y.jsx)(`button`,{ref:a,type:`button`,className:`maintenance-update-anchor`,onClick:o,disabled:s,"aria-haspopup":`dialog`,"aria-controls":`dashboard-update-dialog`,"aria-expanded":c,"aria-label":t(`dash.checkUpdate`),tabIndex:-1})]})]}),d&&(0,Y.jsxs)(`div`,{className:`notice ${d.status===`failed`?`notice-err`:`notice-ok`} maintenance-notice`,role:`status`,children:[d.status===`failed`?(0,Y.jsx)(_e,{}):(0,Y.jsx)(de,{}),(0,Y.jsxs)(`span`,{children:[Xt(d.status,t),d.latestVersion?` ${t(`dash.updateVersionTransition`,{currentVersion:d.currentVersion,latestVersion:d.latestVersion})}`:``,f?` ${t(`dash.updateReconnecting`)}`:``,d.error?` ${d.error}`:``]})]})]}),!h&&l&&(0,Y.jsxs)(`div`,{className:`action-toast notice ${m?`notice-warn`:`notice-ok`}`,role:`status`,"aria-live":`polite`,children:[m?(0,Y.jsx)(_e,{}):(0,Y.jsx)(ce,{}),(0,Y.jsxs)(`span`,{children:[t(`dash.syncOk`,{count:l.added}),l.warning?` ${l.warning}`:``,l.nativeSubagentDefaultsWarning?` ${l.nativeSubagentDefaultsWarning}`:``,l.staleAppServerHint?(0,Y.jsxs)(Y.Fragment,{children:[` `,(0,Y.jsx)(ft,{k:`dash.syncStaleHint`,cmd:`ocx sync --restart-codex`})]}):null]}),(0,Y.jsx)(`button`,{type:`button`,className:`action-toast-dismiss`,onClick:b,"aria-label":t(`api.dismiss`),children:(0,Y.jsx)(le,{width:13,height:13,"aria-hidden":`true`})})]}),!h&&u&&(0,Y.jsxs)(`div`,{className:`action-toast notice notice-err`,role:`status`,"aria-live":`polite`,children:[(0,Y.jsx)(_e,{}),(0,Y.jsx)(`span`,{children:t(`dash.syncFailed`,{error:u})}),(0,Y.jsx)(`button`,{type:`button`,className:`action-toast-dismiss`,onClick:b,"aria-label":t(`api.dismiss`),children:(0,Y.jsx)(le,{width:13,height:13,"aria-hidden":`true`})})]})]})}function yr({t:e,open:t,triggerRef:n,onClose:r,maxValue:i,maxInvalid:a,timeoutValue:o,timeoutInvalid:s,disabled:c,setMaxDraft:l,setMaxInvalid:u,setTimeoutDraft:d,setTimeoutInvalid:f,commitMaxDescriptions:p,commitTimeout:m}){let h=(0,_.useRef)(null),g=(0,_.useRef)(null),[v,y]=(0,_.useState)(),b=(0,_.useCallback)(()=>{n.current&&y(Et(n.current.getBoundingClientRect(),{align:`right`,placement:`below`,menuHeight:h.current?.offsetHeight??180}))},[n]);return(0,_.useLayoutEffect)(()=>{if(!t)return;b();let e=()=>b();return window.addEventListener(`resize`,e),window.addEventListener(`scroll`,e,!0),()=>{window.removeEventListener(`resize`,e),window.removeEventListener(`scroll`,e,!0)}},[t,b,a,s]),(0,_.useEffect)(()=>{if(!t)return;let e=e=>{let t=e.target;if(h.current?.contains(t)||n.current?.contains(t))return;let i=document.activeElement;i&&h.current?.contains(i)&&i.blur(),r()};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[t,r,n]),(0,_.useEffect)(()=>{if(!t)return;let e=e=>{e.key===`Escape`&&(e.preventDefault(),r(),n.current?.focus())};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[t,r,n]),(0,_.useEffect)(()=>{t&&g.current?.focus()},[t]),t?(0,Y.jsxs)(`div`,{ref:h,id:`dash-vision-advanced-popover`,className:`dash-vision-advanced-popover`,role:`dialog`,"aria-modal":`false`,"aria-label":e(`dash.visionAdvancedPopover`),style:{...v,zIndex:60},children:[(0,Y.jsx)(`div`,{className:`dash-vision-advanced-popover-title`,children:e(`dash.visionAdvancedPopover`)}),(0,Y.jsxs)(`label`,{className:`dash-vision-number`,children:[(0,Y.jsx)(`span`,{className:`muted setting-hint`,id:`dash-vision-max-label`,children:e(`dash.visionMaxDescriptions`)}),(0,Y.jsx)(`span`,{className:`codex-auto-switch-input-wrap`,children:(0,Y.jsx)(`input`,{ref:g,className:`input mono codex-auto-switch-input`,type:`number`,min:1,step:1,inputMode:`numeric`,value:i,disabled:c,"aria-invalid":a||void 0,"aria-label":e(`dash.visionMaxDescriptions`),"aria-describedby":a?`dash-vision-max-error dash-vision-max-label`:`dash-vision-max-label`,onChange:e=>{u(!1),l(e.target.value)},onBlur:e=>p(e.currentTarget.value),onKeyDown:e=>{e.nativeEvent.isComposing||c||(e.key===`Enter`?(e.preventDefault(),p(e.currentTarget.value)):e.key===`Escape`&&(e.preventDefault(),l(null),u(!1)))}})}),a&&(0,Y.jsx)(`span`,{id:`dash-vision-max-error`,className:`muted setting-hint`,role:`alert`,children:e(`dash.visionMaxDescriptionsInvalid`)})]}),(0,Y.jsxs)(`label`,{className:`dash-vision-number`,children:[(0,Y.jsx)(`span`,{className:`muted setting-hint`,id:`dash-vision-timeout-label`,children:e(`dash.visionTimeout`)}),(0,Y.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,children:[(0,Y.jsx)(`input`,{className:`input mono codex-auto-switch-input`,type:`number`,min:an,max:rn,step:1e3,inputMode:`numeric`,value:o,disabled:c,"aria-invalid":s||void 0,"aria-label":e(`dash.visionTimeout`),"aria-describedby":s?`dash-vision-timeout-error dash-vision-timeout-label`:`dash-vision-timeout-label`,onChange:e=>{f(!1),d(e.target.value)},onBlur:e=>m(e.currentTarget.value),onKeyDown:e=>{e.nativeEvent.isComposing||c||(e.key===`Enter`?(e.preventDefault(),m(e.currentTarget.value)):e.key===`Escape`&&(e.preventDefault(),d(null),f(!1)))}}),(0,Y.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`ms`})]}),s&&(0,Y.jsx)(`span`,{id:`dash-vision-timeout-error`,className:`muted setting-hint`,role:`alert`,children:e(`dash.visionTimeoutInvalid`,{min:an,max:rn})})]})]}):null}function br({d:e}){let{t,settings:n,settingsSaving:r,syncing:i,toggleCodexAutoStart:a,toggleCodexDesktopAuthless:o,toggleCodexClientCompaction:s,sidecar:c,sidecarSaving:l,sidecarModels:u,visionModels:d,models:f,saveSidecar:p,shadowCall:m,shadowCallSaving:h,shadowCallHelpTriggerRef:g,shadowCallHelpOpen:v,setShadowCallHelpOpen:y,saveShadowCall:b}=e,x=c?.vision?.enabled!==!1,S=x?c?.vision?.model??`gpt-5.6-luna`:``,C=c?.vision?.reasoning??`low`,w=ln(f,S),T=dn(w,C),E=String(c?.vision?.maxDescriptionsPerTurn??8),D=String(c?.vision?.timeoutMs??nn),[O,k]=(0,_.useState)(null),[A,j]=(0,_.useState)(null),[M,N]=(0,_.useState)(!1),[P,F]=(0,_.useState)(!1),[I,L]=(0,_.useState)(!1),R=(0,_.useRef)(null),z=O??E,B=A??D,V=(e=z)=>{let t=on(e);if(t===void 0){k(e),N(!0);return}N(!1),k(null),t!==(c?.vision?.maxDescriptionsPerTurn??8)&&p(en(t))},H=(e=B)=>{let t=sn(e);if(t===void 0){j(e),F(!0);return}F(!1),j(null),t!==(c?.vision?.timeoutMs??nn)&&p(tn(t))};return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`div`,{className:`panel`,children:(0,Y.jsxs)(`div`,{className:`spread`,children:[(0,Y.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,Y.jsx)(`div`,{className:`font-semibold`,children:t(`dash.codexAutoStart`)}),(0,Y.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.codexAutoStartHint`)})]}),(0,Y.jsx)(`button`,{type:`button`,className:`switch ${n?.codexAutoStart??!0?`on`:``}`,onClick:a,disabled:!n||r||i,"aria-label":t(`dash.codexAutoStart`),"aria-pressed":n?.codexAutoStart??!0,children:(0,Y.jsx)(`span`,{className:`knob`})})]})}),(0,Y.jsx)(`div`,{className:`panel`,children:(0,Y.jsxs)(`div`,{className:`spread`,children:[(0,Y.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,Y.jsx)(`div`,{className:`font-semibold`,children:t(`dash.codexDesktopAuthless`)}),(0,Y.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.codexDesktopAuthlessHint`)}),n?.catalogRefreshPending&&(0,Y.jsx)(`div`,{className:`muted setting-hint`,role:`status`,children:t(`codexAuth.catalogRefreshPending`)})]}),(0,Y.jsx)(`button`,{type:`button`,className:`switch ${n?.codexDesktopAuthless??!1?`on`:``}`,onClick:o,disabled:!n||r||i,"aria-label":t(`dash.codexDesktopAuthless`),"aria-pressed":n?.codexDesktopAuthless??!1,children:(0,Y.jsx)(`span`,{className:`knob`})})]})}),(0,Y.jsx)(`div`,{className:`panel`,children:(0,Y.jsxs)(`div`,{className:`spread`,children:[(0,Y.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,Y.jsx)(`div`,{className:`font-semibold`,children:t(`dash.codexClientCompaction`)}),(0,Y.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.codexClientCompactionHint`)}),n?.catalogRefreshPending&&(0,Y.jsx)(`div`,{className:`muted setting-hint`,role:`status`,children:t(`codexAuth.catalogRefreshPending`)})]}),(0,Y.jsx)(`button`,{type:`button`,className:`switch ${n?.codexClientCompaction??!1?`on`:``}`,onClick:s,disabled:!n||r||i,"aria-label":t(`dash.codexClientCompaction`),"aria-pressed":n?.codexClientCompaction??!1,children:(0,Y.jsx)(`span`,{className:`knob`})})]})}),(0,Y.jsxs)(`div`,{className:`dash-sidecar-grid`,children:[(0,Y.jsxs)(`div`,{className:`panel dash-delegation-summary dash-sidecar-row-card`,"aria-busy":!c||void 0,children:[(0,Y.jsxs)(`div`,{className:`dash-sidecar-copy`,children:[(0,Y.jsx)(`div`,{className:`font-semibold`,children:t(`dash.webSearchSidecar`)}),(0,Y.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.webSearchSidecarHint`)})]}),(0,Y.jsxs)(`div`,{className:`dash-delegation-controls`,children:[(0,Y.jsx)(`div`,{className:`dash-sidecar-select-row`,children:(0,Y.jsx)(kt,{value:c?.webSearch?.model??`gpt-5.6-luna`,options:u,onChange:e=>{p({webSearch:_n(f,u,e)})},disabled:!c||l,label:t(`dash.sidecarModel`),align:`right`})}),(0,Y.jsxs)(`div`,{className:`dash-sidecar-trailing-row`,title:t(`dash.webSearchStreamHint`),children:[(0,Y.jsx)(`span`,{className:`muted setting-hint dash-sidecar-toggle-label`,children:t(`dash.webSearchStream`)}),(0,Y.jsx)(`button`,{type:`button`,className:`switch ${c?.webSearch?.streamRoutedModelOutput?`on`:``}`,onClick:()=>{p({webSearch:{streamRoutedModelOutput:!c?.webSearch?.streamRoutedModelOutput}})},disabled:!c||l,"aria-label":t(`dash.webSearchStream`),"aria-pressed":c?.webSearch?.streamRoutedModelOutput===!0,children:(0,Y.jsx)(`span`,{className:`knob`})})]})]})]}),(0,Y.jsxs)(`div`,{className:`panel dash-delegation-summary dash-sidecar-row-card dash-vision-sidecar-card`,"aria-busy":!c||void 0,children:[(0,Y.jsxs)(`div`,{className:`dash-sidecar-copy`,children:[(0,Y.jsx)(`div`,{className:`font-semibold`,children:t(`dash.visionSidecar`)}),(0,Y.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.visionSidecarHint`)})]}),(0,Y.jsxs)(`div`,{className:`dash-delegation-controls`,children:[(0,Y.jsxs)(`div`,{className:`dash-sidecar-select-row`,children:[(0,Y.jsx)(kt,{value:S,options:[{value:``,label:t(`dash.visionOff`)},...d],onChange:e=>{if(e===``){p($t(!1));return}let t=dn(ln(f,e),T),n={vision:{model:e,backend:vn(f,d,e),reasoning:t}};x||(n.vision={...n.vision,enabled:!0}),p(n)},disabled:!c||l,label:t(`dash.sidecarModel`)}),(0,Y.jsx)(kt,{value:T,options:un(w,T).map(e=>({value:e,label:e})),onChange:e=>{p(Qt(e))},disabled:!x||!c||l,align:`right`,label:`${t(`dash.visionSidecar`)} — ${t(`dash.injectionEffortLabel`)}`})]}),(0,Y.jsx)(`div`,{className:`dash-sidecar-trailing-row`,children:(0,Y.jsxs)(`button`,{type:`button`,ref:R,className:`dash-vision-advanced-trigger`,onClick:()=>L(e=>!e),disabled:!x||!c||l,"aria-expanded":I,"aria-haspopup":`dialog`,"aria-controls":`dash-vision-advanced-popover`,children:[(0,Y.jsx)(`span`,{children:t(`dash.visionAdvanced`)}),(0,Y.jsx)(Ce,{width:12,height:12,"aria-hidden":`true`,style:{transform:I?`rotate(90deg)`:`none`,transition:`transform .12s`}})]})})]}),(0,gt.createPortal)((0,Y.jsx)(yr,{t,open:I,triggerRef:R,onClose:()=>L(!1),maxValue:z,maxInvalid:M,timeoutValue:B,timeoutInvalid:P,disabled:!x||!c||l,setMaxDraft:k,setMaxInvalid:N,setTimeoutDraft:j,setTimeoutInvalid:F,commitMaxDescriptions:V,commitTimeout:H}),document.body)]})]}),(0,Y.jsx)(`div`,{className:`panel`,"aria-busy":!m||void 0,children:(0,Y.jsxs)(`div`,{className:`spread`,style:{alignItems:`center`},children:[(0,Y.jsxs)(`div`,{className:`dash-shadow-label`,style:{display:`flex`,alignItems:`center`,gap:8},children:[(0,Y.jsx)(`span`,{className:`font-semibold`,children:t(`dash.shadowCallIntercept`)}),(0,Y.jsx)(`button`,{ref:g,type:`button`,className:`btn btn-ghost btn-sm`,style:{width:22,height:22,minWidth:22,padding:0,borderRadius:`var(--radius-pill)`,color:`var(--muted)`},onClick:()=>y(e=>!e),"aria-label":t(`dash.shadowCallIntercept`),"aria-expanded":v,"aria-haspopup":`dialog`,"aria-controls":`shadow-call-help-dialog`,children:(0,Y.jsx)(ve,{width:13,height:13,"aria-hidden":`true`})}),(0,Y.jsx)(`code`,{className:`muted text-caption`,children:`⚠ ${Vt(m?.sourceModels)}`})]}),(0,Y.jsxs)(`div`,{className:`setting-controls dash-shadow-controls`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`switch ${m?.enabled?`on`:``}`,onClick:()=>b({enabled:!m?.enabled}),disabled:!m||h,"aria-label":t(`dash.shadowCallIntercept`),"aria-pressed":m?.enabled??!1,children:(0,Y.jsx)(`span`,{className:`knob`})}),(0,Y.jsx)(kt,{value:m?.model??``,options:hn(f,m?.model,m?.sourceModels).map(e=>e.value===``?e:{...e,label:Bn(e.value,t)}),onChange:e=>{b({model:e})},disabled:!m||h||!m?.enabled,label:t(`dash.shadowCallModel`),align:`right`})]})]})})]})}function xr(e){return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(gr,{apiBase:e.apiBase,d:e}),(0,Y.jsxs)(`div`,{className:`dash-overview-tools`,children:[(0,Y.jsx)(_r,{apiBase:e.apiBase,d:e}),(0,Y.jsx)(vr,{d:e})]}),(0,Y.jsx)(br,{d:e}),(0,Y.jsx)(hr,{apiBase:e.apiBase})]})}function Sr(e){return(0,Y.jsxs)(`div`,{className:`dash-overview-stack`,children:[(0,Y.jsx)(Yn,{...e}),(0,Y.jsx)(xr,{...e})]})}function Cr({t:e,providers:t}){return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{className:`h-section`,children:[e(`dash.activeProviders`),` `,(0,Y.jsx)(`span`,{className:`count`,children:t.length})]}),t.length===0?(0,Y.jsx)(At,{title:(0,Y.jsx)(ft,{k:`dash.noProviders`,cmd:`ocx init`})}):(0,Y.jsx)(`div`,{className:`tbl-wrap`,children:(0,Y.jsxs)(`table`,{className:`tbl`,children:[(0,Y.jsx)(`thead`,{children:(0,Y.jsxs)(`tr`,{children:[(0,Y.jsx)(`th`,{children:e(`dash.col.name`)}),(0,Y.jsx)(`th`,{children:e(`dash.col.adapter`)}),(0,Y.jsx)(`th`,{children:e(`dash.col.baseUrl`)}),(0,Y.jsx)(`th`,{children:e(`dash.col.model`)})]})}),(0,Y.jsx)(`tbody`,{children:t.map(t=>(0,Y.jsxs)(`tr`,{children:[(0,Y.jsx)(`td`,{className:`font-semibold`,children:Ln(t.name,e)}),(0,Y.jsx)(`td`,{children:(0,Y.jsx)(`span`,{className:`chip`,children:t.adapter})}),(0,Y.jsx)(`td`,{className:`muted mono text-label`,children:t.baseUrl}),(0,Y.jsx)(`td`,{className:`muted`,children:t.defaultModel??`—`})]},t.name))})]})})]})}var wr=`__ocxCachedAt`;function Tr(e){try{let t=sessionStorage.getItem(e);if(!t)return null;let n=JSON.parse(t);return Er(n)?n.data:n}catch{return null}}function Er(e){return typeof e==`object`&&!!e&&typeof e[wr]==`number`&&`data`in e}function Dr(e){try{let t=sessionStorage.getItem(e);if(!t)return null;let n=JSON.parse(t);return Er(n)?{data:n.data,cachedAt:n[wr]}:{data:n,cachedAt:null}}catch{return null}}function Or(e,t){try{sessionStorage.setItem(e,JSON.stringify({[wr]:Date.now(),data:t}))}catch{}}function kr(e,t){try{sessionStorage.setItem(e,JSON.stringify(t))}catch{}}function Ar(e,t,n){if(!n)return{kind:`disabled`,data:void 0,error:void 0,showSkeleton:!1,refreshing:!1,showError:!1};let r=e.data!==void 0,i=!e.lastAttemptOk&&e.error!==void 0;return e.refreshing?r?{kind:`loading-with-stale-data`,data:e.data,error:e.error,showSkeleton:!1,refreshing:!0,showError:i}:{kind:i?`retrying-cold`:`cold`,data:void 0,error:i?e.error:void 0,showSkeleton:!0,refreshing:!0,showError:!1}:i?r?{kind:`failed-with-stale`,data:e.data,error:e.error,showSkeleton:!1,refreshing:!1,showError:!0}:{kind:`failed-cold`,data:void 0,error:e.error,showSkeleton:!1,refreshing:!1,showError:!0}:r?{kind:t(e.data)?`ready-empty`:`ready-populated`,data:e.data,error:void 0,showSkeleton:!1,refreshing:!1,showError:!1}:{kind:`cold`,data:void 0,error:void 0,showSkeleton:!0,refreshing:!1,showError:!1}}function jr(e,t,n,r){let{isEmpty:i,sessionCacheKey:a,...o}=r,s=(0,_.useMemo)(()=>a?Dr(a):null,[a]),c=K(e,t,(0,_.useCallback)(async e=>{let t=await n(e);return a&&Or(a,t),t},[n,a]),{...o,...a?{initialData:o.initialData??s?.data,initialDataCachedAt:o.initialDataCachedAt??s?.cachedAt??null}:{}});return{...c,state:Ar(c,i,r.enabled!==!1)}}function Mr(e){return e.routingKind===`custom-local`?`startup.riskDetailCustomLocal`:e.shimCoverage===`cli-only`?`startup.riskDetailWindowsShim`:`startup.riskDetail`}function Nr(e,t){return!t.mutationInFlight&&e.request===t.request&&e.mutation===t.mutation}function Pr(e,t){return{request:++e.current,mutation:t.current}}var Fr=2e3;function Ir(e){let t=e.status;return t!==`native`&&t!==`protected`&&t!==`at-risk`?null:t}function Lr(e){return e?e.stale&&e.status!==`error`:!1}function Rr(e,t){return!t||e!==null&&e!==`error`?e:t.status}var zr=3e4;function Br(e){return{multiAgentGuidanceEnabled:e.multiAgentGuidanceEnabled!==!1,syncCodexSubagentDefaults:e.syncCodexSubagentDefaults===!0,injectionModel:e.model??``,injectionEffort:e.effort??``}}function Vr(e,t){return t.aborted?!0:e instanceof Error&&e.name===`AbortError`}async function Hr(e,t){try{let n=await fetch(`${e}/api/startup-health`,{signal:t});if(!n.ok)throw Error(`startup health unavailable`);let r=await n.json(),i=Ir(r);if(!i)throw Error(`invalid startup health response`);return{status:i,stale:r.diagnosticStale===!0}}catch(e){if(Vr(e,t))throw e;return{status:`error`,stale:!1}}}async function Ur(e,t){try{return(await Lt(await fetch(`${e}/api/diagnostics/project-config`,{signal:t})))?.grouped??[]}catch{return[]}}async function Wr(e,t){return Kt(await fetch(`${e}/api/models`,{signal:t}))}async function Gr(e,t){return Kt(await fetch(`${e}/api/usage?range=30d`,{signal:t}))}async function Kr(e,t,n){let{request:r,mutation:i}=Pr(n.shadowCallRequestEpochRef,n.shadowCallMutationEpochRef),[a,o]=await Promise.all([fetch(`${e}/api/sidecar-settings`,{signal:t}),fetch(`${e}/api/shadow-call-settings`,{signal:t})]),s=await Kt(a),c;try{if(o.ok){let e=await o.json();Nr({request:r,mutation:i},{request:n.shadowCallRequestEpochRef.current,mutation:n.shadowCallMutationEpochRef.current,mutationInFlight:n.shadowCallMutationInFlightRef.current})&&(c=e)}else Nr({request:r,mutation:i},{request:n.shadowCallRequestEpochRef.current,mutation:n.shadowCallMutationEpochRef.current,mutationInFlight:n.shadowCallMutationInFlightRef.current})&&(c=null)}catch{Nr({request:r,mutation:i},{request:n.shadowCallRequestEpochRef.current,mutation:n.shadowCallMutationEpochRef.current,mutationInFlight:n.shadowCallMutationInFlightRef.current})&&(c=null)}return{sidecar:s,shadowCall:c}}async function qr(e,t,n){let{request:r,mutation:i}=Pr(n.settingsRequestEpochRef,n.settingsMutationEpochRef),a=await Kt(await fetch(`${e}/api/settings`,{signal:t})),o,s;return Nr({request:r,mutation:i},{request:n.settingsRequestEpochRef.current,mutation:n.settingsMutationEpochRef.current,mutationInFlight:n.settingsMutationInFlightRef.current})&&(o=a,s=a.startupHealth),{settings:o,startupHealthSeed:s}}async function Jr(e,t){try{let n=await fetch(`${e}/api/v2`,{signal:t});if(!n.ok)return{maMode:`default`};let r=await n.json(),i=Cn(r.multiAgentSurfaceAdvisory);return r.multiAgentMode===`v1`||r.multiAgentMode===`v2`?{maMode:r.multiAgentMode,advisory:i}:{maMode:`default`,advisory:i}}catch(e){if(Vr(e,t))throw e;return{maMode:`default`}}}async function Yr(e,t){let n=e=>({health:null,providers:[],error:!0,failure:e}),r=new AbortController,i=AbortSignal.any([t,r.signal]),a,o,s=new Promise(e=>{o=()=>e(`access`)}),c=e=>((e.status===401||e.status===403)&&((e.status===403||a===void 0)&&(a=e.status===403?`denied`:`auth`),o()),e);try{let r=[`/api/system/health`,`/api/providers`].map(t=>Promise.resolve().then(()=>fetch(`${e}${t}`,{signal:i})).then(c)),o=await Promise.race([Promise.allSettled(r),s]);if(t.throwIfAborted(),o===`access`)return n(a??`auth`);let[l,u]=o;if(l.status===`rejected`||u.status===`rejected`)return n(`unavailable`);let d=l.value,f=u.value;if(!d.ok||!f.ok)return n(`request`);try{let e=await Kt(d),t=await Kt(f);return!e||typeof e.status!=`string`||typeof e.version!=`string`||!Number.isFinite(e.uptime)||e.uptime<0||!Array.isArray(t)||t.some(e=>!e||typeof e.name!=`string`||typeof e.adapter!=`string`||typeof e.baseUrl!=`string`||typeof e.hasApiKey!=`boolean`||e.defaultModel!==void 0&&typeof e.defaultModel!=`string`)?n(`invalid`):{health:e,providers:t,error:!1}}catch(e){if(Vr(e,t))throw e;return n(`invalid`)}}finally{r.abort()}}async function Xr(e,t){let[n,r]=await Promise.all([fetch(`${e}/api/injection-model`,{signal:t}).catch(()=>null),fetch(`${e}/api/effort-caps`,{signal:t}).catch(()=>null)]),i;try{if(n?.ok){let e=await n.json();i={...Br(e),injectionEfforts:e.efforts??[],injectionAvailable:e.available??[]}}}catch{}let a;try{if(r?.ok){let e=await r.json();a={effortCap:e.effortCap??``,subagentEffortCap:e.subagentEffortCap??``}}}catch{}return{injection:i,effortCaps:a}}var Zr=`ocx.dash.controls.v1:`,Qr=`ocx.dash.overview.v1:`,$r=`ocx.dash.usage30d.v1:`,ei=`ocx.dash.startup.v1:`,ti=`ocx.dash.maMode.v1:`;function ni(e,t){switch(t.type){case`polled`:return e.beforeSave?e:{...e,settings:{...t.settings,catalogRefreshPending:e.settings?.catalogRefreshPending===!0||t.settings.catalogRefreshPending}};case`save-started`:return!e.settings||e.beforeSave?e:{beforeSave:e.settings,settings:{...e.settings,[t.key]:t.value}};case`save-succeeded`:return!e.settings||!e.beforeSave?e:{...e,settings:{...e.settings,[t.key]:t.settings[t.key],catalogRefreshPending:t.key===`codexDesktopAuthless`||t.key===`codexClientCompaction`||e.settings.catalogRefreshPending,startupHealth:t.settings.startupHealth??e.settings.startupHealth}};case`save-failed`:return e.beforeSave?{...e,settings:e.beforeSave}:e;case`save-finished`:return{...e,beforeSave:null};case`applied`:return e.settings?{...e,settings:{...e.settings,catalogRefreshPending:!1}}:e}}function ri(e){let t=new Map;for(let n of e){let e=t.get(n.provider);e?e.push(n):t.set(n.provider,[n])}return[...t.entries()].sort(([e],[t])=>e.localeCompare(t))}function ii(e){return`${Zr}${e}`}function ai(e,t=0){let{locale:n,t:r}=ut(),[i,a]=(0,_.useState)(Ut),[o,s]=(0,_.useState)(``),[c,l]=(0,_.useState)(new Set),u=(0,_.useMemo)(()=>Tr(ii(e)),[e]),d=(0,_.useMemo)(()=>Tr(`${Qr}${e}`),[e]),f=(0,_.useMemo)(()=>Tr(`${$r}${e}`),[e]),p=(0,_.useMemo)(()=>{let t=Tr(`${ei}${e}`);return t===`error`?null:t},[e]),m=(0,_.useMemo)(()=>Tr(`${ti}${e}`),[e]),[h,g]=(0,_.useState)(()=>d?.health??null),[v,y]=(0,_.useState)(()=>p),[b,x]=(0,_.useState)(()=>d?.providers??[]),[S,C]=(0,_.useState)([]),[w,T]=(0,_.useReducer)(ni,{settings:u?.settings??null,beforeSave:null}),{settings:E}=w,D=w.beforeSave!==null,[O,k]=(0,_.useState)(()=>u?.sidecar??null),[A,j]=(0,_.useState)(()=>u?.shadowCall??null),[M,N]=(0,_.useState)(()=>f),[P,F]=(0,_.useState)(!1),[I,L]=(0,_.useState)(!1),[R,z]=(0,_.useState)(!1),[B,V]=(0,_.useState)(!1),[H,U]=(0,_.useState)(()=>m??`default`),[W,G]=(0,_.useState)(!1),[q,J]=(0,_.useState)(null),[Y,X]=(0,_.useState)(null),[ee,te]=(0,_.useState)(null),[ne,Z]=(0,_.useState)(null),re=Y?.apiBase===e?Y.advisory:null,ie=ee===e,ae=ne?.apiBase===e?ne.mode:null,[oe,se]=(0,_.useState)(!1),[ce,le]=(0,_.useState)(!1),[ue,de]=(0,_.useState)(!1),[fe,pe]=(0,_.useState)(``),[me,he]=(0,_.useState)(``),[ge,_e]=(0,_.useState)([]),[ve,ye]=(0,_.useState)([]),[be,xe]=(0,_.useState)(!1),[Se,Ce]=(0,_.useState)(!0),[we,Te]=(0,_.useState)(!1),[Ee,De]=(0,_.useState)(``),[Oe,ke]=(0,_.useState)(``),[Ae,je]=(0,_.useState)(!1),[Me,Ne]=(0,_.useState)(null),[Pe,Fe]=(0,_.useState)(null),[Ie,Le]=(0,_.useState)([]),[Re,ze]=(0,_.useState)(!1),[Be,Ve]=(0,_.useState)(`latest`),[He,Ue]=(0,_.useState)(!0),[We,Ge]=(0,_.useState)(!1),Ke=(0,_.useRef)(0),qe=(0,_.useRef)(null),Je=(0,_.useRef)(0),Ye=(0,_.useRef)(0),Xe=(0,_.useRef)(0),Ze=(0,_.useRef)(!1),Qe=(0,_.useRef)(0),$e=(0,_.useRef)(0),et=(0,_.useRef)(!1),[tt,nt]=(0,_.useState)(null),[rt,it]=(0,_.useState)(null),[at,ot]=(0,_.useState)(null),[st,ct]=(0,_.useState)(!1),[lt,Q]=(0,_.useState)(!1),dt=(0,_.useRef)(null),ft=(0,_.useRef)(null),pt=(0,_.useRef)(null),ht=(0,_.useRef)(null),gt=xn(ce,dt),_t=xn(Re,ft),vt=xn(oe,pt),yt=xn(ue,ht);(0,_.useEffect)(()=>{let e=()=>a(Ut());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]),(0,_.useEffect)(()=>()=>{Je.current+=1,qe.current!==null&&(window.clearTimeout(qe.current),qe.current=null)},[]);let bt=(0,_.useRef)(p),xt=(0,_.useRef)(0),St=(0,_.useRef)({settingsRequestEpochRef:Ye,settingsMutationEpochRef:Xe,settingsMutationInFlightRef:Ze,shadowCallRequestEpochRef:Qe,shadowCallMutationEpochRef:$e,shadowCallMutationInFlightRef:et}).current,Ct=K(`dashboard-startup-health:${e}`,[e,t],t=>Hr(e,t),{pollMs:3e4}),wt=Lr(Ct.data),Tt=Ct.refresh;(0,_.useEffect)(()=>{if(!wt)return;let e=window.setTimeout(()=>{Tt()},Fr);return()=>window.clearTimeout(e)},[wt,Tt]);let Et=K(`dashboard-overview:${e}`,[e,t],t=>Yr(e,t),{pollMs:5e3}),Dt=Ar(Et,e=>e.health===null,!0),$=h!==null||Et.data!==void 0,Ot=K(`dashboard-ma-mode:${e}`,[e,t],t=>Jr(e,t),{pollMs:5e3}),kt=K(`dashboard-sidecars:${e}`,[e,t],async t=>{let n=xt.current;return{...await Kr(e,t,St),startupHealthGeneration:n}},{pollMs:5e3}),At=K(`dashboard-settings:${e}`,[e,t],async t=>{let n=xt.current;return{...await qr(e,t,St),startupHealthGeneration:n}},{pollMs:5e3}),jt=K(`dashboard-multi-agent:${e}`,[e,t],t=>Xr(e,t),{pollMs:5e3,enabled:$}),Mt=K(qn(e),[e,t],t=>Gr(e,t),{enabled:$,pollMs:6e4,deadlineMs:6e4}),Nt=K(`dashboard-diagnostics:${e}`,[e,t],t=>Ur(e,t),{pollMs:zr,enabled:$}),Pt=K(`dashboard-models:${e}`,[e,lt,t],t=>Wr(e,t),{enabled:$&&!lt});(0,_.useEffect)(()=>{if(Ct.data!==void 0){let t=Ct.data;xt.current+=1,y(t.status),bt.current=t.status,t.status!==`error`&&!t.stale&&kr(`${ei}${e}`,t.status)}},[Ct.data,e]),(0,_.useEffect)(()=>{let t=Et.data;t&&(t.health&&(g(t.health),x(t.providers),kr(`${Qr}${e}`,{health:t.health,providers:t.providers})),Q(t.error))},[Et.data,e]),(0,_.useEffect)(()=>{Ot.data!==void 0&&(U(Ot.data.maMode),X({advisory:Ot.data.advisory??null,apiBase:e}),kr(`${ti}${e}`,Ot.data.maMode))},[Ot.data,e]);let Ft=Ot.data!==void 0||m!==null;(0,_.useEffect)(()=>{let e=jt.data;e&&(e.injection&&(Ce(e.injection.multiAgentGuidanceEnabled),Te(e.injection.syncCodexSubagentDefaults),pe(e.injection.injectionModel),he(e.injection.injectionEffort),_e(e.injection.injectionEfforts),ye(e.injection.injectionAvailable)),e.effortCaps&&(De(e.effortCaps.effortCap),ke(e.effortCaps.subagentEffortCap)))},[jt.data]),(0,_.useEffect)(()=>{let t=kt.data;if(!t)return;k(t.sidecar),t.shadowCall!==void 0&&j(t.shadowCall);let n=Tr(ii(e))??{};kr(ii(e),{...n,sidecar:t.sidecar,...t.shadowCall===void 0?{}:{shadowCall:t.shadowCall}})},[kt.data,e]),(0,_.useEffect)(()=>{let t=At.data;if(t&&(t.settings!==void 0&&T({type:`polled`,settings:t.settings}),t.startupHealthSeed!==void 0&&t.startupHealthGeneration===xt.current)){let n=Rr(bt.current,t.startupHealthSeed);y(n),bt.current=n,n&&kr(`${ei}${e}`,n)}},[At.data,e]),(0,_.useEffect)(()=>{if(!E)return;let t=Tr(ii(e))??{};kr(ii(e),{...t,settings:E})},[E,e]),(0,_.useEffect)(()=>{Mt.data!==void 0&&(N(Mt.data),kr(`${$r}${e}`,Mt.data))},[Mt.data,e]),(0,_.useEffect)(()=>{Nt.data&&Le(Nt.data)},[Nt.data]),(0,_.useEffect)(()=>{Pt.data&&C(Pt.data),z(Pt.loading)},[Pt.data,Pt.loading]),(0,_.useEffect)(()=>()=>{Ye.current+=1,Qe.current+=1},[]);let It=K(at?.id&&at.restart?`update-job:${e}:${at.id}`:`update-job:idle:${e}`,[e,at?.id,at?.restart,at?.latestVersion],async t=>{if(!at?.id||!at.restart)return{reconnecting:!1};let n=at.latestVersion;try{let r=await Kt(await fetch(`${e}/api/update/status?jobId=${encodeURIComponent(at.id)}`,{signal:t}));if(r.job){if(r.job.status===`failed`)return{job:r.job,reconnecting:!1};if(n)try{if((await Kt(await fetch(`${e}/healthz`,{cache:`no-store`,signal:t}))).version===n)return{job:r.job,reconnecting:!1,reload:!0}}catch{return{job:r.job,reconnecting:!0}}return{job:r.job,reconnecting:!1}}}catch{return{reconnecting:!0}}return{reconnecting:!1}},{pollMs:1500,enabled:!!(at?.id&&at.restart),pauseWhenHidden:!1});(0,_.useEffect)(()=>{let e=It.data;e&&(`job`in e&&e.job&&ot(e.job),ct(e.reconnecting),`reload`in e&&e.reload&&window.location.reload())},[It.data]);let Lt=(0,_.useMemo)(()=>ri(S),[S]),Rt=(0,_.useMemo)(()=>{let e=o.trim().toLowerCase();if(!e)return Lt;let t=[];for(let[n,r]of Lt){let i=r.filter(t=>t.id.toLowerCase().includes(e)||n.toLowerCase().includes(e));i.length>0&&t.push([n,i])}return t},[Lt,o]),zt=(0,_.useMemo)(()=>{let e=O?.webSearch?.backend;return pn(O?.webSearchModels,S,O?.webSearch?.model,e===`routed`?void 0:e)},[S,O?.webSearchModels,O?.webSearch]),Bt=(0,_.useMemo)(()=>mn(O?.visionModels,S,O?.vision?.model,O?.vision?.backend),[O?.visionModels,S,O?.vision]),Vt=async t=>{if(!O||P)return;let n=O,r={webSearch:Zt(O.webSearch,t.webSearch),vision:Zt(O.vision,t.vision),...O.visionModels?{visionModels:O.visionModels}:{},...O.webSearchModels?{webSearchModels:O.webSearchModels}:{}};F(!0),k(r);try{let n=await Kt(await fetch(`${e}/api/sidecar-settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)}),`save failed`);k({webSearch:n.webSearch,vision:n.vision,...n.visionModels?{visionModels:n.visionModels}:{},...n.webSearchModels?{webSearchModels:n.webSearchModels}:{}});let r=Tr(ii(e))??{};kr(ii(e),{...r,sidecar:{webSearch:n.webSearch,vision:n.vision,...n.visionModels?{visionModels:n.visionModels}:{},...n.webSearchModels?{webSearchModels:n.webSearchModels}:{}}})}catch{k(n)}finally{F(!1)}};async function Ht(t){if(!A||I)return;let n=A,r={...A,...t};L(!0),et.current=!0,j(r);try{if(!(await fetch(`${e}/api/shadow-call-settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)})).ok)throw Error(`shadow-call save failed`);$e.current+=1}catch{j(n)}finally{et.current=!1,L(!1)}}let Gt=async(t,n=!1)=>{G(!0),J(null);try{let i={multiAgentMode:t};n&&(i.multiAgentSurfaceAdvisoryAcknowledged=!0);let a=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(i)});if(a.ok)U(t),n&&te(e),kr(`${ti}${e}`,t);else{let e=r(`dash.maSwitchFailed`,{status:String(a.status)});try{let t=await a.json();e=typeof t.error==`string`&&t.error||typeof t.message==`string`&&t.message||e}catch{}J(e)}}catch(e){J(e instanceof Error?e.message:r(`dash.maNetworkError`))}finally{G(!1)}},qt=async t=>{if(!(W||H===t)){if(t!==`v1`){Z({mode:t,apiBase:e});return}await Gt(`v1`)}},Yt=async()=>{te(e);try{let t=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({multiAgentSurfaceAdvisoryAcknowledged:!0})});t.ok||J(r(`dash.maSwitchFailed`,{status:String(t.status)}))}catch(e){J(e instanceof Error?e.message:r(`dash.maNetworkError`))}},Xt=async()=>{let e=ae;if(Z(null),e){await Gt(e,!0);return}await Yt()},Qt=async()=>{if(Z(null),H===`v1`){await Yt();return}await Gt(`v1`,!0)},$t=()=>{if(ae){Z(null);return}te(e)},en=!ae&&!ie&&re?.required===!0,tn=async t=>{if(!be){xe(!0);try{if(!(await fetch(`${e}/api/injection-model`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)})).ok)throw Error(`injection save failed`);let n=await Kt(await fetch(`${e}/api/injection-model`)),r=Br(n);Ce(r.multiAgentGuidanceEnabled),Te(r.syncCodexSubagentDefaults),pe(r.injectionModel),he(r.injectionEffort),Array.isArray(n.efforts)&&_e(n.efforts),Array.isArray(n.available)&&ye(n.available)}catch{}finally{xe(!1)}}},nn=async t=>{if(!E||D||B)return;let n=!(E[t]??t===`codexAutoStart`);Ze.current=!0,T({type:`save-started`,key:t,value:n});try{let r=await Kt(await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({[t]:n})}),`save failed`);Xe.current+=1,T({type:`save-succeeded`,key:t,settings:r}),(t===`codexDesktopAuthless`||t===`codexClientCompaction`)&&await cn()}catch{T({type:`save-failed`}),Q(!0)}finally{Ze.current=!1,T({type:`save-finished`})}},rn=()=>nn(`codexAutoStart`),an=()=>nn(`codexDesktopAuthless`),on=()=>nn(`codexClientCompaction`),sn=(0,_.useCallback)(()=>{Ne(null),Fe(null)},[]),cn=async()=>{if(!B){V(!0),Ne(null),Fe(null);try{let t=await Kt(await fetch(`${e}/api/sync`,{method:`POST`}),`sync failed`);Ne(t),t.ok&&t.status===`applied`&&T({type:`applied`}),t.projectConfigGrouped&&Le(t.projectConfigGrouped)}catch(e){Fe(e instanceof Error?e.message:String(e))}finally{V(!1)}}},ln=async(t,n=!1)=>{n&&(Ke.current=0),qe.current!==null&&(window.clearTimeout(qe.current),qe.current=null);let r=++Je.current;Ge(!0),it(null),nt(null);try{let n=await Kt(await fetch(`${e}/api/update/check?tag=${t}`),`update check failed`);if(r!==Je.current)return;if(nt(n),n.reason===`latest_unavailable`&&Ke.current<2){let e=++Ke.current;qe.current=window.setTimeout(()=>{r===Je.current&&(qe.current=null,ln(t))},800*e);return}n.reason!==`latest_unavailable`&&(Ke.current=0),Ge(!1)}catch(e){if(r!==Je.current)return;it(e instanceof Error?e.message:String(e)),Ge(!1)}},un=()=>{Je.current+=1,qe.current!==null&&(window.clearTimeout(qe.current),qe.current=null),Ge(!1),ze(!1)},dn=()=>{let e=Jt(h?.version);Ve(e),Ue(!0),ze(!0),ln(e,!0)},fn=e=>{Ve(e),ln(e,!0)},hn=(0,_.useRef)(dn);return(0,_.useEffect)(()=>{hn.current=dn}),(0,_.useEffect)(()=>{let e=()=>{Wt()&&(mt(`dashboard`),hn.current())},t=Wt()?window.setTimeout(e,0):null;return window.addEventListener(`hashchange`,e),()=>{t!==null&&window.clearTimeout(t),window.removeEventListener(`hashchange`,e)}},[]),{apiBase:e,locale:n,t:r,selectedSection:i,setSelectedSection:a,modelQuery:o,setModelQuery:s,expandedProviders:c,setExpandedProviders:l,health:h,startupHealth:v,providers:b,models:S,settings:E,sidecar:O,shadowCall:A,usage30d:M,usageLoading:Mt.loading&&!M,healthLoading:Et.loading&&!h,sidecarSaving:P,shadowCallSaving:I,modelsLoading:R,settingsSaving:D,syncing:B,maMode:H,maModeResolved:Ft,maBusy:W,setMaHelpOpen:se,maHelpOpen:oe,maError:q,maAdvisory:re,maAdvisoryOpen:en,pendingMaMode:ae,keepMaMode:Xt,chooseMaV1:Qt,dismissMaSurfaceDialog:$t,effortCapHelpOpen:ce,setEffortCapHelpOpen:le,shadowCallHelpOpen:ue,setShadowCallHelpOpen:de,injectionModel:fe,injectionEffort:me,injectionEfforts:ge,injectionAvailable:ve,injectionSaving:be,multiAgentGuidanceEnabled:Se,syncCodexSubagentDefaults:we,saveInjection:tn,effortCap:Ee,subagentEffortCap:Oe,effortCapSaving:Ae,setEffortCap:De,setSubagentEffortCap:ke,setEffortCapSaving:je,syncResult:Me,syncError:Pe,projectConfigWarnings:Ie,updateOpen:Re,updateChannel:Be,setUpdateRestart:Ue,updateRestart:He,updateLoading:We,updateCheck:tt,updateError:rt,updateJob:at,reconnecting:st,error:lt||Dt.showError,connectionFailure:Et.data?.failure??(Dt.showError?`unavailable`:void 0),refreshDashboard:Et.refresh,effortCapHelpTriggerRef:dt,updateTriggerRef:ft,maHelpTriggerRef:pt,shadowCallHelpTriggerRef:ht,effortCapHelpDialogRef:gt,updateDialogRef:_t,maHelpDialogRef:vt,shadowCallHelpDialogRef:yt,filteredGroups:Rt,sidecarModels:zt,visionModels:Bt,saveSidecar:Vt,saveShadowCall:Ht,switchMaMode:qt,toggleCodexAutoStart:rn,toggleCodexDesktopAuthless:an,toggleCodexClientCompaction:on,runSync:cn,clearSyncFeedback:sn,fetchUpdateCheck:ln,closeUpdateDialog:un,openUpdateDialog:dn,changeUpdateChannel:fn,runUpdate:async()=>{if(tt?.canUpdate){it(null);try{let t=await Kt(await fetch(`${e}/api/update/run`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({tag:Be,restart:He})}),`update failed to start`);if(!t.job)throw Error(`update failed to start`);ot(t.job),ct(!1),un()}catch(e){it(e instanceof Error?e.message:String(e))}}}}}function oi(e){ht(Gt(e))}function si({apiBase:e,connected:t=!1,authenticationPending:n=!1,refreshEpoch:r=0}){let i=ai(e,r),{t:a,error:o,selectedSection:s,providers:c,models:l,modelsLoading:u,modelQuery:d,setModelQuery:f,filteredGroups:p,expandedProviders:m,setExpandedProviders:h}=i;if(n)return null;let g=i.connectionFailure===`auth`||i.connectionFailure===`denied`;if(o&&(g||!i.health))return(0,Y.jsxs)(At,{style:{marginTop:40},icon:(0,Y.jsx)(_e,{}),title:(0,Y.jsx)(`span`,{style:{color:`var(--red)`},children:a(i.connectionFailure===`denied`?`dash.permissionDenied`:i.connectionFailure===`auth`?`dash.authRequired`:`dash.dataUnavailable`)}),children:[!t&&i.connectionFailure===`unavailable`&&(0,Y.jsx)(ft,{k:`dash.runStart`,cmd:`ocx start`}),(0,Y.jsx)(`button`,{className:`btn btn-ghost`,type:`button`,onClick:()=>i.refreshDashboard(),children:a(`common.retry`)})]});let _=(0,Y.jsx)(Sr,{...i}),v=(0,Y.jsx)(Cr,{t:a,providers:c}),y=(0,Y.jsx)(Vn,{t:a,models:l,modelsLoading:u,modelQuery:d,setModelQuery:f,filteredGroups:p,expandedProviders:m,setExpandedProviders:h}),b=(0,Y.jsx)(En,{...i}),x=[{id:`overview`,label:a(`dash.workspace.overview`),body:_},{id:`providers`,label:a(`dash.activeProviders`),body:v},{id:`models`,label:a(`dash.availableModels`),body:y}],S=x.find(e=>e.id===s)??x[0],C=oi,w=e=>{let t=x.findIndex(e=>e.id===s),n=-1;if(e.key===`ArrowRight`?n=(t+1)%x.length:e.key===`ArrowLeft`?n=(t-1+x.length)%x.length:e.key===`Home`?n=0:e.key===`End`&&(n=x.length-1),n<0)return;e.preventDefault();let r=x[n];C(r.id),document.getElementById(`dashboard-tab-${r.id}`)?.focus()};return(0,Y.jsxs)(`div`,{className:`dashboard-workspace-shell`,children:[o&&(0,Y.jsxs)($,{tone:`warn`,children:[a(`dash.staleData`),` `,(0,Y.jsx)(`button`,{className:`btn btn-ghost`,type:`button`,onClick:()=>i.refreshDashboard(),children:a(`common.retry`)})]}),(0,Y.jsx)(`div`,{className:`page-head`,children:(0,Y.jsx)(`h2`,{children:a(`nav.dashboard`)})}),(0,Y.jsx)(`p`,{className:`page-sub`,children:a(`dash.subtitle`)}),(0,Y.jsx)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":a(`dash.workspace.sections`),children:x.map(e=>(0,Y.jsx)(`button`,{type:`button`,role:`tab`,id:`dashboard-tab-${e.id}`,"aria-selected":s===e.id,"aria-controls":`dashboard-panel-${e.id}`,tabIndex:s===e.id?0:-1,className:`page-tab${s===e.id?` page-tab--active`:``}`,onClick:()=>C(e.id),onKeyDown:w,children:e.label},e.id))}),(0,Y.jsx)(`section`,{className:`dashboard-workspace-main`,role:`tabpanel`,id:`dashboard-panel-${S.id}`,"aria-labelledby":`dashboard-tab-${S.id}`,tabIndex:0,children:S.body}),b]})}var ci=`https://chatgpt.com/backend-api/codex`,li=`openai`;function ui(e){try{let t=new URL(e.trim());if(t.username||t.password||t.search||t.hash)return;let n=t.pathname.replace(/\/+$/,``);return`${t.origin}${n}`}catch{return}}var di=new URL(ci).protocol;function fi(e,...t){return`${di}//${e}/${t.join(`/`)}`}var pi={"cline-pass":{adapter:`openai-chat`,baseUrl:fi(`api.cline.bot`,`api`,`v1`)},"mimo-free":{adapter:`mimo-free`,baseUrl:fi(`api.xiaomimimo.com`,`api`,`free-ai`,`openai`,`chat`)}};function mi(e,t){let n=pi[e];return!n||t.adapter!==n.adapter||ui(t.baseUrl)!==ui(n.baseUrl)}function hi(e){try{let t=new URL(e).hostname.replace(/^\[|\]$/g,``).toLowerCase();return t===`localhost`||t===`127.0.0.1`||t===`::1`}catch{return!1}}function gi(e){return e.keyOptional===!0||e.authMode===`oauth`||e.authMode===`forward`||e.authMode===`local`||hi(e.baseUrl)||e.hasApiKey===!0}function _i(e){return e.adapter===`openai-responses`&&e.authMode===`forward`&&ui(e.baseUrl)===ci}function vi(e,t){return e===li&&_i(t)}function yi(e){return e.freeTier===!0||e.keyOptional===!0||e.authMode===`local`||hi(e.baseUrl)}function bi(e,t){return vi(e,t)?`accounts`:yi(t)?`free`:`paid`}function xi(e,t){let n=[...e],r=(e,t)=>e.name.localeCompare(t.name,void 0,{sensitivity:`base`}),i=e=>e.tier??bi(e.name,e);switch(t){case`az`:return n.sort(r);case`za`:return n.sort((e,t)=>r(t,e));case`free-paid`:return n.sort((e,t)=>(i(e)===`free`?0:1)-(i(t)===`free`?0:1)||r(e,t));case`paid-free`:return n.sort((e,t)=>(i(e)===`free`)-+(i(t)===`free`)||r(e,t));case`accounts-first`:return n.sort((e,t)=>{let n=e=>{let t=i(e);return t===`accounts`?0:t===`free`?1:2};return n(e)-n(t)||r(e,t)});default:return n}}function Si(e){let t=[],n=[],r=[];for(let[i,a]of Object.entries(e)){if(a.disabled){r.push({name:i,...a});continue}gi(a)?t.push({name:i,...a,tier:bi(i,a)}):n.push({name:i,...a})}return{ready:t,needsSetup:n,disabled:r}}function Ci(e,t){let n=new Set(Object.entries(t).filter(([,e])=>e).map(([e])=>e));if(n.size===0)return e;let r=e=>e.map(e=>n.has(e.name)?{...e,activeNeedsReauth:!0}:e);return{ready:r(e.ready),needsSetup:r(e.needsSetup),disabled:e.disabled}}function wi(e){return e.disabled?`disabled`:`activeNeedsReauth`in e&&e.activeNeedsReauth?`needs-setup`:gi(e)?`ready`:`needs-setup`}function Ti(e){let t=e.openai,n=e.chatgpt;if(!t||!n||!vi(`openai`,t)||!_i(n))return e;let r={...e};return delete r.chatgpt,r}function Ei(e){return e.authMode===`local`||hi(e.baseUrl)}var Di=[`ollama`,`vllm`,`lm-studio`,`lmstudio`,`litellm`,`localai`];function Oi(e){let t=(e.authMode??``).toLowerCase();if(t===`oauth`||t===`forward`)return`login`;if(Ei(e))return`local`;let n=`${e.name??``} ${e.adapter} ${e.baseUrl}`.toLowerCase();return Di.some(e=>n.includes(e))?`selfHosted`:`cloud`}function ki(e){let t=Object.create(null);for(let n of e)t[n.provider]={requests:n.requests,totalTokens:n.totalTokens};return t}function Ai(e,t){let n=Object.create(null);for(let r of e){let e=t[r.provider]?.totalTokens??0,{provider:i,...a}=r;(n[i]??=[]).push({...a,shareRatio:e>0?Math.min(1,Math.max(0,r.totalTokens/e)):0})}return n}function ji(e){return Object.entries(e).filter(e=>typeof e[1].requests==`number`&&e[1].requests>0).map(([e,t])=>({name:e,...t,requests:t.requests})).sort((e,t)=>t.requests-e.requests||e.name.localeCompare(t.name))}var Mi={justNow:`Just now`,notChecked:`Not checked`,minutesAgo:e=>`${e}m ago`,hoursAgo:e=>`${e}h ago`,daysAgo:e=>`${e}d ago`};function Ni(e,t,n){let r=typeof t==`object`&&t?t:Mi,i=typeof t==`number`?t:n??Date.now();if(e===void 0||!Number.isFinite(e))return r.notChecked;let a=Math.max(0,i-e),o=Math.floor(a/6e4);if(o<1)return r.justNow;if(o<60)return r.minutesAgo(o);let s=Math.floor(o/60);return s<24?r.hoursAgo(s):r.daysAgo(Math.floor(s/24))}function Pi(e){return{justNow:e(`time.justNow`),notChecked:e(`time.notChecked`),minutesAgo:t=>e(`time.minutesAgo`,{n:t}),hoursAgo:t=>e(`time.hoursAgo`,{n:t}),daysAgo:t=>e(`time.daysAgo`,{n:t})}}function Fi(e,t){let n=[];for(let r of e.ready)r.activeNeedsReauth&&n.push({name:r.name,reason:t[r.name]??`Active account needs re-authentication`});for(let r of e.needsSetup){let e=r.activeNeedsReauth?t[r.name]??`Active account needs re-authentication`:t[r.name]??`Missing credentials`;n.push({name:r.name,reason:e})}for(let r of e.disabled){let e=t[r.name];e&&n.push({name:r.name,reason:e})}return n}function Ii(e){return e===`Active account needs re-authentication`?`reauth`:e===`Missing credentials`?`missing`:`custom`}function Li(e,t=`en`){if(e===void 0)return`—`;if(t.toLowerCase().slice(0,2)===`de`){let t=e=>e.replace(/\.0+$/,``).replace(`.`,`,`);return e>=1e9?`${t((e/1e9).toFixed(2))} Mrd.`:e>=1e6?`${t((e/1e6).toFixed(1))} Mio.`:e>=1e3?`${t((e/1e3).toFixed(1))} Tsd.`:String(e)}return e>=1e9?`${(e/1e9).toFixed(2).replace(/\.?0+$/,``)}B`:e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e)}function Ri(e,t=`en`){return Li(e,t)}function zi(e,t=`en`){return e==null||!Number.isFinite(e)||e<0?`—`:`~$${new Intl.NumberFormat(t,{minimumFractionDigits:4,maximumFractionDigits:4}).format(e)}`}function Bi(e,t){if(!e||typeof e!=`object`||Array.isArray(e))return null;let n=e;if(typeof n.updatedAt!=`number`||!Number.isFinite(n.updatedAt))return null;let r=n.observed===!0;return!r&&t-n.updatedAt>=18e5||!(`quota`in n)||n.label!==void 0&&typeof n.label!=`string`||n.source!==void 0&&typeof n.source!=`string`?null:{...typeof n.label==`string`?{label:n.label}:{},...typeof n.source==`string`?{source:n.source}:{},updatedAt:n.updatedAt,quota:n.quota,...r?{observed:!0}:{},...n.aggregation===void 0?{}:{aggregation:n.aggregation}}}function Vi(e,t=Date.now()){if(!e||typeof e!=`object`||Array.isArray(e))return null;let n={};for(let[r,i]of Object.entries(e)){let e=Bi(i,t);r.trim()&&e&&(n[r]=e)}return n}function Hi(e,t=Date.now()){if(!Array.isArray(e))return{};let n={};for(let r of e){if(!r||typeof r!=`object`||Array.isArray(r))continue;let e=r.provider,i=Bi(r,t);typeof e==`string`&&e.trim()&&i&&(n[e]=i)}return n}function Ui(e){return e?.observed===!0&&typeof e.updatedAt==`number`?e.updatedAt:void 0}var Wi=e=>typeof e==`number`&&Number.isFinite(e)?e:void 0,Gi=e=>{let t=Wi(e);if(t===void 0)return;let n=t>1e10?t:t*1e3;return Number.isFinite(new Date(n).getTime())?t:void 0};function Ki(e,t){if(!e||typeof e!=`object`||Array.isArray(e))return null;let n=e,r=Array.isArray(n.customWindows)?n.customWindows.flatMap(e=>{if(!e||typeof e!=`object`)return[];let t=e;return typeof t.label!=`string`||Wi(t.percent)===void 0?[]:[{label:t.label,percent:t.percent,...Wi(t.resetAt)===void 0?{}:{resetAt:t.resetAt}}]}):[],i=n.creditsUsd&&typeof n.creditsUsd==`object`&&!Array.isArray(n.creditsUsd)?n.creditsUsd:null,a=Wi(i?.used),o=Wi(i?.limit),s=Wi(i?.remaining),c=Wi(i?.percent),l=Gi(i?.expiresAt),u=a!==void 0&&o!==void 0&&s!==void 0&&c!==void 0?{used:a,limit:o,remaining:s,percent:c,...l===void 0?{}:{expiresAt:l},...typeof i?.unlimited==`boolean`?{unlimited:i.unlimited}:{}}:void 0,d={...Wi(n.fiveHourPercent)===void 0?{}:{fiveHourPercent:n.fiveHourPercent},...Wi(n.fiveHourResetAt)===void 0?{}:{fiveHourResetAt:n.fiveHourResetAt},...Wi(n.weeklyPercent)===void 0?{}:{weeklyPercent:n.weeklyPercent},...Wi(n.weeklyResetAt)===void 0?{}:{weeklyResetAt:n.weeklyResetAt},...Wi(n.monthlyPercent)===void 0?{}:{monthlyPercent:n.monthlyPercent},...Wi(n.monthlyResetAt)===void 0?{}:{monthlyResetAt:n.monthlyResetAt},...r.length>0?{customWindows:r}:{},...u?{creditsUsd:u}:{},updatedAt:Wi(n.updatedAt)??t??Date.now()};return d.fiveHourPercent!==void 0||d.weeklyPercent!==void 0||d.monthlyPercent!==void 0||(d.customWindows?.length??0)>0||d.creditsUsd!==void 0?d:null}function qi(e){return Ki(e?.quota,e?.updatedAt)}function Ji(e){if(!e)return;if(e.aggregation===void 0)return e;let t=Xi(e)?.currentAccount?.quota??null;return{...e,aggregation:void 0,quota:t,updatedAt:t?.updatedAt}}function Yi(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e,n=Wi(t.usedPercent);if(n!==void 0)return{usedPercent:n,...typeof t.incomplete==`boolean`?{incomplete:t.incomplete}:{},...Wi(t.excludedAccounts)===void 0?{}:{excludedAccounts:t.excludedAccounts},...Wi(t.nextRecoveryAt)===void 0?{}:{nextRecoveryAt:t.nextRecoveryAt},...Wi(t.nextRecoveryPercent)===void 0?{}:{nextRecoveryPercent:t.nextRecoveryPercent}}}function Xi(e){let t=e?.aggregation;if(!t||typeof t!=`object`||Array.isArray(t))return null;let n=t;if(n.kind!==`capacity-weighted-v1`||n.scope!==`routable-known`)return null;let r=Wi(n.excludedAccounts),i=Wi(n.unknownPlanAccounts);if(r===void 0||i===void 0||typeof n.incomplete!=`boolean`)return null;let a=n.currentAccount&&typeof n.currentAccount==`object`&&!Array.isArray(n.currentAccount)?n.currentAccount:null,o=Array.isArray(n.customWindows)?n.customWindows.flatMap(e=>{if(!e||typeof e!=`object`||Array.isArray(e))return[];let t=e,n=Yi(t);return typeof t.label==`string`&&n?[{label:t.label,...n}]:[]}):[],s=Yi(n.fiveHour),c=Yi(n.weekly),l=Yi(n.monthly),u=!!s||!!c||!!l||o.length>0;return{presentation:n.presentation===`aggregate`||n.presentation===`effective-account-fallback`||n.presentation===`coverage-only`?n.presentation:u?`aggregate`:`coverage-only`,incomplete:n.incomplete,excludedAccounts:r,unknownPlanAccounts:i,partialWindowAccounts:Wi(n.partialWindowAccounts)??0,...s?{fiveHour:s}:{},...c?{weekly:c}:{},...l?{monthly:l}:{},...o.length>0?{customWindows:o}:{},...a?{currentAccount:{...typeof a.plan==`string`||a.plan===null?{plan:a.plan}:{},quota:Ki(a.quota)}}:{}}}function Zi(e){if(!e?.trim())return``;let[t,n]=e.split(`:`,2);return n?`${t} · ${n.replace(/-/g,` `)}`:e}function Qi(e,t){let n=wi(e);return n===`disabled`?t(`prov.disabledBadge`):n===`ready`?t(`pws.status.ready`):`activeNeedsReauth`in e&&e.activeNeedsReauth?t(`pws.status.needsAttention`):t(`pws.status.needsSetup`)}function $i(e,t){switch(e.authMode){case`oauth`:return t(`modal.badge.oauth`);case`forward`:return t(`pws.auth.chatgptPassthrough`);case`local`:return t(`modal.badge.local`);case`key`:return t(`modal.badge.apiKey`);default:return e.authMode??(e.keyOptional?t(`pws.auth.noKey`):t(`modal.badge.apiKey`))}}function ea(e){let t=wi(e);return t===`disabled`?`providers-workspace-rail-status providers-workspace-rail-status--inactive`:t===`ready`?`providers-workspace-rail-status providers-workspace-rail-status--active`:`providers-workspace-rail-status providers-workspace-rail-status--warning`}function ta({name:e,adapter:t,baseUrl:n,cls:r}){let i=Q(),a=Mn(e,{adapter:t,baseUrl:n}),o=In(a),s=o===`plate`?`${r} provider-icon--plate`:o===`dark-plate`?`${r} provider-icon--plate-dark`:r;return(0,Y.jsx)(`span`,{className:s,children:a&&o===`mask`?(0,Y.jsx)(`span`,{className:`provider-icon-mask`,style:{maskImage:`url(${a})`,WebkitMaskImage:`url(${a})`},"aria-hidden":`true`}):a?(0,Y.jsx)(`img`,{src:a,alt:``,"aria-hidden":`true`}):(0,Y.jsx)(na,{name:e,label:Ln(e,i)})})}function na({name:e,label:t}){let n=[...e].reduce((e,t)=>e+t.charCodeAt(0),0)%360,r=(t.trim()[0]??e[0]??`?`).toUpperCase();return(0,Y.jsx)(`span`,{className:`provider-icon-fallback`,style:{background:`hsl(${n} 55% 90%)`,color:`hsl(${n} 65% 32%)`},"aria-hidden":`true`,children:r})}function ra({item:e,selected:t,tabbable:n,modelCount:r,isDefault:i,showConfigId:a,onClick:o,onFocus:s}){let c=Q(),l=yi(e),u=Ei(e),d=Qi(e,c),f=Ln(e.name,c),p=a?`${f} (${e.name})`:f,m=`${i?c(`pws.rail.suffixDefault`):``}${u?c(`pws.rail.suffixLocal`):l?c(`pws.rail.suffixFree`):``}`,h=r!==void 0&&r>0?r===1?c(`pws.modelCountOne`):c(`pws.modelCount`,{count:r}):``,g=[a?e.name:``,h].filter(Boolean).join(` · `);return(0,Y.jsxs)(`button`,{type:`button`,className:`providers-workspace-rail-row${t?` providers-workspace-rail-row--selected`:``}`,onClick:o,role:`option`,"aria-selected":t,tabIndex:n?0:-1,"aria-label":c(`pws.rail.selectAria`,{name:p,status:d,suffix:m}),title:p,onFocus:s,children:[(0,Y.jsx)(ta,{name:e.name,adapter:e.adapter,baseUrl:e.baseUrl,cls:`providers-workspace-rail-icon`}),(0,Y.jsxs)(`span`,{className:`providers-workspace-rail-copy`,children:[(0,Y.jsxs)(`span`,{className:`providers-workspace-rail-primary`,children:[(0,Y.jsx)(`span`,{className:`providers-workspace-rail-name-label`,title:f,children:f}),u?(0,Y.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--local`,title:c(`pws.localTitle`),children:c(`modal.badge.local`)}):l?(0,Y.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--free`,title:c(`pws.freeTitle`),children:c(`modal.badge.free`)}):null]}),(0,Y.jsx)(`span`,{className:`providers-workspace-rail-secondary`,title:g||void 0,children:g||`\xA0`})]}),(0,Y.jsxs)(`span`,{className:`providers-workspace-rail-trail`,children:[i&&(0,Y.jsx)(`span`,{className:`pwi-default-star`,title:c(`prov.defaultBadge`),"aria-label":c(`prov.defaultBadge`),children:(0,Y.jsx)(Re,{width:17,height:17,"aria-hidden":`true`})}),(0,Y.jsx)(`span`,{className:ea(e),title:d,"aria-hidden":`true`})]})]})}function ia(e){return{fiveHourAvailable:e?.shortWindowSeconds===18e3&&typeof e.shortResetAt==`number`,weeklyAvailable:typeof e?.weeklyResetAt==`number`}}function aa(e){let t=e?.trim().toLowerCase();return t===`go`||t===`free`}function oa(e,t){if(!e)return null;let n=e.shortPercent===void 0&&e.shortResetAt===void 0?e:{...e,fiveHourPercent:e.fiveHourPercent??e.shortPercent,fiveHourResetAt:e.fiveHourResetAt??e.shortResetAt};return aa(t)?{...n.monthlyPercent===void 0?{}:{monthlyPercent:n.monthlyPercent},...n.monthlyResetAt===void 0?{}:{monthlyResetAt:n.monthlyResetAt},...n.creditsUsd===void 0?{}:{creditsUsd:n.creditsUsd},...n.resetCredits===void 0?{}:{resetCredits:n.resetCredits},updatedAt:n.updatedAt}:n}function sa(e){return e===`5h`?0:e===`First-party models`?2:e===`API usage`?3:e===`Total subscription credits`?4.5:5}var ca=`Total subscription credits`;function la(e){return e.trim().toLowerCase()===ca.toLowerCase()?ca:e}function ua(e,t){if(e===void 0||!t)return!1;let n=la(e);for(let e of t)if(la(e)===n)return!0;return!1}function da(e,t){switch(e){case`First-party models`:return t(`quota.cursorFirstParty`);case`API usage`:return t(`quota.cursorApiUsage`);case`Total subscription credits`:return t(`quota.totalSubscriptionCredits`);default:return e}}function fa(e,t,n){let r=oa(e,t);if(!r)return[];let i=[];typeof r.fiveHourPercent==`number`&&i.push({rank:0,row:{windowKey:`fiveHour`,label:n(`codexAuth.fiveHour`),limitLabel:n(`quota.fiveHourLimit`),percent:r.fiveHourPercent,resetAt:r.fiveHourResetAt}}),typeof r.weeklyPercent==`number`&&i.push({rank:1,row:{windowKey:`weekly`,label:n(`codexAuth.weekly`),limitLabel:n(`quota.weeklyLimit`),percent:r.weeklyPercent,resetAt:r.weeklyResetAt}}),typeof r.monthlyPercent==`number`&&i.push({rank:4,row:{windowKey:`monthly`,label:n(`codexAuth.monthly`),limitLabel:n(`quota.monthlyLimit`),percent:r.monthlyPercent,resetAt:r.monthlyResetAt}});for(let e of r.customWindows??[]){let t=la(e.label),r=da(t,n);i.push({rank:sa(t),row:{customLabel:t,label:r,limitLabel:r,percent:e.percent,resetAt:e.resetAt}})}if(r.creditsUsd&&typeof r.creditsUsd.percent==`number`&&!r.customWindows?.some(e=>la(e.label)===ca)){let e=da(ca,n);i.push({rank:sa(ca),row:{customLabel:ca,label:e,limitLabel:e,percent:r.creditsUsd.percent,resetAt:r.creditsUsd.expiresAt}})}return i.sort((e,t)=>e.rank-t.rank).map(e=>e.row)}function pa(e){if(!e)return-1;let t=[e.fiveHourPercent,e.weeklyPercent,e.monthlyPercent].filter(e=>typeof e==`number`);for(let n of e.customWindows??[])typeof n.percent==`number`&&t.push(n.percent);return!e.customWindows?.some(e=>la(e.label)===ca)&&typeof e.creditsUsd?.percent==`number`&&t.push(e.creditsUsd.percent),t.length?Math.max(...t):-1}function ma(e){switch(e){case`en`:return`en-GB`;case`de`:return`de-DE`;case`fr`:return`fr-FR`;case`ko`:return`ko-KR`;case`zh`:return`zh-CN`;case`zh-TW`:return`zh-TW`;case`ru`:return`ru-RU`;case`ja`:return`ja-JP`;case`tr`:return`tr-TR`;default:return e}}function ha(e){return e>=99.5}function ga(e,t){return t>0&&e>=t}function _a(e,t){return ga(e,t)||ha(e)?`bar-warn`:`bar-green`}function va(e){let t=Math.max(0,Math.min(100,e));return t<=0?0:Math.max(4,Math.round(t))}function ya(e){return{"--bar-scale":String(va(e)/100)}}function ba(e,t,n=Date.now()){let r=n-e;return!Number.isFinite(r)||r<6e4?null:r<36e5?t(`quota.ageMinutes`).replace(`{n}`,String(Math.floor(r/6e4))):r<864e5?t(`quota.ageHours`).replace(`{n}`,String(Math.floor(r/36e5))):t(`quota.ageDays`).replace(`{n}`,String(Math.floor(r/864e5)))}function xa({quota:e,plan:t,threshold:n,t:r,className:i,layout:a=`compact`,pending:o=!1,incompleteWindowKeys:s,incompleteCustomWindowLabels:c,observedAt:l}){let{locale:u}=ut(),d=fa(e,t,r),f=l===void 0?null:ba(l,r),p=f===null?null:(0,Y.jsx)(`p`,{className:`quota-observed muted`,title:r(`quota.observedHint`),children:r(`quota.observedAgo`).replace(`{age}`,f)});return d.length===0?o?a===`stacked`?(0,Y.jsxs)(`div`,{className:`quota-stacked quota-stacked--pending${i?` ${i}`:``}`,"aria-busy":`true`,role:`status`,children:[Array.from({length:2},(e,t)=>(0,Y.jsxs)(`div`,{className:`quota-stacked-row quota-stacked-row--skeleton`,"aria-hidden":`true`,children:[(0,Y.jsxs)(`div`,{className:`quota-stacked-head`,children:[(0,Y.jsx)(`span`,{className:`quota-skel quota-skel--label`,style:{width:72}}),(0,Y.jsx)(`span`,{className:`quota-skel quota-skel--time`,style:{width:64}})]}),(0,Y.jsxs)(`div`,{className:`quota-stacked-bar-row`,children:[(0,Y.jsx)(`span`,{className:`quota-skel quota-skel--bar`,style:{height:6,flex:1}}),(0,Y.jsx)(`span`,{className:`quota-skel quota-skel--val`,style:{width:36}})]})]},t)),(0,Y.jsx)(`span`,{className:`sr-only`,children:r(`common.loading`)})]}):(0,Y.jsxs)(`div`,{className:`codex-account-quota-slot quota-compact quota-compact--pending${i?` ${i}`:``}`,"aria-busy":`true`,role:`status`,children:[(0,Y.jsxs)(`div`,{className:`quota-row quota-row--skeleton`,"aria-hidden":`true`,children:[(0,Y.jsx)(`span`,{className:`quota-skel quota-skel--label`}),(0,Y.jsx)(`span`,{className:`quota-skel quota-skel--reset`}),(0,Y.jsx)(`span`,{className:`quota-skel quota-skel--day`}),(0,Y.jsx)(`span`,{className:`quota-skel quota-skel--time`}),(0,Y.jsx)(`span`,{className:`quota-skel quota-skel--bar`}),(0,Y.jsx)(`span`,{className:`quota-skel quota-skel--val`})]}),(0,Y.jsx)(`span`,{className:`sr-only`,children:r(`common.loading`)})]}):null:a===`stacked`?(0,Y.jsxs)(`div`,{className:`quota-stacked${i?` ${i}`:``}`,children:[p,d.map(e=>(0,Y.jsx)(Ca,{row:e,threshold:n,t:r,locale:u,incomplete:e.windowKey?s?.has(e.windowKey)===!0:ua(e.customLabel,c)},e.limitLabel))]}):(0,Y.jsxs)(`div`,{className:`codex-account-quota-slot quota-compact${i?` ${i}`:``}`,children:[p,d.map(e=>(0,Y.jsx)(Sa,{credits:e.customLabel===ca,label:e.label,percent:e.percent,resetAt:e.resetAt,threshold:n,t:r,locale:u},e.label))]})}function Sa({credits:e,label:t,percent:n,resetAt:r,threshold:i,t:a,locale:o}){let s=ha(n),c=ga(n,i),l=_a(n,i),u=Ta(r,a,o),d=u.day||u.time?`${a(`codexAuth.resets`)} ${u.day} ${u.time}`.replace(/\s+/g,` `).trim():void 0,f=u.day!==``||u.time!==``;return(0,Y.jsxs)(`div`,{className:`quota-row${e?` quota-row--credits`:``}${c?` quota-row--warn`:``}${s?` quota-row--exhausted`:``}`,children:[(0,Y.jsx)(`span`,{className:`quota-label`,title:d,children:t}),(0,Y.jsx)(`span`,{className:`quota-reset-label`,children:f?a(`codexAuth.resets`):``}),(0,Y.jsx)(`span`,{className:`quota-reset-day`,children:u.day}),(0,Y.jsx)(`span`,{className:`quota-reset-time`,children:u.time}),(0,Y.jsx)(`div`,{className:`bar`,title:d,children:(0,Y.jsx)(`div`,{className:`bar-fill ${l}`,style:ya(n)})}),(0,Y.jsxs)(`span`,{className:`quota-val${c?` quota-val--warn`:``}`,title:s?a(`quota.limitReached`):d,"aria-label":d,children:[c&&(0,Y.jsx)(_e,{width:12,height:12,"aria-hidden":`true`}),Math.round(n),`%`,s?` · ${a(`quota.limitReached`)}`:``]})]})}function Ca({row:e,threshold:t,t:n,locale:r,incomplete:i}){let a=ha(e.percent),o=ga(e.percent,t),s=_a(e.percent,t),c=Ea(e.resetAt,n,r);return(0,Y.jsxs)(`div`,{className:`quota-stacked-row${o?` quota-stacked-row--warn`:``}${a?` quota-stacked-row--exhausted`:``}`,children:[(0,Y.jsxs)(`div`,{className:`quota-stacked-head`,children:[(0,Y.jsxs)(`span`,{className:`quota-stacked-limit-group`,children:[(0,Y.jsx)(`span`,{className:`quota-stacked-limit`,children:e.limitLabel}),i&&(0,Y.jsx)(`span`,{className:`quota-window-partial`,role:`note`,"aria-label":n(`pws.capacity.windowPartialA11y`,{window:e.limitLabel}),title:n(`pws.capacity.windowPartialA11y`,{window:e.limitLabel}),children:n(`pws.capacity.windowPartial`)})]}),(0,Y.jsx)(`span`,{className:`quota-stacked-reset muted`,children:c})]}),(0,Y.jsxs)(`div`,{className:`quota-stacked-bar-row`,children:[(0,Y.jsx)(`div`,{className:`bar quota-stacked-bar`,children:(0,Y.jsx)(`div`,{className:`bar-fill ${s}`,style:ya(e.percent)})}),(0,Y.jsx)(`span`,{className:`quota-stacked-used${o?` quota-stacked-used--warn`:``}`,children:n(`quota.usedPercent`,{pct:Math.round(e.percent)})})]}),a&&(0,Y.jsxs)(`div`,{className:`quota-stacked-limit-reached`,role:`status`,children:[(0,Y.jsx)(_e,{width:12,height:12,"aria-hidden":`true`}),n(`quota.limitReached`)]})]})}function wa(e){if(typeof e!=`number`||!Number.isFinite(e))return null;let t=e<1e10?e*1e3:e,n=new Date(t);return Number.isFinite(n.getTime())?{date:n,ms:t}:null}function Ta(e,t,n){let r=wa(e);if(!r)return{day:``,time:``};let{date:i}=r,a=new Date,o=ma(n),s=new Intl.DateTimeFormat(o,{hour:`2-digit`,minute:`2-digit`,hour12:!1}).format(i);return i.getFullYear()===a.getFullYear()&&i.getMonth()===a.getMonth()&&i.getDate()===a.getDate()?{day:t(`codexAuth.today`),time:s}:{day:new Intl.DateTimeFormat(o,{day:`numeric`,month:`short`}).format(i),time:s}}function Ea(e,t,n=`en`,r=Date.now()){let i=wa(e);if(!i)return``;let{date:a,ms:o}=i,s=ma(n),c=new Intl.DateTimeFormat(s,{hour:`2-digit`,minute:`2-digit`,hour12:!1}).format(a),l=new Date(r),u=new Date(l.getFullYear(),l.getMonth(),l.getDate()).getTime(),d=new Date(a.getFullYear(),a.getMonth(),a.getDate()).getTime(),f=Math.round((d-u)/864e5);if(f===1)return t(`quota.resetsTomorrow`,{time:c});let p=a.getFullYear()!==l.getFullYear(),m=new Intl.DateTimeFormat(s,{day:`numeric`,month:`short`,...p?{year:`numeric`}:{}}).format(a);if(o<=r)return t(`quota.resetsAt`,{date:m,time:c,when:`${m}, ${c}`});let h=Math.round((o-r)/6e4);if(h<60)return t(`quota.resetsRelativeMinutes`,{n:Math.max(1,h)});let g=Math.round(h/60);return g<12&&f===0?t(`quota.resetsRelativeHours`,{n:Math.max(1,g)}):f===0?t(`quota.resetsToday`,{time:c}):t(`quota.resetsAt`,{date:m,time:c,when:`${m}, ${c}`})}function Da(e){switch(e){case`en`:return`en-GB`;case`de`:return`de-DE`;case`fr`:return`fr-FR`;case`ko`:return`ko-KR`;case`zh`:return`zh-CN`;case`zh-TW`:return`zh-TW`;case`ru`:return`ru-RU`;case`ja`:return`ja-JP`;case`tr`:return`tr-TR`;default:return e}}function Oa(e){let t=new Date(e>1e10?e:e*1e3);return Number.isFinite(t.getTime())?t:null}function ka({report:e,pending:t}){let n=Q(),{locale:r}=ut(),i=Xi(e),a=qi(e),o=Ui(e),s=a?.creditsUsd,c=i?.presentation===`aggregate`,l=new Set,u=new Set;if(c&&i){i.fiveHour?.incomplete&&l.add(`fiveHour`),i.weekly?.incomplete&&l.add(`weekly`),i.monthly?.incomplete&&l.add(`monthly`);for(let e of i.customWindows??[])e.incomplete&&u.add(e.label)}let d=c&&i?[...i.fiveHour?[{key:0,label:n(`codexAuth.fiveHour`),window:i.fiveHour}]:[],...i.weekly?[{key:1,label:n(`codexAuth.weekly`),window:i.weekly}]:[],...i.monthly?[{key:2,label:n(`codexAuth.monthly`),window:i.monthly}]:[],...(i.customWindows??[]).map((e,t)=>({key:t+3,label:e.label,window:e}))]:[],f=e=>new Intl.NumberFormat(r,{maximumFractionDigits:1}).format(e),p=e=>{let t=Oa(e);return t===null?null:new Intl.DateTimeFormat(r,{dateStyle:`medium`,timeStyle:`short`}).format(t)},m=Da(r),h=e=>new Intl.NumberFormat(m,{style:`currency`,currency:`USD`}).format(e),g=s?.expiresAt===void 0?null:(e=>{let t=Oa(e);return t===null?null:new Intl.DateTimeFormat(m,{dateStyle:`medium`}).format(t)})(s.expiresAt);return(0,Y.jsxs)(Y.Fragment,{children:[c&&(0,Y.jsx)(`div`,{className:`pws-capacity-label`,children:n(`pws.capacity.estimate`)}),(a||t)&&(0,Y.jsx)(xa,{quota:a,threshold:80,t:n,layout:`stacked`,pending:t,...o===void 0?{}:{observedAt:o},incompleteWindowKeys:c?l:void 0,incompleteCustomWindowLabels:c?u:void 0}),(s||i)&&(0,Y.jsxs)(`div`,{className:`pws-capacity-details`,children:[s&&(0,Y.jsxs)(`div`,{className:`pws-capacity-recovery`,children:[(0,Y.jsx)(`span`,{children:n(`quota.creditsBalance`)}),(0,Y.jsx)(`strong`,{children:h(s.remaining)})]}),g!==null&&(0,Y.jsx)(`div`,{className:`pws-capacity-recovery`,children:(0,Y.jsx)(`span`,{children:n(`quota.creditsPeriodEnds`,{date:g})})}),d.flatMap(({key:e,label:t,window:r})=>{let i=r.nextRecoveryAt===void 0?null:p(r.nextRecoveryAt);return i!==null&&r.nextRecoveryPercent!==void 0?[(0,Y.jsxs)(`div`,{className:`pws-capacity-recovery`,children:[(0,Y.jsxs)(`span`,{children:[n(`pws.capacity.nextRecovery`),` · `,t,` · `,i]}),(0,Y.jsx)(`strong`,{children:n(`pws.capacity.recoveryShare`,{percent:f(r.nextRecoveryPercent)})})]},e)]:[]}),c&&i&&i.currentAccount?.quota&&(0,Y.jsxs)(`div`,{className:`pws-capacity-current`,children:[(0,Y.jsxs)(`span`,{className:`pws-capacity-label`,children:[n(`pws.capacity.currentAccount`),i.currentAccount.plan?` · ${i.currentAccount.plan}`:``]}),(0,Y.jsx)(xa,{quota:i.currentAccount.quota,threshold:80,t:n,layout:`stacked`})]}),i&&i.incomplete&&i.excludedAccounts>0&&(0,Y.jsx)(`div`,{className:`pws-capacity-incomplete`,children:n(`pws.capacity.incomplete`,{excluded:i.excludedAccounts})}),i&&i.unknownPlanAccounts>0&&(0,Y.jsx)(`div`,{className:`pws-capacity-incomplete`,children:n(`pws.capacity.uncalibratedPlan`,{count:i.unknownPlanAccounts})}),i&&i.partialWindowAccounts>0&&(0,Y.jsx)(`div`,{className:`pws-capacity-incomplete`,children:n(`pws.capacity.partial`,{count:i.partialWindowAccounts})})]})]})}function Aa({sections:e,quotaReports:t,usageTotals:n,usageLoading:r=!1,quotasLoading:i=!1,onSelectProvider:a,onEditConfig:o,onRefreshAllQuotas:s}){let c=Q(),{locale:l}=ut(),u=Pi(c),[d,f]=(0,_.useState)(!1),[p,m]=(0,_.useState)(null),h=async()=>{if(!(!s||d)){f(!0),m(null);try{let e=await s();m({ok:e,text:c(e?`pws.quotaRefreshDone`:`codexAuth.quotaRefreshFailed`)})}catch{m({ok:!1,text:c(`codexAuth.quotaRefreshFailed`)})}finally{f(!1)}}},g=(0,_.useMemo)(()=>[...e.ready,...e.needsSetup,...e.disabled],[e]),v=(0,_.useMemo)(()=>new Set(g.map(e=>e.name)),[g]),y=(0,_.useMemo)(()=>Fi(e,{}),[e]),b=y.length,x=(0,_.useMemo)(()=>e.ready.filter(e=>e.activeNeedsReauth).length,[e]),S=e.ready.length-x,C=e.needsSetup.length+x,w=(0,_.useMemo)(()=>{let e=[];for(let n of g){let r=t[n.name],i=r?qi(r):null,a=r?Xi(r):null;r&&(i||a?.presentation===`coverage-only`)&&e.push({item:n,report:r,urgency:i?pa(i):-1})}return e.sort((e,t)=>t.urgency-e.urgency||e.item.name.localeCompare(t.item.name))},[g,t]),T=(0,_.useMemo)(()=>{let e={};for(let[t,r]of Object.entries(n))v.has(t)&&(e[t]=r);return ji(e).slice(0,4)},[n,v]),E=e=>{let t=Ii(e);return t===`reauth`?c(`pws.attention.reauth`):t===`missing`?c(`pws.attention.missingCredentials`):e};return(0,Y.jsxs)(`div`,{className:`pws-dashboard`,children:[(0,Y.jsxs)(`div`,{className:`pws-dashboard-header`,children:[(0,Y.jsx)(`div`,{className:`pws-dashboard-header-text`,children:(0,Y.jsx)(`h2`,{className:`pws-dashboard-title`,children:c(`pws.dashboard.title`)})}),(0,Y.jsxs)(`div`,{className:`pws-dashboard-header-actions`,children:[p&&(0,Y.jsx)(`span`,{role:`status`,className:p.ok?`pws-status-ok`:`pws-status-warn`,children:p.text}),s&&(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:d,onClick:()=>{h()},children:[(0,Y.jsx)(de,{width:14,height:14,"aria-hidden":`true`}),` `,c(d?`codexAuth.refreshingQuota`:`pws.refreshAllQuotas`)]}),o&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:o,children:c(`prov.editJson`)})]})]}),(0,Y.jsxs)(`div`,{className:`pws-dashboard-summary`,children:[(0,Y.jsx)(ja,{count:S,label:c(`pws.status.ready`),tone:`ok`}),(0,Y.jsx)(ja,{count:C,label:c(x>0?`pws.status.needsAttention`:`pws.status.needsSetup`),tone:`warn`}),(0,Y.jsx)(ja,{count:e.disabled.length,label:c(`prov.disabledBadge`),tone:`muted`})]}),b>0&&(0,Y.jsxs)(`section`,{className:`pws-dashboard-section pws-dashboard-attention`,"aria-label":c(`pws.attentionTitle`),children:[(0,Y.jsxs)(`h3`,{className:`pws-dashboard-section-title`,children:[(0,Y.jsx)(_e,{style:{width:14,height:14},"aria-hidden":`true`}),c(`pws.attentionTitle`)]}),(0,Y.jsx)(`div`,{className:`pws-dashboard-rows`,children:y.map(e=>(0,Y.jsxs)(`button`,{type:`button`,className:`pws-dashboard-row pws-dashboard-row--attention`,onClick:()=>a(e.name),children:[(0,Y.jsx)(ta,{name:e.name,adapter:``,baseUrl:``,cls:`pws-dashboard-row-icon`}),(0,Y.jsxs)(`div`,{className:`pws-dashboard-row-info`,children:[(0,Y.jsx)(`span`,{className:`pws-dashboard-row-name`,children:Ln(e.name,c)}),(0,Y.jsx)(`span`,{className:`pws-dashboard-row-meta muted`,children:E(e.reason)})]}),(0,Y.jsx)(Ce,{className:`pws-dashboard-row-chevron`,"aria-hidden":`true`})]},`${e.name}:${e.reason}`))})]}),(0,Y.jsxs)(`div`,{className:`pws-dashboard-columns`,children:[(0,Y.jsxs)(`section`,{className:`pws-dashboard-section pws-dashboard-section--rate-limits`,"aria-label":c(`pws.dashboard.rateLimits`),"aria-busy":i||void 0,children:[(0,Y.jsx)(`h3`,{className:`pws-dashboard-section-title`,children:c(`pws.dashboard.rateLimits`)}),w.length>0?(0,Y.jsx)(`div`,{className:`pws-dashboard-rows`,children:w.map(({item:e,report:t})=>(0,Y.jsxs)(`button`,{type:`button`,className:`pws-dashboard-row`,onClick:()=>a(e.name),children:[(0,Y.jsx)(ta,{name:e.name,adapter:e.adapter,baseUrl:e.baseUrl,cls:`pws-dashboard-row-icon`}),(0,Y.jsxs)(`div`,{className:`pws-dashboard-row-info`,children:[(0,Y.jsx)(`span`,{className:`pws-dashboard-row-name`,children:Ln(e.name,c)}),(0,Y.jsx)(`span`,{className:`pws-dashboard-row-meta muted`,children:c(`pws.dashboard.checkedAgo`,{time:Ni(t.updatedAt,u)})})]}),(0,Y.jsx)(Ce,{className:`pws-dashboard-row-chevron`,"aria-hidden":`true`}),(0,Y.jsx)(`div`,{className:`pws-dashboard-row-bars`,children:(0,Y.jsx)(ka,{report:t,pending:i&&!t.quota})})]},e.name))}):i?(0,Y.jsx)(`div`,{className:`pws-dashboard-rows pws-dashboard-rows--pending`,"aria-hidden":`true`,children:Array.from({length:3},(e,t)=>(0,Y.jsxs)(`div`,{className:`pws-dashboard-row pws-dashboard-row--skeleton`,children:[(0,Y.jsx)(`span`,{className:`pws-dashboard-row-icon pws-skel`}),(0,Y.jsxs)(`div`,{className:`pws-dashboard-row-info`,children:[(0,Y.jsx)(`span`,{className:`pws-skel pws-skel--name`}),(0,Y.jsx)(`span`,{className:`pws-skel pws-skel--meta`})]}),(0,Y.jsx)(`div`,{className:`pws-dashboard-row-bars`,children:(0,Y.jsx)(xa,{quota:null,threshold:80,t:c,layout:`stacked`,pending:!0})})]},t))}):(0,Y.jsx)(`p`,{className:`muted pws-dashboard-empty`,children:c(`pws.dashboard.noRateLimits`)})]}),(0,Y.jsx)(`section`,{className:`pws-dashboard-section pws-dashboard-section--recent`,"aria-label":c(`pws.dashboard.recentlyUsed`),"aria-busy":r||void 0,children:(0,Y.jsxs)(`details`,{className:`pws-dashboard-recent-details`,children:[(0,Y.jsx)(`summary`,{className:`pws-dashboard-section-title`,children:c(`pws.dashboard.recentlyUsed`)}),T.length>0?(0,Y.jsx)(`div`,{className:`pws-dashboard-rows`,children:T.map(e=>(0,Y.jsxs)(`button`,{type:`button`,className:`pws-dashboard-row`,onClick:()=>a(e.name),children:[(0,Y.jsx)(ta,{name:e.name,adapter:``,baseUrl:``,cls:`pws-dashboard-row-icon`}),(0,Y.jsx)(`span`,{className:`pws-dashboard-row-name`,children:Ln(e.name,c)}),(0,Y.jsx)(`span`,{className:`pws-dashboard-row-count muted`,children:c(`pws.dashboard.requests`,{count:Li(e.requests,l)})}),(0,Y.jsx)(Ce,{className:`pws-dashboard-row-chevron`,"aria-hidden":`true`})]},e.name))}):r?(0,Y.jsx)(`div`,{className:`pws-dashboard-rows pws-dashboard-rows--pending`,"aria-hidden":`true`,children:Array.from({length:3},(e,t)=>(0,Y.jsxs)(`div`,{className:`pws-dashboard-row pws-dashboard-row--skeleton`,children:[(0,Y.jsx)(`span`,{className:`pws-dashboard-row-icon pws-skel`}),(0,Y.jsx)(`span`,{className:`pws-skel pws-skel--name`}),(0,Y.jsx)(`span`,{className:`pws-skel pws-skel--count`})]},t))}):(0,Y.jsx)(`p`,{className:`muted pws-dashboard-empty`,children:c(`pws.dashboard.noUsage`)})]})})]})]})}function ja({count:e,label:t,tone:n}){return(0,Y.jsxs)(`div`,{className:`pws-dashboard-card pws-dashboard-card--${n}`,children:[(0,Y.jsx)(`span`,{className:`pws-dashboard-card-count`,children:e}),(0,Y.jsx)(`span`,{className:`pws-dashboard-card-label`,children:t})]})}function Ma({editor:e,providerName:t,saving:n,onSave:r,message:i}){let a=Q(),o=(0,_.useRef)(null);return(0,_.useEffect)(()=>{e.open&&o.current?.focus()},[e.open]),e.open?(0,Y.jsxs)(`div`,{className:`pwi-json-panel`,children:[(0,Y.jsxs)(`div`,{className:`pwi-json-panel-header`,children:[(0,Y.jsx)(`span`,{className:`pwi-json-panel-title`,children:a(`pws.jsonEditorTitle`,{name:t})}),(0,Y.jsxs)(`div`,{className:`pwi-json-panel-actions`,children:[e.onRestore&&e.isDirty&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:e.onRestore,children:a(`pws.jsonRestore`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:e.onClose,children:a(`common.cancel`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:r,disabled:n||!e.isDirty,children:a(n?`pws.saving`:`pws.jsonSave`)})]})]}),(0,Y.jsx)(`p`,{className:`pwi-json-panel-desc muted`,children:a(`pws.jsonEditorDesc`)}),(0,Y.jsx)(`textarea`,{ref:o,className:`input pwi-json-textarea`,value:e.draft,onChange:t=>e.onDraftChange(t.target.value),spellCheck:!1,rows:20,"aria-label":a(`pws.jsonEditorDesc`)}),i&&(0,Y.jsx)(`div`,{className:i.ok?`pwi-settings-msg pwi-settings-msg--ok`:`pwi-settings-msg pwi-settings-msg--err`,children:i.text})]}):null}function Na(e){if(!(!Pa(e)||!Array.isArray(e.clientIntegrations)))return e.clientIntegrations.filter(e=>Pa(e)&&e.ok===!1).map(e=>({client:typeof e.client==`string`?e.client:``,...Number.isSafeInteger(e.profileId)&&e.profileId>=0?{profileId:e.profileId}:{},...typeof e.reason==`string`?{reason:e.reason}:{},...typeof e.refusalReason==`string`?{refusalReason:e.refusalReason}:{},...typeof e.snapshotPath==`string`?{snapshotPath:e.snapshotPath}:{},...e.residual===!0?{residual:!0}:{}}))}function Pa(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Fa(e){if(!Array.isArray(e)||e.some(e=>typeof e!=`string`))throw Error(`invalid model list`);return[...new Set(e)]}function Ia(e){if(!Pa(e))throw Error(`invalid selected models response`);let t=e.selected;if(!Pa(t))throw Error(`invalid selected models response`);return Object.fromEntries(Object.entries(t).map(([e,t])=>[e,Fa(t)]))}async function La(e,t=fetch,n){let r=await t(`${e}/api/selected-models`,n?{signal:n}:void 0);if(!r.ok)throw Error(`selected models HTTP ${r.status}`);return Ia(await r.json())}function Ra(e,t,n,r=!1){if(r)return!0;let i=e[t];return!i||i.length===0||i.includes(n)}function za(e,t,n,r,i){return Ra(e,t,n,r)&&!i}async function Ba(e,t,n,r,i,a=fetch){return a(`${e}/api/model-visibility`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({scope:t,provider:n,targets:r,enabled:i})})}function Va(e,t){return e===t}function Ha(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Invalid model response`);return e}function Ua(e){if(typeof e!=`string`||!e.trim())throw Error(`Invalid model identity`);return e}function Wa(e){if(!Array.isArray(e))throw Error(`Invalid model inventory`);let t=new Map,n=[];for(let r of e){let e=Ha(r),i=Ua(e.provider),a=Ua(e.id),o=Ua(e.namespaced);if(typeof e.disabled!=`boolean`)throw Error(`Invalid model visibility`);for(let t of[`native`,`custom`,`initialSelectionPending`,`contextCapped`])if(e[t]!==void 0&&typeof e[t]!=`boolean`)throw Error(`Invalid model flag`);if(e.custom===!0&&Ua(e.customId),e.customId!==void 0&&(e.custom!==!0||typeof e.customId!=`string`))throw Error(`Invalid custom ownership`);if(e.custom===!0&&e.native===!0)throw Error(`Conflicting model ownership`);if(e.displayName!==void 0&&typeof e.displayName!=`string`)throw Error(`Invalid model label`);for(let t of[`inputModalities`,`reasoningEfforts`])if(e[t]!==void 0&&(!Array.isArray(e[t])||e[t].some(e=>typeof e!=`string`)))throw Error(`Invalid model metadata`);for(let t of[`contextWindow`,`contextCap`])if(e[t]!==void 0&&(typeof e[t]!=`number`||!Number.isFinite(e[t])))throw Error(`Invalid model context`);let s={...e,provider:i,id:a,namespaced:o,disabled:e.disabled},c=t.get(i)??new Map,l=c.get(o);if(l&&(l.id!==a||l.disabled!==s.disabled||!!l.native!=!!s.native||!!l.custom!=!!s.custom||l.customId!==s.customId||!!l.initialSelectionPending!=!!s.initialSelectionPending))throw Error(`Conflicting model selector`);l||(c.set(o,s),n.push(s)),t.set(i,c)}return n}function Ga(e){let t=new Map;for(let n of e){let e=t.get(n.provider)??new Set;n.disabled||e.add(n.namespaced),t.set(n.provider,e)}return Object.fromEntries([...t].map(([e,t])=>[e,t.size]))}function Ka(e){let t=Ha(e),n=Object.assign(Object.create(null),Ia(t));for(let[e,t]of Object.entries(n))Ua(e),t.forEach(Ua);let r=Object.fromEntries(Object.entries(Ha(t.available)).map(([e,t])=>{if(Ua(e),!Array.isArray(t))throw Error(`Invalid available models`);return[e,t.map(Ua)]})),i=Object.hasOwn(t,`liveModelCounts`)?Ha(t.liveModelCounts):{},a=Object.fromEntries(Object.entries(i).map(([e,t])=>{if(Ua(e),typeof t!=`number`||!Number.isInteger(t)||t<0)throw Error(`Invalid discovery count`);return[e,t]}));return{available:Object.assign(Object.create(null),r),selected:n,liveModelCounts:Object.assign(Object.create(null),a)}}function qa(e){let t=Ha(e);return{id:Ua(t.id),provider:Ua(t.provider),modelId:Ua(t.modelId)}}function Ja(e){if(!Array.isArray(e))throw Error(`Invalid custom model inventory`);let t=new Map,n=new Set;for(let r of e){let e=qa(r),i=JSON.stringify([e.provider,e.modelId]);if(t.has(e.id)||n.has(i))throw Error(`Duplicate custom ownership`);t.set(e.id,e),n.add(i)}return[...t.values()]}function Ya(e,t,n){let r=qa(e);if(r.provider!==t||r.modelId!==n)throw Error(`Unexpected created model`);return r}function Xa(e){if(!e||typeof e!=`object`||Array.isArray(e))return!0;let t=e.catalogRefresh;if(!t||typeof t!=`object`||Array.isArray(t))return!0;let n=t;return n.status!==`committed`||typeof n.changed!=`boolean`||typeof n.degraded!=`boolean`}var Za=[{id:`az`,labelKey:`pws.sort.az`},{id:`za`,labelKey:`pws.sort.za`},{id:`free-paid`,labelKey:`pws.sort.freePaid`},{id:`paid-free`,labelKey:`pws.sort.paidFree`},{id:`accounts-first`,labelKey:`pws.sort.accountsFirst`}];function Qa(e){return Vi(Tr(e))}function $a({providers:e,apiBase:t,defaultProvider:n,selectedName:r,onSelect:i,onRemoveProvider:a,onAddProvider:o,onEditConfig:s,jsonEditor:c,jsonSaving:l=!1,modelsRefreshToken:u=0,onModelsSettled:d,activeAccountNeedsReauth:f,quotaRefreshEpoch:p=0,quotaForceRefresh:m=!1,onQuotaRefreshSettled:h,onRefreshAllQuotas:g,detail:v}){let y=Q(),[b,x]=(0,_.useState)(``),[S,C]=(0,_.useState)({ready:!0,needsSetup:!0,disabled:!0}),[w,T]=(0,_.useState)({free:!0,paid:!0}),[E,D]=(0,_.useState)({cloud:!0,local:!0,selfHosted:!0,login:!0}),[O,k]=(0,_.useState)(`az`),[A,j]=(0,_.useState)(!1),[M,N]=(0,_.useState)(null),[P,F]=(0,_.useState)(null),[I,L]=(0,_.useState)(!1),[R,z]=(0,_.useState)(!1),B=`ocx.providers.quotas.v1:${t}`,V=`ocx.providers.usage.v2:${t}`,[H,U]=(0,_.useState)(()=>Kn(Tr(V))),[W,G]=(0,_.useState)(()=>Tr(V)?.totals??{}),[q,J]=(0,_.useState)(()=>Tr(V)?.models??{}),[X,ee]=(0,_.useState)(()=>Qa(B)??{}),[te,ne]=(0,_.useState)(()=>!Tr(V)),[Z,re]=(0,_.useState)(()=>{let e=Qa(B);return!e||Object.keys(e).length===0}),[ie,ae]=(0,_.useState)(0),oe=JSON.stringify([t,u,ie]),se=P?.revision===oe&&!I&&!R,ce=(0,_.useMemo)(()=>Ga(P?.rows??[]),[P]),le=(0,_.useRef)(d);(0,_.useEffect)(()=>{le.current=d},[d]);let ue=(0,_.useRef)(null),de=K(qn(t),[t],async e=>{let n=await fetch(t+`/api/usage?range=30d`,{signal:e});if(!n.ok)throw Error(String(n.status));return await n.json()},{deadlineMs:6e4}),fe=(0,_.useMemo)(()=>Ci(Si(Ti(e)),f??{}),[e,f]),pe=(0,_.useCallback)(()=>{L(!0),z(!1),ae(e=>e+1)},[]);(0,_.useEffect)(()=>{let e=!1,n=Xn(6e4),r=window.setTimeout(()=>{L(!0),(async()=>{let r=!1;try{let[i,a]=await Promise.all([fetch(`${t}/api/selected-models`,{signal:n.signal}).then(It).then(Ka),fetch(`${t}/api/models`,{signal:n.signal}).then(It).then(Wa)]);if(e)return;F({revision:oe,selection:i,rows:a}),z(!1),r=!0}catch{if(e)return;z(!0)}finally{n.controller.abort(),n.clear(),e||(L(!1),le.current?.(r))}})()},0);return()=>{e=!0,window.clearTimeout(r),n.controller.abort(),n.clear()}},[t,oe]),(0,_.useEffect)(()=>{let e=!1,t=window.setTimeout(()=>{let t=de.data;if(e)return;if(!t){de.loading&&ne(!Tr(V));return}let n=ki(t.providers??[]);G(n);let r=Ai(t.models??[],n);J(r);let i=Kn(t);U(i),kr(V,{totals:n,models:r,...i}),ne(!1)},0);return()=>{e=!0,window.clearTimeout(t)}},[t,V,de.data,de.loading]),(0,_.useEffect)(()=>{let e=!1,n=window.setTimeout(()=>{let n=Qa(B);(!n||Object.keys(n).length===0)&&re(!0);let i=Xn(2e4);r=()=>{i.controller.abort(),i.clear()},fetch(`${t}/api/provider-quotas${m?`?refresh=1`:``}`,{signal:i.signal}).then(e=>Lt(e)).then(t=>{if(e)return;if(!t){m&&h?.(!1,p);return}let n=Hi(t.reports);ee(n),kr(B,n),m&&h?.(!0,p)}).catch(()=>{e||(ee(e=>{let t=Vi(e)??{};return kr(B,t),t}),m&&h?.(!1,p))}).finally(()=>{i.clear(),e||re(!1)})},0),r;return()=>{e=!0,window.clearTimeout(n),r?.()}},[t,p,m,B,h]),(0,_.useEffect)(()=>{if(!A)return;let e=e=>{ue.current&&!ue.current.contains(e.target)&&j(!1)},t=e=>{e.key===`Escape`&&j(!1)};return document.addEventListener(`mousedown`,e),window.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),window.removeEventListener(`keydown`,t)}},[A]);let he=(0,_.useMemo)(()=>[...fe.ready,...fe.needsSetup,...fe.disabled],[fe]),ge=(0,_.useMemo)(()=>he.filter(yi).length,[he]),_e=he.length-ge,ve=(0,_.useMemo)(()=>{let e={cloud:0,local:0,selfHosted:0,login:0};for(let t of he)e[Oi(t)]+=1;return e},[he]),be=(0,_.useMemo)(()=>{let e=b.trim().toLowerCase(),t=t=>xi(t.filter(t=>{if(e&&!t.name.toLowerCase().includes(e)&&!t.adapter.toLowerCase().includes(e))return!1;let n=yi(t);return!(n&&!w.free||!n&&!w.paid||!E[Oi(t)])}),O);return{ready:S.ready?t(fe.ready):[],needsSetup:S.needsSetup?t(fe.needsSetup):[],disabled:S.disabled?t(fe.disabled):[]}},[fe,b,S,w,E,O]),xe=!S.ready||!S.needsSetup||!S.disabled||!w.free||!w.paid||!E.cloud||!E.local||!E.selfHosted||!E.login||O!==`az`,Se=()=>{C({ready:!0,needsSetup:!0,disabled:!0}),T({free:!0,paid:!0}),D({cloud:!0,local:!0,selfHosted:!0,login:!0}),k(`az`)},Ce=(0,_.useMemo)(()=>r?he.find(e=>e.name===r)??null:null,[r,he]),we=(0,_.useMemo)(()=>{let e=new Map;for(let t of he){let n=Ln(t.name,y);e.set(n,(e.get(n)??0)+1)}let t=new Set;for(let[n,r]of e.entries())r>1&&t.add(n);return t},[he,y]);if(he.length===0)return(0,Y.jsx)(eo,{onAddProvider:o});let Te=[{key:`ready`,label:y(`pws.status.ready`),count:fe.ready.length},{key:`needsSetup`,label:y(`pws.status.needsSetup`),count:fe.needsSetup.length},{key:`disabled`,label:y(`prov.disabledBadge`),count:fe.disabled.length}],Ee=[{id:`ready`,label:y(`pws.status.ready`),count:be.ready.length,ariaLabel:y(`pws.groupReady`,{count:be.ready.length}),items:be.ready},{id:`needs-setup`,label:y(`pws.status.needsSetup`),count:be.needsSetup.length,ariaLabel:y(`pws.groupNeedsSetup`,{count:be.needsSetup.length}),items:be.needsSetup},{id:`disabled`,label:y(`prov.disabledBadge`),count:be.disabled.length,ariaLabel:y(`pws.groupDisabled`,{count:be.disabled.length}),items:be.disabled}],De=Ee.flatMap(e=>e.items.map(e=>e.name)),Oe=M&&De.includes(M)?M:r&&De.includes(r)?r:De[0]??null;return(0,Y.jsx)(`div`,{className:`pws-shell-container`,children:(0,Y.jsxs)(`div`,{className:`pws-root`,children:[(0,Y.jsxs)(`aside`,{className:`pws-rail`,"aria-label":y(`pws.providerList`),children:[(0,Y.jsxs)(`div`,{className:`pws-search-row`,children:[(0,Y.jsxs)(`div`,{className:`pws-search-wrap`,children:[(0,Y.jsx)(ye,{className:`pws-search-icon`,width:14,height:14,"aria-hidden":`true`}),(0,Y.jsx)(`input`,{type:`search`,className:`input pws-search-input`,placeholder:y(`pws.searchPlaceholder`),value:b,onChange:e=>x(e.target.value),"aria-label":y(`pws.searchPlaceholder`)})]}),(0,Y.jsxs)(`div`,{className:`pws-filter-wrap`,ref:ue,children:[(0,Y.jsxs)(`button`,{type:`button`,className:`pws-filter-btn${xe||A?` pws-filter-btn--active`:``}`,onClick:()=>j(e=>!e),"aria-label":y(`pws.filterAria`),"aria-expanded":A,"aria-controls":`pws-provider-filters`,children:[(0,Y.jsx)(ze,{width:18,height:18,"aria-hidden":`true`}),xe&&(0,Y.jsx)(`span`,{className:`pws-filter-dot`,"aria-hidden":`true`})]}),A&&(0,Y.jsxs)(`div`,{id:`pws-provider-filters`,className:`pws-filter-menu`,role:`group`,"aria-label":y(`pws.providerFiltersAria`),children:[(0,Y.jsx)(`div`,{className:`pws-filter-title`,children:y(`pws.filters`)}),(0,Y.jsx)(`div`,{className:`pws-filter-head`,children:y(`pws.filterStatus`)}),Te.map(({key:e,label:t,count:n})=>(0,Y.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,Y.jsx)(`input`,{type:`checkbox`,checked:S[e],onChange:()=>C(t=>({...t,[e]:!t[e]}))}),(0,Y.jsx)(`span`,{className:`pws-filter-label`,children:t}),(0,Y.jsx)(`span`,{className:`pws-filter-count`,children:n})]},e)),(0,Y.jsx)(`div`,{className:`pws-filter-head`,children:y(`pws.pricing`)}),(0,Y.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,Y.jsx)(`input`,{type:`checkbox`,checked:w.free,onChange:()=>T(e=>({...e,free:!e.free}))}),(0,Y.jsx)(`span`,{className:`pws-filter-label`,children:y(`modal.badge.free`)}),(0,Y.jsx)(`span`,{className:`pws-filter-count`,children:ge})]}),(0,Y.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,Y.jsx)(`input`,{type:`checkbox`,checked:w.paid,onChange:()=>T(e=>({...e,paid:!e.paid}))}),(0,Y.jsx)(`span`,{className:`pws-filter-label`,children:y(`pws.paid`)}),(0,Y.jsx)(`span`,{className:`pws-filter-count`,children:_e})]}),(0,Y.jsx)(`div`,{className:`pws-filter-head`,children:y(`pws.filterType`)}),[{key:`cloud`,label:y(`pws.type.cloud`),count:ve.cloud},{key:`local`,label:y(`pws.type.local`),count:ve.local},{key:`selfHosted`,label:y(`pws.type.selfHosted`),count:ve.selfHosted},{key:`login`,label:y(`pws.type.login`),count:ve.login}].map(({key:e,label:t,count:n})=>(0,Y.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,Y.jsx)(`input`,{type:`checkbox`,checked:E[e],onChange:()=>D(t=>({...t,[e]:!t[e]}))}),(0,Y.jsx)(`span`,{className:`pws-filter-label`,children:t}),(0,Y.jsx)(`span`,{className:`pws-filter-count`,children:n})]},e)),(0,Y.jsx)(`div`,{className:`pws-filter-head`,children:y(`pws.sort`)}),(0,Y.jsx)(`div`,{className:`pws-sort-grid`,role:`group`,"aria-label":y(`pws.sortProvidersAria`),children:Za.map(e=>(0,Y.jsx)(`button`,{type:`button`,className:`pws-sort-btn${O===e.id?` pws-sort-btn--active`:``}`,onClick:()=>k(e.id),"aria-pressed":O===e.id,children:y(e.labelKey)},e.id))}),(0,Y.jsx)(`div`,{className:`pws-filter-footer`,children:(0,Y.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:Se,disabled:!xe,children:y(`pws.resetAll`)})})]})]})]}),(0,Y.jsxs)(`div`,{className:`pws-rail-list`,role:`listbox`,"aria-label":y(`pws.providersAria`),onKeyDown:e=>{let t=Array.from(e.currentTarget.querySelectorAll(`[role="option"]`));if(t.length===0)return;let n=document.activeElement,r=t.findIndex(e=>e===n||e.contains(n));if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault();let n=e.key===`ArrowDown`?1:-1;t[r<0?n>0?0:t.length-1:(r+n+t.length)%t.length]?.focus();return}if(e.key===`Home`){e.preventDefault(),t[0]?.focus();return}e.key===`End`&&(e.preventDefault(),t[t.length-1]?.focus())},children:[Object.values(be).every(e=>e.length===0)&&(0,Y.jsx)(`span`,{className:`muted pws-rail-empty`,role:`status`,children:y(b?`pws.noSearchResults`:xe?`pws.noMatchFilters`:`pws.noProvidersConfigured`)}),Ee.map(({id:e,label:t,count:o,ariaLabel:s,items:c})=>c.length===0?null:(0,Y.jsxs)(`div`,{className:`pws-rail-group`,role:`group`,"aria-label":s,children:[(0,Y.jsxs)(`div`,{className:`pws-rail-group-head`,"aria-hidden":`true`,children:[(0,Y.jsx)(`span`,{className:`pws-rail-group-label`,children:t}),(0,Y.jsx)(`span`,{className:`pws-rail-group-count`,children:o})]}),c.map(e=>(0,Y.jsxs)(`div`,{className:`pws-rail-row-wrap`,children:[(0,Y.jsx)(ra,{item:e,selected:r===e.name,tabbable:Oe===e.name,modelCount:P?Object.hasOwn(ce,e.name)?ce[e.name]:0:void 0,isDefault:n===e.name,showConfigId:we.has(Ln(e.name,y)),onClick:()=>i(e.name),onFocus:()=>N(e.name)}),a&&(0,Y.jsx)(`button`,{type:`button`,className:`pws-rail-row-remove`,tabIndex:-1,"aria-hidden":`true`,onClick:t=>{t.stopPropagation(),a(e.name)},title:y(`pws.removeConfirmTitle`),children:(0,Y.jsx)(me,{width:14,height:14})})]},e.name))]},e))]})]}),(0,Y.jsxs)(`main`,{className:`pws-main`,"aria-label":y(`pws.workspaceMainAria`),children:[!c?.open&&(0,Y.jsx)(Jn,{data:H}),c?.open?(0,Y.jsx)(Ma,{editor:c,providerName:y(`nav.providers`),saving:l,onSave:()=>{c.onSave()}}):Ce?v?.(Ce,{usageTotals:W[Ce.name],modelUsage:q[Ce.name],quotaReport:X[Ce.name],availableModels:P?.selection.available[Ce.name]??[],hasLiveModels:(P?.selection.liveModelCounts[Ce.name]??0)>0,selectedModels:P?.selection.selected[Ce.name]??[],modelRows:P?.rows.filter(e=>e.provider===Ce.name)??null,modelRevision:oe,modelRowsReady:se,modelsLoading:I||!se&&!R,modelsLoadFailed:R,onRetryModels:pe})??(0,Y.jsxs)(`div`,{className:`pws-detail-placeholder`,children:[(0,Y.jsx)(`h3`,{children:Ln(Ce.name,y)}),(0,Y.jsx)(`p`,{className:`muted`,children:y(`pws.detailComingSoon`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>i(null),children:y(`modal.back`)})]}):(0,Y.jsx)(Aa,{sections:fe,quotaReports:X,usageTotals:W,usageLoading:te,quotasLoading:Z,onSelectProvider:e=>i(e),onEditConfig:s,...g?{onRefreshAllQuotas:g}:{}})]})]})})}function eo({onAddProvider:e}){let t=Q();return(0,Y.jsx)(`div`,{className:`pws-empty-root`,children:(0,Y.jsxs)(`div`,{className:`pws-empty-hero`,children:[(0,Y.jsx)(`div`,{"aria-hidden":`true`,children:(0,Y.jsx)(ne,{style:{width:64,height:64}})}),(0,Y.jsx)(`h2`,{children:t(`pws.connectFirst`)}),(0,Y.jsxs)(`div`,{className:`pws-empty-tiles`,children:[(0,Y.jsxs)(`button`,{type:`button`,className:`pws-empty-tile`,onClick:()=>e({tier:`free`}),children:[(0,Y.jsx)(`span`,{"aria-hidden":`true`,children:(0,Y.jsx)(Fe,{width:18,height:18})}),(0,Y.jsx)(`span`,{className:`pws-empty-tile-label`,children:t(`pws.empty.browseFree`)}),(0,Y.jsx)(`span`,{className:`pws-empty-tile-desc muted`,children:t(`pws.empty.browseFreeDesc`)})]}),(0,Y.jsxs)(`button`,{type:`button`,className:`pws-empty-tile`,onClick:()=>e({tier:`accounts`}),children:[(0,Y.jsx)(`span`,{"aria-hidden":`true`,children:(0,Y.jsx)(ke,{width:18,height:18})}),(0,Y.jsx)(`span`,{className:`pws-empty-tile-label`,children:t(`pws.empty.connectAccount`)}),(0,Y.jsx)(`span`,{className:`pws-empty-tile-desc muted`,children:t(`pws.empty.connectAccountDesc`)})]}),(0,Y.jsxs)(`button`,{type:`button`,className:`pws-empty-tile`,onClick:()=>e({custom:!0}),children:[(0,Y.jsx)(`span`,{"aria-hidden":`true`,children:(0,Y.jsx)(De,{width:18,height:18})}),(0,Y.jsx)(`span`,{className:`pws-empty-tile-label`,children:t(`pws.empty.addEndpoint`)}),(0,Y.jsx)(`span`,{className:`pws-empty-tile-desc muted`,children:t(`pws.empty.addEndpointDesc`)})]})]})]})})}function to(e){if(vi(e.name,e))return`codex-accounts`;let t=(e.authMode??``).toLowerCase();if(t===`forward`||t===`local`||Ei(e))return null;if(t===`oauth`)return`oauth-accounts`;let n=e.hasApiKey===!0;return!(t===`key`||n||t===``)||e.keyOptional===!0&&!n?null:`api-keys`}function no(e,t,n){let r=t.alias?.trim();if(r)return r;let i=t.email?.trim();if(i)return i;let a=e.findIndex(e=>e.id===t.id);return n(`pws.accountOrdinal`,{count:String(a>=0?a+1:1)})}var ro=18e5,io=[`account_unavailable`,`access_denied`,`rate_limited`,`upstream_error`,`redirect_blocked`,`destination_blocked`,`dns_failed`,`timeout`,`transport_error`,`response_unusable`];function ao(e){return io.find(t=>t===e)}function oo({quota:e,quotaMode:t,quotaUnavailable:n,quotaPending:r,quotaFailure:i}){let a=Q(),o=qi({quota:e});if(t===`unsupported`)return(0,Y.jsx)(`p`,{className:`muted`,"data-quota-state":`unsupported`,children:a(`pws.quotaUnsupported`)});let s=t===`probe`&&n?ao(i):void 0,c=t===`probe`&&r===!0;return(0,Y.jsxs)(`div`,{"data-quota-state":n?`unavailable`:c?`pending`:o?`ready`:t===`passive`?`unobserved`:`unknown`,children:[n&&(0,Y.jsx)(`p`,{className:`muted pwi-auth-acct-quota-stale`,children:a(s?`pws.quotaFailure.${s}`:`pws.accountQuotaUnavailable`)}),o||c?(0,Y.jsx)(ka,{report:{quota:o,updatedAt:o?.updatedAt,...t===`passive`?{observed:!0}:{}},pending:c&&!o}):!n&&(0,Y.jsx)(`p`,{className:`muted`,children:a(t===`passive`?`pws.quotaUnobserved`:`pws.quotaUnavailable`)}),n&&o&&(0,Y.jsxs)(`p`,{className:`muted`,children:[a(`pws.stats.quotaUpdated`),`: `,Ni(o.updatedAt,Pi(a))]})]})}function so({report:e,reading:t,onRefreshQuota:n}){let r=Q(),i=Ji(e),a=t!==void 0&&(t.quotaMode!==void 0||t.quota!==void 0||t.quotaUnavailable!==void 0||t.quotaPending!==void 0),o=a?t:{quota:qi(i),...i?.observed===!0?{quotaMode:`passive`}:{}},s=qi({quota:o.quota}),[c,l]=(0,_.useState)(!1),[u,d]=(0,_.useState)(null),f=async()=>{if(!(!n||c)){l(!0),d(null);try{d(await n())}catch{d(!1)}finally{l(!1)}}};return(0,Y.jsxs)(`section`,{className:`pws-usage-block`,"aria-label":r(`pws.currentAccountUsage`),children:[(0,Y.jsxs)(`div`,{className:`pws-usage-block-head`,children:[(0,Y.jsx)(`h3`,{className:`pws-section-title`,children:r(`pws.currentAccountUsage`)}),n&&o.quotaMode!==`unsupported`&&(0,Y.jsxs)(`div`,{className:`pws-quota-refresh`,children:[u!==null&&(0,Y.jsx)(`span`,{role:`status`,className:u?`pws-status-ok`:`pws-status-warn`,children:r(u?`pws.quotaCheckCompleted`:`codexAuth.quotaRefreshFailed`)}),(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:c,onClick:()=>{f()},children:[(0,Y.jsx)(de,{width:14,height:14,"aria-hidden":`true`}),` `,r(c?`codexAuth.refreshingQuota`:`codexAuth.refreshQuota`)]})]})]}),(0,Y.jsx)(oo,{...o}),s&&!o.quotaUnavailable&&o.quotaMode!==`unsupported`&&(0,Y.jsxs)(`dl`,{className:`pws-kv pws-usage-meta`,children:[!a&&i?.source?.trim()&&(0,Y.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Y.jsx)(`dt`,{children:r(`pws.stats.source`)}),(0,Y.jsx)(`dd`,{children:Zi(i.source)})]}),(0,Y.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Y.jsx)(`dt`,{children:r(`pws.stats.quotaUpdated`)}),(0,Y.jsx)(`dd`,{children:Ni(s.updatedAt,Pi(r))})]})]})]})}function co(e,t){let n=e=>{try{let t=new URL(e.trim());return t.username||t.password||t.search||t.hash?void 0:`${t.origin}${t.pathname.replace(/\/+$/,``)}`}catch{return}},r=n(e.baseUrl);if(r)return t.find(t=>t.id===e.name&&t.adapter===e.adapter&&n(t.baseUrl)===r)}function lo(e){return{adapter:e.adapter,baseUrl:e.baseUrl,authMode:e.auth,freeTier:!!e.freeTier,keyOptional:!!e.keyOptional}}function uo(e){return bi(e.id,lo(e))}function fo(e){return Ei(lo(e))}function po(e){let t={accounts:[],free:[],local:[],paid:[]};for(let n of e){let e=uo(n);t[e===`accounts`?`accounts`:fo(n)?`local`:e].push(n)}return t}function mo(e){return!!e?.trim()}var ho=new Set([`local`,`localhost`,`ollama`,`vllm`,`lmstudio`,`lm studio`,`self-hosted`,`selfhosted`]);function go(e,t){let n=t.trim().toLowerCase();return!n||e.label.toLowerCase().includes(n)||e.id.toLowerCase().includes(n)||e.adapter.toLowerCase()===n?!0:ho.has(n)&&fo(e)}function _o(e,t){let n=t.trim().toLowerCase();if(!n)return e;let r=e=>{let t=e.label.toLowerCase(),r=e.id.toLowerCase();return r===n||t===n?0:t.startsWith(n)||r.startsWith(n)?1:2};return e.map((e,t)=>({preset:e,index:t})).sort((e,t)=>r(e.preset)-r(t.preset)||e.index-t.index).map(e=>e.preset)}function vo(e,t,n){let r=t.trim().toLowerCase();return r?e.filter(e=>e.id===n||e.label.toLowerCase().includes(r)||e.id.toLowerCase().includes(r)):[...e]}function yo(e,t){if(t.length===0)return e;let n=new Set(t.map(e=>e.id));return e.filter(e=>!n.has(e.id))}var bo={main:0,standard:1};function xo(e){let t=e.filter(e=>e.sponsor);return t.length===0?e:(t.sort((e,t)=>bo[e.sponsor]-bo[t.sponsor]||e.label.localeCompare(t.label,void 0,{sensitivity:`base`})||e.id.localeCompare(t.id)),[...t,...e.filter(e=>!e.sponsor)])}function So(e){if(e)try{let t=new URL(e);return(t.protocol===`https:`||t.protocol===`http:`)&&!t.username&&!t.password?e:void 0}catch{return}}function Co({item:e,preset:t}){let n=Q();if(!t?.sponsor||!co(e,[t]))return null;let r=t.id===`orcarouter`||t.id===`orcarouter-oauth`?`OrcaRouter`:t.id===`packycode`?`PackyCode`:void 0;if(!r)return null;let i=r===`OrcaRouter`,a=So(t.sponsorUrl),o=So(t.dashboardUrl);return(0,Y.jsxs)(`section`,{className:`pws-sponsor`,"aria-label":`${r} · ${n(`modal.badge.sponsor`)}`,children:[(0,Y.jsxs)(`div`,{className:`pws-sponsor-copy`,children:[(0,Y.jsxs)(`div`,{className:`pws-sponsor-byline`,children:[(0,Y.jsx)(`span`,{children:r}),(0,Y.jsx)(`span`,{className:`pws-sponsor-badge`,children:n(`modal.badge.sponsor`)})]}),(0,Y.jsx)(`h3`,{children:n(i?`pws.sponsor.orcaTitle`:`pws.sponsor.packyTitle`)}),(0,Y.jsx)(`p`,{children:n(i?`pws.sponsor.orcaDescription`:`pws.sponsor.packyDescription`)})]}),(a||o)&&(0,Y.jsxs)(`div`,{className:`pws-sponsor-actions`,children:[a&&(0,Y.jsxs)(`a`,{className:`btn btn-primary`,href:a,target:`_blank`,rel:`noopener noreferrer`,children:[n(`pws.sponsor.visit`,{provider:r}),(0,Y.jsx)(Ee,{width:14,height:14,"aria-hidden":`true`})]}),o&&o!==a&&(0,Y.jsxs)(`a`,{className:`pws-sponsor-console`,href:o,target:`_blank`,rel:`noopener noreferrer`,children:[n(`pws.sponsor.console`),(0,Y.jsx)(Ee,{width:13,height:13,"aria-hidden":`true`})]})]})]})}function wo({item:e,preset:t,usageTotals:n,quotaReport:r,currentQuotaReading:i,onRefreshQuota:a,oauthEmail:o,oauth:s,apiBase:c,connectionIdentity:l,onEditSettings:u,onViewUsage:d,onUpdateProvider:f,onReauthenticate:p,onCancelLogin:m,reauthBusy:h=!1}){let g=Q(),{locale:v}=ut(),y=wi(e),b=!!e.activeNeedsReauth,x=g(y===`ready`?`pws.status.connected`:y===`needs-setup`?b?`pws.status.needsAttention`:`pws.status.needsSetup`:`prov.disabledBadge`),S=n?.requests,C=n?.totalTokens,w=JSON.stringify([c??null,e.name,e.adapter,e.baseUrl,e.authMode??null,e.apiKeyTransport??null,e.liveModels??null,e.disabled===!0,e.hasApiKey===!0,e.hasHeaders===!0,e.allowPrivateNetwork===!0,e.keyOptional===!0,e.activeNeedsReauth===!0,l??null]),[T,E]=(0,_.useState)(null),D=(0,_.useRef)(null),O=T?.key===w&&T.testing,k=T?.key===w?T.result:null;(0,_.useEffect)(()=>()=>{D.current?.key===w&&(D.current.controller.abort(),D.current=null)},[w]);let A=(0,_.useCallback)(async()=>{if(!c)return;D.current?.controller.abort();let t=new AbortController;D.current={key:w,controller:t},E({key:w,testing:!0,result:null});try{let n=await It(await fetch(`${c}/api/providers/test?name=${encodeURIComponent(e.name)}`,{method:`POST`,signal:t.signal}),g(`pws.connectionFailed`));if(!n)throw Error(g(`pws.connectionFailed`));t.signal.aborted||E({key:w,testing:!1,result:n})}catch(e){t.signal.aborted||E({key:w,testing:!1,result:{applicable:!0,ok:!1,error:e instanceof Error?e.message:g(`pws.connectionFailed`)}})}finally{D.current?.controller===t&&(D.current=null)}},[c,w,e.name,g]),j=k?.applicable===!1?`not-applicable`:k?.ok===!0?`ok`:`failed`,M=k?.applicable===!1?g(`pws.connectionNotApplicable`):k?.ok===!0?k.message||g(`pws.connectionOk`):k?.error||g(`pws.connectionFailed`);return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(Co,{item:e,preset:t}),(0,Y.jsxs)(`div`,{className:`pws-overview-layout`,children:[(0,Y.jsxs)(`div`,{className:`pws-overview-main`,children:[(0,Y.jsxs)(`section`,{className:`pws-section`,"aria-label":g(`pws.connection`),children:[(0,Y.jsx)(`h3`,{className:`pws-section-title`,children:g(`pws.connection`)}),(0,Y.jsxs)(`dl`,{className:`pws-kv`,children:[(0,Y.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Y.jsx)(`dt`,{children:g(`dash.status`)}),(0,Y.jsxs)(`dd`,{className:y===`ready`?`pws-status-ok`:`pws-status-warn`,children:[y===`ready`?(0,Y.jsx)(ce,{style:{width:13,height:13},"aria-hidden":`true`}):(0,Y.jsx)(_e,{style:{width:13,height:13},"aria-hidden":`true`}),x]})]}),(0,Y.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Y.jsx)(`dt`,{children:g(`modal.baseUrl`)}),(0,Y.jsx)(`dd`,{children:(0,Y.jsx)(`code`,{children:e.baseUrl?.trim()?e.baseUrl:`—`})})]}),(0,Y.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Y.jsx)(`dt`,{children:g(`pws.cell.auth`)}),(0,Y.jsx)(`dd`,{children:o?`${$i(e,g)} · ${o}`:$i(e,g)})]}),(0,Y.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Y.jsx)(`dt`,{children:g(`modal.defaultModel`)}),(0,Y.jsx)(`dd`,{children:e.defaultModel??(0,Y.jsx)(`span`,{className:`muted`,children:`—`})})]})]}),c&&(0,Y.jsxs)(`div`,{className:`row`,style:{marginTop:12,alignItems:`center`},children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:O,onClick:()=>void A(),children:g(O?`pws.testing`:`pws.testConnection`)}),k&&(0,Y.jsx)(`span`,{role:`status`,className:j===`ok`?`pws-status-ok`:j===`failed`?`pws-status-warn`:`muted`,"data-connection-test-state":j,children:M})]}),u&&(0,Y.jsx)(`button`,{type:`button`,className:`link-btn pws-edit-settings-link`,onClick:u,children:g(`pws.editSettings`)})]}),(0,Y.jsxs)(`section`,{className:`pws-section`,"aria-label":g(`pws.authSummary`),children:[(0,Y.jsx)(`h3`,{className:`pws-section-title`,children:g(`pws.authSummary`)}),b?(0,Y.jsxs)(`div`,{className:`pws-auth-summary pws-auth-summary--warn`,role:`status`,children:[(0,Y.jsx)(_e,{style:{width:14,height:14},"aria-hidden":`true`}),(0,Y.jsxs)(`div`,{className:`pws-auth-summary-body`,children:[(0,Y.jsxs)(`span`,{children:[(0,Y.jsx)(`strong`,{children:g(`pws.status.needsAttention`)}),` — `,e.authMode===`forward`?g(`pws.attention.reauthForward`):g(`pws.attention.reauth`)]}),p&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:h,onClick:()=>p(),children:g(h?`prov.waitingBrowser`:`pws.reauthenticate`)}),h&&m&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>m(),children:g(`common.cancel`)})]})]}):(0,Y.jsxs)(`div`,{className:`pws-auth-summary`,children:[(0,Y.jsx)(`span`,{className:`pws-auth-dot`}),(0,Y.jsx)(`span`,{children:e.authMode===`forward`?g(`pws.passthrough`):e.authMode===`oauth`?o?g(`pws.loggedInAs`,{email:o}):s?.loggedIn?g(`pws.loggedInTitle`):g(`pws.notLoggedIn`):e.hasApiKey?g(`pws.apiKeyConfigured`):$i(e,g)})]})]}),(0,Y.jsx)(To,{item:e,onUpdateProvider:f})]}),(0,Y.jsxs)(`aside`,{className:`pws-overview-sidebar`,children:[(0,Y.jsxs)(`section`,{className:`pws-section`,"aria-label":g(`pws.statsAria`),children:[(0,Y.jsx)(`h3`,{className:`pws-section-title`,children:g(`pws.statsTitle`)}),(0,Y.jsxs)(`dl`,{className:`pws-kv`,children:[typeof S==`number`&&(0,Y.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Y.jsx)(`dt`,{children:g(`pws.stats.totalRequests`)}),(0,Y.jsx)(`dd`,{className:`pws-kv-mono`,children:Li(S,v)})]}),typeof C==`number`&&(0,Y.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Y.jsx)(`dt`,{children:g(`pws.stats.totalTokens`)}),(0,Y.jsx)(`dd`,{className:`pws-kv-mono`,children:Ri(C,v)})]}),typeof S!=`number`&&typeof C!=`number`&&(0,Y.jsx)(`div`,{className:`muted`,children:g(`pws.usageUnavailable`)})]}),d&&(0,Y.jsxs)(`button`,{type:`button`,className:`link-btn pws-view-usage-link`,onClick:d,children:[g(`pws.viewUsage`),` →`]})]}),(0,Y.jsx)(so,{report:r,reading:i,onRefreshQuota:a},`${e.name}:${l??``}`)]})]})]})}function To({item:e,onUpdateProvider:t}){let n=Q(),[r,i]=(0,_.useState)(!1),[a,o]=(0,_.useState)(``),[s,c]=(0,_.useState)(!1),[l,u]=(0,_.useState)(``),d=(0,_.useRef)(null);(0,_.useEffect)(()=>{r&&d.current?.focus()},[r]);let f=(0,_.useCallback)(async()=>{if(s||!t)return;let r=a.trim();if(r===(e.note??``)){i(!1),u(``);return}c(!0);try{let a=await t(e.name,{note:r||void 0});if(!a.ok){u(a.error||n(`prov.saveFailed`));return}u(``),i(!1)}finally{c(!1)}},[a,e.name,e.note,t,s,n]);return r?(0,Y.jsxs)(`section`,{className:`pws-section pws-notes-section`,"aria-label":n(`pws.notes`),children:[(0,Y.jsx)(`h3`,{className:`pws-section-title`,children:n(`pws.notes`)}),(0,Y.jsx)(`textarea`,{ref:d,className:`pws-notes-textarea`,value:a,onChange:e=>o(e.target.value),onBlur:()=>void f(),onKeyDown:t=>{t.key===`Escape`&&(o(e.note??``),u(``),i(!1))},placeholder:n(`pws.notePlaceholder`),rows:3,disabled:s}),l?(0,Y.jsx)(`p`,{className:`pws-inline-error`,role:`alert`,children:l}):null]}):(0,Y.jsxs)(`section`,{className:`pws-section pws-notes-section`,"aria-label":n(`pws.notes`),children:[(0,Y.jsx)(`h3`,{className:`pws-section-title`,children:n(`pws.notes`)}),(0,Y.jsx)(`button`,{type:`button`,className:`pws-notes-display`,onClick:()=>{t&&(o(e.note??``),u(``),i(!0))},disabled:!t,children:e.note||(0,Y.jsx)(`span`,{className:`muted`,children:n(`pws.notePlaceholder`)})})]})}function Eo(e,t){switch(t.reason){case`http`:return e(`models.discoveryFailedHttp`,{status:t.httpStatus});case`blocked`:return e(`models.discoveryFailedBlocked`);case`invalid_response`:return e(`models.discoveryFailedInvalidResponse`);case`network`:return e(`models.discoveryFailedNetwork`);case`provider`:return e(`models.discoveryFailedProvider`);default:return e(`models.discoveryFailedGeneric`)}}function Do(e){return e.some(e=>e.pricingStatus!==void 0)}function Oo(e,t){return t?e.filter(e=>e.pricingStatus===`free`):[...e]}function ko(e,t){return e&&Do(t)}function Ao(e){return[...e].some(e=>{let t=e.codePointAt(0);return t<=31||t>=127&&t<=159||t===8232||t===8233})}function jo(e){let t=e.trim();return t?t.length>128?`models.displayNameTooLong`:t.includes(`/`)?`models.displayNameNoSlash`:Ao(t)?`models.displayNameNoControl`:null:`models.displayNameRequired`}var Mo=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`],No=Array.from({length:18},(e,t)=>1e5+t*5e4),Po=new Set(No),Fo=[272e3,372e3,922e3],Io=new Set(Fo),Lo=`custom`,Ro=[4,8,16,32,64,128,256,500,1e3],zo=new Set(Ro),Bo=`ocx-models-collapsed:v2`;function Vo(e){return!Number.isFinite(e)||e<=0?String(e):e%1e3==0?e>=1e6?Number((e/1e6).toFixed(2))+`M`:`${e/1e3}k`:e.toLocaleString()}function Ho(e){let t=new Set;for(let n of e)n.disabled&&t.add(n.namespaced);return t}function Uo(e,t,n,r){let i=[];for(let a of e){let e=t.has(a.id)||t.has(a.namespaced);za(n,a.provider,a.id,a.native===!0,e)&&i.push({value:a.namespaced,label:r?Bn(a.namespaced,r):a.namespaced})}return i}function Wo(e=localStorage){try{let t=e.getItem(Bo);if(t===null)return null;let n=JSON.parse(t);return Array.isArray(n)?new Set(n.filter(e=>typeof e==`string`)):null}catch{return null}}function Go(e,t=localStorage){try{t.setItem(Bo,JSON.stringify([...e]))}catch{}}function Ko(e){return e.includes(`/`)?e.replaceAll(`/`,`-`):e}function qo(e,t){let n=Ko(e);for(let r of t)if(r!==e&&Ko(r)===n)return!0;return!1}function Jo({row:e,disambiguate:t,copied:n,isDefault:r,selected:i,action:a,disabled:o,onCopy:s,onRemove:c}){let l=Q(),u=l(a===`delete`?`models.customDelete`:`models.hide`);return(0,Y.jsxs)(`li`,{className:`pws-model-chip`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`pws-model-chip-main`,onClick:s,title:e.namespaced,"aria-label":l(n?`pws.modelCopied`:`pws.copyModelId`),children:(0,Y.jsx)(`span`,{className:`pws-model-id`,children:t?e.namespaced:e.id})}),r&&(0,Y.jsx)(`span`,{className:`badge badge-muted pws-model-flag`,children:l(`prov.defaultBadge`)}),i&&(0,Y.jsx)(`span`,{className:`badge badge-accent pws-model-flag`,children:l(`pws.selected`)}),a&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm btn-icon-only`,onClick:e=>c(e.currentTarget),disabled:o,"aria-label":`${u}: ${e.namespaced}`,title:`${u}: ${e.namespaced}`,children:a===`delete`?(0,Y.jsx)(me,{style:{width:13,height:13},"aria-hidden":`true`}):(0,Y.jsx)(he,{style:{width:13,height:13},"aria-hidden":`true`})})]})}var Yo=300;function Xo(e){return(0,Y.jsx)(Zo,{...e},JSON.stringify([e.apiBase,e.item.name]))}function Zo({item:e,apiBase:t,availableModels:n,selectedModels:r,modelRows:i,modelRevision:a,modelRowsReady:o,modelsLoading:s=!1,modelsLoadFailed:c=!1,needsReauth:l=!1,onRetryModels:u,onOpenAccounts:d,onOpenModels:f}){let p=Q(),[m,h]=(0,_.useState)(``),[g,v]=(0,_.useState)(!1),[y,b]=(0,_.useState)(``),[x,S]=(0,_.useState)(0),C=JSON.stringify([t,e.name,a,x]),[w,T]=(0,_.useState)(null),[E,D]=(0,_.useState)(null),[O,k]=(0,_.useState)(!1),[A,j]=(0,_.useState)(null),[M,N]=(0,_.useState)(null),P=(0,_.useRef)(null),F=(0,_.useRef)(!1),I=(0,_.useRef)(!0),L=(0,_.useRef)(a),R=(0,_.useRef)(null),z=(0,_.useRef)(null),B=(0,_.useRef)(null),V=w?.key===C&&E!==C,H=i!==null&&o&&!s&&!c&&V,U=H&&(!A||a!==A.revision),W=O||!!A&&!U,G=(i??[]).filter(t=>t.provider===e.name),K=G.some(e=>e.initialSelectionPending),q=!H||W||K,J=w?.rows.filter(t=>t.provider===e.name)??[],X=new Set(r),ee=[...n,...e.models??[],...J.map(e=>e.modelId),...e.defaultModel?[e.defaultModel]:[]],te=y.trim(),ne=!!te&&(ee.includes(te)||qo(te,ee)),Z=G.filter(e=>!e.disabled),re=Do(Z),ie=ko(g,Z),ae=Oo(Z,ie),oe=m.trim().toLowerCase(),se=ae.filter(e=>[e.id,e.namespaced].some(e=>e.toLowerCase().includes(oe))),ce=new Map;for(let e of Z)ce.set(e.id,(ce.get(e.id)??0)+1);(0,_.useEffect)(()=>{L.current=a},[a]),(0,_.useEffect)(()=>{I.current=!0;let e=e=>{B.current&&e.target!==B.current.button&&e.target!==document.body&&(B.current.retained=!1)};return document.addEventListener(`focusin`,e),()=>{I.current=!1,document.removeEventListener(`focusin`,e),P.current!==null&&clearTimeout(P.current)}},[]),(0,_.useEffect)(()=>{let e=!1,n=Xn(2e4);return fetch(`${t}/api/custom-models`,{signal:n.signal}).then(It).then(Ja).then(t=>{e||(T({key:C,rows:t}),D(null))}).catch(()=>{e||D(C)}).finally(()=>n.clear()),()=>{e=!0,n.controller.abort(),n.clear()}},[t,C]),(0,_.useEffect)(()=>{!O&&U&&(F.current=!1);let e=B.current;e&&!e.button.isConnected&&(e.retained&&document.activeElement===document.body&&(R.current??z.current)?.focus(),B.current=null)},[O,U,i]);let le=()=>{S(e=>e+1),u?.()},ue=async e=>{try{if(await navigator.clipboard.writeText((ce.get(e.id)??0)>1?e.namespaced:e.id),!I.current)return;N(e.namespaced),P.current!==null&&clearTimeout(P.current),P.current=setTimeout(()=>N(null),1200)}catch{}},de=e=>e.custom===!0&&e.native!==!0&&J.some(t=>t.id===e.customId&&t.provider===e.provider&&t.modelId===e.id),fe=e=>!H||e.initialSelectionPending?null:e.custom?de(e)?`delete`:null:e.native!==!0&&J.some(t=>t.modelId===e.id)?null:`hide`,pe=e=>{if(!I.current){u?.();return}j({...e,revision:L.current}),k(!1),le()},me=async()=>{if(q||F.current||!te||ne)return;F.current=!0,k(!0),j(null);let n=Xn(6e4),r={outcome:`unconfirmed`,refreshPending:!1};try{let i=await fetch(`${t}/api/custom-models`,{method:`POST`,signal:n.signal,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.name,modelId:te})});if(i.status===201){let t=await It(i),n=Ya(t,e.name,te);if(w?.rows.some(e=>e.id===n.id))throw Error(`Reused custom identity`);r={outcome:`saved`,created:n,refreshPending:Xa(t)},I.current&&b(``)}else i.status>=400&&i.status<500&&(r={outcome:`rejected`,refreshPending:!1})}catch{}finally{n.clear(),pe(r)}},he=async(e,n)=>{let r=fe(e);if(q||F.current||!r||!window.confirm(p(r===`delete`?`models.customDeleteConfirm`:`models.hideConfirm`,{name:e.namespaced})))return;F.current=!0,k(!0),j(null),B.current={button:n,retained:document.activeElement===n};let i=Xn(6e4),a={outcome:`unconfirmed`,refreshPending:!1};try{let n=r===`delete`?await fetch(`${t}/api/custom-models/${encodeURIComponent(e.customId)}`,{method:`DELETE`,signal:i.signal}):await Ba(t,`models`,e.provider,[{id:e.id,native:e.native===!0}],!1,(e,t)=>fetch(e,{...t,signal:i.signal}));if(n.ok){let e=await It(n);e&&typeof e==`object`&&!Array.isArray(e)&&`ok`in e&&e.ok===!0&&(a={outcome:r===`delete`?`deleted`:`hidden`,refreshPending:Xa(e)})}else n.status>=400&&n.status<500&&(a={outcome:`rejected`,refreshPending:!1})}catch{}finally{i.clear(),pe(a)}},ge=A?.created&&U&&G.some(e=>e.customId===A.created?.id&&e.disabled),_e=A&&(A.refreshPending||c||E===C),ve=A?A.outcome===`unconfirmed`?p(`pws.modelMutationUnconfirmed`):A.outcome===`rejected`?p(`models.customSaveFailed`):A.outcome===`saved`?p(_e?`pws.modelSavedRefreshPending`:ge?`pws.modelSavedHidden`:`pws.modelSaved`):p(_e?`pws.modelRemovedRefreshPending`:A.outcome===`deleted`?`pws.modelDefinitionDeleted`:`pws.modelHidden`):null;return(0,Y.jsxs)(`div`,{className:`pws-section`,children:[(0,Y.jsxs)(`div`,{className:`pws-section-head`,children:[(0,Y.jsx)(`h3`,{className:`pws-section-title`,children:p(`pws.tab.models`)}),i!==null&&(0,Y.jsx)(`span`,{className:`muted`,children:p(`pws.modelsAvailable`,{count:Z.length})})]}),(0,Y.jsx)(`div`,{className:`row`,children:(0,Y.jsx)(`button`,{ref:z,type:`button`,className:`btn btn-ghost btn-sm`,onClick:f,children:p(`pws.manageModelVisibility`)})}),l&&(0,Y.jsxs)(`div`,{className:`pws-inline-error`,role:`status`,children:[(0,Y.jsx)(`span`,{children:p(`pws.modelsNeedsReauth`)}),d&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:d,children:p(`pws.tab.accounts`)})]}),o&&n.length===0&&Z.length>0&&(e.models?.length??0)>0&&!l&&(0,Y.jsx)(`p`,{className:`muted text-label`,children:p(`pws.modelsConfiguredFallback`)}),K&&(0,Y.jsx)(`p`,{role:`status`,className:`muted`,children:p(`pws.modelSelectionPending`)}),(0,Y.jsx)(`label`,{className:`text-label pws-custom-model-label`,htmlFor:`pws-custom-model-${e.name}`,children:p(`models.customAdd`)}),(0,Y.jsxs)(`div`,{className:`row pws-custom-model-row`,children:[(0,Y.jsx)(`input`,{id:`pws-custom-model-${e.name}`,className:`input`,value:y,onChange:e=>b(e.target.value),onKeyDown:e=>{e.key===`Enter`&&me()},placeholder:p(`models.customFieldModelIdPlaceholder`),"aria-label":p(`models.customAdd`),disabled:O}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>{me()},disabled:q||!te||ne,children:p(O?`models.customSaving`:`models.customAddBtn`)})]}),ne&&(0,Y.jsx)(`p`,{className:`muted text-label`,role:`status`,children:p(`pws.modelKnown`)}),ve&&(0,Y.jsx)(`p`,{className:A?.outcome===`unconfirmed`||A?.outcome===`rejected`?`pws-inline-error`:`muted text-label`,role:A?.outcome===`unconfirmed`||A?.outcome===`rejected`?`alert`:`status`,children:ve}),ge&&_e&&(0,Y.jsx)(`p`,{className:`muted text-label`,role:`status`,children:p(`pws.modelSavedHidden`)}),A?.refreshPending&&(0,Y.jsx)(`p`,{className:`muted text-label`,role:`status`,children:p(`codexAuth.catalogRefreshPending`)}),c||E===C?(0,Y.jsxs)(`div`,{className:`pws-inline-error`,role:`alert`,children:[(0,Y.jsx)(`span`,{children:p(c?`pws.modelsLoadFailed`:`pws.modelOwnershipFailed`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:le,disabled:O,children:p(`common.retry`)})]}):(!H||W)&&(0,Y.jsx)(`p`,{className:`muted`,role:`status`,children:p(!o||s?`pws.modelsLoading`:`pws.modelOwnershipLoading`)}),A&&(A.outcome===`unconfirmed`||A.refreshPending)&&!c&&E!==C&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:le,disabled:O,children:p(`common.retry`)}),re&&(0,Y.jsx)(`div`,{className:`row`,children:(0,Y.jsx)(Dt,{on:g,onClick:()=>v(!g),label:p(`models.freeOnly`),showLabel:!0})}),(0,Y.jsx)(`input`,{ref:R,type:`search`,className:`input pws-model-search`,placeholder:p(`pws.modelSearchPlaceholder`),value:m,onChange:e=>h(e.target.value),"aria-label":p(`pws.modelSearchPlaceholder`)}),i!==null&&Z.length===0?(0,Y.jsx)(`p`,{className:`muted`,children:p(`pws.noModels`)}):se.length===0&&i!==null?(0,Y.jsx)(`p`,{className:`muted`,role:`status`,children:p(ie&&ae.length===0?`models.noFreeMatch`:`pws.noModelMatch`)}):(0,Y.jsx)(`ul`,{className:`pws-model-list`,children:se.slice(0,Yo).map(t=>(0,Y.jsx)(Jo,{row:t,disambiguate:(ce.get(t.id)??0)>1,copied:M===t.namespaced,isDefault:t.id===e.defaultModel,selected:t.native!==!0&&X.has(t.id),action:fe(t),disabled:q,onCopy:()=>{ue(t)},onRemove:e=>{he(t,e)}},t.namespaced))}),se.length>Yo&&(0,Y.jsx)(`p`,{className:`muted text-label`,style:{marginTop:10},children:p(`pws.modelsTruncated`,{shown:String(Yo),total:String(se.length)})})]})}function Qo({item:e,usageTotals:t,quotaReport:n,currentQuotaReading:r,quotaIdentity:i,modelUsage:a,onRefreshQuota:o}){let s=Q(),{locale:c}=ut(),l=t?.requests!==void 0,[u,d]=(0,_.useState)(null),f=(0,_.useMemo)(()=>a?.length?a.toSorted((e,t)=>t.totalTokens-e.totalTokens):[],[a]),p=(0,_.useMemo)(()=>{if(!f.length)return;let e=0,t=!1;for(let n of f)n.estimatedCostUsd!==void 0&&(e+=n.estimatedCostUsd,t=!0);return t?e:void 0},[f]);return(0,Y.jsxs)(`div`,{className:`pws-section`,children:[(0,Y.jsxs)(`div`,{className:`pws-usage-block`,children:[(0,Y.jsx)(`h3`,{className:`pws-section-title`,children:s(`pws.usageLast30d`)}),l?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{className:`pws-usage-metrics pws-usage-metrics-3`,role:`group`,"aria-label":s(`pws.usageLast30d`),children:[(0,Y.jsxs)(`div`,{className:`pws-usage-metric`,children:[(0,Y.jsx)(`span`,{className:`pws-usage-metric-value mono`,children:zi(p,c)}),(0,Y.jsx)(`span`,{className:`muted pws-usage-metric-label`,children:s(`pws.estimatedCost`)})]}),(0,Y.jsxs)(`div`,{className:`pws-usage-metric`,children:[(0,Y.jsx)(`span`,{className:`pws-usage-metric-value`,children:Li(t?.requests,c)}),(0,Y.jsx)(`span`,{className:`muted pws-usage-metric-label`,children:s(`pws.metricRequests`)})]}),(0,Y.jsxs)(`div`,{className:`pws-usage-metric`,children:[(0,Y.jsx)(`span`,{className:`pws-usage-metric-value`,children:Ri(t?.totalTokens,c)}),(0,Y.jsx)(`span`,{className:`muted pws-usage-metric-label`,children:s(`pws.metricTokens`)})]})]}),(0,Y.jsx)(`p`,{className:`muted pws-cost-disclaimer`,children:s(`pws.costDisclaimer`)})]}):(0,Y.jsx)(`p`,{className:`muted`,children:s(`pws.usageUnavailable`)})]}),f.length>0&&(0,Y.jsxs)(`div`,{className:`pws-usage-block`,children:[(0,Y.jsx)(`h3`,{className:`pws-section-title`,children:s(`pws.modelBreakdown`)}),(0,Y.jsx)(`div`,{className:`tbl-wrap`,children:(0,Y.jsxs)(`table`,{className:`pws-model-table`,children:[(0,Y.jsx)(`thead`,{children:(0,Y.jsxs)(`tr`,{children:[(0,Y.jsx)(`th`,{children:s(`pws.col.model`)}),(0,Y.jsx)(`th`,{className:`num`,children:s(`pws.col.cost`)}),(0,Y.jsx)(`th`,{className:`num`,children:s(`pws.col.tokens`)}),(0,Y.jsx)(`th`,{className:`num`,children:s(`pws.col.requests`)}),(0,Y.jsx)(`th`,{children:s(`pws.col.share`)})]})}),(0,Y.jsx)(`tbody`,{children:f.map(e=>{let t=e.model,n=u===t;return(0,Y.jsxs)(_.Fragment,{children:[(0,Y.jsxs)(`tr`,{className:`pws-model-row`,children:[(0,Y.jsxs)(`td`,{className:`mono`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`pws-model-expand`,"aria-expanded":n,onClick:()=>d(n?null:t),children:e.model}),e.hasUnresolvedRequestedModel&&(0,Y.jsx)(`div`,{className:`muted pws-model-attribution`,children:s(`pws.unresolvedRequestedModel`)})]}),(0,Y.jsx)(`td`,{className:`num mono`,children:zi(e.estimatedCostUsd,c)}),(0,Y.jsx)(`td`,{className:`num mono`,children:Ri(e.totalTokens,c)}),(0,Y.jsx)(`td`,{className:`num`,children:e.requests}),(0,Y.jsx)(`td`,{children:(0,Y.jsx)(`div`,{className:`pws-share-bar`,children:(0,Y.jsx)(`div`,{className:`pws-share-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})})]}),n&&(0,Y.jsx)(`tr`,{className:`pws-model-detail`,children:(0,Y.jsx)(`td`,{colSpan:5,children:(0,Y.jsxs)(`div`,{className:`pws-model-detail-grid`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`muted`,children:s(`pws.tokenInput`)}),(0,Y.jsxs)(`span`,{className:`mono`,children:[` `,Ri(e.inputTokens,c)]})]}),(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`muted`,children:s(`pws.tokenOutput`)}),(0,Y.jsxs)(`span`,{className:`mono`,children:[` `,Ri(e.outputTokens,c)]})]})]})})})]},t)})})]})})]}),(0,Y.jsx)(so,{report:n,reading:r,onRefreshQuota:o},`${e.name}:${i??``}`)]})}function $o(e){if(!e)return null;let t=e.trim();return t?t.length<=4?`account-…`:`account-…${t.slice(-4)}`:null}function es(e){return $o(e)??`account-…`}function ts(e){return e===`healthy`?`ok`:e===`cooldown`?`muted`:e===`reauth_required`||e===`warning`?`warn`:`muted`}function ns(e){let t=ts(e);return t===`ok`?`badge badge-green`:t===`warn`?`badge badge-amber`:`badge badge-muted`}function rs(e){return e===`reauth_required`}function is(e){return!!e?.needsReauth||rs(e?.health?.status)}function as(e){return e===`cooldown`}function os(e){return e===`warning`||e===`reauth_required`}function ss(e){if(!e||e.status===`healthy`)return null;if(e.status===`cooldown`)return e.reason===`rate_limit`?`pws.healthLabel.rateLimited`:`pws.healthLabel.quotaLimited`;if(e.status===`reauth_required`)return e.reason===`refresh_failed`?`pws.healthLabel.refreshFailed`:`pws.healthLabel.reauthRequired`;switch(e.reason){case`validation_pending`:return`pws.healthLabel.validationPending`;case`refresh_conflict`:return`pws.healthLabel.credentialConflict`;case`metadata_mismatch`:return`pws.healthLabel.metadataMismatch`;case`stale_credentials`:return`pws.healthLabel.refreshFailed`;default:return`pws.healthLabel.reauthRequired`}}function cs(e,t){let n=ss(t);return n?e(n):null}function ls(e,t,n,r){if(!r||r.status===`healthy`)return null;let i=n===`__main__`?e(`codexAuth.mainAccount`):es(n);if(r.status===`cooldown`){let n=r.until?new Date(r.until).toLocaleString():``;return e(r.reason===`rate_limit`?`pws.healthSummary.rateLimited`:`pws.healthSummary.quotaLimited`,{provider:t,account:i,until:n})}return r.status===`reauth_required`?e(`pws.healthSummary.reauthRequired`,{provider:t,account:i}):r.reason===`validation_pending`?e(`pws.healthSummary.validationPending`,{provider:t,account:i}):r.reason===`refresh_conflict`?e(`pws.healthSummary.credentialConflict`,{provider:t,account:i}):r.reason===`metadata_mismatch`?e(`pws.healthSummary.metadataMismatch`,{provider:t,account:i}):e(`pws.healthSummary.staleCredentials`,{provider:t,account:i})}async function us(e){let t=navigator.clipboard?.writeText?.bind(navigator.clipboard);if(t)try{return await t(e),!0}catch{}return ds(e)}function ds(e){if(typeof document>`u`||typeof document.execCommand!=`function`)return!1;let t=document.createElement(`textarea`);t.value=e,t.setAttribute(`readonly`,``),t.setAttribute(`aria-hidden`,`true`),t.style.position=`fixed`,t.style.top=`0`,t.style.opacity=`0`,document.body.appendChild(t);try{return t.select(),document.execCommand(`copy`)}catch{return!1}finally{t.remove()}}function fs(e,t){return e(t?t===`copied`?`pws.doctorCopied`:`pws.doctorCopyUnavailable`:`pws.copyDoctor`)}var ps=e=>({step:e?`oauth-waiting`:`pick`,id:``,error:``,authUrl:``,deviceCode:``,instructions:``,manualCode:``,manualCodeState:`idle`,statusNotice:``,statusTone:`ok`,flowId:null});function ms(e,t){switch(t.type){case`set-step`:return{...e,step:t.step};case`set-id`:return{...e,id:t.id};case`set-error`:return{...e,error:t.error};case`set-auth-url`:return{...e,authUrl:t.authUrl};case`set-login-hint`:return{...e,authUrl:t.authUrl,deviceCode:t.deviceCode??``,instructions:t.instructions??``};case`set-manual-code`:return{...e,manualCode:t.manualCode};case`set-manual-code-state`:return{...e,manualCodeState:t.manualCodeState};case`set-status-notice`:return{...e,statusNotice:t.statusNotice,statusTone:t.statusTone??e.statusTone};case`set-flow-id`:return{...e,flowId:t.flowId};case`clear-manual-code`:return{...e,manualCode:``,manualCodeState:`idle`,statusNotice:``,statusTone:`ok`};case`reset-oauth-start`:return{...e,error:``,statusNotice:``,statusTone:`ok`,flowId:null};case`oauth-code-submitted`:return{...e,error:``,manualCode:``,manualCodeState:`waiting`,statusTone:`ok`,statusNotice:``};default:return e}}function hs({id:e,error:t,onIdChange:n,onStartOAuth:r,onStartDeviceOAuth:i,onClose:a}){let o=Q();return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`h3`,{style:{marginBottom:4},children:o(`codexAuth.addTitle`)}),(0,Y.jsx)(`p`,{className:`modal-desc`,children:o(`codexAuth.addPickDesc`)}),(0,Y.jsx)(`label`,{className:`field-label`,htmlFor:`codex-account-id-input`,children:o(`codexAuth.addIdLabel`)}),(0,Y.jsx)(`input`,{id:`codex-account-id-input`,className:`input`,placeholder:o(`codexAuth.addIdPlaceholder`),value:e,onChange:e=>n(e.target.value),style:{marginBottom:12}}),(0,Y.jsx)(`button`,{type:`button`,className:`list-row`,onClick:r,style:{marginBottom:8},children:(0,Y.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:10},children:[(0,Y.jsx)(Fe,{width:20}),(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`div`,{className:`title`,children:o(`codexAuth.oauthLogin`)}),(0,Y.jsx)(`div`,{className:`sub`,children:o(`codexAuth.oauthDesc`)})]})]})}),(0,Y.jsx)(`button`,{type:`button`,className:`list-row`,onClick:i,style:{marginBottom:8},children:(0,Y.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:10},children:[(0,Y.jsx)(je,{width:20}),(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`div`,{className:`title`,children:o(`codexAuth.deviceLogin`)}),(0,Y.jsx)(`div`,{className:`sub`,children:o(`codexAuth.deviceDesc`)})]})]})}),t&&(0,Y.jsx)(`div`,{className:`notice notice-err`,style:{marginTop:8},children:t}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:a,style:{width:`100%`},children:o(`codexAuth.cancel`)})]})}var gs=2500;function _s(){let[e,t]=(0,_.useState)(null),n=(0,_.useRef)(null),r=(0,_.useRef)(0),i=(0,_.useCallback)(()=>{n.current&&=(clearTimeout(n.current),null)},[]);return(0,_.useEffect)(()=>i,[i]),{outcomeFor:(0,_.useCallback)(t=>e&&Object.is(e.scope,t)?e.outcome:null,[e]),copy:(0,_.useCallback)((e,a)=>{let o=++r.current;us(e).then(e=>{r.current===o&&(i(),t({scope:a,outcome:e?`copied`:`unavailable`}),n.current=setTimeout(()=>{n.current=null,r.current===o&&t(null)},gs))})},[i])}}function vs({url:e}){let t=Q(),{outcomeFor:n,copy:r}=_s();if(!e)return null;let i=n(e),a=t(i===`copied`?`prov.linkCopied`:i===`unavailable`?`prov.linkCopyUnavailable`:`prov.copyLink`);return(0,Y.jsxs)(`div`,{className:`login-url-block`,children:[(0,Y.jsx)(`code`,{className:`login-url-block-text`,children:e}),(0,Y.jsxs)(`div`,{className:`login-url-block-actions`,children:[(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>r(e,e),children:[(0,Y.jsx)(je,{style:{width:13,height:13},"aria-hidden":`true`}),(0,Y.jsx)(`span`,{"aria-live":`polite`,children:a})]}),(0,Y.jsxs)(`a`,{href:e,target:`_blank`,rel:`noreferrer`,className:`login-url-block-open`,children:[(0,Y.jsx)(Ee,{style:{width:13,height:13},"aria-hidden":`true`}),` `,t(`prov.didntOpen`)]})]})]})}function ys({hint:e,paste:t}){let n=Q(),r=_s(),i=e.deviceCode??``,a=e.url??``;if(!i&&!a&&!e.instructions&&!t)return null;let o=r.outcomeFor(i),s=n(o===`copied`?`prov.codeCopied`:o===`unavailable`?`prov.linkCopyUnavailable`:`prov.copyCode`);return(0,Y.jsxs)(`div`,{className:`login-hint`,children:[i&&(0,Y.jsxs)(`div`,{className:`login-hint-device pwi-device-code-wrap`,children:[(0,Y.jsx)(`span`,{className:`text-label`,children:n(`prov.deviceCode`)}),(0,Y.jsx)(`code`,{className:`login-hint-device-code pwi-device-code`,children:i}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>r.copy(i,i),children:(0,Y.jsx)(`span`,{"aria-live":`polite`,children:s})})]}),(0,Y.jsx)(vs,{url:a}),e.instructions&&(0,Y.jsx)(`div`,{className:`muted text-label`,children:e.instructions}),t&&(0,Y.jsxs)(`div`,{className:`login-hint-paste`,children:[(0,Y.jsx)(`div`,{className:`muted text-label`,children:n(`prov.pasteRedirectHint`)}),(0,Y.jsxs)(`div`,{className:`login-hint-paste-row`,children:[(0,Y.jsx)(`input`,{type:`text`,autoComplete:`off`,spellCheck:!1,value:t.value,onChange:e=>t.onChange(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),t.onSubmit())},placeholder:n(`prov.pasteRedirect`),"aria-label":n(`prov.pasteRedirect`),disabled:t.busy,className:`input text-label login-hint-paste-input`}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:t.busy||t.disabled===!0||!t.value.trim(),onClick:t.onSubmit,children:t.busy?t.submittingLabel??n(`prov.pasteSubmitting`):n(`prov.pasteSubmit`)})]}),t.message&&(0,Y.jsx)(`div`,{className:`text-label`,"aria-live":`polite`,style:{color:t.ok?`var(--accent-hover)`:`var(--amber)`},children:t.message})]})]})}function bs({reauthAccountId:e,authUrl:t,deviceCode:n,instructions:r,manualCode:i,manualCodeBusy:a,manualCodeWaiting:o,statusNotice:s,statusTone:c,flowId:l,error:u,onSwitchToDevice:d,onManualCodeChange:f,onSubmitManualCode:p,onClose:m}){let h=Q();return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`h3`,{style:{marginBottom:4},children:h(e?`codexAuth.reauthenticate`:`codexAuth.oauthLogin`)}),(0,Y.jsx)(`p`,{className:`modal-desc`,children:h(`codexAuth.oauthWaiting`)}),(0,Y.jsx)(ys,{hint:{url:t,deviceCode:n,instructions:r},paste:{value:i,busy:a,disabled:a||o||!i.trim()||!l,submittingLabel:h(`codexAuth.oauthSubmittingCode`),message:``,ok:!0,onChange:f,onSubmit:p}}),s&&(0,Y.jsx)(`div`,{className:c===`warn`?`notice-warn`:`notice notice-ok`,role:`status`,"aria-live":`polite`,style:{marginTop:12},children:s}),u&&(0,Y.jsx)(`div`,{className:`notice notice-err`,style:{marginTop:12},children:u}),d&&!n&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:d,style:{width:`100%`,marginTop:8},children:h(`codexAuth.deviceLogin`)}),(0,Y.jsx)(`div`,{style:{textAlign:`center`,padding:`24px 0`},children:(0,Y.jsx)(`span`,{className:`spin`,style:{width:24,height:24}})}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:m,style:{width:`100%`},children:h(`codexAuth.cancel`)})]})}var xs=`ocx.oauth.openBrowser`;function Ss(){try{let e=window.localStorage.getItem(xs);return e===`0`?!1:e===`1`||void 0}catch{return}}function Cs(){let e=Ss();return e===void 0?{}:{openBrowser:e}}function ws(e){try{window.localStorage.setItem(xs,e?`1`:`0`)}catch{}}function Ts(e){if(typeof e!=`object`||!e||Array.isArray(e))return{catalogRefreshPending:!1};let t=Object.getOwnPropertyDescriptor(e,`catalogRefreshPending`),n=Object.getOwnPropertyDescriptor(e,`validationPending`);return{...n&&`value`in n&&n.value===!0?{validationPending:!0}:{},catalogRefreshPending:t!==void 0&&`value`in t&&t.value===!0}}var Es=3e5,Ds=96e4;function Os({apiBase:e,reauthAccountId:t,ui:n,dispatch:r,t:i}){let a=(0,_.useRef)(!0),o=(0,_.useRef)(0),s=(0,_.useRef)(!1),c=(0,_.useRef)(null),l=(0,_.useRef)(null),u=(0,_.useRef)(null),d=(0,_.useRef)(null),f=(0,_.useRef)(n.manualCodeState),p=(0,_.useRef)(null),m=(0,_.useRef)(null),h=(0,_.useRef)(()=>{}),g=(0,_.useRef)(()=>{}),v=n.manualCodeState===`submitting`,y=n.manualCodeState===`waiting`;(0,_.useEffect)(()=>{f.current=n.manualCodeState},[n.manualCodeState]),(0,_.useEffect)(()=>{d.current=n.flowId},[n.flowId]);let b=(0,_.useCallback)(()=>{c.current&&=(c.current(),null),l.current&&=(clearTimeout(l.current),null),u.current?.abort(),u.current=null,s.current=!1},[]),x=(0,_.useCallback)(()=>{r({type:`clear-manual-code`}),o.current=0},[r]),S=(0,_.useCallback)(async()=>{x();let t=d.current;d.current=null,r({type:`set-flow-id`,flowId:null}),r({type:`set-login-hint`,authUrl:``}),b(),p.current?.abort(),p.current=null,t&&await fetch(`${e}/api/codex-auth/login/cancel`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({flowId:t})}).catch(()=>{})},[e,x,r,b]);(0,_.useEffect)(()=>(a.current=!0,()=>{x(),a.current=!1,m.current=null,p.current?.abort(),p.current=null;let t=d.current;d.current=null,r({type:`set-flow-id`,flowId:null}),b(),t&&fetch(`${e}/api/codex-auth/login/cancel`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({flowId:t})}).catch(()=>{})}),[e,x,r,b]);let C=(0,_.useCallback)((e,t)=>{h.current=e,g.current=t},[]),w=(0,_.useCallback)(()=>{n.step===`oauth-waiting`&&S(),g.current()},[n.step,S]),T=(0,_.useCallback)(async(n,m)=>{x(),d.current=null,r({type:`set-flow-id`,flowId:null});let _=new AbortController;p.current?.abort(),p.current=_,r({type:`reset-oauth-start`}),o.current=0;try{let p=t??n?.trim()??``,v=m?.device===!0,y=()=>fetch(`${e}/api/codex-auth/login`,{signal:_.signal,method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...Cs(),...v?{device:!0}:{},...t?{id:t,reauth:!0}:p?{id:p}:{}})}),C=await y();if(!a.current)return;if(C.status===409){if(await fetch(`${e}/api/codex-auth/login/cancel`,{method:`POST`,headers:{"Content-Type":`application/json`},body:`{}`}),!a.current||_.signal.aborted)return;if(C=await y(),C.status===409){r({type:`set-error`,error:i(`codexAuth.oauthAlreadyInProgress`)});return}}let w=await It(C,i(`modal.networkError`));if(!a.current||!w)return;if(w.url){d.current=w.flowId??null,r({type:`set-flow-id`,flowId:w.flowId??null}),r({type:`set-login-hint`,authUrl:w.url,deviceCode:w.deviceCode,instructions:w.instructions}),r({type:`set-step`,step:`oauth-waiting`}),b();let n=w.flowId??``,m=t?`&reauth=1`:``,_=n?`${e}/api/codex-auth/login-status?flowId=${encodeURIComponent(n)}${p?`&accountId=${encodeURIComponent(p)}`:``}${m}`:`${e}/api/codex-auth/login-status`,y=new AbortController;u.current=y,c.current=er(async()=>{if(s.current||y.signal.aborted)return;s.current=!0;let e=AbortSignal.any([y.signal,AbortSignal.timeout(1e4)]);try{let n=await Lt(await fetch(_,{signal:e}));if(!a.current||y.signal.aborted)return;if(!n){o.current+=1,o.current>=3&&r({type:`set-status-notice`,statusNotice:i(`codexAuth.oauthStatusRetrying`),statusTone:`warn`});return}if(o.current=0,f.current===`waiting`?r({type:`set-status-notice`,statusNotice:i(`codexAuth.oauthCodeSubmitted`),statusTone:`ok`}):r({type:`set-status-notice`,statusNotice:``,statusTone:`ok`}),n.status===`done`){if(b(),x(),d.current=null,r({type:`set-flow-id`,flowId:null}),!a.current)return;h.current(Ts(n)),g.current()}else(n.status===`error`||n.status===`expired`)&&(b(),x(),d.current=null,r({type:`set-flow-id`,flowId:null}),a.current&&(t||r({type:`set-step`,step:`pick`}),r({type:`set-error`,error:n.error??i(`codexAuth.loginFailed`)})))}catch(e){if(!a.current||y.signal.aborted||e instanceof Error&&e.name===`AbortError`)return;o.current+=1,o.current>=3&&r({type:`set-status-notice`,statusNotice:i(`codexAuth.oauthStatusRetrying`),statusTone:`warn`})}finally{s.current=!1}},2e3),l.current=setTimeout(()=>{c.current&&(x(),S(),a.current&&(t||r({type:`set-step`,step:`pick`}),r({type:`set-error`,error:i(`modal.loginTimeout`)})))},v?Ds:Es)}w.error&&!w.url&&r({type:`set-error`,error:w.error})}catch(e){a.current&&!(e instanceof Error&&e.name===`AbortError`)&&r({type:`set-error`,error:e instanceof Error?e.message:String(e)})}},[e,S,x,r,t,b,i]);return(0,_.useEffect)(()=>{if(!t){m.current=null;return}m.current!==t&&(m.current=t,T())},[t,T]),{manualCodeBusy:v,manualCodeWaiting:y,bindCallbacks:C,closeModal:w,startOAuth:T,submitManualCode:(0,_.useCallback)(async()=>{let t=d.current,s=n.manualCode.trim();if(!(!t||!s||v||y)){r({type:`set-manual-code-state`,manualCodeState:`submitting`}),r({type:`set-status-notice`,statusNotice:``,statusTone:`ok`});try{let n=await fetch(`${e}/api/codex-auth/login/code`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({flowId:t,input:s})});if(!a.current)return;if(!n.ok){r({type:`set-error`,error:i(`prov.pasteFail`,{error:(await n.json().catch(()=>({}))).error??n.statusText})}),r({type:`set-manual-code-state`,manualCodeState:`idle`});return}r({type:`oauth-code-submitted`}),r({type:`set-status-notice`,statusNotice:i(`codexAuth.oauthCodeSubmitted`),statusTone:`ok`}),o.current=0}catch{a.current&&(r({type:`set-error`,error:i(`modal.networkError`)}),r({type:`set-manual-code-state`,manualCodeState:`idle`}))}}},[e,r,v,y,i,n.manualCode])}}function ks({apiBase:e,onClose:t,onAdded:n,reauthAccountId:r}){let i=Q(),[a,o]=(0,_.useReducer)(ms,r,ps),s=(0,_.useRef)(null),c=(0,_.useRef)(null),{manualCodeBusy:l,manualCodeWaiting:u,bindCallbacks:d,closeModal:f,startOAuth:p,submitManualCode:m}=Os({apiBase:e,reauthAccountId:r,ui:a,dispatch:o,t:i});(0,_.useEffect)(()=>{d(n,t)},[d,n,t]),(0,_.useEffect)(()=>{s.current=document.activeElement;let e=c.current;e&&!e.open&&e.showModal();let t=e?.querySelector(`input:not([disabled]), button:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex='-1'])`);return t&&t.focus(),()=>{s.current?.focus()}},[]);let h=(0,_.useCallback)(e=>{e.preventDefault(),f()},[f]),g=i(r?`codexAuth.reauthenticate`:`codexAuth.addTitle`);return(0,Y.jsx)(`dialog`,{ref:c,"aria-label":g,className:`modal-overlay`,onCancel:h,children:(0,Y.jsxs)(`div`,{className:`modal-card`,style:{maxWidth:440},children:[a.step===`pick`&&(0,Y.jsx)(hs,{id:a.id,error:a.error,onIdChange:e=>o({type:`set-id`,id:e}),onStartOAuth:()=>{p(a.id)},onStartDeviceOAuth:()=>{p(a.id,{device:!0})},onClose:f}),a.step===`oauth-waiting`&&(0,Y.jsx)(bs,{reauthAccountId:r,authUrl:a.authUrl,deviceCode:a.deviceCode,instructions:a.instructions,manualCode:a.manualCode,manualCodeBusy:l,manualCodeWaiting:u,statusNotice:a.statusNotice,statusTone:a.statusTone,flowId:a.flowId,error:a.error,onSwitchToDevice:()=>{p(a.id,{device:!0})},onManualCodeChange:e=>o({type:`set-manual-code`,manualCode:e}),onSubmitManualCode:()=>{m()},onClose:f})]})})}var As=[2,1,0,-1,-2],js=new Map([[2,`accountPool.priorityFirst`],[1,`accountPool.priorityEarlier`],[0,`accountPool.priorityNormal`],[-1,`accountPool.priorityLater`],[-2,`accountPool.priorityLast`]]);function Ms(e){return typeof e==`number`&&Number.isInteger(e)&&e>=-100&&e<=100?e:0}function Ns(e){let t=Ms(e);return t>0?`+${t}`:String(t)}function Ps(e){return js.has(e)}function Fs(e){return js.get(e)??null}function Is(e,t){let n=Ms(t);return e(`accountPool.priorityOption`,{name:e(Fs(n)??`accountPool.priorityCustom`),value:Ns(n)})}var Ls=[`quota`,`round-robin`,`fill-first`,`reset-first`],Rs=[`five-hour`,`weekly`,`max-utilization`],zs=`quota`,Bs=`five-hour`,Vs=new Set(Ls),Hs=new Set(Rs);function Us(e){return typeof e==`string`&&Vs.has(e)?e:zs}function Ws(e){return typeof e==`string`&&Hs.has(e)?e:Bs}function Gs(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=100?e:1}function Ks(e){let t=e.trim();if(!/^\d+$/.test(t))return null;let n=Number(t);return n>=1&&n<=100?n:null}var qs=`openai`;function Js(e,t,n){let r=e??{},i=r.autoSwitchThreshold??n?.threshold;return{provider:t,kind:r.kind===`codex`||r.kind===`anthropic`?r.kind:`generic`,supported:Array.isArray(r.supported)?r.supported.filter(e=>typeof e==`string`):[],enabled:typeof r.enabled==`boolean`?r.enabled:null,enabledEffective:r.enabledEffective===!0,strategy:Us(r.strategy??n?.strategy),stickyLimit:Gs(r.stickyLimit??n?.stickyLimit),autoSwitchThreshold:typeof i==`number`?i:null,quotaWindow:(r.quotaWindow??n?.quotaWindow)===void 0||r.quotaWindow===null?null:Ws(r.quotaWindow??n?.quotaWindow)}}function Ys(e,t){return{provider:e,...t.enabled===void 0?{}:{enabled:t.enabled},...t.strategy===void 0?{}:{strategy:t.strategy},...t.stickyLimit===void 0?{}:{stickyLimit:t.stickyLimit},...t.threshold===void 0?{}:{autoSwitchThreshold:t.threshold},...t.quotaWindow===void 0?{}:{quotaWindow:t.quotaWindow}}}async function Xs(e,t,n=(e,t)=>fetch(e,t),r){try{let i=await n(`${e}/api/pool/settings?provider=${encodeURIComponent(t)}`,r);return i.ok?Js(await i.json(),t):null}catch{return null}}async function Zs(e,t,n,r=(e,t)=>fetch(e,t),i){try{let a=await r(`${e}/api/pool/settings`,{...i,method:`PUT`,headers:{"Content-Type":`application/json`,...i?.headers??{}},body:JSON.stringify(Ys(t,n))});return a.ok?Js(await a.json().catch(()=>({})),t,n):null}catch{return null}}async function Qs(e,t,n=(e,t)=>fetch(e,t)){if(t.strategy===void 0&&t.stickyLimit===void 0)return{ok:!1};let r=await Zs(e,qs,{strategy:t.strategy,stickyLimit:t.stickyLimit},n);return r?{ok:!0,strategy:r.strategy,stickyLimit:r.stickyLimit}:{ok:!1}}var $s=1e4;function ec(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<=100?e:80}function tc(e){let t=e.trim();if(!/^\d+$/.test(t))return null;let n=Number(t);return n>=1&&n<=100?n:null}function nc(e,t){return e>0?0:Number.isInteger(t)&&t>=1&&t<=100?t:80}function rc(e,t,n,r){return n===r?e||t?`defer`:`apply`:`ignore`}function ic(e){return e&&typeof e==`object`&&e&&`autoSwitchThreshold`in e?e.autoSwitchThreshold:e}function ac(e,t,n){if(e<=0){let t=nc(e,n);return{threshold:t,lastEnabled:t}}return{threshold:0,lastEnabled:tc(t)??nc(0,n)}}async function oc(e,t,n=(e,t)=>fetch(e,t),r=$s){return!Number.isInteger(t)||t<0||t>100?!1:await Zs(e,qs,{threshold:t},(e,t)=>n(e,t),{signal:AbortSignal.timeout(r)})!==null}var sc=3e4,cc=new Map;function lc(e,t=!0){let n=cc.get(e),[r,i]=(0,_.useState)(()=>n?.accounts??[]),a=K(qn(e,`codex`),[e],async t=>{let n=await fetch(`${e}/api/usage?range=30d&surface=codex`,{signal:t});if(!n.ok)throw Error(`account usage load failed`);return n.json()},{enabled:t}),[o,s]=(0,_.useState)(()=>n?.activeId??null),[c,l]=(0,_.useState)(()=>n==null?`loading`:`ready`),[u,d]=(0,_.useState)(null),[f,p]=(0,_.useState)(null),[m,h]=(0,_.useState)(null),[g,v]=(0,_.useState)(!1),[y,b]=(0,_.useState)(null),[x,S]=(0,_.useState)(0),[C,w]=(0,_.useState)(()=>n!=null),[T,E]=(0,_.useState)(0),D=(0,_.useRef)(null);D.current===null&&(D.current=new Set);let O=(0,_.useRef)(null),k=(0,_.useRef)(0),A=(0,_.useRef)(null),j=(0,_.useRef)(null);j.current===null&&(j.current=new Set);let M=(0,_.useRef)(null),N=(0,_.useRef)(null),P=(0,_.useRef)(!!n?.accounts.length),F=(0,_.useRef)(n!=null),I=(0,_.useRef)(null),L=(0,_.useRef)(null),R=(0,_.useCallback)(e=>(j.current.add(e),()=>{j.current.delete(e)}),[]),z=(0,_.useCallback)(()=>ic(M.current?.value),[]),B=(0,_.useCallback)(()=>M.current?.value,[]),V=(0,_.useCallback)(async(t=!1,n={})=>{let r=++k.current,a=n.validatePending===!0,o=cc.get(e)?.accounts.length??0,c=Xn(a?3e4+12e4*Math.max(1,o):2e4),u=a?{}:null;u&&(D.current.add(u),E(D.current.size)),S(e=>e+1);try{let n=[...j.current],o=new Map;for(let e of n)o.set(e,e.beginActiveRead());!t&&!F.current&&l(`loading`);let u=null,d,f=(async()=>{try{let n=await fetch(`${e}/api/codex-auth/accounts${a?`/refresh`:t?`?refresh=1`:``}`,{method:a?`POST`:`GET`,signal:c.signal});if(!n.ok)throw Error(`account load failed`);let o=await n.json();return k.current===r&&(u=(o.accounts??[]).map(e=>{let t=e.isMain?`main`:e.logLabel,n=ia(e.quota);return{...e,...t?{logLabel:t}:{},priority:Ms(e.priority),quotaAutoRefresh:e.quotaAutoRefresh??{...n,fiveHourEnabled:!1,weeklyEnabled:!1}}}),i(u),P.current=u.length>0,F.current=!0,l(`ready`)),!0}catch{return!1}})(),p=(async()=>{try{let t=await fetch(`${e}/api/codex-auth/active`,{signal:c.signal});if(!t.ok)throw Error(`active account load failed`);let i=await t.json();if(k.current===r){let e=i.activeCodexAccountId??null,t=A.current;t&&e!==t.id||(A.current=null,d=e,s(e)),M.current={value:i},b(typeof i.pinnedAccountId==`string`?i.pinnedAccountId:null);for(let e of n)e.acceptActiveRead(i,o.get(e))}return!0}catch{if(k.current===r)for(let e of n)e.rejectActiveRead();return!1}})(),[m,h]=await Promise.all([f,p]);if(k.current!==r)return!1;if(m){l(`ready`),F.current=!0;let t=cc.get(e);return cc.set(e,{accounts:u??t?.accounts??[],activeId:d===void 0?t?.activeId??null:d}),h}return F.current||l(`error`),!1}finally{c.clear(),u&&(D.current.delete(u),E(D.current.size)),S(e=>Math.max(0,e-1)),w(!0)}},[e]);(0,_.useEffect)(()=>{t&&O.current!==e&&(O.current=e,Promise.resolve().then(()=>{V()}))},[e,t,V]);let H=r.some(e=>e.hasCredential&&!e.quota);(0,_.useEffect)(()=>{if(!t||!H||T>0)return;let e=[350,900,2e3].map(e=>window.setTimeout(()=>{D.current.size===0&&V(!1)},e));return()=>{for(let t of e)window.clearTimeout(t)}},[t,H,T,V]),(0,_.useEffect)(()=>{if(!(!t||T>0))return er(()=>{D.current.size===0&&V()},sc)},[t,V,T]);let U=(0,_.useCallback)(()=>{let e={};return D.current.add(e),E(D.current.size),e},[]),W=(0,_.useCallback)(e=>{D.current.delete(e)&&E(D.current.size)},[]),G=(0,_.useCallback)(async t=>{if(N.current||L.current)return{ok:!1,reason:`busy`};N.current=t??`__main__`,d(t??`__main__`);try{let n=await fetch(`${e}/api/codex-auth/active`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({accountId:t})});if(!n.ok)throw Error(`account switch failed`);let r=(await n.json().catch(()=>({}))).activeCodexAccountId??t;return A.current={id:r??null},s(r??null),b(r??`__main__`),V(),{ok:!0,activeId:r??null}}catch{return{ok:!1,reason:`request`}}finally{N.current=null,d(null)}},[e,V]),q=(0,_.useCallback)(async(t,n)=>{try{return(await fetch(`${e}/api/codex-auth/accounts/alias`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:t,alias:n.trim()})})).ok?(await V(),{ok:!0}):{ok:!1,reason:`request`}}catch{return{ok:!1,reason:`request`}}},[e,V]),J=(0,_.useCallback)(async(t,n)=>{if(I.current)return{ok:!1,reason:`busy`};I.current={accountId:t},p(t);try{let r=await fetch(`${e}/api/codex-auth/accounts/pause`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:t,paused:n})});if(!r.ok)return{ok:!1,reason:`request`};let a=await r.json().catch(()=>({})),o=a&&typeof a==`object`?a:{};if(i(e=>e.map(e=>e.id===t||t===`__main__`&&e.isMain?{...e,paused:n}:e)),Object.prototype.hasOwnProperty.call(o,`activeCodexAccountId`)){let e=o.activeCodexAccountId??null;A.current={id:e},s(e)}return n&&b(e=>e===t?null:e),V(),{ok:!0}}catch{return{ok:!1,reason:`request`}}finally{I.current=null,p(null)}},[e,V]),Y=(0,_.useCallback)(async(t,n)=>{if(L.current||N.current)return{ok:!1,reason:`busy`};L.current={accountId:t},h(t);try{let r=await fetch(`${e}/api/codex-auth/accounts/priority`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:t,priority:n})});if(!r.ok)return{ok:!1,reason:`request`};let a=await r.json().catch(()=>({})),o=Ms((a&&typeof a==`object`?a:{}).priority??n);return i(e=>e.map(e=>e.id===t||t===`__main__`&&e.isMain?{...e,priority:o}:e)),b(null),A.current=null,V(),{ok:!0}}catch{return{ok:!1,reason:`request`}}finally{L.current=null,h(null)}},[e,V]),X=(0,_.useCallback)(async()=>{if(I.current)return{ok:!1,reason:`busy`};I.current=`bulk`,v(!0);try{let t=await fetch(`${e}/api/codex-auth/accounts/pause-exhausted`,{method:`PUT`});if(!t.ok)return{ok:!1,reason:`request`};let n=await t.json().catch(()=>({})),r=n&&typeof n==`object`?n:{},a=new Set(r.pausedAccountIds??[]);if(i(e=>e.map(e=>a.has(e.id)||a.has(`__main__`)&&e.isMain?{...e,paused:!0}:e)),Object.prototype.hasOwnProperty.call(r,`activeCodexAccountId`)){let e=r.activeCodexAccountId??null;A.current={id:e},s(e)}return b(e=>e!==null&&a.has(e)?null:e),V(),{ok:!0,pausedCount:r.pausedCount??a.size}}catch{return{ok:!1,reason:`request`}}finally{I.current=null,v(!1)}},[e,V]),ee=(0,_.useCallback)(async t=>{try{let n=await fetch(`${e}/api/codex-auth/accounts?id=${encodeURIComponent(t)}`,{method:`DELETE`});if(!n.ok)return{ok:!1,reason:`request`};let r=Ts(await n.json().catch(()=>({})));return await V(),{ok:!0,...r}}catch{return{ok:!1,reason:`request`}}},[e,V]),te=(0,_.useCallback)(async()=>await V()?{ok:!0}:{ok:!1,reason:`reload`},[V]),ne=o&&o!==`__main__`?r.find(e=>e.id===o):null,Z=r.find(e=>e.isMain),re=ne??Z,ie=!re?.paused&&is(re);return{accounts:(0,_.useMemo)(()=>{let e=new Map((a.data?.accounts??[]).map(e=>[e.accountLogLabel,e]));return r.map(t=>{let n=t.isMain?`main`:t.logLabel,r=n?e.get(n):void 0;return r?{...t,usage30d:r}:t})},[r,a.data]),activeId:o,loadState:c,refreshing:x>0,initialLoading:!C,switchingId:u,pauseUpdatingId:f,priorityUpdatingId:m,pausingExhausted:g,activeNeedsReauth:ie,activePinnedId:y,load:V,switchAccount:G,setAccountPaused:J,setAccountPriority:Y,pauseExhaustedAccounts:X,saveAlias:q,removeAccount:ee,syncAfterAccountAdded:te,pauseRefresh:U,resumeRefresh:W,subscribeLoadObserver:R,readLastThreshold:z,readLastActive:B}}var uc=`https://auth.openai.com/codex/device`,dc=2e3,fc=1e4,pc=new Set([`identity_mismatch`,`credential_changed`,`native_main_unavailable`,`device_authorization_failed`,`publication_failed`,`reconciliation_failed`,`flow_in_progress`]);function mc(e){return typeof e==`string`&&pc.has(e)?e:`request_failed`}function hc(e){return typeof e==`string`&&e.startsWith(uc)?e:``}function gc(e){return typeof e==`string`&&/^[A-Z0-9-]{1,16}$/i.test(e)?e:``}function _c(e,t){let[n,r]=(0,_.useState)({phase:`idle`}),i=(0,_.useRef)(null),a=(0,_.useRef)(null),o=(0,_.useRef)(!1),s=(0,_.useCallback)(()=>{a.current?.abort(),a.current=null},[]),c=(0,_.useCallback)(async()=>{let t=i.current;if(s(),i.current=null,!t){r({phase:`idle`});return}try{await fetch(`${e}/api/codex-auth/main/reauth-device?flowId=${encodeURIComponent(t)}`,{method:`DELETE`})}catch{}r({phase:`cancelled`})},[e,s]),l=(0,_.useCallback)(async()=>{s(),i.current=null;let n=new AbortController;a.current=n,r({phase:`starting`});let c;try{let t=await fetch(`${e}/api/codex-auth/main/reauth-device`,{method:`POST`,signal:n.signal});if(!t.ok){let e=await t.json().catch(()=>({}));r({phase:`failed`,code:mc(e.code)});return}let i=await t.json().catch(()=>({}));if(typeof i.flowId!=`string`||!i.flowId){r({phase:`failed`,code:`request_failed`});return}c=i.flowId}catch{n.signal.aborted||r({phase:`failed`,code:`request_failed`});return}i.current=c;let l=``,u=``;for(;!n.signal.aborted;){if(n.signal.aborted||o.current||i.current!==c)return;try{let a=await fetch(`${e}/api/codex-auth/main/reauth-device?flowId=${encodeURIComponent(c)}`,{signal:AbortSignal.any([n.signal,AbortSignal.timeout(fc)])});if(!a.ok){let e=await a.json().catch(()=>({}));r({phase:`failed`,code:mc(e.code)});return}let o=await a.json().catch(()=>({}));if(l=hc(o.verificationUrl)||l,u=gc(o.deviceCode)||u,o.status===`pending`||o.status===`committing`)r({phase:o.status,flowId:c,verificationUrl:l,deviceCode:u});else if(o.status===`succeeded`){i.current=null,r({phase:`succeeded`}),t();return}else if(o.status===`cancelled`){i.current=null,r({phase:`cancelled`});return}else if(o.status===`failed`){i.current=null,r({phase:`failed`,code:mc(o.code)});return}}catch{if(n.signal.aborted||o.current)return}await new Promise(e=>setTimeout(e,dc))}},[e,t,s]);return(0,_.useEffect)(()=>()=>{o.current=!0,s();let t=i.current;i.current=null,t&&fetch(`${e}/api/codex-auth/main/reauth-device?flowId=${encodeURIComponent(t)}`,{method:`DELETE`}).catch(()=>{})},[e,s]),{state:n,start:l,cancel:c}}function vc(e,t,n,r,i=1){let a=e.trim(),o=a===``?NaN:Number(a),s=Math.min(r,Math.max(n,(Number.isFinite(o)?o:n)+t));return String(i<1?Math.round(s*10)/10:Math.round(s))}function yc({disabled:e=!1,onIncrement:t,onDecrement:n,incrementLabel:r,decrementLabel:i}){return(0,Y.jsxs)(`div`,{className:`ocx-stepper`,role:`group`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`ocx-stepper__btn`,disabled:e,"aria-label":r,onMouseDown:e=>e.preventDefault(),onClick:t,children:(0,Y.jsx)(be,{width:10,height:10,"aria-hidden":`true`})}),(0,Y.jsx)(`button`,{type:`button`,className:`ocx-stepper__btn`,disabled:e,"aria-label":i,onMouseDown:e=>e.preventDefault(),onClick:n,children:(0,Y.jsx)(xe,{width:10,height:10,"aria-hidden":`true`})})]})}var bc={"reset-first":{on:`accountPool.strategyHintResetFirst`,off:`codexAuth.autoSwitchQuotaOffDesc`},quota:{on:`codexAuth.autoSwitchQuotaDesc`,off:`codexAuth.autoSwitchQuotaOffDesc`},"round-robin":{on:`codexAuth.autoSwitchRoundRobinDesc`,off:`codexAuth.autoSwitchRoundRobinDesc`},"fill-first":{on:`codexAuth.autoSwitchFillFirstDesc`,off:`codexAuth.autoSwitchFillFirstOffDesc`}};function xc({threshold:e,draft:t,strategy:n=`quota`,hydrated:r=!0,saving:i,loadError:a,feedback:o,onDraftChange:s,onEditingChange:c,onCommit:l,onCancel:u,onToggle:d,onRetry:f}){let p=Q(),m=(0,_.useRef)(!1),h=e>0,g=bc[n][h?`on`:`off`],v=i||!r,y=i?p(`common.saving`):o?.message??``,b=i?`pending`:o?.tone,x=y?`codex-auto-switch-desc codex-auto-switch-feedback`:`codex-auto-switch-desc`;return(0,Y.jsxs)(`div`,{className:`card card-row codex-auto-switch-card`,style:{marginTop:16},"aria-busy":i||!r&&!a||void 0,children:[(0,Y.jsxs)(`div`,{className:`codex-auto-switch-copy`,children:[(0,Y.jsx)(`strong`,{children:p(`codexAuth.autoSwitch`)}),(0,Y.jsx)(`div`,{id:`codex-auto-switch-desc`,className:`card-sub`,role:a?`alert`:void 0,children:a?p(`codexAuth.autoSwitchLoadFailed`):p(g,{threshold:e})}),(0,Y.jsx)(`div`,{className:`card-sub`,children:p(`codexAuth.failureRecoveryNote`)}),(0,Y.jsx)(`div`,{className:`card-sub`,children:p(`codexAuth.cacheWarning`)})]}),(0,Y.jsxs)(`div`,{className:`codex-auto-switch-controls`,onBlur:e=>{if(!e.currentTarget.contains(e.relatedTarget)){if(c(!1),m.current){m.current=!1;return}h&&!v&&l()}},children:[a&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:f,children:p(`pws.retryAccounts`)}),h&&(0,Y.jsxs)(`label`,{className:`codex-auto-switch-threshold`,children:[(0,Y.jsx)(`span`,{className:`field-label`,children:p(`codexAuth.autoSwitchThreshold`)}),(0,Y.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,children:[(0,Y.jsx)(`input`,{className:`input mono codex-auto-switch-input`,type:`number`,min:1,max:100,step:1,inputMode:`numeric`,value:t,readOnly:v,"aria-disabled":v,"aria-label":p(`codexAuth.autoSwitchThresholdAria`),"aria-describedby":x,onChange:e=>s(e.target.value),onFocus:()=>{v||c(!0)},onKeyDown:e=>{e.nativeEvent.isComposing||v||(e.key===`Enter`?(e.preventDefault(),l()):e.key===`Escape`&&(e.preventDefault(),u()))}}),(0,Y.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`%`}),(0,Y.jsx)(yc,{disabled:v,incrementLabel:p(`codexAuth.autoSwitchThresholdInc`),decrementLabel:p(`codexAuth.autoSwitchThresholdDec`),onIncrement:()=>{c(!0),s(vc(t,1,1,100))},onDecrement:()=>{c(!0),s(vc(t,-1,1,100))}})]})]}),(0,Y.jsx)(`span`,{className:`codex-auto-switch-toggle-slot`,children:(0,Y.jsx)(`button`,{type:`button`,className:`toggle ${h?`on`:``}`,onPointerDownCapture:()=>{m.current=!0},onPointerUp:()=>{m.current=!1},onPointerCancel:()=>{m.current=!1},onClick:()=>{m.current=!1,d()},disabled:v,"aria-pressed":h,"aria-label":p(`codexAuth.autoSwitch`),"aria-describedby":x,title:p(`codexAuth.autoSwitch`),children:(0,Y.jsx)(`span`,{className:`toggle-knob`})})})]}),y&&(0,Y.jsx)(`div`,{id:`codex-auto-switch-feedback`,className:`codex-auto-switch-feedback${b===`err`?` is-error`:``}`,role:b===`err`?`alert`:`status`,"aria-atomic":`true`,children:y})]})}var Sc={"reset-first":`accountPool.strategyResetFirst`,quota:`accountPool.strategyQuota`,"round-robin":`accountPool.strategyRoundRobin`,"fill-first":`accountPool.strategyFillFirst`},Cc={"reset-first":`accountPool.strategyHintResetFirst`,quota:`accountPool.strategyHintQuota`,"round-robin":`accountPool.strategyHintRoundRobin`,"fill-first":`accountPool.strategyHintFillFirst`};function wc({strategy:e,codex:t=!1,stickyDraft:n,disabled:r=!1,strategySelectId:i=`account-pool-strategy`,stickyInputId:a=`account-pool-sticky-limit`,onStrategyChange:o,onStickyDraftChange:s,onStickyCommit:c}){let l=Q(),u=Ls.filter(e=>t||e!==`reset-first`).map(e=>({value:e,label:l(Sc[e])}));return(0,Y.jsxs)(`div`,{className:`account-pool-strategy-controls`,children:[(0,Y.jsxs)(`div`,{className:`setting-row`,children:[(0,Y.jsxs)(`div`,{className:`setting-label`,children:[(0,Y.jsx)(`span`,{className:`title`,id:`${i}-label`,children:l(`accountPool.strategy`)}),(0,Y.jsx)(`span`,{className:`desc`,children:l(`accountPool.strategyDesc`)}),(0,Y.jsx)(`span`,{className:`desc`,children:l(Cc[e])}),(0,Y.jsx)(`span`,{className:`desc`,children:l(`accountPool.unboundDefinition`)})]}),(0,Y.jsx)(`div`,{className:`setting-controls`,children:(0,Y.jsx)(kt,{id:i,value:e,options:u,disabled:r,label:l(`accountPool.strategy`),onChange:e=>o(e)})})]}),e===`round-robin`&&(0,Y.jsxs)(`div`,{className:`setting-row`,children:[(0,Y.jsxs)(`label`,{className:`setting-label`,htmlFor:a,children:[(0,Y.jsx)(`span`,{className:`title`,children:l(`accountPool.stickyLimit`)}),(0,Y.jsx)(`span`,{className:`desc`,children:l(`accountPool.stickyLimitHelp`)})]}),(0,Y.jsx)(`div`,{className:`setting-controls`,children:(0,Y.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,children:[(0,Y.jsx)(`input`,{id:a,className:`input mono codex-auto-switch-input`,type:`number`,min:1,max:100,step:1,inputMode:`numeric`,value:n,disabled:r,"aria-label":l(`accountPool.stickyLimitAria`),onChange:e=>s(e.target.value),onBlur:()=>c(),onKeyDown:e=>{e.nativeEvent.isComposing||r||e.key===`Enter`&&(e.preventDefault(),c())}}),(0,Y.jsx)(yc,{disabled:r,incrementLabel:l(`accountPool.stickyLimitInc`),decrementLabel:l(`accountPool.stickyLimitDec`),onIncrement:()=>{let e=vc(n,1,1,100);s(e),c(e)},onDecrement:()=>{let e=vc(n,-1,1,100);s(e),c(e)}})]})})]})]})}function Tc(e){if(!e||typeof e!=`object`)return null;let t=e;return!(`accountPoolStrategy`in t)&&!(`accountPoolStickyLimit`in t)?null:{strategy:Us(t.accountPoolStrategy),stickyLimit:Gs(t.accountPoolStickyLimit)}}function Ec({apiBase:e,subscribeLoadObserver:t,readLastActive:n,onStrategyResolved:r}){let i=Q(),[a,o]=(0,_.useState)(zs),[s,c]=(0,_.useState)(1),[l,u]=(0,_.useState)(`1`),[d,f]=(0,_.useState)(!1),p=(0,_.useRef)(!1),[m,h]=(0,_.useState)(!1),g=(0,_.useRef)(!1),v=(0,_.useRef)(!1),y=(0,_.useRef)(0),[b,x]=(0,_.useState)(!1),[S,C]=(0,_.useState)(null),w=(0,_.useCallback)(e=>{let t=Us(e.accountPoolStrategy),n=Gs(e.accountPoolStickyLimit);o(t),r?.(t),c(n),u(String(n)),p.current=!0,f(!0),x(!1),C(null)},[r]),T=(0,_.useCallback)(e=>{let t=Tc(e);t&&w({accountPoolStrategy:t.strategy,accountPoolStickyLimit:t.stickyLimit})},[w]),E=(0,_.useCallback)(async()=>{try{let t=await fetch(`${e}/api/codex-auth/active`);if(!t.ok)throw Error(`load`);let n=await t.json();if(g.current){v.current=!0;return}w(n)}catch{g.current||x(!0)}},[e,w]),D=(0,_.useCallback)(()=>{v.current&&(v.current=!1,queueMicrotask(()=>{if(g.current){v.current=!0;return}E()}))},[E]);(0,_.useEffect)(()=>{if(!t)return;let e=t({beginActiveRead:()=>y.current,acceptActiveRead:(e,t)=>{if(t===y.current){if(g.current){v.current=!0;return}T(e)}},rejectActiveRead:()=>{p.current||x(!0)}});return!g.current&&n&&T(n()),e},[t,T,n]),(0,_.useEffect)(()=>{!n||t||g.current||T(n())},[n,T,t]),(0,_.useEffect)(()=>{t||E()},[E,t]);let O=(0,_.useCallback)(async t=>{if(g.current)return;let n=a,l=s;t.strategy!==void 0&&(o(t.strategy),r?.(t.strategy)),t.stickyLimit!==void 0&&(c(t.stickyLimit),u(String(t.stickyLimit))),g.current=!0,h(!0),C(null),y.current+=1;let d=await Qs(e,t);y.current+=1,d.ok?(o(d.strategy),r?.(d.strategy),c(d.stickyLimit),u(String(d.stickyLimit)),p.current=!0,f(!0)):(C(i(`accountPool.strategyUpdateFailed`)),o(n),r?.(n),c(l),u(String(l))),g.current=!1,h(!1),D()},[e,r,D,s,a,i]),k=m||b||!d;return(0,Y.jsxs)(`div`,{className:`card account-pool-strategy-card`,"aria-busy":m||!d&&!b,children:[b&&(0,Y.jsx)(`div`,{className:`card-sub`,role:`alert`,children:i(`accountPool.strategyLoadFailed`)}),b&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm account-pool-strategy-card__retry`,onClick:()=>{E()},children:i(`common.retry`)}),!b&&(0,Y.jsx)(wc,{codex:!0,strategy:a,stickyDraft:l,disabled:k,strategySelectId:`codex-pool-strategy`,stickyInputId:`codex-pool-sticky-limit`,onStrategyChange:e=>{k||e===a||O({strategy:e})},onStickyDraftChange:u,onStickyCommit:e=>{if(k)return;let t=Ks(e??l);if(t===null){u(String(s)),C(i(`accountPool.stickyLimitInvalid`));return}if(t===s){u(String(t));return}O({stickyLimit:t})}}),S&&(0,Y.jsx)(`div`,{role:`alert`,className:`card-sub account-pool-strategy-card__error`,children:S})]})}function Dc({t:e,open:t,onToggle:n,children:r}){return(0,Y.jsxs)(`section`,{className:`codex-auth-advanced`,children:[(0,Y.jsxs)(`button`,{type:`button`,className:`codex-auth-advanced__toggle`,"aria-expanded":t,"aria-controls":`codex-auth-advanced-boxes`,onClick:n,children:[(0,Y.jsx)(`span`,{children:e(`codexAuth.advancedSettings`)}),(0,Y.jsx)(Ce,{width:12,height:12,"aria-hidden":`true`,className:t?`codex-auth-advanced__chevron is-open`:`codex-auth-advanced__chevron`})]}),t&&(0,Y.jsx)(`div`,{id:`codex-auth-advanced-boxes`,className:`codex-auth-advanced__boxes`,children:r})]})}function Oc(e,t){let[n,r]=(0,_.useState)(80),[i,a]=(0,_.useState)(`80`),[o,s]=(0,_.useState)(!1),[c,l]=(0,_.useState)(!1),[u,d]=(0,_.useState)(!1),[f,p]=(0,_.useState)(null),m=(0,_.useRef)(80),h=(0,_.useRef)(!1),g=(0,_.useRef)(80),v=(0,_.useRef)(!1),y=(0,_.useRef)(!1),b=(0,_.useRef)(!1),x=(0,_.useRef)(0),S=(0,_.useRef)(null),C=(0,_.useRef)(null),w=(0,_.useCallback)(e=>{m.current=e,h.current=!0,s(!0),r(e),e>0&&(g.current=e),a(String(e>0?e:g.current))},[]),T=(0,_.useCallback)(e=>{if(v.current||y.current){S.current=e;return}S.current=null,w(e)},[w]),E=(0,_.useCallback)(()=>{let e=S.current;return e!==null&&(S.current=null,w(e),!0)},[w]),D=(0,_.useCallback)(()=>{C.current!==null&&(window.clearTimeout(C.current),C.current=null),p(null)},[]),O=(0,_.useCallback)((e,t)=>{C.current!==null&&window.clearTimeout(C.current),p({tone:t?`err`:`ok`,message:e}),C.current=window.setTimeout(()=>{p(null),C.current=null},5e3)},[]);(0,_.useEffect)(()=>()=>{C.current!==null&&window.clearTimeout(C.current)},[]);let k=(0,_.useCallback)(()=>(h.current||l(!1),x.current),[]),A=(0,_.useCallback)((e,t)=>{l(!1);let n=ic(e),r=rc(v.current,y.current,t,x.current);r===`defer`?S.current=ec(n):r===`apply`&&T(ec(n))},[T]),j=(0,_.useCallback)(e=>{h.current||v.current||y.current||(l(!1),w(ec(ic(e))))},[w]),M=(0,_.useCallback)(()=>{h.current||l(!0)},[]),N=(0,_.useCallback)(async(n,r,i=!0)=>{if(y.current)return!1;y.current=!0,v.current=!1,D(),d(!0),x.current+=1;try{let a=await oc(e,n);return x.current+=1,a?(S.current=null,w(n),i&&O(t.updated,!1)):(E()||w(r),O(t.updateFailed,!0)),a}finally{y.current=!1,d(!1)}},[e,w,D,t.updateFailed,t.updated,E,O]),P=(0,_.useCallback)(()=>{v.current=!1;let e=m.current;E()||a(String(e>0?e:g.current)),O(t.invalid,!0)},[t.invalid,E,O]),F=(0,_.useCallback)(()=>{v.current=!1,b.current=!0,D();let e=m.current;E()||a(String(e>0?e:g.current))},[D,E]),I=(0,_.useCallback)(async()=>{if(b.current)return b.current=!1,!0;if(!h.current||y.current)return!1;let e=m.current;v.current=!1;let t=tc(i);return t===null?(P(),!1):t===e?(E()||a(String(t)),!0):N(t,e)},[i,E,P,N]),L=(0,_.useCallback)(async()=>{if(!h.current||y.current)return!1;let e=m.current;v.current=!1;let t=ac(e,i,g.current),n=await N(t.threshold,e);return n?(g.current=t.lastEnabled,t.threshold===0&&a(String(t.lastEnabled)),n):!1},[i,N]);return{threshold:n,draft:i,hydrated:o,saving:u,loadError:c,feedback:f,beginServerRead:k,acceptServerRead:A,hydrateServerValue:j,rejectServerRead:M,setDraft:(0,_.useCallback)(e=>{h.current&&(v.current=!0,b.current=!1,D(),a(e))},[D]),setEditing:(0,_.useCallback)(e=>{v.current=e},[]),commit:I,cancel:F,toggle:L,retry:(0,_.useCallback)(()=>{l(!1),D()},[D])}}function kc({value:e,disabled:t=!1,selectId:n,onChange:r}){let i=Q(),a=Ms(e),o=i(`accountPool.priorityHint`),s=`${n}-hint`,c=As.map(e=>({value:String(e),label:Is(i,e)})),l=Ps(a)?c:[{value:String(a),label:Is(i,a)},...c];return(0,Y.jsxs)(`div`,{className:`codex-account-priority`,children:[(0,Y.jsx)(`label`,{className:`codex-account-priority-label`,htmlFor:n,children:i(`accountPool.priority`)}),(0,Y.jsx)(kt,{id:n,value:String(a),options:l,disabled:t,label:i(`accountPool.priorityAria`),describedBy:s,title:o,onChange:e=>r(Ms(Number.parseInt(e,10)))}),(0,Y.jsx)(`span`,{id:s,className:`sr-only`,children:o})]})}function Ac({value:e}){let t=Q(),n=Ms(e);return n===0?null:(0,Y.jsx)(`span`,{className:`badge badge-muted`,children:Is(t,n)})}function jc(e,t){return`${e??``}\0${JSON.stringify(t)}`}var Mc={month:`short`,day:`numeric`,year:`numeric`},Nc={month:`short`,day:`numeric`,year:`numeric`,hour:`2-digit`,minute:`2-digit`},Pc=new Map;function Fc(e,t){let n=jc(e,t),r=Pc.get(n);return r||(r=new Intl.DateTimeFormat(e,t),Pc.set(n,r)),r}function Ic(e,t){let n=new Date(e);return Number.isNaN(n.getTime())?`—`:Fc(t,Mc).format(n)}function Lc(e,t){let n=new Date(e);return Number.isNaN(n.getTime())?`—`:Fc(t,Nc).format(n)}var Rc=new Intl.NumberFormat(`en-US`,{style:`currency`,currency:`USD`,currencyDisplay:`narrowSymbol`,minimumFractionDigits:4,maximumFractionDigits:4});function zc(e,t){return!Number.isFinite(e)||e<0?`—`:`~${Rc.format(e)}`}function Bc(e,t){return Ic(e,t)}function Vc(e,t){return Lc(e,t)}function Hc(e){return Math.max(0,Math.ceil((new Date(e).getTime()-Date.now())/864e5))}function Uc({index:e,grantedAt:t,expiresAt:n,isNext:r,locale:i,t:a}){let o=Hc(n),s=o<=7;return(0,Y.jsxs)(`div`,{className:`credit-item${r?` credit-next`:``}`,children:[(0,Y.jsxs)(`div`,{className:`credit-item-head`,children:[(0,Y.jsx)(Ae,{width:13}),(0,Y.jsx)(`span`,{className:`credit-item-label`,children:r?a(`codexAuth.creditNext`):a(`codexAuth.creditLabel`,{n:String(e+1)})}),r&&(0,Y.jsx)(`span`,{className:`badge badge-amber text-micro`,style:{padding:`1px 6px`},children:a(`codexAuth.creditNextBadge`)})]}),(0,Y.jsxs)(`div`,{className:`credit-item-dates`,children:[(0,Y.jsx)(`span`,{children:a(`codexAuth.creditGranted`,{date:Bc(t,i)})}),(0,Y.jsx)(`span`,{className:s?`credit-urgent`:``,children:a(`codexAuth.creditExpires`,{date:Vc(n,i),days:String(o)})})]})]})}function Wc({account:e,onClick:t,t:n}){let r=e.quota?.resetCredits;return e.quota==null?(0,Y.jsxs)(`span`,{className:`badge badge-muted codex-ticket-badge-slot`,"aria-hidden":`true`,children:[(0,Y.jsx)(Ae,{width:12}),`0`]}):r===void 0?null:(0,Y.jsxs)(`button`,{type:`button`,className:`badge ${typeof r==`number`&&r>0?`badge-amber`:`badge-muted`} badge-clickable`,onClick:e=>{e.stopPropagation(),t()},"aria-label":n(`codexAuth.resetCreditsAria`,{count:String(r)}),children:[(0,Y.jsx)(Ae,{width:12}),r]})}function Gc({t:e,paused:t,saving:n}){let r=e(`codexAuth.pause`),i=e(`codexAuth.resume`),a=e(`common.saving`),o=n?a:t?i:r,s=Math.max(r.length,i.length,a.length);return(0,Y.jsx)(`span`,{className:`codex-auth-pause-label`,style:{minWidth:`${s}ch`},children:o})}function Kc({pool:e,activeId:t,accountModeState:n,switchActionLabel:r,threshold:i,onOpenReset:a,onSwitch:o,onTogglePause:s,pauseUpdatingId:c,pauseBusy:l,onPriorityChange:u,priorityUpdatingId:d,switchingId:f,pinnedId:p=null,onReauth:m,onEditAlias:h,onRemove:g,onCopyDoctor:v,doctorCopyOutcomeFor:y}){let b=Q(),x=e=>!e.paused&&t===e.id,S=_s(),[C,w]=(0,_.useState)(new Set);return(0,Y.jsx)(Y.Fragment,{children:e.map(e=>{let t=e.health?.status,_=e.selectionExcludedReason===`plan_excluded`,T=!!e.needsReauth||rs(t),E=as(t),D=e.health?.reason===`validation_pending`,O=cs(b,e.health),k=ls(b,`codex`,e.id,e.health);return(0,Y.jsxs)(`div`,{className:`card ${x(e)?`card-active`:``}`,style:{marginBottom:8},children:[(0,Y.jsxs)(`div`,{className:`card-head`,children:[(0,Y.jsx)(`span`,{className:`dot ${T?`dot-amber`:x(e)?`dot-blue`:`dot-muted`}`}),(0,Y.jsx)(`strong`,{children:e.alias??e.email}),(0,Y.jsxs)(`span`,{className:`card-badges`,children:[e.plan&&(0,Y.jsx)(`span`,{className:`badge badge-green`,children:e.plan}),_&&(0,Y.jsx)(`span`,{className:`badge badge-muted`,title:b(`codexAuth.planExcludedHint`,{plan:e.selectionExcludedPlan??e.plan??``}),children:b(`codexAuth.planExcluded`)}),e.paused&&(0,Y.jsx)(`span`,{className:`badge badge-muted`,title:b(`codexAuth.pausedHint`),children:b(`codexAuth.paused`)}),(0,Y.jsx)(Ac,{value:e.priority}),e.id===p&&!e.paused&&(0,Y.jsx)(`span`,{className:`badge badge-muted`,children:b(`codexAuth.pinned`)}),(0,Y.jsx)(Wc,{t:b,account:e,onClick:()=>a(e)}),O&&(0,Y.jsx)(`span`,{className:ns(t),children:O}),T&&!O&&(0,Y.jsx)(`span`,{className:`badge badge-amber`,children:b(`codexAuth.needsReauth`)}),x(e)&&!_&&!T&&!E&&!D&&(0,Y.jsx)(`span`,{className:`badge badge-primary`,children:b(n===`direct`?`codexAuth.poolPrepared`:`codexAuth.nextSession`)})]}),!e.paused&&!_&&(!x(e)||p!==e.id)&&!T&&!E&&!D&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-account-switch`,onClick:()=>o(e),children:r}),T&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>m(e.id),children:b(`codexAuth.reauthenticate`)}),v&&os(t)&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-auth-action-btn`,onClick:()=>v(e.id),children:(0,Y.jsx)(`span`,{"aria-live":`polite`,children:fs(b,y?.(e.id))})}),(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:()=>s(e),disabled:l,title:e.paused?b(`codexAuth.pausedHint`):void 0,"aria-label":e.paused?`${b(`codexAuth.resume`)}. ${b(`codexAuth.pausedHint`)}`:b(`codexAuth.pause`),children:[e.paused?(0,Y.jsx)(pe,{width:14}):(0,Y.jsx)(fe,{width:14}),(0,Y.jsx)(Gc,{t:b,paused:e.paused,saving:c===e.id})]}),(0,Y.jsxs)(`details`,{className:`codex-account-more card-right`,open:C.has(e.id),onToggle:t=>{let n=t.currentTarget.open;w(t=>{let r=new Set(t);return n?r.add(e.id):r.delete(e.id),r})},children:[(0,Y.jsx)(`summary`,{className:`btn btn-ghost btn-sm`,"aria-label":`${b(`codexAuth.moreActions`)} — ${e.email}`,title:b(`codexAuth.moreActions`),children:`⋯`}),(0,Y.jsxs)(`div`,{className:`codex-account-more-body`,children:[(0,Y.jsxs)(`span`,{className:`mono text-caption muted`,children:[b(`prov.accountId`),`: `,es(e.id)]}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>S.copy(e.id,e.id),children:S.outcomeFor(e.id)===`copied`?b(`startup.copied`):b(`codexAuth.copyId`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void h(e),children:b(`prov.editAlias`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn-icon btn-icon-danger`,"aria-label":`${b(`common.remove`)} — ${e.email}`,title:`${b(`common.remove`)} — ${e.email}`,onClick:t=>{t.stopPropagation(),g(e.id)},children:(0,Y.jsx)(le,{width:14})})]})]})]}),(0,Y.jsxs)(`div`,{className:`codex-account-identity`,children:[(0,Y.jsxs)(`div`,{className:`codex-account-identity-copy`,children:[e.email,e.plan?` · ${e.plan}`:``]}),(Ms(e.priority)!==0||C.has(e.id))&&(0,Y.jsx)(kc,{value:e.priority,selectId:`codex-account-priority-${e.id}`,disabled:d!==null||f!==null,onChange:t=>u(e,t)})]}),k&&(0,Y.jsx)(`div`,{className:`card-sub faint`,children:k}),E&&(0,Y.jsx)(`div`,{className:`card-sub faint`,children:b(`pws.healthCooldownHint`)}),T?(0,Y.jsx)(`div`,{className:`card-sub faint`,children:b(`codexAuth.tokenExpired`)}):!E&&(0,Y.jsx)(Y.Fragment,{children:(0,Y.jsx)(xa,{quota:e.quota,plan:e.plan,threshold:i,t:b,pending:e.quota==null})})]},e.id)})})}function qc({onReauth:e}){let t=Q();return(0,Y.jsxs)(`div`,{className:`notice-warn`,style:{marginBottom:12,display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:12,flexWrap:`wrap`},children:[(0,Y.jsxs)(`span`,{children:[(0,Y.jsx)(_e,{width:14}),` `,t(`codexAuth.tokenExpired`)]}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:e,children:t(`codexAuth.reauthenticate`)})]})}function Jc({confirm:e,mainEmail:t,accountModeState:n,switchingId:r,orderBusy:i=!1,onCancel:a,onConfirm:o}){let s=Q(),c=(0,_.useRef)(null);(0,_.useEffect)(()=>{let e=c.current;e&&!e.open&&e.showModal()},[]);let l=(0,_.useCallback)(e=>{e.preventDefault(),a()},[a]);return(0,Y.jsxs)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":`codex-switch-title`,onCancel:l,children:[(0,Y.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":s(`common.close`),tabIndex:-1,onClick:a}),(0,Y.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),role:`document`,children:[(0,Y.jsx)(`h3`,{id:`codex-switch-title`,children:n===`direct`?s(`codexAuth.preparePoolTitle`):e.id===`__main__`?s(`codexAuth.switchBack`):s(`codexAuth.switchTitle`)}),(0,Y.jsx)(`p`,{className:`modal-desc`,children:n===`direct`?s(`codexAuth.preparePoolDesc`):e.id===`__main__`?s(`codexAuth.switchBackDesc`):s(`codexAuth.switchDesc`)}),(0,Y.jsxs)(`div`,{className:`card`,style:{margin:`12px 0`},children:[(0,Y.jsx)(`strong`,{children:e.id===`__main__`?t||s(`codexAuth.codexApp`):e.email}),e.plan&&(0,Y.jsx)(`span`,{className:`badge badge-green`,style:{marginLeft:8},children:e.plan})]}),e.id!==`__main__`&&(0,Y.jsxs)(`div`,{className:`notice-warn`,children:[(0,Y.jsx)(_e,{width:14}),` `,s(`codexAuth.cacheWarning`)]}),(0,Y.jsxs)(`div`,{className:`modal-actions`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:a,children:s(`codexAuth.cancel`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!!r||i,onClick:o,children:s(r?`pws.accountSwitching`:n===`direct`?`codexAuth.prepareForPool`:`codexAuth.setAsNext`)})]})]})]})}function Yc({resetPopup:e,resetConfirm:t,creditDetails:n,creditDetailsLoading:r,redeeming:i,onClose:a,onShowConfirm:o,onCancelConfirm:s,onRedeem:c}){let{locale:l,t:u}=ut(),d=(0,_.useRef)(null);(0,_.useEffect)(()=>{let e=d.current;e&&!e.open&&e.showModal()},[]);let f=(0,_.useCallback)(e=>{e.preventDefault(),a()},[a]);return(0,Y.jsxs)(`dialog`,{ref:d,className:`modal-overlay`,"aria-labelledby":`codex-reset-title`,onCancel:f,children:[(0,Y.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":u(`common.close`),tabIndex:-1,onClick:a}),(0,Y.jsx)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),role:`document`,children:t?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{style:{textAlign:`center`,padding:`12px 0`},children:[(0,Y.jsx)(`div`,{className:`confirm-icon`,children:(0,Y.jsx)(_e,{width:22})}),(0,Y.jsx)(`h3`,{id:`codex-reset-title`,children:u(`codexAuth.confirmResetTitle`)}),(0,Y.jsx)(`p`,{className:`modal-desc`,children:u(`codexAuth.confirmResetDesc`,{count:String(e.quota?.resetCredits??0)})}),n&&n[0]&&(0,Y.jsx)(`p`,{className:`faint text-label`,children:u(`codexAuth.confirmWhichCredit`,{date:Bc(n[0].granted_at,l)})}),(0,Y.jsx)(`p`,{className:`faint text-label`,children:u(`codexAuth.irreversible`)})]}),(0,Y.jsxs)(`div`,{className:`modal-actions`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:s,children:u(`codexAuth.cancel`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:c,disabled:i,children:u(i?`codexAuth.redeeming`:`codexAuth.useCredit`)})]})]}):(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`h3`,{id:`codex-reset-title`,children:[(0,Y.jsx)(Ae,{width:16}),` `,u(`codexAuth.resetCreditsTitle`)]}),(0,Y.jsxs)(`div`,{className:`card-sub`,children:[e.email,e.plan?` · ${e.plan}`:``]}),(0,Y.jsx)(`div`,{style:{margin:`16px 0`},children:(e.quota?.resetCredits??0)>0?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`p`,{style:{marginBottom:12},children:u(`codexAuth.resetCreditsAvailable`,{count:String(e.quota?.resetCredits??0)})}),r&&(0,Y.jsx)(`p`,{className:`faint text-label`,children:u(`common.loading`)}),n&&n.length>0&&(0,Y.jsx)(`div`,{className:`credit-list`,children:n.map((e,t)=>(0,Y.jsx)(Uc,{index:t,grantedAt:e.granted_at,expiresAt:e.expires_at,isNext:t===0,locale:l,t:u},`${e.granted_at}:${e.expires_at}`))}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary`,style:{marginTop:12,width:`100%`},onClick:o,disabled:i,children:u(`codexAuth.useOneCredit`)}),(0,Y.jsx)(`p`,{className:`card-sub text-caption`,style:{marginTop:8,textAlign:`center`},children:u(`codexAuth.fifoNote`)})]}):(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`p`,{className:`faint`,children:u(`codexAuth.noResetCredits`)}),(0,Y.jsx)(`p`,{className:`modal-desc`,children:u(`codexAuth.earnCreditsHint`)})]})})]})})]})}function Xc({t:e,main:t,isMainActive:n,accountModeState:r,threshold:i,switchActionLabel:a,onSwitch:o,onTogglePause:s,pauseUpdatingId:c,pauseBusy:l,onPriorityChange:u,priorityUpdatingId:d,switchingId:f,pinnedId:p=null,onOpenReset:m,onCopyDoctor:h,doctorCopyOutcomeFor:g,onManageMainHardLock:_,mainReauth:v}){let y=e(`codexAuth.codexApp`),b=t?.id??`__main__`,x={id:`__main__`,email:t?.email||y,plan:t?.plan,isMain:!0,paused:t?.paused??!1,priority:t?.priority??0,hasCredential:!0,quota:t?.quota??null,quotaAutoRefresh:t?.quotaAutoRefresh??{fiveHourAvailable:!1,weeklyAvailable:!1,fiveHourEnabled:!1,weeklyEnabled:!1}},S=!!t?.needsReauth||rs(t?.health?.status),C=as(t?.health?.status),w=t?.mainAccountHardLock,T=w?.enabled===!0&&w.state===`blocked`,E=cs(e,t?.health),D=t?ls(e,`codex`,b,t.health):null;return(0,Y.jsxs)(`div`,{className:`card ${n&&!T?`card-active`:``}`,style:{marginBottom:12},children:[(0,Y.jsxs)(`div`,{className:`card-head`,children:[(0,Y.jsx)(`span`,{className:`dot ${S||T?`dot-amber`:`dot-green`}`}),(0,Y.jsx)(`strong`,{children:e(`codexAuth.mainAccount`)}),(0,Y.jsxs)(`span`,{className:`card-badges`,children:[t?.plan&&(0,Y.jsx)(`span`,{className:`badge badge-green`,children:t.plan}),t?.paused&&(0,Y.jsx)(`span`,{className:`badge badge-muted`,title:e(`codexAuth.pausedHint`),children:e(`codexAuth.paused`)}),(0,Y.jsx)(Ac,{value:x.priority}),p===`__main__`&&!t?.paused&&(0,Y.jsx)(`span`,{className:`badge badge-muted`,children:e(`codexAuth.pinned`)}),t&&(0,Y.jsx)(Wc,{t:e,account:{...t,id:`__main__`},onClick:()=>m({...t,id:`__main__`})}),E&&(0,Y.jsx)(`span`,{className:ns(t?.health?.status),children:E}),S&&!E&&(0,Y.jsx)(`span`,{className:`badge badge-amber`,children:e(`codexAuth.needsReauth`)}),!t?.paused&&!T&&(0,Y.jsx)(`span`,{className:`badge ${n?`badge-primary`:`badge-muted`}`,children:e(n?r===`direct`?`codexAuth.poolPrepared`:`codexAuth.nextSession`:`codexAuth.current`)})]}),!t?.paused&&!T&&(!n||p!==`__main__`)&&!S&&!C&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-account-switch`,onClick:()=>o(x),children:a}),h&&os(t?.health?.status)&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-auth-action-btn`,onClick:()=>h(b),children:(0,Y.jsx)(`span`,{"aria-live":`polite`,children:fs(e,g?.(b))})}),t&&(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:()=>s(x),disabled:l,title:t.paused?e(`codexAuth.pausedHint`):void 0,"aria-label":t.paused?`${e(`codexAuth.resume`)}. ${e(`codexAuth.pausedHint`)}`:e(`codexAuth.pause`),children:[t.paused?(0,Y.jsx)(pe,{width:14}):(0,Y.jsx)(fe,{width:14}),(0,Y.jsx)(Gc,{t:e,paused:!!t.paused,saving:c===`__main__`})]}),(0,Y.jsxs)(`span`,{className:`card-right`,children:[(0,Y.jsx)(ke,{width:14}),` `,e(`codexAuth.appLogin`)]})]}),(0,Y.jsxs)(`div`,{className:`codex-account-identity`,children:[(0,Y.jsxs)(`div`,{className:`codex-account-identity-copy`,children:[t?.email||e(`codexAuth.appLogin`),t?.plan?` · ${t.plan}`:``]}),t&&(0,Y.jsx)(kc,{value:x.priority,selectId:`codex-account-priority-${x.id}`,disabled:d!==null||f!==null,onChange:e=>u(x,e)})]}),w?.enabled&&(0,Y.jsxs)(`div`,{className:`codex-main-hard-lock-status${T?` is-blocked`:``}`,children:[(0,Y.jsx)(`p`,{role:`status`,children:e(T?`codexAuth.mainHardLockBlocked`:w.state===`ready`?`codexAuth.mainHardLockMonitoring`:`codexAuth.mainHardLockUnknown`)}),_?(0,Y.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:_,children:e(`codexAuth.mainHardLockManage`)}):(0,Y.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>ht(`codex-set`),children:e(`codexAuth.mainHardLockManage`)})]}),D&&(0,Y.jsx)(`div`,{className:`card-sub faint`,children:D}),C&&(0,Y.jsx)(`div`,{className:`card-sub faint`,children:e(`pws.healthCooldownHint`)}),S?(0,Y.jsxs)(`div`,{className:`card-sub faint`,children:[(0,Y.jsx)(`p`,{role:`status`,children:e(`codexAuth.mainTokenExpired`)}),v&&(v.state.phase===`idle`||v.state.phase===`failed`)&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-auth-action-btn`,onClick:()=>{v.start()},children:e(`codexAuth.mainReauthDevice`)}),v.state.phase===`failed`&&(0,Y.jsxs)(`span`,{className:`badge badge-amber`,children:[e(`codexAuth.mainReauthFailed`),`: `,v.state.code]})]}),v&&v.state.phase===`starting`&&(0,Y.jsx)(`span`,{className:`faint`,children:e(`codexAuth.mainReauthPending`)}),v&&(v.state.phase===`pending`||v.state.phase===`committing`)&&(0,Y.jsxs)(`span`,{className:`codex-main-reauth-pending`,children:[v.state.verificationUrl&&(0,Y.jsxs)(`span`,{children:[e(`codexAuth.mainReauthOpen`),`: `,v.state.verificationUrl]}),v.state.deviceCode&&(0,Y.jsxs)(`strong`,{children:[e(`codexAuth.mainReauthCode`),`: `,v.state.deviceCode]}),(0,Y.jsx)(`span`,{className:`faint`,children:e(`codexAuth.mainReauthPending`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-auth-action-btn`,onClick:()=>{v.cancel()},children:e(`codexAuth.mainReauthCancel`)})]}),v&&v.state.phase===`succeeded`&&(0,Y.jsx)(`span`,{className:`badge badge-primary`,children:e(`codexAuth.mainReauthSucceeded`)})]}):!C&&(0,Y.jsx)(Y.Fragment,{children:(0,Y.jsx)(xa,{quota:t?.quota??null,plan:t?.plan,threshold:i,t:e,pending:t!=null&&t.quota==null})})]})}function Zc({t:e,embedded:t,refreshingQuota:n,pausingExhausted:r,pauseBusy:i,actionFeedback:a,actionFeedbackTone:o,onRefresh:s,onPauseExhausted:c}){return(0,Y.jsxs)(`div`,{className:t?`row`:`page-head codex-auth-page-head`,style:t?{justifyContent:`flex-end`,marginBottom:8}:void 0,children:[!t&&(0,Y.jsx)(`h2`,{className:`page-title`,children:e(`nav.codexAuth`)}),(0,Y.jsxs)(`div`,{className:t?`row`:`codex-auth-page-head__actions`,children:[(0,Y.jsx)(`span`,{className:`codex-auth-page-head__feedback${o===`ok`?` is-ok`:``}${o===`warn`?` is-warn`:``}${o===`err`?` is-err`:``}`,role:`status`,"aria-live":`polite`,children:a??``}),t&&(0,Y.jsx)(Qc,{t:e,refreshingQuota:n,pausingExhausted:r,pauseBusy:i,onRefresh:s,onPauseExhausted:c})]})]})}function Qc({t:e,refreshingQuota:t,pausingExhausted:n,pauseBusy:r,onRefresh:i,onPauseExhausted:a}){return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:a,disabled:t||n||!!r,children:[(0,Y.jsx)(fe,{width:14}),` `,e(n?`codexAuth.pausingExhausted`:`codexAuth.pauseExhausted`)]}),(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:i,disabled:t||n||!!r,children:[(0,Y.jsx)(de,{width:14}),` `,e(t?`codexAuth.refreshingQuota`:`codexAuth.refreshQuota`)]})]})}function $c(e){return(0,Y.jsx)(`div`,{className:`codex-auth-actions-row`,children:(0,Y.jsx)(Qc,{...e})})}function el({t:e,loadState:t,accountsCount:n,onRetry:r}){return t===`loading`&&n===0?(0,Y.jsxs)(`div`,{className:`codex-auth-load-skeleton`,role:`status`,"aria-live":`polite`,"aria-busy":`true`,children:[(0,Y.jsxs)(`div`,{className:`card codex-auth-load-skeleton__main`,style:{marginBottom:12},"aria-hidden":`true`,children:[(0,Y.jsxs)(`div`,{className:`card-head`,children:[(0,Y.jsx)(`span`,{className:`dot dot-muted`}),(0,Y.jsx)(`strong`,{children:e(`codexAuth.mainAccount`)}),(0,Y.jsxs)(`span`,{className:`card-badges`,children:[(0,Y.jsxs)(`span`,{className:`badge badge-muted codex-ticket-badge-slot`,"aria-hidden":`true`,children:[(0,Y.jsx)(Ae,{width:12}),`0`]}),(0,Y.jsx)(`span`,{className:`badge badge-primary`,children:e(`codexAuth.nextSession`)})]}),(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,tabIndex:-1,disabled:!0,children:[(0,Y.jsx)(fe,{width:14}),` `,e(`codexAuth.pause`)]}),(0,Y.jsxs)(`span`,{className:`card-right`,children:[(0,Y.jsx)(ke,{width:14}),` `,e(`codexAuth.appLogin`)]})]}),(0,Y.jsxs)(`div`,{className:`card-sub`,children:[(0,Y.jsx)(`span`,{className:`codex-auth-load-skeleton__strut`,children:e(`codexAuth.appLogin`)}),(0,Y.jsx)(`span`,{className:`codex-auth-load-skeleton__line codex-auth-load-skeleton__line--sub`})]}),(0,Y.jsx)(xa,{quota:null,threshold:0,t:e,pending:!0})]}),(0,Y.jsxs)(`div`,{className:`section-sep`,"aria-hidden":`true`,children:[(0,Y.jsx)(`span`,{className:`section-label`,children:e(`codexAuth.accountPool`)}),(0,Y.jsx)(`div`,{className:`sep-line`}),(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,tabIndex:-1,disabled:!0,children:[(0,Y.jsx)(ue,{width:14}),` `,e(`codexAuth.add`)]})]}),(0,Y.jsx)(`div`,{className:`empty codex-auth-pool-empty codex-auth-load-skeleton__empty`,"aria-hidden":`true`,children:(0,Y.jsx)(`div`,{className:`title`,children:e(`codexAuth.noPool`)})}),(0,Y.jsx)(`span`,{className:`sr-only`,children:e(`pws.accountsLoading`)})]}):t===`error`?(0,Y.jsxs)(`div`,{className:`pwi-auth-state pwi-auth-state--error`,role:`alert`,children:[(0,Y.jsx)(`span`,{children:e(`codexAuth.loadFailed`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:r,children:e(`pws.retryAccounts`)})]}):null}function tl(e,t){return t===void 0?e(`codexAuth.resetSuccessGeneric`):e(`codexAuth.resetSuccess`,{remaining:String(t)})}async function nl(e,t,n,r){try{let i=await Lt(await fetch(`${e}/api/codex-auth/reset-credits/consume`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({accountId:t})}));return i?i.code===`reset`||i.code===`already_redeemed`?(await r(!0),{ok:!0,close:!0,toast:tl(n,typeof i.remaining==`number`&&Number.isFinite(i.remaining)?Math.max(0,i.remaining):void 0)}):{ok:!1,close:!0,toast:n(i.code===`nothing_to_reset`?`codexAuth.resetNothingToReset`:i.code===`no_credit`?`codexAuth.resetNoCredit`:`codexAuth.resetError`)}:{ok:!1,toast:n(`codexAuth.resetError`)}}catch{return{ok:!1,toast:n(`codexAuth.resetError`)}}}function rl({windows:e,ready:t,busy:n,loadError:r,feedback:i,onToggle:a,onRetry:o}){let s=Q(),c=e.filter(e=>e.available),l=e.some(e=>e.enabled),u=c.length?c.every(e=>e.enabled):l,d=l&&!u,f=c.length===0&&!l,p=n?s(`common.saving`):r?s(`codexAuth.quotaAutoRefreshLoadFailed`):t?i?.message??(f?s(`codexAuth.quotaAutoRefreshEmpty`):d?s(`codexAuth.quotaAutoRefreshMixed`):``):s(`common.loading`),m=!n&&(r||i?.failed);return(0,Y.jsxs)(`div`,{id:`codex-quota-activation`,className:`card card-row codex-quota-activation`,"aria-busy":n||!t&&!r||void 0,children:[(0,Y.jsxs)(`div`,{className:`codex-quota-activation__copy`,children:[(0,Y.jsx)(`strong`,{children:s(`codexAuth.quotaAutoRefresh`)}),(0,Y.jsx)(`div`,{id:`codex-quota-activation-desc`,className:`card-sub`,children:s(`codexAuth.quotaAutoRefreshAllHint`)}),p&&(0,Y.jsx)(`div`,{className:`card-sub${m?` is-error`:``}`,role:m?`alert`:`status`,children:p})]}),(0,Y.jsxs)(`div`,{className:`codex-quota-activation__controls`,children:[m&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:n,onClick:o,children:s(`common.retry`)}),(0,Y.jsx)(`button`,{type:`button`,className:`toggle ${t&&u?`on`:``}`,"aria-label":s(`codexAuth.quotaAutoRefresh`),"aria-describedby":`codex-quota-activation-desc`,"aria-pressed":t?d?`mixed`:u:void 0,disabled:!t||n||f,onClick:()=>a(!u),children:(0,Y.jsx)(`span`,{className:`toggle-knob`})})]})]})}function il(e){let t=e&&typeof e==`object`&&`codexQuotaAutoRefresh`in e?e.codexQuotaAutoRefresh:null;if(!t||typeof t!=`object`||Array.isArray(t)||Object.values(t).some(e=>!e||typeof e!=`object`||Array.isArray(e)||[e.fiveHour,e.weekly].some(e=>e!==void 0&&typeof e!=`boolean`)))throw Error(`Invalid quota activation settings`);return t}function al(e,t){return e.flatMap(e=>{let n=e.isMain?`__main__`:e.id,r=e.quotaAutoRefresh??ia(e.quota);return[`fiveHour`,`weekly`].map(e=>({id:n,window:e,available:r[e===`fiveHour`?`fiveHourAvailable`:`weeklyAvailable`],enabled:t[n]?.[e]===!0}))})}function ol(e){let t=Q(),n=(0,_.useId)(),r=(0,_.useRef)(null),i=(0,_.useRef)(null);(0,_.useEffect)(()=>{let e=document.activeElement;return i.current?.focus(),()=>{e?.isConnected&&typeof e.focus==`function`&&e.focus()}},[]);let a=e.selection?.status===`pending`,o=e.failed||!e.providerKnown,s=e.loading?t(`prov.modelsNoticeChecking`):o?t(`prov.modelsNoticeFailed`):a?t(`prov.modelsNoticePending`):e.initialRegistration&&e.selection?.status===`all-off`?t(`prov.modelsNoticeOff`):t(`prov.modelsNoticeReady`);return(0,Y.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":n,onKeyDown:t=>{if(t.key===`Escape`&&(t.preventDefault(),t.stopPropagation(),e.onClose()),t.key!==`Tab`)return;let n=r.current?.querySelectorAll(`button:not([disabled])`),i=n?.[0],a=n?.[n.length-1];t.shiftKey&&document.activeElement===i?(t.preventDefault(),a?.focus()):!t.shiftKey&&document.activeElement===a&&(t.preventDefault(),i?.focus())},children:(0,Y.jsxs)(`div`,{className:`modal-card`,ref:r,children:[(0,Y.jsx)(`div`,{className:`modal-head`,children:(0,Y.jsx)(`h2`,{id:n,style:{fontSize:`var(--text-subtitle)`,margin:0},children:t(`prov.modelsNoticeTitle`)})}),(0,Y.jsx)(`p`,{children:(0,Y.jsx)(`strong`,{style:{overflowWrap:`anywhere`},children:e.provider})}),(0,Y.jsx)(`p`,{role:`status`,"aria-live":`polite`,children:s}),e.initialRegistration&&e.selection?.modelCount!==void 0&&(0,Y.jsx)(`p`,{className:`muted`,children:t(`prov.modelsNoticeCount`,{count:e.selection.modelCount})}),e.catalogRefreshPending&&(0,Y.jsx)(`p`,{className:`muted`,role:`status`,children:t(`codexAuth.catalogRefreshPending`)}),!e.loading&&(a||o)&&e.onRetry&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>{e.onRetry?.(),i.current?.focus()},children:t(`common.retry`)}),(0,Y.jsxs)(`div`,{className:`modal-actions`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:e.onClose,children:t(`common.close`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary`,ref:i,onClick:e.onOpenModels,children:t(`prov.modelsNoticeOpen`)})]})]})})}var sl=`ocx doctor`;function cl({apiBase:e,accountModeState:t=null,banner:n=null,embedded:r=!1,onActiveNeedsReauthChange:i,controller:a,advancedExtras:o=null,hasMainHardLockSetting:s=!1}){let c=Q(),l=Oc(e,{updated:c(`codexAuth.autoSwitchUpdated`),updateFailed:c(`codexAuth.autoSwitchUpdateFailed`),invalid:c(`codexAuth.autoSwitchThresholdInvalid`)}),[u,d]=(0,_.useState)(null),{beginServerRead:f,acceptServerRead:p,rejectServerRead:m,hydrateServerValue:h}=l,g=lc(e,!a),v=a??g,{accounts:y,activeId:b,loadState:x,switchingId:S,pauseUpdatingId:C,priorityUpdatingId:w,pausingExhausted:T,activePinnedId:E,load:D}=v,O=_c(e,()=>{D()}),k=O.state.phase===`starting`||O.state.phase===`pending`||O.state.phase===`committing`,[A,j]=(0,_.useState)(null),[M,N]=(0,_.useState)(!1),[P,F]=(0,_.useState)(null),[I,L]=(0,_.useState)(!1),R=(0,_.useRef)(!1),z=(0,_.useCallback)(()=>{let e=document.getElementById(`codex-main-hard-lock-setting`);e?.focus(),e?.scrollIntoView({block:`nearest`})},[]);(0,_.useEffect)(()=>{I&&R.current&&(R.current=!1,z())},[I,z]);let B=()=>{I?z():(R.current=!0,L(!0))},[V,H]=(0,_.useState)(null),[U,W]=(0,_.useState)(null),[G,K]=(0,_.useState)(null),q=(0,_.useRef)(null),[J,X]=(0,_.useState)(!1),[ee,te]=(0,_.useState)(null),[ne,Z]=(0,_.useState)(null),re=(0,_.useRef)(0),ie=(0,_.useRef)(null),ae=(0,_.useRef)(null),[oe,se]=(0,_.useState)(0),[ce,le]=(0,_.useState)(e),[de,fe]=(0,_.useState)(null),pe=(0,_.useRef)(null),me=ne?.apiBase===e&&ne.revision===oe?ne:null,he=me?.settings??null,ge=me?.error??!1,_e=ee===e;ce!==e&&(le(e),se(e=>e+1),Z(null),te(null),fe(null));let[ve,ye]=(0,_.useState)(null),[be,xe]=(0,_.useState)(!1),[Se,Ce]=(0,_.useState)(!1),[we,Te]=(0,_.useState)(null),[Ee,De]=(0,_.useState)(!1),Oe=_s(),ke=(0,_.useCallback)((e,t=`ok`)=>{q.current&&clearTimeout(q.current),W(e),K(t),q.current=setTimeout(()=>{W(null),K(null),q.current=null},5e3)},[]);(0,_.useEffect)(()=>()=>{q.current&&clearTimeout(q.current)},[]);let Ae=(0,_.useCallback)(e=>{Oe.copy(sl,e)},[Oe]),{subscribeLoadObserver:je,readLastThreshold:Me}=v;(0,_.useEffect)(()=>je({beginActiveRead:f,acceptActiveRead:p,rejectActiveRead:m}),[je,f,p,m]),(0,_.useEffect)(()=>{let e=Me();e!==void 0&&h(e)},[Me,h]),(0,_.useEffect)(()=>{if(!M&&!k)return;let e=v.pauseRefresh();return()=>v.resumeRefresh(e)},[v,M,k]);let Ne=b&&b!==`__main__`?y.find(e=>e.id===b):null,Pe=!Ne?.paused&&is(Ne);(0,_.useEffect)(()=>{i?.(Pe)},[Pe,i]);let Fe=(0,_.useCallback)(e=>{H(e),N(!0)},[]),Ie=(0,_.useCallback)(()=>{N(!1),H(null)},[]),Le=(0,_.useCallback)(e=>{v.syncAfterAccountAdded(),ke(c(e.validationPending?`pws.healthLabel.validationPending`:e.catalogRefreshPending?`codexAuth.catalogRefreshPending`:`codexAuth.accountAdded`),e.validationPending||e.catalogRefreshPending?`warn`:`ok`),Ie(),F(e.validationPending?null:{catalogRefreshPending:e.catalogRefreshPending})},[Ie,v,ke,c]),Re=async e=>{let n=await v.switchAccount(e);if(!n.ok){if(n.reason===`busy`)return;ke(c(`codexAuth.switchFailed`),`err`);return}j(null);let r=n.activeId,i=r&&r!==`__main__`?y.find(e=>e.id===r)?.email??c(`pws.accountOrdinal`,{count:`1`}):c(`codexAuth.mainAccount`);ke(c(t===`direct`?`codexAuth.poolPreparedToast`:`codexAuth.switched`,{email:i}))},ze=async e=>{let t=window.prompt(c(`prov.aliasPrompt`),e.alias??``);if(t===null)return;let n=await v.saveAlias(e.id,t);ke(c(n.ok?`prov.aliasSaved`:`prov.aliasSaveFailed`),n.ok?`ok`:`err`)},Be=async e=>{let t=!e.paused,n=await v.setAccountPaused(e.id,t);!n.ok&&n.reason===`busy`||(j(t=>t?.id===e.id?null:t),ke(c(n.ok?t?`codexAuth.pauseSucceeded`:`codexAuth.resumeSucceeded`:t?`codexAuth.pauseFailed`:`codexAuth.resumeFailed`,{email:e.alias??e.email}),n.ok?`ok`:`err`))},Ve=async(e,t)=>{if(t===e.priority)return;let n=await v.setAccountPriority(e.id,t);!n.ok&&n.reason===`busy`||ke(c(n.ok?`accountPool.priorityUpdated`:`accountPool.priorityUpdateFailed`,{email:e.alias??e.email}),n.ok?`ok`:`err`)},He=async e=>{let t=y.find(t=>t.id===e)?.email??c(`pws.accountOrdinal`,{count:`1`});if(!window.confirm(c(`codexAuth.removeConfirm`,{id:t})))return;let n=await v.removeAccount(e);n.ok?n.catalogRefreshPending&&ke(c(`codexAuth.catalogRefreshPending`),`warn`):ke(c(`codexAuth.removeFailed`),`err`)},Ue=async()=>{X(!0);try{let e=await D(!0,{validatePending:!0});ke(c(e?`codexAuth.quotaRefreshed`:`codexAuth.quotaRefreshFailed`),e?`ok`:`err`)}finally{X(!1)}},We=async t=>{let n=ie.current;if(ae.current||!n||n.signal.aborted||he===null||x!==`ready`)return;let r=Xn(3e4);ae.current=r,re.current+=1;let i=()=>ie.current===n&&!n.signal.aborted,a=al(y,he);te(e),fe(null);let o=!1;try{for(let n of a){if(t&&!n.available)continue;let a=t;if(n.enabled!==a){if(!i())return;if(r.signal.aborted){o=!0;break}try{if(!(await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"content-type":`application/json`},signal:r.signal,body:JSON.stringify({codexQuotaAutoRefresh:{id:n.id,window:n.window,enabled:a}})})).ok)throw Error(`save`)}catch{o=!0}}}if(!i())return;r.clear();let n=Xn(15e3);ae.current=n;try{let r=await fetch(`${e}/api/settings`,{signal:n.signal});if(!r.ok)throw Error(`read`);let s=il(await r.json());if(!i())return;o||=a.some(e=>(!t||e.available)&&s[e.id]?.[e.window]===!0!==t),Z({apiBase:e,revision:oe,settings:s,error:!1})}catch{if(!i())return;o=!0,Z({apiBase:e,revision:oe,settings:null,error:!0})}finally{n.clear()}if(!i())return;pe.current=o?{apiBase:e,enabled:t}:null,fe({apiBase:e,message:c(o?`codexAuth.quotaAutoRefreshPartial`:`codexAuth.quotaAutoRefreshUpdated`),failed:o})}finally{r.clear(),i()&&(ae.current=null,te(null))}};(0,_.useEffect)(()=>{let t=new AbortController,n=Xn(15e3);ie.current=t;let r=re.current;return fetch(`${e}/api/settings`,{signal:n.signal}).then(e=>{if(!e.ok)throw Error(`read`);return e.json()}).then(n=>{if(!t.signal.aborted){if(!n)throw Error(`read`);re.current===r&&(Z({apiBase:e,revision:oe,settings:il(n),error:!1}),te(null))}}).catch(()=>{!t.signal.aborted&&re.current===r&&(Z({apiBase:e,revision:oe,settings:null,error:!0}),te(null))}).finally(()=>n.clear()),()=>{t.abort(),n.controller.abort(),n.clear(),ae.current?.controller.abort(),ae.current?.clear(),ae.current=null}},[e,oe]);let Ge=async()=>{let e=await v.pauseExhaustedAccounts();!e.ok&&e.reason===`busy`||ke(e.ok?e.pausedCount>0?c(`codexAuth.pauseExhaustedSucceeded`,{count:String(e.pausedCount)}):c(`codexAuth.pauseExhaustedNone`):c(`codexAuth.pauseExhaustedFailed`),e.ok?`ok`:`err`)},Ke=async t=>{ye(t),xe(!1),Te(null),De(!0);try{let n=await Lt(await fetch(`${e}/api/codex-auth/reset-credits?accountId=${encodeURIComponent(t.id)}`));if(n){let e=(n.credits??[]).sort((e,t)=>new Date(e.granted_at).getTime()-new Date(t.granted_at).getTime());Te(e)}}catch{}finally{De(!1)}},qe=async t=>{Ce(!0);try{let n=await nl(e,t,c,D);n.close&&(ye(null),xe(!1)),n.toast&&ke(n.toast,n.ok?`ok`:`err`)}finally{Ce(!1)}},Je=y.find(e=>e.isMain),Ye=y.filter(e=>!e.isMain),Xe=!Je?.paused&&(!b||b===`__main__`),Ze=c(t===`direct`?`codexAuth.prepareForPool`:`codexAuth.setAsNext`),Qe=C!==null||T,$e=l.threshold??0,et=!r;return(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(Zc,{t:c,embedded:r,refreshingQuota:J,actionFeedback:U,actionFeedbackTone:G,pausingExhausted:T,pauseBusy:Qe,onRefresh:()=>{Ue()},onPauseExhausted:()=>{Ge()}}),n,!r&&(0,Y.jsx)($c,{t:c,refreshingQuota:J,pausingExhausted:T,pauseBusy:Qe,onRefresh:()=>{Ue()},onPauseExhausted:()=>{Ge()}}),(0,Y.jsx)(el,{t:c,loadState:x,accountsCount:y.length,onRetry:()=>{D()}}),(x!==`loading`||y.length!==0)&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(Xc,{t:c,main:Je,isMainActive:Xe,accountModeState:t,threshold:$e,switchActionLabel:Ze,onSwitch:j,onTogglePause:Be,pauseUpdatingId:C,pauseBusy:Qe,onPriorityChange:(e,t)=>{Ve(e,t)},priorityUpdatingId:w,switchingId:S,pinnedId:E,onOpenReset:Ke,onCopyDoctor:et?Ae:void 0,doctorCopyOutcomeFor:et?Oe.outcomeFor:void 0,onManageMainHardLock:s?B:void 0,mainReauth:O}),(0,Y.jsxs)(`div`,{className:`section-sep`,children:[(0,Y.jsx)(`span`,{className:`section-label`,children:c(`codexAuth.accountPool`)}),(0,Y.jsx)(`div`,{className:`sep-line`}),(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,onClick:()=>N(!0),children:[(0,Y.jsx)(ue,{width:14}),` `,c(`codexAuth.add`)]})]}),Pe&&Ne&&(0,Y.jsx)(qc,{onReauth:()=>Fe(Ne.id)}),Ye.length===0&&(0,Y.jsx)(At,{title:c(`codexAuth.noPool`)}),(0,Y.jsx)(Kc,{pool:Ye,activeId:b,accountModeState:t,switchActionLabel:Ze,threshold:$e,onOpenReset:Ke,onSwitch:j,onTogglePause:Be,pauseUpdatingId:C,pauseBusy:Qe,onPriorityChange:(e,t)=>{Ve(e,t)},priorityUpdatingId:w,switchingId:S,pinnedId:E,onReauth:Fe,onEditAlias:ze,onRemove:He,onCopyDoctor:et?Ae:void 0,doctorCopyOutcomeFor:et?Oe.outcomeFor:void 0})]}),(0,Y.jsx)(Ec,{apiBase:e,subscribeLoadObserver:v.subscribeLoadObserver,readLastActive:v.readLastActive,onStrategyResolved:d}),(0,Y.jsxs)(Dc,{t:c,open:I,onToggle:()=>L(e=>!e),children:[(0,Y.jsx)(rl,{windows:al(y,he??{}),ready:he!==null&&x===`ready`,busy:_e,loadError:ge||x===`error`,feedback:de?.apiBase===e?de:null,onToggle:e=>{We(e)},onRetry:()=>{ge||he===null||x!==`ready`?(se(e=>e+1),D()):pe.current?.apiBase===e&&We(pe.current.enabled)}}),u!==null&&(0,Y.jsx)(xc,{threshold:l.threshold,draft:l.draft,strategy:u,hydrated:l.hydrated,saving:l.saving,loadError:l.loadError,feedback:l.feedback,onDraftChange:l.setDraft,onEditingChange:l.setEditing,onCommit:l.commit,onCancel:l.cancel,onToggle:l.toggle,onRetry:()=>{l.retry(),D()}}),o]}),A&&(0,Y.jsx)(Jc,{confirm:A,mainEmail:Je?.email,accountModeState:t,switchingId:S,orderBusy:w!==null,onCancel:()=>j(null),onConfirm:()=>{Re(A.id===`__main__`?`__main__`:A.id)}}),ve&&(0,Y.jsx)(Yc,{resetPopup:ve,resetConfirm:be,creditDetails:we,creditDetailsLoading:Ee,redeeming:Se,onClose:()=>{ye(null),xe(!1),Te(null)},onShowConfirm:()=>xe(!0),onCancelConfirm:()=>xe(!1),onRedeem:()=>{qe(ve.id)}}),M&&(0,Y.jsx)(ks,{apiBase:e,reauthAccountId:V??void 0,onClose:Ie,onAdded:Le}),P&&(0,Y.jsx)(ol,{provider:`openai`,loading:!1,failed:!1,providerKnown:!0,initialRegistration:!1,catalogRefreshPending:P.catalogRefreshPending,onClose:()=>F(null),onOpenModels:()=>{F(null),ht(`models`)}})]})}var ll={"five-hour":`accountPool.quotaWindowFiveHour`,weekly:`accountPool.quotaWindowWeekly`,"max-utilization":`accountPool.quotaWindowMaxUtilization`};function ul({apiBase:e,accountCount:t}){let n=Q(),[r,i]=(0,_.useState)(null),[a,o]=(0,_.useState)(`80`),[s,c]=(0,_.useState)(`1`),[l,u]=(0,_.useState)(!1),[d,f]=(0,_.useState)(null),[p,m]=(0,_.useState)(!1);(0,_.useEffect)(()=>{let t=!1,n=new AbortController;return Promise.resolve().then(()=>Xs(e,`anthropic`,(e,t)=>fetch(e,t),{signal:n.signal})).then(e=>{if(!e)throw Error(`load`);return e}).then(e=>{if(t)return;let n=typeof e.autoSwitchThreshold==`number`?e.autoSwitchThreshold:80,r=Gs(e.stickyLimit);i({enabled:e.enabled===!0,threshold:n,strategy:Us(e.strategy),stickyLimit:r,quotaWindow:Ws(e.quotaWindow)}),o(String(n)),c(String(r)),m(!1)}).catch(()=>{t||n.signal.aborted||m(!0)}),()=>{t=!0,n.abort()}},[e]);let h=(0,_.useCallback)(async t=>{let a=r;i({enabled:t.enabled,threshold:t.threshold,strategy:t.strategy,stickyLimit:t.stickyLimit,quotaWindow:t.quotaWindow}),u(!0),f(null);try{let n=await Zs(e,`anthropic`,{enabled:t.enabled,threshold:t.threshold,strategy:t.strategy,stickyLimit:t.stickyLimit,quotaWindow:t.quotaWindow});if(!n)throw Error(`save`);let r=Us(n?.strategy??t.strategy),a=Gs(n?.stickyLimit??t.stickyLimit),s=Ws(n?.quotaWindow??t.quotaWindow);i({enabled:t.enabled,threshold:t.threshold,strategy:r,stickyLimit:a,quotaWindow:s}),o(String(t.threshold)),c(String(a))}catch{f(n(`anthropicPool.saveFailed`)),a&&(i(a),o(String(a.threshold)),c(String(a.stickyLimit)))}finally{u(!1)}},[e,r,n]),g=r?.enabled===!0,v=r?.threshold??80,y=r?.strategy??`quota`,b=r?.stickyLimit??1,x=r?.quotaWindow??`five-hour`,S=y===`round-robin`,C=r===null&&!p,w=C||l||p||!g&&t<2;return(0,Y.jsxs)(`div`,{className:`card anthropic-pool-card`,"aria-busy":C||l,children:[(0,Y.jsxs)(`div`,{className:`card-row`,style:{alignItems:`flex-start`,gap:12},children:[(0,Y.jsxs)(`div`,{style:{flex:1},children:[(0,Y.jsx)(`strong`,{children:n(`anthropicPool.title`)}),(0,Y.jsx)(`div`,{className:`card-sub`,style:{marginTop:4},children:p?n(`anthropicPool.loadFailed`):C?n(`common.loading`):g?v===0?n(`anthropicPool.enabledNoProactiveDesc`,{window:n(ll[x])}):n(`anthropicPool.enabledDesc`,{threshold:v,window:n(ll[x])}):n(`anthropicPool.disabledDesc`)})]}),(0,Y.jsx)(`button`,{type:`button`,className:`toggle ${g?`on`:``}`,disabled:w,"aria-pressed":g,"aria-label":n(`anthropicPool.title`),title:n(g?`anthropicPool.on`:`anthropicPool.off`),onClick:()=>{h({enabled:!g,threshold:v,strategy:y,stickyLimit:b,quotaWindow:x})},children:(0,Y.jsx)(`span`,{className:`toggle-knob`})})]}),(0,Y.jsx)(`div`,{role:`alert`,className:`card-sub anthropic-pool-card__notice`,children:n(`anthropicPool.experimentalWarning`)}),t<2&&(0,Y.jsx)(`div`,{className:`card-sub`,style:{marginTop:8},children:n(`anthropicPool.needTwoAccounts`)}),g&&r&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`label`,{className:`field anthropic-pool-card__field`,children:[(0,Y.jsx)(`span`,{className:`field-label`,children:n(`anthropicPool.threshold`)}),(0,Y.jsx)(`input`,{className:`input mono`,type:`number`,min:0,max:100,step:1,value:a,disabled:l,"aria-label":n(`anthropicPool.thresholdAria`),onChange:e=>o(e.target.value),onBlur:()=>{let e=Number(a);if(!Number.isInteger(e)||e<0||e>100){o(String(v)),f(n(`anthropicPool.thresholdInvalid`));return}e!==v&&h({enabled:!0,threshold:e,strategy:y,stickyLimit:b,quotaWindow:x})}}),(0,Y.jsx)(`div`,{className:`card-sub`,style:{marginTop:4},children:n(`anthropicPool.thresholdHelp`)})]}),(0,Y.jsx)(wc,{strategy:y,stickyDraft:s,disabled:l,strategySelectId:`anthropic-pool-strategy`,stickyInputId:`anthropic-pool-sticky-limit`,onStrategyChange:e=>{e!==y&&h({enabled:!0,threshold:v,strategy:e,stickyLimit:b,quotaWindow:x})},onStickyDraftChange:c,onStickyCommit:e=>{let t=Ks(e??s);if(t===null){c(String(b)),f(n(`accountPool.stickyLimitInvalid`));return}if(t===b){c(String(t));return}h({enabled:!0,threshold:v,strategy:y,stickyLimit:t,quotaWindow:x})}}),(0,Y.jsxs)(`div`,{className:`field anthropic-pool-card__field anthropic-pool-card__field--quota-window`,children:[(0,Y.jsx)(`span`,{className:`field-label`,children:n(`accountPool.quotaWindow`)}),(0,Y.jsx)(kt,{id:`anthropic-pool-quota-window`,value:x,options:Rs.map(e=>({value:e,label:n(ll[e])})),disabled:l||S,label:n(`accountPool.quotaWindow`),onChange:e=>{let t=Ws(e);t!==x&&h({enabled:!0,threshold:v,strategy:y,stickyLimit:b,quotaWindow:t})}}),(0,Y.jsx)(`div`,{className:`card-sub`,style:{marginTop:4},children:n(`accountPool.quotaWindowDesc`)}),(0,Y.jsx)(`div`,{className:`card-sub`,style:{marginTop:4},children:n(S?`accountPool.quotaWindowInert`:`accountPool.quotaWindowHint`)})]})]}),d&&(0,Y.jsx)(`div`,{role:`alert`,className:`card-sub`,style:{marginTop:8,color:`var(--danger, #c44)`},children:d})]})}function dl({serverDefault:e=!0}){let t=Q(),[n,r]=(0,_.useState)(Ss);return(0,Y.jsxs)(`label`,{className:`open-browser-pref`,children:[(0,Y.jsx)(`input`,{type:`checkbox`,checked:!(n??e),onChange:e=>{let t=!e.target.checked;r(t),ws(t)}}),(0,Y.jsxs)(`span`,{className:`open-browser-pref-copy`,children:[(0,Y.jsx)(`span`,{className:`text-label`,children:t(`prov.dontOpenBrowser`)}),(0,Y.jsx)(`span`,{className:`muted text-label`,children:t(`prov.dontOpenBrowserHint`)})]})]})}function fl(e){return e?.status===`ready`?e.coupons:[]}function pl(){let e=globalThis.crypto;if(e&&typeof e.randomUUID==`function`)return e.randomUUID();if(e&&typeof e.getRandomValues==`function`){let t=e.getRandomValues(new Uint8Array(16));t[6]=t[6]&15|64,t[8]=t[8]&63|128;let n=[...t].map(e=>e.toString(16).padStart(2,`0`)).join(``);return[n.slice(0,8),n.slice(8,12),n.slice(12,16),n.slice(16,20),n.slice(20)].join(`-`)}}var ml={auth_failed:`grokCoupon.authFailed`,no_account:`grokCoupon.noAccount`,no_coupons_available:`grokCoupon.noneAvailable`,operation_id_owned_by_another_account:`grokCoupon.identityMismatch`,capacity:`grokCoupon.capacity`,unavailable:`grokCoupon.capacity`,network:`grokCoupon.networkError`,redeem_failed:`grokCoupon.redeemFailed`};function hl({entry:e,onClick:t,t:n}){if(e===void 0||e.status===`loading`)return(0,Y.jsxs)(`span`,{className:`badge badge-muted codex-ticket-badge-slot`,"aria-hidden":`true`,children:[(0,Y.jsx)(Ae,{width:12}),`0`]});let r=e.status===`ready`?e.coupons.length:null,i=r===null?n(`grokCoupon.badgeErrorAria`):n(`grokCoupon.badgeAria`,{count:String(r)});return(0,Y.jsxs)(`button`,{type:`button`,className:`badge ${r?`badge-amber`:`badge-muted`} badge-clickable`,"data-grok-coupon-badge":r===null?`error`:String(r),onClick:e=>{e.stopPropagation(),t()},"aria-label":i,title:i,children:[(0,Y.jsx)(Ae,{width:12}),r===null?(0,Y.jsx)(_e,{width:11}):r]})}function gl({coupon:e,index:t,isNext:n,locale:r,t:i}){let a=e.validityEnd?Hc(e.validityEnd):null;return(0,Y.jsxs)(`div`,{className:`credit-item${n?` credit-next`:``}`,children:[(0,Y.jsxs)(`div`,{className:`credit-item-head`,children:[(0,Y.jsx)(Ae,{width:13}),(0,Y.jsx)(`span`,{className:`credit-item-label`,children:n?i(`grokCoupon.couponNext`):i(`grokCoupon.couponLabel`,{n:String(t+1)})}),n&&(0,Y.jsx)(`span`,{className:`badge badge-amber text-micro`,style:{padding:`1px 6px`},children:i(`grokCoupon.couponNextBadge`)})]}),(0,Y.jsxs)(`div`,{className:`credit-item-dates`,children:[e.validityStart&&(0,Y.jsx)(`span`,{children:i(`grokCoupon.validFrom`,{date:Bc(e.validityStart,r)})}),a!==null&&(0,Y.jsx)(`span`,{className:a<=7?`credit-urgent`:``,children:i(`grokCoupon.expires`,{date:Vc(e.validityEnd,r),days:String(a)})})]})]})}function _l({accountId:e,accountLabel:t,entry:n,controller:r,onClose:i}){let{locale:a,t:o}=ut(),s=(0,_.useRef)(null),c=(0,_.useRef)(null),[l,u]=(0,_.useState)(!1),[d,f]=(0,_.useState)(!1),[p,m]=(0,_.useState)(!1),[h,g]=(0,_.useState)(null),[v,y]=(0,_.useState)(null),b=(0,_.useRef)(void 0);(0,_.useEffect)(()=>{let e=s.current;e&&!e.open&&e.showModal()},[]),(0,_.useEffect)(()=>{l&&c.current?.focus()},[l]);let x=(0,_.useCallback)(e=>{e.preventDefault(),i()},[i]),S=fl(n),C=S[0],w=()=>{if(h)return;let e=pl();if(!e){y({tone:`warn`,key:`grokCoupon.noOperationId`});return}b.current=e,y(null),u(!0)},T=async()=>{if(d||h)return;let t=b.current;if(!C?.tokenId){y({tone:`warn`,key:`grokCoupon.noneAvailable`});return}if(!t){y({tone:`warn`,key:`grokCoupon.noOperationId`});return}f(!0);let n=await r.redeem(e,{tokenId:C.tokenId,operationId:t});if(f(!1),n.ok){b.current=void 0,u(!1),y({tone:`ok`,key:n.replayed?`grokCoupon.redeemReplayed`:`grokCoupon.redeemSuccess`});return}if(n.code===`aborted`){g({tokenId:C.tokenId}),y(null),r.refresh(e);return}n.code===`operation_id_owned_by_another_account`&&(b.current=void 0),y({tone:`warn`,key:ml[n.code]??`grokCoupon.redeemFailed`})},E=async()=>{!h||p||(m(!0),await r.refresh(e),m(!1))},D=h?fl(n).some(e=>e.tokenId===h.tokenId):!1,O=String(S.length),k=e=>(0,Y.jsx)(`p`,{className:e.tone===`ok`?`pws-status-ok`:`pws-status-warn`,role:e.tone===`ok`?`status`:`alert`,style:{marginTop:12},children:o(e.key,{count:O})});return(0,Y.jsxs)(`dialog`,{ref:s,className:`modal-overlay`,"aria-labelledby":`grok-coupon-title`,onCancel:x,children:[(0,Y.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":o(`common.close`),tabIndex:-1,onClick:i}),(0,Y.jsx)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),role:`document`,children:h?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{style:{textAlign:`center`,padding:`12px 0`},children:[(0,Y.jsx)(`div`,{className:`confirm-icon`,children:(0,Y.jsx)(_e,{width:22})}),(0,Y.jsx)(`h3`,{id:`grok-coupon-title`,children:o(`grokCoupon.title`)}),(0,Y.jsx)(`p`,{className:`pws-status-warn`,role:`alert`,children:o(`grokCoupon.unknownOutcome`)}),!p&&(0,Y.jsx)(`p`,{className:`faint text-label`,children:o(D?`grokCoupon.unresolved`:`grokCoupon.consumedElsewhere`)})]}),(0,Y.jsxs)(`div`,{className:`modal-actions`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:i,children:o(`common.close`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>{E()},disabled:p,children:o(p?`grokCoupon.checking`:`grokCoupon.checkResult`)})]})]}):l?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{style:{textAlign:`center`,padding:`12px 0`},children:[(0,Y.jsx)(`div`,{className:`confirm-icon`,children:(0,Y.jsx)(_e,{width:22})}),(0,Y.jsx)(`h3`,{id:`grok-coupon-title`,children:o(`grokCoupon.confirmTitle`)}),(0,Y.jsx)(`p`,{className:`modal-desc`,children:o(`grokCoupon.confirmDesc`,{count:O})}),C?.validityEnd&&(0,Y.jsx)(`p`,{className:`faint text-label`,children:o(`grokCoupon.confirmWhich`,{date:Bc(C.validityEnd,a)})}),(0,Y.jsx)(`p`,{className:`faint text-label`,children:o(`grokCoupon.irreversible`)}),v&&k(v)]}),(0,Y.jsxs)(`div`,{className:`modal-actions`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>u(!1),disabled:d,children:o(`common.cancel`)}),(0,Y.jsx)(`button`,{ref:c,type:`button`,className:`btn btn-primary`,onClick:()=>{T()},disabled:d,children:o(d?`grokCoupon.redeeming`:`grokCoupon.redeem`)})]})]}):(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`h3`,{id:`grok-coupon-title`,children:[(0,Y.jsx)(Ae,{width:16}),` `,o(`grokCoupon.title`)]}),(0,Y.jsx)(`div`,{className:`card-sub`,children:t}),(0,Y.jsxs)(`div`,{style:{margin:`16px 0`},children:[n===void 0||n.status===`loading`?(0,Y.jsx)(`p`,{className:`faint text-label`,children:o(`common.loading`)}):n.status===`error`?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`p`,{className:`faint`,role:`alert`,children:o(n.reason===`auth`?`grokCoupon.loadFailedAuth`:`grokCoupon.loadFailed`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,style:{marginTop:12},onClick:()=>{r.refresh(e)},children:o(`grokCoupon.retry`)})]}):S.length>0?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`p`,{style:{marginBottom:12},children:o(`grokCoupon.available`,{count:O})}),(0,Y.jsx)(`div`,{className:`credit-list`,children:S.map((e,t)=>(0,Y.jsx)(gl,{coupon:e,index:t,isNext:t===0,locale:a,t:o},e.tokenId))}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary`,style:{marginTop:12,width:`100%`},onClick:w,disabled:d,children:o(`grokCoupon.useOne`)}),(0,Y.jsx)(`p`,{className:`card-sub text-caption`,style:{marginTop:8,textAlign:`center`},children:o(`grokCoupon.fifoNote`)})]}):(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`p`,{className:`faint`,children:o(`grokCoupon.none`)}),(0,Y.jsx)(`p`,{className:`modal-desc`,children:o(`grokCoupon.desc`)})]}),v&&k(v)]})]})})]})}var vl=2e4,yl=3e4,bl=3;function xl(e){if(!e||typeof e!=`object`)return null;let t=e.tokens;if(!Array.isArray(t))return null;let n=[];for(let e of t){if(!e||typeof e!=`object`)return null;let{tokenId:t,validityStart:r,validityEnd:i}=e;if(typeof t!=`string`||t===``)return null;n.push({tokenId:t,validityStart:typeof r==`string`?r:``,validityEnd:typeof i==`string`?i:``})}return n}function Sl(e){if(e&&typeof e==`object`){let t=e.error;if(t&&typeof t==`object`){let e=t.code;if(typeof e==`string`&&e!==``)return e}}return`redeem_failed`}function Cl(e){if(e&&typeof e==`object`){let t=e.code;if(typeof t==`string`&&t!==``)return t}return`redeemed`}function wl(e){if(!e.validityEnd)return 1/0;let t=Date.parse(e.validityEnd);return Number.isNaN(t)?1/0:t}function Tl(e){return e.toSorted((e,t)=>wl(e)-wl(t))}function El(e,t){return t.aborted?!0:!!(e&&typeof e==`object`&&e.name===`AbortError`)}function Dl({apiBase:e,accountIds:t,enabled:n}){let[r,i]=(0,_.useState)({}),a=(0,_.useRef)(0),o=(0,_.useRef)(new Map),s=(0,_.useRef)({active:0,waiting:[]}),c=t.join(`\0`),l=(0,_.useCallback)(async(t,n)=>{let r=(o.current.get(t)??0)+1;o.current.set(t,r);let c=s.current;c.active>=bl&&await new Promise(e=>c.waiting.push(e)),c.active+=1;let l=()=>a.current===n&&o.current.get(t)===r,u=Xn(vl);try{let n=await fetch(`${e}/api/grok/reset-coupons?accountId=${encodeURIComponent(t)}`,{signal:u.signal}),r=n.ok?xl(await n.json().catch(()=>null)):null;if(!l())return;i(e=>({...e,[t]:r?{status:`ready`,coupons:Tl(r)}:{status:`error`,reason:n.status===401?`auth`:`upstream`}}))}catch{if(!l())return;i(e=>({...e,[t]:{status:`error`,reason:`upstream`}}))}finally{u.clear(),--c.active,c.waiting.shift()?.()}},[e]);return(0,_.useEffect)(()=>{if(!n||c===``)return;let e=++a.current;return Promise.resolve().then(()=>{for(let t of c.split(`\0`))l(t,e)}),()=>{a.current+=1}},[n,c,l]),{entries:r,refresh:(0,_.useCallback)(async e=>{i(t=>({...t,[e]:{status:`loading`}})),await l(e,a.current)},[l]),redeem:(0,_.useCallback)(async(t,n)=>{let r=Xn(yl);try{let i=await fetch(`${e}/api/grok/reset-coupons/consume`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({accountId:t,tokenId:n.tokenId,operationId:n.operationId}),signal:r.signal});if(!i.ok)return{ok:!1,code:Sl(await i.json().catch(()=>null)),replayed:!1};let o=await i.json().catch(()=>null),s=!!(o&&typeof o==`object`&&o.replayed===!0),c=Cl(o);return await l(t,a.current),{ok:c===`redeemed`,code:c,replayed:s}}catch(e){return{ok:!1,code:El(e,r.signal)?`aborted`:`network`,replayed:!1}}finally{r.clear()}},[e,l])}}var Ol=262144,kl=[],Al=[];function jl(e){return!!e.needsReauth||rs(e.health?.status)}function Ml({initialState:e,onUpdateProvider:t}){let n=Q(),[r,i]=(0,_.useState)(e),[a,o]=(0,_.useState)(e),[s,c]=(0,_.useState)(!1),[l,u]=(0,_.useState)(``);e!==a&&(o(e),i(e));let d=r===`mixed`,f=async()=>{if(!t||s)return;let e=r===!1;c(!0),u(``);try{let r=await t(`xai`,{xaiResponsesOptIn:e});if(!r.ok){u(r.error??n(`prov.updateFail`));return}i(r.xaiResponsesOptInState??e)}catch{u(n(`prov.networkError`))}finally{c(!1)}};return(0,Y.jsxs)(`div`,{className:`pwi-auth-optin-row`,children:[(0,Y.jsxs)(`div`,{className:`pwi-auth-optin-copy`,children:[(0,Y.jsx)(`span`,{className:`pwi-auth-optin-label`,children:n(`pws.xaiChatOptIn`)}),(0,Y.jsxs)(`span`,{className:`pwi-auth-row-secondary`,children:[n(`pws.xaiChatOptInDesc`),d&&(0,Y.jsxs)(`span`,{className:`pwi-auth-optin-mixed`,children:[` `,n(`pws.xaiChatOptInMixed`)]})]}),l&&(0,Y.jsx)(`span`,{className:`pwi-auth-optin-error`,role:`alert`,children:l})]}),(0,Y.jsx)(Dt,{on:r===!1,mixed:d,onClick:()=>{f()},disabled:!t||s,label:n(`pws.xaiChatOptIn`)})]})}var Nl=new Set([`totalCount`,`importedCount`,`updatedCount`,`failedCount`,`unsupportedCount`,`results`]),Pl=new Set([`imported`,`updated`,`failed`,`unsupported`]),Fl={imported:new Set([`imported`]),updated:new Set([`updated`]),failed:new Set([`invalid_record`,`credential_rejected`,`identity_mismatch`,`missing_project`,`persist_failed`]),unsupported:new Set([`unsupported_provider`,`unsupported_format`])};function Il(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Ll(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function Rl(e){if(!Il(e)||Object.keys(e).some(e=>!Nl.has(e)))return null;let{totalCount:t,importedCount:n,updatedCount:r,failedCount:i,unsupportedCount:a,results:o}=e;if(!Ll(t)||!Ll(n)||!Ll(r)||!Ll(i)||!Ll(a)||!Array.isArray(o)||o.length!==t||n+r+i+a!==t)return null;let s={imported:0,updated:0,failed:0,unsupported:0};for(let[e,t]of o.entries()){if(!Il(t)||Object.keys(t).some(e=>![`index`,`status`,`code`].includes(e)))return null;let n=String(t.status),r=String(t.code);if(t.index!==e||!Pl.has(n)||!Fl[n]?.has(r))return null;s[n]+=1}return s.imported!==n||s.updated!==r||s.failed!==i||s.unsupported!==a?null:{importedCount:n,updatedCount:r,failedCount:i,unsupportedCount:a}}function zl({item:e,apiBase:t,oauth:n,accounts:r=kl,keys:i=Al,accountLoadState:a=`ready`,switchingAccountId:o=null,busy:s=!1,loginHint:c,authHandlers:l,onCodexActiveNeedsReauthChange:u,codexController:d,onUpdateProvider:f}){let p=Q(),[m,h]=(0,_.useState)(!1),[g,v]=(0,_.useState)(``),[y,b]=(0,_.useState)(!1),[x,S]=(0,_.useState)(!1),[C,w]=(0,_.useState)(`idle`),[T,E]=(0,_.useState)(null),D=(0,_.useRef)(null),[O,k]=(0,_.useState)(``),[A,j]=(0,_.useState)(!1),[M,N]=(0,_.useState)(``),[P,F]=(0,_.useState)(!0),I=JSON.stringify([t,e.name,r.find(e=>e.active)?.id,i.find(e=>e.active)?.id]),[L,R]=(0,_.useState)({identity:I,refreshing:!1,result:null}),z=L.identity===I&&L.refreshing,B=L.identity===I?L.result:null,V=(0,_.useRef)(0);(0,_.useEffect)(()=>(V.current+=1,()=>{V.current+=1}),[I]);let H=l?.onRefreshQuota,U=to({...e,hasApiKey:e.hasApiKey||i.length>0}),W=U===`oauth-accounts`,G=U===`api-keys`,K=W&&e.name===`xai`&&r.length>0,q=Dl({apiBase:t,accountIds:(0,_.useMemo)(()=>K?r.filter(e=>!jl(e)).map(e=>e.id):[],[K,r]),enabled:K}),[J,X]=(0,_.useState)(null),ee=async()=>{if(!H||z)return;let t=++V.current;R({identity:I,refreshing:!0,result:null});try{let n=await H(e.name);V.current===t&&R({identity:I,refreshing:!1,result:{ok:n,text:p(n?`pws.quotaCheckCompleted`:`codexAuth.quotaRefreshFailed`)}})}catch{V.current===t&&R({identity:I,refreshing:!1,result:{ok:!1,text:p(`codexAuth.quotaRefreshFailed`)}})}};if(U===`codex-accounts`)return(0,Y.jsxs)(`section`,{className:`pwi-section pwi-auth-section`,"aria-label":p(`pws.availableAccounts`),children:[(0,Y.jsx)(`h3`,{className:`pwi-section-title`,children:p(`pws.availableAccounts`)}),(0,Y.jsx)(`div`,{className:`pwi-auth-body`,children:(0,Y.jsx)(cl,{apiBase:t,embedded:!0,controller:d,onActiveNeedsReauthChange:u})})]});if(!U||!l)return null;let te=c?.provider===e.name?c:null,ne=async()=>{let n=O.trim();if(!(!n||A)){j(!0),N(``);try{let r=await fetch(`${t}/api/oauth/login/code`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.name,input:n})});if(!r.ok){let e=await r.json().catch(()=>({}));F(!1),N(p(`prov.pasteFail`,{error:e.error||r.statusText}));return}k(``),F(!0),N(p(`prov.pasteOk`))}catch{F(!1),N(p(`modal.networkError`))}finally{j(!1)}}},Z=r.length>0||n?.loggedIn===!0,re=r.find(e=>e.active&&e.needsReauth),ie=!!re,ae=W?r:i,oe=!!H&&!(ae.length>0&&ae.every(e=>e.quotaMode===`unsupported`)),se=async()=>{let t=g.trim();if(t){b(!0);try{await l.onAddApiKey(e.name,t)&&(v(``),h(!1))}finally{b(!1)}}},ce=async n=>{if(!(!n||x)){S(!0),w(`idle`),E(null);try{if(!n.name.toLowerCase().endsWith(`.json`)||n.size>Ol){w(`invalid`);return}let r;try{r=JSON.parse(await n.text())}catch{w(`invalid`);return}let i=await fetch(`${t}/api/oauth/accounts/import`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:`google-antigravity`,format:`cockpit-tools`,document:r})});if(!i.ok){w(`failed`);return}let a=Rl(await i.json().catch(()=>null));if(!a){w(`failed`);return}E(a),w(`complete`);try{await l.onRetryAccounts?.(e.name)}catch{}}catch{w(`failed`)}finally{D.current&&(D.current.value=``),S(!1)}}};return(0,Y.jsxs)(`section`,{className:`pwi-section pwi-auth-section`,"aria-label":p(W?`pws.availableAccounts`:`pws.apiKeys`),children:[(0,Y.jsxs)(`div`,{className:`pwi-auth-head`,children:[(0,Y.jsx)(`h3`,{className:`pwi-section-title`,children:p(W?`pws.availableAccounts`:`pws.apiKeys`)}),(W&&Z||G)&&oe&&(0,Y.jsxs)(`div`,{className:`pwi-auth-head-actions`,children:[B&&(0,Y.jsx)(`span`,{role:`status`,className:B.ok?`pws-status-ok`:`pws-status-warn`,children:B.text}),(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:z||s||!!o,onClick:()=>{ee()},children:[(0,Y.jsx)(de,{width:14,height:14,"aria-hidden":`true`}),` `,p(z?`codexAuth.refreshingQuota`:`codexAuth.refreshQuota`)]})]})]}),(0,Y.jsxs)(`div`,{className:`pwi-auth-body`,children:[e.name===`xai`&&(0,Y.jsx)(Ml,{initialState:e.xaiResponsesOptInState??!0,onUpdateProvider:f}),W&&(0,Y.jsxs)(Y.Fragment,{children:[e.name===`anthropic`&&(0,Y.jsx)(ul,{apiBase:t,accountCount:r.length}),e.name===`google-antigravity`&&(0,Y.jsxs)(`div`,{className:`pwi-auth-add-key`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`div`,{id:`cockpit-import-description`,className:`pwi-auth-row-secondary`,children:p(`pws.cockpitImportDescription`)}),(0,Y.jsx)(`label`,{className:`sr-only`,htmlFor:`cockpit-import-file`,children:p(`pws.cockpitImportFileLabel`)}),(0,Y.jsx)(`input`,{ref:D,id:`cockpit-import-file`,type:`file`,accept:`application/json,.json`,className:`sr-only`,"aria-describedby":`cockpit-import-description cockpit-import-status`,disabled:x,onChange:e=>{ce(e.currentTarget.files?.[0])}})]}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:x,onClick:()=>D.current?.click(),children:p(x?`pws.cockpitImporting`:`pws.cockpitImportChooseFile`)}),(0,Y.jsxs)(`div`,{id:`cockpit-import-status`,role:`status`,"aria-live":`polite`,children:[C===`invalid`&&p(`pws.cockpitImportInvalid`),C===`failed`&&p(`pws.cockpitImportFailed`),C===`complete`&&T&&p(`pws.cockpitImportComplete`,{imported:T.importedCount,updated:T.updatedCount,failed:T.failedCount,unsupported:T.unsupportedCount})]})]}),(0,Y.jsxs)(`div`,{className:`pwi-auth-status-row`,children:[(0,Y.jsx)(`span`,{className:`pwi-auth-dot ${ie?`pwi-auth-dot--warn`:Z?`pwi-auth-dot--ok`:`pwi-auth-dot--off`}`,"aria-hidden":`true`}),(0,Y.jsx)(`span`,{className:`pwi-auth-status-text`,children:Z?r.length>0?p(`pws.loggedInTitle`):n?.email??p(`pws.loggedInTitle`):n?.error||p(`pws.notLoggedInTitle`)}),(0,Y.jsxs)(`span`,{className:`pwi-auth-actions`,children:[re&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:s,onClick:()=>void l.onReauth(e.name,re.id),children:p(`pws.reauthenticate`)}),Z?(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void l.onLogout(e.name),children:p(`prov.logout`)}):(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:s,onClick:()=>void l.onLogin(e.name,!1),children:[s?(0,Y.jsx)(`span`,{className:`pwi-spin-inline`,"aria-hidden":`true`}):(0,Y.jsx)(ke,{style:{width:13,height:13},"aria-hidden":`true`}),p(s?`prov.waitingBrowser`:`prov.login`)]})]})]}),!s&&(0,Y.jsx)(dl,{}),s&&te&&(0,Y.jsxs)(`div`,{className:`pwi-auth-wait`,children:[(0,Y.jsx)(`span`,{className:`pwi-spin-inline`,"aria-hidden":`true`}),(0,Y.jsxs)(`div`,{className:`pwi-auth-wait-copy`,children:[(0,Y.jsx)(`div`,{className:`pwi-auth-wait-title`,children:p(`prov.waitingBrowser`)}),(0,Y.jsx)(ys,{hint:{url:te.url,deviceCode:te.deviceCode,instructions:te.instructions},paste:{value:O,busy:A,message:M,ok:P,onChange:k,onSubmit:()=>{ne()}}}),l.onCancelLogin&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void l.onCancelLogin?.(e.name),children:p(`common.cancel`)})]})]}),a===`loading`&&r.length===0&&(0,Y.jsxs)(`div`,{className:`pwi-auth-state`,role:`status`,children:[(0,Y.jsx)(`span`,{className:`pwi-spin-inline`,"aria-hidden":`true`}),p(`pws.accountsLoading`)]}),a===`error`&&(0,Y.jsxs)(`div`,{className:`pwi-auth-state pwi-auth-state--error`,role:`alert`,children:[(0,Y.jsx)(`span`,{children:p(`pws.accountsLoadFailed`)}),l.onRetryAccounts&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void l.onRetryAccounts?.(e.name),children:p(`pws.retryAccounts`)})]}),r.length>0&&(0,Y.jsx)(`ul`,{className:`pwi-auth-list`,children:r.map(t=>{let n=no(r,t,p),i=o===t.id,a=t.health?.status,c=jl(t),u=as(a),d=es(t.id),f=cs(p,t.health),m=ls(p,e.name,t.id,t.health);return(0,Y.jsxs)(`li`,{className:`pwi-auth-acct${t.active?` pwi-auth-acct--active`:``}`,children:[(0,Y.jsxs)(`div`,{className:`pwi-auth-row${t.active?` pwi-auth-row--active`:``}`,children:[(0,Y.jsxs)(`button`,{type:`button`,className:`pwi-auth-row-main`,onClick:()=>{!t.active&&!c&&!u&&!o&&l.onSwitchAccount(e.name,t)},"aria-current":t.active?`true`:void 0,"aria-label":`${n}${t.active?` — ${p(`pws.accountCurrent`)}`:``}`,disabled:!!(c||u||o&&!i),children:[(0,Y.jsx)(`span`,{className:`pwi-auth-dot ${c?`pwi-auth-dot--warn`:t.active?`pwi-auth-dot--ok`:`pwi-auth-dot--off`}`,"aria-hidden":`true`}),(0,Y.jsxs)(`span`,{className:`pwi-auth-row-copy`,children:[(0,Y.jsx)(`span`,{className:`pwi-auth-row-label`,children:n}),(0,Y.jsx)(`span`,{className:`pwi-auth-row-secondary`,children:[t.email,`${p(`prov.accountId`)}: ${d}`].filter(Boolean).join(` · `)}),m&&(0,Y.jsx)(`span`,{className:`pwi-auth-row-secondary faint`,children:m}),u&&(0,Y.jsx)(`span`,{className:`pwi-auth-row-secondary faint`,children:p(`pws.healthCooldownHint`)})]}),f&&(0,Y.jsx)(`span`,{className:ns(a),children:f}),c&&!f&&(0,Y.jsx)(`span`,{className:`badge badge-amber`,children:p(`pws.reauth`)}),t.active&&(0,Y.jsx)(`span`,{className:`badge badge-primary`,children:p(`prov.accountActive`)}),i&&(0,Y.jsx)(`span`,{className:`badge badge-muted`,children:p(`pws.accountSwitching`)})]}),c&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:s||!!o,onClick:()=>void l.onReauth(e.name,t.id),children:p(`pws.reauthenticate`)}),K&&!c&&(0,Y.jsx)(hl,{entry:q.entries[t.id],t:p,onClick:()=>X(t)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void l.onEditAlias(e.name,`oauth`,t.id,t.alias),children:p(`prov.editAlias`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm pwi-auth-row-remove`,"aria-label":`${p(`common.remove`)} — ${n}`,title:`${p(`common.remove`)} — ${n}`,disabled:!!o,onClick:()=>void l.onRemoveAccount(e.name,t),children:(0,Y.jsx)(me,{style:{width:13,height:13},"aria-hidden":`true`})})]}),(0,Y.jsx)(`div`,{className:`pwi-auth-acct-quota`,children:(0,Y.jsx)(oo,{quotaMode:t.quotaMode,quota:t.quota,quotaUnavailable:t.quotaUnavailable,quotaPending:t.quotaPending,quotaFailure:t.quotaFailure})})]},t.id)})}),J&&(0,Y.jsx)(_l,{accountId:J.id,accountLabel:no(r,J,p),entry:q.entries[J.id],controller:q,onClose:()=>X(null)}),a===`ready`&&Z&&r.length===0&&(0,Y.jsx)(`div`,{className:`pwi-auth-state pwi-auth-state--empty`,children:p(`pws.noAccounts`)}),Z&&(0,Y.jsxs)(`div`,{className:`pwi-auth-actions`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void l.onLogin(e.name,!0),disabled:s||!!o,children:p(`pws.addAccount`)}),oe&&(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:z||s||!!o,onClick:()=>{ee()},children:[(0,Y.jsx)(de,{width:14,height:14,"aria-hidden":`true`}),` `,p(z?`codexAuth.refreshingQuota`:`codexAuth.refreshQuota`)]})]})]}),G&&(0,Y.jsxs)(Y.Fragment,{children:[i.length>0&&(0,Y.jsx)(`ul`,{className:`pwi-auth-list`,children:i.map(t=>(0,Y.jsxs)(`li`,{className:`pwi-auth-acct${t.active?` pwi-auth-acct--active`:``}`,children:[(0,Y.jsxs)(`div`,{className:`pwi-auth-row${t.active?` pwi-auth-row--active`:``}`,children:[(0,Y.jsxs)(`button`,{type:`button`,className:`pwi-auth-row-main`,onClick:()=>void l.onSwitchApiKey(e.name,t),disabled:t.active,children:[(0,Y.jsx)(`span`,{className:`pwi-auth-dot ${t.active?`pwi-auth-dot--ok`:`pwi-auth-dot--off`}`,"aria-hidden":`true`}),(0,Y.jsxs)(`span`,{className:`pwi-auth-row-copy`,children:[(0,Y.jsx)(`span`,{className:`pwi-auth-row-label`,children:t.label??t.masked}),t.label&&(0,Y.jsxs)(`code`,{className:`pwi-auth-row-secondary`,children:[t.masked,` · `,p(`prov.accountId`),`: `,t.id]})]}),t.active&&(0,Y.jsx)(`span`,{className:`badge badge-primary`,children:p(`prov.accountActive`)})]}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void l.onEditAlias(e.name,`api-key`,t.id,t.label),children:p(`prov.editAlias`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm pwi-auth-row-remove`,"aria-label":`${p(`common.remove`)} — ${t.label??t.masked}`,title:`${p(`common.remove`)} — ${t.label??t.masked}`,onClick:()=>void l.onRemoveApiKey(e.name,t),children:(0,Y.jsx)(me,{style:{width:13,height:13},"aria-hidden":`true`})})]}),(0,Y.jsx)(`div`,{className:`pwi-auth-acct-quota`,children:(0,Y.jsx)(oo,{quotaMode:t.quotaMode,quota:t.quota,quotaUnavailable:t.quotaUnavailable,quotaPending:t.quotaPending,quotaFailure:t.quotaFailure})})]},t.id))}),m?(0,Y.jsxs)(`div`,{className:`pwi-auth-add-key`,children:[(0,Y.jsx)(`input`,{className:`input`,type:`password`,value:g,onChange:e=>v(e.target.value),placeholder:p(`modal.apiKeyPlaceholder`),autoComplete:`off`,disabled:y}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>void se(),disabled:y||!g.trim(),children:p(y?`pws.saving`:`pws.addKey`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{h(!1),v(``)},children:p(`common.cancel`)})]}):(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{marginTop:8},onClick:()=>h(!0),children:p(`pws.addKey`)})]})]})]})}function Bl(e,t,n){let r=e?.find(e=>e.id===t);if(!r)return n;if(r.baseUrl)return r.baseUrl;let i=new Set((e??[]).map(e=>e.baseUrl?.trim().replace(/\/+$/,``)).filter(e=>!!e)),a=n.trim().replace(/\/+$/,``);return i.has(a)?``:n}function Vl(e,t){if(!e?.length)return`custom`;let n=t.trim().replace(/\/+$/,``);for(let t of e)if(t.baseUrl&&t.baseUrl.trim().replace(/\/+$/,``)===n)return t.id;return e.some(e=>e.id===`custom`)?`custom`:e[0].id}function Hl(e,t,n){let r=e?.find(e=>e.id===t);return r?.baseUrl?r.baseUrl.trim():n.trim()}var Ul=`https://chatgpt.com/backend-api/codex`;function Wl(e){try{let t=new URL(e.trim());if(t.username||t.password||t.search||t.hash)return;let n=t.pathname.replace(/\/+$/,``);return`${t.origin}${n}`}catch{return}}function Gl(e){return[`openai`,...Object.entries(e).filter(([,e])=>e.authMode===`forward`).map(([e])=>e).filter(e=>e!==`openai`).sort((e,t)=>e.localeCompare(t))]}function Kl(e){return e?e.adapter!==`openai-responses`||e.authMode!==`forward`||typeof e.baseUrl!=`string`||Wl(e.baseUrl)!==Ul?`invalid`:e.disabled===!0?`disabled`:`ready`:`absent`}function ql(e){return e.id===`openai`}function Jl(e){return e.id===`openai`?e.codexAccountMode===`direct`?`prov.openaiDirectDesc`:`prov.openaiPoolDesc`:null}function Yl(e){let t={adapter:e.adapter.trim(),baseUrl:e.baseUrl.trim()};return e.responsesPath?.trim()&&(t.responsesPath=e.responsesPath.trim()),(e.authMode===`key`||e.authMode===`forward`)&&(t.authMode=e.authMode),e.authMode===`key`&&e.apiKey.trim()&&(t.apiKey=e.apiKey.trim()),e.adapter.trim()===`anthropic`&&e.authMode===`key`&&e.apiKeyTransport===`bearer`&&(t.apiKeyTransport=`bearer`),e.defaultModel.trim()&&(t.defaultModel=e.defaultModel.trim()),e.allowPrivateNetwork&&(t.allowPrivateNetwork=!0),t}function Xl(e,t){return ql(e)?Zl(e):{name:t.name.trim(),provider:Yl(t)}}function Zl(e){if(!e.provider)throw Error(`Missing canonical provider seed for ${e.id}`);return{name:e.id,provider:structuredClone(e.provider)}}var Ql=class extends Error{i18nKey;constructor(e){super(e),this.name=`OpenAiEnableError`,this.i18nKey=e}};async function $l(e,t,n=fetch){if(t===`disabled`){if((await n(`${e}/api/providers?name=openai`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({disabled:!1})})).ok)return;throw new Ql(`codexAuth.enableOpenaiFailed`)}let r=await n(`${e}/api/provider-presets`);if(!r.ok)throw new Ql(`codexAuth.openaiPresetLoadFailed`);let i=(await r.json()).providers?.find(e=>e.id===`openai`);if(!i?.provider)throw new Ql(`codexAuth.openaiPresetUnavailable`);if(!(await n(`${e}/api/providers`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(Zl(i))})).ok)throw new Ql(`codexAuth.enableOpenaiFailed`)}var eu=[`openai-responses`,`openai-chat`,`anthropic`,`google`,`azure-openai`,`cursor`],tu=[];function nu(e){return e===`http1.1`||e===`h1`?`http1.1`:`http2`}function ru(e){return e===void 0?``:String(e)}function iu(e){if(!e.trim())return;let t=Number(e);return Number.isFinite(t)&&t>=1/60?t:void 0}function au(e){if(!e.trim())return;let t=Number(e);return Number.isSafeInteger(t)&&t>0?t:void 0}function ou(e){let t=Object.entries(e?.models??{}).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,t.requestsPerMinute??null,t.minIntervalMs??null]);return JSON.stringify([e?.enabled===!0,e?.requestsPerMinute??null,e?.minIntervalMs??null,t])}function su({item:e,availableModels:t=tu,apiBase:n,onUpdateProvider:r,onDirtyChange:i,onRegisterSave:a}){let o=Q(),s=String(e.authMode??(e.keyOptional?`local`:`key`)),c=mi(e.name,e),l=c?e.liveModels!==!1:!1,u=nu(e.upstreamHttpVersion),[d,f]=(0,_.useState)(e.adapter),[p,m]=(0,_.useState)(e.baseUrl),[h,g]=(0,_.useState)(e.defaultModel??``),[v,y]=(0,_.useState)(s),[b,x]=(0,_.useState)(e.apiKeyTransport??`x-api-key`),[S,C]=(0,_.useState)(e.note??``),[w,T]=(0,_.useState)(e.allowPrivateNetwork??!1),[E,D]=(0,_.useState)(l),[O,k]=(0,_.useState)(u),[A,j]=(0,_.useState)(!1),[M,N]=(0,_.useState)(null),[P,F]=(0,_.useState)(e.codexAccountMode??`pool`),[I,L]=(0,_.useState)(!1),[R,z]=(0,_.useState)(null),[B,V]=(0,_.useState)(),[H,U]=(0,_.useState)(n?`loading`:`idle`),[W,G]=(0,_.useState)(()=>`custom`),[K,q]=(0,_.useState)(e.requestPacing?.enabled===!0),[J,X]=(0,_.useState)(()=>ru(e.requestPacing?.requestsPerMinute)),[ee,te]=(0,_.useState)(()=>ru(e.requestPacing?.minIntervalMs)),[ne,Z]=(0,_.useState)(()=>({...e.requestPacing?.models??{}})),[re,ie]=(0,_.useState)(``),[ae,oe]=(0,_.useState)(``),[se,ce]=(0,_.useState)(``),[le,ue]=(0,_.useState)(null);(0,_.useEffect)(()=>{f(e.adapter),m(e.baseUrl),g(e.defaultModel??``),y(String(e.authMode??(e.keyOptional?`local`:`key`))),x(e.apiKeyTransport??`x-api-key`),C(e.note??``),T(e.allowPrivateNetwork??!1),D(l),k(u),q(e.requestPacing?.enabled===!0),X(ru(e.requestPacing?.requestsPerMinute)),te(ru(e.requestPacing?.minIntervalMs)),Z({...e.requestPacing?.models??{}}),N(null),z(null),queueMicrotask(()=>G(Vl(B,e.baseUrl)))},[e.adapter,e.baseUrl,e.defaultModel,e.authMode,e.apiKeyTransport,e.keyOptional,e.note,e.allowPrivateNetwork,l,u,e.requestPacing,B]),(0,_.useEffect)(()=>{F(e.codexAccountMode??`pool`)},[e.codexAccountMode]),(0,_.useEffect)(()=>{if(!n)return;let t=!1,r=e.name,i=e.baseUrl;return fetch(`${n}/api/provider-presets`).then(e=>Lt(e)).then(e=>{if(t)return;if(!e){V(void 0),U(`error`);return}let n=(e.providers??[]).find(e=>e.id===r)?.baseUrlChoices;V(n),U(`ready`),G(Vl(n,i))}).catch(()=>{t||(V(void 0),U(`error`))}),()=>{t=!0}},[n,e.name]),(0,_.useEffect)(()=>{if(!n)return;let t=!0,r=!1,i=()=>{if(r)return;r=!0;let i=Xn(1e4);fetch(`${n}/api/provider-request-pacing?name=${encodeURIComponent(e.name)}`,{signal:i.signal}).then(e=>Lt(e)).then(e=>{t&&e&&ue(e)}).catch(()=>void 0).finally(()=>{i.clear(),r=!1})};i();let a=er(i,2e3);return()=>{t=!1,a()}},[n,e.name]);let de=(0,_.useMemo)(()=>({enabled:K,...iu(J)===void 0?{}:{requestsPerMinute:iu(J)},...au(ee)===void 0?{}:{minIntervalMs:au(ee)},...Object.keys(ne).length>0?{models:ne}:{}}),[ee,K,ne,J]),fe=d.trim()!==e.adapter||p.trim()!==e.baseUrl||h.trim()!==(e.defaultModel??``)||v!==String(e.authMode??(e.keyOptional?`local`:`key`))||d.trim()===`anthropic`&&v===`key`&&b!==(e.apiKeyTransport??`x-api-key`)||S.trim()!==(e.note??``)||w!==(e.allowPrivateNetwork??!1)||E!==l||d.trim()===`cursor`&&O!==u,pe=ou(de)!==ou(e.requestPacing),me=fe||pe;(0,_.useEffect)(()=>(i?.(me),()=>i?.(!1)),[me,i]);let he=(0,_.useMemo)(()=>{let n=new Set(t);return h.trim()&&n.add(h.trim()),e.defaultModel&&n.add(e.defaultModel),[...n].sort((e,t)=>e.localeCompare(t))},[t,h,e.defaultModel]),ge=(0,_.useMemo)(()=>{let e=[...eu];return d&&!e.includes(d)&&e.unshift(d),e},[d]),_e=Rn(e.name),ve=H===`ready`&&!!(B&&B.length>0),ye=d.trim()===`anthropic`&&v===`key`,be=e.name===`openai`?Kl(e):`invalid`,xe=be===`ready`||be===`disabled`,Se=_e&&H!==`error`,Ce=async()=>{if(!r)return N({ok:!1,text:o(`pws.updatesUnavailable`)}),!1;if(I)return!1;let t=ve?Hl(B,W,p):p.trim();if(!d.trim()||!t)return N({ok:!1,text:o(`pws.adapterBaseRequired`)}),!1;j(!0),N(null);try{if(K&&!de.requestsPerMinute&&!de.minIntervalMs&&!de.models)return N({ok:!1,text:o(`pws.pacingRuleRequired`)}),!1;let n=pe&&!fe,i=n?{requestPacing:de}:{adapter:d.trim(),baseUrl:t,defaultModel:h.trim(),authMode:v,note:S.trim(),allowPrivateNetwork:w,...pe?{requestPacing:de}:{}};n||(c&&E!==(e.liveModels!==!1)&&(i.liveModels=E),d.trim()===`cursor`&&O!==u&&(i.upstreamHttpVersion=O===`http1.1`?`http1.1`:null),ye?i.apiKeyTransport=b:e.apiKeyTransport!==void 0&&(i.apiKeyTransport=``));let a=await r(e.name,i);return N(a.ok?{ok:!0,text:o(`pws.settingsSaved`)}:{ok:!1,text:a.error||o(`prov.saveFailed`)}),a.ok}finally{j(!1)}},we=(0,_.useRef)(Ce);(0,_.useEffect)(()=>{we.current=Ce}),(0,_.useEffect)(()=>{if(a)return a(()=>we.current()),()=>a(null)},[a]);let Te=async e=>{if(!(I||A||e===P)){if(!r){z({ok:!1,text:o(`pws.updatesUnavailable`)});return}L(!0),z(null);try{let t=await r(`openai`,{codexAccountMode:e});t.ok?(F(e),z({ok:!0,text:o(`pws.accountModeSaved`)})):z({ok:!1,text:t.error||o(`pws.accountModeFailed`)})}catch{z({ok:!1,text:o(`pws.accountModeFailed`)})}finally{L(!1)}}},Ee=()=>{f(e.adapter),m(e.baseUrl),g(e.defaultModel??``),y(s),x(e.apiKeyTransport??`x-api-key`),C(e.note??``),T(e.allowPrivateNetwork??!1),D(l),k(u),N(null),q(e.requestPacing?.enabled===!0),X(ru(e.requestPacing?.requestsPerMinute)),te(ru(e.requestPacing?.minIntervalMs)),Z({...e.requestPacing?.models??{}}),G(Vl(B,e.baseUrl))},De=(e,t)=>{switch(e){case`token-plan`:return o(`modal.endpoint.tokenPlan`);case`payg`:return o(`modal.endpoint.payAsYouGo`);case`custom`:return o(`modal.endpoint.custom`);default:return t}};return(0,Y.jsxs)(`div`,{className:`pwi-settings-form`,children:[(0,Y.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Y.jsxs)(`span`,{className:`pwi-settings-label`,children:[(0,Y.jsx)(ke,{style:{width:12,height:12}}),` `,o(`pws.providerId`)]}),(0,Y.jsx)(`input`,{className:`input`,value:e.name,readOnly:!0,disabled:!0})]}),(0,Y.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Y.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.adapter`)}),_e?(0,Y.jsx)(`input`,{className:`input`,value:d,readOnly:!0,disabled:!0}):(0,Y.jsx)(`select`,{className:`input`,value:d,onChange:e=>f(e.target.value),children:ge.map(e=>(0,Y.jsx)(`option`,{value:e,children:e},e))})]}),ve?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Y.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.endpoint`)}),(0,Y.jsx)(`select`,{className:`input`,value:W,onChange:e=>{let t=e.target.value;G(t),m(Bl(B,t,p))},children:B.map(e=>(0,Y.jsx)(`option`,{value:e.id,children:De(e.id,e.label)},e.id))})]}),W===`custom`&&(0,Y.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Y.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.baseUrl`)}),(0,Y.jsx)(`input`,{className:`input`,value:p,onChange:e=>m(e.target.value),placeholder:o(`modal.baseUrlPlaceholder`)})]})]}):(0,Y.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Y.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.baseUrl`)}),(0,Y.jsx)(`input`,{className:`input`,value:p,onChange:e=>m(e.target.value),readOnly:Se,disabled:Se})]}),d.trim()===`cursor`&&(0,Y.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Y.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.cursorTransport`)}),(0,Y.jsxs)(`select`,{className:`input`,value:O,onChange:e=>k(e.target.value),children:[(0,Y.jsx)(`option`,{value:`http2`,children:o(`pws.cursorTransportHttp2`)}),(0,Y.jsx)(`option`,{value:`http1.1`,children:o(`pws.cursorTransportHttp1`)})]}),(0,Y.jsx)(`span`,{className:`pwi-settings-hint`,children:o(`pws.cursorTransportDesc`)})]}),(0,Y.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Y.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.cell.defaultModel`)}),he.length>0?(0,Y.jsxs)(`select`,{className:`input`,value:h,onChange:e=>g(e.target.value),children:[(0,Y.jsx)(`option`,{value:``,children:o(`pws.defaultModelNone`)}),he.map(e=>(0,Y.jsx)(`option`,{value:e,children:e},e))]}):(0,Y.jsx)(`input`,{className:`input`,value:h,onChange:e=>g(e.target.value),placeholder:o(`pws.optionalPlaceholder`)})]}),(0,Y.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Y.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.authMode`)}),_e?(0,Y.jsx)(`input`,{className:`input`,value:$i(e,o),readOnly:!0,disabled:!0}):(0,Y.jsxs)(`select`,{className:`input`,value:v,onChange:e=>y(e.target.value),children:[(0,Y.jsx)(`option`,{value:`key`,children:o(`modal.badge.apiKey`)}),(0,Y.jsx)(`option`,{value:`forward`,children:o(`pws.auth.chatgptPassthrough`)}),(0,Y.jsx)(`option`,{value:`oauth`,children:o(`modal.badge.oauth`)}),(0,Y.jsx)(`option`,{value:`local`,children:o(`modal.badge.local`)})]})]}),xe&&(0,Y.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Y.jsx)(`span`,{className:`pwi-settings-label`,children:o(`codexAuth.accountModeTitle`)}),(0,Y.jsxs)(`select`,{className:`input`,value:P,disabled:I||A,onChange:e=>{let t=e.target.value;if(t!==P){if(!window.confirm(o(`pws.accountModeConfirm`))){e.target.value=P;return}Te(t)}},children:[(0,Y.jsx)(`option`,{value:`pool`,children:o(`codexAuth.accountModePool`)}),(0,Y.jsx)(`option`,{value:`direct`,children:o(`codexAuth.accountModeDirect`)})]}),(0,Y.jsx)(`span`,{className:`pwi-settings-hint`,children:o(P===`direct`?`codexAuth.accountModeDirectDesc`:`codexAuth.accountModePoolDesc`)}),I&&(0,Y.jsx)(`span`,{className:`muted text-label`,children:o(`pws.accountSwitching`)}),R&&(0,Y.jsx)(`span`,{role:R.ok?`status`:`alert`,className:R.ok?`pwi-settings-mode-msg pwi-settings-mode-msg--ok`:`pwi-settings-mode-msg pwi-settings-mode-msg--err`,children:R.text})]}),ye&&(0,Y.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Y.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.apiKeyTransport`)}),(0,Y.jsxs)(`select`,{className:`input`,value:b,onChange:e=>x(e.target.value),children:[(0,Y.jsx)(`option`,{value:`x-api-key`,children:o(`modal.apiKeyTransportNative`)}),(0,Y.jsx)(`option`,{value:`bearer`,children:o(`modal.apiKeyTransportBearer`)})]})]}),(0,Y.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Y.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.note`)}),(0,Y.jsx)(`textarea`,{className:`input pwi-settings-textarea`,value:S,onChange:e=>C(e.target.value),rows:2})]}),(0,Y.jsxs)(`label`,{className:`pwi-settings-field`,style:{flexDirection:`row`,alignItems:`center`,gap:8},children:[(0,Y.jsx)(`input`,{type:`checkbox`,checked:w,onChange:e=>T(e.target.checked)}),(0,Y.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.allowPrivateNetwork`)})]}),(0,Y.jsxs)(`label`,{className:`pwi-settings-field`,style:{flexDirection:`row`,alignItems:`flex-start`,gap:8},children:[(0,Y.jsx)(`input`,{type:`checkbox`,checked:E,disabled:!c,onChange:e=>D(e.target.checked)}),(0,Y.jsxs)(`span`,{children:[(0,Y.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.liveModels`)}),(0,Y.jsx)(`span`,{className:`muted text-label`,style:{display:`block`,marginTop:2},children:o(`pws.liveModelsDesc`)})]})]}),(0,Y.jsxs)(`section`,{className:`pwi-pacing-card`,"aria-labelledby":`pwi-pacing-title`,children:[(0,Y.jsxs)(`div`,{className:`pwi-pacing-head`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`h3`,{id:`pwi-pacing-title`,children:o(`pws.pacingTitle`)}),(0,Y.jsx)(`p`,{children:o(`pws.pacingDesc`)})]}),(0,Y.jsxs)(`label`,{className:`pwi-pacing-toggle`,children:[(0,Y.jsx)(`input`,{type:`checkbox`,checked:K,onChange:e=>q(e.target.checked)}),` `,o(`pws.pacingEnabled`)]})]}),(0,Y.jsxs)(`div`,{className:`pwi-pacing-grid`,children:[(0,Y.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Y.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.pacingRpm`)}),(0,Y.jsx)(`input`,{className:`input`,type:`number`,min:`0.016667`,step:`any`,value:J,onChange:e=>X(e.target.value),placeholder:`38`})]}),(0,Y.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Y.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.pacingDelay`)}),(0,Y.jsx)(`input`,{className:`input`,type:`number`,min:`1`,step:`1`,value:ee,onChange:e=>te(e.target.value),placeholder:`1600`})]})]}),(0,Y.jsx)(`p`,{className:`pwi-settings-hint`,children:o(`pws.pacingSlowerWins`)}),(0,Y.jsxs)(`div`,{className:`pwi-pacing-status`,"aria-live":`polite`,children:[(0,Y.jsxs)(`span`,{children:[(0,Y.jsx)(`strong`,{children:le?.queued??0}),` `,o(`pws.pacingQueued`)]}),(0,Y.jsxs)(`span`,{children:[(0,Y.jsxs)(`strong`,{children:[le?.nextSlotInMs??0,` ms`]}),` `,o(`pws.pacingNextSlot`)]}),(0,Y.jsxs)(`span`,{children:[(0,Y.jsx)(`strong`,{children:le?.lastModelId??o(`pws.pacingNone`)}),` `,o(`pws.pacingLastModel`)]})]}),(0,Y.jsx)(`h4`,{children:o(`pws.pacingModelOverrides`)}),(0,Y.jsxs)(`div`,{className:`pwi-pacing-grid pwi-pacing-grid--model`,children:[(0,Y.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Y.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.pacingModel`)}),(0,Y.jsx)(`input`,{className:`input`,list:`pacing-models-${e.name}`,value:re,onChange:e=>ie(e.target.value)}),(0,Y.jsx)(`datalist`,{id:`pacing-models-${e.name}`,children:t.map(e=>(0,Y.jsx)(`option`,{value:e},e))})]}),(0,Y.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Y.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.pacingRpm`)}),(0,Y.jsx)(`input`,{className:`input`,type:`number`,min:`0.016667`,step:`any`,value:ae,onChange:e=>oe(e.target.value)})]}),(0,Y.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Y.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.pacingDelay`)}),(0,Y.jsx)(`input`,{className:`input`,type:`number`,min:`1`,step:`1`,value:se,onChange:e=>ce(e.target.value)})]}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{let e=re.trim(),t=iu(ae),n=au(se);!e||t===void 0&&n===void 0||(Z(r=>({...r,[e]:{...t===void 0?{}:{requestsPerMinute:t},...n===void 0?{}:{minIntervalMs:n}}})),ie(``),oe(``),ce(``))},children:o(`pws.pacingAdd`)})]}),Object.entries(ne).length>0&&(0,Y.jsx)(`div`,{className:`pwi-pacing-overrides`,children:Object.entries(ne).map(([e,t])=>(0,Y.jsxs)(`div`,{className:`pwi-pacing-row`,children:[(0,Y.jsx)(`code`,{children:e}),(0,Y.jsxs)(`span`,{children:[t.requestsPerMinute===void 0?``:`${t.requestsPerMinute} ${o(`pws.pacingRpmUnit`)}`,t.requestsPerMinute!==void 0&&t.minIntervalMs!==void 0?` · `:``,t.minIntervalMs===void 0?``:`${t.minIntervalMs} ms`]}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>Z(t=>Object.fromEntries(Object.entries(t).filter(([t])=>t!==e))),"aria-label":o(`pws.pacingRemoveModel`,{model:e}),children:o(`pws.pacingRemove`)})]},e))})]}),me&&(0,Y.jsxs)(`div`,{className:`pwi-settings-sticky-bar`,children:[(0,Y.jsx)(`span`,{className:`muted`,children:o(`pws.settingsUnsavedBar`)}),(0,Y.jsxs)(`div`,{className:`pwi-settings-sticky-bar-actions`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:Ee,disabled:A,children:o(`pws.discardSettings`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>void Ce(),disabled:A||I,children:o(A?`pws.saving`:`pws.saveSettings`)})]})]}),M&&(0,Y.jsx)(`div`,{role:M.ok?`status`:`alert`,className:M.ok?`pwi-settings-msg pwi-settings-msg--ok`:`pwi-settings-msg pwi-settings-msg--err`,children:M.text})]})}function cu({providerName:e,defaultProviderName:t,onConfirm:n,onCancel:r}){let i=Q();return(0,Y.jsx)(`div`,{className:`dialog-backdrop`,onClick:r,children:(0,Y.jsxs)(`div`,{className:`dialog`,role:`alertdialog`,"aria-label":i(`pws.removeConfirmTitle`),onClick:e=>e.stopPropagation(),children:[(0,Y.jsx)(`h3`,{children:i(`pws.removeConfirmTitle`)}),(0,Y.jsx)(`p`,{children:t?i(`pws.removeDefaultConfirmBody`,{name:e,defaultProvider:t}):i(`pws.removeConfirmBody`,{name:e})}),(0,Y.jsxs)(`div`,{className:`dialog-actions`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:r,children:i(`common.cancel`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-danger`,onClick:n,children:i(`pws.removeConfirm`)})]})]})})}function lu({onSave:e,onDiscard:t,onCancel:n,saving:r=!1}){let i=Q();return(0,Y.jsx)(`div`,{className:`dialog-backdrop`,onClick:n,children:(0,Y.jsxs)(`div`,{className:`dialog`,role:`alertdialog`,"aria-label":i(`pws.unsavedLeaveTitle`),onClick:e=>e.stopPropagation(),children:[(0,Y.jsx)(`h3`,{children:i(`pws.unsavedLeaveTitle`)}),(0,Y.jsx)(`p`,{children:i(`pws.unsavedLeaveBody`)}),(0,Y.jsxs)(`div`,{className:`dialog-actions`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:n,children:i(`common.cancel`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:t,children:i(`pws.discardSettings`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:e,disabled:r,children:i(r?`pws.saving`:`pws.saveSettings`)})]})]})})}function uu({item:e,preset:t,usageTotals:n,modelUsage:r,quotaReport:i,availableModels:a,hasLiveModels:o,selectedModels:s,modelRows:c,modelRevision:l,modelRowsReady:u,onOpenModels:d,modelsLoading:f,modelsLoadFailed:p,onRetryModels:m,oauthEmail:h,onDeselect:g,apiBase:v,oauth:y,accounts:b,accountLoadState:x,accountsFocusToken:S=0,accountsFocusProvider:C=null,switchingAccountId:w,keys:T,busyProvider:E,loginHint:D,authHandlers:O,onCodexActiveNeedsReauthChange:k,codexController:A,onUpdateProvider:j,isDefault:M,onRemoveProvider:N,onSetDisabled:P,onSetDefault:F,onRefreshQuota:I}){let L=Q(),[R,z]=(0,_.useState)(`overview`),[B,V]=(0,_.useState)(!1),[H,U]=(0,_.useState)(null),[W,G]=(0,_.useState)(!1),K=(0,_.useRef)(null),[q,J]=(0,_.useState)(0),X=(0,_.useCallback)(e=>{K.current=e},[]),ee=e.disabled===!0,te=(0,_.useMemo)(()=>yi(e),[e]),ne=(0,_.useMemo)(()=>Ei(e),[e]),Z=(0,_.useMemo)(()=>to(e),[e]),re=Z===`oauth-accounts`?b?.find(e=>e.active):Z===`api-keys`?T?.find(e=>e.active):void 0,ie=C===e.name?S:0,ae=JSON.stringify([A?.activeId??``,b?.find(e=>e.active)?.id??``,T?.find(e=>e.active)?.id??``,y?.loggedIn===void 0?``:String(y.loggedIn),y?.needsReauth===void 0?``:String(y.needsReauth),h??``]),oe=(0,_.useMemo)(()=>[{id:`overview`,label:L(`pws.tab.overview`)},{id:`models`,label:L(`pws.tab.models`)},{id:`usage`,label:L(`pws.tab.usage`)},...Z?[{id:`accounts`,label:L(Z===`api-keys`?`pws.apiKeys`:`pws.tab.accounts`)}]:[],{id:`settings`,label:L(`pws.tab.settings`)}],[Z,L]),se=(0,_.useCallback)(e=>{if(B&&R===`settings`&&e!==`settings`){U(e);return}z(e)},[R,B]);ie!==q&&!(ie&&!Z)&&(J(ie),ie&&Z&&(B&&R===`settings`?U(`accounts`):z(`accounts`)));let ce=(0,_.useCallback)(()=>{if(B&&R===`settings`){U(`deselect`);return}g()},[B,R,g]),le=(0,_.useCallback)((e,t)=>{let n;if(e.key===`ArrowRight`)n=(t+1)%oe.length;else if(e.key===`ArrowLeft`)n=(t-1+oe.length)%oe.length;else if(e.key===`Home`)n=0;else if(e.key===`End`)n=oe.length-1;else return;e.preventDefault(),se(oe[n].id),e.currentTarget.parentElement?.querySelectorAll(`[role="tab"]`)[n]?.focus()},[se,oe]),ue=`pws-tab-${R}`,de=`pws-panel-${R}`;return(0,Y.jsxs)(`div`,{className:`pws-detail`,children:[(0,Y.jsx)(`div`,{className:`pws-detail-head`,children:(0,Y.jsxs)(`button`,{type:`button`,className:`pws-detail-back-link`,onClick:ce,children:[(0,Y.jsx)(Ce,{className:`pws-detail-back-chevron`,"aria-hidden":`true`}),L(`pws.allProviders`)]})}),(0,Y.jsxs)(`div`,{className:`pws-detail-head-main`,children:[(0,Y.jsx)(ta,{name:e.name,adapter:e.adapter,baseUrl:e.baseUrl,cls:`pws-detail-icon`}),(0,Y.jsx)(`div`,{className:`pws-detail-title-wrap`,children:(0,Y.jsxs)(`h2`,{className:`pws-detail-title`,children:[Ln(e.name,L),ne&&(0,Y.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--local`,children:L(`modal.badge.local`)}),!ne&&te&&(0,Y.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--free`,children:L(`modal.badge.free`)})]})}),(0,Y.jsxs)(`div`,{className:`pws-detail-actions`,children:[!M&&!ee&&F&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>F(e.name),children:L(`prov.setDefault`)}),N&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm btn-icon-only`,onClick:()=>N(e.name),"aria-label":L(`pws.removeConfirmTitle`),title:L(`pws.removeConfirmTitle`),children:(0,Y.jsx)(me,{style:{width:15,height:15},"aria-hidden":`true`})}),P&&(0,Y.jsxs)(`div`,{className:`pws-detail-toggle`,children:[(0,Y.jsx)(`span`,{className:`pws-detail-toggle-label`,children:L(`pws.enabledLabel`)}),(0,Y.jsx)(Dt,{on:!ee,onClick:()=>P(e.name,!ee),disabled:M,label:L(`pws.enabledLabel`)})]})]})]}),(0,Y.jsx)(`div`,{className:`pws-detail-tabs`,role:`tablist`,children:oe.map((e,t)=>(0,Y.jsx)(`button`,{type:`button`,role:`tab`,id:`pws-tab-${e.id}`,"aria-controls":`pws-panel-${e.id}`,"aria-selected":R===e.id,tabIndex:R===e.id?0:-1,className:`pws-detail-tab${R===e.id?` pws-detail-tab--active`:``}`,onClick:()=>se(e.id),onKeyDown:e=>le(e,t),children:e.label},e.id))}),(0,Y.jsxs)(`div`,{className:`pws-detail-panel`,role:`tabpanel`,id:de,"aria-labelledby":ue,tabIndex:0,children:[R===`overview`&&(0,Y.jsx)(wo,{item:e,preset:t,apiBase:v,connectionIdentity:ae,usageTotals:n,quotaReport:i,currentQuotaReading:re,onRefreshQuota:I,oauthEmail:h,oauth:y,onEditSettings:()=>se(`settings`),onViewUsage:()=>se(`usage`),onUpdateProvider:j,reauthBusy:E===e.name,onCancelLogin:O?.onCancelLogin?()=>void O.onCancelLogin?.(e.name):void 0,onReauthenticate:e.activeNeedsReauth?()=>{if(e.authMode===`oauth`){let t=b??[],n=t.find(e=>e.active&&e.needsReauth)??t.find(e=>e.needsReauth);O?.onReauth(e.name,n?.id);return}se(`accounts`)}:void 0}),R===`models`&&(0,Y.jsx)(Xo,{item:e,apiBase:v,availableModels:a,hasLiveModels:o,selectedModels:s,modelRows:c,modelRevision:l,modelRowsReady:u,onOpenModels:d,modelsLoading:f,modelsLoadFailed:p,needsReauth:(b??[]).some(e=>e.active&&e.needsReauth)||y?.needsReauth===!0,onRetryModels:m,onOpenAccounts:Z?()=>se(`accounts`):void 0},e.name),R===`usage`&&(0,Y.jsx)(Qo,{item:e,usageTotals:n,quotaReport:i,currentQuotaReading:re,quotaIdentity:ae,modelUsage:r,...I?{onRefreshQuota:I}:{}}),R===`accounts`&&(0,Y.jsx)(zl,{item:e,apiBase:v,oauth:y,accounts:b,keys:T,accountLoadState:x,switchingAccountId:w,busy:E===e.name,loginHint:D,authHandlers:O,onUpdateProvider:j,onCodexActiveNeedsReauthChange:k,codexController:A}),R===`settings`&&(0,Y.jsx)(su,{item:e,apiBase:v,availableModels:a,onUpdateProvider:j,onDirtyChange:V,onRegisterSave:X},e.name)]}),H&&(0,Y.jsx)(lu,{saving:W,onCancel:()=>{W||U(null)},onDiscard:()=>{if(W)return;let e=H;U(null),V(!1),e===`deselect`?g():z(e)},onSave:()=>{(async()=>{if(!W){G(!0);try{if(!(await K.current?.()??!1))return;let e=H;U(null),V(!1),e===`deselect`?g():e&&z(e)}finally{G(!1)}}})()}})]})}var du=new Set([`anthropic`,`google-antigravity`,`meta-muse`]),fu=new Set([`github-copilot`,`cursor`]);function pu(e){let t=e.trim().toLowerCase();return du.has(t)?`high`:fu.has(t)?`elevated`:null}function mu(e){switch(e){case`high`:return`oauthTos.highTitle`;case`elevated`:return`oauthTos.elevatedTitle`;default:return e}}function hu(e){switch(e){case`high`:return`oauthTos.highBody`;case`elevated`:return`oauthTos.elevatedBody`;default:return e}}function gu(e,t){return t===void 0?e:e.map(e=>({...e,active:e.id===t}))}function _u(e,t){let n=new Map(t.map(e=>[e.id,e]));return bu(e,t,!1).map(e=>yu(e)?{...e,quotaPending:n.get(e.id)?.quotaPending??!1,quotaUnavailable:n.get(e.id)?.quotaMode===e.quotaMode?n.get(e.id)?.quotaUnavailable??!1:!1,quotaFailure:e.quotaMode===`probe`&&n.get(e.id)?.quotaMode===e.quotaMode&&n.get(e.id)?.quotaUnavailable?ao(n.get(e.id)?.quotaFailure):void 0}:e)}function vu(e,t){let n=new Map(t.map(e=>[e.id,e]));return e.map(e=>{let t=n.get(e.id);if(!t||t.quotaMode!==e.quotaMode)return e;let r=bu([t],[e],!0)[0];return{...e,quota:r.quota,quotaPending:r.quotaPending,quotaUnavailable:r.quotaUnavailable,quotaFailure:r.quotaFailure}})}var yu=e=>e.quotaMode===`probe`||e.quotaMode===`passive`;function bu(e,t,n){let r=new Map(t.map(e=>[e.id,e]));return e.map(e=>{let t=yu(e);if(!t&&e.quotaMode!==`unsupported`)return{...e,quotaMode:void 0,quotaPending:void 0,quotaFailure:void 0};let i=t&&(!n||e.quotaUnavailable===!0);return{...e,quota:e.quotaMode===`unsupported`?null:e.quota===void 0?i?r.get(e.id)?.quota:void 0:e.quota,quotaPending:!n&&e.quotaMode===`probe`,quotaUnavailable:n?e.quotaUnavailable===!0:!1,quotaFailure:n&&e.quotaMode===`probe`&&e.quotaUnavailable===!0?ao(e.quotaFailure):void 0}})}function xu(e,t){let n=t&&new Map(t.map(e=>[e.id,e.quotaMode]));return e.map(e=>yu(e)&&(!n||n.get(e.id)===e.quotaMode)?{...e,quotaUnavailable:!0,quotaPending:!1,quotaFailure:void 0}:e)}function Su(e,t=!1){let n={};for(let[t,r]of Object.entries(e))is(r.accounts.find(e=>e.active)??r.accounts.find(e=>e.id===r.activeAccountId))&&(n[t]=!0);return t&&(n.openai=!0),n}function Cu(e){let{apiBase:t,t:n,config:r,aliveRef:i,notify:a,fetchConfig:o,fetchOauth:s,fetchProviderQuotas:c,codexActiveNeedsReauth:l}=e,[u,d]=(0,_.useState)({}),[f,p]=(0,_.useState)({}),[m,h]=(0,_.useState)(null),[g,v]=(0,_.useState)({}),[y,b]=(0,_.useState)({}),[x,S]=(0,_.useState)(null),[C,w]=(0,_.useState)(``),T=(0,_.useRef)({}),E=(0,_.useRef)({}),D=(0,_.useRef)({}),O=(0,_.useRef)(new Map),k=(0,_.useRef)(new Set),A=(0,_.useRef)(!0),j=(0,_.useRef)(t);(0,_.useEffect)(()=>{let e=T.current,n=k.current,r=E.current,i=D.current,a=O.current;A.current=!0;let o=j.current!==t;return j.current=t,o&&Promise.resolve().then(()=>{!A.current||j.current!==t||(d({}),b({}),p({}))}),()=>{A.current=!1;for(let t of Object.keys(e))e[t]+=1;for(let e of Object.keys(r))r[e]+=1;for(let e of Object.keys(i))i[e]+=1;a.clear();for(let e of n)e.abort();n.clear()}},[t]);let M=(0,_.useRef)(null),N=(0,_.useRef)(null),P=(0,_.useRef)(null),F=(0,_.useCallback)(async(e,t)=>{let n=Xn(2e4),r=()=>n.controller.abort();t?.aborted&&r(),t?.addEventListener(`abort`,r,{once:!0}),k.current.add(n.controller);try{let t=await fetch(e,{signal:n.signal});if(!t.ok)throw Error(String(t.status));let r=await t.json();if(n.signal.aborted)throw Error(`Quota roster deadline exceeded`);return r}finally{n.clear(),t?.removeEventListener(`abort`,r),k.current.delete(n.controller)}},[]),I=(0,_.useCallback)(async(e,n=!1)=>{if(!i.current||!A.current||j.current!==t)return!1;let r=[...new Set(e)];return p(e=>{let t={...e};for(let e of r)t[e]=`loading`;return t}),(await Promise.all(r.map(async e=>{let r=`oauth:${e}`,a=(T.current[r]??0)+1;T.current[r]=a;let o=(E.current[r]??0)+1;E.current[r]=o;let s=()=>i.current&&A.current&&j.current===t&&T.current[r]===a,c=()=>s()&&E.current[r]===o,l=`${t}/api/oauth/accounts?provider=${encodeURIComponent(e)}`;try{let a=await F(l);if(!Array.isArray(a.accounts))throw Error(`Invalid account roster`);if(!s())return!1;let o=gu(a.accounts,a.activeAccountId);if(d(t=>c()?{...t,[e]:{activeAccountId:a.activeAccountId??null,accounts:bu(o,t[e]?.accounts??[],!1)}}:t),p(t=>c()?{...t,[e]:`ready`}:t),!o.some(yu))return!0;let u=async()=>{let s=(D.current[r]??0)+1;D.current[r]=s;let u=()=>i.current&&A.current&&j.current===t&&D.current[r]===s;try{let t=await F(`${l}"a=1${n?`&refresh=1`:``}`);if(!Array.isArray(t.accounts))throw Error(`Invalid account quota roster`);if(!u())return!1;let r=gu(t.accounts,t.activeAccountId);return d(n=>u()?c()?{...n,[e]:{activeAccountId:t.activeAccountId===void 0?a.activeAccountId??null:t.activeAccountId,accounts:bu(r,n[e]?.accounts??[],!0)}}:{...n,[e]:{...n[e],accounts:vu(n[e]?.accounts??[],r)}}:n),!r.some(e=>e.quotaUnavailable===!0)}catch{return u()&&d(t=>u()&&t[e]?{...t,[e]:{...t[e],accounts:xu(t[e].accounts,o)}}:t),!1}};return n?await u():(u(),!0)}catch{return c()?(p(t=>c()?{...t,[e]:`error`}:t),d(t=>c()&&t[e]?{...t,[e]:{...t[e],accounts:xu(t[e].accounts)}}:t),!1):!1}}))).every(Boolean)},[i,t,F]),L=(0,_.useCallback)(async(e,n=!1)=>!i.current||!A.current||j.current!==t?!1:(await Promise.all([...new Set(e)].map(async e=>{let r=`key:${e}`,a=(T.current[r]??0)+1;T.current[r]=a;let o=(E.current[r]??0)+1;E.current[r]=o;let s=()=>i.current&&A.current&&j.current===t&&T.current[r]===a,c=()=>s()&&E.current[r]===o,l=`${t}/api/providers/keys?name=${encodeURIComponent(e)}`,u=()=>(c()&&b(t=>c()?{...t,[e]:xu(t[e]??[])}:t),!1);try{let a=await F(l);if(!Array.isArray(a.keys))throw Error(`Invalid key roster`);if(!s())return!1;let o=gu(a.keys,a.activeId);if(b(t=>c()?{...t,[e]:bu(o,t[e]??[],!1)}:t),!o.some(yu))return!0;let u=async()=>{let a=(D.current[r]??0)+1;D.current[r]=a;let s=()=>i.current&&A.current&&j.current===t&&D.current[r]===a;try{let t=await F(`${l}"a=1${n?`&refresh=1`:``}`);if(!Array.isArray(t.keys))throw Error(`Invalid key quota roster`);if(!s())return!1;let r=gu(t.keys,t.activeId);return b(t=>s()?{...t,[e]:c()?bu(r,t[e]??[],!0):vu(t[e]??[],r)}:t),!r.some(e=>e.quotaUnavailable===!0)}catch{return s()&&b(t=>s()?{...t,[e]:xu(t[e]??[],o)}:t),!1}};return n?await u():(u(),!0)}catch{return u()}}))).every(Boolean),[t,i,F]),R=(0,_.useCallback)(async(e,n)=>{if(!i.current||!A.current||j.current!==t||n?.aborted)return!1;let a=e?[e]:Object.entries(r?.providers??{}).flatMap(([e,t])=>t.authMode===`oauth`&&e!==`openai`?[{provider:e,kind:`oauth`}]:t.hasApiKey&&t.authMode!==`oauth`&&t.authMode!==`forward`?[{provider:e,kind:`api-key`}]:[]);return(await Promise.all(a.map(async({provider:e,kind:r})=>{let a=`${r===`oauth`?`oauth`:`key`}:${e}`;if(O.current.has(a))return!1;let o=(E.current[a]??0)+1;E.current[a]=o;let s=()=>i.current&&A.current&&j.current===t&&!n?.aborted&&E.current[a]===o&&!O.current.has(a);try{if(r===`oauth`){let r=await F(`${t}/api/oauth/accounts?provider=${encodeURIComponent(e)}`,n);if(!Array.isArray(r.accounts)||!s())return!1;let i=gu(r.accounts,r.activeAccountId);d(t=>s()?{...t,[e]:{activeAccountId:r.activeAccountId===void 0?i.find(e=>e.active)?.id??null:r.activeAccountId,accounts:_u(i,t[e]?.accounts??[])}}:t),p(t=>s()?{...t,[e]:`ready`}:t)}else{let r=await F(`${t}/api/providers/keys?name=${encodeURIComponent(e)}`,n);if(!Array.isArray(r.keys)||!s())return!1;let i=gu(r.keys,r.activeId);b(t=>s()?{...t,[e]:_u(i,t[e]??[])}:t)}return!0}catch{return!1}}))).every(Boolean)},[i,t,r,F]),z=(e,t)=>{let n=`${t===`oauth`?`oauth`:`key`}:${e}`;return T.current[n]=(T.current[n]??0)+1,E.current[n]=(E.current[n]??0)+1,n},B=async(e,r)=>{if(r.active||r.needsReauth||P.current)return;let o={provider:e,accountId:r.id};P.current=o,h(o);let l=z(e,`oauth`),f=Symbol();O.current.set(l,f);let p=()=>i.current&&A.current&&j.current===t&&O.current.get(l)===f,m=no(u[e]?.accounts??[r],r,n);try{let i=await fetch(`${t}/api/oauth/accounts/active`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e,accountId:r.id})});if(!p())return;if(!i.ok){a(n(`prov.accountSwitchFail`),!1);return}let o=await i.json().catch(()=>({}));if(!p())return;z(e,`oauth`);let u=o.activeAccountId===void 0?r.id:o.activeAccountId;d(t=>t[e]?{...t,[e]:{...t[e],activeAccountId:u,accounts:gu(t[e].accounts,u)}}:t),O.current.delete(l);let f=await R({provider:e,kind:`oauth`});if(await Promise.all([s(),c(!0)]),!f){a(n(`pws.accountsLoadFailed`),!1);return}a(n(`prov.accountSwitched`,{email:m}),!0)}catch{p()&&a(n(`prov.accountSwitchFail`),!1)}finally{p()&&(z(e,`oauth`),O.current.delete(l),R({provider:e,kind:`oauth`})),P.current?.provider===o.provider&&P.current.accountId===o.accountId&&(P.current=null,i.current&&h(null))}},V=async(e,r)=>{if(r.active||O.current.has(`key:${e}`))return;let o=z(e,`api-key`),s=Symbol();O.current.set(o,s);let l=()=>i.current&&A.current&&j.current===t&&O.current.get(o)===s;try{let i=await fetch(`${t}/api/providers/keys/active`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:e,id:r.id})});if(!l())return;if(!i.ok){let e=await i.json().catch(()=>({}));l()&&a(e.error||n(`prov.keySwitchFail`),!1);return}let o=await i.json().catch(()=>({}));if(!l())return;z(e,`api-key`);let s=o.activeId===void 0?r.id:o.activeId;b(t=>t[e]?{...t,[e]:gu(t[e],s)}:t),a(n(`prov.keySwitched`,{key:r.label??r.masked}),!0),c(!0)}catch{l()&&a(n(`prov.keySwitchFail`),!1)}finally{l()&&(z(e,`api-key`),O.current.delete(o),R({provider:e,kind:`api-key`}))}},H=async(e,r)=>{window.confirm(n(`prov.keyRemoveConfirm`,{key:r.label??r.masked}))&&(await fetch(`${t}/api/providers/keys?name=${encodeURIComponent(e)}&id=${encodeURIComponent(r.id)}`,{method:`DELETE`})).ok&&(a(n(`prov.keyRemoved`,{key:r.label??r.masked}),!0),L(Object.keys(y)),o(),c(!0))},U=async(e,r)=>{let i=r.trim();if(!i)return!1;try{let r=await fetch(`${t}/api/providers/keys`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:e,key:i})});if(!r.ok){let e=await r.json().catch(()=>({}));return a(e.error||n(`prov.keyAddFail`),!1),!1}return a(n(`prov.keyAdded`,{name:e}),!0),S(null),await Promise.all([L(Object.keys(y).includes(e)?Object.keys(y):[...Object.keys(y),e]),o(),c(!0)]),!0}catch{return a(n(`prov.keyAddFail`),!1),!1}},W=async e=>{await U(e,C)&&w(``)},G=async(e,r,i,o)=>{let s=window.prompt(n(`prov.aliasPrompt`),o??``);if(s===null)return;let c=s.trim(),l=await fetch(r===`oauth`?`${t}/api/oauth/accounts/alias`:`${t}/api/providers/keys/alias`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r===`oauth`?{provider:e,accountId:i,alias:c}:{name:e,id:i,alias:c})});if(!l.ok){let e=await l.json().catch(()=>({}));a(e.error||n(`prov.aliasSaveFailed`),!1);return}r===`oauth`?await I([e]):await L(Object.keys(y).includes(e)?Object.keys(y):[...Object.keys(y),e]),a(n(`prov.aliasSaved`),!0)},K=async(e,r)=>{let i=no(u[e]?.accounts??[r],r,n);if(window.confirm(n(`prov.accountRemoveConfirm`,{email:i})))try{if(!(await fetch(`${t}/api/oauth/accounts?provider=${encodeURIComponent(e)}&id=${encodeURIComponent(r.id)}`,{method:`DELETE`})).ok){a(n(`prov.accountRemoveFail`,{email:i}),!1);return}a(n(`prov.accountRemoved`,{email:i}),!0),await I([e]),await Promise.all([s(),c(!0)])}catch{a(n(`prov.accountRemoveFail`,{email:i}),!1)}},q=(0,_.useMemo)(()=>r?Object.entries(r.providers).filter(([,e])=>e.authMode===`oauth`).map(([e])=>e):[],[r]);(0,_.useEffect)(()=>{if(q.length===0)return;let e=`${t}:${q.join(`,`)}`;M.current!==e&&(M.current=e,Promise.resolve().then(()=>{I(q)}))},[t,I,q]);let J=(0,_.useMemo)(()=>r?Object.entries(r.providers).filter(([,e])=>e.hasApiKey&&e.authMode!==`oauth`&&e.authMode!==`forward`).map(([e])=>e):[],[r]);return(0,_.useEffect)(()=>{if(J.length===0)return;let e=`${t}:${J.join(`,`)}`;N.current!==e&&(N.current=e,Promise.resolve().then(()=>{L(J)}))},[t,L,J]),{accountSets:u,accountLoadStates:f,switchingAccount:m,openAccounts:g,keyPools:y,addingKeyFor:x,newKeyValue:C,setAccountSets:d,setAccountLoadStates:p,setSwitchingAccount:h,setOpenAccounts:v,setKeyPools:b,setAddingKeyFor:S,setNewKeyValue:w,fetchAccountSets:I,fetchKeyPools:L,refreshAccountRosters:R,switchAccount:B,switchApiKey:V,removeApiKey:H,addApiKeyValue:U,addApiKey:W,editCredentialAlias:G,removeAccount:K,oauthCardProviders:q,keyCardProviders:J,activeAccountNeedsReauth:(0,_.useMemo)(()=>Su(u,l),[u,l])}}var wu=new Set([`hasApiKey`,`hasHeaders`,`xaiResponsesOptInState`,`initialModelSelection`]);function Tu(e){return{defaultProvider:e.defaultProvider,providers:Object.fromEntries(Object.entries(e.providers).map(([e,t])=>{let n={};for(let[e,r]of Object.entries(t))wu.has(e)||(n[e]=structuredClone(r));return[e,n]}))}}function Eu(e){let{apiBase:t,config:n,notify:r,fetchConfig:i,fetchProviderQuotas:a,onSaved:o,t:s}=e,[c,l]=(0,_.useState)(!1),[u,d]=(0,_.useState)(``),[f,p]=(0,_.useState)(!1),[m,h]=(0,_.useState)(``),[g,v]=(0,_.useState)(!1),[y,b]=(0,_.useState)(!1),x=(0,_.useRef)(!1);(0,_.useEffect)(()=>{n&&!x.current&&d(JSON.stringify(Tu(n),null,2))},[n]);let S=(0,_.useCallback)(async()=>{v(!0);let e;try{e=JSON.parse(u)}catch{return r(s(`prov.invalidJson`),!1),v(!1),!1}try{let n=JSON.parse(m),c=await fetch(`${t}/api/providers`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({baseline:n,next:e})});if(!c.ok){let e=await c.json().catch(()=>({}));return r(e.error||s(`prov.saveFailed`),!1),!1}r(s(`prov.saved`),!0),l(!1),p(!1),x.current=!1,b(!1),h(JSON.stringify(e,null,2)),i(),a(!0);let u=Object.keys(e.providers).filter(e=>!Object.hasOwn(n.providers,e));return o(u),!0}catch{return r(s(`prov.saveFailed`),!1),!1}finally{v(!1)}},[t,u,i,a,m,r,o,s]),C=(0,_.useCallback)(()=>{let e=n?JSON.stringify(Tu(n),null,2):u;h(e),d(e),b(!1),p(!0),x.current=!0},[n,u]),w=(0,_.useCallback)(()=>{b(!1),p(!1),x.current=!1;let e=n?JSON.stringify(Tu(n),null,2):m;h(e),d(e)},[n,m]);return{editing:c,setEditing:l,draft:u,setDraft:d,jsonEditorOpen:f,jsonBaseline:m,jsonSaving:g,jsonLeaveOpen:y,jsonEditorOpenRef:x,saveConfig:S,openJsonEditor:C,discardJsonEditor:w,requestCloseJsonEditor:(0,_.useCallback)(()=>{if(f&&u!==m){b(!0);return}w()},[w,u,m,f]),restoreJsonEditor:(0,_.useCallback)(()=>{d(m)},[m]),jsonIsDirty:f&&u!==m,setJsonLeaveOpen:b}}var Du=new Map;function Ou(e,t){let n=JSON.stringify([e,t]),r=Du.get(n);if(r)return r;let i=(async()=>{await fetch(`${e}/api/oauth/login/cancel`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:t}),keepalive:!0})})().catch(()=>{}).finally(()=>{Du.get(n)===i&&Du.delete(n)});return Du.set(n,i),i}async function ku(e,t,n){let r=JSON.stringify([e,t]),i=Du.get(r);return i?(await i,ku(e,t,n)):n()}var Au={xai:`xAI (Grok)`,anthropic:`Anthropic (Claude)`,kimi:`Kimi (Moonshot)`,"meta-muse":`Meta Muse Code (CLI)`,"google-antigravity":`Google Antigravity`,"github-copilot":`GitHub Copilot`,cursor:`Cursor`,devin:`Devin`},ju=e=>Au[e]??e;function Mu({apiBase:e,t,aliveRef:n,accountSets:r,setAccountSets:i,setBusy:a,setStatus:o,setLoginInfo:s,setOauthStatus:c,notify:l,fetchConfig:u,fetchOauth:d,fetchAccountSets:f,fetchProviderQuotas:p,bumpModelsRefresh:m,onLoginSettled:h}){let g=(0,_.useRef)(null);g.current===null&&(g.current=new Map);let v=(0,_.useRef)(new Map),y=(0,_.useCallback)(e=>{let t=(g.current.get(e)??0)+1;return g.current.set(e,t),t},[]),b=(0,_.useCallback)(t=>Ou(e,t),[e]);return(0,_.useEffect)(()=>{let e=e=>{let t=[...v.current];v.current.clear();for(let[n,r]of t)g.current.get(n)===r&&y(n),e&&(a(e=>e===n?null:e),s(e=>e?.provider===n?null:e)),b(n)},t=()=>e(!0);return window.addEventListener(`pagehide`,t),()=>{window.removeEventListener(`pagehide`,t),e(!1)}},[y,b,a,s]),{cancelLoginOAuth:(0,_.useCallback)(async e=>{let r=y(e);v.current.delete(e),await b(e),!(!n.current||g.current.get(e)!==r)&&(a(t=>t===e?null:t),s(t=>t?.provider===e?null:t),l(t(`prov.loginCancelled`,{provider:ju(e)}),!1))},[n,y,b,l,a,s,t]),loginOAuth:async(d,_=!1,x)=>{let S=y(d);v.current.set(d,S);let C=x?.trim()||void 0;a(d),o(``),s(null);try{let a=await ku(e,d,()=>{if(!(!n.current||g.current.get(d)!==S))return fetch(`${e}/api/oauth/login`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:d,...Cs(),..._||C?{addAccount:!0}:{},...C?{accountId:C,reauth:!0}:{}})})});if(!a||g.current.get(d)!==S||!n.current)return;if(!a.ok){let e=await a.json().catch(()=>({}));if(!n.current||g.current.get(d)!==S)return;l(e.error||t(`prov.loginFailStart`,{provider:ju(d)}),!1);return}let o=await a.json();if(!n.current||g.current.get(d)!==S)return;(o.url||o.instructions||o.deviceCode)&&s({provider:d,url:o.url,instructions:o.instructions,deviceCode:o.deviceCode});let v=r[d]?.accounts.length??0,y=!1;for(let a=0;a<150&&n.current&&g.current.get(d)===S;a++){if(await new Promise(e=>setTimeout(e,2e3)),g.current.get(d)!==S||!n.current)return;let a=await fetch(`${e}/api/oauth/status?provider=${d}`).catch(()=>null),o=a?await Lt(a)??null:null;if(!n.current||g.current.get(d)!==S)return;if(!o)continue;if(o.error){c(e=>({...e,[d]:o})),l(/cancel/i.test(o.error)?t(`prov.loginCancelled`,{provider:ju(d)}):t(`prov.loginError`,{provider:ju(d),error:o.error}),!1),s(null),y=!0;break}let b=o.accounts?.length??0;if(_||C?b>v||o.done===!0:o.loggedIn||o.done===!0){c(e=>({...e,[d]:o}));let e=C?o.accounts?.find(e=>e.id===C):o.accounts?.find(e=>e.active)??o.accounts?.find(e=>e.id===o.activeAccountId);if(C&&!e){l(t(`prov.loginError`,{provider:ju(d),error:t(`prov.reauthAccountMissing`)}),!1),s(null),y=!0;break}if(e?.needsReauth){l(t(`prov.loginError`,{provider:ju(d),error:t(`prov.reauthIdentityMismatch`)}),!1),s(null),y=!0;break}if(o.accounts){let e=o.accounts.find(e=>e.active)?.id??null;i(t=>t[d]?t:{...t,[d]:{activeAccountId:o.activeAccountId??e,accounts:o.accounts}})}s(null),h?.(d);let a=Object.keys(r);if(await f(new Set(a).has(d)?a:[...a,d]),!n.current||g.current.get(d)!==S)return;_&&!C&&b<=v?l(t(`prov.loginSameAccount`,{provider:ju(d)}),!1):l(t(`prov.loginOk`,{provider:ju(d),cmd:`ocx sync`}),!0),u(),p(!0),m(),y=!0;break}}if(!y&&g.current.get(d)===S&&n.current){if(await b(d),!n.current||g.current.get(d)!==S)return;l(t(`prov.loginTimeout`,{provider:ju(d)}),!1),s(null)}}catch{if(g.current.get(d)===S){if(await b(d),!n.current||g.current.get(d)!==S)return;l(t(`prov.loginRequestFail`,{provider:ju(d)}),!1)}}finally{v.current.get(d)===S&&v.current.delete(d),n.current&&g.current.get(d)===S&&a(null)}},logoutOAuth:async n=>{y(n),a(e=>e===n?null:e),s(e=>e?.provider===n?null:e);try{if(!(await fetch(`${e}/api/oauth/logout?provider=${encodeURIComponent(n)}`,{method:`POST`})).ok){l(t(`prov.logoutFail`,{provider:ju(n)}),!1);return}await Promise.all([f([n]),d(),u(),p(!0)]),m(),l(t(`prov.logoutOk`,{provider:ju(n)}),!0)}catch{l(t(`prov.logoutFail`,{provider:ju(n)}),!1)}}}}async function Nu(e,t){try{let t=await e.json();if(typeof t.error==`string`&&t.error.trim())return t.error.trim()}catch{}return t}function Pu(e,t,n){switch(e.code){case`last_provider`:return t(`prov.removeLastProvider`);case`provider_has_dependent_combos`:return t(`prov.removeHasDependentCombos`,{combos:(Array.isArray(e.combos)?e.combos.filter(e=>typeof e==`string`).join(`, `):``)||`—`});case`default_provider_disabled`:return t(`prov.defaultDisabled`);default:return typeof e.error==`string`&&e.error.trim()?e.error.trim():n}}function Fu({apiBase:e,t,removeBusyRef:n,workspaceSelected:r,setWorkspaceSelected:i,setRemoveConfirmName:a,notify:o,fetchConfig:s,fetchOauth:c,fetchProviderQuotas:l,refreshCodexAccount:u}){let d=(0,_.useCallback)(async e=>{a(e)},[a]),f=(0,_.useCallback)(async u=>{let d=u;if(!d||n.current)return;n.current=!0,a(null);let f=t(`prov.removeFail`,{name:d});try{let n=await fetch(`${e}/api/providers?name=${encodeURIComponent(d)}`,{method:`DELETE`});if(n.ok){let e=await n.json().catch(()=>({})),a=typeof e.defaultProvider==`string`?e.defaultProvider:null;o(a?t(`prov.removedDefault`,{name:d,defaultProvider:a}):t(`prov.removed`,{name:d}),!0),r===d&&i(null),s(),c(),l(!0)}else o(Pu(await n.json().catch(()=>({})),t,f),!1)}catch{o(f,!1)}finally{n.current=!1}},[e,s,c,l,o,n,a,i,t,r]),p=(0,_.useCallback)(async(n,r)=>{let i=await fetch(`${e}/api/providers?name=${encodeURIComponent(n)}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({disabled:r})});if(!i.ok){o(await Nu(i,t(r?`prov.disableFail`:`prov.enableFail`,{name:n})),!1);return}o(t(r?`prov.disabled`:`prov.enabled`,{name:n}),!0),s(),c(),l(!0)},[e,s,c,l,o,t]),m=(0,_.useCallback)(async(n,r)=>{try{let i=await fetch(`${e}/api/providers?name=${encodeURIComponent(n)}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r)});if(!i.ok)return{ok:!1,error:await Nu(i,t(`prov.updateFail`))};let a=await i.json().catch(()=>({}));if(await s(),Object.hasOwn(r,`codexAccountMode`)){let e=[l(!0)];u&&e.push(Promise.resolve(u())),await Promise.all(e)}let o=a.xaiResponsesOptInState;return{ok:!0,...o===!0||o===!1||o===`mixed`?{xaiResponsesOptInState:o}:{}}}catch{return{ok:!1,error:t(`prov.networkError`)}}},[e,s,l,u,t]);return{removeProvider:d,confirmRemoveProvider:f,setProviderDisabled:p,setDefaultProvider:(0,_.useCallback)(async n=>{try{let r=await fetch(`${e}/api/providers?name=${encodeURIComponent(n)}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({setDefault:!0})});return r.ok?(o(t(`prov.setDefaultSuccess`,{name:n}),!0),await s(),!0):(o(Pu(await r.json().catch(()=>({})),t,t(`prov.setDefaultFail`,{name:n})),!1),!1)}catch{return o(t(`prov.setDefaultFail`,{name:n}),!1),!1}},[e,s,o,t]),updateProvider:m}}function Iu({apiBase:e,t,setConfig:n,setOauthProviders:r,setOauthStatus:i,notify:a,invalidateProviderQuotas:o,configCacheKey:s}){let c=(0,_.useRef)(0);return(0,_.useEffect)(()=>()=>{c.current+=1},[e]),{fetchConfig:(0,_.useCallback)(async()=>{let r=++c.current;try{let t=await It(await fetch(`${e}/api/config`));if(r!==c.current)return`superseded`;if(!t)throw Error(`config response missing`);return n(t??null),s&&t&&kr(s,t),`applied`}catch{return r===c.current?(a(t(`prov.loadConfigFail`),!1),`failed`):`superseded`}},[e,s,a,n,t]),fetchOauth:(0,_.useCallback)(async()=>{try{let t=(await It(await fetch(`${e}/api/oauth/providers`)))?.providers??[];r(t);let n=await Promise.all(t.map(async t=>{let n=await fetch(`${e}/api/oauth/status?provider=${encodeURIComponent(t)}`).catch(()=>null);return[t,n?await Lt(n)??{loggedIn:!1}:{loggedIn:!1}]}));i(Object.fromEntries(n))}catch{}},[e,r,i]),fetchProviderQuotas:(0,_.useCallback)(async(e=!1)=>{o(e)},[o])}}function Lu({providerId:e,providerLabel:t,onCancel:n,onContinue:r}){let i=Q(),a=(0,_.useId)(),o=(0,_.useId)(),s=(0,_.useRef)(null),c=(0,_.useRef)(!1),[l,u]=(0,_.useState)(!1),[d,f]=(0,_.useState)(!1),p=pu(e);(0,_.useEffect)(()=>{let e=s.current;e&&!e.open&&e.showModal()},[]);let m=(0,_.useCallback)(e=>{e.preventDefault(),n()},[n]);if(!p)return null;let h=e.trim().toLowerCase(),g=h===`anthropic`?`oauthTos.anthropicBody`:hu(p),v=h===`anthropic`||h===`google-antigravity`;return(0,Y.jsxs)(`dialog`,{ref:s,"aria-labelledby":a,"aria-describedby":o,className:`modal-overlay`,onCancel:m,children:[(0,Y.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":i(`common.close`),tabIndex:-1,onClick:n}),(0,Y.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),style:{maxWidth:460},children:[(0,Y.jsx)(`h3`,{id:a,children:i(mu(p),{provider:t})}),(0,Y.jsxs)(`div`,{id:o,className:`notice-warn`,style:{marginTop:12,display:`flex`,gap:8,alignItems:`flex-start`},children:[(0,Y.jsx)(_e,{width:16,height:16,style:{flexShrink:0,marginTop:2},"aria-hidden":`true`}),(0,Y.jsx)(`p`,{className:`modal-desc`,style:{margin:0},children:i(g,{provider:t})})]}),v&&(0,Y.jsx)(`p`,{className:`muted text-label`,style:{marginTop:12},children:i(`oauthTos.saferPath`)}),(0,Y.jsxs)(`label`,{className:`oauth-tos-ack`,style:{display:`flex`,gap:8,alignItems:`flex-start`,marginTop:14},children:[(0,Y.jsx)(`input`,{type:`checkbox`,checked:l,onChange:e=>u(e.target.checked),style:{marginTop:3},"aria-required":`true`}),(0,Y.jsx)(`span`,{className:`text-label`,children:i(`oauthTos.acknowledge`)})]}),(0,Y.jsxs)(`div`,{className:`modal-actions`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:n,children:i(`common.cancel`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!l||d,onClick:()=>{!l||c.current||(c.current=!0,f(!0),r())},children:i(`oauthTos.continue`)})]})]})]})}function Ru(e,t,n){return!n||e.kind!==`oauth`||t!==e.id?!1:n.provider===e.id}function zu({row:e,status:t,busyProvider:n,loginHint:r,paste:i,onLogin:a,onCancelLogin:o,onLogout:s,onManage:c}){let l=Q(),u=n===e.id,d=!!t?.loggedIn,f=d?t?.email??e.statusLabel??l(`modal.accountLoggedIn`):t?.error??e.statusLabel??l(`modal.accountLoggedOut`),p=Ru(e,n,r);return(0,Y.jsxs)(`div`,{className:`list-row provider-catalog-account-row${p?` provider-catalog-account-row--waiting`:``}`,children:[(0,Y.jsxs)(`div`,{className:`provider-catalog-account-row-head`,children:[(0,Y.jsx)(ta,{name:e.id,cls:`provider-icon provider-icon-sm`}),(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`div`,{className:`title`,children:e.label}),(0,Y.jsx)(`div`,{className:`sub`,children:f})]}),(0,Y.jsx)(`div`,{className:`provider-catalog-badges`,children:e.kind===`key`?null:e.kind===`codex`?(0,Y.jsxs)(Y.Fragment,{children:[d&&(0,Y.jsx)(`a`,{className:`btn btn-ghost`,href:e.href??`#codex-set`,children:l(`modal.accountManage`)}),a&&(0,Y.jsx)(`button`,{type:`button`,className:d?`btn btn-ghost`:`btn btn-primary`,disabled:u,onClick:()=>{u||a(e.id)},children:l(u?`codexAuth.enablingOpenai`:d?`modal.accountAdd`:`modal.accountLogin`)})]}):d?(0,Y.jsxs)(Y.Fragment,{children:[c&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>c(e.id),children:l(`modal.accountManage`)}),a&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:u,onClick:()=>{u||a(e.id,!0)},children:l(u?`prov.waitingBrowser`:`modal.accountAdd`)}),u&&o&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>o(e.id),children:l(`common.cancel`)}),s&&!u&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>s(e.id),children:l(`modal.accountLogout`)})]}):u?o&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>o(e.id),children:l(`common.cancel`)}):a&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>a(e.id),children:l(`modal.accountLogin`)})})]}),p&&r&&(0,Y.jsx)(ys,{hint:{url:r.url,deviceCode:r.deviceCode,instructions:r.instructions},...i?{paste:{value:i.value,busy:i.busy,message:i.message,ok:i.ok,onChange:i.onChange,onSubmit:()=>i.onSubmit(e.id)}}:{}})]})}var Bu=[`accounts`,`free`,`local`,`paid`],Vu={accounts:`modal.tab.accounts`,free:`modal.tab.free`,local:`modal.tab.local`,paid:`modal.tab.paid`},Hu={},Uu=[],Wu={};function Gu({presets:e,usageRank:t=Hu,presetsLoading:n=!1,initialTier:r=`free`,query:i,onQueryChange:a,onSelectPreset:o,onSelectCustom:s,onShowNote:c,accountRows:l=Uu,accountStatus:u=Wu,busyProvider:d=null,loginHint:f=null,paste:p,onLogin:m,onCancelLogin:h,onLogout:g,onManage:v}){let y=Q(),[b,x]=(0,_.useState)(r),S=(0,_.useId)(),C=e=>`${S}-${e}`,w=(0,_.useRef)(null),T=i.trim().length>0;(0,_.useEffect)(()=>{w.current&&(w.current.scrollTop=0)},[b,T]);let E=(0,_.useMemo)(()=>e.filter(e=>e.id!==`custom`),[e]),D=(0,_.useMemo)(()=>{let e=Object.keys(t).length>0;return E.toSorted((n,r)=>{if(e){let e=t[n.id]??0,i=t[r.id]??0;if(i!==e)return i-e}return n.label.localeCompare(r.label,void 0,{sensitivity:`base`})||n.id.localeCompare(r.id)})},[E,t]),O=(0,_.useMemo)(()=>po(xo(D)),[D]),k=O[b],A=(0,_.useMemo)(()=>T?vo(l,i,d):l,[l,i,T,d]),j=(0,_.useMemo)(()=>{let e=Bu.filter(e=>e!==`accounts`);return T?e.map(e=>({tier:e,rows:_o(yo(O[e].filter(e=>go(e,i)),A),i)})):b===`accounts`?[]:[{tier:b,rows:k}]},[T,b,k,O,i,A]),M=(0,_.useMemo)(()=>({...Object.fromEntries(j.map(e=>[e.tier,e.rows.length])),accounts:A.length}),[j,A]),N=Bu.reduce((e,t)=>e+(M[t]??0),0),P=Bu.filter(e=>(M[e]??0)>0),F=T?N:b===`accounts`?A.length:j[0]?.rows.length??0,I=e=>{let t=w.current,n=t?.querySelector(`[data-catalog-group="${e}"]`);!t||!n||(t.scrollTop=n.offsetTop-t.offsetTop,d||n.focus({preventScroll:!0}))},L=e=>{if(e.key!==`ArrowDown`)return;let t=w.current?.querySelector(`button:not(:disabled), a[href]`);t&&(e.preventDefault(),t.focus())},R=(e,t)=>(0,Y.jsxs)(`h4`,{id:C(e),"data-catalog-group":e,className:`provider-catalog-group-head`,tabIndex:-1,children:[(0,Y.jsx)(`span`,{children:y(Vu[e])}),(0,Y.jsx)(`span`,{className:`provider-catalog-group-count`,children:t})]}),z=e=>{let t=e.codexAccountMode===`direct`?(0,Y.jsx)(`span`,{className:`badge badge-green`,children:y(`modal.badge.direct`)}):e.codexAccountMode===`pool`?(0,Y.jsx)(`span`,{className:`badge badge-accent`,children:y(`modal.badge.pool`)}):e.auth===`oauth`?(0,Y.jsx)(`span`,{className:`badge badge-accent`,children:y(`modal.badge.oauth`)}):e.auth===`forward`?(0,Y.jsx)(`span`,{className:`badge badge-green`,children:y(`modal.badge.codexLogin`)}):e.auth===`local`?(0,Y.jsx)(`span`,{className:`badge badge-amber`,children:y(`modal.badge.local`)}):e.keyOptional?null:(0,Y.jsx)(`span`,{className:`badge badge-muted`,children:y(`modal.badge.apiKey`)}),n=(e.freeTier||e.keyOptional)&&e.auth===`key`?(0,Y.jsx)(`span`,{className:`badge badge-green`,children:y(`modal.badge.free`)}):null,r=e.sponsor?(0,Y.jsx)(`span`,{className:`badge badge-accent provider-catalog-sponsor`,title:e.sponsorUrl,children:y(`modal.badge.sponsor`)}):null;return(0,Y.jsxs)(Y.Fragment,{children:[r,n,t]})};return(0,Y.jsxs)(`div`,{className:`provider-catalog`,children:[(0,Y.jsx)(`input`,{className:`input provider-catalog-search`,type:`search`,value:i,onChange:e=>a(e.target.value),onKeyDown:L,placeholder:y(`modal.search`),"aria-label":y(`modal.search`)}),T?(0,Y.jsx)(`div`,{className:`provider-catalog-tabs provider-catalog-tabs--chips`,children:Bu.map(e=>(0,Y.jsxs)(`button`,{type:`button`,className:`provider-catalog-tab provider-catalog-chip`,disabled:(M[e]??0)===0,...(M[e]??0)>0?{"aria-controls":C(e)}:{},onClick:()=>I(e),children:[y(Vu[e]),(0,Y.jsx)(`span`,{className:`provider-catalog-chip-count`,children:M[e]??0})]},e))}):(0,Y.jsx)(`div`,{className:`provider-catalog-tabs`,role:`tablist`,children:Bu.map(e=>(0,Y.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":b===e,"aria-controls":S,className:`provider-catalog-tab${b===e?` active`:``}`,onClick:()=>x(e),children:y(Vu[e])},e))}),!T&&b===`accounts`&&(0,Y.jsx)(`div`,{className:`provider-catalog-accounts-hint muted text-label`,children:y(`modal.accountsHint`)}),(0,Y.jsx)(`div`,{className:`sr-only`,"aria-live":`polite`,"aria-atomic":`true`,children:T?N===0?y(`modal.noMatch`):y(`modal.searchResults`,{count:N,tiers:P.map(e=>y(Vu[e])).join(`, `)}):``}),(0,Y.jsxs)(`div`,{className:`provider-catalog-rows`,id:S,ref:w,children:[n&&F===0&&(0,Y.jsx)(`div`,{className:`muted text-control provider-catalog-empty`,children:y(`modal.catalogLoading`)}),(T||b===`accounts`)&&A.length>0&&(0,Y.jsxs)(_.Fragment,{children:[T&&R(`accounts`,A.length),A.map(e=>(0,Y.jsx)(zu,{row:e,status:u[e.id],busyProvider:d,loginHint:f,...p?{paste:p}:{},...m?{onLogin:m}:{},...h?{onCancelLogin:h}:{},...g?{onLogout:g}:{},...v?{onManage:v}:{}},e.id))]},`accounts`),j.map(e=>e.rows.length===0?null:(0,Y.jsxs)(_.Fragment,{children:[T&&R(e.tier,e.rows.length),e.rows.map(e=>(0,Y.jsxs)(`div`,{className:`provider-catalog-row-wrap`,children:[(0,Y.jsxs)(`button`,{type:`button`,className:`list-row`,onClick:()=>o(e),children:[(0,Y.jsx)(ta,{name:e.id,adapter:e.adapter,cls:`provider-icon provider-icon-sm`}),(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`div`,{className:`title`,children:e.label}),(0,Y.jsxs)(`div`,{className:`sub`,children:[(0,Y.jsx)(`code`,{className:`chip`,children:e.adapter}),e.note?` · ${e.note}`:``]})]}),(0,Y.jsx)(`div`,{className:`provider-catalog-badges`,children:z(e)})]}),c&&mo(e.note)&&(0,Y.jsx)(`button`,{type:`button`,className:`link-btn provider-catalog-note-more`,onClick:()=>c(e),children:y(`modal.noteMore`)})]},e.id))]},e.tier)),!n&&F===0&&(0,Y.jsx)(`div`,{className:`muted text-control provider-catalog-empty`,children:y(`modal.noMatch`)})]}),(0,Y.jsxs)(`div`,{className:`provider-catalog-footer`,children:[(0,Y.jsx)(`div`,{style:{flex:1}}),!T&&b!==`accounts`&&(0,Y.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:s,children:y(`modal.notListed`)})]})]})}function Ku({providerId:e,label:t,adapter:n,note:r,onClose:i}){let a=Q(),o=(0,_.useId)(),s=(0,_.useId)(),c=(0,_.useRef)(null);(0,_.useEffect)(()=>{let e=c.current,t=document.activeElement;return e&&!e.open&&e.showModal(),()=>{e?.open&&e.close(),t?.isConnected&&t.focus({preventScroll:!0})}},[]);let l=(0,_.useCallback)(e=>{e.preventDefault(),i()},[i]);return(0,Y.jsxs)(`dialog`,{ref:c,"aria-labelledby":o,"aria-describedby":s,className:`modal-overlay`,onCancel:l,children:[(0,Y.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":a(`common.close`),tabIndex:-1,onClick:i}),(0,Y.jsxs)(`div`,{className:`modal-card provider-note-card`,onClick:e=>e.stopPropagation(),children:[(0,Y.jsxs)(`div`,{className:`modal-head`,children:[(0,Y.jsxs)(`h3`,{id:o,className:`provider-note-title`,children:[(0,Y.jsx)(ta,{name:e,adapter:n,cls:`provider-icon provider-icon-sm`}),t]}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,"aria-label":a(`common.close`),onClick:i,children:(0,Y.jsx)(le,{})})]}),(0,Y.jsxs)(`div`,{id:s,className:`provider-note-body`,children:[(0,Y.jsx)(`code`,{className:`chip`,children:n}),(0,Y.jsx)(`p`,{className:`modal-desc provider-note-text`,children:r})]}),(0,Y.jsx)(`div`,{className:`modal-actions`,children:(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:i,children:a(`common.close`)})})]})]})}function qu({preset:e,oauthSupported:t,oauthBusy:n,oauthMsg:r,oauthMsgTone:i,oauthUrl:a,oauthDeviceCode:o,oauthInstructions:s,manualCode:c,manualCodeBusy:l,manualCodeMsg:u,manualCodeOk:d,onRequestLogin:f,onCancelLogin:p,onUseApiKeyInstead:m,onManualCodeChange:h,onSubmitManualCode:g,onBack:_}){let v=Q();return(0,Y.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:14},children:[(0,Y.jsx)(`div`,{className:`muted text-control`,children:e.note??v(`modal.oauthDefaultNote`)}),t.includes(e.oauthProvider??``)?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>f(e.oauthProvider),disabled:n,style:{width:`100%`,padding:`12px 16px`},children:[(0,Y.jsx)(ke,{}),n?v(`modal.waitingBrowser`):v(`modal.logInWith`,{label:e.label})]}),!n&&(0,Y.jsx)(dl,{})]}):(0,Y.jsx)(`div`,{className:`text-control`,style:{color:`var(--amber)`,background:`var(--amber-soft)`,border:`1px solid var(--amber)`,borderRadius:`var(--radius-sm)`,padding:`10px 12px`},children:v(`modal.oauthComingSoon`,{label:e.label})}),r&&(0,Y.jsx)(`div`,{className:`text-label`,style:{color:i===`warn`?`var(--amber)`:`var(--accent-hover)`},children:r}),n&&(0,Y.jsx)(ys,{hint:{url:a,deviceCode:o,instructions:s},paste:{value:c,busy:l,disabled:!e.oauthProvider,message:u,ok:d,onChange:h,onSubmit:()=>{e.oauthProvider&&g(e.oauthProvider)}}}),(0,Y.jsxs)(`div`,{style:{display:`flex`,gap:8,alignItems:`center`,marginTop:2},children:[(0,Y.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:m,children:v(`modal.useApiKeyInstead`)}),(0,Y.jsx)(`div`,{style:{flex:1}}),n&&e.oauthProvider&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>p(e.oauthProvider),children:v(`common.cancel`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:_,children:v(`modal.back`)})]})]})}function Ju({label:e,children:t}){return(0,Y.jsxs)(`label`,{style:{display:`block`},children:[(0,Y.jsx)(`span`,{className:`field-label`,children:e}),t]})}function Yu({preset:e,form:t,endpointChoice:n,error:r,saving:i,dup:a,isCustom:o,isLocal:s,isReservedForward:c,presetDescription:l,onFormChange:u,onEndpointChoiceChange:d,onSubmit:f,onUseOauthLogin:p,onBack:m}){let h=Q();return(0,Y.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:10},children:[!c&&!o&&!s&&!e.keyOptional&&e.note&&(0,Y.jsxs)(`details`,{className:`setup-guide`,children:[(0,Y.jsx)(`summary`,{children:h(`modal.setupGuide`)}),(0,Y.jsxs)(`ol`,{className:`text-label leading-relaxed`,style:{margin:`8px 0 0`,paddingLeft:18,color:`var(--muted)`},children:[(0,Y.jsxs)(`li`,{children:[h(`modal.setupStep1Prefix`),` `,(0,Y.jsx)(`a`,{href:e.dashboardUrl,target:`_blank`,rel:`noreferrer`,children:h(`modal.setupDashboardLink`,{label:e.label})}),` `,h(`modal.setupStep1Suffix`)]}),(0,Y.jsx)(`li`,{children:h(`modal.setupStep2`)}),(0,Y.jsx)(`li`,{children:h(`modal.setupStep3`)})]}),e.note&&(0,Y.jsx)(`div`,{className:`text-label`,style:{color:`var(--muted)`,marginTop:6,fontStyle:`italic`},children:e.note}),/\{[^}]*\}/.test(t.baseUrl)&&(0,Y.jsx)(`div`,{className:`text-label`,style:{color:`var(--amber)`,marginTop:6},children:h(`modal.baseUrlPlaceholderHint`)})]}),(0,Y.jsx)(Ju,{label:h(`modal.providerName`),children:(0,Y.jsx)(`input`,{className:`input`,value:t.name,readOnly:c,onChange:e=>u({...t,name:e.target.value}),placeholder:h(`modal.namePlaceholder`)})}),a&&(0,Y.jsx)(`div`,{className:`text-label`,style:{color:`var(--amber)`},children:h(`modal.duplicateWarn`,{name:t.name.trim()})}),!c&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(Ju,{label:h(`modal.adapter`),children:(0,Y.jsx)(`select`,{className:`input`,value:t.adapter,onChange:e=>u({...t,adapter:e.target.value}),children:[`openai-responses`,`openai-chat`,`anthropic`,`google`,`azure-openai`,`cursor`].map(e=>(0,Y.jsx)(`option`,{value:e,children:e},e))})}),e.baseUrlChoices&&e.baseUrlChoices.length>0?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(Ju,{label:h(`modal.endpoint`),children:(0,Y.jsx)(`select`,{className:`input`,value:n,onChange:n=>{let r=n.target.value;d(r),u({...t,baseUrl:Bl(e.baseUrlChoices,r,t.baseUrl)})},children:e.baseUrlChoices.map(e=>(0,Y.jsx)(`option`,{value:e.id,children:e.id===`token-plan`?h(`modal.endpoint.tokenPlan`):e.id===`payg`?h(`modal.endpoint.payAsYouGo`):e.id===`custom`?h(`modal.endpoint.custom`):e.label},e.id))})}),n===`custom`&&(0,Y.jsx)(Ju,{label:h(`modal.baseUrl`),children:(0,Y.jsx)(`input`,{className:`input`,value:t.baseUrl,onChange:e=>u({...t,baseUrl:e.target.value}),placeholder:h(`modal.baseUrlPlaceholder`)})})]}):(0,Y.jsx)(Ju,{label:h(`modal.baseUrl`),children:(0,Y.jsx)(`input`,{className:`input`,value:t.baseUrl,onChange:e=>u({...t,baseUrl:e.target.value}),placeholder:h(`modal.baseUrlPlaceholder`)})}),!c&&(0,Y.jsxs)(`label`,{className:`modal-field`,style:{flexDirection:`row`,alignItems:`center`,gap:8},children:[(0,Y.jsx)(`input`,{type:`checkbox`,checked:t?.allowPrivateNetwork??!1,onChange:e=>u({...t,allowPrivateNetwork:e.target.checked})}),(0,Y.jsx)(`span`,{className:`muted text-control`,children:h(`modal.allowPrivateNetwork`)})]}),!c&&(t?.allowPrivateNetwork??!1)&&(0,Y.jsx)(`p`,{className:`muted text-hint`,children:h(`modal.allowPrivateNetworkHint`)})]}),t.authMode===`forward`?(0,Y.jsx)(`div`,{className:`text-label`,style:{color:`var(--green)`,background:`var(--green-soft)`,border:`1px solid var(--green)`,borderRadius:`var(--radius-sm)`,padding:`8px 10px`},children:l(e)}):t.authMode===`local`?(0,Y.jsx)(`div`,{className:`text-label leading-relaxed`,style:{color:`var(--amber)`,background:`var(--amber-soft)`,border:`1px solid var(--amber)`,borderRadius:`var(--radius-sm)`,padding:`8px 10px`},children:h(`modal.localHint`)}):e.keyOptional?(0,Y.jsxs)(`div`,{className:`text-label leading-relaxed`,style:{color:`var(--green)`,background:`var(--green-soft)`,border:`1px solid var(--green)`,borderRadius:`var(--radius-sm)`,padding:`10px 12px`},children:[(0,Y.jsx)(`strong`,{children:h(`modal.freeTierTitle`)}),` — `,e.note??h(`modal.freeTierDefault`)]}):(0,Y.jsxs)(Y.Fragment,{children:[e.dashboardUrl&&(0,Y.jsxs)(`a`,{className:`text-label`,href:e.dashboardUrl,target:`_blank`,rel:`noreferrer`,style:{display:`inline-flex`,alignItems:`center`,gap:5},children:[(0,Y.jsx)(De,{style:{width:14,height:14}}),h(`modal.getApiKey`,{label:e.label}),(0,Y.jsx)(Ee,{style:{width:13,height:13}})]}),(0,Y.jsx)(Ju,{label:h(`modal.apiKey`),children:(0,Y.jsx)(`input`,{className:`input`,type:`password`,value:t.apiKey,onChange:e=>u({...t,apiKey:e.target.value}),placeholder:h(`modal.apiKeyPlaceholder`)})}),t.adapter===`anthropic`&&t.authMode===`key`&&(0,Y.jsx)(Ju,{label:h(`modal.apiKeyTransport`),children:(0,Y.jsxs)(`select`,{className:`input`,value:t.apiKeyTransport??`x-api-key`,onChange:e=>u({...t,apiKeyTransport:e.target.value===`bearer`?`bearer`:void 0}),children:[(0,Y.jsx)(`option`,{value:`x-api-key`,children:h(`modal.apiKeyTransportNative`)}),(0,Y.jsx)(`option`,{value:`bearer`,children:h(`modal.apiKeyTransportBearer`)})]})})]}),!c&&(0,Y.jsx)(Ju,{label:h(`modal.defaultModel`),children:(0,Y.jsx)(`input`,{className:`input`,value:t.defaultModel,onChange:e=>u({...t,defaultModel:e.target.value}),placeholder:h(`modal.defaultModelPlaceholder`)})}),r&&(0,Y.jsx)(`div`,{className:`text-control`,role:`alert`,style:{color:`var(--red)`},children:r}),(0,Y.jsxs)(`div`,{style:{display:`flex`,gap:8,marginTop:4,alignItems:`center`},children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:f,disabled:i,children:h(i?`modal.adding`:`modal.add`)}),e.auth===`oauth`&&(0,Y.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:p,children:h(`modal.useOauthLogin`)}),(0,Y.jsx)(`div`,{style:{flex:1}}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:m,children:h(`modal.back`)})]})]})}var Xu=2e3;function Zu({apiBase:e,t,aliveRef:n,onAdded:r}){let i=(0,_.useRef)(new Map),a=(0,_.useRef)(new Map),o=(0,_.useCallback)(e=>{let t=(i.current.get(e)??0)+1;return i.current.set(e,t),t},[]),s=(0,_.useCallback)(t=>Ou(e,t),[e]);return(0,_.useEffect)(()=>{let e=e=>{let t=[...a.current];a.current.clear();for(let[n,r]of t)o(n),e&&(r.setOauthBusy(!1),r.setOauthUrl(``,n),r.setOauthMsg(``)),s(n)},t=()=>e(!0);return window.addEventListener(`pagehide`,t),()=>{window.removeEventListener(`pagehide`,t),e(!1)}},[o,s]),{cancelLoginOAuth:(0,_.useCallback)(async(e,r,c=e)=>{let l=o(e);a.current.delete(e),await s(e),!(!n.current||i.current.get(e)!==l)&&(r.setOauthBusy(!1),r.setOauthUrl(``,e),r.setOauthMsgTone(`warn`),r.setOauthMsg(t(`prov.loginCancelled`,{provider:c})))},[n,o,s,t]),loginOAuth:(0,_.useCallback)(async(c,l)=>{let{setOauthBusy:u,setOauthMsg:d,setOauthMsgTone:f,setOauthUrl:p,setManualCode:m,setManualCodeMsg:h,setManualCodeOk:g}=l,_=o(c),v=()=>i.current.get(c)===_;a.current.set(c,l),u(!0),d(``),f(`ok`),p(``,c),m(``),h(``),g(!0);try{let i=await ku(e,c,()=>{if(!(!n.current||!v()))return fetch(`${e}/api/oauth/login`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:c,...Cs()})})});if(!i||!n.current||!v())return;if(!i.ok){a.current.delete(c);let e=await i.json().catch(()=>({}));if(!n.current||!v())return;f(`warn`),d(e.error===`unknown oauth provider`?t(`modal.oauthComingSoonShort`):e.error||t(`modal.loginFailStart`));return}let o=await i.json();if(!n.current||!v())return;p(o.url??``,c,o.deviceCode,o.instructions),o.url||o.deviceCode?d(t(`modal.waitingLogin`)):d(o.instructions||t(`modal.loggingIn`));for(let i=0;i<100;i++){if(await new Promise(e=>setTimeout(e,Xu)),!n.current||!v())return;let i=await fetch(`${e}/api/oauth/status?provider=${c}`).catch(()=>null),o=i?await Lt(i):null;if(!n.current||!v())return;if(o?.error){a.current.delete(c),f(`warn`),d(t(`modal.loginError`,{error:o.error}));return}if(o?.loggedIn){a.current.delete(c),r(c);return}}if(await s(c),!n.current||!v())return;a.current.delete(c),f(`warn`),d(t(`modal.loginTimeout`))}catch{v()&&await s(c),v()&&a.current.delete(c),n.current&&v()&&(f(`warn`),d(t(`modal.networkError`)))}finally{n.current&&v()&&u(!1)}},[n,e,o,s,r,t]),submitManualCode:(0,_.useCallback)(async(r,i,a,o)=>{let s=i.trim();if(!s||a)return;let{setManualCodeBusy:c,setManualCode:l,setManualCodeOk:u,setManualCodeMsg:d}=o;c(!0),d(``);try{let i=await fetch(`${e}/api/oauth/login/code`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:r,input:s})});if(!n.current)return;if(!i.ok){let e=await i.json().catch(()=>({}));u(!1),d(t(`prov.pasteFail`,{error:e.error||i.statusText}));return}l(``),u(!0),d(t(`prov.pasteOk`))}catch{n.current&&(u(!1),d(t(`modal.networkError`)))}finally{n.current&&c(!1)}},[n,e,t])}}function Qu(e,t){return{preset:e?{id:`custom`,label:t,adapter:`openai-chat`,baseUrl:``,auth:`key`}:null,form:e?{name:``,adapter:`openai-chat`,baseUrl:``,authMode:`key`,apiKey:``,apiKeyTransport:void 0,defaultModel:``,allowPrivateNetwork:!1}:null,saving:!1,error:``,oauthBusy:!1,oauthMsg:``,oauthMsgTone:`ok`,oauthUrl:``,oauthDeviceCode:``,oauthInstructions:``,oauthUrlProvider:null,manualCode:``,manualCodeBusy:!1,manualCodeMsg:``,manualCodeOk:!0,endpointChoice:`custom`,oauthTosPending:null}}function $u(e,t){switch(t.type){case`choose-preset`:return{...e,preset:t.preset,form:t.form,endpointChoice:t.endpointChoice,error:``,oauthMsg:``,oauthMsgTone:`ok`,oauthUrl:``,oauthDeviceCode:``,oauthInstructions:``,oauthUrlProvider:null,oauthBusy:!1,manualCode:``,manualCodeMsg:``,manualCodeOk:!0};case`back`:return{...e,preset:null,form:null,endpointChoice:`custom`,error:``,oauthMsg:``,oauthMsgTone:`ok`,oauthUrl:``,oauthDeviceCode:``,oauthInstructions:``,oauthUrlProvider:null,oauthBusy:!1,manualCode:``,manualCodeMsg:``,manualCodeOk:!0};case`set-form`:return{...e,form:t.form};case`set-endpoint-choice`:return{...e,endpointChoice:t.choice};case`set-saving`:return{...e,saving:t.saving};case`set-error`:return{...e,error:t.error};case`set-oauth-busy`:return{...e,oauthBusy:t.busy};case`set-oauth-msg`:return{...e,oauthMsg:t.msg,oauthMsgTone:t.tone??e.oauthMsgTone};case`set-oauth-tone`:return{...e,oauthMsgTone:t.tone};case`set-oauth-url`:return e.preset?.oauthProvider===t.providerId?{...e,oauthUrl:t.url,oauthDeviceCode:t.deviceCode??``,oauthInstructions:t.instructions??``,oauthUrlProvider:t.providerId}:e;case`set-manual-code`:return{...e,manualCode:t.code};case`set-manual-code-busy`:return{...e,manualCodeBusy:t.busy};case`set-manual-code-msg`:return{...e,manualCodeMsg:t.msg,manualCodeOk:t.ok??e.manualCodeOk};case`set-oauth-tos-pending`:return{...e,oauthTosPending:t.providerId};case`use-oauth-login`:return{...e,form:t.form,error:``,oauthUrl:``,oauthDeviceCode:``,oauthInstructions:``,oauthUrlProvider:null};case`use-api-key-instead`:return{...e,form:t.form,oauthMsg:``,oauthMsgTone:`ok`,oauthUrl:``,oauthDeviceCode:``,oauthInstructions:``,oauthUrlProvider:null,oauthBusy:!1,manualCode:``,manualCodeMsg:``};default:return e}}function ed({apiBase:e,existingNames:t,onClose:n,onAdded:r,initialTier:i,initialCustom:a=!1,accountRows:o,accountStatus:s,accountBusy:c,accountLoginHint:l=null,onAccountLogin:u,onAccountCancelLogin:d,onAccountLogout:f,onAccountManage:p,onOpen:m}){let h=Q(),g=(0,_.useMemo)(()=>[{id:`custom`,label:h(`modal.customProvider`),adapter:`openai-chat`,baseUrl:``,auth:`key`}],[h]),[v,y]=(0,_.useReducer)($u,a,e=>Qu(e,h(`modal.customProvider`))),b=(0,_.useRef)(!0),x=(0,_.useRef)(null),S=(0,_.useRef)(null),[C,w]=(0,_.useState)(null),[T,E]=(0,_.useState)(``),D=K(`add-provider-oauth:${e}`,[e],async t=>{let n=await fetch(`${e}/api/oauth/providers`,{signal:t});return n.ok?(await n.json()).providers??[]:[]}),O=K(`add-provider-presets:${e}`,[e],async t=>{let n=await fetch(`${e}/api/provider-presets`,{signal:t});if(!n.ok)throw Error(String(n.status));let r=await n.json();return Array.isArray(r.providers)&&r.providers.length>0?r.providers:null}),k=K(qn(e),[e],async t=>{let n=await fetch(`${e}/api/usage?range=30d`,{signal:t});if(!n.ok)throw Error(String(n.status));return await n.json()},{deadlineMs:6e4}),A=D.data??[],j=O.data??g,M=O.loading,N=Object.fromEntries((k.data?.providers??[]).map(e=>[e.provider,e.requests])),{preset:P,form:F,saving:I,error:L,oauthBusy:R,oauthMsg:z,oauthMsgTone:B,oauthUrl:V,oauthUrlProvider:H,oauthDeviceCode:U,oauthInstructions:W,manualCode:G,manualCodeBusy:q,manualCodeMsg:J,manualCodeOk:X,endpointChoice:ee,oauthTosPending:te}=v;(0,_.useEffect)(()=>{b.current=!0,x.current=document.activeElement,m?.();let e=S.current;if(e){let t=e.querySelector(`input:not([disabled]), button:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex='-1'])`);t&&t.focus()}return()=>{b.current=!1,x.current?.focus()}},[]),(0,_.useEffect)(()=>{let e=e=>{let t=!te&&!C;if(!(e.key!==`Escape`||!t)){if(T){E(``);return}n()}};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n,te,C,T]);let ne=e=>{let t=Jl(e);return t?h(t):e.note},Z=e=>{let t=Vl(e.baseUrlChoices,e.baseUrl);y({type:`choose-preset`,preset:e,endpointChoice:t,form:{name:e.id===`custom`?``:e.id,adapter:e.adapter,baseUrl:e.baseUrlChoices?.length?Bl(e.baseUrlChoices,t,e.baseUrl):e.baseUrl,responsesPath:e.responsesPath,authMode:e.auth,apiKey:``,apiKeyTransport:void 0,defaultModel:e.defaultModel??``,allowPrivateNetwork:!1}})},re=async()=>{if(!F)return;let t=P?ql(P):!1,n=P?.baseUrlChoices?.length?Hl(P.baseUrlChoices,ee,F.baseUrl):F.baseUrl.trim();if(!t&&!F.name.trim()){y({type:`set-error`,error:h(`modal.nameRequired`)});return}if(!t&&!n){y({type:`set-error`,error:h(`modal.baseUrlRequired`)});return}if(!t&&/\{[^}]*\}/.test(n)){y({type:`set-error`,error:h(`modal.baseUrlPlaceholderError`)});return}let i={...F,baseUrl:n},a;try{a=Xl(P??{id:`custom`},i)}catch{y({type:`set-error`,error:h(`modal.invalidPreset`)});return}y({type:`set-saving`,saving:!0}),y({type:`set-error`,error:``});try{let t=await fetch(`${e}/api/providers`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(a)});if(!t.ok){let e=await t.json().catch(()=>({}));y({type:`set-error`,error:e.error||h(`modal.failedStatus`,{status:t.status})});return}r(a.name)}catch{y({type:`set-error`,error:h(`modal.networkError`)})}finally{y({type:`set-saving`,saving:!1})}},{cancelLoginOAuth:ie,loginOAuth:ae,submitManualCode:oe}=Zu({apiBase:e,t:h,aliveRef:b,onAdded:r}),se={setOauthBusy:e=>y({type:`set-oauth-busy`,busy:e}),setOauthMsg:e=>y({type:`set-oauth-msg`,msg:e}),setOauthMsgTone:e=>y({type:`set-oauth-tone`,tone:e}),setOauthUrl:(e,t,n,r)=>y({type:`set-oauth-url`,url:e,providerId:t,deviceCode:n,instructions:r}),setManualCode:e=>y({type:`set-manual-code`,code:e}),setManualCodeMsg:e=>y({type:`set-manual-code-msg`,msg:e}),setManualCodeOk:e=>y({type:`set-manual-code-msg`,msg:J,ok:e})},ce=F?t.includes(F.name.trim())&&F.name.trim()!==``:!1,ue=e=>{if(!R){if(pu(e)){y({type:`set-oauth-tos-pending`,providerId:e});return}ae(e,se)}},de=e=>{oe(e,G,q,{setManualCodeBusy:e=>y({type:`set-manual-code-busy`,busy:e}),setManualCode:e=>y({type:`set-manual-code`,code:e}),setManualCodeOk:e=>y({type:`set-manual-code-msg`,msg:J,ok:e}),setManualCodeMsg:e=>y({type:`set-manual-code-msg`,msg:e})})},fe=P?.id===`custom`,pe=F?.authMode===`local`,me=P?ql(P):!1;return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":h(`modal.add`),className:`modal-overlay`,children:(0,Y.jsxs)(`div`,{ref:S,className:`modal-card`,children:[(0,Y.jsxs)(`div`,{className:`modal-head`,children:[(0,Y.jsx)(`h3`,{children:P?h(`modal.addNamed`,{label:P.label}):h(`modal.add`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,"aria-label":h(`common.close`),onClick:n,children:(0,Y.jsx)(le,{})})]}),!P&&(0,Y.jsx)(Jn,{data:k.data}),P?F&&(P.auth===`oauth`&&F.authMode===`oauth`?(0,Y.jsx)(qu,{preset:P,oauthSupported:A,oauthBusy:R,oauthMsg:z,oauthMsgTone:B,oauthUrl:H===P.oauthProvider?V:``,oauthDeviceCode:H===P.oauthProvider?U:``,oauthInstructions:H===P.oauthProvider?W:``,manualCode:G,manualCodeBusy:q,manualCodeMsg:J,manualCodeOk:X,onRequestLogin:ue,onCancelLogin:e=>{ie(e,se,P.label)},onUseApiKeyInstead:()=>{R&&P.oauthProvider&&ie(P.oauthProvider,se,P.label),y({type:`use-api-key-instead`,form:{...F,authMode:`key`}})},onManualCodeChange:e=>y({type:`set-manual-code`,code:e}),onSubmitManualCode:e=>{de(e)},onBack:()=>{R&&P.oauthProvider&&ie(P.oauthProvider,se,P.label),y({type:`back`})}}):(0,Y.jsx)(Yu,{preset:P,form:F,endpointChoice:ee,error:L,saving:I,dup:ce,isCustom:fe,isLocal:pe,isReservedForward:me,presetDescription:ne,onFormChange:e=>y({type:`set-form`,form:e}),onEndpointChoiceChange:e=>y({type:`set-endpoint-choice`,choice:e}),onSubmit:()=>{re()},onUseOauthLogin:()=>y({type:`use-oauth-login`,form:{...F,authMode:`oauth`}}),onBack:()=>y({type:`back`})})):(0,Y.jsx)(Gu,{presets:j,usageRank:N,presetsLoading:M,initialTier:i,query:T,onQueryChange:E,onSelectPreset:e=>Z(e),onSelectCustom:()=>Z(g[0]),onShowNote:e=>w(e),accountRows:o,accountStatus:s,busyProvider:c,onLogin:u,onCancelLogin:d,onLogout:f,onManage:p,loginHint:l,paste:{value:G,busy:q,message:J,ok:X,onChange:e=>y({type:`set-manual-code`,code:e}),onSubmit:e=>{de(e)}}})]})}),te&&(0,Y.jsx)(Lu,{providerId:te,providerLabel:P?.label??te,onCancel:()=>y({type:`set-oauth-tos-pending`,providerId:null}),onContinue:()=>{let e=te;e&&(y({type:`set-oauth-tos-pending`,providerId:null}),ae(e,se))}},te),C?.note&&(0,Y.jsx)(Ku,{providerId:C.id,label:C.label,adapter:C.adapter,note:C.note,onClose:()=>w(null)},C.id)]})}function td({apiBase:e,config:t,adding:n,modelsNotice:r,addIntent:i,busy:a,addModalAccountRows:o,accountLoginStatus:s,accountLoginHint:c,removeConfirmName:l,removeDefaultProvider:u,codexLoginOpen:d,jsonLeaveOpen:f,jsonSaving:p,oauthTosPending:m,onCloseAdd:h,onAdded:g,onAccountLogin:_,onAccountCancelLogin:v,onAccountLogout:y,onAccountManage:b,onOpenAdd:x,onCloseCodexLogin:S,onCodexAdded:C,onCancelRemove:w,onConfirmRemove:T,onCancelJsonLeave:E,onDiscardJson:D,onSaveJson:O,onCancelOauthTos:k,onContinueOauthTos:A}){return(0,Y.jsxs)(Y.Fragment,{children:[r&&(0,Y.jsx)(ol,{...r}),n&&(0,Y.jsx)(ed,{apiBase:e,existingNames:Object.keys(t.providers),initialTier:i?.tier,initialCustom:i?.custom,onClose:h,onAdded:g,accountRows:o,accountStatus:s,accountBusy:a,accountLoginHint:c??null,onAccountLogin:_,onAccountCancelLogin:v,onAccountLogout:y,onAccountManage:b,onOpen:x}),d&&(0,Y.jsx)(ks,{apiBase:e,onClose:S,onAdded:C}),l&&(0,Y.jsx)(cu,{providerName:l,defaultProviderName:u,onCancel:w,onConfirm:T}),f&&E&&D&&O&&(0,Y.jsx)(lu,{saving:p??!1,onCancel:E,onDiscard:D,onSave:O}),m&&(0,Y.jsx)(Lu,{providerId:m.provider,providerLabel:ju(m.provider),onCancel:k,onContinue:A},`${m.provider}:${m.addAccount?`add`:`login`}`)]})}function nd(e,t,n){return[...Gl(e.providers).map(e=>({id:e,label:Ln(e,n),kind:`codex`,href:`#codex-set`})),...t.toSorted((e,t)=>e.localeCompare(t)).map(e=>({id:e,label:ju(e),kind:`oauth`}))]}function rd(e,t){let n={...t},r=t.openai;if(r)for(let[t,i]of Object.entries(e.providers))i.authMode===`forward`&&(n[t]=r);return n}function id(e,t){let[n,r]=(0,_.useState)({apiBase:e,notice:null});n.apiBase!==e&&r({apiBase:e,notice:null});let i=(0,_.useRef)(null);(0,_.useEffect)(()=>()=>{i.current=null},[e]);let a=(0,_.useCallback)((t,n,a=!1)=>{let o=typeof t==`string`?[t]:t,s={provider:o.join(`, `),providers:o,apiBase:e,initialRegistration:n&&o.length===1,catalogRefreshPending:a};i.current=s,r({apiBase:e,notice:{context:s,loading:!0,failed:!1}})},[e]),o=(0,_.useCallback)(()=>{i.current=null,r(e=>({...e,notice:null}))},[]),s=(0,_.useCallback)(n=>{let a=i.current;!a||a.apiBase!==e||t().then(async e=>{e===`superseded`&&i.current===a&&(e=await t()),i.current===a&&r(t=>t.apiBase===a.apiBase?{...t,notice:{context:a,loading:!1,failed:!n||e!==`applied`}}:t)}).catch(()=>{i.current===a&&r(e=>e.apiBase===a.apiBase?{...e,notice:{context:a,loading:!1,failed:!0}}:e)})},[e,t]);return{notice:n.apiBase===e?n.notice:null,open:a,close:o,modelsSettled:s}}function ad(e){let[t,n]=(0,_.useState)({epoch:0,force:!1}),r=(0,_.useRef)(0),i=(0,_.useRef)(!0),a=(0,_.useRef)(new Map),o=(0,_.useCallback)(()=>{for(let e of a.current.values())e.resolve(!1);a.current.clear()},[]);(0,_.useEffect)(()=>(i.current=!0,()=>{i.current=!1,o()}),[e,o]);let s=(0,_.useCallback)((e=!1)=>{o();let t=++r.current;return i.current&&n({epoch:t,force:e}),t},[o]),c=(0,_.useCallback)((e,t,n)=>{let r=a.current.get(e);!r||!i.current||(r[t]=n,r.accounts!==void 0&&r.report!==void 0&&(a.current.delete(e),r.resolve(r.accounts&&r.report)))},[]);return{quotaRefresh:t,invalidateProviderQuotas:s,settleQuotaRefresh:(0,_.useCallback)((e,t)=>c(t,`report`,e),[c]),beginQuotaRefresh:(0,_.useCallback)(e=>{if(!i.current)return Promise.resolve(!1);let t=s(!0),n=new Promise(n=>{a.current.set(t,{resolve:n,accounts:!e||void 0})});return e&&Promise.resolve().then(e).then(e=>c(t,`accounts`,e),()=>c(t,`accounts`,!1)),n},[c,s])}}function od(e,t,n){let r=(0,_.useRef)(n);(0,_.useLayoutEffect)(()=>{r.current=n});let i=(0,_.useRef)(()=>{});return(0,_.useEffect)(()=>{if(!t)return;let n=!1,a=null,o=250,s=null,c=()=>{a!==null&&window.clearTimeout(a),a=null},l=e=>{e.controller.abort(),e.reader?.cancel().catch(()=>{})},u=()=>{if(n||s)return;c();let t={controller:new AbortController,lastActivity:Date.now()};s=t,(async()=>{try{let i=await fetch(`${e}/api/accounts/events`,{signal:t.controller.signal,credentials:`same-origin`,headers:{Accept:`text/event-stream`}});if(!i.ok||!i.headers.get(`content-type`)?.includes(`text/event-stream`)||!i.body)throw Error(`Account selection stream unavailable`);if(n||t.controller.signal.aborted){await i.body.cancel();return}let a=i.body.getReader();t.reader=a,t.openedAt=Date.now();let o=new TextDecoder,s=new Map,c=new Map,l=!1,u=!1,d=()=>{u||(u=!0,Promise.resolve().then(async()=>{if(u=!1,n||t.controller.signal.aborted)return;let e=l?[void 0]:[...c.values()];l=!1,c.clear(),await Promise.all(e.map(e=>r.current(e)))}).catch(()=>{}))},f=``,p=``,m=[],h=0,g=()=>{let e;try{e=JSON.parse(m.join(`
|
|
80
80
|
`))}catch{return}if(!(!e||typeof e!=`object`||typeof e.revision!=`number`||!Number.isSafeInteger(e.revision)||e.revision<0)){if(p===`ready`)s.clear(),l=!0,d();else if(p===`account-selection`&&typeof e.provider==`string`&&e.provider&&(e.kind===`oauth`||e.kind===`api-key`)){let t=`${e.kind}:${e.provider}`;if(e.revision<=(s.get(t)??-1))return;s.set(t,e.revision),c.set(t,{provider:e.provider,kind:e.kind}),d()}}};for(;!n&&!t.controller.signal.aborted;){let e=await a.read();if(e.done)break;t.lastActivity=Date.now(),f+=o.decode(e.value,{stream:!0});let n;for(;(n=f.indexOf(`
|
|
81
|
-
`))!==-1;){let e=f.slice(0,n).replace(/\r$/,``);if(f=f.slice(n+1),h+=e.length,h>16384)throw Error(`Account selection event too large`);e?e.startsWith(`event:`)?p=e.slice(6).replace(/^ /,``):e.startsWith(`data:`)&&m.push(e.slice(5).replace(/^ /,``)):(g(),p=``,m=[],h=0)}if(f.length+h>16384)throw Error(`Account selection event too large`)}}catch{}finally{if(l(t),s===t&&(s=null,!n)){t.openedAt!==void 0&&Date.now()-t.openedAt>=1e4&&(o=250);let e=o;o=Math.min(o*2,5e3),a=window.setTimeout(()=>{a=null,u()},e)}}})()};return i.current=()=>{s&&Date.now()-s.lastActivity>6e4&&(l(s),s=null),u()},u(),()=>{n=!0,i.current=()=>{},c(),s&&l(s)}},[e,t]),(0,_.useCallback)(()=>i.current(),[])}function sd({apiBase:e}){let t=Q(),n=`ocx.providers.config.v1:${e}`,[r,i]=(0,_.useState)(()=>Tr(n)),[a,o]=(0,_.useState)(!1),[s,c]=(0,_.useState)(``),[l,u]=(0,_.useState)(!1),[d,f]=(0,_.useState)(`err`),[p,m]=(0,_.useState)(0),[h,g]=(0,_.useState)([]),[v,y]=(0,_.useState)({}),[b,x]=(0,_.useState)(null),[S,C]=(0,_.useState)(null),[w,T]=(0,_.useState)(null),[E,D]=(0,_.useState)(null),[O,k]=(0,_.useState)(null),[A,j]=(0,_.useState)(!1),[M,N]=(0,_.useState)(0),[P,F]=(0,_.useState)(null),[I,L]=(0,_.useState)({token:0,provider:null}),R=(0,_.useRef)(!0),z=(0,_.useRef)(null),B=(0,_.useRef)(!1),V=(0,_.useCallback)((e,t=!0)=>{c(e),u(t),f(t?`ok`:`err`),m(e=>e+1)},[]),H=(0,_.useCallback)(()=>{c(``),u(!1),f(`err`)},[]),U=(0,_.useCallback)(e=>{if(e.validationPending||e.catalogRefreshPending){c(t(e.validationPending?`pws.healthLabel.validationPending`:`codexAuth.catalogRefreshPending`)),u(!1),f(`warn`),m(e=>e+1);return}V(t(`codexAuth.accountAdded`),!0)},[V,t]);(0,_.useEffect)(()=>(R.current=!0,()=>{R.current=!1}),[]),(0,_.useEffect)(()=>{if(!s||!l)return;let e=window.setTimeout(H,4500);return()=>window.clearTimeout(e)},[s,l,p,H]);let W=(0,_.useCallback)(e=>{o(!1),D(null),T(e),L(t=>({token:t.token+1,provider:e}))},[]),G=K(`add-provider-presets:${e}`,[e],async t=>{let n=await fetch(`${e}/api/provider-presets`,{signal:t});if(!n.ok)throw Error(String(n.status));let r=await n.json();return Array.isArray(r.providers)&&r.providers.length>0?r.providers:null});K(qn(e),[e],async t=>{let n=await fetch(`${e}/api/usage?range=30d`,{signal:t});if(!n.ok)throw Error(String(n.status));return await n.json()},{deadlineMs:6e4});let{quotaRefresh:q,invalidateProviderQuotas:J,settleQuotaRefresh:X,beginQuotaRefresh:ee}=ad(e),{fetchConfig:te,fetchOauth:ne,fetchProviderQuotas:Z}=Iu({apiBase:e,t,setConfig:i,setOauthProviders:g,setOauthStatus:y,notify:V,invalidateProviderQuotas:J,configCacheKey:n}),re=(0,_.useCallback)(async()=>{await te()},[te]),ie=id(e,te),ae=ie.open,oe=(0,_.useCallback)(e=>{W(e),ae(e,!1)},[W,ae]),se=lc(e),ce=se.activeNeedsReauth,le=(0,_.useMemo)(()=>{let e=se.accounts;if(e.length===0&&se.loadState===`loading`)return v;let t=e.find(e=>e.isMain)??e[0],n=!!t&&!!t.email&&t.email!==`Codex App login`,r=e.some(e=>!e.isMain&&(e.hasCredential||e.email)),i=n||r,a=n?t?.email:e.find(e=>!e.isMain&&e.email)?.email??void 0;return{...v,openai:{loggedIn:i,...a?{email:a}:{},...ce?{needsReauth:!0}:{}}}},[v,se.accounts,se.loadState,ce]),{accountSets:de,setAccountSets:fe,accountLoadStates:pe,switchingAccount:me,keyPools:he,fetchAccountSets:ge,fetchKeyPools:_e,refreshAccountRosters:ve,oauthCardProviders:ye,keyCardProviders:be,switchAccount:xe,switchApiKey:Se,removeApiKey:Ce,addApiKeyValue:we,editCredentialAlias:Te,removeAccount:Ee,activeAccountNeedsReauth:De}=Cu({apiBase:e,t,config:r,oauthStatus:le,aliveRef:R,notify:V,fetchConfig:re,fetchOauth:ne,fetchProviderQuotas:Z,codexActiveNeedsReauth:ce}),Oe=(0,_.useCallback)(e=>e&&!(e.kind===`oauth`?ye:be).includes(e.provider)?Promise.resolve(!0):ve(e),[ve,ye,be]),ke=od(e,r!==null,Oe),Ae=JSON.stringify([e,ye.toSorted(),be.toSorted()]),je=(0,_.useRef)(null);K(`provider-rosters:${Ae}`,[Ae],async e=>je.current===Ae?(ke(),ve(void 0,e)):(je.current=Ae,!0),{enabled:r!==null,pollMs:3e4});let{draft:Me,setDraft:Ne,jsonEditorOpen:Pe,jsonSaving:Fe,jsonLeaveOpen:Ie,saveConfig:Le,openJsonEditor:Re,discardJsonEditor:ze,requestCloseJsonEditor:Be,restoreJsonEditor:Ve,jsonIsDirty:He,setJsonLeaveOpen:Ue}=Eu({apiBase:e,config:r,notify:V,fetchConfig:re,fetchProviderQuotas:Z,onSaved:e=>{e.length&&ie.open(e,!0),N(e=>e+1)},t}),We=(0,_.useCallback)(e=>{let t=r?.providers[e],n=t?.authMode,i=t&&vi(e,t)?()=>se.load(!0,{validatePending:!0}):n===`oauth`?()=>ge([e],!0):n===`forward`||n===`local`?void 0:()=>_e([e],!0);return ee(i)},[r,se,ge,_e,ee]),Ge=(0,_.useCallback)(()=>ee(),[ee]);(0,_.useEffect)(()=>{z.current!==e&&(z.current=e,Promise.resolve().then(()=>{re(),ne()}))},[e,re,ne]);let Ke=()=>N(e=>e+1),{cancelLoginOAuth:qe,loginOAuth:Je,logoutOAuth:Ye}=Mu({apiBase:e,t,aliveRef:R,accountSets:de,setAccountSets:fe,setBusy:x,setStatus:c,setLoginInfo:C,setOauthStatus:y,notify:V,fetchConfig:re,fetchOauth:ne,fetchAccountSets:ge,fetchProviderQuotas:Z,bumpModelsRefresh:Ke,onLoginSettled:oe}),{removeProvider:Xe,confirmRemoveProvider:Ze,setProviderDisabled:Qe,setDefaultProvider:$e,updateProvider:et}=Fu({apiBase:e,t,removeBusyRef:B,workspaceSelected:w,setWorkspaceSelected:T,setRemoveConfirmName:k,notify:V,fetchConfig:re,fetchOauth:ne,fetchProviderQuotas:Z,refreshCodexAccount:()=>se.load(!0)}),tt=(e,t=!1,n)=>{if(b!==e){if(pu(e)){F({provider:e,addAccount:t,...n?{accountId:n}:{}});return}Je(e,t,n)}};if(!r)return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`div`,{className:`page-head`,children:(0,Y.jsx)(`h2`,{children:t(`nav.providers`)})}),s?(0,Y.jsx)(Ot,{tone:d,onDismiss:H,dismissLabel:t(`common.close`),children:s}):(0,Y.jsxs)(`div`,{className:`providers-workspace providers-workspace--boot`,"aria-busy":`true`,children:[(0,Y.jsx)(`div`,{className:`providers-workspace-rail providers-workspace-rail--boot`,"aria-hidden":`true`}),(0,Y.jsx)(`div`,{className:`providers-workspace-main`,children:(0,Y.jsxs)(`p`,{className:`muted`,children:[(0,Y.jsx)(`span`,{className:`spin`,"aria-hidden":`true`}),` `,t(`prov.loadingConfig`)]})})]})]});let nt=nd(r,h,t),rt=rd(r,le),it=e=>r.providers[e]?.authMode===`forward`;return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{className:`page-head`,children:[(0,Y.jsx)(`h2`,{children:t(`nav.providers`)}),(0,Y.jsx)(`div`,{className:`row`,children:(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>o(!0),children:[(0,Y.jsx)(ue,{}),t(`prov.add`)]})})]}),s&&(0,Y.jsx)(Ot,{tone:d,onDismiss:H,dismissLabel:t(`common.close`),children:s}),(0,Y.jsx)($a,{onRemoveProvider:Xe,providers:r.providers,apiBase:e,defaultProvider:r.defaultProvider,selectedName:w,onSelect:T,onAddProvider:e=>{D(e??null),o(!0)},onEditConfig:Re,jsonEditor:{open:Pe,draft:Me,isDirty:He,onDraftChange:Ne,onSave:()=>Le(),onClose:Be,onRestore:Ve},jsonSaving:Fe,modelsRefreshToken:M,onModelsSettled:ie.modelsSettled,activeAccountNeedsReauth:De,quotaRefreshEpoch:q.epoch,quotaForceRefresh:q.force,onQuotaRefreshSettled:X,onRefreshAllQuotas:Ge,detail:(t,n)=>{let i=rt[t.name]??v[t.name];return(0,Y.jsx)(uu,{item:t,preset:co(t,G.data??[]),usageTotals:n.usageTotals,modelUsage:n.modelUsage,quotaReport:n.quotaReport,availableModels:n.availableModels,hasLiveModels:n.hasLiveModels,selectedModels:n.selectedModels,modelRows:n.modelRows,modelRevision:n.modelRevision,modelRowsReady:n.modelRowsReady,onOpenModels:()=>ht(`models`),modelsLoading:n.modelsLoading,modelsLoadFailed:n.modelsLoadFailed,onRetryModels:n.onRetryModels,oauthEmail:i?.email,onDeselect:()=>T(null),apiBase:e,oauth:i,accounts:de[t.name]?.accounts??[],keys:he[t.name]??[],accountLoadState:pe[t.name]??(t.authMode===`oauth`?`idle`:`ready`),accountsFocusToken:I.token,accountsFocusProvider:I.provider,switchingAccountId:me?.provider===t.name?me.accountId:null,busyProvider:b,loginHint:S,authHandlers:{onLogin:tt,onCancelLogin:qe,onLogout:Ye,onReauth:(e,t)=>tt(e,!0,t),onSwitchAccount:xe,onRemoveAccount:Ee,onRetryAccounts:async e=>{await ge([e])},onAddApiKey:we,onSwitchApiKey:Se,onRemoveApiKey:Ce,onEditAlias:Te,onRefreshQuota:We},onRefreshQuota:()=>We(t.name),isDefault:t.name===r.defaultProvider,onRemoveProvider:Xe,onSetDisabled:Qe,onSetDefault:e=>{$e(e)},onUpdateProvider:et,codexController:se},t.name)}}),(0,Y.jsx)(td,{apiBase:e,config:r,adding:a,modelsNotice:ie.notice?{provider:ie.notice.context.provider,initialRegistration:ie.notice.context.initialRegistration,catalogRefreshPending:ie.notice.context.catalogRefreshPending,loading:ie.notice.loading,failed:ie.notice.failed,providerKnown:ie.notice.context.providers.every(e=>!!r.providers[e]),selection:ie.notice.context.providers.length===1?r.providers[ie.notice.context.provider]?.initialModelSelection:ie.notice.context.providers.some(e=>r.providers[e]?.initialModelSelection?.status===`pending`)?{status:`pending`}:void 0,onClose:ie.close,onOpenModels:()=>{ie.close(),ht(`models`)},onRetry:()=>{let e=ie.notice.context;ie.open(e.providers,e.initialRegistration,e.catalogRefreshPending),Ke()}}:null,addIntent:E,busy:b,addModalAccountRows:nt,accountLoginStatus:rt,accountLoginHint:S,removeConfirmName:O,removeDefaultProvider:O===r.defaultProvider?Object.entries(r.providers).find(([e,t])=>e!==O&&t.disabled!==!0)?.[0]??null:null,codexLoginOpen:A,jsonLeaveOpen:Ie,jsonSaving:Fe,oauthTosPending:P,onCloseAdd:()=>{b&&qe(b),o(!1),D(null)},onAdded:e=>{o(!1),D(null),H(),ie.open(e,!r.providers[e]),re(),ne(),Z(!0),Ke()},onAccountLogin:async(n,i=!1)=>{if(n===`openai`){if(b===`openai`)return;let n=r.providers.openai,i=Kl(n);if(i===`invalid`){V(t(`codexAuth.openaiMissing`),!1);return}if(i===`absent`||i===`disabled`){x(`openai`);try{await $l(e,i),await re()}catch(e){e instanceof Ql?V(t(e.i18nKey),!1):V(e instanceof Error?e.message:t(`prov.saveFailed`),!1);return}finally{R.current&&x(e=>e===`openai`?null:e)}}j(!0);return}if(it(n)){j(!0);return}(r.providers[n]?.authMode===`oauth`||h.includes(n))&&tt(n,i)},onAccountCancelLogin:e=>{qe(e)},onAccountLogout:e=>{Ye(e)},onAccountManage:e=>{W(e)},onOpenAdd:ne,onCloseCodexLogin:()=>j(!1),onCodexAdded:e=>{j(!1),U(e),e.validationPending||ie.open(`openai`,!r.providers.openai,e.catalogRefreshPending),re(),ne(),Z(!0),Ke()},onCancelRemove:()=>k(null),onConfirmRemove:()=>{Ze(O)},onCancelJsonLeave:()=>{Fe||Ue(!1)},onDiscardJson:ze,onSaveJson:()=>{Le()},onCancelOauthTos:()=>F(null),onContinueOauthTos:()=>{let e=P;e&&(F(null),Je(e.provider,e.addAccount,e.accountId))}})]})}function cd(e){let{t}=ut();return e.state===`stale`?(0,Y.jsxs)(`div`,{className:`codex-stale-banner`,role:`status`,children:[(0,Y.jsx)(`span`,{className:`codex-stale-banner-text`,children:t(`models.staleBanner`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:e.controller.restarting,onClick:()=>{e.controller.restart()},children:e.controller.restarting?t(`dash.codexRestarting`):t(`dash.codexRestart`)})]}):null}function ld(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e.trim().length>0)}function ud(e){return e===null||e===`alphabetical`||e===`provider`||e===`most-used`}function dd(e){if(typeof e!=`object`||!e)return!1;let t=e;return ld(t.pickerOrder)&&ud(t.pickerOrderMode)}function fd(e){if(!dd(e))return!1;let t=e;return ld(t.pickerAvailable)&&(!(`chosen`in t)||Array.isArray(t.chosen)&&t.chosen.every(e=>typeof e==`string`))}function pd(e){return Array.isArray(e)&&e.every(e=>typeof e==`object`&&!!e&&typeof e.provider==`string`&&typeof e.model==`string`&&(e.resolvedModel===void 0||typeof e.resolvedModel==`string`)&&typeof e.requests==`number`&&Number.isFinite(e.requests)&&e.requests>=0)}function md(e){let t=e.indexOf(`/`);return t<0?[``,e]:[e.slice(0,t),e.slice(t+1)]}var hd=(e,t)=>e.localeCompare(t,`en`);function gd(e,t){let[n,r]=md(e),[i,a]=md(t);return hd(n,i)||hd(r,a)}function _d(e,t,n=[],r=[]){if(e==="default")return null;let i=[...new Set(t)];if(e===`alphabetical`)return i.sort((e,t)=>hd(md(e)[1],md(t)[1])||gd(e,t));if(e===`provider`)return i.sort(gd);let a=new Set(i),o=new Map,s=new Map;for(let e of r){if(!a.has(e.namespaced))continue;let t=JSON.stringify([e.provider,e.id]),n=o.get(t)??new Set;n.add(e.namespaced),o.set(t,n);let r=s.get(e.namespaced)??new Set;r.add(t),s.set(e.namespaced,r)}let c=e=>(s.get(e)?.size??0)>1?null:e,l=(e,t)=>{let n=o.get(JSON.stringify([e,t]));if(n)return n.size===1?c([...n][0]):null;if(t.startsWith(`${e}/`)&&a.has(t))return c(t);let r=`${e}/${t}`;return!t.includes(`/`)&&a.has(r)?c(r):void 0},u=new Map;for(let e of n){let t=l(e.provider,e.model);t&&u.set(t,(u.get(t)??0)+e.requests)}return i.sort((e,t)=>(u.get(t)??0)-(u.get(e)??0)||gd(e,t))}function vd(e,t,n){if(t.length===0)return`default`;if(t.some(e=>!e.includes(`/`)))return`custom`;if(n===`alphabetical`||n===`provider`||n===`most-used`)return n;let r=new Set(e);if(new Set(t).size!==t.length||t.length!==r.size||t.some(e=>!r.has(e)))return`custom`;for(let n of[`alphabetical`,`provider`]){let r=_d(n,e);if(r!==null&&r.length===t.length&&r.every((e,n)=>e===t[n]))return n}return`custom`}function yd(e,t,n){let r=new Set(t.filter(e=>e.includes(`/`))),i=e=>{if(r.has(e))return e;let t=new Set(n.filter(t=>r.has(t.namespaced)&&e===`${t.provider}/${t.id}`).map(e=>e.namespaced));return t.size===1?[...t][0]:void 0};return[...new Set(e.map(e=>i(e.trim())).filter(e=>e!==void 0))]}function bd(e,t,n){return JSON.stringify([e,t,n.pickerAvailable,n.chosen??null,n.pickerOrder,n.pickerOrderMode])}function xd(e,t){let n=new Set(e.filter(e=>e.includes(`/`))),r=new Map,i=new Map;for(let e of t){if(!n.has(e.namespaced))continue;let t=`${e.provider}/${e.id}`,a=r.get(e.namespaced)??new Set,o=i.get(t)??new Set;a.add(t),o.add(e.namespaced),r.set(e.namespaced,a),i.set(t,o)}return[...n].every(e=>{let t=r.get(e);return t?.size===1&&i.get([...t][0])?.size===1})}function Sd(e,t){if(e.chosen===void 0||e.pickerOrder.some(e=>!e.includes(`/`)))return null;let n=[...new Set(e.pickerAvailable.filter(e=>e.includes(`/`)))];if(!xd(n,t))return null;let r=new Map(e.chosen.map((e,t)=>[e,t])),i=new Map(t.map(e=>[e.namespaced,`${e.provider}/${e.id}`])),a=e=>r.get(e)??r.get(i.get(e)),o=n.filter(e=>a(e)!==void 0).sort((e,t)=>a(e)-a(t)),s=yd(e.pickerOrder,n,t);return{fixed:o,order:[...new Set([...o,...s,...n])]}}function Cd(e,t,n,r){let i=[...e];return t===n||r.includes(t)||r.includes(n)||!i.includes(t)||!i.includes(n)?i:(i.splice(i.indexOf(t),1),i.splice(i.indexOf(n),0,t),i)}function wd(e,t,n,r){let i=[...e],a=i.indexOf(t),o=a+n;return a<0||o<0||o>=i.length||r.includes(t)||r.includes(i[o])||([i[a],i[o]]=[i[o],i[a]]),i}var Td=`application/x-ocx-picker-order`,Ed=0;function Dd(){let e=++Ed;if(typeof crypto<`u`&&typeof crypto.randomUUID==`function`)try{return`${e}:${crypto.randomUUID()}`}catch{}return`picker-${Date.now().toString(36)}-${e}`}function Od({apiBase:e,active:t,identities:n,onAccepted:r,onBusyChange:i}){let a=Q(),[o,s]=(0,_.useState)(null),[c,l]=(0,_.useState)([]),[u,d]=(0,_.useState)(!1),[f,p]=(0,_.useState)(null),[m,h]=(0,_.useState)(!1),[g,v]=(0,_.useState)(``),[y,b]=(0,_.useState)(null),[x,S]=(0,_.useState)(null),C=(0,_.useRef)({generation:0,flight:null,drag:null}),[w,T]=(0,_.useState)({apiBase:e,active:t,onBusyChange:i}),E=JSON.stringify(n.map(({provider:e,id:t,namespaced:n})=>[e,t,n])),D=(0,_.useRef)(E);(0,_.useLayoutEffect)(()=>{D.current=E},[E]);let O=o!==null&&o.identities!==E,k=!t||u||!o||f!==null||O,A=o!==null&&JSON.stringify(c)!==JSON.stringify(o.order),j=(0,_.useCallback)(()=>{C.current.drag=null,b(null),S(null)},[]);(w.apiBase!==e||w.active!==t||w.onBusyChange!==i)&&(T({apiBase:e,active:t,onBusyChange:i}),s(null),l([]),p(null),h(!1),d(!1));let[M,N]=(0,_.useState)({disabled:k,snapshot:o,identitySignature:E});(M.disabled!==k||M.snapshot!==o||M.identitySignature!==E)&&(N({disabled:k,snapshot:o,identitySignature:E}),b(null),S(null)),(0,_.useLayoutEffect)(()=>{let e=C.current;return e.generation++,()=>{e.generation++,e.flight?.controller.abort(),e.flight?.clear(),e.flight=null,e.drag=null,i(!1)}},[e,t,i]),(0,_.useLayoutEffect)(()=>{C.current.drag=null},[k,o,E]);let P=async a=>{if(!t||C.current.flight||a&&(k||!A))return;let u=C.current.generation,f=Xn(15e3);C.current.flight=f,d(!0),i(!0),h(!1),j();let m=()=>C.current.generation===u&&C.current.flight===f,g=()=>m()&&!f.signal.aborted&&D.current===E;try{let t=await fetch(`${e}/api/subagent-models`,{signal:f.signal});if(!g())return;let i=await It(t);if(!g())return;if(!fd(i))throw Error(`Invalid picker settings`);let d=bd(e,u,i);if(a&&(!o||d!==o.signature||E!==o.identities)){p(`models.pickerOrder.changed`);return}let m=Sd(i,n);if(!m){p(i.pickerOrder.some(e=>!e.includes(`/`))?`models.pickerOrder.nativeLocked`:i.chosen===void 0?`models.pickerOrder.unknownChosen`:`models.pickerOrder.catalogRequired`);return}if(!a){s({...m,signature:d,identities:E}),l(m.order),p(null),v(``);return}let h=await fetch(`${e}/api/subagent-models`,{method:`PUT`,headers:{"Content-Type":`application/json`},signal:f.signal,body:JSON.stringify({pickerOrder:c,pickerOrderMode:null})});if(!g())return;let _=await It(h);if(!g())return;if(!dd(_)||!(`ok`in _)||_.ok!==!0)throw Error(`Invalid picker receipt`);l(_.pickerOrder),p(`models.pickerOrder.savedReload`),r({pickerOrder:_.pickerOrder,pickerOrderMode:_.pickerOrderMode,catalogRefresh:`catalogRefresh`in _?_.catalogRefresh:void 0})}catch{m()&&D.current===E&&h(!0)}finally{f.clear(),m()&&(C.current.flight=null,d(!1),i(!1))}},F=(0,_.useEffectEvent)(async()=>{let e=C.current,n=e.generation;await Promise.resolve(),t&&e.generation===n&&P(!1)});(0,_.useEffect)(()=>{t&&F()},[e,t,i]);let I=(e,t)=>{k||(l(t),v(a(`models.pickerOrder.position`,{model:e,position:t.indexOf(e)+1,total:t.length})),j())},L=new Set(c),R=new Set(o?.fixed),z=e=>!k&&L.has(e)&&!R.has(e),B=(e,t)=>{!C.current.drag||C.current.drag.id===t||!z(C.current.drag.id)||!z(t)||!e.dataTransfer.types.includes(Td)||(e.preventDefault(),e.dataTransfer.dropEffect=`move`,S(t))};return(0,Y.jsxs)(`section`,{className:`picker-order-editor`,"aria-label":a(`models.pickerOrder.custom`),"aria-busy":u,children:[(0,Y.jsx)(`p`,{className:`muted text-label`,children:a(`models.pickerOrder.editorHint`)}),(f||O)&&(0,Y.jsx)(`p`,{role:`alert`,children:a(f??`models.pickerOrder.changed`)}),m&&(0,Y.jsx)(`p`,{role:`alert`,children:a(`models.pickerOrder.requestFailed`)}),o&&c.length===0&&(0,Y.jsx)(`p`,{children:a(`models.pickerOrder.empty`)}),(0,Y.jsx)(`ol`,{className:`picker-order-list`,children:c.map((e,t)=>{let n=R.has(e);return(0,Y.jsxs)(`li`,{className:`picker-order-row${y===e?` cwi-target-row--dragging`:``}${x===e?` cwi-target-row--drop`:``}`,onDragOver:t=>B(t,e),onDragLeave:()=>S(null),onDrop:t=>{let n=C.current.drag;n&&n.id!==e&&n.token===t.dataTransfer.getData(Td)&&z(n.id)&&z(e)&&(t.preventDefault(),I(n.id,Cd(c,n.id,e,o?.fixed??[]))),j()},onDragEnd:j,children:[(0,Y.jsx)(`button`,{type:`button`,className:`cwi-target-grip`,disabled:k||n,draggable:!k&&!n,"aria-label":a(`models.pickerOrder.dragModel`,{model:e}),onDragStart:t=>{if(!z(e)){t.preventDefault();return}let n=Dd();C.current.drag={id:e,token:n},b(e),t.dataTransfer.effectAllowed=`move`,t.dataTransfer.setData(Td,n)},children:(0,Y.jsx)(Le,{width:14,height:14,"aria-hidden":`true`})}),(0,Y.jsx)(`code`,{className:`picker-order-name`,children:e}),n&&(0,Y.jsx)(`span`,{className:`muted text-caption`,children:a(`models.pickerOrder.featured`)}),(0,Y.jsxs)(`span`,{className:`picker-order-actions`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:k||n||t===0||R.has(c[t-1]),"aria-label":a(`models.pickerOrder.upModel`,{model:e}),onClick:()=>I(e,wd(c,e,-1,o?.fixed??[])),children:(0,Y.jsx)(be,{width:14,height:14,"aria-hidden":`true`})}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:k||n||t===c.length-1||R.has(c[t+1]),"aria-label":a(`models.pickerOrder.downModel`,{model:e}),onClick:()=>I(e,wd(c,e,1,o?.fixed??[])),children:(0,Y.jsx)(xe,{width:14,height:14,"aria-hidden":`true`})})]})]},e)})}),(0,Y.jsx)(`p`,{role:`status`,"aria-live":`polite`,children:g}),(0,Y.jsxs)(`div`,{className:`row`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:k||!A,onClick:()=>void P(!0),children:a(u?`models.pickerOrder.applying`:`models.pickerOrder.saveDraft`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:!t||u,onClick:()=>void P(!1),children:a(`models.pickerOrder.reloadDraft`)})]})]})}var kd={operator:`models.displayNameSourceOperator`,provider:`models.displayNameSourceProvider`,fallback:`models.displayNameSourceFallback`};function Ad({model:e,saving:t,requestError:n,currentNamePending:r=!1,mutationOutcomeUnknown:i=!1,onRetry:a,onEdit:o,onSave:s,onReset:c,onClose:l}){let u=Q(),d=(0,_.useRef)(null),f=(0,_.useRef)(null),p=(0,_.useRef)(null),m=(0,_.useRef)(t),h=(0,_.useId)(),g=(0,_.useId)(),v=(0,_.useId)(),[y,b]=(0,_.useState)(e),[x,S]=(0,_.useState)(e.displayNameOverride??``),[C,w]=(0,_.useState)(null);(0,_.useEffect)(()=>{let e=d.current;return e&&!e.open&&e.showModal(),f.current?.focus(),()=>{e?.open&&e.close()}},[]),(0,_.useEffect)(()=>{let e=m.current&&!t&&!!n;m.current=t,e&&(i?p.current?.focus():f.current?.focus())},[n,t,i]),y!==e&&(b(e),S(e.displayNameOverride??``),w(null));let T=C?u(C):null,E=T??n,D=e.displayNameSource?kd[e.displayNameSource]:`models.displayNameSourceFallback`,O=()=>{t||l()};return(0,Y.jsxs)(`dialog`,{ref:d,className:`modal-overlay`,"aria-labelledby":h,onCancel:e=>{e.preventDefault(),O()},children:[(0,Y.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":u(`common.close`),tabIndex:-1,disabled:t,onClick:O}),(0,Y.jsxs)(`form`,{className:`modal-card model-display-name-dialog`,role:`document`,onClick:e=>e.stopPropagation(),onSubmit:e=>{if(e.preventDefault(),t)return;if(a){a();return}if(i)return;let n=jo(x);w(n),n||s(x.trim())},children:[(0,Y.jsxs)(`div`,{className:`modal-head`,children:[(0,Y.jsx)(`h3`,{id:h,children:u(`models.displayNameTitle`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:t,onClick:O,children:u(`common.close`)})]}),(0,Y.jsxs)(`div`,{className:`model-display-name-identity`,children:[(0,Y.jsx)(`span`,{className:`muted text-label`,children:u(`models.displayNameModelId`)}),(0,Y.jsx)(`code`,{className:`mono text-control`,children:e.namespaced})]}),(0,Y.jsxs)(`div`,{className:`model-display-name-current`,children:[(0,Y.jsx)(`span`,{className:`muted text-label`,children:u(`models.displayNameCurrent`)}),(0,Y.jsx)(`strong`,{children:r?u(`models.displayNameCurrentUnavailable`):e.displayName??e.namespaced}),!r&&(0,Y.jsx)(`span`,{className:`models-chip muted text-caption`,children:u(D)})]}),(0,Y.jsx)(`label`,{className:`field-label`,htmlFor:`${h}-input`,children:u(`models.displayNameField`)}),(0,Y.jsx)(`input`,{ref:f,id:`${h}-input`,className:`input`,value:x,maxLength:129,placeholder:u(`models.displayNamePlaceholder`),"aria-describedby":`${g}${E?` ${v}`:``}`,"aria-invalid":T?!0:void 0,disabled:t||i,onChange:e=>{t||i||(o?.(),S(e.target.value),w(null))}}),(0,Y.jsx)(`p`,{id:g,className:`muted small`,children:u(`models.displayNameHelp`,{model:e.namespaced})}),E&&(0,Y.jsx)(`p`,{id:v,className:`model-display-name-error`,role:`alert`,children:E}),(0,Y.jsxs)(`div`,{className:`modal-actions`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:t||i||!e.displayNameOverride,onClick:()=>{!t&&!i&&c()},children:u(`models.displayNameReset`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:t,onClick:O,children:u(`common.cancel`)}),(0,Y.jsx)(`button`,{ref:p,type:`submit`,className:`btn btn-primary btn-sm`,disabled:t||i&&!a,children:u(t?`common.saving`:a?`common.retry`:`common.save`)})]})]})]})}var jd=[`input`,`output`,`cacheRead`,`cacheWrite`],Md={input:`pricing.override.input`,output:`pricing.override.output`,cacheRead:`pricing.override.cacheRead`,cacheWrite:`pricing.override.cacheWrite`},Nd=1e6,Pd=6e4,Fd={input:``,output:``,cacheRead:``,cacheWrite:``};function Id(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ld(e){return Id(e)&&jd.every(t=>typeof e[t]==`number`&&Number.isFinite(e[t])&&e[t]>=0&&e[t]<=Nd)}function Rd({model:e,apiBase:t,onRefresh:n,onClose:r}){let i=Q(),a=(0,_.useId)(),o=(0,_.useRef)(null),s=(0,_.useRef)(null),c=(0,_.useRef)(null),l=(0,_.useRef)(null),u=(0,_.useRef)(!1),[d,f]=(0,_.useState)(`loading`),[p,m]=(0,_.useState)(Fd),[h,g]=(0,_.useState)(!1),[v,y]=(0,_.useState)(null),[b,x]=(0,_.useState)(!1),S=`${t}/api/providers/${encodeURIComponent(e.provider)}/model-costs`,C=d===`saving`||d===`refreshing`,w=d!==`ready`,T=(0,_.useCallback)((t=!1)=>{if(l.current)return;let n=Xn(Pd);l.current=n,fetch(S,{signal:n.signal,cache:`no-store`}).then(async r=>{let i=await It(r);if(n.signal.throwIfAborted(),!Id(i)||i.provider!==e.provider||!Id(i.modelCosts))throw Error(`invalid model-costs response`);let a=Object.hasOwn(i.modelCosts,e.id)?i.modelCosts[e.id]:void 0;if(a!==void 0&&!Ld(a))throw Error(`invalid model cost`);l.current===n&&(m(a===void 0?Fd:{input:String(a.input),output:String(a.output),cacheRead:String(a.cacheRead),cacheWrite:String(a.cacheWrite)}),g(a!==void 0),x(t),f(`ready`))}).catch(()=>{l.current===n&&(f(t?`unknown`:`loadFailed`),y(t?`pricing.override.recoveryFailed`:`pricing.override.loadFailed`))}).finally(()=>{n.clear(),l.current===n&&(l.current=null)})},[S,e.id,e.provider]);(0,_.useEffect)(()=>{let e=o.current;return e&&!e.open&&e.showModal(),T(),()=>{l.current?.controller.abort(),l.current?.clear(),l.current=null,e?.open&&e.close()}},[T]),(0,_.useEffect)(()=>{d===`ready`?s.current?.focus():(d===`unknown`||d===`loadFailed`||d===`refreshFailed`)&&c.current?.focus()},[d]);let E=async t=>{if(l.current||(t===void 0?d!==`refreshFailed`:d!==`ready`))return;let i=Xn(Pd);l.current=i,f(t===void 0?`refreshing`:`saving`),u.current=!0,y(null);let a=t===void 0;try{if(t!==void 0){let n=await It(await fetch(S,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({modelId:e.id,cost:t}),signal:i.signal}));i.signal.throwIfAborted();let r=Id(n)?n.cost:void 0;if(!Id(n)||n.ok!==!0||n.provider!==e.provider||n.modelId!==e.id||(t===null?r!==null:!Ld(r)||!jd.every(e=>r[e]===t[e])))throw Error(`invalid model-costs receipt`);if(l.current!==i)return;a=!0,f(`refreshing`)}if(!await n(i.signal))throw Error(`catalog refresh failed`);i.signal.throwIfAborted(),l.current===i&&r()}catch{if(l.current!==i)return;f(a?`refreshFailed`:`unknown`),y(a?`pricing.override.refreshFailed`:`pricing.override.outcomeUnknown`)}finally{i.clear(),l.current===i&&(l.current=null,u.current=!1)}},D=()=>{u.current||r()};return(0,Y.jsxs)(`dialog`,{ref:o,className:`modal-overlay`,"aria-labelledby":`${a}-title`,onCancel:e=>{e.preventDefault(),D()},children:[(0,Y.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,tabIndex:-1,"aria-label":i(`pricing.override.close`),disabled:C,onClick:D}),(0,Y.jsxs)(`form`,{className:`modal-card model-display-name-dialog`,role:`document`,noValidate:!0,"aria-busy":d===`loading`||C,onClick:e=>e.stopPropagation(),onSubmit:e=>{if(e.preventDefault(),l.current)return;if(d===`unknown`||d===`loadFailed`){f(`loading`),y(null),T(d===`unknown`);return}if(d===`refreshFailed`){E(void 0);return}if(w)return;let t={input:Number(p.input),output:Number(p.output),cacheRead:Number(p.cacheRead),cacheWrite:Number(p.cacheWrite)};if([...e.currentTarget.querySelectorAll(`input`)].some(e=>e.validity.badInput)||!p.input.trim()||!p.output.trim()||!Ld(t)){y(`pricing.override.invalid`),s.current?.focus();return}E(t)},children:[(0,Y.jsxs)(`div`,{className:`modal-head`,children:[(0,Y.jsx)(`h3`,{id:`${a}-title`,children:i(`pricing.override.title`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:C,onClick:D,children:i(`pricing.override.close`)})]}),(0,Y.jsxs)(`div`,{className:`model-display-name-identity`,children:[(0,Y.jsx)(`span`,{className:`muted text-label`,children:i(`pricing.override.modelId`)}),(0,Y.jsx)(`code`,{className:`mono text-control`,children:e.namespaced})]}),(0,Y.jsx)(`p`,{id:`${a}-help`,className:`muted small`,children:i(`pricing.override.help`)}),d===`loading`&&(0,Y.jsx)(`p`,{role:`status`,className:`muted small`,children:i(`pricing.override.loading`)}),jd.map(e=>(0,Y.jsxs)(_.Fragment,{children:[(0,Y.jsx)(`label`,{className:`field-label`,htmlFor:`${a}-${e}`,children:i(Md[e])}),(0,Y.jsx)(`input`,{ref:e===`input`?s:void 0,id:`${a}-${e}`,className:`input`,type:`number`,min:0,max:Nd,step:`any`,inputMode:`decimal`,value:p[e],disabled:w,required:e===`input`||e===`output`,"aria-describedby":`${a}-help${v?` ${a}-error`:``}`,"aria-invalid":v===`pricing.override.invalid`||void 0,onChange:t=>{if(w||l.current)return;let n=t.target.value;m(t=>({...t,cacheRead:t.cacheRead||`0`,cacheWrite:t.cacheWrite||`0`,[e]:n})),y(null)}})]},e)),b&&(0,Y.jsx)(`p`,{role:`status`,className:`muted small`,children:i(`pricing.override.recovered`)}),v&&(0,Y.jsx)(`p`,{id:`${a}-error`,className:`model-display-name-error`,role:`alert`,children:i(v)}),(0,Y.jsxs)(`div`,{className:`modal-actions`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:w||!h,onClick:()=>void E(null),children:i(`pricing.override.reset`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:C,onClick:D,children:i(`pricing.override.cancel`)}),(0,Y.jsx)(`button`,{ref:c,type:`submit`,className:`btn btn-primary btn-sm`,disabled:d===`loading`||C,children:i(C?`pricing.override.saving`:d===`unknown`||d===`loadFailed`?`pricing.override.reload`:d===`refreshFailed`?`pricing.override.refresh`:`pricing.override.save`)})]})]})]})}var zd=[`fresh`,`stale`,`not_running`,`unknown`],Bd=[`stopped`,`nothing_running`,`enumeration_unavailable`,`partially_stopped`];function Vd(e){return Array.isArray(e)&&e.every(e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>0)}function Hd(e){if(typeof e!=`object`||!e)return!1;let t=e;if(!(typeof t.success==`boolean`&&typeof t.synced==`boolean`&&typeof t.stateBefore==`string`&&zd.includes(t.stateBefore)&&typeof t.code==`string`&&Bd.includes(t.code)&&Vd(t.requested)&&Vd(t.stopped)&&Vd(t.surviving)&&Vd(t.failed)))return!1;let n=t.success,r=t.code,i=t.surviving,a=t.failed,o=t.stopped;return!(n!==(r!==`partially_stopped`)||n&&(i.length>0||a.length>0)||!n&&i.length===0&&a.length===0||(r===`nothing_running`||r===`enumeration_unavailable`)&&o.length>0)}function Ud(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.state==`string`&&zd.includes(t.state)&&typeof t.runningCount==`number`&&Number.isSafeInteger(t.runningCount)&&t.runningCount>=0}var Wd={state:null,runningCount:0};async function Gd(e,t={}){let n=t.fetchFn??fetch;try{let r=await n(`${e}/api/system/codex-app-server`,{signal:t.signal});if(!r.ok)return Wd;let i=await r.json().catch(()=>null);return Ud(i)?{state:i.state,runningCount:i.runningCount}:Wd}catch{return Wd}}var Kd=3e4;function qd(e){return(e instanceof DOMException||e instanceof Error)&&(e.name===`AbortError`||e.name===`TimeoutError`)}async function Jd(e,t={}){let{fetchFn:n=fetch,timeoutMs:r=Kd,formatFailure:i=e=>`Failed to restart Codex (HTTP ${e}).`,formatUnreachable:a=()=>`Could not reach the proxy.`,formatMalformed:o=()=>`The proxy returned an unexpected response.`,formatTimeout:s=()=>`The proxy did not answer in time. It may still be working.`}=t,c;try{c=await n(`${e}/api/system/codex-restart`,{method:`POST`,signal:AbortSignal.timeout(r)})}catch(e){return{ok:!1,message:qd(e)?s():a()}}if(!c.ok)return{ok:!1,message:i(c.status)};let l;try{l=await c.json()}catch(e){return{ok:!1,message:qd(e)?s():o()}}return Hd(l)?{ok:!0,result:l}:{ok:!1,message:o()}}function Yd(e){return e===`stopped`||e===`nothing_running`}function Xd(e,t={}){let{t:n}=ut(),[r,i]=(0,_.useState)(!1),a=(0,_.useRef)(!0),o=(0,_.useRef)(t.onSettled);return(0,_.useEffect)(()=>{o.current=t.onSettled},[t.onSettled]),(0,_.useEffect)(()=>(a.current=!0,()=>{a.current=!1}),[]),{restarting:r,restart:(0,_.useCallback)(async()=>{if(!confirm(n(`dash.codexRestartConfirm`)))return null;i(!0);let t=await Jd(e,{formatFailure:e=>n(`dash.codexRestartFailed`,{status:String(e)}),formatUnreachable:()=>n(`dash.codexRestartUnreachable`),formatTimeout:()=>n(`dash.codexRestartTimeout`),formatMalformed:()=>n(`dash.codexRestartMalformed`)});if(a.current&&i(!1),!t.ok||!t.result)return alert(t.message),null;let r=t.result;return r.code===`stopped`?alert(n(`dash.codexRestartDone`,{count:String(r.stopped.length)})):r.code===`nothing_running`?alert(n(`dash.codexRestartNothing`)):r.code===`enumeration_unavailable`?alert(n(`dash.codexRestartUnknown`)):alert(n(`dash.codexRestartPartial`,{count:String(r.surviving.length)})),a.current&&Yd(r.code)&&o.current?.(r.code),r.code},[e,n])}}var Zd={"gpt-5.6-sol":Me,"gpt-5.6-terra":Fe,"gpt-5.6-luna":Ne,"gpt-daybreak-blue-latest":Me,"daybreak-blue-latest":Me,"daybreak-red-latest":ke},Qd={width:14,height:14,flexShrink:0,verticalAlign:`text-bottom`};function $d(e){return e.slice(e.lastIndexOf(`/`)+1)}function ef(e){return Zd[e]??Zd[$d(e)]??null}function tf(e){let t=ef(e);return t?(0,_.createElement)(`span`,{className:`model-label`},(0,_.createElement)(t,{style:Qd,"aria-hidden":!0}),e):e}var nf=new Set([`absent`,`current`,`stale`,`conflict`,`unsafe`]),rf=new Set([`unparseable`,`not-regular-file`,`foreign-edit`,`unowned-key`,`blocked-container`,`unresolvable-path`]);function af(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function of(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function sf(e){if(!af(e)||e.clientId!==`aside`||!of(e.profileId)||typeof e.current!=`boolean`||typeof e.enabled!=`boolean`||!nf.has(e.state)||typeof e.installed!=`boolean`||typeof e.configPath!=`string`||!Number.isSafeInteger(e.snapshotCount)||e.snapshotCount<-1||typeof e.retentionDegraded!=`boolean`||e.reason!==void 0&&!rf.has(e.reason))return null;for(let t of[`name`,`error`,`appliedAt`,`lastOpId`])if(e[t]!==void 0&&typeof e[t]!=`string`)return null;return{clientId:`aside`,profileId:e.profileId,current:e.current,enabled:e.enabled,state:e.state,installed:e.installed,configPath:e.configPath,snapshotCount:e.snapshotCount,retentionDegraded:e.retentionDegraded,...typeof e.name==`string`?{name:e.name}:{},...typeof e.error==`string`?{error:e.error}:{},...typeof e.appliedAt==`string`?{appliedAt:e.appliedAt}:{},...typeof e.lastOpId==`string`?{lastOpId:e.lastOpId}:{},...e.reason===void 0?{}:{reason:e.reason}}}function cf(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!af(n)||!of(n.profileId)||typeof n.ok!=`boolean`||n.state!==void 0&&!nf.has(n.state)||n.residual!==void 0&&typeof n.residual!=`boolean`)return null;for(let e of[`reason`,`refusalReason`,`message`,`snapshotPath`])if(n[e]!==void 0&&typeof n[e]!=`string`)return null;t.push({profileId:n.profileId,ok:n.ok,...n.state===void 0?{}:{state:n.state},...typeof n.reason==`string`?{reason:n.reason}:{},...typeof n.refusalReason==`string`?{refusalReason:n.refusalReason}:{},...typeof n.message==`string`?{message:n.message}:{},...typeof n.snapshotPath==`string`?{snapshotPath:n.snapshotPath}:{},...typeof n.residual==`boolean`?{residual:n.residual}:{}})}return t}var lf=[`opencode`,`pi`,`omp`,`hermes`,`openclaw`,`kimi`,`gajae`,`dsh`,`mcode`,`zcode`,`prime`,`aside`,`raycast`,`omo`,`cline`],uf=new Set([`not_installed`,`conflict`,`unsafe`,`non_loopback`,`drift_requires_confirm`,`snapshot_expired`,`write_failed`]),df=new Set([`integration_unsafe`,`integration_conflict`,`integration_drift_confirmation_required`,`integration_snapshot_expired`,`integration_mutation_failed`]),ff=new Set([`absent`,`current`,`stale`,`conflict`,`unsafe`]);function pf(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function mf(e){return!pf(e)||!uf.has(String(e.reason))?!1:typeof e.error==`string`&&df.has(String(e.code))&&lf.includes(e.clientId)&&ff.has(String(e.state))&&typeof e.message==`string`}var hf=class extends Error{refusal;status;body;constructor(e,t){let n=mf(t)?t:null;super(n?.message??t.error??t.message??String(e)),this.name=`IntegrationApiError`,this.status=e,this.body=t,this.refusal=n}};function gf(e){return e instanceof hf&&e.status===404&&e.body.code===`integration_operation_not_found`}async function _f(e){try{let t=await e.json();return pf(t)?t:{}}catch{return{}}}async function vf(e){if(!e.ok)throw new hf(e.status,await _f(e));let t=await Lt(e);if(t==null)throw new hf(e.status,{});return t}function yf(e){if(!Number.isSafeInteger(e)||e<0)throw new hf(400,{code:`invalid_aside_profile`});return`/api/client-integrations/aside/profiles/${e}`}function bf(e,t){if(t!==void 0){if(e!==`aside`)throw new hf(400,{code:`invalid_aside_profile`});return yf(t)}return e===`aside`?`/api/client-integrations/aside/profiles`:`/api/client-integrations/${encodeURIComponent(e)}`}async function xf(e,t){return vf(await fetch(`${e}/api/client-integrations`,{signal:t}))}async function Sf(e,t,n,r){let i=await vf(await fetch(`${e}${bf(t,r)}`,{signal:n}));if(r!==void 0){let e=sf(i);if(!e||e.profileId!==r)throw new hf(502,{code:`invalid_aside_profile_response`});return e}return i}async function Cf(e,t,n,r){if(r!==void 0&&t!==`aside`)throw new hf(400,{code:`invalid_aside_profile`});let i=t===`aside`?`${bf(t,r)}/journal`:`/api/client-integrations/journal${t?`?client=${encodeURIComponent(t)}`:``}`,a=await vf(await fetch(`${e}${i}`,{signal:n}));if(r!==void 0&&(!Array.isArray(a.operations)||a.operations.some(e=>e.clientId!==`aside`||e.profileId!==r)))throw new hf(502,{code:`invalid_aside_profile_response`});return a}async function wf(e,t,n,r,i,a){let o=await vf(await fetch(`${e}${bf(t,a)}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(i===!0?{enabled:n,overwriteConflict:!0}:{enabled:n}),signal:r})),s=o.results===void 0?void 0:cf(o.results);if(t===`aside`&&o.results!==void 0&&(!s||o.ok!==s.every(e=>e.ok)))throw new hf(502,{code:`invalid_aside_profile_response`});if(o.ok!==!0)throw new hf(207,{code:t===`aside`?`aside_profile_partial`:`integration_mutation_failed`,message:o.message,results:s??void 0});if(a!==void 0&&o.profileId!==a)throw new hf(502,{code:`invalid_aside_profile_response`});return{...o,...s?{results:s}:{}}}async function Tf(e,t,n=!1,r,i){let a=await vf(await fetch(`${e}${i===void 0?`/api/client-integrations/restore`:`${yf(i)}/restore`}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({opId:t,confirmDrift:n}),signal:r}));if(i!==void 0&&a.profileId!==i)throw new hf(502,{code:`invalid_aside_profile_response`});return a}async function Ef(e,t,n,r){let i=await vf(await fetch(`${e}${r===void 0?`/api/client-integrations/journal`:`${yf(r)}/journal`}?opId=${encodeURIComponent(t)}`,{method:`DELETE`,signal:n}));if(r!==void 0&&i.profileId!==r)throw new hf(502,{code:`invalid_aside_profile_response`});return i}async function Df(e){try{let t=await e;return t.ok?await Lt(t)??null:null}catch{return null}}async function Of(e,t){let n=await Df(fetch(`${e}/api/startup-health`,{signal:t}));return n?{routingInjected:n.routingInjected===!0,status:typeof n.status==`string`?n.status:void 0,recommendedCommand:typeof n.recommendedCommand==`string`?n.recommendedCommand:null}:null}async function kf(e,t){let n=await fetch(`${e}/api/keys`,{signal:t});if(!n.ok)throw Error(`/api/keys responded ${n.status}`);let r=await Lt(n);if(!r||!Array.isArray(r.keys))throw Error(`/api/keys returned an unexpected body`);return r.keys.length}async function Af(e,t){let n=await Df(fetch(`${e}/api/claude-code`,{signal:t}));return n?{enabled:n.enabled===!0,authMode:typeof n.authMode==`string`?n.authMode:void 0}:null}async function jf(e,t){let n=await Df(fetch(`${e}/api/claude-desktop/status`,{signal:t}));return!n||typeof n.desiredEnabled!=`boolean`||typeof n.installed!=`boolean`||typeof n.observedKind!=`string`?null:{desiredEnabled:n.desiredEnabled,installed:n.installed,observedKind:n.observedKind,applied:n.applied===!0,stale:n.stale===!0,drift:n.drift===!0,driftReason:typeof n.driftReason==`string`?n.driftReason:null,activeProfile:typeof n.activeProfile==`boolean`?n.activeProfile:null,appliedAt:typeof n.appliedAt==`string`?n.appliedAt:null}}async function Mf(e,t){let n=await Df(fetch(`${e}/api/grok`,{signal:t}));return n?{present:n.present===!0,models:Array.isArray(n.models)?n.models:[]}:null}var Nf=new Set([`claude`,`grok`,`codex`,`claude-desktop`]),Pf=new Set([`native_integration_refused`,`native_integration_failed`]),Ff=new Set([`not_installed`,`orphaned_marker`,`home_mismatch`,`config_busy`,`write_failed`,`metadata_unreadable`,`cleanup_incomplete`,`desired_state_changed`]);function If(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Lf(e){return If(e)?typeof e.error==`string`&&Pf.has(String(e.code))&&Nf.has(String(e.clientId))&&Ff.has(String(e.reason))&&typeof e.message==`string`:!1}var Rf=class extends Error{refusal;status;body;constructor(e,t){let n=Lf(t)?t:null;super(n?.message??t.error??t.message??String(e)),this.name=`NativeApiError`,this.status=e,this.body=t,this.refusal=n}};async function zf(e){try{let t=await e;return t.ok?await Lt(t)??null:null}catch{return null}}async function Bf(e){try{let t=await e.json();return If(t)?t:{}}catch{return{}}}async function Vf(e){if(!e.ok)throw new Rf(e.status,await Bf(e));let t=await Lt(e);if(t==null)throw new Rf(e.status,{});return t}function Hf(e,t){return zf(fetch(`${e}/api/native-integrations`,{signal:t}))}async function Uf(e,t,n,r){return Vf(await fetch(`${e}/api/native-integrations/${encodeURIComponent(t)}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({enabled:n}),signal:r}))}var Wf={integration_mutation_busy:`integrations.error.busy`,integration_journal_newest_protected:`integrations.rollback.deleteNewest`,integration_operation_not_found:`integrations.rollback.deleteGone`,aside_profile_partial:`integrations.aside.partial`,invalid_aside_profile_response:`integrations.aside.loadError`};function Gf(e){return e instanceof hf?e.refusal:null}function Kf(e){return e instanceof Rf?e.refusal:null}function qf(e){return e===`conflict`?`integrations.error.conflict`:e===`unsafe`?`integrations.error.unsafe`:e===`non_loopback`?`integrations.error.nonLoopback`:`integrations.error.generic`}var Jf=new Set([`non_loopback`]);function Yf(e,t,n){return t.reason===`orphaned_marker`?e(`integrations.native.error.orphanedMarker`,{path:n??``}):t.reason===`home_mismatch`?`${e(`integrations.native.error.homeMismatch`)} ${t.message}`:t.reason===`not_installed`?e(`integrations.native.error.notInstalled`):t.reason===`config_busy`?e(`integrations.native.error.configBusy`):t.reason===`metadata_unreadable`?e(`integrations.native.error.desktopUnsafeMetadata`,{path:n??``}):t.reason===`cleanup_incomplete`?e(`integrations.native.error.desktopCleanupIncomplete`,{paths:(t.residualPaths??[]).join(`, `)}):t.message||e(`integrations.error.generic`)}function Xf(e,t,n,r){let i=Kf(t);if(i)return Yf(e,i,r);let a=Gf(t);if(!a){if(t instanceof hf&&`results`in t.body&&t.body.results?.length){let n=t.body.results.filter(e=>!e.ok).map(t=>{let n=Zf(e,t);return`${e(`integrations.aside.profile`,{id:String(t.profileId)})}: ${n}`});return[e(`integrations.aside.partial`),...n].join(`
|
|
81
|
+
`))!==-1;){let e=f.slice(0,n).replace(/\r$/,``);if(f=f.slice(n+1),h+=e.length,h>16384)throw Error(`Account selection event too large`);e?e.startsWith(`event:`)?p=e.slice(6).replace(/^ /,``):e.startsWith(`data:`)&&m.push(e.slice(5).replace(/^ /,``)):(g(),p=``,m=[],h=0)}if(f.length+h>16384)throw Error(`Account selection event too large`)}}catch{}finally{if(l(t),s===t&&(s=null,!n)){t.openedAt!==void 0&&Date.now()-t.openedAt>=1e4&&(o=250);let e=o;o=Math.min(o*2,5e3),a=window.setTimeout(()=>{a=null,u()},e)}}})()};return i.current=()=>{s&&Date.now()-s.lastActivity>6e4&&(l(s),s=null),u()},u(),()=>{n=!0,i.current=()=>{},c(),s&&l(s)}},[e,t]),(0,_.useCallback)(()=>i.current(),[])}function sd({apiBase:e}){let t=Q(),n=`ocx.providers.config.v1:${e}`,[r,i]=(0,_.useState)(()=>Tr(n)),[a,o]=(0,_.useState)(!1),[s,c]=(0,_.useState)(``),[l,u]=(0,_.useState)(!1),[d,f]=(0,_.useState)(`err`),[p,m]=(0,_.useState)(0),[h,g]=(0,_.useState)([]),[v,y]=(0,_.useState)({}),[b,x]=(0,_.useState)(null),[S,C]=(0,_.useState)(null),[w,T]=(0,_.useState)(null),[E,D]=(0,_.useState)(null),[O,k]=(0,_.useState)(null),[A,j]=(0,_.useState)(!1),[M,N]=(0,_.useState)(0),[P,F]=(0,_.useState)(null),[I,L]=(0,_.useState)({token:0,provider:null}),R=(0,_.useRef)(!0),z=(0,_.useRef)(null),B=(0,_.useRef)(!1),V=(0,_.useCallback)((e,t=!0)=>{c(e),u(t),f(t?`ok`:`err`),m(e=>e+1)},[]),H=(0,_.useCallback)(()=>{c(``),u(!1),f(`err`)},[]),U=(0,_.useCallback)(e=>{if(e.validationPending||e.catalogRefreshPending){c(t(e.validationPending?`pws.healthLabel.validationPending`:`codexAuth.catalogRefreshPending`)),u(!1),f(`warn`),m(e=>e+1);return}V(t(`codexAuth.accountAdded`),!0)},[V,t]);(0,_.useEffect)(()=>(R.current=!0,()=>{R.current=!1}),[]),(0,_.useEffect)(()=>{if(!s||!l)return;let e=window.setTimeout(H,4500);return()=>window.clearTimeout(e)},[s,l,p,H]);let W=(0,_.useCallback)(e=>{o(!1),D(null),T(e),L(t=>({token:t.token+1,provider:e}))},[]),G=K(`add-provider-presets:${e}`,[e],async t=>{let n=await fetch(`${e}/api/provider-presets`,{signal:t});if(!n.ok)throw Error(String(n.status));let r=await n.json();return Array.isArray(r.providers)&&r.providers.length>0?r.providers:null});K(qn(e),[e],async t=>{let n=await fetch(`${e}/api/usage?range=30d`,{signal:t});if(!n.ok)throw Error(String(n.status));return await n.json()},{deadlineMs:6e4});let{quotaRefresh:q,invalidateProviderQuotas:J,settleQuotaRefresh:X,beginQuotaRefresh:ee}=ad(e),{fetchConfig:te,fetchOauth:ne,fetchProviderQuotas:Z}=Iu({apiBase:e,t,setConfig:i,setOauthProviders:g,setOauthStatus:y,notify:V,invalidateProviderQuotas:J,configCacheKey:n}),re=(0,_.useCallback)(async()=>{await te()},[te]),ie=id(e,te),ae=ie.open,oe=(0,_.useCallback)(e=>{W(e),ae(e,!1)},[W,ae]),se=lc(e),ce=se.activeNeedsReauth,le=(0,_.useMemo)(()=>{let e=se.accounts;if(e.length===0&&se.loadState===`loading`)return v;let t=e.find(e=>e.isMain)??e[0],n=!!t&&!!t.email&&t.email!==`Codex App login`,r=e.some(e=>!e.isMain&&(e.hasCredential||e.email)),i=n||r,a=n?t?.email:e.find(e=>!e.isMain&&e.email)?.email??void 0;return{...v,openai:{loggedIn:i,...a?{email:a}:{},...ce?{needsReauth:!0}:{}}}},[v,se.accounts,se.loadState,ce]),{accountSets:de,setAccountSets:fe,accountLoadStates:pe,switchingAccount:me,keyPools:he,fetchAccountSets:ge,fetchKeyPools:_e,refreshAccountRosters:ve,oauthCardProviders:ye,keyCardProviders:be,switchAccount:xe,switchApiKey:Se,removeApiKey:Ce,addApiKeyValue:we,editCredentialAlias:Te,removeAccount:Ee,activeAccountNeedsReauth:De}=Cu({apiBase:e,t,config:r,oauthStatus:le,aliveRef:R,notify:V,fetchConfig:re,fetchOauth:ne,fetchProviderQuotas:Z,codexActiveNeedsReauth:ce}),Oe=(0,_.useCallback)(e=>e&&!(e.kind===`oauth`?ye:be).includes(e.provider)?Promise.resolve(!0):ve(e),[ve,ye,be]),ke=od(e,r!==null,Oe),Ae=JSON.stringify([e,ye.toSorted(),be.toSorted()]),je=(0,_.useRef)(null);K(`provider-rosters:${Ae}`,[Ae],async e=>je.current===Ae?(ke(),ve(void 0,e)):(je.current=Ae,!0),{enabled:r!==null,pollMs:3e4});let{draft:Me,setDraft:Ne,jsonEditorOpen:Pe,jsonSaving:Fe,jsonLeaveOpen:Ie,saveConfig:Le,openJsonEditor:Re,discardJsonEditor:ze,requestCloseJsonEditor:Be,restoreJsonEditor:Ve,jsonIsDirty:He,setJsonLeaveOpen:Ue}=Eu({apiBase:e,config:r,notify:V,fetchConfig:re,fetchProviderQuotas:Z,onSaved:e=>{e.length&&ie.open(e,!0),N(e=>e+1)},t}),We=(0,_.useCallback)(e=>{let t=r?.providers[e],n=t?.authMode,i=t&&vi(e,t)?()=>se.load(!0,{validatePending:!0}):n===`oauth`?()=>ge([e],!0):n===`forward`||n===`local`?void 0:()=>_e([e],!0);return ee(i)},[r,se,ge,_e,ee]),Ge=(0,_.useCallback)(()=>ee(),[ee]);(0,_.useEffect)(()=>{z.current!==e&&(z.current=e,Promise.resolve().then(()=>{re(),ne()}))},[e,re,ne]);let Ke=()=>N(e=>e+1),{cancelLoginOAuth:qe,loginOAuth:Je,logoutOAuth:Ye}=Mu({apiBase:e,t,aliveRef:R,accountSets:de,setAccountSets:fe,setBusy:x,setStatus:c,setLoginInfo:C,setOauthStatus:y,notify:V,fetchConfig:re,fetchOauth:ne,fetchAccountSets:ge,fetchProviderQuotas:Z,bumpModelsRefresh:Ke,onLoginSettled:oe}),{removeProvider:Xe,confirmRemoveProvider:Ze,setProviderDisabled:Qe,setDefaultProvider:$e,updateProvider:et}=Fu({apiBase:e,t,removeBusyRef:B,workspaceSelected:w,setWorkspaceSelected:T,setRemoveConfirmName:k,notify:V,fetchConfig:re,fetchOauth:ne,fetchProviderQuotas:Z,refreshCodexAccount:()=>se.load(!0)}),tt=(e,t=!1,n)=>{if(b!==e){if(pu(e)){F({provider:e,addAccount:t,...n?{accountId:n}:{}});return}Je(e,t,n)}};if(!r)return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`div`,{className:`page-head`,children:(0,Y.jsx)(`h2`,{children:t(`nav.providers`)})}),s?(0,Y.jsx)(Ot,{tone:d,onDismiss:H,dismissLabel:t(`common.close`),children:s}):(0,Y.jsxs)(`div`,{className:`providers-workspace providers-workspace--boot`,"aria-busy":`true`,children:[(0,Y.jsx)(`div`,{className:`providers-workspace-rail providers-workspace-rail--boot`,"aria-hidden":`true`}),(0,Y.jsx)(`div`,{className:`providers-workspace-main`,children:(0,Y.jsxs)(`p`,{className:`muted`,children:[(0,Y.jsx)(`span`,{className:`spin`,"aria-hidden":`true`}),` `,t(`prov.loadingConfig`)]})})]})]});let nt=nd(r,h,t),rt=rd(r,le),it=e=>r.providers[e]?.authMode===`forward`;return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{className:`page-head`,children:[(0,Y.jsx)(`h2`,{children:t(`nav.providers`)}),(0,Y.jsx)(`div`,{className:`row`,children:(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>o(!0),children:[(0,Y.jsx)(ue,{}),t(`prov.add`)]})})]}),s&&(0,Y.jsx)(Ot,{tone:d,onDismiss:H,dismissLabel:t(`common.close`),children:s}),(0,Y.jsx)($a,{onRemoveProvider:Xe,providers:r.providers,apiBase:e,defaultProvider:r.defaultProvider,selectedName:w,onSelect:T,onAddProvider:e=>{D(e??null),o(!0)},onEditConfig:Re,jsonEditor:{open:Pe,draft:Me,isDirty:He,onDraftChange:Ne,onSave:()=>Le(),onClose:Be,onRestore:Ve},jsonSaving:Fe,modelsRefreshToken:M,onModelsSettled:ie.modelsSettled,activeAccountNeedsReauth:De,quotaRefreshEpoch:q.epoch,quotaForceRefresh:q.force,onQuotaRefreshSettled:X,onRefreshAllQuotas:Ge,detail:(t,n)=>{let i=rt[t.name]??v[t.name];return(0,Y.jsx)(uu,{item:t,preset:co(t,G.data??[]),usageTotals:n.usageTotals,modelUsage:n.modelUsage,quotaReport:n.quotaReport,availableModels:n.availableModels,hasLiveModels:n.hasLiveModels,selectedModels:n.selectedModels,modelRows:n.modelRows,modelRevision:n.modelRevision,modelRowsReady:n.modelRowsReady,onOpenModels:()=>ht(`models`),modelsLoading:n.modelsLoading,modelsLoadFailed:n.modelsLoadFailed,onRetryModels:n.onRetryModels,oauthEmail:i?.email,onDeselect:()=>T(null),apiBase:e,oauth:i,accounts:de[t.name]?.accounts??[],keys:he[t.name]??[],accountLoadState:pe[t.name]??(t.authMode===`oauth`?`idle`:`ready`),accountsFocusToken:I.token,accountsFocusProvider:I.provider,switchingAccountId:me?.provider===t.name?me.accountId:null,busyProvider:b,loginHint:S,authHandlers:{onLogin:tt,onCancelLogin:qe,onLogout:Ye,onReauth:(e,t)=>tt(e,!0,t),onSwitchAccount:xe,onRemoveAccount:Ee,onRetryAccounts:async e=>{await ge([e])},onAddApiKey:we,onSwitchApiKey:Se,onRemoveApiKey:Ce,onEditAlias:Te,onRefreshQuota:We},onRefreshQuota:()=>We(t.name),isDefault:t.name===r.defaultProvider,onRemoveProvider:Xe,onSetDisabled:Qe,onSetDefault:e=>{$e(e)},onUpdateProvider:et,codexController:se},t.name)}}),(0,Y.jsx)(td,{apiBase:e,config:r,adding:a,modelsNotice:ie.notice?{provider:ie.notice.context.provider,initialRegistration:ie.notice.context.initialRegistration,catalogRefreshPending:ie.notice.context.catalogRefreshPending,loading:ie.notice.loading,failed:ie.notice.failed,providerKnown:ie.notice.context.providers.every(e=>!!r.providers[e]),selection:ie.notice.context.providers.length===1?r.providers[ie.notice.context.provider]?.initialModelSelection:ie.notice.context.providers.some(e=>r.providers[e]?.initialModelSelection?.status===`pending`)?{status:`pending`}:void 0,onClose:ie.close,onOpenModels:()=>{ie.close(),ht(`models`)},onRetry:()=>{let e=ie.notice.context;ie.open(e.providers,e.initialRegistration,e.catalogRefreshPending),Ke()}}:null,addIntent:E,busy:b,addModalAccountRows:nt,accountLoginStatus:rt,accountLoginHint:S,removeConfirmName:O,removeDefaultProvider:O===r.defaultProvider?Object.entries(r.providers).find(([e,t])=>e!==O&&t.disabled!==!0)?.[0]??null:null,codexLoginOpen:A,jsonLeaveOpen:Ie,jsonSaving:Fe,oauthTosPending:P,onCloseAdd:()=>{b&&qe(b),o(!1),D(null)},onAdded:e=>{o(!1),D(null),H(),ie.open(e,!r.providers[e]),re(),ne(),Z(!0),Ke()},onAccountLogin:async(n,i=!1)=>{if(n===`openai`){if(b===`openai`)return;let n=r.providers.openai,i=Kl(n);if(i===`invalid`){V(t(`codexAuth.openaiMissing`),!1);return}if(i===`absent`||i===`disabled`){x(`openai`);try{await $l(e,i),await re()}catch(e){e instanceof Ql?V(t(e.i18nKey),!1):V(e instanceof Error?e.message:t(`prov.saveFailed`),!1);return}finally{R.current&&x(e=>e===`openai`?null:e)}}j(!0);return}if(it(n)){j(!0);return}(r.providers[n]?.authMode===`oauth`||h.includes(n))&&tt(n,i)},onAccountCancelLogin:e=>{qe(e)},onAccountLogout:e=>{Ye(e)},onAccountManage:e=>{W(e)},onOpenAdd:ne,onCloseCodexLogin:()=>j(!1),onCodexAdded:e=>{j(!1),U(e),e.validationPending||ie.open(`openai`,!r.providers.openai,e.catalogRefreshPending),re(),ne(),Z(!0),Ke()},onCancelRemove:()=>k(null),onConfirmRemove:()=>{Ze(O)},onCancelJsonLeave:()=>{Fe||Ue(!1)},onDiscardJson:ze,onSaveJson:()=>{Le()},onCancelOauthTos:()=>F(null),onContinueOauthTos:()=>{let e=P;e&&(F(null),Je(e.provider,e.addAccount,e.accountId))}})]})}function cd(e){let{t}=ut();return e.state===`stale`?(0,Y.jsxs)(`div`,{className:`codex-stale-banner`,role:`status`,children:[(0,Y.jsx)(`span`,{className:`codex-stale-banner-text`,children:t(`models.staleBanner`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:e.controller.restarting,onClick:()=>{e.controller.restart()},children:e.controller.restarting?t(`dash.codexRestarting`):t(`dash.codexRestart`)})]}):null}function ld(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e.trim().length>0)}function ud(e){return e===null||e===`alphabetical`||e===`provider`||e===`most-used`}function dd(e){if(typeof e!=`object`||!e)return!1;let t=e;return ld(t.pickerOrder)&&ud(t.pickerOrderMode)}function fd(e){if(!dd(e))return!1;let t=e;return ld(t.pickerAvailable)&&(!(`chosen`in t)||Array.isArray(t.chosen)&&t.chosen.every(e=>typeof e==`string`))}function pd(e){return Array.isArray(e)&&e.every(e=>typeof e==`object`&&!!e&&typeof e.provider==`string`&&typeof e.model==`string`&&(e.resolvedModel===void 0||typeof e.resolvedModel==`string`)&&typeof e.requests==`number`&&Number.isFinite(e.requests)&&e.requests>=0)}function md(e){let t=e.indexOf(`/`);return t<0?[``,e]:[e.slice(0,t),e.slice(t+1)]}var hd=(e,t)=>e.localeCompare(t,`en`);function gd(e,t){let[n,r]=md(e),[i,a]=md(t);return hd(n,i)||hd(r,a)}function _d(e,t,n=[],r=[]){if(e==="default")return null;let i=[...new Set(t)];if(e===`alphabetical`)return i.sort((e,t)=>hd(md(e)[1],md(t)[1])||gd(e,t));if(e===`provider`)return i.sort(gd);let a=new Set(i),o=new Map,s=new Map;for(let e of r){if(!a.has(e.namespaced))continue;let t=JSON.stringify([e.provider,e.id]),n=o.get(t)??new Set;n.add(e.namespaced),o.set(t,n);let r=s.get(e.namespaced)??new Set;r.add(t),s.set(e.namespaced,r)}let c=e=>(s.get(e)?.size??0)>1?null:e,l=(e,t)=>{let n=o.get(JSON.stringify([e,t]));if(n)return n.size===1?c([...n][0]):null;if(t.startsWith(`${e}/`)&&a.has(t))return c(t);let r=`${e}/${t}`;return!t.includes(`/`)&&a.has(r)?c(r):void 0},u=new Map;for(let e of n){let t=l(e.provider,e.model);t&&u.set(t,(u.get(t)??0)+e.requests)}return i.sort((e,t)=>(u.get(t)??0)-(u.get(e)??0)||gd(e,t))}function vd(e,t,n){if(t.length===0)return`default`;if(t.some(e=>!e.includes(`/`)))return`custom`;if(n===`alphabetical`||n===`provider`||n===`most-used`)return n;let r=new Set(e);if(new Set(t).size!==t.length||t.length!==r.size||t.some(e=>!r.has(e)))return`custom`;for(let n of[`alphabetical`,`provider`]){let r=_d(n,e);if(r!==null&&r.length===t.length&&r.every((e,n)=>e===t[n]))return n}return`custom`}function yd(e,t,n){let r=new Set(t.filter(e=>e.includes(`/`))),i=e=>{if(r.has(e))return e;let t=new Set(n.filter(t=>r.has(t.namespaced)&&e===`${t.provider}/${t.id}`).map(e=>e.namespaced));return t.size===1?[...t][0]:void 0};return[...new Set(e.map(e=>i(e.trim())).filter(e=>e!==void 0))]}function bd(e,t,n){return JSON.stringify([e,t,n.pickerAvailable,n.chosen??null,n.pickerOrder,n.pickerOrderMode])}function xd(e,t){let n=new Set(e.filter(e=>e.includes(`/`))),r=new Map,i=new Map;for(let e of t){if(!n.has(e.namespaced))continue;let t=`${e.provider}/${e.id}`,a=r.get(e.namespaced)??new Set,o=i.get(t)??new Set;a.add(t),o.add(e.namespaced),r.set(e.namespaced,a),i.set(t,o)}return[...n].every(e=>{let t=r.get(e);return t?.size===1&&i.get([...t][0])?.size===1})}function Sd(e,t){if(e.chosen===void 0||e.pickerOrder.some(e=>!e.includes(`/`)))return null;let n=[...new Set(e.pickerAvailable.filter(e=>e.includes(`/`)))];if(!xd(n,t))return null;let r=new Map(e.chosen.map((e,t)=>[e,t])),i=new Map(t.map(e=>[e.namespaced,`${e.provider}/${e.id}`])),a=e=>r.get(e)??r.get(i.get(e)),o=n.filter(e=>a(e)!==void 0).sort((e,t)=>a(e)-a(t)),s=yd(e.pickerOrder,n,t);return{fixed:o,order:[...new Set([...o,...s,...n])]}}function Cd(e,t,n,r){let i=[...e];return t===n||r.includes(t)||r.includes(n)||!i.includes(t)||!i.includes(n)?i:(i.splice(i.indexOf(t),1),i.splice(i.indexOf(n),0,t),i)}function wd(e,t,n,r){let i=[...e],a=i.indexOf(t),o=a+n;return a<0||o<0||o>=i.length||r.includes(t)||r.includes(i[o])||([i[a],i[o]]=[i[o],i[a]]),i}var Td=`application/x-ocx-picker-order`,Ed=0;function Dd(){let e=++Ed;if(typeof crypto<`u`&&typeof crypto.randomUUID==`function`)try{return`${e}:${crypto.randomUUID()}`}catch{}return`picker-${Date.now().toString(36)}-${e}`}function Od({apiBase:e,active:t,identities:n,onAccepted:r,onBusyChange:i}){let a=Q(),[o,s]=(0,_.useState)(null),[c,l]=(0,_.useState)([]),[u,d]=(0,_.useState)(!1),[f,p]=(0,_.useState)(null),[m,h]=(0,_.useState)(!1),[g,v]=(0,_.useState)(``),[y,b]=(0,_.useState)(null),[x,S]=(0,_.useState)(null),C=(0,_.useRef)({generation:0,flight:null,drag:null}),[w,T]=(0,_.useState)({apiBase:e,active:t,onBusyChange:i}),E=JSON.stringify(n.map(({provider:e,id:t,namespaced:n})=>[e,t,n])),D=(0,_.useRef)(E);(0,_.useLayoutEffect)(()=>{D.current=E},[E]);let O=o!==null&&o.identities!==E,k=!t||u||!o||f!==null||O,A=o!==null&&JSON.stringify(c)!==JSON.stringify(o.order),j=(0,_.useCallback)(()=>{C.current.drag=null,b(null),S(null)},[]);(w.apiBase!==e||w.active!==t||w.onBusyChange!==i)&&(T({apiBase:e,active:t,onBusyChange:i}),s(null),l([]),p(null),h(!1),d(!1));let[M,N]=(0,_.useState)({disabled:k,snapshot:o,identitySignature:E});(M.disabled!==k||M.snapshot!==o||M.identitySignature!==E)&&(N({disabled:k,snapshot:o,identitySignature:E}),b(null),S(null)),(0,_.useLayoutEffect)(()=>{let e=C.current;return e.generation++,()=>{e.generation++,e.flight?.controller.abort(),e.flight?.clear(),e.flight=null,e.drag=null,i(!1)}},[e,t,i]),(0,_.useLayoutEffect)(()=>{C.current.drag=null},[k,o,E]);let P=async a=>{if(!t||C.current.flight||a&&(k||!A))return;let u=C.current.generation,f=Xn(15e3);C.current.flight=f,d(!0),i(!0),h(!1),j();let m=()=>C.current.generation===u&&C.current.flight===f,g=()=>m()&&!f.signal.aborted&&D.current===E;try{let t=await fetch(`${e}/api/subagent-models`,{signal:f.signal});if(!g())return;let i=await It(t);if(!g())return;if(!fd(i))throw Error(`Invalid picker settings`);let d=bd(e,u,i);if(a&&(!o||d!==o.signature||E!==o.identities)){p(`models.pickerOrder.changed`);return}let m=Sd(i,n);if(!m){p(i.pickerOrder.some(e=>!e.includes(`/`))?`models.pickerOrder.nativeLocked`:i.chosen===void 0?`models.pickerOrder.unknownChosen`:`models.pickerOrder.catalogRequired`);return}if(!a){s({...m,signature:d,identities:E}),l(m.order),p(null),v(``);return}let h=await fetch(`${e}/api/subagent-models`,{method:`PUT`,headers:{"Content-Type":`application/json`},signal:f.signal,body:JSON.stringify({pickerOrder:c,pickerOrderMode:null})});if(!g())return;let _=await It(h);if(!g())return;if(!dd(_)||!(`ok`in _)||_.ok!==!0)throw Error(`Invalid picker receipt`);l(_.pickerOrder),p(`models.pickerOrder.savedReload`),r({pickerOrder:_.pickerOrder,pickerOrderMode:_.pickerOrderMode,catalogRefresh:`catalogRefresh`in _?_.catalogRefresh:void 0})}catch{m()&&D.current===E&&h(!0)}finally{f.clear(),m()&&(C.current.flight=null,d(!1),i(!1))}},F=(0,_.useEffectEvent)(async()=>{let e=C.current,n=e.generation;await Promise.resolve(),t&&e.generation===n&&P(!1)});(0,_.useEffect)(()=>{t&&F()},[e,t,i]);let I=(e,t)=>{k||(l(t),v(a(`models.pickerOrder.position`,{model:e,position:t.indexOf(e)+1,total:t.length})),j())},L=new Set(c),R=new Set(o?.fixed),z=e=>!k&&L.has(e)&&!R.has(e),B=(e,t)=>{!C.current.drag||C.current.drag.id===t||!z(C.current.drag.id)||!z(t)||!e.dataTransfer.types.includes(Td)||(e.preventDefault(),e.dataTransfer.dropEffect=`move`,S(t))};return(0,Y.jsxs)(`section`,{className:`picker-order-editor`,"aria-label":a(`models.pickerOrder.custom`),"aria-busy":u,children:[(0,Y.jsx)(`p`,{className:`muted text-label`,children:a(`models.pickerOrder.editorHint`)}),(f||O)&&(0,Y.jsx)(`p`,{role:`alert`,children:a(f??`models.pickerOrder.changed`)}),m&&(0,Y.jsx)(`p`,{role:`alert`,children:a(`models.pickerOrder.requestFailed`)}),o&&c.length===0&&(0,Y.jsx)(`p`,{children:a(`models.pickerOrder.empty`)}),(0,Y.jsx)(`ol`,{className:`picker-order-list`,children:c.map((e,t)=>{let n=R.has(e);return(0,Y.jsxs)(`li`,{className:`picker-order-row${y===e?` cwi-target-row--dragging`:``}${x===e?` cwi-target-row--drop`:``}`,onDragOver:t=>B(t,e),onDragLeave:()=>S(null),onDrop:t=>{let n=C.current.drag;n&&n.id!==e&&n.token===t.dataTransfer.getData(Td)&&z(n.id)&&z(e)&&(t.preventDefault(),I(n.id,Cd(c,n.id,e,o?.fixed??[]))),j()},onDragEnd:j,children:[(0,Y.jsx)(`button`,{type:`button`,className:`cwi-target-grip`,disabled:k||n,draggable:!k&&!n,"aria-label":a(`models.pickerOrder.dragModel`,{model:e}),onDragStart:t=>{if(!z(e)){t.preventDefault();return}let n=Dd();C.current.drag={id:e,token:n},b(e),t.dataTransfer.effectAllowed=`move`,t.dataTransfer.setData(Td,n)},children:(0,Y.jsx)(Le,{width:14,height:14,"aria-hidden":`true`})}),(0,Y.jsx)(`code`,{className:`picker-order-name`,children:e}),n&&(0,Y.jsx)(`span`,{className:`muted text-caption`,children:a(`models.pickerOrder.featured`)}),(0,Y.jsxs)(`span`,{className:`picker-order-actions`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:k||n||t===0||R.has(c[t-1]),"aria-label":a(`models.pickerOrder.upModel`,{model:e}),onClick:()=>I(e,wd(c,e,-1,o?.fixed??[])),children:(0,Y.jsx)(be,{width:14,height:14,"aria-hidden":`true`})}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:k||n||t===c.length-1||R.has(c[t+1]),"aria-label":a(`models.pickerOrder.downModel`,{model:e}),onClick:()=>I(e,wd(c,e,1,o?.fixed??[])),children:(0,Y.jsx)(xe,{width:14,height:14,"aria-hidden":`true`})})]})]},e)})}),(0,Y.jsx)(`p`,{role:`status`,"aria-live":`polite`,children:g}),(0,Y.jsxs)(`div`,{className:`row`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:k||!A,onClick:()=>void P(!0),children:a(u?`models.pickerOrder.applying`:`models.pickerOrder.saveDraft`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:!t||u,onClick:()=>void P(!1),children:a(`models.pickerOrder.reloadDraft`)})]})]})}var kd={operator:`models.displayNameSourceOperator`,provider:`models.displayNameSourceProvider`,fallback:`models.displayNameSourceFallback`};function Ad({model:e,saving:t,requestError:n,currentNamePending:r=!1,mutationOutcomeUnknown:i=!1,onRetry:a,onEdit:o,onSave:s,onReset:c,onClose:l}){let u=Q(),d=(0,_.useRef)(null),f=(0,_.useRef)(null),p=(0,_.useRef)(null),m=(0,_.useRef)(t),h=(0,_.useId)(),g=(0,_.useId)(),v=(0,_.useId)(),[y,b]=(0,_.useState)(e),[x,S]=(0,_.useState)(e.displayNameOverride??``),[C,w]=(0,_.useState)(null);(0,_.useEffect)(()=>{let e=d.current;return e&&!e.open&&e.showModal(),f.current?.focus(),()=>{e?.open&&e.close()}},[]),(0,_.useEffect)(()=>{let e=m.current&&!t&&!!n;m.current=t,e&&(i?p.current?.focus():f.current?.focus())},[n,t,i]),y!==e&&(b(e),S(e.displayNameOverride??``),w(null));let T=C?u(C):null,E=T??n,D=e.displayNameSource?kd[e.displayNameSource]:`models.displayNameSourceFallback`,O=()=>{t||l()};return(0,Y.jsxs)(`dialog`,{ref:d,className:`modal-overlay`,"aria-labelledby":h,onCancel:e=>{e.preventDefault(),O()},children:[(0,Y.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":u(`common.close`),tabIndex:-1,disabled:t,onClick:O}),(0,Y.jsxs)(`form`,{className:`modal-card model-display-name-dialog`,role:`document`,onClick:e=>e.stopPropagation(),onSubmit:e=>{if(e.preventDefault(),t)return;if(a){a();return}if(i)return;let n=jo(x);w(n),n||s(x.trim())},children:[(0,Y.jsxs)(`div`,{className:`modal-head`,children:[(0,Y.jsx)(`h3`,{id:h,children:u(`models.displayNameTitle`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:t,onClick:O,children:u(`common.close`)})]}),(0,Y.jsxs)(`div`,{className:`model-display-name-identity`,children:[(0,Y.jsx)(`span`,{className:`muted text-label`,children:u(`models.displayNameModelId`)}),(0,Y.jsx)(`code`,{className:`mono text-control`,children:e.namespaced})]}),(0,Y.jsxs)(`div`,{className:`model-display-name-current`,children:[(0,Y.jsx)(`span`,{className:`muted text-label`,children:u(`models.displayNameCurrent`)}),(0,Y.jsx)(`strong`,{children:r?u(`models.displayNameCurrentUnavailable`):e.displayName??e.namespaced}),!r&&(0,Y.jsx)(`span`,{className:`models-chip muted text-caption`,children:u(D)})]}),(0,Y.jsx)(`label`,{className:`field-label`,htmlFor:`${h}-input`,children:u(`models.displayNameField`)}),(0,Y.jsx)(`input`,{ref:f,id:`${h}-input`,className:`input`,value:x,maxLength:129,placeholder:u(`models.displayNamePlaceholder`),"aria-describedby":`${g}${E?` ${v}`:``}`,"aria-invalid":T?!0:void 0,disabled:t||i,onChange:e=>{t||i||(o?.(),S(e.target.value),w(null))}}),(0,Y.jsx)(`p`,{id:g,className:`muted small`,children:u(`models.displayNameHelp`,{model:e.namespaced})}),E&&(0,Y.jsx)(`p`,{id:v,className:`model-display-name-error`,role:`alert`,children:E}),(0,Y.jsxs)(`div`,{className:`modal-actions`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:t||i||!e.displayNameOverride,onClick:()=>{!t&&!i&&c()},children:u(`models.displayNameReset`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:t,onClick:O,children:u(`common.cancel`)}),(0,Y.jsx)(`button`,{ref:p,type:`submit`,className:`btn btn-primary btn-sm`,disabled:t||i&&!a,children:u(t?`common.saving`:a?`common.retry`:`common.save`)})]})]})]})}var jd=[`input`,`output`,`cacheRead`,`cacheWrite`],Md={input:`pricing.override.input`,output:`pricing.override.output`,cacheRead:`pricing.override.cacheRead`,cacheWrite:`pricing.override.cacheWrite`},Nd=1e6,Pd=6e4,Fd={input:``,output:``,cacheRead:``,cacheWrite:``};function Id(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ld(e){return Id(e)&&jd.every(t=>typeof e[t]==`number`&&Number.isFinite(e[t])&&e[t]>=0&&e[t]<=Nd)}function Rd({model:e,apiBase:t,onRefresh:n,onClose:r}){let i=Q(),a=(0,_.useId)(),o=(0,_.useRef)(null),s=(0,_.useRef)(null),c=(0,_.useRef)(null),l=(0,_.useRef)(null),u=(0,_.useRef)(!1),[d,f]=(0,_.useState)(`loading`),[p,m]=(0,_.useState)(Fd),[h,g]=(0,_.useState)(!1),[v,y]=(0,_.useState)(null),[b,x]=(0,_.useState)(!1),S=`${t}/api/providers/${encodeURIComponent(e.provider)}/model-costs`,C=d===`saving`||d===`refreshing`,w=d!==`ready`,T=(0,_.useCallback)((t=!1)=>{if(l.current)return;let n=Xn(Pd);l.current=n,fetch(S,{signal:n.signal,cache:`no-store`}).then(async r=>{let i=await It(r);if(n.signal.throwIfAborted(),!Id(i)||i.provider!==e.provider||!Id(i.modelCosts))throw Error(`invalid model-costs response`);let a=Object.hasOwn(i.modelCosts,e.id)?i.modelCosts[e.id]:void 0;if(a!==void 0&&!Ld(a))throw Error(`invalid model cost`);l.current===n&&(m(a===void 0?Fd:{input:String(a.input),output:String(a.output),cacheRead:String(a.cacheRead),cacheWrite:String(a.cacheWrite)}),g(a!==void 0),x(t),f(`ready`))}).catch(()=>{l.current===n&&(f(t?`unknown`:`loadFailed`),y(t?`pricing.override.recoveryFailed`:`pricing.override.loadFailed`))}).finally(()=>{n.clear(),l.current===n&&(l.current=null)})},[S,e.id,e.provider]);(0,_.useEffect)(()=>{let e=o.current;return e&&!e.open&&e.showModal(),T(),()=>{l.current?.controller.abort(),l.current?.clear(),l.current=null,e?.open&&e.close()}},[T]),(0,_.useEffect)(()=>{d===`ready`?s.current?.focus():(d===`unknown`||d===`loadFailed`||d===`refreshFailed`)&&c.current?.focus()},[d]);let E=async t=>{if(l.current||(t===void 0?d!==`refreshFailed`:d!==`ready`))return;let i=Xn(Pd);l.current=i,f(t===void 0?`refreshing`:`saving`),u.current=!0,y(null);let a=t===void 0;try{if(t!==void 0){let n=await It(await fetch(S,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({modelId:e.id,cost:t}),signal:i.signal}));i.signal.throwIfAborted();let r=Id(n)?n.cost:void 0;if(!Id(n)||n.ok!==!0||n.provider!==e.provider||n.modelId!==e.id||(t===null?r!==null:!Ld(r)||!jd.every(e=>r[e]===t[e])))throw Error(`invalid model-costs receipt`);if(l.current!==i)return;a=!0,f(`refreshing`)}if(!await n(i.signal))throw Error(`catalog refresh failed`);i.signal.throwIfAborted(),l.current===i&&r()}catch{if(l.current!==i)return;f(a?`refreshFailed`:`unknown`),y(a?`pricing.override.refreshFailed`:`pricing.override.outcomeUnknown`)}finally{i.clear(),l.current===i&&(l.current=null,u.current=!1)}},D=()=>{u.current||r()};return(0,Y.jsxs)(`dialog`,{ref:o,className:`modal-overlay`,"aria-labelledby":`${a}-title`,onCancel:e=>{e.preventDefault(),D()},children:[(0,Y.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,tabIndex:-1,"aria-label":i(`pricing.override.close`),disabled:C,onClick:D}),(0,Y.jsxs)(`form`,{className:`modal-card model-display-name-dialog`,role:`document`,noValidate:!0,"aria-busy":d===`loading`||C,onClick:e=>e.stopPropagation(),onSubmit:e=>{if(e.preventDefault(),l.current)return;if(d===`unknown`||d===`loadFailed`){f(`loading`),y(null),T(d===`unknown`);return}if(d===`refreshFailed`){E(void 0);return}if(w)return;let t={input:Number(p.input),output:Number(p.output),cacheRead:Number(p.cacheRead),cacheWrite:Number(p.cacheWrite)};if([...e.currentTarget.querySelectorAll(`input`)].some(e=>e.validity.badInput)||!p.input.trim()||!p.output.trim()||!Ld(t)){y(`pricing.override.invalid`),s.current?.focus();return}E(t)},children:[(0,Y.jsxs)(`div`,{className:`modal-head`,children:[(0,Y.jsx)(`h3`,{id:`${a}-title`,children:i(`pricing.override.title`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:C,onClick:D,children:i(`pricing.override.close`)})]}),(0,Y.jsxs)(`div`,{className:`model-display-name-identity`,children:[(0,Y.jsx)(`span`,{className:`muted text-label`,children:i(`pricing.override.modelId`)}),(0,Y.jsx)(`code`,{className:`mono text-control`,children:e.namespaced})]}),(0,Y.jsx)(`p`,{id:`${a}-help`,className:`muted small`,children:i(`pricing.override.help`)}),d===`loading`&&(0,Y.jsx)(`p`,{role:`status`,className:`muted small`,children:i(`pricing.override.loading`)}),jd.map(e=>(0,Y.jsxs)(_.Fragment,{children:[(0,Y.jsx)(`label`,{className:`field-label`,htmlFor:`${a}-${e}`,children:i(Md[e])}),(0,Y.jsx)(`input`,{ref:e===`input`?s:void 0,id:`${a}-${e}`,className:`input`,type:`number`,min:0,max:Nd,step:`any`,inputMode:`decimal`,value:p[e],disabled:w,required:e===`input`||e===`output`,"aria-describedby":`${a}-help${v?` ${a}-error`:``}`,"aria-invalid":v===`pricing.override.invalid`||void 0,onChange:t=>{if(w||l.current)return;let n=t.target.value;m(t=>({...t,cacheRead:t.cacheRead||`0`,cacheWrite:t.cacheWrite||`0`,[e]:n})),y(null)}})]},e)),b&&(0,Y.jsx)(`p`,{role:`status`,className:`muted small`,children:i(`pricing.override.recovered`)}),v&&(0,Y.jsx)(`p`,{id:`${a}-error`,className:`model-display-name-error`,role:`alert`,children:i(v)}),(0,Y.jsxs)(`div`,{className:`modal-actions`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:w||!h,onClick:()=>void E(null),children:i(`pricing.override.reset`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:C,onClick:D,children:i(`pricing.override.cancel`)}),(0,Y.jsx)(`button`,{ref:c,type:`submit`,className:`btn btn-primary btn-sm`,disabled:d===`loading`||C,children:i(C?`pricing.override.saving`:d===`unknown`||d===`loadFailed`?`pricing.override.reload`:d===`refreshFailed`?`pricing.override.refresh`:`pricing.override.save`)})]})]})]})}var zd=[`fresh`,`stale`,`not_running`,`unknown`],Bd=[`stopped`,`nothing_running`,`enumeration_unavailable`,`partially_stopped`];function Vd(e){return Array.isArray(e)&&e.every(e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>0)}function Hd(e){if(typeof e!=`object`||!e)return!1;let t=e;if(!(typeof t.success==`boolean`&&typeof t.synced==`boolean`&&typeof t.stateBefore==`string`&&zd.includes(t.stateBefore)&&typeof t.code==`string`&&Bd.includes(t.code)&&Vd(t.requested)&&Vd(t.stopped)&&Vd(t.surviving)&&Vd(t.failed)))return!1;let n=t.success,r=t.code,i=t.surviving,a=t.failed,o=t.stopped;if(n!==(r!==`partially_stopped`)||n&&(i.length>0||a.length>0)||!n&&i.length===0&&a.length===0||(r===`nothing_running`||r===`enumeration_unavailable`)&&o.length>0)return!1;if(`desktopApp`in t&&t.desktopApp!==void 0){let e=t.desktopApp;if(typeof e!=`object`||!e)return!1;let n=e;if(typeof n.attempted!=`boolean`||!Vd(n.stopped)||!Vd(n.surviving)||n.relaunch!==`started`&&n.relaunch!==`skipped`||n.reason!==void 0&&typeof n.reason!=`string`||n.relaunch===`started`&&n.surviving.length>0)return!1}return!0}function Ud(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.state==`string`&&zd.includes(t.state)&&typeof t.runningCount==`number`&&Number.isSafeInteger(t.runningCount)&&t.runningCount>=0}var Wd={state:null,runningCount:0};async function Gd(e,t={}){let n=t.fetchFn??fetch;try{let r=await n(`${e}/api/system/codex-app-server`,{signal:t.signal});if(!r.ok)return Wd;let i=await r.json().catch(()=>null);return Ud(i)?{state:i.state,runningCount:i.runningCount}:Wd}catch{return Wd}}var Kd=3e4;function qd(e){return(e instanceof DOMException||e instanceof Error)&&(e.name===`AbortError`||e.name===`TimeoutError`)}async function Jd(e,t={}){let{fetchFn:n=fetch,timeoutMs:r=Kd,formatFailure:i=e=>`Failed to restart Codex (HTTP ${e}).`,formatUnreachable:a=()=>`Could not reach the proxy.`,formatMalformed:o=()=>`The proxy returned an unexpected response.`,formatTimeout:s=()=>`The proxy did not answer in time. It may still be working.`}=t,c;try{c=await n(`${e}/api/system/codex-restart`,{method:`POST`,signal:AbortSignal.timeout(r)})}catch(e){return{ok:!1,message:qd(e)?s():a()}}if(!c.ok)return{ok:!1,message:i(c.status)};let l;try{l=await c.json()}catch(e){return{ok:!1,message:qd(e)?s():o()}}return Hd(l)?{ok:!0,result:l}:{ok:!1,message:o()}}function Yd(e){return e===`stopped`||e===`nothing_running`}function Xd(e,t={}){let{t:n}=ut(),[r,i]=(0,_.useState)(!1),a=(0,_.useRef)(!0),o=(0,_.useRef)(t.onSettled);return(0,_.useEffect)(()=>{o.current=t.onSettled},[t.onSettled]),(0,_.useEffect)(()=>(a.current=!0,()=>{a.current=!1}),[]),{restarting:r,restart:(0,_.useCallback)(async()=>{if(!confirm(n(`dash.codexRestartConfirm`)))return null;i(!0);let t=await Jd(e,{formatFailure:e=>n(`dash.codexRestartFailed`,{status:String(e)}),formatUnreachable:()=>n(`dash.codexRestartUnreachable`),formatTimeout:()=>n(`dash.codexRestartTimeout`),formatMalformed:()=>n(`dash.codexRestartMalformed`)});if(a.current&&i(!1),!t.ok||!t.result)return alert(t.message),null;let r=t.result;return r.code===`stopped`?alert(n(`dash.codexRestartDone`,{count:String(r.stopped.length)})):r.code===`nothing_running`?alert(n(`dash.codexRestartNothing`)):r.code===`enumeration_unavailable`?alert(n(`dash.codexRestartUnknown`)):alert(n(`dash.codexRestartPartial`,{count:String(r.surviving.length)})),a.current&&Yd(r.code)&&o.current?.(r.code),r.code},[e,n])}}var Zd={"gpt-5.6-sol":Me,"gpt-5.6-terra":Fe,"gpt-5.6-luna":Ne,"gpt-daybreak-blue-latest":Me,"daybreak-blue-latest":Me,"daybreak-red-latest":ke},Qd={width:14,height:14,flexShrink:0,verticalAlign:`text-bottom`};function $d(e){return e.slice(e.lastIndexOf(`/`)+1)}function ef(e){return Zd[e]??Zd[$d(e)]??null}function tf(e){let t=ef(e);return t?(0,_.createElement)(`span`,{className:`model-label`},(0,_.createElement)(t,{style:Qd,"aria-hidden":!0}),e):e}var nf=new Set([`absent`,`current`,`stale`,`conflict`,`unsafe`]),rf=new Set([`unparseable`,`not-regular-file`,`foreign-edit`,`unowned-key`,`blocked-container`,`unresolvable-path`]);function af(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function of(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function sf(e){if(!af(e)||e.clientId!==`aside`||!of(e.profileId)||typeof e.current!=`boolean`||typeof e.enabled!=`boolean`||!nf.has(e.state)||typeof e.installed!=`boolean`||typeof e.configPath!=`string`||!Number.isSafeInteger(e.snapshotCount)||e.snapshotCount<-1||typeof e.retentionDegraded!=`boolean`||e.reason!==void 0&&!rf.has(e.reason))return null;for(let t of[`name`,`error`,`appliedAt`,`lastOpId`])if(e[t]!==void 0&&typeof e[t]!=`string`)return null;return{clientId:`aside`,profileId:e.profileId,current:e.current,enabled:e.enabled,state:e.state,installed:e.installed,configPath:e.configPath,snapshotCount:e.snapshotCount,retentionDegraded:e.retentionDegraded,...typeof e.name==`string`?{name:e.name}:{},...typeof e.error==`string`?{error:e.error}:{},...typeof e.appliedAt==`string`?{appliedAt:e.appliedAt}:{},...typeof e.lastOpId==`string`?{lastOpId:e.lastOpId}:{},...e.reason===void 0?{}:{reason:e.reason}}}function cf(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!af(n)||!of(n.profileId)||typeof n.ok!=`boolean`||n.state!==void 0&&!nf.has(n.state)||n.residual!==void 0&&typeof n.residual!=`boolean`)return null;for(let e of[`reason`,`refusalReason`,`message`,`snapshotPath`])if(n[e]!==void 0&&typeof n[e]!=`string`)return null;t.push({profileId:n.profileId,ok:n.ok,...n.state===void 0?{}:{state:n.state},...typeof n.reason==`string`?{reason:n.reason}:{},...typeof n.refusalReason==`string`?{refusalReason:n.refusalReason}:{},...typeof n.message==`string`?{message:n.message}:{},...typeof n.snapshotPath==`string`?{snapshotPath:n.snapshotPath}:{},...typeof n.residual==`boolean`?{residual:n.residual}:{}})}return t}var lf=[`opencode`,`pi`,`omp`,`hermes`,`openclaw`,`kimi`,`gajae`,`dsh`,`mcode`,`zcode`,`prime`,`aside`,`raycast`,`omo`,`cline`],uf=new Set([`not_installed`,`conflict`,`unsafe`,`non_loopback`,`drift_requires_confirm`,`snapshot_expired`,`write_failed`]),df=new Set([`integration_unsafe`,`integration_conflict`,`integration_drift_confirmation_required`,`integration_snapshot_expired`,`integration_mutation_failed`]),ff=new Set([`absent`,`current`,`stale`,`conflict`,`unsafe`]);function pf(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function mf(e){return!pf(e)||!uf.has(String(e.reason))?!1:typeof e.error==`string`&&df.has(String(e.code))&&lf.includes(e.clientId)&&ff.has(String(e.state))&&typeof e.message==`string`}var hf=class extends Error{refusal;status;body;constructor(e,t){let n=mf(t)?t:null;super(n?.message??t.error??t.message??String(e)),this.name=`IntegrationApiError`,this.status=e,this.body=t,this.refusal=n}};function gf(e){return e instanceof hf&&e.status===404&&e.body.code===`integration_operation_not_found`}async function _f(e){try{let t=await e.json();return pf(t)?t:{}}catch{return{}}}async function vf(e){if(!e.ok)throw new hf(e.status,await _f(e));let t=await Lt(e);if(t==null)throw new hf(e.status,{});return t}function yf(e){if(!Number.isSafeInteger(e)||e<0)throw new hf(400,{code:`invalid_aside_profile`});return`/api/client-integrations/aside/profiles/${e}`}function bf(e,t){if(t!==void 0){if(e!==`aside`)throw new hf(400,{code:`invalid_aside_profile`});return yf(t)}return e===`aside`?`/api/client-integrations/aside/profiles`:`/api/client-integrations/${encodeURIComponent(e)}`}async function xf(e,t){return vf(await fetch(`${e}/api/client-integrations`,{signal:t}))}async function Sf(e,t,n,r){let i=await vf(await fetch(`${e}${bf(t,r)}`,{signal:n}));if(r!==void 0){let e=sf(i);if(!e||e.profileId!==r)throw new hf(502,{code:`invalid_aside_profile_response`});return e}return i}async function Cf(e,t,n,r){if(r!==void 0&&t!==`aside`)throw new hf(400,{code:`invalid_aside_profile`});let i=t===`aside`?`${bf(t,r)}/journal`:`/api/client-integrations/journal${t?`?client=${encodeURIComponent(t)}`:``}`,a=await vf(await fetch(`${e}${i}`,{signal:n}));if(r!==void 0&&(!Array.isArray(a.operations)||a.operations.some(e=>e.clientId!==`aside`||e.profileId!==r)))throw new hf(502,{code:`invalid_aside_profile_response`});return a}async function wf(e,t,n,r,i,a){let o=await vf(await fetch(`${e}${bf(t,a)}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(i===!0?{enabled:n,overwriteConflict:!0}:{enabled:n}),signal:r})),s=o.results===void 0?void 0:cf(o.results);if(t===`aside`&&o.results!==void 0&&(!s||o.ok!==s.every(e=>e.ok)))throw new hf(502,{code:`invalid_aside_profile_response`});if(o.ok!==!0)throw new hf(207,{code:t===`aside`?`aside_profile_partial`:`integration_mutation_failed`,message:o.message,results:s??void 0});if(a!==void 0&&o.profileId!==a)throw new hf(502,{code:`invalid_aside_profile_response`});return{...o,...s?{results:s}:{}}}async function Tf(e,t,n=!1,r,i){let a=await vf(await fetch(`${e}${i===void 0?`/api/client-integrations/restore`:`${yf(i)}/restore`}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({opId:t,confirmDrift:n}),signal:r}));if(i!==void 0&&a.profileId!==i)throw new hf(502,{code:`invalid_aside_profile_response`});return a}async function Ef(e,t,n,r){let i=await vf(await fetch(`${e}${r===void 0?`/api/client-integrations/journal`:`${yf(r)}/journal`}?opId=${encodeURIComponent(t)}`,{method:`DELETE`,signal:n}));if(r!==void 0&&i.profileId!==r)throw new hf(502,{code:`invalid_aside_profile_response`});return i}async function Df(e){try{let t=await e;return t.ok?await Lt(t)??null:null}catch{return null}}async function Of(e,t){let n=await Df(fetch(`${e}/api/startup-health`,{signal:t}));return n?{routingInjected:n.routingInjected===!0,status:typeof n.status==`string`?n.status:void 0,recommendedCommand:typeof n.recommendedCommand==`string`?n.recommendedCommand:null}:null}async function kf(e,t){let n=await fetch(`${e}/api/keys`,{signal:t});if(!n.ok)throw Error(`/api/keys responded ${n.status}`);let r=await Lt(n);if(!r||!Array.isArray(r.keys))throw Error(`/api/keys returned an unexpected body`);return r.keys.length}async function Af(e,t){let n=await Df(fetch(`${e}/api/claude-code`,{signal:t}));return n?{enabled:n.enabled===!0,authMode:typeof n.authMode==`string`?n.authMode:void 0}:null}async function jf(e,t){let n=await Df(fetch(`${e}/api/claude-desktop/status`,{signal:t}));return!n||typeof n.desiredEnabled!=`boolean`||typeof n.installed!=`boolean`||typeof n.observedKind!=`string`?null:{desiredEnabled:n.desiredEnabled,installed:n.installed,observedKind:n.observedKind,applied:n.applied===!0,stale:n.stale===!0,drift:n.drift===!0,driftReason:typeof n.driftReason==`string`?n.driftReason:null,activeProfile:typeof n.activeProfile==`boolean`?n.activeProfile:null,appliedAt:typeof n.appliedAt==`string`?n.appliedAt:null}}async function Mf(e,t){let n=await Df(fetch(`${e}/api/grok`,{signal:t}));return n?{present:n.present===!0,models:Array.isArray(n.models)?n.models:[]}:null}var Nf=new Set([`claude`,`grok`,`codex`,`claude-desktop`]),Pf=new Set([`native_integration_refused`,`native_integration_failed`]),Ff=new Set([`not_installed`,`orphaned_marker`,`home_mismatch`,`config_busy`,`write_failed`,`metadata_unreadable`,`cleanup_incomplete`,`desired_state_changed`]);function If(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Lf(e){return If(e)?typeof e.error==`string`&&Pf.has(String(e.code))&&Nf.has(String(e.clientId))&&Ff.has(String(e.reason))&&typeof e.message==`string`:!1}var Rf=class extends Error{refusal;status;body;constructor(e,t){let n=Lf(t)?t:null;super(n?.message??t.error??t.message??String(e)),this.name=`NativeApiError`,this.status=e,this.body=t,this.refusal=n}};async function zf(e){try{let t=await e;return t.ok?await Lt(t)??null:null}catch{return null}}async function Bf(e){try{let t=await e.json();return If(t)?t:{}}catch{return{}}}async function Vf(e){if(!e.ok)throw new Rf(e.status,await Bf(e));let t=await Lt(e);if(t==null)throw new Rf(e.status,{});return t}function Hf(e,t){return zf(fetch(`${e}/api/native-integrations`,{signal:t}))}async function Uf(e,t,n,r){return Vf(await fetch(`${e}/api/native-integrations/${encodeURIComponent(t)}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({enabled:n}),signal:r}))}var Wf={integration_mutation_busy:`integrations.error.busy`,integration_journal_newest_protected:`integrations.rollback.deleteNewest`,integration_operation_not_found:`integrations.rollback.deleteGone`,aside_profile_partial:`integrations.aside.partial`,invalid_aside_profile_response:`integrations.aside.loadError`};function Gf(e){return e instanceof hf?e.refusal:null}function Kf(e){return e instanceof Rf?e.refusal:null}function qf(e){return e===`conflict`?`integrations.error.conflict`:e===`unsafe`?`integrations.error.unsafe`:e===`non_loopback`?`integrations.error.nonLoopback`:`integrations.error.generic`}var Jf=new Set([`non_loopback`]);function Yf(e,t,n){return t.reason===`orphaned_marker`?e(`integrations.native.error.orphanedMarker`,{path:n??``}):t.reason===`home_mismatch`?`${e(`integrations.native.error.homeMismatch`)} ${t.message}`:t.reason===`not_installed`?e(`integrations.native.error.notInstalled`):t.reason===`config_busy`?e(`integrations.native.error.configBusy`):t.reason===`metadata_unreadable`?e(`integrations.native.error.desktopUnsafeMetadata`,{path:n??``}):t.reason===`cleanup_incomplete`?e(`integrations.native.error.desktopCleanupIncomplete`,{paths:(t.residualPaths??[]).join(`, `)}):t.message||e(`integrations.error.generic`)}function Xf(e,t,n,r){let i=Kf(t);if(i)return Yf(e,i,r);let a=Gf(t);if(!a){if(t instanceof hf&&`results`in t.body&&t.body.results?.length){let n=t.body.results.filter(e=>!e.ok).map(t=>{let n=Zf(e,t);return`${e(`integrations.aside.profile`,{id:String(t.profileId)})}: ${n}`});return[e(`integrations.aside.partial`),...n].join(`
|
|
82
82
|
`)}let r=Wf[t instanceof hf?String(t.body.code??``):``];return r?e(r):t instanceof Error&&t.message?t.message:n??e(`integrations.error.generic`)}return Qf(e,a)}function Zf(e,t){return Qf(e,{clientId:`aside`,message:t.message??t.reason,reason:t.refusalReason??t.reason,snapshotPath:t.snapshotPath,residual:t.residual})}function Qf(e,t){let n=Jf.has(t.reason??``)?e(qf(t.reason),{client:t.clientId}):t.message||e(qf(t.reason));return t.snapshotPath?e(t.residual?`integrations.error.residual`:`integrations.error.recover`,{message:n,path:t.snapshotPath}):t.residual?e(`integrations.error.residualNoSnapshot`,{message:n}):t.reason===`conflict`||t.reason===`unsafe`?`${e(qf(t.reason))} ${n}`:n}function $f({className:e,style:t}){return(0,Y.jsx)(`span`,{"aria-hidden":`true`,className:e?`data-surface-skeleton__block ${e}`:`data-surface-skeleton__block`,style:t})}function ep({label:e,rows:t=3,className:n}){let r=Math.max(1,Math.floor(t));return(0,Y.jsxs)(`div`,{className:n?`data-surface-skeleton ${n}`:`data-surface-skeleton`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,"aria-busy":`true`,children:[(0,Y.jsx)(`span`,{className:`sr-only`,children:e}),Array.from({length:r},(e,t)=>(0,Y.jsx)(`div`,{className:`data-surface-skeleton__row`,"aria-hidden":`true`,children:(0,Y.jsx)($f,{})},t))]})}function tp({children:e,busy:t=!0,live:n=!0,className:r}){return(0,Y.jsxs)(`div`,{className:r?`data-surface-status ${r}`:`data-surface-status`,role:n?`status`:void 0,"aria-live":n?`polite`:void 0,"aria-atomic":n?`true`:void 0,"aria-busy":t||void 0,children:[t&&(0,Y.jsx)(`span`,{className:`spin`,"aria-hidden":`true`}),(0,Y.jsx)(`span`,{children:e})]})}var np=class extends _.Component{state={error:null};static getDerivedStateFromError(e){return{error:e instanceof Error?e:Error(String(e))}}reload=()=>{this.setState({error:null})};render(){return this.state.error?(0,Y.jsxs)(`section`,{className:`card`,role:`alert`,style:{maxWidth:720,padding:`var(--space-6)`},children:[(0,Y.jsxs)(`h2`,{style:{margin:`0 0 var(--space-2)`,fontSize:`var(--text-title)`},children:[this.props.pageName,`: `,this.props.title]}),(0,Y.jsx)(`p`,{className:`muted`,style:{margin:`0 0 var(--space-4)`},children:this.props.message}),(0,Y.jsxs)(`p`,{style:{margin:`0 0 var(--space-5)`,overflowWrap:`anywhere`},children:[(0,Y.jsxs)(`strong`,{children:[this.props.detailsLabel,`:`]}),` `,this.state.error.message]}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:this.reload,children:this.props.reloadLabel})]}):this.props.children}},rp=`gpt-daybreak-blue-latest`,ip=`gpt-6-astra`,ap=new Set([rp]),op=Object.freeze({[rp]:`gpt-5.6-sol`});Object.freeze(Object.keys(op)),Object.freeze({[rp]:{displayName:`Daybreak Blue`,description:`Frontier general-purpose model with safeguards for defensive cybersecurity work.`}});var sp=new Set([`gpt-5.5`,`gpt-5.6-sol`,`gpt-5.6-terra`,`gpt-5.6-luna`,rp,ip]);[...ap];var cp=[`low`,`medium`,`high`,`xhigh`,`max`,`ultra`],lp=[`failover`,`round-robin`,`random`,`least-used`,`reset-window`],up={failover:`cws.strategy.failover`,"round-robin":`cws.strategy.roundRobin`,random:`cws.strategy.random`,"least-used":`cws.strategy.leastUsed`,"reset-window":`cws.strategy.resetWindow`},dp={failover:`cws.strategy.failoverHint`,"round-robin":`cws.strategy.roundRobinHint`,random:`cws.strategy.randomHint`,"least-used":`cws.strategy.leastUsedHint`,"reset-window":`cws.strategy.resetWindowHint`},fp={failover:`cws.targets.failoverHint`,"round-robin":`cws.targets.roundRobinHint`,random:`cws.targets.randomHint`,"least-used":`cws.targets.leastUsedHint`,"reset-window":`cws.targets.resetWindowHint`},pp=new Set(lp);function mp(e,t,n=`strict`){let r=e.filter(e=>e.provider.trim()&&e.model.trim());if(r.length===0)return[...cp];let i=new Set(cp),a=null;for(let e of r){let r=`${e.provider.trim()}/${e.model.trim()}`,o=t.get(r);if(o===void 0||n===`adaptive`&&o.length===0)continue;let s=o.filter(e=>i.has(e));if(a===null)a=s;else{let e=new Set(s);a=a.filter(t=>e.has(t))}}if(a===null)return[...cp];let o=new Set(a);return cp.filter(e=>o.has(e))}var hp=ro,gp=0;function _p(e={}){return{provider:e.provider??``,model:e.model??``,...e.weight===void 0?{}:{weight:e.weight},clientKey:e.clientKey??`ct-${++gp}`}}function vp(e){return e===`disabled`?`disabled`:`auto`}function yp(e){return e===`adaptive`?`adaptive`:`strict`}var bp=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/,xp=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}(\/[a-zA-Z0-9][a-zA-Z0-9._-]{0,63})?$/,Sp=/^(?:gpt-|o1-|o3-|o4-|codex-)/;function Cp(e){return bp.test(e.trim())}function wp(e){return`combo/${e.trim()}`}function Tp(e,t){return(typeof t==`string`?t.trim():``)||wp(e)}function Ep(e,t){let n=t.trim(),r=e.nativeAlias&&(!n||n.includes(`/`)||!Sp.test(n));return{...e,alias:n?t:null,model:Tp(e.id,t),...r?{nativeAlias:!1,displayName:null}:{}}}function Dp(e){return typeof e==`string`&&e.trim()?e.trim():null}function Op(e){return typeof e==`string`&&pp.has(e)?e:`failover`}function kp(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=100?e:1}function Ap(e){return typeof e==`string`&&cp.includes(e)?e:null}function jp(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=1e4?e:void 0}function Mp(e){if(!e||typeof e!=`object`)return[];let t=e.combos;if(!Array.isArray(t))return[];let n=[];for(let e of t){if(!e||typeof e!=`object`)continue;let t=e,r=typeof t.id==`string`?t.id.trim():``;if(!r)continue;let i=Array.isArray(t.targets)?t.targets:[],a=[];for(let e of i){if(!e||typeof e!=`object`)continue;let t=e,n=typeof t.provider==`string`?t.provider.trim():``,r=typeof t.model==`string`?t.model.trim():``;if(!n||!r)continue;let i=jp(t.weight);a.push(_p(i===void 0?{provider:n,model:r}:{provider:n,model:r,weight:i}))}n.push({id:r,model:typeof t.model==`string`&&t.model.trim()?t.model.trim():Tp(r,Dp(t.alias)),alias:Dp(t.alias),nativeAlias:t.nativeAlias===!0,displayName:Dp(t.displayName),strategy:Op(t.strategy),stickyLimit:kp(t.stickyLimit),defaultEffort:Ap(t.defaultEffort),imageInput:vp(t.imageInput),reasoningEffortMode:yp(t.reasoningEffortMode),targets:a})}return n.sort((e,t)=>e.id.localeCompare(t.id,void 0,{sensitivity:`base`}))}function Np(e){let t=[],n=[],r=[];for(let i of e)i.strategy===`failover`?t.push(i):i.strategy===`round-robin`?n.push(i):r.push(i);return{failover:t,roundRobin:n,other:r}}function Pp(e,t){let n=t.trim().toLowerCase();return n?e.filter(e=>e.id.toLowerCase().includes(n)||e.model.toLowerCase().includes(n)?!0:e.targets.some(e=>e.provider.toLowerCase().includes(n)||e.model.toLowerCase().includes(n))):e}function Fp(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:null}function Ip(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function Lp(e,t){let n=Fp(e.routingQuota);if(!n||n.state!==`available`&&n.state!==`exhausted`)return null;let r=Ip(n.updatedAt),i=Ip(n.validUntil);return r===null||r<0||r>t||t-r>=hp||i===null||i<=t||i>r+hp?null:{state:n.state,validUntil:i}}function Rp(e,t){return Lp(e,t)?.state??`unknown`}function zp(e,t=Date.now()){if(!Array.isArray(e))return;let n;for(let r of e){let e=Fp(r);if(!e||typeof e.provider!=`string`||!e.provider.trim())continue;let i=Lp(e,t);i&&(n===void 0||i.validUntil<n)&&(n=i.validUntil)}return n}function Bp(e,t=Date.now()){if(!Array.isArray(e))return{};let n={};for(let r of e){let e=Fp(r),i=typeof e?.provider==`string`?e.provider.trim():``;if(!e||!i)continue;let a=Rp(e,t);n[i]=Object.hasOwn(n,i)&&n[i]!==a?`unknown`:a}return n}function Vp(e,t,n){let r=e.flatMap(e=>{let t=e.provider.trim();return!t||!e.model.trim()||!Object.hasOwn(n,t)||n[t]?.disabled===!0?[]:[t]});if(r.length===0)return`unknown`;let i=!1;for(let e of r){let n=t[e]??`unknown`;if(n===`available`)return`available`;n===`unknown`&&(i=!0)}return i?`unknown`:`exhausted`}function Hp(e,t={}){let n=[],r=t.cataloguedComboIds;for(let i of e)i.targets.length===0?n.push({id:i.id,model:i.model,reason:`empty-targets`}):i.targets.length<2&&n.push({id:i.id,model:i.model,reason:`few-targets`}),r&&i.targets.length>0&&!r.has(i.id)&&n.push({id:i.id,model:i.model,reason:`catalog-omitted`}),t.providerQuotaStates&&t.providers&&Vp(i.targets,t.providerQuotaStates,t.providers)===`exhausted`&&n.push({id:i.id,model:i.model,reason:`all-targets-exhausted`});return n}function Up(e,t){return e.id!==t.id||e.alias!==t.alias||e.nativeAlias!==t.nativeAlias||e.displayName!==t.displayName||e.strategy!==t.strategy||e.stickyLimit!==t.stickyLimit||e.defaultEffort!==t.defaultEffort||(e.imageInput??`auto`)!==(t.imageInput??`auto`)||(e.reasoningEffortMode??`strict`)!==(t.reasoningEffortMode??`strict`)||e.targets.length!==t.targets.length?!1:e.targets.every((e,n)=>{let r=t.targets[n];return e.provider===r.provider&&e.model===r.model&&(e.weight??1)===(r.weight??1)})}function Wp(e,t={}){let n=e.strategy===`round-robin`||e.strategy===`random`;return{id:e.id.trim(),...t.renameFrom?{renameFrom:t.renameFrom}:{},combo:{targets:e.targets.map(e=>n?{provider:e.provider.trim(),model:e.model.trim(),weight:e.weight??1}:{provider:e.provider.trim(),model:e.model.trim()}),strategy:e.strategy,defaultEffort:e.defaultEffort,...e.imageInput===`disabled`?{imageInput:`disabled`}:{},...e.reasoningEffortMode===`adaptive`?{reasoningEffortMode:`adaptive`}:{},...e.strategy===`round-robin`?{stickyLimit:e.stickyLimit}:{},...e.alias&&e.alias.trim()?{alias:e.alias.trim()}:{},...e.nativeAlias?{nativeAlias:!0}:{},...e.displayName&&e.displayName.trim()?{displayName:e.displayName.trim()}:{}}}}function Gp(e,t){let n=e.id.trim();if(!n)return`missingId`;if(!Cp(n))return`invalidId`;if(t.existingIds.includes(n))return`duplicateId`;if(Object.hasOwn(t.providers,`combo`))return`reservedNamespace`;if(Object.hasOwn(t.providers,n))return`providerCollision`;let r=e.alias?.trim()??``,i=e.displayName?.trim()??``;if(r){if(!xp.test(r))return`invalidAlias`;if(r===`combo`||r.startsWith(`combo/`))return`aliasReservedNamespace`;if(!r.includes(`/`)&&Sp.test(r)&&!e.nativeAlias)return`aliasNativeFamily`;if((t.existingAliases??[]).includes(r))return`duplicateAlias`}let a=[...e.displayName??``].some(e=>{let t=e.codePointAt(0)??0;return t<=31||t===127});if(e.displayName!==null&&(i.length>128||a))return`invalidDisplayName`;if(e.nativeAlias&&!sp.has(r))return`unsupportedNativeAlias`;if(e.nativeAlias&&!i)return`missingNativeAliasDisplayName`;if(e.targets.length<1)return`noTargets`;for(let n of e.targets){if(!n.provider.trim()||!n.model.trim())return`incompleteTarget`;if(!Object.hasOwn(t.providers,n.provider.trim()))return`unknownProvider`}let o=new Set;for(let t of e.targets){let e=`${t.provider.trim()}/${t.model.trim()}`;if(o.has(e))return`duplicateTarget`;o.add(e)}if(e.strategy===`round-robin`&&(!Number.isInteger(e.stickyLimit)||e.stickyLimit<1||e.stickyLimit>100))return`invalidStickyLimit`;if(e.strategy===`round-robin`||e.strategy===`random`)for(let t of e.targets){let e=t.weight??1;if(!Number.isInteger(e)||e<1||e>1e4)return`invalidWeight`}return e.targets.some(e=>t.providers[e.provider.trim()]?.disabled!==!0)?null:`noEnabledTarget`}function Kp(e=``){return{id:e,model:e?wp(e):`combo/`,alias:null,nativeAlias:!1,displayName:null,strategy:`failover`,stickyLimit:1,defaultEffort:null,imageInput:`auto`,reasoningEffortMode:`strict`,targets:[_p()]}}function qp(e,t){return e.length!==0&&e.every(e=>{let n=e.provider.trim(),r=e.model.trim();return!n||!r?!1:!!t.find(e=>e.provider===n&&e.id===r)?.inputModalities?.includes(`image`)})}function Jp(e){return e.filter(e=>!e.disabled&&!e.hiddenFromPicker).sort((e,t)=>e.name.localeCompare(t.name))}function Yp(e,t,n){if(e===``)return;let r=Number(e);if(Number.isFinite(r))return Math.min(n,Math.max(t,r))}function Xp(e){if(!e)return!1;let t=e.name.toLowerCase();if(t!==`openai`&&t!==`chatgpt`||(e.authMode??``).toLowerCase()!==`forward`||(e.adapter??``).toLowerCase()!==`openai-responses`)return!1;let n=(e.baseUrl??``).replace(/\/+$/,``);return!n||n.includes(`chatgpt.com/backend-api/codex`)}function Zp(e,t,n){let r=new Set([t]),i=n.find(e=>e.name===t);(t.toLowerCase()===`chatgpt`||Xp(i))&&r.add(`openai`);let a=[],o=new Set;for(let t of e)!r.has(t.provider)||!t.id||o.has(t.id)||(o.add(t.id),a.push(t.id));return a.toSorted((e,t)=>e.localeCompare(t))}function Qp({value:e,onChange:t,disabled:n}){let r=Q();return(0,Y.jsx)(`div`,{className:`cwi-strategy-seg`,role:`radiogroup`,"aria-label":r(`cws.strategy`),children:lp.map(i=>(0,Y.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":e===i,className:`btn btn-sm${e===i?` btn-primary`:` btn-ghost`}`,disabled:n,onClick:()=>t(i),children:r(up[i])},i))})}function $p({id:e,value:t,onChange:n,disabled:r,allowedEfforts:i}){let a=Q(),o=i??cp,s=t!==null&&!o.includes(t);return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`select`,{id:e,className:`input`,value:t??``,disabled:r,"aria-label":a(`cws.field.defaultEffort`),onChange:e=>n(e.target.value===``?null:e.target.value),children:[(0,Y.jsx)(`option`,{value:``,children:a(`cws.field.defaultEffortNone`)}),s&&t?(0,Y.jsxs)(`option`,{value:t,children:[t,` (`,a(`cws.field.defaultEffortUnsupportedOption`),`)`]}):null,o.map(e=>(0,Y.jsx)(`option`,{value:e,children:e},e))]}),s?(0,Y.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`,color:`var(--danger, #b42318)`},children:a(`cws.field.defaultEffortUnsupported`)}):null]})}function em({targets:e,models:t,imageInput:n,reasoningEffortMode:r,disabled:i,onChange:a}){let o=Q(),s=qp(e,t),c=s&&n!==`disabled`;return(0,Y.jsxs)(`section`,{className:`cwi-capabilities`,"aria-label":o(`cws.capabilities`),children:[(0,Y.jsx)(`span`,{className:`field-label`,children:o(`cws.capabilities`)}),(0,Y.jsxs)(`div`,{className:`cwi-capability-row`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`cwi-capability-label`,children:o(`cws.capability.imageInput`)}),(0,Y.jsx)(`p`,{className:`muted cwi-capability-hint`,children:o(s?`cws.capability.imageInputHint`:`cws.capability.imageInputUnavailable`)})]}),(0,Y.jsx)(Dt,{on:c,onClick:()=>{s&&a({imageInput:n===`auto`?`disabled`:`auto`})},disabled:i||!s,label:o(`cws.capability.imageInput`)})]}),(0,Y.jsxs)(`div`,{className:`cwi-capability-row`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`cwi-capability-label`,children:o(`cws.capability.adaptiveEffort`)}),(0,Y.jsx)(`p`,{className:`muted cwi-capability-hint`,children:o(`cws.capability.adaptiveEffortHint`)})]}),(0,Y.jsx)(Dt,{on:r===`adaptive`,onClick:()=>{a({reasoningEffortMode:r===`adaptive`?`strict`:`adaptive`})},disabled:i,label:o(`cws.capability.adaptiveEffort`)})]})]})}function tm({targets:e,strategy:t,providers:n,models:r,providerQuotaStates:i,onChange:a}){let o=Q(),s=Jp(n),[c,l]=(0,_.useState)(null),[u,d]=(0,_.useState)(null),f=(t,n)=>{a(e.map((e,r)=>r===t?{...e,...n}:e))},p=(t,n)=>{if(t===n||t<0||n<0||t>=e.length||n>=e.length)return;let r=[...e],[i]=r.splice(t,1);r.splice(n,0,i),a(r)};return(0,Y.jsxs)(`div`,{className:`cwi-target-list`,children:[e.map((m,h)=>{let g=n.find(e=>e.name===m.provider),_=g&&!s.some(e=>e.name===m.provider)?[...s,g]:s,v=Zp(r,m.provider,n),y=m.model&&!v.includes(m.model)?[m.model,...v]:v,b=!m.provider,x=c===h,S=u===h&&c!==null&&c!==h,C=i[m.provider.trim()]??`unknown`;return(0,Y.jsxs)(`div`,{className:[`cwi-target-row`,t===`failover`?`cwi-target-row--failover`:``,x?`cwi-target-row--dragging`:``,S?`cwi-target-row--drop`:``].filter(Boolean).join(` `),onDragOver:e=>{c!==null&&(e.preventDefault(),e.dataTransfer.dropEffect=`move`,u!==h&&d(h))},onDrop:e=>{e.preventDefault(),c!==null&&p(c,h),l(null),d(null)},onDragEnd:()=>{l(null),d(null)},children:[(0,Y.jsx)(`button`,{type:`button`,className:`cwi-target-grip`,draggable:!0,"aria-label":o(`cws.target.drag`),title:o(`cws.target.drag`),onDragStart:e=>{l(h),e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,String(h))},children:(0,Y.jsx)(Le,{width:14,height:14,"aria-hidden":`true`})}),(0,Y.jsxs)(`div`,{className:`cwi-target-reorder`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:h===0,"aria-label":o(`cws.target.moveUp`),onClick:()=>p(h,h-1),children:(0,Y.jsx)(be,{width:14,height:14,"aria-hidden":`true`})}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:h===e.length-1,"aria-label":o(`cws.target.moveDown`),onClick:()=>p(h,h+1),children:(0,Y.jsx)(xe,{width:14,height:14,"aria-hidden":`true`})})]}),(0,Y.jsxs)(`select`,{className:`input`,value:m.provider,"aria-label":o(`cws.target.provider`),onChange:e=>{let t=e.target.value,i=Zp(r,t,n)[0]??``;f(h,{provider:t,model:i})},children:[(0,Y.jsx)(`option`,{value:``,children:o(`cws.target.pickProvider`)}),_.map(e=>(0,Y.jsx)(`option`,{value:e.name,children:e.disabled?o(`cws.target.disabled`,{name:Ln(e.name,o)}):Ln(e.name,o)},e.name))]}),(0,Y.jsxs)(`select`,{className:`input`,value:m.model,disabled:b,"aria-label":o(`cws.target.model`),onChange:e=>f(h,{model:e.target.value}),children:[(0,Y.jsx)(`option`,{value:``,children:b?o(`cws.target.pickProviderFirst`):y.length===0?o(`cws.target.noModels`):o(`cws.target.pickModel`)}),y.map(e=>(0,Y.jsx)(`option`,{value:e,children:e},e))]}),(t===`round-robin`||t===`random`)&&(0,Y.jsx)(`input`,{className:`input mono`,type:`number`,min:1,max:1e4,value:m.weight??1,"aria-label":o(`cws.target.weight`),onChange:e=>{let t=Yp(e.target.value,1,1e4);t!==void 0&&f(h,{weight:t})}}),(0,Y.jsx)(`span`,{className:`cwi-quota-badge cwi-quota-badge--${C}`,"aria-label":o(`cws.quota.${C}`),children:o(`cws.quota.${C}`)}),(0,Y.jsx)(`div`,{className:`cwi-target-actions`,children:(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:e.length<=1,onClick:()=>a(e.filter((e,t)=>t!==h)),"aria-label":o(`common.remove`),children:(0,Y.jsx)(me,{width:14,height:14})})})]},m.clientKey??`${m.provider}:${m.model}`)}),(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{alignSelf:`flex-start`},onClick:()=>a([...e,_p()]),children:[(0,Y.jsx)(ue,{width:14,height:14}),` `,o(`cws.target.add`)]})]})}function nm({existingIds:e,existingAliases:t,providerMap:n,providerQuotaStates:r,providers:i,models:a,onClose:o,onSubmit:s}){let c=Q(),l=(0,_.useRef)(null),[u,d]=(0,_.useState)(()=>Kp()),[f,p]=(0,_.useState)(!1),[m,h]=(0,_.useState)(``),g=(0,_.useMemo)(()=>{let e=new Map;for(let t of a)e.set(`${t.provider}/${t.id}`,t.reasoningEfforts);return e},[a]),v=(0,_.useMemo)(()=>mp(u.targets,g,u.reasoningEffortMode??`strict`),[u.targets,g,u.reasoningEffortMode]),y=Vp(u.targets,r,n)===`exhausted`;(0,_.useEffect)(()=>{let e=l.current;e&&!e.open&&e.showModal()},[]);let b=(0,_.useCallback)(()=>{f||o()},[f,o]),x=(0,_.useCallback)(e=>{e.preventDefault(),b()},[b]),S=async()=>{let r=Gp(u,{existingIds:e,existingAliases:t,isCreate:!0,providers:n});if(r){h(c(`cws.err.${r}`));return}p(!0),h(``);let i=u.id.trim(),a=u.alias?.trim()||null;try{let e=await s({...u,id:i,alias:a,model:Tp(i,a)});if(!e.ok){h(e.error||c(`cws.saveFailed`));return}}finally{p(!1)}};return(0,Y.jsxs)(`dialog`,{ref:l,className:`modal-overlay`,"aria-labelledby":`cwi-add-title`,onCancel:x,children:[(0,Y.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":c(`common.close`),tabIndex:-1,onClick:b}),(0,Y.jsxs)(`div`,{className:`modal-card`,style:{width:`min(560px, 94vw)`},onClick:e=>e.stopPropagation(),children:[(0,Y.jsxs)(`div`,{className:`row`,style:{justifyContent:`space-between`,marginBottom:8},children:[(0,Y.jsx)(`h3`,{id:`cwi-add-title`,style:{margin:0},children:c(`cws.addTitle`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:b,disabled:f,"aria-label":c(`common.close`),children:(0,Y.jsx)(le,{width:16,height:16})})]}),(0,Y.jsx)(`p`,{className:`muted`,style:{marginTop:0,maxWidth:`62ch`,overflowWrap:`anywhere`},children:c(`cws.addSubtitle`)}),m&&(0,Y.jsx)($,{tone:`err`,children:m}),y&&(0,Y.jsx)(`div`,{className:`cwi-quota-banner`,role:`status`,"aria-live":`polite`,children:c(`cws.quota.allExhausted`)}),(0,Y.jsxs)(`div`,{className:`cwi-modal-form`,children:[(0,Y.jsxs)(`div`,{className:`cwi-field`,children:[(0,Y.jsx)(`label`,{htmlFor:`cwi-new-id`,children:c(`cws.field.id`)}),(0,Y.jsx)(`input`,{id:`cwi-new-id`,className:`input mono`,value:u.id,disabled:f,onChange:e=>d(t=>({...t,id:e.target.value,model:Tp(e.target.value,t.alias)}))}),(0,Y.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:c(`cws.field.idInternalHint`)})]}),(0,Y.jsxs)(`div`,{className:`cwi-field`,children:[(0,Y.jsx)(`label`,{htmlFor:`cwi-new-alias`,children:c(`cws.field.alias`)}),(0,Y.jsx)(`input`,{id:`cwi-new-alias`,className:`input mono`,value:u.alias??``,placeholder:c(`cws.field.aliasPlaceholder`),disabled:f,onChange:e=>d(t=>({...t,alias:e.target.value.trim()?e.target.value:null,model:Tp(t.id,e.target.value)}))}),(0,Y.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:c(`cws.field.aliasHint`)}),(0,Y.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:c(`cws.field.idHint`,{model:u.id.trim()?Tp(u.id,u.alias):`…`})})]}),(0,Y.jsxs)(`div`,{className:`cwi-field`,children:[(0,Y.jsx)(`span`,{className:`field-label`,children:c(`cws.strategy`)}),(0,Y.jsx)(Qp,{value:u.strategy,disabled:f,onChange:e=>d(t=>({...t,strategy:e}))}),(0,Y.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:c(dp[u.strategy])})]}),(0,Y.jsxs)(`div`,{className:`cwi-field`,children:[(0,Y.jsx)(`label`,{htmlFor:`cwi-new-effort`,children:c(`cws.field.defaultEffort`)}),(0,Y.jsx)($p,{id:`cwi-new-effort`,value:u.defaultEffort,disabled:f,allowedEfforts:v,onChange:e=>d(t=>({...t,defaultEffort:e}))}),(0,Y.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:c(`cws.field.defaultEffortHint`)})]}),u.strategy===`round-robin`&&(0,Y.jsxs)(`div`,{className:`cwi-field`,children:[(0,Y.jsx)(`label`,{htmlFor:`cwi-new-sticky`,children:c(`cws.field.stickyLimit`)}),(0,Y.jsx)(`input`,{id:`cwi-new-sticky`,className:`input mono`,type:`number`,min:1,max:100,value:u.stickyLimit,disabled:f,onChange:e=>{let t=Yp(e.target.value,1,100);t!==void 0&&d(e=>({...e,stickyLimit:t}))}}),(0,Y.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:c(`cws.field.stickyLimitHint`)})]}),(0,Y.jsxs)(`div`,{className:`cwi-field`,children:[(0,Y.jsx)(`span`,{className:`field-label`,children:c(`cws.targets`)}),(0,Y.jsx)(tm,{targets:u.targets,strategy:u.strategy,providers:i,models:a,providerQuotaStates:r,onChange:e=>d(t=>({...t,targets:e}))}),(0,Y.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:c(fp[u.strategy])})]}),(0,Y.jsx)(em,{targets:u.targets,models:a,imageInput:u.imageInput??`auto`,reasoningEffortMode:u.reasoningEffortMode??`strict`,disabled:f,onChange:e=>d(t=>({...t,...e}))})]}),(0,Y.jsxs)(`div`,{className:`cwi-modal-actions`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:b,disabled:f,children:c(`common.cancel`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>{S()},disabled:f||y,children:c(f?`common.saving`:`cws.create`)})]})]})]})}var rm=[`config`,`about`],im=e=>`cws-detail-tab-${e}`,am=e=>`cws-detail-panel-${e}`;function om({baseline:e,isCreate:t=!1,otherIds:n,otherAliases:r,providerMap:i,providerQuotaStates:a,providers:o,models:s,onBack:c,onSaved:l,onRequestRemove:u,onSave:d,onDirtyChange:f}){let p=Q(),[m,h]=(0,_.useState)(`config`),g=(0,_.useCallback)((e,t)=>{let n;if(e.key===`ArrowRight`)n=(t+1)%rm.length;else if(e.key===`ArrowLeft`)n=(t-1+rm.length)%rm.length;else if(e.key===`Home`)n=0;else if(e.key===`End`)n=rm.length-1;else return;e.preventDefault(),h(rm[n]),e.currentTarget.parentElement?.querySelectorAll(`[role="tab"]`)[n]?.focus()},[]),[v,y]=(0,_.useState)(e),[b,x]=(0,_.useState)(!1),[S,C]=(0,_.useState)(null),[w,T]=(0,_.useState)(!1),E=!Up(v,e),D=Vp(v.targets,a,i)===`exhausted`,O=`${e.id}:${e.alias??``}:${e.nativeAlias}:${e.displayName??``}:${e.strategy}:${e.stickyLimit}:${e.defaultEffort}:${e.imageInput??`auto`}:${e.reasoningEffortMode??`strict`}:${e.targets.map(e=>`${e.provider}/${e.model}:${e.weight??1}`).join(`,`)}`,k=(0,_.useMemo)(()=>{let e=new Map;for(let t of s)e.set(`${t.provider}/${t.id}`,t.reasoningEfforts);return e},[s]),A=(0,_.useMemo)(()=>mp(v.targets,k,v.reasoningEffortMode??`strict`),[v.targets,k,v.reasoningEffortMode]),j=(0,_.useCallback)(t=>{let n=t(v);y(n),f(!Up(n,e))},[v,e,f]);(0,_.useEffect)(()=>{let t=window.setTimeout(()=>{y(e),C(null),h(`config`),f(!1)},0);return()=>window.clearTimeout(t)},[O]);let M=async()=>{try{await navigator.clipboard.writeText(e.model),T(!0),window.setTimeout(()=>T(!1),1200)}catch{}},N=async()=>{let a=Gp(v,{existingIds:n,existingAliases:r,isCreate:t,providers:i});if(a){C({ok:!1,text:p(`cws.err.${a}`)});return}x(!0);let o=v.id.trim(),s=v.alias?.trim()||null,c=v.displayName?.trim()||null,u={...v,id:o,alias:s,displayName:c,model:Tp(o,s)},f=!t&&o!==e.id?e.id:void 0;try{let e=await d(u,t,f);if(!e.ok){C({ok:!1,text:e.error||p(`cws.saveFailed`)});return}C({ok:!0,text:t?p(`cws.created`,{model:u.model}):p(`cws.saved`)}),l(u)}finally{x(!1)}},P=t?v.id.trim()?Tp(v.id,v.alias):p(`cws.addTitle`):e.model;return(0,Y.jsxs)(`div`,{className:`combos-workspace-detail`,children:[(0,Y.jsxs)(`div`,{className:`combos-workspace-detail-head`,children:[c&&(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm pwi-back-overview`,onClick:c,"aria-label":p(`cws.backToAll`),children:[(0,Y.jsx)(Ce,{style:{width:14,height:14,transform:`rotate(180deg)`},"aria-hidden":`true`}),p(`cws.allCombos`)]}),(0,Y.jsx)(`h2`,{className:`combos-workspace-detail-title`,children:P}),!t&&(0,Y.jsx)(`button`,{type:`button`,className:`chip cwi-copy-chip`,onClick:()=>{M()},title:p(`cws.copyModel`),children:p(w?`cws.copied`:`cws.copyModel`)}),(0,Y.jsxs)(`div`,{className:`combos-workspace-detail-actions`,children:[!t&&u&&(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:u,children:[(0,Y.jsx)(me,{width:14,height:14}),` `,p(`common.remove`)]}),(0,Y.jsx)(`button`,{id:t?`cwi-edit-create`:`cwi-edit-save`,type:`button`,className:`btn btn-primary btn-sm`,disabled:!t&&!E||b||D,onClick:()=>{N()},children:p(b?`common.saving`:t?`cws.create`:`common.save`)})]})]}),S&&(0,Y.jsx)($,{tone:S.ok?`ok`:`err`,children:S.text}),D&&(0,Y.jsx)(`div`,{className:`cwi-quota-banner`,role:`status`,"aria-live":`polite`,children:p(`cws.quota.allExhausted`)}),(0,Y.jsx)(`div`,{className:`segmented combos-workspace-segmented`,role:`tablist`,"aria-label":p(`cws.tabsLabel`),children:rm.map((e,t)=>(0,Y.jsx)(`button`,{type:`button`,role:`tab`,id:im(e),"aria-selected":m===e,"aria-controls":am(e),tabIndex:m===e?0:-1,className:`btn btn-sm ${m===e?`btn-primary`:`btn-ghost`}`,onClick:()=>h(e),onKeyDown:e=>g(e,t),children:p(e===`config`?`cws.tab.config`:`cws.tab.about`)},e))}),(0,Y.jsx)(`div`,{className:`combos-workspace-tab-content`,role:`tabpanel`,id:am(`config`),"aria-labelledby":im(`config`),hidden:m!==`config`,children:(0,Y.jsxs)(`div`,{className:`cwi-form-grid`,children:[(0,Y.jsxs)(`div`,{className:`cwi-field`,children:[(0,Y.jsx)(`label`,{htmlFor:`cwi-edit-id`,children:p(`cws.field.id`)}),(0,Y.jsx)(`input`,{id:`cwi-edit-id`,className:`input mono`,value:v.id,disabled:b,onChange:e=>j(t=>({...t,id:e.target.value,model:Tp(e.target.value,t.alias)}))}),(0,Y.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:t?p(`cws.field.idInternalHint`):p(`cws.field.idHintEdit`,{model:Tp(v.id,v.alias)})})]}),(0,Y.jsxs)(`div`,{className:`cwi-field`,children:[(0,Y.jsx)(`label`,{htmlFor:`cwi-edit-alias`,children:p(`cws.field.alias`)}),(0,Y.jsx)(`input`,{id:`cwi-edit-alias`,className:`input mono`,value:v.alias??``,placeholder:wp(v.id.trim()||`…`),disabled:b,onChange:e=>j(t=>Ep(t,e.target.value))}),(0,Y.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:p(`cws.field.aliasHint`)})]}),(0,Y.jsxs)(`div`,{className:`cwi-field`,children:[(0,Y.jsxs)(`label`,{htmlFor:`cwi-edit-native-alias`,children:[(0,Y.jsx)(`input`,{id:`cwi-edit-native-alias`,type:`checkbox`,checked:v.nativeAlias,disabled:b,onChange:e=>j(t=>({...t,nativeAlias:e.target.checked}))}),` `,p(`cws.field.nativeAlias`)]}),(0,Y.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:p(`cws.field.nativeAliasHint`)})]}),(0,Y.jsxs)(`div`,{className:`cwi-field`,children:[(0,Y.jsx)(`label`,{htmlFor:`cwi-edit-display-name`,children:p(`cws.field.displayName`)}),(0,Y.jsx)(`input`,{id:`cwi-edit-display-name`,className:`input`,value:v.displayName??``,maxLength:128,disabled:b,onChange:e=>j(t=>({...t,displayName:e.target.value||null}))}),(0,Y.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:p(`cws.field.displayNameHint`)})]}),(0,Y.jsxs)(`div`,{className:`cwi-field`,children:[(0,Y.jsx)(`span`,{className:`field-label`,children:p(`cws.strategy`)}),(0,Y.jsx)(Qp,{value:v.strategy,disabled:b,onChange:e=>j(t=>({...t,strategy:e}))}),(0,Y.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:p(dp[v.strategy])})]}),(0,Y.jsxs)(`div`,{className:`cwi-field`,children:[(0,Y.jsx)(`label`,{htmlFor:`cwi-effort`,children:p(`cws.field.defaultEffort`)}),(0,Y.jsx)($p,{id:`cwi-effort`,value:v.defaultEffort,disabled:b,allowedEfforts:A,onChange:e=>j(t=>({...t,defaultEffort:e}))}),(0,Y.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:p(`cws.field.defaultEffortHint`)})]}),v.strategy===`round-robin`&&(0,Y.jsxs)(`div`,{className:`cwi-field`,children:[(0,Y.jsx)(`label`,{htmlFor:`cwi-sticky`,children:p(`cws.field.stickyLimit`)}),(0,Y.jsx)(`input`,{id:`cwi-sticky`,className:`input mono`,type:`number`,min:1,max:100,value:v.stickyLimit,disabled:b,onChange:e=>{let t=Yp(e.target.value,1,100);t!==void 0&&j(e=>({...e,stickyLimit:t}))}})]}),(0,Y.jsxs)(`div`,{className:`cwi-field`,children:[(0,Y.jsx)(`span`,{className:`field-label`,children:p(`cws.targets`)}),(0,Y.jsx)(tm,{targets:v.targets,strategy:v.strategy,providers:o,models:s,providerQuotaStates:a,onChange:e=>j(t=>({...t,targets:e}))}),(0,Y.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:p(fp[v.strategy])})]}),(0,Y.jsx)(em,{targets:v.targets,models:s,imageInput:v.imageInput??`auto`,reasoningEffortMode:v.reasoningEffortMode??`strict`,disabled:b,onChange:e=>j(t=>({...t,...e}))})]})}),(0,Y.jsx)(`div`,{className:`combos-workspace-tab-content`,role:`tabpanel`,id:am(`about`),"aria-labelledby":im(`about`),hidden:m!==`about`,tabIndex:0,children:(0,Y.jsxs)(`section`,{className:`pwi-section`,children:[(0,Y.jsx)(`h3`,{className:`pwi-section-title`,children:p(`cws.aboutTitle`)}),(0,Y.jsx)(`p`,{className:`muted`,style:{margin:0,maxWidth:`70ch`,overflowWrap:`anywhere`},children:p(`cws.aboutBody`)})]})})]})}function sm({model:e,onCancel:t,onConfirm:n}){let r=Q(),i=(0,_.useRef)(null);(0,_.useEffect)(()=>{let e=i.current;e&&!e.open&&e.showModal()},[]);let a=(0,_.useCallback)(e=>{e.preventDefault(),t()},[t]);return(0,Y.jsxs)(`dialog`,{ref:i,className:`modal-overlay`,"aria-labelledby":`cwi-remove-title`,onCancel:a,children:[(0,Y.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":r(`common.close`),tabIndex:-1,onClick:t}),(0,Y.jsxs)(`div`,{className:`modal-card pwi-remove-confirm-card`,onClick:e=>e.stopPropagation(),children:[(0,Y.jsx)(`h3`,{id:`cwi-remove-title`,className:`pwi-remove-confirm-title`,children:r(`cws.removeConfirmTitle`,{model:e})}),(0,Y.jsx)(`p`,{className:`muted pwi-remove-confirm-desc`,children:r(`cws.removeConfirmDesc`)}),(0,Y.jsxs)(`div`,{className:`pwi-remove-confirm-actions`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:t,children:r(`common.cancel`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn pwi-remove-confirm-danger`,onClick:n,children:r(`common.remove`)})]})]})]})}function cm({onKeep:e,onDiscard:t}){let n=Q(),r=(0,_.useRef)(null);(0,_.useEffect)(()=>{let e=r.current;e&&!e.open&&e.showModal()},[]);let i=(0,_.useCallback)(t=>{t.preventDefault(),e()},[e]);return(0,Y.jsxs)(`dialog`,{ref:r,className:`modal-overlay`,"aria-labelledby":`cwi-unsaved-title`,onCancel:i,children:[(0,Y.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":n(`common.close`),tabIndex:-1,onClick:e}),(0,Y.jsxs)(`div`,{className:`modal-card pwi-json-unsaved-card`,onClick:e=>e.stopPropagation(),children:[(0,Y.jsx)(`h3`,{id:`cwi-unsaved-title`,className:`pwi-json-unsaved-title`,children:n(`cws.unsavedTitle`)}),(0,Y.jsx)(`p`,{className:`muted pwi-json-unsaved-desc`,children:n(`cws.unsavedDesc`)}),(0,Y.jsxs)(`div`,{className:`pwi-json-unsaved-actions`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,"data-testid":`cwi-unsaved-keep`,onClick:e,children:n(`cws.keepEditing`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-danger`,"data-testid":`cwi-unsaved-discard`,onClick:t,children:n(`common.discard`)})]})]})]})}function lm(e,t){return t(e===`empty-targets`?`cws.attention.empty`:e===`catalog-omitted`?`cws.attention.catalogOmitted`:e===`all-targets-exhausted`?`cws.attention.allTargetsExhausted`:`cws.attention.few`)}function um({combos:e,cataloguedComboIds:t,providerMap:n,providerQuotaStates:r,onSelect:i,onAdd:a}){let o=Q(),s=Np(e),c=Hp(e,{cataloguedComboIds:t,providers:n,providerQuotaStates:r});return(0,Y.jsxs)(`div`,{className:`combos-workspace-overview`,children:[(0,Y.jsxs)(`div`,{className:`combos-workspace-overview-head`,children:[(0,Y.jsx)(`h2`,{className:`combos-workspace-overview-title`,children:o(`cws.overviewTitle`)}),(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:a,children:[(0,Y.jsx)(ue,{width:14,height:14}),` `,o(`cws.add`)]})]}),(0,Y.jsx)(`p`,{className:`muted`,style:{marginTop:0,maxWidth:`62ch`},children:o(`cws.overviewBlurb`)}),(0,Y.jsxs)(`div`,{className:`cwi-count-strip`,children:[(0,Y.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,Y.jsx)(`strong`,{children:e.length}),(0,Y.jsx)(`span`,{children:o(`cws.count.total`)})]}),(0,Y.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,Y.jsx)(`strong`,{children:s.failover.length}),(0,Y.jsx)(`span`,{children:o(`cws.count.failover`)})]}),(0,Y.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,Y.jsx)(`strong`,{children:s.roundRobin.length}),(0,Y.jsx)(`span`,{children:o(`cws.count.roundRobin`)})]}),(0,Y.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,Y.jsx)(`strong`,{children:s.other.length}),(0,Y.jsx)(`span`,{children:o(`cws.count.other`)})]})]}),(0,Y.jsxs)(`section`,{className:`pwi-section`,"aria-label":o(`cws.howTitle`),children:[(0,Y.jsx)(`h3`,{className:`pwi-section-title`,children:o(`cws.howTitle`)}),(0,Y.jsx)(`p`,{className:`muted`,style:{margin:0},children:o(`cws.howBody`)})]}),c.length>0&&(0,Y.jsxs)(`section`,{className:`pwi-section`,"aria-label":o(`cws.attentionTitle`),children:[(0,Y.jsx)(`h3`,{className:`pwi-section-title`,children:o(`cws.attentionTitle`)}),(0,Y.jsx)(`div`,{className:`cwi-attention-list`,children:c.map(e=>(0,Y.jsxs)(`button`,{type:`button`,className:`cwi-attention-row`,onClick:()=>i(e.id),children:[(0,Y.jsx)(_e,{width:14,height:14,"aria-hidden":`true`}),(0,Y.jsx)(`code`,{className:`chip`,children:e.model}),(0,Y.jsx)(`span`,{className:`muted`,children:lm(e.reason,o)}),(0,Y.jsx)(Ce,{width:14,height:14,style:{marginLeft:`auto`},"aria-hidden":`true`})]},`${e.id}:${e.reason}`))})]})]})}function dm({combos:e,providerQuotaStates:t,providers:n,models:r,cataloguedComboIds:i,loading:a,onRefresh:o,onSave:s,onRemove:c,onAdd:l,adding:u,onCloseAdd:d,onCreated:f}){let p=Q(),m=(0,_.useMemo)(()=>Object.fromEntries(n.map(e=>[e.name,{disabled:e.disabled}])),[n]),[h,g]=(0,_.useState)(``),[v,y]=(0,_.useState)(null),[b,x]=(0,_.useState)(void 0),[S,C]=(0,_.useState)(null),[w,T]=(0,_.useState)(null),E=(0,_.useMemo)(()=>Kp(),[]),D=(0,_.useMemo)(()=>Pp(e,h),[e,h]),O=(0,_.useMemo)(()=>Np(D),[D]),k=(0,_.useMemo)(()=>e.flatMap(e=>e.alias?[e.alias]:[]),[e]),A=v&&e.some(e=>e.id===v)?v:null,j=e.find(e=>e.id===A)??null,M=j&&w?.id===j.id?w:j,[N,P]=(0,_.useState)(!1),F=[],I=[];if(M)for(let t of e)t.id!==M.id&&(F.push(t.id),t.alias&&I.push(t.alias));let L=(0,_.useCallback)(e=>{if(e!==A){if(!N){y(e),T(null);return}x(e)}},[A,N]),R=()=>{b!==void 0&&(y(b),T(null),P(!1),x(void 0))},z=()=>x(void 0),B=b!==void 0&&N,V=!a&&e.length===0;return(0,Y.jsxs)(`div`,{className:`combos-workspace-root`,children:[(0,Y.jsxs)(`aside`,{className:`combos-workspace-rail`,"aria-label":p(`cws.railAria`),children:[(0,Y.jsxs)(`div`,{className:`combos-workspace-rail-header`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`div`,{className:`combos-workspace-rail-title`,children:p(`nav.combos`)}),(0,Y.jsx)(`div`,{className:`combos-workspace-rail-count`,children:e.length})]}),(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>{if(V){document.getElementById(`cwi-edit-id`)?.focus();return}l()},"aria-label":p(`cws.add`),children:[(0,Y.jsx)(ue,{width:14,height:14}),` `,p(`cws.add`)]})]}),e.length>0&&(0,Y.jsx)(`div`,{className:`cwi-search-row`,children:(0,Y.jsxs)(`div`,{className:`cwi-search-wrap`,children:[(0,Y.jsx)(ye,{className:`cwi-search-icon`,"aria-hidden":`true`}),(0,Y.jsx)(`input`,{className:`input cwi-search-input`,value:h,onChange:e=>g(e.target.value),placeholder:p(`cws.searchPlaceholder`),"aria-label":p(`cws.searchPlaceholder`)})]})}),(0,Y.jsx)(`div`,{className:`combos-workspace-rail-list`,children:D.length===0&&e.length>0?(0,Y.jsx)(`p`,{className:`muted`,style:{padding:`16px`},children:p(`cws.noSearchResults`)}):(0,Y.jsx)(Y.Fragment,{children:[[`failover`,O.failover,`cws.group.failover`],[`round-robin`,O.roundRobin,`cws.group.roundRobin`],[`other`,O.other,`cws.group.other`]].map(([e,t,n])=>t.length>0?(0,Y.jsxs)(`div`,{className:`combos-workspace-rail-group`,children:[(0,Y.jsxs)(`div`,{className:`combos-workspace-rail-group-head`,children:[(0,Y.jsx)(`span`,{className:`pwi-dot`,"aria-hidden":`true`}),p(n),(0,Y.jsx)(`span`,{className:`combos-workspace-rail-count`,children:t.length})]}),t.map(e=>(0,Y.jsxs)(`button`,{type:`button`,className:`combos-workspace-rail-row${A===e.id?` combos-workspace-rail-row--selected`:``}`,onClick:()=>L(e.id),"aria-current":A===e.id?`true`:void 0,children:[(0,Y.jsx)(`span`,{className:`combos-workspace-rail-icon`,"aria-hidden":`true`,children:(0,Y.jsx)(Ie,{width:16,height:16})}),(0,Y.jsx)(`span`,{className:`combos-workspace-rail-name`,children:e.model}),(0,Y.jsx)(`span`,{className:`combos-workspace-rail-meta`,children:e.targets.length===1?p(`cws.targetCountOne`):p(`cws.targetCount`,{count:e.targets.length})}),(0,Y.jsx)(Ce,{className:`combos-workspace-rail-chevron`,"aria-hidden":`true`})]},e.id))]},e):null)})})]}),(0,Y.jsx)(`div`,{className:`combos-workspace-main`,children:M?(0,Y.jsx)(om,{baseline:M,otherIds:F,otherAliases:I,providerMap:m,providerQuotaStates:t,providers:n,models:r,onBack:()=>L(null),onSaved:e=>{P(!1),e.id===M.id?T(e):(y(e.id),T(null)),o()},onRequestRemove:()=>C(M.id),onSave:s,onDirtyChange:P},M.id):V?(0,Y.jsx)(om,{baseline:E,isCreate:!0,otherIds:[],otherAliases:[],providerMap:m,providerQuotaStates:t,providers:n,models:r,onSaved:e=>{P(!1),y(e.id),T(e),f(e.id)},onSave:s,onDirtyChange:P},`first-combo`):(0,Y.jsx)(um,{combos:e,cataloguedComboIds:i,providerMap:m,providerQuotaStates:t,onSelect:e=>L(e),onAdd:l})}),u&&!V&&(0,Y.jsx)(nm,{existingIds:e.map(e=>e.id),existingAliases:k,providerMap:m,providerQuotaStates:t,providers:n,models:r,onClose:d,onSubmit:async e=>{let t=await s(e,!0);return t.ok&&(d(),f(e.id),y(e.id),T(null)),t}}),S&&(0,Y.jsx)(sm,{model:e.find(e=>e.id===S)?.model??wp(S),onCancel:()=>C(null),onConfirm:()=>{(async()=>{let e=await c(S);C(null),e.ok&&(A===S&&(y(null),T(null)),o())})()}}),B&&(0,Y.jsx)(cm,{onKeep:z,onDiscard:R})]})}function fm(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e.error;return typeof t==`string`&&t.trim()?t:void 0}function pm(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&e.success===!0}function mm(e){return Dr(e)?.data??null}function hm(e){return Dr(e)?.cachedAt??null}function gm({apiBase:e,active:t=!0,onCountChange:n}){let r=Q(),i=`ocx.combos.workspace.v1:${e}`,a=(0,_.useMemo)(()=>mm(i),[i]),[o,s]=(0,_.useState)(a??null),[c,l]=(0,_.useState)(``),[u,d]=(0,_.useState)(!1),[f,p]=(0,_.useState)(!1),m=(e,t)=>{l(e),d(t)};(0,_.useEffect)(()=>{if(!c||!u)return;let e=window.setTimeout(()=>{l(``),d(!1)},5e3);return()=>window.clearTimeout(e)},[c,u]);let h=(0,_.useCallback)(async t=>{let[n,r,a]=await Promise.all([fetch(`${e}/api/combos`,{signal:t}),fetch(`${e}/api/config`,{signal:t}),fetch(`${e}/api/models`,{signal:t})]);if(!n.ok||!r.ok||!a.ok)throw Error(`combo workspace load failed`);let o=await n.json(),c=await r.json(),l=await a.json(),u=Array.isArray(l)?l:Array.isArray(l?.models)?l.models:[],d=Mp(o),f=c.providers??{},p=Ti(f),m=Object.entries(f).map(([e,t])=>({name:e,disabled:!!t.disabled,hiddenFromPicker:!Object.hasOwn(p,e),authMode:t.authMode,adapter:t.adapter,baseUrl:t.baseUrl})),h=[],g=new Set;for(let e of u){if(!e||typeof e!=`object`)continue;let t=e;if(typeof t.provider!=`string`||typeof t.id!=`string`)continue;let n=t.provider.trim(),r=t.id.trim();if(!n||!r)continue;if(n===`combo`){g.add(r);continue}if(t.disabled===!0)continue;let i=Array.isArray(t.reasoningEfforts)?t.reasoningEfforts.filter(e=>typeof e==`string`):void 0,a=Array.isArray(t.inputModalities)?t.inputModalities.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean):void 0;h.push({provider:n,id:r,namespaced:typeof t.namespaced==`string`?t.namespaced:void 0,...i?{reasoningEfforts:i}:{},...a&&a.length>0?{inputModalities:a}:{}})}for(let[e,t]of Object.entries(f)){let n=typeof t.defaultModel==`string`?t.defaultModel.trim():``;!n||t.disabled||h.some(t=>t.provider===e&&t.id===n)||h.push({provider:e,id:n,namespaced:`${e}/${n}`})}let _={combos:d,providers:m,models:h,cataloguedComboIds:[...g]};return Or(i,_),s(_),_},[e,i]),g=jr(i,[e],h,{isEmpty:()=>!1,initialData:a??void 0,initialDataCachedAt:hm(i),staleAfterMs:6e4,enabled:t}),{state:v}=g,[y,b]=(0,_.useState)(()=>Date.now()),x=(0,_.useCallback)(async t=>{let n=await fetch(`${e}/api/provider-quotas`,{signal:t});if(!n.ok)throw Error(`combo quota load failed`);let r=await n.json();return t?.aborted||b(Date.now()),r&&typeof r==`object`&&!Array.isArray(r)?r:{}},[e]),S=jr(`ocx.combos.provider-quotas.v1:${e}`,[e],x,{isEmpty:()=>!1,pollMs:6e4,pauseWhenHidden:!0,enabled:t}),C=t&&S.lastAttemptOk?S.data?.reports:void 0,w=Bp(C,y),T=zp(C,y);(0,_.useEffect)(()=>{if(!t)return;let e=()=>b(Date.now()),n=window.setTimeout(e,T===void 0?0:Math.max(0,T-Date.now())),r=()=>{document.visibilityState===`visible`&&e()};return document.addEventListener(`visibilitychange`,r),()=>{window.clearTimeout(n),document.removeEventListener(`visibilitychange`,r)}},[t,e,S.data,S.lastAttemptOk,T]);let E=v.data??o??void 0,D=E?.combos??[];(0,_.useEffect)(()=>{E&&n?.(D.length)},[D.length,E,n]);let O=E?.providers??[],k=E?.models??[],A=new Set(E?.cataloguedComboIds??[]),j=async(t,n,i)=>{try{let a=await fetch(`${e}/api/combos`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(Wp(t,i?{renameFrom:i}:{}))}),o=a.ok?await a.json():await a.json().catch(()=>null),s=fm(o);if(!a.ok||s||!pm(o)){let e=s||r(`cws.saveFailed`);return m(e,!1),{ok:!1,error:e}}return g.refresh(),m(i?r(`cws.renamed`,{from:wp(i),to:t.model}):n?r(`cws.created`,{model:t.model}):r(`cws.saved`),!0),{ok:!0}}catch{let e=r(`cws.saveFailed`);return m(e,!1),{ok:!1,error:e}}},M=async t=>{try{let n=await fetch(`${e}/api/combos?id=${encodeURIComponent(t)}`,{method:`DELETE`}),i=n.ok?await n.json():await n.json().catch(()=>null),a=fm(i);if(!n.ok||a||!pm(i)){let e=a||r(`cws.removeFailed`);return m(e,!1),{ok:!1,error:e}}return g.refresh(),m(r(`cws.removed`,{id:t}),!0),{ok:!0}}catch{let e=r(`cws.removeFailed`);return m(e,!1),{ok:!1,error:e}}};if(v.showSkeleton&&!E)return(0,Y.jsx)(ep,{label:r(`cws.loading`),rows:5});if(v.kind===`failed-cold`&&!E){let e=v.error instanceof Error?v.error.message:r(`cws.loadFailed`);return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)($,{tone:`err`,children:e}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>g.refresh(),children:r(`common.retry`)})]})}return(0,Y.jsxs)(`div`,{className:`combos-workspace-shell`,children:[c&&(0,Y.jsx)(`div`,{className:`combos-workspace-shell-banner`,children:(0,Y.jsx)($,{tone:u?`ok`:`err`,children:c})}),v.showError&&(0,Y.jsx)(`div`,{className:`combos-workspace-shell-banner`,children:(0,Y.jsx)($,{tone:`err`,children:r(`cws.loadFailed`)})}),(0,Y.jsxs)(`div`,{className:`combos-workspace-shell-body`,"aria-busy":v.refreshing,children:[(0,Y.jsx)(`span`,{className:`sr-only`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:v.refreshing?r(`common.loading`):``}),(0,Y.jsx)(dm,{combos:D,providerQuotaStates:w,providers:O,models:k,cataloguedComboIds:A,loading:!1,onRefresh:()=>{g.refresh(),S.refresh()},onSave:j,onRemove:M,onAdd:()=>p(!0),adding:f,onCloseAdd:()=>p(!1),onCreated:()=>g.refresh()})]})]})}var _m=0;function vm(){return _m+=1,`candidate-${_m}`}function ym(e,t){return{provider:e,model:t,key:vm()}}function bm(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!=`object`||Array.isArray(n))continue;let e=typeof n.suiteId==`string`?n.suiteId.trim():``,r=n.evidenceLayer;!e||r!==`protocol_conformance`&&r!==`live_route_compatibility`||t.push({suiteId:e,evidenceLayer:r})}return t}function xm(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n={requiredSuites:bm(t.requiredSuites)};return(t.minStatus===`PROBED`||t.minStatus===`VERIFIED`)&&(n.minStatus=t.minStatus),typeof t.maxEvidenceAgeMs==`number`&&Number.isFinite(t.maxEvidenceAgeMs)&&t.maxEvidenceAgeMs>=0&&(n.maxEvidenceAgeMs=t.maxEvidenceAgeMs),(t.unknownEvidence===`allow`||t.unknownEvidence===`penalize`||t.unknownEvidence===`exclude`)&&(n.unknownEvidence=t.unknownEvidence),(t.degradedEvidence===`allow`||t.degradedEvidence===`penalize`||t.degradedEvidence===`exclude`)&&(n.degradedEvidence=t.degradedEvidence),n}var Sm={latency:`0.55`,health:`0.25`,cost:`0.1`,quota:`0.1`},Cm={capability:`exclude`,health:`penalize`,quota:`penalize`,cost:`penalize`};function wm(e){return e===!0?`true`:e===!1?`false`:``}function Tm(e){return e===void 0?``:String(e)}function Em(e=``,t=``){return{id:``,alias:``,candidates:[ym(e,t)],require:{minContextWindow:``,minQuotaHeadroom:``,tools:``,imageInput:``,structuredOutput:``,reasoningEffort:``,serviceTier:``,localOnly:``,remoteAllowed:``,encryptedCodexTasks:``},optimize:{...Sm},limits:{maxEstimatedCostUsd:``,onUnknownCost:`allow`},unknownEvidence:{...Cm},compatibility:{enabled:!1,requiredSuites:[],minStatus:``,maxEvidenceAgeMs:``,unknownEvidence:`exclude`,degradedEvidence:`penalize`}}}function Dm(e){let t=xm(e.compatibility);return{id:e.id,alias:e.alias??``,candidates:e.candidates.map(e=>({...e,key:vm()})),require:{minContextWindow:Tm(e.require.minContextWindow),minQuotaHeadroom:Tm(e.require.minQuotaHeadroom),tools:wm(e.require.tools),imageInput:wm(e.require.imageInput),structuredOutput:wm(e.require.structuredOutput),reasoningEffort:e.require.reasoningEffort??``,serviceTier:e.require.serviceTier??``,localOnly:wm(e.require.localOnly),remoteAllowed:wm(e.require.remoteAllowed),encryptedCodexTasks:wm(e.require.encryptedCodexTasks)},optimize:{latency:String(e.optimize.latency),health:String(e.optimize.health),cost:String(e.optimize.cost),quota:String(e.optimize.quota)},limits:{maxEstimatedCostUsd:Tm(e.limits.maxEstimatedCostUsd),onUnknownCost:e.limits.onUnknownCost===`exclude`?`exclude`:`allow`},unknownEvidence:{...e.unknownEvidence},compatibility:{enabled:!!t,requiredSuites:t?.requiredSuites??[],minStatus:t?.minStatus??``,maxEvidenceAgeMs:Tm(t?.maxEvidenceAgeMs),unknownEvidence:t?.unknownEvidence??`exclude`,degradedEvidence:t?.degradedEvidence??`penalize`}}}function Om(e){let t=e.trim();return t?Number(t):void 0}function km(e){if(e===`true`)return!0;if(e===`false`)return!1}function Am(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function jm(e,t,n){let r=Am({minContextWindow:Om(e.require.minContextWindow),minQuotaHeadroom:Om(e.require.minQuotaHeadroom),tools:km(e.require.tools),imageInput:km(e.require.imageInput),structuredOutput:km(e.require.structuredOutput),reasoningEffort:e.require.reasoningEffort.trim()||void 0,serviceTier:e.require.serviceTier.trim()||void 0,localOnly:km(e.require.localOnly),remoteAllowed:km(e.require.remoteAllowed),encryptedCodexTasks:km(e.require.encryptedCodexTasks)}),i=Om(e.limits.maxEstimatedCostUsd),a=e.compatibility.enabled?Am({requiredSuites:e.compatibility.requiredSuites,minStatus:e.compatibility.minStatus||void 0,maxEvidenceAgeMs:Om(e.compatibility.maxEvidenceAgeMs),unknownEvidence:e.compatibility.unknownEvidence,degradedEvidence:e.compatibility.degradedEvidence}):void 0,o=Am({maxEstimatedCostUsd:i,onUnknownCost:e.limits.onUnknownCost===`exclude`?`exclude`:void 0});return{mode:t,id:e.id.trim(),...t===`update`&&n?{expectedRevision:n}:{},profile:{...e.alias.trim()?{alias:e.alias.trim()}:{},candidates:e.candidates.map(e=>({provider:e.provider.trim(),model:e.model.trim()})),...Object.keys(r).length>0?{require:r}:{},optimize:{latency:Number(e.optimize.latency),health:Number(e.optimize.health),cost:Number(e.optimize.cost),quota:Number(e.optimize.quota)},...Object.keys(o).length>0?{limits:o}:{},unknownEvidence:{...e.unknownEvidence},...a&&Object.keys(a).length>0?{compatibility:a}:{}}}}function Mm(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e.error;if(typeof t==`string`&&t.trim())return t;if(t&&typeof t==`object`&&!Array.isArray(t)){let e=t.message;if(typeof e==`string`&&e.trim())return e}}function Nm(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&e.success===!0}function Pm(e,t){return e.filter(e=>e.provider===t)}var Fm={en:{maxEvidenceAgeMs:`Maximum evidence age (ms)`,unknownEvidence:`Unknown evidence`,degradedEvidence:`Degraded evidence`},de:{maxEvidenceAgeMs:`Maximales Evidenzalter (ms)`,unknownEvidence:`Unbekannte Evidenz`,degradedEvidence:`Eingeschränkte Evidenz`},fr:{maxEvidenceAgeMs:`Âge maximal des preuves (ms)`,unknownEvidence:`Preuves inconnues`,degradedEvidence:`Preuves dégradées`},ko:{maxEvidenceAgeMs:`최대 증거 유효 기간 (ms)`,unknownEvidence:`알 수 없는 증거`,degradedEvidence:`저하된 증거`},zh:{maxEvidenceAgeMs:`证据最大有效期(毫秒)`,unknownEvidence:`未知证据`,degradedEvidence:`降级证据`},"zh-TW":{maxEvidenceAgeMs:`證據最大有效期限(毫秒)`,unknownEvidence:`未知證據`,degradedEvidence:`降級證據`},ru:{maxEvidenceAgeMs:`Максимальный возраст доказательств (мс)`,unknownEvidence:`Неизвестные доказательства`,degradedEvidence:`Ухудшенные доказательства`},ja:{maxEvidenceAgeMs:`エビデンスの最大有効期間 (ms)`,unknownEvidence:`不明なエビデンス`,degradedEvidence:`低下したエビデンス`},tr:{maxEvidenceAgeMs:`Maksimum kanıt yaşı (ms)`,unknownEvidence:`Bilinmeyen kanıt`,degradedEvidence:`Bozulmuş kanıt`}},Im=[`tools`,`imageInput`,`structuredOutput`,`localOnly`,`remoteAllowed`,`encryptedCodexTasks`],Lm=[`reasoningEffort`,`serviceTier`],Rm={minContextWindow:{min:1,max:void 0,step:1},minQuotaHeadroom:{min:0,max:1,step:`any`}},zm=Object.keys(Rm),Bm=[`latency`,`health`,`cost`,`quota`],Vm=[`capability`,`health`,`quota`,`cost`],Hm=[`allow`,`penalize`,`exclude`],Um=[`allow`,`exclude`];function Wm(e){return`${e.evidenceLayer}:${e.suiteId}`}function Gm(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Km(e){let t=new Set,n=[];for(let r of e){if(!Gm(r))continue;let e=typeof r.suiteId==`string`?r.suiteId.trim():``,i=r.evidenceLayer;if(!e||i!==`protocol_conformance`&&i!==`live_route_compatibility`)continue;let a={suiteId:e,evidenceLayer:i},o=Wm(a);t.has(o)||(t.add(o),n.push({...a,key:o}))}return n.sort((e,t)=>{let n=e.evidenceLayer.localeCompare(t.evidenceLayer);return n===0?e.suiteId.localeCompare(t.suiteId):n})}function qm(e,t){return e.some(e=>e.suiteId===t.suiteId&&e.evidenceLayer===t.evidenceLayer)}function Jm(e,t){return e===void 0?t:`${Math.round(e)}ms`}function Ym(e,t){return e==null?t:`${Math.round(e*100)}%`}function Xm(e,t,n){switch(e){case`satisfied`:return t(`routing.capOutcome.satisfied`);case`exceeded`:return t(`routing.capOutcome.exceeded`);case`unknown-allowed`:return t(`routing.capOutcome.unknown-allowed`);case`unknown-excluded`:return t(`routing.capOutcome.unknown-excluded`);default:return n}}function Zm(e,t){switch(e){case`capability-unsatisfied`:return t(`routing.exclusion.capability-unsatisfied`);case`unknown-capability`:return t(`routing.exclusion.unknown-capability`);case`cost-limit`:return t(`routing.exclusion.cost-limit`);case`cost-limit-unknown`:return t(`routing.exclusion.cost-limit-unknown`);case`cooldown`:return t(`routing.exclusion.cooldown`);case`unknown-health`:return t(`routing.exclusion.unknown-health`);case`unknown-quota`:return t(`routing.exclusion.unknown-quota`);case`unknown-price`:return t(`routing.exclusion.unknown-price`);default:return t(`routing.exclusion.other`,{code:e})}}function Qm(e){if(!e||typeof e!=`object`||Array.isArray(e))return[];let t=e.profiles;return Array.isArray(t)?t.filter(e=>Gm(e)?typeof e.id==`string`&&typeof e.model==`string`&&typeof e.revision==`string`&&Array.isArray(e.candidates)&&Gm(e.require)&&Gm(e.optimize)&&Gm(e.limits)&&Gm(e.unknownEvidence):!1).map(e=>{let t=xm(`compatibility`in e?e.compatibility:void 0),n={...e};return delete n.compatibility,{...n,alias:e.alias??null,...t?{compatibility:t}:{}}}):[]}function $m(e){let t=Array.isArray(e)?e:e&&typeof e==`object`&&Array.isArray(e.models)?e.models:[],n=new Set,r=[];for(let e of t){if(!e||typeof e!=`object`||Array.isArray(e))continue;let t=typeof e.provider==`string`?e.provider.trim():``,i=typeof e.id==`string`?e.id.trim():``;if(!t||!i||t===`combo`||t===`policy`||e.disabled===!0)continue;let a=JSON.stringify([t,i]);n.has(a)||(n.add(a),r.push({provider:t,id:i}))}return r}function eh(e,t,n){let r=n??t;if(r){let t=e.find(e=>e.id===r);if(t)return t}return e[0]??null}function th({apiBase:e,active:t=!0,onCountChange:n}){let{locale:r,t:i}=ut(),a=Fm[r],o=i(`routing.unavailable`),[s,c]=(0,_.useState)([]),[l,u]=(0,_.useState)(null),[d,f]=(0,_.useState)([]),[p,m]=(0,_.useState)({}),[h,g]=(0,_.useState)([]),[v,y]=(0,_.useState)(``),[b,x]=(0,_.useState)(null),[S,C]=(0,_.useState)(null),[w,T]=(0,_.useState)(null),[E,D]=(0,_.useState)(!1),[O,k]=(0,_.useState)(``),[A,j]=(0,_.useState)(!1),[M,N]=(0,_.useState)(!1),[P,F]=(0,_.useState)(!1),[I,L]=(0,_.useState)(null),[R,z]=(0,_.useState)(``),[B,V]=(0,_.useState)(!1),[H,U]=(0,_.useState)([]),[W,G]=(0,_.useState)(!1),K=(0,_.useRef)(null),q=(0,_.useRef)(0),J=(0,_.useRef)(null),X=(0,_.useRef)(!0),ee=(0,_.useCallback)(()=>{X.current=!1,J.current?.abort(),q.current++},[]),te=(0,_.useRef)(0),ne=(0,_.useCallback)((e,t)=>{T({message:e,ok:t})},[]);(0,_.useEffect)(()=>{if(!w?.ok)return;let e=window.setTimeout(()=>T(null),5e3);return()=>window.clearTimeout(e)},[w]);let Z=(0,_.useCallback)(()=>{te.current+=1,L(null),z(``),V(!1)},[]),re=(0,_.useCallback)(e=>{K.current=e,x(e),C(e?Dm(e):null),T(null),Z()},[Z]),ie=(0,_.useCallback)(async t=>{if(!X.current)return;J.current?.abort();let n=new AbortController;J.current=n;let{signal:r}=n,i=++q.current;y(``);try{let[n,a,o,s,l]=await Promise.all([fetch(`${e}/api/routing-profiles`,{signal:r}),fetch(`${e}/api/routing-analytics`,{signal:r}),fetch(`${e}/api/config`,{signal:r}),fetch(`${e}/api/models`,{signal:r}),fetch(`${e}/api/lab/catalog`,{signal:r})]);if(!n.ok)throw Error(`load-${n.status}`);let[d,p,h,_,v]=await Promise.all([n.json(),a.ok?a.json():Promise.resolve(null),o.ok?o.json():Promise.resolve({}),s.ok?s.json():Promise.resolve([]),l.ok?l.json().catch(()=>null):Promise.resolve(null)]);if(i!==q.current)return;let y=Qm(d),b=K.current,S=eh(y,b?.id??null,t),w=h.providers??{},T=Object.entries(w).filter(([,e])=>e.disabled!==!0).map(([e])=>e).sort((e,t)=>e<t?-1:+(e>t)),E=Object.fromEntries(Object.entries(w).filter(([,e])=>e.disabled!==!0&&typeof e.defaultModel==`string`).map(([e,t])=>[e,t.defaultModel.trim()]));K.current=S,c(y),x(S),C(S?Dm(S):null),u(p),f(T),m(E),g($m(_)),v&&Array.isArray(v.scenarios)?(U(Km(v.scenarios)),G(!1)):(U([]),G(!0)),(!b||!S||b.id!==S.id||b.revision!==S.revision)&&Z()}catch(e){if(i!==q.current||r.aborted)return;y(e instanceof Error?e.message:String(e))}finally{J.current===n&&(J.current=null)}},[e,Z]);(0,_.useEffect)(()=>{if(!t){ee();return}X.current=!0;let e=window.setTimeout(()=>void ie(),0);return()=>{window.clearTimeout(e),ee()}},[t,ee,ie]),(0,_.useEffect)(()=>{n?.(s.length)},[n,s.length]);let ae=d[0]??``,oe=p[ae]??Pm(h,ae)[0]?.id??``,se=()=>{K.current=null,x(null),C(Em(ae,oe)),T(null),Z()},ce=()=>{if(b){C(Dm(b)),T(null);return}re(s[0]??null)},le=async()=>{if(!(!S||E)){D(!0),T(null);try{let t=jm(S,b?`update`:`create`,b?.revision),n=await fetch(`${e}/api/routing-profiles`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(t)}),r=await Lt(n);if(!n.ok){let e=await n.json().catch(()=>null);ne(Mm(e)??i(`routing.loadFailed`),!1);return}if(!Nm(r)){ne(Mm(r)??i(`routing.loadFailed`),!1);return}await ie(t.id),ne(i(`common.ok`),!0)}catch(e){ne(e instanceof Error?e.message:i(`routing.loadFailed`),!1)}finally{D(!1)}}},ue=async()=>{if(!(!b||E)&&window.confirm(i(`routing.removeConfirm`,{id:b.id}))){D(!0),T(null);try{let t=await fetch(`${e}/api/routing-profiles?id=${encodeURIComponent(b.id)}`,{method:`DELETE`}),n=await Lt(t);if(!t.ok){let e=await t.json().catch(()=>null);ne(Mm(e)??i(`routing.loadFailed`),!1);return}if(!Nm(n)){ne(Mm(n)??i(`routing.loadFailed`),!1);return}K.current=null,await ie(),ne(i(`common.ok`),!0)}catch(e){ne(e instanceof Error?e.message:i(`routing.loadFailed`),!1)}finally{D(!1)}}},de=(e,t,n)=>{C(r=>{if(!r)return r;let i=r.candidates.map((r,i)=>i===e?t===`provider`?{...r,provider:n,model:p[n]??Pm(h,n)[0]?.id??``}:{...r,model:n}:r);return{...r,candidates:i}})},fe=()=>{C(e=>e&&{...e,candidates:[...e.candidates,ym(ae,oe)]})},pe=e=>{C(t=>t&&{...t,candidates:t.candidates.filter((t,n)=>n!==e)})},me=async()=>{if(!b)return;let t=++te.current;V(!0),L(null),z(``);try{let n={},r=O.trim()?Number(O.trim()):NaN;Number.isFinite(r)&&r>0&&(n.contextWindow=r),A&&(n.toolsRequired=!0),M&&(n.imageInputRequired=!0),P&&(n.structuredOutputRequired=!0);let a=await fetch(`${e}/api/routing-profiles/dry-run`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({profile:b.id,evidence:n})});if(t!==te.current)return;if(!a.ok){let e=await a.json().catch(()=>null);if(t!==te.current)return;z(Mm(e)??i(`routing.dryRunError`,{status:a.status}));return}let o=await a.json();if(t!==te.current)return;L(o)}catch(e){if(t!==te.current)return;z(e instanceof Error?e.message:String(e))}finally{t===te.current&&V(!1)}},he=S?.candidates.map(e=>Pm(h,e.provider))??[];return(0,Y.jsxs)(`div`,{className:`page`,"data-page":`routing`,children:[(0,Y.jsxs)(`div`,{className:`row`,style:{display:`flex`,gap:8,justifyContent:`flex-end`,marginBottom:12},children:[(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:se,children:[(0,Y.jsx)(`span`,{"aria-hidden":`true`,children:`+`}),` `,i(`routing.createProfile`)]}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void ie(),children:i(`common.retry`)})]}),v?(0,Y.jsxs)($,{tone:`err`,children:[i(`routing.loadFailed`),`: `,v]}):null,w?(0,Y.jsx)($,{tone:w.ok?`ok`:`err`,children:w.message}):null,s.length>0?(0,Y.jsx)(`div`,{className:`panel`,style:{display:`flex`,flexDirection:`column`,gap:12},children:s.map(e=>(0,Y.jsx)(`button`,{type:`button`,className:`model-card`,style:{textAlign:`left`,cursor:`pointer`},onClick:()=>re(e),"aria-pressed":b?.id===e.id,children:(0,Y.jsxs)(`div`,{className:`card-badges`,children:[(0,Y.jsx)(`strong`,{children:e.id}),(0,Y.jsx)(`span`,{className:`badge badge-muted`,children:e.model}),(0,Y.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.revision`),`: `,e.revision]})]})},e.id))}):null,S?(0,Y.jsxs)(`form`,{className:`panel`,style:{marginTop:14,display:`flex`,flexDirection:`column`,gap:16},onSubmit:e=>{e.preventDefault(),le()},children:[(0,Y.jsxs)(`div`,{className:`page-head`,children:[(0,Y.jsxs)(`h3`,{children:[i(`routing.detail`),`: `,b?.model??(0,Y.jsx)(`code`,{children:`policy/…`})]}),b?(0,Y.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.revision`),`: `,b.revision]}):null]}),(0,Y.jsxs)(`div`,{className:`model-grid`,children:[(0,Y.jsxs)(`label`,{className:`field-label`,children:[(0,Y.jsx)(`code`,{children:`id`}),(0,Y.jsx)(`input`,{className:`input`,required:!0,disabled:b!==null,value:S.id,onChange:e=>C(t=>t&&{...t,id:e.target.value})})]}),(0,Y.jsxs)(`label`,{className:`field-label`,children:[(0,Y.jsx)(`code`,{children:`alias`}),(0,Y.jsx)(`input`,{className:`input`,value:S.alias,onChange:e=>C(t=>t&&{...t,alias:e.target.value})})]})]}),(0,Y.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,Y.jsx)(`legend`,{className:`field-label`,children:i(`routing.candidates`)}),(0,Y.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:10},children:[S.candidates.map((e,t)=>{let n=[...new Set([e.provider,...d])].filter(Boolean),r=`routing-model-options-${t}`;return(0,Y.jsxs)(`div`,{className:`model-card`,children:[(0,Y.jsxs)(`div`,{className:`model-grid`,children:[(0,Y.jsxs)(`label`,{className:`field-label`,children:[(0,Y.jsx)(`code`,{children:`provider`}),(0,Y.jsxs)(`select`,{className:`input`,required:!0,value:e.provider,onChange:e=>de(t,`provider`,e.target.value),children:[(0,Y.jsx)(`option`,{value:``,disabled:!0,children:i(`routing.none`)}),n.map(e=>(0,Y.jsx)(`option`,{value:e,children:e},e))]})]}),(0,Y.jsxs)(`label`,{className:`field-label`,children:[(0,Y.jsx)(`code`,{children:`model`}),(0,Y.jsx)(`input`,{className:`input`,required:!0,list:r,value:e.model,onChange:e=>de(t,`model`,e.target.value)}),(0,Y.jsx)(`datalist`,{id:r,children:he[t]?.map(e=>(0,Y.jsx)(`option`,{value:e.id},e.id))})]})]}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:S.candidates.length===1,onClick:()=>pe(t),"aria-label":i(`routing.removeCandidate`,{provider:e.provider,model:e.model}),children:i(`common.remove`)})]},e.key)}),(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:fe,children:[(0,Y.jsx)(`span`,{"aria-hidden":`true`,children:`+`}),` `,i(`routing.candidate`)]})]})]}),(0,Y.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,Y.jsx)(`legend`,{className:`field-label`,children:i(`routing.require`)}),(0,Y.jsxs)(`div`,{className:`model-grid`,children:[zm.map(e=>(0,Y.jsxs)(`label`,{className:`field-label`,children:[(0,Y.jsx)(`code`,{children:e}),(0,Y.jsx)(`input`,{className:`input`,type:`number`,min:Rm[e].min,max:Rm[e].max,step:Rm[e].step,value:S.require[e],onChange:t=>C(n=>n&&{...n,require:{...n.require,[e]:t.target.value}})})]},e)),Lm.map(e=>(0,Y.jsxs)(`label`,{className:`field-label`,children:[(0,Y.jsx)(`code`,{children:e}),(0,Y.jsx)(`input`,{className:`input`,value:S.require[e],onChange:t=>C(n=>n&&{...n,require:{...n.require,[e]:t.target.value}})})]},e)),Im.map(e=>(0,Y.jsxs)(`label`,{className:`field-label`,children:[(0,Y.jsx)(`code`,{children:e}),(0,Y.jsxs)(`select`,{className:`input`,value:S.require[e],onChange:t=>C(n=>n&&{...n,require:{...n.require,[e]:t.target.value}}),children:[(0,Y.jsx)(`option`,{value:``,children:i(`routing.none`)}),(0,Y.jsx)(`option`,{value:`true`,children:i(`routing.yes`)}),(0,Y.jsx)(`option`,{value:`false`,children:i(`routing.no`)})]})]},e))]})]}),(0,Y.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,Y.jsx)(`legend`,{className:`field-label`,children:i(`routing.optimize`)}),(0,Y.jsx)(`div`,{className:`model-grid`,children:Bm.map(e=>(0,Y.jsxs)(`label`,{className:`field-label`,children:[(0,Y.jsx)(`code`,{children:e}),(0,Y.jsx)(`input`,{className:`input`,type:`number`,min:0,step:`any`,required:!0,value:S.optimize[e],onChange:t=>C(n=>n&&{...n,optimize:{...n.optimize,[e]:t.target.value}})})]},e))})]}),(0,Y.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,Y.jsx)(`legend`,{className:`field-label`,children:i(`routing.limits`)}),(0,Y.jsxs)(`label`,{className:`field-label`,children:[(0,Y.jsx)(`code`,{children:`maxEstimatedCostUsd`}),(0,Y.jsx)(`input`,{className:`input`,type:`number`,min:0,step:`any`,value:S.limits.maxEstimatedCostUsd,onChange:e=>C(t=>t&&{...t,limits:{...t.limits,maxEstimatedCostUsd:e.target.value}})})]}),(0,Y.jsxs)(`label`,{className:`field-label`,children:[(0,Y.jsx)(`code`,{children:`onUnknownCost`}),(0,Y.jsx)(`select`,{className:`input`,value:S.limits.onUnknownCost,onChange:e=>C(t=>t&&{...t,limits:{...t.limits,onUnknownCost:e.target.value}}),children:Um.map(e=>(0,Y.jsx)(`option`,{value:e,children:i(`routing.unknownEvidence.${e}`)},e))})]})]}),(0,Y.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,Y.jsx)(`legend`,{className:`field-label`,children:i(`routing.unknownEvidence`)}),(0,Y.jsx)(`div`,{className:`model-grid`,children:Vm.map(e=>(0,Y.jsxs)(`label`,{className:`field-label`,children:[(0,Y.jsx)(`code`,{children:e}),(0,Y.jsx)(`select`,{className:`input`,value:S.unknownEvidence[e],onChange:t=>C(n=>n&&{...n,unknownEvidence:{...n.unknownEvidence,[e]:t.target.value}}),children:Hm.map(e=>(0,Y.jsx)(`option`,{value:e,children:i(`routing.unknownEvidence.${e}`)},e))})]},e))})]}),(0,Y.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,Y.jsx)(`legend`,{className:`field-label`,children:i(`routing.compatibility.title`)}),(0,Y.jsxs)(`label`,{className:`checkbox`,children:[(0,Y.jsx)(`input`,{type:`checkbox`,checked:S.compatibility.enabled,onChange:e=>C(t=>t&&{...t,compatibility:{...t.compatibility,enabled:e.target.checked}})}),i(`routing.compatibility.enabled`)]}),S.compatibility.enabled?(0,Y.jsxs)(`div`,{className:`model-grid`,style:{marginTop:10},children:[(0,Y.jsxs)(`div`,{className:`field-label`,style:{gridColumn:`1 / -1`},children:[i(`routing.compatibility.requiredSuites`),W?(0,Y.jsx)(`div`,{style:{marginTop:6},children:(0,Y.jsx)($,{tone:`warn`,children:i(`routing.compatibility.catalogUnavailable`)})}):null,H.length>0?(0,Y.jsx)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:4,marginTop:6},children:H.map(e=>(0,Y.jsxs)(`label`,{className:`checkbox`,children:[(0,Y.jsx)(`input`,{type:`checkbox`,checked:qm(S.compatibility.requiredSuites,e),onChange:t=>C(n=>{if(!n)return n;let r=t.target.checked?[...n.compatibility.requiredSuites,{suiteId:e.suiteId,evidenceLayer:e.evidenceLayer}]:n.compatibility.requiredSuites.filter(t=>t.suiteId!==e.suiteId||t.evidenceLayer!==e.evidenceLayer);return{...n,compatibility:{...n.compatibility,requiredSuites:r}}})}),(0,Y.jsxs)(`span`,{children:[e.suiteId,` `,(0,Y.jsxs)(`span`,{className:`muted`,children:[`(`,i(`routing.compatibility.layer.${e.evidenceLayer}`),`)`]})]})]},e.key))}):null]}),(0,Y.jsxs)(`label`,{className:`field-label`,children:[i(`routing.compatibility.minStatus`),(0,Y.jsxs)(`select`,{className:`input`,value:S.compatibility.minStatus,onChange:e=>C(t=>t&&{...t,compatibility:{...t.compatibility,minStatus:e.target.value}}),children:[(0,Y.jsx)(`option`,{value:``,children:i(`routing.none`)}),(0,Y.jsx)(`option`,{value:`PROBED`,children:i(`lab.verdict.PROBED`)}),(0,Y.jsx)(`option`,{value:`VERIFIED`,children:i(`lab.verdict.VERIFIED`)})]})]}),(0,Y.jsxs)(`label`,{className:`field-label`,children:[a.maxEvidenceAgeMs,(0,Y.jsx)(`input`,{className:`input`,type:`number`,min:0,value:S.compatibility.maxEvidenceAgeMs,onChange:e=>C(t=>t&&{...t,compatibility:{...t.compatibility,maxEvidenceAgeMs:e.target.value}})})]}),(0,Y.jsxs)(`label`,{className:`field-label`,children:[a.unknownEvidence,(0,Y.jsx)(`select`,{className:`input`,value:S.compatibility.unknownEvidence,onChange:e=>C(t=>t&&{...t,compatibility:{...t.compatibility,unknownEvidence:e.target.value}}),children:Hm.map(e=>(0,Y.jsx)(`option`,{value:e,children:i(`routing.unknownEvidence.${e}`)},e))})]}),(0,Y.jsxs)(`label`,{className:`field-label`,children:[a.degradedEvidence,(0,Y.jsx)(`select`,{className:`input`,value:S.compatibility.degradedEvidence,onChange:e=>C(t=>t&&{...t,compatibility:{...t.compatibility,degradedEvidence:e.target.value}}),children:Hm.map(e=>(0,Y.jsx)(`option`,{value:e,children:i(`routing.unknownEvidence.${e}`)},e))})]})]}):null]}),(0,Y.jsxs)(`div`,{style:{display:`flex`,gap:8,flexWrap:`wrap`},children:[(0,Y.jsx)(`button`,{type:`submit`,className:`btn btn-primary`,disabled:E,children:i(E?`common.saving`:`common.save`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:E,onClick:ce,children:i(`common.cancel`)}),b?(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:E,onClick:()=>void ue(),children:i(`common.remove`)}):null]})]}):null,b&&(0,Y.jsxs)(`div`,{className:`panel`,style:{marginTop:14,display:`flex`,flexDirection:`column`,gap:10},children:[(0,Y.jsx)(`h3`,{children:i(`routing.dryRun`)}),(0,Y.jsxs)(`label`,{className:`field-label`,htmlFor:`routing-context`,children:[i(`routing.dryRunContext`),(0,Y.jsx)(`input`,{id:`routing-context`,className:`input`,type:`number`,min:1,value:O,onChange:e=>{k(e.target.value),Z()}})]}),(0,Y.jsxs)(`label`,{className:`checkbox`,children:[(0,Y.jsx)(`input`,{type:`checkbox`,checked:A,onChange:e=>{j(e.target.checked),Z()}}),i(`routing.dryRunTools`)]}),(0,Y.jsxs)(`label`,{className:`checkbox`,children:[(0,Y.jsx)(`input`,{type:`checkbox`,checked:M,onChange:e=>{N(e.target.checked),Z()}}),i(`routing.dryRunImage`)]}),(0,Y.jsxs)(`label`,{className:`checkbox`,children:[(0,Y.jsx)(`input`,{type:`checkbox`,checked:P,onChange:e=>{F(e.target.checked),Z()}}),i(`routing.dryRunStructured`)]}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!b||B,onClick:()=>void me(),children:i(`routing.dryRunRun`)}),R?(0,Y.jsx)($,{tone:`err`,children:R}):null,I?(0,Y.jsxs)(`table`,{className:`tbl`,children:[(0,Y.jsx)(`thead`,{children:(0,Y.jsxs)(`tr`,{children:[(0,Y.jsx)(`th`,{children:i(`routing.candidate`)}),(0,Y.jsx)(`th`,{children:i(`routing.eligible`)}),(0,Y.jsx)(`th`,{children:i(`routing.exclusions`)}),(0,Y.jsx)(`th`,{children:i(`routing.costCap`)}),(0,Y.jsx)(`th`,{children:i(`routing.score`)})]})}),(0,Y.jsx)(`tbody`,{children:I.candidates.map((e,t)=>(0,Y.jsxs)(`tr`,{children:[(0,Y.jsxs)(`td`,{children:[e.provider,`/`,e.model,t===I.selectedIndex?` ✓ (${i(`routing.selected`)})`:``]}),(0,Y.jsx)(`td`,{children:e.eligible?i(`routing.yes`):i(`routing.no`)}),(0,Y.jsx)(`td`,{children:e.exclusions.map(e=>Zm(e.code,i)).join(`, `)||i(`routing.none`)}),(0,Y.jsx)(`td`,{children:Xm(e.cost?.capOutcome,i,o)}),(0,Y.jsx)(`td`,{children:e.score?e.score.total.toFixed(3):o})]},`${e.provider}/${e.model}`))})]}):null]}),s.length>0&&(0,Y.jsxs)(`div`,{className:`panel`,style:{marginTop:14,display:`flex`,flexDirection:`column`,gap:10},children:[(0,Y.jsx)(`h3`,{children:i(`routing.analytics`)}),l?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{className:`card-badges`,children:[(0,Y.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsTotal`),`: `,l.totalRequests]}),(0,Y.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsSuccessRate`),`: `,Ym(l.successRate,o)]}),(0,Y.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsFallbackRate`),`: `,Ym(l.fallbackRate,o)]}),(0,Y.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsP50`),`: `,Jm(l.durationMs.p50,o)]}),(0,Y.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsP95`),`: `,Jm(l.durationMs.p95,o)]}),(0,Y.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsP99`),`: `,Jm(l.durationMs.p99,o)]}),(0,Y.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsCooldown`),`: `,l.cooldownTriggeringFailures]}),(0,Y.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsConfidence`),`: `,l.confidence??o]}),l.historyTruncated?(0,Y.jsx)(`span`,{className:`badge badge-muted`,children:i(`routing.analyticsTruncated`)}):null]}),(0,Y.jsxs)(`table`,{className:`tbl`,children:[(0,Y.jsx)(`thead`,{children:(0,Y.jsxs)(`tr`,{children:[(0,Y.jsx)(`th`,{children:i(`routing.candidate`)}),(0,Y.jsx)(`th`,{children:i(`routing.analyticsRequests`)}),(0,Y.jsx)(`th`,{children:i(`routing.analyticsSuccessRate`)}),(0,Y.jsx)(`th`,{children:i(`routing.analyticsP50`)})]})}),(0,Y.jsx)(`tbody`,{children:l.breakdown.map(e=>(0,Y.jsxs)(`tr`,{children:[(0,Y.jsxs)(`td`,{children:[e.provider,`/`,e.model]}),(0,Y.jsx)(`td`,{children:e.requests}),(0,Y.jsx)(`td`,{children:Ym(e.successRate,o)}),(0,Y.jsx)(`td`,{children:Jm(e.p50DurationMs,o)})]},`${e.provider}/${e.model}`))})]})]}):(0,Y.jsx)(`p`,{className:`muted`,children:i(`routing.analyticsEmpty`)})]})]})}var nh=[`protocol_conformance`,`live_route_compatibility`,`task_effectiveness`],rh=[`UNKNOWN`,`CLAIMED`,`PROBED`,`VERIFIED`,`DEGRADED`,`BLOCKED`,`UNSUPPORTED`],ih=[`present`,`corrupt`,`purged_unavailable`];function ah(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function oh(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function sh(e){return e===null||typeof e==`string`}function ch(e){return e===void 0||typeof e==`number`&&Number.isFinite(e)}function lh(e){if(!ah(e)||typeof e.projectionAvailable!=`boolean`||e.projectionIncompatible!==void 0&&typeof e.projectionIncompatible!=`boolean`)return null;for(let t of[`sqliteSchemaVersion`,`builtAtMs`,`eventCount`,`subjectCount`,`observationCount`,`claimCount`,`verdictCount`,`artifactCount`,`corruptionCount`])if(!ch(e[t]))return null;return e.projectionSpecVersion!==void 0&&typeof e.projectionSpecVersion!=`string`?null:e}function uh(e){return!ah(e)||typeof e.projectionKey!=`string`||e.projectionKey.length===0||typeof e.subjectId!=`string`||e.subjectId.length===0||typeof e.evidenceLayer!=`string`||!nh.includes(e.evidenceLayer)||typeof e.suiteId!=`string`||e.suiteId.length===0||typeof e.suiteVersion!=`string`||typeof e.suiteManifestDigest!=`string`||typeof e.projectionSpecVersion!=`string`||typeof e.verdict!=`string`||!rh.includes(e.verdict)||typeof e.asOf!=`number`||!Number.isFinite(e.asOf)||!oh(e.scenarioManifestDigests)||!sh(e.claimSourceDigest)||!oh(e.contributingEventIds)||!oh(e.contradictingEventIds)||!oh(e.notes)?null:e}function dh(e){return!ah(e)||!Array.isArray(e.verdicts)?{verdicts:[],hasMore:!1}:{verdicts:e.verdicts.map(uh).filter(e=>e!==null),hasMore:e.hasMore===!0,nextCursor:typeof e.nextCursor==`string`?e.nextCursor:void 0}}function fh(e){return!ah(e)||!Array.isArray(e.subjects)?{subjects:[],hasMore:!1}:{subjects:e.subjects.filter(e=>ah(e)&&typeof e.subjectId==`string`&&typeof e.subjectKind==`string`),hasMore:e.hasMore===!0,nextCursor:typeof e.nextCursor==`string`?e.nextCursor:void 0}}function ph(e){return!ah(e)||!ah(e.subject)||typeof e.subject.subjectKind!=`string`?null:e.subject}function mh(e){return!ah(e)||typeof e.eventId!=`string`||typeof e.subjectId!=`string`||typeof e.evidenceLayer!=`string`||!nh.includes(e.evidenceLayer)||typeof e.suiteId!=`string`||typeof e.suiteVersion!=`string`||typeof e.suiteManifestDigest!=`string`||typeof e.scenarioId!=`string`||typeof e.scenarioVersion!=`string`||typeof e.scenarioManifestDigest!=`string`||typeof e.outcome!=`string`||typeof e.completedAt!=`number`||!Number.isFinite(e.completedAt)||typeof e.executionMode!=`string`||typeof e.excluded!=`boolean`||!sh(e.exclusionReason)?null:e}function hh(e){return!ah(e)||!Array.isArray(e.observations)?{observations:[],hasMore:!1}:{observations:e.observations.map(mh).filter(e=>e!==null),hasMore:e.hasMore===!0,nextCursor:typeof e.nextCursor==`string`?e.nextCursor:void 0}}function gh(e){if(!ah(e)||!ah(e.event))return null;let t={...e.event};return delete t.payload_json,typeof t.eventKind!=`string`||typeof t.eventId!=`string`||typeof t.recordedAt!=`number`||!Number.isFinite(t.recordedAt)||typeof t.producer!=`string`||typeof t.producerVersion!=`string`||typeof t.excluded!=`boolean`||!sh(t.exclusionReason)?null:t}function _h(e){if(!ah(e)||!ah(e.artifact))return null;let t=e.artifact;return typeof t.digest!=`string`||typeof t.status!=`string`||!ih.includes(t.status)||!sh(t.artifactClass)||!sh(t.mediaType)||t.byteCount!==null&&(typeof t.byteCount!=`number`||!Number.isFinite(t.byteCount))||!sh(t.lastError)?null:t}function vh(e){let t={},n=e.subjectQuery.trim();return e.layer&&(t.layer=e.layer),e.verdict&&(t.verdict=e.verdict),n&&(t.subjectId=n),e.suiteId.trim()&&(t.suiteId=e.suiteId.trim()),t}function yh(){return{protocol_conformance:[],live_route_compatibility:[],task_effectiveness:[]}}function bh(e,t){let n=new Map(t.map(e=>[e.subjectId,e.subjectKind])),r=new Map;for(let t of e){let e=r.get(t.subjectId);e||(e={subjectId:t.subjectId,subjectKind:n.get(t.subjectId)??``,byLayer:yh()},r.set(t.subjectId,e)),e.byLayer[t.evidenceLayer].push(t)}return[...r.values()].sort((e,t)=>e.subjectId.localeCompare(t.subjectId))}function xh(e){return e.length<=16?e:`${e.slice(0,8)}.${e.slice(-6)}`}function Sh(e,t){return!Number.isFinite(e)||e<=0?`-`:new Date(e).toLocaleString(t)}function Ch(e){let t=new Set;e.suiteManifestDigest&&t.add(e.suiteManifestDigest);for(let n of e.scenarioManifestDigests)n&&t.add(n);return e.claimSourceDigest&&t.add(e.claimSourceDigest),[...t]}var wh=50,Th=200,Eh=6,Dh=200;async function Oh(e,t,n){return It(await fetch(`${e}${t}`,{signal:n}))}function kh(e,t){let n=new URLSearchParams({limit:String(wh)});for(let[t,r]of Object.entries(e))r&&n.set(t,r);return t&&n.set(`cursor`,t),n.toString()}var Ah=class extends Error{};function jh(){return new Ah}function Mh(e,t,n){if(e.hasMore!==void 0&&typeof e.hasMore!=`boolean`||e.nextCursor!==void 0&&typeof e.nextCursor!=`string`||t&&!n)throw jh()}function Nh(e){if(!ah(e)||!Array.isArray(e.verdicts))throw jh();let t=dh(e);if(t.verdicts.length!==e.verdicts.length)throw jh();return Mh(e,t.hasMore,t.nextCursor),t}function Ph(e){if(!ah(e)||!Array.isArray(e.subjects))throw jh();let t=fh(e);if(t.subjects.length!==e.subjects.length)throw jh();return Mh(e,t.hasMore,t.nextCursor),t}function Fh(e){if(!ah(e)||!Array.isArray(e.observations))throw jh();let t=hh(e);if(t.observations.length!==e.observations.length)throw jh();return Mh(e,t.hasMore,t.nextCursor),t}async function Ih(e,t){let n=lh(await Oh(e,`/api/lab/status`,t));if(!n)throw jh();return n}async function Lh(e,t,n,r){return Nh(await Oh(e,`/api/lab/verdicts?${kh({layer:t.layer,verdict:t.verdict,subjectId:t.subjectId,suiteId:t.suiteId},n)}`,r))}async function Rh(e,t,n){return Ph(await Oh(e,`/api/lab/subjects?${kh({},t)}`,n))}async function zh(e){let t=[],n=new Set,r;for(let i=0;i<Th;i++){let i=await e(r);if(t.push(...i.rows),!i.hasMore)return{rows:t,truncated:!1};let a=i.nextCursor;if(!a||n.has(a)||a===r)throw new Ah;n.add(a),r=a}return{rows:t,truncated:!0}}async function Bh(e,t){return zh(async n=>{let r=await Rh(e,n,t);return{rows:r.subjects,hasMore:r.hasMore,nextCursor:r.nextCursor}})}async function Vh(e,t,n){let r=ph(await Oh(e,`/api/lab/subjects/${encodeURIComponent(t)}`,n));if(!r)throw jh();return r}async function Hh(e,t,n,r){return Fh(await Oh(e,`/api/lab/observations?${kh({subjectId:t.subjectId,layer:t.layer,suiteId:t.suiteId},n)}`,r))}async function Uh(e,t,n){return zh(async r=>{let i=await Hh(e,t,r,n);return{rows:i.observations,hasMore:i.hasMore,nextCursor:i.nextCursor}})}async function Wh(e,t,n){let r=gh(await Oh(e,`/api/lab/events/${encodeURIComponent(t)}`,n));if(!r)throw jh();return r}async function Gh(e,t,n){let r=_h(await Oh(e,`/api/lab/artifacts/${encodeURIComponent(t)}`,n));if(!r)throw jh();return r}function Kh(e){if(!ah(e)||e.verificationStatus!==`not_verification`||!ah(e.summary))throw jh();let t=e.summary;if(t.verificationStatus!==`not_verification`||typeof t.subjectId!=`string`||typeof t.recentProductionAttempts!=`number`||typeof t.recentSuccessfulAttempts!=`number`||typeof t.recentRouteErrorSignals!=`number`||t.lastObservedProductionAttempt!==void 0&&typeof t.lastObservedProductionAttempt!=`number`)throw jh();return{verificationStatus:`not_verification`,summary:t}}async function qh(e,t,n){return Kh(await Oh(e,`/api/lab/production-signals?${kh({subjectId:t})}`,n))}function Jh(e,t){let n=new Set(t);return Object.keys(e).every(e=>n.has(e))}function Yh(e){return typeof e==`string`&&/^[0-9a-f]{64}$/.test(e)}function Xh(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function Zh(e){if(!ah(e)||!Jh(e,[`evidence`,`trustClass`,`locallyVerified`])||e.trustClass!==`community_untrusted_v1`||e.locallyVerified!==!1||!Array.isArray(e.evidence)||e.evidence.length>4096)return null;let t=[];for(let n of e.evidence){if(!ah(n)||!Jh(n,[`trustClass`,`status`,`bundleId`,`publisherKeyId`,`activeRecordCount`,`revokedRecordCount`])||n.trustClass!==`community_untrusted_v1`||n.status!==`cryptographically_valid`||!Yh(n.bundleId)||!Yh(n.publisherKeyId)||!Xh(n.activeRecordCount)||!Xh(n.revokedRecordCount))return null;t.push({trustClass:`community_untrusted_v1`,status:`cryptographically_valid`,bundleId:n.bundleId,publisherKeyId:n.publisherKeyId,activeRecordCount:n.activeRecordCount,revokedRecordCount:n.revokedRecordCount})}return{evidence:t,trustClass:`community_untrusted_v1`,locallyVerified:!1}}async function Qh(e,t){let n=Zh(await Oh(e,`/api/lab/public/community`,t));if(!n)throw jh();return n}async function $h(e,t,n){let[r,i]=await Promise.all([Ih(e,n),Qh(e,n).catch(e=>{if(n.aborted)throw e;return null})]);if(!r.projectionAvailable)return{status:r,verdicts:[],subjects:[],subjectsTruncated:!1,hasMore:!1,community:i};let[a,o]=await Promise.all([Lh(e,t,void 0,n),Bh(e,n)]);return{status:r,verdicts:a.verdicts,subjects:o.rows,subjectsTruncated:o.truncated,hasMore:a.hasMore,nextCursor:a.nextCursor,community:i}}async function eg(e,t,n,r){return Lh(e,t,n,r)}async function tg(e,t,n,r){let i=e.slice(0,Dh),a=[],o=0,s=async()=>{for(;;){if(n.aborted)throw new DOMException(`Aborted`,`AbortError`);let e=o++;if(e>=i.length)return;try{a.push(await r(i[e]))}catch(e){if(n.aborted)throw e}}},c=Math.min(t,i.length);return await Promise.all(Array.from({length:c},()=>s())),a}async function ng(e,t,n){let r=[...new Set([...t.contributingEventIds,...t.contradictingEventIds])],i=Ch(t),a={subjectId:t.subjectId,layer:t.evidenceLayer,suiteId:t.suiteId},[o,s,c,l,u]=await Promise.all([Vh(e,t.subjectId,n),Uh(e,a,n),tg(r,Eh,n,t=>Wh(e,t,n)),tg(i,Eh,n,t=>Gh(e,t,n)),qh(e,t.subjectId,n).catch(e=>{if(n.aborted)throw e;return null})]);return{subject:o,observations:s.rows,observationsTruncated:s.truncated,events:c,artifacts:l,production:u}}var rg={protocol_conformance:`lab.layer.protocol_conformance`,live_route_compatibility:`lab.layer.live_route_compatibility`,task_effectiveness:`lab.layer.task_effectiveness`},ig={protocol_conformance:`lab.col.protocol`,live_route_compatibility:`lab.col.live`,task_effectiveness:`lab.col.task`},ag={UNKNOWN:`lab.verdict.UNKNOWN`,CLAIMED:`lab.verdict.CLAIMED`,PROBED:`lab.verdict.PROBED`,VERIFIED:`lab.verdict.VERIFIED`,DEGRADED:`lab.verdict.DEGRADED`,BLOCKED:`lab.verdict.BLOCKED`,UNSUPPORTED:`lab.verdict.UNSUPPORTED`},og={present:`artifact.present`,corrupt:`artifact.corrupt`,purged_unavailable:`artifact.purged_unavailable`};function sg(e,t){if(!(e instanceof Error))return t;let n=e.message;return n===`Failed to fetch`||n.includes(`NetworkError`)||n.includes(`network error`)?t:n||t}function cg({verdict:e,caption:t,label:n,selected:r,onSelect:i}){let a=`lab-verdict-badge${r?` lab-verdict-badge--selected`:``}`;return i?(0,Y.jsxs)(`button`,{type:`button`,className:a,"data-verdict":e,title:t,onClick:i,children:[(0,Y.jsx)(`span`,{children:n}),(0,Y.jsx)(`span`,{className:`suite`,children:t})]}):(0,Y.jsxs)(`span`,{className:a,"data-verdict":e,title:t,children:[(0,Y.jsx)(`span`,{children:n}),(0,Y.jsx)(`span`,{className:`suite`,children:t})]})}function lg({rows:e,t,selectedKey:n,onSelect:r}){return e.length===0?(0,Y.jsx)(`span`,{className:`muted`,children:`-`}):(0,Y.jsx)(`div`,{className:`lab-verdict-stack`,children:e.map(e=>(0,Y.jsx)(cg,{verdict:e.verdict,caption:e.suiteId,label:t(ag[e.verdict]),selected:n===e.projectionKey,onSelect:()=>r(e)},e.projectionKey))})}function ug({data:e,t,locale:n}){let{status:r}=e,i=[{label:t(`lab.subjectCount`),value:String(r.subjectCount??0)},{label:t(`lab.verdictCount`),value:String(r.verdictCount??0)},{label:t(`lab.observationCount`),value:String(r.observationCount??0)},{label:t(`lab.eventCount`),value:String(r.eventCount??0)}];return r.builtAtMs&&i.push({label:t(`lab.builtAt`),value:Sh(r.builtAtMs,n)}),(0,Y.jsx)(`div`,{className:`lab-status-grid`,"aria-label":t(`lab.statusTitle`),children:i.map(e=>(0,Y.jsxs)(`div`,{className:`lab-status-card`,children:[(0,Y.jsx)(`span`,{className:`label`,children:e.label}),(0,Y.jsx)(`span`,{className:`value`,children:e.value})]},e.label))})}function dg({community:e,locale:t}){if(!e||e.evidence.length===0)return null;let n=e.evidence.reduce((e,t)=>e+t.activeRecordCount,0),r=e.evidence.reduce((e,t)=>e+t.revokedRecordCount,0);return(0,Y.jsxs)(`section`,{className:`lab-matrix-block`,"data-testid":`lab-community-evidence`,children:[(0,Y.jsx)(`h3`,{className:`lab-matrix-title`,children:Ze(t,`community.title`)}),(0,Y.jsx)(`p`,{className:`muted`,children:Ze(t,`community.notLocalVerdict`)}),(0,Y.jsxs)(`dl`,{className:`lab-detail-meta`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`dt`,{children:Ze(t,`community.bundles`)}),(0,Y.jsx)(`dd`,{children:e.evidence.length})]}),(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`dt`,{children:Ze(t,`community.activeRecords`)}),(0,Y.jsx)(`dd`,{children:n})]}),(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`dt`,{children:Ze(t,`community.revokedRecords`)}),(0,Y.jsx)(`dd`,{children:r})]})]})]})}function fg({verdict:e,detail:t,loading:n,error:r,t:i,locale:a,onClose:o}){let s=new Set([...e.contributingEventIds,...e.contradictingEventIds]).size;return(0,Y.jsxs)(`aside`,{className:`lab-detail-pane`,"aria-label":i(`lab.detailTitle`),children:[(0,Y.jsxs)(`div`,{className:`lab-detail-head`,children:[(0,Y.jsx)(`h3`,{children:xh(e.subjectId)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:o,children:i(`lab.detailClose`)})]}),(0,Y.jsxs)(`dl`,{className:`lab-detail-meta`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`dt`,{children:i(`lab.col.layer`)}),(0,Y.jsx)(`dd`,{children:i(rg[e.evidenceLayer])})]}),(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`dt`,{children:i(`lab.col.suite`)}),(0,Y.jsx)(`dd`,{className:`mono`,children:e.suiteId})]}),(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`dt`,{children:i(`lab.col.verdict`)}),(0,Y.jsx)(`dd`,{children:i(ag[e.verdict])})]}),(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`dt`,{children:i(`lab.col.asOf`)}),(0,Y.jsx)(`dd`,{children:Sh(e.asOf,a)})]})]}),n&&(0,Y.jsx)(tp,{busy:!0,children:i(`common.loading`)}),r&&(0,Y.jsx)($,{tone:`err`,children:r}),t&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`section`,{className:`lab-detail-section`,children:[(0,Y.jsx)(`h4`,{children:i(`lab.detailSubject`)}),(0,Y.jsx)(`p`,{className:`mono`,children:t.subject.subjectKind})]}),t.production&&(0,Y.jsxs)(`section`,{className:`lab-detail-section`,"data-testid":`lab-production-signals`,children:[(0,Y.jsx)(`h4`,{children:i(`lab.production.title`)}),(0,Y.jsx)(`p`,{className:`muted`,children:i(`lab.production.notVerification`)}),(0,Y.jsxs)(`dl`,{className:`lab-detail-meta`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`dt`,{children:i(`lab.production.attempts`)}),(0,Y.jsx)(`dd`,{children:t.production.summary.recentProductionAttempts})]}),(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`dt`,{children:i(`lab.production.successes`)}),(0,Y.jsx)(`dd`,{children:t.production.summary.recentSuccessfulAttempts})]}),(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`dt`,{children:i(`lab.production.routeErrors`)}),(0,Y.jsx)(`dd`,{children:t.production.summary.recentRouteErrorSignals})]}),t.production.summary.lastObservedProductionAttempt!==void 0&&(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`dt`,{children:i(`lab.production.lastObserved`)}),(0,Y.jsx)(`dd`,{children:Sh(t.production.summary.lastObservedProductionAttempt,a)})]})]})]}),t.observations.length>0&&(0,Y.jsxs)(`section`,{className:`lab-detail-section`,children:[(0,Y.jsx)(`h4`,{children:i(`lab.detailObservations`)}),(0,Y.jsx)(`ul`,{className:`lab-detail-list`,children:t.observations.map(e=>(0,Y.jsxs)(`li`,{children:[(0,Y.jsx)(`span`,{className:`mono`,children:e.scenarioId}),(0,Y.jsx)(`span`,{children:e.outcome}),(0,Y.jsx)(`span`,{className:`muted`,children:Sh(e.completedAt,a)})]},e.eventId))})]}),(t.events.length>0||s>0)&&(0,Y.jsxs)(`section`,{className:`lab-detail-section`,children:[(0,Y.jsxs)(`h4`,{children:[i(`lab.detailEvents`),t.events.length<s?` (${t.events.length}/${s})`:``]}),(0,Y.jsx)(`ul`,{className:`lab-detail-list`,children:t.events.map(e=>(0,Y.jsxs)(`li`,{children:[(0,Y.jsx)(`span`,{className:`mono`,children:e.eventId}),(0,Y.jsx)(`span`,{children:e.eventKind})]},e.eventId))})]}),t.artifacts.length>0&&(0,Y.jsxs)(`section`,{className:`lab-detail-section`,children:[(0,Y.jsx)(`h4`,{children:i(`lab.detailArtifacts`)}),(0,Y.jsx)(`ul`,{className:`lab-detail-list`,children:t.artifacts.map(e=>(0,Y.jsxs)(`li`,{children:[(0,Y.jsx)(`span`,{className:`mono`,title:e.digest,children:xh(e.digest)}),(0,Y.jsx)(`span`,{children:e.artifactClass??`-`}),(0,Y.jsx)(`span`,{children:Ze(a,og[e.status])})]},e.digest))})]})]})]})}function pg({apiBase:e,active:t=!0,onCountChange:n}){let{t:r,locale:i}=ut(),[a,o]=(0,_.useState)({layer:``,verdict:``,subjectQuery:``,suiteId:``}),[s,c]=(0,_.useState)(null),[l,u]=(0,_.useState)(null),[d,f]=(0,_.useState)(!1),[p,m]=(0,_.useState)(null),[h,g]=(0,_.useState)(null),[v,y]=(0,_.useState)(!1),[b,x]=(0,_.useState)(null),S=(0,_.useRef)(null),C=(0,_.useRef)(null),w=(0,_.useRef)(null),T=(0,_.useMemo)(()=>vh(a),[a]),E=JSON.stringify(T),D=(0,_.useCallback)(t=>$h(e,T,t),[e,T]),O=jr(`lab-matrix:${e}:${E}`,[e,E],D,{isEmpty:e=>e.verdicts.length===0,pollMs:6e4,enabled:t,pauseWhenHidden:!0}),k=(0,_.useCallback)(()=>{S.current?.abort(),S.current=null,c(null),u(null),f(!1)},[]),A=(0,_.useCallback)(()=>{w.current=null,C.current?.abort(),C.current=null,m(null),g(null),x(null),y(!1)},[]);(0,_.useEffect)(()=>{S.current?.abort()},[O.data]),(0,_.useEffect)(()=>()=>{S.current?.abort(),C.current?.abort()},[]);let j=(0,_.useCallback)(e=>{A(),k(),o(e)},[A,k]),M=s!==null&&s.baseData===O.data&&s.queryKey===E?s:null,N=l!==null&&l.baseData===O.data&&l.queryKey===E?l.message:null,P=(0,_.useMemo)(()=>{if(!t||!O.data?.status.projectionAvailable)return null;let e=O.data.status.verdictCount;return typeof e==`number`?e:O.data.verdicts.length+(M?.verdicts.length??0)},[t,O.data,M]);(0,_.useEffect)(()=>{n?.(P)},[n,P]);let F=(0,_.useMemo)(()=>O.data?[...O.data.verdicts,...M?.verdicts??[]]:[],[O.data,M]),I=(0,_.useMemo)(()=>O.data?bh(F,O.data.subjects):[],[F,O.data]),L=(0,_.useCallback)(async()=>{let t=M?.nextCursor??O.data?.nextCursor,n=O.data;if(!t||!n||d)return;S.current?.abort();let i=new AbortController;S.current=i;let a=E;u(null),f(!0);try{let r=await eg(e,T,t,i.signal);if(i.signal.aborted)return;c(e=>{let t=e?.baseData===n&&e.queryKey===a?e.verdicts:[];return{baseData:n,queryKey:a,verdicts:[...t,...r.verdicts],nextCursor:r.nextCursor,hasMore:r.hasMore}})}catch(e){i.signal.aborted||u({baseData:n,queryKey:a,message:sg(e,r(`lab.loadFailed`))})}finally{S.current===i&&(S.current=null,f(!1))}},[e,d,T,E,O.data,r,M]),R=(0,_.useCallback)(async n=>{if(!t)return;C.current?.abort();let i=new AbortController;C.current=i,w.current=n.projectionKey,m(n),g(null),x(null),y(!0);try{let t=await ng(e,n,i.signal);!i.signal.aborted&&w.current===n.projectionKey&&g(t)}catch(e){!i.signal.aborted&&w.current===n.projectionKey&&x(sg(e,r(`lab.detailLoadFailed`)))}finally{C.current===i&&(C.current=null,!i.signal.aborted&&w.current===n.projectionKey&&y(!1))}},[t,e,r]),z=O.refresh,B=(0,_.useCallback)(()=>{A(),k(),z({forceLoading:!0})},[A,z,k]),V=t?p:null,H=M?M.hasMore:O.data?.hasMore??!1,U=[{value:``,label:r(`lab.filter.all`)},...nh.map(e=>({value:e,label:r(rg[e])}))],W=[{value:``,label:r(`lab.filter.all`)},...rh.map(e=>({value:e,label:r(ag[e])}))],G=[{value:``,label:r(`lab.filter.all`)},...(O.data?.subjects??[]).map(e=>({value:e.subjectId,label:`${xh(e.subjectId)} · ${e.subjectKind}`}))];if(O.state.showSkeleton)return(0,Y.jsx)(ep,{label:r(`lab.loading`),rows:5});let K=O.state.showError?sg(O.error,r(`lab.loadFailed`)):null,q=O.data?.status,J=q&&!q.projectionAvailable,X=q?.projectionIncompatible===!0;return(0,Y.jsxs)(`div`,{className:`lab-page`,children:[(0,Y.jsx)(`div`,{className:`lab-toolbar`,children:(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:B,disabled:O.refreshing,children:[(0,Y.jsx)(de,{}),r(`lab.refresh`)]})}),O.refreshing&&!O.state.showSkeleton&&(0,Y.jsx)(tp,{busy:!0,live:!K,children:r(`common.loading`)}),K&&(0,Y.jsx)($,{tone:`err`,children:K}),X&&(0,Y.jsx)($,{tone:`err`,children:r(`lab.projectionIncompatible`)}),J&&!X&&(0,Y.jsx)(At,{title:r(`lab.projectionUnavailable`)}),O.data&&(0,Y.jsx)(dg,{community:O.data.community,locale:i}),O.data&&q?.projectionAvailable&&!X&&(0,Y.jsxs)(`div`,{className:`lab-layout`,children:[(0,Y.jsxs)(`div`,{className:`lab-main`,children:[(0,Y.jsx)(ug,{data:O.data,t:r,locale:i}),(0,Y.jsxs)(`div`,{className:`lab-filters`,children:[(0,Y.jsxs)(`div`,{className:`lab-filter-field`,children:[(0,Y.jsx)(`label`,{htmlFor:`lab-filter-layer`,children:r(`lab.filter.layer`)}),(0,Y.jsx)(kt,{id:`lab-filter-layer`,value:a.layer,options:U,onChange:e=>j(t=>({...t,layer:e})),label:r(`lab.filter.layer`),portal:!1})]}),(0,Y.jsxs)(`div`,{className:`lab-filter-field`,children:[(0,Y.jsx)(`label`,{htmlFor:`lab-filter-verdict`,children:r(`lab.filter.verdict`)}),(0,Y.jsx)(kt,{id:`lab-filter-verdict`,value:a.verdict,options:W,onChange:e=>j(t=>({...t,verdict:e})),label:r(`lab.filter.verdict`),portal:!1})]}),(0,Y.jsxs)(`div`,{className:`lab-filter-field`,children:[(0,Y.jsx)(`label`,{htmlFor:`lab-filter-subject`,children:r(`lab.filter.subject`)}),(0,Y.jsx)(kt,{id:`lab-filter-subject`,value:a.subjectQuery,options:G,onChange:e=>j(t=>({...t,subjectQuery:e})),label:r(`lab.filter.subject`),portal:!1})]})]}),I.length===0?(0,Y.jsx)(At,{title:r(`lab.empty`)}):(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{className:`lab-matrix-block`,children:[(0,Y.jsx)(`h3`,{className:`lab-matrix-title`,children:r(`lab.matrixTitle`)}),(0,Y.jsx)(`div`,{className:`lab-matrix-scroll`,children:(0,Y.jsxs)(`table`,{className:`lab-matrix`,children:[(0,Y.jsx)(`thead`,{children:(0,Y.jsxs)(`tr`,{children:[(0,Y.jsx)(`th`,{children:r(`lab.col.subject`)}),(0,Y.jsx)(`th`,{children:r(`lab.subjectKind`)}),nh.map(e=>(0,Y.jsx)(`th`,{children:r(ig[e])},e))]})}),(0,Y.jsx)(`tbody`,{children:I.map(e=>(0,Y.jsxs)(`tr`,{children:[(0,Y.jsx)(`td`,{className:`subject`,title:e.subjectId,children:xh(e.subjectId)}),(0,Y.jsx)(`td`,{className:`kind`,children:e.subjectKind||Ze(i,`subjectKindUnknown`)}),nh.map(t=>(0,Y.jsx)(`td`,{children:(0,Y.jsx)(lg,{rows:e.byLayer[t],t:r,selectedKey:V?.projectionKey??null,onSelect:e=>{R(e)}})},t))]},e.subjectId))})]})})]}),(0,Y.jsxs)(`div`,{className:`lab-matrix-block`,children:[(0,Y.jsx)(`h3`,{className:`lab-matrix-title`,children:r(`lab.verdictsTitle`)}),(0,Y.jsx)(`div`,{className:`lab-matrix-scroll`,children:(0,Y.jsxs)(`table`,{className:`lab-detail-table`,children:[(0,Y.jsx)(`thead`,{children:(0,Y.jsxs)(`tr`,{children:[(0,Y.jsx)(`th`,{children:r(`lab.col.subject`)}),(0,Y.jsx)(`th`,{children:r(`lab.col.layer`)}),(0,Y.jsx)(`th`,{children:r(`lab.col.suite`)}),(0,Y.jsx)(`th`,{children:r(`lab.col.verdict`)}),(0,Y.jsx)(`th`,{children:r(`lab.col.asOf`)})]})}),(0,Y.jsx)(`tbody`,{children:F.map(e=>{let t=V?.projectionKey===e.projectionKey;return(0,Y.jsxs)(`tr`,{className:t?`selected`:``,children:[(0,Y.jsx)(`td`,{className:`mono`,title:e.subjectId,children:(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"data-verdict-detail":e.projectionKey,"aria-pressed":t,"aria-label":Ze(i,`selectVerdict`,{subject:xh(e.subjectId)}),onClick:()=>{R(e)},children:xh(e.subjectId)})}),(0,Y.jsx)(`td`,{children:r(rg[e.evidenceLayer])}),(0,Y.jsx)(`td`,{className:`mono`,children:e.suiteId}),(0,Y.jsx)(`td`,{children:(0,Y.jsx)(cg,{verdict:e.verdict,caption:e.suiteId,label:r(ag[e.verdict])})}),(0,Y.jsx)(`td`,{children:Sh(e.asOf,i)})]},e.projectionKey)})})]})})]}),N&&(0,Y.jsx)($,{tone:`err`,children:N}),H&&(0,Y.jsx)(`div`,{className:`lab-load-more`,children:(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:d,onClick:()=>{L()},children:r(d?`common.loading`:`lab.loadMore`)})})]})]}),V&&(0,Y.jsx)(fg,{verdict:V,detail:h,loading:v,error:b,t:r,locale:i,onClose:A})]})]})}var mg=[`catalog`,`combos`,`routing`,`compatibility`];function hg(e){return e===`catalog`?`models`:`models/${e}`}function gg(e=window.location.hash){let t=pt(e);return t===`models/combos`||t===`combos`||t.startsWith(`combos/`)?`combos`:t===`models/routing`||t===`routing`||t.startsWith(`routing/`)?`routing`:t===`models/compatibility`||t===`lab`||t.startsWith(`lab/`)?`compatibility`:`catalog`}function _g(e){ht(hg(e))}function vg(e){return`models-tab-${e}`}function yg(e){return`models-panel-${e}`}var bg={catalog:`models.tab.catalog`,combos:`models.tab.combos`,routing:`models.tab.routing`,compatibility:`models.tab.compatibility`};function xg({tab:e,onSelect:t,meta:n}){let r=Q(),i=(0,_.useRef)(null);i.current===null&&(i.current=new Map);let a=e=>{t(e),window.requestAnimationFrame(()=>{i.current.get(e)?.focus({preventScroll:!0})})},o=t=>{let n=mg.indexOf(e),r=null;t.key===`ArrowLeft`?r=(n-1+mg.length)%mg.length:t.key===`ArrowRight`?r=(n+1)%mg.length:t.key===`Home`?r=0:t.key===`End`&&(r=mg.length-1),r!==null&&(t.preventDefault(),a(mg[r]))};return(0,Y.jsx)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":r(`models.tabsLabel`),children:mg.map(t=>{let s=t===e,c=n?.[t];return(0,Y.jsxs)(`button`,{ref:e=>{e?i.current.set(t,e):i.current.delete(t)},type:`button`,role:`tab`,id:vg(t),"aria-selected":s,"aria-controls":yg(t),tabIndex:s?0:-1,className:`page-tab${s?` page-tab--active`:``}`,onClick:()=>a(t),onKeyDown:o,children:[r(bg[t]),c?(0,Y.jsx)(`span`,{className:`section-tab-meta`,children:c}):null]},t)})})}function Sg(e,t){let n=new Map;for(let t of e){let e=n.get(t.provider);e?e.push(t):n.set(t.provider,[t])}let r=new Map(t.map(e=>[e.name,e]));for(let e of t){if(e.disabled===!0){n.delete(e.name);continue}e.authMode!==`forward`&&(n.has(e.name)||n.set(e.name,[]))}return[...n.entries()].map(([e,t])=>{let n=r.get(e);return{provider:e,rows:t,native:t.length>0&&t.every(e=>e.native===!0),nativeProviderGroup:t.some(e=>e.native===!0)||e===`openai`&&n?.authMode===`forward`,liveModels:n?.liveModels!==!1,configuredModels:n?.models??[],contextWindow:n?.contextWindow,modelContextWindows:n?.modelContextWindows,discovery:n?.discovery,entitlement:n?.entitlement}}).sort((e,t)=>e.nativeProviderGroup===t.nativeProviderGroup?e.provider.localeCompare(t.provider):e.nativeProviderGroup?-1:1)}function Cg({liveModels:e,discovery:t,showFailureBadge:n=!0}){let r=Q(),i=e&&t?.status===`failed`?t:void 0;return(0,Y.jsxs)(`div`,{className:`row muted text-label leading-body`,role:`status`,style:{alignItems:`flex-start`,gap:8,padding:`6px 0`},children:[(0,Y.jsx)(ve,{width:15,height:15,"aria-hidden":`true`,style:{flexShrink:0,marginTop:2}}),(0,Y.jsxs)(`span`,{children:[i&&n&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`span`,{className:`badge badge-amber`,children:r(`models.discoveryFailedBadge`)}),` `]}),i?`${Eo(r,i)} `:`${r(e?`models.emptyDiscovery`:`models.emptyDiscoveryDisabled`)} `,(0,Y.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>ht(`providers`),children:r(`models.openProviderSettings`)})]})]})}function wg(){let e=Q();return(0,Y.jsxs)(`div`,{className:`row muted text-label leading-body`,role:`status`,style:{alignItems:`flex-start`,gap:8,padding:`6px 0`},children:[(0,Y.jsx)(ve,{width:15,height:15,"aria-hidden":`true`,style:{flexShrink:0,marginTop:2}}),(0,Y.jsxs)(`span`,{children:[`${e(`models.discoveryFailedDependency`,{control:e(`pws.liveModels`)})} `,(0,Y.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>ht(`providers`),children:e(`models.openProviderSettings`)})]})]})}var Tg={catalog:`models.subtitle`,combos:`models.subtitle.combos`,routing:`models.subtitle.routing`,compatibility:`models.subtitle.compatibility`};function Eg(e){let t=e.replace(/[_,\s]/g,``);if(!t)return null;let n=Number(t);return Number.isSafeInteger(n)&&n>0?n:void 0}function Dg({apiBase:e,restartEpoch:t=0}){let[n,r]=(0,_.useState)(null),i=(0,_.useRef)(!0);(0,_.useEffect)(()=>(i.current=!0,()=>{i.current=!1}),[]);let a=(0,_.useRef)(null),o=(0,_.useRef)(0),s=(0,_.useRef)(e),c=(0,_.useCallback)(()=>{o.current++,a.current?.controller.abort(),a.current?.clear(),a.current=null},[]),l=(0,_.useCallback)(async()=>{if(!i.current||s.current!==e)return;c();let t=o.current,n=Xn(15e3);a.current=n;try{let c=await Gd(e,{signal:n.signal});if(n.signal.aborted||!i.current||s.current!==e||t!==o.current||a.current!==n)return;r(c.state)}finally{n.clear(),a.current===n&&(a.current=null)}},[e,c]),{restarting:u,restart:d}=Xd(e,{onSettled:()=>{l()}});(0,_.useEffect)(()=>(s.current=e,r(null),l(),c),[e,c,l,t]);let[f,p]=(0,_.useState)(gg),[m,h]=(0,_.useState)(()=>new Set([gg()])),g=(0,_.useCallback)(e=>{p(e),h(t=>t.has(e)?t:new Set([...t,e]))},[]);(0,_.useEffect)(()=>{let e=()=>g(gg());return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[g]);let v=(0,_.useCallback)(e=>{_g(e),g(e)},[g]),y=f===`catalog`,[b,x]=(0,_.useState)(null),[S,C]=(0,_.useState)(null),[w,T]=(0,_.useState)(null),E=Q(),D=`ocx.models.catalog.v1:${e}`,O=(0,_.useMemo)(()=>Tr(D),[D]),[k,A]=(0,_.useState)(()=>O?.models??[]),[j,M]=(0,_.useState)(()=>O?.providers??[]),[N,P]=(0,_.useState)(()=>new Set(O?.disabled??[])),[F,I]=(0,_.useState)(()=>O?.selectedModels??null),[L,R]=(0,_.useState)({}),[z,B]=(0,_.useState)({}),[V,H]=(0,_.useState)({}),[U,W]=(0,_.useState)(()=>O?.contextCaps??{}),[G,K]=(0,_.useState)(()=>O?.contextCapValues??{}),[J,X]=(0,_.useState)(()=>O?.contextCapValue??35e4),ee=`${D}:picker-order`,te=(0,_.useMemo)(()=>{let e=Tr(ee);return fd(e)?e:void 0},[ee]),[Z,re]=(0,_.useState)(null),[ie,ae]=(0,_.useState)(!1),oe=(0,_.useRef)(null),se=(0,_.useRef)(0),le=jr(ee,[e],(0,_.useCallback)(async t=>{let n=await It(await fetch(`${e}/api/subagent-models`,{signal:t}));if(!fd(n))throw Error(`picker settings payload missing`);if(t.aborted)throw Error(`picker settings request aborted`);return kr(ee,n),n},[e,ee]),{isEmpty:()=>!1,enabled:y,deadlineMs:15e3,initialData:te}),ue=le.state.data,fe=Z??vd(ue?.pickerAvailable??[],ue?.pickerOrder??[],ue?.pickerOrderMode);(0,_.useLayoutEffect)(()=>(se.current++,re(null),ae(!1),()=>{se.current++,oe.current?.controller.abort(),oe.current?.clear(),oe.current=null,c()}),[e,y,c]),(0,_.useLayoutEffect)(()=>{y&&Z===null&&fe===`custom`&&re(`custom`)},[y,Z,fe]);let[pe,me]=(0,_.useState)(``),[he,ye]=(0,_.useState)(!1),[be,xe]=(0,_.useState)({}),[Se,we]=(0,_.useState)({}),Te=Wo(),[Ee,De]=(0,_.useState)(()=>Te??new Set),Oe=(0,_.useRef)(Te===null),[ke,Ae]=(0,_.useState)(``),[je,Me]=(0,_.useState)([]),[Ne,Pe]=(0,_.useState)(!1),[Fe,Ie]=(0,_.useState)(0),Le=(0,_.useCallback)((e,t)=>{Pe(e),Ae(t),Ie(e=>e+1)},[]);(0,_.useEffect)(()=>{if(!ke)return;let e=setTimeout(()=>Ae(``),Ne?6e3:8e3);return()=>clearTimeout(e)},[ke,Ne,Fe]);let[Re,ze]=(0,_.useState)(!1),Be=(0,_.useRef)(!1),Ve=(0,_.useRef)(!1),He=(0,_.useRef)(0),Ue=(0,_.useRef)(!1),[We,Ge]=(0,_.useState)(null),[Ke,qe]=(0,_.useState)({}),[Je,Ye]=(0,_.useState)(null),[Xe,Ze]=(0,_.useState)({providers:{},models:{},defaults:{global:!1,providers:{}}}),[Qe,$e]=(0,_.useState)(!1),[et,tt]=(0,_.useState)(null),[nt,rt]=(0,_.useState)(!0),[it,at]=(0,_.useState)(!1),[ot,st]=(0,_.useState)(``),ct=(0,_.useRef)(!1),[lt,ut]=(0,_.useState)(``),[dt,ft]=(0,_.useState)(!1),[pt,mt]=(0,_.useState)(!1),[ht,gt]=(0,_.useState)(null),[_t,vt]=(0,_.useState)(!1),[yt,bt]=(0,_.useState)(null),[xt,St]=(0,_.useState)(null),Ct=(0,_.useRef)(null),[wt,Tt]=(0,_.useState)(!1),[Et,Ot]=(0,_.useState)(null),[Mt,Nt]=(0,_.useState)(null),[Pt,Ft]=(0,_.useState)(!1),Rt=(0,_.useRef)(null),zt=(0,_.useRef)(!1);(0,_.useEffect)(()=>()=>{Rt.current?.controller.abort(),Rt.current?.clear(),Rt.current=null},[]);let Ht=(0,_.useRef)(null),Ut=(0,_.useCallback)(async t=>{let n=await Lt(await fetch(`${e}/api/aliases`,{signal:t}));n&&!t?.aborted&&Ze(n)},[e]);(0,_.useEffect)(()=>{let e=new AbortController;return Ut(e.signal),()=>e.abort()},[Ut]);let Wt=async t=>{let n=window.prompt(E(`models.aliasPrompt`),Xe.providers[t]??``);if(n!==null){if(!(await fetch(`${e}/api/providers/${encodeURIComponent(t)}/alias`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({alias:n.trim()||null})})).ok){Le(!1,E(`models.aliasConflict`));return}await Ut(),Le(!0,E(`models.aliasSaved`))}},Gt=async(t,n)=>{let r=Xe.models[t]?.[n]?.alias??``,i=window.prompt(E(`models.modelAliasPrompt`),r);if(i===null)return;let a=i.trim()?{set:{[n]:i.trim()}}:{remove:[n]};if(!(await fetch(`${e}/api/providers/${encodeURIComponent(t)}/model-aliases`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(a)})).ok){Le(!1,E(`models.aliasConflict`));return}await Ut(),Le(!0,E(`models.aliasSaved`))},Kt=async(t,n)=>{(await fetch(`${e}/api/default-aliases`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({enabled:t,...n?{provider:n}:{}})})).ok&&await Ut()},[qt,Jt]=(0,_.useState)(`add`),[Yt,Xt]=(0,_.useState)(``),[Zt,Qt]=(0,_.useState)(``),[$t,en]=(0,_.useState)(``),[tn,nn]=(0,_.useState)(``),[rn,an]=(0,_.useState)(``),[on,sn]=(0,_.useState)(!1),[cn,ln]=(0,_.useState)([`text`]),[un,dn]=(0,_.useState)(!1),[fn,pn]=(0,_.useState)([]),mn=(0,_.useRef)(!1),[gn,_n]=(0,_.useState)(!1),[vn,yn]=(0,_.useState)(``),[bn,xn]=(0,_.useState)(null),[Sn,wn]=(0,_.useState)([]),[En,Dn]=(0,_.useState)(``),[On,kn]=(0,_.useState)(``),[An,jn]=(0,_.useState)({}),[Mn,Nn]=(0,_.useState)({contextWindow:null,modelContextWindows:{}}),[Pn,Fn]=(0,_.useState)(new Set),[In,Rn]=(0,_.useState)(!1),[Bn,Vn]=(0,_.useState)(!1),[Hn,Un]=(0,_.useState)(``),[Wn,Gn]=(0,_.useState)(null),Kn=(0,_.useRef)(null),[qn,Jn]=(0,_.useState)(null),[Yn,Zn]=(0,_.useState)(!1),[Qn,$n]=(0,_.useState)(null);(0,_.useEffect)(()=>()=>{Kn.current&&clearTimeout(Kn.current)},[]);let tr=(0,_.useMemo)(()=>Uo(k,N,F??{},E),[k,N,F,E]),nr=(0,_.useMemo)(()=>{let e=new Set(tr.map(e=>e.value));return hn(k.filter(t=>e.has(t.namespaced)),qn?.model,qn?.sourceModels)},[k,qn?.model,qn?.sourceModels,tr]),rr=(0,_.useCallback)(async()=>{let t=Xn(15e3);try{let n=await Lt(await fetch(`${e}/api/shadow-call-settings`,{signal:t.signal}));n&&Jn(n)}catch{}finally{t.clear()}},[e]),ir=(0,_.useCallback)(async()=>{if(ct.current)return;let t=Xn(15e3);try{let n=await fetch(`${e}/api/v2`,{signal:t.signal});if(!(n.headers.get(`content-type`)??``).includes(`application/json`)){Ge(null);return}let r=await Lt(n);if(!r||typeof r.enabled!=`boolean`){Ge(null);return}Ge({enabled:r.enabled,agentsMaxThreadsConflict:r.agentsMaxThreadsConflict===!0,maxConcurrentThreadsPerSession:typeof r.maxConcurrentThreadsPerSession==`number`?r.maxConcurrentThreadsPerSession:null,multiAgentMode:r.multiAgentMode===`v1`||r.multiAgentMode===`v2`?r.multiAgentMode:`default`,keepNativeChatGptOnV1:r.keepNativeChatGptOnV1===!0})}catch{Ge(null)}finally{t.clear(),rt(!1)}},[e]),ar=(0,_.useCallback)(async t=>{let[n,r,i,a]=await Promise.all([fetch(`${e}/api/models`,{signal:t}),fetch(`${e}/api/provider-context-caps`,{signal:t}),fetch(`${e}/api/providers`,{signal:t}),La(e,fetch,t)]),[o,s,c]=await Promise.all([It(n),It(r),It(i)]);if(o===void 0||s===void 0||c===void 0)throw Error(`models payload missing`);if(t.aborted)throw Error(`models request aborted`);let l=Ho(o),u=typeof s.value==`number`&&Number.isFinite(s.value)&&s.value>0?s.value:typeof s.cap==`number`&&Number.isFinite(s.cap)&&s.cap>0?s.cap:void 0,d=u===void 0?35e4:u,f={models:o,providers:c,selectedModels:a,disabled:[...l],contextCaps:s.caps??{},contextCapValues:s.values??s.caps??{},contextCapValue:d};return kr(D,f),f},[e,D]),or=(0,_.useCallback)(e=>{let t=Sg(e.models,e.providers);$n(e=>e!==null&&!t.some(t=>t.provider===e)?null:e),A(e.models),M(e.providers),P(new Set(e.disabled)),I(e.selectedModels),X(e.contextCapValue),W(e.contextCaps),K(e.contextCapValues??e.contextCaps)},[]),sr=jr(D,[e],async e=>{let t=await ar(e);if(e.aborted)throw Error(`models request aborted`);return or(t),t},{isEmpty:()=>!1,pollMs:1e4,initialData:O??void 0,enabled:y,deadlineMs:6e4}),cr=sr.state,lr=(0,_.useCallback)(async(e=!1,t)=>{if(Ue.current&&!e)return!1;Ue.current=!0;let n=++He.current;try{let e=await ar(t??new AbortController().signal);return Va(n,He.current)?(or(e),q(D,e),le.refresh(),!0):!1}catch{return!1}finally{Va(n,He.current)&&(Ue.current=!1)}},[or,D,ar,le.refresh]),ur=(0,_.useCallback)(()=>{let e=Ht.current;bt(null),Ot(null),Nt(null),Ft(!1),window.setTimeout(()=>{e?.isConnected&&e.focus()},0)},[]),dr=(0,_.useCallback)(()=>{zt.current||ur()},[ur]),fr=(0,_.useCallback)(async t=>{let n=yt;if(!n||zt.current)return;let r=Xn(6e4);Rt.current=r,zt.current=!0,Tt(!0),Ot(null);let i=Mt?.confirmed===!0&&(t===void 0||t===Mt.value),a=t===void 0,o=t===void 0;try{if(t!==void 0){let s=await fetch(`${e}/api/providers/${encodeURIComponent(n.provider)}/model-display-names`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({modelId:n.id,displayName:t}),signal:r.signal}),c=s.ok?await It(s,E(`models.displayNameSaveFailed`)):await s.json();if(r.signal.throwIfAborted(),!c||typeof c!=`object`||Array.isArray(c)||!s.ok&&c.saved!==!0&&typeof c.error!=`string`)throw Error(E(`models.displayNameSaveFailed`));a=!0;let l=s.ok||c.saved===!0;if(i||=l,l){let e=c.displayNameOverride===null?void 0:c.displayNameOverride??t??void 0,r={displayName:c.displayName??e,displayNameOverride:e,displayNameSource:c.displayNameSource??(e?`operator`:void 0)};A(e=>e.map(e=>e.namespaced===n.namespaced?{...e,...r}:e)),bt({...n,...r}),Ft(r.displayName===void 0)}if(!s.ok)throw Error(c.error||E(`models.displayNameSaveFailed`));o=!0}if(!await lr(!0,r.signal))throw Error(E(`models.loadFail`));r.signal.throwIfAborted(),Le(!0,E(i?t===null||t===void 0&&Mt?.value===null?`models.displayNameResetDone`:`models.displayNameSaved`:`models.displayNameReloaded`)),ur()}catch(e){if(Rt.current!==r)return;let n=!a||r.signal.aborted;n&&!i&&Ft(!0),Nt(i||n||o?{value:o||n?void 0:t,confirmed:i}:null),Ot(i?E(`models.displayNameSavedRefreshFailed`):n||o?E(`models.displayNameOutcomeUnknown`):e instanceof Error&&e.message?e.message:E(`models.displayNameSaveFailed`))}finally{r.clear(),Rt.current===r&&(Rt.current=null,zt.current=!1,Tt(!1))}},[e,yt,Mt,ur,lr,Le,E]);(0,_.useEffect)(()=>{if(!y)return;let e=window.setTimeout(()=>{rr(),ir(),Rr(),zr()},0),t=er(()=>{ct.current||ir()},1e4);return()=>{window.clearTimeout(e),t()}},[y,rr,ir]);let pr=(0,_.useMemo)(()=>Sg(k,j),[k,j]),mr=k.length>0||cr.data!==void 0,hr=e=>{let t=[...new Set([...e.rows.map(e=>e.id),...e.configuredModels,...Object.keys(e.modelContextWindows??{})])].sort(),n=t[0]??``;xn(e.provider),wn(t),Dn(n);let r=e.contextWindow?String(e.contextWindow):``,i=Object.fromEntries(Object.entries(e.modelContextWindows??{}).map(([e,t])=>[e,String(t)]));kn(r),jn(i),Nn({contextWindow:e.contextWindow??null,modelContextWindows:Object.fromEntries(Object.entries(e.modelContextWindows??{}).map(([e,t])=>[e,t]))}),Fn(new Set),Rn(!1),Un(``)},gr=e=>{Dn(e)},_r=async()=>{if(!bn)return;let t=Eg(On);if(!pr.find(e=>e.provider===bn)){Un(E(`models.contextSaveFailed`));return}if(In&&t===void 0){Un(E(`models.contextInvalid`));return}let n={};for(let e of Pn){let t=Eg(An[e]??``);if(t===void 0){Un(E(`models.contextInvalid`));return}t!==(Mn.modelContextWindows[e]??null)&&(n[e]=t)}let r=In&&t!==Mn.contextWindow;if(!r&&Object.keys(n).length===0){xn(null),Le(!0,E(`models.contextUnchanged`));return}Vn(!0),Un(``);try{let i={};r&&(i.contextWindow=t),Object.keys(n).length>0&&(i.modelContextWindows=n),await It(await fetch(`${e}/api/providers?name=${encodeURIComponent(bn)}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify(i)}),E(`models.contextSaveFailed`))}catch(e){Un(e instanceof Error?e.message:E(`models.contextSaveFailed`));return}finally{Vn(!1)}xn(null),Le(!0,E(`models.contextSaved`)),await lr(!0)};(0,_.useEffect)(()=>{if(!Oe.current||pr.length===0)return;Oe.current=!1;let e=new Set(pr.map(e=>e.provider));De(e),Go(e)},[pr]);let vr=(0,_.useMemo)(()=>F?k.filter(e=>za(F,e.provider,e.id,e.native===!0,N.has(e.namespaced))).length:0,[N,k,F]),yr=(0,_.useMemo)(()=>({catalog:mr?E(`models.active`,{active:vr,total:k.length}):void 0,combos:b===null?void 0:String(b),routing:S===null?void 0:String(S),compatibility:w===null?void 0:String(w)}),[mr,b,w,vr,k.length,S,E]),br=async(t,n,r,i)=>{if(Ve.current)return;Ve.current=!0,++He.current,ze(!0),Be.current=!0,Ae(``);let a=null;try{let o=await Ba(e,t,n,r,i);if(!o.ok)a=`models.saveFailed`;else{let e=Na(await o.json());e!==void 0&&Me(e)}}catch{a=`models.networkError`}finally{let e=await lr(!0);a?(Pe(!1),Ae(E(a))):e&&(Pe(!0),Ae(E(`models.applied`))),ze(!1),Be.current=!1,Ve.current=!1}},xr=async t=>{ze(!0),Be.current=!0,Ae(``);let n=U[t]===void 0;try{let r=await fetch(`${e}/api/provider-context-caps`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:t,enabled:n})});try{let e=await It(r,E(`models.capSaveFailed`));W(e?.caps??{}),K(e?.values??e?.caps??{}),Pe(!0),Ae(E(`models.capApplied`)),await lr(!0)}catch(e){Pe(!1),Ae(e instanceof Error?e.message:E(`models.capSaveFailed`))}}catch{Pe(!1),Ae(E(`models.networkError`))}finally{ze(!1),Be.current=!1}},Sr=e=>{De(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),Go(n),n})},Cr=e=>{De(()=>{let t=e?new Set(pr.map(e=>e.provider)):new Set;return Go(t),t})},wr=async t=>{ze(!0),Be.current=!0,Ae(``);try{let n=await fetch(`${e}/api/provider-context-caps`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});try{let e=await It(n,E(`models.capSaveFailed`));typeof e?.value==`number`&&Number.isFinite(e.value)&&e.value>0&&X(e.value),W(e?.caps??{}),K(e?.values??e?.caps??{}),Pe(!0),Ae(E(`models.capApplied`)),await lr(!0)}catch(e){Pe(!1),Ae(e instanceof Error?e.message:E(`models.capSaveFailed`))}}catch{Pe(!1),Ae(E(`models.networkError`))}finally{ze(!1),Be.current=!1}},Er=(0,_.useMemo)(()=>{let e=pr.filter(e=>!e.native);return e.length>0&&e.every(e=>U[e.provider]===J)&&Object.keys(U).every(e=>U[e]===J)},[pr,U,J]),Dr=e=>{!Number.isSafeInteger(e)||e<=0||wr(Er?{value:e,setAll:!0}:{value:e})},Or=(e,t)=>{if(t===`custom`){xe(t=>({...t,[e]:!0})),we(t=>({...t,[e]:String(U[e]??G[e]??J)}));return}xe(t=>({...t,[e]:!1}));let n=Number(t);Number.isSafeInteger(n)&&n>0&&n!==U[e]&&wr({provider:e,enabled:!0,value:n})},Ar=e=>{let t=Number((Se[e]??``).replace(/[_,\s]/g,``));if(!Number.isSafeInteger(t)||t<=0){Le(!1,E(`models.capSaveFailed`));return}xe(t=>({...t,[e]:!1})),wr({provider:e,enabled:!0,value:t})},Mr=e=>{if(e===`custom`){ye(!0),me(String(J));return}ye(!1);let t=Number(e);Number.isSafeInteger(t)&&t>0&&t!==J&&Dr(t)},Nr=()=>{let e=Number(pe.replace(/[_,\s]/g,``));if(!Number.isSafeInteger(e)||e<=0){Le(!1,E(`models.capSaveFailed`));return}ye(!1),Dr(e)},Pr=()=>{wr({setAll:!Er})},Fr=async t=>{if(!(!qn||Yn)){Zn(!0),Jn({...qn,...t});try{await fetch(`${e}/api/shadow-call-settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)})}finally{Zn(!1)}}},Ir=async t=>{if(!(!We||ct.current)){at(!0),ct.current=!0,st(``),Ae(``);try{let n=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});try{let e=await It(n,E(`models.saveFailed`));if(!e||typeof e.enabled!=`boolean`){Pe(!1),Ae(E(`models.saveFailed`));return}Ge({enabled:e.enabled,agentsMaxThreadsConflict:e.agentsMaxThreadsConflict===!0,maxConcurrentThreadsPerSession:typeof e.maxConcurrentThreadsPerSession==`number`?e.maxConcurrentThreadsPerSession:null,multiAgentMode:e.multiAgentMode===`v1`||e.multiAgentMode===`v2`?e.multiAgentMode:`default`,keepNativeChatGptOnV1:e.keepNativeChatGptOnV1===!0}),Pe(!0),Ae(E(`models.v2Applied`)),st((e.warnings??[]).join(` `))}catch(e){Pe(!1),Ae(e instanceof Error?e.message:E(`models.saveFailed`))}}catch{Pe(!1),Ae(E(`models.networkError`))}finally{at(!1),ct.current=!1}}},Lr=async e=>{if(!(!We||We.multiAgentMode===e)){if(e===`v1`){await Ir({multiAgentMode:`v1`});return}gt(e)}},Rr=async()=>{try{let t=Xn(15e3),n=await Lt(await fetch(`${e}/api/model-presets`,{signal:t.signal}));qe(n?.providers??{})}catch{qe({})}},zr=async()=>{try{let t=await fetch(`${e}/api/model-discovery`);Ye(await Lt(t)??null)}catch{Ye(null)}},Br=async(t,n)=>{await Lt(await fetch(`${e}/api/model-discovery`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({policy:t,provider:n??null})})),await Promise.all([zr(),lr()])},Vr=async(t,n)=>{if(!Ve.current){Ve.current=!0,tt(t),ze(!0),Be.current=!0;try{let r=Xn(3e4),i=await It(await fetch(`${e}/api/model-presets`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({provider:t,mode:n}),signal:r.signal}),E(`models.saveFailed`));if(!i)throw Error(E(`models.saveFailed`));if(i.fallback===`preset-empty`)Le(!1,E(`models.presetEmpty`,{provider:t}));else{let e=Na(i);e!==void 0&&Me(e),Le(!0,n===`all`?E(`models.presetClearedToast`,{provider:t}):E(`models.presetAppliedToast`,{provider:t,count:String(i.selected?.length??0)}))}await Promise.all([Rr(),lr()])}catch(e){Le(!1,e instanceof Error?e.message:String(e))}finally{tt(null),ze(!1),Be.current=!1,Ve.current=!1}}},Hr=async e=>{!We||We.keepNativeChatGptOnV1===e||await Ir({keepNativeChatGptOnV1:e})},Ur=async t=>{if(!(!We||ct.current)){if(!Number.isInteger(t)||t<1){Le(!1,E(`models.v2ThreadsInvalid`));return}if(We.maxConcurrentThreadsPerSession!==t){at(!0),ct.current=!0,st(``),Ae(``);try{let n=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({maxConcurrentThreadsPerSession:t})});try{let e=await It(n,E(`models.saveFailed`));if(!e||typeof e.enabled!=`boolean`){Pe(!1),Ae(E(`models.saveFailed`));return}Ge({enabled:e.enabled,agentsMaxThreadsConflict:e.agentsMaxThreadsConflict===!0,maxConcurrentThreadsPerSession:typeof e.maxConcurrentThreadsPerSession==`number`?e.maxConcurrentThreadsPerSession:null,multiAgentMode:e.multiAgentMode===`v1`||e.multiAgentMode===`v2`?e.multiAgentMode:`default`,keepNativeChatGptOnV1:e.keepNativeChatGptOnV1===!0}),Pe(!0),Ae(E(`models.v2ThreadsApplied`)),ft(!1)}catch(e){Pe(!1),Ae(e instanceof Error?e.message:E(`models.saveFailed`))}}catch{Pe(!1),Ae(E(`models.networkError`))}finally{at(!1),ct.current=!1}}}},Wr=e=>{if(e===`custom`){ft(!0),ut(String(We?.maxConcurrentThreadsPerSession??``));return}ft(!1),Ur(Number(e))},Gr=(e,t)=>{Kn.current&&clearTimeout(Kn.current),Kn.current=setTimeout(()=>{Gn({namespaced:e,rect:t.getBoundingClientRect()})},300)},Kr=(e,t)=>{Kn.current&&clearTimeout(Kn.current),Gn({namespaced:e,rect:t.getBoundingClientRect()})},qr=()=>{Kn.current&&clearTimeout(Kn.current),Kn.current=setTimeout(()=>Gn(null),120)},Jr=()=>{Kn.current&&clearTimeout(Kn.current)},Yr=async(t,n,r,i,a,o)=>{_n(!0),yn(``);try{let s=await fetch(`${e}/api/custom-models`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:t,modelId:n,displayName:r,contextWindow:i,inputModalities:a,reasoningEfforts:o})});try{await It(s,E(`models.customSaveFailed`)),vt(!1),Le(!0,E(`models.customAdded`)),await lr(!0)}catch(e){yn(e instanceof Error?e.message:E(`models.customSaveFailed`))}}catch{yn(E(`models.networkError`))}finally{_n(!1)}},Xr=async(t,n)=>{_n(!0),yn(``);try{let r=await fetch(`${e}/api/custom-models/${encodeURIComponent(t)}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});try{await It(r,E(`models.customSaveFailed`)),vt(!1),Le(!0,E(`models.customUpdated`)),await lr(!0)}catch(e){yn(e instanceof Error?e.message:E(`models.customSaveFailed`))}}catch{yn(E(`models.networkError`))}finally{_n(!1)}},Zr=async t=>{try{(await fetch(`${e}/api/custom-models/${encodeURIComponent(t)}`,{method:`DELETE`})).ok?(Le(!0,E(`models.customDeleted`)),await lr(!0)):Le(!1,E(`models.customSaveFailed`))}catch{Le(!1,E(`models.networkError`))}},Qr=cr.data??O,$r=cr.kind===`failed-cold`?cr.error instanceof Error?cr.error.message:E(`models.loadFail`):null,ei=cr.showSkeleton&&!Qr,ti=F??{},ni=e=>{let{provider:t,rows:n,nativeProviderGroup:r,liveModels:i,discovery:a}=e,o=Ee.has(t),s=e=>za(ti,t,e.id,e.native===!0,N.has(e.namespaced)),c=z[t]===!0,l=Do(n),u=ko(c,n),d=Oo(n,u),f=d.filter(s).length,p=Je?.recentArrivals[t]??[],m=new Set(p.map(e=>e.id)),h=U[t]!==void 0,g=U[t]??G[t]??J,_=e.nativeProviderGroup?Fo:No,v=e.nativeProviderGroup?Io:Po,y=i&&a?.status===`failed`?a:void 0,b=(L[t]??``).trim().toLowerCase(),x=b?d.filter(e=>e.id.toLowerCase().includes(b)):d,S=x.toSorted((e,t)=>Number(!s(e))-Number(!s(t))),C=V[t]??60,w=S.slice(0,C),T=x.length-w.length,D=d.length>0,O=n.some(e=>e.initialSelectionPending),k=!D||d.every(s),A=!D||d.every(e=>!s(e)),j=e=>{!D||O||br(`provider`,t,d.map(e=>({id:e.id,native:e.native===!0})),e)};return(0,Y.jsxs)(`div`,{className:`card models-provider-card`,children:[(0,Y.jsxs)(`div`,{className:`row group-head models-provider-head${o?``:` open`}`,children:[(0,Y.jsxs)(`button`,{type:`button`,className:`row models-provider-toggle`,onClick:()=>Sr(t),"aria-expanded":!o,style:{flex:`1 1 auto`,border:0,background:`transparent`,padding:0,color:`inherit`,cursor:`pointer`,textAlign:`left`},children:[(0,Y.jsx)(Ce,{style:{width:14,height:14,color:`var(--muted)`,transform:o?`none`:`rotate(90deg)`,transition:`transform .12s`}}),(0,Y.jsx)(`span`,{className:`text-body font-semibold`,style:{whiteSpace:`nowrap`},children:zn(t)}),Xe.providers[t]&&(0,Y.jsx)(`span`,{className:`models-chip mono text-caption`,children:Xe.providers[t]}),r&&(0,Y.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:E(`models.nativeGroupLabel`)}),y&&(0,Y.jsx)(`span`,{className:`badge badge-amber`,role:`status`,title:Eo(E,y),children:E(`models.discoveryFailedBadge`)}),(0,Y.jsx)(`span`,{className:`muted mono text-label`,children:E(`models.active`,{active:f,total:d.length})}),p.length>0&&(0,Y.jsx)(`span`,{className:`models-chip mono text-caption`,children:E(`models.newCount`,{count:p.length})})]}),(0,Y.jsxs)(`div`,{className:`row models-provider-actions`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm models-alias-edit`,"aria-label":E(`models.editProviderAlias`),title:E(`models.editProviderAlias`),onClick:()=>void Wt(t),children:(0,Y.jsx)(ge,{style:{width:14,height:14}})}),(0,Y.jsx)(Dt,{on:Xe.defaults.providers[t]??Xe.defaults.global,onClick:()=>void Kt(!(Xe.defaults.providers[t]??Xe.defaults.global),t),label:E(`models.useDefaultAliases`),showLabel:!0}),(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:e=>{e.stopPropagation(),Jt(`add`),Xt(t),Qt(``),en(``),nn(``),an(``),sn(!1),ln([`text`]),dn(!1),pn([]),mn.current=!1,yn(``),vt(!0)},"aria-haspopup":`dialog`,children:[(0,Y.jsx)(`span`,{"aria-hidden":`true`,children:`+`}),` `,E(`models.customAdd`)]}),(()=>{let e=Ke[t];if(!e)return null;let n=Re||et!==null,r=e.mode===`custom`&&e.appliedVersion!==void 0&&e.appliedVersion<e.availableVersion;return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":E(`models.presetLabel`),children:[[`preset`,`all`].map(r=>(0,Y.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":e.mode===r,className:`btn btn-sm${e.mode===r?` btn-primary`:` btn-ghost`}`,style:{background:e.mode===r?void 0:`transparent`,color:e.mode===r?void 0:`var(--muted)`},disabled:Re||n||O,onClick:n=>{n.stopPropagation(),!(r===`preset`&&e.mode===`custom`&&!confirm(E(`models.presetConfirmReplace`,{count:String(e.presetCount)})))&&Vr(t,r)},children:E(`models.presetMode_${r}`)},r)),e.mode===`custom`&&(0,Y.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":!0,className:`btn btn-sm btn-primary`,disabled:!0,children:E(`models.presetMode_custom`)})]}),e.mode===`preset`&&(0,Y.jsx)(`span`,{className:`muted mono text-label`,children:E(`models.presetSummary`,{count:String(e.presetCount),total:String(e.totalCount),version:String(e.availableVersion)})}),r&&(0,Y.jsx)(`span`,{className:`badge badge-amber`,role:`status`,children:E(`models.presetUpdateAvailable`,{version:String(e.availableVersion)})})]})})(),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,disabled:Re||k||O,onClick:()=>j(!0),children:E(`models.allOn`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,disabled:Re||A||O,onClick:()=>j(!1),children:E(`models.allOff`)}),(0,Y.jsxs)(`div`,{className:`models-cap-cluster`,children:[(0,Y.jsx)(Dt,{on:h,onClick:()=>xr(t),disabled:Re,label:E(`models.contextCapLabel`),showLabel:!0}),(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(kt,{value:be[t]?Lo:String(g),options:[...!v.has(g)&&!be[t]?[{value:String(g),label:Vo(g)}]:[],..._.map(e=>({value:String(e),label:Vo(e)})),{value:Lo,label:E(`models.custom`)}],onChange:e=>Or(t,e),disabled:Re||!h,label:E(`models.capValue`,{value:Vo(g)}),title:E(`models.contextCapLabel`)}),h&&be[t]&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`input`,{className:`input`,style:{width:120},inputMode:`numeric`,placeholder:E(`models.customPlaceholder`),value:Se[t]??``,onChange:e=>we(n=>({...n,[t]:e.target.value})),onKeyDown:e=>{e.key===`Enter`&&Ar(t)},disabled:Re,"aria-label":E(`models.customPlaceholder`)}),(0,Y.jsx)(`button`,{type:`button`,onClick:()=>Ar(t),disabled:Re,className:`btn btn-ghost btn-sm`,children:E(`models.customApply`)})]})]}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>hr(e),"aria-haspopup":`dialog`,children:E(`models.contextSettings`)})]})]})]}),!o&&(0,Y.jsxs)(`div`,{className:`models-provider-body`,children:[r&&(0,Y.jsx)(`p`,{className:`muted text-label models-provider-hint`,children:E(`models.nativeHint`)}),!r&&Je&&(0,Y.jsxs)(`div`,{className:`row models-provider-hint`,children:[(0,Y.jsx)(`span`,{className:`muted text-label`,children:E(`models.newPolicyProvider`)}),(0,Y.jsx)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":E(`models.newPolicyProvider`),children:[`off`,`on`].map(e=>(0,Y.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":(Je.providers[t]??`inherit`)===e,className:`btn btn-sm${(Je.providers[t]??`inherit`)===e?` btn-primary`:` btn-ghost`}`,onClick:()=>void Br(e,t),children:E(`models.newPolicy_${e}`)},e))})]}),n.length===0&&(0,Y.jsx)(Cg,{liveModels:i,discovery:a,showFailureBadge:!1}),n.length>0&&y&&(0,Y.jsx)(wg,{}),l&&(0,Y.jsx)(`div`,{className:`row models-provider-hint`,children:(0,Y.jsx)(Dt,{on:c,onClick:()=>B(e=>({...e,[t]:!c})),label:E(`models.freeOnly`),showLabel:!0})}),u&&d.length===0&&n.length>0&&(0,Y.jsx)(`p`,{className:`muted text-label`,role:`status`,children:E(`models.noFreeMatch`)}),n.length>30&&(0,Y.jsx)(`input`,{className:`input`,placeholder:E(`models.search`),value:L[t]??``,onChange:e=>R(n=>({...n,[t]:e.target.value})),"aria-label":E(`models.search`)}),w.map(e=>{let n=!s(e);return(0,Y.jsxs)(`div`,{className:`model-row-wrap`,onMouseEnter:t=>Gr(e.namespaced,t.currentTarget),onMouseLeave:qr,onFocus:t=>Kr(e.namespaced,t.currentTarget),onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||Gn(null)},children:[(0,Y.jsxs)(`div`,{className:`row models-model-row`,children:[(0,Y.jsx)(Dt,{on:!n,onClick:()=>void br(`models`,t,[{id:e.id,native:e.native===!0}],n),disabled:Re||e.initialSelectionPending,label:e.native?e.id:e.namespaced}),e.initialSelectionPending&&(0,Y.jsx)(`span`,{className:`models-chip muted`,role:`status`,children:E(`models.initialSelectionPending`)}),e.quotaInactiveReason===`no_credit`&&(0,Y.jsx)(`span`,{className:`models-chip muted`,role:`status`,title:E(`models.inactiveNoCreditHint`),children:E(`models.inactiveNoCredit`)}),Xe.models[t]?.[e.id]&&(0,Y.jsx)(`strong`,{className:`mono text-control`,children:Xe.models[t][e.id].alias}),(0,Y.jsxs)(`span`,{className:`models-model-identity`,children:[(0,Y.jsx)(`code`,{className:`mono text-control`,style:{color:n?`var(--faint)`:`var(--text)`,textDecoration:n?`line-through`:`none`},children:e.native?tf(e.id):e.namespaced}),!e.native&&e.displayName?.trim()&&e.displayName.trim()!==e.namespaced&&(0,Y.jsx)(`span`,{className:`models-model-friendly text-caption`,children:e.displayName.trim()})]}),Xe.models[t]?.[e.id]?.source===`builtin`&&(0,Y.jsx)(`span`,{className:`models-chip muted text-caption`,children:E(`models.aliasAuto`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":E(`models.editModelAlias`),title:E(`models.editModelAlias`),onClick:()=>void Gt(t,e.id),children:(0,Y.jsx)(ge,{style:{width:13,height:13}})}),!e.native&&!e.custom&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption models-display-name-trigger`,"aria-haspopup":`dialog`,"aria-label":E(`models.displayNameActionLabel`,{model:e.namespaced}),onClick:t=>{Ht.current=t.currentTarget,Ot(null),Nt(null),Ft(!1),bt(e)},children:E(`models.displayNameAction`)}),e.custom&&(0,Y.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:E(`models.customBadge`)}),!e.native&&e.provider!==`combo`&&(0,Y.jsxs)(Y.Fragment,{children:[e.manualPricing===!0&&(0,Y.jsx)(`span`,{className:`models-chip muted text-caption`,children:E(`pricing.override.badge`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption models-display-name-trigger`,"aria-haspopup":`dialog`,"aria-label":E(`pricing.override.actionLabel`,{model:e.namespaced}),onClick:t=>{Ct.current=t.currentTarget,St(e)},children:E(`pricing.override.action`)})]}),!e.custom&&m.has(e.id)&&(0,Y.jsx)(`span`,{className:`badge badge-amber`,children:E(`models.newBadge`)}),e.contextCapped&&(0,Y.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:E(`models.contextCappedValue`,{value:Vo(e.contextCap??J)})})]}),Wn?.namespaced===e.namespaced&&(()=>{let t=Wn.rect,r=t.bottom+4,i=r+360>window.innerHeight;return(0,Y.jsxs)(`div`,{className:`model-tip${e.custom?` has-actions`:``}${i?` flip-up`:``}`,role:`tooltip`,style:{position:`fixed`,left:t.left+24,...i?{bottom:window.innerHeight-t.top+4}:{top:r}},onMouseEnter:Jr,onMouseLeave:qr,children:[(0,Y.jsx)(`div`,{className:`model-tip-id`,children:e.native?e.id:e.namespaced}),e.displayName&&(0,Y.jsx)(`div`,{className:`model-tip-display`,children:e.displayName}),e.custom&&(0,Y.jsx)(`span`,{className:`models-chip models-chip--tip muted mono text-caption`,children:E(`models.customBadge`)}),(0,Y.jsxs)(`div`,{className:`model-tip-grid`,children:[(0,Y.jsx)(`span`,{className:`model-tip-key`,children:E(`models.tipProvider`)}),(0,Y.jsx)(`span`,{className:`model-tip-val`,children:Ln(e.provider,E)}),(e.contextWindow||e.contextCap)&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`span`,{className:`model-tip-key`,children:E(`models.tipContext`)}),(0,Y.jsx)(`span`,{className:`model-tip-val`,children:Vo(e.contextWindow??e.contextCap??0)})]}),e.inputModalities&&e.inputModalities.length>0&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`span`,{className:`model-tip-key`,children:E(`models.tipModalities`)}),(0,Y.jsx)(`span`,{className:`model-tip-val`,children:e.inputModalities.join(`, `)})]}),(0,Y.jsx)(`span`,{className:`model-tip-key`,children:E(`models.tipStatus`)}),(0,Y.jsx)(`span`,{className:`model-tip-val`,children:E(n?`models.tipDisabled`:`models.tipActive`)})]}),e.custom&&e.customId&&(0,Y.jsxs)(`div`,{className:`model-tip-actions`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>{Jt(`edit`),Xt(e.provider),Qt(e.customId),en(e.id),nn(e.displayName??``),an(e.contextWindow?String(e.contextWindow):``),sn(!1),ln(e.inputModalities??[`text`]),dn(Array.isArray(e.reasoningEfforts)),pn(e.reasoningEfforts??[]),mn.current=Array.isArray(e.reasoningEfforts),yn(``),vt(!0),Gn(null)},children:E(`models.customEdit`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,style:{color:`var(--red)`},onClick:()=>{window.confirm(E(`models.customDeleteConfirm`,{name:e.displayName??e.id}))&&Zr(e.customId),Gn(null)},children:E(`models.customDelete`)})]})]})})()]},e.namespaced)}),T>0&&(0,Y.jsx)(`button`,{type:`button`,onClick:()=>H(e=>({...e,[t]:C+60})),className:`btn btn-ghost btn-sm models-show-more`,children:E(`models.showMore`,{n:T})})]})]},t)},ri=Qn?pr.filter(e=>e.provider===Qn):pr,ii=(e,t=!1)=>{let n={pickerOrder:e.pickerOrder,pickerOrderMode:e.pickerOrderMode,pickerAvailable:[]};q(ee,n),kr(ee,n),t&&re(`custom`),le.refresh();let r=e.catalogRefresh,i=typeof r==`object`&&!!r&&`status`in r&&r.status===`committed`&&`degraded`in r&&r.degraded===!1;Le(i,E(i?`models.pickerOrder.saved`:`models.pickerOrder.pending`)),l()},ai=async()=>{if(oe.current||!ue||le.state.showError||fe===`custom`)return;let t=se.current,n=fe,r=ue.pickerAvailable,i=Xn(15e3);oe.current=i,ae(!0);let a=()=>se.current===t&&oe.current===i,o=()=>a()&&!i.signal.aborted;try{let t=[];if(n===`most-used`){let n=await fetch(`${e}/api/usage?range=all&surface=all`,{signal:i.signal});if(!o())return;let r=await It(n,E(`models.pickerOrder.usageFailed`));if(!o())return;if(r?.usageIncomplete===!0)throw Error(E(`models.pickerOrder.usageIncomplete`));if(!pd(r?.models))throw Error(E(`models.pickerOrder.usageFailed`));t=r.models}if(!o())return;let a=_d(n,r,t,k),s=await fetch(`${e}/api/subagent-models`,{method:`PUT`,headers:{"Content-Type":`application/json`},signal:i.signal,body:JSON.stringify({pickerOrder:a,pickerOrderMode:n==="default"?null:n})});if(!o())return;let c=await It(s,E(`models.saveFailed`));if(!dd(c)||!(`ok`in c)||c.ok!==!0)throw Error(E(`models.saveFailed`));if(!o())return;ii({pickerOrder:c.pickerOrder,pickerOrderMode:c.pickerOrderMode,catalogRefresh:`catalogRefresh`in c?c.catalogRefresh:void 0}),re(null)}catch(e){a()&&Le(!1,e instanceof Error?e.message:E(`models.networkError`))}finally{i.clear(),a()&&(oe.current=null,ae(!1))}},oi=(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{className:`models-control-top-row`,children:[Je&&(0,Y.jsxs)(`div`,{className:`models-shadow-row row muted text-control`,children:[(0,Y.jsx)(`span`,{className:`models-shadow-label`,children:E(`models.newPolicyGlobal`)}),(0,Y.jsx)(Dt,{on:Je.policy===`off`,onClick:()=>void Br(Je.policy===`off`?`on`:`off`),label:E(`models.newPolicyGlobal`)})]}),(0,Y.jsxs)(`div`,{className:`row`,children:[(0,Y.jsx)(Dt,{on:Xe.defaults.global,onClick:()=>void Kt(!Xe.defaults.global),label:E(`models.useDefaultAliasesGlobal`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>$e(e=>!e),children:E(`models.aliases`)})]}),(0,Y.jsxs)(`div`,{className:`models-shadow-row row muted text-control`,"aria-busy":!qn||void 0,children:[(0,Y.jsxs)(`span`,{className:`models-shadow-label`,children:[E(`models.shadowCallIntercept`),` `,(0,Y.jsx)(jt,{content:E(`models.shadowCallInterceptHint`,{models:Bt(qn?.sourceModels)}),side:`top`,maxWidth:320,children:(0,Y.jsx)(`span`,{style:{cursor:`help`},"aria-label":E(`models.shadowCallInterceptHint`,{models:Bt(qn?.sourceModels)}),children:`ⓘ`})})]}),(0,Y.jsx)(`code`,{className:`text-caption models-shadow-warning`,style:{opacity:.6},children:E(`models.shadowCallOriginal`,{models:Vt(qn?.sourceModels)})}),(0,Y.jsx)(Dt,{on:qn?.enabled??!1,onClick:()=>void Fr({enabled:!qn?.enabled}),disabled:!qn||Yn,label:E(`models.shadowCallIntercept`)}),(0,Y.jsx)(`div`,{className:`models-shadow-model-slot`,children:(0,Y.jsx)(kt,{value:qn?.model??``,options:nr,onChange:e=>{Jn(t=>t&&{...t,model:e}),Fr({model:e})},disabled:!qn||Yn||!qn.enabled,label:E(`models.shadowCallIntercept`)})})]}),(nt||We)&&(0,Y.jsxs)(`div`,{className:`models-v2-mode-row row`,children:[(0,Y.jsx)(`span`,{className:`muted text-control`,children:E(`models.v2Label`)}),(0,Y.jsx)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":E(`models.v2Label`),children:[`v1`,`default`,`v2`].map(e=>(0,Y.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":(We?.multiAgentMode??`default`)===e,className:`btn btn-sm${(We?.multiAgentMode??`default`)===e?` btn-primary`:` btn-ghost`}`,style:{background:(We?.multiAgentMode??`default`)===e?void 0:`transparent`,color:(We?.multiAgentMode??`default`)===e?void 0:`var(--muted)`},disabled:!We||it,onClick:()=>void Lr(e),children:E(`models.v2Mode_${e}`)},e))}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{width:24,height:24,minWidth:24,flex:`0 0 24px`,padding:0,borderRadius:`var(--radius-pill)`,color:`var(--muted)`},disabled:!We,onClick:()=>mt(!0),"aria-label":E(`models.v2Label`),"aria-haspopup":`dialog`,children:(0,Y.jsx)(ve,{width:14,height:14,"aria-hidden":`true`})})]}),We&&We.multiAgentMode===`v2`&&(0,Y.jsx)(`div`,{className:`models-v2-keep-native-row`,children:(0,Y.jsxs)(`div`,{className:`models-v2-keep-native`,children:[(0,Y.jsx)(`span`,{className:`models-v2-keep-native-label text-caption`,children:E(`models.keepNativeOnV1`)}),(0,Y.jsx)(Dt,{on:We.keepNativeChatGptOnV1===!0,onClick:()=>void Hr(!We.keepNativeChatGptOnV1),disabled:it,label:E(`models.keepNativeOnV1`)}),(0,Y.jsx)(jt,{content:E(`models.keepNativeOnV1Hint`),side:`top`,maxWidth:360,children:(0,Y.jsx)(`span`,{className:`models-v2-keep-native-info`,"aria-label":E(`models.keepNativeOnV1Hint`),children:(0,Y.jsx)(ve,{width:13,height:13,"aria-hidden":`true`})})})]})}),ht&&(0,Y.jsx)(Tn,{reason:`selection`,mode:ht,docsUrl:Cn(We?.multiAgentSurfaceAdvisory)?.docsUrl??`https://opencodex.me/guides/subagent-v1-default/`,busy:it,onContinue:()=>{let e=ht;gt(null),Ir({multiAgentMode:e,multiAgentSurfaceAdvisoryAcknowledged:!0})},onChooseV1:()=>{gt(null),We?.multiAgentMode!==`v1`&&Ir({multiAgentMode:`v1`,multiAgentSurfaceAdvisoryAcknowledged:!0})},onDismiss:()=>gt(null)})]}),We&&(We.enabled||We.agentsMaxThreadsConflict||ot)&&(0,Y.jsxs)(`div`,{className:`models-v2-detail-row row`,children:[We.enabled&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`span`,{className:`muted text-control`,children:E(`models.v2ThreadsLabel`)}),(0,Y.jsx)(kt,{value:dt?`custom`:We.maxConcurrentThreadsPerSession!==null&&We.maxConcurrentThreadsPerSession!==void 0?zo.has(We.maxConcurrentThreadsPerSession)?String(We.maxConcurrentThreadsPerSession):`custom`:``,options:[...We.maxConcurrentThreadsPerSession===null||We.maxConcurrentThreadsPerSession===void 0?[{value:``,label:E(`models.v2ThreadsDefault`)}]:[],...We.maxConcurrentThreadsPerSession!==null&&We.maxConcurrentThreadsPerSession!==void 0&&!zo.has(We.maxConcurrentThreadsPerSession)&&!dt?[{value:`custom`,label:String(We.maxConcurrentThreadsPerSession)}]:[],...Ro.map(e=>({value:String(e),label:String(e)})),{value:`custom`,label:E(`models.custom`)}],onChange:e=>Wr(e),disabled:it,label:E(`models.v2ThreadsLabel`)}),dt&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`input`,{className:`input`,style:{width:100},inputMode:`numeric`,value:lt,onChange:e=>ut(e.target.value),onKeyDown:e=>{e.key===`Enter`&&Ur(Number(lt.replace(/[_,\s]/g,``)))},disabled:it,"aria-label":E(`models.v2ThreadsLabel`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:it,onClick:()=>{Ur(Number(lt.replace(/[_,\s]/g,``)))},children:E(`models.v2ThreadsApply`)})]})]}),We.enabled&&We.agentsMaxThreadsConflict&&(0,Y.jsx)(`span`,{className:`mono text-label`,style:{color:`var(--err, #e5484d)`},children:E(`models.v2Conflict`)}),ot&&(0,Y.jsx)(`span`,{className:`muted text-label`,children:ot})]}),(0,Y.jsxs)(`div`,{className:`row models-cap-row`,children:[(0,Y.jsx)(`span`,{className:`muted text-control`,children:E(`models.contextCapLabel`)}),(0,Y.jsx)(kt,{value:he?Lo:String(J),options:[...!Po.has(J)&&!he?[{value:String(J),label:Vo(J)}]:[],...No.map(e=>({value:String(e),label:Vo(e)})),{value:Lo,label:E(`models.custom`)}],onChange:e=>Mr(e),disabled:Re,label:E(`models.contextCapLabel`)}),he&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`input`,{className:`input`,style:{width:160},inputMode:`numeric`,placeholder:E(`models.customPlaceholder`),value:pe,onChange:e=>me(e.target.value),onKeyDown:e=>{e.key===`Enter`&&Nr()},disabled:Re,"aria-label":E(`models.customPlaceholder`)}),(0,Y.jsx)(`button`,{type:`button`,onClick:Nr,disabled:Re,className:`btn btn-ghost btn-sm`,children:E(`models.customApply`)})]}),(0,Y.jsx)(Dt,{on:Er,onClick:Pr,disabled:Re,label:E(`models.setAll`)}),(0,Y.jsx)(`span`,{className:`muted text-label leading-body`,children:E(`models.setAllHint`,{value:Vo(J)})})]}),(0,Y.jsxs)(`div`,{className:`row models-cap-row`,"aria-busy":ie||le.state.refreshing,children:[(0,Y.jsx)(`span`,{className:`muted text-control`,children:E(`models.pickerOrder.label`)}),(0,Y.jsx)(kt,{value:fe,options:[{value:`default`,label:E(`models.pickerOrder.default`)},{value:`alphabetical`,label:E(`models.pickerOrder.alphabetical`)},{value:`provider`,label:E(`models.pickerOrder.provider`)},{value:`most-used`,label:E(`models.pickerOrder.mostUsed`)},{value:`custom`,label:E(`models.pickerOrder.custom`)}],onChange:e=>re(e),disabled:ie||!ue||le.state.showError,label:E(`models.pickerOrder.label`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void ai(),disabled:ie||!ue||le.state.showError||fe===`custom`||fe!=="default"&&ue.pickerAvailable.length===0,children:E(ie?`models.pickerOrder.applying`:`models.pickerOrder.apply`)}),le.state.showError&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`span`,{role:`alert`,children:E(`models.pickerOrder.loadFailed`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>le.refresh(),children:E(`models.pickerOrder.retry`)})]}),(0,Y.jsx)(`span`,{className:`muted text-label leading-body`,children:E(`models.pickerOrder.hint`)})]}),fe===`custom`&&(0,Y.jsx)(Od,{apiBase:e,active:y,identities:k,onBusyChange:ae,onAccepted:e=>ii(e,!0)},e),(()=>{let e=k.filter(e=>e.custom).length;return e===0?null:(0,Y.jsx)(`div`,{className:`row muted text-label models-custom-summary`,children:(0,Y.jsx)(`span`,{className:`models-chip mono text-caption`,children:E(`models.customSummary`,{count:e})})})})(),(0,Y.jsxs)(`div`,{className:`row muted text-label leading-body models-order-hint`,children:[(0,Y.jsx)(ve,{width:15,height:15,"aria-hidden":`true`}),(0,Y.jsx)(`span`,{children:E(`models.orderHint`)})]})]}),si=(0,Y.jsxs)(`div`,{className:`row models-collapse-controls`,children:[(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>Cr(!0),disabled:Re,children:[(0,Y.jsx)(Ce,{width:12,height:12,"aria-hidden":`true`}),` `,E(`models.collapseAll`)]}),(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>Cr(!1),disabled:Re,children:[(0,Y.jsx)(Ce,{width:12,height:12,"aria-hidden":`true`,style:{transform:`rotate(90deg)`}}),` `,E(`models.expandAll`)]})]}),ci=(0,Y.jsx)(Y.Fragment,{children:pr.length===0&&(0,Y.jsx)(At,{icon:(0,Y.jsx)(ne,{}),title:E(`models.noRouted`),children:E(`models.noRoutedHint`)})}),li=(0,Y.jsxs)(Y.Fragment,{children:[pt&&(0,Y.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":E(`models.v2Label`),onClick:()=>mt(!1),onKeyDown:e=>{e.key===`Escape`&&mt(!1)},children:(0,Y.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Y.jsxs)(`div`,{className:`modal-head`,children:[(0,Y.jsx)(`h3`,{children:E(`models.v2Label`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>mt(!1),"aria-label":E(`common.close`),children:`×`})]}),(0,Y.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:E(`models.v2Help`)}),(0,Y.jsx)(`div`,{className:`models-help-link`,children:(0,Y.jsx)(`a`,{className:`text-control`,href:`https://opencodex.me/guides/sub-agent-surface/`,target:`_blank`,rel:`noreferrer`,style:{color:`var(--accent)`},children:E(`models.v2DocsLink`)})}),(0,Y.jsx)(`div`,{className:`modal-actions`,children:(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>mt(!1),children:E(`common.ok`)})})]})}),bn&&(0,Y.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":E(`models.contextSettings`),onClick:()=>{Bn||xn(null)},onKeyDown:e=>{e.key===`Escape`&&!Bn&&xn(null)},children:(0,Y.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Y.jsxs)(`div`,{className:`modal-head`,children:[(0,Y.jsx)(`h3`,{children:E(`models.contextSettingsTitle`,{provider:Ln(bn,E)})}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>xn(null),disabled:Bn,"aria-label":E(`common.close`),children:`×`})]}),Hn&&(0,Y.jsx)($,{tone:`err`,children:Hn}),(0,Y.jsx)(`p`,{className:`modal-desc leading-relaxed`,children:E(`models.contextHint`)}),(0,Y.jsxs)(`div`,{className:`models-context-fields`,children:[(0,Y.jsxs)(`label`,{className:`text-label models-field`,children:[E(`models.contextDefault`),(0,Y.jsx)(`input`,{className:`input`,inputMode:`numeric`,value:On,onChange:e=>{kn(e.target.value),Rn(!0)},disabled:Bn,placeholder:E(`models.contextAutomatic`),autoFocus:!0})]}),Sn.length>0&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{className:`text-label models-field`,children:[E(`models.contextModel`),(0,Y.jsx)(kt,{value:En,options:Sn.map(e=>({value:e,label:e})),onChange:gr,disabled:Bn,label:E(`models.contextModel`)})]}),(0,Y.jsxs)(`label`,{className:`text-label models-field`,children:[E(`models.contextModelOverride`),(0,Y.jsx)(`input`,{className:`input`,inputMode:`numeric`,value:An[En]??``,onChange:e=>{jn(t=>({...t,[En]:e.target.value})),Fn(e=>new Set(e).add(En))},disabled:Bn,placeholder:E(`models.contextAutomatic`)})]})]})]}),(0,Y.jsxs)(`div`,{className:`modal-actions`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>xn(null),disabled:Bn,children:E(`common.cancel`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>void _r(),disabled:Bn,children:E(Bn?`models.customSaving`:`models.customApply`)})]})]})}),_t&&(0,Y.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":E(`models.customAdd`),onClick:()=>{gn||vt(!1)},onKeyDown:e=>{e.key===`Escape`&&!gn&&vt(!1)},children:(0,Y.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Y.jsxs)(`div`,{className:`modal-head`,children:[(0,Y.jsx)(`h3`,{children:E(qt===`add`?`models.customAddTitle`:`models.customEditTitle`,{provider:Ln(Yt,E)})}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>vt(!1),disabled:gn,"aria-label":E(`common.close`),children:`×`})]}),vn&&(0,Y.jsx)($,{tone:`err`,children:vn}),(0,Y.jsxs)(`div`,{className:`models-field-stack`,children:[(0,Y.jsxs)(`label`,{className:`text-label models-field`,children:[E(`models.customFieldModelId`),(0,Y.jsx)(`input`,{className:`input`,value:$t,onChange:e=>en(e.target.value),disabled:gn,placeholder:E(`models.customFieldModelIdPlaceholder`),autoFocus:!0})]}),(0,Y.jsxs)(`label`,{className:`text-label models-field`,children:[E(`models.customFieldDisplayName`),(0,Y.jsx)(`input`,{className:`input`,value:tn,onChange:e=>nn(e.target.value),disabled:gn,placeholder:E(`models.customFieldDisplayNamePlaceholder`)})]}),(0,Y.jsxs)(`label`,{className:`text-label models-field`,children:[E(`models.customFieldContext`),(0,Y.jsxs)(`div`,{className:`row models-field-row`,children:[(0,Y.jsx)(kt,{value:on?`custom`:rn,options:[{value:``,label:`—`},{value:`100000`,label:`100k`},{value:`128000`,label:`128k`},{value:`200000`,label:`200k`},{value:`256000`,label:`256k`},{value:`352000`,label:`352k`},{value:`500000`,label:`500k`},{value:`1000000`,label:`1M`},{value:`custom`,label:E(`models.custom`)}],onChange:e=>{if(e===`custom`){sn(!0);return}sn(!1),an(e)},disabled:gn,label:E(`models.customFieldContext`)}),on&&(0,Y.jsx)(`input`,{className:`input`,style:{width:120},inputMode:`numeric`,value:rn,onChange:e=>an(e.target.value),disabled:gn,placeholder:E(`models.customPlaceholder`),"aria-label":E(`models.customFieldContext`)})]})]}),(0,Y.jsxs)(`div`,{className:`text-label models-field`,children:[E(`models.customFieldModalities`),(0,Y.jsx)(`div`,{className:`row models-field-row`,children:[`text`,`image`,`audio`].map(e=>(0,Y.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,Y.jsx)(`input`,{type:`checkbox`,checked:cn.includes(e),onChange:t=>{ln(n=>t.target.checked?[...n,e]:n.filter(t=>t!==e))},disabled:gn}),(0,Y.jsx)(`span`,{className:`text-control`,children:e})]},e))})]}),(0,Y.jsxs)(`div`,{className:`text-label models-field`,children:[E(`models.customFieldReasoning`),(0,Y.jsx)(`div`,{className:`row models-field-row`,children:(0,Y.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,Y.jsx)(`input`,{type:`checkbox`,checked:un,onChange:e=>{if(dn(e.target.checked),e.target.checked&&!mn.current){mn.current=!0;let e=k.find(e=>e.provider===Yt&&e.id===$t),t=Array.isArray(e?.reasoningEfforts)?e.reasoningEfforts:void 0;pn(t??[...Mo])}},disabled:gn}),(0,Y.jsx)(`span`,{className:`text-control`,children:E(`models.customFieldReasoningOverride`)})]})}),un&&(0,Y.jsx)(`div`,{className:`row models-field-row`,style:{flexWrap:`wrap`},children:Mo.map(e=>(0,Y.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,Y.jsx)(`input`,{type:`checkbox`,checked:fn.includes(e),onChange:t=>{pn(n=>t.target.checked?[...n,e]:n.filter(t=>t!==e))},disabled:gn}),(0,Y.jsx)(`span`,{className:`text-control`,children:E(`models.reasoningEffort.${e}`)})]},e))})]})]}),(0,Y.jsxs)(`div`,{className:`modal-actions`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>vt(!1),disabled:gn,children:E(`common.cancel`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:gn||!$t.trim(),onClick:()=>{let e=$t.trim(),t=tn.trim(),n=rn?Number(rn.replace(/[_,\s]/g,``)):void 0,r=n&&n>0?Math.floor(n):void 0;if(qt===`add`){let n=un?fn:void 0;Yr(Yt,e,t||void 0,r,cn.length>0?cn:void 0,n)}else Xr(Zt,{modelId:e,displayName:t,contextWindow:r??null,inputModalities:cn,reasoningEfforts:un?fn:null})},children:E(gn?`models.customSaving`:qt===`add`?`models.customAddBtn`:`models.customEditBtn`)})]})]})})]}),ui=(0,Y.jsxs)(`div`,{className:`models-workspace-shell`,children:[ke&&(0,Y.jsxs)(`div`,{className:`action-toast notice ${Ne?`notice-ok`:`notice-err`}`,role:`status`,"aria-live":`polite`,children:[Ne?(0,Y.jsx)(ce,{}):(0,Y.jsx)(_e,{}),(0,Y.jsx)(`span`,{children:ke})]}),cr.showError&&(0,Y.jsx)($,{tone:`err`,children:E(`models.loadFail`)}),je.length>0&&(0,Y.jsx)(`div`,{className:`models-integration-warning`,children:(0,Y.jsxs)($,{tone:`warn`,children:[E(`models.integrationRefreshWarning`),(0,Y.jsx)(`ul`,{children:je.map(e=>(0,Y.jsxs)(`li`,{children:[e.client,e.profileId===void 0?``:`:${e.profileId}`,`: `,Qf(E,{clientId:e.client,message:e.reason===`integration_mutation_busy`?E(`integrations.error.busy`):e.reason,reason:e.refusalReason,snapshotPath:e.snapshotPath,residual:e.residual})]},`${e.client}:${e.profileId??`all`}`))})]})}),(0,Y.jsxs)(`div`,{className:`models-workspace-root`,"aria-busy":cr.refreshing||void 0,children:[(0,Y.jsxs)(`aside`,{className:`models-workspace-rail`,"aria-label":E(`nav.models`),children:[(0,Y.jsxs)(`div`,{className:`models-workspace-rail-header`,children:[(0,Y.jsx)(`span`,{className:`models-workspace-rail-title`,children:E(`models.workspace.providers`)}),(0,Y.jsx)(`span`,{className:`models-workspace-rail-count`,children:pr.length})]}),(0,Y.jsxs)(`div`,{className:`models-workspace-rail-list`,children:[(0,Y.jsxs)(`button`,{type:`button`,className:`models-workspace-rail-row${Qn===null?` models-workspace-rail-row--selected`:``}`,onClick:()=>$n(null),"aria-current":Qn===null?`true`:void 0,children:[(0,Y.jsx)(`span`,{className:`models-workspace-rail-name`,children:E(`models.workspace.allProviders`)}),(0,Y.jsx)(`span`,{className:`models-workspace-rail-meta`,children:E(`models.active`,{active:vr,total:k.length})})]}),pr.map(e=>{let{provider:t,rows:n}=e,r=n.filter(e=>za(ti,t,e.id,e.native===!0,N.has(e.namespaced))).length;return(0,Y.jsxs)(`button`,{type:`button`,className:`models-workspace-rail-row${Qn===t?` models-workspace-rail-row--selected`:``}`,onClick:()=>$n(t),"aria-current":Qn===t?`true`:void 0,children:[(0,Y.jsx)(`span`,{className:`models-workspace-rail-name`,children:Ln(t,E)}),(0,Y.jsx)(`span`,{className:`models-workspace-rail-meta`,children:E(`models.active`,{active:r,total:n.length})})]},t)})]})]}),(0,Y.jsxs)(`section`,{className:`models-workspace-main`,"aria-label":E(`models.workspace.mainAria`),children:[oi,si,Qe&&(0,Y.jsxs)(`div`,{className:`card`,"aria-label":E(`models.aliasesTable`),children:[(0,Y.jsx)(`div`,{className:`row group-head`,children:(0,Y.jsx)(`strong`,{children:E(`models.aliases`)})}),Object.entries(Xe.models).flatMap(([e,t])=>Object.entries(t).map(([t,n])=>(0,Y.jsxs)(`div`,{className:`row models-model-row`,children:[(0,Y.jsxs)(`code`,{className:`mono text-caption`,style:{flex:1},children:[e,`/`,t]}),(0,Y.jsx)(`strong`,{className:`mono text-control`,children:n.alias}),(0,Y.jsx)(`span`,{className:`models-chip muted text-caption`,children:n.source===`builtin`?E(`models.aliasAuto`):E(`models.aliasUser`)}),n.stale&&(0,Y.jsx)(`span`,{className:`badge badge-amber`,children:E(`models.aliasStale`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":E(`models.editModelAlias`),onClick:()=>void Gt(e,t),children:(0,Y.jsx)(ge,{style:{width:13,height:13}})})]},`${e}/${t}`)))]}),(0,Y.jsx)(`div`,{className:`models-provider-list`,children:ri.map(e=>ni(e))}),pr.length===0&&ci]})]}),li]});return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{className:`page-head`,children:[(0,Y.jsx)(`h2`,{children:E(`nav.models`)}),(0,Y.jsx)(`div`,{className:`page-head-actions`,children:(0,Y.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:()=>{d()},disabled:u,"aria-label":E(u?`dash.codexRestarting`:`dash.codexRestart`),title:E(u?`dash.codexRestarting`:`dash.codexRestart`),children:(0,Y.jsx)(de,{})})})]}),(0,Y.jsx)(cd,{state:n,controller:{restarting:u,restart:d}}),(0,Y.jsx)(xg,{tab:f,onSelect:v,meta:yr}),(0,Y.jsx)(`p`,{className:`page-sub`,children:E(Tg[f])}),(0,Y.jsx)(`div`,{className:`models-tab-panel`,role:`tabpanel`,id:yg(`catalog`),"aria-labelledby":vg(`catalog`),hidden:f!==`catalog`,children:(0,Y.jsx)(np,{pageName:E(`models.tab.catalog`),title:E(`errorBoundary.title`),message:E(`errorBoundary.message`),detailsLabel:E(`errorBoundary.details`),reloadLabel:E(`errorBoundary.reload`),children:ei?(0,Y.jsx)(ep,{label:E(`models.loading`),rows:5}):$r===null?ui:(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)($,{tone:`err`,children:$r}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>sr.refresh(),children:E(`common.retry`)})]})})}),(0,Y.jsx)(`div`,{className:`models-tab-panel models-tab-panel--fill`,role:`tabpanel`,id:yg(`combos`),"aria-labelledby":vg(`combos`),hidden:f!==`combos`,children:m.has(`combos`)&&(0,Y.jsx)(np,{pageName:E(`models.tab.combos`),title:E(`errorBoundary.title`),message:E(`errorBoundary.message`),detailsLabel:E(`errorBoundary.details`),reloadLabel:E(`errorBoundary.reload`),children:(0,Y.jsx)(gm,{apiBase:e,active:f===`combos`,onCountChange:x})})}),(0,Y.jsx)(`div`,{className:`models-tab-panel`,role:`tabpanel`,id:yg(`routing`),"aria-labelledby":vg(`routing`),hidden:f!==`routing`,children:m.has(`routing`)&&(0,Y.jsx)(np,{pageName:E(`models.tab.routing`),title:E(`errorBoundary.title`),message:E(`errorBoundary.message`),detailsLabel:E(`errorBoundary.details`),reloadLabel:E(`errorBoundary.reload`),children:(0,Y.jsx)(th,{apiBase:e,active:f===`routing`,onCountChange:C})})}),(0,Y.jsx)(`div`,{className:`models-tab-panel`,role:`tabpanel`,id:yg(`compatibility`),"aria-labelledby":vg(`compatibility`),hidden:f!==`compatibility`,children:m.has(`compatibility`)&&(0,Y.jsx)(np,{pageName:E(`models.tab.compatibility`),title:E(`errorBoundary.title`),message:E(`errorBoundary.message`),detailsLabel:E(`errorBoundary.details`),reloadLabel:E(`errorBoundary.reload`),children:(0,Y.jsx)(pg,{apiBase:e,active:f===`compatibility`,onCountChange:T})})}),yt&&(0,Y.jsx)(Ad,{model:yt,saving:wt,requestError:Et,currentNamePending:Pt,mutationOutcomeUnknown:Mt?.confirmed===!1,onRetry:Mt?()=>void fr(Mt.value):void 0,onEdit:()=>Nt(null),onSave:e=>void fr(e),onReset:()=>void fr(null),onClose:dr}),xt&&(0,Y.jsx)(Rd,{model:xt,apiBase:e,onRefresh:e=>lr(!0,e),onClose:()=>{let e=Ct.current;St(null),window.setTimeout(()=>{e?.isConnected&&e.focus()},0)}},`${e}/${xt.namespaced}`)]})}var Og=`section`;function kg(e,t){return[e,Og,t].join(`-`)}function Ag(e){return[e,Og,``].join(`-`)}var jg=1200;function Mg({scope:e,items:t,ariaLabel:n,mobileReadingLine:r}){let[i,a]=(0,_.useState)(()=>r&&window.matchMedia(`(max-width: 760px)`).matches?r:72);(0,_.useEffect)(()=>{if(!r)return;let e=window.matchMedia(`(max-width: 760px)`),t=()=>a(e.matches?r:72);return t(),e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[r]);let[o,s]=(0,_.useState)(t[0]?.id??``),c=(0,_.useRef)(null),l=(0,_.useRef)(null),u=(0,_.useCallback)(()=>{c.current=null,l.current!==null&&(clearTimeout(l.current),l.current=null)},[]),d=(0,_.useCallback)(()=>{u();let n=null,r=1/0;for(let a of t){let t=document.getElementById(kg(e,a.id));if(!t)continue;let o=Math.abs(t.getBoundingClientRect().top-i);o<r&&(r=o,n=a.id)}n&&s(n)},[u,t,e,i]);(0,_.useEffect)(()=>()=>u(),[u]),(0,_.useEffect)(()=>{if(typeof IntersectionObserver>`u`)return;let n=t.map(t=>document.getElementById(kg(e,t.id))).filter(e=>e!==null);if(n.length===0)return;let r=new IntersectionObserver(t=>{let n=c.current;if(n){let r=document.getElementById(kg(e,n));t.some(e=>e.isIntersecting&&e.target===r)&&(u(),s(n));return}let r=t.filter(e=>e.isIntersecting).sort((e,t)=>e.boundingClientRect.top-t.boundingClientRect.top)[0];if(!r)return;let i=r.target.id.slice(Ag(e).length);s(e=>e===i?e:i)},{rootMargin:[String(-i)+`px`,`0px`,`-60%`,`0px`].join(` `),threshold:0});for(let e of n)r.observe(e);return()=>r.disconnect()},[u,t,e,i]);let f=t=>{let n=document.getElementById(kg(e,t));n&&(c.current=t,l.current!==null&&clearTimeout(l.current),l.current=setTimeout(d,jg),s(t),n.scrollIntoView({behavior:`smooth`,block:`start`}))};return(0,Y.jsx)(`div`,{className:`page-tabs section-tabs`,role:`tablist`,"aria-label":n,children:t.map(t=>(0,Y.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":o===t.id,"aria-controls":kg(e,t.id),tabIndex:o===t.id?0:-1,className:`page-tab${o===t.id?` page-tab--active`:``}`,onClick:()=>f(t.id),children:[t.label,t.meta?(0,Y.jsx)(`span`,{className:`section-tab-meta`,children:t.meta}):null]},t.id))})}function Ng({model:e,effort:t,efforts:n,available:r,guidanceEnabled:i,syncCodexDefaults:a,saving:o,onSave:s,ultraMode:c,ultraSaving:l,onUltraModeSave:u,ultraLoadFailed:d,onUltraModeRetry:f,fallback:p,fallbackPollMs:m,fallbackBusy:h,availableModels:g,onFallbackChange:v,onFallbackPollMsChange:y,onFallbackSave:b}){let x=Q(),S=(c.hintText??``).trim().length>0,C=r.some(t=>t.namespaced===e&&(t.provider!==`openai`||t.namespaced!==t.model)),w=c.enabled||c.multiAgentMode!==`v1`&&!(c.multiAgentMode===`v2`&&c.keepNativeChatGptOnV1),T=!d&&c.loaded===!0&&C&&w,E=new Set(g),D=new Set(p),[O,k]=(0,_.useState)(()=>({pollMs:m,text:String(m)}));Object.is(O.pollMs,m)||k({pollMs:m,text:Number.isFinite(m)?String(m):``});let A=(0,_.useRef)(null),[j,M]=(0,_.useState)(()=>({models:p,rows:p.map((e,t)=>({model:e,id:t})),nextId:p.length})),N=j.rows;if(j.models!==p){let e=[...j.rows],t=j.nextId;N=p.map(n=>{let r=e.findIndex(e=>e.model===n);return r>=0?e.splice(r,1)[0]:{model:n,id:t++}}),M({models:p,rows:N,nextId:t})}let P=(0,_.useRef)(null);(0,_.useLayoutEffect)(()=>{let e=P.current;if(!e)return;P.current=null;let t=A.current?.querySelectorAll(`.swi-fallback-row`)[e.row],n=t?.querySelectorAll(`button[data-action]:not(:disabled)`);(Array.from(n??[]).find(t=>t.dataset.action===e.action)??t?.querySelector(`button:not(:disabled)`)??A.current?.querySelector(`button[role="combobox"]`))?.focus()},[p]);let F=Number.isInteger(m)&&m>=5e3&&m<=6e5,I=(e,t)=>{let n=[...p],r=e+t;if(h||r<0||r>=n.length)return;[n[e],n[r]]=[n[r],n[e]];let i=[...N];[i[e],i[r]]=[i[r],i[e]],M({...j,models:n,rows:i}),P.current={row:r,action:t===-1?`up`:`down`},v(n)};return(0,Y.jsxs)(`div`,{className:`swi-delegation`,children:[d&&(0,Y.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,Y.jsxs)(`div`,{className:`setting-copy`,children:[(0,Y.jsx)(`div`,{className:`font-semibold`,children:x(`sub.ultraMode`)}),(0,Y.jsx)(`div`,{className:`muted setting-hint`,children:x(`sub.ultraModeLoadFail`)})]}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:f,children:x(`common.retry`)})]}),(0,Y.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,Y.jsxs)(`div`,{className:`setting-copy`,children:[(0,Y.jsx)(`div`,{className:`font-semibold`,children:x(`sub.delegation.model`)}),(0,Y.jsx)(`div`,{className:`muted setting-hint`,children:x(`sub.delegation.modelHint`)})]}),(0,Y.jsxs)(`div`,{className:`swi-delegation-controls`,children:[(0,Y.jsx)(kt,{value:e,options:[{value:``,label:x(`dash.injectionNone`)},...r.map(e=>({value:e.namespaced,label:Bn(`${e.provider}/${e.model}`,x)}))],onChange:e=>s({model:e||null,effort:t||null}),disabled:o,label:x(`dash.injectionLabel`),align:`right`}),e&&n.length>0&&(0,Y.jsx)(kt,{value:t,options:[{value:``,label:x(`dash.injectionEffortNone`)},...n.map(e=>({value:e,label:e}))],onChange:t=>s({model:e||null,effort:t||null}),disabled:o,label:x(`dash.injectionEffortLabel`),align:`right`})]})]}),T&&(0,Y.jsx)(`div`,{className:`swi-delegation-row swi-v2-compatibility`,role:`note`,children:(0,Y.jsxs)(`div`,{className:`setting-copy`,children:[(0,Y.jsx)(`div`,{className:`font-semibold`,children:x(`sub.v2Compatibility.title`)}),(0,Y.jsx)(`p`,{className:`muted setting-hint`,children:x(`sub.v2Compatibility.risk`)}),(0,Y.jsx)(`p`,{className:`muted setting-hint`,children:x(`sub.v2Compatibility.recoveryUnknown`)}),(0,Y.jsx)(`a`,{href:`https://github.com/lidge-jun/opencodex/issues/92`,target:`_blank`,rel:`noreferrer`,children:x(`sub.v2Compatibility.details`)})]})}),(0,Y.jsxs)(`div`,{className:`swi-delegation-row swi-fallback-editor`,children:[(0,Y.jsxs)(`div`,{className:`setting-copy`,children:[(0,Y.jsx)(`div`,{className:`font-semibold`,children:x(`sub.fallbackLabel`)}),(0,Y.jsx)(`div`,{className:`muted setting-hint`,children:x(`sub.fallbackHint`)})]}),(0,Y.jsxs)(`div`,{className:`swi-fallback-controls`,ref:A,children:[p.map((e,t)=>(0,Y.jsxs)(`div`,{className:`swi-fallback-row`,children:[(0,Y.jsxs)(`span`,{className:`swi-fallback-model`,children:[t+1,`. `,e,!E.has(e)&&(0,Y.jsx)(`span`,{className:`muted setting-hint`,children:x(`sub.fallbackUnavailable`)})]}),(0,Y.jsxs)(`span`,{className:`swi-fallback-actions`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,"data-action":`up`,onClick:()=>I(t,-1),disabled:h||t===0,"aria-label":x(`sub.moveUp`,{m:e}),children:(0,Y.jsx)(be,{})}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,"data-action":`down`,onClick:()=>I(t,1),disabled:h||t===p.length-1,"aria-label":x(`sub.moveDown`,{m:e}),children:(0,Y.jsx)(xe,{})}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,"data-action":`remove`,onClick:()=>{let e=p.filter((e,n)=>n!==t);M({...j,models:e,rows:N.filter((e,n)=>n!==t)}),P.current={row:Math.max(0,Math.min(t,p.length-2)),action:`remove`},v(e)},disabled:h,"aria-label":x(`sub.removeAria`,{m:e}),children:(0,Y.jsx)(le,{})})]})]},N[t].id)),(0,Y.jsx)(kt,{value:``,label:x(`sub.fallbackAdd`),options:[{value:``,label:x(`sub.fallbackAdd`)},...g.filter(e=>!D.has(e)).map(e=>({value:e,label:e}))],onChange:e=>{e&&!D.has(e)&&v([...p,e])},disabled:h}),(0,Y.jsxs)(`label`,{className:`setting-hint`,children:[x(`sub.fallbackPoll`),(0,Y.jsx)(`input`,{className:`input`,type:`number`,min:5e3,max:6e5,step:1e3,value:O.text,onChange:e=>{let t=e.currentTarget.value,n=Number(t),r=t.trim()!==``&&Number.isFinite(n)?n:NaN;k({pollMs:r,text:t}),y(r)},disabled:h,"aria-invalid":!F}),` ms`]}),!F&&(0,Y.jsx)(`div`,{className:`setting-hint`,role:`alert`,children:x(`sub.fallbackPollInvalid`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:b,disabled:h||!F,children:x(`common.save`)})]})]}),(0,Y.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,Y.jsxs)(`div`,{className:`setting-copy`,children:[(0,Y.jsx)(`div`,{className:`font-semibold`,children:x(`dash.syncCodexSubagentDefaults`)}),(0,Y.jsx)(`div`,{className:`muted setting-hint`,children:x(`dash.syncCodexSubagentDefaultsHint`)})]}),(0,Y.jsx)(`button`,{type:`button`,className:`switch ${a?`on`:``}`,onClick:()=>s({syncCodexSubagentDefaults:!a}),disabled:o||!e,"aria-label":x(`dash.syncCodexSubagentDefaults`),"aria-pressed":a,children:(0,Y.jsx)(`span`,{className:`knob`})})]}),(0,Y.jsxs)(`details`,{className:`swi-advanced`,children:[(0,Y.jsx)(`summary`,{className:`muted text-label`,children:x(`sub.advanced`)}),(0,Y.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,Y.jsxs)(`div`,{className:`setting-copy`,children:[(0,Y.jsxs)(`div`,{className:`font-semibold`,style:{display:`inline-flex`,alignItems:`center`,gap:6},children:[x(`models.v2Label`),(0,Y.jsxs)(jt,{content:x(`models.v2Help`),side:`top`,maxWidth:380,children:[(0,Y.jsx)(ve,{width:13,height:13,"aria-hidden":`true`}),(0,Y.jsx)(`span`,{className:`sr-only`,children:x(`models.v2Label`)})]})]}),(0,Y.jsx)(`div`,{className:`muted setting-hint`,children:(0,Y.jsx)(`a`,{className:`text-control`,href:`https://opencodex.me/guides/sub-agent-surface/`,target:`_blank`,rel:`noreferrer`,style:{color:`var(--accent)`},children:x(`models.v2DocsLink`)})})]}),(0,Y.jsx)(`div`,{className:`swi-delegation-controls`,children:(0,Y.jsx)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":x(`models.v2Label`),children:[`v1`,`default`,`v2`].map(e=>(0,Y.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":c.multiAgentMode===e,className:`btn btn-sm${c.multiAgentMode===e?` btn-primary`:` btn-ghost`}`,style:{background:c.multiAgentMode===e?void 0:`transparent`,color:c.multiAgentMode===e?void 0:`var(--muted)`},disabled:l||d,onClick:()=>{c.multiAgentMode!==e&&u({multiAgentMode:e})},children:x(`models.v2Mode_${e}`)},e))})})]}),(0,Y.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,Y.jsxs)(`div`,{className:`setting-copy`,children:[(0,Y.jsx)(`div`,{className:`font-semibold`,children:x(`dash.multiAgentGuidance`)}),(0,Y.jsx)(`div`,{className:`muted setting-hint`,children:x(`dash.multiAgentGuidanceHint`)})]}),(0,Y.jsx)(`button`,{type:`button`,className:`switch ${i?`on`:``}`,onClick:()=>s({multiAgentGuidanceEnabled:!i}),disabled:o,"aria-label":x(`dash.multiAgentGuidance`),"aria-pressed":i,children:(0,Y.jsx)(`span`,{className:`knob`})})]}),(0,Y.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,Y.jsxs)(`div`,{className:`setting-copy`,children:[(0,Y.jsx)(`div`,{className:`font-semibold`,children:x(`sub.ultraMode`)}),(0,Y.jsx)(`div`,{className:`muted setting-hint`,children:x(`sub.ultraModeHint`)})]}),(0,Y.jsx)(`button`,{type:`button`,className:`switch ${S?`on`:``}`,onClick:()=>{S?u({multiAgentModeHintText:null}):c.recommendation&&u({multiAgentModeHintText:c.recommendation.text})},disabled:o||l||!S&&(!c.multiAgentV2Enabled||!c.recommendation),"aria-label":x(`sub.ultraMode`),"aria-pressed":S,children:(0,Y.jsx)(`span`,{className:`knob`})}),!c.multiAgentV2Enabled&&(0,Y.jsx)(`div`,{className:`muted setting-hint`,children:x(`sub.ultraModeV2Required`)})]}),S&&(0,Y.jsx)(`div`,{className:`swi-delegation-row swi-ultra-mode-editor`,children:(0,Y.jsx)(Pg,{initialHint:c.hintText??``,disabled:o||l,onSave:u,preset:c.recommendation?.text??null,labels:{text:x(`sub.ultraModeText`),preset:x(`sub.ultraModePreset`),save:x(`common.save`)}},c.hintText)})]})]})}function Pg({initialHint:e,disabled:t,onSave:n,preset:r,labels:i}){let[a,o]=(0,_.useState)(e);return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`textarea`,{className:`input swi-ultra-mode-textarea`,value:a,onChange:e=>o(e.target.value),disabled:t,rows:4,"aria-label":i.text}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{r!==null&&o(r)},disabled:t||r===null,children:i.preset}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>{a.trim().length!==0&&n({multiAgentModeHintText:a})},disabled:t||a.trim().length===0,children:i.save})]})}function Fg({available:e,fallbackAvailable:t,chosen:n,busy:r=!1,onToggle:i,onMove:a,onSave:o,fallback:s,fallbackPollMs:c,fallbackBusy:l,onFallbackChange:u,onFallbackPollMsChange:d,onFallbackSave:f,delegation:p}){let m=Q(),[h,g]=(0,_.useState)(``),v=(0,_.useMemo)(()=>new Set(n),[n]),y=n.length>=5,b=(0,_.useMemo)(()=>{let t=h.trim().toLowerCase();return e.filter(e=>!t||e.toLowerCase().includes(t))},[e,h]),x=(0,_.useMemo)(()=>[{id:`featured`,label:m(`sub.featured`),meta:`${n.length}/5`},{id:`models`,label:m(`sub.models`),meta:String(b.length)},{id:`settings`,label:m(`sub.settings`)}],[m,n.length,b.length]);return(0,Y.jsxs)(`div`,{className:`subagents-workspace-shell`,children:[(0,Y.jsx)(Mg,{scope:`subagents`,items:x,ariaLabel:m(`sub.sections`)}),(0,Y.jsxs)(`div`,{className:`subagents-workspace-root`,children:[(0,Y.jsxs)(`section`,{id:kg(`subagents`,`featured`),className:`subagents-workspace-section`,"aria-label":m(`sub.featured`),children:[(0,Y.jsxs)(`div`,{className:`swi-featured-head`,children:[(0,Y.jsx)(`h2`,{className:`swi-featured-title`,children:m(`sub.featured`)}),(0,Y.jsxs)(`span`,{className:`swi-featured-count`,children:[n.length,`/`,5]}),(0,Y.jsxs)(jt,{content:(0,Y.jsx)(ft,{k:`sub.orderHint`,cmd:`spawn_agent`}),side:`bottom`,maxWidth:380,children:[(0,Y.jsx)(ve,{width:14,height:14,"aria-hidden":`true`}),(0,Y.jsx)(`span`,{className:`sr-only`,children:m(`sub.orderHintAria`)})]})]}),n.length===0?(0,Y.jsx)(`div`,{className:`swi-featured-empty`,children:m(`sub.noneSelected`)}):(0,Y.jsx)(`div`,{className:`swi-featured-list`,children:n.map((e,t)=>(0,Y.jsxs)(`div`,{className:`swi-featured-row`,children:[(0,Y.jsx)(`span`,{className:`swi-featured-pos`,children:t+1}),(0,Y.jsx)(`span`,{className:`swi-featured-name`,children:tf(e)}),(0,Y.jsxs)(`span`,{className:`swi-featured-actions`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,onClick:()=>a(t,-1),disabled:r||t===0,"aria-label":m(`sub.moveUp`,{m:e}),children:(0,Y.jsx)(be,{})}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,onClick:()=>a(t,1),disabled:r||t===n.length-1,"aria-label":m(`sub.moveDown`,{m:e}),children:(0,Y.jsx)(xe,{})}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,onClick:()=>i(e),disabled:r,"aria-label":m(`sub.removeAria`,{m:e}),style:{color:`var(--red)`},children:(0,Y.jsx)(le,{})})]})]},e))}),(0,Y.jsx)(`div`,{className:`swi-save-row`,children:(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:o,disabled:r,children:m(`common.save`)})})]}),(0,Y.jsxs)(`section`,{id:kg(`subagents`,`models`),className:`subagents-workspace-section`,"aria-label":m(`sub.models`),children:[(0,Y.jsxs)(`div`,{className:`swi-featured-head`,children:[(0,Y.jsx)(`h2`,{className:`swi-featured-title`,children:m(`sub.models`)}),(0,Y.jsx)(`span`,{className:`swi-featured-count`,children:b.length})]}),(0,Y.jsxs)(`div`,{className:`swi-picker-box`,children:[(0,Y.jsx)(`div`,{className:`subagents-workspace-rail-search`,children:(0,Y.jsx)(`input`,{className:`input`,value:h,onChange:e=>g(e.target.value),placeholder:m(`sub.search`),"aria-label":m(`sub.search`)})}),(0,Y.jsx)(`div`,{className:`subagents-workspace-rail-list`,children:b.length===0?(0,Y.jsx)(`span`,{className:`subagents-workspace-rail-empty`,children:m(`sub.noModels`)}):b.map(e=>{let t=v.has(e),a=t?n.indexOf(e)+1:null,o=!t&&(y||r);return(0,Y.jsxs)(`div`,{className:`subagents-workspace-rail-row${t?` subagents-workspace-rail-row--selected`:``}`,children:[(0,Y.jsxs)(`span`,{className:`subagents-workspace-rail-row-main`,children:[(0,Y.jsx)(`span`,{className:`swi-rail-priority`,children:a??``}),(0,Y.jsx)(Z,{className:`swi-rail-icon`,"aria-hidden":`true`}),(0,Y.jsx)(`span`,{className:`subagents-workspace-rail-name`,children:tf(e)})]}),(0,Y.jsx)(`button`,{type:`button`,className:`subagents-workspace-rail-toggle${t?` subagents-workspace-rail-toggle--on`:``}${o?` subagents-workspace-rail-toggle--disabled`:``}`,onClick:()=>{o||i(e)},disabled:o,"aria-pressed":t,"aria-label":m(t?`sub.workspace.removeFromFeatured`:`sub.workspace.addToFeatured`,{m:e}),title:t?m(`sub.workspace.removeFromFeatured`,{m:e}):y?m(`sub.workspace.featuredFull`):m(`sub.workspace.addToFeatured`,{m:e}),children:t?(0,Y.jsx)(ce,{style:{width:14,height:14}}):(0,Y.jsx)(ue,{style:{width:14,height:14}})})]},e)})})]})]}),(0,Y.jsxs)(`section`,{id:kg(`subagents`,`settings`),className:`subagents-workspace-section`,"aria-label":m(`sub.settings`),children:[(0,Y.jsx)(`div`,{className:`swi-featured-head`,children:(0,Y.jsx)(`h2`,{className:`swi-featured-title`,children:m(`sub.settings`)})}),(0,Y.jsx)(Ng,{model:p.model,effort:p.effort,efforts:p.efforts,available:p.available,guidanceEnabled:p.guidanceEnabled,syncCodexDefaults:p.syncCodexDefaults,saving:p.saving,onSave:p.onSave,ultraMode:p.ultraMode,ultraSaving:p.ultraSaving,onUltraModeSave:p.onUltraModeSave,ultraLoadFailed:p.ultraLoadFailed,onUltraModeRetry:p.onUltraModeRetry,fallback:s,fallbackPollMs:c,fallbackBusy:l,availableModels:t??e,onFallbackChange:u,onFallbackPollMsChange:d,onFallbackSave:f})]})]})]})}function Ig(e){let[t,n]=(0,_.useState)(!1),[r,i]=(0,_.useState)(!1),[a,o]=(0,_.useState)(``),[s,c]=(0,_.useState)(``),[l,u]=(0,_.useState)([]),[d,f]=(0,_.useState)([]),[p,m]=(0,_.useState)(!0),[h,g]=(0,_.useState)(!1),v=(0,_.useCallback)(e=>{let t=Br(e);m(t.multiAgentGuidanceEnabled),g(t.syncCodexSubagentDefaults),o(t.injectionModel),c(t.injectionEffort),Array.isArray(e.efforts)&&u(e.efforts),Array.isArray(e.available)&&f(e.available)},[]);return(0,_.useEffect)(()=>{let t=!1;return(async()=>{try{let n=await Kt(await fetch(`${e}/api/injection-model`));if(t)return;v(n)}catch{}finally{t||n(!0)}})(),()=>{t=!0}},[e,v]),{loaded:t,saving:r,model:a,effort:s,efforts:l,available:d,guidanceEnabled:p,syncCodexDefaults:h,save:(0,_.useCallback)(async t=>{if(!r){i(!0);try{if(!(await fetch(`${e}/api/injection-model`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)})).ok)throw Error(`injection save failed`);let n=await fetch(`${e}/api/injection-model`);v(await Kt(n))}catch{}finally{i(!1)}}},[e,v,r])}}var Lg={enabled:!1,hintText:null,recommendation:null,multiAgentV2Enabled:!1,multiAgentMode:`default`};function Rg(e){return Tr(e)}function zg({apiBase:e}){let t=Q(),n=`ocx.subagents.v1:${e}`,r=Rg(n),[i,a]=(0,_.useState)(()=>r?.chosen??[]),[o,s]=(0,_.useState)(()=>r?.fallback??[]),[c,l]=(0,_.useState)(()=>r?.pollMs??6e4),[u,d]=(0,_.useState)(!1),[f,p]=(0,_.useState)(()=>Array.isArray(r?.fallback)&&Number.isInteger(r?.pollMs)),[m,h]=(0,_.useState)(()=>r?.fallbackAvailable),[g,v]=(0,_.useState)(``),[y,b]=(0,_.useState)(!0),x=(0,_.useRef)(null),S=(0,_.useRef)({fallback:r?.fallback,pollMs:r?.pollMs,fallbackAvailable:r?.fallbackAvailable}),C=(0,_.useRef)(0),w=(0,_.useRef)(0),T=(0,_.useRef)(!1),E=(0,_.useRef)(r),[D,O]=(0,_.useState)(``),[k,A]=(0,_.useState)(!1),[j,M]=(0,_.useState)(!1),N=(0,_.useRef)(!1),P=Ig(e),[F,I]=(0,_.useState)(null),L=F?.apiBase===e,R=L?F.mode:Lg,[z,B]=(0,_.useState)(!1),[V,H]=(0,_.useState)(null),[U,W]=(0,_.useState)(!1),G=(0,_.useRef)(0),K=(0,_.useRef)(e);(0,_.useEffect)(()=>{K.current=e,G.current++},[e]);let q=(0,_.useCallback)(async n=>{if(K.current!==e)return!1;let r=++G.current,i=await It(await fetch(`${e}/api/v2`,{signal:n}),t(`sub.ultraModeLoadFail`));if(!i||n?.aborted||r!==G.current||K.current!==e)return!1;W(!1);let a=i.multiAgentModeHintRecommendation,o=a&&typeof a.text==`string`&&a.text.trim().length>0&&typeof a.revision==`string`&&a.revision.trim().length>0?{text:a.text,revision:a.revision}:null;return I({apiBase:e,mode:{enabled:i.enabled??!1,loaded:!0,keepNativeChatGptOnV1:i.keepNativeChatGptOnV1===!0,hintText:i.multiAgentModeHintText??null,recommendation:o,multiAgentV2Enabled:i.enabled===!0&&i.multiAgentMode===`v2`,multiAgentMode:i.multiAgentMode??`default`}}),!0},[e,t]);(0,_.useEffect)(()=>{let e=new AbortController;return(async()=>{await q(e.signal)})().catch(()=>{e.signal.aborted||(A(!1),W(!0),O(t(`sub.ultraModeLoadFail`)))}),()=>{e.abort()}},[q,t]);let J=async n=>{if(z||!L||K.current!==e)return;let r=e;B(!0),O(``);try{if(await It(await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)}),t(`sub.ultraModeSaveFail`)),K.current!==r||!await q())return;A(!0),O(t(`sub.ultraModeSaved`))}catch(e){if(K.current!==r)return;A(!1),O(e instanceof Error&&e.message?e.message:t(`sub.networkError`))}finally{B(!1)}},X=(0,_.useCallback)(async()=>{try{if(!await q())return;A(!1),O(e=>e===t(`sub.ultraModeLoadFail`)?``:e)}catch{A(!1),W(!0),O(t(`sub.ultraModeLoadFail`))}},[q,t]),ee=(0,_.useCallback)(async()=>{x.current?.abort();let r=new AbortController;x.current=r;let{signal:i}=r,a=C.current;try{let r=await It(await fetch(`${e}/api/subagent-model-fallback`,{signal:i}));if(!r||!Array.isArray(r.models)||!r.models.every(e=>typeof e==`string`&&e.trim())||typeof r.pollMs!=`number`||!Number.isInteger(r.pollMs)||r.pollMs<5e3||r.pollMs>6e5||!Array.isArray(r.available)||!r.available.every(e=>typeof e==`string`&&e.trim()))throw Error(t(`sub.loadFail`));if(i.aborted||a!==C.current||T.current)return;let o={fallback:r.models,pollMs:r.pollMs,fallbackAvailable:r.available};S.current=o,s(o.fallback),l(o.pollMs),h(o.fallbackAvailable),p(!0),v(``),E.current&&(E.current={...E.current,...o},kr(n,E.current))}catch(e){if(i.aborted||a!==C.current||T.current)return;p(!1),v(e instanceof Error&&!(e instanceof SyntaxError)?e.message:t(`sub.loadFail`))}finally{i.aborted||b(!1)}},[e,n,t]);(0,_.useEffect)(()=>((async()=>{await ee()})(),()=>{x.current?.abort()}),[ee]);let te=(0,_.useCallback)(async r=>{let i=w.current,o=await It(await fetch(`${e}/api/subagent-models`,{signal:r}),t(`sub.loadFail`));if(!o)throw Error(t(`sub.loadFail`));let s=o.available??[],c=new Set(s),l=i===w.current&&!N.current,u={...S.current,available:s,chosen:l?(o.chosen??[]).filter(e=>c.has(e)):E.current?.chosen??[]};if(r?.aborted)throw r.reason;return E.current=u,l&&a(u.chosen),kr(n,u),u},[e,n,t]),ne=jr(n,[e],te,{isEmpty:()=>!1,initialData:r??void 0}),{state:Z}=ne,re=ne.refresh,ie=Z.data??r,ae=ie?.available??[],oe=e=>{j||(O(``),w.current+=1,a(t=>t.includes(e)?t.filter(t=>t!==e):t.length>=5?t:[...t,e]))},se=(e,t)=>{j||(w.current+=1,a(n=>{let r=[...n],i=e+t;return i<0||i>=r.length?n:([r[e],r[i]]=[r[i],r[e]],r)}))},ce=async()=>{if(!(j||N.current)){N.current=!0,w.current+=1,M(!0),O(``);try{let r=await It(await fetch(`${e}/api/subagent-models`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({models:i})}),t(`sub.saveFailed`));w.current+=1;let o=r?.applied??i;r?.applied&&a(r.applied);let s={...E.current,available:ae,chosen:o};E.current=s,kr(n,s),A(!0),O(t(`sub.saved`,{n:o.length,cmd:`ocx sync`}))}catch(e){A(!1),O(e instanceof Error&&e.message?e.message:t(`sub.networkError`))}finally{N.current=!1,M(!1)}}},le=async()=>{if(!f||T.current||!Number.isInteger(c)||c<5e3||c>6e5)return;T.current=!0,C.current+=1;let r=e;d(!0),O(``);try{let i=await It(await fetch(`${e}/api/subagent-model-fallback`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({models:o,pollMs:c})}),t(`sub.fallbackSaveFailed`));if(K.current!==r)return;if(!i||!Array.isArray(i.models)||typeof i.pollMs!=`number`)throw Error(t(`sub.fallbackSaveFailed`));C.current+=1,s(i.models),l(i.pollMs),S.current={...S.current,fallback:i.models,pollMs:i.pollMs};let a={available:ae,chosen:E.current?.chosen??[],...S.current};E.current=a,kr(n,a),A(!0),O(t(`sub.fallbackSaved`))}catch(e){A(!1),O(e instanceof Error&&e.message?e.message:t(`sub.networkError`))}finally{T.current=!1,d(!1)}};if(Z.showSkeleton&&!ie)return(0,Y.jsx)(ep,{label:t(`sub.loading`),rows:4});if(Z.kind===`failed-cold`){let e=Z.error instanceof Error?Z.error.message:t(`sub.loadFail`);return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)($,{tone:`err`,children:e}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>re(),children:t(`common.retry`)})]})}return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`div`,{className:`page-head`,children:(0,Y.jsx)(`h2`,{children:t(`nav.subagents`)})}),D&&(0,Y.jsx)($,{tone:k?`ok`:`err`,children:D}),Z.showError&&(0,Y.jsx)($,{tone:`err`,children:t(`sub.loadFail`)}),g&&(0,Y.jsxs)($,{tone:`err`,children:[t(`sub.fallbackLabel`),`: `,t(`sub.loadFail`),g!==t(`sub.loadFail`)&&(0,Y.jsxs)(Y.Fragment,{children:[` `,g]}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:y,onClick:()=>{b(!0),ee()},children:t(`common.retry`)})]}),(0,Y.jsx)(Fg,{available:ae,fallbackAvailable:m??[],chosen:i,busy:j,onToggle:oe,onMove:se,onSave:()=>{ce()},fallback:o,fallbackPollMs:c,fallbackBusy:u||!f,onFallbackChange:e=>{C.current+=1,s(e)},onFallbackPollMsChange:e=>{C.current+=1,l(e)},onFallbackSave:()=>{le()},delegation:{model:P.model,effort:P.effort,efforts:P.efforts,available:P.available,guidanceEnabled:P.guidanceEnabled,syncCodexDefaults:P.syncCodexDefaults,saving:P.saving,onSave:e=>{P.save(e)},ultraMode:R,ultraSaving:z||!L,onUltraModeSave:t=>{if(t.multiAgentMode==="default"||t.multiAgentMode===`v2`){H({mode:t.multiAgentMode,apiBase:e});return}J(t)},ultraLoadFailed:U,onUltraModeRetry:()=>{X()}}}),V&&V.apiBase===e&&(0,Y.jsx)(Tn,{reason:`selection`,mode:V.mode,docsUrl:`https://opencodex.me/guides/subagent-v1-default/`,busy:z,onContinue:()=>{let e=V.mode;H(null),J({multiAgentMode:e,multiAgentSurfaceAdvisoryAcknowledged:!0})},onChooseV1:()=>{H(null),R.multiAgentMode!==`v1`&&J({multiAgentMode:`v1`,multiAgentSurfaceAdvisoryAcknowledged:!0})},onDismiss:()=>H(null)})]})}function Bg(e,t,n){let r=Array(e);return new Proxy(r,{get(r,i,a){if(typeof i==`string`){let a=i.charCodeAt(0);if(a>=48&&a<=57){let a=+i;if(Number.isInteger(a)&&a>=0&&a<e){let e=r[a];if(!e){let i=t[a*2];e=r[a]={index:a,key:n(a),start:i,size:t[a*2+1],end:i+t[a*2+1],lane:0}}return e}}if(i===`length`)return e}return Reflect.get(r,i,a)}})}function Vg(e,t,n){let r=n.initialDeps??[],i,a=!0;function o(){let o=e();return o.length!==r.length||o.some((e,t)=>r[t]!==e)?(r=o,i=t(...o),n?.onChange&&!(a&&n.skipInitialOnChange)&&n.onChange(i),a=!1,i):i}return o.updateDeps=e=>{r=e},o}function Hg(e,t){if(e===void 0)throw Error(`Unexpected undefined${t?`: ${t}`:``}`);return e}var Ug=(e,t)=>Math.abs(e-t)<1.01,Wg=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}},Gg,Kg=()=>{if(Gg!==void 0)return Gg;if(typeof navigator>`u`)return Gg=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return Gg=!0;let e=navigator.maxTouchPoints;return Gg=navigator.platform===`MacIntel`&&e!==void 0&&e>0},qg=e=>{let{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},Jg=e=>e,Yg=e=>{let t=Math.max(e.startIndex-e.overscan,0),n=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,r=Array(n);for(let e=0;e<n;e++)r[e]=t+e;return r},Xg=(e,t)=>{let n=e.scrollElement;if(!n)return;let r=e.targetWindow;if(!r)return;let i=e=>{let{width:n,height:r}=e;t({width:Math.round(n),height:Math.round(r)})};if(i(qg(n)),!r.ResizeObserver)return()=>{};let a=new r.ResizeObserver(t=>{let r=()=>{let e=t[0];if(e?.borderBoxSize){let t=e.borderBoxSize[0];if(t){i({width:t.inlineSize,height:t.blockSize});return}}i(qg(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(r):r()});return a.observe(n,{box:`border-box`}),()=>{a.unobserve(n)}},Zg={passive:!0},Qg=typeof window>`u`||`onscrollend`in window,$g=(e,t,n)=>{let r=e.scrollElement;if(!r)return;let i=e.targetWindow;if(!i)return;let a=e.options.useScrollendEvent&&Qg,o=0,s=a?null:Wg(i,()=>t(o,!1),e.options.isScrollingResetDelay),c=e=>()=>{o=n(r),s?.(),t(o,e)},l=c(!0),u=c(!1);return r.addEventListener(`scroll`,l,Zg),a&&r.addEventListener(`scrollend`,u,Zg),()=>{r.removeEventListener(`scroll`,l),a&&r.removeEventListener(`scrollend`,u)}},e_=(e,t)=>$g(e,t,t=>{let{horizontal:n,isRtl:r}=e.options;return n?t.scrollLeft*(r&&-1||1):t.scrollTop}),t_=(e,t,n)=>{if(n.options.useCachedMeasurements){let t=n.indexFromElement(e),r=n.options.getItemKey(t);return n.itemSizeCache.get(r)??n.options.estimateSize(t)}if(t?.borderBoxSize){let e=t.borderBoxSize[0];if(e)return Math.round(e[n.options.horizontal?`inlineSize`:`blockSize`])}if(!t){let t=n.indexFromElement(e),r=n.options.getItemKey(t),i=n.itemSizeCache.get(r);if(i!==void 0)return i}return e[n.options.horizontal?`offsetWidth`:`offsetHeight`]},n_=(e,{adjustments:t=0,behavior:n},r)=>{var i,a;(a=(i=r.scrollElement)?.scrollTo)==null||a.call(i,{[r.options.horizontal?`left`:`top`]:e+t,behavior:n})},r_=class{constructor(e){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var e;return((e=this.targetWindow?.performance)?.now)?.call(e)??Date.now()},this.observer=(()=>{let e=null,t=()=>e||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:e=new this.targetWindow.ResizeObserver(e=>{e.forEach(e=>{let t=()=>{let t=e.target,n=this.indexFromElement(t);if(!t.isConnected){this.observer.unobserve(t);for(let[e,n]of this.elementsCache)if(n===t){this.elementsCache.delete(e);break}return}this.shouldMeasureDuringScroll(n)&&this.resizeItem(n,this.options.measureElement(t,e,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(t):t()})}));return{disconnect:()=>{var n;(n=t())==null||n.disconnect(),e=null},observe:e=>t()?.observe(e,{box:`border-box`}),unobserve:e=>t()?.unobserve(e)}})(),this.range=null,this.setOptions=e=>{let t={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:Jg,rangeExtractor:Yg,onChange:()=>{},measureElement:t_,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:`data-index`,initialMeasurementsCache:[],lanes:1,anchorTo:`start`,followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:`estimate`,useCachedMeasurements:!1};for(let n in e){let r=e[n];r!==void 0&&(t[n]=r)}let n=this.options,r=null,i=null,a=!1;if(n!==void 0&&n.enabled&&t.enabled&&t.anchorTo===`end`&&this.scrollElement!==null){let e=n.count,o=t.count,s=this.getMeasurements(),c=e>0?s[0]?.key??n.getItemKey(0):null,l=e>0?s[e-1]?.key??n.getItemKey(e-1):null;if(o!==e||e>0&&o>0&&(t.getItemKey(0)!==c||t.getItemKey(o-1)!==l)){a=!0;let c=e>0?this.getVirtualItemForOffset(this.getScrollOffset())??s[0]:null;c&&(r=[c.key,this.getScrollOffset()-c.start]);let u=t.followOnAppend===!0?`auto`:t.followOnAppend||null;u&&o>e&&this.isAtEnd(n.scrollEndThreshold)&&(e===0||t.getItemKey(o-1)!==l)&&(i=u)}}this.options=t,a&&(this.pendingMin=0,this.itemSizeCacheVersion++);let o=!1,s=0;if(r&&this.scrollOffset!==null){let[e,t]=r,n=this.getMeasurements(),{count:i,getItemKey:a}=this.options,c=0;for(;c<i&&a(c)!==e;)c++;if(c<i){let e=n[c];if(e){let n=Math.max(0,e.start+t);n!==this.scrollOffset&&(s=n-this.scrollOffset,this.scrollOffset=n,o=!0)}}}(o||i)&&(this.pendingScrollAnchor=[o?r[0]:null,o?r[1]:0,i,s])},this.notify=e=>{var t,n;(n=(t=this.options).onChange)==null||n.call(t,this,e)},this.maybeNotify=Vg(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),e=>{this.notify(e)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(e=>e()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{let e=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==e){if(this.cleanup(),!e){this.maybeNotify();return}if(this.scrollElement=e,this.targetWindow=this.scrollElement&&`ownerDocument`in this.scrollElement?this.scrollElement.ownerDocument.defaultView:this.scrollElement?.window??null,this.elementsCache.forEach(e=>{this.observer.observe(e)}),this.unsubs.push(this.options.observeElementRect(this,e=>{this.scrollRect=e,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(e,t)=>{if(t&&this._intendedScrollOffset===null&&e===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(e-this._intendedScrollOffset)<1.5&&(e=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;let n=this.getScrollOffset();this.scrollDirection=t?n===e?this.scrollDirection:n<e?`forward`:`backward`:null,this.scrollOffset=e,this.isScrolling=t,this._flushIosDeferredIfReady(),this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),`addEventListener`in this.scrollElement){let e=this.scrollElement,t=()=>{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},n=()=>{this._iosTouching=!1,!(!Kg()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};e.addEventListener(`touchstart`,t,Zg),e.addEventListener(`touchend`,n,Zg),this.unsubs.push(()=>{e.removeEventListener(`touchstart`,t),e.removeEventListener(`touchend`,n),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}let t=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,t&&this.scrollElement&&this.options.enabled){let[e,n,r,i]=t;e!==null&&!r&&(Kg()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?i!==0&&(this._iosDeferredAdjustment+=i):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),r&&this.scrollToEnd({behavior:r})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;let e=this.getScrollOffset(),t=this.getMaxScrollOffset();if(e<0||e>t)return;if(this._iosDeferredAdjustment<0&&e>=t-1){this._iosDeferredAdjustment=0;return}let n=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(e,{adjustments:this.scrollAdjustments+=n,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?`width`:`height`]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset==`function`?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=Vg(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(e,t,n,r,i,a,o,s)=>(this.prevLanes!==void 0&&this.prevLanes!==a&&(this.lanesChangedFlag=!0),this.prevLanes=a,this.pendingMin=null,{count:e,paddingStart:t,scrollMargin:n,getItemKey:r,enabled:i,lanes:a,laneAssignmentMode:o,gap:s}),{key:!1}),this.getMeasurements=Vg(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:e,paddingStart:t,scrollMargin:n,getItemKey:r,enabled:i,lanes:a,laneAssignmentMode:o,gap:s},c)=>{let l=this.itemSizeCache;if(!i)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>e)for(let t of this.laneAssignments.keys())t>=e&&this.laneAssignments.delete(t);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(e=>{this.itemSizeCache.set(e.key,e.size)}));let u=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===e&&(this.lanesSettling=!1),a===1){let i=e*2,a=this._flatMeasurements;if(!a||a.length<i){let e=new Float64Array(i);a&&u>0&&e.set(a.subarray(0,u*2)),a=e,this._flatMeasurements=a}let o;if(u===0)o=t+n;else{let e=u-1;o=a[e*2]+a[e*2+1]+s}for(let t=u;t<e;t++){let e=r(t),n=l.get(e),i=typeof n==`number`?n:this.options.estimateSize(t);a[t*2]=o,a[t*2+1]=i,o+=i+s}let c=Bg(e,a,r);return this.measurementsCache=c,c}let d=this.measurementsCache.slice(0,u),f=Array(a).fill(void 0),p=new Float64Array(a),m=0;for(let e=0;e<u;e++){let t=d[e];t&&(f[t.lane]===void 0&&m++,f[t.lane]=e,p[t.lane]=t.end)}for(let i=u;i<e;i++){let e=r(i),c=this.laneAssignments.get(i),u,h,g=o===`estimate`||l.has(e);if(c!==void 0&&this.options.lanes>1){u=c;let e=f[u],r=e===void 0?void 0:d[e];h=r?r.end+s:t+n}else if(m===a){let e=0,t=p[0],n=f[0];for(let r=1;r<a;r++){let i=p[r];(i<t||i===t&&f[r]<n)&&(e=r,t=i,n=f[r])}u=e,h=t+s,g&&this.laneAssignments.set(i,u)}else u=i%this.options.lanes,h=t+n,g&&this.laneAssignments.set(i,u);let _=l.get(e),v=typeof _==`number`?_:this.options.estimateSize(i),y=h+v;d[i]={index:i,start:h,size:v,end:y,key:e,lane:u},f[u]===void 0&&m++,f[u]=i,p[u]=y}return this.measurementsCache=d,d},{key:!1,debug:()=>this.options.debug}),this.calculateRange=Vg(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(e,t,n,r)=>e.length===0||t===0?(this.range=null,null):(this.range=o_(e,t,n,r,r===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=Vg(()=>{let e=null,t=null,n=this.calculateRange();return n&&(e=n.startIndex,t=n.endIndex),this.maybeNotify.updateDeps([this.isScrolling,e,t]),[this.options.rangeExtractor,this.options.overscan,this.options.count,e,t]},(e,t,n,r,i)=>r===null||i===null?[]:e({startIndex:r,endIndex:i,overscan:t,count:n}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=e=>{let t=this.options.indexAttribute,n=e.getAttribute(t);return n?parseInt(n,10):(console.warn(`Missing attribute name '${t}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=e=>{if(!this.scrollState||this.scrollState.behavior!==`smooth`)return!0;let t=this.scrollState.index??this.getVirtualItemForOffset(this.scrollState.lastTargetOffset)?.index;if(t!==void 0&&this.range){let n=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),r=Math.max(0,t-n),i=Math.min(this.options.count-1,t+n);return e>=r&&e<=i}return!0},this.measureElement=e=>{if(!e){this.elementsCache.forEach((e,t)=>{e.isConnected||(this.observer.unobserve(e),this.elementsCache.delete(t))});return}let t=this.indexFromElement(e),n=this.options.getItemKey(t),r=this.elementsCache.get(n);r!==e&&(r&&this.observer.unobserve(r),this.observer.observe(e),this.elementsCache.set(n,e)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(t)&&this.resizeItem(t,this.options.measureElement(e,void 0,this))},this.resizeItem=(e,t)=>{if(e<0||e>=this.options.count)return;let n,r,i,a=this._flatMeasurements;if(this.options.lanes===1&&a!==null)i=this.options.getItemKey(e),r=a[e*2],n=a[e*2+1];else{let t=this.measurementsCache[e];if(!t)return;i=t.key,r=t.start,n=t.size}let o=this.itemSizeCache.get(i)??n,s=t-o;if(s!==0){let a=this.options.anchorTo===`end`&&this.scrollState?.behavior!==`smooth`&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,c=a?this.getTotalSize():0,l=this.getScrollOffset()+this.scrollAdjustments,u=this.itemSizeCache.has(i)?r+o<=l&&this.scrollDirection!==`backward`:r<l,d=this.scrollState?.behavior!==`smooth`&&(this.shouldAdjustScrollPositionOnItemSizeChange===void 0?u:this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[e]??{index:e,key:i,start:r,size:n,end:r+n,lane:0},s,this));(this.pendingMin===null||e<this.pendingMin)&&(this.pendingMin=e),this.itemSizeCache.set(i,t),this.itemSizeCacheVersion++;let f=!1;a?f=this.applyScrollAdjustment(this.getTotalSize()-c):d&&(f=this.applyScrollAdjustment(s)),this.notify(f)}},this.getVirtualItems=Vg(()=>[this.getVirtualIndexes(),this.getMeasurements()],(e,t)=>{let n=[];for(let r=0,i=e.length;r<i;r++){let i=t[e[r]];n.push(i)}return n},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=e=>{let t=this.getMeasurements();if(t.length===0)return;let n=this._flatMeasurements,r=this.options.lanes===1&&n!=null;return Hg(t[i_(0,t.length-1,r?e=>n[e*2]:e=>Hg(t[e]).start,e)])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if(`scrollHeight`in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{let e=this.scrollElement.document.documentElement;return this.options.horizontal?e.scrollWidth-this.scrollElement.innerWidth:e.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(e=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=e,this.getOffsetForAlignment=(e,t,n=0)=>{if(!this.scrollElement)return 0;let r=this.getSize(),i=this.getScrollOffset();t===`auto`&&(t=e>=i+r?`end`:`start`),t===`center`?e+=(n-r)/2:t===`end`&&(e-=r);let a=this.getMaxScrollOffset();return Math.max(Math.min(a,e),0)},this.getOffsetForIndex=(e,t=`auto`)=>{e=Math.max(0,Math.min(e,this.options.count-1));let n=this.getSize(),r=this.getScrollOffset(),i=this.measurementsCache[e];if(!i)return;if(t===`auto`){if(i.end>=r+n-this.options.scrollPaddingEnd)t=`end`;else if(i.start<=r+this.options.scrollPaddingStart)t=`start`;else return[r,t]}if(t===`end`&&e===this.options.count-1)return[this.getMaxScrollOffset(),t];let a=t===`end`?i.end+this.options.scrollPaddingEnd:i.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(a,t,i.size),t]},this.scrollToOffset=(e,{align:t=`start`,behavior:n=`auto`}={})=>{this._iosDeferredAdjustment=0;let r=this.getOffsetForAlignment(e,t),i=this.now();this.scrollState={index:null,align:t,behavior:n,startedAt:i,lastTargetOffset:r,stableFrames:0},this._scrollToOffset(r,{adjustments:void 0,behavior:n}),this.scheduleScrollReconcile()},this.scrollToIndex=(e,{align:t=`auto`,behavior:n=`auto`}={})=>{this._iosDeferredAdjustment=0,e=Math.max(0,Math.min(e,this.options.count-1));let r=this.getOffsetForIndex(e,t);if(!r)return;let[i,a]=r,o=this.now();this.scrollState={index:e,align:a,behavior:n,startedAt:o,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:n}),this.scheduleScrollReconcile()},this.scrollBy=(e,{behavior:t=`auto`}={})=>{let n=this.getScrollOffset()+e,r=this.now();this.scrollState={index:null,align:`start`,behavior:t,startedAt:r,lastTargetOffset:n,stableFrames:0},this._scrollToOffset(n,{adjustments:void 0,behavior:t}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:e=`auto`}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:`end`,behavior:e});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:e})},this.getTotalSize=()=>{let e=this.getMeasurements(),t;if(e.length===0)t=this.options.paddingStart;else if(this.options.lanes===1){let n=e.length-1,r=this._flatMeasurements;t=r==null?e[n]?.end??0:r[n*2]+r[n*2+1]}else{let n=Array(this.options.lanes).fill(null),r=e.length-1;for(;r>=0&&n.some(e=>e===null);){let t=e[r];n[t.lane]===null&&(n[t.lane]=t.end),r--}t=Math.max(...n.filter(e=>e!==null))}return Math.max(t-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{let e=[];if(this.itemSizeCache.size===0)return e;let t=this.getMeasurements();for(let n of t)n&&this.itemSizeCache.has(n.key)&&e.push({index:n.index,key:n.key,start:n.start,size:n.size,end:n.end,lane:n.lane});return e},this._scrollToOffset=(e,{adjustments:t,behavior:n})=>{this._intendedScrollOffset=e+(t??0),this.options.scrollToFn(e,{behavior:n,adjustments:t},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(e)}applyScrollAdjustment(e,t){return e===0?!1:Kg()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?(this._iosDeferredAdjustment+=e,!1):(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=e,behavior:t}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollOffset<0&&(this.scrollOffset=0),this.scrollAdjustments=0),!0)}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId??=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()})}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}let e=this.scrollState.index==null?void 0:this.getOffsetForIndex(this.scrollState.index,this.scrollState.align),t=e?e[0]:this.scrollState.lastTargetOffset,n=t!==this.scrollState.lastTargetOffset;if(!n&&Ug(t,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=1){this.getScrollOffset()!==t&&this._scrollToOffset(t,{adjustments:void 0,behavior:`auto`}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,n){let e=this.getSize()||600,n=Math.abs(t-this.getScrollOffset()),r=this.scrollState.behavior===`smooth`&&n>e;this.scrollState.lastTargetOffset=t,r||(this.scrollState.behavior=`auto`),this._scrollToOffset(t,{adjustments:void 0,behavior:r?`smooth`:`auto`})}this.scheduleScrollReconcile()}},i_=(e,t,n,r)=>{for(;e<=t;){let i=(e+t)/2|0,a=n(i);if(a<r)e=i+1;else if(a>r)t=i-1;else return i}return e>0?e-1:0};function a_(e,t,n){let r=0;for(;r<=t;){let i=(r+t)/2|0,a=e[i*2];if(a<n)r=i+1;else if(a>n)t=i-1;else return i}return r>0?r-1:0}function o_(e,t,n,r,i){let a=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:a};if(r===1&&i!==null){let e=a_(i,a,n),r=e,o=n+t;for(;r<a&&i[r*2]+i[r*2+1]<o;)r++;return{startIndex:e,endIndex:r}}let o=i_(0,a,t=>e[t].start,n),s=o;if(r===1)for(;s<a&&e[s].end<n+t;)s++;else if(r>1){let i=Array(r).fill(0);for(;s<a&&i.some(e=>e<n+t);){let t=e[s];i[t.lane]=t.end,s++}let c=Array(r).fill(n+t);for(;o>=0&&c.some(e=>e>=n);){let t=e[o];c[t.lane]=t.start,o--}o=Math.max(0,o-o%r),s=Math.min(a,s+(r-1-s%r))}return{startIndex:o,endIndex:s}}var s_=typeof document<`u`?_.useLayoutEffect:_.useEffect;function c_({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n=`transform`,...r}){let i=_.useReducer(e=>e+1,0)[1],a=_.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});a.current.enabled=t,a.current.mode=n;let o=e=>{let t=a.current;if(!t.enabled||!t.container)return;let n=e.getTotalSize();if(n!==t.lastSize){t.lastSize=n;let r=e.options.horizontal?`width`:`height`;t.container.style[r]=`${n}px`}},s=e=>{let t=a.current;if(!t.enabled||!t.container)return;o(e);let n=!!e.options.horizontal,r=t.mode===`transform`,i=n?`left`:`top`,s=e.options.scrollMargin,c=e.getVirtualItems();for(let a of c){let o=a.start-s,c=e.elementsCache.get(a.key);c&&t.lastPositions.get(c)!==o&&(t.lastPositions.set(c,o),r?c.style.transform=n?`translate3d(${o}px, 0, 0)`:`translate3d(0, ${o}px, 0)`:c.style[i]=`${o}px`)}},c={...r,onChange:(t,n)=>{var o;let c=a.current,l=!0;if(c.enabled){s(t);let e=t.range,n=c.prevRange;l=!n||n.isScrolling!==t.isScrolling||n.startIndex!==e?.startIndex||n.endIndex!==e?.endIndex,l&&(c.prevRange=e?{startIndex:e.startIndex,endIndex:e.endIndex,isScrolling:t.isScrolling}:null)}l&&(e&&n?(0,gt.flushSync)(i):i()),(o=r.onChange)==null||o.call(r,t,n)}},[l]=_.useState(()=>{let e=new r_(c);return Object.assign(e,{containerRef:t=>{let n=a.current;if(n.container=t,n.lastSize=null,t&&n.enabled){let r=e.getTotalSize();n.lastSize=r;let i=e.options.horizontal?`width`:`height`;t.style[i]=`${r}px`}}})});return l.setOptions(c),s_(()=>l._didMount(),[]),s_(()=>(o(l),l._willUpdate())),s_(()=>{s(l)}),l}function l_(e){return c_({observeElementRect:Xg,observeElementOffset:e_,scrollToFn:n_,...e})}var u_=32;function d_(e){return[...new Uint8Array(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}function f_(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<=31||n===127)return!0}return!1}async function p_(e){let t=e.trim();if(t&&!f_(t)&&!(t.length>4096))return d_(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(t))).slice(0,u_)}function m_(e,t,n){if(!e)return!1;let r=t.trim();return r?e===r||n!==void 0&&e===n:!1}var h_={400:{en:{label:`Bad request`,description:`The proxy could not understand the request. Check the model, message shape, headers, and JSON body before retrying.`},fr:{label:`Requête incorrecte`,description:`Le proxy n’a pas pu comprendre la requête. Vérifiez le modèle, la structure des messages, les en-têtes et le corps JSON avant de réessayer.`},ko:{label:`잘못된 요청`,description:`프록시가 요청을 이해할 수 없습니다. 재시도 전에 모델, 메시지 형식, 헤더, JSON 본문을 확인해야 합니다.`},zh:{label:`错误请求`,description:`代理无法理解该请求。重试前请检查模型、消息结构、标头和 JSON 正文。`},"zh-TW":{label:`錯誤請求`,description:`代理無法理解該請求。重試前請檢查模型、訊息結構、標頭和 JSON 本文。`},de:{label:`Ungültige Anfrage`,description:`Der Proxy konnte die Anfrage nicht verstehen. Prüfe Modell, Nachrichtenformat, Header und JSON-Body vor einem erneuten Versuch.`},ru:{label:`Некорректный запрос`,description:`Прокси не смог интерпретировать запрос. Перед повторной попыткой проверьте модель, формат сообщений, заголовки и тело JSON.`},ja:{label:`不正なリクエスト`,description:`プロキシがリクエストを解釈できませんでした。再試行前にモデル、メッセージ形式、ヘッダー、JSON 本文を確認してください。`},tr:{label:`Hatalı istek`,description:`Proxy isteği anlayamadı. Yeniden denemeden önce modeli, mesaj yapısını, başlıkları ve JSON gövdesini kontrol edin.`}},401:{en:{label:`Unauthorized`,description:`Credentials are missing, expired, or invalid. Re-login or refresh the account/provider credentials used by opencodex.`},fr:{label:`Non autorisé`,description:`Les identifiants sont absents, expirés ou non valides. Reconnectez-vous ou actualisez les identifiants du compte ou du fournisseur utilisés par opencodex.`},ko:{label:`인증 필요`,description:`자격 증명이 없거나 만료되었거나 유효하지 않습니다. opencodex에서 사용하는 계정 또는 제공자 자격 증명을 다시 로그인하거나 갱신해야 합니다.`},zh:{label:`未授权`,description:`凭据缺失、已过期或无效。请重新登录,或刷新 opencodex 使用的账号/提供商凭据。`},"zh-TW":{label:`未授權`,description:`憑證缺失、已過期或無效。請重新登入,或重新整理 opencodex 使用的帳號/供應商憑證。`},de:{label:`Nicht autorisiert`,description:`Anmeldedaten fehlen, sind abgelaufen oder ungültig. Melde dich erneut an oder aktualisiere die von opencodex genutzten Konto-/Anbieter-Zugangsdaten.`},ru:{label:`Не авторизован`,description:`Учётные данные отсутствуют, истекли или недействительны. Войдите заново или обновите учётные данные аккаунта или провайдера, которые использует opencodex.`},ja:{label:`認証が必要`,description:`認証情報が不在・期限切れ・無効です。opencodex が使用するアカウントまたはプロバイダー認証情報を再ログインまたは更新してください。`},tr:{label:`Yetkisiz erişim`,description:`Kimlik bilgileri eksik, süresi dolmuş veya geçersiz. opencodex tarafından kullanılan hesap veya sağlayıcı kimlik bilgilerini yeniden doğrulayın.`}},402:{en:{label:`Payment required`,description:`The upstream provider rejected the request because billing, credits, or plan access is not available. Add credits, update billing, or switch provider.`},fr:{label:`Paiement requis`,description:`Le fournisseur en amont a rejeté la requête, car la facturation, les crédits ou l’accès à l’offre ne sont pas disponibles. Ajoutez des crédits, mettez à jour la facturation ou changez de fournisseur.`},ko:{label:`결제 필요`,description:`청구, 크레딧, 플랜 접근 권한 문제로 업스트림 제공자가 요청을 거부했습니다. 크레딧 추가, 결제 정보 갱신, 제공자 전환이 필요합니다.`},zh:{label:`需要付款`,description:`上游提供商因账单、额度或套餐权限不可用而拒绝了请求。请充值、更新账单信息或切换提供商。`},"zh-TW":{label:`需要付款`,description:`上游供應商因帳單、額度或方案許可權不可用而拒絕了請求。請儲值、更新帳單資訊或切換供應商。`},de:{label:`Zahlung erforderlich`,description:`Der Upstream-Anbieter hat die Anfrage abgelehnt, weil Abrechnung, Guthaben oder Planzugriff nicht verfügbar ist. Guthaben aufladen, Abrechnung aktualisieren oder Anbieter wechseln.`},ru:{label:`Требуется оплата`,description:`Вышестоящий провайдер отклонил запрос из-за проблем с оплатой, кредитами или доступом по тарифному плану. Пополните баланс, обновите платёжные данные или переключитесь на другого провайдера.`},ja:{label:`支払いが必要`,description:`課金、クレジット、プランアクセスが利用できないため上流プロバイダーがリクエストを拒否しました。クレジット追加、支払い情報更新、プロバイダー切替が必要です。`},tr:{label:`Ödeme gerekli`,description:`Yukarı akış sağlayıcısı faturalandırma, kredi veya plan erişimi bulunmadığından isteği reddetti. Kredi ekleyin, ödeme bilgilerini güncelleyin veya sağlayıcı değiştirin.`}},403:{en:{label:`Forbidden`,description:`The account is authenticated but not allowed to use this model or operation. Often a plan/subscription gate (e.g. Ollama Cloud Pro), org policy, or model permission — not necessarily a bad API key.`},fr:{label:`Accès interdit`,description:`Le compte est authentifié, mais n’est pas autorisé à utiliser ce modèle ou cette opération. Il s’agit souvent d’une restriction liée à l’offre ou à l’abonnement (p. ex. Ollama Cloud Pro), à la politique de l’organisation ou aux autorisations du modèle — pas nécessairement d’une clé API incorrecte.`},ko:{label:`권한 없음`,description:`계정 인증은 되었지만 이 모델 또는 작업을 사용할 권한이 없습니다. 플랜/구독 제한(예: Ollama Cloud Pro), 조직 정책, 모델 권한 문제인 경우가 많으며 API 키가 잘못된 것은 아닐 수 있습니다.`},zh:{label:`禁止访问`,description:`账号已认证,但无权使用此模型或操作。常见原因是套餐/订阅限制(例如 Ollama Cloud Pro)、组织策略或模型权限——不一定是 API 密钥无效。`},"zh-TW":{label:`禁止存取`,description:`帳號已認證,但無權使用此模型或操作。常見原因是方案/訂閱限制(例如 Ollama Cloud Pro)、組織策略或模型許可權——不一定是 API 金鑰無效。`},de:{label:`Verboten`,description:`Das Konto ist authentifiziert, darf dieses Modell oder diese Operation aber nicht nutzen. Oft Plan-/Abo-Sperre (z. B. Ollama Cloud Pro), Organisationsrichtlinie oder Modellrecht — nicht zwingend ein ungültiger API-Key.`},ru:{label:`Доступ запрещён`,description:`Аккаунт аутентифицирован, но не имеет права использовать эту модель или операцию. Часто причина — ограничение тарифа или подписки (например, Ollama Cloud Pro), политика организации или права доступа к модели, а не обязательно неверный API-ключ.`},ja:{label:`アクセス禁止`,description:`アカウントは認証済みですがこのモデルや操作の使用が許可されていません。多くはプラン/サブスクリプション制限(例: Ollama Cloud Pro)、組織ポリシー、モデル権限であり、API キーが不正とは限りません。`},tr:{label:`Erişim yasaklandı`,description:`Hesabın kimliği doğrulandı ancak bu modeli veya işlemi kullanma izni yok. Genellikle plan/abonelik sınırı (örn. Ollama Cloud Pro), organizasyon politikası veya model izni kaynaklıdır.`}},404:{en:{label:`Not found`,description:`The requested route, model, account, or upstream resource was not found. Verify the model name and opencodex provider configuration.`},fr:{label:`Introuvable`,description:`La route, le modèle, le compte ou la ressource en amont demandés sont introuvables. Vérifiez le nom du modèle et la configuration du fournisseur opencodex.`},ko:{label:`찾을 수 없음`,description:`요청한 경로, 모델, 계정 또는 업스트림 리소스를 찾을 수 없습니다. 모델 이름과 opencodex 제공자 설정을 확인해야 합니다.`},zh:{label:`未找到`,description:`找不到请求的路由、模型、账号或上游资源。请确认模型名称和 opencodex 提供商配置。`},"zh-TW":{label:`未找到`,description:`找不到請求的路由、模型、帳號或上游資源。請確認模型名稱和 opencodex 供應商配置。`},de:{label:`Nicht gefunden`,description:`Die angeforderte Route, das Modell, das Konto oder die Upstream-Ressource wurde nicht gefunden. Prüfe Modellname und opencodex-Anbieterkonfiguration.`},ru:{label:`Не найдено`,description:`Запрошенный маршрут, модель, аккаунт или вышестоящий ресурс не найден. Проверьте имя модели и конфигурацию провайдера в opencodex.`},ja:{label:`見つかりません`,description:`要求されたルート、モデル、アカウント、上流リソースが見つかりませんでした。モデル名と opencodex プロバイダー設定を確認してください。`},tr:{label:`Bulunamadı`,description:`İstenen rota, model, hesap veya yukarı akış kaynağı bulunamadı. Model adını ve opencodex sağlayıcı yapılandırmasını doğrulayın.`}},408:{en:{label:`Request timeout`,description:`The request took too long before the proxy or upstream provider could complete it. Retry with a smaller request or a different provider.`},fr:{label:`Délai d’attente de la requête dépassé`,description:`La requête a pris trop de temps pour que le proxy ou le fournisseur en amont puisse la traiter. Réessayez avec une requête plus petite ou un autre fournisseur.`},ko:{label:`요청 시간 초과`,description:`프록시 또는 업스트림 제공자가 요청을 완료하기 전에 시간이 초과되었습니다. 더 작은 요청으로 재시도하거나 다른 제공자로 전환해야 합니다.`},zh:{label:`请求超时`,description:`代理或上游提供商未能在限定时间内完成请求。请缩小请求后重试,或切换提供商。`},"zh-TW":{label:`請求逾時`,description:`代理或上游供應商未能在限定時間內完成請求。請縮小請求後重試,或切換供應商。`},de:{label:`Anfrage-Timeout`,description:`Die Anfrage dauerte zu lange, bevor Proxy oder Upstream-Anbieter sie abschließen konnten. Mit kleinerer Anfrage oder anderem Anbieter erneut versuchen.`},ru:{label:`Тайм-аут запроса`,description:`Обработка запроса заняла слишком много времени, и прокси или вышестоящий провайдер не успел её завершить. Повторите попытку с меньшим запросом или через другого провайдера.`},ja:{label:`リクエストタイムアウト`,description:`プロキシまたは上流プロバイダーがリクエストを完了する前に時間切れになりました。より小さいリクエストで再試行するか、別のプロバイダーに切り替えてください。`},tr:{label:`İstek zaman aşımı`,description:`Proxy veya yukarı akış sağlayıcısı isteği tamamlayamadan zaman aşımına uğradı. Daha küçük bir istek veya farklı bir sağlayıcı ile tekrar deneyin.`}},409:{en:{label:`Conflict`,description:`The request conflicts with the current account, session, or provider state. Refresh the session or retry after the active operation finishes.`},fr:{label:`Conflit`,description:`La requête entre en conflit avec l’état actuel du compte, de la session ou du fournisseur. Actualisez la session ou réessayez une fois l’opération en cours terminée.`},ko:{label:`상태 충돌`,description:`요청이 현재 계정, 세션 또는 제공자 상태와 충돌합니다. 세션을 갱신하거나 진행 중인 작업이 끝난 뒤 재시도해야 합니다.`},zh:{label:`状态冲突`,description:`请求与当前账号、会话或提供商状态冲突。请刷新会话,或等待当前操作完成后重试。`},"zh-TW":{label:`狀態衝突`,description:`請求與當前帳號、會話或供應商狀態衝突。請重新整理會話,或等待當前操作完成後重試。`},de:{label:`Konflikt`,description:`Die Anfrage kollidiert mit dem aktuellen Konto-, Sitzungs- oder Anbieterstatus. Sitzung aktualisieren oder nach Abschluss der laufenden Operation erneut versuchen.`},ru:{label:`Конфликт`,description:`Запрос конфликтует с текущим состоянием аккаунта, сессии или провайдера. Обновите сессию или повторите попытку после завершения текущей операции.`},ja:{label:`状態の衝突`,description:`リクエストが現在のアカウント、セッション、プロバイダー状態と衝突しています。セッションを更新するか、進行中の操作が終わった後に再試行してください。`},tr:{label:`Durum çakışması`,description:`İstek mevcut hesap, oturum veya sağlayıcı durumuyla çakışıyor. Oturumu yenileyin veya aktif işlem bittikten sonra tekrar deneyin.`}},413:{en:{label:`Request too large`,description:`The prompt, attachments, or generated payload exceeds a proxy or upstream limit. Reduce tokens, file size, or conversation history.`},fr:{label:`Requête trop volumineuse`,description:`L’invite, les pièces jointes ou la charge utile générée dépassent une limite du proxy ou du fournisseur en amont. Réduisez le nombre de jetons, la taille des fichiers ou l’historique de la conversation.`},ko:{label:`요청 과대`,description:`프롬프트, 첨부 파일 또는 생성 페이로드가 프록시나 업스트림 한도를 초과했습니다. 토큰, 파일 크기, 대화 기록을 줄여야 합니다.`},zh:{label:`请求过大`,description:`提示、附件或生成的负载超过了代理或上游限制。请减少 token、文件大小或对话历史。`},"zh-TW":{label:`請求過大`,description:`提示、附件或生成的負載超過了代理或上游限制。請減少 token、檔案大小或對話歷史。`},de:{label:`Anfrage zu groß`,description:`Prompt, Anhänge oder generierte Nutzlast überschreiten ein Proxy- oder Upstream-Limit. Tokens, Dateigröße oder Verlauf reduzieren.`},ru:{label:`Слишком большой запрос`,description:`Промпт, вложения или сформированная полезная нагрузка превышают лимит прокси или вышестоящего провайдера. Сократите количество токенов, размер файлов или историю диалога.`},ja:{label:`リクエストが大きすぎます`,description:`プロンプト、添付ファイル、生成ペイロードがプロキシまたは上流の制限を超えました。トークン、ファイルサイズ、会話履歴を減らしてください。`},tr:{label:`İstek çok büyük`,description:`İstemi, ekler veya oluşturulan veri proxy ya da yukarı akış sınırını aşıyor. Jeton sayısını, dosya boyutunu veya sohbet geçmişini azaltın.`}},422:{en:{label:`Invalid content`,description:`The provider accepted the request format but rejected its contents. Check model options, tool definitions, message roles, and unsupported fields.`},fr:{label:`Contenu non valide`,description:`Le fournisseur a accepté le format de la requête, mais en a rejeté le contenu. Vérifiez les options du modèle, les définitions des outils, les rôles des messages et les champs non pris en charge.`},ko:{label:`내용 검증 실패`,description:`제공자가 요청 형식은 받았지만 내용을 거부했습니다. 모델 옵션, 도구 정의, 메시지 역할, 지원되지 않는 필드를 확인해야 합니다.`},zh:{label:`内容无效`,description:`提供商接受了请求格式,但拒绝了其中的内容。请检查模型选项、工具定义、消息角色和不支持的字段。`},"zh-TW":{label:`內容無效`,description:`供應商接受了請求格式,但拒絕了其中的內容。請檢查模型選項、工具定義、訊息角色和不支援的欄位。`},de:{label:`Ungültiger Inhalt`,description:`Der Anbieter akzeptierte das Anfrageformat, lehnte den Inhalt aber ab. Prüfe Modelloptionen, Tool-Definitionen, Nachrichtenrollen und nicht unterstützte Felder.`},ru:{label:`Недопустимое содержимое`,description:`Провайдер принял формат запроса, но отклонил его содержимое. Проверьте параметры модели, определения инструментов, роли сообщений и неподдерживаемые поля.`},ja:{label:`内容の検証失敗`,description:`プロバイダーはリクエスト形式を受け付けましたが内容を拒否しました。モデルオプション、ツール定義、メッセージロール、未サポートのフィールドを確認してください。`},tr:{label:`Geçersiz içerik`,description:`Sağlayıcı istek formatını kabul etti ancak içeriğini reddetti. Model seçeneklerini, araç tanımlarını, mesaj rollerini ve desteklenmeyen alanları kontrol edin.`}},424:{en:{label:`Provider dependency failed`,description:`A required upstream dependency failed while opencodex was routing the request. Retry later or switch to another configured provider.`},fr:{label:`Échec d’une dépendance du fournisseur`,description:`Une dépendance en amont requise a échoué pendant le routage de la requête par opencodex. Réessayez plus tard ou sélectionnez un autre fournisseur configuré.`},ko:{label:`제공자 의존성 실패`,description:`opencodex가 요청을 라우팅하는 동안 필요한 업스트림 의존성이 실패했습니다. 나중에 재시도하거나 다른 설정된 제공자로 전환해야 합니다.`},zh:{label:`提供商依赖失败`,description:`opencodex 路由请求时,必需的上游依赖失败。请稍后重试,或切换到另一个已配置的提供商。`},"zh-TW":{label:`供應商依賴失敗`,description:`opencodex 路由請求時,必需的上游依賴失敗。請稍後重試,或切換到另一個已配置的供應商。`},de:{label:`Anbieter-Abhängigkeit fehlgeschlagen`,description:`Eine erforderliche Upstream-Abhängigkeit ist fehlgeschlagen, während opencodex die Anfrage geroutet hat. Später erneut versuchen oder zu einem anderen Anbieter wechseln.`},ru:{label:`Сбой зависимости провайдера`,description:`Необходимая вышестоящая зависимость дала сбой, пока opencodex маршрутизировал запрос. Повторите попытку позже или переключитесь на другого настроенного провайдера.`},ja:{label:`プロバイダー依存の失敗`,description:`opencodex がリクエストをルーティング中に必要な上流依存が失敗しました。後で再試行するか、別の設定済みプロバイダーに切り替えてください。`},tr:{label:`Sağlayıcı bağımlılığı başarısız`,description:`opencodex isteği yönlendirirken gerekli bir yukarı akış bağımlılığı başarısız oldu. Daha sonra tekrar deneyin veya başka bir sağlayıcıya geçin.`}},429:{en:{label:`Rate limited`,description:`The upstream provider rate or quota limit has been reached. Wait for the quota window to reset or switch account/provider.`},fr:{label:`Limite de débit atteinte`,description:`La limite de débit ou de quota du fournisseur en amont a été atteinte. Attendez la réinitialisation de la fenêtre de quota ou changez de compte ou de fournisseur.`},ko:{label:`한도 초과`,description:`업스트림 제공자의 속도 또는 할당량 한도에 도달했습니다. 한도 창이 초기화될 때까지 기다리거나 계정/제공자를 전환해야 합니다.`},zh:{label:`限流`,description:`已达到上游提供商的速率或额度限制。请等待额度窗口重置,或切换账号/提供商。`},"zh-TW":{label:`限流`,description:`已達到上游供應商的速率或額度限制。請等待額度視窗重設,或切換帳號/供應商。`},de:{label:`Ratenlimit erreicht`,description:`Das Raten- oder Kontingentlimit des Upstream-Anbieters ist erreicht. Auf Reset des Kontingentfensters warten oder Konto/Anbieter wechseln.`},ru:{label:`Превышен лимит запросов`,description:`Достигнут лимит скорости или квота вышестоящего провайдера. Дождитесь сброса окна квоты или переключитесь на другой аккаунт или провайдера.`},ja:{label:`レート制限`,description:`上流プロバイダーのレートまたはクォータ制限に達しました。クォータウィンドウがリセットされるまで待つか、アカウント/プロバイダーを切り替えてください。`},tr:{label:`Oran sınırı aşıldı`,description:`Yukarı akış sağlayıcısının hız veya kota sınırına ulaşıldı. Kota penceresinin sıfırlanmasını bekleyin ya da hesap/sağlayıcı değiştirin.`}},499:{en:{label:`Client closed request`,description:`The client disconnected or canceled the request before opencodex finished routing it. Retry if the cancellation was accidental.`},fr:{label:`Requête fermée par le client`,description:`Le client s’est déconnecté ou a annulé la requête avant la fin de son routage par opencodex. Réessayez si l’annulation était involontaire.`},ko:{label:`클라이언트 취소`,description:`opencodex가 라우팅을 끝내기 전에 클라이언트 연결이 끊기거나 요청이 취소되었습니다. 의도한 취소가 아니면 다시 시도해야 합니다.`},zh:{label:`客户端已取消`,description:`opencodex 完成路由前,客户端已断开连接或取消请求。如果不是有意取消,请重试。`},"zh-TW":{label:`客戶端已取消`,description:`opencodex 完成路由前,客戶端已斷開連線或取消請求。如果不是有意取消,請重試。`},de:{label:`Client hat Anfrage geschlossen`,description:`Der Client hat die Verbindung getrennt oder die Anfrage abgebrochen, bevor opencodex das Routing abgeschlossen hat. Bei versehentlichem Abbruch erneut versuchen.`},ru:{label:`Запрос закрыт клиентом`,description:`Клиент отключился или отменил запрос до того, как opencodex завершил его маршрутизацию. Если отмена была случайной, повторите попытку.`},ja:{label:`クライアントがリクエストをクローズ`,description:`opencodex がルーティングを終える前にクライアントが切断またはキャンセルしました。意図しないキャンセルなら再試行してください。`},tr:{label:`İstemci isteği kapattı`,description:`opencodex yönlendirmeyi bitirmeden önce istemci bağlantıyı kesti veya isteği iptal etti. İptal kazara yapıldıysa tekrar deneyin.`}},500:{en:{label:`Proxy error`,description:`opencodex hit an internal error while handling the request. Retry once, then check proxy logs if it repeats.`},fr:{label:`Erreur du proxy`,description:`opencodex a rencontré une erreur interne lors du traitement de la requête. Réessayez une fois, puis consultez les journaux du proxy si l’erreur se reproduit.`},ko:{label:`프록시 오류`,description:`opencodex가 요청을 처리하는 동안 내부 오류가 발생했습니다. 한 번 재시도하고 반복되면 프록시 로그를 확인해야 합니다.`},zh:{label:`代理错误`,description:`opencodex 处理请求时发生内部错误。请先重试一次;如果重复出现,请检查代理日志。`},"zh-TW":{label:`代理錯誤`,description:`opencodex 處理請求時發生內部錯誤。請先重試一次;如果重複出現,請檢查代理日誌。`},de:{label:`Proxy-Fehler`,description:`opencodex ist bei der Anfragebearbeitung auf einen internen Fehler gestoßen. Einmal erneut versuchen, bei Wiederholung Proxy-Logs prüfen.`},ru:{label:`Ошибка прокси`,description:`В opencodex произошла внутренняя ошибка при обработке запроса. Повторите попытку один раз; если ошибка повторяется, проверьте логи прокси.`},ja:{label:`プロキシエラー`,description:`opencodex がリクエスト処理中に内部エラーに遭遇しました。1 回再試行し、繰り返す場合はプロキシログを確認してください。`},tr:{label:`Proxy hatası`,description:`opencodex isteği işlerken dahili bir hatayla karşılaştı. Bir kez tekrar deneyin, tekrarlarsa proxy günlüklerini kontrol edin.`}},502:{en:{label:`Bad upstream response`,description:`The upstream provider returned an invalid or failed response through the proxy. Retry or route the request to another provider.`},fr:{label:`Réponse incorrecte du fournisseur en amont`,description:`Le fournisseur en amont a renvoyé une réponse non valide ou en échec par l’intermédiaire du proxy. Réessayez ou acheminez la requête vers un autre fournisseur.`},ko:{label:`업스트림 응답 오류`,description:`업스트림 제공자가 프록시를 통해 유효하지 않거나 실패한 응답을 반환했습니다. 재시도하거나 다른 제공자로 라우팅해야 합니다.`},zh:{label:`上游响应错误`,description:`上游提供商通过代理返回了无效或失败的响应。请重试,或将请求路由到其他提供商。`},"zh-TW":{label:`上游回應錯誤`,description:`上游供應商透過代理返回了無效或失敗的回應。請重試,或將請求路由到其他供應商。`},de:{label:`Ungültige Upstream-Antwort`,description:`Der Upstream-Anbieter lieferte über den Proxy eine ungültige oder fehlgeschlagene Antwort. Erneut versuchen oder zu einem anderen Anbieter routen.`},ru:{label:`Некорректный ответ провайдера`,description:`Вышестоящий провайдер вернул через прокси недействительный или ошибочный ответ. Повторите попытку или направьте запрос другому провайдеру.`},ja:{label:`上流レスポンス不良`,description:`上流プロバイダーがプロキシ経由で無効または失敗したレスポンスを返しました。再試行するか、リクエストを別のプロバイダーにルーティングしてください。`},tr:{label:`Kötü yukarı akış yanıtı`,description:`Yukarı akış sağlayıcısı proxy üzerinden geçersiz veya başarısız bir yanıt döndürdü. Tekrar deneyin veya isteği başka bir sağlayıcıya yönlendirin.`}},503:{en:{label:`Provider unavailable`,description:`The proxy or upstream provider is temporarily unavailable or overloaded. Wait briefly, then retry or switch provider.`},fr:{label:`Fournisseur indisponible`,description:`Le proxy ou le fournisseur en amont est temporairement indisponible ou surchargé. Patientez un instant, puis réessayez ou changez de fournisseur.`},ko:{label:`제공자 사용 불가`,description:`프록시 또는 업스트림 제공자가 일시적으로 사용할 수 없거나 과부하 상태입니다. 잠시 기다린 뒤 재시도하거나 제공자를 전환해야 합니다.`},zh:{label:`提供商不可用`,description:`代理或上游提供商暂时不可用或过载。请稍后重试,或切换提供商。`},"zh-TW":{label:`供應商不可用`,description:`代理或上游供應商暫時不可用或過載。請稍後重試,或切換供應商。`},de:{label:`Anbieter nicht verfügbar`,description:`Proxy oder Upstream-Anbieter ist vorübergehend nicht verfügbar oder überlastet. Kurz warten, dann erneut versuchen oder Anbieter wechseln.`},ru:{label:`Провайдер недоступен`,description:`Прокси или вышестоящий провайдер временно недоступен или перегружен. Немного подождите, затем повторите попытку или смените провайдера.`},ja:{label:`プロバイダー利用不可`,description:`プロキシまたは上流プロバイダーが一時的に利用不可または過負荷です。少し待ってから再試行するか、プロバイダーを切り替えてください。`},tr:{label:`Sağlayıcı kullanılamıyor`,description:`Proxy veya yukarı akış sağlayıcısı geçici olarak kullanılamıyor veya aşırı yüklü. Kısa bir süre bekleyip tekrar deneyin ya da sağlayıcı değiştirin.`}},504:{en:{label:`Upstream timeout`,description:`The upstream provider did not respond before the proxy timeout. Retry with a smaller request or choose a faster provider.`},fr:{label:`Délai d’attente du fournisseur en amont dépassé`,description:`Le fournisseur en amont n’a pas répondu avant l’expiration du délai du proxy. Réessayez avec une requête plus petite ou choisissez un fournisseur plus rapide.`},ko:{label:`업스트림 시간 초과`,description:`프록시 시간 제한 전에 업스트림 제공자가 응답하지 않았습니다. 더 작은 요청으로 재시도하거나 더 빠른 제공자를 선택해야 합니다.`},zh:{label:`上游超时`,description:`上游提供商未在代理超时前响应。请缩小请求后重试,或选择响应更快的提供商。`},"zh-TW":{label:`上游逾時`,description:`上游供應商未在代理逾時前回應。請縮小請求後重試,或選擇回應更快的供應商。`},de:{label:`Upstream-Timeout`,description:`Der Upstream-Anbieter antwortete nicht vor dem Proxy-Timeout. Mit kleinerer Anfrage erneut versuchen oder schnelleren Anbieter wählen.`},ru:{label:`Тайм-аут вышестоящего провайдера`,description:`Вышестоящий провайдер не ответил до истечения тайм-аута прокси. Повторите попытку с меньшим запросом или выберите более быстрого провайдера.`},ja:{label:`上流タイムアウト`,description:`上流プロバイダーがプロキシタイムアウト前に応答しませんでした。より小さいリクエストで再試行するか、より速いプロバイダーを選んでください。`},tr:{label:`Yukarı akış zaman aşımı`,description:`Yukarı akış sağlayıcısı proxy zaman aşımı süresinden önce yanıt vermedi. Daha küçük bir istekle tekrar deneyin veya daha hızlı bir sağlayıcı seçin.`}},529:{en:{label:`Provider overloaded`,description:`The upstream provider is overloaded or capacity-limited. Wait and retry, or switch to another account/provider.`},fr:{label:`Fournisseur surchargé`,description:`Le fournisseur en amont est surchargé ou sa capacité est limitée. Patientez et réessayez, ou changez de compte ou de fournisseur.`},ko:{label:`제공자 과부하`,description:`업스트림 제공자가 과부하 상태이거나 처리 용량이 제한되었습니다. 기다렸다가 재시도하거나 다른 계정/제공자로 전환해야 합니다.`},zh:{label:`提供商过载`,description:`上游提供商过载或容量受限。请等待后重试,或切换到其他账号/提供商。`},"zh-TW":{label:`供應商過載`,description:`上游供應商過載或容量受限。請等待後重試,或切換到其他帳號/供應商。`},de:{label:`Anbieter überlastet`,description:`Der Upstream-Anbieter ist überlastet oder kapazitätsbegrenzt. Warten und erneut versuchen oder anderes Konto/Anbieter nutzen.`},ru:{label:`Провайдер перегружен`,description:`Вышестоящий провайдер перегружен или ограничен по мощности. Подождите и повторите попытку либо переключитесь на другой аккаунт или провайдера.`},ja:{label:`プロバイダー過負荷`,description:`上流プロバイダーが過負荷または容量制限されています。待ってから再試行するか、別のアカウント/プロバイダーに切り替えてください。`},tr:{label:`Sağlayıcı aşırı yüklü`,description:`Yukarı akış sağlayıcısı aşırı yüklü veya kapasitesi sınırlı. Bekleyip tekrar deneyin veya başka bir hesap/sağlayıcıya geçin.`}}},g_={client:{en:{label:`Request error`,description:`The proxy or upstream provider rejected the request. Check the request shape, credentials, model name, and provider configuration.`},fr:{label:`Erreur de requête`,description:`Le proxy ou le fournisseur en amont a rejeté la requête. Vérifiez sa structure, les identifiants, le nom du modèle et la configuration du fournisseur.`},ko:{label:`요청 오류`,description:`프록시 또는 업스트림 제공자가 요청을 거부했습니다. 요청 형식, 자격 증명, 모델 이름, 제공자 설정을 확인해야 합니다.`},zh:{label:`请求错误`,description:`代理或上游提供商拒绝了该请求。请检查请求结构、凭据、模型名称和提供商配置。`},"zh-TW":{label:`請求錯誤`,description:`代理或上游供應商拒絕了該請求。請檢查請求結構、憑證、模型名稱和供應商配置。`},de:{label:`Anfragefehler`,description:`Der Proxy oder Upstream-Anbieter hat die Anfrage abgelehnt. Prüfe Anfrageformat, Anmeldedaten, Modellname und Anbieterkonfiguration.`},ru:{label:`Ошибка запроса`,description:`Прокси или вышестоящий провайдер отклонил запрос. Проверьте структуру запроса, учётные данные, имя модели и конфигурацию провайдера.`},ja:{label:`リクエストエラー`,description:`プロキシまたは上流プロバイダーがリクエストを拒否しました。リクエスト形式、認証情報、モデル名、プロバイダー設定を確認してください。`},tr:{label:`İstek hatası`,description:`Proxy veya yukarı akış sağlayıcısı isteği reddetti. İstek yapısını, kimlik bilgilerini, model adını ve sağlayıcı yapılandırmasını kontrol edin.`}},server:{en:{label:`Server or upstream error`,description:`opencodex or an upstream provider failed while processing the request. Retry later or route the request to another provider.`},fr:{label:`Erreur du serveur ou du fournisseur en amont`,description:`opencodex ou un fournisseur en amont a échoué lors du traitement de la requête. Réessayez plus tard ou acheminez la requête vers un autre fournisseur.`},ko:{label:`서버 또는 업스트림 오류`,description:`opencodex 또는 업스트림 제공자가 요청 처리 중 실패했습니다. 나중에 재시도하거나 다른 제공자로 라우팅해야 합니다.`},zh:{label:`服务器或上游错误`,description:`opencodex 或上游提供商处理请求时失败。请稍后重试,或将请求路由到其他提供商。`},"zh-TW":{label:`伺服器或上游錯誤`,description:`opencodex 或上游供應商處理請求時失敗。請稍後重試,或將請求路由到其他供應商。`},de:{label:`Server- oder Upstream-Fehler`,description:`opencodex oder ein Upstream-Anbieter ist bei der Anfragebearbeitung fehlgeschlagen. Später erneut versuchen oder zu einem anderen Anbieter routen.`},ru:{label:`Ошибка сервера или провайдера`,description:`opencodex или вышестоящий провайдер завершил обработку запроса с ошибкой. Повторите попытку позже или направьте запрос другому провайдеру.`},ja:{label:`サーバーまたは上流エラー`,description:`opencodex または上流プロバイダーがリクエスト処理中に失敗しました。後で再試行するか、リクエストを別のプロバイダーにルーティングしてください。`},tr:{label:`Sunucu veya yukarı akış hatası`,description:`opencodex veya bir yukarı akış sağlayıcısı isteği işlerken başarısız oldu. Daha sonra tekrar deneyin veya isteği başka bir sağlayıcıya yönlendirin.`}}};function __(e){return e.toLowerCase().startsWith(`fr`)?`fr`:e===`de`||e===`ko`||e===`zh`||e===`zh-TW`||e===`ru`||e===`ja`||e===`tr`?e:`en`}function v_(e,t){if(e<400)return null;let n=__(t);return(h_[Math.trunc(e)]??(e<500?g_.client:g_.server))[n]}var y_=[`provider`,`usage`,`injection`];function b_(e){return e>0?`[${new Date(e).toLocaleTimeString()}] `:``}function x_(e){return new Date(e).toLocaleTimeString()}function S_(e,t){return t===`provider`?!!e?.enabled:t===`usage`?!!e?.usage:!!e?.injection}function C_(e,t){return t===`debug`?e.enabled:t===`usage`?e.usage:t===`injection`?e.injection:e.claude}function w_({entries:e}){let{t}=ut();return(0,Y.jsxs)(`div`,{className:`card`,style:{marginBottom:16,padding:`12px 14px`},children:[(0,Y.jsx)(`div`,{className:`font-semibold`,style:{marginBottom:4},children:t(`debug.claudeInbound.title`)}),(0,Y.jsx)(`div`,{className:`muted text-control`,style:{marginBottom:10},children:t(`debug.claudeInbound.sub`)}),e.length===0?(0,Y.jsx)(`div`,{className:`muted text-control`,children:t(`debug.claudeInbound.empty`)}):(0,Y.jsx)(`div`,{style:{overflowX:`auto`},children:(0,Y.jsxs)(`table`,{className:`table text-label`,children:[(0,Y.jsx)(`thead`,{children:(0,Y.jsxs)(`tr`,{children:[(0,Y.jsx)(`th`,{children:t(`debug.claudeInbound.time`)}),(0,Y.jsx)(`th`,{children:t(`debug.claudeInbound.endpoint`)}),(0,Y.jsx)(`th`,{children:t(`debug.claudeInbound.model`)}),(0,Y.jsx)(`th`,{children:`thinking`}),(0,Y.jsx)(`th`,{children:`effort`}),(0,Y.jsx)(`th`,{children:`beta`}),(0,Y.jsx)(`th`,{children:`metadata`}),(0,Y.jsx)(`th`,{children:`system`})]})}),(0,Y.jsx)(`tbody`,{children:e.map(e=>(0,Y.jsxs)(`tr`,{children:[(0,Y.jsx)(`td`,{className:`muted mono`,children:x_(e.at)}),(0,Y.jsx)(`td`,{className:`mono`,children:e.endpoint}),(0,Y.jsxs)(`td`,{className:`mono`,title:e.resolvedModel,children:[e.model,e.resolvedModel&&e.resolvedModel!==e.model&&(0,Y.jsxs)(`span`,{className:`muted`,children:[` → `,e.resolvedModel]})]}),(0,Y.jsxs)(`td`,{className:`mono`,children:[e.thinkingType??`-`,e.thinkingBudgetTokens!==void 0&&(0,Y.jsxs)(`span`,{className:`muted`,children:[` (`,e.thinkingBudgetTokens,`)`]})]}),(0,Y.jsx)(`td`,{className:`mono`,children:e.outputConfigEffort??`-`}),(0,Y.jsx)(`td`,{className:`mono`,title:e.anthropicBeta,style:{maxWidth:160,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:e.anthropicBeta??`-`}),(0,Y.jsx)(`td`,{className:`mono`,title:e.metadataKeys?.join(`, `),children:e.hasMetadataUserId?`user_id ${e.userIdTag??``}`:t(`debug.claudeInbound.none`)}),(0,Y.jsx)(`td`,{className:`mono`,children:e.hasSystem?e.systemTag??`yes`:t(`debug.claudeInbound.none`)})]},e.id))})]})})]})}function T_({debug:e,stream:t,streamEnabled:n,entries:r,scrollContainerRef:i,lineVirtualizer:a}){let{t:o}=ut();return e?n?r.length===0?(0,Y.jsxs)(`div`,{className:`empty`,children:[(0,Y.jsx)(`div`,{className:`font-semibold`,style:{marginBottom:6},children:o(`debug.noLinesTitle`)}),(0,Y.jsx)(`div`,{className:`muted text-control`,style:{maxWidth:560,marginInline:`auto`},children:o(`debug.noLines.${t}`)})]}):(0,Y.jsx)(`div`,{ref:i,className:`log-detail-json`,style:{maxHeight:`calc(100vh - 280px)`,overflow:`auto`},children:(0,Y.jsx)(`div`,{style:{position:`relative`,height:a.getTotalSize(),width:`100%`},children:a.getVirtualItems().map(e=>(0,Y.jsx)(`div`,{ref:a.measureElement,"data-index":e.index,style:{position:`absolute`,top:0,left:0,width:`100%`,transform:`translateY(${e.start}px)`},children:`${b_(r[e.index].at)}${r[e.index].line}`},e.key))})}):(0,Y.jsxs)(`div`,{className:`empty`,children:[(0,Y.jsx)(`div`,{className:`font-semibold`,style:{marginBottom:6},children:o(`debug.emptyTitle`)}),(0,Y.jsx)(`div`,{className:`muted text-control`,style:{maxWidth:560,marginInline:`auto`},children:o(`debug.empty`)})]}):null}function E_({debug:e,debugBusy:t,stream:n,onSetFlag:r,onReset:i,onStreamChange:a}){let{t:o}=ut();return(0,Y.jsxs)(`div`,{className:`card`,style:{marginBottom:16,padding:`12px 14px`},children:[(0,Y.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:12,flexWrap:`wrap`},children:[(0,Y.jsx)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:16},children:[`debug`,`usage`,`injection`,`claude`].map(n=>{let i=C_(e,n);return(0,Y.jsxs)(`div`,{style:{display:`inline-flex`,alignItems:`center`,gap:10,minWidth:220},children:[(0,Y.jsx)(Dt,{on:i,disabled:t,label:o(`debug.${n}`),onClick:()=>r(n,!i)}),(0,Y.jsx)(`span`,{className:`text-control`,children:o(`debug.${n}`)})]},n)})}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:t,onClick:i,children:o(`debug.reset`)})]}),(e.enabled||e.usage||e.injection)&&(0,Y.jsxs)(`div`,{style:{display:`inline-flex`,gap:6,marginTop:12},children:[e.enabled&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-sm${n===`provider`?` btn-primary`:` btn-ghost`}`,onClick:()=>a(`provider`),children:o(`debug.streamProvider`)}),e.usage&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-sm${n===`usage`?` btn-primary`:` btn-ghost`}`,onClick:()=>a(`usage`),children:o(`debug.streamUsage`)}),e.injection&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-sm${n===`injection`?` btn-primary`:` btn-ghost`}`,onClick:()=>a(`injection`),children:o(`debug.streamInjection`)})]})]})}function D_({embedded:e,refreshing:t,streamEnabled:n,follow:r,onRefresh:i,onFollowChange:a}){let{t:o}=ut();return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{className:e?`row`:`page-head`,style:e?{justifyContent:`flex-end`,marginBottom:4}:void 0,children:[!e&&(0,Y.jsx)(`h2`,{children:o(`debug.title`)}),(0,Y.jsxs)(`div`,{style:{display:`inline-flex`,alignItems:`center`,gap:12},children:[(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:t||!n,onClick:i,children:[(0,Y.jsx)(de,{}),` `,o(`debug.refresh`)]}),(0,Y.jsxs)(`label`,{className:`muted text-control`,style:{cursor:`pointer`,display:`inline-flex`,alignItems:`center`,gap:6},children:[(0,Y.jsx)(`input`,{type:`checkbox`,checked:r,onChange:e=>a(e.target.checked)}),o(`debug.follow`)]})]})]}),(0,Y.jsx)(`p`,{className:`page-sub`,children:o(`debug.subtitle`)})]})}function O_(e){return`debug-settings:${e}`}function k_({apiBase:e,embedded:t,active:n=!0}){let{t:r}=ut(),i=`ocx.debug.settings.v1:${e}`,a=Tr(i),o=O_(e),[s,c]=(0,_.useState)(!1),[l,u]=(0,_.useState)(`provider`),[d,f]=(0,_.useState)([]),[p,m]=(0,_.useState)(!0),[h,g]=(0,_.useState)(!1),v=(0,_.useRef)(0),y=(0,_.useRef)(0),b=(0,_.useRef)(0),x=(0,_.useRef)(null),S=(0,_.useRef)(null),C=(0,_.useRef)(null),w=jr(o,[e],async t=>{let n=await fetch(`${e}/api/debug`,{signal:t});if(!n.ok)throw Error(String(n.status));let r=await n.json();return kr(i,r),r},{pollMs:2e3,enabled:n,isEmpty:()=>!1,initialData:a??void 0}),T=w.state,E=w.data??a??null,D=K(`debug-claude-inbound:${e}`,[e,E?.claude],async t=>{let n=await fetch(`${e}/api/claude/inbound-debug`,{signal:t});if(!n.ok)return[];let r=await n.json();return Array.isArray(r.entries)?r.entries:[]},{pollMs:2e3,enabled:n&&!!E?.claude}).data??[],O=l_({count:d.length,getScrollElement:()=>S.current,estimateSize:()=>20,overscan:30,getItemKey:e=>d[e].seq}),k=(0,_.useCallback)(e=>S_(E,e),[E]);(0,_.useEffect)(()=>{if(!E||k(l))return;let e=y_.find(k);if(!e)return;let t=window.setTimeout(()=>u(e),0);return()=>window.clearTimeout(t)},[E,l,k]);let A=k(l),j=l===`provider`?`${e}/api/debug/logs`:l===`usage`?`${e}/api/debug/usage-logs`:`${e}/api/debug/injection-logs`,M=(0,_.useCallback)(async(e,t)=>{let n=++b.current;if(!A){n===b.current&&(f([]),v.current=0);return}g(!0);try{let r=new URLSearchParams({limit:`500`});!e&&v.current>0&&r.set(`after`,String(v.current));let i=await fetch(`${j}?${r}`,{signal:t});if(!i.ok||t?.aborted||n!==b.current)return;let a=await i.json();if(t?.aborted||n!==b.current||a.length===0)return;f(t=>(e?a:[...t,...a]).slice(-2e3)),v.current=a[a.length-1].seq}catch{}finally{n===b.current&&g(!1)}},[j,A]);(0,_.useEffect)(()=>{if(!n)return;let t=`${e}:${l}:${A}`,r=C.current!==t;if(C.current=t,!r&&d.length>0)return;v.current=0;let i=new AbortController,a=window.setTimeout(()=>{r&&f([]),M(!0,i.signal)},0);return()=>{window.clearTimeout(a),b.current+=1,i.abort()}},[n,e,l,A]);let N=(0,_.useRef)(!1),P=(0,_.useEffectEvent)(()=>{if(N.current)return;N.current=!0;let e=Xn(1e4);M(!1,e.signal).finally(()=>{e.clear(),N.current=!1})});(0,_.useEffect)(()=>{if(!(!n||!p||!A))return er(()=>P(),1e3)},[n,p,A]),(0,_.useEffect)(()=>{p&&d.length>0&&O.scrollToIndex(d.length-1,{align:`end`})},[d,p,O]);let F=async t=>{let n=++y.current;c(!0);let r=async()=>{try{let r=await fetch(`${e}/api/debug`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(t)});if(!r.ok)return;let a=await r.json();if(n!==y.current)return;kr(i,a),q(o,a)}catch{}},a=(x.current??Promise.resolve()).then(r,r);x.current=a.then(()=>void 0,()=>void 0);try{await a}finally{n===y.current&&c(!1)}},I=async(e,t)=>{await F({[e]:t})},L=async()=>{await F({reset:!0})};return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(D_,{embedded:t,refreshing:h,streamEnabled:A,follow:p,onRefresh:()=>void M(!0),onFollowChange:m}),!E&&T.showError?(0,Y.jsxs)(`div`,{className:`notice notice-err`,role:`alert`,children:[(0,Y.jsx)(`span`,{children:r(`debug.loadFailed`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>w.refresh(),children:r(`common.retry`)})]}):T.showSkeleton&&!E?(0,Y.jsx)(ep,{label:r(`debug.loading`),rows:3}):E?(0,Y.jsx)(E_,{debug:E,debugBusy:s,stream:l,onSetFlag:(e,t)=>{I(e,t)},onReset:()=>{L()},onStreamChange:u}):null,E&&T.showError&&(0,Y.jsx)($,{tone:`err`,children:r(`debug.loadFailed`)}),E?.claude&&(0,Y.jsx)(w_,{entries:D}),(0,Y.jsx)(T_,{debug:!!E,stream:l,streamEnabled:A,entries:d,scrollContainerRef:S,lineVirtualizer:O})]})}var A_=[`all`,`claude`,`codex`,`grok`];function j_(e,t,n){let r=A_.indexOf(t),i=-1;if(e.key===`ArrowRight`||e.key===`ArrowDown`?i=(r+1)%A_.length:e.key===`ArrowLeft`||e.key===`ArrowUp`?i=(r-1+A_.length)%A_.length:e.key===`Home`?i=0:e.key===`End`&&(i=A_.length-1),i<0)return;e.preventDefault();let a=A_[i];n(a),document.getElementById(`logs-surface-${a}`)?.focus()}function M_({filters:e,options:t,hasActiveFilters:n,filteredCount:r,totalCount:i,t:a,onFilterChange:o,onResetFilters:s}){let c=(0,_.useRef)(null),l=()=>{s(),c.current?.focus({preventScroll:!0})},u=e.maxTokPerSec===15?`slow`:e.minTokPerSec===15&&e.maxTokPerSec===50?`medium`:e.minTokPerSec===50?`fast`:`all`,d=t=>{let n=t===`slow`?{minTokPerSec:void 0,maxTokPerSec:15}:t===`medium`?{minTokPerSec:15,maxTokPerSec:50}:t===`fast`?{minTokPerSec:50,maxTokPerSec:void 0}:{minTokPerSec:void 0,maxTokPerSec:void 0};o({...e,...n})};return(0,Y.jsxs)(`div`,{className:`logs-filter-container`,children:[(0,Y.jsxs)(`div`,{className:`logs-toolbar`,children:[(0,Y.jsx)(`span`,{className:`muted text-control`,children:a(`logs.filter.surface.label`)}),(0,Y.jsx)(`div`,{className:`segmented logs-segmented`,role:`radiogroup`,"aria-label":a(`logs.filter.surface.label`),children:[`all`,`claude`,`codex`,`grok`].map(t=>(0,Y.jsx)(`button`,{ref:t===`all`?c:void 0,type:`button`,role:`radio`,"aria-checked":e.surface===t,id:`logs-surface-${t}`,tabIndex:e.surface===t?0:-1,className:`btn btn-sm${e.surface===t?` btn-primary`:` btn-ghost`}`,style:{background:e.surface===t?void 0:`transparent`,color:e.surface===t?void 0:`var(--muted)`},onClick:()=>o({...e,surface:t}),onKeyDown:n=>j_(n,t,t=>o({...e,surface:t})),children:a(`logs.filter.surface.${t}`)},t))}),(0,Y.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[(0,Y.jsx)(`input`,{type:`checkbox`,checked:e.interceptedOnly,onChange:t=>o({...e,interceptedOnly:t.target.checked})}),a(`logs.filter.interceptedHelpersOnly`)]}),(0,Y.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[a(`logs.filter.provider.label`),(0,Y.jsxs)(`select`,{className:`input select-sm`,value:e.provider,"aria-label":a(`logs.filter.provider.label`),onChange:t=>o({...e,provider:t.target.value}),children:[(0,Y.jsx)(`option`,{value:``,children:a(`logs.filter.provider.all`)}),t.providers.map(e=>(0,Y.jsx)(`option`,{value:e,children:Ln(e,a)},e))]})]}),(0,Y.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[a(`logs.filter.model.label`),(0,Y.jsxs)(`select`,{className:`input select-sm`,value:e.model,"aria-label":a(`logs.filter.model.label`),onChange:t=>o({...e,model:t.target.value}),children:[(0,Y.jsx)(`option`,{value:``,children:a(`logs.filter.model.all`)}),t.models.map(e=>(0,Y.jsx)(`option`,{value:e,children:e},e))]})]}),(0,Y.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[a(`logs.filter.time.label`),(0,Y.jsxs)(`select`,{className:`input select-sm`,value:e.timeWindow,"aria-label":a(`logs.filter.time.label`),onChange:t=>o({...e,timeWindow:t.target.value}),children:[(0,Y.jsx)(`option`,{value:`all`,children:a(`logs.filter.time.all`)}),(0,Y.jsx)(`option`,{value:`15m`,children:a(`logs.filter.time.15m`)}),(0,Y.jsx)(`option`,{value:`1h`,children:a(`logs.filter.time.1h`)}),(0,Y.jsx)(`option`,{value:`24h`,children:a(`logs.filter.time.24h`)})]})]}),(0,Y.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[a(`logs.filter.speed.label`),(0,Y.jsxs)(`select`,{className:`input select-sm`,value:u,"aria-label":a(`logs.filter.speed.label`),onChange:e=>d(e.target.value),children:[(0,Y.jsx)(`option`,{value:`all`,children:a(`logs.filter.speed.all`)}),(0,Y.jsx)(`option`,{value:`slow`,children:a(`logs.filter.speed.slow`)}),(0,Y.jsx)(`option`,{value:`medium`,children:a(`logs.filter.speed.medium`)}),(0,Y.jsx)(`option`,{value:`fast`,children:a(`logs.filter.speed.fast`)})]})]}),(0,Y.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[a(`logs.filter.status.label`),(0,Y.jsxs)(`select`,{className:`input select-sm`,value:e.status,"aria-label":a(`logs.filter.status.label`),onChange:t=>o({...e,status:t.target.value}),children:[(0,Y.jsx)(`option`,{value:`all`,children:a(`logs.filter.status.all`)}),(0,Y.jsx)(`option`,{value:`success`,children:a(`logs.filter.status.success`)}),(0,Y.jsx)(`option`,{value:`errors`,children:a(`logs.filter.status.errors`)})]})]})]}),(0,Y.jsxs)(`div`,{className:`logs-toolbar logs-toolbar-secondary`,children:[(0,Y.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[a(`logs.filter.conversation.label`),(0,Y.jsx)(`input`,{type:`search`,className:`input mono select-sm`,value:e.conversationId,onChange:t=>o({...e,conversationId:t.target.value}),placeholder:a(`logs.filter.conversation.placeholder`),"aria-label":a(`logs.filter.conversation.label`)})]}),n&&(0,Y.jsxs)(`div`,{className:`logs-filter-status`,children:[(0,Y.jsx)(`span`,{className:`muted text-control`,children:a(`logs.filter.showingCount`,{count:r,total:i})}),(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:l,children:[(0,Y.jsx)(le,{}),` `,a(`logs.filter.reset`)]})]})]})]})}function N_(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?{generatedAt:e,receivedAt:t}:void 0}function P_(e,t,n){return e?e.generatedAt+Math.max(0,t-e.receivedAt):n}function F_(e,t){return t===`all`?!0:t===`claude`?e.surface===`claude`||e.surface===`claude-desktop`:t===`grok`?e.surface===`grok`:e.surface===void 0}var I_={surface:`all`,model:``,provider:``,status:`all`,timeWindow:`all`,interceptedOnly:!1,conversationId:``};function L_(e){return e.surface!==`all`||e.model.trim()!==``||e.provider.trim()!==``||e.status!==`all`||e.timeWindow!==`all`||e.minTokPerSec!==void 0||e.maxTokPerSec!==void 0||e.interceptedOnly||e.conversationId.trim()!==``}function R_(e){return Array.isArray(e.attempts)?e.attempts.filter(e=>typeof e==`object`&&!!e):[]}function z_(e){if(typeof e!=`string`)return;let t=e.trim();return t?t.toLowerCase():void 0}function B_(e,t){if(e===`15m`)return t-9e5;if(e===`1h`)return t-36e5;if(e===`24h`)return t-864e5}function V_(e,t,n=Date.now()){let r=t.model.trim().toLowerCase(),i=t.provider.trim().toLowerCase(),a=t.conversationId.trim(),o=B_(t.timeWindow,n);return e.filter(e=>{if(!F_(e,t.surface)||t.interceptedOnly&&typeof e.shadowCallRewrittenFrom!=`string`||a&&!m_(e.conversationId,a,t.conversationQueryHash)||t.status===`success`&&(typeof e.status!=`number`||!Number.isInteger(e.status)||e.status<200||e.status>=300)||t.status===`errors`&&(typeof e.status!=`number`||!Number.isInteger(e.status)||e.status<400||e.status>599))return!1;let n=R_(e);if(r&&![z_(e.model),z_(e.resolvedModel),...n.map(e=>z_(e.model))].some(e=>e===r)||i&&![z_(e.provider),...n.map(e=>z_(e.provider))].some(e=>e===i)||o!==void 0&&(typeof e.timestamp!=`number`||!Number.isFinite(e.timestamp)||e.timestamp<o))return!1;let s=e.displayMetrics?.tokPerSecond?.kind===`value`&&Number.isFinite(e.displayMetrics.tokPerSecond.value)?e.displayMetrics.tokPerSecond.value:void 0;return!(t.minTokPerSec!==void 0&&(s===void 0||s<t.minTokPerSec)||t.maxTokPerSec!==void 0&&(s===void 0||s>=t.maxTokPerSec))})}function H_(e,t){if(typeof t!=`string`)return;let n=t.trim(),r=z_(n);if(!r)return;let i=e.get(r);(i===void 0||n<i)&&e.set(r,n)}function U_(e){let t=new Map,n=new Map;for(let r of e){for(let e of[r.model,r.resolvedModel,...R_(r).map(e=>e.model)])H_(t,e);for(let e of[r.provider,...R_(r).map(e=>e.provider)])H_(n,e)}return{models:[...t.values()].sort(),providers:[...n.values()].sort()}}function W_(){return window.location.hash.replace(/^#\/?/,``)===`logs/debug`?`debug`:`logs`}function G_(e){window.location.hash=e===`debug`?`logs/debug`:`logs`}function K_(e){e.key===`ArrowLeft`||e.key===`Home`?(e.preventDefault(),G_(`logs`),document.getElementById(`logs-tab-logs`)?.focus()):(e.key===`ArrowRight`||e.key===`End`)&&(e.preventDefault(),G_(`debug`),document.getElementById(`logs-tab-debug`)?.focus())}function q_(e,t){let n=e?.confirmation;if(!n)return``;let r=n===`downgraded`&&e?.fastDowngradeReason?`: ${e.fastDowngradeReason}`:``;return` (${t(`logs.modelTooltip.tierOutcome.${n}`)}${r})`}function J_(e,t){return[`${t(`logs.modelTooltip.model`)}=${e.model}`,e.resolvedModel?`${t(`logs.modelTooltip.resolvedModel`)}=${e.resolvedModel}`:void 0,e.requestedServiceTier?`${t(`logs.modelTooltip.requestedTier`)}=${e.requestedServiceTier}`:void 0,e.configuredServiceTier?`${t(`logs.modelTooltip.configuredTier`)}=${e.configuredServiceTier}`:void 0,e.responseServiceTier?`${t(`logs.modelTooltip.responseTier`)}=${e.responseServiceTier}${q_(e.tierOutcome,t)}`:void 0,e.modelSupportsServiceTier===void 0?void 0:`${t(`logs.modelTooltip.supportsTier`)}=${e.modelSupportsServiceTier}`].filter(Boolean).join(` · `)}function Y_(e){return e.requestedSpeedLabel||void 0}var X_=new Intl.NumberFormat(`en-US`,{style:`currency`,currency:`USD`,currencyDisplay:`narrowSymbol`,minimumFractionDigits:4,maximumFractionDigits:4});function Z_(e,t,n,r=!1){if(!Number.isFinite(e)||e<0)return t(`logs.cost.unavailable`);let i=X_.format(e);return t(r?`logs.cost.lowerBound`:`logs.cost.approximate`,{amount:i})}function Q_(e,t,n){return!e||e.kind===`unavailable`?t(`logs.cost.unavailable`):Z_(e.estimate.cost.total,t,n,e.estimate.priorityLowerBound)}function $_(e){let t=0,n=!0,r=0,i=0,a=0;for(let o of e){if(o.usageStatus===`unsupported`){a+=1;continue}let e=o.displayMetrics?.cost;if(e?.kind===`value`){let i=e.estimate.cost.total;if(Number.isFinite(i)&&i>=0){t+=i,r+=1,n&&=e.estimate.priorityLowerBound===!0;continue}}i+=1}return{estimatedCostUsd:t,priorityLowerBound:r>0&&n,unpricedRequests:i,unmeteredRequests:a}}function ev(e){return e===`cursor`||e.startsWith(`cursor-`)}function tv(e){let t=e.usage;if(!t)return{};let n=typeof t.cacheCreationInputTokens==`number`?t.cacheCreationInputTokens:void 0;return{read:typeof t.cacheReadInputTokens==`number`?t.cacheReadInputTokens:typeof t.cachedInputTokens==`number`&&n!==void 0?Math.max(0,t.cachedInputTokens-n):t.cachedInputTokens,write:n}}function nv(e,t){if(!e.usage)return;let n=tv(e),r=[`${t(`logs.tokens.input`)}=${e.usage.inputTokens}`,`${t(`logs.tokens.output`)}=${e.usage.outputTokens}`];return n.read!==void 0&&r.push(`${t(`logs.tokens.cacheRead`)}=${n.read}`),n.write!==void 0&&r.push(`${t(`logs.tokens.cacheWrite`)}=${n.write}`),typeof e.usage.contextTotalTokens==`number`&&r.push(`${t(`logs.tokens.contextTotal`)}=${e.usage.contextTotalTokens}`),typeof e.usage.reasoningOutputTokens==`number`&&r.push(`${t(`logs.tokens.reasoning`)}=${e.usage.reasoningOutputTokens}`),e.usageStatus===`estimated`&&r.push(t(`logs.tokens.estimatedNote`)),e.usageStatus===`estimated`&&n.read===void 0&&n.write===void 0&&r.push(t(ev(e.provider)?`logs.tokens.noCacheCursorNote`:`logs.tokens.noCacheNote`)),r.join(` · `)}function rv(e){return e===void 0||typeof e==`string`}function iv(e){if(e===void 0)return!0;if(!e||typeof e!=`object`||!rv(e.routeKind)||e.profile!==void 0&&(!e.profile||typeof e.profile!=`object`||!rv(e.profile.id)||!rv(e.profile.revision))||e.selected!==void 0&&(!e.selected||typeof e.selected!=`object`||!rv(e.selected.provider)||!rv(e.selected.model)||!rv(e.selected.reason)))return!1;if(e.candidates===void 0)return!0;if(!Array.isArray(e.candidates))return!1;for(let t of e.candidates){if(!t||typeof t!=`object`||!rv(t.provider)||!rv(t.model)||t.eligible!==void 0&&typeof t.eligible!=`boolean`)return!1;if(t.exclusions!==void 0){if(!Array.isArray(t.exclusions))return!1;for(let e of t.exclusions)if(!e||typeof e!=`object`||!rv(e.code))return!1}}return!0}function av(e){if(e.routeDecision===void 0||iv(e.routeDecision))return e;let t={...e};return delete t.routeDecision,t}function ov(e){if(Array.isArray(e))return{rows:e,cursor:null,reset:!1};if(!e||typeof e!=`object`)throw Error(`Invalid log response`);let t=e,n=Object.hasOwn(t,`cursor`)||Object.hasOwn(t,`reset`);if(t.logs!==void 0&&!Array.isArray(t.logs)||n&&(!Array.isArray(t.logs)||typeof t.cursor!=`string`||t.cursor.length===0||t.cursor.length>512||!/^[A-Za-z0-9_-]+$/.test(t.cursor)||typeof t.reset!=`boolean`))throw Error(`Invalid log response`);return{rows:t.logs??[],cursor:n?t.cursor:null,reset:t.reset===!0,generatedAt:t.generatedAt,...typeof t.timeZone==`string`?{timeZone:t.timeZone}:{},...typeof t.total==`number`&&Number.isFinite(t.total)&&t.total>=0?{total:t.total}:{}}}function sv(e,t,n=2e3){if(t.length===0&&e.length<=n)return e;let r=[...e,...t];return r.length>n?r.slice(r.length-n):r}function cv(e){return`ocx.logs.list.v1:${e}`}var lv=[];function uv(e){if(!Array.isArray(e))return null;for(let t of e)if(!t||typeof t!=`object`||typeof t.timestamp!=`number`||typeof t.model!=`string`||typeof t.provider!=`string`||typeof t.status!=`number`||typeof t.durationMs!=`number`||t.shadowCallRewrittenFrom!==void 0&&typeof t.shadowCallRewrittenFrom!=`string`||!iv(t.routeDecision))return null;return e}function dv(e){if(!e.usage)return typeof e.totalTokens==`number`?e.totalTokens:void 0;let t=e.usage.inputTokens+e.usage.outputTokens,n=e.usage.totalTokens??e.totalTokens;return typeof n==`number`?Math.max(n,t):t}function fv(e){let t=dv(e),n=e.usage?.contextTotalTokens;return typeof n==`number`?Math.max(t??0,n)||void 0:t}function pv(e){let t=e.requestedEffort?.replace(/\s*->\s*/g,` → `),n=e.effectiveEffort;return t?!n||t===n||t.split(` → `).at(-1)===n?t:`${t} → ${n}`:n??`-`}function mv(e){if(!(!e.reasoningWireField||e.reasoningWireValue===void 0))return`${e.reasoningWireField}=${e.reasoningWireValue}`}function hv(e,t){if(!e||e.kind===`unavailable`||!Number.isFinite(e.value)||e.value<=0)return`—`;let n=e.value>=100?0:1,r=new Intl.NumberFormat(t,{minimumFractionDigits:n,maximumFractionDigits:n}).format(e.value);return`${e.estimated?`~`:``}${r}`}var gv=2e3,_v=3e4,vv=4,yv=3,bv={usage_missing:`logs.detail.reason.usage_missing`,usage_unsupported:`logs.detail.reason.usage_unsupported`,output_missing:`logs.detail.reason.output_missing`,invalid_duration:`logs.detail.reason.invalid_duration`,price_unmatched:`logs.detail.reason.price_unmatched`,invalid_cache_breakdown:`logs.detail.reason.invalid_cache_breakdown`,invalid_usage:`logs.detail.reason.invalid_usage`,combo_attempt_unavailable:`logs.detail.reason.combo_attempt_unavailable`,ttft_missing:`logs.detail.reason.ttft_missing`,decode_window_too_short:`logs.detail.reason.decode_window_too_short`},xv={usage_estimated:`logs.detail.estimate.usage_estimated`,cache_detail_missing:`logs.detail.estimate.cache_detail_missing`,expected_price_overlay:`logs.detail.estimate.expected_price_overlay`,provider_cost_overlay:`logs.detail.estimate.provider_cost_overlay`,priority_lower_bound:`logs.detail.estimate.priority_lower_bound`},Sv={"transient-5xx":`logs.detail.attempt.recovery.transient5xx`,"connection-reset":`logs.detail.attempt.recovery.connectionReset`,"oauth-401":`logs.detail.attempt.recovery.oauth401`,"key-429":`logs.detail.attempt.recovery.key429`,"rate-limit-429":`logs.detail.attempt.recovery.rateLimit429`,"anthropic-oauth-429":`logs.detail.attempt.recovery.anthropicOauth429`,"image-413":`logs.detail.attempt.recovery.image413`,"empty-completion":`logs.detail.attempt.recovery.emptyCompletion`,"console-go-upload-retry":`logs.detail.attempt.recovery.consoleGoUpload`};function Cv(e){return bv[e]}function wv(e){return xv[e]}function Tv(e){return Sv[e]??`logs.detail.attempt.recovery.unknown`}function Ev(e){return e===`verified`?`logs.detail.verification.verified`:`logs.detail.verification.derived`}function Dv(e){return e>=200&&e<300?`var(--green)`:e>=400?`var(--red)`:`var(--amber)`}function Ov(e,t,n){let r=n?{timeZone:n}:void 0;try{return{date:new Date(e).toLocaleDateString(t,r),time:new Date(e).toLocaleTimeString(t,r)}}catch{return{date:new Date(e).toLocaleDateString(t),time:new Date(e).toLocaleTimeString(t)}}}function kv(e,t,n){let{date:r,time:i}=Ov(e,t,n);return`${r} ${i}`}function Av(e){let t=0;for(let n of e){let e=dv(n);e!==void 0&&(t+=e)}return{requests:e.length,totalTokens:t,...$_(e)}}function jv({apiBase:e}){let{t,locale:n}=ut(),r=cv(e),i=uv(Tr(r)),[a,o]=(0,_.useState)(!0),[s,c]=(0,_.useState)({error:null,count:0}),[l,u]=(0,_.useState)(null),[d,f]=(0,_.useState)(I_),[p,m]=(0,_.useState)(()=>Date.now()),h=(0,_.useRef)({key:r,active:!1,request:0}),g=(0,_.useRef)({key:r,cursor:null,rows:[]});(0,_.useLayoutEffect)(()=>{let e={key:r,active:!0,request:0};return h.current=e,g.current={key:r,cursor:null,rows:[]},m(Date.now()),()=>{e.active=!1}},[r]);let v=(0,_.useCallback)(()=>{let e=h.current;return P_(e.key===r?e.anchor:void 0,performance.now(),Date.now())},[r]),y=(0,_.useRef)(null),b=(0,_.useRef)({key:r,failures:0,nextAttemptAt:0,error:null}),x=nt.find(e=>e.code===n)?.htmlLang,[S,C]=(0,_.useState)();(0,_.useEffect)(()=>{let t=new AbortController,n=!1;return fetch(`${e}/api/settings`,{signal:t.signal}).then(e=>e.ok?e.json():null).then(e=>{n||!e||typeof e.timeZone==`string`&&e.timeZone.trim()&&C(e.timeZone.trim())}).catch(()=>{}),()=>{n=!0,t.abort()}},[e]);let[w,T]=(0,_.useState)(W_),[E,D]=(0,_.useState)(()=>W_()===`debug`);(0,_.useEffect)(()=>{let e=()=>T(W_());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]),(0,_.useEffect)(()=>{w===`debug`&&D(!0)},[w]);let O=G_,k=(0,_.useCallback)(async t=>{let n=h.current;if(t.aborted||!n.active||n.key!==r)throw t.reason??new DOMException(`Obsolete log request`,`AbortError`);let i=++n.request,a=()=>!t.aborted&&n.active&&h.current===n&&n.request===i,o=b.current;if(o.key!==r&&(o={key:r,failures:0,nextAttemptAt:0,error:null},b.current=o),o.failures>0&&Date.now()<o.nextAttemptAt)throw o.error;let s=g.current,c=s.key===r?s.cursor:null,l=`${e}/api/logs?limit=2000${c?`&cursor=${encodeURIComponent(c)}`:``}`;try{let e=await fetch(l,{signal:t});if(!e.ok)throw Error(`${e.status} ${e.statusText}`.trim());let i=await e.json(),o=performance.now(),u=ov(i),d=u.rows.map(av),p=c&&u.cursor&&!u.reset?sv(s.rows,d):d;if(!a())throw t.reason??new DOMException(`Obsolete log request`,`AbortError`);g.current={key:r,cursor:u.cursor,rows:p};let h=U_(p);f(e=>{let t=e.model.trim().toLowerCase(),n=e.provider.trim().toLowerCase(),r=t?h.models.find(e=>e.trim().toLowerCase()===t)??``:``,i=n?h.providers.find(e=>e.trim().toLowerCase()===n)??``:``;return e.model===r&&e.provider===i?e:{...e,model:r,provider:i}});let _=N_(u.generatedAt,o);return _&&(n.anchor=_),m(P_(n.anchor,o,Date.now())),b.current={key:r,failures:0,nextAttemptAt:0,error:null},kr(r,p),p}catch(e){if(!a())throw e;let t=e??Error(`log request failed`),n=o.failures+1,i=gv*2**Math.min(n,vv);throw b.current={key:r,failures:n,nextAttemptAt:Date.now()+i,error:t},t}},[e,r]),A=jr(r,[e],k,{isEmpty:e=>e.length===0,enabled:w===`logs`,pollMs:a?gv:void 0,initialData:i??void 0}),j=A.state,M=j.data??i??lv,N=A.refresh,P=(0,_.useCallback)(()=>{b.current={key:r,failures:0,nextAttemptAt:0,error:null},g.current={key:r,cursor:null,rows:[]},N({forceLoading:!0})},[N,r]),F=!A.refreshing&&j.showError;!A.refreshing&&!j.showError&&j.data!==void 0&&s.count!==0?c({error:null,count:0}):F&&s.error!==j.error&&c(e=>({error:j.error,count:e.count+1}));let I=s.count>=yv||!a&&F,L=l?v_(l.status,n):null,R=d.conversationId.trim();(0,_.useEffect)(()=>{if(d.timeWindow===`all`||w!==`logs`)return;m(v());let e=window.setInterval(()=>m(v()),_v);return()=>window.clearInterval(e)},[d.timeWindow,w,v]),(0,_.useEffect)(()=>{let e=!1;if(!R){f(e=>e.conversationQueryHash===void 0?e:{...e,conversationQueryHash:void 0});return}return p_(R).then(t=>{e||f(e=>e.conversationQueryHash===t?e:{...e,conversationQueryHash:t})}),()=>{e=!0}},[R]);let z=(0,_.useMemo)(()=>U_(M),[M]),B=L_(d),V=(0,_.useMemo)(()=>V_(M,d,p),[M,d,p]),H=R?Av(V):null,U=l_({count:V.length,getScrollElement:()=>y.current,estimateSize:()=>92,overscan:15,getItemKey:e=>{let t=V[V.length-1-e];return t.requestId??`${t.timestamp}:${t.model}:${t.provider}`}}),W=U.getVirtualItems(),G=W.length>0?W[0].start:0,K=W.length>0?U.getTotalSize()-W[W.length-1].end:0;return(0,Y.jsxs)(`div`,{className:`logs-page`,children:[(0,Y.jsxs)(`div`,{className:`page-head`,children:[(0,Y.jsx)(`h2`,{children:t(`nav.logs`)}),w===`logs`&&(0,Y.jsxs)(`label`,{className:`muted text-control logs-auto-refresh`,children:[(0,Y.jsx)(`input`,{type:`checkbox`,checked:a,onChange:e=>o(e.target.checked)}),t(`logs.autoRefresh`)]})]}),(0,Y.jsxs)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":t(`nav.logs`),children:[(0,Y.jsx)(`button`,{type:`button`,role:`tab`,id:`logs-tab-logs`,"aria-selected":w===`logs`,"aria-controls":`logs-panel-logs`,tabIndex:w===`logs`?0:-1,className:`page-tab${w===`logs`?` page-tab--active`:``}`,onClick:()=>O(`logs`),onKeyDown:K_,children:t(`logs.tabLogs`)}),(0,Y.jsx)(`button`,{type:`button`,role:`tab`,id:`logs-tab-debug`,"aria-selected":w===`debug`,"aria-controls":`logs-panel-debug`,tabIndex:w===`debug`?0:-1,className:`page-tab${w===`debug`?` page-tab--active`:``}`,onClick:()=>O(`debug`),onKeyDown:K_,children:t(`logs.tabDebug`)})]}),E&&(0,Y.jsx)(`div`,{role:`tabpanel`,id:`logs-panel-debug`,"aria-labelledby":`logs-tab-debug`,hidden:w!==`debug`,children:(0,Y.jsx)(k_,{apiBase:e,embedded:!0,active:w===`debug`})}),(0,Y.jsxs)(`div`,{role:`tabpanel`,id:`logs-panel-logs`,"aria-labelledby":`logs-tab-logs`,hidden:w!==`logs`,children:[(0,Y.jsx)(M_,{filters:d,options:z,hasActiveFilters:B,filteredCount:V.length,totalCount:M.length,t,onFilterChange:f,onResetFilters:()=>f(I_)}),H&&(0,Y.jsx)(`div`,{className:`logs-conversation-totals`,children:(0,Y.jsxs)($,{tone:`ok`,children:[t(`logs.conversation.totals`,{requests:H.requests,tokens:Wn(H.totalTokens,x??n),cost:Z_(H.estimatedCostUsd,t,x,H.priorityLowerBound)}),` `,(0,Y.jsxs)(`span`,{className:`muted`,children:[t(`logs.conversation.scope`),H.unpricedRequests+H.unmeteredRequests>0?` ${t(`logs.conversation.excluded`,{unpriced:H.unpricedRequests,unmetered:H.unmeteredRequests})}`:``]})]})}),j.kind===`failed-cold`&&(0,Y.jsxs)($,{tone:`err`,children:[j.error instanceof Error?`${t(`logs.loadError`)} ${j.error.message}`:t(`logs.loadError`),` `,(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:P,disabled:j.refreshing,children:t(`common.retry`)})]}),I&&M.length>0&&(0,Y.jsxs)($,{tone:`err`,children:[t(`logs.loadError`),` `,(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:P,disabled:A.refreshing,children:t(`common.retry`)})]}),j.kind===`failed-cold`?null:j.showSkeleton&&M.length===0?(0,Y.jsx)(ep,{label:t(`common.loading`),rows:6}):V.length===0?(0,Y.jsx)(At,{title:M.length>0&&B?t(`logs.noMatchingRequests`):t(`logs.noRequests`)}):(0,Y.jsx)(Y.Fragment,{children:(0,Y.jsx)(`div`,{ref:y,className:`tbl-wrap logs-table-wrap`,children:(0,Y.jsxs)(`table`,{className:`tbl logs-table`,children:[(0,Y.jsxs)(`colgroup`,{children:[(0,Y.jsx)(`col`,{className:`logs-col-time`}),(0,Y.jsx)(`col`,{className:`logs-col-tokens`}),(0,Y.jsx)(`col`,{className:`logs-col-rate`}),(0,Y.jsx)(`col`,{className:`logs-col-cost`}),(0,Y.jsx)(`col`,{className:`logs-col-model`}),(0,Y.jsx)(`col`,{className:`logs-col-effort`}),(0,Y.jsx)(`col`,{className:`logs-col-provider`}),(0,Y.jsx)(`col`,{className:`logs-col-status`}),(0,Y.jsx)(`col`,{className:`logs-col-request`}),(0,Y.jsx)(`col`,{className:`logs-col-duration`})]}),(0,Y.jsx)(`thead`,{children:(0,Y.jsxs)(`tr`,{children:[(0,Y.jsx)(`th`,{children:t(`logs.col.time`)}),(0,Y.jsx)(`th`,{className:`num log-col-tokens`,children:t(`logs.col.tokens`)}),(0,Y.jsx)(`th`,{className:`num log-col-rate`,title:t(`logs.metric.tokPerSecTitle`),children:t(`logs.col.tokPerSec`)}),(0,Y.jsx)(`th`,{className:`num log-col-cost`,title:t(`logs.metric.estimatedCostTitle`),children:t(`logs.col.estimatedCost`)}),(0,Y.jsx)(`th`,{className:`log-col-model`,children:t(`logs.col.model`)}),(0,Y.jsx)(`th`,{children:t(`logs.col.effort`)}),(0,Y.jsx)(`th`,{children:t(`logs.col.provider`)}),(0,Y.jsx)(`th`,{children:t(`logs.col.status`)}),(0,Y.jsx)(`th`,{children:t(`logs.col.request`)}),(0,Y.jsx)(`th`,{className:`num log-col-duration`,children:t(`logs.col.duration`)})]})}),(0,Y.jsxs)(`tbody`,{children:[G>0&&(0,Y.jsx)(`tr`,{children:(0,Y.jsx)(`td`,{colSpan:10,className:`logs-virtual-spacer`,style:{height:G}})}),W.map(e=>{let r=V[V.length-1-e.index],i=mv(r),a=Ov(r.timestamp,x,S);return(0,Y.jsxs)(`tr`,{"data-index":e.index,ref:U.measureElement,children:[(0,Y.jsx)(`td`,{className:`muted mono log-col-time`,children:(0,Y.jsxs)(`span`,{className:`logs-stack-start`,children:[(0,Y.jsx)(`span`,{children:a.date}),(0,Y.jsx)(`span`,{children:a.time})]})}),(0,Y.jsx)(`td`,{className:`num mono log-col-tokens`,title:nv(r,t),children:(()=>{let e=fv(r),{read:i,write:a}=tv(r);return e===void 0?(0,Y.jsx)(`span`,{className:`muted`,children:t(`logs.tokens.${r.usageStatus??`unreported`}`)}):(0,Y.jsxs)(`span`,{className:`logs-stack-end`,children:[(0,Y.jsxs)(`span`,{children:[r.usageStatus===`estimated`?`~`:``,Wn(e,n)]}),i!==void 0&&i>0&&(0,Y.jsxs)(`span`,{className:`muted text-caption leading-tight`,children:[`c `,Wn(i,n)]}),a!==void 0&&a>0&&(0,Y.jsxs)(`span`,{className:`muted text-caption leading-tight`,children:[`w `,Wn(a,n)]}),r.usageStatus===`estimated`&&i===void 0&&a===void 0&&(0,Y.jsx)(`span`,{className:`muted text-caption leading-tight`,children:t(ev(r.provider)?`logs.tokens.noCacheCursor`:`logs.tokens.noCache`)})]})})()}),(0,Y.jsxs)(`td`,{className:`num mono log-col-rate`,children:[hv(r.displayMetrics?.tokPerSecond,x),r.displayMetrics?.decodeTokPerSecond?.kind===`value`&&(0,Y.jsx)(`span`,{className:`logs-stack-end muted`,title:t(`logs.detail.decodeTokPerSec`),children:hv(r.displayMetrics.decodeTokPerSecond,x)})]}),(0,Y.jsx)(`td`,{className:`num mono log-col-cost`,children:Q_(r.displayMetrics?.cost,t,x)}),(0,Y.jsx)(`td`,{className:`mono log-col-model`,title:J_(r,t),children:(0,Y.jsxs)(`span`,{className:`logs-model-cell`,children:[(0,Y.jsx)(`span`,{children:tf(r.resolvedModel??r.model)}),r.shadowCallRewrittenFrom&&(0,Y.jsx)(`span`,{className:`badge badge-muted`,style:{whiteSpace:`nowrap`},title:t(`logs.badge.interceptedHelperTitle`),children:t(`logs.badge.interceptedHelper`,{model:r.shadowCallRewrittenFrom})}),(r.surface===`claude`||r.surface===`claude-desktop`)&&(0,Y.jsx)(`span`,{className:`badge badge-accent`,children:t(`logs.badge.claude`)}),r.surface===`grok`&&(0,Y.jsx)(`span`,{className:`badge badge-accent`,children:t(`logs.badge.grok`)}),Y_(r)&&(0,Y.jsx)(`span`,{className:`badge badge-amber`,children:Y_(r)})]})}),(0,Y.jsx)(`td`,{className:`mono log-reasoning-cell`,title:i,children:pv(r)}),(0,Y.jsx)(`td`,{className:`muted`,children:Ln(r.provider,t)}),(0,Y.jsx)(`td`,{children:(0,Y.jsxs)(`span`,{className:`log-status-cell`,children:[(0,Y.jsx)(`span`,{className:`mono font-semibold`,style:{color:Dv(r.status)},children:r.status}),(0,Y.jsx)(`button`,{type:`button`,className:`log-detail-btn`,onClick:()=>u(r),"aria-label":`${t(`logs.details`)}: ${r.requestId??r.status}`,children:t(`logs.details`)})]})}),(0,Y.jsx)(`td`,{className:`muted mono`,children:(0,Y.jsx)(`span`,{className:`log-reqid`,title:r.requestId,children:r.requestId??`-`})}),(0,Y.jsxs)(`td`,{className:`num log-col-duration`,children:[r.durationMs,`ms`]})]},e.key)}),K>0&&(0,Y.jsx)(`tr`,{children:(0,Y.jsx)(`td`,{colSpan:10,className:`logs-virtual-spacer`,style:{height:K}})})]})]})})}),l&&(0,Y.jsx)(Nv,{detail:l,detailInfo:L,localeCode:n,localeTag:x,serverTimeZone:S,t,onClose:()=>u(null),onFilterConversation:e=>{f(t=>({...t,conversationId:e})),u(null)}})]})]})}function Mv(e){let t=(0,_.useRef)(null);return(0,_.useEffect)(()=>{let n=t.current;n&&(e&&!n.open?n.showModal():!e&&n.open&&n.close())},[e]),t}function Nv({detail:e,detailInfo:t,localeCode:n,localeTag:r,serverTimeZone:i,t:a,onClose:o,onFilterConversation:s}){let c=Mv(!0),[l,u]=(0,_.useState)(!1),d=tv(e),f=e.displayMetrics?.cost,p=mv(e),m=async()=>{if(e.requestId)try{await navigator.clipboard.writeText(e.requestId),u(!0),window.setTimeout(()=>u(!1),1200)}catch{}};return(0,Y.jsxs)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":`log-detail-title`,onCancel:e=>{e.preventDefault(),o()},children:[(0,Y.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":a(`common.close`),tabIndex:-1,onClick:o}),(0,Y.jsxs)(`div`,{className:`modal-card log-detail-card`,onClick:e=>e.stopPropagation(),role:`document`,children:[(0,Y.jsxs)(`div`,{className:`modal-head`,children:[(0,Y.jsxs)(`h3`,{id:`log-detail-title`,children:[(0,Y.jsx)(`span`,{className:`mono`,style:{color:Dv(e.status)},children:e.status}),t&&(0,Y.jsx)(`span`,{className:`logs-detail-info`,children:t.label})]}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:o,"aria-label":a(`common.cancel`),children:(0,Y.jsx)(le,{})})]}),t&&(0,Y.jsx)(`p`,{className:`modal-desc`,children:t.description}),(0,Y.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-basic`,children:[(0,Y.jsx)(`h4`,{id:`log-detail-basic`,className:`log-detail-section-title`,children:a(`logs.detail.section.basic`)}),(0,Y.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,Y.jsx)(`span`,{className:`muted`,children:a(`logs.col.time`)}),(0,Y.jsx)(`span`,{className:`mono`,children:kv(e.timestamp,r,i)}),(0,Y.jsx)(`span`,{className:`muted`,children:a(`logs.col.request`)}),(0,Y.jsxs)(`span`,{className:`log-detail-request-row`,children:[(0,Y.jsx)(`span`,{className:`mono log-detail-break`,children:e.requestId??`—`}),e.requestId&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void m(),children:a(l?`logs.detail.copied`:`logs.detail.copyRequestId`)})]}),e.conversationId&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`span`,{className:`muted`,children:a(`logs.detail.conversation`)}),(0,Y.jsxs)(`span`,{className:`log-detail-request-row`,children:[(0,Y.jsx)(`span`,{className:`mono log-detail-break`,children:e.conversationId}),s&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>s(e.conversationId),children:a(`logs.filter.conversation.apply`)})]})]}),(0,Y.jsx)(`span`,{className:`muted`,children:a(`logs.col.model`)}),(0,Y.jsx)(`span`,{className:`mono`,children:tf(e.resolvedModel??e.model)}),(0,Y.jsx)(`span`,{className:`muted`,children:a(`logs.col.provider`)}),(0,Y.jsx)(`span`,{children:Ln(e.provider,a)}),(e.requestedEffort||e.effectiveEffort)&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`span`,{className:`muted`,children:a(`logs.col.effort`)}),(0,Y.jsxs)(`span`,{className:`mono`,children:[pv(e),p?` (${p})`:``]})]}),e.errorCode&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`span`,{className:`muted`,children:a(`logs.col.error`)}),(0,Y.jsx)(`span`,{className:`mono`,children:e.errorCode})]}),e.upstreamError&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`span`,{className:`muted`,children:a(`logs.col.upstreamReason`)}),(0,Y.jsx)(`span`,{className:`mono log-detail-break`,children:e.upstreamError})]})]})]}),(0,Y.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-route`,children:[(0,Y.jsx)(`h4`,{id:`log-detail-route`,className:`log-detail-section-title`,children:a(`logs.detail.route.section`)}),e.routeDecision?(0,Y.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,Y.jsx)(`span`,{className:`muted`,children:a(`logs.detail.route.kind`)}),(0,Y.jsx)(`span`,{className:`mono`,children:e.routeDecision.routeKind??`–`}),e.routeDecision.profile?.id&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`span`,{className:`muted`,children:a(`logs.detail.route.profile`)}),(0,Y.jsxs)(`span`,{className:`mono`,children:[e.routeDecision.profile.id,` (`,e.routeDecision.profile.revision,`)`]})]}),e.routeDecision.selected?.provider&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`span`,{className:`muted`,children:a(`logs.detail.route.selected`)}),(0,Y.jsxs)(`span`,{className:`mono`,children:[e.routeDecision.selected.provider,`/`,e.routeDecision.selected.model,e.routeDecision.selected.reason?` — ${e.routeDecision.selected.reason}`:``]})]}),(0,Y.jsx)(`span`,{className:`muted`,children:a(`logs.detail.route.candidates`)}),(0,Y.jsx)(`span`,{className:`mono`,children:(e.routeDecision.candidates??[]).map(e=>`${typeof e.provider==`string`&&e.provider.length>0?e.provider:`–`}/${typeof e.model==`string`&&e.model.length>0?e.model:`–`}${e.eligible===!0?` ✓`:e.eligible===!1?` ✗`:` ?`}`).join(` `)||`–`})]}):(0,Y.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`logs.detail.route.unknown`)})]}),(0,Y.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-performance`,children:[(0,Y.jsx)(`h4`,{id:`log-detail-performance`,className:`log-detail-section-title`,children:a(`logs.detail.section.performance`)}),(0,Y.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,Y.jsx)(`span`,{className:`muted`,children:a(`logs.col.duration`)}),(0,Y.jsxs)(`span`,{className:`mono`,children:[e.durationMs,`ms`]}),(0,Y.jsx)(`span`,{className:`muted`,children:a(`logs.col.tokPerSec`)}),(0,Y.jsx)(`span`,{className:`mono`,children:hv(e.displayMetrics?.tokPerSecond,r)}),e.displayMetrics?.decodeTokPerSecond?.kind===`value`&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`span`,{className:`muted`,children:a(`logs.detail.decodeTokPerSec`)}),(0,Y.jsx)(`span`,{className:`mono`,children:hv(e.displayMetrics.decodeTokPerSecond,r)})]}),e.firstOutputMs!==void 0&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`span`,{className:`muted`,children:a(`logs.detail.ttft`)}),(0,Y.jsxs)(`span`,{className:`mono`,children:[e.firstOutputMs,`ms`]})]})]}),e.displayMetrics?.tokPerSecond.kind===`unavailable`&&(0,Y.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(Cv(e.displayMetrics.tokPerSecond.reason))}),e.displayMetrics?.decodeTokPerSecond?.kind===`unavailable`&&(0,Y.jsxs)(`p`,{className:`log-detail-notes-line muted`,children:[a(`logs.detail.decodeTokPerSec`),`: `,a(Cv(e.displayMetrics.decodeTokPerSecond.reason))]})]}),(0,Y.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-cost`,children:[(0,Y.jsx)(`h4`,{id:`log-detail-cost`,className:`log-detail-section-title`,children:a(`logs.detail.section.cost`)}),(0,Y.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`usage.cost.disclaimer`)}),f?.kind===`value`?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,Y.jsx)(`span`,{className:`muted`,children:a(`logs.detail.costTotal`)}),(0,Y.jsx)(`span`,{className:`mono`,children:Z_(f.estimate.cost.total,a,r,f.estimate.priorityLowerBound)}),(0,Y.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.input`)}),(0,Y.jsx)(`span`,{className:`mono`,children:Z_(f.estimate.cost.input,a,r,f.estimate.priorityLowerBound)}),(0,Y.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheRead`)}),(0,Y.jsx)(`span`,{className:`mono`,children:Z_(f.estimate.cost.cacheRead,a,r,f.estimate.priorityLowerBound)}),(0,Y.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheWrite`)}),(0,Y.jsx)(`span`,{className:`mono`,children:Z_(f.estimate.cost.cacheWrite,a,r,f.estimate.priorityLowerBound)}),(0,Y.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.output`)}),(0,Y.jsx)(`span`,{className:`mono`,children:Z_(f.estimate.cost.output,a,r,f.estimate.priorityLowerBound)}),f.estimate.price&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`span`,{className:`muted`,children:a(`logs.detail.matchedKey`)}),(0,Y.jsxs)(`span`,{className:`mono log-detail-break`,children:[f.estimate.price.jawcodeProvider??f.estimate.price.provider,`/`,f.estimate.price.modelId]}),(0,Y.jsx)(`span`,{className:`muted`,children:a(`logs.detail.priceSource`)}),(0,Y.jsxs)(`span`,{children:[a(`logs.detail.source.${f.estimate.price.source}`),` · `,a(Ev(f.estimate.price.status))]})]})]}),f.estimateReasons.length>0&&(0,Y.jsx)(`ul`,{className:`log-detail-notes`,children:f.estimateReasons.map(e=>(0,Y.jsx)(`li`,{children:a(wv(e))},e))})]}):(0,Y.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,Y.jsx)(`span`,{className:`muted`,children:a(`logs.detail.costTotal`)}),(0,Y.jsx)(`span`,{className:`mono`,children:a(`logs.cost.unavailable`)}),(0,Y.jsx)(`span`,{className:`muted`,children:a(`logs.detail.unavailableReason`)}),(0,Y.jsx)(`span`,{children:f?.kind===`unavailable`?a(Cv(f.reason)):a(`logs.detail.reason.usage_missing`)})]})]}),e.attempts?.length?(0,Y.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-attempts`,children:[(0,Y.jsx)(`h4`,{id:`log-detail-attempts`,className:`log-detail-section-title`,children:a(`logs.detail.section.attempts`)}),(0,Y.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`logs.detail.attempt.e2eNote`)}),(0,Y.jsx)(`div`,{className:`log-detail-attempts-wrap`,children:(0,Y.jsxs)(`table`,{className:`tbl log-detail-attempts`,children:[(0,Y.jsx)(`thead`,{children:(0,Y.jsxs)(`tr`,{children:[(0,Y.jsx)(`th`,{className:`num`,children:`#`}),(0,Y.jsx)(`th`,{children:a(`logs.detail.attempt.target`)}),(0,Y.jsx)(`th`,{className:`num`,children:a(`logs.col.duration`)}),(0,Y.jsx)(`th`,{className:`num`,children:a(`logs.col.tokPerSec`)}),(0,Y.jsx)(`th`,{className:`num`,children:a(`logs.col.estimatedCost`)}),(0,Y.jsx)(`th`,{children:a(`logs.detail.attempt.reason`)})]})}),(0,Y.jsx)(`tbody`,{children:e.attempts.toSorted((e,t)=>e.ordinal-t.ordinal).map(e=>{let t=e.displayMetrics?.cost,n=mv(e),i=t?.kind===`value`?t.estimate.price:void 0,o=e.errorCode??(e.recoveryKinds.length?e.recoveryKinds.map(e=>a(Tv(e))).join(`, `):void 0)??(t?.kind===`unavailable`?a(Cv(t.reason)):a(`logs.detail.attempt.completed`));return(0,Y.jsxs)(`tr`,{children:[(0,Y.jsx)(`td`,{className:`num mono`,children:e.ordinal}),(0,Y.jsxs)(`td`,{children:[(0,Y.jsx)(`span`,{children:Ln(e.provider,a)}),(0,Y.jsx)(`br`,{}),(0,Y.jsx)(`span`,{className:`mono muted log-detail-break`,children:e.model}),(e.requestedEffort||e.effectiveEffort)&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`br`,{}),(0,Y.jsxs)(`span`,{className:`mono muted text-caption log-detail-break`,children:[pv(e),n?` (${n})`:``]})]}),i&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`br`,{}),(0,Y.jsxs)(`span`,{className:`muted text-caption log-detail-break`,children:[i.jawcodeProvider??i.provider,`/`,i.modelId,` · `,a(`logs.detail.source.${i.source}`),` · `,a(Ev(i.status))]})]})]}),(0,Y.jsxs)(`td`,{className:`num mono`,children:[e.durationMs,`ms`]}),(0,Y.jsxs)(`td`,{className:`num mono`,children:[hv(e.displayMetrics?.tokPerSecond,r),e.displayMetrics?.decodeTokPerSecond?.kind===`value`&&(0,Y.jsx)(`span`,{className:`logs-stack-end muted`,title:a(`logs.detail.decodeTokPerSec`),children:hv(e.displayMetrics.decodeTokPerSecond,r)})]}),(0,Y.jsx)(`td`,{className:`num mono`,children:Q_(t,a,r)}),(0,Y.jsx)(`td`,{className:`log-detail-break`,children:o})]},`${e.ordinal}-${e.provider}-${e.model}`)})})]})})]}):null,(0,Y.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-usage`,children:[(0,Y.jsx)(`h4`,{id:`log-detail-usage`,className:`log-detail-section-title`,children:a(`logs.detail.section.usage`)}),(0,Y.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,Y.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.input`)}),(0,Y.jsx)(`span`,{className:`mono`,children:e.usage?Wn(e.usage.inputTokens,n):`—`}),(0,Y.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.output`)}),(0,Y.jsx)(`span`,{className:`mono`,children:e.usage?Wn(e.usage.outputTokens,n):`—`}),(0,Y.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheRead`)}),(0,Y.jsx)(`span`,{className:`mono`,children:d.read===void 0?`—`:Wn(d.read,n)}),(0,Y.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheWrite`)}),(0,Y.jsx)(`span`,{className:`mono`,children:d.write===void 0?`—`:Wn(d.write,n)}),(0,Y.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.reasoning`)}),(0,Y.jsx)(`span`,{className:`mono`,children:e.usage?.reasoningOutputTokens===void 0?`—`:Wn(e.usage.reasoningOutputTokens,n)}),(0,Y.jsx)(`span`,{className:`muted`,children:a(`logs.detail.totalTokens`)}),(0,Y.jsx)(`span`,{className:`mono`,children:fv(e)===void 0?`—`:Wn(fv(e),n)}),e.usage?.contextTotalTokens!==void 0&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.contextTotal`)}),(0,Y.jsx)(`span`,{className:`mono`,children:Wn(e.usage.contextTotalTokens,n)})]})]}),e.usageStatus===`estimated`&&(0,Y.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`logs.tokens.estimatedNote`)})]}),(0,Y.jsxs)(`details`,{className:`log-detail-raw`,children:[(0,Y.jsx)(`summary`,{children:a(`logs.detailRaw`)}),(0,Y.jsx)(`pre`,{className:`log-detail-json`,children:JSON.stringify(e,null,2)})]})]})]})}function Pv(e){let t=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})$/.exec(e);if(!t)return null;let[n,r,i,a,o]=t.slice(1).map(Number),s=new Date(`${e}:00`),c=s.getTime();return!Number.isSafeInteger(c)||c<0||s.getFullYear()!==n||s.getMonth()!==r-1||s.getDate()!==i||s.getHours()!==a||s.getMinutes()!==o?null:c}function Fv(e,t){if(!e||!t)return{ok:!1,error:`required`};let n=Pv(e),r=Pv(t);return n===null||r===null?{ok:!1,error:`invalid`}:n>r?{ok:!1,error:`reversed`}:{ok:!0,window:{since:n,until:r+59999}}}var Iv=class extends Error{};function Lv(e){return`${Math.round(e*100)}%`}function Rv(e,t){let n=`${t}/${e}`,r=0;for(let e=0;e<n.length;e++)r=r*31+n.charCodeAt(e)>>>0;return`hsl(${r%360} 55% 55%)`}function zv(e){let t=new Map(e.map(e=>[e.date,e])),n=[],r=new Date;r.setHours(0,0,0,0),r.setDate(r.getDate()-6);for(let e=0;e<7;e++){let e=`${r.getFullYear()}-${String(r.getMonth()+1).padStart(2,`0`)}-${String(r.getDate()).padStart(2,`0`)}`,i=t.get(e);n.push({date:e,requests:i?.requests??0,measuredRequests:i?.measuredRequests??0,reportedRequests:i?.reportedRequests??0,totalTokens:i?.totalTokens??0,models:i?.models??[]}),r.setDate(r.getDate()+1)}return n}function Bv(e){let t=e.filter(e=>e>0).sort((e,t)=>e-t);if(t.length===0)return[0,0,0,0];let n=e=>t[Math.min(t.length-1,Math.floor(e*t.length))];return[n(.25),n(.5),n(.75),n(.95)]}function Vv(e,t){return e<=0?0:e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4}function Hv(e,t=!1){let n=Bv(e.map(e=>e.totalTokens)),r=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];if(t){let t=[],i=[],a=[],o,s=-1,c=-4,l=e=>{for(;a.length<e;)a.push({date:``,requests:0,totalTokens:0,level:0,dayOfWeek:a.length})};for(let u of e){let[e,d,f]=u.date.split(`-`).map(Number),p=new Date(Date.UTC(e,d-1,f)),m=p.getUTCDay(),h=p.getTime()-m*864e5;o!==h&&(a.length>0&&(l(7),t.push(a)),a=[],o=h);let g=p.getUTCMonth();g!==s&&t.length-c>=4&&(i.push({label:r[g],col:t.length}),s=g,c=t.length),l(m),a.push({date:u.date,requests:u.requests,totalTokens:u.totalTokens,level:Vv(u.totalTokens,n),dayOfWeek:m})}return a.length>0&&(l(7),t.push(a)),{weeks:t,months:i,buckets:n}}let i=new Map(e.map(e=>[e.date,e])),a=new Date;a.setHours(0,0,0,0);let o=new Date(a);o.setDate(o.getDate()-364),o.setDate(o.getDate()-o.getDay());let s=[],c=[],l=-4,u=-1,d=[],f=new Date(o);for(;f<=a;){let e=`${f.getFullYear()}-${String(f.getMonth()+1).padStart(2,`0`)}-${String(f.getDate()).padStart(2,`0`)}`,t=f.getMonth();f.getDay()===0&&t!==u&&s.length-l>=4&&(c.push({label:r[t],col:s.length}),l=s.length,u=t);let a=i.get(e);d.push({date:e,requests:a?.requests??0,totalTokens:a?.totalTokens??0,level:a?Vv(a.totalTokens,n):0,dayOfWeek:f.getDay()}),f.getDay()===6&&(s.push(d),d=[]),f.setDate(f.getDate()+1)}if(d.length>0){for(;d.length<7;)d.push({date:``,requests:0,totalTokens:0,level:0,dayOfWeek:d.length});s.push(d)}return{weeks:s,months:c,buckets:n}}function Uv({surface:e,range:t,onSurface:n,onRange:r,t:i}){return(0,Y.jsxs)(`div`,{className:`usage-filters`,children:[(0,Y.jsx)(`div`,{className:`usage-segmented`,role:`group`,"aria-label":i(`logs.filter.surface.label`),children:[`all`,`codex`,`claude`,`grok`].map(t=>{let r=i(`logs.filter.surface.${t}`);return(0,Y.jsxs)(`button`,{type:`button`,className:`usage-segmented-btn usage-source-btn${e===t?` active`:``}`,"aria-label":r,"aria-pressed":e===t,onClick:()=>n(t),children:[t===`codex`&&(0,Y.jsx)(`img`,{className:`usage-source-mark`,src:`/provider-icons/openai.svg`,alt:``,"aria-hidden":`true`}),t===`claude`&&(0,Y.jsx)(`img`,{className:`usage-source-mark`,src:`/provider-icons/claude-color.svg`,alt:``,"aria-hidden":`true`}),t===`grok`&&(0,Y.jsx)(`img`,{className:`usage-source-mark usage-source-mark--mono`,src:`/provider-icons/grok.svg`,alt:``,"aria-hidden":`true`}),(0,Y.jsx)(`span`,{className:t===`all`?`usage-source-label`:`usage-source-label usage-source-label-collapsible`,children:r})]},t)})}),(0,Y.jsx)(`div`,{className:`usage-segmented`,role:`group`,"aria-label":i(`usage.title`),children:[`all`,`30d`,`7d`].map(e=>{let n=i(e===`all`?`usage.range.available`:`usage.range.${e}`);return(0,Y.jsx)(`button`,{type:`button`,className:`usage-segmented-btn${t===e?` active`:``}`,"aria-label":n,"aria-pressed":t===e,onClick:()=>r(e),children:n},e)})})]})}function Wv({summary:e,activeDays:t,locale:n,t:r}){return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{className:`usage-cards usage-cards-3x2`,role:`group`,"aria-label":r(`usage.title`),children:[(0,Y.jsxs)(`div`,{className:`stat`,children:[(0,Y.jsx)(`div`,{className:`muted`,children:r(`usage.card.requests`)}),(0,Y.jsx)(`div`,{className:`stat-value`,children:e.requests})]}),(0,Y.jsxs)(`div`,{className:`stat`,children:[(0,Y.jsx)(`div`,{className:`muted`,children:r(`usage.card.measured`)}),(0,Y.jsx)(`div`,{className:`stat-value`,children:e.measuredRequests})]}),(0,Y.jsxs)(`div`,{className:`stat`,children:[(0,Y.jsx)(`div`,{className:`muted`,children:r(`usage.card.totalTokens`)}),(0,Y.jsx)(`div`,{className:`stat-value`,children:Wn(e.totalTokens,n)})]}),(0,Y.jsxs)(`div`,{className:`stat`,title:r(`usage.card.cachedTokensHint`),children:[(0,Y.jsx)(`div`,{className:`muted`,children:r(`usage.card.cachedTokens`)}),(0,Y.jsx)(`div`,{className:`stat-value`,children:Wn(e.cacheReadInputTokens??e.cachedInputTokens,n)}),(e.cacheCreationInputTokens??0)>0&&(0,Y.jsxs)(`div`,{className:`muted text-caption`,children:[r(`usage.card.cacheWriteTokens`),`: `,Wn(e.cacheCreationInputTokens??0,n)]})]}),(0,Y.jsxs)(`div`,{className:`stat`,children:[(0,Y.jsx)(`div`,{className:`muted`,children:r(`usage.card.coverage`)}),(0,Y.jsx)(`div`,{className:`stat-value`,children:Lv(e.coverageRatio)})]}),(0,Y.jsxs)(`div`,{className:`stat`,children:[(0,Y.jsx)(`div`,{className:`muted`,children:r(`usage.card.activeDays`)}),(0,Y.jsx)(`div`,{className:`stat-value`,children:t})]})]}),e.estimatedCostUsd!==void 0&&(0,Y.jsxs)(`div`,{className:`usage-cost-row`,role:`note`,children:[(0,Y.jsx)(`span`,{className:`muted`,children:r(`usage.cost.total`)}),(0,Y.jsx)(`span`,{className:`stat-value mono usage-cost-value`,children:zc(e.estimatedCostUsd,n)}),(0,Y.jsx)(`span`,{className:`muted text-caption`,children:r(`usage.cost.disclaimer`)}),(e.unpricedRequests??0)+(e.unmeteredRequests??0)>0&&(0,Y.jsx)(`span`,{className:`muted text-caption`,children:r(`usage.cost.unpricedNote`).replace(`{count}`,String((e.unpricedRequests??0)+(e.unmeteredRequests??0)))})]})]})}function Gv({weekBars:e,locale:t,t:n}){let[r,i]=(0,_.useState)(null),a=Math.max(1,...e.map(e=>e.totalTokens));return(0,Y.jsx)(`div`,{className:`daybars`,role:`img`,"aria-label":n(`usage.section.heatmap`),children:e.map(e=>{let n=Math.round(e.totalTokens/a*100),o=e.date.slice(5);return(0,Y.jsxs)(`div`,{className:`daybar`,onMouseEnter:()=>i(e.date),onMouseLeave:()=>i(t=>t===e.date?null:t),children:[(0,Y.jsx)(`div`,{className:`daybar-track`,children:(0,Y.jsxs)(`div`,{className:`daybar-stack`,style:{"--daybar-scale":String(Math.max(0,Math.min(1,n/100)))},children:[e.models.map(e=>(0,Y.jsx)(`div`,{className:`daybar-seg`,style:{flexGrow:e.totalTokens,background:Rv(e.model,e.provider)}},`${e.provider}/${e.model}`)),e.models.length===0&&e.totalTokens>0&&(0,Y.jsx)(`div`,{className:`daybar-seg`,style:{flexGrow:1,background:`var(--green)`}})]})}),r===e.date&&e.totalTokens>0&&(0,Y.jsxs)(`div`,{className:`daybar-tip`,role:`tooltip`,children:[(0,Y.jsx)(`div`,{className:`daybar-tip-date`,children:e.date}),e.models.slice(0,8).map(e=>(0,Y.jsxs)(`div`,{className:`daybar-tip-row`,children:[(0,Y.jsx)(`span`,{className:`daybar-tip-swatch`,style:{background:Rv(e.model,e.provider)}}),(0,Y.jsx)(`span`,{className:`daybar-tip-name`,children:tf(e.model)}),(0,Y.jsx)(`span`,{className:`daybar-tip-val`,children:Wn(e.totalTokens,t)})]},`${e.provider}/${e.model}`))]}),(0,Y.jsx)(`span`,{className:`daybar-count`,children:Wn(e.totalTokens,t)}),(0,Y.jsx)(`span`,{className:`daybar-label muted`,children:o})]},e.date)})})}function Kv({range:e,heatmap:t,weekBars:n,locale:r,t:i}){let a=(0,_.useRef)(null),[o,s]=(0,_.useState)(null);return(0,_.useEffect)(()=>{let e=a.current;if(!e)return;let t=()=>{e.scrollLeft=e.scrollWidth};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[t,e]),(0,Y.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":`usage-heatmap-title`,children:[(0,Y.jsx)(`h3`,{id:`usage-heatmap-title`,className:`panel-title`,children:i(`usage.section.heatmap`)}),e===`7d`?(0,Y.jsx)(Gv,{weekBars:n,locale:r,t:i}):(0,Y.jsxs)(`div`,{className:`heatmap`,ref:a,role:`img`,"aria-labelledby":`usage-heatmap-title`,children:[(0,Y.jsxs)(`div`,{className:`heatmap-months`,style:{gridTemplateColumns:`28px repeat(${t.weeks.length}, calc(var(--hm-cell) + var(--hm-gap)))`},children:[(0,Y.jsx)(`span`,{className:`heatmap-day-spacer`}),t.months.map(e=>(0,Y.jsx)(`span`,{className:`heatmap-month`,style:{gridColumn:e.col+2},children:e.label},`${e.label}-${e.col}`))]}),(0,Y.jsxs)(`div`,{className:`heatmap-body`,children:[(0,Y.jsxs)(`div`,{className:`heatmap-days`,children:[(0,Y.jsx)(`span`,{}),(0,Y.jsx)(`span`,{children:i(`usage.dayMon`)}),(0,Y.jsx)(`span`,{}),(0,Y.jsx)(`span`,{children:i(`usage.dayWed`)}),(0,Y.jsx)(`span`,{}),(0,Y.jsx)(`span`,{children:i(`usage.dayFri`)}),(0,Y.jsx)(`span`,{})]}),(0,Y.jsx)(`div`,{className:`heatmap-grid`,style:{gridTemplateColumns:`repeat(${t.weeks.length}, var(--hm-cell))`},children:t.weeks.map((e,t)=>(0,Y.jsx)(`div`,{className:`heatmap-week`,children:e.map((e,n)=>(0,Y.jsx)(`div`,{className:`heatmap-cell heatmap-cell-${e.level}`,onMouseEnter:r=>{if(!e.date)return;let i=r.currentTarget.getBoundingClientRect();s({weekIndex:t,dayIndex:n,x:i.left+i.width/2,y:i.top})},onMouseLeave:()=>s(e=>e?.weekIndex===t&&e.dayIndex===n?null:e)},e.date||`pad-${t}-${n}`))},e[0]?.date||`week-${t}`))})]}),o&&(()=>{let e=t.weeks[o.weekIndex]?.[o.dayIndex];return e?.date?(0,Y.jsxs)(`div`,{className:`heatmap-tip`,role:`tooltip`,style:{left:o.x,top:o.y},children:[(0,Y.jsx)(`div`,{className:`heatmap-tip-date`,children:e.date}),(0,Y.jsx)(`div`,{className:`heatmap-tip-val`,children:i(`usage.heatmap.tooltipTokens`,{tokens:Wn(e.totalTokens,r)})}),(0,Y.jsx)(`div`,{className:`heatmap-tip-req muted`,children:i(`usage.heatmap.tooltipRequests`,{requests:e.requests})})]}):null})(),(0,Y.jsxs)(`div`,{className:`heatmap-legend muted`,children:[(0,Y.jsx)(`span`,{children:i(`usage.heatmap.less`)}),[0,1,2,3,4].map(e=>(0,Y.jsx)(`span`,{className:`heatmap-cell heatmap-cell-${e}`},e)),(0,Y.jsx)(`span`,{children:i(`usage.heatmap.more`)})]})]})]})}function qv({title:e,titleId:t,children:n}){return(0,Y.jsxs)(`section`,{className:`usw-section`,"aria-labelledby":t,children:[(0,Y.jsx)(`h3`,{id:t,className:`h-section`,children:e}),n]})}function Jv({models:e,modelQuery:t,onModelQuery:n,locale:r,t:i,workspace:a=!1}){let o=i(`usage.search.models`),s=i(`usage.section.models`),c=`usage-models-title`,l=(0,Y.jsx)(`input`,{className:`input`,"aria-label":o,placeholder:o,value:t,onChange:e=>n(e.target.value)}),u=(0,Y.jsx)(`div`,{className:`tbl-wrap`,children:(0,Y.jsxs)(`table`,{className:`tbl`,children:[(0,Y.jsx)(`thead`,{children:(0,Y.jsxs)(`tr`,{children:[(0,Y.jsx)(`th`,{children:i(`logs.col.model`)}),(0,Y.jsx)(`th`,{children:i(`logs.col.provider`)}),(0,Y.jsx)(`th`,{className:`num`,children:i(`usage.col.requests`)}),(0,Y.jsx)(`th`,{className:`num`,children:i(`usage.col.measured`)}),(0,Y.jsx)(`th`,{className:`num`,children:i(`usage.col.tokens`)}),(0,Y.jsx)(`th`,{children:i(`usage.col.share`)})]})}),(0,Y.jsx)(`tbody`,{children:e.map(e=>(0,Y.jsxs)(`tr`,{children:[(0,Y.jsx)(`td`,{className:`mono`,children:tf(e.model)}),(0,Y.jsx)(`td`,{className:`muted`,children:Ln(e.provider,i)}),(0,Y.jsx)(`td`,{className:`num`,children:e.requests}),(0,Y.jsx)(`td`,{className:`num`,children:e.measuredRequests}),(0,Y.jsx)(`td`,{className:`num mono`,children:Wn(e.totalTokens,r)}),(0,Y.jsx)(`td`,{children:(0,Y.jsx)(`div`,{className:`usage-bar`,children:(0,Y.jsx)(`div`,{className:`usage-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})})]},`${e.provider}/${e.model}`))})]})});return a?(0,Y.jsxs)(qv,{title:s,titleId:c,children:[(0,Y.jsx)(`div`,{className:`usw-section-toolbar`,children:l}),u]}):(0,Y.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":c,children:[(0,Y.jsxs)(`div`,{className:`panel-head`,children:[(0,Y.jsx)(`h3`,{id:c,className:`panel-title`,children:s}),l]}),u]})}function Yv({providers:e,locale:t,t:n,workspace:r=!1}){let i=n(`usage.section.providers`),a=`usage-providers-title`,o=(0,Y.jsx)(`div`,{className:`tbl-wrap`,children:(0,Y.jsxs)(`table`,{className:`tbl`,children:[(0,Y.jsx)(`thead`,{children:(0,Y.jsxs)(`tr`,{children:[(0,Y.jsx)(`th`,{children:n(`logs.col.provider`)}),(0,Y.jsx)(`th`,{className:`num`,children:n(`usage.col.requests`)}),(0,Y.jsx)(`th`,{className:`num`,children:n(`usage.col.measured`)}),(0,Y.jsx)(`th`,{className:`num`,children:n(`usage.col.tokens`)}),(0,Y.jsx)(`th`,{children:n(`usage.col.share`)})]})}),(0,Y.jsx)(`tbody`,{children:e.map(e=>(0,Y.jsxs)(`tr`,{children:[(0,Y.jsx)(`td`,{className:`mono`,children:Ln(e.provider,n)}),(0,Y.jsx)(`td`,{className:`num`,children:e.requests}),(0,Y.jsx)(`td`,{className:`num`,children:e.measuredRequests}),(0,Y.jsx)(`td`,{className:`num mono`,children:Wn(e.totalTokens,t)}),(0,Y.jsx)(`td`,{children:(0,Y.jsx)(`div`,{className:`usage-bar`,children:(0,Y.jsx)(`div`,{className:`usage-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})})]},e.provider))})]})});return r?(0,Y.jsx)(qv,{title:i,titleId:a,children:o}):(0,Y.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":a,children:[(0,Y.jsx)(`h3`,{id:a,className:`panel-title`,children:i}),o]})}function Xv({summary:e,t,workspace:n=!1}){let r=t(`usage.section.coverage`),i=`usage-coverage-title`,a=(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{className:`usage-cards usage-cards-3x2`,children:[(0,Y.jsxs)(`div`,{className:`stat`,children:[(0,Y.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.measured`)}),(0,Y.jsx)(`div`,{className:`stat-value`,children:e.measuredRequests})]}),(0,Y.jsxs)(`div`,{className:`stat`,children:[(0,Y.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.reported`)}),(0,Y.jsx)(`div`,{className:`stat-value`,children:e.reportedRequests})]}),(0,Y.jsxs)(`div`,{className:`stat`,children:[(0,Y.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.estimated`)}),(0,Y.jsx)(`div`,{className:`stat-value`,children:e.estimatedRequests})]}),(0,Y.jsxs)(`div`,{className:`stat`,children:[(0,Y.jsx)(`div`,{className:`muted`,children:t(`logs.tokens.unreported`)}),(0,Y.jsx)(`div`,{className:`stat-value`,children:e.unreportedRequests})]}),(0,Y.jsxs)(`div`,{className:`stat`,children:[(0,Y.jsx)(`div`,{className:`muted`,children:t(`logs.tokens.unsupported`)}),(0,Y.jsx)(`div`,{className:`stat-value`,children:e.unsupportedRequests})]})]}),(0,Y.jsx)(`p`,{className:`muted text-control`,style:{marginTop:12},children:t(`usage.coverage.note`)})]});return n?(0,Y.jsx)(qv,{title:r,titleId:i,children:a}):(0,Y.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":i,children:[(0,Y.jsx)(`h3`,{id:i,className:`panel-title`,children:r}),a]})}function Zv({data:e,heatmap:t,weekBars:n,activeDays:r,filteredModels:i,modelQuery:a,onModelQuery:o,sortedProviders:s,range:c,locale:l,t:u}){let d=!!e&&e.summary.requests===0,f=[{id:`overview`,label:u(`usage.section.overview`),meta:e?`${e.summary.requests}`:`—`,body:e?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(Wv,{summary:e.summary,activeDays:r,locale:l,t:u}),(0,Y.jsx)(Kv,{range:c,heatmap:t,weekBars:n,locale:l,t:u})]}):null},{id:`models`,label:u(`usage.section.models`),meta:e?`${e.models.length}`:`—`,body:e?(0,Y.jsx)(Jv,{models:i,modelQuery:a,onModelQuery:o,locale:l,t:u,workspace:!0}):null},{id:`providers`,label:u(`usage.section.providers`),meta:e?`${e.providers.length}`:`—`,body:e?(0,Y.jsx)(Yv,{providers:s,locale:l,t:u,workspace:!0}):null},{id:`coverage`,label:u(`usage.section.coverage`),meta:e?Lv(e.summary.coverageRatio):`—`,body:e?(0,Y.jsx)(Xv,{summary:e.summary,t:u,workspace:!0}):null}];return(0,Y.jsx)(`div`,{className:`usage-workspace-shell`,children:(0,Y.jsxs)(`div`,{className:`usage-workspace-root`,children:[(0,Y.jsx)(Mg,{scope:`usage`,ariaLabel:u(`usage.workspace.sections`),items:f.map(e=>({id:e.id,label:e.label,meta:e.meta}))}),(0,Y.jsx)(`section`,{className:`usage-workspace-main`,"aria-label":u(`usage.workspace.report`),children:d?(0,Y.jsx)(At,{title:u(`usage.empty`)}):f.map(e=>(0,Y.jsx)(`div`,{id:kg(`usage`,e.id),className:`usw-body usw-section-block`,children:e.body},e.id))})]})})}var Qv=new Map;function $v(e,t,n,r,i,a){return`ocx.usage.v2:${e}:${r?`connected`:`standalone`}:${i}:${a??``}:${t}:${n}`}function ey(e,t,n,r,i,a){let o=$v(e,t,n,r,i,a);return Qv.get(o)??Tr(o)}function ty(e,t,n,r,i,a,o){let s=$v(e,t,n,r,i,a);Qv.set(s,o),kr(s,o)}function ny({apiBase:e,connected:t=!1,apiKeyId:n}){let{t:r,locale:i}=ut(),[a,o]=(0,_.useState)(`30d`),[s,c]=(0,_.useState)(`all`),[l,u]=(0,_.useState)(`machine`),[d,f]=(0,_.useState)(``),[p,m]=(0,_.useState)({since:``,until:``}),[h,g]=(0,_.useState)(null),[v,y]=(0,_.useState)(null),[b,x]=(0,_.useState)(!1),S=h?.since,C=h?.until,w=()=>{g(null),m({since:``,until:``}),y(null)},T=e=>{o(e),w()},E=(0,_.useCallback)(async r=>{let i=new URLSearchParams({range:a,surface:s});t&&l===`machine`&&n&&i.set(`apiKeyId`,n),S!==void 0&&C!==void 0&&(i.set(`since`,String(S)),i.set(`until`,String(C)));let o=await fetch(`${e}/api/usage?${i}`,{signal:r});if(!o.ok)throw Error(`${o.status} ${o.statusText}`.trim());let c=await o.json();if(S!==void 0&&(c?.customWindow!==!0||c.since!==S||c.until!==C))throw new Iv;return S===void 0&&ty(e,a,s,t,l,n,c),c},[e,n,t,a,l,s,S,C]),D=$v(e,a,s,t,l,n),O=h?JSON.stringify([D,S,C]):D,k=h?null:ey(e,a,s,t,l,n),A=jr(O,[e,n,t,a,l,s,S,C],E,{isEmpty:()=>!1,initialData:k??void 0}),{state:j}=A,M=j.data??k??null,N=(0,_.useMemo)(()=>Hv(M?.days??[],!!h),[M?.days,h]),P=(0,_.useMemo)(()=>zv(M?.days??[]),[M?.days]),F=(0,_.useMemo)(()=>(M?.days??[]).filter(e=>e.requests>0).length,[M?.days]),I=(0,_.useMemo)(()=>{let e=d.trim().toLowerCase(),t=(M?.models??[]).toSorted((e,t)=>t.totalTokens-e.totalTokens);return e?t.filter(t=>t.model.toLowerCase().includes(e)||t.provider.toLowerCase().includes(e)||(t.resolvedModel??``).toLowerCase().includes(e)).slice(0,100):t.slice(0,100)},[M?.models,d]),L=(0,_.useMemo)(()=>(M?.providers??[]).toSorted((e,t)=>t.totalTokens-e.totalTokens),[M?.providers]);return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{className:`page-head usage-head`,children:[(0,Y.jsx)(`h2`,{id:`usage-page-title`,children:r(`usage.title`)}),(0,Y.jsx)(Uv,{surface:s,range:h?null:a,onSurface:c,onRange:T,t:r})]}),(0,Y.jsx)(`p`,{className:`page-sub`,children:r(`usage.subtitle`)}),(0,Y.jsxs)(`section`,{className:`usage-range`,children:[(0,Y.jsxs)(`div`,{className:`usage-range-bar`,children:[(0,Y.jsxs)(`button`,{type:`button`,className:`usage-range-toggle${h?` is-active`:``}`,"aria-expanded":b,"aria-controls":b?`usage-range-panel`:void 0,onClick:()=>{b&&y(null),x(!b)},children:[(0,Y.jsx)(`span`,{children:r(`usage.range.custom`)}),(0,Y.jsx)(Ce,{width:12,height:12,"aria-hidden":`true`,className:`usage-range-chevron`})]}),h&&(0,Y.jsx)(`p`,{className:`usage-range-applied muted text-control`,role:`status`,children:(()=>{let e=new Intl.DateTimeFormat(i,{year:`numeric`,month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,fractionalSecondDigits:3,timeZoneName:`short`});return r(`usage.range.applied`,{start:e.format(h.since),end:e.format(h.until)})})()})]}),b&&(0,Y.jsxs)(`form`,{id:`usage-range-panel`,className:`usage-range-panel`,"aria-label":r(`usage.range.custom`),noValidate:!0,onSubmit:e=>{e.preventDefault();let t=Fv(p.since,p.until);if(t.ok===!1){y(t.error);return}y(null),g(t.window)},children:[(0,Y.jsxs)(`div`,{className:`usage-range-fields`,children:[(0,Y.jsxs)(`label`,{className:`usage-range-field`,children:[(0,Y.jsx)(`span`,{className:`field-label`,children:r(`usage.range.start`)}),(0,Y.jsx)(`input`,{className:`input`,type:`datetime-local`,step:`60`,required:!0,value:p.since,"aria-invalid":v!==null,"aria-describedby":v?`usage-range-help usage-range-error`:`usage-range-help`,onChange:e=>{let t=e.currentTarget.value;m(e=>({...e,since:t})),y(null)}})]}),(0,Y.jsxs)(`label`,{className:`usage-range-field`,children:[(0,Y.jsx)(`span`,{className:`field-label`,children:r(`usage.range.end`)}),(0,Y.jsx)(`input`,{className:`input`,type:`datetime-local`,step:`60`,required:!0,value:p.until,"aria-invalid":v!==null,"aria-describedby":v?`usage-range-help usage-range-error`:`usage-range-help`,onChange:e=>{let t=e.currentTarget.value;m(e=>({...e,until:t})),y(null)}})]}),(0,Y.jsx)(`button`,{type:`submit`,className:`btn btn-primary btn-sm usage-range-action`,children:r(`usage.range.apply`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm usage-range-action`,onClick:w,children:r(`usage.range.clear`)})]}),(0,Y.jsx)(`p`,{id:`usage-range-help`,className:`muted text-caption`,children:r(`usage.range.help`)}),v&&(0,Y.jsx)(`p`,{id:`usage-range-error`,role:`alert`,className:`notice notice-err`,children:r(`usage.range.${v}`)})]})]}),t&&(0,Y.jsxs)(`div`,{className:`usage-source-row`,children:[(0,Y.jsx)(`span`,{children:r(`usage.source.connected`)}),(0,Y.jsxs)(`div`,{className:`usage-scope-control`,role:`group`,"aria-label":r(`usage.scope.label`),children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-sm${l===`machine`?` btn-primary`:` btn-ghost`}`,"aria-pressed":l===`machine`,onClick:()=>u(`machine`),children:r(`usage.scope.machine`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-sm${l===`hub`?` btn-primary`:` btn-ghost`}`,"aria-pressed":l===`hub`,onClick:()=>u(`hub`),children:r(`usage.scope.hub`)})]})]}),j.showSkeleton&&!M?(0,Y.jsx)(ep,{label:r(`usage.loading`),rows:5}):j.kind===`failed-cold`?(0,Y.jsxs)($,{tone:`err`,children:[j.error instanceof Iv?`${r(`usage.loadError`)} ${r(`dash.codexRestartMalformed`)}`:t?r(`usage.hubOffline`):j.error instanceof Error?`${r(`usage.loadError`)} ${j.error.message}`:r(`usage.loadError`),` `,(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>A.refresh(),children:r(`common.retry`)})]}):(0,Y.jsxs)(Y.Fragment,{children:[j.showError&&(0,Y.jsx)($,{tone:`err`,children:r(t?`usage.hubOffline`:`usage.loadError`)}),(0,Y.jsx)(Jn,{data:M}),M?.historyTruncated&&(0,Y.jsx)($,{tone:`warn`,children:(()=>{let e=ry(M.snapshotWindowStart),t=ry(M.snapshotWindowEnd);return e!==null&&t!==null?r(`usage.historyTruncatedWindow`,{start:e,end:t}):r(`usage.historyTruncated`)})()}),(0,Y.jsx)(Zv,{data:M,heatmap:N,weekBars:P,activeDays:F,filteredModels:I,modelQuery:d,onModelQuery:f,sortedProviders:L,range:h?null:a,locale:i,t:r})]})]})}function ry(e){if(typeof e!=`number`||!Number.isFinite(e))return null;let t=new Date(e);return Number.isFinite(t.getTime())?t.toLocaleString():null}function iy(e,t){if(e<1024)return`${e} B`;let n=[`KiB`,`MiB`,`GiB`,`TiB`],r=e,i=-1;do r/=1024,i++;while(r>=1024&&i<n.length-1);return`${r.toLocaleString(t,{maximumFractionDigits:1})} ${n[i]}`}var ay={en:{compact:`Compact`,compactComplete:`Compaction complete (logical / on-disk reclaimed)`,pagesUnit:`pages`,compactPartial:`Compaction partial (logical / on-disk reclaimed)`,confirmCompact:`Confirm compaction`,cancel:`Cancel`,inspectionOnly:`Inspection only`,externalSqliteHome:`External SQLite storage`,inspectionUnavailable:`Diagnostic log inspection is unavailable.`,metricsSkippedLarge:`Row metrics skipped: the database is above {threshold}, and scanning it would stall the proxy.`,protection:`Protection`,compat:`Compatibility`,quiet:`Quiet`,disable:`Disable protection`,repair:`Repair protection`,applying:`Applying protection…`,"error.generic":`Could not change Codex log protection.`,"error.codex_running":`Quit Codex before changing log protection.`,"error.process_enumeration_failed":`Could not verify that Codex is stopped. Protection was not changed.`,"error.busy":`The Codex logs database is busy. Quit Codex and try again.`,"error.unsupported_schema":`This Codex logs schema is not supported for protection.`,"error.trigger_collision":`A reserved Log Guard trigger name is already in use. Protection was not changed.`,"error.unsafe_path":`The Codex logs database path failed the safety check.`,"error.database_error":`Could not update the Codex logs database.`,"error.config_write_failed":`The database changed, but OpenCodex could not save the protection setting. Fix config storage, then run Repair.`},de:{compact:`Komprimieren`,compactComplete:`Komprimierung abgeschlossen (logisch / auf Datentraeger freigegeben)`,pagesUnit:`Seiten`,compactPartial:`Komprimierung teilweise (logisch / auf Datentraeger freigegeben)`,confirmCompact:`Komprimierung bestätigen`,cancel:`Abbrechen`,inspectionOnly:`Nur Inspektion`,externalSqliteHome:`Externer SQLite-Speicher`,inspectionUnavailable:`Die Diagnoseprotokoll-Inspektion ist nicht verfügbar.`,metricsSkippedLarge:`Zeilenmetriken übersprungen: Die Datenbank ist größer als {threshold}; ein Scan würde den Proxy blockieren.`,protection:`Schutz`,compat:`Kompatibilität`,quiet:`Leise`,disable:`Schutz deaktivieren`,repair:`Schutz reparieren`,applying:`Schutz wird angewendet…`,"error.generic":`Der Schutz der Codex-Protokolle konnte nicht geändert werden.`,"error.codex_running":`Beende Codex, bevor du den Protokollschutz änderst.`,"error.process_enumeration_failed":`Es konnte nicht sicher festgestellt werden, dass Codex beendet ist. Der Schutz wurde nicht geändert.`,"error.busy":`Die Codex-Protokolldatenbank ist belegt. Beende Codex und versuche es erneut.`,"error.unsupported_schema":`Dieses Schema der Codex-Protokolldatenbank wird für den Schutz nicht unterstützt.`,"error.trigger_collision":`Ein reservierter Log-Guard-Triggername wird bereits verwendet. Der Schutz wurde nicht geändert.`,"error.unsafe_path":`Der Pfad der Codex-Protokolldatenbank hat die Sicherheitsprüfung nicht bestanden.`,"error.database_error":`Die Codex-Protokolldatenbank konnte nicht aktualisiert werden.`,"error.config_write_failed":`Die Datenbank wurde geändert, aber OpenCodex konnte die Schutzeinstellung nicht speichern. Repariere den Konfigurationsspeicher und führe danach Reparieren aus.`},fr:{compact:`Compacter`,compactComplete:`Compactage termine (logique / recupere sur disque)`,pagesUnit:`pages`,compactPartial:`Compactage partiel (logique / recupere sur disque)`,confirmCompact:`Confirmer le compactage`,cancel:`Annuler`,inspectionOnly:`Inspection uniquement`,externalSqliteHome:`Stockage SQLite externe`,inspectionUnavailable:`L’inspection des journaux de diagnostic est indisponible.`,metricsSkippedLarge:`Métriques de lignes ignorées : la base dépasse {threshold} et son analyse bloquerait le proxy.`,protection:`Protection`,compat:`Compatibilité`,quiet:`Silencieux`,disable:`Désactiver la protection`,repair:`Réparer la protection`,applying:`Application de la protection…`,"error.generic":`Impossible de modifier la protection des journaux Codex.`,"error.codex_running":`Quittez Codex avant de modifier la protection des journaux.`,"error.process_enumeration_failed":`Impossible de vérifier que Codex est arrêté. La protection n’a pas été modifiée.`,"error.busy":`La base de données des journaux Codex est occupée. Quittez Codex et réessayez.`,"error.unsupported_schema":`Ce schéma de journaux Codex n’est pas pris en charge pour la protection.`,"error.trigger_collision":`Un nom de déclencheur Log Guard réservé est déjà utilisé. La protection n’a pas été modifiée.`,"error.unsafe_path":`Le chemin de la base de données des journaux Codex a échoué au contrôle de sécurité.`,"error.database_error":`Impossible de mettre à jour la base de données des journaux Codex.`,"error.config_write_failed":`La base de données a été modifiée, mais OpenCodex n’a pas pu enregistrer le paramètre de protection. Corrigez le stockage de configuration, puis lancez Réparer.`},ko:{compact:`압축`,compactComplete:`압축 완료 (논리 / 디스크 회수량)`,pagesUnit:`페이지`,compactPartial:`압축 부분 완료 (논리 / 디스크 회수량)`,confirmCompact:`압축 확인`,cancel:`취소`,inspectionOnly:`검사 전용`,externalSqliteHome:`외부 SQLite 저장소`,inspectionUnavailable:`진단 로그 검사를 사용할 수 없습니다.`,metricsSkippedLarge:`행 지표를 건너뛰었습니다. 데이터베이스가 {threshold}보다 커서 스캔하면 프록시가 멈춥니다.`,protection:`보호`,compat:`호환 모드`,quiet:`조용한 모드`,disable:`보호 비활성화`,repair:`보호 복구`,applying:`보호 적용 중…`,"error.generic":`Codex 로그 보호를 변경하지 못했습니다.`,"error.codex_running":`로그 보호를 변경하기 전에 Codex를 종료하세요.`,"error.process_enumeration_failed":`Codex가 종료되었는지 확인할 수 없어 보호를 변경하지 않았습니다.`,"error.busy":`Codex 로그 데이터베이스가 사용 중입니다. Codex를 종료한 뒤 다시 시도하세요.`,"error.unsupported_schema":`이 Codex 로그 스키마는 보호 기능을 지원하지 않습니다.`,"error.trigger_collision":`예약된 Log Guard 트리거 이름이 이미 사용 중입니다. 보호를 변경하지 않았습니다.`,"error.unsafe_path":`Codex 로그 데이터베이스 경로가 안전성 검사를 통과하지 못했습니다.`,"error.database_error":`Codex 로그 데이터베이스를 업데이트하지 못했습니다.`,"error.config_write_failed":`데이터베이스는 변경되었지만 OpenCodex가 보호 설정을 저장하지 못했습니다. 구성 저장소를 수정한 뒤 복구를 실행하세요.`},zh:{compact:`压缩`,compactComplete:`压缩完成(逻辑 / 磁盘回收)`,pagesUnit:`页`,compactPartial:`压缩部分完成(逻辑 / 磁盘回收)`,confirmCompact:`确认压缩`,cancel:`取消`,inspectionOnly:`仅检查`,externalSqliteHome:`外部 SQLite 存储`,inspectionUnavailable:`诊断日志检查当前不可用。`,metricsSkippedLarge:`已跳过行指标:数据库超过 {threshold},扫描会阻塞代理。`,protection:`保护`,compat:`兼容模式`,quiet:`静默模式`,disable:`禁用保护`,repair:`修复保护`,applying:`正在应用保护…`,"error.generic":`无法更改 Codex 日志保护。`,"error.codex_running":`更改 Codex 日志保护前请先退出 Codex。`,"error.process_enumeration_failed":`无法确认 Codex 已停止,因此未更改保护设置。`,"error.busy":`Codex 日志数据库正忙。请退出 Codex 后重试。`,"error.unsupported_schema":`此 Codex 日志数据库结构不支持保护功能。`,"error.trigger_collision":`保留的 Log Guard 触发器名称已被占用,因此未更改保护设置。`,"error.unsafe_path":`Codex 日志数据库路径未通过安全检查。`,"error.database_error":`无法更新 Codex 日志数据库。`,"error.config_write_failed":`数据库已更改,但 OpenCodex 无法保存保护设置。请先修复配置存储,然后运行“修复保护”。`},"zh-TW":{compact:`壓縮`,compactComplete:`压缩完成(逻辑 / 磁盘回收)`,pagesUnit:`頁`,compactPartial:`压缩部分完成(逻辑 / 磁盘回收)`,confirmCompact:`確認壓縮`,cancel:`取消`,inspectionOnly:`僅檢查`,externalSqliteHome:`外部 SQLite 儲存空間`,inspectionUnavailable:`診斷記錄檢查目前無法使用。`,metricsSkippedLarge:`已略過列指標:資料庫超過 {threshold},掃描會阻塞代理。`,protection:`保護`,compat:`相容模式`,quiet:`靜默模式`,disable:`停用保護`,repair:`修復保護`,applying:`正在套用保護…`,"error.generic":`無法變更 Codex 日誌保護。`,"error.codex_running":`變更 Codex 日誌保護前請先退出 Codex。`,"error.process_enumeration_failed":`無法確認 Codex 已停止,因此未變更保護設定。`,"error.busy":`Codex 日誌資料庫忙碌中。請退出 Codex 後重試。`,"error.unsupported_schema":`此 Codex 日誌資料庫結構不支援保護功能。`,"error.trigger_collision":`保留的 Log Guard 觸發器名稱已被使用,因此未變更保護設定。`,"error.unsafe_path":`Codex 日誌資料庫路徑未通過安全檢查。`,"error.database_error":`無法更新 Codex 日誌資料庫。`,"error.config_write_failed":`資料庫已變更,但 OpenCodex 無法儲存保護設定。請先修復設定儲存空間,再執行「修復保護」。`},ru:{compact:`Сжать`,compactComplete:`Сжатие завершено (логически / освобождено на диске)`,pagesUnit:`страниц`,compactPartial:`Сжатие частичное (логически / освобождено на диске)`,confirmCompact:`Подтвердить сжатие`,cancel:`Отмена`,inspectionOnly:`Только проверка`,externalSqliteHome:`Внешнее хранилище SQLite`,inspectionUnavailable:`Проверка диагностических журналов недоступна.`,metricsSkippedLarge:`Метрики строк пропущены: база больше {threshold}, и её сканирование заблокировало бы прокси.`,protection:`Защита`,compat:`Совместимость`,quiet:`Тихий режим`,disable:`Отключить защиту`,repair:`Восстановить защиту`,applying:`Применение защиты…`,"error.generic":`Не удалось изменить защиту журналов Codex.`,"error.codex_running":`Закройте Codex перед изменением защиты журналов.`,"error.process_enumeration_failed":`Не удалось убедиться, что Codex остановлен. Защита не изменена.`,"error.busy":`База журналов Codex занята. Закройте Codex и повторите попытку.`,"error.unsupported_schema":`Эта схема базы журналов Codex не поддерживает защиту.`,"error.trigger_collision":`Зарезервированное имя триггера Log Guard уже используется. Защита не изменена.`,"error.unsafe_path":`Путь к базе журналов Codex не прошёл проверку безопасности.`,"error.database_error":`Не удалось обновить базу журналов Codex.`,"error.config_write_failed":`База была изменена, но OpenCodex не смог сохранить настройку защиты. Исправьте хранилище конфигурации и затем запустите восстановление.`},ja:{compact:`圧縮`,compactComplete:`圧縮完了(論理 / ディスク解放)`,pagesUnit:`ページ`,compactPartial:`圧縮は部分的に完了(論理 / ディスク解放)`,confirmCompact:`圧縮を確認`,cancel:`キャンセル`,inspectionOnly:`検査のみ`,externalSqliteHome:`外部 SQLite ストレージ`,inspectionUnavailable:`診断ログの検査を利用できません。`,metricsSkippedLarge:`行メトリクスをスキップしました。データベースが {threshold} を超えており、走査するとプロキシが停止します。`,protection:`保護`,compat:`互換モード`,quiet:`静音モード`,disable:`保護を無効化`,repair:`保護を修復`,applying:`保護を適用中…`,"error.generic":`Codex ログ保護を変更できませんでした。`,"error.codex_running":`ログ保護を変更する前に Codex を終了してください。`,"error.process_enumeration_failed":`Codex が停止していることを確認できなかったため、保護は変更されませんでした。`,"error.busy":`Codex ログデータベースが使用中です。Codex を終了して再試行してください。`,"error.unsupported_schema":`この Codex ログスキーマでは保護機能を使用できません。`,"error.trigger_collision":`予約済みの Log Guard トリガー名が既に使用されています。保護は変更されませんでした。`,"error.unsafe_path":`Codex ログデータベースのパスが安全性チェックに失敗しました。`,"error.database_error":`Codex ログデータベースを更新できませんでした。`,"error.config_write_failed":`データベースは変更されましたが、OpenCodex は保護設定を保存できませんでした。設定ストレージを修正してから保護を修復してください。`},tr:{compact:`Sıkıştır`,compactComplete:`Sikistirma tamamlandi (mantiksal / diskte geri kazanilan)`,pagesUnit:`sayfa`,compactPartial:`Sikistirma kismi (mantiksal / diskte geri kazanilan)`,confirmCompact:`Sıkıştırmayı onayla`,cancel:`İptal`,inspectionOnly:`Yalnızca inceleme`,externalSqliteHome:`Harici SQLite depolaması`,inspectionUnavailable:`Tanılama günlüğü incelemesi kullanılamıyor.`,metricsSkippedLarge:`Satır ölçümleri atlandı: veritabanı {threshold} sınırının üzerinde ve taranması proxy’yi kilitler.`,protection:`Koruma`,compat:`Uyumluluk`,quiet:`Sessiz`,disable:`Korumayı devre dışı bırak`,repair:`Korumayı onar`,applying:`Koruma uygulanıyor…`,"error.generic":`Codex günlük koruması değiştirilemedi.`,"error.codex_running":`Günlük korumasını değiştirmeden önce Codex'i kapatın.`,"error.process_enumeration_failed":`Codex'in kapalı olduğu doğrulanamadı. Koruma değiştirilmedi.`,"error.busy":`Codex günlük veritabanı meşgul. Codex'i kapatıp yeniden deneyin.`,"error.unsupported_schema":`Bu Codex günlük şeması koruma için desteklenmiyor.`,"error.trigger_collision":`Ayrılmış bir Log Guard tetikleyici adı zaten kullanılıyor. Koruma değiştirilmedi.`,"error.unsafe_path":`Codex günlük veritabanı yolu güvenlik denetimini geçemedi.`,"error.database_error":`Codex günlük veritabanı güncellenemedi.`,"error.config_write_failed":`Veritabanı değişti ancak OpenCodex koruma ayarını kaydedemedi. Yapılandırma depolamasını düzeltip ardından korumayı onarın.`}};function oy(e,t){return ay[e][t]}var sy={en:{applying:`Applying Log Guard change…`,"error.generic":`Could not update Codex log storage.`,"error.codex_running":`Quit Codex before changing Codex log storage.`,"error.process_enumeration_failed":`Could not verify that Codex is stopped. The Log Guard operation was not started.`,"error.busy":`The Codex logs database is busy. Quit Codex and try again.`,"error.unsupported_schema":`This Codex logs schema is not supported for this operation.`,"error.unsafe_path":`The Codex logs database path failed the safety check.`,"error.database_error":`Could not update the Codex logs database.`,"error.auto_vacuum_not_incremental":`This Codex logs database is not configured for incremental vacuum, so space cannot be reclaimed without a full rebuild.`,"error.integrity_check_failed":`The Codex logs database failed its integrity check. No space was reclaimed.`},de:{applying:`Log-Guard-Änderung wird angewendet…`,"error.generic":`Der Codex-Protokollspeicher konnte nicht aktualisiert werden.`,"error.codex_running":`Beende Codex, bevor du den Codex-Protokollspeicher änderst.`,"error.process_enumeration_failed":`Es konnte nicht sicher festgestellt werden, dass Codex beendet ist. Der Log-Guard-Vorgang wurde nicht gestartet.`,"error.busy":`Die Codex-Protokolldatenbank ist belegt. Beende Codex und versuche es erneut.`,"error.unsupported_schema":`Dieses Schema der Codex-Protokolldatenbank wird für diesen Vorgang nicht unterstützt.`,"error.unsafe_path":`Der Pfad der Codex-Protokolldatenbank hat die Sicherheitsprüfung nicht bestanden.`,"error.database_error":`Die Codex-Protokolldatenbank konnte nicht aktualisiert werden.`,"error.auto_vacuum_not_incremental":`Diese Codex-Protokolldatenbank ist nicht fuer inkrementelles Vacuum konfiguriert; ohne vollstaendigen Neuaufbau kann kein Speicher freigegeben werden.`,"error.integrity_check_failed":`Die Integritaetspruefung der Codex-Protokolldatenbank ist fehlgeschlagen. Es wurde kein Speicher freigegeben.`},fr:{applying:`Application de la modification Log Guard…`,"error.generic":`Impossible de mettre à jour le stockage des journaux Codex.`,"error.codex_running":`Quittez Codex avant de modifier le stockage des journaux Codex.`,"error.process_enumeration_failed":`Impossible de vérifier que Codex est arrêté. L’opération Log Guard n’a pas été lancée.`,"error.busy":`La base de données des journaux Codex est occupée. Quittez Codex et réessayez.`,"error.unsupported_schema":`Ce schéma de journaux Codex n’est pas pris en charge pour cette opération.`,"error.unsafe_path":`Le chemin de la base de données des journaux Codex a échoué au contrôle de sécurité.`,"error.database_error":`Impossible de mettre à jour la base de données des journaux Codex.`,"error.auto_vacuum_not_incremental":`Cette base de donnees de journaux Codex n'est pas configuree pour le vacuum incrementiel : l'espace ne peut pas etre recupere sans reconstruction complete.`,"error.integrity_check_failed":`La verification d'integrite de la base de donnees de journaux Codex a echoue. Aucun espace n'a ete recupere.`},ko:{applying:`Log Guard 변경 적용 중…`,"error.generic":`Codex 로그 저장소를 업데이트하지 못했습니다.`,"error.codex_running":`Codex 로그 저장소를 변경하기 전에 Codex를 종료하세요.`,"error.process_enumeration_failed":`Codex가 종료되었는지 확인할 수 없어 Log Guard 작업을 시작하지 않았습니다.`,"error.busy":`Codex 로그 데이터베이스가 사용 중입니다. Codex를 종료한 뒤 다시 시도하세요.`,"error.unsupported_schema":`이 Codex 로그 스키마는 이 작업을 지원하지 않습니다.`,"error.unsafe_path":`Codex 로그 데이터베이스 경로가 안전성 검사를 통과하지 못했습니다.`,"error.database_error":`Codex 로그 데이터베이스를 업데이트하지 못했습니다.`,"error.auto_vacuum_not_incremental":`이 Codex 로그 데이터베이스는 증분 정리로 구성되어 있지 않아, 전체 재구축 없이는 공간을 회수할 수 없습니다.`,"error.integrity_check_failed":`Codex 로그 데이터베이스 무결성 검사에 실패했습니다. 공간이 회수되지 않았습니다.`},zh:{applying:`正在应用 Log Guard 更改…`,"error.generic":`无法更新 Codex 日志存储。`,"error.codex_running":`更改 Codex 日志存储前请先退出 Codex。`,"error.process_enumeration_failed":`无法确认 Codex 已停止,因此未启动 Log Guard 操作。`,"error.busy":`Codex 日志数据库正忙。请退出 Codex 后重试。`,"error.unsupported_schema":`此 Codex 日志数据库结构不支持此操作。`,"error.unsafe_path":`Codex 日志数据库路径未通过安全检查。`,"error.database_error":`无法更新 Codex 日志数据库。`,"error.auto_vacuum_not_incremental":`此 Codex 日志数据库未配置增量清理,因此不完整重建就无法回收空间。`,"error.integrity_check_failed":`Codex 日志数据库完整性检查失败,未回收任何空间。`},"zh-TW":{applying:`正在套用 Log Guard 變更…`,"error.generic":`無法更新 Codex 日誌儲存空間。`,"error.codex_running":`變更 Codex 日誌儲存空間前請先退出 Codex。`,"error.process_enumeration_failed":`無法確認 Codex 已停止,因此未啟動 Log Guard 操作。`,"error.busy":`Codex 日誌資料庫忙碌中。請退出 Codex 後重試。`,"error.unsupported_schema":`此 Codex 日誌資料庫結構不支援此操作。`,"error.unsafe_path":`Codex 日誌資料庫路徑未通過安全檢查。`,"error.database_error":`無法更新 Codex 日誌資料庫。`,"error.auto_vacuum_not_incremental":`此 Codex 日志数据库未配置增量清理,因此不完整重建就无法回收空间。`,"error.integrity_check_failed":`Codex 日志数据库完整性检查失败,未回收任何空间。`},ru:{applying:`Применение изменения Log Guard…`,"error.generic":`Не удалось обновить хранилище журналов Codex.`,"error.codex_running":`Закройте Codex перед изменением хранилища журналов Codex.`,"error.process_enumeration_failed":`Не удалось убедиться, что Codex остановлен. Операция Log Guard не запущена.`,"error.busy":`База журналов Codex занята. Закройте Codex и повторите попытку.`,"error.unsupported_schema":`Эта схема базы журналов Codex не поддерживает эту операцию.`,"error.unsafe_path":`Путь к базе журналов Codex не прошёл проверку безопасности.`,"error.database_error":`Не удалось обновить базу журналов Codex.`,"error.auto_vacuum_not_incremental":`Эта база данных журналов Codex не настроена на инкрементальную очистку, поэтому освободить место без полной перестройки невозможно.`,"error.integrity_check_failed":`Проверка целостности базы данных журналов Codex не пройдена. Место не освобождено.`},ja:{applying:`Log Guard の変更を適用中…`,"error.generic":`Codex ログストレージを更新できませんでした。`,"error.codex_running":`Codex ログストレージを変更する前に Codex を終了してください。`,"error.process_enumeration_failed":`Codex が停止していることを確認できなかったため、Log Guard 操作を開始しませんでした。`,"error.busy":`Codex ログデータベースが使用中です。Codex を終了して再試行してください。`,"error.unsupported_schema":`この Codex ログスキーマではこの操作を使用できません。`,"error.unsafe_path":`Codex ログデータベースのパスが安全性チェックに失敗しました。`,"error.database_error":`Codex ログデータベースを更新できませんでした。`,"error.auto_vacuum_not_incremental":`この Codex ログ データベースは増分バキューム用に構成されていないため、完全な再構築なしに領域を解放できません。`,"error.integrity_check_failed":`Codex ログ データベースの整合性チェックに失敗しました。領域は解放されていません。`},tr:{applying:`Log Guard değişikliği uygulanıyor…`,"error.generic":`Codex günlük depolaması güncellenemedi.`,"error.codex_running":`Codex günlük depolamasını değiştirmeden önce Codex'i kapatın.`,"error.process_enumeration_failed":`Codex'in kapalı olduğu doğrulanamadı. Log Guard işlemi başlatılmadı.`,"error.busy":`Codex günlük veritabanı meşgul. Codex'i kapatıp yeniden deneyin.`,"error.unsupported_schema":`Bu Codex günlük şeması bu işlem için desteklenmiyor.`,"error.unsafe_path":`Codex günlük veritabanı yolu güvenlik denetimini geçemedi.`,"error.database_error":`Codex günlük veritabanı güncellenemedi.`,"error.auto_vacuum_not_incremental":`Bu Codex gunluk veritabani artimli vacuum icin yapilandirilmamis; tam yeniden olusturma olmadan alan geri kazanilamaz.`,"error.integrity_check_failed":`Codex gunluk veritabani butunluk denetiminden gecemedi. Alan geri kazanilmadi.`}};function cy(e,t){return sy[e][t]}var ly={en:{schema:{compatible:`Compatible`,missing:`Database not found`,unreadable:`Database unavailable`,unsupported:`Unsupported`},protection:{off:`Off`,active:`Active`,drifted:`Needs repair`,unsupported:`Unsupported`,unknown:`Unknown`},mode:{off:`Off`,compat:`Compatibility`,quiet:`Quiet`,collision:`Unknown`}},de:{schema:{compatible:`Kompatibel`,missing:`Datenbank nicht gefunden`,unreadable:`Datenbank nicht lesbar`,unsupported:`Nicht unterstützt`},protection:{off:`Aus`,active:`Aktiv`,drifted:`Reparatur erforderlich`,unsupported:`Nicht unterstützt`,unknown:`Unbekannt`},mode:{off:`Aus`,compat:`Kompatibilität`,quiet:`Leise`,collision:`Unbekannt`}},fr:{schema:{compatible:`Compatible`,missing:`Base de données introuvable`,unreadable:`Base de données indisponible`,unsupported:`Non pris en charge`},protection:{off:`Désactivée`,active:`Active`,drifted:`Réparation requise`,unsupported:`Non prise en charge`,unknown:`Inconnue`},mode:{off:`Désactivé`,compat:`Compatibilité`,quiet:`Silencieux`,collision:`Inconnu`}},ko:{schema:{compatible:`호환됨`,missing:`데이터베이스 없음`,unreadable:`데이터베이스를 읽을 수 없음`,unsupported:`지원되지 않음`},protection:{off:`꺼짐`,active:`활성`,drifted:`복구 필요`,unsupported:`지원되지 않음`,unknown:`알 수 없음`},mode:{off:`꺼짐`,compat:`호환 모드`,quiet:`조용한 모드`,collision:`알 수 없음`}},zh:{schema:{compatible:`兼容`,missing:`未找到数据库`,unreadable:`无法读取数据库`,unsupported:`不受支持`},protection:{off:`关闭`,active:`已启用`,drifted:`需要修复`,unsupported:`不受支持`,unknown:`未知`},mode:{off:`关闭`,compat:`兼容模式`,quiet:`静默模式`,collision:`未知`}},"zh-TW":{schema:{compatible:`相容`,missing:`找不到資料庫`,unreadable:`無法讀取資料庫`,unsupported:`不支援`},protection:{off:`關閉`,active:`已啟用`,drifted:`需要修復`,unsupported:`不支援`,unknown:`未知`},mode:{off:`關閉`,compat:`相容模式`,quiet:`靜默模式`,collision:`未知`}},ru:{schema:{compatible:`Совместимо`,missing:`База не найдена`,unreadable:`База недоступна`,unsupported:`Не поддерживается`},protection:{off:`Выключено`,active:`Активно`,drifted:`Требуется восстановление`,unsupported:`Не поддерживается`,unknown:`Неизвестно`},mode:{off:`Выключено`,compat:`Совместимость`,quiet:`Тихий режим`,collision:`Неизвестно`}},ja:{schema:{compatible:`互換`,missing:`データベースが見つかりません`,unreadable:`データベースを読み取れません`,unsupported:`未対応`},protection:{off:`オフ`,active:`有効`,drifted:`修復が必要`,unsupported:`未対応`,unknown:`不明`},mode:{off:`オフ`,compat:`互換モード`,quiet:`静音モード`,collision:`不明`}},tr:{schema:{compatible:`Uyumlu`,missing:`Veritabanı bulunamadı`,unreadable:`Veritabanı okunamıyor`,unsupported:`Desteklenmiyor`},protection:{off:`Kapalı`,active:`Etkin`,drifted:`Onarım gerekli`,unsupported:`Desteklenmiyor`,unknown:`Bilinmiyor`},mode:{off:`Kapalı`,compat:`Uyumluluk`,quiet:`Sessiz`,collision:`Bilinmiyor`}}};function uy(e,t){return ly[e].schema[t]}function dy(e,t){return ly[e].protection[t]}function fy(e,t){return ly[e].mode[t]}var py={sessions:`storage.bucket.sessions`,archived_sessions:`storage.bucket.archived_sessions`,logs_db:`storage.bucket.logs_db`,state_db:`storage.bucket.state_db`,attachments:`storage.bucket.attachments`,deletion_manifests:`storage.bucket.deletion_manifests`,other:`storage.bucket.other`};function my(e,t){let n=py[e.key];return n?t(n):e.label}function hy(e,t){return e===void 0?`—`:new Date(e).toLocaleDateString(t)}function gy(e,t,n){return e.rows===void 0?`—`:e.rows===null?n(`storage.rows.unknown`):e.rows.toLocaleString(t)}function _y(e,t){switch(t){case`codex_running`:return cy(e,`error.codex_running`);case`process_enumeration_failed`:return cy(e,`error.process_enumeration_failed`);case`busy`:return cy(e,`error.busy`);case`unsupported_schema`:return cy(e,`error.unsupported_schema`);case`trigger_collision`:return oy(e,`error.trigger_collision`);case`unsafe_path`:return cy(e,`error.unsafe_path`);case`database_error`:return cy(e,`error.database_error`);case`auto_vacuum_not_incremental`:return cy(e,`error.auto_vacuum_not_incremental`);case`integrity_check_failed`:return cy(e,`error.integrity_check_failed`);case`config_write_failed`:return oy(e,`error.config_write_failed`);default:return cy(e,`error.generic`)}}function vy({report:e,locale:t,t:n,busy:r,error:i,compaction:a,onAction:o}){let s=e.metrics,c=e.capabilities.protection.state===`unsupported`||e.capabilities.reclaim.state===`unsupported`,l=e.protection,u=r||e.capabilities.protection.state!==`supported`,d=l!==void 0&&e.capabilities.reclaim.state===`supported`&&(s?.reclaimableBytes??0)>0,[f,p]=(0,_.useState)(!1);return(0,Y.jsxs)(`div`,{className:`stw-section`,"data-testid":`codex-log-guard`,children:[(0,Y.jsx)(`h3`,{className:`stw-section-title`,children:n(`storage.bucket.logs_db`)}),(0,Y.jsxs)(`dl`,{className:`stw-kv`,children:[(0,Y.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Y.jsx)(`dt`,{children:n(`dash.status`)}),(0,Y.jsxs)(`dd`,{className:`stw-kv-mono`,children:[(0,Y.jsx)(`code`,{children:uy(t,e.schema.state)}),c&&e.schema.state===`unsupported`?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`span`,{"aria-hidden":`true`,children:` · `}),(0,Y.jsx)(`code`,{children:oy(t,`inspectionOnly`)})]}):null]})]}),(0,Y.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Y.jsx)(`dt`,{children:n(`storage.bucket.logs_db`)}),(0,Y.jsx)(`dd`,{className:`stw-kv-mono`,children:iy(e.files.databaseBytes,t)})]}),(0,Y.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Y.jsx)(`dt`,{children:(0,Y.jsx)(`code`,{children:`WAL`})}),(0,Y.jsx)(`dd`,{className:`stw-kv-mono`,children:iy(e.files.walBytes,t)})]}),(0,Y.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Y.jsx)(`dt`,{children:(0,Y.jsx)(`code`,{children:`SHM`})}),(0,Y.jsx)(`dd`,{className:`stw-kv-mono`,children:iy(e.files.shmBytes,t)})]}),s&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Y.jsx)(`dt`,{children:n(`storage.col.rows`)}),(0,Y.jsx)(`dd`,{className:`stw-kv-mono`,children:s.totalRows.toLocaleString(t)})]}),(0,Y.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Y.jsx)(`dt`,{children:(0,Y.jsx)(`code`,{children:`TRACE`})}),(0,Y.jsxs)(`dd`,{className:`stw-kv-mono`,children:[(s.traceShare*100).toFixed(1),`%`]})]}),(0,Y.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Y.jsx)(`dt`,{children:(0,Y.jsx)(`code`,{children:`freelist`})}),(0,Y.jsx)(`dd`,{className:`stw-kv-mono`,children:iy(s.reclaimableBytes,t)})]})]}),!s&&e.metricsSkipped&&(0,Y.jsxs)(`div`,{className:`stw-kv-row`,"data-testid":`log-guard-metrics-skipped`,children:[(0,Y.jsx)(`dt`,{children:n(`storage.col.rows`)}),(0,Y.jsx)(`dd`,{className:`muted`,children:oy(t,`metricsSkippedLarge`).replace(`{threshold}`,iy(e.metricsSkipped.thresholdBytes,t))})]}),(0,Y.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Y.jsx)(`dt`,{children:(0,Y.jsx)(`code`,{children:`sqlite_home`})}),(0,Y.jsx)(`dd`,{className:`stw-kv-mono`,children:(0,Y.jsx)(`code`,{children:e.externalSqliteHome?oy(t,`externalSqliteHome`):`CODEX_HOME`})})]})]}),l&&(0,Y.jsxs)(`div`,{className:`stw-section`,"data-testid":`log-guard-protection`,children:[(0,Y.jsx)(`h4`,{className:`stw-section-title`,children:oy(t,`protection`)}),(0,Y.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Y.jsx)(`span`,{className:`muted`,children:(0,Y.jsx)(`code`,{children:dy(t,l.state)})}),(0,Y.jsxs)(`span`,{className:`stw-kv-mono`,children:[(0,Y.jsx)(`code`,{children:fy(t,l.desiredMode)}),l.observedMode===l.desiredMode?null:(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`span`,{"aria-hidden":`true`,children:` · `}),(0,Y.jsx)(`code`,{children:fy(t,l.observedMode)})]})]})]}),(0,Y.jsxs)(`div`,{className:`storage-policy-actions`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"data-testid":`log-guard-protect-compat`,disabled:u,"aria-pressed":l.desiredMode===`compat`,onClick:()=>o({action:`protect`,mode:`compat`}),children:oy(t,`compat`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"data-testid":`log-guard-protect-quiet`,disabled:u,"aria-pressed":l.desiredMode===`quiet`,onClick:()=>o({action:`protect`,mode:`quiet`}),children:oy(t,`quiet`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"data-testid":`log-guard-unprotect`,disabled:u||l.desiredMode===`off`,onClick:()=>o({action:`unprotect`}),children:oy(t,`disable`)}),l.state===`drifted`&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-sm`,"data-testid":`log-guard-repair`,disabled:u,onClick:()=>o({action:`repair`}),children:oy(t,`repair`)}),r&&(0,Y.jsx)(`span`,{className:`muted`,role:`status`,children:cy(t,`applying`)})]}),i&&(0,Y.jsx)(`p`,{className:`err`,role:`alert`,children:i})]}),d&&(0,Y.jsx)(`div`,{className:`stw-section`,"data-testid":`log-guard-reclaim`,children:(0,Y.jsx)(`div`,{className:`storage-policy-actions`,children:f?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-sm`,"data-testid":`log-guard-compact-confirm`,disabled:r,onClick:()=>{p(!1),o({action:`compact`})},children:oy(t,`confirmCompact`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:r,onClick:()=>p(!1),children:oy(t,`cancel`)})]}):(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"data-testid":`log-guard-compact`,disabled:r,onClick:()=>p(!0),children:oy(t,`compact`)})})}),a&&(0,Y.jsx)(`div`,{className:`stw-section`,children:(0,Y.jsx)(`p`,{className:`stw-kv-mono`,role:`status`,"data-testid":`log-guard-compact-result`,children:a})}),s&&s.topTargets.length>0&&(0,Y.jsxs)(`div`,{className:`stw-section`,children:[(0,Y.jsx)(`h4`,{className:`stw-section-title`,children:(0,Y.jsx)(`code`,{children:`target`})}),s.topTargets.slice(0,5).map(e=>(0,Y.jsxs)(`div`,{className:`stw-file-row`,children:[(0,Y.jsx)(`span`,{className:`stw-file-path`,title:e.target,children:(0,Y.jsx)(`code`,{children:e.target})}),(0,Y.jsx)(`span`,{className:`stw-file-size`,children:e.rows.toLocaleString(t)})]},e.target))]}),(0,Y.jsx)(`p`,{className:`stw-hint`,children:(0,Y.jsxs)(`code`,{children:[`immutable=1 · snapshot=`,e.snapshot]})})]})}function yy({locale:e,t}){return(0,Y.jsxs)(`div`,{className:`stw-section`,"data-testid":`codex-log-guard-unavailable`,children:[(0,Y.jsx)(`h3`,{className:`stw-section-title`,children:t(`storage.bucket.logs_db`)}),(0,Y.jsx)(`p`,{className:`stw-hint`,children:oy(e,`inspectionUnavailable`)})]})}function by({report:e,locale:t,apiBase:n=``,logGuardBusy:r=!1,onLogGuardAction:i}){let a=Q(),[o,s]=(0,_.useState)(null),[c,l]=(0,_.useState)(null),[u,d]=(0,_.useState)(!1),[f,p]=(0,_.useState)(null),[m,h]=(0,_.useState)(null),g=(0,_.useMemo)(()=>e.buckets.toSorted((e,t)=>t.bytes-e.bytes),[e.buckets]),v=g.find(e=>e.key===o)??null,y=c?.generation===e.generatedAt?c.report:e.codexLogs??null,b=f?.generation===e.generatedAt?f.message:null,x=m?.generation===e.generatedAt?m.summary:null,S=r||u,C=(0,_.useMemo)(()=>{let t=[];for(let n of e.buckets)for(let e of n.largest??[])t.push({...e,bucketKey:n.key});return t.sort((e,t)=>t.bytes-e.bytes).slice(0,10)},[e.buckets]),w=(0,_.useMemo)(()=>new Map(e.buckets.map(e=>[e.key,e])),[e.buckets]);return(0,Y.jsxs)(`div`,{className:`storage-workspace-root`,children:[(0,Y.jsxs)(`aside`,{className:`storage-workspace-rail`,"aria-label":a(`storage.section.buckets`),children:[(0,Y.jsxs)(`div`,{className:`storage-workspace-rail-header`,children:[(0,Y.jsx)(`span`,{className:`storage-workspace-rail-title`,children:a(`storage.section.buckets`)}),(0,Y.jsx)(`span`,{className:`storage-workspace-rail-count`,children:g.length})]}),(0,Y.jsx)(`div`,{className:`storage-workspace-rail-list`,children:g.length===0?(0,Y.jsx)(`span`,{className:`storage-workspace-rail-empty`,children:a(`storage.empty`)}):g.map(e=>(0,Y.jsxs)(`button`,{type:`button`,className:`storage-workspace-rail-row${o===e.key?` storage-workspace-rail-row--selected`:``}`,onClick:()=>s(t=>t===e.key?null:e.key),"aria-current":o===e.key?`true`:void 0,children:[(0,Y.jsxs)(`span`,{className:`storage-workspace-rail-primary`,children:[(0,Y.jsx)(`span`,{className:`storage-workspace-rail-name`,children:my(e,a)}),(0,Y.jsx)(`span`,{className:`storage-workspace-rail-size`,children:iy(e.bytes,t)})]}),(0,Y.jsxs)(`span`,{className:`storage-workspace-rail-meta`,children:[e.fileCount.toLocaleString(t),` `,a(`storage.col.files`).toLowerCase()]})]},e.key))})]}),(0,Y.jsx)(`section`,{className:`storage-workspace-main`,"aria-label":v?my(v,a):a(`storage.section.largest`),children:v?(0,Y.jsxs)(`div`,{className:`stw-detail`,children:[(0,Y.jsx)(`div`,{className:`stw-detail-toolbar`,children:(0,Y.jsxs)(`button`,{type:`button`,className:`stw-detail-back`,onClick:()=>s(null),children:[(0,Y.jsx)(Ce,{className:`stw-detail-back-chevron`,"aria-hidden":`true`}),a(`modal.back`)]})}),(0,Y.jsxs)(`div`,{className:`stw-detail-body`,children:[(0,Y.jsx)(`h2`,{className:`stw-detail-title`,children:my(v,a)}),(0,Y.jsxs)(`dl`,{className:`stw-kv`,children:[(0,Y.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Y.jsx)(`dt`,{children:a(`storage.col.size`)}),(0,Y.jsx)(`dd`,{className:`stw-kv-mono`,children:iy(v.bytes,t)})]}),(0,Y.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Y.jsx)(`dt`,{children:a(`storage.col.files`)}),(0,Y.jsx)(`dd`,{className:`stw-kv-mono`,children:v.fileCount.toLocaleString(t)})]}),(0,Y.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Y.jsx)(`dt`,{children:a(`storage.col.oldest`)}),(0,Y.jsx)(`dd`,{children:hy(v.oldest,t)})]}),(0,Y.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Y.jsx)(`dt`,{children:a(`storage.col.newest`)}),(0,Y.jsx)(`dd`,{children:hy(v.newest,t)})]}),(0,Y.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Y.jsx)(`dt`,{children:a(`storage.col.rows`)}),(0,Y.jsx)(`dd`,{className:`stw-kv-mono`,children:gy(v,t,a)})]})]}),(v.largest?.length??0)>0&&(0,Y.jsxs)(`div`,{className:`stw-section`,children:[(0,Y.jsx)(`h3`,{className:`stw-section-title`,children:a(`storage.section.largest`)}),v.largest.map(e=>(0,Y.jsxs)(`div`,{className:`stw-file-row`,children:[(0,Y.jsx)(`span`,{className:`stw-file-path`,title:e.path,children:e.path}),(0,Y.jsx)(`span`,{className:`stw-file-size`,children:iy(e.bytes,t)})]},e.path))]})]})]}):(0,Y.jsxs)(`div`,{className:`stw-overview`,children:[(0,Y.jsxs)(`div`,{className:`stw-summary`,children:[(0,Y.jsxs)(`div`,{className:`stw-summary-card`,children:[(0,Y.jsx)(`div`,{className:`stw-summary-label`,children:a(`storage.card.total`)}),(0,Y.jsx)(`div`,{className:`stw-summary-value`,children:iy(e.total.bytes,t)})]}),(0,Y.jsxs)(`div`,{className:`stw-summary-card`,children:[(0,Y.jsx)(`div`,{className:`stw-summary-label`,children:a(`storage.card.files`)}),(0,Y.jsx)(`div`,{className:`stw-summary-value`,children:e.total.fileCount.toLocaleString(t)})]}),(0,Y.jsxs)(`div`,{className:`stw-summary-card`,children:[(0,Y.jsx)(`div`,{className:`stw-summary-label`,children:a(`storage.card.home`)}),(0,Y.jsx)(`div`,{className:`stw-summary-value mono stw-home-path`,title:e.codexHome,children:e.codexHome})]})]}),y?(0,Y.jsx)(vy,{report:y,locale:t,t:a,busy:S,error:b,compaction:x,onAction:r=>{if(i){i(r);return}if(u)return;let a=e.generatedAt;(async()=>{d(!0),p(null),r.action===`compact`&&h(null);try{let e=r.action===`protect`?`protect`:r.action,i={method:`POST`,...r.action===`protect`?{headers:{"content-type":`application/json`},body:JSON.stringify({mode:r.mode})}:{}},o=await fetch(`${n}/api/storage/codex-logs/${e}`,i);if(!o.ok){let e=await o.json().catch(()=>({}));p({generation:a,message:_y(t,e.error)});return}if(r.action===`compact`){let e=(await o.json().catch(()=>null))?.report;if(e){let n=iy(e.logicalBytesReclaimed??0,t),r=iy(e.physicalDatabaseBytesReclaimed??0,t),i=e.complete?oy(t,`compactComplete`):oy(t,`compactPartial`),o=e.pagesReclaimed??0,s=!e.complete&&e.stopReason?` (${e.stopReason})`:``;h({generation:a,summary:[`${i}${s}`,`${o.toLocaleString(t)} ${oy(t,`pagesUnit`)}`,`${n} / ${r}`].join(` — `)})}try{let e=await fetch(`${n}/api/storage/codex-logs`);if(e.ok){let t=await e.json();l({generation:a,report:t})}}catch{}return}let s=await o.json();l({generation:a,report:s})}catch{p({generation:a,message:cy(t,`error.generic`)})}finally{d(!1)}})()}}):e.codexLogsError===`inspect_failed`?(0,Y.jsx)(yy,{locale:t,t:a}):null,C.length>0?(0,Y.jsxs)(`div`,{className:`stw-section`,children:[(0,Y.jsx)(`h3`,{className:`stw-section-title`,children:a(`storage.section.largest`)}),C.map(e=>{let n=w.get(e.bucketKey);return(0,Y.jsxs)(`div`,{className:`stw-file-row`,children:[(0,Y.jsx)(`span`,{className:`stw-file-path`,title:e.path,children:e.path}),n&&(0,Y.jsx)(`span`,{className:`stw-file-bucket`,children:my(n,a)}),(0,Y.jsx)(`span`,{className:`stw-file-size`,children:iy(e.bytes,t)})]},`${e.bucketKey}:${e.path}`)})]}):(0,Y.jsxs)(`p`,{className:`stw-hint`,children:[(0,Y.jsx)(se,{style:{width:14,height:14,verticalAlign:`text-bottom`,marginRight:6},"aria-hidden":`true`}),a(`storage.workspace.selectBucket`)]})]})})]})}var xy=1024**3,Sy=[10,25,50],Cy=(e,t)=>{if(!(e instanceof Error))return t;let n=e.message;return n===`Failed to fetch`||n.includes(`NetworkError`)||n.includes(`network error`)||n.includes(`JSON`)||n.includes(`Unexpected end of`)?t:n||t};function wy({apiBase:e,locale:t,t:n,onDone:r}){let[i,a]=(0,_.useState)(25),[o,s]=(0,_.useState)(null),[c,l]=(0,_.useState)(!1),[u,d]=(0,_.useState)(!1),[f,p]=(0,_.useState)(!1),[m,h]=(0,_.useState)(null),[g,v]=(0,_.useState)(null),y=(0,_.useRef)(null),b=(0,_.useRef)(null),x=(0,_.useRef)(!1),S=(0,_.useCallback)((e=!1)=>{l(!1),d(!1),e&&s(null)},[]);(0,_.useEffect)(()=>{x.current=f},[f]),(0,_.useEffect)(()=>{if(!c)return;b.current=document.activeElement,y.current?.focus();let e=e=>{e.key===`Escape`&&!x.current&&S()};return window.addEventListener(`keydown`,e),()=>{window.removeEventListener(`keydown`,e),b.current?.focus()}},[c,S]);let C=(e,t,r)=>{switch(e){case`codex_busy`:return n(`storage.cleanup.err.codex_busy`);case`stale_preview`:return n(`storage.cleanup.err.stale_preview`);case`restore_pending_overlap`:return n(`storage.cleanup.err.restore_pending_overlap`);case`referenced_history`:return n(`storage.cleanup.err.referenced_history`);case`invalid_digest`:return n(`storage.cleanup.err.invalid_digest`);case`invalid_mode`:return n(`storage.cleanup.err.invalid_mode`);case`fs_failed`:return r?n(`storage.cleanup.err.fs_failed_trash`,{trashDir:r}):n(`storage.cleanup.err.fs_failed`);case`db_reconcile_failed`:return n(`storage.cleanup.err.db_reconcile_failed`);case`cleanup_failed`:return n(`storage.cleanup.err.cleanup_failed`);default:return t??n(`storage.cleanup.cleanupFailed`)}},w=e=>n(`storage.cleanup.preset`,{percent:new Intl.NumberFormat(t,{style:`percent`,maximumFractionDigits:0}).format(e/100)}),T=async()=>{p(!0),v(null),h(null);try{let t=await fetch(`${e}/api/storage/cleanup/preview`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({percent:i})});if(!t.ok){let e=await t.json().catch(()=>({}));throw Error(C(e.error,n(`storage.cleanup.previewFailed`)))}let r=await t.json();s(r),l(!0)}catch(e){v(Cy(e,n(`storage.cleanup.previewFailed`)))}finally{p(!1)}},E=async()=>{if(o){p(!0),v(null);try{let i=await fetch(`${e}/api/storage/cleanup`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({percent:o.percent,mode:u?`permanent`:`quarantine`,digest:o.digest})});if(!i.ok){let e=await i.json().catch(()=>({}));throw e.error===`stale_preview`&&S(!0),Error(C(e.error,e.message,e.trashDir))}let a=await i.json();if(!a.ok)throw a.error===`stale_preview`&&S(!0),Error(C(a.error,a.message,a.trashDir));S(!0);let s=n(u?`storage.cleanup.donePermanent`:`storage.cleanup.doneQuarantine`,{count:String(a.count),size:iy(a.bytes,t)});h(a.skippedReferencedPaths?.length?`${s} ${n(`storage.cleanup.skippedReferenced`,{count:String(a.skippedReferencedPaths.length)})}`:s),r()}catch(e){v(Cy(e,n(`storage.cleanup.cleanupFailed`)))}finally{p(!1)}}};return(0,Y.jsxs)(`section`,{className:`storage-cleanup-pane`,children:[(0,Y.jsx)(`p`,{className:`muted storage-manual-panel__help`,children:n(`storage.cleanup.help`)}),(0,Y.jsxs)(`div`,{className:`storage-manual-panel__controls`,children:[(0,Y.jsxs)(`label`,{className:`storage-manual-panel__slider`,children:[(0,Y.jsx)(`span`,{className:`muted mono`,style:{minWidth:`3.5rem`,fontVariantNumeric:`tabular-nums`},children:n(`storage.cleanup.percent`,{percent:String(i)})}),(0,Y.jsx)(`input`,{type:`range`,min:1,max:100,value:i,onChange:e=>a(Number(e.target.value)),disabled:f,style:{flex:1,minWidth:0},"aria-label":n(`storage.cleanup.slider`)})]}),(0,Y.jsx)(`div`,{className:`storage-manual-panel__presets`,children:Sy.map(e=>(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm${i===e?` active`:``}`,disabled:f,onClick:()=>a(e),children:w(e)},e))}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:f,onClick:()=>void T(),children:n(`storage.cleanup.preview`)})]}),m&&(0,Y.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:m}),g&&!c&&(0,Y.jsx)(`p`,{className:`storage-manual-panel__status`,style:{color:`var(--red)`},children:g}),c&&o&&(0,Y.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`storage-cleanup-confirm-title`,onClick:()=>!f&&S(),children:(0,Y.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Y.jsx)(`h3`,{id:`storage-cleanup-confirm-title`,children:n(`storage.cleanup.confirmTitle`)}),(0,Y.jsx)(`p`,{children:n(`storage.cleanup.confirmBody`,{count:String(o.count),size:iy(o.bytes,t),percent:String(o.percent)})}),o.candidates.length>0&&(0,Y.jsxs)(`ul`,{className:`mono muted`,style:{maxHeight:160,overflow:`auto`,fontSize:`var(--text-caption)`},children:[o.candidates.slice(0,8).map(e=>(0,Y.jsx)(`li`,{children:e.relPath},e.relPath)),o.count>8&&(0,Y.jsx)(`li`,{children:n(`storage.cleanup.moreFiles`,{n:String(Math.max(0,o.count-8))})})]}),(0,Y.jsxs)(`label`,{style:{display:`flex`,gap:8,alignItems:`center`,marginTop:12},children:[(0,Y.jsx)(`input`,{type:`checkbox`,checked:u,disabled:f,onChange:e=>d(e.target.checked)}),(0,Y.jsx)(`span`,{children:n(`storage.cleanup.permanent`)})]}),(0,Y.jsx)(`p`,{className:`muted`,style:{marginTop:8,fontSize:`var(--text-caption)`},children:n(u?`storage.cleanup.permanentWarn`:`storage.cleanup.quarantineNote`)}),g&&(0,Y.jsx)(`p`,{style:{marginTop:12,color:`var(--red)`},children:g}),(0,Y.jsxs)(`div`,{className:`dialog-actions`,style:{marginTop:16},children:[(0,Y.jsx)(`button`,{ref:y,type:`button`,className:`btn btn-ghost`,disabled:f,onClick:()=>S(),children:n(`storage.cleanup.cancel`)}),(0,Y.jsx)(`button`,{type:`button`,className:u?`btn btn-danger`:`btn`,disabled:f||o.count===0,onClick:()=>void E(),children:n(u?`storage.cleanup.confirmPermanent`:`storage.cleanup.confirmQuarantine`)})]})]})})]})}function Ty({apiBase:e,locale:t,t:n,onDone:r,reloadToken:i,onEntriesChange:a}){let[o,s]=(0,_.useState)(!1),[c,l]=(0,_.useState)(null),[u,d]=(0,_.useState)(null),[f,p]=(0,_.useState)(null),m=(0,_.useRef)(null),h=(0,_.useRef)(null),g=(0,_.useRef)(!1);(0,_.useEffect)(()=>{g.current=o},[o]);let v=(0,_.useCallback)(()=>l(null),[]);(0,_.useEffect)(()=>{if(!c)return;h.current=document.activeElement,m.current?.focus();let e=e=>{e.key===`Escape`&&!g.current&&v()};return window.addEventListener(`keydown`,e),()=>{window.removeEventListener(`keydown`,e),h.current?.focus()}},[c,v]);let y=(0,_.useCallback)(async t=>{let r=await fetch(`${e}/api/storage/trash`,{signal:t});if(!r.ok)throw Error(n(`storage.trash.listFailed`));let i=await r.json(),o=Array.isArray(i.entries)?i.entries:[];return a?.(o),o},[e,a,n]),b=jr(`storage-trash:${e}`,[e,i],y,{isEmpty:e=>e.length===0}).state,x=b.data??[],S=(e,t)=>{switch(e){case`codex_busy`:return n(`storage.trash.err.codex_busy`);case`invalid_trash`:return n(`storage.trash.err.invalid_trash`);case`missing_trash`:return n(`storage.trash.err.missing_trash`);case`dest_exists`:return n(`storage.trash.err.dest_exists`);case`fs_failed`:return n(`storage.trash.err.fs_failed`);case`db_reconcile_failed`:return n(`storage.trash.err.db_reconcile_failed`);case`storage_mutation_busy`:return n(`storage.trash.err.storage_mutation_busy`);case`restore_failed`:return n(`storage.trash.err.restore_failed`);case`restore_worker_timeout`:return n(`storage.trash.err.restore_worker_timeout`);case`restore_worker_aborted`:return n(`storage.trash.err.restore_worker_aborted`);case`restore_worker_failed`:return t??n(`storage.trash.err.restore_worker_failed`);default:return t??n(`storage.trash.restoreFailed`)}},C=async()=>{if(c){s(!0),p(null);try{let i=await fetch(`${e}/api/storage/trash/restore`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({id:c.id})});if(!i.ok){let e=await i.json().catch(()=>({}));throw Error(S(e.error,e.message))}let a=await i.json();if(!a.ok)throw Error(S(a.error,a.message));v(),d(n(`storage.trash.done`,{count:String(a.count),size:iy(a.bytes,t)})),r()}catch(e){p(Cy(e,n(`storage.trash.restoreFailed`)))}finally{s(!1)}}},w=e=>{let n=e.quarantinedAt??Number(e.epoch.split(`-`)[0]);return!Number.isFinite(n)||n<=0?`—`:new Date(n).toLocaleString(t)},T=e=>e===`permanent`?n(`storage.trash.mode.permanent`):e===`quarantine`?n(`storage.trash.mode.quarantine`):`—`;return(0,Y.jsxs)(`section`,{className:`storage-cleanup-pane storage-quarantine-pane`,children:[(0,Y.jsx)(`p`,{className:`muted storage-manual-panel__help`,children:n(`storage.trash.help`)}),u&&(0,Y.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:u}),f&&!c&&(0,Y.jsx)(`p`,{className:`storage-manual-panel__status`,style:{color:`var(--red)`},role:`alert`,children:f}),b.showError&&!c&&(0,Y.jsx)(`p`,{className:`storage-manual-panel__status`,style:{color:`var(--red)`},role:`alert`,children:b.error instanceof Error?b.error.message:n(`storage.trash.listFailed`)}),b.refreshing&&!b.showSkeleton&&(0,Y.jsx)(tp,{live:!b.showError,children:n(`storage.trash.loading`)}),b.showSkeleton?(0,Y.jsx)(ep,{label:n(`storage.trash.loading`),rows:2}):x.length===0?(0,Y.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.trash.empty`)}):(0,Y.jsx)(`div`,{className:`tbl-wrap storage-manual-panel__table`,children:(0,Y.jsxs)(`table`,{className:`tbl`,children:[(0,Y.jsx)(`thead`,{children:(0,Y.jsxs)(`tr`,{children:[(0,Y.jsx)(`th`,{children:n(`storage.trash.col.when`)}),(0,Y.jsx)(`th`,{className:`num`,children:n(`storage.trash.col.files`)}),(0,Y.jsx)(`th`,{className:`num`,children:n(`storage.trash.col.size`)}),(0,Y.jsx)(`th`,{children:n(`storage.trash.col.mode`)}),(0,Y.jsx)(`th`,{children:n(`storage.trash.col.id`)}),(0,Y.jsx)(`th`,{})]})}),(0,Y.jsx)(`tbody`,{children:x.map(e=>(0,Y.jsxs)(`tr`,{children:[(0,Y.jsx)(`td`,{className:`muted`,children:w(e)}),(0,Y.jsx)(`td`,{className:`num`,children:e.fileCount}),(0,Y.jsx)(`td`,{className:`num mono`,children:iy(e.bytes,t)}),(0,Y.jsx)(`td`,{className:`muted`,children:T(e.mode)}),(0,Y.jsx)(`td`,{className:`mono`,style:{fontSize:`var(--text-caption)`},children:e.id}),(0,Y.jsx)(`td`,{children:(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:o,onClick:()=>{p(null),l(e)},children:n(`storage.trash.restore`)})})]},e.id))})]})}),c&&(0,Y.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`storage-trash-confirm-title`,onClick:()=>!o&&v(),children:(0,Y.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Y.jsx)(`h3`,{id:`storage-trash-confirm-title`,children:n(`storage.trash.confirmTitle`)}),(0,Y.jsx)(`p`,{children:n(`storage.trash.confirmBody`,{count:String(c.fileCount),size:iy(c.bytes,t),id:c.id})}),f&&(0,Y.jsx)(`p`,{style:{marginTop:12,color:`var(--red)`},children:f}),(0,Y.jsxs)(`div`,{className:`dialog-actions`,style:{marginTop:16},children:[(0,Y.jsx)(`button`,{ref:m,type:`button`,className:`btn btn-ghost`,disabled:o,onClick:()=>v(),children:n(`storage.trash.cancel`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn`,disabled:o,onClick:()=>void C(),children:n(`storage.trash.confirmRestore`)})]})]})})]})}function Ey(e){let{job:t,...n}=e;return n}function Dy(e){let t=String(Math.max(0,Math.round(e.trigger.archivedBytesOver/xy*100)/100));return e.target.reduceToBytes===void 0?{policy:Ey(e),thresholdGb:t,targetMode:`percent`,percent:String(Math.min(100,Math.max(1,Math.floor(e.target.removeOldestPercent??25)))),reduceGb:`4`}:{policy:Ey(e),thresholdGb:t,targetMode:`reduce`,percent:`25`,reduceGb:String(Math.max(0,Math.round(e.target.reduceToBytes/xy*100)/100))}}async function Oy(e){await new Promise(t=>window.setTimeout(t,e))}function ky({apiBase:e,locale:t,t:n,onDone:r}){let i=`ocx.storage.cleanup-policy.v1:${e}`,a=Tr(i),o=(0,_.useRef)(!!a),[s,c]=(0,_.useState)(()=>a?.policy??null),[l,u]=(0,_.useState)(()=>!a),[d,f]=(0,_.useState)(!1),[p,m]=(0,_.useState)(!1),[h,g]=(0,_.useState)(null),[v,y]=(0,_.useState)(null),[b,x]=(0,_.useState)(()=>a?.targetMode??`percent`),[S,C]=(0,_.useState)(()=>a?.percent??`25`),[w,T]=(0,_.useState)(()=>a?.reduceGb??`4`),[E,D]=(0,_.useState)(()=>a?.thresholdGb??`5`),O=(0,_.useRef)(null),k=(0,_.useRef)(!1),A=(0,_.useRef)(!1),j=(0,_.useRef)(0),M=(0,_.useCallback)(e=>{let t=Dy(e);c(t.policy),D(t.thresholdGb),x(t.targetMode),C(t.percent),T(t.reduceGb),o.current=!0,kr(i,t),k.current=!1},[i]),N=(0,_.useCallback)(()=>{k.current=!0},[]),P=(0,_.useCallback)(e=>{A.current=e},[]),F=(0,_.useCallback)(async t=>{let r=++j.current;o.current||u(!0),y(null);try{let n=await fetch(`${e}/api/storage/cleanup-policy`,{signal:t});if(!n.ok)throw Error(`load_failed`);let i=await n.json();if(t?.aborted||r!==j.current||k.current||A.current)return;M(i)}catch{if(t?.aborted||r!==j.current)return;o.current||(c(null),y(n(`storage.policy.loadFailed`)))}finally{!t?.aborted&&r===j.current&&u(!1)}},[e,M,n]);(0,_.useEffect)(()=>{let e=new AbortController,t=window.setTimeout(()=>{F(e.signal)},0);return()=>{window.clearTimeout(t),j.current+=1,e.abort()}},[F]),(0,_.useEffect)(()=>()=>{O.current?.abort(),O.current=null},[]);let I=()=>{if(!s)return null;let e=E.trim();if(e===``)return null;let t=Number(e);if(!Number.isFinite(t)||t<0)return null;let n;if(b===`reduce`){let e=w.trim();if(e===``)return null;let t=Number(e);if(!Number.isFinite(t)||t<0)return null;n={reduceToBytes:Math.floor(t*xy)}}else{let e=Number(S);if(!Number.isFinite(e)||e<1||e>100)return null;n={removeOldestPercent:Math.min(100,Math.max(1,Math.floor(e)))}}return{enabled:s.enabled,trigger:{archivedBytesOver:Math.floor(t*xy)},target:n,schedule:s.schedule,mode:s.mode}},L=async t=>{let r=I();if(!r){y(n(`storage.policy.invalid`));return}let i={...r,...t};f(!0),y(null),g(null);try{let t=await fetch(`${e}/api/storage/cleanup-policy`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(i)});if(!t.ok){y(n(`storage.policy.saveFailed`));return}let r=await t.json();if(!r.policy){y(n(`storage.policy.saveFailed`));return}M(r.policy),g(n(`storage.policy.saved`))}catch{y(n(`storage.policy.saveFailed`))}finally{f(!1)}},R=async()=>{O.current?.abort();let i=new AbortController;O.current=i;let{signal:a}=i;m(!0),y(null),g(null);try{let i=I();if(!i){y(n(`storage.policy.invalid`));return}let o=await fetch(`${e}/api/storage/cleanup-policy`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(i),signal:a});if(a.aborted)return;if(!o.ok){y(n(`storage.policy.saveFailed`));return}let s=await o.json();if(a.aborted)return;if(!s.policy){y(n(`storage.policy.saveFailed`));return}M(s.policy);let c=await fetch(`${e}/api/storage/cleanup-policy/run`,{method:`POST`,signal:a});if(a.aborted)return;if(c.status===409){let e=await c.json().catch(()=>({}));if(a.aborted)return;e.policy&&M(e.policy),y(n(`storage.policy.alreadyRunning`));return}if(!c.ok){let e=await c.json().catch(()=>({}));if(a.aborted)return;if(e.policy&&M(e.policy),e.error===`already_running`){y(n(`storage.policy.alreadyRunning`));return}y(n(`storage.policy.runFailed`));return}let l=await c.json();if(a.aborted)return;if(l.policy&&M(l.policy),l.error===`already_running`){y(n(`storage.policy.alreadyRunning`));return}if(!l.started||!l.job?.startedAt){y(n(`storage.policy.runFailed`));return}let u=l.job.startedAt,d=Date.now()+12e4,f,p;for(;Date.now()<d;){if(a.aborted||(await Oy(250),a.aborted))return;let t=await fetch(`${e}/api/storage/cleanup-policy`,{signal:a});if(a.aborted)return;if(!t.ok)continue;let n=await t.json();if(a.aborted)return;p=Ey(n),M(n);let r=n.job;if(r&&r.status!==`running`){if(r.startedAt===u&&r.lastOutcome){f=r.lastOutcome;break}if(r.finishedAt&&r.finishedAt>=u&&r.lastOutcome){f=r.lastOutcome;break}}}if(a.aborted)return;if(p&&M(p),!f){y(n(`storage.policy.runFailed`));return}f.skipped===`disabled`?g(n(`storage.policy.skippedDisabled`)):f.ok&&f.metadataPersistenceError?(y(n(`storage.policy.metadataSaveWarning`)),f.removed!==void 0&&r()):f.skipped===`under_threshold`?g(n(`storage.policy.skippedUnder`)):f.skipped===`nothing_selected`?g(n(`storage.policy.skippedEmpty`)):f.deferred===`codex_busy`||f.error===`codex_busy`?y(n(`storage.cleanup.err.codex_busy`)):f.ok?(g(f.mode===`permanent`?n(`storage.policy.donePermanent`,{count:String(f.removed??0),size:iy(f.freedBytes??0,t)}):n(`storage.policy.doneQuarantine`,{count:String(f.removed??0),size:iy(f.freedBytes??0,t)})),r()):y(n(`storage.policy.runFailed`))}catch(e){if(a.aborted||e instanceof DOMException&&e.name===`AbortError`)return;y(n(`storage.policy.runFailed`))}finally{O.current===i&&(O.current=null),a.aborted||m(!1)}},z=e=>e===void 0?n(`storage.policy.never`):new Date(e).toLocaleString(t);return l&&!s?(0,Y.jsx)(`section`,{className:`storage-cleanup-pane`,children:(0,Y.jsx)(`p`,{className:`muted storage-policy-help`,children:n(`storage.policy.loading`)})}):s?(0,Y.jsxs)(`section`,{className:`storage-cleanup-pane`,children:[(0,Y.jsx)(`p`,{className:`muted storage-policy-help`,children:n(`storage.policy.help`)}),(0,Y.jsx)(`div`,{className:`storage-policy-enable`,children:(0,Y.jsxs)(`div`,{className:`storage-policy-enable-row`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`toggle${s.enabled?` on`:``}`,disabled:d||p,"aria-pressed":s.enabled,"aria-label":n(`storage.policy.enabled`),title:n(`storage.policy.enabledHint`),onClick:()=>void L({enabled:!s.enabled}),children:(0,Y.jsx)(`span`,{className:`toggle-knob`})}),(0,Y.jsx)(`span`,{children:n(`storage.policy.enabled`)})]})}),(0,Y.jsxs)(`div`,{className:`storage-policy-fields`,children:[(0,Y.jsxs)(`div`,{className:`field storage-policy-trigger`,children:[(0,Y.jsx)(`label`,{className:`field-label`,htmlFor:`storage-policy-threshold`,children:n(`storage.policy.trigger`)}),(0,Y.jsxs)(`div`,{className:`storage-policy-trigger-row`,children:[(0,Y.jsx)(`span`,{className:`storage-policy-trigger-hint`,children:n(`storage.policy.threshold`)}),(0,Y.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(P(!1),L())},children:[(0,Y.jsx)(`input`,{id:`storage-policy-threshold`,className:`input mono codex-auto-switch-input`,type:`number`,min:0,step:.1,inputMode:`decimal`,value:E,disabled:d||p,"aria-label":n(`storage.policy.threshold`),onFocus:()=>P(!0),onChange:e=>{N(),D(e.target.value)},onKeyDown:e=>{e.nativeEvent.isComposing||d||p||e.key===`Enter`&&(e.preventDefault(),L())}}),(0,Y.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`GiB`}),(0,Y.jsx)(yc,{disabled:d||p,incrementLabel:n(`storage.policy.thresholdInc`),decrementLabel:n(`storage.policy.thresholdDec`),onIncrement:()=>{N(),D(vc(E,.1,0,1e4,.1))},onDecrement:()=>{N(),D(vc(E,-.1,0,1e4,.1))}})]})]})]}),(0,Y.jsxs)(`fieldset`,{className:`field storage-policy-target`,children:[(0,Y.jsx)(`legend`,{className:`field-label`,children:n(`storage.policy.target`)}),(0,Y.jsxs)(`label`,{className:`storage-policy-target-row`,children:[(0,Y.jsx)(`input`,{type:`radio`,name:`storage-policy-target`,checked:b===`percent`,disabled:d||p,onChange:()=>{N(),x(`percent`)}}),(0,Y.jsx)(`span`,{className:`storage-policy-target-label`,children:n(`storage.policy.targetPercent`)}),b===`percent`&&(0,Y.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(P(!1),L())},children:[(0,Y.jsx)(`input`,{id:`storage-policy-percent`,className:`input mono codex-auto-switch-input`,type:`number`,min:1,max:100,step:1,inputMode:`numeric`,value:S,disabled:d||p,"aria-label":n(`storage.policy.targetPercent`),onFocus:()=>P(!0),onChange:e=>{N(),C(e.target.value)},onKeyDown:e=>{e.nativeEvent.isComposing||d||p||e.key===`Enter`&&(e.preventDefault(),L())}}),(0,Y.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`%`}),(0,Y.jsx)(yc,{disabled:d||p,incrementLabel:n(`storage.policy.percentInc`),decrementLabel:n(`storage.policy.percentDec`),onIncrement:()=>{N(),C(vc(S,1,1,100))},onDecrement:()=>{N(),C(vc(S,-1,1,100))}})]})]}),(0,Y.jsxs)(`label`,{className:`storage-policy-target-row`,children:[(0,Y.jsx)(`input`,{type:`radio`,name:`storage-policy-target`,checked:b===`reduce`,disabled:d||p,onChange:()=>{N(),x(`reduce`)}}),(0,Y.jsx)(`span`,{className:`storage-policy-target-label`,children:n(`storage.policy.targetReduce`)}),b===`reduce`&&(0,Y.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(P(!1),L())},children:[(0,Y.jsx)(`input`,{id:`storage-policy-reduce`,className:`input mono codex-auto-switch-input`,type:`number`,min:0,step:.1,inputMode:`decimal`,value:w,disabled:d||p,"aria-label":n(`storage.policy.targetReduce`),onFocus:()=>P(!0),onChange:e=>{N(),T(e.target.value)},onKeyDown:e=>{e.nativeEvent.isComposing||d||p||e.key===`Enter`&&(e.preventDefault(),L())}}),(0,Y.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`GiB`}),(0,Y.jsx)(yc,{disabled:d||p,incrementLabel:n(`storage.policy.reduceInc`),decrementLabel:n(`storage.policy.reduceDec`),onIncrement:()=>{N(),T(vc(w,.1,0,1e4,.1))},onDecrement:()=>{N(),T(vc(w,-.1,0,1e4,.1))}})]})]})]}),(0,Y.jsxs)(`div`,{className:`storage-policy-selects`,children:[(0,Y.jsxs)(`label`,{className:`field`,htmlFor:`storage-policy-schedule`,children:[(0,Y.jsx)(`span`,{className:`field-label`,children:n(`storage.policy.schedule`)}),(0,Y.jsxs)(`select`,{id:`storage-policy-schedule`,className:`input`,value:s.schedule,disabled:d||p,onChange:e=>{let t=e.target.value;L({schedule:t})},children:[(0,Y.jsx)(`option`,{value:`manual`,children:n(`storage.policy.schedule.manual`)}),(0,Y.jsx)(`option`,{value:`startup`,children:n(`storage.policy.schedule.startup`)}),(0,Y.jsx)(`option`,{value:`daily`,children:n(`storage.policy.schedule.daily`)}),(0,Y.jsx)(`option`,{value:`weekly`,children:n(`storage.policy.schedule.weekly`)})]})]}),(0,Y.jsxs)(`label`,{className:`field`,htmlFor:`storage-policy-mode`,children:[(0,Y.jsx)(`span`,{className:`field-label`,children:n(`storage.policy.mode`)}),(0,Y.jsxs)(`select`,{id:`storage-policy-mode`,className:`input`,value:s.mode,disabled:d||p,onChange:e=>{let t=e.target.value;L({mode:t})},children:[(0,Y.jsx)(`option`,{value:`quarantine`,children:n(`storage.policy.mode.quarantine`)}),(0,Y.jsx)(`option`,{value:`permanent`,children:n(`storage.policy.mode.permanent`)})]})]})]}),s.mode===`permanent`&&(0,Y.jsx)(`p`,{className:`err storage-policy-warn`,role:`status`,children:n(`storage.policy.permanentWarn`)})]}),(0,Y.jsxs)(`div`,{className:`storage-policy-meta`,children:[(0,Y.jsxs)(`div`,{className:`storage-policy-meta-item`,children:[(0,Y.jsx)(`span`,{className:`muted`,children:n(`storage.policy.lastRun`)}),(0,Y.jsxs)(`span`,{className:`storage-policy-meta-value`,children:[z(s.lastRun?.at),s.lastRun?` · ${n(`storage.policy.lastRunDetail`,{count:String(s.lastRun.removed),size:iy(s.lastRun.freedBytes,t)})}`:``]})]}),(0,Y.jsxs)(`div`,{className:`storage-policy-meta-item`,children:[(0,Y.jsx)(`span`,{className:`muted`,children:n(`storage.policy.nextRun`)}),(0,Y.jsx)(`span`,{className:`storage-policy-meta-value`,children:z(s.nextRun)})]})]}),(0,Y.jsxs)(`div`,{className:`storage-policy-actions`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:d||p,onClick:()=>void L(),children:n(`storage.policy.save`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:d||p,onClick:()=>void R(),children:n(p?`storage.policy.running`:`storage.policy.runNow`)}),(0,Y.jsx)(`span`,{className:`storage-policy-actions__status${v?` is-error`:``}`,role:v?`alert`:`status`,"aria-live":`polite`,children:v??h??``})]})]}):(0,Y.jsx)(`section`,{className:`storage-cleanup-pane`,children:v&&(0,Y.jsx)(`p`,{className:`err`,role:`alert`,children:v})})}function Ay({apiBase:e,locale:t,t:n,archivedCount:r,showQuarantine:i,trashReloadToken:a,onDone:o,onTrashEntriesChange:s}){let[c,l]=(0,_.useState)(`policy`),u=(0,_.useRef)(null),d=(0,_.useRef)(null),f=[{id:`policy`,label:n(`storage.cleanupCard.tab.policy`),ref:u},{id:`quarantine`,label:n(`storage.cleanupCard.tab.quarantine`),ref:d}],p=e=>{l(e),window.requestAnimationFrame(()=>(e===`policy`?u:d).current?.focus())},m=e=>{e.key===`ArrowLeft`||e.key===`ArrowRight`?(e.preventDefault(),p(c===`policy`?`quarantine`:`policy`)):e.key===`Home`?(e.preventDefault(),p(`policy`)):e.key===`End`&&(e.preventDefault(),p(`quarantine`))};return(0,Y.jsxs)(`section`,{className:`panel storage-cleanup-card`,"aria-labelledby":`storage-cleanup-card-title`,children:[(0,Y.jsx)(`div`,{className:`page-tabs storage-cleanup-card__tabs`,role:`tablist`,"aria-label":n(`storage.cleanupCard.tabs`),children:f.map(({id:e,label:t,ref:n})=>(0,Y.jsx)(`button`,{type:`button`,role:`tab`,ref:n,id:`storage-cleanup-tab-${e}`,"aria-selected":c===e,"aria-controls":`storage-cleanup-panel-${e}`,tabIndex:c===e?0:-1,className:`page-tab${c===e?` page-tab--active`:``}`,onKeyDown:m,onClick:()=>p(e),children:t},e))}),(0,Y.jsx)(`h3`,{id:`storage-cleanup-card-title`,className:`panel-title`,children:n(`storage.cleanupCard.title`)}),(0,Y.jsxs)(`div`,{className:`storage-cleanup-card__stack`,children:[(0,Y.jsxs)(`div`,{id:`storage-cleanup-panel-policy`,role:`tabpanel`,"aria-labelledby":`storage-cleanup-tab-policy`,className:`storage-cleanup-card__body storage-cleanup-policy-split`,"data-active":c===`policy`?`true`:`false`,"aria-hidden":c!==`policy`,...c===`policy`?{}:{inert:!0},children:[(0,Y.jsx)(ky,{apiBase:e,locale:t,t:n,onDone:o}),(0,Y.jsxs)(`aside`,{className:`storage-cleanup-manual`,"aria-labelledby":`storage-cleanup-manual-title`,children:[(0,Y.jsx)(`h4`,{id:`storage-cleanup-manual-title`,className:`storage-cleanup-manual__title`,children:n(`storage.cleanup.title`)}),r>0?(0,Y.jsx)(wy,{apiBase:e,locale:t,t:n,onDone:o}):(0,Y.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.cleanup.noArchives`)})]})]}),(0,Y.jsx)(`div`,{id:`storage-cleanup-panel-quarantine`,role:`tabpanel`,"aria-labelledby":`storage-cleanup-tab-quarantine`,className:`storage-cleanup-card__body`,"data-active":c===`quarantine`?`true`:`false`,"aria-hidden":c!==`quarantine`,...c===`quarantine`?{}:{inert:!0},children:i?(0,Y.jsx)(Ty,{apiBase:e,locale:t,t:n,onDone:o,reloadToken:a,onEntriesChange:s}):(0,Y.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.trash.empty`)})})]})]})}function jy({apiBase:e}){let{t,locale:n}=ut(),r=`ocx.storage.report.v1:${e}`,i=Tr(r),[a,o]=(0,_.useState)(null),[s,c]=(0,_.useState)(0),l=(0,_.useRef)(!1),[u,d]=(0,_.useState)({apiBase:e,settled:!1,hasEntries:!1}),f=(0,_.useCallback)(async n=>{try{let i=await fetch(`${e}/api/storage`,{signal:n});if(!i.ok)throw Error(t(`storage.error`));let a=await i.json();return kr(r,a),l.current&&(l.current=!1,o(t(`storage.rescanned`))),a}catch(e){throw l.current&&(l.current=!1,o(t(`storage.error`))),n.aborted?e:Error(t(`storage.error`),{cause:e})}},[e,r,t]),p=jr(`storage-report:${e}`,[e],f,{isEmpty:e=>e.total.fileCount===0&&e.error===void 0}),m=p.state,h=m.data??i,g=m.refreshing||m.showSkeleton&&!h,v=p.refresh,y=(0,_.useCallback)(()=>{o(null),l.current=!0,v(),c(e=>e+1)},[v]),b=(0,_.useCallback)(t=>{d({apiBase:e,settled:!0,hasEntries:t.length>0})},[e]),x=u.apiBase===e&&u.settled,S=u.apiBase===e&&u.hasEntries,C=h?.error!==void 0,w=!g&&!m.showError&&!C&&h.total.fileCount===0&&x&&!S,T=h?.buckets.find(e=>e.key===`archived_sessions`)?.fileCount??0,E=!!h&&!C,D=E&&(h.total.fileCount>0||!x||S);return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{className:`page-head`,children:[(0,Y.jsx)(`h2`,{id:`storage-page-title`,children:t(`storage.title`)}),(0,Y.jsxs)(`div`,{className:`storage-page-head-actions`,children:[(0,Y.jsx)(`span`,{className:`storage-page-head-feedback`,role:`status`,"aria-live":`polite`,children:a??``}),(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:g,onClick:()=>void y(),children:[(0,Y.jsx)(de,{}),` `,t(`storage.refresh`)]})]})]}),(0,Y.jsx)(`p`,{className:`page-sub`,children:t(`storage.subtitle`)}),h&&h.error===void 0&&(0,Y.jsxs)(`p`,{className:`storage-page-meta`,children:[(0,Y.jsx)(`code`,{className:`mono storage-page-meta__home`,title:h.codexHome,children:h.codexHome}),(0,Y.jsx)(`span`,{className:`storage-page-meta__sep`,"aria-hidden":`true`,children:`·`}),(0,Y.jsxs)(`span`,{children:[t(`storage.snapshot.lastScan`),`:`,` `,new Date(h.generatedAt).toLocaleString(n)]})]}),m.showSkeleton&&!h?(0,Y.jsx)(ep,{label:t(`storage.loading`),rows:5}):m.kind===`failed-cold`&&!h?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:m.error instanceof Error?m.error.message:t(`storage.error`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>v(),children:t(`common.retry`)})]}):C?(0,Y.jsx)(Y.Fragment,{children:(0,Y.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:t(`storage.error`)})}):(0,Y.jsxs)(Y.Fragment,{children:[m.showError&&(0,Y.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:t(`storage.error`)}),w?(0,Y.jsx)(At,{title:t(`storage.empty`)}):h&&h.total.fileCount>0&&(0,Y.jsx)(by,{report:h,locale:n,apiBase:e})]}),h&&h.error===void 0&&m.refreshing&&!m.showSkeleton&&(0,Y.jsx)(tp,{live:!m.showError,children:t(`storage.loading`)}),E&&(0,Y.jsx)(Ay,{apiBase:e,locale:n,t,archivedCount:T,showQuarantine:D,trashReloadToken:s,onDone:()=>void y(),onTrashEntriesChange:b})]})}var My=`/api/codex-auth/features/default-mode-request-user-input`;function Ny({apiBase:e}){let t=Q(),[n,r]=(0,_.useState)(!1),[i,a]=(0,_.useState)(!1),[o,s]=(0,_.useState)(!1),[c,l]=(0,_.useState)(!1),[u,d]=(0,_.useState)(null),f=(0,_.useRef)(!1),p=(0,_.useRef)(!1),m=(0,_.useRef)(0),h=(0,_.useCallback)(async()=>{if(f.current)return;let t=++m.current,n=Xn(15e3);try{let i=await fetch(`${e}${My}`,{signal:n.signal});if(!i.ok)throw Error(`load`);let o=await i.json();if(f.current||t!==m.current)return;p.current=o.enabled===!0,r(p.current),a(!0),l(!1)}catch{!f.current&&t===m.current&&l(!0)}finally{n.clear()}},[e]);(0,_.useEffect)(()=>{let e=window.setTimeout(()=>{h()},0),t=er(()=>{h()},3e4);return()=>{window.clearTimeout(e),t()}},[h]);let g=(0,_.useCallback)(async()=>{if(f.current||!i||c)return;let n=!p.current,o=p.current;p.current=n,r(n),f.current=!0,s(!0),d(null),m.current++;try{let i=await fetch(`${e}${My}`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({enabled:n})}),o=await It(i)??{};if(o.ok!==!0)throw Error(String(i.status));p.current=o.enabled===!0,r(p.current),a(!0),d({tone:`ok`,message:t(o.changed===!0?`codexAuth.requestUserInputUpdatedRestart`:`codexAuth.requestUserInputUpdated`)})}catch(e){p.current=o,r(o);let n=e instanceof Error&&e.message&&!/^HTTP \d{3}$/.test(e.message)?e.message:t(`codexAuth.requestUserInputUpdateFailed`);d({tone:`err`,message:n})}finally{f.current=!1,s(!1)}},[e,i,c,t]),v=o||!i||c;return(0,Y.jsxs)(`div`,{className:`card card-row codex-request-user-input-card`,style:{marginTop:16},"aria-busy":o||!i&&!c||void 0,children:[(0,Y.jsxs)(`div`,{className:`codex-request-user-input-copy`,children:[(0,Y.jsx)(`strong`,{children:t(`codexAuth.requestUserInput`)}),(0,Y.jsx)(`div`,{className:`card-sub`,role:c?`alert`:void 0,children:t(c?`codexAuth.requestUserInputLoadFailed`:`codexAuth.requestUserInputDesc`)}),(0,Y.jsx)(`code`,{className:`mono codex-request-user-input-config`,children:`[features]
|
|
83
83
|
default_mode_request_user_input = true`})]}),(0,Y.jsxs)(`div`,{className:`codex-request-user-input-controls`,children:[c&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{h()},children:t(`common.retry`)}),(0,Y.jsx)(`button`,{type:`button`,className:`toggle ${n?`on`:``}`,onClick:()=>{g()},disabled:v,"aria-pressed":n,"aria-label":t(`codexAuth.requestUserInput`),title:t(`codexAuth.requestUserInput`),children:(0,Y.jsx)(`span`,{className:`toggle-knob`})})]}),u&&(0,Y.jsx)(`div`,{className:`codex-request-user-input-feedback${u.tone===`err`?` is-error`:``}`,role:u.tone===`err`?`alert`:`status`,"aria-atomic":`true`,children:u.message})]})}function Py({apiBase:e}){let t=Q(),[n,r]=(0,_.useState)(!1),[i,a]=(0,_.useState)(!1),[o,s]=(0,_.useState)(!1),[c,l]=(0,_.useState)(!1),[u,d]=(0,_.useState)(null),f=(0,_.useRef)(!1),p=(0,_.useRef)(0),m=(0,_.useCallback)(async()=>{if(f.current)return;let t=++p.current,n=Xn(15e3);try{let i=await fetch(`${e}/api/settings`,{signal:n.signal});if(!i.ok)throw Error(`load`);let o=await i.json();if(f.current||t!==p.current)return;r(o.ultraFastTier===!0),a(!0),l(!1)}catch{!f.current&&t===p.current&&l(!0)}finally{n.clear()}},[e]);(0,_.useEffect)(()=>{let e=window.setTimeout(()=>{m()},0),t=er(()=>{m()},3e4);return()=>{window.clearTimeout(e),t()}},[m]);let h=(0,_.useCallback)(async()=>{if(f.current||!i||c)return;let a=!n;f.current=!0,s(!0),d(null),r(a);let o=Xn(15e3);try{let n=await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({ultraFastTier:a}),signal:o.signal});if(!n.ok)throw Error(`save`);let i=await n.json(),s=typeof i.ultraFastTier==`boolean`?i.ultraFastTier:a;r(s),d({tone:`ok`,message:t(s?`codexAuth.ultraFastEnabled`:`codexAuth.ultraFastDisabled`)})}catch{r(!a),d({tone:`err`,message:t(`codexAuth.ultraFastFailed`)})}finally{o.clear(),f.current=!1,s(!1)}},[e,n,i,c,t]),g=o||!i||c;return(0,Y.jsxs)(`div`,{className:`card card-row codex-ultrafast-card`,style:{marginTop:16},"aria-busy":o||!i&&!c||void 0,children:[(0,Y.jsxs)(`div`,{className:`codex-ultrafast-copy`,children:[(0,Y.jsx)(`strong`,{children:t(`codexAuth.ultraFastTitle`)}),(0,Y.jsx)(`div`,{className:`card-sub`,role:c?`alert`:void 0,children:t(c?`codexAuth.ultraFastLoadFailed`:`codexAuth.ultraFastDesc`)})]}),(0,Y.jsxs)(`div`,{className:`codex-ultrafast-controls`,children:[c&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{m()},children:t(`common.retry`)}),(0,Y.jsx)(`button`,{type:`button`,className:`toggle ${n?`on`:``}`,onClick:()=>{h()},disabled:g,"aria-pressed":n,"aria-label":t(`codexAuth.ultraFastTitle`),title:t(`codexAuth.ultraFastTitle`),children:(0,Y.jsx)(`span`,{className:`toggle-knob`})})]}),u&&(0,Y.jsx)(`div`,{className:`codex-ultrafast-feedback${u.tone===`err`?` is-error`:``}`,role:u.tone===`err`?`alert`:`status`,"aria-atomic":`true`,children:u.message})]})}function Fy(e){if(!e||typeof e!=`object`)throw Error(`settings shape`);let t=e,n=t.mainAccountHardLock;if(typeof t.codexMainAccountHardLock!=`boolean`||!n||n.enabled!==t.codexMainAccountHardLock||!(n.enabled?[`unknown`,`ready`,`blocked`]:[`off`]).includes(n.state)||n.resetAt!==void 0&&(typeof n.resetAt!=`number`||!Number.isFinite(n.resetAt)))throw Error(`settings shape`);return t}function Iy({pending:e,onCancel:t,onConfirm:n}){let r=Q(),i=(0,_.useId)(),a=(0,_.useRef)(null),o=(0,_.useRef)(null),s=(0,_.useRef)(null);return(0,_.useEffect)(()=>{let e=a.current;return e&&!e.open&&e.showModal(),o.current?.focus(),()=>{e?.open&&e.close()}},[]),(0,Y.jsxs)(`dialog`,{ref:a,className:`modal-overlay`,"aria-labelledby":`${i}-title`,"aria-describedby":`${i}-body`,"aria-busy":e||void 0,onCancel:e=>{e.preventDefault(),t()},onKeyDown:t=>{if(t.key!==`Tab`||e)return;let n=t.shiftKey?o.current:s.current,r=t.shiftKey?s.current:o.current;document.activeElement===n&&(t.preventDefault(),r?.focus())},children:[(0,Y.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,tabIndex:-1,"aria-label":r(`common.close`),disabled:e,onClick:t}),(0,Y.jsxs)(`div`,{className:`modal-card codex-main-hard-lock-dialog`,role:`document`,children:[(0,Y.jsx)(`h3`,{id:`${i}-title`,children:r(`codexAuth.mainHardLockConfirmTitle`)}),(0,Y.jsx)(`p`,{id:`${i}-body`,className:`modal-desc`,children:r(`codexAuth.mainHardLockConfirmBody`)}),(0,Y.jsxs)(`div`,{className:`modal-actions`,children:[(0,Y.jsx)(`button`,{ref:o,type:`button`,className:`btn btn-ghost`,disabled:e,onClick:t,children:r(`codexAuth.cancel`)}),(0,Y.jsx)(`button`,{ref:s,type:`button`,className:`btn btn-primary`,disabled:e,onClick:n,children:r(e?`common.saving`:`codexAuth.mainHardLockConfirm`)})]})]})]})}function Ly(e){return(0,Y.jsx)(Ry,{...e},e.apiBase)}function Ry({apiBase:e,onSaved:t}){let n=Q(),r=(0,_.useId)(),[i,a]=(0,_.useState)(null),[o,s]=(0,_.useState)(!1),[c,l]=(0,_.useState)(!1),[u,d]=(0,_.useState)(!1),[f,p]=(0,_.useState)(null),[m,h]=(0,_.useState)(!1),[g,v]=(0,_.useState)(!1),y=(0,_.useRef)(!1),b=(0,_.useRef)(!1),x=(0,_.useRef)(0),S=(0,_.useRef)(null),C=(0,_.useRef)(null),w=(0,_.useRef)(null),T=(0,_.useRef)(!1),E=(0,_.useCallback)(async()=>{if(y.current)return;let t=++x.current;S.current?.abort();let n=Xn(15e3);S.current=n.controller;try{let r=await fetch(`${e}/api/settings`,{signal:n.signal});if(!r.ok)throw Error(`load`);let i=Fy(await r.json());if(!b.current||t!==x.current)return;a(i),s(!1),p(null)}catch{b.current&&t===x.current&&s(!0)}finally{n.clear()}},[e]);(0,_.useEffect)(()=>{b.current=!0;let e=window.setTimeout(()=>{E()},0),t=er(()=>{E()},3e4);return()=>{b.current=!1,x.current+=1,S.current?.abort(),window.clearTimeout(e),t()}},[E]),(0,_.useEffect)(()=>{g||m||!T.current||(C.current&&!C.current.disabled?(C.current.focus(),T.current=!1):w.current?.focus())},[g,m,o,i]);let D=async()=>{let e=!1;try{e=await t()}catch{}b.current&&d(!e)},O=async t=>{if(y.current||!i)return;y.current=!0,x.current+=1,S.current?.abort(),h(!0),l(!1),d(!1),p(null);let n=Xn(15e3),r=!1;try{let i=await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({codexMainAccountHardLock:t}),signal:n.signal});if(!i.ok)throw Error(`save`);let o=await i.json();if(!o||typeof o!=`object`||!(`ok`in o)||o.ok!==!0)throw Error(`unconfirmed`);let c=Fy(o);r=!0,b.current&&(a(c),s(!1),p(c.codexMainAccountHardLock))}catch{b.current&&(l(!0),s(!0))}finally{n.clear()}r&&await D(),y.current=!1,b.current&&(h(!1),v(!1),r||E())},k=()=>{y.current||v(!1)},A=async()=>{y.current||(y.current=!0,x.current+=1,h(!0),await D(),y.current=!1,b.current&&h(!1))},j=i?.codexMainAccountHardLock;return(0,Y.jsxs)(`section`,{ref:w,id:`codex-main-hard-lock-setting`,tabIndex:-1,className:`card card-row codex-main-hard-lock-setting`,"aria-labelledby":`${r}-title`,"aria-busy":m||!i&&!o||void 0,onBlurCapture:e=>{e.relatedTarget!==null&&!e.currentTarget.contains(e.relatedTarget)&&(T.current=!1)},children:[(0,Y.jsxs)(`div`,{className:`codex-main-hard-lock-copy`,children:[(0,Y.jsx)(`strong`,{id:`${r}-title`,children:n(`codexAuth.mainHardLockTitle`)}),(0,Y.jsx)(`div`,{id:`${r}-desc`,className:`card-sub`,children:n(`codexAuth.mainHardLockDesc`)})]}),(0,Y.jsx)(`button`,{ref:C,type:`button`,className:`toggle ${j===!0?`on`:``}`,disabled:m||j===void 0||o,"aria-pressed":j,"aria-label":n(`codexAuth.mainHardLockTitle`),"aria-describedby":`${r}-desc`,onClick:()=>{y.current||j===void 0||o||(T.current=!0,j?O(!1):v(!0))},children:(0,Y.jsx)(`span`,{className:`toggle-knob`})}),(0,Y.jsxs)(`div`,{className:`codex-main-hard-lock-feedback`,children:[(c||o)&&(0,Y.jsxs)(`p`,{role:`alert`,children:[n(c?`codexAuth.mainHardLockSaveFailed`:`codexAuth.mainHardLockLoadFailed`),` `,(0,Y.jsx)(`button`,{type:`button`,className:`link-btn`,disabled:m,onClick:()=>{E()},children:n(`common.retry`)})]}),f!==null&&!u&&(0,Y.jsx)(`p`,{role:`status`,children:n(f?`codexAuth.mainHardLockEnabled`:`codexAuth.mainHardLockDisabled`)}),u&&(0,Y.jsxs)(`p`,{role:`status`,children:[n(`codexAuth.mainHardLockRefreshFailed`),` `,(0,Y.jsx)(`button`,{type:`button`,className:`link-btn`,disabled:m,onClick:()=>{A()},children:n(`common.retry`)})]})]}),g&&(0,Y.jsx)(Iy,{pending:m,onCancel:k,onConfirm:()=>{O(!0)}})]})}function zy({apiBase:e}){let t=Q(),[n,r]=(0,_.useState)(!1),[i,a]=(0,_.useState)(!1),[o,s]=(0,_.useState)(!1),[c,l]=(0,_.useState)(!1),[u,d]=(0,_.useState)(null),f=(0,_.useRef)(!1),p=(0,_.useRef)(!1),m=(0,_.useRef)(0),h=(0,_.useCallback)(async()=>{if(p.current)return;let t=++m.current,n=Xn(15e3);try{let i=await fetch(`${e}/api/settings`,{signal:n.signal});if(!i.ok)throw Error(`load`);let o=await i.json();if(p.current||t!==m.current)return;if(typeof o.codexAccountPickerEnabled!=`boolean`)throw Error(`shape`);f.current=o.codexAccountPickerEnabled,r(o.codexAccountPickerEnabled),a(!0),l(!1)}catch{!p.current&&t===m.current&&l(!0)}finally{n.clear()}},[e]);(0,_.useEffect)(()=>{let e=window.setTimeout(()=>{h()},0),t=er(()=>{h()},3e4);return()=>{window.clearTimeout(e),t()}},[h]);let g=(0,_.useCallback)(async()=>{if(p.current||!i)return;let n=f.current,o=!n;f.current=o,r(o),p.current=!0,s(!0),d(null),m.current+=1;try{let n=await It(await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({codexAccountPickerEnabled:o})}))??{};if(n.ok!==!0||typeof n.codexAccountPickerEnabled!=`boolean`)throw Error(`unconfirmed`);f.current=n.codexAccountPickerEnabled,r(n.codexAccountPickerEnabled),a(!0),l(!1),d(n.catalogRefreshPending===!0?{tone:`warn`,message:t(`codexAuth.catalogRefreshPending`)}:{tone:`ok`,message:t(`codexAuth.accountPickerUpdated`)})}catch{f.current=n,r(n),d({tone:`err`,message:t(`codexAuth.accountPickerUpdateFailed`)})}finally{p.current=!1,s(!1)}},[e,i,t]),v=c&&!i;return(0,Y.jsxs)(`div`,{className:`card card-row codex-account-picker-card`,"aria-busy":o||!i&&!v||void 0,children:[(0,Y.jsxs)(`div`,{className:`codex-account-picker-copy`,children:[(0,Y.jsx)(`strong`,{children:t(`codexAuth.accountPickerTitle`)}),(0,Y.jsx)(`div`,{className:`card-sub`,role:v?`status`:void 0,children:t(v?`codexAuth.accountPickerLoadFailed`:i?n?`codexAuth.accountPickerOnDesc`:`codexAuth.accountPickerOffDesc`:`common.loading`)}),i&&n&&(0,Y.jsx)(`div`,{className:`card-sub faint`,children:t(`codexAuth.accountPickerCompatibility`)}),i&&c&&(0,Y.jsx)(`div`,{className:`card-sub faint`,role:`status`,children:t(`codexAuth.accountPickerRefreshFailed`)})]}),(0,Y.jsxs)(`div`,{className:`codex-account-picker-controls`,children:[c&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{h()},disabled:o,children:t(`common.retry`)}),i&&(0,Y.jsx)(`button`,{type:`button`,className:`toggle ${n?`on`:``}`,onClick:()=>{g()},disabled:o,"aria-pressed":n,"aria-label":t(`codexAuth.accountPickerTitle`),title:t(`codexAuth.accountPickerTitle`),children:(0,Y.jsx)(`span`,{className:`toggle-knob`})})]}),u&&(0,Y.jsx)(`div`,{className:`codex-account-picker-feedback is-${u.tone}`,role:u.tone===`err`?`alert`:`status`,"aria-atomic":`true`,children:u.message})]})}function By(e){if(!e||typeof e!=`object`)return`absent`;let t=e.providers;if(!t||typeof t!=`object`||Array.isArray(t)||!Object.hasOwn(t,`openai`))return`absent`;let n=t.openai;if(!n||typeof n!=`object`||Array.isArray(n))return`absent`;let r=n;return r.disabled===!0?`disabled`:r.codexAccountMode===`direct`?`direct`:r.codexAccountMode===void 0||r.codexAccountMode===`pool`?`pool`:`absent`}function Vy({state:e,busy:t,onEnable:n}){let r=Q();return e===null?null:(0,Y.jsxs)(`div`,{className:`panel openai-account-mode-banner`,style:{marginBottom:16},children:[(0,Y.jsxs)(`div`,{className:`row`,children:[(0,Y.jsx)(`strong`,{children:r(`codexAuth.accountModeTitle`)}),e===`pool`?(0,Y.jsx)(`span`,{className:`badge badge-accent openai-account-mode-banner__badge-slot`,children:r(`codexAuth.accountModePool`)}):e===`direct`?(0,Y.jsx)(`span`,{className:`badge badge-green openai-account-mode-banner__badge-slot`,children:r(`codexAuth.accountModeDirect`)}):null]}),e===`pool`&&(0,Y.jsx)(`p`,{className:`card-sub openai-account-mode-banner__desc`,children:r(`codexAuth.accountModePoolDesc`)}),e===`direct`&&(0,Y.jsxs)(`p`,{className:`card-sub openai-account-mode-banner__desc`,children:[r(`codexAuth.accountModeDirectDesc`),` `,(0,Y.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>ht(`providers`),children:r(`codexAuth.openProviders`)})]}),(e===`absent`||e===`disabled`)&&(0,Y.jsxs)(`div`,{className:`row`,style:{alignItems:`center`,marginTop:8},children:[(0,Y.jsx)(`p`,{className:`card-sub`,style:{flex:1,margin:0},children:r(`codexAuth.openaiUnavailableDesc`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:t,onClick:n,children:r(t?`codexAuth.enablingOpenai`:`codexAuth.enableOpenai`)})]}),e===`invalid`&&(0,Y.jsxs)(`p`,{className:`card-sub openai-account-mode-banner__desc`,children:[r(`codexAuth.openaiMissing`),` `,(0,Y.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>ht(`providers`),children:r(`codexAuth.openProviders`)})]})]})}function Hy(e){if(!e||typeof e!=`object`)return;let t=e.providers;if(!t||typeof t!=`object`||Array.isArray(t)||!Object.hasOwn(t,`openai`))return;let n=t.openai;if(!(!n||typeof n!=`object`||Array.isArray(n)))return n}function Uy({apiBase:e}){return(0,Y.jsx)(Wy,{apiBase:e},e)}function Wy({apiBase:e}){let t=Q(),n=lc(e),{load:r}=n,i=(0,_.useRef)(!1);(0,_.useLayoutEffect)(()=>(i.current=!0,()=>{i.current=!1}),[]);let a=(0,_.useCallback)(()=>i.current?r(!1):Promise.resolve(!1),[r]),o=`ocx.codex-auth.config.v1:${e}`,s=Tr(o),[c,l]=(0,_.useState)(()=>s?.bannerState??null),[u,d]=(0,_.useState)(()=>s?.accountModeState??null),f=(0,_.useRef)(null),[p,m]=(0,_.useState)(!1),[h,g]=(0,_.useState)(``),v=(0,_.useCallback)(async()=>{let t=Xn(15e3);try{let n=await fetch(`${e}/api/config`,{signal:t.signal});if(!n.ok)throw Error(String(n.status));let r=await n.json(),i=Kl(Hy(r));if(i===`absent`||i===`disabled`||i===`invalid`){l(i);let e=i===`disabled`?`disabled`:`absent`;d(e),kr(o,{bannerState:i,accountModeState:e});return}let a=By(r);l(a),d(a),kr(o,{bannerState:a,accountModeState:a})}catch{}finally{t.clear()}},[e,o]);(0,_.useEffect)(()=>{f.current!==e&&(f.current=e,Promise.resolve().then(()=>{v()}));let t=er(()=>{v()},3e4);return()=>{t()}},[e,v]);let y=async()=>{m(!0),g(``);try{if(c!==`absent`&&c!==`disabled`)return;await $l(e,c),await v()}catch(e){e instanceof Ql?g(t(e.i18nKey)):g(e instanceof Error?e.message:t(`prov.saveFailed`))}finally{m(!1)}};return(0,Y.jsx)(Y.Fragment,{children:(0,Y.jsx)(cl,{apiBase:e,controller:n,hasMainHardLockSetting:!0,accountModeState:u,banner:(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(Vy,{state:c,busy:p,onEnable:()=>{y()}}),h&&(0,Y.jsx)(`div`,{className:`notice notice-err`,role:`alert`,children:h})]}),advancedExtras:(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(zy,{apiBase:e}),(0,Y.jsx)(Ny,{apiBase:e}),(0,Y.jsx)(Py,{apiBase:e}),(0,Y.jsx)(Ly,{apiBase:e,onSaved:a})]})})})}var Gy={"base-instructions":`codexSet.layer.base-instructions`,"model-switch":`codexSet.layer.model-switch`,personality:`codexSet.layer.personality`,"context-window-guidance":`codexSet.layer.context-window-guidance`,realtime:`codexSet.layer.realtime`,"agents-md":`codexSet.layer.agents-md`,permissions:`codexSet.layer.permissions`,collaboration:`codexSet.layer.collaboration`,environment:`codexSet.layer.environment`,"environments-instructions":`codexSet.layer.environments-instructions`,apps:`codexSet.layer.apps`,plugins:`codexSet.layer.plugins`,tools:`codexSet.layer.tools`,skills:`codexSet.layer.skills`,"multi-agent-mode":`codexSet.layer.multi-agent-mode`,"git-attribution":`codexSet.layer.git-attribution`},Ky={"base-instructions":`codexSet.about.base-instructions`,"model-switch":`codexSet.about.model-switch`,personality:`codexSet.about.personality`,"context-window-guidance":`codexSet.about.context-window-guidance`,realtime:`codexSet.about.realtime`,"agents-md":`codexSet.about.agents-md`,permissions:`codexSet.about.permissions`,collaboration:`codexSet.about.collaboration`,environment:`codexSet.about.environment`,"environments-instructions":`codexSet.about.environments-instructions`,apps:`codexSet.about.apps`,plugins:`codexSet.about.plugins`,tools:`codexSet.about.tools`,skills:`codexSet.about.skills`,"multi-agent-mode":`codexSet.about.multi-agent-mode`,"git-attribution":`codexSet.about.git-attribution`},qy={"model-switch":`codexSet.condition.model-switch`,realtime:`codexSet.condition.realtime`,"agents-md":`codexSet.condition.agents-md`,plugins:`codexSet.condition.plugins`,"git-attribution":`codexSet.condition.git-attribution`},Jy={base:`codexSet.class.base`,"config-toggle":`codexSet.class.config-toggle`,"feature-gated":`codexSet.class.feature-gated`,"runtime-conditional":`codexSet.class.runtime-conditional`,"extension-unknown":`codexSet.class.extension-unknown`};function Yy({descriptor:e,toggle:t,bytes:n,transitionOnly:r=!1,busy:i,writesRefused:a,onToggle:o,onSelectBase:s,baseSelection:c,onOpen:l}){let u=Q(),d=Gy[e.id],f=d?u(d):e.id,p=qy[e.id],m=t?.defaultedUserValue??e.default??!0,h=c?.kind==="default";return(0,Y.jsxs)(`li`,{className:`codex-set-prompt__row`,"data-layer-id":e.id,"data-layer-class":e.class,children:[(0,Y.jsx)(`span`,{className:`codex-set-prompt__pos`,"aria-hidden":`true`,children:e.order===null?`·`:e.order+1}),(0,Y.jsx)(`button`,{type:`button`,className:`link-btn codex-set-prompt__name`,onClick:()=>l(e.id),children:f}),e.key&&(0,Y.jsx)(`code`,{className:`codex-set-prompt__key`,children:e.key}),n!==null&&n>0&&(0,Y.jsx)(`span`,{className:`codex-set-prompt__bytes`,title:u(`codexSet.dialog.sourceBytes`,{bytes:n}),children:n>=1024?Math.round(n/1024)+` KB`:n+` B`}),e.class===`base`&&s?(0,Y.jsx)(`button`,{type:`button`,role:`switch`,className:`toggle ${h?`on`:``}`,"aria-checked":h,"aria-label":f,disabled:i||a||c?.kind===`external`,onClick:()=>{s(!h)},children:(0,Y.jsx)(`span`,{className:`toggle-knob`})}):e.class===`config-toggle`?(0,Y.jsx)(`button`,{type:`button`,role:`switch`,className:`toggle ${m?`on`:``}`,"aria-checked":m,"aria-label":f,disabled:i||a,onClick:()=>{o(e.id,!m)},children:(0,Y.jsx)(`span`,{className:`toggle-knob`})}):e.class===`feature-gated`?(0,Y.jsxs)(`span`,{className:`codex-set-prompt__note`,children:[u(`codexSet.row.featureGated`),` `,(0,Y.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>ht(`integrations/codex`),children:u(`codexSet.row.openFeatures`)})]}):(0,Y.jsx)(`span`,{className:`codex-set-prompt__note codex-set-prompt__note--locked`,children:u(r?`codexSet.row.onChange`:p||`codexSet.row.alwaysOn`)})]})}function Xy({descriptor:e,toggle:t,text:n,busy:r,onToggle:i,onClose:a}){let o=Q(),s=(0,_.useRef)(null),c=`codex-set-layer-dialog-`+e.id;(0,_.useEffect)(()=>{let e=s.current,t=document.activeElement;return e&&!e.open&&e.showModal(),()=>{e?.open&&e.close(),t&&typeof t.focus==`function`&&t.focus()}},[]);let l=(0,_.useCallback)(e=>{e.preventDefault(),a()},[a]),u=Jy[e.class],d=Gy[e.id],f=Ky[e.id],p=qy[e.id];return(0,Y.jsxs)(`dialog`,{ref:s,className:`modal-overlay`,"aria-labelledby":c,onCancel:l,children:[(0,Y.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":o(`common.close`),tabIndex:-1,onClick:a}),(0,Y.jsxs)(`div`,{className:`modal-card codex-set-layer-dialog`,onClick:e=>e.stopPropagation(),role:`document`,children:[(0,Y.jsxs)(`div`,{className:`modal-head`,children:[(0,Y.jsx)(`h3`,{id:c,children:d?o(d):e.id}),e.class===`config-toggle`&&t&&(0,Y.jsx)(`button`,{type:`button`,role:`switch`,className:`toggle ${t.defaultedUserValue?`on`:``}`,"aria-checked":t.defaultedUserValue,"aria-label":d?o(d):e.id,disabled:r,onClick:()=>{i(e.id,!t.defaultedUserValue)},children:(0,Y.jsx)(`span`,{className:`toggle-knob`})}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:a,children:o(`common.close`)})]}),(0,Y.jsx)(`p`,{className:`muted small`,children:o(f||`codexSet.dialog.unknownLayer`)}),(0,Y.jsxs)(`div`,{className:`codex-set-layer-dialog__line`,children:[(0,Y.jsx)(`span`,{className:`muted text-label`,children:o(`codexSet.dialog.class`)}),(0,Y.jsx)(`span`,{children:o(u)})]}),e.key&&(0,Y.jsxs)(`div`,{className:`codex-set-layer-dialog__line`,children:[(0,Y.jsx)(`span`,{className:`muted text-label`,children:o(`codexSet.dialog.key`)}),(0,Y.jsx)(`code`,{className:`api-code`,children:e.key}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{navigator.clipboard?.writeText(e.key??``)},children:o(`codexSet.dialog.copyKey`)})]}),e.class===`config-toggle`&&t&&(0,Y.jsxs)(`div`,{className:`codex-set-layer-dialog__line`,children:[(0,Y.jsx)(`span`,{className:`muted text-label`,children:o(`codexSet.dialog.fileValue`)}),(0,Y.jsx)(`span`,{children:t.userFileValue===null?o(`codexSet.dialog.absentDefault`,{value:String(t.default)}):o(`codexSet.dialog.setValue`,{value:String(t.userFileValue),fallback:String(t.default)})})]}),e.class===`runtime-conditional`&&p&&(0,Y.jsx)(`p`,{className:`muted small`,children:o(p)}),n?.reason===`ok`&&n.text?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{className:`codex-set-layer-dialog__line`,children:[(0,Y.jsx)(`span`,{className:`muted text-label`,children:o(`codexSet.dialog.sourceText`)}),(0,Y.jsx)(`span`,{className:`muted small`,children:o(`codexSet.dialog.sourceBytes`,{bytes:n.bytes})})]}),(0,Y.jsx)(`pre`,{className:`api-code codex-set-layer-dialog__text`,children:n.text})]}):(0,Y.jsx)(`p`,{className:`muted small codex-set-layer-dialog__no-text`,children:n?.reason===`empty-source`?o(`codexSet.dialog.emptySource`,{path:n.sourcePath??``}):n?.reason===`not-rendered`?o(`codexSet.dialog.notRendered`):n?.reason===`not-exposed`?o(`codexSet.dialog.notExposed`):o(`codexSet.dialog.textUnavailable`)})]})]})}function Zy({layer:e,index:t,total:n,busy:r,onToggle:i,onEdit:a,onDelete:o,onMove:s}){let c=Q();return(0,Y.jsxs)(`li`,{className:`codex-set-prompt__row codex-set-custom__row`,"data-custom-id":e.id,onKeyDown:i=>{!i.altKey||r||(i.key===`ArrowUp`&&t>0?(i.preventDefault(),s(e.id,-1)):i.key===`ArrowDown`&&t<n-1&&(i.preventDefault(),s(e.id,1)))},children:[(0,Y.jsx)(`span`,{className:`codex-set-prompt__pos`,"aria-hidden":`true`,children:t+1}),(0,Y.jsx)(`button`,{type:`button`,className:`link-btn codex-set-prompt__name`,onClick:()=>a(e.id),children:e.title}),(0,Y.jsxs)(`span`,{className:`codex-set-custom__reorder`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":c(`codexSet.custom.moveUp`,{title:e.title}),disabled:t===0||r,onClick:()=>s(e.id,-1),children:`↑`}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":c(`codexSet.custom.moveDown`,{title:e.title}),disabled:t===n-1||r,onClick:()=>s(e.id,1),children:`↓`})]}),(0,Y.jsx)(`button`,{type:`button`,role:`switch`,className:`toggle ${e.enabled?`on`:``}`,"aria-checked":e.enabled,"aria-label":e.title,disabled:r,onClick:()=>i(e.id,!e.enabled),children:(0,Y.jsx)(`span`,{className:`toggle-knob`})}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-set-custom__delete`,"aria-label":c(`codexSet.custom.delete`,{title:e.title}),disabled:r,onClick:()=>o(e.id),children:`×`})]})}var Qy=8192,$y=[{rule:`identity`,level:`warn`,messageKey:`codexSet.lint.identity`,pattern:/you\s+are\s+(claude|grok|gemini|gpt-|chatgpt)/gi},{rule:`foreign-tool`,level:`warn`,messageKey:`codexSet.lint.foreignTool`,pattern:/\b(Read|Edit|Write|Bash|Glob|Grep)\s+tool\b/g},{rule:`placeholder`,level:`warn`,messageKey:`codexSet.lint.placeholder`,pattern:/\$\{\{[\s\S]*?\}\}/g},{rule:`apply-patch`,level:`warn`,messageKey:`codexSet.lint.applyPatch`,pattern:/apply_patch\s+(?:is|must|should|means|works)/gi},{rule:`approval-vocab`,level:`warn`,messageKey:`codexSet.lint.approvalVocab`,pattern:/\b(always-approve|ask mode|acceptEdits)\b/gi},{rule:`environment`,level:`warn`,messageKey:`codexSet.lint.environment`,pattern:/\b(your (?:cwd|working directory) is|today's date is|you have no network access|you are running on (?:macos|linux|windows))/gi}];function eb(e){let t=0;for(let n of e){let e=n.codePointAt(0);t+=e<128?1:e<2048?2:e<65536?3:4}return t}function tb(e){let t=[];for(let n of $y){let r=new RegExp(n.pattern.source,n.pattern.flags);for(let i=r.exec(e);i!==null;i=r.exec(e))t.push({level:n.level,rule:n.rule,messageKey:n.messageKey,span:[i.index,i.index+i[0].length]}),i[0].length===0&&(r.lastIndex+=1)}return eb(e)>Qy&&t.push({level:`info`,rule:`size`,messageKey:`codexSet.lint.size`}),t.sort((e,t)=>(e.span?.[0]??1/0)-(t.span?.[0]??1/0))}var nb=65536;function rb(e){let t=0;for(let n of e){let e=n.codePointAt(0);t+=e<128?1:e<2048?2:e<65536?3:4}return t}function ib(e){return e.replace(/\r\n/g,`
|
|
84
84
|
`).replace(/\r/g,`
|
|
@@ -125,4 +125,4 @@ const closeSession = () => ws.send(JSON.stringify({ type: "session.close" }));`}
|
|
|
125
125
|
`)}),(0,Y.jsxs)(`details`,{className:`audio-api-examples`,children:[(0,Y.jsx)(`summary`,{children:t(`audio.examples`)}),(0,Y.jsx)(tx,{text:lS(e.liveEndpoint,!0,e.liveModel,t(`audio.key`))})]})]})]})}function hS({keys:e,apiBase:t,active:n=!0,attributionSince:r,historyTruncated:i,usageMetadata:a,authMatrix:o,keysLoading:s,keysLoadFailed:c,endpoints:l,claudeCodeEnabled:u,localeTag:d,newName:f,creating:p,newKey:m,copied:h,rotationSecret:g=null,rotationCopied:v=!1,filteredModels:y,modelsLoading:b,modelsRefreshing:x=!1,modelsLoadFailed:S,modelCount:C,hasModelData:w,modelQuery:T,copiedModelId:E,modelTests:D,canTestModels:O,onNewNameChange:k,onCreate:A,onDismissNewKey:j,onCopyKey:M,onDelete:N,onRename:P,onRotationStart:F,onRotationCommit:I,onRotationAbort:L,onCopyRotationSecret:R,onDismissRotationSecret:z,onModelQueryChange:B,onCopyModelId:V,onTestModel:H,onRetryModels:U,sourceLabel:W,protocolLabel:G}){let K=Q(),[q,J]=(0,_.useState)(null),[X,ee]=(0,_.useState)(!1),[te,ne]=(0,_.useState)(!1),[Z,re]=(0,_.useState)(!1),[ie,ae]=(0,_.useState)(!1),[oe,se]=(0,_.useState)(``),[ce,le]=(0,_.useState)(!1),[ue,de]=(0,_.useState)(!1),[fe,pe]=(0,_.useState)(!1),[he,ge]=(0,_.useState)(!1),[_e,ve]=(0,_.useState)(!1),ye=q?e.find(e=>e.id===q)??null:null,be=ye?g?.id===ye.id?g.rotationId:ye.pendingRotation?.id:void 0,xe=Z||ce||he,Se=async e=>{if(!(!ye||he)){ge(!0),ve(!1);try{let t=be;(e===`start`?await F?.(ye.id)??!1:t&&(await(e===`commit`?I:L)?.(ye.id,t)??!1))||ve(!0)}finally{ge(!1)}}},we=(0,_.useMemo)(()=>[{id:`keys`,label:K(`api.section.keys`),meta:s?void 0:String(e.length)},{id:`connect`,label:K(`api.section.connect`)},{id:`endpoints`,label:K(`api.section.endpoints`)},{id:`dictation`,label:K(`audio.dictation`)},{id:`live-voice`,label:K(`audio.liveVoice`)},{id:`models`,label:K(`api.section.models`),meta:String(C)},{id:`examples`,label:K(`api.section.examples`)}],[K,e.length,s,C]),Te=()=>{ee(!1),ne(!1)},Ee=()=>{J(null),Te(),ae(!1),de(!1),pe(!1)};(0,_.useEffect)(()=>{if(!X)return;let e=window.setTimeout(()=>ne(!0),300);return()=>window.clearTimeout(e)},[X]);let De=()=>{ye&&ee(!0)},Oe=async()=>{if(!(!ye||!te||Z)){re(!0),pe(!1);try{await N(ye.id)?(Te(),J(null)):pe(!0)}finally{re(!1)}}},ke=()=>{ye&&(se(ye.name),de(!1),ae(!0))},Ae=async()=>{if(!ye||ce)return;let e=oe.trim();if(!e||e===ye.name){ae(!1);return}le(!0),de(!1);try{await P(ye.id,e)?ae(!1):de(!0)}finally{le(!1)}};return(0,Y.jsxs)(`div`,{className:`apikeys-workspace-shell`,children:[!ye&&(0,Y.jsx)(Mg,{scope:`api`,items:we,ariaLabel:K(`api.workspace.sections`),mobileReadingLine:108}),(0,Y.jsx)(`div`,{className:`apikeys-workspace-root`,children:(0,Y.jsx)(`section`,{className:`apikeys-workspace-main`,"aria-label":K(`api.workspace.details`),children:ye?(0,Y.jsxs)(`div`,{className:`awi-detail`,children:[(0,Y.jsx)(`div`,{className:`awi-detail-toolbar`,children:(0,Y.jsxs)(`button`,{type:`button`,className:`awi-back`,onClick:Ee,disabled:xe,children:[(0,Y.jsx)(Ce,{className:`awi-back-chevron`,"aria-hidden":`true`}),K(`modal.back`)]})}),(0,Y.jsxs)(`div`,{className:`awi-detail-body`,children:[(0,Y.jsxs)(`div`,{className:`awi-detail-head`,children:[(0,Y.jsx)(`h2`,{className:`awi-detail-title`,children:ye.name}),(0,Y.jsx)(`span`,{className:`awi-detail-actions`,children:X?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-danger btn-sm awi-confirm-delete`,onClick:()=>{Oe()},disabled:!te||Z,children:[(0,Y.jsx)(me,{}),` `,K(Z?`api.key.deleting`:`api.confirm`)]},`confirm-delete`),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:Te,disabled:Z,children:K(`common.cancel`)})]}):(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:ke,disabled:ie,children:K(`api.key.rename`)},`rename`),(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-danger btn-sm`,onClick:De,"aria-label":K(`api.deleteAria`),children:[(0,Y.jsx)(me,{}),` `,K(`api.workspace.deleteKey`)]},`request-delete`)]})})]}),X&&(0,Y.jsx)(`p`,{className:`muted awi-delete-hint`,children:K(`api.workspace.deleteConfirm`)}),fe&&(0,Y.jsx)(`p`,{className:`awi-delete-error`,role:`alert`,children:K(`api.deleteFailed`)}),ie&&(0,Y.jsxs)(`div`,{className:`awi-rename`,children:[(0,Y.jsx)(`label`,{className:`awi-rename-label`,htmlFor:`awi-key-name`,children:K(`api.key.name`)}),(0,Y.jsx)(`input`,{id:`awi-key-name`,className:`input`,type:`text`,value:oe,maxLength:64,disabled:ce,onChange:e=>se(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),Ae())}}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-sm`,onClick:()=>{Ae()},disabled:ce,children:K(ce?`api.key.renaming`:`api.key.saveName`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>ae(!1),disabled:ce,children:K(`common.cancel`)}),ue&&(0,Y.jsx)(`p`,{className:`awi-rename-error`,role:`alert`,children:K(`api.key.renameFailed`)})]}),(0,Y.jsxs)(`div`,{className:`awi-section`,children:[(0,Y.jsx)(`h3`,{className:`awi-section-title`,children:K(`api.workspace.keyDetails`)}),(0,Y.jsxs)(`dl`,{className:`awi-kv`,children:[(0,Y.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Y.jsx)(`dt`,{children:K(`api.workspace.keyPrefix`)}),(0,Y.jsx)(`dd`,{children:(0,Y.jsx)(`code`,{children:ye.prefix})})]}),(0,Y.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Y.jsx)(`dt`,{children:K(`api.colCreated`)}),(0,Y.jsx)(`dd`,{children:Qb(ye.createdAt,d)})]})]})]}),(0,Y.jsxs)(`div`,{className:`awi-section`,"aria-live":`polite`,children:[(0,Y.jsx)(`h3`,{className:`awi-section-title`,children:K(`api.rotation.title`)}),be?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`p`,{className:`muted`,children:K(`api.rotation.pending`)}),ye.pendingRotation&&(0,Y.jsxs)(`p`,{className:`muted`,children:[K(`api.rotation.expires`),` `,Qb(ye.pendingRotation.expiresAt,d)]}),g?.id===ye.id&&(0,Y.jsxs)(`div`,{className:`api-key-reveal`,role:`status`,children:[(0,Y.jsx)(`p`,{children:K(`api.rotation.secretOnce`)}),(0,Y.jsx)(`code`,{children:g.key}),(0,Y.jsxs)(`span`,{children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-sm`,onClick:R,children:K(v?`api.copied`:`api.copy`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:z,children:K(`common.close`)})]})]}),(0,Y.jsxs)(`div`,{className:`awi-detail-actions`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:he,onClick:()=>{Se(`commit`)},children:K(`api.rotation.commit`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:he,onClick:()=>{Se(`abort`)},children:K(`api.rotation.abort`)})]})]}):(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`p`,{className:`muted`,children:K(`api.rotation.description`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:he,onClick:()=>{Se(`start`)},children:K(he?`api.rotation.starting`:`api.rotation.start`)})]}),_e&&(0,Y.jsx)(`p`,{className:`awi-delete-error`,role:`alert`,children:K(`api.rotation.failed`)})]}),(0,Y.jsxs)(`div`,{className:`awi-section`,children:[(0,Y.jsx)(`h3`,{className:`awi-section-title`,children:K(`api.attribution.title`)}),(0,Y.jsx)(Jn,{data:a}),r?ye.usage.ambiguous?(0,Y.jsx)(`p`,{className:`muted`,children:K(`api.attribution.ambiguous`)}):(0,Y.jsxs)(`dl`,{className:`awi-kv`,children:[(0,Y.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Y.jsx)(`dt`,{children:K(`api.attribution.requests7d`)}),(0,Y.jsx)(`dd`,{children:ye.usage.requests7d.toLocaleString(d)})]}),(0,Y.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Y.jsx)(`dt`,{children:i||a?.usageIncomplete?K(`api.attribution.totalRequestsAvailable`):K(`api.attribution.totalRequests`)}),(0,Y.jsx)(`dd`,{children:ye.usage.totalRequests.toLocaleString(d)})]}),(0,Y.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Y.jsx)(`dt`,{children:K(`api.attribution.lastUsed`)}),(0,Y.jsx)(`dd`,{children:ye.usage.lastUsedAt?Qb(ye.usage.lastUsedAt,d):K(a?.usageIncomplete?`api.attribution.noRecordedUse`:`api.attribution.neverUsed`)})]}),(0,Y.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Y.jsx)(`dt`,{children:i||a?.usageIncomplete?K(`api.attribution.sinceAvailable`):K(`api.attribution.since`)}),(0,Y.jsx)(`dd`,{children:Qb(r,d)})]})]}):(0,Y.jsx)(`p`,{className:`muted`,children:K(`api.attribution.unavailableDetail`)})]})]})]}):(0,Y.jsx)(`div`,{className:`awi-overview`,children:(0,Y.jsxs)(`div`,{className:`awi-overview-section`,children:[(0,Y.jsxs)(`div`,{id:kg(`api`,`keys`),className:`awi-section-anchor`,children:[(0,Y.jsx)(ix,{keys:e,keysLoading:s,keysLoadFailed:c,newName:f,creating:p,newKey:m,copied:h,confirmDelete:null,localeTag:d,showKeyList:!1,onNewNameChange:k,onCreate:A,onDismissNewKey:j,onCopyKey:M,onConfirmDelete:()=>{},onCancelDelete:()=>{},onDelete:()=>{}}),(0,Y.jsx)(ux,{keys:e,keysLoading:s,keysLoadFailed:c,attributionSince:r,usageMetadata:a,localeTag:d,busy:xe,onSelect:e=>{J(e),Te(),ae(!1),de(!1),pe(!1)}})]}),(0,Y.jsx)(`div`,{id:kg(`api`,`connect`),className:`awi-section-anchor`,children:(0,Y.jsx)(lx,{apiBase:t,baseUrl:l.baseUrl,hasKeys:e.length>0})}),(0,Y.jsx)(`div`,{id:kg(`api`,`endpoints`),className:`awi-section-anchor`,children:(0,Y.jsx)(rx,{endpoints:l,claudeCodeEnabled:u,authMatrix:o})}),(0,Y.jsx)(`div`,{id:kg(`api`,`dictation`),className:`awi-section-anchor`,children:n&&(0,Y.jsx)(pS,{audio:l.audio},`${t}:${JSON.stringify(l.audio)}`)}),(0,Y.jsx)(`div`,{id:kg(`api`,`live-voice`),className:`awi-section-anchor`,children:n&&(0,Y.jsx)(mS,{audio:l.audio},`${t}:${JSON.stringify(l.audio)}`)}),(0,Y.jsx)(`div`,{id:kg(`api`,`models`),className:`awi-section-anchor`,children:(0,Y.jsx)(ax,{filteredModels:y,modelsLoading:b,modelsRefreshing:x,modelsLoadFailed:S,modelCount:C,hasModelData:w,modelQuery:T,copiedModelId:E,modelTests:D,claudeCodeEnabled:u,onModelQueryChange:B,onCopyModelId:V,onTestModel:H,onRetryModels:U,canTestModels:O,sourceLabel:W,protocolLabel:G})}),(0,Y.jsx)(`div`,{id:kg(`api`,`examples`),className:`awi-section-anchor`,children:(0,Y.jsx)(ox,{endpoints:l,claudeCodeEnabled:u})})]})})})})]})}var gS=[],_S=15e3;function vS(e){let t=e.replace(/\/$/,``);if(!t)return Xb;try{return new URL(t).host?Zb(`${t}/v1/responses`):Xb}catch{return Xb}}function yS(e){if(!e||!Jb(e.authMatrix)||!Array.isArray(e.keys)||e.keys.some(e=>!e||!Kb(e.usage)||!bS(e.pendingRotation)))return null;if(e.endpoints?.audio!==void 0&&!Yb(e.endpoints.audio,e.endpoints.baseUrl)){let{audio:t,...n}=e.endpoints;return{...e,endpoints:n}}return e}function bS(e){if(e===void 0)return!0;if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return typeof t.id==`string`&&!!t.id&&typeof t.createdAt==`string`&&!Number.isNaN(Date.parse(t.createdAt))&&typeof t.expiresAt==`string`&&!Number.isNaN(Date.parse(t.expiresAt))}function xS({apiBase:e,active:t=!0}){let{t:n,locale:r}=ut(),i=nt.find(e=>e.code===r)?.htmlLang,a=`ocx.apikeys.list.v2:${e}`,o=`ocx.apikeys.models.v1:${e}`,s=`api-keys:${e}`,c=`api-models:${e}`,l=Dr(a),u=Dr(o),d=yS(l?.data??null),f=u?.data??null,[p,m]=(0,_.useState)(null),[h,g]=(0,_.useState)(``),[v,y]=(0,_.useState)(null),[b,x]=(0,_.useState)({}),[S,C]=(0,_.useState)(``),[w,T]=(0,_.useState)(!1),[E,D]=(0,_.useState)(null),[O,k]=(0,_.useState)(!1),[A,j]=(0,_.useState)(null),[M,N]=(0,_.useState)(!1),P=(0,_.useRef)(!1),F=(0,_.useCallback)(async t=>{let r=await Lt(await fetch(`${e}/api/keys`,{signal:t}));if(!r||!Jb(r.authMatrix))throw Error(n(`api.keysLoadFailed`));let i=r.keys??[];if(i.some(e=>!Kb(e.usage)||!bS(e.pendingRotation)))throw Error(n(`api.keysLoadFailed`));let o=i,s=Zb(r.endpoint??``),c={keys:o,endpoints:{baseUrl:r.baseUrl??s.baseUrl,responses:r.responsesEndpoint??r.endpoint??Xb.responses,chatCompletions:r.chatCompletionsEndpoint??s.chatCompletions,messages:r.messagesEndpoint??s.messages,models:r.modelsEndpoint??s.models,...Yb(r.audio,r.baseUrl??s.baseUrl)?{audio:r.audio}:{}},claudeCodeEnabled:r.claudeCodeEnabled!==!1,...r.attributionSince?{attributionSince:r.attributionSince}:{},...r.historyTruncated===!0?{historyTruncated:!0}:{},...Kn(r),authMatrix:r.authMatrix};return Or(a,c),c},[e,a,n]),I=(0,_.useCallback)(async t=>{let r=await fetch(`${e}/v1/models`,{signal:t});if(!r.ok)throw Error(n(`api.modelsLoadFailed`));let i=await r.json(),a=Array.isArray(i)?i:typeof i==`object`&&i&&Array.isArray(i.data)?i.data:null;if(!a)throw Error(n(`api.modelsLoadFailed`));let s=a.filter(e=>typeof e==`object`&&!!e&&typeof e.id==`string`).map(e=>Wb(e)).sort((e,t)=>Gb(e).localeCompare(Gb(t)));return Or(o,s),s},[e,o,n]),L=jr(s,[e],F,{isEmpty:e=>e.keys.length===0,initialData:d??void 0,initialDataCachedAt:l?.cachedAt??null,staleAfterMs:6e4,enabled:t}),R=jr(c,[e],I,{isEmpty:e=>e.length===0,initialData:f??void 0,initialDataCachedAt:u?.cachedAt??null,staleAfterMs:6e4,enabled:t}),z=L.state,B=R.state,V=z.data??d,H=B.data??f??gS,U=V?.keys??[],W=V?.endpoints??vS(e),G=V?.claudeCodeEnabled??!0,K=V?.attributionSince,q=V?.historyTruncated===!0,J=V?.authMatrix??[],X=L.refresh,ee=R.refresh,te=(0,_.useMemo)(()=>{let e=h.trim().toLowerCase();return e?H.filter(t=>Gb(t).toLowerCase().includes(e)||t.displayName.toLowerCase().includes(e)||t.provider.toLowerCase().includes(e)):H},[h,H]),ne=async t=>{if(P.current)return!1;P.current=!0,T(!0),m(null);try{let r=t??S,i=await It(await fetch(`${e}/api/keys`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:r||`default`})}),n(`api.createFailed`));return typeof i?.key!=`string`||i.key.length===0?(m(n(`api.createFailed`)),!1):(D(i.key),C(``),X(),!0)}catch{return m(n(`api.createFailed`)),!1}finally{P.current=!1,T(!1)}},Z=async t=>{m(null);let n=Xn(_S);try{return(await fetch(`${e}/api/keys`,{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:t}),signal:n.signal})).ok?(X(),!0):!1}catch{return!1}finally{n.clear()}},re=async(t,n)=>{m(null);let r=Xn(_S);try{return(await fetch(`${e}/api/keys`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:t,name:n}),signal:r.signal})).ok?(X(),!0):!1}catch{return!1}finally{r.clear()}},ie=async t=>{m(null);let r=Xn(_S);try{let i=await It(await fetch(`${e}/api/keys/rotate`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:t}),signal:r.signal}),n(`api.rotation.startFailed`));return!i||typeof i.key!=`string`||!i.key||typeof i.rotationId!=`string`||!i.rotationId?!1:(j({id:t,key:i.key,rotationId:i.rotationId}),X(),!0)}catch{return!1}finally{r.clear()}},ae=async(t,n,r)=>{m(null);let i=Xn(_S);try{return(await fetch(`${e}${r===`commit`?`/api/keys/rotate/commit`:`/api/keys/rotate`}`,{method:r===`commit`?`POST`:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:t,rotationId:n}),signal:i.signal})).ok?(j(e=>e?.id===t?null:e),X(),!0):!1}catch{return!1}finally{i.clear()}},oe=async()=>{if(A)try{await navigator.clipboard.writeText(A.key),N(!0),window.setTimeout(()=>N(!1),2e3)}catch{m(n(`api.key.copyFailed`))}},se=async()=>{if(E){m(null);try{await navigator.clipboard.writeText(E),k(!0),window.setTimeout(()=>k(!1),2e3)}catch{k(!1),m(n(`api.key.copyFailed`))}}},ce=async e=>{try{await navigator.clipboard.writeText(e),y(e),window.setTimeout(()=>y(t=>t===e?null:t),2e3)}catch{}},le=e=>e.native?n(`api.sourceNative`):e.provider===`combo`?n(`api.sourceCombo`):e.custom?n(`api.sourceCustom`):Ln(e.provider,n),ue=e=>n(e===`responses`?`api.protocolResponses`:e===`messages`?`api.protocolMessages`:`api.protocolChatCompletions`),de=(e,t)=>e===`responses`?{url:W.responses,body:{model:t,input:`ping`,max_output_tokens:1,stream:!1}}:e===`messages`?{url:W.messages,body:{model:t,max_tokens:1,messages:[{role:`user`,content:`ping`}]}}:{url:W.chatCompletions,body:{model:t,messages:[{role:`user`,content:`ping`}],max_tokens:1,stream:!1}},fe=(e,t,n)=>x(r=>({...r,[e]:{...r[e],[t]:n}})),pe=async(e,t)=>{if(!E)return;let r=Gb(e),i=de(t,r);fe(r,t,{state:`testing`});try{let e=await fetch(i.url,{method:`POST`,headers:{"Content-Type":`application/json`,"x-opencodex-api-key":E},body:JSON.stringify(i.body)});if(!e.ok){let n=await e.text();fe(r,t,{state:`error`,detail:n.slice(0,160)||String(e.status)});return}fe(r,t,{state:`ok`})}catch(e){fe(r,t,{state:`error`,detail:e instanceof Error?e.message:n(`api.testFailed`)})}},me=n(`api.subtitle`).split(`{authHeader}`);return(0,Y.jsxs)(`section`,{className:`api-page`,"aria-busy":z.refreshing||B.refreshing||void 0,children:[(0,Y.jsx)(`div`,{className:`page-head`,children:(0,Y.jsx)(`h2`,{children:n(`api.title`)})}),(0,Y.jsxs)(`p`,{className:`page-sub`,children:[me[0],(0,Y.jsx)(`code`,{children:`x-opencodex-api-key`}),me[1]]}),p&&(0,Y.jsx)($,{tone:`err`,children:p}),z.showError&&V&&(0,Y.jsx)($,{tone:`err`,children:n(`api.keysLoadFailed`)}),z.showSkeleton&&!V?(0,Y.jsx)(ep,{label:n(`api.activeKeysLoading`),rows:4}):z.kind===`failed-cold`&&!V?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)($,{tone:`err`,children:z.error instanceof Error?z.error.message:n(`api.keysLoadFailed`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>X(),children:n(`common.retry`)})]}):(0,Y.jsx)(Y.Fragment,{children:(0,Y.jsx)(hS,{active:t,keys:U,apiBase:e,attributionSince:K,historyTruncated:q,usageMetadata:Kn(V),authMatrix:J,keysLoading:!1,keysLoadFailed:z.showError,endpoints:W,claudeCodeEnabled:G,localeTag:i,newName:S,creating:w,newKey:E,copied:O,rotationSecret:A,rotationCopied:M,filteredModels:te,modelsLoading:B.showSkeleton&&!B.data&&!f,modelsRefreshing:B.refreshing&&B.showError&&(B.data!==void 0||f!==null),modelsLoadFailed:B.showError,modelCount:H.length,hasModelData:B.data!==void 0||f!==null,modelQuery:h,copiedModelId:v,modelTests:b,onNewNameChange:C,onCreate:()=>{ne()},onDismissNewKey:()=>D(null),onCopyKey:()=>{se()},onDelete:Z,onRename:re,...Mb()?{onRotationStart:ie,onRotationCommit:(e,t)=>ae(e,t,`commit`),onRotationAbort:(e,t)=>ae(e,t,`abort`),onCopyRotationSecret:()=>{oe()},onDismissRotationSecret:()=>j(null)}:{},onModelQueryChange:g,onCopyModelId:e=>{ce(e)},onTestModel:(e,t)=>{pe(e,t)},onRetryModels:()=>{ee({forceLoading:!0})},canTestModels:E!==null,sourceLabel:le,protocolLabel:ue})})]})}function SS(e,t){let n=(e??[]).map(e=>({value:e,label:tf(e)}));return[{value:``,label:t},...n]}function CS(e){let t=e.autoConnectSupported===!0;return{autoConnectSupported:t,systemEnv:t&&e.systemEnv===!0}}function wS(){if(typeof crypto<`u`&&typeof crypto.randomUUID==`function`)try{return crypto.randomUUID()}catch{}let e=new Uint8Array(16);if(typeof crypto<`u`&&typeof crypto.getRandomValues==`function`)crypto.getRandomValues(e);else for(let t=0;t<16;t++)e[t]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}var TS=829800;function ES(e,t=`en`){if(e>=1e6){let n=e/1e6,r=n.toFixed(1).replace(/\.0$/,``);return Number.isInteger(n)||Number(r)*1e6===e?new Intl.NumberFormat(t,{notation:`compact`,compactDisplay:`short`,maximumFractionDigits:+!Number.isInteger(n)}).format(e):`${Math.round(e/1e3)}k`}return`${Math.round(e/1e3)}k`}var DS=[`ANTHROPIC_MODEL`,`ANTHROPIC_DEFAULT_OPUS_MODEL`,`ANTHROPIC_DEFAULT_SONNET_MODEL`,`ANTHROPIC_DEFAULT_HAIKU_MODEL`,`ANTHROPIC_DEFAULT_FABLE_MODEL`];function OS(e){let t=`http://127.0.0.1:${e.port}`,n=e.authMode===`auto`?e.markerMode??`subscription`:e.authMode,r=e.autoContext&&e.maxContextTokens===null,i=DS.filter(t=>e.effectiveModelEnv[t]).map(t=>`export ${t}=${e.effectiveModelEnv[t]}`);return[`export ANTHROPIC_BASE_URL=${t}`,...n===`proxy`?[`export ANTHROPIC_AUTH_TOKEN=opencodex-proxy`]:[`# no ANTHROPIC_AUTH_TOKEN: your claude.ai login (and connectors) stay active`],`export CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1`,...n===`proxy`?['[ -z "${CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST+x}" ] && export CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST=1']:[],...r?[`export CLAUDE_CODE_AUTO_COMPACT_WINDOW=${e.autoCompactWindow??829800}`]:[],...i,`claude`].join(`
|
|
126
126
|
`)}function kS(e){return e?e.backend??`auto`:`inherit`}function AS(e,t){if(t!==`inherit`)return t===`auto`?{...e,backend:void 0}:{...e,backend:t}}function jS(e,t){return{...e,model:t}}function MS(e){if(!e)return null;let t=(e.model??``).trim();return e.backend?{backend:e.backend,model:t}:t?{backend:null,model:t}:null}function NS({label:e,checked:t,onChange:n,disabled:r=!1,describedBy:i}){return(0,Y.jsxs)(`label`,{className:`toggle`,children:[(0,Y.jsx)(`input`,{type:`checkbox`,checked:t,disabled:r,"aria-label":e,"aria-describedby":i,onChange:e=>n(e.target.checked)}),(0,Y.jsx)(`span`,{className:`slider`,"aria-hidden":`true`})]})}function PS({supported:e,checked:t,onChange:n}){let r=Q(),i=e?void 0:`claude-system-env-unsupported`;return(0,Y.jsxs)(`div`,{className:`setting-row`,children:[(0,Y.jsxs)(`div`,{className:`setting-label`,children:[(0,Y.jsx)(`span`,{className:`title`,children:r(`claude.systemEnv`)}),e?(0,Y.jsx)(`span`,{className:`desc`,children:r(`claude.systemEnvDesc`)}):(0,Y.jsx)(`span`,{className:`desc`,id:i,children:(0,Y.jsx)(ft,{k:`claude.systemEnvUnsupported`,cmd:`ocx claude`})}),e&&t&&(0,Y.jsx)(`span`,{className:`desc`,style:{color:`var(--red)`},children:r(`claude.systemEnvWarn`)})]}),(0,Y.jsx)(NS,{label:r(`claude.systemEnv`),checked:e&&t,disabled:!e,describedBy:i,onChange:n})]})}function FS({value:e,tierHaikuModel:t,options:n,onChange:r}){let i=Q(),a=t??e;return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`p`,{className:`muted text-label`,style:{margin:`0 0 8px`},children:i(`claude.smallFastModelAccurateHint`)}),(0,Y.jsx)(kt,{value:e,options:n,onChange:r,label:i(`claude.smallFastModel`),style:{maxWidth:420}}),a===``&&(0,Y.jsx)(`p`,{className:`notice-warn`,role:`status`,style:{marginTop:8},children:i(`claude.smallFastModelNativeWarning`)})]})}function IS(e,t){return e&&[`claude-json-oauth`,`claude-credentials-file`,`macos-keychain`,`exported-env`].includes(e)?t(`claude.authSource.${e}`):t(`claude.authSource.unknown`)}function LS({state:e,autoCompactOptions:t,availableModels:n,onStateChange:r}){let i=Q();return(0,Y.jsxs)(`div`,{className:`card`,style:{overflow:`hidden`},children:[(0,Y.jsxs)(`div`,{className:`setting-row`,children:[(0,Y.jsxs)(`div`,{className:`setting-label`,children:[(0,Y.jsx)(`span`,{className:`title`,children:i(`claude.authMode`)}),(0,Y.jsx)(`span`,{className:`desc`,children:i(`claude.authModeHint`)})]}),(0,Y.jsx)(`div`,{className:`setting-controls`,children:(0,Y.jsx)(kt,{value:e.authMode,options:[{value:`auto`,label:i(`claude.authModeAuto`)},{value:`subscription`,label:i(`claude.authModeSubscription`)},{value:`proxy`,label:i(`claude.authModeProxy`)}],onChange:t=>r({...e,authMode:t}),label:i(`claude.authMode`),style:{minWidth:220},align:`right`,portal:!0})})]}),e.authModeOrigin&&(0,Y.jsxs)(`div`,{className:`claude-effective-auth${e.authModeOrigin===`auto-unknown`?` warn`:``}`,role:`status`,children:[(0,Y.jsx)(`span`,{className:`claude-effective-auth-label`,children:i(`claude.effectiveMode.label`)}),(0,Y.jsxs)(`span`,{children:[e.authModeOrigin===`manual`?i(`claude.effectiveMode.manual`,{mode:e.markerMode===`proxy`?i(`claude.authModeProxy`):i(`claude.authModeSubscription`)}):e.authModeOrigin===`auto-present`?i(`claude.effectiveMode.autoPresent`,{source:IS(e.authFoundBy,i)}):e.authModeOrigin===`auto-absent`?i(`claude.effectiveMode.autoAbsent`):i(`claude.effectiveMode.autoUnknown`),e.admissionKeyActive===!0?` ${i(`claude.effectiveMode.admissionKey`)}`:``]})]}),(0,Y.jsx)(PS,{supported:e.autoConnectSupported,checked:e.systemEnv,onChange:t=>r({...e,systemEnv:t})}),(0,Y.jsxs)(`div`,{className:`setting-row`,children:[(0,Y.jsxs)(`div`,{className:`setting-label`,children:[(0,Y.jsx)(`span`,{className:`title`,children:i(`claude.fastMode`)}),(0,Y.jsx)(`span`,{className:`desc`,children:i(`claude.fastModeDesc`)})]}),(0,Y.jsx)(`div`,{className:`setting-controls`,children:(0,Y.jsx)(kt,{value:e.fastMode===null?`auto`:e.fastMode?`on`:`off`,options:[{value:`auto`,label:i(`claude.fastAuto`)},{value:`on`,label:i(`claude.fastOn`)},{value:`off`,label:i(`claude.fastOff`)}],onChange:t=>r({...e,fastMode:t===`auto`?null:t===`on`}),label:i(`claude.fastMode`),style:{minWidth:140},align:`right`,portal:!0})})]}),(0,Y.jsxs)(`div`,{className:`setting-row`,children:[(0,Y.jsxs)(`div`,{className:`setting-label`,children:[(0,Y.jsx)(`span`,{className:`title`,children:i(`claude.autoContext`)}),(0,Y.jsx)(`span`,{className:`desc`,children:i(`claude.autoContextDesc`)}),e.maxContextTokens!==null&&(0,Y.jsx)(`span`,{className:`desc`,style:{color:`var(--muted)`},children:i(`claude.autoContextInert`)})]}),(0,Y.jsx)(NS,{label:i(`claude.autoContext`),checked:e.autoContext,onChange:t=>r({...e,autoContext:t})})]}),e.autoContext&&(0,Y.jsxs)(`div`,{className:`setting-row`,children:[(0,Y.jsxs)(`div`,{className:`setting-label`,children:[(0,Y.jsx)(`span`,{className:`title`,children:i(`claude.autoCompactWindow`)}),(0,Y.jsx)(`span`,{className:`desc`,children:i(`claude.autoCompactWindowDesc`)}),e.autoCompactWindow!==null&&(0,Y.jsx)(`span`,{className:`desc`,style:{color:`var(--red)`},children:i(`claude.autoCompactWindowWarn`)})]}),(0,Y.jsx)(`div`,{className:`setting-controls`,children:(0,Y.jsx)(kt,{value:e.autoCompactWindow===null?``:String(e.autoCompactWindow),options:t,onChange:t=>r({...e,autoCompactWindow:t===``?null:Number(t)}),label:i(`claude.autoCompactWindow`),style:{minWidth:130},align:`right`,portal:!0})})]}),(0,Y.jsxs)(`div`,{className:`setting-row`,children:[(0,Y.jsxs)(`div`,{className:`setting-label`,children:[(0,Y.jsx)(`span`,{className:`title`,children:i(`claude.injectAgents`)}),(0,Y.jsx)(`span`,{className:`desc`,children:i(`claude.injectAgentsDesc`)})]}),(0,Y.jsx)(NS,{label:i(`claude.injectAgents`),checked:e.injectAgents,onChange:t=>r({...e,injectAgents:t})})]}),[`webSearchSidecar`,`visionSidecar`].map(t=>{let a=e[t],o=t===`webSearchSidecar`?`claude.webSearchSidecar`:`claude.visionSidecar`,s=t===`webSearchSidecar`?`claude.webSearchSidecarHint`:`claude.visionSidecarHint`,c=`claude-sidecar-models-${t}`;return(0,Y.jsxs)(`div`,{className:`setting-row`,style:{alignItems:`flex-start`},children:[(0,Y.jsxs)(`div`,{className:`setting-label setting-copy`,style:{flex:1},children:[(0,Y.jsx)(`span`,{className:`title`,children:i(o)}),(0,Y.jsx)(`span`,{className:`desc`,children:i(s)})]}),(0,Y.jsxs)(`div`,{className:`setting-controls`,style:{display:`flex`,gap:8},children:[(0,Y.jsx)(kt,{value:kS(a),options:[{value:`inherit`,label:i(`claude.useMainSetting`)},{value:`auto`,label:i(`dash.backendAuto`)},{value:`openai`,label:i(`dash.backendOpenAI`)},{value:`anthropic`,label:i(`dash.backendAnthropic`)}],onChange:n=>{r({...e,[t]:AS(a,n)})},label:i(`dash.sidecarBackend`),portal:!0}),(0,Y.jsx)(`input`,{className:`input mono`,value:a?.model??``,onChange:n=>{r({...e,[t]:jS(a,n.target.value)})},placeholder:i(`claude.sidecarModelPlaceholder`),disabled:!a,list:a?c:void 0,"aria-label":i(`dash.sidecarModel`),style:{minWidth:210},autoComplete:`off`}),a&&(0,Y.jsx)(`datalist`,{id:c,children:n.map(e=>(0,Y.jsx)(`option`,{value:e},e))})]})]},t)})]})}function RS({manualEnv:e}){let t=Q();return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`p`,{className:`muted text-label`,style:{margin:`0 0 8px`},children:(0,Y.jsx)(ft,{k:`claude.quickstartHint`,cmd:`ocx claude`})}),(0,Y.jsx)(`pre`,{className:`mono card`,style:{padding:`10px 14px`,overflowX:`auto`,margin:0},children:`ocx claude`}),(0,Y.jsxs)(`details`,{style:{margin:`10px 0 0`},children:[(0,Y.jsx)(`summary`,{className:`muted text-label`,style:{cursor:`pointer`,padding:`2px 2px`},children:t(`claude.manualEnv`)}),(0,Y.jsx)(`pre`,{className:`mono card text-label`,style:{padding:`10px 14px`,overflowX:`auto`,margin:`6px 0 0`},children:e})]})]})}function zS({rows:e,onRowsChange:t}){let n=Q();return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`p`,{className:`muted text-label`,style:{margin:`0 0 8px`},children:n(`claude.modelMapHint`)}),(0,Y.jsx)(`div`,{className:`stack`,style:{gap:8},children:e.map((r,i)=>(0,Y.jsxs)(`div`,{className:`row`,style:{gap:8},children:[(0,Y.jsx)(`input`,{className:`input mono`,value:r.from,placeholder:n(`claude.mapFrom`),"aria-label":n(`claude.mapFrom`),onChange:n=>t(e.map((e,t)=>t===i?{...e,from:n.target.value}:e)),style:{flex:1}}),(0,Y.jsx)(`span`,{className:`muted`,"aria-hidden":!0,children:`→`}),(0,Y.jsx)(`input`,{className:`input mono`,value:r.to,placeholder:n(`claude.mapTo`),"aria-label":n(`claude.mapTo`),onChange:n=>t(e.map((e,t)=>t===i?{...e,to:n.target.value}:e)),style:{flex:1}}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,onClick:()=>t(e.filter((e,t)=>t!==i)),"aria-label":n(`claude.removeMapping`),style:{color:`var(--red)`},children:(0,Y.jsx)(le,{})})]},r.id))}),(0,Y.jsx)(`div`,{style:{marginTop:8},children:(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>t([...e,{id:wS(),from:``,to:``}]),children:[(0,Y.jsx)(ue,{}),` `,n(`claude.addMapping`)]})})]})}var BS=`etc`;function VS(e){let t=new Map;for(let n of e){let e=/\(([^)]+)\)\s*$/.exec(n.display_name),r=e?e[1]:BS,i=t.get(r);i?i.push(n):t.set(r,[n])}return Array.from(t)}function HS({aliases:e}){let t=Q();return(0,Y.jsxs)(`div`,{className:`claude-aliases`,children:[(0,Y.jsx)(`p`,{className:`muted text-label claude-aliases-hint`,children:t(`claude.aliasesHint`)}),e.length===0?(0,Y.jsx)(`div`,{className:`muted text-label`,children:t(`claude.none`)}):(0,Y.jsx)(`div`,{className:`claude-aliases-scroll`,children:VS(e).map(([e,n])=>(0,Y.jsxs)(`div`,{className:`claude-aliases-group`,children:[(0,Y.jsxs)(`div`,{className:`claude-aliases-group-label`,children:[e===BS?t(`claude.aliasProviderOther`):e,(0,Y.jsx)(`span`,{className:`claude-aliases-group-count`,children:n.length})]}),(0,Y.jsx)(`div`,{className:`claude-aliases-chips`,children:n.map(e=>(0,Y.jsxs)(`span`,{className:`claude-aliases-chip`,children:[(0,Y.jsx)(`code`,{className:`claude-aliases-chip-id`,children:e.id}),e.display_name?(0,Y.jsx)(`span`,{className:`claude-aliases-chip-name`,children:e.display_name}):null]},e.id))})]},e))})]})}function US({apiBase:e,active:t=!0}){let n=Q(),{locale:r}=ut(),i=nt.find(e=>e.code===r)?.htmlLang??`en`,a=`ocx.claude-code.v1:${e}`,o=`claude-code:${e}`,s=(0,_.useMemo)(()=>Dr(a),[a]),c=s?.data??null,[l,u]=(0,_.useState)(()=>c?.state??null),[d,f]=(0,_.useState)(()=>c?.rows??[]),[p,m]=(0,_.useState)(!!c),[h,g]=(0,_.useState)(``),[v,y]=(0,_.useState)(!1),[b,x]=(0,_.useState)(`settings`),[S,C]=(0,_.useState)(!1),w=(0,_.useRef)(!1),T=(0,_.useCallback)(async t=>{let r=await It(await fetch(`${e}/api/claude-code`,{signal:t}),n(`claude.loadFail`));if(!r)throw Error(n(`claude.loadFail`));let i={...r,authMode:r.authMode===`proxy`||r.authMode===`subscription`?r.authMode:`auto`,...CS(r),fastMode:r.fastMode??null,maxContextTokens:r.maxContextTokens??null,autoContext:r.autoContext!==!1,autoCompactWindow:r.autoCompactWindow??null,injectAgents:r.injectAgents!==!1,effectiveModelEnv:r.effectiveModelEnv??{}},o=Object.entries(r.modelMap??{}).map(([e,t])=>({id:wS(),from:e,to:String(t)})),s={state:i,rows:o};if(t.aborted)throw Error(`Claude Code request aborted`);return u(i),f(o),m(!0),Or(a,s),s},[e,a,n]),E=jr(o,[e],T,{isEmpty:()=>!1,enabled:t,initialData:c??void 0,initialDataCachedAt:s?.cachedAt??null,staleAfterMs:6e4}),D=E.state,O=D.data??c,k=l??O?.state??null,A=p?d:O?.rows??d,j=(0,_.useMemo)(()=>SS(k?.available,n(`claude.smallFastModelUnsetOption`)),[k?.available,n]),M=(0,_.useMemo)(()=>{let e=[1e5,2e5,25e4,3e5,35e4,4e5,5e5,6e5,75e4,TS,9e5,1e6].sort((e,t)=>e-t),t=k?.autoCompactWindow??null,r=t!==null&&!e.includes(t)?[...e,t].sort((e,t)=>e-t):e;return[{value:``,label:n(`claude.autoCompactDefault`,{value:ES(TS,i)})},...r.map(e=>({value:String(e),label:ES(e,i)}))]},[k?.autoCompactWindow,n,i]),N=async()=>{if(!k||w.current)return;w.current=!0,C(!0),g(``);let t=!k.enabled;try{await It(await fetch(`${e}/api/claude-code`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({enabled:t})}),n(`claude.saveFailed`)),u({...k,enabled:t}),E.refresh()}catch(e){y(!1),g(e instanceof Error&&e.message?e.message:n(`claude.networkError`))}finally{w.current=!1,C(!1)}},P=async()=>{if(!k)return;g(``);let t={};for(let e of A)e.from.trim()&&e.to.trim()&&(t[e.from.trim()]=e.to.trim());try{await It(await fetch(`${e}/api/claude-code`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({enabled:k.enabled,authMode:k.authMode,systemEnv:k.systemEnv,fastMode:k.fastMode,autoContext:k.autoContext,autoCompactWindow:k.autoCompactWindow,injectAgents:k.injectAgents,smallFastModel:k.smallFastModel,modelMap:t,webSearchSidecar:MS(k.webSearchSidecar),visionSidecar:MS(k.visionSidecar)})}),n(`claude.saveFailed`)),y(!0),g(n(`claude.saved`)),E.refresh()}catch(e){y(!1),g(e instanceof Error&&e.message?e.message:n(`claude.networkError`))}};if(D.kind===`disabled`&&!O)return null;if(D.showSkeleton&&!O)return(0,Y.jsx)(ep,{label:n(`claude.loading`),rows:3});if(D.kind===`failed-cold`){let e=D.error instanceof Error?D.error.message:n(`claude.loadFail`);return(0,Y.jsxs)(`div`,{className:`claudecode-workspace-shell`,children:[(0,Y.jsx)($,{tone:`err`,children:e}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>E.refresh(),children:n(`common.retry`)})]})}if(!k)return null;let F=[{id:`settings`,label:n(`claude.workspace.settings`),body:(0,Y.jsx)(LS,{state:k,autoCompactOptions:M,availableModels:k.available??[],onStateChange:u})},{id:`quickstart`,label:n(`claude.quickstart`),body:(0,Y.jsx)(RS,{manualEnv:OS(k)})},{id:`smallFast`,label:n(`claude.smallFastModel`),body:(0,Y.jsx)(FS,{value:k.smallFastModel,tierHaikuModel:k.tierModels?.haiku,options:j,onChange:e=>u({...k,smallFastModel:e})})},{id:`modelMap`,label:n(`claude.modelMap`),meta:String(A.length),body:(0,Y.jsx)(zS,{rows:A,onRowsChange:e=>{m(!0),f(e)}})},{id:`aliases`,label:n(`claude.aliases`),meta:String(k.aliases.length),body:(0,Y.jsx)(HS,{aliases:k.aliases})}],I=F.find(e=>e.id===b)??F[0],L=b===`settings`||b===`smallFast`||b===`modelMap`;return(0,Y.jsxs)(`div`,{className:`claudecode-workspace-shell`,children:[h&&(0,Y.jsx)($,{tone:v?`ok`:`err`,children:h}),D.showError&&(0,Y.jsx)($,{tone:`err`,children:n(`claude.loadFail`)}),k&&(0,Y.jsxs)(`div`,{className:`claudecode-connection-head`,children:[(0,Y.jsx)(`span`,{id:`claudecode-connection-label`,children:n(`claude.enabledLabel`)}),(0,Y.jsx)(Dt,{on:k.enabled,onClick:()=>void N(),disabled:S,label:n(`claude.toggleAria`)})]}),(0,Y.jsxs)(`div`,{className:`claudecode-workspace-root`,children:[(0,Y.jsx)(`aside`,{className:`claudecode-workspace-rail`,"aria-label":n(`claude.pageTitle`),children:(0,Y.jsx)(`div`,{className:`claudecode-workspace-rail-list`,children:F.map(e=>(0,Y.jsx)(`button`,{type:`button`,className:`claudecode-workspace-rail-row${b===e.id?` claudecode-workspace-rail-row--selected`:``}`,onClick:()=>x(e.id),"aria-current":b===e.id?`true`:void 0,children:(0,Y.jsx)(`span`,{className:`claudecode-workspace-rail-name`,children:e.label})},e.id))})}),(0,Y.jsxs)(`section`,{className:`claudecode-workspace-main`,"aria-label":I.label,children:[(0,Y.jsxs)(`div`,{className:`ccw-main-head`,children:[(0,Y.jsxs)(`h3`,{className:`ccw-main-title`,children:[I.label,I.meta==null?null:(0,Y.jsx)(`span`,{className:`count`,children:I.meta})]}),(0,Y.jsx)(`div`,{className:`claudecode-workspace-save`,"data-visible":L?`true`:`false`,children:(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:!L,tabIndex:L?0:-1,"aria-hidden":!L,onClick:()=>{P()},children:n(`common.save`)})})]}),(0,Y.jsx)(`div`,{className:`ccw-body`,children:I.body})]})]})]})}function WS(e,t,n){let r=t.trim().toLowerCase(),i=(r?e.filter(e=>e.label.toLowerCase().includes(r)||e.route.toLowerCase().includes(r)):e).toSorted((e,t)=>Number(!e.available)-Number(!t.available)),a=i.slice(0,n);return{total:e.length,showSearch:e.length>4,shown:a,hidden:i.length-a.length,noMatch:e.length>0&&i.length===0}}function GS(e){return new Set(Object.keys(e))}function KS(e,t){return t!==null&&e===t}function qS(e){return e||(typeof localStorage>`u`?void 0:localStorage)}function JS(e){return{read(t){let n=qS(t);if(!n)return null;try{let t=n.getItem(e);if(t===null)return null;let r=JSON.parse(t);return Array.isArray(r)?new Set(r.filter(e=>typeof e==`string`)):null}catch{return null}},write(t,n){let r=qS(n);if(r)try{r.setItem(e,JSON.stringify([...t]))}catch{}}}}function YS(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n}var XS=[`opus`,`fable`,`sonnet`,`haiku`],ZS=JS(`ocx.claudeDesktop.collapsedFamilies.v2`),QS={opus:`claudeDesktop.family.opus`,fable:`claudeDesktop.family.fable`,sonnet:`claudeDesktop.family.sonnet`,haiku:`claudeDesktop.family.haiku`};function $S(e){return{version:1,assignments:Object.fromEntries(Object.entries(e.assignments).map(([e,t])=>[e,{...t}])),defaults:{...e.defaults},...e.appliedFingerprint===void 0?{}:{appliedFingerprint:e.appliedFingerprint},...e.appliedAt===void 0?{}:{appliedAt:e.appliedAt}}}function eC(e){let t={...e.profile.assignments};for(let n of e.models){let e=t[n.route]??n.assignment;t[n.route]={family:XS.includes(e?.family)?e.family:`opus`,alias:typeof e?.alias==`string`?e.alias:``}}return{version:1,assignments:t,defaults:{opus:e.profile.defaults.opus??null,fable:e.profile.defaults.fable??null,sonnet:e.profile.defaults.sonnet??null,haiku:e.profile.defaults.haiku??null}}}function tC(e,t){return e&&typeof e==`object`&&`error`in e&&typeof e.error==`string`?e.error:t}function nC(e,t){return e?e>=1048576?t(`claudeDesktop.contextM`,{n:Math.round(e/1048576)}):e>=1e6?t(`claudeDesktop.contextM`,{n:e/1e6}):t(`claudeDesktop.contextK`,{n:Math.round(e/1e3)}):null}function rC(e){return Dr(e)?.data??null}function iC(e){return Dr(e)?.cachedAt??null}function aC(e){let t=rC(e);return{held:t,data:t?.data??null,profile:t?.profile??null,savedProfile:t?.profile?$S(t.profile):null,destinations:t?.data?Object.fromEntries(t.data.models.map(e=>[e.route,t.profile.assignments[e.route]?.family??`opus`])):{}}}function oC({apiBase:e,active:t=!0,onPortChange:n}){let{t:r,locale:i}=ut(),a=nt.find(e=>e.code===i)?.htmlLang,o=`ocx.claude-desktop.v1:${e}`,s=`claude-desktop:${e}`,c=(0,_.useMemo)(()=>aC(o),[o]),[l,u]=(0,_.useState)(()=>c.profile),[d,f]=(0,_.useState)(()=>c.savedProfile),[p,m]=(0,_.useState)(()=>c.destinations),[h,g]=(0,_.useState)(null),[v,y]=(0,_.useState)(``),[b,x]=(0,_.useState)(null),[S,C]=(0,_.useState)({}),[w,T]=(0,_.useState)({}),[E,D]=(0,_.useState)(()=>ZS.read()??new Set(XS)),[O,k]=(0,_.useState)({}),A=(0,_.useRef)(null),j=(0,_.useCallback)(async t=>{let n=await It(await fetch(`${e}/api/claude-desktop`,{signal:t}),r(`claudeDesktop.loadFail`));if(!n||!(`profile`in n)||!(`models`in n))throw Error(tC(n,r(`claudeDesktop.loadFail`)));let i=eC(n),a={data:n,profile:i};if(t.aborted)throw Error(`Claude Desktop request aborted`);if(u(i),f($S(i)),m(Object.fromEntries(n.models.map(e=>[e.route,i.assignments[e.route]?.family??`opus`]))),ZS.read()===null){let e=Object.fromEntries(XS.map(e=>[e,0]));for(let t of n.models)e[i.assignments[t.route]?.family??`opus`]+=1;D(GS(e))}return Or(o,a),a},[e,o,r,m,u,f]),M=jr(s,[e],j,{isEmpty:()=>!1,enabled:t,initialData:c.held??void 0,initialDataCachedAt:iC(o),staleAfterMs:6e4}),N=M.state,P=N.data??(c.data&&c.profile?{data:c.data,profile:c.profile}:null),F=P?.data??null,I=l??P?.profile??null,L=d??P?.profile??null,R=P?Object.fromEntries(P.data.models.map(e=>[e.route,P.profile.assignments[e.route]?.family??`opus`])):{},z=Object.keys(p).length>0?p:R;(0,_.useEffect)(()=>{if(n){if(typeof F?.port==`number`){n(F.port);return}N.kind===`failed-cold`&&n(null)}},[F?.port,N.kind,n]);let B=(0,_.useMemo)(()=>I!==null&&L!==null&&JSON.stringify(I)!==JSON.stringify(L),[I,L]),V=(0,_.useMemo)(()=>{let e=Object.fromEntries(XS.map(e=>[e,[]]));if(!F||!I)return e;for(let t of F.models)e[I.assignments[t.route]?.family??`opus`].push(t);return e},[F,I]),H=(0,_.useMemo)(()=>{let e={};for(let t of XS){let n=V[t].filter(e=>e.available).map(e=>e.route).sort(),r=I?.defaults[t]??null;e[t]=r&&n.includes(r)?r:n[0]??null}return e},[V,I]),U=`ocx.claude-desktop.status.v1:${e}`,W=`claude-desktop-status:${e}`,G=Dr(U),K=jr(W,[e],async t=>{let n=await Lt(await fetch(`${e}/api/claude-desktop/status`,{signal:t}));if(!n)throw Error(`Claude Desktop status unavailable`);return Or(U,n),n},{isEmpty:()=>!1,pollMs:5e3,enabled:t,initialData:G?.data??void 0}),q=K.state,J=q.data??G?.data??null,X=q.showError,ee=(e,t)=>{!I||I.assignments[e]?.family===t||(u(n=>{if(!n)return n;let r=n.assignments[e];if(!r||r.family===t)return n;let i={...n.assignments,[e]:{...r,family:t}},a={...n.defaults};return a[r.family]===e&&(a[r.family]=Object.keys(i).filter(t=>t!==e&&i[t].family===r.family).sort()[0]??null),a[t]===null&&(a[t]=e),{...n,assignments:i,defaults:a}}),m(n=>({...n,[e]:t})),y(r(`claudeDesktop.moved`,{route:e,family:r(QS[t])})))},te=e=>{let t=YS(E,e);ZS.write(t),D(t)},ne=async t=>{if(!(!I||b)){x(`save`),g(null);try{await It(await fetch(`${e}/api/claude-desktop`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({profile:I})}),r(`claudeDesktop.saveFailed`)),f($S(I)),t?(x(`apply`),(await It(await fetch(`${e}/api/claude-desktop/apply`,{method:`POST`}),r(`claudeDesktop.applyFailed`)))?.saved===!1?(g({tone:`warn`,text:r(`claudeDesktop.appliedMarkerUnsaved`)}),y(r(`claudeDesktop.appliedMarkerUnsaved`))):(g({tone:`ok`,text:r(`claudeDesktop.savedApplied`)}),y(r(`claudeDesktop.savedAppliedAnnounce`)))):(g({tone:`ok`,text:r(`claudeDesktop.saved`)}),y(r(`claudeDesktop.savedAnnounce`))),K.refresh()}catch(e){let t=e instanceof Error?e.message:r(`claudeDesktop.updateFailed`);g({tone:`err`,text:t}),y(t)}finally{x(null)}}},Z=()=>{if(!I)return;let e=URL.createObjectURL(new Blob([`${JSON.stringify(I,null,2)}\n`],{type:`application/json`})),t=document.createElement(`a`);t.href=e,t.download=`claude-desktop-profile.json`,t.click(),URL.revokeObjectURL(e),y(r(`claudeDesktop.exported`))},re=async e=>{let t=e.target.files?.[0];if(e.target.value=``,t)try{let e=JSON.parse(await t.text());if(e.version!==1||!e.assignments||!e.defaults)throw Error(r(`claudeDesktop.importExpected`));let n=eC({...F,profile:e});u(n),g({tone:`ok`,text:r(`claudeDesktop.importReady`)}),y(r(`claudeDesktop.importedAnnounce`))}catch(e){let t=e instanceof Error?e.message:r(`claudeDesktop.importInvalid`);g({tone:`err`,text:t}),y(r(`claudeDesktop.importFailed`,{error:t}))}},ie=(e,t)=>{e.preventDefault();let n=e.dataTransfer.getData(`text/plain`);n&&ee(n,t)};if(N.kind===`disabled`&&!P)return null;if(N.showSkeleton&&!P)return(0,Y.jsx)(ep,{label:r(`claudeDesktop.loading`),rows:4});if(N.kind===`failed-cold`){let e=N.error instanceof Error?N.error.message:r(`claudeDesktop.loadFail`);return(0,Y.jsxs)(`div`,{className:`claude-desktop-error`,children:[(0,Y.jsx)($,{tone:`err`,children:e}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>M.refresh(),children:r(`claudeDesktop.retry`)})]})}return!F||!I?null:(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`div`,{className:`claude-desktop-toolbar`,children:(0,Y.jsxs)(`div`,{className:`claude-profile-tools`,children:[(0,Y.jsx)(`input`,{ref:A,type:`file`,accept:`application/json,.json`,hidden:!0,onChange:e=>void re(e)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>A.current?.click(),children:r(`claudeDesktop.importJson`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:Z,children:r(`claudeDesktop.exportJson`)})]})}),(0,Y.jsxs)(`div`,{className:`claude-status-bar ${X&&!J?`not-applied`:J?J.desiredEnabled?J.activeProfile===!1?`not-applied`:J.stale?`stale`:J.applied?`applied`:`not-applied`:`not-applied`:`pending`}`,"aria-busy":!J&&!X||void 0,children:[(0,Y.jsx)(`span`,{className:`claude-status-dot`}),(0,Y.jsx)(`span`,{children:X&&!J?r(`claudeDesktop.loadFail`):J?J.desiredEnabled?J.activeProfile===!1?r(`claudeDesktop.status.notActiveProfile`):J.stale?r(`claudeDesktop.status.stale`):J.applied?r(`claudeDesktop.status.applied`):r(`claudeDesktop.status.notApplied`):r(`claudeDesktop.status.disabled`):r(`claudeDesktop.loading`)}),J?.health.lastRequestAt&&(0,Y.jsxs)(`span`,{className:`claude-status-health`,children:[r(`claudeDesktop.health.lastRequest`),`:`,` `,new Date(J.health.lastRequestAt).toLocaleTimeString(a)]}),J&&J.health.requestCount>0&&(0,Y.jsx)(`span`,{className:`claude-status-health`,children:r(`claudeDesktop.health.stats`,{count:J.health.requestCount,errors:J.health.errorCount})})]}),(0,Y.jsx)(`div`,{className:`sr-only`,"aria-live":`polite`,"aria-atomic":`true`,children:v}),h&&(0,Y.jsx)($,{tone:h.tone,children:h.text}),N.showError&&(0,Y.jsx)($,{tone:`err`,children:r(`claudeDesktop.loadFail`)}),X&&J&&(0,Y.jsx)($,{tone:`err`,children:r(`claudeDesktop.loadFail`)}),(0,Y.jsxs)(`div`,{className:`claude-profile-bar`,children:[(0,Y.jsx)(`span`,{className:`claude-dirty${B?` active`:``}`,children:r(B?`claudeDesktop.unsaved`:`claudeDesktop.upToDate`)}),(0,Y.jsxs)(`div`,{className:`claude-save-actions`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:!B||b!==null,onClick:()=>void ne(!1),children:r(b===`save`?`claudeDesktop.saving`:`common.save`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:b!==null,onClick:()=>void ne(!0),children:b===`apply`?r(`claudeDesktop.applying`):b===`save`?r(`claudeDesktop.saving`):J?.desiredEnabled===!1?r(`claudeDesktop.enableApply`):r(`claudeDesktop.saveApply`)})]})]}),F.models.length===0&&(0,Y.jsx)(At,{title:r(`claudeDesktop.emptyTitle`),children:r(`claudeDesktop.emptyHint`)}),(0,Y.jsx)(`div`,{className:`ocx-group-stack`,"aria-label":r(`claudeDesktop.assignmentsLabel`),children:XS.map(e=>{let t=V[e],n=WS(t,S[e]??``,w[e]??6),i=E.has(e),a=H[e];return(0,Y.jsxs)(`section`,{className:`ocx-group${i?` collapsed`:``}`,"aria-labelledby":`claude-lane-${e}`,onDragOver:e=>e.preventDefault(),onDrop:t=>ie(t,e),children:[(0,Y.jsxs)(`header`,{className:`ocx-group-head${i?``:` open`}`,children:[(0,Y.jsx)(`h3`,{id:`claude-lane-${e}`,className:`ocx-group-heading`,children:(0,Y.jsxs)(`button`,{type:`button`,className:`ocx-group-toggle`,"aria-expanded":!i,"aria-controls":`claude-lane-body-${e}`,onClick:()=>te(e),children:[(0,Y.jsx)(Ce,{className:`ocx-chevron`,width:14,height:14,"aria-hidden":`true`,style:{transform:i?`none`:`rotate(90deg)`}}),(0,Y.jsx)(`span`,{className:`ocx-group-name`,children:r(QS[e])}),(0,Y.jsx)(`span`,{className:`ocx-group-count`,children:r(t.length===1?`claudeDesktop.modelCountOne`:`claudeDesktop.modelCountMany`,{count:t.length})}),a&&(0,Y.jsx)(`code`,{className:`claude-lane-default`,title:a,children:a})]})}),t.length>0&&I.defaults[e]===null&&(0,Y.jsx)(`span`,{className:`claude-default-needed`,children:r(`claudeDesktop.chooseDefault`)}),a&&a!==I.defaults[e]&&(0,Y.jsx)(`span`,{className:`claude-default-needed`,title:a,children:r(`claudeDesktop.temporaryDefault`)})]}),!i&&(0,Y.jsxs)(`div`,{id:`claude-lane-body-${e}`,children:[n.showSearch&&(0,Y.jsx)(`input`,{className:`input claude-lane-search`,type:`search`,placeholder:r(`models.search`),"aria-label":r(`models.search`),value:S[e]??``,onChange:t=>{let n=t.target.value;C(t=>({...t,[e]:n})),T(t=>({...t,[e]:6}))}}),(0,Y.jsxs)(`div`,{className:`claude-lane-models`,children:[t.length===0?(0,Y.jsx)(`div`,{className:`claude-lane-empty`,children:r(`claudeDesktop.laneEmpty`)}):n.noMatch?(0,Y.jsx)(`div`,{className:`claude-lane-empty`,children:r(`claudeDesktop.laneNoMatch`)}):n.shown.map(t=>{let n=I.assignments[t.route],i=nC(t.contextWindow,r),a=z[t.route]??`opus`,o=O[t.route]??KS(t.route,H[e]);return(0,Y.jsxs)(`article`,{className:`claude-model-card${o?` open`:``}`,draggable:t.available,onDragStart:e=>{e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,t.route)},children:[(0,Y.jsxs)(`button`,{type:`button`,className:`claude-model-summary`,"aria-expanded":o,"aria-controls":`claude-model-body-${t.route}`,onClick:()=>k(e=>({...e,[t.route]:!o})),children:[(0,Y.jsx)(Ce,{className:`ocx-chevron`,width:12,height:12,"aria-hidden":`true`,style:{transform:o?`rotate(90deg)`:`none`}}),(0,Y.jsxs)(`span`,{className:`claude-model-names`,children:[(0,Y.jsx)(`strong`,{title:t.label,children:t.label}),(0,Y.jsx)(`code`,{title:t.route,children:t.route})]}),i&&(0,Y.jsx)(`span`,{className:`claude-model-context`,children:i}),!i&&(0,Y.jsx)(`span`,{className:`claude-model-context claude-model-context-unknown`,children:r(`claudeDesktop.contextUnknown`)}),t.supports1m===!0&&(0,Y.jsx)(`span`,{className:`claude-1m-chip`,children:r(`claudeDesktop.supports1m`)}),t.effortSupported===!1&&(0,Y.jsx)(`span`,{className:`claude-effort-badge off`,children:r(`claudeDesktop.effort.displayOnly`)}),t.effortSupported===!0&&(0,Y.jsx)(`span`,{className:`claude-effort-badge on`,children:r(`claudeDesktop.effort.supported`)}),I.defaults[e]===t.route&&(0,Y.jsx)(`span`,{className:`claude-row-default`,children:r(`claudeDesktop.defaultBadge`)}),(0,Y.jsx)(`span`,{className:`badge ${t.available?`badge-green`:`badge-muted`}`,children:t.available?r(`claudeDesktop.available`):r(`claudeDesktop.unavailable`)})]}),o&&(0,Y.jsxs)(`div`,{className:`claude-model-body`,id:`claude-model-body-${t.route}`,children:[H[e]===t.route&&I.defaults[e]!==t.route&&(0,Y.jsx)(`span`,{className:`claude-effective-default`,children:r(`claudeDesktop.temporaryDefault`)}),(0,Y.jsxs)(`div`,{className:`claude-field`,children:[(0,Y.jsx)(`span`,{children:r(`claudeDesktop.alias`)}),(0,Y.jsx)(`code`,{className:`claude-alias`,title:n.alias,children:n.alias})]}),(0,Y.jsxs)(`label`,{className:`claude-default-radio`,children:[(0,Y.jsx)(`input`,{type:`radio`,name:`default-${e}`,checked:I.defaults[e]===t.route,disabled:!t.available,onChange:()=>u(n=>n&&{...n,defaults:{...n.defaults,[e]:t.route}})}),r(`claudeDesktop.useAsDefault`,{family:r(QS[e])})]}),(0,Y.jsxs)(`div`,{className:`claude-move-row`,children:[(0,Y.jsx)(`label`,{htmlFor:`move-${t.route}`,children:r(`claudeDesktop.moveTo`)}),(0,Y.jsx)(`select`,{id:`move-${t.route}`,className:`input`,value:a,disabled:!t.available,onChange:e=>m(n=>({...n,[t.route]:e.target.value})),children:XS.map(e=>(0,Y.jsx)(`option`,{value:e,children:r(QS[e])},e))}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:!t.available||a===e,onClick:()=>ee(t.route,a),children:r(`claudeDesktop.move`)})]})]})]},t.route)}),n.hidden>0&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm claude-lane-more`,onClick:()=>T(t=>({...t,[e]:(t[e]??6)+6})),children:r(`models.showMore`,{n:n.hidden})})]})]})]},e)})})]})}var sC=`integrations/claude`,cC=`integrations/claude/desktop`;function lC(e=typeof window<`u`?window.location.hash:``){return pt(e)===cC?`desktop`:`code`}function uC(e){let t=Tr(`ocx.claude-desktop.v1:${e}`);return typeof t?.data?.port==`number`?t.data.port:null}function dC({apiBase:e,active:t=!0}){let[n,r]=(0,_.useState)(lC),i=Q(),a=(0,_.useRef)(null),o=(0,_.useRef)(null),s=uC(e),[c,l]=(0,_.useState)(null),u=c?.base===e?c.port:s,d=c?.base===e,f=(0,_.useCallback)(t=>{l(n=>n?.base===e&&n.port===t?n:{base:e,port:t})},[e]);(0,_.useEffect)(()=>{let e=()=>r(lC());return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]);let p=e=>{ht(e===`desktop`?cC:sC),r(e),window.requestAnimationFrame(()=>{(e===`code`?a:o).current?.focus({preventScroll:!0})})},m=e=>{e.key===`ArrowLeft`||e.key===`ArrowRight`?(e.preventDefault(),p(n===`code`?`desktop`:`code`)):e.key===`Home`?(e.preventDefault(),p(`code`)):e.key===`End`&&(e.preventDefault(),p(`desktop`))};return(0,Y.jsxs)(`section`,{className:`claude-page`,children:[(0,Y.jsxs)(`div`,{className:`claude-page-intro`,children:[(0,Y.jsx)(`div`,{className:`page-head`,children:(0,Y.jsx)(`h2`,{children:i(n===`code`?`claude.pageTitle`:`claudeDesktop.title`)})}),n===`code`?(0,Y.jsx)(`p`,{className:`page-sub`,children:i(`claude.subtitle`)}):(0,Y.jsx)(`p`,{className:`page-sub`,children:u==null?i(d?`claudeDesktop.loadFail`:`claudeDesktop.loading`):i(`claudeDesktop.subtitle`,{port:u})})]}),(0,Y.jsxs)(`div`,{className:`claude-tabs`,role:`tablist`,"aria-label":i(`claude.tabsLabel`),children:[(0,Y.jsx)(`button`,{type:`button`,role:`tab`,ref:a,"aria-selected":n===`code`,"aria-controls":`claude-code-panel`,id:`claude-code-tab`,className:n===`code`?`active`:``,tabIndex:n===`code`?0:-1,onKeyDown:m,onClick:()=>p(`code`),children:i(`claude.tabCode`)}),(0,Y.jsx)(`button`,{type:`button`,role:`tab`,ref:o,"aria-selected":n===`desktop`,"aria-controls":`claude-desktop-panel`,id:`claude-desktop-tab`,className:n===`desktop`?`active`:``,tabIndex:n===`desktop`?0:-1,onKeyDown:m,onClick:()=>p(`desktop`),children:i(`claude.tabDesktop`)})]}),(0,Y.jsx)(`div`,{id:`claude-code-panel`,role:`tabpanel`,"aria-labelledby":`claude-code-tab`,hidden:n!==`code`,children:(0,Y.jsx)(US,{apiBase:e,active:t&&n===`code`},e)}),(0,Y.jsx)(`div`,{id:`claude-desktop-panel`,role:`tabpanel`,"aria-labelledby":`claude-desktop-tab`,hidden:n!==`desktop`,children:(0,Y.jsx)(oC,{apiBase:e,active:t&&n===`desktop`,onPortChange:f},e)})]})}function fC(e,t,n,r){let i=e.filter(e=>r===`native`===e.native).map(e=>({...e,alias:t.get(e.id)??null,enabled:!n.has(e.id)})).toSorted((e,t)=>Number(!e.enabled)-Number(!t.enabled));return{rows:i,total:i.length,enabled:i.filter(e=>e.enabled).length}}var pC=JS(`ocx.grok.collapsedGroups.v2`),mC=[{id:`native`,tkey:`grok.groupNative`},{id:`routed`,tkey:`grok.groupRouted`}],hC=new Set(mC.map(e=>e.id));function gC(e,t){return e?e>=1048576?t(`claudeDesktop.contextM`,{n:Math.round(e/1048576)}):e>=1e6?t(`claudeDesktop.contextM`,{n:e/1e6}):t(`claudeDesktop.contextK`,{n:Math.round(e/1e3)}):`—`}function _C({apiBase:e,active:t=!0}){let n=Q(),r=`ocx.grok.status.v1:${e}`,i=Dr(r),a=i?.data??null,[o,s]=(0,_.useState)(null),[c,l]=(0,_.useState)(()=>pC.read()??new Set(hC)),[u,d]=(0,_.useState)(null),[f,p]=(0,_.useState)(null),[m,h]=(0,_.useState)(``),g=(0,_.useCallback)(async t=>{let i=await It(await fetch(`${e}/api/grok`,{signal:t}),n(`grok.loadFail`));if(!i)throw Error(n(`grok.loadFail`));let a={...i,candidates:i.candidates??[],excluded:i.excluded??[]};return Or(r,a),a},[e,r,n]),v=`grok-status:${e}`,y=jr(v,[e],g,{isEmpty:()=>!1,initialData:a??void 0,initialDataCachedAt:i?.cachedAt??null,staleAfterMs:6e4,enabled:t}),{state:b}=y,x=y.refresh,S=b.data??a,C=(0,_.useMemo)(()=>new Set(S?.excluded??[]),[S]),w=o??C,T=(0,_.useMemo)(()=>o!==null&&(o.size!==C.size||[...o].some(e=>!C.has(e))),[o,C]),E=(0,_.useMemo)(()=>new Map((S?.models??[]).map(e=>[e.id,e.alias])),[S]),D=e=>{let t=YS(c,e);pC.write(t),l(t)},O=e=>{let t=e?new Set(mC.map(e=>e.id)):new Set;pC.write(t),l(t)},k=(e,t)=>{s(n=>{let r=new Set(n??C);return t?r.delete(e):r.add(e),r})},A=async t=>{if(!u){d(`save`),p(null);try{await It(await fetch(`${e}/api/grok/selection`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({excluded:[...w]})}),n(`grok.saveFailed`));let i=[...w];if(S&&q(v,{...S,excluded:i}),s(null),t){d(`apply`);let t=await fetch(`${e}/api/grok/apply`,{method:`POST`});if(!t.ok){let e=await t.json().catch(()=>({}));throw Error(e.message??e.error??n(`grok.applyFailed`))}let r=await t.json().catch(()=>({}));r.skippedReason?(p({tone:`err`,text:r.message??n(`grok.applySkipped`)}),h(r.message??n(`grok.applySkipped`))):(p({tone:`ok`,text:n(`grok.savedApplied`)}),h(n(`grok.savedApplied`))),await x()}else p({tone:`ok`,text:n(`grok.saved`)}),h(n(`grok.saved`)),S&&Or(r,{...S,excluded:i})}catch(e){let t=e instanceof Error?e.message:n(`grok.saveFailed`);p({tone:`err`,text:t}),h(t)}finally{d(null)}}};if(b.showSkeleton&&!S)return(0,Y.jsx)(`section`,{className:`grok-page`,children:(0,Y.jsx)(ep,{label:n(`grok.loading`),rows:4})});if(b.kind===`failed-cold`){let e=b.error instanceof Error?b.error.message:n(`grok.loadFail`);return(0,Y.jsxs)(`section`,{className:`grok-page`,children:[(0,Y.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:e}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>x(),children:n(`common.retry`)})]})}return(0,Y.jsxs)(`section`,{className:`grok-page`,"aria-busy":b.refreshing||void 0,children:[(0,Y.jsx)(`h2`,{className:`page-title`,children:n(`grok.title`)}),(0,Y.jsx)(`p`,{className:`page-sub`,children:n(`grok.subtitle`)}),(0,Y.jsx)(`div`,{className:`sr-only`,"aria-live":`polite`,"aria-atomic":`true`,children:m}),f&&(0,Y.jsx)($,{tone:f.tone,children:f.text}),b.showError&&(0,Y.jsx)($,{tone:`err`,children:n(`grok.loadFail`)}),S&&S.candidates.length>0&&(0,Y.jsxs)(`div`,{className:`claude-profile-bar`,children:[(0,Y.jsx)(`span`,{className:`claude-dirty${T?` active`:``}`,children:n(T?`grok.unsaved`:`grok.upToDate`)}),(0,Y.jsxs)(`div`,{className:`claude-save-actions`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:!T||u!==null,onClick:()=>void A(!1),children:n(u===`save`?`grok.saving`:`common.save`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!T||u!==null,onClick:()=>void A(!0),children:n(u===`apply`?`grok.applying`:u===`save`?`grok.saving`:`grok.saveApply`)})]})]}),S?.present?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{className:`grok-endpoint`,children:[(0,Y.jsx)(`span`,{children:n(`grok.endpoint`)}),(0,Y.jsx)(`code`,{children:S.baseUrl??`—`})]}),(0,Y.jsx)(`p`,{className:`page-sub`,children:(0,Y.jsx)(`code`,{children:S.configPath})})]}):(0,Y.jsxs)(At,{title:n(`grok.notConfiguredTitle`),children:[n(`grok.notConfiguredHint`),(0,Y.jsx)(`br`,{}),(0,Y.jsx)(`code`,{children:S?.configPath})]}),S&&S.candidates.length>0&&(0,Y.jsxs)(`div`,{className:`ocx-group-stack`,children:[(0,Y.jsxs)(`div`,{className:`row`,style:{gap:6,margin:`2px 0 10px`},children:[(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>O(!0),disabled:u!==null,children:[(0,Y.jsx)(Ce,{width:12,height:12,"aria-hidden":`true`}),` `,n(`models.collapseAll`)]}),(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>O(!1),disabled:u!==null,children:[(0,Y.jsx)(Ce,{width:12,height:12,"aria-hidden":`true`,style:{transform:`rotate(90deg)`}}),` `,n(`models.expandAll`)]})]}),mC.map(e=>{let t=fC(S.candidates,E,w,e.id);if(t.total===0)return null;let r=c.has(e.id);return(0,Y.jsxs)(`section`,{className:`ocx-group${r?` collapsed`:``}`,"aria-labelledby":`grok-group-${e.id}`,children:[(0,Y.jsx)(`header`,{className:`ocx-group-head${r?``:` open`}`,children:(0,Y.jsx)(`h3`,{id:`grok-group-${e.id}`,className:`ocx-group-heading`,children:(0,Y.jsxs)(`button`,{type:`button`,className:`ocx-group-toggle`,"aria-expanded":!r,"aria-controls":`grok-group-body-${e.id}`,onClick:()=>D(e.id),children:[(0,Y.jsx)(Ce,{className:`ocx-chevron`,width:14,height:14,"aria-hidden":`true`,style:{transform:r?`none`:`rotate(90deg)`}}),(0,Y.jsx)(`span`,{className:`ocx-group-name`,children:n(e.tkey)}),(0,Y.jsx)(`span`,{className:`ocx-group-count`,children:n(`grok.enabledCount`,{on:t.enabled,total:t.total})})]})})}),!r&&(0,Y.jsx)(`div`,{id:`grok-group-body-${e.id}`,className:`grok-model-list`,children:t.rows.map(e=>(0,Y.jsxs)(`div`,{className:`grok-model-row`,children:[(0,Y.jsx)(Dt,{on:e.enabled,onClick:()=>k(e.id,!e.enabled),disabled:u!==null,label:n(`grok.toggleModel`,{id:e.id})}),(0,Y.jsxs)(`span`,{className:`grok-model-names`,children:[(0,Y.jsx)(`strong`,{title:e.id,children:e.id}),(0,Y.jsx)(`code`,{title:e.alias??void 0,children:e.alias??`—`})]}),(0,Y.jsx)(`span`,{className:`claude-model-context`,children:gC(e.contextWindow,n)})]},e.id))})]},e.id)})]})]})}async function vC(e,t){try{let n=await fetch(`${e}/api/native-integrations/cursor`,{signal:t});if(!n.ok)return null;let r=await Lt(n);return!r||typeof r!=`object`||!r.gateway||!r.privateInference?null:r}catch{return null}}function yC({value:e,label:t}){let n=Q(),[r,i]=(0,_.useState)(!1),a=(0,_.useRef)(null);(0,_.useEffect)(()=>()=>{a.current!==null&&window.clearTimeout(a.current)},[]);let o=async()=>{try{await navigator.clipboard.writeText(e),i(!0),a.current!==null&&window.clearTimeout(a.current),a.current=window.setTimeout(()=>i(!1),1500)}catch{i(!1)}};return(0,Y.jsxs)(`div`,{className:`cursor-gateway-row`,children:[(0,Y.jsx)(`span`,{className:`cursor-gateway-label`,children:t}),(0,Y.jsx)(`code`,{className:`cursor-gateway-value`,children:e}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void o(),"aria-label":`${n(`integrations.cursor.copy`)} ${t}`,children:n(r?`integrations.cursor.copied`:`integrations.cursor.copy`)})]})}function bC({labelKey:e,installed:t,path:n,version:r}){let i=Q();return(0,Y.jsxs)(`div`,{className:`cursor-detect-row`,"data-installed":t?`true`:`false`,children:[(0,Y.jsx)(`span`,{className:`cursor-detect-name`,children:i(e)}),(0,Y.jsx)(`span`,{className:`badge ${t?`badge-green`:`badge-muted`}`,children:i(t?`integrations.cursor.detected`:`integrations.cursor.notFound`)}),t&&n&&(0,Y.jsxs)(`span`,{className:`cursor-detect-path muted`,children:[r?`${r} · `:``,n]})]})}function xC({apiBase:e,active:t}){let{t:n,locale:r}=ut(),[i,a]=(0,_.useState)(()=>Date.now()),o=(0,_.useCallback)(async t=>{let n=await vC(e,t);if(!n)throw Error(`cursor status unavailable`);return a(Date.now()),n},[e]),s=jr(`integration-cursor-page:${e}`,[e],o,{isEmpty:()=>!1,enabled:t,pollMs:15e3,pauseWhenHidden:!0}),c=s.state.data??null,l=Pi(n);return(0,Y.jsxs)(`section`,{className:`integration-native-page cursor-page`,"aria-labelledby":`cursor-integration-title`,children:[(0,Y.jsx)(`h3`,{id:`cursor-integration-title`,children:n(`integrations.cursor.title`)}),(0,Y.jsx)(`p`,{children:n(`integrations.cursor.intro`)}),s.state.showError&&(0,Y.jsx)($,{tone:`err`,children:n(`integrations.cursor.unavailable`)}),!c&&!s.state.showError&&(0,Y.jsx)(ep,{label:n(`integrations.cursor.loading`),rows:4}),c&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{className:`cursor-card`,children:[(0,Y.jsx)(`h4`,{children:n(`integrations.cursor.detection`)}),(0,Y.jsx)(bC,{labelKey:`integrations.cursor.privateInference`,installed:c.privateInference.installed,path:c.privateInference.path,version:c.privateInference.version}),(0,Y.jsx)(bC,{labelKey:`integrations.cursor.regular`,installed:c.regularCursor.installed,path:c.regularCursor.path,version:null}),!c.privateInference.installed&&(0,Y.jsxs)($,{tone:`warn`,children:[n(c.regularCursor.installed?`integrations.cursor.regularOnly`:`integrations.cursor.nothingFound`),` `,(0,Y.jsx)(`a`,{href:c.guideUrl,target:`_blank`,rel:`noreferrer`,"data-cursor-guide":`notice`,children:n(`integrations.cursor.guide`)})]})]}),(0,Y.jsxs)(`div`,{className:`cursor-card`,children:[(0,Y.jsx)(`h4`,{children:n(`integrations.cursor.gateway`)}),(0,Y.jsx)(`p`,{className:`muted`,children:n(`integrations.cursor.gatewayHint`)}),(0,Y.jsx)(yC,{label:n(`integrations.cursor.baseUrl`),value:c.gateway.baseUrl}),c.gateway.apiKeyMode===`placeholder`?(0,Y.jsx)(yC,{label:n(`integrations.cursor.apiKey`),value:c.gateway.placeholder}):(0,Y.jsxs)(`div`,{className:`cursor-gateway-row`,children:[(0,Y.jsx)(`span`,{className:`cursor-gateway-label`,children:n(`integrations.cursor.apiKey`)}),(0,Y.jsx)(`span`,{className:`cursor-gateway-value`,children:n(`integrations.cursor.apiKeyCredential`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>ht(`integrations/keys`),children:n(`integrations.tab.keys`)})]})]}),(0,Y.jsxs)(`div`,{className:`cursor-card`,"data-seen":c.lastSeen?`true`:`false`,children:[(0,Y.jsx)(`h4`,{children:n(`integrations.cursor.connection`)}),c.lastSeen?(0,Y.jsx)(`p`,{children:(0,Y.jsx)(`span`,{className:`badge ${i-c.lastSeen.at<864e5?`badge-green`:`badge-muted`}`,children:n(`integrations.cursor.seen`,{time:Ni(c.lastSeen.at,l,i),ua:c.lastSeen.userAgent})})}):(0,Y.jsx)(`p`,{className:`muted`,children:n(`integrations.cursor.neverSeen`)})]}),(0,Y.jsxs)(`div`,{className:`cursor-card`,children:[(0,Y.jsx)(`h4`,{children:n(`integrations.cursor.models`)}),(0,Y.jsx)(`p`,{className:`muted`,children:c.effortTable.source===`bundle`?n(`integrations.cursor.ladderFromBundle`,{version:c.effortTable.version??n(`integrations.cursor.unknownVersion`)}):n(`integrations.cursor.ladderFromStatic`)}),(0,Y.jsxs)(`table`,{className:`cursor-model-table`,children:[(0,Y.jsx)(`thead`,{children:(0,Y.jsxs)(`tr`,{children:[(0,Y.jsx)(`th`,{children:n(`integrations.cursor.colModel`)}),(0,Y.jsx)(`th`,{children:n(`integrations.cursor.colReasoning`)}),(0,Y.jsx)(`th`,{children:n(`integrations.cursor.colContext`)})]})}),(0,Y.jsx)(`tbody`,{children:c.models.map(e=>(0,Y.jsxs)(`tr`,{children:[(0,Y.jsx)(`td`,{children:(0,Y.jsx)(`code`,{children:e.id})}),(0,Y.jsx)(`td`,{children:e.reasoning?e.reasoning.join(` · `):(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`span`,{className:`cursor-no-control`,title:n(`integrations.cursor.noControlTitle`),"aria-label":n(`integrations.cursor.noControlTitle`),children:n(`integrations.cursor.noControl`)}),e.effortRows.length>0?(0,Y.jsx)(`span`,{className:`cursor-effort-rows`,children:n(e.effortRows.length===1?`integrations.cursor.effortRowsOne`:`integrations.cursor.effortRowsMany`,{n:e.effortRows.length})}):(0,Y.jsx)(`span`,{className:`cursor-effort-rows muted`,children:n(`integrations.cursor.effortRowsOff`)})]})}),(0,Y.jsx)(`td`,{children:e.context?`${Wn(e.context.defaultWindow,r)} · ${Wn(e.context.longWindow,r)}`:n(`integrations.cursor.singleWindow`)})]},e.id))})]}),c.models.some(e=>e.tableLess)&&(0,Y.jsx)(`p`,{className:`muted`,"data-cursor-tableless-hint":!0,children:n(`integrations.cursor.tableLessHint`)})]}),(0,Y.jsx)(`p`,{children:(0,Y.jsx)(`a`,{href:c.guideUrl,target:`_blank`,rel:`noreferrer`,children:n(`integrations.cursor.guide`)})})]})]})}var SC={"not-installed":`integrations.state.notInstalled`,unknown:`integrations.state.unknown`,absent:`integrations.state.absent`,current:`integrations.state.current`,stale:`integrations.state.stale`,conflict:`integrations.state.conflict`,unsafe:`integrations.state.unsafe`},CC={"not-installed":`badge badge-muted`,unknown:`badge badge-muted`,absent:`badge badge-muted`,current:`badge badge-green`,stale:`badge badge-amber`,conflict:`badge integration-badge--danger`,unsafe:`badge integration-badge--danger-outline`};function wC({state:e,installed:t,id:n}){let r=Q(),i=e===`unknown`||e===`not-installed`||t?e:`not-installed`;return(0,Y.jsx)(`span`,{id:n,className:CC[i],"data-integration-state":i,children:r(SC[i])})}function TC({copyKey:e,vars:t}){let n=Q()(e,t),r=t?.path;if(!r||!n.includes(r))return(0,Y.jsx)(`p`,{children:n});let[i,...a]=n.split(r);return(0,Y.jsxs)(`p`,{children:[i,(0,Y.jsx)(`code`,{children:r}),a.join(r)]})}function EC({copy:e,onConfirm:t,onClose:n}){let r=Q(),i=(0,_.useRef)(null),[a,o]=(0,_.useState)(!1),[s,c]=(0,_.useState)(null),l=`integration-consequence-dialog-title`;(0,_.useEffect)(()=>{let e=i.current;return e&&!e.open&&e.showModal(),()=>{e?.open&&e.close()}},[]);let u=(0,_.useCallback)(e=>{e.preventDefault(),a||n()},[n,a]),d=(0,_.useCallback)(async()=>{if(!a){o(!0),c(null);try{await t()}catch(e){c(e instanceof Error?e.message:r(`integrations.error.generic`)),o(!1)}}},[t,a,r]),f=[(0,Y.jsx)(TC,{copyKey:e.changesKey,vars:e.vars},`changes`),(0,Y.jsx)(TC,{copyKey:e.breakageKey,vars:e.vars},`breakage`),(0,Y.jsx)(TC,{copyKey:e.undoKey,vars:e.vars},`undo`)];return e.sideEffectKey&&f.push((0,Y.jsx)(TC,{copyKey:e.sideEffectKey,vars:e.vars},`side-effect`)),(0,Y.jsxs)(`dialog`,{ref:i,className:`modal-overlay`,"aria-labelledby":l,onCancel:u,children:[(0,Y.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":r(`common.close`),tabIndex:-1,onClick:()=>{a||n()}}),(0,Y.jsxs)(`div`,{className:`modal-card integration-consequence-dialog`,role:`document`,children:[(0,Y.jsxs)(`div`,{className:`modal-head`,children:[(0,Y.jsx)(`h3`,{id:l,children:r(e.titleKey,e.vars)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:n,disabled:a,children:r(`common.close`)})]}),(0,Y.jsx)(`div`,{className:`integration-consequence-body`,children:f}),s&&(0,Y.jsx)($,{tone:`err`,children:s}),(0,Y.jsx)(`div`,{className:`modal-actions`,children:(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>void d(),disabled:a,children:r(e.confirmKey)})})]})]})}function DC({apiBase:e,row:t,onClose:n,onRestored:r,profileId:i,onReconcile:a}){let o=Q(),s=(0,_.useRef)(null),c=(0,_.useRef)(null),l=(0,_.useRef)(null),u=(0,_.useRef)(!1),[d,f]=(0,_.useState)(!1),[p,m]=(0,_.useState)(!1),[h,g]=(0,_.useState)(null);(0,_.useEffect)(()=>{let e=s.current,t=document.activeElement;return c.current=t?.tagName===`BUTTON`?t:null,l.current=t?.closest?.(`section, [role='region'], main`)??null,e&&!e.open&&e.showModal(),()=>{e?.open&&e.close();let t=l.current;if(u.current&&t?.isConnected){t.hasAttribute(`tabindex`)||t.setAttribute(`tabindex`,`-1`),t.focus?.();return}let n=c.current;if(n?.isConnected){n.focus?.();return}t?.isConnected&&(t.hasAttribute(`tabindex`)||t.setAttribute(`tabindex`,`-1`),t.focus?.())}},[]);let v=(0,_.useCallback)(e=>{e.preventDefault(),p||n()},[n,p]),y=async()=>{if(!p){m(!0),g(null);try{await Tf(e,t.opId,d,void 0,t.clientId===`aside`?i??t.profileId:void 0),u.current=!0,r(),n()}catch(e){if(t.clientId===`aside`&&a?.(),Gf(e)?.reason===`drift_requires_confirm`){f(!0),m(!1);return}g(Xf(o,e)),m(!1)}}};return(0,Y.jsxs)(`dialog`,{ref:s,className:`modal-overlay`,"aria-labelledby":`integration-restore-title`,onCancel:v,children:[(0,Y.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":o(`common.close`),tabIndex:-1,onClick:()=>{p||n()}}),(0,Y.jsxs)(`div`,{className:`modal-card integration-restore-dialog`,role:`document`,children:[(0,Y.jsx)(`div`,{className:`modal-head`,children:(0,Y.jsx)(`h3`,{id:`integration-restore-title`,children:o(d?`integrations.restore.driftTitle`:`integrations.restore.title`)})}),(0,Y.jsx)(`div`,{className:`modal-desc`,children:o(d?`integrations.restore.driftBody`:`integrations.restore.body`)}),(0,Y.jsx)(`p`,{className:`integration-path`,children:t.configPath}),h&&(0,Y.jsx)($,{tone:`err`,children:h}),(0,Y.jsxs)(`div`,{className:`modal-actions`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:n,disabled:p,children:o(`common.cancel`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>void y(),disabled:p,children:o(p?`integrations.restore.pending`:d?`integrations.restore.confirmDrift`:`integrations.restore.confirm`)})]})]})]})}var OC={opencode:`integrations.tab.opencode`,pi:`integrations.tab.pi`,omp:`integrations.tab.omp`,hermes:`integrations.tab.hermes`,openclaw:`integrations.tab.openclaw`,kimi:`integrations.tab.kimi`,gajae:`integrations.tab.gajae`,dsh:`integrations.tab.dsh`,mcode:`integrations.tab.mcode`,zcode:`integrations.tab.zcode`,prime:`integrations.tab.prime`,aside:`integrations.tab.aside`,raycast:`integrations.tab.raycast`,omo:`integrations.tab.omo`,cline:`integrations.tab.cline`},kC={apply:`integrations.kind.apply`,disable:`integrations.kind.disable`,refresh:`integrations.kind.refresh`,restore:`integrations.kind.restore`,overwrite:`integrations.kind.overwrite`};function AC(e){return e===`current`||e===`stale`}function jC(e,t,n){let r={id:`codex`,hash:`integrations/codex`,labelKey:`integrations.tab.codex`,toggle:`codex`,toggleBlocked:t?.disableBlocked??null,togglePath:t?.configPath??null,status:null,detail:null,detailVars:null};if(n===void 0)return e?e.routingInjected===!0?{...r,state:e.status===`error`?`stale`:`current`,installed:!0,applied:!0,detailKey:`integrations.detail.codexRouted`}:{...r,state:`absent`,installed:!0,applied:!1,detail:e.recommendedCommand??null,detailKey:e.recommendedCommand?null:`integrations.detail.codexAbsent`}:{...r,state:`unknown`,installed:!1,applied:!1,detailKey:null};if(!n)return{...r,state:`unknown`,installed:!1,applied:!1,detailKey:null};if(!t)return{...r,toggle:null,state:`unknown`,installed:!1,applied:!1,detailKey:null};let i=t.desiredEnabled;return e?e.routingInjected===!0?{...r,state:e.status===`error`?`stale`:`current`,installed:t.installed,applied:!0,toggleOn:i,detailKey:`integrations.detail.codexRouted`}:{...r,state:`absent`,installed:t.installed,applied:!1,toggleOn:i,detail:e.recommendedCommand??null,detailKey:e.recommendedCommand?null:`integrations.detail.codexAbsent`}:{...r,state:`unknown`,installed:t.installed,applied:!1,toggleOn:i,detailKey:null}}function MC(e,t){let n={hash:`integrations/keys`,labelKey:`integrations.tab.keys`};return e===`checking`?{...n,state:`checking`,detailKey:`integrations.detail.keyChecking`,detailVars:null}:e===`unavailable`||t===null?{...n,state:`unavailable`,detailKey:`integrations.detail.keyUnavailable`,detailVars:null}:{...n,state:t>0?`issued`:`none-issued`,detailKey:t>0?`integrations.detail.keyCount`:`integrations.detail.keyNone`,detailVars:t>0?{count:String(t)}:null}}function NC(e){return e?e.enabled===!0?e.authMode===`subscription`?`claude.authModeSubscription`:e.authMode===`proxy`?`claude.authModeProxy`:e.authMode===`auto`?`claude.authModeAuto`:null:`integrations.detail.claudeOff`:null}function PC(e,t,n){let r={id:`claude`,hash:`integrations/claude`,labelKey:`integrations.tab.claude`,toggle:`claude`,toggleBlocked:t?.disableBlocked??null,togglePath:t?.configPath??null,status:null,detail:null,detailVars:null},i=NC(e);if(n===void 0){if(!e)return{...r,state:`unknown`,installed:!1,applied:!1,detailKey:i};let t=e.enabled===!0;return{...r,state:t?`current`:`absent`,installed:!0,applied:t,detailKey:i}}return n?t?{...r,state:t.state,installed:t.installed,applied:t.state===`current`,detailKey:i}:{...r,toggle:null,state:`unknown`,installed:!1,applied:!1,detailKey:i}:{...r,state:`unknown`,installed:!1,applied:!1,detailKey:i}}function FC(e,t,n){let r={id:`claudeDesktop`,hash:`integrations/claude/desktop`,labelKey:`claudeDesktop.title`,toggle:`claude-desktop`,toggleBlocked:t?.disableBlocked??null,togglePath:t?.configPath??null,status:null,detail:null,detailVars:null};if(!e||!n||!t||typeof e.desiredEnabled!=`boolean`)return{...r,toggle:null,state:`unknown`,installed:!1,applied:!1,detailKey:null};let i=e.desiredEnabled;if(!i)return e.applied===!0||e.driftReason===`desired_off_gateway_selected`?{...r,state:`stale`,installed:e.installed===!0,applied:!0,toggleOn:!1,detailKey:`integrations.detail.desktopDesiredOffCleanupPending`}:{...r,state:`absent`,installed:e.installed===!0,applied:!1,toggleOn:!1,detailKey:`integrations.detail.desktopDesiredOff`};if(e.applied!==!0)return{...r,state:`absent`,installed:e.installed===!0,applied:!1,toggleOn:i,detailKey:`integrations.detail.desktopDesiredOnNotApplied`};let a=e.stale===!0||e.activeProfile===!1;return{...r,state:a?`stale`:`current`,installed:!0,applied:!0,toggleOn:i,detailKey:e.activeProfile===!1?`integrations.detail.desktopNotServed`:a?`integrations.detail.desktopStale`:`integrations.detail.desktopCurrent`}}function IC(e){if(!e)return{detailKey:null,detailVars:null};let t=e.present===!0;return{detailKey:t?`integrations.detail.grokModels`:`integrations.detail.grokAbsent`,detailVars:t?{count:String(e.models?.length??0)}:null}}function LC(e,t,n){let r={id:`grok`,hash:`integrations/grok`,labelKey:`integrations.tab.grok`,toggle:`grok`,toggleBlocked:t?.disableBlocked??null,togglePath:t?.configPath??null,status:null,detail:null},i=IC(e);if(n===void 0){if(!e)return{...r,state:`unknown`,installed:!1,applied:!1,...i};let t=e.present===!0;return{...r,state:t?`current`:`absent`,installed:t,applied:t,...i}}return n?t?{...r,state:t.state,installed:t.installed,applied:t.state===`current`,...i}:{...r,toggle:null,state:`unknown`,installed:!1,applied:!1,...i}:{...r,state:`unknown`,installed:!1,applied:!1,...i}}function RC(e,t=Date.now()){let n={id:`cursor`,hash:`integrations/cursor`,labelKey:`integrations.tab.cursor`,toggle:null,toggleBlocked:null,togglePath:null,status:null,detail:null,detailVars:null};if(!e)return{...n,state:`unknown`,installed:!1,applied:!1,detailKey:null};if(!e.privateInference.installed)return{...n,state:`not-installed`,installed:!1,applied:!1,detailKey:`integrations.detail.cursorAbsent`};let r=e.lastSeen!==null&&t-e.lastSeen.at<864e5;return{...n,state:r?`current`:`absent`,installed:!0,applied:r,detailKey:r?`integrations.detail.cursorSeen`:`integrations.detail.cursorNeverSeen`}}function zC(e){return{id:e.clientId,hash:`integrations/${e.clientId}`,labelKey:OC[e.clientId],state:e.installed?e.state:`not-installed`,installed:e.installed,applied:e.installed&&AC(e.state),detail:e.configPath,detailKey:null,detailVars:null,toggle:e.clientId,toggleBlocked:null,togglePath:e.configPath,status:e}}function BC(e){let t=e.native?.find(e=>e.clientId===`codex`),n=e.native?.find(e=>e.clientId===`claude`),r=e.native?.find(e=>e.clientId===`grok`),i=new Map(e.clients.map(e=>[e.clientId,e])),a=[jC(e.codex,t,e.nativeSettled),PC(e.claude,n,e.nativeSettled),FC(e.claudeDesktop,e.native?.find(e=>e.clientId===`claude-desktop`),e.nativeSettled),LC(e.grok,r,e.nativeSettled),RC(e.cursor)];for(let t of lf){let n=i.get(t);if(n){a.push(zC(n));continue}e.clientsSettled||a.push({id:t,hash:`integrations/${t}`,labelKey:OC[t],state:`unknown`,installed:!1,applied:!1,detail:null,detailKey:null,detailVars:null,toggle:null,toggleBlocked:null,togglePath:null,status:null})}return{keysRow:MC(e.keyPhase,e.keyCount),rows:a}}function VC(e){return{detected:e.filter(e=>e.installed).length,applied:e.filter(e=>e.applied).length,stale:e.filter(e=>e.state===`stale`).length,unknown:e.filter(e=>e.state===`unknown`).length}}var HC=6;function UC({row:e,showClient:t,onRestore:n,onDelete:r}){let i=Q();return(0,Y.jsxs)(`li`,{className:`integration-history-row`,children:[(0,Y.jsx)(`span`,{className:`integration-history-kind`,children:i(kC[e.kind])}),t&&(0,Y.jsx)(`span`,{className:`integration-history-client`,children:e.clientId}),(0,Y.jsx)(`span`,{className:`integration-history-at`,children:new Date(e.at).toLocaleString()}),e.snapshot===`expired`?(0,Y.jsx)(`span`,{className:`badge badge-muted`,children:i(`integrations.action.snapshotExpired`)}):(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>n(e),children:e.undoable?i(`integrations.action.undo`):i(`integrations.action.restorePoint`)}),e.deletable&&r&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>r(e),"aria-label":i(`integrations.rollback.deleteAria`,{at:new Date(e.at).toLocaleString()}),children:i(`integrations.rollback.delete`)})]})}function WC({rows:e,showClient:t,onRestore:n,onDelete:r}){let i=Q(),[a,o]=(0,_.useState)(HC),[s,...c]=e;if(!s)return null;let l=c.slice(0,a),u=c.length-l.length;return(0,Y.jsxs)(`div`,{className:`integration-history`,children:[(0,Y.jsx)(`ul`,{className:`integration-history-list`,children:(0,Y.jsx)(UC,{row:s,showClient:t,onRestore:n,onDelete:r})}),c.length>0&&(0,Y.jsxs)(`details`,{className:`integration-history-older`,children:[(0,Y.jsx)(`summary`,{children:i(`integrations.rollback.older`)}),(0,Y.jsx)(`ul`,{className:`integration-history-list`,children:l.map(e=>(0,Y.jsx)(UC,{row:e,showClient:t,onRestore:n,onDelete:r},e.opId))}),u>0&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm integration-history-more`,onClick:()=>o(e=>e+HC),children:i(`integrations.rollback.showMore`,{n:String(Math.min(u,HC))})})]})]})}var GC={titleKey:`integrations.dialog.grok.title`,changesKey:`integrations.dialog.grok.changes`,breakageKey:`integrations.dialog.grok.breakage`,undoKey:`integrations.dialog.grok.undo`,confirmKey:`integrations.dialog.grok.confirm`},KC={titleKey:`integrations.dialog.codex.title`,changesKey:`integrations.dialog.codex.changes`,breakageKey:`integrations.dialog.codex.breakage`,undoKey:`integrations.dialog.codex.undo`,sideEffectKey:`integrations.dialog.codex.sideEffect`,confirmKey:`integrations.dialog.codex.confirm`},qC={titleKey:`integrations.dialog.desktop.title`,changesKey:`integrations.dialog.desktop.changes`,breakageKey:`integrations.dialog.desktop.breakage`,undoKey:`integrations.dialog.desktop.undo`,sideEffectKey:`integrations.dialog.desktop.restart`,confirmKey:`integrations.dialog.desktop.confirm`};function JC(e){return e.state===`current`||e.state===`stale`}function YC({row:e,pending:t,result:n,onOpen:r,onToggle:i,onOverwrite:a}){let o=Q(),s=e.detail??(e.detailKey?o(e.detailKey,e.detailVars??void 0):null),c=e.toggleBlocked!==null&&(e.applied||e.toggleBlocked.reason===`orphaned_marker`),l=c&&e.toggleBlocked&&(e.toggle===`claude`||e.toggle===`grok`||e.toggle===`codex`)?Xf(o,new Rf(409,{error:`native integration change refused`,code:`native_integration_refused`,clientId:e.toggle,reason:e.toggleBlocked.reason,message:e.toggleBlocked.message}),void 0,e.togglePath??void 0):null,u=e.toggleOn??e.applied;return(0,Y.jsxs)(`li`,{className:`integration-card`,"data-client":e.id,children:[(0,Y.jsxs)(`div`,{className:`integration-card-head`,children:[(0,Y.jsx)(Ab,{src:kb(e.id),label:o(e.labelKey),size:20}),(0,Y.jsx)(`h4`,{children:(0,Y.jsx)(`button`,{type:`button`,className:`integration-card-link`,onClick:r,children:o(e.labelKey)})}),(0,Y.jsx)(wC,{state:e.state,installed:e.installed})]}),s&&(0,Y.jsx)(`p`,{className:e.detail?`integration-path`:`integration-meta`,children:s}),n?.tone===`err`&&(0,Y.jsx)($,{tone:`err`,children:n.text}),n?.tone===`ok`&&(0,Y.jsx)($,{tone:`ok`,children:n.text}),(0,Y.jsxs)(`div`,{className:`integration-card-actions`,children:[e.toggle&&i&&(0,Y.jsxs)(`div`,{className:`integration-toggle-control`,children:[(0,Y.jsx)(Dt,{on:u,onClick:i,disabled:e.state===`unknown`||!e.installed||e.state===`conflict`||e.state===`unsafe`||c||t,label:o(u?`integrations.action.disable`:`integrations.action.apply`)}),l&&(0,Y.jsx)(`p`,{className:`integration-toggle-blocked`,children:l})]}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:r,tabIndex:-1,children:o(`integrations.action.settings`)}),a&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-danger`,onClick:a,disabled:t,children:o(`integrations.action.overwrite`)})]})]})}function XC({apiBase:e,active:t=!0}){let n=Q(),[r,i]=(0,_.useState)(!1),[a,o]=(0,_.useState)(null),[s,c]=(0,_.useState)(null),[l,u]=(0,_.useState)(null),[d,f]=(0,_.useState)({}),[p,m]=(0,_.useState)(null),[h,g]=(0,_.useState)(null),v=(0,_.useRef)(null);(0,_.useEffect)(()=>{if(p!==null)return;let e=v.current;e&&(v.current=null,e.isConnected&&e.focus())},[p]);let y=(0,_.useCallback)(async t=>(await xf(e,t)).clients,[e]),b=(0,_.useCallback)(async t=>(await Cf(e,void 0,t)).operations,[e]),x=(0,_.useCallback)(t=>Of(e,t),[e]),S=(0,_.useCallback)(t=>kf(e,t),[e]),C=(0,_.useCallback)(t=>Af(e,t),[e]),w=(0,_.useCallback)(t=>jf(e,t),[e]),T=(0,_.useCallback)(t=>Mf(e,t),[e]),E=(0,_.useCallback)(t=>vC(e,t),[e]),D=(0,_.useCallback)(async t=>(await Hf(e,t))?.clients??null,[e]),O=jr(`integration-states:${e}`,[e],y,{isEmpty:e=>e.length===0,enabled:t,sessionCacheKey:`ocx.integrations.states.v1:${e}`}),k=jr(`integration-journal-all:${e}`,[e],b,{isEmpty:e=>e.length===0,enabled:t,sessionCacheKey:`ocx.integrations.journal.v1:${e}`}),A=jr(`integration-codex:${e}`,[e],x,{isEmpty:e=>e===null,enabled:t,sessionCacheKey:`ocx.integrations.codex.v1:${e}`}),j=jr(`integration-keys:${e}`,[e],S,{isEmpty:()=>!1,enabled:t,sessionCacheKey:`ocx.integrations.keys.v1:${e}`}),M=jr(`integration-claude:${e}`,[e],C,{isEmpty:e=>e===null,enabled:t,sessionCacheKey:`ocx.integrations.claude.v1:${e}`}),N=jr(`integration-claude-desktop:${e}`,[e],w,{isEmpty:e=>e===null,enabled:t,sessionCacheKey:`ocx.integrations.claude-desktop.v1:${e}`}),P=jr(`integration-grok:${e}`,[e],T,{isEmpty:e=>e===null,enabled:t,sessionCacheKey:`ocx.integrations.grok.v1:${e}`}),F=jr(`integration-cursor:${e}`,[e],E,{isEmpty:e=>e===null,enabled:t,sessionCacheKey:`ocx.integrations.cursor.v1:${e}`}),I=jr(`integration-native:${e}`,[e],D,{isEmpty:e=>e===null,enabled:t,sessionCacheKey:`ocx.integrations.native.v1:${e}`}),L=O.state.data??[],R=k.state.data??[],z=L.filter(JC),B=L.filter(e=>e.installed),V=O.state.kind!==`cold`&&O.state.kind!==`retrying-cold`,H=I.state.data??null,U=H!==null,W=j.state.kind===`cold`||j.state.kind===`retrying-cold`?`checking`:j.state.kind===`failed-cold`||j.state.kind===`failed-with-stale`?`unavailable`:`settled`,{keysRow:G,rows:K}=BC({clients:L,clientsSettled:V,codex:A.state.data??null,keyCount:j.state.data??null,keyPhase:W,claude:M.state.data??null,claudeDesktop:N.state.data??null,grok:P.state.data??null,cursor:F.state.data??null,native:H,nativeSettled:U}),q=VC(K),J=()=>{O.refresh(),k.refresh(),A.refresh(),j.refresh(),M.refresh(),N.refresh(),P.refresh(),I.refresh()},X=async()=>{if(r||z.length===0)return;let t=[n(`integrations.bulk.title`),n(`integrations.bulk.body`)].join(`
|
|
127
127
|
|
|
128
|
-
`);if(!confirm(t))return;i(!0),o(null);let a=[];for(let t of z)try{await wf(e,t.clientId,!1)}catch(e){a.push(`${t.clientId}: ${Xf(n,e)}`)}let s=!1;try{s=(await xf(e)).clients.some(JC)}catch{a.push(n(`integrations.error.stale`))}s&&a.length===0&&a.push(n(`integrations.error.stale`)),J(),i(!1),o(a.length===0?{tone:`ok`,text:n(`integrations.bulk.success`)}:{tone:`err`,text:n(`integrations.bulk.partial`,{clients:a.join(`; `)})})},ee=R[0]?.at,[te,ne]=(0,_.useState)(null),Z=()=>{I.refresh(),A.refresh(),M.refresh(),P.refresh()},re=(e,t)=>{f(n=>{let r={...n};return t?r[e]=t:delete r[e],r})},ie=async(t,r)=>{if(!te&&t.toggle){ne(t.id),re(t.id,null);try{if(t.status)await wf(e,t.status.clientId,r),J();else if(t.toggle===`claude`||t.toggle===`grok`||t.toggle===`codex`||t.toggle===`claude-desktop`){let i=await Uf(e,t.toggle,r);i.reason===`non_loopback_removed`?re(t.id,{tone:`ok`,text:n(i.changed?`integrations.native.msg.nonLoopbackRemoved`:`integrations.native.msg.nonLoopbackRemovedNoop`)}):i.reason===`non_loopback_superseded`&&re(t.id,{tone:`ok`,text:n(`integrations.native.msg.nonLoopbackSuperseded`)}),Z()}}catch(e){re(t.id,{tone:`err`,text:Xf(n,e,void 0,t.togglePath??void 0)}),(t.toggle===`claude`||t.toggle===`grok`||t.toggle===`codex`||t.toggle===`claude-desktop`)&&Z()}finally{ne(null)}}},ae=(e,t)=>{if(e.status||t||e.id===`claude`||e.toggle===null){ie(e,t);return}let n=document.activeElement;v.current=n?.tagName===`BUTTON`?n:null,m(e)},oe=async t=>{if(t.status){ne(t.id),re(t.id,null);try{await wf(e,t.status.clientId,!0,void 0,!0),J()}catch(e){throw re(t.id,{tone:`err`,text:Xf(n,e,void 0,t.togglePath??void 0)}),e}finally{ne(null)}}};return(0,Y.jsxs)(`section`,{className:`integrations-overview`,children:[(0,Y.jsxs)(`div`,{className:`integration-summary`,children:[(0,Y.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,Y.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.summary.detected`)}),(0,Y.jsx)(`strong`,{children:q.detected})]}),(0,Y.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,Y.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.summary.applied`)}),(0,Y.jsx)(`strong`,{children:q.applied})]}),(0,Y.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,Y.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.summary.stale`)}),(0,Y.jsx)(`strong`,{children:q.stale})]}),q.unknown>0&&(0,Y.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,Y.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.state.unknown`)}),(0,Y.jsx)(`strong`,{children:q.unknown})]}),(0,Y.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,Y.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.summary.lastChange`)}),(0,Y.jsx)(`strong`,{children:ee?new Date(ee).toLocaleString():n(`integrations.status.unknown`)})]}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>void X(),disabled:r||z.length===0,children:n(`integrations.summary.disableAll`)})]}),(0,Y.jsx)(`h3`,{children:n(`integrations.catalog.title`)}),(0,Y.jsx)(ZC,{row:G}),(0,Y.jsx)(`p`,{className:`page-sub`,children:n(`integrations.onboarding`)}),O.state.kind===`failed-cold`&&(0,Y.jsx)($,{tone:`err`,children:n(`integrations.error.load`)}),O.state.kind===`failed-with-stale`&&(0,Y.jsx)($,{tone:`err`,children:n(`integrations.error.stale`)}),a&&(0,Y.jsx)($,{tone:a.tone,children:a.text}),K.length===0?O.state.kind===`failed-cold`?null:(0,Y.jsx)(`p`,{className:`page-sub`,children:n(`common.loading`)}):(0,Y.jsx)(`ul`,{className:`integration-cards`,children:K.map(e=>(0,Y.jsx)(YC,{row:e,pending:te!==null,result:d[e.id]??null,onOpen:()=>ht(e.hash),onToggle:e.toggle?()=>ae(e,!(e.toggleOn??e.applied)):null,onOverwrite:e.status!==null&&e.status.state===`conflict`&&e.installed?()=>g(e):null},e.id))}),V&&B.length===0&&(0,Y.jsxs)(`div`,{className:`integration-empty`,children:[(0,Y.jsx)(`h4`,{children:n(`integrations.empty.title`)}),(0,Y.jsx)(`p`,{children:n(`integrations.empty.body`)})]}),(0,Y.jsx)(`h3`,{children:n(`integrations.rollback.title`)}),k.state.showSkeleton?(0,Y.jsx)(ep,{label:n(`integrations.rollback.title`),rows:2}):k.state.kind===`failed-cold`?(0,Y.jsxs)($,{tone:`err`,children:[n(`integrations.rollback.failed`),` `,(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void k.refresh(),children:n(`common.retry`)})]}):R.length===0?(0,Y.jsxs)(`div`,{className:`integration-empty`,children:[(0,Y.jsx)(`p`,{children:n(`integrations.rollback.empty`)}),(0,Y.jsx)(`p`,{className:`page-sub`,children:n(`integrations.rollback.emptyBody`)})]}):(0,Y.jsx)(WC,{rows:R,showClient:!0,onRestore:c,onDelete:u}),s&&(0,Y.jsx)(DC,{apiBase:e,row:s,onClose:()=>c(null),onRestored:J,onReconcile:J}),l&&(0,Y.jsx)(EC,{copy:{titleKey:`integrations.dialog.deleteEntry.title`,changesKey:`integrations.dialog.deleteEntry.changes`,breakageKey:`integrations.dialog.deleteEntry.breakage`,undoKey:`integrations.dialog.deleteEntry.undo`,confirmKey:`integrations.dialog.deleteEntry.confirm`,vars:{path:l.configPath}},onClose:()=>u(null),onConfirm:async()=>{try{await Ef(e,l.opId,void 0,l.clientId===`aside`?l.profileId:void 0)}catch(e){if(gf(e)){u(null),await k.refresh();return}throw Error(Xf(n,e),{cause:e})}u(null),await k.refresh()}}),p&&(0,Y.jsx)(EC,{copy:{...p.toggle===`claude-desktop`?qC:p.id===`codex`?KC:GC,vars:{path:p.togglePath??``}},onClose:()=>m(null),onConfirm:async()=>{await ie(p,!1),m(null)}}),h&&h.status&&(0,Y.jsx)(EC,{copy:{titleKey:`integrations.dialog.overwrite.title`,changesKey:h.status.reason===`foreign-edit`?`integrations.dialog.overwrite.changesForeign`:`integrations.dialog.overwrite.changesUnowned`,breakageKey:`integrations.dialog.overwrite.breakage`,undoKey:`integrations.dialog.overwrite.undo`,confirmKey:`integrations.dialog.overwrite.confirm`,vars:{path:h.status.configPath}},onClose:()=>g(null),onConfirm:async()=>{await oe(h),g(null)}})]})}function ZC({row:e}){let t=Q(),n=e.detailKey?t(e.detailKey,e.detailVars??void 0):null;return(0,Y.jsxs)(`div`,{className:`integration-api-keys-row`,"data-client":`keys`,"data-key-state":e.state,children:[(0,Y.jsxs)(`div`,{className:`integration-api-keys-copy`,children:[(0,Y.jsx)(`h4`,{children:t(e.labelKey)}),n&&(0,Y.jsx)(`p`,{className:`integration-meta`,children:n})]}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>ht(e.hash),children:t(`integrations.action.manageKeys`)})]})}function QC({install:e}){let t=Q();return(0,Y.jsxs)(Y.Fragment,{children:[e.plan===`free`&&(0,Y.jsx)($,{tone:`warn`,children:t(`integrations.raycast.proRequired`)}),e.plan===`unknown`&&(0,Y.jsx)(`p`,{className:`page-sub`,"data-raycast-plan":`unknown`,children:t(`integrations.raycast.planUnknown`)}),!e.aiDirPresent&&(0,Y.jsx)(`p`,{className:`page-sub`,"data-raycast-ai-dir":`absent`,children:t(`integrations.raycast.revealConfig`)})]})}function $C(e,t){return{titleKey:`integrations.dialog.overwrite.title`,changesKey:e===`foreign-edit`?`integrations.dialog.overwrite.changesForeign`:`integrations.dialog.overwrite.changesUnowned`,breakageKey:`integrations.dialog.overwrite.breakage`,undoKey:`integrations.dialog.overwrite.undo`,confirmKey:`integrations.dialog.overwrite.confirm`,vars:{path:t}}}var ew={opencode:`integrations.semantics.opencode`,pi:`integrations.semantics.pi`,omp:`integrations.semantics.omp`,hermes:`integrations.semantics.hermes`,openclaw:`integrations.semantics.openclaw`,kimi:`integrations.semantics.kimi`,gajae:`integrations.semantics.gajae`,dsh:`integrations.semantics.dsh`,mcode:`integrations.semantics.mcode`,zcode:`integrations.semantics.zcode`,prime:`integrations.semantics.prime`,aside:`integrations.semantics.aside`,raycast:`integrations.semantics.raycast`,omo:`integrations.semantics.omo`,cline:`integrations.semantics.cline`},tw={opencode:`integrations.tab.opencode`,pi:`integrations.tab.pi`,omp:`integrations.tab.omp`,hermes:`integrations.tab.hermes`,openclaw:`integrations.tab.openclaw`,kimi:`integrations.tab.kimi`,gajae:`integrations.tab.gajae`,dsh:`integrations.tab.dsh`,mcode:`integrations.tab.mcode`,zcode:`integrations.tab.zcode`,prime:`integrations.tab.prime`,aside:`integrations.tab.aside`,raycast:`integrations.tab.raycast`,omo:`integrations.tab.omo`,cline:`integrations.tab.cline`};function nw({apiBase:e,client:t,active:n=!0,profileId:r,profileLabel:i}){let a=Q(),o=r===void 0?t:`${t}:${r}`,[s,c]=(0,_.useState)(!1),[l,u]=(0,_.useState)(null),[d,f]=(0,_.useState)(null),[p,m]=(0,_.useState)(null),[h,g]=(0,_.useState)(!1),v=(0,_.useCallback)(n=>Sf(e,t,n,r),[e,t,r]),y=(0,_.useCallback)(async n=>(await Cf(e,t,n,r)).operations,[e,t,r]),b=jr(`integration-state:${e}:${o}`,[e,t,r],v,{isEmpty:()=>!1,enabled:n,sessionCacheKey:`ocx.integrations.state.v1:${e}:${o}`}),x=jr(`integration-journal:${e}:${o}`,[e,t,r],y,{isEmpty:e=>e.length===0,enabled:n,sessionCacheKey:`ocx.integrations.client-journal.v1:${e}:${o}`}),S=b.state.data??null,C=S&&(r===void 0||S.profileId===r&&typeof S.enabled==`boolean`)?S:null,w=x.state.data??[],T=()=>{b.refresh(),x.refresh()},E=async n=>{if(!(!C||s)){c(!0),u(null);try{await wf(e,t,n,void 0,void 0,r)}catch(e){u(Xf(a,e))}finally{T(),c(!1)}}},D=async()=>{if(C){u(null);try{await wf(e,t,!0,void 0,!0,r),T()}catch(e){throw u(Xf(a,e)),T(),e}}},O=()=>void E(!(C&&(r===void 0?C.state===`current`||C.state===`stale`:C.enabled)));if(!C)return(0,Y.jsx)(`section`,{className:`integration-client-page`,children:b.state.showError?(0,Y.jsx)($,{tone:`err`,children:a(`integrations.error.load`)}):(0,Y.jsx)(`p`,{className:`page-sub`,children:a(`common.loading`)})});let k=C.state===`current`||C.state===`stale`,A=r===void 0?k:C.enabled===!0,j=r!==void 0&&(b.state.showError||b.state.refreshing),M=(!C.installed||C.state===`conflict`||C.state===`unsafe`)&&!(r!==void 0&&A);return(0,Y.jsxs)(`section`,{className:`integration-client-page`,children:[(0,Y.jsxs)(`div`,{className:`integration-client-head`,children:[(0,Y.jsx)(Ab,{src:kb(t),label:a(tw[t]),size:24}),(0,Y.jsx)(`h3`,{children:i??a(tw[t])}),(0,Y.jsx)(wC,{state:C.state,installed:C.installed,id:`integration-state-${t}${r===void 0?``:`-${r}`}`}),(0,Y.jsx)(Dt,{on:A,onClick:O,disabled:M||s||j,label:a(A?`integrations.action.disable`:`integrations.action.apply`)})]}),r!==void 0&&b.state.showError&&(0,Y.jsxs)($,{tone:`err`,children:[a(`integrations.aside.loadError`),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:T,disabled:s||b.state.refreshing,children:a(`common.retry`)})]}),C.state===`stale`&&A&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>void E(!0),disabled:s,children:a(`integrations.action.refresh`)}),C.installed&&C.state===`conflict`&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-danger`,onClick:()=>g(!0),disabled:s,children:a(`integrations.action.overwrite`)}),(0,Y.jsx)(`p`,{className:`page-sub`,children:a(ew[t])}),(0,Y.jsx)(`p`,{className:`integration-path`,children:C.configPath}),C.raycast&&(0,Y.jsx)(QC,{install:C.raycast}),C.appliedAt&&(0,Y.jsxs)(`p`,{className:`integration-meta`,children:[a(`integrations.status.appliedAt`),`: `,new Date(C.appliedAt).toLocaleString()]}),C.retentionDegraded&&(0,Y.jsx)($,{tone:`err`,children:a(`integrations.retention.degraded`)}),l&&(0,Y.jsx)($,{tone:`err`,children:l}),(0,Y.jsx)(`h4`,{children:a(`integrations.rollback.title`)}),x.state.showSkeleton?(0,Y.jsx)(ep,{label:a(`integrations.rollback.title`),rows:2}):x.state.kind===`failed-cold`?(0,Y.jsxs)($,{tone:`err`,children:[a(`integrations.rollback.failed`),` `,(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void x.refresh(),children:a(`common.retry`)})]}):w.length===0?(0,Y.jsx)(`p`,{className:`page-sub`,children:a(`integrations.rollback.empty`)}):(0,Y.jsx)(WC,{rows:w,onRestore:f,onDelete:m}),d&&(0,Y.jsx)(DC,{apiBase:e,row:d,profileId:r,onClose:()=>f(null),onRestored:T,onReconcile:T}),p&&(0,Y.jsx)(EC,{copy:{titleKey:`integrations.dialog.deleteEntry.title`,changesKey:`integrations.dialog.deleteEntry.changes`,breakageKey:`integrations.dialog.deleteEntry.breakage`,undoKey:`integrations.dialog.deleteEntry.undo`,confirmKey:`integrations.dialog.deleteEntry.confirm`,vars:{path:p.configPath}},onClose:()=>m(null),onConfirm:async()=>{try{await Ef(e,p.opId,void 0,r)}catch(e){if(gf(e)){m(null),await x.refresh();return}throw Error(Xf(a,e),{cause:e})}m(null),await x.refresh()}}),h&&(0,Y.jsx)(EC,{copy:$C(C.reason,C.configPath),onClose:()=>g(!1),onConfirm:async()=>{await D(),g(!1)}})]})}function rw(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function iw(){throw new hf(502,{code:`invalid_aside_profile_response`})}async function aw(e,t){let n=await vf(await fetch(`${e}/api/client-integrations/aside/profiles`,{signal:t}));(!rw(n)||!Array.isArray(n.profiles)||typeof n.allEnabled!=`boolean`)&&iw();let r=n.profiles.map(e=>sf(e)??iw());new Set(r.map(e=>e.profileId)).size!==r.length&&iw();let i=r.filter(e=>e.enabled).length,a=r.filter(e=>e.state===`current`||e.state===`stale`).length;return(n.total!==r.length||n.enabledCount!==i||n.appliedCount!==a||n.allEnabled!==(r.length>0&&i===r.length))&&iw(),{profiles:r,allEnabled:n.allEnabled,enabledCount:i,appliedCount:a,total:r.length,...typeof n.error==`string`?{error:n.error}:{}}}async function ow(e,t){let n=await vf(await fetch(`${e}/api/client-integrations/aside/sync`,{method:`POST`,headers:{"Content-Type":`application/json`},body:`{}`,signal:t}));(!rw(n)||typeof n.ok!=`boolean`||!Array.isArray(n.results))&&iw(),n.results.some(e=>!rw(e)||e.client!==`aside`)&&iw();let r=cf(n.results)??iw();return n.ok!==r.every(e=>e.ok)&&iw(),{ok:n.ok,results:r}}function sw({apiBase:e,active:t=!0}){let n=Q(),[r,i]=(0,_.useState)(null),[a,o]=(0,_.useState)(null),s=(0,_.useRef)(!1),[c,l]=(0,_.useState)(null),[u,d]=(0,_.useState)(new Map),f=(0,_.useCallback)(t=>aw(e,t),[e]),p=jr(`aside-profiles:${e}`,[e],f,{enabled:t,isEmpty:e=>!e.error&&e.profiles.length===0,sessionCacheKey:`ocx.integrations.aside-profiles.v1:${e}`}),m=p.state.data,h=m?.profiles??[],g=p.state.showError||!!m?.error,v=a!==null||p.state.refreshing,y=e=>e.name||n(`integrations.aside.profile`,{id:e.profileId}),b=e=>d(t=>{let r=new Map(t);for(let t of e)t.ok?r.delete(t.profileId):r.set(t.profileId,Zf(n,t));return r}),x=(e,t)=>{e instanceof hf&&`results`in e.body&&e.body.results?.length?(b(e.body.results),l(n(`integrations.aside.partial`))):t===void 0?l(Xf(n,e)):d(r=>new Map(r).set(t,Xf(n,e)))},S=async(t,n)=>{if(!s.current){s.current=!0,o(n??`all`),l(null);try{let r=await wf(e,`aside`,t,void 0,void 0,n);b(r.results??(n===void 0?h.map(e=>e.profileId):[n]).map(e=>({profileId:e,ok:!0})))}catch(e){x(e,n)}finally{p.refresh(),s.current=!1,o(null)}}},C=async()=>{if(!s.current){s.current=!0,o(`sync`),l(null);try{let t=await ow(e);b(t.results),t.ok||l(n(`integrations.aside.partial`))}catch(e){x(e)}finally{p.refresh(),s.current=!1,o(null)}}};return r?(0,Y.jsxs)(`section`,{className:`integration-client-page`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,autoFocus:!0,onClick:()=>{i(null),p.refresh()},children:n(`integrations.aside.back`)}),u.has(r.profileId)&&(0,Y.jsx)($,{tone:`err`,children:(0,Y.jsx)(`span`,{className:`aside-profile-failure`,children:u.get(r.profileId)})}),(0,Y.jsx)(nw,{apiBase:e,client:`aside`,active:t,profileId:r.profileId,profileLabel:y(r)},r.profileId)]}):(0,Y.jsxs)(`section`,{className:`integration-client-page`,"aria-busy":v,children:[(0,Y.jsxs)(`div`,{className:`integration-client-head`,children:[(0,Y.jsx)(Ab,{src:kb(`aside`),label:n(`integrations.tab.aside`),size:24}),(0,Y.jsx)(`h3`,{children:n(`integrations.aside.profilesTitle`)})]}),(0,Y.jsx)(`p`,{className:`page-sub`,children:n(`integrations.aside.profilesHint`)}),(0,Y.jsxs)(`div`,{className:`aside-profile-toolbar`,children:[(0,Y.jsx)(Dt,{on:m?.allEnabled??!1,mixed:!!(m&&m.enabledCount>0&&m.enabledCount<m.total),onClick:()=>void S(!m?.allEnabled),disabled:v||g||h.length===0,label:n(`integrations.aside.all`),showLabel:!0}),(0,Y.jsx)(`span`,{className:`text-caption muted`,children:n(`integrations.aside.applied`,{count:m?.appliedCount??0,total:m?.total??0})}),(0,Y.jsx)(`button`,{type:`button`,className:`btn`,disabled:v||g||!m?.enabledCount,onClick:()=>void C(),children:n(`integrations.aside.syncNow`)})]}),c&&(0,Y.jsx)($,{tone:`err`,children:(0,Y.jsx)(`span`,{className:`aside-profile-failure`,children:c})}),[...u].filter(([e])=>!h.some(t=>t.profileId===e)).map(([e,t])=>(0,Y.jsx)($,{tone:`err`,children:(0,Y.jsxs)(`span`,{className:`aside-profile-failure`,children:[n(`integrations.aside.profile`,{id:e}),`: `,t]})},e)),g&&(0,Y.jsxs)($,{tone:`err`,children:[(0,Y.jsx)(`span`,{children:n(`integrations.aside.loadError`)}),m?.error&&(0,Y.jsx)(`span`,{className:`text-caption`,children:m.error}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>p.refresh(),disabled:v,children:n(`common.retry`)})]}),p.state.showSkeleton&&(0,Y.jsx)(ep,{label:n(`common.loading`),rows:3}),!p.state.showSkeleton&&!g&&m&&h.length===0&&(0,Y.jsx)(`p`,{className:`page-sub`,children:n(`integrations.aside.empty`)}),h.length>0&&(0,Y.jsx)(`div`,{className:`aside-profile-list`,children:h.map(e=>{let t=y(e),r=e.state===`current`||e.state===`stale`,o=e.enabled!==r||e.enabled&&e.state===`stale`,s=(!e.installed||e.state===`unsafe`||e.state===`conflict`)&&!e.enabled;return(0,Y.jsxs)(`div`,{className:`aside-profile-row`,"aria-busy":a===e.profileId,children:[(0,Y.jsxs)(`div`,{className:`aside-profile-info`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost aside-profile-name`,"aria-label":n(`integrations.aside.details`,{name:t}),onClick:()=>i(e),disabled:v||g,children:t}),(0,Y.jsxs)(`div`,{className:`aside-profile-meta`,children:[(0,Y.jsx)(`code`,{children:e.profileId}),e.current&&(0,Y.jsx)(`span`,{className:`text-caption muted`,children:n(`integrations.aside.current`)})]}),o&&(0,Y.jsx)(`span`,{className:`text-caption muted`,children:n(`integrations.aside.pending`)}),e.error&&(0,Y.jsx)(`span`,{className:`text-caption muted`,children:e.error}),u.has(e.profileId)&&(0,Y.jsx)($,{tone:`err`,children:(0,Y.jsx)(`span`,{className:`aside-profile-failure`,children:u.get(e.profileId)})})]}),(0,Y.jsxs)(`div`,{className:`aside-profile-controls`,children:[(0,Y.jsx)(wC,{state:e.state,installed:e.installed,id:`aside-profile-state-${e.profileId}`}),o&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:v||g,"aria-label":n(`integrations.aside.retry`,{name:t}),onClick:()=>void S(e.enabled,e.profileId),children:n(`common.retry`)}),(0,Y.jsx)(Dt,{on:e.enabled,onClick:()=>void S(!e.enabled,e.profileId),disabled:v||g||s,label:n(`integrations.aside.toggle`,{name:t})})]})]},e.profileId)})})]})}var cw=[{id:`overview`,hash:`integrations`,labelKey:`integrations.tab.overview`},{id:`keys`,hash:`integrations/keys`,labelKey:`integrations.tab.keys`},{id:`codex`,hash:`integrations/codex`,labelKey:`integrations.tab.codex`},{id:`claude`,hash:`integrations/claude`,labelKey:`integrations.tab.claude`},{id:`grok`,hash:`integrations/grok`,labelKey:`integrations.tab.grok`},{id:`cursor`,hash:`integrations/cursor`,labelKey:`integrations.tab.cursor`},{id:`opencode`,hash:`integrations/opencode`,labelKey:`integrations.tab.opencode`},{id:`pi`,hash:`integrations/pi`,labelKey:`integrations.tab.pi`},{id:`omp`,hash:`integrations/omp`,labelKey:`integrations.tab.omp`},{id:`hermes`,hash:`integrations/hermes`,labelKey:`integrations.tab.hermes`},{id:`openclaw`,hash:`integrations/openclaw`,labelKey:`integrations.tab.openclaw`},{id:`kimi`,hash:`integrations/kimi`,labelKey:`integrations.tab.kimi`},{id:`gajae`,hash:`integrations/gajae`,labelKey:`integrations.tab.gajae`},{id:`dsh`,hash:`integrations/dsh`,labelKey:`integrations.tab.dsh`},{id:`mcode`,hash:`integrations/mcode`,labelKey:`integrations.tab.mcode`},{id:`zcode`,hash:`integrations/zcode`,labelKey:`integrations.tab.zcode`},{id:`prime`,hash:`integrations/prime`,labelKey:`integrations.tab.prime`},{id:`aside`,hash:`integrations/aside`,labelKey:`integrations.tab.aside`},{id:`raycast`,hash:`integrations/raycast`,labelKey:`integrations.tab.raycast`},{id:`omo`,hash:`integrations/omo`,labelKey:`integrations.tab.omo`},{id:`cline`,hash:`integrations/cline`,labelKey:`integrations.tab.cline`}],lw=new Set([`opencode`,`pi`,`omp`,`hermes`,`openclaw`,`kimi`,`gajae`,`dsh`,`mcode`,`zcode`,`prime`,`aside`,`raycast`,`omo`,`cline`]);function uw(e=window.location.hash){let t=pt(e);return t===`integrations/claude/desktop`?`claude`:cw.find(e=>e.hash===t)?.id??`overview`}function dw(e){return`integrations-tab-${e}`}function fw(e){return`integrations-panel-${e}`}function pw(e){return e===`overview`||e===`keys`?null:Eb[e]??null}function mw({apiBase:e,machineApiBase:t=e,connected:n=!1}){let r=Q(),[i,a]=(0,_.useState)(uw),[o,s]=(0,_.useState)(()=>new Set([uw()])),c=(0,_.useRef)(null),[l,u]=(0,_.useState)([]),[d,f]=(0,_.useState)(!1);c.current===null&&(c.current=new Map),(0,_.useEffect)(()=>{if(!n)return;let e=new AbortController;return fetch(`${t}/api/machine/clients`,{signal:e.signal}).then(e=>e.ok?e.json():null).then(t=>{!e.signal.aborted&&Array.isArray(t?.selectedClients)&&u(t.selectedClients.filter(e=>typeof e==`string`))}).catch(()=>{}),()=>e.abort()},[n,t]);let p=async()=>{f(!0);try{await fetch(`${t}/api/machine/sync`,{method:`POST`,headers:{"Content-Type":`application/json`},body:`{}`})}finally{f(!1)}},m=e=>{a(e),s(t=>t.has(e)?t:new Set([...t,e]))};(0,_.useEffect)(()=>{let e=()=>m(uw());return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]);let h=(e,t)=>{let n=cw.find(t=>t.id===e);n&&(ht(n.hash),m(e),t&&window.requestAnimationFrame(()=>{c.current.get(e)?.focus({preventScroll:!0})}))},g=e=>{let t=cw.findIndex(e=>e.id===i),n=null;e.key===`ArrowLeft`?n=(t-1+cw.length)%cw.length:e.key===`ArrowRight`?n=(t+1)%cw.length:e.key===`Home`?n=0:e.key===`End`&&(n=cw.length-1),n!==null&&(e.preventDefault(),h(cw[n].id,!0))};return(0,Y.jsxs)(`section`,{className:`integrations-page`,children:[(0,Y.jsx)(`div`,{className:`page-head`,children:(0,Y.jsx)(`h2`,{children:r(`nav.integrations`)})}),(0,Y.jsx)(`p`,{className:`page-sub`,children:r(`integrations.subtitle`)}),n&&(0,Y.jsxs)(`section`,{className:`notice`,"aria-label":r(`connection.clients.title`),children:[(0,Y.jsx)(`strong`,{children:r(`connection.clients.title`)}),(0,Y.jsx)(`span`,{children:l.length>0?l.join(`, `):r(`connection.clients.none`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:d,onClick:()=>void p(),children:r(d?`connection.clients.syncing`:`connection.clients.sync`)})]}),(0,Y.jsx)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":r(`integrations.tabsLabel`),children:cw.map(e=>(0,Y.jsxs)(`button`,{ref:t=>{t?c.current.set(e.id,t):c.current.delete(e.id)},type:`button`,role:`tab`,id:dw(e.id),"aria-selected":i===e.id,"aria-controls":fw(e.id),tabIndex:i===e.id?0:-1,className:`page-tab${i===e.id?` page-tab--active`:``}`,onClick:()=>h(e.id,!0),onKeyDown:g,children:[pw(e.id)&&(0,Y.jsx)(Ab,{src:pw(e.id),label:r(e.labelKey),size:14}),r(e.labelKey)]},e.id))}),cw.map(t=>{if(!o.has(t.id))return null;let n=i===t.id;return(0,Y.jsxs)(`div`,{role:`tabpanel`,id:fw(t.id),"aria-labelledby":dw(t.id),hidden:!n,children:[t.id===`overview`&&(0,Y.jsx)(XC,{apiBase:e,active:n}),t.id===`keys`&&(0,Y.jsx)(xS,{apiBase:e,active:n}),t.id===`codex`&&(0,Y.jsxs)(`section`,{className:`integration-native-page`,"aria-labelledby":`codex-integration-title`,children:[(0,Y.jsx)(`h3`,{id:`codex-integration-title`,children:r(`integrations.codex.title`)}),(0,Y.jsx)(`p`,{children:r(`integrations.codex.body`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>ht(`startup`),children:r(`integrations.codex.openService`)})]}),t.id===`claude`&&(0,Y.jsx)(dC,{apiBase:e,active:n}),t.id===`grok`&&(0,Y.jsx)(_C,{apiBase:e,active:n}),t.id===`cursor`&&(0,Y.jsx)(xC,{apiBase:e,active:n}),lw.has(t.id)&&(t.id===`aside`?(0,Y.jsx)(sw,{apiBase:e,active:n}):(0,Y.jsx)(nw,{apiBase:e,client:t.id,active:n}))]},t.id)})]})}function hw(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.supported==`boolean`&&typeof t.installed==`boolean`&&typeof t.running==`boolean`&&typeof t.stale==`boolean`&&typeof t.summary==`string`}var gw={native:`startup.status.native`,protected:`startup.status.protected`,"at-risk":`startup.status.atRisk`},_w={native:`startup.summary.native`,protected:`startup.summary.protected`,"at-risk":`startup.summary.atRisk`},vw={service:`startup.protection.service`,shim:`startup.protection.shim`,none:`startup.protection.none`};function yw({ok:e,yes:t,no:n}){return(0,Y.jsx)(`span`,{className:`badge ${e?`badge-green`:`badge-amber`}`,children:e?t:n})}function bw({failed:e,data:t}){let{t:n}=ut(),r=e?`startup-hero--risk`:t.status===`protected`?`startup-hero--safe`:t.status===`at-risk`?`startup-hero--risk`:`startup-hero--native`,i=e||t.status===`at-risk`?_e:ce,a=t.routingKind===`opencodex-local`?`startup.routing.proxy`:t.routingKind===`custom-local`?`startup.routing.customLocal`:t.routingKind===`custom-remote`?`startup.routing.customRemote`:t.routingKind===`unknown`?`startup.routing.unknown`:`startup.routing.native`;return(0,Y.jsx)(Y.Fragment,{children:(0,Y.jsxs)(`section`,{className:`panel startup-hero ${r}`,"aria-live":`polite`,children:[(0,Y.jsx)(`div`,{className:`startup-hero-icon`,children:(0,Y.jsx)(i,{})}),(0,Y.jsxs)(`div`,{className:`startup-hero-copy`,children:[(0,Y.jsx)(`span`,{className:`badge ${e||t.status===`at-risk`?`badge-amber`:`badge-green`}`,children:n(e?`startup.status.atRisk`:gw[t.status])}),(0,Y.jsx)(`h3`,{children:n(e?`startup.error`:_w[t.status])}),(0,Y.jsx)(`p`,{children:e?n(`startup.staleData`):t.status===`at-risk`?n(Mr(t)):n(`startup.safeDetail`)}),(0,Y.jsxs)(`p`,{className:`muted startup-state-line`,children:[n(a),` · `,n(vw[t.protection]),` · `,n(t.autostartEnabled?`startup.enabled`:`startup.disabled`)]}),(0,Y.jsx)(`p`,{className:`muted text-label`,children:n(`startup.subtitle`)})]})]})})}function xw({data:e,failed:t,loading:n=!1,installBusy:r,installResult:i,onInstall:a}){let{t:o}=ut(),s=e.serviceSupported&&e.serviceInstalled&&e.serviceStale&&!e.serviceConflict,c=e.shimInstalled&&!e.shimHealthy,l=r!==null||t||n;return(0,Y.jsxs)(`section`,{className:`panel startup-details`,children:[(0,Y.jsxs)(`div`,{className:`panel-head`,children:[(0,Y.jsx)(`h3`,{className:`panel-title`,children:o(`startup.details`)}),(0,Y.jsx)(`span`,{className:`muted mono`,children:e.platform})]}),(0,Y.jsxs)(`div`,{className:`startup-detail-row`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`strong`,{children:o(`startup.service`)}),(0,Y.jsx)(`span`,{children:o(`startup.serviceHint`)})]}),(0,Y.jsxs)(`div`,{className:`startup-detail-actions`,children:[(0,Y.jsx)(yw,{ok:e.serviceViable,yes:o(`startup.viable`),no:o(e.serviceConflict?`startup.conflict`:e.serviceStale?`startup.stale`:e.serviceInstalled?`startup.unhealthy`:e.serviceSupported?`startup.notInstalled`:`startup.unsupported`)}),e.serviceSupported&&!e.serviceInstalled&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,"aria-label":`${o(`startup.service`)} - ${o(`startup.install`)}`,disabled:l,onClick:()=>a(`install-service`),children:o(r===`install-service`?`startup.installing`:`startup.install`)}),s&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,"aria-label":`${o(`startup.service`)} - ${o(`startup.repair`)}`,disabled:l,onClick:()=>a(`install-service`,{repair:!0}),children:o(r===`install-service`?`startup.repairing`:`startup.repair`)})]})]}),(0,Y.jsxs)(`div`,{className:`startup-detail-row`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`strong`,{children:o(`startup.shim`)}),(0,Y.jsx)(`span`,{children:o(`startup.shimHint`)})]}),(0,Y.jsxs)(`div`,{className:`startup-detail-actions`,children:[(0,Y.jsx)(yw,{ok:e.shimHealthy&&e.autostartEnabled,yes:o(e.shimCoverage===`cli-only`?`startup.cliOnly`:`startup.healthy`),no:o(e.shimInstalled?e.shimHealthy&&!e.autostartEnabled?`startup.installedDisabled`:`startup.stale`:`startup.notInstalled`)}),!e.shimInstalled&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,"aria-label":`${o(`startup.shim`)} - ${o(`startup.install`)}`,disabled:l,onClick:()=>a(`install-shim`),children:o(r===`install-shim`?`startup.installing`:`startup.install`)}),c&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,"aria-label":`${o(`startup.shim`)} - ${o(`startup.repair`)}`,disabled:l,onClick:()=>a(`install-shim`,{repair:!0}),children:o(r===`install-shim`?`startup.repairing`:`startup.repair`)})]})]}),i&&(0,Y.jsx)(`div`,{className:`notice ${i.kind===`success`?`notice-ok`:`notice-warn`} startup-action-notice`,role:`status`,"aria-live":`polite`,children:i.kind===`success`?i.action===`install-service`?o(i.repair?`startup.serviceRepaired`:`startup.serviceInstalled`):o(i.repair?`startup.shimRepaired`:`startup.shimInstalled`):`${o(`startup.installFailed`)} ${i.detail??``}`})]})}function Sw({tray:e,trayLoading:t,trayError:n,trayBusy:r,onTrayAction:i}){let{t:a}=ut();return(0,Y.jsxs)(`section`,{className:`panel startup-actions`,children:[(0,Y.jsxs)(`div`,{className:`panel-head`,children:[(0,Y.jsx)(`h3`,{className:`panel-title`,children:a(`startup.tray.title`)}),(0,Y.jsx)(Te,{})]}),(0,Y.jsx)(`p`,{className:`muted`,children:a(`startup.tray.hint`)}),(0,Y.jsxs)(`div`,{className:`startup-detail-row`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`strong`,{children:a(`startup.tray.login`)}),(0,Y.jsx)(`span`,{children:a(`startup.tray.notProtection`)})]}),t||n||!e?(0,Y.jsx)(`span`,{className:`badge badge-amber`,children:a(t?`startup.tray.loading`:`startup.tray.unavailable`)}):(0,Y.jsx)(yw,{ok:e.running&&!e.stale,yes:a(`startup.tray.running`),no:a(e.stale?`startup.tray.stale`:e.installed?`startup.tray.stopped`:`startup.tray.notInstalled`)})]}),(0,Y.jsxs)(`div`,{className:`startup-tray-buttons`,children:[!t&&!n&&e&&!e.installed&&!e.stale&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:r,onClick:()=>i(`install`),children:a(`startup.tray.install`)}),!t&&!n&&e?.installed&&!e.stale&&!e.running&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:r,onClick:()=>i(`start`),children:a(`startup.tray.start`)}),!t&&!n&&e?.running&&!e.stale&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:r,onClick:()=>i(`stop`),children:a(`startup.tray.stop`)}),!t&&!n&&e&&(e.installed||e.stale)&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-danger`,disabled:r,onClick:()=>{window.confirm(a(`startup.tray.uninstall`))&&i(`uninstall`)},children:a(`startup.tray.uninstall`)})]}),(n||e?.stale)&&(0,Y.jsx)(`div`,{className:`notice notice-warn startup-tray-error`,role:`alert`,children:a(`startup.tray.error`)})]})}function Cw({data:e,copied:t,onCopy:n}){let{t:r}=ut(),i=e.serviceInstalled&&!e.serviceConflict?e.commands.repairService:e.commands.installService;return(0,Y.jsxs)(`section`,{className:`panel startup-actions`,children:[(0,Y.jsxs)(`div`,{className:`panel-head`,children:[(0,Y.jsx)(`h3`,{className:`panel-title`,children:r(`startup.recovery`)}),(0,Y.jsx)(ae,{})]}),(0,Y.jsxs)(`details`,{className:`startup-recovery-details`,open:e.status!==`protected`,children:[(0,Y.jsx)(`summary`,{className:`muted`,children:r(`startup.recoveryHint`)}),(0,Y.jsxs)(`div`,{className:`startup-command-list`,children:[e.serviceSupported&&(0,Y.jsxs)(`div`,{className:`startup-command-row`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`strong`,{children:r(`startup.command.service`)}),(0,Y.jsx)(`code`,{children:i})]}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>n(i),children:r(t===i?`startup.copied`:`startup.copy`)})]}),(0,Y.jsxs)(`div`,{className:`startup-command-row`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`strong`,{children:r(`startup.command.shim`)}),(0,Y.jsx)(`code`,{children:e.commands.installShim})]}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>n(e.commands.installShim),children:t===e.commands.installShim?r(`startup.copied`):r(`startup.copy`)})]}),(0,Y.jsxs)(`div`,{className:`startup-command-row`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`strong`,{children:r(`startup.command.native`)}),(0,Y.jsx)(`code`,{children:e.commands.restoreNative})]}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>n(e.commands.restoreNative),children:t===e.commands.restoreNative?r(`startup.copied`):r(`startup.copy`)})]})]}),e.status===`at-risk`&&(0,Y.jsxs)(`div`,{className:`notice notice-warn startup-action-notice`,role:`alert`,children:[(0,Y.jsx)(Te,{}),` `,r(`startup.recommended`,{cmd:e.recommendedCommand??e.commands.installService})]})]})]})}var ww=`ocx.startup.page.v1:`;function Tw(e,t){let n=t===`win32`?`; `:` && `;return e.join(n)}function Ew(e,t,n){if(!e)return{warning:null,fix:null};let r=!!e.catalogClamp?.active,i=!!e.newerAvailable,a=(r?e.catalogClamp?.runtimeVersion:e.version)??e.version??`unknown`,o=(e.catalogClamp?.removedEfforts??[]).join(`, `),s=Tw([`ocx doctor --fix-codex-runtime`,`ocx sync`],n);return r?{warning:o?t(`startup.codexRuntime.clampHiddenWithEfforts`,{version:a,efforts:o}):t(`startup.codexRuntime.clampHidden`,{version:a}),fix:i?s:`ocx sync`}:i?{warning:t(`startup.codexRuntime.olderBinary`,{version:a}),fix:s}:{warning:null,fix:null}}function Dw({apiBase:e,machineApiBase:t=e,connected:n=!1}){let{t:r}=ut(),i=`${ww}${e}`,a=(0,_.useMemo)(()=>Tr(i),[i]),o=`startup-page:${e}`,[s,c]=(0,_.useState)(null),[l,u]=(0,_.useState)(()=>a?.tray??null),[d,f]=(0,_.useState)(()=>!a?.data),[p,m]=(0,_.useState)(!1),[h,g]=(0,_.useState)(!1),[v,y]=(0,_.useState)(null),[b,x]=(0,_.useState)(null),[S,C]=(0,_.useState)(()=>a?.warning??null),[w,T]=(0,_.useState)(()=>a?.fix??null),[E,D]=(0,_.useState)(()=>!a?.data),O=(0,_.useRef)(!!a?.data),k=(0,_.useRef)(0),[A,j]=(0,_.useState)(null),[M,N]=(0,_.useState)(!1);(0,_.useEffect)(()=>{if(!n)return;let e=new AbortController;return fetch(`${t}/api/machine/shim`,{signal:e.signal}).then(e=>e.ok?e.json():null).then(t=>{e.signal.aborted||j(t)}).catch(()=>{e.signal.aborted||j(null)}),()=>e.abort()},[n,t]);let P=async e=>{N(!0);try{let n=await fetch(`${t}/api/machine/shim`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:e})});if(n.ok){let e=await n.json();j(e.shim??null)}}finally{N(!1)}};(0,_.useEffect)(()=>()=>{k.current+=1},[e]);let F=(0,_.useCallback)(async t=>{let n=++k.current,a=O.current;a||(f(!0),D(!0));try{let a=fetch(`${e}/api/settings`,{signal:t}).then(async e=>e.ok?await e.json():null).catch(()=>null),o=await fetch(`${e}/api/startup-health`,{signal:t});if(!o.ok)throw Error(`fetch failed`);let s=await o.json();x(e=>e?.kind===`error`&&(s.status===`native`&&e.forLocalRouting===!0||(e.action===`install-service`?s.serviceViable:s.shimInstalled&&s.shimHealthy))?null:e),O.current=!0;let c=Tr(i);kr(i,{data:s,warning:c?.warning??null,fix:c?.fix??null,tray:c?.tray??null});let l=s.platform===`win32`?fetch(`${e}/api/windows-tray`,{signal:t}).then(async e=>{if(!e.ok)throw Error(`tray status failed`);let t=await e.json();if(!hw(t))throw Error(`invalid tray status`);return{tray:t,error:!1}}).catch(()=>({tray:null,error:!0})):Promise.resolve({tray:null,error:!1});return Promise.all([a,l]).then(([e,a])=>{if(t.aborted||n!==k.current)return;let o=s.platform===`win32`?a.tray:null;if(s.platform===`win32`?(u(o),g(a.error)):(u(null),g(!1)),f(!1),D(!1),e){let t=Ew(e.codexRuntime,r,s.platform);C(t.warning),T(t.fix),kr(i,{data:s,warning:t.warning,fix:t.fix,tray:o});return}let c=Tr(i);kr(i,{data:s,warning:c?.warning??null,fix:c?.fix??null,tray:o})}),s}catch(e){throw t.aborted?e:(a||(u(null),g(!0),C(null),T(null)),D(!1),f(!1),e)}},[e,i,r]),I=jr(o,[e],F,{isEmpty:()=>!1,initialData:a?.data??void 0}),L=I.state,R=I.refresh,z=L.data??a?.data??null,B=L.refreshing,V=!!z?.diagnosticStale||L.showError;(0,_.useEffect)(()=>{if(!z?.diagnosticStale)return;let e=window.setTimeout(R,2e3);return()=>window.clearTimeout(e)},[z,R]);let H=async e=>{try{await navigator.clipboard.writeText(e),c(e),window.setTimeout(()=>c(t=>t===e?null:t),1600)}catch{c(null)}},U=async t=>{m(!0),g(!1);try{let n=await fetch(`${e}/api/windows-tray`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:t})});if(!n.ok)throw Error(`tray action failed`);let r=await n.json();if(!hw(r.status))throw Error(`invalid tray action status`);u(r.status),g(!1)}catch{u(null),g(!0)}finally{m(!1)}},W=async(t,n)=>{y(t),x(null);try{let r=await fetch(`${e}/api/startup-action`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:t,repair:n?.repair===!0})});if(!r.ok){let e=await r.json().catch(()=>null);throw Error(typeof e?.error==`string`?e.error:`installation failed`)}x({kind:`success`,action:t,repair:n?.repair===!0}),R()}catch(e){x({kind:`error`,action:t,repair:n?.repair===!0,detail:e instanceof Error?e.message:String(e),forLocalRouting:z?.localRoutingDependency===!0})}finally{y(null)}};return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{className:`page-head`,children:[(0,Y.jsx)(`h2`,{children:r(`startup.title`)}),(0,Y.jsx)(`div`,{className:`startup-page-head-actions`,children:(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>R(),disabled:B,children:[(0,Y.jsx)(de,{}),` `,r(`startup.refresh`)]})})]}),n&&(0,Y.jsxs)(`section`,{className:`notice startup-page-notice`,"aria-label":r(`connection.machine.title`),children:[(0,Y.jsx)(`strong`,{children:r(`connection.machine.title`)}),(0,Y.jsx)(`span`,{children:A?.healthy?r(`connection.machine.shimHealthy`):r(`connection.machine.shimNeedsAttention`)}),(0,Y.jsxs)(`div`,{className:`startup-page-head-actions`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:M,onClick:()=>void P(`repair`),children:r(`connection.machine.repairShim`)}),A?.installed&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:M,onClick:()=>void P(`uninstall`),children:r(`connection.machine.removeShim`)})]})]}),L.showSkeleton&&!z?(0,Y.jsx)(ep,{label:r(`startup.loading`),rows:5}):L.kind===`failed-cold`?(0,Y.jsxs)(`div`,{className:`startup-page-notice`,children:[(0,Y.jsx)($,{tone:`err`,children:L.error instanceof Error?L.error.message:r(`startup.error`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>R(),children:r(`common.retry`)})]}):z?(0,Y.jsxs)(Y.Fragment,{children:[L.showError&&(0,Y.jsx)($,{tone:`err`,children:r(`startup.error`)}),V&&(0,Y.jsx)(`div`,{className:`notice notice-warn startup-page-notice`,role:`alert`,children:r(`startup.staleData`)}),(E||S)&&(0,Y.jsx)(`div`,{className:`startup-runtime-notice-slot${E&&!S?` startup-runtime-notice-slot--pending`:``}`,"aria-hidden":E&&!S?!0:void 0,children:S&&(0,Y.jsxs)(`div`,{className:`notice notice-warn startup-page-notice startup-runtime-notice`,role:`status`,children:[(0,Y.jsx)(`p`,{className:`startup-runtime-notice__text`,children:S}),w&&(0,Y.jsxs)(`div`,{className:`startup-runtime-notice__fix`,children:[(0,Y.jsx)(`code`,{children:w}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void H(w),children:r(s===w?`startup.copied`:`startup.copy`)})]})]})}),(0,Y.jsx)(bw,{failed:V,data:z}),(0,Y.jsx)(xw,{data:z,failed:V,loading:B,installBusy:v,installResult:b,onInstall:(e,t)=>{W(e,t)}}),z.platform===`win32`&&(0,Y.jsx)(Sw,{tray:l,trayLoading:d,trayError:h,trayBusy:p,onTrayAction:e=>{U(e)}}),(0,Y.jsx)(Cw,{data:z,copied:s,onCopy:e=>{H(e)}})]}):null]})}function Ow(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function kw(e){return`'${e.replace(/'/g,`''`)}'`}function Aw(e,t){return{posix:`printf '%s\\n' ${Ow(e)} | ocx remote-workspace pair ${Ow(t)} --pairing-code-stdin --root "$PWD" && ocx remote-workspace agent`,powershell:`$pairingCode = ${kw(e)}; $pairingCode | ocx remote-workspace pair ${kw(t)} --pairing-code-stdin --root (Get-Location).Path; if ($LASTEXITCODE -eq 0) { ocx remote-workspace agent }`}}var jw=[`codex`,`claude`,`pi`],Mw={codex:`Codex`,claude:`Claude Code`,pi:`Pi`},Nw={starting:`remote.status.starting`,ready:`remote.status.ready`,running:`remote.status.running`,waiting_for_executor:`remote.status.waiting`,failed:`remote.status.failed`,stopped:`remote.status.stopped`},Pw={status:`remote.event.status`,tool:`remote.event.tool`,error:`remote.event.error`};function Fw(e){return e===`codex`||e===`claude`||e===`pi`}function Iw(e){return e===`read-only`||e===`workspace`}async function Lw(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}function Rw({apiBase:e,hubOrigin:t}){let n=Q(),r=K(`remote-workspace:${e}`,[e],async t=>await It(await fetch(`${e}/api/remote-workspace`,{signal:t,cache:`no-store`}),n(`remote.loadFailed`)),{pollMs:3e3,deadlineMs:1e4}),i=r.data,[a,o]=(0,_.useState)(``),[s,c]=(0,_.useState)(``),[l,u]=(0,_.useState)(`codex`),[d,f]=(0,_.useState)(`read-only`),[p,m]=(0,_.useState)(``),[h,g]=(0,_.useState)(null),[v,y]=(0,_.useState)(null),[b,x]=(0,_.useState)({}),[S,C]=(0,_.useState)(null),[w,T]=(0,_.useState)(!1),[E,D]=(0,_.useState)(!1),O=(0,_.useRef)(null),[k,A]=(0,_.useState)(null),[j,M]=(0,_.useState)(null),N=i?.devices??[],P=N.find(e=>e.id===a)??N.find(e=>e.online)??N[0]??null,F=P?.roots.find(e=>e.id===s)??P?.roots[0]??null,I=d===`workspace`&&(P?.capabilities.includes(`workspace.exec`)??!1),L=P&&!P.capabilities.includes(`workspace.exec`)?n(`remote.access.workspaceFilesOnly`):n(`remote.access.workspace`),R=jw.filter(e=>i?.runtimes?.[e]?.available),z=R.includes(l)?l:R[0]??l,B=i?.sessions??[],V=[...B].reverse().find(e=>e.status!==`stopped`),H=(B.find(e=>e.id===p)??(h?.id===p?h:null)??V??h)?.id,U=B.find(e=>e.id===H),W=h?.id===H?h:null,G=(W&&(!U||(W.events.at(-1)?.sequence??0)>(U.events.at(-1)?.sequence??0))?W:U)??V??h,q=b[G?.id??``]??``,J=e=>{let t=G?.id;t&&x(n=>({...n,[t]:typeof e==`function`?e(n[t]??``):e}))},X=!!(i&&!r.lastAttemptOk),ee=!!(G&&q.trim()&&S===null&&!w&&!E&&!X&&G.status!==`running`&&G.status!==`starting`&&G.status!==`stopped`&&(G.status!==`failed`||G.resumable!==!1)&&!(G.status===`waiting_for_executor`&&!N.find(e=>e.id===G.deviceId)?.online)),te=(0,_.useMemo)(()=>v?Aw(v.code,t):{posix:``,powershell:``},[v,t]),ne=async(t,n,r)=>{let i=await It(await fetch(`${e}${t}`,n),r);if(i===void 0)throw Error(r);return i},Z=async()=>{C(`pair`),A(null);try{let e=await ne(`/api/remote-workspace/pairing`,{method:`POST`},n(`remote.requestFailed`));y(e),M(null)}catch(e){A({tone:`err`,text:e instanceof Error?e.message:n(`remote.requestFailed`)})}finally{C(null)}},re=async()=>{if(!(!P||!F)){C(`session`),A(null);try{let e=await ne(`/api/remote-workspace/sessions`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({profile:z,deviceId:P.id,rootId:F.id,accessMode:d})},n(`remote.requestFailed`));g(e),m(e.id),A({tone:`ok`,text:n(`remote.sessionStarted`)}),r.refresh()}catch(e){A({tone:`err`,text:e instanceof Error?e.message:n(`remote.requestFailed`)})}finally{C(null)}}},ie=async()=>{if(!G||!ee)return;let t=G,i=q;T(!0),A(null);let a;try{let o=await fetch(`${e}/api/remote-workspace/sessions/${t.id}/prompt`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({prompt:i})});a=o.status;let s=await It(o,n(`remote.requestFailed`));if(!s)throw Error(n(`remote.requestFailed`));J(e=>e===i?``:e),O.current!==t.id&&g(s),r.refresh()}catch(e){O.current!==t.id&&(A({tone:`err`,text:a!==void 0&&a>=400&&a<500?e instanceof Error?e.message:n(`remote.requestFailed`):n(`remote.submissionUnknown`)}),r.refresh())}finally{T(!1)}},oe=async()=>{if(!G||E)return;let e=G;D(!0);try{await ne(`/api/remote-workspace/sessions/${e.id}`,{method:`DELETE`},n(`remote.requestFailed`)),O.current=e.id,g({...e,status:`stopped`}),r.refresh()}catch(e){A({tone:`err`,text:e instanceof Error?e.message:n(`remote.requestFailed`)})}finally{D(!1)}},se=async e=>{if(confirm(n(`remote.revokeConfirm`,{name:e.name}))){C(`revoke`);try{await ne(`/api/remote-workspace/devices/${e.id}`,{method:`DELETE`},n(`remote.requestFailed`)),a===e.id&&o(``),r.refresh()}catch(e){A({tone:`err`,text:e instanceof Error?e.message:n(`remote.requestFailed`)})}finally{C(null)}}},ce=async(e,t)=>{M(await Lw(t)?e:null)};return r.loading&&!i?(0,Y.jsx)(`div`,{className:`alert`,children:n(`remote.loading`)}):r.error&&!i?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)($,{tone:`err`,children:n(`remote.loadFailed`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>void r.refresh(),children:n(`common.retry`)})]}):i?.available===!1?(0,Y.jsx)($,{tone:`err`,children:n(`remote.hubRequired`)}):(0,Y.jsxs)(`section`,{className:`remote-workspace-page`,children:[(0,Y.jsxs)(`div`,{className:`page-head`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`h2`,{children:n(`remote.title`)}),(0,Y.jsx)(`p`,{className:`page-sub`,children:n(`remote.subtitle`)})]}),(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void r.refresh(),disabled:r.refreshing,children:[(0,Y.jsx)(de,{}),` `,n(`remote.refresh`)]})]}),X?(0,Y.jsx)($,{tone:`err`,children:n(`remote.loadFailed`)}):null,k?(0,Y.jsx)($,{tone:k.tone,children:k.text}):null,(0,Y.jsxs)(`div`,{className:`remote-workspace-grid`,children:[(0,Y.jsxs)(`div`,{className:`remote-workspace-column`,children:[(0,Y.jsxs)(`article`,{className:`panel panel-accent remote-pair-card`,children:[(0,Y.jsxs)(`div`,{className:`remote-panel-head`,children:[(0,Y.jsx)(`div`,{className:`remote-icon`,children:(0,Y.jsx)(je,{})}),(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`h3`,{children:n(`remote.addComputer`)}),(0,Y.jsx)(`p`,{children:n(`remote.addComputerHint`)})]})]}),(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>void Z(),disabled:S!==null,children:[(0,Y.jsx)(ue,{}),` `,n(`remote.createPairing`)]}),v?(0,Y.jsxs)(`div`,{className:`remote-pairing-result`,children:[(0,Y.jsx)(`span`,{className:`field-label`,children:n(`remote.pairingCode`)}),(0,Y.jsx)(`div`,{className:`remote-pairing-code`,children:v.code}),(0,Y.jsx)(`div`,{className:`remote-expiry`,children:n(`remote.pairingExpires`,{time:new Date(v.expiresAt).toLocaleTimeString()})}),(0,Y.jsx)(`span`,{className:`field-label`,children:n(`remote.pairingCommandPosix`)}),(0,Y.jsx)(`pre`,{children:(0,Y.jsx)(`code`,{children:te.posix})}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void ce(`posix`,te.posix),children:n(j===`posix`?`remote.copied`:`remote.copyCommand`)}),(0,Y.jsx)(`span`,{className:`field-label`,children:n(`remote.pairingCommandWindows`)}),(0,Y.jsx)(`pre`,{children:(0,Y.jsx)(`code`,{children:te.powershell})}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void ce(`powershell`,te.powershell),children:n(j===`powershell`?`remote.copied`:`remote.copyCommand`)})]}):null]}),(0,Y.jsxs)(`section`,{className:`panel remote-device-panel`,children:[(0,Y.jsxs)(`div`,{className:`remote-section-title`,children:[(0,Y.jsx)(`h3`,{children:n(`remote.devices`)}),(0,Y.jsx)(`span`,{children:N.length})]}),N.length===0?(0,Y.jsx)(`p`,{className:`remote-empty`,children:n(`remote.noDevices`)}):(0,Y.jsx)(`div`,{className:`remote-device-list`,children:N.map(e=>(0,Y.jsxs)(`div`,{className:`remote-device${P?.id===e.id?` selected`:``}`,children:[(0,Y.jsxs)(`button`,{type:`button`,className:`remote-device-main`,onClick:()=>{o(e.id),c(e.roots[0]?.id??``)},"aria-pressed":P?.id===e.id,children:[(0,Y.jsx)(`span`,{className:`remote-online-dot${e.online?` online`:``}`}),(0,Y.jsxs)(`span`,{className:`remote-device-copy`,children:[(0,Y.jsx)(`strong`,{children:e.name}),(0,Y.jsxs)(`small`,{children:[e.platform,` · `,e.online?n(`remote.online`):n(`remote.offline`),` · `,e.capabilities.includes(`workspace.exec`)?n(`remote.capability.full`):n(`remote.capability.files`)]})]})]}),(0,Y.jsx)(`button`,{type:`button`,className:`remote-revoke`,"aria-label":n(`remote.revoke`),disabled:S!==null||w||E,onClick:()=>void se(e),children:(0,Y.jsx)(me,{})})]},e.id))})]})]}),(0,Y.jsxs)(`div`,{className:`remote-workspace-column remote-session-column`,children:[(0,Y.jsxs)(`section`,{className:`panel remote-launch-panel`,children:[(0,Y.jsxs)(`div`,{className:`remote-section-title`,children:[(0,Y.jsx)(`h3`,{children:n(`remote.newSession`)}),(0,Y.jsx)(Pe,{})]}),(0,Y.jsxs)(`div`,{className:`remote-launch-fields`,children:[(0,Y.jsxs)(`label`,{children:[(0,Y.jsx)(`span`,{className:`field-label`,children:n(`remote.device`)}),(0,Y.jsx)(kt,{value:P?.id??``,options:N.map(e=>({value:e.id,label:e.name})),onChange:e=>{o(e),c(N.find(t=>t.id===e)?.roots[0]?.id??``)},label:n(`remote.device`),disabled:N.length===0})]}),(0,Y.jsxs)(`label`,{children:[(0,Y.jsx)(`span`,{className:`field-label`,children:n(`remote.folder`)}),(0,Y.jsx)(kt,{value:F?.id??``,options:(P?.roots??[]).map(e=>({value:e.id,label:e.label})),onChange:c,label:n(`remote.folder`),disabled:!P})]}),(0,Y.jsxs)(`label`,{children:[(0,Y.jsx)(`span`,{className:`field-label`,children:n(`remote.runtime`)}),(0,Y.jsx)(kt,{value:z,options:jw.map(e=>({value:e,label:i?.runtimes?.[e]?.available?Mw[e]:`${Mw[e]} · ${n(`remote.unavailable`)}`})),onChange:e=>{Fw(e)&&u(e)},label:n(`remote.runtime`)})]}),(0,Y.jsxs)(`label`,{children:[(0,Y.jsx)(`span`,{className:`field-label`,children:n(`remote.access`)}),(0,Y.jsx)(kt,{value:d,options:[{value:`read-only`,label:n(`remote.access.readOnly`)},{value:`workspace`,label:L}],onChange:e=>{Iw(e)&&f(e)},label:n(`remote.access`)})]})]}),P?(0,Y.jsxs)(`div`,{className:`remote-execution-map`,children:[(0,Y.jsxs)(`span`,{children:[(0,Y.jsx)(`strong`,{children:Mw[z]}),n(`remote.runsOnHub`)]}),(0,Y.jsxs)(`span`,{children:[(0,Y.jsx)(`strong`,{children:P.name}),n(d===`read-only`?`remote.runsReadOnly`:I?`remote.runsFilesCommands`:`remote.runsFilesOnly`)]})]}):null,d===`workspace`&&!I&&P?(0,Y.jsx)($,{tone:`err`,children:n(`remote.execUnavailable`)}):null,!i?.runtimes?.[z]?.available&&i?.runtimes?.[z]?.reason?(0,Y.jsx)(`p`,{className:`remote-runtime-reason`,children:i.runtimes[z].reason}):null,(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-primary remote-start`,onClick:()=>void re(),disabled:!P?.online||!F||!i?.runtimes?.[z]?.available||S!==null||w||E,children:[(0,Y.jsx)(ae,{}),` `,n(`remote.startSession`)]})]}),(0,Y.jsxs)(`section`,{className:`panel remote-console-panel`,children:[(0,Y.jsxs)(`div`,{className:`remote-section-title`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`h3`,{children:n(`remote.sessions`)}),G?(0,Y.jsxs)(`small`,{children:[Mw[G.profile],` · `,G.deviceName,`/`,G.rootLabel,` · `,G.accessMode===`read-only`?n(`remote.access.readOnly`):G.capabilities.includes(`workspace.exec`)?n(`remote.access.workspace`):n(`remote.access.workspaceFilesOnly`)]}):null]}),G?(0,Y.jsx)(`span`,{className:`remote-status remote-status--${G.status}`,children:n(Nw[G.status])}):null]}),B.length>1?(0,Y.jsx)(kt,{value:G?.id??``,options:B.map(e=>({value:e.id,label:`${Mw[e.profile]} · ${e.deviceName}/${e.rootLabel}`})),onChange:m,label:n(`remote.sessions`)}):null,G?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`div`,{className:`remote-events`,"aria-live":`polite`,"aria-label":n(`remote.events`),children:G.events.length===0?(0,Y.jsx)(`p`,{className:`remote-empty`,children:n(`remote.noEvents`)}):G.events.map(e=>(0,Y.jsxs)(`div`,{className:`remote-event remote-event--${e.type}`,children:[(0,Y.jsx)(`span`,{children:e.type===`assistant`?Mw[G.profile]:n(Pw[e.type])}),(0,Y.jsx)(`p`,{children:e.text})]},e.sequence))}),G.status===`failed`&&G.resumable===!1?(0,Y.jsx)($,{tone:`err`,children:n(`remote.notResumable`)}):null,(0,Y.jsxs)(`label`,{className:`remote-composer`,children:[(0,Y.jsx)(`span`,{className:`field-label`,children:n(`remote.prompt`)}),(0,Y.jsx)(`textarea`,{className:`input`,rows:4,value:q,onChange:e=>J(e.target.value),placeholder:n(`remote.promptPlaceholder`),disabled:G.status===`stopped`||G.status===`failed`&&G.resumable===!1,onKeyDown:e=>{(e.ctrlKey||e.metaKey)&&e.key===`Enter`&&(e.preventDefault(),ie())}})]}),(0,Y.jsxs)(`div`,{className:`remote-console-actions`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>void ie(),disabled:!ee,children:n(`remote.send`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-danger`,onClick:()=>void oe(),disabled:E||G.status===`stopped`,children:n(`remote.stop`)})]})]}):(0,Y.jsx)(`p`,{className:`remote-empty remote-empty--console`,children:n(`remote.noSessions`)})]})]})]})]})}var zw=3e5,Bw=6e5,Vw=`https://github.com/lidge-jun/opencodex`;async function Hw(e,t){let n=await fetch(e,{signal:t});return n.ok?await n.json():null}function Uw({apiBase:e,onOpenUpdate:t}){let n=Q(),[r,i]=(0,_.useState)(!1),[a,o]=(0,_.useState)(null),s=K(`sidebar-star:${e}`,[e],t=>Hw(`${e}/api/github/star`,t),{pollMs:zw}),c=K(`sidebar-update-badge:${e}`,[e],t=>Hw(`${e}/api/update/badge`,t),{pollMs:Bw}),l=s.data?.state??null,u=a!==null&&a.basedOn===l?a.state:l??`not-starred`,d=s.data?.url??Vw,f=u===`starred`,p=c.data,m=p?.updateAvailable===!0,h=p?.latestVersion??null,g=()=>window.open(d,`_blank`,`noopener,noreferrer`),v=async()=>{if(!(f||r)){if(u===`unauthenticated`){g();return}i(!0);try{let t=await fetch(`${e}/api/github/star`,{method:`POST`}),n=t.ok?await t.json():null;if(n?.ok===!0){o({state:`starred`,basedOn:l});return}n?.state&&o({state:n.state,basedOn:l}),g()}catch{g()}finally{i(!1),s.refresh()}}},y=n(f?`sidebar.starred`:u===`unauthenticated`?`sidebar.starUnauthenticated`:`sidebar.star`),b=m&&h?n(`sidebar.updateAvailable`,{version:h}):n(`sidebar.checkUpdate`);return(0,Y.jsxs)(`div`,{className:`sidebar-github-row`,children:[(0,Y.jsxs)(`a`,{className:`sidebar-link sidebar-github-link`,href:d,target:`_blank`,rel:`noreferrer`,children:[(0,Y.jsx)(we,{}),` `,n(`common.github`)]}),(0,Y.jsxs)(`div`,{className:`sidebar-github-actions`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`sidebar-orb${f?` sidebar-orb--starred`:``}`,onClick:()=>{v()},disabled:r||f,"aria-label":y,"aria-pressed":f,title:y,children:(0,Y.jsx)(Re,{"aria-hidden":`true`,...f?{fill:`currentColor`}:{}})}),(0,Y.jsxs)(`button`,{type:`button`,className:`sidebar-orb${m?` sidebar-orb--update`:``}`,onClick:t,"aria-label":b,title:b,children:[(0,Y.jsx)(Se,{"aria-hidden":`true`}),m&&(0,Y.jsx)(`span`,{className:`sidebar-orb-dot`,"aria-hidden":`true`})]})]})]})}var Ww=/^ocx_pair_[A-Za-z0-9_-]{43}$/,Gw=class extends Error{kind;constructor(e){super(`pairing_${e}`),this.kind=e,this.name=`PairingError`}};async function Kw(e,t,n,r){r?.throwIfAborted();let i=t.trim();if(!Ww.test(i))throw new Gw(`invalid-code`);let a=n??((e,t)=>window.fetch(e,t)),o;try{o=await a(e.bootstrapPath,{method:`POST`,signal:r,headers:{"Content-Type":`application/json`,Accept:`text/html`},body:JSON.stringify({grant:i})})}catch(e){throw r?.aborted?e:new Gw(`unreachable`)}if(!o.ok){try{await o.body?.cancel()}catch{}throw new Gw(o.status===401||o.status===403?`refused`:`request-failed`)}let s;try{s=await o.text()}catch(e){throw r?.aborted?e:new Gw(`invalid-response`)}if(r?.throwIfAborted(),!Ux(`shared`,s))throw new Gw(`invalid-response`);return!0}function qw({target:e,onConnected:t}){let n=Q(),[r,i]=(0,_.useState)(``),[a,o]=(0,_.useState)(!1),[s,c]=(0,_.useState)(null),l=(0,_.useRef)(null);(0,_.useEffect)(()=>()=>l.current?.abort(),[]);let u=_s(),d=`ocx gui pair --origin "${window.location.origin}"`,f=u.outcomeFor(d);return(0,Y.jsxs)(`section`,{className:`card connect-pairing`,"aria-labelledby":`connect-pairing-title`,children:[(0,Y.jsx)(`h2`,{id:`connect-pairing-title`,children:n(`connection.pairing.title`)}),(0,Y.jsxs)(`p`,{children:[n(`connection.pairing.hub`),`: `,(0,Y.jsx)(`code`,{children:e.serverOrigin})]}),(0,Y.jsx)(`p`,{children:n(`connection.pairing.getCode`)}),(0,Y.jsx)(`pre`,{style:{whiteSpace:`pre-wrap`,overflowWrap:`anywhere`},children:(0,Y.jsx)(`code`,{children:d})}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>u.copy(d,d),children:n(f===`copied`?`startup.copied`:`startup.copy`)}),f===`unavailable`&&(0,Y.jsx)(`p`,{role:`status`,children:n(`prov.linkCopyUnavailable`)}),(0,Y.jsx)(`p`,{children:n(`connection.pairing.askOperator`)}),(0,Y.jsx)(`p`,{children:n(`connection.pairing.notApiKey`)}),(0,Y.jsxs)(`form`,{onSubmit:async n=>{if(n.preventDefault(),a)return;o(!0),c(null);let i=new AbortController;l.current=i;try{await Kw(e,r,void 0,i.signal),i.signal.aborted||t()}catch(e){i.signal.aborted||c(e instanceof Gw?e.kind:`unreachable`)}finally{i.signal.aborted||o(!1),l.current===i&&(l.current=null)}},className:`api-form-row`,children:[(0,Y.jsx)(`label`,{htmlFor:`connect-pairing-code`,className:`field-label`,children:n(`connection.pairing.code`)}),(0,Y.jsx)(`input`,{id:`connect-pairing-code`,name:`pairingCode`,value:r,onChange:e=>i(e.currentTarget.value),autoComplete:`off`,spellCheck:!1,disabled:a,className:`input mono`,"aria-invalid":!!s||void 0,"aria-describedby":s?`connect-pairing-error`:void 0}),(0,Y.jsx)(`button`,{type:`submit`,className:`btn btn-primary`,disabled:a||!r.trim(),children:n(a?`connection.pairing.submitting`:`connection.pairing.submit`)}),s&&(0,Y.jsx)(`p`,{id:`connect-pairing-error`,className:`alert alert-err`,role:`alert`,children:n(s===`invalid-code`?`connection.pairing.notApiKey`:s===`unreachable`?`connection.pairing.networkError`:s===`request-failed`?`connection.pairing.requestError`:s===`invalid-response`?`connection.pairing.responseError`:`connection.pairing.error`)})]}),e.transport===`relay`&&(0,Y.jsx)(`p`,{className:`text-muted`,children:n(`connection.pairing.relayWarning`)})]})}var Jw=new Set([`dashboard`,`startup`,`providers`,`models`,`subagents`,`logs`,`usage`,`storage`,`remote`,`codex-set`,`integrations`]);function Yw(e){let t=pt(e??(typeof window<`u`?window.location.hash:``)).split(`/`)[0];return t===`debug`?`logs`:t===`codex-auth`?`codex-set`:t===`combos`||t===`routing`||t===`lab`?`models`:t===`api`||t===`claude`||t===`grok`?`integrations`:Jw.has(t)?t:`dashboard`}var Xw=[`dashboard/providers`,`dashboard/models`],Zw=[`models/combos`,`models/routing`,`models/compatibility`],Qw=[`integrations/keys`,`integrations/codex`,`integrations/claude`,`integrations/claude/desktop`,`integrations/grok`,`integrations/cursor`,`integrations/opencode`,`integrations/pi`,`integrations/omp`,`integrations/hermes`,`integrations/openclaw`,`integrations/kimi`,`integrations/gajae`,`integrations/dsh`,`integrations/mcode`,`integrations/zcode`,`integrations/prime`,`integrations/aside`,`integrations/raycast`,`integrations/omo`,`integrations/cline`];function $w(e,t){return e===t||t===`logs`&&e===`logs/debug`||t===`codex-set`&&e===`codex-set/prompt`||t===`models`&&Zw.includes(e)||t===`dashboard`&&(e===`dashboard/update`||Xw.includes(e))||t===`integrations`&&Qw.includes(e)}function eT(e){let t=Yw(e);return e===`debug`||e.startsWith(`debug/`)?{page:`logs`,replaceTo:`logs/debug`}:e===`codex-auth`||e.startsWith(`codex-auth/`)?{page:`codex-set`,replaceTo:`codex-set`}:e===`combos`||e.startsWith(`combos/`)?{page:`models`,replaceTo:`models/combos`}:e===`routing`||e.startsWith(`routing/`)?{page:`models`,replaceTo:`models/routing`}:e===`lab`||e.startsWith(`lab/`)?{page:`models`,replaceTo:`models/compatibility`}:e===`api`?{page:`integrations`,replaceTo:`integrations/keys`}:e===`claude`?{page:`integrations`,replaceTo:`integrations/claude`}:e===`grok`?{page:`integrations`,replaceTo:`integrations/grok`}:e===`providers/workspace`?{page:`providers`,replaceTo:`providers`}:$w(e,t)?{page:t,replaceTo:null}:{page:t,replaceTo:t}}var tT=[`ocx-global-view`,`ocx-view`,`ocx-providers-view`,`ocx-subagents-view`,`ocx-storage-view`,`ocx-codexauth-view`,`ocx-apikeys-view`,`ocx-claudecode-view`,`ocx-usage-view`,`ocx-logs-view`,`ocx-models-view`,`ocx-dashboard-view`];function nT(){try{for(let e of tT)localStorage.removeItem(e)}catch{}}function rT(){let[e,t]=(0,_.useState)(Yw);(0,_.useEffect)(()=>{nT()},[]);let n=(0,_.useCallback)(e=>{let n=eT(e);n.replaceTo&&mt(n.replaceTo),t(n.page)},[]);return(0,_.useEffect)(()=>{let e=()=>{n(pt(window.location.hash))};return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[n]),(0,_.useEffect)(()=>{let n=eT(pt(window.location.hash));n.replaceTo&&mt(n.replaceTo),n.page!==e&&t(n.page)},[e]),{page:e,setPageState:t,navigateToPage:(e,n)=>{ht(n?`${e}/${n}`:e),t(e)}}}var iT=15e3;function aT(e,t,n){return typeof e?.message==`string`&&e.message.trim()?e.message:typeof e?.error==`string`&&e.error.trim()?e.error:n(t)}function oT(e){return(e instanceof DOMException||e instanceof Error)&&e.name===`AbortError`}async function sT(e,t={}){let{fetchFn:n=fetch,timeoutMs:r=iT,formatFailure:i=e=>`Failed to stop proxy (HTTP ${e}).`,mode:a=`standalone`}=t,o;try{o=await n(`${e}${a===`client`?`/api/machine/disconnect`:`/api/stop`}`,{method:`POST`,...a===`client`?{headers:{"Content-Type":`application/json`},body:`{}`}:{},signal:AbortSignal.timeout(r)})}catch(e){return oT(e),{accepted:!0}}let s=await o.json().catch(()=>null);return!o.ok||s?.success===!1?{accepted:!1,message:aT(s,o.status,i)}:{accepted:!0}}var cT={dashboard:`nav.dashboard`,startup:`nav.startup`,providers:`nav.providers`,models:`nav.models`,subagents:`nav.subagents`,logs:`nav.logs`,usage:`nav.usage`,storage:`nav.storage`,remote:`nav.remote`,"codex-set":`nav.codexSet`,integrations:`nav.integrations`},lT=``,uT=Rb(lT);Px(uT),eS();var dT=`ocx-theme`,fT=[{id:`dashboard`,tkey:`nav.dashboard`,Icon:ee},{id:`codex-set`,tkey:`nav.codexSet`,Icon:Oe},{id:`providers`,tkey:`nav.providers`,Icon:te},{id:`models`,tkey:`nav.models`,Icon:ne},{id:`subagents`,tkey:`nav.subagents`,Icon:Z},{id:`logs`,tkey:`nav.logs`,Icon:re},{id:`usage`,tkey:`nav.usage`,Icon:oe},{id:`storage`,tkey:`nav.storage`,Icon:se},{id:`remote`,tkey:`nav.remote`,Icon:Pe},{id:`integrations`,tkey:`nav.integrations`,Icon:Fe}],pT={light:Me,dark:Ne,system:Pe},mT={light:`theme.light`,dark:`theme.dark`,system:`theme.system`};function hT(e){if(!e||typeof e!=`object`||!(`version`in e))return null;let t=e.version;return typeof t==`string`&&t.length>0?t:null}function gT(){let e=localStorage.getItem(dT);return e===`light`||e===`dark`?e:`system`}function _T(){let{page:e,navigateToPage:t}=rT(),[n,r]=(0,_.useState)(gg);(0,_.useEffect)(()=>{let e=()=>r(gg());return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]);let[i,a]=(0,_.useState)(gT),{locale:o,setLocale:s}=ut(),c=Q(),[l,u]=(0,_.useState)(uT),[d,f]=(0,_.useState)(()=>!Mb()),[p,m]=(0,_.useState)(!1),[h,g]=(0,_.useState)(()=>Rx(`shared`)),[v,y]=(0,_.useState)(0),[b,x]=(0,_.useState)(!1);(0,_.useEffect)(()=>{let e=e=>{e.detail?.plane===`shared`&&!Rx(`shared`)&&g(!1)};return window.addEventListener(hx,e),()=>window.removeEventListener(hx,e)},[]),(0,_.useEffect)(()=>{let e=new AbortController;return Hb(lT,e.signal).then(async t=>{if(Px(t),u(t),t.connected&&!Rx(`shared`))try{let n=await fetch(t.shared.bootstrapPath,{cache:`no-store`,signal:AbortSignal.any([e.signal,AbortSignal.timeout(5e3)])});n.ok&&Ux(`shared`,await n.text())}catch{}e.signal.aborted||(g(Rx(`shared`)),m(!1),f(!0))}).catch(()=>{e.signal.aborted||(m(!0),f(!0))}),()=>e.abort()},[]);let S=Vb(`machine`,l),C=Vb(`shared`,l),[w,T]=(0,_.useState)(!1),E=(0,_.useRef)(null),D=(0,_.useRef)(null),O=(0,_.useRef)(!1);(0,_.useEffect)(()=>{let e=()=>T(!1);return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]),(0,_.useEffect)(()=>{let e=document.documentElement;i===`system`?(e.removeAttribute(`data-theme`),localStorage.removeItem(dT)):(e.setAttribute(`data-theme`,i),localStorage.setItem(dT,i))},[i]);let k=K(`app-healthz:${S}`,[S,d],async e=>{let t=await fetch(`${S}/healthz`,{signal:e});return t.ok?hT(await t.json()):null},{pollMs:3e4,enabled:d}),A=()=>a(e=>e===`light`?`dark`:e===`dark`?`system`:`light`),j=pT[i],M=k.data??`2.53.0-preview.20260913`,[N,P]=(0,_.useState)(!1);(0,_.useEffect)(()=>{if(!w)return;let e=e=>{e.key===`Escape`&&T(!1)};window.addEventListener(`keydown`,e);let t=document.body.style.overflow;return document.body.style.overflow=`hidden`,()=>{window.removeEventListener(`keydown`,e),document.body.style.overflow=t}},[w]),(0,_.useEffect)(()=>{if(w){O.current=!0;let e=setTimeout(()=>D.current?.focus(),200);return()=>clearTimeout(e)}O.current&&(O.current=!1,E.current?.focus())},[w]),(0,_.useEffect)(()=>{let e=window.matchMedia(`(min-width: 761px)`),t=()=>{e.matches&&T(!1)};return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]);let[F,I]=(0,_.useState)(0),{restarting:L,restart:R}=Xd(C,{onSettled:()=>I(e=>e+1)}),z=async()=>{if(!confirm(c(l.connected?`connection.disconnectConfirm`:`dash.stopConfirm`)))return;P(!0);let e=await sT(S,{formatFailure:e=>c(`dash.stopFailed`,{status:String(e)}),mode:l.connected?`client`:`standalone`});e.accepted||(P(!1),alert(e.message))},B=async()=>{if(b)return;x(!0);let e=await zx(`shared`);x(!1),e?g(!1):alert(c(`connection.sessionLogoutFailed`))},V=(0,Y.jsxs)(`button`,{type:`button`,className:`brand brand-home`,onClick:()=>{t(`dashboard`),T(!1)},"aria-label":c(`nav.goHome`),title:c(`nav.goHome`),...e===`dashboard`?{"aria-current":`page`}:{},children:[(0,Y.jsx)(`span`,{className:`brand-logo`,role:`img`,"aria-label":c(`app.logoAria`)}),(0,Y.jsx)(`span`,{className:`name`,children:`opencodex`}),(0,Y.jsxs)(`span`,{className:`ver`,title:M,children:[`v`,M]})]});return(0,Y.jsxs)(`div`,{className:`app`,children:[(0,Y.jsxs)(`header`,{className:`mobile-topbar`,inert:w,children:[(0,Y.jsx)(`button`,{ref:E,type:`button`,className:`menu-toggle`,onClick:()=>T(e=>!e),"aria-expanded":w,"aria-controls":`app-sidebar`,"aria-label":c(w?`nav.closeMenu`:`nav.openMenu`),title:c(w?`nav.closeMenu`:`nav.openMenu`),children:(0,Y.jsx)(ie,{})}),V,(0,Y.jsxs)(`div`,{className:`mobile-topbar-actions`,children:[l.connected&&h&&(0,Y.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:()=>{B()},disabled:b,"aria-label":c(b?`connection.sessionLoggingOut`:`connection.sessionLogout`),title:c(`connection.sessionLogout`),children:(0,Y.jsx)(le,{})}),(0,Y.jsx)(`button`,{type:`button`,className:`sidebar-orb sidebar-orb--danger`,onClick:z,disabled:N,"aria-label":c(l.connected?`connection.disconnect`:`dash.stop`),title:c(l.connected?`connection.disconnect`:`dash.stop`),children:(0,Y.jsx)(Te,{})}),(0,Y.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:()=>{R()},disabled:L,"aria-label":c(`dash.codexRestart`),title:c(`dash.codexRestart`),children:(0,Y.jsx)(de,{})})]})]}),w&&(0,Y.jsx)(`div`,{className:`drawer-scrim`,onClick:()=>T(!1),"aria-hidden":`true`}),(0,Y.jsxs)(`aside`,{id:`app-sidebar`,className:`sidebar${w?` open`:``}`,ref:D,tabIndex:-1,children:[(0,Y.jsxs)(`div`,{className:`drawer-head`,children:[V,(0,Y.jsx)(`button`,{type:`button`,className:`menu-toggle drawer-close`,onClick:()=>T(!1),"aria-label":c(`nav.closeMenu`),title:c(`nav.closeMenu`),children:(0,Y.jsx)(le,{})})]}),(0,Y.jsx)(`nav`,{children:fT.map(n=>{let{id:r,tkey:i,Icon:a}=n,o=r===e;return(0,Y.jsx)(`div`,{className:`nav-entry`,children:(0,Y.jsxs)(`button`,{type:`button`,className:`nav-item${o?` active`:``}`,"data-page":r,onClick:()=>{t(r),T(!1)},"aria-current":o?`page`:void 0,children:[(0,Y.jsx)(a,{}),` `,c(i)]})},r)})}),(0,Y.jsxs)(`div`,{className:`sidebar-foot`,children:[(0,Y.jsxs)(`div`,{className:`lang-toggle`,children:[(0,Y.jsx)(Fe,{"aria-hidden":!0}),(0,Y.jsx)(kt,{value:o,options:nt.map(e=>({value:e.code,label:et(e.code)})),onChange:e=>s(e),label:c(`lang.label`),placement:`right`,portal:!1,style:{flex:1,minWidth:0,width:`100%`}})]}),(0,Y.jsxs)(`button`,{type:`button`,className:`theme-toggle`,onClick:A,"aria-label":`${c(`theme.label`)}: ${c(mT[i])}`,title:`${c(`theme.label`)}: ${c(mT[i])}`,children:[(0,Y.jsx)(j,{}),` `,(0,Y.jsx)(`span`,{className:`mode`,children:c(mT[i])})]}),(0,Y.jsxs)(`div`,{className:`sidebar-action-row`,children:[(0,Y.jsx)(`span`,{className:`sidebar-action-label`,children:c(`dash.actions`)}),(0,Y.jsxs)(`div`,{className:`sidebar-action-orbs`,children:[l.connected&&h&&(0,Y.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:()=>{B()},disabled:b,"aria-label":c(b?`connection.sessionLoggingOut`:`connection.sessionLogout`),title:c(`connection.sessionLogout`),children:(0,Y.jsx)(le,{})}),(0,Y.jsx)(`button`,{type:`button`,className:`sidebar-orb sidebar-orb--danger`,onClick:z,disabled:N,"aria-label":c(N?`dash.stopping`:l.connected?`connection.disconnect`:`dash.stop`),title:c(N?`dash.stopping`:l.connected?`connection.disconnect`:`dash.stop`),children:(0,Y.jsx)(Te,{})}),(0,Y.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:()=>{R()},disabled:L,"aria-label":c(L?`dash.codexRestarting`:`dash.codexRestart`),title:c(L?`dash.codexRestarting`:`dash.codexRestart`),children:(0,Y.jsx)(de,{})})]})]}),(0,Y.jsx)(Uw,{apiBase:C,onOpenUpdate:()=>{T(!1),t(`dashboard`,`update`)}})]})]}),(0,Y.jsx)(`main`,{className:`main`,inert:w,children:(0,Y.jsx)(`div`,{className:`main-inner${e===`models`&&n===`combos`?` main-inner--combos`:``}`,children:(0,Y.jsx)(np,{pageName:c(cT[e]),title:c(`errorBoundary.title`),message:c(`errorBoundary.message`),detailsLabel:c(`errorBoundary.details`),reloadLabel:c(`errorBoundary.reload`),children:d?(0,Y.jsxs)(Y.Fragment,{children:[p&&(0,Y.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:c(`connection.machineUnavailable`)}),l.connected&&!h&&(0,Y.jsx)(qw,{target:l.shared,onConnected:()=>{g(!0),y(e=>e+1)}},`${l.shared.serverOrigin}:${l.shared.bootstrapPath}`),e===`dashboard`&&(0,Y.jsx)(si,{apiBase:C,connected:l.connected,authenticationPending:l.connected&&!h,refreshEpoch:v}),e===`startup`&&(0,Y.jsx)(Dw,{apiBase:C,machineApiBase:S,connected:l.connected}),e===`providers`&&(0,Y.jsx)(sd,{apiBase:C}),e===`models`&&(0,Y.jsx)(Dg,{apiBase:C,restartEpoch:F},C),e===`subagents`&&(0,Y.jsx)(zg,{apiBase:C},C),e===`logs`&&(0,Y.jsx)(jv,{apiBase:C}),e===`usage`&&(0,Y.jsx)(ny,{apiBase:C,connected:l.connected,apiKeyId:l.apiKeyId}),e===`storage`&&(0,Y.jsx)(jy,{apiBase:C}),e===`remote`&&(0,Y.jsx)(Rw,{apiBase:C,hubOrigin:l.shared.serverOrigin}),e===`codex-set`&&(0,Y.jsx)(bb,{apiBase:C}),e===`integrations`&&(0,Y.jsx)(mw,{apiBase:C,machineApiBase:S,connected:l.connected})]}):(0,Y.jsx)(`div`,{className:`alert`,children:c(`connection.discovering`)})},e)})})]})}g.createRoot(document.getElementById(`root`)).render((0,Y.jsx)(_.StrictMode,{children:(0,Y.jsx)(dt,{children:(0,Y.jsx)(_T,{})})}));
|
|
128
|
+
`);if(!confirm(t))return;i(!0),o(null);let a=[];for(let t of z)try{await wf(e,t.clientId,!1)}catch(e){a.push(`${t.clientId}: ${Xf(n,e)}`)}let s=!1;try{s=(await xf(e)).clients.some(JC)}catch{a.push(n(`integrations.error.stale`))}s&&a.length===0&&a.push(n(`integrations.error.stale`)),J(),i(!1),o(a.length===0?{tone:`ok`,text:n(`integrations.bulk.success`)}:{tone:`err`,text:n(`integrations.bulk.partial`,{clients:a.join(`; `)})})},ee=R[0]?.at,[te,ne]=(0,_.useState)(null),Z=()=>{I.refresh(),A.refresh(),M.refresh(),P.refresh()},re=(e,t)=>{f(n=>{let r={...n};return t?r[e]=t:delete r[e],r})},ie=async(t,r)=>{if(!te&&t.toggle){ne(t.id),re(t.id,null);try{if(t.status)await wf(e,t.status.clientId,r),J();else if(t.toggle===`claude`||t.toggle===`grok`||t.toggle===`codex`||t.toggle===`claude-desktop`){let i=await Uf(e,t.toggle,r);i.reason===`non_loopback_removed`?re(t.id,{tone:`ok`,text:n(i.changed?`integrations.native.msg.nonLoopbackRemoved`:`integrations.native.msg.nonLoopbackRemovedNoop`)}):i.reason===`non_loopback_superseded`&&re(t.id,{tone:`ok`,text:n(`integrations.native.msg.nonLoopbackSuperseded`)}),Z()}}catch(e){re(t.id,{tone:`err`,text:Xf(n,e,void 0,t.togglePath??void 0)}),(t.toggle===`claude`||t.toggle===`grok`||t.toggle===`codex`||t.toggle===`claude-desktop`)&&Z()}finally{ne(null)}}},ae=(e,t)=>{if(e.status||t||e.id===`claude`||e.toggle===null){ie(e,t);return}let n=document.activeElement;v.current=n?.tagName===`BUTTON`?n:null,m(e)},oe=async t=>{if(t.status){ne(t.id),re(t.id,null);try{await wf(e,t.status.clientId,!0,void 0,!0),J()}catch(e){throw re(t.id,{tone:`err`,text:Xf(n,e,void 0,t.togglePath??void 0)}),e}finally{ne(null)}}};return(0,Y.jsxs)(`section`,{className:`integrations-overview`,children:[(0,Y.jsxs)(`div`,{className:`integration-summary`,children:[(0,Y.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,Y.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.summary.detected`)}),(0,Y.jsx)(`strong`,{children:q.detected})]}),(0,Y.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,Y.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.summary.applied`)}),(0,Y.jsx)(`strong`,{children:q.applied})]}),(0,Y.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,Y.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.summary.stale`)}),(0,Y.jsx)(`strong`,{children:q.stale})]}),q.unknown>0&&(0,Y.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,Y.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.state.unknown`)}),(0,Y.jsx)(`strong`,{children:q.unknown})]}),(0,Y.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,Y.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.summary.lastChange`)}),(0,Y.jsx)(`strong`,{children:ee?new Date(ee).toLocaleString():n(`integrations.status.unknown`)})]}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>void X(),disabled:r||z.length===0,children:n(`integrations.summary.disableAll`)})]}),(0,Y.jsx)(`h3`,{children:n(`integrations.catalog.title`)}),(0,Y.jsx)(ZC,{row:G}),(0,Y.jsx)(`p`,{className:`page-sub`,children:n(`integrations.onboarding`)}),O.state.kind===`failed-cold`&&(0,Y.jsx)($,{tone:`err`,children:n(`integrations.error.load`)}),O.state.kind===`failed-with-stale`&&(0,Y.jsx)($,{tone:`err`,children:n(`integrations.error.stale`)}),a&&(0,Y.jsx)($,{tone:a.tone,children:a.text}),K.length===0?O.state.kind===`failed-cold`?null:(0,Y.jsx)(`p`,{className:`page-sub`,children:n(`common.loading`)}):(0,Y.jsx)(`ul`,{className:`integration-cards`,children:K.map(e=>(0,Y.jsx)(YC,{row:e,pending:te!==null,result:d[e.id]??null,onOpen:()=>ht(e.hash),onToggle:e.toggle?()=>ae(e,!(e.toggleOn??e.applied)):null,onOverwrite:e.status!==null&&e.status.state===`conflict`&&e.installed?()=>g(e):null},e.id))}),V&&B.length===0&&(0,Y.jsxs)(`div`,{className:`integration-empty`,children:[(0,Y.jsx)(`h4`,{children:n(`integrations.empty.title`)}),(0,Y.jsx)(`p`,{children:n(`integrations.empty.body`)})]}),(0,Y.jsx)(`h3`,{children:n(`integrations.rollback.title`)}),k.state.showSkeleton?(0,Y.jsx)(ep,{label:n(`integrations.rollback.title`),rows:2}):k.state.kind===`failed-cold`?(0,Y.jsxs)($,{tone:`err`,children:[n(`integrations.rollback.failed`),` `,(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void k.refresh(),children:n(`common.retry`)})]}):R.length===0?(0,Y.jsxs)(`div`,{className:`integration-empty`,children:[(0,Y.jsx)(`p`,{children:n(`integrations.rollback.empty`)}),(0,Y.jsx)(`p`,{className:`page-sub`,children:n(`integrations.rollback.emptyBody`)})]}):(0,Y.jsx)(WC,{rows:R,showClient:!0,onRestore:c,onDelete:u}),s&&(0,Y.jsx)(DC,{apiBase:e,row:s,onClose:()=>c(null),onRestored:J,onReconcile:J}),l&&(0,Y.jsx)(EC,{copy:{titleKey:`integrations.dialog.deleteEntry.title`,changesKey:`integrations.dialog.deleteEntry.changes`,breakageKey:`integrations.dialog.deleteEntry.breakage`,undoKey:`integrations.dialog.deleteEntry.undo`,confirmKey:`integrations.dialog.deleteEntry.confirm`,vars:{path:l.configPath}},onClose:()=>u(null),onConfirm:async()=>{try{await Ef(e,l.opId,void 0,l.clientId===`aside`?l.profileId:void 0)}catch(e){if(gf(e)){u(null),await k.refresh();return}throw Error(Xf(n,e),{cause:e})}u(null),await k.refresh()}}),p&&(0,Y.jsx)(EC,{copy:{...p.toggle===`claude-desktop`?qC:p.id===`codex`?KC:GC,vars:{path:p.togglePath??``}},onClose:()=>m(null),onConfirm:async()=>{await ie(p,!1),m(null)}}),h&&h.status&&(0,Y.jsx)(EC,{copy:{titleKey:`integrations.dialog.overwrite.title`,changesKey:h.status.reason===`foreign-edit`?`integrations.dialog.overwrite.changesForeign`:`integrations.dialog.overwrite.changesUnowned`,breakageKey:`integrations.dialog.overwrite.breakage`,undoKey:`integrations.dialog.overwrite.undo`,confirmKey:`integrations.dialog.overwrite.confirm`,vars:{path:h.status.configPath}},onClose:()=>g(null),onConfirm:async()=>{await oe(h),g(null)}})]})}function ZC({row:e}){let t=Q(),n=e.detailKey?t(e.detailKey,e.detailVars??void 0):null;return(0,Y.jsxs)(`div`,{className:`integration-api-keys-row`,"data-client":`keys`,"data-key-state":e.state,children:[(0,Y.jsxs)(`div`,{className:`integration-api-keys-copy`,children:[(0,Y.jsx)(`h4`,{children:t(e.labelKey)}),n&&(0,Y.jsx)(`p`,{className:`integration-meta`,children:n})]}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>ht(e.hash),children:t(`integrations.action.manageKeys`)})]})}function QC({install:e}){let t=Q();return(0,Y.jsxs)(Y.Fragment,{children:[e.plan===`free`&&(0,Y.jsx)($,{tone:`warn`,children:t(`integrations.raycast.proRequired`)}),e.plan===`unknown`&&(0,Y.jsx)(`p`,{className:`page-sub`,"data-raycast-plan":`unknown`,children:t(`integrations.raycast.planUnknown`)}),!e.aiDirPresent&&(0,Y.jsx)(`p`,{className:`page-sub`,"data-raycast-ai-dir":`absent`,children:t(`integrations.raycast.revealConfig`)})]})}function $C(e,t){return{titleKey:`integrations.dialog.overwrite.title`,changesKey:e===`foreign-edit`?`integrations.dialog.overwrite.changesForeign`:`integrations.dialog.overwrite.changesUnowned`,breakageKey:`integrations.dialog.overwrite.breakage`,undoKey:`integrations.dialog.overwrite.undo`,confirmKey:`integrations.dialog.overwrite.confirm`,vars:{path:t}}}var ew={opencode:`integrations.semantics.opencode`,pi:`integrations.semantics.pi`,omp:`integrations.semantics.omp`,hermes:`integrations.semantics.hermes`,openclaw:`integrations.semantics.openclaw`,kimi:`integrations.semantics.kimi`,gajae:`integrations.semantics.gajae`,dsh:`integrations.semantics.dsh`,mcode:`integrations.semantics.mcode`,zcode:`integrations.semantics.zcode`,prime:`integrations.semantics.prime`,aside:`integrations.semantics.aside`,raycast:`integrations.semantics.raycast`,omo:`integrations.semantics.omo`,cline:`integrations.semantics.cline`},tw={opencode:`integrations.tab.opencode`,pi:`integrations.tab.pi`,omp:`integrations.tab.omp`,hermes:`integrations.tab.hermes`,openclaw:`integrations.tab.openclaw`,kimi:`integrations.tab.kimi`,gajae:`integrations.tab.gajae`,dsh:`integrations.tab.dsh`,mcode:`integrations.tab.mcode`,zcode:`integrations.tab.zcode`,prime:`integrations.tab.prime`,aside:`integrations.tab.aside`,raycast:`integrations.tab.raycast`,omo:`integrations.tab.omo`,cline:`integrations.tab.cline`};function nw({apiBase:e,client:t,active:n=!0,profileId:r,profileLabel:i}){let a=Q(),o=r===void 0?t:`${t}:${r}`,[s,c]=(0,_.useState)(!1),[l,u]=(0,_.useState)(null),[d,f]=(0,_.useState)(null),[p,m]=(0,_.useState)(null),[h,g]=(0,_.useState)(!1),v=(0,_.useCallback)(n=>Sf(e,t,n,r),[e,t,r]),y=(0,_.useCallback)(async n=>(await Cf(e,t,n,r)).operations,[e,t,r]),b=jr(`integration-state:${e}:${o}`,[e,t,r],v,{isEmpty:()=>!1,enabled:n,sessionCacheKey:`ocx.integrations.state.v1:${e}:${o}`}),x=jr(`integration-journal:${e}:${o}`,[e,t,r],y,{isEmpty:e=>e.length===0,enabled:n,sessionCacheKey:`ocx.integrations.client-journal.v1:${e}:${o}`}),S=b.state.data??null,C=S&&(r===void 0||S.profileId===r&&typeof S.enabled==`boolean`)?S:null,w=x.state.data??[],T=()=>{b.refresh(),x.refresh()},E=async n=>{if(!(!C||s)){c(!0),u(null);try{await wf(e,t,n,void 0,void 0,r)}catch(e){u(Xf(a,e))}finally{T(),c(!1)}}},D=async()=>{if(C){u(null);try{await wf(e,t,!0,void 0,!0,r),T()}catch(e){throw u(Xf(a,e)),T(),e}}},O=()=>void E(!(C&&(r===void 0?C.state===`current`||C.state===`stale`:C.enabled)));if(!C)return(0,Y.jsx)(`section`,{className:`integration-client-page`,children:b.state.showError?(0,Y.jsx)($,{tone:`err`,children:a(`integrations.error.load`)}):(0,Y.jsx)(`p`,{className:`page-sub`,children:a(`common.loading`)})});let k=C.state===`current`||C.state===`stale`,A=r===void 0?k:C.enabled===!0,j=r!==void 0&&(b.state.showError||b.state.refreshing),M=(!C.installed||C.state===`conflict`||C.state===`unsafe`)&&!(r!==void 0&&A);return(0,Y.jsxs)(`section`,{className:`integration-client-page`,children:[(0,Y.jsxs)(`div`,{className:`integration-client-head`,children:[(0,Y.jsx)(Ab,{src:kb(t),label:a(tw[t]),size:24}),(0,Y.jsx)(`h3`,{children:i??a(tw[t])}),(0,Y.jsx)(wC,{state:C.state,installed:C.installed,id:`integration-state-${t}${r===void 0?``:`-${r}`}`}),(0,Y.jsx)(Dt,{on:A,onClick:O,disabled:M||s||j,label:a(A?`integrations.action.disable`:`integrations.action.apply`)})]}),r!==void 0&&b.state.showError&&(0,Y.jsxs)($,{tone:`err`,children:[a(`integrations.aside.loadError`),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:T,disabled:s||b.state.refreshing,children:a(`common.retry`)})]}),C.state===`stale`&&A&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>void E(!0),disabled:s,children:a(`integrations.action.refresh`)}),C.installed&&C.state===`conflict`&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-danger`,onClick:()=>g(!0),disabled:s,children:a(`integrations.action.overwrite`)}),(0,Y.jsx)(`p`,{className:`page-sub`,children:a(ew[t])}),(0,Y.jsx)(`p`,{className:`integration-path`,children:C.configPath}),C.raycast&&(0,Y.jsx)(QC,{install:C.raycast}),C.appliedAt&&(0,Y.jsxs)(`p`,{className:`integration-meta`,children:[a(`integrations.status.appliedAt`),`: `,new Date(C.appliedAt).toLocaleString()]}),C.retentionDegraded&&(0,Y.jsx)($,{tone:`err`,children:a(`integrations.retention.degraded`)}),l&&(0,Y.jsx)($,{tone:`err`,children:l}),(0,Y.jsx)(`h4`,{children:a(`integrations.rollback.title`)}),x.state.showSkeleton?(0,Y.jsx)(ep,{label:a(`integrations.rollback.title`),rows:2}):x.state.kind===`failed-cold`?(0,Y.jsxs)($,{tone:`err`,children:[a(`integrations.rollback.failed`),` `,(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void x.refresh(),children:a(`common.retry`)})]}):w.length===0?(0,Y.jsx)(`p`,{className:`page-sub`,children:a(`integrations.rollback.empty`)}):(0,Y.jsx)(WC,{rows:w,onRestore:f,onDelete:m}),d&&(0,Y.jsx)(DC,{apiBase:e,row:d,profileId:r,onClose:()=>f(null),onRestored:T,onReconcile:T}),p&&(0,Y.jsx)(EC,{copy:{titleKey:`integrations.dialog.deleteEntry.title`,changesKey:`integrations.dialog.deleteEntry.changes`,breakageKey:`integrations.dialog.deleteEntry.breakage`,undoKey:`integrations.dialog.deleteEntry.undo`,confirmKey:`integrations.dialog.deleteEntry.confirm`,vars:{path:p.configPath}},onClose:()=>m(null),onConfirm:async()=>{try{await Ef(e,p.opId,void 0,r)}catch(e){if(gf(e)){m(null),await x.refresh();return}throw Error(Xf(a,e),{cause:e})}m(null),await x.refresh()}}),h&&(0,Y.jsx)(EC,{copy:$C(C.reason,C.configPath),onClose:()=>g(!1),onConfirm:async()=>{await D(),g(!1)}})]})}function rw(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function iw(){throw new hf(502,{code:`invalid_aside_profile_response`})}async function aw(e,t){let n=await vf(await fetch(`${e}/api/client-integrations/aside/profiles`,{signal:t}));(!rw(n)||!Array.isArray(n.profiles)||typeof n.allEnabled!=`boolean`)&&iw();let r=n.profiles.map(e=>sf(e)??iw());new Set(r.map(e=>e.profileId)).size!==r.length&&iw();let i=r.filter(e=>e.enabled).length,a=r.filter(e=>e.state===`current`||e.state===`stale`).length;return(n.total!==r.length||n.enabledCount!==i||n.appliedCount!==a||n.allEnabled!==(r.length>0&&i===r.length))&&iw(),{profiles:r,allEnabled:n.allEnabled,enabledCount:i,appliedCount:a,total:r.length,...typeof n.error==`string`?{error:n.error}:{}}}async function ow(e,t){let n=await vf(await fetch(`${e}/api/client-integrations/aside/sync`,{method:`POST`,headers:{"Content-Type":`application/json`},body:`{}`,signal:t}));(!rw(n)||typeof n.ok!=`boolean`||!Array.isArray(n.results))&&iw(),n.results.some(e=>!rw(e)||e.client!==`aside`)&&iw();let r=cf(n.results)??iw();return n.ok!==r.every(e=>e.ok)&&iw(),{ok:n.ok,results:r}}function sw({apiBase:e,active:t=!0}){let n=Q(),[r,i]=(0,_.useState)(null),[a,o]=(0,_.useState)(null),s=(0,_.useRef)(!1),[c,l]=(0,_.useState)(null),[u,d]=(0,_.useState)(new Map),f=(0,_.useCallback)(t=>aw(e,t),[e]),p=jr(`aside-profiles:${e}`,[e],f,{enabled:t,isEmpty:e=>!e.error&&e.profiles.length===0,sessionCacheKey:`ocx.integrations.aside-profiles.v1:${e}`}),m=p.state.data,h=m?.profiles??[],g=p.state.showError||!!m?.error,v=a!==null||p.state.refreshing,y=e=>e.name||n(`integrations.aside.profile`,{id:e.profileId}),b=e=>d(t=>{let r=new Map(t);for(let t of e)t.ok?r.delete(t.profileId):r.set(t.profileId,Zf(n,t));return r}),x=(e,t)=>{e instanceof hf&&`results`in e.body&&e.body.results?.length?(b(e.body.results),l(n(`integrations.aside.partial`))):t===void 0?l(Xf(n,e)):d(r=>new Map(r).set(t,Xf(n,e)))},S=async(t,n)=>{if(!s.current){s.current=!0,o(n??`all`),l(null);try{let r=await wf(e,`aside`,t,void 0,void 0,n);b(r.results??(n===void 0?h.map(e=>e.profileId):[n]).map(e=>({profileId:e,ok:!0})))}catch(e){x(e,n)}finally{p.refresh(),s.current=!1,o(null)}}},C=async()=>{if(!s.current){s.current=!0,o(`sync`),l(null);try{let t=await ow(e);b(t.results),t.ok||l(n(`integrations.aside.partial`))}catch(e){x(e)}finally{p.refresh(),s.current=!1,o(null)}}};return r?(0,Y.jsxs)(`section`,{className:`integration-client-page`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,autoFocus:!0,onClick:()=>{i(null),p.refresh()},children:n(`integrations.aside.back`)}),u.has(r.profileId)&&(0,Y.jsx)($,{tone:`err`,children:(0,Y.jsx)(`span`,{className:`aside-profile-failure`,children:u.get(r.profileId)})}),(0,Y.jsx)(nw,{apiBase:e,client:`aside`,active:t,profileId:r.profileId,profileLabel:y(r)},r.profileId)]}):(0,Y.jsxs)(`section`,{className:`integration-client-page`,"aria-busy":v,children:[(0,Y.jsxs)(`div`,{className:`integration-client-head`,children:[(0,Y.jsx)(Ab,{src:kb(`aside`),label:n(`integrations.tab.aside`),size:24}),(0,Y.jsx)(`h3`,{children:n(`integrations.aside.profilesTitle`)})]}),(0,Y.jsx)(`p`,{className:`page-sub`,children:n(`integrations.aside.profilesHint`)}),(0,Y.jsxs)(`div`,{className:`aside-profile-toolbar`,children:[(0,Y.jsx)(Dt,{on:m?.allEnabled??!1,mixed:!!(m&&m.enabledCount>0&&m.enabledCount<m.total),onClick:()=>void S(!m?.allEnabled),disabled:v||g||h.length===0,label:n(`integrations.aside.all`),showLabel:!0}),(0,Y.jsx)(`span`,{className:`text-caption muted`,children:n(`integrations.aside.applied`,{count:m?.appliedCount??0,total:m?.total??0})}),(0,Y.jsx)(`button`,{type:`button`,className:`btn`,disabled:v||g||!m?.enabledCount,onClick:()=>void C(),children:n(`integrations.aside.syncNow`)})]}),c&&(0,Y.jsx)($,{tone:`err`,children:(0,Y.jsx)(`span`,{className:`aside-profile-failure`,children:c})}),[...u].filter(([e])=>!h.some(t=>t.profileId===e)).map(([e,t])=>(0,Y.jsx)($,{tone:`err`,children:(0,Y.jsxs)(`span`,{className:`aside-profile-failure`,children:[n(`integrations.aside.profile`,{id:e}),`: `,t]})},e)),g&&(0,Y.jsxs)($,{tone:`err`,children:[(0,Y.jsx)(`span`,{children:n(`integrations.aside.loadError`)}),m?.error&&(0,Y.jsx)(`span`,{className:`text-caption`,children:m.error}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>p.refresh(),disabled:v,children:n(`common.retry`)})]}),p.state.showSkeleton&&(0,Y.jsx)(ep,{label:n(`common.loading`),rows:3}),!p.state.showSkeleton&&!g&&m&&h.length===0&&(0,Y.jsx)(`p`,{className:`page-sub`,children:n(`integrations.aside.empty`)}),h.length>0&&(0,Y.jsx)(`div`,{className:`aside-profile-list`,children:h.map(e=>{let t=y(e),r=e.state===`current`||e.state===`stale`,o=e.enabled!==r||e.enabled&&e.state===`stale`,s=(!e.installed||e.state===`unsafe`||e.state===`conflict`)&&!e.enabled;return(0,Y.jsxs)(`div`,{className:`aside-profile-row`,"aria-busy":a===e.profileId,children:[(0,Y.jsxs)(`div`,{className:`aside-profile-info`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost aside-profile-name`,"aria-label":n(`integrations.aside.details`,{name:t}),onClick:()=>i(e),disabled:v||g,children:t}),(0,Y.jsxs)(`div`,{className:`aside-profile-meta`,children:[(0,Y.jsx)(`code`,{children:e.profileId}),e.current&&(0,Y.jsx)(`span`,{className:`text-caption muted`,children:n(`integrations.aside.current`)})]}),o&&(0,Y.jsx)(`span`,{className:`text-caption muted`,children:n(`integrations.aside.pending`)}),e.error&&(0,Y.jsx)(`span`,{className:`text-caption muted`,children:e.error}),u.has(e.profileId)&&(0,Y.jsx)($,{tone:`err`,children:(0,Y.jsx)(`span`,{className:`aside-profile-failure`,children:u.get(e.profileId)})})]}),(0,Y.jsxs)(`div`,{className:`aside-profile-controls`,children:[(0,Y.jsx)(wC,{state:e.state,installed:e.installed,id:`aside-profile-state-${e.profileId}`}),o&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:v||g,"aria-label":n(`integrations.aside.retry`,{name:t}),onClick:()=>void S(e.enabled,e.profileId),children:n(`common.retry`)}),(0,Y.jsx)(Dt,{on:e.enabled,onClick:()=>void S(!e.enabled,e.profileId),disabled:v||g||s,label:n(`integrations.aside.toggle`,{name:t})})]})]},e.profileId)})})]})}var cw=[{id:`overview`,hash:`integrations`,labelKey:`integrations.tab.overview`},{id:`keys`,hash:`integrations/keys`,labelKey:`integrations.tab.keys`},{id:`codex`,hash:`integrations/codex`,labelKey:`integrations.tab.codex`},{id:`claude`,hash:`integrations/claude`,labelKey:`integrations.tab.claude`},{id:`grok`,hash:`integrations/grok`,labelKey:`integrations.tab.grok`},{id:`cursor`,hash:`integrations/cursor`,labelKey:`integrations.tab.cursor`},{id:`opencode`,hash:`integrations/opencode`,labelKey:`integrations.tab.opencode`},{id:`pi`,hash:`integrations/pi`,labelKey:`integrations.tab.pi`},{id:`omp`,hash:`integrations/omp`,labelKey:`integrations.tab.omp`},{id:`hermes`,hash:`integrations/hermes`,labelKey:`integrations.tab.hermes`},{id:`openclaw`,hash:`integrations/openclaw`,labelKey:`integrations.tab.openclaw`},{id:`kimi`,hash:`integrations/kimi`,labelKey:`integrations.tab.kimi`},{id:`gajae`,hash:`integrations/gajae`,labelKey:`integrations.tab.gajae`},{id:`dsh`,hash:`integrations/dsh`,labelKey:`integrations.tab.dsh`},{id:`mcode`,hash:`integrations/mcode`,labelKey:`integrations.tab.mcode`},{id:`zcode`,hash:`integrations/zcode`,labelKey:`integrations.tab.zcode`},{id:`prime`,hash:`integrations/prime`,labelKey:`integrations.tab.prime`},{id:`aside`,hash:`integrations/aside`,labelKey:`integrations.tab.aside`},{id:`raycast`,hash:`integrations/raycast`,labelKey:`integrations.tab.raycast`},{id:`omo`,hash:`integrations/omo`,labelKey:`integrations.tab.omo`},{id:`cline`,hash:`integrations/cline`,labelKey:`integrations.tab.cline`}],lw=new Set([`opencode`,`pi`,`omp`,`hermes`,`openclaw`,`kimi`,`gajae`,`dsh`,`mcode`,`zcode`,`prime`,`aside`,`raycast`,`omo`,`cline`]);function uw(e=window.location.hash){let t=pt(e);return t===`integrations/claude/desktop`?`claude`:cw.find(e=>e.hash===t)?.id??`overview`}function dw(e){return`integrations-tab-${e}`}function fw(e){return`integrations-panel-${e}`}function pw(e){return e===`overview`||e===`keys`?null:Eb[e]??null}function mw({apiBase:e,machineApiBase:t=e,connected:n=!1}){let r=Q(),[i,a]=(0,_.useState)(uw),[o,s]=(0,_.useState)(()=>new Set([uw()])),c=(0,_.useRef)(null),[l,u]=(0,_.useState)([]),[d,f]=(0,_.useState)(!1);c.current===null&&(c.current=new Map),(0,_.useEffect)(()=>{if(!n)return;let e=new AbortController;return fetch(`${t}/api/machine/clients`,{signal:e.signal}).then(e=>e.ok?e.json():null).then(t=>{!e.signal.aborted&&Array.isArray(t?.selectedClients)&&u(t.selectedClients.filter(e=>typeof e==`string`))}).catch(()=>{}),()=>e.abort()},[n,t]);let p=async()=>{f(!0);try{await fetch(`${t}/api/machine/sync`,{method:`POST`,headers:{"Content-Type":`application/json`},body:`{}`})}finally{f(!1)}},m=e=>{a(e),s(t=>t.has(e)?t:new Set([...t,e]))};(0,_.useEffect)(()=>{let e=()=>m(uw());return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]);let h=(e,t)=>{let n=cw.find(t=>t.id===e);n&&(ht(n.hash),m(e),t&&window.requestAnimationFrame(()=>{c.current.get(e)?.focus({preventScroll:!0})}))},g=e=>{let t=cw.findIndex(e=>e.id===i),n=null;e.key===`ArrowLeft`?n=(t-1+cw.length)%cw.length:e.key===`ArrowRight`?n=(t+1)%cw.length:e.key===`Home`?n=0:e.key===`End`&&(n=cw.length-1),n!==null&&(e.preventDefault(),h(cw[n].id,!0))};return(0,Y.jsxs)(`section`,{className:`integrations-page`,children:[(0,Y.jsx)(`div`,{className:`page-head`,children:(0,Y.jsx)(`h2`,{children:r(`nav.integrations`)})}),(0,Y.jsx)(`p`,{className:`page-sub`,children:r(`integrations.subtitle`)}),n&&(0,Y.jsxs)(`section`,{className:`notice`,"aria-label":r(`connection.clients.title`),children:[(0,Y.jsx)(`strong`,{children:r(`connection.clients.title`)}),(0,Y.jsx)(`span`,{children:l.length>0?l.join(`, `):r(`connection.clients.none`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:d,onClick:()=>void p(),children:r(d?`connection.clients.syncing`:`connection.clients.sync`)})]}),(0,Y.jsx)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":r(`integrations.tabsLabel`),children:cw.map(e=>(0,Y.jsxs)(`button`,{ref:t=>{t?c.current.set(e.id,t):c.current.delete(e.id)},type:`button`,role:`tab`,id:dw(e.id),"aria-selected":i===e.id,"aria-controls":fw(e.id),tabIndex:i===e.id?0:-1,className:`page-tab${i===e.id?` page-tab--active`:``}`,onClick:()=>h(e.id,!0),onKeyDown:g,children:[pw(e.id)&&(0,Y.jsx)(Ab,{src:pw(e.id),label:r(e.labelKey),size:14}),r(e.labelKey)]},e.id))}),cw.map(t=>{if(!o.has(t.id))return null;let n=i===t.id;return(0,Y.jsxs)(`div`,{role:`tabpanel`,id:fw(t.id),"aria-labelledby":dw(t.id),hidden:!n,children:[t.id===`overview`&&(0,Y.jsx)(XC,{apiBase:e,active:n}),t.id===`keys`&&(0,Y.jsx)(xS,{apiBase:e,active:n}),t.id===`codex`&&(0,Y.jsxs)(`section`,{className:`integration-native-page`,"aria-labelledby":`codex-integration-title`,children:[(0,Y.jsx)(`h3`,{id:`codex-integration-title`,children:r(`integrations.codex.title`)}),(0,Y.jsx)(`p`,{children:r(`integrations.codex.body`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>ht(`startup`),children:r(`integrations.codex.openService`)})]}),t.id===`claude`&&(0,Y.jsx)(dC,{apiBase:e,active:n}),t.id===`grok`&&(0,Y.jsx)(_C,{apiBase:e,active:n}),t.id===`cursor`&&(0,Y.jsx)(xC,{apiBase:e,active:n}),lw.has(t.id)&&(t.id===`aside`?(0,Y.jsx)(sw,{apiBase:e,active:n}):(0,Y.jsx)(nw,{apiBase:e,client:t.id,active:n}))]},t.id)})]})}function hw(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.supported==`boolean`&&typeof t.installed==`boolean`&&typeof t.running==`boolean`&&typeof t.stale==`boolean`&&typeof t.summary==`string`}var gw={native:`startup.status.native`,protected:`startup.status.protected`,"at-risk":`startup.status.atRisk`},_w={native:`startup.summary.native`,protected:`startup.summary.protected`,"at-risk":`startup.summary.atRisk`},vw={service:`startup.protection.service`,shim:`startup.protection.shim`,none:`startup.protection.none`};function yw({ok:e,yes:t,no:n}){return(0,Y.jsx)(`span`,{className:`badge ${e?`badge-green`:`badge-amber`}`,children:e?t:n})}function bw({failed:e,data:t}){let{t:n}=ut(),r=e?`startup-hero--risk`:t.status===`protected`?`startup-hero--safe`:t.status===`at-risk`?`startup-hero--risk`:`startup-hero--native`,i=e||t.status===`at-risk`?_e:ce,a=t.routingKind===`opencodex-local`?`startup.routing.proxy`:t.routingKind===`custom-local`?`startup.routing.customLocal`:t.routingKind===`custom-remote`?`startup.routing.customRemote`:t.routingKind===`unknown`?`startup.routing.unknown`:`startup.routing.native`;return(0,Y.jsx)(Y.Fragment,{children:(0,Y.jsxs)(`section`,{className:`panel startup-hero ${r}`,"aria-live":`polite`,children:[(0,Y.jsx)(`div`,{className:`startup-hero-icon`,children:(0,Y.jsx)(i,{})}),(0,Y.jsxs)(`div`,{className:`startup-hero-copy`,children:[(0,Y.jsx)(`span`,{className:`badge ${e||t.status===`at-risk`?`badge-amber`:`badge-green`}`,children:n(e?`startup.status.atRisk`:gw[t.status])}),(0,Y.jsx)(`h3`,{children:n(e?`startup.error`:_w[t.status])}),(0,Y.jsx)(`p`,{children:e?n(`startup.staleData`):t.status===`at-risk`?n(Mr(t)):n(`startup.safeDetail`)}),(0,Y.jsxs)(`p`,{className:`muted startup-state-line`,children:[n(a),` · `,n(vw[t.protection]),` · `,n(t.autostartEnabled?`startup.enabled`:`startup.disabled`)]}),(0,Y.jsx)(`p`,{className:`muted text-label`,children:n(`startup.subtitle`)})]})]})})}function xw({data:e,failed:t,loading:n=!1,installBusy:r,installResult:i,onInstall:a}){let{t:o}=ut(),s=e.serviceSupported&&e.serviceInstalled&&e.serviceStale&&!e.serviceConflict,c=e.shimInstalled&&!e.shimHealthy,l=r!==null||t||n;return(0,Y.jsxs)(`section`,{className:`panel startup-details`,children:[(0,Y.jsxs)(`div`,{className:`panel-head`,children:[(0,Y.jsx)(`h3`,{className:`panel-title`,children:o(`startup.details`)}),(0,Y.jsx)(`span`,{className:`muted mono`,children:e.platform})]}),(0,Y.jsxs)(`div`,{className:`startup-detail-row`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`strong`,{children:o(`startup.service`)}),(0,Y.jsx)(`span`,{children:o(`startup.serviceHint`)})]}),(0,Y.jsxs)(`div`,{className:`startup-detail-actions`,children:[(0,Y.jsx)(yw,{ok:e.serviceViable,yes:o(`startup.viable`),no:o(e.serviceConflict?`startup.conflict`:e.serviceStale?`startup.stale`:e.serviceInstalled?`startup.unhealthy`:e.serviceSupported?`startup.notInstalled`:`startup.unsupported`)}),e.serviceSupported&&!e.serviceInstalled&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,"aria-label":`${o(`startup.service`)} - ${o(`startup.install`)}`,disabled:l,onClick:()=>a(`install-service`),children:o(r===`install-service`?`startup.installing`:`startup.install`)}),s&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,"aria-label":`${o(`startup.service`)} - ${o(`startup.repair`)}`,disabled:l,onClick:()=>a(`install-service`,{repair:!0}),children:o(r===`install-service`?`startup.repairing`:`startup.repair`)})]})]}),(0,Y.jsxs)(`div`,{className:`startup-detail-row`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`strong`,{children:o(`startup.shim`)}),(0,Y.jsx)(`span`,{children:o(`startup.shimHint`)})]}),(0,Y.jsxs)(`div`,{className:`startup-detail-actions`,children:[(0,Y.jsx)(yw,{ok:e.shimHealthy&&e.autostartEnabled,yes:o(e.shimCoverage===`cli-only`?`startup.cliOnly`:`startup.healthy`),no:o(e.shimInstalled?e.shimHealthy&&!e.autostartEnabled?`startup.installedDisabled`:`startup.stale`:`startup.notInstalled`)}),!e.shimInstalled&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,"aria-label":`${o(`startup.shim`)} - ${o(`startup.install`)}`,disabled:l,onClick:()=>a(`install-shim`),children:o(r===`install-shim`?`startup.installing`:`startup.install`)}),c&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,"aria-label":`${o(`startup.shim`)} - ${o(`startup.repair`)}`,disabled:l,onClick:()=>a(`install-shim`,{repair:!0}),children:o(r===`install-shim`?`startup.repairing`:`startup.repair`)})]})]}),i&&(0,Y.jsx)(`div`,{className:`notice ${i.kind===`success`?`notice-ok`:`notice-warn`} startup-action-notice`,role:`status`,"aria-live":`polite`,children:i.kind===`success`?i.action===`install-service`?o(i.repair?`startup.serviceRepaired`:`startup.serviceInstalled`):o(i.repair?`startup.shimRepaired`:`startup.shimInstalled`):`${o(`startup.installFailed`)} ${i.detail??``}`})]})}function Sw({tray:e,trayLoading:t,trayError:n,trayBusy:r,onTrayAction:i}){let{t:a}=ut();return(0,Y.jsxs)(`section`,{className:`panel startup-actions`,children:[(0,Y.jsxs)(`div`,{className:`panel-head`,children:[(0,Y.jsx)(`h3`,{className:`panel-title`,children:a(`startup.tray.title`)}),(0,Y.jsx)(Te,{})]}),(0,Y.jsx)(`p`,{className:`muted`,children:a(`startup.tray.hint`)}),(0,Y.jsxs)(`div`,{className:`startup-detail-row`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`strong`,{children:a(`startup.tray.login`)}),(0,Y.jsx)(`span`,{children:a(`startup.tray.notProtection`)})]}),t||n||!e?(0,Y.jsx)(`span`,{className:`badge badge-amber`,children:a(t?`startup.tray.loading`:`startup.tray.unavailable`)}):(0,Y.jsx)(yw,{ok:e.running&&!e.stale,yes:a(`startup.tray.running`),no:a(e.stale?`startup.tray.stale`:e.installed?`startup.tray.stopped`:`startup.tray.notInstalled`)})]}),(0,Y.jsxs)(`div`,{className:`startup-tray-buttons`,children:[!t&&!n&&e&&!e.installed&&!e.stale&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:r,onClick:()=>i(`install`),children:a(`startup.tray.install`)}),!t&&!n&&e?.installed&&!e.stale&&!e.running&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:r,onClick:()=>i(`start`),children:a(`startup.tray.start`)}),!t&&!n&&e?.running&&!e.stale&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:r,onClick:()=>i(`stop`),children:a(`startup.tray.stop`)}),!t&&!n&&e&&(e.installed||e.stale)&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-danger`,disabled:r,onClick:()=>{window.confirm(a(`startup.tray.uninstall`))&&i(`uninstall`)},children:a(`startup.tray.uninstall`)})]}),(n||e?.stale)&&(0,Y.jsx)(`div`,{className:`notice notice-warn startup-tray-error`,role:`alert`,children:a(`startup.tray.error`)})]})}function Cw({data:e,copied:t,onCopy:n}){let{t:r}=ut(),i=e.serviceInstalled&&!e.serviceConflict?e.commands.repairService:e.commands.installService;return(0,Y.jsxs)(`section`,{className:`panel startup-actions`,children:[(0,Y.jsxs)(`div`,{className:`panel-head`,children:[(0,Y.jsx)(`h3`,{className:`panel-title`,children:r(`startup.recovery`)}),(0,Y.jsx)(ae,{})]}),(0,Y.jsxs)(`details`,{className:`startup-recovery-details`,open:e.status!==`protected`,children:[(0,Y.jsx)(`summary`,{className:`muted`,children:r(`startup.recoveryHint`)}),(0,Y.jsxs)(`div`,{className:`startup-command-list`,children:[e.serviceSupported&&(0,Y.jsxs)(`div`,{className:`startup-command-row`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`strong`,{children:r(`startup.command.service`)}),(0,Y.jsx)(`code`,{children:i})]}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>n(i),children:r(t===i?`startup.copied`:`startup.copy`)})]}),(0,Y.jsxs)(`div`,{className:`startup-command-row`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`strong`,{children:r(`startup.command.shim`)}),(0,Y.jsx)(`code`,{children:e.commands.installShim})]}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>n(e.commands.installShim),children:t===e.commands.installShim?r(`startup.copied`):r(`startup.copy`)})]}),(0,Y.jsxs)(`div`,{className:`startup-command-row`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`strong`,{children:r(`startup.command.native`)}),(0,Y.jsx)(`code`,{children:e.commands.restoreNative})]}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>n(e.commands.restoreNative),children:t===e.commands.restoreNative?r(`startup.copied`):r(`startup.copy`)})]})]}),e.status===`at-risk`&&(0,Y.jsxs)(`div`,{className:`notice notice-warn startup-action-notice`,role:`alert`,children:[(0,Y.jsx)(Te,{}),` `,r(`startup.recommended`,{cmd:e.recommendedCommand??e.commands.installService})]})]})]})}var ww=`ocx.startup.page.v1:`;function Tw(e,t){let n=t===`win32`?`; `:` && `;return e.join(n)}function Ew(e,t,n){if(!e)return{warning:null,fix:null};let r=!!e.catalogClamp?.active,i=!!e.newerAvailable,a=(r?e.catalogClamp?.runtimeVersion:e.version)??e.version??`unknown`,o=(e.catalogClamp?.removedEfforts??[]).join(`, `),s=Tw([`ocx doctor --fix-codex-runtime`,`ocx sync`],n);return r?{warning:o?t(`startup.codexRuntime.clampHiddenWithEfforts`,{version:a,efforts:o}):t(`startup.codexRuntime.clampHidden`,{version:a}),fix:i?s:`ocx sync`}:i?{warning:t(`startup.codexRuntime.olderBinary`,{version:a}),fix:s}:{warning:null,fix:null}}function Dw({apiBase:e,machineApiBase:t=e,connected:n=!1}){let{t:r}=ut(),i=`${ww}${e}`,a=(0,_.useMemo)(()=>Tr(i),[i]),o=`startup-page:${e}`,[s,c]=(0,_.useState)(null),[l,u]=(0,_.useState)(()=>a?.tray??null),[d,f]=(0,_.useState)(()=>!a?.data),[p,m]=(0,_.useState)(!1),[h,g]=(0,_.useState)(!1),[v,y]=(0,_.useState)(null),[b,x]=(0,_.useState)(null),[S,C]=(0,_.useState)(()=>a?.warning??null),[w,T]=(0,_.useState)(()=>a?.fix??null),[E,D]=(0,_.useState)(()=>!a?.data),O=(0,_.useRef)(!!a?.data),k=(0,_.useRef)(0),[A,j]=(0,_.useState)(null),[M,N]=(0,_.useState)(!1);(0,_.useEffect)(()=>{if(!n)return;let e=new AbortController;return fetch(`${t}/api/machine/shim`,{signal:e.signal}).then(e=>e.ok?e.json():null).then(t=>{e.signal.aborted||j(t)}).catch(()=>{e.signal.aborted||j(null)}),()=>e.abort()},[n,t]);let P=async e=>{N(!0);try{let n=await fetch(`${t}/api/machine/shim`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:e})});if(n.ok){let e=await n.json();j(e.shim??null)}}finally{N(!1)}};(0,_.useEffect)(()=>()=>{k.current+=1},[e]);let F=(0,_.useCallback)(async t=>{let n=++k.current,a=O.current;a||(f(!0),D(!0));try{let a=fetch(`${e}/api/settings`,{signal:t}).then(async e=>e.ok?await e.json():null).catch(()=>null),o=await fetch(`${e}/api/startup-health`,{signal:t});if(!o.ok)throw Error(`fetch failed`);let s=await o.json();x(e=>e?.kind===`error`&&(s.status===`native`&&e.forLocalRouting===!0||(e.action===`install-service`?s.serviceViable:s.shimInstalled&&s.shimHealthy))?null:e),O.current=!0;let c=Tr(i);kr(i,{data:s,warning:c?.warning??null,fix:c?.fix??null,tray:c?.tray??null});let l=s.platform===`win32`?fetch(`${e}/api/windows-tray`,{signal:t}).then(async e=>{if(!e.ok)throw Error(`tray status failed`);let t=await e.json();if(!hw(t))throw Error(`invalid tray status`);return{tray:t,error:!1}}).catch(()=>({tray:null,error:!0})):Promise.resolve({tray:null,error:!1});return Promise.all([a,l]).then(([e,a])=>{if(t.aborted||n!==k.current)return;let o=s.platform===`win32`?a.tray:null;if(s.platform===`win32`?(u(o),g(a.error)):(u(null),g(!1)),f(!1),D(!1),e){let t=Ew(e.codexRuntime,r,s.platform);C(t.warning),T(t.fix),kr(i,{data:s,warning:t.warning,fix:t.fix,tray:o});return}let c=Tr(i);kr(i,{data:s,warning:c?.warning??null,fix:c?.fix??null,tray:o})}),s}catch(e){throw t.aborted?e:(a||(u(null),g(!0),C(null),T(null)),D(!1),f(!1),e)}},[e,i,r]),I=jr(o,[e],F,{isEmpty:()=>!1,initialData:a?.data??void 0}),L=I.state,R=I.refresh,z=L.data??a?.data??null,B=L.refreshing,V=!!z?.diagnosticStale||L.showError;(0,_.useEffect)(()=>{if(!z?.diagnosticStale)return;let e=window.setTimeout(R,2e3);return()=>window.clearTimeout(e)},[z,R]);let H=async e=>{try{await navigator.clipboard.writeText(e),c(e),window.setTimeout(()=>c(t=>t===e?null:t),1600)}catch{c(null)}},U=async t=>{m(!0),g(!1);try{let n=await fetch(`${e}/api/windows-tray`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:t})});if(!n.ok)throw Error(`tray action failed`);let r=await n.json();if(!hw(r.status))throw Error(`invalid tray action status`);u(r.status),g(!1)}catch{u(null),g(!0)}finally{m(!1)}},W=async(t,n)=>{y(t),x(null);try{let r=await fetch(`${e}/api/startup-action`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:t,repair:n?.repair===!0})});if(!r.ok){let e=await r.json().catch(()=>null);throw Error(typeof e?.error==`string`?e.error:`installation failed`)}x({kind:`success`,action:t,repair:n?.repair===!0}),R()}catch(e){x({kind:`error`,action:t,repair:n?.repair===!0,detail:e instanceof Error?e.message:String(e),forLocalRouting:z?.localRoutingDependency===!0})}finally{y(null)}};return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{className:`page-head`,children:[(0,Y.jsx)(`h2`,{children:r(`startup.title`)}),(0,Y.jsx)(`div`,{className:`startup-page-head-actions`,children:(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>R(),disabled:B,children:[(0,Y.jsx)(de,{}),` `,r(`startup.refresh`)]})})]}),n&&(0,Y.jsxs)(`section`,{className:`notice startup-page-notice`,"aria-label":r(`connection.machine.title`),children:[(0,Y.jsx)(`strong`,{children:r(`connection.machine.title`)}),(0,Y.jsx)(`span`,{children:A?.healthy?r(`connection.machine.shimHealthy`):r(`connection.machine.shimNeedsAttention`)}),(0,Y.jsxs)(`div`,{className:`startup-page-head-actions`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:M,onClick:()=>void P(`repair`),children:r(`connection.machine.repairShim`)}),A?.installed&&(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:M,onClick:()=>void P(`uninstall`),children:r(`connection.machine.removeShim`)})]})]}),L.showSkeleton&&!z?(0,Y.jsx)(ep,{label:r(`startup.loading`),rows:5}):L.kind===`failed-cold`?(0,Y.jsxs)(`div`,{className:`startup-page-notice`,children:[(0,Y.jsx)($,{tone:`err`,children:L.error instanceof Error?L.error.message:r(`startup.error`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>R(),children:r(`common.retry`)})]}):z?(0,Y.jsxs)(Y.Fragment,{children:[L.showError&&(0,Y.jsx)($,{tone:`err`,children:r(`startup.error`)}),V&&(0,Y.jsx)(`div`,{className:`notice notice-warn startup-page-notice`,role:`alert`,children:r(`startup.staleData`)}),(E||S)&&(0,Y.jsx)(`div`,{className:`startup-runtime-notice-slot${E&&!S?` startup-runtime-notice-slot--pending`:``}`,"aria-hidden":E&&!S?!0:void 0,children:S&&(0,Y.jsxs)(`div`,{className:`notice notice-warn startup-page-notice startup-runtime-notice`,role:`status`,children:[(0,Y.jsx)(`p`,{className:`startup-runtime-notice__text`,children:S}),w&&(0,Y.jsxs)(`div`,{className:`startup-runtime-notice__fix`,children:[(0,Y.jsx)(`code`,{children:w}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void H(w),children:r(s===w?`startup.copied`:`startup.copy`)})]})]})}),(0,Y.jsx)(bw,{failed:V,data:z}),(0,Y.jsx)(xw,{data:z,failed:V,loading:B,installBusy:v,installResult:b,onInstall:(e,t)=>{W(e,t)}}),z.platform===`win32`&&(0,Y.jsx)(Sw,{tray:l,trayLoading:d,trayError:h,trayBusy:p,onTrayAction:e=>{U(e)}}),(0,Y.jsx)(Cw,{data:z,copied:s,onCopy:e=>{H(e)}})]}):null]})}function Ow(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function kw(e){return`'${e.replace(/'/g,`''`)}'`}function Aw(e,t){return{posix:`printf '%s\\n' ${Ow(e)} | ocx remote-workspace pair ${Ow(t)} --pairing-code-stdin --root "$PWD" && ocx remote-workspace agent`,powershell:`$pairingCode = ${kw(e)}; $pairingCode | ocx remote-workspace pair ${kw(t)} --pairing-code-stdin --root (Get-Location).Path; if ($LASTEXITCODE -eq 0) { ocx remote-workspace agent }`}}var jw=[`codex`,`claude`,`pi`],Mw={codex:`Codex`,claude:`Claude Code`,pi:`Pi`},Nw={starting:`remote.status.starting`,ready:`remote.status.ready`,running:`remote.status.running`,waiting_for_executor:`remote.status.waiting`,failed:`remote.status.failed`,stopped:`remote.status.stopped`},Pw={status:`remote.event.status`,tool:`remote.event.tool`,error:`remote.event.error`};function Fw(e){return e===`codex`||e===`claude`||e===`pi`}function Iw(e){return e===`read-only`||e===`workspace`}async function Lw(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}function Rw({apiBase:e,hubOrigin:t}){let n=Q(),r=K(`remote-workspace:${e}`,[e],async t=>await It(await fetch(`${e}/api/remote-workspace`,{signal:t,cache:`no-store`}),n(`remote.loadFailed`)),{pollMs:3e3,deadlineMs:1e4}),i=r.data,[a,o]=(0,_.useState)(``),[s,c]=(0,_.useState)(``),[l,u]=(0,_.useState)(`codex`),[d,f]=(0,_.useState)(`read-only`),[p,m]=(0,_.useState)(``),[h,g]=(0,_.useState)(null),[v,y]=(0,_.useState)(null),[b,x]=(0,_.useState)({}),[S,C]=(0,_.useState)(null),[w,T]=(0,_.useState)(!1),[E,D]=(0,_.useState)(!1),O=(0,_.useRef)(null),[k,A]=(0,_.useState)(null),[j,M]=(0,_.useState)(null),N=i?.devices??[],P=N.find(e=>e.id===a)??N.find(e=>e.online)??N[0]??null,F=P?.roots.find(e=>e.id===s)??P?.roots[0]??null,I=d===`workspace`&&(P?.capabilities.includes(`workspace.exec`)??!1),L=P&&!P.capabilities.includes(`workspace.exec`)?n(`remote.access.workspaceFilesOnly`):n(`remote.access.workspace`),R=jw.filter(e=>i?.runtimes?.[e]?.available),z=R.includes(l)?l:R[0]??l,B=i?.sessions??[],V=[...B].reverse().find(e=>e.status!==`stopped`),H=(B.find(e=>e.id===p)??(h?.id===p?h:null)??V??h)?.id,U=B.find(e=>e.id===H),W=h?.id===H?h:null,G=(W&&(!U||(W.events.at(-1)?.sequence??0)>(U.events.at(-1)?.sequence??0))?W:U)??V??h,q=b[G?.id??``]??``,J=e=>{let t=G?.id;t&&x(n=>({...n,[t]:typeof e==`function`?e(n[t]??``):e}))},X=!!(i&&!r.lastAttemptOk),ee=!!(G&&q.trim()&&S===null&&!w&&!E&&!X&&G.status!==`running`&&G.status!==`starting`&&G.status!==`stopped`&&(G.status!==`failed`||G.resumable!==!1)&&!(G.status===`waiting_for_executor`&&!N.find(e=>e.id===G.deviceId)?.online)),te=(0,_.useMemo)(()=>v?Aw(v.code,t):{posix:``,powershell:``},[v,t]),ne=async(t,n,r)=>{let i=await It(await fetch(`${e}${t}`,n),r);if(i===void 0)throw Error(r);return i},Z=async()=>{C(`pair`),A(null);try{let e=await ne(`/api/remote-workspace/pairing`,{method:`POST`},n(`remote.requestFailed`));y(e),M(null)}catch(e){A({tone:`err`,text:e instanceof Error?e.message:n(`remote.requestFailed`)})}finally{C(null)}},re=async()=>{if(!(!P||!F)){C(`session`),A(null);try{let e=await ne(`/api/remote-workspace/sessions`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({profile:z,deviceId:P.id,rootId:F.id,accessMode:d})},n(`remote.requestFailed`));g(e),m(e.id),A({tone:`ok`,text:n(`remote.sessionStarted`)}),r.refresh()}catch(e){A({tone:`err`,text:e instanceof Error?e.message:n(`remote.requestFailed`)})}finally{C(null)}}},ie=async()=>{if(!G||!ee)return;let t=G,i=q;T(!0),A(null);let a;try{let o=await fetch(`${e}/api/remote-workspace/sessions/${t.id}/prompt`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({prompt:i})});a=o.status;let s=await It(o,n(`remote.requestFailed`));if(!s)throw Error(n(`remote.requestFailed`));J(e=>e===i?``:e),O.current!==t.id&&g(s),r.refresh()}catch(e){O.current!==t.id&&(A({tone:`err`,text:a!==void 0&&a>=400&&a<500?e instanceof Error?e.message:n(`remote.requestFailed`):n(`remote.submissionUnknown`)}),r.refresh())}finally{T(!1)}},oe=async()=>{if(!G||E)return;let e=G;D(!0);try{await ne(`/api/remote-workspace/sessions/${e.id}`,{method:`DELETE`},n(`remote.requestFailed`)),O.current=e.id,g({...e,status:`stopped`}),r.refresh()}catch(e){A({tone:`err`,text:e instanceof Error?e.message:n(`remote.requestFailed`)})}finally{D(!1)}},se=async e=>{if(confirm(n(`remote.revokeConfirm`,{name:e.name}))){C(`revoke`);try{await ne(`/api/remote-workspace/devices/${e.id}`,{method:`DELETE`},n(`remote.requestFailed`)),a===e.id&&o(``),r.refresh()}catch(e){A({tone:`err`,text:e instanceof Error?e.message:n(`remote.requestFailed`)})}finally{C(null)}}},ce=async(e,t)=>{M(await Lw(t)?e:null)};return r.loading&&!i?(0,Y.jsx)(`div`,{className:`alert`,children:n(`remote.loading`)}):r.error&&!i?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)($,{tone:`err`,children:n(`remote.loadFailed`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>void r.refresh(),children:n(`common.retry`)})]}):i?.available===!1?(0,Y.jsx)($,{tone:`err`,children:n(`remote.hubRequired`)}):(0,Y.jsxs)(`section`,{className:`remote-workspace-page`,children:[(0,Y.jsxs)(`div`,{className:`page-head`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`h2`,{children:n(`remote.title`)}),(0,Y.jsx)(`p`,{className:`page-sub`,children:n(`remote.subtitle`)})]}),(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void r.refresh(),disabled:r.refreshing,children:[(0,Y.jsx)(de,{}),` `,n(`remote.refresh`)]})]}),X?(0,Y.jsx)($,{tone:`err`,children:n(`remote.loadFailed`)}):null,k?(0,Y.jsx)($,{tone:k.tone,children:k.text}):null,(0,Y.jsxs)(`div`,{className:`remote-workspace-grid`,children:[(0,Y.jsxs)(`div`,{className:`remote-workspace-column`,children:[(0,Y.jsxs)(`article`,{className:`panel panel-accent remote-pair-card`,children:[(0,Y.jsxs)(`div`,{className:`remote-panel-head`,children:[(0,Y.jsx)(`div`,{className:`remote-icon`,children:(0,Y.jsx)(je,{})}),(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`h3`,{children:n(`remote.addComputer`)}),(0,Y.jsx)(`p`,{children:n(`remote.addComputerHint`)})]})]}),(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>void Z(),disabled:S!==null,children:[(0,Y.jsx)(ue,{}),` `,n(`remote.createPairing`)]}),v?(0,Y.jsxs)(`div`,{className:`remote-pairing-result`,children:[(0,Y.jsx)(`span`,{className:`field-label`,children:n(`remote.pairingCode`)}),(0,Y.jsx)(`div`,{className:`remote-pairing-code`,children:v.code}),(0,Y.jsx)(`div`,{className:`remote-expiry`,children:n(`remote.pairingExpires`,{time:new Date(v.expiresAt).toLocaleTimeString()})}),(0,Y.jsx)(`span`,{className:`field-label`,children:n(`remote.pairingCommandPosix`)}),(0,Y.jsx)(`pre`,{children:(0,Y.jsx)(`code`,{children:te.posix})}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void ce(`posix`,te.posix),children:n(j===`posix`?`remote.copied`:`remote.copyCommand`)}),(0,Y.jsx)(`span`,{className:`field-label`,children:n(`remote.pairingCommandWindows`)}),(0,Y.jsx)(`pre`,{children:(0,Y.jsx)(`code`,{children:te.powershell})}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void ce(`powershell`,te.powershell),children:n(j===`powershell`?`remote.copied`:`remote.copyCommand`)})]}):null]}),(0,Y.jsxs)(`section`,{className:`panel remote-device-panel`,children:[(0,Y.jsxs)(`div`,{className:`remote-section-title`,children:[(0,Y.jsx)(`h3`,{children:n(`remote.devices`)}),(0,Y.jsx)(`span`,{children:N.length})]}),N.length===0?(0,Y.jsx)(`p`,{className:`remote-empty`,children:n(`remote.noDevices`)}):(0,Y.jsx)(`div`,{className:`remote-device-list`,children:N.map(e=>(0,Y.jsxs)(`div`,{className:`remote-device${P?.id===e.id?` selected`:``}`,children:[(0,Y.jsxs)(`button`,{type:`button`,className:`remote-device-main`,onClick:()=>{o(e.id),c(e.roots[0]?.id??``)},"aria-pressed":P?.id===e.id,children:[(0,Y.jsx)(`span`,{className:`remote-online-dot${e.online?` online`:``}`}),(0,Y.jsxs)(`span`,{className:`remote-device-copy`,children:[(0,Y.jsx)(`strong`,{children:e.name}),(0,Y.jsxs)(`small`,{children:[e.platform,` · `,e.online?n(`remote.online`):n(`remote.offline`),` · `,e.capabilities.includes(`workspace.exec`)?n(`remote.capability.full`):n(`remote.capability.files`)]})]})]}),(0,Y.jsx)(`button`,{type:`button`,className:`remote-revoke`,"aria-label":n(`remote.revoke`),disabled:S!==null||w||E,onClick:()=>void se(e),children:(0,Y.jsx)(me,{})})]},e.id))})]})]}),(0,Y.jsxs)(`div`,{className:`remote-workspace-column remote-session-column`,children:[(0,Y.jsxs)(`section`,{className:`panel remote-launch-panel`,children:[(0,Y.jsxs)(`div`,{className:`remote-section-title`,children:[(0,Y.jsx)(`h3`,{children:n(`remote.newSession`)}),(0,Y.jsx)(Pe,{})]}),(0,Y.jsxs)(`div`,{className:`remote-launch-fields`,children:[(0,Y.jsxs)(`label`,{children:[(0,Y.jsx)(`span`,{className:`field-label`,children:n(`remote.device`)}),(0,Y.jsx)(kt,{value:P?.id??``,options:N.map(e=>({value:e.id,label:e.name})),onChange:e=>{o(e),c(N.find(t=>t.id===e)?.roots[0]?.id??``)},label:n(`remote.device`),disabled:N.length===0})]}),(0,Y.jsxs)(`label`,{children:[(0,Y.jsx)(`span`,{className:`field-label`,children:n(`remote.folder`)}),(0,Y.jsx)(kt,{value:F?.id??``,options:(P?.roots??[]).map(e=>({value:e.id,label:e.label})),onChange:c,label:n(`remote.folder`),disabled:!P})]}),(0,Y.jsxs)(`label`,{children:[(0,Y.jsx)(`span`,{className:`field-label`,children:n(`remote.runtime`)}),(0,Y.jsx)(kt,{value:z,options:jw.map(e=>({value:e,label:i?.runtimes?.[e]?.available?Mw[e]:`${Mw[e]} · ${n(`remote.unavailable`)}`})),onChange:e=>{Fw(e)&&u(e)},label:n(`remote.runtime`)})]}),(0,Y.jsxs)(`label`,{children:[(0,Y.jsx)(`span`,{className:`field-label`,children:n(`remote.access`)}),(0,Y.jsx)(kt,{value:d,options:[{value:`read-only`,label:n(`remote.access.readOnly`)},{value:`workspace`,label:L}],onChange:e=>{Iw(e)&&f(e)},label:n(`remote.access`)})]})]}),P?(0,Y.jsxs)(`div`,{className:`remote-execution-map`,children:[(0,Y.jsxs)(`span`,{children:[(0,Y.jsx)(`strong`,{children:Mw[z]}),n(`remote.runsOnHub`)]}),(0,Y.jsxs)(`span`,{children:[(0,Y.jsx)(`strong`,{children:P.name}),n(d===`read-only`?`remote.runsReadOnly`:I?`remote.runsFilesCommands`:`remote.runsFilesOnly`)]})]}):null,d===`workspace`&&!I&&P?(0,Y.jsx)($,{tone:`err`,children:n(`remote.execUnavailable`)}):null,!i?.runtimes?.[z]?.available&&i?.runtimes?.[z]?.reason?(0,Y.jsx)(`p`,{className:`remote-runtime-reason`,children:i.runtimes[z].reason}):null,(0,Y.jsxs)(`button`,{type:`button`,className:`btn btn-primary remote-start`,onClick:()=>void re(),disabled:!P?.online||!F||!i?.runtimes?.[z]?.available||S!==null||w||E,children:[(0,Y.jsx)(ae,{}),` `,n(`remote.startSession`)]})]}),(0,Y.jsxs)(`section`,{className:`panel remote-console-panel`,children:[(0,Y.jsxs)(`div`,{className:`remote-section-title`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`h3`,{children:n(`remote.sessions`)}),G?(0,Y.jsxs)(`small`,{children:[Mw[G.profile],` · `,G.deviceName,`/`,G.rootLabel,` · `,G.accessMode===`read-only`?n(`remote.access.readOnly`):G.capabilities.includes(`workspace.exec`)?n(`remote.access.workspace`):n(`remote.access.workspaceFilesOnly`)]}):null]}),G?(0,Y.jsx)(`span`,{className:`remote-status remote-status--${G.status}`,children:n(Nw[G.status])}):null]}),B.length>1?(0,Y.jsx)(kt,{value:G?.id??``,options:B.map(e=>({value:e.id,label:`${Mw[e.profile]} · ${e.deviceName}/${e.rootLabel}`})),onChange:m,label:n(`remote.sessions`)}):null,G?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`div`,{className:`remote-events`,"aria-live":`polite`,"aria-label":n(`remote.events`),children:G.events.length===0?(0,Y.jsx)(`p`,{className:`remote-empty`,children:n(`remote.noEvents`)}):G.events.map(e=>(0,Y.jsxs)(`div`,{className:`remote-event remote-event--${e.type}`,children:[(0,Y.jsx)(`span`,{children:e.type===`assistant`?Mw[G.profile]:n(Pw[e.type])}),(0,Y.jsx)(`p`,{children:e.text})]},e.sequence))}),G.status===`failed`&&G.resumable===!1?(0,Y.jsx)($,{tone:`err`,children:n(`remote.notResumable`)}):null,(0,Y.jsxs)(`label`,{className:`remote-composer`,children:[(0,Y.jsx)(`span`,{className:`field-label`,children:n(`remote.prompt`)}),(0,Y.jsx)(`textarea`,{className:`input`,rows:4,value:q,onChange:e=>J(e.target.value),placeholder:n(`remote.promptPlaceholder`),disabled:G.status===`stopped`||G.status===`failed`&&G.resumable===!1,onKeyDown:e=>{(e.ctrlKey||e.metaKey)&&e.key===`Enter`&&(e.preventDefault(),ie())}})]}),(0,Y.jsxs)(`div`,{className:`remote-console-actions`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>void ie(),disabled:!ee,children:n(`remote.send`)}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-danger`,onClick:()=>void oe(),disabled:E||G.status===`stopped`,children:n(`remote.stop`)})]})]}):(0,Y.jsx)(`p`,{className:`remote-empty remote-empty--console`,children:n(`remote.noSessions`)})]})]})]})]})}var zw=3e5,Bw=6e5,Vw=`https://github.com/lidge-jun/opencodex`;async function Hw(e,t){let n=await fetch(e,{signal:t});return n.ok?await n.json():null}function Uw({apiBase:e,onOpenUpdate:t}){let n=Q(),[r,i]=(0,_.useState)(!1),[a,o]=(0,_.useState)(null),s=K(`sidebar-star:${e}`,[e],t=>Hw(`${e}/api/github/star`,t),{pollMs:zw}),c=K(`sidebar-update-badge:${e}`,[e],t=>Hw(`${e}/api/update/badge`,t),{pollMs:Bw}),l=s.data?.state??null,u=a!==null&&a.basedOn===l?a.state:l??`not-starred`,d=s.data?.url??Vw,f=u===`starred`,p=c.data,m=p?.updateAvailable===!0,h=p?.latestVersion??null,g=()=>window.open(d,`_blank`,`noopener,noreferrer`),v=async()=>{if(!(f||r)){if(u===`unauthenticated`){g();return}i(!0);try{let t=await fetch(`${e}/api/github/star`,{method:`POST`}),n=t.ok?await t.json():null;if(n?.ok===!0){o({state:`starred`,basedOn:l});return}n?.state&&o({state:n.state,basedOn:l}),g()}catch{g()}finally{i(!1),s.refresh()}}},y=n(f?`sidebar.starred`:u===`unauthenticated`?`sidebar.starUnauthenticated`:`sidebar.star`),b=m&&h?n(`sidebar.updateAvailable`,{version:h}):n(`sidebar.checkUpdate`);return(0,Y.jsxs)(`div`,{className:`sidebar-github-row`,children:[(0,Y.jsxs)(`a`,{className:`sidebar-link sidebar-github-link`,href:d,target:`_blank`,rel:`noreferrer`,children:[(0,Y.jsx)(we,{}),` `,n(`common.github`)]}),(0,Y.jsxs)(`div`,{className:`sidebar-github-actions`,children:[(0,Y.jsx)(`button`,{type:`button`,className:`sidebar-orb${f?` sidebar-orb--starred`:``}`,onClick:()=>{v()},disabled:r||f,"aria-label":y,"aria-pressed":f,title:y,children:(0,Y.jsx)(Re,{"aria-hidden":`true`,...f?{fill:`currentColor`}:{}})}),(0,Y.jsxs)(`button`,{type:`button`,className:`sidebar-orb${m?` sidebar-orb--update`:``}`,onClick:t,"aria-label":b,title:b,children:[(0,Y.jsx)(Se,{"aria-hidden":`true`}),m&&(0,Y.jsx)(`span`,{className:`sidebar-orb-dot`,"aria-hidden":`true`})]})]})]})}var Ww=/^ocx_pair_[A-Za-z0-9_-]{43}$/,Gw=class extends Error{kind;constructor(e){super(`pairing_${e}`),this.kind=e,this.name=`PairingError`}};async function Kw(e,t,n,r){r?.throwIfAborted();let i=t.trim();if(!Ww.test(i))throw new Gw(`invalid-code`);let a=n??((e,t)=>window.fetch(e,t)),o;try{o=await a(e.bootstrapPath,{method:`POST`,signal:r,headers:{"Content-Type":`application/json`,Accept:`text/html`},body:JSON.stringify({grant:i})})}catch(e){throw r?.aborted?e:new Gw(`unreachable`)}if(!o.ok){try{await o.body?.cancel()}catch{}throw new Gw(o.status===401||o.status===403?`refused`:`request-failed`)}let s;try{s=await o.text()}catch(e){throw r?.aborted?e:new Gw(`invalid-response`)}if(r?.throwIfAborted(),!Ux(`shared`,s))throw new Gw(`invalid-response`);return!0}function qw({target:e,onConnected:t}){let n=Q(),[r,i]=(0,_.useState)(``),[a,o]=(0,_.useState)(!1),[s,c]=(0,_.useState)(null),l=(0,_.useRef)(null);(0,_.useEffect)(()=>()=>l.current?.abort(),[]);let u=_s(),d=`ocx gui pair --origin "${window.location.origin}"`,f=u.outcomeFor(d);return(0,Y.jsxs)(`section`,{className:`card connect-pairing`,"aria-labelledby":`connect-pairing-title`,children:[(0,Y.jsx)(`h2`,{id:`connect-pairing-title`,children:n(`connection.pairing.title`)}),(0,Y.jsxs)(`p`,{children:[n(`connection.pairing.hub`),`: `,(0,Y.jsx)(`code`,{children:e.serverOrigin})]}),(0,Y.jsx)(`p`,{children:n(`connection.pairing.getCode`)}),(0,Y.jsx)(`pre`,{style:{whiteSpace:`pre-wrap`,overflowWrap:`anywhere`},children:(0,Y.jsx)(`code`,{children:d})}),(0,Y.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>u.copy(d,d),children:n(f===`copied`?`startup.copied`:`startup.copy`)}),f===`unavailable`&&(0,Y.jsx)(`p`,{role:`status`,children:n(`prov.linkCopyUnavailable`)}),(0,Y.jsx)(`p`,{children:n(`connection.pairing.askOperator`)}),(0,Y.jsx)(`p`,{children:n(`connection.pairing.notApiKey`)}),(0,Y.jsxs)(`form`,{onSubmit:async n=>{if(n.preventDefault(),a)return;o(!0),c(null);let i=new AbortController;l.current=i;try{await Kw(e,r,void 0,i.signal),i.signal.aborted||t()}catch(e){i.signal.aborted||c(e instanceof Gw?e.kind:`unreachable`)}finally{i.signal.aborted||o(!1),l.current===i&&(l.current=null)}},className:`api-form-row`,children:[(0,Y.jsx)(`label`,{htmlFor:`connect-pairing-code`,className:`field-label`,children:n(`connection.pairing.code`)}),(0,Y.jsx)(`input`,{id:`connect-pairing-code`,name:`pairingCode`,value:r,onChange:e=>i(e.currentTarget.value),autoComplete:`off`,spellCheck:!1,disabled:a,className:`input mono`,"aria-invalid":!!s||void 0,"aria-describedby":s?`connect-pairing-error`:void 0}),(0,Y.jsx)(`button`,{type:`submit`,className:`btn btn-primary`,disabled:a||!r.trim(),children:n(a?`connection.pairing.submitting`:`connection.pairing.submit`)}),s&&(0,Y.jsx)(`p`,{id:`connect-pairing-error`,className:`alert alert-err`,role:`alert`,children:n(s===`invalid-code`?`connection.pairing.notApiKey`:s===`unreachable`?`connection.pairing.networkError`:s===`request-failed`?`connection.pairing.requestError`:s===`invalid-response`?`connection.pairing.responseError`:`connection.pairing.error`)})]}),e.transport===`relay`&&(0,Y.jsx)(`p`,{className:`text-muted`,children:n(`connection.pairing.relayWarning`)})]})}var Jw=new Set([`dashboard`,`startup`,`providers`,`models`,`subagents`,`logs`,`usage`,`storage`,`remote`,`codex-set`,`integrations`]);function Yw(e){let t=pt(e??(typeof window<`u`?window.location.hash:``)).split(`/`)[0];return t===`debug`?`logs`:t===`codex-auth`?`codex-set`:t===`combos`||t===`routing`||t===`lab`?`models`:t===`api`||t===`claude`||t===`grok`?`integrations`:Jw.has(t)?t:`dashboard`}var Xw=[`dashboard/providers`,`dashboard/models`],Zw=[`models/combos`,`models/routing`,`models/compatibility`],Qw=[`integrations/keys`,`integrations/codex`,`integrations/claude`,`integrations/claude/desktop`,`integrations/grok`,`integrations/cursor`,`integrations/opencode`,`integrations/pi`,`integrations/omp`,`integrations/hermes`,`integrations/openclaw`,`integrations/kimi`,`integrations/gajae`,`integrations/dsh`,`integrations/mcode`,`integrations/zcode`,`integrations/prime`,`integrations/aside`,`integrations/raycast`,`integrations/omo`,`integrations/cline`];function $w(e,t){return e===t||t===`logs`&&e===`logs/debug`||t===`codex-set`&&e===`codex-set/prompt`||t===`models`&&Zw.includes(e)||t===`dashboard`&&(e===`dashboard/update`||Xw.includes(e))||t===`integrations`&&Qw.includes(e)}function eT(e){let t=Yw(e);return e===`debug`||e.startsWith(`debug/`)?{page:`logs`,replaceTo:`logs/debug`}:e===`codex-auth`||e.startsWith(`codex-auth/`)?{page:`codex-set`,replaceTo:`codex-set`}:e===`combos`||e.startsWith(`combos/`)?{page:`models`,replaceTo:`models/combos`}:e===`routing`||e.startsWith(`routing/`)?{page:`models`,replaceTo:`models/routing`}:e===`lab`||e.startsWith(`lab/`)?{page:`models`,replaceTo:`models/compatibility`}:e===`api`?{page:`integrations`,replaceTo:`integrations/keys`}:e===`claude`?{page:`integrations`,replaceTo:`integrations/claude`}:e===`grok`?{page:`integrations`,replaceTo:`integrations/grok`}:e===`providers/workspace`?{page:`providers`,replaceTo:`providers`}:$w(e,t)?{page:t,replaceTo:null}:{page:t,replaceTo:t}}var tT=[`ocx-global-view`,`ocx-view`,`ocx-providers-view`,`ocx-subagents-view`,`ocx-storage-view`,`ocx-codexauth-view`,`ocx-apikeys-view`,`ocx-claudecode-view`,`ocx-usage-view`,`ocx-logs-view`,`ocx-models-view`,`ocx-dashboard-view`];function nT(){try{for(let e of tT)localStorage.removeItem(e)}catch{}}function rT(){let[e,t]=(0,_.useState)(Yw);(0,_.useEffect)(()=>{nT()},[]);let n=(0,_.useCallback)(e=>{let n=eT(e);n.replaceTo&&mt(n.replaceTo),t(n.page)},[]);return(0,_.useEffect)(()=>{let e=()=>{n(pt(window.location.hash))};return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[n]),(0,_.useEffect)(()=>{let n=eT(pt(window.location.hash));n.replaceTo&&mt(n.replaceTo),n.page!==e&&t(n.page)},[e]),{page:e,setPageState:t,navigateToPage:(e,n)=>{ht(n?`${e}/${n}`:e),t(e)}}}var iT=15e3;function aT(e,t,n){return typeof e?.message==`string`&&e.message.trim()?e.message:typeof e?.error==`string`&&e.error.trim()?e.error:n(t)}function oT(e){return(e instanceof DOMException||e instanceof Error)&&e.name===`AbortError`}async function sT(e,t={}){let{fetchFn:n=fetch,timeoutMs:r=iT,formatFailure:i=e=>`Failed to stop proxy (HTTP ${e}).`,mode:a=`standalone`}=t,o;try{o=await n(`${e}${a===`client`?`/api/machine/disconnect`:`/api/stop`}`,{method:`POST`,...a===`client`?{headers:{"Content-Type":`application/json`},body:`{}`}:{},signal:AbortSignal.timeout(r)})}catch(e){return oT(e),{accepted:!0}}let s=await o.json().catch(()=>null);return!o.ok||s?.success===!1?{accepted:!1,message:aT(s,o.status,i)}:{accepted:!0}}var cT={dashboard:`nav.dashboard`,startup:`nav.startup`,providers:`nav.providers`,models:`nav.models`,subagents:`nav.subagents`,logs:`nav.logs`,usage:`nav.usage`,storage:`nav.storage`,remote:`nav.remote`,"codex-set":`nav.codexSet`,integrations:`nav.integrations`},lT=``,uT=Rb(lT);Px(uT),eS();var dT=`ocx-theme`,fT=[{id:`dashboard`,tkey:`nav.dashboard`,Icon:ee},{id:`codex-set`,tkey:`nav.codexSet`,Icon:Oe},{id:`providers`,tkey:`nav.providers`,Icon:te},{id:`models`,tkey:`nav.models`,Icon:ne},{id:`subagents`,tkey:`nav.subagents`,Icon:Z},{id:`logs`,tkey:`nav.logs`,Icon:re},{id:`usage`,tkey:`nav.usage`,Icon:oe},{id:`storage`,tkey:`nav.storage`,Icon:se},{id:`remote`,tkey:`nav.remote`,Icon:Pe},{id:`integrations`,tkey:`nav.integrations`,Icon:Fe}],pT={light:Me,dark:Ne,system:Pe},mT={light:`theme.light`,dark:`theme.dark`,system:`theme.system`};function hT(e){if(!e||typeof e!=`object`||!(`version`in e))return null;let t=e.version;return typeof t==`string`&&t.length>0?t:null}function gT(){let e=localStorage.getItem(dT);return e===`light`||e===`dark`?e:`system`}function _T(){let{page:e,navigateToPage:t}=rT(),[n,r]=(0,_.useState)(gg);(0,_.useEffect)(()=>{let e=()=>r(gg());return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]);let[i,a]=(0,_.useState)(gT),{locale:o,setLocale:s}=ut(),c=Q(),[l,u]=(0,_.useState)(uT),[d,f]=(0,_.useState)(()=>!Mb()),[p,m]=(0,_.useState)(!1),[h,g]=(0,_.useState)(()=>Rx(`shared`)),[v,y]=(0,_.useState)(0),[b,x]=(0,_.useState)(!1);(0,_.useEffect)(()=>{let e=e=>{e.detail?.plane===`shared`&&!Rx(`shared`)&&g(!1)};return window.addEventListener(hx,e),()=>window.removeEventListener(hx,e)},[]),(0,_.useEffect)(()=>{let e=new AbortController;return Hb(lT,e.signal).then(async t=>{if(Px(t),u(t),t.connected&&!Rx(`shared`))try{let n=await fetch(t.shared.bootstrapPath,{cache:`no-store`,signal:AbortSignal.any([e.signal,AbortSignal.timeout(5e3)])});n.ok&&Ux(`shared`,await n.text())}catch{}e.signal.aborted||(g(Rx(`shared`)),m(!1),f(!0))}).catch(()=>{e.signal.aborted||(m(!0),f(!0))}),()=>e.abort()},[]);let S=Vb(`machine`,l),C=Vb(`shared`,l),[w,T]=(0,_.useState)(!1),E=(0,_.useRef)(null),D=(0,_.useRef)(null),O=(0,_.useRef)(!1);(0,_.useEffect)(()=>{let e=()=>T(!1);return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]),(0,_.useEffect)(()=>{let e=document.documentElement;i===`system`?(e.removeAttribute(`data-theme`),localStorage.removeItem(dT)):(e.setAttribute(`data-theme`,i),localStorage.setItem(dT,i))},[i]);let k=K(`app-healthz:${S}`,[S,d],async e=>{let t=await fetch(`${S}/healthz`,{signal:e});return t.ok?hT(await t.json()):null},{pollMs:3e4,enabled:d}),A=()=>a(e=>e===`light`?`dark`:e===`dark`?`system`:`light`),j=pT[i],M=k.data??`2.54.0-preview.20260914`,[N,P]=(0,_.useState)(!1);(0,_.useEffect)(()=>{if(!w)return;let e=e=>{e.key===`Escape`&&T(!1)};window.addEventListener(`keydown`,e);let t=document.body.style.overflow;return document.body.style.overflow=`hidden`,()=>{window.removeEventListener(`keydown`,e),document.body.style.overflow=t}},[w]),(0,_.useEffect)(()=>{if(w){O.current=!0;let e=setTimeout(()=>D.current?.focus(),200);return()=>clearTimeout(e)}O.current&&(O.current=!1,E.current?.focus())},[w]),(0,_.useEffect)(()=>{let e=window.matchMedia(`(min-width: 761px)`),t=()=>{e.matches&&T(!1)};return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]);let[F,I]=(0,_.useState)(0),{restarting:L,restart:R}=Xd(C,{onSettled:()=>I(e=>e+1)}),z=async()=>{if(!confirm(c(l.connected?`connection.disconnectConfirm`:`dash.stopConfirm`)))return;P(!0);let e=await sT(S,{formatFailure:e=>c(`dash.stopFailed`,{status:String(e)}),mode:l.connected?`client`:`standalone`});e.accepted||(P(!1),alert(e.message))},B=async()=>{if(b)return;x(!0);let e=await zx(`shared`);x(!1),e?g(!1):alert(c(`connection.sessionLogoutFailed`))},V=(0,Y.jsxs)(`button`,{type:`button`,className:`brand brand-home`,onClick:()=>{t(`dashboard`),T(!1)},"aria-label":c(`nav.goHome`),title:c(`nav.goHome`),...e===`dashboard`?{"aria-current":`page`}:{},children:[(0,Y.jsx)(`span`,{className:`brand-logo`,role:`img`,"aria-label":c(`app.logoAria`)}),(0,Y.jsx)(`span`,{className:`name`,children:`opencodex`}),(0,Y.jsxs)(`span`,{className:`ver`,title:M,children:[`v`,M]})]});return(0,Y.jsxs)(`div`,{className:`app`,children:[(0,Y.jsxs)(`header`,{className:`mobile-topbar`,inert:w,children:[(0,Y.jsx)(`button`,{ref:E,type:`button`,className:`menu-toggle`,onClick:()=>T(e=>!e),"aria-expanded":w,"aria-controls":`app-sidebar`,"aria-label":c(w?`nav.closeMenu`:`nav.openMenu`),title:c(w?`nav.closeMenu`:`nav.openMenu`),children:(0,Y.jsx)(ie,{})}),V,(0,Y.jsxs)(`div`,{className:`mobile-topbar-actions`,children:[l.connected&&h&&(0,Y.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:()=>{B()},disabled:b,"aria-label":c(b?`connection.sessionLoggingOut`:`connection.sessionLogout`),title:c(`connection.sessionLogout`),children:(0,Y.jsx)(le,{})}),(0,Y.jsx)(`button`,{type:`button`,className:`sidebar-orb sidebar-orb--danger`,onClick:z,disabled:N,"aria-label":c(l.connected?`connection.disconnect`:`dash.stop`),title:c(l.connected?`connection.disconnect`:`dash.stop`),children:(0,Y.jsx)(Te,{})}),(0,Y.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:()=>{R()},disabled:L,"aria-label":c(`dash.codexRestart`),title:c(`dash.codexRestart`),children:(0,Y.jsx)(de,{})})]})]}),w&&(0,Y.jsx)(`div`,{className:`drawer-scrim`,onClick:()=>T(!1),"aria-hidden":`true`}),(0,Y.jsxs)(`aside`,{id:`app-sidebar`,className:`sidebar${w?` open`:``}`,ref:D,tabIndex:-1,children:[(0,Y.jsxs)(`div`,{className:`drawer-head`,children:[V,(0,Y.jsx)(`button`,{type:`button`,className:`menu-toggle drawer-close`,onClick:()=>T(!1),"aria-label":c(`nav.closeMenu`),title:c(`nav.closeMenu`),children:(0,Y.jsx)(le,{})})]}),(0,Y.jsx)(`nav`,{children:fT.map(n=>{let{id:r,tkey:i,Icon:a}=n,o=r===e;return(0,Y.jsx)(`div`,{className:`nav-entry`,children:(0,Y.jsxs)(`button`,{type:`button`,className:`nav-item${o?` active`:``}`,"data-page":r,onClick:()=>{t(r),T(!1)},"aria-current":o?`page`:void 0,children:[(0,Y.jsx)(a,{}),` `,c(i)]})},r)})}),(0,Y.jsxs)(`div`,{className:`sidebar-foot`,children:[(0,Y.jsxs)(`div`,{className:`lang-toggle`,children:[(0,Y.jsx)(Fe,{"aria-hidden":!0}),(0,Y.jsx)(kt,{value:o,options:nt.map(e=>({value:e.code,label:et(e.code)})),onChange:e=>s(e),label:c(`lang.label`),placement:`right`,portal:!1,style:{flex:1,minWidth:0,width:`100%`}})]}),(0,Y.jsxs)(`button`,{type:`button`,className:`theme-toggle`,onClick:A,"aria-label":`${c(`theme.label`)}: ${c(mT[i])}`,title:`${c(`theme.label`)}: ${c(mT[i])}`,children:[(0,Y.jsx)(j,{}),` `,(0,Y.jsx)(`span`,{className:`mode`,children:c(mT[i])})]}),(0,Y.jsxs)(`div`,{className:`sidebar-action-row`,children:[(0,Y.jsx)(`span`,{className:`sidebar-action-label`,children:c(`dash.actions`)}),(0,Y.jsxs)(`div`,{className:`sidebar-action-orbs`,children:[l.connected&&h&&(0,Y.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:()=>{B()},disabled:b,"aria-label":c(b?`connection.sessionLoggingOut`:`connection.sessionLogout`),title:c(`connection.sessionLogout`),children:(0,Y.jsx)(le,{})}),(0,Y.jsx)(`button`,{type:`button`,className:`sidebar-orb sidebar-orb--danger`,onClick:z,disabled:N,"aria-label":c(N?`dash.stopping`:l.connected?`connection.disconnect`:`dash.stop`),title:c(N?`dash.stopping`:l.connected?`connection.disconnect`:`dash.stop`),children:(0,Y.jsx)(Te,{})}),(0,Y.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:()=>{R()},disabled:L,"aria-label":c(L?`dash.codexRestarting`:`dash.codexRestart`),title:c(L?`dash.codexRestarting`:`dash.codexRestart`),children:(0,Y.jsx)(de,{})})]})]}),(0,Y.jsx)(Uw,{apiBase:C,onOpenUpdate:()=>{T(!1),t(`dashboard`,`update`)}})]})]}),(0,Y.jsx)(`main`,{className:`main`,inert:w,children:(0,Y.jsx)(`div`,{className:`main-inner${e===`models`&&n===`combos`?` main-inner--combos`:``}`,children:(0,Y.jsx)(np,{pageName:c(cT[e]),title:c(`errorBoundary.title`),message:c(`errorBoundary.message`),detailsLabel:c(`errorBoundary.details`),reloadLabel:c(`errorBoundary.reload`),children:d?(0,Y.jsxs)(Y.Fragment,{children:[p&&(0,Y.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:c(`connection.machineUnavailable`)}),l.connected&&!h&&(0,Y.jsx)(qw,{target:l.shared,onConnected:()=>{g(!0),y(e=>e+1)}},`${l.shared.serverOrigin}:${l.shared.bootstrapPath}`),e===`dashboard`&&(0,Y.jsx)(si,{apiBase:C,connected:l.connected,authenticationPending:l.connected&&!h,refreshEpoch:v}),e===`startup`&&(0,Y.jsx)(Dw,{apiBase:C,machineApiBase:S,connected:l.connected}),e===`providers`&&(0,Y.jsx)(sd,{apiBase:C}),e===`models`&&(0,Y.jsx)(Dg,{apiBase:C,restartEpoch:F},C),e===`subagents`&&(0,Y.jsx)(zg,{apiBase:C},C),e===`logs`&&(0,Y.jsx)(jv,{apiBase:C}),e===`usage`&&(0,Y.jsx)(ny,{apiBase:C,connected:l.connected,apiKeyId:l.apiKeyId}),e===`storage`&&(0,Y.jsx)(jy,{apiBase:C}),e===`remote`&&(0,Y.jsx)(Rw,{apiBase:C,hubOrigin:l.shared.serverOrigin}),e===`codex-set`&&(0,Y.jsx)(bb,{apiBase:C}),e===`integrations`&&(0,Y.jsx)(mw,{apiBase:C,machineApiBase:S,connected:l.connected})]}):(0,Y.jsx)(`div`,{className:`alert`,children:c(`connection.discovering`)})},e)})})]})}g.createRoot(document.getElementById(`root`)).render((0,Y.jsx)(_.StrictMode,{children:(0,Y.jsx)(dt,{children:(0,Y.jsx)(_T,{})})}));
|