@koreanhole/opencodex 2.95.1 → 2.95.3

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.
@@ -1,10 +1,10 @@
1
- import{A as e,C as t,D as n,E as r,M as i,N as a,O as o,P as s,S as c,T as l,_ as u,a as d,b as f,c as p,d as m,f as h,g,h as _,i as v,j as y,k as b,l as x,m as S,n as C,o as w,p as T,r as E,s as D,t as O,u as k,v as A,w as j,x as M,y as N}from"./index-BnsxCFZM.js";import{$ as P,A as F,At as I,B as L,Bt as R,C as z,Ct as B,D as V,Dt as H,E as U,Et as ee,F as W,Ft as te,G,H as ne,I as K,It as re,J as q,K as J,L as Y,Lt as ie,M as X,Mt as ae,N as oe,Nt as se,O as ce,Ot as le,P as ue,Pt as de,Q as fe,R as pe,Rt as me,S as he,St as ge,T as _e,Tt as ve,U as ye,V as be,Vt as xe,W as Se,X as Ce,Y as we,Z as Te,_ as Ee,_t as De,at as Oe,b as ke,bt as Ae,ct as je,dt as Me,et as Ne,ft as Pe,g as Fe,gt as Ie,h as Le,ht as Re,it as ze,j as Be,jt as Ve,k as He,kt as Ue,lt as We,m as Ge,mt as Ke,n as qe,nt as Je,ot as Ye,pt as Xe,q as Ze,rt as Qe,st as $e,t as et,tt,ut as nt,v as rt,vt as it,w as at,wt as ot,x as st,xt as ct,y as lt,yt as ut,z as dt,zt as ft}from"./quota-summary-C7b7JF2K.js";var Z=s(a(),1);function pt(){return typeof document<`u`&&document.visibilityState===`hidden`||typeof window<`u`&&window.__OPENCODEX_HOST_VISIBLE__===!1}function mt(e){let t=pt(),n=()=>{let n=pt();n!==t&&(t=n,e())},r=e=>{let t=e.detail;typeof window<`u`&&typeof t==`boolean`&&(window.__OPENCODEX_HOST_VISIBLE__=t),n()};return typeof document<`u`&&document.addEventListener(`visibilitychange`,n),typeof window<`u`&&window.addEventListener(`opencodex:host-visibility`,r),()=>{typeof document<`u`&&document.removeEventListener(`visibilitychange`,n),typeof window<`u`&&window.removeEventListener(`opencodex:host-visibility`,r)}}var ht=new Map,gt=new Set,_t=3e4,vt=`ocx-resource-deadline`,yt={data:void 0,error:void 0,loading:!1,refreshing:!1,hasSucceeded:!1,lastAttemptOk:!1};function bt(e){let t=ht.get(e);return t||(t={key:e,snapshot:{data:void 0,error:void 0,loading:!1,refreshing:!1,hasSucceeded:!1,lastAttemptOk:!1},listeners:new Set,pollByListener:new Map,pauseWhenHiddenByListener:new Map,fetcherByListener:new Map,deadlineByListener:new Map,subscriberCount:0,pollIntervalMs:void 0,inflight:null,inflightOwner:null,generation:0,seedNeedsRevalidate:!1,lastSettledAt:void 0},ht.set(e,t)),t}function xt(e){for(let t of e.listeners)t()}var St=new Map;function Ct(e){for(let[t,n]of e.pollByListener)if(typeof n==`number`&&n>0&&e.pauseWhenHiddenByListener.get(t)===!1)return!0;return!1}function wt(e){if(e.stores.size===0)return!1;if(!At())return!0;for(let t of e.stores)if(Ct(t))return!0;return!1}function Tt(e){for(let t of e.stores){let e=jt(t);e&&Lt(t,e.fetcher,{replaceInflight:!1,owner:e.owner,deadlineMs:e.deadlineMs})}}function Et(e,t){let n=wt(t);n&&t.timer===null?t.timer=setInterval(()=>Tt(t),e):(!n&&t.timer!==null&&(clearInterval(t.timer),t.timer=null),t.stores.size===0&&St.delete(e))}function Dt(){for(let[e,t]of[...St])Et(e,t)}function Ot(e){let t=e.pollIntervalMs;if(t===void 0)return;let n=St.get(t);e.pollIntervalMs=void 0,n&&(n.stores.delete(e),Et(t,n))}function kt(e,t){let n=St.get(t);n||(n={timer:null,stores:new Set},St.set(t,n)),n.stores.add(e),e.pollIntervalMs=t,Et(t,n)}function At(){return pt()}function jt(e){if(!At())return Mt(e);for(let[t,n]of e.pollByListener)if(!(typeof n!=`number`||n<=0)&&e.pauseWhenHiddenByListener.get(t)===!1){let n=e.fetcherByListener.get(t);if(n)return{owner:t,fetcher:n,deadlineMs:e.deadlineByListener.get(t)}}return null}function Mt(e){for(let[t,n]of e.pollByListener)if(typeof n==`number`&&n>0){let n=e.fetcherByListener.get(t);if(n)return{owner:t,fetcher:n,deadlineMs:e.deadlineByListener.get(t)}}for(let[t,n]of e.fetcherByListener)return{owner:t,fetcher:n,deadlineMs:e.deadlineByListener.get(t)};return null}function Nt(e){let t;for(let n of e.pollByListener.values())typeof n==`number`&&n>0&&(t=t===void 0?n:Math.min(t,n));if(t===void 0)Ot(e),It(e);else if(t===e.pollIntervalMs){let n=St.get(t);n&&Et(t,n),Ft(e)}else Ot(e),kt(e,t),Ft(e)}var Pt=null;function Ft(e){typeof document>`u`||Pt||(Pt=mt(()=>{if(Dt(),!At())for(let e of St.values())for(let t of e.stores){let e=Mt(t);e&&Lt(t,e.fetcher,{replaceInflight:!1,owner:e.owner,deadlineMs:e.deadlineMs})}}))}function It(e){Pt&&(St.size>0||(Pt(),Pt=null))}async function Lt(e,t,n){let r=n?.replaceInflight!==!1;if(e.inflight&&!r)return;r&&e.inflight?.abort();let i=new AbortController;e.inflight=i,e.inflightOwner=n?.owner??null;let a=++e.generation,o=n?.deadlineMs??_t,s=!1,c=setTimeout(()=>{s=!0,i.abort(vt)},o),l=e.snapshot.data===void 0||n?.forceLoading===!0;e.snapshot={...e.snapshot,loading:l?!0:e.snapshot.loading,refreshing:!0},xt(e);try{let n=await Promise.race([t(i.signal),new Promise((e,t)=>{i.signal.addEventListener(`abort`,()=>{s?t(Error(`resource request timed out after ${o}ms`)):e(null)},{once:!0})})]);if(a!==e.generation||i.signal.aborted)return;e.seedNeedsRevalidate=!1,gt.delete(e.key),e.lastSettledAt=Date.now(),e.snapshot={data:n,error:void 0,loading:!1,refreshing:!1,hasSucceeded:!0,lastAttemptOk:!0}}catch(t){if(a!==e.generation||i.signal.aborted&&!s)return;e.seedNeedsRevalidate=!1,e.snapshot={...e.snapshot,error:t===void 0?Error(`resource load failed`):t,loading:!1,refreshing:!1,lastAttemptOk:!1}}finally{clearTimeout(c),e.inflight===i&&(e.inflight=null,e.inflightOwner=null),xt(e)}}function Rt(e,t){return e.inflightOwner===t&&(e.inflight?.abort(),e.inflight=null,e.inflightOwner=null,e.generation++,e.snapshot.refreshing&&(e.snapshot={...e.snapshot,refreshing:!1},xt(e)),!0)}function zt(e,t){Ot(t),It(t),setTimeout(()=>{t.subscriberCount===0&&ht.get(e)===t&&(t.inflight?.abort(),t.inflight=null,t.inflightOwner=null,ht.delete(e))},0)}function Bt(e,t,n){let{fetcher:r,pollMs:i,pauseWhenHidden:a=!0,deadlineMs:o,staleAfterMs:s}=n,c=bt(e);if(c.listeners.add(t),c.pollByListener.set(t,i),c.pauseWhenHiddenByListener.set(t,a),c.fetcherByListener.set(t,r),c.deadlineByListener.set(t,o),c.subscriberCount++,c.subscriberCount===1){let n=typeof s==`number`&&c.lastSettledAt!==void 0&&Date.now()-c.lastSettledAt>s;(c.snapshot.data===void 0||c.seedNeedsRevalidate||gt.has(e)||n)&&Lt(c,r,{replaceInflight:!0,owner:t,deadlineMs:o})}return Nt(c),()=>{c.listeners.delete(t),c.pollByListener.delete(t),c.pauseWhenHiddenByListener.delete(t),c.fetcherByListener.delete(t),c.deadlineByListener.delete(t),c.subscriberCount--;let n=Rt(c,t);if(c.subscriberCount===0)zt(e,c);else{if(n){let e=Mt(c);e&&Lt(c,e.fetcher,{replaceInflight:!0,owner:e.owner,deadlineMs:e.deadlineMs})}Nt(c)}}}function Vt(e,t,n,r){let i=bt(e);i.subscriberCount===0&&i.snapshot.data===void 0&&(Kt(e,t),!gt.has(e)&&typeof r==`number`&&typeof n==`number`&&Date.now()-n<r&&(i.seedNeedsRevalidate=!1,i.lastSettledAt=n))}function Ht(e,t,n){let r=n?.enabled!==!1,i=n?.pollMs,a=n?.pauseWhenHidden!==!1,o=n?.deadlineMs,s=n?.staleAfterMs;r&&n?.initialData!==void 0&&Vt(e,n.initialData,n.initialDataCachedAt,s);let c=(0,Z.useRef)(t);(0,Z.useLayoutEffect)(()=>{c.current=t});let l=(0,Z.useCallback)(e=>c.current(e),[]),u=(0,Z.useRef)(null),d=(0,Z.useCallback)(t=>r?(u.current=t,Bt(e,t,{fetcher:l,pollMs:i,pauseWhenHidden:a,deadlineMs:o,staleAfterMs:s})):()=>{},[e,l,i,r,a,o,s]),f=(0,Z.useCallback)(()=>r?bt(e).snapshot:yt,[e,r]),p=(0,Z.useSyncExternalStore)(d,f,f),m=(0,Z.useCallback)(t=>{if(!r)return;let n=bt(e);Lt(n,l,{replaceInflight:!0,owner:u.current,forceLoading:t?.forceLoading,deadlineMs:u.current?n.deadlineByListener.get(u.current):o})},[e,l,r,o]);return{...p,refresh:m}}function Ut(e,t){if(e===null)return!1;if(e.length!==t.length)return!0;for(let n=0;n<e.length;n++)if(!Object.is(e[n],t[n]))return!0;return!1}function Wt(e,t,n,r){let i=Ht(e,n,r),a=(0,Z.useRef)(null),o=(0,Z.useRef)(null);return(0,Z.useLayoutEffect)(()=>{let n=a.current,r=o.current;a.current=t,o.current=e,Ut(n,t)&&(r===null||r===e)&&i.refresh({forceLoading:!0})}),i}function Gt(e){gt.add(e);let t=ht.get(e);if(!t)return;let n=Mt(t);n&&Lt(t,n.fetcher,{replaceInflight:!0,owner:n.owner,deadlineMs:n.deadlineMs})}function Kt(e,t){let n=bt(e);n.inflight?.abort(),n.inflight=null,n.inflightOwner=null,n.generation++,n.snapshot={data:t,error:void 0,loading:!1,refreshing:!1,hasSucceeded:!0,lastAttemptOk:!0},n.seedNeedsRevalidate=n.subscriberCount===0,n.lastSettledAt=Date.now(),xt(n)}function qt(e){return e.replace(/^#\/?/,``)}function Jt(e){let t=e.indexOf(`?`);return t<0?{path:e,query:``}:{path:e.slice(0,t),query:e.slice(t+1)}}function Yt(e,t=window){let n=qt(e);if(qt(t.location.hash)===n)return;let r=`${t.location.pathname}${t.location.search}#${n}`;t.history.replaceState(t.history.state,``,r)}function Xt(e,t=window){let n=qt(e);qt(t.location.hash)!==n&&(t.location.hash=n)}var Zt=i(),Qt=4,$t=8,en=8,tn=280,nn=120,rn=160,an=12;function on(){return typeof window<`u`?window.innerHeight:800}function sn(){return typeof window<`u`?window.innerWidth:1024}function cn(e,{align:t,placement:n=`below`,menuHeight:r=tn}={}){let i=Math.min(Math.max(r,nn),tn),a=on(),o=sn();if(n===`right`){let t=a-e.top-en,n=e.top-en,r=i+$t>t&&n>t,s=Math.max(en,Math.min(e.right+an,o-rn-en));return r?{position:`fixed`,left:s,bottom:a-e.top+$t,minWidth:rn,maxHeight:Math.max(nn,Math.min(tn,e.top-en-Qt))}:{position:`fixed`,top:e.top,left:s,minWidth:rn,maxHeight:Math.max(nn,Math.min(tn,a-e.top-en))}}let s=t??(e.right>o/2?`right`:`left`),c=Math.max(e.width,0),l=a-e.bottom-en,u=e.top-en;if(i+Qt>l&&u>l){let t={position:`fixed`,bottom:a-e.top+$t,minWidth:c,maxHeight:Math.max(0,Math.min(tn,u-Qt))};return s===`right`?t.right=Math.max(en,o-e.right):t.left=Math.max(en,Math.min(e.left,o-en-c)),t}let d={position:`fixed`,top:e.bottom+Qt,minWidth:c,maxHeight:Math.max(0,Math.min(tn,l-Qt))};return s===`right`?d.right=Math.max(en,o-e.right):d.left=Math.max(en,Math.min(e.left,o-en-c)),d}var Q=C();function ln({on:e,mixed:t=!1,onClick:n,disabled:r,label:i,showLabel:a=!1,title:o}){let s=a&&!!i;return(0,Q.jsxs)(`button`,{type:`button`,className:`switch${e?` on`:``}${t?` mixed`:``}${s?` switch-labeled`:``}`,onClick:n,disabled:r,"aria-pressed":t?`mixed`:e,"aria-label":s?void 0:i??(e?`enabled`:`disabled`),title:o,children:[(0,Q.jsx)(`span`,{className:`knob`}),s?(0,Q.jsx)(`span`,{className:`switch-labeled-text text-label muted`,children:i}):null]})}function $({tone:e,children:t}){return(0,Q.jsxs)(`div`,{className:`notice ${e===`ok`?`notice-ok`:e===`warn`?`notice-warn`:`notice-err`}`,role:`status`,children:[e===`ok`?(0,Q.jsx)(Oe,{}):(0,Q.jsx)(Ne,{}),(0,Q.jsx)(`span`,{children:t})]})}function un({tone:e,children:t,onDismiss:n,dismissLabel:r}){return(0,Zt.createPortal)((0,Q.jsx)(`div`,{className:`toast-notice-host`,role:`presentation`,children:(0,Q.jsxs)(`div`,{className:`toast-notice notice ${e===`ok`?`notice-ok`:e===`warn`?`notice-warn`:`notice-err`}`,role:`status`,"aria-live":`polite`,children:[e===`ok`?(0,Q.jsx)(Oe,{}):(0,Q.jsx)(Ne,{}),(0,Q.jsx)(`span`,{className:`toast-notice-copy`,children:t}),n&&(0,Q.jsx)(`button`,{type:`button`,className:`toast-notice-dismiss`,onClick:n,"aria-label":r,children:`×`})]})}),document.body)}function dn({value:e,options:t,onChange:n,disabled:r,id:i,label:a,describedBy:o,title:s,style:c,align:l,placement:u,dropdownStyle:d,portal:f=!0}){let p=(0,Z.useId)(),[m,h]=(0,Z.useState)(!1),[g,_]=(0,Z.useState)(null),[v,y]=(0,Z.useState)(),b=(0,Z.useRef)(null),x=(0,Z.useRef)(null),S=(0,Z.useRef)(null),C=(0,Z.useCallback)(e=>`${p}-${e}`,[p]),w=t.find(t=>t.value===e),T=t.length===0?0:Math.max(0,t.findIndex(t=>t.value===e)),E=!m||t.length===0?T:Math.min(g??T,t.length-1),D=(0,Z.useCallback)((e=!1)=>{h(!1),_(null),e&&x.current?.focus()},[]),O=(0,Z.useCallback)(e=>{if(r||t.length===0)return;let n=Math.max(0,Math.min(t.length-1,e));_(n),h(!0)},[r,t.length]),k=(0,Z.useCallback)(e=>{if(!f)return;let t=x.current;t&&y(cn(t.getBoundingClientRect(),{align:l,placement:u,menuHeight:e}))},[l,u,f]);(0,Z.useEffect)(()=>{if(!m)return;let e=e=>{let t=e.target;b.current?.contains(t)||S.current?.contains(t)||D()};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[D,m]),(0,Z.useLayoutEffect)(()=>{if(!m||!f)return;k();let e=()=>k(S.current?.offsetHeight);return window.addEventListener(`resize`,e),window.addEventListener(`scroll`,e,!0),()=>{window.removeEventListener(`resize`,e),window.removeEventListener(`scroll`,e,!0)}},[m,t.length,f,k]),(0,Z.useLayoutEffect)(()=>{if(!m||!f||!S.current||!x.current)return;let e=S.current.offsetHeight;if(!e)return;let t=cn(x.current.getBoundingClientRect(),{align:l,placement:u,menuHeight:e});y(e=>e?.top===t.top&&e?.bottom===t.bottom&&e?.maxHeight===t.maxHeight?e:t)},[l,m,t.length,u,f]),(0,Z.useLayoutEffect)(()=>{m&&S.current&&S.current.querySelector(`[id="${C(E)}"]`)?.scrollIntoView({block:`nearest`})},[E,m,C]);let A=e=>{if(r)return;let i=t[e];i&&(n(i.value),D(!0))},j=e=>{if(!r)switch(e.key){case`ArrowDown`:e.preventDefault(),O(m?Math.min(t.length-1,E+1):T);break;case`ArrowUp`:e.preventDefault(),O(m?Math.max(0,E-1):T);break;case`Home`:e.preventDefault(),O(0);break;case`End`:e.preventDefault(),O(t.length-1);break;case`Enter`:case` `:e.preventDefault(),m?A(E):O(T);break;case`Escape`:m&&(e.preventDefault(),D(!0));break;case`Tab`:if(m){let e=t[E];e&&n(e.value),h(!1)}}},M=m&&t[E]?C(E):void 0,N=m&&!r?(0,Q.jsx)(`div`,{ref:S,id:p,className:`select-dropdown${f?` select-dropdown-portal`:``}${!f&&l===`right`?` select-dropdown-right`:``}${!f&&u===`right`?` select-dropdown-beside`:``}`,role:`listbox`,"aria-label":a,style:f?{...v,zIndex:60,...d}:d,children:t.map((t,n)=>(0,Q.jsx)(`button`,{id:C(n),type:`button`,role:`option`,tabIndex:-1,disabled:r,"aria-selected":t.value===e,className:`select-option${t.value===e?` active`:``}${n===E?` select-option-active`:``}`,onMouseEnter:()=>_(n),onClick:()=>A(n),children:t.label},t.value))}):null;return(0,Q.jsxs)(`div`,{ref:b,className:`custom-select`,style:{position:`relative`,display:`inline-block`,...c},children:[(0,Q.jsxs)(`button`,{ref:x,id:i,type:`button`,role:`combobox`,title:s,"aria-describedby":o,className:`select-trigger`,onClick:()=>{r||(m?D():O(T))},onKeyDown:j,disabled:r,"aria-haspopup":`listbox`,"aria-expanded":m,"aria-controls":m?p:void 0,"aria-activedescendant":M,"aria-label":a,children:[(0,Q.jsx)(`span`,{children:w?.label??e}),(0,Q.jsx)(Ye,{style:{width:12,height:12,color:`var(--muted)`,transform:m?`rotate(90deg)`:`none`,transition:`transform .12s`}})]}),f?N&&(0,Zt.createPortal)(N,document.body):N]})}function fn({icon:e,title:t,children:n,className:r,style:i}){return(0,Q.jsxs)(`div`,{className:r?`empty ${r}`:`empty`,style:i,children:[e,(0,Q.jsx)(`div`,{className:`title`,children:t}),n&&(0,Q.jsx)(`div`,{className:`text-control`,children:n})]})}function pn({content:e,children:t,side:n=`top`,maxWidth:r=280}){let[i,a]=(0,Z.useState)(!1),o=(0,Z.useId)(),s=(0,Z.useRef)(null),c=()=>{s.current!==null&&window.clearTimeout(s.current),s.current=window.setTimeout(()=>a(!0),150)},l=()=>{s.current!==null&&(window.clearTimeout(s.current),s.current=null),a(!1)};return(0,Z.useEffect)(()=>()=>{s.current!==null&&window.clearTimeout(s.current)},[]),(0,Q.jsxs)(`button`,{type:`button`,className:`ocx-tooltip`,onMouseEnter:c,onMouseLeave:l,onFocus:c,onBlur:l,onKeyDown:e=>{e.key===`Escape`&&l()},"aria-describedby":i?o:void 0,style:{display:`inline`,border:0,background:`transparent`,padding:0,margin:0,color:`inherit`,font:`inherit`,cursor:`inherit`},children:[t,i&&(0,Q.jsx)(`span`,{id:o,className:`ocx-tooltip-bubble ocx-tooltip-bubble--${n}`,role:`tooltip`,style:{maxWidth:r},children:e})]})}var mn=45e3,hn=2147483647;async function gn(e){if(e.status!==204){if(typeof e.text==`function`){let t=await e.text();return t.trim()?JSON.parse(t):void 0}return await e.json()}}function _n(e,t){return typeof e.error==`string`&&e.error?e.error:typeof e.message==`string`&&e.message?e.message:t}async function vn(e,t=`HTTP ${e.status}`){if(!e.ok){let n=t;try{n=_n(await e.json(),t)}catch{}throw Error(n)}return gn(e)}async function yn(e){if(!e.ok)return null;try{return await gn(e)}catch{return null}}var bn=[`gpt-6-luna`,`gpt-5.6-luna`];function xn(e){let t=Array.isArray(e)?e.filter(e=>typeof e==`string`&&e.trim()!==``).map(e=>e.trim()):[];return t.length===0?bn:t.filter(e=>!e.includes(`/`))}function Sn(e){return xn(e).join(`, `)}function Cn(e){return xn(e).map(e=>e.replace(/^gpt-/,``)).join(`, `)}function wn(e,t){return xn(t).some(t=>e.startsWith(t))}function Tn(e,t){let n=xn(t),r=n.find(t=>t!==e.id&&e.id.startsWith(t));if(r!==void 0)return{blocked:`covered`,prefix:r};if(!n.includes(e.id))return{sourceModels:[...n,e.id]};let i=n.filter(t=>t!==e.id);return i.length===0?{blocked:`last`}:{sourceModels:i}}function En(e,t,n=[`gpt-6.1-terra`,`gpt-5.6-terra`]){let r=xn(e),i=n.some(e=>e!==``&&r.some(t=>e.startsWith(t))),a=Cn(e);return i?a:`${a} (+ ${t})`}var Dn=`dashboard/update`;function On(){let e=window.location.hash.replace(/^#\/?/,``);return e===`dashboard/providers`?`providers`:e===`dashboard/models`?`models`:`overview`}function kn(){return window.location.hash.replace(/^#\/?/,``)===Dn}function An(e){return e===`overview`?`dashboard`:`dashboard/${e}`}async function jn(e,t){let n=await vn(e,t);if(n===void 0)throw Error(t??`empty response`);return n}var Mn=[`low`,`medium`,`high`,`xhigh`];function Nn(e){return e?.includes(`-preview.`)?`preview`:`latest`}function Pn(e,t){switch(e){case`source_checkout`:return t(`dash.updateReason.source_checkout`);case`latest_unavailable`:return t(`dash.updateReason.latest_unavailable`);case`already_latest`:return t(`dash.updateReason.already_latest`);case`externally_managed`:return t(`dash.updateReason.externally_managed`);case`external_ownership_invalid`:return t(`dash.updateReason.external_ownership_invalid`);default:return t(`dash.updateReason.unknown`)}}function Fn(e,t){switch(e){case`running`:return t(`dash.updateStatus.running`);case`restarting`:return t(`dash.updateStatus.restarting`);case`succeeded`:return t(`dash.updateStatus.succeeded`);case`failed`:return t(`dash.updateStatus.failed`)}}function In(e,t){let n={...e};return t?.model!==void 0&&(n.model=t.model),t?.backend===null?delete n.backend:t?.backend!==void 0&&(n.backend=t.backend),t?.anthropicInstance===null?delete n.anthropicInstance:t?.anthropicInstance!==void 0&&(n.anthropicInstance=t.anthropicInstance),t?.backend!==void 0&&t.backend!==`anthropic`&&delete n.anthropicInstance,t?.reasoning!==void 0&&(n.reasoning=t.reasoning),t?.streamRoutedModelOutput!==void 0&&(n.streamRoutedModelOutput=t.streamRoutedModelOutput),t?.enabled!==void 0&&(n.enabled=t.enabled),t?.maxDescriptionsPerTurn!==void 0&&(n.maxDescriptionsPerTurn=t.maxDescriptionsPerTurn),t?.timeoutMs!==void 0&&(n.timeoutMs=t.timeoutMs),n}function Ln(e){return{vision:{reasoning:e}}}function Rn(e){return{vision:{enabled:e}}}function zn(e){return{webSearch:{enabled:e}}}function Bn(e){return e?.applied===!1&&e.reason!==`not_requested`}function Vn(e,t){return t?.reason===`not_requested`&&Bn(e)?e:t}function Hn(e){return{vision:{maxDescriptionsPerTurn:e}}}function Un(e){return{vision:{timeoutMs:e}}}var Wn=mn,Gn=hn,Kn=1;function qn(e){let t=e.trim();if(!/^[0-9]+$/.test(t))return;let n=Number(t);if(!(!Number.isSafeInteger(n)||n<=0))return n}function Jn(e){let t=qn(e);if(!(t===void 0||t<Kn||t>Gn))return t}var Yn=[`low`,`medium`,`high`,`xhigh`,`max`];function Xn(e,t){let n=e.find(e=>e.id===t)?.reasoningEfforts;if(!n||n.length===0)return[...Yn];let r=Yn.filter(e=>n.includes(e));return r.length>0?r:[...Yn]}function Zn(e,t){let n=Qn(e,t);return e.includes(n)?e:[n,...e]}function Qn(e,t){if(e.length===0||e.includes(t))return t;let n=Yn.indexOf(t),r=e[0],i=Yn.indexOf(r);for(let t of e){let e=Yn.indexOf(t);e<=n&&e>=i&&(r=t,i=e)}return r}function $n(e){let t=[];for(let n of e)(n.provider===`openai`||n.provider===`anthropic`)&&t.push({value:n.id,label:`${n.provider}/${n.id}`});return t}function er(e,t,n,r){if(e===void 0){let e=$n(t);return n&&!e.some(e=>e.value===n)&&e.unshift({value:n,label:n,...r?{backend:r}:{},model:n}),e}let i=e.map(e=>({value:e.value,label:e.label,backend:e.backend,model:e.model}));return n&&!i.some(e=>e.value===n)&&i.unshift({value:n,label:n,...r?{backend:r}:{},model:n}),i}function tr(e,t,n,r){let i=e?e.map(e=>({value:e.value,label:e.label,backend:e.backend})):$n(t);return n&&!i.some(e=>e.value===n)&&i.unshift({value:n,label:n,...r?{backend:r}:{}}),i}function nr(e,t,n){let r=xn(n),i=r.flatMap(t=>{let n=e.find(e=>e.namespaced.startsWith(t))??e.find(e=>e.id.startsWith(t));return n?[{provider:n.provider,modelId:t}]:[]}),a=e.filter(e=>i.some(t=>e.provider===t.provider&&e.id.startsWith(t.modelId))),o=new Set([...r.flatMap(e=>[e,`openai/${e}`]),...a.flatMap(e=>[e.namespaced,`${e.provider}/${e.id}`])]),s=[{value:``,label:`—`},...e.filter(e=>!o.has(e.namespaced)).map(e=>({value:e.namespaced,label:e.namespaced}))];return t&&!o.has(t)&&!s.some(e=>e.value===t)&&s.push({value:t,label:t}),s}function rr(e,t){let n=e.find(e=>e.id===t)?.provider;return n===`anthropic`||n===`anthropic2`?`anthropic`:`openai`}function ir(e,t){function n(e,t){return t.backend!==void 0&&t.backend!==`anthropic`&&e.anthropicInstance!==void 0?{...t,anthropicInstance:null}:t}return{...t,...t.webSearch?{webSearch:n(e.webSearch,t.webSearch)}:{},...t.vision?{vision:n(e.vision,t.vision)}:{}}}function ar(e,t,n){let r=t.find(e=>e.value===n);return{backend:r?.backend??rr(e,n),model:r?.model??n}}function or(e,t,n){return t.find(e=>e.value===n)?.backend||(n.includes(`/`)?`routed`:rr(e,n))}var sr=!1;typeof window<`u`&&typeof window.addEventListener==`function`&&(window.addEventListener(`keydown`,()=>{sr=!0},{capture:!0,passive:!0}),window.addEventListener(`pointerdown`,()=>{sr=!1},{capture:!0,passive:!0}));function cr(e){if(e){if(sr)e.focus({preventScroll:!0});else try{e.focus({preventScroll:!0,focusVisible:!1})}catch{e.focus({preventScroll:!0})}}}function lr(e,t){let n=(0,Z.useRef)(null);return(0,Z.useEffect)(()=>{let r=n.current;r&&(e?r.open||r.showModal():(r.open&&r.close(),cr(t.current)))},[e,t]),(0,Z.useEffect)(()=>()=>{let e=n.current;e?.open&&e.close(),cr(t.current)},[t]),n}var ur=`https://opencodex.me/guides/subagent-v1-default/`;function dr(e){if(!e||typeof e!=`object`)return null;let t=e,n=t.mode;return n!==`v1`&&n!=="default"&&n!==`v2`||typeof t.required!=`boolean`?null:{required:t.required,mode:n,recommended:`v1`,version:typeof t.version==`number`?t.version:0,docsUrl:typeof t.docsUrl==`string`&&t.docsUrl?t.docsUrl:ur}}function fr(e){return e==="default"?`base`:e}function pr({reason:e,mode:t,docsUrl:r,busy:i=!1,onContinue:a,onChooseV1:o,onDismiss:s}){let c=n(),l=(0,Z.useId)(),u=(0,Z.useId)(),d=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{let e=d.current;e&&!e.open&&e.showModal()},[]);let f=(0,Z.useCallback)(e=>{e.preventDefault(),!i&&s()},[i,s]),p=fr(t),m=e===`advisory`;return(0,Q.jsxs)(`dialog`,{ref:d,"aria-labelledby":l,"aria-describedby":u,className:`modal-overlay`,"data-subagent-surface-reason":e,onCancel:f,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":c(`common.close`),tabIndex:-1,disabled:i,onClick:()=>{i||s()}}),(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),style:{maxWidth:480},children:[(0,Q.jsx)(`h3`,{id:l,children:c(m?`subagentSurface.advisoryTitle`:`subagentSurface.selectionTitle`,{mode:p})}),(0,Q.jsxs)(`div`,{id:u,className:`notice-warn`,style:{marginTop:12,display:`flex`,gap:8,alignItems:`flex-start`},children:[(0,Q.jsx)(Ne,{width:16,height:16,style:{flexShrink:0,marginTop:2},"aria-hidden":`true`}),(0,Q.jsx)(`p`,{className:`modal-desc`,style:{margin:0},children:c(m?`subagentSurface.advisoryBody`:`subagentSurface.selectionBody`,{mode:p})})]}),(0,Q.jsx)(`p`,{className:`text-label`,style:{marginTop:12},children:(0,Q.jsx)(`a`,{href:r,target:`_blank`,rel:`noreferrer`,style:{color:`var(--accent)`},children:c(`subagentSurface.learnMore`)})}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:i,onClick:a,children:c(`subagentSurface.continue`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:i,onClick:o,children:c(`subagentSurface.switchToV1`)})]})]})]})}function mr(e){let{t,updateOpen:n,closeUpdateDialog:r,updateDialogRef:i,updateChannel:a,changeUpdateChannel:o,updateLoading:s,updateError:c,updateCheck:l,fetchUpdateCheck:u,updateRestart:d,setUpdateRestart:f,runUpdate:p,maHelpOpen:m,setMaHelpOpen:h,maHelpDialogRef:g,effortCapHelpOpen:_,setEffortCapHelpOpen:v,effortCapHelpDialogRef:y,shadowCallHelpOpen:b,setShadowCallHelpOpen:x,shadowCallHelpDialogRef:S,shadowCall:C,maAdvisory:w,maAdvisoryOpen:T,pendingMaMode:E,maBusy:D,keepMaMode:O,chooseMaV1:k,dismissMaSurfaceDialog:A}=e;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`dialog`,{ref:i,id:`dashboard-update-dialog`,className:`modal-overlay`,style:{display:n?`flex`:`none`,border:`none`,margin:0,maxWidth:`none`,maxHeight:`none`,width:`100%`,height:`100%`},"aria-labelledby":`update-title`,onCancel:e=>{e.preventDefault(),r()},children:(0,Q.jsxs)(`div`,{className:`modal-card`,children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:`update-title`,children:t(`dash.updateTitle`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:r,"aria-label":t(`common.cancel`),children:(0,Q.jsx)(xe,{})})]}),(0,Q.jsx)(`div`,{className:`modal-desc`,children:t(`dash.updateDesc`)}),(0,Q.jsxs)(`div`,{className:`update-row`,children:[(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`update-channel`,children:t(`dash.updateChannel`)}),(0,Q.jsx)(dn,{value:a,options:[{value:`latest`,label:`latest`},{value:`preview`,label:`preview`}],onChange:e=>o(e),disabled:s,label:t(`dash.updateChannel`),portal:!1})]}),s&&(0,Q.jsx)(fn,{className:`update-empty`,icon:(0,Q.jsx)(`span`,{className:`spin`}),title:t(`dash.updateChecking`)}),c&&(0,Q.jsxs)(`div`,{className:`notice notice-err`,role:`status`,children:[(0,Q.jsx)(Ne,{}),(0,Q.jsx)(`span`,{children:c})]}),l&&!s&&(0,Q.jsxs)(`div`,{className:`update-box`,children:[(0,Q.jsxs)(`div`,{className:`spread`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`muted text-label`,children:t(`dash.updateInstalled`)}),(0,Q.jsx)(`div`,{className:`mono`,children:l.currentVersion})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`muted text-label`,children:t(`dash.updateLatest`)}),(0,Q.jsx)(`div`,{className:`mono`,children:l.latestVersion??`—`})]}),(0,Q.jsx)(`span`,{className:`badge ${l.updateAvailable?`badge-green`:`badge-muted`}`,children:l.updateAvailable?t(`dash.updateAvailable`):t(`dash.updateCurrent`)})]}),l.command&&(0,Q.jsxs)(`div`,{className:`muted update-command`,children:[t(`dash.updateCommand`),` `,(0,Q.jsx)(`code`,{className:`chip`,children:l.command})]}),l.reason===`source_checkout`&&(0,Q.jsxs)(`div`,{className:`notice-warn`,role:`status`,children:[(0,Q.jsx)(Ne,{}),` `,t(`dash.updateSource`)]}),l.reason===`latest_unavailable`&&(0,Q.jsxs)(`div`,{className:`notice-warn`,role:`status`,children:[(0,Q.jsx)(Ne,{}),` `,t(`dash.updateUnavailable`),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:s,onClick:()=>{u(a,!0)},style:{marginLeft:12},children:[(0,Q.jsx)(ae,{}),` `,t(`dash.updateRetry`)]})]}),!l.canUpdate&&l.reason!==`latest_unavailable`&&l.reason!==`source_checkout`&&(0,Q.jsxs)(`div`,{className:`update-recheck`,children:[(0,Q.jsx)(`span`,{className:`muted update-recheck-reason`,children:t(`dash.updateCannotAuto`,{reason:Pn(l.reason,t)})}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:s,onClick:()=>{u(a,!0)},children:[(0,Q.jsx)(ae,{}),` `,t(s?`dash.updateChecking`:`dash.updateRecheck`)]})]}),l.canUpdate&&(0,Q.jsxs)(`div`,{className:`spread update-restart`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:t(`dash.updateRestart`)}),(0,Q.jsx)(`div`,{className:`muted text-label`,children:t(`dash.updateRestartHint`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`switch ${d?`on`:``}`,onClick:()=>f(e=>!e),"aria-label":t(`dash.updateRestart`),"aria-pressed":d,children:(0,Q.jsx)(`span`,{className:`knob`})})]})]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:r,children:t(`common.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:p,disabled:!l?.canUpdate||s,children:t(`dash.runUpdate`)})]})]})}),(0,Q.jsxs)(`dialog`,{ref:g,id:`multi-agent-help-dialog`,className:`modal-overlay`,style:{display:m?`flex`:`none`,border:`none`,margin:0,maxWidth:`none`,maxHeight:`none`,width:`100%`,height:`100%`},"aria-labelledby":`multi-agent-help-title`,onCancel:e=>{e.preventDefault(),h(!1)},children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":t(`common.close`),tabIndex:-1,onClick:()=>h(!1)}),(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:`multi-agent-help-title`,children:t(`dash.multiAgent`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:()=>h(!1),"aria-label":t(`common.close`),children:(0,Q.jsx)(xe,{})})]}),(0,Q.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:t(`models.v2Help`)}),(0,Q.jsx)(`div`,{style:{marginTop:12},children:(0,Q.jsx)(`a`,{className:`text-control`,href:`https://opencodex.me/guides/sub-agent-surface/`,target:`_blank`,rel:`noreferrer`,style:{color:`var(--accent)`},children:t(`models.v2DocsLink`)})}),(0,Q.jsx)(`div`,{className:`modal-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>h(!1),children:t(`common.ok`)})})]})]}),(0,Q.jsxs)(`dialog`,{ref:y,id:`effort-cap-help-dialog`,className:`modal-overlay`,style:{display:_?`flex`:`none`,border:`none`,margin:0,maxWidth:`none`,maxHeight:`none`,width:`100%`,height:`100%`},"aria-labelledby":`effort-cap-help-title`,onCancel:e=>{e.preventDefault(),v(!1)},children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":t(`common.close`),tabIndex:-1,onClick:()=>v(!1)}),(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:`effort-cap-help-title`,children:t(`dash.effortCapLabel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:()=>v(!1),"aria-label":t(`common.close`),children:(0,Q.jsx)(xe,{})})]}),(0,Q.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:t(`dash.effortCapHelp`)}),(0,Q.jsx)(`div`,{className:`modal-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>v(!1),children:t(`common.ok`)})})]})]}),(0,Q.jsxs)(`dialog`,{ref:S,id:`shadow-call-help-dialog`,className:`modal-overlay`,style:{display:b?`flex`:`none`,border:`none`,margin:0,maxWidth:`none`,maxHeight:`none`,width:`100%`,height:`100%`},"aria-labelledby":`shadow-call-help-title`,onCancel:e=>{e.preventDefault(),x(!1)},children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":t(`common.close`),tabIndex:-1,onClick:()=>x(!1)}),(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:`shadow-call-help-title`,children:t(`dash.shadowCallIntercept`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:()=>x(!1),"aria-label":t(`common.close`),children:(0,Q.jsx)(xe,{})})]}),(0,Q.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:t(`dash.shadowCallTooltip`,{models:Sn(C?.sourceModels)})}),(0,Q.jsx)(`div`,{className:`modal-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>x(!1),children:t(`common.ok`)})})]})]}),(E||T)&&(0,Q.jsx)(pr,{reason:E?`selection`:`advisory`,mode:E??w?.mode??`default`,docsUrl:w?.docsUrl??`https://opencodex.me/guides/subagent-v1-default/`,busy:D,onContinue:()=>{O()},onChooseV1:()=>{k()},onDismiss:A})]})}function hr({t:e,models:t,modelsLoading:n,modelQuery:r,setModelQuery:i,filteredGroups:a,expandedProviders:o,setExpandedProviders:s}){return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`h-section`,children:[e(`dash.availableModels`),` `,(0,Q.jsx)(`span`,{className:`count`,children:t.length}),n&&(0,Q.jsx)(`span`,{className:`spin`,style:{marginLeft:4}})]}),t.length===0&&!n?(0,Q.jsx)(fn,{title:e(`dash.noModels`)}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`pws-search-wrap`,children:[(0,Q.jsx)(se,{className:`pws-search-icon`,width:14,height:14,"aria-hidden":`true`}),(0,Q.jsx)(`input`,{type:`search`,className:`input pws-search-input`,placeholder:e(`models.search`),value:r,onChange:e=>i(e.target.value),"aria-label":e(`models.search`)})]}),a.length===0?(0,Q.jsx)(`p`,{className:`muted text-control`,style:{margin:`4px 0`},children:e(`dash.modelsNoResults`)}):(0,Q.jsx)(`div`,{className:`dash-model-acc`,children:a.map(([t,n])=>{let i=r.trim().toLowerCase()!==``||o.has(t);return(0,Q.jsxs)(`div`,{className:`dash-model-group`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`dash-model-head`,onClick:()=>s(e=>{let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n}),"aria-expanded":i,children:[(0,Q.jsx)(Ye,{width:12,height:12,style:{transform:i?`rotate(90deg)`:`none`,transition:`transform .12s`,color:`var(--muted)`},"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`font-semibold`,children:Ce(t,e)}),(0,Q.jsx)(`span`,{className:`count`,children:n.length})]}),i&&(0,Q.jsx)(`div`,{className:`dash-model-chips`,children:n.map(e=>(0,Q.jsx)(`code`,{className:`dash-model-chip`,children:e.id},`${e.provider}/${e.id}`))})]},t)})})]})]})}function gr(e,t){let n=Math.max(0,Math.floor(e)),r=b(t,`uptime.day`),i=b(t,`uptime.hour`),a=b(t,`uptime.minute`),o=b(t,`uptime.second`);if(n<300)return`${n}${o}`;let s=Math.floor(n/60);if(s<60)return`${s}${a}`;let c=Math.floor(s/60);if(c<24){let e=s%60;return e>0?`${c}${i} ${e}${a}`:`${c}${i}`}let l=Math.floor(c/24),u=c%24;return u>0?`${l}${r} ${u}${i}`:`${l}${r}`}function _r(e){return!e||typeof e!=`object`||!(`usageIncomplete`in e)||e.usageIncomplete!==!0?{}:{usageIncomplete:!0,...`usageIncompleteReason`in e&&e.usageIncompleteReason===`oversized_rows`?{usageIncompleteReason:`oversized_rows`}:{}}}function vr(e){return!!e&&typeof e==`object`&&`error`in e&&e.error===`read_failed`}var yr=class extends Error{constructor(){super(`usage ledger read failed`),this.name=`UsageReadFailedError`}};async function br(e,t){let n;try{n=await e.json()}catch{throw Error(t??`${e.status} ${e.statusText}`.trim())}if(vr(n))throw new yr;if(!e.ok)throw Error(t??`${e.status} ${e.statusText}`.trim());return n}function xr(e,t=`all`){return t===`codex`?[`usage-summary-30d`,e,`codex`].join(`:`):[`usage-summary-30d`,e,`all`].join(`:`)}function Sr({data:e}){let t=n();return _r(e).usageIncomplete?(0,Q.jsx)($,{tone:`warn`,children:t(`usage.incomplete`)}):null}function Cr({locale:e,health:t,providers:r,usage30d:i,usageLoading:a,healthLoading:o,startupHealth:s,projectConfigWarnings:c,maMode:l,maBusy:u,maHelpTriggerRef:d,maHelpOpen:f,setMaHelpOpen:p,switchMaMode:m,maError:h}){let g=n(),_=t?.status===`ok`;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`dash-overview-head`,children:[(0,Q.jsxs)(`div`,{className:`stat-row`,children:[(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsxs)(`div`,{className:`label`,style:{display:`flex`,alignItems:`center`,gap:6},children:[g(`dash.multiAgent`),(0,Q.jsx)(`button`,{ref:d,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)`},onClick:()=>p(!0),"aria-label":g(`dash.multiAgent`),"aria-haspopup":`dialog`,"aria-controls":`multi-agent-help-dialog`,"aria-expanded":f,children:(0,Q.jsx)(De,{width:14,height:14,"aria-hidden":`true`})})]}),(0,Q.jsx)(`div`,{className:`value`,style:{display:`flex`,alignItems:`center`},children:(0,Q.jsx)(`div`,{className:`dash-ma-switch`,role:`radiogroup`,"aria-label":g(`dash.multiAgent`),style:{display:`inline-flex`,borderRadius:`var(--radius-pill)`,background:`var(--surface-soft, var(--raised))`,padding:3,gap:2},children:[`v1`,`default`,`v2`].map(e=>(0,Q.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":l===e,className:`btn btn-sm text-caption dash-ma-option${l===e?` btn-primary`:` btn-ghost`}`,style:{borderRadius:`var(--radius-pill)`,border:`none`,background:l===e?void 0:`transparent`,color:l===e?void 0:`var(--muted)`},disabled:u,onClick:()=>void m(e),children:g(`models.v2Mode_${e}`)},e))})}),h&&(0,Q.jsx)(`div`,{role:`alert`,className:`text-caption`,style:{color:`var(--red)`,marginTop:4,textAlign:`center`,maxWidth:280,wordBreak:`break-word`},children:h})]}),(0,Q.jsxs)(`div`,{className:`stat`,"aria-busy":o||void 0,children:[(0,Q.jsx)(`div`,{className:`label`,children:g(`dash.status`)}),(0,Q.jsxs)(`div`,{className:`value`,style:{display:`flex`,alignItems:`center`,gap:9,color:_?`var(--green)`:`var(--red)`},children:[(0,Q.jsx)(`span`,{className:`dot ${_?`dot-green`:`dot-red`}`}),g(_?`dash.online`:`dash.offline`)]})]}),(0,Q.jsxs)(`div`,{className:`stat`,"aria-busy":o||void 0,children:[(0,Q.jsx)(`div`,{className:`label`,children:g(`dash.version`)}),(0,Q.jsx)(`div`,{className:`value mono dash-stat-version`,title:t?.version,children:t?.version??`—`})]}),(0,Q.jsxs)(`div`,{className:`stat`,"aria-busy":o||void 0,children:[(0,Q.jsx)(`div`,{className:`label`,children:g(`dash.uptime`)}),(0,Q.jsx)(`div`,{className:`value mono`,children:t?gr(t.uptime,e):`—`})]}),(0,Q.jsxs)(`div`,{className:`stat`,"aria-busy":o||void 0,children:[(0,Q.jsx)(`div`,{className:`label`,children:g(`dash.providers`)}),(0,Q.jsx)(`div`,{className:`value`,children:r.length})]}),(0,Q.jsxs)(`div`,{className:`stat`,"aria-busy":a||void 0,children:[(0,Q.jsx)(`div`,{className:`label`,children:g(`dash.tokens30d`)}),(0,Q.jsx)(`div`,{className:`value mono`,children:i&&i.summary.requests>0?q(i.summary.totalTokens,e):`—`}),(0,Q.jsx)(`div`,{className:`muted text-label dash-stat-coverage`,children:i&&i.summary.requests>0?g(`dash.coverage`).replace(`{pct}`,`${Math.round(i.summary.coverageRatio*100)}%`):`\xA0`})]})]}),(0,Q.jsx)(`div`,{className:`startup-health-slot`,"aria-live":`polite`,children:s?(0,Q.jsxs)(`button`,{type:`button`,className:`startup-health-bar`,onClick:()=>Xt(`startup`),children:[(0,Q.jsx)(`span`,{className:`dot ${s===`error`?`dot-red`:s===`at-risk`?`dot-amber`:`dot-green`}`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`startup-health-bar__summary`,children:g(s===`error`?`startup.error`:s===`at-risk`?`startup.summary.atRisk`:s===`protected`?`startup.summary.protected`:`startup.summary.native`)})]}):(0,Q.jsxs)(`div`,{className:`startup-health-bar startup-health-bar--pending`,"aria-hidden":`true`,children:[(0,Q.jsx)(`span`,{className:`dot dot-amber`}),(0,Q.jsx)(`span`,{className:`startup-health-bar__summary`,children:`\xA0`})]})})]}),(0,Q.jsx)(Sr,{data:i}),c.length>0&&(0,Q.jsxs)(`div`,{className:`notice notice-err maintenance-notice`,role:`alert`,children:[(0,Q.jsx)(Ne,{}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:g(`dash.projectConfigTitle`)}),(0,Q.jsx)(`div`,{className:`muted text-control`,style:{marginTop:4},children:g(`dash.projectConfigHint`)}),(0,Q.jsx)(`ul`,{className:`text-control`,style:{margin:`10px 0 0`,paddingLeft:18},children:c.map(e=>(0,Q.jsxs)(`li`,{style:{marginBottom:8},children:[(0,Q.jsx)(`code`,{children:e.path}),` — `,e.issues.join(`, `),(0,Q.jsx)(`div`,{className:`muted`,style:{marginTop:2},children:e.bypass})]},e.path))})]})]})]})}var wr=`gpt-daybreak-blue-latest`,Tr=`gpt-6-astra`,Er=`gpt-6-sol`,Dr=`gpt-6-luna`,Or=`gpt-6.1-sol`,kr=`gpt-6.1-terra`,Ar=`gpt-6-astra-minor`,jr=Object.freeze({contextWindow:272e3,maxContextWindow:872e3,maxInputTokens:872e3});Object.freeze({...jr,contextWindow:5e5}),Object.freeze({...jr,contextWindow:5e5});var Mr=new Set([wr,Ar]),Nr=Object.freeze({[wr]:`gpt-5.6-sol`,[Ar]:Tr});Object.freeze(Object.keys(Nr)),Object.freeze({[wr]:{displayName:`Daybreak Blue`,description:`Frontier general-purpose model with safeguards for defensive cybersecurity work.`},[Ar]:{displayName:`GPT-6-Astra-Minor`,description:`Unreleased GPT-6 Astra variant; shown only when your account's Codex roster lists it.`}});var Pr=[...Object.freeze([`gpt-5.5`,`gpt-5.6-sol`,`gpt-5.6-terra`,`gpt-5.6-luna`,wr,Tr,Er,Dr,Or,kr,Ar])],Fr=new Set(Pr);[...Mr];var Ir=18e5,Lr=[`account_unavailable`,`access_denied`,`rate_limited`,`upstream_error`,`redirect_blocked`,`destination_blocked`,`dns_failed`,`timeout`,`transport_error`,`response_unusable`];function Rr(e){return Lr.find(t=>t===e)}var zr=6e4,Br=864e5;function Vr(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=Object.keys(e);if(t.length!==1||t[0]!==`ttlMs`)return;let n=e.ttlMs;return typeof n==`number`&&Number.isSafeInteger(n)&&n>=6e4&&n<=864e5?{ttlMs:n}:void 0}var Hr=1e3,Ur=12e4,Wr=4e3;function Gr(e){try{let t=e.trim();if(/[\u0000-\u001f\u007f]/.test(t))return!1;let n=t.replace(/^[a-z][a-z\d+.-]*:[/\\]*/i,``).split(/[/\\]/,1)[0]??``;if(/[?#]/.test(t)||n.includes(`@`))return!1;let r=new URL(t);if(r.username||r.password||r.search||r.hash)return!1;let i=r.hostname,a=i===`localhost`||i===`[::1]`||/^(?:(?:127|10)\.\d+|172\.(?:1[6-9]|2\d|3[01])|192\.168)\.\d+\.\d+$/.test(i)||/^\[f[cd][\da-f]{2}:/.test(i)||/^\[::ffff:7f[\da-f]{2}:/.test(i);return r.protocol===`https:`||r.protocol===`http:`&&a&&r.pathname.replace(/\/+$/,``).endsWith(`/systemone`)}catch{return!1}}function Kr(e){return e?e.adapter===`jev-decision`?e.disabled===!0?`disabled`:Gr(e.baseUrl??``)?!e.defaultModel?.trim()&&!e.models?.[0]?.trim()?`model`:null:`endpoint`:`notDecision`:`missing`}function qr(e){return e.name===`jev`?e.adapter===`jev-decision`&&e.disabled!==!0&&e.hasApiKey===!0:Kr(e)===null}var Jr={typesafe:`cws.jev.backend.typesafe`,systemone:`cws.jev.backend.systemone`,model:`cws.jev.backend.model`,unknown:`cws.jev.backend.unknown`};function Yr(e){return e.decisionModel==null?e.decisionProvider!=null&&e.decisionProvider.trim()!==`jev`?`systemone`:`typesafe`:`model`}function Xr(e,t,n){let r=e.trim(),i=e=>r===`combo/${e.id.trim()}`||!!e.alias?.trim()&&r===e.alias.trim()||!!e.model?.trim()&&r===e.model.trim();return!!n&&i(n)||t.some(e=>e.strategy===`jev`&&i(e))}function Zr(e,t,n,r){let i=new Set(t.filter(e=>!e.disabled&&e.adapter!==`jev-decision`).map(e=>e.name)),a=e.filter(e=>!e.disabled&&e.provider!==`combo`&&i.has(e.provider)).map(e=>e.namespaced?.trim()||`${e.provider}/${e.id}`);return a.push(...n.filter(e=>e.strategy!==`jev`).map(e=>e.model)),[...new Set(a)].filter(e=>!Xr(e,n,r)).sort((e,t)=>e.localeCompare(t))}var Qr=[`low`,`medium`,`high`,`xhigh`,`max`,`ultra`],$r=[`failover`,`round-robin`,`random`,`least-used`,`reset-window`,`jev`],ei={failover:`cws.strategy.failover`,"round-robin":`cws.strategy.roundRobin`,random:`cws.strategy.random`,"least-used":`cws.strategy.leastUsed`,"reset-window":`cws.strategy.resetWindow`,jev:`cws.strategy.jev`},ti={failover:`cws.strategy.failoverHint`,"round-robin":`cws.strategy.roundRobinHint`,random:`cws.strategy.randomHint`,"least-used":`cws.strategy.leastUsedHint`,"reset-window":`cws.strategy.resetWindowHint`,jev:`cws.strategy.jevHint`},ni={failover:`cws.targets.failoverHint`,"round-robin":`cws.targets.roundRobinHint`,random:`cws.targets.randomHint`,"least-used":`cws.targets.leastUsedHint`,"reset-window":`cws.targets.resetWindowHint`,jev:`cws.targets.jevHint`},ri=new Set($r),ii={missing:`cws.jev.decisionIssue.missing`,notDecision:`cws.jev.decisionIssue.notDecision`,disabled:`cws.jev.decisionIssue.disabled`,endpoint:`cws.jev.decisionIssue.endpoint`,model:`cws.jev.decisionIssue.model`};function ai(e,t,n=`strict`){let r=e.filter(e=>e.provider.trim()&&e.model.trim());if(r.length===0)return[...Qr];let i=new Set(Qr),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[...Qr];let o=new Set(a);return Qr.filter(e=>o.has(e))}var oi=Ir,si=0;function ci(e={}){return{provider:e.provider??``,model:e.model??``,...e.weight===void 0?{}:{weight:e.weight},...e.reasoningEfforts===void 0?{}:{reasoningEfforts:[...e.reasoningEfforts]},...e.modelProfile===void 0?{}:{modelProfile:e.modelProfile},clientKey:e.clientKey??`ct-${++si}`}}function li(e){return e===`disabled`?`disabled`:`auto`}function ui(e){return e===`adaptive`?`adaptive`:`strict`}var di=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/,fi=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}(\/[a-zA-Z0-9][a-zA-Z0-9._-]{0,63})?$/,pi=/^(?:gpt-|o1-|o3-|o4-|codex-)/;function mi(e){return di.test(e.trim())}function hi(e){return`combo/${e.trim()}`}function gi(e,t){return(typeof t==`string`?t.trim():``)||hi(e)}function _i(e,t){let n=t.trim(),r=e.nativeAlias&&(!n||n.includes(`/`)||!pi.test(n));return{...e,alias:n?t:null,model:gi(e.id,t),...r?{nativeAlias:!1,displayName:null}:{}}}function vi(e){let t=typeof e==`string`?e.trim():``;return t&&t!==`jev`?t:null}function yi(e){return typeof e==`number`&&Number.isInteger(e)?e:null}function bi(e){return typeof e==`string`&&e.trim()?e.trim():null}function xi(e){return typeof e==`string`&&ri.has(e)?e:`failover`}function Si(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=100?e:1}function Ci(e){return typeof e==`string`&&Qr.includes(e)?e:null}function wi(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=1e4?e:void 0}function Ti(e){if(!Array.isArray(e)||e.length===0)return;let t=[],n=new Set;for(let r of e){if(typeof r!=`string`||!Qr.includes(r))return;let e=r;if(n.has(e))return;n.add(e),t.push(e)}return t}function Ei(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=wi(t.weight),o=Ti(t.reasoningEfforts);a.push(ci({provider:n,model:r,...i===void 0?{}:{weight:i},...o===void 0?{}:{reasoningEfforts:o},...typeof t.modelProfile==`string`?{modelProfile:t.modelProfile}:{}}))}let o=vi(t.decisionProvider),s=bi(t.decisionModel),c=yi(t.decisionTimeoutMs),l=t.sessionPin===null?null:Vr(t.sessionPin);n.push({id:r,model:typeof t.model==`string`&&t.model.trim()?t.model.trim():gi(r,bi(t.alias)),alias:bi(t.alias),nativeAlias:t.nativeAlias===!0,displayName:bi(t.displayName),strategy:xi(t.strategy),stickyLimit:Si(t.stickyLimit),defaultEffort:Ci(t.defaultEffort),imageInput:li(t.imageInput),reasoningEffortMode:ui(t.reasoningEffortMode),...o===null?{}:{decisionProvider:o},...s===null?{}:{decisionModel:s},...c===null?{}:{decisionTimeoutMs:c},...l===void 0?{}:{sessionPin:l},targets:a})}return n.sort((e,t)=>e.id.localeCompare(t.id,void 0,{sensitivity:`base`}))}function Di(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 Oi(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 ki(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:null}function Ai(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function ji(e,t){let n=ki(e.routingQuota);if(!n||n.state!==`available`&&n.state!==`exhausted`)return null;let r=Ai(n.updatedAt),i=Ai(n.validUntil);return r===null||r<0||r>t||t-r>=oi||i===null||i<=t||i>r+oi?null:{state:n.state,validUntil:i}}function Mi(e,t){return ji(e,t)?.state??`unknown`}function Ni(e,t=Date.now()){if(!Array.isArray(e))return;let n;for(let r of e){let e=ki(r);if(!e||typeof e.provider!=`string`||!e.provider.trim())continue;let i=ji(e,t);i&&(n===void 0||i.validUntil<n)&&(n=i.validUntil)}return n}function Pi(e,t=Date.now()){if(!Array.isArray(e))return{};let n={};for(let r of e){let e=ki(r),i=typeof e?.provider==`string`?e.provider.trim():``;if(!e||!i)continue;let a=Mi(e,t);n[i]=Object.hasOwn(n,i)&&n[i]!==a?`unknown`:a}return n}function Fi(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 Ii(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&&Fi(i.targets,t.providerQuotaStates,t.providers)===`exhausted`&&n.push({id:i.id,model:i.model,reason:`all-targets-exhausted`});return n}function Li(e,t){return e.reasoningEfforts===void 0||t.reasoningEfforts===void 0?e.reasoningEfforts===t.reasoningEfforts:e.reasoningEfforts.length===t.reasoningEfforts.length&&e.reasoningEfforts.every((e,n)=>e===t.reasoningEfforts[n])}function Ri(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.strategy===`jev`&&((e.decisionProvider??null)!==(t.decisionProvider??null)||(e.decisionModel??null)!==(t.decisionModel??null)||(e.decisionTimeoutMs??null)!==(t.decisionTimeoutMs??null)||e.sessionPin===void 0!=(t.sessionPin===void 0)||(e.sessionPin?.ttlMs??null)!==(t.sessionPin?.ttlMs??null))||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)&&Li(e,r)&&(e.modelProfile??``)===(r.modelProfile??``)})}function zi(e,t={}){let n=e.strategy===`round-robin`||e.strategy===`random`;return{id:e.id.trim(),...t.renameFrom?{renameFrom:t.renameFrom}:{},...t.visionSidecarTargets?.length?{visionSidecarTargets:t.visionSidecarTargets}:{},combo:{targets:e.targets.map(e=>({provider:e.provider.trim(),model:e.model.trim(),...n?{weight:e.weight??1}:{},...e.reasoningEfforts===void 0?{}:{reasoningEfforts:[...e.reasoningEfforts]},...e.modelProfile?.trim()?{modelProfile:e.modelProfile.trim()}:{}})),strategy:e.strategy,defaultEffort:e.defaultEffort,imageInput:e.imageInput===`disabled`?`disabled`:`auto`,reasoningEffortMode:e.reasoningEffortMode===`adaptive`?`adaptive`:`strict`,...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()}:{},...e.strategy===`jev`?{decisionProvider:e.decisionModel?.trim()?null:vi(e.decisionProvider),decisionModel:e.decisionModel?.trim()||null,decisionTimeoutMs:e.decisionTimeoutMs??null,...e.sessionPin===void 0?{}:{sessionPin:e.sessionPin}}:{}}}}function Bi(e,t){let n=e.id.trim();if(!n)return`missingId`;if(!mi(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(!fi.test(r))return`invalidAlias`;if(r===`combo`||r.startsWith(`combo/`))return`aliasReservedNamespace`;if(!r.includes(`/`)&&pi.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&&!Fr.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`;if(n.reasoningEfforts!==void 0&&(n.reasoningEfforts.length===0||n.reasoningEfforts.some(e=>!Qr.includes(e))||new Set(n.reasoningEfforts).size!==n.reasoningEfforts.length))return`invalidReasoningEfforts`;if(n.modelProfile!==void 0&&(n.modelProfile.length>512||[...n.modelProfile].some(e=>{let t=e.charCodeAt(0);return t<32&&t!==9&&t!==10&&t!==13||t===127})))return`invalidModelProfile`}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`}if(e.strategy===`jev`&&e.sessionPin!=null&&!Vr(e.sessionPin))return`invalidSessionPin`;if(e.strategy===`jev`&&e.decisionTimeoutMs!=null&&(!Number.isInteger(e.decisionTimeoutMs)||e.decisionTimeoutMs<1e3||e.decisionTimeoutMs>12e4))return`invalidDecisionTimeout`;if(e.strategy===`jev`&&Yr(e)===`model`){let n=e.decisionModel?.trim()??``;if(!n||n.length>512||e.decisionProvider!=null||Xr(n,t.combos??[],e)||t.decisionModels&&!t.decisionModels.includes(n))return`invalidDecisionModel`}return e.strategy===`jev`&&Yr(e)===`systemone`&&(!e.decisionProvider?.trim()||Wi(e.decisionProvider,t.providers)!==null)?`invalidDecisionProvider`:e.targets.some(e=>t.providers[e.provider.trim()]?.disabled!==!0)?null:`noEnabledTarget`}function Vi(e=``){return{id:e,model:e?hi(e):`combo/`,alias:null,nativeAlias:!1,displayName:null,strategy:`failover`,stickyLimit:1,defaultEffort:null,imageInput:`auto`,reasoningEffortMode:`strict`,targets:[ci()]}}var Hi=[`gpt-6-astra`,`gpt-5.6-sol`,`gpt-5.6-luna`];function Ui(e,t,n){let r=Hi.flatMap(n=>{let r=e.find(e=>e.id===n&&(t===void 0||t.has(e.provider)));return r?[ci({provider:r.provider,model:r.id})]:[]});return{id:`jev-auto`,model:`jev-auto`,alias:`jev-auto`,nativeAlias:!1,displayName:null,strategy:`jev`,stickyLimit:1,defaultEffort:null,imageInput:`auto`,reasoningEffortMode:`adaptive`,decisionProvider:vi(n),targets:r.length>0?r:[ci()]}}function Wi(e,t){let n=vi(e);return n===null?null:Kr(Object.hasOwn(t,n)?t[n]:void 0)}function Gi(e,t){let n=e.filter(e=>e.adapter===`jev-decision`&&e.name!==`jev`).toSorted((e,t)=>e.name.localeCompare(t.name)).map(e=>{let t=Kr(e);return{id:e.name,...e.baseUrl?{baseUrl:e.baseUrl}:{},...t?{issue:t}:{}}}),r=vi(t),i=r!==null&&!n.some(e=>e.id===r)?[{id:r,issue:e.some(e=>e.name===r)?`notDecision`:`missing`}]:[];return[{id:null},...n,...i]}function Ki(e,t){if(e.strategy!==`jev`)return null;let n=vi(e.decisionProvider),r=n===null?void 0:t.find(e=>e.name===n);return{provider:n,model:e.decisionModel?.trim()||null,baseUrl:r?.baseUrl?.trim()||null,timeoutMs:e.decisionTimeoutMs??null}}var qi=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`,`ultra`],Ji=[`manual`,`auto`],Yi=300,Xi=[`manual`,`manual+auto`,`auto`],Zi={manual:`compactionRouting.triggersManual`,"manual+auto":`compactionRouting.triggersBoth`,auto:`compactionRouting.triggersAuto`},Qi=[`all`,`selected`],$i={all:`compactionRouting.sourcesAll`,selected:`compactionRouting.sourcesSelected`};function ea(e){if(!e)return`manual`;let t=e.includes(`auto`);return e.includes(`manual`)?t?`manual+auto`:`manual`:t?`auto`:`manual`}function ta(e){if(e===`auto`)return[`auto`];if(e===`manual+auto`)return[`manual`,`auto`]}function na(e){let t=new Map;for(let n of Ei(e))t.set(n.model,[...new Set(n.targets.flatMap(e=>e.provider?[e.provider]:[]))]);return t}function ra(e){let t=e.compactionRouting;if(t==null)return null;if(!t||typeof t!=`object`||!(`model`in t)||typeof t.model!=`string`||!t.model.trim())throw Error(`invalid settings`);let n=`reasoningEffort`in t?t.reasoningEffort:void 0;if(n!==void 0&&(typeof n!=`string`||!qi.includes(n)))throw Error(`invalid effort`);let r=`triggers`in t?t.triggers:void 0,i=`sourceModels`in t?t.sourceModels:void 0;if(i!==void 0&&(!Array.isArray(i)||!i.length||!i.every(e=>typeof e==`string`&&e.trim())))throw Error(`invalid sourceModels`);if(r!==void 0&&(!Array.isArray(r)||r.length===0||!r.every(e=>typeof e==`string`&&Ji.includes(e))||new Set(r).size!==r.length))throw Error(`invalid triggers`);return{model:t.model,...n?{reasoningEffort:n}:{},...r?{triggers:r}:{},...i?{sourceModels:i}:{}}}function ia(e){if(!e)return``;try{return new URL(e).hostname||e}catch{return e}}function aa(e,t){let n=t.get(e);return n?`${e} (${n})`:e}function oa(e){return(0,Q.jsx)(sa,{...e},e.apiBase)}function sa({apiBase:e,models:t,providers:r=[]}){let i=n(),[a,o]=(0,Z.useState)(void 0),[s,c]=(0,Z.useState)(``),[l,u]=(0,Z.useState)(``),[d,f]=(0,Z.useState)(`manual`),[p,m]=(0,Z.useState)(`all`),[h,g]=(0,Z.useState)([]),[_,v]=(0,Z.useState)(``),[y,b]=(0,Z.useState)(!1),[x,S]=(0,Z.useState)(!1),[C,w]=(0,Z.useState)(null),[T,E]=(0,Z.useState)(()=>new Map),D=(0,Z.useRef)(!1),O=(0,Z.useRef)(null),k=(0,Z.useCallback)(e=>{o(e),c(e?.model??``),u(e?.reasoningEffort??``),f(ea(e?.triggers)),m(e?.sourceModels?`selected`:`all`),g(e?.sourceModels??[])},[]),A=e=>{g(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]),w(null)},j=(0,Z.useCallback)(async()=>{if(O.current)return;let t=M(15e3);O.current=t,S(!1);try{let n=ra(await jn(await fetch(`${e}/api/settings`,{signal:t.signal})));D.current&&O.current===t&&k(n);let r=await fetch(`${e}/api/combos`,{signal:t.signal}).then(jn).then(na).catch(()=>new Map);D.current&&O.current===t&&E(r)}catch{D.current&&O.current===t&&S(!0)}finally{t.clear(),O.current===t&&(O.current=null)}},[e,k]);(0,Z.useEffect)(()=>{D.current=!0;let e=window.setTimeout(()=>{j()},0);return()=>{window.clearTimeout(e),D.current=!1,O.current?.controller.abort(),O.current?.clear(),O.current=null}},[j]);let N=async()=>{if(O.current||a===void 0)return;let t=M(15e3);O.current=t,b(!0),w(null);try{let n=ra(await jn(await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({compactionRouting:s?{model:s,...l?{reasoningEffort:l}:{},...ta(d)?{triggers:ta(d)}:{},...p===`selected`&&h.length>0?{sourceModels:h}:{}}:null}),signal:t.signal})));D.current&&O.current===t&&(k(n),w(`saved`))}catch{D.current&&O.current===t&&w(`failed`)}finally{t.clear(),D.current&&O.current===t&&b(!1),O.current===t&&(O.current=null)}},P=[{value:``,label:i(`compactionRouting.currentModel`)},...[...new Set([...t.map(e=>e.namespaced),...s?[s]:[]])].map(e=>({value:e,label:we(e,i)}))],F=[...new Set([...r.map(e=>e.name),...t.flatMap(e=>e.provider?[e.provider]:[])])].map(e=>`${e}/*`),I=new Set([...F,...t.map(e=>e.namespaced)]),L=(a?.sourceModels??[]).filter(e=>!I.has(e)),R=y||a===void 0||x,z=a?.sourceModels?`selected`:`all`,B=new Set(a?.sourceModels),V=s!==(a?.model??``)||l!==(a?.reasoningEffort??``)||d!==ea(a?.triggers)||p!==z||p===`selected`&&(h.length!==(a?.sourceModels?.length??0)||h.some(e=>!B.has(e))),H=p===`selected`&&h.length===0,U=new Set(h),ee=[...new Set(t.map(e=>e.namespaced))].filter(e=>e.toLowerCase().includes(_.trim().toLowerCase())),W=e=>(0,Q.jsxs)(`label`,{children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:U.has(e),disabled:R,onChange:()=>{A(e)}}),(0,Q.jsx)(`span`,{children:e})]},e),te=T.get(s),G=te!==void 0||s.startsWith(hi(``)),ne=s.slice(0,Math.max(s.indexOf(`/`),0)),K=new Map(r.map(e=>[e.name,ia(e.baseUrl)]).filter(([,e])=>e)),re=G?``:aa(ne||s,K),q=te?.map(e=>aa(e,K)).join(`, `)||i(`compactionRouting.comboProvidersUnknown`),J=d!==`manual`,Y=h.join(`, `),ie=!s||H?null:G?p===`selected`?i(`compactionRouting.comboWarningScoped`,{combo:s,providers:q,sources:Y}):i(`compactionRouting.comboWarning`,{combo:s,providers:q}):p===`selected`?i(`compactionRouting.providerWarningScoped`,{provider:re,sources:Y}):i(`compactionRouting.providerWarning`,{provider:re});return(0,Q.jsxs)(`section`,{className:`panel`,"aria-labelledby":`compaction-routing-title`,"aria-busy":y||a===void 0&&!x,children:[(0,Q.jsxs)(`div`,{className:`spread`,style:{alignItems:`flex-start`,flexWrap:`wrap`},children:[(0,Q.jsxs)(`div`,{style:{flex:`1 1 20rem`,minWidth:0},children:[(0,Q.jsx)(`div`,{className:`font-semibold`,id:`compaction-routing-title`,children:i(`compactionRouting.title`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:i(`compactionRouting.description`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:i(`compactionRouting.dataNotice`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:i(`compactionRouting.effortHint`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:i(`compactionRouting.sourcesHint`)})]}),(0,Q.jsxs)(`div`,{className:`dash-delegation-controls compaction-routing-controls`,style:{flex:`0 1 auto`},children:[(0,Q.jsxs)(`div`,{className:`compaction-field`,children:[(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`compaction-routing-model`,children:i(`compactionRouting.model`)}),(0,Q.jsx)(dn,{id:`compaction-routing-model`,value:s,options:P,disabled:R,label:i(`compactionRouting.model`),onChange:e=>{c(e),e||(u(``),f(`manual`),m(`all`),g([])),w(null)}})]}),(0,Q.jsxs)(`div`,{className:`compaction-field`,children:[(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`compaction-routing-triggers`,children:i(`compactionRouting.triggers`)}),(0,Q.jsx)(dn,{id:`compaction-routing-triggers`,value:d,disabled:R||!s,align:`right`,label:i(`compactionRouting.triggers`),options:Xi.map(e=>({value:e,label:i(Zi[e])})),onChange:e=>{f(e),w(null)}})]}),(0,Q.jsxs)(`div`,{className:`compaction-field`,children:[(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`compaction-routing-sources`,children:i(`compactionRouting.sources`)}),(0,Q.jsx)(dn,{id:`compaction-routing-sources`,value:p,disabled:R||!s,align:`right`,label:i(`compactionRouting.sources`),options:Qi.map(e=>({value:e,label:i($i[e])})),onChange:e=>{m(e),w(null)}})]}),(0,Q.jsxs)(`div`,{className:`compaction-field`,children:[(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`compaction-routing-effort`,children:i(`compactionRouting.effort`)}),(0,Q.jsx)(dn,{id:`compaction-routing-effort`,value:l,disabled:R||!s,align:`right`,label:i(`compactionRouting.effort`),options:[{value:``,label:i(`compactionRouting.currentEffort`)},...qi.map(e=>({value:e,label:i(`models.reasoningEffort.${e}`)}))],onChange:e=>{u(e),w(null)}})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:R||!V||H,onClick:()=>{N()},children:i(y?`common.saving`:`common.save`)})]})]}),s&&p===`selected`&&(0,Q.jsxs)(`div`,{className:`compaction-sources-block`,children:[(0,Q.jsx)(`div`,{className:`field-label compaction-sources-title`,children:i(`compactionRouting.sourcesGridTitle`)}),(0,Q.jsxs)(`div`,{className:`source-scope-groups`,children:[F.length>0&&(0,Q.jsxs)(`fieldset`,{className:`source-scope-group`,children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:i(`compactionRouting.sourcesProviders`)}),F.map(W)]}),t.length>0&&(0,Q.jsxs)(`fieldset`,{className:`source-scope-group`,children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:i(`compactionRouting.sourcesModels`)}),(0,Q.jsx)(`input`,{type:`search`,className:`input`,value:_,disabled:R,"aria-label":i(`pws.modelSearchPlaceholder`),placeholder:i(`pws.modelSearchPlaceholder`),onChange:e=>v(e.target.value)}),ee.slice(0,Yi).map(W),ee.length>Yi&&(0,Q.jsx)(`p`,{className:`muted text-label`,children:i(`pws.modelsTruncated`,{shown:Yi,total:ee.length})})]}),L.length>0&&(0,Q.jsxs)(`fieldset`,{className:`source-scope-group`,children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:i(`compactionRouting.sourcesSaved`)}),L.map(W)]}),H&&(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:i(`compactionRouting.sourcesNone`)})]})]}),ie&&(0,Q.jsxs)(`div`,{className:`notice-warn`,role:`note`,style:{marginTop:12},children:[(0,Q.jsx)(Ne,{width:14}),` `,ie]}),s&&J&&(0,Q.jsxs)(`div`,{className:`notice-warn`,role:`note`,style:{marginTop:12},children:[(0,Q.jsx)(Ne,{width:14}),` `,i(`compactionRouting.autoNotice`)]}),x&&(0,Q.jsxs)(`div`,{className:`notice notice-err`,role:`alert`,style:{marginTop:12,marginBottom:0},children:[i(`compactionRouting.loadFailed`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{j()},children:i(`common.retry`)})]}),C===`failed`&&(0,Q.jsx)(`div`,{className:`notice notice-err`,role:`alert`,style:{marginTop:12,marginBottom:0},children:i(`compactionRouting.saveFailed`)}),C===`saved`&&(0,Q.jsx)(`div`,{className:`muted setting-hint`,role:`status`,children:i(`compactionRouting.saved`)})]})}function ca(e){if(!(`reasoningRetention`in e))throw Error(`Missing reasoningRetention settings`);return e.reasoningRetention??null}function la({apiBase:e}){let t=n();return(0,Q.jsxs)(`details`,{className:`panel`,children:[(0,Q.jsx)(`summary`,{className:`font-semibold`,children:t(`reasoningRetention.advanced`)}),(0,Q.jsx)(ua,{apiBase:e},e)]})}function ua({apiBase:e}){let t=n(),[r,i]=(0,Z.useState)(),[a,o]=(0,Z.useState)(!1),[s,c]=(0,Z.useState)(`20`),[l,u]=(0,Z.useState)(`100000`),[d,f]=(0,Z.useState)(!1),[p,m]=(0,Z.useState)(!1),[h,g]=(0,Z.useState)(null),_=(0,Z.useRef)(!1),v=(0,Z.useRef)(null),y=(0,Z.useCallback)(e=>{i(e),o(e?.enabled===!0),c(String(e?.maxContextPercent??20)),u(String(e?.maxTokens??1e5))},[]),b=(0,Z.useCallback)(async()=>{if(v.current)return;let t=M(15e3);v.current=t,m(!1);try{let n=ca(await jn(await fetch(`${e}/api/settings`,{signal:t.signal})));_.current&&v.current===t&&y(n)}catch{_.current&&v.current===t&&m(!0)}finally{t.clear(),v.current===t&&(v.current=null)}},[e,y]);(0,Z.useEffect)(()=>{_.current=!0;let e=window.setTimeout(()=>{b()},0);return()=>{window.clearTimeout(e),_.current=!1,v.current?.controller.abort(),v.current?.clear(),v.current=null}},[b]);let x=s.trim()!==``&&Number.isFinite(Number(s))&&Number(s)>0&&Number(s)<=100,S=l.trim()!==``&&Number.isSafeInteger(Number(l))&&Number(l)>0,C=!a||x&&S,w=a!==(r?.enabled===!0)||a&&(Number(s)!==(r?.maxContextPercent??20)||Number(l)!==(r?.maxTokens??1e5)),T=async(t=!1)=>{if(v.current||r===void 0||!t&&!C)return;let n=M(15e3);v.current=n,f(!0),g(null);try{let r=ca(await jn(await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},signal:n.signal,body:JSON.stringify({reasoningRetention:t?null:a?{enabled:!0,maxContextPercent:Number(s),maxTokens:Number(l)}:{enabled:!1}})})));_.current&&v.current===n&&(y(r),g(`saved`))}catch{_.current&&v.current===n&&g(`failed`)}finally{n.clear(),_.current&&v.current===n&&f(!1),v.current===n&&(v.current=null)}},E=d||r===void 0||p;return(0,Q.jsxs)(`section`,{"aria-labelledby":`reasoning-retention-title`,"aria-busy":d||r===void 0&&!p,children:[(0,Q.jsx)(`div`,{className:`font-semibold`,id:`reasoning-retention-title`,children:t(`reasoningRetention.title`)}),(0,Q.jsx)(`p`,{className:`muted setting-hint`,children:t(`reasoningRetention.description`)}),(0,Q.jsx)(`p`,{className:`muted setting-hint`,children:t(`reasoningRetention.storageHint`)}),(0,Q.jsx)(ln,{on:a,disabled:E,label:t(`reasoningRetention.enable`),showLabel:!0,onClick:()=>{o(e=>!e),g(null)}}),(0,Q.jsxs)(`div`,{className:`row`,style:{flexWrap:`wrap`,alignItems:`flex-end`},children:[a&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`label`,{className:`field-label`,htmlFor:`reasoning-retention-percent`,children:[t(`reasoningRetention.percent`),(0,Q.jsx)(`input`,{id:`reasoning-retention-percent`,className:`input`,type:`number`,min:`0`,max:`100`,step:`any`,value:s,disabled:E,"aria-invalid":!x||void 0,"aria-describedby":x?void 0:`reasoning-retention-error`,onInput:e=>{c(e.currentTarget.value),g(null)}})]}),(0,Q.jsxs)(`label`,{className:`field-label`,htmlFor:`reasoning-retention-tokens`,children:[t(`reasoningRetention.tokens`),(0,Q.jsx)(`input`,{id:`reasoning-retention-tokens`,className:`input`,type:`number`,min:`1`,step:`1`,value:l,disabled:E,"aria-invalid":!S||void 0,"aria-describedby":S?void 0:`reasoning-retention-error`,onInput:e=>{u(e.currentTarget.value),g(null)}})]})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:E||!C||!w,onClick:()=>{T()},children:t(`common.save`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:E||r===null&&!w,onClick:()=>{T(!0)},children:t(`reasoningRetention.reset`)})]}),!C&&(0,Q.jsx)(`div`,{id:`reasoning-retention-error`,className:`notice notice-err`,role:`alert`,children:t(`reasoningRetention.invalid`)}),p&&(0,Q.jsxs)(`div`,{className:`notice notice-err`,role:`alert`,children:[t(`reasoningRetention.loadFailed`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{b()},children:t(`common.retry`)})]}),h===`failed`&&(0,Q.jsx)(`div`,{className:`notice notice-err`,role:`alert`,children:t(`reasoningRetention.saveFailed`)}),h===`saved`&&(0,Q.jsx)(`div`,{className:`muted setting-hint`,role:`status`,children:t(`reasoningRetention.saved`)})]})}var da=0;function fa(e){let t=e.split(/\n{2,}/).map(e=>e.trim()).filter(e=>e.length>0);return t.length>0?t:[e]}function pa(e,t,n,r){let i=o[e],a=`opencodex-action-dialog-${++da}`,s=document.activeElement,c=typeof s?.focus==`function`?s:null,l=!1,u=document.createElement(`dialog`);u.id=a,u.className=`modal-overlay`,u.setAttribute(`aria-labelledby`,`${a}-body`);let d=document.createElement(`button`);d.type=`button`,d.className=`modal-backdrop-dismiss`,d.tabIndex=-1,d.setAttribute(`aria-label`,i[`common.close`]);let f=document.createElement(`form`);f.className=`modal-card`;let p=e=>{if(!l){l=!0,window.removeEventListener(`hashchange`,m),window.removeEventListener(`popstate`,m),document.removeEventListener(`keydown`,h),r?.removeEventListener(`abort`,m);try{u.open&&typeof u.close==`function`&&u.close(),u.remove(),c?.isConnected&&c.focus()}finally{n(e)}}};function m(){p(t)}function h(e){e.key===`Escape`&&p(t)}return d.addEventListener(`click`,()=>p(t)),u.addEventListener(`cancel`,e=>{e.preventDefault(),p(t)}),window.addEventListener(`hashchange`,m),window.addEventListener(`popstate`,m),r?.addEventListener(`abort`,m),u.append(d,f),document.body.append(u),typeof u.showModal==`function`?u.showModal():(u.setAttribute(`open`,``),document.addEventListener(`keydown`,h)),{form:f,bodyId:`${a}-body`,finish:p}}function ma(e,t,n,r=`div`){let i=document.createElement(r);i.id=t;for(let e of fa(n)){let t=document.createElement(`p`);t.className=`modal-desc`,t.textContent=e,i.append(t)}return e.append(i),i}function ha(e){let t=e.locale??l(),n=o[t],r=e.tone===`danger`;return new Promise(i=>{if(e.signal?.aborted){i(!1);return}let{form:a,bodyId:o,finish:s}=pa(t,!1,i,e.signal);ma(a,o,e.message);let c=document.createElement(`div`);c.className=`modal-actions`;let l=document.createElement(`button`);l.type=`button`,l.className=`btn btn-ghost`,l.textContent=n[`common.cancel`],l.addEventListener(`click`,()=>s(!1));let u=document.createElement(`button`);u.type=`submit`,u.className=r?`btn btn-danger`:`btn btn-primary`,u.textContent=e.confirmLabel??n[`common.ok`],a.addEventListener(`submit`,e=>{e.preventDefault(),s(!0)}),c.append(l,u),a.append(c),queueMicrotask(()=>(r?l:u).focus())})}function ga(e){let t=e.locale??l(),n=o[t];return new Promise(r=>{if(e.signal?.aborted){r(null);return}let{form:i,bodyId:a,finish:o}=pa(t,null,r,e.signal),s=document.createElement(`input`),c=`${a}-input`,l=ma(i,a,e.message,`label`);l.className=`field-label`,l.setAttribute(`for`,c),s.id=c,s.className=`input`,s.type=`text`,s.value=e.initialValue??``,s.spellcheck=!1,s.autocapitalize=`none`,e.maxLength!==void 0&&(s.maxLength=e.maxLength);let u=document.createElement(`div`),d=`${a}-error`;u.id=d,u.className=`notice notice-err`,u.setAttribute(`role`,`alert`),u.hidden=!0;let f=e=>{u.textContent=e??``,u.hidden=e===null,e===null?(s.removeAttribute(`aria-invalid`),s.removeAttribute(`aria-describedby`)):(s.setAttribute(`aria-invalid`,`true`),s.setAttribute(`aria-describedby`,d))},p=document.createElement(`div`);p.className=`modal-actions`;let m=document.createElement(`button`);m.type=`button`,m.className=`btn btn-ghost`,m.textContent=n[`common.cancel`],m.addEventListener(`click`,()=>o(null));let h=document.createElement(`button`);h.type=`submit`,h.className=`btn btn-primary`,h.textContent=e.confirmLabel??n[`common.save`],i.addEventListener(`submit`,t=>{t.preventDefault();let n=s.value,r=e.validate?.(n)??null;f(r),r===null?o(n):(h.disabled=!0,s.focus())}),s.addEventListener(`input`,()=>{h.disabled&&=!1,u.hidden||f(null)}),p.append(m,h),i.append(s,u,p),queueMicrotask(()=>s.focus())})}function _a(){return pt()}function va(e,t){return typeof window<`u`&&typeof window.setInterval==`function`?window.setInterval(e,t):setInterval(e,t)}function ya(e){typeof window<`u`&&typeof window.clearInterval==`function`?window.clearInterval(e):clearInterval(e)}function ba(e,t,n){let r=n?.pauseWhenHidden!==!1,i=null,a=!1,o=()=>{try{e()}catch(e){console.error(`[visibility-poll]`,e)}},s=()=>{i!==null||a||(i=va(o,t))},c=()=>{i!==null&&(ya(i),i=null)},l=()=>{r&&(_a()?c():(o(),s()))};r&&_a()||s();let u=r?mt(l):null;return n?.immediate&&o(),()=>{a=!0,c(),u?.()}}var xa=new Map;function Sa(e,t){let n=`${e}:${t}`,r=xa.get(n);return r||(r=new Intl.NumberFormat(e,{minimumFractionDigits:t,maximumFractionDigits:t}),xa.set(n,r)),r}var Ca=new Map;function wa(e){let t=Ca.get(e);return t||(t=new Intl.NumberFormat(e),Ca.set(e,t)),t}function Ta(e,t){if(!Number.isFinite(e)||e<=0)return`0 B`;let n=[`B`,`KiB`,`MiB`,`GiB`,`TiB`],r=Math.min(Math.floor(Math.log(e)/Math.log(1024)),n.length-1),i=e/1024**r;return`${Sa(t,r===0?0:1).format(i)} ${n[r]}`}function Ea(e,t){return!Number.isFinite(e)||e<0?`—`:gr(e/1e3,t)}function Da(e){return typeof e.observedBytes==`number`?e.observedBytes:Math.max(e.rss,e.external??0,e.arrayBuffers??0)}function Oa(e){if(e.observedMetric)return e.observedMetric;if(e.watchdog?.observedMetric)return e.watchdog.observedMetric;let t=[{metric:`rss`,bytes:e.rss},{metric:`external`,bytes:e.external??0},{metric:`arrayBuffers`,bytes:e.arrayBuffers??0}];return t.reduce((e,t)=>t.bytes>e.bytes?t:e,t[0]).metric}function ka(e){if(e.length<2)return null;let t=e[0],n=e[e.length-1],r=n.at-t.at;return r<=0?null:(Da(n)-Da(t))/r*36e5}function Aa({label:e,value:t,sub:n,tone:r}){return(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`label`,children:e}),(0,Q.jsx)(`div`,{className:`value mono${r?` value--${r}`:``}`,children:t}),n&&(0,Q.jsx)(`div`,{className:`stat-sub mono`,children:n})]})}function ja({observedBytes:e,thresholdBytes:t,metric:n,locale:r,t:i}){let a=e!==null&&t!==null&&t>0?e/t:null,o=a===null?`unknown`:a>=1?`over`:a>=.75?`warn`:`ok`,s=a===null?null:Math.round(a*100);return(0,Q.jsxs)(`div`,{className:`mem-pressure mem-pressure--${o}`,children:[(0,Q.jsxs)(`div`,{className:`mem-pressure-head`,children:[(0,Q.jsxs)(`span`,{className:`mem-pressure-label`,children:[i(`dash.mem.pressure`),n?(0,Q.jsx)(`span`,{className:`mem-pressure-metric mono`,children:n}):null]}),(0,Q.jsxs)(`span`,{className:`mem-pressure-figure mono`,children:[e===null?`—`:Ta(e,r),t!==null&&(0,Q.jsxs)(`span`,{className:`mem-pressure-limit`,children:[` / `,Ta(t,r)]})]})]}),(0,Q.jsx)(`div`,{className:`mem-pressure-track`,role:`presentation`,children:(0,Q.jsx)(`span`,{className:`mem-pressure-fill`,style:{"--mem-scale":String(a===null?0:Math.min(1,Math.max(.01,a)))}})}),(0,Q.jsx)(`div`,{className:`mem-pressure-foot`,children:s===null?i(`dash.mem.pressureUnknown`):i(`dash.mem.pressureOf`,{pct:s})})]})}var Ma=60,Na=1500,Pa=12e4;function Fa({apiBase:e}){let{locale:t,t:n}=r(),[i,a]=(0,Z.useState)(null),[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(`idle`),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)(!1),[m,h]=(0,Z.useState)(!1),[g,_]=(0,Z.useState)(null);(0,Z.useEffect)(()=>{let t=!1;return(async()=>{try{let n=await fetch(`${e}/api/startup-health`);if(!n.ok||t)return;let r=await n.json();t||p(r.protection===`none`)}catch{}})(),()=>{t=!0}},[e]),(0,Z.useEffect)(()=>{let t=!1,n=!1,r=null,i=async()=>{if(n)return;n=!0;let i=M(1e4);r=i;try{let n=await fetch(`${e}/api/system/memory`,{signal:i.signal});if(!n.ok)throw Error(`memory unavailable`);let r=await n.json();if(t)return;a(r),s(!1),h(typeof r.activeTurnCount==`number`),r.isDraining&&c===`idle`&&l(`draining`),(c===`draining`||c===`reconnecting`)&&g!=null&&typeof r.pid==`number`&&r.pid!==g&&!r.isDraining&&(l(`idle`),_(null),d(null))}catch{if(t)return;c===`draining`||c===`reconnecting`?l(`reconnecting`):s(!0)}finally{i.clear(),r===i&&(r=null),n=!1}};i();let o=ba(()=>void i(),5e3);return()=>{t=!0,r?.controller.abort(),r?.clear(),o()}},[e,c,g]),(0,Z.useEffect)(()=>{if(c!==`reconnecting`)return;let t=!1,r=!1,i=null,a=Date.now(),o=()=>{if(r||t)return;r=!0;let o=M(5e3);i=o,fetch(`${e}/api/system/health`,{cache:`no-store`,signal:o.signal}).then(async e=>{if(t)return;if(!e.ok){Date.now()-a>=Pa&&(l(`error`),d(n(`dash.mem.restartFailed`)));return}let r=g==null;if(g!=null)try{let t=await e.json();r=typeof t.pid==`number`&&t.pid!==g}catch{r=!0}t||(r?(l(`idle`),_(null),d(null)):Date.now()-a>=Pa&&(l(`error`),d(n(`dash.mem.restartFailed`))))}).catch(()=>{t||Date.now()-a>=Pa&&(l(`error`),d(n(`dash.mem.restartFailed`)))}).finally(()=>{o.clear(),i===o&&(i=null),r=!1})};o();let s=setInterval(o,Na);return()=>{t=!0,i?.controller.abort(),i?.clear(),clearInterval(s)}},[e,c,g,n]);let v=async()=>{let t=i?.activeTurnCount??0,r=[n(`dash.mem.restartConfirm`,{count:t,seconds:Ma})];if(f&&r.push(n(`dash.mem.restartNoSupervisor`)),await ha({message:r.join(`
1
+ import{A as e,C as t,D as n,E as r,M as i,N as a,O as o,P as s,S as c,T as l,_ as u,a as d,b as f,c as p,d as m,f as h,g,h as _,i as v,j as y,k as b,l as x,m as S,n as C,o as w,p as T,r as E,s as D,t as O,u as k,v as A,w as j,x as M,y as N}from"./index-BmLjL__g.js";import{$ as P,A as F,At as I,B as L,Bt as R,C as z,Ct as B,D as V,Dt as H,E as U,Et as ee,F as W,Ft as te,G,H as ne,I as K,It as re,J as q,K as J,L as Y,Lt as ie,M as X,Mt as ae,N as oe,Nt as se,O as ce,Ot as le,P as ue,Pt as de,Q as fe,R as pe,Rt as me,S as he,St as ge,T as _e,Tt as ve,U as ye,V as be,Vt as xe,W as Se,X as Ce,Y as we,Z as Te,_ as Ee,_t as De,at as Oe,b as ke,bt as Ae,ct as je,dt as Me,et as Ne,ft as Pe,g as Fe,gt as Ie,h as Le,ht as Re,it as ze,j as Be,jt as Ve,k as He,kt as Ue,lt as We,m as Ge,mt as Ke,n as qe,nt as Je,ot as Ye,pt as Xe,q as Ze,rt as Qe,st as $e,t as et,tt,ut as nt,v as rt,vt as it,w as at,wt as ot,x as st,xt as ct,y as lt,yt as ut,z as dt,zt as ft}from"./quota-summary-D7vPARtH.js";var Z=s(a(),1);function pt(){return typeof document<`u`&&document.visibilityState===`hidden`||typeof window<`u`&&window.__OPENCODEX_HOST_VISIBLE__===!1}function mt(e){let t=pt(),n=()=>{let n=pt();n!==t&&(t=n,e())},r=e=>{let t=e.detail;typeof window<`u`&&typeof t==`boolean`&&(window.__OPENCODEX_HOST_VISIBLE__=t),n()};return typeof document<`u`&&document.addEventListener(`visibilitychange`,n),typeof window<`u`&&window.addEventListener(`opencodex:host-visibility`,r),()=>{typeof document<`u`&&document.removeEventListener(`visibilitychange`,n),typeof window<`u`&&window.removeEventListener(`opencodex:host-visibility`,r)}}var ht=new Map,gt=new Set,_t=3e4,vt=`ocx-resource-deadline`,yt={data:void 0,error:void 0,loading:!1,refreshing:!1,hasSucceeded:!1,lastAttemptOk:!1};function bt(e){let t=ht.get(e);return t||(t={key:e,snapshot:{data:void 0,error:void 0,loading:!1,refreshing:!1,hasSucceeded:!1,lastAttemptOk:!1},listeners:new Set,pollByListener:new Map,pauseWhenHiddenByListener:new Map,fetcherByListener:new Map,deadlineByListener:new Map,subscriberCount:0,pollIntervalMs:void 0,inflight:null,inflightOwner:null,generation:0,seedNeedsRevalidate:!1,lastSettledAt:void 0},ht.set(e,t)),t}function xt(e){for(let t of e.listeners)t()}var St=new Map;function Ct(e){for(let[t,n]of e.pollByListener)if(typeof n==`number`&&n>0&&e.pauseWhenHiddenByListener.get(t)===!1)return!0;return!1}function wt(e){if(e.stores.size===0)return!1;if(!At())return!0;for(let t of e.stores)if(Ct(t))return!0;return!1}function Tt(e){for(let t of e.stores){let e=jt(t);e&&Lt(t,e.fetcher,{replaceInflight:!1,owner:e.owner,deadlineMs:e.deadlineMs})}}function Et(e,t){let n=wt(t);n&&t.timer===null?t.timer=setInterval(()=>Tt(t),e):(!n&&t.timer!==null&&(clearInterval(t.timer),t.timer=null),t.stores.size===0&&St.delete(e))}function Dt(){for(let[e,t]of[...St])Et(e,t)}function Ot(e){let t=e.pollIntervalMs;if(t===void 0)return;let n=St.get(t);e.pollIntervalMs=void 0,n&&(n.stores.delete(e),Et(t,n))}function kt(e,t){let n=St.get(t);n||(n={timer:null,stores:new Set},St.set(t,n)),n.stores.add(e),e.pollIntervalMs=t,Et(t,n)}function At(){return pt()}function jt(e){if(!At())return Mt(e);for(let[t,n]of e.pollByListener)if(!(typeof n!=`number`||n<=0)&&e.pauseWhenHiddenByListener.get(t)===!1){let n=e.fetcherByListener.get(t);if(n)return{owner:t,fetcher:n,deadlineMs:e.deadlineByListener.get(t)}}return null}function Mt(e){for(let[t,n]of e.pollByListener)if(typeof n==`number`&&n>0){let n=e.fetcherByListener.get(t);if(n)return{owner:t,fetcher:n,deadlineMs:e.deadlineByListener.get(t)}}for(let[t,n]of e.fetcherByListener)return{owner:t,fetcher:n,deadlineMs:e.deadlineByListener.get(t)};return null}function Nt(e){let t;for(let n of e.pollByListener.values())typeof n==`number`&&n>0&&(t=t===void 0?n:Math.min(t,n));if(t===void 0)Ot(e),It(e);else if(t===e.pollIntervalMs){let n=St.get(t);n&&Et(t,n),Ft(e)}else Ot(e),kt(e,t),Ft(e)}var Pt=null;function Ft(e){typeof document>`u`||Pt||(Pt=mt(()=>{if(Dt(),!At())for(let e of St.values())for(let t of e.stores){let e=Mt(t);e&&Lt(t,e.fetcher,{replaceInflight:!1,owner:e.owner,deadlineMs:e.deadlineMs})}}))}function It(e){Pt&&(St.size>0||(Pt(),Pt=null))}async function Lt(e,t,n){let r=n?.replaceInflight!==!1;if(e.inflight&&!r)return;r&&e.inflight?.abort();let i=new AbortController;e.inflight=i,e.inflightOwner=n?.owner??null;let a=++e.generation,o=n?.deadlineMs??_t,s=!1,c=setTimeout(()=>{s=!0,i.abort(vt)},o),l=e.snapshot.data===void 0||n?.forceLoading===!0;e.snapshot={...e.snapshot,loading:l?!0:e.snapshot.loading,refreshing:!0},xt(e);try{let n=await Promise.race([t(i.signal),new Promise((e,t)=>{i.signal.addEventListener(`abort`,()=>{s?t(Error(`resource request timed out after ${o}ms`)):e(null)},{once:!0})})]);if(a!==e.generation||i.signal.aborted)return;e.seedNeedsRevalidate=!1,gt.delete(e.key),e.lastSettledAt=Date.now(),e.snapshot={data:n,error:void 0,loading:!1,refreshing:!1,hasSucceeded:!0,lastAttemptOk:!0}}catch(t){if(a!==e.generation||i.signal.aborted&&!s)return;e.seedNeedsRevalidate=!1,e.snapshot={...e.snapshot,error:t===void 0?Error(`resource load failed`):t,loading:!1,refreshing:!1,lastAttemptOk:!1}}finally{clearTimeout(c),e.inflight===i&&(e.inflight=null,e.inflightOwner=null),xt(e)}}function Rt(e,t){return e.inflightOwner===t&&(e.inflight?.abort(),e.inflight=null,e.inflightOwner=null,e.generation++,e.snapshot.refreshing&&(e.snapshot={...e.snapshot,refreshing:!1},xt(e)),!0)}function zt(e,t){Ot(t),It(t),setTimeout(()=>{t.subscriberCount===0&&ht.get(e)===t&&(t.inflight?.abort(),t.inflight=null,t.inflightOwner=null,ht.delete(e))},0)}function Bt(e,t,n){let{fetcher:r,pollMs:i,pauseWhenHidden:a=!0,deadlineMs:o,staleAfterMs:s}=n,c=bt(e);if(c.listeners.add(t),c.pollByListener.set(t,i),c.pauseWhenHiddenByListener.set(t,a),c.fetcherByListener.set(t,r),c.deadlineByListener.set(t,o),c.subscriberCount++,c.subscriberCount===1){let n=typeof s==`number`&&c.lastSettledAt!==void 0&&Date.now()-c.lastSettledAt>s;(c.snapshot.data===void 0||c.seedNeedsRevalidate||gt.has(e)||n)&&Lt(c,r,{replaceInflight:!0,owner:t,deadlineMs:o})}return Nt(c),()=>{c.listeners.delete(t),c.pollByListener.delete(t),c.pauseWhenHiddenByListener.delete(t),c.fetcherByListener.delete(t),c.deadlineByListener.delete(t),c.subscriberCount--;let n=Rt(c,t);if(c.subscriberCount===0)zt(e,c);else{if(n){let e=Mt(c);e&&Lt(c,e.fetcher,{replaceInflight:!0,owner:e.owner,deadlineMs:e.deadlineMs})}Nt(c)}}}function Vt(e,t,n,r){let i=bt(e);i.subscriberCount===0&&i.snapshot.data===void 0&&(Kt(e,t),!gt.has(e)&&typeof r==`number`&&typeof n==`number`&&Date.now()-n<r&&(i.seedNeedsRevalidate=!1,i.lastSettledAt=n))}function Ht(e,t,n){let r=n?.enabled!==!1,i=n?.pollMs,a=n?.pauseWhenHidden!==!1,o=n?.deadlineMs,s=n?.staleAfterMs;r&&n?.initialData!==void 0&&Vt(e,n.initialData,n.initialDataCachedAt,s);let c=(0,Z.useRef)(t);(0,Z.useLayoutEffect)(()=>{c.current=t});let l=(0,Z.useCallback)(e=>c.current(e),[]),u=(0,Z.useRef)(null),d=(0,Z.useCallback)(t=>r?(u.current=t,Bt(e,t,{fetcher:l,pollMs:i,pauseWhenHidden:a,deadlineMs:o,staleAfterMs:s})):()=>{},[e,l,i,r,a,o,s]),f=(0,Z.useCallback)(()=>r?bt(e).snapshot:yt,[e,r]),p=(0,Z.useSyncExternalStore)(d,f,f),m=(0,Z.useCallback)(t=>{if(!r)return;let n=bt(e);Lt(n,l,{replaceInflight:!0,owner:u.current,forceLoading:t?.forceLoading,deadlineMs:u.current?n.deadlineByListener.get(u.current):o})},[e,l,r,o]);return{...p,refresh:m}}function Ut(e,t){if(e===null)return!1;if(e.length!==t.length)return!0;for(let n=0;n<e.length;n++)if(!Object.is(e[n],t[n]))return!0;return!1}function Wt(e,t,n,r){let i=Ht(e,n,r),a=(0,Z.useRef)(null),o=(0,Z.useRef)(null);return(0,Z.useLayoutEffect)(()=>{let n=a.current,r=o.current;a.current=t,o.current=e,Ut(n,t)&&(r===null||r===e)&&i.refresh({forceLoading:!0})}),i}function Gt(e){gt.add(e);let t=ht.get(e);if(!t)return;let n=Mt(t);n&&Lt(t,n.fetcher,{replaceInflight:!0,owner:n.owner,deadlineMs:n.deadlineMs})}function Kt(e,t){let n=bt(e);n.inflight?.abort(),n.inflight=null,n.inflightOwner=null,n.generation++,n.snapshot={data:t,error:void 0,loading:!1,refreshing:!1,hasSucceeded:!0,lastAttemptOk:!0},n.seedNeedsRevalidate=n.subscriberCount===0,n.lastSettledAt=Date.now(),xt(n)}function qt(e){return e.replace(/^#\/?/,``)}function Jt(e){let t=e.indexOf(`?`);return t<0?{path:e,query:``}:{path:e.slice(0,t),query:e.slice(t+1)}}function Yt(e,t=window){let n=qt(e);if(qt(t.location.hash)===n)return;let r=`${t.location.pathname}${t.location.search}#${n}`;t.history.replaceState(t.history.state,``,r)}function Xt(e,t=window){let n=qt(e);qt(t.location.hash)!==n&&(t.location.hash=n)}var Zt=i(),Qt=4,$t=8,en=8,tn=280,nn=120,rn=160,an=12;function on(){return typeof window<`u`?window.innerHeight:800}function sn(){return typeof window<`u`?window.innerWidth:1024}function cn(e,{align:t,placement:n=`below`,menuHeight:r=tn}={}){let i=Math.min(Math.max(r,nn),tn),a=on(),o=sn();if(n===`right`){let t=a-e.top-en,n=e.top-en,r=i+$t>t&&n>t,s=Math.max(en,Math.min(e.right+an,o-rn-en));return r?{position:`fixed`,left:s,bottom:a-e.top+$t,minWidth:rn,maxHeight:Math.max(nn,Math.min(tn,e.top-en-Qt))}:{position:`fixed`,top:e.top,left:s,minWidth:rn,maxHeight:Math.max(nn,Math.min(tn,a-e.top-en))}}let s=t??(e.right>o/2?`right`:`left`),c=Math.max(e.width,0),l=a-e.bottom-en,u=e.top-en;if(i+Qt>l&&u>l){let t={position:`fixed`,bottom:a-e.top+$t,minWidth:c,maxHeight:Math.max(0,Math.min(tn,u-Qt))};return s===`right`?t.right=Math.max(en,o-e.right):t.left=Math.max(en,Math.min(e.left,o-en-c)),t}let d={position:`fixed`,top:e.bottom+Qt,minWidth:c,maxHeight:Math.max(0,Math.min(tn,l-Qt))};return s===`right`?d.right=Math.max(en,o-e.right):d.left=Math.max(en,Math.min(e.left,o-en-c)),d}var Q=C();function ln({on:e,mixed:t=!1,onClick:n,disabled:r,label:i,showLabel:a=!1,title:o}){let s=a&&!!i;return(0,Q.jsxs)(`button`,{type:`button`,className:`switch${e?` on`:``}${t?` mixed`:``}${s?` switch-labeled`:``}`,onClick:n,disabled:r,"aria-pressed":t?`mixed`:e,"aria-label":s?void 0:i??(e?`enabled`:`disabled`),title:o,children:[(0,Q.jsx)(`span`,{className:`knob`}),s?(0,Q.jsx)(`span`,{className:`switch-labeled-text text-label muted`,children:i}):null]})}function $({tone:e,children:t}){return(0,Q.jsxs)(`div`,{className:`notice ${e===`ok`?`notice-ok`:e===`warn`?`notice-warn`:`notice-err`}`,role:`status`,children:[e===`ok`?(0,Q.jsx)(Oe,{}):(0,Q.jsx)(Ne,{}),(0,Q.jsx)(`span`,{children:t})]})}function un({tone:e,children:t,onDismiss:n,dismissLabel:r}){return(0,Zt.createPortal)((0,Q.jsx)(`div`,{className:`toast-notice-host`,role:`presentation`,children:(0,Q.jsxs)(`div`,{className:`toast-notice notice ${e===`ok`?`notice-ok`:e===`warn`?`notice-warn`:`notice-err`}`,role:`status`,"aria-live":`polite`,children:[e===`ok`?(0,Q.jsx)(Oe,{}):(0,Q.jsx)(Ne,{}),(0,Q.jsx)(`span`,{className:`toast-notice-copy`,children:t}),n&&(0,Q.jsx)(`button`,{type:`button`,className:`toast-notice-dismiss`,onClick:n,"aria-label":r,children:`×`})]})}),document.body)}function dn({value:e,options:t,onChange:n,disabled:r,id:i,label:a,describedBy:o,title:s,style:c,align:l,placement:u,dropdownStyle:d,portal:f=!0}){let p=(0,Z.useId)(),[m,h]=(0,Z.useState)(!1),[g,_]=(0,Z.useState)(null),[v,y]=(0,Z.useState)(),b=(0,Z.useRef)(null),x=(0,Z.useRef)(null),S=(0,Z.useRef)(null),C=(0,Z.useCallback)(e=>`${p}-${e}`,[p]),w=t.find(t=>t.value===e),T=t.length===0?0:Math.max(0,t.findIndex(t=>t.value===e)),E=!m||t.length===0?T:Math.min(g??T,t.length-1),D=(0,Z.useCallback)((e=!1)=>{h(!1),_(null),e&&x.current?.focus()},[]),O=(0,Z.useCallback)(e=>{if(r||t.length===0)return;let n=Math.max(0,Math.min(t.length-1,e));_(n),h(!0)},[r,t.length]),k=(0,Z.useCallback)(e=>{if(!f)return;let t=x.current;t&&y(cn(t.getBoundingClientRect(),{align:l,placement:u,menuHeight:e}))},[l,u,f]);(0,Z.useEffect)(()=>{if(!m)return;let e=e=>{let t=e.target;b.current?.contains(t)||S.current?.contains(t)||D()};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[D,m]),(0,Z.useLayoutEffect)(()=>{if(!m||!f)return;k();let e=()=>k(S.current?.offsetHeight);return window.addEventListener(`resize`,e),window.addEventListener(`scroll`,e,!0),()=>{window.removeEventListener(`resize`,e),window.removeEventListener(`scroll`,e,!0)}},[m,t.length,f,k]),(0,Z.useLayoutEffect)(()=>{if(!m||!f||!S.current||!x.current)return;let e=S.current.offsetHeight;if(!e)return;let t=cn(x.current.getBoundingClientRect(),{align:l,placement:u,menuHeight:e});y(e=>e?.top===t.top&&e?.bottom===t.bottom&&e?.maxHeight===t.maxHeight?e:t)},[l,m,t.length,u,f]),(0,Z.useLayoutEffect)(()=>{m&&S.current&&S.current.querySelector(`[id="${C(E)}"]`)?.scrollIntoView({block:`nearest`})},[E,m,C]);let A=e=>{if(r)return;let i=t[e];i&&(n(i.value),D(!0))},j=e=>{if(!r)switch(e.key){case`ArrowDown`:e.preventDefault(),O(m?Math.min(t.length-1,E+1):T);break;case`ArrowUp`:e.preventDefault(),O(m?Math.max(0,E-1):T);break;case`Home`:e.preventDefault(),O(0);break;case`End`:e.preventDefault(),O(t.length-1);break;case`Enter`:case` `:e.preventDefault(),m?A(E):O(T);break;case`Escape`:m&&(e.preventDefault(),D(!0));break;case`Tab`:if(m){let e=t[E];e&&n(e.value),h(!1)}}},M=m&&t[E]?C(E):void 0,N=m&&!r?(0,Q.jsx)(`div`,{ref:S,id:p,className:`select-dropdown${f?` select-dropdown-portal`:``}${!f&&l===`right`?` select-dropdown-right`:``}${!f&&u===`right`?` select-dropdown-beside`:``}`,role:`listbox`,"aria-label":a,style:f?{...v,zIndex:60,...d}:d,children:t.map((t,n)=>(0,Q.jsx)(`button`,{id:C(n),type:`button`,role:`option`,tabIndex:-1,disabled:r,"aria-selected":t.value===e,className:`select-option${t.value===e?` active`:``}${n===E?` select-option-active`:``}`,onMouseEnter:()=>_(n),onClick:()=>A(n),children:t.label},t.value))}):null;return(0,Q.jsxs)(`div`,{ref:b,className:`custom-select`,style:{position:`relative`,display:`inline-block`,...c},children:[(0,Q.jsxs)(`button`,{ref:x,id:i,type:`button`,role:`combobox`,title:s,"aria-describedby":o,className:`select-trigger`,onClick:()=>{r||(m?D():O(T))},onKeyDown:j,disabled:r,"aria-haspopup":`listbox`,"aria-expanded":m,"aria-controls":m?p:void 0,"aria-activedescendant":M,"aria-label":a,children:[(0,Q.jsx)(`span`,{children:w?.label??e}),(0,Q.jsx)(Ye,{style:{width:12,height:12,color:`var(--muted)`,transform:m?`rotate(90deg)`:`none`,transition:`transform .12s`}})]}),f?N&&(0,Zt.createPortal)(N,document.body):N]})}function fn({icon:e,title:t,children:n,className:r,style:i}){return(0,Q.jsxs)(`div`,{className:r?`empty ${r}`:`empty`,style:i,children:[e,(0,Q.jsx)(`div`,{className:`title`,children:t}),n&&(0,Q.jsx)(`div`,{className:`text-control`,children:n})]})}function pn({content:e,children:t,side:n=`top`,maxWidth:r=280}){let[i,a]=(0,Z.useState)(!1),o=(0,Z.useId)(),s=(0,Z.useRef)(null),c=()=>{s.current!==null&&window.clearTimeout(s.current),s.current=window.setTimeout(()=>a(!0),150)},l=()=>{s.current!==null&&(window.clearTimeout(s.current),s.current=null),a(!1)};return(0,Z.useEffect)(()=>()=>{s.current!==null&&window.clearTimeout(s.current)},[]),(0,Q.jsxs)(`button`,{type:`button`,className:`ocx-tooltip`,onMouseEnter:c,onMouseLeave:l,onFocus:c,onBlur:l,onKeyDown:e=>{e.key===`Escape`&&l()},"aria-describedby":i?o:void 0,style:{display:`inline`,border:0,background:`transparent`,padding:0,margin:0,color:`inherit`,font:`inherit`,cursor:`inherit`},children:[t,i&&(0,Q.jsx)(`span`,{id:o,className:`ocx-tooltip-bubble ocx-tooltip-bubble--${n}`,role:`tooltip`,style:{maxWidth:r},children:e})]})}var mn=45e3,hn=2147483647;async function gn(e){if(e.status!==204){if(typeof e.text==`function`){let t=await e.text();return t.trim()?JSON.parse(t):void 0}return await e.json()}}function _n(e,t){return typeof e.error==`string`&&e.error?e.error:typeof e.message==`string`&&e.message?e.message:t}async function vn(e,t=`HTTP ${e.status}`){if(!e.ok){let n=t;try{n=_n(await e.json(),t)}catch{}throw Error(n)}return gn(e)}async function yn(e){if(!e.ok)return null;try{return await gn(e)}catch{return null}}var bn=[`gpt-6-luna`,`gpt-5.6-luna`];function xn(e){let t=Array.isArray(e)?e.filter(e=>typeof e==`string`&&e.trim()!==``).map(e=>e.trim()):[];return t.length===0?bn:t.filter(e=>!e.includes(`/`))}function Sn(e){return xn(e).join(`, `)}function Cn(e){return xn(e).map(e=>e.replace(/^gpt-/,``)).join(`, `)}function wn(e,t){return xn(t).some(t=>e.startsWith(t))}function Tn(e,t){let n=xn(t),r=n.find(t=>t!==e.id&&e.id.startsWith(t));if(r!==void 0)return{blocked:`covered`,prefix:r};if(!n.includes(e.id))return{sourceModels:[...n,e.id]};let i=n.filter(t=>t!==e.id);return i.length===0?{blocked:`last`}:{sourceModels:i}}function En(e,t,n=[`gpt-6.1-terra`,`gpt-5.6-terra`]){let r=xn(e),i=n.some(e=>e!==``&&r.some(t=>e.startsWith(t))),a=Cn(e);return i?a:`${a} (+ ${t})`}var Dn=`dashboard/update`;function On(){let e=window.location.hash.replace(/^#\/?/,``);return e===`dashboard/providers`?`providers`:e===`dashboard/models`?`models`:`overview`}function kn(){return window.location.hash.replace(/^#\/?/,``)===Dn}function An(e){return e===`overview`?`dashboard`:`dashboard/${e}`}async function jn(e,t){let n=await vn(e,t);if(n===void 0)throw Error(t??`empty response`);return n}var Mn=[`low`,`medium`,`high`,`xhigh`];function Nn(e){return e?.includes(`-preview.`)?`preview`:`latest`}function Pn(e,t){switch(e){case`source_checkout`:return t(`dash.updateReason.source_checkout`);case`latest_unavailable`:return t(`dash.updateReason.latest_unavailable`);case`already_latest`:return t(`dash.updateReason.already_latest`);case`externally_managed`:return t(`dash.updateReason.externally_managed`);case`external_ownership_invalid`:return t(`dash.updateReason.external_ownership_invalid`);default:return t(`dash.updateReason.unknown`)}}function Fn(e,t){switch(e){case`running`:return t(`dash.updateStatus.running`);case`restarting`:return t(`dash.updateStatus.restarting`);case`succeeded`:return t(`dash.updateStatus.succeeded`);case`failed`:return t(`dash.updateStatus.failed`)}}function In(e,t){let n={...e};return t?.model!==void 0&&(n.model=t.model),t?.backend===null?delete n.backend:t?.backend!==void 0&&(n.backend=t.backend),t?.anthropicInstance===null?delete n.anthropicInstance:t?.anthropicInstance!==void 0&&(n.anthropicInstance=t.anthropicInstance),t?.backend!==void 0&&t.backend!==`anthropic`&&delete n.anthropicInstance,t?.reasoning!==void 0&&(n.reasoning=t.reasoning),t?.streamRoutedModelOutput!==void 0&&(n.streamRoutedModelOutput=t.streamRoutedModelOutput),t?.enabled!==void 0&&(n.enabled=t.enabled),t?.maxDescriptionsPerTurn!==void 0&&(n.maxDescriptionsPerTurn=t.maxDescriptionsPerTurn),t?.timeoutMs!==void 0&&(n.timeoutMs=t.timeoutMs),n}function Ln(e){return{vision:{reasoning:e}}}function Rn(e){return{vision:{enabled:e}}}function zn(e){return{webSearch:{enabled:e}}}function Bn(e){return e?.applied===!1&&e.reason!==`not_requested`}function Vn(e,t){return t?.reason===`not_requested`&&Bn(e)?e:t}function Hn(e){return{vision:{maxDescriptionsPerTurn:e}}}function Un(e){return{vision:{timeoutMs:e}}}var Wn=mn,Gn=hn,Kn=1;function qn(e){let t=e.trim();if(!/^[0-9]+$/.test(t))return;let n=Number(t);if(!(!Number.isSafeInteger(n)||n<=0))return n}function Jn(e){let t=qn(e);if(!(t===void 0||t<Kn||t>Gn))return t}var Yn=[`low`,`medium`,`high`,`xhigh`,`max`];function Xn(e,t){let n=e.find(e=>e.id===t)?.reasoningEfforts;if(!n||n.length===0)return[...Yn];let r=Yn.filter(e=>n.includes(e));return r.length>0?r:[...Yn]}function Zn(e,t){let n=Qn(e,t);return e.includes(n)?e:[n,...e]}function Qn(e,t){if(e.length===0||e.includes(t))return t;let n=Yn.indexOf(t),r=e[0],i=Yn.indexOf(r);for(let t of e){let e=Yn.indexOf(t);e<=n&&e>=i&&(r=t,i=e)}return r}function $n(e){let t=[];for(let n of e)(n.provider===`openai`||n.provider===`anthropic`)&&t.push({value:n.id,label:`${n.provider}/${n.id}`});return t}function er(e,t,n,r){if(e===void 0){let e=$n(t);return n&&!e.some(e=>e.value===n)&&e.unshift({value:n,label:n,...r?{backend:r}:{},model:n}),e}let i=e.map(e=>({value:e.value,label:e.label,backend:e.backend,model:e.model}));return n&&!i.some(e=>e.value===n)&&i.unshift({value:n,label:n,...r?{backend:r}:{},model:n}),i}function tr(e,t,n,r){let i=e?e.map(e=>({value:e.value,label:e.label,backend:e.backend})):$n(t);return n&&!i.some(e=>e.value===n)&&i.unshift({value:n,label:n,...r?{backend:r}:{}}),i}function nr(e,t,n){let r=xn(n),i=r.flatMap(t=>{let n=e.find(e=>e.namespaced.startsWith(t))??e.find(e=>e.id.startsWith(t));return n?[{provider:n.provider,modelId:t}]:[]}),a=e.filter(e=>i.some(t=>e.provider===t.provider&&e.id.startsWith(t.modelId))),o=new Set([...r.flatMap(e=>[e,`openai/${e}`]),...a.flatMap(e=>[e.namespaced,`${e.provider}/${e.id}`])]),s=[{value:``,label:`—`},...e.filter(e=>!o.has(e.namespaced)).map(e=>({value:e.namespaced,label:e.namespaced}))];return t&&!o.has(t)&&!s.some(e=>e.value===t)&&s.push({value:t,label:t}),s}function rr(e,t){let n=e.find(e=>e.id===t)?.provider;return n===`anthropic`||n===`anthropic2`?`anthropic`:`openai`}function ir(e,t){function n(e,t){return t.backend!==void 0&&t.backend!==`anthropic`&&e.anthropicInstance!==void 0?{...t,anthropicInstance:null}:t}return{...t,...t.webSearch?{webSearch:n(e.webSearch,t.webSearch)}:{},...t.vision?{vision:n(e.vision,t.vision)}:{}}}function ar(e,t,n){let r=t.find(e=>e.value===n);return{backend:r?.backend??rr(e,n),model:r?.model??n}}function or(e,t,n){return t.find(e=>e.value===n)?.backend||(n.includes(`/`)?`routed`:rr(e,n))}var sr=!1;typeof window<`u`&&typeof window.addEventListener==`function`&&(window.addEventListener(`keydown`,()=>{sr=!0},{capture:!0,passive:!0}),window.addEventListener(`pointerdown`,()=>{sr=!1},{capture:!0,passive:!0}));function cr(e){if(e){if(sr)e.focus({preventScroll:!0});else try{e.focus({preventScroll:!0,focusVisible:!1})}catch{e.focus({preventScroll:!0})}}}function lr(e,t){let n=(0,Z.useRef)(null);return(0,Z.useEffect)(()=>{let r=n.current;r&&(e?r.open||r.showModal():(r.open&&r.close(),cr(t.current)))},[e,t]),(0,Z.useEffect)(()=>()=>{let e=n.current;e?.open&&e.close(),cr(t.current)},[t]),n}var ur=`https://opencodex.me/guides/subagent-v1-default/`;function dr(e){if(!e||typeof e!=`object`)return null;let t=e,n=t.mode;return n!==`v1`&&n!=="default"&&n!==`v2`||typeof t.required!=`boolean`?null:{required:t.required,mode:n,recommended:`v1`,version:typeof t.version==`number`?t.version:0,docsUrl:typeof t.docsUrl==`string`&&t.docsUrl?t.docsUrl:ur}}function fr(e){return e==="default"?`base`:e}function pr({reason:e,mode:t,docsUrl:r,busy:i=!1,onContinue:a,onChooseV1:o,onDismiss:s}){let c=n(),l=(0,Z.useId)(),u=(0,Z.useId)(),d=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{let e=d.current;e&&!e.open&&e.showModal()},[]);let f=(0,Z.useCallback)(e=>{e.preventDefault(),!i&&s()},[i,s]),p=fr(t),m=e===`advisory`;return(0,Q.jsxs)(`dialog`,{ref:d,"aria-labelledby":l,"aria-describedby":u,className:`modal-overlay`,"data-subagent-surface-reason":e,onCancel:f,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":c(`common.close`),tabIndex:-1,disabled:i,onClick:()=>{i||s()}}),(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),style:{maxWidth:480},children:[(0,Q.jsx)(`h3`,{id:l,children:c(m?`subagentSurface.advisoryTitle`:`subagentSurface.selectionTitle`,{mode:p})}),(0,Q.jsxs)(`div`,{id:u,className:`notice-warn`,style:{marginTop:12,display:`flex`,gap:8,alignItems:`flex-start`},children:[(0,Q.jsx)(Ne,{width:16,height:16,style:{flexShrink:0,marginTop:2},"aria-hidden":`true`}),(0,Q.jsx)(`p`,{className:`modal-desc`,style:{margin:0},children:c(m?`subagentSurface.advisoryBody`:`subagentSurface.selectionBody`,{mode:p})})]}),(0,Q.jsx)(`p`,{className:`text-label`,style:{marginTop:12},children:(0,Q.jsx)(`a`,{href:r,target:`_blank`,rel:`noreferrer`,style:{color:`var(--accent)`},children:c(`subagentSurface.learnMore`)})}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:i,onClick:a,children:c(`subagentSurface.continue`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:i,onClick:o,children:c(`subagentSurface.switchToV1`)})]})]})]})}function mr(e){let{t,updateOpen:n,closeUpdateDialog:r,updateDialogRef:i,updateChannel:a,changeUpdateChannel:o,updateLoading:s,updateError:c,updateCheck:l,fetchUpdateCheck:u,updateRestart:d,setUpdateRestart:f,runUpdate:p,maHelpOpen:m,setMaHelpOpen:h,maHelpDialogRef:g,effortCapHelpOpen:_,setEffortCapHelpOpen:v,effortCapHelpDialogRef:y,shadowCallHelpOpen:b,setShadowCallHelpOpen:x,shadowCallHelpDialogRef:S,shadowCall:C,maAdvisory:w,maAdvisoryOpen:T,pendingMaMode:E,maBusy:D,keepMaMode:O,chooseMaV1:k,dismissMaSurfaceDialog:A}=e;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`dialog`,{ref:i,id:`dashboard-update-dialog`,className:`modal-overlay`,style:{display:n?`flex`:`none`,border:`none`,margin:0,maxWidth:`none`,maxHeight:`none`,width:`100%`,height:`100%`},"aria-labelledby":`update-title`,onCancel:e=>{e.preventDefault(),r()},children:(0,Q.jsxs)(`div`,{className:`modal-card`,children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:`update-title`,children:t(`dash.updateTitle`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:r,"aria-label":t(`common.cancel`),children:(0,Q.jsx)(xe,{})})]}),(0,Q.jsx)(`div`,{className:`modal-desc`,children:t(`dash.updateDesc`)}),(0,Q.jsxs)(`div`,{className:`update-row`,children:[(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`update-channel`,children:t(`dash.updateChannel`)}),(0,Q.jsx)(dn,{value:a,options:[{value:`latest`,label:`latest`},{value:`preview`,label:`preview`}],onChange:e=>o(e),disabled:s,label:t(`dash.updateChannel`),portal:!1})]}),s&&(0,Q.jsx)(fn,{className:`update-empty`,icon:(0,Q.jsx)(`span`,{className:`spin`}),title:t(`dash.updateChecking`)}),c&&(0,Q.jsxs)(`div`,{className:`notice notice-err`,role:`status`,children:[(0,Q.jsx)(Ne,{}),(0,Q.jsx)(`span`,{children:c})]}),l&&!s&&(0,Q.jsxs)(`div`,{className:`update-box`,children:[(0,Q.jsxs)(`div`,{className:`spread`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`muted text-label`,children:t(`dash.updateInstalled`)}),(0,Q.jsx)(`div`,{className:`mono`,children:l.currentVersion})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`muted text-label`,children:t(`dash.updateLatest`)}),(0,Q.jsx)(`div`,{className:`mono`,children:l.latestVersion??`—`})]}),(0,Q.jsx)(`span`,{className:`badge ${l.updateAvailable?`badge-green`:`badge-muted`}`,children:l.updateAvailable?t(`dash.updateAvailable`):t(`dash.updateCurrent`)})]}),l.command&&(0,Q.jsxs)(`div`,{className:`muted update-command`,children:[t(`dash.updateCommand`),` `,(0,Q.jsx)(`code`,{className:`chip`,children:l.command})]}),l.reason===`source_checkout`&&(0,Q.jsxs)(`div`,{className:`notice-warn`,role:`status`,children:[(0,Q.jsx)(Ne,{}),` `,t(`dash.updateSource`)]}),l.reason===`latest_unavailable`&&(0,Q.jsxs)(`div`,{className:`notice-warn`,role:`status`,children:[(0,Q.jsx)(Ne,{}),` `,t(`dash.updateUnavailable`),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:s,onClick:()=>{u(a,!0)},style:{marginLeft:12},children:[(0,Q.jsx)(ae,{}),` `,t(`dash.updateRetry`)]})]}),!l.canUpdate&&l.reason!==`latest_unavailable`&&l.reason!==`source_checkout`&&(0,Q.jsxs)(`div`,{className:`update-recheck`,children:[(0,Q.jsx)(`span`,{className:`muted update-recheck-reason`,children:t(`dash.updateCannotAuto`,{reason:Pn(l.reason,t)})}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:s,onClick:()=>{u(a,!0)},children:[(0,Q.jsx)(ae,{}),` `,t(s?`dash.updateChecking`:`dash.updateRecheck`)]})]}),l.canUpdate&&(0,Q.jsxs)(`div`,{className:`spread update-restart`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:t(`dash.updateRestart`)}),(0,Q.jsx)(`div`,{className:`muted text-label`,children:t(`dash.updateRestartHint`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`switch ${d?`on`:``}`,onClick:()=>f(e=>!e),"aria-label":t(`dash.updateRestart`),"aria-pressed":d,children:(0,Q.jsx)(`span`,{className:`knob`})})]})]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:r,children:t(`common.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:p,disabled:!l?.canUpdate||s,children:t(`dash.runUpdate`)})]})]})}),(0,Q.jsxs)(`dialog`,{ref:g,id:`multi-agent-help-dialog`,className:`modal-overlay`,style:{display:m?`flex`:`none`,border:`none`,margin:0,maxWidth:`none`,maxHeight:`none`,width:`100%`,height:`100%`},"aria-labelledby":`multi-agent-help-title`,onCancel:e=>{e.preventDefault(),h(!1)},children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":t(`common.close`),tabIndex:-1,onClick:()=>h(!1)}),(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:`multi-agent-help-title`,children:t(`dash.multiAgent`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:()=>h(!1),"aria-label":t(`common.close`),children:(0,Q.jsx)(xe,{})})]}),(0,Q.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:t(`models.v2Help`)}),(0,Q.jsx)(`div`,{style:{marginTop:12},children:(0,Q.jsx)(`a`,{className:`text-control`,href:`https://opencodex.me/guides/sub-agent-surface/`,target:`_blank`,rel:`noreferrer`,style:{color:`var(--accent)`},children:t(`models.v2DocsLink`)})}),(0,Q.jsx)(`div`,{className:`modal-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>h(!1),children:t(`common.ok`)})})]})]}),(0,Q.jsxs)(`dialog`,{ref:y,id:`effort-cap-help-dialog`,className:`modal-overlay`,style:{display:_?`flex`:`none`,border:`none`,margin:0,maxWidth:`none`,maxHeight:`none`,width:`100%`,height:`100%`},"aria-labelledby":`effort-cap-help-title`,onCancel:e=>{e.preventDefault(),v(!1)},children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":t(`common.close`),tabIndex:-1,onClick:()=>v(!1)}),(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:`effort-cap-help-title`,children:t(`dash.effortCapLabel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:()=>v(!1),"aria-label":t(`common.close`),children:(0,Q.jsx)(xe,{})})]}),(0,Q.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:t(`dash.effortCapHelp`)}),(0,Q.jsx)(`div`,{className:`modal-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>v(!1),children:t(`common.ok`)})})]})]}),(0,Q.jsxs)(`dialog`,{ref:S,id:`shadow-call-help-dialog`,className:`modal-overlay`,style:{display:b?`flex`:`none`,border:`none`,margin:0,maxWidth:`none`,maxHeight:`none`,width:`100%`,height:`100%`},"aria-labelledby":`shadow-call-help-title`,onCancel:e=>{e.preventDefault(),x(!1)},children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":t(`common.close`),tabIndex:-1,onClick:()=>x(!1)}),(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:`shadow-call-help-title`,children:t(`dash.shadowCallIntercept`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:()=>x(!1),"aria-label":t(`common.close`),children:(0,Q.jsx)(xe,{})})]}),(0,Q.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:t(`dash.shadowCallTooltip`,{models:Sn(C?.sourceModels)})}),(0,Q.jsx)(`div`,{className:`modal-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>x(!1),children:t(`common.ok`)})})]})]}),(E||T)&&(0,Q.jsx)(pr,{reason:E?`selection`:`advisory`,mode:E??w?.mode??`default`,docsUrl:w?.docsUrl??`https://opencodex.me/guides/subagent-v1-default/`,busy:D,onContinue:()=>{O()},onChooseV1:()=>{k()},onDismiss:A})]})}function hr({t:e,models:t,modelsLoading:n,modelQuery:r,setModelQuery:i,filteredGroups:a,expandedProviders:o,setExpandedProviders:s}){return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`h-section`,children:[e(`dash.availableModels`),` `,(0,Q.jsx)(`span`,{className:`count`,children:t.length}),n&&(0,Q.jsx)(`span`,{className:`spin`,style:{marginLeft:4}})]}),t.length===0&&!n?(0,Q.jsx)(fn,{title:e(`dash.noModels`)}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`pws-search-wrap`,children:[(0,Q.jsx)(se,{className:`pws-search-icon`,width:14,height:14,"aria-hidden":`true`}),(0,Q.jsx)(`input`,{type:`search`,className:`input pws-search-input`,placeholder:e(`models.search`),value:r,onChange:e=>i(e.target.value),"aria-label":e(`models.search`)})]}),a.length===0?(0,Q.jsx)(`p`,{className:`muted text-control`,style:{margin:`4px 0`},children:e(`dash.modelsNoResults`)}):(0,Q.jsx)(`div`,{className:`dash-model-acc`,children:a.map(([t,n])=>{let i=r.trim().toLowerCase()!==``||o.has(t);return(0,Q.jsxs)(`div`,{className:`dash-model-group`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`dash-model-head`,onClick:()=>s(e=>{let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n}),"aria-expanded":i,children:[(0,Q.jsx)(Ye,{width:12,height:12,style:{transform:i?`rotate(90deg)`:`none`,transition:`transform .12s`,color:`var(--muted)`},"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`font-semibold`,children:Ce(t,e)}),(0,Q.jsx)(`span`,{className:`count`,children:n.length})]}),i&&(0,Q.jsx)(`div`,{className:`dash-model-chips`,children:n.map(e=>(0,Q.jsx)(`code`,{className:`dash-model-chip`,children:e.id},`${e.provider}/${e.id}`))})]},t)})})]})]})}function gr(e,t){let n=Math.max(0,Math.floor(e)),r=b(t,`uptime.day`),i=b(t,`uptime.hour`),a=b(t,`uptime.minute`),o=b(t,`uptime.second`);if(n<300)return`${n}${o}`;let s=Math.floor(n/60);if(s<60)return`${s}${a}`;let c=Math.floor(s/60);if(c<24){let e=s%60;return e>0?`${c}${i} ${e}${a}`:`${c}${i}`}let l=Math.floor(c/24),u=c%24;return u>0?`${l}${r} ${u}${i}`:`${l}${r}`}function _r(e){return!e||typeof e!=`object`||!(`usageIncomplete`in e)||e.usageIncomplete!==!0?{}:{usageIncomplete:!0,...`usageIncompleteReason`in e&&e.usageIncompleteReason===`oversized_rows`?{usageIncompleteReason:`oversized_rows`}:{}}}function vr(e){return!!e&&typeof e==`object`&&`error`in e&&e.error===`read_failed`}var yr=class extends Error{constructor(){super(`usage ledger read failed`),this.name=`UsageReadFailedError`}};async function br(e,t){let n;try{n=await e.json()}catch{throw Error(t??`${e.status} ${e.statusText}`.trim())}if(vr(n))throw new yr;if(!e.ok)throw Error(t??`${e.status} ${e.statusText}`.trim());return n}function xr(e,t=`all`){return t===`codex`?[`usage-summary-30d`,e,`codex`].join(`:`):[`usage-summary-30d`,e,`all`].join(`:`)}function Sr({data:e}){let t=n();return _r(e).usageIncomplete?(0,Q.jsx)($,{tone:`warn`,children:t(`usage.incomplete`)}):null}function Cr({locale:e,health:t,providers:r,usage30d:i,usageLoading:a,healthLoading:o,startupHealth:s,projectConfigWarnings:c,maMode:l,maBusy:u,maHelpTriggerRef:d,maHelpOpen:f,setMaHelpOpen:p,switchMaMode:m,maError:h}){let g=n(),_=t?.status===`ok`;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`dash-overview-head`,children:[(0,Q.jsxs)(`div`,{className:`stat-row`,children:[(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsxs)(`div`,{className:`label`,style:{display:`flex`,alignItems:`center`,gap:6},children:[g(`dash.multiAgent`),(0,Q.jsx)(`button`,{ref:d,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)`},onClick:()=>p(!0),"aria-label":g(`dash.multiAgent`),"aria-haspopup":`dialog`,"aria-controls":`multi-agent-help-dialog`,"aria-expanded":f,children:(0,Q.jsx)(De,{width:14,height:14,"aria-hidden":`true`})})]}),(0,Q.jsx)(`div`,{className:`value`,style:{display:`flex`,alignItems:`center`},children:(0,Q.jsx)(`div`,{className:`dash-ma-switch`,role:`radiogroup`,"aria-label":g(`dash.multiAgent`),style:{display:`inline-flex`,borderRadius:`var(--radius-pill)`,background:`var(--surface-soft, var(--raised))`,padding:3,gap:2},children:[`v1`,`default`,`v2`].map(e=>(0,Q.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":l===e,className:`btn btn-sm text-caption dash-ma-option${l===e?` btn-primary`:` btn-ghost`}`,style:{borderRadius:`var(--radius-pill)`,border:`none`,background:l===e?void 0:`transparent`,color:l===e?void 0:`var(--muted)`},disabled:u,onClick:()=>void m(e),children:g(`models.v2Mode_${e}`)},e))})}),h&&(0,Q.jsx)(`div`,{role:`alert`,className:`text-caption`,style:{color:`var(--red)`,marginTop:4,textAlign:`center`,maxWidth:280,wordBreak:`break-word`},children:h})]}),(0,Q.jsxs)(`div`,{className:`stat`,"aria-busy":o||void 0,children:[(0,Q.jsx)(`div`,{className:`label`,children:g(`dash.status`)}),(0,Q.jsxs)(`div`,{className:`value`,style:{display:`flex`,alignItems:`center`,gap:9,color:_?`var(--green)`:`var(--red)`},children:[(0,Q.jsx)(`span`,{className:`dot ${_?`dot-green`:`dot-red`}`}),g(_?`dash.online`:`dash.offline`)]})]}),(0,Q.jsxs)(`div`,{className:`stat`,"aria-busy":o||void 0,children:[(0,Q.jsx)(`div`,{className:`label`,children:g(`dash.version`)}),(0,Q.jsx)(`div`,{className:`value mono dash-stat-version`,title:t?.version,children:t?.version??`—`})]}),(0,Q.jsxs)(`div`,{className:`stat`,"aria-busy":o||void 0,children:[(0,Q.jsx)(`div`,{className:`label`,children:g(`dash.uptime`)}),(0,Q.jsx)(`div`,{className:`value mono`,children:t?gr(t.uptime,e):`—`})]}),(0,Q.jsxs)(`div`,{className:`stat`,"aria-busy":o||void 0,children:[(0,Q.jsx)(`div`,{className:`label`,children:g(`dash.providers`)}),(0,Q.jsx)(`div`,{className:`value`,children:r.length})]}),(0,Q.jsxs)(`div`,{className:`stat`,"aria-busy":a||void 0,children:[(0,Q.jsx)(`div`,{className:`label`,children:g(`dash.tokens30d`)}),(0,Q.jsx)(`div`,{className:`value mono`,children:i&&i.summary.requests>0?q(i.summary.totalTokens,e):`—`}),(0,Q.jsx)(`div`,{className:`muted text-label dash-stat-coverage`,children:i&&i.summary.requests>0?g(`dash.coverage`).replace(`{pct}`,`${Math.round(i.summary.coverageRatio*100)}%`):`\xA0`})]})]}),(0,Q.jsx)(`div`,{className:`startup-health-slot`,"aria-live":`polite`,children:s?(0,Q.jsxs)(`button`,{type:`button`,className:`startup-health-bar`,onClick:()=>Xt(`startup`),children:[(0,Q.jsx)(`span`,{className:`dot ${s===`error`?`dot-red`:s===`at-risk`?`dot-amber`:`dot-green`}`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`startup-health-bar__summary`,children:g(s===`error`?`startup.error`:s===`at-risk`?`startup.summary.atRisk`:s===`protected`?`startup.summary.protected`:`startup.summary.native`)})]}):(0,Q.jsxs)(`div`,{className:`startup-health-bar startup-health-bar--pending`,"aria-hidden":`true`,children:[(0,Q.jsx)(`span`,{className:`dot dot-amber`}),(0,Q.jsx)(`span`,{className:`startup-health-bar__summary`,children:`\xA0`})]})})]}),(0,Q.jsx)(Sr,{data:i}),c.length>0&&(0,Q.jsxs)(`div`,{className:`notice notice-err maintenance-notice`,role:`alert`,children:[(0,Q.jsx)(Ne,{}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:g(`dash.projectConfigTitle`)}),(0,Q.jsx)(`div`,{className:`muted text-control`,style:{marginTop:4},children:g(`dash.projectConfigHint`)}),(0,Q.jsx)(`ul`,{className:`text-control`,style:{margin:`10px 0 0`,paddingLeft:18},children:c.map(e=>(0,Q.jsxs)(`li`,{style:{marginBottom:8},children:[(0,Q.jsx)(`code`,{children:e.path}),` — `,e.issues.join(`, `),(0,Q.jsx)(`div`,{className:`muted`,style:{marginTop:2},children:e.bypass})]},e.path))})]})]})]})}var wr=`gpt-daybreak-blue-latest`,Tr=`gpt-6-astra`,Er=`gpt-6-sol`,Dr=`gpt-6-luna`,Or=`gpt-6.1-sol`,kr=`gpt-6.1-terra`,Ar=`gpt-6-astra-minor`,jr=Object.freeze({contextWindow:272e3,maxContextWindow:872e3,maxInputTokens:872e3});Object.freeze({...jr,contextWindow:5e5}),Object.freeze({...jr,contextWindow:5e5});var Mr=new Set([wr,Ar]),Nr=Object.freeze({[wr]:`gpt-5.6-sol`,[Ar]:Tr});Object.freeze(Object.keys(Nr)),Object.freeze({[wr]:{displayName:`Daybreak Blue`,description:`Frontier general-purpose model with safeguards for defensive cybersecurity work.`},[Ar]:{displayName:`GPT-6-Astra-Minor`,description:`Unreleased GPT-6 Astra variant; shown only when your account's Codex roster lists it.`}});var Pr=[...Object.freeze([`gpt-5.5`,`gpt-5.6-sol`,`gpt-5.6-terra`,`gpt-5.6-luna`,wr,Tr,Er,Dr,Or,kr,Ar])],Fr=new Set(Pr);[...Mr];var Ir=18e5,Lr=[`account_unavailable`,`access_denied`,`rate_limited`,`upstream_error`,`redirect_blocked`,`destination_blocked`,`dns_failed`,`timeout`,`transport_error`,`response_unusable`];function Rr(e){return Lr.find(t=>t===e)}var zr=6e4,Br=864e5;function Vr(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=Object.keys(e);if(t.length!==1||t[0]!==`ttlMs`)return;let n=e.ttlMs;return typeof n==`number`&&Number.isSafeInteger(n)&&n>=6e4&&n<=864e5?{ttlMs:n}:void 0}var Hr=1e3,Ur=12e4,Wr=4e3;function Gr(e){try{let t=e.trim();if(/[\u0000-\u001f\u007f]/.test(t))return!1;let n=t.replace(/^[a-z][a-z\d+.-]*:[/\\]*/i,``).split(/[/\\]/,1)[0]??``;if(/[?#]/.test(t)||n.includes(`@`))return!1;let r=new URL(t);if(r.username||r.password||r.search||r.hash)return!1;let i=r.hostname,a=i===`localhost`||i===`[::1]`||/^(?:(?:127|10)\.\d+|172\.(?:1[6-9]|2\d|3[01])|192\.168)\.\d+\.\d+$/.test(i)||/^\[f[cd][\da-f]{2}:/.test(i)||/^\[::ffff:7f[\da-f]{2}:/.test(i);return r.protocol===`https:`||r.protocol===`http:`&&a&&r.pathname.replace(/\/+$/,``).endsWith(`/systemone`)}catch{return!1}}function Kr(e){return e?e.adapter===`jev-decision`?e.disabled===!0?`disabled`:Gr(e.baseUrl??``)?!e.defaultModel?.trim()&&!e.models?.[0]?.trim()?`model`:null:`endpoint`:`notDecision`:`missing`}function qr(e){return e.name===`jev`?e.adapter===`jev-decision`&&e.disabled!==!0&&e.hasApiKey===!0:Kr(e)===null}var Jr={typesafe:`cws.jev.backend.typesafe`,systemone:`cws.jev.backend.systemone`,model:`cws.jev.backend.model`,unknown:`cws.jev.backend.unknown`};function Yr(e){return e.decisionModel==null?e.decisionProvider!=null&&e.decisionProvider.trim()!==`jev`?`systemone`:`typesafe`:`model`}function Xr(e,t,n){let r=e.trim(),i=e=>r===`combo/${e.id.trim()}`||!!e.alias?.trim()&&r===e.alias.trim()||!!e.model?.trim()&&r===e.model.trim();return!!n&&i(n)||t.some(e=>e.strategy===`jev`&&i(e))}function Zr(e,t,n,r){let i=new Set(t.filter(e=>!e.disabled&&e.adapter!==`jev-decision`).map(e=>e.name)),a=e.filter(e=>!e.disabled&&e.provider!==`combo`&&i.has(e.provider)).map(e=>e.namespaced?.trim()||`${e.provider}/${e.id}`);return a.push(...n.filter(e=>e.strategy!==`jev`).map(e=>e.model)),[...new Set(a)].filter(e=>!Xr(e,n,r)).sort((e,t)=>e.localeCompare(t))}var Qr=[`low`,`medium`,`high`,`xhigh`,`max`,`ultra`],$r=[`failover`,`round-robin`,`random`,`least-used`,`reset-window`,`jev`],ei={failover:`cws.strategy.failover`,"round-robin":`cws.strategy.roundRobin`,random:`cws.strategy.random`,"least-used":`cws.strategy.leastUsed`,"reset-window":`cws.strategy.resetWindow`,jev:`cws.strategy.jev`},ti={failover:`cws.strategy.failoverHint`,"round-robin":`cws.strategy.roundRobinHint`,random:`cws.strategy.randomHint`,"least-used":`cws.strategy.leastUsedHint`,"reset-window":`cws.strategy.resetWindowHint`,jev:`cws.strategy.jevHint`},ni={failover:`cws.targets.failoverHint`,"round-robin":`cws.targets.roundRobinHint`,random:`cws.targets.randomHint`,"least-used":`cws.targets.leastUsedHint`,"reset-window":`cws.targets.resetWindowHint`,jev:`cws.targets.jevHint`},ri=new Set($r),ii={missing:`cws.jev.decisionIssue.missing`,notDecision:`cws.jev.decisionIssue.notDecision`,disabled:`cws.jev.decisionIssue.disabled`,endpoint:`cws.jev.decisionIssue.endpoint`,model:`cws.jev.decisionIssue.model`};function ai(e,t,n=`strict`){let r=e.filter(e=>e.provider.trim()&&e.model.trim());if(r.length===0)return[...Qr];let i=new Set(Qr),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[...Qr];let o=new Set(a);return Qr.filter(e=>o.has(e))}var oi=Ir,si=0;function ci(e={}){return{provider:e.provider??``,model:e.model??``,...e.weight===void 0?{}:{weight:e.weight},...e.reasoningEfforts===void 0?{}:{reasoningEfforts:[...e.reasoningEfforts]},...e.modelProfile===void 0?{}:{modelProfile:e.modelProfile},clientKey:e.clientKey??`ct-${++si}`}}function li(e){return e===`disabled`?`disabled`:`auto`}function ui(e){return e===`adaptive`?`adaptive`:`strict`}var di=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/,fi=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}(\/[a-zA-Z0-9][a-zA-Z0-9._-]{0,63})?$/,pi=/^(?:gpt-|o1-|o3-|o4-|codex-)/;function mi(e){return di.test(e.trim())}function hi(e){return`combo/${e.trim()}`}function gi(e,t){return(typeof t==`string`?t.trim():``)||hi(e)}function _i(e,t){let n=t.trim(),r=e.nativeAlias&&(!n||n.includes(`/`)||!pi.test(n));return{...e,alias:n?t:null,model:gi(e.id,t),...r?{nativeAlias:!1,displayName:null}:{}}}function vi(e){let t=typeof e==`string`?e.trim():``;return t&&t!==`jev`?t:null}function yi(e){return typeof e==`number`&&Number.isInteger(e)?e:null}function bi(e){return typeof e==`string`&&e.trim()?e.trim():null}function xi(e){return typeof e==`string`&&ri.has(e)?e:`failover`}function Si(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=100?e:1}function Ci(e){return typeof e==`string`&&Qr.includes(e)?e:null}function wi(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=1e4?e:void 0}function Ti(e){if(!Array.isArray(e)||e.length===0)return;let t=[],n=new Set;for(let r of e){if(typeof r!=`string`||!Qr.includes(r))return;let e=r;if(n.has(e))return;n.add(e),t.push(e)}return t}function Ei(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=wi(t.weight),o=Ti(t.reasoningEfforts);a.push(ci({provider:n,model:r,...i===void 0?{}:{weight:i},...o===void 0?{}:{reasoningEfforts:o},...typeof t.modelProfile==`string`?{modelProfile:t.modelProfile}:{}}))}let o=vi(t.decisionProvider),s=bi(t.decisionModel),c=yi(t.decisionTimeoutMs),l=t.sessionPin===null?null:Vr(t.sessionPin);n.push({id:r,model:typeof t.model==`string`&&t.model.trim()?t.model.trim():gi(r,bi(t.alias)),alias:bi(t.alias),nativeAlias:t.nativeAlias===!0,displayName:bi(t.displayName),strategy:xi(t.strategy),stickyLimit:Si(t.stickyLimit),defaultEffort:Ci(t.defaultEffort),imageInput:li(t.imageInput),reasoningEffortMode:ui(t.reasoningEffortMode),...o===null?{}:{decisionProvider:o},...s===null?{}:{decisionModel:s},...c===null?{}:{decisionTimeoutMs:c},...l===void 0?{}:{sessionPin:l},targets:a})}return n.sort((e,t)=>e.id.localeCompare(t.id,void 0,{sensitivity:`base`}))}function Di(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 Oi(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 ki(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:null}function Ai(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function ji(e,t){let n=ki(e.routingQuota);if(!n||n.state!==`available`&&n.state!==`exhausted`)return null;let r=Ai(n.updatedAt),i=Ai(n.validUntil);return r===null||r<0||r>t||t-r>=oi||i===null||i<=t||i>r+oi?null:{state:n.state,validUntil:i}}function Mi(e,t){return ji(e,t)?.state??`unknown`}function Ni(e,t=Date.now()){if(!Array.isArray(e))return;let n;for(let r of e){let e=ki(r);if(!e||typeof e.provider!=`string`||!e.provider.trim())continue;let i=ji(e,t);i&&(n===void 0||i.validUntil<n)&&(n=i.validUntil)}return n}function Pi(e,t=Date.now()){if(!Array.isArray(e))return{};let n={};for(let r of e){let e=ki(r),i=typeof e?.provider==`string`?e.provider.trim():``;if(!e||!i)continue;let a=Mi(e,t);n[i]=Object.hasOwn(n,i)&&n[i]!==a?`unknown`:a}return n}function Fi(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 Ii(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&&Fi(i.targets,t.providerQuotaStates,t.providers)===`exhausted`&&n.push({id:i.id,model:i.model,reason:`all-targets-exhausted`});return n}function Li(e,t){return e.reasoningEfforts===void 0||t.reasoningEfforts===void 0?e.reasoningEfforts===t.reasoningEfforts:e.reasoningEfforts.length===t.reasoningEfforts.length&&e.reasoningEfforts.every((e,n)=>e===t.reasoningEfforts[n])}function Ri(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.strategy===`jev`&&((e.decisionProvider??null)!==(t.decisionProvider??null)||(e.decisionModel??null)!==(t.decisionModel??null)||(e.decisionTimeoutMs??null)!==(t.decisionTimeoutMs??null)||e.sessionPin===void 0!=(t.sessionPin===void 0)||(e.sessionPin?.ttlMs??null)!==(t.sessionPin?.ttlMs??null))||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)&&Li(e,r)&&(e.modelProfile??``)===(r.modelProfile??``)})}function zi(e,t={}){let n=e.strategy===`round-robin`||e.strategy===`random`;return{id:e.id.trim(),...t.renameFrom?{renameFrom:t.renameFrom}:{},...t.visionSidecarTargets?.length?{visionSidecarTargets:t.visionSidecarTargets}:{},combo:{targets:e.targets.map(e=>({provider:e.provider.trim(),model:e.model.trim(),...n?{weight:e.weight??1}:{},...e.reasoningEfforts===void 0?{}:{reasoningEfforts:[...e.reasoningEfforts]},...e.modelProfile?.trim()?{modelProfile:e.modelProfile.trim()}:{}})),strategy:e.strategy,defaultEffort:e.defaultEffort,imageInput:e.imageInput===`disabled`?`disabled`:`auto`,reasoningEffortMode:e.reasoningEffortMode===`adaptive`?`adaptive`:`strict`,...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()}:{},...e.strategy===`jev`?{decisionProvider:e.decisionModel?.trim()?null:vi(e.decisionProvider),decisionModel:e.decisionModel?.trim()||null,decisionTimeoutMs:e.decisionTimeoutMs??null,...e.sessionPin===void 0?{}:{sessionPin:e.sessionPin}}:{}}}}function Bi(e,t){let n=e.id.trim();if(!n)return`missingId`;if(!mi(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(!fi.test(r))return`invalidAlias`;if(r===`combo`||r.startsWith(`combo/`))return`aliasReservedNamespace`;if(!r.includes(`/`)&&pi.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&&!Fr.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`;if(n.reasoningEfforts!==void 0&&(n.reasoningEfforts.length===0||n.reasoningEfforts.some(e=>!Qr.includes(e))||new Set(n.reasoningEfforts).size!==n.reasoningEfforts.length))return`invalidReasoningEfforts`;if(n.modelProfile!==void 0&&(n.modelProfile.length>512||[...n.modelProfile].some(e=>{let t=e.charCodeAt(0);return t<32&&t!==9&&t!==10&&t!==13||t===127})))return`invalidModelProfile`}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`}if(e.strategy===`jev`&&e.sessionPin!=null&&!Vr(e.sessionPin))return`invalidSessionPin`;if(e.strategy===`jev`&&e.decisionTimeoutMs!=null&&(!Number.isInteger(e.decisionTimeoutMs)||e.decisionTimeoutMs<1e3||e.decisionTimeoutMs>12e4))return`invalidDecisionTimeout`;if(e.strategy===`jev`&&Yr(e)===`model`){let n=e.decisionModel?.trim()??``;if(!n||n.length>512||e.decisionProvider!=null||Xr(n,t.combos??[],e)||t.decisionModels&&!t.decisionModels.includes(n))return`invalidDecisionModel`}return e.strategy===`jev`&&Yr(e)===`systemone`&&(!e.decisionProvider?.trim()||Wi(e.decisionProvider,t.providers)!==null)?`invalidDecisionProvider`:e.targets.some(e=>t.providers[e.provider.trim()]?.disabled!==!0)?null:`noEnabledTarget`}function Vi(e=``){return{id:e,model:e?hi(e):`combo/`,alias:null,nativeAlias:!1,displayName:null,strategy:`failover`,stickyLimit:1,defaultEffort:null,imageInput:`auto`,reasoningEffortMode:`strict`,targets:[ci()]}}var Hi=[`gpt-6-astra`,`gpt-5.6-sol`,`gpt-5.6-luna`];function Ui(e,t,n){let r=Hi.flatMap(n=>{let r=e.find(e=>e.id===n&&(t===void 0||t.has(e.provider)));return r?[ci({provider:r.provider,model:r.id})]:[]});return{id:`jev-auto`,model:`jev-auto`,alias:`jev-auto`,nativeAlias:!1,displayName:null,strategy:`jev`,stickyLimit:1,defaultEffort:null,imageInput:`auto`,reasoningEffortMode:`adaptive`,decisionProvider:vi(n),targets:r.length>0?r:[ci()]}}function Wi(e,t){let n=vi(e);return n===null?null:Kr(Object.hasOwn(t,n)?t[n]:void 0)}function Gi(e,t){let n=e.filter(e=>e.adapter===`jev-decision`&&e.name!==`jev`).toSorted((e,t)=>e.name.localeCompare(t.name)).map(e=>{let t=Kr(e);return{id:e.name,...e.baseUrl?{baseUrl:e.baseUrl}:{},...t?{issue:t}:{}}}),r=vi(t),i=r!==null&&!n.some(e=>e.id===r)?[{id:r,issue:e.some(e=>e.name===r)?`notDecision`:`missing`}]:[];return[{id:null},...n,...i]}function Ki(e,t){if(e.strategy!==`jev`)return null;let n=vi(e.decisionProvider),r=n===null?void 0:t.find(e=>e.name===n);return{provider:n,model:e.decisionModel?.trim()||null,baseUrl:r?.baseUrl?.trim()||null,timeoutMs:e.decisionTimeoutMs??null}}var qi=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`,`ultra`],Ji=[`manual`,`auto`],Yi=300,Xi=[`manual`,`manual+auto`,`auto`],Zi={manual:`compactionRouting.triggersManual`,"manual+auto":`compactionRouting.triggersBoth`,auto:`compactionRouting.triggersAuto`},Qi=[`all`,`selected`],$i={all:`compactionRouting.sourcesAll`,selected:`compactionRouting.sourcesSelected`};function ea(e){if(!e)return`manual`;let t=e.includes(`auto`);return e.includes(`manual`)?t?`manual+auto`:`manual`:t?`auto`:`manual`}function ta(e){if(e===`auto`)return[`auto`];if(e===`manual+auto`)return[`manual`,`auto`]}function na(e){let t=new Map;for(let n of Ei(e))t.set(n.model,[...new Set(n.targets.flatMap(e=>e.provider?[e.provider]:[]))]);return t}function ra(e){let t=e.compactionRouting;if(t==null)return null;if(!t||typeof t!=`object`||!(`model`in t)||typeof t.model!=`string`||!t.model.trim())throw Error(`invalid settings`);let n=`reasoningEffort`in t?t.reasoningEffort:void 0;if(n!==void 0&&(typeof n!=`string`||!qi.includes(n)))throw Error(`invalid effort`);let r=`triggers`in t?t.triggers:void 0,i=`sourceModels`in t?t.sourceModels:void 0;if(i!==void 0&&(!Array.isArray(i)||!i.length||!i.every(e=>typeof e==`string`&&e.trim())))throw Error(`invalid sourceModels`);if(r!==void 0&&(!Array.isArray(r)||r.length===0||!r.every(e=>typeof e==`string`&&Ji.includes(e))||new Set(r).size!==r.length))throw Error(`invalid triggers`);return{model:t.model,...n?{reasoningEffort:n}:{},...r?{triggers:r}:{},...i?{sourceModels:i}:{}}}function ia(e){if(!e)return``;try{return new URL(e).hostname||e}catch{return e}}function aa(e,t){let n=t.get(e);return n?`${e} (${n})`:e}function oa(e){return(0,Q.jsx)(sa,{...e},e.apiBase)}function sa({apiBase:e,models:t,providers:r=[]}){let i=n(),[a,o]=(0,Z.useState)(void 0),[s,c]=(0,Z.useState)(``),[l,u]=(0,Z.useState)(``),[d,f]=(0,Z.useState)(`manual`),[p,m]=(0,Z.useState)(`all`),[h,g]=(0,Z.useState)([]),[_,v]=(0,Z.useState)(``),[y,b]=(0,Z.useState)(!1),[x,S]=(0,Z.useState)(!1),[C,w]=(0,Z.useState)(null),[T,E]=(0,Z.useState)(()=>new Map),D=(0,Z.useRef)(!1),O=(0,Z.useRef)(null),k=(0,Z.useCallback)(e=>{o(e),c(e?.model??``),u(e?.reasoningEffort??``),f(ea(e?.triggers)),m(e?.sourceModels?`selected`:`all`),g(e?.sourceModels??[])},[]),A=e=>{g(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]),w(null)},j=(0,Z.useCallback)(async()=>{if(O.current)return;let t=M(15e3);O.current=t,S(!1);try{let n=ra(await jn(await fetch(`${e}/api/settings`,{signal:t.signal})));D.current&&O.current===t&&k(n);let r=await fetch(`${e}/api/combos`,{signal:t.signal}).then(jn).then(na).catch(()=>new Map);D.current&&O.current===t&&E(r)}catch{D.current&&O.current===t&&S(!0)}finally{t.clear(),O.current===t&&(O.current=null)}},[e,k]);(0,Z.useEffect)(()=>{D.current=!0;let e=window.setTimeout(()=>{j()},0);return()=>{window.clearTimeout(e),D.current=!1,O.current?.controller.abort(),O.current?.clear(),O.current=null}},[j]);let N=async()=>{if(O.current||a===void 0)return;let t=M(15e3);O.current=t,b(!0),w(null);try{let n=ra(await jn(await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({compactionRouting:s?{model:s,...l?{reasoningEffort:l}:{},...ta(d)?{triggers:ta(d)}:{},...p===`selected`&&h.length>0?{sourceModels:h}:{}}:null}),signal:t.signal})));D.current&&O.current===t&&(k(n),w(`saved`))}catch{D.current&&O.current===t&&w(`failed`)}finally{t.clear(),D.current&&O.current===t&&b(!1),O.current===t&&(O.current=null)}},P=[{value:``,label:i(`compactionRouting.currentModel`)},...[...new Set([...t.map(e=>e.namespaced),...s?[s]:[]])].map(e=>({value:e,label:we(e,i)}))],F=[...new Set([...r.map(e=>e.name),...t.flatMap(e=>e.provider?[e.provider]:[])])].map(e=>`${e}/*`),I=new Set([...F,...t.map(e=>e.namespaced)]),L=(a?.sourceModels??[]).filter(e=>!I.has(e)),R=y||a===void 0||x,z=a?.sourceModels?`selected`:`all`,B=new Set(a?.sourceModels),V=s!==(a?.model??``)||l!==(a?.reasoningEffort??``)||d!==ea(a?.triggers)||p!==z||p===`selected`&&(h.length!==(a?.sourceModels?.length??0)||h.some(e=>!B.has(e))),H=p===`selected`&&h.length===0,U=new Set(h),ee=[...new Set(t.map(e=>e.namespaced))].filter(e=>e.toLowerCase().includes(_.trim().toLowerCase())),W=e=>(0,Q.jsxs)(`label`,{children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:U.has(e),disabled:R,onChange:()=>{A(e)}}),(0,Q.jsx)(`span`,{children:e})]},e),te=T.get(s),G=te!==void 0||s.startsWith(hi(``)),ne=s.slice(0,Math.max(s.indexOf(`/`),0)),K=new Map(r.map(e=>[e.name,ia(e.baseUrl)]).filter(([,e])=>e)),re=G?``:aa(ne||s,K),q=te?.map(e=>aa(e,K)).join(`, `)||i(`compactionRouting.comboProvidersUnknown`),J=d!==`manual`,Y=h.join(`, `),ie=!s||H?null:G?p===`selected`?i(`compactionRouting.comboWarningScoped`,{combo:s,providers:q,sources:Y}):i(`compactionRouting.comboWarning`,{combo:s,providers:q}):p===`selected`?i(`compactionRouting.providerWarningScoped`,{provider:re,sources:Y}):i(`compactionRouting.providerWarning`,{provider:re});return(0,Q.jsxs)(`section`,{className:`panel`,"aria-labelledby":`compaction-routing-title`,"aria-busy":y||a===void 0&&!x,children:[(0,Q.jsxs)(`div`,{className:`spread`,style:{alignItems:`flex-start`,flexWrap:`wrap`},children:[(0,Q.jsxs)(`div`,{style:{flex:`1 1 20rem`,minWidth:0},children:[(0,Q.jsx)(`div`,{className:`font-semibold`,id:`compaction-routing-title`,children:i(`compactionRouting.title`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:i(`compactionRouting.description`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:i(`compactionRouting.dataNotice`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:i(`compactionRouting.effortHint`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:i(`compactionRouting.sourcesHint`)})]}),(0,Q.jsxs)(`div`,{className:`dash-delegation-controls compaction-routing-controls`,style:{flex:`0 1 auto`},children:[(0,Q.jsxs)(`div`,{className:`compaction-field`,children:[(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`compaction-routing-model`,children:i(`compactionRouting.model`)}),(0,Q.jsx)(dn,{id:`compaction-routing-model`,value:s,options:P,disabled:R,label:i(`compactionRouting.model`),onChange:e=>{c(e),e||(u(``),f(`manual`),m(`all`),g([])),w(null)}})]}),(0,Q.jsxs)(`div`,{className:`compaction-field`,children:[(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`compaction-routing-triggers`,children:i(`compactionRouting.triggers`)}),(0,Q.jsx)(dn,{id:`compaction-routing-triggers`,value:d,disabled:R||!s,align:`right`,label:i(`compactionRouting.triggers`),options:Xi.map(e=>({value:e,label:i(Zi[e])})),onChange:e=>{f(e),w(null)}})]}),(0,Q.jsxs)(`div`,{className:`compaction-field`,children:[(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`compaction-routing-sources`,children:i(`compactionRouting.sources`)}),(0,Q.jsx)(dn,{id:`compaction-routing-sources`,value:p,disabled:R||!s,align:`right`,label:i(`compactionRouting.sources`),options:Qi.map(e=>({value:e,label:i($i[e])})),onChange:e=>{m(e),w(null)}})]}),(0,Q.jsxs)(`div`,{className:`compaction-field`,children:[(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`compaction-routing-effort`,children:i(`compactionRouting.effort`)}),(0,Q.jsx)(dn,{id:`compaction-routing-effort`,value:l,disabled:R||!s,align:`right`,label:i(`compactionRouting.effort`),options:[{value:``,label:i(`compactionRouting.currentEffort`)},...qi.map(e=>({value:e,label:i(`models.reasoningEffort.${e}`)}))],onChange:e=>{u(e),w(null)}})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:R||!V||H,onClick:()=>{N()},children:i(y?`common.saving`:`common.save`)})]})]}),s&&p===`selected`&&(0,Q.jsxs)(`div`,{className:`compaction-sources-block`,children:[(0,Q.jsx)(`div`,{className:`field-label compaction-sources-title`,children:i(`compactionRouting.sourcesGridTitle`)}),(0,Q.jsxs)(`div`,{className:`source-scope-groups`,children:[F.length>0&&(0,Q.jsxs)(`fieldset`,{className:`source-scope-group`,children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:i(`compactionRouting.sourcesProviders`)}),F.map(W)]}),t.length>0&&(0,Q.jsxs)(`fieldset`,{className:`source-scope-group`,children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:i(`compactionRouting.sourcesModels`)}),(0,Q.jsx)(`input`,{type:`search`,className:`input`,value:_,disabled:R,"aria-label":i(`pws.modelSearchPlaceholder`),placeholder:i(`pws.modelSearchPlaceholder`),onChange:e=>v(e.target.value)}),ee.slice(0,Yi).map(W),ee.length>Yi&&(0,Q.jsx)(`p`,{className:`muted text-label`,children:i(`pws.modelsTruncated`,{shown:Yi,total:ee.length})})]}),L.length>0&&(0,Q.jsxs)(`fieldset`,{className:`source-scope-group`,children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:i(`compactionRouting.sourcesSaved`)}),L.map(W)]}),H&&(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:i(`compactionRouting.sourcesNone`)})]})]}),ie&&(0,Q.jsxs)(`div`,{className:`notice-warn`,role:`note`,style:{marginTop:12},children:[(0,Q.jsx)(Ne,{width:14}),` `,ie]}),s&&J&&(0,Q.jsxs)(`div`,{className:`notice-warn`,role:`note`,style:{marginTop:12},children:[(0,Q.jsx)(Ne,{width:14}),` `,i(`compactionRouting.autoNotice`)]}),x&&(0,Q.jsxs)(`div`,{className:`notice notice-err`,role:`alert`,style:{marginTop:12,marginBottom:0},children:[i(`compactionRouting.loadFailed`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{j()},children:i(`common.retry`)})]}),C===`failed`&&(0,Q.jsx)(`div`,{className:`notice notice-err`,role:`alert`,style:{marginTop:12,marginBottom:0},children:i(`compactionRouting.saveFailed`)}),C===`saved`&&(0,Q.jsx)(`div`,{className:`muted setting-hint`,role:`status`,children:i(`compactionRouting.saved`)})]})}function ca(e){if(!(`reasoningRetention`in e))throw Error(`Missing reasoningRetention settings`);return e.reasoningRetention??null}function la({apiBase:e}){let t=n();return(0,Q.jsxs)(`details`,{className:`panel`,children:[(0,Q.jsx)(`summary`,{className:`font-semibold`,children:t(`reasoningRetention.advanced`)}),(0,Q.jsx)(ua,{apiBase:e},e)]})}function ua({apiBase:e}){let t=n(),[r,i]=(0,Z.useState)(),[a,o]=(0,Z.useState)(!1),[s,c]=(0,Z.useState)(`20`),[l,u]=(0,Z.useState)(`100000`),[d,f]=(0,Z.useState)(!1),[p,m]=(0,Z.useState)(!1),[h,g]=(0,Z.useState)(null),_=(0,Z.useRef)(!1),v=(0,Z.useRef)(null),y=(0,Z.useCallback)(e=>{i(e),o(e?.enabled===!0),c(String(e?.maxContextPercent??20)),u(String(e?.maxTokens??1e5))},[]),b=(0,Z.useCallback)(async()=>{if(v.current)return;let t=M(15e3);v.current=t,m(!1);try{let n=ca(await jn(await fetch(`${e}/api/settings`,{signal:t.signal})));_.current&&v.current===t&&y(n)}catch{_.current&&v.current===t&&m(!0)}finally{t.clear(),v.current===t&&(v.current=null)}},[e,y]);(0,Z.useEffect)(()=>{_.current=!0;let e=window.setTimeout(()=>{b()},0);return()=>{window.clearTimeout(e),_.current=!1,v.current?.controller.abort(),v.current?.clear(),v.current=null}},[b]);let x=s.trim()!==``&&Number.isFinite(Number(s))&&Number(s)>0&&Number(s)<=100,S=l.trim()!==``&&Number.isSafeInteger(Number(l))&&Number(l)>0,C=!a||x&&S,w=a!==(r?.enabled===!0)||a&&(Number(s)!==(r?.maxContextPercent??20)||Number(l)!==(r?.maxTokens??1e5)),T=async(t=!1)=>{if(v.current||r===void 0||!t&&!C)return;let n=M(15e3);v.current=n,f(!0),g(null);try{let r=ca(await jn(await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},signal:n.signal,body:JSON.stringify({reasoningRetention:t?null:a?{enabled:!0,maxContextPercent:Number(s),maxTokens:Number(l)}:{enabled:!1}})})));_.current&&v.current===n&&(y(r),g(`saved`))}catch{_.current&&v.current===n&&g(`failed`)}finally{n.clear(),_.current&&v.current===n&&f(!1),v.current===n&&(v.current=null)}},E=d||r===void 0||p;return(0,Q.jsxs)(`section`,{"aria-labelledby":`reasoning-retention-title`,"aria-busy":d||r===void 0&&!p,children:[(0,Q.jsx)(`div`,{className:`font-semibold`,id:`reasoning-retention-title`,children:t(`reasoningRetention.title`)}),(0,Q.jsx)(`p`,{className:`muted setting-hint`,children:t(`reasoningRetention.description`)}),(0,Q.jsx)(`p`,{className:`muted setting-hint`,children:t(`reasoningRetention.storageHint`)}),(0,Q.jsx)(ln,{on:a,disabled:E,label:t(`reasoningRetention.enable`),showLabel:!0,onClick:()=>{o(e=>!e),g(null)}}),(0,Q.jsxs)(`div`,{className:`row`,style:{flexWrap:`wrap`,alignItems:`flex-end`},children:[a&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`label`,{className:`field-label`,htmlFor:`reasoning-retention-percent`,children:[t(`reasoningRetention.percent`),(0,Q.jsx)(`input`,{id:`reasoning-retention-percent`,className:`input`,type:`number`,min:`0`,max:`100`,step:`any`,value:s,disabled:E,"aria-invalid":!x||void 0,"aria-describedby":x?void 0:`reasoning-retention-error`,onInput:e=>{c(e.currentTarget.value),g(null)}})]}),(0,Q.jsxs)(`label`,{className:`field-label`,htmlFor:`reasoning-retention-tokens`,children:[t(`reasoningRetention.tokens`),(0,Q.jsx)(`input`,{id:`reasoning-retention-tokens`,className:`input`,type:`number`,min:`1`,step:`1`,value:l,disabled:E,"aria-invalid":!S||void 0,"aria-describedby":S?void 0:`reasoning-retention-error`,onInput:e=>{u(e.currentTarget.value),g(null)}})]})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:E||!C||!w,onClick:()=>{T()},children:t(`common.save`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:E||r===null&&!w,onClick:()=>{T(!0)},children:t(`reasoningRetention.reset`)})]}),!C&&(0,Q.jsx)(`div`,{id:`reasoning-retention-error`,className:`notice notice-err`,role:`alert`,children:t(`reasoningRetention.invalid`)}),p&&(0,Q.jsxs)(`div`,{className:`notice notice-err`,role:`alert`,children:[t(`reasoningRetention.loadFailed`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{b()},children:t(`common.retry`)})]}),h===`failed`&&(0,Q.jsx)(`div`,{className:`notice notice-err`,role:`alert`,children:t(`reasoningRetention.saveFailed`)}),h===`saved`&&(0,Q.jsx)(`div`,{className:`muted setting-hint`,role:`status`,children:t(`reasoningRetention.saved`)})]})}var da=0;function fa(e){let t=e.split(/\n{2,}/).map(e=>e.trim()).filter(e=>e.length>0);return t.length>0?t:[e]}function pa(e,t,n,r){let i=o[e],a=`opencodex-action-dialog-${++da}`,s=document.activeElement,c=typeof s?.focus==`function`?s:null,l=!1,u=document.createElement(`dialog`);u.id=a,u.className=`modal-overlay`,u.setAttribute(`aria-labelledby`,`${a}-body`);let d=document.createElement(`button`);d.type=`button`,d.className=`modal-backdrop-dismiss`,d.tabIndex=-1,d.setAttribute(`aria-label`,i[`common.close`]);let f=document.createElement(`form`);f.className=`modal-card`;let p=e=>{if(!l){l=!0,window.removeEventListener(`hashchange`,m),window.removeEventListener(`popstate`,m),document.removeEventListener(`keydown`,h),r?.removeEventListener(`abort`,m);try{u.open&&typeof u.close==`function`&&u.close(),u.remove(),c?.isConnected&&c.focus()}finally{n(e)}}};function m(){p(t)}function h(e){e.key===`Escape`&&p(t)}return d.addEventListener(`click`,()=>p(t)),u.addEventListener(`cancel`,e=>{e.preventDefault(),p(t)}),window.addEventListener(`hashchange`,m),window.addEventListener(`popstate`,m),r?.addEventListener(`abort`,m),u.append(d,f),document.body.append(u),typeof u.showModal==`function`?u.showModal():(u.setAttribute(`open`,``),document.addEventListener(`keydown`,h)),{form:f,bodyId:`${a}-body`,finish:p}}function ma(e,t,n,r=`div`){let i=document.createElement(r);i.id=t;for(let e of fa(n)){let t=document.createElement(`p`);t.className=`modal-desc`,t.textContent=e,i.append(t)}return e.append(i),i}function ha(e){let t=e.locale??l(),n=o[t],r=e.tone===`danger`;return new Promise(i=>{if(e.signal?.aborted){i(!1);return}let{form:a,bodyId:o,finish:s}=pa(t,!1,i,e.signal);ma(a,o,e.message);let c=document.createElement(`div`);c.className=`modal-actions`;let l=document.createElement(`button`);l.type=`button`,l.className=`btn btn-ghost`,l.textContent=n[`common.cancel`],l.addEventListener(`click`,()=>s(!1));let u=document.createElement(`button`);u.type=`submit`,u.className=r?`btn btn-danger`:`btn btn-primary`,u.textContent=e.confirmLabel??n[`common.ok`],a.addEventListener(`submit`,e=>{e.preventDefault(),s(!0)}),c.append(l,u),a.append(c),queueMicrotask(()=>(r?l:u).focus())})}function ga(e){let t=e.locale??l(),n=o[t];return new Promise(r=>{if(e.signal?.aborted){r(null);return}let{form:i,bodyId:a,finish:o}=pa(t,null,r,e.signal),s=document.createElement(`input`),c=`${a}-input`,l=ma(i,a,e.message,`label`);l.className=`field-label`,l.setAttribute(`for`,c),s.id=c,s.className=`input`,s.type=`text`,s.value=e.initialValue??``,s.spellcheck=!1,s.autocapitalize=`none`,e.maxLength!==void 0&&(s.maxLength=e.maxLength);let u=document.createElement(`div`),d=`${a}-error`;u.id=d,u.className=`notice notice-err`,u.setAttribute(`role`,`alert`),u.hidden=!0;let f=e=>{u.textContent=e??``,u.hidden=e===null,e===null?(s.removeAttribute(`aria-invalid`),s.removeAttribute(`aria-describedby`)):(s.setAttribute(`aria-invalid`,`true`),s.setAttribute(`aria-describedby`,d))},p=document.createElement(`div`);p.className=`modal-actions`;let m=document.createElement(`button`);m.type=`button`,m.className=`btn btn-ghost`,m.textContent=n[`common.cancel`],m.addEventListener(`click`,()=>o(null));let h=document.createElement(`button`);h.type=`submit`,h.className=`btn btn-primary`,h.textContent=e.confirmLabel??n[`common.save`],i.addEventListener(`submit`,t=>{t.preventDefault();let n=s.value,r=e.validate?.(n)??null;f(r),r===null?o(n):(h.disabled=!0,s.focus())}),s.addEventListener(`input`,()=>{h.disabled&&=!1,u.hidden||f(null)}),p.append(m,h),i.append(s,u,p),queueMicrotask(()=>s.focus())})}function _a(){return pt()}function va(e,t){return typeof window<`u`&&typeof window.setInterval==`function`?window.setInterval(e,t):setInterval(e,t)}function ya(e){typeof window<`u`&&typeof window.clearInterval==`function`?window.clearInterval(e):clearInterval(e)}function ba(e,t,n){let r=n?.pauseWhenHidden!==!1,i=null,a=!1,o=()=>{try{e()}catch(e){console.error(`[visibility-poll]`,e)}},s=()=>{i!==null||a||(i=va(o,t))},c=()=>{i!==null&&(ya(i),i=null)},l=()=>{r&&(_a()?c():(o(),s()))};r&&_a()||s();let u=r?mt(l):null;return n?.immediate&&o(),()=>{a=!0,c(),u?.()}}var xa=new Map;function Sa(e,t){let n=`${e}:${t}`,r=xa.get(n);return r||(r=new Intl.NumberFormat(e,{minimumFractionDigits:t,maximumFractionDigits:t}),xa.set(n,r)),r}var Ca=new Map;function wa(e){let t=Ca.get(e);return t||(t=new Intl.NumberFormat(e),Ca.set(e,t)),t}function Ta(e,t){if(!Number.isFinite(e)||e<=0)return`0 B`;let n=[`B`,`KiB`,`MiB`,`GiB`,`TiB`],r=Math.min(Math.floor(Math.log(e)/Math.log(1024)),n.length-1),i=e/1024**r;return`${Sa(t,r===0?0:1).format(i)} ${n[r]}`}function Ea(e,t){return!Number.isFinite(e)||e<0?`—`:gr(e/1e3,t)}function Da(e){return typeof e.observedBytes==`number`?e.observedBytes:Math.max(e.rss,e.external??0,e.arrayBuffers??0)}function Oa(e){if(e.observedMetric)return e.observedMetric;if(e.watchdog?.observedMetric)return e.watchdog.observedMetric;let t=[{metric:`rss`,bytes:e.rss},{metric:`external`,bytes:e.external??0},{metric:`arrayBuffers`,bytes:e.arrayBuffers??0}];return t.reduce((e,t)=>t.bytes>e.bytes?t:e,t[0]).metric}function ka(e){if(e.length<2)return null;let t=e[0],n=e[e.length-1],r=n.at-t.at;return r<=0?null:(Da(n)-Da(t))/r*36e5}function Aa({label:e,value:t,sub:n,tone:r}){return(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`label`,children:e}),(0,Q.jsx)(`div`,{className:`value mono${r?` value--${r}`:``}`,children:t}),n&&(0,Q.jsx)(`div`,{className:`stat-sub mono`,children:n})]})}function ja({observedBytes:e,thresholdBytes:t,metric:n,locale:r,t:i}){let a=e!==null&&t!==null&&t>0?e/t:null,o=a===null?`unknown`:a>=1?`over`:a>=.75?`warn`:`ok`,s=a===null?null:Math.round(a*100);return(0,Q.jsxs)(`div`,{className:`mem-pressure mem-pressure--${o}`,children:[(0,Q.jsxs)(`div`,{className:`mem-pressure-head`,children:[(0,Q.jsxs)(`span`,{className:`mem-pressure-label`,children:[i(`dash.mem.pressure`),n?(0,Q.jsx)(`span`,{className:`mem-pressure-metric mono`,children:n}):null]}),(0,Q.jsxs)(`span`,{className:`mem-pressure-figure mono`,children:[e===null?`—`:Ta(e,r),t!==null&&(0,Q.jsxs)(`span`,{className:`mem-pressure-limit`,children:[` / `,Ta(t,r)]})]})]}),(0,Q.jsx)(`div`,{className:`mem-pressure-track`,role:`presentation`,children:(0,Q.jsx)(`span`,{className:`mem-pressure-fill`,style:{"--mem-scale":String(a===null?0:Math.min(1,Math.max(.01,a)))}})}),(0,Q.jsx)(`div`,{className:`mem-pressure-foot`,children:s===null?i(`dash.mem.pressureUnknown`):i(`dash.mem.pressureOf`,{pct:s})})]})}var Ma=60,Na=1500,Pa=12e4;function Fa({apiBase:e}){let{locale:t,t:n}=r(),[i,a]=(0,Z.useState)(null),[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(`idle`),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)(!1),[m,h]=(0,Z.useState)(!1),[g,_]=(0,Z.useState)(null);(0,Z.useEffect)(()=>{let t=!1;return(async()=>{try{let n=await fetch(`${e}/api/startup-health`);if(!n.ok||t)return;let r=await n.json();t||p(r.protection===`none`)}catch{}})(),()=>{t=!0}},[e]),(0,Z.useEffect)(()=>{let t=!1,n=!1,r=null,i=async()=>{if(n)return;n=!0;let i=M(1e4);r=i;try{let n=await fetch(`${e}/api/system/memory`,{signal:i.signal});if(!n.ok)throw Error(`memory unavailable`);let r=await n.json();if(t)return;a(r),s(!1),h(typeof r.activeTurnCount==`number`),r.isDraining&&c===`idle`&&l(`draining`),(c===`draining`||c===`reconnecting`)&&g!=null&&typeof r.pid==`number`&&r.pid!==g&&!r.isDraining&&(l(`idle`),_(null),d(null))}catch{if(t)return;c===`draining`||c===`reconnecting`?l(`reconnecting`):s(!0)}finally{i.clear(),r===i&&(r=null),n=!1}};i();let o=ba(()=>void i(),5e3);return()=>{t=!0,r?.controller.abort(),r?.clear(),o()}},[e,c,g]),(0,Z.useEffect)(()=>{if(c!==`reconnecting`)return;let t=!1,r=!1,i=null,a=Date.now(),o=()=>{if(r||t)return;r=!0;let o=M(5e3);i=o,fetch(`${e}/api/system/health`,{cache:`no-store`,signal:o.signal}).then(async e=>{if(t)return;if(!e.ok){Date.now()-a>=Pa&&(l(`error`),d(n(`dash.mem.restartFailed`)));return}let r=g==null;if(g!=null)try{let t=await e.json();r=typeof t.pid==`number`&&t.pid!==g}catch{r=!0}t||(r?(l(`idle`),_(null),d(null)):Date.now()-a>=Pa&&(l(`error`),d(n(`dash.mem.restartFailed`))))}).catch(()=>{t||Date.now()-a>=Pa&&(l(`error`),d(n(`dash.mem.restartFailed`)))}).finally(()=>{o.clear(),i===o&&(i=null),r=!1})};o();let s=setInterval(o,Na);return()=>{t=!0,i?.controller.abort(),i?.clear(),clearInterval(s)}},[e,c,g,n]);let v=async()=>{let t=i?.activeTurnCount??0,r=[n(`dash.mem.restartConfirm`,{count:t,seconds:Ma})];if(f&&r.push(n(`dash.mem.restartNoSupervisor`)),await ha({message:r.join(`
2
2
 
3
3
  `),tone:`danger`})){d(null),_(typeof i?.pid==`number`?i.pid:null),l(`draining`);try{if(!(await fetch(`${e}/api/system/restart`,{method:`POST`})).ok)throw Error(`restart_failed`)}catch{l(`error`),_(null),d(n(`dash.mem.restartFailed`))}}};if(o&&!i&&c===`idle`)return(0,Q.jsxs)(`div`,{className:`panel`,style:{marginBottom:24},children:[(0,Q.jsxs)(`div`,{className:`font-semibold`,style:{display:`flex`,alignItems:`center`,gap:8},children:[(0,Q.jsx)(P,{width:16,height:16,"aria-hidden":`true`}),n(`dash.mem.title`)]}),(0,Q.jsx)(`div`,{className:`muted text-control`,style:{marginTop:8},children:n(`dash.mem.unavailable`)})]});let y=i?.watchdog?ka(i.watchdog.samples):null,b=i?i.observedBytes??i.watchdog?.observedBytes??Da(i):null,x=i?Oa(i):null,S=(()=>{let e=i?.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=i?.responseState,w=i?.activeTurnCount,T=c===`draining`||c===`reconnecting`;return(0,Q.jsxs)(`div`,{className:`panel`,style:{marginBottom:24},children:[(0,Q.jsxs)(`div`,{className:`mem-head`,children:[(0,Q.jsxs)(`div`,{className:`font-semibold mem-head-title`,children:[(0,Q.jsx)(P,{width:16,height:16,"aria-hidden":`true`}),n(`dash.mem.title`)]}),m&&(0,Q.jsxs)(`div`,{className:`mem-head-actions`,children:[(0,Q.jsxs)(`span`,{className:`mem-inflight`,children:[(0,Q.jsx)(`span`,{className:`mem-inflight-label`,children:n(`dash.mem.inFlight`)}),(0,Q.jsx)(`span`,{className:`mem-inflight-value mono`,children:typeof w==`number`?wa(t).format(w):`—`})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:T,onClick:()=>{v()},children:n(`dash.mem.restart`)})]})]}),(0,Q.jsx)(ja,{observedBytes:b,thresholdBytes:i?.watchdog?.warnThresholdBytes??null,metric:x,locale:t,t:n}),(0,Q.jsxs)(`div`,{className:`stat-row mem-stats`,children:[(0,Q.jsx)(Aa,{label:n(`dash.mem.rss`),value:i?Ta(i.rss,t):`—`}),(0,Q.jsx)(Aa,{label:n(`dash.mem.jsHeap`),value:i?Ta(i.heapUsed,t):`—`,sub:i?n(`dash.mem.jsHeapArena`,{total:Ta(i.heapTotal,t)}):void 0}),(0,Q.jsx)(Aa,{label:n(`dash.mem.jscHeap`),value:i?.jscHeap?Ta(i.jscHeap.heapSize,t):`—`}),(0,Q.jsx)(Aa,{label:n(`dash.mem.growth`),value:y===null?`—`:`${y>=0?`+`:`−`}${Ta(Math.abs(y),t)}${n(`dash.mem.perHour`)}`,tone:S})]}),(0,Q.jsxs)(`details`,{style:{marginTop:10},children:[(0,Q.jsx)(`summary`,{className:`muted text-label`,style:{cursor:`pointer`,padding:`2px 2px`},children:n(`dash.mem.details`)}),(0,Q.jsx)(`div`,{className:`muted text-control`,style:{margin:`8px 0 0`},children:n(`dash.mem.hint`)}),(0,Q.jsx)(`div`,{className:`muted text-label`,style:{margin:`14px 0 6px`},children:n(`dash.mem.runtime`)}),(0,Q.jsxs)(`div`,{className:`stat-row`,children:[(0,Q.jsx)(Aa,{label:n(`dash.mem.observed`),value:b===null?`—`:`${Ta(b,t)} (${x})`}),(0,Q.jsx)(Aa,{label:n(`dash.mem.external`),value:i?.external===void 0?`—`:Ta(i.external,t)}),(0,Q.jsx)(Aa,{label:n(`dash.mem.arrayBuffers`),value:i?.arrayBuffers===void 0?`—`:Ta(i.arrayBuffers,t)})]}),(0,Q.jsx)(`div`,{className:`muted text-label`,style:{margin:`14px 0 6px`},children:n(`dash.mem.store`)}),(0,Q.jsx)(`div`,{className:`muted text-control`,style:{marginBottom:10},children:n(`dash.mem.storeHint`)}),(0,Q.jsxs)(`div`,{className:`stat-row`,children:[(0,Q.jsx)(Aa,{label:n(`dash.mem.storeEntries`),value:C?wa(t).format(C.count):`—`}),(0,Q.jsx)(Aa,{label:n(`dash.mem.storeTotal`),value:C?Ta(C.totalBytes,t):`—`}),(0,Q.jsx)(Aa,{label:n(`dash.mem.storeLargest`),value:C?Ta(C.largestBytes,t):`—`}),(0,Q.jsx)(Aa,{label:n(`dash.mem.storeOldest`),value:C?C.count===0?`—`:Ea(C.oldestAgeMs,t):`—`})]}),i?.watchdog&&(0,Q.jsxs)(`div`,{className:`stat-row`,style:{marginTop:16},children:[(0,Q.jsx)(Aa,{label:n(`dash.mem.threshold`),value:Ta(i.watchdog.warnThresholdBytes,t)}),(0,Q.jsx)(Aa,{label:n(`dash.mem.lastWarn`),value:i.watchdog.lastWarnAt?new Date(i.watchdog.lastWarnAt).toLocaleString(t):n(`dash.mem.never`)})]})]}),m&&(0,Q.jsxs)(`div`,{className:`mem-status`,"aria-live":`polite`,children:[c===`draining`&&(0,Q.jsx)(`span`,{className:`muted text-control`,children:n(`dash.mem.draining`,{count:typeof w==`number`?w:0})}),c===`reconnecting`&&(0,Q.jsx)(`span`,{className:`muted text-control`,children:n(`dash.mem.reconnecting`)}),c===`error`&&u&&(0,Q.jsx)(`span`,{className:`text-control`,style:{color:`var(--danger, #c44)`},children:u}),f&&c===`idle`&&(0,Q.jsx)(`span`,{className:`muted text-control`,children:n(`dash.mem.restartNoSupervisor`)})]})]})}var Ia=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`,`ultra`];function La(e){let t=e.memoryModels;if(t==null)return{};if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`invalid settings`);let n={};for(let e of[`extract`,`consolidation`]){let r=t[e];if(r===void 0)continue;if(!r||typeof r!=`object`||Array.isArray(r))throw Error(`invalid phase`);let i=`model`in r&&typeof r.model==`string`?r.model.trim():``;if(!i)throw Error(`invalid model`);let a=`reasoningEffort`in r?r.reasoningEffort:void 0;if(a!==void 0&&(typeof a!=`string`||!Ia.includes(a)))throw Error(`invalid effort`);n[e]={model:i,...a?{reasoningEffort:a}:{}}}return n}function Ra(e,t){return e?{model:e,...t?{reasoningEffort:t}:{}}:void 0}function za(e){return(0,Q.jsx)(Ba,{...e},e.apiBase)}function Ba({apiBase:e,models:t}){let r=n(),[i,a]=(0,Z.useState)(void 0),[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(``),[u,d]=(0,Z.useState)(``),[f,p]=(0,Z.useState)(``),[m,h]=(0,Z.useState)(``),[g,_]=(0,Z.useState)(!1),[v,y]=(0,Z.useState)(!1),[b,x]=(0,Z.useState)(null),S=(0,Z.useRef)(!1),C=(0,Z.useRef)(null),w=(0,Z.useRef)(null),T=lr(o,w),E=(0,Z.useCallback)(e=>{a(e),l(e.extract?.model??``),d(e.extract?.reasoningEffort??``),p(e.consolidation?.model??``),h(e.consolidation?.reasoningEffort??``)},[]),D=(0,Z.useCallback)(async()=>{if(C.current)return;let t=M(15e3);C.current=t,y(!1);try{let n=La(await jn(await fetch(`${e}/api/settings`,{signal:t.signal})));S.current&&C.current===t&&E(n)}catch{S.current&&C.current===t&&y(!0)}finally{t.clear(),C.current===t&&(C.current=null)}},[e,E]);(0,Z.useEffect)(()=>{S.current=!0;let e=window.setTimeout(()=>{D()},0);return()=>{window.clearTimeout(e),S.current=!1,C.current?.controller.abort(),C.current?.clear(),C.current=null}},[D]);let O=async()=>{if(C.current||i===void 0)return;let t=M(15e3);C.current=t,_(!0),x(null);let n=Ra(c,u),r=Ra(f,m);try{let i=La(await jn(await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({memoryModels:n||r?{...n?{extract:n}:{},...r?{consolidation:r}:{}}:null}),signal:t.signal})));S.current&&C.current===t&&(E(i),x(`saved`))}catch{S.current&&C.current===t&&x(`failed`)}finally{t.clear(),S.current&&C.current===t&&_(!1),C.current===t&&(C.current=null)}},k=[{value:``,label:r(`memoryModels.off`)},...[...new Set([...t.map(e=>e.namespaced),...[c,f].filter(Boolean)])].map(e=>({value:e,label:we(e,r)}))],A=[{value:``,label:r(`memoryModels.defaultEffort`)},...Ia.map(e=>({value:e,label:r(`models.reasoningEffort.${e}`)}))],j=g||i===void 0||v,N=c!==(i?.extract?.model??``)||u!==(i?.extract?.reasoningEffort??``)||f!==(i?.consolidation?.model??``)||m!==(i?.consolidation?.reasoningEffort??``),P=!!c!=!!f,F=r(`memoryModels.info`),I=(e,t,n,i,a)=>(0,Q.jsxs)(`div`,{className:`spread memory-models-row`,style:{flexWrap:`wrap`,gap:8,marginTop:12},children:[(0,Q.jsxs)(`div`,{style:{flex:`1 1 18rem`,minWidth:0},children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:r(`memoryModels.${e}`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:r(`memoryModels.${e}Hint`)})]}),(0,Q.jsxs)(`div`,{className:`memory-models-controls`,children:[(0,Q.jsx)(dn,{id:`memory-models-${e}`,value:t,options:k,disabled:j,label:r(`memoryModels.model`),onChange:e=>{i(e),e||a(``),x(null)}}),(0,Q.jsx)(dn,{id:`memory-models-${e}-effort`,value:n,options:A,disabled:j||!t,align:`right`,label:r(`memoryModels.effort`),onChange:e=>{a(e),x(null)}})]})]});return(0,Q.jsxs)(`section`,{className:`panel`,"aria-labelledby":`memory-models-title`,"aria-busy":g||i===void 0&&!v,children:[(0,Q.jsxs)(`div`,{className:`font-semibold`,id:`memory-models-title`,style:{display:`flex`,alignItems:`center`,gap:6},children:[r(`memoryModels.title`),(0,Q.jsx)(`button`,{ref:w,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":r(`memoryModels.infoLabel`),"aria-expanded":o,"aria-haspopup":`dialog`,"aria-controls":`memory-models-help-dialog`,children:(0,Q.jsx)(De,{width:13,height:13,"aria-hidden":`true`})})]}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:r(`memoryModels.description`)}),I(`extract`,c,u,l,d),I(`consolidation`,f,m,p,h),(0,Q.jsxs)(`div`,{className:`spread`,style:{alignItems:`center`,flexWrap:`wrap`,gap:8,marginTop:12},children:[(0,Q.jsx)(`div`,{className:`muted setting-hint`,style:{flex:`1 1 18rem`,minWidth:0},children:r(`memoryModels.dataNotice`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:j||!N,onClick:()=>{O()},children:r(g?`common.saving`:`common.save`)})]}),P&&(0,Q.jsxs)(`div`,{className:`notice-warn`,role:`note`,style:{marginTop:12},children:[(0,Q.jsx)(Ne,{width:14}),` `,r(`memoryModels.accountNotice`)]}),v&&(0,Q.jsxs)(`div`,{className:`notice notice-err`,role:`alert`,style:{marginTop:12,marginBottom:0},children:[r(`memoryModels.loadFailed`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{D()},children:r(`common.retry`)})]}),b===`failed`&&(0,Q.jsx)(`div`,{className:`notice notice-err`,role:`alert`,style:{marginTop:12,marginBottom:0},children:r(`memoryModels.saveFailed`)}),b===`saved`&&(0,Q.jsx)(`div`,{className:`muted setting-hint`,role:`status`,children:r(`memoryModels.saved`)}),(0,Q.jsxs)(`dialog`,{ref:T,id:`memory-models-help-dialog`,className:`modal-overlay`,style:{display:o?`flex`:`none`,border:`none`,margin:0,maxWidth:`none`,maxHeight:`none`,width:`100%`,height:`100%`},"aria-labelledby":`memory-models-help-title`,onCancel:e=>{e.preventDefault(),s(!1)},children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":r(`common.close`),tabIndex:-1,onClick:()=>s(!1)}),(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:`memory-models-help-title`,children:r(`memoryModels.title`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:()=>s(!1),"aria-label":r(`common.close`),children:(0,Q.jsx)(xe,{})})]}),(0,Q.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:F}),(0,Q.jsx)(`div`,{className:`modal-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>s(!1),children:r(`common.ok`)})})]})]})]})}function Va(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Invalid reasoning settings`);let t=e;if(typeof t.modelSwitch!=`boolean`||typeof t.accountSwitch!=`boolean`)throw Error(`Missing reasoning settings`);return{modelSwitch:t.modelSwitch,accountSwitch:t.accountSwitch}}function Ha({apiBase:e}){return(0,Q.jsx)(Ua,{apiBase:e},e)}function Ua({apiBase:e}){let t=n(),[r,i]=(0,Z.useState)(),[a,o]=(0,Z.useState)(!1),[s,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(!1),[d,f]=(0,Z.useState)(!1),[p,m]=(0,Z.useState)(null),h=(0,Z.useRef)(!1),g=(0,Z.useRef)(null),_=(0,Z.useCallback)(e=>{i(e),o(e.modelSwitch),c(e.accountSwitch)},[]),v=(0,Z.useCallback)(async()=>{if(g.current)return;let t=M(15e3);g.current=t,f(!1);try{let n=Va(await jn(await fetch(`${e}/api/native-reasoning-retention`,{signal:t.signal})));h.current&&g.current===t&&_(n)}catch{h.current&&g.current===t&&f(!0)}finally{t.clear(),g.current===t&&(g.current=null)}},[e,_]);(0,Z.useEffect)(()=>{h.current=!0;let e=window.setTimeout(()=>{v()},0);return()=>{window.clearTimeout(e),h.current=!1,g.current?.controller.abort(),g.current?.clear(),g.current=null}},[v]);let y=async(t=!1)=>{if(g.current||r===void 0)return;let n=M(15e3);g.current=n,u(!0),m(null);try{let r=Va(await jn(await fetch(`${e}/api/native-reasoning-retention`,{method:`PUT`,headers:{"Content-Type":`application/json`},signal:n.signal,body:JSON.stringify(t?null:{modelSwitch:a,accountSwitch:s})})));h.current&&g.current===n&&(_(r),m(`saved`))}catch{h.current&&g.current===n&&m(`failed`)}finally{n.clear(),h.current&&g.current===n&&u(!1),g.current===n&&(g.current=null)}},b=l||r===void 0||d,x=a!==r?.modelSwitch||s!==r?.accountSwitch;return(0,Q.jsxs)(`section`,{className:`panel`,"aria-labelledby":`native-reasoning-retention-title`,"aria-busy":l||r===void 0&&!d,children:[(0,Q.jsx)(`div`,{className:`font-semibold`,id:`native-reasoning-retention-title`,children:t(`nativeReasoningRetention.title`)}),(0,Q.jsx)(`p`,{className:`muted setting-hint`,children:t(`nativeReasoningRetention.description`)}),(0,Q.jsxs)(`div`,{className:`stack`,style:{gap:`var(--space-3)`},children:[(0,Q.jsxs)(`div`,{className:`spread`,children:[(0,Q.jsx)(`span`,{children:t(`nativeReasoningRetention.modelSwitch`)}),(0,Q.jsx)(ln,{on:a,disabled:b,label:t(`nativeReasoningRetention.modelSwitch`),onClick:()=>{o(e=>!e),m(null)}})]}),(0,Q.jsxs)(`div`,{className:`spread`,children:[(0,Q.jsx)(`span`,{children:t(`nativeReasoningRetention.accountSwitch`)}),(0,Q.jsx)(ln,{on:s,disabled:b,label:t(`nativeReasoningRetention.accountSwitch`),onClick:()=>{c(e=>!e),m(null)}})]}),(0,Q.jsx)(`p`,{className:`muted setting-hint`,children:t(`nativeReasoningRetention.accountHint`)}),(0,Q.jsxs)(`div`,{className:`row`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:b||!x,onClick:()=>{y()},children:t(`common.save`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:b||!x&&!r?.modelSwitch&&!r?.accountSwitch,onClick:()=>{y(!0)},children:t(`nativeReasoningRetention.reset`)})]})]}),d&&(0,Q.jsxs)(`div`,{className:`notice notice-err`,role:`alert`,children:[t(`nativeReasoningRetention.loadFailed`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{v()},children:t(`common.retry`)})]}),p===`failed`&&(0,Q.jsx)(`div`,{className:`notice notice-err`,role:`alert`,children:t(`nativeReasoningRetention.saveFailed`)}),p===`saved`&&(0,Q.jsx)(`div`,{className:`muted setting-hint`,role:`status`,children:t(`nativeReasoningRetention.saved`)})]})}function Wa(e,t){switch(t){case`helper`:return e(`shadowCall.sourceHelper`);case`memory`:return e(`shadowCall.sourceMemory`);case`legacy`:return e(`shadowCall.sourceLegacy`);case`custom`:return e(`shadowCall.sourceCustom`)}}function Ga({options:e,sourceModels:t,disabled:r=!1,saving:i=!1,onChange:a,className:o}){let s=n(),c=(0,Z.useId)();return!e||e.length===0?null:(0,Q.jsxs)(`div`,{className:[`shadow-source-toggles`,o].filter(Boolean).join(` `),role:`group`,"aria-label":s(`shadowCall.sources`),"aria-describedby":c,children:[(0,Q.jsx)(`div`,{className:`shadow-source-toggle-list`,children:e.map(e=>{let n=wn(e.id,t),o=Tn(e,t),c=`blocked`in o&&o.blocked===`covered`?o.prefix:void 0,l=`blocked`in o&&o.blocked===`last`,u=c?s(`shadowCall.sourceCovered`,{prefix:c}):l?s(`shadowCall.sourceLastRequired`):void 0,d=c?s(`shadowCall.sourceCoveredShort`,{prefix:c}):l?s(`shadowCall.sourceRequired`):void 0;return(0,Q.jsxs)(`span`,{className:`shadow-source-toggle${n?` on`:``}`,children:[(0,Q.jsx)(ln,{on:n,onClick:()=>{`sourceModels`in o&&a(o.sourceModels)},disabled:r||i||c!==void 0||l,label:`${e.id} (${Wa(s,e.role)})`,title:u}),(0,Q.jsx)(`code`,{className:`shadow-source-id`,children:Cn([e.id])}),(0,Q.jsx)(`span`,{className:`muted text-caption shadow-source-role`,children:Wa(s,e.role)}),d?(0,Q.jsx)(`span`,{className:`muted text-caption shadow-source-reason`,children:d}):null]},e.id)})}),(0,Q.jsx)(`span`,{id:c,className:`muted text-caption shadow-source-hint`,children:s(`shadowCall.sourceHint`)})]})}function Ka({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,Q.jsx)(`div`,{className:`panel dash-effort-panel`,children:(0,Q.jsxs)(`div`,{className:`injection-head`,children:[(0,Q.jsxs)(`span`,{className:`injection-label`,style:{display:`inline-flex`,alignItems:`center`,gap:6},children:[n(`dash.effortCapLabel`),(0,Q.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,Q.jsx)(De,{width:13,height:13,"aria-hidden":`true`})})]}),(0,Q.jsxs)(`div`,{className:`dash-effort-controls`,children:[(0,Q.jsx)(dn,{value:c,options:[{value:``,label:n(`dash.effortCapNone`)},...Mn.map(e=>({value:e,label:e}))],onChange:async t=>{if(!u){p(!0);try{let n=await jn(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,Q.jsx)(dn,{value:l,options:[{value:``,label:n(`dash.effortCapNone`)},...Mn.map(e=>({value:e,label:e}))],onChange:async t=>{if(!u){p(!0);try{let n=await jn(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 qa({d:e}){let{t,injectionModel:n,injectionEffort:r,injectionEfforts:i,injectionAvailable:a,injectionSaving:o,saveInjection:s}=e;return(0,Q.jsxs)(`div`,{className:`panel dash-delegation-summary`,children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:t(`dash.injectionLabel`)}),(0,Q.jsxs)(`div`,{className:`dash-delegation-controls`,children:[(0,Q.jsx)(dn,{value:n,options:[{value:``,label:t(`dash.injectionNone`)},...a.map(e=>({value:e.namespaced,label:we(`${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,Q.jsx)(dn,{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,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>Xt(`#subagents`),children:t(`dash.injectionManage`)})]})]})}function Ja({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,Z.useState)(!1),_=(0,Z.useRef)(null);(0,Z.useEffect)(()=>(_.current&&=(clearTimeout(_.current),null),(l||u)&&!m&&(_.current=setTimeout(()=>{_.current=null,g(!0),p()},u?8e3:6e3)),()=>{_.current&&clearTimeout(_.current)}),[l,u,m,p]);let v=()=>{g(!1),n()},y=()=>{g(!0),p()};return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`panel maintenance-panel`,children:[(0,Q.jsxs)(`div`,{className:`dash-sync-summary`,children:[(0,Q.jsxs)(`div`,{className:`dash-sync-copy`,children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:t(`dash.syncModels`)}),(0,Q.jsx)(`div`,{className:`muted text-control dash-sync-hint`,children:t(`dash.syncModelsHint`)})]}),(0,Q.jsxs)(`div`,{className:`maintenance-actions`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:v,disabled:r||i,children:[(0,Q.jsx)(ae,{className:r?`spin-icon`:void 0}),` `,t(r?`dash.syncing`:`dash.syncRun`)]}),(0,Q.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,Q.jsxs)(`div`,{className:`notice ${d.status===`failed`?`notice-err`:`notice-ok`} maintenance-notice`,role:`status`,children:[d.status===`failed`?(0,Q.jsx)(Ne,{}):(0,Q.jsx)(ae,{}),(0,Q.jsxs)(`span`,{children:[Fn(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,Q.jsxs)(`div`,{className:`action-toast notice ${m?`notice-warn`:`notice-ok`}`,role:`status`,"aria-live":`polite`,children:[m?(0,Q.jsx)(Ne,{}):(0,Q.jsx)(Oe,{}),(0,Q.jsxs)(`span`,{children:[t(`dash.syncOk`,{count:l.added}),l.warning?` ${l.warning}`:``,l.nativeSubagentDefaultsWarning?` ${l.nativeSubagentDefaultsWarning}`:``,l.staleAppServerHint?(0,Q.jsxs)(Q.Fragment,{children:[` `,(0,Q.jsx)(O,{k:`dash.syncStaleHint`,cmd:`ocx sync --restart-codex`})]}):null]}),(0,Q.jsx)(`button`,{type:`button`,className:`action-toast-dismiss`,onClick:y,"aria-label":t(`api.dismiss`),children:(0,Q.jsx)(xe,{width:13,height:13,"aria-hidden":`true`})})]}),!h&&u&&(0,Q.jsxs)(`div`,{className:`action-toast notice notice-err`,role:`status`,"aria-live":`polite`,children:[(0,Q.jsx)(Ne,{}),(0,Q.jsx)(`span`,{children:t(`dash.syncFailed`,{error:u})}),(0,Q.jsx)(`button`,{type:`button`,className:`action-toast-dismiss`,onClick:y,"aria-label":t(`api.dismiss`),children:(0,Q.jsx)(xe,{width:13,height:13,"aria-hidden":`true`})})]})]})}function Ya({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,Z.useRef)(null),g=(0,Z.useRef)(null),[_,v]=(0,Z.useState)(),y=(0,Z.useCallback)(()=>{n.current&&v(cn(n.current.getBoundingClientRect(),{align:`right`,placement:`below`,menuHeight:h.current?.offsetHeight??180}))},[n]);return(0,Z.useLayoutEffect)(()=>{if(!t)return;y();let e=()=>y();return window.addEventListener(`resize`,e),window.addEventListener(`scroll`,e,!0),()=>{window.removeEventListener(`resize`,e),window.removeEventListener(`scroll`,e,!0)}},[t,y,a,s]),(0,Z.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,Z.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,Z.useEffect)(()=>{t&&g.current?.focus()},[t]),t?(0,Q.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:{..._,zIndex:60},children:[(0,Q.jsx)(`div`,{className:`dash-vision-advanced-popover-title`,children:e(`dash.visionAdvancedPopover`)}),(0,Q.jsxs)(`label`,{className:`dash-vision-number`,children:[(0,Q.jsx)(`span`,{className:`muted setting-hint`,id:`dash-vision-max-label`,children:e(`dash.visionMaxDescriptions`)}),(0,Q.jsx)(`span`,{className:`codex-auto-switch-input-wrap`,children:(0,Q.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,Q.jsx)(`span`,{id:`dash-vision-max-error`,className:`muted setting-hint`,role:`alert`,children:e(`dash.visionMaxDescriptionsInvalid`)})]}),(0,Q.jsxs)(`label`,{className:`dash-vision-number`,children:[(0,Q.jsx)(`span`,{className:`muted setting-hint`,id:`dash-vision-timeout-label`,children:e(`dash.visionTimeout`)}),(0,Q.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,children:[(0,Q.jsx)(`input`,{className:`input mono codex-auto-switch-input`,type:`number`,min:Kn,max:Gn,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,Q.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`ms`})]}),s&&(0,Q.jsx)(`span`,{id:`dash-vision-timeout-error`,className:`muted setting-hint`,role:`alert`,children:e(`dash.visionTimeoutInvalid`,{min:Kn,max:Gn})})]})]}):null}function Xa({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,sidecarCodexApply:m,shadowCall:h,shadowCallSaving:g,shadowCallError:_,shadowCallHelpTriggerRef:v,shadowCallHelpOpen:y,setShadowCallHelpOpen:b,saveShadowCall:x}=e,S=t(`shadowCall.memoryLabel`),C=c?.vision?.enabled!==!1,w=C?c?.vision?.model??`gpt-5.6-luna`:``,T=c?.vision.backend??d.find(e=>e.value===c?.vision.model)?.backend,E=c?.webSearch.backend??u.find(e=>e.value===c?.webSearch.model)?.backend,D=c?.webSearch?.enabled!==!1,O=D?c?.webSearch?.model??`gpt-5.6-luna`:``,k=c?.vision?.reasoning??`low`,A=Xn(f,w),j=Qn(A,k),M=String(c?.vision?.maxDescriptionsPerTurn??8),N=String(c?.vision?.timeoutMs??Wn),[P,F]=(0,Z.useState)(null),[I,L]=(0,Z.useState)(null),[R,z]=(0,Z.useState)(!1),[B,V]=(0,Z.useState)(!1),[H,U]=(0,Z.useState)(!1),ee=(0,Z.useRef)(null),W=P??M,te=I??N,G=(e=W)=>{let t=qn(e);t===void 0?(F(e),z(!0)):(z(!1),F(null),t!==(c?.vision?.maxDescriptionsPerTurn??8)&&p(Hn(t)))},ne=(e=te)=>{let t=Jn(e);t===void 0?(L(e),V(!0)):(V(!1),L(null),t!==(c?.vision?.timeoutMs??Wn)&&p(Un(t)))};return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`panel`,children:(0,Q.jsxs)(`div`,{className:`spread`,children:[(0,Q.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:t(`dash.codexAutoStart`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.codexAutoStartHint`)})]}),(0,Q.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,Q.jsx)(`span`,{className:`knob`})})]})}),(0,Q.jsx)(`div`,{className:`panel`,children:(0,Q.jsxs)(`div`,{className:`spread`,children:[(0,Q.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:t(`dash.codexDesktopAuthless`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.codexDesktopAuthlessHint`)}),n?.codexDesktopAuthless&&(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.codexRemoteHistoryHint`)}),n?.catalogRefreshPending&&(0,Q.jsx)(`div`,{className:`muted setting-hint`,role:`status`,children:t(`codexAuth.catalogRefreshPending`)})]}),(0,Q.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,Q.jsx)(`span`,{className:`knob`})})]})}),(0,Q.jsx)(`div`,{className:`panel`,children:(0,Q.jsxs)(`div`,{className:`spread`,children:[(0,Q.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:t(`dash.codexClientCompaction`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.codexClientCompactionHint`)}),!n?.codexDesktopAuthless&&n?.codexClientCompaction&&(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.codexRemoteHistoryHint`)}),n?.catalogRefreshPending&&(0,Q.jsx)(`div`,{className:`muted setting-hint`,role:`status`,children:t(`codexAuth.catalogRefreshPending`)})]}),(0,Q.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,Q.jsx)(`span`,{className:`knob`})})]})}),(0,Q.jsxs)(`div`,{className:`dash-sidecar-grid`,children:[(0,Q.jsxs)(`div`,{className:`panel dash-delegation-summary dash-sidecar-row-card`,"aria-busy":!c||void 0,children:[(0,Q.jsxs)(`div`,{className:`dash-sidecar-copy`,children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:t(`dash.webSearchSidecar`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.webSearchSidecarHint`)}),Bn(m)&&(0,Q.jsxs)(`div`,{className:`notice-warn`,role:`status`,children:[(0,Q.jsx)(Ne,{}),(0,Q.jsx)(`span`,{children:t(`dash.webSearchCodexSync`)})]})]}),(0,Q.jsxs)(`div`,{className:`dash-delegation-controls`,children:[(0,Q.jsx)(`div`,{className:`dash-sidecar-select-row`,children:(0,Q.jsx)(dn,{value:O,options:[{value:``,label:t(`dash.webSearchOff`)},...u],onChange:e=>{if(e===``){p(zn(!1));return}let t={webSearch:ar(f,u,e)};D||(t.webSearch={...t.webSearch,enabled:!0}),p(t)},disabled:!c||l,label:t(`dash.sidecarModel`),align:`right`})}),c&&E===`anthropic`&&(0,Q.jsxs)(`div`,{className:`dash-sidecar-trailing-row`,children:[(0,Q.jsx)(dn,{value:c.webSearch.anthropicInstance??``,label:t(`sidecar.pool`),options:[{value:``,label:t(`sidecar.poolCurrent`)},{value:`anthropic`,label:t(`sidecar.poolA`)},{value:`anthropic2`,label:t(`sidecar.poolB`)}],disabled:l,align:`right`,onChange:e=>{p({webSearch:{anthropicInstance:e===`anthropic`||e===`anthropic2`?e:null}})}}),c.webSearch.anthropicPool?.mixed&&(0,Q.jsx)(`span`,{className:`muted setting-hint`,children:t(`sidecar.poolMixed`)})]}),(0,Q.jsxs)(`div`,{className:`dash-sidecar-trailing-row`,title:t(`dash.webSearchStreamHint`),children:[(0,Q.jsx)(`span`,{className:`muted setting-hint dash-sidecar-toggle-label`,children:t(`dash.webSearchStream`)}),(0,Q.jsx)(`button`,{type:`button`,className:`switch ${c?.webSearch?.streamRoutedModelOutput?`on`:``}`,onClick:()=>{p({webSearch:{streamRoutedModelOutput:!c?.webSearch?.streamRoutedModelOutput}})},disabled:!D||!c||l,"aria-label":t(`dash.webSearchStream`),"aria-pressed":c?.webSearch?.streamRoutedModelOutput===!0,children:(0,Q.jsx)(`span`,{className:`knob`})})]})]})]}),(0,Q.jsxs)(`div`,{className:`panel dash-delegation-summary dash-sidecar-row-card dash-vision-sidecar-card`,"aria-busy":!c||void 0,children:[(0,Q.jsxs)(`div`,{className:`dash-sidecar-copy`,children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:t(`dash.visionSidecar`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.visionSidecarHint`)})]}),(0,Q.jsxs)(`div`,{className:`dash-delegation-controls`,children:[(0,Q.jsxs)(`div`,{className:`dash-sidecar-select-row`,children:[(0,Q.jsx)(dn,{value:w,options:[{value:``,label:t(`dash.visionOff`)},...d],onChange:e=>{if(e===``){p(Rn(!1));return}let t=Qn(Xn(f,e),j),n={vision:{model:e,backend:or(f,d,e),reasoning:t}};C||(n.vision={...n.vision,enabled:!0}),p(n)},disabled:!c||l,label:t(`dash.sidecarModel`)}),(0,Q.jsx)(dn,{value:j,options:Zn(A,j).map(e=>({value:e,label:e})),onChange:e=>{p(Ln(e))},disabled:!C||!c||l,align:`right`,label:`${t(`dash.visionSidecar`)} — ${t(`dash.injectionEffortLabel`)}`})]}),c&&T===`anthropic`&&(0,Q.jsxs)(`div`,{className:`dash-sidecar-trailing-row`,children:[(0,Q.jsx)(dn,{value:c.vision.anthropicInstance??``,label:t(`sidecar.pool`),options:[{value:``,label:t(`sidecar.poolCurrent`)},{value:`anthropic`,label:t(`sidecar.poolA`)},{value:`anthropic2`,label:t(`sidecar.poolB`)}],disabled:l,align:`right`,onChange:e=>{p({vision:{anthropicInstance:e===`anthropic`||e===`anthropic2`?e:null}})}}),c.vision.anthropicPool?.mixed&&(0,Q.jsx)(`span`,{className:`muted setting-hint`,children:t(`sidecar.poolMixed`)})]}),(0,Q.jsx)(`div`,{className:`dash-sidecar-trailing-row`,children:(0,Q.jsxs)(`button`,{type:`button`,ref:ee,className:`dash-vision-advanced-trigger`,onClick:()=>U(e=>!e),disabled:!C||!c||l,"aria-expanded":H,"aria-haspopup":`dialog`,"aria-controls":`dash-vision-advanced-popover`,children:[(0,Q.jsx)(`span`,{children:t(`dash.visionAdvanced`)}),(0,Q.jsx)(Ye,{width:12,height:12,"aria-hidden":`true`,style:{transform:H?`rotate(90deg)`:`none`,transition:`transform .12s`}})]})})]}),(0,Zt.createPortal)((0,Q.jsx)(Ya,{t,open:H,triggerRef:ee,onClose:()=>U(!1),maxValue:W,maxInvalid:R,timeoutValue:te,timeoutInvalid:B,disabled:!C||!c||l,setMaxDraft:F,setMaxInvalid:z,setTimeoutDraft:L,setTimeoutInvalid:V,commitMaxDescriptions:G,commitTimeout:ne}),document.body)]})]}),(0,Q.jsxs)(`div`,{className:`panel`,"aria-busy":!h||void 0,children:[(0,Q.jsxs)(`div`,{className:`spread`,style:{alignItems:`center`},children:[(0,Q.jsxs)(`div`,{className:`dash-shadow-label`,style:{display:`flex`,alignItems:`center`,gap:8},children:[(0,Q.jsx)(`span`,{className:`font-semibold`,children:t(`dash.shadowCallIntercept`)}),(0,Q.jsx)(`button`,{ref:v,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:()=>b(e=>!e),"aria-label":t(`dash.shadowCallIntercept`),"aria-expanded":y,"aria-haspopup":`dialog`,"aria-controls":`shadow-call-help-dialog`,children:(0,Q.jsx)(De,{width:13,height:13,"aria-hidden":`true`})}),(0,Q.jsx)(`code`,{className:`muted text-caption`,children:`⚠ ${En(h?.sourceModels,S)}`})]}),(0,Q.jsxs)(`div`,{className:`setting-controls dash-shadow-controls`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`switch ${h?.enabled?`on`:``}`,onClick:()=>x({enabled:!h?.enabled}),disabled:!h||g,"aria-label":t(`dash.shadowCallIntercept`),"aria-pressed":h?.enabled??!1,children:(0,Q.jsx)(`span`,{className:`knob`})}),(0,Q.jsx)(dn,{value:h?.model??``,options:nr(f,h?.model,h?.sourceModels).map(e=>e.value===``?e:{...e,label:we(e.value,t)}),onChange:e=>{x({model:e})},disabled:!h||g||!h?.enabled,label:t(`dash.shadowCallModel`),align:`right`})]})]}),(0,Q.jsx)(Ga,{className:`dash-shadow-sources`,options:h?.sourceModelOptions,sourceModels:h?.sourceModels,disabled:!h?.enabled,saving:g,onChange:e=>void x({sourceModels:e})}),_&&(0,Q.jsxs)(`div`,{className:`notice notice-err`,role:`alert`,style:{marginTop:8},children:[(0,Q.jsx)(Ne,{}),(0,Q.jsx)(`span`,{children:_})]})]})]})}function Za(e){return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Ka,{apiBase:e.apiBase,d:e}),(0,Q.jsxs)(`div`,{className:`dash-overview-tools`,children:[(0,Q.jsx)(qa,{apiBase:e.apiBase,d:e}),(0,Q.jsx)(Ja,{d:e})]}),(0,Q.jsx)(Xa,{d:e}),(0,Q.jsx)(oa,{apiBase:e.apiBase,models:e.models,providers:e.providers}),(0,Q.jsx)(Ha,{apiBase:e.apiBase}),(0,Q.jsx)(za,{apiBase:e.apiBase,models:e.models}),(0,Q.jsx)(Fa,{apiBase:e.apiBase}),(0,Q.jsx)(la,{apiBase:e.apiBase})]})}function Qa(e){if(!e||typeof e!=`object`)return null;let t=e;return t.schema!==`ocx.fallback/1`||!t.global||!Array.isArray(t.devices)?null:{schema:t.schema,global:{model:t.global.model!==!1,provider:t.global.provider!==!1},providers:t.providers&&typeof t.providers==`object`?t.providers:{},routes:t.routes&&typeof t.routes==`object`?t.routes:{},devices:t.devices.filter(e=>!!e&&typeof e.id==`string`),last:t.last&&typeof t.last==`object`?t.last:null}}function $a({apiBase:e,section:t,readOnly:r=!1}){let i=n(),[a,o]=(0,Z.useState)(null),[s,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(!1),[d,f]=(0,Z.useState)(!1),p=(0,Z.useRef)(!1),m=(0,Z.useRef)(0),h=(0,Z.useCallback)(async()=>{if(p.current)return;let t=++m.current,n=M(15e3);try{let r=await fetch(e+`/api/fallback`,{signal:n.signal}),i=r.ok?Qa(await r.json()):null;if(!i)throw Error(`shape`);!p.current&&t===m.current&&(o(i),c(!1))}catch{!p.current&&t===m.current&&c(!0)}finally{n.clear()}},[e]);(0,Z.useEffect)(()=>{let e=window.setTimeout(()=>{h()},0),t=ba(()=>{h()},3e4);return()=>{window.clearTimeout(e),t()}},[h]);let g=(0,Z.useCallback)(async t=>{if(p.current||r)return;p.current=!0,m.current+=1,f(!0),u(!1);let n=M(15e3);try{let r=await fetch(e+`/api/fallback`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({writes:t}),signal:n.signal}),i=r.ok?Qa(await r.json()):null;if(!i)throw Error(`save`);m.current+=1,o(i)}catch{u(!0)}finally{n.clear(),p.current=!1,f(!1)}},[e,r]),_=e=>i(e===!1?`fallback.state.off`:e===!0?`fallback.state.on`:`fallback.state.inherit`),v=d||r;if(!a)return t===`devices`?null:(0,Q.jsxs)(`section`,{className:`panel fallback-panel`,"aria-busy":!s||void 0,children:[(0,Q.jsx)(`h3`,{children:i(t===`routing`?`fallback.title`:`fallback.devices.title`)}),(0,Q.jsx)(`p`,{className:`card-sub`,role:`status`,children:i(s?`fallback.loadFailed`:`common.loading`)}),s&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{h()},children:i(`common.retry`)})]});if(t===`devices`)return(0,Q.jsxs)(`section`,{className:`panel fallback-panel`,children:[(0,Q.jsx)(`h3`,{children:i(`fallback.devices.title`)}),(0,Q.jsx)(`p`,{className:`card-sub`,children:i(r?`fallback.devices.childNote`:`fallback.devices.desc`)}),a.devices.length===0?(0,Q.jsx)(`p`,{className:`card-sub`,children:i(`fallback.devices.empty`)}):(0,Q.jsxs)(`table`,{className:`fallback-devices`,"aria-label":i(`fallback.devices.title`),children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{className:`fallback-device-head`,children:[(0,Q.jsx)(`th`,{scope:`col`,children:i(`fallback.devices.device`)}),(0,Q.jsx)(`th`,{scope:`col`,children:i(`fallback.devices.local`)}),(0,Q.jsx)(`th`,{scope:`col`,children:i(`fallback.devices.chains`)})]})}),(0,Q.jsx)(`tbody`,{children:a.devices.map(e=>{let t=e.model!==!1&&e.provider!==!1,n=e.alias??e.id;return(0,Q.jsxs)(`tr`,{children:[(0,Q.jsxs)(`td`,{children:[(0,Q.jsx)(`strong`,{children:n}),e.alias&&(0,Q.jsx)(`code`,{className:`fallback-device-id`,children:e.id})]}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(eo,{label:i(`fallback.devices.localFor`,{name:n}),on:e.localFallback,disabled:v,onToggle:()=>{g([{scope:`device`,key:e.id,setting:`localFallback`,value:!e.localFallback||null}])}})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(eo,{label:i(`fallback.devices.chainsFor`,{name:n}),on:t,disabled:v,onToggle:()=>{let n=!t&&null;g([{scope:`device`,key:e.id,setting:`model`,value:n},{scope:`device`,key:e.id,setting:`provider`,value:n}])}})})]},e.id)})})]}),l&&(0,Q.jsx)($,{tone:`err`,children:i(`fallback.saveFailed`)})]});let y=[...Object.entries(a.providers).map(([e,t])=>({scope:`provider`,key:e,value:t})),...Object.entries(a.routes).map(([e,t])=>({scope:`route`,key:e,value:t}))],b=a.last;return(0,Q.jsxs)(`section`,{className:`panel fallback-panel`,children:[(0,Q.jsx)(`h3`,{children:i(`fallback.title`)}),(0,Q.jsx)(`p`,{className:`card-sub`,children:i(r?`fallback.devices.childNote`:`fallback.desc`)}),[`model`,`provider`].map(e=>(0,Q.jsxs)(`div`,{className:`fallback-switch-row`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:i(e===`model`?`fallback.model`:`fallback.provider`)}),(0,Q.jsx)(`div`,{className:`card-sub`,children:i(e===`model`?`fallback.modelHint`:`fallback.providerHint`)})]}),(0,Q.jsx)(eo,{label:i(e===`model`?`fallback.model`:`fallback.provider`),on:a.global[e],disabled:v,onToggle:()=>{g([{scope:`global`,setting:e,value:!a.global[e]&&null}])}})]},e)),(0,Q.jsx)(`p`,{className:`card-sub faint`,children:i(`fallback.rotationNote`)}),y.length>0&&(0,Q.jsxs)(`div`,{className:`fallback-overrides`,children:[(0,Q.jsx)(`strong`,{children:i(`fallback.overrides`)}),(0,Q.jsx)(`ul`,{children:y.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`span`,{children:i(e.scope===`provider`?`fallback.scope.provider`:`fallback.scope.route`,{name:e.key})}),(0,Q.jsxs)(`span`,{className:`card-sub`,children:[i(`fallback.model`),`: `,_(e.value.model),` · `,i(`fallback.provider`),`: `,_(e.value.provider)]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:v,onClick:()=>{g([`model`,`provider`].filter(t=>e.value[t]!==void 0).map(t=>({scope:e.scope,key:e.key,setting:t,value:null})))},children:i(`fallback.clear`)})]},e.scope+`:`+e.key))})]}),(0,Q.jsxs)(`div`,{className:`fallback-last`,"aria-live":`polite`,children:[(0,Q.jsx)(`strong`,{children:i(`fallback.last`)}),b?(0,Q.jsxs)(`p`,{className:`card-sub`,children:[(0,Q.jsx)(`time`,{dateTime:b.at,children:new Date(b.at).toLocaleString()}),` · `,(0,Q.jsx)(`code`,{children:b.route}),`: `,(0,Q.jsx)(`code`,{children:b.from}),` → `,(0,Q.jsx)(`code`,{children:b.to}),` (`,(0,Q.jsx)(`code`,{children:b.trigger}),`) · `,i(b.outcome===`refused`?`fallback.last.refused`:`fallback.last.taken`)]}):(0,Q.jsx)(`p`,{className:`card-sub`,children:i(`fallback.last.none`)})]}),l&&(0,Q.jsx)($,{tone:`err`,children:i(`fallback.saveFailed`)})]})}function eo({label:e,on:t,disabled:n,onToggle:r}){return(0,Q.jsx)(`button`,{type:`button`,className:`toggle `+(t?`on`:``),"aria-pressed":t,"aria-label":e,title:e,onClick:r,disabled:n,children:(0,Q.jsx)(`span`,{className:`toggle-knob`})})}function to({readOnly:e=!1,...t}){return(0,Q.jsxs)(`div`,{className:`dash-overview-stack`,children:[(0,Q.jsx)(Cr,{...t}),(0,Q.jsx)(Za,{...t}),(0,Q.jsx)($a,{apiBase:t.apiBase,section:`routing`,readOnly:e})]})}function no({t:e,providers:t}){return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`h-section`,children:[e(`dash.activeProviders`),` `,(0,Q.jsx)(`span`,{className:`count`,children:t.length})]}),t.length===0?(0,Q.jsx)(fn,{title:(0,Q.jsx)(O,{k:`dash.noProviders`,cmd:`ocx init`})}):(0,Q.jsx)(`div`,{className:`tbl-wrap`,children:(0,Q.jsxs)(`table`,{className:`tbl`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:e(`dash.col.name`)}),(0,Q.jsx)(`th`,{children:e(`dash.col.adapter`)}),(0,Q.jsx)(`th`,{children:e(`dash.col.baseUrl`)}),(0,Q.jsx)(`th`,{children:e(`dash.col.model`)})]})}),(0,Q.jsx)(`tbody`,{children:t.map(t=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`font-semibold`,children:Ce(t.name,e)}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`span`,{className:`chip`,children:t.adapter})}),(0,Q.jsx)(`td`,{className:`muted mono text-label`,children:t.baseUrl}),(0,Q.jsx)(`td`,{className:`muted`,children:t.defaultModel??`—`})]},t.name))})]})})]})}var ro=`__ocxCachedAt`;function io(e){try{let t=sessionStorage.getItem(e);if(!t)return null;let n=JSON.parse(t);return ao(n)?n.data:n}catch{return null}}function ao(e){return typeof e==`object`&&!!e&&typeof e[ro]==`number`&&`data`in e}function oo(e){try{let t=sessionStorage.getItem(e);if(!t)return null;let n=JSON.parse(t);return ao(n)?{data:n.data,cachedAt:n[ro]}:{data:n,cachedAt:null}}catch{return null}}function so(e,t){try{sessionStorage.setItem(e,JSON.stringify({[ro]:Date.now(),data:t}))}catch{}}function co(e,t){try{sessionStorage.setItem(e,JSON.stringify(t))}catch{}}function lo(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 uo(e,t,n,r){let{isEmpty:i,sessionCacheKey:a,...o}=r,s=(0,Z.useMemo)(()=>a?oo(a):null,[a]),c=Wt(e,t,(0,Z.useCallback)(async e=>{let t=await n(e);return a&&so(a,t),t},[n,a]),{...o,...a?{initialData:o.initialData??s?.data,initialDataCachedAt:o.initialDataCachedAt??s?.cachedAt??null}:{}});return{...c,state:lo(c,i,r.enabled!==!1)}}function fo(){return typeof navigator>`u`?``:navigator.userAgent}function po(e=fo()){return e.match(/OpenCodexDesktop\/(\S+)/)?.[1]??null}function mo(e=fo()){return po(e)!==null}var ho=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;function go(e=typeof location>`u`?``:location.search){let t=new URLSearchParams(e).get(`desktop_session`);return t&&ho.test(t)?t:null}function _o(e,t,n){let r=e+`/api/update/badge`;if(!mo(t))return r;let i=go(n);return r+`?surface=desktop`+(i?`&session=`+encodeURIComponent(i):``)}function vo(e=fo()){return/Windows/i.test(e)?`windows`:/Mac OS X|Macintosh/i.test(e)?`macos`:/Linux|X11/i.test(e)&&!/Android/i.test(e)?`linux`:`unknown`}function yo(e=fo()){if(!mo(e))return null;let t=vo(e);return t===`windows`?`http://tauri.localhost/update.html`:t===`macos`||t===`linux`?`tauri://localhost/update.html`:null}function bo(e=fo()){let t=yo(e);return t?(window.location.assign(t),!0):!1}function xo(e=fo()){if(!mo(e))return null;let t=vo(e);return t===`windows`?`http://tauri.localhost/cli.html`:t===`macos`||t===`linux`?`tauri://localhost/cli.html`:null}function So(e=fo()){let t=xo(e);return t?(window.location.assign(t),!0):!1}function Co(e,t=typeof location>`u`?``:location.origin){if(!/^https?:\/\//i.test(e))return!1;try{return new URL(e).origin!==t}catch{return!1}}function wo(e){return e.desktop!==void 0&&(e.desktop.owned||e.desktop.supervisor!==void 0)}function To(e,t){return t?`startup.unhealthy`:e.viable?`startup.viable`:e.running&&!e.loginEnabled&&(e.owned||e.supervisor!==void 0)?`startup.desktopLoginUnverified`:`startup.unhealthy`}function Eo(e){if(e.routingKind===`custom-local`)return`startup.riskDetailCustomLocal`;if(e.routingKind===`opencodex-local`){if(e.diagnosticStale&&e.desktop)return`startup.desktopReopenRecovery`;if(e.desktop?.owned)return`startup.desktopRecovery`;if(e.desktop?.supervisor)return`startup.desktopSupervisedRecovery`}return e.shimCoverage===`cli-only`?`startup.riskDetailWindowsShim`:`startup.riskDetail`}function Do(e,t){return!t.mutationInFlight&&e.request===t.request&&e.mutation===t.mutation}function Oo(e,t){return{request:++e.current,mutation:t.current}}var ko=2e3;function Ao(e){let t=e.status;return t!==`native`&&t!==`protected`&&t!==`at-risk`?null:t}function jo(e){return e?e.stale&&e.status!==`error`:!1}function Mo(e,t){return!t||t.diagnosticStale||e!==null&&e!==`error`?e:t.status}var No=3e4;function Po(e){return{multiAgentGuidanceEnabled:e.multiAgentGuidanceEnabled!==!1,syncCodexSubagentDefaults:e.syncCodexSubagentDefaults===!0,injectionModel:e.model??``,injectionEffort:e.effort??``}}function Fo(e,t){return t.aborted?!0:e instanceof Error&&e.name===`AbortError`}async function Io(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=Ao(r);if(!i)throw Error(`invalid startup health response`);return{status:i,stale:r.diagnosticStale===!0}}catch(e){if(Fo(e,t))throw e;return{status:`error`,stale:!1}}}async function Lo(e,t){try{return(await yn(await fetch(`${e}/api/diagnostics/project-config`,{signal:t})))?.grouped??[]}catch{return[]}}async function Ro(e,t){return jn(await fetch(`${e}/api/models`,{signal:t}))}async function zo(e,t){return br(await fetch(`${e}/api/usage?range=30d`,{signal:t}))}async function Bo(e,t,n){let{request:r,mutation:i}=Oo(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 jn(a),c;try{if(o.ok){let e=await o.json();Do({request:r,mutation:i},{request:n.shadowCallRequestEpochRef.current,mutation:n.shadowCallMutationEpochRef.current,mutationInFlight:n.shadowCallMutationInFlightRef.current})&&(c=e)}else Do({request:r,mutation:i},{request:n.shadowCallRequestEpochRef.current,mutation:n.shadowCallMutationEpochRef.current,mutationInFlight:n.shadowCallMutationInFlightRef.current})&&(c=null)}catch{Do({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 Vo(e,t,n){let{request:r,mutation:i}=Oo(n.settingsRequestEpochRef,n.settingsMutationEpochRef),a=await jn(await fetch(`${e}/api/settings`,{signal:t})),o,s;return Do({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 Ho(e,t){try{let n=await fetch(`${e}/api/v2`,{signal:t});if(!n.ok)return{maMode:`default`};let r=await n.json(),i=dr(r.multiAgentSurfaceAdvisory);return r.multiAgentMode===`v1`||r.multiAgentMode===`v2`?{maMode:r.multiAgentMode,advisory:i}:{maMode:`default`,advisory:i}}catch(e){if(Fo(e,t))throw e;return{maMode:`default`}}}async function Uo(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 jn(d),t=await jn(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(Fo(e,t))throw e;return n(`invalid`)}}finally{r.abort()}}async function Wo(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={...Po(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}}function Go(e){if(Ko(e)&&Array.isArray(e.clientIntegrations))return e.clientIntegrations.filter(e=>Ko(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 Ko(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function qo(e){if(!Array.isArray(e)||e.some(e=>typeof e!=`string`))throw Error(`invalid model list`);return[...new Set(e)]}function Jo(e){if(!Ko(e))throw Error(`invalid selected models response`);let t=e.selected;if(!Ko(t))throw Error(`invalid selected models response`);return Object.fromEntries(Object.entries(t).map(([e,t])=>[e,qo(t)]))}async function Yo(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 Jo(await r.json())}function Xo(e,t,n,r=!1){if(r)return!0;let i=e[t];return!i||i.length===0||i.includes(n)}function Zo(e,t,n,r,i){return Xo(e,t,n,r)&&!i}async function Qo(e,t,n,r,i,a=fetch,o){return a(`${e}/api/model-visibility`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({scope:t,provider:n,targets:r,enabled:i}),...o?{signal:o}:{}})}function $o(e,t){return e===t}function es(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 ts(e){return e.some(e=>e.pricingStatus!==void 0)}function ns(e,t){return t?e.filter(e=>e.pricingStatus===`free`):[...e]}function rs(e,t){return e&&ts(t)}function is(e){return[...e].some(e=>{let t=e.codePointAt(0);return t<=31||t>=127&&t<=159||t===8232||t===8233})}function as(e){let t=e.trim();return t?t.length>128?`models.displayNameTooLong`:t.includes(`/`)?`models.displayNameNoSlash`:is(t)?`models.displayNameNoControl`:null:`models.displayNameRequired`}var os=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function ss(e){return e===`shadow_call_target_invalid`?`models.shadowCallTargetInvalid`:e===`shadow_call_source_invalid`?`models.shadowCallSourceInvalid`:`models.shadowCallSaveFailed`}var cs=Array.from({length:18},(e,t)=>1e5+t*5e4),ls=new Set(cs),us=[272e3,372e3,922e3],ds=new Set(us),fs=`custom`,ps=[4,8,16,32,64,128,256,500,1e3],ms=new Set(ps);function hs(e,t){return t?Math.max(0,e-1):e}function gs(e,t){return t?e+1:e}var _s=`ocx-models-collapsed:v2`;function vs(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 ys(e){let t=new Set;for(let n of e)n.disabled&&t.add(n.namespaced);return t}function bs(e,t,n,r){let i=[];for(let a of e){let e=t.has(a.id)||t.has(a.namespaced);Zo(n,a.provider,a.id,a.native===!0,e)&&i.push({value:a.namespaced,label:r?we(a.namespaced,r):a.namespaced})}return i}function xs(e,t,n){let r=new Set(t.filter(e=>e.native===!0).map(e=>e.namespaced)),i=e.filter(e=>!r.has(e.value));return n&&!i.some(e=>e.value===n)&&i.push({value:n,label:e.find(e=>e.value===n)?.label??n}),i}function Ss(e=localStorage){try{let t=e.getItem(_s);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 Cs(e,t=localStorage){try{t.setItem(_s,JSON.stringify([...e]))}catch{}}function ws(e){let t=e.replace(/[_,\s]/g,``);if(!t)return null;let n=Number(t);return Number.isSafeInteger(n)&&n>0?n:void 0}var Ts=`ocx.dash.controls.v1:`,Es=`ocx.dash.overview.v1:`,Ds=`ocx.dash.usage30d.v1:`,Os=`ocx.dash.startup.v1:`,ks=`ocx.dash.maMode.v1:`;function As(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 js(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 Ms(e){return`${Ts}${e}`}function Ns(e,t=0){let{locale:n,t:i}=r(),[a,o]=(0,Z.useState)(On),[s,c]=(0,Z.useState)(``),[l,u]=(0,Z.useState)(new Set),d=(0,Z.useMemo)(()=>io(Ms(e)),[e]),f=(0,Z.useMemo)(()=>io(`${Es}${e}`),[e]),p=(0,Z.useMemo)(()=>io(`${Ds}${e}`),[e]),m=(0,Z.useMemo)(()=>{let t=io(`${Os}${e}`);return t===`error`?null:t},[e]),h=(0,Z.useMemo)(()=>io(`${ks}${e}`),[e]),[g,_]=(0,Z.useState)(()=>f?.health??null),[v,y]=(0,Z.useState)(()=>m),[b,x]=(0,Z.useState)(()=>f?.providers??[]),[S,C]=(0,Z.useState)([]),[w,T]=(0,Z.useReducer)(As,{settings:d?.settings??null,beforeSave:null}),{settings:E}=w,D=w.beforeSave!==null,[O,k]=(0,Z.useState)(()=>d?.sidecar??null),[A,j]=(0,Z.useState)(()=>d?.shadowCall??null),[M,N]=(0,Z.useState)(()=>p),[P,F]=(0,Z.useState)(!1),[I,L]=(0,Z.useState)(),[R,z]=(0,Z.useState)(!1),[B,V]=(0,Z.useState)(null),[H,U]=(0,Z.useState)(!1),[ee,W]=(0,Z.useState)(!1),[te,G]=(0,Z.useState)(()=>h??`default`),[ne,K]=(0,Z.useState)(!1),[re,q]=(0,Z.useState)(null),[J,Y]=(0,Z.useState)(null),[ie,X]=(0,Z.useState)(null),[ae,oe]=(0,Z.useState)(null),se=J?.apiBase===e?J.advisory:null,ce=ie===e,le=ae?.apiBase===e?ae.mode:null,[ue,de]=(0,Z.useState)(!1),[fe,pe]=(0,Z.useState)(!1),[me,he]=(0,Z.useState)(!1),[ge,_e]=(0,Z.useState)(``),[ve,ye]=(0,Z.useState)(``),[be,xe]=(0,Z.useState)([]),[Se,Ce]=(0,Z.useState)([]),[we,Te]=(0,Z.useState)(!1),[Ee,De]=(0,Z.useState)(!0),[Oe,ke]=(0,Z.useState)(!1),[Ae,je]=(0,Z.useState)(``),[Me,Ne]=(0,Z.useState)(``),[Pe,Fe]=(0,Z.useState)(!1),[Ie,Le]=(0,Z.useState)(null),[Re,ze]=(0,Z.useState)(null),[Be,Ve]=(0,Z.useState)([]),[He,Ue]=(0,Z.useState)(!1),[We,Ge]=(0,Z.useState)(`latest`),[Ke,qe]=(0,Z.useState)(!0),[Je,Ye]=(0,Z.useState)(!1),Xe=(0,Z.useRef)(0),Ze=(0,Z.useRef)(null),Qe=(0,Z.useRef)(0),$e=(0,Z.useRef)(0),et=(0,Z.useRef)(0),tt=(0,Z.useRef)(!1),nt=(0,Z.useRef)(0),rt=(0,Z.useRef)(0),it=(0,Z.useRef)(!1),[at,ot]=(0,Z.useState)(null),[st,ct]=(0,Z.useState)(null),[lt,ut]=(0,Z.useState)(null),[dt,ft]=(0,Z.useState)(!1),[pt,mt]=(0,Z.useState)(!1),ht=(0,Z.useRef)(null),gt=(0,Z.useRef)(null),_t=(0,Z.useRef)(null),vt=(0,Z.useRef)(null),yt=lr(fe,ht),bt=lr(He,gt),xt=lr(ue,_t),St=lr(me,vt);(0,Z.useEffect)(()=>{let e=()=>o(On());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]),(0,Z.useEffect)(()=>()=>{Qe.current+=1,Ze.current!==null&&(window.clearTimeout(Ze.current),Ze.current=null)},[]);let Ct=(0,Z.useRef)(m),wt=(0,Z.useRef)(0),Tt=(0,Z.useRef)({settingsRequestEpochRef:$e,settingsMutationEpochRef:et,settingsMutationInFlightRef:tt,shadowCallRequestEpochRef:nt,shadowCallMutationEpochRef:rt,shadowCallMutationInFlightRef:it}).current,Et=Wt(`dashboard-startup-health:${e}`,[e,t],t=>Io(e,t),{pollMs:3e4}),Dt=jo(Et.data),Ot=Et.refresh;(0,Z.useEffect)(()=>{if(!Dt)return;let e=window.setTimeout(()=>{Ot()},ko);return()=>window.clearTimeout(e)},[Dt,Ot]);let kt=Wt(`dashboard-overview:${e}`,[e,t],t=>Uo(e,t),{pollMs:5e3}),At=lo(kt,e=>e.health===null,!0),jt=g!==null||kt.data!==void 0,Mt=Wt(`dashboard-ma-mode:${e}`,[e,t],t=>Ho(e,t),{pollMs:5e3}),Nt=Wt(`dashboard-sidecars:${e}`,[e,t],async t=>{let n=wt.current;return{...await Bo(e,t,Tt),startupHealthGeneration:n}},{pollMs:5e3}),Pt=Wt(`dashboard-settings:${e}`,[e,t],async t=>{let n=wt.current;return{...await Vo(e,t,Tt),startupHealthGeneration:n}},{pollMs:5e3}),Ft=Wt(`dashboard-multi-agent:${e}`,[e,t],t=>Wo(e,t),{pollMs:5e3,enabled:jt}),It=Wt(xr(e),[e,t],t=>zo(e,t),{enabled:jt,pollMs:6e4,deadlineMs:6e4}),Lt=Wt(`dashboard-diagnostics:${e}`,[e,t],t=>Lo(e,t),{pollMs:No,enabled:jt}),Rt=Wt(`dashboard-models:${e}`,[e,pt,t],t=>Ro(e,t),{enabled:jt&&!pt});(0,Z.useEffect)(()=>{if(Et.data!==void 0){let t=Et.data;wt.current+=1,y(t.status),Ct.current=t.status,t.status!==`error`&&!t.stale&&co(`${Os}${e}`,t.status)}},[Et.data,e]),(0,Z.useEffect)(()=>{let t=kt.data;t&&(t.health&&(_(t.health),x(t.providers),co(`${Es}${e}`,{health:t.health,providers:t.providers})),mt(t.error))},[kt.data,e]),(0,Z.useEffect)(()=>{Mt.data!==void 0&&(G(Mt.data.maMode),Y({advisory:Mt.data.advisory??null,apiBase:e}),co(`${ks}${e}`,Mt.data.maMode))},[Mt.data,e]);let zt=Mt.data!==void 0||h!==null;(0,Z.useEffect)(()=>{let e=Ft.data;e&&(e.injection&&(De(e.injection.multiAgentGuidanceEnabled),ke(e.injection.syncCodexSubagentDefaults),_e(e.injection.injectionModel),ye(e.injection.injectionEffort),xe(e.injection.injectionEfforts),Ce(e.injection.injectionAvailable)),e.effortCaps&&(je(e.effortCaps.effortCap),Ne(e.effortCaps.subagentEffortCap)))},[Ft.data]),(0,Z.useEffect)(()=>{let t=Nt.data;if(!t)return;k(t.sidecar),t.shadowCall!==void 0&&j(t.shadowCall);let n=io(Ms(e))??{};co(Ms(e),{...n,sidecar:t.sidecar,...t.shadowCall===void 0?{}:{shadowCall:t.shadowCall}})},[Nt.data,e]),(0,Z.useEffect)(()=>{let t=Pt.data;if(t&&(t.settings!==void 0&&T({type:`polled`,settings:t.settings}),t.startupHealthSeed!==void 0&&t.startupHealthGeneration===wt.current)){let n=Mo(Ct.current,t.startupHealthSeed);y(n),Ct.current=n,n&&co(`${Os}${e}`,n)}},[Pt.data,e]),(0,Z.useEffect)(()=>{if(!E)return;let t=io(Ms(e))??{};co(Ms(e),{...t,settings:E})},[E,e]),(0,Z.useEffect)(()=>{It.data!==void 0&&(N(It.data),co(`${Ds}${e}`,It.data))},[It.data,e]),(0,Z.useEffect)(()=>{Lt.data&&Ve(Lt.data)},[Lt.data]),(0,Z.useEffect)(()=>{Rt.data&&C(Rt.data),U(Rt.loading)},[Rt.data,Rt.loading]),(0,Z.useEffect)(()=>()=>{$e.current+=1,nt.current+=1},[]);let Bt=Wt(lt?.id&&lt.restart?`update-job:${e}:${lt.id}`:`update-job:idle:${e}`,[e,lt?.id,lt?.restart,lt?.latestVersion],async t=>{if(!lt?.id||!lt.restart)return{reconnecting:!1};let n=lt.latestVersion;try{let r=await jn(await fetch(`${e}/api/update/status?jobId=${encodeURIComponent(lt.id)}`,{signal:t}));if(r.job){if(r.job.status===`failed`)return{job:r.job,reconnecting:!1};if(n)try{if((await jn(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:!!(lt?.id&&lt.restart),pauseWhenHidden:!1});(0,Z.useEffect)(()=>{let e=Bt.data;e&&(`job`in e&&e.job&&ut(e.job),ft(e.reconnecting),`reload`in e&&e.reload&&window.location.reload())},[Bt.data]);let Vt=(0,Z.useMemo)(()=>js(S),[S]),Ht=(0,Z.useMemo)(()=>{let e=s.trim().toLowerCase();if(!e)return Vt;let t=[];for(let[n,r]of Vt){let i=r.filter(t=>t.id.toLowerCase().includes(e)||n.toLowerCase().includes(e));i.length>0&&t.push([n,i])}return t},[Vt,s]),Ut=(0,Z.useMemo)(()=>{let e=O?.webSearch?.backend;return er(O?.webSearchModels,S,O?.webSearch?.model,e===`routed`?void 0:e)},[S,O?.webSearchModels,O?.webSearch]),Gt=(0,Z.useMemo)(()=>tr(O?.visionModels,S,O?.vision?.model,O?.vision?.backend),[O?.visionModels,S,O?.vision]),Kt=async t=>{if(!O||P)return;t=ir(O,t);let n=O,r={webSearch:In(O.webSearch,t.webSearch),vision:In(O.vision,t.vision),...O.visionModels?{visionModels:O.visionModels}:{},...O.webSearchModels?{webSearchModels:O.webSearchModels}:{}};F(!0),k(r);try{let n=await jn(await fetch(`${e}/api/sidecar-settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)}),`save failed`);L(e=>Vn(e,n.codexWebSearch)),k({webSearch:n.webSearch,vision:n.vision,...n.visionModels?{visionModels:n.visionModels}:{},...n.webSearchModels?{webSearchModels:n.webSearchModels}:{}});let r=io(Ms(e))??{};co(Ms(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 qt(t){if(!A||R)return;let n=A,r={...A,...t};z(!0),V(null),it.current=!0,j(r);try{let r=await fetch(`${e}/api/shadow-call-settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!r.ok){j(n);let e=await r.json().catch(()=>null);V(i(ss(e?.code)));return}rt.current+=1}catch{j(n),V(i(`models.networkError`))}finally{it.current=!1,z(!1)}}let Jt=async(t,n=!1)=>{K(!0),q(null);try{let r={multiAgentMode:t};n&&(r.multiAgentSurfaceAdvisoryAcknowledged=!0);let a=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r)});if(a.ok)G(t),n&&X(e),co(`${ks}${e}`,t);else{let e=i(`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{}q(e)}}catch(e){q(e instanceof Error?e.message:i(`dash.maNetworkError`))}finally{K(!1)}},Xt=async t=>{ne||te===t||(t===`v1`?await Jt(`v1`):oe({mode:t,apiBase:e}))},Zt=async()=>{X(e);try{let t=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({multiAgentSurfaceAdvisoryAcknowledged:!0})});t.ok||q(i(`dash.maSwitchFailed`,{status:String(t.status)}))}catch(e){q(e instanceof Error?e.message:i(`dash.maNetworkError`))}},Qt=async()=>{let e=le;oe(null),e?await Jt(e,!0):await Zt()},$t=async()=>{oe(null),te===`v1`?await Zt():await Jt(`v1`,!0)},en=()=>{le?oe(null):X(e)},tn=!le&&!ce&&se?.required===!0,nn=async t=>{if(!we){Te(!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 jn(await fetch(`${e}/api/injection-model`)),r=Po(n);De(r.multiAgentGuidanceEnabled),ke(r.syncCodexSubagentDefaults),_e(r.injectionModel),ye(r.injectionEffort),Array.isArray(n.efforts)&&xe(n.efforts),Array.isArray(n.available)&&Ce(n.available)}catch{}finally{Te(!1)}}},rn=async t=>{if(!E||D||ee)return;let n=!(E[t]??t===`codexAutoStart`);tt.current=!0,T({type:`save-started`,key:t,value:n});try{let r=await jn(await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({[t]:n})}),`save failed`);et.current+=1,T({type:`save-succeeded`,key:t,settings:r}),(t===`codexDesktopAuthless`||t===`codexClientCompaction`)&&await Q()}catch{T({type:`save-failed`}),mt(!0)}finally{tt.current=!1,T({type:`save-finished`})}},an=()=>rn(`codexAutoStart`),on=()=>rn(`codexDesktopAuthless`),sn=()=>rn(`codexClientCompaction`),cn=(0,Z.useCallback)(()=>{Le(null),ze(null)},[]),Q=async()=>{if(!ee){W(!0),Le(null),ze(null);try{let t=await jn(await fetch(`${e}/api/sync`,{method:`POST`}),`sync failed`);Le(t),t.ok&&t.status===`applied`&&(T({type:`applied`}),L(void 0)),t.projectConfigGrouped&&Ve(t.projectConfigGrouped)}catch(e){ze(e instanceof Error?e.message:String(e))}finally{W(!1)}}},ln=async(t,n=!1)=>{n&&(Xe.current=0),Ze.current!==null&&(window.clearTimeout(Ze.current),Ze.current=null);let r=++Qe.current;Ye(!0),ct(null),ot(null);try{let n=await jn(await fetch(`${e}/api/update/check?tag=${t}`),`update check failed`);if(r!==Qe.current)return;if(ot(n),n.reason===`latest_unavailable`&&Xe.current<2){let e=++Xe.current;Ze.current=window.setTimeout(()=>{r===Qe.current&&(Ze.current=null,ln(t))},800*e);return}n.reason!==`latest_unavailable`&&(Xe.current=0),Ye(!1)}catch(e){if(r!==Qe.current)return;ct(e instanceof Error?e.message:String(e)),Ye(!1)}},$=()=>{Qe.current+=1,Ze.current!==null&&(window.clearTimeout(Ze.current),Ze.current=null),Ye(!1),Ue(!1)},un=()=>{if(bo())return;let e=Nn(g?.version);Ge(e),qe(!0),Ue(!0),ln(e,!0)},dn=e=>{Ge(e),ln(e,!0)},fn=(0,Z.useRef)(un);return(0,Z.useEffect)(()=>{fn.current=un}),(0,Z.useEffect)(()=>{let e=()=>{kn()&&(Yt(`dashboard`),fn.current())},t=kn()?window.setTimeout(e,0):null;return window.addEventListener(`hashchange`,e),()=>{t!==null&&window.clearTimeout(t),window.removeEventListener(`hashchange`,e)}},[]),{apiBase:e,locale:n,t:i,selectedSection:a,setSelectedSection:o,modelQuery:s,setModelQuery:c,expandedProviders:l,setExpandedProviders:u,health:g,startupHealth:v,providers:b,models:S,settings:E,sidecar:O,shadowCall:A,usage30d:M,usageLoading:It.loading&&!M,healthLoading:kt.loading&&!g,sidecarSaving:P,shadowCallSaving:R,shadowCallError:B,modelsLoading:H,settingsSaving:D,syncing:ee,maMode:te,maModeResolved:zt,maBusy:ne,setMaHelpOpen:de,maHelpOpen:ue,maError:re,maAdvisory:se,maAdvisoryOpen:tn,pendingMaMode:le,keepMaMode:Qt,chooseMaV1:$t,dismissMaSurfaceDialog:en,effortCapHelpOpen:fe,setEffortCapHelpOpen:pe,shadowCallHelpOpen:me,setShadowCallHelpOpen:he,injectionModel:ge,injectionEffort:ve,injectionEfforts:be,injectionAvailable:Se,injectionSaving:we,multiAgentGuidanceEnabled:Ee,syncCodexSubagentDefaults:Oe,saveInjection:nn,effortCap:Ae,subagentEffortCap:Me,effortCapSaving:Pe,setEffortCap:je,setSubagentEffortCap:Ne,setEffortCapSaving:Fe,syncResult:Ie,syncError:Re,projectConfigWarnings:Be,updateOpen:He,updateChannel:We,setUpdateRestart:qe,updateRestart:Ke,updateLoading:Je,updateCheck:at,updateError:st,updateJob:lt,reconnecting:dt,error:pt||At.showError,connectionFailure:kt.data?.failure??(At.showError?`unavailable`:void 0),refreshDashboard:kt.refresh,effortCapHelpTriggerRef:ht,updateTriggerRef:gt,maHelpTriggerRef:_t,shadowCallHelpTriggerRef:vt,effortCapHelpDialogRef:yt,updateDialogRef:bt,maHelpDialogRef:xt,shadowCallHelpDialogRef:St,filteredGroups:Ht,sidecarModels:Ut,visionModels:Gt,sidecarCodexApply:I,saveSidecar:Kt,saveShadowCall:qt,switchMaMode:Xt,toggleCodexAutoStart:an,toggleCodexDesktopAuthless:on,toggleCodexClientCompaction:sn,runSync:Q,clearSyncFeedback:cn,fetchUpdateCheck:ln,closeUpdateDialog:$,openUpdateDialog:un,changeUpdateChannel:dn,runUpdate:async()=>{if(at?.canUpdate){ct(null);try{let t=await jn(await fetch(`${e}/api/update/run`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({tag:We,restart:Ke})}),`update failed to start`);if(!t.job)throw Error(`update failed to start`);ut(t.job),ft(!1),$()}catch(e){ct(e instanceof Error?e.message:String(e))}}}}}function Ps(e){Xt(An(e))}function Fs({apiBase:e,readOnly:t=!1,connected:n=!1,authenticationPending:r=!1,refreshEpoch:i=0}){let a=Ns(e,i),{t:o,error:s,selectedSection:c,providers:l,models:u,modelsLoading:d,modelQuery:f,setModelQuery:p,filteredGroups:m,expandedProviders:h,setExpandedProviders:g}=a;if(r)return null;let _=a.connectionFailure===`auth`||a.connectionFailure===`denied`;if(s&&(_||!a.health))return(0,Q.jsxs)(fn,{style:{marginTop:40},icon:(0,Q.jsx)(Ne,{}),title:(0,Q.jsx)(`span`,{style:{color:`var(--red)`},children:o(a.connectionFailure===`denied`?`dash.permissionDenied`:a.connectionFailure===`auth`?`dash.authRequired`:`dash.dataUnavailable`)}),children:[!n&&a.connectionFailure===`unavailable`&&(0,Q.jsx)(O,{k:`dash.runStart`,cmd:`ocx start`}),(0,Q.jsx)(`button`,{className:`btn btn-ghost`,type:`button`,onClick:()=>a.refreshDashboard(),children:o(`common.retry`)})]});let v=(0,Q.jsx)(to,{...a,readOnly:t}),y=(0,Q.jsx)(no,{t:o,providers:l}),b=(0,Q.jsx)(hr,{t:o,models:u,modelsLoading:d,modelQuery:f,setModelQuery:p,filteredGroups:m,expandedProviders:h,setExpandedProviders:g}),x=(0,Q.jsx)(mr,{...a}),S=[{id:`overview`,label:o(`dash.workspace.overview`),body:v},{id:`providers`,label:o(`dash.activeProviders`),body:y},{id:`models`,label:o(`dash.availableModels`),body:b}],C=S.find(e=>e.id===c)??S[0],w=Ps,T=e=>{let t=S.findIndex(e=>e.id===c),n=-1;if(e.key===`ArrowRight`?n=(t+1)%S.length:e.key===`ArrowLeft`?n=(t-1+S.length)%S.length:e.key===`Home`?n=0:e.key===`End`&&(n=S.length-1),n<0)return;e.preventDefault();let r=S[n];w(r.id),document.getElementById(`dashboard-tab-${r.id}`)?.focus()};return(0,Q.jsxs)(`div`,{className:`dashboard-workspace-shell`,children:[s&&(0,Q.jsxs)($,{tone:`warn`,children:[o(`dash.staleData`),` `,(0,Q.jsx)(`button`,{className:`btn btn-ghost`,type:`button`,onClick:()=>a.refreshDashboard(),children:o(`common.retry`)})]}),(0,Q.jsx)(`div`,{className:`page-head`,children:(0,Q.jsx)(`h2`,{children:o(`nav.dashboard`)})}),(0,Q.jsx)(`p`,{className:`page-sub`,children:o(`dash.subtitle`)}),(0,Q.jsx)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":o(`dash.workspace.sections`),children:S.map(e=>(0,Q.jsx)(`button`,{type:`button`,role:`tab`,id:`dashboard-tab-${e.id}`,"aria-selected":c===e.id,"aria-controls":`dashboard-panel-${e.id}`,tabIndex:c===e.id?0:-1,className:`page-tab${c===e.id?` page-tab--active`:``}`,onClick:()=>w(e.id),onKeyDown:T,children:e.label},e.id))}),(0,Q.jsx)(`section`,{className:`dashboard-workspace-main`,role:`tabpanel`,id:`dashboard-panel-${C.id}`,"aria-labelledby":`dashboard-tab-${C.id}`,tabIndex:0,children:C.body}),x]})}function Is(e){let t=Object.create(null);for(let n of e)t[n.provider]={requests:n.requests,totalTokens:n.totalTokens};return t}function Ls(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 Rs(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 zs={justNow:`Just now`,notChecked:`Not checked`,minutesAgo:e=>`${e}m ago`,hoursAgo:e=>`${e}h ago`,daysAgo:e=>`${e}d ago`};function Bs(e,t,n){let r=typeof t==`object`&&t?t:zs,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 Vs(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 Hs(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 Us(e){return e===`Active account needs re-authentication`?`reauth`:e===`Missing credentials`?`missing`:`custom`}function Ws(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 Gs(e,t=`en`){return Ws(e,t)}function Ks(e,t=`en`){return e==null||!Number.isFinite(e)||e<0?`—`:`~$${new Intl.NumberFormat(t,{minimumFractionDigits:4,maximumFractionDigits:4}).format(e)}`}function qs(e){return e===`5h`?0:e===`First-party models`?2:e===`API usage`?3:e===`Total subscription credits`?4.5:5}var Js=`Total subscription credits`;function Ys(e){return e.trim().toLowerCase()===Js.toLowerCase()?Js:e}function Xs(e,t){if(e===void 0||!t)return!1;let n=Ys(e);for(let e of t)if(Ys(e)===n)return!0;return!1}function Zs(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 Qs(e,t,n){let r=z(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=Ys(e.label),r=Zs(t,n);i.push({rank:qs(t),row:{id:JSON.stringify([e.modelId??null,e.label,e.resetAt??null]),customLabel:t,label:r,limitLabel:r,percent:e.percent,resetAt:e.resetAt}})}if(r.creditsUsd&&typeof r.creditsUsd.percent==`number`&&!r.customWindows?.some(e=>e.modelId===void 0&&Ys(e.label)===Js)){let e=Zs(Js,n);i.push({rank:qs(Js),row:{customLabel:Js,label:e,limitLabel:e,percent:r.creditsUsd.percent,resetAt:r.creditsUsd.expiresAt}})}let a=new Map;return i.sort((e,t)=>e.rank-t.rank).map(({row:e})=>{let t=e.id??e.windowKey??e.customLabel,n=a.get(t)??0;return a.set(t,n+1),{...e,id:JSON.stringify([t,n])}})}function $s(e){if(!e)return-1;let t=[e.fiveHourPercent,e.weeklyPercent,e.monthlyPercent].filter(e=>typeof e==`number`);for(let n of e.customWindows??[])n.modelId===void 0&&typeof n.percent==`number`&&t.push(n.percent);return!e.customWindows?.some(e=>e.modelId===void 0&&Ys(e.label)===Js)&&typeof e.creditsUsd?.percent==`number`&&t.push(e.creditsUsd.percent),t.length?Math.max(...t):-1}function ec(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`;case`vi`:return`vi-VN`;case`pt`:return`pt-BR`;default:return e}}function tc(e){return e>=99.5}function nc(e,t){return t>0&&e>=t}function rc(e,t){return nc(e,t)||tc(e)?`bar-warn`:`bar-green`}function ic(e){let t=Math.max(0,Math.min(100,e));return t<=0?0:Math.max(4,Math.round(t))}function ac(e){return{"--bar-scale":String(ic(e)/100)}}function oc(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 sc({quota:e,plan:t,threshold:n,t:i,className:a,layout:o=`compact`,pending:s=!1,incompleteWindowKeys:c,incompleteCustomWindowLabels:l,observedAt:u,afterWeekly:d}){let{locale:f}=r(),p=Qs(e,t,i),m=u===void 0?null:oc(u,i),h=m===null?null:(0,Q.jsx)(`p`,{className:`quota-observed muted`,title:i(`quota.observedHint`),children:i(`quota.observedAgo`).replace(`{age}`,m)});return p.length===0?s?o===`stacked`?(0,Q.jsxs)(`div`,{className:`quota-stacked quota-stacked--pending${a?` ${a}`:``}`,"aria-busy":`true`,role:`status`,children:[Array.from({length:2},(e,t)=>(0,Q.jsxs)(`div`,{className:`quota-stacked-row quota-stacked-row--skeleton`,"aria-hidden":`true`,children:[(0,Q.jsxs)(`div`,{className:`quota-stacked-head`,children:[(0,Q.jsx)(`span`,{className:`quota-skel quota-skel--label`,style:{width:72}}),(0,Q.jsx)(`span`,{className:`quota-skel quota-skel--time`,style:{width:64}})]}),(0,Q.jsxs)(`div`,{className:`quota-stacked-bar-row`,children:[(0,Q.jsx)(`span`,{className:`quota-skel quota-skel--bar`,style:{height:6,flex:1}}),(0,Q.jsx)(`span`,{className:`quota-skel quota-skel--val`,style:{width:36}})]})]},t)),(0,Q.jsx)(`span`,{className:`sr-only`,children:i(`common.loading`)})]}):(0,Q.jsxs)(`div`,{className:`codex-account-quota-slot quota-compact quota-compact--pending${a?` ${a}`:``}`,"aria-busy":`true`,role:`status`,children:[(0,Q.jsxs)(`div`,{className:`quota-row quota-row--skeleton`,"aria-hidden":`true`,children:[(0,Q.jsx)(`span`,{className:`quota-skel quota-skel--label`}),(0,Q.jsx)(`span`,{className:`quota-skel quota-skel--reset`}),(0,Q.jsx)(`span`,{className:`quota-skel quota-skel--day`}),(0,Q.jsx)(`span`,{className:`quota-skel quota-skel--time`}),(0,Q.jsx)(`span`,{className:`quota-skel quota-skel--bar`}),(0,Q.jsx)(`span`,{className:`quota-skel quota-skel--val`})]}),(0,Q.jsx)(`span`,{className:`sr-only`,children:i(`common.loading`)})]}):o===`compact`&&d?(0,Q.jsx)(`div`,{className:`codex-account-quota-slot quota-compact${a?` ${a}`:``}`,children:d}):null:o===`stacked`?(0,Q.jsxs)(`div`,{className:`quota-stacked${a?` ${a}`:``}`,children:[h,p.map(e=>(0,Q.jsx)(lc,{row:e,threshold:n,t:i,locale:f,incomplete:e.windowKey?c?.has(e.windowKey)===!0:Xs(e.customLabel,l)},e.id))]}):(0,Q.jsxs)(`div`,{className:`codex-account-quota-slot quota-compact${a?` ${a}`:``}`,children:[h,p.map(e=>(0,Q.jsxs)(Z.Fragment,{children:[(0,Q.jsx)(cc,{credits:e.customLabel===Js,label:e.label,percent:e.percent,resetAt:e.resetAt,threshold:n,t:i,locale:f}),e.windowKey===`weekly`&&d]},e.id)),!p.some(e=>e.windowKey===`weekly`)&&d]})}function cc({credits:e,label:t,percent:n,resetAt:r,threshold:i,t:a,locale:o}){let s=tc(n),c=nc(n,i),l=rc(n,i),u=dc(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,Q.jsxs)(`div`,{className:`quota-row${e?` quota-row--credits`:``}${c?` quota-row--warn`:``}${s?` quota-row--exhausted`:``}`,children:[(0,Q.jsx)(`span`,{className:`quota-label`,title:d,children:t}),(0,Q.jsx)(`span`,{className:`quota-reset-label`,children:f?a(`codexAuth.resets`):``}),(0,Q.jsx)(`span`,{className:`quota-reset-day`,children:u.day}),(0,Q.jsx)(`span`,{className:`quota-reset-time`,children:u.time}),(0,Q.jsx)(`div`,{className:`bar`,title:d,children:(0,Q.jsx)(`div`,{className:`bar-fill ${l}`,style:ac(n)})}),(0,Q.jsxs)(`span`,{className:`quota-val${c?` quota-val--warn`:``}`,title:s?a(`quota.limitReached`):d,"aria-label":d,children:[c&&(0,Q.jsx)(Ne,{width:12,height:12,"aria-hidden":`true`}),Math.round(n),`%`,s?` · ${a(`quota.limitReached`)}`:``]})]})}function lc({row:e,threshold:t,t:n,locale:r,incomplete:i}){let a=tc(e.percent),o=nc(e.percent,t),s=rc(e.percent,t),c=fc(e.resetAt,n,r);return(0,Q.jsxs)(`div`,{className:`quota-stacked-row${o?` quota-stacked-row--warn`:``}${a?` quota-stacked-row--exhausted`:``}`,children:[(0,Q.jsxs)(`div`,{className:`quota-stacked-head`,children:[(0,Q.jsxs)(`span`,{className:`quota-stacked-limit-group`,children:[(0,Q.jsx)(`span`,{className:`quota-stacked-limit`,children:e.limitLabel}),i&&(0,Q.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,Q.jsx)(`span`,{className:`quota-stacked-reset muted`,children:c})]}),(0,Q.jsxs)(`div`,{className:`quota-stacked-bar-row`,children:[(0,Q.jsx)(`div`,{className:`bar quota-stacked-bar`,children:(0,Q.jsx)(`div`,{className:`bar-fill ${s}`,style:ac(e.percent)})}),(0,Q.jsx)(`span`,{className:`quota-stacked-used${o?` quota-stacked-used--warn`:``}`,children:n(`quota.usedPercent`,{pct:Math.round(e.percent)})})]}),a&&(0,Q.jsxs)(`div`,{className:`quota-stacked-limit-reached`,role:`status`,children:[(0,Q.jsx)(Ne,{width:12,height:12,"aria-hidden":`true`}),n(`quota.limitReached`)]})]})}function uc(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 dc(e,t,n){let r=uc(e);if(!r)return{day:``,time:``};let{date:i}=r,a=new Date,o=ec(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 fc(e,t,n=`en`,r=Date.now()){let i=uc(e);if(!i)return``;let{date:a,ms:o}=i,s=ec(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 pc({credits:e,updatedAt:t}){let{t:n,locale:i}=r(),a=e=>new Intl.NumberFormat(i,{maximumFractionDigits:2}).format(e),o=e=>n(`quota.workbuddy.amount`,{amount:a(e)}),s=e.total>0?Math.min(100,e.used/e.total*100):0;return(0,Q.jsxs)(`div`,{"data-workbuddy-credits":!0,children:[(0,Q.jsxs)(`div`,{className:`pws-capacity-recovery`,children:[(0,Q.jsx)(`span`,{children:n(`quota.creditsBalance`)}),(0,Q.jsx)(`strong`,{children:o(e.remaining)})]}),(0,Q.jsx)(sc,{quota:{updatedAt:t,customWindows:[{label:n(`quota.totalSubscriptionCredits`),percent:s}]},threshold:80,t:n,layout:`stacked`}),(0,Q.jsxs)(`div`,{className:`pws-capacity-details`,children:[(0,Q.jsx)(`div`,{className:`pws-capacity-recovery`,children:(0,Q.jsx)(`span`,{children:n(`quota.workbuddy.usage`,{used:a(e.used),total:a(e.total)})})}),e.groups.filter(e=>e.total>0||e.remaining>0).map(e=>(0,Q.jsxs)(`div`,{className:`pws-capacity-recovery`,children:[(0,Q.jsx)(`span`,{children:n(`quota.workbuddy.${e.kind}`)}),(0,Q.jsxs)(`strong`,{children:[o(e.remaining),` / `,a(e.total)]})]},e.kind)),e.frozen>0&&(0,Q.jsxs)(`div`,{className:`pws-capacity-recovery`,children:[(0,Q.jsx)(`span`,{children:n(`quota.workbuddy.frozen`)}),(0,Q.jsx)(`strong`,{children:o(e.frozen)})]}),e.expiring&&(0,Q.jsx)(`p`,{className:`muted`,children:n(`quota.workbuddy.expiring`,{amount:a(e.expiring.amount),date:new Intl.DateTimeFormat(i,{dateStyle:`medium`,timeStyle:`short`}).format(e.expiring.at)})})]})]})}function mc(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`;case`vi`:return`vi-VN`;case`pt`:return`pt-BR`;default:return e}}function hc(e){let t=new Date(e>1e10?e:e*1e3);return Number.isFinite(t.getTime())?t:null}function gc({report:e,pending:t}){let i=n(),{locale:a}=r(),o=He(e),s=ce(e),c=ue(e),l=s?.creditsUsd,u=o?.presentation===`aggregate`,d=new Set,f=new Set;if(u&&o){o.fiveHour?.incomplete&&d.add(`fiveHour`),o.weekly?.incomplete&&d.add(`weekly`),o.monthly?.incomplete&&d.add(`monthly`);for(let e of o.customWindows??[])e.incomplete&&f.add(e.label)}let p=u&&o?[...o.fiveHour?[{key:0,label:i(`codexAuth.fiveHour`),window:o.fiveHour}]:[],...o.weekly?[{key:1,label:i(`codexAuth.weekly`),window:o.weekly}]:[],...o.monthly?[{key:2,label:i(`codexAuth.monthly`),window:o.monthly}]:[],...(o.customWindows??[]).map((e,t)=>({key:t+3,label:e.label,window:e}))]:[],m=e=>new Intl.NumberFormat(a,{maximumFractionDigits:1}).format(e),h=e=>{let t=hc(e);return t===null?null:new Intl.DateTimeFormat(a,{dateStyle:`medium`,timeStyle:`short`}).format(t)},g=mc(a),_=e=>new Intl.NumberFormat(g,{style:`currency`,currency:`USD`}).format(e),v=l?.expiresAt===void 0?null:(e=>{let t=hc(e);return t===null?null:new Intl.DateTimeFormat(g,{dateStyle:`medium`}).format(t)})(l.expiresAt);return(0,Q.jsxs)(Q.Fragment,{children:[s?.workbuddyCredits&&(0,Q.jsx)(pc,{credits:s.workbuddyCredits,updatedAt:s.updatedAt}),u&&(0,Q.jsx)(`div`,{className:`pws-capacity-label`,children:i(`pws.capacity.estimate`)}),(s||t)&&(0,Q.jsx)(sc,{quota:s,threshold:80,t:i,layout:`stacked`,pending:t,...c===void 0?{}:{observedAt:c},incompleteWindowKeys:u?d:void 0,incompleteCustomWindowLabels:u?f:void 0}),(l||o)&&(0,Q.jsxs)(`div`,{className:`pws-capacity-details`,children:[l&&(0,Q.jsxs)(`div`,{className:`pws-capacity-recovery`,children:[(0,Q.jsx)(`span`,{children:i(`quota.creditsBalance`)}),(0,Q.jsx)(`strong`,{children:_(l.remaining)})]}),v!==null&&(0,Q.jsx)(`div`,{className:`pws-capacity-recovery`,children:(0,Q.jsx)(`span`,{children:i(`quota.creditsPeriodEnds`,{date:v})})}),p.flatMap(({key:e,label:t,window:n})=>{let r=n.nextRecoveryAt===void 0?null:h(n.nextRecoveryAt);return r!==null&&n.nextRecoveryPercent!==void 0?[(0,Q.jsxs)(`div`,{className:`pws-capacity-recovery`,children:[(0,Q.jsxs)(`span`,{children:[i(`pws.capacity.nextRecovery`),` · `,t,` · `,r]}),(0,Q.jsx)(`strong`,{children:i(`pws.capacity.recoveryShare`,{percent:m(n.nextRecoveryPercent)})})]},e)]:[]}),u&&o&&o.currentAccount?.quota&&(0,Q.jsxs)(`div`,{className:`pws-capacity-current`,children:[(0,Q.jsxs)(`span`,{className:`pws-capacity-label`,children:[i(`pws.capacity.currentAccount`),o.currentAccount.plan?` · ${o.currentAccount.plan}`:``]}),(0,Q.jsx)(sc,{quota:o.currentAccount.quota,threshold:80,t:i,layout:`stacked`})]}),o&&o.incomplete&&o.excludedAccounts>0&&(0,Q.jsx)(`div`,{className:`pws-capacity-incomplete`,children:i(`pws.capacity.incomplete`,{excluded:o.excludedAccounts})}),o&&o.unknownPlanAccounts>0&&(0,Q.jsx)(`div`,{className:`pws-capacity-incomplete`,children:i(`pws.capacity.uncalibratedPlan`,{count:o.unknownPlanAccounts})}),o&&o.partialWindowAccounts>0&&(0,Q.jsx)(`div`,{className:`pws-capacity-incomplete`,children:i(`pws.capacity.partial`,{count:o.partialWindowAccounts})})]})]})}function _c({sections:e,quotaReports:t,usageTotals:i,usageLoading:a=!1,quotasLoading:o=!1,onSelectProvider:s,onEditConfig:c,onRefreshAllQuotas:l}){let u=n(),{locale:d}=r(),f=Vs(u),[p,m]=(0,Z.useState)(!1),[h,g]=(0,Z.useState)(null),_=async()=>{if(l&&!p){m(!0),g(null);try{let e=await l();g({ok:e,text:u(e?`pws.quotaRefreshDone`:`codexAuth.quotaRefreshFailed`)})}catch{g({ok:!1,text:u(`codexAuth.quotaRefreshFailed`)})}finally{m(!1)}}},v=(0,Z.useMemo)(()=>[...e.ready,...e.needsSetup,...e.disabled],[e]),y=(0,Z.useMemo)(()=>new Set(v.map(e=>e.name)),[v]),b=(0,Z.useMemo)(()=>Hs(e,{}),[e]),x=b.length,S=(0,Z.useMemo)(()=>e.ready.filter(e=>e.activeNeedsReauth).length,[e]),C=e.ready.length-S,w=e.needsSetup.length+S,T=(0,Z.useMemo)(()=>{let e=[];for(let n of v){let r=t[n.name],i=r?ce(r):null,a=r?He(r):null;r&&(i||a?.presentation===`coverage-only`)&&e.push({item:n,report:r,urgency:i?$s(i):-1})}return e.sort((e,t)=>t.urgency-e.urgency||e.item.name.localeCompare(t.item.name))},[v,t]),E=(0,Z.useMemo)(()=>{let e={};for(let[t,n]of Object.entries(i))y.has(t)&&(e[t]=n);return Rs(e).slice(0,4)},[i,y]),D=e=>{let t=Us(e);return t===`reauth`?u(`pws.attention.reauth`):t===`missing`?u(`pws.attention.missingCredentials`):e};return(0,Q.jsxs)(`div`,{className:`pws-dashboard`,children:[(0,Q.jsxs)(`div`,{className:`pws-dashboard-header`,children:[(0,Q.jsx)(`div`,{className:`pws-dashboard-header-text`,children:(0,Q.jsx)(`h2`,{className:`pws-dashboard-title`,children:u(`pws.dashboard.title`)})}),(0,Q.jsxs)(`div`,{className:`pws-dashboard-header-actions`,children:[h&&(0,Q.jsx)(`span`,{role:`status`,className:h.ok?`pws-status-ok`:`pws-status-warn`,children:h.text}),l&&(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:p,onClick:()=>{_()},children:[(0,Q.jsx)(ae,{width:14,height:14,"aria-hidden":`true`}),` `,u(p?`codexAuth.refreshingQuota`:`pws.refreshAllQuotas`)]}),c&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:c,children:u(`prov.editJson`)})]})]}),(0,Q.jsxs)(`div`,{className:`pws-dashboard-summary`,children:[(0,Q.jsx)(vc,{count:C,label:u(`pws.status.ready`),tone:`ok`}),(0,Q.jsx)(vc,{count:w,label:u(S>0?`pws.status.needsAttention`:`pws.status.needsSetup`),tone:`warn`}),(0,Q.jsx)(vc,{count:e.disabled.length,label:u(`prov.disabledBadge`),tone:`muted`})]}),x>0&&(0,Q.jsxs)(`section`,{className:`pws-dashboard-section pws-dashboard-attention`,"aria-label":u(`pws.attentionTitle`),children:[(0,Q.jsxs)(`h3`,{className:`pws-dashboard-section-title`,children:[(0,Q.jsx)(Ne,{style:{width:14,height:14},"aria-hidden":`true`}),u(`pws.attentionTitle`)]}),(0,Q.jsx)(`div`,{className:`pws-dashboard-rows`,children:b.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`pws-dashboard-row pws-dashboard-row--attention`,onClick:()=>s(e.name),children:[(0,Q.jsx)(_e,{name:e.name,adapter:``,baseUrl:``,cls:`pws-dashboard-row-icon`}),(0,Q.jsxs)(`div`,{className:`pws-dashboard-row-info`,children:[(0,Q.jsx)(`span`,{className:`pws-dashboard-row-name`,children:Ce(e.name,u)}),(0,Q.jsx)(`span`,{className:`pws-dashboard-row-meta muted`,children:D(e.reason)})]}),(0,Q.jsx)(Ye,{className:`pws-dashboard-row-chevron`,"aria-hidden":`true`})]},`${e.name}:${e.reason}`))})]}),(0,Q.jsxs)(`div`,{className:`pws-dashboard-columns`,children:[(0,Q.jsxs)(`section`,{className:`pws-dashboard-section pws-dashboard-section--rate-limits`,"aria-label":u(`pws.dashboard.rateLimits`),"aria-busy":o||void 0,children:[(0,Q.jsx)(`h3`,{className:`pws-dashboard-section-title`,children:u(`pws.dashboard.rateLimits`)}),T.length>0?(0,Q.jsx)(`div`,{className:`pws-dashboard-rows`,children:T.map(({item:e,report:t})=>(0,Q.jsxs)(`button`,{type:`button`,className:`pws-dashboard-row`,onClick:()=>s(e.name),children:[(0,Q.jsx)(_e,{name:e.name,adapter:e.adapter,baseUrl:e.baseUrl,cls:`pws-dashboard-row-icon`}),(0,Q.jsxs)(`div`,{className:`pws-dashboard-row-info`,children:[(0,Q.jsx)(`span`,{className:`pws-dashboard-row-name`,children:Ce(e.name,u)}),(0,Q.jsx)(`span`,{className:`pws-dashboard-row-meta muted`,children:u(`pws.dashboard.checkedAgo`,{time:Bs(t.updatedAt,f)})})]}),(0,Q.jsx)(Ye,{className:`pws-dashboard-row-chevron`,"aria-hidden":`true`}),(0,Q.jsx)(`div`,{className:`pws-dashboard-row-bars`,children:(0,Q.jsx)(gc,{report:t,pending:o&&!t.quota})})]},e.name))}):o?(0,Q.jsx)(`div`,{className:`pws-dashboard-rows pws-dashboard-rows--pending`,"aria-hidden":`true`,children:Array.from({length:3},(e,t)=>(0,Q.jsxs)(`div`,{className:`pws-dashboard-row pws-dashboard-row--skeleton`,children:[(0,Q.jsx)(`span`,{className:`pws-dashboard-row-icon pws-skel`}),(0,Q.jsxs)(`div`,{className:`pws-dashboard-row-info`,children:[(0,Q.jsx)(`span`,{className:`pws-skel pws-skel--name`}),(0,Q.jsx)(`span`,{className:`pws-skel pws-skel--meta`})]}),(0,Q.jsx)(`div`,{className:`pws-dashboard-row-bars`,children:(0,Q.jsx)(sc,{quota:null,threshold:80,t:u,layout:`stacked`,pending:!0})})]},t))}):(0,Q.jsx)(`p`,{className:`muted pws-dashboard-empty`,children:u(`pws.dashboard.noRateLimits`)})]}),(0,Q.jsx)(`section`,{className:`pws-dashboard-section pws-dashboard-section--recent`,"aria-label":u(`pws.dashboard.recentlyUsed`),"aria-busy":a||void 0,children:(0,Q.jsxs)(`details`,{className:`pws-dashboard-recent-details`,children:[(0,Q.jsx)(`summary`,{className:`pws-dashboard-section-title`,children:u(`pws.dashboard.recentlyUsed`)}),E.length>0?(0,Q.jsx)(`div`,{className:`pws-dashboard-rows`,children:E.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`pws-dashboard-row`,onClick:()=>s(e.name),children:[(0,Q.jsx)(_e,{name:e.name,adapter:``,baseUrl:``,cls:`pws-dashboard-row-icon`}),(0,Q.jsx)(`span`,{className:`pws-dashboard-row-name`,children:Ce(e.name,u)}),(0,Q.jsx)(`span`,{className:`pws-dashboard-row-count muted`,children:u(`pws.dashboard.requests`,{count:Ws(e.requests,d)})}),(0,Q.jsx)(Ye,{className:`pws-dashboard-row-chevron`,"aria-hidden":`true`})]},e.name))}):a?(0,Q.jsx)(`div`,{className:`pws-dashboard-rows pws-dashboard-rows--pending`,"aria-hidden":`true`,children:Array.from({length:3},(e,t)=>(0,Q.jsxs)(`div`,{className:`pws-dashboard-row pws-dashboard-row--skeleton`,children:[(0,Q.jsx)(`span`,{className:`pws-dashboard-row-icon pws-skel`}),(0,Q.jsx)(`span`,{className:`pws-skel pws-skel--name`}),(0,Q.jsx)(`span`,{className:`pws-skel pws-skel--count`})]},t))}):(0,Q.jsx)(`p`,{className:`muted pws-dashboard-empty`,children:u(`pws.dashboard.noUsage`)})]})})]})]})}function vc({count:e,label:t,tone:n}){return(0,Q.jsxs)(`div`,{className:`pws-dashboard-card pws-dashboard-card--${n}`,children:[(0,Q.jsx)(`span`,{className:`pws-dashboard-card-count`,children:e}),(0,Q.jsx)(`span`,{className:`pws-dashboard-card-label`,children:t})]})}function yc({editor:e,providerName:t,saving:r,onSave:i,message:a}){let o=n(),s=(0,Z.useRef)(null);return(0,Z.useEffect)(()=>{e.open&&s.current?.focus()},[e.open]),e.open?(0,Q.jsxs)(`div`,{className:`pwi-json-panel`,children:[(0,Q.jsxs)(`div`,{className:`pwi-json-panel-header`,children:[(0,Q.jsx)(`span`,{className:`pwi-json-panel-title`,children:o(`pws.jsonEditorTitle`,{name:t})}),(0,Q.jsxs)(`div`,{className:`pwi-json-panel-actions`,children:[e.onRestore&&e.isDirty&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:e.onRestore,children:o(`pws.jsonRestore`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:e.onClose,children:o(`common.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:i,disabled:r||!e.isDirty,children:o(r?`pws.saving`:`pws.jsonSave`)})]})]}),(0,Q.jsx)(`p`,{className:`pwi-json-panel-desc muted`,children:o(`pws.jsonEditorDesc`)}),(0,Q.jsx)(`textarea`,{ref:s,className:`input pwi-json-textarea`,value:e.draft,onChange:t=>e.onDraftChange(t.target.value),spellCheck:!1,rows:20,"aria-label":o(`pws.jsonEditorDesc`)}),a&&(0,Q.jsx)(`div`,{className:a.ok?`pwi-settings-msg pwi-settings-msg--ok`:`pwi-settings-msg pwi-settings-msg--err`,children:a.text})]}):null}function bc(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Invalid model response`);return e}function xc(e){if(typeof e!=`string`||!e.trim())throw Error(`Invalid model identity`);return e}function Sc(e){if(!Array.isArray(e))throw Error(`Invalid model inventory`);let t=new Map,n=[];for(let r of e){let e=bc(r),i=xc(e.provider),a=xc(e.id),o=xc(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&&xc(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 Cc(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 wc(e){let t=bc(e),n=Object.assign(Object.create(null),Jo(t));for(let[e,t]of Object.entries(n))xc(e),t.forEach(xc);let r=Object.fromEntries(Object.entries(bc(t.available)).map(([e,t])=>{if(xc(e),!Array.isArray(t))throw Error(`Invalid available models`);return[e,t.map(xc)]})),i=Object.hasOwn(t,`liveModelCounts`)?bc(t.liveModelCounts):{},a=Object.fromEntries(Object.entries(i).map(([e,t])=>{if(xc(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 Tc(e){let t=bc(e);return{id:xc(t.id),provider:xc(t.provider),modelId:xc(t.modelId)}}function Ec(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=Tc(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 Dc(e,t,n){let r=Tc(e);if(r.provider!==t||r.modelId!==n)throw Error(`Unexpected created model`);return r}function Oc(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 kc=[{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 Ac(e){return X(io(e))}function jc({providers:e,apiBase:t,defaultProvider:r,selectedName:i,onSelect:a,onRemoveProvider:o,onAddProvider:s,onEditConfig:c,jsonEditor:l,jsonSaving:u=!1,modelsRefreshToken:d=0,onModelsSettled:f,activeAccountNeedsReauth:p,quotaRefreshEpoch:m=0,quotaForceRefresh:h=!1,onQuotaRefreshSettled:g,onRefreshAllQuotas:_,detail:v}){let y=n(),[b,x]=(0,Z.useState)(``),[S,C]=(0,Z.useState)({ready:!0,needsSetup:!0,disabled:!0}),[w,T]=(0,Z.useState)({free:!0,paid:!0}),[E,D]=(0,Z.useState)({cloud:!0,local:!0,selfHosted:!0,login:!0}),[O,k]=(0,Z.useState)(`az`),[A,j]=(0,Z.useState)(!1),[N,P]=(0,Z.useState)(null),[F,I]=(0,Z.useState)(null),[z,B]=(0,Z.useState)(!1),[V,H]=(0,Z.useState)(!1),ee=`ocx.providers.quotas.v1:${t}`,W=`ocx.providers.usage.v2:${t}`,[te,re]=(0,Z.useState)(()=>_r(io(W))),[q,J]=(0,Z.useState)(()=>io(W)?.totals??{}),[ie,ae]=(0,Z.useState)(()=>io(W)?.models??{}),[ce,le]=(0,Z.useState)(()=>Ac(ee)??{}),[ue,de]=(0,Z.useState)(()=>!io(W)),[fe,pe]=(0,Z.useState)(()=>{let e=Ac(ee);return!e||Object.keys(e).length===0}),[me,he]=(0,Z.useState)(0),ge=JSON.stringify([t,d,me]),_e=F?.revision===ge&&!z&&!V,ve=(0,Z.useMemo)(()=>Cc(F?.rows??[]),[F]),ye=(0,Z.useRef)(f);(0,Z.useEffect)(()=>{ye.current=f},[f]);let be=(0,Z.useRef)(null),xe=Wt(xr(t),[t],async e=>await br(await fetch(t+`/api/usage?range=30d`,{signal:e})),{deadlineMs:6e4}),Se=(0,Z.useMemo)(()=>{let t=dt(L(e));return Y(t,p??{})},[e,p]),we=(0,Z.useCallback)(()=>{B(!0),H(!1),he(e=>e+1)},[]);(0,Z.useEffect)(()=>{let e=!1,n=M(6e4),r=window.setTimeout(()=>{B(!0),(async()=>{let r=!1;try{let[i,a]=await Promise.all([fetch(`${t}/api/selected-models`,{signal:n.signal}).then(vn).then(wc),fetch(`${t}/api/models`,{signal:n.signal}).then(vn).then(Sc)]);if(e)return;I({revision:ge,selection:i,rows:a}),H(!1),r=!0}catch{if(e)return;H(!0)}finally{n.controller.abort(),n.clear(),e||(B(!1),ye.current?.(r))}})()},0);return()=>{e=!0,window.clearTimeout(r),n.controller.abort(),n.clear()}},[t,ge]),(0,Z.useEffect)(()=>{let e=!1,t=window.setTimeout(()=>{let t=xe.data;if(e)return;if(!t){xe.loading&&de(!io(W));return}let n=Is(t.providers??[]);J(n);let r=Ls(t.models??[],n);ae(r);let i=_r(t);re(i),co(W,{totals:n,models:r,...i}),de(!1)},0);return()=>{e=!0,window.clearTimeout(t)}},[t,W,xe.data,xe.loading]),(0,Z.useEffect)(()=>{let e=!1,n=window.setTimeout(()=>{let n=Ac(ee);(!n||Object.keys(n).length===0)&&pe(!0);let i=M(2e4);r=()=>{i.controller.abort(),i.clear()},fetch(`${t}/api/provider-quotas${h?`?refresh=1`:``}`,{signal:i.signal}).then(e=>yn(e)).then(t=>{if(e)return;if(!t){h&&g?.(!1,m);return}let n=oe(t.reports);le(n),co(ee,n),h&&g?.(!0,m)}).catch(()=>{e||(le(e=>{let t=X(e)??{};return co(ee,t),t}),h&&g?.(!1,m))}).finally(()=>{i.clear(),e||pe(!1)})},0),r;return()=>{e=!0,window.clearTimeout(n),r?.()}},[t,m,h,ee,g]),(0,Z.useEffect)(()=>{if(!A)return;let e=e=>{be.current&&!be.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 Te=(0,Z.useMemo)(()=>[...Se.ready,...Se.needsSetup,...Se.disabled],[Se]),Ee=(0,Z.useMemo)(()=>Te.filter(ne).length,[Te]),De=Te.length-Ee,Oe=(0,Z.useMemo)(()=>{let e={cloud:0,local:0,selfHosted:0,login:0};for(let t of Te)e[K(t)]+=1;return e},[Te]),ke=(0,Z.useMemo)(()=>{let e=b.trim().toLowerCase(),t=t=>{let n=t.filter(t=>{if(e&&!t.name.toLowerCase().includes(e)&&!t.adapter.toLowerCase().includes(e))return!1;let n=ne(t);return!(n&&!w.free||!n&&!w.paid||!E[K(t)])});return G(n,O)};return{ready:S.ready?t(Se.ready):[],needsSetup:S.needsSetup?t(Se.needsSetup):[],disabled:S.disabled?t(Se.disabled):[]}},[Se,b,S,w,E,O]),Ae=!S.ready||!S.needsSetup||!S.disabled||!w.free||!w.paid||!E.cloud||!E.local||!E.selfHosted||!E.login||O!==`az`,je=()=>{C({ready:!0,needsSetup:!0,disabled:!0}),T({free:!0,paid:!0}),D({cloud:!0,local:!0,selfHosted:!0,login:!0}),k(`az`)},Ne=(0,Z.useMemo)(()=>i?Te.find(e=>e.name===i)??null:null,[i,Te]),Pe=(0,Z.useMemo)(()=>{let e=new Map;for(let t of Te){let n=Ce(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},[Te,y]);if(Te.length===0)return(0,Q.jsx)(Mc,{onAddProvider:s});let Fe=[{key:`ready`,label:y(`pws.status.ready`),count:Se.ready.length},{key:`needsSetup`,label:y(`pws.status.needsSetup`),count:Se.needsSetup.length},{key:`disabled`,label:y(`prov.disabledBadge`),count:Se.disabled.length}],Ie=[{id:`ready`,label:y(`pws.status.ready`),count:ke.ready.length,ariaLabel:y(`pws.groupReady`,{count:ke.ready.length}),items:ke.ready},{id:`needs-setup`,label:y(`pws.status.needsSetup`),count:ke.needsSetup.length,ariaLabel:y(`pws.groupNeedsSetup`,{count:ke.needsSetup.length}),items:ke.needsSetup},{id:`disabled`,label:y(`prov.disabledBadge`),count:ke.disabled.length,ariaLabel:y(`pws.groupDisabled`,{count:ke.disabled.length}),items:ke.disabled}],Le=Ie.flatMap(e=>e.items.map(e=>e.name)),Re=N&&Le.includes(N)?N:i&&Le.includes(i)?i:Le[0]??null;return(0,Q.jsx)(`div`,{className:`pws-shell-container`,children:(0,Q.jsxs)(`div`,{className:`pws-root`,children:[(0,Q.jsxs)(`aside`,{className:`pws-rail`,"aria-label":y(`pws.providerList`),children:[(0,Q.jsxs)(`div`,{className:`pws-search-row`,children:[(0,Q.jsxs)(`div`,{className:`pws-search-wrap`,children:[(0,Q.jsx)(se,{className:`pws-search-icon`,width:14,height:14,"aria-hidden":`true`}),(0,Q.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,Q.jsxs)(`div`,{className:`pws-filter-wrap`,ref:be,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`pws-filter-btn${Ae||A?` pws-filter-btn--active`:``}`,onClick:()=>j(e=>!e),"aria-label":y(`pws.filterAria`),"aria-expanded":A,"aria-controls":`pws-provider-filters`,children:[(0,Q.jsx)(Me,{width:18,height:18,"aria-hidden":`true`}),Ae&&(0,Q.jsx)(`span`,{className:`pws-filter-dot`,"aria-hidden":`true`})]}),A&&(0,Q.jsxs)(`div`,{id:`pws-provider-filters`,className:`pws-filter-menu`,role:`group`,"aria-label":y(`pws.providerFiltersAria`),children:[(0,Q.jsx)(`div`,{className:`pws-filter-title`,children:y(`pws.filters`)}),(0,Q.jsx)(`div`,{className:`pws-filter-head`,children:y(`pws.filterStatus`)}),Fe.map(({key:e,label:t,count:n})=>(0,Q.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:S[e],onChange:()=>C(t=>({...t,[e]:!t[e]}))}),(0,Q.jsx)(`span`,{className:`pws-filter-label`,children:t}),(0,Q.jsx)(`span`,{className:`pws-filter-count`,children:n})]},e)),(0,Q.jsx)(`div`,{className:`pws-filter-head`,children:y(`pws.pricing`)}),(0,Q.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:w.free,onChange:()=>T(e=>({...e,free:!e.free}))}),(0,Q.jsx)(`span`,{className:`pws-filter-label`,children:y(`modal.badge.free`)}),(0,Q.jsx)(`span`,{className:`pws-filter-count`,children:Ee})]}),(0,Q.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:w.paid,onChange:()=>T(e=>({...e,paid:!e.paid}))}),(0,Q.jsx)(`span`,{className:`pws-filter-label`,children:y(`pws.paid`)}),(0,Q.jsx)(`span`,{className:`pws-filter-count`,children:De})]}),(0,Q.jsx)(`div`,{className:`pws-filter-head`,children:y(`pws.filterType`)}),[{key:`cloud`,label:y(`pws.type.cloud`),count:Oe.cloud},{key:`local`,label:y(`pws.type.local`),count:Oe.local},{key:`selfHosted`,label:y(`pws.type.selfHosted`),count:Oe.selfHosted},{key:`login`,label:y(`pws.type.login`),count:Oe.login}].map(({key:e,label:t,count:n})=>(0,Q.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:E[e],onChange:()=>D(t=>({...t,[e]:!t[e]}))}),(0,Q.jsx)(`span`,{className:`pws-filter-label`,children:t}),(0,Q.jsx)(`span`,{className:`pws-filter-count`,children:n})]},e)),(0,Q.jsx)(`div`,{className:`pws-filter-head`,children:y(`pws.sort`)}),(0,Q.jsx)(`div`,{className:`pws-sort-grid`,role:`group`,"aria-label":y(`pws.sortProvidersAria`),children:kc.map(e=>(0,Q.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,Q.jsx)(`div`,{className:`pws-filter-footer`,children:(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:je,disabled:!Ae,children:y(`pws.resetAll`)})})]})]})]}),(0,Q.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()}else e.key===`Home`?(e.preventDefault(),t[0]?.focus()):e.key===`End`&&(e.preventDefault(),t[t.length-1]?.focus())},children:[Object.values(ke).every(e=>e.length===0)&&(0,Q.jsx)(`span`,{className:`muted pws-rail-empty`,role:`status`,children:y(b?`pws.noSearchResults`:Ae?`pws.noMatchFilters`:`pws.noProvidersConfigured`)}),Ie.map(({id:e,label:t,count:n,ariaLabel:s,items:c})=>c.length===0?null:(0,Q.jsxs)(`div`,{className:`pws-rail-group`,role:`group`,"aria-label":s,children:[(0,Q.jsxs)(`div`,{className:`pws-rail-group-head`,"aria-hidden":`true`,children:[(0,Q.jsx)(`span`,{className:`pws-rail-group-label`,children:t}),(0,Q.jsx)(`span`,{className:`pws-rail-group-count`,children:n})]}),c.map(e=>(0,Q.jsxs)(`div`,{className:`pws-rail-row-wrap`,children:[(0,Q.jsx)(U,{item:e,selected:i===e.name,tabbable:Re===e.name,modelCount:F?Object.hasOwn(ve,e.name)?ve[e.name]:0:void 0,isDefault:r===e.name,showConfigId:Pe.has(Ce(e.name,y)),onClick:()=>a(e.name),onFocus:()=>P(e.name)}),o&&(0,Q.jsx)(`button`,{type:`button`,className:`pws-rail-row-remove`,tabIndex:-1,"aria-hidden":`true`,onClick:t=>{t.stopPropagation(),o(e.name)},title:y(`pws.removeConfirmTitle`),children:(0,Q.jsx)(R,{width:14,height:14})})]},e.name))]},e))]})]}),(0,Q.jsxs)(`main`,{className:`pws-main`,"aria-label":y(`pws.workspaceMainAria`),children:[!l?.open&&(0,Q.jsx)(Sr,{data:te}),l?.open?(0,Q.jsx)(yc,{editor:l,providerName:y(`nav.providers`),saving:u,onSave:()=>{l.onSave()}}):Ne?v?.(Ne,{usageTotals:q[Ne.name],modelUsage:ie[Ne.name],quotaReport:ce[Ne.name],availableModels:F?.selection.available[Ne.name]??[],hasLiveModels:(F?.selection.liveModelCounts[Ne.name]??0)>0,selectedModels:F?.selection.selected[Ne.name]??[],modelRows:F?.rows.filter(e=>e.provider===Ne.name)??null,modelRevision:ge,modelRowsReady:_e,modelsLoading:z||!_e&&!V,modelsLoadFailed:V,onRetryModels:we})??(0,Q.jsxs)(`div`,{className:`pws-detail-placeholder`,children:[(0,Q.jsx)(`h3`,{children:Ce(Ne.name,y)}),(0,Q.jsx)(`p`,{className:`muted`,children:y(`pws.detailComingSoon`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>a(null),children:y(`modal.back`)})]}):(0,Q.jsx)(_c,{sections:Se,quotaReports:ce,usageTotals:q,usageLoading:ue,quotasLoading:fe,onSelectProvider:e=>a(e),onEditConfig:c,..._?{onRefreshAllQuotas:_}:{}})]})]})})}function Mc({onAddProvider:e}){let t=n();return(0,Q.jsx)(`div`,{className:`pws-empty-root`,children:(0,Q.jsxs)(`div`,{className:`pws-empty-hero`,children:[(0,Q.jsx)(`div`,{"aria-hidden":`true`,children:(0,Q.jsx)(ze,{style:{width:64,height:64}})}),(0,Q.jsx)(`h2`,{children:t(`pws.connectFirst`)}),(0,Q.jsxs)(`div`,{className:`pws-empty-tiles`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`pws-empty-tile`,onClick:()=>e({tier:`free`}),children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:(0,Q.jsx)(Xe,{width:18,height:18})}),(0,Q.jsx)(`span`,{className:`pws-empty-tile-label`,children:t(`pws.empty.browseFree`)}),(0,Q.jsx)(`span`,{className:`pws-empty-tile-desc muted`,children:t(`pws.empty.browseFreeDesc`)})]}),(0,Q.jsxs)(`button`,{type:`button`,className:`pws-empty-tile`,onClick:()=>e({tier:`accounts`}),children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:(0,Q.jsx)(ct,{width:18,height:18})}),(0,Q.jsx)(`span`,{className:`pws-empty-tile-label`,children:t(`pws.empty.connectAccount`)}),(0,Q.jsx)(`span`,{className:`pws-empty-tile-desc muted`,children:t(`pws.empty.connectAccountDesc`)})]}),(0,Q.jsxs)(`button`,{type:`button`,className:`pws-empty-tile`,onClick:()=>e({custom:!0}),children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:(0,Q.jsx)(it,{width:18,height:18})}),(0,Q.jsx)(`span`,{className:`pws-empty-tile-label`,children:t(`pws.empty.addEndpoint`)}),(0,Q.jsx)(`span`,{className:`pws-empty-tile-desc muted`,children:t(`pws.empty.addEndpointDesc`)})]})]})]})})}function Nc(e){if(be(e.name,e))return`codex-accounts`;let t=(e.authMode??``).toLowerCase();if(t===`forward`||t===`local`||W(e))return null;if(t===`oauth`)return`oauth-accounts`;let n=e.hasApiKey===!0,r=t===`key`||n||t===``,i=e.keyOptional===!0||Ze(e);return!r||i&&!n?null:`api-keys`}function Pc(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)})}function Fc({quota:e,quotaMode:t,quotaUnavailable:r,quotaPending:i,quotaFailure:a}){let o=n(),s=ce({quota:e});if(t===`unsupported`)return(0,Q.jsx)(`p`,{className:`muted`,"data-quota-state":`unsupported`,children:o(`pws.quotaUnsupported`)});let c=t===`probe`&&r?Rr(a):void 0,l=t===`probe`&&i===!0;return(0,Q.jsxs)(`div`,{"data-quota-state":r?`unavailable`:l?`pending`:s?`ready`:t===`passive`?`unobserved`:`unknown`,children:[r&&(0,Q.jsx)(`p`,{className:`muted pwi-auth-acct-quota-stale`,children:o(c?`pws.quotaFailure.${c}`:`pws.accountQuotaUnavailable`)}),s||l?(0,Q.jsx)(gc,{report:{quota:s,updatedAt:s?.updatedAt,...t===`passive`?{observed:!0}:{}},pending:l&&!s}):!r&&(0,Q.jsx)(`p`,{className:`muted`,children:o(t===`passive`?`pws.quotaUnobserved`:`pws.quotaUnavailable`)}),r&&s&&(0,Q.jsxs)(`p`,{className:`muted`,children:[o(`pws.stats.quotaUpdated`),`: `,Bs(s.updatedAt,Vs(o))]})]})}function Ic({report:e,reading:t,onRefreshQuota:r}){let i=n(),a=F(e),o=t!==void 0&&(t.quotaMode!==void 0||t.quota!==void 0||t.quotaUnavailable!==void 0||t.quotaPending!==void 0),s=o?t:{quota:ce(a),...a?.observed===!0?{quotaMode:`passive`}:{}},c=ce({quota:s.quota}),[l,u]=(0,Z.useState)(!1),[d,f]=(0,Z.useState)(null),p=async()=>{if(r&&!l){u(!0),f(null);try{f(await r())}catch{f(!1)}finally{u(!1)}}};return(0,Q.jsxs)(`section`,{className:`pws-usage-block`,"aria-label":i(`pws.currentAccountUsage`),children:[(0,Q.jsxs)(`div`,{className:`pws-usage-block-head`,children:[(0,Q.jsx)(`h3`,{className:`pws-section-title`,children:i(`pws.currentAccountUsage`)}),r&&s.quotaMode!==`unsupported`&&(0,Q.jsxs)(`div`,{className:`pws-quota-refresh`,children:[d!==null&&(0,Q.jsx)(`span`,{role:`status`,className:d?`pws-status-ok`:`pws-status-warn`,children:i(d?`pws.quotaCheckCompleted`:`codexAuth.quotaRefreshFailed`)}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:l,onClick:()=>{p()},children:[(0,Q.jsx)(ae,{width:14,height:14,"aria-hidden":`true`}),` `,i(l?`codexAuth.refreshingQuota`:`codexAuth.refreshQuota`)]})]})]}),(0,Q.jsx)(Fc,{...s}),c&&!s.quotaUnavailable&&s.quotaMode!==`unsupported`&&(0,Q.jsxs)(`dl`,{className:`pws-kv pws-usage-meta`,children:[!o&&a?.source?.trim()&&(0,Q.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Q.jsx)(`dt`,{children:i(`pws.stats.source`)}),(0,Q.jsx)(`dd`,{children:Be(a.source)})]}),(0,Q.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Q.jsx)(`dt`,{children:i(`pws.stats.quotaUpdated`)}),(0,Q.jsx)(`dd`,{children:Bs(c.updatedAt,Vs(i))})]})]})]})}function Lc(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 Rc(e){return{adapter:e.adapter,baseUrl:e.baseUrl,authMode:e.auth,freeTier:!!e.freeTier,keyOptional:!!e.keyOptional}}function zc(e){return Se(e.id,Rc(e))}function Bc(e){return W(Rc(e))}function Vc(e){let t={accounts:[],free:[],local:[],paid:[]};for(let n of e){let e=zc(n);t[e===`accounts`?`accounts`:Bc(n)?`local`:e].push(n)}return t}function Hc(e){return!!e?.trim()}var Uc=new Set([`local`,`localhost`,`ollama`,`vllm`,`lmstudio`,`lm studio`,`self-hosted`,`selfhosted`]);function Wc(e,t){let n=t.trim().toLowerCase();return!n||e.label.toLowerCase().includes(n)||e.id.toLowerCase().includes(n)||e.adapter.toLowerCase()===n?!0:Uc.has(n)&&Bc(e)}function Gc(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 Kc(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 qc(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 Jc={main:0,standard:1};function Yc(e){let t=e.filter(e=>e.sponsor);return t.length===0?e:(t.sort((e,t)=>Jc[e.sponsor]-Jc[t.sponsor]||e.label.localeCompare(t.label,void 0,{sensitivity:`base`})||e.id.localeCompare(t.id)),[...t,...e.filter(e=>!e.sponsor)])}var Xc={name:`OrcaRouter`,title:`pws.sponsor.orcaTitle`,description:`pws.sponsor.orcaDescription`},Zc={orcarouter:Xc,"orcarouter-oauth":Xc,tokenlab:{name:`TokenLab`,title:`pws.sponsor.tokenlabTitle`,description:`pws.sponsor.tokenlabDescription`}};function Qc(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 $c({item:e,preset:t}){let r=n();if(!t?.sponsor||!Lc(e,[t]))return null;let i=Object.hasOwn(Zc,t.id)?Zc[t.id]:void 0;if(!i)return null;let a=Qc(t.sponsorUrl),o=Qc(t.dashboardUrl);return(0,Q.jsxs)(`section`,{className:`pws-sponsor`,"aria-label":`${i.name} · ${r(`modal.badge.sponsor`)}`,children:[(0,Q.jsxs)(`div`,{className:`pws-sponsor-copy`,children:[(0,Q.jsxs)(`div`,{className:`pws-sponsor-byline`,children:[(0,Q.jsx)(`span`,{children:i.name}),(0,Q.jsx)(`span`,{className:`pws-sponsor-badge`,children:r(`modal.badge.sponsor`)})]}),(0,Q.jsx)(`h3`,{children:r(i.title)}),(0,Q.jsx)(`p`,{children:r(i.description)})]}),(a||o)&&(0,Q.jsxs)(`div`,{className:`pws-sponsor-actions`,children:[a&&(0,Q.jsxs)(`a`,{className:`btn btn-primary`,href:a,target:`_blank`,rel:`noopener noreferrer`,children:[r(`pws.sponsor.visit`,{provider:i.name}),(0,Q.jsx)(We,{width:14,height:14,"aria-hidden":`true`})]}),o&&o!==a&&(0,Q.jsxs)(`a`,{className:`pws-sponsor-console`,href:o,target:`_blank`,rel:`noopener noreferrer`,children:[r(`pws.sponsor.console`),(0,Q.jsx)(We,{width:13,height:13,"aria-hidden":`true`})]})]})]})}function el({apiBase:e,provider:t,models:r}){let i=n(),[a,o]=(0,Z.useState)(``),s=r.includes(a)?a:``;return(0,Q.jsxs)(`section`,{className:`pws-completion-test`,"aria-label":i(`pws.completion.title`),children:[(0,Q.jsx)(`h4`,{className:`pws-section-title`,children:i(`pws.completion.title`)}),(0,Q.jsx)(dn,{label:i(`pws.completion.model`),value:s,options:[{value:``,label:i(`pws.completion.choose`)},...r.map(e=>({value:e,label:e}))],onChange:o}),(0,Q.jsx)(tl,{apiBase:e,provider:t,model:s},JSON.stringify([e,t,s]))]})}function tl({apiBase:e,provider:t,model:i}){let a=n(),{locale:o}=r(),[s,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(null),[d,f]=(0,Z.useState)(null),p=(0,Z.useRef)(null);(0,Z.useEffect)(()=>()=>{p.current?.abort(),p.current=null},[]);async function m(){if(!i||p.current)return;let n=new AbortController;p.current=n,c(!0),u(null),f(null);try{if(!await ha({message:a(`pws.completion.confirm`,{model:i,provider:t}),confirmLabel:a(`pws.completion.run`),signal:n.signal,locale:o})||n.signal.aborted)return;let r=await vn(await fetch(`${e}/api/providers/test-completion?name=${encodeURIComponent(t)}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({model:i,confirm:!0}),signal:n.signal}),a(`pws.completion.failed`));if(!r)throw Error(a(`pws.completion.failed`));n.signal.aborted||u(r)}catch(e){n.signal.aborted||f(e instanceof Error?e.message:a(`pws.completion.failed`))}finally{p.current===n&&(p.current=null,n.signal.aborted||c(!1))}}return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:!i||s,onClick:()=>void m(),children:a(s?`pws.testing`:`pws.completion.run`)}),d&&(0,Q.jsx)(`p`,{role:`alert`,className:`pws-inline-error pws-completion-result`,children:d}),l&&(0,Q.jsx)(nl,{result:l})]})}function nl({result:e}){let t=n();return e.applicable?(0,Q.jsxs)(`div`,{role:`status`,className:`pws-completion-result`,"data-completion-test-state":e.ok?`ok`:`failed`,children:[(0,Q.jsx)(`p`,{className:e.ok?`pws-status-ok`:`pws-status-warn`,children:t(e.ok?`pws.completion.ok`:`pws.completion.failed`)}),(0,Q.jsxs)(`dl`,{className:`pws-kv`,children:[(0,Q.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Q.jsx)(`dt`,{children:t(`pws.completion.ttft`)}),(0,Q.jsx)(`dd`,{children:e.ttftMs===null?`—`:`${e.ttftMs} ms`})]}),(0,Q.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Q.jsx)(`dt`,{children:t(`pws.completion.total`)}),(0,Q.jsxs)(`dd`,{children:[e.totalLatencyMs,` ms`]})]})]}),(0,Q.jsx)(`p`,{children:e.upstreamModel===null?t(`pws.completion.unreported`,{model:e.wireModel}):t(`pws.completion.reported`,{upstream:e.upstreamModel,model:e.wireModel})}),(0,Q.jsx)(`span`,{className:`badge ${e.modelComparison===`match`?`badge-green`:e.modelComparison===`mismatch`?`badge-amber`:`badge-muted`}`,children:t(`pws.completion.${e.modelComparison}`)}),e.comparisonNote&&(0,Q.jsx)(`p`,{className:`muted`,children:t(`pws.completion.${e.comparisonNote}`)}),(0,Q.jsx)(`p`,{className:`muted`,children:t(`pws.completion.identity`)}),e.error&&(0,Q.jsxs)(`p`,{role:`alert`,className:`pws-inline-error`,children:[(0,Q.jsx)(`code`,{children:e.error.code}),e.error.status!==void 0&&(0,Q.jsxs)(Q.Fragment,{children:[` (`,e.error.status,`)`]}),`: `,e.error.message]})]}):(0,Q.jsxs)(`div`,{role:`status`,className:`pws-completion-result muted`,children:[(0,Q.jsxs)(`p`,{children:[t(`pws.completion.notApplicable`),`: `,t(`pws.completion.${e.reason}`)]}),e.detail&&(0,Q.jsx)(`p`,{children:t(`pws.completion.${e.detail}`)}),e.adapter&&(0,Q.jsx)(`p`,{children:(0,Q.jsx)(`code`,{children:e.adapter})})]})}function rl({item:e,preset:t,usageTotals:i,quotaReport:a,currentQuotaReading:o,onRefreshQuota:s,oauthEmail:c,oauth:l,apiBase:u,connectionIdentity:d,availableModels:f=[],onEditSettings:p,onViewUsage:m,onUpdateProvider:h,onCreateJevAuto:g,onReauthenticate:_,onCancelLogin:v,reauthBusy:y=!1}){let b=n(),{locale:x}=r(),S=pe(e),C=!!e.activeNeedsReauth,w=b(S===`ready`?`pws.status.connected`:S===`needs-setup`?C?`pws.status.needsAttention`:`pws.status.needsSetup`:`prov.disabledBadge`),T=i?.requests,E=i?.totalTokens,D=JSON.stringify([u??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,d??null]),[O,k]=(0,Z.useState)(null),A=(0,Z.useRef)(null),j=O?.key===D&&O.testing,M=O?.key===D?O.result:null;(0,Z.useEffect)(()=>()=>{A.current?.key===D&&(A.current.controller.abort(),A.current=null)},[D]);let N=(0,Z.useCallback)(async()=>{if(u===void 0)return;A.current?.controller.abort();let t=new AbortController;A.current={key:D,controller:t},k({key:D,testing:!0,result:null});try{let n=await vn(await fetch(`${u}/api/providers/test?name=${encodeURIComponent(e.name)}`,{method:`POST`,signal:t.signal}),b(`pws.connectionFailed`));if(!n)throw Error(b(`pws.connectionFailed`));t.signal.aborted||k({key:D,testing:!1,result:n})}catch(e){t.signal.aborted||k({key:D,testing:!1,result:{applicable:!0,ok:!1,error:e instanceof Error?e.message:b(`pws.connectionFailed`)}})}finally{A.current?.controller===t&&(A.current=null)}},[u,D,e.name,b]),P=M?.applicable===!1?`not-applicable`:M?.ok===!0?`ok`:`failed`,F=M?.applicable===!1?b(`pws.connectionNotApplicable`):M?.ok===!0?M.message||b(`pws.connectionOk`):M?.error||b(`pws.connectionFailed`);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)($c,{item:e,preset:t}),(0,Q.jsxs)(`div`,{className:`pws-overview-layout`,children:[(0,Q.jsxs)(`div`,{className:`pws-overview-main`,children:[(0,Q.jsxs)(`section`,{className:`pws-section`,"aria-label":b(`pws.connection`),children:[(0,Q.jsx)(`h3`,{className:`pws-section-title`,children:b(`pws.connection`)}),(0,Q.jsxs)(`dl`,{className:`pws-kv`,children:[(0,Q.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Q.jsx)(`dt`,{children:b(`dash.status`)}),(0,Q.jsxs)(`dd`,{className:S===`ready`?`pws-status-ok`:`pws-status-warn`,children:[S===`ready`?(0,Q.jsx)(Oe,{style:{width:13,height:13},"aria-hidden":`true`}):(0,Q.jsx)(Ne,{style:{width:13,height:13},"aria-hidden":`true`}),w]})]}),(0,Q.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Q.jsx)(`dt`,{children:b(`modal.baseUrl`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(`code`,{children:e.baseUrl?.trim()?e.baseUrl:`—`})})]}),(0,Q.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Q.jsx)(`dt`,{children:b(`pws.cell.auth`)}),(0,Q.jsx)(`dd`,{children:c?`${V(e,b)} · ${c}`:V(e,b)})]}),(0,Q.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Q.jsx)(`dt`,{children:b(`modal.defaultModel`)}),(0,Q.jsx)(`dd`,{children:e.defaultModel??(0,Q.jsx)(`span`,{className:`muted`,children:`—`})})]})]}),u!==void 0&&(0,Q.jsxs)(`div`,{className:`row`,style:{marginTop:12,alignItems:`center`},children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:j,onClick:()=>void N(),children:b(j?`pws.testing`:`pws.testConnection`)}),M&&(0,Q.jsx)(`span`,{role:`status`,className:P===`ok`?`pws-status-ok`:P===`failed`?`pws-status-warn`:`muted`,"data-connection-test-state":P,children:F})]}),u!==void 0&&(0,Q.jsx)(el,{apiBase:u,provider:e.name,models:[...new Set([...e.models??[],...f,...e.defaultModel?[e.defaultModel]:[]])]},D),p&&(0,Q.jsx)(`button`,{type:`button`,className:`link-btn pws-edit-settings-link`,onClick:p,children:b(`pws.editSettings`)})]}),e.adapter===`jev-decision`&&g&&(0,Q.jsxs)(`section`,{className:`pws-section`,"aria-label":b(`cws.jev.create`),children:[(0,Q.jsx)(`h3`,{className:`pws-section-title`,children:b(`cws.jev.create`)}),(0,Q.jsx)(`p`,{className:`muted`,style:{marginTop:0},children:b(`cws.jev.setupHint`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:g,children:b(`cws.jev.create`)})]}),(0,Q.jsxs)(`section`,{className:`pws-section`,"aria-label":b(`pws.authSummary`),children:[(0,Q.jsx)(`h3`,{className:`pws-section-title`,children:b(`pws.authSummary`)}),C?(0,Q.jsxs)(`div`,{className:`pws-auth-summary pws-auth-summary--warn`,role:`status`,children:[(0,Q.jsx)(Ne,{style:{width:14,height:14},"aria-hidden":`true`}),(0,Q.jsxs)(`div`,{className:`pws-auth-summary-body`,children:[(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:b(`pws.status.needsAttention`)}),` — `,e.authMode===`forward`?b(`pws.attention.reauthForward`):b(`pws.attention.reauth`)]}),_&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:y,onClick:()=>_(),children:b(y?`prov.waitingBrowser`:`pws.reauthenticate`)}),y&&v&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>v(),children:b(`common.cancel`)})]})]}):(0,Q.jsxs)(`div`,{className:`pws-auth-summary`,children:[(0,Q.jsx)(`span`,{className:`pws-auth-dot`}),(0,Q.jsx)(`span`,{children:e.authMode===`forward`?b(`pws.passthrough`):e.authMode===`oauth`?c?b(`pws.loggedInAs`,{email:c}):l?.loggedIn?b(`pws.loggedInTitle`):b(`pws.notLoggedIn`):e.hasApiKey?b(`pws.apiKeyConfigured`):V(e,b)})]})]}),(0,Q.jsx)(il,{item:e,onUpdateProvider:h})]}),(0,Q.jsxs)(`aside`,{className:`pws-overview-sidebar`,children:[(0,Q.jsxs)(`section`,{className:`pws-section`,"aria-label":b(`pws.statsAria`),children:[(0,Q.jsx)(`h3`,{className:`pws-section-title`,children:b(`pws.statsTitle`)}),(0,Q.jsxs)(`dl`,{className:`pws-kv`,children:[typeof T==`number`&&(0,Q.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Q.jsx)(`dt`,{children:b(`pws.stats.totalRequests`)}),(0,Q.jsx)(`dd`,{className:`pws-kv-mono`,children:Ws(T,x)})]}),typeof E==`number`&&(0,Q.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,Q.jsx)(`dt`,{children:b(`pws.stats.totalTokens`)}),(0,Q.jsx)(`dd`,{className:`pws-kv-mono`,children:Gs(E,x)})]}),typeof T!=`number`&&typeof E!=`number`&&(0,Q.jsx)(`div`,{className:`muted`,children:b(`pws.usageUnavailable`)})]}),m&&(0,Q.jsxs)(`button`,{type:`button`,className:`link-btn pws-view-usage-link`,onClick:m,children:[b(`pws.viewUsage`),` →`]})]}),(0,Q.jsx)(Ic,{report:a,reading:o,onRefreshQuota:s},`${e.name}:${d??``}`)]})]})]})}function il({item:e,onUpdateProvider:t}){let r=n(),[i,a]=(0,Z.useState)(!1),[o,s]=(0,Z.useState)(``),[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(``),f=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{i&&f.current?.focus()},[i]);let p=(0,Z.useCallback)(async()=>{if(c||!t)return;let n=o.trim();if(n===(e.note??``))a(!1),d(``);else{l(!0);try{let i=await t(e.name,{note:n||void 0});if(!i.ok){d(i.error||r(`prov.saveFailed`));return}d(``),a(!1)}finally{l(!1)}}},[o,e.name,e.note,t,c,r]);return i?(0,Q.jsxs)(`section`,{className:`pws-section pws-notes-section`,"aria-label":r(`pws.notes`),children:[(0,Q.jsx)(`h3`,{className:`pws-section-title`,children:r(`pws.notes`)}),(0,Q.jsx)(`textarea`,{ref:f,className:`pws-notes-textarea`,value:o,onChange:e=>s(e.target.value),onBlur:()=>void p(),onKeyDown:t=>{t.key===`Escape`&&(s(e.note??``),d(``),a(!1))},placeholder:r(`pws.notePlaceholder`),rows:3,disabled:c}),u?(0,Q.jsx)(`p`,{className:`pws-inline-error`,role:`alert`,children:u}):null]}):(0,Q.jsxs)(`section`,{className:`pws-section pws-notes-section`,"aria-label":r(`pws.notes`),children:[(0,Q.jsx)(`h3`,{className:`pws-section-title`,children:r(`pws.notes`)}),(0,Q.jsx)(`button`,{type:`button`,className:`pws-notes-display`,onClick:()=>{t&&(s(e.note??``),d(``),a(!0))},disabled:!t,children:e.note||(0,Q.jsx)(`span`,{className:`muted`,children:r(`pws.notePlaceholder`)})})]})}function al(e){return e.includes(`/`)?e.replaceAll(`/`,`-`):e}function ol(e,t){let n=al(e);for(let r of t)if(r!==e&&al(r)===n)return!0;return!1}function sl({row:e,disambiguate:t,copied:r,isDefault:i,selected:a,action:o,disabled:s,onCopy:c,onRemove:l}){let u=n(),d=u(o===`delete`?`models.customDelete`:`models.hide`);return(0,Q.jsxs)(`li`,{className:`pws-model-chip`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`pws-model-chip-main`,onClick:c,title:e.namespaced,"aria-label":u(r?`pws.modelCopied`:`pws.copyModelId`),children:(0,Q.jsx)(`span`,{className:`pws-model-id`,children:t?e.namespaced:e.id})}),i&&(0,Q.jsx)(`span`,{className:`badge badge-muted pws-model-flag`,children:u(`prov.defaultBadge`)}),a&&(0,Q.jsx)(`span`,{className:`badge badge-accent pws-model-flag`,children:u(`pws.selected`)}),o&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm btn-icon-only`,onClick:e=>l(e.currentTarget),disabled:s,"aria-label":`${d}: ${e.namespaced}`,title:`${d}: ${e.namespaced}`,children:o===`delete`?(0,Q.jsx)(R,{style:{width:13,height:13},"aria-hidden":`true`}):(0,Q.jsx)(nt,{style:{width:13,height:13},"aria-hidden":`true`})})]})}var cl=300;function ll(e){return(0,Q.jsx)(ul,{...e},JSON.stringify([e.apiBase,e.item.name]))}function ul({item:e,apiBase:t,availableModels:r,selectedModels:i,modelRows:a,modelRevision:o,modelRowsReady:s,modelsLoading:c=!1,modelsLoadFailed:l=!1,needsReauth:u=!1,onRetryModels:d,onOpenAccounts:f,onOpenModels:p}){let m=n(),[h,g]=(0,Z.useState)(``),[_,v]=(0,Z.useState)(!1),[y,b]=(0,Z.useState)(``),[x,S]=(0,Z.useState)(0),C=JSON.stringify([t,e.name,o,x]),[w,T]=(0,Z.useState)(null),[E,D]=(0,Z.useState)(null),[O,k]=(0,Z.useState)(!1),[A,j]=(0,Z.useState)(null),[N,P]=(0,Z.useState)(null),F=(0,Z.useRef)(null),I=(0,Z.useRef)(!1),L=(0,Z.useRef)(!0),R=(0,Z.useRef)(o),z=(0,Z.useRef)(null),B=(0,Z.useRef)(null),V=(0,Z.useRef)(null),H=w?.key===C&&E!==C,U=a!==null&&s&&!c&&!l&&H,ee=U&&(!A||o!==A.revision),W=O||!!A&&!ee,te=(a??[]).filter(t=>t.provider===e.name),G=te.some(e=>e.initialSelectionPending),ne=!U||W||G,K=w?.rows.filter(t=>t.provider===e.name)??[],re=new Set(i),q=[...r,...e.models??[],...K.map(e=>e.modelId),...e.defaultModel?[e.defaultModel]:[]],J=y.trim(),Y=!!J&&(q.includes(J)||ol(J,q)),ie=te.filter(e=>!e.disabled),X=ts(ie),ae=rs(_,ie),oe=ns(ie,ae),se=h.trim().toLowerCase(),ce=oe.filter(e=>[e.id,e.namespaced].some(e=>e.toLowerCase().includes(se))),le=new Map;for(let e of ie)le.set(e.id,(le.get(e.id)??0)+1);(0,Z.useEffect)(()=>{R.current=o},[o]),(0,Z.useEffect)(()=>{L.current=!0;let e=e=>{V.current&&e.target!==V.current.button&&e.target!==document.body&&(V.current.retained=!1)};return document.addEventListener(`focusin`,e),()=>{L.current=!1,document.removeEventListener(`focusin`,e),F.current!==null&&clearTimeout(F.current)}},[]),(0,Z.useEffect)(()=>{let e=!1,n=M(2e4);return fetch(`${t}/api/custom-models`,{signal:n.signal}).then(vn).then(Ec).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,Z.useEffect)(()=>{!O&&ee&&(I.current=!1);let e=V.current;e&&!e.button.isConnected&&(e.retained&&document.activeElement===document.body&&(z.current??B.current)?.focus(),V.current=null)},[O,ee,a]);let ue=()=>{S(e=>e+1),d?.()},de=async e=>{try{if(await navigator.clipboard.writeText((le.get(e.id)??0)>1?e.namespaced:e.id),!L.current)return;P(e.namespaced),F.current!==null&&clearTimeout(F.current),F.current=setTimeout(()=>P(null),1200)}catch{}},fe=e=>e.custom===!0&&e.native!==!0&&K.some(t=>t.id===e.customId&&t.provider===e.provider&&t.modelId===e.id),pe=e=>!U||e.initialSelectionPending?null:e.custom?fe(e)?`delete`:null:e.native!==!0&&K.some(t=>t.modelId===e.id)?null:`hide`,me=e=>{L.current?(j({...e,revision:R.current}),k(!1),ue()):d?.()},he=async()=>{if(ne||I.current||!J||Y)return;I.current=!0,k(!0),j(null);let n=M(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:J})});if(i.status===201){let t=await vn(i),n=Dc(t,e.name,J);if(w?.rows.some(e=>e.id===n.id))throw Error(`Reused custom identity`);r={outcome:`saved`,created:n,refreshPending:Oc(t)},L.current&&b(``)}else i.status>=400&&i.status<500&&(r={outcome:`rejected`,refreshPending:!1})}catch{}finally{n.clear(),me(r)}},ge=async(e,n)=>{let r=pe(e);if(ne||I.current||!r)return;if(I.current=!0,!await ha({message:m(r===`delete`?`models.customDeleteConfirm`:`models.hideConfirm`,{name:e.namespaced}),confirmLabel:m(r===`delete`?`common.delete`:`common.ok`),tone:`danger`})){I.current=!1;return}k(!0),j(null),V.current={button:n,retained:document.activeElement===n};let i=M(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 Qo(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 vn(n);e&&typeof e==`object`&&!Array.isArray(e)&&`ok`in e&&e.ok===!0&&(a={outcome:r===`delete`?`deleted`:`hidden`,refreshPending:Oc(e)})}else n.status>=400&&n.status<500&&(a={outcome:`rejected`,refreshPending:!1})}catch{}finally{i.clear(),me(a)}},_e=A?.created&&ee&&te.some(e=>e.customId===A.created?.id&&e.disabled),ve=A&&(A.refreshPending||l||E===C),ye=A?A.outcome===`unconfirmed`?m(`pws.modelMutationUnconfirmed`):A.outcome===`rejected`?m(`models.customSaveFailed`):A.outcome===`saved`?m(ve?`pws.modelSavedRefreshPending`:_e?`pws.modelSavedHidden`:`pws.modelSaved`):m(ve?`pws.modelRemovedRefreshPending`:A.outcome===`deleted`?`pws.modelDefinitionDeleted`:`pws.modelHidden`):null;return(0,Q.jsxs)(`div`,{className:`pws-section`,children:[(0,Q.jsxs)(`div`,{className:`pws-section-head`,children:[(0,Q.jsx)(`h3`,{className:`pws-section-title`,children:m(`pws.tab.models`)}),a!==null&&(0,Q.jsx)(`span`,{className:`muted`,children:m(`pws.modelsAvailable`,{count:ie.length})})]}),(0,Q.jsx)(`div`,{className:`row`,children:(0,Q.jsx)(`button`,{ref:B,type:`button`,className:`btn btn-ghost btn-sm`,onClick:p,children:m(`pws.manageModelVisibility`)})}),u&&(0,Q.jsxs)(`div`,{className:`pws-inline-error`,role:`status`,children:[(0,Q.jsx)(`span`,{children:m(`pws.modelsNeedsReauth`)}),f&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:f,children:m(`pws.tab.accounts`)})]}),s&&r.length===0&&ie.length>0&&(e.models?.length??0)>0&&!u&&(0,Q.jsx)(`p`,{className:`muted text-label`,children:m(`pws.modelsConfiguredFallback`)}),G&&(0,Q.jsx)(`p`,{role:`status`,className:`muted`,children:m(`pws.modelSelectionPending`)}),(0,Q.jsx)(`label`,{className:`text-label pws-custom-model-label`,htmlFor:`pws-custom-model-${e.name}`,children:m(`models.customAdd`)}),(0,Q.jsxs)(`div`,{className:`row pws-custom-model-row`,children:[(0,Q.jsx)(`input`,{id:`pws-custom-model-${e.name}`,className:`input`,value:y,onChange:e=>b(e.target.value),onKeyDown:e=>{e.key===`Enter`&&he()},placeholder:m(`models.customFieldModelIdPlaceholder`),"aria-label":m(`models.customAdd`),disabled:O}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>{he()},disabled:ne||!J||Y,children:m(O?`models.customSaving`:`models.customAddBtn`)})]}),Y&&(0,Q.jsx)(`p`,{className:`muted text-label`,role:`status`,children:m(`pws.modelKnown`)}),ye&&(0,Q.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:ye}),_e&&ve&&(0,Q.jsx)(`p`,{className:`muted text-label`,role:`status`,children:m(`pws.modelSavedHidden`)}),A?.refreshPending&&(0,Q.jsx)(`p`,{className:`muted text-label`,role:`status`,children:m(`codexAuth.catalogRefreshPending`)}),l||E===C?(0,Q.jsxs)(`div`,{className:`pws-inline-error`,role:`alert`,children:[(0,Q.jsx)(`span`,{children:m(l?`pws.modelsLoadFailed`:`pws.modelOwnershipFailed`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:ue,disabled:O,children:m(`common.retry`)})]}):(!U||W)&&(0,Q.jsx)(`p`,{className:`muted`,role:`status`,children:m(!s||c?`pws.modelsLoading`:`pws.modelOwnershipLoading`)}),A&&(A.outcome===`unconfirmed`||A.refreshPending)&&!l&&E!==C&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:ue,disabled:O,children:m(`common.retry`)}),X&&(0,Q.jsx)(`div`,{className:`row`,children:(0,Q.jsx)(ln,{on:_,onClick:()=>v(!_),label:m(`models.freeOnly`),showLabel:!0})}),(0,Q.jsx)(`input`,{ref:z,type:`search`,className:`input pws-model-search`,placeholder:m(`pws.modelSearchPlaceholder`),value:h,onChange:e=>g(e.target.value),"aria-label":m(`pws.modelSearchPlaceholder`)}),a!==null&&ie.length===0?(0,Q.jsx)(`p`,{className:`muted`,children:m(`pws.noModels`)}):ce.length===0&&a!==null?(0,Q.jsx)(`p`,{className:`muted`,role:`status`,children:m(ae&&oe.length===0?`models.noFreeMatch`:`pws.noModelMatch`)}):(0,Q.jsx)(`ul`,{className:`pws-model-list`,children:ce.slice(0,cl).map(t=>(0,Q.jsx)(sl,{row:t,disambiguate:(le.get(t.id)??0)>1,copied:N===t.namespaced,isDefault:t.id===e.defaultModel,selected:t.native!==!0&&re.has(t.id),action:pe(t),disabled:ne,onCopy:()=>{de(t)},onRemove:e=>{ge(t,e)}},t.namespaced))}),ce.length>cl&&(0,Q.jsx)(`p`,{className:`muted text-label`,style:{marginTop:10},children:m(`pws.modelsTruncated`,{shown:String(cl),total:String(ce.length)})})]})}function dl({item:e,usageTotals:t,quotaReport:i,currentQuotaReading:a,quotaIdentity:o,modelUsage:s,onRefreshQuota:c}){let l=n(),{locale:u}=r(),d=t?.requests!==void 0,[f,p]=(0,Z.useState)(null),m=(0,Z.useMemo)(()=>s?.length?s.toSorted((e,t)=>t.totalTokens-e.totalTokens):[],[s]),h=(0,Z.useMemo)(()=>{if(!m.length)return;let e=0,t=!1;for(let n of m)n.estimatedCostUsd!==void 0&&(e+=n.estimatedCostUsd,t=!0);return t?e:void 0},[m]);return(0,Q.jsxs)(`div`,{className:`pws-section`,children:[(0,Q.jsxs)(`div`,{className:`pws-usage-block`,children:[(0,Q.jsx)(`h3`,{className:`pws-section-title`,children:l(`pws.usageLast30d`)}),d?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`pws-usage-metrics pws-usage-metrics-3`,role:`group`,"aria-label":l(`pws.usageLast30d`),children:[(0,Q.jsxs)(`div`,{className:`pws-usage-metric`,children:[(0,Q.jsx)(`span`,{className:`pws-usage-metric-value mono`,children:Ks(h,u)}),(0,Q.jsx)(`span`,{className:`muted pws-usage-metric-label`,children:l(`pws.estimatedCost`)})]}),(0,Q.jsxs)(`div`,{className:`pws-usage-metric`,children:[(0,Q.jsx)(`span`,{className:`pws-usage-metric-value`,children:Ws(t?.requests,u)}),(0,Q.jsx)(`span`,{className:`muted pws-usage-metric-label`,children:l(`pws.metricRequests`)})]}),(0,Q.jsxs)(`div`,{className:`pws-usage-metric`,children:[(0,Q.jsx)(`span`,{className:`pws-usage-metric-value`,children:Gs(t?.totalTokens,u)}),(0,Q.jsx)(`span`,{className:`muted pws-usage-metric-label`,children:l(`pws.metricTokens`)})]})]}),(0,Q.jsx)(`p`,{className:`muted pws-cost-disclaimer`,children:l(`pws.costDisclaimer`)})]}):(0,Q.jsx)(`p`,{className:`muted`,children:l(`pws.usageUnavailable`)})]}),m.length>0&&(0,Q.jsxs)(`div`,{className:`pws-usage-block`,children:[(0,Q.jsx)(`h3`,{className:`pws-section-title`,children:l(`pws.modelBreakdown`)}),(0,Q.jsx)(`div`,{className:`tbl-wrap`,children:(0,Q.jsxs)(`table`,{className:`pws-model-table`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:l(`pws.col.model`)}),(0,Q.jsx)(`th`,{className:`num`,children:l(`pws.col.cost`)}),(0,Q.jsx)(`th`,{className:`num`,children:l(`pws.col.tokens`)}),(0,Q.jsx)(`th`,{className:`num`,children:l(`pws.col.requests`)}),(0,Q.jsx)(`th`,{children:l(`pws.col.share`)})]})}),(0,Q.jsx)(`tbody`,{children:m.map(e=>{let t=e.model,n=f===t;return(0,Q.jsxs)(Z.Fragment,{children:[(0,Q.jsxs)(`tr`,{className:`pws-model-row`,children:[(0,Q.jsxs)(`td`,{className:`mono`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`pws-model-expand`,"aria-expanded":n,onClick:()=>p(n?null:t),children:e.model}),e.hasUnresolvedRequestedModel&&(0,Q.jsx)(`div`,{className:`muted pws-model-attribution`,children:l(`pws.unresolvedRequestedModel`)})]}),(0,Q.jsx)(`td`,{className:`num mono`,children:Ks(e.estimatedCostUsd,u)}),(0,Q.jsx)(`td`,{className:`num mono`,children:Gs(e.totalTokens,u)}),(0,Q.jsx)(`td`,{className:`num`,children:e.requests}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`div`,{className:`pws-share-bar`,children:(0,Q.jsx)(`div`,{className:`pws-share-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})})]}),n&&(0,Q.jsx)(`tr`,{className:`pws-model-detail`,children:(0,Q.jsx)(`td`,{colSpan:5,children:(0,Q.jsxs)(`div`,{className:`pws-model-detail-grid`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:l(`pws.tokenInput`)}),(0,Q.jsxs)(`span`,{className:`mono`,children:[` `,Gs(e.inputTokens,u)]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:l(`pws.tokenOutput`)}),(0,Q.jsxs)(`span`,{className:`mono`,children:[` `,Gs(e.outputTokens,u)]})]})]})})})]},t)})})]})})]}),(0,Q.jsx)(Ic,{report:i,reading:a,onRefreshQuota:c},`${e.name}:${o??``}`)]})}function fl(e){return e===`anthropic`||e===`anthropic2`}function pl(e,t){return e===`anthropic`?!0:e!==`anthropic2`||!t?!1:Object.hasOwn(t,`anthropicOAuthInstance`)&&t.anthropicOAuthInstance===`anthropic2`&&t.adapter===`anthropic`&&t.authMode===`oauth`}var ml={oauth_organization_disabled:`accountPause.reason.organizationDisabled`,account_permission_denied:`accountPause.reason.permissionDenied`,subscription_inactive:`accountPause.reason.subscriptionInactive`,subscription_expired:`accountPause.reason.subscriptionExpired`,plan_downgraded:`accountPause.reason.planDowngraded`};function hl(e,t,n){let r=Object.hasOwn(ml,n.reason)?e(ml[n.reason]):e(`codexAuth.paused`),i=new Date(n.pausedAt);return Number.isNaN(i.getTime())?r:e(`accountPause.tooltip`,{reason:r,date:i.toLocaleString(t)})}function gl(e){if(!e)return null;let t=e.trim();return t?t.length<=4?`account-…`:`account-…${t.slice(-4)}`:null}function _l(e){return gl(e)??`account-…`}function vl(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 yl({disabled:e=!1,onIncrement:t,onDecrement:n,incrementLabel:r,decrementLabel:i}){return(0,Q.jsxs)(`div`,{className:`ocx-stepper`,role:`group`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`ocx-stepper__btn`,disabled:e,"aria-label":r,onMouseDown:e=>e.preventDefault(),onClick:t,children:(0,Q.jsx)(Je,{width:10,height:10,"aria-hidden":`true`})}),(0,Q.jsx)(`button`,{type:`button`,className:`ocx-stepper__btn`,disabled:e,"aria-label":i,onMouseDown:e=>e.preventDefault(),onClick:n,children:(0,Q.jsx)(tt,{width:10,height:10,"aria-hidden":`true`})})]})}function bl({accountLabel:e,globalThreshold:t,override:r,disabled:i=!1,inputId:a,hintText:o,onChange:s}){let c=n(),l=(0,Z.useRef)(!1),u=(0,Z.useRef)(!1),[d,f]=(0,Z.useState)(!1),p=r!==null,[m,h]=(0,Z.useState)({override:r,draft:String(r??t)});m.override!==r&&h({override:r,draft:String(r??t)});let{draft:g}=m,_=e=>h(t=>({...t,draft:e})),v=()=>h(e=>({...e,draft:String(e.override??t)})),y=i||d,b=o??c(`accountPool.autoSwitchHint`),x=(0,Z.useId)(),S=async e=>{if(!(i||u.current)){u.current=!0,f(!0);try{await s(e)}finally{v(),u.current=!1,f(!1)}}},C=async()=>{if(!p||i||u.current)return;let e=g.trim(),t=e===``?NaN:Number(e);!Number.isInteger(t)||t<0||t>100?v():t!==r&&await S(t)},w=e=>{if(i||u.current)return;let t=vl(g,e,0,100);_(t);let n=Number(t);n!==r&&S(n)};return(0,Q.jsxs)(`div`,{className:`codex-account-auto-switch`,title:b,"aria-busy":d,"aria-disabled":y,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(l.current?l.current=!1:C())},children:[(0,Q.jsx)(`label`,{className:`codex-account-auto-switch-label`,htmlFor:p?a:void 0,children:c(`accountPool.autoSwitchThreshold`)}),p&&(0,Q.jsxs)(`span`,{className:`codex-account-auto-switch-input-wrap`,children:[(0,Q.jsx)(`input`,{id:a,className:`input mono codex-auto-switch-input codex-account-auto-switch-input`,type:`number`,min:0,max:100,step:1,inputMode:`numeric`,value:g,readOnly:y,"aria-disabled":y,"aria-label":c(`accountPool.autoSwitchThresholdAria`,{email:e}),"aria-describedby":x,onChange:e=>{y||_(e.target.value)},onKeyDown:e=>{e.nativeEvent.isComposing||y||(e.key===`Enter`?(e.preventDefault(),C()):e.key===`Escape`&&(e.preventDefault(),v()))}}),(0,Q.jsx)(`span`,{className:`codex-account-auto-switch-unit`,"aria-hidden":`true`,children:`%`}),(0,Q.jsx)(yl,{disabled:i&&!d,incrementLabel:c(`codexAuth.autoSwitchThresholdInc`),decrementLabel:c(`codexAuth.autoSwitchThresholdDec`),onIncrement:()=>w(1),onDecrement:()=>w(-1)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`toggle codex-account-auto-switch-toggle ${p?`on`:``}`,disabled:i&&!d,"aria-disabled":y,"aria-pressed":p,"aria-label":c(`accountPool.autoSwitchOverrideAria`,{email:e}),"aria-describedby":x,onPointerDownCapture:()=>{l.current=!0},onPointerUp:()=>{l.current=!1},onPointerCancel:()=>{l.current=!1},onClick:()=>{l.current=!1,S(p?null:t)},children:(0,Q.jsx)(`span`,{className:`toggle-knob`})}),(0,Q.jsx)(`span`,{id:x,className:`sr-only`,children:b})]})}function xl(e){return e===`healthy`?`ok`:e===`cooldown`?`muted`:e===`reauth_required`||e===`warning`?`warn`:`muted`}function Sl(e){let t=xl(e);return t===`ok`?`badge badge-green`:t===`warn`?`badge badge-amber`:`badge badge-muted`}function Cl(e){return e===`reauth_required`}function wl(e){return!!e?.needsReauth||Cl(e?.health?.status)}function Tl(e){return e===`cooldown`}function El(e){return e===`warning`||e===`reauth_required`}function Dl(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 Ol(e,t){let n=Dl(t);return n?e(n):null}function kl(e,t,n,r){if(!r||r.status===`healthy`)return null;let i=n===`__main__`?e(`codexAuth.mainAccount`):_l(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 Al(e){let t=navigator.clipboard?.writeText?.bind(navigator.clipboard);if(t)try{return await t(e),!0}catch{}return jl(e)}function jl(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 Ml(e,t){return e(t?t===`copied`?`pws.doctorCopied`:`pws.doctorCopyUnavailable`:`pws.copyDoctor`)}function Nl(e){return[...e].some(e=>{let t=e.codePointAt(0);return t<=31||t===127})}function Pl(e,t){let n=e.trim();return n.length>80||Nl(n)?t(`prov.aliasInvalid`):null}var Fl=e=>({step:e?`oauth-waiting`:`pick`,id:``,error:``,authUrl:``,deviceCode:``,instructions:``,manualCode:``,manualCodeState:`idle`,statusNotice:``,statusTone:`ok`,flowId:null});function Il(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??``,browserLaunch:t.browserLaunch};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,browserLaunch:void 0};case`oauth-code-submitted`:return{...e,error:``,manualCode:``,manualCodeState:`waiting`,statusTone:`ok`,statusNotice:``};default:return e}}function Ll({id:e,error:t,onIdChange:r,onStartOAuth:i,onStartDeviceOAuth:a,onClose:o}){let s=n();return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`h3`,{style:{marginBottom:4},children:s(`codexAuth.addTitle`)}),(0,Q.jsx)(`p`,{className:`modal-desc`,children:s(`codexAuth.addPickDesc`)}),(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`codex-account-id-input`,children:s(`codexAuth.addIdLabel`)}),(0,Q.jsx)(`input`,{id:`codex-account-id-input`,className:`input`,placeholder:s(`codexAuth.addIdPlaceholder`),value:e,onChange:e=>r(e.target.value),style:{marginBottom:12}}),(0,Q.jsx)(`button`,{type:`button`,className:`list-row`,onClick:i,style:{marginBottom:8},children:(0,Q.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:10},children:[(0,Q.jsx)(Xe,{width:20}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`title`,children:s(`codexAuth.oauthLogin`)}),(0,Q.jsx)(`div`,{className:`sub`,children:s(`codexAuth.oauthDesc`)})]})]})}),(0,Q.jsx)(`button`,{type:`button`,className:`list-row`,onClick:a,style:{marginBottom:8},children:(0,Q.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:10},children:[(0,Q.jsx)(ut,{width:20}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`title`,children:s(`codexAuth.deviceLogin`)}),(0,Q.jsx)(`div`,{className:`sub`,children:s(`codexAuth.deviceDesc`)})]})]})}),t&&(0,Q.jsx)(`div`,{className:`notice notice-err`,style:{marginTop:8},children:t}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:o,style:{width:`100%`},children:s(`codexAuth.cancel`)})]})}var Rl=2500;function zl(){let[e,t]=(0,Z.useState)(null),n=(0,Z.useRef)(null),r=(0,Z.useRef)(0),i=(0,Z.useCallback)(()=>{n.current&&=(clearTimeout(n.current),null)},[]);return(0,Z.useEffect)(()=>i,[i]),{outcomeFor:(0,Z.useCallback)(t=>e&&Object.is(e.scope,t)?e.outcome:null,[e]),copy:(0,Z.useCallback)((e,a)=>{let o=++r.current;Al(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)},Rl))})},[i])}}function Bl(e){try{let t=new URL(e).protocol;return t===`https:`||t===`http:`}catch{return!1}}function Vl({url:e,openLabel:t}){let r=n(),{outcomeFor:i,copy:a}=zl();if(!e)return null;let o=i(e),s=r(o===`copied`?`prov.linkCopied`:o===`unavailable`?`prov.linkCopyUnavailable`:`prov.copyLink`),c=Bl(e);return(0,Q.jsxs)(`div`,{className:`login-url-block`,children:[(0,Q.jsx)(`code`,{className:`login-url-block-text`,children:e}),(0,Q.jsxs)(`div`,{className:`login-url-block-actions`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>a(e,e),children:[(0,Q.jsx)(ut,{style:{width:13,height:13},"aria-hidden":`true`}),(0,Q.jsx)(`span`,{"aria-live":`polite`,children:s})]}),c&&(0,Q.jsxs)(`a`,{href:e,target:`_blank`,rel:`noreferrer`,className:`login-url-block-open`,children:[(0,Q.jsx)(We,{style:{width:13,height:13},"aria-hidden":`true`}),` `,t??r(`prov.didntOpen`)]})]})]})}function Hl({hint:e,paste:t}){let r=n(),i=zl(),a=e.deviceCode??``,o=e.url??``;if(!a&&!o&&!e.instructions&&!t)return null;let s=i.outcomeFor(a),c=r(s===`copied`?`prov.codeCopied`:s===`unavailable`?`prov.linkCopyUnavailable`:`prov.copyCode`),l=a||e.browserLaunch===`skipped`?r(`prov.openSignInPage`):void 0,u=a&&Bl(o)?()=>{i.copy(a,a),window.open(o,`_blank`,`noopener,noreferrer`)}:null;return(0,Q.jsxs)(`div`,{className:`login-hint`,children:[e.browserLaunch===`failed`&&o&&(0,Q.jsx)(`div`,{className:`notice-warn login-hint-launch-failed`,role:`status`,children:r(`prov.browserLaunchFailed`)}),a&&(0,Q.jsxs)(`div`,{className:`login-hint-device pwi-device-code-wrap`,children:[(0,Q.jsx)(`span`,{className:`text-label`,children:r(`prov.deviceCode`)}),(0,Q.jsx)(`code`,{className:`login-hint-device-code pwi-device-code`,children:a}),(0,Q.jsx)(`button`,{type:`button`,className:u?`btn btn-ghost btn-sm`:`btn btn-primary btn-sm`,onClick:()=>i.copy(a,a),children:(0,Q.jsx)(`span`,{"aria-live":`polite`,children:c})}),u&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm login-hint-copy-open`,onClick:u,children:r(`prov.copyCodeAndOpen`)})]}),(0,Q.jsx)(Vl,{url:o,openLabel:l}),e.instructions&&(0,Q.jsx)(`div`,{className:`muted text-label`,children:e.instructions}),t&&!a&&(0,Q.jsxs)(`div`,{className:`login-hint-paste`,children:[(0,Q.jsx)(`div`,{className:`muted text-label`,children:r(`prov.pasteRedirectHint`)}),(0,Q.jsxs)(`div`,{className:`login-hint-paste-row`,children:[(0,Q.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:r(`prov.pasteRedirect`),"aria-label":r(`prov.pasteRedirect`),disabled:t.busy,className:`input text-label login-hint-paste-input`}),(0,Q.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??r(`prov.pasteSubmitting`):r(`prov.pasteSubmit`)})]}),t.message&&(0,Q.jsx)(`div`,{className:`text-label`,"aria-live":`polite`,style:{color:t.ok?`var(--accent-hover)`:`var(--amber)`},children:t.message})]})]})}function Ul({reauthAccountId:e,authUrl:t,deviceCode:r,instructions:i,browserLaunch:a,manualCode:o,manualCodeBusy:s,manualCodeWaiting:c,statusNotice:l,statusTone:u,flowId:d,error:f,onSwitchToDevice:p,onManualCodeChange:m,onSubmitManualCode:h,onClose:g}){let _=n();return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`h3`,{style:{marginBottom:4},children:_(e?`codexAuth.reauthenticate`:`codexAuth.oauthLogin`)}),(0,Q.jsx)(`p`,{className:`modal-desc`,children:_(`codexAuth.oauthWaiting`)}),(0,Q.jsx)(Hl,{hint:{url:t,deviceCode:r,instructions:i,browserLaunch:a},paste:{value:o,busy:s,disabled:s||c||!o.trim()||!d,submittingLabel:_(`codexAuth.oauthSubmittingCode`),message:``,ok:!0,onChange:m,onSubmit:h}}),l&&(0,Q.jsx)(`div`,{className:u===`warn`?`notice-warn`:`notice notice-ok`,role:`status`,"aria-live":`polite`,style:{marginTop:12},children:l}),f&&(0,Q.jsx)(`div`,{className:`notice notice-err`,style:{marginTop:12},children:f}),p&&!r&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:p,style:{width:`100%`,marginTop:8},children:_(`codexAuth.deviceLogin`)}),(0,Q.jsx)(`div`,{style:{textAlign:`center`,padding:`24px 0`},children:(0,Q.jsx)(`span`,{className:`spin`,style:{width:24,height:24}})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:g,style:{width:`100%`},children:_(`codexAuth.cancel`)})]})}var Wl=`ocx.oauth.openBrowser`;function Gl(){try{let e=window.localStorage.getItem(Wl);return e===`0`?!1:e===`1`||void 0}catch{return}}function Kl(){let e=Gl();return e===void 0?{}:{openBrowser:e}}function ql(e){try{window.localStorage.setItem(Wl,e?`1`:`0`)}catch{}}function Jl(e){return e===`started`||e===`failed`||e===`skipped`?e:void 0}function Yl(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 Xl=3e5,Zl=96e4;function Ql({apiBase:e,reauthAccountId:t,ui:n,dispatch:r,t:i}){let a=(0,Z.useRef)(!0),o=(0,Z.useRef)(0),s=(0,Z.useRef)(!1),c=(0,Z.useRef)(null),l=(0,Z.useRef)(null),u=(0,Z.useRef)(null),d=(0,Z.useRef)(null),f=(0,Z.useRef)(n.manualCodeState),p=(0,Z.useRef)(null),m=(0,Z.useRef)(null),h=(0,Z.useRef)(()=>{}),g=(0,Z.useRef)(()=>{}),_=n.manualCodeState===`submitting`,v=n.manualCodeState===`waiting`;(0,Z.useEffect)(()=>{f.current=n.manualCodeState},[n.manualCodeState]),(0,Z.useEffect)(()=>{d.current=n.flowId},[n.flowId]);let y=(0,Z.useCallback)(()=>{c.current&&=(c.current(),null),l.current&&=(clearTimeout(l.current),null),u.current?.abort(),u.current=null,s.current=!1},[]),b=(0,Z.useCallback)(()=>{r({type:`clear-manual-code`}),o.current=0},[r]),x=(0,Z.useCallback)(async()=>{b();let t=d.current;d.current=null,r({type:`set-flow-id`,flowId:null}),r({type:`set-login-hint`,authUrl:``}),y(),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,b,r,y]);(0,Z.useEffect)(()=>(a.current=!0,()=>{b(),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}),y(),t&&fetch(`${e}/api/codex-auth/login/cancel`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({flowId:t})}).catch(()=>{})}),[e,b,r,y]);let S=(0,Z.useCallback)((e,t)=>{h.current=e,g.current=t},[]),C=(0,Z.useCallback)(()=>{n.step===`oauth-waiting`&&x(),g.current()},[n.step,x]),w=(0,Z.useCallback)(async(n,m)=>{b(),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,S=()=>fetch(`${e}/api/codex-auth/login`,{signal:_.signal,method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...Kl(),...v?{device:!0}:{},...t?{id:t,reauth:!0}:p?{id:p}:{}})}),C=await S();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 S(),C.status===409){r({type:`set-error`,error:i(`codexAuth.oauthAlreadyInProgress`)});return}}let w=await vn(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,browserLaunch:Jl(w.browserLaunch)}),r({type:`set-step`,step:`oauth-waiting`}),y();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`,S=new AbortController;u.current=S,c.current=ba(async()=>{if(s.current||S.signal.aborted)return;s.current=!0;let e=AbortSignal.any([S.signal,AbortSignal.timeout(1e4)]);try{let n=await yn(await fetch(_,{signal:e}));if(!a.current||S.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(y(),b(),d.current=null,r({type:`set-flow-id`,flowId:null}),!a.current)return;h.current(Yl(n)),g.current()}else(n.status===`error`||n.status===`expired`)&&(y(),b(),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||S.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&&(b(),x(),a.current&&(t||r({type:`set-step`,step:`pick`}),r({type:`set-error`,error:i(`modal.loginTimeout`)})))},v?Zl:Xl)}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,x,b,r,t,y,i]);return(0,Z.useEffect)(()=>{t?m.current!==t&&(m.current=t,w()):m.current=null},[t,w]),{manualCodeBusy:_,manualCodeWaiting:v,bindCallbacks:S,closeModal:C,startOAuth:w,submitManualCode:(0,Z.useCallback)(async()=>{let t=d.current,s=n.manualCode.trim();if(t&&s&&!_&&!v){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,i,n.manualCode])}}function $l({apiBase:e,onClose:t,onAdded:r,reauthAccountId:i}){let a=n(),[o,s]=(0,Z.useReducer)(Il,i,Fl),c=(0,Z.useRef)(null),l=(0,Z.useRef)(null),{manualCodeBusy:u,manualCodeWaiting:d,bindCallbacks:f,closeModal:p,startOAuth:m,submitManualCode:h}=Ql({apiBase:e,reauthAccountId:i,ui:o,dispatch:s,t:a});(0,Z.useEffect)(()=>{f(r,t)},[f,r,t]),(0,Z.useEffect)(()=>{c.current=document.activeElement;let e=l.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(),()=>{c.current?.focus()}},[]);let g=(0,Z.useCallback)(e=>{e.preventDefault(),p()},[p]),_=a(i?`codexAuth.reauthenticate`:`codexAuth.addTitle`);return(0,Q.jsx)(`dialog`,{ref:l,"aria-label":_,className:`modal-overlay`,onCancel:g,children:(0,Q.jsxs)(`div`,{className:`modal-card`,style:{maxWidth:440},children:[o.step===`pick`&&(0,Q.jsx)(Ll,{id:o.id,error:o.error,onIdChange:e=>s({type:`set-id`,id:e}),onStartOAuth:()=>{m(o.id)},onStartDeviceOAuth:()=>{m(o.id,{device:!0})},onClose:p}),o.step===`oauth-waiting`&&(0,Q.jsx)(Ul,{reauthAccountId:i,authUrl:o.authUrl,deviceCode:o.deviceCode,instructions:o.instructions,browserLaunch:o.browserLaunch,manualCode:o.manualCode,manualCodeBusy:u,manualCodeWaiting:d,statusNotice:o.statusNotice,statusTone:o.statusTone,flowId:o.flowId,error:o.error,onSwitchToDevice:()=>{m(o.id,{device:!0})},onManualCodeChange:e=>s({type:`set-manual-code`,manualCode:e}),onSubmitManualCode:()=>{h()},onClose:p})]})})}var eu=[2,1,0,-1,-2],tu=new Map([[2,`accountPool.priorityFirst`],[1,`accountPool.priorityEarlier`],[0,`accountPool.priorityNormal`],[-1,`accountPool.priorityLater`],[-2,`accountPool.priorityLast`]]);function nu(e){return typeof e==`number`&&Number.isInteger(e)&&e>=-100&&e<=100?e:0}function ru(e){let t=nu(e);return t>0?`+${t}`:String(t)}function iu(e){return tu.has(e)}function au(e){return tu.get(e)??null}function ou(e,t){let n=nu(t);return e(`accountPool.priorityOption`,{name:e(au(n)??`accountPool.priorityCustom`),value:ru(n)})}var su=[`quota`,`round-robin`,`fill-first`,`reset-first`],cu=[`five-hour`,`weekly`,`max-utilization`],lu=`quota`,uu=`five-hour`,du=new Set(su),fu=new Set(cu);function pu(e){return typeof e==`string`&&du.has(e)?e:lu}function mu(e){return typeof e==`string`&&fu.has(e)?e:uu}function hu(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=100?e:1}function gu(e){let t=e.trim();if(!/^\d+$/.test(t))return null;let n=Number(t);return n>=1&&n<=100?n:null}var _u=`openai`;function vu(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:pu(r.strategy??n?.strategy),stickyLimit:hu(r.stickyLimit??n?.stickyLimit),autoSwitchThreshold:typeof i==`number`?i:null,quotaWindow:(r.quotaWindow??n?.quotaWindow)===void 0||r.quotaWindow===null?null:mu(r.quotaWindow??n?.quotaWindow),nativeMessages:fl(t)?Object.hasOwn(r,`nativeMessages`)?r.nativeMessages===!0:n?.nativeMessages??!0:null,...r.warning===`config_bookkeeping_failed`?{warning:r.warning}:{}}}function yu(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},...fl(e)&&t.nativeMessages!==void 0?{nativeMessages:t.nativeMessages}:{}}}async function bu(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?vu(await i.json(),t):null}catch{return null}}var xu=class extends Error{code=`config_save_state_unknown`;constructor(){super(`config_save_state_unknown`),this.name=`PoolSettingsSaveStateUnknownError`}};async function Su(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(yu(t,n))});if(!a.ok){if(fl(t)&&a.status===409&&(await a.json().catch(()=>null))?.code===`config_save_state_unknown`)throw new xu;return null}return vu(await a.json().catch(()=>({})),t,n)}catch(e){if(e instanceof xu)throw e;return null}}async function Cu(e,t,n=(e,t)=>fetch(e,t)){if(t.strategy===void 0&&t.stickyLimit===void 0)return{ok:!1};let r=await Su(e,_u,{strategy:t.strategy,stickyLimit:t.stickyLimit},n);return r?{ok:!0,strategy:r.strategy,stickyLimit:r.stickyLimit}:{ok:!1}}var wu=1e4;function Tu(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<=100?e:80}function Eu(e){let t=e.trim();if(!/^\d+$/.test(t))return null;let n=Number(t);return n>=1&&n<=100?n:null}function Du(e,t){return e>0?0:Number.isInteger(t)&&t>=1&&t<=100?t:80}function Ou(e,t,n,r){return n===r?e||t?`defer`:`apply`:`ignore`}function ku(e){return e&&typeof e==`object`&&e&&`autoSwitchThreshold`in e?e.autoSwitchThreshold:e}function Au(e,t,n){if(e<=0){let t=Du(e,n);return{threshold:t,lastEnabled:t}}return{threshold:0,lastEnabled:Eu(t)??Du(0,n)}}async function ju(e,t,n=(e,t)=>fetch(e,t),r=wu){return!Number.isInteger(t)||t<0||t>100?!1:await Su(e,_u,{threshold:t},(e,t)=>n(e,t),{signal:AbortSignal.timeout(r)})!==null}var Mu={short:90,long:98};function Nu(e){let t=e&&typeof e==`object`?e:void 0,n=e=>typeof e==`number`&&Number.isFinite(e)&&e>=0&&e<=100;return t&&n(t.short)&&n(t.long)?{short:t.short,long:t.long}:{...Mu}}var Pu=3e4,Fu=new Map;function Iu(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<=100?e:null}function Lu(e,t=!0){let n=Fu.get(e),[r,i]=(0,Z.useState)(()=>n?.accounts??[]),a=Wt(xr(e,`codex`),[e],async t=>br(await fetch(`${e}/api/usage?range=30d&surface=codex`,{signal:t}),`account usage load failed`),{enabled:t}),[o,s]=(0,Z.useState)(()=>n?.activeId??null),[c,l]=(0,Z.useState)(()=>n==null?`loading`:`ready`),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(null),[m,h]=(0,Z.useState)(null),[g,_]=(0,Z.useState)(null),[v,y]=(0,Z.useState)(null),[b,x]=(0,Z.useState)(null),[S,C]=(0,Z.useState)(!1),[w,T]=(0,Z.useState)(null),[E,D]=(0,Z.useState)(0),[O,k]=(0,Z.useState)(()=>n!=null),[A,j]=(0,Z.useState)(0),N=(0,Z.useRef)(null);N.current===null&&(N.current=new Set);let P=(0,Z.useRef)(null),F=(0,Z.useRef)(0),I=(0,Z.useRef)(null),L=(0,Z.useRef)(null);L.current===null&&(L.current=new Set);let R=(0,Z.useRef)(null),z=(0,Z.useRef)(null),B=(0,Z.useRef)(!!n?.accounts.length),V=(0,Z.useRef)(n!=null),H=(0,Z.useRef)(null),U=(0,Z.useRef)(null),ee=(0,Z.useRef)(null),W=(0,Z.useRef)(!1),te=(0,Z.useCallback)(e=>(L.current.add(e),()=>{L.current.delete(e)}),[]),G=(0,Z.useCallback)(()=>ku(R.current?.value),[]),ne=(0,Z.useCallback)(()=>R.current?.value,[]),K=(0,Z.useCallback)(async(t=!1,n={})=>{let r=++F.current,a=n.validatePending===!0,o=Fu.get(e)?.accounts.length??0,c=M(a?3e4+12e4*Math.max(1,o):2e4),u=a?{}:null;u&&(N.current.add(u),j(N.current.size)),D(e=>e+1);try{let n=[...L.current],o=new Map;for(let e of n)o.set(e,e.beginActiveRead());!t&&!V.current&&l(`loading`);let u=null,f,p=(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 F.current===r&&(u=(o.accounts??[]).map(e=>{let t=e.isMain?`main`:e.logLabel,n=at(e.quota);return{...e,...t?{logLabel:t}:{},priority:nu(e.priority),autoSwitchThresholdOverride:Iu(e.autoSwitchThresholdOverride),quotaAutoRefresh:e.quotaAutoRefresh??{...n,fiveHourEnabled:!1,weeklyEnabled:!1}}}),i(u),B.current=u.length>0,V.current=!0,l(`ready`),d(!1)),!0}catch{return!1}})(),m=(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(F.current===r){let e=i.activeCodexAccountId??null,t=I.current;t&&t.staleReadsRemaining>0&&e!==t.id?--t.staleReadsRemaining:(I.current=null,f=e,s(e)),R.current={value:i},T(typeof i.pinnedAccountId==`string`?i.pinnedAccountId:null);for(let e of n)e.acceptActiveRead(i,o.get(e))}return!0}catch{if(F.current===r)for(let e of n)e.rejectActiveRead();return!1}})(),[h,g]=await Promise.all([p,m]);if(F.current!==r)return!1;if(h){l(`ready`),V.current=!0;let t=Fu.get(e);return Fu.set(e,{accounts:u??t?.accounts??[],activeId:f===void 0?t?.activeId??null:f}),g}return V.current||l(`error`),d(!0),!1}finally{c.clear(),u&&(N.current.delete(u),j(N.current.size)),D(e=>Math.max(0,e-1)),k(!0)}},[e]);(0,Z.useEffect)(()=>{t&&P.current!==e&&(P.current=e,Promise.resolve().then(()=>{K()}))},[e,t,K]);let re=r.some(e=>e.hasCredential&&!e.quota);(0,Z.useEffect)(()=>{if(!t||!re||A>0)return;let e=[350,900,2e3].map(e=>window.setTimeout(()=>{N.current.size===0&&K(!1)},e));return()=>{for(let t of e)window.clearTimeout(t)}},[t,re,A,K]),(0,Z.useEffect)(()=>{if(!(!t||A>0))return ba(()=>{N.current.size===0&&K()},Pu)},[t,K,A]);let q=(0,Z.useCallback)(()=>{let e={};return N.current.add(e),j(N.current.size),e},[]),J=(0,Z.useCallback)(e=>{N.current.delete(e)&&j(N.current.size)},[]),Y=(0,Z.useCallback)(async(t,n)=>{if(z.current||U.current)return{ok:!1,reason:`busy`};z.current=t??`__main__`,p(t??`__main__`);let r=`request`;try{let i=await fetch(`${e}/api/codex-auth/active`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({accountId:t,...n?{expectedPinnedAccountId:n.expectedPinnedAccountId}:{}})});if(!i.ok)throw(await i.json().catch(()=>({}))).code===`account_pin_changed`&&(r=`pin_changed`),Error(`account switch failed`);let a=(await i.json().catch(()=>({}))).activeCodexAccountId??t;return I.current={id:a??null,staleReadsRemaining:1},s(a??null),T(a??null),K(),{ok:!0,activeId:a??null}}catch{return t===null&&(I.current=null,await K()),{ok:!1,reason:r}}finally{z.current=null,p(null)}},[e,K]),ie=(0,Z.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 K(),{ok:!0}):{ok:!1,reason:`request`}}catch{return{ok:!1,reason:`request`}}},[e,K]),X=(0,Z.useCallback)(async(t,n)=>{if(H.current)return{ok:!1,reason:`busy`};H.current={accountId:t},h(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;I.current={id:e,staleReadsRemaining:1},s(e)}return n&&T(e=>e===t?null:e),K(),{ok:!0}}catch{return{ok:!1,reason:`request`}}finally{H.current=null,h(null)}},[e,K]),ae=(0,Z.useCallback)(async(t,n)=>{if(U.current||z.current)return{ok:!1,reason:`busy`};U.current={accountId:t},_(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=nu((a&&typeof a==`object`?a:{}).priority??n);return i(e=>e.map(e=>e.id===t||t===`__main__`&&e.isMain?{...e,priority:o}:e)),T(null),I.current=null,K(),{ok:!0}}catch{return{ok:!1,reason:`request`}}finally{U.current=null,_(null)}},[e,K]),oe=(0,Z.useCallback)(async(t,n)=>{if(ee.current)return{ok:!1,reason:`busy`};ee.current={accountId:t},y(t);try{let r=await fetch(`${e}/api/codex-auth/auto-switch`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:t,threshold:n})});if(!r.ok)return{ok:!1,reason:`request`};let a=await r.json().catch(()=>({})),o=a&&typeof a==`object`?a:{},s=Object.prototype.hasOwnProperty.call(o,`autoSwitchThresholdOverride`)?Iu(o.autoSwitchThresholdOverride):n;return i(e=>e.map(e=>e.id===t||t===`__main__`&&e.isMain?{...e,autoSwitchThresholdOverride:s}:e)),K(),{ok:!0}}catch{return{ok:!1,reason:`request`}}finally{ee.current=null,y(null)}},[e,K]),se=(0,Z.useCallback)(async(t,n,r)=>{if(W.current)return{ok:!1,reason:`busy`};W.current=!0,x(t);try{return(await fetch(`${e}/api/codex-auth/accounts/credits`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)})).ok?(i(e=>e.map(r)),K(),{ok:!0}):{ok:!1,reason:`request`}}catch{return{ok:!1,reason:`request`}}finally{W.current=!1,x(null)}},[e,K]),ce=(0,Z.useCallback)((e,t)=>se(e,{id:e,creditsAfterLimit:t},n=>n.id===e||e===`__main__`&&n.isMain?{...n,creditsAfterLimit:t}:n),[se]),le=(0,Z.useCallback)(e=>se(`*`,{all:e},t=>({...t,creditsAfterLimit:e})),[se]),ue=(0,Z.useCallback)(async()=>{if(H.current)return{ok:!1,reason:`busy`};H.current=`bulk`,C(!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;I.current={id:e,staleReadsRemaining:1},s(e)}return T(e=>e!==null&&a.has(e)?null:e),K(),{ok:!0,pausedCount:r.pausedCount??a.size}}catch{return{ok:!1,reason:`request`}}finally{H.current=null,C(!1)}},[e,K]),de=(0,Z.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=Yl(await n.json().catch(()=>({})));return await K(),{ok:!0,...r}}catch{return{ok:!1,reason:`request`}}},[e,K]),fe=(0,Z.useCallback)(async()=>await K()?{ok:!0}:{ok:!1,reason:`reload`},[K]),pe=o&&o!==`__main__`?r.find(e=>e.id===o):null,me=r.find(e=>e.isMain),he=pe??me,ge=!he?.paused&&wl(he);return{accounts:(0,Z.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:E>0,refreshFailed:u,initialLoading:!O,switchingId:f,pauseUpdatingId:m,priorityUpdatingId:g,autoSwitchUpdatingId:v,creditsAfterLimitUpdatingId:b,pausingExhausted:S,activeNeedsReauth:ge,activePinnedId:w,load:K,switchAccount:Y,setAccountPaused:X,setAccountPriority:ae,setAccountAutoSwitchThreshold:oe,setAccountCreditsAfterLimit:ce,setAllCreditsAfterLimit:le,pauseExhaustedAccounts:ue,saveAlias:ie,removeAccount:de,syncAfterAccountAdded:fe,pauseRefresh:q,resumeRefresh:J,subscribeLoadObserver:te,readLastThreshold:G,readLastActive:ne}}function Ru(e,t,n,r,i){let[a,o]=(0,Z.useState)({apiBase:e,busy:!1}),s=(0,Z.useRef)(null),c=(0,Z.useRef)(0),l=(0,Z.useEffectEvent)((e,t)=>{i?.onRead(e,t)}),u=i?.revision??0,d=(0,Z.useRef)(null);a.apiBase!==e&&o({apiBase:e,busy:!1});let f=a.apiBase===e?a.visible:void 0,p=a.apiBase===e&&a.busy;return(0,Z.useEffect)(()=>{let e=new AbortController;return s.current=e,()=>{e.abort(),d.current?.abort(),d.current=null}},[e]),(0,Z.useEffect)(()=>{let t=new AbortController,n=M(15e3),r=c.current,i=fetch(`${e}/api/settings`,{signal:n.signal}).then(e=>{if(!e.ok)throw Error(`read`);return e.json()});return l(i,t.signal),i.then(n=>{t.signal.aborted||d.current||c.current!==r||n&&typeof n==`object`&&`showCodexCredits`in n&&typeof n.showCodexCredits==`boolean`&&o({apiBase:e,visible:n.showCodexCredits,busy:!1})}).catch(()=>{}).finally(()=>n.clear()),()=>{t.abort(),n.controller.abort(),n.clear()}},[e,u]),{visible:f,busy:p,toggle:async()=>{let i=s.current;if(f===void 0||p||d.current||!i||i.signal.aborted)return;let a=new AbortController;d.current=a;let l=M(15e3),u=()=>l.controller.abort();a.signal.addEventListener(`abort`,u,{once:!0});let m=()=>s.current===i&&!i.signal.aborted,h=!f;c.current+=1,o({apiBase:e,visible:h,busy:!0});try{let i;try{let t=await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"content-type":`application/json`},signal:l.signal,body:JSON.stringify({showCodexCredits:h})});if(!t.ok)throw Error(`save`);let n=await t.json();if(typeof n?.showCodexCredits!=`boolean`)throw Error(`shape`);i=n.showCodexCredits}catch{m()&&(o({apiBase:e,visible:f,busy:!1}),n(r(`codexAuth.creditsToggleFailed`),`err`));return}if(!m())return;o({apiBase:e,visible:i,busy:!0}),n(r(i?`codexAuth.creditsShown`:`codexAuth.creditsHidden`),`ok`);try{let e=await t(!0);m()&&!e&&n(r(`codexAuth.quotaRefreshFailed`),`err`)}catch{m()&&n(r(`codexAuth.quotaRefreshFailed`),`err`)}}finally{l.clear(),a.signal.removeEventListener(`abort`,u),m()&&(d.current=null,o(e=>({...e,busy:!1})))}}}}var zu=`https://auth.openai.com/codex/device`,Bu=2e3,Vu=1e4,Hu=new Set([`identity_mismatch`,`credential_changed`,`native_main_unavailable`,`device_authorization_failed`,`publication_failed`,`reconciliation_failed`,`flow_in_progress`]);function Uu(e){return typeof e==`string`&&Hu.has(e)?e:`request_failed`}function Wu(e){return typeof e==`string`&&e.startsWith(zu)?e:``}function Gu(e){return typeof e==`string`&&/^[A-Z0-9-]{1,16}$/i.test(e)?e:``}function Ku(e,t){let[n,r]=(0,Z.useState)({phase:`idle`}),i=(0,Z.useRef)(null),a=(0,Z.useRef)(null),o=(0,Z.useRef)(null),s=(0,Z.useRef)(null),c=(0,Z.useRef)(!1),l=(0,Z.useCallback)(()=>{s.current?.abort(),s.current=null},[]),u=(0,Z.useCallback)(async()=>{let n=i.current;if(!n)l(),r({phase:`idle`});else{a.current=n;try{let a=await fetch(`${e}/api/codex-auth/main/reauth-device?flowId=${encodeURIComponent(n)}`,{method:`DELETE`}),o=await a.json().catch(()=>({}));if(c.current||i.current!==n)return;if(a.status===404&&o.code===`unknown_flow`){l(),i.current=null,r({phase:`failed`,code:`request_failed`});return}if(!a.ok||o.status!==`cancelled`&&o.status!==`succeeded`&&o.status!==`failed`)throw Error();l(),i.current=null,r(o.status===`failed`?{phase:`failed`,code:Uu(o.code)}:{phase:o.status}),o.status===`succeeded`&&t()}catch{if(c.current||i.current!==n)return;r(e=>{if(c.current||i.current!==n)return e;let t=e.phase===`pending`||e.phase===`committing`?e:o.current;return t?.flowId===n?{...t,cancelFailed:!0}:e})}}},[e,t,l]),d=(0,Z.useCallback)(async()=>{l(),i.current=null,a.current=null,o.current=null;let n=new AbortController;s.current=n;let u=()=>!n.signal.aborted&&!c.current&&s.current===n;r({phase:`starting`});let d;try{let t=await fetch(`${e}/api/codex-auth/main/reauth-device`,{method:`POST`,signal:n.signal}),i=await t.json().catch(()=>({}));if(!u())return;if(!t.ok){r({phase:`failed`,code:Uu(i.code)});return}if(typeof i.flowId!=`string`||!i.flowId){r({phase:`failed`,code:`request_failed`});return}d=i.flowId}catch{u()&&r({phase:`failed`,code:`request_failed`});return}let f=d;i.current=f;let p=``,m=``;for(;u();){if(i.current!==f)return;try{let s=await fetch(`${e}/api/codex-auth/main/reauth-device?flowId=${encodeURIComponent(f)}`,{signal:AbortSignal.any([n.signal,AbortSignal.timeout(Vu)])}),c=await s.json().catch(()=>({}));if(!u()||i.current!==f)return;if(!s.ok){if(s.status===404&&c.code===`unknown_flow`){l(),i.current=null,r({phase:`failed`,code:`request_failed`});return}let e=a.current===f;if(r(t=>!u()||i.current!==f||(t.phase===`pending`||t.phase===`committing`)&&t.flowId===f&&(e||t.cancelFailed)?t:{phase:`failed`,code:Uu(c.code)}),!e)return}else if(p=Wu(c.verificationUrl)||p,m=Gu(c.deviceCode)||m,c.status===`pending`||c.status===`committing`){let e={phase:c.status,flowId:f,verificationUrl:p,deviceCode:m};o.current=e,r(t=>(t.phase===`pending`||t.phase===`committing`)&&t.flowId===f&&t.cancelFailed?{...e,cancelFailed:!0}:e)}else if(c.status===`succeeded`){i.current=null,r({phase:`succeeded`}),t();return}else if(c.status===`cancelled`){i.current=null,r({phase:`cancelled`});return}else if(c.status===`failed`){i.current=null,r({phase:`failed`,code:Uu(c.code)});return}}catch{if(!u()||i.current!==f)return}await new Promise(e=>setTimeout(e,Bu))}},[e,t,l]);return(0,Z.useEffect)(()=>(c.current=!1,()=>{c.current=!0,l();let t=i.current;i.current=null,t&&fetch(`${e}/api/codex-auth/main/reauth-device?flowId=${encodeURIComponent(t)}`,{method:`DELETE`}).catch(()=>{})}),[e,l]),{state:n,start:d,cancel:u}}var qu={en:{"nativeMain.title":`Native main login`,"nativeMain.manage":`Manage main login`,"nativeMain.close":`Close main login manager`,"nativeMain.separate":`These controls change the native Codex login, not the account selected for the next Pool request.`,"nativeMain.home":`Effective CODEX_HOME`,"nativeMain.current":`Registered active profile`,"nativeMain.unregistered":`Not registered`,"nativeMain.physicalHint":`This home belongs to the OpenCodex server, which may be a different computer. The backend verifies the physical login before any switch.`,"nativeMain.busyOther":`Another native login operation is running. Finish or cancel it first.`,"nativeMain.working":`Working…`,"nativeMain.changed":`The home, active profile or recovery state changed. Review the refreshed state and confirm again.`,"nativeMain.error":`The result could not be confirmed. A missing response does not mean the original login was restored.`,"nativeMain.doctorHint":`Run {cmd} on the server for details.`,"nativeMain.saved":`Current login saved as a profile. The physical login was not changed.`,"nativeMain.lastResult":`Last confirmed result`,"nativeMain.restart":`Login change completed. The server requires a native Codex restart.`,"nativeMain.done":`Operation completed. The server did not request a native Codex restart.`,"nativeMain.refreshFailed":`Could not refresh all account information. A completed change has not been undone. Refresh before another operation.`,"nativeMain.refresh":`Refresh status`,"nativeMain.unsupported":`This credential store is not supported. Native profile management requires the file credential store.`,"nativeMain.recoveryHint":`An interrupted transaction needs recovery. Recover finishes reconciliation; restore rolls back the pending transaction. Neither action runs until you confirm.`,"nativeMain.recover":`Recover interrupted change`,"nativeMain.rollback":`Restore pending transaction`,"nativeMain.empty":`No native profiles are registered yet. Save the current login first.`,"nativeMain.active":`Active`,"nativeMain.switchTo":`Switch native login to {label}`,"nativeMain.switch":`Switch`,"nativeMain.restore":`Return to previously displayed: {label}`,"nativeMain.restoreHint":`This shortcut selects the profile shown before your last switch, not a server-verified transaction history. It is kept only on this page.`,"nativeMain.label":`Profile label`,"nativeMain.save":`Save current as profile`,"nativeMain.saveHint":`For an already registered active login, saving updates its label. It does not add a new login.`,"nativeMain.confirmHint":`This changes only the native login in the home below. Close native Codex on that computer first. Pool strategy, membership, provider keys and task/history data are not edited by this panel.`,"nativeMain.stepClose":`Close native Codex on the server computer for the displayed CODEX_HOME. Keep it closed until you have checked the result.`,"nativeMain.stepConfirm":`Select the checkbox below to confirm Codex is closed, then confirm the change.`,"nativeMain.stepResult":`Wait for the result and the updated active profile, then follow the instructions to reopen Codex.`,"nativeMain.reopenHint":`Check the updated active profile, then reopen native Codex on the server computer with the displayed CODEX_HOME. Follow any restart requirement shown here.`,"nativeMain.retryHint":`Refresh the status and review the active profile. To retry a login change, select the action again and confirm that Codex is closed. Nothing is retried automatically.`,"nativeMain.errorCodexBusy":`Native Codex is still running on the server computer. Close it for the displayed CODEX_HOME before retrying.`,"nativeMain.errorProcessCheck":`The server could not verify whether native Codex is running. Check that Codex is closed on that computer and inspect the server diagnostics before retrying.`,"nativeMain.errorRequests":`Main-account requests are still running or draining. Wait for them to finish before retrying.`,"nativeMain.errorBusy":`Another native-login operation is running. Wait for it to finish before trying again.`,"nativeMain.errorAuth":`The current native login could not be read or verified against its saved profile. Inspect the server diagnostics before another change.`,"nativeMain.errorKeyStore":`The saved profile or operating-system key store could not be opened. Inspect the key-store and profile diagnostics on the server before another change.`,"nativeMain.errorStorage":`The server cannot safely access the login folder or profile storage. Check the server diagnostics before another change.`,"nativeMain.errorProfile":`The saved profile state cannot be used for this action. Refresh and review the profile list; inspect the diagnostics if the problem persists.`,"nativeMain.errorRecovery":`Profile storage or an interrupted transaction needs attention. Refresh status and inspect the server diagnostics. Use recovery controls only when the panel offers them.`,"nativeMain.errorRolledBack":`The server reports that the switch failed and the original login was restored. Review the refreshed active profile before another attempt.`,"nativeMain.stopped":`I have stopped native Codex using this CODEX_HOME and understand that a restart may be required.`,"nativeMain.cancel":`Cancel`,"nativeMain.confirm":`Confirm native-login change`,"nativeMain.unavailable":`Profile changes are unavailable. Check the diagnostic code before continuing.`},ko:{"nativeMain.title":`실제 Codex 메인 로그인`,"nativeMain.manage":`메인 로그인 관리`,"nativeMain.close":`메인 로그인 관리 닫기`,"nativeMain.separate":`이 기능은 실제 Codex 로그인을 변경합니다. 다음 요청에 사용할 Pool 계정 선택과는 다릅니다.`,"nativeMain.home":`실제 적용되는 CODEX_HOME`,"nativeMain.current":`등록된 활성 프로필`,"nativeMain.unregistered":`등록되지 않음`,"nativeMain.physicalHint":`이 경로는 OpenCodex 서버의 경로이며, 현재 컴퓨터와 다를 수 있습니다. 서버는 전환 전에 실제 로그인을 검증합니다.`,"nativeMain.busyOther":`다른 메인 로그인 작업이 진행 중입니다. 먼저 완료하거나 취소해 주세요.`,"nativeMain.working":`처리 중…`,"nativeMain.changed":`적용 경로, 활성 프로필 또는 복구 상태가 바뀌었습니다. 갱신된 정보를 검토하고 다시 확인해 주세요.`,"nativeMain.error":`결과를 확인하지 못했습니다. 응답이 없다고 해서 원래 로그인이 복원되었다는 뜻은 아닙니다.`,"nativeMain.doctorHint":`자세한 내용은 서버에서 {cmd} 명령을 실행해 확인하세요.`,"nativeMain.saved":`현재 로그인을 프로필로 저장했습니다. 실제 로그인은 변경하지 않았습니다.`,"nativeMain.lastResult":`마지막으로 확인된 결과`,"nativeMain.restart":`로그인 변경을 완료했습니다. 서버는 Codex 재시작이 필요하다고 응답했습니다.`,"nativeMain.done":`작업을 완료했습니다. 서버는 Codex 재시작이 필요하지 않다고 응답했습니다.`,"nativeMain.refreshFailed":`일부 계정 정보를 갱신하지 못했습니다. 완료된 변경이 취소된 것은 아닙니다. 다음 작업 전에 새로고침해 주세요.`,"nativeMain.refresh":`상태 새로고침`,"nativeMain.unsupported":`이 자격 증명 저장 방식은 지원하지 않습니다. 파일 저장 방식이 필요합니다.`,"nativeMain.recoveryHint":`중단된 전환에 복구가 필요합니다. 복구는 상태 정리를 진행하고, 되돌리기는 미완료 전환을 원복합니다. 확인 전에는 실행되지 않습니다.`,"nativeMain.recover":`중단된 전환 복구`,"nativeMain.rollback":`미완료 전환 되돌리기`,"nativeMain.empty":`등록된 메인 프로필이 없습니다. 현재 로그인을 먼저 저장해 주세요.`,"nativeMain.active":`활성`,"nativeMain.switchTo":`실제 로그인을 {label}(으)로 전환`,"nativeMain.switch":`전환`,"nativeMain.restore":`이전에 표시된 프로필로 돌아가기: {label}`,"nativeMain.restoreHint":`마지막 전환 전에 표시된 프로필을 선택하는 바로가기입니다. 서버가 검증한 거래 이력은 아니며 이 페이지에만 보관됩니다.`,"nativeMain.label":`프로필 이름`,"nativeMain.save":`현재 로그인을 프로필로 저장`,"nativeMain.saveHint":`현재 로그인이 이미 등록되어 있으면 이름을 변경합니다. 새 로그인은 추가하지 않습니다.`,"nativeMain.confirmHint":`아래 경로의 실제 로그인만 변경합니다. 해당 컴퓨터의 Codex를 먼저 종료해 주세요. 이 패널은 Pool 전략·구성, 공급자 키, 작업·기록 데이터를 수정하지 않습니다.`,"nativeMain.stepClose":`서버 컴퓨터에서 표시된 CODEX_HOME을 사용하는 실제 Codex를 종료합니다. 결과를 확인할 때까지 종료 상태를 유지합니다.`,"nativeMain.stepConfirm":`아래 체크박스를 선택해 Codex가 종료되었음을 확인한 다음 변경을 확인합니다.`,"nativeMain.stepResult":`작업 결과와 갱신된 활성 프로필을 기다린 다음 안내에 따라 Codex를 다시 엽니다.`,"nativeMain.reopenHint":`갱신된 활성 프로필을 확인한 다음 서버 컴퓨터에서 표시된 CODEX_HOME을 사용하는 실제 Codex를 다시 엽니다. 여기에 재시작이 필요하다고 표시되면 해당 안내를 따릅니다.`,"nativeMain.retryHint":`상태를 새로고침하고 활성 프로필을 확인합니다. 로그인 변경을 다시 시도하려면 작업을 다시 선택하고 Codex가 종료되었음을 확인해야 합니다. 자동으로 다시 시도하지 않습니다.`,"nativeMain.errorCodexBusy":`서버 컴퓨터에서 Codex가 아직 실행 중입니다. 다시 시도하기 전에 표시된 CODEX_HOME을 사용하는 Codex를 종료하세요.`,"nativeMain.errorProcessCheck":`서버가 Codex 실행 여부를 확인하지 못했습니다. 해당 컴퓨터에서 Codex가 종료됐는지 확인하고 서버 진단을 살펴본 뒤 다시 시도하세요.`,"nativeMain.errorRequests":`메인 계정 요청이 실행 중이거나 종료를 기다리고 있습니다. 요청이 끝난 뒤 다시 시도하세요.`,"nativeMain.errorBusy":`다른 실제 로그인 작업이 진행 중입니다. 해당 작업이 끝날 때까지 기다린 다음 다시 시도해야 합니다.`,"nativeMain.errorAuth":`현재 실제 로그인을 읽거나 저장된 프로필과 일치하는지 확인하지 못했습니다. 다음 변경 전에 서버 진단을 확인하세요.`,"nativeMain.errorKeyStore":`저장된 프로필 또는 운영체제 키 저장소를 열지 못했습니다. 다음 변경 전에 서버에서 키 저장소와 프로필 진단을 확인하세요.`,"nativeMain.errorStorage":`서버가 로그인 폴더 또는 프로필 저장소에 안전하게 접근할 수 없습니다. 다음 변경 전에 서버 진단을 확인해야 합니다.`,"nativeMain.errorProfile":`저장된 프로필 상태로 이 작업을 수행할 수 없습니다. 프로필 목록을 새로고침하고 확인하세요. 문제가 계속되면 진단을 확인하세요.`,"nativeMain.errorRecovery":`프로필 저장소 또는 중단된 전환을 확인해야 합니다. 상태를 새로고침하고 서버 진단을 확인하세요. 패널에 복구 기능이 표시될 때만 사용하세요.`,"nativeMain.errorRolledBack":`서버는 전환이 실패하여 원래 로그인을 복원했다고 응답했습니다. 다시 시도하기 전에 갱신된 활성 프로필을 확인하세요.`,"nativeMain.stopped":`이 CODEX_HOME을 사용하는 Codex를 종료했으며, 변경 후 재시작이 필요할 수 있음을 확인했습니다.`,"nativeMain.cancel":`취소`,"nativeMain.confirm":`메인 로그인 변경 확인`,"nativeMain.unavailable":`프로필을 변경할 수 없습니다. 계속하기 전에 진단 코드를 확인하세요.`},de:{"nativeMain.title":`Native Codex-Hauptanmeldung`,"nativeMain.manage":`Hauptanmeldung verwalten`,"nativeMain.close":`Anmeldungsverwaltung schließen`,"nativeMain.separate":`Diese Aktionen ändern die native Codex-Anmeldung, nicht das Konto für die nächste Pool-Anfrage.`,"nativeMain.home":`Wirksames CODEX_HOME`,"nativeMain.current":`Registriertes aktives Profil`,"nativeMain.unregistered":`Nicht registriert`,"nativeMain.physicalHint":`Dieser Pfad gehört zum OpenCodex-Server, möglicherweise auf einem anderen Computer. Das Backend prüft die tatsächliche Anmeldung vor jedem Wechsel.`,"nativeMain.busyOther":`Eine andere native Anmeldung läuft. Beenden oder abbrechen Sie sie zuerst.`,"nativeMain.working":`Wird verarbeitet…`,"nativeMain.changed":`Pfad, aktives Profil oder Wiederherstellungsstatus haben sich geändert. Prüfen und bestätigen Sie den neuen Stand.`,"nativeMain.error":`Das Ergebnis konnte nicht bestätigt werden. Eine fehlende Antwort bedeutet nicht, dass die ursprüngliche Anmeldung wiederhergestellt wurde.`,"nativeMain.doctorHint":`Führen Sie {cmd} auf dem Server aus, um Details zu sehen.`,"nativeMain.saved":`Aktuelle Anmeldung als Profil gespeichert. Die tatsächliche Anmeldung wurde nicht geändert.`,"nativeMain.lastResult":`Zuletzt bestätigtes Ergebnis`,"nativeMain.restart":`Anmeldung geändert. Der Server verlangt einen Neustart von nativem Codex.`,"nativeMain.done":`Vorgang abgeschlossen. Der Server verlangt keinen Codex-Neustart.`,"nativeMain.refreshFailed":`Nicht alle Kontodaten konnten aktualisiert werden. Eine abgeschlossene Änderung wurde nicht zurückgenommen. Aktualisieren Sie vor weiteren Aktionen.`,"nativeMain.refresh":`Status aktualisieren`,"nativeMain.unsupported":`Dieser Anmeldespeicher wird nicht unterstützt. Native Profile benötigen den dateibasierten Speicher.`,"nativeMain.recoveryHint":`Eine unterbrochene Transaktion muss wiederhergestellt werden. Wiederherstellen gleicht den Zustand ab; Zurücksetzen nimmt die ausstehende Transaktion zurück. Beide benötigen Ihre Bestätigung.`,"nativeMain.recover":`Unterbrochenen Wechsel wiederherstellen`,"nativeMain.rollback":`Ausstehende Transaktion zurücksetzen`,"nativeMain.empty":`Noch keine nativen Profile. Speichern Sie zuerst die aktuelle Anmeldung.`,"nativeMain.active":`Aktiv`,"nativeMain.switchTo":`Native Anmeldung zu {label} wechseln`,"nativeMain.switch":`Wechseln`,"nativeMain.restore":`Zum zuvor angezeigten Profil: {label}`,"nativeMain.restoreHint":`Diese Verknüpfung wählt das vor Ihrem letzten Wechsel angezeigte Profil, keinen servergeprüften Transaktionsverlauf. Sie bleibt nur auf dieser Seite erhalten.`,"nativeMain.label":`Profilname`,"nativeMain.save":`Aktuelle Anmeldung als Profil speichern`,"nativeMain.saveHint":`Ist die aktive Anmeldung bereits registriert, wird ihr Name geändert. Es wird keine neue Anmeldung hinzugefügt.`,"nativeMain.confirmHint":`Nur die native Anmeldung im folgenden Pfad wird geändert. Schließen Sie dort zuerst Codex. Pool-Strategie, Mitgliedschaft, Anbieterschlüssel sowie Aufgaben und Verlauf werden nicht bearbeitet.`,"nativeMain.stepClose":`Schließen Sie natives Codex auf dem Servercomputer für das angezeigte CODEX_HOME. Lassen Sie es geschlossen, bis Sie das Ergebnis geprüft haben.`,"nativeMain.stepConfirm":`Aktivieren Sie das Kontrollkästchen unten, um zu bestätigen, dass Codex geschlossen ist, und bestätigen Sie dann die Änderung.`,"nativeMain.stepResult":`Warten Sie auf das Ergebnis und das aktualisierte aktive Profil und folgen Sie dann den Anweisungen zum erneuten Öffnen von Codex.`,"nativeMain.reopenHint":`Prüfen Sie das aktualisierte aktive Profil und öffnen Sie dann natives Codex auf dem Servercomputer mit dem angezeigten CODEX_HOME. Beachten Sie alle hier angezeigten Neustartanforderungen.`,"nativeMain.retryHint":`Aktualisieren Sie den Status und prüfen Sie das aktive Profil. Um einen Anmeldewechsel erneut zu versuchen, wählen Sie die Aktion erneut und bestätigen Sie, dass Codex geschlossen ist. Nichts wird automatisch erneut versucht.`,"nativeMain.errorCodexBusy":`Natives Codex läuft noch auf dem Servercomputer. Schließen Sie es für das angezeigte CODEX_HOME vor einem erneuten Versuch.`,"nativeMain.errorProcessCheck":`Der Server konnte nicht prüfen, ob natives Codex läuft. Prüfen Sie auf diesem Computer, dass Codex beendet ist, und lesen Sie vor einem erneuten Versuch die Serverdiagnose.`,"nativeMain.errorRequests":`Anfragen des Hauptkontos laufen noch oder werden abgearbeitet. Warten Sie vor einem erneuten Versuch auf deren Abschluss.`,"nativeMain.errorBusy":`Ein anderer Vorgang für die native Anmeldung läuft. Warten Sie, bis er abgeschlossen ist, bevor Sie es erneut versuchen.`,"nativeMain.errorAuth":`Die aktuelle native Anmeldung konnte nicht gelesen oder mit dem gespeicherten Profil abgeglichen werden. Prüfen Sie vor einer weiteren Änderung die Serverdiagnose.`,"nativeMain.errorKeyStore":`Das gespeicherte Profil oder der Schlüsselspeicher des Betriebssystems konnte nicht geöffnet werden. Prüfen Sie vor einer weiteren Änderung die Schlüssel- und Profildiagnose auf dem Server.`,"nativeMain.errorStorage":`Der Server kann nicht sicher auf den Anmeldeordner oder den Profilspeicher zugreifen. Prüfen Sie vor einer weiteren Änderung die Serverdiagnose.`,"nativeMain.errorProfile":`Der gespeicherte Profilzustand erlaubt diese Aktion nicht. Aktualisieren und prüfen Sie die Profilliste; lesen Sie bei anhaltenden Problemen die Diagnose.`,"nativeMain.errorRecovery":`Der Profilspeicher oder eine unterbrochene Transaktion benötigt Aufmerksamkeit. Aktualisieren Sie den Status und prüfen Sie die Serverdiagnose. Nutzen Sie Wiederherstellungsaktionen nur, wenn das Panel sie anbietet.`,"nativeMain.errorRolledBack":`Der Server meldet, dass der Wechsel fehlgeschlagen ist und die ursprüngliche Anmeldung wiederhergestellt wurde. Prüfen Sie vor einem erneuten Versuch das aktualisierte aktive Profil.`,"nativeMain.stopped":`Ich habe natives Codex für dieses CODEX_HOME beendet und weiß, dass ein Neustart nötig sein kann.`,"nativeMain.cancel":`Abbrechen`,"nativeMain.confirm":`Änderung der Hauptanmeldung bestätigen`,"nativeMain.unavailable":`Profiländerungen sind nicht verfügbar. Prüfen Sie zuerst den Diagnosecode.`},fr:{"nativeMain.title":`Connexion principale native Codex`,"nativeMain.manage":`Gérer la connexion principale`,"nativeMain.close":`Fermer la gestion de connexion`,"nativeMain.separate":`Ces commandes modifient la connexion native Codex, pas le compte choisi pour la prochaine requête du Pool.`,"nativeMain.home":`CODEX_HOME effectif`,"nativeMain.current":`Profil actif enregistré`,"nativeMain.unregistered":`Non enregistré`,"nativeMain.physicalHint":`Ce chemin appartient au serveur OpenCodex, qui peut être un autre ordinateur. Le serveur vérifie la connexion réelle avant tout changement.`,"nativeMain.busyOther":`Une autre opération de connexion est en cours. Terminez-la ou annulez-la.`,"nativeMain.working":`Traitement…`,"nativeMain.changed":`Le chemin, le profil actif ou la récupération a changé. Vérifiez les informations actualisées et confirmez à nouveau.`,"nativeMain.error":`Le résultat n’a pas pu être confirmé. L’absence de réponse ne signifie pas que la connexion d’origine a été restaurée.`,"nativeMain.doctorHint":`Exécutez {cmd} sur le serveur pour obtenir des détails.`,"nativeMain.saved":`Connexion actuelle enregistrée comme profil. La connexion réelle reste inchangée.`,"nativeMain.lastResult":`Dernier résultat confirmé`,"nativeMain.restart":`Connexion modifiée. Le serveur demande un redémarrage de Codex natif.`,"nativeMain.done":`Opération terminée. Le serveur ne demande pas de redémarrage de Codex.`,"nativeMain.refreshFailed":`Certaines informations n’ont pas pu être actualisées. Une modification terminée n’a pas été annulée. Actualisez avant une autre opération.`,"nativeMain.refresh":`Actualiser l’état`,"nativeMain.unsupported":`Ce stockage d’identifiants n’est pas pris en charge. Les profils natifs exigent le stockage dans un fichier.`,"nativeMain.recoveryHint":`Une transaction interrompue nécessite une récupération. Récupérer réconcilie l’état ; restaurer annule la transaction en attente. Les deux actions exigent une confirmation.`,"nativeMain.recover":`Récupérer le changement interrompu`,"nativeMain.rollback":`Restaurer la transaction en attente`,"nativeMain.empty":`Aucun profil natif enregistré. Enregistrez d’abord la connexion actuelle.`,"nativeMain.active":`Actif`,"nativeMain.switchTo":`Utiliser {label} comme connexion native`,"nativeMain.switch":`Changer`,"nativeMain.restore":`Revenir au profil affiché précédemment : {label}`,"nativeMain.restoreHint":`Ce raccourci sélectionne le profil affiché avant votre dernier changement, et non un historique de transactions vérifié par le serveur. Il reste uniquement sur cette page.`,"nativeMain.label":`Nom du profil`,"nativeMain.save":`Enregistrer la connexion actuelle`,"nativeMain.saveHint":`Si la connexion active est déjà enregistrée, son nom est mis à jour. Aucune nouvelle connexion n’est ajoutée.`,"nativeMain.confirmHint":`Seule la connexion native du chemin ci-dessous change. Fermez d’abord Codex sur cet ordinateur. Ce panneau ne modifie ni la stratégie ni les membres du Pool, les clés fournisseur, les tâches ou l’historique.`,"nativeMain.stepClose":`Fermez Codex natif sur l’ordinateur du serveur pour le CODEX_HOME affiché. Gardez-le fermé jusqu’à ce que vous ayez vérifié le résultat.`,"nativeMain.stepConfirm":`Cochez la case ci-dessous pour confirmer que Codex est fermé, puis confirmez la modification.`,"nativeMain.stepResult":`Attendez le résultat et le profil actif actualisé, puis suivez les instructions pour rouvrir Codex.`,"nativeMain.reopenHint":`Vérifiez le profil actif actualisé, puis rouvrez Codex natif sur l’ordinateur du serveur avec le CODEX_HOME affiché. Respectez toute exigence de redémarrage indiquée ici.`,"nativeMain.retryHint":`Actualisez l’état et vérifiez le profil actif. Pour réessayer un changement de connexion, sélectionnez à nouveau l’action et confirmez que Codex est fermé. Aucune action n’est réessayée automatiquement.`,"nativeMain.errorCodexBusy":`Codex natif fonctionne encore sur l’ordinateur du serveur. Fermez-le pour le CODEX_HOME affiché avant de réessayer.`,"nativeMain.errorProcessCheck":`Le serveur n’a pas pu vérifier si Codex natif fonctionne. Vérifiez son arrêt sur cet ordinateur et consultez le diagnostic du serveur avant de réessayer.`,"nativeMain.errorRequests":`Des requêtes du compte principal sont encore en cours ou en cours de terminaison. Attendez leur fin avant de réessayer.`,"nativeMain.errorBusy":`Une autre opération de connexion native est en cours. Attendez qu’elle se termine avant de réessayer.`,"nativeMain.errorAuth":`La connexion native actuelle n’a pas pu être lue ou vérifiée avec le profil enregistré. Consultez le diagnostic du serveur avant toute autre modification.`,"nativeMain.errorKeyStore":`Le profil enregistré ou le trousseau du système n’a pas pu être ouvert. Consultez leurs diagnostics sur le serveur avant toute autre modification.`,"nativeMain.errorStorage":`Le serveur ne peut pas accéder en toute sécurité au dossier de connexion ou au stockage des profils. Consultez le diagnostic du serveur avant toute autre modification.`,"nativeMain.errorProfile":`L’état du profil enregistré ne permet pas cette action. Actualisez et vérifiez la liste ; consultez le diagnostic si le problème persiste.`,"nativeMain.errorRecovery":`Le stockage des profils ou une transaction interrompue nécessite une intervention. Actualisez l’état et consultez le diagnostic du serveur. Utilisez la récupération uniquement si le panneau la propose.`,"nativeMain.errorRolledBack":`Le serveur indique que le changement a échoué et que la connexion initiale a été restaurée. Vérifiez le profil actif actualisé avant un nouvel essai.`,"nativeMain.stopped":`J’ai arrêté Codex natif utilisant ce CODEX_HOME et comprends qu’un redémarrage peut être nécessaire.`,"nativeMain.cancel":`Annuler`,"nativeMain.confirm":`Confirmer le changement de connexion`,"nativeMain.unavailable":`La modification des profils est indisponible. Vérifiez le code de diagnostic avant de continuer.`},zh:{"nativeMain.title":`原生 Codex 主登录`,"nativeMain.manage":`管理主登录`,"nativeMain.close":`关闭主登录管理`,"nativeMain.separate":`这些操作更改原生 Codex 登录,不会选择下一次 Pool 请求使用的账号。`,"nativeMain.home":`实际使用的 CODEX_HOME`,"nativeMain.current":`已注册的活动配置`,"nativeMain.unregistered":`尚未注册`,"nativeMain.physicalHint":`此路径属于 OpenCodex 服务器,可能位于另一台计算机。后端会在切换前验证实际登录。`,"nativeMain.busyOther":`另一项原生登录操作正在进行。请先完成或取消。`,"nativeMain.working":`处理中…`,"nativeMain.changed":`路径、活动配置或恢复状态已变化。请查看刷新后的状态并重新确认。`,"nativeMain.error":`无法确认结果。未收到响应并不意味着原来的登录已恢复。`,"nativeMain.doctorHint":`在服务器上运行 {cmd} 可查看详细信息。`,"nativeMain.saved":`已将当前登录保存为配置。实际登录未改变。`,"nativeMain.lastResult":`最近确认的结果`,"nativeMain.restart":`登录已更改。服务器要求重启原生 Codex。`,"nativeMain.done":`操作已完成。服务器未要求重新启动 Codex。`,"nativeMain.refreshFailed":`部分账号信息刷新失败。已完成的更改并未撤销。请在继续操作前刷新。`,"nativeMain.refresh":`刷新状态`,"nativeMain.unsupported":`不支持此凭据存储方式。原生配置管理需要文件凭据存储。`,"nativeMain.recoveryHint":`中断的事务需要恢复。恢复会完成状态协调;还原会回滚待处理事务。两项操作均需确认后才执行。`,"nativeMain.recover":`恢复中断的更改`,"nativeMain.rollback":`还原待处理事务`,"nativeMain.empty":`尚无原生配置。请先保存当前登录。`,"nativeMain.active":`活动`,"nativeMain.switchTo":`将原生登录切换为 {label}`,"nativeMain.switch":`切换`,"nativeMain.restore":`返回之前显示的配置档案:{label}`,"nativeMain.restoreHint":`此快捷方式选择上次切换前显示的配置档案,并非服务器验证的事务历史记录,仅保留在此页面。`,"nativeMain.label":`配置名称`,"nativeMain.save":`将当前登录保存为配置`,"nativeMain.saveHint":`如果当前活动登录已注册,保存会更新其名称,不会添加新登录。`,"nativeMain.confirmHint":`仅更改以下路径中的原生登录。请先关闭该计算机上的 Codex。此面板不会编辑 Pool 策略、成员、供应商密钥或任务与历史数据。`,"nativeMain.stepClose":`在服务器计算机上关闭使用所示 CODEX_HOME 的原生 Codex。在检查结果之前,请保持 Codex 关闭。`,"nativeMain.stepConfirm":`勾选下方复选框,确认 Codex 已关闭,然后确认更改。`,"nativeMain.stepResult":`等待结果和更新后的活动配置,然后按照提示重新打开 Codex。`,"nativeMain.reopenHint":`检查更新后的活动配置,然后在服务器计算机上重新打开使用所示 CODEX_HOME 的原生 Codex。请遵循此处显示的任何重启要求。`,"nativeMain.retryHint":`刷新状态并检查活动配置。要重试登录更改,请重新选择操作并确认 Codex 已关闭。不会自动重试任何操作。`,"nativeMain.errorCodexBusy":`服务器计算机上的原生 Codex 仍在运行。重试前请关闭使用所示 CODEX_HOME 的 Codex。`,"nativeMain.errorProcessCheck":`服务器无法验证原生 Codex 是否在运行。重试前请确认该计算机上的 Codex 已关闭,并检查服务器诊断。`,"nativeMain.errorRequests":`主账号请求仍在运行或等待结束。请等待请求结束后再重试。`,"nativeMain.errorBusy":`另一项原生登录操作正在运行。请等待其完成后再试。`,"nativeMain.errorAuth":`无法读取当前原生登录或验证其是否匹配保存的配置。再次更改前请检查服务器诊断。`,"nativeMain.errorKeyStore":`无法打开保存的配置或操作系统密钥存储。再次更改前请检查服务器上的密钥存储和配置诊断。`,"nativeMain.errorStorage":`服务器无法安全访问登录文件夹或配置存储。再次更改前,请检查服务器诊断。`,"nativeMain.errorProfile":`保存的配置状态无法用于此操作。请刷新并检查配置列表;若问题持续,请检查诊断。`,"nativeMain.errorRecovery":`配置存储或中断的事务需要处理。请刷新状态并检查服务器诊断。仅在面板提供恢复功能时使用。`,"nativeMain.errorRolledBack":`服务器报告切换失败且原登录已恢复。再次尝试前请检查刷新的活动配置。`,"nativeMain.stopped":`我已停止使用此 CODEX_HOME 的原生 Codex,并了解之后可能需要重新启动。`,"nativeMain.cancel":`取消`,"nativeMain.confirm":`确认更改原生登录`,"nativeMain.unavailable":`目前无法更改配置档案。请先检查诊断代码。`},"zh-TW":{"nativeMain.title":`原生 Codex 主登入`,"nativeMain.manage":`管理主登入`,"nativeMain.close":`關閉主登入管理`,"nativeMain.separate":`這些操作會變更原生 Codex 登入,不會選擇下一次 Pool 請求使用的帳號。`,"nativeMain.home":`實際使用的 CODEX_HOME`,"nativeMain.current":`已註冊的作用中設定檔`,"nativeMain.unregistered":`尚未註冊`,"nativeMain.physicalHint":`此路徑屬於 OpenCodex 伺服器,可能位於另一台電腦。後端會在切換前驗證實際登入。`,"nativeMain.busyOther":`另一項原生登入操作正在進行。請先完成或取消。`,"nativeMain.working":`處理中…`,"nativeMain.changed":`路徑、作用中設定檔或復原狀態已變更。請查看更新後的狀態並再次確認。`,"nativeMain.error":`無法確認結果。未收到回應並不代表原本的登入已還原。`,"nativeMain.doctorHint":`在伺服器上執行 {cmd} 可查看詳細資訊。`,"nativeMain.saved":`已將目前登入儲存為設定檔。實際登入未變更。`,"nativeMain.lastResult":`最近確認的結果`,"nativeMain.restart":`登入已變更。伺服器要求重新啟動原生 Codex。`,"nativeMain.done":`操作已完成。伺服器未要求重新啟動 Codex。`,"nativeMain.refreshFailed":`部分帳號資訊更新失敗。已完成的變更並未撤銷。請在繼續操作前重新整理。`,"nativeMain.refresh":`重新整理狀態`,"nativeMain.unsupported":`不支援此憑證儲存方式。原生設定檔管理需要檔案憑證儲存。`,"nativeMain.recoveryHint":`中斷的交易需要復原。復原會完成狀態協調;還原會回復待處理的交易。兩項操作都需確認後才執行。`,"nativeMain.recover":`復原中斷的變更`,"nativeMain.rollback":`還原待處理交易`,"nativeMain.empty":`尚無原生設定檔。請先儲存目前登入。`,"nativeMain.active":`作用中`,"nativeMain.switchTo":`將原生登入切換為 {label}`,"nativeMain.switch":`切換`,"nativeMain.restore":`返回先前顯示的設定檔:{label}`,"nativeMain.restoreHint":`此捷徑選擇上次切換前顯示的設定檔,並非伺服器驗證的交易歷史紀錄,僅保留於此頁面。`,"nativeMain.label":`設定檔名稱`,"nativeMain.save":`將目前登入儲存為設定檔`,"nativeMain.saveHint":`若目前登入已註冊,儲存會更新名稱,不會新增登入。`,"nativeMain.confirmHint":`僅變更以下路徑中的原生登入。請先關閉該電腦上的 Codex。此面板不會編輯 Pool 策略、成員、供應商金鑰或工作與歷史資料。`,"nativeMain.stepClose":`在伺服器電腦上關閉使用所示 CODEX_HOME 的原生 Codex。在檢查結果之前,請保持 Codex 關閉。`,"nativeMain.stepConfirm":`勾選下方核取方塊,確認 Codex 已關閉,然後確認變更。`,"nativeMain.stepResult":`等待結果和更新後的作用中設定檔,然後依照指示重新開啟 Codex。`,"nativeMain.reopenHint":`檢查更新後的作用中設定檔,然後在伺服器電腦上重新開啟使用所示 CODEX_HOME 的原生 Codex。請遵循此處顯示的任何重新啟動要求。`,"nativeMain.retryHint":`重新整理狀態並檢查作用中設定檔。若要重試登入變更,請重新選擇操作並確認 Codex 已關閉。不會自動重試任何操作。`,"nativeMain.errorCodexBusy":`伺服器電腦上的原生 Codex 仍在執行。重試前請關閉使用所示 CODEX_HOME 的 Codex。`,"nativeMain.errorProcessCheck":`伺服器無法驗證原生 Codex 是否在執行。重試前請確認該電腦上的 Codex 已關閉,並檢查伺服器診斷。`,"nativeMain.errorRequests":`主帳號請求仍在執行或等待結束。請等待請求結束後再重試。`,"nativeMain.errorBusy":`另一項原生登入操作正在執行。請等待其完成後再試。`,"nativeMain.errorAuth":`無法讀取目前的原生登入或驗證其是否符合已儲存的設定檔。再次變更前請檢查伺服器診斷。`,"nativeMain.errorKeyStore":`無法開啟已儲存的設定檔或作業系統金鑰儲存區。再次變更前請檢查伺服器上的金鑰儲存區和設定檔診斷。`,"nativeMain.errorStorage":`伺服器無法安全存取登入資料夾或設定檔儲存區。再次變更前,請檢查伺服器診斷。`,"nativeMain.errorProfile":`已儲存的設定檔狀態無法用於此操作。請重新整理並檢查設定檔清單;若問題持續,請檢查診斷。`,"nativeMain.errorRecovery":`設定檔儲存區或中斷的交易需要處理。請重新整理狀態並檢查伺服器診斷。僅在面板提供復原功能時使用。`,"nativeMain.errorRolledBack":`伺服器回報切換失敗且原登入已還原。再次嘗試前請檢查更新的作用中設定檔。`,"nativeMain.stopped":`我已停止使用此 CODEX_HOME 的原生 Codex,並了解之後可能需要重新啟動。`,"nativeMain.cancel":`取消`,"nativeMain.confirm":`確認變更原生登入`,"nativeMain.unavailable":`目前無法變更設定檔。請先檢查診斷代碼。`},ru:{"nativeMain.title":`Основной вход в Codex`,"nativeMain.manage":`Управление основным входом`,"nativeMain.close":`Закрыть управление входом`,"nativeMain.separate":`Эти действия меняют вход самого Codex, а не аккаунт для следующего запроса Pool.`,"nativeMain.home":`Фактический CODEX_HOME`,"nativeMain.current":`Зарегистрированный активный профиль`,"nativeMain.unregistered":`Не зарегистрирован`,"nativeMain.physicalHint":`Этот путь относится к серверу OpenCodex, возможно на другом компьютере. Сервер проверяет фактический вход перед переключением.`,"nativeMain.busyOther":`Выполняется другая операция входа. Сначала завершите или отмените её.`,"nativeMain.working":`Обработка…`,"nativeMain.changed":`Путь, активный профиль или состояние восстановления изменились. Проверьте обновлённые данные и подтвердите снова.`,"nativeMain.error":`Не удалось подтвердить результат. Отсутствие ответа не означает, что исходный вход был восстановлен.`,"nativeMain.doctorHint":`Выполните {cmd} на сервере, чтобы увидеть подробности.`,"nativeMain.saved":`Текущий вход сохранён как профиль. Фактический вход не изменён.`,"nativeMain.lastResult":`Последний подтверждённый результат`,"nativeMain.restart":`Вход изменён. Сервер требует перезапуска нативного Codex.`,"nativeMain.done":`Операция завершена. Сервер не требует перезапуска Codex.`,"nativeMain.refreshFailed":`Не все данные аккаунтов обновлены. Завершённое изменение не отменено. Обновите состояние перед следующей операцией.`,"nativeMain.refresh":`Обновить состояние`,"nativeMain.unsupported":`Этот способ хранения учётных данных не поддерживается. Требуется файловое хранилище.`,"nativeMain.recoveryHint":`Прерванная транзакция требует восстановления. Восстановление согласует состояние, а откат отменяет незавершённую транзакцию. Оба действия требуют подтверждения.`,"nativeMain.recover":`Восстановить прерванное изменение`,"nativeMain.rollback":`Откатить незавершённую транзакцию`,"nativeMain.empty":`Профилей пока нет. Сначала сохраните текущий вход.`,"nativeMain.active":`Активен`,"nativeMain.switchTo":`Переключить вход Codex на {label}`,"nativeMain.switch":`Переключить`,"nativeMain.restore":`Вернуться к ранее показанному профилю: {label}`,"nativeMain.restoreHint":`Этот ярлык выбирает профиль, показанный перед последним переключением, а не подтверждённую сервером историю транзакций. Он хранится только на этой странице.`,"nativeMain.label":`Название профиля`,"nativeMain.save":`Сохранить текущий вход`,"nativeMain.saveHint":`Если активный вход уже зарегистрирован, обновляется его название. Новый вход не добавляется.`,"nativeMain.confirmHint":`Изменится только вход Codex по указанному пути. Сначала закройте Codex на том компьютере. Панель не меняет стратегию и состав Pool, ключи провайдеров, задачи или историю.`,"nativeMain.stepClose":`Закройте нативный Codex на серверном компьютере, где он использует указанный CODEX_HOME. Не открывайте его, пока не проверите результат.`,"nativeMain.stepConfirm":`Установите флажок ниже, чтобы подтвердить, что Codex закрыт, затем подтвердите изменение.`,"nativeMain.stepResult":`Дождитесь результата и обновлённого активного профиля, затем следуйте инструкциям, чтобы снова открыть Codex.`,"nativeMain.reopenHint":`Проверьте обновлённый активный профиль, затем снова откройте нативный Codex на серверном компьютере с указанным CODEX_HOME. Соблюдайте все указанные здесь требования к перезапуску.`,"nativeMain.retryHint":`Обновите состояние и проверьте активный профиль. Чтобы повторить смену входа, выберите действие снова и подтвердите, что Codex закрыт. Никакие действия не повторяются автоматически.`,"nativeMain.errorCodexBusy":`Нативный Codex всё ещё работает на компьютере сервера. Перед повтором закройте Codex, использующий указанный CODEX_HOME.`,"nativeMain.errorProcessCheck":`Сервер не смог проверить, работает ли нативный Codex. Перед повтором проверьте его остановку на этом компьютере и диагностику сервера.`,"nativeMain.errorRequests":`Запросы основного аккаунта ещё выполняются или завершаются. Дождитесь их окончания перед повтором.`,"nativeMain.errorBusy":`Выполняется другая операция нативного входа. Дождитесь её завершения, прежде чем повторить попытку.`,"nativeMain.errorAuth":`Не удалось прочитать текущий нативный вход или сверить его с сохранённым профилем. Перед новым изменением проверьте диагностику сервера.`,"nativeMain.errorKeyStore":`Не удалось открыть сохранённый профиль или системное хранилище ключей. Перед новым изменением проверьте их диагностику на сервере.`,"nativeMain.errorStorage":`Сервер не может безопасно получить доступ к папке входа или хранилищу профилей. Перед следующим изменением проверьте диагностику сервера.`,"nativeMain.errorProfile":`Состояние сохранённого профиля не подходит для этого действия. Обновите и проверьте список; если проблема остаётся, изучите диагностику.`,"nativeMain.errorRecovery":`Хранилище профилей или прерванная транзакция требуют внимания. Обновите состояние и проверьте диагностику сервера. Используйте восстановление только когда панель его предлагает.`,"nativeMain.errorRolledBack":`Сервер сообщает, что переключение не удалось и исходный вход восстановлен. Перед повтором проверьте обновлённый активный профиль.`,"nativeMain.stopped":`Я остановил Codex, использующий этот CODEX_HOME, и понимаю, что может потребоваться перезапуск.`,"nativeMain.cancel":`Отмена`,"nativeMain.confirm":`Подтвердить изменение входа`,"nativeMain.unavailable":`Изменение профилей недоступно. Перед продолжением проверьте диагностический код.`},ja:{"nativeMain.title":`ネイティブ Codex メインログイン`,"nativeMain.manage":`メインログインを管理`,"nativeMain.close":`ログイン管理を閉じる`,"nativeMain.separate":`この操作は Codex 本体のログインを変更します。次の Pool リクエストに使うアカウントの選択とは異なります。`,"nativeMain.home":`適用される CODEX_HOME`,"nativeMain.current":`登録済みの有効なプロファイル`,"nativeMain.unregistered":`未登録`,"nativeMain.physicalHint":`これは OpenCodex サーバーのパスであり、別のコンピューターの場合があります。切り替え前にサーバーが実際のログインを検証します。`,"nativeMain.busyOther":`別のログイン操作が実行中です。先に完了またはキャンセルしてください。`,"nativeMain.working":`処理中…`,"nativeMain.changed":`パス、有効なプロファイル、または復旧状態が変わりました。更新された情報を確認し、再度承認してください。`,"nativeMain.error":`結果を確認できませんでした。応答がないことは、元のログインが復元されたことを意味しません。`,"nativeMain.doctorHint":`詳細はサーバーで {cmd} を実行して確認してください。`,"nativeMain.saved":`現在のログインをプロファイルとして保存しました。実際のログインは変更していません。`,"nativeMain.lastResult":`最後に確認された結果`,"nativeMain.restart":`ログインを変更しました。サーバーはネイティブ Codex の再起動を要求しています。`,"nativeMain.done":`操作が完了しました。サーバーは Codex の再起動を要求していません。`,"nativeMain.refreshFailed":`一部のアカウント情報を更新できませんでした。完了した変更は取り消されていません。次の操作前に更新してください。`,"nativeMain.refresh":`状態を更新`,"nativeMain.unsupported":`この認証情報の保存方式には対応していません。ファイル方式が必要です。`,"nativeMain.recoveryHint":`中断された処理の復旧が必要です。復旧は状態を整合させ、復元は未完了の変更を戻します。どちらも確認後に実行されます。`,"nativeMain.recover":`中断された変更を復旧`,"nativeMain.rollback":`未完了の変更を復元`,"nativeMain.empty":`登録されたプロファイルがありません。まず現在のログインを保存してください。`,"nativeMain.active":`有効`,"nativeMain.switchTo":`ネイティブログインを {label} に切り替える`,"nativeMain.switch":`切り替え`,"nativeMain.restore":`以前表示されていたプロファイルに戻る: {label}`,"nativeMain.restoreHint":`最後の切り替え前に表示されていたプロファイルを選ぶショートカットです。サーバーが検証した取引履歴ではなく、このページだけに保持されます。`,"nativeMain.label":`プロファイル名`,"nativeMain.save":`現在のログインを保存`,"nativeMain.saveHint":`現在のログインが登録済みの場合は名前を更新します。新しいログインは追加しません。`,"nativeMain.confirmHint":`以下のパスの Codex ログインだけを変更します。そのコンピューターの Codex を先に終了してください。Pool の戦略・構成、プロバイダーのキー、タスクや履歴は編集しません。`,"nativeMain.stepClose":`サーバーのコンピューターで、表示された CODEX_HOME を使用するネイティブ Codex を終了してください。結果を確認するまで終了したままにしてください。`,"nativeMain.stepConfirm":`下のチェックボックスを選択して Codex が終了していることを確認し、その後で変更を確定してください。`,"nativeMain.stepResult":`結果と更新されたアクティブプロファイルを待ち、その後で案内に従って Codex を再度開いてください。`,"nativeMain.reopenHint":`更新されたアクティブプロファイルを確認し、サーバーのコンピューターで表示された CODEX_HOME を使用するネイティブ Codex を再度開いてください。ここに再起動が必要と表示された場合は、その案内に従ってください。`,"nativeMain.retryHint":`状態を更新し、アクティブプロファイルを確認してください。ログイン変更を再試行するには、操作を再度選択し、Codex が終了していることを確認してください。自動では再試行しません。`,"nativeMain.errorCodexBusy":`サーバーのコンピューターでネイティブ Codex がまだ動作しています。再試行の前に、表示された CODEX_HOME を使う Codex を終了してください。`,"nativeMain.errorProcessCheck":`サーバーはネイティブ Codex の動作状態を確認できませんでした。そのコンピューターで Codex が終了していることとサーバー診断を確認してから再試行してください。`,"nativeMain.errorRequests":`メインアカウントのリクエストが実行中、または終了待ちです。完了してから再試行してください。`,"nativeMain.errorBusy":`別のネイティブログイン操作が実行中です。完了するまで待ってから再試行してください。`,"nativeMain.errorAuth":`現在のネイティブログインを読み取るか、保存されたプロファイルと照合することができませんでした。次の変更前にサーバー診断を確認してください。`,"nativeMain.errorKeyStore":`保存されたプロファイルまたは OS のキーストアを開けませんでした。次の変更前にサーバーのキーストアとプロファイルの診断を確認してください。`,"nativeMain.errorStorage":`サーバーがログインフォルダーまたはプロファイル保存先に安全にアクセスできません。次の変更前にサーバー診断を確認してください。`,"nativeMain.errorProfile":`保存されたプロファイルの状態ではこの操作を実行できません。一覧を更新して確認し、問題が続く場合は診断を確認してください。`,"nativeMain.errorRecovery":`プロファイル保存先または中断された処理への対応が必要です。状態を更新し、サーバー診断を確認してください。復旧操作はパネルに表示される場合のみ使用してください。`,"nativeMain.errorRolledBack":`サーバーは切り替えに失敗し、元のログインを復元したと報告しています。再試行の前に更新されたアクティブプロファイルを確認してください。`,"nativeMain.stopped":`この CODEX_HOME を使う Codex を終了し、変更後に再起動が必要な場合があることを確認しました。`,"nativeMain.cancel":`キャンセル`,"nativeMain.confirm":`ログインの変更を確認`,"nativeMain.unavailable":`プロファイルを変更できません。続行する前に診断コードを確認してください。`},tr:{"nativeMain.title":`Yerel Codex ana oturumu`,"nativeMain.manage":`Ana oturumu yönet`,"nativeMain.close":`Oturum yönetimini kapat`,"nativeMain.separate":`Bu işlemler sonraki Pool isteğinin hesabını değil, yerel Codex oturumunu değiştirir.`,"nativeMain.home":`Geçerli CODEX_HOME`,"nativeMain.current":`Kayıtlı etkin profil`,"nativeMain.unregistered":`Kayıtlı değil`,"nativeMain.physicalHint":`Bu yol OpenCodex sunucusuna aittir; başka bir bilgisayarda olabilir. Sunucu her geçişten önce gerçek oturumu doğrular.`,"nativeMain.busyOther":`Başka bir yerel oturum işlemi sürüyor. Önce tamamlayın veya iptal edin.`,"nativeMain.working":`İşleniyor…`,"nativeMain.changed":`Yol, etkin profil veya kurtarma durumu değişti. Güncel durumu inceleyip yeniden onaylayın.`,"nativeMain.error":`Sonuç doğrulanamadı. Yanıt alınamaması, önceki girişin geri yüklendiği anlamına gelmez.`,"nativeMain.doctorHint":`Ayrıntılar için sunucuda {cmd} komutunu çalıştırın.`,"nativeMain.saved":`Geçerli oturum profil olarak kaydedildi. Gerçek oturum değiştirilmedi.`,"nativeMain.lastResult":`Son doğrulanan sonuç`,"nativeMain.restart":`Giriş değiştirildi. Sunucu yerel Codex’in yeniden başlatılmasını gerektiriyor.`,"nativeMain.done":`İşlem tamamlandı. Sunucu Codex uygulamasının yeniden başlatılmasını istemedi.`,"nativeMain.refreshFailed":`Tüm hesap bilgileri yenilenemedi. Tamamlanan değişiklik geri alınmadı. Sonraki işlemden önce yenileyin.`,"nativeMain.refresh":`Durumu yenile`,"nativeMain.unsupported":`Bu kimlik bilgisi deposu desteklenmiyor. Yerel profiller dosya tabanlı depo gerektirir.`,"nativeMain.recoveryHint":`Kesilen işlem kurtarma gerektiriyor. Kurtarma durumu uzlaştırır; geri yükleme bekleyen işlemi geri alır. Her iki işlem de onay gerektirir.`,"nativeMain.recover":`Kesilen değişikliği kurtar`,"nativeMain.rollback":`Bekleyen işlemi geri al`,"nativeMain.empty":`Henüz yerel profil yok. Önce geçerli oturumu kaydedin.`,"nativeMain.active":`Etkin`,"nativeMain.switchTo":`Yerel oturumu {label} profiline geçir`,"nativeMain.switch":`Geçiş yap`,"nativeMain.restore":`Önceden görüntülenen profile dön: {label}`,"nativeMain.restoreHint":`Bu kısayol son geçişinizden önce görüntülenen profili seçer; sunucu tarafından doğrulanmış işlem geçmişi değildir. Yalnızca bu sayfada tutulur.`,"nativeMain.label":`Profil adı`,"nativeMain.save":`Geçerli oturumu profil olarak kaydet`,"nativeMain.saveHint":`Etkin oturum zaten kayıtlıysa adı güncellenir. Yeni bir oturum eklenmez.`,"nativeMain.confirmHint":`Yalnızca aşağıdaki yoldaki yerel oturum değişir. Önce o bilgisayarda Codex uygulamasını kapatın. Bu panel Pool stratejisini ve üyelerini, sağlayıcı anahtarlarını, görevleri veya geçmişi değiştirmez.`,"nativeMain.stepClose":`Sunucu bilgisayarında gösterilen CODEX_HOME’u kullanan yerel Codex’i kapatın. Sonucu kontrol edene kadar kapalı tutun.`,"nativeMain.stepConfirm":`Codex’in kapalı olduğunu doğrulamak için aşağıdaki onay kutusunu işaretleyin, ardından değişikliği onaylayın.`,"nativeMain.stepResult":`Sonucu ve güncellenmiş etkin profili bekleyin, ardından Codex’i yeniden açma talimatlarını izleyin.`,"nativeMain.reopenHint":`Güncellenmiş etkin profili kontrol edin, ardından sunucu bilgisayarında gösterilen CODEX_HOME ile yerel Codex’i yeniden açın. Burada gösterilen yeniden başlatma gerekliliklerine uyun.`,"nativeMain.retryHint":`Durumu yenileyin ve etkin profili kontrol edin. Bir giriş değişikliğini tekrar denemek için işlemi yeniden seçin ve Codex’in kapalı olduğunu doğrulayın. Hiçbir işlem otomatik olarak tekrar denenmez.`,"nativeMain.errorCodexBusy":`Yerel Codex sunucu bilgisayarında hâlâ çalışıyor. Tekrar denemeden önce gösterilen CODEX_HOME için Codex’i kapatın.`,"nativeMain.errorProcessCheck":`Sunucu yerel Codex’in çalışıp çalışmadığını doğrulayamadı. Tekrar denemeden önce o bilgisayarda Codex’in kapalı olduğunu ve sunucu tanılamasını kontrol edin.`,"nativeMain.errorRequests":`Ana hesap istekleri hâlâ çalışıyor veya tamamlanmayı bekliyor. Tekrar denemeden önce bitmelerini bekleyin.`,"nativeMain.errorBusy":`Başka bir yerel giriş işlemi çalışıyor. Tekrar denemeden önce bitmesini bekleyin.`,"nativeMain.errorAuth":`Mevcut yerel giriş okunamadı veya kayıtlı profille doğrulanamadı. Başka bir değişiklikten önce sunucu tanılamasını inceleyin.`,"nativeMain.errorKeyStore":`Kayıtlı profil veya işletim sistemi anahtar deposu açılamadı. Başka bir değişiklikten önce sunucudaki anahtar deposu ve profil tanılamasını inceleyin.`,"nativeMain.errorStorage":`Sunucu giriş klasörüne veya profil deposuna güvenli bir şekilde erişemiyor. Başka bir değişiklikten önce sunucu tanılamasını kontrol edin.`,"nativeMain.errorProfile":`Kayıtlı profil durumu bu işlem için kullanılamıyor. Listeyi yenileyip inceleyin; sorun sürerse tanılamayı inceleyin.`,"nativeMain.errorRecovery":`Profil deposu veya kesintiye uğramış bir işlem dikkat gerektiriyor. Durumu yenileyip sunucu tanılamasını inceleyin. Kurtarma kontrollerini yalnızca panel sunduğunda kullanın.`,"nativeMain.errorRolledBack":`Sunucu geçişin başarısız olduğunu ve önceki girişin geri yüklendiğini bildiriyor. Tekrar denemeden önce yenilenmiş etkin profili kontrol edin.`,"nativeMain.stopped":`Bu CODEX_HOME ile çalışan Codex uygulamasını durdurdum ve yeniden başlatma gerekebileceğini anlıyorum.`,"nativeMain.cancel":`İptal`,"nativeMain.confirm":`Yerel oturum değişikliğini onayla`,"nativeMain.unavailable":`Profil değişiklikleri kullanılamıyor. Devam etmeden önce tanılama kodunu kontrol edin.`},vi:{"nativeMain.title":`Đăng nhập Codex gốc`,"nativeMain.manage":`Quản lý đăng nhập chính`,"nativeMain.close":`Đóng trình quản lý đăng nhập chính`,"nativeMain.separate":`Các điều khiển này thay đổi đăng nhập Codex gốc, không phải tài khoản được chọn cho yêu cầu Pool tiếp theo.`,"nativeMain.home":`CODEX_HOME đang có hiệu lực`,"nativeMain.current":`Hồ sơ đang hoạt động đã đăng ký`,"nativeMain.unregistered":`Chưa đăng ký`,"nativeMain.physicalHint":`Thư mục home này thuộc về máy chủ OpenCodex, có thể là một máy tính khác. Backend xác minh đăng nhập thực tế trước mọi lần chuyển đổi.`,"nativeMain.busyOther":`Một thao tác đăng nhập gốc khác đang chạy. Hãy hoàn tất hoặc hủy nó trước.`,"nativeMain.working":`Đang xử lý…`,"nativeMain.changed":`Thư mục home, hồ sơ đang hoạt động hoặc trạng thái khôi phục đã thay đổi. Hãy xem lại trạng thái vừa làm mới và xác nhận lại.`,"nativeMain.error":`Không thể xác nhận kết quả. Không nhận được phản hồi không có nghĩa là đăng nhập ban đầu đã được khôi phục.`,"nativeMain.doctorHint":`Chạy {cmd} trên máy chủ để biết chi tiết.`,"nativeMain.saved":`Đã lưu đăng nhập hiện tại thành một hồ sơ. Đăng nhập thực tế không bị thay đổi.`,"nativeMain.lastResult":`Kết quả được xác nhận gần nhất`,"nativeMain.restart":`Đã thay đổi đăng nhập. Máy chủ yêu cầu khởi động lại Codex gốc.`,"nativeMain.done":`Đã hoàn tất thao tác. Máy chủ không yêu cầu khởi động lại Codex gốc.`,"nativeMain.refreshFailed":`Không thể làm mới toàn bộ thông tin tài khoản. Một thay đổi đã hoàn tất sẽ không bị hoàn tác. Hãy làm mới trước khi thực hiện thao tác khác.`,"nativeMain.refresh":`Làm mới trạng thái`,"nativeMain.unsupported":`Kho lưu trữ thông tin đăng nhập này không được hỗ trợ. Quản lý hồ sơ gốc yêu cầu kho lưu trữ dạng tệp.`,"nativeMain.recoveryHint":`Một giao dịch bị gián đoạn cần được khôi phục. Khôi phục sẽ hoàn tất việc đối chiếu; phục hồi sẽ quay lui giao dịch đang chờ. Không thao tác nào chạy cho đến khi bạn xác nhận.`,"nativeMain.recover":`Khôi phục thay đổi bị gián đoạn`,"nativeMain.rollback":`Phục hồi giao dịch đang chờ`,"nativeMain.empty":`Chưa có hồ sơ gốc nào được đăng ký. Hãy lưu đăng nhập hiện tại trước.`,"nativeMain.active":`Đang hoạt động`,"nativeMain.switchTo":`Chuyển đăng nhập gốc sang {label}`,"nativeMain.switch":`Chuyển`,"nativeMain.restore":`Quay lại hồ sơ đã hiển thị trước đó: {label}`,"nativeMain.restoreHint":`Lối tắt này chọn hồ sơ được hiển thị trước lần chuyển đổi gần nhất của bạn, không phải lịch sử giao dịch được máy chủ xác minh. Nó chỉ được giữ trên trang này.`,"nativeMain.label":`Nhãn hồ sơ`,"nativeMain.save":`Lưu hiện tại thành hồ sơ`,"nativeMain.saveHint":`Với một đăng nhập đang hoạt động đã được đăng ký, việc lưu sẽ cập nhật nhãn của nó. Nó không thêm một đăng nhập mới.`,"nativeMain.confirmHint":`Thao tác này chỉ thay đổi đăng nhập gốc trong thư mục home bên dưới. Hãy đóng Codex gốc trên máy tính đó trước. Bảng này không chỉnh sửa chiến lược Pool, thành viên, khóa nhà cung cấp hay dữ liệu tác vụ/lịch sử.`,"nativeMain.stepClose":`Đóng Codex gốc trên máy tính của máy chủ đang dùng CODEX_HOME được hiển thị. Giữ Codex đóng cho đến khi bạn đã kiểm tra kết quả.`,"nativeMain.stepConfirm":`Chọn ô bên dưới để xác nhận Codex đã đóng, rồi xác nhận thay đổi.`,"nativeMain.stepResult":`Chờ kết quả và hồ sơ đang hoạt động được cập nhật, rồi làm theo hướng dẫn để mở lại Codex.`,"nativeMain.reopenHint":`Kiểm tra hồ sơ đang hoạt động đã cập nhật, rồi mở lại Codex gốc trên máy tính của máy chủ với CODEX_HOME được hiển thị. Làm theo mọi yêu cầu khởi động lại hiển thị tại đây.`,"nativeMain.retryHint":`Làm mới trạng thái và kiểm tra hồ sơ đang hoạt động. Để thử lại việc đổi đăng nhập, hãy chọn lại thao tác và xác nhận Codex đã đóng. Không thao tác nào được tự động thử lại.`,"nativeMain.errorCodexBusy":`Codex gốc vẫn đang chạy trên máy chủ. Đóng Codex dùng CODEX_HOME hiển thị trước khi thử lại.`,"nativeMain.errorProcessCheck":`Máy chủ không xác minh được Codex gốc có đang chạy hay không. Kiểm tra Codex đã đóng trên máy đó và xem chẩn đoán máy chủ trước khi thử lại.`,"nativeMain.errorRequests":`Yêu cầu của tài khoản chính vẫn đang chạy hoặc chờ hoàn tất. Chờ chúng kết thúc trước khi thử lại.`,"nativeMain.errorBusy":`Một thao tác đăng nhập gốc khác đang chạy. Chờ thao tác đó kết thúc trước khi thử lại.`,"nativeMain.errorAuth":`Không đọc được đăng nhập gốc hiện tại hoặc không xác minh được với hồ sơ đã lưu. Xem chẩn đoán máy chủ trước khi thay đổi tiếp.`,"nativeMain.errorKeyStore":`Không mở được hồ sơ đã lưu hoặc kho khóa của hệ điều hành. Xem chẩn đoán kho khóa và hồ sơ trên máy chủ trước khi thay đổi tiếp.`,"nativeMain.errorStorage":`Máy chủ không thể truy cập an toàn vào thư mục đăng nhập hoặc kho hồ sơ. Kiểm tra chẩn đoán máy chủ trước khi thực hiện thay đổi khác.`,"nativeMain.errorProfile":`Trạng thái hồ sơ đã lưu không dùng được cho thao tác này. Làm mới và xem danh sách; kiểm tra chẩn đoán nếu vấn đề tiếp diễn.`,"nativeMain.errorRecovery":`Kho hồ sơ hoặc giao dịch bị gián đoạn cần được xử lý. Làm mới trạng thái và xem chẩn đoán máy chủ. Chỉ dùng điều khiển khôi phục khi bảng cung cấp.`,"nativeMain.errorRolledBack":`Máy chủ báo việc chuyển đổi thất bại và đăng nhập ban đầu đã được khôi phục. Kiểm tra hồ sơ đang hoạt động đã cập nhật trước khi thử lại.`,"nativeMain.stopped":`Tôi đã dừng Codex gốc đang dùng CODEX_HOME này và hiểu rằng có thể cần khởi động lại.`,"nativeMain.cancel":`Hủy`,"nativeMain.confirm":`Xác nhận thay đổi đăng nhập gốc`,"nativeMain.unavailable":`Không thể thay đổi hồ sơ. Hãy kiểm tra mã chẩn đoán trước khi tiếp tục.`},pt:{"nativeMain.title":`Login principal do Codex nativo`,"nativeMain.manage":`Gerenciar login principal`,"nativeMain.close":`Fechar o gerenciador de login principal`,"nativeMain.separate":`Estes controles alteram o login do Codex nativo, não a conta selecionada para a próxima requisição do Pool.`,"nativeMain.home":`CODEX_HOME efetivo`,"nativeMain.current":`Perfil ativo registrado`,"nativeMain.unregistered":`Não registrado`,"nativeMain.physicalHint":`Este diretório home pertence ao servidor do OpenCodex, que pode ser outro computador. O backend verifica o login físico antes de qualquer troca.`,"nativeMain.busyOther":`Outra operação de login nativo está em andamento. Conclua ou cancele-a primeiro.`,"nativeMain.working":`Processando…`,"nativeMain.changed":`O diretório home, o perfil ativo ou o estado de recuperação mudou. Revise o estado atualizado e confirme novamente.`,"nativeMain.error":`Não foi possível confirmar o resultado. A ausência de resposta não significa que o login original foi restaurado.`,"nativeMain.doctorHint":`Execute {cmd} no servidor para ver os detalhes.`,"nativeMain.saved":`Login atual salvo como perfil. O login físico não foi alterado.`,"nativeMain.lastResult":`Último resultado confirmado`,"nativeMain.restart":`Login alterado. O servidor exige a reinicialização do Codex nativo.`,"nativeMain.done":`Operação concluída. O servidor não solicitou a reinicialização do Codex nativo.`,"nativeMain.refreshFailed":`Não foi possível atualizar todas as informações da conta. Uma alteração já concluída não foi desfeita. Atualize antes de outra operação.`,"nativeMain.refresh":`Atualizar status`,"nativeMain.unsupported":`Este armazenamento de credenciais não é suportado. O gerenciamento de perfis nativos exige o armazenamento de credenciais em arquivo.`,"nativeMain.recoveryHint":`Uma transação interrompida precisa de recuperação. Recuperar conclui a reconciliação; restaurar reverte a transação pendente. Nenhuma das ações é executada até você confirmar.`,"nativeMain.recover":`Recuperar alteração interrompida`,"nativeMain.rollback":`Restaurar transação pendente`,"nativeMain.empty":`Nenhum perfil nativo registrado ainda. Salve primeiro o login atual.`,"nativeMain.active":`Ativo`,"nativeMain.switchTo":`Trocar o login nativo para {label}`,"nativeMain.switch":`Trocar`,"nativeMain.restore":`Voltar ao perfil exibido anteriormente: {label}`,"nativeMain.restoreHint":`Este atalho seleciona o perfil exibido antes da sua última troca, não um histórico de transações verificado pelo servidor. Ele é mantido apenas nesta página.`,"nativeMain.label":`Rótulo do perfil`,"nativeMain.save":`Salvar atual como perfil`,"nativeMain.saveHint":`Para um login ativo já registrado, salvar atualiza o rótulo. Não adiciona um novo login.`,"nativeMain.confirmHint":`Isto altera apenas o login nativo no diretório home abaixo. Feche primeiro o Codex nativo naquele computador. Este painel não edita estratégia do Pool, membros, chaves de provedor nem dados de tarefas/histórico.`,"nativeMain.stepClose":`Feche o Codex nativo no computador do servidor que usa o CODEX_HOME exibido. Mantenha-o fechado até verificar o resultado.`,"nativeMain.stepConfirm":`Marque a caixa de seleção abaixo para confirmar que o Codex está fechado e depois confirme a alteração.`,"nativeMain.stepResult":`Aguarde o resultado e o perfil ativo atualizado e depois siga as instruções para reabrir o Codex.`,"nativeMain.reopenHint":`Verifique o perfil ativo atualizado e depois reabra o Codex nativo no computador do servidor com o CODEX_HOME exibido. Siga qualquer exigência de reinicialização indicada aqui.`,"nativeMain.retryHint":`Atualize o status e verifique o perfil ativo. Para tentar novamente uma alteração de login, selecione a ação novamente e confirme que o Codex está fechado. Nada é repetido automaticamente.`,"nativeMain.errorCodexBusy":`O Codex nativo ainda está em execução no computador do servidor. Feche-o para o CODEX_HOME exibido antes de tentar novamente.`,"nativeMain.errorProcessCheck":`O servidor não pôde verificar se o Codex nativo está em execução. Verifique se ele está fechado nesse computador e consulte o diagnóstico do servidor antes de tentar novamente.`,"nativeMain.errorRequests":`As solicitações da conta principal ainda estão em execução ou terminando. Aguarde sua conclusão antes de tentar novamente.`,"nativeMain.errorBusy":`Outra operação de login nativo está em andamento. Aguarde sua conclusão antes de tentar novamente.`,"nativeMain.errorAuth":`O login nativo atual não pôde ser lido ou verificado com o perfil salvo. Consulte o diagnóstico do servidor antes de outra alteração.`,"nativeMain.errorKeyStore":`O perfil salvo ou o armazenamento de chaves do sistema não pôde ser aberto. Consulte seus diagnósticos no servidor antes de outra alteração.`,"nativeMain.errorStorage":`O servidor não consegue acessar com segurança a pasta de login ou o armazenamento de perfis. Verifique o diagnóstico do servidor antes de outra alteração.`,"nativeMain.errorProfile":`O estado do perfil salvo não pode ser usado nesta ação. Atualize e verifique a lista; consulte o diagnóstico se o problema persistir.`,"nativeMain.errorRecovery":`O armazenamento de perfis ou uma transação interrompida requer atenção. Atualize o status e consulte o diagnóstico do servidor. Use a recuperação somente quando o painel a oferecer.`,"nativeMain.errorRolledBack":`O servidor informa que a troca falhou e o login original foi restaurado. Verifique o perfil ativo atualizado antes de tentar novamente.`,"nativeMain.stopped":`Parei o Codex nativo que usa este CODEX_HOME e entendo que pode ser necessário reiniciá-lo.`,"nativeMain.cancel":`Cancelar`,"nativeMain.confirm":`Confirmar alteração do login nativo`,"nativeMain.unavailable":`As alterações de perfil estão indisponíveis. Verifique o código de diagnóstico antes de continuar.`}};function Ju(e){return(t,n)=>{let r=qu[e][t];for(let[e,t]of Object.entries(n??{}))r=r.split(`{${e}}`).join(String(t));return r}}var Yu=`INVALID_REQUEST.CODEX_HOME_UNAVAILABLE.UNSUPPORTED_AUTH_STORE.AUTH_MISSING.AUTH_INVALID.AUTH_UNREADABLE.AUTH_TEMP_CLEANUP_REQUIRED.ACTIVE_PROFILE_MISMATCH.PROFILE_NOT_FOUND.PROFILE_ALREADY_EXISTS.PROFILE_DECRYPT_FAILED.KEYRING_UNAVAILABLE.KEYRING_KEY_MISSING.PROFILE_LOCK_UNAVAILABLE.NATIVE_PROFILE_BUSY.NATIVE_MAIN_OWNER_BUSY.NATIVE_MAIN_OWNER_UNAVAILABLE.NATIVE_MAIN_CLAIM_BUSY.NATIVE_MAIN_CLAIM_UNAVAILABLE.CODEX_BUSY.CODEX_PROCESS_CHECK_UNAVAILABLE.MAIN_REQUESTS_ACTIVE.RECOVERY_REQUIRED.AUTH_RESTORE_FAILED.SWITCH_ROLLED_BACK.PROFILE_METADATA_TOO_LARGE.PROFILE_STORAGE_UNSAFE.LEGACY_PROFILE_STATE.INTERNAL_ERROR.VAULT_INVALID.STAGING_CLEANUP_REQUIRED.NETWORK_ERROR.INVALID_RESPONSE.STATE_CHANGED`.split(`.`),Xu=class extends Error{code;constructor(e){super(e),this.code=e}};function Zu(e){return e instanceof Xu?e.code:`NETWORK_ERROR`}function Qu(){throw new Xu(`INVALID_RESPONSE`)}function $u(e){return!e||typeof e!=`object`||Array.isArray(e)?Qu():e}function ed(e){return typeof e!=`string`||!e.trim()?Qu():e}function td(e){return e===null?null:ed(e)}function nd(e){return typeof e==`boolean`?e:Qu()}function rd(e,t){return typeof e==`string`&&t.includes(e)?e:Qu()}function id(e){let t=$u(e);return{id:ed(t.id),label:ed(t.label),identityHint:ed(t.identityHint),state:rd(t.state,[`active`,`inactive`])}}function ad(e){let t=$u(e);if(!Array.isArray(t.profiles)||t.profiles.length>32)return Qu();let n=t.profiles.map(id),r=td(t.activeProfileId);if(new Set(n.map(e=>e.id)).size!==n.length)return Qu();let i=n.filter(e=>e.state===`active`);return(r===null?n.length!==0:i.length!==1||i[0].id!==r)?Qu():{effectiveCodexHome:ed(t.effectiveCodexHome),activeProfileId:r,profiles:n}}function od(e){let t=$u(e);return{effectiveCodexHome:ed(t.effectiveCodexHome),activeProfileId:td(t.activeProfileId),supported:nd(t.supported),authStatus:rd(t.authStatus,[`ok`,`missing`,`invalid`,`unreadable`]),keyStore:rd(t.keyStore,[`available`,`missing-key`,`unavailable`]),vaultStatus:rd(t.vaultStatus,[`ok`,`missing`,`invalid`]),recoveryPending:nd(t.recoveryPending)}}async function sd(e,t,n,r,i){n.throwIfAborted();let a=await(i??fetch)(`${e}/api/native-main-profiles${t}`,{method:r?`POST`:`GET`,signal:n,cache:`no-store`,...r?{headers:{"content-type":`application/json`},body:JSON.stringify(r)}:{}}),o;try{o=await a.json()}catch{throw new Xu(`INVALID_RESPONSE`)}if(n.throwIfAborted(),!a.ok){let e=o&&typeof o==`object`?o.code:void 0;throw new Xu(typeof e==`string`&&Yu.includes(e)?e:`INTERNAL_ERROR`)}return o}async function cd(e,t,n){let[r,i]=await Promise.allSettled([sd(e,``,t,void 0,n).then(ad),sd(e,`/doctor`,t,void 0,n).then(od)]);if(t.throwIfAborted(),i.status===`rejected`)throw i.reason;if(r.status===`rejected`){if(!i.value.recoveryPending)throw r.reason;return{doctor:i.value,list:null}}if(r.value.effectiveCodexHome!==i.value.effectiveCodexHome||r.value.activeProfileId!==i.value.activeProfileId)throw new Xu(`STATE_CHANGED`);return{doctor:i.value,list:r.value}}function ld(e){let t=e.doctor;return t.supported?t.recoveryPending?`RECOVERY_REQUIRED`:t.authStatus===`ok`?t.keyStore===`available`?t.vaultStatus===`invalid`?`VAULT_INVALID`:null:t.keyStore===`missing-key`?`KEYRING_KEY_MISSING`:`KEYRING_UNAVAILABLE`:t.authStatus===`missing`?`AUTH_MISSING`:t.authStatus===`invalid`?`AUTH_INVALID`:`AUTH_UNREADABLE`:`UNSUPPORTED_AUTH_STORE`}function ud(e){let t=e.doctor;return!!e.list&&t.supported&&t.authStatus===`ok`&&t.keyStore===`available`&&t.vaultStatus!==`invalid`&&!t.recoveryPending}function dd(e,t){let n=e.doctor;return n.supported?t.kind===`recover`?n.recoveryPending:ud(e)&&!!e.list?.profiles.some(e=>e.id===t.target&&e.label===t.label&&e.state===`inactive`):!1}function fd(e,t){return e.doctor.effectiveCodexHome===t.doctor.effectiveCodexHome&&e.doctor.activeProfileId===t.doctor.activeProfileId&&e.doctor.recoveryPending===t.doctor.recoveryPending}async function pd(e,t,n,r){let i=$u(await sd(e,`/register`,n,{label:t.trim()},r)),a=ed(i.effectiveCodexHome);return id(i.profile).state===`active`?a:Qu()}async function md(e,t,n,r,i){if(!n)throw new Xu(`INVALID_REQUEST`);let a=$u(await sd(e,t.kind===`switch`?`/switch`:`/recover`,r,t.kind===`switch`?{target:t.target,confirmedStopped:!0}:{rollback:t.rollback,confirmedStopped:!0},i));if(a.ok!==!0)return Qu();if(t.kind===`switch`){let e=id(a.activeProfile);if(e.id!==t.target||e.state!==`active`)return Qu()}let o=t.kind===`recover`&&a.restartRequired===void 0&&a.recovered===!1?!1:nd(a.restartRequired);return{effectiveCodexHome:ed(a.effectiveCodexHome),restartRequired:o,...typeof a.recovered==`boolean`?{recovered:a.recovered}:{}}}var hd=2e4,gd=Symbol(`account-refresh-timeout`),_d=class{state={open:!1,busy:!1,blocked:!1,snapshot:null,label:``,action:null,confirmedStopped:!1,previous:null,error:null,result:null,refreshFailed:!1};listener=null;epoch=0;pending=null;onChanged=()=>{};restartRequired=!1;resultHome=null;apiBase;accountRefreshTimeoutMs;fetchImpl;constructor(e,t=hd,n){this.apiBase=e,this.accountRefreshTimeoutMs=t,this.fetchImpl=n}attach(e){let t=++this.epoch;return this.listener=e,e(this.state),()=>{this.epoch===t&&(this.epoch++,this.listener=null,this.pending?.abort(),this.pending=null,this.state.busy&&(this.state={...this.state,busy:!1,snapshot:null,action:null,confirmedStopped:!1,previous:null,refreshFailed:!0}))}}updateOptions(e,t){this.onChanged=t,this.state.blocked!==e&&this.set({blocked:e,action:null,confirmedStopped:!1})}set(e){this.state={...this.state,...e},this.listener?.(this.state)}current(e){return this.epoch===e&&this.listener!==null}accept(e){let t=this.state.previous,n=this.resultHome!==null&&this.resultHome!==e.doctor.effectiveCodexHome;n&&(this.restartRequired=!1,this.resultHome=null),this.set({snapshot:e,...n?{result:null}:{},previous:t&&t.home===e.doctor.effectiveCodexHome&&t.active===e.doctor.activeProfileId?t:null})}setLabel(e){this.pending||this.set({label:e})}setStopped(e){!this.pending&&this.state.action&&!this.state.blocked&&this.set({confirmedStopped:e})}select(e){this.pending||(!e||!this.state.blocked&&!this.state.refreshFailed&&this.state.snapshot&&dd(this.state.snapshot,e))&&this.set({action:e,confirmedStopped:!1,error:null})}async toggle(){if(this.pending)return;let e=!this.state.open;this.set({open:e,action:null,confirmedStopped:!1}),e&&await this.refresh()}async run(e){if(!this.listener||this.pending||this.state.blocked)return;let t=this.epoch,n=new AbortController;this.pending=n;let r=setTimeout(()=>n.abort(),45e3);this.set({busy:!0});try{await e(t,n.signal)}catch(e){this.current(t)&&this.set({error:Zu(e),snapshot:null})}finally{clearTimeout(r),this.current(t)&&(this.pending=null,this.set({busy:!1}))}}async refresh(){this.state.action||await this.run(async(e,t)=>{let n=this.state.refreshFailed;this.set({error:null});let r=await cd(this.apiBase,t,this.fetchImpl);this.current(e)&&(this.accept(r),this.set({refreshFailed:!1}),n&&await this.refreshAccount(e))})}async refreshAccount(e){if(!this.current(e))return;let t=new AbortController,n,r=(async()=>{try{return await this.onChanged(t.signal)}catch{return!1}})(),i=new Promise(e=>{n=setTimeout(()=>{t.abort(),e(gd)},this.accountRefreshTimeoutMs)});try{let t=await Promise.race([r,i]);this.current(e)&&(t===!1||t===gd)&&this.set({refreshFailed:!0})}finally{clearTimeout(n)}}async reconcile(e){if(!this.current(e))return;let t=new AbortController;this.pending=t;let n=setTimeout(()=>t.abort(),2e4);try{let n=await cd(this.apiBase,t.signal,this.fetchImpl);if(!this.current(e))return;this.accept(n)}catch{this.current(e)&&this.set({snapshot:null,refreshFailed:!0})}finally{clearTimeout(n)}await this.refreshAccount(e)}async register(){let e=this.state.snapshot,t=this.state.label.trim();e&&!this.state.refreshFailed&&t&&!this.state.action&&ud(e)&&await this.mutate(e,{label:t})}async confirm(){let{snapshot:e,action:t,confirmedStopped:n,refreshFailed:r}=this.state;e&&t&&n&&!r&&dd(e,t)&&await this.mutate(e,{action:t})}async mutate(e,t){await this.run(async(n,r)=>{this.set({error:null,result:this.restartRequired?`restart`:null,refreshFailed:!1});let i=!1;try{let a=await cd(this.apiBase,r,this.fetchImpl);if(r.throwIfAborted(),!this.current(n)||this.state.blocked)return;if(this.accept(a),!fd(e,a)||(`action`in t?!dd(a,t.action):!ud(a)))throw new Xu(`STATE_CHANGED`);if(i=!0,`label`in t){let i=await pd(this.apiBase,t.label,r,this.fetchImpl);if(!this.current(n))return;if(i!==e.doctor.effectiveCodexHome)throw new Xu(`STATE_CHANGED`);this.resultHome=i,this.set({label:``,result:this.restartRequired?`restart`:`saved`})}else{let i=await md(this.apiBase,t.action,!0,r,this.fetchImpl);if(!this.current(n))return;if(i.effectiveCodexHome!==e.doctor.effectiveCodexHome)throw new Xu(`STATE_CHANGED`);this.resultHome=i.effectiveCodexHome,this.restartRequired||=i.restartRequired,this.set({previous:t.action.kind===`switch`?{id:e.doctor.activeProfileId,home:e.doctor.effectiveCodexHome,active:t.action.target}:null,result:this.restartRequired?`restart`:`done`})}}catch(e){this.current(n)&&this.set({error:Zu(e),previous:null})}finally{this.current(n)&&this.set({action:null,confirmedStopped:!1}),i&&await this.reconcile(n)}})}},vd={INVALID_REQUEST:`nativeMain.error`,CODEX_HOME_UNAVAILABLE:`nativeMain.errorStorage`,UNSUPPORTED_AUTH_STORE:`nativeMain.unsupported`,AUTH_MISSING:`nativeMain.errorAuth`,AUTH_INVALID:`nativeMain.errorAuth`,AUTH_UNREADABLE:`nativeMain.errorAuth`,AUTH_TEMP_CLEANUP_REQUIRED:`nativeMain.errorRecovery`,ACTIVE_PROFILE_MISMATCH:`nativeMain.errorAuth`,PROFILE_NOT_FOUND:`nativeMain.errorProfile`,PROFILE_ALREADY_EXISTS:`nativeMain.errorProfile`,PROFILE_DECRYPT_FAILED:`nativeMain.errorKeyStore`,KEYRING_UNAVAILABLE:`nativeMain.errorKeyStore`,KEYRING_KEY_MISSING:`nativeMain.errorKeyStore`,PROFILE_LOCK_UNAVAILABLE:`nativeMain.errorStorage`,NATIVE_PROFILE_BUSY:`nativeMain.errorBusy`,NATIVE_MAIN_OWNER_BUSY:`nativeMain.errorBusy`,NATIVE_MAIN_OWNER_UNAVAILABLE:`nativeMain.errorStorage`,NATIVE_MAIN_CLAIM_BUSY:`nativeMain.errorBusy`,NATIVE_MAIN_CLAIM_UNAVAILABLE:`nativeMain.errorStorage`,CODEX_BUSY:`nativeMain.errorCodexBusy`,CODEX_PROCESS_CHECK_UNAVAILABLE:`nativeMain.errorProcessCheck`,MAIN_REQUESTS_ACTIVE:`nativeMain.errorRequests`,RECOVERY_REQUIRED:`nativeMain.errorRecovery`,AUTH_RESTORE_FAILED:`nativeMain.errorRecovery`,SWITCH_ROLLED_BACK:`nativeMain.errorRolledBack`,PROFILE_METADATA_TOO_LARGE:`nativeMain.errorProfile`,PROFILE_STORAGE_UNSAFE:`nativeMain.errorStorage`,LEGACY_PROFILE_STATE:`nativeMain.errorProfile`,INTERNAL_ERROR:`nativeMain.error`,VAULT_INVALID:`nativeMain.errorRecovery`,STAGING_CLEANUP_REQUIRED:`nativeMain.errorRecovery`,NETWORK_ERROR:`nativeMain.error`,INVALID_RESPONSE:`nativeMain.error`,STATE_CHANGED:`nativeMain.changed`},yd=`ocx account main doctor`;function bd({t:e}){let[t,n=``]=e(`nativeMain.doctorHint`).split(`{cmd}`);return(0,Q.jsxs)(Q.Fragment,{children:[t,(0,Q.jsx)(`code`,{className:`chip`,children:yd}),n]})}function xd({t:e,id:t,open:n,busy:r,blocked:i,snapshot:a,label:o,action:s,confirmedStopped:c,previousId:l,error:u,result:d,refreshFailed:f,summaryRef:p,confirmationRef:m,onToggle:h,onRefresh:g,onLabel:_,onRegister:v,onSelect:y,onStopped:b,onConfirm:x}){let S=r||i,C=S||f,w=a?ld(a):null,T=a?.list?.profiles??[],E=T.find(e=>e.id===a?.doctor.activeProfileId),D=T.find(e=>e.id===l&&e.state===`inactive`);return(0,Q.jsxs)(`section`,{className:`panel`,"aria-labelledby":`${t}-heading`,style:{marginBottom:12},children:[(0,Q.jsxs)(`div`,{className:`row`,style:{justifyContent:`space-between`},children:[(0,Q.jsx)(`strong`,{id:`${t}-heading`,children:e(`nativeMain.title`)}),(0,Q.jsx)(`button`,{ref:p,type:`button`,className:`btn btn-sm btn-ghost`,"aria-expanded":n,"aria-controls":`${t}-panel`,onClick:h,disabled:r,children:e(n?`nativeMain.close`:`nativeMain.manage`)})]}),n&&(0,Q.jsxs)(`div`,{id:`${t}-panel`,"aria-busy":r,children:[(0,Q.jsx)(`p`,{className:`card-sub`,children:e(`nativeMain.separate`)}),a&&(0,Q.jsxs)(`dl`,{children:[(0,Q.jsx)(`dt`,{children:e(`nativeMain.home`)}),(0,Q.jsx)(`dd`,{style:{marginLeft:0,overflowWrap:`anywhere`},children:(0,Q.jsx)(`code`,{children:a.doctor.effectiveCodexHome})}),a.list&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`dt`,{children:e(`nativeMain.current`)}),(0,Q.jsx)(`dd`,{style:{marginLeft:0,overflowWrap:`anywhere`},children:E?.label??e(`nativeMain.unregistered`)})]})]}),(0,Q.jsx)(`p`,{className:`card-sub`,children:e(`nativeMain.physicalHint`)}),i&&(0,Q.jsx)(`p`,{role:`status`,className:`notice notice-warn`,children:e(`nativeMain.busyOther`)}),r&&(0,Q.jsx)(`p`,{role:`status`,children:e(`nativeMain.working`)}),u&&(0,Q.jsxs)(`div`,{role:`alert`,className:`notice notice-err native-main-notice`,children:[(0,Q.jsx)(`p`,{children:e(vd[u])}),(0,Q.jsx)(`p`,{children:e(`nativeMain.retryHint`)}),(0,Q.jsxs)(`p`,{children:[(0,Q.jsx)(`code`,{children:u}),` `,(0,Q.jsx)(bd,{t:e})]})]}),d&&!r&&!u&&!s&&(0,Q.jsxs)(`div`,{role:`status`,className:`notice native-main-notice`,children:[(0,Q.jsx)(`strong`,{children:e(`nativeMain.lastResult`)}),(0,Q.jsx)(`p`,{children:e(d===`saved`?`nativeMain.saved`:d===`restart`?`nativeMain.restart`:`nativeMain.done`)}),d!==`saved`&&a&&!f&&(0,Q.jsx)(`p`,{children:e(`nativeMain.reopenHint`)})]}),f&&(0,Q.jsx)(`p`,{role:`alert`,className:`notice notice-warn`,children:e(`nativeMain.refreshFailed`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,onClick:g,disabled:S||!!s,children:e(`nativeMain.refresh`)}),a&&!a.doctor.supported&&(0,Q.jsx)(`p`,{role:`alert`,children:e(`nativeMain.unsupported`)}),w&&a?.doctor.supported&&!a.doctor.recoveryPending&&(0,Q.jsxs)(`p`,{role:`status`,children:[e(`nativeMain.unavailable`),` `,(0,Q.jsx)(`code`,{children:w})]}),a?.doctor.recoveryPending&&(0,Q.jsxs)(`div`,{className:`notice notice-warn`,children:[(0,Q.jsx)(`p`,{children:e(`nativeMain.recoveryHint`)}),(0,Q.jsxs)(`div`,{className:`row`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:C||!!s||!a.doctor.supported,onClick:()=>y({kind:`recover`,rollback:!1}),children:e(`nativeMain.recover`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:C||!!s||!a.doctor.supported,onClick:()=>y({kind:`recover`,rollback:!0}),children:e(`nativeMain.rollback`)})]})]}),a?.list&&(0,Q.jsxs)(Q.Fragment,{children:[T.length===0&&(0,Q.jsx)(`p`,{children:e(`nativeMain.empty`)}),(0,Q.jsx)(`ul`,{style:{listStyle:`none`,padding:0},children:T.map(t=>(0,Q.jsxs)(`li`,{className:`row`,style:{padding:`8px 0`,flexWrap:`wrap`},children:[(0,Q.jsx)(`strong`,{style:{overflowWrap:`anywhere`,minWidth:0},children:t.label}),` `,(0,Q.jsx)(`code`,{style:{overflowWrap:`anywhere`,minWidth:0},children:t.identityHint}),t.state===`active`?(0,Q.jsx)(`span`,{className:`badge badge-green`,children:e(`nativeMain.active`)}):(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:C||!!s||!dd(a,{kind:`switch`,target:t.id,label:t.label}),"aria-label":e(`nativeMain.switchTo`,{label:t.label}),onClick:()=>y({kind:`switch`,target:t.id,label:t.label}),children:e(`nativeMain.switch`)})]},t.id))}),D&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:C||!!s||!dd(a,{kind:`switch`,target:D.id,label:D.label}),onClick:()=>y({kind:`switch`,target:D.id,label:D.label}),children:e(`nativeMain.restore`,{label:D.label})}),(0,Q.jsx)(`p`,{className:`card-sub`,children:e(`nativeMain.restoreHint`)})]}),(0,Q.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),v()},children:[(0,Q.jsx)(`label`,{htmlFor:`${t}-label`,children:e(`nativeMain.label`)}),(0,Q.jsxs)(`div`,{className:`row`,style:{flexWrap:`wrap`},children:[(0,Q.jsx)(`input`,{id:`${t}-label`,value:o,onChange:e=>_(e.target.value),disabled:C||!!s||!ud(a),maxLength:80,autoComplete:`off`}),(0,Q.jsx)(`button`,{type:`submit`,className:`btn btn-sm`,disabled:C||!!s||!o.trim()||!ud(a),children:e(`nativeMain.save`)})]}),(0,Q.jsx)(`p`,{className:`card-sub`,children:e(`nativeMain.saveHint`)})]})]}),s&&a&&(0,Q.jsxs)(`div`,{ref:m,role:`group`,tabIndex:-1,"aria-labelledby":`${t}-confirm-title`,className:`notice notice-warn`,style:{marginTop:12,display:`block`},onKeyDown:e=>{e.key===`Escape`&&!r&&(e.preventDefault(),y(null))},children:[(0,Q.jsx)(`h3`,{id:`${t}-confirm-title`,style:{overflowWrap:`anywhere`},children:e(s.kind===`switch`?`nativeMain.switchTo`:s.rollback?`nativeMain.rollback`:`nativeMain.recover`,{label:s.kind===`switch`?s.label:``})}),(0,Q.jsx)(`p`,{children:e(`nativeMain.confirmHint`)}),(0,Q.jsx)(`code`,{style:{overflowWrap:`anywhere`},children:a.doctor.effectiveCodexHome}),(0,Q.jsxs)(`ol`,{children:[(0,Q.jsx)(`li`,{children:e(`nativeMain.stepClose`)}),(0,Q.jsx)(`li`,{children:e(`nativeMain.stepConfirm`)}),(0,Q.jsx)(`li`,{children:e(`nativeMain.stepResult`)})]}),(0,Q.jsx)(`p`,{children:(0,Q.jsxs)(`label`,{htmlFor:`${t}-stopped`,children:[(0,Q.jsx)(`input`,{id:`${t}-stopped`,type:`checkbox`,checked:c,disabled:C,onChange:e=>b(e.target.checked)}),` `,e(`nativeMain.stopped`)]})}),(0,Q.jsxs)(`div`,{className:`row`,style:{flexWrap:`wrap`},children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,style:{whiteSpace:`normal`,overflowWrap:`anywhere`,maxWidth:`100%`},disabled:r,onClick:()=>y(null),children:e(`nativeMain.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm btn-primary`,style:{whiteSpace:`normal`,overflowWrap:`anywhere`,maxWidth:`100%`},disabled:C||!c||!dd(a,s),onClick:x,children:e(`nativeMain.confirm`)})]})]})]})]})}function Sd(e){return(0,Q.jsx)(Cd,{...e},e.apiBase)}function Cd({apiBase:e,disabled:t=!1,onChanged:n}){let{locale:i}=r(),a=Ju(i),o=(0,Z.useId)(),[s]=(0,Z.useState)(()=>new _d(e)),[c,l]=(0,Z.useState)(s.state),u=(0,Z.useRef)(null),d=(0,Z.useRef)(null),f=(0,Z.useRef)(!1);return(0,Z.useLayoutEffect)(()=>s.attach(l),[s]),(0,Z.useLayoutEffect)(()=>{s.updateOptions(t,n)},[s,t,n]),(0,Z.useLayoutEffect)(()=>{c.action?(f.current=!0,d.current?.focus()):!c.busy&&f.current&&(f.current=!1,u.current?.focus())},[c.action,c.busy]),(0,Q.jsx)(xd,{t:a,id:o,...c,previousId:c.previous?.id??null,summaryRef:u,confirmationRef:d,onToggle:()=>{s.toggle()},onRefresh:()=>{s.refresh()},onLabel:e=>s.setLabel(e),onRegister:()=>{s.register()},onSelect:e=>s.select(e),onStopped:e=>s.setStopped(e),onConfirm:()=>{s.confirm()}})}var wd={"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 Td({threshold:e,draft:t,strategy:r=`quota`,hydrated:i=!0,saving:a,loadError:o,feedback:s,onDraftChange:c,onEditingChange:l,onCommit:u,onCancel:d,onToggle:f,onRetry:p}){let m=n(),h=(0,Z.useRef)(!1),g=e>0,_=wd[r][g?`on`:`off`],v=a||!i,y=a?m(`common.saving`):s?.message??``,b=a?`pending`:s?.tone,x=y?`codex-auto-switch-desc codex-auto-switch-feedback`:`codex-auto-switch-desc`;return(0,Q.jsxs)(`div`,{className:`card card-row codex-auto-switch-card`,style:{marginTop:16},"aria-busy":a||!i&&!o||void 0,children:[(0,Q.jsxs)(`div`,{className:`codex-auto-switch-copy`,children:[(0,Q.jsx)(`strong`,{children:m(`codexAuth.autoSwitch`)}),(0,Q.jsx)(`div`,{id:`codex-auto-switch-desc`,className:`card-sub`,role:o?`alert`:void 0,children:o?m(`codexAuth.autoSwitchLoadFailed`):m(_,{threshold:e})}),(0,Q.jsx)(`div`,{className:`card-sub`,children:m(`codexAuth.failureRecoveryNote`)}),(0,Q.jsx)(`div`,{className:`card-sub`,children:m(`codexAuth.cacheWarning`)})]}),(0,Q.jsxs)(`div`,{className:`codex-auto-switch-controls`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(l(!1),h.current?h.current=!1:g&&!v&&u())},children:[o&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:p,children:m(`pws.retryAccounts`)}),g&&(0,Q.jsxs)(`label`,{className:`codex-auto-switch-threshold`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:m(`codexAuth.autoSwitchThreshold`)}),(0,Q.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,children:[(0,Q.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":m(`codexAuth.autoSwitchThresholdAria`),"aria-describedby":x,onChange:e=>c(e.target.value),onFocus:()=>{v||l(!0)},onKeyDown:e=>{e.nativeEvent.isComposing||v||(e.key===`Enter`?(e.preventDefault(),u()):e.key===`Escape`&&(e.preventDefault(),d()))}}),(0,Q.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`%`}),(0,Q.jsx)(yl,{disabled:v,incrementLabel:m(`codexAuth.autoSwitchThresholdInc`),decrementLabel:m(`codexAuth.autoSwitchThresholdDec`),onIncrement:()=>{l(!0),c(vl(t,1,1,100))},onDecrement:()=>{l(!0),c(vl(t,-1,1,100))}})]})]}),(0,Q.jsx)(`span`,{className:`codex-auto-switch-toggle-slot`,children:(0,Q.jsx)(`button`,{type:`button`,className:`toggle ${g?`on`:``}`,onPointerDownCapture:()=>{h.current=!0},onPointerUp:()=>{h.current=!1},onPointerCancel:()=>{h.current=!1},onClick:()=>{h.current=!1,f()},disabled:v,"aria-pressed":g,"aria-label":m(`codexAuth.autoSwitch`),"aria-describedby":x,title:m(`codexAuth.autoSwitch`),children:(0,Q.jsx)(`span`,{className:`toggle-knob`})})})]}),y&&(0,Q.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 Ed={"reset-first":`accountPool.strategyResetFirst`,quota:`accountPool.strategyQuota`,"round-robin":`accountPool.strategyRoundRobin`,"fill-first":`accountPool.strategyFillFirst`},Dd={"reset-first":`accountPool.strategyHintResetFirst`,quota:`accountPool.strategyHintQuota`,"round-robin":`accountPool.strategyHintRoundRobin`,"fill-first":`accountPool.strategyHintFillFirst`};function Od({strategy:e,codex:t=!1,threshold:r,stickyDraft:i,disabled:a=!1,strategySelectId:o=`account-pool-strategy`,stickyInputId:s=`account-pool-sticky-limit`,onStrategyChange:c,onStickyDraftChange:l,onStickyCommit:u}){let d=n(),f=su.filter(e=>t||e!==`reset-first`).map(e=>({value:e,label:d(Ed[e])})),p=r===void 0?null:e===`round-robin`?d(`accountPool.thresholdNotUsed`):r>0?d(e===`fill-first`?`accountPool.drainAtThreshold`:e===`reset-first`?`accountPool.resetBelowThreshold`:`accountPool.switchAtThreshold`,{threshold:String(r)}):d(`accountPool.proactiveSwitchingOff`);return(0,Q.jsxs)(`div`,{className:`account-pool-strategy-controls`,children:[(0,Q.jsxs)(`div`,{className:`setting-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-label`,children:[(0,Q.jsx)(`span`,{className:`title`,id:`${o}-label`,children:d(`accountPool.strategy`)}),(0,Q.jsx)(`span`,{className:`desc`,children:d(`accountPool.strategyDesc`)}),(0,Q.jsx)(`span`,{className:`desc`,children:d(Dd[e])}),(0,Q.jsx)(`span`,{className:`desc`,children:d(`accountPool.unboundDefinition`)})]}),(0,Q.jsxs)(`div`,{className:`setting-controls`,children:[(0,Q.jsx)(dn,{id:o,value:e,options:f,disabled:a,label:d(`accountPool.strategy`),onChange:e=>c(e)}),p&&(0,Q.jsx)(`span`,{className:`badge badge-muted account-pool-threshold-badge`,"data-testid":`account-pool-threshold-summary`,children:p})]})]}),e===`round-robin`&&(0,Q.jsxs)(`div`,{className:`setting-row`,children:[(0,Q.jsxs)(`label`,{className:`setting-label`,htmlFor:s,children:[(0,Q.jsx)(`span`,{className:`title`,children:d(`accountPool.stickyLimit`)}),(0,Q.jsx)(`span`,{className:`desc`,children:d(`accountPool.stickyLimitHelp`)})]}),(0,Q.jsx)(`div`,{className:`setting-controls`,children:(0,Q.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,children:[(0,Q.jsx)(`input`,{id:s,className:`input mono codex-auto-switch-input`,type:`number`,min:1,max:100,step:1,inputMode:`numeric`,value:i,disabled:a,"aria-label":d(`accountPool.stickyLimitAria`),onChange:e=>l(e.target.value),onBlur:()=>u(),onKeyDown:e=>{e.nativeEvent.isComposing||a||e.key===`Enter`&&(e.preventDefault(),u())}}),(0,Q.jsx)(yl,{disabled:a,incrementLabel:d(`accountPool.stickyLimitInc`),decrementLabel:d(`accountPool.stickyLimitDec`),onIncrement:()=>{let e=vl(i,1,1,100);l(e),u(e)},onDecrement:()=>{let e=vl(i,-1,1,100);l(e),u(e)}})]})})]})]})}function kd(e){if(!e||typeof e!=`object`)return null;let t=e;if(!(`accountPoolStrategy`in t)&&!(`accountPoolStickyLimit`in t)&&!(`autoSwitchThreshold`in t))return null;let n=typeof t.autoSwitchThreshold==`number`?t.autoSwitchThreshold:void 0;return{strategy:pu(t.accountPoolStrategy),stickyLimit:hu(t.accountPoolStickyLimit),threshold:n}}function Ad({apiBase:e,subscribeLoadObserver:t,readLastActive:r,onStrategyResolved:i,threshold:a}){let o=n(),[s,c]=(0,Z.useState)(lu),[l,u]=(0,Z.useState)(1),[d,f]=(0,Z.useState)(`1`),[p,m]=(0,Z.useState)(void 0),[h,g]=(0,Z.useState)(!1),_=(0,Z.useRef)(!1),[v,y]=(0,Z.useState)(!1),b=(0,Z.useRef)(!1),x=(0,Z.useRef)(!1),S=(0,Z.useRef)(0),[C,w]=(0,Z.useState)(!1),[T,E]=(0,Z.useState)(null),D=(0,Z.useCallback)(e=>{let t=pu(e.accountPoolStrategy),n=hu(e.accountPoolStickyLimit);typeof e.autoSwitchThreshold==`number`&&m(e.autoSwitchThreshold),c(t),i?.(t),u(n),f(String(n)),_.current=!0,g(!0),w(!1),E(null)},[i]),O=(0,Z.useCallback)(e=>{let t=kd(e);t&&D({accountPoolStrategy:t.strategy,accountPoolStickyLimit:t.stickyLimit,autoSwitchThreshold:t.threshold})},[D]),k=(0,Z.useCallback)(async()=>{try{let t=await fetch(`${e}/api/codex-auth/active`);if(!t.ok)throw Error(`load`);let n=await t.json();if(b.current){x.current=!0;return}D(n)}catch{b.current||w(!0)}},[e,D]),A=(0,Z.useCallback)(()=>{x.current&&(x.current=!1,queueMicrotask(()=>{b.current?x.current=!0:k()}))},[k]);(0,Z.useEffect)(()=>{if(!t)return;let e=t({beginActiveRead:()=>S.current,acceptActiveRead:(e,t)=>{t===S.current&&(b.current?x.current=!0:O(e))},rejectActiveRead:()=>{_.current||w(!0)}});return!b.current&&r&&O(r()),e},[t,O,r]),(0,Z.useEffect)(()=>{r&&!t&&(b.current||O(r()))},[r,O,t]),(0,Z.useEffect)(()=>{t||k()},[k,t]);let j=(0,Z.useCallback)(async t=>{if(b.current)return;let n=s,r=l;t.strategy!==void 0&&(c(t.strategy),i?.(t.strategy)),t.stickyLimit!==void 0&&(u(t.stickyLimit),f(String(t.stickyLimit))),b.current=!0,y(!0),E(null),S.current+=1;let a=await Cu(e,t);S.current+=1,a.ok?(c(a.strategy),i?.(a.strategy),u(a.stickyLimit),f(String(a.stickyLimit)),_.current=!0,g(!0)):(E(o(`accountPool.strategyUpdateFailed`)),c(n),i?.(n),u(r),f(String(r))),b.current=!1,y(!1),A()},[e,i,A,l,s,o]),M=v||C||!h;return(0,Q.jsxs)(`div`,{className:`card account-pool-strategy-card`,"aria-busy":v||!h&&!C,children:[C&&(0,Q.jsx)(`div`,{className:`card-sub`,role:`alert`,children:o(`accountPool.strategyLoadFailed`)}),C&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm account-pool-strategy-card__retry`,onClick:()=>{k()},children:o(`common.retry`)}),!C&&(0,Q.jsx)(Od,{codex:!0,strategy:s,threshold:a===void 0?p:a,stickyDraft:d,disabled:M,strategySelectId:`codex-pool-strategy`,stickyInputId:`codex-pool-sticky-limit`,onStrategyChange:e=>{M||e===s||j({strategy:e})},onStickyDraftChange:f,onStickyCommit:e=>{if(M)return;let t=gu(e??d);t===null?(f(String(l)),E(o(`accountPool.stickyLimitInvalid`))):t===l?f(String(t)):j({stickyLimit:t})}}),T&&(0,Q.jsx)(`div`,{role:`alert`,className:`card-sub account-pool-strategy-card__error`,children:T})]})}function jd({t:e,open:t,onToggle:n,children:r}){return(0,Q.jsxs)(`section`,{className:`codex-auth-advanced`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`codex-auth-advanced__toggle`,"aria-expanded":t,"aria-controls":`codex-auth-advanced-boxes`,onClick:n,children:[(0,Q.jsx)(`span`,{children:e(`codexAuth.advancedSettings`)}),(0,Q.jsx)(Ye,{width:12,height:12,"aria-hidden":`true`,className:t?`codex-auth-advanced__chevron is-open`:`codex-auth-advanced__chevron`})]}),t&&(0,Q.jsx)(`div`,{id:`codex-auth-advanced-boxes`,className:`codex-auth-advanced__boxes`,children:r})]})}function Md(e,t){let[n,r]=(0,Z.useState)(80),[i,a]=(0,Z.useState)(`80`),[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(null),m=(0,Z.useRef)(80),h=(0,Z.useRef)(!1),g=(0,Z.useRef)(80),_=(0,Z.useRef)(!1),v=(0,Z.useRef)(!1),y=(0,Z.useRef)(!1),b=(0,Z.useRef)(0),x=(0,Z.useRef)(null),S=(0,Z.useRef)(null),C=(0,Z.useCallback)(e=>{m.current=e,h.current=!0,s(!0),r(e),e>0&&(g.current=e),a(String(e>0?e:g.current))},[]),w=(0,Z.useCallback)(e=>{_.current||v.current?x.current=e:(x.current=null,C(e))},[C]),T=(0,Z.useCallback)(()=>{let e=x.current;return e!==null&&(x.current=null,C(e),!0)},[C]),E=(0,Z.useCallback)(()=>{S.current!==null&&(window.clearTimeout(S.current),S.current=null),p(null)},[]),D=(0,Z.useCallback)((e,t)=>{S.current!==null&&window.clearTimeout(S.current),p({tone:t?`err`:`ok`,message:e}),S.current=window.setTimeout(()=>{p(null),S.current=null},5e3)},[]);(0,Z.useEffect)(()=>()=>{S.current!==null&&window.clearTimeout(S.current)},[]);let O=(0,Z.useCallback)(()=>(h.current||l(!1),b.current),[]),k=(0,Z.useCallback)((e,t)=>{l(!1);let n=ku(e),r=Ou(_.current,v.current,t,b.current);r===`defer`?x.current=Tu(n):r===`apply`&&w(Tu(n))},[w]),A=(0,Z.useCallback)(e=>{h.current||_.current||v.current||(l(!1),C(Tu(ku(e))))},[C]),j=(0,Z.useCallback)(()=>{h.current||l(!0)},[]),M=(0,Z.useCallback)(async(n,r,i=!0)=>{if(v.current)return!1;v.current=!0,_.current=!1,E(),d(!0),b.current+=1;try{let a=await ju(e,n);return b.current+=1,a?(x.current=null,C(n),i&&D(t.updated,!1)):(T()||C(r),D(t.updateFailed,!0)),a}finally{v.current=!1,d(!1)}},[e,C,E,t.updateFailed,t.updated,T,D]),N=(0,Z.useCallback)(()=>{_.current=!1;let e=m.current;T()||a(String(e>0?e:g.current)),D(t.invalid,!0)},[t.invalid,T,D]),P=(0,Z.useCallback)(()=>{_.current=!1,y.current=!0,E();let e=m.current;T()||a(String(e>0?e:g.current))},[E,T]),F=(0,Z.useCallback)(async()=>{if(y.current)return y.current=!1,!0;if(!h.current||v.current)return!1;let e=m.current;_.current=!1;let t=Eu(i);return t===null?(N(),!1):t===e?(T()||a(String(t)),!0):M(t,e)},[i,T,N,M]),I=(0,Z.useCallback)(async()=>{if(!h.current||v.current)return!1;let e=m.current;_.current=!1;let t=Au(e,i,g.current),n=await M(t.threshold,e);return n?(g.current=t.lastEnabled,t.threshold===0&&a(String(t.lastEnabled)),n):!1},[i,M]);return{threshold:n,draft:i,hydrated:o,saving:u,loadError:c,feedback:f,beginServerRead:O,acceptServerRead:k,hydrateServerValue:A,rejectServerRead:j,setDraft:(0,Z.useCallback)(e=>{h.current&&(_.current=!0,y.current=!1,E(),a(e))},[E]),setEditing:(0,Z.useCallback)(e=>{_.current=e},[]),commit:F,cancel:P,toggle:I,retry:(0,Z.useCallback)(()=>{l(!1),E()},[E])}}function Nd({value:e,disabled:t=!1,selectId:r,onChange:i}){let a=n(),o=nu(e),s=a(`accountPool.priorityHint`),c=`${r}-hint`,l=eu.map(e=>({value:String(e),label:ou(a,e)})),u=iu(o)?l:[{value:String(o),label:ou(a,o)},...l];return(0,Q.jsxs)(`div`,{className:`codex-account-priority`,children:[(0,Q.jsx)(`label`,{className:`codex-account-priority-label`,htmlFor:r,children:a(`accountPool.priority`)}),(0,Q.jsx)(dn,{id:r,value:String(o),options:u,disabled:t,label:a(`accountPool.priorityAria`),describedBy:c,title:s,onChange:e=>i(nu(Number.parseInt(e,10)))}),(0,Q.jsx)(`span`,{id:c,className:`sr-only`,children:s})]})}function Pd({value:e}){let t=n(),r=nu(e);return r===0?null:(0,Q.jsx)(`span`,{className:`badge badge-muted`,children:ou(t,r)})}function Fd({summary:e,busy:t,onToggleAll:r}){let i=n(),a=(0,Z.useId)(),o=e.total>0&&e.enabled===e.total,s=e.enabled>0&&!o;return(0,Q.jsxs)(`span`,{className:`codex-credit-spend`,"aria-busy":t||void 0,children:[(0,Q.jsx)(`span`,{className:`codex-auth-credits-toggle__label`,children:i(`codexAuth.creditSpend`)}),(0,Q.jsx)(`button`,{type:`button`,className:`toggle ${o?`on`:``}`,"aria-label":i(`codexAuth.creditSpendAria`),"aria-describedby":a,"aria-pressed":s?`mixed`:o,title:i(`codexAuth.creditsAfterLimitHint`),disabled:t||e.total===0,onClick:()=>r(!o),children:(0,Q.jsx)(`span`,{className:`toggle-knob`})}),(0,Q.jsx)(`span`,{id:a,className:`sr-only`,children:i(`codexAuth.creditsAfterLimitHint`)})]})}function Id({accountLabel:e,enabled:t,saving:r,disabled:i,hint:a,onChange:o}){let s=n(),c=(0,Z.useId)(),l=t===!0,u=a??s(`codexAuth.creditsAfterLimitHint`);return(0,Q.jsxs)(`div`,{className:`codex-account-credits`,title:u,"aria-busy":r||void 0,children:[(0,Q.jsx)(`span`,{className:`codex-account-credits__label`,children:s(`codexAuth.creditsAfterLimit`)}),(0,Q.jsx)(`button`,{type:`button`,className:`toggle codex-account-credits__toggle ${l?`on`:``}`,disabled:i||r,"aria-pressed":l,"aria-label":s(`codexAuth.creditsAfterLimitAria`,{email:e}),"aria-describedby":c,onClick:()=>o(!l),children:(0,Q.jsx)(`span`,{className:`toggle-knob`})}),(0,Q.jsx)(`span`,{id:c,className:`sr-only`,children:u})]})}function Ld({enabled:e}){let t=n();return e===!0?(0,Q.jsx)(`span`,{className:`badge badge-amber`,title:t(`codexAuth.creditsAfterLimitHint`),children:t(`codexAuth.creditsOn`)}):null}function Rd({credits:e,t,locale:n}){if(!e)return null;let r=e.balance!==void 0&&/^\d+(\.\d+)?$/.test(e.balance)?Number(e.balance):void 0,i=r!==void 0&&Number.isFinite(r);if(!i&&e.unlimited!==!0&&e.overageLimitReached!==!0)return null;let a=new Intl.NumberFormat(n,{maximumFractionDigits:2}),o=i?a.format(r):``,s=e.overageLimitReached===!0,c=e.unlimited===!0,l=s?`${o?`${o} · `:``}${t(`codexAuth.creditsOverage`)}`:c?t(`codexAuth.creditsUnlimited`):o,u=!s&&(c||i&&r>0),d=e=>e?e.map(e=>a.format(e)).join(`–`):`—`,f=e.approxLocalMessages||e.approxCloudMessages?t(`codexAuth.creditsApprox`,{local:d(e.approxLocalMessages),cloud:d(e.approxCloudMessages)}):void 0;return(0,Q.jsxs)(`div`,{className:`quota-row quota-row--codex-credits`,title:f,children:[(0,Q.jsx)(`span`,{className:`quota-label`,children:t(`codexAuth.credits`)}),(0,Q.jsx)(`span`,{className:`quota-reset-label`,children:t(`codexAuth.creditsRemaining`)}),(0,Q.jsx)(`span`,{className:`quota-reset-day`}),(0,Q.jsx)(`span`,{className:`quota-reset-time`}),(0,Q.jsx)(`div`,{className:`bar`,"aria-hidden":`true`,children:(0,Q.jsx)(`div`,{className:`bar-fill bar-green`,style:{"--bar-scale":u?`1`:`0`}})}),(0,Q.jsx)(`span`,{className:`quota-val`,children:l})]})}function zd(e,t){return`${e??``}\0${JSON.stringify(t)}`}var Bd={month:`short`,day:`numeric`,year:`numeric`},Vd={month:`short`,day:`numeric`,year:`numeric`,hour:`2-digit`,minute:`2-digit`},Hd=new Map;function Ud(e,t){let n=zd(e,t),r=Hd.get(n);return r||(r=new Intl.DateTimeFormat(e,t),Hd.set(n,r)),r}function Wd(e,t){let n=new Date(e);return Number.isNaN(n.getTime())?`—`:Ud(t,Bd).format(n)}function Gd(e,t){let n=new Date(e);return Number.isNaN(n.getTime())?`—`:Ud(t,Vd).format(n)}var Kd=new Intl.NumberFormat(`en-US`,{style:`currency`,currency:`USD`,currencyDisplay:`narrowSymbol`,minimumFractionDigits:4,maximumFractionDigits:4});function qd(e,t){return!Number.isFinite(e)||e<0?`—`:`~${Kd.format(e)}`}function Jd(e,t){return Wd(e,t)}function Yd(e,t){return Gd(e,t)}function Xd(e){return Math.max(0,Math.ceil((new Date(e).getTime()-Date.now())/864e5))}function Zd({index:e,grantedAt:t,expiresAt:n,isNext:r,locale:i,t:a}){let o=Xd(n),s=o<=7;return(0,Q.jsxs)(`div`,{className:`credit-item${r?` credit-next`:``}`,children:[(0,Q.jsxs)(`div`,{className:`credit-item-head`,children:[(0,Q.jsx)(ft,{width:13}),(0,Q.jsx)(`span`,{className:`credit-item-label`,children:r?a(`codexAuth.creditNext`):a(`codexAuth.creditLabel`,{n:String(e+1)})}),r&&(0,Q.jsx)(`span`,{className:`badge badge-amber text-micro`,style:{padding:`1px 6px`},children:a(`codexAuth.creditNextBadge`)})]}),(0,Q.jsxs)(`div`,{className:`credit-item-dates`,children:[(0,Q.jsx)(`span`,{children:a(`codexAuth.creditGranted`,{date:Jd(t,i)})}),(0,Q.jsx)(`span`,{className:s?`credit-urgent`:``,children:a(`codexAuth.creditExpires`,{date:Yd(n,i),days:String(o)})})]})]})}function Qd({t:e,onUnpin:t}){return(0,Q.jsx)(`button`,{type:`button`,className:`badge badge-muted badge-clickable`,onClick:e=>{e.stopPropagation(),t()},title:`${e(`codexAuth.pinnedHint`)} ${e(`codexAuth.unpinHint`)}`,"aria-label":`${e(`codexAuth.pinned`)} — ${e(`codexAuth.unpinHint`)}`,children:e(`codexAuth.pinned`)})}function $d({account:e,onClick:t,t:n}){let r=e.quota?.resetCredits;return e.quota==null?(0,Q.jsxs)(`span`,{className:`badge badge-muted codex-ticket-badge-slot`,"aria-hidden":`true`,children:[(0,Q.jsx)(ft,{width:12}),`0`]}):r===void 0?null:(0,Q.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,Q.jsx)(ft,{width:12}),r]})}function ef({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,Q.jsx)(`span`,{className:`codex-auth-pause-label`,style:{minWidth:`${s}ch`},children:o})}function tf({pool:e,creditsVisible:t,loading:i=!1,activeId:a,accountModeState:o,switchActionLabel:s,threshold:c,onOpenReset:l,onSwitch:u,onTogglePause:d,pauseUpdatingId:f,pauseBusy:p,onPriorityChange:m,priorityUpdatingId:h,onAutoSwitchThresholdChange:g,autoSwitchDisabled:_,switchingId:v,pinnedId:y=null,onUnpin:b,onReauth:x,onEditAlias:S,onRemove:C,onToggleCreditsAfterLimit:w,creditsAfterLimitUpdatingId:T=null,onCopyDoctor:E,doctorCopyOutcomeFor:D}){let O=n(),{locale:k}=r(),A=e=>!e.paused&&a===e.id,j=zl(),[M,N]=(0,Z.useState)(new Set);return(0,Q.jsx)(Q.Fragment,{children:e.map(e=>{let n=t===!0&&e.credits!==void 0,r=e.health?.status,a=e.selectionExcludedReason===`plan_excluded`,P=!!e.needsReauth||Cl(r),F=Tl(r),I=e.health?.reason===`validation_pending`,L=Ol(O,e.health),R=kl(O,`codex`,e.id,e.health);return(0,Q.jsxs)(`div`,{className:`card ${A(e)?`card-active`:``}`,style:{marginBottom:8},children:[(0,Q.jsxs)(`div`,{className:`card-head`,children:[(0,Q.jsx)(`span`,{className:`dot ${P?`dot-amber`:A(e)?`dot-blue`:`dot-muted`}`}),(0,Q.jsx)(`strong`,{children:e.alias??e.email}),(0,Q.jsxs)(`span`,{className:`card-badges`,children:[e.plan&&(0,Q.jsx)(`span`,{className:`badge badge-green`,children:e.plan}),a&&(0,Q.jsx)(`span`,{className:`badge badge-muted`,title:O(`codexAuth.planExcludedHint`,{plan:e.selectionExcludedPlan??e.plan??``}),children:O(`codexAuth.planExcluded`)}),e.paused&&(0,Q.jsx)(`span`,{className:`badge badge-muted`,title:e.pauseDetails?hl(O,k,e.pauseDetails):O(`codexAuth.pausedHint`),children:O(`codexAuth.paused`)}),(0,Q.jsx)(Pd,{value:e.priority}),(0,Q.jsx)(Ld,{enabled:e.creditsAfterLimit}),e.id===y&&!e.paused&&(0,Q.jsx)(Qd,{t:O,onUnpin:()=>b(e)}),(0,Q.jsx)($d,{t:O,account:e,onClick:()=>l(e)}),L&&(0,Q.jsx)(`span`,{className:Sl(r),children:L}),P&&!L&&(0,Q.jsx)(`span`,{className:`badge badge-amber`,children:O(`codexAuth.needsReauth`)}),A(e)&&!a&&!P&&!F&&!I&&(0,Q.jsx)(`span`,{className:`badge badge-primary`,children:O(o===`direct`?`codexAuth.poolPrepared`:`codexAuth.nextSession`)})]}),!e.paused&&!a&&(!A(e)||y!==e.id)&&!P&&!F&&!I&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-account-switch`,onClick:()=>u(e),children:s}),P&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>x(e.id),children:O(`codexAuth.reauthenticate`)}),E&&El(r)&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-auth-action-btn`,onClick:()=>E(e.id),children:(0,Q.jsx)(`span`,{"aria-live":`polite`,children:Ml(O,D?.(e.id))})}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:()=>d(e),disabled:p,title:e.paused?O(`codexAuth.pausedHint`):void 0,"aria-label":e.paused?`${O(`codexAuth.resume`)}. ${O(`codexAuth.pausedHint`)}`:O(`codexAuth.pause`),children:[e.paused?(0,Q.jsx)(Ue,{width:14}):(0,Q.jsx)(H,{width:14}),(0,Q.jsx)(ef,{t:O,paused:e.paused,saving:f===e.id})]}),(0,Q.jsxs)(`details`,{className:`codex-account-more card-right`,open:M.has(e.id),onToggle:t=>{let n=t.currentTarget.open;N(t=>{let r=new Set(t);return n?r.add(e.id):r.delete(e.id),r})},children:[(0,Q.jsx)(`summary`,{className:`btn btn-ghost btn-sm`,"aria-label":`${O(`codexAuth.moreActions`)} — ${e.email}`,title:O(`codexAuth.moreActions`),children:`⋯`}),(0,Q.jsxs)(`div`,{className:`codex-account-more-body`,children:[(0,Q.jsxs)(`span`,{className:`mono text-caption muted`,children:[O(`prov.accountId`),`: `,_l(e.id)]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>j.copy(e.id,e.id),children:j.outcomeFor(e.id)===`copied`?O(`startup.copied`):O(`codexAuth.copyId`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void S(e),children:O(`prov.editAlias`)}),w&&(0,Q.jsx)(Id,{accountLabel:e.alias??e.email,enabled:e.creditsAfterLimit,saving:T===e.id,disabled:T!==null,onChange:t=>w(e,t)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn-icon btn-icon-danger`,"aria-label":`${O(`common.remove`)} — ${e.email}`,title:`${O(`common.remove`)} — ${e.email}`,onClick:t=>{t.stopPropagation(),C(e.id)},children:(0,Q.jsx)(xe,{width:14})})]})]})]}),(0,Q.jsxs)(`div`,{className:`codex-account-identity`,children:[(0,Q.jsxs)(`div`,{className:`codex-account-identity-copy`,children:[e.email,e.plan?` · ${e.plan}`:``]}),(0,Q.jsxs)(`div`,{className:`codex-account-controls`,children:[(nu(e.priority)!==0||M.has(e.id))&&(0,Q.jsx)(Nd,{value:e.priority,selectId:`codex-account-priority-${e.id}`,disabled:h!==null||v!==null,onChange:t=>m(e,t)}),(0,Q.jsx)(bl,{accountLabel:e.alias??e.email,globalThreshold:c,override:e.autoSwitchThresholdOverride,inputId:`codex-account-auto-switch-${e.id}`,disabled:_,onChange:t=>g(e,t)},e.id)]})]}),R&&(0,Q.jsx)(`div`,{className:`card-sub faint`,children:R}),F&&(0,Q.jsx)(`div`,{className:`card-sub faint`,children:O(`pws.healthCooldownHint`)}),P?(0,Q.jsx)(`div`,{className:`card-sub faint`,children:O(`codexAuth.tokenExpired`)}):!F&&(0,Q.jsx)(Q.Fragment,{children:(0,Q.jsx)(sc,{quota:e.quota,plan:e.plan,threshold:e.autoSwitchThresholdOverride??c,t:O,pending:e.quota==null&&(i||!n),afterWeekly:n&&!i?(0,Q.jsx)(Rd,{credits:e.credits,t:O,locale:k}):void 0})})]},e.id)})})}function nf({onReauth:e}){let t=n();return(0,Q.jsxs)(`div`,{className:`notice-warn`,style:{marginBottom:12,display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:12,flexWrap:`wrap`},children:[(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(Ne,{width:14}),` `,t(`codexAuth.tokenExpired`)]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:e,children:t(`codexAuth.reauthenticate`)})]})}function rf({confirm:e,mainEmail:t,accountModeState:r,switchingId:i,orderBusy:a=!1,threshold:o,unpin:s=!1,onCancel:c,onConfirm:l}){let u=n(),d=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{let e=d.current;e&&!e.open&&e.showModal()},[]);let f=(0,Z.useCallback)(e=>{e.preventDefault(),c()},[c]),p=he(e.quota,e.plan),m=o!==void 0&&o>0&&p!==null&&p>=o;return(0,Q.jsxs)(`dialog`,{ref:d,className:`modal-overlay`,"aria-labelledby":`codex-switch-title`,onCancel:f,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":u(`common.close`),tabIndex:-1,onClick:c}),(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),role:`document`,children:[(0,Q.jsx)(`h3`,{id:`codex-switch-title`,children:s?u(`codexAuth.unpinTitle`):r===`direct`?u(`codexAuth.preparePoolTitle`):e.id===`__main__`?u(`codexAuth.switchBack`):u(`codexAuth.switchTitle`)}),(0,Q.jsx)(`p`,{className:`modal-desc`,children:s?u(`codexAuth.unpinDesc`):r===`direct`?u(`codexAuth.preparePoolDesc`):e.id===`__main__`?u(`codexAuth.switchBackDesc`):u(`codexAuth.switchDesc`)}),(0,Q.jsxs)(`div`,{className:`card`,style:{margin:`12px 0`},children:[(0,Q.jsx)(`strong`,{children:e.id===`__main__`?t||u(`codexAuth.codexApp`):e.email}),e.plan&&(0,Q.jsx)(`span`,{className:`badge badge-green`,style:{marginLeft:8},children:e.plan})]}),!s&&e.id!==`__main__`&&(0,Q.jsxs)(`div`,{className:`notice-warn`,children:[(0,Q.jsx)(Ne,{width:14}),` `,u(`codexAuth.cacheWarning`)]}),!s&&m&&(0,Q.jsxs)(`div`,{className:`notice-warn`,"data-testid":`codex-switch-threshold-warning`,children:[(0,Q.jsx)(Ne,{width:14}),` `,u(`codexAuth.switchExceedsThresholdWarning`,{threshold:o})]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:c,children:u(`codexAuth.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!!i||a,onClick:l,children:u(i?`pws.accountSwitching`:s?`codexAuth.unpinAction`:r===`direct`?`codexAuth.prepareForPool`:`codexAuth.setAsNext`)})]})]})]})}function af({resetPopup:e,resetConfirm:t,creditDetails:n,creditDetailsLoading:i,redeeming:a,onClose:o,onShowConfirm:s,onCancelConfirm:c,onRedeem:l}){let{locale:u,t:d}=r(),f=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{let e=f.current;e&&!e.open&&e.showModal()},[]);let p=(0,Z.useCallback)(e=>{e.preventDefault(),o()},[o]);return(0,Q.jsxs)(`dialog`,{ref:f,className:`modal-overlay`,"aria-labelledby":`codex-reset-title`,onCancel:p,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":d(`common.close`),tabIndex:-1,onClick:o}),(0,Q.jsx)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),role:`document`,children:t?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{style:{textAlign:`center`,padding:`12px 0`},children:[(0,Q.jsx)(`div`,{className:`confirm-icon`,children:(0,Q.jsx)(Ne,{width:22})}),(0,Q.jsx)(`h3`,{id:`codex-reset-title`,children:d(`codexAuth.confirmResetTitle`)}),(0,Q.jsx)(`p`,{className:`modal-desc`,children:d(`codexAuth.confirmResetDesc`,{count:String(e.quota?.resetCredits??0)})}),n&&n[0]&&(0,Q.jsx)(`p`,{className:`faint text-label`,children:d(`codexAuth.confirmWhichCredit`,{date:Jd(n[0].granted_at,u)})}),(0,Q.jsx)(`p`,{className:`faint text-label`,children:d(`codexAuth.irreversible`)})]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:c,children:d(`codexAuth.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:l,disabled:a,children:d(a?`codexAuth.redeeming`:`codexAuth.useCredit`)})]})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`h3`,{id:`codex-reset-title`,children:[(0,Q.jsx)(ft,{width:16}),` `,d(`codexAuth.resetCreditsTitle`)]}),(0,Q.jsxs)(`div`,{className:`card-sub`,children:[e.email,e.plan?` · ${e.plan}`:``]}),(0,Q.jsx)(`div`,{style:{margin:`16px 0`},children:(e.quota?.resetCredits??0)>0?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{style:{marginBottom:12},children:d(`codexAuth.resetCreditsAvailable`,{count:String(e.quota?.resetCredits??0)})}),i&&(0,Q.jsx)(`p`,{className:`faint text-label`,children:d(`common.loading`)}),n&&n.length>0&&(0,Q.jsx)(`div`,{className:`credit-list`,children:n.map((e,t)=>(0,Q.jsx)(Zd,{index:t,grantedAt:e.granted_at,expiresAt:e.expires_at,isNext:t===0,locale:u,t:d},`${e.granted_at}:${e.expires_at}`))}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,style:{marginTop:12,width:`100%`},onClick:s,disabled:a,children:d(`codexAuth.useOneCredit`)}),(0,Q.jsx)(`p`,{className:`card-sub text-caption`,style:{marginTop:8,textAlign:`center`},children:d(`codexAuth.fifoNote`)})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`faint`,children:d(`codexAuth.noResetCredits`)}),(0,Q.jsx)(`p`,{className:`modal-desc`,children:d(`codexAuth.earnCreditsHint`)})]})})]})})]})}function of({t:e,main:t,isMainActive:n,accountModeState:i,threshold:a,switchActionLabel:o,onSwitch:s,onTogglePause:c,pauseUpdatingId:l,pauseBusy:u,onPriorityChange:d,priorityUpdatingId:f,onAutoSwitchThresholdChange:p,autoSwitchDisabled:m,switchingId:h,pinnedId:g=null,onUnpin:_,onOpenReset:v,onCopyDoctor:y,doctorCopyOutcomeFor:b,onManageMainHardLock:x,mainReauth:S,onToggleCreditsAfterLimit:C,creditsAfterLimitUpdatingId:w=null,creditsVisible:T,loading:E=!1}){let{locale:D}=r(),O=T===!0&&t?.credits!==void 0,k=e(`codexAuth.codexApp`),A=t?.id??`__main__`,j={id:`__main__`,email:t?.email||k,plan:t?.plan,isMain:!0,paused:t?.paused??!1,priority:t?.priority??0,autoSwitchThresholdOverride:t?.autoSwitchThresholdOverride??null,hasCredential:!0,quota:t?.quota??null,quotaAutoRefresh:t?.quotaAutoRefresh??{fiveHourAvailable:!1,weeklyAvailable:!1,fiveHourEnabled:!1,weeklyEnabled:!1}},M=!!t?.needsReauth||Cl(t?.health?.status),N=Tl(t?.health?.status),P=t?.mainAccountHardLock,F=P?.enabled===!0&&P.state===`blocked`,I=Ol(e,t?.health),L=t?kl(e,`codex`,A,t.health):null;return(0,Q.jsxs)(`div`,{className:`card ${n&&!F?`card-active`:``}`,style:{marginBottom:12},children:[(0,Q.jsxs)(`div`,{className:`card-head`,children:[(0,Q.jsx)(`span`,{className:`dot ${M||F?`dot-amber`:`dot-green`}`}),(0,Q.jsx)(`strong`,{children:e(`codexAuth.mainAccount`)}),(0,Q.jsxs)(`span`,{className:`card-badges`,children:[t?.plan&&(0,Q.jsx)(`span`,{className:`badge badge-green`,children:t.plan}),t?.paused&&(0,Q.jsx)(`span`,{className:`badge badge-muted`,title:e(`codexAuth.pausedHint`),children:e(`codexAuth.paused`)}),(0,Q.jsx)(Pd,{value:j.priority}),(0,Q.jsx)(Ld,{enabled:t?.creditsAfterLimit}),g===`__main__`&&!t?.paused&&(0,Q.jsx)(Qd,{t:e,onUnpin:()=>_(j)}),t&&(0,Q.jsx)($d,{t:e,account:{...t,id:`__main__`},onClick:()=>v({...t,id:`__main__`})}),I&&(0,Q.jsx)(`span`,{className:Sl(t?.health?.status),children:I}),M&&!I&&(0,Q.jsx)(`span`,{className:`badge badge-amber`,children:e(`codexAuth.needsReauth`)}),!t?.paused&&!F&&(0,Q.jsx)(`span`,{className:`badge ${n?`badge-primary`:`badge-muted`}`,children:e(n?i===`direct`?`codexAuth.poolPrepared`:`codexAuth.nextSession`:`codexAuth.current`)})]}),!t?.paused&&!F&&(!n||g!==`__main__`)&&!M&&!N&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-account-switch`,onClick:()=>s(j),children:o}),y&&El(t?.health?.status)&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-auth-action-btn`,onClick:()=>y(A),children:(0,Q.jsx)(`span`,{"aria-live":`polite`,children:Ml(e,b?.(A))})}),t&&(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:()=>c(j),disabled:u,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,Q.jsx)(Ue,{width:14}):(0,Q.jsx)(H,{width:14}),(0,Q.jsx)(ef,{t:e,paused:!!t.paused,saving:l===`__main__`})]}),t?.hasCredential&&C&&(0,Q.jsxs)(`details`,{className:`codex-account-more card-right`,children:[(0,Q.jsx)(`summary`,{className:`btn btn-ghost btn-sm`,"aria-label":`${e(`codexAuth.moreActions`)} — ${e(`codexAuth.mainAccount`)}`,title:e(`codexAuth.moreActions`),children:`⋯`}),(0,Q.jsx)(`div`,{className:`codex-account-more-body`,children:(0,Q.jsx)(Id,{accountLabel:t.alias??(t.email||e(`codexAuth.mainAccount`)),enabled:t.creditsAfterLimit,saving:w===`__main__`,disabled:w!==null,hint:e(`codexAuth.creditsAfterLimitMainHint`),onChange:e=>C(j,e)})})]}),(0,Q.jsxs)(`span`,{className:`card-right`,children:[(0,Q.jsx)(ct,{width:14}),` `,e(`codexAuth.appLogin`)]})]}),(0,Q.jsxs)(`div`,{className:`codex-account-identity`,children:[(0,Q.jsxs)(`div`,{className:`codex-account-identity-copy`,children:[t?.email||e(`codexAuth.appLogin`),t?.plan?` · ${t.plan}`:``]}),t&&(0,Q.jsxs)(`div`,{className:`codex-account-controls`,children:[(0,Q.jsx)(Nd,{value:j.priority,selectId:`codex-account-priority-${j.id}`,disabled:f!==null||h!==null,onChange:e=>d(j,e)}),(0,Q.jsx)(bl,{accountLabel:j.email,globalThreshold:a,override:j.autoSwitchThresholdOverride,inputId:`codex-account-auto-switch-${j.id}`,disabled:m,onChange:e=>p(j,e)},j.id)]})]}),P?.enabled&&(0,Q.jsxs)(`div`,{className:`codex-main-hard-lock-status${F?` is-blocked`:``}`,children:[(0,Q.jsx)(`p`,{role:`status`,children:e(F?`codexAuth.mainHardLockBlocked`:P.state===`ready`?`codexAuth.mainHardLockMonitoring`:`codexAuth.mainHardLockUnknown`,Nu(P.thresholds))}),x?(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:x,children:e(`codexAuth.mainHardLockManage`)}):(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>Xt(`codex-set`),children:e(`codexAuth.mainHardLockManage`)})]}),P?.externalUsage&&(0,Q.jsx)(`div`,{className:`codex-main-hard-lock-status is-blocked`,children:(0,Q.jsx)(`p`,{role:`status`,children:e(`codexAuth.mainExternalUsageWarning`)})}),L&&(0,Q.jsx)(`div`,{className:`card-sub faint`,children:L}),N&&(0,Q.jsx)(`div`,{className:`card-sub faint`,children:e(`pws.healthCooldownHint`)}),M?(0,Q.jsxs)(`div`,{className:`card-sub faint`,children:[(0,Q.jsx)(`p`,{role:`status`,children:e(`codexAuth.mainTokenExpired`)}),S&&(S.state.phase===`idle`||S.state.phase===`failed`||S.state.phase===`cancelled`)&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-auth-action-btn`,onClick:()=>{S.start()},children:e(`codexAuth.mainReauthDevice`)}),S.state.phase===`failed`&&(0,Q.jsxs)(`span`,{className:`badge badge-amber`,children:[e(`codexAuth.mainReauthFailed`),`: `,S.state.code]})]}),S&&S.state.phase===`starting`&&(0,Q.jsx)(`span`,{className:`faint`,children:e(`codexAuth.mainReauthPending`)}),S&&(S.state.phase===`pending`||S.state.phase===`committing`)&&(0,Q.jsxs)(`span`,{className:`codex-main-reauth-pending`,children:[(0,Q.jsx)(Hl,{hint:{url:S.state.verificationUrl,deviceCode:S.state.deviceCode}}),(0,Q.jsx)(`span`,{className:`faint`,children:e(`codexAuth.mainReauthPending`)}),S.state.cancelFailed&&(0,Q.jsx)(`span`,{role:`status`,className:`badge badge-amber`,children:e(`codexAuth.mainReauthFailed`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-auth-action-btn`,onClick:()=>{S.cancel()},children:e(`codexAuth.mainReauthCancel`)})]}),S&&S.state.phase===`succeeded`&&(0,Q.jsx)(`span`,{className:`badge badge-primary`,children:e(`codexAuth.mainReauthSucceeded`)})]}):!N&&(0,Q.jsx)(Q.Fragment,{children:(0,Q.jsx)(sc,{quota:t?.quota??null,plan:t?.plan,threshold:j.autoSwitchThresholdOverride??a,t:e,pending:t!=null&&t.quota==null&&(E||!O),afterWeekly:O&&!E?(0,Q.jsx)(Rd,{credits:t?.credits,t:e,locale:D}):void 0})})]})}function sf({t:e,embedded:t,refreshingQuota:n,pausingExhausted:r,pauseBusy:i,actionFeedback:a,actionFeedbackTone:o,onRefresh:s,onPauseExhausted:c,creditsVisible:l,creditsBusy:u,onToggleCredits:d,creditSpendControl:f}){return(0,Q.jsxs)(`div`,{className:t?`row`:`page-head codex-auth-page-head`,style:t?{justifyContent:`flex-end`,marginBottom:8}:void 0,children:[!t&&(0,Q.jsx)(`h2`,{className:`page-title`,children:e(`nav.codexAuth`)}),(0,Q.jsxs)(`div`,{className:t?`row`:`codex-auth-page-head__actions`,children:[(0,Q.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??``}),l!==void 0&&d&&(0,Q.jsxs)(`span`,{className:`codex-auth-credits-toggle`,children:[(0,Q.jsx)(`span`,{className:`codex-auth-credits-toggle__label`,children:e(`codexAuth.creditsToggle`)}),(0,Q.jsx)(`button`,{type:`button`,className:`toggle ${l?`on`:``}`,onClick:d,disabled:!!u,"aria-pressed":l,"aria-label":e(`codexAuth.creditsToggle`),title:e(`codexAuth.creditsToggleHint`),children:(0,Q.jsx)(`span`,{className:`toggle-knob`})})]}),f,t&&(0,Q.jsx)(cf,{t:e,refreshingQuota:n,pausingExhausted:r,pauseBusy:i,onRefresh:s,onPauseExhausted:c})]})]})}function cf({t:e,refreshingQuota:t,pausingExhausted:n,pauseBusy:r,onRefresh:i,onPauseExhausted:a}){return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:a,disabled:t||n||!!r,children:[(0,Q.jsx)(H,{width:14}),` `,e(n?`codexAuth.pausingExhausted`:`codexAuth.pauseExhausted`)]}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:i,disabled:t||n||!!r,children:[(0,Q.jsx)(ae,{width:14}),` `,e(t?`codexAuth.refreshingQuota`:`codexAuth.refreshQuota`)]})]})}function lf(e){return(0,Q.jsx)(`div`,{className:`codex-auth-actions-row`,children:(0,Q.jsx)(cf,{...e})})}function uf({t:e,loadState:t,refreshFailed:n,accountsCount:r,onRetry:i}){return t===`loading`&&r===0?(0,Q.jsxs)(`div`,{className:`codex-auth-load-skeleton`,role:`status`,"aria-live":`polite`,"aria-busy":`true`,children:[(0,Q.jsxs)(`div`,{className:`card codex-auth-load-skeleton__main`,style:{marginBottom:12},"aria-hidden":`true`,children:[(0,Q.jsxs)(`div`,{className:`card-head`,children:[(0,Q.jsx)(`span`,{className:`dot dot-muted`}),(0,Q.jsx)(`strong`,{children:e(`codexAuth.mainAccount`)}),(0,Q.jsxs)(`span`,{className:`card-badges`,children:[(0,Q.jsxs)(`span`,{className:`badge badge-muted codex-ticket-badge-slot`,"aria-hidden":`true`,children:[(0,Q.jsx)(ft,{width:12}),`0`]}),(0,Q.jsx)(`span`,{className:`badge badge-primary`,children:e(`codexAuth.nextSession`)})]}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,tabIndex:-1,disabled:!0,children:[(0,Q.jsx)(H,{width:14}),` `,e(`codexAuth.pause`)]}),(0,Q.jsxs)(`span`,{className:`card-right`,children:[(0,Q.jsx)(ct,{width:14}),` `,e(`codexAuth.appLogin`)]})]}),(0,Q.jsxs)(`div`,{className:`card-sub`,children:[(0,Q.jsx)(`span`,{className:`codex-auth-load-skeleton__strut`,children:e(`codexAuth.appLogin`)}),(0,Q.jsx)(`span`,{className:`codex-auth-load-skeleton__line codex-auth-load-skeleton__line--sub`})]}),(0,Q.jsx)(sc,{quota:null,threshold:0,t:e,pending:!0})]}),(0,Q.jsxs)(`div`,{className:`section-sep`,"aria-hidden":`true`,children:[(0,Q.jsx)(`span`,{className:`section-label`,children:e(`codexAuth.accountPool`)}),(0,Q.jsx)(`div`,{className:`sep-line`}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,tabIndex:-1,disabled:!0,children:[(0,Q.jsx)(I,{width:14}),` `,e(`codexAuth.add`)]})]}),(0,Q.jsx)(`div`,{className:`empty codex-auth-pool-empty codex-auth-load-skeleton__empty`,"aria-hidden":`true`,children:(0,Q.jsx)(`div`,{className:`title`,children:e(`codexAuth.noPool`)})}),(0,Q.jsx)(`span`,{className:`sr-only`,children:e(`pws.accountsLoading`)})]}):t===`error`?(0,Q.jsxs)(`div`,{className:`pwi-auth-state pwi-auth-state--error`,role:`alert`,children:[(0,Q.jsx)(`span`,{children:e(`codexAuth.loadFailed`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:i,children:e(`pws.retryAccounts`)})]}):n&&r>0?(0,Q.jsxs)(`div`,{className:`pwi-auth-state pwi-auth-state--stale`,role:`status`,children:[(0,Q.jsx)(`span`,{children:e(`codexAuth.accountsRefreshFailed`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:i,children:e(`pws.retryAccounts`)})]}):null}function df(e,t){return t===void 0?e(`codexAuth.resetSuccessGeneric`):e(`codexAuth.resetSuccess`,{remaining:String(t)})}async function ff(e,t,n,r){try{let i=await yn(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:df(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 pf({windows:e,ready:t,busy:r,loadError:i,feedback:a,onToggle:o,onRetry:s}){let c=n(),l=e.filter(e=>e.available),u=e.some(e=>e.enabled),d=l.length?l.every(e=>e.enabled):u,f=u&&!d,p=l.length===0&&!u,m=r?c(`common.saving`):i?c(`codexAuth.quotaAutoRefreshLoadFailed`):t?a?.message??(p?c(`codexAuth.quotaAutoRefreshEmpty`):f?c(`codexAuth.quotaAutoRefreshMixed`):``):c(`common.loading`),h=!r&&(i||a?.failed);return(0,Q.jsxs)(`div`,{id:`codex-quota-activation`,className:`card card-row codex-quota-activation`,"aria-busy":r||!t&&!i||void 0,children:[(0,Q.jsxs)(`div`,{className:`codex-quota-activation__copy`,children:[(0,Q.jsx)(`strong`,{children:c(`codexAuth.quotaAutoRefresh`)}),(0,Q.jsx)(`div`,{id:`codex-quota-activation-desc`,className:`card-sub`,children:c(`codexAuth.quotaAutoRefreshAllHint`)}),m&&(0,Q.jsx)(`div`,{className:`card-sub${h?` is-error`:``}`,role:h?`alert`:`status`,children:m})]}),(0,Q.jsxs)(`div`,{className:`codex-quota-activation__controls`,children:[h&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:r,onClick:s,children:c(`common.retry`)}),(0,Q.jsx)(`button`,{type:`button`,className:`toggle ${t&&d?`on`:``}`,"aria-label":c(`codexAuth.quotaAutoRefresh`),"aria-describedby":`codex-quota-activation-desc`,"aria-pressed":t?f?`mixed`:d:void 0,disabled:!t||r||p,onClick:()=>o(!d),children:(0,Q.jsx)(`span`,{className:`toggle-knob`})})]})]})}function mf(e){return{enabled:e.filter(e=>e.creditsAfterLimit===!0).length,total:e.length}}function hf(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 gf(e,t){return e.flatMap(e=>{let n=e.isMain?`__main__`:e.id,r=e.quotaAutoRefresh??at(e.quota);return[`fiveHour`,`weekly`].map(e=>({id:n,window:e,available:r[e===`fiveHour`?`fiveHourAvailable`:`weeklyAvailable`],enabled:t[n]?.[e]===!0}))})}function _f(e){let t=n(),r=(0,Z.useId)(),i=(0,Z.useRef)(null),a=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{let e=document.activeElement;return a.current?.focus(),()=>{e?.isConnected&&typeof e.focus==`function`&&e.focus()}},[]);let o=e.selection?.status===`pending`,s=e.failed||!e.providerKnown,c=e.loading?t(`prov.modelsNoticeChecking`):s?t(`prov.modelsNoticeFailed`):o?t(`prov.modelsNoticePending`):e.initialRegistration&&e.selection?.status===`all-off`?t(`prov.modelsNoticeOff`):t(`prov.modelsNoticeReady`);return(0,Q.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":r,onKeyDown:t=>{if(t.key===`Escape`&&(t.preventDefault(),t.stopPropagation(),e.onClose()),t.key!==`Tab`)return;let n=i.current?.querySelectorAll(`button:not([disabled])`),r=n?.[0],a=n?.[n.length-1];t.shiftKey&&document.activeElement===r?(t.preventDefault(),a?.focus()):!t.shiftKey&&document.activeElement===a&&(t.preventDefault(),r?.focus())},children:(0,Q.jsxs)(`div`,{className:`modal-card`,ref:i,children:[(0,Q.jsx)(`div`,{className:`modal-head`,children:(0,Q.jsx)(`h2`,{id:r,style:{fontSize:`var(--text-subtitle)`,margin:0},children:t(`prov.modelsNoticeTitle`)})}),(0,Q.jsx)(`p`,{children:(0,Q.jsx)(`strong`,{style:{overflowWrap:`anywhere`},children:e.provider})}),(0,Q.jsx)(`p`,{role:`status`,"aria-live":`polite`,children:c}),e.initialRegistration&&e.selection?.modelCount!==void 0&&(0,Q.jsx)(`p`,{className:`muted`,children:t(`prov.modelsNoticeCount`,{count:e.selection.modelCount})}),e.catalogRefreshPending&&(0,Q.jsx)(`p`,{className:`muted`,role:`status`,children:t(`codexAuth.catalogRefreshPending`)}),!e.loading&&(o||s)&&e.onRetry&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>{e.onRetry?.(),a.current?.focus()},children:t(`common.retry`)}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:e.onClose,children:t(`common.close`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,ref:a,onClick:e.onOpenModels,children:t(`prov.modelsNoticeOpen`)})]})]})})}var vf=`ocx doctor`;function yf({apiBase:e,accountModeState:t=null,banner:r=null,embedded:i=!1,onActiveNeedsReauthChange:a,controller:o,advancedExtras:s=null,hasMainHardLockSetting:c=!1}){let l=n(),u=Md(e,{updated:l(`codexAuth.autoSwitchUpdated`),updateFailed:l(`codexAuth.autoSwitchUpdateFailed`),invalid:l(`codexAuth.autoSwitchThresholdInvalid`)}),[d,f]=(0,Z.useState)(null),{beginServerRead:p,acceptServerRead:m,rejectServerRead:h,hydrateServerValue:g}=u,_=Lu(e,!o),v=o??_,{accounts:y,activeId:b,loadState:x,refreshFailed:S,switchingId:C,pauseUpdatingId:w,priorityUpdatingId:T,autoSwitchUpdatingId:E,pausingExhausted:D,activePinnedId:O,load:k}=v,A=Ku(e,()=>{k()}),j=A.state.phase===`starting`||A.state.phase===`pending`||A.state.phase===`committing`,[N,P]=(0,Z.useState)(null),[F,L]=(0,Z.useState)(null),[R,z]=(0,Z.useState)(!1),[B,V]=(0,Z.useState)(null),[H,U]=(0,Z.useState)(!1),ee=(0,Z.useRef)(!1),W=(0,Z.useCallback)(()=>{let e=document.getElementById(`codex-main-hard-lock-setting`);e?.focus(),e?.scrollIntoView({block:`nearest`})},[]);(0,Z.useEffect)(()=>{H&&ee.current&&(ee.current=!1,W())},[H,W]);let te=()=>{H?W():(ee.current=!0,U(!0))},[G,ne]=(0,Z.useState)(null),[K,re]=(0,Z.useState)(null),[q,J]=(0,Z.useState)(null),Y=(0,Z.useRef)(null),[ie,X]=(0,Z.useState)(!1),[ae,oe]=(0,Z.useState)(null),[se,ce]=(0,Z.useState)(null),le=(0,Z.useRef)(0),ue=(0,Z.useRef)(null),de=(0,Z.useRef)(null),[fe,pe]=(0,Z.useState)(0),[me,he]=(0,Z.useState)(e),[ge,_e]=(0,Z.useState)(null),ve=(0,Z.useRef)(null),ye=se?.apiBase===e&&se.revision===fe?se:null,be=ye?.settings??null,xe=ye?.error??!1,Se=ae===e;me!==e&&(he(e),pe(e=>e+1),ce(null),oe(null),_e(null));let[Ce,we]=(0,Z.useState)(null),[Te,Ee]=(0,Z.useState)(!1),[De,Oe]=(0,Z.useState)(!1),[ke,Ae]=(0,Z.useState)(null),[je,Me]=(0,Z.useState)(!1),Ne=zl(),Pe=(0,Z.useCallback)((e,t=`ok`)=>{Y.current&&clearTimeout(Y.current),re(e),J(t),Y.current=setTimeout(()=>{re(null),J(null),Y.current=null},5e3)},[]);(0,Z.useEffect)(()=>()=>{Y.current&&clearTimeout(Y.current)},[]);let Fe=Ru(e,k,Pe,l,{revision:fe,onRead:(t,n)=>{let r=le.current;t.then(t=>{n.aborted||le.current!==r||(ce({apiBase:e,revision:fe,settings:hf(t),error:!1}),oe(null))}).catch(()=>{n.aborted||le.current!==r||(ce({apiBase:e,revision:fe,settings:null,error:!0}),oe(null))})}}),Ie=(0,Z.useCallback)(e=>{Ne.copy(vf,e)},[Ne]),{subscribeLoadObserver:Le,readLastThreshold:Re}=v;(0,Z.useEffect)(()=>Le({beginActiveRead:p,acceptActiveRead:m,rejectActiveRead:h}),[Le,p,m,h]),(0,Z.useEffect)(()=>{let e=Re();e!==void 0&&g(e)},[Re,g]),(0,Z.useEffect)(()=>{if(!R&&!j)return;let e=v.pauseRefresh();return()=>v.resumeRefresh(e)},[v,R,j]);let ze=b&&b!==`__main__`?y.find(e=>e.id===b):null,Be=!ze?.paused&&wl(ze);(0,Z.useEffect)(()=>{a?.(Be)},[Be,a]);let Ve=(0,Z.useCallback)(e=>{ne(e),z(!0)},[]),He=(0,Z.useCallback)(()=>{z(!1),ne(null)},[]),Ue=(0,Z.useCallback)(e=>{v.syncAfterAccountAdded(),Pe(l(e.validationPending?`pws.healthLabel.validationPending`:e.catalogRefreshPending?`codexAuth.catalogRefreshPending`:`codexAuth.accountAdded`),e.validationPending||e.catalogRefreshPending?`warn`:`ok`),He(),V(e.validationPending?null:{catalogRefreshPending:e.catalogRefreshPending})},[He,v,Pe,l]),We=async e=>{let n=await v.switchAccount(e);if(!n.ok){if(n.reason===`busy`)return;Pe(l(`codexAuth.switchFailed`),`err`);return}P(null);let r=n.activeId,i=r&&r!==`__main__`?y.find(e=>e.id===r)?.email??l(`pws.accountOrdinal`,{count:`1`}):l(`codexAuth.mainAccount`);Pe(l(t===`direct`?`codexAuth.poolPreparedToast`:`codexAuth.switched`,{email:i}))},Ge=async()=>{if(!F)return;let e=await v.switchAccount(null,{expectedPinnedAccountId:F.id});if(e.ok)L(null),Pe(l(`codexAuth.unpinned`),`ok`);else{if(e.reason===`busy`)return;L(null),Pe(l(e.reason===`pin_changed`?`codexAuth.unpinChanged`:`codexAuth.unpinFailed`),`err`)}},Ke=async e=>{let t=await ga({message:l(`prov.aliasPrompt`),initialValue:e.alias??``,maxLength:80,validate:e=>Pl(e,l)});if(t===null)return;let n=await v.saveAlias(e.id,t);Pe(l(n.ok?`prov.aliasSaved`:`prov.aliasSaveFailed`),n.ok?`ok`:`err`)},qe=async e=>{let t=!e.paused,n=await v.setAccountPaused(e.id,t);(n.ok||n.reason!==`busy`)&&(P(t=>t?.id===e.id?null:t),Pe(l(n.ok?t?`codexAuth.pauseSucceeded`:`codexAuth.resumeSucceeded`:t?`codexAuth.pauseFailed`:`codexAuth.resumeFailed`,{email:e.alias??e.email}),n.ok?`ok`:`err`))},Je=async e=>{let t=await v.setAllCreditsAfterLimit(e);(t.ok||t.reason!==`busy`)&&Pe(l(t.ok?e?`codexAuth.creditsAllOnSucceeded`:`codexAuth.creditsAllOffSucceeded`:`codexAuth.creditsAllUpdateFailed`),t.ok?`ok`:`err`)},Ye=async(e,t)=>{if(t===e.priority)return;let n=await v.setAccountPriority(e.id,t);(n.ok||n.reason!==`busy`)&&Pe(l(n.ok?`accountPool.priorityUpdated`:`accountPool.priorityUpdateFailed`,{email:e.alias??e.email}),n.ok?`ok`:`err`)},Xe=async(e,t)=>{if(t===e.autoSwitchThresholdOverride)return!0;let n=await v.setAccountAutoSwitchThreshold(e.id,t);return!n.ok&&n.reason===`busy`?!1:(Pe(l(n.ok?`accountPool.autoSwitchUpdated`:`accountPool.autoSwitchUpdateFailed`,{email:e.alias??e.email}),n.ok?`ok`:`err`),n.ok)},Ze=async(e,t)=>{let n=await v.setAccountCreditsAfterLimit(e.id,t);(n.ok||n.reason!==`busy`)&&Pe(l(n.ok?t?`codexAuth.creditsOnSucceeded`:`codexAuth.creditsOffSucceeded`:`codexAuth.creditsUpdateFailed`,{email:e.alias??e.email}),n.ok?`ok`:`err`)},Qe=async e=>{let t=y.find(t=>t.id===e)?.email??l(`pws.accountOrdinal`,{count:`1`});if(!await ha({message:l(`codexAuth.removeConfirm`,{id:t}),confirmLabel:l(`common.remove`),tone:`danger`}))return;let n=await v.removeAccount(e);n.ok?n.catalogRefreshPending&&Pe(l(`codexAuth.catalogRefreshPending`),`warn`):Pe(l(`codexAuth.removeFailed`),`err`)},$e=async()=>{X(!0);try{let e=await k(!0,{validatePending:!0});Pe(l(e?`codexAuth.quotaRefreshed`:`codexAuth.quotaRefreshFailed`),e?`ok`:`err`)}finally{X(!1)}},et=async t=>{let n=ue.current;if(de.current||!n||n.signal.aborted||be===null||x!==`ready`)return;let r=M(3e4);de.current=r,le.current+=1;let i=()=>ue.current===n&&!n.signal.aborted,a=gf(y,be);oe(e),_e(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=M(15e3);de.current=n;try{let r=await fetch(`${e}/api/settings`,{signal:n.signal});if(!r.ok)throw Error(`read`);let s=hf(await r.json());if(!i())return;o||=a.some(e=>(!t||e.available)&&s[e.id]?.[e.window]===!0!==t),ce({apiBase:e,revision:fe,settings:s,error:!1})}catch{if(!i())return;o=!0,ce({apiBase:e,revision:fe,settings:null,error:!0})}finally{n.clear()}if(!i())return;ve.current=o?{apiBase:e,enabled:t}:null,_e({apiBase:e,message:l(o?`codexAuth.quotaAutoRefreshPartial`:`codexAuth.quotaAutoRefreshUpdated`),failed:o})}finally{r.clear(),i()&&(de.current=null,oe(null))}};(0,Z.useEffect)(()=>{let e=new AbortController;return ue.current=e,()=>{e.abort(),de.current?.controller.abort(),de.current?.clear(),de.current=null}},[e,fe]);let tt=async()=>{let e=await v.pauseExhaustedAccounts();(e.ok||e.reason!==`busy`)&&Pe(e.ok?e.pausedCount>0?l(`codexAuth.pauseExhaustedSucceeded`,{count:String(e.pausedCount)}):l(`codexAuth.pauseExhaustedNone`):l(`codexAuth.pauseExhaustedFailed`),e.ok?`ok`:`err`)},nt=async t=>{we(t),Ee(!1),Ae(null),Me(!0);try{let n=await yn(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());Ae(e)}}catch{}finally{Me(!1)}},rt=async t=>{Oe(!0);try{let n=await ff(e,t,l,k);n.close&&(we(null),Ee(!1)),n.toast&&Pe(n.toast,n.ok?`ok`:`err`)}finally{Oe(!1)}},it=y.find(e=>e.isMain),at=y.filter(e=>!e.isMain),ot=mf([...it?.hasCredential?[it]:[],...at]),st=!it?.paused&&(!b||b===`__main__`),ct=l(t===`direct`?`codexAuth.prepareForPool`:`codexAuth.setAsNext`),lt=w!==null||D,ut=u.threshold,dt=!u.hydrated||E!==null,ft=!i;return(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(sf,{t:l,embedded:i,creditsVisible:Fe.visible,creditsBusy:Fe.busy,onToggleCredits:()=>{Fe.toggle()},creditSpendControl:x===`loading`&&y.length===0?void 0:(0,Q.jsx)(Fd,{summary:ot,busy:v.creditsAfterLimitUpdatingId!==null,onToggleAll:e=>{Je(e)}}),refreshingQuota:ie,actionFeedback:K,actionFeedbackTone:q,pausingExhausted:D,pauseBusy:lt,onRefresh:()=>{$e()},onPauseExhausted:()=>{tt()}}),r,!i&&(0,Q.jsx)(lf,{t:l,refreshingQuota:ie,pausingExhausted:D,pauseBusy:lt,onRefresh:()=>{$e()},onPauseExhausted:()=>{tt()}}),(0,Q.jsx)(uf,{t:l,loadState:x,refreshFailed:S,accountsCount:y.length,onRetry:()=>{k()}}),(x!==`loading`||y.length!==0)&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(of,{t:l,main:it,creditsVisible:Fe.visible,loading:x===`loading`,isMainActive:st,accountModeState:t,threshold:ut,switchActionLabel:ct,onSwitch:P,onUnpin:L,onTogglePause:qe,pauseUpdatingId:w,pauseBusy:lt,onPriorityChange:(e,t)=>{Ye(e,t)},priorityUpdatingId:T,onAutoSwitchThresholdChange:Xe,autoSwitchDisabled:dt,onToggleCreditsAfterLimit:(e,t)=>{Ze(e,t)},creditsAfterLimitUpdatingId:v.creditsAfterLimitUpdatingId,switchingId:C,pinnedId:O,onOpenReset:nt,onCopyDoctor:ft?Ie:void 0,doctorCopyOutcomeFor:ft?Ne.outcomeFor:void 0,onManageMainHardLock:c?te:void 0,mainReauth:A}),(0,Q.jsx)(Sd,{apiBase:e,disabled:j,onChanged:()=>k(!1)}),(0,Q.jsxs)(`div`,{className:`section-sep`,children:[(0,Q.jsx)(`span`,{className:`section-label`,children:l(`codexAuth.accountPool`)}),(0,Q.jsx)(`div`,{className:`sep-line`}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,onClick:()=>z(!0),children:[(0,Q.jsx)(I,{width:14}),` `,l(`codexAuth.add`)]})]}),Be&&ze&&(0,Q.jsx)(nf,{onReauth:()=>Ve(ze.id)}),at.length===0&&(0,Q.jsx)(fn,{title:l(`codexAuth.noPool`)}),(0,Q.jsx)(tf,{pool:at,creditsVisible:Fe.visible,loading:x===`loading`,activeId:b,accountModeState:t,switchActionLabel:ct,threshold:ut,onOpenReset:nt,onSwitch:P,onUnpin:L,onTogglePause:qe,pauseUpdatingId:w,pauseBusy:lt,onPriorityChange:(e,t)=>{Ye(e,t)},priorityUpdatingId:T,onAutoSwitchThresholdChange:Xe,autoSwitchDisabled:dt,onToggleCreditsAfterLimit:(e,t)=>{Ze(e,t)},creditsAfterLimitUpdatingId:v.creditsAfterLimitUpdatingId,switchingId:C,pinnedId:O,onReauth:Ve,onEditAlias:Ke,onRemove:Qe,onCopyDoctor:ft?Ie:void 0,doctorCopyOutcomeFor:ft?Ne.outcomeFor:void 0})]}),(0,Q.jsx)(Ad,{apiBase:e,subscribeLoadObserver:v.subscribeLoadObserver,readLastActive:v.readLastActive,onStrategyResolved:f,threshold:u.threshold}),(0,Q.jsxs)(jd,{t:l,open:H,onToggle:()=>U(e=>!e),children:[(0,Q.jsx)(pf,{windows:gf(y,be??{}),ready:be!==null&&x===`ready`,busy:Se,loadError:xe||x===`error`,feedback:ge?.apiBase===e?ge:null,onToggle:e=>{et(e)},onRetry:()=>{xe||be===null||x!==`ready`?(pe(e=>e+1),k()):ve.current?.apiBase===e&&et(ve.current.enabled)}}),d!==null&&(0,Q.jsx)(Td,{threshold:u.threshold,draft:u.draft,strategy:d,hydrated:u.hydrated,saving:u.saving,loadError:u.loadError,feedback:u.feedback,onDraftChange:u.setDraft,onEditingChange:u.setEditing,onCommit:u.commit,onCancel:u.cancel,onToggle:u.toggle,onRetry:()=>{u.retry(),k()}}),s]}),N&&(0,Q.jsx)(rf,{confirm:N,mainEmail:it?.email,accountModeState:t,switchingId:C,orderBusy:T!==null,threshold:d&&d!==`round-robin`?ut:void 0,onCancel:()=>P(null),onConfirm:()=>{We(N.id===`__main__`?`__main__`:N.id)}}),F&&(0,Q.jsx)(rf,{unpin:!0,confirm:F,mainEmail:it?.email,accountModeState:t,switchingId:C,orderBusy:T!==null,onCancel:()=>L(null),onConfirm:()=>{Ge()}}),Ce&&(0,Q.jsx)(af,{resetPopup:Ce,resetConfirm:Te,creditDetails:ke,creditDetailsLoading:je,redeeming:De,onClose:()=>{we(null),Ee(!1),Ae(null)},onShowConfirm:()=>Ee(!0),onCancelConfirm:()=>Ee(!1),onRedeem:()=>{rt(Ce.id)}}),R&&(0,Q.jsx)($l,{apiBase:e,reauthAccountId:G??void 0,onClose:He,onAdded:Ue}),B&&(0,Q.jsx)(_f,{provider:`openai`,loading:!1,failed:!1,providerKnown:!0,initialRegistration:!1,catalogRefreshPending:B.catalogRefreshPending,onClose:()=>V(null),onOpenModels:()=>{V(null),Xt(`models`)}})]})}var bf=`https://opencodex.me/guides/claude-code/#claude-oauth-account-pool-experimental`,xf={"five-hour":`accountPool.quotaWindowFiveHour`,weekly:`accountPool.quotaWindowWeekly`,"max-utilization":`accountPool.quotaWindowMaxUtilization`};function Sf(e,t,n,r){let i=e(xf[r]);return t===`round-robin`?e(`anthropicPool.enabledRoundRobinDesc`):t===`fill-first`?n===0?e(`anthropicPool.enabledFillFirstNoThresholdDesc`):e(`anthropicPool.enabledFillFirstDesc`,{threshold:n,window:i}):n===0?e(`anthropicPool.enabledNoProactiveDesc`,{window:i}):e(`anthropicPool.enabledDesc`,{threshold:n,window:i})}function Cf({apiBase:e,provider:t=`anthropic`,accountCount:r,onThresholdChange:i}){let a=n(),[o,s]=(0,Z.useState)(null),[c,l]=(0,Z.useState)(`80`),[u,d]=(0,Z.useState)(`1`),[f,p]=(0,Z.useState)(!1),[m,h]=(0,Z.useState)(null),[g,_]=(0,Z.useState)(!1),[v,y]=(0,Z.useState)(!1),[b,x]=(0,Z.useState)(!1),[S,C]=(0,Z.useState)(0),[w,T]=(0,Z.useState)(!1),E=(0,Z.useRef)(i),D=(0,Z.useRef)(!0),O=(0,Z.useRef)(e),k=(0,Z.useRef)(t),A=(0,Z.useRef)(null);(0,Z.useLayoutEffect)(()=>(D.current=!0,()=>{D.current=!1,A.current?.abort(),A.current=null}),[]),(0,Z.useLayoutEffect)(()=>{E.current=i,O.current=e,k.current=t},[e,t,i]),(0,Z.useEffect)(()=>{let n=!1,r=new AbortController;return Promise.resolve().then(()=>bu(e,t,(e,t)=>fetch(e,t),{signal:r.signal})).then(e=>{if(!e)throw Error(`load`);return e}).then(e=>{if(n)return;let t=typeof e.autoSwitchThreshold==`number`?e.autoSwitchThreshold:80,r=hu(e.stickyLimit);s({enabled:e.enabled===!0,threshold:t,strategy:pu(e.strategy),stickyLimit:r,quotaWindow:mu(e.quotaWindow),nativeMessages:e.nativeMessages===!0}),l(String(t)),E.current?.(t),d(String(r)),_(!1),x(!1),h(null),y(!1),T(!1)}).catch(()=>{n||r.signal.aborted||(_(!0),T(!1))}),()=>{n=!0,r.abort()}},[e,t,S]);let j=(0,Z.useCallback)(async n=>{let r=e,i=t;A.current?.abort();let c=new AbortController;A.current=c;let u=()=>D.current&&O.current===r&&k.current===i&&A.current===c&&!c.signal.aborted,f=o;p(!0),h(null),y(!1);try{let e=await Su(r,i,{enabled:n.enabled,threshold:n.threshold,strategy:n.strategy,stickyLimit:n.stickyLimit,quotaWindow:n.quotaWindow,nativeMessages:n.nativeMessages},(e,t)=>fetch(e,t),{signal:c.signal});if(!u())return;if(!e)throw Error(`save`);let t=typeof e.autoSwitchThreshold==`number`?e.autoSwitchThreshold:n.threshold,a=pu(e?.strategy??n.strategy),o=hu(e?.stickyLimit??n.stickyLimit),f=mu(e?.quotaWindow??n.quotaWindow);s({enabled:e.enabled??n.enabled,threshold:t,strategy:a,stickyLimit:o,quotaWindow:f,nativeMessages:e.nativeMessages===!0}),l(String(t)),E.current?.(t),d(String(o)),y(e.warning===`config_bookkeeping_failed`)}catch(e){if(!u())return;if(e instanceof xu){s(null),x(!0),_(!1),h(null);return}h(a(`anthropicPool.saveFailed`)),f&&(s(f),l(String(f.threshold)),d(String(f.stickyLimit)))}finally{let e=A.current===c;e&&(A.current=null),e&&D.current&&O.current===r&&k.current===i&&p(!1)}},[e,t,o,a]),M=o?.enabled===!0,N=o?.threshold??80,P=o?.strategy??`quota`,F=o?.stickyLimit??1,I=o?.quotaWindow??`five-hour`,L=o?.nativeMessages??!0,R=P===`round-robin`,z=w||o===null&&!g&&!b,B=z||f||g||b,V=B||!M&&r<2;return(0,Q.jsxs)(`div`,{className:`card anthropic-pool-card`,"aria-busy":z||f,children:[(0,Q.jsxs)(`div`,{className:`card-row`,style:{alignItems:`flex-start`,gap:12},children:[(0,Q.jsxs)(`div`,{style:{flex:1},children:[(0,Q.jsx)(`strong`,{children:a(`anthropicPool.title`)}),(0,Q.jsx)(`div`,{className:`card-sub`,style:{marginTop:4},children:b?a(`anthropicPool.saveStateUnknown`):g?a(`anthropicPool.loadFailed`):z?a(`common.loading`):M?Sf(a,P,N,I):a(`anthropicPool.disabledDesc`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`toggle ${M?`on`:``}`,disabled:V,"aria-pressed":b?void 0:M,"aria-label":a(`anthropicPool.title`),title:a(M?`anthropicPool.on`:`anthropicPool.off`),onClick:()=>{j({enabled:!M,threshold:N,strategy:P,stickyLimit:F,quotaWindow:I,nativeMessages:L})},children:(0,Q.jsx)(`span`,{className:`toggle-knob`})})]}),(0,Q.jsx)(`p`,{className:`card-sub anthropic-pool-card__notice`,children:a(`anthropicPool.experimentalWarning`)}),r<2&&(0,Q.jsx)(`div`,{className:`card-sub`,style:{marginTop:8},children:a(`anthropicPool.needTwoAccounts`)}),(0,Q.jsxs)(`details`,{className:`anthropic-pool-card__details`,children:[(0,Q.jsx)(`summary`,{children:a(`anthropicPool.detailsSummary`)}),(0,Q.jsx)(`p`,{children:a(`anthropicPool.detailsEnabling`)}),(0,Q.jsx)(`p`,{children:a(`anthropicPool.detailsFailover`)}),(0,Q.jsx)(`p`,{children:a(`anthropicPool.detailsActivity`)}),(0,Q.jsxs)(`label`,{className:`anthropic-pool-card__native-messages`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:o?L:!1,disabled:B||!o,"aria-label":a(`anthropicPool.nativeMessagesLabel`),"aria-describedby":`anthropic-pool-native-messages-help`,onChange:e=>{j({enabled:M,threshold:N,strategy:P,stickyLimit:F,quotaWindow:I,nativeMessages:e.target.checked})}}),(0,Q.jsxs)(`span`,{className:`anthropic-pool-card__native-messages-copy`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:a(`anthropicPool.nativeMessagesLabel`)}),(0,Q.jsx)(`span`,{id:`anthropic-pool-native-messages-help`,className:`card-sub`,children:a(`anthropicPool.nativeMessagesHelp`)})]})]}),(0,Q.jsx)(`p`,{children:(0,Q.jsx)(`a`,{href:bf,target:`_blank`,rel:`noreferrer`,children:a(`anthropicPool.detailsGuide`)})})]}),M&&o&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`label`,{className:`field anthropic-pool-card__field`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:a(`anthropicPool.threshold`)}),(0,Q.jsx)(`input`,{className:`input mono`,type:`number`,min:0,max:100,step:1,value:c,disabled:B,"aria-label":a(`anthropicPool.thresholdAria`),onChange:e=>l(e.target.value),onBlur:()=>{let e=Number(c);!Number.isInteger(e)||e<0||e>100?(l(String(N)),h(a(`anthropicPool.thresholdInvalid`))):e!==N&&j({enabled:!0,threshold:e,strategy:P,stickyLimit:F,quotaWindow:I,nativeMessages:L})}}),(0,Q.jsx)(`div`,{className:`card-sub`,style:{marginTop:4},children:a(`anthropicPool.thresholdHelp`)})]}),(0,Q.jsx)(Od,{strategy:P,stickyDraft:u,disabled:B,strategySelectId:`anthropic-pool-strategy`,stickyInputId:`anthropic-pool-sticky-limit`,onStrategyChange:e=>{e!==P&&j({enabled:!0,threshold:N,strategy:e,stickyLimit:F,quotaWindow:I,nativeMessages:L})},onStickyDraftChange:d,onStickyCommit:e=>{let t=gu(e??u);t===null?(d(String(F)),h(a(`accountPool.stickyLimitInvalid`))):t===F?d(String(t)):j({enabled:!0,threshold:N,strategy:P,stickyLimit:t,quotaWindow:I,nativeMessages:L})}}),(0,Q.jsxs)(`div`,{className:`field anthropic-pool-card__field anthropic-pool-card__field--quota-window`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:a(`accountPool.quotaWindow`)}),(0,Q.jsx)(dn,{id:`anthropic-pool-quota-window`,value:I,options:cu.map(e=>({value:e,label:a(xf[e])})),disabled:B||R,label:a(`accountPool.quotaWindow`),onChange:e=>{let t=mu(e);t!==I&&j({enabled:!0,threshold:N,strategy:P,stickyLimit:F,quotaWindow:t,nativeMessages:L})}}),(0,Q.jsx)(`div`,{className:`card-sub`,style:{marginTop:4},children:a(`accountPool.quotaWindowDesc`)}),(0,Q.jsx)(`div`,{className:`card-sub`,style:{marginTop:4},children:a(R?`accountPool.quotaWindowInert`:`accountPool.quotaWindowHint`)})]})]}),b&&(0,Q.jsxs)(`div`,{role:`alert`,className:`anthropic-pool-card__save-warning`,children:[(0,Q.jsx)(`p`,{children:a(`anthropicPool.saveStateUnknown`)}),g&&(0,Q.jsx)(`p`,{children:a(`anthropicPool.loadFailed`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:w,onClick:()=>{_(!1),T(!0),C(e=>e+1)},children:a(`anthropicPool.reloadSettings`)})]}),v&&(0,Q.jsx)(`div`,{role:`status`,className:`anthropic-pool-card__save-warning`,children:a(`anthropicPool.saveWarning`)}),m&&(0,Q.jsx)(`div`,{role:`alert`,className:`card-sub`,style:{marginTop:8,color:`var(--danger, #c44)`},children:m})]})}function wf({serverDefault:e=!0}){let t=n(),[r,i]=(0,Z.useState)(Gl);return(0,Q.jsxs)(`label`,{className:`open-browser-pref`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:!(r??e),onChange:e=>{let t=!e.target.checked;i(t),ql(t)}}),(0,Q.jsxs)(`span`,{className:`open-browser-pref-copy`,children:[(0,Q.jsx)(`span`,{className:`text-label`,children:t(`prov.dontOpenBrowser`)}),(0,Q.jsx)(`span`,{className:`muted text-label`,children:t(`prov.dontOpenBrowserHint`)})]})]})}function Tf(e){return e?.status===`ready`?e.coupons:[]}function Ef(){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 Df={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 Of({entry:e,onClick:t,t:n}){if(e===void 0||e.status===`loading`)return(0,Q.jsxs)(`span`,{className:`badge badge-muted codex-ticket-badge-slot`,"aria-hidden":`true`,children:[(0,Q.jsx)(ft,{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,Q.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,Q.jsx)(ft,{width:12}),r===null?(0,Q.jsx)(Ne,{width:11}):r]})}function kf({coupon:e,index:t,isNext:n,locale:r,t:i}){let a=e.validityEnd?Xd(e.validityEnd):null;return(0,Q.jsxs)(`div`,{className:`credit-item${n?` credit-next`:``}`,children:[(0,Q.jsxs)(`div`,{className:`credit-item-head`,children:[(0,Q.jsx)(ft,{width:13}),(0,Q.jsx)(`span`,{className:`credit-item-label`,children:n?i(`grokCoupon.couponNext`):i(`grokCoupon.couponLabel`,{n:String(t+1)})}),n&&(0,Q.jsx)(`span`,{className:`badge badge-amber text-micro`,style:{padding:`1px 6px`},children:i(`grokCoupon.couponNextBadge`)})]}),(0,Q.jsxs)(`div`,{className:`credit-item-dates`,children:[e.validityStart&&(0,Q.jsx)(`span`,{children:i(`grokCoupon.validFrom`,{date:Jd(e.validityStart,r)})}),a!==null&&(0,Q.jsx)(`span`,{className:a<=7?`credit-urgent`:``,children:i(`grokCoupon.expires`,{date:Yd(e.validityEnd,r),days:String(a)})})]})]})}function Af({accountId:e,accountLabel:t,entry:n,controller:i,onClose:a}){let{locale:o,t:s}=r(),c=(0,Z.useRef)(null),l=(0,Z.useRef)(null),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(!1),[m,h]=(0,Z.useState)(!1),g=i.uncertain[e],[_,v]=(0,Z.useState)(null),y=(0,Z.useRef)(void 0);(0,Z.useEffect)(()=>{let e=c.current;e&&!e.open&&e.showModal()},[]),(0,Z.useEffect)(()=>{u&&l.current?.focus()},[u]);let b=(0,Z.useCallback)(e=>{e.preventDefault(),a()},[a]),x=Tf(n),S=x[0],C=()=>{if(g)return;let e=Ef();e?(y.current=e,v(null),d(!0)):v({tone:`warn`,key:`grokCoupon.noOperationId`})},w=async()=>{if(f||g)return;let t=y.current;if(!S?.tokenId){v({tone:`warn`,key:`grokCoupon.noneAvailable`});return}if(!t){v({tone:`warn`,key:`grokCoupon.noOperationId`});return}p(!0);let n=await i.redeem(e,{tokenId:S.tokenId,operationId:t});p(!1),n.ok?(y.current=void 0,d(!1),v({tone:`ok`,key:n.replayed?`grokCoupon.redeemReplayed`:`grokCoupon.redeemSuccess`})):n.uncertain||n.code===`aborted`?(n.operationId&&(y.current=n.operationId),d(!1),v(null),i.refresh(e)):(n.code===`operation_id_owned_by_another_account`&&(y.current=void 0),v({tone:`warn`,key:Df[n.code]??`grokCoupon.redeemFailed`}))},T=async()=>{g&&!m&&(h(!0),await i.refresh(e),h(!1))},E=g?Tf(n).some(e=>e.tokenId===g.tokenId):!1,D=String(x.length),O=e=>(0,Q.jsx)(`p`,{className:e.tone===`ok`?`pws-status-ok`:`pws-status-warn`,role:e.tone===`ok`?`status`:`alert`,style:{marginTop:12},children:s(e.key,{count:D})});return(0,Q.jsxs)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":`grok-coupon-title`,onCancel:b,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":s(`common.close`),tabIndex:-1,onClick:a}),(0,Q.jsx)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),role:`document`,children:g?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{style:{textAlign:`center`,padding:`12px 0`},children:[(0,Q.jsx)(`div`,{className:`confirm-icon`,children:(0,Q.jsx)(Ne,{width:22})}),(0,Q.jsx)(`h3`,{id:`grok-coupon-title`,children:s(`grokCoupon.title`)}),(0,Q.jsx)(`p`,{className:`pws-status-warn`,role:`alert`,children:s(`grokCoupon.unknownOutcome`)}),!m&&(0,Q.jsx)(`p`,{className:`faint text-label`,children:s(E?`grokCoupon.unresolved`:`grokCoupon.consumedElsewhere`)})]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:a,children:s(`common.close`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>{T()},disabled:m,children:s(m?`grokCoupon.checking`:`grokCoupon.checkResult`)})]})]}):u?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{style:{textAlign:`center`,padding:`12px 0`},children:[(0,Q.jsx)(`div`,{className:`confirm-icon`,children:(0,Q.jsx)(Ne,{width:22})}),(0,Q.jsx)(`h3`,{id:`grok-coupon-title`,children:s(`grokCoupon.confirmTitle`)}),(0,Q.jsx)(`p`,{className:`modal-desc`,children:s(`grokCoupon.confirmDesc`,{count:D})}),S?.validityEnd&&(0,Q.jsx)(`p`,{className:`faint text-label`,children:s(`grokCoupon.confirmWhich`,{date:Jd(S.validityEnd,o)})}),(0,Q.jsx)(`p`,{className:`faint text-label`,children:s(`grokCoupon.irreversible`)}),_&&O(_)]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>d(!1),disabled:f,children:s(`common.cancel`)}),(0,Q.jsx)(`button`,{ref:l,type:`button`,className:`btn btn-primary`,onClick:()=>{w()},disabled:f,children:s(f?`grokCoupon.redeeming`:`grokCoupon.redeem`)})]})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`h3`,{id:`grok-coupon-title`,children:[(0,Q.jsx)(ft,{width:16}),` `,s(`grokCoupon.title`)]}),(0,Q.jsx)(`div`,{className:`card-sub`,children:t}),(0,Q.jsxs)(`div`,{style:{margin:`16px 0`},children:[n===void 0||n.status===`loading`?(0,Q.jsx)(`p`,{className:`faint text-label`,children:s(`common.loading`)}):n.status===`error`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`faint`,role:`alert`,children:s(n.reason===`auth`?`grokCoupon.loadFailedAuth`:`grokCoupon.loadFailed`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,style:{marginTop:12},onClick:()=>{i.refresh(e)},children:s(`grokCoupon.retry`)})]}):x.length>0?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{style:{marginBottom:12},children:s(`grokCoupon.available`,{count:D})}),(0,Q.jsx)(`div`,{className:`credit-list`,children:x.map((e,t)=>(0,Q.jsx)(kf,{coupon:e,index:t,isNext:t===0,locale:o,t:s},e.tokenId))}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,style:{marginTop:12,width:`100%`},onClick:C,disabled:f,children:s(`grokCoupon.useOne`)}),(0,Q.jsx)(`p`,{className:`card-sub text-caption`,style:{marginTop:8,textAlign:`center`},children:s(`grokCoupon.fifoNote`)})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`faint`,children:s(`grokCoupon.none`)}),(0,Q.jsx)(`p`,{className:`modal-desc`,children:s(`grokCoupon.desc`)})]}),_&&O(_)]})]})})]})}var jf=2e4,Mf=6e4,Nf=3,Pf={},Ff=[`five_hour`,`seven_day`,`seven_day_overage_included`],If=new Set([`unknown_outcome`,`journal_write_failed`,`in_flight`]);function Lf(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Rf(e){return e==null?null:typeof e==`string`?e:void 0}function zf(e){if(!Lf(e))return null;let{id:t,label:n,resetsTotal:r,resetsLeft:i,paused:a,usableNow:o,useRequiresLimit:s}=e,c=Rf(e.startsAt),l=Rf(e.endsAt);if(typeof t!=`string`||t===``||typeof n!=`string`||typeof r!=`number`||typeof i!=`number`||typeof a!=`boolean`||typeof o!=`boolean`||typeof s!=`boolean`||c===void 0||l===void 0||!Array.isArray(e.clears))return null;let u={};if(Lf(e.percentUsed))for(let t of Ff){let n=e.percentUsed[t];typeof n==`number`&&(u[t]=n)}return{id:t,label:n,resetsTotal:r,resetsLeft:i,startsAt:c,endsAt:l,paused:a,usableNow:o,useRequiresLimit:s,percentUsed:u,clears:Ff.filter(t=>e.clears.includes(t))}}function Bf(e){if(!Lf(e)||typeof e.eligible!=`boolean`||!Array.isArray(e.grants))return null;let t=[];for(let n of e.grants){let e=zf(n);if(!e)return null;t.push(e)}let n=null,r=e.pendingOperation;return Lf(r)&&typeof r.operationId==`string`&&typeof r.grantId==`string`&&typeof r.retryableUntil==`number`&&(n={operationId:r.operationId,grantId:r.grantId,retryableUntil:r.retryableUntil}),{eligible:e.eligible,atLimit:e.atLimit===!0,grants:t,pendingOperation:n,journalAvailable:e.journalAvailable!==!1}}function Vf(e){return e.eligible?e.grants.reduce((e,t)=>e+t.resetsLeft,0):0}function Hf(e){if(e.eligible&&e.journalAvailable)return e.grants.find(t=>!t.paused&&t.usableNow&&t.resetsLeft>0&&(!t.useRequiresLimit||e.atLimit))}function Uf(e){return Lf(e)&&Lf(e.error)&&typeof e.error.code==`string`&&e.error.code!==``?e.error.code:`failed`}function Wf({apiBase:e,provider:t=`anthropic`,accountIds:n,enabled:r}){let i=`${e}\0${t}`,[a,o]=(0,Z.useState)(()=>({namespace:i,entries:{}})),s=(0,Z.useRef)(0),c=(0,Z.useRef)(new Map),l=(0,Z.useRef)({active:0,waiting:[]}),u=n.join(`\0`);(0,Z.useLayoutEffect)(()=>{s.current+=1,c.current.clear();let e=l.current;l.current={active:0,waiting:[]};for(let t of e.waiting.splice(0))t();return()=>{s.current+=1}},[i]);let d=(0,Z.useCallback)((e,t)=>{o(n=>({namespace:i,entries:{...n.namespace===i?n.entries:{},[e]:t}}))},[i]),f=(0,Z.useCallback)(async(n,r)=>{if(s.current!==r)return;let i=(c.current.get(n)??0)+1;c.current.set(n,i);let a=l.current;a.active>=Nf&&await new Promise(e=>a.waiting.push(e)),a.active+=1;let o=()=>s.current===r&&c.current.get(n)===i,u=M(jf);try{if(!o())return;let r=await fetch(`${e}/api/anthropic/reset-grants?accountId=${encodeURIComponent(n)}${t===`anthropic`?``:`&provider=${encodeURIComponent(t)}`}`,{signal:u.signal}),i=r.ok?await r.json().catch(()=>null):null,a=Lf(i)&&(i.provider===t||t===`anthropic`&&i.provider===void 0)?Bf(i):null;if(!o())return;d(n,a?{status:`ready`,snapshot:a}:{status:`error`,reason:r.status===401?`auth`:`upstream`})}catch{if(!o())return;d(n,{status:`error`,reason:`upstream`})}finally{u.clear(),--a.active,a.waiting.shift()?.()}},[e,t,d]);(0,Z.useEffect)(()=>{if(!r||u===``)return;let e=++s.current;return Promise.resolve().then(()=>{for(let t of u.split(`\0`))f(t,e)}),()=>{s.current+=1}},[r,u,f]);let p=(0,Z.useCallback)(async e=>{d(e,{status:`loading`}),await f(e,s.current)},[f,d]),m=(0,Z.useCallback)(async(n,r)=>{let i=s.current,a=M(Mf);try{let o=await fetch(`${e}/api/anthropic/reset-grants/consume`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...t===`anthropic`?{}:{provider:t},accountId:n,grantId:r.grantId,operationId:r.operationId}),signal:a.signal});if(!o.ok){let e=Uf(await o.json().catch(()=>null));return If.has(e)?{kind:`unknown`,code:e}:{kind:`refused`,code:e}}let c=await o.json().catch(()=>null);return!Lf(c)||typeof c.code!=`string`||c.provider!==t&&(t!==`anthropic`||c.provider!==void 0)?{kind:`unknown`,code:`unknown_outcome`}:(i===s.current&&f(n,i),{kind:`settled`,code:c.code,replayed:c.replayed===!0,resetsLeft:typeof c.resetsLeft==`number`?c.resetsLeft:null})}catch{return{kind:`unknown`,code:`aborted`}}finally{a.clear()}},[e,t,f]);return{entries:a.namespace===i?a.entries:Pf,refresh:p,spend:m}}function Gf(){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 Kf={reset:`anthropicGrant.resultReset`,already_used:`anthropicGrant.resultAlreadyUsed`,not_limited:`anthropicGrant.resultNotLimited`,cooldown:`anthropicGrant.resultCooldown`,ineligible:`anthropicGrant.resultIneligible`,unavailable:`anthropicGrant.resultUnavailable`,rate_limited:`anthropicGrant.resultRateLimited`,auth_error:`anthropicGrant.resultAuthError`},qf={grant_not_usable:`anthropicGrant.notUsableNow`,operation_identity_mismatch:`anthropicGrant.identityMismatch`,unresolved_prior_operation:`anthropicGrant.unresolvedPrior`,unknown_outcome_expired:`anthropicGrant.expired`,session_required:`anthropicGrant.sessionRequired`,ledger_busy:`anthropicGrant.journalBusy`,ledger_unavailable:`anthropicGrant.journalBusy`,ledger_capacity:`anthropicGrant.journalBusy`,auth_failed:`anthropicGrant.resultAuthError`};function Jf({entry:e,onClick:t,t:n}){if(e===void 0||e.status===`loading`)return(0,Q.jsxs)(`span`,{className:`badge badge-muted codex-ticket-badge-slot`,"aria-hidden":`true`,children:[(0,Q.jsx)(ft,{width:12}),`0`]});let r=e.status===`ready`?Vf(e.snapshot):null,i=e.status===`ready`&&Hf(e.snapshot)!==void 0,a=r===null?n(`anthropicGrant.badgeErrorAria`):n(`anthropicGrant.badgeAria`,{count:String(r)});return(0,Q.jsxs)(`button`,{type:`button`,className:`badge ${i?`badge-amber`:`badge-muted`} badge-clickable`,"data-anthropic-grant-badge":r===null?`error`:String(r),onClick:e=>{e.stopPropagation(),t()},"aria-label":a,title:a,children:[(0,Q.jsx)(ft,{width:12}),r===null?(0,Q.jsx)(Ne,{width:11}):r]})}var Yf={five_hour:`anthropicGrant.windowFiveHour`,seven_day:`anthropicGrant.windowWeekly`,seven_day_overage_included:`anthropicGrant.windowOverage`};function Xf({grant:e,snapshot:t,isNext:n,locale:r,t:i}){let a=e.endsAt?Xd(e.endsAt):null,o=e.paused?i(`anthropicGrant.paused`):e.usableNow?e.useRequiresLimit&&!t.atLimit?i(`anthropicGrant.requiresLimit`):null:i(`anthropicGrant.notUsable`);return(0,Q.jsxs)(`div`,{className:`credit-item${n?` credit-next`:``}`,"data-anthropic-grant":e.id,children:[(0,Q.jsxs)(`div`,{className:`credit-item-head`,children:[(0,Q.jsx)(ft,{width:13}),(0,Q.jsx)(`span`,{className:`credit-item-label`,children:e.label||e.id}),(0,Q.jsx)(`span`,{className:`badge badge-muted text-micro anthropic-grant-count`,children:i(`anthropicGrant.resetsLeft`,{left:String(e.resetsLeft),total:String(e.resetsTotal)})})]}),(0,Q.jsxs)(`div`,{className:`credit-item-dates`,children:[e.startsAt&&(0,Q.jsx)(`span`,{children:i(`anthropicGrant.validFrom`,{date:Jd(e.startsAt,r)})}),e.endsAt&&a!==null&&(0,Q.jsx)(`span`,{className:a<=7?`credit-urgent`:``,children:i(`anthropicGrant.expires`,{date:Yd(e.endsAt,r),days:String(a)})})]}),e.clears.length>0&&(0,Q.jsx)(`div`,{className:`anthropic-grant-windows`,children:e.clears.map(t=>(0,Q.jsx)(`span`,{className:`anthropic-grant-window`,children:i(Yf[t],{percent:String(e.percentUsed[t]??0)})},t))}),o&&(0,Q.jsx)(`div`,{className:`faint text-caption anthropic-grant-note`,children:o})]})}function Zf(e){return e.kind===`settled`?e.replayed&&e.code===`reset`?{tone:`ok`,key:`anthropicGrant.replayed`}:{tone:e.code===`reset`?`ok`:`warn`,key:Kf[e.code]??`anthropicGrant.failed`,count:e.resetsLeft===null?`?`:String(e.resetsLeft)}:{tone:`warn`,key:qf[e.code]??`anthropicGrant.failed`}}var Qf=new Set([`unknown_outcome_expired`,`operation_identity_mismatch`]);function $f({accountId:e,accountLabel:t,entry:n,controller:i,onClose:a}){let{locale:o,t:s}=r(),c=(0,Z.useRef)(null),l=(0,Z.useRef)(null),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)(!1),[m,h]=(0,Z.useState)(!1),[g,_]=(0,Z.useState)(null),[v,y]=(0,Z.useState)(null);(0,Z.useEffect)(()=>{let e=c.current;e&&!e.open&&e.showModal()},[]),(0,Z.useEffect)(()=>{u&&l.current?.focus()},[u]);let b=(0,Z.useCallback)(e=>{e.preventDefault(),a()},[a]),x=n?.status===`ready`?n.snapshot:null,S=x?.pendingOperation,C=g??(S?{grantId:S.grantId,operationId:S.operationId}:null),w=x?Hf(x):void 0,T=()=>{if(!w||C)return;let e=Gf();e?(y(null),d({grantId:w.id,operationId:e})):y({tone:`warn`,key:`anthropicGrant.noOperationId`})},E=async t=>{if(f)return;let n=C!==null&&C.operationId===t.operationId;p(!0);let r=await i.spend(e,t);p(!1),d(null),r.kind===`unknown`||r.kind===`refused`&&n&&!Qf.has(r.code)?(_(t),y(r.kind===`refused`?Zf(r):null)):(_(null),y(Zf(r)),r.kind===`refused`&&i.refresh(e))},D=async()=>{m||(h(!0),await i.refresh(e),h(!1))},O=e=>(0,Q.jsx)(`p`,{className:e.tone===`ok`?`pws-status-ok`:`pws-status-warn`,role:e.tone===`ok`?`status`:`alert`,style:{marginTop:12},children:s(e.key,{count:e.count??``})}),k=u&&x?x.grants.find(e=>e.id===u.grantId):void 0,A=x?Vf(x):0;return(0,Q.jsxs)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":`anthropic-grant-title`,onCancel:b,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":s(`common.close`),tabIndex:-1,onClick:a}),(0,Q.jsx)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),role:`document`,children:C?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{style:{textAlign:`center`,padding:`12px 0`},children:[(0,Q.jsx)(`div`,{className:`confirm-icon`,children:(0,Q.jsx)(Ne,{width:22})}),(0,Q.jsx)(`h3`,{id:`anthropic-grant-title`,children:s(`anthropicGrant.title`)}),(0,Q.jsx)(`p`,{className:`pws-status-warn`,role:`alert`,children:s(`anthropicGrant.unknownOutcome`)}),v&&O(v)]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:a,children:s(`common.close`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>{D()},disabled:m||f,children:s(m?`anthropicGrant.checking`:`anthropicGrant.checkResult`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,"data-anthropic-grant-retry":!0,onClick:()=>{E(C)},disabled:f||m,children:s(f?`anthropicGrant.redeeming`:`anthropicGrant.retrySame`)})]})]}):u?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{style:{textAlign:`center`,padding:`12px 0`},children:[(0,Q.jsx)(`div`,{className:`confirm-icon`,children:(0,Q.jsx)(Ne,{width:22})}),(0,Q.jsx)(`h3`,{id:`anthropic-grant-title`,children:s(`anthropicGrant.confirmTitle`)}),(0,Q.jsx)(`p`,{className:`modal-desc`,children:s(`anthropicGrant.confirmDesc`)}),k&&(0,Q.jsx)(`p`,{className:`faint text-label`,children:s(`anthropicGrant.confirmWhich`,{label:k.label||k.id})}),(0,Q.jsx)(`p`,{className:`faint text-label`,children:s(`anthropicGrant.irreversible`)})]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>d(null),disabled:f,children:s(`common.cancel`)}),(0,Q.jsx)(`button`,{ref:l,type:`button`,className:`btn btn-primary`,"data-anthropic-grant-confirm":!0,onClick:()=>{E(u)},disabled:f,children:s(f?`anthropicGrant.redeeming`:`anthropicGrant.redeem`)})]})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`h3`,{id:`anthropic-grant-title`,children:[(0,Q.jsx)(ft,{width:16}),` `,s(`anthropicGrant.title`)]}),(0,Q.jsx)(`div`,{className:`card-sub`,children:t}),(0,Q.jsxs)(`div`,{style:{margin:`16px 0`},children:[n===void 0||n.status===`loading`?(0,Q.jsx)(`p`,{className:`faint text-label`,children:s(`common.loading`)}):n.status===`error`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`faint`,role:`alert`,children:s(n.reason===`auth`?`anthropicGrant.loadFailedAuth`:`anthropicGrant.loadFailed`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,style:{marginTop:12},onClick:()=>{i.refresh(e)},children:s(`anthropicGrant.retry`)})]}):n.snapshot.eligible?n.snapshot.grants.length>0?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{style:{marginBottom:12},children:s(`anthropicGrant.available`,{count:String(A)})}),(0,Q.jsx)(`div`,{className:`credit-list`,children:n.snapshot.grants.map(e=>(0,Q.jsx)(Xf,{grant:e,snapshot:n.snapshot,isNext:e.id===w?.id,locale:o,t:s},e.id))}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,"data-anthropic-grant-use":!0,style:{marginTop:12,width:`100%`},onClick:T,disabled:!w||f,children:s(`anthropicGrant.useOne`)}),(0,Q.jsx)(`p`,{className:`card-sub text-caption`,style:{marginTop:8,textAlign:`center`},children:s(`anthropicGrant.desc`)})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`faint`,children:s(`anthropicGrant.none`)}),(0,Q.jsx)(`p`,{className:`modal-desc`,children:s(`anthropicGrant.desc`)})]}):(0,Q.jsx)(`p`,{className:`faint`,children:s(`anthropicGrant.ineligible`)}),v&&O(v)]})]})})]})}var ep=2e4,tp=3e4,np=3,rp=`ocx.grok-coupon-holds.v1`,ip=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,ap=new Set([`attempt_unresolved`,`attempt_in_progress`,`attempt_reconcile_failed`,`operation_state_changed`,`redeem_failed`,`attempt_mark_failed`,`operation_token_mismatch`]),op=new Set([`ledger_unavailable`,`capacity`]),sp=new Set([`redeemed`,`auth_failed`,`fetch_resets_failed`,`no_coupons_available`,`coupon_unavailable`,`token_unresolved`]),cp=new Map,lp=new Set,up;function dp(e){if(!e||typeof e!=`object`)return!1;let{tokenId:t,operationId:n}=e;return typeof t==`string`&&t.trim()!==``&&typeof n==`string`&&ip.test(n)}function fp(){try{let e=window.sessionStorage.getItem(rp);if(e!==up){up=e;let t=e===null?null:JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))for(let[e,n]of Object.entries(t))e.includes(`\0`)&&dp(n)&&(cp.has(e)||(cp=new Map(cp).set(e,{tokenId:n.tokenId,operationId:n.operationId})))}}catch{}return cp}function pp(e){return lp.add(e),()=>{lp.delete(e)}}function mp(){try{let e=JSON.stringify(Object.fromEntries(cp));window.sessionStorage.setItem(rp,e),up=e}catch{}for(let e of lp)e()}function hp(e,t){cp=new Map(cp).set(e,{...t}),mp()}function gp(e,t){fp().get(e)?.operationId===t&&(cp=new Map(cp),cp.delete(e),mp())}function _p(e,t){return ap.has(e)||op.has(e)&&!!(t&&typeof t==`object`&&`operationId`in t)}function vp(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 yp(e){if(e&&typeof e==`object`){let t=e.error;if(t&&typeof t==`object`){let e=t.code;if(typeof e==`string`&&e.trim()!==``)return e}}return`redeem_failed`}function bp(e){if(e&&typeof e==`object`){let t=e.code;if(typeof t==`string`&&t.trim()!==``)return t}return null}function xp(e){if(!e.validityEnd)return 1/0;let t=Date.parse(e.validityEnd);return Number.isNaN(t)?1/0:t}function Sp(e){return e.toSorted((e,t)=>xp(e)-xp(t))}function Cp({apiBase:e,accountIds:t,enabled:n}){let[r,i]=(0,Z.useState)({}),a=(0,Z.useSyncExternalStore)(pp,fp,fp),o=(0,Z.useMemo)(()=>{let t=`${e}\u0000`;return Object.fromEntries([...a].filter(([e])=>e.startsWith(t)).map(([e,n])=>[e.slice(t.length),n]))},[e,a]),s=(0,Z.useRef)(0),c=(0,Z.useRef)(new Map),l=(0,Z.useRef)({active:0,waiting:[]}),u=t.join(`\0`),d=(0,Z.useCallback)(async(t,n)=>{let r=(c.current.get(t)??0)+1;c.current.set(t,r);let a=l.current;a.active>=np&&await new Promise(e=>a.waiting.push(e)),a.active+=1;let o=()=>s.current===n&&c.current.get(t)===r,u=M(ep);try{let n=await fetch(`${e}/api/grok/reset-coupons?accountId=${encodeURIComponent(t)}`,{signal:u.signal}),r=n.ok?vp(await n.json().catch(()=>null)):null;if(!o())return;i(e=>({...e,[t]:r?{status:`ready`,coupons:Sp(r)}:{status:`error`,reason:n.status===401?`auth`:`upstream`}}))}catch{if(!o())return;i(e=>({...e,[t]:{status:`error`,reason:`upstream`}}))}finally{u.clear(),--a.active,a.waiting.shift()?.()}},[e]);return(0,Z.useEffect)(()=>{if(!n||u===``)return;let e=++s.current;return Promise.resolve().then(()=>{for(let t of u.split(`\0`))d(t,e)}),()=>{s.current+=1}},[n,u,d]),{entries:r,uncertain:o,refresh:(0,Z.useCallback)(async e=>{i(t=>({...t,[e]:{status:`loading`}})),await d(e,s.current)},[d]),redeem:(0,Z.useCallback)(async(t,n)=>{let r=`${e}\u0000${t}`,i=(e,t=`attempt_unresolved`)=>({ok:!1,code:t,replayed:!1,operationId:e.operationId,uncertain:!0}),a=fp().get(r);if(a)return i(a);hp(r,n);let o=()=>gp(r,n.operationId),c=M(tp);try{let r=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:c.signal});if(!r.ok){let e=await r.json().catch(()=>null),t=yp(e);return _p(t,e)?i(n,t):(o(),{ok:!1,code:t,replayed:!1})}let a=await r.json().catch(()=>null),l=!!(a&&typeof a==`object`&&a.replayed===!0),u=bp(a);return u===null||!sp.has(u)?i(n,u??`attempt_unresolved`):(o(),await d(t,s.current),{ok:u===`redeemed`,code:u,replayed:l})}catch{return i(n,`aborted`)}finally{c.clear()}},[e,d])}}var wp=new Set([`builder-id`,`google`,`github`]),Tp=new Set([`pending`,`done`,`failed`,`expired`,`cancelled`]);function Ep(e){if(!e||typeof e!=`object`)return null;let t=e;return typeof t.flowId!=`string`||!t.flowId||!wp.has(t.method)||!Tp.has(t.state)?null:{flowId:t.flowId,method:t.method,state:t.state,...typeof t.userCode==`string`?{userCode:t.userCode}:{},...typeof t.verificationUri==`string`?{verificationUri:t.verificationUri}:{},...typeof t.verificationUriComplete==`string`?{verificationUriComplete:t.verificationUriComplete}:{},...typeof t.expiresAt==`number`&&Number.isFinite(t.expiresAt)?{expiresAt:t.expiresAt}:{},...t.warning===`duplicate_profile_arn`||t.warning===`manual_review_required`?{warning:t.warning}:{}}}function Dp(e){if(!e||[...e].some(e=>e.charCodeAt(0)<32||e.charCodeAt(0)===127))return null;let t=/^https:\/\/([^/?#]+)/iu.exec(e)?.[1];if(!t||t.includes(`@`)||t.includes(`:`))return null;try{let t=new URL(e);if(t.protocol!==`https:`||t.username||t.password||t.port)return null;let n=t.hostname.toLowerCase();return n!==`device.sso.us-east-1.amazonaws.com`&&n!==`kiro.dev`&&!n.endsWith(`.kiro.dev`)?null:t.href}catch{return null}}function Op(e,t){return t!==`kiro`||e.autoSelectable!==!1||e.skipReason===`needs_reauth`||e.skipReason===`paused`||e.skipReason===`cooldown`&&e.health?.status===`cooldown`?null:e.skipReason===`suspended`?`kiroSelection.suspended`:e.skipReason===`quota_exhausted`?`kiroSelection.quotaExhausted`:e.skipReason===`cooldown`?`kiroSelection.cooldown`:`kiroSelection.generic`}var kp=new Map;function Ap(e,t){let n=JSON.stringify([e,t]),r=kp.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(()=>{kp.get(n)===i&&kp.delete(n)});return kp.set(n,i),i}async function jp(e,t,n){let r=JSON.stringify([e,t]),i=kp.get(r);return i?(await i,jp(e,t,n)):n()}var Mp=new Map,Np=new Map,Pp=new Map,Fp=(e,t)=>JSON.stringify([e,t]),Ip=e=>new Promise(t=>setTimeout(t,e)),Lp=65536;function Rp(e){try{e.body?.cancel().catch(()=>{})}catch{}}function zp(e,t,n=45e3){let r=new AbortController,i,a=!1,o,s=new Promise(e=>{o=e}),c=e=>{a||(a=!0,clearTimeout(u),o(e))},l=()=>{if(!a){r.abort();try{i?.cancel().catch(()=>{})}catch{}c({kind:`retry`})}},u=setTimeout(l,Math.max(0,n));return(async()=>{try{let n=await fetch(`${e}/api/oauth/status?provider=kiro&flowId=${encodeURIComponent(t)}`,{signal:r.signal});if(a){Rp(n);return}if(n.status===404){Rp(n),c({kind:`missing`});return}if(!n.ok||!n.body){Rp(n),c({kind:`retry`});return}i=n.body.getReader();let o=new TextDecoder,s=``,u=0;for(;;){let e=await i.read();if(a)return;if(e.done)break;if(u+=e.value.byteLength,u>Lp){l();return}s+=o.decode(e.value,{stream:!0})}s+=o.decode();let d;try{d=JSON.parse(s)}catch{c({kind:`retry`});return}let f=Ep(d);c(f?{kind:`view`,view:f}:{kind:`retry`})}catch{c({kind:`retry`})}})(),{result:s,cancel:l}}async function Bp(e,t){let n;try{return await Promise.race([e.result,new Promise(r=>{n=setTimeout(()=>{e.cancel(),r({kind:`retry`})},Math.max(0,t))})])}finally{n&&clearTimeout(n)}}function Vp(e,t){let n=Pp.get(e)??new Set;return n.add(t),Pp.set(e,n),()=>{n.delete(t),n.size===0&&Pp.delete(e)}}function Hp(e,t,n){let r=Fp(e,t);if(Np.has(r))return Np.get(r);Np.set(r,n);for(let t of Pp.get(e)??[])t(n);return n}function Up(e,t,n,r=`status`){return n.flowId!==t||r===`cancel`&&n.state!==`failed`?null:n.state===`done`?Hp(e,t,`added`):n.state===`failed`?Hp(e,t,`failed`):n.state===`expired`||n.state===`cancelled`?Hp(e,t,`ended`):null}function Wp(e,t,n,r){let i=Fp(e,t),a=Mp.get(i);if(a)return a;let o=Np.get(i);if(o)return Promise.resolve(o);let s=Math.min(Date.now()+96e4,(n??Date.now()+9e5)+6e4),c=(async()=>{let n=r;for(;Date.now()<s;){let r=s-Date.now(),a=n??zp(e,t,Math.min(45e3,r));n=void 0;let o=await Bp(a,r);if(Np.has(i))return Np.get(i);if(o.kind===`missing`)return Hp(e,t,`ended`);if(o.kind===`view`){let n=Up(e,t,o.view);if(n)return n}let c=s-Date.now();if(c<=0)break;await Ip(Math.min(2e3,c))}return n?.cancel(),Hp(e,t,`ended`)})().finally(()=>{Mp.delete(i)});return Mp.set(i,c),c}var Gp=(e,t)=>new Promise(n=>{if(t.aborted){n();return}let r=setTimeout(()=>{t.removeEventListener(`abort`,i),n()},e),i=()=>{clearTimeout(r),t.removeEventListener(`abort`,i),n()};t.addEventListener(`abort`,i,{once:!0})}),Kp=Symbol(`closed`),qp=(e,t)=>new Promise(n=>{if(e.closed){n(Kp);return}let r=!1,i=t=>{r||(r=!0,e.closedController.signal.removeEventListener(`abort`,a),n(t))},a=()=>i(Kp);e.closedController.signal.addEventListener(`abort`,a,{once:!0}),t.then(t=>i(e.closed?Kp:t),()=>i(Kp))});function Jp(e,t,n=Gp){let[r,i]=(0,Z.useState)({phase:`idle`}),a=(0,Z.useRef)(null),o=(0,Z.useRef)(!0),s=(0,Z.useRef)(t);(0,Z.useEffect)(()=>{s.current=t},[t]);let c=(0,Z.useCallback)(async t=>{try{return await fetch(`${e}/api/oauth/login/cancel`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:`kiro`,flowId:t.flowId}),keepalive:!0})}catch{return null}},[e]),l=(0,Z.useCallback)(t=>{let n=t.view;n&&!t.terminal&&Wp(e,n.flowId,n.expiresAt,t.inFlight)},[e]),u=(0,Z.useCallback)(async()=>{let t=a.current;if(!t||t.closed||(t.closed=!0,t.closedController.abort(),a.current=null,t.waitController?.abort(),o.current&&i({phase:`cancelled`}),!t.view||t.terminal))return;let n=c(t.view);l(t);let r=await n,s=r?.ok?Ep(await r.json().catch(()=>null)):null;s&&Up(e,t.view.flowId,s,`cancel`)},[e,c,l]);return(0,Z.useEffect)(()=>(o.current=!0,()=>{o.current=!1,u()}),[u]),{state:r,start:(0,Z.useCallback)(async t=>{if(a.current)return;let r={closed:!1,closedController:new AbortController};a.current=r,i({phase:`starting`});let u;try{u=await jp(e,`kiro`,()=>fetch(`${e}/api/oauth/login`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:`kiro`,method:t})}))}catch{!r.closed&&o.current&&i({phase:`failed`,error:`network`}),a.current===r&&(a.current=null);return}let d=u.ok?Ep(await u.json().catch(()=>null)):null;if(!d||d.method!==t)!r.closed&&o.current&&i({phase:`failed`,error:u.ok?`invalid`:`start`}),a.current===r&&(a.current=null);else if(r.view=d,r.closed){let t=c(d);l(r);let n=await t,i=n?.ok?Ep(await n.json().catch(()=>null)):null;i&&Up(e,d.flowId,i,`cancel`)}else if(d.state!==`pending`)d.state===`done`?s.current?.(`kiro`,`added`):d.state===`failed`&&s.current?.(`kiro`,`failed`),o.current&&i({phase:d.state,view:d}),r.terminal=d.state===`done`?`added`:d.state===`failed`?`failed`:`ended`,a.current=null;else{for(i({phase:`pending`,view:d});!r.closed&&!r.terminal;){let t=new AbortController;if(r.waitController=t,await n(2e3,t.signal),r.waitController=void 0,r.closed||r.terminal)break;if(r.view?.expiresAt&&Date.now()>=r.view.expiresAt){r.terminal=`ended`,o.current&&i({phase:`expired`,view:r.view});break}let a=d.flowId,c=zp(e,a);r.inFlight=c;let l=await qp(r,c.result);if(l===Kp)break;if(r.inFlight=void 0,l.kind===`missing`){r.terminal=`ended`,s.current?.(`kiro`,`ended`),i({phase:`ended`,view:r.view});break}let u=l.kind===`view`?l.view:null;if(u&&u.flowId===a){if(r.view=u,u.state===`pending`)i({phase:`pending`,view:u});else{r.terminal=u.state===`done`?`added`:u.state===`failed`?`failed`:`ended`,(u.state===`done`||u.state===`failed`)&&s.current?.(`kiro`,r.terminal),i({phase:u.state,view:u});break}}}a.current===r&&(a.current=null)}},[e,c,l,n]),close:u,reset:(0,Z.useCallback)(()=>{a.current||i({phase:`idle`})},[])}}function Yp({disabled:e,onCli:t,onMethod:r}){let i=n();return(0,Q.jsxs)(`div`,{className:`kiro-login-choices`,role:`group`,"aria-label":i(`kiroLogin.chooseMethod`),children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:e,onClick:t,children:i(`kiroLogin.cli`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:e,onClick:()=>r(`builder-id`),children:i(`kiroLogin.builderId`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:e,onClick:()=>r(`google`),children:i(`kiroLogin.google`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:e,onClick:()=>r(`github`),children:i(`kiroLogin.github`)})]})}function Xp({apiBase:e,triggerRef:t,addAccount:r,busy:i,onCli:a,onClose:o,onSettled:s,pollDelay:c}){let l=n(),u=(0,Z.useId)(),d=lr(!0,t),f=Jp(e,s,c),p=zl(),{state:m}=f,h=m.view,g=h?.verificationUriComplete??h?.verificationUri,_=Dp(g),v=()=>{f.close(),o()};return(0,Q.jsxs)(`dialog`,{ref:d,className:`kiro-device-dialog`,"aria-modal":`true`,"aria-labelledby":u,onCancel:e=>{e.preventDefault(),v()},children:[(0,Q.jsx)(`h2`,{id:u,children:l(`kiroLogin.title`)}),m.phase===`idle`&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`muted`,children:l(r?`kiroLogin.addDescription`:`kiroLogin.loginDescription`)}),(0,Q.jsx)(Yp,{disabled:i,onCli:()=>{o(),a(r)},onMethod:e=>{f.start(e)}})]}),m.phase===`starting`&&(0,Q.jsx)(`p`,{role:`status`,"aria-live":`polite`,children:l(`kiroLogin.starting`)}),h&&(m.phase===`pending`||m.phase===`done`||m.phase===`failed`||m.phase===`expired`||m.phase===`ended`)&&(0,Q.jsxs)(Q.Fragment,{children:[h.userCode&&(0,Q.jsxs)(`div`,{className:`kiro-device-code`,children:[(0,Q.jsx)(`span`,{className:`kiro-device-code-value`,children:h.userCode}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>p.copy(h.userCode,h.flowId),children:p.outcomeFor(h.flowId)===`copied`?l(`kiroLogin.copied`):p.outcomeFor(h.flowId)===`unavailable`?l(`kiroLogin.copyUnavailable`):l(`kiroLogin.copyCode`)})]}),g&&(_?(0,Q.jsx)(`a`,{href:_,target:`_blank`,rel:`noopener noreferrer`,children:l(`kiroLogin.openVerification`)}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`kiro-device-destination`,children:g}),(0,Q.jsx)(`p`,{className:`notice-warn`,children:l(`kiroLogin.unexpectedHost`)})]})),h.warning===`duplicate_profile_arn`&&(0,Q.jsx)(`p`,{className:`notice-warn`,children:l(`kiroLogin.duplicate`)}),h.warning===`manual_review_required`&&(0,Q.jsx)(`p`,{className:`notice-warn`,children:l(`kiroLogin.manualReview`)})]}),(0,Q.jsxs)(`p`,{role:`status`,"aria-live":`polite`,children:[m.phase===`pending`&&l(`kiroLogin.pending`),m.phase===`done`&&l(`kiroLogin.done`),m.phase===`expired`&&l(`kiroLogin.expired`),m.phase===`ended`&&l(`kiroLogin.ended`),m.phase===`failed`&&l(m.error===`start`?`kiroLogin.startFailed`:`kiroLogin.failed`)]}),(0,Q.jsxs)(`div`,{className:`kiro-device-actions`,children:[(m.phase===`failed`||m.phase===`expired`||m.phase===`ended`)&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:f.reset,children:l(`kiroLogin.tryAgain`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:v,children:l(`common.cancel`)})]})]})}var Zp=262144,Qp=[],$p=[];function em(e){return!!e.needsReauth||Cl(e.health?.status)}function tm({initialState:e,onUpdateProvider:t}){let r=n(),[i,a]=(0,Z.useState)(e),[o,s]=(0,Z.useState)(e),[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(``);e!==o&&(s(e),a(e));let f=i===`mixed`,p=async()=>{if(!t||c)return;let e=i===!1;l(!0),d(``);try{let n=await t(`xai`,{xaiResponsesOptIn:e});if(!n.ok){d(n.error??r(`prov.updateFail`));return}a(n.xaiResponsesOptInState??e)}catch{d(r(`prov.networkError`))}finally{l(!1)}};return(0,Q.jsxs)(`div`,{className:`pwi-auth-optin-row`,children:[(0,Q.jsxs)(`div`,{className:`pwi-auth-optin-copy`,children:[(0,Q.jsx)(`span`,{className:`pwi-auth-optin-label`,children:r(`pws.xaiChatOptIn`)}),(0,Q.jsxs)(`span`,{className:`pwi-auth-row-secondary`,children:[r(`pws.xaiChatOptInDesc`),f&&(0,Q.jsxs)(`span`,{className:`pwi-auth-optin-mixed`,children:[` `,r(`pws.xaiChatOptInMixed`)]})]}),u&&(0,Q.jsx)(`span`,{className:`pwi-auth-optin-error`,role:`alert`,children:u})]}),(0,Q.jsx)(ln,{on:i===!1,mixed:f,onClick:()=>{p()},disabled:!t||c,label:r(`pws.xaiChatOptIn`)})]})}var nm=new Set([`totalCount`,`importedCount`,`updatedCount`,`failedCount`,`unsupportedCount`,`results`]),rm=new Set([`imported`,`updated`,`failed`,`unsupported`]),im={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 am(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function om(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function sm(e){if(!am(e)||Object.keys(e).some(e=>!nm.has(e)))return null;let{totalCount:t,importedCount:n,updatedCount:r,failedCount:i,unsupportedCount:a,results:o}=e;if(!om(t)||!om(n)||!om(r)||!om(i)||!om(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(!am(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||!rm.has(n)||!im[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 cm({item:e,apiBase:t,oauth:i,accounts:a=Qp,keys:o=$p,accountLoadState:s=`ready`,switchingAccountId:c=null,pausingAccountId:l=null,busy:u=!1,loginHint:d,authHandlers:f,onCodexActiveNeedsReauthChange:p,codexController:m,onUpdateProvider:h}){let g=n(),{locale:_}=r(),[v,y]=(0,Z.useState)(!1),[b,x]=(0,Z.useState)(null),S=(0,Z.useRef)(null),C=(0,Z.useRef)(null),w=t=>{e.name===`kiro`?x({addAccount:t}):f?.onLogin(e.name,t)},[T,E]=(0,Z.useState)(``),[D,O]=(0,Z.useState)(!1),[k,A]=(0,Z.useState)(!1),[j,M]=(0,Z.useState)(`idle`),[N,P]=(0,Z.useState)(null),F=(0,Z.useRef)(null),[I,L]=(0,Z.useState)(``),[z,B]=(0,Z.useState)(!1),[V,H]=(0,Z.useState)(``),[U,ee]=(0,Z.useState)(!0),W=JSON.stringify([t,e.name,a.find(e=>e.active)?.id,o.find(e=>e.active)?.id]),[te,G]=(0,Z.useState)({identity:W,refreshing:!1,result:null}),ne=te.identity===W&&te.refreshing,K=te.identity===W?te.result:null,re=(0,Z.useRef)(0);(0,Z.useEffect)(()=>(re.current+=1,()=>{re.current+=1}),[W]);let q=f?.onRefreshQuota,J=Nc({...e,hasApiKey:e.hasApiKey||o.length>0}),Y=J===`oauth-accounts`,ie=J===`api-keys`,X=Y&&e.name===`xai`&&a.length>0,oe=Cp({apiBase:t,accountIds:(0,Z.useMemo)(()=>X?a.filter(e=>!em(e)).map(e=>e.id):[],[X,a]),enabled:X}),[se,ce]=(0,Z.useState)(null),le=fl(e.name)&&pl(e.name,e),ue=Y&&le&&a.length>0,de=(0,Z.useMemo)(()=>ue?a.filter(e=>!em(e)).map(e=>e.id):[],[ue,a]),fe=Wf({apiBase:t,provider:fl(e.name)?e.name:`anthropic`,accountIds:de,enabled:ue}),pe=`${t}\0${e.name}`,[me,he]=(0,Z.useState)(null),ge=me?.scope===pe?me.account:null,_e=e=>{he(e?{scope:pe,account:e}:null)},ve=async()=>{if(!q||ne)return;let t=++re.current;G({identity:W,refreshing:!0,result:null});try{let n=await q(e.name);re.current===t&&G({identity:W,refreshing:!1,result:{ok:n,text:g(n?`pws.quotaCheckCompleted`:`codexAuth.quotaRefreshFailed`)}})}catch{re.current===t&&G({identity:W,refreshing:!1,result:{ok:!1,text:g(`codexAuth.quotaRefreshFailed`)}})}};if(J===`codex-accounts`)return(0,Q.jsxs)(`section`,{className:`pwi-section pwi-auth-section`,"aria-label":g(`pws.availableAccounts`),children:[(0,Q.jsx)(`h3`,{className:`pwi-section-title`,children:g(`pws.availableAccounts`)}),(0,Q.jsx)(`div`,{className:`pwi-auth-body`,children:(0,Q.jsx)(yf,{apiBase:t,embedded:!0,controller:m,onActiveNeedsReauthChange:p})})]});if(!J||!f)return null;let ye=d?.provider===e.name?d:null,be=async()=>{let n=I.trim();if(n&&!z){B(!0),H(``);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(()=>({}));ee(!1),H(g(`prov.pasteFail`,{error:e.error||r.statusText}));return}L(``),ee(!0),H(g(`prov.pasteOk`))}catch{ee(!1),H(g(`modal.networkError`))}finally{B(!1)}}},xe=a.length>0||i?.loggedIn===!0,Se=a.find(e=>e.active&&e.needsReauth),Ce=!!Se,we=Y?a:o,Te=!!q&&!(we.length>0&&we.every(e=>e.quotaMode===`unsupported`)),Ee=async()=>{let t=T.trim();if(t){O(!0);try{await f.onAddApiKey(e.name,t)&&(E(``),y(!1))}finally{O(!1)}}},De=async n=>{if(n&&!k){A(!0),M(`idle`),P(null);try{if(!n.name.toLowerCase().endsWith(`.json`)||n.size>Zp){M(`invalid`);return}let r;try{r=JSON.parse(await n.text())}catch{M(`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){M(`failed`);return}let a=sm(await i.json().catch(()=>null));if(!a){M(`failed`);return}P(a),M(`complete`);try{await f.onRetryAccounts?.(e.name)}catch{}}catch{M(`failed`)}finally{F.current&&(F.current.value=``),A(!1)}}};return(0,Q.jsxs)(`section`,{className:`pwi-section pwi-auth-section`,"aria-label":g(Y?`pws.availableAccounts`:`pws.apiKeys`),children:[(0,Q.jsxs)(`div`,{className:`pwi-auth-head`,children:[(0,Q.jsx)(`h3`,{className:`pwi-section-title`,children:g(Y?`pws.availableAccounts`:`pws.apiKeys`)}),(Y&&xe||ie)&&Te&&(0,Q.jsxs)(`div`,{className:`pwi-auth-head-actions`,children:[K&&(0,Q.jsx)(`span`,{role:`status`,className:K.ok?`pws-status-ok`:`pws-status-warn`,children:K.text}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:ne||u||!!c,onClick:()=>{ve()},children:[(0,Q.jsx)(ae,{width:14,height:14,"aria-hidden":`true`}),` `,g(ne?`codexAuth.refreshingQuota`:`codexAuth.refreshQuota`)]})]})]}),(0,Q.jsxs)(`div`,{className:`pwi-auth-body`,children:[e.name===`xai`&&(0,Q.jsx)(tm,{initialState:e.xaiResponsesOptInState??!0,onUpdateProvider:h}),Y&&(0,Q.jsxs)(Q.Fragment,{children:[le&&(0,Q.jsx)(Cf,{apiBase:t,provider:fl(e.name)?e.name:`anthropic`,accountCount:a.length,onThresholdChange:t=>{f?.onAccountPoolThreshold?.(e.name,t)}},`${t}:${e.name}`),e.name===`google-antigravity`&&(0,Q.jsxs)(`div`,{className:`pwi-auth-add-key`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{id:`cockpit-import-description`,className:`pwi-auth-row-secondary`,children:g(`pws.cockpitImportDescription`)}),(0,Q.jsx)(`label`,{className:`sr-only`,htmlFor:`cockpit-import-file`,children:g(`pws.cockpitImportFileLabel`)}),(0,Q.jsx)(`input`,{ref:F,id:`cockpit-import-file`,type:`file`,accept:`application/json,.json`,className:`sr-only`,"aria-describedby":`cockpit-import-description cockpit-import-status`,disabled:k,onChange:e=>{De(e.currentTarget.files?.[0])}})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:k,onClick:()=>F.current?.click(),children:g(k?`pws.cockpitImporting`:`pws.cockpitImportChooseFile`)}),(0,Q.jsxs)(`div`,{id:`cockpit-import-status`,role:`status`,"aria-live":`polite`,children:[j===`invalid`&&g(`pws.cockpitImportInvalid`),j===`failed`&&g(`pws.cockpitImportFailed`),j===`complete`&&N&&g(`pws.cockpitImportComplete`,{imported:N.importedCount,updated:N.updatedCount,failed:N.failedCount,unsupported:N.unsupportedCount})]})]}),(0,Q.jsxs)(`div`,{className:`pwi-auth-status-row`,children:[(0,Q.jsx)(`span`,{className:`pwi-auth-dot ${Ce?`pwi-auth-dot--warn`:xe?`pwi-auth-dot--ok`:`pwi-auth-dot--off`}`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`pwi-auth-status-text`,children:xe?a.length>0?g(`pws.loggedInTitle`):i?.email??g(`pws.loggedInTitle`):i?.error||g(`pws.notLoggedInTitle`)}),(0,Q.jsxs)(`span`,{className:`pwi-auth-actions`,children:[Se&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:u,onClick:()=>void f.onReauth(e.name,Se.id),children:g(`pws.reauthenticate`)}),xe?(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void f.onLogout(e.name),children:g(`prov.logout`)}):(0,Q.jsxs)(`button`,{ref:e.name===`kiro`?S:void 0,type:`button`,className:`btn btn-primary btn-sm`,disabled:u||e.name===`kiro`&&!!b,onClick:()=>w(!1),children:[u?(0,Q.jsx)(`span`,{className:`pwi-spin-inline`,"aria-hidden":`true`}):(0,Q.jsx)(ct,{style:{width:13,height:13},"aria-hidden":`true`}),g(u?`prov.waitingBrowser`:`prov.login`)]})]})]}),!u&&(0,Q.jsx)(wf,{}),u&&ye&&(0,Q.jsxs)(`div`,{className:`pwi-auth-wait`,children:[(0,Q.jsx)(`span`,{className:`pwi-spin-inline`,"aria-hidden":`true`}),(0,Q.jsxs)(`div`,{className:`pwi-auth-wait-copy`,children:[(0,Q.jsx)(`div`,{className:`pwi-auth-wait-title`,children:g(`prov.waitingBrowser`)}),(0,Q.jsx)(Hl,{hint:{url:ye.url,deviceCode:ye.deviceCode,instructions:ye.instructions,browserLaunch:ye.browserLaunch},paste:{value:I,busy:z,message:V,ok:U,onChange:L,onSubmit:()=>{be()}}}),f.onCancelLogin&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void f.onCancelLogin?.(e.name),children:g(`common.cancel`)})]})]}),s===`loading`&&a.length===0&&(0,Q.jsxs)(`div`,{className:`pwi-auth-state`,role:`status`,children:[(0,Q.jsx)(`span`,{className:`pwi-spin-inline`,"aria-hidden":`true`}),g(`pws.accountsLoading`)]}),s===`error`&&(0,Q.jsxs)(`div`,{className:`pwi-auth-state pwi-auth-state--error`,role:`alert`,children:[(0,Q.jsx)(`span`,{children:g(`pws.accountsLoadFailed`)}),f.onRetryAccounts&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void f.onRetryAccounts?.(e.name),children:g(`pws.retryAccounts`)})]}),a.length>0&&(0,Q.jsx)(`ul`,{className:`pwi-auth-list`,children:a.map(t=>{let n=Pc(a,t,g),r=e.name===`google-antigravity`?t.plan:void 0,i=c===t.id,o=l===t.id,s=t.health?.status,d=em(t),p=Tl(s),m=_l(t.id),h=Ol(g,t.health),v=kl(g,e.name,t.id,t.health);return(0,Q.jsxs)(`li`,{className:`pwi-auth-acct${t.active?` pwi-auth-acct--active`:``}`,children:[(0,Q.jsxs)(`div`,{className:`pwi-auth-row${t.active?` pwi-auth-row--active`:``}`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`pwi-auth-row-main`,onClick:()=>{!t.active&&!t.paused&&!d&&!p&&!c&&!l&&f.onSwitchAccount(e.name,t)},"aria-current":t.active?`true`:void 0,"aria-label":`${n}${r?` — ${r}`:``}${t.active?` — ${g(`pws.accountCurrent`)}`:``}`,disabled:!!(t.paused||d||p||c||l),children:[(0,Q.jsx)(`span`,{className:`pwi-auth-dot ${d?`pwi-auth-dot--warn`:t.active&&!t.paused?`pwi-auth-dot--ok`:`pwi-auth-dot--off`}`,"aria-hidden":`true`}),(0,Q.jsxs)(`span`,{className:`pwi-auth-row-copy`,children:[(0,Q.jsxs)(`span`,{className:`pwi-auth-row-heading`,children:[(0,Q.jsx)(`span`,{className:`pwi-auth-row-label`,children:n}),r&&(0,Q.jsx)(`span`,{className:`badge badge-green`,children:r})]}),(0,Q.jsx)(`span`,{className:`pwi-auth-row-secondary`,children:[t.email,`${g(`prov.accountId`)}: ${m}`].filter(Boolean).join(` · `)}),v&&(0,Q.jsx)(`span`,{className:`pwi-auth-row-secondary faint`,children:v}),p&&(0,Q.jsx)(`span`,{className:`pwi-auth-row-secondary faint`,children:g(`pws.healthCooldownHint`)}),t.paused&&(0,Q.jsx)(`span`,{className:`pwi-auth-row-secondary faint`,children:g(`pws.accountPausedHint`)})]}),h&&(0,Q.jsx)(`span`,{className:Sl(s),children:h}),d&&!h&&(0,Q.jsx)(`span`,{className:`badge badge-amber`,children:g(`pws.reauth`)}),Op(t,e.name)&&(0,Q.jsx)(`span`,{className:`badge badge-amber`,children:g(Op(t,e.name))}),t.paused&&(0,Q.jsx)(`span`,{className:`badge badge-muted`,title:t.pauseDetails?hl(g,_,t.pauseDetails):void 0,children:g(`codexAuth.paused`)}),t.active&&!t.paused&&(0,Q.jsx)(`span`,{className:`badge badge-primary`,children:g(`prov.accountActive`)}),i&&(0,Q.jsx)(`span`,{className:`badge badge-muted`,children:g(`pws.accountSwitching`)})]}),typeof t.paused==`boolean`&&f.onPauseAccount&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":`${g(t.paused?`codexAuth.resume`:`codexAuth.pause`)} — ${n}`,title:t.paused?g(`pws.accountPausedHint`):void 0,"aria-busy":o,disabled:u||!!c||!!l,onClick:()=>void f.onPauseAccount(e.name,t,!t.paused),children:g(t.paused?`codexAuth.resume`:`codexAuth.pause`)}),d&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:u||!!c||!!l,onClick:()=>void f.onReauth(e.name,t.id),children:g(`pws.reauthenticate`)}),X&&!d&&(0,Q.jsx)(Of,{entry:oe.entries[t.id],t:g,onClick:()=>ce(t)}),ue&&!d&&(0,Q.jsx)(Jf,{entry:fe.entries[t.id],t:g,onClick:()=>_e(t)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void f.onEditAlias(e.name,`oauth`,t.id,t.alias),children:g(`prov.editAlias`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm pwi-auth-row-remove`,"aria-label":`${g(`common.remove`)} — ${n}`,title:`${g(`common.remove`)} — ${n}`,disabled:!!c||!!l,onClick:()=>void f.onRemoveAccount(e.name,t),children:(0,Q.jsx)(R,{style:{width:13,height:13},"aria-hidden":`true`})})]}),(0,Q.jsxs)(`div`,{className:`pwi-auth-acct-quota`,children:[le&&t.autoSwitchThresholdOverride!==void 0&&t.autoSwitchThreshold!==void 0&&f.onAccountThreshold&&(0,Q.jsx)(bl,{accountLabel:n,inputId:`anthropic-threshold-${t.id}`,globalThreshold:t.autoSwitchThreshold,override:t.autoSwitchThresholdOverride,hintText:g(`pws.anthropicAccountThresholdHint`),disabled:u||!!c||!!l,onChange:n=>f.onAccountThreshold(e.name,t,n)}),(0,Q.jsx)(Fc,{quotaMode:t.quotaMode,quota:t.quota,quotaUnavailable:t.quotaUnavailable,quotaPending:t.quotaPending,quotaFailure:t.quotaFailure})]})]},t.id)})}),se&&(0,Q.jsx)(Af,{accountId:se.id,accountLabel:Pc(a,se,g),entry:oe.entries[se.id],controller:oe,onClose:()=>ce(null)}),ge&&(0,Q.jsx)($f,{accountId:ge.id,accountLabel:Pc(a,ge,g),entry:fe.entries[ge.id],controller:fe,onClose:()=>_e(null)},`${t}:${e.name}:${ge.id}`),s===`ready`&&xe&&a.length===0&&(0,Q.jsx)(`div`,{className:`pwi-auth-state pwi-auth-state--empty`,children:g(`pws.noAccounts`)}),xe&&(0,Q.jsxs)(`div`,{className:`pwi-auth-actions`,children:[(0,Q.jsx)(`button`,{ref:e.name===`kiro`?C:void 0,type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>w(!0),disabled:u||!!c||e.name===`kiro`&&!!b,children:g(`pws.addAccount`)}),Te&&(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:ne||u||!!c,onClick:()=>{ve()},children:[(0,Q.jsx)(ae,{width:14,height:14,"aria-hidden":`true`}),` `,g(ne?`codexAuth.refreshingQuota`:`codexAuth.refreshQuota`)]})]})]}),e.name===`kiro`&&b&&(0,Q.jsx)(Xp,{apiBase:t,triggerRef:b.addAccount?C:S,addAccount:b.addAccount,busy:u,onClose:()=>x(null),onCli:t=>{f.onLogin(e.name,t)},onSettled:f.onNativeLoginSettled}),ie&&(0,Q.jsxs)(Q.Fragment,{children:[o.length>0&&(0,Q.jsx)(`ul`,{className:`pwi-auth-list`,children:o.map(t=>(0,Q.jsxs)(`li`,{className:`pwi-auth-acct${t.active?` pwi-auth-acct--active`:``}`,children:[(0,Q.jsxs)(`div`,{className:`pwi-auth-row${t.active?` pwi-auth-row--active`:``}`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`pwi-auth-row-main`,onClick:()=>void f.onSwitchApiKey(e.name,t),disabled:t.active&&!t.disabled,"aria-label":t.disabled?`${g(`codexAuth.resume`)} — ${t.label??t.masked}`:void 0,children:[(0,Q.jsx)(`span`,{className:`pwi-auth-dot ${t.active?`pwi-auth-dot--ok`:`pwi-auth-dot--off`}`,"aria-hidden":`true`}),(0,Q.jsxs)(`span`,{className:`pwi-auth-row-copy`,children:[(0,Q.jsx)(`span`,{className:`pwi-auth-row-label`,children:t.label??t.masked}),t.label&&(0,Q.jsxs)(`code`,{className:`pwi-auth-row-secondary`,children:[t.masked,` · `,g(`prov.accountId`),`: `,t.id]})]}),t.disabled&&(0,Q.jsxs)(`span`,{className:`badge badge-muted`,title:t.pauseDetails?hl(g,_,t.pauseDetails):void 0,children:[g(`codexAuth.paused`),` · `,g(`codexAuth.resume`)]}),t.active&&!t.disabled&&(0,Q.jsx)(`span`,{className:`badge badge-primary`,children:g(`prov.accountActive`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void f.onEditAlias(e.name,`api-key`,t.id,t.label),children:g(`prov.editAlias`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm pwi-auth-row-remove`,"aria-label":`${g(`common.remove`)} — ${t.label??t.masked}`,title:`${g(`common.remove`)} — ${t.label??t.masked}`,onClick:()=>void f.onRemoveApiKey(e.name,t),children:(0,Q.jsx)(R,{style:{width:13,height:13},"aria-hidden":`true`})})]}),(0,Q.jsx)(`div`,{className:`pwi-auth-acct-quota`,children:(0,Q.jsx)(Fc,{quotaMode:t.quotaMode,quota:t.quota,quotaUnavailable:t.quotaUnavailable,quotaPending:t.quotaPending,quotaFailure:t.quotaFailure})})]},t.id))}),v?(0,Q.jsxs)(`div`,{className:`pwi-auth-add-key`,children:[(0,Q.jsx)(`input`,{className:`input`,type:`password`,value:T,onChange:e=>E(e.target.value),placeholder:g(`modal.apiKeyPlaceholder`),autoComplete:`off`,disabled:D}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>void Ee(),disabled:D||!T.trim(),children:g(D?`pws.saving`:`pws.addKey`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{y(!1),E(``)},children:g(`common.cancel`)})]}):(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{marginTop:8},onClick:()=>y(!0),children:g(`pws.addKey`)})]})]})]})}function lm(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 um(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 dm(e,t,n){let r=e?.find(e=>e.id===t);return r?.baseUrl?r.baseUrl.trim():n.trim()}function fm(e){if(e.adapter.trim()!==`openai-responses`||e.authMode&&e.authMode!==`key`&&e.authMode!==`local`)return!1;try{let t=new URL(e.baseUrl.trim());if(![`https:`,`http:`].includes(t.protocol)||t.username||t.password)return!1;let n=t.hostname.toLowerCase().replace(/\.$/,``);return n!==`api.openai.com`&&n!==`chatgpt.com`&&n!==`chat.openai.com`&&![`.openai.azure.com`,`.services.ai.azure.com`,`.cognitiveservices.azure.com`].some(e=>n.endsWith(e))}catch{return!1}}var pm=`https://chatgpt.com/backend-api/codex`;function mm(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 hm(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 gm(e){return e?e.adapter!==`openai-responses`||e.authMode!==`forward`||typeof e.baseUrl!=`string`||mm(e.baseUrl)!==pm?`invalid`:e.disabled===!0?`disabled`:`ready`:`absent`}function _m(e){return e.id===`openai`}function vm(e){return e.id===`openai`?e.codexAccountMode===`direct`?`prov.openaiDirectDesc`:`prov.openaiPoolDesc`:null}function ym(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),fm(e)&&e.preserveResponsesReasoningContent===!0&&(t.preserveResponsesReasoningContent=!0),t}function bm(e,t){return _m(e)?xm(e):{name:t.name.trim(),provider:ym(t)}}function xm(e){if(!e.provider)throw Error(`Missing canonical provider seed for ${e.id}`);return{name:e.id,provider:structuredClone(e.provider)}}var Sm=class extends Error{i18nKey;constructor(e){super(e),this.name=`OpenAiEnableError`,this.i18nKey=e}};async function Cm(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 Sm(`codexAuth.enableOpenaiFailed`)}let r=await n(`${e}/api/provider-presets`);if(!r.ok)throw new Sm(`codexAuth.openaiPresetLoadFailed`);let i=(await r.json()).providers?.find(e=>e.id===`openai`);if(!i?.provider)throw new Sm(`codexAuth.openaiPresetUnavailable`);if(!(await n(`${e}/api/providers`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(xm(i))})).ok)throw new Sm(`codexAuth.enableOpenaiFailed`)}function wm({checked:e,onChange:t}){let r=n();return(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,style:{flexDirection:`row`,alignItems:`flex-start`,gap:8},children:[(0,Q.jsx)(`input`,{name:`preserveResponsesReasoningContent`,type:`checkbox`,checked:e,onChange:e=>t(e.target.checked)}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:r(`pws.responsesReasoningReplay`)}),(0,Q.jsx)(`span`,{className:`muted text-label`,style:{display:`block`,marginTop:2},children:r(`pws.responsesReasoningReplayHint`)})]})]})}var Tm=[`responses`,`chat`,`messages`],Em=[`responses`,`chat`,`messages`,`other`],Dm=[`responses`,`chat`,`messages`,`other`,`ir`,`responses-internal`],Om=[`native`,`translated`,`legacy-bridge`,`blocked`],km=[`preserved`,`degraded`,`unknown`],Am=[`same-wire-native`,`cross-wire-codec`,`cross-wire-ir`,`combo-or-policy-route`,`responses-only-feature`,`hosted-tool`,`vision-preprocessing`,`tool-result-image`,`auth-mode-not-native`,`effort-row`,`fast-row`,`caller-credential-required`,`not-migrated`,`surface-disabled`,`feature-unrepresentable`,`compatibility-reject`,`unknown-model`,`upstream-other`,`rollout-disabled`,`bridge-only-policy`,`oauth-account-pool`,`anthropic-beta-dropped`,`opaque-state-stripped`],jm=new Set(Tm),Mm=new Set(Em),Nm=new Set(Dm),Pm=new Set(Om),Fm=new Set(km),Im=new Set(Am);function Lm(e){return typeof e==`string`&&jm.has(e)}function Rm(e){return typeof e==`string`&&Mm.has(e)}function zm(e){return typeof e==`string`&&Nm.has(e)}function Bm(e){return typeof e==`string`&&Pm.has(e)}function Vm(e){return typeof e==`string`&&Fm.has(e)}function Hm(e){return typeof e==`string`&&Im.has(e)}function Um(e){switch(e){case`openai-responses`:return`responses`;case`openai-chat`:return`chat`;case`anthropic-messages`:return`messages`;default:return}}function Wm(e){switch(e){case`openai-responses`:return`responses`;case`openai-chat`:return`chat`;case`anthropic`:return`messages`;default:return`other`}}var Gm=[`request.tools`,`request.hosted_tools`,`request.images`,`request.documents`,`request.multiple_choices`,`request.logprobs`,`request.logit_bias`,`request.seed`,`request.audio`,`request.prediction`,`request.response_format`,`request.reasoning`,`request.thinking_budget`,`request.top_k`,`request.cache_control`,`request.previous_response_id`,`request.store`,`request.background`,`request.compaction`],Km=new Set(Gm);function qm(e){return typeof e==`string`&&Km.has(e)}var Jm={"request.tools":[`responses`,`chat`,`messages`],"request.hosted_tools":[`responses`],"request.images":[`responses`,`chat`,`messages`],"request.documents":[`responses`,`chat`,`messages`],"request.multiple_choices":[`chat`],"request.logprobs":[`responses`,`chat`],"request.logit_bias":[`chat`],"request.seed":[`chat`],"request.audio":[`chat`],"request.prediction":[`chat`],"request.response_format":[`responses`,`chat`],"request.reasoning":[`responses`,`chat`,`messages`],"request.thinking_budget":[`messages`],"request.top_k":[`messages`],"request.cache_control":[`messages`],"request.previous_response_id":[`responses`],"request.store":[`responses`],"request.background":[`responses`],"request.compaction":[`responses`]},Ym={pathHops:6,reasonCodes:8,featureEffects:24,candidates:16,attempts:16,identifierLength:200},Xm=[`hard-pin`,`operator`,`registry`,`provider-default`];function Zm(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}var Qm=new Set([`passthrough`,`translated`,`degraded`,`unsupported`]);function $m(e,t,n){return Array.isArray(e)&&e.length<=t&&e.every(n)}function eh(e){return typeof e==`string`&&e.length>0&&e.length<=Ym.identifierLength&&!/[\u0000-\u001f\u007f]/.test(e)}function th(e){return Zm(e)&&qm(e.feature)&&typeof e.disposition==`string`&&Qm.has(e.disposition)}function nh(e){return $m(e,Ym.pathHops,zm)&&e.length>0}function rh(e){return $m(e,Ym.reasonCodes,Hm)}function ih(e){return $m(e,Ym.featureEffects,qm)}function ah(e){return Zm(e)&&eh(e.provider)&&eh(e.model)&&eh(e.adapter)&&Rm(e.upstream)&&Bm(e.mode)&&(e.mode===`blocked`?Array.isArray(e.requestPath):nh(e.requestPath))&&(e.mode===`blocked`?Array.isArray(e.responsePath):nh(e.responsePath))&&Vm(e.fidelity)&&rh(e.reasonCodes)&&$m(e.featureEffects,Ym.featureEffects,th)&&ih(e.unknownFeatures)&&typeof e.eligible==`boolean`}function oh(e){return Zm(e)&&e.schemaVersion===1&&(e.basis===`preview`||e.basis===`dispatch`)&&typeof e.contractVersion==`string`&&typeof e.policyRevision==`string`&&Lm(e.inbound)&&eh(e.requestedModel)&&(e.routeKind===`direct`||e.routeKind===`combo`||e.routeKind===`policy`||e.routeKind===`unknown`)&&Bm(e.mode)&&rh(e.reasonCodes)&&$m(e.candidates,Ym.candidates,ah)&&ih(e.guaranteedFeatures)&&ih(e.partialFeatures)}function sh(e){return Zm(e)&&typeof e.ordinal==`number`&&Number.isInteger(e.ordinal)&&e.ordinal>0&&Rm(e.upstream)&&Bm(e.mode)&&e.mode!==`blocked`&&nh(e.requestPath)&&(e.responsePath===void 0||nh(e.responsePath))}function ch(e){return!(!Zm(e)||e.v!==1||!Lm(e.inbound)||!Bm(e.mode)||e.upstream!==void 0&&!Rm(e.upstream)||!(e.mode===`blocked`?Array.isArray(e.requestPath)&&e.requestPath.length===0&&Array.isArray(e.responsePath)&&e.responsePath.length===0:nh(e.requestPath)&&nh(e.responsePath))||!rh(e.reasonCodes)||typeof e.contractVersion!=`string`||e.featureEffects!==void 0&&!$m(e.featureEffects,Ym.featureEffects,th)||e.attempts!==void 0&&!$m(e.attempts,Ym.attempts,sh)||e.planMismatch!==void 0&&e.planMismatch!==!0)}function lh(e){if(ch(e))return{v:1,inbound:e.inbound,mode:e.mode,...e.upstream===void 0?{}:{upstream:e.upstream},requestPath:[...e.requestPath],responsePath:[...e.responsePath],reasonCodes:[...e.reasonCodes],...e.featureEffects?{featureEffects:e.featureEffects.map(e=>({...e}))}:{},...e.attempts?{attempts:e.attempts.map(e=>({...e,requestPath:[...e.requestPath],...e.responsePath?{responsePath:[...e.responsePath]}:{}}))}:{},...e.planMismatch?{planMismatch:!0}:{},contractVersion:e.contractVersion}}var uh=new Set(Xm);function dh(e){return typeof e==`string`&&uh.has(e)}function fh(e){return Zm(e)&&eh(e.model)&&eh(e.adapter)&&dh(e.source)}function ph(e){return Zm(e)&&eh(e.name)&&eh(e.adapter)&&dh(e.adapterSource)&&(e.authMode===null||eh(e.authMode))&&Rm(e.upstream)&&$m(e.modelOverrides,64,fh)&&(e.modelOverridesTruncated===void 0||e.modelOverridesTruncated===!0)}var mh=32,hh=new Map;function gh(e,t,n){return JSON.stringify([e,t.model,t.inbound,[...new Set(t.features)].sort(),n])}function _h(e,t){for(hh.delete(e),hh.set(e,t);hh.size>mh;){let e=hh.keys().next().value;if(e===void 0)break;hh.delete(e)}}function vh(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function yh(e){if(!vh(e)||e.schemaVersion!==1||typeof e.policyRevision!=`string`||!Array.isArray(e.features)||!e.features.every(qm)||!vh(e.surfaces))return null;let t={};for(let[n,r]of Object.entries(e.surfaces)){if(!Lm(n)||!vh(r)||typeof r.enabled!=`boolean`)return null;t[n]={enabled:r.enabled}}return!t.responses||!t.chat||!t.messages?null:{policyRevision:e.policyRevision,features:[...e.features],surfaces:t}}async function bh(e,t){let n=await fetch(`${e}/api/protocols`,{signal:t});if(n.status===404)return null;if(!n.ok)throw Error(`HTTP ${n.status}`);let r=yh(await n.json());if(!r)throw Error(`invalid protocol info`);return r}async function xh(e,t,n){try{let r=await bh(e,n);if(!r)return{kind:`unavailable`};let i=gh(e,t,r.policyRevision),a=hh.get(i);if(a)return{kind:`plan`,plan:a};let o=await fetch(`${e}/api/protocols/plan`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({model:t.model,inbound:t.inbound,features:[...t.features]}),signal:n});if(o.status===404)return{kind:`unavailable`};if(!o.ok)return{kind:`error`};let s=await o.json();return oh(s)?(_h(gh(e,t,s.policyRevision),s),{kind:`plan`,plan:s}):{kind:`error`}}catch(e){if(e instanceof DOMException&&e.name===`AbortError`)throw e;return{kind:`error`}}}async function Sh(e,t,n){try{let r=await fetch(`${e}/api/protocols/settings`,{method:`PATCH`,headers:{"content-type":`application/json`},body:JSON.stringify(t),signal:n});if(r.status===404||r.status===405)return{kind:`unavailable`};let i=await r.json().catch(()=>null);if(!r.ok){let e=vh(i)&&vh(i.error)&&typeof i.error.code==`string`?i.error.code:void 0;return e?{kind:`error`,code:e}:{kind:`error`}}let a=yh(i);return a?{kind:`ok`,info:a}:{kind:`error`}}catch(e){if(e instanceof DOMException&&e.name===`AbortError`)throw e;return{kind:`error`}}}async function Ch(e,t,n){try{let r=await fetch(`${e}/api/protocols?${new URLSearchParams({provider:t}).toString()}`,{signal:n});if(r.status===404)return{kind:`unavailable`};if(!r.ok)return{kind:`error`};let i=await r.json();return!vh(i)||i.provider===void 0?{kind:`unavailable`}:!ph(i.provider)||i.provider.name!==t?{kind:`error`}:{kind:`summary`,summary:i.provider}}catch(e){if(e instanceof DOMException&&e.name===`AbortError`)throw e;return{kind:`error`}}}var wh={native:`logs.protocol.mode.native`,translated:`logs.protocol.mode.translated`,"legacy-bridge":`logs.protocol.mode.legacyBridge`,blocked:`logs.protocol.mode.blocked`},Th={passthrough:`logs.protocol.disposition.passthrough`,translated:`logs.protocol.disposition.translated`,degraded:`logs.protocol.disposition.degraded`,unsupported:`logs.protocol.disposition.unsupported`},Eh={responses:`logs.protocol.wire.responses`,chat:`logs.protocol.wire.chat`,messages:`logs.protocol.wire.messages`,other:`logs.protocol.wire.other`,ir:`logs.protocol.hop.ir`,"responses-internal":`logs.protocol.hop.internal`},Dh=` → `;function Oh(e,t){return t(Eh[e])}function kh(e,t){return e.map(e=>Oh(e,t)).join(Dh)}function Ah(e,t){let n=Oh(e.inbound,t);if(e.mode===`blocked`)return n;let r=e.upstream??e.requestPath[e.requestPath.length-1];return r?`${n}${Dh}${Oh(r,t)}`:n}var jh={"hard-pin":`pws.protocol.source.hardPin`,operator:`pws.protocol.source.operator`,registry:`pws.protocol.source.registry`,"provider-default":`pws.protocol.source.providerDefault`};function Mh({adapter:e}){let t=n();return(0,Q.jsxs)(`span`,{className:`ppp-wire`,children:[(0,Q.jsx)(`code`,{children:e}),(0,Q.jsx)(`span`,{className:`muted`,children:Oh(Wm(e),t)})]})}function Nh({apiBase:e,providerName:t,savedAdapter:r,draftAdapter:i,refreshKey:a}){let o=n(),s=JSON.stringify([e??``,t,r,a??``]),[c,l]=(0,Z.useState)(null);(0,Z.useEffect)(()=>{if(e===void 0)return;let n=new AbortController;return Ch(e,t,n.signal).then(e=>{n.signal.aborted||l(e.kind===`summary`?{key:s,kind:`summary`,summary:e.summary}:{key:s,kind:e.kind===`unavailable`?`hidden`:`error`})}).catch(()=>{}),()=>n.abort()},[e,t,s]);let u=c?.key===s?c:null;if(e===void 0||!u||u.kind===`hidden`)return null;let d=i&&i!==r?i:null;return(0,Q.jsxs)(`section`,{className:`ppp-card`,"aria-labelledby":`ppp-title`,"data-testid":`provider-protocol-panel`,children:[(0,Q.jsx)(`h3`,{id:`ppp-title`,children:o(`pws.protocol.title`)}),(0,Q.jsx)(`p`,{className:`pwi-settings-hint`,children:o(`pws.protocol.note`)}),u.kind===`error`?(0,Q.jsx)(`p`,{className:`muted small`,role:`status`,children:o(`pws.protocol.loadFailed`)}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`dl`,{className:`ppp-kv`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:o(`pws.protocol.adapterLabel`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(Mh,{adapter:u.summary.adapter})})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:o(`pws.protocol.source`)}),(0,Q.jsx)(`dd`,{"data-adapter-source":u.summary.adapterSource,children:o(jh[u.summary.adapterSource])})]}),u.summary.authMode&&(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:o(`pws.authMode`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(`code`,{children:u.summary.authMode})})]})]}),d&&(0,Q.jsx)(`p`,{className:`ppp-pending`,role:`status`,children:o(`pws.protocol.pending`,{adapter:d})}),(0,Q.jsx)(`h4`,{children:o(`pws.protocol.overrides`)}),u.summary.modelOverrides.length===0?(0,Q.jsx)(`p`,{className:`muted small`,children:o(`pws.protocol.noOverrides`)}):(0,Q.jsxs)(`table`,{className:`ppp-overrides`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`col`,children:o(`pws.protocol.col.model`)}),(0,Q.jsx)(`th`,{scope:`col`,children:o(`pws.protocol.col.wire`)}),(0,Q.jsx)(`th`,{scope:`col`,children:o(`pws.protocol.col.source`)})]})}),(0,Q.jsx)(`tbody`,{children:u.summary.modelOverrides.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`code`,{children:e.model})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(Mh,{adapter:e.adapter})}),(0,Q.jsx)(`td`,{"data-adapter-source":e.source,children:o(jh[e.source])})]},e.model))})]}),u.summary.modelOverridesTruncated&&(0,Q.jsx)(`p`,{className:`muted small`,children:o(`pws.protocol.overridesTruncated`,{count:u.summary.modelOverrides.length})})]})]})}function Ph({value:e,onChange:t,status:r=[]}){let i=n(),a=(n,r)=>{let i={...e.keys};r.trim()?i[n]=Number(r):delete i[n],t({...e,keys:Object.keys(i).length?i:void 0})};return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:i(`pws.keySelection`)}),(0,Q.jsxs)(`select`,{className:`input`,value:e.keySelection??`active`,onChange:n=>t({...e,keySelection:n.target.value}),children:[(0,Q.jsx)(`option`,{value:`active`,children:i(`pws.keyActive`)}),(0,Q.jsx)(`option`,{value:`round-robin`,children:i(`pws.keyRoundRobin`)})]})]}),(0,Q.jsx)(`h4`,{children:i(`pws.keyLimits`)}),(0,Q.jsx)(`div`,{className:`pwi-key-limits`,style:{display:`flex`,flexWrap:`wrap`,gap:12},children:[`requestsPerMinute`,`minIntervalMs`,`maxConcurrentRequests`].map((t,n)=>(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,style:{flex:`1 1 160px`,minWidth:0},children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:i([`pws.pacingRpm`,`pws.pacingDelay`,`pws.pacingConcurrency`][n])}),(0,Q.jsx)(`input`,{className:`input`,type:`number`,min:t===`requestsPerMinute`?1/60:1,step:t===`requestsPerMinute`?`any`:1,value:e.keys?.[t]??``,onChange:e=>a(t,e.target.value)})]},t))}),(0,Q.jsx)(`p`,{className:`pwi-settings-hint`,children:i(`pws.keySharedQuota`)}),r.length>0&&(0,Q.jsxs)(`table`,{style:{width:`100%`,tableLayout:`fixed`,overflowWrap:`anywhere`},children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:i(`pws.keyHandle`)}),(0,Q.jsx)(`th`,{children:i(`pws.keyStarts`)}),(0,Q.jsx)(`th`,{children:i(`pws.keyInFlight`)}),(0,Q.jsx)(`th`,{children:i(`pws.pacingQueued`)}),(0,Q.jsx)(`th`,{children:i(`pws.keyWait`)})]})}),(0,Q.jsx)(`tbody`,{children:r.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`code`,{children:e.id})}),(0,Q.jsx)(`td`,{children:e.starts}),(0,Q.jsx)(`td`,{children:e.inFlight}),(0,Q.jsx)(`td`,{children:e.queued}),(0,Q.jsx)(`td`,{children:e.cooldownUntil?i(`pws.keyCooldown`):`${e.nextSlotInMs} ms`})]},e.id))})]})]})}var Fh=[`openai-responses`,`openai-chat`,`anthropic`,`google`,`azure-openai`,`cursor`],Ih=[];function Lh(e){return e===`http1.1`||e===`h1`?`http1.1`:`http2`}function Rh(e){return e===void 0?``:String(e)}function zh(e){if(!e.trim())return;let t=Number(e);return Number.isFinite(t)&&t>=1/60?t:void 0}function Bh(e){if(!e.trim())return;let t=Number(e);return Number.isSafeInteger(t)&&t>0?t:void 0}function Vh(e){let t=Object.entries(e?.models??{}).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,t.requestsPerMinute??null,t.minIntervalMs??null,t.maxConcurrentRequests??null]);return JSON.stringify([e?.enabled===!0,e?.requestsPerMinute??null,e?.minIntervalMs??null,e?.maxConcurrentRequests??null,e?.keySelection??`active`,[e?.keys?.requestsPerMinute??null,e?.keys?.minIntervalMs??null,e?.keys?.maxConcurrentRequests??null],t])}function Hh({item:e,availableModels:t=Ih,apiBase:r,onUpdateProvider:i,onDirtyChange:a,onRegisterSave:o}){let s=n(),c=String(e.authMode??(e.keyOptional?`local`:`key`)),l=ye(e.name,e),u=l?e.liveModels!==!1:!1,d=Lh(e.upstreamHttpVersion),[f,p]=(0,Z.useState)(e.adapter),[m,h]=(0,Z.useState)(e.baseUrl),[g,_]=(0,Z.useState)(e.defaultModel??``),[v,y]=(0,Z.useState)(c),[b,x]=(0,Z.useState)(e.apiKeyTransport??`x-api-key`),[S,C]=(0,Z.useState)(e.note??``),[w,T]=(0,Z.useState)(e.allowPrivateNetwork??!1),[E,D]=(0,Z.useState)(e.preserveResponsesReasoningContent===!0),[O,k]=(0,Z.useState)(u),[A,j]=(0,Z.useState)(d),[N,P]=(0,Z.useState)(!1),[F,I]=(0,Z.useState)(null),[L,R]=(0,Z.useState)(e.codexAccountMode??`pool`),[z,B]=(0,Z.useState)(!1),[H,U]=(0,Z.useState)(null),[ee,W]=(0,Z.useState)(),[te,G]=(0,Z.useState)(r===void 0?`idle`:`loading`),[ne,K]=(0,Z.useState)(()=>`custom`),[re,q]=(0,Z.useState)(e.requestPacing?.enabled===!0),[J,Y]=(0,Z.useState)({keySelection:e.requestPacing?.keySelection,keys:e.requestPacing?.keys}),[ie,X]=(0,Z.useState)(()=>Rh(e.requestPacing?.requestsPerMinute)),[ae,oe]=(0,Z.useState)(()=>Rh(e.requestPacing?.minIntervalMs)),[se,ce]=(0,Z.useState)(()=>Rh(e.requestPacing?.maxConcurrentRequests)),[le,ue]=(0,Z.useState)(()=>({...e.requestPacing?.models??{}})),[de,fe]=(0,Z.useState)(``),[pe,me]=(0,Z.useState)(``),[he,ge]=(0,Z.useState)(``),[_e,ve]=(0,Z.useState)(``),[be,xe]=(0,Z.useState)(null);(0,Z.useEffect)(()=>{p(e.adapter),h(e.baseUrl),_(e.defaultModel??``),y(String(e.authMode??(e.keyOptional?`local`:`key`))),x(e.apiKeyTransport??`x-api-key`),C(e.note??``),T(e.allowPrivateNetwork??!1),D(e.preserveResponsesReasoningContent===!0),k(u),j(d),q(e.requestPacing?.enabled===!0),Y({keySelection:e.requestPacing?.keySelection,keys:e.requestPacing?.keys}),X(Rh(e.requestPacing?.requestsPerMinute)),oe(Rh(e.requestPacing?.minIntervalMs)),ce(Rh(e.requestPacing?.maxConcurrentRequests)),ue({...e.requestPacing?.models??{}}),I(null),U(null),queueMicrotask(()=>K(um(ee,e.baseUrl)))},[e.adapter,e.baseUrl,e.defaultModel,e.authMode,e.apiKeyTransport,e.keyOptional,e.note,e.allowPrivateNetwork,e.preserveResponsesReasoningContent,u,d,e.requestPacing,ee]),(0,Z.useEffect)(()=>{R(e.codexAccountMode??`pool`)},[e.codexAccountMode]),(0,Z.useEffect)(()=>{if(r===void 0)return;let t=!1,n=e.name,i=e.baseUrl;return fetch(`${r}/api/provider-presets`).then(e=>yn(e)).then(e=>{if(t)return;if(!e){W(void 0),G(`error`);return}let r=(e.providers??[]).find(e=>e.id===n)?.baseUrlChoices;W(r),G(`ready`),K(um(r,i))}).catch(()=>{t||(W(void 0),G(`error`))}),()=>{t=!0}},[r,e.name]),(0,Z.useEffect)(()=>{if(r===void 0)return;let t=!0,n=!1,i=()=>{if(n)return;n=!0;let i=M(1e4);fetch(`${r}/api/provider-request-pacing?name=${encodeURIComponent(e.name)}`,{signal:i.signal}).then(e=>yn(e)).then(e=>{t&&e&&xe(e)}).catch(()=>void 0).finally(()=>{i.clear(),n=!1})};i();let a=ba(i,2e3);return()=>{t=!1,a()}},[r,e.name]);let Se=(0,Z.useMemo)(()=>({enabled:re,...J,...zh(ie)===void 0?{}:{requestsPerMinute:zh(ie)},...Bh(ae)===void 0?{}:{minIntervalMs:Bh(ae)},...Bh(se)===void 0?{}:{maxConcurrentRequests:Bh(se)},...Object.keys(le).length>0?{models:le}:{}}),[J,se,ae,re,le,ie]),Ce=!Te(e.name)&&fm({adapter:f,baseUrl:m,authMode:v}),we=Ce&&E!==(e.preserveResponsesReasoningContent===!0),Ee=we||f.trim()!==e.adapter||m.trim()!==e.baseUrl||g.trim()!==(e.defaultModel??``)||v!==String(e.authMode??(e.keyOptional?`local`:`key`))||f.trim()===`anthropic`&&v===`key`&&b!==(e.apiKeyTransport??`x-api-key`)||S.trim()!==(e.note??``)||w!==(e.allowPrivateNetwork??!1)||O!==u||f.trim()===`cursor`&&A!==d,De=Vh(Se)!==Vh(e.requestPacing),Oe=Ee||De;(0,Z.useEffect)(()=>(a?.(Oe),()=>a?.(!1)),[Oe,a]);let ke=(0,Z.useMemo)(()=>{let n=new Set(t);return g.trim()&&n.add(g.trim()),e.defaultModel&&n.add(e.defaultModel),[...n].sort((e,t)=>e.localeCompare(t))},[t,g,e.defaultModel]),Ae=(0,Z.useMemo)(()=>{let e=[...Fh];return f&&!e.includes(f)&&e.unshift(f),e},[f]),je=Te(e.name),Me=te===`ready`&&!!(ee&&ee.length>0),Ne=f.trim()===`anthropic`&&v===`key`,Pe=e.name===`openai`?gm(e):`invalid`,Fe=Pe===`ready`||Pe===`disabled`,Ie=je&&te!==`error`,Le=async()=>{if(!i)return I({ok:!1,text:s(`pws.updatesUnavailable`)}),!1;if(z)return!1;let t=Me?dm(ee,ne,m):m.trim();if(!f.trim()||!t)return I({ok:!1,text:s(`pws.adapterBaseRequired`)}),!1;P(!0),I(null);try{if(se.trim()!==``&&Bh(se)===void 0)return I({ok:!1,text:s(`pws.pacingCapInvalid`)}),!1;if(Object.entries(J.keys??{}).some(([e,t])=>!Number.isFinite(t)||t<=0||e!==`requestsPerMinute`&&!Number.isSafeInteger(t)||e===`requestsPerMinute`&&(t<1/60||t>6e4)||e===`minIntervalMs`&&t>36e5))return I({ok:!1,text:s(`pws.keyLimitInvalid`)}),!1;if(re&&!Se.requestsPerMinute&&!Se.minIntervalMs&&!Se.maxConcurrentRequests&&!Se.models&&!Se.keys&&Se.keySelection!==`round-robin`)return I({ok:!1,text:s(`pws.pacingRuleRequired`)}),!1;let n=De&&!Ee,r=n?{requestPacing:Se}:{adapter:f.trim(),baseUrl:t,defaultModel:g.trim(),authMode:v,note:S.trim(),allowPrivateNetwork:w,...De?{requestPacing:Se}:{}};n||(l&&O!==(e.liveModels!==!1)&&(r.liveModels=O),we&&(r.preserveResponsesReasoningContent=E),f.trim()===`cursor`&&A!==d&&(r.upstreamHttpVersion=A===`http1.1`?`http1.1`:null),Ne?r.apiKeyTransport=b:e.apiKeyTransport!==void 0&&(r.apiKeyTransport=``));let a=await i(e.name,r);return I(a.ok?{ok:!0,text:s(`pws.settingsSaved`)}:{ok:!1,text:a.error||s(`prov.saveFailed`)}),a.ok}finally{P(!1)}},Re=(0,Z.useRef)(Le);(0,Z.useEffect)(()=>{Re.current=Le}),(0,Z.useEffect)(()=>{if(o)return o(()=>Re.current()),()=>o(null)},[o]);let ze=async e=>{if(!(z||N||e===L)){if(!i)U({ok:!1,text:s(`pws.updatesUnavailable`)});else{B(!0),U(null);try{let t=await i(`openai`,{codexAccountMode:e});t.ok?(R(e),U({ok:!0,text:s(`pws.accountModeSaved`)})):U({ok:!1,text:t.error||s(`pws.accountModeFailed`)})}catch{U({ok:!1,text:s(`pws.accountModeFailed`)})}finally{B(!1)}}}},Be=async(e,t)=>{await ha({message:s(`pws.accountModeConfirm`)})?await ze(e):t.value=L},Ve=()=>{p(e.adapter),h(e.baseUrl),_(e.defaultModel??``),y(c),x(e.apiKeyTransport??`x-api-key`),C(e.note??``),T(e.allowPrivateNetwork??!1),k(u),D(e.preserveResponsesReasoningContent===!0),j(d),I(null),q(e.requestPacing?.enabled===!0),X(Rh(e.requestPacing?.requestsPerMinute)),Y({keySelection:e.requestPacing?.keySelection,keys:e.requestPacing?.keys}),oe(Rh(e.requestPacing?.minIntervalMs)),ce(Rh(e.requestPacing?.maxConcurrentRequests)),ue({...e.requestPacing?.models??{}}),K(um(ee,e.baseUrl))},He=(e,t)=>{switch(e){case`token-plan`:return s(`modal.endpoint.tokenPlan`);case`payg`:return s(`modal.endpoint.payAsYouGo`);case`custom`:return s(`modal.endpoint.custom`);default:return t}};return(0,Q.jsxs)(`div`,{className:`pwi-settings-form`,children:[(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsxs)(`span`,{className:`pwi-settings-label`,children:[(0,Q.jsx)(ct,{style:{width:12,height:12}}),` `,s(`pws.providerId`)]}),(0,Q.jsx)(`input`,{className:`input`,value:e.name,readOnly:!0,disabled:!0})]}),(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:s(`modal.adapter`)}),je?(0,Q.jsx)(`input`,{className:`input`,value:f,readOnly:!0,disabled:!0}):(0,Q.jsx)(`select`,{className:`input`,value:f,onChange:e=>p(e.target.value),children:Ae.map(e=>(0,Q.jsx)(`option`,{value:e,children:e},e))})]}),(0,Q.jsx)(Nh,{apiBase:r,providerName:e.name,savedAdapter:e.adapter,draftAdapter:f.trim(),refreshKey:`${e.baseUrl}|${e.authMode??``}`}),Me?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:s(`modal.endpoint`)}),(0,Q.jsx)(`select`,{className:`input`,value:ne,onChange:e=>{let t=e.target.value;K(t),h(lm(ee,t,m))},children:ee.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:He(e.id,e.label)},e.id))})]}),ne===`custom`&&(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:s(`modal.baseUrl`)}),(0,Q.jsx)(`input`,{className:`input`,value:m,onChange:e=>h(e.target.value),placeholder:s(`modal.baseUrlPlaceholder`)})]})]}):(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:s(`modal.baseUrl`)}),(0,Q.jsx)(`input`,{className:`input`,value:m,onChange:e=>h(e.target.value),readOnly:Ie,disabled:Ie})]}),f.trim()===`cursor`&&(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:s(`pws.cursorTransport`)}),(0,Q.jsxs)(`select`,{className:`input`,value:A,onChange:e=>j(e.target.value),children:[(0,Q.jsx)(`option`,{value:`http2`,children:s(`pws.cursorTransportHttp2`)}),(0,Q.jsx)(`option`,{value:`http1.1`,children:s(`pws.cursorTransportHttp1`)})]}),(0,Q.jsx)(`span`,{className:`pwi-settings-hint`,children:s(`pws.cursorTransportDesc`)})]}),(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:s(`pws.cell.defaultModel`)}),ke.length>0?(0,Q.jsxs)(`select`,{className:`input`,value:g,onChange:e=>_(e.target.value),children:[(0,Q.jsx)(`option`,{value:``,children:s(`pws.defaultModelNone`)}),ke.map(e=>(0,Q.jsx)(`option`,{value:e,children:e},e))]}):(0,Q.jsx)(`input`,{className:`input`,value:g,onChange:e=>_(e.target.value),placeholder:s(`pws.optionalPlaceholder`)})]}),(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:s(`pws.authMode`)}),je?(0,Q.jsx)(`input`,{className:`input`,value:V(e,s),readOnly:!0,disabled:!0}):(0,Q.jsxs)(`select`,{className:`input`,value:v,onChange:e=>y(e.target.value),children:[(0,Q.jsx)(`option`,{value:`key`,children:s(`modal.badge.apiKey`)}),(0,Q.jsx)(`option`,{value:`forward`,children:s(`pws.auth.chatgptPassthrough`)}),(0,Q.jsx)(`option`,{value:`oauth`,children:s(`modal.badge.oauth`)}),(0,Q.jsx)(`option`,{value:`local`,children:s(`modal.badge.local`)})]})]}),Fe&&(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:s(`codexAuth.accountModeTitle`)}),(0,Q.jsxs)(`select`,{className:`input`,value:L,disabled:z||N,onChange:e=>{let t=e.target.value;t!==L&&Be(t,e.currentTarget)},children:[(0,Q.jsx)(`option`,{value:`pool`,children:s(`codexAuth.accountModePool`)}),(0,Q.jsx)(`option`,{value:`direct`,children:s(`codexAuth.accountModeDirect`)})]}),(0,Q.jsx)(`span`,{className:`pwi-settings-hint`,children:s(L===`direct`?`codexAuth.accountModeDirectDesc`:`codexAuth.accountModePoolDesc`)}),z&&(0,Q.jsx)(`span`,{className:`muted text-label`,children:s(`pws.accountSwitching`)}),H&&(0,Q.jsx)(`span`,{role:H.ok?`status`:`alert`,className:H.ok?`pwi-settings-mode-msg pwi-settings-mode-msg--ok`:`pwi-settings-mode-msg pwi-settings-mode-msg--err`,children:H.text})]}),Ne&&(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:s(`modal.apiKeyTransport`)}),(0,Q.jsxs)(`select`,{className:`input`,value:b,onChange:e=>x(e.target.value),children:[(0,Q.jsx)(`option`,{value:`x-api-key`,children:s(`modal.apiKeyTransportNative`)}),(0,Q.jsx)(`option`,{value:`bearer`,children:s(`modal.apiKeyTransportBearer`)})]})]}),(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:s(`pws.note`)}),(0,Q.jsx)(`textarea`,{className:`input pwi-settings-textarea`,value:S,onChange:e=>C(e.target.value),rows:2})]}),(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,style:{flexDirection:`row`,alignItems:`center`,gap:8},children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:w,onChange:e=>T(e.target.checked)}),(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:s(`pws.allowPrivateNetwork`)})]}),Ce&&(0,Q.jsx)(wm,{checked:E,onChange:D}),(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,style:{flexDirection:`row`,alignItems:`flex-start`,gap:8},children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:O,disabled:!l,onChange:e=>k(e.target.checked)}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:s(`pws.liveModels`)}),(0,Q.jsx)(`span`,{className:`muted text-label`,style:{display:`block`,marginTop:2},children:s(`pws.liveModelsDesc`)})]})]}),(0,Q.jsxs)(`section`,{className:`pwi-pacing-card`,"aria-labelledby":`pwi-pacing-title`,children:[(0,Q.jsxs)(`div`,{className:`pwi-pacing-head`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h3`,{id:`pwi-pacing-title`,children:s(`pws.pacingTitle`)}),(0,Q.jsx)(`p`,{children:s(`pws.pacingDesc`)})]}),(0,Q.jsxs)(`label`,{className:`pwi-pacing-toggle`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:re,onChange:e=>q(e.target.checked)}),` `,s(`pws.pacingEnabled`)]})]}),(0,Q.jsxs)(`div`,{className:`pwi-pacing-grid`,children:[(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:s(`pws.pacingRpm`)}),(0,Q.jsx)(`input`,{className:`input`,type:`number`,min:`0.016667`,step:`any`,value:ie,onChange:e=>X(e.target.value),placeholder:`38`})]}),(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:s(`pws.pacingDelay`)}),(0,Q.jsx)(`input`,{className:`input`,type:`number`,min:`1`,step:`1`,value:ae,onChange:e=>oe(e.target.value),placeholder:`1600`})]}),(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:s(`pws.pacingConcurrency`)}),(0,Q.jsx)(`input`,{className:`input`,type:`number`,min:`1`,step:`1`,value:se,onChange:e=>ce(e.target.value),placeholder:`8`})]})]}),(0,Q.jsx)(`p`,{className:`pwi-settings-hint`,children:s(`pws.pacingSlowerWins`)}),(0,Q.jsxs)(`div`,{className:`pwi-pacing-status`,"aria-live":`polite`,children:[(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:be?.queued??0}),` `,s(`pws.pacingQueued`)]}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsxs)(`strong`,{children:[be?.nextSlotInMs??0,` ms`]}),` `,s(`pws.pacingNextSlot`)]}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:be?.lastModelId??s(`pws.pacingNone`)}),` `,s(`pws.pacingLastModel`)]})]}),v!==`oauth`&&v!==`forward`&&(0,Q.jsx)(Ph,{value:J,onChange:Y,status:be?.keys}),(0,Q.jsx)(`h4`,{children:s(`pws.pacingModelOverrides`)}),(0,Q.jsxs)(`div`,{className:`pwi-pacing-grid pwi-pacing-grid--model`,children:[(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:s(`pws.pacingModel`)}),(0,Q.jsx)(`input`,{className:`input`,list:`pacing-models-${e.name}`,value:de,onChange:e=>fe(e.target.value)}),(0,Q.jsx)(`datalist`,{id:`pacing-models-${e.name}`,children:t.map(e=>(0,Q.jsx)(`option`,{value:e},e))})]}),(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:s(`pws.pacingRpm`)}),(0,Q.jsx)(`input`,{className:`input`,type:`number`,min:`0.016667`,step:`any`,value:pe,onChange:e=>me(e.target.value)})]}),(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:s(`pws.pacingDelay`)}),(0,Q.jsx)(`input`,{className:`input`,type:`number`,min:`1`,step:`1`,value:he,onChange:e=>ge(e.target.value)})]}),(0,Q.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,Q.jsx)(`span`,{className:`pwi-settings-label`,children:s(`pws.pacingConcurrency`)}),(0,Q.jsx)(`input`,{className:`input`,type:`number`,min:`1`,step:`1`,value:_e,onChange:e=>ve(e.target.value)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{let e=de.trim(),t=zh(pe),n=Bh(he),r=Bh(_e);_e.trim()!==``&&r===void 0?I({ok:!1,text:s(`pws.pacingCapInvalid`)}):!e||t===void 0&&n===void 0&&r===void 0||(ue(i=>({...i,[e]:{...t===void 0?{}:{requestsPerMinute:t},...n===void 0?{}:{minIntervalMs:n},...r===void 0?{}:{maxConcurrentRequests:r}}})),fe(``),me(``),ge(``),ve(``))},children:s(`pws.pacingAdd`)})]}),Object.entries(le).length>0&&(0,Q.jsx)(`div`,{className:`pwi-pacing-overrides`,children:Object.entries(le).map(([e,t])=>(0,Q.jsxs)(`div`,{className:`pwi-pacing-row`,children:[(0,Q.jsx)(`code`,{children:e}),(0,Q.jsx)(`span`,{children:[t.requestsPerMinute===void 0?void 0:`${t.requestsPerMinute} ${s(`pws.pacingRpmUnit`)}`,t.minIntervalMs===void 0?void 0:`${t.minIntervalMs} ms`,t.maxConcurrentRequests===void 0?void 0:`${t.maxConcurrentRequests} ${s(`pws.pacingCapUnit`)}`].filter(e=>e!==void 0).join(` · `)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>ue(t=>Object.fromEntries(Object.entries(t).filter(([t])=>t!==e))),"aria-label":s(`pws.pacingRemoveModel`,{model:e}),children:s(`pws.pacingRemove`)})]},e))})]}),Oe&&(0,Q.jsxs)(`div`,{className:`pwi-settings-sticky-bar`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:s(`pws.settingsUnsavedBar`)}),(0,Q.jsxs)(`div`,{className:`pwi-settings-sticky-bar-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:Ve,disabled:N,children:s(`pws.discardSettings`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>void Le(),disabled:N||z,children:s(N?`pws.saving`:`pws.saveSettings`)})]})]}),F&&(0,Q.jsx)(`div`,{role:F.ok?`status`:`alert`,className:F.ok?`pwi-settings-msg pwi-settings-msg--ok`:`pwi-settings-msg pwi-settings-msg--err`,children:F.text})]})}function Uh({providerName:e,defaultProviderName:t,onConfirm:r,onCancel:i}){let a=n();return(0,Q.jsx)(`div`,{className:`dialog-backdrop`,onClick:i,children:(0,Q.jsxs)(`div`,{className:`dialog`,role:`alertdialog`,"aria-label":a(`pws.removeConfirmTitle`),onClick:e=>e.stopPropagation(),children:[(0,Q.jsx)(`h3`,{children:a(`pws.removeConfirmTitle`)}),(0,Q.jsx)(`p`,{children:t?a(`pws.removeDefaultConfirmBody`,{name:e,defaultProvider:t}):a(`pws.removeConfirmBody`,{name:e})}),(0,Q.jsxs)(`div`,{className:`dialog-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:i,children:a(`common.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-danger`,onClick:r,children:a(`pws.removeConfirm`)})]})]})})}function Wh({onSave:e,onDiscard:t,onCancel:r,saving:i=!1}){let a=n();return(0,Q.jsx)(`div`,{className:`dialog-backdrop`,onClick:r,children:(0,Q.jsxs)(`div`,{className:`dialog`,role:`alertdialog`,"aria-label":a(`pws.unsavedLeaveTitle`),onClick:e=>e.stopPropagation(),children:[(0,Q.jsx)(`h3`,{children:a(`pws.unsavedLeaveTitle`)}),(0,Q.jsx)(`p`,{children:a(`pws.unsavedLeaveBody`)}),(0,Q.jsxs)(`div`,{className:`dialog-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:r,children:a(`common.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:t,children:a(`pws.discardSettings`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:e,disabled:i,children:a(i?`pws.saving`:`pws.saveSettings`)})]})]})})}function Gh({item:e,preset:t,usageTotals:r,modelUsage:i,quotaReport:a,availableModels:o,hasLiveModels:s,selectedModels:c,modelRows:l,modelRevision:u,modelRowsReady:d,onOpenModels:f,onCreateJevAuto:p,modelsLoading:m,modelsLoadFailed:h,onRetryModels:g,oauthEmail:_,onDeselect:v,apiBase:y,oauth:b,accounts:x,accountLoadState:S,accountsFocusToken:C=0,accountsFocusProvider:w=null,settingsFocusToken:T=0,settingsFocusProvider:E=null,switchingAccountId:D,pausingAccountId:O,keys:k,busyProvider:A,loginHint:j,authHandlers:M,onCodexActiveNeedsReauthChange:N,codexController:P,onUpdateProvider:F,isDefault:I,onRemoveProvider:L,onSetDisabled:z,onSetDefault:B,onRefreshQuota:V}){let H=n(),[U,ee]=(0,Z.useState)(`overview`),[te,G]=(0,Z.useState)(!1),[K,re]=(0,Z.useState)(null),[q,J]=(0,Z.useState)(!1),Y=(0,Z.useRef)(null),[ie,X]=(0,Z.useState)(0),[ae,oe]=(0,Z.useState)(0),se=(0,Z.useCallback)(e=>{Y.current=e},[]),ce=e.disabled===!0,le=(0,Z.useMemo)(()=>ne(e),[e]),ue=(0,Z.useMemo)(()=>W(e),[e]),de=(0,Z.useMemo)(()=>Nc(e),[e]),fe=de===`oauth-accounts`?x?.find(e=>e.active):de===`api-keys`?k?.find(e=>e.active):void 0,pe=w===e.name?C:0,me=JSON.stringify([P?.activeId??``,x?.find(e=>e.active)?.id??``,k?.find(e=>e.active)?.id??``,b?.loggedIn===void 0?``:String(b.loggedIn),b?.needsReauth===void 0?``:String(b.needsReauth),_??``]),he=(0,Z.useMemo)(()=>[{id:`overview`,label:H(`pws.tab.overview`)},{id:`models`,label:H(`pws.tab.models`)},{id:`usage`,label:H(`pws.tab.usage`)},...de?[{id:`accounts`,label:H(de===`api-keys`?`pws.apiKeys`:`pws.tab.accounts`)}]:[],{id:`settings`,label:H(`pws.tab.settings`)}],[de,H]),ge=(0,Z.useCallback)(e=>{te&&U===`settings`&&e!==`settings`?re(e):ee(e)},[U,te]);pe!==ie&&(!pe||de)&&(X(pe),pe&&de&&(te&&U===`settings`?re(`accounts`):ee(`accounts`)));let ve=E===e.name?T:0;ve!==ae&&(oe(ve),ve&&ee(`settings`));let ye=(0,Z.useCallback)(()=>{te&&U===`settings`?re(`deselect`):v()},[te,U,v]),be=(0,Z.useCallback)((e,t)=>{let n;if(e.key===`ArrowRight`)n=(t+1)%he.length;else if(e.key===`ArrowLeft`)n=(t-1+he.length)%he.length;else if(e.key===`Home`)n=0;else if(e.key===`End`)n=he.length-1;else return;e.preventDefault(),ge(he[n].id),e.currentTarget.parentElement?.querySelectorAll(`[role="tab"]`)[n]?.focus()},[ge,he]),xe=`pws-tab-${U}`,Se=`pws-panel-${U}`;return(0,Q.jsxs)(`div`,{className:`pws-detail`,children:[(0,Q.jsx)(`div`,{className:`pws-detail-head`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`pws-detail-back-link`,onClick:ye,children:[(0,Q.jsx)(Ye,{className:`pws-detail-back-chevron`,"aria-hidden":`true`}),H(`pws.allProviders`)]})}),(0,Q.jsxs)(`div`,{className:`pws-detail-head-main`,children:[(0,Q.jsx)(_e,{name:e.name,adapter:e.adapter,baseUrl:e.baseUrl,cls:`pws-detail-icon`}),(0,Q.jsx)(`div`,{className:`pws-detail-title-wrap`,children:(0,Q.jsxs)(`h2`,{className:`pws-detail-title`,children:[Ce(e.name,H),ue&&(0,Q.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--local`,children:H(`modal.badge.local`)}),!ue&&le&&(0,Q.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--free`,children:H(`modal.badge.free`)})]})}),(0,Q.jsxs)(`div`,{className:`pws-detail-actions`,children:[!I&&!ce&&B&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>B(e.name),children:H(`prov.setDefault`)}),L&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm btn-icon-only`,onClick:()=>L(e.name),"aria-label":H(`pws.removeConfirmTitle`),title:H(`pws.removeConfirmTitle`),children:(0,Q.jsx)(R,{style:{width:15,height:15},"aria-hidden":`true`})}),z&&(0,Q.jsxs)(`div`,{className:`pws-detail-toggle`,children:[(0,Q.jsx)(`span`,{className:`pws-detail-toggle-label`,children:H(`pws.enabledLabel`)}),(0,Q.jsx)(ln,{on:!ce,onClick:()=>z(e.name,!ce),disabled:I,label:H(`pws.enabledLabel`)})]})]})]}),(0,Q.jsx)(`div`,{className:`pws-detail-tabs`,role:`tablist`,children:he.map((e,t)=>(0,Q.jsx)(`button`,{type:`button`,role:`tab`,id:`pws-tab-${e.id}`,"aria-controls":`pws-panel-${e.id}`,"aria-selected":U===e.id,tabIndex:U===e.id?0:-1,className:`pws-detail-tab${U===e.id?` pws-detail-tab--active`:``}`,onClick:()=>ge(e.id),onKeyDown:e=>be(e,t),children:e.label},e.id))}),(0,Q.jsxs)(`div`,{className:`pws-detail-panel`,role:`tabpanel`,id:Se,"aria-labelledby":xe,tabIndex:0,children:[U===`overview`&&(0,Q.jsx)(rl,{item:e,preset:t,apiBase:y,connectionIdentity:me,availableModels:o,usageTotals:r,quotaReport:a,currentQuotaReading:fe,onRefreshQuota:V,oauthEmail:_,oauth:b,onEditSettings:()=>ge(`settings`),onViewUsage:()=>ge(`usage`),onCreateJevAuto:p,onUpdateProvider:F,reauthBusy:A===e.name,onCancelLogin:M?.onCancelLogin?()=>void M.onCancelLogin?.(e.name):void 0,onReauthenticate:e.activeNeedsReauth?()=>{if(e.authMode===`oauth`){let t=x??[],n=t.find(e=>e.active&&e.needsReauth)??t.find(e=>e.needsReauth);M?.onReauth(e.name,n?.id)}else ge(`accounts`)}:void 0}),U===`models`&&(0,Q.jsx)(ll,{item:e,apiBase:y,availableModels:o,hasLiveModels:s,selectedModels:c,modelRows:l,modelRevision:u,modelRowsReady:d,onOpenModels:f,modelsLoading:m,modelsLoadFailed:h,needsReauth:(x??[]).some(e=>e.active&&e.needsReauth)||b?.needsReauth===!0,onRetryModels:g,onOpenAccounts:de?()=>ge(`accounts`):void 0},e.name),U===`usage`&&(0,Q.jsx)(dl,{item:e,usageTotals:r,quotaReport:a,currentQuotaReading:fe,quotaIdentity:me,modelUsage:i,...V?{onRefreshQuota:V}:{}}),U===`accounts`&&(0,Q.jsx)(cm,{item:e,apiBase:y,oauth:b,accounts:x,keys:k,accountLoadState:S,switchingAccountId:D,pausingAccountId:O,busy:A===e.name,loginHint:j,authHandlers:M,onUpdateProvider:F,onCodexActiveNeedsReauthChange:N,codexController:P}),U===`settings`&&(0,Q.jsx)(Hh,{item:e,apiBase:y,availableModels:o,onUpdateProvider:F,onDirtyChange:G,onRegisterSave:se},e.name)]}),K&&(0,Q.jsx)(Wh,{saving:q,onCancel:()=>{q||re(null)},onDiscard:()=>{if(q)return;let e=K;re(null),G(!1),e===`deselect`?v():ee(e)},onSave:()=>{(async()=>{if(!q){J(!0);try{if(!(await Y.current?.()??!1))return;let e=K;re(null),G(!1),e===`deselect`?v():e&&ee(e)}finally{J(!1)}}})()}})]})}var Kh=new Set([`anthropic`,`anthropic2`,`google-antigravity`,`meta-muse`]),qh=new Set([`github-copilot`,`cursor`,`zed`]);function Jh(e){let t=e.trim().toLowerCase();return Kh.has(t)?`high`:qh.has(t)?`elevated`:null}function Yh(e){switch(e){case`high`:return`oauthTos.highTitle`;case`elevated`:return`oauthTos.elevatedTitle`;default:return e}}function Xh(e){switch(e){case`high`:return`oauthTos.highBody`;case`elevated`:return`oauthTos.elevatedBody`;default:return e}}function Zh(e,t){let n=e.trim().toLowerCase();return n===`anthropic`||n===`anthropic2`?{title:`oauthTos.anthropicTitle`,body:`oauthTos.anthropicBody`,conditions:`oauthTos.anthropicConditions`,saferPath:`oauthTos.anthropicSaferPath`,acknowledge:`oauthTos.anthropicAcknowledge`,continue:`oauthTos.anthropicContinue`}:{title:Yh(t),body:Xh(t),conditions:null,saferPath:n===`google-antigravity`?`oauthTos.saferPath`:null,acknowledge:`oauthTos.acknowledge`,continue:`oauthTos.continue`}}function Qh(e,t){return t===void 0?e:e.map(e=>({...e,active:e.id===t}))}function $h(e,t){let n=new Map(t.map(e=>[e.id,e]));return ng(e,t,!1).map(e=>tg(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?Rr(n.get(e.id)?.quotaFailure):void 0}:e)}function eg(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=ng([t],[e],!0)[0];return{...e,quota:r.quota,quotaPending:r.quotaPending,quotaUnavailable:r.quotaUnavailable,quotaFailure:r.quotaFailure}})}var tg=e=>e.quotaMode===`probe`||e.quotaMode===`passive`;function ng(e,t,n){let r=new Map(t.map(e=>[e.id,e]));return e.map(e=>{let t=tg(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?Rr(e.quotaFailure):void 0}})}function rg(e,t){let n=t&&new Map(t.map(e=>[e.id,e.quotaMode]));return e.map(e=>tg(e)&&(!n||n.get(e.id)===e.quotaMode)?{...e,quotaUnavailable:!0,quotaPending:!1,quotaFailure:void 0}:e)}function ig(e,t=!1){let n={};for(let[t,r]of Object.entries(e))wl(r.accounts.find(e=>e.active)??r.accounts.find(e=>e.id===r.activeAccountId))&&(n[t]=!0);return t&&(n.openai=!0),n}function ag(e){let{apiBase:t,t:n,config:r,aliveRef:i,notify:a,fetchConfig:o,fetchOauth:s,fetchProviderQuotas:c,codexActiveNeedsReauth:l}=e,[u,d]=(0,Z.useState)({}),[f,p]=(0,Z.useState)({}),[m,h]=(0,Z.useState)({}),g=Object.values(m)[0]??null,_=e=>h(e?{[e.provider]:e}:{}),[v,y]=(0,Z.useState)({}),b=Object.values(v)[0]??null,[x,S]=(0,Z.useState)({}),[C,w]=(0,Z.useState)({}),[T,E]=(0,Z.useState)(null),[D,O]=(0,Z.useState)(``),k=(0,Z.useRef)({}),A=(0,Z.useRef)({}),j=(0,Z.useRef)({}),N=(0,Z.useRef)(new Map),P=(0,Z.useRef)(new Set),F=(0,Z.useRef)(new Map),I=(0,Z.useRef)(new Map),L=(0,Z.useRef)(!0),R=(0,Z.useRef)(t);(0,Z.useEffect)(()=>{let e=k.current,n=P.current,r=A.current,i=j.current,a=N.current,o=F.current,s=I.current;L.current=!0;let c=R.current!==t;return R.current=t,c&&Promise.resolve().then(()=>{L.current&&R.current===t&&(d({}),y({}),h({}),w({}),p({}))}),()=>{L.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(),o.clear(),s.clear();for(let e of n)e.abort();n.clear()}},[t]);let z=(0,Z.useRef)(null),B=(0,Z.useRef)(null),V=(0,Z.useCallback)(async(e,t)=>{let n=M(2e4),r=()=>n.controller.abort();t?.aborted&&r(),t?.addEventListener(`abort`,r,{once:!0}),P.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),P.current.delete(n.controller)}},[]),H=(0,Z.useCallback)(async(e,n=!1)=>{if(!i.current||!L.current||R.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=(k.current[r]??0)+1;k.current[r]=a;let o=(A.current[r]??0)+1;A.current[r]=o;let s=()=>i.current&&L.current&&R.current===t&&k.current[r]===a,c=()=>s()&&A.current[r]===o,l=`${t}/api/oauth/accounts?provider=${encodeURIComponent(e)}`;try{let a=await V(l);if(!Array.isArray(a.accounts))throw Error(`Invalid account roster`);if(!s())return!1;let o=Qh(a.accounts,a.activeAccountId);if(d(t=>c()?{...t,[e]:{activeAccountId:a.activeAccountId??null,accounts:ng(o,t[e]?.accounts??[],!1)}}:t),p(t=>c()?{...t,[e]:`ready`}:t),!o.some(tg))return!0;let u=async()=>{let s=(j.current[r]??0)+1;j.current[r]=s;let u=()=>i.current&&L.current&&R.current===t&&j.current[r]===s;try{let t=await V(`${l}&quota=1${n?`&refresh=1`:``}`);if(!Array.isArray(t.accounts))throw Error(`Invalid account quota roster`);if(!u())return!1;let r=Qh(t.accounts,t.activeAccountId);return d(n=>u()?c()?{...n,[e]:{activeAccountId:t.activeAccountId===void 0?a.activeAccountId??null:t.activeAccountId,accounts:ng(r,n[e]?.accounts??[],!0)}}:{...n,[e]:{...n[e],accounts:eg(n[e]?.accounts??[],r)}}:n),!r.filter(e=>e.paused!==!0&&tg(e)).some(e=>e.quotaUnavailable===!0)}catch{return u()&&d(t=>u()&&t[e]?{...t,[e]:{...t[e],accounts:rg(t[e].accounts,o.filter(e=>e.paused!==!0))}}: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:rg(t[e].accounts)}}:t)),!1}}))).every(Boolean)},[i,t,V]),U=(0,Z.useCallback)(async(e,n=!1)=>!i.current||!L.current||R.current!==t?!1:(await Promise.all([...new Set(e)].map(async e=>{let r=`key:${e}`,a=(k.current[r]??0)+1;k.current[r]=a;let o=(A.current[r]??0)+1;A.current[r]=o;let s=()=>i.current&&L.current&&R.current===t&&k.current[r]===a,c=()=>s()&&A.current[r]===o,l=`${t}/api/providers/keys?name=${encodeURIComponent(e)}`,u=()=>(c()&&w(t=>c()?{...t,[e]:rg(t[e]??[])}:t),!1);try{let a=await V(l);if(!Array.isArray(a.keys))throw Error(`Invalid key roster`);if(!s())return!1;let o=Qh(a.keys,a.activeId);if(w(t=>c()?{...t,[e]:ng(o,t[e]??[],!1)}:t),!o.some(tg))return!0;let u=async()=>{let a=(j.current[r]??0)+1;j.current[r]=a;let s=()=>i.current&&L.current&&R.current===t&&j.current[r]===a;try{let t=await V(`${l}&quota=1${n?`&refresh=1`:``}`);if(!Array.isArray(t.keys))throw Error(`Invalid key quota roster`);if(!s())return!1;let r=Qh(t.keys,t.activeId);return w(t=>s()?{...t,[e]:c()?ng(r,t[e]??[],!0):eg(t[e]??[],r)}:t),!r.filter(e=>e.disabled!==!0&&tg(e)).some(e=>e.quotaUnavailable===!0)}catch{return s()&&w(t=>s()?{...t,[e]:rg(t[e]??[],o.filter(e=>e.disabled!==!0&&tg(e)))}:t),s()&&!o.some(e=>e.disabled!==!0&&tg(e))}};return n?await u():(u(),!0)}catch{return u()}}))).every(Boolean),[t,i,V]),ee=(0,Z.useCallback)(async(e,n)=>{if(!i.current||!L.current||R.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(N.current.has(a))return!1;let o=(A.current[a]??0)+1;A.current[a]=o;let s=()=>i.current&&L.current&&R.current===t&&!n?.aborted&&A.current[a]===o&&!N.current.has(a);try{if(r===`oauth`){let r=await V(`${t}/api/oauth/accounts?provider=${encodeURIComponent(e)}`,n);if(!Array.isArray(r.accounts)||!s())return!1;let i=Qh(r.accounts,r.activeAccountId);d(t=>s()?{...t,[e]:{activeAccountId:r.activeAccountId===void 0?i.find(e=>e.active)?.id??null:r.activeAccountId,accounts:$h(i,t[e]?.accounts??[])}}:t),p(t=>s()?{...t,[e]:`ready`}:t)}else{let r=await V(`${t}/api/providers/keys?name=${encodeURIComponent(e)}`,n);if(!Array.isArray(r.keys)||!s())return!1;let i=Qh(r.keys,r.activeId);w(t=>s()?{...t,[e]:$h(i,t[e]??[])}:t)}return!0}catch{return!1}}))).every(Boolean)},[i,t,r,V]),W=(e,t)=>{let n=`${t===`oauth`?`oauth`:`key`}:${e}`;return k.current[n]=(k.current[n]??0)+1,A.current[n]=(A.current[n]??0)+1,n},te=async(e,n)=>!i.current||!L.current||R.current!==t?!1:(W(e,`oauth`),d(t=>{let r=t[e];return r?{...t,[e]:{...r,accounts:r.accounts.map(e=>({...e,autoSwitchThreshold:n,effectiveAutoSwitchThreshold:typeof e.autoSwitchThresholdOverride==`number`?e.autoSwitchThresholdOverride:n}))}}:t}),H([e])),G=async(e,r)=>{if(r.active||r.needsReauth||r.paused||I.current.has(e)||F.current.has(e)||N.current.has(`oauth:${e}`))return;let o={provider:e,accountId:r.id};I.current.set(e,o),h(t=>({...t,[e]:o}));let l=W(e,`oauth`),f=Symbol();N.current.set(l,f);let p=()=>i.current&&L.current&&R.current===t&&N.current.get(l)===f,m=Pc(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;W(e,`oauth`);let u=o.activeAccountId===void 0?r.id:o.activeAccountId;d(t=>t[e]?{...t,[e]:{...t[e],activeAccountId:u,accounts:Qh(t[e].accounts,u)}}:t),N.current.delete(l);let f=await ee({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()&&(W(e,`oauth`),N.current.delete(l),ee({provider:e,kind:`oauth`})),I.current.get(e)===o&&(I.current.delete(e),i.current&&h(t=>{let n={...t};return delete n[e],n}))}},ne=async(e,r,o)=>{let s=`oauth:${e}`;if(I.current.has(e)||F.current.has(e)||N.current.has(s))return!1;let c=W(e,`oauth`),l=Symbol();N.current.set(c,l);let f=()=>i.current&&L.current&&R.current===t&&N.current.get(c)===l,p=Pc(u[e]?.accounts??[r],r,n);try{let n=M(2e4);P.current.add(n.controller);let i;try{let a=await fetch(`${t}/api/oauth/accounts/auto-switch`,{method:`PUT`,headers:{"Content-Type":`application/json`},signal:n.signal,body:JSON.stringify({provider:e,accountId:r.id,threshold:o})});if(!a.ok)throw Error(`account threshold write failed`);if(i=await a.json(),n.signal.aborted)throw Error(`account threshold deadline exceeded`)}finally{n.clear(),P.current.delete(n.controller)}let a=e=>typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<=100;if(!i||i.autoSwitchThresholdOverride!==null&&!a(i.autoSwitchThresholdOverride)||!a(i.autoSwitchThreshold)||!a(i.effectiveAutoSwitchThreshold))throw Error(`invalid threshold response`);return f()?(W(e,`oauth`),d(t=>{let n=t[e];return n?{...t,[e]:{...n,accounts:n.accounts.map(e=>e.id===r.id?{...e,autoSwitchThresholdOverride:i.autoSwitchThresholdOverride,autoSwitchThreshold:i.autoSwitchThreshold,effectiveAutoSwitchThreshold:i.effectiveAutoSwitchThreshold}:e)}}:t}),!0):!1}catch{return f()&&a(n(`accountPool.autoSwitchUpdateFailed`,{email:p}),!1),!1}finally{f()&&(W(e,`oauth`),N.current.delete(c),ee({provider:e,kind:`oauth`}))}},K=async(e,r,o)=>{if(I.current.has(e)||F.current.has(e)||N.current.has(`oauth:${e}`))return;let l={provider:e,accountId:r.id};F.current.set(e,l),y(t=>({...t,[e]:{...l,paused:o}}));let f=W(e,`oauth`),p=Symbol();N.current.set(f,p);let m=()=>i.current&&L.current&&R.current===t&&N.current.get(f)===p,h=Pc(u[e]?.accounts??[r],r,n),g;try{let i=await fetch(`${t}/api/oauth/accounts/pause`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e,accountId:r.id,paused:o})});if(!m())return;if(!i.ok){a(n(o?`codexAuth.pauseFailed`:`codexAuth.resumeFailed`,{email:h}),!1);return}if(g=await i.json().catch(()=>({})),!m())return;W(e,`oauth`);let s=g.activeAccountId===void 0?u[e]?.activeAccountId??null:g.activeAccountId;d(t=>{let n=t[e];if(!n)return t;let i=n.accounts.map(e=>e.id===r.id?{...e,paused:o}:e);return{...t,[e]:{activeAccountId:s,accounts:Qh(i,s)}}}),N.current.delete(f)}catch{m()&&a(n(o?`codexAuth.pauseFailed`:`codexAuth.resumeFailed`,{email:h}),!1);return}finally{m()&&(W(e,`oauth`),N.current.delete(f),ee({provider:e,kind:`oauth`})),F.current.get(e)===l&&(F.current.delete(e),i.current&&y(t=>{let n={...t};return delete n[e],n}))}if(i.current&&L.current&&R.current===t){a(n(o?`codexAuth.pauseSucceeded`:`codexAuth.resumeSucceeded`,{email:h}),!0);try{let t=await ee({provider:e,kind:`oauth`});g.activeAccountChanged&&await Promise.all([s(),c(!0)]),t||a(n(`pws.accountsLoadFailed`),!1)}catch{i.current&&L.current&&a(n(`pws.accountsLoadFailed`),!1)}}},re=async(e,r)=>{if(r.active&&!r.disabled||N.current.has(`key:${e}`))return;let o=W(e,`api-key`),s=Symbol();N.current.set(o,s);let l=()=>i.current&&L.current&&R.current===t&&N.current.get(o)===s,u=!1;try{if(r.disabled){let i=await fetch(`${t}/api/providers/keys/pause`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:e,id:r.id,paused:!1})});if(!l())return;if(!i.ok){a(n(`prov.keySwitchFail`),!1);return}u=!0}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(u?n(`prov.keyResumedSwitchFailed`):e.error||n(`prov.keySwitchFail`),!1);return}let o=await i.json().catch(()=>({}));if(!l())return;W(e,`api-key`);let s=o.activeId===void 0?r.id:o.activeId;w(t=>t[e]?{...t,[e]:Qh(t[e],s)}:t),a(n(`prov.keySwitched`,{key:r.label??r.masked}),!0),c(!0)}catch{l()&&a(n(u?`prov.keyResumedSwitchFailed`:`prov.keySwitchFail`),!1)}finally{l()&&(W(e,`api-key`),N.current.delete(o),ee({provider:e,kind:`api-key`}))}},q=async(e,r)=>{await ha({message:n(`prov.keyRemoveConfirm`,{key:r.label??r.masked}),confirmLabel:n(`common.remove`),tone:`danger`})&&(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),U(Object.keys(C)),o(),c(!0))},J=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),E(null),await Promise.all([U(Object.keys(C).includes(e)?Object.keys(C):[...Object.keys(C),e]),o(),c(!0)]),!0}catch{return a(n(`prov.keyAddFail`),!1),!1}},Y=async e=>{await J(e,D)&&O(``)},ie=async(e,r,i,o)=>{let s=await ga({message:n(`prov.aliasPrompt`),initialValue:o??``,maxLength:80,validate:e=>Pl(e,n)});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)r===`oauth`?await H([e]):await U(Object.keys(C).includes(e)?Object.keys(C):[...Object.keys(C),e]),a(n(`prov.aliasSaved`),!0);else{let e=await l.json().catch(()=>({}));a(e.error||n(`prov.aliasSaveFailed`),!1)}},X=async(e,r)=>{let i=Pc(u[e]?.accounts??[r],r,n);if(await ha({message:n(`prov.accountRemoveConfirm`,{email:i}),confirmLabel:n(`common.remove`),tone:`danger`}))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 H([e]),await Promise.all([s(),c(!0)])}catch{a(n(`prov.accountRemoveFail`,{email:i}),!1)}},ae=(0,Z.useMemo)(()=>r?Object.entries(r.providers).filter(([,e])=>e.authMode===`oauth`).map(([e])=>e):[],[r]);(0,Z.useEffect)(()=>{if(ae.length===0)return;let e=`${t}:${ae.join(`,`)}`;z.current!==e&&(z.current=e,Promise.resolve().then(()=>{H(ae)}))},[t,H,ae]);let oe=(0,Z.useMemo)(()=>r?Object.entries(r.providers).filter(([,e])=>e.hasApiKey&&e.authMode!==`oauth`&&e.authMode!==`forward`).map(([e])=>e):[],[r]);return(0,Z.useEffect)(()=>{if(oe.length===0)return;let e=`${t}:${oe.join(`,`)}`;B.current!==e&&(B.current=e,Promise.resolve().then(()=>{U(oe)}))},[t,U,oe]),{accountSets:u,accountLoadStates:f,switchingAccount:g,pausingAccount:b,switchingAccounts:m,pausingAccounts:v,openAccounts:x,keyPools:C,addingKeyFor:T,newKeyValue:D,setAccountSets:d,setAccountLoadStates:p,setSwitchingAccount:_,setOpenAccounts:S,setKeyPools:w,setAddingKeyFor:E,setNewKeyValue:O,fetchAccountSets:H,fetchKeyPools:U,refreshAccountRosters:ee,switchAccount:G,pauseAccount:K,setAccountPoolThreshold:te,setAccountThreshold:ne,switchApiKey:re,removeApiKey:q,addApiKeyValue:J,addApiKey:Y,editCredentialAlias:ie,removeAccount:X,oauthCardProviders:ae,keyCardProviders:oe,activeAccountNeedsReauth:(0,Z.useMemo)(()=>ig(u,l),[u,l])}}var og=new Set([`hasApiKey`,`hasHeaders`,`xaiResponsesOptInState`,`initialModelSelection`]);function sg(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))og.has(e)||(n[e]=structuredClone(r));return[e,n]}))}}function cg(e){let{apiBase:t,config:n,notify:r,fetchConfig:i,fetchProviderQuotas:a,onSaved:o,t:s}=e,[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(``),[f,p]=(0,Z.useState)(!1),[m,h]=(0,Z.useState)(``),[g,_]=(0,Z.useState)(!1),[v,y]=(0,Z.useState)(!1),b=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>{n&&!b.current&&d(JSON.stringify(sg(n),null,2))},[n]);let x=(0,Z.useCallback)(async()=>{_(!0);let e;try{e=JSON.parse(u)}catch{return r(s(`prov.invalidJson`),!1),_(!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),b.current=!1,y(!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{_(!1)}},[t,u,i,a,m,r,o,s]),S=(0,Z.useCallback)(()=>{let e=n?JSON.stringify(sg(n),null,2):u;h(e),d(e),y(!1),p(!0),b.current=!0},[n,u]),C=(0,Z.useCallback)(()=>{y(!1),p(!1),b.current=!1;let e=n?JSON.stringify(sg(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:v,jsonEditorOpenRef:b,saveConfig:x,openJsonEditor:S,discardJsonEditor:C,requestCloseJsonEditor:(0,Z.useCallback)(()=>{f&&u!==m?y(!0):C()},[C,u,m,f]),restoreJsonEditor:(0,Z.useCallback)(()=>{d(m)},[m]),jsonIsDirty:f&&u!==m,setJsonLeaveOpen:y}}var lg=186e4;function ug(e,t,n){return e?Math.max(n,Math.ceil(lg/t)):n}var dg={xai:`xAI (Grok)`,anthropic:`Anthropic (Claude)`,anthropic2:`Anthropic · Pool 2`,kimi:`Kimi (Moonshot)`,"meta-muse":`Meta Muse Code (CLI)`,"google-antigravity":`Google Antigravity`,"github-copilot":`GitHub Copilot`,cursor:`Cursor`,zed:`Zed Hosted AI`,devin:`Devin`,"dsh-account":`DeepSeek Account (DSH)`,"workbuddy-ai":`WorkBuddy AI`},fg=e=>dg[e]??e;function pg({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,Z.useRef)(null);g.current===null&&(g.current=new Map);let _=(0,Z.useRef)(new Map),v=(0,Z.useCallback)(e=>{let t=(g.current.get(e)??0)+1;return g.current.set(e,t),t},[]),y=(0,Z.useCallback)(t=>Ap(e,t),[e]),b=(0,Z.useCallback)(async e=>{let t=Object.keys(r);await f(new Set(t).has(e)?t:[...t,e])},[r,f]),x=(0,Z.useCallback)(()=>{u(),p(!0),m()},[u,p,m]),S=(0,Z.useCallback)(async(e,r)=>{if(n.current){r===`added`&&h?.(e);try{await b(e)}catch{}n.current&&(r===`added`?l(t(`prov.loginOk`,{provider:fg(e),cmd:`ocx sync`}),!0):l(r===`ended`?t(`kiroLogin.ended`):t(`prov.loginError`,{provider:fg(e),error:t(`kiroLogin.failed`)}),!1),x())}},[n,h,b,l,t,x]);return(0,Z.useEffect)(()=>{let e=e=>{let t=[..._.current];_.current.clear();for(let[n,r]of t)g.current.get(n)===r&&v(n),e&&(a(e=>e===n?null:e),s(e=>e?.provider===n?null:e)),y(n)},t=()=>e(!0);return window.addEventListener(`pagehide`,t),()=>{window.removeEventListener(`pagehide`,t),e(!1)}},[v,y,a,s]),{cancelLoginOAuth:(0,Z.useCallback)(async e=>{let r=v(e);_.current.delete(e),await y(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:fg(e)}),!1))},[n,v,y,l,a,s,t]),loginOAuth:async(u,d=!1,f)=>{let p=v(u);_.current.set(u,p);let m=f?.trim()||void 0;a(u),o(``),s(null);try{let a=await jp(e,u,()=>{if(n.current&&g.current.get(u)===p)return fetch(`${e}/api/oauth/login`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:u,...Kl(),...d||m?{addAccount:!0}:{},...m?{accountId:m,reauth:!0}:{}})})});if(!a||g.current.get(u)!==p||!n.current)return;if(!a.ok){let e=await a.json().catch(()=>({}));if(!n.current||g.current.get(u)!==p)return;l(e.error||t(`prov.loginFailStart`,{provider:fg(u)}),!1);return}let o=await a.json();if(!n.current||g.current.get(u)!==p)return;let f=Jl(o.browserLaunch);(o.url||o.instructions||o.deviceCode)&&s({provider:u,url:o.url,instructions:o.instructions,deviceCode:o.deviceCode,browserLaunch:f});let _=r[u]?.accounts.length??0,v=!1,S=!!o.deviceCode;for(let r=0;r<ug(S,2e3,150)&&n.current&&g.current.get(u)===p;r++){if(await new Promise(e=>setTimeout(e,2e3)),g.current.get(u)!==p||!n.current)return;let r=await fetch(`${e}/api/oauth/status?provider=${u}`).catch(()=>null),a=r?await yn(r)??null:null;if(!n.current||g.current.get(u)!==p)return;if(!a)continue;if(a.error){c(e=>({...e,[u]:a})),l(/cancel/i.test(a.error)?t(`prov.loginCancelled`,{provider:fg(u)}):t(`prov.loginError`,{provider:fg(u),error:a.error}),!1),s(null),v=!0;break}let o=a.accounts?.length??0;if(d||m?o>_||a.done===!0:a.loggedIn||a.done===!0){c(e=>({...e,[u]:a}));let e=m?a.accounts?.find(e=>e.id===m):a.accounts?.find(e=>e.active)??a.accounts?.find(e=>e.id===a.activeAccountId);if(m&&!e){l(t(`prov.loginError`,{provider:fg(u),error:t(`prov.reauthAccountMissing`)}),!1),s(null),v=!0;break}if(e?.needsReauth){l(t(`prov.loginError`,{provider:fg(u),error:t(`prov.reauthIdentityMismatch`)}),!1),s(null),v=!0;break}if(a.accounts){let e=a.accounts.find(e=>e.active)?.id??null;i(t=>t[u]?t:{...t,[u]:{activeAccountId:a.activeAccountId??e,accounts:a.accounts}})}if(s(null),h?.(u),await b(u),!n.current||g.current.get(u)!==p)return;d&&!m&&o<=_?l(t(`prov.loginSameAccount`,{provider:fg(u)}),!1):l(t(`prov.loginOk`,{provider:fg(u),cmd:`ocx sync`}),!0),x(),v=!0;break}a.hint&&(a.hint.deviceCode&&(S=!0),s({provider:u,url:a.hint.url,instructions:a.hint.instructions,deviceCode:a.hint.deviceCode,browserLaunch:f}))}if(!v&&g.current.get(u)===p&&n.current){if(await y(u),!n.current||g.current.get(u)!==p)return;l(t(`prov.loginTimeout`,{provider:fg(u)}),!1),s(null)}}catch{if(g.current.get(u)===p){if(await y(u),!n.current||g.current.get(u)!==p)return;l(t(`prov.loginRequestFail`,{provider:fg(u)}),!1)}}finally{_.current.get(u)===p&&_.current.delete(u),n.current&&g.current.get(u)===p&&a(null)}},logoutOAuth:async n=>{v(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:fg(n)}),!1);return}await Promise.all([f([n]),d(),u(),p(!0)]),m(),l(t(`prov.logoutOk`,{provider:fg(n)}),!0)}catch{l(t(`prov.logoutFail`,{provider:fg(n)}),!1)}},onNativeLoginSettled:S}}async function mg(e,t){try{let t=await e.json();if(typeof t.error==`string`&&t.error.trim())return t.error.trim()}catch{}return t}function hg(e){let t=e.dependentShadowIntercept;return!t||typeof t.model!=`string`||t.enabled!==!0?null:{model:t.model,enabled:!0}}function gg(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 _g({apiBase:e,t,removeBusyRef:n,workspaceSelected:r,setWorkspaceSelected:i,setRemoveConfirmName:a,notify:o,fetchConfig:s,fetchOauth:c,fetchProviderQuotas:l,refreshCodexAccount:u}){let d=(0,Z.useCallback)(async e=>{a(e)},[a]),f=(0,Z.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,u=hg(e);u?o(t(`prov.removedShadowTarget`,{name:d,model:u.model}),!1,`warn`):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(gg(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,Z.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 mg(i,t(r?`prov.disableFail`:`prov.enableFail`,{name:n})),!1);return}let a=hg(await i.json().catch(()=>({})));a?o(t(`prov.disabledShadowTarget`,{name:n,model:a.model}),!1,`warn`):o(t(r?`prov.disabled`:`prov.enabled`,{name:n}),!0),s(),c(),l(!0)},[e,s,c,l,o,t]),m=(0,Z.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 mg(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,Z.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(gg(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 vg({apiBase:e,t,setConfig:n,setOauthProviders:r,setOauthStatus:i,notify:a,invalidateProviderQuotas:o,configCacheKey:s}){let c=(0,Z.useRef)(0);return(0,Z.useEffect)(()=>()=>{c.current+=1},[e]),{fetchConfig:(0,Z.useCallback)(async()=>{let r=++c.current;try{let t=await vn(await fetch(`${e}/api/config`));if(r!==c.current)return`superseded`;if(!t)throw Error(`config response missing`);return n(t??null),s&&t&&co(s,t),`applied`}catch{return r===c.current?(a(t(`prov.loadConfigFail`),!1),`failed`):`superseded`}},[e,s,a,n,t]),fetchOauth:(0,Z.useCallback)(async()=>{try{let t=(await vn(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 yn(n)??{loggedIn:!1}:{loggedIn:!1}]}));i(Object.fromEntries(n))}catch{}},[e,r,i]),fetchProviderQuotas:(0,Z.useCallback)(async(e=!1)=>{o(e)},[o])}}function yg({providerId:e,providerLabel:t,onCancel:r,onContinue:i}){let a=n(),o=(0,Z.useId)(),s=(0,Z.useId)(),c=(0,Z.useId)(),l=(0,Z.useRef)(null),u=(0,Z.useRef)(!1),[d,f]=(0,Z.useState)(!1),[p,m]=(0,Z.useState)(!1),h=Jh(e);(0,Z.useEffect)(()=>{let e=l.current;e&&!e.open&&e.showModal()},[]);let g=(0,Z.useCallback)(e=>{e.preventDefault(),r()},[r]);if(!h)return null;let _=Zh(e,h);return(0,Q.jsxs)(`dialog`,{ref:l,"aria-labelledby":o,"aria-describedby":_.conditions?`${s} ${c}`:s,className:`modal-overlay`,onCancel:g,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":a(`common.close`),tabIndex:-1,onClick:r}),(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),style:{maxWidth:460},children:[(0,Q.jsx)(`h3`,{id:o,children:a(_.title,{provider:t})}),(0,Q.jsxs)(`div`,{id:s,className:`notice-warn`,style:{marginTop:12,display:`flex`,gap:8,alignItems:`flex-start`},children:[(0,Q.jsx)(Ne,{width:16,height:16,style:{flexShrink:0,marginTop:2},"aria-hidden":`true`}),(0,Q.jsx)(`p`,{className:`modal-desc`,style:{margin:0},children:a(_.body,{provider:t})})]}),_.conditions&&(0,Q.jsx)(`p`,{id:c,className:`modal-desc`,style:{marginTop:12},children:a(_.conditions)}),_.saferPath&&(0,Q.jsx)(`p`,{className:`muted text-label`,style:{marginTop:12},children:a(_.saferPath)}),(0,Q.jsxs)(`label`,{className:`oauth-tos-ack`,style:{display:`flex`,gap:8,alignItems:`flex-start`,marginTop:14},children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:d,onChange:e=>f(e.target.checked),style:{marginTop:3},"aria-required":`true`}),(0,Q.jsx)(`span`,{className:`text-label`,children:a(_.acknowledge)})]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:r,children:a(`common.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!d||p,onClick:()=>{d&&!u.current&&(u.current=!0,m(!0),i())},children:a(_.continue)})]})]})]})}function bg(e,t,n){return!n||e.kind!==`oauth`||t!==e.id?!1:n.provider===e.id}function xg({row:e,status:t,busyProvider:r,loginHint:i,paste:a,onLogin:o,onCancelLogin:s,onLogout:c,onManage:l}){let u=n(),d=r===e.id,f=!!t?.loggedIn,p=f?t?.email??e.statusLabel??u(`modal.accountLoggedIn`):t?.error??e.statusLabel??u(`modal.accountLoggedOut`),m=bg(e,r,i);return(0,Q.jsxs)(`div`,{className:`list-row provider-catalog-account-row${m?` provider-catalog-account-row--waiting`:``}`,children:[(0,Q.jsxs)(`div`,{className:`provider-catalog-account-row-head`,children:[(0,Q.jsx)(_e,{name:e.id,cls:`provider-icon provider-icon-sm`}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`title`,children:e.label}),(0,Q.jsx)(`div`,{className:`sub`,children:p})]}),(0,Q.jsx)(`div`,{className:`provider-catalog-badges`,children:e.kind===`key`?null:e.kind===`codex`?(0,Q.jsxs)(Q.Fragment,{children:[f&&(0,Q.jsx)(`a`,{className:`btn btn-ghost`,href:e.href??`#codex-set`,children:u(`modal.accountManage`)}),o&&(0,Q.jsx)(`button`,{type:`button`,className:f?`btn btn-ghost`:`btn btn-primary`,disabled:d,onClick:()=>{d||o(e.id)},children:u(d?`codexAuth.enablingOpenai`:f?`modal.accountAdd`:`modal.accountLogin`)})]}):f?(0,Q.jsxs)(Q.Fragment,{children:[l&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>l(e.id),children:u(`modal.accountManage`)}),o&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:d,onClick:()=>{d||o(e.id,!0)},children:u(d?`prov.waitingBrowser`:`modal.accountAdd`)}),d&&s&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>s(e.id),children:u(`common.cancel`)}),c&&!d&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>c(e.id),children:u(`modal.accountLogout`)})]}):d?s&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>s(e.id),children:u(`common.cancel`)}):o&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>o(e.id),children:u(`modal.accountLogin`)})})]}),m&&i&&(0,Q.jsx)(Hl,{hint:{url:i.url,deviceCode:i.deviceCode,instructions:i.instructions,browserLaunch:i.browserLaunch},...a?{paste:{value:a.value,busy:a.busy,message:a.message,ok:a.ok,onChange:a.onChange,onSubmit:()=>a.onSubmit(e.id)}}:{}})]})}var Sg=[`accounts`,`free`,`local`,`paid`],Cg={accounts:`modal.tab.accounts`,free:`modal.tab.free`,local:`modal.tab.local`,paid:`modal.tab.paid`},wg={},Tg=[],Eg={};function Dg({presets:e,usageRank:t=wg,presetsLoading:r=!1,initialTier:i=`free`,query:a,onQueryChange:o,onSelectPreset:s,onSelectCustom:c,onShowNote:l,accountRows:u=Tg,accountStatus:d=Eg,busyProvider:f=null,loginHint:p=null,paste:m,onLogin:h,onCancelLogin:g,onLogout:_,onManage:v}){let y=n(),[b,x]=(0,Z.useState)(i),S=(0,Z.useId)(),C=e=>`${S}-${e}`,w=(0,Z.useRef)(null),T=a.trim().length>0;(0,Z.useEffect)(()=>{w.current&&(w.current.scrollTop=0)},[b,T]);let E=(0,Z.useMemo)(()=>e.filter(e=>e.id!==`custom`),[e]),D=(0,Z.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,Z.useMemo)(()=>Vc(Yc(D)),[D]),k=O[b],A=(0,Z.useMemo)(()=>T?Kc(u,a,f):u,[u,a,T,f]),j=(0,Z.useMemo)(()=>{let e=Sg.filter(e=>e!==`accounts`);return T?e.map(e=>({tier:e,rows:Gc(qc(O[e].filter(e=>Wc(e,a)),A),a)})):b===`accounts`?[]:[{tier:b,rows:k}]},[T,b,k,O,a,A]),M=(0,Z.useMemo)(()=>({...Object.fromEntries(j.map(e=>[e.tier,e.rows.length])),accounts:A.length}),[j,A]),N=Sg.reduce((e,t)=>e+(M[t]??0),0),P=Sg.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,f||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,Q.jsxs)(`h4`,{id:C(e),"data-catalog-group":e,className:`provider-catalog-group-head`,tabIndex:-1,children:[(0,Q.jsx)(`span`,{children:y(Cg[e])}),(0,Q.jsx)(`span`,{className:`provider-catalog-group-count`,children:t})]}),z=e=>{let t=Ze(e),n=t?(0,Q.jsx)(`span`,{className:`badge badge-amber`,children:y(`modal.badge.subscriptionCli`)}):e.codexAccountMode===`direct`?(0,Q.jsx)(`span`,{className:`badge badge-green`,children:y(`modal.badge.direct`)}):e.codexAccountMode===`pool`?(0,Q.jsx)(`span`,{className:`badge badge-accent`,children:y(`modal.badge.pool`)}):e.auth===`oauth`?(0,Q.jsx)(`span`,{className:`badge badge-accent`,children:y(`modal.badge.oauth`)}):e.auth===`forward`?(0,Q.jsx)(`span`,{className:`badge badge-green`,children:y(`modal.badge.codexLogin`)}):e.auth===`local`?(0,Q.jsx)(`span`,{className:`badge badge-amber`,children:y(`modal.badge.local`)}):e.keyOptional?null:(0,Q.jsx)(`span`,{className:`badge badge-muted`,children:y(`modal.badge.apiKey`)}),r=(e.freeTier||e.keyOptional)&&e.auth===`key`&&!t?(0,Q.jsx)(`span`,{className:`badge badge-green`,children:y(`modal.badge.free`)}):null,i=e.sponsor?(0,Q.jsx)(`span`,{className:`badge badge-accent provider-catalog-sponsor`,title:e.sponsorUrl,children:y(`modal.badge.sponsor`)}):null;return(0,Q.jsxs)(Q.Fragment,{children:[i,r,n]})};return(0,Q.jsxs)(`div`,{className:`provider-catalog`,children:[(0,Q.jsx)(`input`,{className:`input provider-catalog-search`,type:`search`,value:a,onChange:e=>o(e.target.value),onKeyDown:L,placeholder:y(`modal.search`),"aria-label":y(`modal.search`)}),T?(0,Q.jsx)(`div`,{className:`provider-catalog-tabs provider-catalog-tabs--chips`,children:Sg.map(e=>(0,Q.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(Cg[e]),(0,Q.jsx)(`span`,{className:`provider-catalog-chip-count`,children:M[e]??0})]},e))}):(0,Q.jsx)(`div`,{className:`provider-catalog-tabs`,role:`tablist`,children:Sg.map(e=>(0,Q.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(Cg[e])},e))}),!T&&b===`accounts`&&(0,Q.jsx)(`div`,{className:`provider-catalog-accounts-hint muted text-label`,children:y(`modal.accountsHint`)}),(0,Q.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(Cg[e])).join(`, `)}):``}),(0,Q.jsxs)(`div`,{className:`provider-catalog-rows`,id:S,ref:w,children:[r&&F===0&&(0,Q.jsx)(`div`,{className:`muted text-control provider-catalog-empty`,children:y(`modal.catalogLoading`)}),(T||b===`accounts`)&&A.length>0&&(0,Q.jsxs)(Z.Fragment,{children:[T&&R(`accounts`,A.length),A.map(e=>(0,Q.jsx)(xg,{row:e,status:d[e.id],busyProvider:f,loginHint:p,...m?{paste:m}:{},...h?{onLogin:h}:{},...g?{onCancelLogin:g}:{},..._?{onLogout:_}:{},...v?{onManage:v}:{}},e.id))]},`accounts`),j.map(e=>e.rows.length===0?null:(0,Q.jsxs)(Z.Fragment,{children:[T&&R(e.tier,e.rows.length),e.rows.map(e=>(0,Q.jsxs)(`div`,{className:`provider-catalog-row-wrap`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`list-row`,onClick:()=>s(e),children:[(0,Q.jsx)(_e,{name:e.id,adapter:e.adapter,cls:`provider-icon provider-icon-sm`}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`title`,children:e.label}),(0,Q.jsxs)(`div`,{className:`sub`,children:[(0,Q.jsx)(`code`,{className:`chip`,children:e.adapter}),e.note?` · ${e.note}`:``]})]}),(0,Q.jsx)(`div`,{className:`provider-catalog-badges`,children:z(e)})]}),l&&Hc(e.note)&&(0,Q.jsx)(`button`,{type:`button`,className:`link-btn provider-catalog-note-more`,onClick:()=>l(e),children:y(`modal.noteMore`)})]},e.id))]},e.tier)),!r&&F===0&&(0,Q.jsx)(`div`,{className:`muted text-control provider-catalog-empty`,children:y(`modal.noMatch`)})]}),(0,Q.jsxs)(`div`,{className:`provider-catalog-footer`,children:[(0,Q.jsx)(`div`,{style:{flex:1}}),!T&&b!==`accounts`&&(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:c,children:y(`modal.notListed`)})]})]})}function Og({providerId:e,label:t,adapter:r,note:i,onClose:a}){let o=n(),s=(0,Z.useId)(),c=(0,Z.useId)(),l=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{let e=l.current,t=document.activeElement;return e&&!e.open&&e.showModal(),()=>{e?.open&&e.close(),t?.isConnected&&t.focus({preventScroll:!0})}},[]);let u=(0,Z.useCallback)(e=>{e.preventDefault(),a()},[a]);return(0,Q.jsxs)(`dialog`,{ref:l,"aria-labelledby":s,"aria-describedby":c,className:`modal-overlay`,onCancel:u,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":o(`common.close`),tabIndex:-1,onClick:a}),(0,Q.jsxs)(`div`,{className:`modal-card provider-note-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsxs)(`h3`,{id:s,className:`provider-note-title`,children:[(0,Q.jsx)(_e,{name:e,adapter:r,cls:`provider-icon provider-icon-sm`}),t]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,"aria-label":o(`common.close`),onClick:a,children:(0,Q.jsx)(xe,{})})]}),(0,Q.jsxs)(`div`,{id:c,className:`provider-note-body`,children:[(0,Q.jsx)(`code`,{className:`chip`,children:r}),(0,Q.jsx)(`p`,{className:`modal-desc provider-note-text`,children:i})]}),(0,Q.jsx)(`div`,{className:`modal-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:a,children:o(`common.close`)})})]})]})}function kg({preset:e,oauthSupported:t,oauthBusy:r,oauthMsg:i,oauthMsgTone:a,oauthUrl:o,oauthDeviceCode:s,oauthInstructions:c,oauthBrowserLaunch:l,manualCode:u,manualCodeBusy:d,manualCodeMsg:f,manualCodeOk:p,onRequestLogin:m,onCancelLogin:h,onUseApiKeyInstead:g,onManualCodeChange:_,onSubmitManualCode:v,onBack:y}){let b=n();return(0,Q.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:14},children:[(0,Q.jsx)(`div`,{className:`muted text-control`,children:e.note??b(`modal.oauthDefaultNote`)}),t.includes(e.oauthProvider??``)?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>m(e.oauthProvider),disabled:r,style:{width:`100%`,padding:`12px 16px`},children:[(0,Q.jsx)(ct,{}),r?b(`modal.waitingBrowser`):b(`modal.logInWith`,{label:e.label})]}),!r&&(0,Q.jsx)(wf,{})]}):(0,Q.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:b(`modal.oauthComingSoon`,{label:e.label})}),i&&(0,Q.jsx)(`div`,{className:`text-label`,style:{color:a===`warn`?`var(--amber)`:`var(--accent-hover)`},children:i}),r&&(0,Q.jsx)(Hl,{hint:{url:o,deviceCode:s,instructions:c,browserLaunch:l},paste:{value:u,busy:d,disabled:!e.oauthProvider,message:f,ok:p,onChange:_,onSubmit:()=>{e.oauthProvider&&v(e.oauthProvider)}}}),(0,Q.jsxs)(`div`,{style:{display:`flex`,gap:8,alignItems:`center`,marginTop:2},children:[(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:g,children:b(`modal.useApiKeyInstead`)}),(0,Q.jsx)(`div`,{style:{flex:1}}),r&&e.oauthProvider&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>h(e.oauthProvider),children:b(`common.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:y,children:b(`modal.back`)})]})]})}function Ag({label:e,children:t}){return(0,Q.jsxs)(`label`,{style:{display:`block`},children:[(0,Q.jsx)(`span`,{className:`field-label`,children:e}),t]})}var jg=[`openai-responses`,`openai-chat`,`anthropic`,`google`,`azure-openai`,`cursor`];function Mg(e){return e&&!jg.includes(e)?[e,...jg]:jg}function Ng({preset:e,form:t,endpointChoice:r,error:i,saving:a,dup:o,isCustom:s,isLocal:c,isReservedForward:l,presetDescription:u,onFormChange:d,onEndpointChoiceChange:f,onSubmit:p,onUseOauthLogin:m,onBack:h}){let g=n(),_=Ze(t);return(0,Q.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:10},children:[!l&&!s&&!c&&!e.keyOptional&&e.note&&(0,Q.jsxs)(`details`,{className:`setup-guide`,children:[(0,Q.jsx)(`summary`,{children:g(`modal.setupGuide`)}),(0,Q.jsxs)(`ol`,{className:`text-label leading-relaxed`,style:{margin:`8px 0 0`,paddingLeft:18,color:`var(--muted)`},children:[(0,Q.jsxs)(`li`,{children:[g(`modal.setupStep1Prefix`),` `,(0,Q.jsx)(`a`,{href:e.dashboardUrl,target:`_blank`,rel:`noreferrer`,children:g(`modal.setupDashboardLink`,{label:e.label})}),` `,g(`modal.setupStep1Suffix`)]}),(0,Q.jsx)(`li`,{children:g(`modal.setupStep2`)}),(0,Q.jsx)(`li`,{children:g(`modal.setupStep3`)})]}),e.note&&(0,Q.jsx)(`div`,{className:`text-label`,style:{color:`var(--muted)`,marginTop:6,fontStyle:`italic`},children:e.note}),/\{[^}]*\}/.test(t.baseUrl)&&(0,Q.jsx)(`div`,{className:`text-label`,style:{color:`var(--amber)`,marginTop:6},children:g(`modal.baseUrlPlaceholderHint`)})]}),(0,Q.jsx)(Ag,{label:g(`modal.providerName`),children:(0,Q.jsx)(`input`,{className:`input`,value:t.name,readOnly:l,onChange:e=>d({...t,name:e.target.value}),placeholder:g(`modal.namePlaceholder`)})}),o&&(0,Q.jsx)(`div`,{className:`text-label`,style:{color:`var(--amber)`},children:g(`modal.duplicateWarn`,{name:t.name.trim()})}),!l&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Ag,{label:g(`modal.adapter`),children:(0,Q.jsx)(`select`,{className:`input`,value:t.adapter,onChange:e=>d({...t,adapter:e.target.value}),children:Mg(t.adapter).map(e=>(0,Q.jsx)(`option`,{value:e,children:e},e))})}),e.baseUrlChoices&&e.baseUrlChoices.length>0?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Ag,{label:g(`modal.endpoint`),children:(0,Q.jsx)(`select`,{className:`input`,value:r,onChange:n=>{let r=n.target.value;f(r),d({...t,baseUrl:lm(e.baseUrlChoices,r,t.baseUrl)})},children:e.baseUrlChoices.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.id===`token-plan`?g(`modal.endpoint.tokenPlan`):e.id===`payg`?g(`modal.endpoint.payAsYouGo`):e.id===`custom`?g(`modal.endpoint.custom`):e.label},e.id))})}),r===`custom`&&(0,Q.jsx)(Ag,{label:g(`modal.baseUrl`),children:(0,Q.jsx)(`input`,{className:`input`,value:t.baseUrl,onChange:e=>d({...t,baseUrl:e.target.value}),placeholder:g(`modal.baseUrlPlaceholder`)})})]}):(0,Q.jsx)(Ag,{label:g(`modal.baseUrl`),children:(0,Q.jsx)(`input`,{className:`input`,value:t.baseUrl,onChange:e=>d({...t,baseUrl:e.target.value}),placeholder:g(`modal.baseUrlPlaceholder`)})}),!l&&(0,Q.jsxs)(`label`,{className:`modal-field`,style:{flexDirection:`row`,alignItems:`center`,gap:8},children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:t?.allowPrivateNetwork??!1,onChange:e=>d({...t,allowPrivateNetwork:e.target.checked})}),(0,Q.jsx)(`span`,{className:`muted text-control`,children:g(`modal.allowPrivateNetwork`)})]}),!l&&(t?.allowPrivateNetwork??!1)&&(0,Q.jsx)(`p`,{className:`muted text-hint`,children:g(`modal.allowPrivateNetworkHint`)})]}),s&&fm(t)&&(0,Q.jsx)(wm,{checked:t.preserveResponsesReasoningContent===!0,onChange:e=>d({...t,preserveResponsesReasoningContent:e})}),t.authMode===`forward`?(0,Q.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:u(e)}):t.authMode===`local`?(0,Q.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:g(`modal.localHint`)}):_?(0,Q.jsxs)(`div`,{role:`note`,"data-subscription-cli-warning":``,className:`text-label leading-relaxed`,style:{color:`var(--amber)`,background:`var(--amber-soft)`,border:`1px solid var(--amber)`,borderRadius:`var(--radius-sm)`,padding:`10px 12px`},children:[(0,Q.jsx)(`strong`,{children:g(`modal.subscriptionCliTitle`)}),(0,Q.jsx)(`div`,{style:{marginTop:4},children:(0,Q.jsx)(O,{k:`modal.subscriptionCliWarning`,cmd:`claude -p`,vars:{apiProvider:J}})})]}):e.keyOptional?(0,Q.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,Q.jsx)(`strong`,{children:g(`modal.freeTierTitle`)}),` — `,e.note??g(`modal.freeTierDefault`)]}):(0,Q.jsxs)(Q.Fragment,{children:[e.dashboardUrl&&(0,Q.jsxs)(`a`,{className:`text-label`,href:e.dashboardUrl,target:`_blank`,rel:`noreferrer`,style:{display:`inline-flex`,alignItems:`center`,gap:5},children:[(0,Q.jsx)(it,{style:{width:14,height:14}}),g(`modal.getApiKey`,{label:e.label}),(0,Q.jsx)(We,{style:{width:13,height:13}})]}),(0,Q.jsx)(Ag,{label:g(`modal.apiKey`),children:(0,Q.jsx)(`input`,{className:`input`,type:`password`,value:t.apiKey,onChange:e=>d({...t,apiKey:e.target.value}),placeholder:g(`modal.apiKeyPlaceholder`)})}),t.adapter===`anthropic`&&t.authMode===`key`&&(0,Q.jsx)(Ag,{label:g(`modal.apiKeyTransport`),children:(0,Q.jsxs)(`select`,{className:`input`,value:t.apiKeyTransport??`x-api-key`,onChange:e=>d({...t,apiKeyTransport:e.target.value===`bearer`?`bearer`:void 0}),children:[(0,Q.jsx)(`option`,{value:`x-api-key`,children:g(`modal.apiKeyTransportNative`)}),(0,Q.jsx)(`option`,{value:`bearer`,children:g(`modal.apiKeyTransportBearer`)})]})})]}),!l&&(0,Q.jsx)(Ag,{label:g(`modal.defaultModel`),children:(0,Q.jsx)(`input`,{className:`input`,value:t.defaultModel,onChange:e=>d({...t,defaultModel:e.target.value}),placeholder:g(`modal.defaultModelPlaceholder`)})}),i&&(0,Q.jsx)(`div`,{className:`text-control`,role:`alert`,style:{color:`var(--red)`},children:i}),(0,Q.jsxs)(`div`,{style:{display:`flex`,gap:8,marginTop:4,alignItems:`center`},children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:p,disabled:a,children:g(a?`modal.adding`:`modal.add`)}),e.auth===`oauth`&&(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:m,children:g(`modal.useOauthLogin`)}),(0,Q.jsx)(`div`,{style:{flex:1}}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:h,children:g(`modal.back`)})]})]})}var Pg=2e3;function Fg({apiBase:e,t,aliveRef:n,onAdded:r}){let i=(0,Z.useRef)(new Map),a=(0,Z.useRef)(new Map),o=(0,Z.useCallback)(e=>{let t=(i.current.get(e)??0)+1;return i.current.set(e,t),t},[]),s=(0,Z.useCallback)(t=>Ap(e,t),[e]);return(0,Z.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,Z.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,Z.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 jp(e,c,()=>{if(n.current&&v())return fetch(`${e}/api/oauth/login`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:c,...Kl()})})});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,Jl(o.browserLaunch)),o.url||o.deviceCode?d(t(`modal.waitingLogin`)):d(o.instructions||t(`modal.loggingIn`));let l=!!o.deviceCode;for(let i=0;i<ug(l,Pg,100);i++){if(await new Promise(e=>setTimeout(e,Pg)),!n.current||!v())return;let i=await fetch(`${e}/api/oauth/status?provider=${c}`).catch(()=>null),o=i?await yn(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),d(``),r(c);return}let s=o?.hint;s&&(s.deviceCode&&(l=!0),p(s.url??``,c,s.deviceCode,s.instructions),d(s.url||s.deviceCode?t(`modal.waitingLogin`):s.instructions||t(`modal.loggingIn`)))}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),p(``,c))}},[n,e,o,s,r,t]),submitManualCode:(0,Z.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 Ig(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 Lg(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:``,oauthBrowserLaunch:void 0,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:``,oauthBrowserLaunch:void 0,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,oauthBrowserLaunch:t.url?t.browserLaunch??(e.oauthUrlProvider===t.providerId?e.oauthBrowserLaunch:void 0):void 0}: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:``,oauthBrowserLaunch:void 0,oauthUrlProvider:null};case`use-api-key-instead`:return{...e,form:t.form,oauthMsg:``,oauthMsgTone:`ok`,oauthUrl:``,oauthDeviceCode:``,oauthInstructions:``,oauthBrowserLaunch:void 0,oauthUrlProvider:null,oauthBusy:!1,manualCode:``,manualCodeMsg:``};default:return e}}function Rg({apiBase:e,existingNames:t,onClose:r,onAdded:i,initialTier:a,initialCustom:o=!1,accountRows:s,accountStatus:c,accountBusy:l,accountLoginHint:u=null,onAccountLogin:d,onAccountCancelLogin:f,onAccountLogout:p,onAccountManage:m,onOpen:h}){let g=n(),_=(0,Z.useMemo)(()=>[{id:`custom`,label:g(`modal.customProvider`),adapter:`openai-chat`,baseUrl:``,auth:`key`}],[g]),[v,y]=(0,Z.useReducer)(Lg,o,e=>Ig(e,g(`modal.customProvider`))),b=(0,Z.useRef)(!0),x=(0,Z.useRef)(null),S=(0,Z.useRef)(null),[C,w]=(0,Z.useState)(null),[T,E]=(0,Z.useState)(``),D=Wt(`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=Wt(`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=Wt(xr(e),[e],async t=>await br(await fetch(`${e}/api/usage?range=30d`,{signal:t})),{deadlineMs:6e4}),A=D.data??[],j=O.data??_,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:ee,oauthBrowserLaunch:W,manualCode:te,manualCodeBusy:G,manualCodeMsg:ne,manualCodeOk:K,endpointChoice:re,oauthTosPending:q}=v;(0,Z.useEffect)(()=>{b.current=!0,x.current=document.activeElement,h?.();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,Z.useEffect)(()=>{let e=e=>{let t=!q&&!C;e.key===`Escape`&&t&&(T?E(``):r())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[r,q,C,T]);let J=e=>{let t=vm(e);return t?g(t):e.note},Y=e=>{let t=um(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?lm(e.baseUrlChoices,t,e.baseUrl):e.baseUrl,responsesPath:e.responsesPath,authMode:e.auth,apiKey:``,apiKeyTransport:void 0,defaultModel:e.defaultModel??``,allowPrivateNetwork:!1}})},ie=async()=>{if(!F)return;let t=P?_m(P):!1,n=P?.baseUrlChoices?.length?dm(P.baseUrlChoices,re,F.baseUrl):F.baseUrl.trim();if(!t&&!F.name.trim()){y({type:`set-error`,error:g(`modal.nameRequired`)});return}if(!t&&!n){y({type:`set-error`,error:g(`modal.baseUrlRequired`)});return}if(!t&&/\{[^}]*\}/.test(n)){y({type:`set-error`,error:g(`modal.baseUrlPlaceholderError`)});return}let r={...F,baseUrl:n},a;try{a=bm(P??{id:`custom`},r)}catch{y({type:`set-error`,error:g(`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||g(`modal.failedStatus`,{status:t.status})});return}i(a.name)}catch{y({type:`set-error`,error:g(`modal.networkError`)})}finally{y({type:`set-saving`,saving:!1})}},{cancelLoginOAuth:X,loginOAuth:ae,submitManualCode:oe}=Fg({apiBase:e,t:g,aliveRef:b,onAdded:i}),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,i)=>y({type:`set-oauth-url`,url:e,providerId:t,deviceCode:n,instructions:r,browserLaunch:i}),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:ne,ok:e})},ce=F?t.includes(F.name.trim())&&F.name.trim()!==``:!1,le=e=>{R||(Jh(e)?y({type:`set-oauth-tos-pending`,providerId:e}):ae(e,se))},ue=e=>{oe(e,te,G,{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:ne,ok:e}),setManualCodeMsg:e=>y({type:`set-manual-code-msg`,msg:e})})},de=P?.id===`custom`,fe=F?.authMode===`local`,pe=P?_m(P):!1;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":g(`modal.add`),className:`modal-overlay`,children:(0,Q.jsxs)(`div`,{ref:S,className:`modal-card`,children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{children:P?g(`modal.addNamed`,{label:P.label}):g(`modal.add`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,"aria-label":g(`common.close`),onClick:r,children:(0,Q.jsx)(xe,{})})]}),!P&&(0,Q.jsx)(Sr,{data:k.data}),P?F&&(P.auth===`oauth`&&F.authMode===`oauth`?(0,Q.jsx)(kg,{preset:P,oauthSupported:A,oauthBusy:R,oauthMsg:z,oauthMsgTone:B,oauthUrl:H===P.oauthProvider?V:``,oauthDeviceCode:H===P.oauthProvider?U:``,oauthInstructions:H===P.oauthProvider?ee:``,oauthBrowserLaunch:H===P.oauthProvider?W:void 0,manualCode:te,manualCodeBusy:G,manualCodeMsg:ne,manualCodeOk:K,onRequestLogin:le,onCancelLogin:e=>{X(e,se,P.label)},onUseApiKeyInstead:()=>{R&&P.oauthProvider&&X(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=>{ue(e)},onBack:()=>{R&&P.oauthProvider&&X(P.oauthProvider,se,P.label),y({type:`back`})}}):(0,Q.jsx)(Ng,{preset:P,form:F,endpointChoice:re,error:L,saving:I,dup:ce,isCustom:de,isLocal:fe,isReservedForward:pe,presetDescription:J,onFormChange:e=>y({type:`set-form`,form:e}),onEndpointChoiceChange:e=>y({type:`set-endpoint-choice`,choice:e}),onSubmit:()=>{ie()},onUseOauthLogin:()=>y({type:`use-oauth-login`,form:{...F,authMode:`oauth`}}),onBack:()=>y({type:`back`})})):(0,Q.jsx)(Dg,{presets:j,usageRank:N,presetsLoading:M,initialTier:a,query:T,onQueryChange:E,onSelectPreset:e=>Y(e),onSelectCustom:()=>Y(_[0]),onShowNote:e=>w(e),accountRows:s,accountStatus:c,busyProvider:l,onLogin:d,onCancelLogin:f,onLogout:p,onManage:m,loginHint:u,paste:{value:te,busy:G,message:ne,ok:K,onChange:e=>y({type:`set-manual-code`,code:e}),onSubmit:e=>{ue(e)}}})]})}),q&&(0,Q.jsx)(yg,{providerId:q,providerLabel:P?.label??q,onCancel:()=>y({type:`set-oauth-tos-pending`,providerId:null}),onContinue:()=>{let e=q;e&&(y({type:`set-oauth-tos-pending`,providerId:null}),ae(e,se))}},q),C?.note&&(0,Q.jsx)(Og,{providerId:C.id,label:C.label,adapter:C.adapter,note:C.note,onClose:()=>w(null)},C.id)]})}function zg({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,Q.jsxs)(Q.Fragment,{children:[r&&(0,Q.jsx)(_f,{...r}),n&&(0,Q.jsx)(Rg,{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,Q.jsx)($l,{apiBase:e,onClose:S,onAdded:C}),l&&(0,Q.jsx)(Uh,{providerName:l,defaultProviderName:u,onCancel:w,onConfirm:T}),f&&E&&D&&O&&(0,Q.jsx)(Wh,{saving:p??!1,onCancel:E,onDiscard:D,onSave:O}),m&&(0,Q.jsx)(yg,{providerId:m.provider,providerLabel:fg(m.provider),onCancel:k,onContinue:A},`${m.provider}:${m.addAccount?`add`:`login`}`)]})}function Bg(e,t,n){return[...hm(e.providers).map(e=>({id:e,label:Ce(e,n),kind:`codex`,href:`#codex-set`})),...t.toSorted((e,t)=>e.localeCompare(t)).map(e=>({id:e,label:fg(e),kind:`oauth`}))]}function Vg(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 Hg(e,t){let[n,r]=(0,Z.useState)({apiBase:e,notice:null});n.apiBase!==e&&r({apiBase:e,notice:null});let i=(0,Z.useRef)(null);(0,Z.useEffect)(()=>()=>{i.current=null},[e]);let a=(0,Z.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,Z.useCallback)(()=>{i.current=null,r(e=>({...e,notice:null}))},[]),s=(0,Z.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}}var Ug=new Set([`dashboard`,`startup`,`providers`,`models`,`subagents`,`advisor`,`logs`,`usage`,`storage`,`remote`,`remote-workspace`,`codex-set`,`integrations`,`claude`]);function Wg(e){let t=Jt(qt(e??(typeof window<`u`?window.location.hash:``))).path,n=t.split(`/`)[0];return n===`debug`?`logs`:n===`codex-auth`?`codex-set`:n===`combos`||n===`routing`||n===`lab`?`models`:n===`api`||n===`grok`?`integrations`:t===`integrations/claude`||t===`integrations/claude/desktop`?`claude`:t===`claude/account`?`providers`:Ug.has(n)?n:`dashboard`}function Gg(e){let t=qt(e);return t_(t).replaceTo??t}var Kg=[`dashboard/providers`,`dashboard/models`],qg=[`models/combos`,`models/routing`,`models/compatibility`],Jg=`models/combos/jev-auto`;function Yg(e){let t=e?.trim();return t&&t!==`jev`?`${Jg}?${new URLSearchParams({decisionProvider:t})}`:Jg}function Xg(e){let{path:t,query:n}=Jt(qt(e));if(t!==`models/combos/jev-auto`)return;let r=new URLSearchParams(n).get(`decisionProvider`)?.trim();return r&&r!==`jev`?r:null}var Zg=`integrations/keys.integrations/codex.integrations/claude.integrations/claude/desktop.integrations/grok.integrations/cursor.integrations/opencode.integrations/pi.integrations/gentle-shell.integrations/omp.integrations/hermes.integrations/openclaw.integrations/kimi.integrations/gajae.integrations/dsh.integrations/mcode.integrations/zcode.integrations/commandcode.integrations/prime.integrations/aside.integrations/raycast.integrations/omo.integrations/cline.integrations/kilo.integrations/droid.integrations/qoder.integrations/qoder-cn.integrations/workbuddy.integrations/workbuddy-ai.integrations/t3code`.split(`.`),Qg=[`providers`,`models/compatibility`,Jg],$g=`providers?provider=anthropic&tab=accounts`;function e_(e,t){return e===t||t===`claude`&&[`claude/code`,`claude/desktop`].includes(e)||t===`logs`&&e===`logs/debug`||t===`usage`&&e===`usage/companion`||t===`codex-set`&&(e===`codex-set/prompt`||e===`codex-set/desktop`)||t===`models`&&(qg.includes(e)||e===`models/combos/jev-auto`)||t===`dashboard`&&(e===`dashboard/update`||Kg.includes(e))||t===`integrations`&&Zg.includes(e)}function t_(e){let{path:t,query:n}=Jt(e);if(n||t!==e){let e=t_(t);return e.replaceTo===null&&Qg.includes(t)?e:{page:e.page,replaceTo:e.replaceTo??t}}let r=Wg(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===`integrations/claude`?{page:`claude`,replaceTo:`claude/code`}:e===`integrations/claude/desktop`?{page:`claude`,replaceTo:`claude/desktop`}:e===`claude/account`?{page:`providers`,replaceTo:$g}:e===`claude/settings`?{page:`claude`,replaceTo:`claude/code`}:e===`grok`?{page:`integrations`,replaceTo:`integrations/grok`}:e===`providers/workspace`?{page:`providers`,replaceTo:`providers`}:e_(e,r)?{page:r,replaceTo:null}:{page:r,replaceTo:r}}var n_=`models/compatibility`,r_=`providers`,i_=200,a_={inbound:``,upstream:``};function o_(e){return e!==void 0&&Lm(e)?e:``}function s_(e){let t=new URLSearchParams;e.inbound&&t.set(`inbound`,e.inbound),e.upstream&&t.set(`upstream`,e.upstream);let n=t.toString();return n?`${n_}?${n}`:n_}function c_(e,t){let n=Jt(Gg(e));return n.path===t?new URLSearchParams(n.query):null}function l_(e=window.location.hash){let t=c_(e,n_);if(!t)return null;let n=t.get(`inbound`),r=t.get(`upstream`);return{inbound:Lm(n)?n:``,upstream:Lm(r)?r:``}}function u_(e){return`${r_}?${new URLSearchParams({provider:e}).toString()}`}function d_(e){return`${r_}?${new URLSearchParams({provider:e,tab:`accounts`}).toString()}`}function f_(e=window.location.hash){return c_(e,`providers`)?.get(`tab`)===`accounts`?`accounts`:`settings`}function p_(e=window.location.hash){let t=c_(e,`providers`)?.get(`provider`)?.trim()??``;return t&&t.length<=i_?t:null}function m_(e){Xt(s_(e))}function h_(e){Xt(u_(e))}function g_(e,t=window){let n=d_(e);qt(t.location.hash)===n?t.dispatchEvent(new t.Event(`hashchange`)):Xt(n,t)}function __(e,t,n,r){let[i,a]=(0,Z.useState)(()=>({name:p_(),tab:f_(),seq:0})),[o,s]=(0,Z.useState)(null),c=(0,Z.useRef)(t);if((0,Z.useEffect)(()=>{let e=()=>a(e=>({name:p_(),tab:f_(),seq:e.seq+1}));return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]),i.name&&o?.seq!==i.seq&&e?.includes(i.name)){let e=i.tab===`accounts`?r:void 0;s({seq:i.seq,provider:i.name,tab:e?`accounts`:`settings`}),e?e(i.name):n(i.name)}return(0,Z.useEffect)(()=>{let e=c.current;if(c.current=t,e===t)return;let n=p_();n&&o?.seq===i.seq&&i.name===n&&(t===null?e===n:t!==n)&&Yt(r_)},[o,i,t]),o?.tab===`settings`?{token:o.seq+1,provider:o.provider}:{token:0,provider:null}}function v_(e){let[t,n]=(0,Z.useState)({epoch:0,force:!1}),r=(0,Z.useRef)(0),i=(0,Z.useRef)(!0),a=(0,Z.useRef)(new Map),o=(0,Z.useCallback)(()=>{for(let e of a.current.values())e.resolve(!1);a.current.clear()},[]);(0,Z.useEffect)(()=>(i.current=!0,()=>{i.current=!1,o()}),[e,o]);let s=(0,Z.useCallback)((e=!1)=>{o();let t=++r.current;return i.current&&n({epoch:t,force:e}),t},[o]),c=(0,Z.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,Z.useCallback)((e,t)=>c(t,`report`,e),[c]),beginQuotaRefresh:(0,Z.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 y_(e,t,n){let r=(0,Z.useRef)(n);(0,Z.useLayoutEffect)(()=>{r.current=n});let i=(0,Z.useRef)(()=>{});return(0,Z.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(`
4
4
  `))}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(`
5
5
  `))!==-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,Z.useCallback)(()=>i.current(),[])}function b_({apiBase:e}){let t=n(),r=`ocx.providers.config.v1:${e}`,[i,a]=(0,Z.useState)(()=>io(r)),[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(``),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(`err`),[m,h]=(0,Z.useState)(0),[g,_]=(0,Z.useState)([]),[v,y]=(0,Z.useState)({}),[b,x]=(0,Z.useState)(null),[S,C]=(0,Z.useState)(null),[w,T]=(0,Z.useState)(null),[E,D]=(0,Z.useState)(null),[O,k]=(0,Z.useState)(null),[A,j]=(0,Z.useState)(!1),[M,N]=(0,Z.useState)(0),[P,F]=(0,Z.useState)(null),[L,R]=(0,Z.useState)({token:0,provider:null}),z=(0,Z.useRef)(!0),B=(0,Z.useRef)(null),V=(0,Z.useRef)(!1),H=(0,Z.useCallback)((e,t=!0,n)=>{l(e),d(t),p(n??(t?`ok`:`err`)),h(e=>e+1)},[]),U=(0,Z.useCallback)(()=>{l(``),d(!1),p(`err`)},[]),ee=(0,Z.useCallback)(e=>{e.validationPending||e.catalogRefreshPending?(l(t(e.validationPending?`pws.healthLabel.validationPending`:`codexAuth.catalogRefreshPending`)),d(!1),p(`warn`),h(e=>e+1)):H(t(`codexAuth.accountAdded`),!0)},[H,t]);(0,Z.useEffect)(()=>(z.current=!0,()=>{z.current=!1}),[]),(0,Z.useEffect)(()=>{if(!c||!u)return;let e=window.setTimeout(U,4500);return()=>window.clearTimeout(e)},[c,u,m,U]);let W=(0,Z.useCallback)(e=>{s(!1),D(null),T(e),R(t=>({token:t.token+1,provider:e}))},[]),te=__(i?Object.keys(i.providers):null,w,T,W),G=Wt(`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});Wt(xr(e),[e],async t=>await br(await fetch(`${e}/api/usage?range=30d`,{signal:t})),{deadlineMs:6e4});let{quotaRefresh:ne,invalidateProviderQuotas:K,settleQuotaRefresh:re,beginQuotaRefresh:q}=v_(e),{fetchConfig:J,fetchOauth:Y,fetchProviderQuotas:ie}=vg({apiBase:e,t,setConfig:a,setOauthProviders:_,setOauthStatus:y,notify:H,invalidateProviderQuotas:K,configCacheKey:r}),X=(0,Z.useCallback)(async()=>{await J()},[J]),ae=Hg(e,J),oe=ae.open,se=(0,Z.useCallback)(e=>{W(e),oe(e,!1)},[W,oe]),ce=Lu(e),le=ce.activeNeedsReauth,ue=(0,Z.useMemo)(()=>{let e=ce.accounts;if(e.length===0&&ce.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}:{},...le?{needsReauth:!0}:{}}}},[v,ce.accounts,ce.loadState,le]),{accountSets:de,setAccountSets:fe,accountLoadStates:pe,switchingAccounts:me,pausingAccounts:he,keyPools:ge,fetchAccountSets:_e,fetchKeyPools:ve,refreshAccountRosters:ye,oauthCardProviders:xe,keyCardProviders:Se,switchAccount:Ce,pauseAccount:we,setAccountPoolThreshold:Te,setAccountThreshold:Ee,switchApiKey:De,removeApiKey:Oe,addApiKeyValue:ke,editCredentialAlias:Ae,removeAccount:je,activeAccountNeedsReauth:Me}=ag({apiBase:e,t,config:i,oauthStatus:ue,aliveRef:z,notify:H,fetchConfig:X,fetchOauth:Y,fetchProviderQuotas:ie,codexActiveNeedsReauth:le}),Ne=(0,Z.useCallback)(e=>e&&!(e.kind===`oauth`?xe:Se).includes(e.provider)?Promise.resolve(!0):ye(e),[ye,xe,Se]),Pe=y_(e,i!==null,Ne),Fe=JSON.stringify([e,xe.toSorted(),Se.toSorted()]),Ie=(0,Z.useRef)(null);Wt(`provider-rosters:${Fe}`,[Fe],async e=>Ie.current===Fe?(Pe(),ye(void 0,e)):(Ie.current=Fe,!0),{enabled:i!==null,pollMs:3e4});let{draft:Le,setDraft:Re,jsonEditorOpen:ze,jsonSaving:Be,jsonLeaveOpen:Ve,saveConfig:He,openJsonEditor:Ue,discardJsonEditor:We,requestCloseJsonEditor:Ge,restoreJsonEditor:Ke,jsonIsDirty:qe,setJsonLeaveOpen:Je}=cg({apiBase:e,config:i,notify:H,fetchConfig:X,fetchProviderQuotas:ie,onSaved:e=>{e.length&&ae.open(e,!0),N(e=>e+1)},t}),Ye=(0,Z.useCallback)(e=>{let t=i?.providers[e],n=t?.authMode,r=t&&be(e,t)?()=>ce.load(!0,{validatePending:!0}):n===`oauth`?()=>_e([e],!0):n===`forward`||n===`local`?void 0:()=>ve([e],!0);return q(r)},[i,ce,_e,ve,q]),Xe=(0,Z.useCallback)(()=>q(),[q]);(0,Z.useEffect)(()=>{B.current!==e&&(B.current=e,Promise.resolve().then(()=>{X(),Y()}))},[e,X,Y]);let Ze=()=>N(e=>e+1),{cancelLoginOAuth:Qe,loginOAuth:$e,logoutOAuth:et,onNativeLoginSettled:tt}=pg({apiBase:e,t,aliveRef:z,accountSets:de,setAccountSets:fe,setBusy:x,setStatus:l,setLoginInfo:C,setOauthStatus:y,notify:H,fetchConfig:X,fetchOauth:Y,fetchAccountSets:_e,fetchProviderQuotas:ie,bumpModelsRefresh:Ze,onLoginSettled:se}),nt=(0,Z.useRef)(tt);(0,Z.useEffect)(()=>{nt.current=tt},[tt]),(0,Z.useEffect)(()=>Vp(e,e=>{nt.current(`kiro`,e).catch(()=>{})}),[e]);let{removeProvider:rt,confirmRemoveProvider:it,setProviderDisabled:at,setDefaultProvider:ot,updateProvider:st}=_g({apiBase:e,t,removeBusyRef:V,workspaceSelected:w,setWorkspaceSelected:T,setRemoveConfirmName:k,notify:H,fetchConfig:X,fetchOauth:Y,fetchProviderQuotas:ie,refreshCodexAccount:()=>ce.load(!0)}),ct=(e,t=!1,n)=>{b!==e&&(Jh(e)?F({provider:e,addAccount:t,...n?{accountId:n}:{}}):$e(e,t,n))};if(!i)return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`page-head`,children:(0,Q.jsx)(`h2`,{children:t(`nav.providers`)})}),c?(0,Q.jsx)(un,{tone:f,onDismiss:U,dismissLabel:t(`common.close`),children:c}):(0,Q.jsxs)(`div`,{className:`providers-workspace providers-workspace--boot`,"aria-busy":`true`,children:[(0,Q.jsx)(`div`,{className:`providers-workspace-rail providers-workspace-rail--boot`,"aria-hidden":`true`}),(0,Q.jsx)(`div`,{className:`providers-workspace-main`,children:(0,Q.jsxs)(`p`,{className:`muted`,children:[(0,Q.jsx)(`span`,{className:`spin`,"aria-hidden":`true`}),` `,t(`prov.loadingConfig`)]})})]})]});let lt=Bg(i,g,t),ut=Vg(i,ue),dt=e=>i.providers[e]?.authMode===`forward`,ft=async(n,r=!1)=>{if(n===`openai`){if(b===`openai`)return;let n=i.providers.openai,r=gm(n);if(r===`invalid`){H(t(`codexAuth.openaiMissing`),!1);return}if(r===`absent`||r===`disabled`){x(`openai`);try{await Cm(e,r),await X()}catch(e){e instanceof Sm?H(t(e.i18nKey),!1):H(e instanceof Error?e.message:t(`prov.saveFailed`),!1);return}finally{z.current&&x(e=>e===`openai`?null:e)}}j(!0)}else dt(n)?j(!0):(i.providers[n]?.authMode===`oauth`||g.includes(n))&&ct(n,r)},pt=e=>{W(e)},mt={onLogin:ct,onNativeLoginSettled:tt,onCancelLogin:Qe,onLogout:et,onReauth:(e,t)=>ct(e,!0,t),onSwitchAccount:Ce,onPauseAccount:we,onAccountPoolThreshold:Te,onAccountThreshold:Ee,onRemoveAccount:je,onRetryAccounts:async e=>{await _e([e])},onAddApiKey:ke,onSwitchApiKey:De,onRemoveApiKey:Oe,onEditAlias:Ae,onRefreshQuota:Ye};return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`page-head`,children:[(0,Q.jsx)(`h2`,{children:t(`nav.providers`)}),(0,Q.jsx)(`div`,{className:`row`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>s(!0),children:[(0,Q.jsx)(I,{}),t(`prov.add`)]})})]}),c&&(0,Q.jsx)(un,{tone:f,onDismiss:U,dismissLabel:t(`common.close`),children:c}),(0,Q.jsx)(jc,{onRemoveProvider:rt,providers:i.providers,apiBase:e,defaultProvider:i.defaultProvider,selectedName:w,onSelect:T,onAddProvider:e=>{D(e??null),s(!0)},onEditConfig:Ue,jsonEditor:{open:ze,draft:Le,isDirty:qe,onDraftChange:Re,onSave:()=>He(),onClose:Ge,onRestore:Ke},jsonSaving:Be,modelsRefreshToken:M,onModelsSettled:ae.modelsSettled,activeAccountNeedsReauth:Me,quotaRefreshEpoch:ne.epoch,quotaForceRefresh:ne.force,onQuotaRefreshSettled:re,onRefreshAllQuotas:Xe,detail:(t,n)=>{let r=ut[t.name]??v[t.name];return(0,Q.jsx)(Gh,{item:t,preset:Lc(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:()=>Xt(`models`),onCreateJevAuto:qr(t)?()=>Xt(Yg(t.name)):void 0,modelsLoading:n.modelsLoading,modelsLoadFailed:n.modelsLoadFailed,onRetryModels:n.onRetryModels,oauthEmail:r?.email,onDeselect:()=>T(null),apiBase:e,oauth:r,accounts:de[t.name]?.accounts??[],keys:ge[t.name]??[],accountLoadState:pe[t.name]??(t.authMode===`oauth`?`idle`:`ready`),accountsFocusToken:L.token,accountsFocusProvider:L.provider,settingsFocusToken:te.token,settingsFocusProvider:te.provider,switchingAccountId:me[t.name]?.accountId??null,pausingAccountId:he[t.name]?.accountId??null,busyProvider:b,loginHint:S,authHandlers:mt,onRefreshQuota:()=>Ye(t.name),isDefault:t.name===i.defaultProvider,onRemoveProvider:rt,onSetDisabled:at,onSetDefault:e=>{ot(e)},onUpdateProvider:st,codexController:ce},t.name)}}),(0,Q.jsx)(zg,{apiBase:e,config:i,adding:o,modelsNotice:ae.notice?{provider:ae.notice.context.provider,initialRegistration:ae.notice.context.initialRegistration,catalogRefreshPending:ae.notice.context.catalogRefreshPending,loading:ae.notice.loading,failed:ae.notice.failed,providerKnown:ae.notice.context.providers.every(e=>!!i.providers[e]),selection:ae.notice.context.providers.length===1?i.providers[ae.notice.context.provider]?.initialModelSelection:ae.notice.context.providers.some(e=>i.providers[e]?.initialModelSelection?.status===`pending`)?{status:`pending`}:void 0,onClose:ae.close,onOpenModels:()=>{ae.close(),Xt(`models`)},onRetry:()=>{let e=ae.notice.context;ae.open(e.providers,e.initialRegistration,e.catalogRefreshPending),Ze()}}:null,addIntent:E,busy:b,addModalAccountRows:lt,accountLoginStatus:ut,accountLoginHint:S,removeConfirmName:O,removeDefaultProvider:O===i.defaultProvider?Object.entries(i.providers).find(([e,t])=>e!==O&&t.disabled!==!0)?.[0]??null:null,codexLoginOpen:A,jsonLeaveOpen:Ve,jsonSaving:Be,oauthTosPending:P,onCloseAdd:()=>{b&&Qe(b),s(!1),D(null)},onAdded:e=>{s(!1),D(null),U(),ae.open(e,!i.providers[e]),X(),Y(),ie(!0),Ze()},onAccountLogin:ft,onAccountCancelLogin:e=>{Qe(e)},onAccountLogout:e=>{et(e)},onAccountManage:pt,onOpenAdd:Y,onCloseCodexLogin:()=>j(!1),onCodexAdded:e=>{j(!1),ee(e),e.validationPending||ae.open(`openai`,!i.providers.openai,e.catalogRefreshPending),X(),Y(),ie(!0),Ze()},onCancelRemove:()=>k(null),onConfirmRemove:()=>{it(O)},onCancelJsonLeave:()=>{Be||Je(!1)},onDiscardJson:We,onSaveJson:()=>{He()},onCancelOauthTos:()=>F(null),onContinueOauthTos:()=>{let e=P;e&&(F(null),$e(e.provider,e.addAccount,e.accountId))}})]})}function x_(e){let{t}=r();return e.state===`stale`?(0,Q.jsxs)(`div`,{className:`codex-stale-banner`,role:`status`,children:[(0,Q.jsx)(`span`,{className:`codex-stale-banner-text`,children:t(`models.staleBanner`)}),(0,Q.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 S_(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e.trim().length>0)}function C_(e){return e===null||e===`alphabetical`||e===`provider`||e===`most-used`}function w_(e){if(typeof e!=`object`||!e)return!1;let t=e;return S_(t.pickerOrder)&&C_(t.pickerOrderMode)}function T_(e){if(!w_(e))return!1;let t=e;return S_(t.pickerAvailable)&&(!(`chosen`in t)||Array.isArray(t.chosen)&&t.chosen.every(e=>typeof e==`string`))}function E_(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 D_(e){let t=e.indexOf(`/`);return t<0?[``,e]:[e.slice(0,t),e.slice(t+1)]}var O_=(e,t)=>e.localeCompare(t,`en`);function k_(e,t){let[n,r]=D_(e),[i,a]=D_(t);return O_(n,i)||O_(r,a)}function A_(e,t,n=[],r=[]){if(e==="default")return null;let i=[...new Set(t)];if(e===`alphabetical`)return i.sort((e,t)=>O_(D_(e)[1],D_(t)[1])||k_(e,t));if(e===`provider`)return i.sort(k_);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)||k_(e,t))}function j_(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=A_(n,e);if(r!==null&&r.length===t.length&&r.every((e,n)=>e===t[n]))return n}return`custom`}function M_(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 N_(e,t,n){return JSON.stringify([e,t,n.pickerAvailable,n.chosen??null,n.pickerOrder,n.pickerOrderMode])}function P_(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 F_(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(!P_(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=M_(e.pickerOrder,n,t);return{fixed:o,order:[...new Set([...o,...s,...n])]}}function I_(e,t,n,r){let i=[...e];return t===n||r.includes(t)||r.includes(n)||!i.includes(t)||!i.includes(n)||(i.splice(i.indexOf(t),1),i.splice(i.indexOf(n),0,t)),i}function L_(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 R_=`application/x-ocx-picker-order`,z_=0;function B_(){let e=++z_;if(typeof crypto<`u`&&typeof crypto.randomUUID==`function`)try{return`${e}:${crypto.randomUUID()}`}catch{}return`picker-${Date.now().toString(36)}-${e}`}function V_({apiBase:e,active:t,identities:r,onAccepted:i,onBusyChange:a}){let o=n(),[s,c]=(0,Z.useState)(null),[l,u]=(0,Z.useState)([]),[d,f]=(0,Z.useState)(!1),[p,m]=(0,Z.useState)(null),[h,g]=(0,Z.useState)(!1),[_,v]=(0,Z.useState)(``),[y,b]=(0,Z.useState)(null),[x,S]=(0,Z.useState)(null),C=(0,Z.useRef)({generation:0,flight:null,drag:null}),[w,T]=(0,Z.useState)({apiBase:e,active:t,onBusyChange:a}),E=JSON.stringify(r.map(({provider:e,id:t,namespaced:n})=>[e,t,n])),D=(0,Z.useRef)(E);(0,Z.useLayoutEffect)(()=>{D.current=E},[E]);let O=s!==null&&s.identities!==E,k=!t||d||!s||p!==null||O,A=s!==null&&JSON.stringify(l)!==JSON.stringify(s.order),j=(0,Z.useCallback)(()=>{C.current.drag=null,b(null),S(null)},[]);(w.apiBase!==e||w.active!==t||w.onBusyChange!==a)&&(T({apiBase:e,active:t,onBusyChange:a}),c(null),u([]),m(null),g(!1),f(!1));let[N,P]=(0,Z.useState)({disabled:k,snapshot:s,identitySignature:E});(N.disabled!==k||N.snapshot!==s||N.identitySignature!==E)&&(P({disabled:k,snapshot:s,identitySignature:E}),b(null),S(null)),(0,Z.useLayoutEffect)(()=>{let e=C.current;return e.generation++,()=>{e.generation++,e.flight?.controller.abort(),e.flight?.clear(),e.flight=null,e.drag=null,a(!1)}},[e,t,a]),(0,Z.useLayoutEffect)(()=>{C.current.drag=null},[k,s,E]);let F=async n=>{if(!t||C.current.flight||n&&(k||!A))return;let o=C.current.generation,d=M(15e3);C.current.flight=d,f(!0),a(!0),g(!1),j();let p=()=>C.current.generation===o&&C.current.flight===d,h=()=>p()&&!d.signal.aborted&&D.current===E;try{let t=await fetch(`${e}/api/subagent-models`,{signal:d.signal});if(!h())return;let a=await vn(t);if(!h())return;if(!T_(a))throw Error(`Invalid picker settings`);let f=N_(e,o,a);if(n&&(!s||f!==s.signature||E!==s.identities)){m(`models.pickerOrder.changed`);return}let p=F_(a,r);if(!p){m(a.pickerOrder.some(e=>!e.includes(`/`))?`models.pickerOrder.nativeLocked`:a.chosen===void 0?`models.pickerOrder.unknownChosen`:`models.pickerOrder.catalogRequired`);return}if(!n){c({...p,signature:f,identities:E}),u(p.order),m(null),v(``);return}let g=await fetch(`${e}/api/subagent-models`,{method:`PUT`,headers:{"Content-Type":`application/json`},signal:d.signal,body:JSON.stringify({pickerOrder:l,pickerOrderMode:null})});if(!h())return;let _=await vn(g);if(!h())return;if(!w_(_)||!(`ok`in _)||_.ok!==!0)throw Error(`Invalid picker receipt`);u(_.pickerOrder),m(`models.pickerOrder.savedReload`),i({pickerOrder:_.pickerOrder,pickerOrderMode:_.pickerOrderMode,catalogRefresh:`catalogRefresh`in _?_.catalogRefresh:void 0})}catch{p()&&D.current===E&&g(!0)}finally{d.clear(),p()&&(C.current.flight=null,f(!1),a(!1))}},I=(0,Z.useEffectEvent)(async()=>{let e=C.current,n=e.generation;await Promise.resolve(),t&&e.generation===n&&F(!1)});(0,Z.useEffect)(()=>{t&&I()},[e,t,a]);let L=(e,t)=>{k||(u(t),v(o(`models.pickerOrder.position`,{model:e,position:t.indexOf(e)+1,total:t.length})),j())},R=new Set(l),z=new Set(s?.fixed),B=e=>!k&&R.has(e)&&!z.has(e),V=(e,t)=>{C.current.drag&&C.current.drag.id!==t&&B(C.current.drag.id)&&B(t)&&e.dataTransfer.types.includes(R_)&&(e.preventDefault(),e.dataTransfer.dropEffect=`move`,S(t))};return(0,Q.jsxs)(`section`,{className:`picker-order-editor`,"aria-label":o(`models.pickerOrder.custom`),"aria-busy":d,children:[(0,Q.jsx)(`p`,{className:`muted text-label`,children:o(`models.pickerOrder.editorHint`)}),(p||O)&&(0,Q.jsx)(`p`,{role:`alert`,children:o(p??`models.pickerOrder.changed`)}),h&&(0,Q.jsx)(`p`,{role:`alert`,children:o(`models.pickerOrder.requestFailed`)}),s&&l.length===0&&(0,Q.jsx)(`p`,{children:o(`models.pickerOrder.empty`)}),(0,Q.jsx)(`ol`,{className:`picker-order-list`,children:l.map((e,t)=>{let n=z.has(e);return(0,Q.jsxs)(`li`,{className:`picker-order-row${y===e?` cwi-target-row--dragging`:``}${x===e?` cwi-target-row--drop`:``}`,onDragOver:t=>V(t,e),onDragLeave:()=>S(null),onDrop:t=>{let n=C.current.drag;n&&n.id!==e&&n.token===t.dataTransfer.getData(R_)&&B(n.id)&&B(e)&&(t.preventDefault(),L(n.id,I_(l,n.id,e,s?.fixed??[]))),j()},onDragEnd:j,children:[(0,Q.jsx)(`button`,{type:`button`,className:`cwi-target-grip`,disabled:k||n,draggable:!k&&!n,"aria-label":o(`models.pickerOrder.dragModel`,{model:e}),onDragStart:t=>{if(!B(e)){t.preventDefault();return}let n=B_();C.current.drag={id:e,token:n},b(e),t.dataTransfer.effectAllowed=`move`,t.dataTransfer.setData(R_,n)},children:(0,Q.jsx)(Re,{width:14,height:14,"aria-hidden":`true`})}),(0,Q.jsx)(`code`,{className:`picker-order-name`,children:e}),n&&(0,Q.jsx)(`span`,{className:`muted text-caption`,children:o(`models.pickerOrder.featured`)}),(0,Q.jsxs)(`span`,{className:`picker-order-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:k||n||t===0||z.has(l[t-1]),"aria-label":o(`models.pickerOrder.upModel`,{model:e}),onClick:()=>L(e,L_(l,e,-1,s?.fixed??[])),children:(0,Q.jsx)(Je,{width:14,height:14,"aria-hidden":`true`})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:k||n||t===l.length-1||z.has(l[t+1]),"aria-label":o(`models.pickerOrder.downModel`,{model:e}),onClick:()=>L(e,L_(l,e,1,s?.fixed??[])),children:(0,Q.jsx)(tt,{width:14,height:14,"aria-hidden":`true`})})]})]},e)})}),(0,Q.jsx)(`p`,{role:`status`,"aria-live":`polite`,children:_}),(0,Q.jsxs)(`div`,{className:`row`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:k||!A,onClick:()=>void F(!0),children:o(d?`models.pickerOrder.applying`:`models.pickerOrder.saveDraft`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:!t||d,onClick:()=>void F(!1),children:o(`models.pickerOrder.reloadDraft`)})]})]})}function H_({apiBase:e,onSaved:t}){let r=n(),[i,a]=(0,Z.useState)(!0),[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(null),m=(0,Z.useRef)(!0),h=(0,Z.useRef)(!1),g=(0,Z.useRef)(0),_=(0,Z.useCallback)(async()=>{if(h.current)return;let t=++g.current,n=M(15e3);try{let r=await fetch(`${e}/api/settings`,{signal:n.signal});if(!r.ok)throw Error(`load`);let i=await r.json();if(h.current||t!==g.current)return;if(typeof i.fastRows!=`boolean`)throw Error(`shape`);m.current=i.fastRows,a(i.fastRows),s(!0),d(!1)}catch{!h.current&&t===g.current&&d(!0)}finally{n.clear()}},[e]);(0,Z.useEffect)(()=>{let e=window.setTimeout(()=>{_()},0),t=ba(()=>{_()},3e4);return()=>{window.clearTimeout(e),t()}},[_]);let v=(0,Z.useCallback)(async()=>{if(h.current||!o)return;let n=m.current,i=!n;m.current=i,a(i),h.current=!0,l(!0),p(null),g.current+=1;let c=M(15e3);try{let n=await vn(await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({fastRows:i}),signal:c.signal}))??{};if(n.ok!==!0||typeof n.fastRows!=`boolean`)throw Error(`unconfirmed`);m.current=n.fastRows,a(n.fastRows),s(!0),d(!1),p(n.catalogRefreshPending===!0?{tone:`warn`,message:r(`models.fastRows.refreshHint`)}:{tone:`ok`,message:r(n.fastRows?`models.fastRows.enabled`:`models.fastRows.disabled`)}),t?.()}catch{let o=M(15e3);try{let t=await fetch(`${e}/api/settings`,{signal:o.signal});if(!t.ok)throw Error(`reconcile`);let n=await t.json();if(typeof n.fastRows!=`boolean`)throw Error(`shape`);m.current=n.fastRows,a(n.fastRows),s(!0),d(!1),p(n.fastRows===i?{tone:`warn`,message:r(`models.fastRows.refreshHint`)}:{tone:`err`,message:r(`models.fastRows.updateFailed`)})}catch{m.current=n,a(n),p({tone:`err`,message:r(`models.fastRows.updateFailed`)})}finally{o.clear(),t?.()}}finally{c.clear(),h.current=!1,l(!1)}},[e,o,t,r]),y=u&&!o;return(0,Q.jsxs)(`div`,{className:`card card-row fast-rows-card`,"aria-busy":c||!o&&!y||void 0,children:[(0,Q.jsxs)(`div`,{className:`fast-rows-copy`,children:[(0,Q.jsx)(`strong`,{children:r(`models.fastRows.title`)}),(0,Q.jsx)(`div`,{className:`card-sub`,role:y?`status`:void 0,children:r(y?`models.fastRows.loadFailed`:o?`models.fastRows.desc`:`common.loading`)}),o&&u&&(0,Q.jsx)(`div`,{className:`card-sub faint`,role:`status`,children:r(`models.fastRows.loadFailed`)})]}),(0,Q.jsxs)(`div`,{className:`fast-rows-controls`,children:[u&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{_()},disabled:c,children:r(`common.retry`)}),o&&(0,Q.jsx)(`button`,{type:`button`,className:`toggle ${i?`on`:``}`,onClick:()=>{v()},disabled:c,"aria-pressed":i,"aria-label":r(`models.fastRows.title`),title:r(`models.fastRows.title`),children:(0,Q.jsx)(`span`,{className:`toggle-knob`})})]}),f&&(0,Q.jsx)(`div`,{className:`fast-rows-feedback is-${f.tone}`,role:f.tone===`err`?`alert`:`status`,"aria-atomic":`true`,children:f.message})]})}function U_({showOrderEditor:e,onSaved:t,...n}){return(0,Q.jsxs)(Q.Fragment,{children:[e&&(0,Q.jsx)(V_,{...n},n.apiBase),(0,Q.jsx)(H_,{apiBase:n.apiBase,onSaved:t})]})}var W_={operator:`models.displayNameSourceOperator`,provider:`models.displayNameSourceProvider`,fallback:`models.displayNameSourceFallback`};function G_({model:e,saving:t,requestError:r,currentNamePending:i=!1,mutationOutcomeUnknown:a=!1,onRetry:o,onEdit:s,onSave:c,onReset:l,onClose:u}){let d=n(),f=(0,Z.useRef)(null),p=(0,Z.useRef)(null),m=(0,Z.useRef)(null),h=(0,Z.useRef)(t),g=(0,Z.useId)(),_=(0,Z.useId)(),v=(0,Z.useId)(),[y,b]=(0,Z.useState)(e),[x,S]=(0,Z.useState)(e.displayNameOverride??``),[C,w]=(0,Z.useState)(null);(0,Z.useEffect)(()=>{let e=f.current;return e&&!e.open&&e.showModal(),p.current?.focus(),()=>{e?.open&&e.close()}},[]),(0,Z.useEffect)(()=>{let e=h.current&&!t&&!!r;h.current=t,e&&(a?m.current?.focus():p.current?.focus())},[r,t,a]),y!==e&&(b(e),S(e.displayNameOverride??``),w(null));let T=C?d(C):null,E=T??r,D=e.displayNameSource?W_[e.displayNameSource]:`models.displayNameSourceFallback`,O=()=>{t||u()};return(0,Q.jsxs)(`dialog`,{ref:f,className:`modal-overlay`,"aria-labelledby":g,onCancel:e=>{e.preventDefault(),O()},children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":d(`common.close`),tabIndex:-1,disabled:t,onClick:O}),(0,Q.jsxs)(`form`,{className:`modal-card model-display-name-dialog`,role:`document`,onClick:e=>e.stopPropagation(),onSubmit:e=>{if(e.preventDefault(),t)return;if(o){o();return}if(a)return;let n=as(x);w(n),n||c(x.trim())},children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:g,children:d(`models.displayNameTitle`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:t,onClick:O,children:d(`common.close`)})]}),(0,Q.jsxs)(`div`,{className:`model-display-name-identity`,children:[(0,Q.jsx)(`span`,{className:`muted text-label`,children:d(`models.displayNameModelId`)}),(0,Q.jsx)(`code`,{className:`mono text-control`,children:e.namespaced})]}),(0,Q.jsxs)(`div`,{className:`model-display-name-current`,children:[(0,Q.jsx)(`span`,{className:`muted text-label`,children:d(`models.displayNameCurrent`)}),(0,Q.jsx)(`strong`,{children:i?d(`models.displayNameCurrentUnavailable`):e.displayName??e.namespaced}),!i&&(0,Q.jsx)(`span`,{className:`models-chip muted text-caption`,children:d(D)})]}),(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`${g}-input`,children:d(`models.displayNameField`)}),(0,Q.jsx)(`input`,{ref:p,id:`${g}-input`,className:`input`,value:x,maxLength:129,placeholder:d(`models.displayNamePlaceholder`),"aria-describedby":`${_}${E?` ${v}`:``}`,"aria-invalid":T?!0:void 0,disabled:t||a,onChange:e=>{t||a||(s?.(),S(e.target.value),w(null))}}),(0,Q.jsx)(`p`,{id:_,className:`muted small`,children:d(`models.displayNameHelp`,{model:e.namespaced})}),E&&(0,Q.jsx)(`p`,{id:v,className:`model-display-name-error`,role:`alert`,children:E}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:t||a||!e.displayNameOverride,onClick:()=>{!t&&!a&&l()},children:d(`models.displayNameReset`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:t,onClick:O,children:d(`common.cancel`)}),(0,Q.jsx)(`button`,{ref:m,type:`submit`,className:`btn btn-primary btn-sm`,disabled:t||a&&!o,children:d(t?`common.saving`:o?`common.retry`:`common.save`)})]})]})]})}var K_=[`input`,`output`,`cacheRead`,`cacheWrite`],q_={input:``,output:``,cacheRead:``,cacheWrite:``},J_={...q_,threshold:``,comparison:`gt`},Y_=Symbol(`invalid model cost`),X_={input:`customInput`,output:`customOutput`,cacheRead:`customCacheRead`,cacheWrite:`customCacheWrite`};function Z_(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Q_(e,t){return Object.keys(e).length===t.length&&t.every(t=>Object.hasOwn(e,t))}function $_(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0&&e<=1e6}function ev(e){return Z_(e)&&Q_(e,K_)&&K_.every(t=>$_(e[t]))}function tv(e){if(e!==void 0){if(!Z_(e))return Y_;if(!(e.mode===`automatic`&&Q_(e,[`mode`])))return e.mode===`flat`&&Q_(e,[`mode`])?{mode:`flat`}:e.mode!==`custom`||!Number.isSafeInteger(e.thresholdTokens)||Number(e.thresholdTokens)<=0||!Q_(e,[`mode`,`thresholdTokens`,`comparison`,`rates`])||e.comparison!==`gt`&&e.comparison!==`gte`||!ev(e.rates)?Y_:{mode:`custom`,thresholdTokens:Number(e.thresholdTokens),comparison:e.comparison,rates:{input:e.rates.input,output:e.rates.output,cacheRead:e.rates.cacheRead,cacheWrite:e.rates.cacheWrite}}}}function nv(e){if(!Z_(e)||!Q_(e,Object.hasOwn(e,`promptLengthPricing`)?[...K_,`promptLengthPricing`]:K_)||!K_.every(t=>$_(e[t])))return Y_;let t=tv(e.promptLengthPricing);if(t===Y_)return Y_;let n=Object.fromEntries(K_.map(t=>[t,e[t]]));return t===void 0?n:{...n,promptLengthPricing:t}}function rv(e,t){if(!K_.every(n=>e[n]===t[n]))return!1;let n=e.promptLengthPricing??{mode:`automatic`},r=t.promptLengthPricing??{mode:`automatic`};return n.mode===r.mode?n.mode!==`custom`||r.mode===`custom`&&n.thresholdTokens===r.thresholdTokens&&n.comparison===r.comparison&&K_.every(e=>n.rates[e]===r.rates[e]):!1}function iv(e,t){if(t===null)return e===null;let n=nv(e);return n!==Y_&&rv(n,t)}var av=e=>Object.fromEntries(K_.map(t=>[t,String(e[t])]));function ov(e){if(!e)return{rates:q_,mode:`automatic`,custom:J_};let t=e.promptLengthPricing;return!t||t.mode===`flat`?{rates:av(e),mode:t?.mode??`automatic`,custom:J_}:{rates:av(e),mode:`custom`,custom:{...av(t.rates),threshold:String(t.thresholdTokens),comparison:t.comparison}}}var sv=e=>e.trim()===``?0:Number(e);function cv(e,t,n,r){if(r)return{field:r};if(!e.input.trim())return{field:`input`};if(!e.output.trim())return{field:`output`};let i={input:Number(e.input),output:Number(e.output),cacheRead:sv(e.cacheRead),cacheWrite:sv(e.cacheWrite)},a=K_.find(e=>!$_(i[e]));if(a)return{field:a};if(t===`automatic`)return{cost:i};if(t===`flat`)return{cost:{...i,promptLengthPricing:{mode:`flat`}}};let o=n.threshold.trim();if(!/^[1-9]\d*$/.test(o)||!Number.isSafeInteger(Number(o)))return{field:`threshold`};if(!n.input.trim())return{field:`customInput`};if(!n.output.trim())return{field:`customOutput`};let s={input:Number(n.input),output:Number(n.output),cacheRead:sv(n.cacheRead),cacheWrite:sv(n.cacheWrite)},c=K_.find(e=>!$_(s[e]));return c?{field:X_[c]}:{cost:{...i,promptLengthPricing:{mode:`custom`,thresholdTokens:Number(o),comparison:n.comparison,rates:s}}}}var lv={input:`pricing.override.input`,output:`pricing.override.output`,cacheRead:`pricing.override.cacheRead`,cacheWrite:`pricing.override.cacheWrite`},uv=6e4;function dv({model:e,apiBase:t,onRefresh:r,onClose:i}){let a=n(),o=(0,Z.useId)(),s=(0,Z.useId)(),c=(0,Z.useId)(),l=(0,Z.useRef)(null),u=(0,Z.useRef)(null),d=(0,Z.useRef)({}),f=(0,Z.useRef)(null),p=(0,Z.useRef)(null),m=(0,Z.useRef)(!1),[h,g]=(0,Z.useState)(`loading`),[_,v]=(0,Z.useState)(q_),[y,b]=(0,Z.useState)(`automatic`),[x,S]=(0,Z.useState)(J_),[C,w]=(0,Z.useState)(!1),[T,E]=(0,Z.useState)(null),[D,O]=(0,Z.useState)(null),[k,A]=(0,Z.useState)(!1),j=`${t}/api/providers/${encodeURIComponent(e.provider)}/model-costs`,N=h===`saving`||h===`refreshing`,P=h!==`ready`,F=(0,Z.useCallback)((t=!1)=>{if(p.current)return;let n=M(uv);p.current=n,fetch(j,{signal:n.signal,cache:`no-store`}).then(async r=>{let i=await vn(r);if(n.signal.throwIfAborted(),!Z_(i)||i.provider!==e.provider||!Z_(i.modelCosts))throw Error(`invalid model-costs response`);let a=Object.hasOwn(i.modelCosts,e.id)?i.modelCosts[e.id]:void 0,o=a===void 0?void 0:nv(a);if(o===Y_)throw Error(`invalid model cost`);if(p.current!==n)return;let s=ov(o);v(s.rates),b(s.mode),S(s.custom),w(o!==void 0),E(null),O(null),A(t),g(`ready`)}).catch(()=>{p.current===n&&(g(t?`unknown`:`loadFailed`),E(t?`pricing.override.recoveryFailed`:`pricing.override.loadFailed`))}).finally(()=>{n.clear(),p.current===n&&(p.current=null)})},[j,e.id,e.provider,S,E,O,b]);(0,Z.useEffect)(()=>{let e=l.current;return e&&!e.open&&e.showModal(),F(),()=>{p.current?.controller.abort(),p.current?.clear(),p.current=null,e?.open&&e.close()}},[F]),(0,Z.useEffect)(()=>{h===`ready`?u.current?.focus():(h===`unknown`||h===`loadFailed`||h===`refreshFailed`)&&f.current?.focus()},[h]);let I=async t=>{if(p.current||(t===void 0?h!==`refreshFailed`:h!==`ready`))return;let n=M(uv);p.current=n,g(t===void 0?`refreshing`:`saving`),m.current=!0,E(null),O(null);let a=t===void 0;try{if(t!==void 0){let r=await vn(await fetch(j,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({modelId:e.id,cost:t}),signal:n.signal}));n.signal.throwIfAborted();let i=Z_(r)?r.cost:void 0;if(!Z_(r)||r.ok!==!0||r.provider!==e.provider||r.modelId!==e.id||!iv(i,t))throw Error(`invalid model-costs receipt`);if(p.current!==n)return;a=!0,g(`refreshing`)}if(!await r(n.signal))throw Error(`catalog refresh failed`);n.signal.throwIfAborted(),p.current===n&&i()}catch{if(p.current!==n)return;g(a?`refreshFailed`:`unknown`),E(a?`pricing.override.refreshFailed`:`pricing.override.outcomeUnknown`)}finally{n.clear(),p.current===n&&(p.current=null,m.current=!1)}},L=()=>{m.current||i()};return(0,Q.jsxs)(`dialog`,{ref:l,className:`modal-overlay`,"aria-labelledby":`${o}-title`,onCancel:e=>{e.preventDefault(),L()},children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,tabIndex:-1,"aria-label":a(`pricing.override.close`),disabled:N,onClick:L}),(0,Q.jsxs)(`form`,{className:`modal-card model-display-name-dialog model-price-dialog`,role:`document`,noValidate:!0,"aria-busy":h===`loading`||N,onClick:e=>e.stopPropagation(),onSubmit:e=>{if(e.preventDefault(),p.current)return;if(h===`unknown`||h===`loadFailed`){g(`loading`),E(null),F(h===`unknown`);return}if(h===`refreshFailed`){I(void 0);return}if(P)return;let t=Object.entries(d.current).find(([,e])=>e.validity.badInput)?.[0],n=cv(_,y,x,t);`field`in n?(O(n.field),E(n.field===`threshold`||n.field.startsWith(`custom`)?`pricing.override.customInvalid`:`pricing.override.invalid`),d.current[n.field]?.focus()):I(n.cost)},children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:`${o}-title`,children:a(`pricing.override.title`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:N,onClick:L,children:a(`pricing.override.close`)})]}),(0,Q.jsxs)(`div`,{className:`model-display-name-identity`,children:[(0,Q.jsx)(`span`,{className:`muted text-label`,children:a(`pricing.override.modelId`)}),(0,Q.jsx)(`code`,{className:`mono text-control`,children:e.namespaced})]}),(0,Q.jsxs)(`div`,{className:`model-price-body`,children:[(0,Q.jsx)(`p`,{id:s,className:`muted small`,children:a(`pricing.override.help`)}),(0,Q.jsx)(`p`,{className:`muted small`,children:a(`pricing.override.promptHelp`)}),h===`loading`&&(0,Q.jsx)(`p`,{role:`status`,className:`muted small`,children:a(`pricing.override.loading`)}),(0,Q.jsx)(`div`,{className:`model-price-rates-grid`,children:K_.map(e=>(0,Q.jsxs)(`div`,{className:`model-price-rate-field`,children:[(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`${o}-${e}`,children:a(lv[e])}),(0,Q.jsx)(`input`,{ref:t=>{t?d.current[e]=t:delete d.current[e],e===`input`&&(u.current=t)},id:`${o}-${e}`,className:`input`,type:`number`,min:0,max:1e6,step:`any`,inputMode:`decimal`,value:_[e],disabled:P,required:e===`input`||e===`output`,"aria-describedby":`${s}${T?` ${c}`:``}`,"aria-invalid":D===e||void 0,onChange:t=>{if(P||p.current)return;let n=t.target.value;v(t=>({...t,cacheRead:t.cacheRead||`0`,cacheWrite:t.cacheWrite||`0`,[e]:n})),E(null),O(null)}})]},e))}),(0,Q.jsxs)(`fieldset`,{className:`model-price-mode`,children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:a(`pricing.override.promptTitle`)}),[`automatic`,`flat`,`custom`].map(e=>(0,Q.jsxs)(`label`,{className:`model-price-mode-option`,children:[(0,Q.jsx)(`input`,{type:`radio`,name:`${o}-mode`,value:e,checked:y===e,disabled:P,onChange:()=>{b(e),E(null),O(null)}}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:a(`pricing.override.mode${e[0].toUpperCase()}${e.slice(1)}`)}),(0,Q.jsx)(`small`,{className:`muted`,children:a(`pricing.override.mode${e[0].toUpperCase()}${e.slice(1)}Help`)})]})]},e))]}),y===`custom`&&(0,Q.jsxs)(`section`,{className:`model-price-band`,"aria-labelledby":`${o}-custom-title`,children:[(0,Q.jsx)(`h4`,{id:`${o}-custom-title`,className:`model-price-band-title`,children:a(`pricing.override.bandTitle`)}),(0,Q.jsxs)(`div`,{className:`model-price-custom-controls`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`${o}-threshold`,children:a(`pricing.override.threshold`)}),(0,Q.jsx)(`input`,{ref:e=>{e?d.current.threshold=e:delete d.current.threshold},id:`${o}-threshold`,className:`input`,type:`number`,min:1,step:1,inputMode:`numeric`,value:x.threshold,disabled:P,"aria-describedby":`${s}${T?` ${c}`:``}`,"aria-invalid":D===`threshold`||void 0,onChange:e=>{S(t=>({...t,threshold:e.target.value})),E(null),O(null)}})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`${o}-comparison`,children:a(`pricing.override.comparison`)}),(0,Q.jsx)(dn,{id:`${o}-comparison`,label:a(`pricing.override.comparison`),value:x.comparison,disabled:P,portal:!1,describedBy:s,options:[{value:`gt`,label:a(`pricing.override.comparisonGt`)},{value:`gte`,label:a(`pricing.override.comparisonGte`)}],onChange:e=>S(t=>({...t,comparison:e}))})]})]}),(0,Q.jsx)(`p`,{id:`${o}-custom-help`,className:`muted small`,children:a(`pricing.override.bandHelp`)}),(0,Q.jsx)(`div`,{className:`model-price-rates-grid`,children:K_.map(e=>(0,Q.jsxs)(`div`,{className:`model-price-rate-field`,children:[(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`${o}-custom-${e}`,children:a(lv[e])}),(0,Q.jsx)(`input`,{ref:t=>{let n=X_[e];t?d.current[n]=t:delete d.current[n]},id:`${o}-custom-${e}`,className:`input`,type:`number`,min:0,max:1e6,step:`any`,inputMode:`decimal`,value:x[e],disabled:P,required:e===`input`||e===`output`,"aria-describedby":`${s}${T?` ${c}`:``}`,"aria-invalid":D===X_[e]||void 0,onChange:t=>{let n=t.target.value;S(t=>({...t,[e]:n})),E(null),O(null)}})]},`custom-${e}`))})]})]}),k&&(0,Q.jsx)(`p`,{role:`status`,className:`muted small`,children:a(`pricing.override.recovered`)}),T&&(0,Q.jsx)(`p`,{id:c,className:`model-display-name-error`,role:`alert`,children:a(T)}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:P||!C,onClick:()=>void I(null),children:a(`pricing.override.reset`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:N,onClick:L,children:a(`pricing.override.cancel`)}),(0,Q.jsx)(`button`,{ref:f,type:`submit`,className:`btn btn-primary btn-sm`,disabled:h===`loading`||N,children:a(N?`pricing.override.saving`:h===`unknown`||h===`loadFailed`?`pricing.override.reload`:h===`refreshFailed`?`pricing.override.refresh`:`pricing.override.save`)})]})]})]})}var fv=[`text`,`image`,`audio`],pv=[`100000`,`128000`,`200000`,`256000`,`352000`,`500000`,`1000000`],mv=6e4;function hv(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function gv(e){let t=e.reasoningOverridden===!0;return{contextWindow:e.contextWindowDeclared===void 0?``:String(e.contextWindowDeclared),modalities:Array.isArray(e.inputModalitiesDeclared)?[...e.inputModalitiesDeclared]:[],reasoning:t,ladder:t&&Array.isArray(e.reasoningEfforts)?[...e.reasoningEfforts]:[],defaultEffort:t?e.defaultReasoningEffort??``:``}}function _v(e){return e.toSorted().join(`,`)}function vv(e){let t=e.trim();if(!t)return null;let n=Number(t.replace(/[_,\s]/g,``));return Number.isSafeInteger(n)&&n>0?n:void 0}function yv({row:e,apiBase:t,onRefresh:r,onFeedback:i,onClose:a}){let o=n(),s=(0,Z.useId)(),c=(0,Z.useRef)(null),l=(0,Z.useRef)(null),u=(0,Z.useRef)(null),[d]=(0,Z.useState)(()=>gv(e)),[f,p]=(0,Z.useState)(`ready`),[m,h]=(0,Z.useState)(()=>d.contextWindow),[g,_]=(0,Z.useState)(()=>d.contextWindow!==``&&!pv.includes(d.contextWindow)),[v,y]=(0,Z.useState)(()=>[...d.modalities]),[b,x]=(0,Z.useState)(()=>d.reasoning),[S,C]=(0,Z.useState)(()=>[...d.ladder]),[w,T]=(0,Z.useState)(()=>d.defaultEffort),[E,D]=(0,Z.useState)(null),O=f===`saving`||f===`restoring`,k=f===`unknown`||f===`saved-stale`;(0,Z.useEffect)(()=>{let e=c.current,t=document.activeElement;return e&&!e.open&&e.showModal(),()=>{e?.open&&e.close(),t?.isConnected&&typeof t.focus==`function`&&t.focus()}},[]),(0,Z.useEffect)(()=>{k&&l.current?.focus()},[k]);let A=async()=>{let t=M(mv);u.current=t;try{if(!await r(t.signal)||(t.signal.throwIfAborted(),u.current!==t))return;i(!0,o(`models.settingsReloaded`,{model:e.namespaced})),a()}catch{}finally{t.clear(),u.current===t&&(u.current=null)}},j=t=>{if(x(t),!t||S.length>0)return;let n=Array.isArray(e.reasoningEfforts)?e.reasoningEfforts:void 0;C(n&&n.length>0?[...n]:[...os])},N=(e,t)=>{C(n=>t?[...n,e]:n.filter(t=>t!==e)),!t&&w===e&&T(``)},P=()=>{O||a()},F=async(n,s)=>{let c=M(mv);u.current=c,p(s?`restoring`:`saving`),D(null);let l=!1,d=!1;try{let f=await fetch(t+`/api/model-settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({provider:e.provider,modelId:e.id,...n}),signal:c.signal});if(f.status>=400&&f.status<500)throw d=!0,Error(`model settings rejected`);let p=await vn(f);if(c.signal.throwIfAborted(),!hv(p)||p.ok!==!0||p.provider!==e.provider||p.modelId!==e.id||typeof p.changed!=`boolean`||typeof p.hasOverrides!=`boolean`||typeof p.saved!=`boolean`||p.saved!==p.changed||!hv(p.catalogRefresh)||![`committed`,`skipped`,`failed`].includes(String(p.catalogRefresh.status)))throw Error(`invalid model-settings receipt`);if(u.current!==c)return;if(l=!0,!p.changed){i(!0,o(s&&!p.hasOverrides?`models.settingsNothingToRestore`:`models.settingsNoChange`,{model:e.namespaced})),a();return}let m=p.catalogRefresh,h=m.status===`failed`||m.status===`skipped`&&m.retryable===!0;if(!await r(c.signal))throw Error(`catalog refresh failed`);if(c.signal.throwIfAborted(),u.current!==c)return;h?i(!1,o(`models.settingsSavedCodexStale`,{model:e.namespaced})):s?i(!0,o(`models.settingsRestored`,{model:e.namespaced})):i(!0,o(`models.settingsSaved`,{model:e.namespaced})),a()}catch{if(u.current!==c)return;if(d){p(`ready`),D(`models.settingsRejected`);return}p(l?`saved-stale`:`unknown`),D(l?`models.settingsRefreshFailed`:`models.settingsSaveFailed`)}finally{c.clear(),u.current===c&&(u.current=null)}},I=()=>{if(f!==`ready`)return;let e=vv(m);if(e===void 0){D(`models.contextInvalid`);return}let t=d,n={};m.trim()!==t.contextWindow&&(n.contextWindow=e),_v(v)!==_v(t.modalities)&&(n.inputModalities=v.length>0?[...v]:null);let r=b?_v(S):``;(b!==t.reasoning||r!==_v(t.ladder))&&(n.reasoningEfforts=b?[...S]:null);let i=b&&S.includes(w)?w:``;i!==t.defaultEffort&&(n.defaultReasoningEffort=i||null),Object.keys(n).length===0?a():F(n,!1)},L=async()=>{f===`ready`&&await ha({message:o(`models.settingsRestoreConfirm`,{model:e.namespaced}),confirmLabel:o(`models.settingsRestore`),tone:`danger`})&&F({contextWindow:null,inputModalities:null,reasoningEfforts:null,defaultReasoningEffort:null},!0)},R=Array.isArray(e.inputModalities)?e.inputModalities.join(`, `):``,z=Array.isArray(e.inputModalities)?e.inputModalities.filter(e=>fv.includes(e)):[];return(0,Q.jsxs)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":s+`-title`,onCancel:e=>{e.preventDefault(),P()},children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":o(`common.close`),tabIndex:-1,disabled:O,onClick:P}),(0,Q.jsxs)(`form`,{className:`modal-card model-display-name-dialog`,role:`document`,noValidate:!0,"aria-busy":O,onClick:e=>e.stopPropagation(),onSubmit:e=>{e.preventDefault(),I()},children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:s+`-title`,children:o(`models.settingsTitle`,{model:e.namespaced})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:O,onClick:P,children:o(`common.close`)})]}),E&&(0,Q.jsx)($,{tone:f===`saved-stale`?`warn`:`err`,children:o(E)}),(0,Q.jsxs)(`div`,{className:`models-field-stack`,children:[(0,Q.jsxs)(`div`,{className:`text-label models-field`,children:[o(`models.customFieldModelId`),(0,Q.jsx)(`code`,{className:`mono text-control`,children:e.namespaced})]}),(0,Q.jsxs)(`label`,{className:`text-label models-field`,children:[o(`models.customFieldContext`),(0,Q.jsxs)(`div`,{className:`row models-field-row`,children:[(0,Q.jsx)(dn,{value:g?fs:m,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:fs,label:o(`models.custom`)}],onChange:e=>{e===`custom`?_(!0):(_(!1),h(e))},disabled:O,label:o(`models.customFieldContext`),portal:!1}),g&&(0,Q.jsx)(`input`,{className:`input`,style:{width:120},inputMode:`numeric`,value:m,onChange:e=>h(e.target.value),disabled:O,placeholder:o(`models.customPlaceholder`),"aria-label":o(`models.customFieldContext`)})]}),e.contextWindowDeclared===void 0&&(0,Q.jsx)(`span`,{className:`muted text-caption`,children:o(`models.settingsContextInherit`,{value:e.contextWindow?String(e.contextWindow):o(`models.settingsContextUnknown`)})})]}),(0,Q.jsxs)(`div`,{className:`text-label models-field`,children:[o(`models.customFieldModalities`),(0,Q.jsx)(`div`,{className:`row models-field-row`,children:fv.map(e=>(0,Q.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:v.includes(e),onChange:t=>{let n=t.target.checked;y(t=>{if(!n)return t.filter(t=>t!==e);let r=t.length>0?t:z;return[...new Set([...r,e])]})},disabled:O}),(0,Q.jsx)(`span`,{className:`text-control`,children:e})]},e))}),v.length===0&&(0,Q.jsx)(`span`,{className:`muted text-caption`,children:o(`models.settingsModalitiesInherit`,{modalities:R||o(`models.settingsModalitiesUnknown`)})})]}),(0,Q.jsxs)(`div`,{className:`text-label models-field`,children:[o(`models.customFieldReasoning`),(0,Q.jsx)(`div`,{className:`row models-field-row`,children:(0,Q.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:b,onChange:e=>j(e.target.checked),disabled:O}),(0,Q.jsx)(`span`,{className:`text-control`,children:o(`models.customFieldReasoningOverride`)})]})}),b&&(0,Q.jsx)(`div`,{className:`row models-field-row`,style:{flexWrap:`wrap`},children:os.map(e=>(0,Q.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:S.includes(e),onChange:t=>N(e,t.target.checked),disabled:O}),(0,Q.jsx)(`span`,{className:`text-control`,children:o(`models.reasoningEffort.`+e)})]},e))})]}),b&&(0,Q.jsxs)(`label`,{className:`text-label models-field`,children:[o(`models.settingsDefaultEffort`),(0,Q.jsx)(`div`,{className:`row models-field-row`,children:(0,Q.jsx)(dn,{value:w,options:[{value:``,label:`—`},...S.map(e=>({value:e,label:o(`models.reasoningEffort.`+e)}))],onChange:T,disabled:O,label:o(`models.settingsDefaultEffort`),portal:!1})})]})]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[k&&(0,Q.jsx)(`button`,{ref:l,type:`button`,className:`btn btn-ghost`,onClick:()=>void A(),children:o(`models.settingsReload`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,title:o(`models.settingsRestoreHint`),disabled:O||k,onClick:()=>void L(),children:o(`models.settingsRestore`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:P,disabled:O,children:o(`common.cancel`)}),(0,Q.jsx)(`button`,{type:`submit`,className:`btn btn-primary`,disabled:O||k,children:o(O?`models.customSaving`:`models.customApply`)})]})]})]})}var bv=[`current`,`stale`,`unknown`,`not_running`],xv=[`fresh`,`stale`,`not_running`,`unknown`],Sv=[`stopped`,`nothing_running`,`enumeration_unavailable`,`partially_stopped`];function Cv(e){return Array.isArray(e)&&e.every(e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>0)}function wv(e){if(typeof e!=`object`||!e)return!1;let t=e;if(!(typeof t.success==`boolean`&&typeof t.synced==`boolean`&&typeof t.stateBefore==`string`&&xv.includes(t.stateBefore)&&typeof t.code==`string`&&Sv.includes(t.code)&&Cv(t.requested)&&Cv(t.stopped)&&Cv(t.surviving)&&Cv(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`||!Cv(n.stopped)||!Cv(n.surviving)||n.relaunch!==`started`&&n.relaunch!==`skipped`||n.reason!==void 0&&typeof n.reason!=`string`||n.pickerState!==void 0&&(typeof n.pickerState!=`string`||!bv.includes(n.pickerState))||n.relaunch===`started`&&n.surviving.length>0)return!1}return!0}function Tv(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.state==`string`&&xv.includes(t.state)&&typeof t.runningCount==`number`&&Number.isSafeInteger(t.runningCount)&&t.runningCount>=0}var Ev={state:null,runningCount:0};async function Dv(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 Ev;let i=await r.json().catch(()=>null);return Tv(i)?{state:i.state,runningCount:i.runningCount}:Ev}catch{return Ev}}var Ov=3e4;function kv(e){return(e instanceof DOMException||e instanceof Error)&&(e.name===`AbortError`||e.name===`TimeoutError`)}async function Av(e,t={}){let{fetchFn:n=fetch,timeoutMs:r=Ov,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:kv(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:kv(e)?s():o()}}return wv(l)?{ok:!0,result:l}:{ok:!1,message:o()}}function jv(e){return e===`stopped`||e===`nothing_running`}function Mv(e,t){let{t:n}=r(),[i,a]=(0,Z.useState)(!1),o=(0,Z.useRef)(!0),s=(0,Z.useRef)(t.onSettled),c=(0,Z.useRef)(t.report),l=(0,Z.useRef)(e),u=(0,Z.useRef)(null);return(0,Z.useEffect)(()=>{s.current=t.onSettled,c.current=t.report},[t.onSettled,t.report]),(0,Z.useEffect)(()=>(l.current=e,()=>{u.current?.abort(),u.current=null}),[e]),(0,Z.useEffect)(()=>(o.current=!0,()=>{o.current=!1,u.current?.abort(),u.current=null}),[]),{restarting:i,restart:(0,Z.useCallback)(async()=>{let t=new AbortController;u.current?.abort(),u.current=t;let r=await ha({message:n(`dash.codexRestartConfirm`),confirmLabel:n(`dash.codexRestart`),tone:`danger`,signal:t.signal});if(u.current===t&&(u.current=null),!r||!o.current||l.current!==e)return null;a(!0);let i=await Av(e,{formatFailure:e=>n(`dash.codexRestartFailed`,{status:String(e)}),formatUnreachable:()=>n(`dash.codexRestartUnreachable`),formatTimeout:()=>n(`dash.codexRestartTimeout`),formatMalformed:()=>n(`dash.codexRestartMalformed`)});if(o.current&&a(!1),!i.ok)return c.current(i.message,`err`),null;let d=i.result;return d.code===`stopped`?c.current(n(`dash.codexRestartDone`,{count:String(d.stopped.length)}),`ok`):d.code===`nothing_running`?c.current(n(`dash.codexRestartNothing`),`ok`):d.code===`enumeration_unavailable`?c.current(n(`dash.codexRestartUnknown`),`warn`):c.current(n(`dash.codexRestartPartial`,{count:String(d.surviving.length)}),`warn`),o.current&&jv(d.code)&&s.current?.(d.code),d.code},[e,n])}}async function Nv(e,t,{apiBase:n,t:r,reloadAliases:i,publishFeedback:a}){let o=await ga({message:r(`models.aliasPrompt`),initialValue:t});o!==null&&((await fetch(`${n}/api/providers/${encodeURIComponent(e)}/alias`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({alias:o.trim()||null})})).ok?(await i(),a(!0,r(`models.aliasSaved`))):a(!1,r(`models.aliasConflict`)))}async function Pv(e,t,n,{apiBase:r,t:i,reloadAliases:a,publishFeedback:o}){let s=await ga({message:i(`models.modelAliasPrompt`),initialValue:n});if(s===null)return;let c=s.trim()?{set:{[t]:s.trim()}}:{remove:[t]};(await fetch(`${r}/api/providers/${encodeURIComponent(e)}/model-aliases`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(c)})).ok?(await a(),o(!0,i(`models.aliasSaved`))):o(!1,i(`models.aliasConflict`))}var Fv={"gpt-5.6-sol":ie,"gpt-5.6-terra":Xe,"gpt-5.6-luna":ve,"gpt-daybreak-blue-latest":ie,"daybreak-blue-latest":ie,"daybreak-red-latest":ct},Iv={width:14,height:14,flexShrink:0,verticalAlign:`text-bottom`};function Lv(e){return e.slice(e.lastIndexOf(`/`)+1)}function Rv(e){return Fv[e]??Fv[Lv(e)]??null}function zv(e){let t=Rv(e);return t?(0,Z.createElement)(`span`,{className:`model-label`},(0,Z.createElement)(t,{style:Iv,"aria-hidden":!0}),e):e}function Bv(e,t){return Object.hasOwn(e,t)?e[t]:void 0}var Vv=new Set([`absent`,`current`,`stale`,`conflict`,`unsafe`]),Hv=new Set([`unparseable`,`not-regular-file`,`foreign-edit`,`unowned-key`,`blocked-container`,`unresolvable-path`]);function Uv(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Wv(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function Gv(e){if(!Uv(e)||e.clientId!==`aside`||!Wv(e.profileId)||typeof e.current!=`boolean`||typeof e.enabled!=`boolean`||!Vv.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&&!Hv.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 Kv(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Uv(n)||!Wv(n.profileId)||typeof n.ok!=`boolean`||n.state!==void 0&&!Vv.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 qv=[`qoder`,`qoder-cn`,`workbuddy`,`workbuddy-ai`,`opencode`,`pi`,`omp`,`hermes`,`openclaw`,`kimi`,`gajae`,`dsh`,`mcode`,`zcode`,`commandcode`,`prime`,`aside`,`raycast`,`omo`,`cline`,`kilo`,`droid`,`gentle-shell`,`t3code`];function Jv(e){return e.clientId===`kilo`&&!!e.lastOpId&&(e.reason===`candidate-conflict`||e.state===`unsafe`&&!!e.candidateFailurePath&&e.candidateFailurePath!==e.configPath)}var Yv=new Set([`not_installed`,`conflict`,`unsafe`,`non_loopback`,`superseded_store`,`drift_requires_confirm`,`snapshot_expired`,`write_failed`]),Xv=new Set([`integration_unsafe`,`integration_conflict`,`integration_drift_confirmation_required`,`integration_snapshot_expired`,`integration_mutation_failed`]),Zv=new Set([`absent`,`current`,`stale`,`conflict`,`unsafe`]),Qv=[`apply`,`overwrite`,`disable`,`restore`],$v=[`add`,`replace`,`remove`,`snapshot`,`ownership`,`journal`],ey=[`none`,`unowned`,`foreign-edit`,`drift`],ty=new Set([`version`,`clientId`,`operation`,`state`,`foreignEdit`,`changes`,`fingerprint`,`canApply`,`willChange`,`refusalReason`,`supersededReason`,`missingStoreDocument`,`profileId`]),ny=new Set([`owned-config-file`,`unestablished-schema`,`missing-store`]),ry=/^[\x20-\x7e]{1,64}$/,iy=new Set([`kind`,`path`]),ay=new Set([`$snapshot`,`$ownership`,`$journal`]),oy=new Set([`*`,`provider.opencodex`,`providers.opencodex`,`models.providers.opencodex`,`models.*`,`modelConfigs.customModels.*`,`providerInstances.opencodex`,`llm-pi-ai.providers.opencodex`,`custom_provider.opencodex`,`providers.[id=opencodex]`,`settings.providers.opencodex`,`catalog.providers.opencodex`,`customModels.*`,`config.providerConfigRules.providerRules.[providerId=opencodex]`,`config.modelConfigRules.providerModelRules.*`,`[id=llm-pi-ai].config.providers.opencodex`]),sy=256;function cy(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ly(e,t){return Object.keys(e).every(e=>t.has(e))}function uy(e){return ay.has(e)||oy.has(e)}function dy(){return new my(502,{code:`invalid_integration_preview_response`})}function fy(e){if(!cy(e)||!ly(e,ty)||e.version!==1||!qv.includes(e.clientId)||!Qv.includes(e.operation)||!Zv.has(String(e.state))||!ey.includes(e.foreignEdit)||typeof e.fingerprint!=`string`||!/^p[0-9]+:(?:[0-9a-f]{32}|unbound)$/.test(e.fingerprint)||typeof e.canApply!=`boolean`||typeof e.willChange!=`boolean`||!Array.isArray(e.changes)||e.changes.length>sy||e.profileId!==void 0&&(typeof e.profileId!=`number`||!Number.isSafeInteger(e.profileId)||e.profileId<0)||e.profileId!==void 0&&e.clientId!==`aside`||e.refusalReason!==void 0&&!Yv.has(String(e.refusalReason))||e.supersededReason!==void 0&&(e.refusalReason!==`superseded_store`||typeof e.supersededReason!=`string`||!ny.has(e.supersededReason))||e.missingStoreDocument!==void 0&&(e.supersededReason!==`missing-store`||typeof e.missingStoreDocument!=`string`||!ry.test(e.missingStoreDocument)))throw dy();let t=[],n=-1,r=``,i=new Map;for(let a of e.changes){if(!cy(a)||!ly(a,iy)||!$v.includes(a.kind)||typeof a.path!=`string`||!uy(a.path))throw dy();let e=$v.indexOf(a.kind);if(e<n||e===n&&a.path<=r)throw dy();let o=a.kind,s=i.get(o)??new Set;if(s.has(a.path))throw dy();s.add(a.path),i.set(o,s),n=e,r=a.path,t.push({kind:o,path:a.path})}if(e.willChange&&(!e.canApply||t.length===0)||!e.willChange&&t.length!==0||e.fingerprint.endsWith(`:unbound`)&&e.canApply||e.canApply===(e.refusalReason!==void 0))throw dy();return{version:1,clientId:e.clientId,operation:e.operation,state:e.state,foreignEdit:e.foreignEdit,changes:t,fingerprint:e.fingerprint,canApply:e.canApply,willChange:e.willChange,...e.refusalReason===void 0?{}:{refusalReason:e.refusalReason},...e.supersededReason===void 0?{}:{supersededReason:e.supersededReason},...e.missingStoreDocument===void 0?{}:{missingStoreDocument:e.missingStoreDocument},...e.profileId===void 0?{}:{profileId:Number(e.profileId)}}}function py(e){return!cy(e)||!Yv.has(String(e.reason))?!1:typeof e.error==`string`&&Xv.has(String(e.code))&&qv.includes(e.clientId)&&Zv.has(String(e.state))&&typeof e.message==`string`}var my=class extends Error{refusal;status;body;stalePlan;constructor(e,t){let n=py(t)?t:null;super(n?.message??t.error??t.message??String(e)),this.name=`IntegrationApiError`,this.status=e,this.body=t,this.refusal=n,this.stalePlan=t.code===`integration_preview_stale`&&`plan`in t&&t.plan?t.plan:null}};function hy(e){return e instanceof my&&e.status===404&&e.body.code===`integration_operation_not_found`}async function gy(e){let t;try{t=await e.json()}catch{return{}}return cy(t)?t.code===`integration_preview_stale`?{code:t.code,plan:fy(t.plan)}:t:{}}async function _y(e){if(!e.ok)throw new my(e.status,await gy(e));let t=await yn(e);if(t==null)throw new my(e.status,{});return t}function vy(e){return e instanceof my&&e.body.code===`integration_preview_unavailable`}function yy(e){return{operation:e.operation,planFingerprint:e.fingerprint}}function by(e){if(!Number.isSafeInteger(e)||e<0)throw new my(400,{code:`invalid_aside_profile`});return`/api/client-integrations/aside/profiles/${e}`}function xy(e,t){if(t!==void 0){if(e!==`aside`)throw new my(400,{code:`invalid_aside_profile`});return by(t)}return e===`aside`?`/api/client-integrations/aside/profiles`:`/api/client-integrations/${encodeURIComponent(e)}`}function Sy(e,t){if(e===void 0)return``;let n=`profile=${encodeURIComponent(e)}`;return t?`client=hermes&${n}`:n}function Cy(e,t){return t?`${e}${e.includes(`?`)?`&`:`?`}${t}`:e}function wy(){return new my(502,{code:`invalid_hermes_profile_response`})}async function Ty(e,t){return _y(await fetch(`${e}/api/client-integrations`,{signal:t}))}async function Ey(e,t,n,r,i){let a=await _y(await fetch(`${e}${Cy(xy(t,r),Sy(i,!1))}`,{signal:n}));if(i!==void 0&&(t!==`hermes`||a.hermesProfile!==i))throw wy();if(r!==void 0){let e=Gv(a);if(!e||e.profileId!==r)throw new my(502,{code:`invalid_aside_profile_response`});return e}return a}async function Dy(e,t,n,r,i){if(r!==void 0&&t!==`aside`)throw new my(400,{code:`invalid_aside_profile`});if(i!==void 0&&t!==`hermes`)throw new my(400,{code:`invalid_hermes_profile`});let a=t===`aside`?`${xy(t,r)}/journal`:Cy(`/api/client-integrations/journal${t?`?client=${encodeURIComponent(t)}`:``}`,Sy(i,!1)),o=await _y(await fetch(`${e}${a}`,{signal:n}));if(r!==void 0&&(!Array.isArray(o.operations)||o.operations.some(e=>e.clientId!==`aside`||e.profileId!==r)))throw new my(502,{code:`invalid_aside_profile_response`});return o}async function Oy(e,t,n,r,i,a,o){let s=i===void 0?Cy(`/api/client-integrations/preview`,Sy(o,!0)):`${by(i)}/preview`,c={...i===void 0?{clientId:t}:{},operation:n,...t===`droid`&&a!==void 0?{droidReasoningDefaults:a}:{}},l=fy(await _y(await fetch(`${e}${s}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(c),signal:r})));if(l.clientId!==t||l.operation!==n||l.profileId!==i)throw dy();return l}async function ky(e,t,n=!1,r,i,a){let o=i===void 0?Cy(`/api/client-integrations/restore/preview`,Sy(a,!0)):`${by(i)}/preview`,s=i===void 0?{opId:t,confirmDrift:n}:{operation:`restore`,opId:t,confirmDrift:n},c=fy(await _y(await fetch(`${e}${o}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(s),signal:r})));if(c.operation!==`restore`||c.profileId!==i)throw dy();return c}async function Ay(e,t,n){let{enabled:r,signal:i,overwriteConflict:a,profileId:o,binding:s,droidReasoningDefaults:c,hermesProfile:l}=n;if(l!==void 0&&t!==`hermes`)throw new my(400,{code:`invalid_hermes_profile`});let u=r?a?`overwrite`:`apply`:`disable`,d;try{d=await _y(await fetch(`${e}${Cy(xy(t,o),Sy(l,!1))}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({enabled:r,...a===!0?{overwriteConflict:!0}:{},...s,...t===`droid`&&c!==void 0?{droidReasoningDefaults:c}:{}}),signal:i}))}catch(e){throw e instanceof my&&e.stalePlan&&(e.stalePlan.clientId!==t||e.stalePlan.operation!==u||e.stalePlan.profileId!==o)?dy():e}let f=d.results===void 0?void 0:Kv(d.results);if(t===`aside`&&d.results!==void 0&&(!f||d.ok!==f.every(e=>e.ok)))throw new my(502,{code:`invalid_aside_profile_response`});if(d.ok!==!0)throw new my(207,{code:t===`aside`?`aside_profile_partial`:`integration_mutation_failed`,message:d.message,results:f??void 0});if(o!==void 0&&d.profileId!==o)throw new my(502,{code:`invalid_aside_profile_response`});return{...d,...f?{results:f}:{}}}async function jy(e,t){let{opId:n,confirmDrift:r=!1,signal:i,profileId:a,binding:o,hermesProfile:s}=t,c;try{c=await _y(await fetch(`${e}${a===void 0?Cy(`/api/client-integrations/restore`,Sy(s,!0)):`${by(a)}/restore`}`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({opId:n,confirmDrift:r,...o}),signal:i}))}catch(e){throw e instanceof my&&e.stalePlan&&(e.stalePlan.operation!==`restore`||e.stalePlan.profileId!==a)?dy():e}if(a!==void 0&&c.profileId!==a)throw new my(502,{code:`invalid_aside_profile_response`});return c}async function My(e,t,n,r,i){let a=await _y(await fetch(`${e}${Cy(r===void 0?`/api/client-integrations/journal`:`${by(r)}/journal`,Sy(i,!0))}${i===void 0?`?`:`&`}opId=${encodeURIComponent(t)}`,{method:`DELETE`,signal:n}));if(r!==void 0&&a.profileId!==r)throw new my(502,{code:`invalid_aside_profile_response`});return a}async function Ny(e){try{let t=await e;return t.ok?await yn(t)??null:null}catch{return null}}async function Py(e,t){let n=await Ny(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 Fy(e,t){let n=await fetch(`${e}/api/keys`,{signal:t});if(!n.ok)throw Error(`/api/keys responded ${n.status}`);let r=await yn(n);if(!r||!Array.isArray(r.keys))throw Error(`/api/keys returned an unexpected body`);return r.keys.length}async function Iy(e,t){let n=await Ny(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 Ly(e,t){let n=await Ny(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 Ry(e,t){let n=await Ny(fetch(`${e}/api/grok`,{signal:t}));return n?{present:n.present===!0,models:Array.isArray(n.models)?n.models:[]}:null}var zy=new Set([`claude`,`grok`,`codex`,`claude-desktop`]),By=new Set([`native_integration_refused`,`native_integration_failed`]),Vy=new Set([`not_installed`,`orphaned_marker`,`home_mismatch`,`config_busy`,`write_failed`,`metadata_unreadable`,`cleanup_incomplete`,`desired_state_changed`]);function Hy(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Uy(e){return Hy(e)?typeof e.error==`string`&&By.has(String(e.code))&&zy.has(String(e.clientId))&&Vy.has(String(e.reason))&&typeof e.message==`string`:!1}var Wy=class extends Error{refusal;status;body;constructor(e,t){let n=Uy(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 Gy(e){try{let t=await e;return t.ok?await yn(t)??null:null}catch{return null}}async function Ky(e){try{let t=await e.json();return Hy(t)?t:{}}catch{return{}}}async function qy(e){if(!e.ok)throw new Wy(e.status,await Ky(e));let t=await yn(e);if(t==null)throw new Wy(e.status,{});return t}function Jy(e,t){return Gy(fetch(`${e}/api/native-integrations`,{signal:t}))}async function Yy(e,t,n,r){return qy(await fetch(`${e}/api/native-integrations/${encodeURIComponent(t)}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({enabled:n}),signal:r}))}var Xy={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 Zy(e){return e instanceof my?e.refusal:null}function Qy(e){return e instanceof Wy?e.refusal:null}function $y(e){return e===`conflict`?`integrations.error.conflict`:e===`unsafe`?`integrations.error.unsafe`:e===`non_loopback`?`integrations.error.nonLoopback`:`integrations.error.generic`}var eb=new Set([`non_loopback`]);function tb(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 nb(e,t,n,r){let i=Qy(t);if(i)return tb(e,i,r);let a=Zy(t);if(!a){if(t instanceof my&&`results`in t.body&&t.body.results?.length){let n=t.body.results.filter(e=>!e.ok).map(t=>{let n=rb(e,t);return`${e(`integrations.aside.profile`,{id:String(t.profileId)})}: ${n}`});return[e(`integrations.aside.partial`),...n].join(`
6
6
  `)}let r=Xy[t instanceof my?String(t.body.code??``):``];return r?e(r):t instanceof Error&&t.message?t.message:n??e(`integrations.error.generic`)}return ib(e,a)}function rb(e,t){return ib(e,{clientId:`aside`,message:t.message??t.reason,reason:t.refusalReason??t.reason,snapshotPath:t.snapshotPath,residual:t.residual})}function ib(e,t){let n=eb.has(t.reason??``)?e($y(t.reason),{client:t.clientId}):t.message||e($y(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($y(t.reason))} ${n}`:n}var ab=(e,t,n)=>JSON.stringify([e,t,n]),ob=new Map;function sb(e,t){let[n,r]=(0,Z.useState)({apiBase:e,overrides:ob,pending:!1});n.apiBase!==e&&r({apiBase:e,overrides:ob,pending:!1});let i=n.apiBase===e?n.overrides:ob,a=n.apiBase===e&&n.pending,o=(0,Z.useRef)(t);(0,Z.useLayoutEffect)(()=>{o.current=t});let s=(0,Z.useRef)(null);(0,Z.useLayoutEffect)(()=>{let e={active:!0,running:!1,queue:[],readVersion:0,bounded:null};return s.current=e,o.current.onBusy(!1),()=>{e.active=!1,e.queue.length=0,e.bounded?.controller.abort(),e.bounded?.clear()}},[e]);let c=async t=>{let n=null;for(;t.active;){for(;t.active&&t.queue.length>0;){let r=t.queue.shift(),i=M(6e4);t.bounded=i;try{let a=await Qo(e,r.scope,r.provider,r.targets,r.enabled,fetch,i.signal);if(t.active){if(!a.ok)n=`models.saveFailed`;else{let e=await a.json().catch(()=>void 0);t.active&&o.current.onResponse(e)}}}catch{if(!t.active)return;n=`models.networkError`}finally{i.clear(),t.bounded=null}}if(!t.active)return;let i=t.readVersion,a=!1,s=M(6e4);t.bounded=s;try{a=await o.current.refresh(s.signal)}catch{}finally{s.clear(),t.bounded=null}if(!t.active)return;if(!(t.queue.length||i!==t.readVersion)){t.running=!1,r({apiBase:e,overrides:ob,pending:!1}),o.current.onBusy(!1),o.current.onSettled(n??(a?null:`models.networkError`));return}}};return{pending:a,overrides:i,enqueue:(t,n,i,a)=>{let l=s.current;l?.active&&(l.queue.push({scope:t,provider:n,targets:i,enabled:a}),l.readVersion++,o.current.onQueued(),r(t=>{let r=new Map(t.apiBase===e?t.overrides:ob);for(let e of i)r.set(ab(n,e.id,e.native===!0),a);return{apiBase:e,overrides:r,pending:!0}}),l.running||(l.running=!0,o.current.onBusy(!0),c(l)))},isRunning:()=>s.current?.running===!0,visible:(e,t,n,r)=>i.get(ab(e,t,n))??r}}function cb({className:e,style:t}){return(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:e?`data-surface-skeleton__block ${e}`:`data-surface-skeleton__block`,style:t})}function lb({label:e,rows:t=3,className:n}){let r=Math.max(1,Math.floor(t));return(0,Q.jsxs)(`div`,{className:n?`data-surface-skeleton ${n}`:`data-surface-skeleton`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,"aria-busy":`true`,children:[(0,Q.jsx)(`span`,{className:`sr-only`,children:e}),Array.from({length:r},(e,t)=>(0,Q.jsx)(`div`,{className:`data-surface-skeleton__row`,"aria-hidden":`true`,children:(0,Q.jsx)(cb,{})},t))]})}function ub({children:e,busy:t=!0,live:n=!0,className:r}){return(0,Q.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,Q.jsx)(`span`,{className:`spin`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{children:e})]})}var db=class extends Z.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,Q.jsxs)(`section`,{className:`card`,role:`alert`,style:{maxWidth:720,padding:`var(--space-6)`},children:[(0,Q.jsxs)(`h2`,{style:{margin:`0 0 var(--space-2)`,fontSize:`var(--text-title)`},children:[this.props.pageName,`: `,this.props.title]}),(0,Q.jsx)(`p`,{className:`muted`,style:{margin:`0 0 var(--space-4)`},children:this.props.message}),(0,Q.jsxs)(`p`,{style:{margin:`0 0 var(--space-5)`,overflowWrap:`anywhere`},children:[(0,Q.jsxs)(`strong`,{children:[this.props.detailsLabel,`:`]}),` `,this.state.error.message]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:this.reload,children:this.props.reloadLabel})]}):this.props.children}};function fb(e,t){let n=e.provider.trim(),r=e.model.trim();if(!n||!r)return`missing`;let i=t.find(e=>e.provider===n&&e.id===r);if(!i)return`missing`;if(i.visionSidecarConsumer===!0)return`sidecar`;let a=i.inputModalitiesDeclared??i.inputModalities;return!a||a.length===0?`blocked`:a.includes(`image`)?`vision`:a.includes(`text`)?`sidecar`:`blocked`}function pb(e,t){return e.length!==0&&e.every(e=>{let n=fb(e,t);return n===`vision`||n===`sidecar`})}function mb(e,t){if(!pb(e,t))return[];let n=new Set,r=[];for(let i of e){if(fb(i,t)!==`sidecar`)continue;let e=i.provider.trim(),a=i.model.trim(),o=`${e}/${a}`;n.has(o)||(n.add(o),r.push({provider:e,model:a}))}return r}function hb(e,t){return e.filter(e=>fb(e,t)===`blocked`).map(e=>({provider:e.provider.trim(),model:e.model.trim()}))}function gb(e,t,n,r){if(t===`invalidSessionPin`)return e(`cws.err.invalidSessionPin`,{min:zr,max:Br});if(t===`invalidDecisionTimeout`)return e(`cws.err.invalidDecisionTimeout`,{min:Hr,max:Ur});if(t===`invalidDecisionProvider`){let t=Wi(n.decisionProvider,r)??`missing`;return e(`cws.err.invalidDecisionProvider`,{name:n.decisionProvider??``,reason:e(ii[t])})}return e(`cws.err.${t}`)}function _b(e){return e.filter(e=>!e.disabled&&!e.hiddenFromPicker).sort((e,t)=>e.name.localeCompare(t.name))}function vb(e,t,n){if(e===``)return;let r=Number(e);if(Number.isFinite(r))return Math.min(n,Math.max(t,r))}function yb(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 bb(e,t,n){let r=new Set([t]),i=n.find(e=>e.name===t);(t.toLowerCase()===`chatgpt`||yb(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 xb({value:e,onChange:t,disabled:r}){let i=n();return(0,Q.jsx)(`div`,{className:`cwi-strategy-seg`,role:`radiogroup`,"aria-label":i(`cws.strategy`),children:$r.map(n=>(0,Q.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":e===n,className:`btn btn-sm${e===n?` btn-primary`:` btn-ghost`}`,disabled:r,onClick:()=>t(n),children:i(ei[n])},n))})}function Sb({id:e,value:t,onChange:r,disabled:i,allowedEfforts:a}){let o=n(),s=a??Qr,c=t!==null&&!s.includes(t);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`select`,{id:e,className:`input`,value:t??``,disabled:i,"aria-label":o(`cws.field.defaultEffort`),onChange:e=>r(e.target.value===``?null:e.target.value),children:[(0,Q.jsx)(`option`,{value:``,children:o(`cws.field.defaultEffortNone`)}),c&&t?(0,Q.jsxs)(`option`,{value:t,children:[t,` (`,o(`cws.field.defaultEffortUnsupportedOption`),`)`]}):null,s.map(e=>(0,Q.jsx)(`option`,{value:e,children:e},e))]}),c?(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`,color:`var(--danger, #b42318)`},children:o(`cws.field.defaultEffortUnsupported`)}):null]})}function Cb({targets:e,models:t,imageInput:r,reasoningEffortMode:i,visionEnabled:a,disabled:o,onChange:s}){let c=n(),l=pb(e,t),u=hb(e,t),d=l&&r!==`disabled`,f=mb(e,t),p=l?f.length>0&&r!==`disabled`?c(`cws.capability.imageInputSidecarHint`,{models:f.map(({provider:e,model:t})=>`${e}/${t}`).join(`, `)}):c(`cws.capability.imageInputHint`):u.length>0?c(`cws.capability.imageInputBlockedHint`,{models:u.map(({provider:e,model:t})=>`${e}/${t}`).join(`, `)}):c(`cws.capability.imageInputUnavailable`);return(0,Q.jsxs)(`section`,{className:`cwi-capabilities`,"aria-label":c(`cws.capabilities`),children:[(0,Q.jsx)(`span`,{className:`field-label`,children:c(`cws.capabilities`)}),(0,Q.jsxs)(`div`,{className:`cwi-capability-row`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`span`,{className:`cwi-capability-label`,children:c(`cws.capability.imageInput`)}),(0,Q.jsx)(`p`,{className:`muted cwi-capability-hint`,children:p}),f.length>0&&d&&a===!1?(0,Q.jsxs)(`p`,{className:`cwi-capability-hint cwi-capability-hint--warn`,children:[c(`cws.capability.imageInputSidecarDisabled`,{models:f.map(({provider:e,model:t})=>`${e}/${t}`).join(`, `)}),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>Xt(`dashboard`),children:c(`nav.dashboard`)})]}):null]}),(0,Q.jsx)(ln,{on:d,onClick:()=>{l&&s({imageInput:r===`auto`?`disabled`:`auto`})},disabled:o||!l,label:c(`cws.capability.imageInput`)})]}),(0,Q.jsxs)(`div`,{className:`cwi-capability-row`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`span`,{className:`cwi-capability-label`,children:c(`cws.capability.adaptiveEffort`)}),(0,Q.jsx)(`p`,{className:`muted cwi-capability-hint`,children:c(`cws.capability.adaptiveEffortHint`)})]}),(0,Q.jsx)(ln,{on:i===`adaptive`,onClick:()=>{s({reasoningEffortMode:i===`adaptive`?`strict`:`adaptive`})},disabled:o,label:c(`cws.capability.adaptiveEffort`)})]})]})}function wb({targets:e,strategy:t,providers:r,models:i,capabilityModels:a=i,providerQuotaStates:o,onChange:s}){let c=n(),l=_b(r),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)(null),m=t===`jev`?e.findIndex(e=>{let t=r.find(t=>t.name===e.provider.trim());return!!e.provider.trim()&&!!e.model.trim()&&t!==void 0&&t.disabled!==!0&&t.adapter!==`jev-decision`&&o[e.provider.trim()]!==`exhausted`}):-1,h=(t,n)=>{s(e.map((e,r)=>r===t?{...e,...n}:e))},g=(t,n)=>{s(e.map((e,r)=>{if(r!==t)return e;let{reasoningEfforts:i,modelProfile:a,...o}=e;return{...o,...n}}))},_=(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),s(r)};return(0,Q.jsxs)(`div`,{className:`cwi-target-list`,children:[e.map((n,v)=>{let y=r.find(e=>e.name===n.provider),b=y&&!l.some(e=>e.name===n.provider)?[...l,y]:l,x=bb(i,n.provider,r),S=n.model&&!x.includes(n.model)?[n.model,...x]:x,C=!n.provider,w=u===v,T=f===v&&u!==null&&u!==v,E=o[n.provider.trim()]??`unknown`,D=a.find(e=>e.provider===n.provider&&e.id===n.model)?.reasoningEfforts,O=D===void 0?void 0:new Set(D),k=O===void 0?void 0:Qr.filter(e=>O.has(e)),A=new Set(k??[]),j=k===void 0?[]:n.reasoningEfforts===void 0?k:n.reasoningEfforts.filter(e=>A.has(e)),M=new Set(j);return(0,Q.jsxs)(`div`,{className:`cwi-target-entry`,children:[(0,Q.jsxs)(`div`,{className:[`cwi-target-row`,t===`failover`||t===`jev`?`cwi-target-row--failover`:``,w?`cwi-target-row--dragging`:``,T?`cwi-target-row--drop`:``].filter(Boolean).join(` `),onDragOver:e=>{u!==null&&(e.preventDefault(),e.dataTransfer.dropEffect=`move`,f!==v&&p(v))},onDrop:e=>{e.preventDefault(),u!==null&&_(u,v),d(null),p(null)},onDragEnd:()=>{d(null),p(null)},children:[(0,Q.jsx)(`button`,{type:`button`,className:`cwi-target-grip`,draggable:!0,"aria-label":c(`cws.target.drag`),title:c(`cws.target.drag`),onDragStart:e=>{d(v),e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,String(v))},children:(0,Q.jsx)(Re,{width:14,height:14,"aria-hidden":`true`})}),(0,Q.jsxs)(`div`,{className:`cwi-target-reorder`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:v===0,"aria-label":c(`cws.target.moveUp`),onClick:()=>_(v,v-1),children:(0,Q.jsx)(Je,{width:14,height:14,"aria-hidden":`true`})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:v===e.length-1,"aria-label":c(`cws.target.moveDown`),onClick:()=>_(v,v+1),children:(0,Q.jsx)(tt,{width:14,height:14,"aria-hidden":`true`})})]}),(0,Q.jsxs)(`select`,{className:`input`,value:n.provider,"aria-label":c(`cws.target.provider`),onChange:e=>{let t=e.target.value,n=bb(i,t,r)[0]??``;g(v,{provider:t,model:n})},children:[(0,Q.jsx)(`option`,{value:``,children:c(`cws.target.pickProvider`)}),b.map(e=>(0,Q.jsx)(`option`,{value:e.name,children:e.disabled?c(`cws.target.disabled`,{name:Ce(e.name,c)}):Ce(e.name,c)},e.name))]}),(0,Q.jsxs)(`select`,{className:`input`,value:n.model,disabled:C,"aria-label":c(`cws.target.model`),onChange:e=>g(v,{provider:n.provider,model:e.target.value}),children:[(0,Q.jsx)(`option`,{value:``,children:C?c(`cws.target.pickProviderFirst`):S.length===0?c(`cws.target.noModels`):c(`cws.target.pickModel`)}),S.map(e=>(0,Q.jsx)(`option`,{value:e,children:e},e))]}),(t===`round-robin`||t===`random`)&&(0,Q.jsx)(`input`,{className:`input mono`,type:`number`,min:1,max:1e4,value:n.weight??1,"aria-label":c(`cws.target.weight`),onChange:e=>{let t=vb(e.target.value,1,1e4);t!==void 0&&h(v,{weight:t})}}),(0,Q.jsx)(`span`,{className:`cwi-quota-badge cwi-quota-badge--${E}`,"aria-label":c(`cws.quota.${E}`),children:c(`cws.quota.${E}`)}),(0,Q.jsx)(`div`,{className:`cwi-target-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:e.length<=1,onClick:()=>s(e.filter((e,t)=>t!==v)),"aria-label":c(`common.remove`),children:(0,Q.jsx)(R,{width:14,height:14})})})]}),t===`jev`&&(0,Q.jsxs)(`div`,{className:`cwi-jev-target-meta`,children:[v===m&&(0,Q.jsx)(`span`,{className:`chip`,children:c(`cws.jev.failOpen`)}),k===void 0?(0,Q.jsx)(`span`,{className:`muted`,children:c(`cws.jev.effortsUnknown`)}):k.length===0?(0,Q.jsx)(`span`,{className:`muted`,children:c(`cws.jev.effortsNone`)}):(0,Q.jsxs)(`fieldset`,{className:`cwi-jev-efforts`,children:[(0,Q.jsx)(`legend`,{children:c(`cws.jev.allowedEfforts`)}),k.map(e=>{let t=M.has(e);return(0,Q.jsxs)(`label`,{className:`cwi-jev-effort`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,"data-jev-effort":!0,value:e,checked:t,disabled:t&&j.length===1,onChange:t=>{let n=new Set(j);t.target.checked?n.add(e):n.delete(e),h(v,{reasoningEfforts:k.filter(e=>n.has(e))})}}),(0,Q.jsx)(`span`,{children:e})]},e)})]}),(0,Q.jsxs)(`label`,{className:`cwi-field`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:c(`cws.jev.modelProfile`)}),(0,Q.jsx)(`textarea`,{className:`input`,rows:3,maxLength:512,value:n.modelProfile??``,placeholder:c(`cws.jev.modelProfilePlaceholder`),onChange:e=>h(v,{modelProfile:e.target.value})}),(0,Q.jsx)(`span`,{className:`muted`,children:c(`cws.jev.modelProfileHint`)})]})]})]},n.clientKey??`${n.provider}:${n.model}`)}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{alignSelf:`flex-start`},onClick:()=>s([...e,ci()]),children:[(0,Q.jsx)(I,{width:14,height:14}),` `,c(`cws.target.add`)]})]})}var Tb=[`typesafe`,`systemone`,`model`],Eb={typesafe:`cws.jev.method.typesafe`,systemone:`cws.jev.method.systemone`,model:`cws.jev.method.model`};function Db({idPrefix:e,apiBase:t,combo:r,combos:i,providers:a,models:o,decisionProvider:s,decisionModel:c,decisionTimeoutMs:l,sessionPin:u,disabled:d,onChange:f}){let p=n(),m=Yr({decisionProvider:s,decisionModel:c}),h=u!=null&&!Vr(u),g=(0,Z.useMemo)(()=>Gi(a,s).filter(e=>e.id!==null),[a,s]),_=g.find(e=>e.id===s?.trim()),{id:v,alias:y,model:b}=r,x=(0,Z.useMemo)(()=>Zr(o,a,i,{id:v,alias:y,model:b}),[o,a,i,v,y,b]),[S,C]=(0,Z.useState)(null),w=(0,Z.useRef)(null),T=`${m}\0${s??``}\0${c??``}\0${l??``}`,E=S?.key===T?S.result:null,D=e+`-decision-model-options`;(0,Z.useEffect)(()=>()=>{w.current?.abort(),w.current=null},[T]);let O=e=>{e!==m&&f(e===`typesafe`?{decisionProvider:null,decisionModel:null}:e===`systemone`?{decisionProvider:g.find(e=>!e.issue)?.id??g[0]?.id??``,decisionModel:null}:{decisionProvider:null,decisionModel:x[0]??``})},k=m===`typesafe`||m===`systemone`&&!!_&&!_.issue||m===`model`&&!!c?.trim(),A=async()=>{w.current?.abort();let e=new AbortController;w.current=e;let n=T,i=e=>C({key:n,result:e});i({state:`running`});try{let n=await fetch(`${t??``}/api/combos/decision-test`,{method:`POST`,headers:{"content-type":`application/json`},signal:e.signal,body:JSON.stringify({...r.id.trim()?{comboId:r.id.trim()}:{},...m===`systemone`&&s?{decisionProvider:s.trim()}:{},...m===`model`&&c?{decisionModel:c.trim()}:{},...l===null?{}:{decisionTimeoutMs:l}})});if(!n.ok){let t=await n.json().catch(()=>null);if(e.signal.aborted)return;i({state:`error`,message:t&&typeof t.error==`string`?t.error:String(n.status)});return}let a=await n.json().catch(()=>null);if(e.signal.aborted)return;if(!a||typeof a.gate!=`string`){i({state:`error`,message:String(n.status)});return}i({state:`done`,ok:a.ok===!0,backend:typeof a.backend==`string`?a.backend:`unknown`,gate:a.gate,latencyMs:typeof a.latencyMs==`number`?Math.round(a.latencyMs):0})}catch(t){if(e.signal.aborted)return;i({state:`error`,message:t instanceof Error?t.message:String(t)})}finally{w.current===e&&(w.current=null)}};return(0,Q.jsxs)(`fieldset`,{className:`cwi-field cwi-jev-decision`,"aria-describedby":`${e}-decision-method-hint`,children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:p(`cws.jev.decisionMethod`)}),(0,Q.jsx)(`div`,{className:`segmented`,role:`group`,"aria-label":p(`cws.jev.decisionMethod`),children:Tb.map(t=>(0,Q.jsx)(`button`,{type:`button`,id:`${e}-decision-method-${t}`,className:`btn btn-sm ${m===t?`btn-primary`:`btn-ghost`}`,"aria-pressed":m===t,disabled:d,onClick:()=>O(t),children:p(Eb[t])},t))}),(0,Q.jsxs)(`p`,{id:`${e}-decision-method-hint`,className:`muted`,style:{fontSize:12,margin:`8px 0 0`,overflowWrap:`anywhere`},children:[m===`typesafe`&&p(`cws.jev.decisionServiceDefaultHint`),m===`systemone`&&g.length===0&&p(`cws.jev.method.systemoneEmpty`)]}),m===`systemone`&&g.length>0&&(0,Q.jsxs)(`div`,{className:`cwi-field`,style:{marginTop:8},children:[(0,Q.jsx)(`label`,{htmlFor:`${e}-decision-provider`,children:p(`cws.jev.decisionService`)}),(0,Q.jsxs)(`select`,{id:`${e}-decision-provider`,className:`input`,value:s?.trim()??``,disabled:d,"aria-describedby":_?.issue?`${e}-decision-provider-hint ${e}-decision-provider-issue`:`${e}-decision-provider-hint`,"aria-invalid":_?.issue?!0:void 0,onChange:e=>f({decisionProvider:e.target.value,decisionModel:null}),children:[!_&&(0,Q.jsx)(`option`,{value:``,disabled:!0,children:`—`}),g.map(e=>(0,Q.jsx)(`option`,{value:e.id,disabled:e.issue!==void 0&&e.id!==_?.id,children:e.issue?`${e.id} (${p(ii[e.issue])})`:e.id},e.id))]}),(0,Q.jsxs)(`p`,{id:`${e}-decision-provider-hint`,className:`muted`,style:{fontSize:12,margin:`8px 0 0`,overflowWrap:`anywhere`},children:[p(`cws.jev.decisionServiceHint`),_?.baseUrl&&(0,Q.jsxs)(Q.Fragment,{children:[` `,(0,Q.jsx)(`code`,{children:_.baseUrl})]})]}),_?.issue&&(0,Q.jsx)(`p`,{id:`${e}-decision-provider-issue`,className:`muted`,style:{fontSize:12,margin:`4px 0 0`,color:`var(--danger, #b42318)`},children:p(`cws.err.invalidDecisionProvider`,{name:_.id??``,reason:p(ii[_.issue])})})]}),m===`model`&&(0,Q.jsxs)(`div`,{className:`cwi-field`,style:{marginTop:8},children:[(0,Q.jsx)(`label`,{htmlFor:`${e}-decision-model`,children:p(`cws.jev.decisionModel`)}),(0,Q.jsx)(`input`,{id:`${e}-decision-model`,className:`input mono`,list:D,value:c??``,maxLength:512,spellCheck:!1,autoComplete:`off`,placeholder:`ollama/qwen3:4b`,disabled:d,"aria-describedby":`${e}-decision-model-hint`,onChange:e=>f({decisionModel:e.target.value,decisionProvider:null})}),(0,Q.jsx)(`datalist`,{id:D,children:x.map(e=>(0,Q.jsx)(`option`,{value:e},e))}),(0,Q.jsx)(`p`,{id:`${e}-decision-model-hint`,className:`muted`,style:{fontSize:12,margin:`8px 0 0`,overflowWrap:`anywhere`},children:p(`cws.jev.decisionModelHint`)})]}),(0,Q.jsxs)(`div`,{className:`cwi-field`,style:{marginTop:8},children:[(0,Q.jsx)(`label`,{htmlFor:`${e}-decision-timeout`,children:p(`cws.jev.decisionTimeout`)}),(0,Q.jsx)(`input`,{id:`${e}-decision-timeout`,className:`input mono`,type:`number`,inputMode:`numeric`,min:Hr,max:Ur,step:1,placeholder:String(Wr),value:l??``,disabled:d,"aria-describedby":`${e}-decision-timeout-hint`,onChange:e=>{if(e.target.value===``){f({decisionTimeoutMs:null});return}let t=Number(e.target.value);Number.isFinite(t)&&f({decisionTimeoutMs:t})}}),(0,Q.jsx)(`p`,{id:`${e}-decision-timeout-hint`,className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:p(`cws.jev.decisionTimeoutHint`,{default:Wr,min:Hr,max:Ur})})]}),(0,Q.jsxs)(`div`,{className:`cwi-field`,style:{marginTop:8},children:[(0,Q.jsxs)(`label`,{htmlFor:`${e}-session-pin`,children:[(0,Q.jsx)(`input`,{id:`${e}-session-pin`,type:`checkbox`,checked:u!=null,disabled:d,"aria-describedby":`${e}-session-pin-hint`,onChange:e=>f({sessionPin:e.target.checked?{ttlMs:zr}:null})}),` `,p(`cws.jev.sessionPin`)]}),(0,Q.jsx)(`p`,{id:`${e}-session-pin-hint`,className:`muted text-label`,children:p(`cws.jev.sessionPinHint`,{min:zr,max:Br})}),u!=null&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`label`,{htmlFor:`${e}-session-pin-ttl`,children:p(`cws.jev.sessionPinTtl`)}),(0,Q.jsx)(`input`,{id:`${e}-session-pin-ttl`,className:`input mono`,type:`number`,inputMode:`numeric`,min:6e4,max:864e5,step:1,value:u.ttlMs||``,disabled:d,"aria-invalid":h||void 0,"aria-describedby":h?`${e}-session-pin-hint ${e}-session-pin-error`:`${e}-session-pin-hint`,onChange:e=>{if(e.target.value===``){f({sessionPin:{ttlMs:0}});return}let t=Number(e.target.value);f({sessionPin:{ttlMs:Number.isFinite(t)?t:0}})}}),h&&(0,Q.jsx)(`p`,{id:`${e}-session-pin-error`,className:`notice-err text-label`,role:`alert`,children:p(`cws.err.invalidSessionPin`,{min:6e4,max:864e5})})]})]}),(0,Q.jsxs)(`div`,{className:`cwi-jev-decision-test`,style:{display:`flex`,gap:8,alignItems:`center`,flexWrap:`wrap`,marginTop:8},children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:d||!k||E?.state===`running`,onClick:()=>{A()},children:E?.state===`running`?p(`cws.jev.testing`):p(`cws.jev.test`)}),(0,Q.jsxs)(`span`,{className:`muted`,role:`status`,"aria-live":`polite`,style:{fontSize:12,overflowWrap:`anywhere`},children:[E===null&&p(`cws.jev.testHint`),E?.state===`done`&&(E.ok?p(`cws.jev.testOk`,{ms:E.latencyMs,backend:p(Jr[E.backend]??`cws.jev.backend.unknown`)}):p(`cws.jev.testFailOpen`,{gate:E.gate,ms:E.latencyMs})),E?.state===`error`&&p(`cws.jev.testError`,{error:E.message})]})]})]})}var Ob=[];function kb({apiBase:e,combos:t=Ob,existingIds:r,existingAliases:i,providerMap:a,providerQuotaStates:o,providers:s,models:c,capabilityModels:l=c,initialDraft:u,onClose:d,onSubmit:f}){let p=n(),m=(0,Z.useRef)(null),[h,g]=(0,Z.useState)(()=>u?{...u,targets:u.targets.map(e=>({...e}))}:Vi()),[_,v]=(0,Z.useState)(!1),[y,b]=(0,Z.useState)(``),x=(0,Z.useMemo)(()=>{let e=new Map;for(let t of l)e.set(`${t.provider}/${t.id}`,t.reasoningEfforts);return e},[l]),S=(0,Z.useMemo)(()=>ai(h.targets,x,h.reasoningEffortMode??`strict`),[h.targets,x,h.reasoningEffortMode]),C=Fi(h.targets,o,a)===`exhausted`,w=u?.strategy===`jev`,T=w&&(r.includes(h.id.trim())||!!h.alias?.trim()&&i.includes(h.alias.trim()));(0,Z.useEffect)(()=>{let e=m.current;e&&!e.open&&e.showModal()},[]);let E=(0,Z.useCallback)(()=>{_||d()},[_,d]),D=(0,Z.useCallback)(e=>{e.preventDefault(),E()},[E]),O=async()=>{let e=Bi(h,{existingIds:r,existingAliases:i,combos:t,isCreate:!0,providers:a});if(e){b(gb(p,e,h,a));return}v(!0),b(``);let n=h.id.trim(),o=h.alias?.trim()||null;try{let e=await f({...h,id:n,alias:o,model:gi(n,o)});if(!e.ok){b(e.error||p(`cws.saveFailed`));return}}finally{v(!1)}};return(0,Q.jsxs)(`dialog`,{ref:m,className:`modal-overlay`,"data-combo-preset":w?`jev-auto`:void 0,"aria-labelledby":`cwi-add-title`,onCancel:D,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":p(`common.close`),tabIndex:-1,onClick:E}),(0,Q.jsxs)(`div`,{className:`modal-card`,style:{width:`min(560px, 94vw)`},onClick:e=>e.stopPropagation(),children:[(0,Q.jsxs)(`div`,{className:`row`,style:{justifyContent:`space-between`,marginBottom:8},children:[(0,Q.jsx)(`h3`,{id:`cwi-add-title`,style:{margin:0},children:p(`cws.addTitle`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:E,disabled:_,"aria-label":p(`common.close`),children:(0,Q.jsx)(xe,{width:16,height:16})})]}),(0,Q.jsx)(`p`,{className:`muted`,style:{marginTop:0,maxWidth:`62ch`,overflowWrap:`anywhere`},children:p(w?`cws.jev.setupHint`:`cws.addSubtitle`)}),y&&(0,Q.jsx)($,{tone:`err`,children:y}),T&&(0,Q.jsx)($,{tone:`err`,children:p(`cws.jev.exists`)}),C&&(0,Q.jsx)(`div`,{className:`cwi-quota-banner`,role:`status`,"aria-live":`polite`,children:p(`cws.quota.allExhausted`)}),(0,Q.jsxs)(`div`,{className:`cwi-modal-form`,children:[(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`cwi-new-id`,children:p(`cws.field.id`)}),(0,Q.jsx)(`input`,{id:`cwi-new-id`,className:`input mono`,value:h.id,disabled:_,onChange:e=>g(t=>({...t,id:e.target.value,model:gi(e.target.value,t.alias)}))}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:p(`cws.field.idInternalHint`)})]}),(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`cwi-new-alias`,children:p(`cws.field.alias`)}),(0,Q.jsx)(`input`,{id:`cwi-new-alias`,className:`input mono`,value:h.alias??``,placeholder:p(`cws.field.aliasPlaceholder`),disabled:_,onChange:e=>g(t=>({...t,alias:e.target.value.trim()?e.target.value:null,model:gi(t.id,e.target.value)}))}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:p(`cws.field.aliasHint`)}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:p(`cws.field.idHint`,{model:h.id.trim()?gi(h.id,h.alias):`…`})})]}),(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:p(`cws.strategy`)}),(0,Q.jsx)(xb,{value:h.strategy,disabled:_,onChange:e=>g(t=>({...t,strategy:e}))}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:p(ti[h.strategy])})]}),h.strategy===`jev`&&(0,Q.jsx)(Db,{idPrefix:`cwi-new`,apiBase:e,combo:h,combos:t,providers:s,models:c,decisionProvider:h.decisionProvider??null,decisionModel:h.decisionModel??null,decisionTimeoutMs:h.decisionTimeoutMs??null,sessionPin:h.sessionPin,disabled:_,onChange:e=>g(t=>({...t,...e}))}),(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`cwi-new-effort`,children:p(`cws.field.defaultEffort`)}),(0,Q.jsx)(Sb,{id:`cwi-new-effort`,value:h.defaultEffort,disabled:_,allowedEfforts:S,onChange:e=>g(t=>({...t,defaultEffort:e}))}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:p(`cws.field.defaultEffortHint`)})]}),h.strategy===`round-robin`&&(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`cwi-new-sticky`,children:p(`cws.field.stickyLimit`)}),(0,Q.jsx)(`input`,{id:`cwi-new-sticky`,className:`input mono`,type:`number`,min:1,max:100,value:h.stickyLimit,disabled:_,onChange:e=>{let t=vb(e.target.value,1,100);t!==void 0&&g(e=>({...e,stickyLimit:t}))}}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:p(`cws.field.stickyLimitHint`)})]}),(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:p(`cws.targets`)}),(0,Q.jsx)(wb,{targets:h.targets,strategy:h.strategy,providers:s,models:c,capabilityModels:l,providerQuotaStates:o,onChange:e=>g(t=>({...t,targets:e}))}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:p(ni[h.strategy])})]}),(0,Q.jsx)(Cb,{targets:h.targets,models:l,imageInput:h.imageInput??`auto`,reasoningEffortMode:h.reasoningEffortMode??`strict`,disabled:_,onChange:e=>g(t=>({...t,...e}))})]}),(0,Q.jsxs)(`div`,{className:`cwi-modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:E,disabled:_,children:p(`common.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>{O()},disabled:_||C||T,children:p(_?`common.saving`:`cws.create`)})]})]})]})}function Ab(e){return e===null?`—`:`${Math.round(e*100)}%`}function jb(e,t){if(e===null)return`—`;let n=e>=1e3;return new Intl.NumberFormat(t,{style:`unit`,unit:n?`second`:`millisecond`,unitDisplay:`short`,maximumFractionDigits:n&&e<1e4?1:0}).format(n?e/1e3:e)}function Mb({apiBase:e,comboId:t,active:n}){let{t:i,locale:a}=r(),[o,s]=(0,Z.useState)(`30d`),c=(0,Z.useCallback)(async n=>{let r=new URLSearchParams({jev:`1`,comboId:t,range:o}),i=await fetch(`${e}/api/usage?${r}`,{signal:n});if(!i.ok)throw Error(String(i.status));return i.json()},[e,t,o]),l=uo(`ocx.jev-stats.v1:${e}:${t}:${o}`,[e,t,o],c,{isEmpty:e=>e.summary.decisions===0,enabled:n,pollMs:3e4,pauseWhenHidden:!0,deadlineMs:6e4}),{state:u}=l,d=u.data;return n?(0,Q.jsxs)(`section`,{className:`jev-stats`,"aria-busy":u.refreshing,children:[(0,Q.jsxs)(`div`,{className:`jev-stats-toolbar`,children:[(0,Q.jsx)(`div`,{className:`segmented jev-stats-ranges`,role:`group`,"aria-label":i(`cws.jev.stats.range`),children:[`7d`,`30d`,`all`].map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm ${o===e?`btn-primary`:`btn-ghost`}`,"aria-pressed":o===e,onClick:()=>s(e),children:i(e===`all`?`usage.range.available`:`usage.range.${e}`)},e))}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>l.refresh(),children:i(`cws.jev.stats.refresh`)})]}),u.showSkeleton&&(0,Q.jsx)(lb,{label:i(`cws.jev.stats.loading`),rows:4}),u.showError&&(0,Q.jsx)($,{tone:`err`,children:i(`cws.jev.stats.loadFailed`)}),d&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Sr,{data:d}),(d.historyTruncated||d.entriesTruncated)&&(0,Q.jsx)($,{tone:`warn`,children:i(`cws.jev.stats.historyIncomplete`)}),d.error&&(0,Q.jsx)($,{tone:`err`,children:i(`cws.jev.stats.loadFailed`)}),d.summary.decisions===0?(0,Q.jsxs)(`div`,{className:`jev-stats-empty`,children:[(0,Q.jsx)(`h3`,{children:i(`cws.jev.stats.emptyTitle`)}),(0,Q.jsx)(`p`,{className:`muted`,children:i(`cws.jev.stats.emptyBody`)})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`jev-stats-cards`,children:[(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`muted`,children:i(`cws.jev.stats.decisions`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:d.summary.decisions.toLocaleString(a)}),(0,Q.jsx)(`div`,{className:`muted text-caption`,children:i(`cws.jev.stats.appliedAndFailOpen`,{applied:d.summary.appliedDecisions,failOpen:d.summary.failOpenDecisions})})]}),(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`muted`,children:i(`cws.jev.stats.modelTokens`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:q(d.summary.modelTotalTokens,a)}),(0,Q.jsx)(`div`,{className:`muted text-caption`,children:i(`cws.jev.stats.measuredAttempts`,{measured:d.summary.measuredModelAttempts,total:d.summary.modelAttempts})})]}),(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`muted`,children:i(`cws.jev.stats.decisionTokens`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:q(d.summary.decisionTotalTokens,a)}),(0,Q.jsx)(`div`,{className:`muted text-caption`,children:i(`cws.jev.stats.measuredDecisions`,{measured:d.summary.decisionUsageReported,total:d.summary.decisions})})]})]}),(0,Q.jsxs)(`div`,{className:`jev-stats-facts`,children:[(0,Q.jsx)(`span`,{children:i(`cws.jev.stats.successful`,{count:d.summary.successfulRequests})}),(0,Q.jsx)(`span`,{children:i(d.summary.requestsWithModelFallback===1?`cws.jev.stats.fallbackOne`:`cws.jev.stats.fallbackMany`,{count:d.summary.requestsWithModelFallback})}),(0,Q.jsx)(`span`,{children:i(`cws.jev.stats.averageLatency`,{value:jb(d.summary.averageLatencyMs,a)})}),(0,Q.jsx)(`span`,{children:i(`cws.jev.stats.averageConfidence`,{value:Ab(d.summary.averageConfidence)})})]}),(0,Q.jsx)(`div`,{className:`jev-stats-gates`,"aria-label":i(`cws.jev.stats.gates`),children:d.gates.map(e=>(0,Q.jsxs)(`span`,{className:`chip`,children:[e.gate,`: `,e.decisions]},e.gate))}),d.backends&&d.backends.length>0&&(0,Q.jsx)(`div`,{className:`jev-stats-table-wrap`,children:(0,Q.jsxs)(`table`,{className:`jev-stats-table`,"aria-label":i(`cws.jev.stats.backends`),children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:i(`cws.jev.stats.backend`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`cws.jev.stats.decisions`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`cws.jev.stats.applied`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`cws.jev.stats.latency`)})]})}),(0,Q.jsx)(`tbody`,{children:d.backends.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{children:i(Jr[e.backend]??`cws.jev.backend.unknown`)}),(0,Q.jsx)(`td`,{className:`num mono`,children:e.decisions.toLocaleString(a)}),(0,Q.jsx)(`td`,{className:`num mono`,children:e.applied.toLocaleString(a)}),(0,Q.jsx)(`td`,{className:`num mono`,children:jb(e.averageLatencyMs,a)})]},e.backend))})]})}),(0,Q.jsx)(`div`,{className:`jev-stats-table-wrap`,children:(0,Q.jsxs)(`table`,{className:`jev-stats-table`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:i(`cws.jev.stats.model`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`cws.jev.stats.picks`)}),(0,Q.jsx)(`th`,{children:i(`cws.jev.stats.efforts`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`cws.jev.stats.attempts`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`cws.jev.stats.input`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`cws.jev.stats.output`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`cws.jev.stats.reasoning`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`cws.jev.stats.cacheReadWrite`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`cws.jev.stats.total`)})]})}),(0,Q.jsx)(`tbody`,{children:d.models.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{children:e.overflow?(0,Q.jsx)(`div`,{children:i(`cws.jev.stats.otherModels`)}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`mono`,children:e.model}),(0,Q.jsx)(`div`,{className:`muted text-caption`,children:Ce(e.provider,i)})]})}),(0,Q.jsxs)(`td`,{className:`num mono`,children:[e.picks,(0,Q.jsx)(`span`,{className:`jev-stats-cell-note`,children:i(`cws.jev.stats.appliedAndFailOpen`,{applied:e.appliedPicks,failOpen:e.failOpenPicks})})]}),(0,Q.jsx)(`td`,{children:e.efforts.length>0?e.efforts.map(e=>`${e.effort??i(`cws.jev.stats.noEffort`)} × ${e.picks}`).join(`, `):`—`}),(0,Q.jsxs)(`td`,{className:`num mono`,children:[e.attempts,(0,Q.jsxs)(`span`,{className:`jev-stats-cell-note`,children:[e.measuredAttempts,` `,i(`cws.jev.stats.measuredShort`)]})]}),(0,Q.jsx)(`td`,{className:`num mono`,children:q(e.inputTokens,a)}),(0,Q.jsx)(`td`,{className:`num mono`,children:q(e.outputTokens,a)}),(0,Q.jsx)(`td`,{className:`num mono`,children:q(e.reasoningTokens,a)}),(0,Q.jsxs)(`td`,{className:`num mono`,children:[q(e.cacheReadTokens,a),` / `,q(e.cacheWriteTokens,a)]}),(0,Q.jsx)(`td`,{className:`num mono`,children:q(e.totalTokens,a)})]},e.overflow?`__jev_stats_overflow__`:`${e.provider}\0${e.model}`))})]})}),(0,Q.jsx)(`p`,{className:`muted text-caption jev-stats-footnote`,children:i(`cws.jev.stats.tokenFootnote`)})]})]})]}):null}var Nb={passthrough:`api.plan.disposition.passthrough`,translated:`api.plan.disposition.translated`,degraded:`api.plan.disposition.degraded`,unsupported:`api.plan.disposition.unsupported`},Pb={passthrough:`badge-green`,translated:`badge-accent`,degraded:`badge-amber`,unsupported:`badge-muted`};function Fb({effects:e,unknownFeatures:t}){let r=n();return e.length===0&&t.length===0?(0,Q.jsx)(`p`,{className:`muted small`,children:r(`api.plan.noFeatures`)}):(0,Q.jsxs)(`ul`,{className:`protocol-feature-list`,children:[e.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`code`,{children:e.feature}),(0,Q.jsx)(`span`,{className:`badge ${Pb[e.disposition]}`,children:r(Nb[e.disposition])})]},e.feature)),t.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`code`,{children:e}),(0,Q.jsx)(`span`,{className:`badge badge-muted`,children:r(`api.plan.disposition.unknown`)})]},e))]})}var Ib=[`responses`,`chat`,`messages`],Lb={native:`api.plan.mode.native`,translated:`api.plan.mode.translated`,"legacy-bridge":`api.plan.mode.legacyBridge`,blocked:`api.plan.mode.blocked`},Rb={native:`badge-green`,translated:`badge-accent`,"legacy-bridge":`badge-amber`,blocked:`badge-muted`},zb={preserved:`api.plan.fidelity.preserved`,degraded:`api.plan.fidelity.degraded`,unknown:`api.plan.fidelity.unknown`},Bb={direct:`api.plan.routeKind.direct`,combo:`api.plan.routeKind.combo`,policy:`api.plan.routeKind.policy`,unknown:`api.plan.routeKind.unknown`},Vb=` → `;function Hb({path:e}){let t=n();return e.length>0?(0,Q.jsx)(`code`,{children:e.join(Vb)}):(0,Q.jsx)(`span`,{className:`muted`,children:t(`api.plan.noPath`)})}function Ub({features:e}){let t=n();return e.length===0?(0,Q.jsx)(`span`,{className:`muted`,children:t(`api.plan.none`)}):(0,Q.jsx)(`span`,{className:`protocol-plan-chips`,children:e.map(e=>(0,Q.jsx)(`code`,{className:`chip`,children:e},e))})}function Wb({plan:e}){let t=n();return(0,Q.jsxs)(`div`,{className:`protocol-plan-result`,"aria-live":`polite`,children:[(0,Q.jsxs)(`dl`,{className:`awi-kv`,children:[(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:t(`api.plan.overallMode`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(`span`,{className:`badge ${Rb[e.mode]}`,children:t(Lb[e.mode])})})]}),(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:t(`api.plan.routeKind`)}),(0,Q.jsx)(`dd`,{children:t(Bb[e.routeKind])})]}),e.reasonCodes.length>0&&(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:t(`api.plan.reasons`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(`span`,{className:`protocol-plan-chips`,children:e.reasonCodes.map(e=>(0,Q.jsx)(`code`,{className:`chip`,children:e},e))})})]}),(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:t(`api.plan.guaranteed`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(Ub,{features:e.guaranteedFeatures})})]}),(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:t(`api.plan.partial`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(Ub,{features:e.partialFeatures})})]}),(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:t(`api.plan.policyRevision`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(`code`,{children:e.policyRevision})})]})]}),e.candidates.length===0?(0,Q.jsx)(`p`,{className:`muted small`,children:t(`api.plan.noCandidates`)}):(0,Q.jsx)(`ol`,{className:`protocol-plan-candidates`,children:e.candidates.map(n=>(0,Q.jsxs)(`li`,{className:`protocol-plan-candidate`,children:[(0,Q.jsxs)(`div`,{className:`protocol-plan-candidate-head`,children:[(0,Q.jsxs)(`code`,{children:[n.provider,`/`,n.model]}),(0,Q.jsx)(`span`,{className:`badge ${Rb[n.mode]}`,children:t(Lb[n.mode])}),!n.eligible&&n.mode!==`blocked`&&(0,Q.jsx)(`span`,{className:`badge badge-muted`,children:t(`api.plan.ineligible`)})]}),(0,Q.jsxs)(`dl`,{className:`awi-kv`,children:[(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:t(`api.plan.requestPath`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(Hb,{path:n.requestPath})})]}),(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:t(`api.plan.responsePath`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(Hb,{path:n.responsePath})})]}),(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:t(`api.plan.fidelity`)}),(0,Q.jsx)(`dd`,{children:t(zb[n.fidelity])})]}),n.reasonCodes.length>0&&(0,Q.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,Q.jsx)(`dt`,{children:t(`api.plan.reasons`)}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(`span`,{className:`protocol-plan-chips`,children:n.reasonCodes.map(e=>(0,Q.jsx)(`code`,{className:`chip`,children:e},e))})})]})]}),(0,Q.jsx)(Fb,{effects:n.featureEffects,unknownFeatures:n.unknownFeatures}),(0,Q.jsxs)(`div`,{className:`protocol-plan-links`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>h_(n.provider),children:t(`protocolLinks.providerSettings`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>m_({inbound:e.inbound,upstream:o_(n.upstream)}),children:t(`protocolLinks.labEvidence`)})]})]},`${n.provider}/${n.model}`))})]})}function Gb({apiBase:e,models:t,protocolLabel:r}){let i=n(),[a,o]=(0,Z.useState)(``),[s,c]=(0,Z.useState)(`chat`),[l,u]=(0,Z.useState)(()=>new Set),[d,f]=(0,Z.useState)(null),[p,m]=(0,Z.useState)(!1),[h,g]=(0,Z.useState)(!1),[_,v]=(0,Z.useState)(!1),y=(0,Z.useRef)(null);(0,Z.useEffect)(()=>()=>y.current?.abort(),[]);let b=a||t[0]?.id||``,x=(0,Z.useMemo)(()=>Gm.filter(e=>Jm[e].includes(s)),[s]),S=e=>{c(e),u(t=>new Set([...t].filter(t=>Jm[t].includes(e))))},C=(e,t)=>{u(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r})},w=async()=>{if(!b||p)return;y.current?.abort();let t=new AbortController;y.current=t,m(!0),g(!1);try{let n=await xh(e,{model:b,inbound:s,features:[...l]},t.signal);if(t.signal.aborted)return;n.kind===`unavailable`?(v(!0),f(null)):n.kind===`error`?g(!0):f(n.plan)}catch{}finally{y.current===t&&m(!1)}};return(0,Q.jsxs)(`div`,{className:`panel api-panel protocol-plan-panel`,children:[(0,Q.jsx)(`h3`,{className:`panel-title`,children:i(`api.plan.title`)}),(0,Q.jsx)(`p`,{className:`muted small`,children:i(`api.plan.description`)}),(0,Q.jsx)(`p`,{className:`muted small`,children:i(`api.plan.modeNote`)}),_?(0,Q.jsx)(`p`,{className:`muted small`,children:i(`api.plan.unavailable`)}):t.length===0?(0,Q.jsx)(`p`,{className:`muted small`,children:i(`api.plan.noModels`)}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`protocol-plan-form`,children:[(0,Q.jsxs)(`label`,{className:`protocol-plan-field`,children:[(0,Q.jsx)(`span`,{className:`muted small`,children:i(`api.plan.model`)}),(0,Q.jsx)(`select`,{className:`input`,value:b,onChange:e=>o(e.target.value),children:t.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.id},e.id))})]}),(0,Q.jsxs)(`label`,{className:`protocol-plan-field`,children:[(0,Q.jsx)(`span`,{className:`muted small`,children:i(`api.plan.inbound`)}),(0,Q.jsx)(`select`,{className:`input`,value:s,onChange:e=>S(e.target.value),children:Ib.map(e=>(0,Q.jsx)(`option`,{value:e,children:r(e)},e))})]})]}),(0,Q.jsxs)(`fieldset`,{className:`protocol-plan-features`,children:[(0,Q.jsx)(`legend`,{className:`muted small`,children:i(`api.plan.features`)}),x.map(e=>(0,Q.jsxs)(`label`,{className:`protocol-plan-feature`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:l.has(e),onChange:t=>C(e,t.target.checked)}),(0,Q.jsx)(`code`,{children:e})]},e))]}),(0,Q.jsx)(`div`,{children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:!b||p,onClick:()=>{w()},children:i(p?`api.plan.previewing`:`api.plan.preview`)})}),h&&(0,Q.jsx)(`p`,{className:`awi-delete-error`,role:`alert`,children:i(`api.plan.failed`)}),d&&(0,Q.jsx)(Wb,{plan:d})]})]})}function Kb({apiBase:e,model:t,dirty:r}){let i=n(),[a,o]=(0,Z.useState)(`responses`),[s,c]=(0,Z.useState)(null),[l,u]=(0,Z.useState)(!1),[d,f]=(0,Z.useState)(!1),[p,m]=(0,Z.useState)(!1),h=(0,Z.useRef)(null);(0,Z.useEffect)(()=>()=>h.current?.abort(),[]);let g=(0,Z.useMemo)(()=>Gm.filter(e=>Jm[e].includes(a)),[a]),_=async()=>{if(l)return;h.current?.abort();let n=new AbortController;h.current=n,u(!0),f(!1);try{let r=await xh(e,{model:t,inbound:a,features:g},n.signal);if(n.signal.aborted)return;r.kind===`unavailable`?m(!0):r.kind===`error`?f(!0):c(r.plan)}catch{}finally{h.current===n&&u(!1)}};return p?null:(0,Q.jsxs)(`section`,{className:`pwi-section combo-protocol-plan`,"aria-labelledby":`cws-plan-title`,children:[(0,Q.jsx)(`h3`,{id:`cws-plan-title`,className:`pwi-section-title`,children:i(`cws.plan.title`)}),(0,Q.jsx)(`p`,{className:`muted small`,children:i(`cws.plan.description`)}),(0,Q.jsx)(`p`,{className:`muted small`,children:i(`api.plan.modeNote`)}),r&&(0,Q.jsx)(`p`,{className:`muted small`,role:`status`,children:i(`cws.plan.savedOnly`)}),(0,Q.jsx)(`div`,{className:`protocol-plan-form`,children:(0,Q.jsxs)(`label`,{className:`protocol-plan-field`,children:[(0,Q.jsx)(`span`,{className:`muted small`,children:i(`api.plan.inbound`)}),(0,Q.jsx)(`select`,{className:`input`,value:a,onChange:e=>{o(e.target.value),c(null)},children:Tm.map(e=>(0,Q.jsx)(`option`,{value:e,children:Oh(e,i)},e))})]})}),(0,Q.jsx)(`div`,{children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:l,onClick:()=>{_()},children:i(l?`api.plan.previewing`:`cws.plan.run`)})}),d&&(0,Q.jsx)(`p`,{className:`awi-delete-error`,role:`alert`,children:i(`api.plan.failed`)}),s&&s.inbound===a&&(0,Q.jsx)(Wb,{plan:s})]})}var qb=[`config`,`about`],Jb=[`config`,`stats`,`about`],Yb=e=>`cws-detail-tab-${e}`,Xb=e=>`cws-detail-panel-${e}`,Zb=[];function Qb({apiBase:e,baseline:t,combos:r=Zb,isCreate:i=!1,otherIds:a,otherAliases:o,providerMap:s,providerQuotaStates:c,providers:l,models:u,capabilityModels:d=u,visionEnabled:f,onBack:p,onSaved:m,onRequestRemove:h,onSave:g,onDirtyChange:_}){let v=n(),[y,b]=(0,Z.useState)(`config`),x=!i&&t.strategy===`jev`?Jb:qb,S=(0,Z.useCallback)((e,t)=>{let n;if(e.key===`ArrowRight`)n=(t+1)%x.length;else if(e.key===`ArrowLeft`)n=(t-1+x.length)%x.length;else if(e.key===`Home`)n=0;else if(e.key===`End`)n=x.length-1;else return;e.preventDefault(),b(x[n]),e.currentTarget.parentElement?.querySelectorAll(`[role="tab"]`)[n]?.focus()},[x]),[C,w]=(0,Z.useState)(t),[T,E]=(0,Z.useState)(!1),[D,O]=(0,Z.useState)(null),[k,A]=(0,Z.useState)(!1),j=!Ri(C,t),M=Fi(C.targets,c,s)===`exhausted`,N=JSON.stringify([t.id,t.alias,t.nativeAlias,t.displayName,t.strategy,t.stickyLimit,t.defaultEffort,t.imageInput,t.reasoningEffortMode,t.decisionProvider,t.decisionModel,t.decisionTimeoutMs,t.sessionPin===void 0,t.sessionPin,t.targets.map(e=>[e.provider,e.model,e.weight,e.reasoningEfforts,e.modelProfile])]),P=(0,Z.useMemo)(()=>{let e=new Map;for(let t of d)e.set(`${t.provider}/${t.id}`,t.reasoningEfforts);return e},[d]),F=(0,Z.useMemo)(()=>ai(C.targets,P,C.reasoningEffortMode??`strict`),[C.targets,P,C.reasoningEffortMode]),I=(0,Z.useCallback)(e=>{let n=e(C);w(n),_(!Ri(n,t))},[C,t,_]);(0,Z.useEffect)(()=>{let e=window.setTimeout(()=>{w(t),O(null),b(`config`),_(!1)},0);return()=>window.clearTimeout(e)},[N]);let L=async()=>{try{await navigator.clipboard.writeText(t.model),A(!0),window.setTimeout(()=>A(!1),1200)}catch{}},z=async()=>{let e=Bi(C,{existingIds:a,existingAliases:o,combos:r,isCreate:i,providers:s});if(e){O({ok:!1,text:gb(v,e,C,s)});return}E(!0);let n=C.id.trim(),c=C.alias?.trim()||null,l=C.displayName?.trim()||null,u={...C,id:n,alias:c,displayName:l,model:gi(n,c),...C.strategy===`jev`?{}:{decisionProvider:null,decisionModel:null,decisionTimeoutMs:null,sessionPin:void 0}},d=!i&&n!==t.id?t.id:void 0;try{let e=await g(u,i,d);if(!e.ok){O({ok:!1,text:e.error||v(`cws.saveFailed`)});return}O({ok:!0,text:i?v(`cws.created`,{model:u.model}):v(`cws.saved`)}),m(u)}finally{E(!1)}},B=i?C.id.trim()?gi(C.id,C.alias):v(`cws.addTitle`):t.model;return(0,Q.jsxs)(`div`,{className:`combos-workspace-detail`,children:[(0,Q.jsxs)(`div`,{className:`combos-workspace-detail-head`,children:[p&&(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm pwi-back-overview`,onClick:p,"aria-label":v(`cws.backToAll`),children:[(0,Q.jsx)(Ye,{style:{width:14,height:14,transform:`rotate(180deg)`},"aria-hidden":`true`}),v(`cws.allCombos`)]}),(0,Q.jsx)(`h2`,{className:`combos-workspace-detail-title`,children:B}),!i&&(0,Q.jsx)(`button`,{type:`button`,className:`chip cwi-copy-chip`,onClick:()=>{L()},title:v(`cws.copyModel`),children:v(k?`cws.copied`:`cws.copyModel`)}),(0,Q.jsxs)(`div`,{className:`combos-workspace-detail-actions`,children:[!i&&h&&(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:h,children:[(0,Q.jsx)(R,{width:14,height:14}),` `,v(`common.remove`)]}),(0,Q.jsx)(`button`,{id:i?`cwi-edit-create`:`cwi-edit-save`,type:`button`,className:`btn btn-primary btn-sm`,disabled:!i&&!j||T||M,onClick:()=>{z()},children:v(T?`common.saving`:i?`cws.create`:`common.save`)})]})]}),D&&(0,Q.jsx)($,{tone:D.ok?`ok`:`err`,children:D.text}),M&&(0,Q.jsx)(`div`,{className:`cwi-quota-banner`,role:`status`,"aria-live":`polite`,children:v(`cws.quota.allExhausted`)}),(0,Q.jsx)(`div`,{className:`segmented combos-workspace-segmented`,role:`tablist`,"aria-label":v(`cws.tabsLabel`),children:x.map((e,t)=>(0,Q.jsx)(`button`,{type:`button`,role:`tab`,id:Yb(e),"aria-selected":y===e,"aria-controls":Xb(e),tabIndex:y===e?0:-1,className:`btn btn-sm ${y===e?`btn-primary`:`btn-ghost`}`,onClick:()=>b(e),onKeyDown:e=>S(e,t),children:v(e===`config`?`cws.tab.config`:e===`stats`?`cws.jev.stats.tab`:`cws.tab.about`)},e))}),(0,Q.jsxs)(`div`,{className:`combos-workspace-tab-content`,role:`tabpanel`,id:Xb(`config`),"aria-labelledby":Yb(`config`),hidden:y!==`config`,children:[(0,Q.jsxs)(`div`,{className:`cwi-form-grid`,children:[(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`cwi-edit-id`,children:v(`cws.field.id`)}),(0,Q.jsx)(`input`,{id:`cwi-edit-id`,className:`input mono`,value:C.id,disabled:T,onChange:e=>I(t=>({...t,id:e.target.value,model:gi(e.target.value,t.alias)}))}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:i?v(`cws.field.idInternalHint`):v(`cws.field.idHintEdit`,{model:gi(C.id,C.alias)})})]}),(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`cwi-edit-alias`,children:v(`cws.field.alias`)}),(0,Q.jsx)(`input`,{id:`cwi-edit-alias`,className:`input mono`,value:C.alias??``,placeholder:hi(C.id.trim()||`…`),disabled:T,onChange:e=>I(t=>_i(t,e.target.value))}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:v(`cws.field.aliasHint`)})]}),(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsxs)(`label`,{htmlFor:`cwi-edit-native-alias`,children:[(0,Q.jsx)(`input`,{id:`cwi-edit-native-alias`,type:`checkbox`,checked:C.nativeAlias,disabled:T,onChange:e=>I(t=>({...t,nativeAlias:e.target.checked}))}),` `,v(`cws.field.nativeAlias`)]}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:v(`cws.field.nativeAliasHint`)})]}),(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`cwi-edit-display-name`,children:v(`cws.field.displayName`)}),(0,Q.jsx)(`input`,{id:`cwi-edit-display-name`,className:`input`,value:C.displayName??``,maxLength:128,disabled:T,onChange:e=>I(t=>({...t,displayName:e.target.value||null}))}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:v(`cws.field.displayNameHint`)})]}),(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:v(`cws.strategy`)}),(0,Q.jsx)(xb,{value:C.strategy,disabled:T,onChange:e=>I(t=>({...t,strategy:e}))}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:v(ti[C.strategy])})]}),C.strategy===`jev`&&(0,Q.jsx)(Db,{idPrefix:`cwi-edit`,apiBase:e,combo:C,combos:r,providers:l,models:u,decisionProvider:C.decisionProvider??null,decisionModel:C.decisionModel??null,decisionTimeoutMs:C.decisionTimeoutMs??null,sessionPin:C.sessionPin,disabled:T,onChange:e=>I(t=>({...t,...e}))}),(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`cwi-effort`,children:v(`cws.field.defaultEffort`)}),(0,Q.jsx)(Sb,{id:`cwi-effort`,value:C.defaultEffort,disabled:T,allowedEfforts:F,onChange:e=>I(t=>({...t,defaultEffort:e}))}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:v(`cws.field.defaultEffortHint`)})]}),C.strategy===`round-robin`&&(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`cwi-sticky`,children:v(`cws.field.stickyLimit`)}),(0,Q.jsx)(`input`,{id:`cwi-sticky`,className:`input mono`,type:`number`,min:1,max:100,value:C.stickyLimit,disabled:T,onChange:e=>{let t=vb(e.target.value,1,100);t!==void 0&&I(e=>({...e,stickyLimit:t}))}})]}),(0,Q.jsxs)(`div`,{className:`cwi-field`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:v(`cws.targets`)}),(0,Q.jsx)(wb,{targets:C.targets,strategy:C.strategy,providers:l,models:u,capabilityModels:d,providerQuotaStates:c,onChange:e=>I(t=>({...t,targets:e}))}),(0,Q.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:v(ni[C.strategy])})]}),(0,Q.jsx)(Cb,{targets:C.targets,models:d,imageInput:C.imageInput??`auto`,reasoningEffortMode:C.reasoningEffortMode??`strict`,visionEnabled:f,disabled:T,onChange:e=>I(t=>({...t,...e}))})]}),!i&&e!==void 0&&(0,Q.jsx)(Kb,{apiBase:e,model:t.model,dirty:j})]}),!i&&t.strategy===`jev`&&(0,Q.jsx)(`div`,{className:`combos-workspace-tab-content`,role:`tabpanel`,id:Xb(`stats`),"aria-labelledby":Yb(`stats`),hidden:y!==`stats`,children:(0,Q.jsx)(Mb,{apiBase:e??``,comboId:t.id,active:y===`stats`})}),(0,Q.jsx)(`div`,{className:`combos-workspace-tab-content`,role:`tabpanel`,id:Xb(`about`),"aria-labelledby":Yb(`about`),hidden:y!==`about`,tabIndex:0,children:(0,Q.jsxs)(`section`,{className:`pwi-section`,children:[(0,Q.jsx)(`h3`,{className:`pwi-section-title`,children:v(`cws.aboutTitle`)}),(0,Q.jsx)(`p`,{className:`muted`,style:{margin:0,maxWidth:`70ch`,overflowWrap:`anywhere`},children:v(`cws.aboutBody`)})]})})]})}function $b({model:e,onCancel:t,onConfirm:r}){let i=n(),a=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{let e=a.current;e&&!e.open&&e.showModal()},[]);let o=(0,Z.useCallback)(e=>{e.preventDefault(),t()},[t]);return(0,Q.jsxs)(`dialog`,{ref:a,className:`modal-overlay`,"aria-labelledby":`cwi-remove-title`,onCancel:o,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":i(`common.close`),tabIndex:-1,onClick:t}),(0,Q.jsxs)(`div`,{className:`modal-card pwi-remove-confirm-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsx)(`h3`,{id:`cwi-remove-title`,className:`pwi-remove-confirm-title`,children:i(`cws.removeConfirmTitle`,{model:e})}),(0,Q.jsx)(`p`,{className:`muted pwi-remove-confirm-desc`,children:i(`cws.removeConfirmDesc`)}),(0,Q.jsxs)(`div`,{className:`pwi-remove-confirm-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:t,children:i(`common.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn pwi-remove-confirm-danger`,onClick:r,children:i(`common.remove`)})]})]})]})}function ex({onKeep:e,onDiscard:t}){let r=n(),i=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{let e=i.current;e&&!e.open&&e.showModal()},[]);let a=(0,Z.useCallback)(t=>{t.preventDefault(),e()},[e]);return(0,Q.jsxs)(`dialog`,{ref:i,className:`modal-overlay`,"aria-labelledby":`cwi-unsaved-title`,onCancel:a,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":r(`common.close`),tabIndex:-1,onClick:e}),(0,Q.jsxs)(`div`,{className:`modal-card pwi-json-unsaved-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsx)(`h3`,{id:`cwi-unsaved-title`,className:`pwi-json-unsaved-title`,children:r(`cws.unsavedTitle`)}),(0,Q.jsx)(`p`,{className:`muted pwi-json-unsaved-desc`,children:r(`cws.unsavedDesc`)}),(0,Q.jsxs)(`div`,{className:`pwi-json-unsaved-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,"data-testid":`cwi-unsaved-keep`,onClick:e,children:r(`cws.keepEditing`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-danger`,"data-testid":`cwi-unsaved-discard`,onClick:t,children:r(`common.discard`)})]})]})]})}function tx(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 nx({combos:e,cataloguedComboIds:t,providerMap:r,providerQuotaStates:i,providers:a,onSelect:o,onAdd:s}){let c=n(),l=Di(e),u=Ii(e,{cataloguedComboIds:t,providers:r,providerQuotaStates:i}),d=e.flatMap(e=>{let t=Ki(e,a);return t?[{item:e,decision:t}]:[]});return(0,Q.jsxs)(`div`,{className:`combos-workspace-overview`,children:[(0,Q.jsxs)(`div`,{className:`combos-workspace-overview-head`,children:[(0,Q.jsx)(`h2`,{className:`combos-workspace-overview-title`,children:c(`cws.overviewTitle`)}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:s,children:[(0,Q.jsx)(I,{width:14,height:14}),` `,c(`cws.add`)]})]}),(0,Q.jsx)(`p`,{className:`muted`,style:{marginTop:0,maxWidth:`62ch`},children:c(`cws.overviewBlurb`)}),(0,Q.jsxs)(`div`,{className:`cwi-count-strip`,children:[(0,Q.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,Q.jsx)(`strong`,{children:e.length}),(0,Q.jsx)(`span`,{children:c(`cws.count.total`)})]}),(0,Q.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,Q.jsx)(`strong`,{children:l.failover.length}),(0,Q.jsx)(`span`,{children:c(`cws.count.failover`)})]}),(0,Q.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,Q.jsx)(`strong`,{children:l.roundRobin.length}),(0,Q.jsx)(`span`,{children:c(`cws.count.roundRobin`)})]}),(0,Q.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,Q.jsx)(`strong`,{children:l.other.length}),(0,Q.jsx)(`span`,{children:c(`cws.count.other`)})]})]}),(0,Q.jsxs)(`section`,{className:`pwi-section`,"aria-label":c(`cws.howTitle`),children:[(0,Q.jsx)(`h3`,{className:`pwi-section-title`,children:c(`cws.howTitle`)}),(0,Q.jsx)(`p`,{className:`muted`,style:{margin:0},children:c(`cws.howBody`)})]}),d.length>0&&(0,Q.jsxs)(`section`,{className:`pwi-section`,"aria-label":c(`cws.jev.decisionServicesTitle`),children:[(0,Q.jsx)(`h3`,{className:`pwi-section-title`,children:c(`cws.jev.decisionServicesTitle`)}),(0,Q.jsx)(`div`,{className:`cwi-attention-list`,children:d.map(({item:e,decision:t})=>(0,Q.jsxs)(`button`,{type:`button`,className:`cwi-attention-row`,style:{flexWrap:`wrap`},"data-decision-provider":t.model?void 0:t.provider??`jev`,"data-decision-model":t.model??void 0,onClick:()=>o(e.id),children:[(0,Q.jsx)(`code`,{className:`chip`,children:e.model}),t.model?(0,Q.jsxs)(`span`,{children:[c(`cws.jev.method.model`),`: `,(0,Q.jsx)(`code`,{children:t.model})]}):(0,Q.jsx)(`span`,{children:t.provider??c(`cws.jev.decisionServiceDefault`)}),t.baseUrl&&(0,Q.jsx)(`code`,{className:`muted`,style:{overflowWrap:`anywhere`},children:t.baseUrl}),(0,Q.jsx)(`span`,{className:`muted`,children:t.timeoutMs===null?c(`cws.jev.decisionTimeoutDefaultShort`):c(`cws.jev.decisionTimeoutShort`,{ms:t.timeoutMs})}),(0,Q.jsx)(Ye,{width:14,height:14,style:{marginLeft:`auto`},"aria-hidden":`true`})]},e.id))})]}),u.length>0&&(0,Q.jsxs)(`section`,{className:`pwi-section`,"aria-label":c(`cws.attentionTitle`),children:[(0,Q.jsx)(`h3`,{className:`pwi-section-title`,children:c(`cws.attentionTitle`)}),(0,Q.jsx)(`div`,{className:`cwi-attention-list`,children:u.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`cwi-attention-row`,onClick:()=>o(e.id),children:[(0,Q.jsx)(Ne,{width:14,height:14,"aria-hidden":`true`}),(0,Q.jsx)(`code`,{className:`chip`,children:e.model}),(0,Q.jsx)(`span`,{className:`muted`,children:tx(e.reason,c)}),(0,Q.jsx)(Ye,{width:14,height:14,style:{marginLeft:`auto`},"aria-hidden":`true`})]},`${e.id}:${e.reason}`))})]})]})}function rx({apiBase:e,combos:t,providerQuotaStates:r,providers:i,models:a,capabilityModels:o=a,cataloguedComboIds:s,visionEnabled:c,loading:l,onRefresh:u,onSave:d,onRemove:f,onAdd:p,adding:m,addIntent:h,addDecisionProvider:g,onCloseAdd:_,onCreated:v}){let y=n(),b=(0,Z.useMemo)(()=>Object.fromEntries(i.map(e=>[e.name,{disabled:e.disabled,adapter:e.adapter,baseUrl:e.baseUrl,defaultModel:e.defaultModel,models:e.models}])),[i]),[x,S]=(0,Z.useState)(``),[C,w]=(0,Z.useState)(null),[T,E]=(0,Z.useState)(void 0),[D,O]=(0,Z.useState)(null),[k,A]=(0,Z.useState)(null),j=(0,Z.useMemo)(()=>Vi(),[]),M=(0,Z.useMemo)(()=>t.some(e=>e.id===`jev-auto`||e.alias===`jev-auto`),[t]),N=(0,Z.useMemo)(()=>new Set(i.filter(e=>!e.disabled&&!e.hiddenFromPicker&&e.adapter!==`jev-decision`).map(e=>e.name)),[i]),P=(0,Z.useMemo)(()=>{if(h!==`jev-auto`)return;let e=i.length===0||Wi(g,b)===null;return Ui(a,N,e?g:null)},[g,h,N,a,b,i.length]),F=(0,Z.useMemo)(()=>Oi(t,x),[t,x]),L=(0,Z.useMemo)(()=>Di(F),[F]),R=(0,Z.useMemo)(()=>t.flatMap(e=>e.alias?[e.alias]:[]),[t]),z=C&&t.some(e=>e.id===C)?C:null,B=t.find(e=>e.id===z)??null,V=B&&k?.source===B?k.item:B,[H,U]=(0,Z.useState)(!1),ee=[],W=[];if(V)for(let e of t)e.id!==V.id&&(ee.push(e.id),e.alias&&W.push(e.alias));let G=(0,Z.useCallback)(e=>{e!==z&&(H?E(e):(w(e),A(null)))},[z,H]),ne=()=>{T!==void 0&&(w(T),A(null),U(!1),E(void 0))},K=()=>E(void 0),re=T!==void 0&&H,q=!l&&t.length===0&&!m;return(0,Q.jsxs)(`div`,{className:`combos-workspace-root`,children:[(0,Q.jsxs)(`aside`,{className:`combos-workspace-rail`,"aria-label":y(`cws.railAria`),children:[(0,Q.jsxs)(`div`,{className:`combos-workspace-rail-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`combos-workspace-rail-title`,children:y(`nav.combos`)}),(0,Q.jsx)(`div`,{className:`combos-workspace-rail-count`,children:t.length})]}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>{q?document.getElementById(`cwi-edit-id`)?.focus():p()},"aria-label":y(`cws.add`),children:[(0,Q.jsx)(I,{width:14,height:14}),` `,y(`cws.add`)]})]}),(0,Q.jsxs)(`div`,{className:`cwi-jev-quick-action`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>p(`jev-auto`),disabled:M,title:y(M?`cws.jev.exists`:`cws.jev.setupHint`),children:[(0,Q.jsx)(te,{width:14,height:14}),` `,y(`cws.jev.create`)]}),M&&(0,Q.jsx)(`span`,{className:`muted`,children:y(`cws.jev.exists`)})]}),t.length>0&&(0,Q.jsx)(`div`,{className:`cwi-search-row`,children:(0,Q.jsxs)(`div`,{className:`cwi-search-wrap`,children:[(0,Q.jsx)(se,{className:`cwi-search-icon`,"aria-hidden":`true`}),(0,Q.jsx)(`input`,{className:`input cwi-search-input`,value:x,onChange:e=>S(e.target.value),placeholder:y(`cws.searchPlaceholder`),"aria-label":y(`cws.searchPlaceholder`)})]})}),(0,Q.jsx)(`div`,{className:`combos-workspace-rail-list`,children:F.length===0&&t.length>0?(0,Q.jsx)(`p`,{className:`muted`,style:{padding:`16px`},children:y(`cws.noSearchResults`)}):(0,Q.jsx)(Q.Fragment,{children:[[`failover`,L.failover,`cws.group.failover`],[`round-robin`,L.roundRobin,`cws.group.roundRobin`],[`other`,L.other,`cws.group.other`]].map(([e,t,n])=>t.length>0?(0,Q.jsxs)(`div`,{className:`combos-workspace-rail-group`,children:[(0,Q.jsxs)(`div`,{className:`combos-workspace-rail-group-head`,children:[(0,Q.jsx)(`span`,{className:`pwi-dot`,"aria-hidden":`true`}),y(n),(0,Q.jsx)(`span`,{className:`combos-workspace-rail-count`,children:t.length})]}),t.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`combos-workspace-rail-row${z===e.id?` combos-workspace-rail-row--selected`:``}`,onClick:()=>G(e.id),"aria-current":z===e.id?`true`:void 0,children:[(0,Q.jsx)(`span`,{className:`combos-workspace-rail-icon`,"aria-hidden":`true`,children:(0,Q.jsx)(te,{width:16,height:16})}),(0,Q.jsx)(`span`,{className:`combos-workspace-rail-name`,children:e.model}),(0,Q.jsx)(`span`,{className:`combos-workspace-rail-meta`,children:e.targets.length===1?y(`cws.targetCountOne`):y(`cws.targetCount`,{count:e.targets.length})}),(0,Q.jsx)(Ye,{className:`combos-workspace-rail-chevron`,"aria-hidden":`true`})]},e.id))]},e):null)})})]}),(0,Q.jsx)(`div`,{className:`combos-workspace-main`,children:V&&B?(0,Q.jsx)(Qb,{apiBase:e,baseline:V,combos:t.filter(e=>e.id!==V.id),otherIds:ee,otherAliases:W,providerMap:b,providerQuotaStates:r,providers:i,models:a,capabilityModels:o,visionEnabled:c,onBack:()=>G(null),onSaved:e=>{U(!1),e.id===V.id?A({source:B,item:e}):(w(e.id),A(null)),u()},onRequestRemove:()=>O(V.id),onSave:d,onDirtyChange:U},V.id):q?(0,Q.jsx)(Qb,{apiBase:e,baseline:j,isCreate:!0,otherIds:[],otherAliases:[],providerMap:b,providerQuotaStates:r,providers:i,models:a,capabilityModels:o,visionEnabled:c,onSaved:e=>{U(!1),w(e.id),A(null),v(e.id)},onSave:d,onDirtyChange:U},`first-combo`):(0,Q.jsx)(nx,{combos:t,cataloguedComboIds:s,providerMap:b,providerQuotaStates:r,providers:i,onSelect:e=>G(e),onAdd:p})}),m&&(0,Q.jsx)(kb,{apiBase:e,combos:t,existingIds:t.map(e=>e.id),existingAliases:R,providerMap:b,providerQuotaStates:r,providers:i,models:a,capabilityModels:o,initialDraft:P,onClose:_,onSubmit:async e=>{let t=await d(e,!0);return t.ok&&(_(),v(e.id),w(e.id),A(null)),t}},`${h??`blank`}:${P?.decisionProvider??``}`),D&&(0,Q.jsx)($b,{model:t.find(e=>e.id===D)?.model??hi(D),onCancel:()=>O(null),onConfirm:()=>{(async()=>{let e=await f(D);O(null),e.ok&&(z===D&&(w(null),A(null)),u())})()}}),re&&(0,Q.jsx)(ex,{onKeep:K,onDiscard:ne})]})}function ix(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e.error;return typeof t==`string`&&t.trim()?t:void 0}function ax(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&e.success===!0}function ox(e){return oo(e)?.data??null}function sx(e){return oo(e)?.cachedAt??null}function cx({apiBase:e,active:t=!0,onCountChange:r}){let i=n(),a=`ocx.combos.workspace.v2:${e}`,o=(0,Z.useMemo)(()=>ox(a),[a]),[s,c]=(0,Z.useState)(o??null),[l,u]=(0,Z.useState)(``),[d,f]=(0,Z.useState)(!1),[p,m]=(0,Z.useState)(()=>Xg(window.location.hash)===void 0?null:`jev-auto`),[h,g]=(0,Z.useState)(()=>Xg(window.location.hash)??null),_=(0,Z.useCallback)(()=>{m(null),g(null),Xg(window.location.hash)!==void 0&&Yt(`models/combos`)},[]),v=(e,t)=>{u(e),f(t)};(0,Z.useEffect)(()=>{if(!l||!d)return;let e=window.setTimeout(()=>{u(``),f(!1)},5e3);return()=>window.clearTimeout(e)},[l,d]);let y=(0,Z.useCallback)(async t=>{let[n,r,i]=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||!i.ok)throw Error(`combo workspace load failed`);let o=await n.json(),s=await r.json(),l=await i.json(),u=Array.isArray(l)?l:Array.isArray(l?.models)?l.models:[],d=Ei(o),f=s.providers??{},p=L(f),m=Object.entries(f).map(([e,t])=>({name:e,disabled:!!t.disabled,hiddenFromPicker:t.adapter===`jev-decision`||!Object.hasOwn(p,e),authMode:t.authMode,adapter:t.adapter,baseUrl:t.baseUrl,...typeof t.defaultModel==`string`?{defaultModel:t.defaultModel}:{},...Array.isArray(t.models)?{models:t.models.filter(e=>typeof e==`string`)}:{}})),h=[],g=[],_=new Set,v=e=>Array.isArray(e)?e.flatMap(e=>{let t=typeof e==`string`?e.trim():``;return t?[t]:[]}):void 0;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`){_.add(r);continue}let i=Array.isArray(t.reasoningEfforts)?t.reasoningEfforts.filter(e=>typeof e==`string`):void 0,a=v(t.inputModalities),o=v(t.inputModalitiesDeclared),s={provider:n,id:r,namespaced:typeof t.namespaced==`string`?t.namespaced:void 0,...i?{reasoningEfforts:i}:{},...a&&a.length>0?{inputModalities:a}:{},...o&&o.length>0?{inputModalitiesDeclared:o}:{},visionSidecarConsumer:t.visionSidecarConsumer===!0};g.push(s),h.push(s)}for(let[e,t]of Object.entries(f)){let n=typeof t.defaultModel==`string`?t.defaultModel.trim():``;n&&!t.disabled&&(g.some(t=>t.provider===e&&t.id===n)||h.push({provider:e,id:n,namespaced:`${e}/${n}`}))}let y={combos:d,providers:m,models:h,capabilityModels:g,cataloguedComboIds:[..._]};return so(a,y),c(y),y},[e,a]),b=uo(a,[e],y,{isEmpty:()=>!1,initialData:o??void 0,initialDataCachedAt:sx(a),staleAfterMs:6e4,enabled:t}),{state:x}=b,[S,C]=(0,Z.useState)(void 0);(0,Z.useEffect)(()=>{if(!t)return;let n=!1;return fetch(`${e}/api/sidecar-settings`).then(e=>e.ok?e.json():null).then(e=>{if(n||!e||typeof e!=`object`)return;let t=e.vision;t&&typeof t==`object`&&C(t.enabled!==!1)}).catch(()=>{}),()=>{n=!0}},[t,e]);let[w,T]=(0,Z.useState)(()=>Date.now()),E=(0,Z.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||T(Date.now()),r&&typeof r==`object`&&!Array.isArray(r)?r:{}},[e]),D=uo(`ocx.combos.provider-quotas.v1:${e}`,[e],E,{isEmpty:()=>!1,pollMs:6e4,pauseWhenHidden:!0,enabled:t}),O=t&&D.lastAttemptOk?D.data?.reports:void 0,k=Pi(O,w),A=Ni(O,w);(0,Z.useEffect)(()=>{if(!t)return;let e=()=>T(Date.now()),n=window.setTimeout(e,A===void 0?0:Math.max(0,A-Date.now())),r=mt(()=>{pt()||e()});return()=>{window.clearTimeout(n),r()}},[t,e,D.data,D.lastAttemptOk,A]);let j=x.data??s??void 0,M=j?.combos??[];(0,Z.useEffect)(()=>{j&&r?.(M.length)},[M.length,j,r]);let N=j?.providers??[],P=j?.models??[],F=j?.capabilityModels??P,I=new Set(j?.cataloguedComboIds??[]),R=async(t,n,r)=>{try{let a=await fetch(`${e}/api/combos`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(zi(t,{...r?{renameFrom:r}:{},...t.imageInput===`disabled`?{}:{visionSidecarTargets:mb(t.targets,F)}}))}),o=a.ok?await a.json():await a.json().catch(()=>null),s=ix(o);if(!a.ok||s||!ax(o)){let e=s||i(`cws.saveFailed`);return v(e,!1),{ok:!1,error:e}}return b.refresh(),v(r?i(`cws.renamed`,{from:hi(r),to:t.model}):n?i(`cws.created`,{model:t.model}):i(`cws.saved`),!0),{ok:!0}}catch{let e=i(`cws.saveFailed`);return v(e,!1),{ok:!1,error:e}}},z=async t=>{try{let n=await fetch(`${e}/api/combos?id=${encodeURIComponent(t)}`,{method:`DELETE`}),r=n.ok?await n.json():await n.json().catch(()=>null),a=ix(r);if(!n.ok||a||!ax(r)){let e=a||i(`cws.removeFailed`);return v(e,!1),{ok:!1,error:e}}return b.refresh(),v(i(`cws.removed`,{id:t}),!0),{ok:!0}}catch{let e=i(`cws.removeFailed`);return v(e,!1),{ok:!1,error:e}}};if(x.showSkeleton&&!j)return(0,Q.jsx)(lb,{label:i(`cws.loading`),rows:5});if(x.kind===`failed-cold`&&!j){let e=x.error instanceof Error?x.error.message:i(`cws.loadFailed`);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)($,{tone:`err`,children:e}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>b.refresh(),children:i(`common.retry`)})]})}return(0,Q.jsxs)(`div`,{className:`combos-workspace-shell`,children:[l&&(0,Q.jsx)(`div`,{className:`combos-workspace-shell-banner`,children:(0,Q.jsx)($,{tone:d?`ok`:`err`,children:l})}),x.showError&&(0,Q.jsx)(`div`,{className:`combos-workspace-shell-banner`,children:(0,Q.jsx)($,{tone:`err`,children:i(`cws.loadFailed`)})}),(0,Q.jsxs)(`div`,{className:`combos-workspace-shell-body`,"aria-busy":x.refreshing,children:[(0,Q.jsx)(`span`,{className:`sr-only`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:x.refreshing?i(`common.loading`):``}),(0,Q.jsx)(rx,{apiBase:e,combos:M,providerQuotaStates:k,providers:N,models:P,capabilityModels:F,cataloguedComboIds:I,visionEnabled:S,loading:!1,onRefresh:()=>{b.refresh(),D.refresh()},onSave:R,onRemove:z,onAdd:(e=`blank`)=>m(e),adding:p!==null,addIntent:p??void 0,addDecisionProvider:h,onCloseAdd:_,onCreated:()=>b.refresh()})]})]})}var lx=0;function ux(){return lx+=1,`candidate-${lx}`}function dx(e,t){return{provider:e,model:t,key:ux()}}function fx(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 px(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n={requiredSuites:fx(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 mx={latency:`0.55`,health:`0.25`,cost:`0.1`,quota:`0.1`},hx={capability:`exclude`,health:`penalize`,quota:`penalize`,cost:`penalize`};function gx(e){return e===!0?`true`:e===!1?`false`:``}function _x(e){return e===void 0?``:String(e)}function vx(e=``,t=``){return{id:``,alias:``,candidates:[dx(e,t)],require:{minContextWindow:``,minQuotaHeadroom:``,tools:``,imageInput:``,structuredOutput:``,reasoningEffort:``,serviceTier:``,localOnly:``,remoteAllowed:``,encryptedCodexTasks:``},optimize:{...mx},limits:{maxEstimatedCostUsd:``,onUnknownCost:`allow`},unknownEvidence:{...hx},compatibility:{enabled:!1,requiredSuites:[],minStatus:``,maxEvidenceAgeMs:``,unknownEvidence:`exclude`,degradedEvidence:`penalize`}}}function yx(e){let t=px(e.compatibility);return{id:e.id,alias:e.alias??``,candidates:e.candidates.map(e=>({...e,key:ux()})),require:{minContextWindow:_x(e.require.minContextWindow),minQuotaHeadroom:_x(e.require.minQuotaHeadroom),tools:gx(e.require.tools),imageInput:gx(e.require.imageInput),structuredOutput:gx(e.require.structuredOutput),reasoningEffort:e.require.reasoningEffort??``,serviceTier:e.require.serviceTier??``,localOnly:gx(e.require.localOnly),remoteAllowed:gx(e.require.remoteAllowed),encryptedCodexTasks:gx(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:_x(e.limits.maxEstimatedCostUsd),onUnknownCost:e.limits.onUnknownCost===`exclude`?`exclude`:`allow`},unknownEvidence:{...e.unknownEvidence},compatibility:{enabled:!!t,requiredSuites:t?.requiredSuites??[],minStatus:t?.minStatus??``,maxEvidenceAgeMs:_x(t?.maxEvidenceAgeMs),unknownEvidence:t?.unknownEvidence??`exclude`,degradedEvidence:t?.degradedEvidence??`penalize`}}}function bx(e){let t=e.trim();return t?Number(t):void 0}function xx(e){if(e===`true`)return!0;if(e===`false`)return!1}function Sx(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function Cx(e,t,n){let r=Sx({minContextWindow:bx(e.require.minContextWindow),minQuotaHeadroom:bx(e.require.minQuotaHeadroom),tools:xx(e.require.tools),imageInput:xx(e.require.imageInput),structuredOutput:xx(e.require.structuredOutput),reasoningEffort:e.require.reasoningEffort.trim()||void 0,serviceTier:e.require.serviceTier.trim()||void 0,localOnly:xx(e.require.localOnly),remoteAllowed:xx(e.require.remoteAllowed),encryptedCodexTasks:xx(e.require.encryptedCodexTasks)}),i=bx(e.limits.maxEstimatedCostUsd),a=e.compatibility.enabled?Sx({requiredSuites:e.compatibility.requiredSuites,minStatus:e.compatibility.minStatus||void 0,maxEvidenceAgeMs:bx(e.compatibility.maxEvidenceAgeMs),unknownEvidence:e.compatibility.unknownEvidence,degradedEvidence:e.compatibility.degradedEvidence}):void 0,o=Sx({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 wx(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 Tx(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&e.success===!0}function Ex(e,t){return e.filter(e=>e.provider===t)}var Dx={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`},vi:{maxEvidenceAgeMs:`Tuổi bằng chứng tối đa (ms)`,unknownEvidence:`Bằng chứng không xác định`,degradedEvidence:`Bằng chứng bị suy giảm`},pt:{maxEvidenceAgeMs:`Idade máxima da evidência (ms)`,unknownEvidence:`Evidência desconhecida`,degradedEvidence:`Evidência degradada`}},Ox=[`tools`,`imageInput`,`structuredOutput`,`localOnly`,`remoteAllowed`,`encryptedCodexTasks`],kx=[`reasoningEffort`,`serviceTier`],Ax={minContextWindow:{min:1,max:void 0,step:1},minQuotaHeadroom:{min:0,max:1,step:`any`}},jx=Object.keys(Ax),Mx=[`latency`,`health`,`cost`,`quota`],Nx=[`capability`,`health`,`quota`,`cost`],Px=[`allow`,`penalize`,`exclude`],Fx=[`allow`,`exclude`];function Ix(e){return`${e.evidenceLayer}:${e.suiteId}`}function Lx(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Rx(e){let t=new Set,n=[];for(let r of e){if(!Lx(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=Ix(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 zx(e,t){return e.some(e=>e.suiteId===t.suiteId&&e.evidenceLayer===t.evidenceLayer)}function Bx(e,t){return e===void 0?t:`${Math.round(e)}ms`}function Vx(e,t){return e==null?t:`${Math.round(e*100)}%`}function Hx(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 Ux(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 Wx(e){if(!e||typeof e!=`object`||Array.isArray(e))return[];let t=e.profiles;return Array.isArray(t)?t.filter(e=>Lx(e)?typeof e.id==`string`&&typeof e.model==`string`&&typeof e.revision==`string`&&Array.isArray(e.candidates)&&Lx(e.require)&&Lx(e.optimize)&&Lx(e.limits)&&Lx(e.unknownEvidence):!1).map(e=>{let t=px(`compatibility`in e?e.compatibility:void 0),n={...e};return delete n.compatibility,{...n,alias:e.alias??null,...t?{compatibility:t}:{}}}):[]}function Gx(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 Kx(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 qx({apiBase:e,active:t=!0,onCountChange:n}){let{locale:i,t:a}=r(),o=Dx[i],s=a(`routing.unavailable`),[c,l]=(0,Z.useState)([]),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)([]),[m,h]=(0,Z.useState)({}),[g,_]=(0,Z.useState)([]),[v,y]=(0,Z.useState)(``),[b,x]=(0,Z.useState)(null),[S,C]=(0,Z.useState)(null),[w,T]=(0,Z.useState)(null),[E,D]=(0,Z.useState)(!1),[O,k]=(0,Z.useState)(``),[A,j]=(0,Z.useState)(!1),[M,N]=(0,Z.useState)(!1),[P,F]=(0,Z.useState)(!1),[I,L]=(0,Z.useState)(null),[R,z]=(0,Z.useState)(``),[B,V]=(0,Z.useState)(!1),[H,U]=(0,Z.useState)([]),[ee,W]=(0,Z.useState)(!1),te=(0,Z.useRef)(null),G=(0,Z.useRef)(0),ne=(0,Z.useRef)(null),K=(0,Z.useRef)(!0),re=(0,Z.useCallback)(()=>{K.current=!1,ne.current?.abort(),G.current++},[]),q=(0,Z.useRef)(0),J=(0,Z.useCallback)((e,t)=>{T({message:e,ok:t})},[]);(0,Z.useEffect)(()=>{if(!w?.ok)return;let e=window.setTimeout(()=>T(null),5e3);return()=>window.clearTimeout(e)},[w]);let Y=(0,Z.useCallback)(()=>{q.current+=1,L(null),z(``),V(!1)},[]),ie=(0,Z.useCallback)(e=>{te.current=e,x(e),C(e?yx(e):null),T(null),Y()},[Y]),X=(0,Z.useCallback)(async t=>{if(!K.current)return;ne.current?.abort();let n=new AbortController;ne.current=n;let{signal:r}=n,i=++G.current;y(``);try{let[n,a,o,s,c]=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[u,f,m,g,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([]),c.ok?c.json().catch(()=>null):Promise.resolve(null)]);if(i!==G.current)return;let y=Wx(u),b=te.current,S=Kx(y,b?.id??null,t),w=m.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()]));te.current=S,l(y),x(S),C(S?yx(S):null),d(f),p(T),h(E),_(Gx(g)),v&&Array.isArray(v.scenarios)?(U(Rx(v.scenarios)),W(!1)):(U([]),W(!0)),(!b||!S||b.id!==S.id||b.revision!==S.revision)&&Y()}catch(e){if(i!==G.current||r.aborted)return;y(e instanceof Error?e.message:String(e))}finally{ne.current===n&&(ne.current=null)}},[e,Y]);(0,Z.useEffect)(()=>{if(!t){re();return}K.current=!0;let e=window.setTimeout(()=>void X(),0);return()=>{window.clearTimeout(e),re()}},[t,re,X]),(0,Z.useEffect)(()=>{n?.(c.length)},[n,c.length]);let ae=f[0]??``,oe=m[ae]??Ex(g,ae)[0]?.id??``,se=()=>{te.current=null,x(null),C(vx(ae,oe)),T(null),Y()},ce=()=>{b?(C(yx(b)),T(null)):ie(c[0]??null)},le=async()=>{if(S&&!E){D(!0),T(null);try{let t=Cx(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 yn(n);if(!n.ok){let e=await n.json().catch(()=>null);J(wx(e)??a(`routing.loadFailed`),!1);return}if(!Tx(r)){J(wx(r)??a(`routing.loadFailed`),!1);return}await X(t.id),J(a(`common.ok`),!0)}catch(e){J(e instanceof Error?e.message:a(`routing.loadFailed`),!1)}finally{D(!1)}}},ue=async()=>{if(b&&!E&&await ha({message:a(`routing.removeConfirm`,{id:b.id}),confirmLabel:a(`common.remove`),tone:`danger`})){D(!0),T(null);try{let t=await fetch(`${e}/api/routing-profiles?id=${encodeURIComponent(b.id)}`,{method:`DELETE`}),n=await yn(t);if(!t.ok){let e=await t.json().catch(()=>null);J(wx(e)??a(`routing.loadFailed`),!1);return}if(!Tx(n)){J(wx(n)??a(`routing.loadFailed`),!1);return}te.current=null,await X(),J(a(`common.ok`),!0)}catch(e){J(e instanceof Error?e.message:a(`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:m[n]??Ex(g,n)[0]?.id??``}:{...r,model:n}:r);return{...r,candidates:i}})},fe=()=>{C(e=>e&&{...e,candidates:[...e.candidates,dx(ae,oe)]})},pe=e=>{C(t=>t&&{...t,candidates:t.candidates.filter((t,n)=>n!==e)})},me=async()=>{if(!b)return;let t=++q.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 i=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!==q.current)return;if(!i.ok){let e=await i.json().catch(()=>null);if(t!==q.current)return;z(wx(e)??a(`routing.dryRunError`,{status:i.status}));return}let o=await i.json();if(t!==q.current)return;L(o)}catch(e){if(t!==q.current)return;z(e instanceof Error?e.message:String(e))}finally{t===q.current&&V(!1)}},he=S?.candidates.map(e=>Ex(g,e.provider))??[];return(0,Q.jsxs)(`div`,{className:`page`,"data-page":`routing`,children:[(0,Q.jsxs)(`div`,{className:`row`,style:{display:`flex`,gap:8,justifyContent:`flex-end`,marginBottom:12},children:[(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:se,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`+`}),` `,a(`routing.createProfile`)]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void X(),children:a(`common.retry`)})]}),v?(0,Q.jsxs)($,{tone:`err`,children:[a(`routing.loadFailed`),`: `,v]}):null,w?(0,Q.jsx)($,{tone:w.ok?`ok`:`err`,children:w.message}):null,c.length>0?(0,Q.jsx)(`div`,{className:`panel`,style:{display:`flex`,flexDirection:`column`,gap:12},children:c.map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`model-card`,style:{textAlign:`left`,cursor:`pointer`},onClick:()=>ie(e),"aria-pressed":b?.id===e.id,children:(0,Q.jsxs)(`div`,{className:`card-badges`,children:[(0,Q.jsx)(`strong`,{children:e.id}),(0,Q.jsx)(`span`,{className:`badge badge-muted`,children:e.model}),(0,Q.jsxs)(`span`,{className:`badge badge-muted`,children:[a(`routing.revision`),`: `,e.revision]})]})},e.id))}):null,S?(0,Q.jsxs)(`form`,{className:`panel`,style:{marginTop:14,display:`flex`,flexDirection:`column`,gap:16},onSubmit:e=>{e.preventDefault(),le()},children:[(0,Q.jsxs)(`div`,{className:`page-head`,children:[(0,Q.jsxs)(`h3`,{children:[a(`routing.detail`),`: `,b?.model??(0,Q.jsx)(`code`,{children:`policy/…`})]}),b?(0,Q.jsxs)(`span`,{className:`badge badge-muted`,children:[a(`routing.revision`),`: `,b.revision]}):null]}),(0,Q.jsxs)(`div`,{className:`model-grid`,children:[(0,Q.jsxs)(`label`,{className:`field-label`,children:[(0,Q.jsx)(`code`,{children:`id`}),(0,Q.jsx)(`input`,{className:`input`,required:!0,disabled:b!==null,value:S.id,onChange:e=>C(t=>t&&{...t,id:e.target.value})})]}),(0,Q.jsxs)(`label`,{className:`field-label`,children:[(0,Q.jsx)(`code`,{children:`alias`}),(0,Q.jsx)(`input`,{className:`input`,value:S.alias,onChange:e=>C(t=>t&&{...t,alias:e.target.value})})]})]}),(0,Q.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:a(`routing.candidates`)}),(0,Q.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:10},children:[S.candidates.map((e,t)=>{let n=[...new Set([e.provider,...f])].filter(Boolean),r=`routing-model-options-${t}`;return(0,Q.jsxs)(`div`,{className:`model-card`,children:[(0,Q.jsxs)(`div`,{className:`model-grid`,children:[(0,Q.jsxs)(`label`,{className:`field-label`,children:[(0,Q.jsx)(`code`,{children:`provider`}),(0,Q.jsxs)(`select`,{className:`input`,required:!0,value:e.provider,onChange:e=>de(t,`provider`,e.target.value),children:[(0,Q.jsx)(`option`,{value:``,disabled:!0,children:a(`routing.none`)}),n.map(e=>(0,Q.jsx)(`option`,{value:e,children:e},e))]})]}),(0,Q.jsxs)(`label`,{className:`field-label`,children:[(0,Q.jsx)(`code`,{children:`model`}),(0,Q.jsx)(`input`,{className:`input`,required:!0,list:r,value:e.model,onChange:e=>de(t,`model`,e.target.value)}),(0,Q.jsx)(`datalist`,{id:r,children:he[t]?.map(e=>(0,Q.jsx)(`option`,{value:e.id},e.id))})]})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:S.candidates.length===1,onClick:()=>pe(t),"aria-label":a(`routing.removeCandidate`,{provider:e.provider,model:e.model}),children:a(`common.remove`)})]},e.key)}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:fe,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`+`}),` `,a(`routing.candidate`)]})]})]}),(0,Q.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:a(`routing.require`)}),(0,Q.jsxs)(`div`,{className:`model-grid`,children:[jx.map(e=>(0,Q.jsxs)(`label`,{className:`field-label`,children:[(0,Q.jsx)(`code`,{children:e}),(0,Q.jsx)(`input`,{className:`input`,type:`number`,min:Ax[e].min,max:Ax[e].max,step:Ax[e].step,value:S.require[e],onChange:t=>C(n=>n&&{...n,require:{...n.require,[e]:t.target.value}})})]},e)),kx.map(e=>(0,Q.jsxs)(`label`,{className:`field-label`,children:[(0,Q.jsx)(`code`,{children:e}),(0,Q.jsx)(`input`,{className:`input`,value:S.require[e],onChange:t=>C(n=>n&&{...n,require:{...n.require,[e]:t.target.value}})})]},e)),Ox.map(e=>(0,Q.jsxs)(`label`,{className:`field-label`,children:[(0,Q.jsx)(`code`,{children:e}),(0,Q.jsxs)(`select`,{className:`input`,value:S.require[e],onChange:t=>C(n=>n&&{...n,require:{...n.require,[e]:t.target.value}}),children:[(0,Q.jsx)(`option`,{value:``,children:a(`routing.none`)}),(0,Q.jsx)(`option`,{value:`true`,children:a(`routing.yes`)}),(0,Q.jsx)(`option`,{value:`false`,children:a(`routing.no`)})]})]},e))]})]}),(0,Q.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:a(`routing.optimize`)}),(0,Q.jsx)(`div`,{className:`model-grid`,children:Mx.map(e=>(0,Q.jsxs)(`label`,{className:`field-label`,children:[(0,Q.jsx)(`code`,{children:e}),(0,Q.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,Q.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:a(`routing.limits`)}),(0,Q.jsxs)(`label`,{className:`field-label`,children:[(0,Q.jsx)(`code`,{children:`maxEstimatedCostUsd`}),(0,Q.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,Q.jsxs)(`label`,{className:`field-label`,children:[(0,Q.jsx)(`code`,{children:`onUnknownCost`}),(0,Q.jsx)(`select`,{className:`input`,value:S.limits.onUnknownCost,onChange:e=>C(t=>t&&{...t,limits:{...t.limits,onUnknownCost:e.target.value}}),children:Fx.map(e=>(0,Q.jsx)(`option`,{value:e,children:a(`routing.unknownEvidence.${e}`)},e))})]})]}),(0,Q.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:a(`routing.unknownEvidence`)}),(0,Q.jsx)(`div`,{className:`model-grid`,children:Nx.map(e=>(0,Q.jsxs)(`label`,{className:`field-label`,children:[(0,Q.jsx)(`code`,{children:e}),(0,Q.jsx)(`select`,{className:`input`,value:S.unknownEvidence[e],onChange:t=>C(n=>n&&{...n,unknownEvidence:{...n.unknownEvidence,[e]:t.target.value}}),children:Px.map(e=>(0,Q.jsx)(`option`,{value:e,children:a(`routing.unknownEvidence.${e}`)},e))})]},e))})]}),(0,Q.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:a(`routing.compatibility.title`)}),(0,Q.jsxs)(`label`,{className:`checkbox`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:S.compatibility.enabled,onChange:e=>C(t=>t&&{...t,compatibility:{...t.compatibility,enabled:e.target.checked}})}),a(`routing.compatibility.enabled`)]}),S.compatibility.enabled?(0,Q.jsxs)(`div`,{className:`model-grid`,style:{marginTop:10},children:[(0,Q.jsxs)(`div`,{className:`field-label`,style:{gridColumn:`1 / -1`},children:[a(`routing.compatibility.requiredSuites`),ee?(0,Q.jsx)(`div`,{style:{marginTop:6},children:(0,Q.jsx)($,{tone:`warn`,children:a(`routing.compatibility.catalogUnavailable`)})}):null,H.length>0?(0,Q.jsx)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:4,marginTop:6},children:H.map(e=>(0,Q.jsxs)(`label`,{className:`checkbox`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:zx(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,Q.jsxs)(`span`,{children:[e.suiteId,` `,(0,Q.jsxs)(`span`,{className:`muted`,children:[`(`,a(`routing.compatibility.layer.${e.evidenceLayer}`),`)`]})]})]},e.key))}):null]}),(0,Q.jsxs)(`label`,{className:`field-label`,children:[a(`routing.compatibility.minStatus`),(0,Q.jsxs)(`select`,{className:`input`,value:S.compatibility.minStatus,onChange:e=>C(t=>t&&{...t,compatibility:{...t.compatibility,minStatus:e.target.value}}),children:[(0,Q.jsx)(`option`,{value:``,children:a(`routing.none`)}),(0,Q.jsx)(`option`,{value:`PROBED`,children:a(`lab.verdict.PROBED`)}),(0,Q.jsx)(`option`,{value:`VERIFIED`,children:a(`lab.verdict.VERIFIED`)})]})]}),(0,Q.jsxs)(`label`,{className:`field-label`,children:[o.maxEvidenceAgeMs,(0,Q.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,Q.jsxs)(`label`,{className:`field-label`,children:[o.unknownEvidence,(0,Q.jsx)(`select`,{className:`input`,value:S.compatibility.unknownEvidence,onChange:e=>C(t=>t&&{...t,compatibility:{...t.compatibility,unknownEvidence:e.target.value}}),children:Px.map(e=>(0,Q.jsx)(`option`,{value:e,children:a(`routing.unknownEvidence.${e}`)},e))})]}),(0,Q.jsxs)(`label`,{className:`field-label`,children:[o.degradedEvidence,(0,Q.jsx)(`select`,{className:`input`,value:S.compatibility.degradedEvidence,onChange:e=>C(t=>t&&{...t,compatibility:{...t.compatibility,degradedEvidence:e.target.value}}),children:Px.map(e=>(0,Q.jsx)(`option`,{value:e,children:a(`routing.unknownEvidence.${e}`)},e))})]})]}):null]}),(0,Q.jsxs)(`div`,{style:{display:`flex`,gap:8,flexWrap:`wrap`},children:[(0,Q.jsx)(`button`,{type:`submit`,className:`btn btn-primary`,disabled:E,children:a(E?`common.saving`:`common.save`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:E,onClick:ce,children:a(`common.cancel`)}),b?(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:E,onClick:()=>void ue(),children:a(`common.remove`)}):null]})]}):null,b&&(0,Q.jsxs)(`div`,{className:`panel`,style:{marginTop:14,display:`flex`,flexDirection:`column`,gap:10},children:[(0,Q.jsx)(`h3`,{children:a(`routing.dryRun`)}),(0,Q.jsxs)(`label`,{className:`field-label`,htmlFor:`routing-context`,children:[a(`routing.dryRunContext`),(0,Q.jsx)(`input`,{id:`routing-context`,className:`input`,type:`number`,min:1,value:O,onChange:e=>{k(e.target.value),Y()}})]}),(0,Q.jsxs)(`label`,{className:`checkbox`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:A,onChange:e=>{j(e.target.checked),Y()}}),a(`routing.dryRunTools`)]}),(0,Q.jsxs)(`label`,{className:`checkbox`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:M,onChange:e=>{N(e.target.checked),Y()}}),a(`routing.dryRunImage`)]}),(0,Q.jsxs)(`label`,{className:`checkbox`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:P,onChange:e=>{F(e.target.checked),Y()}}),a(`routing.dryRunStructured`)]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!b||B,onClick:()=>void me(),children:a(`routing.dryRunRun`)}),R?(0,Q.jsx)($,{tone:`err`,children:R}):null,I?(0,Q.jsxs)(`table`,{className:`tbl`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:a(`routing.candidate`)}),(0,Q.jsx)(`th`,{children:a(`routing.eligible`)}),(0,Q.jsx)(`th`,{children:a(`routing.exclusions`)}),(0,Q.jsx)(`th`,{children:a(`routing.costCap`)}),(0,Q.jsx)(`th`,{children:a(`routing.score`)})]})}),(0,Q.jsx)(`tbody`,{children:I.candidates.map((e,t)=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsxs)(`td`,{children:[e.provider,`/`,e.model,t===I.selectedIndex?` ✓ (${a(`routing.selected`)})`:``]}),(0,Q.jsx)(`td`,{children:e.eligible?a(`routing.yes`):a(`routing.no`)}),(0,Q.jsx)(`td`,{children:e.exclusions.map(e=>Ux(e.code,a)).join(`, `)||a(`routing.none`)}),(0,Q.jsx)(`td`,{children:Hx(e.cost?.capOutcome,a,s)}),(0,Q.jsx)(`td`,{children:e.score?e.score.total.toFixed(3):s})]},`${e.provider}/${e.model}`))})]}):null]}),c.length>0&&(0,Q.jsxs)(`div`,{className:`panel`,style:{marginTop:14,display:`flex`,flexDirection:`column`,gap:10},children:[(0,Q.jsx)(`h3`,{children:a(`routing.analytics`)}),u?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`card-badges`,children:[(0,Q.jsxs)(`span`,{className:`badge badge-muted`,children:[a(`routing.analyticsTotal`),`: `,u.totalRequests]}),(0,Q.jsxs)(`span`,{className:`badge badge-muted`,children:[a(`routing.analyticsSuccessRate`),`: `,Vx(u.successRate,s)]}),(0,Q.jsxs)(`span`,{className:`badge badge-muted`,children:[a(`routing.analyticsFallbackRate`),`: `,Vx(u.fallbackRate,s)]}),(0,Q.jsxs)(`span`,{className:`badge badge-muted`,children:[a(`routing.analyticsP50`),`: `,Bx(u.durationMs.p50,s)]}),(0,Q.jsxs)(`span`,{className:`badge badge-muted`,children:[a(`routing.analyticsP95`),`: `,Bx(u.durationMs.p95,s)]}),(0,Q.jsxs)(`span`,{className:`badge badge-muted`,children:[a(`routing.analyticsP99`),`: `,Bx(u.durationMs.p99,s)]}),(0,Q.jsxs)(`span`,{className:`badge badge-muted`,children:[a(`routing.analyticsCooldown`),`: `,u.cooldownTriggeringFailures]}),(0,Q.jsxs)(`span`,{className:`badge badge-muted`,children:[a(`routing.analyticsConfidence`),`: `,u.confidence??s]}),u.historyTruncated?(0,Q.jsx)(`span`,{className:`badge badge-muted`,children:a(`routing.analyticsTruncated`)}):null]}),(0,Q.jsxs)(`table`,{className:`tbl`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:a(`routing.candidate`)}),(0,Q.jsx)(`th`,{children:a(`routing.analyticsRequests`)}),(0,Q.jsx)(`th`,{children:a(`routing.analyticsSuccessRate`)}),(0,Q.jsx)(`th`,{children:a(`routing.analyticsP50`)})]})}),(0,Q.jsx)(`tbody`,{children:u.breakdown.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsxs)(`td`,{children:[e.provider,`/`,e.model]}),(0,Q.jsx)(`td`,{children:e.requests}),(0,Q.jsx)(`td`,{children:Vx(e.successRate,s)}),(0,Q.jsx)(`td`,{children:Bx(e.p50DurationMs,s)})]},`${e.provider}/${e.model}`))})]})]}):(0,Q.jsx)(`p`,{className:`muted`,children:a(`routing.analyticsEmpty`)})]})]})}var Jx=[`protocol_conformance`,`live_route_compatibility`,`task_effectiveness`],Yx=[`UNKNOWN`,`CLAIMED`,`PROBED`,`VERIFIED`,`DEGRADED`,`BLOCKED`,`UNSUPPORTED`],Xx=[`present`,`corrupt`,`purged_unavailable`];function Zx(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Qx(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function $x(e){return e===null||typeof e==`string`}function eS(e){return e===void 0||typeof e==`number`&&Number.isFinite(e)}function tS(e){if(!Zx(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(!eS(e[t]))return null;return e.projectionSpecVersion!==void 0&&typeof e.projectionSpecVersion!=`string`?null:e}function nS(e){return!Zx(e)||typeof e.projectionKey!=`string`||e.projectionKey.length===0||typeof e.subjectId!=`string`||e.subjectId.length===0||typeof e.evidenceLayer!=`string`||!Jx.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`||!Yx.includes(e.verdict)||typeof e.asOf!=`number`||!Number.isFinite(e.asOf)||!Qx(e.scenarioManifestDigests)||!$x(e.claimSourceDigest)||!Qx(e.contributingEventIds)||!Qx(e.contradictingEventIds)||!Qx(e.notes)?null:e}function rS(e){return!Zx(e)||!Array.isArray(e.verdicts)?{verdicts:[],hasMore:!1}:{verdicts:e.verdicts.map(nS).filter(e=>e!==null),hasMore:e.hasMore===!0,nextCursor:typeof e.nextCursor==`string`?e.nextCursor:void 0}}function iS(e){return!Zx(e)||!Array.isArray(e.subjects)?{subjects:[],hasMore:!1}:{subjects:e.subjects.filter(e=>Zx(e)&&typeof e.subjectId==`string`&&typeof e.subjectKind==`string`),hasMore:e.hasMore===!0,nextCursor:typeof e.nextCursor==`string`?e.nextCursor:void 0}}function aS(e){return!Zx(e)||!Zx(e.subject)||typeof e.subject.subjectKind!=`string`?null:e.subject}function oS(e){return!Zx(e)||typeof e.eventId!=`string`||typeof e.subjectId!=`string`||typeof e.evidenceLayer!=`string`||!Jx.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`||!$x(e.exclusionReason)?null:e}function sS(e){return!Zx(e)||!Array.isArray(e.observations)?{observations:[],hasMore:!1}:{observations:e.observations.map(oS).filter(e=>e!==null),hasMore:e.hasMore===!0,nextCursor:typeof e.nextCursor==`string`?e.nextCursor:void 0}}function cS(e){if(!Zx(e)||!Zx(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`||!$x(t.exclusionReason)?null:t}function lS(e){if(!Zx(e)||!Zx(e.artifact))return null;let t=e.artifact;return typeof t.digest!=`string`||typeof t.status!=`string`||!Xx.includes(t.status)||!$x(t.artifactClass)||!$x(t.mediaType)||t.byteCount!==null&&(typeof t.byteCount!=`number`||!Number.isFinite(t.byteCount))||!$x(t.lastError)?null:t}function uS(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 dS(){return{protocol_conformance:[],live_route_compatibility:[],task_effectiveness:[]}}function fS(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:dS()},r.set(t.subjectId,e)),e.byLayer[t.evidenceLayer].push(t)}return[...r.values()].sort((e,t)=>e.subjectId.localeCompare(t.subjectId))}function pS(e){return e.length<=16?e:`${e.slice(0,8)}.${e.slice(-6)}`}function mS(e,t){return!Number.isFinite(e)||e<=0?`-`:new Date(e).toLocaleString(t)}function hS(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]}function gS(e){if(!e)return{};let t=typeof e.inboundProtocol==`string`?Um(e.inboundProtocol):void 0,n=typeof e.upstreamProtocol==`string`?Um(e.upstreamProtocol):void 0;return{...t?{inbound:t}:{},...n?{upstream:n}:{}}}function _S(e){return e.inbound!==``||e.upstream!==``}function vS(e,t){return!_S(t)||!(!e||t.inbound&&e.inbound!==t.inbound||t.upstream&&e.upstream!==t.upstream)}function yS(e,t,n){return _S(n)?e.filter(e=>vS(t.get(e.subjectId),n)):e}function bS(e,t){return _S(e)?t.some(e=>Jx.some(t=>e.byLayer[t].length>0))?`evidence`:`unverified`:`any`}function xS(){let e=n();return t=>t?Oh(t,e):e(`compatProtocol.anyProtocol`)}function SS({value:e,onChange:t}){let r=n(),i=xS(),a=[{value:``,label:r(`lab.filter.all`)},...Tm.map(e=>({value:e,label:i(e)}))];return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`lab-filter-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`lab-filter-inbound`,children:r(`compatProtocol.filter.inbound`)}),(0,Q.jsx)(dn,{id:`lab-filter-inbound`,value:e.inbound,options:a,onChange:n=>t({...e,inbound:n}),label:r(`compatProtocol.filter.inbound`),portal:!1})]}),(0,Q.jsxs)(`div`,{className:`lab-filter-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`lab-filter-upstream`,children:r(`compatProtocol.filter.upstream`)}),(0,Q.jsx)(dn,{id:`lab-filter-upstream`,value:e.upstream,options:a,onChange:n=>t({...e,upstream:n}),label:r(`compatProtocol.filter.upstream`),portal:!1})]})]})}function CS({filter:e,evidence:t,resolution:r}){let i=n(),a=xS();if(!_S(e))return null;let o=i(`compatProtocol.pair`,{inbound:a(e.inbound),upstream:a(e.upstream)});return(0,Q.jsxs)(`div`,{className:`lab-protocol-status`,"data-pair-evidence":r.loading?`loading`:t,children:[r.loading?(0,Q.jsx)(`p`,{className:`muted small`,role:`status`,children:i(`compatProtocol.loading`)}):t===`unverified`?(0,Q.jsx)(`p`,{className:`lab-protocol-unverified`,role:`status`,children:i(`compatProtocol.unverified`,{pair:o})}):null,r.unresolved>0&&!r.loading&&(0,Q.jsx)(`p`,{className:`muted small`,children:i(`compatProtocol.unresolved`,{count:r.unresolved})}),(0,Q.jsx)(`p`,{className:`muted small`,children:i(`compatProtocol.axisNote`)})]})}var wS=50,TS=200,ES=6,DS=200;async function OS(e,t,n){return vn(await fetch(`${e}${t}`,{signal:n}))}function kS(e,t){let n=new URLSearchParams({limit:String(wS)});for(let[t,r]of Object.entries(e))r&&n.set(t,r);return t&&n.set(`cursor`,t),n.toString()}var AS=class extends Error{};function jS(){return new AS}function MS(e,t,n){if(e.hasMore!==void 0&&typeof e.hasMore!=`boolean`||e.nextCursor!==void 0&&typeof e.nextCursor!=`string`||t&&!n)throw jS()}function NS(e){if(!Zx(e)||!Array.isArray(e.verdicts))throw jS();let t=rS(e);if(t.verdicts.length!==e.verdicts.length)throw jS();return MS(e,t.hasMore,t.nextCursor),t}function PS(e){if(!Zx(e)||!Array.isArray(e.subjects))throw jS();let t=iS(e);if(t.subjects.length!==e.subjects.length)throw jS();return MS(e,t.hasMore,t.nextCursor),t}function FS(e){if(!Zx(e)||!Array.isArray(e.observations))throw jS();let t=sS(e);if(t.observations.length!==e.observations.length)throw jS();return MS(e,t.hasMore,t.nextCursor),t}async function IS(e,t){let n=tS(await OS(e,`/api/lab/status`,t));if(!n)throw jS();return n}async function LS(e,t,n,r){return NS(await OS(e,`/api/lab/verdicts?${kS({layer:t.layer,verdict:t.verdict,subjectId:t.subjectId,suiteId:t.suiteId},n)}`,r))}async function RS(e,t,n){return PS(await OS(e,`/api/lab/subjects?${kS({},t)}`,n))}async function zS(e){let t=[],n=new Set,r;for(let i=0;i<TS;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 AS;n.add(a),r=a}return{rows:t,truncated:!0}}async function BS(e,t){return zS(async n=>{let r=await RS(e,n,t);return{rows:r.subjects,hasMore:r.hasMore,nextCursor:r.nextCursor}})}async function VS(e,t,n){let r=aS(await OS(e,`/api/lab/subjects/${encodeURIComponent(t)}`,n));if(!r)throw jS();return r}async function HS(e,t,n,r){return FS(await OS(e,`/api/lab/observations?${kS({subjectId:t.subjectId,layer:t.layer,suiteId:t.suiteId},n)}`,r))}async function US(e,t,n){return zS(async r=>{let i=await HS(e,t,r,n);return{rows:i.observations,hasMore:i.hasMore,nextCursor:i.nextCursor}})}async function WS(e,t,n){let r=cS(await OS(e,`/api/lab/events/${encodeURIComponent(t)}`,n));if(!r)throw jS();return r}async function GS(e,t,n){let r=lS(await OS(e,`/api/lab/artifacts/${encodeURIComponent(t)}`,n));if(!r)throw jS();return r}function KS(e){if(!Zx(e)||e.verificationStatus!==`not_verification`||!Zx(e.summary))throw jS();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 jS();return{verificationStatus:`not_verification`,summary:t}}async function qS(e,t,n){return KS(await OS(e,`/api/lab/production-signals?${kS({subjectId:t})}`,n))}function JS(e,t){let n=new Set(t);return Object.keys(e).every(e=>n.has(e))}function YS(e){return typeof e==`string`&&/^[0-9a-f]{64}$/.test(e)}function XS(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function ZS(e){if(!Zx(e)||!JS(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(!Zx(n)||!JS(n,[`trustClass`,`status`,`bundleId`,`publisherKeyId`,`activeRecordCount`,`revokedRecordCount`])||n.trustClass!==`community_untrusted_v1`||n.status!==`cryptographically_valid`||!YS(n.bundleId)||!YS(n.publisherKeyId)||!XS(n.activeRecordCount)||!XS(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 QS(e,t){let n=ZS(await OS(e,`/api/lab/public/community`,t));if(!n)throw jS();return n}async function $S(e,t,n){let[r,i]=await Promise.all([IS(e,n),QS(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([LS(e,t,void 0,n),BS(e,n)]);return{status:r,verdicts:a.verdicts,subjects:o.rows,subjectsTruncated:o.truncated,hasMore:a.hasMore,nextCursor:a.nextCursor,community:i}}async function eC(e,t,n,r){return LS(e,t,n,r)}async function tC(e,t,n,r){let i=e.slice(0,DS),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 nC(e,t,n){let r=[...new Set([...t.contributingEventIds,...t.contradictingEventIds])],i=hS(t),a={subjectId:t.subjectId,layer:t.evidenceLayer,suiteId:t.suiteId},[o,s,c,l,u]=await Promise.all([VS(e,t.subjectId,n),US(e,a,n),tC(r,ES,n,t=>WS(e,t,n)),tC(i,ES,n,t=>GS(e,t,n)),qS(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 rC=6,iC=2e3,aC=`
7
- `,oC=new Map;function sC(e,t){return JSON.stringify([e,t])}function cC(e,t){for(oC.set(e,t);oC.size>iC;){let e=oC.keys().next().value;if(e===void 0)break;oC.delete(e)}}var lC={pairs:new Map,loading:!1,unresolved:0};function uC(e,t,n){let[,r]=(0,Z.useState)(0),i=n?t.slice(0,200):[],a=i.filter(t=>!oC.has(sC(e,t))).join(aC);if((0,Z.useEffect)(()=>{if(!a)return;let t=new AbortController,n=a.split(aC);return Promise.all(Array.from({length:Math.min(rC,n.length)},async()=>{for(let r=n.shift();r!==void 0;r=n.shift())try{let n=await VS(e,r,t.signal);cC(sC(e,r),gS(n))}catch{if(t.signal.aborted)return;cC(sC(e,r),null)}})).then(()=>{t.signal.aborted||r(e=>e+1)}),()=>t.abort()},[e,a]),!n)return lC;let o=new Map,s=Math.max(0,t.length-200);for(let t of i){let n=oC.get(sC(e,t));n?o.set(t,n):n===null&&(s+=1)}return{pairs:o,loading:a.length>0,unresolved:s}}var dC={protocol_conformance:`lab.layer.protocol_conformance`,live_route_compatibility:`lab.layer.live_route_compatibility`,task_effectiveness:`lab.layer.task_effectiveness`},fC={protocol_conformance:`lab.col.protocol`,live_route_compatibility:`lab.col.live`,task_effectiveness:`lab.col.task`},pC={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`},mC={present:`artifact.present`,corrupt:`artifact.corrupt`,purged_unavailable:`artifact.purged_unavailable`};function hC(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 gC({verdict:e,caption:t,label:n,selected:r,onSelect:i}){let a=`lab-verdict-badge${r?` lab-verdict-badge--selected`:``}`;return i?(0,Q.jsxs)(`button`,{type:`button`,className:a,"data-verdict":e,title:t,onClick:i,children:[(0,Q.jsx)(`span`,{children:n}),(0,Q.jsx)(`span`,{className:`suite`,children:t})]}):(0,Q.jsxs)(`span`,{className:a,"data-verdict":e,title:t,children:[(0,Q.jsx)(`span`,{children:n}),(0,Q.jsx)(`span`,{className:`suite`,children:t})]})}function _C({rows:e,t,selectedKey:n,onSelect:r}){return e.length===0?(0,Q.jsx)(`span`,{className:`muted`,children:`-`}):(0,Q.jsx)(`div`,{className:`lab-verdict-stack`,children:e.map(e=>(0,Q.jsx)(gC,{verdict:e.verdict,caption:e.suiteId,label:t(pC[e.verdict]),selected:n===e.projectionKey,onSelect:()=>r(e)},e.projectionKey))})}function vC({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:mS(r.builtAtMs,n)}),(0,Q.jsx)(`div`,{className:`lab-status-grid`,"aria-label":t(`lab.statusTitle`),children:i.map(e=>(0,Q.jsxs)(`div`,{className:`lab-status-card`,children:[(0,Q.jsx)(`span`,{className:`label`,children:e.label}),(0,Q.jsx)(`span`,{className:`value`,children:e.value})]},e.label))})}function yC({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,Q.jsxs)(`section`,{className:`lab-matrix-block`,"data-testid":`lab-community-evidence`,children:[(0,Q.jsx)(`h3`,{className:`lab-matrix-title`,children:y(t,`community.title`)}),(0,Q.jsx)(`p`,{className:`muted`,children:y(t,`community.notLocalVerdict`)}),(0,Q.jsxs)(`dl`,{className:`lab-detail-meta`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:y(t,`community.bundles`)}),(0,Q.jsx)(`dd`,{children:e.evidence.length})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:y(t,`community.activeRecords`)}),(0,Q.jsx)(`dd`,{children:n})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:y(t,`community.revokedRecords`)}),(0,Q.jsx)(`dd`,{children:r})]})]})]})}function bC({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,Q.jsxs)(`aside`,{className:`lab-detail-pane`,"aria-label":i(`lab.detailTitle`),children:[(0,Q.jsxs)(`div`,{className:`lab-detail-head`,children:[(0,Q.jsx)(`h3`,{children:pS(e.subjectId)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:o,children:i(`lab.detailClose`)})]}),(0,Q.jsxs)(`dl`,{className:`lab-detail-meta`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:i(`lab.col.layer`)}),(0,Q.jsx)(`dd`,{children:i(dC[e.evidenceLayer])})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:i(`lab.col.suite`)}),(0,Q.jsx)(`dd`,{className:`mono`,children:e.suiteId})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:i(`lab.col.verdict`)}),(0,Q.jsx)(`dd`,{children:i(pC[e.verdict])})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:i(`lab.col.asOf`)}),(0,Q.jsx)(`dd`,{children:mS(e.asOf,a)})]})]}),n&&(0,Q.jsx)(ub,{busy:!0,children:i(`common.loading`)}),r&&(0,Q.jsx)($,{tone:`err`,children:r}),t&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`section`,{className:`lab-detail-section`,children:[(0,Q.jsx)(`h4`,{children:i(`lab.detailSubject`)}),(0,Q.jsx)(`p`,{className:`mono`,children:t.subject.subjectKind})]}),t.production&&(0,Q.jsxs)(`section`,{className:`lab-detail-section`,"data-testid":`lab-production-signals`,children:[(0,Q.jsx)(`h4`,{children:i(`lab.production.title`)}),(0,Q.jsx)(`p`,{className:`muted`,children:i(`lab.production.notVerification`)}),(0,Q.jsxs)(`dl`,{className:`lab-detail-meta`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:i(`lab.production.attempts`)}),(0,Q.jsx)(`dd`,{children:t.production.summary.recentProductionAttempts})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:i(`lab.production.successes`)}),(0,Q.jsx)(`dd`,{children:t.production.summary.recentSuccessfulAttempts})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:i(`lab.production.routeErrors`)}),(0,Q.jsx)(`dd`,{children:t.production.summary.recentRouteErrorSignals})]}),t.production.summary.lastObservedProductionAttempt!==void 0&&(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:i(`lab.production.lastObserved`)}),(0,Q.jsx)(`dd`,{children:mS(t.production.summary.lastObservedProductionAttempt,a)})]})]})]}),t.observations.length>0&&(0,Q.jsxs)(`section`,{className:`lab-detail-section`,children:[(0,Q.jsx)(`h4`,{children:i(`lab.detailObservations`)}),(0,Q.jsx)(`ul`,{className:`lab-detail-list`,children:t.observations.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`span`,{className:`mono`,children:e.scenarioId}),(0,Q.jsx)(`span`,{children:e.outcome}),(0,Q.jsx)(`span`,{className:`muted`,children:mS(e.completedAt,a)})]},e.eventId))})]}),(t.events.length>0||s>0)&&(0,Q.jsxs)(`section`,{className:`lab-detail-section`,children:[(0,Q.jsxs)(`h4`,{children:[i(`lab.detailEvents`),t.events.length<s?` (${t.events.length}/${s})`:``]}),(0,Q.jsx)(`ul`,{className:`lab-detail-list`,children:t.events.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`span`,{className:`mono`,children:e.eventId}),(0,Q.jsx)(`span`,{children:e.eventKind})]},e.eventId))})]}),t.artifacts.length>0&&(0,Q.jsxs)(`section`,{className:`lab-detail-section`,children:[(0,Q.jsx)(`h4`,{children:i(`lab.detailArtifacts`)}),(0,Q.jsx)(`ul`,{className:`lab-detail-list`,children:t.artifacts.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`span`,{className:`mono`,title:e.digest,children:pS(e.digest)}),(0,Q.jsx)(`span`,{children:e.artifactClass??`-`}),(0,Q.jsx)(`span`,{children:y(a,mC[e.status])})]},e.digest))})]})]})]})}function xC({apiBase:e,active:t=!0,onCountChange:n}){let{t:i,locale:a}=r(),[o,s]=(0,Z.useState)({layer:``,verdict:``,subjectQuery:``,suiteId:``}),[c,l]=(0,Z.useState)(()=>l_()??a_),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)(null),[m,h]=(0,Z.useState)(!1),[g,_]=(0,Z.useState)(null),[v,b]=(0,Z.useState)(null),[x,S]=(0,Z.useState)(!1),[C,w]=(0,Z.useState)(null),T=(0,Z.useRef)(null),E=(0,Z.useRef)(null),D=(0,Z.useRef)(null),O=(0,Z.useMemo)(()=>uS(o),[o]),k=JSON.stringify(O),A=(0,Z.useCallback)(t=>$S(e,O,t),[e,O]),j=uo(`lab-matrix:${e}:${k}`,[e,k],A,{isEmpty:e=>e.verdicts.length===0,pollMs:6e4,enabled:t,pauseWhenHidden:!0}),M=(0,Z.useCallback)(()=>{T.current?.abort(),T.current=null,d(null),p(null),h(!1)},[]),N=(0,Z.useCallback)(()=>{D.current=null,E.current?.abort(),E.current=null,_(null),b(null),w(null),S(!1)},[]);(0,Z.useEffect)(()=>{T.current?.abort()},[j.data]),(0,Z.useEffect)(()=>()=>{T.current?.abort(),E.current?.abort()},[]);let P=(0,Z.useCallback)(e=>{N(),M(),s(e)},[N,M]),F=(0,Z.useCallback)(e=>{N(),l(e),t&&Yt(s_(e))},[t,N]);(0,Z.useEffect)(()=>{let e=()=>{let e=l_();e&&l(t=>t.inbound===e.inbound&&t.upstream===e.upstream?t:e)};return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]);let I=u!==null&&u.baseData===j.data&&u.queryKey===k?u:null,L=f!==null&&f.baseData===j.data&&f.queryKey===k?f.message:null,R=(0,Z.useMemo)(()=>{if(!t||!j.data?.status.projectionAvailable)return null;let e=j.data.status.verdictCount;return typeof e==`number`?e:j.data.verdicts.length+(I?.verdicts.length??0)},[t,j.data,I]);(0,Z.useEffect)(()=>{n?.(R)},[n,R]);let z=(0,Z.useMemo)(()=>j.data?[...j.data.verdicts,...I?.verdicts??[]]:[],[j.data,I]),B=(0,Z.useMemo)(()=>j.data?fS(z,j.data.subjects):[],[z,j.data]),V=_S(c),H=uC(e,(0,Z.useMemo)(()=>B.map(e=>e.subjectId),[B]),t&&V),U=(0,Z.useMemo)(()=>yS(B,H.pairs,c),[c,H.pairs,B]),ee=(0,Z.useMemo)(()=>{if(!V)return z;let e=new Set(U.map(e=>e.subjectId));return z.filter(t=>e.has(t.subjectId))},[z,U,V]),W=bS(c,U),te=(0,Z.useCallback)(async()=>{let t=I?.nextCursor??j.data?.nextCursor,n=j.data;if(!t||!n||m)return;T.current?.abort();let r=new AbortController;T.current=r;let a=k;p(null),h(!0);try{let i=await eC(e,O,t,r.signal);if(r.signal.aborted)return;d(e=>{let t=e?.baseData===n&&e.queryKey===a?e.verdicts:[];return{baseData:n,queryKey:a,verdicts:[...t,...i.verdicts],nextCursor:i.nextCursor,hasMore:i.hasMore}})}catch(e){r.signal.aborted||p({baseData:n,queryKey:a,message:hC(e,i(`lab.loadFailed`))})}finally{T.current===r&&(T.current=null,h(!1))}},[e,m,O,k,j.data,i,I]),G=(0,Z.useCallback)(async n=>{if(!t)return;E.current?.abort();let r=new AbortController;E.current=r,D.current=n.projectionKey,_(n),b(null),w(null),S(!0);try{let t=await nC(e,n,r.signal);!r.signal.aborted&&D.current===n.projectionKey&&b(t)}catch(e){!r.signal.aborted&&D.current===n.projectionKey&&w(hC(e,i(`lab.detailLoadFailed`)))}finally{E.current===r&&(E.current=null,!r.signal.aborted&&D.current===n.projectionKey&&S(!1))}},[t,e,i]),ne=j.refresh,K=(0,Z.useCallback)(()=>{N(),M(),ne({forceLoading:!0})},[N,ne,M]),re=t?g:null,q=I?I.hasMore:j.data?.hasMore??!1,J=[{value:``,label:i(`lab.filter.all`)},...Jx.map(e=>({value:e,label:i(dC[e])}))],Y=[{value:``,label:i(`lab.filter.all`)},...Yx.map(e=>({value:e,label:i(pC[e])}))],ie=[{value:``,label:i(`lab.filter.all`)},...(j.data?.subjects??[]).map(e=>({value:e.subjectId,label:`${pS(e.subjectId)} · ${e.subjectKind}`}))];if(j.state.showSkeleton)return(0,Q.jsx)(lb,{label:i(`lab.loading`),rows:5});let X=j.state.showError?hC(j.error,i(`lab.loadFailed`)):null,oe=j.data?.status,se=oe&&!oe.projectionAvailable,ce=oe?.projectionIncompatible===!0;return(0,Q.jsxs)(`div`,{className:`lab-page`,children:[(0,Q.jsx)(`div`,{className:`lab-toolbar`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:K,disabled:j.refreshing,children:[(0,Q.jsx)(ae,{}),i(`lab.refresh`)]})}),j.refreshing&&!j.state.showSkeleton&&(0,Q.jsx)(ub,{busy:!0,live:!X,children:i(`common.loading`)}),X&&(0,Q.jsx)($,{tone:`err`,children:X}),ce&&(0,Q.jsx)($,{tone:`err`,children:i(`lab.projectionIncompatible`)}),se&&!ce&&(0,Q.jsx)(fn,{title:i(`lab.projectionUnavailable`)}),se&&!ce&&(0,Q.jsx)(CS,{filter:c,evidence:`unverified`,resolution:{loading:!1,unresolved:0}}),j.data&&(0,Q.jsx)(yC,{community:j.data.community,locale:a}),j.data&&oe?.projectionAvailable&&!ce&&(0,Q.jsxs)(`div`,{className:`lab-layout`,children:[(0,Q.jsxs)(`div`,{className:`lab-main`,children:[(0,Q.jsx)(vC,{data:j.data,t:i,locale:a}),(0,Q.jsxs)(`div`,{className:`lab-filters`,children:[(0,Q.jsxs)(`div`,{className:`lab-filter-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`lab-filter-layer`,children:i(`lab.filter.layer`)}),(0,Q.jsx)(dn,{id:`lab-filter-layer`,value:o.layer,options:J,onChange:e=>P(t=>({...t,layer:e})),label:i(`lab.filter.layer`),portal:!1})]}),(0,Q.jsxs)(`div`,{className:`lab-filter-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`lab-filter-verdict`,children:i(`lab.filter.verdict`)}),(0,Q.jsx)(dn,{id:`lab-filter-verdict`,value:o.verdict,options:Y,onChange:e=>P(t=>({...t,verdict:e})),label:i(`lab.filter.verdict`),portal:!1})]}),(0,Q.jsxs)(`div`,{className:`lab-filter-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`lab-filter-subject`,children:i(`lab.filter.subject`)}),(0,Q.jsx)(dn,{id:`lab-filter-subject`,value:o.subjectQuery,options:ie,onChange:e=>P(t=>({...t,subjectQuery:e})),label:i(`lab.filter.subject`),portal:!1})]}),(0,Q.jsx)(SS,{value:c,onChange:F})]}),(0,Q.jsx)(CS,{filter:c,evidence:W,resolution:H}),U.length===0?(0,Q.jsx)(fn,{title:i(`lab.empty`)}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`lab-matrix-block`,children:[(0,Q.jsx)(`h3`,{className:`lab-matrix-title`,children:i(`lab.matrixTitle`)}),(0,Q.jsx)(`div`,{className:`lab-matrix-scroll`,children:(0,Q.jsxs)(`table`,{className:`lab-matrix`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:i(`lab.col.subject`)}),(0,Q.jsx)(`th`,{children:i(`lab.subjectKind`)}),Jx.map(e=>(0,Q.jsx)(`th`,{children:i(fC[e])},e))]})}),(0,Q.jsx)(`tbody`,{children:U.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`subject`,title:e.subjectId,children:pS(e.subjectId)}),(0,Q.jsx)(`td`,{className:`kind`,children:e.subjectKind||y(a,`subjectKindUnknown`)}),Jx.map(t=>(0,Q.jsx)(`td`,{children:(0,Q.jsx)(_C,{rows:e.byLayer[t],t:i,selectedKey:re?.projectionKey??null,onSelect:e=>{G(e)}})},t))]},e.subjectId))})]})})]}),(0,Q.jsxs)(`div`,{className:`lab-matrix-block`,children:[(0,Q.jsx)(`h3`,{className:`lab-matrix-title`,children:i(`lab.verdictsTitle`)}),(0,Q.jsx)(`div`,{className:`lab-matrix-scroll`,children:(0,Q.jsxs)(`table`,{className:`lab-detail-table`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:i(`lab.col.subject`)}),(0,Q.jsx)(`th`,{children:i(`lab.col.layer`)}),(0,Q.jsx)(`th`,{children:i(`lab.col.suite`)}),(0,Q.jsx)(`th`,{children:i(`lab.col.verdict`)}),(0,Q.jsx)(`th`,{children:i(`lab.col.asOf`)})]})}),(0,Q.jsx)(`tbody`,{children:ee.map(e=>{let t=re?.projectionKey===e.projectionKey;return(0,Q.jsxs)(`tr`,{className:t?`selected`:``,children:[(0,Q.jsx)(`td`,{className:`mono`,title:e.subjectId,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"data-verdict-detail":e.projectionKey,"aria-pressed":t,"aria-label":y(a,`selectVerdict`,{subject:pS(e.subjectId)}),onClick:()=>{G(e)},children:pS(e.subjectId)})}),(0,Q.jsx)(`td`,{children:i(dC[e.evidenceLayer])}),(0,Q.jsx)(`td`,{className:`mono`,children:e.suiteId}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(gC,{verdict:e.verdict,caption:e.suiteId,label:i(pC[e.verdict])})}),(0,Q.jsx)(`td`,{children:mS(e.asOf,a)})]},e.projectionKey)})})]})})]}),L&&(0,Q.jsx)($,{tone:`err`,children:L}),q&&(0,Q.jsx)(`div`,{className:`lab-load-more`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:m,onClick:()=>{te()},children:i(m?`common.loading`:`lab.loadMore`)})})]})]}),re&&(0,Q.jsx)(bC,{verdict:re,detail:v,loading:x,error:C,t:i,locale:a,onClose:N})]})]})}var SC=[`catalog`,`combos`,`routing`,`compatibility`];function CC(e){return e===`catalog`?`models`:`models/${e}`}function wC(e=window.location.hash){let t=Jt(qt(e)).path;return t===`models/combos`||t===`models/combos/jev-auto`||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 TC(e){Xt(CC(e))}function EC(e){return`models-tab-${e}`}function DC(e){return`models-panel-${e}`}var OC={catalog:`models.tab.catalog`,combos:`models.tab.combos`,routing:`models.tab.routing`,compatibility:`models.tab.compatibility`};function kC({tab:e,onSelect:t,meta:r}){let i=n(),a=(0,Z.useRef)(null);a.current===null&&(a.current=new Map);let o=e=>{t(e),window.requestAnimationFrame(()=>{a.current.get(e)?.focus({preventScroll:!0})})},s=t=>{let n=SC.indexOf(e),r=null;t.key===`ArrowLeft`?r=(n-1+SC.length)%SC.length:t.key===`ArrowRight`?r=(n+1)%SC.length:t.key===`Home`?r=0:t.key===`End`&&(r=SC.length-1),r!==null&&(t.preventDefault(),o(SC[r]))};return(0,Q.jsx)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":i(`models.tabsLabel`),children:SC.map(t=>{let n=t===e,c=r?.[t];return(0,Q.jsxs)(`button`,{ref:e=>{e?a.current.set(t,e):a.current.delete(t)},type:`button`,role:`tab`,id:EC(t),"aria-selected":n,"aria-controls":DC(t),tabIndex:n?0:-1,className:`page-tab${n?` page-tab--active`:``}`,onClick:()=>o(t),onKeyDown:s,children:[i(OC[t]),c?(0,Q.jsx)(`span`,{className:`section-tab-meta`,children:c}):null]},t)})})}function AC({summary:e,apiBase:t,onSaved:r}){let i=n(),[a,o]=(0,Z.useState)(!1),[s,c]=(0,Z.useState)(null),l=e?.fastOptIn?.enabled;if(s&&l!==s.from&&c(null),!e?.fastOptIn)return null;let u=e.fastOptIn.enabled,d=s&&s.from===u?s.value:u,f=async n=>{if(!(a||n===d)){o(!0);try{await vn(await fetch(`${t}/api/providers?name=${encodeURIComponent(e.name)}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({fastEnabled:n})}),i(`models.fastSaveFailed`)),c({value:n,from:u}),r(!0,i(n?`models.fastEnabled`:`models.fastDisabled`))}catch(e){r(!1,e instanceof Error?e.message:i(`models.fastSaveFailed`))}finally{o(!1)}}};return(0,Q.jsxs)(`div`,{className:`row models-provider-hint`,children:[(0,Q.jsx)(`span`,{className:`muted text-label`,children:i(`models.fastProvider`)}),(0,Q.jsx)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":i(`models.fastProvider`),children:[!1,!0].map(e=>(0,Q.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":d===e,className:`btn btn-sm${d===e?` btn-primary`:` btn-ghost`}`,disabled:a,onClick:()=>void f(e),children:i(e?`models.newPolicy_on`:`models.newPolicy_off`)},String(e)))}),(0,Q.jsx)(`span`,{className:`muted text-caption`,children:i(`models.fastProviderHint`)})]})}function jC(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)e.disabled===!0?n.delete(e.name):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 MC({liveModels:e,discovery:t,showFailureBadge:r=!0}){let i=n(),a=e&&t?.status===`failed`?t:void 0;return(0,Q.jsxs)(`div`,{className:`row muted text-label leading-body`,role:`status`,style:{alignItems:`flex-start`,gap:8,padding:`6px 0`},children:[(0,Q.jsx)(De,{width:15,height:15,"aria-hidden":`true`,style:{flexShrink:0,marginTop:2}}),(0,Q.jsxs)(`span`,{children:[a&&r&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`badge badge-amber`,children:i(`models.discoveryFailedBadge`)}),` `]}),a?`${es(i,a)} `:`${i(e?`models.emptyDiscovery`:`models.emptyDiscoveryDisabled`)} `,(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>Xt(`providers`),children:i(`models.openProviderSettings`)})]})]})}function NC(){let e=n();return(0,Q.jsxs)(`div`,{className:`row muted text-label leading-body`,role:`status`,style:{alignItems:`flex-start`,gap:8,padding:`6px 0`},children:[(0,Q.jsx)(De,{width:15,height:15,"aria-hidden":`true`,style:{flexShrink:0,marginTop:2}}),(0,Q.jsxs)(`span`,{children:[`${e(`models.discoveryFailedDependency`,{control:e(`pws.liveModels`)})} `,(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>Xt(`providers`),children:e(`models.openProviderSettings`)})]})]})}var PC=`ocx.models.settingsOpen.v1`;function FC(e){return e||(typeof localStorage>`u`?void 0:localStorage)}function IC(e){try{return FC(e)?.getItem(PC)===`1`}catch{return!1}}function LC(e,t){try{FC(t)?.setItem(PC,e?`1`:`0`)}catch{}}var RC={default:`models.pickerOrder.default`,alphabetical:`models.pickerOrder.alphabetical`,provider:`models.pickerOrder.provider`,"most-used":`models.pickerOrder.mostUsed`,custom:`models.pickerOrder.custom`};function zC(e,t){let n=e(`models.settingsPanel.off`),r=[];t.multiAgentMode&&r.push({id:`subagent`,label:e(`models.v2Label`),value:e(`models.v2Mode_${t.multiAgentMode}`)}),typeof t.v2Threads==`number`&&r.push({id:`threads`,label:e(`models.v2ThreadsLabel`),value:String(t.v2Threads)}),t.multiAgentMode===`v2`&&t.keepNativeOnV1&&r.push({id:`keep-native`,label:e(`models.keepNativeOnV1`),value:``}),r.push({id:`shadow`,label:e(`models.shadowCallIntercept`),value:t.shadowEnabled&&t.shadowModel?t.shadowModel:n}),t.autoReviewEnabled&&r.push({id:`auto-review`,label:e(`models.autoReviewOverride`),value:t.autoReviewModel||e(`models.autoReviewPending`)}),r.push({id:`window`,label:e(`models.contextCapLabel`),value:t.windowOn?vs(t.windowValue):n});let i=RC[t.pickerMode];return r.push({id:`order`,label:e(`models.pickerOrder.label`),value:i?e(i):t.pickerMode}),t.newModelsOff&&r.push({id:`new-models`,label:e(`models.newPolicyGlobal`),value:``}),t.aliasesOn&&r.push({id:`aliases`,label:e(`models.useDefaultAliasesGlobal`),value:``}),r}function BC({title:e,attentionLabel:t,summary:n,warn:r,children:i,storage:a}){let[o,s]=(0,Z.useState)(()=>IC(a)),[c,l]=(0,Z.useState)(!1),u=o||r&&!c;return(0,Q.jsxs)(`details`,{className:`models-settings`,open:u,onToggle:e=>{let t=e.currentTarget.open;t!==u&&(s(t),!t&&r&&l(!0),LC(t,a))},children:[(0,Q.jsxs)(`summary`,{className:`models-settings-summary`,children:[(0,Q.jsx)(`span`,{className:`models-settings-title`,children:e}),r&&(0,Q.jsx)(`span`,{className:`models-settings-warn`,role:`img`,"aria-label":t,title:t}),(0,Q.jsx)(`span`,{className:`models-settings-state`,children:n.map(e=>(0,Q.jsxs)(`span`,{className:`models-settings-kv`,"data-item":e.id,children:[(0,Q.jsx)(`span`,{className:`models-settings-k`,children:e.label}),e.value&&(0,Q.jsx)(`span`,{className:`models-settings-v`,children:e.value})]},e.id))})]}),(0,Q.jsx)(`div`,{className:`models-settings-body`,children:i})]})}function VC({count:e,label:t}){return e===0?null:(0,Q.jsx)(`span`,{className:`models-chip mono text-caption models-custom-summary`,children:t})}function HC({text:e}){return(0,Q.jsx)(pn,{content:e,side:`top`,maxWidth:360,children:(0,Q.jsxs)(`span`,{className:`models-info-hint`,children:[(0,Q.jsx)(De,{width:14,height:14,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`sr-only`,children:e})]})})}function UC({label:e,hint:t,busy:n,muted:r=!0,caption:i,children:a}){let o=[`models-row-label`,r?`muted`:``,i?`text-caption`:`text-control`].filter(Boolean).join(` `);return(0,Q.jsxs)(`div`,{className:`models-control-row`,"aria-busy":n||void 0,children:[(0,Q.jsxs)(`span`,{className:o,children:[e,t?(0,Q.jsxs)(Q.Fragment,{children:[` `,t]}):null]}),(0,Q.jsx)(`div`,{className:`models-row-actions`,children:a})]})}function WC({shadowCall:e,saving:t,modelOptions:r,onSave:i}){let a=n(),o=a(`models.shadowCallInterceptHint`,{models:Sn(e?.sourceModels)});return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(UC,{label:a(`models.shadowCallIntercept`),hint:(0,Q.jsx)(pn,{content:o,side:`top`,maxWidth:320,children:(0,Q.jsx)(`span`,{style:{cursor:`help`},"aria-label":o,children:(0,Q.jsx)(De,{width:13,height:13,"aria-hidden":`true`})})}),busy:!e,children:[(0,Q.jsx)(`code`,{className:`text-caption models-shadow-warning`,style:{opacity:.6},children:a(`models.shadowCallOriginal`,{models:En(e?.sourceModels,a(`shadowCall.memoryLabel`))})}),(0,Q.jsx)(ln,{on:e?.enabled??!1,onClick:()=>i({enabled:!e?.enabled}),disabled:!e||t,label:a(`models.shadowCallIntercept`)}),(0,Q.jsx)(`div`,{className:`models-shadow-model-slot`,children:(0,Q.jsx)(dn,{value:e?.model??``,options:r,onChange:e=>i({model:e}),disabled:!e||t||!e.enabled,label:a(`models.shadowCallIntercept`)})})]}),(0,Q.jsx)(Ga,{className:`models-shadow-sources`,options:e?.sourceModelOptions,sourceModels:e?.sourceModels,disabled:!e?.enabled,saving:t,onChange:e=>i({sourceModels:e})})]})}function GC(e,t){if(!e)return null;let n=new Date(e);return Number.isNaN(n.getTime())?null:new Intl.DateTimeFormat(t,{dateStyle:`medium`,timeStyle:`short`}).format(n)}function KC({connected:e,catalogSyncedAt:t}){let{locale:n,t:i}=r(),a=GC(t,n),o=e?[{id:`saved`,chip:i(`models.delivery.chip.savedHub`),title:i(`models.delivery.savedHub.title`),body:i(`models.delivery.savedHub.body`)},{id:`synced`,chip:a?i(`models.delivery.chip.synced`,{time:a}):i(`models.delivery.chip.syncedUnknown`),title:i(`models.delivery.synced.title`),body:a?i(`models.delivery.synced.bodyAt`,{time:a}):i(`models.delivery.synced.bodyUnknown`)}]:[{id:`saved`,chip:i(`models.delivery.chip.saved`),title:i(`models.delivery.saved.title`),body:i(`models.delivery.saved.body`)}];return o.push({id:`loaded`,chip:i(`models.delivery.chip.loaded`),title:i(`models.delivery.loaded.title`),body:i(`models.delivery.loaded.body`)}),(0,Q.jsxs)(`details`,{className:`models-delivery`,children:[(0,Q.jsxs)(`summary`,{children:[(0,Q.jsx)(`span`,{className:`models-delivery-title`,children:i(`models.delivery.title`)}),(0,Q.jsx)(`span`,{className:`models-delivery-flow`,children:o.map(e=>e.chip).join(` → `)})]}),(0,Q.jsx)(`ol`,{className:`models-delivery-steps`,children:o.map(e=>(0,Q.jsxs)(`li`,{"data-step":e.id,children:[(0,Q.jsx)(`strong`,{children:e.title}),(0,Q.jsx)(`p`,{children:e.body})]},e.id))}),(0,Q.jsx)(`p`,{className:`models-delivery-hint`,children:i(`models.delivery.hint`)})]})}function qC(e,t,n){let[r,i]=(0,Z.useState)({apiBase:e,data:null,saving:!1}),a=r.apiBase===e?r.data:null,o=r.apiBase===e&&r.saving,s=(0,Z.useRef)({read:null,write:null,generation:0,apiBase:e});(0,Z.useLayoutEffect)(()=>{let t=s.current;return t.apiBase=e,t.generation++,()=>{t.generation++,t.read?.controller.abort(),t.read?.clear(),t.read=null,t.write?.controller.abort(),t.write?.clear(),t.write=null}},[e]);let c=(0,Z.useCallback)(async({reconcile:t=!1}={})=>{let n=s.current;if(n.write&&!t)return null;n.read?.controller.abort(),n.read?.clear();let r=M(15e3),a=n.generation;n.read=r;try{let o=await yn(await fetch(`${e}/api/auto-review-settings`,{signal:r.signal}));return!o||typeof o.enabled!=`boolean`||typeof o.model!=`string`?null:!r.signal.aborted&&n.apiBase===e&&n.generation===a&&n.read===r&&(!n.write||t)?(i({apiBase:e,data:o,saving:n.write!==null}),o):null}catch{return null}finally{r.clear(),n.read===r&&(n.read=null)}},[e]);return{data:a,saving:o,load:c,save:(0,Z.useCallback)(async r=>{let l=s.current;if(!a||o||l.apiBase!==e||l.write)return;let u=a,d=M(15e3);l.write=d;let f=++l.generation;l.read?.controller.abort(),l.read?.clear(),l.read=null,i({apiBase:e,data:{...u,...r},saving:!0});try{let a=await vn(await fetch(`${e}/api/auto-review-settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},signal:d.signal,body:JSON.stringify(r)}),t(`models.saveFailed`));if(!a||a.ok!==!0||typeof a.enabled!=`boolean`||typeof a.model!=`string`)throw Error(t(`models.saveFailed`));if(l.apiBase!==e||l.generation!==f)return;i({apiBase:e,data:{enabled:a.enabled,model:a.model},saving:!0}),(!a.catalogRefresh||a.catalogRefresh.status!==`committed`)&&n(!1,t(`codexAuth.catalogRefreshPending`))}catch(r){if(l.apiBase===e&&l.generation===f){let a=await c({reconcile:!0});if(l.apiBase!==e||l.generation!==f)return;i({apiBase:e,data:a??u,saving:!0}),n(!1,r instanceof Error&&r.message?r.message:t(`models.saveFailed`))}}finally{d.clear(),l.write===d&&(l.write=null),l.apiBase===e&&l.generation===f&&i(t=>t.apiBase===e?{...t,saving:!1}:t)}},[e,a,o,t,n,c])}}function JC({apiBase:e,publishFeedback:t,t:n}){let[r,i]=(0,Z.useState)(null),[a,o]=(0,Z.useState)(!1);return{shadowCall:r,shadowCallSaving:a,loadShadowCall:(0,Z.useCallback)(async()=>{let t=M(15e3);try{let n=await yn(await fetch(`${e}/api/shadow-call-settings`,{signal:t.signal}));n&&i(n)}catch{}finally{t.clear()}},[e]),saveShadowCall:async s=>{if(!r||a)return;let c=r;o(!0),i({...r,...s});try{let r=await fetch(`${e}/api/shadow-call-settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(s)});if(!r.ok){i(c),t(!1,n(ss((await r.json().catch(()=>null))?.code)));return}let a=await r.json().catch(()=>null);a&&typeof a.enabled==`boolean`&&i(a)}catch{i(c),t(!1,n(`models.networkError`))}finally{o(!1)}}}}var YC={catalog:`models.subtitle`,combos:`models.subtitle.combos`,routing:`models.subtitle.routing`,compatibility:`models.subtitle.compatibility`};function XC({apiBase:e,restartEpoch:t=0,connected:r=!1,catalogSyncedAt:i,reportRestart:a}){let[o,s]=(0,Z.useState)(null),c=(0,Z.useRef)(!0);(0,Z.useEffect)(()=>(c.current=!0,()=>{c.current=!1}),[]);let l=(0,Z.useRef)(null),u=(0,Z.useRef)(0),d=(0,Z.useRef)(e),f=(0,Z.useCallback)(()=>{u.current++,l.current?.controller.abort(),l.current?.clear(),l.current=null},[]),p=(0,Z.useCallback)(async()=>{if(!c.current||d.current!==e)return;f();let t=u.current,n=M(15e3);l.current=n;try{let r=await Dv(e,{signal:n.signal});if(n.signal.aborted||!c.current||d.current!==e||t!==u.current||l.current!==n)return;s(r.state)}finally{n.clear(),l.current===n&&(l.current=null)}},[e,f]),{restarting:m,restart:h}=Mv(e,{onSettled:()=>{p()},report:a});(0,Z.useEffect)(()=>(d.current=e,s(null),p(),f),[e,f,p,t]);let[g,_]=(0,Z.useState)(wC),[v,y]=(0,Z.useState)(()=>new Set([wC()])),b=(0,Z.useCallback)(e=>{_(e),y(t=>t.has(e)?t:new Set([...t,e]))},[]);(0,Z.useEffect)(()=>{let e=()=>b(wC());return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[b]);let x=(0,Z.useCallback)(e=>{TC(e),b(e)},[b]),S=g===`catalog`,[C,w]=(0,Z.useState)(null),[T,E]=(0,Z.useState)(null),[D,O]=(0,Z.useState)(null),k=n(),A=`ocx.models.catalog.v1:${e}`,j=(0,Z.useMemo)(()=>io(A),[A]),[N,P]=(0,Z.useState)(()=>j?.models??[]),[F,I]=(0,Z.useState)(()=>j?.providers??[]),[L,R]=(0,Z.useState)(()=>new Set(j?.disabled??[])),[z,B]=(0,Z.useState)(()=>j?.selectedModels??null),[V,H]=(0,Z.useState)({}),[U,ee]=(0,Z.useState)({}),[W,te]=(0,Z.useState)({}),[G,ne]=(0,Z.useState)(()=>j?.contextCaps??{}),[K,re]=(0,Z.useState)(()=>j?.contextCapValues??{}),[q,J]=(0,Z.useState)(()=>j?.contextCapValue??35e4),Y=`${A}:picker-order`,ie=(0,Z.useMemo)(()=>{let e=io(Y);return T_(e)?e:void 0},[Y]),[X,oe]=(0,Z.useState)(null),[se,ce]=(0,Z.useState)(!1),ue=(0,Z.useRef)(null),de=(0,Z.useRef)(0),pe=uo(Y,[e],(0,Z.useCallback)(async t=>{let n=await vn(await fetch(`${e}/api/subagent-models`,{signal:t}));if(!T_(n))throw Error(`picker settings payload missing`);if(t.aborted)throw Error(`picker settings request aborted`);return co(Y,n),n},[e,Y]),{isEmpty:()=>!1,enabled:S,deadlineMs:15e3,initialData:ie}),me=pe.state.data,he=X??j_(me?.pickerAvailable??[],me?.pickerOrder??[],me?.pickerOrderMode);(0,Z.useLayoutEffect)(()=>(de.current++,oe(null),ce(!1),()=>{de.current++,ue.current?.controller.abort(),ue.current?.clear(),ue.current=null}),[e,S]),(0,Z.useLayoutEffect)(()=>{S&&X===null&&he===`custom`&&oe(`custom`)},[S,X,he]);let[ge,_e]=(0,Z.useState)(``),[ve,ye]=(0,Z.useState)(!1),[be,xe]=(0,Z.useState)({}),[Se,we]=(0,Z.useState)({}),Te=Ss(),[Ee,ke]=(0,Z.useState)(()=>Te??new Set),Ae=(0,Z.useRef)(Te===null),[je,Me]=(0,Z.useState)(``),[Pe,Fe]=(0,Z.useState)([]),[Ie,Le]=(0,Z.useState)(!1),[Re,Be]=(0,Z.useState)(0),Ve=(0,Z.useCallback)((e,t)=>{Le(e),Me(t),Be(e=>e+1)},[]),{data:He,saving:Ue,load:We,save:Ge}=qC(e,k,Ve);(0,Z.useEffect)(()=>{S||We()},[e,S,We]),(0,Z.useEffect)(()=>{if(!je)return;let e=setTimeout(()=>Me(``),Ie?6e3:8e3);return()=>clearTimeout(e)},[je,Ie,Re]);let[Ke,qe]=(0,Z.useState)(!1),Je=(0,Z.useRef)(!1),Xe=(0,Z.useRef)(!1),Ze=(0,Z.useRef)(0),Qe=(0,Z.useRef)(!1),$e=sb(e,{onQueued:()=>{++Ze.current,Me(``)},onBusy:e=>{++Ze.current,Qe.current=!1,Xe.current=e,Je.current=e,qe(e)},onResponse:e=>{let t=Go(e);t!==void 0&&Fe(t)},refresh:e=>br(!0,e),onSettled:e=>{Le(!e),Me(k(e??`models.applied`))}}),et=(e,t,n,r,i)=>$e.visible(t,n,r,Zo(e,t,n,r,i)),[tt,nt]=(0,Z.useState)(null),[rt,it]=(0,Z.useState)({}),[at,ot]=(0,Z.useState)(null),[st,ct]=(0,Z.useState)({providers:{},models:{},defaults:{global:!1,providers:{}}}),[lt,ut]=(0,Z.useState)(!1),[dt,ft]=(0,Z.useState)(null),[pt,mt]=(0,Z.useState)(!0),[ht,gt]=(0,Z.useState)(!1),[_t,vt]=(0,Z.useState)(``),yt=(0,Z.useRef)(!1),bt=(0,Z.useRef)(0),xt=(0,Z.useRef)(0),[St,Ct]=(0,Z.useState)(``),[wt,Tt]=(0,Z.useState)(!1),[Et,Dt]=(0,Z.useState)(!1),[Ot,kt]=(0,Z.useState)(null),[At,jt]=(0,Z.useState)(!1),[Mt,Nt]=(0,Z.useState)(null),[Pt,Ft]=(0,Z.useState)(null),It=(0,Z.useRef)(null),[Lt,Rt]=(0,Z.useState)(null),[zt,Bt]=(0,Z.useState)(!1),[Vt,Ht]=(0,Z.useState)(null),[Ut,Wt]=(0,Z.useState)(null),[Gt,qt]=(0,Z.useState)(!1),Jt=(0,Z.useRef)(null),Yt=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>()=>{Jt.current?.controller.abort(),Jt.current?.clear(),Jt.current=null},[]);let Xt=(0,Z.useRef)(null),Zt=(0,Z.useCallback)(async t=>{let n=await yn(await fetch(`${e}/api/aliases`,{signal:t}));n&&!t?.aborted&&ct(n)},[e]);(0,Z.useEffect)(()=>{let e=new AbortController;return Zt(e.signal),()=>e.abort()},[Zt]);let Qt={apiBase:e,t:k,reloadAliases:Zt,publishFeedback:Ve},$t=e=>Nv(e,st.providers[e]??``,Qt),en=(e,t)=>Pv(e,t,st.models[e]?.[t]?.alias??``,Qt),tn=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 Zt()},[nn,rn]=(0,Z.useState)(`add`),[an,on]=(0,Z.useState)(``),[sn,cn]=(0,Z.useState)(``),[un,mn]=(0,Z.useState)(``),[hn,gn]=(0,Z.useState)(``),[_n,bn]=(0,Z.useState)(``),[xn,Sn]=(0,Z.useState)(!1),[Cn,wn]=(0,Z.useState)([`text`]),[Tn,En]=(0,Z.useState)(!1),[Dn,On]=(0,Z.useState)([]),kn=(0,Z.useRef)(!1),[An,jn]=(0,Z.useState)(!1),[Mn,Nn]=(0,Z.useState)(``),[Pn,Fn]=(0,Z.useState)(null),[In,Ln]=(0,Z.useState)([]),[Rn,zn]=(0,Z.useState)(``),[Bn,Vn]=(0,Z.useState)(``),[Hn,Un]=(0,Z.useState)({}),[Wn,Gn]=(0,Z.useState)({contextWindow:null,modelContextWindows:{}}),[Kn,qn]=(0,Z.useState)(new Set),[Jn,Yn]=(0,Z.useState)(!1),[Xn,Zn]=(0,Z.useState)(!1),[Qn,$n]=(0,Z.useState)(``),[er,tr]=(0,Z.useState)(null),rr=(0,Z.useRef)(null),{shadowCall:ir,shadowCallSaving:ar,loadShadowCall:or,saveShadowCall:sr}=JC({apiBase:e,publishFeedback:Ve,t:k}),[cr,lr]=(0,Z.useState)(null);(0,Z.useEffect)(()=>()=>{rr.current&&clearTimeout(rr.current)},[]);let ur=(0,Z.useMemo)(()=>bs(N,L,z??{},k),[N,L,z,k]),fr=(0,Z.useMemo)(()=>{let e=new Set(ur.map(e=>e.value));return nr(N.filter(t=>e.has(t.namespaced)),ir?.model,ir?.sourceModels)},[N,ir?.model,ir?.sourceModels,ur]),mr=(0,Z.useMemo)(()=>[{value:``,label:`—`},...xs(ur,N,He?.model)],[N,ur,He?.model]),hr=(0,Z.useCallback)(async()=>{if(yt.current)return;let t=++bt.current,n=xt.current,r=()=>t===bt.current&&n===xt.current,i=M(15e3);try{let t=await fetch(`${e}/api/v2`,{signal:i.signal});if(!r())return;if(!(t.headers.get(`content-type`)??``).includes(`application/json`)){nt(null);return}let n=await yn(t);if(!r())return;if(!n||typeof n.enabled!=`boolean`){nt(null);return}nt({enabled:n.enabled,agentsMaxThreadsConflict:n.agentsMaxThreadsConflict===!0,maxConcurrentThreadsPerSession:typeof n.maxConcurrentThreadsPerSession==`number`?n.maxConcurrentThreadsPerSession:null,multiAgentMode:n.multiAgentMode===`v1`||n.multiAgentMode===`v2`?n.multiAgentMode:`default`,keepNativeChatGptOnV1:n.keepNativeChatGptOnV1===!0})}catch{r()&&nt(null)}finally{i.clear(),mt(!1)}},[e]),gr=(0,Z.useCallback)(async t=>{let n=Ze.current,[r,i,a,o]=await Promise.all([fetch(`${e}/api/models`,{signal:t}),fetch(`${e}/api/provider-context-caps`,{signal:t}),fetch(`${e}/api/providers`,{signal:t}),Yo(e,fetch,t)]),[s,c,l]=await Promise.all([vn(r),vn(i),vn(a)]);if(s===void 0||c===void 0||l===void 0)throw Error(`models payload missing`);if(t.aborted)throw Error(`models request aborted`);let u=ys(s),d=typeof c.value==`number`&&Number.isFinite(c.value)&&c.value>0?c.value:typeof c.cap==`number`&&Number.isFinite(c.cap)&&c.cap>0?c.cap:void 0,f=d===void 0?35e4:d,p={models:s,providers:l,selectedModels:o,disabled:[...u],contextCaps:c.caps??{},contextCapValues:c.values??c.caps??{},contextCapValue:f};return n===Ze.current&&co(A,p),p},[e,A]),_r=(0,Z.useCallback)(e=>{let t=jC(e.models,e.providers);lr(e=>e!==null&&!t.some(t=>t.provider===e)?null:e),P(e.models),I(e.providers),R(new Set(e.disabled)),B(e.selectedModels),J(e.contextCapValue),ne(e.contextCaps),re(e.contextCapValues??e.contextCaps)},[]),vr=uo(A,[e],async e=>{let t=Ze.current,n=await gr(e);if(e.aborted)throw Error(`models request aborted`);return!Xe.current&&t===Ze.current&&_r(n),n},{isEmpty:()=>!1,pollMs:1e4,initialData:j??void 0,enabled:S,deadlineMs:6e4}),yr=vr.state,br=(0,Z.useCallback)(async(e=!1,t)=>{if(Qe.current&&!e)return!1;Qe.current=!0;let n=++Ze.current;try{let e=await gr(t??new AbortController().signal);return $o(n,Ze.current)?(_r(e),Kt(A,e),pe.refresh(),!0):!1}catch{return!1}finally{$o(n,Ze.current)&&(Qe.current=!1)}},[_r,A,gr,pe.refresh]),xr=(0,Z.useCallback)(()=>{let e=Xt.current;Nt(null),Ht(null),Wt(null),qt(!1),window.setTimeout(()=>{e?.isConnected&&e.focus()},0)},[]),Sr=(0,Z.useCallback)(()=>{Yt.current||xr()},[xr]),Cr=(0,Z.useCallback)(async t=>{let n=Mt;if(!n||Yt.current)return;let r=M(6e4);Jt.current=r,Yt.current=!0,Bt(!0),Ht(null);let i=Ut?.confirmed===!0&&(t===void 0||t===Ut.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 vn(s,k(`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(k(`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)};P(e=>e.map(e=>e.namespaced===n.namespaced?{...e,...r}:e)),Nt({...n,...r}),qt(r.displayName===void 0)}if(!s.ok)throw Error(c.error||k(`models.displayNameSaveFailed`));o=!0}if(!await br(!0,r.signal))throw Error(k(`models.loadFail`));r.signal.throwIfAborted(),Ve(!0,k(i?t===null||t===void 0&&Ut?.value===null?`models.displayNameResetDone`:`models.displayNameSaved`:`models.displayNameReloaded`)),xr()}catch(e){if(Jt.current!==r)return;let n=!a||r.signal.aborted;n&&!i&&qt(!0),Wt(i||n||o?{value:o||n?void 0:t,confirmed:i}:null),Ht(i?k(`models.displayNameSavedRefreshFailed`):n||o?k(`models.displayNameOutcomeUnknown`):e instanceof Error&&e.message?e.message:k(`models.displayNameSaveFailed`))}finally{r.clear(),Jt.current===r&&(Jt.current=null,Yt.current=!1,Bt(!1))}},[e,Mt,Ut,xr,br,Ve,k]);(0,Z.useEffect)(()=>{if(!S)return;let e=window.setTimeout(()=>{or(),We(),hr(),Gr(),Kr()},0),t=ba(()=>{yt.current||hr()},1e4);return()=>{window.clearTimeout(e),t()}},[S,or,We,hr]);let wr=(0,Z.useMemo)(()=>jC(N,F),[N,F]),Tr=N.length>0||yr.data!==void 0,Er=e=>{let t=[...new Set([...e.rows.map(e=>e.id),...e.configuredModels,...Object.keys(e.modelContextWindows??{})])].sort(),n=t[0]??``;Fn(e.provider),Ln(t),zn(n);let r=e.contextWindow?String(e.contextWindow):``,i=Object.fromEntries(Object.entries(e.modelContextWindows??{}).map(([e,t])=>[e,String(t)]));Vn(r),Un(i),Gn({contextWindow:e.contextWindow??null,modelContextWindows:Object.fromEntries(Object.entries(e.modelContextWindows??{}).map(([e,t])=>[e,t]))}),qn(new Set),Yn(!1),$n(``)},Dr=e=>{zn(e)},Or=async()=>{if(!Pn)return;let t=ws(Bn);if(!wr.find(e=>e.provider===Pn)){$n(k(`models.contextSaveFailed`));return}if(Jn&&t===void 0){$n(k(`models.contextInvalid`));return}let n=Object.create(null);for(let e of Kn){let t=ws(Bv(Hn,e)??``);if(t===void 0){$n(k(`models.contextInvalid`));return}t!==(Bv(Wn.modelContextWindows,e)??null)&&(n[e]=t)}let r=Jn&&t!==Wn.contextWindow;if(!r&&Object.keys(n).length===0)Fn(null),Ve(!0,k(`models.contextUnchanged`));else{Zn(!0),$n(``);try{let i={};r&&(i.contextWindow=t),Object.keys(n).length>0&&(i.modelContextWindows=n),await vn(await fetch(`${e}/api/providers?name=${encodeURIComponent(Pn)}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify(i)}),k(`models.contextSaveFailed`))}catch(e){$n(e instanceof Error?e.message:k(`models.contextSaveFailed`));return}finally{Zn(!1)}Fn(null),Ve(!0,k(`models.contextSaved`)),await br(!0)}};(0,Z.useEffect)(()=>{if(!Ae.current||wr.length===0)return;Ae.current=!1;let e=new Set(wr.map(e=>e.provider));ke(e),Cs(e)},[wr]);let kr=(0,Z.useMemo)(()=>z?N.filter(e=>et(z,e.provider,e.id,e.native===!0,L.has(e.namespaced))).length:0,[L,N,z,$e.overrides]),Ar=(0,Z.useMemo)(()=>({catalog:Tr?k(`models.active`,{active:kr,total:N.length}):void 0,combos:C===null?void 0:String(C),routing:T===null?void 0:String(T),compatibility:D===null?void 0:String(D)}),[Tr,C,D,kr,N.length,T,k]),jr=async(e,t,n,r)=>{(!Je.current||$e.isRunning())&&$e.enqueue(e,t,n,r)},Mr=async t=>{qe(!0),Je.current=!0,Me(``);let n=G[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 vn(r,k(`models.capSaveFailed`));ne(e?.caps??{}),re(e?.values??e?.caps??{}),Le(!0),Me(k(`models.capApplied`)),await br(!0)}catch(e){Le(!1),Me(e instanceof Error?e.message:k(`models.capSaveFailed`))}}catch{Le(!1),Me(k(`models.networkError`))}finally{qe(!1),Je.current=!1}},Nr=e=>{ke(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),Cs(n),n})},Pr=e=>{ke(()=>{let t=e?new Set(wr.map(e=>e.provider)):new Set;return Cs(t),t})},Fr=async t=>{qe(!0),Je.current=!0,Me(``);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 vn(n,k(`models.capSaveFailed`));typeof e?.value==`number`&&Number.isFinite(e.value)&&e.value>0&&J(e.value),ne(e?.caps??{}),re(e?.values??e?.caps??{}),Le(!0),Me(k(`models.capApplied`)),await br(!0)}catch(e){Le(!1),Me(e instanceof Error?e.message:k(`models.capSaveFailed`))}}catch{Le(!1),Me(k(`models.networkError`))}finally{qe(!1),Je.current=!1}},Ir=(0,Z.useMemo)(()=>{let e=wr.filter(e=>!e.native);return e.length>0&&e.every(e=>G[e.provider]===q)&&Object.keys(G).every(e=>G[e]===q)},[wr,G,q]),Lr=e=>{!Number.isSafeInteger(e)||e<=0||Fr(Ir?{value:e,setAll:!0}:{value:e})},Rr=(e,t)=>{if(t===`custom`){xe(t=>({...t,[e]:!0})),we(t=>({...t,[e]:String(G[e]??K[e]??q)}));return}xe(t=>({...t,[e]:!1}));let n=Number(t);Number.isSafeInteger(n)&&n>0&&n!==G[e]&&Fr({provider:e,enabled:!0,value:n})},zr=e=>{let t=Number((Se[e]??``).replace(/[_,\s]/g,``));!Number.isSafeInteger(t)||t<=0?Ve(!1,k(`models.capSaveFailed`)):(xe(t=>({...t,[e]:!1})),Fr({provider:e,enabled:!0,value:t}))},Br=e=>{if(e===`custom`){ye(!0),_e(String(q));return}ye(!1);let t=Number(e);Number.isSafeInteger(t)&&t>0&&t!==q&&Lr(t)},Vr=()=>{let e=Number(ge.replace(/[_,\s]/g,``));!Number.isSafeInteger(e)||e<=0?Ve(!1,k(`models.capSaveFailed`)):(ye(!1),Lr(e))},Hr=()=>{Fr({setAll:!Ir})},Ur=async t=>{if(tt&&!yt.current){gt(!0),yt.current=!0,xt.current++,vt(``),Me(``);try{let n=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});try{let e=await vn(n,k(`models.saveFailed`));if(!e||typeof e.enabled!=`boolean`){Le(!1),Me(k(`models.saveFailed`));return}nt({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}),Le(!0),Me(k(`models.v2Applied`)),vt((e.warnings??[]).join(` `))}catch(e){Le(!1),Me(e instanceof Error?e.message:k(`models.saveFailed`))}}catch{Le(!1),Me(k(`models.networkError`))}finally{gt(!1),yt.current=!1}}},Wr=async e=>{tt&&tt.multiAgentMode!==e&&(e===`v1`?await Ur({multiAgentMode:`v1`}):kt(e))},Gr=async()=>{try{let t=M(15e3),n=await yn(await fetch(`${e}/api/model-presets`,{signal:t.signal}));it(n?.providers??{})}catch{it({})}},Kr=async()=>{try{let t=await fetch(`${e}/api/model-discovery`);ot(await yn(t)??null)}catch{ot(null)}},qr=async(t,n)=>{await yn(await fetch(`${e}/api/model-discovery`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({policy:t,provider:n??null})})),await Promise.all([Kr(),br()])},Jr=async(t,n,r)=>{if((!r||await ha({message:k(`models.presetConfirmReplace`,{count:String(r.presetCount)}),tone:`danger`}))&&!Xe.current){Xe.current=!0,ft(t),qe(!0),Je.current=!0;try{let r=M(3e4),i=await vn(await fetch(`${e}/api/model-presets`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({provider:t,mode:n}),signal:r.signal}),k(`models.saveFailed`));if(!i)throw Error(k(`models.saveFailed`));if(i.fallback===`preset-empty`)Ve(!1,k(`models.presetEmpty`,{provider:t}));else{let e=Go(i);e!==void 0&&Fe(e),Ve(!0,n===`all`?k(`models.presetClearedToast`,{provider:t}):k(`models.presetAppliedToast`,{provider:t,count:String(i.selected?.length??0)}))}await Promise.all([Gr(),br()])}catch(e){Ve(!1,e instanceof Error?e.message:String(e))}finally{ft(null),qe(!1),Je.current=!1,Xe.current=!1}}},Yr=async e=>{tt&&tt.keepNativeChatGptOnV1!==e&&await Ur({keepNativeChatGptOnV1:e})},Xr=tt?.maxConcurrentThreadsPerSession==null?null:hs(tt.maxConcurrentThreadsPerSession,tt.enabled),Zr=async t=>{if(!tt||yt.current)return;let n=gs(t,tt.enabled);if(!Number.isSafeInteger(t)||t<1||!Number.isSafeInteger(n))Ve(!1,k(`models.v2ThreadsInvalid`));else if(Xr!==t){gt(!0),yt.current=!0,xt.current++,vt(``),Me(``);try{let t=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({maxConcurrentThreadsPerSession:n})});try{let e=await vn(t,k(`models.saveFailed`));if(!e||typeof e.enabled!=`boolean`){Le(!1),Me(k(`models.saveFailed`));return}nt({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}),Le(!0),Me(k(`models.v2ThreadsApplied`)),Tt(!1)}catch(e){Le(!1),Me(e instanceof Error?e.message:k(`models.saveFailed`))}}catch{Le(!1),Me(k(`models.networkError`))}finally{gt(!1),yt.current=!1}}},Qr=e=>{e===`custom`?(Tt(!0),Ct(String(Xr??``))):(Tt(!1),Zr(Number(e)))},$r=(e,t)=>{rr.current&&clearTimeout(rr.current),rr.current=setTimeout(()=>{tr({namespaced:e,rect:t.getBoundingClientRect()})},300)},ei=(e,t)=>{rr.current&&clearTimeout(rr.current),tr({namespaced:e,rect:t.getBoundingClientRect()})},ti=()=>{rr.current&&clearTimeout(rr.current),rr.current=setTimeout(()=>tr(null),120)},ni=()=>{rr.current&&clearTimeout(rr.current)},ri=async(t,n,r,i,a,o)=>{jn(!0),Nn(``);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 vn(s,k(`models.customSaveFailed`)),jt(!1),Ve(!0,k(`models.customAdded`)),await br(!0)}catch(e){Nn(e instanceof Error?e.message:k(`models.customSaveFailed`))}}catch{Nn(k(`models.networkError`))}finally{jn(!1)}},ii=async(t,n)=>{jn(!0),Nn(``);try{let r=await fetch(`${e}/api/custom-models/${encodeURIComponent(t)}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});try{await vn(r,k(`models.customSaveFailed`)),jt(!1),Ve(!0,k(`models.customUpdated`)),await br(!0)}catch(e){Nn(e instanceof Error?e.message:k(`models.customSaveFailed`))}}catch{Nn(k(`models.networkError`))}finally{jn(!1)}},ai=async(t,n)=>{if(await ha({message:k(`models.customDeleteConfirm`,{name:n}),confirmLabel:k(`common.delete`),tone:`danger`}))try{(await fetch(`${e}/api/custom-models/${encodeURIComponent(t)}`,{method:`DELETE`})).ok?(Ve(!0,k(`models.customDeleted`)),await br(!0)):Ve(!1,k(`models.customSaveFailed`))}catch{Ve(!1,k(`models.networkError`))}},oi=yr.data??j,si=yr.kind===`failed-cold`?yr.error instanceof Error?yr.error.message:k(`models.loadFail`):null,ci=yr.showSkeleton&&!oi,li=z??{},ui=t=>{let{provider:n,rows:r,nativeProviderGroup:i,liveModels:a,discovery:o}=t,s=Ee.has(n),c=e=>et(li,n,e.id,e.native===!0,L.has(e.namespaced)),l=U[n]===!0,u=ts(r),d=rs(l,r),f=ns(r,d),p=f.filter(c).length,m=at?.recentArrivals[n]??[],h=new Set(m.map(e=>e.id)),g=G[n]!==void 0,_=G[n]??K[n]??q,v=t.nativeProviderGroup?us:cs,y=t.nativeProviderGroup?ds:ls,b=a&&o?.status===`failed`?o:void 0,x=(V[n]??``).trim().toLowerCase(),S=x?f.filter(e=>e.id.toLowerCase().includes(x)):f,C=S.toSorted((e,t)=>Number(!c(e))-Number(!c(t))),w=W[n]??60,T=C.slice(0,w),E=S.length-T.length,D=f.length>0,O=r.some(e=>e.initialSelectionPending),A=!D||f.every(c),j=!D||f.every(e=>!c(e)),M=e=>{D&&!O&&jr(`provider`,n,f.map(e=>({id:e.id,native:e.native===!0})),e)};return(0,Q.jsxs)(`div`,{className:`card models-provider-card`,children:[(0,Q.jsxs)(`div`,{className:`row group-head models-provider-head${s?``:` open`}`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`row models-provider-toggle`,onClick:()=>Nr(n),"aria-expanded":!s,style:{flex:`1 1 auto`,border:0,background:`transparent`,padding:0,color:`inherit`,cursor:`pointer`,textAlign:`left`},children:[(0,Q.jsx)(Ye,{style:{width:14,height:14,color:`var(--muted)`,transform:s?`none`:`rotate(90deg)`,transition:`transform .12s`}}),(0,Q.jsx)(`span`,{className:`text-body font-semibold`,style:{whiteSpace:`nowrap`},children:fe(n)}),st.providers[n]&&(0,Q.jsx)(`span`,{className:`models-chip mono text-caption`,children:st.providers[n]}),i&&(0,Q.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:k(`models.nativeGroupLabel`)}),b&&(0,Q.jsx)(`span`,{className:`badge badge-amber`,role:`status`,title:es(k,b),children:k(`models.discoveryFailedBadge`)}),(0,Q.jsx)(`span`,{className:`muted mono text-label`,children:k(`models.active`,{active:p,total:f.length})}),m.length>0&&(0,Q.jsx)(`span`,{className:`models-chip mono text-caption`,children:k(`models.newCount`,{count:m.length})})]}),(0,Q.jsxs)(`div`,{className:`row models-provider-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm models-alias-edit`,"aria-label":k(`models.editProviderAlias`),title:k(`models.editProviderAlias`),onClick:()=>void $t(n),children:(0,Q.jsx)(le,{style:{width:14,height:14}})}),(0,Q.jsx)(ln,{on:st.defaults.providers[n]??st.defaults.global,onClick:()=>void tn(!(st.defaults.providers[n]??st.defaults.global),n),label:k(`models.useDefaultAliases`),showLabel:!0}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:e=>{e.stopPropagation(),rn(`add`),on(n),cn(``),mn(``),gn(``),bn(``),Sn(!1),wn([`text`]),En(!1),On([]),kn.current=!1,Nn(``),jt(!0)},"aria-haspopup":`dialog`,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`+`}),` `,k(`models.customAdd`)]}),(()=>{let e=rt[n];if(!e)return null;let t=Ke||dt!==null,r=e.mode===`custom`&&e.appliedVersion!==void 0&&e.appliedVersion<e.availableVersion;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":k(`models.presetLabel`),children:[[`preset`,`all`].map(r=>(0,Q.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:Ke||t||O,onClick:t=>{t.stopPropagation(),Jr(n,r,r===`preset`&&e.mode===`custom`?e:void 0)},children:k(`models.presetMode_${r}`)},r)),e.mode===`custom`&&(0,Q.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":!0,className:`btn btn-sm btn-primary`,disabled:!0,children:k(`models.presetMode_custom`)})]}),e.mode===`preset`&&(0,Q.jsx)(`span`,{className:`muted mono text-label`,children:k(`models.presetSummary`,{count:String(e.presetCount),total:String(e.totalCount),version:String(e.availableVersion)})}),r&&(0,Q.jsx)(`span`,{className:`badge badge-amber`,role:`status`,children:k(`models.presetUpdateAvailable`,{version:String(e.availableVersion)})})]})})(),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,disabled:Ke&&!$e.pending||A||O,onClick:()=>M(!0),children:k(`models.allOn`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,disabled:Ke&&!$e.pending||j||O,onClick:()=>M(!1),children:k(`models.allOff`)}),(0,Q.jsxs)(`div`,{className:`models-cap-cluster`,children:[(0,Q.jsx)(ln,{on:g,onClick:()=>Mr(n),disabled:Ke,label:k(`models.contextCapLabel`),showLabel:!0}),(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(dn,{value:be[n]?fs:String(_),options:[...!y.has(_)&&!be[n]?[{value:String(_),label:vs(_)}]:[],...v.map(e=>({value:String(e),label:vs(e)})),{value:fs,label:k(`models.custom`)}],onChange:e=>Rr(n,e),disabled:Ke||!g,label:k(`models.capValue`,{value:vs(_)}),title:k(`models.contextCapLabel`)}),g&&be[n]&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`input`,{className:`input`,style:{width:120},inputMode:`numeric`,placeholder:k(`models.customPlaceholder`),value:Se[n]??``,onChange:e=>we(t=>({...t,[n]:e.target.value})),onKeyDown:e=>{e.key===`Enter`&&zr(n)},disabled:Ke,"aria-label":k(`models.customPlaceholder`)}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>zr(n),disabled:Ke,className:`btn btn-ghost btn-sm`,children:k(`models.customApply`)})]})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>Er(t),"aria-haspopup":`dialog`,children:k(`models.contextSettings`)})]})]})]}),!s&&(0,Q.jsxs)(`div`,{className:`models-provider-body`,children:[i&&(0,Q.jsx)(`p`,{className:`muted text-label models-provider-hint`,children:k(`models.nativeHint`)}),!i&&at&&(0,Q.jsxs)(`div`,{className:`row models-provider-hint`,children:[(0,Q.jsx)(`span`,{className:`muted text-label`,children:k(`models.newPolicyProvider`)}),(0,Q.jsx)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":k(`models.newPolicyProvider`),children:[`off`,`on`].map(e=>(0,Q.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":(at.providers[n]??`inherit`)===e,className:`btn btn-sm${(at.providers[n]??`inherit`)===e?` btn-primary`:` btn-ghost`}`,onClick:()=>void qr(e,n),children:k(`models.newPolicy_${e}`)},e))})]}),!i&&(0,Q.jsx)(AC,{summary:F.find(e=>e.name===n),apiBase:e,onSaved:(e,t)=>{Ve(e,t),e&&br(!0)}}),r.length===0&&(0,Q.jsx)(MC,{liveModels:a,discovery:o,showFailureBadge:!1}),r.length>0&&b&&(0,Q.jsx)(NC,{}),u&&(0,Q.jsx)(`div`,{className:`row models-provider-hint`,children:(0,Q.jsx)(ln,{on:l,onClick:()=>ee(e=>({...e,[n]:!l})),label:k(`models.freeOnly`),showLabel:!0})}),d&&f.length===0&&r.length>0&&(0,Q.jsx)(`p`,{className:`muted text-label`,role:`status`,children:k(`models.noFreeMatch`)}),r.length>30&&(0,Q.jsx)(`input`,{className:`input`,placeholder:k(`models.search`),value:V[n]??``,onChange:e=>H(t=>({...t,[n]:e.target.value})),"aria-label":k(`models.search`)}),T.map(e=>{let t=!c(e);return(0,Q.jsxs)(`div`,{className:`model-row-wrap`,onMouseEnter:t=>$r(e.namespaced,t.currentTarget),onMouseLeave:ti,onFocus:t=>ei(e.namespaced,t.currentTarget),onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||tr(null)},children:[(0,Q.jsxs)(`div`,{className:`row models-model-row`,children:[(0,Q.jsx)(ln,{on:!t,onClick:()=>void jr(`models`,n,[{id:e.id,native:e.native===!0}],t),disabled:Ke&&!$e.pending||e.initialSelectionPending,label:e.native?e.id:e.namespaced}),e.initialSelectionPending&&(0,Q.jsx)(`span`,{className:`models-chip muted`,role:`status`,children:k(`models.initialSelectionPending`)}),e.quotaInactiveReason===`no_credit`&&(0,Q.jsx)(`span`,{className:`models-chip muted`,role:`status`,title:k(`models.inactiveNoCreditHint`),children:k(`models.inactiveNoCredit`)}),st.models[n]?.[e.id]&&(0,Q.jsx)(`strong`,{className:`mono text-control`,children:st.models[n][e.id].alias}),(0,Q.jsxs)(`span`,{className:`models-model-identity`,children:[(0,Q.jsx)(`code`,{className:`mono text-control`,style:{color:t?`var(--faint)`:`var(--text)`,textDecoration:t?`line-through`:`none`},children:e.native?zv(e.id):e.namespaced}),!e.native&&e.displayName?.trim()&&e.displayName.trim()!==e.namespaced&&(0,Q.jsx)(`span`,{className:`models-model-friendly text-caption`,children:e.displayName.trim()})]}),st.models[n]?.[e.id]?.source===`builtin`&&(0,Q.jsx)(`span`,{className:`models-chip muted text-caption`,children:k(`models.aliasAuto`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":k(`models.editModelAlias`),title:k(`models.editModelAlias`),onClick:()=>void en(n,e.id),children:(0,Q.jsx)(le,{style:{width:13,height:13}})}),!e.native&&!e.custom&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption models-display-name-trigger`,"aria-haspopup":`dialog`,"aria-label":k(`models.displayNameActionLabel`,{model:e.namespaced}),onClick:t=>{Xt.current=t.currentTarget,Ht(null),Wt(null),qt(!1),Nt(e)},children:k(`models.displayNameAction`)}),e.custom&&(0,Q.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:k(`models.customBadge`)}),!e.native&&e.provider!==`combo`&&(0,Q.jsxs)(Q.Fragment,{children:[e.manualPricing===!0&&(0,Q.jsx)(`span`,{className:`models-chip muted text-caption`,children:k(`pricing.override.badge`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption models-display-name-trigger`,"aria-haspopup":`dialog`,"aria-label":k(`pricing.override.actionLabel`,{model:e.namespaced}),onClick:t=>{It.current=t.currentTarget,Ft(e)},children:k(`pricing.override.action`)})]}),!e.native&&!e.custom&&e.provider!==`combo`&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption models-display-name-trigger`,"aria-haspopup":`dialog`,"aria-label":k(`models.settingsTitle`,{model:e.namespaced}),onClick:()=>Rt(e),children:k(`models.customEdit`)}),!e.custom&&h.has(e.id)&&(0,Q.jsx)(`span`,{className:`badge badge-amber`,children:k(`models.newBadge`)}),e.contextCapped&&(0,Q.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:k(`models.contextCappedValue`,{value:vs(e.contextCap??q)})})]}),er?.namespaced===e.namespaced&&(()=>{let n=er.rect,r=n.bottom+4,i=r+360>window.innerHeight;return(0,Q.jsxs)(`div`,{className:`model-tip${e.custom?` has-actions`:``}${i?` flip-up`:``}`,role:`tooltip`,style:{position:`fixed`,left:n.left+24,...i?{bottom:window.innerHeight-n.top+4}:{top:r}},onMouseEnter:ni,onMouseLeave:ti,children:[(0,Q.jsx)(`div`,{className:`model-tip-id`,children:e.native?e.id:e.namespaced}),e.displayName&&(0,Q.jsx)(`div`,{className:`model-tip-display`,children:e.displayName}),e.custom&&(0,Q.jsx)(`span`,{className:`models-chip models-chip--tip muted mono text-caption`,children:k(`models.customBadge`)}),(0,Q.jsxs)(`div`,{className:`model-tip-grid`,children:[(0,Q.jsx)(`span`,{className:`model-tip-key`,children:k(`models.tipProvider`)}),(0,Q.jsx)(`span`,{className:`model-tip-val`,children:Ce(e.provider,k)}),(e.contextWindow||e.contextCap)&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`model-tip-key`,children:k(`models.tipContext`)}),(0,Q.jsx)(`span`,{className:`model-tip-val`,children:vs(e.contextWindow??e.contextCap??0)})]}),e.inputModalities&&e.inputModalities.length>0&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`model-tip-key`,children:k(`models.tipModalities`)}),(0,Q.jsx)(`span`,{className:`model-tip-val`,children:e.inputModalities.join(`, `)})]}),(0,Q.jsx)(`span`,{className:`model-tip-key`,children:k(`models.tipStatus`)}),(0,Q.jsx)(`span`,{className:`model-tip-val`,children:k(t?`models.tipDisabled`:`models.tipActive`)})]}),e.custom&&e.customId&&(0,Q.jsxs)(`div`,{className:`model-tip-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>{rn(`edit`),on(e.provider),cn(e.customId),mn(e.id),gn(e.displayName??``),bn(e.contextWindow?String(e.contextWindow):``),Sn(!1),wn(e.inputModalities??[`text`]),En(Array.isArray(e.reasoningEfforts)),On(e.reasoningEfforts??[]),kn.current=Array.isArray(e.reasoningEfforts),Nn(``),jt(!0),tr(null)},children:k(`models.customEdit`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,style:{color:`var(--red)`},onClick:()=>{ai(e.customId,e.displayName??e.id).finally(()=>tr(null))},children:k(`models.customDelete`)})]})]})})()]},e.namespaced)}),E>0&&(0,Q.jsx)(`button`,{type:`button`,onClick:()=>te(e=>({...e,[n]:w+60})),className:`btn btn-ghost btn-sm models-show-more`,children:k(`models.showMore`,{n:E})})]})]},n)},di=cr?wr.filter(e=>e.provider===cr):wr,fi=(e,t=!1)=>{let n={pickerOrder:e.pickerOrder,pickerOrderMode:e.pickerOrderMode,pickerAvailable:[]};Kt(Y,n),co(Y,n),t&&oe(`custom`),pe.refresh();let r=e.catalogRefresh,i=typeof r==`object`&&!!r&&`status`in r&&r.status===`committed`&&`degraded`in r&&r.degraded===!1;Ve(i,k(i?`models.pickerOrder.saved`:`models.pickerOrder.pending`)),p()},pi=async()=>{if(ue.current||!me||pe.state.showError||he===`custom`)return;let t=de.current,n=he,r=me.pickerAvailable,i=M(15e3);ue.current=i,ce(!0);let a=()=>de.current===t&&ue.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 vn(n,k(`models.pickerOrder.usageFailed`));if(!o())return;if(r?.usageIncomplete===!0)throw Error(k(`models.pickerOrder.usageIncomplete`));if(!E_(r?.models))throw Error(k(`models.pickerOrder.usageFailed`));t=r.models}if(!o())return;let a=A_(n,r,t,N),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 vn(s,k(`models.saveFailed`));if(!w_(c)||!(`ok`in c)||c.ok!==!0)throw Error(k(`models.saveFailed`));if(!o())return;fi({pickerOrder:c.pickerOrder,pickerOrderMode:c.pickerOrderMode,catalogRefresh:`catalogRefresh`in c?c.catalogRefresh:void 0}),oe(null)}catch(e){a()&&Ve(!1,e instanceof Error?e.message:k(`models.networkError`))}finally{i.clear(),a()&&(ue.current=null,ce(!1))}},mi=(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`models-control-top-row`,children:[at&&(0,Q.jsx)(UC,{label:k(`models.newPolicyGlobal`),children:(0,Q.jsx)(ln,{on:at.policy===`off`,onClick:()=>void qr(at.policy===`off`?`on`:`off`),label:k(`models.newPolicyGlobal`)})}),(0,Q.jsxs)(UC,{label:k(`models.useDefaultAliasesGlobal`),children:[(0,Q.jsx)(ln,{on:st.defaults.global,onClick:()=>void tn(!st.defaults.global),label:k(`models.useDefaultAliasesGlobal`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>ut(e=>!e),children:k(`models.aliases`)})]}),(0,Q.jsx)(WC,{shadowCall:ir,saving:ar,modelOptions:fr,onSave:e=>void sr(e)}),(0,Q.jsxs)(UC,{label:k(`models.autoReviewOverride`),hint:(0,Q.jsx)(pn,{content:k(`models.autoReviewOverrideHint`),side:`top`,maxWidth:320,children:(0,Q.jsx)(`span`,{style:{cursor:`help`},"aria-label":k(`models.autoReviewOverrideHint`),children:`ⓘ`})}),busy:!He,children:[(0,Q.jsx)(ln,{on:He?.enabled??!1,onClick:()=>void Ge({enabled:!He?.enabled}),disabled:!He||Ue,label:k(`models.autoReviewOverride`)}),(0,Q.jsx)(`div`,{className:`models-shadow-model-slot`,children:(0,Q.jsx)(dn,{value:He?.model??``,options:mr,onChange:e=>void Ge({model:e}),disabled:!He||Ue||!He.enabled,label:k(`models.autoReviewOverride`)})})]}),(pt||tt)&&(0,Q.jsxs)(UC,{label:k(`models.v2Label`),children:[(0,Q.jsx)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":k(`models.v2Label`),children:[`v1`,`default`,`v2`].map(e=>(0,Q.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":(tt?.multiAgentMode??`default`)===e,className:`btn btn-sm${(tt?.multiAgentMode??`default`)===e?` btn-primary`:` btn-ghost`}`,style:{background:(tt?.multiAgentMode??`default`)===e?void 0:`transparent`,color:(tt?.multiAgentMode??`default`)===e?void 0:`var(--muted)`},disabled:!tt||ht,onClick:()=>void Wr(e),children:k(`models.v2Mode_${e}`)},e))}),(0,Q.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:!tt,onClick:()=>Dt(!0),"aria-label":k(`models.v2Label`),"aria-haspopup":`dialog`,children:(0,Q.jsx)(De,{width:14,height:14,"aria-hidden":`true`})})]}),tt&&tt.multiAgentMode===`v2`&&(0,Q.jsx)(`div`,{className:`models-v2-keep-native-row`,children:(0,Q.jsxs)(`div`,{className:`models-v2-keep-native`,children:[(0,Q.jsx)(`span`,{className:`models-v2-keep-native-label text-caption`,children:k(`models.keepNativeOnV1`)}),(0,Q.jsx)(ln,{on:tt.keepNativeChatGptOnV1===!0,onClick:()=>void Yr(!tt.keepNativeChatGptOnV1),disabled:ht,label:k(`models.keepNativeOnV1`)}),(0,Q.jsx)(pn,{content:k(`models.keepNativeOnV1Hint`),side:`top`,maxWidth:360,children:(0,Q.jsx)(`span`,{className:`models-v2-keep-native-info`,"aria-label":k(`models.keepNativeOnV1Hint`),children:(0,Q.jsx)(De,{width:13,height:13,"aria-hidden":`true`})})})]})}),Ot&&(0,Q.jsx)(pr,{reason:`selection`,mode:Ot,docsUrl:dr(tt?.multiAgentSurfaceAdvisory)?.docsUrl??`https://opencodex.me/guides/subagent-v1-default/`,busy:ht,onContinue:()=>{let e=Ot;kt(null),Ur({multiAgentMode:e,multiAgentSurfaceAdvisoryAcknowledged:!0})},onChooseV1:()=>{kt(null),tt?.multiAgentMode!==`v1`&&Ur({multiAgentMode:`v1`,multiAgentSurfaceAdvisoryAcknowledged:!0})},onDismiss:()=>kt(null)})]}),tt&&(0,Q.jsxs)(`div`,{className:`models-v2-detail-row row`,children:[(0,Q.jsx)(`span`,{className:`muted text-control`,children:k(`models.v2ThreadsLabel`)}),(0,Q.jsx)(dn,{value:wt?`custom`:Xr===null?``:ms.has(Xr)?String(Xr):`custom`,options:[...Xr===null?[{value:``,label:k(`models.v2ThreadsDefault`)}]:[],...Xr!==null&&!ms.has(Xr)&&!wt?[{value:`custom`,label:String(Xr)}]:[],...ps.map(e=>({value:String(e),label:String(e)})),{value:`custom`,label:k(`models.custom`)}],onChange:e=>Qr(e),disabled:ht,label:k(`models.v2ThreadsLabel`)}),wt&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`input`,{className:`input`,style:{width:100},inputMode:`numeric`,value:St,onChange:e=>Ct(e.target.value),onKeyDown:e=>{e.key===`Enter`&&Zr(Number(St.replace(/[_,\s]/g,``)))},disabled:ht,"aria-label":k(`models.v2ThreadsLabel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:ht,onClick:()=>{Zr(Number(St.replace(/[_,\s]/g,``)))},children:k(`models.v2ThreadsApply`)})]}),tt.enabled&&tt.agentsMaxThreadsConflict&&(0,Q.jsx)(`span`,{className:`mono text-label`,style:{color:`var(--err, #e5484d)`},children:k(`models.v2Conflict`)}),_t&&(0,Q.jsx)(`span`,{className:`muted text-label`,children:_t})]}),(0,Q.jsxs)(`div`,{className:`row models-cap-row`,children:[(0,Q.jsx)(`span`,{className:`muted text-control`,children:k(`models.contextCapLabel`)}),(0,Q.jsx)(dn,{value:ve?fs:String(q),options:[...!ls.has(q)&&!ve?[{value:String(q),label:vs(q)}]:[],...cs.map(e=>({value:String(e),label:vs(e)})),{value:fs,label:k(`models.custom`)}],onChange:e=>Br(e),disabled:Ke,label:k(`models.contextCapLabel`)}),ve&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`input`,{className:`input`,style:{width:160},inputMode:`numeric`,placeholder:k(`models.customPlaceholder`),value:ge,onChange:e=>_e(e.target.value),onKeyDown:e=>{e.key===`Enter`&&Vr()},disabled:Ke,"aria-label":k(`models.customPlaceholder`)}),(0,Q.jsx)(`button`,{type:`button`,onClick:Vr,disabled:Ke,className:`btn btn-ghost btn-sm`,children:k(`models.customApply`)})]}),(0,Q.jsx)(ln,{on:Ir,onClick:Hr,disabled:Ke,label:k(`models.setAll`)}),(0,Q.jsx)(HC,{text:k(`models.setAllHint`,{value:vs(q)})})]}),(0,Q.jsxs)(`div`,{className:`row models-cap-row`,"aria-busy":se||pe.state.refreshing,children:[(0,Q.jsx)(`span`,{className:`muted text-control`,children:k(`models.pickerOrder.label`)}),(0,Q.jsx)(dn,{value:he,options:[{value:`default`,label:k(`models.pickerOrder.default`)},{value:`alphabetical`,label:k(`models.pickerOrder.alphabetical`)},{value:`provider`,label:k(`models.pickerOrder.provider`)},{value:`most-used`,label:k(`models.pickerOrder.mostUsed`)},{value:`custom`,label:k(`models.pickerOrder.custom`)}],onChange:e=>oe(e),disabled:se||!me||pe.state.showError,label:k(`models.pickerOrder.label`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void pi(),disabled:se||!me||pe.state.showError||he===`custom`||he!=="default"&&me.pickerAvailable.length===0,children:k(se?`models.pickerOrder.applying`:`models.pickerOrder.apply`)}),pe.state.showError&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{role:`alert`,children:k(`models.pickerOrder.loadFailed`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>pe.refresh(),children:k(`models.pickerOrder.retry`)})]}),(0,Q.jsx)(HC,{text:k(`models.pickerOrder.hint`)})]}),(0,Q.jsx)(U_,{showOrderEditor:he===`custom`,apiBase:e,active:S,identities:N,onBusyChange:ce,onAccepted:e=>fi(e,!0),onSaved:()=>vr.refresh()}),lt&&(0,Q.jsxs)(`div`,{className:`card models-aliases-card`,"aria-label":k(`models.aliasesTable`),children:[(0,Q.jsx)(`div`,{className:`row group-head`,children:(0,Q.jsx)(`strong`,{children:k(`models.aliases`)})}),Object.entries(st.models).flatMap(([e,t])=>Object.entries(t).map(([t,n])=>(0,Q.jsxs)(`div`,{className:`row models-model-row`,children:[(0,Q.jsxs)(`code`,{className:`mono text-caption`,style:{flex:1},children:[e,`/`,t]}),(0,Q.jsx)(`strong`,{className:`mono text-control`,children:n.alias}),(0,Q.jsx)(`span`,{className:`models-chip muted text-caption`,children:n.source===`builtin`?k(`models.aliasAuto`):k(`models.aliasUser`)}),n.stale&&(0,Q.jsx)(`span`,{className:`badge badge-amber`,children:k(`models.aliasStale`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":k(`models.editModelAlias`),onClick:()=>void en(e,t),children:(0,Q.jsx)(le,{style:{width:13,height:13}})})]},`${e}/${t}`)))]})]}),hi=N.filter(e=>e.custom).length,gi=(0,Q.jsxs)(`div`,{className:`row models-collapse-controls`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>Pr(!0),disabled:Ke,children:[(0,Q.jsx)(Ye,{width:12,height:12,"aria-hidden":`true`}),` `,k(`models.collapseAll`)]}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>Pr(!1),disabled:Ke,children:[(0,Q.jsx)(Ye,{width:12,height:12,"aria-hidden":`true`,style:{transform:`rotate(90deg)`}}),` `,k(`models.expandAll`)]}),(0,Q.jsx)(HC,{text:k(`models.orderHint`)}),(0,Q.jsx)(VC,{count:hi,label:k(`models.customSummary`,{count:hi})})]}),_i=(0,Q.jsx)(Q.Fragment,{children:wr.length===0&&(0,Q.jsx)(fn,{icon:(0,Q.jsx)(ze,{}),title:k(`models.noRouted`),children:k(`models.noRoutedHint`)})}),vi=(0,Q.jsxs)(Q.Fragment,{children:[Et&&(0,Q.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":k(`models.v2Label`),onClick:()=>Dt(!1),onKeyDown:e=>{e.key===`Escape`&&Dt(!1)},children:(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{children:k(`models.v2Label`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>Dt(!1),"aria-label":k(`common.close`),children:`×`})]}),(0,Q.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:k(`models.v2Help`)}),(0,Q.jsx)(`div`,{className:`models-help-link`,children:(0,Q.jsx)(`a`,{className:`text-control`,href:`https://opencodex.me/guides/sub-agent-surface/`,target:`_blank`,rel:`noreferrer`,style:{color:`var(--accent)`},children:k(`models.v2DocsLink`)})}),(0,Q.jsx)(`div`,{className:`modal-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>Dt(!1),children:k(`common.ok`)})})]})}),Pn&&(0,Q.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":k(`models.contextSettings`),onClick:()=>{Xn||Fn(null)},onKeyDown:e=>{e.key===`Escape`&&!Xn&&Fn(null)},children:(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{children:k(`models.contextSettingsTitle`,{provider:Ce(Pn,k)})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>Fn(null),disabled:Xn,"aria-label":k(`common.close`),children:`×`})]}),Qn&&(0,Q.jsx)($,{tone:`err`,children:Qn}),(0,Q.jsx)(`p`,{className:`modal-desc leading-relaxed`,children:k(`models.contextHint`)}),(0,Q.jsxs)(`div`,{className:`models-context-fields`,children:[(0,Q.jsxs)(`label`,{className:`text-label models-field`,children:[k(`models.contextDefault`),(0,Q.jsx)(`input`,{className:`input`,inputMode:`numeric`,value:Bn,onChange:e=>{Vn(e.target.value),Yn(!0)},disabled:Xn,placeholder:k(`models.contextAutomatic`),autoFocus:!0})]}),In.length>0&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`text-label models-field`,children:[k(`models.contextModel`),(0,Q.jsx)(dn,{value:Rn,options:In.map(e=>({value:e,label:e})),onChange:Dr,disabled:Xn,label:k(`models.contextModel`)})]}),(0,Q.jsxs)(`label`,{className:`text-label models-field`,children:[k(`models.contextModelOverride`),(0,Q.jsx)(`input`,{className:`input`,inputMode:`numeric`,value:Bv(Hn,Rn)??``,onChange:e=>{Un(t=>({...t,[Rn]:e.target.value})),qn(e=>new Set(e).add(Rn))},disabled:Xn,placeholder:k(`models.contextAutomatic`)})]})]})]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>Fn(null),disabled:Xn,children:k(`common.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>void Or(),disabled:Xn,children:k(Xn?`models.customSaving`:`models.customApply`)})]})]})}),At&&(0,Q.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":k(`models.customAdd`),onClick:()=>{An||jt(!1)},onKeyDown:e=>{e.key===`Escape`&&!An&&jt(!1)},children:(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{children:k(nn===`add`?`models.customAddTitle`:`models.customEditTitle`,{provider:Ce(an,k)})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>jt(!1),disabled:An,"aria-label":k(`common.close`),children:`×`})]}),Mn&&(0,Q.jsx)($,{tone:`err`,children:Mn}),(0,Q.jsxs)(`div`,{className:`models-field-stack`,children:[(0,Q.jsxs)(`label`,{className:`text-label models-field`,children:[k(`models.customFieldModelId`),(0,Q.jsx)(`input`,{className:`input`,value:un,onChange:e=>mn(e.target.value),disabled:An,placeholder:k(`models.customFieldModelIdPlaceholder`),autoFocus:!0})]}),(0,Q.jsxs)(`label`,{className:`text-label models-field`,children:[k(`models.customFieldDisplayName`),(0,Q.jsx)(`input`,{className:`input`,value:hn,onChange:e=>gn(e.target.value),disabled:An,placeholder:k(`models.customFieldDisplayNamePlaceholder`)})]}),(0,Q.jsxs)(`label`,{className:`text-label models-field`,children:[k(`models.customFieldContext`),(0,Q.jsxs)(`div`,{className:`row models-field-row`,children:[(0,Q.jsx)(dn,{value:xn?`custom`:_n,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:k(`models.custom`)}],onChange:e=>{e===`custom`?Sn(!0):(Sn(!1),bn(e))},disabled:An,label:k(`models.customFieldContext`)}),xn&&(0,Q.jsx)(`input`,{className:`input`,style:{width:120},inputMode:`numeric`,value:_n,onChange:e=>bn(e.target.value),disabled:An,placeholder:k(`models.customPlaceholder`),"aria-label":k(`models.customFieldContext`)})]})]}),(0,Q.jsxs)(`div`,{className:`text-label models-field`,children:[k(`models.customFieldModalities`),(0,Q.jsx)(`div`,{className:`row models-field-row`,children:[`text`,`image`,`audio`].map(e=>(0,Q.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:Cn.includes(e),onChange:t=>{wn(n=>t.target.checked?[...n,e]:n.filter(t=>t!==e))},disabled:An}),(0,Q.jsx)(`span`,{className:`text-control`,children:e})]},e))})]}),(0,Q.jsxs)(`div`,{className:`text-label models-field`,children:[k(`models.customFieldReasoning`),(0,Q.jsx)(`div`,{className:`row models-field-row`,children:(0,Q.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:Tn,onChange:e=>{if(En(e.target.checked),e.target.checked&&!kn.current){kn.current=!0;let e=N.find(e=>e.provider===an&&e.id===un),t=Array.isArray(e?.reasoningEfforts)?e.reasoningEfforts:void 0;On(t??[...os])}},disabled:An}),(0,Q.jsx)(`span`,{className:`text-control`,children:k(`models.customFieldReasoningOverride`)})]})}),Tn&&(0,Q.jsx)(`div`,{className:`row models-field-row`,style:{flexWrap:`wrap`},children:os.map(e=>(0,Q.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:Dn.includes(e),onChange:t=>{On(n=>t.target.checked?[...n,e]:n.filter(t=>t!==e))},disabled:An}),(0,Q.jsx)(`span`,{className:`text-control`,children:k(`models.reasoningEffort.${e}`)})]},e))})]})]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>jt(!1),disabled:An,children:k(`common.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:An||!un.trim(),onClick:()=>{let e=un.trim(),t=hn.trim(),n=ws(_n);if(n===void 0)Nn(k(`models.contextInvalid`));else if(nn===`add`){let r=Tn?Dn:void 0;ri(an,e,t||void 0,n??void 0,Cn.length>0?Cn:void 0,r)}else ii(sn,{modelId:e,displayName:t,contextWindow:n,inputModalities:Cn,reasoningEfforts:Tn?Dn:null})},children:k(An?`models.customSaving`:nn===`add`?`models.customAddBtn`:`models.customEditBtn`)})]})]})})]}),yi=(0,Q.jsxs)(`div`,{className:`models-workspace-shell`,children:[je&&(0,Q.jsxs)(`div`,{className:`action-toast notice ${Ie?`notice-ok`:`notice-err`}`,role:`status`,"aria-live":`polite`,children:[Ie?(0,Q.jsx)(Oe,{}):(0,Q.jsx)(Ne,{}),(0,Q.jsx)(`span`,{children:je})]}),yr.showError&&(0,Q.jsx)($,{tone:`err`,children:k(`models.loadFail`)}),Pe.length>0&&(0,Q.jsx)(`div`,{className:`models-integration-warning`,children:(0,Q.jsxs)($,{tone:`warn`,children:[k(`models.integrationRefreshWarning`),(0,Q.jsx)(`ul`,{children:Pe.map(e=>(0,Q.jsxs)(`li`,{children:[e.client,e.profileId===void 0?``:`:${e.profileId}`,`: `,ib(k,{clientId:e.client,message:e.reason===`integration_mutation_busy`?k(`integrations.error.busy`):e.reason,reason:e.refusalReason,snapshotPath:e.snapshotPath,residual:e.residual})]},`${e.client}:${e.profileId??`all`}`))})]})}),(0,Q.jsx)(BC,{title:k(`models.settingsPanel.title`),attentionLabel:k(`models.settingsPanel.attention`),warn:!!(tt?.enabled&&tt.agentsMaxThreadsConflict)||_t!==``||pe.state.showError,summary:zC(k,{multiAgentMode:tt?.multiAgentMode,v2Threads:Xr,keepNativeOnV1:tt?.keepNativeChatGptOnV1===!0,shadowEnabled:ir?.enabled===!0,shadowModel:ir?.model,windowOn:Ir,windowValue:q,newModelsOff:at?.policy===`off`,aliasesOn:st.defaults.global,autoReviewEnabled:He?.enabled===!0,autoReviewModel:He?.model,pickerMode:j_(me?.pickerAvailable??[],me?.pickerOrder??[],me?.pickerOrderMode)}),children:mi}),(0,Q.jsxs)(`div`,{className:`models-workspace-root`,"aria-busy":$e.pending||yr.refreshing||void 0,children:[(0,Q.jsxs)(`aside`,{className:`models-workspace-rail`,"aria-label":k(`nav.models`),children:[(0,Q.jsxs)(`div`,{className:`models-workspace-rail-header`,children:[(0,Q.jsx)(`span`,{className:`models-workspace-rail-title`,children:k(`models.workspace.providers`)}),(0,Q.jsx)(`span`,{className:`models-workspace-rail-count`,children:wr.length})]}),(0,Q.jsxs)(`div`,{className:`models-workspace-rail-list`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`models-workspace-rail-row${cr===null?` models-workspace-rail-row--selected`:``}`,onClick:()=>lr(null),"aria-current":cr===null?`true`:void 0,children:[(0,Q.jsx)(`span`,{className:`models-workspace-rail-name`,children:k(`models.workspace.allProviders`)}),(0,Q.jsx)(`span`,{className:`models-workspace-rail-meta`,children:k(`models.active`,{active:kr,total:N.length})})]}),wr.map(e=>{let{provider:t,rows:n}=e,r=n.filter(e=>et(li,t,e.id,e.native===!0,L.has(e.namespaced))).length;return(0,Q.jsxs)(`button`,{type:`button`,className:`models-workspace-rail-row${cr===t?` models-workspace-rail-row--selected`:``}`,onClick:()=>lr(t),"aria-current":cr===t?`true`:void 0,children:[(0,Q.jsx)(`span`,{className:`models-workspace-rail-name`,children:Ce(t,k)}),(0,Q.jsx)(`span`,{className:`models-workspace-rail-meta`,children:k(`models.active`,{active:r,total:n.length})})]},t)})]})]}),(0,Q.jsxs)(`section`,{className:`models-workspace-main`,"aria-label":k(`models.workspace.mainAria`),children:[gi,(0,Q.jsx)(`div`,{className:`models-provider-list`,children:di.map(e=>ui(e))}),wr.length===0&&_i]})]}),vi]});return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`page-head`,children:[(0,Q.jsx)(`h2`,{children:k(`nav.models`)}),(0,Q.jsx)(`div`,{className:`page-head-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:()=>{h()},disabled:m,"aria-label":k(m?`dash.codexRestarting`:`dash.codexRestart`),title:k(m?`dash.codexRestarting`:`dash.codexRestart`),children:(0,Q.jsx)(ae,{})})})]}),(0,Q.jsx)(x_,{state:o,controller:{restarting:m,restart:h}}),(0,Q.jsx)(kC,{tab:g,onSelect:x,meta:Ar}),(0,Q.jsx)(`p`,{className:`page-sub`,children:k(YC[g])}),g===`catalog`&&(0,Q.jsx)(KC,{connected:r,catalogSyncedAt:i}),(0,Q.jsx)(`div`,{className:`models-tab-panel`,role:`tabpanel`,id:DC(`catalog`),"aria-labelledby":EC(`catalog`),hidden:g!==`catalog`,children:(0,Q.jsx)(db,{pageName:k(`models.tab.catalog`),title:k(`errorBoundary.title`),message:k(`errorBoundary.message`),detailsLabel:k(`errorBoundary.details`),reloadLabel:k(`errorBoundary.reload`),children:ci?(0,Q.jsx)(lb,{label:k(`models.loading`),rows:5}):si===null?yi:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)($,{tone:`err`,children:si}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>vr.refresh(),children:k(`common.retry`)})]})})}),(0,Q.jsx)(`div`,{className:`models-tab-panel models-tab-panel--fill`,role:`tabpanel`,id:DC(`combos`),"aria-labelledby":EC(`combos`),hidden:g!==`combos`,children:v.has(`combos`)&&(0,Q.jsx)(db,{pageName:k(`models.tab.combos`),title:k(`errorBoundary.title`),message:k(`errorBoundary.message`),detailsLabel:k(`errorBoundary.details`),reloadLabel:k(`errorBoundary.reload`),children:(0,Q.jsx)(cx,{apiBase:e,active:g===`combos`,onCountChange:w})})}),(0,Q.jsx)(`div`,{className:`models-tab-panel`,role:`tabpanel`,id:DC(`routing`),"aria-labelledby":EC(`routing`),hidden:g!==`routing`,children:v.has(`routing`)&&(0,Q.jsx)(db,{pageName:k(`models.tab.routing`),title:k(`errorBoundary.title`),message:k(`errorBoundary.message`),detailsLabel:k(`errorBoundary.details`),reloadLabel:k(`errorBoundary.reload`),children:(0,Q.jsx)(qx,{apiBase:e,active:g===`routing`,onCountChange:E})})}),(0,Q.jsx)(`div`,{className:`models-tab-panel`,role:`tabpanel`,id:DC(`compatibility`),"aria-labelledby":EC(`compatibility`),hidden:g!==`compatibility`,children:v.has(`compatibility`)&&(0,Q.jsx)(db,{pageName:k(`models.tab.compatibility`),title:k(`errorBoundary.title`),message:k(`errorBoundary.message`),detailsLabel:k(`errorBoundary.details`),reloadLabel:k(`errorBoundary.reload`),children:(0,Q.jsx)(xC,{apiBase:e,active:g===`compatibility`,onCountChange:O})})}),Mt&&(0,Q.jsx)(G_,{model:Mt,saving:zt,requestError:Vt,currentNamePending:Gt,mutationOutcomeUnknown:Ut?.confirmed===!1,onRetry:Ut?()=>void Cr(Ut.value):void 0,onEdit:()=>Wt(null),onSave:e=>void Cr(e),onReset:()=>void Cr(null),onClose:Sr}),Pt&&(0,Q.jsx)(dv,{model:Pt,apiBase:e,onRefresh:e=>br(!0,e),onClose:()=>{let e=It.current;Ft(null),window.setTimeout(()=>{e?.isConnected&&e.focus()},0)}},`${e}/${Pt.namespaced}`),Lt&&(0,Q.jsx)(yv,{row:Lt,apiBase:e,onRefresh:e=>br(!0,e),onFeedback:Ve,onClose:()=>Rt(null)},`${e}/${Lt.namespaced}`)]})}function ZC(e){return[...new Set(e.filter(e=>!e.disabled&&!e.initialSelectionPending).map(e=>e.namespaced))]}function QC({apiBase:e,value:t,disabled:r,onChange:i}){let a=n(),o=uo(`advisor-models:${e}`,[e],async t=>{let n=await fetch(`${e}/api/models`,{signal:t});if(!n.ok)throw Error(String(n.status));let r=await n.json();if(!Array.isArray(r)||!r.every(e=>e&&typeof e.namespaced==`string`&&e.namespaced.length>0))throw Error(`Invalid model catalog`);return r},{isEmpty:e=>e.length===0}),{state:s}=o,c=ZC(s.data??[]),l=t!==``&&!c.includes(t),u=[{value:``,label:a(`advisor.modelClear`)},...l?[{value:t,label:t}]:[],...c.map(e=>({value:e,label:e}))];return(0,Q.jsxs)(`div`,{"aria-busy":s.showSkeleton||s.refreshing,children:[(0,Q.jsx)(dn,{id:`advisor-model`,value:t,options:u,label:a(`advisor.model`),describedBy:`advisor-model-hint`,disabled:r||s.showSkeleton,onChange:i}),(0,Q.jsx)(`p`,{id:`advisor-model-hint`,className:`muted setting-hint`,children:a(`advisor.modelHint`)}),s.showSkeleton&&(0,Q.jsx)($,{tone:`warn`,children:a(`common.loading`)}),s.showError&&!s.showSkeleton&&(0,Q.jsxs)($,{tone:`err`,children:[a(`advisor.modelsLoadFailed`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:r,onClick:()=>o.refresh(),children:a(`common.retry`)})]}),!s.showSkeleton&&!s.showError&&c.length===0&&(0,Q.jsxs)($,{tone:`warn`,children:[a(`advisor.modelsEmpty`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:r,onClick:()=>o.refresh(),children:a(`common.retry`)})]}),!s.showSkeleton&&!s.showError&&l&&(0,Q.jsx)($,{tone:`warn`,children:a(`advisor.modelUnavailable`)})]})}function $C({entries:e}){let t=n();return e.length?(0,Q.jsx)(`div`,{className:`tbl-wrap`,children:(0,Q.jsxs)(`table`,{className:`tbl advisor-activity-table`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:t(`advisor.activity.started`)}),(0,Q.jsx)(`th`,{children:t(`advisor.activity.trigger`)}),(0,Q.jsx)(`th`,{children:t(`advisor.model`)}),(0,Q.jsx)(`th`,{children:t(`advisor.effort`)}),(0,Q.jsx)(`th`,{children:t(`advisor.activity.tokens`)}),(0,Q.jsx)(`th`,{children:t(`advisor.activity.duration`)})]})}),(0,Q.jsx)(`tbody`,{children:e.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`time`,{dateTime:new Date(e.startedAt).toISOString(),children:new Date(e.startedAt).toLocaleTimeString()})}),(0,Q.jsxs)(`td`,{children:[(0,Q.jsx)(`div`,{children:t(`advisor.activity.trigger.${e.trigger}`)}),(0,Q.jsx)(`span`,{className:e.status===`ok`?`badge badge-green`:`badge badge-muted`,children:t(`advisor.activity.status.${e.status}`)})]}),(0,Q.jsxs)(`td`,{children:[(0,Q.jsx)(`code`,{children:e.advisorModel}),(0,Q.jsx)(`div`,{className:`muted`,children:(0,Q.jsx)(`code`,{children:e.workerModel})})]}),(0,Q.jsx)(`td`,{children:(0,Q.jsxs)(`code`,{children:[e.requestedEffort,` → `,e.effectiveEffort??t(`logs.tokens.unreported`)]})}),(0,Q.jsx)(`td`,{className:`num`,children:e.usage?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{title:t(`logs.tokens.input`),children:e.usage.inputTokens??`—`}),` / `,(0,Q.jsx)(`span`,{title:t(`logs.tokens.output`),children:e.usage.outputTokens??`—`})]}):t(`logs.tokens.unreported`)}),(0,Q.jsx)(`td`,{className:`num`,children:e.durationMs===null?`—`:(0,Q.jsxs)(Q.Fragment,{children:[e.durationMs,` ms`]})})]},e.id))})]})}):(0,Q.jsx)(`p`,{className:`muted`,children:t(`advisor.activity.empty`)})}function ew({apiBase:e}){let t=n(),r=uo(`advisor-activity:${e}`,[e],async t=>{let n=await fetch(`${e}/api/advisor/activity`,{signal:t});if(!n.ok)throw Error(String(n.status));return await n.json()},{isEmpty:e=>e.entries.length===0,pollMs:5e3,pauseWhenHidden:!0}),{state:i}=r;return(0,Q.jsxs)(`section`,{"aria-label":t(`advisor.activity.title`),children:[(0,Q.jsx)(`h3`,{children:t(`advisor.activity.title`)}),(0,Q.jsx)(`p`,{className:`muted`,children:t(`advisor.activity.note`)}),i.showSkeleton&&(0,Q.jsx)(`p`,{className:`muted`,children:t(`common.loading`)}),i.showError&&(0,Q.jsxs)($,{tone:`err`,children:[t(`advisor.activity.failed`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>r.refresh(),children:t(`common.retry`)})]}),i.data&&(0,Q.jsx)($C,{entries:i.data.entries})]})}var tw=[`low`,`medium`,`high`,`xhigh`,`max`,`ultra`];function nw({apiBase:e,initial:t}){let r=n(),[i,a]=(0,Z.useState)(t),[o,s]=(0,Z.useState)(t),[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(``),m=(0,Z.useRef)(null);(0,Z.useEffect)(()=>()=>{m.current!==null&&(clearTimeout(m.current),m.current=null)},[]);let h=(0,Z.useCallback)(async()=>{m.current!==null&&(clearTimeout(m.current),m.current=null),d(!1),l(!0),p(``);let t=o;try{let n=await fetch(`${e}/api/advisor/settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({enabled:t.enabled,model:t.model,effort:t.effort,policy:t.policy,...t.maxConsultationsPerTask===void 0?{}:{maxConsultationsPerTask:t.maxConsultationsPerTask},timeoutMs:t.timeoutMs,contextSharingConsent:t.contextSharingConsent})});if(!n.ok){let e=await n.json().catch(()=>null);p(e?.error?.message??String(n.status));return}let r=await n.json();a(r.settings),s(e=>JSON.stringify(e)===JSON.stringify(t)?r.settings:e),d(!0),m.current=setTimeout(()=>{m.current=null,d(!1)},2500)}catch(e){p(e instanceof Error?e.message:String(e))}finally{l(!1)}},[e,o]),g=(0,Z.useCallback)(e=>{p(``),s(t=>({...t,...e}))},[]),_=JSON.stringify(o)!==JSON.stringify(i),v=o.enabled&&o.model.trim()===``,y=o.enabled&&o.model.trim()!==``&&o.contextSharingConsent!==`v1`;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{style:{marginTop:`0.75rem`},children:[(0,Q.jsxs)(`div`,{className:`advisor-editor-row`,children:[(0,Q.jsx)(`span`,{className:`advisor-editor-label`,children:r(`advisor.enabled`)}),(0,Q.jsxs)(`label`,{className:`toggle`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:o.enabled,disabled:c,"aria-label":r(`advisor.enabled`),onChange:e=>g({enabled:e.target.checked})}),(0,Q.jsx)(`span`,{className:`slider`,"aria-hidden":`true`})]})]}),(0,Q.jsxs)(`div`,{className:`advisor-editor-row`,children:[(0,Q.jsx)(`label`,{htmlFor:`advisor-model`,className:`advisor-editor-label`,children:r(`advisor.model`)}),(0,Q.jsx)(QC,{apiBase:e,value:o.model,disabled:c,onChange:e=>g({model:e})})]}),(0,Q.jsxs)(`div`,{className:`advisor-editor-row`,children:[(0,Q.jsx)(`label`,{htmlFor:`advisor-effort`,className:`advisor-editor-label`,children:r(`advisor.effort`)}),(0,Q.jsx)(`select`,{id:`advisor-effort`,value:o.effort,disabled:c,onChange:e=>g({effort:e.target.value}),children:tw.map(e=>(0,Q.jsx)(`option`,{value:e,children:r(`models.reasoningEffort.${e}`)},e))})]}),(0,Q.jsxs)(`div`,{className:`advisor-editor-row`,children:[(0,Q.jsx)(`label`,{htmlFor:`advisor-policy`,className:`advisor-editor-label`,children:r(`advisor.policy`)}),(0,Q.jsxs)(`select`,{id:`advisor-policy`,value:o.policy,disabled:c,onChange:e=>g({policy:e.target.value}),children:[(0,Q.jsx)(`option`,{value:`manual`,children:r(`advisor.policy.manual`)}),(0,Q.jsx)(`option`,{value:`preflight`,children:r(`advisor.policy.preflight`)}),(0,Q.jsx)(`option`,{value:`adaptive`,children:r(`advisor.policy.adaptive`)})]})]}),o.policy===`adaptive`&&(0,Q.jsxs)(`div`,{className:`advisor-editor-row`,children:[(0,Q.jsx)(`label`,{htmlFor:`advisor-task-limit`,className:`advisor-editor-label`,children:r(`advisor.taskLimit`)}),(0,Q.jsx)(`select`,{id:`advisor-task-limit`,value:o.maxConsultationsPerTask??3,disabled:c,onChange:e=>g({maxConsultationsPerTask:Number(e.target.value)}),children:[1,2,3].map(e=>(0,Q.jsx)(`option`,{value:e,children:e},e))})]}),o.policy===`adaptive`&&(0,Q.jsx)(`p`,{className:`muted`,children:r(`advisor.adaptiveNote`)}),(0,Q.jsx)(`div`,{style:{margin:`0.8rem 0`},children:(0,Q.jsxs)(`label`,{style:{display:`flex`,alignItems:`flex-start`,gap:`0.6rem`},children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:o.contextSharingConsent===`v1`,disabled:c,"aria-label":r(`advisor.consent.label`),onChange:e=>g({contextSharingConsent:e.target.checked?`v1`:null})}),(0,Q.jsx)(`span`,{children:r(`advisor.consent.label`)})]})}),(0,Q.jsxs)(`div`,{className:`advisor-editor-row`,children:[(0,Q.jsx)(`label`,{htmlFor:`advisor-timeout`,className:`advisor-editor-label`,children:r(`advisor.timeout`)}),(0,Q.jsx)(`input`,{id:`advisor-timeout`,type:`number`,min:1e3,max:6e5,value:o.timeoutMs,disabled:c,onChange:e=>{let t=e.target.value.trim();if(t===``)return;let n=Number(t);Number.isFinite(n)&&g({timeoutMs:n})}})]})]}),v&&(0,Q.jsx)($,{tone:`warn`,children:r(`advisor.warning.noModel`)}),y&&(0,Q.jsx)($,{tone:`warn`,children:r(`advisor.consent.required`)}),f&&(0,Q.jsx)($,{tone:`err`,children:f}),u&&(0,Q.jsx)($,{tone:`ok`,children:r(`advisor.saved`)}),(0,Q.jsx)(`div`,{style:{marginTop:`0.75rem`},children:(0,Q.jsx)(`button`,{type:`button`,className:`btn`,disabled:!_||c,onClick:()=>void h(),children:r(c?`common.loading`:`advisor.save`)})})]})}function rw({apiBase:e}){let t=n(),r=uo(`advisor-settings:${e}`,[e],async t=>{let n=await fetch(`${e}/api/advisor/settings`,{signal:t});if(!n.ok)throw Error(String(n.status));return await n.json()},{isEmpty:()=>!1}),{state:i}=r,a=(0,Q.jsx)(`h2`,{children:t(`nav.advisor`)});return(0,Q.jsxs)(`section`,{className:`panel`,children:[a,(0,Q.jsx)(`p`,{className:`muted`,children:t(`advisor.description`)}),(0,Q.jsxs)(`details`,{className:`advisor-notices`,style:{margin:`0.5rem 0`},children:[(0,Q.jsx)(`summary`,{className:`muted text-label`,style:{cursor:`pointer`,padding:`2px 2px`},children:t(`advisor.notices`)}),(0,Q.jsx)($,{tone:`warn`,children:t(`advisor.costNote`)}),(0,Q.jsx)($,{tone:`warn`,children:t(`advisor.privacyNote`)}),(0,Q.jsx)($,{tone:`warn`,children:t(`advisor.disclosure`)})]}),i.showSkeleton&&(0,Q.jsx)($,{tone:`warn`,children:t(`common.loading`)}),i.showError&&!i.showSkeleton&&(0,Q.jsxs)($,{tone:`err`,children:[t(`advisor.loadFailed`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>r.refresh(),children:t(`common.retry`)})]}),i.data!==void 0&&(0,Q.jsx)(nw,{apiBase:e,initial:i.data.settings},r.hasSucceeded?`ready`:`cold`),(0,Q.jsx)(ew,{apiBase:e})]})}function iw(e,t){let n=new Set(t);return[...new Set([...e.filter(e=>n.has(e)),...t])]}function aw({apiBase:e,roster:t}){let r=n(),[i,a]=(0,Z.useState)(null),[o,s]=(0,Z.useState)(``),[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(``),[f,p]=(0,Z.useState)(!1),[m,h]=(0,Z.useState)(0),[g,_]=(0,Z.useState)(null),v=c||g?.retry!==m||g.t!==r,y=(0,Z.useRef)(!1),b=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>{b.current=!0,y.current=!0;let t=new AbortController,n=!1;return(async()=>{try{let i=await vn(await fetch(`${e}/api/subagent-models`,{signal:t.signal}),r(`sub.loadFail`));if(n)return;let o={force:i?.force??null,forceAvailable:i?.forceAvailable??[],forceStatus:i?.forceStatus??null};a(o),s(o.force??``),d(``)}catch{n||d(r(`sub.loadFail`))}finally{n||(y.current=!1,_({retry:m,t:r}))}})(),()=>{n=!0,b.current=!1,t.abort()}},[e,m,r]);async function x(t){if(!(!i||v||y.current)){y.current=!0,l(!0),d(``),p(!1);try{let n=await vn(await fetch(`${e}/api/subagent-models`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({force:t})}),r(`sub.saveFailed`));if(!b.current)return;a(e=>e&&{...e,force:n?.force??null,forceStatus:null}),s(n?.force??o),p(!0),h(e=>e+1)}catch{b.current&&d(r(`sub.saveFailed`))}finally{y.current=!1,b.current&&l(!1)}}}let S=iw(t,i?.forceAvailable??[]),C=i?.force??o,w=S.includes(C),T=i?.forceStatus;return(0,Q.jsxs)(`section`,{className:`panel`,children:[(0,Q.jsx)(`h3`,{children:r(`sub.forceTitle`)}),(0,Q.jsx)(ln,{on:!!i?.force,disabled:!i||v||!i.force&&!w,label:r(`sub.forceTitle`),onClick:()=>{x(i?.force?null:o)}}),(0,Q.jsxs)(`label`,{className:`field-label`,children:[r(`sub.forceModel`),(0,Q.jsxs)(`select`,{className:`input`,value:C,disabled:!i||v,onChange:e=>{let t=e.target.value;i?.force?x(t):s(t)},children:[(0,Q.jsx)(`option`,{value:``,disabled:!0,children:r(`sub.forceChoose`)}),C&&!w&&(0,Q.jsx)(`option`,{value:C,disabled:!0,children:C}),S.map(e=>(0,Q.jsx)(`option`,{value:e,children:e},e))]})]}),(0,Q.jsx)(`p`,{className:`muted`,children:r(`sub.forceHelp`)}),(0,Q.jsx)(`p`,{className:`muted`,children:r(`sub.forceScope`)}),i?.force&&(!w||T?.targetValid===!1)&&(0,Q.jsx)($,{tone:`warn`,children:r(`sub.forceInvalid`)}),i?.force&&T?.support===`unsupported`&&(0,Q.jsx)($,{tone:`warn`,children:r(`sub.forceOld`)}),i?.force&&(!T||T.support===`unknown`)&&(0,Q.jsx)($,{tone:`warn`,children:r(`sub.forceUnknown`)}),i?.force&&T?.settingsOverride&&(0,Q.jsx)($,{tone:`warn`,children:r(`sub.forceOverride`)}),i?.force&&T?.settingsReadable===!1&&(0,Q.jsx)($,{tone:`warn`,children:r(`sub.forceSettingsUnknown`)}),f&&(0,Q.jsx)($,{tone:`ok`,children:r(`sub.forceSaved`)}),u&&(0,Q.jsxs)($,{tone:`err`,children:[u,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:v,onClick:()=>h(e=>e+1),children:r(`common.retry`)})]})]})}var ow=`section`;function sw(e,t){return[e,ow,t].join(`-`)}function cw(e){return[e,ow,``].join(`-`)}var lw=1200;function uw({scope:e,items:t,ariaLabel:n,mobileReadingLine:r}){let[i,a]=(0,Z.useState)(()=>r&&window.matchMedia(`(max-width: 760px)`).matches?r:72);(0,Z.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,Z.useState)(t[0]?.id??``),c=(0,Z.useRef)(null),l=(0,Z.useRef)(null),u=(0,Z.useCallback)(()=>{c.current=null,l.current!==null&&(clearTimeout(l.current),l.current=null)},[]),d=(0,Z.useCallback)(()=>{u();let n=null,r=1/0;for(let a of t){let t=document.getElementById(sw(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,Z.useEffect)(()=>()=>u(),[u]),(0,Z.useEffect)(()=>{if(typeof IntersectionObserver>`u`)return;let n=t.map(t=>document.getElementById(sw(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(sw(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(cw(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(sw(e,t));n&&(c.current=t,l.current!==null&&clearTimeout(l.current),l.current=setTimeout(d,lw),s(t),n.scrollIntoView({behavior:`smooth`,block:`start`}))};return(0,Q.jsx)(`div`,{className:`page-tabs section-tabs`,role:`tablist`,"aria-label":n,children:t.map(t=>(0,Q.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":o===t.id,"aria-controls":sw(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,Q.jsx)(`span`,{className:`section-tab-meta`,children:t.meta}):null]},t.id))})}var dw=1500,fw={fast:`integrations.lazycodexRoles.auto.tierFast`,standard:`integrations.lazycodexRoles.auto.tierStandard`,frontier:`integrations.lazycodexRoles.auto.tierFrontier`},pw={glance:`integrations.lazycodexRoles.auto.effortGlance`,measured:`integrations.lazycodexRoles.auto.effortMeasured`,thorough:`integrations.lazycodexRoles.auto.effortThorough`,exhaustive:`integrations.lazycodexRoles.auto.effortExhaustive`};function mw({apiBase:e,model:t,effort:r,available:i,saving:a,onAccept:o}){let s=n(),[c,l]=(0,Z.useState)(``),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(null),[m,h]=(0,Z.useState)(null),g=e=>{let t=i.find(t=>t.namespaced===e);return t?we(`${t.provider}/${t.model}`,s):e},_=async()=>{d(!0),p(null);try{let t=await fetch(`${e}/api/injection-model/suggest`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({work:c.trim()})});h(await vn(t,s(`sub.suggest.failed`))??null)}catch(e){h(null),p(e instanceof Error&&e.message?e.message:s(`sub.suggest.failed`))}finally{d(!1)}},v=m?.proposal,y=!!v?.proposedModel&&v.proposedModel===t&&(v.proposedEffort??``)===r,b=u?s(`sub.suggest.running`):m?s(`sub.suggest.title`):``;return(0,Q.jsxs)(`div`,{className:`swi-suggest`,children:[(0,Q.jsx)(`div`,{className:`sr-only`,"aria-live":`polite`,"aria-atomic":`true`,children:b}),(0,Q.jsx)(`label`,{className:`swi-suggest-label`,htmlFor:`swi-suggest-work`,children:s(`sub.suggest.label`)}),(0,Q.jsxs)(`div`,{className:`swi-suggest-input`,children:[(0,Q.jsx)(`textarea`,{id:`swi-suggest-work`,className:`input`,rows:2,maxLength:dw,value:c,placeholder:s(`sub.suggest.placeholder`),onChange:e=>l(e.target.value),disabled:u}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:u||a||c.trim()===``,onClick:()=>void _(),children:s(u?`sub.suggest.running`:`sub.suggest.submit`)})]}),f&&(0,Q.jsx)($,{tone:`err`,children:f}),m&&v&&(0,Q.jsxs)(`section`,{className:`swi-suggest-result`,"aria-label":s(`sub.suggest.title`),children:[(0,Q.jsxs)(`div`,{className:`swi-suggest-head`,children:[v.tier&&v.effortIntent&&(0,Q.jsx)(`span`,{className:`font-semibold`,children:s(`integrations.lazycodexRoles.auto.tierEffort`,{tier:s(fw[v.tier]),effort:s(pw[v.effortIntent])})}),(0,Q.jsx)(`span`,{className:`muted setting-hint`,children:s(`integrations.lazycodexRoles.auto.sizedWith`,{model:m.sizingModel})})]}),m.sizingError&&(0,Q.jsx)($,{tone:`warn`,children:s(`integrations.lazycodexRoles.auto.sizingFailed`,{error:m.sizingError})}),v.status===`unsized`?(0,Q.jsx)(`p`,{className:`muted setting-hint`,children:s(`integrations.lazycodexRoles.auto.unsized`,{reason:v.reason??``})}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`swi-suggest-change`,children:[(0,Q.jsxs)(`span`,{children:[v.model?g(v.model):s(`dash.injectionNone`),v.effort?` · ${v.effort}`:``]}),(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`→`}),v.proposedModel?(0,Q.jsxs)(`strong`,{children:[g(v.proposedModel),v.proposedEffort?` · ${v.proposedEffort}`:``]}):(0,Q.jsx)(`span`,{className:`muted`,children:s(`integrations.lazycodexRoles.auto.unassigned`,{reason:v.reason??``})})]}),v.rationale&&(0,Q.jsx)(`p`,{children:v.rationale}),v.moveUpIf&&(0,Q.jsx)(`p`,{className:`muted setting-hint`,children:s(`integrations.lazycodexRoles.auto.moveUp`,{text:v.moveUpIf})}),v.moveDownIf&&(0,Q.jsx)(`p`,{className:`muted setting-hint`,children:s(`integrations.lazycodexRoles.auto.moveDown`,{text:v.moveDownIf})})]}),(0,Q.jsxs)(`div`,{className:`swi-suggest-actions`,children:[y?(0,Q.jsx)(`span`,{className:`swi-suggest-done`,children:s(`integrations.lazycodexRoles.auto.alreadySet`)}):v.status===`proposed`&&v.proposedModel&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:a,onClick:()=>o({model:v.proposedModel,effort:v.proposedEffort??null}),children:s(`sub.suggest.accept`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:a,onClick:()=>h(null),children:s(`integrations.lazycodexRoles.auto.discard`)})]})]})]})}function hw({apiBase:e,model:t,effort:r,efforts:i,available:a,guidanceEnabled:o,syncCodexDefaults:s,saving:c,onSave:l,ultraMode:u,ultraSaving:d,onUltraModeSave:f,ultraLoadFailed:p,onUltraModeRetry:m,fallback:h,fallbackPollMs:g,fallbackBusy:_,availableModels:v,onFallbackChange:y,onFallbackPollMsChange:b,onFallbackSave:x}){let S=n(),C=(u.hintText??``).trim().length>0,w=a.some(e=>e.namespaced===t&&(e.provider!==`openai`||e.namespaced!==e.model)),T=u.enabled||u.multiAgentMode!==`v1`&&!(u.multiAgentMode===`v2`&&u.keepNativeChatGptOnV1),E=!p&&u.loaded===!0&&w&&T,D=new Set(v),O=new Set(h),[k,A]=(0,Z.useState)(()=>({pollMs:g,text:String(g)}));Object.is(k.pollMs,g)||A({pollMs:g,text:Number.isFinite(g)?String(g):``});let j=(0,Z.useRef)(null),[M,N]=(0,Z.useState)(!1),[P,F]=(0,Z.useState)(()=>({models:h,rows:h.map((e,t)=>({model:e,id:t})),nextId:h.length})),I=P.rows;if(P.models!==h){let e=[...P.rows],t=P.nextId;I=h.map(n=>{let r=e.findIndex(e=>e.model===n);return r>=0?e.splice(r,1)[0]:{model:n,id:t++}}),F({models:h,rows:I,nextId:t})}let L=(0,Z.useRef)(null);(0,Z.useLayoutEffect)(()=>{let e=L.current;if(!e)return;L.current=null;let t=j.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)`)??j.current?.querySelector(`button[role="combobox"]`))?.focus()},[h]);let R=Number.isInteger(g)&&g>=5e3&&g<=6e5,z=(e,t)=>{let n=[...h],r=e+t;if(_||r<0||r>=n.length)return;[n[e],n[r]]=[n[r],n[e]];let i=[...I];[i[e],i[r]]=[i[r],i[e]],F({...P,models:n,rows:i}),L.current={row:r,action:t===-1?`up`:`down`},y(n)};return(0,Q.jsxs)(`div`,{className:`swi-delegation`,children:[p&&(0,Q.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-copy`,children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:S(`sub.ultraMode`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:S(`sub.ultraModeLoadFail`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:m,children:S(`common.retry`)})]}),(0,Q.jsxs)(`div`,{className:`swi-delegation-row swi-delegation-model-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-copy`,children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:S(`sub.delegation.model`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:S(`sub.delegation.modelHint`)})]}),(0,Q.jsxs)(`div`,{className:`swi-delegation-controls`,children:[(0,Q.jsx)(dn,{value:t,options:[{value:``,label:S(`dash.injectionNone`)},...a.map(e=>({value:e.namespaced,label:we(`${e.provider}/${e.model}`,S)}))],onChange:e=>l({model:e||null,effort:r||null}),disabled:c,label:S(`dash.injectionLabel`),align:`right`}),t&&i.length>0&&(0,Q.jsx)(dn,{value:r,options:[{value:``,label:S(`dash.injectionEffortNone`)},...i.map(e=>({value:e,label:e}))],onChange:e=>l({model:t||null,effort:e||null}),disabled:c,label:S(`dash.injectionEffortLabel`),align:`right`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-expanded":M,onClick:()=>N(e=>!e),children:S(`sub.suggest.button`)})]})]}),M&&(0,Q.jsx)(`div`,{className:`swi-delegation-row`,children:(0,Q.jsx)(mw,{apiBase:e,model:t,effort:r,available:a,saving:c,onAccept:l})}),E&&(0,Q.jsx)(`div`,{className:`swi-delegation-row swi-v2-compatibility`,role:`note`,children:(0,Q.jsxs)(`div`,{className:`setting-copy`,children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:S(`sub.v2Compatibility.title`)}),(0,Q.jsx)(`p`,{className:`muted setting-hint`,children:S(`sub.v2Compatibility.risk`)}),(0,Q.jsx)(`p`,{className:`muted setting-hint`,children:S(`sub.v2Compatibility.recoveryUnknown`)}),(0,Q.jsx)(`a`,{href:`https://github.com/lidge-jun/opencodex/issues/92`,target:`_blank`,rel:`noreferrer`,children:S(`sub.v2Compatibility.details`)})]})}),(0,Q.jsxs)(`div`,{className:`swi-delegation-row swi-fallback-editor`,children:[(0,Q.jsxs)(`div`,{className:`setting-copy`,children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:S(`sub.fallbackLabel`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:S(`sub.fallbackHint`)})]}),(0,Q.jsxs)(`div`,{className:`swi-fallback-controls`,ref:j,children:[h.map((e,t)=>(0,Q.jsxs)(`div`,{className:`swi-fallback-row`,children:[(0,Q.jsxs)(`span`,{className:`swi-fallback-model`,children:[t+1,`. `,e,!D.has(e)&&(0,Q.jsx)(`span`,{className:`muted setting-hint`,children:S(`sub.fallbackUnavailable`)})]}),(0,Q.jsxs)(`span`,{className:`swi-fallback-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,"data-action":`up`,onClick:()=>z(t,-1),disabled:_||t===0,"aria-label":S(`sub.moveUp`,{m:e}),children:(0,Q.jsx)(Je,{})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,"data-action":`down`,onClick:()=>z(t,1),disabled:_||t===h.length-1,"aria-label":S(`sub.moveDown`,{m:e}),children:(0,Q.jsx)(tt,{})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,"data-action":`remove`,onClick:()=>{let e=h.filter((e,n)=>n!==t);F({...P,models:e,rows:I.filter((e,n)=>n!==t)}),L.current={row:Math.max(0,Math.min(t,h.length-2)),action:`remove`},y(e)},disabled:_,"aria-label":S(`sub.removeAria`,{m:e}),children:(0,Q.jsx)(xe,{})})]})]},I[t].id)),(0,Q.jsx)(dn,{value:``,label:S(`sub.fallbackAdd`),options:[{value:``,label:S(`sub.fallbackAdd`)},...v.filter(e=>!O.has(e)).map(e=>({value:e,label:e}))],onChange:e=>{e&&!O.has(e)&&y([...h,e])},disabled:_}),(0,Q.jsxs)(`label`,{className:`setting-hint`,children:[S(`sub.fallbackPoll`),(0,Q.jsx)(`input`,{className:`input`,type:`number`,min:5e3,max:6e5,step:1e3,value:k.text,onChange:e=>{let t=e.currentTarget.value,n=Number(t),r=t.trim()!==``&&Number.isFinite(n)?n:NaN;A({pollMs:r,text:t}),b(r)},disabled:_,"aria-invalid":!R}),` ms`]}),!R&&(0,Q.jsx)(`div`,{className:`setting-hint`,role:`alert`,children:S(`sub.fallbackPollInvalid`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:x,disabled:_||!R,children:S(`common.save`)})]})]}),(0,Q.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-copy`,children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:S(`dash.syncCodexSubagentDefaults`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:S(`dash.syncCodexSubagentDefaultsHint`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`switch ${s?`on`:``}`,onClick:()=>l({syncCodexSubagentDefaults:!s}),disabled:c||!t,"aria-label":S(`dash.syncCodexSubagentDefaults`),"aria-pressed":s,children:(0,Q.jsx)(`span`,{className:`knob`})})]}),(0,Q.jsxs)(`details`,{className:`swi-advanced`,children:[(0,Q.jsx)(`summary`,{className:`muted text-label`,children:S(`sub.advanced`)}),(0,Q.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-copy`,children:[(0,Q.jsxs)(`div`,{className:`font-semibold`,style:{display:`inline-flex`,alignItems:`center`,gap:6},children:[S(`models.v2Label`),(0,Q.jsxs)(pn,{content:S(`models.v2Help`),side:`top`,maxWidth:380,children:[(0,Q.jsx)(De,{width:13,height:13,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`sr-only`,children:S(`models.v2Label`)})]})]}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:(0,Q.jsx)(`a`,{className:`text-control`,href:`https://opencodex.me/guides/sub-agent-surface/`,target:`_blank`,rel:`noreferrer`,style:{color:`var(--accent)`},children:S(`models.v2DocsLink`)})})]}),(0,Q.jsx)(`div`,{className:`swi-delegation-controls`,children:(0,Q.jsx)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":S(`models.v2Label`),children:[`v1`,`default`,`v2`].map(e=>(0,Q.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":u.multiAgentMode===e,className:`btn btn-sm${u.multiAgentMode===e?` btn-primary`:` btn-ghost`}`,style:{background:u.multiAgentMode===e?void 0:`transparent`,color:u.multiAgentMode===e?void 0:`var(--muted)`},disabled:d||p,onClick:()=>{u.multiAgentMode!==e&&f({multiAgentMode:e})},children:S(`models.v2Mode_${e}`)},e))})})]}),(0,Q.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-copy`,children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:S(`dash.multiAgentGuidance`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:S(`dash.multiAgentGuidanceHint`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`switch ${o?`on`:``}`,onClick:()=>l({multiAgentGuidanceEnabled:!o}),disabled:c,"aria-label":S(`dash.multiAgentGuidance`),"aria-pressed":o,children:(0,Q.jsx)(`span`,{className:`knob`})})]}),(0,Q.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-copy`,children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:S(`sub.ultraMode`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:S(`sub.ultraModeHint`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`switch ${C?`on`:``}`,onClick:()=>{C?f({multiAgentModeHintText:null}):u.recommendation&&f({multiAgentModeHintText:u.recommendation.text})},disabled:c||d||!C&&(!u.multiAgentV2Enabled||!u.recommendation),"aria-label":S(`sub.ultraMode`),"aria-pressed":C,children:(0,Q.jsx)(`span`,{className:`knob`})}),!u.multiAgentV2Enabled&&(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:S(`sub.ultraModeV2Required`)})]}),C&&(0,Q.jsx)(`div`,{className:`swi-delegation-row swi-ultra-mode-editor`,children:(0,Q.jsx)(gw,{initialHint:u.hintText??``,disabled:c||d,onSave:f,preset:u.recommendation?.text??null,labels:{text:S(`sub.ultraModeText`),preset:S(`sub.ultraModePreset`),save:S(`common.save`)}},u.hintText)})]})]})}function gw({initialHint:e,disabled:t,onSave:n,preset:r,labels:i}){let[a,o]=(0,Z.useState)(e);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.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,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{r!==null&&o(r)},disabled:t||r===null,children:i.preset}),(0,Q.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 _w({available:e,fallbackAvailable:t,chosen:r,onToggle:i,onMove:a,fallback:o,fallbackPollMs:s,fallbackBusy:c,onFallbackChange:l,onFallbackPollMsChange:u,onFallbackSave:d,delegation:f}){let p=n(),[m,h]=(0,Z.useState)(``),g=(0,Z.useMemo)(()=>new Set(r),[r]),_=r.length>=5,v=(0,Z.useMemo)(()=>{let t=m.trim().toLowerCase();return e.filter(e=>!t||e.toLowerCase().includes(t))},[e,m]),y=(0,Z.useMemo)(()=>[{id:`featured`,label:p(`sub.featured`),meta:`${r.length}/5`},{id:`models`,label:p(`sub.models`),meta:String(v.length)},{id:`settings`,label:p(`sub.settings`)}],[p,r.length,v.length]);return(0,Q.jsxs)(`div`,{className:`subagents-workspace-shell`,children:[(0,Q.jsx)(uw,{scope:`subagents`,items:y,ariaLabel:p(`sub.sections`)}),(0,Q.jsxs)(`div`,{className:`subagents-workspace-root`,children:[(0,Q.jsxs)(`section`,{id:sw(`subagents`,`featured`),className:`subagents-workspace-section`,"aria-label":p(`sub.featured`),children:[(0,Q.jsxs)(`div`,{className:`swi-featured-head`,children:[(0,Q.jsx)(`h2`,{className:`swi-featured-title`,children:p(`sub.featured`)}),(0,Q.jsxs)(`span`,{className:`swi-featured-count`,children:[r.length,`/`,5]}),(0,Q.jsxs)(pn,{content:(0,Q.jsx)(O,{k:`sub.orderHint`,cmd:`spawn_agent`}),side:`bottom`,maxWidth:380,children:[(0,Q.jsx)(De,{width:14,height:14,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`sr-only`,children:p(`sub.orderHintAria`)})]})]}),r.length===0?(0,Q.jsx)(`div`,{className:`swi-featured-empty`,children:p(`sub.noneSelected`)}):(0,Q.jsx)(`div`,{className:`swi-featured-list`,children:r.map((e,t)=>(0,Q.jsxs)(`div`,{className:`swi-featured-row`,children:[(0,Q.jsx)(`span`,{className:`swi-featured-pos`,children:t+1}),(0,Q.jsx)(`span`,{className:`swi-featured-name`,children:zv(e)}),(0,Q.jsxs)(`span`,{className:`swi-featured-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,onClick:()=>a(t,-1),disabled:t===0,"aria-label":p(`sub.moveUp`,{m:e}),children:(0,Q.jsx)(Je,{})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,onClick:()=>a(t,1),disabled:t===r.length-1,"aria-label":p(`sub.moveDown`,{m:e}),children:(0,Q.jsx)(tt,{})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,onClick:()=>i(e),"aria-label":p(`sub.removeAria`,{m:e}),style:{color:`var(--red)`},children:(0,Q.jsx)(xe,{})})]})]},e))})]}),(0,Q.jsxs)(`section`,{id:sw(`subagents`,`models`),className:`subagents-workspace-section`,"aria-label":p(`sub.models`),children:[(0,Q.jsxs)(`div`,{className:`swi-featured-head`,children:[(0,Q.jsx)(`h2`,{className:`swi-featured-title`,children:p(`sub.models`)}),(0,Q.jsx)(`span`,{className:`swi-featured-count`,children:v.length})]}),(0,Q.jsxs)(`div`,{className:`swi-picker-box`,children:[(0,Q.jsx)(`div`,{className:`subagents-workspace-rail-search`,children:(0,Q.jsx)(`input`,{className:`input`,value:m,onChange:e=>h(e.target.value),placeholder:p(`sub.search`),"aria-label":p(`sub.search`)})}),(0,Q.jsx)(`div`,{className:`subagents-workspace-rail-list`,children:v.length===0?(0,Q.jsx)(`span`,{className:`subagents-workspace-rail-empty`,children:p(`sub.noModels`)}):v.map(e=>{let t=g.has(e),n=t?r.indexOf(e)+1:null,a=!t&&_;return(0,Q.jsxs)(`div`,{className:`subagents-workspace-rail-row${t?` subagents-workspace-rail-row--selected`:``}`,children:[(0,Q.jsxs)(`span`,{className:`subagents-workspace-rail-row-main`,children:[(0,Q.jsx)(`span`,{className:`swi-rail-priority`,children:n??``}),(0,Q.jsx)(Qe,{className:`swi-rail-icon`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`subagents-workspace-rail-name`,children:zv(e)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`subagents-workspace-rail-toggle${t?` subagents-workspace-rail-toggle--on`:``}${a?` subagents-workspace-rail-toggle--disabled`:``}`,onClick:()=>{a||i(e)},disabled:a,"aria-pressed":t,"aria-label":p(t?`sub.workspace.removeFromFeatured`:`sub.workspace.addToFeatured`,{m:e}),title:t?p(`sub.workspace.removeFromFeatured`,{m:e}):_?p(`sub.workspace.featuredFull`):p(`sub.workspace.addToFeatured`,{m:e}),children:t?(0,Q.jsx)(Oe,{style:{width:14,height:14}}):(0,Q.jsx)(I,{style:{width:14,height:14}})})]},e)})})]})]}),(0,Q.jsxs)(`section`,{id:sw(`subagents`,`settings`),className:`subagents-workspace-section`,"aria-label":p(`sub.settings`),children:[(0,Q.jsx)(`div`,{className:`swi-featured-head`,children:(0,Q.jsx)(`h2`,{className:`swi-featured-title`,children:p(`sub.settings`)})}),(0,Q.jsx)(hw,{apiBase:f.apiBase,model:f.model,effort:f.effort,efforts:f.efforts,available:f.available,guidanceEnabled:f.guidanceEnabled,syncCodexDefaults:f.syncCodexDefaults,saving:f.saving,onSave:f.onSave,ultraMode:f.ultraMode,ultraSaving:f.ultraSaving,onUltraModeSave:f.onUltraModeSave,ultraLoadFailed:f.ultraLoadFailed,onUltraModeRetry:f.onUltraModeRetry,fallback:o,fallbackPollMs:s,fallbackBusy:c,availableModels:t??e,onFallbackChange:l,onFallbackPollMsChange:u,onFallbackSave:d})]})]})]})}function vw(e){let[t,n]=(0,Z.useState)(!1),[r,i]=(0,Z.useState)(!1),[a,o]=(0,Z.useState)(``),[s,c]=(0,Z.useState)(``),[l,u]=(0,Z.useState)([]),[d,f]=(0,Z.useState)([]),[p,m]=(0,Z.useState)(!0),[h,g]=(0,Z.useState)(!1),_=(0,Z.useCallback)(e=>{let t=Po(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,Z.useEffect)(()=>{let t=!1;return(async()=>{try{let n=await jn(await fetch(`${e}/api/injection-model`));if(t)return;_(n)}catch{}finally{t||n(!0)}})(),()=>{t=!0}},[e,_]),{loaded:t,saving:r,model:a,effort:s,efforts:l,available:d,guidanceEnabled:p,syncCodexDefaults:h,save:(0,Z.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`);_(await jn(n))}catch{}finally{i(!1)}}},[e,_,r])}}var yw={enabled:!1,hintText:null,recommendation:null,multiAgentV2Enabled:!1,multiAgentMode:`default`};function bw(e){return io(e)}function xw({apiBase:e}){let t=n(),r=`ocx.subagents.v1:${e}`,i=bw(r),[a,o]=(0,Z.useState)(()=>i?.chosen??[]),[s,c]=(0,Z.useState)(()=>i?.fallback??[]),[l,u]=(0,Z.useState)(()=>i?.pollMs??6e4),[d,f]=(0,Z.useState)(!1),[p,m]=(0,Z.useState)(()=>Array.isArray(i?.fallback)&&Number.isInteger(i?.pollMs)),[h,g]=(0,Z.useState)(()=>i?.fallbackAvailable),[_,v]=(0,Z.useState)(``),[y,b]=(0,Z.useState)(!0),x=(0,Z.useRef)(null),S=(0,Z.useRef)({fallback:i?.fallback,pollMs:i?.pollMs,fallbackAvailable:i?.fallbackAvailable}),C=(0,Z.useRef)(0),w=(0,Z.useRef)(0),T=(0,Z.useRef)(!1),E=(0,Z.useRef)(i),[D,O]=(0,Z.useState)(``),[k,A]=(0,Z.useState)(!1),j=(0,Z.useRef)(!1),M=(0,Z.useRef)(null),N=(0,Z.useRef)(a),P=(0,Z.useCallback)(e=>{N.current=e,o(e)},[]),F=vw(e),[I,L]=(0,Z.useState)(null),R=I?.apiBase===e,z=R?I.mode:yw,[B,V]=(0,Z.useState)(!1),[H,U]=(0,Z.useState)(null),[ee,W]=(0,Z.useState)(!1),te=(0,Z.useRef)(0),G=(0,Z.useRef)(e);(0,Z.useEffect)(()=>{G.current=e,te.current++},[e]);let ne=(0,Z.useCallback)(async n=>{if(G.current!==e)return!1;let r=++te.current,i=await vn(await fetch(`${e}/api/v2`,{signal:n}),t(`sub.ultraModeLoadFail`));if(!i||n?.aborted||r!==te.current||G.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 L({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,Z.useEffect)(()=>{let e=new AbortController;return(async()=>{await ne(e.signal)})().catch(()=>{e.signal.aborted||(A(!1),W(!0),O(t(`sub.ultraModeLoadFail`)))}),()=>{e.abort()}},[ne,t]);let K=async n=>{if(B||!R||G.current!==e)return;let r=e;V(!0),O(``);try{if(await vn(await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)}),t(`sub.ultraModeSaveFail`)),G.current!==r||!await ne())return;A(!0),O(t(`sub.ultraModeSaved`))}catch(e){if(G.current!==r)return;A(!1),O(e instanceof Error&&e.message?e.message:t(`sub.networkError`))}finally{V(!1)}},re=(0,Z.useCallback)(async()=>{try{if(!await ne())return;A(!1),O(e=>e===t(`sub.ultraModeLoadFail`)?``:e)}catch{A(!1),W(!0),O(t(`sub.ultraModeLoadFail`))}},[ne,t]),q=(0,Z.useCallback)(async()=>{x.current?.abort();let n=new AbortController;x.current=n;let{signal:i}=n,a=C.current;try{let n=await vn(await fetch(`${e}/api/subagent-model-fallback`,{signal:i}));if(!n||!Array.isArray(n.models)||!n.models.every(e=>typeof e==`string`&&e.trim())||typeof n.pollMs!=`number`||!Number.isInteger(n.pollMs)||n.pollMs<5e3||n.pollMs>6e5||!Array.isArray(n.available)||!n.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:n.models,pollMs:n.pollMs,fallbackAvailable:n.available};S.current=o,c(o.fallback),u(o.pollMs),g(o.fallbackAvailable),m(!0),v(``),E.current&&(E.current={...E.current,...o},co(r,E.current))}catch(e){if(i.aborted||a!==C.current||T.current)return;m(!1),v(e instanceof Error&&!(e instanceof SyntaxError)?e.message:t(`sub.loadFail`))}finally{i.aborted||b(!1)}},[e,r,t]);(0,Z.useEffect)(()=>((async()=>{await q()})(),()=>{x.current?.abort()}),[q]);let J=(0,Z.useCallback)(async n=>{let i=w.current,a=await vn(await fetch(`${e}/api/subagent-models`,{signal:n}),t(`sub.loadFail`));if(!a)throw Error(t(`sub.loadFail`));let o=a.available??[],s=new Set(o),c=i===w.current&&!j.current,l={...S.current,available:o,chosen:c?(a.chosen??[]).filter(e=>s.has(e)):E.current?.chosen??[]};if(n?.aborted)throw n.reason;return E.current=l,c&&P(l.chosen),co(r,l),l},[e,r,P,t]),Y=uo(r,[e],J,{isEmpty:()=>!1,initialData:i??void 0}),{state:ie}=Y,X=Y.refresh,ae=ie.data??i,oe=ae?.available??[],se=async n=>{if(M.current=n,j.current)return;j.current=!0,O(``);let i=null,a=n;for(;M.current;){let n=M.current;M.current=null;try{a=(await vn(await fetch(`${e}/api/subagent-models`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({models:n})}),t(`sub.saveFailed`)))?.applied??n,E.current={...E.current,available:oe,chosen:a},co(r,E.current),i=null}catch(e){i=e}}w.current+=1,j.current=!1,i?(P(E.current?.chosen??[]),A(!1),O(i instanceof Error&&i.message?i.message:t(`sub.networkError`))):(P(a),A(!0),O(t(`sub.saved`,{n:a.length,cmd:`ocx sync`})))},ce=e=>{w.current+=1,P(e),se(e)},le=e=>{let t=N.current;!t.includes(e)&&t.length>=5||ce(t.includes(e)?t.filter(t=>t!==e):[...t,e])},ue=(e,t)=>{let n=e+t,r=[...N.current];n<0||n>=r.length||([r[e],r[n]]=[r[n],r[e]],ce(r))},de=async()=>{if(!p||T.current||!Number.isInteger(l)||l<5e3||l>6e5)return;T.current=!0,C.current+=1;let n=e;f(!0),O(``);try{let i=await vn(await fetch(`${e}/api/subagent-model-fallback`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({models:s,pollMs:l})}),t(`sub.fallbackSaveFailed`));if(G.current!==n)return;if(!i||!Array.isArray(i.models)||typeof i.pollMs!=`number`)throw Error(t(`sub.fallbackSaveFailed`));C.current+=1,c(i.models),u(i.pollMs),S.current={...S.current,fallback:i.models,pollMs:i.pollMs};let a={available:oe,chosen:E.current?.chosen??[],...S.current};E.current=a,co(r,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,f(!1)}};if(ie.showSkeleton&&!ae)return(0,Q.jsx)(lb,{label:t(`sub.loading`),rows:4});if(ie.kind===`failed-cold`){let e=ie.error instanceof Error?ie.error.message:t(`sub.loadFail`);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)($,{tone:`err`,children:e}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>X(),children:t(`common.retry`)})]})}return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`page-head`,children:(0,Q.jsx)(`h2`,{children:t(`nav.subagents`)})}),D&&(0,Q.jsx)($,{tone:k?`ok`:`err`,children:D}),ie.showError&&(0,Q.jsx)($,{tone:`err`,children:t(`sub.loadFail`)}),_&&(0,Q.jsxs)($,{tone:`err`,children:[t(`sub.fallbackLabel`),`: `,t(`sub.loadFail`),_!==t(`sub.loadFail`)&&(0,Q.jsxs)(Q.Fragment,{children:[` `,_]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:y,onClick:()=>{b(!0),q()},children:t(`common.retry`)})]}),(0,Q.jsx)(aw,{apiBase:e,roster:a},e),(0,Q.jsx)(_w,{available:oe,fallbackAvailable:h??[],chosen:a,onToggle:le,onMove:ue,fallback:s,fallbackPollMs:l,fallbackBusy:d||!p,onFallbackChange:e=>{C.current+=1,c(e)},onFallbackPollMsChange:e=>{C.current+=1,u(e)},onFallbackSave:()=>{de()},delegation:{apiBase:e,model:F.model,effort:F.effort,efforts:F.efforts,available:F.available,guidanceEnabled:F.guidanceEnabled,syncCodexDefaults:F.syncCodexDefaults,saving:F.saving,onSave:e=>{F.save(e)},ultraMode:z,ultraSaving:B||!R,onUltraModeSave:t=>{t.multiAgentMode==="default"||t.multiAgentMode===`v2`?U({mode:t.multiAgentMode,apiBase:e}):K(t)},ultraLoadFailed:ee,onUltraModeRetry:()=>{re()}}}),H&&H.apiBase===e&&(0,Q.jsx)(pr,{reason:`selection`,mode:H.mode,docsUrl:`https://opencodex.me/guides/subagent-v1-default/`,busy:B,onContinue:()=>{let e=H.mode;U(null),K({multiAgentMode:e,multiAgentSurfaceAdvisoryAcknowledged:!0})},onChooseV1:()=>{U(null),z.multiAgentMode!==`v1`&&K({multiAgentMode:`v1`,multiAgentSurfaceAdvisoryAcknowledged:!0})},onDismiss:()=>U(null)})]})}function Sw(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 Cw(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}return o.updateDeps=e=>{r=e},o}function ww(e,t){if(e===void 0)throw Error(`Unexpected undefined${t?`: ${t}`:``}`);return e}var Tw=(e,t)=>Math.abs(e-t)<1.01,Ew=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}},Dw,Ow=()=>{if(Dw!==void 0)return Dw;if(typeof navigator>`u`)return Dw=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return Dw=!0;let e=navigator.maxTouchPoints;return Dw=navigator.platform===`MacIntel`&&e!==void 0&&e>0},kw=e=>{let{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},Aw=e=>e,jw=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},Mw=(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(kw(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(kw(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(r):r()});return a.observe(n,{box:`border-box`}),()=>{a.unobserve(n)}},Nw={passive:!0},Pw=typeof window>`u`||`onscrollend`in window,Fw=(e,t,n)=>{let r=e.scrollElement;if(!r)return;let i=e.targetWindow;if(!i)return;let a=e.options.useScrollendEvent&&Pw,o=0,s=a?null:Ew(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,Nw),a&&r.addEventListener(`scrollend`,u,Nw),()=>{r.removeEventListener(`scroll`,l),a&&r.removeEventListener(`scrollend`,u)}},Iw=(e,t)=>Fw(e,t,t=>{let{horizontal:n,isRtl:r}=e.options;return n?t.scrollLeft*(r&&-1||1):t.scrollTop}),Lw=(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`]},Rw=(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})},zw=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.shouldMeasureDuringScroll(n)&&this.resizeItem(n,this.options.measureElement(t,e,this));else{this.observer.unobserve(t);for(let[e,n]of this.elementsCache)if(n===t){this.elementsCache.delete(e);break}}};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:Aw,rangeExtractor:jw,onChange:()=>{},measureElement:Lw,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=Cw(()=>(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,Ow()&&this.targetWindow!=null&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};e.addEventListener(`touchstart`,t,Nw),e.addEventListener(`touchend`,n,Nw),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&&(Ow()&&(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=Cw(()=>[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=Cw(()=>[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=Sw(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=Cw(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(e,t,n,r)=>e.length===0||t===0?(this.range=null,null):(this.range=Hw(e,t,n,r,r===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=Cw(()=>{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=Cw(()=>[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 ww(t[Bw(0,t.length-1,r?e=>n[e*2]:e=>ww(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`}={})=>{this.options.count>0?this.scrollToIndex(this.options.count-1,{align:`end`,behavior:e}):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:Ow()&&(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(){this.targetWindow?this.rafId??=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}):this.scrollState=null}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&&Tw(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()}},Bw=(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 Vw(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 Hw(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=Vw(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=Bw(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 Uw=typeof document<`u`?Z.useLayoutEffect:Z.useEffect;function Ww({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n=`transform`,...r}){let i=Z.useReducer(e=>e+1,0)[1],a=Z.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,Zt.flushSync)(i):i()),(o=r.onChange)==null||o.call(r,t,n)}},[l]=Z.useState(()=>{let e=new zw(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),Uw(()=>l._didMount(),[]),Uw(()=>(o(l),l._willUpdate())),Uw(()=>{s(l)}),l}function Gw(e){return Ww({observeElementRect:Mw,observeElementOffset:Iw,scrollToFn:Rw,...e})}var Kw=32;function qw(e){return[...new Uint8Array(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}function Jw(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<=31||n===127)return!0}return!1}var Yw=`codex://threads/`,Xw=512;function Zw(e){let t=e.trim();if(t.length>Xw||t.length<=16||!t.toLowerCase().startsWith(Yw))return t;let n=t.slice(16),r=n.search(/[?#]/),i=(r===-1?n:n.slice(0,r)).replace(/\/+$/,``);return i!==``&&!/[/\s]/.test(i)?i:t}function Qw(e){let t=e.trim(),n=Zw(t);return n===t?[n]:[n,t]}async function $w(e){let t=Qw(e).filter(e=>e!==``&&!Jw(e)&&e.length<=4096);return(await Promise.all(t.map(e=>crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e))))).map(e=>qw(e).slice(0,Kw))}function eT(e,t,n){if(!e)return!1;let r=Qw(t);return r.some(Boolean)?r.includes(e)?!0:n!==void 0&&n.includes(e):!1}var tT={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.`},vi:{label:`Yêu cầu không hợp lệ`,description:`Proxy không thể hiểu yêu cầu. Hãy kiểm tra model, cấu trúc tin nhắn, header và nội dung JSON trước khi thử lại.`},pt:{label:`Requisição inválida`,description:`O proxy não conseguiu entender a requisição. Verifique o modelo, a estrutura das mensagens, os cabeçalhos e o corpo JSON antes de tentar novamente.`}},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.`},vi:{label:`Chưa xác thực`,description:`Thông tin xác thực bị thiếu, đã hết hạn hoặc không hợp lệ. Hãy đăng nhập lại hoặc làm mới thông tin xác thực của tài khoản hay nhà cung cấp mà opencodex sử dụng.`},pt:{label:`Não autorizado`,description:`As credenciais estão ausentes, expiradas ou inválidas. Faça login novamente ou atualize as credenciais da conta/provedor usadas pelo opencodex.`}},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.`},vi:{label:`Yêu cầu thanh toán`,description:`Nhà cung cấp upstream đã từ chối yêu cầu vì không có quyền truy cập thanh toán, tín dụng hoặc gói dịch vụ. Hãy thêm tín dụng, cập nhật thanh toán hoặc đổi nhà cung cấp.`},pt:{label:`Pagamento necessário`,description:`O provedor upstream rejeitou a requisição porque faturamento, créditos ou acesso ao plano não estão disponíveis. Adicione créditos, atualize o faturamento ou troque de provedor.`}},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.`},vi:{label:`Bị cấm`,description:`Tài khoản đã được xác thực nhưng không được phép dùng model hoặc thao tác này. Nguyên nhân thường là giới hạn gói hoặc thuê bao (ví dụ Ollama Cloud Pro), chính sách tổ chức hay quyền model — không nhất thiết do API key sai.`},pt:{label:`Acesso negado`,description:`A conta está autenticada, mas não tem permissão para usar este modelo ou esta operação. Costuma ser limite de plano/assinatura (ex.: Ollama Cloud Pro), política da organização ou permissão do modelo — não necessariamente uma API key inválida.`}},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.`},vi:{label:`Không tìm thấy`,description:`Không tìm thấy endpoint, model hoặc tài nguyên được yêu cầu. Hãy kiểm tra base URL, tên model và đường dẫn yêu cầu.`},pt:{label:`Não encontrado`,description:`A rota, o modelo, a conta ou o recurso upstream solicitado não foi encontrado. Verifique o nome do modelo e a configuração do provedor no opencodex.`}},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.`},vi:{label:`Yêu cầu hết thời gian chờ`,description:`Yêu cầu không hoàn tất trước thời hạn. Hãy thử lại với yêu cầu nhỏ hơn hoặc kiểm tra kết nối mạng.`},pt:{label:`Tempo limite da requisição`,description:`A requisição demorou demais para o proxy ou o provedor upstream concluí-la. Tente novamente com uma requisição menor ou outro provedor.`}},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.`},vi:{label:`Xung đột`,description:`Yêu cầu xung đột với trạng thái hiện tại của tài nguyên hoặc tài khoản. Hãy làm mới trạng thái rồi thử lại.`},pt:{label:`Conflito`,description:`A requisição conflita com o estado atual da conta, da sessão ou do provedor. Atualize a sessão ou tente novamente quando a operação ativa terminar.`}},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.`},vi:{label:`Nội dung quá lớn`,description:`Nội dung yêu cầu vượt quá giới hạn của proxy hoặc nhà cung cấp. Hãy giảm kích thước tin nhắn, tệp hoặc ngữ cảnh rồi thử lại.`},pt:{label:`Requisição grande demais`,description:`O prompt, os anexos ou o conteúdo gerado excedem um limite do proxy ou do upstream. Reduza tokens, tamanho de arquivos ou histórico da conversa.`}},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.`},vi:{label:`Yêu cầu không thể xử lý`,description:`Yêu cầu có cú pháp hợp lệ nhưng chứa giá trị hoặc tổ hợp tùy chọn mà model hay nhà cung cấp không hỗ trợ.`},pt:{label:`Conteúdo inválido`,description:`O provedor aceitou o formato da requisição, mas rejeitou o conteúdo. Verifique as opções do modelo, as definições de ferramentas, os papéis das mensagens e campos não suportados.`}},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.`},vi:{label:`Phụ thuộc thất bại`,description:`Không thể hoàn tất yêu cầu vì một dịch vụ phụ thuộc hoặc thao tác upstream đã thất bại. Hãy kiểm tra lỗi liên quan rồi thử lại.`},pt:{label:`Falha em dependência do provedor`,description:`Uma dependência upstream necessária falhou enquanto o opencodex roteava a requisição. Tente novamente mais tarde ou troque para outro provedor configurado.`}},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.`},vi:{label:`Quá nhiều yêu cầu`,description:`Tài khoản hoặc nhà cung cấp đã đạt giới hạn tốc độ hay hạn ngạch. Hãy chờ thời gian Retry-After, đổi tài khoản hoặc đổi nhà cung cấp.`},pt:{label:`Limite de requisições excedido`,description:`O limite de taxa ou de cota do provedor upstream foi atingido. Aguarde a janela de cota reiniciar ou troque de conta/provedor.`}},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.`},vi:{label:`Máy khách đã đóng yêu cầu`,description:`Máy khách đã ngắt kết nối hoặc hủy yêu cầu trước khi opencodex định tuyến xong. Nếu không chủ ý hủy, hãy thử lại.`},pt:{label:`Requisição encerrada pelo cliente`,description:`O cliente desconectou ou cancelou a requisição antes de o opencodex terminar de rotear. Tente novamente se o cancelamento foi acidental.`}},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.`},vi:{label:`Lỗi proxy`,description:`opencodex gặp lỗi nội bộ khi xử lý yêu cầu. Hãy thử lại một lần, rồi kiểm tra log proxy nếu lỗi lặp lại.`},pt:{label:`Erro do proxy`,description:`O opencodex encontrou um erro interno ao tratar a requisição. Tente novamente uma vez; se repetir, verifique os logs do proxy.`}},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.`},vi:{label:`Phản hồi upstream không hợp lệ`,description:`Nhà cung cấp upstream trả về phản hồi không hợp lệ hoặc thất bại qua proxy. Hãy thử lại hoặc định tuyến yêu cầu sang nhà cung cấp khác.`},pt:{label:`Resposta upstream inválida`,description:`O provedor upstream retornou uma resposta inválida ou com falha através do proxy. Tente novamente ou roteie a requisição para outro provedor.`}},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.`},vi:{label:`Nhà cung cấp không khả dụng`,description:`Proxy hoặc nhà cung cấp upstream tạm thời không khả dụng hay đang quá tải. Hãy chờ một lát rồi thử lại hoặc đổi nhà cung cấp.`},pt:{label:`Provedor indisponível`,description:`O proxy ou o provedor upstream está temporariamente indisponível ou sobrecarregado. Aguarde um instante e tente novamente, ou troque de provedor.`}},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.`},vi:{label:`Upstream hết thời gian chờ`,description:`Nhà cung cấp upstream không phản hồi trước thời hạn của proxy. Hãy thử lại với yêu cầu nhỏ hơn hoặc chọn nhà cung cấp nhanh hơn.`},pt:{label:`Tempo limite do upstream`,description:`O provedor upstream não respondeu antes do tempo limite do proxy. Tente novamente com uma requisição menor ou escolha um provedor mais rápido.`}},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.`},vi:{label:`Nhà cung cấp quá tải`,description:`Nhà cung cấp upstream đang quá tải hoặc bị giới hạn công suất. Hãy chờ rồi thử lại, hoặc đổi sang tài khoản hay nhà cung cấp khác.`},pt:{label:`Provedor sobrecarregado`,description:`O provedor upstream está sobrecarregado ou com capacidade limitada. Aguarde e tente novamente, ou troque para outra conta/provedor.`}}},nT={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.`},vi:{label:`Lỗi yêu cầu`,description:`Proxy hoặc nhà cung cấp upstream đã từ chối yêu cầu. Hãy kiểm tra cấu trúc yêu cầu, thông tin xác thực, tên model và cấu hình nhà cung cấp.`},pt:{label:`Erro na requisição`,description:`O proxy ou o provedor upstream rejeitou a requisição. Verifique a estrutura da requisição, as credenciais, o nome do modelo e a configuração do provedor.`}},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.`},vi:{label:`Lỗi máy chủ hoặc upstream`,description:`opencodex hoặc một nhà cung cấp upstream đã thất bại khi xử lý yêu cầu. Hãy thử lại sau hoặc định tuyến yêu cầu sang nhà cung cấp khác.`},pt:{label:`Erro do servidor ou do upstream`,description:`O opencodex ou um provedor upstream falhou ao processar a requisição. Tente novamente mais tarde ou roteie a requisição para outro provedor.`}}};function rT(e){return e.toLowerCase().startsWith(`fr`)?`fr`:e.toLowerCase().startsWith(`vi`)?`vi`:e.toLowerCase().startsWith(`pt`)?`pt`:e===`de`||e===`ko`||e===`zh`||e===`zh-TW`||e===`ru`||e===`ja`||e===`tr`?e:`en`}function iT(e,t){if(e<400)return null;let n=rT(t);return(tT[Math.trunc(e)]??(e<500?nT.client:nT.server))[n]}var aT=[`provider`,`usage`,`injection`];function oT(e){return e>0?`[${new Date(e).toLocaleTimeString()}] `:``}function sT(e){return new Date(e).toLocaleTimeString()}function cT(e,t){return t===`provider`?!!e?.enabled:t===`usage`?!!e?.usage:!!e?.injection}function lT(e,t){return t===`debug`?e.enabled:t===`usage`?e.usage:t===`injection`?e.injection:e.claude}function uT({entries:e}){let{t}=r();return(0,Q.jsxs)(`div`,{className:`card`,style:{marginBottom:16,padding:`12px 14px`},children:[(0,Q.jsx)(`div`,{className:`font-semibold`,style:{marginBottom:4},children:t(`debug.claudeInbound.title`)}),(0,Q.jsx)(`div`,{className:`muted text-control`,style:{marginBottom:10},children:t(`debug.claudeInbound.sub`)}),e.length===0?(0,Q.jsx)(`div`,{className:`muted text-control`,children:t(`debug.claudeInbound.empty`)}):(0,Q.jsx)(`div`,{style:{overflowX:`auto`},children:(0,Q.jsxs)(`table`,{className:`table text-label`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:t(`debug.claudeInbound.time`)}),(0,Q.jsx)(`th`,{children:t(`debug.claudeInbound.endpoint`)}),(0,Q.jsx)(`th`,{children:t(`debug.claudeInbound.model`)}),(0,Q.jsx)(`th`,{children:`thinking`}),(0,Q.jsx)(`th`,{children:`effort`}),(0,Q.jsx)(`th`,{children:`beta`}),(0,Q.jsx)(`th`,{children:`metadata`}),(0,Q.jsx)(`th`,{children:`system`})]})}),(0,Q.jsx)(`tbody`,{children:e.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`muted mono`,children:sT(e.at)}),(0,Q.jsx)(`td`,{className:`mono`,children:e.endpoint}),(0,Q.jsxs)(`td`,{className:`mono`,title:e.resolvedModel,children:[e.model,e.resolvedModel&&e.resolvedModel!==e.model&&(0,Q.jsxs)(`span`,{className:`muted`,children:[` → `,e.resolvedModel]})]}),(0,Q.jsxs)(`td`,{className:`mono`,children:[e.thinkingType??`-`,e.thinkingBudgetTokens!==void 0&&(0,Q.jsxs)(`span`,{className:`muted`,children:[` (`,e.thinkingBudgetTokens,`)`]})]}),(0,Q.jsx)(`td`,{className:`mono`,children:e.outputConfigEffort??`-`}),(0,Q.jsx)(`td`,{className:`mono`,title:e.anthropicBeta,style:{maxWidth:160,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:e.anthropicBeta??`-`}),(0,Q.jsx)(`td`,{className:`mono`,title:e.metadataKeys?.join(`, `),children:e.hasMetadataUserId?`user_id ${e.userIdTag??``}`:t(`debug.claudeInbound.none`)}),(0,Q.jsx)(`td`,{className:`mono`,children:e.hasSystem?e.systemTag??`yes`:t(`debug.claudeInbound.none`)})]},e.id))})]})})]})}function dT({debug:e,stream:t,streamEnabled:n,entries:i,scrollContainerRef:a,lineVirtualizer:o}){let{t:s}=r();return e?n?i.length===0?(0,Q.jsxs)(`div`,{className:`empty`,children:[(0,Q.jsx)(`div`,{className:`font-semibold`,style:{marginBottom:6},children:s(`debug.noLinesTitle`)}),(0,Q.jsx)(`div`,{className:`muted text-control`,style:{maxWidth:560,marginInline:`auto`},children:s(`debug.noLines.${t}`)})]}):(0,Q.jsx)(`div`,{ref:a,className:`log-detail-json`,style:{maxHeight:`calc(100vh - 280px)`,overflow:`auto`},children:(0,Q.jsx)(`div`,{style:{position:`relative`,height:o.getTotalSize(),width:`100%`},children:o.getVirtualItems().map(e=>(0,Q.jsx)(`div`,{ref:o.measureElement,"data-index":e.index,style:{position:`absolute`,top:0,left:0,width:`100%`,transform:`translateY(${e.start}px)`},children:`${oT(i[e.index].at)}${i[e.index].line}`},e.key))})}):(0,Q.jsxs)(`div`,{className:`empty`,children:[(0,Q.jsx)(`div`,{className:`font-semibold`,style:{marginBottom:6},children:s(`debug.emptyTitle`)}),(0,Q.jsx)(`div`,{className:`muted text-control`,style:{maxWidth:560,marginInline:`auto`},children:s(`debug.empty`)})]}):null}function fT({debug:e,debugBusy:t,stream:n,onSetFlag:i,onReset:a,onStreamChange:o}){let{t:s}=r();return(0,Q.jsxs)(`div`,{className:`card`,style:{marginBottom:16,padding:`12px 14px`},children:[(0,Q.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:12,flexWrap:`wrap`},children:[(0,Q.jsx)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:16},children:[`debug`,`usage`,`injection`,`claude`].map(n=>{let r=lT(e,n);return(0,Q.jsxs)(`div`,{style:{display:`inline-flex`,alignItems:`center`,gap:10,minWidth:220},children:[(0,Q.jsx)(ln,{on:r,disabled:t,label:s(`debug.${n}`),onClick:()=>i(n,!r)}),(0,Q.jsx)(`span`,{className:`text-control`,children:s(`debug.${n}`)})]},n)})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:t,onClick:a,children:s(`debug.reset`)})]}),(e.enabled||e.usage||e.injection)&&(0,Q.jsxs)(`div`,{style:{display:`inline-flex`,gap:6,marginTop:12},children:[e.enabled&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm${n===`provider`?` btn-primary`:` btn-ghost`}`,onClick:()=>o(`provider`),children:s(`debug.streamProvider`)}),e.usage&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm${n===`usage`?` btn-primary`:` btn-ghost`}`,onClick:()=>o(`usage`),children:s(`debug.streamUsage`)}),e.injection&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm${n===`injection`?` btn-primary`:` btn-ghost`}`,onClick:()=>o(`injection`),children:s(`debug.streamInjection`)})]})]})}function pT({embedded:e,refreshing:t,streamEnabled:n,follow:i,onRefresh:a,onFollowChange:o}){let{t:s}=r();return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:e?`row`:`page-head`,style:e?{justifyContent:`flex-end`,marginBottom:4}:void 0,children:[!e&&(0,Q.jsx)(`h2`,{children:s(`debug.title`)}),(0,Q.jsxs)(`div`,{style:{display:`inline-flex`,alignItems:`center`,gap:12},children:[(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:t||!n,onClick:a,children:[(0,Q.jsx)(ae,{}),` `,s(`debug.refresh`)]}),(0,Q.jsxs)(`label`,{className:`muted text-control`,style:{cursor:`pointer`,display:`inline-flex`,alignItems:`center`,gap:6},children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:i,onChange:e=>o(e.target.checked)}),s(`debug.follow`)]})]})]}),(0,Q.jsx)(`p`,{className:`page-sub`,children:s(`debug.subtitle`)})]})}function mT(e){return`debug-settings:${e}`}function hT({apiBase:e,embedded:t,active:n=!0}){let{t:i}=r(),a=`ocx.debug.settings.v1:${e}`,o=io(a),s=mT(e),[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(`provider`),[f,p]=(0,Z.useState)([]),[m,h]=(0,Z.useState)(!0),[g,_]=(0,Z.useState)(!1),v=(0,Z.useRef)(0),y=(0,Z.useRef)(0),b=(0,Z.useRef)(0),x=(0,Z.useRef)(null),S=(0,Z.useRef)(null),C=(0,Z.useRef)(null),w=uo(s,[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 co(a,r),r},{pollMs:2e3,enabled:n,isEmpty:()=>!1,initialData:o??void 0}),T=w.state,E=w.data??o??null,D=Wt(`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=Gw({count:f.length,getScrollElement:()=>S.current,estimateSize:()=>20,overscan:30,getItemKey:e=>f[e].seq}),k=(0,Z.useCallback)(e=>cT(E,e),[E]);(0,Z.useEffect)(()=>{if(!E||k(u))return;let e=aT.find(k);if(!e)return;let t=window.setTimeout(()=>d(e),0);return()=>window.clearTimeout(t)},[E,u,k]);let A=k(u),j=u===`provider`?`${e}/api/debug/logs`:u===`usage`?`${e}/api/debug/usage-logs`:`${e}/api/debug/injection-logs`,N=(0,Z.useCallback)(async(e,t)=>{let n=++b.current;if(!A)n===b.current&&(p([]),v.current=0);else{_(!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;p(t=>(e?a:[...t,...a]).slice(-2e3)),v.current=a[a.length-1].seq}catch{}finally{n===b.current&&_(!1)}}},[j,A]);(0,Z.useEffect)(()=>{if(!n)return;let t=`${e}:${u}:${A}`,r=C.current!==t;if(C.current=t,!r&&f.length>0)return;v.current=0;let i=new AbortController,a=window.setTimeout(()=>{r&&p([]),N(!0,i.signal)},0);return()=>{window.clearTimeout(a),b.current+=1,i.abort()}},[n,e,u,A]);let P=(0,Z.useRef)(!1),F=(0,Z.useEffectEvent)(()=>{if(P.current)return;P.current=!0;let e=M(1e4);N(!1,e.signal).finally(()=>{e.clear(),P.current=!1})});(0,Z.useEffect)(()=>{if(n&&m&&A)return ba(()=>F(),1e3)},[n,m,A]),(0,Z.useEffect)(()=>{m&&f.length>0&&O.scrollToIndex(f.length-1,{align:`end`})},[f,m,O]);let I=async t=>{let n=++y.current;l(!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 i=await r.json();if(n!==y.current)return;co(a,i),Kt(s,i)}catch{}},i=(x.current??Promise.resolve()).then(r,r);x.current=i.then(()=>void 0,()=>void 0);try{await i}finally{n===y.current&&l(!1)}},L=async(e,t)=>{await I({[e]:t})},R=async()=>{await I({reset:!0})};return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(pT,{embedded:t,refreshing:g,streamEnabled:A,follow:m,onRefresh:()=>void N(!0),onFollowChange:h}),!E&&T.showError?(0,Q.jsxs)(`div`,{className:`notice notice-err`,role:`alert`,children:[(0,Q.jsx)(`span`,{children:i(`debug.loadFailed`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>w.refresh(),children:i(`common.retry`)})]}):T.showSkeleton&&!E?(0,Q.jsx)(lb,{label:i(`debug.loading`),rows:3}):E?(0,Q.jsx)(fT,{debug:E,debugBusy:c,stream:u,onSetFlag:(e,t)=>{L(e,t)},onReset:()=>{R()},onStreamChange:d}):null,E&&T.showError&&(0,Q.jsx)($,{tone:`err`,children:i(`debug.loadFailed`)}),E?.claude&&(0,Q.jsx)(uT,{entries:D}),(0,Q.jsx)(dT,{debug:!!E,stream:u,streamEnabled:A,entries:f,scrollContainerRef:S,lineVirtualizer:O})]})}function gT(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 _T=[`all`,`native`,`translated`,`legacy-bridge`,`blocked`,`none`],vT={surface:`all`,model:``,provider:``,status:`all`,timeWindow:`all`,interceptedOnly:!1,conversationId:``};function yT(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()!==``||(e.protocolMode??`all`)!==`all`}function bT(e){return Array.isArray(e.attempts)?e.attempts.filter(e=>typeof e==`object`&&!!e):[]}function xT(e){if(typeof e!=`string`)return;let t=e.trim();return t?t.toLowerCase():void 0}function ST(e,t){if(e===`15m`)return t-9e5;if(e===`1h`)return t-36e5;if(e===`24h`)return t-864e5}function CT(e,t,n=Date.now()){let r=t.model.trim().toLowerCase(),i=t.provider.trim().toLowerCase(),a=t.conversationId.trim(),o=ST(t.timeWindow,n),s=t.protocolMode??`all`;return e.filter(e=>{if(!gT(e,t.surface)||t.interceptedOnly&&typeof e.shadowCallRewrittenFrom!=`string`)return!1;if(s!==`all`){let t=lh(e.protocolTrace)?.mode;if(s===`none`?t!==void 0:t!==s)return!1}if(a&&!eT(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=bT(e);if(r&&![xT(e.model),xT(e.resolvedModel),xT(e.servedModel),...n.map(e=>xT(e.model))].some(e=>e===r)||i&&![xT(e.provider),...n.map(e=>xT(e.provider))].some(e=>e===i)||o!==void 0&&(typeof e.timestamp!=`number`||!Number.isFinite(e.timestamp)||e.timestamp<o))return!1;let c=e.displayMetrics?.tokPerSecond?.kind===`value`&&Number.isFinite(e.displayMetrics.tokPerSecond.value)?e.displayMetrics.tokPerSecond.value:void 0;return!(t.minTokPerSec!==void 0&&(c===void 0||c<t.minTokPerSec)||t.maxTokPerSec!==void 0&&(c===void 0||c>=t.maxTokPerSec))})}function wT(e,t){if(typeof t!=`string`)return;let n=t.trim(),r=xT(n);if(!r)return;let i=e.get(r);(i===void 0||n<i)&&e.set(r,n)}function TT(e){let t=new Map,n=new Map;for(let r of e){for(let e of[r.model,r.resolvedModel,r.servedModel,...bT(r).map(e=>e.model)])wT(t,e);for(let e of[r.provider,...bT(r).map(e=>e.provider)])wT(n,e)}return{models:[...t.values()].sort(),providers:[...n.values()].sort()}}var ET=[`all`,`claude`,`codex`,`grok`];function DT(e,t,n){let r=ET.indexOf(t),i=-1;if(e.key===`ArrowRight`||e.key===`ArrowDown`?i=(r+1)%ET.length:e.key===`ArrowLeft`||e.key===`ArrowUp`?i=(r-1+ET.length)%ET.length:e.key===`Home`?i=0:e.key===`End`&&(i=ET.length-1),i<0)return;e.preventDefault();let a=ET[i];n(a),document.getElementById(`logs-surface-${a}`)?.focus()}function OT({filters:e,options:t,hasActiveFilters:n,filteredCount:r,totalCount:i,t:a,onFilterChange:o,onResetFilters:s}){let c=(0,Z.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,Q.jsxs)(`div`,{className:`logs-filter-container`,children:[(0,Q.jsxs)(`div`,{className:`logs-toolbar`,children:[(0,Q.jsx)(`span`,{className:`muted text-control`,children:a(`logs.filter.surface.label`)}),(0,Q.jsx)(`div`,{className:`segmented logs-segmented`,role:`radiogroup`,"aria-label":a(`logs.filter.surface.label`),children:[`all`,`claude`,`codex`,`grok`].map(t=>(0,Q.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=>DT(n,t,t=>o({...e,surface:t})),children:a(`logs.filter.surface.${t}`)},t))}),(0,Q.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:e.interceptedOnly,onChange:t=>o({...e,interceptedOnly:t.target.checked})}),a(`logs.filter.interceptedHelpersOnly`)]}),(0,Q.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[a(`logs.filter.provider.label`),(0,Q.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,Q.jsx)(`option`,{value:``,children:a(`logs.filter.provider.all`)}),t.providers.map(e=>(0,Q.jsx)(`option`,{value:e,children:Ce(e,a)},e))]})]}),(0,Q.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[a(`logs.filter.model.label`),(0,Q.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,Q.jsx)(`option`,{value:``,children:a(`logs.filter.model.all`)}),t.models.map(e=>(0,Q.jsx)(`option`,{value:e,children:e},e))]})]}),(0,Q.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[a(`logs.filter.time.label`),(0,Q.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,Q.jsx)(`option`,{value:`all`,children:a(`logs.filter.time.all`)}),(0,Q.jsx)(`option`,{value:`15m`,children:a(`logs.filter.time.15m`)}),(0,Q.jsx)(`option`,{value:`1h`,children:a(`logs.filter.time.1h`)}),(0,Q.jsx)(`option`,{value:`24h`,children:a(`logs.filter.time.24h`)})]})]}),(0,Q.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[a(`logs.filter.speed.label`),(0,Q.jsxs)(`select`,{className:`input select-sm`,value:u,"aria-label":a(`logs.filter.speed.label`),onChange:e=>d(e.target.value),children:[(0,Q.jsx)(`option`,{value:`all`,children:a(`logs.filter.speed.all`)}),(0,Q.jsx)(`option`,{value:`slow`,children:a(`logs.filter.speed.slow`)}),(0,Q.jsx)(`option`,{value:`medium`,children:a(`logs.filter.speed.medium`)}),(0,Q.jsx)(`option`,{value:`fast`,children:a(`logs.filter.speed.fast`)})]})]}),(0,Q.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[a(`logs.filter.status.label`),(0,Q.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,Q.jsx)(`option`,{value:`all`,children:a(`logs.filter.status.all`)}),(0,Q.jsx)(`option`,{value:`success`,children:a(`logs.filter.status.success`)}),(0,Q.jsx)(`option`,{value:`errors`,children:a(`logs.filter.status.errors`)})]})]}),(0,Q.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[a(`logs.filter.protocol.label`),(0,Q.jsx)(`select`,{className:`input select-sm`,value:e.protocolMode??`all`,"aria-label":a(`logs.filter.protocol.label`),onChange:t=>o({...e,protocolMode:t.target.value}),children:_T.map(e=>(0,Q.jsx)(`option`,{value:e,children:a(kT(e))},e))})]})]}),(0,Q.jsxs)(`div`,{className:`logs-toolbar logs-toolbar-secondary`,children:[(0,Q.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[a(`logs.filter.conversation.label`),(0,Q.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,Q.jsxs)(`div`,{className:`logs-filter-status`,children:[(0,Q.jsx)(`span`,{className:`muted text-control`,children:a(`logs.filter.showingCount`,{count:r,total:i})}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:l,children:[(0,Q.jsx)(xe,{}),` `,a(`logs.filter.reset`)]})]})]})]})}function kT(e){return e===`all`?`logs.filter.protocol.all`:e===`none`?`logs.filter.protocol.none`:wh[e]}function AT({trace:e,t}){let n=lh(e);if(!n)return null;let r=Ah(n,t),i=t(wh[n.mode]);return(0,Q.jsxs)(`span`,{className:`badge badge-muted protocol-path-badge`,title:t(`logs.protocol.badgeTitle`,{path:r,mode:i}),"data-protocol-mode":n.mode,children:[r,` · `,i]})}function jT({trace:e,t}){let n=lh(e);return(0,Q.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-protocol`,children:[(0,Q.jsx)(`h4`,{id:`log-detail-protocol`,className:`log-detail-section-title`,children:t(`logs.detail.protocol.section`)}),n?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`log-detail-grid`,"data-protocol-mode":n.mode,children:[(0,Q.jsx)(`span`,{className:`muted`,children:t(`logs.detail.protocol.inbound`)}),(0,Q.jsx)(`span`,{children:Oh(n.inbound,t)}),(0,Q.jsx)(`span`,{className:`muted`,children:t(`logs.detail.protocol.mode`)}),(0,Q.jsx)(`span`,{children:t(wh[n.mode])}),n.upstream&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:t(`logs.detail.protocol.upstream`)}),(0,Q.jsx)(`span`,{children:Oh(n.upstream,t)})]}),n.requestPath.length>0&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:t(`logs.detail.protocol.requestPath`)}),(0,Q.jsx)(`span`,{children:kh(n.requestPath,t)}),(0,Q.jsx)(`span`,{className:`muted`,children:t(`logs.detail.protocol.responsePath`)}),(0,Q.jsx)(`span`,{children:kh(n.responsePath,t)})]}),(0,Q.jsx)(`span`,{className:`muted`,children:t(`logs.detail.protocol.reasons`)}),(0,Q.jsx)(`span`,{className:`mono log-detail-break`,children:n.reasonCodes.join(`, `)||`–`}),n.featureEffects&&n.featureEffects.length>0&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:t(`logs.detail.protocol.features`)}),(0,Q.jsx)(`span`,{children:n.featureEffects.map(e=>(0,Q.jsxs)(`span`,{style:{display:`block`},children:[(0,Q.jsx)(`code`,{children:e.feature}),`: `,t(Th[e.disposition])]},e.feature))})]}),n.attempts&&n.attempts.length>0&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:t(`logs.detail.protocol.attempts`)}),(0,Q.jsx)(`span`,{children:n.attempts.map(e=>(0,Q.jsxs)(`span`,{style:{display:`block`},children:[t(`logs.detail.protocol.attempt`,{ordinal:e.ordinal}),`:`,` `,kh(e.requestPath,t),` · `,t(wh[e.mode])]},e.ordinal))})]})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm protocol-deep-link`,onClick:()=>m_({inbound:n.inbound,upstream:o_(n.upstream)}),children:t(`protocolLinks.labEvidence`)})]}):(0,Q.jsx)(`p`,{className:`log-detail-notes-line muted`,children:t(`logs.detail.protocol.none`)})]})}function MT(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?{generatedAt:e,receivedAt:t}:void 0}function NT(e,t,n){return e?e.generatedAt+Math.max(0,t-e.receivedAt):n}function PT(){return Gg(window.location.hash)===`logs/debug`?`debug`:`logs`}function FT(e){window.location.hash=e===`debug`?`logs/debug`:`logs`}function IT(e){e.key===`ArrowLeft`||e.key===`Home`?(e.preventDefault(),FT(`logs`),document.getElementById(`logs-tab-logs`)?.focus()):(e.key===`ArrowRight`||e.key===`End`)&&(e.preventDefault(),FT(`debug`),document.getElementById(`logs-tab-debug`)?.focus())}function LT(e){return e.servedModel!==void 0&&e.servedModel!==(e.wireModel??e.model)}function RT(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 zT(e,t){return[LT(e)?t(`logs.modelRerouteTitle`):void 0,`${t(`logs.modelTooltip.model`)}=${e.model}`,e.resolvedModel?`${t(`logs.modelTooltip.resolvedModel`)}=${e.resolvedModel}`:void 0,e.servedModel?`${t(`logs.modelTooltip.servedModel`)}=${e.servedModel}`:void 0,e.wireModel?`${t(`logs.modelTooltip.wireModel`)}=${e.wireModel}`: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}${RT(e.tierOutcome,t)}`:void 0,e.modelSupportsServiceTier===void 0?void 0:`${t(`logs.modelTooltip.supportsTier`)}=${e.modelSupportsServiceTier}`].filter(Boolean).join(` · `)}function BT(e){return e.requestedSpeedLabel||void 0}function VT(e){switch(e.timingBasis){case`generation-window`:return{short:`logs.decodeBasis.generation`,detail:`logs.detail.decodeGeneration`,hint:`logs.detail.decodeBasisHint.generation`};case`legacy-post-visible-output`:return{short:`logs.decodeBasis.legacy`,detail:`logs.detail.decodeLegacy`,hint:`logs.detail.decodeBasisHint.legacy`};default:return{short:`logs.decodeBasis.unknown`,detail:`logs.detail.decodeUnknown`,hint:`logs.detail.decodeBasisHint.unknown`}}}var HT=new Intl.NumberFormat(`en-US`,{style:`currency`,currency:`USD`,currencyDisplay:`narrowSymbol`,minimumFractionDigits:4,maximumFractionDigits:4});function UT(e,t,n,r=!1){if(!Number.isFinite(e)||e<0)return t(`logs.cost.unavailable`);let i=HT.format(e);return t(r?`logs.cost.lowerBound`:`logs.cost.approximate`,{amount:i})}function WT(e,t,n){return!e||e.kind===`unavailable`?t(`logs.cost.unavailable`):UT(e.estimate.cost.total,t,n,e.estimate.priorityLowerBound)}function GT(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 KT(e){return e===`cursor`||e.startsWith(`cursor-`)}function qT(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 JT(e,t){if(!e.usage)return;let n=qT(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(KT(e.provider)?`logs.tokens.noCacheCursorNote`:`logs.tokens.noCacheNote`)),r.join(` · `)}function YT(e){return e===void 0||typeof e==`string`}function XT(e){if(e===void 0)return!0;if(!e||typeof e!=`object`||!YT(e.routeKind)||e.profile!==void 0&&(!e.profile||typeof e.profile!=`object`||!YT(e.profile.id)||!YT(e.profile.revision))||e.selected!==void 0&&(!e.selected||typeof e.selected!=`object`||!YT(e.selected.provider)||!YT(e.selected.model)||!YT(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`||!YT(t.provider)||!YT(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`||!YT(e.code))return!1}}return!0}function ZT(e){if(e.routeDecision===void 0||XT(e.routeDecision))return e;let t={...e};return delete t.routeDecision,t}function QT(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 $T(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}var eE=Object.freeze([`completed`,`failed`,`incomplete`,`aborted`]);Object.freeze(eE.filter(e=>e!==`aborted`)),Object.freeze([`terminal`,`client_cancel`,`non_stream`,`body_stall`,`body_overflow`]);function tE(e){return e.closeReason===`client_cancel`||e.status===499?`aborted`:e.terminalStatus===`failed`?`failed`:e.terminalStatus===`incomplete`||e.closeReason===`body_stall`||e.closeReason===`body_overflow`?`incomplete`:e.terminalStatus===`completed`||e.terminalStatus===void 0&&(e.status===101||e.status>=200&&e.status<400)?`completed`:`failed`}function nE(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function rE(e){return nE(e?.sends)}function iE(e){return nE(e?.unresolved)}function aE(e){return`ocx.logs.list.v1:${e}`}var oE=[];function sE(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`||!XT(t.routeDecision))return null;return e}function cE(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 lE(e){let t=cE(e),n=e.usage?.contextTotalTokens;return typeof n==`number`?Math.max(t??0,n)||void 0:t}function uE(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 dE(e){if(e.reasoningWireField&&e.reasoningWireValue!==void 0)return`${e.reasoningWireField}=${e.reasoningWireValue}`}function fE(e){return LT(e)?(0,Q.jsxs)(Q.Fragment,{children:[zv(e.wireModel??e.model),` → `,zv(e.servedModel)]}):zv(e.servedModel??e.resolvedModel??e.model)}function pE(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 mE=2e3,hE=3e4,gE=4,_E=3,vE={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`},yE={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`},bE={"transient-5xx":`logs.detail.attempt.recovery.transient5xx`,"connection-reset":`logs.detail.attempt.recovery.connectionReset`,"oauth-401":`logs.detail.attempt.recovery.oauth401`,"oauth-account-403":`logs.detail.attempt.recovery.oauthAccount403`,"key-401":`logs.detail.attempt.recovery.key401`,"key-429":`logs.detail.attempt.recovery.key429`,"rate-limit-429":`logs.detail.attempt.recovery.rateLimit429`,"anthropic-oauth-429":`logs.detail.attempt.recovery.anthropicOauth429`,"oauth-account-429":`logs.detail.attempt.recovery.oauthAccount429`,"oauth-account-402":`logs.detail.attempt.recovery.oauthAccount402`,"image-413":`logs.detail.attempt.recovery.image413`,"empty-completion":`logs.detail.attempt.recovery.emptyCompletion`,"console-go-upload-retry":`logs.detail.attempt.recovery.consoleGoUpload`,"opaque-blob-rejection":`logs.detail.attempt.recovery.opaqueBlobRejection`,"reasoning-effort-downgrade":`logs.detail.attempt.recovery.reasoningEffortDowngrade`,"anthropic-fast-downgrade":`logs.detail.attempt.recovery.anthropicFastDowngrade`};function xE(e){return vE[e]}function SE(e){return yE[e]}function CE(e){return bE[e]??`logs.detail.attempt.recovery.unknown`}function wE(e){return e===`verified`?`logs.detail.verification.verified`:`logs.detail.verification.derived`}var TE={completed:`logs.detail.outcome.completed`,failed:`logs.detail.outcome.failed`,incomplete:`logs.detail.outcome.incomplete`,aborted:`logs.detail.outcome.aborted`},EE={"transport-unsent":`logs.detail.cause.transportUnsent`,"transport-ambiguous":`logs.detail.cause.transportAmbiguous`,"upstream-declined":`logs.detail.cause.upstreamDeclined`,"rate-limit":`logs.detail.cause.rateLimit`,"quota-exhausted":`logs.detail.cause.quotaExhausted`,"credential-rejected":`logs.detail.cause.credentialRejected`,"policy-refusal":`logs.detail.cause.policyRefusal`,"parameter-rejected":`logs.detail.cause.parameterRejected`,"ciphertext-refusal":`logs.detail.cause.ciphertextRefusal`,"payload-too-large":`logs.detail.cause.payloadTooLarge`,"payload-rejected":`logs.detail.cause.payloadRejected`,"upstream-fault":`logs.detail.cause.upstreamFault`,"empty-output":`logs.detail.cause.emptyOutput`,"client-cancelled":`logs.detail.cause.clientCancelled`,"local-refusal":`logs.detail.cause.localRefusal`},DE={"pre-header":`logs.detail.stage.preHeader`,"headers-only":`logs.detail.stage.headersOnly`,"protocol-prelude":`logs.detail.stage.protocolPrelude`,"semantic-output":`logs.detail.stage.semanticOutput`,"side-effect":`logs.detail.stage.sideEffect`,terminal:`logs.detail.stage.terminal`},OE={permitted:`logs.detail.resend.permitted`,"permitted-after-repair":`logs.detail.resend.permittedAfterRepair`,"refused-ambiguous":`logs.detail.resend.refusedAmbiguous`,"refused-committed":`logs.detail.resend.refusedCommitted`,"refused-futile":`logs.detail.resend.refusedFutile`};function kE(e){return TE[tE(e)]}function AE(e,t){let n=e.failureCause===void 0?void 0:EE[e.failureCause],r=e.failureStage===void 0?void 0:DE[e.failureStage],i=e.resendPermission===void 0?void 0:OE[e.resendPermission];return{...e.failureCause?{cause:n?t(n):e.failureCause}:{},...e.failureStage?{stage:r?t(r):e.failureStage}:{},...e.resendPermission?{resend:i?t(i):e.resendPermission}:{}}}function jE(e){return e>=200&&e<300?`var(--green)`:e>=400?`var(--red)`:`var(--amber)`}function ME(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 NE(e,t,n){let{date:r,time:i}=ME(e,t,n);return`${r} ${i}`}function PE(e){let t=0;for(let n of e){let e=cE(n);e!==void 0&&(t+=e)}return{requests:e.length,totalTokens:t,...GT(e)}}function FE({apiBase:e}){let{t,locale:n}=r(),i=aE(e),a=sE(io(i)),[o,s]=(0,Z.useState)(!0),[c,l]=(0,Z.useState)({error:null,count:0}),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)(vT),[m,h]=(0,Z.useState)(()=>Date.now()),g=(0,Z.useRef)({key:i,active:!1,request:0}),_=(0,Z.useRef)({key:i,cursor:null,rows:[]});(0,Z.useLayoutEffect)(()=>{let e={key:i,active:!0,request:0};return g.current=e,_.current={key:i,cursor:null,rows:[]},h(Date.now()),()=>{e.active=!1}},[i]);let v=(0,Z.useCallback)(()=>{let e=g.current;return NT(e.key===i?e.anchor:void 0,performance.now(),Date.now())},[i]),y=(0,Z.useRef)(null),b=(0,Z.useRef)({key:i,failures:0,nextAttemptAt:0,error:null}),x=j.find(e=>e.code===n)?.htmlLang,[S,C]=(0,Z.useState)();(0,Z.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,Z.useState)(PT),[E,D]=(0,Z.useState)(()=>PT()===`debug`);(0,Z.useEffect)(()=>{let e=()=>T(PT());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]),(0,Z.useEffect)(()=>{w===`debug`&&D(!0)},[w]);let O=FT,k=(0,Z.useCallback)(async t=>{let n=g.current;if(t.aborted||!n.active||n.key!==i)throw t.reason??new DOMException(`Obsolete log request`,`AbortError`);let r=++n.request,a=()=>!t.aborted&&n.active&&g.current===n&&n.request===r,o=b.current;if(o.key!==i&&(o={key:i,failures:0,nextAttemptAt:0,error:null},b.current=o),o.failures>0&&Date.now()<o.nextAttemptAt)throw o.error;let s=_.current,c=s.key===i?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 r=await e.json(),o=performance.now(),u=QT(r),d=u.rows.map(ZT),f=c&&u.cursor&&!u.reset?$T(s.rows,d):d;if(!a())throw t.reason??new DOMException(`Obsolete log request`,`AbortError`);_.current={key:i,cursor:u.cursor,rows:f};let m=TT(f);p(e=>{let t=e.model.trim().toLowerCase(),n=e.provider.trim().toLowerCase(),r=t?m.models.find(e=>e.trim().toLowerCase()===t)??``:``,i=n?m.providers.find(e=>e.trim().toLowerCase()===n)??``:``;return e.model===r&&e.provider===i?e:{...e,model:r,provider:i}});let g=MT(u.generatedAt,o);return g&&(n.anchor=g),h(NT(n.anchor,o,Date.now())),b.current={key:i,failures:0,nextAttemptAt:0,error:null},co(i,f),f}catch(e){if(!a())throw e;let t=e??Error(`log request failed`),n=o.failures+1,r=mE*2**Math.min(n,gE);throw b.current={key:i,failures:n,nextAttemptAt:Date.now()+r,error:t},t}},[e,i]),A=uo(i,[e],k,{isEmpty:e=>e.length===0,enabled:w===`logs`,pollMs:o?mE:void 0,initialData:a??void 0}),M=A.state,N=M.data??a??oE,P=A.refresh,F=(0,Z.useCallback)(()=>{b.current={key:i,failures:0,nextAttemptAt:0,error:null},_.current={key:i,cursor:null,rows:[]},P({forceLoading:!0})},[P,i]),I=!A.refreshing&&M.showError;!A.refreshing&&!M.showError&&M.data!==void 0&&c.count!==0?l({error:null,count:0}):I&&c.error!==M.error&&l(e=>({error:M.error,count:e.count+1}));let L=c.count>=_E||!o&&I,R=u?iT(u.status,n):null,z=f.conversationId.trim();(0,Z.useEffect)(()=>{if(f.timeWindow===`all`||w!==`logs`)return;h(v());let e=window.setInterval(()=>h(v()),hE);return()=>window.clearInterval(e)},[f.timeWindow,w,v]),(0,Z.useEffect)(()=>{let e=!1;if(!z)p(e=>e.conversationQueryHash===void 0?e:{...e,conversationQueryHash:void 0});else return $w(z).then(t=>{e||p(e=>e.conversationQueryHash?.join(` `)===t.join(` `)?e:{...e,conversationQueryHash:t})}),()=>{e=!0}},[z]);let B=(0,Z.useMemo)(()=>TT(N),[N]),V=yT(f),H=(0,Z.useMemo)(()=>CT(N,f,m),[N,f,m]),U=z?PE(H):null,ee=Gw({count:H.length,getScrollElement:()=>y.current,estimateSize:()=>92,overscan:15,getItemKey:e=>{let t=H[H.length-1-e];return t.requestId??`${t.timestamp}:${t.model}:${t.provider}`}}),W=ee.getVirtualItems(),te=W.length>0?W[0].start:0,G=W.length>0?ee.getTotalSize()-W[W.length-1].end:0;return(0,Q.jsxs)(`div`,{className:`logs-page`,children:[(0,Q.jsxs)(`div`,{className:`page-head`,children:[(0,Q.jsx)(`h2`,{children:t(`nav.logs`)}),w===`logs`&&(0,Q.jsxs)(`label`,{className:`muted text-control logs-auto-refresh`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:o,onChange:e=>s(e.target.checked)}),t(`logs.autoRefresh`)]})]}),(0,Q.jsxs)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":t(`nav.logs`),children:[(0,Q.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:IT,children:t(`logs.tabLogs`)}),(0,Q.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:IT,children:t(`logs.tabDebug`)})]}),E&&(0,Q.jsx)(`div`,{role:`tabpanel`,id:`logs-panel-debug`,"aria-labelledby":`logs-tab-debug`,hidden:w!==`debug`,children:(0,Q.jsx)(hT,{apiBase:e,embedded:!0,active:w===`debug`})}),(0,Q.jsxs)(`div`,{role:`tabpanel`,id:`logs-panel-logs`,"aria-labelledby":`logs-tab-logs`,hidden:w!==`logs`,children:[(0,Q.jsx)(OT,{filters:f,options:B,hasActiveFilters:V,filteredCount:H.length,totalCount:N.length,t,onFilterChange:p,onResetFilters:()=>p(vT)}),U&&(0,Q.jsx)(`div`,{className:`logs-conversation-totals`,children:(0,Q.jsxs)($,{tone:`ok`,children:[t(`logs.conversation.totals`,{requests:U.requests,tokens:q(U.totalTokens,x??n),cost:UT(U.estimatedCostUsd,t,x,U.priorityLowerBound)}),` `,(0,Q.jsxs)(`span`,{className:`muted`,children:[t(`logs.conversation.scope`),U.unpricedRequests+U.unmeteredRequests>0?` ${t(`logs.conversation.excluded`,{unpriced:U.unpricedRequests,unmetered:U.unmeteredRequests})}`:``]})]})}),M.kind===`failed-cold`&&(0,Q.jsxs)($,{tone:`err`,children:[M.error instanceof Error?`${t(`logs.loadError`)} ${M.error.message}`:t(`logs.loadError`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:F,disabled:M.refreshing,children:t(`common.retry`)})]}),L&&N.length>0&&(0,Q.jsxs)($,{tone:`err`,children:[t(`logs.loadError`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:F,disabled:A.refreshing,children:t(`common.retry`)})]}),M.kind===`failed-cold`?null:M.showSkeleton&&N.length===0?(0,Q.jsx)(lb,{label:t(`common.loading`),rows:6}):H.length===0?(0,Q.jsx)(fn,{title:N.length>0&&V?t(`logs.noMatchingRequests`):t(`logs.noRequests`)}):(0,Q.jsx)(Q.Fragment,{children:(0,Q.jsx)(`div`,{ref:y,className:`tbl-wrap logs-table-wrap`,children:(0,Q.jsxs)(`table`,{className:`tbl logs-table`,children:[(0,Q.jsxs)(`colgroup`,{children:[(0,Q.jsx)(`col`,{className:`logs-col-time`}),(0,Q.jsx)(`col`,{className:`logs-col-tokens`}),(0,Q.jsx)(`col`,{className:`logs-col-rate`}),(0,Q.jsx)(`col`,{className:`logs-col-cost`}),(0,Q.jsx)(`col`,{className:`logs-col-model`}),(0,Q.jsx)(`col`,{className:`logs-col-effort`}),(0,Q.jsx)(`col`,{className:`logs-col-provider`}),(0,Q.jsx)(`col`,{className:`logs-col-status`}),(0,Q.jsx)(`col`,{className:`logs-col-request`}),(0,Q.jsx)(`col`,{className:`logs-col-duration`})]}),(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:t(`logs.col.time`)}),(0,Q.jsx)(`th`,{className:`num log-col-tokens`,children:t(`logs.col.tokens`)}),(0,Q.jsx)(`th`,{className:`num log-col-rate`,title:t(`logs.metric.tokPerSecTitle`),children:t(`logs.col.tokPerSec`)}),(0,Q.jsx)(`th`,{className:`num log-col-cost`,title:t(`logs.metric.estimatedCostTitle`),children:t(`logs.col.estimatedCost`)}),(0,Q.jsx)(`th`,{className:`log-col-model`,children:t(`logs.col.model`)}),(0,Q.jsx)(`th`,{children:t(`logs.col.effort`)}),(0,Q.jsx)(`th`,{children:t(`logs.col.provider`)}),(0,Q.jsx)(`th`,{children:t(`logs.col.status`)}),(0,Q.jsx)(`th`,{children:t(`logs.col.request`)}),(0,Q.jsx)(`th`,{className:`num log-col-duration`,children:t(`logs.col.duration`)})]})}),(0,Q.jsxs)(`tbody`,{children:[te>0&&(0,Q.jsx)(`tr`,{children:(0,Q.jsx)(`td`,{colSpan:10,className:`logs-virtual-spacer`,style:{height:te}})}),W.map(e=>{let r=H[H.length-1-e.index],i=dE(r),a=r.displayMetrics?.decodeTokPerSecond,o=VT(a?.kind===`value`?a:{}),s=ME(r.timestamp,x,S);return(0,Q.jsxs)(`tr`,{"data-index":e.index,ref:ee.measureElement,children:[(0,Q.jsx)(`td`,{className:`muted mono log-col-time`,children:(0,Q.jsxs)(`span`,{className:`logs-stack-start`,children:[(0,Q.jsx)(`span`,{children:s.date}),(0,Q.jsx)(`span`,{children:s.time})]})}),(0,Q.jsx)(`td`,{className:`num mono log-col-tokens`,title:JT(r,t),children:(()=>{let e=lE(r),{read:i,write:a}=qT(r);return e===void 0?(0,Q.jsx)(`span`,{className:`muted`,children:t(`logs.tokens.${r.usageStatus??`unreported`}`)}):(0,Q.jsxs)(`span`,{className:`logs-stack-end`,children:[(0,Q.jsxs)(`span`,{children:[r.usageStatus===`estimated`?`~`:``,q(e,n)]}),i!==void 0&&i>0&&(0,Q.jsxs)(`span`,{className:`muted text-caption leading-tight`,children:[`c `,q(i,n)]}),a!==void 0&&a>0&&(0,Q.jsxs)(`span`,{className:`muted text-caption leading-tight`,children:[`w `,q(a,n)]}),r.usageStatus===`estimated`&&i===void 0&&a===void 0&&(0,Q.jsx)(`span`,{className:`muted text-caption leading-tight`,children:t(KT(r.provider)?`logs.tokens.noCacheCursor`:`logs.tokens.noCache`)})]})})()}),(0,Q.jsxs)(`td`,{className:`num mono log-col-rate`,children:[pE(r.displayMetrics?.tokPerSecond,x),a?.kind===`value`&&(0,Q.jsxs)(`span`,{className:`logs-stack-end logs-decode-rate muted`,title:t(o.detail),children:[(0,Q.jsx)(`span`,{children:pE(a,x)}),(0,Q.jsx)(`span`,{className:`text-caption`,children:t(o.short)})]})]}),(0,Q.jsx)(`td`,{className:`num mono log-col-cost`,children:WT(r.displayMetrics?.cost,t,x)}),(0,Q.jsx)(`td`,{className:`mono log-col-model`,title:zT(r,t),children:(0,Q.jsxs)(`span`,{className:`logs-model-cell`,children:[(0,Q.jsx)(`span`,{children:fE(r)}),r.shadowCallRewrittenFrom&&(0,Q.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,Q.jsx)(`span`,{className:`badge badge-accent`,children:t(`logs.badge.claude`)}),r.surface===`grok`&&(0,Q.jsx)(`span`,{className:`badge badge-accent`,children:t(`logs.badge.grok`)}),BT(r)&&(0,Q.jsx)(`span`,{className:`badge badge-amber`,children:BT(r)}),(0,Q.jsx)(AT,{trace:r.protocolTrace,t})]})}),(0,Q.jsx)(`td`,{className:`mono log-reasoning-cell`,title:i,children:uE(r)}),(0,Q.jsx)(`td`,{className:`muted`,children:Ce(r.provider,t)}),(0,Q.jsx)(`td`,{children:(0,Q.jsxs)(`span`,{className:`log-status-cell`,children:[(0,Q.jsx)(`span`,{className:`mono font-semibold`,style:{color:jE(r.status)},children:r.status}),(0,Q.jsx)(`button`,{type:`button`,className:`log-detail-btn`,onClick:()=>d(r),"aria-label":`${t(`logs.details`)}: ${r.requestId??r.status}`,children:t(`logs.details`)})]})}),(0,Q.jsx)(`td`,{className:`muted mono`,children:(0,Q.jsx)(`span`,{className:`log-reqid`,title:r.requestId,children:r.requestId??`-`})}),(0,Q.jsxs)(`td`,{className:`num log-col-duration`,children:[r.durationMs,`ms`]})]},e.key)}),G>0&&(0,Q.jsx)(`tr`,{children:(0,Q.jsx)(`td`,{colSpan:10,className:`logs-virtual-spacer`,style:{height:G}})})]})]})})}),u&&(0,Q.jsx)(LE,{detail:u,detailInfo:R,localeCode:n,localeTag:x,serverTimeZone:S,t,onClose:()=>d(null),onFilterConversation:e=>{p(t=>({...t,conversationId:e})),d(null)}})]})]})}function IE(e){let t=(0,Z.useRef)(null);return(0,Z.useEffect)(()=>{let n=t.current;n&&(e&&!n.open?n.showModal():!e&&n.open&&n.close())},[e]),t}function LE({detail:e,detailInfo:t,localeCode:n,localeTag:r,serverTimeZone:i,t:a,onClose:o,onFilterConversation:s}){let c=IE(!0),[l,u]=(0,Z.useState)(!1),d=qT(e),f=e.displayMetrics?.cost,p=e.displayMetrics?.decodeTokPerSecond,m=VT(p?.kind===`value`?p:{}),h=dE(e),g=AE(e,a),_=async()=>{if(e.requestId)try{await navigator.clipboard.writeText(e.requestId),u(!0),window.setTimeout(()=>u(!1),1200)}catch{}};return(0,Q.jsxs)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":`log-detail-title`,onCancel:e=>{e.preventDefault(),o()},children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":a(`common.close`),tabIndex:-1,onClick:o}),(0,Q.jsxs)(`div`,{className:`modal-card log-detail-card`,onClick:e=>e.stopPropagation(),role:`document`,children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsxs)(`h3`,{id:`log-detail-title`,children:[(0,Q.jsx)(`span`,{className:`mono`,style:{color:jE(e.status)},children:e.status}),t&&(0,Q.jsx)(`span`,{className:`logs-detail-info`,children:t.label})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:o,"aria-label":a(`common.cancel`),children:(0,Q.jsx)(xe,{})})]}),t&&(0,Q.jsx)(`p`,{className:`modal-desc`,children:t.description}),(0,Q.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-basic`,children:[(0,Q.jsx)(`h4`,{id:`log-detail-basic`,className:`log-detail-section-title`,children:a(`logs.detail.section.basic`)}),(0,Q.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.col.time`)}),(0,Q.jsx)(`span`,{className:`mono`,children:NE(e.timestamp,r,i)}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.outcome.label`)}),(0,Q.jsx)(`span`,{children:a(kE(e))}),g.cause&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.cause.label`)}),(0,Q.jsxs)(`span`,{children:[g.cause,g.stage&&` (${a(`logs.detail.stage.label`)}: ${g.stage})`]})]}),g.resend&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.resend.label`)}),(0,Q.jsx)(`span`,{children:g.resend})]}),e.spend&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.sends.label`)}),(0,Q.jsxs)(`span`,{className:`mono`,children:[rE(e.spend),iE(e.spend)>0&&` (${a(`logs.detail.sends.unresolved`)}: ${iE(e.spend)})`]})]}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.col.request`)}),(0,Q.jsxs)(`span`,{className:`log-detail-request-row`,children:[(0,Q.jsx)(`span`,{className:`mono log-detail-break`,children:e.requestId??`—`}),e.requestId&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void _(),children:a(l?`logs.detail.copied`:`logs.detail.copyRequestId`)})]}),e.conversationId&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.conversation`)}),(0,Q.jsxs)(`span`,{className:`log-detail-request-row`,children:[(0,Q.jsx)(`span`,{className:`mono log-detail-break`,children:e.conversationId}),s&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>s(e.conversationId),children:a(`logs.filter.conversation.apply`)})]})]}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.col.model`)}),(0,Q.jsx)(`span`,{className:`mono`,children:fE(e)}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.col.provider`)}),(0,Q.jsx)(`span`,{children:Ce(e.provider,a)}),(e.requestedEffort||e.effectiveEffort)&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.col.effort`)}),(0,Q.jsxs)(`span`,{className:`mono`,children:[uE(e),h?` (${h})`:``]})]}),e.errorCode&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.col.error`)}),(0,Q.jsx)(`span`,{className:`mono`,children:e.errorCode})]}),e.upstreamError&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.col.upstreamReason`)}),(0,Q.jsx)(`span`,{className:`mono log-detail-break`,children:e.upstreamError})]})]})]}),(0,Q.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-route`,children:[(0,Q.jsx)(`h4`,{id:`log-detail-route`,className:`log-detail-section-title`,children:a(`logs.detail.route.section`)}),e.routeDecision?(0,Q.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.route.kind`)}),(0,Q.jsx)(`span`,{className:`mono`,children:e.routeDecision.routeKind??`–`}),e.routeDecision.profile?.id&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.route.profile`)}),(0,Q.jsxs)(`span`,{className:`mono`,children:[e.routeDecision.profile.id,` (`,e.routeDecision.profile.revision,`)`]})]}),e.routeDecision.selected?.provider&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.route.selected`)}),(0,Q.jsxs)(`span`,{className:`mono`,children:[e.routeDecision.selected.provider,`/`,e.routeDecision.selected.model,e.routeDecision.selected.reason?` — ${e.routeDecision.selected.reason}`:``]})]}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.route.candidates`)}),(0,Q.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,Q.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`logs.detail.route.unknown`)})]}),(0,Q.jsx)(jT,{trace:e.protocolTrace,t:a}),(0,Q.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-performance`,children:[(0,Q.jsx)(`h4`,{id:`log-detail-performance`,className:`log-detail-section-title`,children:a(`logs.detail.section.performance`)}),(0,Q.jsxs)(`div`,{className:`log-detail-grid log-detail-performance-grid`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.col.duration`)}),(0,Q.jsxs)(`span`,{className:`mono`,children:[e.durationMs,`ms`]}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.endToEndTokPerSec`)}),(0,Q.jsx)(`span`,{className:`mono`,children:pE(e.displayMetrics?.tokPerSecond,r)}),p?.kind===`value`&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,title:a(m.hint),children:a(m.detail)}),(0,Q.jsx)(`span`,{className:`mono`,children:pE(p,r)}),(0,Q.jsx)(`span`,{className:`logs-decode-basis-hint muted text-caption`,children:a(m.hint)})]}),e.firstOutputMs!==void 0&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.ttft`)}),(0,Q.jsxs)(`span`,{className:`mono`,children:[e.firstOutputMs,`ms`]})]})]}),e.displayMetrics?.tokPerSecond.kind===`unavailable`&&(0,Q.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(xE(e.displayMetrics.tokPerSecond.reason))}),e.displayMetrics?.decodeTokPerSecond?.kind===`unavailable`&&(0,Q.jsxs)(`p`,{className:`log-detail-notes-line muted`,children:[a(`logs.detail.decodeTokPerSec`),`: `,a(xE(e.displayMetrics.decodeTokPerSecond.reason))]})]}),(0,Q.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-cost`,children:[(0,Q.jsx)(`h4`,{id:`log-detail-cost`,className:`log-detail-section-title`,children:a(`logs.detail.section.cost`)}),(0,Q.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`usage.cost.disclaimer`)}),f?.kind===`value`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.costTotal`)}),(0,Q.jsx)(`span`,{className:`mono`,children:UT(f.estimate.cost.total,a,r,f.estimate.priorityLowerBound)}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.input`)}),(0,Q.jsx)(`span`,{className:`mono`,children:UT(f.estimate.cost.input,a,r,f.estimate.priorityLowerBound)}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheRead`)}),(0,Q.jsx)(`span`,{className:`mono`,children:UT(f.estimate.cost.cacheRead,a,r,f.estimate.priorityLowerBound)}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheWrite`)}),(0,Q.jsx)(`span`,{className:`mono`,children:UT(f.estimate.cost.cacheWrite,a,r,f.estimate.priorityLowerBound)}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.output`)}),(0,Q.jsx)(`span`,{className:`mono`,children:UT(f.estimate.cost.output,a,r,f.estimate.priorityLowerBound)}),f.estimate.price&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.matchedKey`)}),(0,Q.jsxs)(`span`,{className:`mono log-detail-break`,children:[f.estimate.price.jawcodeProvider??f.estimate.price.provider,`/`,f.estimate.price.modelId]}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.priceSource`)}),(0,Q.jsxs)(`span`,{children:[a(`logs.detail.source.${f.estimate.price.source}`),` · `,a(wE(f.estimate.price.status))]})]})]}),f.estimateReasons.length>0&&(0,Q.jsx)(`ul`,{className:`log-detail-notes`,children:f.estimateReasons.map(e=>(0,Q.jsx)(`li`,{children:a(SE(e))},e))})]}):(0,Q.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.costTotal`)}),(0,Q.jsx)(`span`,{className:`mono`,children:a(`logs.cost.unavailable`)}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.unavailableReason`)}),(0,Q.jsx)(`span`,{children:f?.kind===`unavailable`?a(xE(f.reason)):a(`logs.detail.reason.usage_missing`)})]})]}),e.attempts?.length?(0,Q.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-attempts`,children:[(0,Q.jsx)(`h4`,{id:`log-detail-attempts`,className:`log-detail-section-title`,children:a(`logs.detail.section.attempts`)}),(0,Q.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`logs.detail.attempt.e2eNote`)}),(0,Q.jsx)(`div`,{className:`log-detail-attempts-wrap`,children:(0,Q.jsxs)(`table`,{className:`tbl log-detail-attempts`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{className:`num`,children:`#`}),(0,Q.jsx)(`th`,{children:a(`logs.detail.attempt.target`)}),(0,Q.jsx)(`th`,{className:`num`,children:a(`logs.col.duration`)}),(0,Q.jsx)(`th`,{className:`num`,title:a(`logs.detail.endToEndTokPerSec`),children:a(`logs.col.tokPerSec`)}),(0,Q.jsx)(`th`,{className:`num`,children:a(`logs.col.estimatedCost`)}),(0,Q.jsx)(`th`,{children:a(`logs.detail.attempt.reason`)})]})}),(0,Q.jsx)(`tbody`,{children:e.attempts.toSorted((e,t)=>e.ordinal-t.ordinal).map(e=>{let t=e.displayMetrics?.cost,n=e.displayMetrics?.decodeTokPerSecond,i=VT(n?.kind===`value`?n:{}),o=dE(e),s=t?.kind===`value`?t.estimate.price:void 0,c=AE(e,a).cause??e.errorCode??(e.recoveryKinds.length?e.recoveryKinds.map(e=>a(CE(e))).join(`, `):void 0)??(t?.kind===`unavailable`?a(xE(t.reason)):a(`logs.detail.attempt.completed`));return(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`num mono`,children:e.ordinal}),(0,Q.jsxs)(`td`,{children:[(0,Q.jsx)(`span`,{children:Ce(e.provider,a)}),(0,Q.jsx)(`br`,{}),(0,Q.jsx)(`span`,{className:`mono muted log-detail-break`,children:e.model}),(e.requestedEffort||e.effectiveEffort)&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`br`,{}),(0,Q.jsxs)(`span`,{className:`mono muted text-caption log-detail-break`,children:[uE(e),o?` (${o})`:``]})]}),s&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`br`,{}),(0,Q.jsxs)(`span`,{className:`muted text-caption log-detail-break`,children:[s.jawcodeProvider??s.provider,`/`,s.modelId,` · `,a(`logs.detail.source.${s.source}`),` · `,a(wE(s.status))]})]})]}),(0,Q.jsxs)(`td`,{className:`num mono`,children:[e.durationMs,`ms`]}),(0,Q.jsxs)(`td`,{className:`num mono`,children:[pE(e.displayMetrics?.tokPerSecond,r),n?.kind===`value`&&(0,Q.jsxs)(`span`,{className:`logs-stack-end logs-decode-rate muted`,title:a(i.detail),children:[(0,Q.jsx)(`span`,{children:pE(n,r)}),(0,Q.jsx)(`span`,{className:`text-caption`,children:a(i.short)})]})]}),(0,Q.jsx)(`td`,{className:`num mono`,children:WT(t,a,r)}),(0,Q.jsx)(`td`,{className:`log-detail-break`,children:c})]},`${e.ordinal}-${e.provider}-${e.model}`)})})]})})]}):null,(0,Q.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-usage`,children:[(0,Q.jsx)(`h4`,{id:`log-detail-usage`,className:`log-detail-section-title`,children:a(`logs.detail.section.usage`)}),(0,Q.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.input`)}),(0,Q.jsx)(`span`,{className:`mono`,children:e.usage?q(e.usage.inputTokens,n):`—`}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.output`)}),(0,Q.jsx)(`span`,{className:`mono`,children:e.usage?q(e.usage.outputTokens,n):`—`}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheRead`)}),(0,Q.jsx)(`span`,{className:`mono`,children:d.read===void 0?`—`:q(d.read,n)}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheWrite`)}),(0,Q.jsx)(`span`,{className:`mono`,children:d.write===void 0?`—`:q(d.write,n)}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.reasoning`)}),(0,Q.jsx)(`span`,{className:`mono`,children:e.usage?.reasoningOutputTokens===void 0?`—`:q(e.usage.reasoningOutputTokens,n)}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.totalTokens`)}),(0,Q.jsx)(`span`,{className:`mono`,children:lE(e)===void 0?`—`:q(lE(e),n)}),e.usage?.contextTotalTokens!==void 0&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.contextTotal`)}),(0,Q.jsx)(`span`,{className:`mono`,children:q(e.usage.contextTotalTokens,n)})]})]}),e.usageStatus===`estimated`&&(0,Q.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`logs.tokens.estimatedNote`)})]}),(0,Q.jsxs)(`details`,{className:`log-detail-raw`,children:[(0,Q.jsx)(`summary`,{children:a(`logs.detailRaw`)}),(0,Q.jsx)(`pre`,{className:`log-detail-json`,children:JSON.stringify(e,null,2)})]})]})]})}function RE(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 zE(e,t){if(!e||!t)return{ok:!1,error:`required`};let n=RE(e),r=RE(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 BE=[`requests`,`tokens`,`cost`,`quota`,`none`],VE=[6,24,72,168],HE=[`line`,`stackedBar`],UE=[`total`,`input`,`output`,`cached`],WE=[`sum`,`average`,`max`],GE=[`model`,`modelAccount`],KE={requests:`usage.companion.menuRequests`,tokens:`usage.companion.menuTokens`,cost:`usage.companion.menuCost`,quota:`usage.companion.menuQuota`,none:`usage.companion.menuNone`},qE={6:`usage.companion.window6`,24:`usage.companion.window24`,72:`usage.companion.window72`,168:`usage.companion.window168`},JE={total:`usage.companion.metricTotal`,input:`usage.companion.metricInput`,output:`usage.companion.metricOutput`,cached:`usage.companion.metricCached`},YE=[[`showToday`,`usage.companion.sectionToday`],[`showChart`,`usage.companion.sectionChart`],[`showModels`,`usage.companion.sectionModels`],[`showCost`,`usage.companion.sectionCost`],[`showAccounts`,`usage.companion.sectionAccounts`]],XE={sum:`usage.companion.aggregationSum`,average:`usage.companion.aggregationAverage`,max:`usage.companion.aggregationMax`},ZE={macos:[`usage.companion.installMacStep1`,`usage.companion.installMacStep2`,`usage.companion.installMacStep3`],windows:[`usage.companion.installWinStep1`,`usage.companion.installWinStep2`,`usage.companion.installWinStep3`],linux:[`usage.companion.installLinuxStep1`,`usage.companion.installLinuxStep2`,`usage.companion.installLinuxStep3`]},QE={macos:`usage.companion.osMac`,windows:`usage.companion.osWindows`,linux:`usage.companion.osLinux`};function $E(e,t){return new Intl.DateTimeFormat(t,{hour:`2-digit`,minute:`2-digit`}).format(e)}function eD(e){return e instanceof Error&&e.message?e.message:String(e)}function tD({value:e,onChange:t,t:n}){return(0,Q.jsx)(`div`,{className:`usage-segmented`,role:`group`,"aria-label":n(`usage.companion.installOs`),children:Object.keys(QE).map(r=>(0,Q.jsx)(`button`,{type:`button`,className:`usage-segmented-btn${e===r?` active`:``}`,"aria-pressed":e===r,onClick:()=>t(r),children:n(QE[r])},r))})}function nD({label:e,value:t,options:n,optionLabel:r,onChange:i}){return(0,Q.jsxs)(`div`,{className:`usage-companion-control`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:e}),(0,Q.jsx)(`div`,{className:`usage-segmented`,role:`group`,"aria-label":e,children:n.map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`usage-segmented-btn${e===t?` active`:``}`,"aria-pressed":e===t,onClick:()=>i(e),children:r(e)},String(e)))})]})}function rD({label:e,value:t,options:n,optionLabel:r,onChange:i}){return(0,Q.jsxs)(`label`,{className:`usage-companion-control`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:e}),(0,Q.jsx)(`select`,{value:t,onChange:e=>i(e.target.value),children:n.map(e=>(0,Q.jsx)(`option`,{value:e,children:r(e)},e))})]})}function iD(e){let[t,n]=(0,Z.useState)(!1);return(0,Z.useEffect)(()=>{if(t||!e.current||typeof IntersectionObserver>`u`)return;let r=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&(n(!0),r.disconnect())},{rootMargin:`240px`});return r.observe(e.current),()=>r.disconnect()},[e,t]),t}function aD({apiBase:e,providers:t,onSettingsLoaded:n}){let{t:i,locale:a}=r(),o=(0,Z.useRef)(null),s=iD(o),[c,l]=(0,Z.useState)(null),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)(null),[m,h]=(0,Z.useState)([]),[g,_]=(0,Z.useState)(null),[v,y]=(0,Z.useState)(null),[b,x]=(0,Z.useState)(!1),[S,C]=(0,Z.useState)(`idle`),[w,T]=(0,Z.useState)(null),[E,D]=(0,Z.useState)(null),O=(0,Z.useRef)(null),k=(0,Z.useRef)(null),A=(0,Z.useRef)(null),j=(0,Z.useRef)(S),M=(0,Z.useRef)(u),N=(0,Z.useRef)(new Map),[P,F]=(0,Z.useState)(new Map),[I,L]=(0,Z.useState)(()=>{let e=vo();return e===`unknown`?`macos`:e});(0,Z.useEffect)(()=>{j.current=S},[S]),(0,Z.useEffect)(()=>{M.current=u},[u]);let R=(0,Z.useCallback)(async()=>{_(null);try{let t=await fetch(`${e}/api/companion/settings`);if(!t.ok)throw Error(`${t.status} ${t.statusText}`.trim());let r=await t.json();l(r),T(Date.now()),d(r.settings),k.current=r.settings,n?.(r.settings.menuBarMetric)}catch(e){_(eD(e))}},[e,n]);(0,Z.useEffect)(()=>{if(!s||c)return;let e=setTimeout(()=>void R(),0);return()=>clearTimeout(e)},[R,c,s]),(0,Z.useEffect)(()=>{if(!s)return;let e=setInterval(()=>{j.current!==`saving`&&(M.current&&k.current!==M.current||R())},6e4);return()=>clearInterval(e)},[R,s]);let z=(0,Z.useMemo)(()=>u?rt(u):null,[u]),B=(0,Z.useCallback)(async()=>{if(!z)return;A.current?.abort();let t=new AbortController;A.current=t,x(!0),y(null);try{let n=await fetch(`${e}/api/usage/timeline?${z}`,{signal:t.signal});if(!n.ok)throw Error(`${n.status} ${n.statusText}`.trim());let r=await n.json(),i=u?Ee(r,u):r;p(i),h(i.availableModels);let a=new Map;for(let e of i.series)a.set(e.id,(a.get(e.id)??0)+e.total);for(let[e,t]of a)N.current.set(e,t);F(new Map(N.current))}catch(e){t.signal.aborted||y(eD(e))}finally{t.signal.aborted||x(!1)}},[u,e,z]);(0,Z.useEffect)(()=>{if(!s||!z)return;let e=setTimeout(()=>void B(),250),t=setInterval(()=>void B(),6e4);return()=>{clearTimeout(e),clearInterval(t),A.current?.abort()}},[z,B,s]);let V=(0,Z.useCallback)(e=>{c?.corrupt||(d(t=>t&&{...t,...e}),C(`saving`),D(null))},[c?.corrupt]);(0,Z.useEffect)(()=>{if(!c?.corrupt&&u&&k.current&&k.current!==u&&S===`saving`)return O.current&&clearTimeout(O.current),O.current=setTimeout(async()=>{try{let t=Fe(u,m),n=await fetch(`${e}/api/companion/settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({settings:t})}),r=await n.json();if(!n.ok)throw Error(r&&`error`in r&&r.error?r.error:`${n.status} ${n.statusText}`.trim());l(r),T(Date.now()),d(r.settings),k.current=r.settings,C(`saved`)}catch(e){D(eD(e)),C(`error`)}},300),()=>{O.current&&clearTimeout(O.current)}},[e,m,c?.corrupt,S,u]);let H=(0,Z.useRef)(m);(0,Z.useEffect)(()=>{H.current=m},[m]),(0,Z.useEffect)(()=>()=>{let t=M.current;t&&k.current&&k.current!==t&&j.current===`saving`&&fetch(`${e}/api/companion/settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({settings:Fe(t,H.current)}),keepalive:!0}).catch(()=>{})},[e]);let U=(0,Z.useCallback)(async()=>{C(`saving`),D(null);try{let t=await fetch(`${e}/api/companion/settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({reset:!0})});if(!t.ok)throw Error(`${t.status} ${t.statusText}`.trim());await R(),C(`saved`)}catch(e){D(eD(e)),C(`error`)}},[e,R]),ee=(0,Z.useCallback)(async()=>{try{let t=location.hash?`/${location.hash}`:`/#/usage`,n=await fetch(`${e}/api/companion/open-in-browser`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({path:t})});if(!n.ok)throw Error(`${n.status} ${n.statusText}`.trim())}catch(e){D(eD(e))}},[e]);if(g)return(0,Q.jsxs)(`section`,{ref:o,className:`usage-companion-panel`,children:[(0,Q.jsx)(`p`,{role:`alert`,children:i(`usage.companion.settingsUnavailable`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void R(),children:i(`common.retry`)})]});let W=u;if(!W)return(0,Q.jsx)(`section`,{ref:o,className:`usage-companion-panel`,"aria-busy":`true`,children:(0,Q.jsx)(`div`,{className:`usage-companion-loading`,children:i(`common.loading`)})});let te=t.map(e=>e.provider).filter((e,t,n)=>n.indexOf(e)===t).toSorted(),G=W.models??m,ne=new Set(G),K=ke(m,P),re=new Set(W.hiddenProviders),q=S===`saved`&&c?.updatedAt?i(`usage.companion.saved`,{time:$E(c.updatedAt,a)}):S===`error`?i(`usage.companion.saveFailed`,{error:E??``}):``;return(0,Q.jsxs)(`section`,{ref:o,className:`usage-companion-panel`,children:[c?.corrupt&&(0,Q.jsxs)(`div`,{className:`usage-companion-save-status is-error`,role:`alert`,children:[(0,Q.jsx)(`span`,{children:i(`usage.companion.corrupt`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void U(),disabled:S===`saving`,children:i(`usage.companion.corruptReset`)})]}),(0,Q.jsxs)(`div`,{className:`usage-companion-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h3`,{className:`panel-title`,children:i(`usage.companion.title`)}),(0,Q.jsx)(`p`,{className:`card-sub`,children:i(`usage.companion.description`)})]}),(0,Q.jsx)(`a`,{className:`btn btn-ghost btn-sm`,href:`https://opencodex.me/guides/macos-menu-bar/`,target:`_blank`,rel:`noreferrer`,children:i(`usage.companion.installGuide`)})]}),(()=>{let e=c?.companion?.lastSeenAt??null,t=e!==null&&w!==null&&w-e<=6e5,n=e===null||w===null?``:Bs(e,Vs(i),w),r=mo(),a=po()??`2.95.1`,o=ZE[I],s=(0,Q.jsxs)(`ol`,{className:`usage-companion-install-steps`,children:[(0,Q.jsxs)(`li`,{children:[i(o[0]),` `,(0,Q.jsx)(`a`,{className:`btn btn-ghost btn-sm`,href:`https://github.com/lidge-jun/opencodex/releases/latest`,target:`_blank`,rel:`noreferrer`,children:i(`common.github`)})]}),(0,Q.jsx)(`li`,{children:i(o[1])}),(0,Q.jsx)(`li`,{children:i(o[2])})]}),l=I===`macos`?(0,Q.jsx)(`code`,{className:`usage-companion-install-command`,children:`xattr -d com.apple.quarantine /Applications/OpenCodex.app`}):I===`linux`?(0,Q.jsx)(`code`,{className:`usage-companion-install-command`,children:`chmod +x OpenCodex-*.AppImage`}):null,u=(0,Q.jsxs)(`details`,{children:[(0,Q.jsx)(`summary`,{children:i(`usage.companion.installAnother`)}),(0,Q.jsx)(tD,{value:I,onChange:L,t:i}),s,l]});return r?(0,Q.jsxs)(`div`,{className:`usage-companion-install usage-companion-install--shell`,children:[(0,Q.jsx)(`p`,{children:i(`usage.companion.runningInDesktop`,{version:a})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void ee(),children:i(`usage.companion.openInBrowser`)}),u]}):t?(0,Q.jsxs)(`div`,{className:`usage-companion-install usage-companion-install--connected`,children:[(0,Q.jsxs)(`div`,{className:`usage-companion-install-status`,children:[(0,Q.jsx)(`span`,{className:`usage-companion-install-dot`,"aria-hidden":`true`}),i(c?.companion?.kind===`desktop`?`usage.companion.connectedDesktop`:`usage.companion.connected`,{age:n})]}),u]}):(0,Q.jsxs)(`details`,{className:`usage-companion-install`,open:!0,children:[(0,Q.jsx)(`summary`,{children:i(`usage.companion.installTitle`)}),e!==null&&(0,Q.jsx)(`p`,{className:`usage-companion-install-last-seen muted text-caption`,children:i(`usage.companion.lastSeen`,{age:n})}),e===null&&(0,Q.jsx)(`p`,{className:`usage-companion-install-last-seen muted text-caption`,children:i(`usage.companion.notConnected`)}),(0,Q.jsx)(tD,{value:I,onChange:L,t:i}),s,l]})})(),(0,Q.jsx)(Ge,{timeline:f,chartStyle:W.chartStyle,hours:W.chartHours,loading:b,error:v,onRetry:()=>void B(),locale:a,t:i}),K.length>0&&(0,Q.jsxs)(`section`,{className:`usage-companion-models`,children:[(0,Q.jsxs)(`div`,{className:`usage-companion-models-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`span`,{className:`field-label`,children:i(`usage.companion.modelsOnChart`)}),(0,Q.jsx)(`span`,{className:`usage-companion-models-count text-caption muted`,children:i(`usage.companion.modelsCount`,{selected:G.length,total:m.length})})]}),W.models!==null&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>V({models:null}),disabled:c?.corrupt,children:i(`usage.companion.modelsShowAll`)})]}),(0,Q.jsx)(`div`,{className:`usage-companion-models-list`,children:K.map(e=>{let t=e.models.filter(e=>ne.has(e.id)).length,n=t===e.models.length;return(0,Q.jsxs)(`div`,{className:`usage-companion-model-group`,children:[(0,Q.jsxs)(`div`,{className:`usage-companion-model-group-header`,children:[(0,Q.jsx)(`span`,{className:`usage-companion-model-provider`,children:e.provider}),(0,Q.jsx)(`span`,{className:`usage-companion-model-chip mono text-caption`,children:e.models.length}),(0,Q.jsx)(ln,{on:n,mixed:t>0&&!n,onClick:()=>V({models:st(W.models,m,e.models.map(e=>e.id),!n)}),disabled:c?.corrupt,label:e.provider,title:e.provider})]}),e.models.map(e=>{let t=ne.has(e.id);return(0,Q.jsxs)(`div`,{className:`usage-companion-model-row${t?``:` is-off`}`,children:[(0,Q.jsx)(ln,{on:t,onClick:()=>V({models:st(W.models,m,[e.id],!t)}),disabled:c?.corrupt,label:e.id,title:e.id}),(0,Q.jsx)(`code`,{className:`mono text-control`,children:e.id}),(0,Q.jsx)(`span`,{className:`usage-companion-model-total muted text-caption`,children:P.has(e.id)?lt(e.total):`—`})]},e.id)})]},e.provider)})})]}),(0,Q.jsxs)(`fieldset`,{className:`usage-companion-controls`,disabled:c?.corrupt,children:[(0,Q.jsx)(nD,{label:i(`usage.companion.menuBarShows`),value:W.menuBarMetric,options:BE,optionLabel:e=>i(KE[e]),onChange:e=>V({menuBarMetric:e})}),(0,Q.jsx)(nD,{label:i(`usage.companion.window`),value:W.chartHours,options:VE,optionLabel:e=>i(qE[e]),onChange:e=>V({chartHours:e,bucketMinutes:Le(e)})}),(0,Q.jsx)(nD,{label:i(`usage.companion.style`),value:W.chartStyle,options:HE,optionLabel:e=>i(e===`line`?`usage.companion.styleLine`:`usage.companion.styleStacked`),onChange:e=>V({chartStyle:e})}),(0,Q.jsx)(rD,{label:i(`usage.companion.metric`),value:W.tokenMetric,options:UE,optionLabel:e=>i(JE[e]),onChange:e=>V({tokenMetric:e})}),(0,Q.jsx)(rD,{label:i(`usage.companion.groupBy`),value:W.chartGrouping,options:GE,optionLabel:e=>i(e===`model`?`usage.companion.groupModel`:`usage.companion.groupAccount`),onChange:e=>V({chartGrouping:e})}),(0,Q.jsxs)(`fieldset`,{className:`usage-companion-switches`,children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:i(`usage.companion.popoverSections`)}),YE.map(([e,t])=>(0,Q.jsxs)(`div`,{className:`usage-companion-switch`,children:[(0,Q.jsx)(`span`,{children:i(t)}),(0,Q.jsx)(`button`,{type:`button`,className:`toggle ${W[e]?`on`:``}`,"aria-label":i(t),"aria-pressed":W[e],onClick:()=>V({[e]:!W[e]}),children:(0,Q.jsx)(`span`,{className:`toggle-knob`})})]},e))]}),(0,Q.jsxs)(`details`,{className:`usage-companion-advanced`,children:[(0,Q.jsx)(`summary`,{children:i(`usage.companion.advanced`)}),(0,Q.jsxs)(`div`,{className:`usage-companion-advanced-body`,children:[(0,Q.jsx)(rD,{label:i(`usage.companion.aggregation`),value:W.aggregation,options:WE,optionLabel:e=>i(XE[e]),onChange:e=>V({aggregation:e})}),(0,Q.jsxs)(`label`,{className:`usage-companion-control`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:i(`usage.companion.menuText`)}),(0,Q.jsx)(`input`,{value:W.menuBarTemplate??``,onChange:e=>V({menuBarTemplate:e.target.value}),maxLength:200}),(0,Q.jsxs)(`span`,{className:`muted text-caption`,children:[i(`usage.companion.placeholders`),` `,(0,Q.jsx)(`code`,{children:`{requests} {totalTokens} {inputTokens} {outputTokens} {costUsd} {quotaPercent}`})]})]}),te.length>0&&(0,Q.jsxs)(`fieldset`,{className:`usage-companion-check-list`,children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:i(`usage.companion.hideProviders`)}),te.map(e=>(0,Q.jsxs)(`label`,{children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:re.has(e),onChange:t=>V({hiddenProviders:t.target.checked?[...W.hiddenProviders,e]:W.hiddenProviders.filter(t=>t!==e)})}),` `,(0,Q.jsx)(`span`,{children:e})]},e))]})]})]})]}),(0,Q.jsxs)(`div`,{className:`usage-companion-save-status${S===`error`?` is-error`:``}`,role:S===`error`?`alert`:`status`,children:[q||`\xA0`,S===`error`&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{C(`saving`)},children:i(`common.retry`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void U(),children:i(`usage.companion.reset`)}),(0,Q.jsx)(`p`,{className:`muted text-caption`,children:i(`usage.companion.footer`)})]})}function oD({apiBase:e,providers:t}){let[n,r]=(0,Z.useState)([]);return(0,Z.useEffect)(()=>{if(t.length>0)return;let n=new AbortController;return fetch(`${e}/api/config`,{signal:n.signal}).then(e=>vn(e)).then(e=>{n.signal.aborted||r(Object.keys(e?.providers??{}).map(e=>({provider:e})))}).catch(()=>{}),()=>n.abort()},[e,t.length]),(0,Q.jsx)(aD,{apiBase:e,providers:t.length>0?t:n})}function sD(){return window.location.hash.replace(/^#\/?/,``)===`usage/companion`?`companion`:`report`}function cD(e){window.location.hash=e===`report`?`usage`:`usage/companion`}function lD(e){if(e.key===`ArrowLeft`||e.key===`Home`||e.key===`ArrowRight`||e.key===`End`){e.preventDefault();let t=e.key===`ArrowLeft`||e.key===`Home`?`report`:`companion`;cD(t),document.getElementById(`usage-tab-${t}`)?.focus()}}var uD=class extends Error{};function dD(e){return`${Math.round(e*100)}%`}function fD({row:e,locale:t,t:n}){if(e.estimatedCostUsd===void 0&&e.pricedRequests===void 0&&e.unpricedRequests===void 0)return(0,Q.jsx)(`span`,{className:`muted`,children:`—`});let r=e.unpricedRequests??0,i=n(r===1?`usage.cost.excludedOne`:`usage.cost.excluded`,{count:r});return e.estimatedCostUsd===void 0?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:`—`}),r>0&&(0,Q.jsxs)(`span`,{className:`muted text-caption usage-cost-note`,children:[` `,i]})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`mono`,children:qd(e.estimatedCostUsd??0,t)}),r>0&&(0,Q.jsxs)(`span`,{className:`muted text-caption usage-cost-note`,children:[` `,i]})]})}function pD(e,t,n){return typeof e==`number`&&Number.isFinite(e)&&e>=0?q(e,t):n}function mD(e,t){return typeof e==`number`&&Number.isFinite(e)?dD(e):t}function hD(e,t,n){if(typeof e.cacheHitRate!=`number`||!Number.isFinite(e.cacheHitRate))return n(`usage.cacheHitRate.unmeasured`);let r=e.cacheObservedInputTokens;if(!(typeof r!=`number`||!Number.isFinite(r)||r>=e.inputTokens))return n(`usage.cacheHitRate.partial`,{measured:q(r,t),total:q(e.inputTokens,t)})}function gD(e){return typeof e==`number`&&Number.isFinite(e)&&e>0}function _D(e,t){return gD(e.throughputTokensPerSec)?t(`usage.throughput.title`,{samples:e.throughputSamples??0}):t(`usage.throughput.unmeasured`)}function vD(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 yD(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 bD(e,t){return new Intl.DateTimeFormat(t,{dateStyle:`medium`}).format(new Date(`${e}T12:00:00`))}function xD(e){let t=window.innerWidth,n=window.innerHeight,r=Math.min(240,Math.max(0,t-16));return{left:Math.max(8,Math.min(e.left+e.width/2-r/2,t-8-r)),maxWidth:r,...e.top-8>n-e.bottom-8?(()=>{let t=Math.max(8,Math.min(n-8,n-e.top+8));return{bottom:t,maxHeight:Math.max(0,n-t-8)}})():(()=>{let t=Math.max(8,Math.min(n-8,e.bottom+8));return{top:t,maxHeight:Math.max(0,n-t-8)}})()}}function SD({anchor:e,className:t,children:n}){return(0,Zt.createPortal)((0,Q.jsx)(`div`,{className:`${t} chart-overlay`,role:`tooltip`,style:xD(e),children:n}),document.body)}function CD(e,t,n){return n(`usage.chart.dayDetail`,{date:bD(e.date,t),requests:e.requests,tokens:q(e.totalTokens,t)})}function wD(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 TD(e,t){return e<=0?0:e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4}function ED(e,t=!1){let n=wD(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:TD(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?TD(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 DD({surface:e,range:t,onSurface:n,onRange:r,t:i}){return(0,Q.jsxs)(`div`,{className:`usage-filters`,children:[(0,Q.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,Q.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,Q.jsx)(`img`,{className:`usage-source-mark`,src:`/provider-icons/openai.svg`,alt:``,"aria-hidden":`true`}),t===`claude`&&(0,Q.jsx)(`img`,{className:`usage-source-mark`,src:`/provider-icons/claude-color.svg`,alt:``,"aria-hidden":`true`}),t===`grok`&&(0,Q.jsx)(`img`,{className:`usage-source-mark usage-source-mark--mono`,src:`/provider-icons/grok.svg`,alt:``,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:t===`all`?`usage-source-label`:`usage-source-label usage-source-label-collapsible`,children:r})]},t)})}),(0,Q.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,Q.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 OD({summary:e,activeDays:t,locale:n,t:r}){return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`usage-cards usage-cards-3x2`,role:`group`,"aria-label":r(`usage.title`),children:[(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`muted`,children:r(`usage.card.requests`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:e.requests})]}),(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`muted`,children:r(`usage.card.measured`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:e.measuredRequests})]}),(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`muted`,children:r(`usage.card.totalTokens`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:q(e.totalTokens,n)})]}),(0,Q.jsxs)(`div`,{className:`stat`,title:r(`usage.card.cachedTokensHint`),children:[(0,Q.jsx)(`div`,{className:`muted`,children:r(`usage.card.cachedTokens`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:q(e.cacheReadInputTokens??e.cachedInputTokens,n)}),(e.cacheCreationInputTokens??0)>0&&(0,Q.jsxs)(`div`,{className:`muted text-caption`,children:[r(`usage.card.cacheWriteTokens`),`: `,q(e.cacheCreationInputTokens??0,n)]})]}),(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`muted`,children:r(`usage.card.coverage`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:dD(e.coverageRatio)})]}),(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`muted`,children:r(`usage.card.activeDays`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:t})]})]}),(0,Q.jsxs)(`div`,{className:`usage-cost-row`,role:`note`,title:_D(e,r),children:[(0,Q.jsx)(`span`,{className:`muted`,children:r(`usage.col.tokPerSec`)}),(0,Q.jsx)(`span`,{className:`stat-value mono usage-cost-value`,children:gD(e.throughputTokensPerSec)?e.throughputTokensPerSec.toFixed(1):r(`usage.unavailable`)}),(0,Q.jsx)(`span`,{className:`muted text-caption`,children:_D(e,r)})]}),e.estimatedCostUsd!==void 0&&(0,Q.jsxs)(`div`,{className:`usage-cost-row`,role:`note`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:r(`usage.cost.total`)}),(0,Q.jsx)(`span`,{className:`stat-value mono usage-cost-value`,children:qd(e.estimatedCostUsd,n)}),(0,Q.jsx)(`span`,{className:`muted text-caption`,children:r(`usage.cost.disclaimer`)}),(e.unpricedRequests??0)+(e.unmeteredRequests??0)>0&&(0,Q.jsx)(`span`,{className:`muted text-caption`,children:r(`usage.cost.unpricedNote`).replace(`{count}`,String((e.unpricedRequests??0)+(e.unmeteredRequests??0)))})]})]})}function kD({weekBars:e,locale:t,t:n}){let[r,i]=(0,Z.useState)(null),a=Math.max(1,...e.map(e=>e.totalTokens)),o=e.find(e=>e.date===r?.date),s=(e,t)=>{i({date:e.date,anchor:t.getBoundingClientRect()})};return(0,Q.jsxs)(`div`,{className:`daybars`,role:`group`,"aria-label":n(`usage.section.heatmap`),children:[e.map(e=>{let r=Math.round(e.totalTokens/a*100),o=new Intl.DateTimeFormat(t,{weekday:`short`}).format(new Date(`${e.date}T12:00:00`));return(0,Q.jsxs)(`button`,{type:`button`,className:`daybar`,"aria-label":CD(e,t,n),onFocus:t=>s(e,t.currentTarget),onBlur:()=>i(t=>t?.date===e.date?null:t),onPointerEnter:t=>s(e,t.currentTarget),onPointerDown:t=>s(e,t.currentTarget),onPointerLeave:t=>{t.pointerType!==`touch`&&document.activeElement!==t.currentTarget&&i(t=>t?.date===e.date?null:t)},children:[(0,Q.jsx)(`div`,{className:`daybar-track`,children:(0,Q.jsxs)(`div`,{className:`daybar-stack`,style:{"--daybar-scale":String(Math.max(0,Math.min(1,r/100)))},children:[e.models.map(e=>(0,Q.jsx)(`div`,{className:`daybar-seg`,style:{flexGrow:e.totalTokens,background:vD(e.model,e.provider)}},`${e.provider}/${e.model}`)),e.models.length===0&&e.totalTokens>0&&(0,Q.jsx)(`div`,{className:`daybar-seg`,style:{flexGrow:1,background:`var(--green)`}})]})}),(0,Q.jsx)(`span`,{className:`daybar-count`,children:q(e.totalTokens,t)}),(0,Q.jsx)(`span`,{className:`daybar-label muted`,children:o})]},e.date)}),r&&o&&(0,Q.jsxs)(SD,{className:`daybar-tip`,anchor:r.anchor,children:[(0,Q.jsx)(`div`,{className:`daybar-tip-date`,children:bD(o.date,t)}),(0,Q.jsxs)(`div`,{className:`daybar-tip-row`,children:[(0,Q.jsx)(`span`,{children:n(`usage.heatmap.tooltipRequests`,{requests:o.requests})}),(0,Q.jsx)(`span`,{className:`daybar-tip-val`,children:n(`usage.heatmap.tooltipTokens`,{tokens:q(o.totalTokens,t)})})]}),o.models.slice(0,8).map(e=>(0,Q.jsxs)(`div`,{className:`daybar-tip-row`,children:[(0,Q.jsx)(`span`,{className:`daybar-tip-swatch`,style:{background:vD(e.model,e.provider)}}),(0,Q.jsx)(`span`,{className:`daybar-tip-name`,children:zv(e.model)}),(0,Q.jsx)(`span`,{className:`daybar-tip-val`,children:q(e.totalTokens,t)})]},`${e.provider}/${e.model}`))]})]})}function AD({range:e,heatmap:t,weekBars:n,locale:r,t:i}){let a=(0,Z.useRef)(null),o=(0,Z.useMemo)(()=>t.weeks.flat().filter(e=>e.date),[t]),[s,c]=(0,Z.useState)(()=>o.at(-1)?.date??``),[l,u]=(0,Z.useState)(null),d=(0,Z.useId)(),f=o.some(e=>e.date===s)?s:o.at(-1)?.date??``,p=(e,t)=>{c(e.date),u({date:e.date,anchor:t.getBoundingClientRect()})},m=(e,t)=>{let n=o.findIndex(e=>e.date===t.date),r=e.key===`ArrowUp`?-1:e.key===`ArrowDown`?1:e.key===`ArrowLeft`?-7:e.key===`ArrowRight`?7:0;if(!r||n<0)return;e.preventDefault();let i=o[Math.max(0,Math.min(o.length-1,n+r))];c(i.date);let s=a.current?.querySelector(`[data-date="${i.date}"]`);s&&(s.focus(),u({date:i.date,anchor:s.getBoundingClientRect()}))};return(0,Z.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,Q.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":`usage-heatmap-title`,children:[(0,Q.jsx)(`h3`,{id:`usage-heatmap-title`,className:`panel-title`,children:i(`usage.section.heatmap`)}),e===`7d`?(0,Q.jsx)(kD,{weekBars:n,locale:r,t:i}):(0,Q.jsxs)(`div`,{className:`heatmap`,ref:a,children:[(0,Q.jsxs)(`div`,{className:`heatmap-months`,style:{gridTemplateColumns:`28px repeat(${t.weeks.length}, calc(var(--hm-cell) + var(--hm-gap)))`},children:[(0,Q.jsx)(`span`,{className:`heatmap-day-spacer`}),t.months.map(e=>(0,Q.jsx)(`span`,{className:`heatmap-month`,style:{gridColumn:e.col+2},children:e.label},`${e.label}-${e.col}`))]}),(0,Q.jsxs)(`div`,{className:`heatmap-body`,children:[(0,Q.jsxs)(`div`,{className:`heatmap-days`,children:[(0,Q.jsx)(`span`,{}),(0,Q.jsx)(`span`,{children:i(`usage.dayMon`)}),(0,Q.jsx)(`span`,{}),(0,Q.jsx)(`span`,{children:i(`usage.dayWed`)}),(0,Q.jsx)(`span`,{}),(0,Q.jsx)(`span`,{children:i(`usage.dayFri`)}),(0,Q.jsx)(`span`,{})]}),(0,Q.jsx)(`div`,{className:`heatmap-grid`,role:`group`,"aria-labelledby":`usage-heatmap-title`,"aria-describedby":d,style:{gridTemplateColumns:`repeat(${t.weeks.length}, var(--hm-cell))`},children:t.weeks.map((e,t)=>(0,Q.jsx)(`div`,{className:`heatmap-week`,children:e.map((e,n)=>e.date?(0,Q.jsx)(`button`,{type:`button`,className:`heatmap-cell heatmap-cell-${e.level}`,"data-date":e.date,tabIndex:f===e.date?0:-1,"aria-label":CD(e,r,i),onFocus:t=>p(e,t.currentTarget),onBlur:()=>u(t=>t?.date===e.date?null:t),onKeyDown:t=>m(t,e),onPointerEnter:t=>p(e,t.currentTarget),onPointerDown:t=>p(e,t.currentTarget),onPointerLeave:t=>{t.pointerType!==`touch`&&document.activeElement!==t.currentTarget&&u(t=>t?.date===e.date?null:t)}},e.date):(0,Q.jsx)(`span`,{className:`heatmap-cell heatmap-cell-0`,"aria-hidden":`true`},`pad-${t}-${n}`))},e[0]?.date||`week-${t}`))})]}),(0,Q.jsx)(`span`,{id:d,className:`sr-only`,children:i(`usage.heatmap.keyboardLabel`)}),(0,Q.jsx)(`span`,{className:`sr-only`,"aria-live":`polite`,children:o.find(e=>e.date===f)?CD(o.find(e=>e.date===f),r,i):``}),l&&(()=>{let e=o.find(e=>e.date===l.date);return e?.date?(0,Q.jsxs)(SD,{className:`heatmap-tip`,anchor:l.anchor,children:[(0,Q.jsx)(`div`,{className:`heatmap-tip-date`,children:bD(e.date,r)}),(0,Q.jsx)(`div`,{className:`heatmap-tip-val`,children:i(`usage.heatmap.tooltipTokens`,{tokens:q(e.totalTokens,r)})}),(0,Q.jsx)(`div`,{className:`heatmap-tip-req muted`,children:i(`usage.heatmap.tooltipRequests`,{requests:e.requests})})]}):null})(),(0,Q.jsxs)(`div`,{className:`heatmap-legend muted`,children:[(0,Q.jsx)(`span`,{children:i(`usage.heatmap.less`)}),[0,1,2,3,4].map(e=>(0,Q.jsx)(`span`,{className:`heatmap-cell heatmap-cell-${e}`},e)),(0,Q.jsx)(`span`,{children:i(`usage.heatmap.more`)})]})]})]})}function jD({title:e,titleId:t,children:n}){return(0,Q.jsxs)(`section`,{className:`usw-section`,"aria-labelledby":t,children:[(0,Q.jsx)(`h3`,{id:t,className:`h-section`,children:e}),n]})}function MD({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=`usage-models-list-price-disclaimer`,u=i(`usage.unavailable`),d=(0,Q.jsx)(`input`,{className:`input`,"aria-label":o,placeholder:o,value:t,onChange:e=>n(e.target.value)}),f=(0,Q.jsxs)(`div`,{className:`tbl-wrap`,children:[(0,Q.jsxs)(`table`,{className:`tbl usage-models-tbl`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:i(`logs.col.model`)}),(0,Q.jsx)(`th`,{children:i(`logs.col.provider`)}),(0,Q.jsx)(`th`,{children:i(`usage.col.share`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`usage.col.tokens`)}),(0,Q.jsx)(`th`,{className:`num`,"aria-describedby":l,children:i(`usage.col.apiListPrice`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`usage.col.requests`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`usage.col.measured`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`usage.col.inputTokens`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`usage.col.outputTokens`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`usage.col.tokPerSec`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`usage.col.cacheHits`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`usage.col.cacheWrites`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`usage.col.cacheHitRate`)})]})}),(0,Q.jsx)(`tbody`,{children:e.map(e=>{let t=Ce(e.provider,i),n=hD(e,r,i),a=_D(e,i);return(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`mono`,title:e.model,children:zv(e.model)}),(0,Q.jsx)(`td`,{className:`muted`,title:t,children:t}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`div`,{className:`usage-bar`,children:(0,Q.jsx)(`div`,{className:`usage-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})}),(0,Q.jsx)(`td`,{className:`num mono`,children:q(e.totalTokens,r)}),(0,Q.jsx)(`td`,{className:`num`,children:(0,Q.jsx)(fD,{row:e,locale:r,t:i})}),(0,Q.jsx)(`td`,{className:`num`,children:e.requests}),(0,Q.jsx)(`td`,{className:`num`,children:e.measuredRequests}),(0,Q.jsx)(`td`,{className:`num mono`,children:q(e.inputTokens,r)}),(0,Q.jsx)(`td`,{className:`num mono`,children:q(e.outputTokens,r)}),(0,Q.jsxs)(`td`,{className:`num mono`,title:a,children:[(0,Q.jsx)(`span`,{className:`usage-hit-rate`,children:gD(e.throughputTokensPerSec)?`${e.throughputTokensPerSec.toFixed(1)} tok/s`:u}),gD(e.throughputTokensPerSec)&&(0,Q.jsx)(`span`,{className:`sr-only`,children:a})]}),(0,Q.jsx)(`td`,{className:`num mono`,children:pD(e.cacheReadInputTokens??e.cachedInputTokens,r,u)}),(0,Q.jsx)(`td`,{className:`num mono`,children:pD(e.cacheCreationInputTokens,r,u)}),(0,Q.jsxs)(`td`,{className:`num mono`,title:n,children:[(0,Q.jsx)(`span`,{className:`usage-hit-rate`,children:mD(e.cacheHitRate,u)}),n!==void 0&&(0,Q.jsx)(`span`,{className:`sr-only`,children:n})]})]},`${e.provider}/${e.model}`)})})]}),(0,Q.jsx)(`p`,{id:l,className:`muted text-caption`,children:i(`usage.cost.disclaimer`)})]});return a?(0,Q.jsxs)(jD,{title:s,titleId:c,children:[(0,Q.jsx)(`div`,{className:`usw-section-toolbar`,children:d}),f]}):(0,Q.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":c,children:[(0,Q.jsxs)(`div`,{className:`panel-head`,children:[(0,Q.jsx)(`h3`,{id:c,className:`panel-title`,children:s}),d]}),f]})}function ND({providers:e,locale:t,t:n,workspace:r=!1}){let i=n(`usage.unavailable`),a=n(`usage.section.providers`),o=`usage-providers-title`,s=`usage-providers-list-price-disclaimer`,c=(0,Q.jsxs)(`div`,{className:`tbl-wrap`,children:[(0,Q.jsxs)(`table`,{className:`tbl`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:n(`logs.col.provider`)}),(0,Q.jsx)(`th`,{className:`num`,children:n(`usage.col.requests`)}),(0,Q.jsx)(`th`,{className:`num`,children:n(`usage.col.measured`)}),(0,Q.jsx)(`th`,{className:`num`,children:n(`usage.col.tokens`)}),(0,Q.jsx)(`th`,{className:`num`,children:n(`usage.col.tokPerSec`)}),(0,Q.jsx)(`th`,{className:`num`,"aria-describedby":s,children:n(`usage.col.apiListPrice`)}),(0,Q.jsx)(`th`,{children:n(`usage.col.share`)})]})}),(0,Q.jsx)(`tbody`,{children:e.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`mono`,children:Ce(e.provider,n)}),(0,Q.jsx)(`td`,{className:`num`,children:e.requests}),(0,Q.jsx)(`td`,{className:`num`,children:e.measuredRequests}),(0,Q.jsx)(`td`,{className:`num mono`,children:q(e.totalTokens,t)}),(0,Q.jsxs)(`td`,{className:`num mono`,title:_D(e,n),children:[(0,Q.jsx)(`span`,{className:`usage-hit-rate`,children:gD(e.throughputTokensPerSec)?`${e.throughputTokensPerSec.toFixed(1)} tok/s`:i}),gD(e.throughputTokensPerSec)&&(0,Q.jsx)(`span`,{className:`sr-only`,children:_D(e,n)})]}),(0,Q.jsx)(`td`,{className:`num`,children:(0,Q.jsx)(fD,{row:e,locale:t,t:n})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`div`,{className:`usage-bar`,children:(0,Q.jsx)(`div`,{className:`usage-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})})]},e.provider))})]}),(0,Q.jsx)(`p`,{id:s,className:`muted text-caption`,children:n(`usage.cost.disclaimer`)})]});return r?(0,Q.jsx)(jD,{title:a,titleId:o,children:c}):(0,Q.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":o,children:[(0,Q.jsx)(`h3`,{id:o,className:`panel-title`,children:a}),c]})}function PD({summary:e,t,workspace:n=!1}){let r=t(`usage.section.coverage`),i=`usage-coverage-title`,a=(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`usage-cards usage-cards-3x2`,children:[(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.measured`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:e.measuredRequests})]}),(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.reported`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:e.reportedRequests})]}),(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.estimated`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:e.estimatedRequests})]}),(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`muted`,children:t(`logs.tokens.unreported`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:e.unreportedRequests})]}),(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`muted`,children:t(`logs.tokens.unsupported`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:e.unsupportedRequests})]})]}),(0,Q.jsx)(`p`,{className:`muted text-control`,style:{marginTop:12},children:t(`usage.coverage.note`)})]});return n?(0,Q.jsx)(jD,{title:r,titleId:i,children:a}):(0,Q.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":i,children:[(0,Q.jsx)(`h3`,{id:i,className:`panel-title`,children:r}),a]})}function FD({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,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(OD,{summary:e.summary,activeDays:r,locale:l,t:u}),(0,Q.jsx)(AD,{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,Q.jsx)(MD,{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,Q.jsx)(ND,{providers:s,locale:l,t:u,workspace:!0}):null},{id:`coverage`,label:u(`usage.section.coverage`),meta:e?dD(e.summary.coverageRatio):`—`,body:e?(0,Q.jsx)(PD,{summary:e.summary,t:u,workspace:!0}):null}];return(0,Q.jsx)(`div`,{className:`usage-workspace-shell`,children:(0,Q.jsxs)(`div`,{className:`usage-workspace-root`,children:[(0,Q.jsx)(uw,{scope:`usage`,ariaLabel:u(`usage.workspace.sections`),items:f.map(e=>({id:e.id,label:e.label,meta:e.meta}))}),(0,Q.jsx)(`section`,{className:`usage-workspace-main`,"aria-label":u(`usage.workspace.report`),children:d?(0,Q.jsx)(fn,{title:u(`usage.empty`)}):f.map(e=>(0,Q.jsx)(`div`,{id:sw(`usage`,e.id),className:`usw-body usw-section-block`,children:e.body},e.id))})]})})}var ID=new Map;function LD(e,t,n,r,i,a){return`ocx.usage.v2:${e}:${r?`connected`:`standalone`}:${i}:${a??``}:${t}:${n}`}function RD(e,t,n,r,i,a){let o=LD(e,t,n,r,i,a);return ID.get(o)??io(o)}function zD(e,t,n,r,i,a,o){let s=LD(e,t,n,r,i,a);ID.set(s,o),co(s,o)}function BD({apiBase:e,connected:t=!1,apiKeyId:n}){let{t:i,locale:a}=r(),[o,s]=(0,Z.useState)(sD);(0,Z.useEffect)(()=>{let e=()=>s(sD());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]);let[c,l]=(0,Z.useState)(`30d`),[u,d]=(0,Z.useState)(`all`),[f,p]=(0,Z.useState)(`machine`),[m,h]=(0,Z.useState)(``),[g,_]=(0,Z.useState)({since:``,until:``}),[v,y]=(0,Z.useState)(null),[b,x]=(0,Z.useState)(null),[S,C]=(0,Z.useState)(!1),w=v?.since,T=v?.until,E=()=>{y(null),_({since:``,until:``}),x(null)},D=e=>{l(e),E()},O=(0,Z.useCallback)(async r=>{let i=new URLSearchParams({range:c,surface:u});t&&f===`machine`&&n&&i.set(`apiKeyId`,n),w!==void 0&&T!==void 0&&(i.set(`since`,String(w)),i.set(`until`,String(T)));let a=await br(await fetch(`${e}/api/usage?${i}`,{signal:r}));if(w!==void 0&&(a?.customWindow!==!0||a.since!==w||a.until!==T))throw new uD;return w===void 0&&zD(e,c,u,t,f,n,a),a},[e,n,t,c,f,u,w,T]),k=LD(e,c,u,t,f,n),A=v?JSON.stringify([k,w,T]):k,j=v?null:RD(e,c,u,t,f,n),M=uo(A,[e,n,t,c,f,u,w,T],O,{isEmpty:()=>!1,initialData:j??void 0}),{state:N}=M,P=N.data??j??null,F=(0,Z.useMemo)(()=>ED(P?.days??[],!!v),[P?.days,v]),I=(0,Z.useMemo)(()=>yD(P?.days??[]),[P?.days]),L=(0,Z.useMemo)(()=>(P?.days??[]).filter(e=>e.requests>0).length,[P?.days]),R=(0,Z.useMemo)(()=>{let e=m.trim().toLowerCase(),t=(P?.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)},[P?.models,m]),z=(0,Z.useMemo)(()=>(P?.providers??[]).toSorted((e,t)=>t.totalTokens-e.totalTokens),[P?.providers]);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`page-head usage-head`,children:[(0,Q.jsx)(`h2`,{id:`usage-page-title`,children:i(`usage.title`)}),o===`report`&&(0,Q.jsx)(DD,{surface:u,range:v?null:c,onSurface:d,onRange:D,t:i})]}),(0,Q.jsx)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":i(`nav.usage`),children:[`report`,`companion`].map(e=>(0,Q.jsx)(`button`,{type:`button`,role:`tab`,id:`usage-tab-${e}`,"aria-selected":o===e,"aria-controls":`usage-panel-${e}`,tabIndex:o===e?0:-1,className:`page-tab${o===e?` page-tab--active`:``}`,onClick:()=>cD(e),onKeyDown:lD,children:i(e===`report`?`usage.workspace.report`:`usage.section.companion`)},e))}),o===`companion`?(0,Q.jsx)(`div`,{role:`tabpanel`,id:`usage-panel-companion`,"aria-labelledby":`usage-tab-companion`,children:(0,Q.jsx)(oD,{apiBase:e,providers:P?.providers??[]})}):(0,Q.jsxs)(`div`,{role:`tabpanel`,id:`usage-panel-report`,"aria-labelledby":`usage-tab-report`,children:[(0,Q.jsx)(`p`,{className:`page-sub`,children:i(`usage.subtitle`)}),(0,Q.jsxs)(`section`,{className:`usage-range`,children:[(0,Q.jsxs)(`div`,{className:`usage-range-bar`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`usage-range-toggle${v?` is-active`:``}`,"aria-expanded":S,"aria-controls":S?`usage-range-panel`:void 0,onClick:()=>{S&&x(null),C(!S)},children:[(0,Q.jsx)(`span`,{children:i(`usage.range.custom`)}),(0,Q.jsx)(Ye,{width:12,height:12,"aria-hidden":`true`,className:`usage-range-chevron`})]}),v&&(0,Q.jsx)(`p`,{className:`usage-range-applied muted text-control`,role:`status`,children:(()=>{let e=new Intl.DateTimeFormat(a,{year:`numeric`,month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,fractionalSecondDigits:3,timeZoneName:`short`});return i(`usage.range.applied`,{start:e.format(v.since),end:e.format(v.until)})})()})]}),S&&(0,Q.jsxs)(`form`,{id:`usage-range-panel`,className:`usage-range-panel`,"aria-label":i(`usage.range.custom`),noValidate:!0,onSubmit:e=>{e.preventDefault();let t=zE(g.since,g.until);t.ok===!1?x(t.error):(x(null),y(t.window))},children:[(0,Q.jsxs)(`div`,{className:`usage-range-fields`,children:[(0,Q.jsxs)(`label`,{className:`usage-range-field`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:i(`usage.range.start`)}),(0,Q.jsx)(`input`,{className:`input`,type:`datetime-local`,step:`60`,required:!0,value:g.since,"aria-invalid":b!==null,"aria-describedby":b?`usage-range-help usage-range-error`:`usage-range-help`,onChange:e=>{let t=e.currentTarget.value;_(e=>({...e,since:t})),x(null)}})]}),(0,Q.jsxs)(`label`,{className:`usage-range-field`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:i(`usage.range.end`)}),(0,Q.jsx)(`input`,{className:`input`,type:`datetime-local`,step:`60`,required:!0,value:g.until,"aria-invalid":b!==null,"aria-describedby":b?`usage-range-help usage-range-error`:`usage-range-help`,onChange:e=>{let t=e.currentTarget.value;_(e=>({...e,until:t})),x(null)}})]}),(0,Q.jsx)(`button`,{type:`submit`,className:`btn btn-primary btn-sm usage-range-action`,children:i(`usage.range.apply`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm usage-range-action`,onClick:E,children:i(`usage.range.clear`)})]}),(0,Q.jsx)(`p`,{id:`usage-range-help`,className:`muted text-caption`,children:i(`usage.range.help`)}),b&&(0,Q.jsx)(`p`,{id:`usage-range-error`,role:`alert`,className:`notice notice-err`,children:i(`usage.range.${b}`)})]})]}),t&&(0,Q.jsxs)(`div`,{className:`usage-source-row`,children:[(0,Q.jsx)(`span`,{children:i(`usage.source.connected`)}),(0,Q.jsxs)(`div`,{className:`usage-scope-control`,role:`group`,"aria-label":i(`usage.scope.label`),children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm${f===`machine`?` btn-primary`:` btn-ghost`}`,"aria-pressed":f===`machine`,onClick:()=>p(`machine`),children:i(`usage.scope.machine`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm${f===`hub`?` btn-primary`:` btn-ghost`}`,"aria-pressed":f===`hub`,onClick:()=>p(`hub`),children:i(`usage.scope.hub`)})]})]}),N.showSkeleton&&!P?(0,Q.jsx)(lb,{label:i(`usage.loading`),rows:5}):N.kind===`failed-cold`?(0,Q.jsxs)($,{tone:`err`,children:[N.error instanceof uD?`${i(`usage.loadError`)} ${i(`dash.codexRestartMalformed`)}`:N.error instanceof yr?i(`usage.loadError`):t?i(`usage.hubOffline`):N.error instanceof Error?`${i(`usage.loadError`)} ${N.error.message}`:i(`usage.loadError`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>M.refresh(),children:i(`common.retry`)})]}):(0,Q.jsxs)(Q.Fragment,{children:[N.showError&&(0,Q.jsx)($,{tone:`err`,children:i(t&&!(N.error instanceof yr)?`usage.hubOffline`:`usage.loadError`)}),(0,Q.jsx)(Sr,{data:P}),P?.historyTruncated&&(0,Q.jsx)($,{tone:`warn`,children:(()=>{let e=VD(P.snapshotWindowStart),t=VD(P.snapshotWindowEnd);return e!==null&&t!==null?i(`usage.historyTruncatedWindow`,{start:e,end:t}):i(`usage.historyTruncated`)})()}),(0,Q.jsx)(FD,{data:P,heatmap:F,weekBars:I,activeDays:L,filteredModels:R,modelQuery:m,onModelQuery:h,sortedProviders:z,range:v?null:c,locale:a,t:i})]})]})]})}function VD(e){if(typeof e!=`number`||!Number.isFinite(e))return null;let t=new Date(e);return Number.isFinite(t.getTime())?t.toLocaleString():null}function HD(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 UD={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.`},vi:{compact:`Nén`,compactComplete:`Hoàn tất nén (logic / thu hồi trên đĩa)`,pagesUnit:`trang`,compactPartial:`Nén một phần (logic / thu hồi trên đĩa)`,confirmCompact:`Xác nhận nén`,cancel:`Hủy`,inspectionOnly:`Chỉ kiểm tra`,externalSqliteHome:`Lưu trữ SQLite bên ngoài`,inspectionUnavailable:`Tính năng kiểm tra nhật ký chẩn đoán không khả dụng.`,metricsSkippedLarge:`Đã bỏ qua số liệu hàng: cơ sở dữ liệu lớn hơn {threshold} và việc quét sẽ làm treo proxy.`,protection:`Bảo vệ`,compat:`Tương thích`,quiet:`Yên tĩnh`,disable:`Tắt bảo vệ`,repair:`Sửa chữa bảo vệ`,applying:`Đang áp dụng bảo vệ…`,"error.generic":`Không thể thay đổi bảo vệ nhật ký Codex.`,"error.codex_running":`Hãy thoát Codex trước khi thay đổi bảo vệ nhật ký.`,"error.process_enumeration_failed":`Không thể xác minh rằng Codex đã dừng. Bảo vệ chưa được thay đổi.`,"error.busy":`Cơ sở dữ liệu nhật ký Codex đang bận. Hãy thoát Codex và thử lại.`,"error.unsupported_schema":`Lược đồ nhật ký Codex này không được hỗ trợ để bảo vệ.`,"error.trigger_collision":`Tên trình kích hoạt Log Guard dành riêng đã được sử dụng. Bảo vệ chưa được thay đổi.`,"error.unsafe_path":`Đường dẫn cơ sở dữ liệu nhật ký Codex không vượt qua được kiểm tra an toàn.`,"error.database_error":`Không thể cập nhật cơ sở dữ liệu nhật ký Codex.`,"error.config_write_failed":`Cơ sở dữ liệu đã thay đổi nhưng OpenCodex không thể lưu cài đặt bảo vệ. Vui lòng sửa lỗi lưu trữ cấu hình, sau đó chạy Sửa chữa.`},pt:{compact:`Compactar`,compactComplete:`Compactação concluída (lógico / recuperado em disco)`,pagesUnit:`páginas`,compactPartial:`Compactação parcial (lógico / recuperado em disco)`,confirmCompact:`Confirmar compactação`,cancel:`Cancelar`,inspectionOnly:`Somente inspeção`,externalSqliteHome:`Armazenamento SQLite externo`,inspectionUnavailable:`A inspeção do log de diagnóstico não está disponível.`,metricsSkippedLarge:`Métricas de linhas ignoradas: o banco de dados excede {threshold} e a varredura travaria o proxy.`,protection:`Proteção`,compat:`Compatibilidade`,quiet:`Silencioso`,disable:`Desativar proteção`,repair:`Reparar proteção`,applying:`Aplicando proteção…`,"error.generic":`Não foi possível alterar a proteção de logs do Codex.`,"error.codex_running":`Feche o Codex antes de alterar a proteção de logs.`,"error.process_enumeration_failed":`Não foi possível verificar se o Codex está parado. A proteção não foi alterada.`,"error.busy":`O banco de dados de logs do Codex está ocupado. Feche o Codex e tente novamente.`,"error.unsupported_schema":`Este esquema de logs do Codex não é suportado para proteção.`,"error.trigger_collision":`Um nome de trigger reservado do Log Guard já está em uso. A proteção não foi alterada.`,"error.unsafe_path":`O caminho do banco de dados de logs do Codex falhou na verificação de segurança.`,"error.database_error":`Não foi possível atualizar o banco de dados de logs do Codex.`,"error.config_write_failed":`O banco de dados foi alterado, mas o OpenCodex não conseguiu salvar a configuração de proteção. Corrija o armazenamento de configuração e execute Reparar.`}};function WD(e,t){return UD[e][t]}var GD={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.`},vi:{applying:`Đang áp dụng thay đổi Log Guard…`,"error.generic":`Không thể cập nhật lưu trữ nhật ký Codex.`,"error.codex_running":`Hãy thoát Codex trước khi thay đổi lưu trữ nhật ký Codex.`,"error.process_enumeration_failed":`Không thể xác minh rằng Codex đã dừng. Thao tác Log Guard chưa được bắt đầu.`,"error.busy":`Cơ sở dữ liệu nhật ký Codex đang bận. Hãy thoát Codex và thử lại.`,"error.unsupported_schema":`Lược đồ nhật ký Codex này không được hỗ trợ cho thao tác này.`,"error.unsafe_path":`Đường dẫn cơ sở dữ liệu nhật ký Codex không vượt qua được kiểm tra an toàn.`,"error.database_error":`Không thể cập nhật cơ sở dữ liệu nhật ký Codex.`,"error.auto_vacuum_not_incremental":`Cơ sở dữ liệu nhật ký Codex này không được định cấu hình cho tính năng incremental vacuum, do đó không thể thu hồi dung lượng nếu không xây dựng lại hoàn toàn.`,"error.integrity_check_failed":`Cơ sở dữ liệu nhật ký Codex không vượt qua được kiểm tra tính toàn vẹn. Không có dung lượng nào được thu hồi.`},pt:{applying:`Aplicando alteração do Log Guard…`,"error.generic":`Não foi possível atualizar o armazenamento de logs do Codex.`,"error.codex_running":`Feche o Codex antes de alterar o armazenamento de logs do Codex.`,"error.process_enumeration_failed":`Não foi possível verificar se o Codex está parado. A operação do Log Guard não foi iniciada.`,"error.busy":`O banco de dados de logs do Codex está ocupado. Feche o Codex e tente novamente.`,"error.unsupported_schema":`Este esquema de logs do Codex não é suportado para esta operação.`,"error.unsafe_path":`O caminho do banco de dados de logs do Codex falhou na verificação de segurança.`,"error.database_error":`Não foi possível atualizar o banco de dados de logs do Codex.`,"error.auto_vacuum_not_incremental":`Este banco de dados de logs do Codex não está configurado para incremental vacuum; por isso, não é possível recuperar espaço sem uma reconstrução completa.`,"error.integrity_check_failed":`O banco de dados de logs do Codex falhou na verificação de integridade. Nenhum espaço foi recuperado.`}};function KD(e,t){return GD[e][t]}var qD={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`}},vi:{schema:{compatible:`Tương thích`,missing:`Không tìm thấy cơ sở dữ liệu`,unreadable:`Cơ sở dữ liệu không khả dụng`,unsupported:`Không được hỗ trợ`},protection:{off:`Tắt`,active:`Đang hoạt động`,drifted:`Cần sửa chữa`,unsupported:`Không được hỗ trợ`,unknown:`Không xác định`},mode:{off:`Tắt`,compat:`Tương thích`,quiet:`Yên tĩnh`,collision:`Không xác định`}},pt:{schema:{compatible:`Compatível`,missing:`Banco de dados não encontrado`,unreadable:`Banco de dados indisponível`,unsupported:`Não suportado`},protection:{off:`Desativada`,active:`Ativa`,drifted:`Requer reparo`,unsupported:`Não suportada`,unknown:`Desconhecida`},mode:{off:`Desativado`,compat:`Compatibilidade`,quiet:`Silencioso`,collision:`Desconhecido`}}};function JD(e,t){return qD[e].schema[t]}function YD(e,t){return qD[e].protection[t]}function XD(e,t){return qD[e].mode[t]}var ZD={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 QD(e,t){let n=ZD[e.key];return n?t(n):e.label}function $D(e,t){return e===void 0?`—`:new Date(e).toLocaleDateString(t)}function eO(e,t,n){return e.rows===void 0?`—`:e.rows===null?n(`storage.rows.unknown`):e.rows.toLocaleString(t)}function tO(e,t){switch(t){case`codex_running`:return KD(e,`error.codex_running`);case`process_enumeration_failed`:return KD(e,`error.process_enumeration_failed`);case`busy`:return KD(e,`error.busy`);case`unsupported_schema`:return KD(e,`error.unsupported_schema`);case`trigger_collision`:return WD(e,`error.trigger_collision`);case`unsafe_path`:return KD(e,`error.unsafe_path`);case`database_error`:return KD(e,`error.database_error`);case`auto_vacuum_not_incremental`:return KD(e,`error.auto_vacuum_not_incremental`);case`integrity_check_failed`:return KD(e,`error.integrity_check_failed`);case`config_write_failed`:return WD(e,`error.config_write_failed`);default:return KD(e,`error.generic`)}}function nO({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,Z.useState)(!1);return(0,Q.jsxs)(`div`,{className:`stw-section`,"data-testid":`codex-log-guard`,children:[(0,Q.jsx)(`h3`,{className:`stw-section-title`,children:n(`storage.bucket.logs_db`)}),(0,Q.jsxs)(`dl`,{className:`stw-kv`,children:[(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:n(`dash.status`)}),(0,Q.jsxs)(`dd`,{className:`stw-kv-mono`,children:[(0,Q.jsx)(`code`,{children:JD(t,e.schema.state)}),c&&e.schema.state===`unsupported`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:` · `}),(0,Q.jsx)(`code`,{children:WD(t,`inspectionOnly`)})]}):null]})]}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:n(`storage.bucket.logs_db`)}),(0,Q.jsx)(`dd`,{className:`stw-kv-mono`,children:HD(e.files.databaseBytes,t)})]}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:(0,Q.jsx)(`code`,{children:`WAL`})}),(0,Q.jsx)(`dd`,{className:`stw-kv-mono`,children:HD(e.files.walBytes,t)})]}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:(0,Q.jsx)(`code`,{children:`SHM`})}),(0,Q.jsx)(`dd`,{className:`stw-kv-mono`,children:HD(e.files.shmBytes,t)})]}),s&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:n(`storage.col.rows`)}),(0,Q.jsx)(`dd`,{className:`stw-kv-mono`,children:s.totalRows.toLocaleString(t)})]}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:(0,Q.jsx)(`code`,{children:`TRACE`})}),(0,Q.jsxs)(`dd`,{className:`stw-kv-mono`,children:[(s.traceShare*100).toFixed(1),`%`]})]}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:(0,Q.jsx)(`code`,{children:`freelist`})}),(0,Q.jsx)(`dd`,{className:`stw-kv-mono`,children:HD(s.reclaimableBytes,t)})]})]}),!s&&e.metricsSkipped&&(0,Q.jsxs)(`div`,{className:`stw-kv-row`,"data-testid":`log-guard-metrics-skipped`,children:[(0,Q.jsx)(`dt`,{children:n(`storage.col.rows`)}),(0,Q.jsx)(`dd`,{className:`muted`,children:WD(t,`metricsSkippedLarge`).replace(`{threshold}`,HD(e.metricsSkipped.thresholdBytes,t))})]}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:(0,Q.jsx)(`code`,{children:`sqlite_home`})}),(0,Q.jsx)(`dd`,{className:`stw-kv-mono`,children:(0,Q.jsx)(`code`,{children:e.externalSqliteHome?WD(t,`externalSqliteHome`):`CODEX_HOME`})})]})]}),l&&(0,Q.jsxs)(`div`,{className:`stw-section`,"data-testid":`log-guard-protection`,children:[(0,Q.jsx)(`h4`,{className:`stw-section-title`,children:WD(t,`protection`)}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:(0,Q.jsx)(`code`,{children:YD(t,l.state)})}),(0,Q.jsxs)(`span`,{className:`stw-kv-mono`,children:[(0,Q.jsx)(`code`,{children:XD(t,l.desiredMode)}),l.observedMode===l.desiredMode?null:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:` · `}),(0,Q.jsx)(`code`,{children:XD(t,l.observedMode)})]})]})]}),(0,Q.jsxs)(`div`,{className:`storage-policy-actions`,children:[(0,Q.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:WD(t,`compat`)}),(0,Q.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:WD(t,`quiet`)}),(0,Q.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:WD(t,`disable`)}),l.state===`drifted`&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,"data-testid":`log-guard-repair`,disabled:u,onClick:()=>o({action:`repair`}),children:WD(t,`repair`)}),r&&(0,Q.jsx)(`span`,{className:`muted`,role:`status`,children:KD(t,`applying`)})]}),i&&(0,Q.jsx)(`p`,{className:`err`,role:`alert`,children:i})]}),d&&(0,Q.jsx)(`div`,{className:`stw-section`,"data-testid":`log-guard-reclaim`,children:(0,Q.jsx)(`div`,{className:`storage-policy-actions`,children:f?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,"data-testid":`log-guard-compact-confirm`,disabled:r,onClick:()=>{p(!1),o({action:`compact`})},children:WD(t,`confirmCompact`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:r,onClick:()=>p(!1),children:WD(t,`cancel`)})]}):(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"data-testid":`log-guard-compact`,disabled:r,onClick:()=>p(!0),children:WD(t,`compact`)})})}),a&&(0,Q.jsx)(`div`,{className:`stw-section`,children:(0,Q.jsx)(`p`,{className:`stw-kv-mono`,role:`status`,"data-testid":`log-guard-compact-result`,children:a})}),s&&s.topTargets.length>0&&(0,Q.jsxs)(`div`,{className:`stw-section`,children:[(0,Q.jsx)(`h4`,{className:`stw-section-title`,children:(0,Q.jsx)(`code`,{children:`target`})}),s.topTargets.slice(0,5).map(e=>(0,Q.jsxs)(`div`,{className:`stw-file-row`,children:[(0,Q.jsx)(`span`,{className:`stw-file-path`,title:e.target,children:(0,Q.jsx)(`code`,{children:e.target})}),(0,Q.jsx)(`span`,{className:`stw-file-size`,children:e.rows.toLocaleString(t)})]},e.target))]}),(0,Q.jsx)(`p`,{className:`stw-hint`,children:(0,Q.jsxs)(`code`,{children:[`immutable=1 · snapshot=`,e.snapshot]})})]})}function rO({locale:e,t}){return(0,Q.jsxs)(`div`,{className:`stw-section`,"data-testid":`codex-log-guard-unavailable`,children:[(0,Q.jsx)(`h3`,{className:`stw-section-title`,children:t(`storage.bucket.logs_db`)}),(0,Q.jsx)(`p`,{className:`stw-hint`,children:WD(e,`inspectionUnavailable`)})]})}function iO({report:e,locale:t,apiBase:r=``,logGuardBusy:i=!1,onLogGuardAction:a}){let o=n(),[s,c]=(0,Z.useState)(null),[l,u]=(0,Z.useState)(null),[d,f]=(0,Z.useState)(!1),[p,m]=(0,Z.useState)(null),[h,g]=(0,Z.useState)(null),_=(0,Z.useMemo)(()=>e.buckets.toSorted((e,t)=>t.bytes-e.bytes),[e.buckets]),v=_.find(e=>e.key===s)??null,y=l?.generation===e.generatedAt?l.report:e.codexLogs??null,b=p?.generation===e.generatedAt?p.message:null,x=h?.generation===e.generatedAt?h.summary:null,S=i||d,C=(0,Z.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,Z.useMemo)(()=>new Map(e.buckets.map(e=>[e.key,e])),[e.buckets]);return(0,Q.jsxs)(`div`,{className:`storage-workspace-root`,children:[(0,Q.jsxs)(`aside`,{className:`storage-workspace-rail`,"aria-label":o(`storage.section.buckets`),children:[(0,Q.jsxs)(`div`,{className:`storage-workspace-rail-header`,children:[(0,Q.jsx)(`span`,{className:`storage-workspace-rail-title`,children:o(`storage.section.buckets`)}),(0,Q.jsx)(`span`,{className:`storage-workspace-rail-count`,children:_.length})]}),(0,Q.jsx)(`div`,{className:`storage-workspace-rail-list`,children:_.length===0?(0,Q.jsx)(`span`,{className:`storage-workspace-rail-empty`,children:o(`storage.empty`)}):_.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`storage-workspace-rail-row${s===e.key?` storage-workspace-rail-row--selected`:``}`,onClick:()=>c(t=>t===e.key?null:e.key),"aria-current":s===e.key?`true`:void 0,children:[(0,Q.jsxs)(`span`,{className:`storage-workspace-rail-primary`,children:[(0,Q.jsx)(`span`,{className:`storage-workspace-rail-name`,children:QD(e,o)}),(0,Q.jsx)(`span`,{className:`storage-workspace-rail-size`,children:HD(e.bytes,t)})]}),(0,Q.jsxs)(`span`,{className:`storage-workspace-rail-meta`,children:[e.fileCount.toLocaleString(t),` `,o(`storage.col.files`).toLowerCase()]})]},e.key))})]}),(0,Q.jsx)(`section`,{className:`storage-workspace-main`,"aria-label":v?QD(v,o):o(`storage.section.largest`),children:v?(0,Q.jsxs)(`div`,{className:`stw-detail`,children:[(0,Q.jsx)(`div`,{className:`stw-detail-toolbar`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`stw-detail-back`,onClick:()=>c(null),children:[(0,Q.jsx)(Ye,{className:`stw-detail-back-chevron`,"aria-hidden":`true`}),o(`modal.back`)]})}),(0,Q.jsxs)(`div`,{className:`stw-detail-body`,children:[(0,Q.jsx)(`h2`,{className:`stw-detail-title`,children:QD(v,o)}),(0,Q.jsxs)(`dl`,{className:`stw-kv`,children:[(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:o(`storage.col.size`)}),(0,Q.jsx)(`dd`,{className:`stw-kv-mono`,children:HD(v.bytes,t)})]}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:o(`storage.col.files`)}),(0,Q.jsx)(`dd`,{className:`stw-kv-mono`,children:v.fileCount.toLocaleString(t)})]}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:o(`storage.col.oldest`)}),(0,Q.jsx)(`dd`,{children:$D(v.oldest,t)})]}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:o(`storage.col.newest`)}),(0,Q.jsx)(`dd`,{children:$D(v.newest,t)})]}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:o(`storage.col.rows`)}),(0,Q.jsx)(`dd`,{className:`stw-kv-mono`,children:eO(v,t,o)})]})]}),(v.largest?.length??0)>0&&(0,Q.jsxs)(`div`,{className:`stw-section`,children:[(0,Q.jsx)(`h3`,{className:`stw-section-title`,children:o(`storage.section.largest`)}),v.largest.map(e=>(0,Q.jsxs)(`div`,{className:`stw-file-row`,children:[(0,Q.jsx)(`span`,{className:`stw-file-path`,title:e.path,children:e.path}),(0,Q.jsx)(`span`,{className:`stw-file-size`,children:HD(e.bytes,t)})]},e.path))]})]})]}):(0,Q.jsxs)(`div`,{className:`stw-overview`,children:[(0,Q.jsxs)(`div`,{className:`stw-summary`,children:[(0,Q.jsxs)(`div`,{className:`stw-summary-card`,children:[(0,Q.jsx)(`div`,{className:`stw-summary-label`,children:o(`storage.card.total`)}),(0,Q.jsx)(`div`,{className:`stw-summary-value`,children:HD(e.total.bytes,t)})]}),(0,Q.jsxs)(`div`,{className:`stw-summary-card`,children:[(0,Q.jsx)(`div`,{className:`stw-summary-label`,children:o(`storage.card.files`)}),(0,Q.jsx)(`div`,{className:`stw-summary-value`,children:e.total.fileCount.toLocaleString(t)})]}),(0,Q.jsxs)(`div`,{className:`stw-summary-card`,children:[(0,Q.jsx)(`div`,{className:`stw-summary-label`,children:o(`storage.card.home`)}),(0,Q.jsx)(`div`,{className:`stw-summary-value mono stw-home-path`,title:e.codexHome,children:e.codexHome})]})]}),y?(0,Q.jsx)(nO,{report:y,locale:t,t:o,busy:S,error:b,compaction:x,onAction:n=>{if(a){a(n);return}if(d)return;let i=e.generatedAt;(async()=>{f(!0),m(null),n.action===`compact`&&g(null);try{let e=n.action===`protect`?`protect`:n.action,a={method:`POST`,...n.action===`protect`?{headers:{"content-type":`application/json`},body:JSON.stringify({mode:n.mode})}:{}},o=await fetch(`${r}/api/storage/codex-logs/${e}`,a);if(!o.ok){let e=await o.json().catch(()=>({}));m({generation:i,message:tO(t,e.error)});return}if(n.action===`compact`){let e=(await o.json().catch(()=>null))?.report;if(e){let n=HD(e.logicalBytesReclaimed??0,t),r=HD(e.physicalDatabaseBytesReclaimed??0,t),a=e.complete?WD(t,`compactComplete`):WD(t,`compactPartial`),o=e.pagesReclaimed??0,s=!e.complete&&e.stopReason?` (${e.stopReason})`:``;g({generation:i,summary:[`${a}${s}`,`${o.toLocaleString(t)} ${WD(t,`pagesUnit`)}`,`${n} / ${r}`].join(` — `)})}try{let e=await fetch(`${r}/api/storage/codex-logs`);if(e.ok){let t=await e.json();u({generation:i,report:t})}}catch{}return}let s=await o.json();u({generation:i,report:s})}catch{m({generation:i,message:KD(t,`error.generic`)})}finally{f(!1)}})()}}):e.codexLogsError===`inspect_failed`?(0,Q.jsx)(rO,{locale:t,t:o}):null,C.length>0?(0,Q.jsxs)(`div`,{className:`stw-section`,children:[(0,Q.jsx)(`h3`,{className:`stw-section-title`,children:o(`storage.section.largest`)}),C.map(e=>{let n=w.get(e.bucketKey);return(0,Q.jsxs)(`div`,{className:`stw-file-row`,children:[(0,Q.jsx)(`span`,{className:`stw-file-path`,title:e.path,children:e.path}),n&&(0,Q.jsx)(`span`,{className:`stw-file-bucket`,children:QD(n,o)}),(0,Q.jsx)(`span`,{className:`stw-file-size`,children:HD(e.bytes,t)})]},`${e.bucketKey}:${e.path}`)})]}):(0,Q.jsxs)(`p`,{className:`stw-hint`,children:[(0,Q.jsx)(Ie,{style:{width:14,height:14,verticalAlign:`text-bottom`,marginRight:6},"aria-hidden":`true`}),o(`storage.workspace.selectBucket`)]})]})})]})}var aO=1024**3,oO=[10,25,50],sO=(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 cO({apiBase:e,locale:t,t:n,onDone:r}){let[i,a]=(0,Z.useState)(25),[o,s]=(0,Z.useState)(null),[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(!1),[m,h]=(0,Z.useState)(null),[g,_]=(0,Z.useState)(null),v=(0,Z.useRef)(null),y=(0,Z.useRef)(null),b=(0,Z.useRef)(!1),x=(0,Z.useCallback)((e=!1)=>{l(!1),d(!1),e&&s(null)},[]);(0,Z.useEffect)(()=>{b.current=f},[f]),(0,Z.useEffect)(()=>{if(!c)return;y.current=document.activeElement,v.current?.focus();let e=e=>{e.key===`Escape`&&!b.current&&x()};return window.addEventListener(`keydown`,e),()=>{window.removeEventListener(`keydown`,e),y.current?.focus()}},[c,x]);let S=(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`)}},C=e=>n(`storage.cleanup.preset`,{percent:new Intl.NumberFormat(t,{style:`percent`,maximumFractionDigits:0}).format(e/100)}),w=async()=>{p(!0),_(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(S(e.error,n(`storage.cleanup.previewFailed`)))}let r=await t.json();s(r),l(!0)}catch(e){_(sO(e,n(`storage.cleanup.previewFailed`)))}finally{p(!1)}},T=async()=>{if(o){p(!0),_(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`&&x(!0),Error(S(e.error,e.message,e.trashDir))}let a=await i.json();if(!a.ok)throw a.error===`stale_preview`&&x(!0),Error(S(a.error,a.message,a.trashDir));x(!0);let s=n(u?`storage.cleanup.donePermanent`:`storage.cleanup.doneQuarantine`,{count:String(a.count),size:HD(a.bytes,t)});h(a.skippedReferencedPaths?.length?`${s} ${n(`storage.cleanup.skippedReferenced`,{count:String(a.skippedReferencedPaths.length)})}`:s),r()}catch(e){_(sO(e,n(`storage.cleanup.cleanupFailed`)))}finally{p(!1)}}};return(0,Q.jsxs)(`section`,{className:`storage-cleanup-pane`,children:[(0,Q.jsx)(`p`,{className:`muted storage-manual-panel__help`,children:n(`storage.cleanup.help`)}),(0,Q.jsxs)(`div`,{className:`storage-manual-panel__controls`,children:[(0,Q.jsxs)(`label`,{className:`storage-manual-panel__slider`,children:[(0,Q.jsx)(`span`,{className:`muted mono`,style:{minWidth:`3.5rem`,fontVariantNumeric:`tabular-nums`},children:n(`storage.cleanup.percent`,{percent:String(i)})}),(0,Q.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,Q.jsx)(`div`,{className:`storage-manual-panel__presets`,children:oO.map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm${i===e?` active`:``}`,disabled:f,onClick:()=>a(e),children:C(e)},e))}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:f,onClick:()=>void w(),children:n(`storage.cleanup.preview`)})]}),m&&(0,Q.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:m}),g&&!c&&(0,Q.jsx)(`p`,{className:`storage-manual-panel__status`,style:{color:`var(--red)`},children:g}),c&&o&&(0,Q.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`storage-cleanup-confirm-title`,onClick:()=>!f&&x(),children:(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsx)(`h3`,{id:`storage-cleanup-confirm-title`,children:n(`storage.cleanup.confirmTitle`)}),(0,Q.jsx)(`p`,{children:n(`storage.cleanup.confirmBody`,{count:String(o.count),size:HD(o.bytes,t),percent:String(o.percent)})}),o.candidates.length>0&&(0,Q.jsxs)(`ul`,{className:`mono muted`,style:{maxHeight:160,overflow:`auto`,fontSize:`var(--text-caption)`},children:[o.candidates.slice(0,8).map(e=>(0,Q.jsx)(`li`,{children:e.relPath},e.relPath)),o.count>8&&(0,Q.jsx)(`li`,{children:n(`storage.cleanup.moreFiles`,{n:String(Math.max(0,o.count-8))})})]}),(0,Q.jsxs)(`label`,{style:{display:`flex`,gap:8,alignItems:`center`,marginTop:12},children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:u,disabled:f,onChange:e=>d(e.target.checked)}),(0,Q.jsx)(`span`,{children:n(`storage.cleanup.permanent`)})]}),(0,Q.jsx)(`p`,{className:`muted`,style:{marginTop:8,fontSize:`var(--text-caption)`},children:n(u?`storage.cleanup.permanentWarn`:`storage.cleanup.quarantineNote`)}),g&&(0,Q.jsx)(`p`,{style:{marginTop:12,color:`var(--red)`},children:g}),(0,Q.jsxs)(`div`,{className:`dialog-actions`,style:{marginTop:16},children:[(0,Q.jsx)(`button`,{ref:v,type:`button`,className:`btn btn-ghost`,disabled:f,onClick:()=>x(),children:n(`storage.cleanup.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:u?`btn btn-danger`:`btn`,disabled:f||o.count===0,onClick:()=>void T(),children:n(u?`storage.cleanup.confirmPermanent`:`storage.cleanup.confirmQuarantine`)})]})]})})]})}function lO({apiBase:e,locale:t,t:n,onDone:r,reloadToken:i,onEntriesChange:a}){let[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(null),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)(null),m=(0,Z.useRef)(null),h=(0,Z.useRef)(null),g=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>{g.current=o},[o]);let _=(0,Z.useCallback)(()=>l(null),[]);(0,Z.useEffect)(()=>{if(!c)return;h.current=document.activeElement,m.current?.focus();let e=e=>{e.key===`Escape`&&!g.current&&_()};return window.addEventListener(`keydown`,e),()=>{window.removeEventListener(`keydown`,e),h.current?.focus()}},[c,_]);let v=(0,Z.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]),y=uo(`storage-trash:${e}`,[e,i],v,{isEmpty:e=>e.length===0}).state,b=y.data??[],x=(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`)}},S=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(x(e.error,e.message))}let a=await i.json();if(!a.ok)throw Error(x(a.error,a.message));_(),d(n(`storage.trash.done`,{count:String(a.count),size:HD(a.bytes,t)})),r()}catch(e){p(sO(e,n(`storage.trash.restoreFailed`)))}finally{s(!1)}}},C=e=>{let n=e.quarantinedAt??Number(e.epoch.split(`-`)[0]);return!Number.isFinite(n)||n<=0?`—`:new Date(n).toLocaleString(t)},w=e=>e===`permanent`?n(`storage.trash.mode.permanent`):e===`quarantine`?n(`storage.trash.mode.quarantine`):`—`;return(0,Q.jsxs)(`section`,{className:`storage-cleanup-pane storage-quarantine-pane`,children:[(0,Q.jsx)(`p`,{className:`muted storage-manual-panel__help`,children:n(`storage.trash.help`)}),u&&(0,Q.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:u}),f&&!c&&(0,Q.jsx)(`p`,{className:`storage-manual-panel__status`,style:{color:`var(--red)`},role:`alert`,children:f}),y.showError&&!c&&(0,Q.jsx)(`p`,{className:`storage-manual-panel__status`,style:{color:`var(--red)`},role:`alert`,children:y.error instanceof Error?y.error.message:n(`storage.trash.listFailed`)}),y.refreshing&&!y.showSkeleton&&(0,Q.jsx)(ub,{live:!y.showError,children:n(`storage.trash.loading`)}),y.showSkeleton?(0,Q.jsx)(lb,{label:n(`storage.trash.loading`),rows:2}):b.length===0?(0,Q.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.trash.empty`)}):(0,Q.jsx)(`div`,{className:`tbl-wrap storage-manual-panel__table`,children:(0,Q.jsxs)(`table`,{className:`tbl`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:n(`storage.trash.col.when`)}),(0,Q.jsx)(`th`,{className:`num`,children:n(`storage.trash.col.files`)}),(0,Q.jsx)(`th`,{className:`num`,children:n(`storage.trash.col.size`)}),(0,Q.jsx)(`th`,{children:n(`storage.trash.col.mode`)}),(0,Q.jsx)(`th`,{children:n(`storage.trash.col.id`)}),(0,Q.jsx)(`th`,{})]})}),(0,Q.jsx)(`tbody`,{children:b.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`muted`,children:C(e)}),(0,Q.jsx)(`td`,{className:`num`,children:e.fileCount}),(0,Q.jsx)(`td`,{className:`num mono`,children:HD(e.bytes,t)}),(0,Q.jsx)(`td`,{className:`muted`,children:w(e.mode)}),(0,Q.jsx)(`td`,{className:`mono`,style:{fontSize:`var(--text-caption)`},children:e.id}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:o,onClick:()=>{p(null),l(e)},children:n(`storage.trash.restore`)})})]},e.id))})]})}),c&&(0,Q.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`storage-trash-confirm-title`,onClick:()=>!o&&_(),children:(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsx)(`h3`,{id:`storage-trash-confirm-title`,children:n(`storage.trash.confirmTitle`)}),(0,Q.jsx)(`p`,{children:n(`storage.trash.confirmBody`,{count:String(c.fileCount),size:HD(c.bytes,t),id:c.id})}),f&&(0,Q.jsx)(`p`,{style:{marginTop:12,color:`var(--red)`},children:f}),(0,Q.jsxs)(`div`,{className:`dialog-actions`,style:{marginTop:16},children:[(0,Q.jsx)(`button`,{ref:m,type:`button`,className:`btn btn-ghost`,disabled:o,onClick:()=>_(),children:n(`storage.trash.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn`,disabled:o,onClick:()=>void S(),children:n(`storage.trash.confirmRestore`)})]})]})})]})}function uO(e){let{job:t,...n}=e;return n}function dO(e){let t=String(Math.max(0,Math.round(e.trigger.archivedBytesOver/aO*100)/100));return e.target.reduceToBytes===void 0?{policy:uO(e),thresholdGb:t,targetMode:`percent`,percent:String(Math.min(100,Math.max(1,Math.floor(e.target.removeOldestPercent??25)))),reduceGb:`4`}:{policy:uO(e),thresholdGb:t,targetMode:`reduce`,percent:`25`,reduceGb:String(Math.max(0,Math.round(e.target.reduceToBytes/aO*100)/100))}}async function fO(e){await new Promise(t=>window.setTimeout(t,e))}function pO({apiBase:e,locale:t,t:n,onDone:r}){let i=`ocx.storage.cleanup-policy.v1:${e}`,a=io(i),o=(0,Z.useRef)(!!a),[s,c]=(0,Z.useState)(()=>a?.policy??null),[l,u]=(0,Z.useState)(()=>!a),[d,f]=(0,Z.useState)(!1),[p,m]=(0,Z.useState)(!1),[h,g]=(0,Z.useState)(null),[_,v]=(0,Z.useState)(null),[y,b]=(0,Z.useState)(()=>a?.targetMode??`percent`),[x,S]=(0,Z.useState)(()=>a?.percent??`25`),[C,w]=(0,Z.useState)(()=>a?.reduceGb??`4`),[T,E]=(0,Z.useState)(()=>a?.thresholdGb??`5`),D=(0,Z.useRef)(null),O=(0,Z.useRef)(!1),k=(0,Z.useRef)(!1),A=(0,Z.useRef)(0),j=(0,Z.useCallback)(e=>{let t=dO(e);c(t.policy),E(t.thresholdGb),b(t.targetMode),S(t.percent),w(t.reduceGb),o.current=!0,co(i,t),O.current=!1},[i]),M=(0,Z.useCallback)(()=>{O.current=!0},[]),N=(0,Z.useCallback)(e=>{k.current=e},[]),P=(0,Z.useCallback)(async t=>{let r=++A.current;o.current||u(!0),v(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!==A.current||O.current||k.current)return;j(i)}catch{if(t?.aborted||r!==A.current)return;o.current||(c(null),v(n(`storage.policy.loadFailed`)))}finally{!t?.aborted&&r===A.current&&u(!1)}},[e,j,n]);(0,Z.useEffect)(()=>{let e=new AbortController,t=window.setTimeout(()=>{P(e.signal)},0);return()=>{window.clearTimeout(t),A.current+=1,e.abort()}},[P]),(0,Z.useEffect)(()=>()=>{D.current?.abort(),D.current=null},[]);let F=()=>{if(!s)return null;let e=T.trim();if(e===``)return null;let t=Number(e);if(!Number.isFinite(t)||t<0)return null;let n;if(y===`reduce`){let e=C.trim();if(e===``)return null;let t=Number(e);if(!Number.isFinite(t)||t<0)return null;n={reduceToBytes:Math.floor(t*aO)}}else{let e=Number(x);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*aO)},target:n,schedule:s.schedule,mode:s.mode}},I=async t=>{let r=F();if(!r){v(n(`storage.policy.invalid`));return}let i={...r,...t};f(!0),v(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){v(n(`storage.policy.saveFailed`));return}let r=await t.json();if(!r.policy){v(n(`storage.policy.saveFailed`));return}j(r.policy),g(n(`storage.policy.saved`))}catch{v(n(`storage.policy.saveFailed`))}finally{f(!1)}},L=async()=>{D.current?.abort();let i=new AbortController;D.current=i;let{signal:a}=i;m(!0),v(null),g(null);try{let i=F();if(!i){v(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){v(n(`storage.policy.saveFailed`));return}let s=await o.json();if(a.aborted)return;if(!s.policy){v(n(`storage.policy.saveFailed`));return}j(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&&j(e.policy),v(n(`storage.policy.alreadyRunning`));return}if(!c.ok){let e=await c.json().catch(()=>({}));if(a.aborted)return;if(e.policy&&j(e.policy),e.error===`already_running`){v(n(`storage.policy.alreadyRunning`));return}v(n(`storage.policy.runFailed`));return}let l=await c.json();if(a.aborted)return;if(l.policy&&j(l.policy),l.error===`already_running`){v(n(`storage.policy.alreadyRunning`));return}if(!l.started||!l.job?.startedAt){v(n(`storage.policy.runFailed`));return}let u=l.job.startedAt,d=Date.now()+12e4,f,p;for(;Date.now()<d;){if(a.aborted||(await fO(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=uO(n),j(n);let r=n.job;if(r&&r.status!==`running`&&(r.startedAt===u&&r.lastOutcome||r.finishedAt&&r.finishedAt>=u&&r.lastOutcome)){f=r.lastOutcome;break}}if(a.aborted)return;if(p&&j(p),!f){v(n(`storage.policy.runFailed`));return}f.skipped===`disabled`?g(n(`storage.policy.skippedDisabled`)):f.ok&&f.metadataPersistenceError?(v(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`?v(n(`storage.cleanup.err.codex_busy`)):f.ok?(g(f.mode===`permanent`?n(`storage.policy.donePermanent`,{count:String(f.removed??0),size:HD(f.freedBytes??0,t)}):n(`storage.policy.doneQuarantine`,{count:String(f.removed??0),size:HD(f.freedBytes??0,t)})),r()):v(n(`storage.policy.runFailed`))}catch(e){if(a.aborted||e instanceof DOMException&&e.name===`AbortError`)return;v(n(`storage.policy.runFailed`))}finally{D.current===i&&(D.current=null),a.aborted||m(!1)}},R=e=>e===void 0?n(`storage.policy.never`):new Date(e).toLocaleString(t);return l&&!s?(0,Q.jsx)(`section`,{className:`storage-cleanup-pane`,children:(0,Q.jsx)(`p`,{className:`muted storage-policy-help`,children:n(`storage.policy.loading`)})}):s?(0,Q.jsxs)(`section`,{className:`storage-cleanup-pane`,children:[(0,Q.jsx)(`p`,{className:`muted storage-policy-help`,children:n(`storage.policy.help`)}),(0,Q.jsx)(`div`,{className:`storage-policy-enable`,children:(0,Q.jsxs)(`div`,{className:`storage-policy-enable-row`,children:[(0,Q.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 I({enabled:!s.enabled}),children:(0,Q.jsx)(`span`,{className:`toggle-knob`})}),(0,Q.jsx)(`span`,{children:n(`storage.policy.enabled`)})]})}),(0,Q.jsxs)(`div`,{className:`storage-policy-fields`,children:[(0,Q.jsxs)(`div`,{className:`field storage-policy-trigger`,children:[(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`storage-policy-threshold`,children:n(`storage.policy.trigger`)}),(0,Q.jsxs)(`div`,{className:`storage-policy-trigger-row`,children:[(0,Q.jsx)(`span`,{className:`storage-policy-trigger-hint`,children:n(`storage.policy.threshold`)}),(0,Q.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(N(!1),I())},children:[(0,Q.jsx)(`input`,{id:`storage-policy-threshold`,className:`input mono codex-auto-switch-input`,type:`number`,min:0,step:.1,inputMode:`decimal`,value:T,disabled:d||p,"aria-label":n(`storage.policy.threshold`),onFocus:()=>N(!0),onChange:e=>{M(),E(e.target.value)},onKeyDown:e=>{e.nativeEvent.isComposing||d||p||e.key===`Enter`&&(e.preventDefault(),I())}}),(0,Q.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`GiB`}),(0,Q.jsx)(yl,{disabled:d||p,incrementLabel:n(`storage.policy.thresholdInc`),decrementLabel:n(`storage.policy.thresholdDec`),onIncrement:()=>{M(),E(vl(T,.1,0,1e4,.1))},onDecrement:()=>{M(),E(vl(T,-.1,0,1e4,.1))}})]})]})]}),(0,Q.jsxs)(`fieldset`,{className:`field storage-policy-target`,children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:n(`storage.policy.target`)}),(0,Q.jsxs)(`label`,{className:`storage-policy-target-row`,children:[(0,Q.jsx)(`input`,{type:`radio`,name:`storage-policy-target`,checked:y===`percent`,disabled:d||p,onChange:()=>{M(),b(`percent`)}}),(0,Q.jsx)(`span`,{className:`storage-policy-target-label`,children:n(`storage.policy.targetPercent`)}),y===`percent`&&(0,Q.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(N(!1),I())},children:[(0,Q.jsx)(`input`,{id:`storage-policy-percent`,className:`input mono codex-auto-switch-input`,type:`number`,min:1,max:100,step:1,inputMode:`numeric`,value:x,disabled:d||p,"aria-label":n(`storage.policy.targetPercent`),onFocus:()=>N(!0),onChange:e=>{M(),S(e.target.value)},onKeyDown:e=>{e.nativeEvent.isComposing||d||p||e.key===`Enter`&&(e.preventDefault(),I())}}),(0,Q.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`%`}),(0,Q.jsx)(yl,{disabled:d||p,incrementLabel:n(`storage.policy.percentInc`),decrementLabel:n(`storage.policy.percentDec`),onIncrement:()=>{M(),S(vl(x,1,1,100))},onDecrement:()=>{M(),S(vl(x,-1,1,100))}})]})]}),(0,Q.jsxs)(`label`,{className:`storage-policy-target-row`,children:[(0,Q.jsx)(`input`,{type:`radio`,name:`storage-policy-target`,checked:y===`reduce`,disabled:d||p,onChange:()=>{M(),b(`reduce`)}}),(0,Q.jsx)(`span`,{className:`storage-policy-target-label`,children:n(`storage.policy.targetReduce`)}),y===`reduce`&&(0,Q.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(N(!1),I())},children:[(0,Q.jsx)(`input`,{id:`storage-policy-reduce`,className:`input mono codex-auto-switch-input`,type:`number`,min:0,step:.1,inputMode:`decimal`,value:C,disabled:d||p,"aria-label":n(`storage.policy.targetReduce`),onFocus:()=>N(!0),onChange:e=>{M(),w(e.target.value)},onKeyDown:e=>{e.nativeEvent.isComposing||d||p||e.key===`Enter`&&(e.preventDefault(),I())}}),(0,Q.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`GiB`}),(0,Q.jsx)(yl,{disabled:d||p,incrementLabel:n(`storage.policy.reduceInc`),decrementLabel:n(`storage.policy.reduceDec`),onIncrement:()=>{M(),w(vl(C,.1,0,1e4,.1))},onDecrement:()=>{M(),w(vl(C,-.1,0,1e4,.1))}})]})]})]}),(0,Q.jsxs)(`div`,{className:`storage-policy-selects`,children:[(0,Q.jsxs)(`label`,{className:`field`,htmlFor:`storage-policy-schedule`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:n(`storage.policy.schedule`)}),(0,Q.jsxs)(`select`,{id:`storage-policy-schedule`,className:`input`,value:s.schedule,disabled:d||p,onChange:e=>{let t=e.target.value;I({schedule:t})},children:[(0,Q.jsx)(`option`,{value:`manual`,children:n(`storage.policy.schedule.manual`)}),(0,Q.jsx)(`option`,{value:`startup`,children:n(`storage.policy.schedule.startup`)}),(0,Q.jsx)(`option`,{value:`daily`,children:n(`storage.policy.schedule.daily`)}),(0,Q.jsx)(`option`,{value:`weekly`,children:n(`storage.policy.schedule.weekly`)})]})]}),(0,Q.jsxs)(`label`,{className:`field`,htmlFor:`storage-policy-mode`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:n(`storage.policy.mode`)}),(0,Q.jsxs)(`select`,{id:`storage-policy-mode`,className:`input`,value:s.mode,disabled:d||p,onChange:e=>{let t=e.target.value;I({mode:t})},children:[(0,Q.jsx)(`option`,{value:`quarantine`,children:n(`storage.policy.mode.quarantine`)}),(0,Q.jsx)(`option`,{value:`permanent`,children:n(`storage.policy.mode.permanent`)})]})]})]}),s.mode===`permanent`&&(0,Q.jsx)(`p`,{className:`err storage-policy-warn`,role:`status`,children:n(`storage.policy.permanentWarn`)})]}),(0,Q.jsxs)(`div`,{className:`storage-policy-meta`,children:[(0,Q.jsxs)(`div`,{className:`storage-policy-meta-item`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:n(`storage.policy.lastRun`)}),(0,Q.jsxs)(`span`,{className:`storage-policy-meta-value`,children:[R(s.lastRun?.at),s.lastRun?` · ${n(`storage.policy.lastRunDetail`,{count:String(s.lastRun.removed),size:HD(s.lastRun.freedBytes,t)})}`:``]})]}),(0,Q.jsxs)(`div`,{className:`storage-policy-meta-item`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:n(`storage.policy.nextRun`)}),(0,Q.jsx)(`span`,{className:`storage-policy-meta-value`,children:R(s.nextRun)})]})]}),(0,Q.jsxs)(`div`,{className:`storage-policy-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:d||p,onClick:()=>void I(),children:n(`storage.policy.save`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:d||p,onClick:()=>void L(),children:n(p?`storage.policy.running`:`storage.policy.runNow`)}),(0,Q.jsx)(`span`,{className:`storage-policy-actions__status${_?` is-error`:``}`,role:_?`alert`:`status`,"aria-live":`polite`,children:_??h??``})]})]}):(0,Q.jsx)(`section`,{className:`storage-cleanup-pane`,children:_&&(0,Q.jsx)(`p`,{className:`err`,role:`alert`,children:_})})}function mO({apiBase:e,locale:t,t:n,archivedCount:r,showQuarantine:i,trashReloadToken:a,onDone:o,onTrashEntriesChange:s}){let[c,l]=(0,Z.useState)(`policy`),u=(0,Z.useRef)(null),d=(0,Z.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,Q.jsxs)(`section`,{className:`panel storage-cleanup-card`,"aria-labelledby":`storage-cleanup-card-title`,children:[(0,Q.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,Q.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,Q.jsx)(`h3`,{id:`storage-cleanup-card-title`,className:`panel-title`,children:n(`storage.cleanupCard.title`)}),(0,Q.jsxs)(`div`,{className:`storage-cleanup-card__stack`,children:[(0,Q.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,Q.jsx)(pO,{apiBase:e,locale:t,t:n,onDone:o}),(0,Q.jsxs)(`aside`,{className:`storage-cleanup-manual`,"aria-labelledby":`storage-cleanup-manual-title`,children:[(0,Q.jsx)(`h4`,{id:`storage-cleanup-manual-title`,className:`storage-cleanup-manual__title`,children:n(`storage.cleanup.title`)}),r>0?(0,Q.jsx)(cO,{apiBase:e,locale:t,t:n,onDone:o}):(0,Q.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.cleanup.noArchives`)})]})]}),(0,Q.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,Q.jsx)(lO,{apiBase:e,locale:t,t:n,onDone:o,reloadToken:a,onEntriesChange:s}):(0,Q.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.trash.empty`)})})]})]})}function hO({apiBase:e}){let{t,locale:n}=r(),i=`ocx.storage.report.v1:${e}`,a=io(i),[o,s]=(0,Z.useState)(null),[c,l]=(0,Z.useState)(0),u=(0,Z.useRef)(!1),[d,f]=(0,Z.useState)({apiBase:e,settled:!1,hasEntries:!1}),p=(0,Z.useCallback)(async n=>{try{let r=await fetch(`${e}/api/storage`,{signal:n});if(!r.ok)throw Error(t(`storage.error`));let a=await r.json();return co(i,a),u.current&&(u.current=!1,s(t(`storage.rescanned`))),a}catch(e){throw u.current&&(u.current=!1,s(t(`storage.error`))),n.aborted?e:Error(t(`storage.error`),{cause:e})}},[e,i,t]),m=uo(`storage-report:${e}`,[e],p,{isEmpty:e=>e.total.fileCount===0&&e.error===void 0}),h=m.state,g=h.data??a,_=h.refreshing||h.showSkeleton&&!g,v=m.refresh,y=(0,Z.useCallback)(()=>{s(null),u.current=!0,v(),l(e=>e+1)},[v]),b=(0,Z.useCallback)(t=>{f({apiBase:e,settled:!0,hasEntries:t.length>0})},[e]),x=d.apiBase===e&&d.settled,S=d.apiBase===e&&d.hasEntries,C=g?.error!==void 0,w=!_&&!h.showError&&!C&&g.total.fileCount===0&&x&&!S,T=g?.buckets.find(e=>e.key===`archived_sessions`)?.fileCount??0,E=!!g&&!C,D=E&&(g.total.fileCount>0||!x||S);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`page-head`,children:[(0,Q.jsx)(`h2`,{id:`storage-page-title`,children:t(`storage.title`)}),(0,Q.jsxs)(`div`,{className:`storage-page-head-actions`,children:[(0,Q.jsx)(`span`,{className:`storage-page-head-feedback`,role:`status`,"aria-live":`polite`,children:o??``}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:_,onClick:()=>void y(),children:[(0,Q.jsx)(ae,{}),` `,t(`storage.refresh`)]})]})]}),(0,Q.jsx)(`p`,{className:`page-sub`,children:t(`storage.subtitle`)}),g&&g.error===void 0&&(0,Q.jsxs)(`p`,{className:`storage-page-meta`,children:[(0,Q.jsx)(`code`,{className:`mono storage-page-meta__home`,title:g.codexHome,children:g.codexHome}),(0,Q.jsx)(`span`,{className:`storage-page-meta__sep`,"aria-hidden":`true`,children:`·`}),(0,Q.jsxs)(`span`,{children:[t(`storage.snapshot.lastScan`),`:`,` `,new Date(g.generatedAt).toLocaleString(n)]})]}),h.showSkeleton&&!g?(0,Q.jsx)(lb,{label:t(`storage.loading`),rows:5}):h.kind===`failed-cold`&&!g?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:h.error instanceof Error?h.error.message:t(`storage.error`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>v(),children:t(`common.retry`)})]}):C?(0,Q.jsx)(Q.Fragment,{children:(0,Q.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:t(`storage.error`)})}):(0,Q.jsxs)(Q.Fragment,{children:[h.showError&&(0,Q.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:t(`storage.error`)}),w?(0,Q.jsx)(fn,{title:t(`storage.empty`)}):g&&g.total.fileCount>0&&(0,Q.jsx)(iO,{report:g,locale:n,apiBase:e})]}),g&&g.error===void 0&&h.refreshing&&!h.showSkeleton&&(0,Q.jsx)(ub,{live:!h.showError,children:t(`storage.loading`)}),E&&(0,Q.jsx)(mO,{apiBase:e,locale:n,t,archivedCount:T,showQuarantine:D,trashReloadToken:c,onDone:()=>void y(),onTrashEntriesChange:b})]})}var gO=`/api/codex-auth/features/default-mode-request-user-input`;function _O({apiBase:e}){let t=n(),[r,i]=(0,Z.useState)(!1),[a,o]=(0,Z.useState)(!1),[s,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(!1),[d,f]=(0,Z.useState)(null),p=(0,Z.useRef)(!1),m=(0,Z.useRef)(!1),h=(0,Z.useRef)(0),g=(0,Z.useCallback)(async()=>{if(p.current)return;let t=++h.current,n=M(15e3);try{let r=await fetch(`${e}${gO}`,{signal:n.signal});if(!r.ok)throw Error(`load`);let a=await r.json();if(p.current||t!==h.current)return;m.current=a.enabled===!0,i(m.current),o(!0),u(!1)}catch{!p.current&&t===h.current&&u(!0)}finally{n.clear()}},[e]);(0,Z.useEffect)(()=>{let e=window.setTimeout(()=>{g()},0),t=ba(()=>{g()},3e4);return()=>{window.clearTimeout(e),t()}},[g]);let _=(0,Z.useCallback)(async()=>{if(p.current||!a||l)return;let n=!m.current,r=m.current;m.current=n,i(n),p.current=!0,c(!0),f(null),h.current++;try{let r=await fetch(`${e}${gO}`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({enabled:n})}),a=await vn(r)??{};if(a.ok!==!0)throw Error(String(r.status));m.current=a.enabled===!0,i(m.current),o(!0),f({tone:`ok`,message:t(a.changed===!0?`codexAuth.requestUserInputUpdatedRestart`:`codexAuth.requestUserInputUpdated`)})}catch(e){m.current=r,i(r);let n=e instanceof Error&&e.message&&!/^HTTP \d{3}$/.test(e.message)?e.message:t(`codexAuth.requestUserInputUpdateFailed`);f({tone:`err`,message:n})}finally{p.current=!1,c(!1)}},[e,a,l,t]),v=s||!a||l;return(0,Q.jsxs)(`div`,{className:`card card-row codex-request-user-input-card`,style:{marginTop:16},"aria-busy":s||!a&&!l||void 0,children:[(0,Q.jsxs)(`div`,{className:`codex-request-user-input-copy`,children:[(0,Q.jsx)(`strong`,{children:t(`codexAuth.requestUserInput`)}),(0,Q.jsx)(`div`,{className:`card-sub`,role:l?`alert`:void 0,children:t(l?`codexAuth.requestUserInputLoadFailed`:`codexAuth.requestUserInputDesc`)}),(0,Q.jsx)(`code`,{className:`mono codex-request-user-input-config`,children:`[features]
7
+ `,oC=new Map;function sC(e,t){return JSON.stringify([e,t])}function cC(e,t){for(oC.set(e,t);oC.size>iC;){let e=oC.keys().next().value;if(e===void 0)break;oC.delete(e)}}var lC={pairs:new Map,loading:!1,unresolved:0};function uC(e,t,n){let[,r]=(0,Z.useState)(0),i=n?t.slice(0,200):[],a=i.filter(t=>!oC.has(sC(e,t))).join(aC);if((0,Z.useEffect)(()=>{if(!a)return;let t=new AbortController,n=a.split(aC);return Promise.all(Array.from({length:Math.min(rC,n.length)},async()=>{for(let r=n.shift();r!==void 0;r=n.shift())try{let n=await VS(e,r,t.signal);cC(sC(e,r),gS(n))}catch{if(t.signal.aborted)return;cC(sC(e,r),null)}})).then(()=>{t.signal.aborted||r(e=>e+1)}),()=>t.abort()},[e,a]),!n)return lC;let o=new Map,s=Math.max(0,t.length-200);for(let t of i){let n=oC.get(sC(e,t));n?o.set(t,n):n===null&&(s+=1)}return{pairs:o,loading:a.length>0,unresolved:s}}var dC={protocol_conformance:`lab.layer.protocol_conformance`,live_route_compatibility:`lab.layer.live_route_compatibility`,task_effectiveness:`lab.layer.task_effectiveness`},fC={protocol_conformance:`lab.col.protocol`,live_route_compatibility:`lab.col.live`,task_effectiveness:`lab.col.task`},pC={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`},mC={present:`artifact.present`,corrupt:`artifact.corrupt`,purged_unavailable:`artifact.purged_unavailable`};function hC(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 gC({verdict:e,caption:t,label:n,selected:r,onSelect:i}){let a=`lab-verdict-badge${r?` lab-verdict-badge--selected`:``}`;return i?(0,Q.jsxs)(`button`,{type:`button`,className:a,"data-verdict":e,title:t,onClick:i,children:[(0,Q.jsx)(`span`,{children:n}),(0,Q.jsx)(`span`,{className:`suite`,children:t})]}):(0,Q.jsxs)(`span`,{className:a,"data-verdict":e,title:t,children:[(0,Q.jsx)(`span`,{children:n}),(0,Q.jsx)(`span`,{className:`suite`,children:t})]})}function _C({rows:e,t,selectedKey:n,onSelect:r}){return e.length===0?(0,Q.jsx)(`span`,{className:`muted`,children:`-`}):(0,Q.jsx)(`div`,{className:`lab-verdict-stack`,children:e.map(e=>(0,Q.jsx)(gC,{verdict:e.verdict,caption:e.suiteId,label:t(pC[e.verdict]),selected:n===e.projectionKey,onSelect:()=>r(e)},e.projectionKey))})}function vC({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:mS(r.builtAtMs,n)}),(0,Q.jsx)(`div`,{className:`lab-status-grid`,"aria-label":t(`lab.statusTitle`),children:i.map(e=>(0,Q.jsxs)(`div`,{className:`lab-status-card`,children:[(0,Q.jsx)(`span`,{className:`label`,children:e.label}),(0,Q.jsx)(`span`,{className:`value`,children:e.value})]},e.label))})}function yC({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,Q.jsxs)(`section`,{className:`lab-matrix-block`,"data-testid":`lab-community-evidence`,children:[(0,Q.jsx)(`h3`,{className:`lab-matrix-title`,children:y(t,`community.title`)}),(0,Q.jsx)(`p`,{className:`muted`,children:y(t,`community.notLocalVerdict`)}),(0,Q.jsxs)(`dl`,{className:`lab-detail-meta`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:y(t,`community.bundles`)}),(0,Q.jsx)(`dd`,{children:e.evidence.length})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:y(t,`community.activeRecords`)}),(0,Q.jsx)(`dd`,{children:n})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:y(t,`community.revokedRecords`)}),(0,Q.jsx)(`dd`,{children:r})]})]})]})}function bC({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,Q.jsxs)(`aside`,{className:`lab-detail-pane`,"aria-label":i(`lab.detailTitle`),children:[(0,Q.jsxs)(`div`,{className:`lab-detail-head`,children:[(0,Q.jsx)(`h3`,{children:pS(e.subjectId)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:o,children:i(`lab.detailClose`)})]}),(0,Q.jsxs)(`dl`,{className:`lab-detail-meta`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:i(`lab.col.layer`)}),(0,Q.jsx)(`dd`,{children:i(dC[e.evidenceLayer])})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:i(`lab.col.suite`)}),(0,Q.jsx)(`dd`,{className:`mono`,children:e.suiteId})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:i(`lab.col.verdict`)}),(0,Q.jsx)(`dd`,{children:i(pC[e.verdict])})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:i(`lab.col.asOf`)}),(0,Q.jsx)(`dd`,{children:mS(e.asOf,a)})]})]}),n&&(0,Q.jsx)(ub,{busy:!0,children:i(`common.loading`)}),r&&(0,Q.jsx)($,{tone:`err`,children:r}),t&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`section`,{className:`lab-detail-section`,children:[(0,Q.jsx)(`h4`,{children:i(`lab.detailSubject`)}),(0,Q.jsx)(`p`,{className:`mono`,children:t.subject.subjectKind})]}),t.production&&(0,Q.jsxs)(`section`,{className:`lab-detail-section`,"data-testid":`lab-production-signals`,children:[(0,Q.jsx)(`h4`,{children:i(`lab.production.title`)}),(0,Q.jsx)(`p`,{className:`muted`,children:i(`lab.production.notVerification`)}),(0,Q.jsxs)(`dl`,{className:`lab-detail-meta`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:i(`lab.production.attempts`)}),(0,Q.jsx)(`dd`,{children:t.production.summary.recentProductionAttempts})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:i(`lab.production.successes`)}),(0,Q.jsx)(`dd`,{children:t.production.summary.recentSuccessfulAttempts})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:i(`lab.production.routeErrors`)}),(0,Q.jsx)(`dd`,{children:t.production.summary.recentRouteErrorSignals})]}),t.production.summary.lastObservedProductionAttempt!==void 0&&(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:i(`lab.production.lastObserved`)}),(0,Q.jsx)(`dd`,{children:mS(t.production.summary.lastObservedProductionAttempt,a)})]})]})]}),t.observations.length>0&&(0,Q.jsxs)(`section`,{className:`lab-detail-section`,children:[(0,Q.jsx)(`h4`,{children:i(`lab.detailObservations`)}),(0,Q.jsx)(`ul`,{className:`lab-detail-list`,children:t.observations.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`span`,{className:`mono`,children:e.scenarioId}),(0,Q.jsx)(`span`,{children:e.outcome}),(0,Q.jsx)(`span`,{className:`muted`,children:mS(e.completedAt,a)})]},e.eventId))})]}),(t.events.length>0||s>0)&&(0,Q.jsxs)(`section`,{className:`lab-detail-section`,children:[(0,Q.jsxs)(`h4`,{children:[i(`lab.detailEvents`),t.events.length<s?` (${t.events.length}/${s})`:``]}),(0,Q.jsx)(`ul`,{className:`lab-detail-list`,children:t.events.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`span`,{className:`mono`,children:e.eventId}),(0,Q.jsx)(`span`,{children:e.eventKind})]},e.eventId))})]}),t.artifacts.length>0&&(0,Q.jsxs)(`section`,{className:`lab-detail-section`,children:[(0,Q.jsx)(`h4`,{children:i(`lab.detailArtifacts`)}),(0,Q.jsx)(`ul`,{className:`lab-detail-list`,children:t.artifacts.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`span`,{className:`mono`,title:e.digest,children:pS(e.digest)}),(0,Q.jsx)(`span`,{children:e.artifactClass??`-`}),(0,Q.jsx)(`span`,{children:y(a,mC[e.status])})]},e.digest))})]})]})]})}function xC({apiBase:e,active:t=!0,onCountChange:n}){let{t:i,locale:a}=r(),[o,s]=(0,Z.useState)({layer:``,verdict:``,subjectQuery:``,suiteId:``}),[c,l]=(0,Z.useState)(()=>l_()??a_),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)(null),[m,h]=(0,Z.useState)(!1),[g,_]=(0,Z.useState)(null),[v,b]=(0,Z.useState)(null),[x,S]=(0,Z.useState)(!1),[C,w]=(0,Z.useState)(null),T=(0,Z.useRef)(null),E=(0,Z.useRef)(null),D=(0,Z.useRef)(null),O=(0,Z.useMemo)(()=>uS(o),[o]),k=JSON.stringify(O),A=(0,Z.useCallback)(t=>$S(e,O,t),[e,O]),j=uo(`lab-matrix:${e}:${k}`,[e,k],A,{isEmpty:e=>e.verdicts.length===0,pollMs:6e4,enabled:t,pauseWhenHidden:!0}),M=(0,Z.useCallback)(()=>{T.current?.abort(),T.current=null,d(null),p(null),h(!1)},[]),N=(0,Z.useCallback)(()=>{D.current=null,E.current?.abort(),E.current=null,_(null),b(null),w(null),S(!1)},[]);(0,Z.useEffect)(()=>{T.current?.abort()},[j.data]),(0,Z.useEffect)(()=>()=>{T.current?.abort(),E.current?.abort()},[]);let P=(0,Z.useCallback)(e=>{N(),M(),s(e)},[N,M]),F=(0,Z.useCallback)(e=>{N(),l(e),t&&Yt(s_(e))},[t,N]);(0,Z.useEffect)(()=>{let e=()=>{let e=l_();e&&l(t=>t.inbound===e.inbound&&t.upstream===e.upstream?t:e)};return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]);let I=u!==null&&u.baseData===j.data&&u.queryKey===k?u:null,L=f!==null&&f.baseData===j.data&&f.queryKey===k?f.message:null,R=(0,Z.useMemo)(()=>{if(!t||!j.data?.status.projectionAvailable)return null;let e=j.data.status.verdictCount;return typeof e==`number`?e:j.data.verdicts.length+(I?.verdicts.length??0)},[t,j.data,I]);(0,Z.useEffect)(()=>{n?.(R)},[n,R]);let z=(0,Z.useMemo)(()=>j.data?[...j.data.verdicts,...I?.verdicts??[]]:[],[j.data,I]),B=(0,Z.useMemo)(()=>j.data?fS(z,j.data.subjects):[],[z,j.data]),V=_S(c),H=uC(e,(0,Z.useMemo)(()=>B.map(e=>e.subjectId),[B]),t&&V),U=(0,Z.useMemo)(()=>yS(B,H.pairs,c),[c,H.pairs,B]),ee=(0,Z.useMemo)(()=>{if(!V)return z;let e=new Set(U.map(e=>e.subjectId));return z.filter(t=>e.has(t.subjectId))},[z,U,V]),W=bS(c,U),te=(0,Z.useCallback)(async()=>{let t=I?.nextCursor??j.data?.nextCursor,n=j.data;if(!t||!n||m)return;T.current?.abort();let r=new AbortController;T.current=r;let a=k;p(null),h(!0);try{let i=await eC(e,O,t,r.signal);if(r.signal.aborted)return;d(e=>{let t=e?.baseData===n&&e.queryKey===a?e.verdicts:[];return{baseData:n,queryKey:a,verdicts:[...t,...i.verdicts],nextCursor:i.nextCursor,hasMore:i.hasMore}})}catch(e){r.signal.aborted||p({baseData:n,queryKey:a,message:hC(e,i(`lab.loadFailed`))})}finally{T.current===r&&(T.current=null,h(!1))}},[e,m,O,k,j.data,i,I]),G=(0,Z.useCallback)(async n=>{if(!t)return;E.current?.abort();let r=new AbortController;E.current=r,D.current=n.projectionKey,_(n),b(null),w(null),S(!0);try{let t=await nC(e,n,r.signal);!r.signal.aborted&&D.current===n.projectionKey&&b(t)}catch(e){!r.signal.aborted&&D.current===n.projectionKey&&w(hC(e,i(`lab.detailLoadFailed`)))}finally{E.current===r&&(E.current=null,!r.signal.aborted&&D.current===n.projectionKey&&S(!1))}},[t,e,i]),ne=j.refresh,K=(0,Z.useCallback)(()=>{N(),M(),ne({forceLoading:!0})},[N,ne,M]),re=t?g:null,q=I?I.hasMore:j.data?.hasMore??!1,J=[{value:``,label:i(`lab.filter.all`)},...Jx.map(e=>({value:e,label:i(dC[e])}))],Y=[{value:``,label:i(`lab.filter.all`)},...Yx.map(e=>({value:e,label:i(pC[e])}))],ie=[{value:``,label:i(`lab.filter.all`)},...(j.data?.subjects??[]).map(e=>({value:e.subjectId,label:`${pS(e.subjectId)} · ${e.subjectKind}`}))];if(j.state.showSkeleton)return(0,Q.jsx)(lb,{label:i(`lab.loading`),rows:5});let X=j.state.showError?hC(j.error,i(`lab.loadFailed`)):null,oe=j.data?.status,se=oe&&!oe.projectionAvailable,ce=oe?.projectionIncompatible===!0;return(0,Q.jsxs)(`div`,{className:`lab-page`,children:[(0,Q.jsx)(`div`,{className:`lab-toolbar`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:K,disabled:j.refreshing,children:[(0,Q.jsx)(ae,{}),i(`lab.refresh`)]})}),j.refreshing&&!j.state.showSkeleton&&(0,Q.jsx)(ub,{busy:!0,live:!X,children:i(`common.loading`)}),X&&(0,Q.jsx)($,{tone:`err`,children:X}),ce&&(0,Q.jsx)($,{tone:`err`,children:i(`lab.projectionIncompatible`)}),se&&!ce&&(0,Q.jsx)(fn,{title:i(`lab.projectionUnavailable`)}),se&&!ce&&(0,Q.jsx)(CS,{filter:c,evidence:`unverified`,resolution:{loading:!1,unresolved:0}}),j.data&&(0,Q.jsx)(yC,{community:j.data.community,locale:a}),j.data&&oe?.projectionAvailable&&!ce&&(0,Q.jsxs)(`div`,{className:`lab-layout`,children:[(0,Q.jsxs)(`div`,{className:`lab-main`,children:[(0,Q.jsx)(vC,{data:j.data,t:i,locale:a}),(0,Q.jsxs)(`div`,{className:`lab-filters`,children:[(0,Q.jsxs)(`div`,{className:`lab-filter-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`lab-filter-layer`,children:i(`lab.filter.layer`)}),(0,Q.jsx)(dn,{id:`lab-filter-layer`,value:o.layer,options:J,onChange:e=>P(t=>({...t,layer:e})),label:i(`lab.filter.layer`),portal:!1})]}),(0,Q.jsxs)(`div`,{className:`lab-filter-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`lab-filter-verdict`,children:i(`lab.filter.verdict`)}),(0,Q.jsx)(dn,{id:`lab-filter-verdict`,value:o.verdict,options:Y,onChange:e=>P(t=>({...t,verdict:e})),label:i(`lab.filter.verdict`),portal:!1})]}),(0,Q.jsxs)(`div`,{className:`lab-filter-field`,children:[(0,Q.jsx)(`label`,{htmlFor:`lab-filter-subject`,children:i(`lab.filter.subject`)}),(0,Q.jsx)(dn,{id:`lab-filter-subject`,value:o.subjectQuery,options:ie,onChange:e=>P(t=>({...t,subjectQuery:e})),label:i(`lab.filter.subject`),portal:!1})]}),(0,Q.jsx)(SS,{value:c,onChange:F})]}),(0,Q.jsx)(CS,{filter:c,evidence:W,resolution:H}),U.length===0?(0,Q.jsx)(fn,{title:i(`lab.empty`)}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`lab-matrix-block`,children:[(0,Q.jsx)(`h3`,{className:`lab-matrix-title`,children:i(`lab.matrixTitle`)}),(0,Q.jsx)(`div`,{className:`lab-matrix-scroll`,children:(0,Q.jsxs)(`table`,{className:`lab-matrix`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:i(`lab.col.subject`)}),(0,Q.jsx)(`th`,{children:i(`lab.subjectKind`)}),Jx.map(e=>(0,Q.jsx)(`th`,{children:i(fC[e])},e))]})}),(0,Q.jsx)(`tbody`,{children:U.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`subject`,title:e.subjectId,children:pS(e.subjectId)}),(0,Q.jsx)(`td`,{className:`kind`,children:e.subjectKind||y(a,`subjectKindUnknown`)}),Jx.map(t=>(0,Q.jsx)(`td`,{children:(0,Q.jsx)(_C,{rows:e.byLayer[t],t:i,selectedKey:re?.projectionKey??null,onSelect:e=>{G(e)}})},t))]},e.subjectId))})]})})]}),(0,Q.jsxs)(`div`,{className:`lab-matrix-block`,children:[(0,Q.jsx)(`h3`,{className:`lab-matrix-title`,children:i(`lab.verdictsTitle`)}),(0,Q.jsx)(`div`,{className:`lab-matrix-scroll`,children:(0,Q.jsxs)(`table`,{className:`lab-detail-table`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:i(`lab.col.subject`)}),(0,Q.jsx)(`th`,{children:i(`lab.col.layer`)}),(0,Q.jsx)(`th`,{children:i(`lab.col.suite`)}),(0,Q.jsx)(`th`,{children:i(`lab.col.verdict`)}),(0,Q.jsx)(`th`,{children:i(`lab.col.asOf`)})]})}),(0,Q.jsx)(`tbody`,{children:ee.map(e=>{let t=re?.projectionKey===e.projectionKey;return(0,Q.jsxs)(`tr`,{className:t?`selected`:``,children:[(0,Q.jsx)(`td`,{className:`mono`,title:e.subjectId,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"data-verdict-detail":e.projectionKey,"aria-pressed":t,"aria-label":y(a,`selectVerdict`,{subject:pS(e.subjectId)}),onClick:()=>{G(e)},children:pS(e.subjectId)})}),(0,Q.jsx)(`td`,{children:i(dC[e.evidenceLayer])}),(0,Q.jsx)(`td`,{className:`mono`,children:e.suiteId}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(gC,{verdict:e.verdict,caption:e.suiteId,label:i(pC[e.verdict])})}),(0,Q.jsx)(`td`,{children:mS(e.asOf,a)})]},e.projectionKey)})})]})})]}),L&&(0,Q.jsx)($,{tone:`err`,children:L}),q&&(0,Q.jsx)(`div`,{className:`lab-load-more`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:m,onClick:()=>{te()},children:i(m?`common.loading`:`lab.loadMore`)})})]})]}),re&&(0,Q.jsx)(bC,{verdict:re,detail:v,loading:x,error:C,t:i,locale:a,onClose:N})]})]})}var SC=[`catalog`,`combos`,`routing`,`compatibility`];function CC(e){return e===`catalog`?`models`:`models/${e}`}function wC(e=window.location.hash){let t=Jt(qt(e)).path;return t===`models/combos`||t===`models/combos/jev-auto`||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 TC(e){Xt(CC(e))}function EC(e){return`models-tab-${e}`}function DC(e){return`models-panel-${e}`}var OC={catalog:`models.tab.catalog`,combos:`models.tab.combos`,routing:`models.tab.routing`,compatibility:`models.tab.compatibility`};function kC({tab:e,onSelect:t,meta:r}){let i=n(),a=(0,Z.useRef)(null);a.current===null&&(a.current=new Map);let o=e=>{t(e),window.requestAnimationFrame(()=>{a.current.get(e)?.focus({preventScroll:!0})})},s=t=>{let n=SC.indexOf(e),r=null;t.key===`ArrowLeft`?r=(n-1+SC.length)%SC.length:t.key===`ArrowRight`?r=(n+1)%SC.length:t.key===`Home`?r=0:t.key===`End`&&(r=SC.length-1),r!==null&&(t.preventDefault(),o(SC[r]))};return(0,Q.jsx)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":i(`models.tabsLabel`),children:SC.map(t=>{let n=t===e,c=r?.[t];return(0,Q.jsxs)(`button`,{ref:e=>{e?a.current.set(t,e):a.current.delete(t)},type:`button`,role:`tab`,id:EC(t),"aria-selected":n,"aria-controls":DC(t),tabIndex:n?0:-1,className:`page-tab${n?` page-tab--active`:``}`,onClick:()=>o(t),onKeyDown:s,children:[i(OC[t]),c?(0,Q.jsx)(`span`,{className:`section-tab-meta`,children:c}):null]},t)})})}function AC({summary:e,apiBase:t,onSaved:r}){let i=n(),[a,o]=(0,Z.useState)(!1),[s,c]=(0,Z.useState)(null),l=e?.fastOptIn?.enabled;if(s&&l!==s.from&&c(null),!e?.fastOptIn)return null;let u=e.fastOptIn.enabled,d=s&&s.from===u?s.value:u,f=async n=>{if(!(a||n===d)){o(!0);try{await vn(await fetch(`${t}/api/providers?name=${encodeURIComponent(e.name)}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({fastEnabled:n})}),i(`models.fastSaveFailed`)),c({value:n,from:u}),r(!0,i(n?`models.fastEnabled`:`models.fastDisabled`))}catch(e){r(!1,e instanceof Error?e.message:i(`models.fastSaveFailed`))}finally{o(!1)}}};return(0,Q.jsxs)(`div`,{className:`row models-provider-hint`,children:[(0,Q.jsx)(`span`,{className:`muted text-label`,children:i(`models.fastProvider`)}),(0,Q.jsx)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":i(`models.fastProvider`),children:[!1,!0].map(e=>(0,Q.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":d===e,className:`btn btn-sm${d===e?` btn-primary`:` btn-ghost`}`,disabled:a,onClick:()=>void f(e),children:i(e?`models.newPolicy_on`:`models.newPolicy_off`)},String(e)))}),(0,Q.jsx)(`span`,{className:`muted text-caption`,children:i(`models.fastProviderHint`)})]})}function jC(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)e.disabled===!0?n.delete(e.name):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 MC({liveModels:e,discovery:t,showFailureBadge:r=!0}){let i=n(),a=e&&t?.status===`failed`?t:void 0;return(0,Q.jsxs)(`div`,{className:`row muted text-label leading-body`,role:`status`,style:{alignItems:`flex-start`,gap:8,padding:`6px 0`},children:[(0,Q.jsx)(De,{width:15,height:15,"aria-hidden":`true`,style:{flexShrink:0,marginTop:2}}),(0,Q.jsxs)(`span`,{children:[a&&r&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`badge badge-amber`,children:i(`models.discoveryFailedBadge`)}),` `]}),a?`${es(i,a)} `:`${i(e?`models.emptyDiscovery`:`models.emptyDiscoveryDisabled`)} `,(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>Xt(`providers`),children:i(`models.openProviderSettings`)})]})]})}function NC(){let e=n();return(0,Q.jsxs)(`div`,{className:`row muted text-label leading-body`,role:`status`,style:{alignItems:`flex-start`,gap:8,padding:`6px 0`},children:[(0,Q.jsx)(De,{width:15,height:15,"aria-hidden":`true`,style:{flexShrink:0,marginTop:2}}),(0,Q.jsxs)(`span`,{children:[`${e(`models.discoveryFailedDependency`,{control:e(`pws.liveModels`)})} `,(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>Xt(`providers`),children:e(`models.openProviderSettings`)})]})]})}var PC=`ocx.models.settingsOpen.v1`;function FC(e){return e||(typeof localStorage>`u`?void 0:localStorage)}function IC(e){try{return FC(e)?.getItem(PC)===`1`}catch{return!1}}function LC(e,t){try{FC(t)?.setItem(PC,e?`1`:`0`)}catch{}}var RC={default:`models.pickerOrder.default`,alphabetical:`models.pickerOrder.alphabetical`,provider:`models.pickerOrder.provider`,"most-used":`models.pickerOrder.mostUsed`,custom:`models.pickerOrder.custom`};function zC(e,t){let n=e(`models.settingsPanel.off`),r=[];t.multiAgentMode&&r.push({id:`subagent`,label:e(`models.v2Label`),value:e(`models.v2Mode_${t.multiAgentMode}`)}),typeof t.v2Threads==`number`&&r.push({id:`threads`,label:e(`models.v2ThreadsLabel`),value:String(t.v2Threads)}),t.multiAgentMode===`v2`&&t.keepNativeOnV1&&r.push({id:`keep-native`,label:e(`models.keepNativeOnV1`),value:``}),r.push({id:`shadow`,label:e(`models.shadowCallIntercept`),value:t.shadowEnabled&&t.shadowModel?t.shadowModel:n}),t.autoReviewEnabled&&r.push({id:`auto-review`,label:e(`models.autoReviewOverride`),value:t.autoReviewModel||e(`models.autoReviewPending`)}),r.push({id:`window`,label:e(`models.contextCapLabel`),value:t.windowOn?vs(t.windowValue):n});let i=RC[t.pickerMode];return r.push({id:`order`,label:e(`models.pickerOrder.label`),value:i?e(i):t.pickerMode}),t.newModelsOff&&r.push({id:`new-models`,label:e(`models.newPolicyGlobal`),value:``}),t.aliasesOn&&r.push({id:`aliases`,label:e(`models.useDefaultAliasesGlobal`),value:``}),r}function BC({title:e,attentionLabel:t,summary:n,warn:r,children:i,storage:a}){let[o,s]=(0,Z.useState)(()=>IC(a)),[c,l]=(0,Z.useState)(!1),u=o||r&&!c;return(0,Q.jsxs)(`details`,{className:`models-settings`,open:u,onToggle:e=>{let t=e.currentTarget.open;t!==u&&(s(t),!t&&r&&l(!0),LC(t,a))},children:[(0,Q.jsxs)(`summary`,{className:`models-settings-summary`,children:[(0,Q.jsx)(`span`,{className:`models-settings-title`,children:e}),r&&(0,Q.jsx)(`span`,{className:`models-settings-warn`,role:`img`,"aria-label":t,title:t}),(0,Q.jsx)(`span`,{className:`models-settings-state`,children:n.map(e=>(0,Q.jsxs)(`span`,{className:`models-settings-kv`,"data-item":e.id,children:[(0,Q.jsx)(`span`,{className:`models-settings-k`,children:e.label}),e.value&&(0,Q.jsx)(`span`,{className:`models-settings-v`,children:e.value})]},e.id))})]}),(0,Q.jsx)(`div`,{className:`models-settings-body`,children:i})]})}function VC({count:e,label:t}){return e===0?null:(0,Q.jsx)(`span`,{className:`models-chip mono text-caption models-custom-summary`,children:t})}function HC({text:e}){return(0,Q.jsx)(pn,{content:e,side:`top`,maxWidth:360,children:(0,Q.jsxs)(`span`,{className:`models-info-hint`,children:[(0,Q.jsx)(De,{width:14,height:14,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`sr-only`,children:e})]})})}function UC({label:e,hint:t,busy:n,muted:r=!0,caption:i,children:a}){let o=[`models-row-label`,r?`muted`:``,i?`text-caption`:`text-control`].filter(Boolean).join(` `);return(0,Q.jsxs)(`div`,{className:`models-control-row`,"aria-busy":n||void 0,children:[(0,Q.jsxs)(`span`,{className:o,children:[e,t?(0,Q.jsxs)(Q.Fragment,{children:[` `,t]}):null]}),(0,Q.jsx)(`div`,{className:`models-row-actions`,children:a})]})}function WC({shadowCall:e,saving:t,modelOptions:r,onSave:i}){let a=n(),o=a(`models.shadowCallInterceptHint`,{models:Sn(e?.sourceModels)});return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(UC,{label:a(`models.shadowCallIntercept`),hint:(0,Q.jsx)(pn,{content:o,side:`top`,maxWidth:320,children:(0,Q.jsx)(`span`,{style:{cursor:`help`},"aria-label":o,children:(0,Q.jsx)(De,{width:13,height:13,"aria-hidden":`true`})})}),busy:!e,children:[(0,Q.jsx)(`code`,{className:`text-caption models-shadow-warning`,style:{opacity:.6},children:a(`models.shadowCallOriginal`,{models:En(e?.sourceModels,a(`shadowCall.memoryLabel`))})}),(0,Q.jsx)(ln,{on:e?.enabled??!1,onClick:()=>i({enabled:!e?.enabled}),disabled:!e||t,label:a(`models.shadowCallIntercept`)}),(0,Q.jsx)(`div`,{className:`models-shadow-model-slot`,children:(0,Q.jsx)(dn,{value:e?.model??``,options:r,onChange:e=>i({model:e}),disabled:!e||t||!e.enabled,label:a(`models.shadowCallIntercept`)})})]}),(0,Q.jsx)(Ga,{className:`models-shadow-sources`,options:e?.sourceModelOptions,sourceModels:e?.sourceModels,disabled:!e?.enabled,saving:t,onChange:e=>i({sourceModels:e})})]})}function GC(e,t){if(!e)return null;let n=new Date(e);return Number.isNaN(n.getTime())?null:new Intl.DateTimeFormat(t,{dateStyle:`medium`,timeStyle:`short`}).format(n)}function KC({connected:e,catalogSyncedAt:t}){let{locale:n,t:i}=r(),a=GC(t,n),o=e?[{id:`saved`,chip:i(`models.delivery.chip.savedHub`),title:i(`models.delivery.savedHub.title`),body:i(`models.delivery.savedHub.body`)},{id:`synced`,chip:a?i(`models.delivery.chip.synced`,{time:a}):i(`models.delivery.chip.syncedUnknown`),title:i(`models.delivery.synced.title`),body:a?i(`models.delivery.synced.bodyAt`,{time:a}):i(`models.delivery.synced.bodyUnknown`)}]:[{id:`saved`,chip:i(`models.delivery.chip.saved`),title:i(`models.delivery.saved.title`),body:i(`models.delivery.saved.body`)}];return o.push({id:`loaded`,chip:i(`models.delivery.chip.loaded`),title:i(`models.delivery.loaded.title`),body:i(`models.delivery.loaded.body`)}),(0,Q.jsxs)(`details`,{className:`models-delivery`,children:[(0,Q.jsxs)(`summary`,{children:[(0,Q.jsx)(`span`,{className:`models-delivery-title`,children:i(`models.delivery.title`)}),(0,Q.jsx)(`span`,{className:`models-delivery-flow`,children:o.map(e=>e.chip).join(` → `)})]}),(0,Q.jsx)(`ol`,{className:`models-delivery-steps`,children:o.map(e=>(0,Q.jsxs)(`li`,{"data-step":e.id,children:[(0,Q.jsx)(`strong`,{children:e.title}),(0,Q.jsx)(`p`,{children:e.body})]},e.id))}),(0,Q.jsx)(`p`,{className:`models-delivery-hint`,children:i(`models.delivery.hint`)})]})}function qC(e,t,n){let[r,i]=(0,Z.useState)({apiBase:e,data:null,saving:!1}),a=r.apiBase===e?r.data:null,o=r.apiBase===e&&r.saving,s=(0,Z.useRef)({read:null,write:null,generation:0,apiBase:e});(0,Z.useLayoutEffect)(()=>{let t=s.current;return t.apiBase=e,t.generation++,()=>{t.generation++,t.read?.controller.abort(),t.read?.clear(),t.read=null,t.write?.controller.abort(),t.write?.clear(),t.write=null}},[e]);let c=(0,Z.useCallback)(async({reconcile:t=!1}={})=>{let n=s.current;if(n.write&&!t)return null;n.read?.controller.abort(),n.read?.clear();let r=M(15e3),a=n.generation;n.read=r;try{let o=await yn(await fetch(`${e}/api/auto-review-settings`,{signal:r.signal}));return!o||typeof o.enabled!=`boolean`||typeof o.model!=`string`?null:!r.signal.aborted&&n.apiBase===e&&n.generation===a&&n.read===r&&(!n.write||t)?(i({apiBase:e,data:o,saving:n.write!==null}),o):null}catch{return null}finally{r.clear(),n.read===r&&(n.read=null)}},[e]);return{data:a,saving:o,load:c,save:(0,Z.useCallback)(async r=>{let l=s.current;if(!a||o||l.apiBase!==e||l.write)return;let u=a,d=M(15e3);l.write=d;let f=++l.generation;l.read?.controller.abort(),l.read?.clear(),l.read=null,i({apiBase:e,data:{...u,...r},saving:!0});try{let a=await vn(await fetch(`${e}/api/auto-review-settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},signal:d.signal,body:JSON.stringify(r)}),t(`models.saveFailed`));if(!a||a.ok!==!0||typeof a.enabled!=`boolean`||typeof a.model!=`string`)throw Error(t(`models.saveFailed`));if(l.apiBase!==e||l.generation!==f)return;i({apiBase:e,data:{enabled:a.enabled,model:a.model},saving:!0}),(!a.catalogRefresh||a.catalogRefresh.status!==`committed`)&&n(!1,t(`codexAuth.catalogRefreshPending`))}catch(r){if(l.apiBase===e&&l.generation===f){let a=await c({reconcile:!0});if(l.apiBase!==e||l.generation!==f)return;i({apiBase:e,data:a??u,saving:!0}),n(!1,r instanceof Error&&r.message?r.message:t(`models.saveFailed`))}}finally{d.clear(),l.write===d&&(l.write=null),l.apiBase===e&&l.generation===f&&i(t=>t.apiBase===e?{...t,saving:!1}:t)}},[e,a,o,t,n,c])}}function JC({apiBase:e,publishFeedback:t,t:n}){let[r,i]=(0,Z.useState)(null),[a,o]=(0,Z.useState)(!1);return{shadowCall:r,shadowCallSaving:a,loadShadowCall:(0,Z.useCallback)(async()=>{let t=M(15e3);try{let n=await yn(await fetch(`${e}/api/shadow-call-settings`,{signal:t.signal}));n&&i(n)}catch{}finally{t.clear()}},[e]),saveShadowCall:async s=>{if(!r||a)return;let c=r;o(!0),i({...r,...s});try{let r=await fetch(`${e}/api/shadow-call-settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(s)});if(!r.ok){i(c),t(!1,n(ss((await r.json().catch(()=>null))?.code)));return}let a=await r.json().catch(()=>null);a&&typeof a.enabled==`boolean`&&i(a)}catch{i(c),t(!1,n(`models.networkError`))}finally{o(!1)}}}}var YC={catalog:`models.subtitle`,combos:`models.subtitle.combos`,routing:`models.subtitle.routing`,compatibility:`models.subtitle.compatibility`};function XC({apiBase:e,restartEpoch:t=0,connected:r=!1,catalogSyncedAt:i,reportRestart:a}){let[o,s]=(0,Z.useState)(null),c=(0,Z.useRef)(!0);(0,Z.useEffect)(()=>(c.current=!0,()=>{c.current=!1}),[]);let l=(0,Z.useRef)(null),u=(0,Z.useRef)(0),d=(0,Z.useRef)(e),f=(0,Z.useCallback)(()=>{u.current++,l.current?.controller.abort(),l.current?.clear(),l.current=null},[]),p=(0,Z.useCallback)(async()=>{if(!c.current||d.current!==e)return;f();let t=u.current,n=M(15e3);l.current=n;try{let r=await Dv(e,{signal:n.signal});if(n.signal.aborted||!c.current||d.current!==e||t!==u.current||l.current!==n)return;s(r.state)}finally{n.clear(),l.current===n&&(l.current=null)}},[e,f]),{restarting:m,restart:h}=Mv(e,{onSettled:()=>{p()},report:a});(0,Z.useEffect)(()=>(d.current=e,s(null),p(),f),[e,f,p,t]);let[g,_]=(0,Z.useState)(wC),[v,y]=(0,Z.useState)(()=>new Set([wC()])),b=(0,Z.useCallback)(e=>{_(e),y(t=>t.has(e)?t:new Set([...t,e]))},[]);(0,Z.useEffect)(()=>{let e=()=>b(wC());return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[b]);let x=(0,Z.useCallback)(e=>{TC(e),b(e)},[b]),S=g===`catalog`,[C,w]=(0,Z.useState)(null),[T,E]=(0,Z.useState)(null),[D,O]=(0,Z.useState)(null),k=n(),A=`ocx.models.catalog.v1:${e}`,j=(0,Z.useMemo)(()=>io(A),[A]),[N,P]=(0,Z.useState)(()=>j?.models??[]),[F,I]=(0,Z.useState)(()=>j?.providers??[]),[L,R]=(0,Z.useState)(()=>new Set(j?.disabled??[])),[z,B]=(0,Z.useState)(()=>j?.selectedModels??null),[V,H]=(0,Z.useState)({}),[U,ee]=(0,Z.useState)({}),[W,te]=(0,Z.useState)({}),[G,ne]=(0,Z.useState)(()=>j?.contextCaps??{}),[K,re]=(0,Z.useState)(()=>j?.contextCapValues??{}),[q,J]=(0,Z.useState)(()=>j?.contextCapValue??35e4),Y=`${A}:picker-order`,ie=(0,Z.useMemo)(()=>{let e=io(Y);return T_(e)?e:void 0},[Y]),[X,oe]=(0,Z.useState)(null),[se,ce]=(0,Z.useState)(!1),ue=(0,Z.useRef)(null),de=(0,Z.useRef)(0),pe=uo(Y,[e],(0,Z.useCallback)(async t=>{let n=await vn(await fetch(`${e}/api/subagent-models`,{signal:t}));if(!T_(n))throw Error(`picker settings payload missing`);if(t.aborted)throw Error(`picker settings request aborted`);return co(Y,n),n},[e,Y]),{isEmpty:()=>!1,enabled:S,deadlineMs:15e3,initialData:ie}),me=pe.state.data,he=X??j_(me?.pickerAvailable??[],me?.pickerOrder??[],me?.pickerOrderMode);(0,Z.useLayoutEffect)(()=>(de.current++,oe(null),ce(!1),()=>{de.current++,ue.current?.controller.abort(),ue.current?.clear(),ue.current=null}),[e,S]),(0,Z.useLayoutEffect)(()=>{S&&X===null&&he===`custom`&&oe(`custom`)},[S,X,he]);let[ge,_e]=(0,Z.useState)(``),[ve,ye]=(0,Z.useState)(!1),[be,xe]=(0,Z.useState)({}),[Se,we]=(0,Z.useState)({}),Te=Ss(),[Ee,ke]=(0,Z.useState)(()=>Te??new Set),Ae=(0,Z.useRef)(Te===null),[je,Me]=(0,Z.useState)(``),[Pe,Fe]=(0,Z.useState)([]),[Ie,Le]=(0,Z.useState)(!1),[Re,Be]=(0,Z.useState)(0),Ve=(0,Z.useCallback)((e,t)=>{Le(e),Me(t),Be(e=>e+1)},[]),{data:He,saving:Ue,load:We,save:Ge}=qC(e,k,Ve);(0,Z.useEffect)(()=>{S||We()},[e,S,We]),(0,Z.useEffect)(()=>{if(!je)return;let e=setTimeout(()=>Me(``),Ie?6e3:8e3);return()=>clearTimeout(e)},[je,Ie,Re]);let[Ke,qe]=(0,Z.useState)(!1),Je=(0,Z.useRef)(!1),Xe=(0,Z.useRef)(!1),Ze=(0,Z.useRef)(0),Qe=(0,Z.useRef)(!1),$e=sb(e,{onQueued:()=>{++Ze.current,Me(``)},onBusy:e=>{++Ze.current,Qe.current=!1,Xe.current=e,Je.current=e,qe(e)},onResponse:e=>{let t=Go(e);t!==void 0&&Fe(t)},refresh:e=>br(!0,e),onSettled:e=>{Le(!e),Me(k(e??`models.applied`))}}),et=(e,t,n,r,i)=>$e.visible(t,n,r,Zo(e,t,n,r,i)),[tt,nt]=(0,Z.useState)(null),[rt,it]=(0,Z.useState)({}),[at,ot]=(0,Z.useState)(null),[st,ct]=(0,Z.useState)({providers:{},models:{},defaults:{global:!1,providers:{}}}),[lt,ut]=(0,Z.useState)(!1),[dt,ft]=(0,Z.useState)(null),[pt,mt]=(0,Z.useState)(!0),[ht,gt]=(0,Z.useState)(!1),[_t,vt]=(0,Z.useState)(``),yt=(0,Z.useRef)(!1),bt=(0,Z.useRef)(0),xt=(0,Z.useRef)(0),[St,Ct]=(0,Z.useState)(``),[wt,Tt]=(0,Z.useState)(!1),[Et,Dt]=(0,Z.useState)(!1),[Ot,kt]=(0,Z.useState)(null),[At,jt]=(0,Z.useState)(!1),[Mt,Nt]=(0,Z.useState)(null),[Pt,Ft]=(0,Z.useState)(null),It=(0,Z.useRef)(null),[Lt,Rt]=(0,Z.useState)(null),[zt,Bt]=(0,Z.useState)(!1),[Vt,Ht]=(0,Z.useState)(null),[Ut,Wt]=(0,Z.useState)(null),[Gt,qt]=(0,Z.useState)(!1),Jt=(0,Z.useRef)(null),Yt=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>()=>{Jt.current?.controller.abort(),Jt.current?.clear(),Jt.current=null},[]);let Xt=(0,Z.useRef)(null),Zt=(0,Z.useCallback)(async t=>{let n=await yn(await fetch(`${e}/api/aliases`,{signal:t}));n&&!t?.aborted&&ct(n)},[e]);(0,Z.useEffect)(()=>{let e=new AbortController;return Zt(e.signal),()=>e.abort()},[Zt]);let Qt={apiBase:e,t:k,reloadAliases:Zt,publishFeedback:Ve},$t=e=>Nv(e,st.providers[e]??``,Qt),en=(e,t)=>Pv(e,t,st.models[e]?.[t]?.alias??``,Qt),tn=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 Zt()},[nn,rn]=(0,Z.useState)(`add`),[an,on]=(0,Z.useState)(``),[sn,cn]=(0,Z.useState)(``),[un,mn]=(0,Z.useState)(``),[hn,gn]=(0,Z.useState)(``),[_n,bn]=(0,Z.useState)(``),[xn,Sn]=(0,Z.useState)(!1),[Cn,wn]=(0,Z.useState)([`text`]),[Tn,En]=(0,Z.useState)(!1),[Dn,On]=(0,Z.useState)([]),kn=(0,Z.useRef)(!1),[An,jn]=(0,Z.useState)(!1),[Mn,Nn]=(0,Z.useState)(``),[Pn,Fn]=(0,Z.useState)(null),[In,Ln]=(0,Z.useState)([]),[Rn,zn]=(0,Z.useState)(``),[Bn,Vn]=(0,Z.useState)(``),[Hn,Un]=(0,Z.useState)({}),[Wn,Gn]=(0,Z.useState)({contextWindow:null,modelContextWindows:{}}),[Kn,qn]=(0,Z.useState)(new Set),[Jn,Yn]=(0,Z.useState)(!1),[Xn,Zn]=(0,Z.useState)(!1),[Qn,$n]=(0,Z.useState)(``),[er,tr]=(0,Z.useState)(null),rr=(0,Z.useRef)(null),{shadowCall:ir,shadowCallSaving:ar,loadShadowCall:or,saveShadowCall:sr}=JC({apiBase:e,publishFeedback:Ve,t:k}),[cr,lr]=(0,Z.useState)(null);(0,Z.useEffect)(()=>()=>{rr.current&&clearTimeout(rr.current)},[]);let ur=(0,Z.useMemo)(()=>bs(N,L,z??{},k),[N,L,z,k]),fr=(0,Z.useMemo)(()=>{let e=new Set(ur.map(e=>e.value));return nr(N.filter(t=>e.has(t.namespaced)),ir?.model,ir?.sourceModels)},[N,ir?.model,ir?.sourceModels,ur]),mr=(0,Z.useMemo)(()=>[{value:``,label:`—`},...xs(ur,N,He?.model)],[N,ur,He?.model]),hr=(0,Z.useCallback)(async()=>{if(yt.current)return;let t=++bt.current,n=xt.current,r=()=>t===bt.current&&n===xt.current,i=M(15e3);try{let t=await fetch(`${e}/api/v2`,{signal:i.signal});if(!r())return;if(!(t.headers.get(`content-type`)??``).includes(`application/json`)){nt(null);return}let n=await yn(t);if(!r())return;if(!n||typeof n.enabled!=`boolean`){nt(null);return}nt({enabled:n.enabled,agentsMaxThreadsConflict:n.agentsMaxThreadsConflict===!0,maxConcurrentThreadsPerSession:typeof n.maxConcurrentThreadsPerSession==`number`?n.maxConcurrentThreadsPerSession:null,multiAgentMode:n.multiAgentMode===`v1`||n.multiAgentMode===`v2`?n.multiAgentMode:`default`,keepNativeChatGptOnV1:n.keepNativeChatGptOnV1===!0})}catch{r()&&nt(null)}finally{i.clear(),mt(!1)}},[e]),gr=(0,Z.useCallback)(async t=>{let n=Ze.current,[r,i,a,o]=await Promise.all([fetch(`${e}/api/models`,{signal:t}),fetch(`${e}/api/provider-context-caps`,{signal:t}),fetch(`${e}/api/providers`,{signal:t}),Yo(e,fetch,t)]),[s,c,l]=await Promise.all([vn(r),vn(i),vn(a)]);if(s===void 0||c===void 0||l===void 0)throw Error(`models payload missing`);if(t.aborted)throw Error(`models request aborted`);let u=ys(s),d=typeof c.value==`number`&&Number.isFinite(c.value)&&c.value>0?c.value:typeof c.cap==`number`&&Number.isFinite(c.cap)&&c.cap>0?c.cap:void 0,f=d===void 0?35e4:d,p={models:s,providers:l,selectedModels:o,disabled:[...u],contextCaps:c.caps??{},contextCapValues:c.values??c.caps??{},contextCapValue:f};return n===Ze.current&&co(A,p),p},[e,A]),_r=(0,Z.useCallback)(e=>{let t=jC(e.models,e.providers);lr(e=>e!==null&&!t.some(t=>t.provider===e)?null:e),P(e.models),I(e.providers),R(new Set(e.disabled)),B(e.selectedModels),J(e.contextCapValue),ne(e.contextCaps),re(e.contextCapValues??e.contextCaps)},[]),vr=uo(A,[e],async e=>{let t=Ze.current,n=await gr(e);if(e.aborted)throw Error(`models request aborted`);return!Xe.current&&t===Ze.current&&_r(n),n},{isEmpty:()=>!1,pollMs:1e4,initialData:j??void 0,enabled:S,deadlineMs:6e4}),yr=vr.state,br=(0,Z.useCallback)(async(e=!1,t)=>{if(Qe.current&&!e)return!1;Qe.current=!0;let n=++Ze.current;try{let e=await gr(t??new AbortController().signal);return $o(n,Ze.current)?(_r(e),Kt(A,e),pe.refresh(),!0):!1}catch{return!1}finally{$o(n,Ze.current)&&(Qe.current=!1)}},[_r,A,gr,pe.refresh]),xr=(0,Z.useCallback)(()=>{let e=Xt.current;Nt(null),Ht(null),Wt(null),qt(!1),window.setTimeout(()=>{e?.isConnected&&e.focus()},0)},[]),Sr=(0,Z.useCallback)(()=>{Yt.current||xr()},[xr]),Cr=(0,Z.useCallback)(async t=>{let n=Mt;if(!n||Yt.current)return;let r=M(6e4);Jt.current=r,Yt.current=!0,Bt(!0),Ht(null);let i=Ut?.confirmed===!0&&(t===void 0||t===Ut.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 vn(s,k(`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(k(`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)};P(e=>e.map(e=>e.namespaced===n.namespaced?{...e,...r}:e)),Nt({...n,...r}),qt(r.displayName===void 0)}if(!s.ok)throw Error(c.error||k(`models.displayNameSaveFailed`));o=!0}if(!await br(!0,r.signal))throw Error(k(`models.loadFail`));r.signal.throwIfAborted(),Ve(!0,k(i?t===null||t===void 0&&Ut?.value===null?`models.displayNameResetDone`:`models.displayNameSaved`:`models.displayNameReloaded`)),xr()}catch(e){if(Jt.current!==r)return;let n=!a||r.signal.aborted;n&&!i&&qt(!0),Wt(i||n||o?{value:o||n?void 0:t,confirmed:i}:null),Ht(i?k(`models.displayNameSavedRefreshFailed`):n||o?k(`models.displayNameOutcomeUnknown`):e instanceof Error&&e.message?e.message:k(`models.displayNameSaveFailed`))}finally{r.clear(),Jt.current===r&&(Jt.current=null,Yt.current=!1,Bt(!1))}},[e,Mt,Ut,xr,br,Ve,k]);(0,Z.useEffect)(()=>{if(!S)return;let e=window.setTimeout(()=>{or(),We(),hr(),Gr(),Kr()},0),t=ba(()=>{yt.current||hr()},1e4);return()=>{window.clearTimeout(e),t()}},[S,or,We,hr]);let wr=(0,Z.useMemo)(()=>jC(N,F),[N,F]),Tr=N.length>0||yr.data!==void 0,Er=e=>{let t=[...new Set([...e.rows.map(e=>e.id),...e.configuredModels,...Object.keys(e.modelContextWindows??{})])].sort(),n=t[0]??``;Fn(e.provider),Ln(t),zn(n);let r=e.contextWindow?String(e.contextWindow):``,i=Object.fromEntries(Object.entries(e.modelContextWindows??{}).map(([e,t])=>[e,String(t)]));Vn(r),Un(i),Gn({contextWindow:e.contextWindow??null,modelContextWindows:Object.fromEntries(Object.entries(e.modelContextWindows??{}).map(([e,t])=>[e,t]))}),qn(new Set),Yn(!1),$n(``)},Dr=e=>{zn(e)},Or=async()=>{if(!Pn)return;let t=ws(Bn);if(!wr.find(e=>e.provider===Pn)){$n(k(`models.contextSaveFailed`));return}if(Jn&&t===void 0){$n(k(`models.contextInvalid`));return}let n=Object.create(null);for(let e of Kn){let t=ws(Bv(Hn,e)??``);if(t===void 0){$n(k(`models.contextInvalid`));return}t!==(Bv(Wn.modelContextWindows,e)??null)&&(n[e]=t)}let r=Jn&&t!==Wn.contextWindow;if(!r&&Object.keys(n).length===0)Fn(null),Ve(!0,k(`models.contextUnchanged`));else{Zn(!0),$n(``);try{let i={};r&&(i.contextWindow=t),Object.keys(n).length>0&&(i.modelContextWindows=n),await vn(await fetch(`${e}/api/providers?name=${encodeURIComponent(Pn)}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify(i)}),k(`models.contextSaveFailed`))}catch(e){$n(e instanceof Error?e.message:k(`models.contextSaveFailed`));return}finally{Zn(!1)}Fn(null),Ve(!0,k(`models.contextSaved`)),await br(!0)}};(0,Z.useEffect)(()=>{if(!Ae.current||wr.length===0)return;Ae.current=!1;let e=new Set(wr.map(e=>e.provider));ke(e),Cs(e)},[wr]);let kr=(0,Z.useMemo)(()=>z?N.filter(e=>et(z,e.provider,e.id,e.native===!0,L.has(e.namespaced))).length:0,[L,N,z,$e.overrides]),Ar=(0,Z.useMemo)(()=>({catalog:Tr?k(`models.active`,{active:kr,total:N.length}):void 0,combos:C===null?void 0:String(C),routing:T===null?void 0:String(T),compatibility:D===null?void 0:String(D)}),[Tr,C,D,kr,N.length,T,k]),jr=async(e,t,n,r)=>{(!Je.current||$e.isRunning())&&$e.enqueue(e,t,n,r)},Mr=async t=>{qe(!0),Je.current=!0,Me(``);let n=G[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 vn(r,k(`models.capSaveFailed`));ne(e?.caps??{}),re(e?.values??e?.caps??{}),Le(!0),Me(k(`models.capApplied`)),await br(!0)}catch(e){Le(!1),Me(e instanceof Error?e.message:k(`models.capSaveFailed`))}}catch{Le(!1),Me(k(`models.networkError`))}finally{qe(!1),Je.current=!1}},Nr=e=>{ke(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),Cs(n),n})},Pr=e=>{ke(()=>{let t=e?new Set(wr.map(e=>e.provider)):new Set;return Cs(t),t})},Fr=async t=>{qe(!0),Je.current=!0,Me(``);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 vn(n,k(`models.capSaveFailed`));typeof e?.value==`number`&&Number.isFinite(e.value)&&e.value>0&&J(e.value),ne(e?.caps??{}),re(e?.values??e?.caps??{}),Le(!0),Me(k(`models.capApplied`)),await br(!0)}catch(e){Le(!1),Me(e instanceof Error?e.message:k(`models.capSaveFailed`))}}catch{Le(!1),Me(k(`models.networkError`))}finally{qe(!1),Je.current=!1}},Ir=(0,Z.useMemo)(()=>{let e=wr.filter(e=>!e.native);return e.length>0&&e.every(e=>G[e.provider]===q)&&Object.keys(G).every(e=>G[e]===q)},[wr,G,q]),Lr=e=>{!Number.isSafeInteger(e)||e<=0||Fr(Ir?{value:e,setAll:!0}:{value:e})},Rr=(e,t)=>{if(t===`custom`){xe(t=>({...t,[e]:!0})),we(t=>({...t,[e]:String(G[e]??K[e]??q)}));return}xe(t=>({...t,[e]:!1}));let n=Number(t);Number.isSafeInteger(n)&&n>0&&n!==G[e]&&Fr({provider:e,enabled:!0,value:n})},zr=e=>{let t=Number((Se[e]??``).replace(/[_,\s]/g,``));!Number.isSafeInteger(t)||t<=0?Ve(!1,k(`models.capSaveFailed`)):(xe(t=>({...t,[e]:!1})),Fr({provider:e,enabled:!0,value:t}))},Br=e=>{if(e===`custom`){ye(!0),_e(String(q));return}ye(!1);let t=Number(e);Number.isSafeInteger(t)&&t>0&&t!==q&&Lr(t)},Vr=()=>{let e=Number(ge.replace(/[_,\s]/g,``));!Number.isSafeInteger(e)||e<=0?Ve(!1,k(`models.capSaveFailed`)):(ye(!1),Lr(e))},Hr=()=>{Fr({setAll:!Ir})},Ur=async t=>{if(tt&&!yt.current){gt(!0),yt.current=!0,xt.current++,vt(``),Me(``);try{let n=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});try{let e=await vn(n,k(`models.saveFailed`));if(!e||typeof e.enabled!=`boolean`){Le(!1),Me(k(`models.saveFailed`));return}nt({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}),Le(!0),Me(k(`models.v2Applied`)),vt((e.warnings??[]).join(` `))}catch(e){Le(!1),Me(e instanceof Error?e.message:k(`models.saveFailed`))}}catch{Le(!1),Me(k(`models.networkError`))}finally{gt(!1),yt.current=!1}}},Wr=async e=>{tt&&tt.multiAgentMode!==e&&(e===`v1`?await Ur({multiAgentMode:`v1`}):kt(e))},Gr=async()=>{try{let t=M(15e3),n=await yn(await fetch(`${e}/api/model-presets`,{signal:t.signal}));it(n?.providers??{})}catch{it({})}},Kr=async()=>{try{let t=await fetch(`${e}/api/model-discovery`);ot(await yn(t)??null)}catch{ot(null)}},qr=async(t,n)=>{await yn(await fetch(`${e}/api/model-discovery`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({policy:t,provider:n??null})})),await Promise.all([Kr(),br()])},Jr=async(t,n,r)=>{if((!r||await ha({message:k(`models.presetConfirmReplace`,{count:String(r.presetCount)}),tone:`danger`}))&&!Xe.current){Xe.current=!0,ft(t),qe(!0),Je.current=!0;try{let r=M(3e4),i=await vn(await fetch(`${e}/api/model-presets`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({provider:t,mode:n}),signal:r.signal}),k(`models.saveFailed`));if(!i)throw Error(k(`models.saveFailed`));if(i.fallback===`preset-empty`)Ve(!1,k(`models.presetEmpty`,{provider:t}));else{let e=Go(i);e!==void 0&&Fe(e),Ve(!0,n===`all`?k(`models.presetClearedToast`,{provider:t}):k(`models.presetAppliedToast`,{provider:t,count:String(i.selected?.length??0)}))}await Promise.all([Gr(),br()])}catch(e){Ve(!1,e instanceof Error?e.message:String(e))}finally{ft(null),qe(!1),Je.current=!1,Xe.current=!1}}},Yr=async e=>{tt&&tt.keepNativeChatGptOnV1!==e&&await Ur({keepNativeChatGptOnV1:e})},Xr=tt?.maxConcurrentThreadsPerSession==null?null:hs(tt.maxConcurrentThreadsPerSession,tt.enabled),Zr=async t=>{if(!tt||yt.current)return;let n=gs(t,tt.enabled);if(!Number.isSafeInteger(t)||t<1||!Number.isSafeInteger(n))Ve(!1,k(`models.v2ThreadsInvalid`));else if(Xr!==t){gt(!0),yt.current=!0,xt.current++,vt(``),Me(``);try{let t=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({maxConcurrentThreadsPerSession:n})});try{let e=await vn(t,k(`models.saveFailed`));if(!e||typeof e.enabled!=`boolean`){Le(!1),Me(k(`models.saveFailed`));return}nt({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}),Le(!0),Me(k(`models.v2ThreadsApplied`)),Tt(!1)}catch(e){Le(!1),Me(e instanceof Error?e.message:k(`models.saveFailed`))}}catch{Le(!1),Me(k(`models.networkError`))}finally{gt(!1),yt.current=!1}}},Qr=e=>{e===`custom`?(Tt(!0),Ct(String(Xr??``))):(Tt(!1),Zr(Number(e)))},$r=(e,t)=>{rr.current&&clearTimeout(rr.current),rr.current=setTimeout(()=>{tr({namespaced:e,rect:t.getBoundingClientRect()})},300)},ei=(e,t)=>{rr.current&&clearTimeout(rr.current),tr({namespaced:e,rect:t.getBoundingClientRect()})},ti=()=>{rr.current&&clearTimeout(rr.current),rr.current=setTimeout(()=>tr(null),120)},ni=()=>{rr.current&&clearTimeout(rr.current)},ri=async(t,n,r,i,a,o)=>{jn(!0),Nn(``);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 vn(s,k(`models.customSaveFailed`)),jt(!1),Ve(!0,k(`models.customAdded`)),await br(!0)}catch(e){Nn(e instanceof Error?e.message:k(`models.customSaveFailed`))}}catch{Nn(k(`models.networkError`))}finally{jn(!1)}},ii=async(t,n)=>{jn(!0),Nn(``);try{let r=await fetch(`${e}/api/custom-models/${encodeURIComponent(t)}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});try{await vn(r,k(`models.customSaveFailed`)),jt(!1),Ve(!0,k(`models.customUpdated`)),await br(!0)}catch(e){Nn(e instanceof Error?e.message:k(`models.customSaveFailed`))}}catch{Nn(k(`models.networkError`))}finally{jn(!1)}},ai=async(t,n)=>{if(await ha({message:k(`models.customDeleteConfirm`,{name:n}),confirmLabel:k(`common.delete`),tone:`danger`}))try{(await fetch(`${e}/api/custom-models/${encodeURIComponent(t)}`,{method:`DELETE`})).ok?(Ve(!0,k(`models.customDeleted`)),await br(!0)):Ve(!1,k(`models.customSaveFailed`))}catch{Ve(!1,k(`models.networkError`))}},oi=yr.data??j,si=yr.kind===`failed-cold`?yr.error instanceof Error?yr.error.message:k(`models.loadFail`):null,ci=yr.showSkeleton&&!oi,li=z??{},ui=t=>{let{provider:n,rows:r,nativeProviderGroup:i,liveModels:a,discovery:o}=t,s=Ee.has(n),c=e=>et(li,n,e.id,e.native===!0,L.has(e.namespaced)),l=U[n]===!0,u=ts(r),d=rs(l,r),f=ns(r,d),p=f.filter(c).length,m=at?.recentArrivals[n]??[],h=new Set(m.map(e=>e.id)),g=G[n]!==void 0,_=G[n]??K[n]??q,v=t.nativeProviderGroup?us:cs,y=t.nativeProviderGroup?ds:ls,b=a&&o?.status===`failed`?o:void 0,x=(V[n]??``).trim().toLowerCase(),S=x?f.filter(e=>e.id.toLowerCase().includes(x)):f,C=S.toSorted((e,t)=>Number(!c(e))-Number(!c(t))),w=W[n]??60,T=C.slice(0,w),E=S.length-T.length,D=f.length>0,O=r.some(e=>e.initialSelectionPending),A=!D||f.every(c),j=!D||f.every(e=>!c(e)),M=e=>{D&&!O&&jr(`provider`,n,f.map(e=>({id:e.id,native:e.native===!0})),e)};return(0,Q.jsxs)(`div`,{className:`card models-provider-card`,children:[(0,Q.jsxs)(`div`,{className:`row group-head models-provider-head${s?``:` open`}`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`row models-provider-toggle`,onClick:()=>Nr(n),"aria-expanded":!s,style:{flex:`1 1 auto`,border:0,background:`transparent`,padding:0,color:`inherit`,cursor:`pointer`,textAlign:`left`},children:[(0,Q.jsx)(Ye,{style:{width:14,height:14,color:`var(--muted)`,transform:s?`none`:`rotate(90deg)`,transition:`transform .12s`}}),(0,Q.jsx)(`span`,{className:`text-body font-semibold`,style:{whiteSpace:`nowrap`},children:fe(n)}),st.providers[n]&&(0,Q.jsx)(`span`,{className:`models-chip mono text-caption`,children:st.providers[n]}),i&&(0,Q.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:k(`models.nativeGroupLabel`)}),b&&(0,Q.jsx)(`span`,{className:`badge badge-amber`,role:`status`,title:es(k,b),children:k(`models.discoveryFailedBadge`)}),(0,Q.jsx)(`span`,{className:`muted mono text-label`,children:k(`models.active`,{active:p,total:f.length})}),m.length>0&&(0,Q.jsx)(`span`,{className:`models-chip mono text-caption`,children:k(`models.newCount`,{count:m.length})})]}),(0,Q.jsxs)(`div`,{className:`row models-provider-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm models-alias-edit`,"aria-label":k(`models.editProviderAlias`),title:k(`models.editProviderAlias`),onClick:()=>void $t(n),children:(0,Q.jsx)(le,{style:{width:14,height:14}})}),(0,Q.jsx)(ln,{on:st.defaults.providers[n]??st.defaults.global,onClick:()=>void tn(!(st.defaults.providers[n]??st.defaults.global),n),label:k(`models.useDefaultAliases`),showLabel:!0}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:e=>{e.stopPropagation(),rn(`add`),on(n),cn(``),mn(``),gn(``),bn(``),Sn(!1),wn([`text`]),En(!1),On([]),kn.current=!1,Nn(``),jt(!0)},"aria-haspopup":`dialog`,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`+`}),` `,k(`models.customAdd`)]}),(()=>{let e=rt[n];if(!e)return null;let t=Ke||dt!==null,r=e.mode===`custom`&&e.appliedVersion!==void 0&&e.appliedVersion<e.availableVersion;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":k(`models.presetLabel`),children:[[`preset`,`all`].map(r=>(0,Q.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:Ke||t||O,onClick:t=>{t.stopPropagation(),Jr(n,r,r===`preset`&&e.mode===`custom`?e:void 0)},children:k(`models.presetMode_${r}`)},r)),e.mode===`custom`&&(0,Q.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":!0,className:`btn btn-sm btn-primary`,disabled:!0,children:k(`models.presetMode_custom`)})]}),e.mode===`preset`&&(0,Q.jsx)(`span`,{className:`muted mono text-label`,children:k(`models.presetSummary`,{count:String(e.presetCount),total:String(e.totalCount),version:String(e.availableVersion)})}),r&&(0,Q.jsx)(`span`,{className:`badge badge-amber`,role:`status`,children:k(`models.presetUpdateAvailable`,{version:String(e.availableVersion)})})]})})(),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,disabled:Ke&&!$e.pending||A||O,onClick:()=>M(!0),children:k(`models.allOn`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,disabled:Ke&&!$e.pending||j||O,onClick:()=>M(!1),children:k(`models.allOff`)}),(0,Q.jsxs)(`div`,{className:`models-cap-cluster`,children:[(0,Q.jsx)(ln,{on:g,onClick:()=>Mr(n),disabled:Ke,label:k(`models.contextCapLabel`),showLabel:!0}),(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(dn,{value:be[n]?fs:String(_),options:[...!y.has(_)&&!be[n]?[{value:String(_),label:vs(_)}]:[],...v.map(e=>({value:String(e),label:vs(e)})),{value:fs,label:k(`models.custom`)}],onChange:e=>Rr(n,e),disabled:Ke||!g,label:k(`models.capValue`,{value:vs(_)}),title:k(`models.contextCapLabel`)}),g&&be[n]&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`input`,{className:`input`,style:{width:120},inputMode:`numeric`,placeholder:k(`models.customPlaceholder`),value:Se[n]??``,onChange:e=>we(t=>({...t,[n]:e.target.value})),onKeyDown:e=>{e.key===`Enter`&&zr(n)},disabled:Ke,"aria-label":k(`models.customPlaceholder`)}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>zr(n),disabled:Ke,className:`btn btn-ghost btn-sm`,children:k(`models.customApply`)})]})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>Er(t),"aria-haspopup":`dialog`,children:k(`models.contextSettings`)})]})]})]}),!s&&(0,Q.jsxs)(`div`,{className:`models-provider-body`,children:[i&&(0,Q.jsx)(`p`,{className:`muted text-label models-provider-hint`,children:k(`models.nativeHint`)}),!i&&at&&(0,Q.jsxs)(`div`,{className:`row models-provider-hint`,children:[(0,Q.jsx)(`span`,{className:`muted text-label`,children:k(`models.newPolicyProvider`)}),(0,Q.jsx)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":k(`models.newPolicyProvider`),children:[`off`,`on`].map(e=>(0,Q.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":(at.providers[n]??`inherit`)===e,className:`btn btn-sm${(at.providers[n]??`inherit`)===e?` btn-primary`:` btn-ghost`}`,onClick:()=>void qr(e,n),children:k(`models.newPolicy_${e}`)},e))})]}),!i&&(0,Q.jsx)(AC,{summary:F.find(e=>e.name===n),apiBase:e,onSaved:(e,t)=>{Ve(e,t),e&&br(!0)}}),r.length===0&&(0,Q.jsx)(MC,{liveModels:a,discovery:o,showFailureBadge:!1}),r.length>0&&b&&(0,Q.jsx)(NC,{}),u&&(0,Q.jsx)(`div`,{className:`row models-provider-hint`,children:(0,Q.jsx)(ln,{on:l,onClick:()=>ee(e=>({...e,[n]:!l})),label:k(`models.freeOnly`),showLabel:!0})}),d&&f.length===0&&r.length>0&&(0,Q.jsx)(`p`,{className:`muted text-label`,role:`status`,children:k(`models.noFreeMatch`)}),r.length>30&&(0,Q.jsx)(`input`,{className:`input`,placeholder:k(`models.search`),value:V[n]??``,onChange:e=>H(t=>({...t,[n]:e.target.value})),"aria-label":k(`models.search`)}),T.map(e=>{let t=!c(e);return(0,Q.jsxs)(`div`,{className:`model-row-wrap`,onMouseEnter:t=>$r(e.namespaced,t.currentTarget),onMouseLeave:ti,onFocus:t=>ei(e.namespaced,t.currentTarget),onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||tr(null)},children:[(0,Q.jsxs)(`div`,{className:`row models-model-row`,children:[(0,Q.jsx)(ln,{on:!t,onClick:()=>void jr(`models`,n,[{id:e.id,native:e.native===!0}],t),disabled:Ke&&!$e.pending||e.initialSelectionPending,label:e.native?e.id:e.namespaced}),e.initialSelectionPending&&(0,Q.jsx)(`span`,{className:`models-chip muted`,role:`status`,children:k(`models.initialSelectionPending`)}),e.quotaInactiveReason===`no_credit`&&(0,Q.jsx)(`span`,{className:`models-chip muted`,role:`status`,title:k(`models.inactiveNoCreditHint`),children:k(`models.inactiveNoCredit`)}),st.models[n]?.[e.id]&&(0,Q.jsx)(`strong`,{className:`mono text-control`,children:st.models[n][e.id].alias}),(0,Q.jsxs)(`span`,{className:`models-model-identity`,children:[(0,Q.jsx)(`code`,{className:`mono text-control`,style:{color:t?`var(--faint)`:`var(--text)`,textDecoration:t?`line-through`:`none`},children:e.native?zv(e.id):e.namespaced}),!e.native&&e.displayName?.trim()&&e.displayName.trim()!==e.namespaced&&(0,Q.jsx)(`span`,{className:`models-model-friendly text-caption`,children:e.displayName.trim()})]}),st.models[n]?.[e.id]?.source===`builtin`&&(0,Q.jsx)(`span`,{className:`models-chip muted text-caption`,children:k(`models.aliasAuto`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":k(`models.editModelAlias`),title:k(`models.editModelAlias`),onClick:()=>void en(n,e.id),children:(0,Q.jsx)(le,{style:{width:13,height:13}})}),!e.native&&!e.custom&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption models-display-name-trigger`,"aria-haspopup":`dialog`,"aria-label":k(`models.displayNameActionLabel`,{model:e.namespaced}),onClick:t=>{Xt.current=t.currentTarget,Ht(null),Wt(null),qt(!1),Nt(e)},children:k(`models.displayNameAction`)}),e.custom&&(0,Q.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:k(`models.customBadge`)}),!e.native&&e.provider!==`combo`&&(0,Q.jsxs)(Q.Fragment,{children:[e.manualPricing===!0&&(0,Q.jsx)(`span`,{className:`models-chip muted text-caption`,children:k(`pricing.override.badge`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption models-display-name-trigger`,"aria-haspopup":`dialog`,"aria-label":k(`pricing.override.actionLabel`,{model:e.namespaced}),onClick:t=>{It.current=t.currentTarget,Ft(e)},children:k(`pricing.override.action`)})]}),!e.native&&!e.custom&&e.provider!==`combo`&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption models-display-name-trigger`,"aria-haspopup":`dialog`,"aria-label":k(`models.settingsTitle`,{model:e.namespaced}),onClick:()=>Rt(e),children:k(`models.customEdit`)}),!e.custom&&h.has(e.id)&&(0,Q.jsx)(`span`,{className:`badge badge-amber`,children:k(`models.newBadge`)}),e.contextCapped&&(0,Q.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:k(`models.contextCappedValue`,{value:vs(e.contextCap??q)})})]}),er?.namespaced===e.namespaced&&(()=>{let n=er.rect,r=n.bottom+4,i=r+360>window.innerHeight;return(0,Q.jsxs)(`div`,{className:`model-tip${e.custom?` has-actions`:``}${i?` flip-up`:``}`,role:`tooltip`,style:{position:`fixed`,left:n.left+24,...i?{bottom:window.innerHeight-n.top+4}:{top:r}},onMouseEnter:ni,onMouseLeave:ti,children:[(0,Q.jsx)(`div`,{className:`model-tip-id`,children:e.native?e.id:e.namespaced}),e.displayName&&(0,Q.jsx)(`div`,{className:`model-tip-display`,children:e.displayName}),e.custom&&(0,Q.jsx)(`span`,{className:`models-chip models-chip--tip muted mono text-caption`,children:k(`models.customBadge`)}),(0,Q.jsxs)(`div`,{className:`model-tip-grid`,children:[(0,Q.jsx)(`span`,{className:`model-tip-key`,children:k(`models.tipProvider`)}),(0,Q.jsx)(`span`,{className:`model-tip-val`,children:Ce(e.provider,k)}),(e.contextWindow||e.contextCap)&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`model-tip-key`,children:k(`models.tipContext`)}),(0,Q.jsx)(`span`,{className:`model-tip-val`,children:vs(e.contextWindow??e.contextCap??0)})]}),e.inputModalities&&e.inputModalities.length>0&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`model-tip-key`,children:k(`models.tipModalities`)}),(0,Q.jsx)(`span`,{className:`model-tip-val`,children:e.inputModalities.join(`, `)})]}),(0,Q.jsx)(`span`,{className:`model-tip-key`,children:k(`models.tipStatus`)}),(0,Q.jsx)(`span`,{className:`model-tip-val`,children:k(t?`models.tipDisabled`:`models.tipActive`)})]}),e.custom&&e.customId&&(0,Q.jsxs)(`div`,{className:`model-tip-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>{rn(`edit`),on(e.provider),cn(e.customId),mn(e.id),gn(e.displayName??``),bn(e.contextWindow?String(e.contextWindow):``),Sn(!1),wn(e.inputModalities??[`text`]),En(Array.isArray(e.reasoningEfforts)),On(e.reasoningEfforts??[]),kn.current=Array.isArray(e.reasoningEfforts),Nn(``),jt(!0),tr(null)},children:k(`models.customEdit`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,style:{color:`var(--red)`},onClick:()=>{ai(e.customId,e.displayName??e.id).finally(()=>tr(null))},children:k(`models.customDelete`)})]})]})})()]},e.namespaced)}),E>0&&(0,Q.jsx)(`button`,{type:`button`,onClick:()=>te(e=>({...e,[n]:w+60})),className:`btn btn-ghost btn-sm models-show-more`,children:k(`models.showMore`,{n:E})})]})]},n)},di=cr?wr.filter(e=>e.provider===cr):wr,fi=(e,t=!1)=>{let n={pickerOrder:e.pickerOrder,pickerOrderMode:e.pickerOrderMode,pickerAvailable:[]};Kt(Y,n),co(Y,n),t&&oe(`custom`),pe.refresh();let r=e.catalogRefresh,i=typeof r==`object`&&!!r&&`status`in r&&r.status===`committed`&&`degraded`in r&&r.degraded===!1;Ve(i,k(i?`models.pickerOrder.saved`:`models.pickerOrder.pending`)),p()},pi=async()=>{if(ue.current||!me||pe.state.showError||he===`custom`)return;let t=de.current,n=he,r=me.pickerAvailable,i=M(15e3);ue.current=i,ce(!0);let a=()=>de.current===t&&ue.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 vn(n,k(`models.pickerOrder.usageFailed`));if(!o())return;if(r?.usageIncomplete===!0)throw Error(k(`models.pickerOrder.usageIncomplete`));if(!E_(r?.models))throw Error(k(`models.pickerOrder.usageFailed`));t=r.models}if(!o())return;let a=A_(n,r,t,N),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 vn(s,k(`models.saveFailed`));if(!w_(c)||!(`ok`in c)||c.ok!==!0)throw Error(k(`models.saveFailed`));if(!o())return;fi({pickerOrder:c.pickerOrder,pickerOrderMode:c.pickerOrderMode,catalogRefresh:`catalogRefresh`in c?c.catalogRefresh:void 0}),oe(null)}catch(e){a()&&Ve(!1,e instanceof Error?e.message:k(`models.networkError`))}finally{i.clear(),a()&&(ue.current=null,ce(!1))}},mi=(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`models-control-top-row`,children:[at&&(0,Q.jsx)(UC,{label:k(`models.newPolicyGlobal`),children:(0,Q.jsx)(ln,{on:at.policy===`off`,onClick:()=>void qr(at.policy===`off`?`on`:`off`),label:k(`models.newPolicyGlobal`)})}),(0,Q.jsxs)(UC,{label:k(`models.useDefaultAliasesGlobal`),children:[(0,Q.jsx)(ln,{on:st.defaults.global,onClick:()=>void tn(!st.defaults.global),label:k(`models.useDefaultAliasesGlobal`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>ut(e=>!e),children:k(`models.aliases`)})]}),(0,Q.jsx)(WC,{shadowCall:ir,saving:ar,modelOptions:fr,onSave:e=>void sr(e)}),(0,Q.jsxs)(UC,{label:k(`models.autoReviewOverride`),hint:(0,Q.jsx)(pn,{content:k(`models.autoReviewOverrideHint`),side:`top`,maxWidth:320,children:(0,Q.jsx)(`span`,{style:{cursor:`help`},"aria-label":k(`models.autoReviewOverrideHint`),children:`ⓘ`})}),busy:!He,children:[(0,Q.jsx)(ln,{on:He?.enabled??!1,onClick:()=>void Ge({enabled:!He?.enabled}),disabled:!He||Ue,label:k(`models.autoReviewOverride`)}),(0,Q.jsx)(`div`,{className:`models-shadow-model-slot`,children:(0,Q.jsx)(dn,{value:He?.model??``,options:mr,onChange:e=>void Ge({model:e}),disabled:!He||Ue||!He.enabled,label:k(`models.autoReviewOverride`)})})]}),(pt||tt)&&(0,Q.jsxs)(UC,{label:k(`models.v2Label`),children:[(0,Q.jsx)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":k(`models.v2Label`),children:[`v1`,`default`,`v2`].map(e=>(0,Q.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":(tt?.multiAgentMode??`default`)===e,className:`btn btn-sm${(tt?.multiAgentMode??`default`)===e?` btn-primary`:` btn-ghost`}`,style:{background:(tt?.multiAgentMode??`default`)===e?void 0:`transparent`,color:(tt?.multiAgentMode??`default`)===e?void 0:`var(--muted)`},disabled:!tt||ht,onClick:()=>void Wr(e),children:k(`models.v2Mode_${e}`)},e))}),(0,Q.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:!tt,onClick:()=>Dt(!0),"aria-label":k(`models.v2Label`),"aria-haspopup":`dialog`,children:(0,Q.jsx)(De,{width:14,height:14,"aria-hidden":`true`})})]}),tt&&tt.multiAgentMode===`v2`&&(0,Q.jsx)(`div`,{className:`models-v2-keep-native-row`,children:(0,Q.jsxs)(`div`,{className:`models-v2-keep-native`,children:[(0,Q.jsx)(`span`,{className:`models-v2-keep-native-label text-caption`,children:k(`models.keepNativeOnV1`)}),(0,Q.jsx)(ln,{on:tt.keepNativeChatGptOnV1===!0,onClick:()=>void Yr(!tt.keepNativeChatGptOnV1),disabled:ht,label:k(`models.keepNativeOnV1`)}),(0,Q.jsx)(pn,{content:k(`models.keepNativeOnV1Hint`),side:`top`,maxWidth:360,children:(0,Q.jsx)(`span`,{className:`models-v2-keep-native-info`,"aria-label":k(`models.keepNativeOnV1Hint`),children:(0,Q.jsx)(De,{width:13,height:13,"aria-hidden":`true`})})})]})}),Ot&&(0,Q.jsx)(pr,{reason:`selection`,mode:Ot,docsUrl:dr(tt?.multiAgentSurfaceAdvisory)?.docsUrl??`https://opencodex.me/guides/subagent-v1-default/`,busy:ht,onContinue:()=>{let e=Ot;kt(null),Ur({multiAgentMode:e,multiAgentSurfaceAdvisoryAcknowledged:!0})},onChooseV1:()=>{kt(null),tt?.multiAgentMode!==`v1`&&Ur({multiAgentMode:`v1`,multiAgentSurfaceAdvisoryAcknowledged:!0})},onDismiss:()=>kt(null)})]}),tt&&(0,Q.jsxs)(`div`,{className:`models-v2-detail-row row`,children:[(0,Q.jsx)(`span`,{className:`muted text-control`,children:k(`models.v2ThreadsLabel`)}),(0,Q.jsx)(dn,{value:wt?`custom`:Xr===null?``:ms.has(Xr)?String(Xr):`custom`,options:[...Xr===null?[{value:``,label:k(`models.v2ThreadsDefault`)}]:[],...Xr!==null&&!ms.has(Xr)&&!wt?[{value:`custom`,label:String(Xr)}]:[],...ps.map(e=>({value:String(e),label:String(e)})),{value:`custom`,label:k(`models.custom`)}],onChange:e=>Qr(e),disabled:ht,label:k(`models.v2ThreadsLabel`)}),wt&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`input`,{className:`input`,style:{width:100},inputMode:`numeric`,value:St,onChange:e=>Ct(e.target.value),onKeyDown:e=>{e.key===`Enter`&&Zr(Number(St.replace(/[_,\s]/g,``)))},disabled:ht,"aria-label":k(`models.v2ThreadsLabel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:ht,onClick:()=>{Zr(Number(St.replace(/[_,\s]/g,``)))},children:k(`models.v2ThreadsApply`)})]}),tt.enabled&&tt.agentsMaxThreadsConflict&&(0,Q.jsx)(`span`,{className:`mono text-label`,style:{color:`var(--err, #e5484d)`},children:k(`models.v2Conflict`)}),_t&&(0,Q.jsx)(`span`,{className:`muted text-label`,children:_t})]}),(0,Q.jsxs)(`div`,{className:`row models-cap-row`,children:[(0,Q.jsx)(`span`,{className:`muted text-control`,children:k(`models.contextCapLabel`)}),(0,Q.jsx)(dn,{value:ve?fs:String(q),options:[...!ls.has(q)&&!ve?[{value:String(q),label:vs(q)}]:[],...cs.map(e=>({value:String(e),label:vs(e)})),{value:fs,label:k(`models.custom`)}],onChange:e=>Br(e),disabled:Ke,label:k(`models.contextCapLabel`)}),ve&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`input`,{className:`input`,style:{width:160},inputMode:`numeric`,placeholder:k(`models.customPlaceholder`),value:ge,onChange:e=>_e(e.target.value),onKeyDown:e=>{e.key===`Enter`&&Vr()},disabled:Ke,"aria-label":k(`models.customPlaceholder`)}),(0,Q.jsx)(`button`,{type:`button`,onClick:Vr,disabled:Ke,className:`btn btn-ghost btn-sm`,children:k(`models.customApply`)})]}),(0,Q.jsx)(ln,{on:Ir,onClick:Hr,disabled:Ke,label:k(`models.setAll`)}),(0,Q.jsx)(HC,{text:k(`models.setAllHint`,{value:vs(q)})})]}),(0,Q.jsxs)(`div`,{className:`row models-cap-row`,"aria-busy":se||pe.state.refreshing,children:[(0,Q.jsx)(`span`,{className:`muted text-control`,children:k(`models.pickerOrder.label`)}),(0,Q.jsx)(dn,{value:he,options:[{value:`default`,label:k(`models.pickerOrder.default`)},{value:`alphabetical`,label:k(`models.pickerOrder.alphabetical`)},{value:`provider`,label:k(`models.pickerOrder.provider`)},{value:`most-used`,label:k(`models.pickerOrder.mostUsed`)},{value:`custom`,label:k(`models.pickerOrder.custom`)}],onChange:e=>oe(e),disabled:se||!me||pe.state.showError,label:k(`models.pickerOrder.label`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void pi(),disabled:se||!me||pe.state.showError||he===`custom`||he!=="default"&&me.pickerAvailable.length===0,children:k(se?`models.pickerOrder.applying`:`models.pickerOrder.apply`)}),pe.state.showError&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{role:`alert`,children:k(`models.pickerOrder.loadFailed`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>pe.refresh(),children:k(`models.pickerOrder.retry`)})]}),(0,Q.jsx)(HC,{text:k(`models.pickerOrder.hint`)})]}),(0,Q.jsx)(U_,{showOrderEditor:he===`custom`,apiBase:e,active:S,identities:N,onBusyChange:ce,onAccepted:e=>fi(e,!0),onSaved:()=>vr.refresh()}),lt&&(0,Q.jsxs)(`div`,{className:`card models-aliases-card`,"aria-label":k(`models.aliasesTable`),children:[(0,Q.jsx)(`div`,{className:`row group-head`,children:(0,Q.jsx)(`strong`,{children:k(`models.aliases`)})}),Object.entries(st.models).flatMap(([e,t])=>Object.entries(t).map(([t,n])=>(0,Q.jsxs)(`div`,{className:`row models-model-row`,children:[(0,Q.jsxs)(`code`,{className:`mono text-caption`,style:{flex:1},children:[e,`/`,t]}),(0,Q.jsx)(`strong`,{className:`mono text-control`,children:n.alias}),(0,Q.jsx)(`span`,{className:`models-chip muted text-caption`,children:n.source===`builtin`?k(`models.aliasAuto`):k(`models.aliasUser`)}),n.stale&&(0,Q.jsx)(`span`,{className:`badge badge-amber`,children:k(`models.aliasStale`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":k(`models.editModelAlias`),onClick:()=>void en(e,t),children:(0,Q.jsx)(le,{style:{width:13,height:13}})})]},`${e}/${t}`)))]})]}),hi=N.filter(e=>e.custom).length,gi=(0,Q.jsxs)(`div`,{className:`row models-collapse-controls`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>Pr(!0),disabled:Ke,children:[(0,Q.jsx)(Ye,{width:12,height:12,"aria-hidden":`true`}),` `,k(`models.collapseAll`)]}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>Pr(!1),disabled:Ke,children:[(0,Q.jsx)(Ye,{width:12,height:12,"aria-hidden":`true`,style:{transform:`rotate(90deg)`}}),` `,k(`models.expandAll`)]}),(0,Q.jsx)(HC,{text:k(`models.orderHint`)}),(0,Q.jsx)(VC,{count:hi,label:k(`models.customSummary`,{count:hi})})]}),_i=(0,Q.jsx)(Q.Fragment,{children:wr.length===0&&(0,Q.jsx)(fn,{icon:(0,Q.jsx)(ze,{}),title:k(`models.noRouted`),children:k(`models.noRoutedHint`)})}),vi=(0,Q.jsxs)(Q.Fragment,{children:[Et&&(0,Q.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":k(`models.v2Label`),onClick:()=>Dt(!1),onKeyDown:e=>{e.key===`Escape`&&Dt(!1)},children:(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{children:k(`models.v2Label`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>Dt(!1),"aria-label":k(`common.close`),children:`×`})]}),(0,Q.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:k(`models.v2Help`)}),(0,Q.jsx)(`div`,{className:`models-help-link`,children:(0,Q.jsx)(`a`,{className:`text-control`,href:`https://opencodex.me/guides/sub-agent-surface/`,target:`_blank`,rel:`noreferrer`,style:{color:`var(--accent)`},children:k(`models.v2DocsLink`)})}),(0,Q.jsx)(`div`,{className:`modal-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>Dt(!1),children:k(`common.ok`)})})]})}),Pn&&(0,Q.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":k(`models.contextSettings`),onClick:()=>{Xn||Fn(null)},onKeyDown:e=>{e.key===`Escape`&&!Xn&&Fn(null)},children:(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{children:k(`models.contextSettingsTitle`,{provider:Ce(Pn,k)})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>Fn(null),disabled:Xn,"aria-label":k(`common.close`),children:`×`})]}),Qn&&(0,Q.jsx)($,{tone:`err`,children:Qn}),(0,Q.jsx)(`p`,{className:`modal-desc leading-relaxed`,children:k(`models.contextHint`)}),(0,Q.jsxs)(`div`,{className:`models-context-fields`,children:[(0,Q.jsxs)(`label`,{className:`text-label models-field`,children:[k(`models.contextDefault`),(0,Q.jsx)(`input`,{className:`input`,inputMode:`numeric`,value:Bn,onChange:e=>{Vn(e.target.value),Yn(!0)},disabled:Xn,placeholder:k(`models.contextAutomatic`),autoFocus:!0})]}),In.length>0&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`text-label models-field`,children:[k(`models.contextModel`),(0,Q.jsx)(dn,{value:Rn,options:In.map(e=>({value:e,label:e})),onChange:Dr,disabled:Xn,label:k(`models.contextModel`)})]}),(0,Q.jsxs)(`label`,{className:`text-label models-field`,children:[k(`models.contextModelOverride`),(0,Q.jsx)(`input`,{className:`input`,inputMode:`numeric`,value:Bv(Hn,Rn)??``,onChange:e=>{Un(t=>({...t,[Rn]:e.target.value})),qn(e=>new Set(e).add(Rn))},disabled:Xn,placeholder:k(`models.contextAutomatic`)})]})]})]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>Fn(null),disabled:Xn,children:k(`common.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>void Or(),disabled:Xn,children:k(Xn?`models.customSaving`:`models.customApply`)})]})]})}),At&&(0,Q.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":k(`models.customAdd`),onClick:()=>{An||jt(!1)},onKeyDown:e=>{e.key===`Escape`&&!An&&jt(!1)},children:(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{children:k(nn===`add`?`models.customAddTitle`:`models.customEditTitle`,{provider:Ce(an,k)})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>jt(!1),disabled:An,"aria-label":k(`common.close`),children:`×`})]}),Mn&&(0,Q.jsx)($,{tone:`err`,children:Mn}),(0,Q.jsxs)(`div`,{className:`models-field-stack`,children:[(0,Q.jsxs)(`label`,{className:`text-label models-field`,children:[k(`models.customFieldModelId`),(0,Q.jsx)(`input`,{className:`input`,value:un,onChange:e=>mn(e.target.value),disabled:An,placeholder:k(`models.customFieldModelIdPlaceholder`),autoFocus:!0})]}),(0,Q.jsxs)(`label`,{className:`text-label models-field`,children:[k(`models.customFieldDisplayName`),(0,Q.jsx)(`input`,{className:`input`,value:hn,onChange:e=>gn(e.target.value),disabled:An,placeholder:k(`models.customFieldDisplayNamePlaceholder`)})]}),(0,Q.jsxs)(`label`,{className:`text-label models-field`,children:[k(`models.customFieldContext`),(0,Q.jsxs)(`div`,{className:`row models-field-row`,children:[(0,Q.jsx)(dn,{value:xn?`custom`:_n,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:k(`models.custom`)}],onChange:e=>{e===`custom`?Sn(!0):(Sn(!1),bn(e))},disabled:An,label:k(`models.customFieldContext`)}),xn&&(0,Q.jsx)(`input`,{className:`input`,style:{width:120},inputMode:`numeric`,value:_n,onChange:e=>bn(e.target.value),disabled:An,placeholder:k(`models.customPlaceholder`),"aria-label":k(`models.customFieldContext`)})]})]}),(0,Q.jsxs)(`div`,{className:`text-label models-field`,children:[k(`models.customFieldModalities`),(0,Q.jsx)(`div`,{className:`row models-field-row`,children:[`text`,`image`,`audio`].map(e=>(0,Q.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:Cn.includes(e),onChange:t=>{wn(n=>t.target.checked?[...n,e]:n.filter(t=>t!==e))},disabled:An}),(0,Q.jsx)(`span`,{className:`text-control`,children:e})]},e))})]}),(0,Q.jsxs)(`div`,{className:`text-label models-field`,children:[k(`models.customFieldReasoning`),(0,Q.jsx)(`div`,{className:`row models-field-row`,children:(0,Q.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:Tn,onChange:e=>{if(En(e.target.checked),e.target.checked&&!kn.current){kn.current=!0;let e=N.find(e=>e.provider===an&&e.id===un),t=Array.isArray(e?.reasoningEfforts)?e.reasoningEfforts:void 0;On(t??[...os])}},disabled:An}),(0,Q.jsx)(`span`,{className:`text-control`,children:k(`models.customFieldReasoningOverride`)})]})}),Tn&&(0,Q.jsx)(`div`,{className:`row models-field-row`,style:{flexWrap:`wrap`},children:os.map(e=>(0,Q.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:Dn.includes(e),onChange:t=>{On(n=>t.target.checked?[...n,e]:n.filter(t=>t!==e))},disabled:An}),(0,Q.jsx)(`span`,{className:`text-control`,children:k(`models.reasoningEffort.${e}`)})]},e))})]})]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>jt(!1),disabled:An,children:k(`common.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:An||!un.trim(),onClick:()=>{let e=un.trim(),t=hn.trim(),n=ws(_n);if(n===void 0)Nn(k(`models.contextInvalid`));else if(nn===`add`){let r=Tn?Dn:void 0;ri(an,e,t||void 0,n??void 0,Cn.length>0?Cn:void 0,r)}else ii(sn,{modelId:e,displayName:t,contextWindow:n,inputModalities:Cn,reasoningEfforts:Tn?Dn:null})},children:k(An?`models.customSaving`:nn===`add`?`models.customAddBtn`:`models.customEditBtn`)})]})]})})]}),yi=(0,Q.jsxs)(`div`,{className:`models-workspace-shell`,children:[je&&(0,Q.jsxs)(`div`,{className:`action-toast notice ${Ie?`notice-ok`:`notice-err`}`,role:`status`,"aria-live":`polite`,children:[Ie?(0,Q.jsx)(Oe,{}):(0,Q.jsx)(Ne,{}),(0,Q.jsx)(`span`,{children:je})]}),yr.showError&&(0,Q.jsx)($,{tone:`err`,children:k(`models.loadFail`)}),Pe.length>0&&(0,Q.jsx)(`div`,{className:`models-integration-warning`,children:(0,Q.jsxs)($,{tone:`warn`,children:[k(`models.integrationRefreshWarning`),(0,Q.jsx)(`ul`,{children:Pe.map(e=>(0,Q.jsxs)(`li`,{children:[e.client,e.profileId===void 0?``:`:${e.profileId}`,`: `,ib(k,{clientId:e.client,message:e.reason===`integration_mutation_busy`?k(`integrations.error.busy`):e.reason,reason:e.refusalReason,snapshotPath:e.snapshotPath,residual:e.residual})]},`${e.client}:${e.profileId??`all`}`))})]})}),(0,Q.jsx)(BC,{title:k(`models.settingsPanel.title`),attentionLabel:k(`models.settingsPanel.attention`),warn:!!(tt?.enabled&&tt.agentsMaxThreadsConflict)||_t!==``||pe.state.showError,summary:zC(k,{multiAgentMode:tt?.multiAgentMode,v2Threads:Xr,keepNativeOnV1:tt?.keepNativeChatGptOnV1===!0,shadowEnabled:ir?.enabled===!0,shadowModel:ir?.model,windowOn:Ir,windowValue:q,newModelsOff:at?.policy===`off`,aliasesOn:st.defaults.global,autoReviewEnabled:He?.enabled===!0,autoReviewModel:He?.model,pickerMode:j_(me?.pickerAvailable??[],me?.pickerOrder??[],me?.pickerOrderMode)}),children:mi}),(0,Q.jsxs)(`div`,{className:`models-workspace-root`,"aria-busy":$e.pending||yr.refreshing||void 0,children:[(0,Q.jsxs)(`aside`,{className:`models-workspace-rail`,"aria-label":k(`nav.models`),children:[(0,Q.jsxs)(`div`,{className:`models-workspace-rail-header`,children:[(0,Q.jsx)(`span`,{className:`models-workspace-rail-title`,children:k(`models.workspace.providers`)}),(0,Q.jsx)(`span`,{className:`models-workspace-rail-count`,children:wr.length})]}),(0,Q.jsxs)(`div`,{className:`models-workspace-rail-list`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`models-workspace-rail-row${cr===null?` models-workspace-rail-row--selected`:``}`,onClick:()=>lr(null),"aria-current":cr===null?`true`:void 0,children:[(0,Q.jsx)(`span`,{className:`models-workspace-rail-name`,children:k(`models.workspace.allProviders`)}),(0,Q.jsx)(`span`,{className:`models-workspace-rail-meta`,children:k(`models.active`,{active:kr,total:N.length})})]}),wr.map(e=>{let{provider:t,rows:n}=e,r=n.filter(e=>et(li,t,e.id,e.native===!0,L.has(e.namespaced))).length;return(0,Q.jsxs)(`button`,{type:`button`,className:`models-workspace-rail-row${cr===t?` models-workspace-rail-row--selected`:``}`,onClick:()=>lr(t),"aria-current":cr===t?`true`:void 0,children:[(0,Q.jsx)(`span`,{className:`models-workspace-rail-name`,children:Ce(t,k)}),(0,Q.jsx)(`span`,{className:`models-workspace-rail-meta`,children:k(`models.active`,{active:r,total:n.length})})]},t)})]})]}),(0,Q.jsxs)(`section`,{className:`models-workspace-main`,"aria-label":k(`models.workspace.mainAria`),children:[gi,(0,Q.jsx)(`div`,{className:`models-provider-list`,children:di.map(e=>ui(e))}),wr.length===0&&_i]})]}),vi]});return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`page-head`,children:[(0,Q.jsx)(`h2`,{children:k(`nav.models`)}),(0,Q.jsx)(`div`,{className:`page-head-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:()=>{h()},disabled:m,"aria-label":k(m?`dash.codexRestarting`:`dash.codexRestart`),title:k(m?`dash.codexRestarting`:`dash.codexRestart`),children:(0,Q.jsx)(ae,{})})})]}),(0,Q.jsx)(x_,{state:o,controller:{restarting:m,restart:h}}),(0,Q.jsx)(kC,{tab:g,onSelect:x,meta:Ar}),(0,Q.jsx)(`p`,{className:`page-sub`,children:k(YC[g])}),g===`catalog`&&(0,Q.jsx)(KC,{connected:r,catalogSyncedAt:i}),(0,Q.jsx)(`div`,{className:`models-tab-panel`,role:`tabpanel`,id:DC(`catalog`),"aria-labelledby":EC(`catalog`),hidden:g!==`catalog`,children:(0,Q.jsx)(db,{pageName:k(`models.tab.catalog`),title:k(`errorBoundary.title`),message:k(`errorBoundary.message`),detailsLabel:k(`errorBoundary.details`),reloadLabel:k(`errorBoundary.reload`),children:ci?(0,Q.jsx)(lb,{label:k(`models.loading`),rows:5}):si===null?yi:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)($,{tone:`err`,children:si}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>vr.refresh(),children:k(`common.retry`)})]})})}),(0,Q.jsx)(`div`,{className:`models-tab-panel models-tab-panel--fill`,role:`tabpanel`,id:DC(`combos`),"aria-labelledby":EC(`combos`),hidden:g!==`combos`,children:v.has(`combos`)&&(0,Q.jsx)(db,{pageName:k(`models.tab.combos`),title:k(`errorBoundary.title`),message:k(`errorBoundary.message`),detailsLabel:k(`errorBoundary.details`),reloadLabel:k(`errorBoundary.reload`),children:(0,Q.jsx)(cx,{apiBase:e,active:g===`combos`,onCountChange:w})})}),(0,Q.jsx)(`div`,{className:`models-tab-panel`,role:`tabpanel`,id:DC(`routing`),"aria-labelledby":EC(`routing`),hidden:g!==`routing`,children:v.has(`routing`)&&(0,Q.jsx)(db,{pageName:k(`models.tab.routing`),title:k(`errorBoundary.title`),message:k(`errorBoundary.message`),detailsLabel:k(`errorBoundary.details`),reloadLabel:k(`errorBoundary.reload`),children:(0,Q.jsx)(qx,{apiBase:e,active:g===`routing`,onCountChange:E})})}),(0,Q.jsx)(`div`,{className:`models-tab-panel`,role:`tabpanel`,id:DC(`compatibility`),"aria-labelledby":EC(`compatibility`),hidden:g!==`compatibility`,children:v.has(`compatibility`)&&(0,Q.jsx)(db,{pageName:k(`models.tab.compatibility`),title:k(`errorBoundary.title`),message:k(`errorBoundary.message`),detailsLabel:k(`errorBoundary.details`),reloadLabel:k(`errorBoundary.reload`),children:(0,Q.jsx)(xC,{apiBase:e,active:g===`compatibility`,onCountChange:O})})}),Mt&&(0,Q.jsx)(G_,{model:Mt,saving:zt,requestError:Vt,currentNamePending:Gt,mutationOutcomeUnknown:Ut?.confirmed===!1,onRetry:Ut?()=>void Cr(Ut.value):void 0,onEdit:()=>Wt(null),onSave:e=>void Cr(e),onReset:()=>void Cr(null),onClose:Sr}),Pt&&(0,Q.jsx)(dv,{model:Pt,apiBase:e,onRefresh:e=>br(!0,e),onClose:()=>{let e=It.current;Ft(null),window.setTimeout(()=>{e?.isConnected&&e.focus()},0)}},`${e}/${Pt.namespaced}`),Lt&&(0,Q.jsx)(yv,{row:Lt,apiBase:e,onRefresh:e=>br(!0,e),onFeedback:Ve,onClose:()=>Rt(null)},`${e}/${Lt.namespaced}`)]})}function ZC(e){return[...new Set(e.filter(e=>!e.disabled&&!e.initialSelectionPending).map(e=>e.namespaced))]}function QC({apiBase:e,value:t,disabled:r,onChange:i}){let a=n(),o=uo(`advisor-models:${e}`,[e],async t=>{let n=await fetch(`${e}/api/models`,{signal:t});if(!n.ok)throw Error(String(n.status));let r=await n.json();if(!Array.isArray(r)||!r.every(e=>e&&typeof e.namespaced==`string`&&e.namespaced.length>0))throw Error(`Invalid model catalog`);return r},{isEmpty:e=>e.length===0}),{state:s}=o,c=ZC(s.data??[]),l=t!==``&&!c.includes(t),u=[{value:``,label:a(`advisor.modelClear`)},...l?[{value:t,label:t}]:[],...c.map(e=>({value:e,label:e}))];return(0,Q.jsxs)(`div`,{"aria-busy":s.showSkeleton||s.refreshing,children:[(0,Q.jsx)(dn,{id:`advisor-model`,value:t,options:u,label:a(`advisor.model`),describedBy:`advisor-model-hint`,disabled:r||s.showSkeleton,onChange:i}),(0,Q.jsx)(`p`,{id:`advisor-model-hint`,className:`muted setting-hint`,children:a(`advisor.modelHint`)}),s.showSkeleton&&(0,Q.jsx)($,{tone:`warn`,children:a(`common.loading`)}),s.showError&&!s.showSkeleton&&(0,Q.jsxs)($,{tone:`err`,children:[a(`advisor.modelsLoadFailed`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:r,onClick:()=>o.refresh(),children:a(`common.retry`)})]}),!s.showSkeleton&&!s.showError&&c.length===0&&(0,Q.jsxs)($,{tone:`warn`,children:[a(`advisor.modelsEmpty`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:r,onClick:()=>o.refresh(),children:a(`common.retry`)})]}),!s.showSkeleton&&!s.showError&&l&&(0,Q.jsx)($,{tone:`warn`,children:a(`advisor.modelUnavailable`)})]})}function $C({entries:e}){let t=n();return e.length?(0,Q.jsx)(`div`,{className:`tbl-wrap`,children:(0,Q.jsxs)(`table`,{className:`tbl advisor-activity-table`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:t(`advisor.activity.started`)}),(0,Q.jsx)(`th`,{children:t(`advisor.activity.trigger`)}),(0,Q.jsx)(`th`,{children:t(`advisor.model`)}),(0,Q.jsx)(`th`,{children:t(`advisor.effort`)}),(0,Q.jsx)(`th`,{children:t(`advisor.activity.tokens`)}),(0,Q.jsx)(`th`,{children:t(`advisor.activity.duration`)})]})}),(0,Q.jsx)(`tbody`,{children:e.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`time`,{dateTime:new Date(e.startedAt).toISOString(),children:new Date(e.startedAt).toLocaleTimeString()})}),(0,Q.jsxs)(`td`,{children:[(0,Q.jsx)(`div`,{children:t(`advisor.activity.trigger.${e.trigger}`)}),(0,Q.jsx)(`span`,{className:e.status===`ok`?`badge badge-green`:`badge badge-muted`,children:t(`advisor.activity.status.${e.status}`)})]}),(0,Q.jsxs)(`td`,{children:[(0,Q.jsx)(`code`,{children:e.advisorModel}),(0,Q.jsx)(`div`,{className:`muted`,children:(0,Q.jsx)(`code`,{children:e.workerModel})})]}),(0,Q.jsx)(`td`,{children:(0,Q.jsxs)(`code`,{children:[e.requestedEffort,` → `,e.effectiveEffort??t(`logs.tokens.unreported`)]})}),(0,Q.jsx)(`td`,{className:`num`,children:e.usage?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{title:t(`logs.tokens.input`),children:e.usage.inputTokens??`—`}),` / `,(0,Q.jsx)(`span`,{title:t(`logs.tokens.output`),children:e.usage.outputTokens??`—`})]}):t(`logs.tokens.unreported`)}),(0,Q.jsx)(`td`,{className:`num`,children:e.durationMs===null?`—`:(0,Q.jsxs)(Q.Fragment,{children:[e.durationMs,` ms`]})})]},e.id))})]})}):(0,Q.jsx)(`p`,{className:`muted`,children:t(`advisor.activity.empty`)})}function ew({apiBase:e}){let t=n(),r=uo(`advisor-activity:${e}`,[e],async t=>{let n=await fetch(`${e}/api/advisor/activity`,{signal:t});if(!n.ok)throw Error(String(n.status));return await n.json()},{isEmpty:e=>e.entries.length===0,pollMs:5e3,pauseWhenHidden:!0}),{state:i}=r;return(0,Q.jsxs)(`section`,{"aria-label":t(`advisor.activity.title`),children:[(0,Q.jsx)(`h3`,{children:t(`advisor.activity.title`)}),(0,Q.jsx)(`p`,{className:`muted`,children:t(`advisor.activity.note`)}),i.showSkeleton&&(0,Q.jsx)(`p`,{className:`muted`,children:t(`common.loading`)}),i.showError&&(0,Q.jsxs)($,{tone:`err`,children:[t(`advisor.activity.failed`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>r.refresh(),children:t(`common.retry`)})]}),i.data&&(0,Q.jsx)($C,{entries:i.data.entries})]})}var tw=[`low`,`medium`,`high`,`xhigh`,`max`,`ultra`];function nw({apiBase:e,initial:t}){let r=n(),[i,a]=(0,Z.useState)(t),[o,s]=(0,Z.useState)(t),[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(``),m=(0,Z.useRef)(null);(0,Z.useEffect)(()=>()=>{m.current!==null&&(clearTimeout(m.current),m.current=null)},[]);let h=(0,Z.useCallback)(async()=>{m.current!==null&&(clearTimeout(m.current),m.current=null),d(!1),l(!0),p(``);let t=o;try{let n=await fetch(`${e}/api/advisor/settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({enabled:t.enabled,model:t.model,effort:t.effort,policy:t.policy,...t.maxConsultationsPerTask===void 0?{}:{maxConsultationsPerTask:t.maxConsultationsPerTask},timeoutMs:t.timeoutMs,contextSharingConsent:t.contextSharingConsent})});if(!n.ok){let e=await n.json().catch(()=>null);p(e?.error?.message??String(n.status));return}let r=await n.json();a(r.settings),s(e=>JSON.stringify(e)===JSON.stringify(t)?r.settings:e),d(!0),m.current=setTimeout(()=>{m.current=null,d(!1)},2500)}catch(e){p(e instanceof Error?e.message:String(e))}finally{l(!1)}},[e,o]),g=(0,Z.useCallback)(e=>{p(``),s(t=>({...t,...e}))},[]),_=JSON.stringify(o)!==JSON.stringify(i),v=o.enabled&&o.model.trim()===``,y=o.enabled&&o.model.trim()!==``&&o.contextSharingConsent!==`v1`;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{style:{marginTop:`0.75rem`},children:[(0,Q.jsxs)(`div`,{className:`advisor-editor-row`,children:[(0,Q.jsx)(`span`,{className:`advisor-editor-label`,children:r(`advisor.enabled`)}),(0,Q.jsxs)(`label`,{className:`toggle`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:o.enabled,disabled:c,"aria-label":r(`advisor.enabled`),onChange:e=>g({enabled:e.target.checked})}),(0,Q.jsx)(`span`,{className:`slider`,"aria-hidden":`true`})]})]}),(0,Q.jsxs)(`div`,{className:`advisor-editor-row`,children:[(0,Q.jsx)(`label`,{htmlFor:`advisor-model`,className:`advisor-editor-label`,children:r(`advisor.model`)}),(0,Q.jsx)(QC,{apiBase:e,value:o.model,disabled:c,onChange:e=>g({model:e})})]}),(0,Q.jsxs)(`div`,{className:`advisor-editor-row`,children:[(0,Q.jsx)(`label`,{htmlFor:`advisor-effort`,className:`advisor-editor-label`,children:r(`advisor.effort`)}),(0,Q.jsx)(`select`,{id:`advisor-effort`,value:o.effort,disabled:c,onChange:e=>g({effort:e.target.value}),children:tw.map(e=>(0,Q.jsx)(`option`,{value:e,children:r(`models.reasoningEffort.${e}`)},e))})]}),(0,Q.jsxs)(`div`,{className:`advisor-editor-row`,children:[(0,Q.jsx)(`label`,{htmlFor:`advisor-policy`,className:`advisor-editor-label`,children:r(`advisor.policy`)}),(0,Q.jsxs)(`select`,{id:`advisor-policy`,value:o.policy,disabled:c,onChange:e=>g({policy:e.target.value}),children:[(0,Q.jsx)(`option`,{value:`manual`,children:r(`advisor.policy.manual`)}),(0,Q.jsx)(`option`,{value:`preflight`,children:r(`advisor.policy.preflight`)}),(0,Q.jsx)(`option`,{value:`adaptive`,children:r(`advisor.policy.adaptive`)})]})]}),o.policy===`adaptive`&&(0,Q.jsxs)(`div`,{className:`advisor-editor-row`,children:[(0,Q.jsx)(`label`,{htmlFor:`advisor-task-limit`,className:`advisor-editor-label`,children:r(`advisor.taskLimit`)}),(0,Q.jsx)(`select`,{id:`advisor-task-limit`,value:o.maxConsultationsPerTask??3,disabled:c,onChange:e=>g({maxConsultationsPerTask:Number(e.target.value)}),children:[1,2,3].map(e=>(0,Q.jsx)(`option`,{value:e,children:e},e))})]}),o.policy===`adaptive`&&(0,Q.jsx)(`p`,{className:`muted`,children:r(`advisor.adaptiveNote`)}),(0,Q.jsx)(`div`,{style:{margin:`0.8rem 0`},children:(0,Q.jsxs)(`label`,{style:{display:`flex`,alignItems:`flex-start`,gap:`0.6rem`},children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:o.contextSharingConsent===`v1`,disabled:c,"aria-label":r(`advisor.consent.label`),onChange:e=>g({contextSharingConsent:e.target.checked?`v1`:null})}),(0,Q.jsx)(`span`,{children:r(`advisor.consent.label`)})]})}),(0,Q.jsxs)(`div`,{className:`advisor-editor-row`,children:[(0,Q.jsx)(`label`,{htmlFor:`advisor-timeout`,className:`advisor-editor-label`,children:r(`advisor.timeout`)}),(0,Q.jsx)(`input`,{id:`advisor-timeout`,type:`number`,min:1e3,max:6e5,value:o.timeoutMs,disabled:c,onChange:e=>{let t=e.target.value.trim();if(t===``)return;let n=Number(t);Number.isFinite(n)&&g({timeoutMs:n})}})]})]}),v&&(0,Q.jsx)($,{tone:`warn`,children:r(`advisor.warning.noModel`)}),y&&(0,Q.jsx)($,{tone:`warn`,children:r(`advisor.consent.required`)}),f&&(0,Q.jsx)($,{tone:`err`,children:f}),u&&(0,Q.jsx)($,{tone:`ok`,children:r(`advisor.saved`)}),(0,Q.jsx)(`div`,{style:{marginTop:`0.75rem`},children:(0,Q.jsx)(`button`,{type:`button`,className:`btn`,disabled:!_||c,onClick:()=>void h(),children:r(c?`common.loading`:`advisor.save`)})})]})}function rw({apiBase:e}){let t=n(),r=uo(`advisor-settings:${e}`,[e],async t=>{let n=await fetch(`${e}/api/advisor/settings`,{signal:t});if(!n.ok)throw Error(String(n.status));return await n.json()},{isEmpty:()=>!1}),{state:i}=r,a=(0,Q.jsx)(`h2`,{children:t(`nav.advisor`)});return(0,Q.jsxs)(`section`,{className:`panel`,children:[a,(0,Q.jsx)(`p`,{className:`muted`,children:t(`advisor.description`)}),(0,Q.jsxs)(`details`,{className:`advisor-notices`,style:{margin:`0.5rem 0`},children:[(0,Q.jsx)(`summary`,{className:`muted text-label`,style:{cursor:`pointer`,padding:`2px 2px`},children:t(`advisor.notices`)}),(0,Q.jsx)($,{tone:`warn`,children:t(`advisor.costNote`)}),(0,Q.jsx)($,{tone:`warn`,children:t(`advisor.privacyNote`)}),(0,Q.jsx)($,{tone:`warn`,children:t(`advisor.disclosure`)})]}),i.showSkeleton&&(0,Q.jsx)($,{tone:`warn`,children:t(`common.loading`)}),i.showError&&!i.showSkeleton&&(0,Q.jsxs)($,{tone:`err`,children:[t(`advisor.loadFailed`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>r.refresh(),children:t(`common.retry`)})]}),i.data!==void 0&&(0,Q.jsx)(nw,{apiBase:e,initial:i.data.settings},r.hasSucceeded?`ready`:`cold`),(0,Q.jsx)(ew,{apiBase:e})]})}function iw(e,t){let n=new Set(t);return[...new Set([...e.filter(e=>n.has(e)),...t])]}function aw({apiBase:e,roster:t}){let r=n(),[i,a]=(0,Z.useState)(null),[o,s]=(0,Z.useState)(``),[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(``),[f,p]=(0,Z.useState)(!1),[m,h]=(0,Z.useState)(0),[g,_]=(0,Z.useState)(null),v=c||g?.retry!==m||g.t!==r,y=(0,Z.useRef)(!1),b=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>{b.current=!0,y.current=!0;let t=new AbortController,n=!1;return(async()=>{try{let i=await vn(await fetch(`${e}/api/subagent-models`,{signal:t.signal}),r(`sub.loadFail`));if(n)return;let o={force:i?.force??null,forceAvailable:i?.forceAvailable??[],forceStatus:i?.forceStatus??null};a(o),s(o.force??``),d(``)}catch{n||d(r(`sub.loadFail`))}finally{n||(y.current=!1,_({retry:m,t:r}))}})(),()=>{n=!0,b.current=!1,t.abort()}},[e,m,r]);async function x(t){if(!(!i||v||y.current)){y.current=!0,l(!0),d(``),p(!1);try{let n=await vn(await fetch(`${e}/api/subagent-models`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({force:t})}),r(`sub.saveFailed`));if(!b.current)return;a(e=>e&&{...e,force:n?.force??null,forceStatus:null}),s(n?.force??o),p(!0),h(e=>e+1)}catch{b.current&&d(r(`sub.saveFailed`))}finally{y.current=!1,b.current&&l(!1)}}}let S=iw(t,i?.forceAvailable??[]),C=i?.force??o,w=S.includes(C),T=i?.forceStatus;return(0,Q.jsxs)(`section`,{className:`panel`,children:[(0,Q.jsx)(`h3`,{children:r(`sub.forceTitle`)}),(0,Q.jsx)(ln,{on:!!i?.force,disabled:!i||v||!i.force&&!w,label:r(`sub.forceTitle`),onClick:()=>{x(i?.force?null:o)}}),(0,Q.jsxs)(`label`,{className:`field-label`,children:[r(`sub.forceModel`),(0,Q.jsxs)(`select`,{className:`input`,value:C,disabled:!i||v,onChange:e=>{let t=e.target.value;i?.force?x(t):s(t)},children:[(0,Q.jsx)(`option`,{value:``,disabled:!0,children:r(`sub.forceChoose`)}),C&&!w&&(0,Q.jsx)(`option`,{value:C,disabled:!0,children:C}),S.map(e=>(0,Q.jsx)(`option`,{value:e,children:e},e))]})]}),(0,Q.jsx)(`p`,{className:`muted`,children:r(`sub.forceHelp`)}),(0,Q.jsx)(`p`,{className:`muted`,children:r(`sub.forceScope`)}),i?.force&&(!w||T?.targetValid===!1)&&(0,Q.jsx)($,{tone:`warn`,children:r(`sub.forceInvalid`)}),i?.force&&T?.support===`unsupported`&&(0,Q.jsx)($,{tone:`warn`,children:r(`sub.forceOld`)}),i?.force&&(!T||T.support===`unknown`)&&(0,Q.jsx)($,{tone:`warn`,children:r(`sub.forceUnknown`)}),i?.force&&T?.settingsOverride&&(0,Q.jsx)($,{tone:`warn`,children:r(`sub.forceOverride`)}),i?.force&&T?.settingsReadable===!1&&(0,Q.jsx)($,{tone:`warn`,children:r(`sub.forceSettingsUnknown`)}),f&&(0,Q.jsx)($,{tone:`ok`,children:r(`sub.forceSaved`)}),u&&(0,Q.jsxs)($,{tone:`err`,children:[u,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:v,onClick:()=>h(e=>e+1),children:r(`common.retry`)})]})]})}var ow=`section`;function sw(e,t){return[e,ow,t].join(`-`)}function cw(e){return[e,ow,``].join(`-`)}var lw=1200;function uw({scope:e,items:t,ariaLabel:n,mobileReadingLine:r}){let[i,a]=(0,Z.useState)(()=>r&&window.matchMedia(`(max-width: 760px)`).matches?r:72);(0,Z.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,Z.useState)(t[0]?.id??``),c=(0,Z.useRef)(null),l=(0,Z.useRef)(null),u=(0,Z.useCallback)(()=>{c.current=null,l.current!==null&&(clearTimeout(l.current),l.current=null)},[]),d=(0,Z.useCallback)(()=>{u();let n=null,r=1/0;for(let a of t){let t=document.getElementById(sw(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,Z.useEffect)(()=>()=>u(),[u]),(0,Z.useEffect)(()=>{if(typeof IntersectionObserver>`u`)return;let n=t.map(t=>document.getElementById(sw(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(sw(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(cw(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(sw(e,t));n&&(c.current=t,l.current!==null&&clearTimeout(l.current),l.current=setTimeout(d,lw),s(t),n.scrollIntoView({behavior:`smooth`,block:`start`}))};return(0,Q.jsx)(`div`,{className:`page-tabs section-tabs`,role:`tablist`,"aria-label":n,children:t.map(t=>(0,Q.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":o===t.id,"aria-controls":sw(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,Q.jsx)(`span`,{className:`section-tab-meta`,children:t.meta}):null]},t.id))})}var dw=1500,fw={fast:`integrations.lazycodexRoles.auto.tierFast`,standard:`integrations.lazycodexRoles.auto.tierStandard`,frontier:`integrations.lazycodexRoles.auto.tierFrontier`},pw={glance:`integrations.lazycodexRoles.auto.effortGlance`,measured:`integrations.lazycodexRoles.auto.effortMeasured`,thorough:`integrations.lazycodexRoles.auto.effortThorough`,exhaustive:`integrations.lazycodexRoles.auto.effortExhaustive`};function mw({apiBase:e,model:t,effort:r,available:i,saving:a,onAccept:o}){let s=n(),[c,l]=(0,Z.useState)(``),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(null),[m,h]=(0,Z.useState)(null),g=e=>{let t=i.find(t=>t.namespaced===e);return t?we(`${t.provider}/${t.model}`,s):e},_=async()=>{d(!0),p(null);try{let t=await fetch(`${e}/api/injection-model/suggest`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({work:c.trim()})});h(await vn(t,s(`sub.suggest.failed`))??null)}catch(e){h(null),p(e instanceof Error&&e.message?e.message:s(`sub.suggest.failed`))}finally{d(!1)}},v=m?.proposal,y=!!v?.proposedModel&&v.proposedModel===t&&(v.proposedEffort??``)===r,b=u?s(`sub.suggest.running`):m?s(`sub.suggest.title`):``;return(0,Q.jsxs)(`div`,{className:`swi-suggest`,children:[(0,Q.jsx)(`div`,{className:`sr-only`,"aria-live":`polite`,"aria-atomic":`true`,children:b}),(0,Q.jsx)(`label`,{className:`swi-suggest-label`,htmlFor:`swi-suggest-work`,children:s(`sub.suggest.label`)}),(0,Q.jsxs)(`div`,{className:`swi-suggest-input`,children:[(0,Q.jsx)(`textarea`,{id:`swi-suggest-work`,className:`input`,rows:2,maxLength:dw,value:c,placeholder:s(`sub.suggest.placeholder`),onChange:e=>l(e.target.value),disabled:u}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:u||a||c.trim()===``,onClick:()=>void _(),children:s(u?`sub.suggest.running`:`sub.suggest.submit`)})]}),f&&(0,Q.jsx)($,{tone:`err`,children:f}),m&&v&&(0,Q.jsxs)(`section`,{className:`swi-suggest-result`,"aria-label":s(`sub.suggest.title`),children:[(0,Q.jsxs)(`div`,{className:`swi-suggest-head`,children:[v.tier&&v.effortIntent&&(0,Q.jsx)(`span`,{className:`font-semibold`,children:s(`integrations.lazycodexRoles.auto.tierEffort`,{tier:s(fw[v.tier]),effort:s(pw[v.effortIntent])})}),(0,Q.jsx)(`span`,{className:`muted setting-hint`,children:s(`integrations.lazycodexRoles.auto.sizedWith`,{model:m.sizingModel})})]}),m.sizingError&&(0,Q.jsx)($,{tone:`warn`,children:s(`integrations.lazycodexRoles.auto.sizingFailed`,{error:m.sizingError})}),v.status===`unsized`?(0,Q.jsx)(`p`,{className:`muted setting-hint`,children:s(`integrations.lazycodexRoles.auto.unsized`,{reason:v.reason??``})}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`swi-suggest-change`,children:[(0,Q.jsxs)(`span`,{children:[v.model?g(v.model):s(`dash.injectionNone`),v.effort?` · ${v.effort}`:``]}),(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`→`}),v.proposedModel?(0,Q.jsxs)(`strong`,{children:[g(v.proposedModel),v.proposedEffort?` · ${v.proposedEffort}`:``]}):(0,Q.jsx)(`span`,{className:`muted`,children:s(`integrations.lazycodexRoles.auto.unassigned`,{reason:v.reason??``})})]}),v.rationale&&(0,Q.jsx)(`p`,{children:v.rationale}),v.moveUpIf&&(0,Q.jsx)(`p`,{className:`muted setting-hint`,children:s(`integrations.lazycodexRoles.auto.moveUp`,{text:v.moveUpIf})}),v.moveDownIf&&(0,Q.jsx)(`p`,{className:`muted setting-hint`,children:s(`integrations.lazycodexRoles.auto.moveDown`,{text:v.moveDownIf})})]}),(0,Q.jsxs)(`div`,{className:`swi-suggest-actions`,children:[y?(0,Q.jsx)(`span`,{className:`swi-suggest-done`,children:s(`integrations.lazycodexRoles.auto.alreadySet`)}):v.status===`proposed`&&v.proposedModel&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:a,onClick:()=>o({model:v.proposedModel,effort:v.proposedEffort??null}),children:s(`sub.suggest.accept`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:a,onClick:()=>h(null),children:s(`integrations.lazycodexRoles.auto.discard`)})]})]})]})}function hw({apiBase:e,model:t,effort:r,efforts:i,available:a,guidanceEnabled:o,syncCodexDefaults:s,saving:c,onSave:l,ultraMode:u,ultraSaving:d,onUltraModeSave:f,ultraLoadFailed:p,onUltraModeRetry:m,fallback:h,fallbackPollMs:g,fallbackBusy:_,availableModels:v,onFallbackChange:y,onFallbackPollMsChange:b,onFallbackSave:x}){let S=n(),C=(u.hintText??``).trim().length>0,w=a.some(e=>e.namespaced===t&&(e.provider!==`openai`||e.namespaced!==e.model)),T=u.enabled||u.multiAgentMode!==`v1`&&!(u.multiAgentMode===`v2`&&u.keepNativeChatGptOnV1),E=!p&&u.loaded===!0&&w&&T,D=new Set(v),O=new Set(h),[k,A]=(0,Z.useState)(()=>({pollMs:g,text:String(g)}));Object.is(k.pollMs,g)||A({pollMs:g,text:Number.isFinite(g)?String(g):``});let j=(0,Z.useRef)(null),[M,N]=(0,Z.useState)(!1),[P,F]=(0,Z.useState)(()=>({models:h,rows:h.map((e,t)=>({model:e,id:t})),nextId:h.length})),I=P.rows;if(P.models!==h){let e=[...P.rows],t=P.nextId;I=h.map(n=>{let r=e.findIndex(e=>e.model===n);return r>=0?e.splice(r,1)[0]:{model:n,id:t++}}),F({models:h,rows:I,nextId:t})}let L=(0,Z.useRef)(null);(0,Z.useLayoutEffect)(()=>{let e=L.current;if(!e)return;L.current=null;let t=j.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)`)??j.current?.querySelector(`button[role="combobox"]`))?.focus()},[h]);let R=Number.isInteger(g)&&g>=5e3&&g<=6e5,z=(e,t)=>{let n=[...h],r=e+t;if(_||r<0||r>=n.length)return;[n[e],n[r]]=[n[r],n[e]];let i=[...I];[i[e],i[r]]=[i[r],i[e]],F({...P,models:n,rows:i}),L.current={row:r,action:t===-1?`up`:`down`},y(n)};return(0,Q.jsxs)(`div`,{className:`swi-delegation`,children:[p&&(0,Q.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-copy`,children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:S(`sub.ultraMode`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:S(`sub.ultraModeLoadFail`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:m,children:S(`common.retry`)})]}),(0,Q.jsxs)(`div`,{className:`swi-delegation-row swi-delegation-model-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-copy`,children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:S(`sub.delegation.model`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:S(`sub.delegation.modelHint`)})]}),(0,Q.jsxs)(`div`,{className:`swi-delegation-controls`,children:[(0,Q.jsx)(dn,{value:t,options:[{value:``,label:S(`dash.injectionNone`)},...a.map(e=>({value:e.namespaced,label:we(`${e.provider}/${e.model}`,S)}))],onChange:e=>l({model:e||null,effort:r||null}),disabled:c,label:S(`dash.injectionLabel`),align:`right`}),t&&i.length>0&&(0,Q.jsx)(dn,{value:r,options:[{value:``,label:S(`dash.injectionEffortNone`)},...i.map(e=>({value:e,label:e}))],onChange:e=>l({model:t||null,effort:e||null}),disabled:c,label:S(`dash.injectionEffortLabel`),align:`right`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-expanded":M,onClick:()=>N(e=>!e),children:S(`sub.suggest.button`)})]})]}),M&&(0,Q.jsx)(`div`,{className:`swi-delegation-row`,children:(0,Q.jsx)(mw,{apiBase:e,model:t,effort:r,available:a,saving:c,onAccept:l})}),E&&(0,Q.jsx)(`div`,{className:`swi-delegation-row swi-v2-compatibility`,role:`note`,children:(0,Q.jsxs)(`div`,{className:`setting-copy`,children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:S(`sub.v2Compatibility.title`)}),(0,Q.jsx)(`p`,{className:`muted setting-hint`,children:S(`sub.v2Compatibility.risk`)}),(0,Q.jsx)(`p`,{className:`muted setting-hint`,children:S(`sub.v2Compatibility.recoveryUnknown`)}),(0,Q.jsx)(`a`,{href:`https://github.com/lidge-jun/opencodex/issues/92`,target:`_blank`,rel:`noreferrer`,children:S(`sub.v2Compatibility.details`)})]})}),(0,Q.jsxs)(`div`,{className:`swi-delegation-row swi-fallback-editor`,children:[(0,Q.jsxs)(`div`,{className:`setting-copy`,children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:S(`sub.fallbackLabel`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:S(`sub.fallbackHint`)})]}),(0,Q.jsxs)(`div`,{className:`swi-fallback-controls`,ref:j,children:[h.map((e,t)=>(0,Q.jsxs)(`div`,{className:`swi-fallback-row`,children:[(0,Q.jsxs)(`span`,{className:`swi-fallback-model`,children:[t+1,`. `,e,!D.has(e)&&(0,Q.jsx)(`span`,{className:`muted setting-hint`,children:S(`sub.fallbackUnavailable`)})]}),(0,Q.jsxs)(`span`,{className:`swi-fallback-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,"data-action":`up`,onClick:()=>z(t,-1),disabled:_||t===0,"aria-label":S(`sub.moveUp`,{m:e}),children:(0,Q.jsx)(Je,{})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,"data-action":`down`,onClick:()=>z(t,1),disabled:_||t===h.length-1,"aria-label":S(`sub.moveDown`,{m:e}),children:(0,Q.jsx)(tt,{})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,"data-action":`remove`,onClick:()=>{let e=h.filter((e,n)=>n!==t);F({...P,models:e,rows:I.filter((e,n)=>n!==t)}),L.current={row:Math.max(0,Math.min(t,h.length-2)),action:`remove`},y(e)},disabled:_,"aria-label":S(`sub.removeAria`,{m:e}),children:(0,Q.jsx)(xe,{})})]})]},I[t].id)),(0,Q.jsx)(dn,{value:``,label:S(`sub.fallbackAdd`),options:[{value:``,label:S(`sub.fallbackAdd`)},...v.filter(e=>!O.has(e)).map(e=>({value:e,label:e}))],onChange:e=>{e&&!O.has(e)&&y([...h,e])},disabled:_}),(0,Q.jsxs)(`label`,{className:`setting-hint`,children:[S(`sub.fallbackPoll`),(0,Q.jsx)(`input`,{className:`input`,type:`number`,min:5e3,max:6e5,step:1e3,value:k.text,onChange:e=>{let t=e.currentTarget.value,n=Number(t),r=t.trim()!==``&&Number.isFinite(n)?n:NaN;A({pollMs:r,text:t}),b(r)},disabled:_,"aria-invalid":!R}),` ms`]}),!R&&(0,Q.jsx)(`div`,{className:`setting-hint`,role:`alert`,children:S(`sub.fallbackPollInvalid`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:x,disabled:_||!R,children:S(`common.save`)})]})]}),(0,Q.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-copy`,children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:S(`dash.syncCodexSubagentDefaults`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:S(`dash.syncCodexSubagentDefaultsHint`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`switch ${s?`on`:``}`,onClick:()=>l({syncCodexSubagentDefaults:!s}),disabled:c||!t,"aria-label":S(`dash.syncCodexSubagentDefaults`),"aria-pressed":s,children:(0,Q.jsx)(`span`,{className:`knob`})})]}),(0,Q.jsxs)(`details`,{className:`swi-advanced`,children:[(0,Q.jsx)(`summary`,{className:`muted text-label`,children:S(`sub.advanced`)}),(0,Q.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-copy`,children:[(0,Q.jsxs)(`div`,{className:`font-semibold`,style:{display:`inline-flex`,alignItems:`center`,gap:6},children:[S(`models.v2Label`),(0,Q.jsxs)(pn,{content:S(`models.v2Help`),side:`top`,maxWidth:380,children:[(0,Q.jsx)(De,{width:13,height:13,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`sr-only`,children:S(`models.v2Label`)})]})]}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:(0,Q.jsx)(`a`,{className:`text-control`,href:`https://opencodex.me/guides/sub-agent-surface/`,target:`_blank`,rel:`noreferrer`,style:{color:`var(--accent)`},children:S(`models.v2DocsLink`)})})]}),(0,Q.jsx)(`div`,{className:`swi-delegation-controls`,children:(0,Q.jsx)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":S(`models.v2Label`),children:[`v1`,`default`,`v2`].map(e=>(0,Q.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":u.multiAgentMode===e,className:`btn btn-sm${u.multiAgentMode===e?` btn-primary`:` btn-ghost`}`,style:{background:u.multiAgentMode===e?void 0:`transparent`,color:u.multiAgentMode===e?void 0:`var(--muted)`},disabled:d||p,onClick:()=>{u.multiAgentMode!==e&&f({multiAgentMode:e})},children:S(`models.v2Mode_${e}`)},e))})})]}),(0,Q.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-copy`,children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:S(`dash.multiAgentGuidance`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:S(`dash.multiAgentGuidanceHint`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`switch ${o?`on`:``}`,onClick:()=>l({multiAgentGuidanceEnabled:!o}),disabled:c,"aria-label":S(`dash.multiAgentGuidance`),"aria-pressed":o,children:(0,Q.jsx)(`span`,{className:`knob`})})]}),(0,Q.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-copy`,children:[(0,Q.jsx)(`div`,{className:`font-semibold`,children:S(`sub.ultraMode`)}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:S(`sub.ultraModeHint`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`switch ${C?`on`:``}`,onClick:()=>{C?f({multiAgentModeHintText:null}):u.recommendation&&f({multiAgentModeHintText:u.recommendation.text})},disabled:c||d||!C&&(!u.multiAgentV2Enabled||!u.recommendation),"aria-label":S(`sub.ultraMode`),"aria-pressed":C,children:(0,Q.jsx)(`span`,{className:`knob`})}),!u.multiAgentV2Enabled&&(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:S(`sub.ultraModeV2Required`)})]}),C&&(0,Q.jsx)(`div`,{className:`swi-delegation-row swi-ultra-mode-editor`,children:(0,Q.jsx)(gw,{initialHint:u.hintText??``,disabled:c||d,onSave:f,preset:u.recommendation?.text??null,labels:{text:S(`sub.ultraModeText`),preset:S(`sub.ultraModePreset`),save:S(`common.save`)}},u.hintText)})]})]})}function gw({initialHint:e,disabled:t,onSave:n,preset:r,labels:i}){let[a,o]=(0,Z.useState)(e);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.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,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{r!==null&&o(r)},disabled:t||r===null,children:i.preset}),(0,Q.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 _w({available:e,fallbackAvailable:t,chosen:r,onToggle:i,onMove:a,fallback:o,fallbackPollMs:s,fallbackBusy:c,onFallbackChange:l,onFallbackPollMsChange:u,onFallbackSave:d,delegation:f}){let p=n(),[m,h]=(0,Z.useState)(``),g=(0,Z.useMemo)(()=>new Set(r),[r]),_=r.length>=5,v=(0,Z.useMemo)(()=>{let t=m.trim().toLowerCase();return e.filter(e=>!t||e.toLowerCase().includes(t))},[e,m]),y=(0,Z.useMemo)(()=>[{id:`featured`,label:p(`sub.featured`),meta:`${r.length}/5`},{id:`models`,label:p(`sub.models`),meta:String(v.length)},{id:`settings`,label:p(`sub.settings`)}],[p,r.length,v.length]);return(0,Q.jsxs)(`div`,{className:`subagents-workspace-shell`,children:[(0,Q.jsx)(uw,{scope:`subagents`,items:y,ariaLabel:p(`sub.sections`)}),(0,Q.jsxs)(`div`,{className:`subagents-workspace-root`,children:[(0,Q.jsxs)(`section`,{id:sw(`subagents`,`featured`),className:`subagents-workspace-section`,"aria-label":p(`sub.featured`),children:[(0,Q.jsxs)(`div`,{className:`swi-featured-head`,children:[(0,Q.jsx)(`h2`,{className:`swi-featured-title`,children:p(`sub.featured`)}),(0,Q.jsxs)(`span`,{className:`swi-featured-count`,children:[r.length,`/`,5]}),(0,Q.jsxs)(pn,{content:(0,Q.jsx)(O,{k:`sub.orderHint`,cmd:`spawn_agent`}),side:`bottom`,maxWidth:380,children:[(0,Q.jsx)(De,{width:14,height:14,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`sr-only`,children:p(`sub.orderHintAria`)})]})]}),r.length===0?(0,Q.jsx)(`div`,{className:`swi-featured-empty`,children:p(`sub.noneSelected`)}):(0,Q.jsx)(`div`,{className:`swi-featured-list`,children:r.map((e,t)=>(0,Q.jsxs)(`div`,{className:`swi-featured-row`,children:[(0,Q.jsx)(`span`,{className:`swi-featured-pos`,children:t+1}),(0,Q.jsx)(`span`,{className:`swi-featured-name`,children:zv(e)}),(0,Q.jsxs)(`span`,{className:`swi-featured-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,onClick:()=>a(t,-1),disabled:t===0,"aria-label":p(`sub.moveUp`,{m:e}),children:(0,Q.jsx)(Je,{})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,onClick:()=>a(t,1),disabled:t===r.length-1,"aria-label":p(`sub.moveDown`,{m:e}),children:(0,Q.jsx)(tt,{})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,onClick:()=>i(e),"aria-label":p(`sub.removeAria`,{m:e}),style:{color:`var(--red)`},children:(0,Q.jsx)(xe,{})})]})]},e))})]}),(0,Q.jsxs)(`section`,{id:sw(`subagents`,`models`),className:`subagents-workspace-section`,"aria-label":p(`sub.models`),children:[(0,Q.jsxs)(`div`,{className:`swi-featured-head`,children:[(0,Q.jsx)(`h2`,{className:`swi-featured-title`,children:p(`sub.models`)}),(0,Q.jsx)(`span`,{className:`swi-featured-count`,children:v.length})]}),(0,Q.jsxs)(`div`,{className:`swi-picker-box`,children:[(0,Q.jsx)(`div`,{className:`subagents-workspace-rail-search`,children:(0,Q.jsx)(`input`,{className:`input`,value:m,onChange:e=>h(e.target.value),placeholder:p(`sub.search`),"aria-label":p(`sub.search`)})}),(0,Q.jsx)(`div`,{className:`subagents-workspace-rail-list`,children:v.length===0?(0,Q.jsx)(`span`,{className:`subagents-workspace-rail-empty`,children:p(`sub.noModels`)}):v.map(e=>{let t=g.has(e),n=t?r.indexOf(e)+1:null,a=!t&&_;return(0,Q.jsxs)(`div`,{className:`subagents-workspace-rail-row${t?` subagents-workspace-rail-row--selected`:``}`,children:[(0,Q.jsxs)(`span`,{className:`subagents-workspace-rail-row-main`,children:[(0,Q.jsx)(`span`,{className:`swi-rail-priority`,children:n??``}),(0,Q.jsx)(Qe,{className:`swi-rail-icon`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`subagents-workspace-rail-name`,children:zv(e)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`subagents-workspace-rail-toggle${t?` subagents-workspace-rail-toggle--on`:``}${a?` subagents-workspace-rail-toggle--disabled`:``}`,onClick:()=>{a||i(e)},disabled:a,"aria-pressed":t,"aria-label":p(t?`sub.workspace.removeFromFeatured`:`sub.workspace.addToFeatured`,{m:e}),title:t?p(`sub.workspace.removeFromFeatured`,{m:e}):_?p(`sub.workspace.featuredFull`):p(`sub.workspace.addToFeatured`,{m:e}),children:t?(0,Q.jsx)(Oe,{style:{width:14,height:14}}):(0,Q.jsx)(I,{style:{width:14,height:14}})})]},e)})})]})]}),(0,Q.jsxs)(`section`,{id:sw(`subagents`,`settings`),className:`subagents-workspace-section`,"aria-label":p(`sub.settings`),children:[(0,Q.jsx)(`div`,{className:`swi-featured-head`,children:(0,Q.jsx)(`h2`,{className:`swi-featured-title`,children:p(`sub.settings`)})}),(0,Q.jsx)(hw,{apiBase:f.apiBase,model:f.model,effort:f.effort,efforts:f.efforts,available:f.available,guidanceEnabled:f.guidanceEnabled,syncCodexDefaults:f.syncCodexDefaults,saving:f.saving,onSave:f.onSave,ultraMode:f.ultraMode,ultraSaving:f.ultraSaving,onUltraModeSave:f.onUltraModeSave,ultraLoadFailed:f.ultraLoadFailed,onUltraModeRetry:f.onUltraModeRetry,fallback:o,fallbackPollMs:s,fallbackBusy:c,availableModels:t??e,onFallbackChange:l,onFallbackPollMsChange:u,onFallbackSave:d})]})]})]})}function vw(e){let[t,n]=(0,Z.useState)(!1),[r,i]=(0,Z.useState)(!1),[a,o]=(0,Z.useState)(``),[s,c]=(0,Z.useState)(``),[l,u]=(0,Z.useState)([]),[d,f]=(0,Z.useState)([]),[p,m]=(0,Z.useState)(!0),[h,g]=(0,Z.useState)(!1),_=(0,Z.useCallback)(e=>{let t=Po(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,Z.useEffect)(()=>{let t=!1;return(async()=>{try{let n=await jn(await fetch(`${e}/api/injection-model`));if(t)return;_(n)}catch{}finally{t||n(!0)}})(),()=>{t=!0}},[e,_]),{loaded:t,saving:r,model:a,effort:s,efforts:l,available:d,guidanceEnabled:p,syncCodexDefaults:h,save:(0,Z.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`);_(await jn(n))}catch{}finally{i(!1)}}},[e,_,r])}}var yw={enabled:!1,hintText:null,recommendation:null,multiAgentV2Enabled:!1,multiAgentMode:`default`};function bw(e){return io(e)}function xw({apiBase:e}){let t=n(),r=`ocx.subagents.v1:${e}`,i=bw(r),[a,o]=(0,Z.useState)(()=>i?.chosen??[]),[s,c]=(0,Z.useState)(()=>i?.fallback??[]),[l,u]=(0,Z.useState)(()=>i?.pollMs??6e4),[d,f]=(0,Z.useState)(!1),[p,m]=(0,Z.useState)(()=>Array.isArray(i?.fallback)&&Number.isInteger(i?.pollMs)),[h,g]=(0,Z.useState)(()=>i?.fallbackAvailable),[_,v]=(0,Z.useState)(``),[y,b]=(0,Z.useState)(!0),x=(0,Z.useRef)(null),S=(0,Z.useRef)({fallback:i?.fallback,pollMs:i?.pollMs,fallbackAvailable:i?.fallbackAvailable}),C=(0,Z.useRef)(0),w=(0,Z.useRef)(0),T=(0,Z.useRef)(!1),E=(0,Z.useRef)(i),[D,O]=(0,Z.useState)(``),[k,A]=(0,Z.useState)(!1),j=(0,Z.useRef)(!1),M=(0,Z.useRef)(null),N=(0,Z.useRef)(a),P=(0,Z.useCallback)(e=>{N.current=e,o(e)},[]),F=vw(e),[I,L]=(0,Z.useState)(null),R=I?.apiBase===e,z=R?I.mode:yw,[B,V]=(0,Z.useState)(!1),[H,U]=(0,Z.useState)(null),[ee,W]=(0,Z.useState)(!1),te=(0,Z.useRef)(0),G=(0,Z.useRef)(e);(0,Z.useEffect)(()=>{G.current=e,te.current++},[e]);let ne=(0,Z.useCallback)(async n=>{if(G.current!==e)return!1;let r=++te.current,i=await vn(await fetch(`${e}/api/v2`,{signal:n}),t(`sub.ultraModeLoadFail`));if(!i||n?.aborted||r!==te.current||G.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 L({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,Z.useEffect)(()=>{let e=new AbortController;return(async()=>{await ne(e.signal)})().catch(()=>{e.signal.aborted||(A(!1),W(!0),O(t(`sub.ultraModeLoadFail`)))}),()=>{e.abort()}},[ne,t]);let K=async n=>{if(B||!R||G.current!==e)return;let r=e;V(!0),O(``);try{if(await vn(await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)}),t(`sub.ultraModeSaveFail`)),G.current!==r||!await ne())return;A(!0),O(t(`sub.ultraModeSaved`))}catch(e){if(G.current!==r)return;A(!1),O(e instanceof Error&&e.message?e.message:t(`sub.networkError`))}finally{V(!1)}},re=(0,Z.useCallback)(async()=>{try{if(!await ne())return;A(!1),O(e=>e===t(`sub.ultraModeLoadFail`)?``:e)}catch{A(!1),W(!0),O(t(`sub.ultraModeLoadFail`))}},[ne,t]),q=(0,Z.useCallback)(async()=>{x.current?.abort();let n=new AbortController;x.current=n;let{signal:i}=n,a=C.current;try{let n=await vn(await fetch(`${e}/api/subagent-model-fallback`,{signal:i}));if(!n||!Array.isArray(n.models)||!n.models.every(e=>typeof e==`string`&&e.trim())||typeof n.pollMs!=`number`||!Number.isInteger(n.pollMs)||n.pollMs<5e3||n.pollMs>6e5||!Array.isArray(n.available)||!n.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:n.models,pollMs:n.pollMs,fallbackAvailable:n.available};S.current=o,c(o.fallback),u(o.pollMs),g(o.fallbackAvailable),m(!0),v(``),E.current&&(E.current={...E.current,...o},co(r,E.current))}catch(e){if(i.aborted||a!==C.current||T.current)return;m(!1),v(e instanceof Error&&!(e instanceof SyntaxError)?e.message:t(`sub.loadFail`))}finally{i.aborted||b(!1)}},[e,r,t]);(0,Z.useEffect)(()=>((async()=>{await q()})(),()=>{x.current?.abort()}),[q]);let J=(0,Z.useCallback)(async n=>{let i=w.current,a=await vn(await fetch(`${e}/api/subagent-models`,{signal:n}),t(`sub.loadFail`));if(!a)throw Error(t(`sub.loadFail`));let o=a.available??[],s=new Set(o),c=i===w.current&&!j.current,l={...S.current,available:o,chosen:c?(a.chosen??[]).filter(e=>s.has(e)):E.current?.chosen??[]};if(n?.aborted)throw n.reason;return E.current=l,c&&P(l.chosen),co(r,l),l},[e,r,P,t]),Y=uo(r,[e],J,{isEmpty:()=>!1,initialData:i??void 0}),{state:ie}=Y,X=Y.refresh,ae=ie.data??i,oe=ae?.available??[],se=async n=>{if(M.current=n,j.current)return;j.current=!0,O(``);let i=null,a=n;for(;M.current;){let n=M.current;M.current=null;try{a=(await vn(await fetch(`${e}/api/subagent-models`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({models:n})}),t(`sub.saveFailed`)))?.applied??n,E.current={...E.current,available:oe,chosen:a},co(r,E.current),i=null}catch(e){i=e}}w.current+=1,j.current=!1,i?(P(E.current?.chosen??[]),A(!1),O(i instanceof Error&&i.message?i.message:t(`sub.networkError`))):(P(a),A(!0),O(t(`sub.saved`,{n:a.length,cmd:`ocx sync`})))},ce=e=>{w.current+=1,P(e),se(e)},le=e=>{let t=N.current;!t.includes(e)&&t.length>=5||ce(t.includes(e)?t.filter(t=>t!==e):[...t,e])},ue=(e,t)=>{let n=e+t,r=[...N.current];n<0||n>=r.length||([r[e],r[n]]=[r[n],r[e]],ce(r))},de=async()=>{if(!p||T.current||!Number.isInteger(l)||l<5e3||l>6e5)return;T.current=!0,C.current+=1;let n=e;f(!0),O(``);try{let i=await vn(await fetch(`${e}/api/subagent-model-fallback`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({models:s,pollMs:l})}),t(`sub.fallbackSaveFailed`));if(G.current!==n)return;if(!i||!Array.isArray(i.models)||typeof i.pollMs!=`number`)throw Error(t(`sub.fallbackSaveFailed`));C.current+=1,c(i.models),u(i.pollMs),S.current={...S.current,fallback:i.models,pollMs:i.pollMs};let a={available:oe,chosen:E.current?.chosen??[],...S.current};E.current=a,co(r,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,f(!1)}};if(ie.showSkeleton&&!ae)return(0,Q.jsx)(lb,{label:t(`sub.loading`),rows:4});if(ie.kind===`failed-cold`){let e=ie.error instanceof Error?ie.error.message:t(`sub.loadFail`);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)($,{tone:`err`,children:e}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>X(),children:t(`common.retry`)})]})}return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`page-head`,children:(0,Q.jsx)(`h2`,{children:t(`nav.subagents`)})}),D&&(0,Q.jsx)($,{tone:k?`ok`:`err`,children:D}),ie.showError&&(0,Q.jsx)($,{tone:`err`,children:t(`sub.loadFail`)}),_&&(0,Q.jsxs)($,{tone:`err`,children:[t(`sub.fallbackLabel`),`: `,t(`sub.loadFail`),_!==t(`sub.loadFail`)&&(0,Q.jsxs)(Q.Fragment,{children:[` `,_]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:y,onClick:()=>{b(!0),q()},children:t(`common.retry`)})]}),(0,Q.jsx)(aw,{apiBase:e,roster:a},e),(0,Q.jsx)(_w,{available:oe,fallbackAvailable:h??[],chosen:a,onToggle:le,onMove:ue,fallback:s,fallbackPollMs:l,fallbackBusy:d||!p,onFallbackChange:e=>{C.current+=1,c(e)},onFallbackPollMsChange:e=>{C.current+=1,u(e)},onFallbackSave:()=>{de()},delegation:{apiBase:e,model:F.model,effort:F.effort,efforts:F.efforts,available:F.available,guidanceEnabled:F.guidanceEnabled,syncCodexDefaults:F.syncCodexDefaults,saving:F.saving,onSave:e=>{F.save(e)},ultraMode:z,ultraSaving:B||!R,onUltraModeSave:t=>{t.multiAgentMode==="default"||t.multiAgentMode===`v2`?U({mode:t.multiAgentMode,apiBase:e}):K(t)},ultraLoadFailed:ee,onUltraModeRetry:()=>{re()}}}),H&&H.apiBase===e&&(0,Q.jsx)(pr,{reason:`selection`,mode:H.mode,docsUrl:`https://opencodex.me/guides/subagent-v1-default/`,busy:B,onContinue:()=>{let e=H.mode;U(null),K({multiAgentMode:e,multiAgentSurfaceAdvisoryAcknowledged:!0})},onChooseV1:()=>{U(null),z.multiAgentMode!==`v1`&&K({multiAgentMode:`v1`,multiAgentSurfaceAdvisoryAcknowledged:!0})},onDismiss:()=>U(null)})]})}function Sw(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 Cw(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}return o.updateDeps=e=>{r=e},o}function ww(e,t){if(e===void 0)throw Error(`Unexpected undefined${t?`: ${t}`:``}`);return e}var Tw=(e,t)=>Math.abs(e-t)<1.01,Ew=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}},Dw,Ow=()=>{if(Dw!==void 0)return Dw;if(typeof navigator>`u`)return Dw=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return Dw=!0;let e=navigator.maxTouchPoints;return Dw=navigator.platform===`MacIntel`&&e!==void 0&&e>0},kw=e=>{let{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},Aw=e=>e,jw=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},Mw=(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(kw(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(kw(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(r):r()});return a.observe(n,{box:`border-box`}),()=>{a.unobserve(n)}},Nw={passive:!0},Pw=typeof window>`u`||`onscrollend`in window,Fw=(e,t,n)=>{let r=e.scrollElement;if(!r)return;let i=e.targetWindow;if(!i)return;let a=e.options.useScrollendEvent&&Pw,o=0,s=a?null:Ew(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,Nw),a&&r.addEventListener(`scrollend`,u,Nw),()=>{r.removeEventListener(`scroll`,l),a&&r.removeEventListener(`scrollend`,u)}},Iw=(e,t)=>Fw(e,t,t=>{let{horizontal:n,isRtl:r}=e.options;return n?t.scrollLeft*(r&&-1||1):t.scrollTop}),Lw=(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`]},Rw=(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})},zw=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.shouldMeasureDuringScroll(n)&&this.resizeItem(n,this.options.measureElement(t,e,this));else{this.observer.unobserve(t);for(let[e,n]of this.elementsCache)if(n===t){this.elementsCache.delete(e);break}}};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:Aw,rangeExtractor:jw,onChange:()=>{},measureElement:Lw,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=Cw(()=>(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,Ow()&&this.targetWindow!=null&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};e.addEventListener(`touchstart`,t,Nw),e.addEventListener(`touchend`,n,Nw),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&&(Ow()&&(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=Cw(()=>[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=Cw(()=>[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=Sw(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=Cw(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(e,t,n,r)=>e.length===0||t===0?(this.range=null,null):(this.range=Hw(e,t,n,r,r===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=Cw(()=>{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=Cw(()=>[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 ww(t[Bw(0,t.length-1,r?e=>n[e*2]:e=>ww(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`}={})=>{this.options.count>0?this.scrollToIndex(this.options.count-1,{align:`end`,behavior:e}):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:Ow()&&(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(){this.targetWindow?this.rafId??=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}):this.scrollState=null}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&&Tw(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()}},Bw=(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 Vw(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 Hw(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=Vw(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=Bw(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 Uw=typeof document<`u`?Z.useLayoutEffect:Z.useEffect;function Ww({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n=`transform`,...r}){let i=Z.useReducer(e=>e+1,0)[1],a=Z.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,Zt.flushSync)(i):i()),(o=r.onChange)==null||o.call(r,t,n)}},[l]=Z.useState(()=>{let e=new zw(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),Uw(()=>l._didMount(),[]),Uw(()=>(o(l),l._willUpdate())),Uw(()=>{s(l)}),l}function Gw(e){return Ww({observeElementRect:Mw,observeElementOffset:Iw,scrollToFn:Rw,...e})}var Kw=32;function qw(e){return[...new Uint8Array(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}function Jw(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<=31||n===127)return!0}return!1}var Yw=`codex://threads/`,Xw=512;function Zw(e){let t=e.trim();if(t.length>Xw||t.length<=16||!t.toLowerCase().startsWith(Yw))return t;let n=t.slice(16),r=n.search(/[?#]/),i=(r===-1?n:n.slice(0,r)).replace(/\/+$/,``);return i!==``&&!/[/\s]/.test(i)?i:t}function Qw(e){let t=e.trim(),n=Zw(t);return n===t?[n]:[n,t]}async function $w(e){let t=Qw(e).filter(e=>e!==``&&!Jw(e)&&e.length<=4096);return(await Promise.all(t.map(e=>crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e))))).map(e=>qw(e).slice(0,Kw))}function eT(e,t,n){if(!e)return!1;let r=Qw(t);return r.some(Boolean)?r.includes(e)?!0:n!==void 0&&n.includes(e):!1}var tT={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.`},vi:{label:`Yêu cầu không hợp lệ`,description:`Proxy không thể hiểu yêu cầu. Hãy kiểm tra model, cấu trúc tin nhắn, header và nội dung JSON trước khi thử lại.`},pt:{label:`Requisição inválida`,description:`O proxy não conseguiu entender a requisição. Verifique o modelo, a estrutura das mensagens, os cabeçalhos e o corpo JSON antes de tentar novamente.`}},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.`},vi:{label:`Chưa xác thực`,description:`Thông tin xác thực bị thiếu, đã hết hạn hoặc không hợp lệ. Hãy đăng nhập lại hoặc làm mới thông tin xác thực của tài khoản hay nhà cung cấp mà opencodex sử dụng.`},pt:{label:`Não autorizado`,description:`As credenciais estão ausentes, expiradas ou inválidas. Faça login novamente ou atualize as credenciais da conta/provedor usadas pelo opencodex.`}},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.`},vi:{label:`Yêu cầu thanh toán`,description:`Nhà cung cấp upstream đã từ chối yêu cầu vì không có quyền truy cập thanh toán, tín dụng hoặc gói dịch vụ. Hãy thêm tín dụng, cập nhật thanh toán hoặc đổi nhà cung cấp.`},pt:{label:`Pagamento necessário`,description:`O provedor upstream rejeitou a requisição porque faturamento, créditos ou acesso ao plano não estão disponíveis. Adicione créditos, atualize o faturamento ou troque de provedor.`}},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.`},vi:{label:`Bị cấm`,description:`Tài khoản đã được xác thực nhưng không được phép dùng model hoặc thao tác này. Nguyên nhân thường là giới hạn gói hoặc thuê bao (ví dụ Ollama Cloud Pro), chính sách tổ chức hay quyền model — không nhất thiết do API key sai.`},pt:{label:`Acesso negado`,description:`A conta está autenticada, mas não tem permissão para usar este modelo ou esta operação. Costuma ser limite de plano/assinatura (ex.: Ollama Cloud Pro), política da organização ou permissão do modelo — não necessariamente uma API key inválida.`}},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.`},vi:{label:`Không tìm thấy`,description:`Không tìm thấy endpoint, model hoặc tài nguyên được yêu cầu. Hãy kiểm tra base URL, tên model và đường dẫn yêu cầu.`},pt:{label:`Não encontrado`,description:`A rota, o modelo, a conta ou o recurso upstream solicitado não foi encontrado. Verifique o nome do modelo e a configuração do provedor no opencodex.`}},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.`},vi:{label:`Yêu cầu hết thời gian chờ`,description:`Yêu cầu không hoàn tất trước thời hạn. Hãy thử lại với yêu cầu nhỏ hơn hoặc kiểm tra kết nối mạng.`},pt:{label:`Tempo limite da requisição`,description:`A requisição demorou demais para o proxy ou o provedor upstream concluí-la. Tente novamente com uma requisição menor ou outro provedor.`}},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.`},vi:{label:`Xung đột`,description:`Yêu cầu xung đột với trạng thái hiện tại của tài nguyên hoặc tài khoản. Hãy làm mới trạng thái rồi thử lại.`},pt:{label:`Conflito`,description:`A requisição conflita com o estado atual da conta, da sessão ou do provedor. Atualize a sessão ou tente novamente quando a operação ativa terminar.`}},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.`},vi:{label:`Nội dung quá lớn`,description:`Nội dung yêu cầu vượt quá giới hạn của proxy hoặc nhà cung cấp. Hãy giảm kích thước tin nhắn, tệp hoặc ngữ cảnh rồi thử lại.`},pt:{label:`Requisição grande demais`,description:`O prompt, os anexos ou o conteúdo gerado excedem um limite do proxy ou do upstream. Reduza tokens, tamanho de arquivos ou histórico da conversa.`}},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.`},vi:{label:`Yêu cầu không thể xử lý`,description:`Yêu cầu có cú pháp hợp lệ nhưng chứa giá trị hoặc tổ hợp tùy chọn mà model hay nhà cung cấp không hỗ trợ.`},pt:{label:`Conteúdo inválido`,description:`O provedor aceitou o formato da requisição, mas rejeitou o conteúdo. Verifique as opções do modelo, as definições de ferramentas, os papéis das mensagens e campos não suportados.`}},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.`},vi:{label:`Phụ thuộc thất bại`,description:`Không thể hoàn tất yêu cầu vì một dịch vụ phụ thuộc hoặc thao tác upstream đã thất bại. Hãy kiểm tra lỗi liên quan rồi thử lại.`},pt:{label:`Falha em dependência do provedor`,description:`Uma dependência upstream necessária falhou enquanto o opencodex roteava a requisição. Tente novamente mais tarde ou troque para outro provedor configurado.`}},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.`},vi:{label:`Quá nhiều yêu cầu`,description:`Tài khoản hoặc nhà cung cấp đã đạt giới hạn tốc độ hay hạn ngạch. Hãy chờ thời gian Retry-After, đổi tài khoản hoặc đổi nhà cung cấp.`},pt:{label:`Limite de requisições excedido`,description:`O limite de taxa ou de cota do provedor upstream foi atingido. Aguarde a janela de cota reiniciar ou troque de conta/provedor.`}},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.`},vi:{label:`Máy khách đã đóng yêu cầu`,description:`Máy khách đã ngắt kết nối hoặc hủy yêu cầu trước khi opencodex định tuyến xong. Nếu không chủ ý hủy, hãy thử lại.`},pt:{label:`Requisição encerrada pelo cliente`,description:`O cliente desconectou ou cancelou a requisição antes de o opencodex terminar de rotear. Tente novamente se o cancelamento foi acidental.`}},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.`},vi:{label:`Lỗi proxy`,description:`opencodex gặp lỗi nội bộ khi xử lý yêu cầu. Hãy thử lại một lần, rồi kiểm tra log proxy nếu lỗi lặp lại.`},pt:{label:`Erro do proxy`,description:`O opencodex encontrou um erro interno ao tratar a requisição. Tente novamente uma vez; se repetir, verifique os logs do proxy.`}},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.`},vi:{label:`Phản hồi upstream không hợp lệ`,description:`Nhà cung cấp upstream trả về phản hồi không hợp lệ hoặc thất bại qua proxy. Hãy thử lại hoặc định tuyến yêu cầu sang nhà cung cấp khác.`},pt:{label:`Resposta upstream inválida`,description:`O provedor upstream retornou uma resposta inválida ou com falha através do proxy. Tente novamente ou roteie a requisição para outro provedor.`}},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.`},vi:{label:`Nhà cung cấp không khả dụng`,description:`Proxy hoặc nhà cung cấp upstream tạm thời không khả dụng hay đang quá tải. Hãy chờ một lát rồi thử lại hoặc đổi nhà cung cấp.`},pt:{label:`Provedor indisponível`,description:`O proxy ou o provedor upstream está temporariamente indisponível ou sobrecarregado. Aguarde um instante e tente novamente, ou troque de provedor.`}},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.`},vi:{label:`Upstream hết thời gian chờ`,description:`Nhà cung cấp upstream không phản hồi trước thời hạn của proxy. Hãy thử lại với yêu cầu nhỏ hơn hoặc chọn nhà cung cấp nhanh hơn.`},pt:{label:`Tempo limite do upstream`,description:`O provedor upstream não respondeu antes do tempo limite do proxy. Tente novamente com uma requisição menor ou escolha um provedor mais rápido.`}},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.`},vi:{label:`Nhà cung cấp quá tải`,description:`Nhà cung cấp upstream đang quá tải hoặc bị giới hạn công suất. Hãy chờ rồi thử lại, hoặc đổi sang tài khoản hay nhà cung cấp khác.`},pt:{label:`Provedor sobrecarregado`,description:`O provedor upstream está sobrecarregado ou com capacidade limitada. Aguarde e tente novamente, ou troque para outra conta/provedor.`}}},nT={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.`},vi:{label:`Lỗi yêu cầu`,description:`Proxy hoặc nhà cung cấp upstream đã từ chối yêu cầu. Hãy kiểm tra cấu trúc yêu cầu, thông tin xác thực, tên model và cấu hình nhà cung cấp.`},pt:{label:`Erro na requisição`,description:`O proxy ou o provedor upstream rejeitou a requisição. Verifique a estrutura da requisição, as credenciais, o nome do modelo e a configuração do provedor.`}},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.`},vi:{label:`Lỗi máy chủ hoặc upstream`,description:`opencodex hoặc một nhà cung cấp upstream đã thất bại khi xử lý yêu cầu. Hãy thử lại sau hoặc định tuyến yêu cầu sang nhà cung cấp khác.`},pt:{label:`Erro do servidor ou do upstream`,description:`O opencodex ou um provedor upstream falhou ao processar a requisição. Tente novamente mais tarde ou roteie a requisição para outro provedor.`}}};function rT(e){return e.toLowerCase().startsWith(`fr`)?`fr`:e.toLowerCase().startsWith(`vi`)?`vi`:e.toLowerCase().startsWith(`pt`)?`pt`:e===`de`||e===`ko`||e===`zh`||e===`zh-TW`||e===`ru`||e===`ja`||e===`tr`?e:`en`}function iT(e,t){if(e<400)return null;let n=rT(t);return(tT[Math.trunc(e)]??(e<500?nT.client:nT.server))[n]}var aT=[`provider`,`usage`,`injection`];function oT(e){return e>0?`[${new Date(e).toLocaleTimeString()}] `:``}function sT(e){return new Date(e).toLocaleTimeString()}function cT(e,t){return t===`provider`?!!e?.enabled:t===`usage`?!!e?.usage:!!e?.injection}function lT(e,t){return t===`debug`?e.enabled:t===`usage`?e.usage:t===`injection`?e.injection:e.claude}function uT({entries:e}){let{t}=r();return(0,Q.jsxs)(`div`,{className:`card`,style:{marginBottom:16,padding:`12px 14px`},children:[(0,Q.jsx)(`div`,{className:`font-semibold`,style:{marginBottom:4},children:t(`debug.claudeInbound.title`)}),(0,Q.jsx)(`div`,{className:`muted text-control`,style:{marginBottom:10},children:t(`debug.claudeInbound.sub`)}),e.length===0?(0,Q.jsx)(`div`,{className:`muted text-control`,children:t(`debug.claudeInbound.empty`)}):(0,Q.jsx)(`div`,{style:{overflowX:`auto`},children:(0,Q.jsxs)(`table`,{className:`table text-label`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:t(`debug.claudeInbound.time`)}),(0,Q.jsx)(`th`,{children:t(`debug.claudeInbound.endpoint`)}),(0,Q.jsx)(`th`,{children:t(`debug.claudeInbound.model`)}),(0,Q.jsx)(`th`,{children:`thinking`}),(0,Q.jsx)(`th`,{children:`effort`}),(0,Q.jsx)(`th`,{children:`beta`}),(0,Q.jsx)(`th`,{children:`metadata`}),(0,Q.jsx)(`th`,{children:`system`})]})}),(0,Q.jsx)(`tbody`,{children:e.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`muted mono`,children:sT(e.at)}),(0,Q.jsx)(`td`,{className:`mono`,children:e.endpoint}),(0,Q.jsxs)(`td`,{className:`mono`,title:e.resolvedModel,children:[e.model,e.resolvedModel&&e.resolvedModel!==e.model&&(0,Q.jsxs)(`span`,{className:`muted`,children:[` → `,e.resolvedModel]})]}),(0,Q.jsxs)(`td`,{className:`mono`,children:[e.thinkingType??`-`,e.thinkingBudgetTokens!==void 0&&(0,Q.jsxs)(`span`,{className:`muted`,children:[` (`,e.thinkingBudgetTokens,`)`]})]}),(0,Q.jsx)(`td`,{className:`mono`,children:e.outputConfigEffort??`-`}),(0,Q.jsx)(`td`,{className:`mono`,title:e.anthropicBeta,style:{maxWidth:160,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:e.anthropicBeta??`-`}),(0,Q.jsx)(`td`,{className:`mono`,title:e.metadataKeys?.join(`, `),children:e.hasMetadataUserId?`user_id ${e.userIdTag??``}`:t(`debug.claudeInbound.none`)}),(0,Q.jsx)(`td`,{className:`mono`,children:e.hasSystem?e.systemTag??`yes`:t(`debug.claudeInbound.none`)})]},e.id))})]})})]})}function dT({debug:e,stream:t,streamEnabled:n,entries:i,scrollContainerRef:a,lineVirtualizer:o}){let{t:s}=r();return e?n?i.length===0?(0,Q.jsxs)(`div`,{className:`empty`,children:[(0,Q.jsx)(`div`,{className:`font-semibold`,style:{marginBottom:6},children:s(`debug.noLinesTitle`)}),(0,Q.jsx)(`div`,{className:`muted text-control`,style:{maxWidth:560,marginInline:`auto`},children:s(`debug.noLines.${t}`)})]}):(0,Q.jsx)(`div`,{ref:a,className:`log-detail-json`,style:{maxHeight:`calc(100vh - 280px)`,overflow:`auto`},children:(0,Q.jsx)(`div`,{style:{position:`relative`,height:o.getTotalSize(),width:`100%`},children:o.getVirtualItems().map(e=>(0,Q.jsx)(`div`,{ref:o.measureElement,"data-index":e.index,style:{position:`absolute`,top:0,left:0,width:`100%`,transform:`translateY(${e.start}px)`},children:`${oT(i[e.index].at)}${i[e.index].line}`},e.key))})}):(0,Q.jsxs)(`div`,{className:`empty`,children:[(0,Q.jsx)(`div`,{className:`font-semibold`,style:{marginBottom:6},children:s(`debug.emptyTitle`)}),(0,Q.jsx)(`div`,{className:`muted text-control`,style:{maxWidth:560,marginInline:`auto`},children:s(`debug.empty`)})]}):null}function fT({debug:e,debugBusy:t,stream:n,onSetFlag:i,onReset:a,onStreamChange:o}){let{t:s}=r();return(0,Q.jsxs)(`div`,{className:`card`,style:{marginBottom:16,padding:`12px 14px`},children:[(0,Q.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:12,flexWrap:`wrap`},children:[(0,Q.jsx)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:16},children:[`debug`,`usage`,`injection`,`claude`].map(n=>{let r=lT(e,n);return(0,Q.jsxs)(`div`,{style:{display:`inline-flex`,alignItems:`center`,gap:10,minWidth:220},children:[(0,Q.jsx)(ln,{on:r,disabled:t,label:s(`debug.${n}`),onClick:()=>i(n,!r)}),(0,Q.jsx)(`span`,{className:`text-control`,children:s(`debug.${n}`)})]},n)})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:t,onClick:a,children:s(`debug.reset`)})]}),(e.enabled||e.usage||e.injection)&&(0,Q.jsxs)(`div`,{style:{display:`inline-flex`,gap:6,marginTop:12},children:[e.enabled&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm${n===`provider`?` btn-primary`:` btn-ghost`}`,onClick:()=>o(`provider`),children:s(`debug.streamProvider`)}),e.usage&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm${n===`usage`?` btn-primary`:` btn-ghost`}`,onClick:()=>o(`usage`),children:s(`debug.streamUsage`)}),e.injection&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm${n===`injection`?` btn-primary`:` btn-ghost`}`,onClick:()=>o(`injection`),children:s(`debug.streamInjection`)})]})]})}function pT({embedded:e,refreshing:t,streamEnabled:n,follow:i,onRefresh:a,onFollowChange:o}){let{t:s}=r();return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:e?`row`:`page-head`,style:e?{justifyContent:`flex-end`,marginBottom:4}:void 0,children:[!e&&(0,Q.jsx)(`h2`,{children:s(`debug.title`)}),(0,Q.jsxs)(`div`,{style:{display:`inline-flex`,alignItems:`center`,gap:12},children:[(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:t||!n,onClick:a,children:[(0,Q.jsx)(ae,{}),` `,s(`debug.refresh`)]}),(0,Q.jsxs)(`label`,{className:`muted text-control`,style:{cursor:`pointer`,display:`inline-flex`,alignItems:`center`,gap:6},children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:i,onChange:e=>o(e.target.checked)}),s(`debug.follow`)]})]})]}),(0,Q.jsx)(`p`,{className:`page-sub`,children:s(`debug.subtitle`)})]})}function mT(e){return`debug-settings:${e}`}function hT({apiBase:e,embedded:t,active:n=!0}){let{t:i}=r(),a=`ocx.debug.settings.v1:${e}`,o=io(a),s=mT(e),[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(`provider`),[f,p]=(0,Z.useState)([]),[m,h]=(0,Z.useState)(!0),[g,_]=(0,Z.useState)(!1),v=(0,Z.useRef)(0),y=(0,Z.useRef)(0),b=(0,Z.useRef)(0),x=(0,Z.useRef)(null),S=(0,Z.useRef)(null),C=(0,Z.useRef)(null),w=uo(s,[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 co(a,r),r},{pollMs:2e3,enabled:n,isEmpty:()=>!1,initialData:o??void 0}),T=w.state,E=w.data??o??null,D=Wt(`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=Gw({count:f.length,getScrollElement:()=>S.current,estimateSize:()=>20,overscan:30,getItemKey:e=>f[e].seq}),k=(0,Z.useCallback)(e=>cT(E,e),[E]);(0,Z.useEffect)(()=>{if(!E||k(u))return;let e=aT.find(k);if(!e)return;let t=window.setTimeout(()=>d(e),0);return()=>window.clearTimeout(t)},[E,u,k]);let A=k(u),j=u===`provider`?`${e}/api/debug/logs`:u===`usage`?`${e}/api/debug/usage-logs`:`${e}/api/debug/injection-logs`,N=(0,Z.useCallback)(async(e,t)=>{let n=++b.current;if(!A)n===b.current&&(p([]),v.current=0);else{_(!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;p(t=>(e?a:[...t,...a]).slice(-2e3)),v.current=a[a.length-1].seq}catch{}finally{n===b.current&&_(!1)}}},[j,A]);(0,Z.useEffect)(()=>{if(!n)return;let t=`${e}:${u}:${A}`,r=C.current!==t;if(C.current=t,!r&&f.length>0)return;v.current=0;let i=new AbortController,a=window.setTimeout(()=>{r&&p([]),N(!0,i.signal)},0);return()=>{window.clearTimeout(a),b.current+=1,i.abort()}},[n,e,u,A]);let P=(0,Z.useRef)(!1),F=(0,Z.useEffectEvent)(()=>{if(P.current)return;P.current=!0;let e=M(1e4);N(!1,e.signal).finally(()=>{e.clear(),P.current=!1})});(0,Z.useEffect)(()=>{if(n&&m&&A)return ba(()=>F(),1e3)},[n,m,A]),(0,Z.useEffect)(()=>{m&&f.length>0&&O.scrollToIndex(f.length-1,{align:`end`})},[f,m,O]);let I=async t=>{let n=++y.current;l(!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 i=await r.json();if(n!==y.current)return;co(a,i),Kt(s,i)}catch{}},i=(x.current??Promise.resolve()).then(r,r);x.current=i.then(()=>void 0,()=>void 0);try{await i}finally{n===y.current&&l(!1)}},L=async(e,t)=>{await I({[e]:t})},R=async()=>{await I({reset:!0})};return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(pT,{embedded:t,refreshing:g,streamEnabled:A,follow:m,onRefresh:()=>void N(!0),onFollowChange:h}),!E&&T.showError?(0,Q.jsxs)(`div`,{className:`notice notice-err`,role:`alert`,children:[(0,Q.jsx)(`span`,{children:i(`debug.loadFailed`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>w.refresh(),children:i(`common.retry`)})]}):T.showSkeleton&&!E?(0,Q.jsx)(lb,{label:i(`debug.loading`),rows:3}):E?(0,Q.jsx)(fT,{debug:E,debugBusy:c,stream:u,onSetFlag:(e,t)=>{L(e,t)},onReset:()=>{R()},onStreamChange:d}):null,E&&T.showError&&(0,Q.jsx)($,{tone:`err`,children:i(`debug.loadFailed`)}),E?.claude&&(0,Q.jsx)(uT,{entries:D}),(0,Q.jsx)(dT,{debug:!!E,stream:u,streamEnabled:A,entries:f,scrollContainerRef:S,lineVirtualizer:O})]})}function gT(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 _T=[`all`,`native`,`translated`,`legacy-bridge`,`blocked`,`none`],vT={surface:`all`,model:``,provider:``,status:`all`,timeWindow:`all`,interceptedOnly:!1,conversationId:``};function yT(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()!==``||(e.protocolMode??`all`)!==`all`}function bT(e){return Array.isArray(e.attempts)?e.attempts.filter(e=>typeof e==`object`&&!!e):[]}function xT(e){if(typeof e!=`string`)return;let t=e.trim();return t?t.toLowerCase():void 0}function ST(e,t){if(e===`15m`)return t-9e5;if(e===`1h`)return t-36e5;if(e===`24h`)return t-864e5}function CT(e,t,n=Date.now()){let r=t.model.trim().toLowerCase(),i=t.provider.trim().toLowerCase(),a=t.conversationId.trim(),o=ST(t.timeWindow,n),s=t.protocolMode??`all`;return e.filter(e=>{if(!gT(e,t.surface)||t.interceptedOnly&&typeof e.shadowCallRewrittenFrom!=`string`)return!1;if(s!==`all`){let t=lh(e.protocolTrace)?.mode;if(s===`none`?t!==void 0:t!==s)return!1}if(a&&!eT(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=bT(e);if(r&&![xT(e.model),xT(e.resolvedModel),xT(e.servedModel),...n.map(e=>xT(e.model))].some(e=>e===r)||i&&![xT(e.provider),...n.map(e=>xT(e.provider))].some(e=>e===i)||o!==void 0&&(typeof e.timestamp!=`number`||!Number.isFinite(e.timestamp)||e.timestamp<o))return!1;let c=e.displayMetrics?.tokPerSecond?.kind===`value`&&Number.isFinite(e.displayMetrics.tokPerSecond.value)?e.displayMetrics.tokPerSecond.value:void 0;return!(t.minTokPerSec!==void 0&&(c===void 0||c<t.minTokPerSec)||t.maxTokPerSec!==void 0&&(c===void 0||c>=t.maxTokPerSec))})}function wT(e,t){if(typeof t!=`string`)return;let n=t.trim(),r=xT(n);if(!r)return;let i=e.get(r);(i===void 0||n<i)&&e.set(r,n)}function TT(e){let t=new Map,n=new Map;for(let r of e){for(let e of[r.model,r.resolvedModel,r.servedModel,...bT(r).map(e=>e.model)])wT(t,e);for(let e of[r.provider,...bT(r).map(e=>e.provider)])wT(n,e)}return{models:[...t.values()].sort(),providers:[...n.values()].sort()}}var ET=[`all`,`claude`,`codex`,`grok`];function DT(e,t,n){let r=ET.indexOf(t),i=-1;if(e.key===`ArrowRight`||e.key===`ArrowDown`?i=(r+1)%ET.length:e.key===`ArrowLeft`||e.key===`ArrowUp`?i=(r-1+ET.length)%ET.length:e.key===`Home`?i=0:e.key===`End`&&(i=ET.length-1),i<0)return;e.preventDefault();let a=ET[i];n(a),document.getElementById(`logs-surface-${a}`)?.focus()}function OT({filters:e,options:t,hasActiveFilters:n,filteredCount:r,totalCount:i,t:a,onFilterChange:o,onResetFilters:s}){let c=(0,Z.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,Q.jsxs)(`div`,{className:`logs-filter-container`,children:[(0,Q.jsxs)(`div`,{className:`logs-toolbar`,children:[(0,Q.jsx)(`span`,{className:`muted text-control`,children:a(`logs.filter.surface.label`)}),(0,Q.jsx)(`div`,{className:`segmented logs-segmented`,role:`radiogroup`,"aria-label":a(`logs.filter.surface.label`),children:[`all`,`claude`,`codex`,`grok`].map(t=>(0,Q.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=>DT(n,t,t=>o({...e,surface:t})),children:a(`logs.filter.surface.${t}`)},t))}),(0,Q.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:e.interceptedOnly,onChange:t=>o({...e,interceptedOnly:t.target.checked})}),a(`logs.filter.interceptedHelpersOnly`)]}),(0,Q.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[a(`logs.filter.provider.label`),(0,Q.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,Q.jsx)(`option`,{value:``,children:a(`logs.filter.provider.all`)}),t.providers.map(e=>(0,Q.jsx)(`option`,{value:e,children:Ce(e,a)},e))]})]}),(0,Q.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[a(`logs.filter.model.label`),(0,Q.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,Q.jsx)(`option`,{value:``,children:a(`logs.filter.model.all`)}),t.models.map(e=>(0,Q.jsx)(`option`,{value:e,children:e},e))]})]}),(0,Q.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[a(`logs.filter.time.label`),(0,Q.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,Q.jsx)(`option`,{value:`all`,children:a(`logs.filter.time.all`)}),(0,Q.jsx)(`option`,{value:`15m`,children:a(`logs.filter.time.15m`)}),(0,Q.jsx)(`option`,{value:`1h`,children:a(`logs.filter.time.1h`)}),(0,Q.jsx)(`option`,{value:`24h`,children:a(`logs.filter.time.24h`)})]})]}),(0,Q.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[a(`logs.filter.speed.label`),(0,Q.jsxs)(`select`,{className:`input select-sm`,value:u,"aria-label":a(`logs.filter.speed.label`),onChange:e=>d(e.target.value),children:[(0,Q.jsx)(`option`,{value:`all`,children:a(`logs.filter.speed.all`)}),(0,Q.jsx)(`option`,{value:`slow`,children:a(`logs.filter.speed.slow`)}),(0,Q.jsx)(`option`,{value:`medium`,children:a(`logs.filter.speed.medium`)}),(0,Q.jsx)(`option`,{value:`fast`,children:a(`logs.filter.speed.fast`)})]})]}),(0,Q.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[a(`logs.filter.status.label`),(0,Q.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,Q.jsx)(`option`,{value:`all`,children:a(`logs.filter.status.all`)}),(0,Q.jsx)(`option`,{value:`success`,children:a(`logs.filter.status.success`)}),(0,Q.jsx)(`option`,{value:`errors`,children:a(`logs.filter.status.errors`)})]})]}),(0,Q.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[a(`logs.filter.protocol.label`),(0,Q.jsx)(`select`,{className:`input select-sm`,value:e.protocolMode??`all`,"aria-label":a(`logs.filter.protocol.label`),onChange:t=>o({...e,protocolMode:t.target.value}),children:_T.map(e=>(0,Q.jsx)(`option`,{value:e,children:a(kT(e))},e))})]})]}),(0,Q.jsxs)(`div`,{className:`logs-toolbar logs-toolbar-secondary`,children:[(0,Q.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[a(`logs.filter.conversation.label`),(0,Q.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,Q.jsxs)(`div`,{className:`logs-filter-status`,children:[(0,Q.jsx)(`span`,{className:`muted text-control`,children:a(`logs.filter.showingCount`,{count:r,total:i})}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:l,children:[(0,Q.jsx)(xe,{}),` `,a(`logs.filter.reset`)]})]})]})]})}function kT(e){return e===`all`?`logs.filter.protocol.all`:e===`none`?`logs.filter.protocol.none`:wh[e]}function AT({trace:e,t}){let n=lh(e);if(!n)return null;let r=Ah(n,t),i=t(wh[n.mode]);return(0,Q.jsxs)(`span`,{className:`badge badge-muted protocol-path-badge`,title:t(`logs.protocol.badgeTitle`,{path:r,mode:i}),"data-protocol-mode":n.mode,children:[r,` · `,i]})}function jT({trace:e,t}){let n=lh(e);return(0,Q.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-protocol`,children:[(0,Q.jsx)(`h4`,{id:`log-detail-protocol`,className:`log-detail-section-title`,children:t(`logs.detail.protocol.section`)}),n?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`log-detail-grid`,"data-protocol-mode":n.mode,children:[(0,Q.jsx)(`span`,{className:`muted`,children:t(`logs.detail.protocol.inbound`)}),(0,Q.jsx)(`span`,{children:Oh(n.inbound,t)}),(0,Q.jsx)(`span`,{className:`muted`,children:t(`logs.detail.protocol.mode`)}),(0,Q.jsx)(`span`,{children:t(wh[n.mode])}),n.upstream&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:t(`logs.detail.protocol.upstream`)}),(0,Q.jsx)(`span`,{children:Oh(n.upstream,t)})]}),n.requestPath.length>0&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:t(`logs.detail.protocol.requestPath`)}),(0,Q.jsx)(`span`,{children:kh(n.requestPath,t)}),(0,Q.jsx)(`span`,{className:`muted`,children:t(`logs.detail.protocol.responsePath`)}),(0,Q.jsx)(`span`,{children:kh(n.responsePath,t)})]}),(0,Q.jsx)(`span`,{className:`muted`,children:t(`logs.detail.protocol.reasons`)}),(0,Q.jsx)(`span`,{className:`mono log-detail-break`,children:n.reasonCodes.join(`, `)||`–`}),n.featureEffects&&n.featureEffects.length>0&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:t(`logs.detail.protocol.features`)}),(0,Q.jsx)(`span`,{children:n.featureEffects.map(e=>(0,Q.jsxs)(`span`,{style:{display:`block`},children:[(0,Q.jsx)(`code`,{children:e.feature}),`: `,t(Th[e.disposition])]},e.feature))})]}),n.attempts&&n.attempts.length>0&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:t(`logs.detail.protocol.attempts`)}),(0,Q.jsx)(`span`,{children:n.attempts.map(e=>(0,Q.jsxs)(`span`,{style:{display:`block`},children:[t(`logs.detail.protocol.attempt`,{ordinal:e.ordinal}),`:`,` `,kh(e.requestPath,t),` · `,t(wh[e.mode])]},e.ordinal))})]})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm protocol-deep-link`,onClick:()=>m_({inbound:n.inbound,upstream:o_(n.upstream)}),children:t(`protocolLinks.labEvidence`)})]}):(0,Q.jsx)(`p`,{className:`log-detail-notes-line muted`,children:t(`logs.detail.protocol.none`)})]})}function MT(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?{generatedAt:e,receivedAt:t}:void 0}function NT(e,t,n){return e?e.generatedAt+Math.max(0,t-e.receivedAt):n}function PT(){return Gg(window.location.hash)===`logs/debug`?`debug`:`logs`}function FT(e){window.location.hash=e===`debug`?`logs/debug`:`logs`}function IT(e){e.key===`ArrowLeft`||e.key===`Home`?(e.preventDefault(),FT(`logs`),document.getElementById(`logs-tab-logs`)?.focus()):(e.key===`ArrowRight`||e.key===`End`)&&(e.preventDefault(),FT(`debug`),document.getElementById(`logs-tab-debug`)?.focus())}function LT(e){return e.servedModel!==void 0&&e.servedModel!==(e.wireModel??e.model)}function RT(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 zT(e,t){return[LT(e)?t(`logs.modelRerouteTitle`):void 0,`${t(`logs.modelTooltip.model`)}=${e.model}`,e.resolvedModel?`${t(`logs.modelTooltip.resolvedModel`)}=${e.resolvedModel}`:void 0,e.servedModel?`${t(`logs.modelTooltip.servedModel`)}=${e.servedModel}`:void 0,e.wireModel?`${t(`logs.modelTooltip.wireModel`)}=${e.wireModel}`: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}${RT(e.tierOutcome,t)}`:void 0,e.modelSupportsServiceTier===void 0?void 0:`${t(`logs.modelTooltip.supportsTier`)}=${e.modelSupportsServiceTier}`].filter(Boolean).join(` · `)}function BT(e){return e.requestedSpeedLabel||void 0}function VT(e){switch(e.timingBasis){case`generation-window`:return{short:`logs.decodeBasis.generation`,detail:`logs.detail.decodeGeneration`,hint:`logs.detail.decodeBasisHint.generation`};case`legacy-post-visible-output`:return{short:`logs.decodeBasis.legacy`,detail:`logs.detail.decodeLegacy`,hint:`logs.detail.decodeBasisHint.legacy`};default:return{short:`logs.decodeBasis.unknown`,detail:`logs.detail.decodeUnknown`,hint:`logs.detail.decodeBasisHint.unknown`}}}var HT=new Intl.NumberFormat(`en-US`,{style:`currency`,currency:`USD`,currencyDisplay:`narrowSymbol`,minimumFractionDigits:4,maximumFractionDigits:4});function UT(e,t,n,r=!1){if(!Number.isFinite(e)||e<0)return t(`logs.cost.unavailable`);let i=HT.format(e);return t(r?`logs.cost.lowerBound`:`logs.cost.approximate`,{amount:i})}function WT(e,t,n){return!e||e.kind===`unavailable`?t(`logs.cost.unavailable`):UT(e.estimate.cost.total,t,n,e.estimate.priorityLowerBound)}function GT(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 KT(e){return e===`cursor`||e.startsWith(`cursor-`)}function qT(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 JT(e,t){if(!e.usage)return;let n=qT(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(KT(e.provider)?`logs.tokens.noCacheCursorNote`:`logs.tokens.noCacheNote`)),r.join(` · `)}function YT(e){return e===void 0||typeof e==`string`}function XT(e){if(e===void 0)return!0;if(!e||typeof e!=`object`||!YT(e.routeKind)||e.profile!==void 0&&(!e.profile||typeof e.profile!=`object`||!YT(e.profile.id)||!YT(e.profile.revision))||e.selected!==void 0&&(!e.selected||typeof e.selected!=`object`||!YT(e.selected.provider)||!YT(e.selected.model)||!YT(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`||!YT(t.provider)||!YT(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`||!YT(e.code))return!1}}return!0}function ZT(e){if(e.routeDecision===void 0||XT(e.routeDecision))return e;let t={...e};return delete t.routeDecision,t}function QT(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 $T(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}var eE=Object.freeze([`completed`,`failed`,`incomplete`,`aborted`]);Object.freeze(eE.filter(e=>e!==`aborted`)),Object.freeze([`terminal`,`client_cancel`,`non_stream`,`body_stall`,`body_overflow`]);function tE(e){return e.closeReason===`client_cancel`||e.status===499?`aborted`:e.terminalStatus===`failed`?`failed`:e.terminalStatus===`incomplete`||e.closeReason===`body_stall`||e.closeReason===`body_overflow`?`incomplete`:e.terminalStatus===`completed`||e.terminalStatus===void 0&&(e.status===101||e.status>=200&&e.status<400)?`completed`:`failed`}function nE(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function rE(e){return nE(e?.sends)}function iE(e){return nE(e?.unresolved)}function aE(e){return`ocx.logs.list.v1:${e}`}var oE=[];function sE(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`||!XT(t.routeDecision))return null;return e}function cE(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 lE(e){let t=cE(e),n=e.usage?.contextTotalTokens;return typeof n==`number`?Math.max(t??0,n)||void 0:t}function uE(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 dE(e){if(e.reasoningWireField&&e.reasoningWireValue!==void 0)return`${e.reasoningWireField}=${e.reasoningWireValue}`}function fE(e){return LT(e)?(0,Q.jsxs)(Q.Fragment,{children:[zv(e.wireModel??e.model),` → `,zv(e.servedModel)]}):zv(e.servedModel??e.resolvedModel??e.model)}function pE(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 mE=2e3,hE=3e4,gE=4,_E=3,vE={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`},yE={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`},bE={"transient-5xx":`logs.detail.attempt.recovery.transient5xx`,"connection-reset":`logs.detail.attempt.recovery.connectionReset`,"oauth-401":`logs.detail.attempt.recovery.oauth401`,"oauth-account-403":`logs.detail.attempt.recovery.oauthAccount403`,"key-401":`logs.detail.attempt.recovery.key401`,"key-429":`logs.detail.attempt.recovery.key429`,"rate-limit-429":`logs.detail.attempt.recovery.rateLimit429`,"anthropic-oauth-429":`logs.detail.attempt.recovery.anthropicOauth429`,"oauth-account-429":`logs.detail.attempt.recovery.oauthAccount429`,"oauth-account-402":`logs.detail.attempt.recovery.oauthAccount402`,"image-413":`logs.detail.attempt.recovery.image413`,"empty-completion":`logs.detail.attempt.recovery.emptyCompletion`,"console-go-upload-retry":`logs.detail.attempt.recovery.consoleGoUpload`,"opaque-blob-rejection":`logs.detail.attempt.recovery.opaqueBlobRejection`,"reasoning-effort-downgrade":`logs.detail.attempt.recovery.reasoningEffortDowngrade`,"anthropic-fast-downgrade":`logs.detail.attempt.recovery.anthropicFastDowngrade`};function xE(e){return vE[e]}function SE(e){return yE[e]}function CE(e){return bE[e]??`logs.detail.attempt.recovery.unknown`}function wE(e){return e===`verified`?`logs.detail.verification.verified`:`logs.detail.verification.derived`}var TE={completed:`logs.detail.outcome.completed`,failed:`logs.detail.outcome.failed`,incomplete:`logs.detail.outcome.incomplete`,aborted:`logs.detail.outcome.aborted`},EE={"transport-unsent":`logs.detail.cause.transportUnsent`,"transport-ambiguous":`logs.detail.cause.transportAmbiguous`,"upstream-declined":`logs.detail.cause.upstreamDeclined`,"rate-limit":`logs.detail.cause.rateLimit`,"quota-exhausted":`logs.detail.cause.quotaExhausted`,"credential-rejected":`logs.detail.cause.credentialRejected`,"policy-refusal":`logs.detail.cause.policyRefusal`,"parameter-rejected":`logs.detail.cause.parameterRejected`,"ciphertext-refusal":`logs.detail.cause.ciphertextRefusal`,"payload-too-large":`logs.detail.cause.payloadTooLarge`,"payload-rejected":`logs.detail.cause.payloadRejected`,"upstream-fault":`logs.detail.cause.upstreamFault`,"empty-output":`logs.detail.cause.emptyOutput`,"client-cancelled":`logs.detail.cause.clientCancelled`,"local-refusal":`logs.detail.cause.localRefusal`},DE={"pre-header":`logs.detail.stage.preHeader`,"headers-only":`logs.detail.stage.headersOnly`,"protocol-prelude":`logs.detail.stage.protocolPrelude`,"semantic-output":`logs.detail.stage.semanticOutput`,"side-effect":`logs.detail.stage.sideEffect`,terminal:`logs.detail.stage.terminal`},OE={permitted:`logs.detail.resend.permitted`,"permitted-after-repair":`logs.detail.resend.permittedAfterRepair`,"refused-ambiguous":`logs.detail.resend.refusedAmbiguous`,"refused-committed":`logs.detail.resend.refusedCommitted`,"refused-futile":`logs.detail.resend.refusedFutile`};function kE(e){return TE[tE(e)]}function AE(e,t){let n=e.failureCause===void 0?void 0:EE[e.failureCause],r=e.failureStage===void 0?void 0:DE[e.failureStage],i=e.resendPermission===void 0?void 0:OE[e.resendPermission];return{...e.failureCause?{cause:n?t(n):e.failureCause}:{},...e.failureStage?{stage:r?t(r):e.failureStage}:{},...e.resendPermission?{resend:i?t(i):e.resendPermission}:{}}}function jE(e){return e>=200&&e<300?`var(--green)`:e>=400?`var(--red)`:`var(--amber)`}function ME(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 NE(e,t,n){let{date:r,time:i}=ME(e,t,n);return`${r} ${i}`}function PE(e){let t=0;for(let n of e){let e=cE(n);e!==void 0&&(t+=e)}return{requests:e.length,totalTokens:t,...GT(e)}}function FE({apiBase:e}){let{t,locale:n}=r(),i=aE(e),a=sE(io(i)),[o,s]=(0,Z.useState)(!0),[c,l]=(0,Z.useState)({error:null,count:0}),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)(vT),[m,h]=(0,Z.useState)(()=>Date.now()),g=(0,Z.useRef)({key:i,active:!1,request:0}),_=(0,Z.useRef)({key:i,cursor:null,rows:[]});(0,Z.useLayoutEffect)(()=>{let e={key:i,active:!0,request:0};return g.current=e,_.current={key:i,cursor:null,rows:[]},h(Date.now()),()=>{e.active=!1}},[i]);let v=(0,Z.useCallback)(()=>{let e=g.current;return NT(e.key===i?e.anchor:void 0,performance.now(),Date.now())},[i]),y=(0,Z.useRef)(null),b=(0,Z.useRef)({key:i,failures:0,nextAttemptAt:0,error:null}),x=j.find(e=>e.code===n)?.htmlLang,[S,C]=(0,Z.useState)();(0,Z.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,Z.useState)(PT),[E,D]=(0,Z.useState)(()=>PT()===`debug`);(0,Z.useEffect)(()=>{let e=()=>T(PT());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]),(0,Z.useEffect)(()=>{w===`debug`&&D(!0)},[w]);let O=FT,k=(0,Z.useCallback)(async t=>{let n=g.current;if(t.aborted||!n.active||n.key!==i)throw t.reason??new DOMException(`Obsolete log request`,`AbortError`);let r=++n.request,a=()=>!t.aborted&&n.active&&g.current===n&&n.request===r,o=b.current;if(o.key!==i&&(o={key:i,failures:0,nextAttemptAt:0,error:null},b.current=o),o.failures>0&&Date.now()<o.nextAttemptAt)throw o.error;let s=_.current,c=s.key===i?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 r=await e.json(),o=performance.now(),u=QT(r),d=u.rows.map(ZT),f=c&&u.cursor&&!u.reset?$T(s.rows,d):d;if(!a())throw t.reason??new DOMException(`Obsolete log request`,`AbortError`);_.current={key:i,cursor:u.cursor,rows:f};let m=TT(f);p(e=>{let t=e.model.trim().toLowerCase(),n=e.provider.trim().toLowerCase(),r=t?m.models.find(e=>e.trim().toLowerCase()===t)??``:``,i=n?m.providers.find(e=>e.trim().toLowerCase()===n)??``:``;return e.model===r&&e.provider===i?e:{...e,model:r,provider:i}});let g=MT(u.generatedAt,o);return g&&(n.anchor=g),h(NT(n.anchor,o,Date.now())),b.current={key:i,failures:0,nextAttemptAt:0,error:null},co(i,f),f}catch(e){if(!a())throw e;let t=e??Error(`log request failed`),n=o.failures+1,r=mE*2**Math.min(n,gE);throw b.current={key:i,failures:n,nextAttemptAt:Date.now()+r,error:t},t}},[e,i]),A=uo(i,[e],k,{isEmpty:e=>e.length===0,enabled:w===`logs`,pollMs:o?mE:void 0,initialData:a??void 0}),M=A.state,N=M.data??a??oE,P=A.refresh,F=(0,Z.useCallback)(()=>{b.current={key:i,failures:0,nextAttemptAt:0,error:null},_.current={key:i,cursor:null,rows:[]},P({forceLoading:!0})},[P,i]),I=!A.refreshing&&M.showError;!A.refreshing&&!M.showError&&M.data!==void 0&&c.count!==0?l({error:null,count:0}):I&&c.error!==M.error&&l(e=>({error:M.error,count:e.count+1}));let L=c.count>=_E||!o&&I,R=u?iT(u.status,n):null,z=f.conversationId.trim();(0,Z.useEffect)(()=>{if(f.timeWindow===`all`||w!==`logs`)return;h(v());let e=window.setInterval(()=>h(v()),hE);return()=>window.clearInterval(e)},[f.timeWindow,w,v]),(0,Z.useEffect)(()=>{let e=!1;if(!z)p(e=>e.conversationQueryHash===void 0?e:{...e,conversationQueryHash:void 0});else return $w(z).then(t=>{e||p(e=>e.conversationQueryHash?.join(` `)===t.join(` `)?e:{...e,conversationQueryHash:t})}),()=>{e=!0}},[z]);let B=(0,Z.useMemo)(()=>TT(N),[N]),V=yT(f),H=(0,Z.useMemo)(()=>CT(N,f,m),[N,f,m]),U=z?PE(H):null,ee=Gw({count:H.length,getScrollElement:()=>y.current,estimateSize:()=>92,overscan:15,getItemKey:e=>{let t=H[H.length-1-e];return t.requestId??`${t.timestamp}:${t.model}:${t.provider}`}}),W=ee.getVirtualItems(),te=W.length>0?W[0].start:0,G=W.length>0?ee.getTotalSize()-W[W.length-1].end:0;return(0,Q.jsxs)(`div`,{className:`logs-page`,children:[(0,Q.jsxs)(`div`,{className:`page-head`,children:[(0,Q.jsx)(`h2`,{children:t(`nav.logs`)}),w===`logs`&&(0,Q.jsxs)(`label`,{className:`muted text-control logs-auto-refresh`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:o,onChange:e=>s(e.target.checked)}),t(`logs.autoRefresh`)]})]}),(0,Q.jsxs)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":t(`nav.logs`),children:[(0,Q.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:IT,children:t(`logs.tabLogs`)}),(0,Q.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:IT,children:t(`logs.tabDebug`)})]}),E&&(0,Q.jsx)(`div`,{role:`tabpanel`,id:`logs-panel-debug`,"aria-labelledby":`logs-tab-debug`,hidden:w!==`debug`,children:(0,Q.jsx)(hT,{apiBase:e,embedded:!0,active:w===`debug`})}),(0,Q.jsxs)(`div`,{role:`tabpanel`,id:`logs-panel-logs`,"aria-labelledby":`logs-tab-logs`,hidden:w!==`logs`,children:[(0,Q.jsx)(OT,{filters:f,options:B,hasActiveFilters:V,filteredCount:H.length,totalCount:N.length,t,onFilterChange:p,onResetFilters:()=>p(vT)}),U&&(0,Q.jsx)(`div`,{className:`logs-conversation-totals`,children:(0,Q.jsxs)($,{tone:`ok`,children:[t(`logs.conversation.totals`,{requests:U.requests,tokens:q(U.totalTokens,x??n),cost:UT(U.estimatedCostUsd,t,x,U.priorityLowerBound)}),` `,(0,Q.jsxs)(`span`,{className:`muted`,children:[t(`logs.conversation.scope`),U.unpricedRequests+U.unmeteredRequests>0?` ${t(`logs.conversation.excluded`,{unpriced:U.unpricedRequests,unmetered:U.unmeteredRequests})}`:``]})]})}),M.kind===`failed-cold`&&(0,Q.jsxs)($,{tone:`err`,children:[M.error instanceof Error?`${t(`logs.loadError`)} ${M.error.message}`:t(`logs.loadError`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:F,disabled:M.refreshing,children:t(`common.retry`)})]}),L&&N.length>0&&(0,Q.jsxs)($,{tone:`err`,children:[t(`logs.loadError`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:F,disabled:A.refreshing,children:t(`common.retry`)})]}),M.kind===`failed-cold`?null:M.showSkeleton&&N.length===0?(0,Q.jsx)(lb,{label:t(`common.loading`),rows:6}):H.length===0?(0,Q.jsx)(fn,{title:N.length>0&&V?t(`logs.noMatchingRequests`):t(`logs.noRequests`)}):(0,Q.jsx)(Q.Fragment,{children:(0,Q.jsx)(`div`,{ref:y,className:`tbl-wrap logs-table-wrap`,children:(0,Q.jsxs)(`table`,{className:`tbl logs-table`,children:[(0,Q.jsxs)(`colgroup`,{children:[(0,Q.jsx)(`col`,{className:`logs-col-time`}),(0,Q.jsx)(`col`,{className:`logs-col-tokens`}),(0,Q.jsx)(`col`,{className:`logs-col-rate`}),(0,Q.jsx)(`col`,{className:`logs-col-cost`}),(0,Q.jsx)(`col`,{className:`logs-col-model`}),(0,Q.jsx)(`col`,{className:`logs-col-effort`}),(0,Q.jsx)(`col`,{className:`logs-col-provider`}),(0,Q.jsx)(`col`,{className:`logs-col-status`}),(0,Q.jsx)(`col`,{className:`logs-col-request`}),(0,Q.jsx)(`col`,{className:`logs-col-duration`})]}),(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:t(`logs.col.time`)}),(0,Q.jsx)(`th`,{className:`num log-col-tokens`,children:t(`logs.col.tokens`)}),(0,Q.jsx)(`th`,{className:`num log-col-rate`,title:t(`logs.metric.tokPerSecTitle`),children:t(`logs.col.tokPerSec`)}),(0,Q.jsx)(`th`,{className:`num log-col-cost`,title:t(`logs.metric.estimatedCostTitle`),children:t(`logs.col.estimatedCost`)}),(0,Q.jsx)(`th`,{className:`log-col-model`,children:t(`logs.col.model`)}),(0,Q.jsx)(`th`,{children:t(`logs.col.effort`)}),(0,Q.jsx)(`th`,{children:t(`logs.col.provider`)}),(0,Q.jsx)(`th`,{children:t(`logs.col.status`)}),(0,Q.jsx)(`th`,{children:t(`logs.col.request`)}),(0,Q.jsx)(`th`,{className:`num log-col-duration`,children:t(`logs.col.duration`)})]})}),(0,Q.jsxs)(`tbody`,{children:[te>0&&(0,Q.jsx)(`tr`,{children:(0,Q.jsx)(`td`,{colSpan:10,className:`logs-virtual-spacer`,style:{height:te}})}),W.map(e=>{let r=H[H.length-1-e.index],i=dE(r),a=r.displayMetrics?.decodeTokPerSecond,o=VT(a?.kind===`value`?a:{}),s=ME(r.timestamp,x,S);return(0,Q.jsxs)(`tr`,{"data-index":e.index,ref:ee.measureElement,children:[(0,Q.jsx)(`td`,{className:`muted mono log-col-time`,children:(0,Q.jsxs)(`span`,{className:`logs-stack-start`,children:[(0,Q.jsx)(`span`,{children:s.date}),(0,Q.jsx)(`span`,{children:s.time})]})}),(0,Q.jsx)(`td`,{className:`num mono log-col-tokens`,title:JT(r,t),children:(()=>{let e=lE(r),{read:i,write:a}=qT(r);return e===void 0?(0,Q.jsx)(`span`,{className:`muted`,children:t(`logs.tokens.${r.usageStatus??`unreported`}`)}):(0,Q.jsxs)(`span`,{className:`logs-stack-end`,children:[(0,Q.jsxs)(`span`,{children:[r.usageStatus===`estimated`?`~`:``,q(e,n)]}),i!==void 0&&i>0&&(0,Q.jsxs)(`span`,{className:`muted text-caption leading-tight`,children:[`c `,q(i,n)]}),a!==void 0&&a>0&&(0,Q.jsxs)(`span`,{className:`muted text-caption leading-tight`,children:[`w `,q(a,n)]}),r.usageStatus===`estimated`&&i===void 0&&a===void 0&&(0,Q.jsx)(`span`,{className:`muted text-caption leading-tight`,children:t(KT(r.provider)?`logs.tokens.noCacheCursor`:`logs.tokens.noCache`)})]})})()}),(0,Q.jsxs)(`td`,{className:`num mono log-col-rate`,children:[pE(r.displayMetrics?.tokPerSecond,x),a?.kind===`value`&&(0,Q.jsxs)(`span`,{className:`logs-stack-end logs-decode-rate muted`,title:t(o.detail),children:[(0,Q.jsx)(`span`,{children:pE(a,x)}),(0,Q.jsx)(`span`,{className:`text-caption`,children:t(o.short)})]})]}),(0,Q.jsx)(`td`,{className:`num mono log-col-cost`,children:WT(r.displayMetrics?.cost,t,x)}),(0,Q.jsx)(`td`,{className:`mono log-col-model`,title:zT(r,t),children:(0,Q.jsxs)(`span`,{className:`logs-model-cell`,children:[(0,Q.jsx)(`span`,{children:fE(r)}),r.shadowCallRewrittenFrom&&(0,Q.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,Q.jsx)(`span`,{className:`badge badge-accent`,children:t(`logs.badge.claude`)}),r.surface===`grok`&&(0,Q.jsx)(`span`,{className:`badge badge-accent`,children:t(`logs.badge.grok`)}),BT(r)&&(0,Q.jsx)(`span`,{className:`badge badge-amber`,children:BT(r)}),(0,Q.jsx)(AT,{trace:r.protocolTrace,t})]})}),(0,Q.jsx)(`td`,{className:`mono log-reasoning-cell`,title:i,children:uE(r)}),(0,Q.jsx)(`td`,{className:`muted`,children:Ce(r.provider,t)}),(0,Q.jsx)(`td`,{children:(0,Q.jsxs)(`span`,{className:`log-status-cell`,children:[(0,Q.jsx)(`span`,{className:`mono font-semibold`,style:{color:jE(r.status)},children:r.status}),(0,Q.jsx)(`button`,{type:`button`,className:`log-detail-btn`,onClick:()=>d(r),"aria-label":`${t(`logs.details`)}: ${r.requestId??r.status}`,children:t(`logs.details`)})]})}),(0,Q.jsx)(`td`,{className:`muted mono`,children:(0,Q.jsx)(`span`,{className:`log-reqid`,title:r.requestId,children:r.requestId??`-`})}),(0,Q.jsxs)(`td`,{className:`num log-col-duration`,children:[r.durationMs,`ms`]})]},e.key)}),G>0&&(0,Q.jsx)(`tr`,{children:(0,Q.jsx)(`td`,{colSpan:10,className:`logs-virtual-spacer`,style:{height:G}})})]})]})})}),u&&(0,Q.jsx)(LE,{detail:u,detailInfo:R,localeCode:n,localeTag:x,serverTimeZone:S,t,onClose:()=>d(null),onFilterConversation:e=>{p(t=>({...t,conversationId:e})),d(null)}})]})]})}function IE(e){let t=(0,Z.useRef)(null);return(0,Z.useEffect)(()=>{let n=t.current;n&&(e&&!n.open?n.showModal():!e&&n.open&&n.close())},[e]),t}function LE({detail:e,detailInfo:t,localeCode:n,localeTag:r,serverTimeZone:i,t:a,onClose:o,onFilterConversation:s}){let c=IE(!0),[l,u]=(0,Z.useState)(!1),d=qT(e),f=e.displayMetrics?.cost,p=e.displayMetrics?.decodeTokPerSecond,m=VT(p?.kind===`value`?p:{}),h=dE(e),g=AE(e,a),_=async()=>{if(e.requestId)try{await navigator.clipboard.writeText(e.requestId),u(!0),window.setTimeout(()=>u(!1),1200)}catch{}};return(0,Q.jsxs)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":`log-detail-title`,onCancel:e=>{e.preventDefault(),o()},children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":a(`common.close`),tabIndex:-1,onClick:o}),(0,Q.jsxs)(`div`,{className:`modal-card log-detail-card`,onClick:e=>e.stopPropagation(),role:`document`,children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsxs)(`h3`,{id:`log-detail-title`,children:[(0,Q.jsx)(`span`,{className:`mono`,style:{color:jE(e.status)},children:e.status}),t&&(0,Q.jsx)(`span`,{className:`logs-detail-info`,children:t.label})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:o,"aria-label":a(`common.cancel`),children:(0,Q.jsx)(xe,{})})]}),t&&(0,Q.jsx)(`p`,{className:`modal-desc`,children:t.description}),(0,Q.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-basic`,children:[(0,Q.jsx)(`h4`,{id:`log-detail-basic`,className:`log-detail-section-title`,children:a(`logs.detail.section.basic`)}),(0,Q.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.col.time`)}),(0,Q.jsx)(`span`,{className:`mono`,children:NE(e.timestamp,r,i)}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.outcome.label`)}),(0,Q.jsx)(`span`,{children:a(kE(e))}),g.cause&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.cause.label`)}),(0,Q.jsxs)(`span`,{children:[g.cause,g.stage&&` (${a(`logs.detail.stage.label`)}: ${g.stage})`]})]}),g.resend&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.resend.label`)}),(0,Q.jsx)(`span`,{children:g.resend})]}),e.spend&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.sends.label`)}),(0,Q.jsxs)(`span`,{className:`mono`,children:[rE(e.spend),iE(e.spend)>0&&` (${a(`logs.detail.sends.unresolved`)}: ${iE(e.spend)})`]})]}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.col.request`)}),(0,Q.jsxs)(`span`,{className:`log-detail-request-row`,children:[(0,Q.jsx)(`span`,{className:`mono log-detail-break`,children:e.requestId??`—`}),e.requestId&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void _(),children:a(l?`logs.detail.copied`:`logs.detail.copyRequestId`)})]}),e.conversationId&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.conversation`)}),(0,Q.jsxs)(`span`,{className:`log-detail-request-row`,children:[(0,Q.jsx)(`span`,{className:`mono log-detail-break`,children:e.conversationId}),s&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>s(e.conversationId),children:a(`logs.filter.conversation.apply`)})]})]}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.col.model`)}),(0,Q.jsx)(`span`,{className:`mono`,children:fE(e)}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.col.provider`)}),(0,Q.jsx)(`span`,{children:Ce(e.provider,a)}),(e.requestedEffort||e.effectiveEffort)&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.col.effort`)}),(0,Q.jsxs)(`span`,{className:`mono`,children:[uE(e),h?` (${h})`:``]})]}),e.errorCode&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.col.error`)}),(0,Q.jsx)(`span`,{className:`mono`,children:e.errorCode})]}),e.upstreamError&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.col.upstreamReason`)}),(0,Q.jsx)(`span`,{className:`mono log-detail-break`,children:e.upstreamError})]})]})]}),(0,Q.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-route`,children:[(0,Q.jsx)(`h4`,{id:`log-detail-route`,className:`log-detail-section-title`,children:a(`logs.detail.route.section`)}),e.routeDecision?(0,Q.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.route.kind`)}),(0,Q.jsx)(`span`,{className:`mono`,children:e.routeDecision.routeKind??`–`}),e.routeDecision.profile?.id&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.route.profile`)}),(0,Q.jsxs)(`span`,{className:`mono`,children:[e.routeDecision.profile.id,` (`,e.routeDecision.profile.revision,`)`]})]}),e.routeDecision.selected?.provider&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.route.selected`)}),(0,Q.jsxs)(`span`,{className:`mono`,children:[e.routeDecision.selected.provider,`/`,e.routeDecision.selected.model,e.routeDecision.selected.reason?` — ${e.routeDecision.selected.reason}`:``]})]}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.route.candidates`)}),(0,Q.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,Q.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`logs.detail.route.unknown`)})]}),(0,Q.jsx)(jT,{trace:e.protocolTrace,t:a}),(0,Q.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-performance`,children:[(0,Q.jsx)(`h4`,{id:`log-detail-performance`,className:`log-detail-section-title`,children:a(`logs.detail.section.performance`)}),(0,Q.jsxs)(`div`,{className:`log-detail-grid log-detail-performance-grid`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.col.duration`)}),(0,Q.jsxs)(`span`,{className:`mono`,children:[e.durationMs,`ms`]}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.endToEndTokPerSec`)}),(0,Q.jsx)(`span`,{className:`mono`,children:pE(e.displayMetrics?.tokPerSecond,r)}),p?.kind===`value`&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,title:a(m.hint),children:a(m.detail)}),(0,Q.jsx)(`span`,{className:`mono`,children:pE(p,r)}),(0,Q.jsx)(`span`,{className:`logs-decode-basis-hint muted text-caption`,children:a(m.hint)})]}),e.firstOutputMs!==void 0&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.ttft`)}),(0,Q.jsxs)(`span`,{className:`mono`,children:[e.firstOutputMs,`ms`]})]})]}),e.displayMetrics?.tokPerSecond.kind===`unavailable`&&(0,Q.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(xE(e.displayMetrics.tokPerSecond.reason))}),e.displayMetrics?.decodeTokPerSecond?.kind===`unavailable`&&(0,Q.jsxs)(`p`,{className:`log-detail-notes-line muted`,children:[a(`logs.detail.decodeTokPerSec`),`: `,a(xE(e.displayMetrics.decodeTokPerSecond.reason))]})]}),(0,Q.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-cost`,children:[(0,Q.jsx)(`h4`,{id:`log-detail-cost`,className:`log-detail-section-title`,children:a(`logs.detail.section.cost`)}),(0,Q.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`usage.cost.disclaimer`)}),f?.kind===`value`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.costTotal`)}),(0,Q.jsx)(`span`,{className:`mono`,children:UT(f.estimate.cost.total,a,r,f.estimate.priorityLowerBound)}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.input`)}),(0,Q.jsx)(`span`,{className:`mono`,children:UT(f.estimate.cost.input,a,r,f.estimate.priorityLowerBound)}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheRead`)}),(0,Q.jsx)(`span`,{className:`mono`,children:UT(f.estimate.cost.cacheRead,a,r,f.estimate.priorityLowerBound)}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheWrite`)}),(0,Q.jsx)(`span`,{className:`mono`,children:UT(f.estimate.cost.cacheWrite,a,r,f.estimate.priorityLowerBound)}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.output`)}),(0,Q.jsx)(`span`,{className:`mono`,children:UT(f.estimate.cost.output,a,r,f.estimate.priorityLowerBound)}),f.estimate.price&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.matchedKey`)}),(0,Q.jsxs)(`span`,{className:`mono log-detail-break`,children:[f.estimate.price.jawcodeProvider??f.estimate.price.provider,`/`,f.estimate.price.modelId]}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.priceSource`)}),(0,Q.jsxs)(`span`,{children:[a(`logs.detail.source.${f.estimate.price.source}`),` · `,a(wE(f.estimate.price.status))]})]})]}),f.estimateReasons.length>0&&(0,Q.jsx)(`ul`,{className:`log-detail-notes`,children:f.estimateReasons.map(e=>(0,Q.jsx)(`li`,{children:a(SE(e))},e))})]}):(0,Q.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.costTotal`)}),(0,Q.jsx)(`span`,{className:`mono`,children:a(`logs.cost.unavailable`)}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.unavailableReason`)}),(0,Q.jsx)(`span`,{children:f?.kind===`unavailable`?a(xE(f.reason)):a(`logs.detail.reason.usage_missing`)})]})]}),e.attempts?.length?(0,Q.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-attempts`,children:[(0,Q.jsx)(`h4`,{id:`log-detail-attempts`,className:`log-detail-section-title`,children:a(`logs.detail.section.attempts`)}),(0,Q.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`logs.detail.attempt.e2eNote`)}),(0,Q.jsx)(`div`,{className:`log-detail-attempts-wrap`,children:(0,Q.jsxs)(`table`,{className:`tbl log-detail-attempts`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{className:`num`,children:`#`}),(0,Q.jsx)(`th`,{children:a(`logs.detail.attempt.target`)}),(0,Q.jsx)(`th`,{className:`num`,children:a(`logs.col.duration`)}),(0,Q.jsx)(`th`,{className:`num`,title:a(`logs.detail.endToEndTokPerSec`),children:a(`logs.col.tokPerSec`)}),(0,Q.jsx)(`th`,{className:`num`,children:a(`logs.col.estimatedCost`)}),(0,Q.jsx)(`th`,{children:a(`logs.detail.attempt.reason`)})]})}),(0,Q.jsx)(`tbody`,{children:e.attempts.toSorted((e,t)=>e.ordinal-t.ordinal).map(e=>{let t=e.displayMetrics?.cost,n=e.displayMetrics?.decodeTokPerSecond,i=VT(n?.kind===`value`?n:{}),o=dE(e),s=t?.kind===`value`?t.estimate.price:void 0,c=AE(e,a).cause??e.errorCode??(e.recoveryKinds.length?e.recoveryKinds.map(e=>a(CE(e))).join(`, `):void 0)??(t?.kind===`unavailable`?a(xE(t.reason)):a(`logs.detail.attempt.completed`));return(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`num mono`,children:e.ordinal}),(0,Q.jsxs)(`td`,{children:[(0,Q.jsx)(`span`,{children:Ce(e.provider,a)}),(0,Q.jsx)(`br`,{}),(0,Q.jsx)(`span`,{className:`mono muted log-detail-break`,children:e.model}),(e.requestedEffort||e.effectiveEffort)&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`br`,{}),(0,Q.jsxs)(`span`,{className:`mono muted text-caption log-detail-break`,children:[uE(e),o?` (${o})`:``]})]}),s&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`br`,{}),(0,Q.jsxs)(`span`,{className:`muted text-caption log-detail-break`,children:[s.jawcodeProvider??s.provider,`/`,s.modelId,` · `,a(`logs.detail.source.${s.source}`),` · `,a(wE(s.status))]})]})]}),(0,Q.jsxs)(`td`,{className:`num mono`,children:[e.durationMs,`ms`]}),(0,Q.jsxs)(`td`,{className:`num mono`,children:[pE(e.displayMetrics?.tokPerSecond,r),n?.kind===`value`&&(0,Q.jsxs)(`span`,{className:`logs-stack-end logs-decode-rate muted`,title:a(i.detail),children:[(0,Q.jsx)(`span`,{children:pE(n,r)}),(0,Q.jsx)(`span`,{className:`text-caption`,children:a(i.short)})]})]}),(0,Q.jsx)(`td`,{className:`num mono`,children:WT(t,a,r)}),(0,Q.jsx)(`td`,{className:`log-detail-break`,children:c})]},`${e.ordinal}-${e.provider}-${e.model}`)})})]})})]}):null,(0,Q.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-usage`,children:[(0,Q.jsx)(`h4`,{id:`log-detail-usage`,className:`log-detail-section-title`,children:a(`logs.detail.section.usage`)}),(0,Q.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.input`)}),(0,Q.jsx)(`span`,{className:`mono`,children:e.usage?q(e.usage.inputTokens,n):`—`}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.output`)}),(0,Q.jsx)(`span`,{className:`mono`,children:e.usage?q(e.usage.outputTokens,n):`—`}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheRead`)}),(0,Q.jsx)(`span`,{className:`mono`,children:d.read===void 0?`—`:q(d.read,n)}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheWrite`)}),(0,Q.jsx)(`span`,{className:`mono`,children:d.write===void 0?`—`:q(d.write,n)}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.reasoning`)}),(0,Q.jsx)(`span`,{className:`mono`,children:e.usage?.reasoningOutputTokens===void 0?`—`:q(e.usage.reasoningOutputTokens,n)}),(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.detail.totalTokens`)}),(0,Q.jsx)(`span`,{className:`mono`,children:lE(e)===void 0?`—`:q(lE(e),n)}),e.usage?.contextTotalTokens!==void 0&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.contextTotal`)}),(0,Q.jsx)(`span`,{className:`mono`,children:q(e.usage.contextTotalTokens,n)})]})]}),e.usageStatus===`estimated`&&(0,Q.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`logs.tokens.estimatedNote`)})]}),(0,Q.jsxs)(`details`,{className:`log-detail-raw`,children:[(0,Q.jsx)(`summary`,{children:a(`logs.detailRaw`)}),(0,Q.jsx)(`pre`,{className:`log-detail-json`,children:JSON.stringify(e,null,2)})]})]})]})}function RE(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 zE(e,t){if(!e||!t)return{ok:!1,error:`required`};let n=RE(e),r=RE(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 BE=[`requests`,`tokens`,`cost`,`quota`,`none`],VE=[6,24,72,168],HE=[`line`,`stackedBar`],UE=[`total`,`input`,`output`,`cached`],WE=[`sum`,`average`,`max`],GE=[`model`,`modelAccount`],KE={requests:`usage.companion.menuRequests`,tokens:`usage.companion.menuTokens`,cost:`usage.companion.menuCost`,quota:`usage.companion.menuQuota`,none:`usage.companion.menuNone`},qE={6:`usage.companion.window6`,24:`usage.companion.window24`,72:`usage.companion.window72`,168:`usage.companion.window168`},JE={total:`usage.companion.metricTotal`,input:`usage.companion.metricInput`,output:`usage.companion.metricOutput`,cached:`usage.companion.metricCached`},YE=[[`showToday`,`usage.companion.sectionToday`],[`showChart`,`usage.companion.sectionChart`],[`showModels`,`usage.companion.sectionModels`],[`showCost`,`usage.companion.sectionCost`],[`showAccounts`,`usage.companion.sectionAccounts`]],XE={sum:`usage.companion.aggregationSum`,average:`usage.companion.aggregationAverage`,max:`usage.companion.aggregationMax`},ZE={macos:[`usage.companion.installMacStep1`,`usage.companion.installMacStep2`,`usage.companion.installMacStep3`],windows:[`usage.companion.installWinStep1`,`usage.companion.installWinStep2`,`usage.companion.installWinStep3`],linux:[`usage.companion.installLinuxStep1`,`usage.companion.installLinuxStep2`,`usage.companion.installLinuxStep3`]},QE={macos:`usage.companion.osMac`,windows:`usage.companion.osWindows`,linux:`usage.companion.osLinux`};function $E(e,t){return new Intl.DateTimeFormat(t,{hour:`2-digit`,minute:`2-digit`}).format(e)}function eD(e){return e instanceof Error&&e.message?e.message:String(e)}function tD({value:e,onChange:t,t:n}){return(0,Q.jsx)(`div`,{className:`usage-segmented`,role:`group`,"aria-label":n(`usage.companion.installOs`),children:Object.keys(QE).map(r=>(0,Q.jsx)(`button`,{type:`button`,className:`usage-segmented-btn${e===r?` active`:``}`,"aria-pressed":e===r,onClick:()=>t(r),children:n(QE[r])},r))})}function nD({label:e,value:t,options:n,optionLabel:r,onChange:i}){return(0,Q.jsxs)(`div`,{className:`usage-companion-control`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:e}),(0,Q.jsx)(`div`,{className:`usage-segmented`,role:`group`,"aria-label":e,children:n.map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`usage-segmented-btn${e===t?` active`:``}`,"aria-pressed":e===t,onClick:()=>i(e),children:r(e)},String(e)))})]})}function rD({label:e,value:t,options:n,optionLabel:r,onChange:i}){return(0,Q.jsxs)(`label`,{className:`usage-companion-control`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:e}),(0,Q.jsx)(`select`,{value:t,onChange:e=>i(e.target.value),children:n.map(e=>(0,Q.jsx)(`option`,{value:e,children:r(e)},e))})]})}function iD(e){let[t,n]=(0,Z.useState)(!1);return(0,Z.useEffect)(()=>{if(t||!e.current||typeof IntersectionObserver>`u`)return;let r=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&(n(!0),r.disconnect())},{rootMargin:`240px`});return r.observe(e.current),()=>r.disconnect()},[e,t]),t}function aD({apiBase:e,providers:t,onSettingsLoaded:n}){let{t:i,locale:a}=r(),o=(0,Z.useRef)(null),s=iD(o),[c,l]=(0,Z.useState)(null),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)(null),[m,h]=(0,Z.useState)([]),[g,_]=(0,Z.useState)(null),[v,y]=(0,Z.useState)(null),[b,x]=(0,Z.useState)(!1),[S,C]=(0,Z.useState)(`idle`),[w,T]=(0,Z.useState)(null),[E,D]=(0,Z.useState)(null),O=(0,Z.useRef)(null),k=(0,Z.useRef)(null),A=(0,Z.useRef)(null),j=(0,Z.useRef)(S),M=(0,Z.useRef)(u),N=(0,Z.useRef)(new Map),[P,F]=(0,Z.useState)(new Map),[I,L]=(0,Z.useState)(()=>{let e=vo();return e===`unknown`?`macos`:e});(0,Z.useEffect)(()=>{j.current=S},[S]),(0,Z.useEffect)(()=>{M.current=u},[u]);let R=(0,Z.useCallback)(async()=>{_(null);try{let t=await fetch(`${e}/api/companion/settings`);if(!t.ok)throw Error(`${t.status} ${t.statusText}`.trim());let r=await t.json();l(r),T(Date.now()),d(r.settings),k.current=r.settings,n?.(r.settings.menuBarMetric)}catch(e){_(eD(e))}},[e,n]);(0,Z.useEffect)(()=>{if(!s||c)return;let e=setTimeout(()=>void R(),0);return()=>clearTimeout(e)},[R,c,s]),(0,Z.useEffect)(()=>{if(!s)return;let e=setInterval(()=>{j.current!==`saving`&&(M.current&&k.current!==M.current||R())},6e4);return()=>clearInterval(e)},[R,s]);let z=(0,Z.useMemo)(()=>u?rt(u):null,[u]),B=(0,Z.useCallback)(async()=>{if(!z)return;A.current?.abort();let t=new AbortController;A.current=t,x(!0),y(null);try{let n=await fetch(`${e}/api/usage/timeline?${z}`,{signal:t.signal});if(!n.ok)throw Error(`${n.status} ${n.statusText}`.trim());let r=await n.json(),i=u?Ee(r,u):r;p(i),h(i.availableModels);let a=new Map;for(let e of i.series)a.set(e.id,(a.get(e.id)??0)+e.total);for(let[e,t]of a)N.current.set(e,t);F(new Map(N.current))}catch(e){t.signal.aborted||y(eD(e))}finally{t.signal.aborted||x(!1)}},[u,e,z]);(0,Z.useEffect)(()=>{if(!s||!z)return;let e=setTimeout(()=>void B(),250),t=setInterval(()=>void B(),6e4);return()=>{clearTimeout(e),clearInterval(t),A.current?.abort()}},[z,B,s]);let V=(0,Z.useCallback)(e=>{c?.corrupt||(d(t=>t&&{...t,...e}),C(`saving`),D(null))},[c?.corrupt]);(0,Z.useEffect)(()=>{if(!c?.corrupt&&u&&k.current&&k.current!==u&&S===`saving`)return O.current&&clearTimeout(O.current),O.current=setTimeout(async()=>{try{let t=Fe(u,m),n=await fetch(`${e}/api/companion/settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({settings:t})}),r=await n.json();if(!n.ok)throw Error(r&&`error`in r&&r.error?r.error:`${n.status} ${n.statusText}`.trim());l(r),T(Date.now()),d(r.settings),k.current=r.settings,C(`saved`)}catch(e){D(eD(e)),C(`error`)}},300),()=>{O.current&&clearTimeout(O.current)}},[e,m,c?.corrupt,S,u]);let H=(0,Z.useRef)(m);(0,Z.useEffect)(()=>{H.current=m},[m]),(0,Z.useEffect)(()=>()=>{let t=M.current;t&&k.current&&k.current!==t&&j.current===`saving`&&fetch(`${e}/api/companion/settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({settings:Fe(t,H.current)}),keepalive:!0}).catch(()=>{})},[e]);let U=(0,Z.useCallback)(async()=>{C(`saving`),D(null);try{let t=await fetch(`${e}/api/companion/settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({reset:!0})});if(!t.ok)throw Error(`${t.status} ${t.statusText}`.trim());await R(),C(`saved`)}catch(e){D(eD(e)),C(`error`)}},[e,R]),ee=(0,Z.useCallback)(async()=>{try{let t=location.hash?`/${location.hash}`:`/#/usage`,n=await fetch(`${e}/api/companion/open-in-browser`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({path:t})});if(!n.ok)throw Error(`${n.status} ${n.statusText}`.trim())}catch(e){D(eD(e))}},[e]);if(g)return(0,Q.jsxs)(`section`,{ref:o,className:`usage-companion-panel`,children:[(0,Q.jsx)(`p`,{role:`alert`,children:i(`usage.companion.settingsUnavailable`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void R(),children:i(`common.retry`)})]});let W=u;if(!W)return(0,Q.jsx)(`section`,{ref:o,className:`usage-companion-panel`,"aria-busy":`true`,children:(0,Q.jsx)(`div`,{className:`usage-companion-loading`,children:i(`common.loading`)})});let te=t.map(e=>e.provider).filter((e,t,n)=>n.indexOf(e)===t).toSorted(),G=W.models??m,ne=new Set(G),K=ke(m,P),re=new Set(W.hiddenProviders),q=S===`saved`&&c?.updatedAt?i(`usage.companion.saved`,{time:$E(c.updatedAt,a)}):S===`error`?i(`usage.companion.saveFailed`,{error:E??``}):``;return(0,Q.jsxs)(`section`,{ref:o,className:`usage-companion-panel`,children:[c?.corrupt&&(0,Q.jsxs)(`div`,{className:`usage-companion-save-status is-error`,role:`alert`,children:[(0,Q.jsx)(`span`,{children:i(`usage.companion.corrupt`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void U(),disabled:S===`saving`,children:i(`usage.companion.corruptReset`)})]}),(0,Q.jsxs)(`div`,{className:`usage-companion-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h3`,{className:`panel-title`,children:i(`usage.companion.title`)}),(0,Q.jsx)(`p`,{className:`card-sub`,children:i(`usage.companion.description`)})]}),(0,Q.jsx)(`a`,{className:`btn btn-ghost btn-sm`,href:`https://opencodex.me/guides/macos-menu-bar/`,target:`_blank`,rel:`noreferrer`,children:i(`usage.companion.installGuide`)})]}),(()=>{let e=c?.companion?.lastSeenAt??null,t=e!==null&&w!==null&&w-e<=6e5,n=e===null||w===null?``:Bs(e,Vs(i),w),r=mo(),a=po()??`2.95.3`,o=ZE[I],s=(0,Q.jsxs)(`ol`,{className:`usage-companion-install-steps`,children:[(0,Q.jsxs)(`li`,{children:[i(o[0]),` `,(0,Q.jsx)(`a`,{className:`btn btn-ghost btn-sm`,href:`https://github.com/lidge-jun/opencodex/releases/latest`,target:`_blank`,rel:`noreferrer`,children:i(`common.github`)})]}),(0,Q.jsx)(`li`,{children:i(o[1])}),(0,Q.jsx)(`li`,{children:i(o[2])})]}),l=I===`macos`?(0,Q.jsx)(`code`,{className:`usage-companion-install-command`,children:`xattr -d com.apple.quarantine /Applications/OpenCodex.app`}):I===`linux`?(0,Q.jsx)(`code`,{className:`usage-companion-install-command`,children:`chmod +x OpenCodex-*.AppImage`}):null,u=(0,Q.jsxs)(`details`,{children:[(0,Q.jsx)(`summary`,{children:i(`usage.companion.installAnother`)}),(0,Q.jsx)(tD,{value:I,onChange:L,t:i}),s,l]});return r?(0,Q.jsxs)(`div`,{className:`usage-companion-install usage-companion-install--shell`,children:[(0,Q.jsx)(`p`,{children:i(`usage.companion.runningInDesktop`,{version:a})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void ee(),children:i(`usage.companion.openInBrowser`)}),u]}):t?(0,Q.jsxs)(`div`,{className:`usage-companion-install usage-companion-install--connected`,children:[(0,Q.jsxs)(`div`,{className:`usage-companion-install-status`,children:[(0,Q.jsx)(`span`,{className:`usage-companion-install-dot`,"aria-hidden":`true`}),i(c?.companion?.kind===`desktop`?`usage.companion.connectedDesktop`:`usage.companion.connected`,{age:n})]}),u]}):(0,Q.jsxs)(`details`,{className:`usage-companion-install`,open:!0,children:[(0,Q.jsx)(`summary`,{children:i(`usage.companion.installTitle`)}),e!==null&&(0,Q.jsx)(`p`,{className:`usage-companion-install-last-seen muted text-caption`,children:i(`usage.companion.lastSeen`,{age:n})}),e===null&&(0,Q.jsx)(`p`,{className:`usage-companion-install-last-seen muted text-caption`,children:i(`usage.companion.notConnected`)}),(0,Q.jsx)(tD,{value:I,onChange:L,t:i}),s,l]})})(),(0,Q.jsx)(Ge,{timeline:f,chartStyle:W.chartStyle,hours:W.chartHours,loading:b,error:v,onRetry:()=>void B(),locale:a,t:i}),K.length>0&&(0,Q.jsxs)(`section`,{className:`usage-companion-models`,children:[(0,Q.jsxs)(`div`,{className:`usage-companion-models-header`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`span`,{className:`field-label`,children:i(`usage.companion.modelsOnChart`)}),(0,Q.jsx)(`span`,{className:`usage-companion-models-count text-caption muted`,children:i(`usage.companion.modelsCount`,{selected:G.length,total:m.length})})]}),W.models!==null&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>V({models:null}),disabled:c?.corrupt,children:i(`usage.companion.modelsShowAll`)})]}),(0,Q.jsx)(`div`,{className:`usage-companion-models-list`,children:K.map(e=>{let t=e.models.filter(e=>ne.has(e.id)).length,n=t===e.models.length;return(0,Q.jsxs)(`div`,{className:`usage-companion-model-group`,children:[(0,Q.jsxs)(`div`,{className:`usage-companion-model-group-header`,children:[(0,Q.jsx)(`span`,{className:`usage-companion-model-provider`,children:e.provider}),(0,Q.jsx)(`span`,{className:`usage-companion-model-chip mono text-caption`,children:e.models.length}),(0,Q.jsx)(ln,{on:n,mixed:t>0&&!n,onClick:()=>V({models:st(W.models,m,e.models.map(e=>e.id),!n)}),disabled:c?.corrupt,label:e.provider,title:e.provider})]}),e.models.map(e=>{let t=ne.has(e.id);return(0,Q.jsxs)(`div`,{className:`usage-companion-model-row${t?``:` is-off`}`,children:[(0,Q.jsx)(ln,{on:t,onClick:()=>V({models:st(W.models,m,[e.id],!t)}),disabled:c?.corrupt,label:e.id,title:e.id}),(0,Q.jsx)(`code`,{className:`mono text-control`,children:e.id}),(0,Q.jsx)(`span`,{className:`usage-companion-model-total muted text-caption`,children:P.has(e.id)?lt(e.total):`—`})]},e.id)})]},e.provider)})})]}),(0,Q.jsxs)(`fieldset`,{className:`usage-companion-controls`,disabled:c?.corrupt,children:[(0,Q.jsx)(nD,{label:i(`usage.companion.menuBarShows`),value:W.menuBarMetric,options:BE,optionLabel:e=>i(KE[e]),onChange:e=>V({menuBarMetric:e})}),(0,Q.jsx)(nD,{label:i(`usage.companion.window`),value:W.chartHours,options:VE,optionLabel:e=>i(qE[e]),onChange:e=>V({chartHours:e,bucketMinutes:Le(e)})}),(0,Q.jsx)(nD,{label:i(`usage.companion.style`),value:W.chartStyle,options:HE,optionLabel:e=>i(e===`line`?`usage.companion.styleLine`:`usage.companion.styleStacked`),onChange:e=>V({chartStyle:e})}),(0,Q.jsx)(rD,{label:i(`usage.companion.metric`),value:W.tokenMetric,options:UE,optionLabel:e=>i(JE[e]),onChange:e=>V({tokenMetric:e})}),(0,Q.jsx)(rD,{label:i(`usage.companion.groupBy`),value:W.chartGrouping,options:GE,optionLabel:e=>i(e===`model`?`usage.companion.groupModel`:`usage.companion.groupAccount`),onChange:e=>V({chartGrouping:e})}),(0,Q.jsxs)(`fieldset`,{className:`usage-companion-switches`,children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:i(`usage.companion.popoverSections`)}),YE.map(([e,t])=>(0,Q.jsxs)(`div`,{className:`usage-companion-switch`,children:[(0,Q.jsx)(`span`,{children:i(t)}),(0,Q.jsx)(`button`,{type:`button`,className:`toggle ${W[e]?`on`:``}`,"aria-label":i(t),"aria-pressed":W[e],onClick:()=>V({[e]:!W[e]}),children:(0,Q.jsx)(`span`,{className:`toggle-knob`})})]},e))]}),(0,Q.jsxs)(`details`,{className:`usage-companion-advanced`,children:[(0,Q.jsx)(`summary`,{children:i(`usage.companion.advanced`)}),(0,Q.jsxs)(`div`,{className:`usage-companion-advanced-body`,children:[(0,Q.jsx)(rD,{label:i(`usage.companion.aggregation`),value:W.aggregation,options:WE,optionLabel:e=>i(XE[e]),onChange:e=>V({aggregation:e})}),(0,Q.jsxs)(`label`,{className:`usage-companion-control`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:i(`usage.companion.menuText`)}),(0,Q.jsx)(`input`,{value:W.menuBarTemplate??``,onChange:e=>V({menuBarTemplate:e.target.value}),maxLength:200}),(0,Q.jsxs)(`span`,{className:`muted text-caption`,children:[i(`usage.companion.placeholders`),` `,(0,Q.jsx)(`code`,{children:`{requests} {totalTokens} {inputTokens} {outputTokens} {costUsd} {quotaPercent}`})]})]}),te.length>0&&(0,Q.jsxs)(`fieldset`,{className:`usage-companion-check-list`,children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:i(`usage.companion.hideProviders`)}),te.map(e=>(0,Q.jsxs)(`label`,{children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:re.has(e),onChange:t=>V({hiddenProviders:t.target.checked?[...W.hiddenProviders,e]:W.hiddenProviders.filter(t=>t!==e)})}),` `,(0,Q.jsx)(`span`,{children:e})]},e))]})]})]})]}),(0,Q.jsxs)(`div`,{className:`usage-companion-save-status${S===`error`?` is-error`:``}`,role:S===`error`?`alert`:`status`,children:[q||`\xA0`,S===`error`&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{C(`saving`)},children:i(`common.retry`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void U(),children:i(`usage.companion.reset`)}),(0,Q.jsx)(`p`,{className:`muted text-caption`,children:i(`usage.companion.footer`)})]})}function oD({apiBase:e,providers:t}){let[n,r]=(0,Z.useState)([]);return(0,Z.useEffect)(()=>{if(t.length>0)return;let n=new AbortController;return fetch(`${e}/api/config`,{signal:n.signal}).then(e=>vn(e)).then(e=>{n.signal.aborted||r(Object.keys(e?.providers??{}).map(e=>({provider:e})))}).catch(()=>{}),()=>n.abort()},[e,t.length]),(0,Q.jsx)(aD,{apiBase:e,providers:t.length>0?t:n})}function sD(){return window.location.hash.replace(/^#\/?/,``)===`usage/companion`?`companion`:`report`}function cD(e){window.location.hash=e===`report`?`usage`:`usage/companion`}function lD(e){if(e.key===`ArrowLeft`||e.key===`Home`||e.key===`ArrowRight`||e.key===`End`){e.preventDefault();let t=e.key===`ArrowLeft`||e.key===`Home`?`report`:`companion`;cD(t),document.getElementById(`usage-tab-${t}`)?.focus()}}var uD=class extends Error{};function dD(e){return`${Math.round(e*100)}%`}function fD({row:e,locale:t,t:n}){if(e.estimatedCostUsd===void 0&&e.pricedRequests===void 0&&e.unpricedRequests===void 0)return(0,Q.jsx)(`span`,{className:`muted`,children:`—`});let r=e.unpricedRequests??0,i=n(r===1?`usage.cost.excludedOne`:`usage.cost.excluded`,{count:r});return e.estimatedCostUsd===void 0?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`muted`,children:`—`}),r>0&&(0,Q.jsxs)(`span`,{className:`muted text-caption usage-cost-note`,children:[` `,i]})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`mono`,children:qd(e.estimatedCostUsd??0,t)}),r>0&&(0,Q.jsxs)(`span`,{className:`muted text-caption usage-cost-note`,children:[` `,i]})]})}function pD(e,t,n){return typeof e==`number`&&Number.isFinite(e)&&e>=0?q(e,t):n}function mD(e,t){return typeof e==`number`&&Number.isFinite(e)?dD(e):t}function hD(e,t,n){if(typeof e.cacheHitRate!=`number`||!Number.isFinite(e.cacheHitRate))return n(`usage.cacheHitRate.unmeasured`);let r=e.cacheObservedInputTokens;if(!(typeof r!=`number`||!Number.isFinite(r)||r>=e.inputTokens))return n(`usage.cacheHitRate.partial`,{measured:q(r,t),total:q(e.inputTokens,t)})}function gD(e){return typeof e==`number`&&Number.isFinite(e)&&e>0}function _D(e,t){return gD(e.throughputTokensPerSec)?t(`usage.throughput.title`,{samples:e.throughputSamples??0}):t(`usage.throughput.unmeasured`)}function vD(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 yD(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 bD(e,t){return new Intl.DateTimeFormat(t,{dateStyle:`medium`}).format(new Date(`${e}T12:00:00`))}function xD(e){let t=window.innerWidth,n=window.innerHeight,r=Math.min(240,Math.max(0,t-16));return{left:Math.max(8,Math.min(e.left+e.width/2-r/2,t-8-r)),maxWidth:r,...e.top-8>n-e.bottom-8?(()=>{let t=Math.max(8,Math.min(n-8,n-e.top+8));return{bottom:t,maxHeight:Math.max(0,n-t-8)}})():(()=>{let t=Math.max(8,Math.min(n-8,e.bottom+8));return{top:t,maxHeight:Math.max(0,n-t-8)}})()}}function SD({anchor:e,className:t,children:n}){return(0,Zt.createPortal)((0,Q.jsx)(`div`,{className:`${t} chart-overlay`,role:`tooltip`,style:xD(e),children:n}),document.body)}function CD(e,t,n){return n(`usage.chart.dayDetail`,{date:bD(e.date,t),requests:e.requests,tokens:q(e.totalTokens,t)})}function wD(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 TD(e,t){return e<=0?0:e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4}function ED(e,t=!1){let n=wD(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:TD(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?TD(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 DD({surface:e,range:t,onSurface:n,onRange:r,t:i}){return(0,Q.jsxs)(`div`,{className:`usage-filters`,children:[(0,Q.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,Q.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,Q.jsx)(`img`,{className:`usage-source-mark`,src:`/provider-icons/openai.svg`,alt:``,"aria-hidden":`true`}),t===`claude`&&(0,Q.jsx)(`img`,{className:`usage-source-mark`,src:`/provider-icons/claude-color.svg`,alt:``,"aria-hidden":`true`}),t===`grok`&&(0,Q.jsx)(`img`,{className:`usage-source-mark usage-source-mark--mono`,src:`/provider-icons/grok.svg`,alt:``,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:t===`all`?`usage-source-label`:`usage-source-label usage-source-label-collapsible`,children:r})]},t)})}),(0,Q.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,Q.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 OD({summary:e,activeDays:t,locale:n,t:r}){return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`usage-cards usage-cards-3x2`,role:`group`,"aria-label":r(`usage.title`),children:[(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`muted`,children:r(`usage.card.requests`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:e.requests})]}),(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`muted`,children:r(`usage.card.measured`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:e.measuredRequests})]}),(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`muted`,children:r(`usage.card.totalTokens`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:q(e.totalTokens,n)})]}),(0,Q.jsxs)(`div`,{className:`stat`,title:r(`usage.card.cachedTokensHint`),children:[(0,Q.jsx)(`div`,{className:`muted`,children:r(`usage.card.cachedTokens`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:q(e.cacheReadInputTokens??e.cachedInputTokens,n)}),(e.cacheCreationInputTokens??0)>0&&(0,Q.jsxs)(`div`,{className:`muted text-caption`,children:[r(`usage.card.cacheWriteTokens`),`: `,q(e.cacheCreationInputTokens??0,n)]})]}),(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`muted`,children:r(`usage.card.coverage`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:dD(e.coverageRatio)})]}),(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`muted`,children:r(`usage.card.activeDays`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:t})]})]}),(0,Q.jsxs)(`div`,{className:`usage-cost-row`,role:`note`,title:_D(e,r),children:[(0,Q.jsx)(`span`,{className:`muted`,children:r(`usage.col.tokPerSec`)}),(0,Q.jsx)(`span`,{className:`stat-value mono usage-cost-value`,children:gD(e.throughputTokensPerSec)?e.throughputTokensPerSec.toFixed(1):r(`usage.unavailable`)}),(0,Q.jsx)(`span`,{className:`muted text-caption`,children:_D(e,r)})]}),e.estimatedCostUsd!==void 0&&(0,Q.jsxs)(`div`,{className:`usage-cost-row`,role:`note`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:r(`usage.cost.total`)}),(0,Q.jsx)(`span`,{className:`stat-value mono usage-cost-value`,children:qd(e.estimatedCostUsd,n)}),(0,Q.jsx)(`span`,{className:`muted text-caption`,children:r(`usage.cost.disclaimer`)}),(e.unpricedRequests??0)+(e.unmeteredRequests??0)>0&&(0,Q.jsx)(`span`,{className:`muted text-caption`,children:r(`usage.cost.unpricedNote`).replace(`{count}`,String((e.unpricedRequests??0)+(e.unmeteredRequests??0)))})]})]})}function kD({weekBars:e,locale:t,t:n}){let[r,i]=(0,Z.useState)(null),a=Math.max(1,...e.map(e=>e.totalTokens)),o=e.find(e=>e.date===r?.date),s=(e,t)=>{i({date:e.date,anchor:t.getBoundingClientRect()})};return(0,Q.jsxs)(`div`,{className:`daybars`,role:`group`,"aria-label":n(`usage.section.heatmap`),children:[e.map(e=>{let r=Math.round(e.totalTokens/a*100),o=new Intl.DateTimeFormat(t,{weekday:`short`}).format(new Date(`${e.date}T12:00:00`));return(0,Q.jsxs)(`button`,{type:`button`,className:`daybar`,"aria-label":CD(e,t,n),onFocus:t=>s(e,t.currentTarget),onBlur:()=>i(t=>t?.date===e.date?null:t),onPointerEnter:t=>s(e,t.currentTarget),onPointerDown:t=>s(e,t.currentTarget),onPointerLeave:t=>{t.pointerType!==`touch`&&document.activeElement!==t.currentTarget&&i(t=>t?.date===e.date?null:t)},children:[(0,Q.jsx)(`div`,{className:`daybar-track`,children:(0,Q.jsxs)(`div`,{className:`daybar-stack`,style:{"--daybar-scale":String(Math.max(0,Math.min(1,r/100)))},children:[e.models.map(e=>(0,Q.jsx)(`div`,{className:`daybar-seg`,style:{flexGrow:e.totalTokens,background:vD(e.model,e.provider)}},`${e.provider}/${e.model}`)),e.models.length===0&&e.totalTokens>0&&(0,Q.jsx)(`div`,{className:`daybar-seg`,style:{flexGrow:1,background:`var(--green)`}})]})}),(0,Q.jsx)(`span`,{className:`daybar-count`,children:q(e.totalTokens,t)}),(0,Q.jsx)(`span`,{className:`daybar-label muted`,children:o})]},e.date)}),r&&o&&(0,Q.jsxs)(SD,{className:`daybar-tip`,anchor:r.anchor,children:[(0,Q.jsx)(`div`,{className:`daybar-tip-date`,children:bD(o.date,t)}),(0,Q.jsxs)(`div`,{className:`daybar-tip-row`,children:[(0,Q.jsx)(`span`,{children:n(`usage.heatmap.tooltipRequests`,{requests:o.requests})}),(0,Q.jsx)(`span`,{className:`daybar-tip-val`,children:n(`usage.heatmap.tooltipTokens`,{tokens:q(o.totalTokens,t)})})]}),o.models.slice(0,8).map(e=>(0,Q.jsxs)(`div`,{className:`daybar-tip-row`,children:[(0,Q.jsx)(`span`,{className:`daybar-tip-swatch`,style:{background:vD(e.model,e.provider)}}),(0,Q.jsx)(`span`,{className:`daybar-tip-name`,children:zv(e.model)}),(0,Q.jsx)(`span`,{className:`daybar-tip-val`,children:q(e.totalTokens,t)})]},`${e.provider}/${e.model}`))]})]})}function AD({range:e,heatmap:t,weekBars:n,locale:r,t:i}){let a=(0,Z.useRef)(null),o=(0,Z.useMemo)(()=>t.weeks.flat().filter(e=>e.date),[t]),[s,c]=(0,Z.useState)(()=>o.at(-1)?.date??``),[l,u]=(0,Z.useState)(null),d=(0,Z.useId)(),f=o.some(e=>e.date===s)?s:o.at(-1)?.date??``,p=(e,t)=>{c(e.date),u({date:e.date,anchor:t.getBoundingClientRect()})},m=(e,t)=>{let n=o.findIndex(e=>e.date===t.date),r=e.key===`ArrowUp`?-1:e.key===`ArrowDown`?1:e.key===`ArrowLeft`?-7:e.key===`ArrowRight`?7:0;if(!r||n<0)return;e.preventDefault();let i=o[Math.max(0,Math.min(o.length-1,n+r))];c(i.date);let s=a.current?.querySelector(`[data-date="${i.date}"]`);s&&(s.focus(),u({date:i.date,anchor:s.getBoundingClientRect()}))};return(0,Z.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,Q.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":`usage-heatmap-title`,children:[(0,Q.jsx)(`h3`,{id:`usage-heatmap-title`,className:`panel-title`,children:i(`usage.section.heatmap`)}),e===`7d`?(0,Q.jsx)(kD,{weekBars:n,locale:r,t:i}):(0,Q.jsxs)(`div`,{className:`heatmap`,ref:a,children:[(0,Q.jsxs)(`div`,{className:`heatmap-months`,style:{gridTemplateColumns:`28px repeat(${t.weeks.length}, calc(var(--hm-cell) + var(--hm-gap)))`},children:[(0,Q.jsx)(`span`,{className:`heatmap-day-spacer`}),t.months.map(e=>(0,Q.jsx)(`span`,{className:`heatmap-month`,style:{gridColumn:e.col+2},children:e.label},`${e.label}-${e.col}`))]}),(0,Q.jsxs)(`div`,{className:`heatmap-body`,children:[(0,Q.jsxs)(`div`,{className:`heatmap-days`,children:[(0,Q.jsx)(`span`,{}),(0,Q.jsx)(`span`,{children:i(`usage.dayMon`)}),(0,Q.jsx)(`span`,{}),(0,Q.jsx)(`span`,{children:i(`usage.dayWed`)}),(0,Q.jsx)(`span`,{}),(0,Q.jsx)(`span`,{children:i(`usage.dayFri`)}),(0,Q.jsx)(`span`,{})]}),(0,Q.jsx)(`div`,{className:`heatmap-grid`,role:`group`,"aria-labelledby":`usage-heatmap-title`,"aria-describedby":d,style:{gridTemplateColumns:`repeat(${t.weeks.length}, var(--hm-cell))`},children:t.weeks.map((e,t)=>(0,Q.jsx)(`div`,{className:`heatmap-week`,children:e.map((e,n)=>e.date?(0,Q.jsx)(`button`,{type:`button`,className:`heatmap-cell heatmap-cell-${e.level}`,"data-date":e.date,tabIndex:f===e.date?0:-1,"aria-label":CD(e,r,i),onFocus:t=>p(e,t.currentTarget),onBlur:()=>u(t=>t?.date===e.date?null:t),onKeyDown:t=>m(t,e),onPointerEnter:t=>p(e,t.currentTarget),onPointerDown:t=>p(e,t.currentTarget),onPointerLeave:t=>{t.pointerType!==`touch`&&document.activeElement!==t.currentTarget&&u(t=>t?.date===e.date?null:t)}},e.date):(0,Q.jsx)(`span`,{className:`heatmap-cell heatmap-cell-0`,"aria-hidden":`true`},`pad-${t}-${n}`))},e[0]?.date||`week-${t}`))})]}),(0,Q.jsx)(`span`,{id:d,className:`sr-only`,children:i(`usage.heatmap.keyboardLabel`)}),(0,Q.jsx)(`span`,{className:`sr-only`,"aria-live":`polite`,children:o.find(e=>e.date===f)?CD(o.find(e=>e.date===f),r,i):``}),l&&(()=>{let e=o.find(e=>e.date===l.date);return e?.date?(0,Q.jsxs)(SD,{className:`heatmap-tip`,anchor:l.anchor,children:[(0,Q.jsx)(`div`,{className:`heatmap-tip-date`,children:bD(e.date,r)}),(0,Q.jsx)(`div`,{className:`heatmap-tip-val`,children:i(`usage.heatmap.tooltipTokens`,{tokens:q(e.totalTokens,r)})}),(0,Q.jsx)(`div`,{className:`heatmap-tip-req muted`,children:i(`usage.heatmap.tooltipRequests`,{requests:e.requests})})]}):null})(),(0,Q.jsxs)(`div`,{className:`heatmap-legend muted`,children:[(0,Q.jsx)(`span`,{children:i(`usage.heatmap.less`)}),[0,1,2,3,4].map(e=>(0,Q.jsx)(`span`,{className:`heatmap-cell heatmap-cell-${e}`},e)),(0,Q.jsx)(`span`,{children:i(`usage.heatmap.more`)})]})]})]})}function jD({title:e,titleId:t,children:n}){return(0,Q.jsxs)(`section`,{className:`usw-section`,"aria-labelledby":t,children:[(0,Q.jsx)(`h3`,{id:t,className:`h-section`,children:e}),n]})}function MD({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=`usage-models-list-price-disclaimer`,u=i(`usage.unavailable`),d=(0,Q.jsx)(`input`,{className:`input`,"aria-label":o,placeholder:o,value:t,onChange:e=>n(e.target.value)}),f=(0,Q.jsxs)(`div`,{className:`tbl-wrap`,children:[(0,Q.jsxs)(`table`,{className:`tbl usage-models-tbl`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:i(`logs.col.model`)}),(0,Q.jsx)(`th`,{children:i(`logs.col.provider`)}),(0,Q.jsx)(`th`,{children:i(`usage.col.share`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`usage.col.tokens`)}),(0,Q.jsx)(`th`,{className:`num`,"aria-describedby":l,children:i(`usage.col.apiListPrice`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`usage.col.requests`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`usage.col.measured`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`usage.col.inputTokens`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`usage.col.outputTokens`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`usage.col.tokPerSec`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`usage.col.cacheHits`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`usage.col.cacheWrites`)}),(0,Q.jsx)(`th`,{className:`num`,children:i(`usage.col.cacheHitRate`)})]})}),(0,Q.jsx)(`tbody`,{children:e.map(e=>{let t=Ce(e.provider,i),n=hD(e,r,i),a=_D(e,i);return(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`mono`,title:e.model,children:zv(e.model)}),(0,Q.jsx)(`td`,{className:`muted`,title:t,children:t}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`div`,{className:`usage-bar`,children:(0,Q.jsx)(`div`,{className:`usage-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})}),(0,Q.jsx)(`td`,{className:`num mono`,children:q(e.totalTokens,r)}),(0,Q.jsx)(`td`,{className:`num`,children:(0,Q.jsx)(fD,{row:e,locale:r,t:i})}),(0,Q.jsx)(`td`,{className:`num`,children:e.requests}),(0,Q.jsx)(`td`,{className:`num`,children:e.measuredRequests}),(0,Q.jsx)(`td`,{className:`num mono`,children:q(e.inputTokens,r)}),(0,Q.jsx)(`td`,{className:`num mono`,children:q(e.outputTokens,r)}),(0,Q.jsxs)(`td`,{className:`num mono`,title:a,children:[(0,Q.jsx)(`span`,{className:`usage-hit-rate`,children:gD(e.throughputTokensPerSec)?`${e.throughputTokensPerSec.toFixed(1)} tok/s`:u}),gD(e.throughputTokensPerSec)&&(0,Q.jsx)(`span`,{className:`sr-only`,children:a})]}),(0,Q.jsx)(`td`,{className:`num mono`,children:pD(e.cacheReadInputTokens??e.cachedInputTokens,r,u)}),(0,Q.jsx)(`td`,{className:`num mono`,children:pD(e.cacheCreationInputTokens,r,u)}),(0,Q.jsxs)(`td`,{className:`num mono`,title:n,children:[(0,Q.jsx)(`span`,{className:`usage-hit-rate`,children:mD(e.cacheHitRate,u)}),n!==void 0&&(0,Q.jsx)(`span`,{className:`sr-only`,children:n})]})]},`${e.provider}/${e.model}`)})})]}),(0,Q.jsx)(`p`,{id:l,className:`muted text-caption`,children:i(`usage.cost.disclaimer`)})]});return a?(0,Q.jsxs)(jD,{title:s,titleId:c,children:[(0,Q.jsx)(`div`,{className:`usw-section-toolbar`,children:d}),f]}):(0,Q.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":c,children:[(0,Q.jsxs)(`div`,{className:`panel-head`,children:[(0,Q.jsx)(`h3`,{id:c,className:`panel-title`,children:s}),d]}),f]})}function ND({providers:e,locale:t,t:n,workspace:r=!1}){let i=n(`usage.unavailable`),a=n(`usage.section.providers`),o=`usage-providers-title`,s=`usage-providers-list-price-disclaimer`,c=(0,Q.jsxs)(`div`,{className:`tbl-wrap`,children:[(0,Q.jsxs)(`table`,{className:`tbl`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:n(`logs.col.provider`)}),(0,Q.jsx)(`th`,{className:`num`,children:n(`usage.col.requests`)}),(0,Q.jsx)(`th`,{className:`num`,children:n(`usage.col.measured`)}),(0,Q.jsx)(`th`,{className:`num`,children:n(`usage.col.tokens`)}),(0,Q.jsx)(`th`,{className:`num`,children:n(`usage.col.tokPerSec`)}),(0,Q.jsx)(`th`,{className:`num`,"aria-describedby":s,children:n(`usage.col.apiListPrice`)}),(0,Q.jsx)(`th`,{children:n(`usage.col.share`)})]})}),(0,Q.jsx)(`tbody`,{children:e.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`mono`,children:Ce(e.provider,n)}),(0,Q.jsx)(`td`,{className:`num`,children:e.requests}),(0,Q.jsx)(`td`,{className:`num`,children:e.measuredRequests}),(0,Q.jsx)(`td`,{className:`num mono`,children:q(e.totalTokens,t)}),(0,Q.jsxs)(`td`,{className:`num mono`,title:_D(e,n),children:[(0,Q.jsx)(`span`,{className:`usage-hit-rate`,children:gD(e.throughputTokensPerSec)?`${e.throughputTokensPerSec.toFixed(1)} tok/s`:i}),gD(e.throughputTokensPerSec)&&(0,Q.jsx)(`span`,{className:`sr-only`,children:_D(e,n)})]}),(0,Q.jsx)(`td`,{className:`num`,children:(0,Q.jsx)(fD,{row:e,locale:t,t:n})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`div`,{className:`usage-bar`,children:(0,Q.jsx)(`div`,{className:`usage-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})})]},e.provider))})]}),(0,Q.jsx)(`p`,{id:s,className:`muted text-caption`,children:n(`usage.cost.disclaimer`)})]});return r?(0,Q.jsx)(jD,{title:a,titleId:o,children:c}):(0,Q.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":o,children:[(0,Q.jsx)(`h3`,{id:o,className:`panel-title`,children:a}),c]})}function PD({summary:e,t,workspace:n=!1}){let r=t(`usage.section.coverage`),i=`usage-coverage-title`,a=(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`usage-cards usage-cards-3x2`,children:[(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.measured`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:e.measuredRequests})]}),(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.reported`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:e.reportedRequests})]}),(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.estimated`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:e.estimatedRequests})]}),(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`muted`,children:t(`logs.tokens.unreported`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:e.unreportedRequests})]}),(0,Q.jsxs)(`div`,{className:`stat`,children:[(0,Q.jsx)(`div`,{className:`muted`,children:t(`logs.tokens.unsupported`)}),(0,Q.jsx)(`div`,{className:`stat-value`,children:e.unsupportedRequests})]})]}),(0,Q.jsx)(`p`,{className:`muted text-control`,style:{marginTop:12},children:t(`usage.coverage.note`)})]});return n?(0,Q.jsx)(jD,{title:r,titleId:i,children:a}):(0,Q.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":i,children:[(0,Q.jsx)(`h3`,{id:i,className:`panel-title`,children:r}),a]})}function FD({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,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(OD,{summary:e.summary,activeDays:r,locale:l,t:u}),(0,Q.jsx)(AD,{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,Q.jsx)(MD,{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,Q.jsx)(ND,{providers:s,locale:l,t:u,workspace:!0}):null},{id:`coverage`,label:u(`usage.section.coverage`),meta:e?dD(e.summary.coverageRatio):`—`,body:e?(0,Q.jsx)(PD,{summary:e.summary,t:u,workspace:!0}):null}];return(0,Q.jsx)(`div`,{className:`usage-workspace-shell`,children:(0,Q.jsxs)(`div`,{className:`usage-workspace-root`,children:[(0,Q.jsx)(uw,{scope:`usage`,ariaLabel:u(`usage.workspace.sections`),items:f.map(e=>({id:e.id,label:e.label,meta:e.meta}))}),(0,Q.jsx)(`section`,{className:`usage-workspace-main`,"aria-label":u(`usage.workspace.report`),children:d?(0,Q.jsx)(fn,{title:u(`usage.empty`)}):f.map(e=>(0,Q.jsx)(`div`,{id:sw(`usage`,e.id),className:`usw-body usw-section-block`,children:e.body},e.id))})]})})}var ID=new Map;function LD(e,t,n,r,i,a){return`ocx.usage.v2:${e}:${r?`connected`:`standalone`}:${i}:${a??``}:${t}:${n}`}function RD(e,t,n,r,i,a){let o=LD(e,t,n,r,i,a);return ID.get(o)??io(o)}function zD(e,t,n,r,i,a,o){let s=LD(e,t,n,r,i,a);ID.set(s,o),co(s,o)}function BD({apiBase:e,connected:t=!1,apiKeyId:n}){let{t:i,locale:a}=r(),[o,s]=(0,Z.useState)(sD);(0,Z.useEffect)(()=>{let e=()=>s(sD());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]);let[c,l]=(0,Z.useState)(`30d`),[u,d]=(0,Z.useState)(`all`),[f,p]=(0,Z.useState)(`machine`),[m,h]=(0,Z.useState)(``),[g,_]=(0,Z.useState)({since:``,until:``}),[v,y]=(0,Z.useState)(null),[b,x]=(0,Z.useState)(null),[S,C]=(0,Z.useState)(!1),w=v?.since,T=v?.until,E=()=>{y(null),_({since:``,until:``}),x(null)},D=e=>{l(e),E()},O=(0,Z.useCallback)(async r=>{let i=new URLSearchParams({range:c,surface:u});t&&f===`machine`&&n&&i.set(`apiKeyId`,n),w!==void 0&&T!==void 0&&(i.set(`since`,String(w)),i.set(`until`,String(T)));let a=await br(await fetch(`${e}/api/usage?${i}`,{signal:r}));if(w!==void 0&&(a?.customWindow!==!0||a.since!==w||a.until!==T))throw new uD;return w===void 0&&zD(e,c,u,t,f,n,a),a},[e,n,t,c,f,u,w,T]),k=LD(e,c,u,t,f,n),A=v?JSON.stringify([k,w,T]):k,j=v?null:RD(e,c,u,t,f,n),M=uo(A,[e,n,t,c,f,u,w,T],O,{isEmpty:()=>!1,initialData:j??void 0}),{state:N}=M,P=N.data??j??null,F=(0,Z.useMemo)(()=>ED(P?.days??[],!!v),[P?.days,v]),I=(0,Z.useMemo)(()=>yD(P?.days??[]),[P?.days]),L=(0,Z.useMemo)(()=>(P?.days??[]).filter(e=>e.requests>0).length,[P?.days]),R=(0,Z.useMemo)(()=>{let e=m.trim().toLowerCase(),t=(P?.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)},[P?.models,m]),z=(0,Z.useMemo)(()=>(P?.providers??[]).toSorted((e,t)=>t.totalTokens-e.totalTokens),[P?.providers]);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`page-head usage-head`,children:[(0,Q.jsx)(`h2`,{id:`usage-page-title`,children:i(`usage.title`)}),o===`report`&&(0,Q.jsx)(DD,{surface:u,range:v?null:c,onSurface:d,onRange:D,t:i})]}),(0,Q.jsx)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":i(`nav.usage`),children:[`report`,`companion`].map(e=>(0,Q.jsx)(`button`,{type:`button`,role:`tab`,id:`usage-tab-${e}`,"aria-selected":o===e,"aria-controls":`usage-panel-${e}`,tabIndex:o===e?0:-1,className:`page-tab${o===e?` page-tab--active`:``}`,onClick:()=>cD(e),onKeyDown:lD,children:i(e===`report`?`usage.workspace.report`:`usage.section.companion`)},e))}),o===`companion`?(0,Q.jsx)(`div`,{role:`tabpanel`,id:`usage-panel-companion`,"aria-labelledby":`usage-tab-companion`,children:(0,Q.jsx)(oD,{apiBase:e,providers:P?.providers??[]})}):(0,Q.jsxs)(`div`,{role:`tabpanel`,id:`usage-panel-report`,"aria-labelledby":`usage-tab-report`,children:[(0,Q.jsx)(`p`,{className:`page-sub`,children:i(`usage.subtitle`)}),(0,Q.jsxs)(`section`,{className:`usage-range`,children:[(0,Q.jsxs)(`div`,{className:`usage-range-bar`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`usage-range-toggle${v?` is-active`:``}`,"aria-expanded":S,"aria-controls":S?`usage-range-panel`:void 0,onClick:()=>{S&&x(null),C(!S)},children:[(0,Q.jsx)(`span`,{children:i(`usage.range.custom`)}),(0,Q.jsx)(Ye,{width:12,height:12,"aria-hidden":`true`,className:`usage-range-chevron`})]}),v&&(0,Q.jsx)(`p`,{className:`usage-range-applied muted text-control`,role:`status`,children:(()=>{let e=new Intl.DateTimeFormat(a,{year:`numeric`,month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,fractionalSecondDigits:3,timeZoneName:`short`});return i(`usage.range.applied`,{start:e.format(v.since),end:e.format(v.until)})})()})]}),S&&(0,Q.jsxs)(`form`,{id:`usage-range-panel`,className:`usage-range-panel`,"aria-label":i(`usage.range.custom`),noValidate:!0,onSubmit:e=>{e.preventDefault();let t=zE(g.since,g.until);t.ok===!1?x(t.error):(x(null),y(t.window))},children:[(0,Q.jsxs)(`div`,{className:`usage-range-fields`,children:[(0,Q.jsxs)(`label`,{className:`usage-range-field`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:i(`usage.range.start`)}),(0,Q.jsx)(`input`,{className:`input`,type:`datetime-local`,step:`60`,required:!0,value:g.since,"aria-invalid":b!==null,"aria-describedby":b?`usage-range-help usage-range-error`:`usage-range-help`,onChange:e=>{let t=e.currentTarget.value;_(e=>({...e,since:t})),x(null)}})]}),(0,Q.jsxs)(`label`,{className:`usage-range-field`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:i(`usage.range.end`)}),(0,Q.jsx)(`input`,{className:`input`,type:`datetime-local`,step:`60`,required:!0,value:g.until,"aria-invalid":b!==null,"aria-describedby":b?`usage-range-help usage-range-error`:`usage-range-help`,onChange:e=>{let t=e.currentTarget.value;_(e=>({...e,until:t})),x(null)}})]}),(0,Q.jsx)(`button`,{type:`submit`,className:`btn btn-primary btn-sm usage-range-action`,children:i(`usage.range.apply`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm usage-range-action`,onClick:E,children:i(`usage.range.clear`)})]}),(0,Q.jsx)(`p`,{id:`usage-range-help`,className:`muted text-caption`,children:i(`usage.range.help`)}),b&&(0,Q.jsx)(`p`,{id:`usage-range-error`,role:`alert`,className:`notice notice-err`,children:i(`usage.range.${b}`)})]})]}),t&&(0,Q.jsxs)(`div`,{className:`usage-source-row`,children:[(0,Q.jsx)(`span`,{children:i(`usage.source.connected`)}),(0,Q.jsxs)(`div`,{className:`usage-scope-control`,role:`group`,"aria-label":i(`usage.scope.label`),children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm${f===`machine`?` btn-primary`:` btn-ghost`}`,"aria-pressed":f===`machine`,onClick:()=>p(`machine`),children:i(`usage.scope.machine`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm${f===`hub`?` btn-primary`:` btn-ghost`}`,"aria-pressed":f===`hub`,onClick:()=>p(`hub`),children:i(`usage.scope.hub`)})]})]}),N.showSkeleton&&!P?(0,Q.jsx)(lb,{label:i(`usage.loading`),rows:5}):N.kind===`failed-cold`?(0,Q.jsxs)($,{tone:`err`,children:[N.error instanceof uD?`${i(`usage.loadError`)} ${i(`dash.codexRestartMalformed`)}`:N.error instanceof yr?i(`usage.loadError`):t?i(`usage.hubOffline`):N.error instanceof Error?`${i(`usage.loadError`)} ${N.error.message}`:i(`usage.loadError`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>M.refresh(),children:i(`common.retry`)})]}):(0,Q.jsxs)(Q.Fragment,{children:[N.showError&&(0,Q.jsx)($,{tone:`err`,children:i(t&&!(N.error instanceof yr)?`usage.hubOffline`:`usage.loadError`)}),(0,Q.jsx)(Sr,{data:P}),P?.historyTruncated&&(0,Q.jsx)($,{tone:`warn`,children:(()=>{let e=VD(P.snapshotWindowStart),t=VD(P.snapshotWindowEnd);return e!==null&&t!==null?i(`usage.historyTruncatedWindow`,{start:e,end:t}):i(`usage.historyTruncated`)})()}),(0,Q.jsx)(FD,{data:P,heatmap:F,weekBars:I,activeDays:L,filteredModels:R,modelQuery:m,onModelQuery:h,sortedProviders:z,range:v?null:c,locale:a,t:i})]})]})]})}function VD(e){if(typeof e!=`number`||!Number.isFinite(e))return null;let t=new Date(e);return Number.isFinite(t.getTime())?t.toLocaleString():null}function HD(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 UD={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.`},vi:{compact:`Nén`,compactComplete:`Hoàn tất nén (logic / thu hồi trên đĩa)`,pagesUnit:`trang`,compactPartial:`Nén một phần (logic / thu hồi trên đĩa)`,confirmCompact:`Xác nhận nén`,cancel:`Hủy`,inspectionOnly:`Chỉ kiểm tra`,externalSqliteHome:`Lưu trữ SQLite bên ngoài`,inspectionUnavailable:`Tính năng kiểm tra nhật ký chẩn đoán không khả dụng.`,metricsSkippedLarge:`Đã bỏ qua số liệu hàng: cơ sở dữ liệu lớn hơn {threshold} và việc quét sẽ làm treo proxy.`,protection:`Bảo vệ`,compat:`Tương thích`,quiet:`Yên tĩnh`,disable:`Tắt bảo vệ`,repair:`Sửa chữa bảo vệ`,applying:`Đang áp dụng bảo vệ…`,"error.generic":`Không thể thay đổi bảo vệ nhật ký Codex.`,"error.codex_running":`Hãy thoát Codex trước khi thay đổi bảo vệ nhật ký.`,"error.process_enumeration_failed":`Không thể xác minh rằng Codex đã dừng. Bảo vệ chưa được thay đổi.`,"error.busy":`Cơ sở dữ liệu nhật ký Codex đang bận. Hãy thoát Codex và thử lại.`,"error.unsupported_schema":`Lược đồ nhật ký Codex này không được hỗ trợ để bảo vệ.`,"error.trigger_collision":`Tên trình kích hoạt Log Guard dành riêng đã được sử dụng. Bảo vệ chưa được thay đổi.`,"error.unsafe_path":`Đường dẫn cơ sở dữ liệu nhật ký Codex không vượt qua được kiểm tra an toàn.`,"error.database_error":`Không thể cập nhật cơ sở dữ liệu nhật ký Codex.`,"error.config_write_failed":`Cơ sở dữ liệu đã thay đổi nhưng OpenCodex không thể lưu cài đặt bảo vệ. Vui lòng sửa lỗi lưu trữ cấu hình, sau đó chạy Sửa chữa.`},pt:{compact:`Compactar`,compactComplete:`Compactação concluída (lógico / recuperado em disco)`,pagesUnit:`páginas`,compactPartial:`Compactação parcial (lógico / recuperado em disco)`,confirmCompact:`Confirmar compactação`,cancel:`Cancelar`,inspectionOnly:`Somente inspeção`,externalSqliteHome:`Armazenamento SQLite externo`,inspectionUnavailable:`A inspeção do log de diagnóstico não está disponível.`,metricsSkippedLarge:`Métricas de linhas ignoradas: o banco de dados excede {threshold} e a varredura travaria o proxy.`,protection:`Proteção`,compat:`Compatibilidade`,quiet:`Silencioso`,disable:`Desativar proteção`,repair:`Reparar proteção`,applying:`Aplicando proteção…`,"error.generic":`Não foi possível alterar a proteção de logs do Codex.`,"error.codex_running":`Feche o Codex antes de alterar a proteção de logs.`,"error.process_enumeration_failed":`Não foi possível verificar se o Codex está parado. A proteção não foi alterada.`,"error.busy":`O banco de dados de logs do Codex está ocupado. Feche o Codex e tente novamente.`,"error.unsupported_schema":`Este esquema de logs do Codex não é suportado para proteção.`,"error.trigger_collision":`Um nome de trigger reservado do Log Guard já está em uso. A proteção não foi alterada.`,"error.unsafe_path":`O caminho do banco de dados de logs do Codex falhou na verificação de segurança.`,"error.database_error":`Não foi possível atualizar o banco de dados de logs do Codex.`,"error.config_write_failed":`O banco de dados foi alterado, mas o OpenCodex não conseguiu salvar a configuração de proteção. Corrija o armazenamento de configuração e execute Reparar.`}};function WD(e,t){return UD[e][t]}var GD={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.`},vi:{applying:`Đang áp dụng thay đổi Log Guard…`,"error.generic":`Không thể cập nhật lưu trữ nhật ký Codex.`,"error.codex_running":`Hãy thoát Codex trước khi thay đổi lưu trữ nhật ký Codex.`,"error.process_enumeration_failed":`Không thể xác minh rằng Codex đã dừng. Thao tác Log Guard chưa được bắt đầu.`,"error.busy":`Cơ sở dữ liệu nhật ký Codex đang bận. Hãy thoát Codex và thử lại.`,"error.unsupported_schema":`Lược đồ nhật ký Codex này không được hỗ trợ cho thao tác này.`,"error.unsafe_path":`Đường dẫn cơ sở dữ liệu nhật ký Codex không vượt qua được kiểm tra an toàn.`,"error.database_error":`Không thể cập nhật cơ sở dữ liệu nhật ký Codex.`,"error.auto_vacuum_not_incremental":`Cơ sở dữ liệu nhật ký Codex này không được định cấu hình cho tính năng incremental vacuum, do đó không thể thu hồi dung lượng nếu không xây dựng lại hoàn toàn.`,"error.integrity_check_failed":`Cơ sở dữ liệu nhật ký Codex không vượt qua được kiểm tra tính toàn vẹn. Không có dung lượng nào được thu hồi.`},pt:{applying:`Aplicando alteração do Log Guard…`,"error.generic":`Não foi possível atualizar o armazenamento de logs do Codex.`,"error.codex_running":`Feche o Codex antes de alterar o armazenamento de logs do Codex.`,"error.process_enumeration_failed":`Não foi possível verificar se o Codex está parado. A operação do Log Guard não foi iniciada.`,"error.busy":`O banco de dados de logs do Codex está ocupado. Feche o Codex e tente novamente.`,"error.unsupported_schema":`Este esquema de logs do Codex não é suportado para esta operação.`,"error.unsafe_path":`O caminho do banco de dados de logs do Codex falhou na verificação de segurança.`,"error.database_error":`Não foi possível atualizar o banco de dados de logs do Codex.`,"error.auto_vacuum_not_incremental":`Este banco de dados de logs do Codex não está configurado para incremental vacuum; por isso, não é possível recuperar espaço sem uma reconstrução completa.`,"error.integrity_check_failed":`O banco de dados de logs do Codex falhou na verificação de integridade. Nenhum espaço foi recuperado.`}};function KD(e,t){return GD[e][t]}var qD={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`}},vi:{schema:{compatible:`Tương thích`,missing:`Không tìm thấy cơ sở dữ liệu`,unreadable:`Cơ sở dữ liệu không khả dụng`,unsupported:`Không được hỗ trợ`},protection:{off:`Tắt`,active:`Đang hoạt động`,drifted:`Cần sửa chữa`,unsupported:`Không được hỗ trợ`,unknown:`Không xác định`},mode:{off:`Tắt`,compat:`Tương thích`,quiet:`Yên tĩnh`,collision:`Không xác định`}},pt:{schema:{compatible:`Compatível`,missing:`Banco de dados não encontrado`,unreadable:`Banco de dados indisponível`,unsupported:`Não suportado`},protection:{off:`Desativada`,active:`Ativa`,drifted:`Requer reparo`,unsupported:`Não suportada`,unknown:`Desconhecida`},mode:{off:`Desativado`,compat:`Compatibilidade`,quiet:`Silencioso`,collision:`Desconhecido`}}};function JD(e,t){return qD[e].schema[t]}function YD(e,t){return qD[e].protection[t]}function XD(e,t){return qD[e].mode[t]}var ZD={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 QD(e,t){let n=ZD[e.key];return n?t(n):e.label}function $D(e,t){return e===void 0?`—`:new Date(e).toLocaleDateString(t)}function eO(e,t,n){return e.rows===void 0?`—`:e.rows===null?n(`storage.rows.unknown`):e.rows.toLocaleString(t)}function tO(e,t){switch(t){case`codex_running`:return KD(e,`error.codex_running`);case`process_enumeration_failed`:return KD(e,`error.process_enumeration_failed`);case`busy`:return KD(e,`error.busy`);case`unsupported_schema`:return KD(e,`error.unsupported_schema`);case`trigger_collision`:return WD(e,`error.trigger_collision`);case`unsafe_path`:return KD(e,`error.unsafe_path`);case`database_error`:return KD(e,`error.database_error`);case`auto_vacuum_not_incremental`:return KD(e,`error.auto_vacuum_not_incremental`);case`integrity_check_failed`:return KD(e,`error.integrity_check_failed`);case`config_write_failed`:return WD(e,`error.config_write_failed`);default:return KD(e,`error.generic`)}}function nO({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,Z.useState)(!1);return(0,Q.jsxs)(`div`,{className:`stw-section`,"data-testid":`codex-log-guard`,children:[(0,Q.jsx)(`h3`,{className:`stw-section-title`,children:n(`storage.bucket.logs_db`)}),(0,Q.jsxs)(`dl`,{className:`stw-kv`,children:[(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:n(`dash.status`)}),(0,Q.jsxs)(`dd`,{className:`stw-kv-mono`,children:[(0,Q.jsx)(`code`,{children:JD(t,e.schema.state)}),c&&e.schema.state===`unsupported`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:` · `}),(0,Q.jsx)(`code`,{children:WD(t,`inspectionOnly`)})]}):null]})]}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:n(`storage.bucket.logs_db`)}),(0,Q.jsx)(`dd`,{className:`stw-kv-mono`,children:HD(e.files.databaseBytes,t)})]}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:(0,Q.jsx)(`code`,{children:`WAL`})}),(0,Q.jsx)(`dd`,{className:`stw-kv-mono`,children:HD(e.files.walBytes,t)})]}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:(0,Q.jsx)(`code`,{children:`SHM`})}),(0,Q.jsx)(`dd`,{className:`stw-kv-mono`,children:HD(e.files.shmBytes,t)})]}),s&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:n(`storage.col.rows`)}),(0,Q.jsx)(`dd`,{className:`stw-kv-mono`,children:s.totalRows.toLocaleString(t)})]}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:(0,Q.jsx)(`code`,{children:`TRACE`})}),(0,Q.jsxs)(`dd`,{className:`stw-kv-mono`,children:[(s.traceShare*100).toFixed(1),`%`]})]}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:(0,Q.jsx)(`code`,{children:`freelist`})}),(0,Q.jsx)(`dd`,{className:`stw-kv-mono`,children:HD(s.reclaimableBytes,t)})]})]}),!s&&e.metricsSkipped&&(0,Q.jsxs)(`div`,{className:`stw-kv-row`,"data-testid":`log-guard-metrics-skipped`,children:[(0,Q.jsx)(`dt`,{children:n(`storage.col.rows`)}),(0,Q.jsx)(`dd`,{className:`muted`,children:WD(t,`metricsSkippedLarge`).replace(`{threshold}`,HD(e.metricsSkipped.thresholdBytes,t))})]}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:(0,Q.jsx)(`code`,{children:`sqlite_home`})}),(0,Q.jsx)(`dd`,{className:`stw-kv-mono`,children:(0,Q.jsx)(`code`,{children:e.externalSqliteHome?WD(t,`externalSqliteHome`):`CODEX_HOME`})})]})]}),l&&(0,Q.jsxs)(`div`,{className:`stw-section`,"data-testid":`log-guard-protection`,children:[(0,Q.jsx)(`h4`,{className:`stw-section-title`,children:WD(t,`protection`)}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:(0,Q.jsx)(`code`,{children:YD(t,l.state)})}),(0,Q.jsxs)(`span`,{className:`stw-kv-mono`,children:[(0,Q.jsx)(`code`,{children:XD(t,l.desiredMode)}),l.observedMode===l.desiredMode?null:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:` · `}),(0,Q.jsx)(`code`,{children:XD(t,l.observedMode)})]})]})]}),(0,Q.jsxs)(`div`,{className:`storage-policy-actions`,children:[(0,Q.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:WD(t,`compat`)}),(0,Q.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:WD(t,`quiet`)}),(0,Q.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:WD(t,`disable`)}),l.state===`drifted`&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,"data-testid":`log-guard-repair`,disabled:u,onClick:()=>o({action:`repair`}),children:WD(t,`repair`)}),r&&(0,Q.jsx)(`span`,{className:`muted`,role:`status`,children:KD(t,`applying`)})]}),i&&(0,Q.jsx)(`p`,{className:`err`,role:`alert`,children:i})]}),d&&(0,Q.jsx)(`div`,{className:`stw-section`,"data-testid":`log-guard-reclaim`,children:(0,Q.jsx)(`div`,{className:`storage-policy-actions`,children:f?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,"data-testid":`log-guard-compact-confirm`,disabled:r,onClick:()=>{p(!1),o({action:`compact`})},children:WD(t,`confirmCompact`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:r,onClick:()=>p(!1),children:WD(t,`cancel`)})]}):(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"data-testid":`log-guard-compact`,disabled:r,onClick:()=>p(!0),children:WD(t,`compact`)})})}),a&&(0,Q.jsx)(`div`,{className:`stw-section`,children:(0,Q.jsx)(`p`,{className:`stw-kv-mono`,role:`status`,"data-testid":`log-guard-compact-result`,children:a})}),s&&s.topTargets.length>0&&(0,Q.jsxs)(`div`,{className:`stw-section`,children:[(0,Q.jsx)(`h4`,{className:`stw-section-title`,children:(0,Q.jsx)(`code`,{children:`target`})}),s.topTargets.slice(0,5).map(e=>(0,Q.jsxs)(`div`,{className:`stw-file-row`,children:[(0,Q.jsx)(`span`,{className:`stw-file-path`,title:e.target,children:(0,Q.jsx)(`code`,{children:e.target})}),(0,Q.jsx)(`span`,{className:`stw-file-size`,children:e.rows.toLocaleString(t)})]},e.target))]}),(0,Q.jsx)(`p`,{className:`stw-hint`,children:(0,Q.jsxs)(`code`,{children:[`immutable=1 · snapshot=`,e.snapshot]})})]})}function rO({locale:e,t}){return(0,Q.jsxs)(`div`,{className:`stw-section`,"data-testid":`codex-log-guard-unavailable`,children:[(0,Q.jsx)(`h3`,{className:`stw-section-title`,children:t(`storage.bucket.logs_db`)}),(0,Q.jsx)(`p`,{className:`stw-hint`,children:WD(e,`inspectionUnavailable`)})]})}function iO({report:e,locale:t,apiBase:r=``,logGuardBusy:i=!1,onLogGuardAction:a}){let o=n(),[s,c]=(0,Z.useState)(null),[l,u]=(0,Z.useState)(null),[d,f]=(0,Z.useState)(!1),[p,m]=(0,Z.useState)(null),[h,g]=(0,Z.useState)(null),_=(0,Z.useMemo)(()=>e.buckets.toSorted((e,t)=>t.bytes-e.bytes),[e.buckets]),v=_.find(e=>e.key===s)??null,y=l?.generation===e.generatedAt?l.report:e.codexLogs??null,b=p?.generation===e.generatedAt?p.message:null,x=h?.generation===e.generatedAt?h.summary:null,S=i||d,C=(0,Z.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,Z.useMemo)(()=>new Map(e.buckets.map(e=>[e.key,e])),[e.buckets]);return(0,Q.jsxs)(`div`,{className:`storage-workspace-root`,children:[(0,Q.jsxs)(`aside`,{className:`storage-workspace-rail`,"aria-label":o(`storage.section.buckets`),children:[(0,Q.jsxs)(`div`,{className:`storage-workspace-rail-header`,children:[(0,Q.jsx)(`span`,{className:`storage-workspace-rail-title`,children:o(`storage.section.buckets`)}),(0,Q.jsx)(`span`,{className:`storage-workspace-rail-count`,children:_.length})]}),(0,Q.jsx)(`div`,{className:`storage-workspace-rail-list`,children:_.length===0?(0,Q.jsx)(`span`,{className:`storage-workspace-rail-empty`,children:o(`storage.empty`)}):_.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`storage-workspace-rail-row${s===e.key?` storage-workspace-rail-row--selected`:``}`,onClick:()=>c(t=>t===e.key?null:e.key),"aria-current":s===e.key?`true`:void 0,children:[(0,Q.jsxs)(`span`,{className:`storage-workspace-rail-primary`,children:[(0,Q.jsx)(`span`,{className:`storage-workspace-rail-name`,children:QD(e,o)}),(0,Q.jsx)(`span`,{className:`storage-workspace-rail-size`,children:HD(e.bytes,t)})]}),(0,Q.jsxs)(`span`,{className:`storage-workspace-rail-meta`,children:[e.fileCount.toLocaleString(t),` `,o(`storage.col.files`).toLowerCase()]})]},e.key))})]}),(0,Q.jsx)(`section`,{className:`storage-workspace-main`,"aria-label":v?QD(v,o):o(`storage.section.largest`),children:v?(0,Q.jsxs)(`div`,{className:`stw-detail`,children:[(0,Q.jsx)(`div`,{className:`stw-detail-toolbar`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`stw-detail-back`,onClick:()=>c(null),children:[(0,Q.jsx)(Ye,{className:`stw-detail-back-chevron`,"aria-hidden":`true`}),o(`modal.back`)]})}),(0,Q.jsxs)(`div`,{className:`stw-detail-body`,children:[(0,Q.jsx)(`h2`,{className:`stw-detail-title`,children:QD(v,o)}),(0,Q.jsxs)(`dl`,{className:`stw-kv`,children:[(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:o(`storage.col.size`)}),(0,Q.jsx)(`dd`,{className:`stw-kv-mono`,children:HD(v.bytes,t)})]}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:o(`storage.col.files`)}),(0,Q.jsx)(`dd`,{className:`stw-kv-mono`,children:v.fileCount.toLocaleString(t)})]}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:o(`storage.col.oldest`)}),(0,Q.jsx)(`dd`,{children:$D(v.oldest,t)})]}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:o(`storage.col.newest`)}),(0,Q.jsx)(`dd`,{children:$D(v.newest,t)})]}),(0,Q.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,Q.jsx)(`dt`,{children:o(`storage.col.rows`)}),(0,Q.jsx)(`dd`,{className:`stw-kv-mono`,children:eO(v,t,o)})]})]}),(v.largest?.length??0)>0&&(0,Q.jsxs)(`div`,{className:`stw-section`,children:[(0,Q.jsx)(`h3`,{className:`stw-section-title`,children:o(`storage.section.largest`)}),v.largest.map(e=>(0,Q.jsxs)(`div`,{className:`stw-file-row`,children:[(0,Q.jsx)(`span`,{className:`stw-file-path`,title:e.path,children:e.path}),(0,Q.jsx)(`span`,{className:`stw-file-size`,children:HD(e.bytes,t)})]},e.path))]})]})]}):(0,Q.jsxs)(`div`,{className:`stw-overview`,children:[(0,Q.jsxs)(`div`,{className:`stw-summary`,children:[(0,Q.jsxs)(`div`,{className:`stw-summary-card`,children:[(0,Q.jsx)(`div`,{className:`stw-summary-label`,children:o(`storage.card.total`)}),(0,Q.jsx)(`div`,{className:`stw-summary-value`,children:HD(e.total.bytes,t)})]}),(0,Q.jsxs)(`div`,{className:`stw-summary-card`,children:[(0,Q.jsx)(`div`,{className:`stw-summary-label`,children:o(`storage.card.files`)}),(0,Q.jsx)(`div`,{className:`stw-summary-value`,children:e.total.fileCount.toLocaleString(t)})]}),(0,Q.jsxs)(`div`,{className:`stw-summary-card`,children:[(0,Q.jsx)(`div`,{className:`stw-summary-label`,children:o(`storage.card.home`)}),(0,Q.jsx)(`div`,{className:`stw-summary-value mono stw-home-path`,title:e.codexHome,children:e.codexHome})]})]}),y?(0,Q.jsx)(nO,{report:y,locale:t,t:o,busy:S,error:b,compaction:x,onAction:n=>{if(a){a(n);return}if(d)return;let i=e.generatedAt;(async()=>{f(!0),m(null),n.action===`compact`&&g(null);try{let e=n.action===`protect`?`protect`:n.action,a={method:`POST`,...n.action===`protect`?{headers:{"content-type":`application/json`},body:JSON.stringify({mode:n.mode})}:{}},o=await fetch(`${r}/api/storage/codex-logs/${e}`,a);if(!o.ok){let e=await o.json().catch(()=>({}));m({generation:i,message:tO(t,e.error)});return}if(n.action===`compact`){let e=(await o.json().catch(()=>null))?.report;if(e){let n=HD(e.logicalBytesReclaimed??0,t),r=HD(e.physicalDatabaseBytesReclaimed??0,t),a=e.complete?WD(t,`compactComplete`):WD(t,`compactPartial`),o=e.pagesReclaimed??0,s=!e.complete&&e.stopReason?` (${e.stopReason})`:``;g({generation:i,summary:[`${a}${s}`,`${o.toLocaleString(t)} ${WD(t,`pagesUnit`)}`,`${n} / ${r}`].join(` — `)})}try{let e=await fetch(`${r}/api/storage/codex-logs`);if(e.ok){let t=await e.json();u({generation:i,report:t})}}catch{}return}let s=await o.json();u({generation:i,report:s})}catch{m({generation:i,message:KD(t,`error.generic`)})}finally{f(!1)}})()}}):e.codexLogsError===`inspect_failed`?(0,Q.jsx)(rO,{locale:t,t:o}):null,C.length>0?(0,Q.jsxs)(`div`,{className:`stw-section`,children:[(0,Q.jsx)(`h3`,{className:`stw-section-title`,children:o(`storage.section.largest`)}),C.map(e=>{let n=w.get(e.bucketKey);return(0,Q.jsxs)(`div`,{className:`stw-file-row`,children:[(0,Q.jsx)(`span`,{className:`stw-file-path`,title:e.path,children:e.path}),n&&(0,Q.jsx)(`span`,{className:`stw-file-bucket`,children:QD(n,o)}),(0,Q.jsx)(`span`,{className:`stw-file-size`,children:HD(e.bytes,t)})]},`${e.bucketKey}:${e.path}`)})]}):(0,Q.jsxs)(`p`,{className:`stw-hint`,children:[(0,Q.jsx)(Ie,{style:{width:14,height:14,verticalAlign:`text-bottom`,marginRight:6},"aria-hidden":`true`}),o(`storage.workspace.selectBucket`)]})]})})]})}var aO=1024**3,oO=[10,25,50],sO=(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 cO({apiBase:e,locale:t,t:n,onDone:r}){let[i,a]=(0,Z.useState)(25),[o,s]=(0,Z.useState)(null),[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(!1),[m,h]=(0,Z.useState)(null),[g,_]=(0,Z.useState)(null),v=(0,Z.useRef)(null),y=(0,Z.useRef)(null),b=(0,Z.useRef)(!1),x=(0,Z.useCallback)((e=!1)=>{l(!1),d(!1),e&&s(null)},[]);(0,Z.useEffect)(()=>{b.current=f},[f]),(0,Z.useEffect)(()=>{if(!c)return;y.current=document.activeElement,v.current?.focus();let e=e=>{e.key===`Escape`&&!b.current&&x()};return window.addEventListener(`keydown`,e),()=>{window.removeEventListener(`keydown`,e),y.current?.focus()}},[c,x]);let S=(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`)}},C=e=>n(`storage.cleanup.preset`,{percent:new Intl.NumberFormat(t,{style:`percent`,maximumFractionDigits:0}).format(e/100)}),w=async()=>{p(!0),_(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(S(e.error,n(`storage.cleanup.previewFailed`)))}let r=await t.json();s(r),l(!0)}catch(e){_(sO(e,n(`storage.cleanup.previewFailed`)))}finally{p(!1)}},T=async()=>{if(o){p(!0),_(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`&&x(!0),Error(S(e.error,e.message,e.trashDir))}let a=await i.json();if(!a.ok)throw a.error===`stale_preview`&&x(!0),Error(S(a.error,a.message,a.trashDir));x(!0);let s=n(u?`storage.cleanup.donePermanent`:`storage.cleanup.doneQuarantine`,{count:String(a.count),size:HD(a.bytes,t)});h(a.skippedReferencedPaths?.length?`${s} ${n(`storage.cleanup.skippedReferenced`,{count:String(a.skippedReferencedPaths.length)})}`:s),r()}catch(e){_(sO(e,n(`storage.cleanup.cleanupFailed`)))}finally{p(!1)}}};return(0,Q.jsxs)(`section`,{className:`storage-cleanup-pane`,children:[(0,Q.jsx)(`p`,{className:`muted storage-manual-panel__help`,children:n(`storage.cleanup.help`)}),(0,Q.jsxs)(`div`,{className:`storage-manual-panel__controls`,children:[(0,Q.jsxs)(`label`,{className:`storage-manual-panel__slider`,children:[(0,Q.jsx)(`span`,{className:`muted mono`,style:{minWidth:`3.5rem`,fontVariantNumeric:`tabular-nums`},children:n(`storage.cleanup.percent`,{percent:String(i)})}),(0,Q.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,Q.jsx)(`div`,{className:`storage-manual-panel__presets`,children:oO.map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm${i===e?` active`:``}`,disabled:f,onClick:()=>a(e),children:C(e)},e))}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:f,onClick:()=>void w(),children:n(`storage.cleanup.preview`)})]}),m&&(0,Q.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:m}),g&&!c&&(0,Q.jsx)(`p`,{className:`storage-manual-panel__status`,style:{color:`var(--red)`},children:g}),c&&o&&(0,Q.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`storage-cleanup-confirm-title`,onClick:()=>!f&&x(),children:(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsx)(`h3`,{id:`storage-cleanup-confirm-title`,children:n(`storage.cleanup.confirmTitle`)}),(0,Q.jsx)(`p`,{children:n(`storage.cleanup.confirmBody`,{count:String(o.count),size:HD(o.bytes,t),percent:String(o.percent)})}),o.candidates.length>0&&(0,Q.jsxs)(`ul`,{className:`mono muted`,style:{maxHeight:160,overflow:`auto`,fontSize:`var(--text-caption)`},children:[o.candidates.slice(0,8).map(e=>(0,Q.jsx)(`li`,{children:e.relPath},e.relPath)),o.count>8&&(0,Q.jsx)(`li`,{children:n(`storage.cleanup.moreFiles`,{n:String(Math.max(0,o.count-8))})})]}),(0,Q.jsxs)(`label`,{style:{display:`flex`,gap:8,alignItems:`center`,marginTop:12},children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:u,disabled:f,onChange:e=>d(e.target.checked)}),(0,Q.jsx)(`span`,{children:n(`storage.cleanup.permanent`)})]}),(0,Q.jsx)(`p`,{className:`muted`,style:{marginTop:8,fontSize:`var(--text-caption)`},children:n(u?`storage.cleanup.permanentWarn`:`storage.cleanup.quarantineNote`)}),g&&(0,Q.jsx)(`p`,{style:{marginTop:12,color:`var(--red)`},children:g}),(0,Q.jsxs)(`div`,{className:`dialog-actions`,style:{marginTop:16},children:[(0,Q.jsx)(`button`,{ref:v,type:`button`,className:`btn btn-ghost`,disabled:f,onClick:()=>x(),children:n(`storage.cleanup.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:u?`btn btn-danger`:`btn`,disabled:f||o.count===0,onClick:()=>void T(),children:n(u?`storage.cleanup.confirmPermanent`:`storage.cleanup.confirmQuarantine`)})]})]})})]})}function lO({apiBase:e,locale:t,t:n,onDone:r,reloadToken:i,onEntriesChange:a}){let[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(null),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)(null),m=(0,Z.useRef)(null),h=(0,Z.useRef)(null),g=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>{g.current=o},[o]);let _=(0,Z.useCallback)(()=>l(null),[]);(0,Z.useEffect)(()=>{if(!c)return;h.current=document.activeElement,m.current?.focus();let e=e=>{e.key===`Escape`&&!g.current&&_()};return window.addEventListener(`keydown`,e),()=>{window.removeEventListener(`keydown`,e),h.current?.focus()}},[c,_]);let v=(0,Z.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]),y=uo(`storage-trash:${e}`,[e,i],v,{isEmpty:e=>e.length===0}).state,b=y.data??[],x=(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`)}},S=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(x(e.error,e.message))}let a=await i.json();if(!a.ok)throw Error(x(a.error,a.message));_(),d(n(`storage.trash.done`,{count:String(a.count),size:HD(a.bytes,t)})),r()}catch(e){p(sO(e,n(`storage.trash.restoreFailed`)))}finally{s(!1)}}},C=e=>{let n=e.quarantinedAt??Number(e.epoch.split(`-`)[0]);return!Number.isFinite(n)||n<=0?`—`:new Date(n).toLocaleString(t)},w=e=>e===`permanent`?n(`storage.trash.mode.permanent`):e===`quarantine`?n(`storage.trash.mode.quarantine`):`—`;return(0,Q.jsxs)(`section`,{className:`storage-cleanup-pane storage-quarantine-pane`,children:[(0,Q.jsx)(`p`,{className:`muted storage-manual-panel__help`,children:n(`storage.trash.help`)}),u&&(0,Q.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:u}),f&&!c&&(0,Q.jsx)(`p`,{className:`storage-manual-panel__status`,style:{color:`var(--red)`},role:`alert`,children:f}),y.showError&&!c&&(0,Q.jsx)(`p`,{className:`storage-manual-panel__status`,style:{color:`var(--red)`},role:`alert`,children:y.error instanceof Error?y.error.message:n(`storage.trash.listFailed`)}),y.refreshing&&!y.showSkeleton&&(0,Q.jsx)(ub,{live:!y.showError,children:n(`storage.trash.loading`)}),y.showSkeleton?(0,Q.jsx)(lb,{label:n(`storage.trash.loading`),rows:2}):b.length===0?(0,Q.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.trash.empty`)}):(0,Q.jsx)(`div`,{className:`tbl-wrap storage-manual-panel__table`,children:(0,Q.jsxs)(`table`,{className:`tbl`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:n(`storage.trash.col.when`)}),(0,Q.jsx)(`th`,{className:`num`,children:n(`storage.trash.col.files`)}),(0,Q.jsx)(`th`,{className:`num`,children:n(`storage.trash.col.size`)}),(0,Q.jsx)(`th`,{children:n(`storage.trash.col.mode`)}),(0,Q.jsx)(`th`,{children:n(`storage.trash.col.id`)}),(0,Q.jsx)(`th`,{})]})}),(0,Q.jsx)(`tbody`,{children:b.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`muted`,children:C(e)}),(0,Q.jsx)(`td`,{className:`num`,children:e.fileCount}),(0,Q.jsx)(`td`,{className:`num mono`,children:HD(e.bytes,t)}),(0,Q.jsx)(`td`,{className:`muted`,children:w(e.mode)}),(0,Q.jsx)(`td`,{className:`mono`,style:{fontSize:`var(--text-caption)`},children:e.id}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:o,onClick:()=>{p(null),l(e)},children:n(`storage.trash.restore`)})})]},e.id))})]})}),c&&(0,Q.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`storage-trash-confirm-title`,onClick:()=>!o&&_(),children:(0,Q.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsx)(`h3`,{id:`storage-trash-confirm-title`,children:n(`storage.trash.confirmTitle`)}),(0,Q.jsx)(`p`,{children:n(`storage.trash.confirmBody`,{count:String(c.fileCount),size:HD(c.bytes,t),id:c.id})}),f&&(0,Q.jsx)(`p`,{style:{marginTop:12,color:`var(--red)`},children:f}),(0,Q.jsxs)(`div`,{className:`dialog-actions`,style:{marginTop:16},children:[(0,Q.jsx)(`button`,{ref:m,type:`button`,className:`btn btn-ghost`,disabled:o,onClick:()=>_(),children:n(`storage.trash.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn`,disabled:o,onClick:()=>void S(),children:n(`storage.trash.confirmRestore`)})]})]})})]})}function uO(e){let{job:t,...n}=e;return n}function dO(e){let t=String(Math.max(0,Math.round(e.trigger.archivedBytesOver/aO*100)/100));return e.target.reduceToBytes===void 0?{policy:uO(e),thresholdGb:t,targetMode:`percent`,percent:String(Math.min(100,Math.max(1,Math.floor(e.target.removeOldestPercent??25)))),reduceGb:`4`}:{policy:uO(e),thresholdGb:t,targetMode:`reduce`,percent:`25`,reduceGb:String(Math.max(0,Math.round(e.target.reduceToBytes/aO*100)/100))}}async function fO(e){await new Promise(t=>window.setTimeout(t,e))}function pO({apiBase:e,locale:t,t:n,onDone:r}){let i=`ocx.storage.cleanup-policy.v1:${e}`,a=io(i),o=(0,Z.useRef)(!!a),[s,c]=(0,Z.useState)(()=>a?.policy??null),[l,u]=(0,Z.useState)(()=>!a),[d,f]=(0,Z.useState)(!1),[p,m]=(0,Z.useState)(!1),[h,g]=(0,Z.useState)(null),[_,v]=(0,Z.useState)(null),[y,b]=(0,Z.useState)(()=>a?.targetMode??`percent`),[x,S]=(0,Z.useState)(()=>a?.percent??`25`),[C,w]=(0,Z.useState)(()=>a?.reduceGb??`4`),[T,E]=(0,Z.useState)(()=>a?.thresholdGb??`5`),D=(0,Z.useRef)(null),O=(0,Z.useRef)(!1),k=(0,Z.useRef)(!1),A=(0,Z.useRef)(0),j=(0,Z.useCallback)(e=>{let t=dO(e);c(t.policy),E(t.thresholdGb),b(t.targetMode),S(t.percent),w(t.reduceGb),o.current=!0,co(i,t),O.current=!1},[i]),M=(0,Z.useCallback)(()=>{O.current=!0},[]),N=(0,Z.useCallback)(e=>{k.current=e},[]),P=(0,Z.useCallback)(async t=>{let r=++A.current;o.current||u(!0),v(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!==A.current||O.current||k.current)return;j(i)}catch{if(t?.aborted||r!==A.current)return;o.current||(c(null),v(n(`storage.policy.loadFailed`)))}finally{!t?.aborted&&r===A.current&&u(!1)}},[e,j,n]);(0,Z.useEffect)(()=>{let e=new AbortController,t=window.setTimeout(()=>{P(e.signal)},0);return()=>{window.clearTimeout(t),A.current+=1,e.abort()}},[P]),(0,Z.useEffect)(()=>()=>{D.current?.abort(),D.current=null},[]);let F=()=>{if(!s)return null;let e=T.trim();if(e===``)return null;let t=Number(e);if(!Number.isFinite(t)||t<0)return null;let n;if(y===`reduce`){let e=C.trim();if(e===``)return null;let t=Number(e);if(!Number.isFinite(t)||t<0)return null;n={reduceToBytes:Math.floor(t*aO)}}else{let e=Number(x);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*aO)},target:n,schedule:s.schedule,mode:s.mode}},I=async t=>{let r=F();if(!r){v(n(`storage.policy.invalid`));return}let i={...r,...t};f(!0),v(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){v(n(`storage.policy.saveFailed`));return}let r=await t.json();if(!r.policy){v(n(`storage.policy.saveFailed`));return}j(r.policy),g(n(`storage.policy.saved`))}catch{v(n(`storage.policy.saveFailed`))}finally{f(!1)}},L=async()=>{D.current?.abort();let i=new AbortController;D.current=i;let{signal:a}=i;m(!0),v(null),g(null);try{let i=F();if(!i){v(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){v(n(`storage.policy.saveFailed`));return}let s=await o.json();if(a.aborted)return;if(!s.policy){v(n(`storage.policy.saveFailed`));return}j(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&&j(e.policy),v(n(`storage.policy.alreadyRunning`));return}if(!c.ok){let e=await c.json().catch(()=>({}));if(a.aborted)return;if(e.policy&&j(e.policy),e.error===`already_running`){v(n(`storage.policy.alreadyRunning`));return}v(n(`storage.policy.runFailed`));return}let l=await c.json();if(a.aborted)return;if(l.policy&&j(l.policy),l.error===`already_running`){v(n(`storage.policy.alreadyRunning`));return}if(!l.started||!l.job?.startedAt){v(n(`storage.policy.runFailed`));return}let u=l.job.startedAt,d=Date.now()+12e4,f,p;for(;Date.now()<d;){if(a.aborted||(await fO(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=uO(n),j(n);let r=n.job;if(r&&r.status!==`running`&&(r.startedAt===u&&r.lastOutcome||r.finishedAt&&r.finishedAt>=u&&r.lastOutcome)){f=r.lastOutcome;break}}if(a.aborted)return;if(p&&j(p),!f){v(n(`storage.policy.runFailed`));return}f.skipped===`disabled`?g(n(`storage.policy.skippedDisabled`)):f.ok&&f.metadataPersistenceError?(v(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`?v(n(`storage.cleanup.err.codex_busy`)):f.ok?(g(f.mode===`permanent`?n(`storage.policy.donePermanent`,{count:String(f.removed??0),size:HD(f.freedBytes??0,t)}):n(`storage.policy.doneQuarantine`,{count:String(f.removed??0),size:HD(f.freedBytes??0,t)})),r()):v(n(`storage.policy.runFailed`))}catch(e){if(a.aborted||e instanceof DOMException&&e.name===`AbortError`)return;v(n(`storage.policy.runFailed`))}finally{D.current===i&&(D.current=null),a.aborted||m(!1)}},R=e=>e===void 0?n(`storage.policy.never`):new Date(e).toLocaleString(t);return l&&!s?(0,Q.jsx)(`section`,{className:`storage-cleanup-pane`,children:(0,Q.jsx)(`p`,{className:`muted storage-policy-help`,children:n(`storage.policy.loading`)})}):s?(0,Q.jsxs)(`section`,{className:`storage-cleanup-pane`,children:[(0,Q.jsx)(`p`,{className:`muted storage-policy-help`,children:n(`storage.policy.help`)}),(0,Q.jsx)(`div`,{className:`storage-policy-enable`,children:(0,Q.jsxs)(`div`,{className:`storage-policy-enable-row`,children:[(0,Q.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 I({enabled:!s.enabled}),children:(0,Q.jsx)(`span`,{className:`toggle-knob`})}),(0,Q.jsx)(`span`,{children:n(`storage.policy.enabled`)})]})}),(0,Q.jsxs)(`div`,{className:`storage-policy-fields`,children:[(0,Q.jsxs)(`div`,{className:`field storage-policy-trigger`,children:[(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`storage-policy-threshold`,children:n(`storage.policy.trigger`)}),(0,Q.jsxs)(`div`,{className:`storage-policy-trigger-row`,children:[(0,Q.jsx)(`span`,{className:`storage-policy-trigger-hint`,children:n(`storage.policy.threshold`)}),(0,Q.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(N(!1),I())},children:[(0,Q.jsx)(`input`,{id:`storage-policy-threshold`,className:`input mono codex-auto-switch-input`,type:`number`,min:0,step:.1,inputMode:`decimal`,value:T,disabled:d||p,"aria-label":n(`storage.policy.threshold`),onFocus:()=>N(!0),onChange:e=>{M(),E(e.target.value)},onKeyDown:e=>{e.nativeEvent.isComposing||d||p||e.key===`Enter`&&(e.preventDefault(),I())}}),(0,Q.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`GiB`}),(0,Q.jsx)(yl,{disabled:d||p,incrementLabel:n(`storage.policy.thresholdInc`),decrementLabel:n(`storage.policy.thresholdDec`),onIncrement:()=>{M(),E(vl(T,.1,0,1e4,.1))},onDecrement:()=>{M(),E(vl(T,-.1,0,1e4,.1))}})]})]})]}),(0,Q.jsxs)(`fieldset`,{className:`field storage-policy-target`,children:[(0,Q.jsx)(`legend`,{className:`field-label`,children:n(`storage.policy.target`)}),(0,Q.jsxs)(`label`,{className:`storage-policy-target-row`,children:[(0,Q.jsx)(`input`,{type:`radio`,name:`storage-policy-target`,checked:y===`percent`,disabled:d||p,onChange:()=>{M(),b(`percent`)}}),(0,Q.jsx)(`span`,{className:`storage-policy-target-label`,children:n(`storage.policy.targetPercent`)}),y===`percent`&&(0,Q.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(N(!1),I())},children:[(0,Q.jsx)(`input`,{id:`storage-policy-percent`,className:`input mono codex-auto-switch-input`,type:`number`,min:1,max:100,step:1,inputMode:`numeric`,value:x,disabled:d||p,"aria-label":n(`storage.policy.targetPercent`),onFocus:()=>N(!0),onChange:e=>{M(),S(e.target.value)},onKeyDown:e=>{e.nativeEvent.isComposing||d||p||e.key===`Enter`&&(e.preventDefault(),I())}}),(0,Q.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`%`}),(0,Q.jsx)(yl,{disabled:d||p,incrementLabel:n(`storage.policy.percentInc`),decrementLabel:n(`storage.policy.percentDec`),onIncrement:()=>{M(),S(vl(x,1,1,100))},onDecrement:()=>{M(),S(vl(x,-1,1,100))}})]})]}),(0,Q.jsxs)(`label`,{className:`storage-policy-target-row`,children:[(0,Q.jsx)(`input`,{type:`radio`,name:`storage-policy-target`,checked:y===`reduce`,disabled:d||p,onChange:()=>{M(),b(`reduce`)}}),(0,Q.jsx)(`span`,{className:`storage-policy-target-label`,children:n(`storage.policy.targetReduce`)}),y===`reduce`&&(0,Q.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(N(!1),I())},children:[(0,Q.jsx)(`input`,{id:`storage-policy-reduce`,className:`input mono codex-auto-switch-input`,type:`number`,min:0,step:.1,inputMode:`decimal`,value:C,disabled:d||p,"aria-label":n(`storage.policy.targetReduce`),onFocus:()=>N(!0),onChange:e=>{M(),w(e.target.value)},onKeyDown:e=>{e.nativeEvent.isComposing||d||p||e.key===`Enter`&&(e.preventDefault(),I())}}),(0,Q.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`GiB`}),(0,Q.jsx)(yl,{disabled:d||p,incrementLabel:n(`storage.policy.reduceInc`),decrementLabel:n(`storage.policy.reduceDec`),onIncrement:()=>{M(),w(vl(C,.1,0,1e4,.1))},onDecrement:()=>{M(),w(vl(C,-.1,0,1e4,.1))}})]})]})]}),(0,Q.jsxs)(`div`,{className:`storage-policy-selects`,children:[(0,Q.jsxs)(`label`,{className:`field`,htmlFor:`storage-policy-schedule`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:n(`storage.policy.schedule`)}),(0,Q.jsxs)(`select`,{id:`storage-policy-schedule`,className:`input`,value:s.schedule,disabled:d||p,onChange:e=>{let t=e.target.value;I({schedule:t})},children:[(0,Q.jsx)(`option`,{value:`manual`,children:n(`storage.policy.schedule.manual`)}),(0,Q.jsx)(`option`,{value:`startup`,children:n(`storage.policy.schedule.startup`)}),(0,Q.jsx)(`option`,{value:`daily`,children:n(`storage.policy.schedule.daily`)}),(0,Q.jsx)(`option`,{value:`weekly`,children:n(`storage.policy.schedule.weekly`)})]})]}),(0,Q.jsxs)(`label`,{className:`field`,htmlFor:`storage-policy-mode`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:n(`storage.policy.mode`)}),(0,Q.jsxs)(`select`,{id:`storage-policy-mode`,className:`input`,value:s.mode,disabled:d||p,onChange:e=>{let t=e.target.value;I({mode:t})},children:[(0,Q.jsx)(`option`,{value:`quarantine`,children:n(`storage.policy.mode.quarantine`)}),(0,Q.jsx)(`option`,{value:`permanent`,children:n(`storage.policy.mode.permanent`)})]})]})]}),s.mode===`permanent`&&(0,Q.jsx)(`p`,{className:`err storage-policy-warn`,role:`status`,children:n(`storage.policy.permanentWarn`)})]}),(0,Q.jsxs)(`div`,{className:`storage-policy-meta`,children:[(0,Q.jsxs)(`div`,{className:`storage-policy-meta-item`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:n(`storage.policy.lastRun`)}),(0,Q.jsxs)(`span`,{className:`storage-policy-meta-value`,children:[R(s.lastRun?.at),s.lastRun?` · ${n(`storage.policy.lastRunDetail`,{count:String(s.lastRun.removed),size:HD(s.lastRun.freedBytes,t)})}`:``]})]}),(0,Q.jsxs)(`div`,{className:`storage-policy-meta-item`,children:[(0,Q.jsx)(`span`,{className:`muted`,children:n(`storage.policy.nextRun`)}),(0,Q.jsx)(`span`,{className:`storage-policy-meta-value`,children:R(s.nextRun)})]})]}),(0,Q.jsxs)(`div`,{className:`storage-policy-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:d||p,onClick:()=>void I(),children:n(`storage.policy.save`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:d||p,onClick:()=>void L(),children:n(p?`storage.policy.running`:`storage.policy.runNow`)}),(0,Q.jsx)(`span`,{className:`storage-policy-actions__status${_?` is-error`:``}`,role:_?`alert`:`status`,"aria-live":`polite`,children:_??h??``})]})]}):(0,Q.jsx)(`section`,{className:`storage-cleanup-pane`,children:_&&(0,Q.jsx)(`p`,{className:`err`,role:`alert`,children:_})})}function mO({apiBase:e,locale:t,t:n,archivedCount:r,showQuarantine:i,trashReloadToken:a,onDone:o,onTrashEntriesChange:s}){let[c,l]=(0,Z.useState)(`policy`),u=(0,Z.useRef)(null),d=(0,Z.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,Q.jsxs)(`section`,{className:`panel storage-cleanup-card`,"aria-labelledby":`storage-cleanup-card-title`,children:[(0,Q.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,Q.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,Q.jsx)(`h3`,{id:`storage-cleanup-card-title`,className:`panel-title`,children:n(`storage.cleanupCard.title`)}),(0,Q.jsxs)(`div`,{className:`storage-cleanup-card__stack`,children:[(0,Q.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,Q.jsx)(pO,{apiBase:e,locale:t,t:n,onDone:o}),(0,Q.jsxs)(`aside`,{className:`storage-cleanup-manual`,"aria-labelledby":`storage-cleanup-manual-title`,children:[(0,Q.jsx)(`h4`,{id:`storage-cleanup-manual-title`,className:`storage-cleanup-manual__title`,children:n(`storage.cleanup.title`)}),r>0?(0,Q.jsx)(cO,{apiBase:e,locale:t,t:n,onDone:o}):(0,Q.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.cleanup.noArchives`)})]})]}),(0,Q.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,Q.jsx)(lO,{apiBase:e,locale:t,t:n,onDone:o,reloadToken:a,onEntriesChange:s}):(0,Q.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.trash.empty`)})})]})]})}function hO({apiBase:e}){let{t,locale:n}=r(),i=`ocx.storage.report.v1:${e}`,a=io(i),[o,s]=(0,Z.useState)(null),[c,l]=(0,Z.useState)(0),u=(0,Z.useRef)(!1),[d,f]=(0,Z.useState)({apiBase:e,settled:!1,hasEntries:!1}),p=(0,Z.useCallback)(async n=>{try{let r=await fetch(`${e}/api/storage`,{signal:n});if(!r.ok)throw Error(t(`storage.error`));let a=await r.json();return co(i,a),u.current&&(u.current=!1,s(t(`storage.rescanned`))),a}catch(e){throw u.current&&(u.current=!1,s(t(`storage.error`))),n.aborted?e:Error(t(`storage.error`),{cause:e})}},[e,i,t]),m=uo(`storage-report:${e}`,[e],p,{isEmpty:e=>e.total.fileCount===0&&e.error===void 0}),h=m.state,g=h.data??a,_=h.refreshing||h.showSkeleton&&!g,v=m.refresh,y=(0,Z.useCallback)(()=>{s(null),u.current=!0,v(),l(e=>e+1)},[v]),b=(0,Z.useCallback)(t=>{f({apiBase:e,settled:!0,hasEntries:t.length>0})},[e]),x=d.apiBase===e&&d.settled,S=d.apiBase===e&&d.hasEntries,C=g?.error!==void 0,w=!_&&!h.showError&&!C&&g.total.fileCount===0&&x&&!S,T=g?.buckets.find(e=>e.key===`archived_sessions`)?.fileCount??0,E=!!g&&!C,D=E&&(g.total.fileCount>0||!x||S);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`page-head`,children:[(0,Q.jsx)(`h2`,{id:`storage-page-title`,children:t(`storage.title`)}),(0,Q.jsxs)(`div`,{className:`storage-page-head-actions`,children:[(0,Q.jsx)(`span`,{className:`storage-page-head-feedback`,role:`status`,"aria-live":`polite`,children:o??``}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:_,onClick:()=>void y(),children:[(0,Q.jsx)(ae,{}),` `,t(`storage.refresh`)]})]})]}),(0,Q.jsx)(`p`,{className:`page-sub`,children:t(`storage.subtitle`)}),g&&g.error===void 0&&(0,Q.jsxs)(`p`,{className:`storage-page-meta`,children:[(0,Q.jsx)(`code`,{className:`mono storage-page-meta__home`,title:g.codexHome,children:g.codexHome}),(0,Q.jsx)(`span`,{className:`storage-page-meta__sep`,"aria-hidden":`true`,children:`·`}),(0,Q.jsxs)(`span`,{children:[t(`storage.snapshot.lastScan`),`:`,` `,new Date(g.generatedAt).toLocaleString(n)]})]}),h.showSkeleton&&!g?(0,Q.jsx)(lb,{label:t(`storage.loading`),rows:5}):h.kind===`failed-cold`&&!g?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:h.error instanceof Error?h.error.message:t(`storage.error`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>v(),children:t(`common.retry`)})]}):C?(0,Q.jsx)(Q.Fragment,{children:(0,Q.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:t(`storage.error`)})}):(0,Q.jsxs)(Q.Fragment,{children:[h.showError&&(0,Q.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:t(`storage.error`)}),w?(0,Q.jsx)(fn,{title:t(`storage.empty`)}):g&&g.total.fileCount>0&&(0,Q.jsx)(iO,{report:g,locale:n,apiBase:e})]}),g&&g.error===void 0&&h.refreshing&&!h.showSkeleton&&(0,Q.jsx)(ub,{live:!h.showError,children:t(`storage.loading`)}),E&&(0,Q.jsx)(mO,{apiBase:e,locale:n,t,archivedCount:T,showQuarantine:D,trashReloadToken:c,onDone:()=>void y(),onTrashEntriesChange:b})]})}var gO=`/api/codex-auth/features/default-mode-request-user-input`;function _O({apiBase:e}){let t=n(),[r,i]=(0,Z.useState)(!1),[a,o]=(0,Z.useState)(!1),[s,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(!1),[d,f]=(0,Z.useState)(null),p=(0,Z.useRef)(!1),m=(0,Z.useRef)(!1),h=(0,Z.useRef)(0),g=(0,Z.useCallback)(async()=>{if(p.current)return;let t=++h.current,n=M(15e3);try{let r=await fetch(`${e}${gO}`,{signal:n.signal});if(!r.ok)throw Error(`load`);let a=await r.json();if(p.current||t!==h.current)return;m.current=a.enabled===!0,i(m.current),o(!0),u(!1)}catch{!p.current&&t===h.current&&u(!0)}finally{n.clear()}},[e]);(0,Z.useEffect)(()=>{let e=window.setTimeout(()=>{g()},0),t=ba(()=>{g()},3e4);return()=>{window.clearTimeout(e),t()}},[g]);let _=(0,Z.useCallback)(async()=>{if(p.current||!a||l)return;let n=!m.current,r=m.current;m.current=n,i(n),p.current=!0,c(!0),f(null),h.current++;try{let r=await fetch(`${e}${gO}`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({enabled:n})}),a=await vn(r)??{};if(a.ok!==!0)throw Error(String(r.status));m.current=a.enabled===!0,i(m.current),o(!0),f({tone:`ok`,message:t(a.changed===!0?`codexAuth.requestUserInputUpdatedRestart`:`codexAuth.requestUserInputUpdated`)})}catch(e){m.current=r,i(r);let n=e instanceof Error&&e.message&&!/^HTTP \d{3}$/.test(e.message)?e.message:t(`codexAuth.requestUserInputUpdateFailed`);f({tone:`err`,message:n})}finally{p.current=!1,c(!1)}},[e,a,l,t]),v=s||!a||l;return(0,Q.jsxs)(`div`,{className:`card card-row codex-request-user-input-card`,style:{marginTop:16},"aria-busy":s||!a&&!l||void 0,children:[(0,Q.jsxs)(`div`,{className:`codex-request-user-input-copy`,children:[(0,Q.jsx)(`strong`,{children:t(`codexAuth.requestUserInput`)}),(0,Q.jsx)(`div`,{className:`card-sub`,role:l?`alert`:void 0,children:t(l?`codexAuth.requestUserInputLoadFailed`:`codexAuth.requestUserInputDesc`)}),(0,Q.jsx)(`code`,{className:`mono codex-request-user-input-config`,children:`[features]
8
8
  default_mode_request_user_input = true`})]}),(0,Q.jsxs)(`div`,{className:`codex-request-user-input-controls`,children:[l&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{g()},children:t(`common.retry`)}),(0,Q.jsx)(`button`,{type:`button`,className:`toggle ${r?`on`:``}`,onClick:()=>{_()},disabled:v,"aria-pressed":r,"aria-label":t(`codexAuth.requestUserInput`),title:t(`codexAuth.requestUserInput`),children:(0,Q.jsx)(`span`,{className:`toggle-knob`})})]}),d&&(0,Q.jsx)(`div`,{className:`codex-request-user-input-feedback${d.tone===`err`?` is-error`:``}`,role:d.tone===`err`?`alert`:`status`,"aria-atomic":`true`,children:d.message})]})}function vO({apiBase:e}){let t=n(),[r,i]=(0,Z.useState)(!1),[a,o]=(0,Z.useState)(!1),[s,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(!1),[d,f]=(0,Z.useState)(null),p=(0,Z.useRef)(!1),m=(0,Z.useRef)(0),h=(0,Z.useCallback)(async()=>{if(p.current)return;let t=++m.current,n=M(15e3);try{let r=await fetch(`${e}/api/settings`,{signal:n.signal});if(!r.ok)throw Error(`load`);let a=await r.json();if(p.current||t!==m.current)return;i(a.ultraFastTier===!0),o(!0),u(!1)}catch{!p.current&&t===m.current&&u(!0)}finally{n.clear()}},[e]);(0,Z.useEffect)(()=>{let e=window.setTimeout(()=>{h()},0),t=ba(()=>{h()},3e4);return()=>{window.clearTimeout(e),t()}},[h]);let g=(0,Z.useCallback)(async()=>{if(p.current||!a||l)return;let n=!r;p.current=!0,c(!0),f(null),i(n);let o=M(15e3);try{let r=await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({ultraFastTier:n}),signal:o.signal});if(!r.ok)throw Error(`save`);let a=await r.json(),s=typeof a.ultraFastTier==`boolean`?a.ultraFastTier:n;i(s),f({tone:`ok`,message:t(s?`codexAuth.ultraFastEnabled`:`codexAuth.ultraFastDisabled`)})}catch{i(!n),f({tone:`err`,message:t(`codexAuth.ultraFastFailed`)})}finally{o.clear(),p.current=!1,c(!1)}},[e,r,a,l,t]),_=s||!a||l;return(0,Q.jsxs)(`div`,{className:`card card-row codex-ultrafast-card`,style:{marginTop:16},"aria-busy":s||!a&&!l||void 0,children:[(0,Q.jsxs)(`div`,{className:`codex-ultrafast-copy`,children:[(0,Q.jsx)(`strong`,{children:t(`codexAuth.ultraFastTitle`)}),(0,Q.jsx)(`div`,{className:`card-sub`,role:l?`alert`:void 0,children:t(l?`codexAuth.ultraFastLoadFailed`:`codexAuth.ultraFastDesc`)})]}),(0,Q.jsxs)(`div`,{className:`codex-ultrafast-controls`,children:[l&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{h()},children:t(`common.retry`)}),(0,Q.jsx)(`button`,{type:`button`,className:`toggle ${r?`on`:``}`,onClick:()=>{g()},disabled:_,"aria-pressed":r,"aria-label":t(`codexAuth.ultraFastTitle`),title:t(`codexAuth.ultraFastTitle`),children:(0,Q.jsx)(`span`,{className:`toggle-knob`})})]}),d&&(0,Q.jsx)(`div`,{className:`codex-ultrafast-feedback${d.tone===`err`?` is-error`:``}`,role:d.tone===`err`?`alert`:`status`,"aria-atomic":`true`,children:d.message})]})}var yO=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`,`ultra`];function bO(e){if(e==null)return null;if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`settings shape`);let t=`model`in e&&typeof e.model==`string`?e.model.trim():``;if(!t)throw Error(`settings shape`);let n=`reasoningEffort`in e?e.reasoningEffort:void 0;if(n!==void 0&&(typeof n!=`string`||!yO.includes(n)))throw Error(`settings shape`);let r=`enabled`in e?e.enabled:void 0;if(r!==void 0&&typeof r!=`boolean`)throw Error(`settings shape`);return{model:t,...n?{reasoningEffort:n}:{},...r===void 0?{}:{enabled:r}}}function xO(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`);let r=bO(t.codexMainAccountHardLockFallback);return{...t,codexMainAccountHardLock:t.codexMainAccountHardLock,mainAccountHardLock:n,codexMainAccountHardLockFallback:r}}function SO({pending:e,thresholds:t,onCancel:r,onConfirm:i}){let a=n(),o=(0,Z.useId)(),s=(0,Z.useRef)(null),c=(0,Z.useRef)(null),l=(0,Z.useRef)(null);return(0,Z.useEffect)(()=>{let e=s.current;return e&&!e.open&&e.showModal(),c.current?.focus(),()=>{e?.open&&e.close()}},[]),(0,Q.jsxs)(`dialog`,{ref:s,className:`modal-overlay`,"aria-labelledby":`${o}-title`,"aria-describedby":`${o}-body`,"aria-busy":e||void 0,onCancel:e=>{e.preventDefault(),r()},onKeyDown:t=>{if(t.key!==`Tab`||e)return;let n=t.shiftKey?c.current:l.current,r=t.shiftKey?l.current:c.current;document.activeElement===n&&(t.preventDefault(),r?.focus())},children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,tabIndex:-1,"aria-label":a(`common.close`),disabled:e,onClick:r}),(0,Q.jsxs)(`div`,{className:`modal-card codex-main-hard-lock-dialog`,role:`document`,children:[(0,Q.jsx)(`h3`,{id:`${o}-title`,children:a(`codexAuth.mainHardLockConfirmTitle`,t)}),(0,Q.jsx)(`p`,{id:`${o}-body`,className:`modal-desc`,children:a(`codexAuth.mainHardLockConfirmBody`)}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{ref:c,type:`button`,className:`btn btn-ghost`,disabled:e,onClick:r,children:a(`codexAuth.cancel`)}),(0,Q.jsx)(`button`,{ref:l,type:`button`,className:`btn btn-primary`,disabled:e,onClick:i,children:a(e?`common.saving`:`codexAuth.mainHardLockConfirm`)})]})]})]})}function CO(e){return(0,Q.jsx)(wO,{...e},e.apiBase)}function wO({apiBase:e,onSaved:t}){let r=n(),i=(0,Z.useId)(),[a,o]=(0,Z.useState)(null),[s,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(!1),[d,f]=(0,Z.useState)(!1),[p,m]=(0,Z.useState)(null),[h,g]=(0,Z.useState)(!1),[_,v]=(0,Z.useState)(!1),[y,b]=(0,Z.useState)(null),[x,S]=(0,Z.useState)([]),[C,w]=(0,Z.useState)(!1),[T,E]=(0,Z.useState)(!1),D=(0,Z.useRef)(!1),O=(0,Z.useRef)(!1),k=(0,Z.useRef)(0),A=(0,Z.useRef)(null),j=(0,Z.useRef)(null),N=(0,Z.useRef)(!1),P=(0,Z.useCallback)(()=>{if(N.current||j.current)return;let t=new AbortController;j.current=t,(async()=>{try{let n=await fetch(`${e}/api/models`,{signal:t.signal});if(!n.ok)throw Error(`models`);let r=await n.json();if(!Array.isArray(r))throw Error(`models`);N.current=!0,O.current&&S(r.filter(e=>typeof e==`object`&&!!e&&typeof e.namespaced==`string`&&e.native!==!0&&e.disabled!==!0))}catch{}finally{j.current===t&&(j.current=null)}})()},[e]),F=(0,Z.useRef)(null),I=(0,Z.useRef)(null),L=(0,Z.useRef)(!1),R=(0,Z.useCallback)(async()=>{if(D.current)return;let t=++k.current;A.current?.abort();let n=M(15e3);A.current=n.controller;try{let r=await fetch(`${e}/api/settings`,{signal:n.signal});if(!r.ok)throw Error(`load`);let i=xO(await r.json());if(!O.current||t!==k.current)return;o(i),b(i.codexMainAccountHardLockFallback),c(!1),m(null)}catch{O.current&&t===k.current&&c(!0)}finally{n.clear()}},[e]);(0,Z.useEffect)(()=>{O.current=!0;let e=window.setTimeout(()=>{R()},0),t=ba(()=>{R()},3e4);return()=>{O.current=!1,k.current+=1,A.current?.abort(),j.current?.abort(),j.current=null,window.clearTimeout(e),t()}},[R]),(0,Z.useEffect)(()=>{_||h||!L.current||(F.current&&!F.current.disabled?(F.current.focus(),L.current=!1):I.current?.focus())},[_,h,s,a]);let z=async()=>{let e=!1;try{e=await t()}catch{}O.current&&f(!e)},B=async t=>{if(D.current||!a)return;D.current=!0,k.current+=1,A.current?.abort(),g(!0),u(!1),f(!1),m(null);let n=M(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 a=await i.json();if(!a||typeof a!=`object`||!(`ok`in a)||a.ok!==!0)throw Error(`unconfirmed`);let s=xO(a);r=!0,O.current&&(o(s),c(!1),m(s.codexMainAccountHardLock))}catch{O.current&&(u(!0),c(!0))}finally{n.clear()}r&&await z(),D.current=!1,O.current&&(g(!1),v(!1),r||R())},V=()=>{D.current||v(!1)},H=async t=>{if(D.current||C||!a)return;D.current=!0,k.current+=1,A.current?.abort(),w(!0),E(!1);let n=M(15e3),r=!1;try{let i=await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({codexMainAccountHardLockFallback:t}),signal:n.signal});if(!i.ok)throw Error(`save`);let a=await i.json();if(!a||typeof a!=`object`||!(`ok`in a)||a.ok!==!0)throw Error(`unconfirmed`);let s=xO(a);r=!0,O.current&&(o(s),b(s.codexMainAccountHardLockFallback),c(!1))}catch{O.current&&E(!0)}finally{n.clear()}r&&await z(),D.current=!1,O.current&&(w(!1),r||R())},U=y?.enabled!==!1&&!!y?.model,ee=()=>{y?.model&&H({...y,enabled:!U})},W=e=>{if(!e)return;let{enabled:t,...n}=y??{};H({...n,model:e,...y?.enabled===!1?{enabled:!0}:{}})},te=e=>{H({...y??{},...e?{reasoningEffort:e}:{reasoningEffort:void 0}})},G=async()=>{D.current||(D.current=!0,k.current+=1,g(!0),await z(),D.current=!1,O.current&&g(!1))},ne=a?.codexMainAccountHardLock,K=Nu(a?.mainAccountHardLock.thresholds);return(0,Q.jsxs)(`section`,{ref:I,id:`codex-main-hard-lock-setting`,tabIndex:-1,className:`card card-row codex-main-hard-lock-setting`,"aria-labelledby":`${i}-title`,"aria-busy":h||!a&&!s||void 0,onBlurCapture:e=>{e.relatedTarget!==null&&!e.currentTarget.contains(e.relatedTarget)&&(L.current=!1)},children:[(0,Q.jsxs)(`div`,{className:`codex-main-hard-lock-copy`,children:[(0,Q.jsx)(`strong`,{id:`${i}-title`,children:r(`codexAuth.mainHardLockTitle`,K)}),(0,Q.jsx)(`div`,{id:`${i}-desc`,className:`card-sub`,children:r(`codexAuth.mainHardLockDesc`,K)})]}),(0,Q.jsx)(`button`,{ref:F,type:`button`,className:`toggle ${ne===!0?`on`:``}`,disabled:h||ne===void 0||s,"aria-pressed":ne,"aria-label":r(`codexAuth.mainHardLockTitle`,K),"aria-describedby":`${i}-desc`,onClick:()=>{D.current||ne===void 0||s||(L.current=!0,ne?B(!1):v(!0))},children:(0,Q.jsx)(`span`,{className:`toggle-knob`})}),(0,Q.jsxs)(`div`,{className:`codex-main-hard-lock-feedback`,children:[a?.mainAccountHardLock.externalUsage&&(0,Q.jsx)(`div`,{className:`codex-main-hard-lock-status is-blocked`,children:(0,Q.jsx)(`p`,{role:`status`,children:r(`codexAuth.mainExternalUsageWarning`)})}),(l||s)&&(0,Q.jsxs)(`p`,{role:`alert`,children:[r(l?`codexAuth.mainHardLockSaveFailed`:`codexAuth.mainHardLockLoadFailed`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,disabled:h,onClick:()=>{R()},children:r(`common.retry`)})]}),p!==null&&!d&&(0,Q.jsx)(`p`,{role:`status`,children:r(p?`codexAuth.mainHardLockEnabled`:`codexAuth.mainHardLockDisabled`,K)}),d&&(0,Q.jsxs)(`p`,{role:`status`,children:[r(`codexAuth.mainHardLockRefreshFailed`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,disabled:h,onClick:()=>{G()},children:r(`common.retry`)})]})]}),(0,Q.jsxs)(`div`,{className:`codex-main-hard-lock-fallback`,role:`group`,"aria-label":r(`codexAuth.mainHardLockFallbackTitle`),onFocusCapture:P,onPointerDownCapture:P,onClickCapture:P,style:{flexBasis:`100%`},children:[(0,Q.jsxs)(`div`,{className:`spread`,style:{alignItems:`center`},children:[(0,Q.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:8,minWidth:0},children:(0,Q.jsx)(`span`,{className:`font-semibold`,children:r(`codexAuth.mainHardLockFallbackTitle`)})}),(0,Q.jsxs)(`div`,{className:`setting-controls`,style:{flex:`0 1 auto`},children:[(0,Q.jsx)(`button`,{type:`button`,className:`switch ${U?`on`:``}`,onClick:ee,disabled:C||s||!y?.model,"aria-label":r(`codexAuth.mainHardLockFallbackTitle`),"aria-pressed":U,children:(0,Q.jsx)(`span`,{className:`knob`})}),(0,Q.jsx)(dn,{value:y?.model??``,options:[...new Set([y?.model,...x.map(e=>e.namespaced)].filter(e=>!!e))].map(e=>({value:e,label:we(e,r)})),onChange:W,disabled:C||s,label:r(`codexAuth.mainHardLockFallbackModel`),align:`right`}),(0,Q.jsx)(dn,{value:y?.reasoningEffort??``,options:[{value:``,label:r(`codexAuth.mainHardLockFallbackDefaultEffort`)},...yO.map(e=>({value:e,label:r(`models.reasoningEffort.${e}`)}))],onChange:te,disabled:C||s||!U,label:r(`codexAuth.mainHardLockFallbackEffort`),align:`right`})]})]}),(0,Q.jsx)(`div`,{className:`muted setting-hint`,children:r(`codexAuth.mainHardLockFallbackDesc`)}),a?.mainAccountHardLock.state===`blocked`&&U&&y?.model&&(0,Q.jsx)(`p`,{role:`status`,className:`codex-main-hard-lock-status is-blocked`,children:r(`codexAuth.mainHardLockFallbackActive`,{model:y.model})}),T&&(0,Q.jsxs)(`p`,{role:`alert`,children:[r(`codexAuth.mainHardLockFallbackSaveFailed`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,disabled:C,onClick:()=>{R()},children:r(`common.retry`)})]})]}),_&&(0,Q.jsx)(SO,{pending:h,thresholds:K,onCancel:V,onConfirm:()=>{B(!0)}})]})}function TO({apiBase:e}){let t=n(),[r,i]=(0,Z.useState)(!1),[a,o]=(0,Z.useState)(!1),[s,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(!1),[d,f]=(0,Z.useState)(null),p=(0,Z.useRef)(!1),m=(0,Z.useRef)(!1),h=(0,Z.useRef)(0),g=(0,Z.useCallback)(async()=>{if(m.current)return;let t=++h.current,n=M(15e3);try{let r=await fetch(`${e}/api/settings`,{signal:n.signal});if(!r.ok)throw Error(`load`);let a=await r.json();if(m.current||t!==h.current)return;if(typeof a.codexAccountPickerEnabled!=`boolean`)throw Error(`shape`);p.current=a.codexAccountPickerEnabled,i(a.codexAccountPickerEnabled),o(!0),u(!1)}catch{!m.current&&t===h.current&&u(!0)}finally{n.clear()}},[e]);(0,Z.useEffect)(()=>{let e=window.setTimeout(()=>{g()},0),t=ba(()=>{g()},3e4);return()=>{window.clearTimeout(e),t()}},[g]);let _=(0,Z.useCallback)(async()=>{if(m.current||!a)return;let n=p.current,r=!n;p.current=r,i(r),m.current=!0,c(!0),f(null),h.current+=1;try{let n=await vn(await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({codexAccountPickerEnabled:r})}))??{};if(n.ok!==!0||typeof n.codexAccountPickerEnabled!=`boolean`)throw Error(`unconfirmed`);p.current=n.codexAccountPickerEnabled,i(n.codexAccountPickerEnabled),o(!0),u(!1),f(n.catalogRefreshPending===!0?{tone:`warn`,message:t(`codexAuth.catalogRefreshPending`)}:{tone:`ok`,message:t(`codexAuth.accountPickerUpdated`)})}catch{p.current=n,i(n),f({tone:`err`,message:t(`codexAuth.accountPickerUpdateFailed`)})}finally{m.current=!1,c(!1)}},[e,a,t]),v=l&&!a;return(0,Q.jsxs)(`div`,{className:`card card-row codex-account-picker-card`,"aria-busy":s||!a&&!v||void 0,children:[(0,Q.jsxs)(`div`,{className:`codex-account-picker-copy`,children:[(0,Q.jsx)(`strong`,{children:t(`codexAuth.accountPickerTitle`)}),(0,Q.jsx)(`div`,{className:`card-sub`,role:v?`status`:void 0,children:t(v?`codexAuth.accountPickerLoadFailed`:a?r?`codexAuth.accountPickerOnDesc`:`codexAuth.accountPickerOffDesc`:`common.loading`)}),a&&r&&(0,Q.jsx)(`div`,{className:`card-sub faint`,children:t(`codexAuth.accountPickerCompatibility`)}),a&&l&&(0,Q.jsx)(`div`,{className:`card-sub faint`,role:`status`,children:t(`codexAuth.accountPickerRefreshFailed`)})]}),(0,Q.jsxs)(`div`,{className:`codex-account-picker-controls`,children:[l&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{g()},disabled:s,children:t(`common.retry`)}),a&&(0,Q.jsx)(`button`,{type:`button`,className:`toggle ${r?`on`:``}`,onClick:()=>{_()},disabled:s,"aria-pressed":r,"aria-label":t(`codexAuth.accountPickerTitle`),title:t(`codexAuth.accountPickerTitle`),children:(0,Q.jsx)(`span`,{className:`toggle-knob`})})]}),d&&(0,Q.jsx)(`div`,{className:`codex-account-picker-feedback is-${d.tone}`,role:d.tone===`err`?`alert`:`status`,"aria-atomic":`true`,children:d.message})]})}function EO(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 DO({state:e,busy:t,onEnable:r}){let i=n();return e===null?null:(0,Q.jsxs)(`div`,{className:`panel openai-account-mode-banner`,style:{marginBottom:16},children:[(0,Q.jsxs)(`div`,{className:`row`,children:[(0,Q.jsx)(`strong`,{children:i(`codexAuth.accountModeTitle`)}),e===`pool`?(0,Q.jsx)(`span`,{className:`badge badge-accent openai-account-mode-banner__badge-slot`,children:i(`codexAuth.accountModePool`)}):e===`direct`?(0,Q.jsx)(`span`,{className:`badge badge-green openai-account-mode-banner__badge-slot`,children:i(`codexAuth.accountModeDirect`)}):null]}),e===`pool`&&(0,Q.jsx)(`p`,{className:`card-sub openai-account-mode-banner__desc`,children:i(`codexAuth.accountModePoolDesc`)}),e===`direct`&&(0,Q.jsxs)(`p`,{className:`card-sub openai-account-mode-banner__desc`,children:[i(`codexAuth.accountModeDirectDesc`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>Xt(`providers`),children:i(`codexAuth.openProviders`)})]}),(e===`absent`||e===`disabled`)&&(0,Q.jsxs)(`div`,{className:`row`,style:{alignItems:`center`,marginTop:8},children:[(0,Q.jsx)(`p`,{className:`card-sub`,style:{flex:1,margin:0},children:i(`codexAuth.openaiUnavailableDesc`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:t,onClick:r,children:i(t?`codexAuth.enablingOpenai`:`codexAuth.enableOpenai`)})]}),e===`invalid`&&(0,Q.jsxs)(`p`,{className:`card-sub openai-account-mode-banner__desc`,children:[i(`codexAuth.openaiMissing`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>Xt(`providers`),children:i(`codexAuth.openProviders`)})]})]})}function OO(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 kO({apiBase:e}){return(0,Q.jsx)(AO,{apiBase:e},e)}function AO({apiBase:e}){let t=n(),r=Lu(e),{load:i}=r,a=(0,Z.useRef)(!1);(0,Z.useLayoutEffect)(()=>(a.current=!0,()=>{a.current=!1}),[]);let o=(0,Z.useCallback)(()=>a.current?i(!1):Promise.resolve(!1),[i]),s=`ocx.codex-auth.config.v1:${e}`,c=io(s),[l,u]=(0,Z.useState)(()=>c?.bannerState??null),[d,f]=(0,Z.useState)(()=>c?.accountModeState??null),p=(0,Z.useRef)(null),[m,h]=(0,Z.useState)(!1),[g,_]=(0,Z.useState)(``),v=(0,Z.useCallback)(async()=>{let t=M(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=gm(OO(r));if(i===`absent`||i===`disabled`||i===`invalid`){u(i);let e=i===`disabled`?`disabled`:`absent`;f(e),co(s,{bannerState:i,accountModeState:e});return}let a=EO(r);u(a),f(a),co(s,{bannerState:a,accountModeState:a})}catch{}finally{t.clear()}},[e,s]);(0,Z.useEffect)(()=>{p.current!==e&&(p.current=e,Promise.resolve().then(()=>{v()}));let t=ba(()=>{v()},3e4);return()=>{t()}},[e,v]);let y=async()=>{h(!0),_(``);try{if(l!==`absent`&&l!==`disabled`)return;await Cm(e,l),await v()}catch(e){e instanceof Sm?_(t(e.i18nKey)):_(e instanceof Error?e.message:t(`prov.saveFailed`))}finally{h(!1)}};return(0,Q.jsx)(Q.Fragment,{children:(0,Q.jsx)(yf,{apiBase:e,controller:r,hasMainHardLockSetting:!0,accountModeState:d,banner:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(DO,{state:l,busy:m,onEnable:()=>{y()}}),g&&(0,Q.jsx)(`div`,{className:`notice notice-err`,role:`alert`,children:g})]}),advancedExtras:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(TO,{apiBase:e}),(0,Q.jsx)(_O,{apiBase:e}),(0,Q.jsx)(vO,{apiBase:e}),(0,Q.jsx)(CO,{apiBase:e,onSaved:o})]})})})}var jO={"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`},MO={"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`},NO={"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`},PO={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 FO({descriptor:e,toggle:t,bytes:r,transitionOnly:i=!1,busy:a,writesRefused:o,onToggle:s,onReset:c,onSelectBase:l,baseSelection:u,onOpen:d}){let f=n(),p=jO[e.id],m=p?f(p):e.id,h=NO[e.id],g=t?.defaultedUserValue??e.default??!0,_=u?.kind==="default";return(0,Q.jsxs)(`li`,{className:`codex-set-prompt__row`,"data-layer-id":e.id,"data-layer-class":e.class,children:[(0,Q.jsx)(`span`,{className:`codex-set-prompt__pos`,"aria-hidden":`true`,children:e.order===null?`·`:e.order+1}),(0,Q.jsx)(`button`,{type:`button`,className:`link-btn codex-set-prompt__name`,onClick:()=>d(e.id),children:m}),e.key&&(0,Q.jsx)(`code`,{className:`codex-set-prompt__key`,children:e.key}),r!==null&&r>0&&(0,Q.jsx)(`span`,{className:`codex-set-prompt__bytes`,title:f(`codexSet.dialog.sourceBytes`,{bytes:r}),children:r>=1024?Math.round(r/1024)+` KB`:r+` B`}),e.class===`base`&&l?(0,Q.jsx)(`button`,{type:`button`,role:`switch`,className:`toggle ${_?`on`:``}`,"aria-checked":_,"aria-label":m,disabled:a||o||u?.kind===`external`,onClick:()=>{l(!_)},children:(0,Q.jsx)(`span`,{className:`toggle-knob`})}):e.class===`config-toggle`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`button`,{type:`button`,role:`switch`,className:`toggle ${g?`on`:``}`,"aria-checked":g,"aria-label":m,disabled:a||o,onClick:()=>{s(e.id,!g)},children:(0,Q.jsx)(`span`,{className:`toggle-knob`})}),t!==void 0&&t.userFileValue!==null&&c&&(0,Q.jsx)(`button`,{type:`button`,className:`link-btn codex-set-prompt__reset`,disabled:a||o,onClick:()=>{c(e.id)},children:f(`codexSet.row.resetDefault`,{value:String(t.default)})})]}):e.class===`feature-gated`?(0,Q.jsxs)(`span`,{className:`codex-set-prompt__note`,children:[f(`codexSet.row.featureGated`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>Xt(`integrations/codex`),children:f(`codexSet.row.openFeatures`)})]}):(0,Q.jsx)(`span`,{className:`codex-set-prompt__note codex-set-prompt__note--locked`,children:f(i?`codexSet.row.onChange`:h||`codexSet.row.alwaysOn`)})]})}function IO({descriptor:e,toggle:t,text:r,probe:i,busy:a,onToggle:o,onReset:s,onClose:c,onRemeasure:l}){let u=n(),d=(0,Z.useRef)(null),f=`codex-set-layer-dialog-`+e.id;(0,Z.useEffect)(()=>{let e=d.current,t=document.activeElement;return e&&!e.open&&e.showModal(),()=>{e?.open&&e.close(),t&&typeof t.focus==`function`&&t.focus()}},[]);let p=(0,Z.useCallback)(e=>{e.preventDefault(),c()},[c]),m=PO[e.class],h=jO[e.id],g=MO[e.id],_=NO[e.id];return(0,Q.jsxs)(`dialog`,{ref:d,className:`modal-overlay`,"aria-labelledby":f,onCancel:p,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":u(`common.close`),tabIndex:-1,onClick:c}),(0,Q.jsxs)(`div`,{className:`modal-card codex-set-layer-dialog`,onClick:e=>e.stopPropagation(),role:`document`,children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:f,children:h?u(h):e.id}),e.class===`config-toggle`&&t&&(0,Q.jsx)(`button`,{type:`button`,role:`switch`,className:`toggle ${t.defaultedUserValue?`on`:``}`,"aria-checked":t.defaultedUserValue,"aria-label":h?u(h):e.id,disabled:a,onClick:()=>{o(e.id,!t.defaultedUserValue)},children:(0,Q.jsx)(`span`,{className:`toggle-knob`})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:c,children:u(`common.close`)})]}),(0,Q.jsx)(`p`,{className:`muted small`,children:u(g||`codexSet.dialog.unknownLayer`)}),(0,Q.jsxs)(`div`,{className:`codex-set-layer-dialog__line`,children:[(0,Q.jsx)(`span`,{className:`muted text-label`,children:u(`codexSet.dialog.class`)}),(0,Q.jsx)(`span`,{children:u(m)})]}),e.key&&(0,Q.jsxs)(`div`,{className:`codex-set-layer-dialog__line`,children:[(0,Q.jsx)(`span`,{className:`muted text-label`,children:u(`codexSet.dialog.key`)}),(0,Q.jsx)(`code`,{className:`api-code`,children:e.key}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{navigator.clipboard?.writeText(e.key??``)},children:u(`codexSet.dialog.copyKey`)})]}),e.class===`config-toggle`&&t&&(0,Q.jsxs)(`div`,{className:`codex-set-layer-dialog__line`,children:[(0,Q.jsx)(`span`,{className:`muted text-label`,children:u(`codexSet.dialog.fileValue`)}),(0,Q.jsx)(`span`,{children:t.userFileValue===null?u(`codexSet.dialog.absentDefault`,{value:String(t.default)}):u(`codexSet.dialog.setValue`,{value:String(t.userFileValue),fallback:String(t.default)})}),t.userFileValue!==null&&s&&(0,Q.jsx)(`button`,{type:`button`,className:`link-btn codex-set-prompt__reset`,disabled:a,onClick:()=>{s(e.id)},children:u(`codexSet.row.resetDefault`,{value:String(t.default)})})]}),e.class===`runtime-conditional`&&_&&(0,Q.jsx)(`p`,{className:`muted small`,children:u(_)}),e.class===`feature-gated`&&(0,Q.jsx)(`div`,{className:`codex-set-layer-dialog__line`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>Xt(`integrations/codex`),children:u(`codexSet.row.openFeatures`)})}),r?.reason===`ok`&&r.text?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`codex-set-layer-dialog__line`,children:[(0,Q.jsx)(`span`,{className:`muted text-label`,children:u(`codexSet.dialog.sourceText`)}),(0,Q.jsx)(`span`,{className:`muted small`,children:u(`codexSet.dialog.sourceBytes`,{bytes:r.bytes})})]}),(0,Q.jsx)(`pre`,{className:`api-code codex-set-layer-dialog__text`,children:r.text})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`muted small codex-set-layer-dialog__no-text`,children:r?.reason===`empty-source`?u(`codexSet.dialog.emptySource`,{path:r.sourcePath??``}):r?.reason===`not-rendered`?u(`codexSet.dialog.notRendered`):r?.reason===`unmapped`?u(`codexSet.dialog.unmapped`):r?.reason===`not-exposed`?u(`codexSet.dialog.notExposed`):i&&i.ok===!1?i.failure?.kind===`program-not-found`?u(`codexSet.dialog.probeNotFound`):i.failure?.kind===`command-unsupported`?u(`codexSet.dialog.probeUnsupported`):i.failure?.kind===`output-invalid`?u(`codexSet.dialog.probeInvalid`):i.failure?.kind===`execution-failed`||i.failure?.kind===`request-failed`?u(`codexSet.dialog.probeFailed`):u(`codexSet.dialog.probeBusy`):u(`codexSet.dialog.textUnavailable`)}),i&&i.ok===!1&&i.failure===void 0&&l&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:l,children:u(`common.retry`)})]})]})]})}var LO=65536;function RO(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 zO(e){return e.replace(/\r\n/g,`
9
9
  `).replace(/\r/g,`
10
10
  `).replace(/\t/g,` `)}function BO(e){let t=0;for(let n of e){let e=n.codePointAt(0);if(n!==`
@@ -55,4 +55,4 @@ const closeSession = () => ws.send(JSON.stringify({ type: "session.close" }));`}
55
55
  `):o(`claude.tierDefaults.applied`)}),d&&(0,Q.jsx)(`p`,{role:p?`alert`:`status`,children:d}),h&&(0,Q.jsx)(`pre`,{children:h})]})}var Qj=[`authMode`,`systemEnv`,`fastMode`,`autoContext`,`autoCompactWindow`,`contextAccounting`,`injectAgents`,`smallFastModel`,`tierModels`,`webSearchSidecar`,`visionSidecar`];function $j(e){let t=new Map;for(let n of e){let e=n.from.trim(),r=n.to.trim();e&&r&&t.set(e,r)}return Object.fromEntries([...t.entries()].sort(([e],[t])=>e.localeCompare(t)))}function eM(e,t){return{authMode:e.authMode,systemEnv:e.systemEnv,fastMode:e.fastMode,autoContext:e.autoContext,autoCompactWindow:e.autoCompactWindow,contextAccounting:e.contextAccounting,injectAgents:e.injectAgents,smallFastModel:e.smallFastModel,tierModels:e.tierModels??null,modelMap:$j(t),webSearchSidecar:zj(e.webSearchSidecar),visionSidecar:zj(e.visionSidecar)}}function tM(e){return JSON.stringify([eM(e.state,e.rows),e.rows.map(e=>[e.from,e.to])])}function nM(e,t){return tM(e)!==tM(t)}function rM(e){return Object.fromEntries(Qj.map(t=>[t,e[t]]))}function iM(e,t){return{...t,...rM(e)}}function aM(e,t){return{...e,...rM(t)}}function oM(e,t){return!e||e.adoptNextRead||!e.savePending&&!nM(e.draft,e.baseline)?{draft:t,baseline:t,adoptNextRead:!1,savePending:e?.savePending}:{draft:{state:iM(e.draft.state,t.state),rows:e.draft.rows},baseline:t,adoptNextRead:!1,savePending:e.savePending}}function sM(e,t){return{state:{...e,...rM(t.state),visionSidecar:Pj(t.state.visionSidecar),webSearchSidecar:Pj(t.state.webSearchSidecar)},rows:Object.entries($j(t.rows)).map(([e,t])=>({id:Sj(),from:e,to:t}))}}function cM(e,t){if(!e)return e;let n=sM(e.baseline.state,t),r=n.rows;if(tM(e.draft)===tM(t))return{draft:{state:{...e.draft.state,visionSidecar:n.state.visionSidecar,webSearchSidecar:n.state.webSearchSidecar},rows:r},baseline:n,adoptNextRead:!0};let i=e.draft;for(let e of[`visionSidecar`,`webSearchSidecar`]){let n=JSON.stringify(zj(t.state[e]));if(JSON.stringify(zj(i.state[e]))!==n)continue;let r=Pj(i.state[e]);r!==i.state[e]&&(i={...i,state:{...i.state,[e]:r}})}return{draft:i,baseline:n,adoptNextRead:!1}}function lM(e){return{...e,cliFirstParty:e.cliFirstParty===!0,cliFirstPartyApplied:e.cliFirstPartyApplied===!0,desktopFirstParty:e.desktopFirstParty===!0,interceptRunning:e.interceptRunning===!0,interceptEligible:e.interceptEligible===void 0||e.interceptEligible===!0,sharedProxy:mj(e.sharedProxy),contextAccounting:Tj(e.contextAccounting),servedContextAccounting:Tj(e.servedContextAccounting??e.contextAccounting)}}var uM=new Map,dM=e=>uM.get(e)??0,fM=e=>{uM.set(e,dM(e)+1)},pM=Symbol(`claude-code-live`),mM=new Map;function hM(e,t,n){for(let r of mM.get(e)??[])r(t,n)}var gM={unknown:`claude.firstParty.unknown`,foreign:`claude.firstParty.foreign`,local:`claude.firstParty.local`,residual:`claude.firstParty.residual`,disabled:`claude.firstParty.disabled`,routingOff:`claude.firstParty.routingOff`,stopped:`claude.firstParty.deadProxy`,broken:`claude.firstParty.brokenProxy`,notApplied:`claude.firstParty.notApplied`,shared:`claude.firstParty.shared`};function _M({title:e,count:t,children:n}){let r=(0,Z.useId)();return(0,Q.jsxs)(`section`,{className:`ccw-section`,"aria-labelledby":r,children:[(0,Q.jsxs)(`h3`,{className:`ccw-section-title`,id:r,children:[e,t==null?null:(0,Q.jsx)(`span`,{className:`count`,children:t})]}),n]})}function vM({apiBase:e,active:t=!0}){let i=n(),{locale:a}=r(),o=j.find(e=>e.code===a)?.htmlLang??`en`,s=`ocx.claude-code.v1:${e}`,c=`claude-code:${e}`,l=(0,Z.useMemo)(()=>oo(s),[s]),u=(0,Z.useMemo)(()=>l?.data?{...l.data,state:lM(l.data.state)}:null,[l]),[d,f]=(0,Z.useState)(()=>u?{draft:u,baseline:u,adoptNextRead:!1}:null),[p,m]=(0,Z.useState)(!1),[h,g]=(0,Z.useState)(``),[_,v]=(0,Z.useState)(``),[y,b]=(0,Z.useState)(!1),{pending:x,change:S}=yj(e),[C,w]=(0,Z.useState)(!1),T=(0,Z.useRef)(!1),E=(0,Z.useCallback)(async t=>{let n=dM(s),r=await vn(await fetch(`${e}/api/claude-code`,{signal:t}),i(`claude.loadFail`));if(!r)throw Error(i(`claude.loadFail`));let a={state:lM({...r,authMode:r.authMode===`proxy`||r.authMode===`subscription`?r.authMode:`auto`,...xj(r),fastMode:r.fastMode??null,maxContextTokens:r.maxContextTokens??null,autoContext:r.autoContext!==!1,autoCompactWindow:r.autoCompactWindow??null,injectAgents:r.injectAgents!==!1,effectiveModelEnv:r.effectiveModelEnv??{}}),rows:Object.entries(r.modelMap??{}).map(([e,t])=>({id:Sj(),from:e,to:String(t)}))};if(t.aborted)throw Error(`Claude Code request aborted`);return n===dM(s)?(so(s,a),a):{...a,superseded:!0}},[e,s,i]),D=uo(c,[e],E,{isEmpty:()=>!1,enabled:t,initialData:u??void 0,initialDataCachedAt:l?.cachedAt??null,staleAfterMs:6e4}),O=D.state,[k,A]=(0,Z.useState)(O.data);if(O.data!==k){A(O.data);let e=O.data;e&&!e.superseded&&f(t=>oM(t,{state:e.state,rows:e.rows}))}let M=O.data??u,N=d?.draft.state??M?.state??null,P=d?.draft.rows??M?.rows??[],F=d!==null&&nM(d.draft,d.baseline),I=e=>{f(t=>t&&{...t,draft:{...t.draft,state:e},adoptNextRead:!1})},L=e=>{f(t=>t&&{...t,draft:{...t.draft,rows:e},adoptNextRead:!1})},R=e=>{let t=oo(s)?.data;t&&so(s,{...t,state:{...t.state,...e}}),hM(s,{kind:`live`,fields:e},pM)},[z]=(0,Z.useState)(()=>Symbol(`claude-code-page`));(0,Z.useEffect)(()=>{let e=(e,t)=>{if(e.kind===`live`){let{fields:t}=e;f(e=>e&&{...e,draft:{...e.draft,state:{...e.draft.state,...t}},baseline:{...e.baseline,state:{...e.baseline.state,...t}}})}else if(t!==z){let{copy:t}=e;f(e=>oM(e,t))}},t=mM.get(s)??new Set;return t.add(e),mM.set(s,t),()=>{t.delete(e)}},[s,z]);let B=(0,Z.useMemo)(()=>bj(N?.available,i(`claude.smallFastModelUnsetOption`)),[N?.available,i]),V=(0,Z.useMemo)(()=>{let e=[1e5,2e5,25e4,3e5,35e4,4e5,5e5,6e5,75e4,Cj,9e5,1e6].sort((e,t)=>e-t),t=N?.autoCompactWindow??null,n=t!==null&&!e.includes(t)?[...e,t].sort((e,t)=>e-t):e;return[{value:``,label:i(`claude.autoCompactDefault`,{value:wj(Cj,o)})},...n.map(e=>({value:String(e),label:wj(e,o)}))]},[N?.autoCompactWindow,i,o]),H=async()=>{N&&(v(``),await S(!N.enabled,e=>{fM(s),R({enabled:e}),D.refresh()},e=>{b(!1),v(e instanceof Error&&e.message?e.message:i(`claude.networkError`))}))},U=async()=>{if(!N||T.current)return;T.current=!0,w(!0),v(``);let t=!N.cliFirstParty;try{let n=await fetch(`${e}/api/claude-code`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({cliFirstParty:t})});if(!n.ok){let e=await n.json().catch(()=>null),t={intercept_disabled:`claude.firstParty.refusal.interceptDisabled`,intercept_unavailable:`claude.firstParty.refusal.interceptUnavailable`,foreign_env:`claude.firstParty.refusal.foreignEnv`,ca_unavailable:`claude.firstParty.refusal.caUnavailable`,unreadable:`claude.firstParty.refusal.unreadable`,write_failed:`claude.firstParty.refusal.writeFailed`},r=e?.code&&e.code in t?t[e.code]:`claude.saveFailed`;throw Error(e?.code&&[`disabled`,`client_role`,`ephemeral_port`,`port_in_use`,`port_mismatch`,`stopped`,`failed`].includes(e.code)?i(gj(e.code),{port:e.port??``,bound:e.bound??``,configured:e.configured??``}):i(r))}await vn(n,i(`claude.saveFailed`)),fM(s),R({cliFirstParty:t}),D.refresh()}catch(e){b(!1),v(e instanceof Error&&e.message?e.message:i(`claude.networkError`))}finally{T.current=!1,w(!1)}},ee=async()=>{if(!N||!d||p)return;let t=d.draft;v(``),g(``),m(!0),f(e=>e&&{...e,savePending:!0}),fM(s);try{await vn(await fetch(`${e}/api/claude-code`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(eM(t.state,t.rows))}),i(`claude.saveFailed`)),fM(s);let n=oo(s)?.data,r=sM(n?.state??t.state,t);so(s,r),hM(s,{kind:`saved`,copy:r},z),f(e=>cM(e,t)),b(!0),g(``),v(i(`claude.saved`)),D.refresh()}catch(e){f(e=>e&&{...e,savePending:!1}),b(!1),g(e instanceof Error&&e.message?e.message:i(`claude.networkError`))}finally{m(!1)}},W=()=>{v(``),g(``),f(e=>e&&{draft:{state:aM(e.draft.state,e.baseline.state),rows:e.baseline.rows},baseline:e.baseline,adoptNextRead:!1})};if(O.kind===`disabled`&&!M)return null;if(O.showSkeleton&&!M)return(0,Q.jsx)(lb,{label:i(`claude.loading`),rows:3});if(O.kind===`failed-cold`){let e=O.error instanceof Error?O.error.message:i(`claude.loadFail`);return(0,Q.jsxs)(`div`,{className:`claudecode-workspace-shell`,children:[(0,Q.jsx)($,{tone:`err`,children:e}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>D.refresh(),children:i(`common.retry`)})]})}if(!N)return null;let te=(0,Q.jsxs)(`div`,{className:`setting-row claudecode-connection-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-label`,children:[(0,Q.jsx)(`span`,{className:`title`,id:`claudecode-connection-label`,children:i(`claude.enabledLabel`)}),(0,Q.jsx)(`span`,{className:`desc`,children:i(`claude.subtitle`)})]}),(0,Q.jsx)(ln,{on:N.enabled,onClick:()=>void H(),disabled:x,label:i(`claude.toggleAria`)})]});return(0,Q.jsxs)(`div`,{className:`claudecode-workspace-shell claudecode-doc`,children:[_&&(0,Q.jsx)($,{tone:y?`ok`:`err`,children:_}),O.showError&&(0,Q.jsx)($,{tone:`err`,children:i(`claude.loadFail`)}),(0,Q.jsx)(`div`,{className:`card claudecode-connection-card`,children:(0,Q.jsxs)(`div`,{className:`setting-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-label`,children:[(0,Q.jsx)(`span`,{className:`title`,id:`claudecode-first-party-label`,children:i(`claude.firstParty.label`)}),(0,Q.jsx)(`span`,{className:`desc`,children:i(`claude.firstParty.desc`)})]}),(0,Q.jsx)(ln,{on:N.cliFirstParty,onClick:()=>void U(),disabled:C,label:i(`claude.firstParty.aria`)})]})}),!N.interceptRunning&&(0,Q.jsx)(vj,{apiBase:e,reason:N.interceptReason,port:N.interceptFailurePort,onStarted:()=>D.refresh()}),N.cliFirstParty&&(0,Q.jsx)($,{tone:`warn`,children:i(`claude.firstParty.risk`)}),(()=>{let e=hj(N),t=e&&gM[e];return t?(0,Q.jsx)($,{tone:`warn`,children:i(t)}):null})(),(0,Q.jsx)(_M,{title:i(`claude.quickstart`),children:(0,Q.jsx)(Gj,{manualEnv:Mj(N)})}),(0,Q.jsx)(_M,{title:i(`claude.workspace.settings`),children:(0,Q.jsx)(Wj,{state:N,autoCompactOptions:V,availableModels:N.available??[],onStateChange:I})}),(0,Q.jsx)(_M,{title:i(`claude.tierDefaults.title`),children:(0,Q.jsx)(Zj,{state:N,options:B,onChange:I,apiBase:e,dirty:!!d&&nM(d.draft,d.baseline)})}),(0,Q.jsx)(_M,{title:i(`claude.smallFastModel`),children:(0,Q.jsx)(Hj,{value:N.smallFastModel,tierHaikuModel:N.tierModels?.haiku,options:B,onChange:e=>I({...N,smallFastModel:e})})}),(0,Q.jsx)(_M,{title:i(`claude.modelMap`),count:P.length,children:(0,Q.jsx)(Kj,{rows:P,onRowsChange:L})}),(0,Q.jsx)(_M,{title:i(`claude.aliases`),count:N.aliases.length,children:(0,Q.jsx)(Yj,{aliases:N.aliases})}),(0,Q.jsx)(`div`,{className:`card claudecode-master-card`,children:te}),(0,Q.jsxs)(`div`,{className:`ccw-savebar`,role:`region`,"aria-label":i(`claude.saveBar.label`),children:[h&&(0,Q.jsx)(`span`,{className:`ccw-savebar-error`,role:`alert`,children:h}),(0,Q.jsx)(`span`,{className:`ccw-savebar-state${F?` dirty`:``}`,"aria-live":`polite`,"aria-atomic":`true`,children:i(F?`claude.saveBar.dirty`:`claude.saveBar.clean`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:!F||p,onClick:W,children:i(`claude.saveBar.revert`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:p,onClick:()=>{ee()},children:i(`common.save`)})]})]})}function yM({apiBase:e,active:t=!0,embedded:r=!1}){let i=n();return(0,Q.jsxs)(`section`,{className:`claude-page${r?` claude-page--embedded`:``}`,children:[!r&&(0,Q.jsx)(`div`,{className:`page-head`,children:(0,Q.jsx)(`h2`,{children:i(`nav.claude`)})}),(0,Q.jsx)(`p`,{className:`page-sub`,children:i(`claude.pageSub`)}),(0,Q.jsx)(vM,{apiBase:e,active:t},e)]})}function bM(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 xM(e){return new Set(Object.keys(e))}function SM(e,t){return t!==null&&e===t}function CM(e){return e||(typeof localStorage>`u`?void 0:localStorage)}function wM(e){return{read(t){let n=CM(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=CM(n);if(r)try{r.setItem(e,JSON.stringify([...t]))}catch{}}}}function TM(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n}function EM(e){return e.label||e.route}function DM({apiBase:e,bindings:t,suggestions:n,models:i,onSaved:a}){let{t:o}=r(),[s,c]=(0,Z.useState)(``),[l,u]=(0,Z.useState)(``),[d,f]=(0,Z.useState)(null),[p,m]=(0,Z.useState)(null),h=(0,Z.useMemo)(()=>i.filter(e=>e.available),[i]),g=(0,Z.useMemo)(()=>new Set(Object.keys(t)),[t]),_=(0,Z.useMemo)(()=>n.filter(e=>!g.has(e)),[n,g]),v=(0,Z.useMemo)(()=>Object.entries(t).sort(([e],[t])=>e.localeCompare(t)),[t]),y=s.trim(),b=y.startsWith(`claude-`)&&l!==``&&d===null,x=async(t,n)=>{if(d===null){f(n),m(null);try{let n=await vn(await fetch(`${e}/api/claude-desktop/first-party-bindings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)}),o(`claudeDesktop.firstParty.bindings.saveFailed`));if(!n||n.ok!==!0||typeof n.modelBindings!=`object`||n.modelBindings===null)throw Error(o(`claudeDesktop.firstParty.bindings.saveFailed`));c(``),u(``),a(n.modelBindings)}catch(e){m(e instanceof Error?e.message:o(`claudeDesktop.firstParty.bindings.saveFailed`))}finally{f(null)}}};return(0,Q.jsxs)(`section`,{className:`claude-bindings`,"aria-labelledby":`claude-bindings-title`,children:[(0,Q.jsx)(`h3`,{id:`claude-bindings-title`,className:`claude-bindings-title`,children:o(`claudeDesktop.firstParty.bindings.title`)}),(0,Q.jsx)(`p`,{className:`claude-bindings-hint`,children:o(`claudeDesktop.firstParty.bindings.hint`)}),p&&(0,Q.jsx)($,{tone:`err`,children:p}),v.length===0?(0,Q.jsx)(`p`,{className:`claude-bindings-empty`,children:o(`claudeDesktop.firstParty.bindings.empty`)}):(0,Q.jsx)(`ul`,{className:`claude-bindings-list`,children:v.map(([e,t])=>{let n=h.some(e=>e.route===t);return(0,Q.jsxs)(`li`,{className:`claude-bindings-row`,children:[(0,Q.jsx)(`code`,{className:`claude-bindings-id`,title:e,children:e}),(0,Q.jsx)(Ye,{className:`claude-bindings-arrow`,width:12,height:12,"aria-hidden":`true`}),(0,Q.jsxs)(`select`,{className:`input claude-bindings-select`,"aria-label":o(`claudeDesktop.firstParty.bindings.routeLabel`),value:t,disabled:d!==null,onChange:t=>void x({set:{[e]:t.target.value}},e),children:[!n&&(0,Q.jsx)(`option`,{value:t,children:t}),h.map(e=>(0,Q.jsx)(`option`,{value:e.route,children:EM(e)},e.route))]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm claude-bindings-remove`,"aria-label":o(`claudeDesktop.firstParty.bindings.remove`,{id:e}),disabled:d!==null,onClick:()=>void x({remove:[e]},e),children:(0,Q.jsx)(xe,{width:12,height:12,"aria-hidden":`true`})})]},e)})}),(0,Q.jsxs)(`div`,{className:`claude-bindings-add`,children:[(0,Q.jsx)(`input`,{className:`input claude-bindings-input`,type:`text`,list:`claude-bindings-suggestions`,"aria-label":o(`claudeDesktop.firstParty.bindings.pickerLabel`),placeholder:o(`claudeDesktop.firstParty.bindings.pickerPlaceholder`),value:s,disabled:d!==null,onChange:e=>c(e.target.value)}),(0,Q.jsx)(`datalist`,{id:`claude-bindings-suggestions`,children:_.map(e=>(0,Q.jsx)(`option`,{value:e},e))}),(0,Q.jsxs)(`select`,{className:`input claude-bindings-select`,"aria-label":o(`claudeDesktop.firstParty.bindings.routeLabel`),value:l,disabled:d!==null,onChange:e=>u(e.target.value),children:[(0,Q.jsx)(`option`,{value:``,children:o(`claudeDesktop.firstParty.bindings.routePlaceholder`)}),h.map(e=>(0,Q.jsx)(`option`,{value:e.route,children:EM(e)},e.route))]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:!b,onClick:()=>void x({set:{[y]:l}},y),children:o(d!==null&&d===y?`common.saving`:`claudeDesktop.firstParty.bindings.add`)})]})]})}function OM(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.desired==`boolean`&&typeof t.supported==`boolean`&&[`trusted`,`untrusted`,`unsupported`,`unknown`].includes(t.trust)&&[`absent`,`applied`,`not_selected`,`unsafe`].includes(t.profile)&&typeof t.listenerReady==`boolean`&&typeof t.effective==`boolean`&&[`active`,`restart_required`,`unsupported_platform`,`not_first_party`,`integration_off`,`disabled`,`proxy_unavailable`,`mode_not_committed`,`trust_pending`,`trust_declined`,`profile_failed`].includes(t.reason)&&typeof t.models==`number`&&Number.isFinite(t.models)&&t.models>=0&&(t.snapshotAt===null||typeof t.snapshotAt==`number`)&&(t.lastBootstrapAt===null||typeof t.lastBootstrapAt==`number`)&&(t.hint===void 0||typeof t.hint==`string`)&&(t.residual===void 0||Array.isArray(t.residual)&&t.residual.every(e=>typeof e==`string`))}function kM(e){switch(e){case`active`:return`claudeDesktop.picker.state.active`;case`restart_required`:return`claudeDesktop.picker.state.restart`;case`trust_pending`:return`claudeDesktop.picker.state.trustPending`;case`trust_declined`:return`claudeDesktop.picker.state.trustDeclined`;case`proxy_unavailable`:return`claudeDesktop.picker.state.proxyUnavailable`;case`unsupported_platform`:return`claudeDesktop.picker.state.unsupported`;case`profile_failed`:return`claudeDesktop.picker.state.profileFailed`;case`not_first_party`:case`integration_off`:case`disabled`:case`mode_not_committed`:return`claudeDesktop.picker.state.notFirstParty`}}function AM({apiBase:e,picker:t,onUpdated:n,pickerReason:i,pickerFailurePort:a}){let{t:o}=r(),[s,c]=(0,Z.useState)(null),[l,u]=(0,Z.useState)(!1),[d,f]=(0,Z.useState)(null),p=s??t,m=async()=>{if(!l){u(!0),f(null);try{let t=await fetch(`${e}/api/claude-desktop/picker`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({enabled:!p.desired,persist:!0})}),r;if(t.ok)r=await vn(t,o(`claudeDesktop.updateFailed`));else{try{r=await t.json()}catch{throw Error(o(`claudeDesktop.updateFailed`))}if(!r.picker)throw Error(o(gj(r.reason),{port:r.port??``}))}if(!r||r.ok!==!0&&!r.picker||!r.picker||!OM(r.picker))throw Error(o(`claudeDesktop.updateFailed`));c(r.picker),n?.(r.picker)}catch(e){f(e instanceof Error?e.message:o(`claudeDesktop.updateFailed`))}finally{u(!1)}}};return(0,Q.jsxs)(`section`,{className:`claude-picker`,"aria-labelledby":`claude-picker-title`,children:[!p.listenerReady&&i&&(0,Q.jsx)(`span`,{role:`status`,children:o(gj(i===`port_in_use`&&!a?`failed`:i),{port:a??``})}),!p.listenerReady&&!i&&(0,Q.jsx)(vj,{apiBase:e,onStarted:()=>{c(null),n?.(p)}}),(0,Q.jsxs)(`div`,{className:`claude-picker-header`,children:[(0,Q.jsxs)(`div`,{className:`claude-picker-copy`,children:[(0,Q.jsx)(`h3`,{id:`claude-picker-title`,className:`claude-picker-title`,children:o(`claudeDesktop.picker.title`)}),(0,Q.jsx)(`p`,{className:`claude-picker-hint`,children:o(`claudeDesktop.picker.hint`)})]}),(0,Q.jsx)(`button`,{type:`button`,role:`switch`,className:`toggle ${p.desired?`on`:``}`,"aria-checked":p.desired,"aria-label":o(`claudeDesktop.picker.toggle`),disabled:l,onClick:()=>void m(),children:(0,Q.jsx)(`span`,{className:`toggle-knob`})})]}),d&&(0,Q.jsx)($,{tone:`err`,children:d}),(0,Q.jsxs)(`p`,{className:`claude-picker-state claude-picker-state-${p.reason}`,"aria-live":`polite`,children:[(0,Q.jsx)(`span`,{className:`claude-picker-state-dot`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{children:o(kM(p.reason))}),p.reason===`trust_pending`&&p.hint&&(0,Q.jsx)(`code`,{children:p.hint})]}),(0,Q.jsx)(`p`,{className:`claude-picker-models`,children:o(`claudeDesktop.picker.models`,{count:p.models})}),(0,Q.jsx)(`p`,{className:`claude-picker-offline-note`,role:`note`,children:o(`claudeDesktop.picker.offlineNote`)})]})}var jM=[`opus`,`fable`,`sonnet`,`haiku`];function MM(e,t,n,r){let i=e.assignments[t];if(!i)return e;if(i.family===n)return!r||e.defaults[n]===t?e:{...e,defaults:{...e.defaults,[n]:t}};let a={...e.assignments,[t]:{...i,family:n}},o={...e.defaults};return o[i.family]===t&&(o[i.family]=Object.keys(a).filter(e=>e!==t&&a[e].family===i.family).sort()[0]??null),(r||o[n]===null)&&(o[n]=t),{...e,assignments:a,defaults:o}}function NM(e,t){let n=Object.fromEntries(jM.map(e=>[e,[]]));for(let r of e)r.available&&n[t.assignments[r.route]?.family??`opus`].push(r.route);let r={};for(let e of jM){let i=n[e].toSorted(),a=t.defaults[e];r[e]=a&&i.includes(a)?a:i[0]??null}return r}function PM(e,t,n){return e.filter(e=>(t.assignments[e.route]?.family??`opus`)===n).length}function FM(e,t,n){return e.defaults[n]??t[n]??``}function IM(e,t){return e.filter(e=>e.available&&e.route!==t).sort((e,t)=>e.label.localeCompare(t.label)||e.route.localeCompare(t.route))}function LM(e,t,n){let r=e=>e===t?0:e===n?1:2;return e.toSorted((e,t)=>r(e.route)-r(t.route)||e.label.localeCompare(t.label)||e.route.localeCompare(t.route))}var RM=wM(`ocx.claudeDesktop.collapsedFamilies.v2`),zM=[`first-party`,`gateway`];function BM(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.desired==`boolean`&&typeof t.supported==`boolean`&&[`trusted`,`untrusted`,`unsupported`,`unknown`].includes(t.trust)&&[`absent`,`applied`,`not_selected`,`unsafe`].includes(t.profile)&&typeof t.listenerReady==`boolean`&&typeof t.effective==`boolean`&&[`active`,`restart_required`,`unsupported_platform`,`not_first_party`,`integration_off`,`disabled`,`proxy_unavailable`,`mode_not_committed`,`trust_pending`,`trust_declined`,`profile_failed`].includes(t.reason)&&typeof t.models==`number`&&Number.isFinite(t.models)&&t.models>=0&&(t.snapshotAt===null||typeof t.snapshotAt==`number`)&&(t.lastBootstrapAt===null||typeof t.lastBootstrapAt==`number`)&&(t.hint===void 0||typeof t.hint==`string`)&&(t.residual===void 0||Array.isArray(t.residual)&&t.residual.every(e=>typeof e==`string`))}function VM(e){if(typeof e!=`object`||!e)return!1;let t=e,n=t.health;if(t.mode!==void 0&&!zM.includes(t.mode))return!1;if(t.riskWarning!==void 0&&t.riskWarning!==null){let e=t.riskWarning;if(typeof e!=`object`||typeof e.code!=`string`||typeof e.message!=`string`)return!1}if(t.firstParty!==void 0){let e=t.firstParty;if(typeof e!=`object`||!e||typeof e.applied!=`boolean`||typeof e.stale!=`boolean`||typeof e.interceptEnabled!=`boolean`||typeof e.interceptRunning!=`boolean`||typeof e.proxyPort!=`number`||typeof e.caCertPath!=`string`||e.picker!==void 0&&!BM(e.picker))return!1;if(e.modelBindings!==void 0){let t=e.modelBindings;if(typeof t!=`object`||!t||Array.isArray(t)||Object.values(t).some(e=>typeof e!=`string`))return!1}if(e.pickerSuggestions!==void 0&&(!Array.isArray(e.pickerSuggestions)||e.pickerSuggestions.some(e=>typeof e!=`string`)))return!1}return typeof t.desiredEnabled==`boolean`&&typeof t.applied==`boolean`&&(t.appliedAt===null||typeof t.appliedAt==`string`)&&typeof t.stale==`boolean`&&typeof n==`object`&&!!n&&(n.lastRequestAt===null||typeof n.lastRequestAt==`string`)&&typeof n.requestCount==`number`&&typeof n.errorCount==`number`}var HM={opus:`claudeDesktop.family.opus`,fable:`claudeDesktop.family.fable`,sonnet:`claudeDesktop.family.sonnet`,haiku:`claudeDesktop.family.haiku`};function UM(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 WM(e){let t={...e.profile.assignments};for(let n of e.models){let e=t[n.route]??n.assignment;t[n.route]={family:jM.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 GM(e,t){return e&&typeof e==`object`&&`error`in e&&typeof e.error==`string`?e.error:t}var KM=`⁣route⁣`;function qM({route:e,t}){let[n=``,r=``]=t(`claudeDesktop.roles.unavailableOption`,{route:KM}).split(KM);return(0,Q.jsxs)(`span`,{className:`claude-role-option`,children:[n&&(0,Q.jsx)(`span`,{className:`claude-role-option__status`,children:n}),(0,Q.jsx)(`span`,{className:`claude-role-option__route`,children:e}),r&&(0,Q.jsx)(`span`,{className:`claude-role-option__status`,children:r})]})}function JM(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 YM(e){return oo(e)?.data??null}function XM(e){return oo(e)?.cachedAt??null}function ZM(e){let t=YM(e);return{held:t,data:t?.data??null,profile:t?.profile??null,savedProfile:t?.profile?UM(t.profile):null,destinations:t?.data?Object.fromEntries(t.data.models.map(e=>[e.route,t.profile.assignments[e.route]?.family??`opus`])):{}}}function QM({apiBase:e,active:t=!0}){let{t:n,locale:i}=r(),a=j.find(e=>e.code===i)?.htmlLang,o=`ocx.claude-desktop.v1:${e}`,s=`claude-desktop:${e}`,c=(0,Z.useMemo)(()=>ZM(o),[o]),[l,u]=(0,Z.useState)(()=>c.profile),[d,f]=(0,Z.useState)(()=>c.savedProfile),[p,m]=(0,Z.useState)(()=>c.destinations),[h,g]=(0,Z.useState)(null),[_,v]=(0,Z.useState)(``),[y,b]=(0,Z.useState)(null),[x,S]=(0,Z.useState)({}),[C,w]=(0,Z.useState)({}),[T,E]=(0,Z.useState)(()=>RM.read()??new Set(jM)),[D,O]=(0,Z.useState)({}),[k,A]=(0,Z.useState)(!1),[M,N]=(0,Z.useState)(6),[P,F]=(0,Z.useState)(null),I=(0,Z.useRef)(null),L=(0,Z.useCallback)(async t=>{let r=await vn(await fetch(`${e}/api/claude-desktop`,{signal:t}),n(`claudeDesktop.loadFail`));if(!r||!(`profile`in r)||!(`models`in r))throw Error(GM(r,n(`claudeDesktop.loadFail`)));let i=WM(r),a={data:r,profile:i};if(t.aborted)throw Error(`Claude Desktop request aborted`);if(u(i),f(UM(i)),m(Object.fromEntries(r.models.map(e=>[e.route,i.assignments[e.route]?.family??`opus`]))),RM.read()===null){let e=Object.fromEntries(jM.map(e=>[e,0]));for(let t of r.models)e[i.assignments[t.route]?.family??`opus`]+=1;E(xM(e))}return so(o,a),a},[e,o,n,m,u,f]),R=uo(s,[e],L,{isEmpty:()=>!1,enabled:t,initialData:c.held??void 0,initialDataCachedAt:XM(o),staleAfterMs:6e4}),z=R.state,B=z.data??(c.data&&c.profile?{data:c.data,profile:c.profile}:null),V=B?.data??null,H=l??B?.profile??null,U=d??B?.profile??null,ee=B?Object.fromEntries(B.data.models.map(e=>[e.route,B.profile.assignments[e.route]?.family??`opus`])):{},W=Object.keys(p).length>0?p:ee,te=(0,Z.useMemo)(()=>H!==null&&U!==null&&JSON.stringify(H)!==JSON.stringify(U),[H,U]),G=(0,Z.useMemo)(()=>{let e=Object.fromEntries(jM.map(e=>[e,[]]));if(!V||!H)return e;for(let t of V.models)e[H.assignments[t.route]?.family??`opus`].push(t);return e},[V,H]),ne=(0,Z.useMemo)(()=>V&&H?NM(V.models,H):{opus:null,fable:null,sonnet:null,haiku:null},[V,H]),K=`ocx.claude-desktop.status.v1:${e}`,re=`claude-desktop-status:${e}`,q=oo(K),J=q&&VM(q.data)?q.data:null,Y=uo(re,[e],async t=>{let n=await yn(await fetch(`${e}/api/claude-desktop/status`,{signal:t}));if(!VM(n))throw Error(`Claude Desktop status unavailable`);return so(K,n),n},{isEmpty:()=>!1,pollMs:5e3,enabled:t,initialData:J??void 0}),ie=Y.state,X=ie.data??J,ae=ie.showError,oe=X!==null,se=oe||ae,ce=X?.mode??`gateway`,le=P??ce,ue=oe&&le!==ce,de=X?.firstParty?.modelBindings,fe=de?JSON.stringify(de):null,[pe,me]=(0,Z.useState)(null),[he,ge]=(0,Z.useState)(fe);he!==fe&&(ge(fe),me(null));let _e=pe??de??{},ve=(0,Z.useMemo)(()=>X?.firstParty?.pickerSuggestions??[],[X]),ye=(e,t,r=!1)=>{H&&(r||H.assignments[e]?.family!==t)&&(u(n=>n&&MM(n,e,t,r)),m(n=>({...n,[e]:t})),v(n(`claudeDesktop.moved`,{route:e,family:n(HM[t])})))},be=e=>{let t=TM(T,e);RM.write(t),E(t)},xe=async t=>{if(H&&!y){b(`save`),g(null);try{await vn(await fetch(`${e}/api/claude-desktop`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({profile:H})}),n(`claudeDesktop.saveFailed`)),f(UM(H)),t?(b(`apply`),(await vn(await fetch(`${e}/api/claude-desktop/apply`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({mode:le})}),n(`claudeDesktop.applyFailed`)))?.saved===!1?(g({tone:`warn`,text:n(`claudeDesktop.appliedMarkerUnsaved`)}),v(n(`claudeDesktop.appliedMarkerUnsaved`))):(g({tone:`ok`,text:n(`claudeDesktop.savedApplied`)}),v(n(`claudeDesktop.savedAppliedAnnounce`))),F(null)):(g({tone:`ok`,text:n(`claudeDesktop.saved`)}),v(n(`claudeDesktop.savedAnnounce`))),Y.refresh()}catch(e){let t=e instanceof Error?e.message:n(`claudeDesktop.updateFailed`);g({tone:`err`,text:t}),v(t)}finally{b(null)}}},Se=()=>{if(!H)return;let e=URL.createObjectURL(new Blob([`${JSON.stringify(H,null,2)}\n`],{type:`application/json`})),t=document.createElement(`a`);t.href=e,t.download=`claude-desktop-profile.json`,t.click(),URL.revokeObjectURL(e),v(n(`claudeDesktop.exported`))},Ce=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(n(`claudeDesktop.importExpected`));let r=WM({...V,profile:e});u(r),g({tone:`ok`,text:n(`claudeDesktop.importReady`)}),v(n(`claudeDesktop.importedAnnounce`))}catch(e){let t=e instanceof Error?e.message:n(`claudeDesktop.importInvalid`);g({tone:`err`,text:t}),v(n(`claudeDesktop.importFailed`,{error:t}))}},we=(e,t)=>{e.preventDefault();let n=e.dataTransfer.getData(`text/plain`);n&&ye(n,t)};if(z.kind===`disabled`&&!B)return null;if(z.showSkeleton&&!B)return(0,Q.jsx)(lb,{label:n(`claudeDesktop.loading`),rows:4});if(z.kind===`failed-cold`){let e=z.error instanceof Error?z.error.message:n(`claudeDesktop.loadFail`);return(0,Q.jsxs)(`div`,{className:`claude-desktop-error`,children:[(0,Q.jsx)($,{tone:`err`,children:e}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>R.refresh(),children:n(`claudeDesktop.retry`)})]})}if(!V||!H)return null;let Te=FM(H,ne,`opus`),Ee=FM(H,ne,`haiku`),De=new Map(V.models.map(e=>[e.route,e])),Oe=(e,t,r)=>{let i=IM(V.models,t||null).map(e=>({value:e.route,label:e.label}));if(e&&!i.some(t=>t.value===e)){let t=De.get(e);i.unshift({value:e,label:t?.available===!1||!t?(0,Q.jsx)(qM,{route:e,t:n}):e})}return r?i.unshift({value:``,label:n(`claudeDesktop.roles.unset`)}):e||i.unshift({value:``,label:n(`claudeDesktop.roles.pick`)}),i},ke=e=>{if(!e)return;let t=De.get(e);return t?.available?t.label:n(`claudeDesktop.roles.unavailableOption`,{route:e})},Ae=LM(V.models,Te||null,Ee||null),je=PM(V.models,H,`haiku`)===0;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`claude-desktop-toolbar`,children:(0,Q.jsx)(`p`,{className:`claude-panel-lead`,children:n(`claudeDesktop.subtitle`,{port:V.port})})}),(0,Q.jsxs)(`fieldset`,{className:`claude-mode-picker`,disabled:y!==null||!se,children:[(0,Q.jsx)(`legend`,{children:n(`claudeDesktop.mode.legend`)}),zM.map(e=>(0,Q.jsxs)(`label`,{className:`claude-mode-option${se&&le===e?` active`:``}`,children:[(0,Q.jsx)(`input`,{type:`radio`,name:`claude-desktop-mode`,value:e,checked:se&&le===e,onChange:()=>F(e)}),(0,Q.jsxs)(`span`,{className:`claude-mode-title`,children:[n(e===`first-party`?`claudeDesktop.mode.firstParty`:`claudeDesktop.mode.gateway`),e===`gateway`&&(0,Q.jsx)(`span`,{className:`claude-mode-default`,children:n(`claudeDesktop.mode.defaultBadge`)}),oe&&ce===e&&(0,Q.jsx)(`span`,{className:`claude-mode-current`,children:n(`claudeDesktop.mode.current`)})]}),(0,Q.jsx)(`span`,{className:`claude-mode-hint`,children:n(e===`first-party`?`claudeDesktop.mode.firstPartyHint`:`claudeDesktop.mode.gatewayHint`)})]},e)),le===`first-party`&&(0,Q.jsx)(`p`,{className:`claude-mode-risk`,role:`note`,children:n(`claudeDesktop.mode.firstPartyRisk`)}),ue&&(0,Q.jsx)(`span`,{className:`claude-mode-switch-note`,children:n(`claudeDesktop.mode.switchNote`)})]}),(0,Q.jsxs)(`div`,{className:`claude-status-bar ${ae&&!X?`not-applied`:X?X.desiredEnabled?ce===`gateway`&&X.activeProfile===!1?`not-applied`:X.stale?`stale`:X.applied?`applied`:`not-applied`:`not-applied`:`pending`}`,"aria-busy":!X&&!ae||void 0,children:[(0,Q.jsx)(`span`,{className:`claude-status-dot`}),(0,Q.jsx)(`span`,{children:ae&&!X?n(`claudeDesktop.loadFail`):X?X.desiredEnabled?ce===`gateway`&&X.activeProfile===!1?n(`claudeDesktop.status.notActiveProfile`):X.stale?n(`claudeDesktop.status.stale`):X.applied?n(ce===`first-party`?`claudeDesktop.status.appliedFirstParty`:`claudeDesktop.status.applied`):n(`claudeDesktop.status.notApplied`):n(`claudeDesktop.status.disabled`):n(`claudeDesktop.loading`)}),X?.firstParty&&ce===`first-party`&&X.desiredEnabled&&(0,Q.jsx)(`span`,{className:`claude-status-health`,children:X.firstParty.interceptRunning?n(`claudeDesktop.firstParty.proxyRunning`,{port:X.firstParty.proxyPort}):(0,Q.jsx)(vj,{apiBase:e,reason:X.firstParty.interceptReason,port:X.firstParty.proxyPort,onStarted:()=>Y.refresh()})}),X?.health.lastRequestAt&&(0,Q.jsxs)(`span`,{className:`claude-status-health`,children:[n(`claudeDesktop.health.lastRequest`),`:`,` `,new Date(X.health.lastRequestAt).toLocaleTimeString(a)]}),X&&X.health.requestCount>0&&(0,Q.jsx)(`span`,{className:`claude-status-health`,children:n(`claudeDesktop.health.stats`,{count:X.health.requestCount,errors:X.health.errorCount})}),(0,Q.jsxs)(`span`,{className:`claude-status-actions`,children:[(0,Q.jsx)(`span`,{className:`claude-dirty${te?` active`:``}`,children:n(te?`claudeDesktop.unsaved`:`claudeDesktop.upToDate`)}),(0,Q.jsxs)(`span`,{className:`claude-save-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:!te||y!==null,onClick:()=>void xe(!1),children:n(y===`save`?`claudeDesktop.saving`:`common.save`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:y!==null,onClick:()=>void xe(!0),children:y===`apply`?n(`claudeDesktop.applying`):y===`save`?n(`claudeDesktop.saving`):X?.desiredEnabled===!1?n(`claudeDesktop.enableApply`):n(ue?`claudeDesktop.switchModeApply`:`claudeDesktop.saveApply`)})]})]})]}),X?.riskWarning&&le!==`first-party`&&(0,Q.jsx)(`p`,{className:`claude-mode-risk`,role:`note`,children:n(`claudeDesktop.mode.firstPartyRisk`)}),(0,Q.jsx)(`div`,{className:`sr-only`,"aria-live":`polite`,"aria-atomic":`true`,children:_}),h&&(0,Q.jsx)($,{tone:h.tone,children:h.text}),z.showError&&(0,Q.jsx)($,{tone:`err`,children:n(`claudeDesktop.loadFail`)}),ae&&X&&(0,Q.jsx)($,{tone:`err`,children:n(`claudeDesktop.loadFail`)}),ce===`first-party`&&X?.firstParty?.picker&&(0,Q.jsx)(AM,{apiBase:e,picker:X.firstParty.picker,pickerReason:X.firstParty.pickerReason,pickerFailurePort:X.firstParty.pickerFailurePort,onUpdated:()=>void Y.refresh()},`${X.firstParty.picker.reason}:${X.firstParty.picker.desired}:${X.firstParty.picker.effective}:${X.firstParty.picker.models}:${X.firstParty.picker.hint??``}`),ce===`first-party`&&(0,Q.jsx)(DM,{apiBase:e,bindings:_e,suggestions:ve,models:V.models,onSaved:e=>{me(e),Y.refresh()}}),V.models.length===0&&(0,Q.jsx)(fn,{title:n(`claudeDesktop.emptyTitle`),children:n(`claudeDesktop.emptyHint`)}),V.models.length>0&&(0,Q.jsxs)(`section`,{className:`card claude-desktop-roles`,"aria-labelledby":`claude-desktop-roles-title`,children:[(0,Q.jsx)(`h3`,{className:`claude-desktop-section-title`,id:`claude-desktop-roles-title`,children:n(`claudeDesktop.roles.title`)}),ce===`first-party`&&(0,Q.jsx)(`p`,{className:`claude-desktop-roles-scope`,children:n(`claudeDesktop.roles.gatewayScope`)}),(0,Q.jsxs)(`div`,{className:`setting-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-label`,children:[(0,Q.jsx)(`span`,{className:`title`,children:n(`claudeDesktop.roles.default`)}),(0,Q.jsx)(`span`,{className:`desc`,children:n(`claudeDesktop.roles.defaultDesc`)})]}),(0,Q.jsx)(`div`,{className:`setting-controls`,children:(0,Q.jsx)(dn,{value:Te,options:Oe(Te,Ee,!1),onChange:e=>{e&&ye(e,`opus`,!0)},label:n(`claudeDesktop.roles.default`),title:ke(Te),disabled:y!==null,style:{minWidth:240},align:`right`,portal:!0})})]}),(0,Q.jsxs)(`div`,{className:`setting-row`,children:[(0,Q.jsxs)(`div`,{className:`setting-label`,children:[(0,Q.jsx)(`span`,{className:`title`,children:n(`claudeDesktop.roles.quick`)}),(0,Q.jsx)(`span`,{className:`desc`,children:n(`claudeDesktop.roles.quickDesc`)})]}),(0,Q.jsx)(`div`,{className:`setting-controls`,children:(0,Q.jsx)(dn,{value:Ee,options:Oe(Ee,Te,je),onChange:e=>{e&&ye(e,`haiku`,!0)},label:n(`claudeDesktop.roles.quick`),title:ke(Ee),disabled:y!==null,style:{minWidth:240},align:`right`,portal:!0})})]})]}),(0,Q.jsxs)(`section`,{className:`claude-desktop-list`,"aria-labelledby":`claude-desktop-list-title`,children:[(0,Q.jsxs)(`div`,{className:`claude-desktop-list-head`,children:[(0,Q.jsxs)(`h3`,{className:`claude-desktop-section-title`,id:`claude-desktop-list-title`,children:[n(`claudeDesktop.roles.listTitle`),(0,Q.jsx)(`span`,{className:`count`,children:V.models.length})]}),(0,Q.jsxs)(`div`,{className:`claude-profile-tools`,children:[(0,Q.jsx)(`input`,{ref:I,type:`file`,accept:`application/json,.json`,hidden:!0,onChange:e=>void Ce(e)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>I.current?.click(),children:n(`claudeDesktop.importJson`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:Se,children:n(`claudeDesktop.exportJson`)})]})]}),V.models.length>0&&(0,Q.jsx)(`p`,{className:`claude-desktop-list-hint`,children:n(`claudeDesktop.roles.listHint`)}),V.models.length>0&&(0,Q.jsx)(`ul`,{className:`card claude-desktop-list-rows`,children:Ae.slice(0,M).map(e=>{let t=JM(e.contextWindow,n);return(0,Q.jsxs)(`li`,{className:`claude-desktop-list-row`,children:[(0,Q.jsxs)(`span`,{className:`claude-desktop-list-names`,children:[(0,Q.jsx)(`strong`,{title:e.label,children:e.label}),e.label!==e.route&&(0,Q.jsx)(`code`,{title:e.route,children:e.route})]}),e.route===Te&&(0,Q.jsx)(`span`,{className:`claude-row-default`,children:n(`claudeDesktop.defaultBadge`)}),e.route===Ee&&(0,Q.jsx)(`span`,{className:`claude-row-default claude-row-quick`,children:n(`claudeDesktop.roles.quickBadge`)}),t&&(0,Q.jsx)(`span`,{className:`claude-model-context`,children:t}),e.supports1m===!0&&(0,Q.jsx)(`span`,{className:`claude-1m-chip`,children:n(`claudeDesktop.supports1m`)}),!e.available&&(0,Q.jsx)(`span`,{className:`badge badge-muted`,children:n(`claudeDesktop.unavailable`)})]},e.route)})}),Ae.length>M&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm claude-lane-more`,onClick:()=>N(e=>e+6),children:n(`models.showMore`,{n:Ae.length-M})})]}),(0,Q.jsxs)(`details`,{className:`claude-desktop-advanced`,open:k,onToggle:e=>A(e.currentTarget.open),children:[(0,Q.jsxs)(`summary`,{children:[(0,Q.jsxs)(`span`,{className:`claude-desktop-advanced-title`,children:[(0,Q.jsx)(Ye,{className:`ocx-chevron`,width:14,height:14,"aria-hidden":`true`,style:{transform:k?`rotate(90deg)`:`none`}}),n(`claudeDesktop.advanced.title`)]}),(0,Q.jsx)(`span`,{className:`claude-desktop-advanced-chips`,children:jM.map(e=>{let t=G[e].length,r=H.defaults[e],i=ne[e];return(0,Q.jsxs)(`span`,{className:`claude-desktop-advanced-chip`,children:[(0,Q.jsx)(`b`,{children:n(HM[e])}),i?(0,Q.jsx)(`code`,{title:i,children:i}):(0,Q.jsx)(`span`,{children:n(`claudeDesktop.advanced.empty`)}),t>0&&(0,Q.jsx)(`span`,{className:`claude-desktop-advanced-count`,children:t}),t>0&&r===null&&(0,Q.jsx)(`span`,{className:`claude-default-needed`,children:n(`claudeDesktop.chooseDefault`)}),i&&r!==null&&i!==r&&(0,Q.jsx)(`span`,{className:`claude-default-needed`,children:n(`claudeDesktop.temporaryDefault`)})]},e)})})]}),(0,Q.jsx)(`p`,{className:`claude-desktop-advanced-desc`,children:n(`claudeDesktop.advanced.desc`)}),(0,Q.jsx)(`div`,{className:`ocx-group-stack`,"aria-label":n(`claudeDesktop.assignmentsLabel`),children:jM.map(e=>{let t=G[e],r=bM(t,x[e]??``,C[e]??6),i=T.has(e),a=ne[e];return(0,Q.jsxs)(`section`,{className:`ocx-group${i?` collapsed`:``}`,"aria-labelledby":`claude-lane-${e}`,onDragOver:e=>e.preventDefault(),onDrop:t=>we(t,e),children:[(0,Q.jsxs)(`header`,{className:`ocx-group-head${i?``:` open`}`,children:[(0,Q.jsx)(`h3`,{id:`claude-lane-${e}`,className:`ocx-group-heading`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`ocx-group-toggle`,"aria-expanded":!i,"aria-controls":`claude-lane-body-${e}`,onClick:()=>be(e),children:[(0,Q.jsx)(Ye,{className:`ocx-chevron`,width:14,height:14,"aria-hidden":`true`,style:{transform:i?`none`:`rotate(90deg)`}}),(0,Q.jsx)(`span`,{className:`ocx-group-name`,children:n(HM[e])}),(0,Q.jsx)(`span`,{className:`ocx-group-count`,children:n(t.length===1?`claudeDesktop.modelCountOne`:`claudeDesktop.modelCountMany`,{count:t.length})}),a&&(0,Q.jsx)(`code`,{className:`claude-lane-default`,title:a,children:a})]})}),t.length>0&&H.defaults[e]===null&&(0,Q.jsx)(`span`,{className:`claude-default-needed`,children:n(`claudeDesktop.chooseDefault`)}),a&&a!==H.defaults[e]&&(0,Q.jsx)(`span`,{className:`claude-default-needed`,title:a,children:n(`claudeDesktop.temporaryDefault`)})]}),!i&&(0,Q.jsxs)(`div`,{id:`claude-lane-body-${e}`,children:[r.showSearch&&(0,Q.jsx)(`input`,{className:`input claude-lane-search`,type:`search`,placeholder:n(`models.search`),"aria-label":n(`models.search`),value:x[e]??``,onChange:t=>{let n=t.target.value;S(t=>({...t,[e]:n})),w(t=>({...t,[e]:6}))}}),(0,Q.jsxs)(`div`,{className:`claude-lane-models`,children:[t.length===0?(0,Q.jsx)(`div`,{className:`claude-lane-empty`,children:n(`claudeDesktop.laneEmpty`)}):r.noMatch?(0,Q.jsx)(`div`,{className:`claude-lane-empty`,children:n(`claudeDesktop.laneNoMatch`)}):r.shown.map(t=>{let r=H.assignments[t.route],i=JM(t.contextWindow,n),a=W[t.route]??`opus`,o=D[t.route]??SM(t.route,ne[e]);return(0,Q.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,Q.jsxs)(`button`,{type:`button`,className:`claude-model-summary`,"aria-expanded":o,"aria-controls":`claude-model-body-${t.route}`,onClick:()=>O(e=>({...e,[t.route]:!o})),children:[(0,Q.jsx)(Ye,{className:`ocx-chevron`,width:12,height:12,"aria-hidden":`true`,style:{transform:o?`rotate(90deg)`:`none`}}),(0,Q.jsxs)(`span`,{className:`claude-model-names`,children:[(0,Q.jsx)(`strong`,{title:t.label,children:t.label}),(0,Q.jsx)(`code`,{title:t.route,children:t.route})]}),i&&(0,Q.jsx)(`span`,{className:`claude-model-context`,children:i}),!i&&(0,Q.jsx)(`span`,{className:`claude-model-context claude-model-context-unknown`,children:n(`claudeDesktop.contextUnknown`)}),t.supports1m===!0&&(0,Q.jsx)(`span`,{className:`claude-1m-chip`,children:n(`claudeDesktop.supports1m`)}),t.effortSupported===!1&&(0,Q.jsx)(`span`,{className:`claude-effort-badge off`,children:n(`claudeDesktop.effort.displayOnly`)}),t.effortSupported===!0&&(0,Q.jsx)(`span`,{className:`claude-effort-badge on`,children:n(`claudeDesktop.effort.supported`)}),H.defaults[e]===t.route&&(0,Q.jsx)(`span`,{className:`claude-row-default`,children:n(`claudeDesktop.defaultBadge`)}),(0,Q.jsx)(`span`,{className:`badge ${t.available?`badge-green`:`badge-muted`}`,children:t.available?n(`claudeDesktop.available`):n(`claudeDesktop.unavailable`)})]}),o&&(0,Q.jsxs)(`div`,{className:`claude-model-body`,id:`claude-model-body-${t.route}`,children:[ne[e]===t.route&&H.defaults[e]!==t.route&&(0,Q.jsx)(`span`,{className:`claude-effective-default`,children:n(`claudeDesktop.temporaryDefault`)}),(0,Q.jsxs)(`div`,{className:`claude-field`,children:[(0,Q.jsx)(`span`,{children:n(`claudeDesktop.alias`)}),(0,Q.jsx)(`code`,{className:`claude-alias`,title:r.alias,children:r.alias})]}),(0,Q.jsxs)(`label`,{className:`claude-default-radio`,children:[(0,Q.jsx)(`input`,{type:`radio`,name:`default-${e}`,checked:H.defaults[e]===t.route,disabled:!t.available,onChange:()=>u(n=>n&&{...n,defaults:{...n.defaults,[e]:t.route}})}),n(`claudeDesktop.useAsDefault`,{family:n(HM[e])})]}),(0,Q.jsxs)(`div`,{className:`claude-move-row`,children:[(0,Q.jsx)(`label`,{htmlFor:`move-${t.route}`,children:n(`claudeDesktop.moveTo`)}),(0,Q.jsx)(`select`,{id:`move-${t.route}`,className:`input`,value:a,disabled:!t.available,onChange:e=>m(n=>({...n,[t.route]:e.target.value})),children:jM.map(e=>(0,Q.jsx)(`option`,{value:e,children:n(HM[e])},e))}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:!t.available||a===e,onClick:()=>ye(t.route,a),children:n(`claudeDesktop.move`)})]})]})]},t.route)}),r.hidden>0&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm claude-lane-more`,onClick:()=>w(t=>({...t,[e]:(t[e]??6)+6})),children:n(`models.showMore`,{n:r.hidden})})]})]})]},e)})})]})]})}function $M(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 eN=wM(`ocx.grok.collapsedGroups.v2`),tN=[{id:`native`,tkey:`grok.groupNative`},{id:`routed`,tkey:`grok.groupRouted`}],nN=new Set(tN.map(e=>e.id));function rN(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 iN({apiBase:e,active:t=!0}){let r=n(),i=`ocx.grok.status.v1:${e}`,a=oo(i),o=a?.data??null,[s,c]=(0,Z.useState)(null),[l,u]=(0,Z.useState)(()=>eN.read()??new Set(nN)),[d,f]=(0,Z.useState)(null),[p,m]=(0,Z.useState)(null),[h,g]=(0,Z.useState)(``),_=(0,Z.useCallback)(async t=>{let n=await vn(await fetch(`${e}/api/grok`,{signal:t}),r(`grok.loadFail`));if(!n)throw Error(r(`grok.loadFail`));let a={...n,candidates:n.candidates??[],excluded:n.excluded??[]};return so(i,a),a},[e,i,r]),v=`grok-status:${e}`,y=uo(v,[e],_,{isEmpty:()=>!1,initialData:o??void 0,initialDataCachedAt:a?.cachedAt??null,staleAfterMs:6e4,enabled:t}),{state:b}=y,x=y.refresh,S=b.data??o,C=(0,Z.useMemo)(()=>new Set(S?.excluded??[]),[S]),w=s??C,T=(0,Z.useMemo)(()=>s!==null&&(s.size!==C.size||[...s].some(e=>!C.has(e))),[s,C]),E=(0,Z.useMemo)(()=>new Map((S?.models??[]).map(e=>[e.id,e.alias])),[S]),D=e=>{let t=TM(l,e);eN.write(t),u(t)},O=e=>{let t=e?new Set(tN.map(e=>e.id)):new Set;eN.write(t),u(t)},k=(e,t)=>{c(n=>{let r=new Set(n??C);return t?r.delete(e):r.add(e),r})},A=async t=>{if(!d){f(`save`),m(null);try{await vn(await fetch(`${e}/api/grok/selection`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({excluded:[...w]})}),r(`grok.saveFailed`));let n=[...w];if(S&&Kt(v,{...S,excluded:n}),c(null),t){f(`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??r(`grok.applyFailed`))}let n=await t.json().catch(()=>({}));n.skippedReason?(m({tone:`err`,text:n.message??r(`grok.applySkipped`)}),g(n.message??r(`grok.applySkipped`))):(m({tone:`ok`,text:r(`grok.savedApplied`)}),g(r(`grok.savedApplied`))),await x()}else m({tone:`ok`,text:r(`grok.saved`)}),g(r(`grok.saved`)),S&&so(i,{...S,excluded:n})}catch(e){let t=e instanceof Error?e.message:r(`grok.saveFailed`);m({tone:`err`,text:t}),g(t)}finally{f(null)}}};if(b.showSkeleton&&!S)return(0,Q.jsx)(`section`,{className:`grok-page`,children:(0,Q.jsx)(lb,{label:r(`grok.loading`),rows:4})});if(b.kind===`failed-cold`){let e=b.error instanceof Error?b.error.message:r(`grok.loadFail`);return(0,Q.jsxs)(`section`,{className:`grok-page`,children:[(0,Q.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:e}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>x(),children:r(`common.retry`)})]})}return(0,Q.jsxs)(`section`,{className:`grok-page`,"aria-busy":b.refreshing||void 0,children:[(0,Q.jsx)(`h2`,{className:`page-title`,children:r(`grok.title`)}),(0,Q.jsx)(`p`,{className:`page-sub`,children:r(`grok.subtitle`)}),(0,Q.jsx)(`div`,{className:`sr-only`,"aria-live":`polite`,"aria-atomic":`true`,children:h}),p&&(0,Q.jsx)($,{tone:p.tone,children:p.text}),b.showError&&(0,Q.jsx)($,{tone:`err`,children:r(`grok.loadFail`)}),S&&S.candidates.length>0&&(0,Q.jsxs)(`div`,{className:`claude-profile-bar`,children:[(0,Q.jsx)(`span`,{className:`claude-dirty${T?` active`:``}`,children:r(T?`grok.unsaved`:`grok.upToDate`)}),(0,Q.jsxs)(`div`,{className:`claude-save-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:!T||d!==null,onClick:()=>void A(!1),children:r(d===`save`?`grok.saving`:`common.save`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!T||d!==null,onClick:()=>void A(!0),children:r(d===`apply`?`grok.applying`:d===`save`?`grok.saving`:`grok.saveApply`)})]})]}),S?.present?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`grok-endpoint`,children:[(0,Q.jsx)(`span`,{children:r(`grok.endpoint`)}),(0,Q.jsx)(`code`,{children:S.baseUrl??`—`})]}),(0,Q.jsx)(`p`,{className:`page-sub`,children:(0,Q.jsx)(`code`,{children:S.configPath})})]}):(0,Q.jsxs)(fn,{title:r(`grok.notConfiguredTitle`),children:[r(`grok.notConfiguredHint`),(0,Q.jsx)(`br`,{}),(0,Q.jsx)(`code`,{children:S?.configPath})]}),S&&S.candidates.length>0&&(0,Q.jsxs)(`div`,{className:`ocx-group-stack`,children:[(0,Q.jsxs)(`div`,{className:`row`,style:{gap:6,margin:`2px 0 10px`},children:[(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>O(!0),disabled:d!==null,children:[(0,Q.jsx)(Ye,{width:12,height:12,"aria-hidden":`true`}),` `,r(`models.collapseAll`)]}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>O(!1),disabled:d!==null,children:[(0,Q.jsx)(Ye,{width:12,height:12,"aria-hidden":`true`,style:{transform:`rotate(90deg)`}}),` `,r(`models.expandAll`)]})]}),tN.map(e=>{let t=$M(S.candidates,E,w,e.id);if(t.total===0)return null;let n=l.has(e.id);return(0,Q.jsxs)(`section`,{className:`ocx-group${n?` collapsed`:``}`,"aria-labelledby":`grok-group-${e.id}`,children:[(0,Q.jsx)(`header`,{className:`ocx-group-head${n?``:` open`}`,children:(0,Q.jsx)(`h3`,{id:`grok-group-${e.id}`,className:`ocx-group-heading`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`ocx-group-toggle`,"aria-expanded":!n,"aria-controls":`grok-group-body-${e.id}`,onClick:()=>D(e.id),children:[(0,Q.jsx)(Ye,{className:`ocx-chevron`,width:14,height:14,"aria-hidden":`true`,style:{transform:n?`none`:`rotate(90deg)`}}),(0,Q.jsx)(`span`,{className:`ocx-group-name`,children:r(e.tkey)}),(0,Q.jsx)(`span`,{className:`ocx-group-count`,children:r(`grok.enabledCount`,{on:t.enabled,total:t.total})})]})})}),!n&&(0,Q.jsx)(`div`,{id:`grok-group-body-${e.id}`,className:`grok-model-list`,children:t.rows.map(e=>(0,Q.jsxs)(`div`,{className:`grok-model-row`,children:[(0,Q.jsx)(ln,{on:e.enabled,onClick:()=>k(e.id,!e.enabled),disabled:d!==null,label:r(`grok.toggleModel`,{id:e.id})}),(0,Q.jsxs)(`span`,{className:`grok-model-names`,children:[(0,Q.jsx)(`strong`,{title:e.id,children:e.id}),(0,Q.jsx)(`code`,{title:e.alias??void 0,children:e.alias??`—`})]}),(0,Q.jsx)(`span`,{className:`claude-model-context`,children:rN(e.contextWindow,r)})]},e.id))})]},e.id)})]})]})}async function aN(e,t){try{let n=await fetch(`${e}/api/native-integrations/cursor`,{signal:t});if(!n.ok)return null;let r=await yn(n);return!r||typeof r!=`object`||!r.gateway||!r.privateInference?null:r}catch{return null}}async function oN(e,t){try{let n=await fetch(`${e}/api/native-integrations/cursor/local-installer`,{signal:t});if(!n.ok)return null;let r=await yn(n);return!r||typeof r!=`object`||typeof r.available!=`boolean`?null:r}catch{return null}}function sN({value:e,label:t}){let r=n(),[i,a]=(0,Z.useState)(!1),o=(0,Z.useRef)(null);(0,Z.useEffect)(()=>()=>{o.current!==null&&window.clearTimeout(o.current)},[]);let s=async()=>{try{await navigator.clipboard.writeText(e),a(!0),o.current!==null&&window.clearTimeout(o.current),o.current=window.setTimeout(()=>a(!1),1500)}catch{a(!1)}};return(0,Q.jsxs)(`div`,{className:`cursor-gateway-row`,children:[(0,Q.jsx)(`span`,{className:`cursor-gateway-label`,children:t}),(0,Q.jsx)(`code`,{className:`cursor-gateway-value`,children:e}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void s(),"aria-label":`${r(`integrations.cursor.copy`)} ${t}`,children:r(i?`integrations.cursor.copied`:`integrations.cursor.copy`)})]})}function cN({labelKey:e,installed:t,path:r,version:i}){let a=n();return(0,Q.jsxs)(`div`,{className:`cursor-detect-row`,"data-installed":t?`true`:`false`,children:[(0,Q.jsx)(`span`,{className:`cursor-detect-name`,children:a(e)}),(0,Q.jsx)(`span`,{className:`badge ${t?`badge-green`:`badge-muted`}`,children:a(t?`integrations.cursor.detected`:`integrations.cursor.notFound`)}),t&&r&&(0,Q.jsxs)(`span`,{className:`cursor-detect-path muted`,children:[i?`${i} · `:``,r]})]})}function lN({apiBase:e}){let t=n(),[r,i]=(0,Z.useState)(`idle`),[a,o]=(0,Z.useState)(null),s=(0,Z.useRef)(null);(0,Z.useEffect)(()=>()=>s.current?.abort(),[]);let c=async()=>{s.current?.abort();let t=new AbortController;s.current=t,i(`checking`);let n=await oN(e,t.signal);t.signal.aborted||(o(n),i(`done`))};return r===`done`&&a?.available&&a.url!==null?(0,Q.jsxs)(`span`,{"data-cursor-installer-hint":!0,children:[t(`integrations.cursor.installerIntro`,{version:a.version??t(`integrations.cursor.unknownVersion`)}),` `,(0,Q.jsx)(`a`,{href:a.url,target:`_blank`,rel:`noreferrer`,"data-cursor-installer-url":!0,children:t(`integrations.cursor.installerOpen`)}),`.`]}):(0,Q.jsxs)(Q.Fragment,{children:[r===`done`&&(0,Q.jsxs)(`span`,{"data-cursor-installer-unavailable":!0,children:[t(`integrations.cursor.installerUnavailable`),` `]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void c(),disabled:r===`checking`,"data-cursor-installer-check":!0,children:t(r===`checking`?`integrations.cursor.installerChecking`:`integrations.cursor.installerCheck`)})]})}function uN({apiBase:e,active:t}){let{t:n,locale:i}=r(),[a,o]=(0,Z.useState)(()=>Date.now()),s=(0,Z.useCallback)(async t=>{let n=await aN(e,t);if(!n)throw Error(`cursor status unavailable`);return o(Date.now()),n},[e]),c=uo(`integration-cursor-page:${e}`,[e],s,{isEmpty:()=>!1,enabled:t,pollMs:15e3,pauseWhenHidden:!0}),l=c.state.data??null,u=Vs(n);return(0,Q.jsxs)(`section`,{className:`integration-native-page cursor-page`,"aria-labelledby":`cursor-integration-title`,children:[(0,Q.jsx)(`h3`,{id:`cursor-integration-title`,children:n(`integrations.cursor.title`)}),(0,Q.jsx)(`p`,{children:n(`integrations.cursor.intro`)}),c.state.showError&&(0,Q.jsx)($,{tone:`err`,children:n(`integrations.cursor.unavailable`)}),!l&&!c.state.showError&&(0,Q.jsx)(lb,{label:n(`integrations.cursor.loading`),rows:4}),l&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`cursor-card`,children:[(0,Q.jsx)(`h4`,{children:n(`integrations.cursor.detection`)}),(0,Q.jsx)(cN,{labelKey:`integrations.cursor.privateInference`,installed:l.privateInference.installed,path:l.privateInference.path,version:l.privateInference.version}),(0,Q.jsx)(cN,{labelKey:`integrations.cursor.regular`,installed:l.regularCursor.installed,path:l.regularCursor.path,version:null}),!l.privateInference.installed&&(0,Q.jsxs)($,{tone:`warn`,children:[n(l.regularCursor.installed?`integrations.cursor.regularOnly`:`integrations.cursor.nothingFound`),` `,(0,Q.jsx)(`a`,{href:l.guideUrl,target:`_blank`,rel:`noreferrer`,"data-cursor-guide":`notice`,children:n(`integrations.cursor.guide`)}),l.regularCursor.installed&&(0,Q.jsxs)(Q.Fragment,{children:[` `,(0,Q.jsx)(`span`,{"data-cursor-installer":!0,children:(0,Q.jsx)(lN,{apiBase:e})})]})]})]}),(0,Q.jsxs)(`div`,{className:`cursor-card`,children:[(0,Q.jsx)(`h4`,{children:n(`integrations.cursor.gateway`)}),(0,Q.jsx)(`p`,{className:`muted`,children:n(`integrations.cursor.gatewayHint`)}),(0,Q.jsx)(sN,{label:n(`integrations.cursor.baseUrl`),value:l.gateway.baseUrl}),l.gateway.apiKeyMode===`placeholder`?(0,Q.jsx)(sN,{label:n(`integrations.cursor.apiKey`),value:l.gateway.placeholder}):(0,Q.jsxs)(`div`,{className:`cursor-gateway-row`,children:[(0,Q.jsx)(`span`,{className:`cursor-gateway-label`,children:n(`integrations.cursor.apiKey`)}),(0,Q.jsx)(`span`,{className:`cursor-gateway-value`,children:n(`integrations.cursor.apiKeyCredential`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>Xt(`integrations/keys`),children:n(`integrations.tab.keys`)})]})]}),(0,Q.jsxs)(`div`,{className:`cursor-card`,"data-seen":l.lastSeen?`true`:`false`,children:[(0,Q.jsx)(`h4`,{children:n(`integrations.cursor.connection`)}),l.lastSeen?(0,Q.jsx)(`p`,{children:(0,Q.jsx)(`span`,{className:`badge ${a-l.lastSeen.at<864e5?`badge-green`:`badge-muted`}`,children:n(`integrations.cursor.seen`,{time:Bs(l.lastSeen.at,u,a),ua:l.lastSeen.userAgent})})}):(0,Q.jsx)(`p`,{className:`muted`,children:n(`integrations.cursor.neverSeen`)})]}),(0,Q.jsxs)(`div`,{className:`cursor-card`,children:[(0,Q.jsx)(`h4`,{children:n(`integrations.cursor.models`)}),(0,Q.jsx)(`p`,{className:`muted`,children:l.effortTable.source===`bundle`?n(`integrations.cursor.ladderFromBundle`,{version:l.effortTable.version??n(`integrations.cursor.unknownVersion`)}):n(`integrations.cursor.ladderFromStatic`)}),(0,Q.jsxs)(`table`,{className:`cursor-model-table`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:n(`integrations.cursor.colModel`)}),(0,Q.jsx)(`th`,{children:n(`integrations.cursor.colReasoning`)}),(0,Q.jsx)(`th`,{children:n(`integrations.cursor.colContext`)})]})}),(0,Q.jsx)(`tbody`,{children:l.models.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`code`,{children:e.id})}),(0,Q.jsx)(`td`,{children:e.reasoning?e.reasoning.join(` · `):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.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,Q.jsx)(`span`,{className:`cursor-effort-rows`,children:n(e.effortRows.length===1?`integrations.cursor.effortRowsOne`:`integrations.cursor.effortRowsMany`,{n:e.effortRows.length})}):(0,Q.jsx)(`span`,{className:`cursor-effort-rows muted`,children:n(`integrations.cursor.effortRowsOff`)})]})}),(0,Q.jsx)(`td`,{children:e.context?`${q(e.context.defaultWindow,i)} · ${q(e.context.longWindow,i)}`:n(`integrations.cursor.singleWindow`)})]},e.id))})]}),l.models.some(e=>e.tableLess)&&(0,Q.jsx)(`p`,{className:`muted`,"data-cursor-tableless-hint":!0,children:n(`integrations.cursor.tableLessHint`)})]}),(0,Q.jsx)(`p`,{children:(0,Q.jsx)(`a`,{href:l.guideUrl,target:`_blank`,rel:`noreferrer`,children:n(`integrations.cursor.guide`)})})]})]})}var dN={"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`},fN={"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 pN({state:e,installed:t,id:r}){let i=n(),a=e===`unknown`||e===`not-installed`||t?e:`not-installed`;return(0,Q.jsx)(`span`,{id:r,className:fN[a],"data-integration-state":a,children:i(dN[a])})}var mN={apply:`integrations.plan.operation.apply`,overwrite:`integrations.plan.operation.overwrite`,disable:`integrations.plan.operation.disable`,restore:`integrations.plan.operation.restore`},hN={add:`integrations.plan.change.add`,replace:`integrations.plan.change.replace`,remove:`integrations.plan.change.remove`,snapshot:`integrations.plan.change.snapshot`,ownership:`integrations.plan.change.ownership`,journal:`integrations.plan.change.journal`},gN={none:`integrations.plan.foreign.none`,unowned:`integrations.plan.foreign.unowned`,"foreign-edit":`integrations.plan.foreign.foreignEdit`,drift:`integrations.plan.foreign.drift`},_N={not_installed:`integrations.plan.refusal.notInstalled`,conflict:`integrations.plan.refusal.conflict`,unsafe:`integrations.plan.refusal.unsafe`,non_loopback:`integrations.plan.refusal.nonLoopback`,superseded_store:`integrations.plan.refusal.supersededStore`,drift_requires_confirm:`integrations.plan.refusal.driftRequiresConfirm`,snapshot_expired:`integrations.plan.refusal.snapshotExpired`,write_failed:`integrations.plan.refusal.writeFailed`};function vN({plan:e,missingStorePath:t}){let r=n(),i=e.refusalReason?_N[e.refusalReason]:void 0,a=e.supersededReason===`missing-store`?e.missingStoreDocument:void 0,o=a===void 0?r(i??`integrations.plan.refused`):t===void 0?r(`integrations.plan.refusal.missingStore`,{document:a}):r(`integrations.status.missingStore`,{path:t,document:a});return(0,Q.jsxs)(`div`,{className:`integration-plan-details`,children:[(0,Q.jsx)(`p`,{className:`integration-plan-operation`,children:r(`integrations.plan.operation`,{operation:r(mN[e.operation])})}),e.foreignEdit!==`none`&&(0,Q.jsx)(`p`,{children:r(gN[e.foreignEdit])}),!e.willChange&&e.canApply&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{children:r(e.operation===`disable`?`integrations.plan.noop.disabled`:`integrations.plan.noop.applied`)}),e.profileId!==void 0&&(0,Q.jsx)(`p`,{children:r(`integrations.plan.noop.profilePreference`)})]}),!e.canApply&&(0,Q.jsx)(`p`,{children:o}),e.changes.length>0&&(0,Q.jsx)(`ul`,{className:`integration-plan-changes`,children:e.changes.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`span`,{children:r(hN[e.kind])}),` `,(0,Q.jsx)(`code`,{children:e.path})]},`${e.kind}:${e.path}`))})]})}function yN({plan:e,plans:t,missingStorePath:r}){let i=n();return!e&&(!t||t.length===0)?null:(0,Q.jsxs)(`section`,{className:`integration-plan`,"aria-labelledby":`integration-plan-heading`,children:[(0,Q.jsx)(`h4`,{id:`integration-plan-heading`,children:i(`integrations.plan.heading`)}),e&&(0,Q.jsx)(vN,{plan:e,missingStorePath:r}),t?.map(e=>(0,Q.jsxs)(`section`,{className:`integration-plan-group`,children:[(0,Q.jsx)(`h5`,{children:e.label}),(0,Q.jsx)(vN,{plan:e.plan})]},`${e.clientId}:${e.plan.fingerprint}`))]})}function bN({copyKey:e,vars:t}){let r=n()(e,t),i=t?.path;if(!i||!r.includes(i))return(0,Q.jsx)(`p`,{children:r});let[a,...o]=r.split(i);return(0,Q.jsxs)(`p`,{children:[a,(0,Q.jsx)(`code`,{children:i}),o.join(i)]})}function xN(e){return e.changes.some(e=>e.kind===`snapshot`||e.kind===`journal`)}function SN({copy:e,plan:t=null,plans:r,hasUnboundAction:i=!1,planStale:a=!1,planLoading:o=!1,planFailure:s=null,missingStorePath:c,onConfirm:l,onClose:u}){let d=n(),f=(0,Z.useRef)(null),p=(0,Z.useRef)(null),m=(0,Z.useRef)(null),[h,g]=(0,Z.useState)(!1),[_,v]=(0,Z.useState)(null),[y,b]=(0,Z.useState)(null),x=`integration-consequence-dialog-title`,S=t!==null||o||s!==null||r!==void 0,C=y?.sourceFingerprint===(t?.fingerprint??null)?y.plan:t,w=y?.sourceFingerprint===(t?.fingerprint??null),T=r!==void 0&&!i&&!r.some(e=>e.plan.canApply),E=!S||(C?xN(C):r?.some(e=>xN(e.plan))===!0),D=(0,Z.useCallback)(()=>{h||u()},[u,h]);(0,Z.useEffect)(()=>{let e=f.current,t=document.activeElement;return p.current=t?.tagName===`BUTTON`?t:null,e&&!e.open&&e.showModal(),m.current?.focus(),()=>{e?.open&&e.close(),p.current?.isConnected&&p.current.focus?.()}},[]);let O=(0,Z.useCallback)(e=>{e.preventDefault(),D()},[D]),k=(0,Z.useCallback)(async()=>{if(!h){g(!0),v(null);try{await l(C??void 0)}catch(e){if(e instanceof my&&e.stalePlan){b({sourceFingerprint:t?.fingerprint??null,plan:e.stalePlan});return}v(e instanceof Error?e.message:d(`integrations.error.generic`))}finally{g(!1)}}},[C,l,h,t?.fingerprint,d]),A=[(0,Q.jsx)(bN,{copyKey:e.changesKey,vars:e.vars},`changes`),(0,Q.jsx)(bN,{copyKey:e.breakageKey,vars:e.vars},`breakage`)];return E&&A.push((0,Q.jsx)(bN,{copyKey:e.undoKey,vars:e.vars},`undo`)),e.sideEffectKey&&A.push((0,Q.jsx)(bN,{copyKey:e.sideEffectKey,vars:e.vars},`side-effect`)),(0,Q.jsxs)(`dialog`,{ref:f,className:`modal-overlay`,"aria-labelledby":x,"aria-busy":h,onCancel:O,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":d(`common.close`),tabIndex:-1,onClick:D}),(0,Q.jsxs)(`div`,{className:`modal-card integration-consequence-dialog`,role:`document`,children:[(0,Q.jsxs)(`div`,{className:`modal-head`,children:[(0,Q.jsx)(`h3`,{id:x,children:d(e.titleKey,e.vars)}),(0,Q.jsx)(`button`,{ref:m,type:`button`,className:`btn btn-ghost btn-sm`,onClick:D,disabled:h,children:d(`common.close`)})]}),(0,Q.jsx)(`div`,{className:`integration-consequence-body`,children:A}),(0,Q.jsxs)(`div`,{role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:[o&&(0,Q.jsx)(`p`,{children:d(`integrations.preview.loading`)}),h&&(0,Q.jsx)(`p`,{children:d(`integrations.mutation.pending`)}),(w||a)&&(0,Q.jsx)($,{tone:`err`,children:d(`integrations.preview.stale`)}),s&&(0,Q.jsx)($,{tone:`err`,children:s})]}),(0,Q.jsx)(yN,{plan:C,plans:r,missingStorePath:c}),_&&(0,Q.jsx)($,{tone:`err`,children:_}),(0,Q.jsx)(`div`,{className:`modal-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>void k(),disabled:h||o||!!s||S&&!C&&r===void 0||T||C?.canApply===!1,children:d(e.confirmKey)})})]})]})}function CN({apiBase:e,row:t,onClose:r,onRestored:i,profileId:a,onReconcile:o,hermesProfile:s}){let c=n(),l=(0,Z.useRef)(null),u=(0,Z.useRef)(null),d=(0,Z.useRef)(null),f=(0,Z.useRef)(!1),p=(0,Z.useRef)(r),m=(0,Z.useRef)(i),h=(0,Z.useRef)(o),g=(0,Z.useRef)(c),_=(0,Z.useRef)(null),v=(0,Z.useRef)(0),[y,b]=(0,Z.useState)(null),[x,S]=(0,Z.useState)(!0),[C,w]=(0,Z.useState)(!1),[T,E]=(0,Z.useState)(!1),[D,O]=(0,Z.useState)(null),[k,A]=(0,Z.useState)(null),j=t.clientId===`aside`?a??t.profileId:void 0,M=t.clientId===`hermes`?s:void 0,N=y?.plan??null,P=N?.foreignEdit===`drift`;(0,Z.useEffect)(()=>{p.current=r,m.current=i,h.current=o,g.current=c},[r,o,i,c]);let F=(0,Z.useCallback)(()=>{T||(v.current+=1,_.current?.abort(),_.current=null,p.current())},[T]);(0,Z.useEffect)(()=>{let e=l.current,t=document.activeElement;return u.current=t?.tagName===`BUTTON`?t:null,d.current=t?.closest?.(`section, [role='region'], main`)??null,e&&!e.open&&e.showModal(),()=>{e?.open&&e.close();let t=d.current;if(f.current&&t?.isConnected){t.hasAttribute(`tabindex`)||t.setAttribute(`tabindex`,`-1`),t.focus?.();return}let n=u.current;n?.isConnected?n.focus?.():t?.isConnected&&(t.hasAttribute(`tabindex`)||t.setAttribute(`tabindex`,`-1`),t.focus?.())}},[]);let I=(0,Z.useCallback)(async()=>{let n=new AbortController,r=v.current+1;v.current=r,_.current?.abort(),_.current=n,S(!0),O(null),A(null),b(null),w(!1);try{let i=!1,a=await ky(e,t.opId,i,n.signal,j,M);if(a.refusalReason===`drift_requires_confirm`&&(i=!0,a=await ky(e,t.opId,i,n.signal,j,M)),n.signal.aborted||r!==v.current)return;b({plan:a,confirmDrift:i})}catch(e){if(n.signal.aborted||r!==v.current)return;if(vy(e)){h.current?.(),p.current();return}O(g.current(`integrations.preview.failed`))}finally{!n.signal.aborted&&r===v.current&&(_.current=null,S(!1))}},[e,t.opId,j,M]);(0,Z.useEffect)(()=>{let e=window.setTimeout(()=>{I()},0);return()=>{window.clearTimeout(e),v.current+=1,_.current?.abort(),_.current=null}},[I]);let L=(0,Z.useCallback)(e=>{e.preventDefault(),F()},[F]),R=async()=>{if(T||x||!y||!y.plan.canApply)return;let n=y.confirmDrift;E(!0),A(null);try{await jy(e,{opId:t.opId,confirmDrift:n,profileId:j,hermesProfile:M,binding:yy(y.plan)}),f.current=!0,m.current(),p.current()}catch(r){if(t.clientId===`aside`&&h.current?.(),r instanceof my&&r.stalePlan){let i=r.stalePlan,a=n;E(!1);try{if(i.refusalReason===`drift_requires_confirm`){let n=new AbortController,r=v.current+1;v.current=r,_.current?.abort(),_.current=n,S(!0),a=!0;try{i=await ky(e,t.opId,a,n.signal,j,M)}finally{!n.signal.aborted&&r===v.current&&(_.current=null,S(!1))}if(n.signal.aborted||r!==v.current)return}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;if(vy(e)){h.current?.(),p.current();return}O(g.current(`integrations.preview.failed`));return}b({plan:i,confirmDrift:a}),w(!0);return}A(nb(c,r)),E(!1)}};return(0,Q.jsxs)(`dialog`,{ref:l,className:`modal-overlay`,"aria-labelledby":`integration-restore-title`,"aria-busy":T,onCancel:L,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":c(`common.close`),tabIndex:-1,onClick:F}),(0,Q.jsxs)(`div`,{className:`modal-card integration-restore-dialog`,role:`document`,children:[(0,Q.jsx)(`div`,{className:`modal-head`,children:(0,Q.jsx)(`h3`,{id:`integration-restore-title`,children:c(P?`integrations.restore.driftTitle`:`integrations.restore.title`)})}),(0,Q.jsx)(`div`,{className:`modal-desc`,children:c(P?`integrations.restore.driftBody`:`integrations.restore.body`)}),(0,Q.jsxs)(`div`,{role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:[x&&(0,Q.jsx)(`p`,{children:c(`integrations.preview.loading`)}),T&&(0,Q.jsx)(`p`,{children:c(`integrations.mutation.pending`)}),C&&(0,Q.jsx)($,{tone:`err`,children:c(`integrations.preview.stale`)})]}),(0,Q.jsx)(yN,{plan:N}),D&&(0,Q.jsx)($,{tone:`err`,children:D}),k&&(0,Q.jsx)($,{tone:`err`,children:k}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:F,disabled:T,children:c(`common.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>void R(),disabled:T||x||!N?.canApply||!!D,children:c(T?`integrations.restore.pending`:P?`integrations.restore.confirmDrift`:`integrations.restore.confirm`)})]})]})]})}var wN={opencode:`integrations.tab.opencode`,pi:`integrations.tab.pi`,"gentle-shell":`integrations.tab.gentleShell`,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`,commandcode:`integrations.tab.commandcode`,prime:`integrations.tab.prime`,aside:`integrations.tab.aside`,raycast:`integrations.tab.raycast`,omo:`integrations.tab.omo`,cline:`integrations.tab.cline`,kilo:`integrations.tab.kilo`,droid:`integrations.tab.droid`,qoder:`integrations.tab.qoder`,"qoder-cn":`integrations.tab.qoderCn`,workbuddy:`integrations.tab.workbuddy`,"workbuddy-ai":`integrations.tab.workbuddyAi`,t3code:`integrations.tab.t3code`},TN={apply:`integrations.kind.apply`,disable:`integrations.kind.disable`,refresh:`integrations.kind.refresh`,restore:`integrations.kind.restore`,overwrite:`integrations.kind.overwrite`};function EN(e){return e===`current`||e===`stale`}function DN(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 ON(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 kN(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 AN(e,t,n){let r={id:`claude`,hash:`claude/code`,labelKey:`integrations.tab.claude`,toggle:`claude`,toggleBlocked:t?.disableBlocked??null,togglePath:t?.configPath??null,status:null,detail:null,detailVars:null},i=kN(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 jN(e,t,n){let r={id:`claudeDesktop`,hash:`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 MN(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 NN(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=MN(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 PN(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 FN(e){return{id:e.clientId,hash:`integrations/${e.clientId}`,labelKey:wN[e.clientId],state:e.installed?e.state:`not-installed`,installed:e.installed,applied:e.installed&&(EN(e.state)||Jv(e)),detail:e.configPath,detailKey:null,detailVars:null,toggle:e.clientId,toggleBlocked:null,togglePath:e.configPath,status:e}}function IN(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=[DN(e.codex,t,e.nativeSettled),AN(e.claude,n,e.nativeSettled),jN(e.claudeDesktop,e.native?.find(e=>e.clientId===`claude-desktop`),e.nativeSettled),NN(e.grok,r,e.nativeSettled),PN(e.cursor)];for(let t of qv){let n=i.get(t);n?a.push(FN(n)):e.clientsSettled||a.push({id:t,hash:`integrations/${t}`,labelKey:wN[t],state:`unknown`,installed:!1,applied:!1,detail:null,detailKey:null,detailVars:null,toggle:null,toggleBlocked:null,togglePath:null,status:null})}return{keysRow:ON(e.keyPhase,e.keyCount),rows:a}}function LN(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 RN=6;function zN({row:e,showClient:t,onRestore:r,onDelete:i}){let a=n();return(0,Q.jsxs)(`li`,{className:`integration-history-row`,children:[(0,Q.jsx)(`span`,{className:`integration-history-kind`,children:a(TN[e.kind])}),t&&(0,Q.jsx)(`span`,{className:`integration-history-client`,children:e.clientId}),(0,Q.jsx)(`span`,{className:`integration-history-at`,children:new Date(e.at).toLocaleString()}),e.snapshot===`expired`?(0,Q.jsx)(`span`,{className:`badge badge-muted`,children:a(`integrations.action.snapshotExpired`)}):(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>r(e),children:e.undoable?a(`integrations.action.undo`):a(`integrations.action.restorePoint`)}),e.deletable&&i&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>i(e),"aria-label":a(`integrations.rollback.deleteAria`,{at:new Date(e.at).toLocaleString()}),children:a(`integrations.rollback.delete`)})]})}function BN({rows:e,showClient:t,onRestore:r,onDelete:i}){let a=n(),[o,s]=(0,Z.useState)(RN),[c,...l]=e;if(!c)return null;let u=l.slice(0,o),d=l.length-u.length;return(0,Q.jsxs)(`div`,{className:`integration-history`,children:[(0,Q.jsx)(`ul`,{className:`integration-history-list`,children:(0,Q.jsx)(zN,{row:c,showClient:t,onRestore:r,onDelete:i})}),l.length>0&&(0,Q.jsxs)(`details`,{className:`integration-history-older`,children:[(0,Q.jsx)(`summary`,{children:a(`integrations.rollback.older`)}),(0,Q.jsx)(`ul`,{className:`integration-history-list`,children:u.map(e=>(0,Q.jsx)(zN,{row:e,showClient:t,onRestore:r,onDelete:i},e.opId))}),d>0&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm integration-history-more`,onClick:()=>s(e=>e+RN),children:a(`integrations.rollback.showMore`,{n:String(Math.min(d,RN))})})]})]})}var VN={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`},HN={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`},UN={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`},WN={titleKey:`integrations.dialog.apply.title`,changesKey:`integrations.dialog.apply.changes`,breakageKey:`integrations.dialog.apply.breakage`,undoKey:`integrations.dialog.apply.undo`,confirmKey:`integrations.dialog.apply.confirm`},GN={titleKey:`integrations.dialog.disable.title`,changesKey:`integrations.dialog.disable.changes`,breakageKey:`integrations.dialog.disable.breakage`,undoKey:`integrations.dialog.disable.undo`,confirmKey:`integrations.dialog.disable.confirm`},KN={titleKey:`integrations.bulk.title`,changesKey:`integrations.bulk.body`,breakageKey:`integrations.bulk.breakage`,undoKey:`integrations.bulk.undo`,confirmKey:`integrations.bulk.confirm`};function qN(e){return e.flatMap(e=>e.plan?[{clientId:e.clientId,label:e.label,plan:e.plan}]:[])}function JN(e){return e.state===`current`||e.state===`stale`||Jv(e)}function YN({row:e,pending:t,result:r,onOpen:i,onToggle:a,onOverwrite:o}){let s=n(),c=e.detail??(e.detailKey?s(e.detailKey,e.detailVars??void 0):null),l=e.toggleBlocked!==null&&(e.applied||e.toggleBlocked.reason===`orphaned_marker`),u=l&&e.toggleBlocked&&(e.toggle===`claude`||e.toggle===`grok`||e.toggle===`codex`)?nb(s,new Wy(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,d=e.toggleOn??e.applied,f=e.status!==null&&Jv(e.status);return(0,Q.jsxs)(`li`,{className:`integration-card`,"data-client":e.id,children:[(0,Q.jsxs)(`div`,{className:`integration-card-head`,children:[(0,Q.jsx)(gA,{src:hA(e.id),label:s(e.labelKey),size:20}),(0,Q.jsx)(`h4`,{children:(0,Q.jsx)(`button`,{type:`button`,className:`integration-card-link`,onClick:i,children:s(e.labelKey)})}),(0,Q.jsx)(pN,{state:e.state,installed:e.installed})]}),c&&(0,Q.jsx)(`p`,{className:e.detail?`integration-path`:`integration-meta`,children:c}),e.status?.reason===`candidate-conflict`&&e.status.conflictPaths?.map(e=>(0,Q.jsx)($,{tone:`err`,children:s(`integrations.status.candidateConflict`,{path:e})},e)),r?.tone===`err`&&(0,Q.jsx)($,{tone:`err`,children:r.text}),r?.tone===`ok`&&(0,Q.jsx)($,{tone:`ok`,children:r.text}),(0,Q.jsxs)(`div`,{className:`integration-card-actions`,children:[e.toggle&&a&&(0,Q.jsxs)(`div`,{className:`integration-toggle-control`,children:[(0,Q.jsx)(ln,{on:d,onClick:a,disabled:e.state===`unknown`||!e.installed||(e.state===`conflict`||e.state===`unsafe`)&&!f||l||t,label:s(d?`integrations.action.disable`:`integrations.action.apply`)}),u&&(0,Q.jsx)(`p`,{className:`integration-toggle-blocked`,children:u})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:i,tabIndex:-1,children:s(`integrations.action.settings`)}),o&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-danger`,onClick:o,disabled:t,children:s(`integrations.action.overwrite`)})]})]})}function XN({apiBase:e,active:t=!0}){let r=n(),[i,a]=(0,Z.useState)(!1),[o,s]=(0,Z.useState)(null),[c,l]=(0,Z.useState)(null),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)({}),[m,h]=(0,Z.useState)(null),[g,_]=(0,Z.useState)(null),[v,y]=(0,Z.useState)(null),b=(0,Z.useRef)(null),x=(0,Z.useRef)(0),S=(0,Z.useRef)(null),C=(0,Z.useRef)(0),w=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{if(m!==null)return;let e=w.current;e&&(w.current=null,e.isConnected&&e.focus())},[m]),(0,Z.useEffect)(()=>()=>{x.current+=1,C.current+=1,b.current?.abort(),S.current?.abort()},[]);let T=(0,Z.useCallback)(async t=>(await Ty(e,t)).clients,[e]),E=(0,Z.useCallback)(async t=>(await Dy(e,void 0,t)).operations,[e]),D=(0,Z.useCallback)(t=>Py(e,t),[e]),O=(0,Z.useCallback)(t=>Fy(e,t),[e]),k=(0,Z.useCallback)(t=>Iy(e,t),[e]),A=(0,Z.useCallback)(t=>Ly(e,t),[e]),j=(0,Z.useCallback)(t=>Ry(e,t),[e]),M=(0,Z.useCallback)(t=>aN(e,t),[e]),N=(0,Z.useCallback)(async t=>(await Jy(e,t))?.clients??null,[e]),P=uo(`integration-states:${e}`,[e],T,{isEmpty:e=>e.length===0,enabled:t,sessionCacheKey:`ocx.integrations.states.v1:${e}`}),F=uo(`integration-journal-all:${e}`,[e],E,{isEmpty:e=>e.length===0,enabled:t,sessionCacheKey:`ocx.integrations.journal.v1:${e}`}),I=uo(`integration-codex:${e}`,[e],D,{isEmpty:e=>e===null,enabled:t,sessionCacheKey:`ocx.integrations.codex.v1:${e}`}),L=uo(`integration-keys:${e}`,[e],O,{isEmpty:()=>!1,enabled:t,sessionCacheKey:`ocx.integrations.keys.v1:${e}`}),R=uo(`integration-claude:${e}`,[e],k,{isEmpty:e=>e===null,enabled:t,sessionCacheKey:`ocx.integrations.claude.v1:${e}`}),z=uo(`integration-claude-desktop:${e}`,[e],A,{isEmpty:e=>e===null,enabled:t,sessionCacheKey:`ocx.integrations.claude-desktop.v1:${e}`}),B=uo(`integration-grok:${e}`,[e],j,{isEmpty:e=>e===null,enabled:t,sessionCacheKey:`ocx.integrations.grok.v1:${e}`}),V=uo(`integration-cursor:${e}`,[e],M,{isEmpty:e=>e===null,enabled:t,sessionCacheKey:`ocx.integrations.cursor.v1:${e}`}),H=uo(`integration-native:${e}`,[e],N,{isEmpty:e=>e===null,enabled:t,sessionCacheKey:`ocx.integrations.native.v1:${e}`}),U=P.state.data??[],ee=F.state.data??[],W=U.filter(JN),te=U.filter(e=>e.installed),G=P.state.data!==void 0,ne=H.state.data??null,K=ne!==null,re=L.state.kind===`cold`||L.state.kind===`retrying-cold`?`checking`:L.state.kind===`failed-cold`||L.state.kind===`failed-with-stale`?`unavailable`:`settled`,{keysRow:q,rows:J}=IN({clients:U,clientsSettled:G,codex:I.state.data??null,keyCount:L.state.data??null,keyPhase:re,claude:R.state.data??null,claudeDesktop:z.state.data??null,grok:B.state.data??null,cursor:V.state.data??null,native:ne,nativeSettled:K}),Y=LN(J),ie=()=>{P.refresh(),F.refresh(),I.refresh(),L.refresh(),R.refresh(),z.refresh(),B.refresh(),H.refresh()},X=async()=>{if(i||v||W.length===0)return;let t=new AbortController,n=C.current+1;C.current=n,S.current?.abort(),S.current=t,y({actions:[],loading:!0,failure:null,stale:!1,failures:[]});try{let i=await Promise.all(W.map(async n=>{let i=J.find(e=>e.status?.clientId===n.clientId);if(n.clientId===`aside`)return{clientId:n.clientId,label:i?r(i.labelKey):n.clientId,plan:null};let a=await Oy(e,n.clientId,`disable`,t.signal);return{clientId:n.clientId,label:i?r(i.labelKey):n.clientId,plan:a}}));if(t.signal.aborted||n!==C.current)return;S.current=null,y({actions:i,loading:!1,failure:null,stale:!1,failures:[]})}catch(e){if(t.signal.aborted||n!==C.current)return;if(S.current=null,vy(e)){y(null),ie();return}y({actions:[],loading:!1,failure:r(`integrations.preview.failed`),stale:!1,failures:[]})}},ae=()=>{C.current+=1,S.current?.abort(),S.current=null,y(null)},oe=async t=>{if(i||t.actions.length===0)return;a(!0),s(null);let n=[...t.failures],o=[];for(let i of t.actions)if(i.plan&&!i.plan.canApply)n.push(`${i.clientId}: ${r(`integrations.plan.refused`)}`);else try{await Ay(e,i.clientId,{enabled:!1,...i.plan?{binding:yy(i.plan)}:{}})}catch(e){if(i.plan&&e instanceof my&&e.stalePlan){o.push({...i,plan:e.stalePlan});continue}n.push(`${i.clientId}: ${nb(r,e)}`)}if(o.length>0){ie(),a(!1),y({actions:o,loading:!1,failure:null,stale:!0,failures:n}),s(n.length===0?null:{tone:`err`,text:r(`integrations.bulk.partial`,{clients:n.join(`; `)})});return}let c=!1;try{c=(await Ty(e)).clients.some(JN)}catch{n.push(r(`integrations.error.stale`))}c&&n.length===0&&n.push(r(`integrations.error.stale`)),ie(),a(!1),y(null),s(n.length===0?{tone:`ok`,text:r(`integrations.bulk.success`)}:{tone:`err`,text:r(`integrations.bulk.partial`,{clients:n.join(`; `)})})},se=ee[0]?.at,[ce,le]=(0,Z.useState)(null),ue=()=>{H.refresh(),I.refresh(),R.refresh(),B.refresh()},de=(e,t)=>{p(n=>{let r={...n};return t?r[e]=t:delete r[e],r})},fe=async(t,n,i)=>{if(!ce&&t.toggle){le(t.id),de(t.id,null);try{if(t.status){if(!i&&t.status.clientId!==`aside`)return;await Ay(e,t.status.clientId,{enabled:n,...i?{overwriteConflict:i.operation===`overwrite`,binding:yy(i)}:{}}),ie()}else if(t.toggle===`claude`||t.toggle===`grok`||t.toggle===`codex`||t.toggle===`claude-desktop`){let i=await Yy(e,t.toggle,n);i.reason===`non_loopback_removed`?de(t.id,{tone:`ok`,text:r(i.changed?`integrations.native.msg.nonLoopbackRemoved`:`integrations.native.msg.nonLoopbackRemovedNoop`)}):i.reason===`non_loopback_superseded`&&de(t.id,{tone:`ok`,text:r(`integrations.native.msg.nonLoopbackSuperseded`)}),ue()}}catch(e){if(t.status&&e instanceof my&&e.stalePlan)throw e;if(de(t.id,{tone:`err`,text:nb(r,e,void 0,t.togglePath??void 0)}),(t.toggle===`claude`||t.toggle===`grok`||t.toggle===`codex`||t.toggle===`claude-desktop`)&&ue(),t.status)throw Error(nb(r,e,void 0,t.togglePath??void 0),{cause:e})}finally{le(null)}}},pe=async(t,n)=>{if(!t.status||g)return;let i=new AbortController,a=x.current+1;x.current=a,b.current?.abort(),b.current=i,_({row:t,operation:n,plan:null,loading:!0,failure:null});try{let r=await Oy(e,t.status.clientId,n,i.signal);if(i.signal.aborted||a!==x.current)return;b.current=null,_({row:t,operation:n,plan:r,loading:!1,failure:null})}catch(e){if(i.signal.aborted||a!==x.current)return;if(b.current=null,vy(e)){_(null),ie();return}_({row:t,operation:n,plan:null,loading:!1,failure:r(`integrations.preview.failed`)})}},me=()=>{x.current+=1,b.current?.abort(),b.current=null,_(null)},he=(e,t)=>{if(e.status&&e.status.clientId!==`aside`){pe(e,t?`apply`:`disable`);return}if(e.status?.clientId===`aside`){fe(e,t).catch(()=>{});return}if(t||e.id===`claude`||e.toggle===null){fe(e,t);return}let n=document.activeElement;w.current=n?.tagName===`BUTTON`?n:null,h(e)};return(0,Q.jsxs)(`section`,{className:`integrations-overview`,children:[(0,Q.jsxs)(`div`,{className:`integration-summary`,children:[(0,Q.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,Q.jsx)(`span`,{className:`integration-summary-label`,children:r(`integrations.summary.detected`)}),(0,Q.jsx)(`strong`,{children:Y.detected})]}),(0,Q.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,Q.jsx)(`span`,{className:`integration-summary-label`,children:r(`integrations.summary.applied`)}),(0,Q.jsx)(`strong`,{children:Y.applied})]}),(0,Q.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,Q.jsx)(`span`,{className:`integration-summary-label`,children:r(`integrations.summary.stale`)}),(0,Q.jsx)(`strong`,{children:Y.stale})]}),Y.unknown>0&&(0,Q.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,Q.jsx)(`span`,{className:`integration-summary-label`,children:r(`integrations.state.unknown`)}),(0,Q.jsx)(`strong`,{children:Y.unknown})]}),(0,Q.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,Q.jsx)(`span`,{className:`integration-summary-label`,children:r(`integrations.summary.lastChange`)}),(0,Q.jsx)(`strong`,{children:se?new Date(se).toLocaleString():r(`integrations.status.unknown`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>void X(),disabled:i||!!v||W.length===0,children:r(`integrations.summary.disableAll`)})]}),(0,Q.jsx)(`h3`,{children:r(`integrations.catalog.title`)}),(0,Q.jsx)(ZN,{row:q}),(0,Q.jsx)(`p`,{className:`page-sub`,children:r(`integrations.onboarding`)}),P.state.kind===`failed-cold`&&(0,Q.jsx)($,{tone:`err`,children:r(`integrations.error.load`)}),P.state.kind===`failed-with-stale`&&(0,Q.jsx)($,{tone:`err`,children:r(`integrations.error.stale`)}),o&&(0,Q.jsx)($,{tone:o.tone,children:o.text}),J.length===0?P.state.kind===`failed-cold`?null:(0,Q.jsx)(`p`,{className:`page-sub`,children:r(`common.loading`)}):(0,Q.jsx)(`ul`,{className:`integration-cards`,children:J.map(e=>(0,Q.jsx)(YN,{row:e,pending:ce!==null,result:f[e.id]??null,onOpen:()=>Xt(e.hash),onToggle:e.toggle?()=>he(e,!(e.toggleOn??e.applied)):null,onOverwrite:e.status!==null&&e.status.state===`conflict`&&e.status.reason!==`candidate-conflict`&&e.installed?()=>void pe(e,`overwrite`):null},e.id))}),G&&te.length===0&&(0,Q.jsxs)(`div`,{className:`integration-empty`,children:[(0,Q.jsx)(`h4`,{children:r(`integrations.empty.title`)}),(0,Q.jsx)(`p`,{children:r(`integrations.empty.body`)})]}),(0,Q.jsx)(`h3`,{children:r(`integrations.rollback.title`)}),F.state.showSkeleton?(0,Q.jsx)(lb,{label:r(`integrations.rollback.title`),rows:2}):F.state.kind===`failed-cold`?(0,Q.jsxs)($,{tone:`err`,children:[r(`integrations.rollback.failed`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void F.refresh(),children:r(`common.retry`)})]}):ee.length===0?(0,Q.jsxs)(`div`,{className:`integration-empty`,children:[(0,Q.jsx)(`p`,{children:r(`integrations.rollback.empty`)}),(0,Q.jsx)(`p`,{className:`page-sub`,children:r(`integrations.rollback.emptyBody`)})]}):(0,Q.jsx)(BN,{rows:ee,showClient:!0,onRestore:l,onDelete:d}),c&&(0,Q.jsx)(CN,{apiBase:e,row:c,onClose:()=>l(null),onRestored:ie,onReconcile:ie}),u&&(0,Q.jsx)(SN,{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:u.configPath}},onClose:()=>d(null),onConfirm:async()=>{try{await My(e,u.opId,void 0,u.clientId===`aside`?u.profileId:void 0)}catch(e){if(hy(e)){d(null),await F.refresh();return}throw Error(nb(r,e),{cause:e})}d(null),await F.refresh()}}),m&&(0,Q.jsx)(SN,{copy:{...m.toggle===`claude-desktop`?UN:m.id===`codex`?HN:VN,vars:{path:m.togglePath??``}},onClose:()=>h(null),onConfirm:async()=>{await fe(m,!1),h(null)}}),g&&g.row.status&&(0,Q.jsx)(SN,{copy:g.operation===`overwrite`?{titleKey:`integrations.dialog.overwrite.title`,changesKey:g.row.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:g.row.status.configPath}}:g.operation===`disable`?GN:WN,plan:g.plan,planLoading:g.loading,planFailure:g.failure,onClose:me,onConfirm:async e=>{e&&(await fe(g.row,e.operation!==`disable`,e),_(null))}}),v&&(0,Q.jsx)(SN,{copy:KN,plans:qN(v.actions),hasUnboundAction:v.actions.some(e=>e.plan===null),planStale:v.stale,planLoading:v.loading,planFailure:v.failure,onClose:ae,onConfirm:async()=>{await oe(v)}})]})}function ZN({row:e}){let t=n(),r=e.detailKey?t(e.detailKey,e.detailVars??void 0):null;return(0,Q.jsxs)(`div`,{className:`integration-api-keys-row`,"data-client":`keys`,"data-key-state":e.state,children:[(0,Q.jsxs)(`div`,{className:`integration-api-keys-copy`,children:[(0,Q.jsx)(`h4`,{children:t(e.labelKey)}),r&&(0,Q.jsx)(`p`,{className:`integration-meta`,children:r})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>Xt(e.hash),children:t(`integrations.action.manageKeys`)})]})}function QN({install:e}){let t=n();return(0,Q.jsxs)(Q.Fragment,{children:[e.plan===`free`&&(0,Q.jsx)($,{tone:`warn`,children:t(`integrations.raycast.proRequired`)}),e.plan===`unknown`&&(0,Q.jsx)(`p`,{className:`page-sub`,"data-raycast-plan":`unknown`,children:t(`integrations.raycast.planUnknown`)}),!e.aiDirPresent&&(0,Q.jsx)(`p`,{className:`page-sub`,"data-raycast-ai-dir":`absent`,children:t(`integrations.raycast.revealConfig`)})]})}function $N({reasoning:e,defaults:t,disabled:r,onChange:i,onReview:a}){let o=n(),s=new Map(e.models.map(e=>[e.model,new Set(e.efforts)])),c=Object.entries(t).filter(([e,t])=>!s.get(e)?.has(t)),l=(e,n)=>{let r={...t};n?r[e]=n:delete r[e],i(r)};return(0,Q.jsxs)(`section`,{className:`droid-reasoning-panel`,"aria-labelledby":`droid-reasoning-title`,children:[(0,Q.jsxs)(`div`,{className:`droid-reasoning-heading`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h4`,{id:`droid-reasoning-title`,children:o(`integrations.droidReasoning.title`)}),(0,Q.jsx)(`p`,{className:`page-sub`,children:o(`integrations.droidReasoning.description`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:a,disabled:r,children:o(`integrations.droidReasoning.saveReview`)})]}),e.models.length>0?(0,Q.jsx)(`ul`,{className:`droid-reasoning-list`,children:e.models.map(e=>{let n=t[e.model]??``,i=e.efforts.includes(n),a=[{value:``,label:o(`integrations.droidReasoning.noDefault`)},...!i&&n?[{value:n,label:o(`integrations.droidReasoning.unsupportedEffort`,{effort:n})}]:[],...e.efforts.map(e=>({value:e,label:e}))];return(0,Q.jsxs)(`li`,{className:`droid-reasoning-row`,children:[(0,Q.jsxs)(`div`,{className:`droid-reasoning-model`,children:[(0,Q.jsx)(`span`,{children:e.label}),(0,Q.jsx)(`code`,{children:e.model})]}),e.efforts.length>0?(0,Q.jsx)(dn,{value:n,options:a,onChange:t=>l(e.model,t),disabled:r,label:o(`integrations.droidReasoning.modelDefault`,{model:e.label})}):(0,Q.jsx)(`span`,{className:`muted text-caption`,children:o(`integrations.droidReasoning.noEfforts`)})]},e.model)})}):(0,Q.jsx)(`p`,{className:`page-sub`,children:o(`integrations.droidReasoning.noModels`)}),c.length>0&&(0,Q.jsxs)(`div`,{className:`droid-reasoning-unsupported`,role:`status`,children:[(0,Q.jsx)(`p`,{children:o(`integrations.droidReasoning.unsupportedTitle`)}),(0,Q.jsx)(`ul`,{children:c.map(([e,t])=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`code`,{children:e}),` `,o(`integrations.droidReasoning.unsupportedEffort`,{effort:t}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:r,onClick:()=>l(e,``),children:o(`integrations.droidReasoning.clear`)})]},e))})]})]})}function eP(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 tP={titleKey:`integrations.dialog.apply.title`,changesKey:`integrations.dialog.apply.changes`,breakageKey:`integrations.dialog.apply.breakage`,undoKey:`integrations.dialog.apply.undo`,confirmKey:`integrations.dialog.apply.confirm`},nP={titleKey:`integrations.dialog.disable.title`,changesKey:`integrations.dialog.disable.changes`,breakageKey:`integrations.dialog.disable.breakage`,undoKey:`integrations.dialog.disable.undo`,confirmKey:`integrations.dialog.disable.confirm`},rP={opencode:`integrations.semantics.opencode`,pi:`integrations.semantics.pi`,"gentle-shell":`integrations.semantics.gentleShell`,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`,commandcode:`integrations.semantics.commandcode`,prime:`integrations.semantics.prime`,aside:`integrations.semantics.aside`,raycast:`integrations.semantics.raycast`,omo:`integrations.semantics.omo`,cline:`integrations.semantics.cline`,kilo:`integrations.semantics.kilo`,droid:`integrations.semantics.droid`,qoder:`integrations.semantics.qoder`,"qoder-cn":`integrations.semantics.qoderCn`,workbuddy:`integrations.semantics.workbuddy`,"workbuddy-ai":`integrations.semantics.workbuddyAi`,t3code:`integrations.semantics.t3code`},iP={opencode:`integrations.tab.opencode`,pi:`integrations.tab.pi`,"gentle-shell":`integrations.tab.gentleShell`,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`,commandcode:`integrations.tab.commandcode`,prime:`integrations.tab.prime`,aside:`integrations.tab.aside`,raycast:`integrations.tab.raycast`,omo:`integrations.tab.omo`,cline:`integrations.tab.cline`,kilo:`integrations.tab.kilo`,droid:`integrations.tab.droid`,qoder:`integrations.tab.qoder`,"qoder-cn":`integrations.tab.qoderCn`,workbuddy:`integrations.tab.workbuddy`,"workbuddy-ai":`integrations.tab.workbuddyAi`,t3code:`integrations.tab.t3code`};function aP(e){return(0,Q.jsx)(oP,{...e},JSON.stringify([e.apiBase,e.client,e.profileId,e.hermesProfile]))}function oP({apiBase:e,client:t,active:r=!0,profileId:i,profileLabel:a,hermesProfile:o,onRefresh:s}){let c=n(),l=i===void 0?o===void 0?t:`${t}/${o}`:`${t}:${i}`,[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(null),[m,h]=(0,Z.useState)(null),[g,_]=(0,Z.useState)(null),[v,y]=(0,Z.useState)(null),[b,x]=(0,Z.useState)(null),S=(0,Z.useRef)(null),C=(0,Z.useRef)(0);(0,Z.useEffect)(()=>()=>{C.current+=1,S.current?.abort()},[]);let w=(0,Z.useCallback)(n=>Ey(e,t,n,i,o),[e,t,i,o]),T=(0,Z.useCallback)(async n=>(await Dy(e,t,n,i,o)).operations,[e,t,i,o]),E=uo(`integration-state:${e}:${l}`,[e,t,i,o],w,{isEmpty:()=>!1,enabled:r,sessionCacheKey:`ocx.integrations.state.v1:${e}:${l}`}),D=uo(`integration-journal:${e}:${l}`,[e,t,i,o],T,{isEmpty:e=>e.length===0,enabled:r,sessionCacheKey:`ocx.integrations.client-journal.v1:${e}:${l}`}),O=E.state.data??null,k=O&&(i===void 0||O.profileId===i&&typeof O.enabled==`boolean`)&&O.hermesProfile===o?O:null,A=D.state.data??[],j=()=>{E.refresh(),D.refresh(),s?.()},M=()=>{p(null),j()},N=async(n,r=t===`droid`&&n!==`disable`&&f?.scopeKey===l?f.values:void 0)=>{if(!k||u||b)return;let a=r===void 0?void 0:{...r},s=new AbortController,d=C.current+1;C.current=d,S.current?.abort(),S.current=s,x({operation:n,plan:null,loading:!0,failure:null});try{let r=await Oy(e,t,n,s.signal,i,a,o);if(s.signal.aborted||d!==C.current)return;S.current=null,x({operation:n,plan:r,loading:!1,failure:null,droidReasoningDefaults:a})}catch(e){if(s.signal.aborted||d!==C.current)return;if(S.current=null,vy(e)){x(null),j();return}x({operation:n,plan:null,loading:!1,failure:c(`integrations.preview.failed`)})}},P=()=>{C.current+=1,S.current?.abort(),S.current=null,x(null)},F=async n=>{if(k&&!u){d(!0),h(null);try{await Ay(e,t,{enabled:n.operation!==`disable`,overwriteConflict:n.operation===`overwrite`,profileId:i,hermesProfile:o,binding:yy(n),...n.operation!==`disable`&&b?.droidReasoningDefaults!==void 0?{droidReasoningDefaults:b.droidReasoningDefaults}:{}}),x(null),t===`droid`&&p(null)}catch(e){throw j(),e instanceof my&&e.stalePlan?e:Error(nb(c,e),{cause:e})}finally{j(),d(!1)}}},I=()=>void N(z?`disable`:`apply`);if(!k)return(0,Q.jsx)(`section`,{className:`integration-client-page`,children:E.state.showError?(0,Q.jsxs)($,{tone:`err`,children:[c(`integrations.error.load`),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:j,disabled:E.state.refreshing,children:c(`common.retry`)})]}):(0,Q.jsx)(`p`,{className:`page-sub`,children:c(`common.loading`)})});let L=Jv(k),R=k.state===`current`||k.state===`stale`||L,z=i===void 0?R:k.enabled===!0,B=i!==void 0&&(E.state.showError||E.state.refreshing),V=(!k.installed||(k.state===`conflict`||k.state===`unsafe`)&&!L)&&!(i!==void 0&&z);return(0,Q.jsxs)(`section`,{className:`integration-client-page`,children:[(0,Q.jsxs)(`div`,{className:`integration-client-head`,children:[(0,Q.jsx)(gA,{src:hA(t),label:c(iP[t]),size:24}),(0,Q.jsx)(`h3`,{children:a??c(iP[t])}),(0,Q.jsx)(pN,{state:k.state,installed:k.installed,id:`integration-state-${t}${i===void 0?``:`-${i}`}${o===void 0?``:`-${o}`}`}),(0,Q.jsx)(ln,{on:z,onClick:I,disabled:V||u||B,label:c(z?`integrations.action.disable`:`integrations.action.apply`)})]}),i!==void 0&&E.state.showError&&(0,Q.jsxs)($,{tone:`err`,children:[c(`integrations.aside.loadError`),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:j,disabled:u||E.state.refreshing,children:c(`common.retry`)})]}),k.state===`stale`&&z&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>void N(`apply`),disabled:u,children:c(`integrations.action.refresh`)}),t===`droid`&&k.droidReasoning&&(0,Q.jsx)($N,{reasoning:k.droidReasoning,defaults:f?.scopeKey===l?f.values:k.droidReasoning.defaults,disabled:u||b!==null,onChange:e=>p({scopeKey:l,values:e}),onReview:()=>void N(`apply`)}),k.installed&&k.state===`conflict`&&k.reason!==`candidate-conflict`&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-danger`,onClick:()=>void N(`overwrite`),disabled:u,children:c(`integrations.action.overwrite`)}),(0,Q.jsx)(`p`,{className:`page-sub`,children:c(rP[t])}),(0,Q.jsx)(`p`,{className:`integration-path`,children:k.configPath}),k.reason===`candidate-conflict`&&k.conflictPaths?.map(e=>(0,Q.jsx)($,{tone:`err`,children:c(`integrations.status.candidateConflict`,{path:e})},e)),k.raycast&&(0,Q.jsx)(QN,{install:k.raycast}),k.supersededBy&&(0,Q.jsx)($,{tone:`err`,children:k.supersededReason===`missing-store`&&k.missingStoreDocument!==void 0?c(`integrations.status.missingStore`,{path:k.supersededBy,document:k.missingStoreDocument}):c(`integrations.status.supersededStore`,{path:k.supersededBy})}),k.appliedAt&&(0,Q.jsxs)(`p`,{className:`integration-meta`,children:[c(`integrations.status.appliedAt`),`: `,new Date(k.appliedAt).toLocaleString()]}),k.retentionDegraded&&(0,Q.jsx)($,{tone:`err`,children:c(`integrations.retention.degraded`)}),m&&(0,Q.jsx)($,{tone:`err`,children:m}),(0,Q.jsx)(`h4`,{children:c(`integrations.rollback.title`)}),D.state.showSkeleton?(0,Q.jsx)(lb,{label:c(`integrations.rollback.title`),rows:2}):D.state.kind===`failed-cold`?(0,Q.jsxs)($,{tone:`err`,children:[c(`integrations.rollback.failed`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void D.refresh(),children:c(`common.retry`)})]}):A.length===0?(0,Q.jsx)(`p`,{className:`page-sub`,children:c(`integrations.rollback.empty`)}):(0,Q.jsx)(BN,{rows:A,onRestore:_,onDelete:y}),g&&(0,Q.jsx)(CN,{apiBase:e,row:g,profileId:i,hermesProfile:o,onClose:()=>_(null),onRestored:()=>{t===`droid`?M():j()},onReconcile:j}),v&&(0,Q.jsx)(SN,{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:v.configPath}},onClose:()=>y(null),onConfirm:async()=>{try{await My(e,v.opId,void 0,i,o)}catch(e){if(hy(e)){y(null),await D.refresh();return}throw Error(nb(c,e),{cause:e})}y(null),await D.refresh()}}),b&&(0,Q.jsx)(SN,{copy:b.operation===`overwrite`?eP(k.reason,k.configPath):b.operation===`disable`?nP:tP,plan:b.plan,planLoading:b.loading,planFailure:b.failure,missingStorePath:k.supersededReason===`missing-store`?k.supersededBy:void 0,onClose:P,onConfirm:async e=>{e&&await F(e)}})]})}function sP(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function cP(){throw new my(502,{code:`invalid_aside_profile_response`})}async function lP(e,t){let n=await _y(await fetch(`${e}/api/client-integrations/aside/profiles`,{signal:t}));(!sP(n)||!Array.isArray(n.profiles)||typeof n.allEnabled!=`boolean`)&&cP();let r=n.profiles.map(e=>Gv(e)??cP());new Set(r.map(e=>e.profileId)).size!==r.length&&cP();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))&&cP(),{profiles:r,allEnabled:n.allEnabled,enabledCount:i,appliedCount:a,total:r.length,...typeof n.error==`string`?{error:n.error}:{}}}async function uP(e,t){let n=await _y(await fetch(`${e}/api/client-integrations/aside/sync`,{method:`POST`,headers:{"Content-Type":`application/json`},body:`{}`,signal:t}));(!sP(n)||typeof n.ok!=`boolean`||!Array.isArray(n.results))&&cP(),n.results.some(e=>!sP(e)||e.client!==`aside`)&&cP();let r=Kv(n.results)??cP();return n.ok!==r.every(e=>e.ok)&&cP(),{ok:n.ok,results:r}}var dP={titleKey:`integrations.dialog.apply.title`,changesKey:`integrations.dialog.apply.changes`,breakageKey:`integrations.dialog.apply.breakage`,undoKey:`integrations.dialog.apply.undo`,confirmKey:`integrations.dialog.apply.confirm`},fP={titleKey:`integrations.dialog.disable.title`,changesKey:`integrations.dialog.disable.changes`,breakageKey:`integrations.dialog.disable.breakage`,undoKey:`integrations.dialog.disable.undo`,confirmKey:`integrations.dialog.disable.confirm`};function pP({apiBase:e,active:t=!0}){let r=n(),[i,a]=(0,Z.useState)(null),[o,s]=(0,Z.useState)(null),c=(0,Z.useRef)(!1),[l,u]=(0,Z.useState)(null),[d,f]=(0,Z.useState)(new Map),[p,m]=(0,Z.useState)(null),h=(0,Z.useRef)(null),g=(0,Z.useRef)(0);(0,Z.useEffect)(()=>()=>{g.current+=1,h.current?.abort()},[]);let _=(0,Z.useCallback)(t=>lP(e,t),[e]),v=uo(`aside-profiles:${e}`,[e],_,{enabled:t,isEmpty:e=>!e.error&&e.profiles.length===0,sessionCacheKey:`ocx.integrations.aside-profiles.v1:${e}`}),y=v.state.data,b=y?.profiles??[],x=v.state.showError||!!y?.error,S=o!==null||v.state.refreshing||p!==null,C=e=>e.name||r(`integrations.aside.profile`,{id:e.profileId}),w=e=>f(t=>{let n=new Map(t);for(let t of e)t.ok?n.delete(t.profileId):n.set(t.profileId,rb(r,t));return n}),T=(e,t)=>{e instanceof my&&`results`in e.body&&e.body.results?.length?(w(e.body.results),u(r(`integrations.aside.partial`))):t===void 0?u(nb(r,e)):f(n=>new Map(n).set(t,nb(r,e)))},E=async(t,n,i)=>{if(!c.current){c.current=!0,s(n??`all`),u(null);try{let r=await Ay(e,`aside`,{enabled:t,profileId:n,...i?{binding:yy(i)}:{}});w(r.results??(n===void 0?b.map(e=>e.profileId):[n]).map(e=>({profileId:e,ok:!0})))}catch(e){if(i&&e instanceof my&&e.stalePlan)throw e;if(T(e,n),i)throw Error(nb(r,e),{cause:e})}finally{v.refresh(),c.current=!1,s(null)}}},D=async(t,n)=>{if(c.current||p)return;let i=new AbortController,a=g.current+1;g.current=a,h.current?.abort(),h.current=i,m({profile:t,enabled:n,plan:null,loading:!0,failure:null});try{let r=await Oy(e,`aside`,n?`apply`:`disable`,i.signal,t.profileId);if(i.signal.aborted||a!==g.current)return;h.current=null,m({profile:t,enabled:n,plan:r,loading:!1,failure:null})}catch(e){if(i.signal.aborted||a!==g.current)return;if(h.current=null,vy(e)){m(null),v.refresh();return}m({profile:t,enabled:n,plan:null,loading:!1,failure:r(`integrations.preview.failed`)})}},O=()=>{g.current+=1,h.current?.abort(),h.current=null,m(null)},k=async()=>{if(!c.current){c.current=!0,s(`sync`),u(null);try{let t=await uP(e);w(t.results),t.ok||u(r(`integrations.aside.partial`))}catch(e){T(e)}finally{v.refresh(),c.current=!1,s(null)}}};return i?(0,Q.jsxs)(`section`,{className:`integration-client-page`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,autoFocus:!0,onClick:()=>{a(null),v.refresh()},children:r(`integrations.aside.back`)}),d.has(i.profileId)&&(0,Q.jsx)($,{tone:`err`,children:(0,Q.jsx)(`span`,{className:`aside-profile-failure`,children:d.get(i.profileId)})}),(0,Q.jsx)(aP,{apiBase:e,client:`aside`,active:t,profileId:i.profileId,profileLabel:C(i)},i.profileId)]}):(0,Q.jsxs)(`section`,{className:`integration-client-page`,"aria-busy":S,children:[(0,Q.jsxs)(`div`,{className:`integration-client-head`,children:[(0,Q.jsx)(gA,{src:hA(`aside`),label:r(`integrations.tab.aside`),size:24}),(0,Q.jsx)(`h3`,{children:r(`integrations.aside.profilesTitle`)})]}),(0,Q.jsx)(`p`,{className:`page-sub`,children:r(`integrations.aside.profilesHint`)}),(0,Q.jsxs)(`div`,{className:`aside-profile-toolbar`,children:[(0,Q.jsx)(ln,{on:y?.allEnabled??!1,mixed:!!(y&&y.enabledCount>0&&y.enabledCount<y.total),onClick:()=>void E(!y?.allEnabled),disabled:S||x||b.length===0,label:r(`integrations.aside.all`),showLabel:!0}),(0,Q.jsx)(`span`,{className:`text-caption muted`,children:r(`integrations.aside.applied`,{count:y?.appliedCount??0,total:y?.total??0})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn`,disabled:S||x||!y?.enabledCount,onClick:()=>void k(),children:r(`integrations.aside.syncNow`)})]}),l&&(0,Q.jsx)($,{tone:`err`,children:(0,Q.jsx)(`span`,{className:`aside-profile-failure`,children:l})}),[...d].filter(([e])=>!b.some(t=>t.profileId===e)).map(([e,t])=>(0,Q.jsx)($,{tone:`err`,children:(0,Q.jsxs)(`span`,{className:`aside-profile-failure`,children:[r(`integrations.aside.profile`,{id:e}),`: `,t]})},e)),x&&(0,Q.jsxs)($,{tone:`err`,children:[(0,Q.jsx)(`span`,{children:r(`integrations.aside.loadError`)}),y?.error&&(0,Q.jsx)(`span`,{className:`text-caption`,children:y.error}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>v.refresh(),disabled:S,children:r(`common.retry`)})]}),v.state.showSkeleton&&(0,Q.jsx)(lb,{label:r(`common.loading`),rows:3}),!v.state.showSkeleton&&!x&&y&&b.length===0&&(0,Q.jsx)(`p`,{className:`page-sub`,children:r(`integrations.aside.empty`)}),b.length>0&&(0,Q.jsx)(`div`,{className:`aside-profile-list`,children:b.map(e=>{let t=C(e),n=e.state===`current`||e.state===`stale`,i=e.enabled!==n||e.enabled&&e.state===`stale`,s=(!e.installed||e.state===`unsafe`||e.state===`conflict`)&&!e.enabled;return(0,Q.jsxs)(`div`,{className:`aside-profile-row`,"aria-busy":o===e.profileId,children:[(0,Q.jsxs)(`div`,{className:`aside-profile-info`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost aside-profile-name`,"aria-label":r(`integrations.aside.details`,{name:t}),onClick:()=>a(e),disabled:S||x,children:t}),(0,Q.jsxs)(`div`,{className:`aside-profile-meta`,children:[(0,Q.jsx)(`code`,{children:e.profileId}),e.current&&(0,Q.jsx)(`span`,{className:`text-caption muted`,children:r(`integrations.aside.current`)})]}),i&&(0,Q.jsx)(`span`,{className:`text-caption muted`,children:r(`integrations.aside.pending`)}),e.error&&(0,Q.jsx)(`span`,{className:`text-caption muted`,children:e.error}),d.has(e.profileId)&&(0,Q.jsx)($,{tone:`err`,children:(0,Q.jsx)(`span`,{className:`aside-profile-failure`,children:d.get(e.profileId)})})]}),(0,Q.jsxs)(`div`,{className:`aside-profile-controls`,children:[(0,Q.jsx)(pN,{state:e.state,installed:e.installed,id:`aside-profile-state-${e.profileId}`}),i&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:S||x,"aria-label":r(`integrations.aside.retry`,{name:t}),onClick:()=>void D(e,e.enabled),children:r(`common.retry`)}),(0,Q.jsx)(ln,{on:e.enabled,onClick:()=>void D(e,!e.enabled),disabled:S||x||s,label:r(`integrations.aside.toggle`,{name:t})})]})]},e.profileId)})}),p&&(0,Q.jsx)(SN,{copy:p.enabled?dP:fP,plan:p.plan,planLoading:p.loading,planFailure:p.failure,onClose:O,onConfirm:async e=>{e&&(await E(p.enabled,p.profile.profileId,e),m(null))}})]})}var mP=[`absent`,`current`,`stale`,`conflict`,`unsafe`];function hP(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function gP(){throw new my(502,{code:`invalid_hermes_profile_response`})}async function _P(e,t){let n=await _y(await fetch(e+`/api/client-integrations/hermes/profiles`,{signal:t}));(!hP(n)||!Array.isArray(n.profiles))&&gP();let r=n.profiles.map(e=>((!hP(e)||typeof e.hermesProfile!=`string`||typeof e.configPath!=`string`||typeof e.installed!=`boolean`||!mP.includes(e.state))&&gP(),{hermesProfile:e.hermesProfile,configPath:e.configPath,state:e.state,installed:e.installed,...typeof e.error==`string`?{error:e.error}:{}}));return(r[0]?.hermesProfile!=="default"||new Set(r.map(e=>e.hermesProfile)).size!==r.length)&&gP(),r}function vP({apiBase:e,active:t=!0}){let r=n(),[i,a]=(0,Z.useState)(`default`),o=(0,Z.useCallback)(t=>_P(e,t),[e]),s=uo(`hermes-profiles:${e}`,[e],o,{enabled:t,isEmpty:e=>e.length===0,sessionCacheKey:`ocx.integrations.hermes-profiles.v1:${e}`}),c=s.state.data??[],l=c.some(e=>e.hermesProfile===i)?i:`default`,u=e=>e==="default"?r(`integrations.hermes.defaultProfile`):e,d=l==="default"?void 0:l;return(0,Q.jsxs)(`section`,{className:`integration-client-page`,children:[c.length>1&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`h3`,{children:r(`integrations.hermes.profilesTitle`)}),(0,Q.jsx)(`p`,{className:`page-sub`,children:r(`integrations.hermes.profilesHint`)}),(0,Q.jsx)(`ul`,{className:`aside-profile-list hermes-profile-list`,children:c.map(e=>(0,Q.jsxs)(`li`,{className:`aside-profile-row`,children:[(0,Q.jsxs)(`div`,{className:`aside-profile-info`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost aside-profile-name`,"aria-pressed":e.hermesProfile===l,"aria-label":r(`integrations.hermes.select`,{name:u(e.hermesProfile)}),onClick:()=>a(e.hermesProfile),children:u(e.hermesProfile)}),(0,Q.jsx)(`div`,{className:`aside-profile-meta`,children:(0,Q.jsx)(`code`,{children:e.configPath})}),e.error&&(0,Q.jsx)(`span`,{className:`text-caption muted`,children:e.error})]}),(0,Q.jsx)(`div`,{className:`aside-profile-controls`,children:(0,Q.jsx)(pN,{state:e.state,installed:e.installed,id:`hermes-profile-state-${e.hermesProfile}`})})]},e.hermesProfile))})]}),s.state.showError&&(0,Q.jsxs)($,{tone:`err`,children:[(0,Q.jsx)(`span`,{children:r(`integrations.hermes.loadError`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void s.refresh(),disabled:s.state.refreshing,children:r(`common.retry`)})]}),(0,Q.jsx)(aP,{apiBase:e,client:`hermes`,active:t,hermesProfile:d,profileLabel:d===void 0?void 0:r(`integrations.hermes.profileTitle`,{name:d}),onRefresh:()=>void s.refresh()})]})}function yP(e){return e.proposedModel===e.model&&(e.proposedEffort==null||e.proposedEffort===e.effort)}function bP({apiBase:e,busy:t,apply:r}){let i=n(),[a,o]=(0,Z.useState)(!1),[s,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(null),[d,f]=(0,Z.useState)(null),[p,m]=(0,Z.useState)({}),[h,g]=(0,Z.useState)(null),_=async()=>{o(!0),u(null),g(null);try{let t=await vn(await fetch(`${e}/api/codex-agent-roles/auto-assign`,{method:`POST`,headers:{"Content-Type":`application/json`},body:`{}`}),i(`integrations.lazycodexRoles.auto.failed`));f(t??null),m({})}catch(e){f(null),u(e instanceof Error&&e.message?e.message:i(`integrations.lazycodexRoles.auto.failed`))}finally{o(!1)}},v=(d?.proposals??[]).filter(e=>e.status===`proposed`&&e.proposedModel&&!p[e.role]&&!yP(e)),y=async(e,t)=>{let n=await r(e.role,e.proposedModel,e.proposedEffort??void 0,t);return n&&m(t=>({...t,[e.role]:!0})),n},b=async()=>{c(!0);try{let e=0,t=v.length,n;for(let t of v){let r=await y(t,n);r&&(n??=r.batch,e+=1)}g(i(`integrations.lazycodexRoles.auto.appliedCount`,{count:String(e),total:String(t)}))}finally{c(!1)}},x=a||s||t;return(0,Q.jsxs)(`div`,{className:`lazycodex-auto-assign`,children:[(0,Q.jsxs)(`div`,{className:`lazycodex-auto-assign-bar`,children:[(0,Q.jsx)(`p`,{className:`page-sub`,children:i(`integrations.lazycodexRoles.auto.hint`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:x,onClick:()=>void _(),children:i(a?`integrations.lazycodexRoles.auto.running`:`integrations.lazycodexRoles.auto.button`)})]}),l&&(0,Q.jsx)($,{tone:`err`,children:l}),d&&(0,Q.jsxs)(`section`,{className:`lazycodex-auto-assign-panel`,"aria-labelledby":`lazycodex-auto-assign-title`,children:[(0,Q.jsxs)(`div`,{className:`lazycodex-auto-assign-bar`,children:[(0,Q.jsx)(`h5`,{id:`lazycodex-auto-assign-title`,children:i(`integrations.lazycodexRoles.auto.title`)}),(0,Q.jsx)(`span`,{className:`integration-meta`,children:i(`integrations.lazycodexRoles.auto.sizedWith`,{model:d.sizingModel})}),(0,Q.jsxs)(`div`,{className:`lazycodex-auto-assign-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:x||v.length===0,onClick:()=>void b(),children:i(`integrations.lazycodexRoles.auto.applyAll`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:s,onClick:()=>{f(null),g(null)},children:i(`integrations.lazycodexRoles.auto.discard`)})]})]}),d.sizingError&&(0,Q.jsx)($,{tone:`warn`,children:i(`integrations.lazycodexRoles.auto.sizingFailed`,{error:d.sizingError})}),h&&(0,Q.jsx)($,{tone:`ok`,children:h}),(0,Q.jsx)(`ul`,{className:`lazycodex-auto-assign-list`,children:d.proposals.map(e=>(0,Q.jsxs)(`li`,{"aria-label":i(`integrations.lazycodexRoles.auto.proposalFor`,{role:e.role}),children:[(0,Q.jsxs)(`div`,{className:`lazycodex-auto-assign-head`,children:[(0,Q.jsx)(`code`,{children:e.role}),e.tier&&e.effortIntent&&(0,Q.jsx)(`span`,{className:`integration-meta`,children:i(`integrations.lazycodexRoles.auto.tierEffort`,{tier:i(fw[e.tier]),effort:i(pw[e.effortIntent])})})]}),e.status===`unsized`?(0,Q.jsx)(`p`,{className:`integration-meta`,children:i(`integrations.lazycodexRoles.auto.unsized`,{reason:e.reason??``})}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`lazycodex-auto-assign-change`,children:[(0,Q.jsx)(`span`,{children:e.model?(0,Q.jsx)(`code`,{children:e.model}):i(`integrations.lazycodexRoles.none`)}),(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`→`}),e.proposedModel?(0,Q.jsxs)(`code`,{children:[e.proposedModel,e.proposedEffort?` · ${e.proposedEffort}`:``]}):(0,Q.jsx)(`span`,{className:`integration-meta`,children:i(`integrations.lazycodexRoles.auto.unassigned`,{reason:e.reason??``})}),e.status===`proposed`&&(p[e.role]||yP(e)?(0,Q.jsx)(`span`,{className:`lazycodex-auto-assign-done`,children:p[e.role]?i(`integrations.lazycodexRoles.auto.applied`):i(`integrations.lazycodexRoles.auto.alreadySet`)}):(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:x,onClick:()=>void y(e),children:i(`integrations.lazycodexRoles.auto.apply`)}))]}),e.rationale&&(0,Q.jsx)(`p`,{children:e.rationale}),e.moveUpIf&&(0,Q.jsx)(`p`,{className:`integration-meta`,children:i(`integrations.lazycodexRoles.auto.moveUp`,{text:e.moveUpIf})}),e.moveDownIf&&(0,Q.jsx)(`p`,{className:`integration-meta`,children:i(`integrations.lazycodexRoles.auto.moveDown`,{text:e.moveDownIf})})]})]},e.role))})]})]})}function xP(e){let t=new Map;for(let n of e)t.set(n.batch,[...t.get(n.batch)??[],n]);return[...t.values()]}function SP(e){let t=new Map;for(let n of e)t.set(n.role,n.before);return t}function CP({history:e,unavailable:t,busy:n,restore:i}){let{locale:a,t:o}=r(),[s,c]=(0,Z.useState)(null),[l,u]=(0,Z.useState)(null);if(t)return(0,Q.jsx)($,{tone:`warn`,children:o(`integrations.lazycodexRoles.history.unavailable`)});if(e.length===0)return null;let d=e=>{let t=e.model??o(`integrations.lazycodexRoles.none`);return e.effort?`${t} · ${e.effort}`:t},f=async e=>{c(e[0].batch),u(null);try{let t,n=[...SP(e)],r=0;for(let[a,o]of n){let n=await i(a,o.model??void 0,o.effort,t,e[0].batch);if(!n)break;t??=n.batch,r+=1}let s=new Date(e[0].at).toLocaleString(a);u(r===n.length?{tone:`ok`,text:o(`integrations.lazycodexRoles.history.restored`,{count:String(r),time:s})}:{tone:`warn`,text:o(`integrations.lazycodexRoles.history.partial`,{count:String(r),total:String(n.length),role:n[r][0]})})}finally{c(null)}};return(0,Q.jsxs)(`div`,{className:`lazycodex-role-history`,children:[(0,Q.jsx)(`h5`,{children:o(`integrations.lazycodexRoles.history.title`)}),(0,Q.jsx)(`p`,{className:`page-sub`,children:o(`integrations.lazycodexRoles.history.hint`)}),l&&(0,Q.jsx)($,{tone:l.tone,children:l.text}),(0,Q.jsx)(`ul`,{children:xP(e).map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`span`,{className:`integration-meta`,children:new Date(e[0].at).toLocaleString(a)}),(0,Q.jsx)(`ul`,{children:e.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`code`,{children:e.role}),`: `,(0,Q.jsx)(`code`,{children:d(e.before)}),` → `,(0,Q.jsx)(`code`,{children:d(e.after)})]},`${e.at}-${e.role}`))}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:n||s!==null,onClick:()=>void f(e),children:s===e[0].batch?o(`common.saving`):o(`integrations.lazycodexRoles.history.restore`)})]},e[0].batch))})]})}var wP={absent:`integrations.lazycodexRoles.omoAbsent`,skipped_comments:`integrations.lazycodexRoles.omoComments`,invalid:`integrations.lazycodexRoles.omoInvalid`,write_failed:`integrations.lazycodexRoles.omoFailed`};function TP({apiBase:e,active:t}){let r=n(),[i,a]=(0,Z.useState)({}),[o,s]=(0,Z.useState)({}),[c,l]=(0,Z.useState)({}),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)(null),m=(0,Z.useCallback)(async t=>{let n=await vn(await fetch(`${e}/api/codex-agent-roles`,{signal:t}),r(`integrations.lazycodexRoles.loadFailed`));if(n?.lazycodex?.detected!==!0)return{detected:!1,roles:[],history:[],historyUnavailable:!1,omoJsonc:null,available:[],efforts:[]};let[i,a]=await Promise.all([fetch(`${e}/api/subagent-models`,{signal:t}).then(e=>vn(e,r(`integrations.lazycodexRoles.loadFailed`))),fetch(`${e}/api/injection-model`,{signal:t}).then(e=>vn(e,r(`integrations.lazycodexRoles.loadFailed`))).catch(()=>null)]);return{detected:!0,roles:n.roles??[],history:n.history??[],historyUnavailable:n.historyUnavailable===!0,omoJsonc:n.omoJsonc??null,available:i?.available??[],efforts:a?.efforts??[]}},[e,r]),h=`lazycodex-role-models:${e}`,g=uo(h,[e],m,{isEmpty:e=>e.roles.length===0,enabled:t}),_=g.state.data,v=(0,Z.useRef)(_);(0,Z.useLayoutEffect)(()=>{v.current=_},[_]);let y=async(t,n,i=void 0,o,f,m)=>{if(u!==null)return null;let _=i===void 0?c[t]?.sent:i;if(n===void 0&&_===void 0)return null;d(t),p(null);try{let i=await vn(await fetch(`${e}/api/codex-agent-roles/${encodeURIComponent(t)}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...n===void 0?{}:{model:n},..._===void 0?{}:{effort:_},...f===void 0?{}:{batch:f},...m===void 0?{}:{restores:m}})}),r(`integrations.lazycodexRoles.saveFailed`,{role:t})),c=i?.omoJsonc?.status,u=v.current,d=u?.roles.find(e=>e.role===t),y=_===void 0?d?d.effort??null:o||null:_,b=y??``,x=n??d?.model??null;if(u){let e={...u,roles:u.roles.map(e=>e.role===t?{...e,model:n??e.model,effort:y,omoJsoncModel:n!==void 0&&(c===`written`||c===`unchanged`)?n:e.omoJsoncModel}:e)};v.current=e,Kt(h,e)}let S=c?wP[c]:void 0,C=x??r(`integrations.lazycodexRoles.none`),w=b?`${C} · ${b}`:C;p(S?{tone:`warn`,text:r(S,{role:t,model:w})}:{tone:`ok`,text:r(`integrations.lazycodexRoles.saved`,{role:t,model:w})});let T=c===`write_failed`,E=(e,n)=>{let{[t]:r,...i}=e;return T?{...i,[t]:n}:i};return a(e=>E(e,n??``)),s(e=>E(e,b)),l(e=>E(e,{sent:_})),await g.refresh(),{batch:i?.batch}}catch{return p({tone:`err`,text:r(`integrations.lazycodexRoles.saveFailed`,{role:t})}),null}finally{d(null)}},b=(e,t)=>{let n=[...new Set([...e.model?[e.model]:[],..._?.available??[]])];return[...t===``?[{value:``,label:r(`integrations.lazycodexRoles.choose`)}]:[],...n.map(e=>({value:e,label:e}))]};return g.state.kind===`failed-cold`?(0,Q.jsxs)($,{tone:`err`,children:[r(`integrations.lazycodexRoles.loadFailed`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void g.refresh(),children:r(`common.retry`)})]}):_?.detected?(0,Q.jsxs)(`section`,{id:`lazycodex-role-models`,className:`lazycodex-role-models`,"aria-labelledby":`lazycodex-role-models-title`,children:[(0,Q.jsx)(`h4`,{id:`lazycodex-role-models-title`,children:r(`integrations.lazycodexRoles.title`)}),(0,Q.jsx)(`p`,{className:`page-sub`,children:r(`integrations.lazycodexRoles.hint`)}),_.omoJsonc?.state===`comments`&&(0,Q.jsx)($,{tone:`warn`,children:r(`integrations.lazycodexRoles.omoCommentsState`)}),f&&(0,Q.jsx)($,{tone:f.tone,children:f.text}),_.roles.length===0?(0,Q.jsx)(`p`,{className:`page-sub`,children:r(`integrations.lazycodexRoles.empty`)}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(bP,{apiBase:e,busy:u!==null,apply:(e,t,n,r)=>y(e,t,n,void 0,r)}),(0,Q.jsx)(`div`,{className:`tbl-wrap`,children:(0,Q.jsxs)(`table`,{className:`tbl`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:r(`integrations.lazycodexRoles.role`)}),(0,Q.jsx)(`th`,{children:r(`integrations.lazycodexRoles.current`)}),(0,Q.jsxs)(`th`,{children:[r(`integrations.lazycodexRoles.model`),` · `,r(`integrations.lazycodexRoles.effort`)]})]})}),(0,Q.jsx)(`tbody`,{children:_.roles.map(e=>{let t=i[e.role]??e.model??``,n=o[e.role]??e.effort??``,l=n!==(e.effort??``),d=t!==``&&t!==e.model||l,f=c[e.role],p=f!==void 0&&(t!==``||f.sent!==void 0);return(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`code`,{children:e.role})}),(0,Q.jsx)(`td`,{children:e.model?(0,Q.jsx)(`code`,{children:e.effort?`${e.model} · ${e.effort}`:e.model}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`integration-meta`,children:r(`integrations.lazycodexRoles.none`)}),e.effort&&(0,Q.jsxs)(Q.Fragment,{children:[` · `,(0,Q.jsx)(`code`,{children:e.effort})]})]})}),(0,Q.jsx)(`td`,{children:(0,Q.jsxs)(`div`,{className:`lazycodex-role-models-edit`,children:[(0,Q.jsx)(dn,{value:t,options:b(e,t),label:r(`integrations.lazycodexRoles.modelFor`,{role:e.role}),disabled:u!==null,onChange:t=>a(n=>({...n,[e.role]:t}))}),(0,Q.jsx)(dn,{value:n,options:[{value:``,label:r(`integrations.lazycodexRoles.effortDefault`)},...[...new Set([...e.effort?[e.effort]:[],..._.efforts])].map(e=>({value:e,label:e}))],label:r(`integrations.lazycodexRoles.effortFor`,{role:e.role}),disabled:u!==null,onChange:t=>s(n=>({...n,[e.role]:t}))}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:!(d||p)||u!==null,onClick:()=>void y(e.role,t||void 0,l?n||null:void 0,e.effort??``),children:u===e.role?r(`common.saving`):r(p&&!d?`integrations.lazycodexRoles.retryMirror`:`common.save`)})]})})]},e.role)})})]})}),(0,Q.jsx)(CP,{history:_.history,unavailable:_.historyUnavailable,busy:u!==null,restore:(e,t,n,r,i)=>y(e,t,n,void 0,r,i)})]})]}):null}var EP=[{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:`claude`,labelKey:`nav.claude`},{id:`claudeDesktop`,hash:`claude/desktop`,labelKey:`claudeDesktop.title`},{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:`gentle-shell`,hash:`integrations/gentle-shell`,labelKey:`integrations.tab.gentleShell`},{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:`commandcode`,hash:`integrations/commandcode`,labelKey:`integrations.tab.commandcode`},{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:`qoder`,hash:`integrations/qoder`,labelKey:`integrations.tab.qoder`},{id:`qoder-cn`,hash:`integrations/qoder-cn`,labelKey:`integrations.tab.qoderCn`},{id:`workbuddy`,hash:`integrations/workbuddy`,labelKey:`integrations.tab.workbuddy`},{id:`workbuddy-ai`,hash:`integrations/workbuddy-ai`,labelKey:`integrations.tab.workbuddyAi`},{id:`cline`,hash:`integrations/cline`,labelKey:`integrations.tab.cline`},{id:`kilo`,hash:`integrations/kilo`,labelKey:`integrations.tab.kilo`},{id:`droid`,hash:`integrations/droid`,labelKey:`integrations.tab.droid`},{id:`t3code`,hash:`integrations/t3code`,labelKey:`integrations.tab.t3code`}],DP=new Set([`opencode`,`pi`,`gentle-shell`,`omp`,`hermes`,`openclaw`,`kimi`,`gajae`,`dsh`,`mcode`,`zcode`,`commandcode`,`prime`,`aside`,`raycast`,`omo`,`cline`,`kilo`,`droid`,`qoder`,`qoder-cn`,`workbuddy`,`workbuddy-ai`,`t3code`]);function OP(e=window.location.hash){let t=Gg(e);return t===`claude/desktop`?`claudeDesktop`:t===`claude`||t.startsWith(`claude/`)?`claude`:EP.find(e=>e.hash===t)?.id??`overview`}function kP(e){return`integrations-tab-${e}`}function AP(e){return`integrations-panel-${e}`}function jP(e){return e===`overview`||e===`keys`?null:fA[e]??null}function MP({apiBase:e,machineApiBase:t=e,connected:r=!1}){let i=n(),[a,o]=(0,Z.useState)(OP),[s,c]=(0,Z.useState)(()=>new Set([OP()])),l=(0,Z.useRef)(null),[u,d]=(0,Z.useState)([]),[f,p]=(0,Z.useState)(!1);l.current===null&&(l.current=new Map),(0,Z.useEffect)(()=>{if(!r)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)&&d(t.selectedClients.filter(e=>typeof e==`string`))}).catch(()=>{}),()=>e.abort()},[r,t]);let m=async()=>{p(!0);try{await fetch(`${t}/api/machine/sync`,{method:`POST`,headers:{"Content-Type":`application/json`},body:`{}`})}finally{p(!1)}},h=e=>{o(e),c(t=>t.has(e)?t:new Set([...t,e]))};(0,Z.useEffect)(()=>{let e=()=>h(OP());return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]);let g=(e,t)=>{let n=EP.find(t=>t.id===e);n&&(Xt(n.hash),h(e),t&&window.requestAnimationFrame(()=>{l.current.get(e)?.focus({preventScroll:!0})}))},_=e=>{let t=EP.findIndex(e=>e.id===a),n=null;e.key===`ArrowLeft`?n=(t-1+EP.length)%EP.length:e.key===`ArrowRight`?n=(t+1)%EP.length:e.key===`Home`?n=0:e.key===`End`&&(n=EP.length-1),n!==null&&(e.preventDefault(),g(EP[n].id,!0))};return(0,Q.jsxs)(`section`,{className:`integrations-page`,children:[(0,Q.jsx)(`div`,{className:`page-head`,children:(0,Q.jsx)(`h2`,{children:i(`nav.connect`)})}),(0,Q.jsx)(`p`,{className:`page-sub`,children:i(`integrations.subtitle`)}),r&&(0,Q.jsxs)(`section`,{className:`notice`,"aria-label":i(`connection.clients.title`),children:[(0,Q.jsx)(`strong`,{children:i(`connection.clients.title`)}),(0,Q.jsx)(`span`,{children:u.length>0?u.join(`, `):i(`connection.clients.none`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:f,onClick:()=>void m(),children:i(f?`connection.clients.syncing`:`connection.clients.sync`)})]}),(0,Q.jsx)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":i(`integrations.tabsLabel`),children:EP.map(e=>(0,Q.jsxs)(`button`,{ref:t=>{t?l.current.set(e.id,t):l.current.delete(e.id)},type:`button`,role:`tab`,id:kP(e.id),"aria-selected":a===e.id,"aria-controls":AP(e.id),tabIndex:a===e.id?0:-1,className:`page-tab${a===e.id?` page-tab--active`:``}`,onClick:()=>g(e.id,!0),onKeyDown:_,children:[e.id!==`overview`&&e.id!==`keys`&&(0,Q.jsx)(gA,{src:jP(e.id),label:i(e.labelKey),size:14}),i(e.labelKey)]},e.id))}),EP.map(t=>{if(!s.has(t.id))return null;let n=a===t.id;return(0,Q.jsxs)(`div`,{role:`tabpanel`,id:AP(t.id),"aria-labelledby":kP(t.id),hidden:!n,children:[t.id===`overview`&&(0,Q.jsx)(XN,{apiBase:e,active:n}),t.id===`keys`&&(0,Q.jsx)(fj,{apiBase:e,active:n}),t.id===`codex`&&(0,Q.jsxs)(`section`,{className:`integration-native-page`,"aria-labelledby":`codex-integration-title`,children:[(0,Q.jsx)(`h3`,{id:`codex-integration-title`,children:i(`integrations.codex.title`)}),(0,Q.jsx)(`p`,{children:i(`integrations.codex.body`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>Xt(`startup`),children:i(`integrations.codex.openService`)})]}),t.id===`grok`&&(0,Q.jsx)(iN,{apiBase:e,active:n}),t.id===`claude`&&(0,Q.jsx)(yM,{apiBase:e,active:n,embedded:!0}),t.id===`claudeDesktop`&&(0,Q.jsx)(`div`,{className:`claude-page claude-page--embedded`,children:(0,Q.jsx)(QM,{apiBase:e,active:n},e)}),t.id===`cursor`&&(0,Q.jsx)(uN,{apiBase:e,active:n}),DP.has(t.id)&&(t.id===`aside`?(0,Q.jsx)(pP,{apiBase:e,active:n}):t.id===`hermes`?(0,Q.jsx)(vP,{apiBase:e,active:n}):(0,Q.jsx)(aP,{apiBase:e,client:t.id,active:n})),t.id===`omo`&&(0,Q.jsx)(TP,{apiBase:e,active:n})]},t.id)})]})}function NP(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 PP={native:`startup.status.native`,protected:`startup.status.protected`,"at-risk":`startup.status.atRisk`},FP={native:`startup.summary.native`,protected:`startup.summary.protected`,"at-risk":`startup.summary.atRisk`},IP={desktop:`startup.protection.desktop`,service:`startup.protection.service`,shim:`startup.protection.shim`,none:`startup.protection.none`};function LP({ok:e,yes:t,no:n}){return(0,Q.jsx)(`span`,{className:`badge ${e?`badge-green`:`badge-amber`}`,children:e?t:n})}function RP({failed:e,data:t}){let{t:n}=r(),i=e?`startup-hero--risk`:t.status===`protected`?`startup-hero--safe`:t.status===`at-risk`?`startup-hero--risk`:`startup-hero--native`,a=e||t.status===`at-risk`?Ne:Oe,o=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,Q.jsx)(Q.Fragment,{children:(0,Q.jsxs)(`section`,{className:`panel startup-hero ${i}`,"aria-live":`polite`,children:[(0,Q.jsx)(`div`,{className:`startup-hero-icon`,children:(0,Q.jsx)(a,{})}),(0,Q.jsxs)(`div`,{className:`startup-hero-copy`,children:[(0,Q.jsx)(`span`,{className:`badge ${e||t.status===`at-risk`?`badge-amber`:`badge-green`}`,children:n(e?`startup.status.atRisk`:PP[t.status])}),(0,Q.jsx)(`h3`,{children:n(e?`startup.error`:FP[t.status])}),(0,Q.jsx)(`p`,{children:e?n(`startup.staleData`):t.status===`at-risk`?n(Eo(t)):n(`startup.safeDetail`)}),(0,Q.jsxs)(`p`,{className:`muted startup-state-line`,children:[n(o),` · `,n(IP[t.protection]),` · `,n(t.autostartEnabled?`startup.enabled`:`startup.disabled`)]}),(0,Q.jsx)(`p`,{className:`muted text-label`,children:n(`startup.subtitle`)})]})]})})}function zP({data:e,failed:t,loading:n=!1,installBusy:i,installResult:a,onInstall:o}){let{t:s}=r(),c=e.serviceSupported&&e.serviceInstalled&&e.serviceStale&&!e.serviceConflict,l=e.shimInstalled&&!e.shimHealthy&&e.shimActivationPending===!0,u=e.shimInstalled&&!e.shimHealthy&&!l,d=i!==null||t||n,f=d||wo(e);return(0,Q.jsxs)(`section`,{className:`panel startup-details`,children:[(0,Q.jsxs)(`div`,{className:`panel-head`,children:[(0,Q.jsx)(`h3`,{className:`panel-title`,children:s(`startup.details`)}),(0,Q.jsx)(`span`,{className:`muted mono`,children:e.platform})]}),e.desktop&&(0,Q.jsxs)(`div`,{className:`startup-detail-row`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:s(`startup.protection.desktop`)}),(0,Q.jsx)(`span`,{children:s(!t&&e.desktop.viable?`startup.desktopHint`:Eo(e))})]}),(0,Q.jsx)(`div`,{className:`startup-detail-actions`,children:(0,Q.jsx)(LP,{ok:!t&&e.desktop.viable,yes:s(`startup.viable`),no:s(To(e.desktop,t))})})]}),(0,Q.jsxs)(`div`,{className:`startup-detail-row`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:s(`startup.service`)}),(0,Q.jsx)(`span`,{children:s(`startup.serviceHint`)})]}),(0,Q.jsxs)(`div`,{className:`startup-detail-actions`,children:[(0,Q.jsx)(LP,{ok:e.serviceViable,yes:s(`startup.viable`),no:s(e.serviceConflict?`startup.conflict`:e.serviceStale?`startup.stale`:e.serviceInstalled?`startup.unhealthy`:e.serviceSupported?`startup.notInstalled`:`startup.unsupported`)}),e.serviceSupported&&!e.serviceInstalled&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,"aria-label":`${s(`startup.service`)} - ${s(`startup.install`)}`,disabled:f,onClick:()=>o(`install-service`),children:s(i===`install-service`?`startup.installing`:`startup.install`)}),c&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,"aria-label":`${s(`startup.service`)} - ${s(`startup.repair`)}`,disabled:f,onClick:()=>o(`install-service`,{repair:!0}),children:s(i===`install-service`?`startup.repairing`:`startup.repair`)})]})]}),(0,Q.jsxs)(`div`,{className:`startup-detail-row`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:s(`startup.shim`)}),(0,Q.jsx)(`span`,{children:s(l?`startup.shimActivationHint`:`startup.shimHint`)})]}),(0,Q.jsxs)(`div`,{className:`startup-detail-actions`,children:[(0,Q.jsx)(LP,{ok:e.shimHealthy&&e.autostartEnabled,yes:s(e.shimCoverage===`cli-only`?`startup.cliOnly`:`startup.healthy`),no:s(e.shimInstalled?e.shimHealthy&&!e.autostartEnabled?`startup.installedDisabled`:l?`startup.shimActivationPending`:`startup.stale`:`startup.notInstalled`)}),!e.shimInstalled&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,"aria-label":`${s(`startup.shim`)} - ${s(`startup.install`)}`,disabled:d,onClick:()=>o(`install-shim`),children:s(i===`install-shim`?`startup.installing`:`startup.install`)}),u&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,"aria-label":`${s(`startup.shim`)} - ${s(`startup.repair`)}`,disabled:d,onClick:()=>o(`install-shim`,{repair:!0}),children:s(i===`install-shim`?`startup.repairing`:`startup.repair`)})]})]}),a&&(0,Q.jsx)(`div`,{className:`notice ${a.kind===`success`?`notice-ok`:`notice-warn`} startup-action-notice`,role:`status`,"aria-live":`polite`,children:a.kind===`success`?a.action===`install-service`?s(a.repair?`startup.serviceRepaired`:`startup.serviceInstalled`):s(a.repair?`startup.shimRepaired`:`startup.shimInstalled`):`${s(`startup.installFailed`)} ${a.detail??``}`})]})}function BP({tray:e,trayLoading:t,trayError:n,trayBusy:i,onTrayAction:a}){let{t:o}=r(),s=async()=>{await ha({message:o(`startup.tray.uninstall`),tone:`danger`})&&a(`uninstall`)};return(0,Q.jsxs)(`section`,{className:`panel startup-actions`,children:[(0,Q.jsxs)(`div`,{className:`panel-head`,children:[(0,Q.jsx)(`h3`,{className:`panel-title`,children:o(`startup.tray.title`)}),(0,Q.jsx)(Ve,{})]}),(0,Q.jsx)(`p`,{className:`muted`,children:o(`startup.tray.hint`)}),(0,Q.jsxs)(`div`,{className:`startup-detail-row`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:o(`startup.tray.login`)}),(0,Q.jsx)(`span`,{children:o(`startup.tray.notProtection`)})]}),t||n||!e?(0,Q.jsx)(`span`,{className:`badge badge-amber`,children:o(t?`startup.tray.loading`:`startup.tray.unavailable`)}):(0,Q.jsx)(LP,{ok:e.running&&!e.stale,yes:o(`startup.tray.running`),no:o(e.stale?`startup.tray.stale`:e.installed?`startup.tray.stopped`:`startup.tray.notInstalled`)})]}),(0,Q.jsxs)(`div`,{className:`startup-tray-buttons`,children:[!t&&!n&&e&&!e.installed&&!e.stale&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:i,onClick:()=>a(`install`),children:o(`startup.tray.install`)}),!t&&!n&&e?.installed&&!e.stale&&!e.running&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:i,onClick:()=>a(`start`),children:o(`startup.tray.start`)}),!t&&!n&&e?.running&&!e.stale&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:i,onClick:()=>a(`stop`),children:o(`startup.tray.stop`)}),!t&&!n&&e&&(e.installed||e.stale)&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-danger`,disabled:i,onClick:()=>{s()},children:o(`startup.tray.uninstall`)})]}),(n||e?.stale)&&(0,Q.jsx)(`div`,{className:`notice notice-warn startup-tray-error`,role:`alert`,children:o(`startup.tray.error`)})]})}function VP({data:e,copied:t,onCopy:n}){let{t:i}=r(),a=e.serviceInstalled&&!e.serviceConflict?e.commands.repairService:e.commands.installService;return(0,Q.jsxs)(`section`,{className:`panel startup-actions`,children:[(0,Q.jsxs)(`div`,{className:`panel-head`,children:[(0,Q.jsx)(`h3`,{className:`panel-title`,children:i(`startup.recovery`)}),(0,Q.jsx)(me,{})]}),(0,Q.jsxs)(`details`,{className:`startup-recovery-details`,open:e.status!==`protected`,children:[(0,Q.jsx)(`summary`,{className:`muted`,children:i(wo(e)?`startup.protection.desktop`:`startup.recoveryHint`)}),wo(e)&&(0,Q.jsx)(`p`,{className:`muted`,children:i(Eo(e))}),(0,Q.jsxs)(`div`,{className:`startup-command-list`,children:[e.serviceSupported&&!wo(e)&&(0,Q.jsxs)(`div`,{className:`startup-command-row`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:i(`startup.command.service`)}),(0,Q.jsx)(`code`,{children:a})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>n(a),children:i(t===a?`startup.copied`:`startup.copy`)})]}),(0,Q.jsxs)(`div`,{className:`startup-command-row`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:i(`startup.command.shim`)}),(0,Q.jsx)(`code`,{children:e.commands.installShim})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>n(e.commands.installShim),children:t===e.commands.installShim?i(`startup.copied`):i(`startup.copy`)})]}),(0,Q.jsxs)(`div`,{className:`startup-command-row`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:i(`startup.command.native`)}),(0,Q.jsx)(`code`,{children:e.commands.restoreNative})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>n(e.commands.restoreNative),children:t===e.commands.restoreNative?i(`startup.copied`):i(`startup.copy`)})]})]}),e.status===`at-risk`&&e.recommendedCommand&&!wo(e)&&(0,Q.jsxs)(`div`,{className:`notice notice-warn startup-action-notice`,role:`alert`,children:[(0,Q.jsx)(Ve,{}),` `,i(`startup.recommended`,{cmd:e.recommendedCommand})]})]})]})}var HP=`ocx.startup.page.v1:`;function UP(e,t){let n=t===`win32`?`; `:` && `;return e.join(n)}function WP(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=UP([`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 GP({apiBase:e,machineApiBase:t=e,connected:n=!1}){let{t:i}=r(),a=`${HP}${e}`,o=(0,Z.useMemo)(()=>io(a),[a]),s=`startup-page:${e}`,[c,l]=(0,Z.useState)(null),[u,d]=(0,Z.useState)(()=>o?.tray??null),[f,p]=(0,Z.useState)(()=>!o?.data),[m,h]=(0,Z.useState)(!1),[g,_]=(0,Z.useState)(!1),[v,y]=(0,Z.useState)(null),[b,x]=(0,Z.useState)(null),[S,C]=(0,Z.useState)(()=>o?.warning??null),[w,T]=(0,Z.useState)(()=>o?.fix??null),[E,D]=(0,Z.useState)(()=>!o?.data),O=(0,Z.useRef)(!!o?.data),k=(0,Z.useRef)(0),[A,j]=(0,Z.useState)(null),[M,N]=(0,Z.useState)(!1);(0,Z.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,Z.useEffect)(()=>()=>{k.current+=1},[e]);let F=(0,Z.useCallback)(async t=>{let n=++k.current,r=O.current;r||(p(!0),D(!0));try{let r=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||s.shimActivationPending===!0)))?null:e),O.current=!0;let c=io(a);co(a,{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(!NP(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([r,l]).then(([e,r])=>{if(t.aborted||n!==k.current)return;let o=s.platform===`win32`?r.tray:null;if(s.platform===`win32`?(d(o),_(r.error)):(d(null),_(!1)),p(!1),D(!1),e){let t=WP(e.codexRuntime,i,s.platform);C(t.warning),T(t.fix),co(a,{data:s,warning:t.warning,fix:t.fix,tray:o});return}let c=io(a);co(a,{data:s,warning:c?.warning??null,fix:c?.fix??null,tray:o})}),s}catch(e){throw t.aborted||(r||(d(null),_(!0),C(null),T(null)),D(!1),p(!1)),e}},[e,a,i]),I=uo(s,[e],F,{isEmpty:()=>!1,initialData:o?.data??void 0}),L=I.state,R=I.refresh,z=L.data??o?.data??null,B=L.refreshing,V=!!z?.diagnosticStale||L.showError;(0,Z.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),l(e),window.setTimeout(()=>l(t=>t===e?null:t),1600)}catch{l(null)}},U=async t=>{h(!0),_(!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(!NP(r.status))throw Error(`invalid tray action status`);d(r.status),_(!1)}catch{d(null),_(!0)}finally{h(!1)}},ee=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,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`page-head`,children:[(0,Q.jsx)(`h2`,{children:i(`startup.title`)}),(0,Q.jsx)(`div`,{className:`startup-page-head-actions`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>R(),disabled:B,children:[(0,Q.jsx)(ae,{}),` `,i(`startup.refresh`)]})})]}),n&&(0,Q.jsxs)(`section`,{className:`notice startup-page-notice`,"aria-label":i(`connection.machine.title`),children:[(0,Q.jsx)(`strong`,{children:i(`connection.machine.title`)}),(0,Q.jsx)(`span`,{children:A?.healthy?i(`connection.machine.shimHealthy`):i(`connection.machine.shimNeedsAttention`)}),(0,Q.jsxs)(`div`,{className:`startup-page-head-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:M,onClick:()=>void P(`repair`),children:i(`connection.machine.repairShim`)}),A?.installed&&(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:M,onClick:()=>void P(`uninstall`),children:i(`connection.machine.removeShim`)})]})]}),L.showSkeleton&&!z?(0,Q.jsx)(lb,{label:i(`startup.loading`),rows:5}):L.kind===`failed-cold`?(0,Q.jsxs)(`div`,{className:`startup-page-notice`,children:[(0,Q.jsx)($,{tone:`err`,children:L.error instanceof Error?L.error.message:i(`startup.error`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>R(),children:i(`common.retry`)})]}):z?(0,Q.jsxs)(Q.Fragment,{children:[L.showError&&(0,Q.jsx)($,{tone:`err`,children:i(`startup.error`)}),V&&(0,Q.jsx)(`div`,{className:`notice notice-warn startup-page-notice`,role:`alert`,children:i(`startup.staleData`)}),(E||S)&&(0,Q.jsx)(`div`,{className:`startup-runtime-notice-slot${E&&!S?` startup-runtime-notice-slot--pending`:``}`,"aria-hidden":E&&!S?!0:void 0,children:S&&(0,Q.jsxs)(`div`,{className:`notice notice-warn startup-page-notice startup-runtime-notice`,role:`status`,children:[(0,Q.jsx)(`p`,{className:`startup-runtime-notice__text`,children:S}),w&&(0,Q.jsxs)(`div`,{className:`startup-runtime-notice__fix`,children:[(0,Q.jsx)(`code`,{children:w}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void H(w),children:i(c===w?`startup.copied`:`startup.copy`)})]})]})}),(0,Q.jsx)(RP,{failed:V,data:z}),(0,Q.jsx)(zP,{data:z,failed:V,loading:B,installBusy:v,installResult:b,onInstall:(e,t)=>{ee(e,t)}}),z.platform===`win32`&&(0,Q.jsx)(BP,{tray:u,trayLoading:f,trayError:g,trayBusy:m,onTrayAction:e=>{U(e)}}),(0,Q.jsx)(VP,{data:z,copied:c,onCopy:e=>{H(e)}})]}):null]})}function KP(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function qP(e){return`'${e.replace(/'/g,`''`)}'`}function JP(e,t){return{posix:`printf '%s\\n' ${KP(e)} | ocx remote-workspace pair ${KP(t)} --pairing-code-stdin --root "$PWD" && ocx remote-workspace agent`,powershell:`$pairingCode = ${qP(e)}; $pairingCode | ocx remote-workspace pair ${qP(t)} --pairing-code-stdin --root (Get-Location).Path; if ($LASTEXITCODE -eq 0) { ocx remote-workspace agent }`}}var YP=[`codex`,`claude`,`pi`],XP={codex:`Codex`,claude:`Claude Code`,pi:`Pi`},ZP={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`},QP={status:`remote.event.status`,tool:`remote.event.tool`,error:`remote.event.error`},$P=8,eF=e=>e?e.type===`pane`?[e.sessionId]:[...eF(e.first),...eF(e.second)]:[],tF=e=>({type:`pane`,sessionId:e});function nF(e){if(e.type===`pane`)return 260;let t=nF(e.first),n=nF(e.second);return e.axis===`row`?t+$P+n:Math.max(t,n)}function rF(e,t){if(!e)return null;if(e.type===`pane`)return e.sessionId===t?null:e;let n=rF(e.first,t),r=rF(e.second,t);return n?r?n===e.first&&r===e.second?e:{...e,first:n,second:r}:n:r}function iF(e,t,n){return e.type===`pane`?e.sessionId===t?n:e:{...e,first:iF(e.first,t,n),second:iF(e.second,t,n)}}function aF(e,t,n){return e?eF(e).includes(t)?e:iF(e,eF(e).includes(n)?n:eF(e)[0],tF(t)):tF(t)}function oF(e,t,n,r){if(!e)return tF(t);let i=eF(e);if(t===n||!i.includes(n)||i.length>=4&&!i.includes(t))return e;let a=rF(e,t),o=r===`left`||r===`up`,s=new Set,c=e=>{e.type!==`pane`&&(s.add(e.id),c(e.first),c(e.second))};c(a);let l=1;for(;s.has(`split-${l}`);)l++;return iF(a,n,{type:`split`,id:`split-${l}`,axis:r===`left`||r===`right`?`row`:`column`,ratio:.5,first:tF(o?t:n),second:tF(o?n:t)})}function sF(e,t,n){return e.type===`pane`?e:e.id===t?{...e,ratio:Math.min(.8,Math.max(.2,n))}:{...e,first:sF(e.first,t,n),second:sF(e.second,t,n)}}function cF(e,t,n){let r=new Set(t),i=e;for(let t of eF(e))r.has(t)||(i=rF(i,t));return i??(n&&r.has(n)?tF(n):t.length?tF(t[t.length-1]):null)}function lF(e){if(!e||e.length>8192)return null;let t=new Set,n=new Set;function r(e,i){if(!e||typeof e!=`object`||i>4)return null;let a=e;if(a.type===`pane`&&typeof a.sessionId==`string`&&a.sessionId.length>0&&a.sessionId.length<200&&!t.has(a.sessionId))return t.add(a.sessionId),t.size<=4?tF(a.sessionId):null;if(a.type!==`split`||typeof a.id!=`string`||a.id.length>400||a.axis!==`row`&&a.axis!==`column`||typeof a.ratio!=`number`||!Number.isFinite(a.ratio)||n.has(a.id))return null;n.add(a.id);let o=r(a.first,i+1),s=r(a.second,i+1);return o&&s?{type:`split`,id:a.id,axis:a.axis,ratio:Math.min(.8,Math.max(.2,a.ratio)),first:o,second:s}:null}try{return r(JSON.parse(e),0)}catch{return null}}function uF(e,t,r,i,a){let o=n(),[s,c]=(0,Z.useState)({}),[l,u]=(0,Z.useState)({}),[d,f]=(0,Z.useState)({}),[p,m]=(0,Z.useState)({}),h=(0,Z.useRef)(new Set),g=(0,Z.useRef)(new Set),_=(0,Z.useRef)(new Set),v=t.map(e=>{let t=l[e.id];return t?.status===`stopped`?{...e,status:`stopped`}:t&&(t.events.at(-1)?.sequence??0)>(e.events.at(-1)?.sequence??0)?t:e}),y=(e,t)=>c(n=>({...n,[e]:t})),b=(e,t)=>m(n=>({...n,[e]:t})),x=(e,t,n)=>f(r=>({...r,[e]:{...r[e],[t]:n}})),S=e=>!(!(s[e.id]??``).trim()||d[e.id]?.prompt||d[e.id]?.stop||i||e.status===`running`||e.status===`starting`||e.status===`stopped`||e.status===`failed`&&e.resumable===!1||e.status===`waiting_for_executor`&&!r.find(t=>t.id===e.deviceId)?.online);return{sessions:v,drafts:s,setDraft:y,pending:d,errors:p,canSend:S,send:async t=>{let n=t.id;if(!S(t)||g.current.has(n)||_.current.has(n))return;let r=s[n]??``;g.current.add(n),x(n,`prompt`,!0),b(n,``);let i;try{let t=await fetch(`${e}/api/remote-workspace/sessions/${n}/prompt`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({prompt:r})});i=t.status;let s=await vn(t,o(`remote.requestFailed`));if(!s)throw Error(o(`remote.requestFailed`));c(e=>e[n]===r?{...e,[n]:``}:e),h.current.has(n)||u(e=>({...e,[n]:s})),a()}catch(e){h.current.has(n)||(b(n,i!==void 0&&i>=400&&i<500?e instanceof Error?e.message:o(`remote.requestFailed`):o(`remote.submissionUnknown`)),a())}finally{g.current.delete(n),x(n,`prompt`,!1)}},stop:async t=>{let n=t.id;if(!(_.current.has(n)||t.status===`stopped`)){_.current.add(n),x(n,`stop`,!0);try{await vn(await fetch(`${e}/api/remote-workspace/sessions/${n}`,{method:`DELETE`}),o(`remote.requestFailed`)),h.current.add(n),u(e=>({...e,[n]:{...t,status:`stopped`}})),a()}catch(e){b(n,e instanceof Error?e.message:o(`remote.requestFailed`))}finally{_.current.delete(n),x(n,`stop`,!1)}}}}}var dF=`application/x-opencodex-session`,fF=[`left`,`right`,`up`,`down`],pF=e=>e.type===`split`?nF(e):0;function mF({node:e,renderPane:t,resize:r}){let i=n(),a=(0,Z.useRef)(null),o=(0,Z.useRef)(!1);if(e.type===`pane`)return t(e.sessionId);let s={"--split-ratio":e.ratio,"--split-min-width":nF(e),"--split-first-min":pF(e.first),"--split-second-min":pF(e.second)};return(0,Q.jsxs)(`div`,{ref:a,className:`remote-split-branch remote-split-branch--${e.axis}`,style:s,children:[(0,Q.jsx)(`div`,{className:`remote-split-child`,children:(0,Q.jsx)(mF,{node:e.first,renderPane:t,resize:r})}),(0,Q.jsx)(`div`,{role:`separator`,tabIndex:0,className:`remote-split-divider`,"aria-label":i(`remote.split.resize`),"aria-orientation":e.axis===`row`?`vertical`:`horizontal`,"aria-valuemin":20,"aria-valuemax":80,"aria-valuenow":Math.round(e.ratio*100),onPointerDown:e=>{e.button===0&&(e.preventDefault(),e.currentTarget.focus(),o.current=!0,e.currentTarget.setPointerCapture(e.pointerId))},onPointerMove:t=>{if(!o.current||!a.current)return;let n=a.current.getBoundingClientRect(),i=e.axis===`row`?n.width:n.height;i>0&&r(e.id,(e.axis===`row`?t.clientX-n.left:t.clientY-n.top)/i)},onPointerUp:e=>{o.current=!1,e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId)},onPointerCancel:()=>{o.current=!1},onLostPointerCapture:()=>{o.current=!1},onKeyDown:t=>{let n=e.axis===`row`?`ArrowLeft`:`ArrowUp`;[n,e.axis===`row`?`ArrowRight`:`ArrowDown`,`Home`,`End`].includes(t.key)&&(t.preventDefault(),r(e.id,t.key===`Home`?.2:t.key===`End`?.8:e.ratio+(t.key===n?-.05:.05)))}}),(0,Q.jsx)(`div`,{className:`remote-split-child`,children:(0,Q.jsx)(mF,{node:e.second,renderPane:t,resize:r})})]})}function hF({apiBase:e,sessions:t,devices:r,selectedSessionId:i,stale:a,refresh:o}){let s=n(),c=`ocx-remote-workspace-layout:${e}`,[l,u]=(0,Z.useState)(()=>{try{return lF(localStorage.getItem(c))}catch{return null}}),[d,f]=(0,Z.useState)(``),[p,m]=(0,Z.useState)(null),[h,g]=(0,Z.useState)(null),[_,v]=(0,Z.useState)(null),[y,b]=(0,Z.useState)(i),x=(0,Z.useRef)(null),S=uF(e,t,r,a,o),C=S.sessions.map(e=>e.id),w=cF(l,C,[...S.sessions].reverse().find(e=>e.status!==`stopped`)?.id??C.at(-1)),T=eF(w),E=T.includes(d)?d:T[0]??``;y===i?l!==w&&u(w):(b(i),i&&C.includes(i)&&(u(aF(w,i,E)),f(i))),(0,Z.useEffect)(()=>{try{localStorage.setItem(c,JSON.stringify(w))}catch{}},[w,c]),(0,Z.useEffect)(()=>{_&&[...x.current?.querySelectorAll(`[data-pane-heading]`)??[]].find(e=>e.dataset.paneHeading===_.id)?.focus()},[_]);let D=e=>{u(aF(w,e,E)),f(e)},O=(e,t,n)=>{if(!C.includes(e))return;let r=oF(w,e,t,n);u(r),eF(r).includes(e)&&f(e),m(null),g(null)},k=e=>{let t=rF(w,e),n=eF(t)[0]??``;u(t),f(n),v({id:n})},A=(e,t)=>{e.dataTransfer.setData(dF,t),e.dataTransfer.effectAllowed=`move`,m(t)},j=()=>{m(null),g(null)},M=(e,t)=>e!==t&&(T.includes(e)||T.length<4);return(0,Q.jsxs)(`section`,{ref:x,className:`remote-chats-workspace`,"aria-label":s(`remote.split.title`),children:[(0,Q.jsxs)(`div`,{className:`remote-chats-toolbar`,children:[(0,Q.jsx)(`h3`,{children:s(`remote.sessions`)}),(0,Q.jsx)(`p`,{children:s(`remote.split.hint`)})]}),(0,Q.jsxs)(`div`,{className:`remote-chats-layout`,children:[(0,Q.jsxs)(`aside`,{className:`remote-session-rail`,"aria-label":s(`remote.sessions`),children:[S.sessions.map(e=>(0,Q.jsxs)(`div`,{className:`remote-session-row${E===e.id?` is-active`:``}`,draggable:!0,onDragStart:t=>A(t,e.id),onDragEnd:j,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`remote-session-open`,"data-session-open":e.id,"aria-pressed":E===e.id,title:s(`remote.split.open`),onClick:()=>D(e.id),children:[(0,Q.jsx)(Re,{}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsxs)(`strong`,{children:[XP[e.profile],` · `,e.rootLabel]}),(0,Q.jsxs)(`small`,{children:[e.deviceName,` · `,s(ZP[e.status])]})]})]}),(0,Q.jsxs)(`div`,{className:`remote-session-split-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,title:s(`remote.split.right`),"aria-label":s(`remote.split.right`),disabled:!E||!M(e.id,E),onClick:()=>O(e.id,E,`right`),children:(0,Q.jsx)(Ye,{})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,title:s(`remote.split.down`),"aria-label":s(`remote.split.down`),disabled:!E||!M(e.id,E),onClick:()=>O(e.id,E,`down`),children:(0,Q.jsx)(tt,{})})]})]},e.id)),T.length>=4?(0,Q.jsx)(`p`,{className:`remote-split-limit`,children:s(`remote.split.limit`)}):null]}),(0,Q.jsx)(`div`,{className:`remote-pane-surface`,children:w?(0,Q.jsx)(mF,{node:w,renderPane:e=>{let t=S.sessions.find(t=>t.id===e);if(!t)return null;let n=t.status===`stopped`||t.status===`failed`&&t.resumable===!1;return(0,Q.jsxs)(`section`,{className:`remote-chat-pane remote-console-panel${e===E?` is-active`:``}`,"data-session-id":e,"aria-label":`${XP[t.profile]} · ${t.deviceName}/${t.rootLabel}`,onFocusCapture:()=>f(e),onPointerDown:()=>f(e),children:[(0,Q.jsxs)(`header`,{className:`remote-chat-pane-head`,children:[(0,Q.jsxs)(`div`,{tabIndex:-1,"data-pane-heading":e,className:`remote-chat-pane-name`,draggable:!0,onDragStart:t=>A(t,e),onDragEnd:j,children:[(0,Q.jsx)(Re,{}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:XP[t.profile]}),(0,Q.jsxs)(`small`,{children:[t.deviceName,`/`,t.rootLabel]})]})]}),(0,Q.jsx)(`span`,{className:`remote-status remote-status--${t.status}`,children:s(ZP[t.status])}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm remote-pane-close`,"aria-label":s(`remote.split.close`),title:s(`remote.split.close`),disabled:T.length===1,onClick:()=>k(e),children:(0,Q.jsx)(xe,{})})]}),(0,Q.jsx)(`small`,{className:`remote-chat-access`,children:t.accessMode===`read-only`?s(`remote.access.readOnly`):t.capabilities.includes(`workspace.exec`)?s(`remote.access.workspace`):s(`remote.access.workspaceFilesOnly`)}),(0,Q.jsx)(`div`,{className:`remote-events`,"aria-live":`polite`,"aria-label":s(`remote.events`),children:t.events.length===0?(0,Q.jsx)(`p`,{className:`remote-empty`,children:s(`remote.noEvents`)}):t.events.map(e=>(0,Q.jsxs)(`div`,{className:`remote-event remote-event--${e.type}`,children:[(0,Q.jsx)(`span`,{children:e.type===`assistant`?XP[t.profile]:s(QP[e.type])}),(0,Q.jsx)(`p`,{children:e.text})]},e.sequence))}),t.status===`failed`&&t.resumable===!1?(0,Q.jsx)($,{tone:`err`,children:s(`remote.notResumable`)}):null,S.errors[e]?(0,Q.jsx)($,{tone:`err`,children:S.errors[e]}):null,(0,Q.jsxs)(`label`,{className:`remote-composer`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:s(`remote.prompt`)}),(0,Q.jsx)(`textarea`,{className:`input`,rows:3,value:S.drafts[e]??``,onChange:t=>S.setDraft(e,t.target.value),placeholder:s(`remote.promptPlaceholder`),disabled:n,onKeyDown:e=>{(e.ctrlKey||e.metaKey)&&e.key===`Enter`&&(e.preventDefault(),S.send(t))}})]}),(0,Q.jsxs)(`div`,{className:`remote-console-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!S.canSend(t),onClick:()=>void S.send(t),children:s(`remote.send`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-danger`,disabled:S.pending[e]?.stop||t.status===`stopped`,onClick:()=>void S.stop(t),children:s(`remote.stop`)})]}),p&&M(p,e)?(0,Q.jsx)(`div`,{className:`remote-pane-drop-targets`,children:fF.map(t=>(0,Q.jsx)(`div`,{className:`remote-pane-drop remote-pane-drop--${t}${h?.id===e&&h.edge===t?` is-over`:``}`,onDragOver:n=>{n.preventDefault(),n.dataTransfer.dropEffect=`move`,g({id:e,edge:t})},onDrop:n=>{n.preventDefault();let r=n.dataTransfer.getData(dF);r===p?O(r,e,t):j()},children:s(`remote.split.${t}`)},t))}):null]},e)},resize:(e,t)=>u(sF(w,e,t))}):(0,Q.jsx)(`p`,{className:`remote-empty remote-empty--console`,children:s(`remote.noSessions`)})})]})]})}function gF(e){return e===`codex`||e===`claude`||e===`pi`}function _F(e){return e===`read-only`||e===`workspace`}async function vF(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}function yF({apiBase:e,hubOrigin:t}){let r=n(),i=Wt(`remote-workspace:${e}`,[e],async t=>await vn(await fetch(`${e}/api/remote-workspace`,{signal:t,cache:`no-store`}),r(`remote.loadFailed`)),{pollMs:3e3,deadlineMs:1e4}),a=i.data,[o,s]=(0,Z.useState)(``),[c,l]=(0,Z.useState)(``),[u,d]=(0,Z.useState)(`codex`),[f,p]=(0,Z.useState)(`read-only`),[m,h]=(0,Z.useState)(``),[g,_]=(0,Z.useState)(null),[v,y]=(0,Z.useState)(null),[b,x]=(0,Z.useState)(null),[S,C]=(0,Z.useState)(null),[w,T]=(0,Z.useState)(null),E=a?.devices??[],D=E.find(e=>e.id===o)??E.find(e=>e.online)??E[0]??null,O=D?.roots.find(e=>e.id===c)??D?.roots[0]??null,k=f===`workspace`&&(D?.capabilities.includes(`workspace.exec`)??!1),A=D&&!D.capabilities.includes(`workspace.exec`)?r(`remote.access.workspaceFilesOnly`):r(`remote.access.workspace`),j=YP.filter(e=>a?.runtimes?.[e]?.available),M=j.includes(u)?u:j[0]??u,N=a?.sessions??[],P=g&&!N.some(e=>e.id===g.id)?[...N,g]:N;g&&a?.sessions.some(e=>e.id===g.id)&&_(null);let F=!(!a||i.lastAttemptOk),L=(0,Z.useMemo)(()=>v?JP(v.code,t):{posix:``,powershell:``},[v,t]),z=async(t,n,r)=>{let i=await vn(await fetch(`${e}${t}`,n),r);if(i===void 0)throw Error(r);return i},B=async()=>{x(`pair`),C(null);try{let e=await z(`/api/remote-workspace/pairing`,{method:`POST`},r(`remote.requestFailed`));y(e),T(null)}catch(e){C({tone:`err`,text:e instanceof Error?e.message:r(`remote.requestFailed`)})}finally{x(null)}},V=async()=>{if(D&&O){x(`session`),C(null);try{let e=await z(`/api/remote-workspace/sessions`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({profile:M,deviceId:D.id,rootId:O.id,accessMode:f})},r(`remote.requestFailed`));_(e),h(e.id),C({tone:`ok`,text:r(`remote.sessionStarted`)}),i.refresh()}catch(e){C({tone:`err`,text:e instanceof Error?e.message:r(`remote.requestFailed`)})}finally{x(null)}}},H=async e=>{if(await ha({message:r(`remote.revokeConfirm`,{name:e.name}),confirmLabel:r(`common.remove`),tone:`danger`})){x(`revoke`);try{await z(`/api/remote-workspace/devices/${e.id}`,{method:`DELETE`},r(`remote.requestFailed`)),o===e.id&&s(``),i.refresh()}catch(e){C({tone:`err`,text:e instanceof Error?e.message:r(`remote.requestFailed`)})}finally{x(null)}}},U=async(e,t)=>{T(await vF(t)?e:null)};return!a&&!i.error?(0,Q.jsx)(`div`,{className:`alert`,children:r(`remote.loading`)}):i.error&&!a?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)($,{tone:`err`,children:r(`remote.loadFailed`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>void i.refresh(),children:r(`common.retry`)})]}):a?.available===!1?(0,Q.jsx)($,{tone:`err`,children:r(`remote.hubRequired`)}):(0,Q.jsxs)(`section`,{className:`remote-workspace-page`,children:[(0,Q.jsxs)(`div`,{className:`page-head`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h2`,{children:r(`remote.title`)}),(0,Q.jsx)(`p`,{className:`page-sub`,children:r(`remote.subtitle`)})]}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void i.refresh(),disabled:i.refreshing,children:[(0,Q.jsx)(ae,{}),` `,r(`remote.refresh`)]})]}),F?(0,Q.jsx)($,{tone:`err`,children:r(`remote.loadFailed`)}):null,S?(0,Q.jsx)($,{tone:S.tone,children:S.text}):null,(0,Q.jsxs)(`div`,{className:`remote-workspace-grid`,children:[(0,Q.jsxs)(`div`,{className:`remote-workspace-column`,children:[(0,Q.jsxs)(`article`,{className:`panel panel-accent remote-pair-card`,children:[(0,Q.jsxs)(`div`,{className:`remote-panel-head`,children:[(0,Q.jsx)(`div`,{className:`remote-icon`,children:(0,Q.jsx)(ut,{})}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h3`,{children:r(`remote.addComputer`)}),(0,Q.jsx)(`p`,{children:r(`remote.addComputerHint`)})]})]}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>void B(),disabled:b!==null,children:[(0,Q.jsx)(I,{}),` `,r(`remote.createPairing`)]}),v?(0,Q.jsxs)(`div`,{className:`remote-pairing-result`,children:[(0,Q.jsx)(`span`,{className:`field-label`,children:r(`remote.pairingCode`)}),(0,Q.jsx)(`div`,{className:`remote-pairing-code`,children:v.code}),(0,Q.jsx)(`div`,{className:`remote-expiry`,children:r(`remote.pairingExpires`,{time:new Date(v.expiresAt).toLocaleTimeString()})}),(0,Q.jsx)(`span`,{className:`field-label`,children:r(`remote.pairingCommandPosix`)}),(0,Q.jsx)(`pre`,{children:(0,Q.jsx)(`code`,{children:L.posix})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void U(`posix`,L.posix),children:r(w===`posix`?`remote.copied`:`remote.copyCommand`)}),(0,Q.jsx)(`span`,{className:`field-label`,children:r(`remote.pairingCommandWindows`)}),(0,Q.jsx)(`pre`,{children:(0,Q.jsx)(`code`,{children:L.powershell})}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void U(`powershell`,L.powershell),children:r(w===`powershell`?`remote.copied`:`remote.copyCommand`)})]}):null]}),(0,Q.jsxs)(`section`,{className:`panel remote-device-panel`,children:[(0,Q.jsxs)(`div`,{className:`remote-section-title`,children:[(0,Q.jsx)(`h3`,{children:r(`remote.devices`)}),(0,Q.jsx)(`span`,{children:E.length})]}),E.length===0?(0,Q.jsx)(`p`,{className:`remote-empty`,children:r(`remote.noDevices`)}):(0,Q.jsx)(`div`,{className:`remote-device-list`,children:E.map(e=>(0,Q.jsxs)(`div`,{className:`remote-device${D?.id===e.id?` selected`:``}`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`remote-device-main`,onClick:()=>{s(e.id),l(e.roots[0]?.id??``)},"aria-pressed":D?.id===e.id,children:[(0,Q.jsx)(`span`,{className:`remote-online-dot${e.online?` online`:``}`}),(0,Q.jsxs)(`span`,{className:`remote-device-copy`,children:[(0,Q.jsx)(`strong`,{children:e.name}),(0,Q.jsxs)(`small`,{children:[e.platform,` · `,e.online?r(`remote.online`):r(`remote.offline`),` · `,e.capabilities.includes(`workspace.exec`)?r(`remote.capability.full`):r(`remote.capability.files`)]})]})]}),(0,Q.jsx)(`button`,{type:`button`,className:`remote-revoke`,"aria-label":r(`remote.revoke`),disabled:b!==null,onClick:()=>void H(e),children:(0,Q.jsx)(R,{})})]},e.id))})]})]}),(0,Q.jsx)(`div`,{className:`remote-workspace-column remote-session-column`,children:(0,Q.jsxs)(`section`,{className:`panel remote-launch-panel`,children:[(0,Q.jsxs)(`div`,{className:`remote-section-title`,children:[(0,Q.jsx)(`h3`,{children:r(`remote.newSession`)}),(0,Q.jsx)(ot,{})]}),(0,Q.jsxs)(`div`,{className:`remote-launch-fields`,children:[(0,Q.jsxs)(`label`,{children:[(0,Q.jsx)(`span`,{className:`field-label`,children:r(`remote.device`)}),(0,Q.jsx)(dn,{value:D?.id??``,options:E.map(e=>({value:e.id,label:e.name})),onChange:e=>{s(e),l(E.find(t=>t.id===e)?.roots[0]?.id??``)},label:r(`remote.device`),disabled:E.length===0})]}),(0,Q.jsxs)(`label`,{children:[(0,Q.jsx)(`span`,{className:`field-label`,children:r(`remote.folder`)}),(0,Q.jsx)(dn,{value:O?.id??``,options:(D?.roots??[]).map(e=>({value:e.id,label:e.label})),onChange:l,label:r(`remote.folder`),disabled:!D})]}),(0,Q.jsxs)(`label`,{children:[(0,Q.jsx)(`span`,{className:`field-label`,children:r(`remote.runtime`)}),(0,Q.jsx)(dn,{value:M,options:YP.map(e=>({value:e,label:a?.runtimes?.[e]?.available?XP[e]:`${XP[e]} · ${r(`remote.unavailable`)}`})),onChange:e=>{gF(e)&&d(e)},label:r(`remote.runtime`)})]}),(0,Q.jsxs)(`label`,{children:[(0,Q.jsx)(`span`,{className:`field-label`,children:r(`remote.access`)}),(0,Q.jsx)(dn,{value:f,options:[{value:`read-only`,label:r(`remote.access.readOnly`)},{value:`workspace`,label:A}],onChange:e=>{_F(e)&&p(e)},label:r(`remote.access`)})]})]}),D?(0,Q.jsxs)(`div`,{className:`remote-execution-map`,children:[(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:XP[M]}),r(`remote.runsOnHub`)]}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`strong`,{children:D.name}),r(f===`read-only`?`remote.runsReadOnly`:k?`remote.runsFilesCommands`:`remote.runsFilesOnly`)]})]}):null,f===`workspace`&&!k&&D?(0,Q.jsx)($,{tone:`err`,children:r(`remote.execUnavailable`)}):null,!a?.runtimes?.[M]?.available&&a?.runtimes?.[M]?.reason?(0,Q.jsx)(`p`,{className:`remote-runtime-reason`,children:a.runtimes[M].reason}):null,(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-primary remote-start`,onClick:()=>void V(),disabled:!D?.online||!O||!a?.runtimes?.[M]?.available||b!==null,children:[(0,Q.jsx)(me,{}),` `,r(`remote.startSession`)]})]})})]}),(0,Q.jsx)(hF,{apiBase:e,sessions:P,devices:E,selectedSessionId:m,stale:F,refresh:i.refresh},e)]})}function bF(){window.location.reload()}var xF={connecting:`remoteLink.status.connecting`,connected:`remoteLink.status.connected`,reconnecting:`remoteLink.status.reconnecting`,failed:`remoteLink.status.failed`,idle:`remoteLink.status.idle`},SF={admission_failed:`remoteLink.error.admission_failed`,admission_timeout:`remoteLink.error.admission_timeout`,compensation_failed:`remoteLink.error.compensation_failed`,fingerprint_failed:`remoteLink.error.fingerprint_failed`,forbidden:`remoteLink.error.forbidden`,host_confirmation_expired:`remoteLink.error.host_confirmation_expired`,host_fingerprint_mismatch:`remoteLink.error.host_fingerprint_mismatch`,host_not_confirmed:`remoteLink.error.host_not_confirmed`,invalid_alias:`remoteLink.error.invalid_alias`,invalid_body:`remoteLink.error.invalid_body`,invalid_link_id:`remoteLink.error.invalid_link_id`,join_connect_failed:`remoteLink.error.join_connect_failed`,join_in_progress:`remoteLink.error.join_in_progress`,join_issue_failed:`remoteLink.error.join_issue_failed`,join_port_failed:`remoteLink.error.join_port_failed`,join_port_mismatch:`remoteLink.error.join_port_mismatch`,join_restart_failed:`remoteLink.error.join_restart_failed`,join_rollback_failed:`remoteLink.error.join_rollback_failed`,join_tunnel_failed:`remoteLink.error.join_tunnel_failed`,key_issue_failed:`remoteLink.error.key_issue_failed`,key_revoke_failed:`remoteLink.error.key_revoke_failed`,link_apply_failed:`remoteLink.error.link_apply_failed`,link_exists:`remoteLink.error.link_exists`,link_not_found:`remoteLink.error.link_not_found`,link_not_home_initiated:`remoteLink.error.generic`,link_remove_failed:`remoteLink.error.link_remove_failed`,link_unavailable:`remoteLink.error.link_unavailable`,listener_unavailable:`remoteLink.error.listener_unavailable`,probe_failed:`remoteLink.error.probe_failed`,remote_connect_failed:`remoteLink.error.remote_connect_failed`,remote_disconnect_failed:`remoteLink.error.remote_disconnect_failed`,remote_ocx_missing:`remoteLink.error.remote_ocx_missing`,remote_ocx_outdated:`remoteLink.error.remote_ocx_outdated`,remote_ocx_unrecognized:`remoteLink.error.remote_ocx_unrecognized`,remote_port_failed:`remoteLink.error.remote_port_failed`,standalone_required:`remoteLink.error.standalone_required`,tailscale_session_refused:`remoteLink.error.tailscale_session_refused`,version_probe_failed:`remoteLink.error.version_probe_failed`},CF={auth:`remoteLink.reason.auth`,hostkey:`remoteLink.reason.hostkey`,forward:`remoteLink.reason.forward`,timeout:`remoteLink.reason.timeout`,bind:`remoteLink.reason.bind`,persist:`remoteLink.reason.persist`,compensation_failed:`remoteLink.reason.compensation_failed`,"stale tunnel may hold the port":`remoteLink.reason.staleTunnel`},wF={pairing_required:`remoteLink.joinDenied.pairing_required`,standalone_required:`remoteLink.childDisabled`,join_port_mismatch:`remoteLink.error.join_port_mismatch`};function TF(e){return typeof e==`object`&&!!e}function EF(e){return typeof e==`string`&&e.length>0}function DF(e){if(!TF(e)||!Array.isArray(e.candidates))throw Error(`invalid candidates`);return e.candidates.map(e=>{if(!TF(e)||!EF(e.alias)||!EF(e.source))throw Error(`invalid candidate`);return{alias:e.alias,source:e.source}})}function OF(e){if(!TF(e)||!EF(e.alias)||!EF(e.fingerprint)||!EF(e.keyType))throw Error(`invalid probe`);return{alias:e.alias,fingerprint:e.fingerprint,keyType:e.keyType}}function kF(e){if(!TF(e)||!EF(e.alias)||!EF(e.fingerprint)||!EF(e.ocxVersion))throw Error(`invalid confirmation`);return{alias:e.alias,fingerprint:e.fingerprint,ocxVersion:e.ocxVersion}}function AF(e){return e instanceof uk&&e.code in SF?SF[e.code]:`remoteLink.error.generic`}function jF(e){return{key:AF(e),hint:e instanceof uk?e.hint:null}}function MF({error:e}){let t=n();return(0,Q.jsxs)($,{tone:`err`,children:[(0,Q.jsx)(`span`,{className:`remote-link-error`,children:t(e.key)}),e.hint&&(0,Q.jsxs)(`span`,{className:`remote-link-hint`,children:[t(`remoteLink.reason.generic`),` `,(0,Q.jsx)(`code`,{children:e.hint})]})]})}function NF({apiBase:e,sessionReady:t,pairingRecoveryAvailable:r=!1,onRequestPairing:i,workspaceAvailable:a=!1,onOpenWorkspace:o,onChildReady:s=bF,restartWait:c}){let l=n(),[u,d]=(0,Z.useState)(`off`),[p,m]=(0,Z.useState)(`home`),[h,g]=(0,Z.useState)(null),[_,v]=(0,Z.useState)(null),[y,b]=(0,Z.useState)(!1),[x,S]=(0,Z.useState)(!1),[C,w]=(0,Z.useState)(`idle`),[T,E]=(0,Z.useState)([]),[D,k]=(0,Z.useState)(``),[j,M]=(0,Z.useState)(null),[N,P]=(0,Z.useState)(null),[F,L]=(0,Z.useState)(!1),[z,B]=(0,Z.useState)(null),[V,H]=(0,Z.useState)(null),[U,ee]=(0,Z.useState)(null),[W,te]=(0,Z.useState)(null),[G,ne]=(0,Z.useState)(null),K=(0,Z.useRef)(null),re=(0,Z.useRef)(null),q=(0,Z.useRef)(null),J=(0,Z.useRef)(null),Y=(0,Z.useRef)([]),ie=(0,Z.useRef)(null),X=(0,Z.useRef)(0),oe=(0,Z.useRef)(null),se=(0,Z.useRef)(0),ce=(0,Z.useRef)(null),le=(0,Z.useRef)(!1),[ue,de]=(0,Z.useState)(!1),fe=r&&i&&(!t||y)?(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:i,children:l(`connection.pairing.title`)}):null,pe=(0,Z.useCallback)(()=>{oe.current?.controller.abort();let e={controller:new AbortController,sequence:++se.current};return oe.current=e,e},[]),me=(0,Z.useCallback)(()=>{se.current+=1,oe.current?.controller.abort(),oe.current=null},[]),he=e=>oe.current?.sequence===e.sequence&&!e.controller.signal.aborted,ge=(0,Z.useCallback)(()=>{X.current+=1,ie.current?.controller.abort(),ie.current=null},[]),_e=(0,Z.useCallback)(async()=>{if(!t||document.visibilityState===`hidden`||le.current)return;ie.current?.controller.abort();let n=new AbortController,r=++X.current;ie.current={controller:n,sequence:r};try{let t=_k(await yk(e,`/api/link/status`,{signal:n.signal}));if(n.signal.aborted||X.current!==r)return;g(t),v(null),b(!1),U?d(`failed`):t.role===`child`?d(`connected`):t.links.length===0?d(e=>[`role-select`,`adding-child`,`confirming-host`,`applying`,`joining`,`restart-waiting`].includes(e)?e:`off`):t.links.some(e=>e.state===`failed`)?d(`failed`):t.links.some(e=>e.state===`reconnecting`)?d(`reconnecting`):t.links.some(e=>e.state===`connected`)&&d(`connected`)}catch(e){if(n.signal.aborted||X.current!==r)return;v(AF(e)),b(e instanceof uk&&(e.status===401||e.status===403))}finally{ie.current?.sequence===r&&(ie.current=null)}},[e,U,t]),ve=(0,Z.useEffectEvent)(()=>{_e()});(0,Z.useEffect)(()=>{if(!t)return;Promise.resolve().then(ve);let e=window.setInterval(ve,5e3),n=()=>{document.visibilityState===`visible`?ve():ge()};return document.addEventListener(`visibilitychange`,n),()=>{window.clearInterval(e),document.removeEventListener(`visibilitychange`,n),ge()}},[ge,t]),(0,Z.useEffect)(()=>{if(u!==`restart-waiting`)return;let t=new AbortController;return Ek(e,ce.current,t.signal,{...c,onSlow:()=>de(!0)}).then(e=>{e===`ready`&&s()}),()=>t.abort()},[e,s,c,u]),(0,Z.useEffect)(()=>{if(!x){let e=re.current?.open;re.current?.close?.(),e&&K.current?.focus();return}let e=re.current;e&&!e.open&&(typeof e.showModal==`function`?e.showModal():e.setAttribute(`open`,``));let t=window.setTimeout(()=>e?.querySelector(`input, button`)?.focus(),0);return()=>window.clearTimeout(t)},[x]),(0,Z.useEffect)(()=>{let e=q.current;W?e&&!e.open&&(typeof e.showModal==`function`?e.showModal():e.setAttribute(`open`,``)):e?.close?.()},[W]);let ye=()=>{me(),S(!1),w(`idle`),E([]),M(null),P(null),L(!1),H(null),ee(null),B(null),d(e=>[`failed`,`adding-child`,`confirming-host`,`applying`,`joining`].includes(e)?`adding-child`:e)},be=A(),Se=be&&h?.joinAvailable===!0,Ce=h?.joinDenied?wF[h.joinDenied]:`remoteLink.joinDenied.unavailable`,we=f(e).shared,Te=be&&window.location.protocol===`http:`&&[`127.0.0.1`,`[::1]`].includes(window.location.hostname)&&we.serverOrigin===window.location.origin,Ee=async()=>{let t=pe();w(`loading`),E([]),H(null),ee(null),B(`candidates`),M(null),P(null),L(!1);try{let n=await yk(e,`/api/link/candidates`,{signal:t.controller.signal});if(!he(t))return;E(DF(n)),w(`ready`)}catch(e){if(!he(t))return;w(`failed`),H(jF(e))}finally{he(t)&&B(null)}},De=async()=>{S(!0),d(`adding-child`),await Ee()},Oe=async(t=D.trim(),n=oe.current??pe())=>{let r=t.trim();if(r){C===`failed`&&w(`idle`),B(`probe`),H(null),M(null),P(null),L(!1),ee(null),d(`adding-child`);try{let t=await yk(e,`/api/link/probe`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({alias:r}),signal:n.controller.signal});if(!he(n))return;M(OF(t))}catch(e){if(!he(n))return;H(jF(e)),ee({phase:`probe`,alias:r}),d(`failed`)}finally{he(n)&&B(null)}}},ke=async()=>{if(!j||!F)return;let t=oe.current;if(t){B(`confirm`),H(null);try{let n=await yk(e,`/api/link/confirm-host`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({alias:j.alias,fingerprint:j.fingerprint}),signal:t.controller.signal});if(!he(t))return;P(kF(n))}catch(e){if(!he(t))return;H(jF(e))}finally{he(t)&&B(null)}}},Ae=async(t=oe.current)=>{let n=N;if(n&&t){B(`apply`),H(null),ee(null),d(`applying`);try{if(await yk(e,`/api/link/apply`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({alias:n.alias}),signal:t.controller.signal}),!he(t))return;ye(),_e()}catch(e){if(!he(t))return;H(jF(e)),ee({phase:`apply`,alias:n.alias}),d(`failed`)}finally{he(t)&&B(null)}}},je=async(t=N?.alias,n=oe.current??pe())=>{let r=t?.trim();if(r&&Se){B(`join`),H(null),ee(null),d(`joining`);try{if(ce.current=(await bk(e,n.controller.signal))?.pid??null,!he(n)||(await yk(e,`/api/link/join`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({alias:r}),signal:n.controller.signal}),!he(n)))return;le.current=!0,ge(),ye(),de(!1),d(`restart-waiting`)}catch(e){if(!he(n))return;H(jF(e)),ee({phase:`join`,alias:r}),d(`failed`)}finally{he(n)&&B(null)}}},Me=async()=>{let t=(h?.links??[]).filter(e=>e.direction===`hub-initiated`&&(e.state===`failed`||e.state===`reconnecting`));if(t.length===0)await _e();else{B(`reconnect`),H(null);try{let n=(await Promise.allSettled(t.map(t=>yk(e,`/api/link/${encodeURIComponent(t.id)}/reconnect`,{method:`POST`})))).find(e=>e.status===`rejected`);n&&H(jF(n.reason))}finally{await _e(),B(null)}}},Ne=()=>{if(!U){Me();return}let e=pe();U.phase===`probe`?(k(U.alias),Oe(U.alias,e)):U.phase===`join`?je(U.alias,e):Ae(e)},Pe=()=>{te(null),ne(null),window.setTimeout(()=>J.current?.focus(),0)},Fe=(e,t)=>{let n=t===`Home`?0:t===`End`?1:t===`ArrowRight`||t===`ArrowDown`||t===`ArrowLeft`||t===`ArrowUp`?(e+1)%2:e;(n!==1||Se)&&n!==e&&(Y.current[n]?.focus(),m(n===0?`home`:`child`))},Ie=async()=>{if(!W)return;let t=W;B(`remove`),ne(null);try{await yk(e,`/api/link/${encodeURIComponent(t.row.id)}`,t.force?{method:`DELETE`,headers:{"content-type":`application/json`},body:JSON.stringify({force:!0})}:{method:`DELETE`}),Pe(),await _e()}catch(e){!t.force&&e instanceof uk&&e.code===`remote_disconnect_failed`?te({row:t.row,force:!0}):ne(AF(e))}finally{B(null)}},Le=h?.links??[],Re=p===`home`&&(u===`adding-child`||u===`confirming-host`||u===`applying`),ze=h?.role===`home`||Re?`remoteLink.role.home`:h?.role===`child`?`remoteLink.role.child`:`remoteLink.role.standalone`,Be=p===`child`&&!Se;return t?(0,Q.jsxs)(`div`,{className:`remote-link-page`,children:[(0,Q.jsxs)(`div`,{className:`page-head`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h2`,{children:l(`link.title`)}),(0,Q.jsx)(`p`,{className:`page-sub`,children:l(`link.subtitle`)})]}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void _e(),disabled:z!==null,children:[(0,Q.jsx)(ae,{}),l(`link.refresh`)]})]}),a&&(0,Q.jsxs)(`section`,{className:`panel remote-link-workspace-card`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:l(`remoteLink.workspaceMoved.title`)}),(0,Q.jsx)(`p`,{children:l(`remoteLink.workspaceMoved.body`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:o??(()=>{window.location.hash=`remote-workspace`}),children:l(`remoteLink.workspaceMoved.open`)})]}),_&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)($,{tone:`err`,children:(0,Q.jsx)(`span`,{className:`remote-link-error`,children:l(_)})}),fe&&(0,Q.jsx)(`section`,{className:`panel`,children:fe})]}),Le.length===0&&u===`off`&&(0,Q.jsxs)(`section`,{className:`panel remote-link-off-preview`,children:[(0,Q.jsxs)(`div`,{className:`remote-link-switch-row`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`strong`,{children:l(`link.switch`)}),(0,Q.jsx)(`p`,{className:`remote-link-info`,children:l(`link.switchOffHint`)})]}),(0,Q.jsx)(`button`,{type:`button`,role:`switch`,className:`remote-link-switch`,"aria-checked":`false`,"aria-label":l(`link.switch`),onClick:()=>d(`role-select`)})]}),(0,Q.jsxs)(`div`,{className:`remote-link-preview-content`,"aria-hidden":`true`,children:[(0,Q.jsxs)(`div`,{className:`remote-link-preview-row`,children:[(0,Q.jsxs)(`div`,{className:`remote-link-preview-lines`,children:[(0,Q.jsx)(`span`,{}),(0,Q.jsx)(`span`,{}),(0,Q.jsx)(`span`,{})]}),(0,Q.jsx)(`span`,{className:`remote-link-status`,children:l(`remoteLink.status.idle`)})]}),(0,Q.jsxs)(`div`,{className:`remote-link-preview-row`,children:[(0,Q.jsxs)(`div`,{className:`remote-link-preview-lines`,children:[(0,Q.jsx)(`span`,{}),(0,Q.jsx)(`span`,{})]}),(0,Q.jsx)(`span`,{className:`remote-link-status`,children:l(`remoteLink.role.child`)})]})]})]}),u===`role-select`&&(0,Q.jsxs)(`section`,{className:`panel remote-link-panel`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h3`,{children:l(`link.role.title`)}),(0,Q.jsx)(`p`,{className:`remote-link-info`,children:l(`link.role.hint`)})]}),(0,Q.jsxs)(`div`,{className:`remote-link-role-grid`,role:`radiogroup`,"aria-label":l(`link.role.title`),children:[(0,Q.jsxs)(`button`,{ref:e=>{Y.current[0]=e},type:`button`,role:`radio`,tabIndex:p===`home`?0:-1,"aria-checked":p===`home`,className:`remote-link-role-card`,onClick:()=>m(`home`),onKeyDown:e=>{[`ArrowRight`,`ArrowDown`,`ArrowLeft`,`ArrowUp`,`Home`,`End`].includes(e.key)&&(e.preventDefault(),Fe(0,e.key))},children:[(0,Q.jsx)(`strong`,{children:l(`link.role.home`)}),(0,Q.jsx)(`span`,{children:l(`link.role.homeHint`)})]}),(0,Q.jsxs)(`button`,{ref:e=>{Y.current[1]=e},type:`button`,role:`radio`,tabIndex:Se&&p===`child`?0:-1,"aria-checked":p===`child`,"aria-disabled":!Se,className:`remote-link-role-card`,onClick:()=>{Se&&(m(`child`),De())},onKeyDown:e=>{Se&&[`ArrowRight`,`ArrowDown`,`ArrowLeft`,`ArrowUp`,`Home`,`End`].includes(e.key)&&(e.preventDefault(),Fe(1,e.key))},children:[(0,Q.jsx)(`strong`,{children:l(`link.role.child`)}),(0,Q.jsx)(`span`,{children:l(`link.role.childHint`)})]})]}),!be&&(0,Q.jsx)($,{tone:`warn`,children:l(`remoteLink.childDisabled`)}),be&&h!==null&&!h.joinAvailable&&(0,Q.jsx)($,{tone:`warn`,children:l(Ce)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:Be||h?.role===`child`,onClick:()=>void De(),children:l(p===`child`?`remoteLink.findHome.action`:`link.continue`)})]}),u===`role-select`&&Te&&h?.joinAvailable===!1&&h.joinDenied===`pairing_required`&&(0,Q.jsx)(Zk,{local:!0,target:we,onConnected:()=>{_e()}}),(u===`connected`||u===`reconnecting`||u===`failed`||u===`restart-waiting`||h?.role===`child`||Le.length>0||u===`adding-child`||u===`confirming-host`||u===`applying`||u===`joining`)&&(0,Q.jsxs)(`section`,{className:`panel remote-link-panel`,children:[(0,Q.jsxs)(`div`,{className:`remote-link-toolbar`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h3`,{children:l(p===`child`&&be?`remoteLink.findHome.title`:`link.children`)}),(0,Q.jsx)(`p`,{className:`remote-link-info`,children:l(u===`restart-waiting`?`remoteLink.restart.waiting`:ze)})]}),(0,Q.jsxs)(`button`,{ref:K,type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>void De(),disabled:z!==null||u===`applying`||u===`joining`||u===`restart-waiting`||h?.role===`child`,children:[(0,Q.jsx)(I,{}),l(p===`child`&&be?`remoteLink.findHome.action`:`link.addChild`)]})]}),u===`restart-waiting`?(0,Q.jsxs)(`div`,{className:`remote-link-restart`,"aria-live":`polite`,children:[(0,Q.jsx)(`strong`,{children:l(`remoteLink.restart.title`)}),(0,Q.jsx)(`p`,{children:l(`remoteLink.restart.body`)}),ue&&(0,Q.jsx)($,{tone:`warn`,children:l(`remoteLink.restart.slow`)})]}):h?.role===`child`?(0,Q.jsx)(`div`,{className:`remote-link-children`,"aria-live":`polite`,children:(0,Q.jsx)(`div`,{className:`remote-link-row`,children:(0,Q.jsxs)(`div`,{className:`remote-link-row-main`,children:[(0,Q.jsx)(`strong`,{children:h.child?.alias??l(`remoteLink.role.child`)}),h.child&&(0,Q.jsx)(`div`,{className:`remote-link-row-meta`,children:(0,Q.jsx)(`span`,{className:`remote-link-status`,"data-state":h.child.state,children:l(xF[h.child.state])})})]})})}):Le.length>0?(0,Q.jsx)(`div`,{className:`remote-link-children`,"aria-live":`polite`,children:Le.map(e=>(0,Q.jsxs)(`div`,{className:`remote-link-row`,children:[(0,Q.jsxs)(`div`,{className:`remote-link-row-main`,children:[(0,Q.jsx)(`strong`,{children:e.alias}),(0,Q.jsxs)(`div`,{className:`remote-link-row-meta`,children:[(0,Q.jsx)(`span`,{className:`remote-link-status`,"data-state":e.state,children:l(xF[e.state])}),(0,Q.jsx)(`span`,{children:e.direction===`hub-initiated`?l(`remoteLink.direction.hub`):l(`remoteLink.direction.client`)}),e.reason&&(0,Q.jsx)(`span`,{className:`remote-link-error`,children:e.reason in CF?l(CF[e.reason]):(0,Q.jsxs)(Q.Fragment,{children:[l(`remoteLink.reason.generic`),` `,(0,Q.jsx)(`code`,{children:e.reason})]})})]})]}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:t=>{J.current=t.currentTarget,te({row:e,force:!1})},disabled:z!==null,children:[(0,Q.jsx)(R,{}),l(`link.disconnect`)]})]},e.id))}):(0,Q.jsx)(`p`,{className:`remote-link-info`,children:l(p===`child`&&be?`remoteLink.findHome.empty`:`link.noChildren`)}),!x&&(u===`reconnecting`||u===`failed`&&(U!==null&&V?.key!==`remoteLink.error.join_restart_failed`||Le.some(e=>e.state===`failed`)))&&(0,Q.jsxs)(`div`,{className:`remote-link-status-message`,"aria-live":`polite`,children:[(0,Q.jsx)(`span`,{className:`remote-link-status`,"data-state":u===`failed`?`failed`:`reconnecting`,children:l(xF[u===`failed`?`failed`:`reconnecting`])}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:Ne,disabled:z!==null,children:l(`link.retry`)})]}),u===`joining`&&(0,Q.jsx)(`p`,{className:`remote-link-info`,"aria-live":`polite`,children:l(`remoteLink.joining`)}),!x&&V&&(0,Q.jsx)(MF,{error:V})]}),(h?.role===`child`||Le.length>0)&&(0,Q.jsx)($a,{apiBase:e,section:`devices`,readOnly:h?.role===`child`}),(0,Q.jsxs)(`dialog`,{ref:re,className:`remote-link-sheet`,"aria-labelledby":`remote-link-sheet-title`,onCancel:e=>{e.preventDefault(),ye()},children:[(0,Q.jsxs)(`div`,{className:`remote-link-sheet-head`,children:[(0,Q.jsx)(`h3`,{id:`remote-link-sheet-title`,children:l(p===`child`&&be?`remoteLink.findHome.title`:`link.sheetTitle`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:ye,"aria-label":l(`link.close`),children:(0,Q.jsx)(xe,{})})]}),(0,Q.jsxs)(`div`,{className:`remote-link-sheet-body`,children:[p===`home`&&(0,Q.jsxs)(`div`,{className:`remote-link-info`,children:[(0,Q.jsx)(`p`,{children:l(`link.setup.relationship`)}),(0,Q.jsx)(`p`,{children:l(`link.setup.requirements`)})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h4`,{children:l(p===`child`&&be?`remoteLink.findHome.body`:`link.candidates`)}),C===`loading`&&(0,Q.jsx)(`p`,{className:`remote-link-info`,role:`status`,children:l(`link.loading`)}),C===`failed`&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`remote-link-info`,children:l(`link.discoveryFailed`)}),x&&V&&(0,Q.jsx)(MF,{error:V})]}),C===`ready`&&(T.length>0?(0,Q.jsx)(`div`,{className:`remote-link-candidates`,children:T.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`remote-link-candidate`,onClick:()=>k(e.alias),children:[(0,Q.jsx)(`span`,{children:e.alias}),(0,Q.jsx)(`small`,{children:e.source})]},`${e.source}:${e.alias}`))}):(0,Q.jsxs)(`div`,{className:`remote-link-info`,children:[(0,Q.jsx)(`p`,{children:l(`link.noCandidates`)}),(0,Q.jsx)(`p`,{children:l(p===`home`?`link.setup.emptyHome`:`link.setup.emptyLocal`)}),(0,Q.jsx)(`pre`,{children:(0,Q.jsx)(`code`,{children:`Host devbox
56
56
  HostName devbox.example.com
57
57
  User you
58
- IdentityFile ~/.ssh/id_ed25519`})})]})),(0,Q.jsx)(`a`,{href:`https://opencodex.me/guides/remote-link/`,target:`_blank`,rel:`noopener noreferrer`,children:l(`link.setup.guide`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>void Ee(),disabled:z!==null,children:l(C===`failed`?`link.retry`:`link.rescan`)})]}),(0,Q.jsxs)(`div`,{className:`remote-link-form`,children:[(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`remote-link-alias`,children:l(`link.alias`)}),(0,Q.jsx)(`input`,{id:`remote-link-alias`,"aria-describedby":`remote-link-alias-help`,className:`input`,spellCheck:!1,value:D,onChange:e=>k(e.target.value),placeholder:l(`link.aliasPlaceholder`),autoComplete:`off`}),(0,Q.jsx)(`p`,{id:`remote-link-alias-help`,className:`remote-link-info`,children:l(`link.aliasRequired`)}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>void Oe(),disabled:!D.trim()||z!==null,children:[(0,Q.jsx)(ut,{}),l(z===`probe`?`link.probing`:`link.probe`)]})]}),j&&(0,Q.jsxs)(`div`,{className:`remote-link-panel`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`span`,{className:`remote-link-info`,children:l(`link.hostFingerprint`)}),(0,Q.jsx)(`p`,{className:`remote-link-fingerprint`,children:(0,Q.jsx)(`code`,{children:j.fingerprint})}),(0,Q.jsx)(`span`,{className:`remote-link-info`,children:j.keyType})]}),(0,Q.jsxs)(`label`,{children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:F,onChange:e=>L(e.target.checked)}),` `,l(`link.confirmFingerprint`)]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>void ke(),disabled:!F||z!==null,children:l(z===`confirm`?`link.confirming`:`link.confirm`)})]}),N&&(0,Q.jsxs)(`div`,{className:`remote-link-panel`,children:[(0,Q.jsx)(`p`,{className:`remote-link-info`,children:l(`link.ocxVersion`,{version:N.ocxVersion})}),p===`child`&&be&&(0,Q.jsx)($,{tone:`warn`,children:l(`remoteLink.findHome.notice`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>void(p===`child`&&be?je():Ae()),disabled:z!==null||p===`child`&&!Se,children:l(p===`child`&&be?z===`join`?`remoteLink.joining`:`remoteLink.findHome.connect`:z===`apply`?`link.applying`:`link.apply`)})]}),x&&C!==`failed`&&V&&(0,Q.jsx)(MF,{error:V}),U&&V?.key!==`remoteLink.error.join_restart_failed`&&(0,Q.jsxs)(`div`,{children:[U.phase===`probe`&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`remote-link-info`,children:l(`link.probeHelp`)}),(0,Q.jsx)(`pre`,{children:(0,Q.jsx)(`code`,{children:`ssh -o BatchMode=yes <alias> true`})})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:Ne,disabled:z!==null,children:l(`link.retry`)})]}),(0,Q.jsx)(`div`,{className:`remote-link-sheet-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:ye,children:l(`link.cancel`)})})]})]}),(0,Q.jsx)(`dialog`,{ref:q,className:`remote-link-confirm-dialog`,"aria-labelledby":`remote-link-confirm-title`,onCancel:e=>{e.preventDefault(),Pe()},children:W&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`h3`,{id:`remote-link-confirm-title`,children:W.force?l(`remoteLink.forceRemove.title`,{alias:W.row.alias}):l(`link.disconnect`)}),(0,Q.jsx)(`p`,{children:W.force?(0,Q.jsx)(O,{k:`remoteLink.forceRemove.body`,cmd:`ocx disconnect`,vars:{alias:W.row.alias}}):l(`link.disconnectConfirm`,{alias:W.row.alias})}),G&&(0,Q.jsx)(`p`,{className:`remote-link-error`,role:`alert`,children:l(G)}),(0,Q.jsxs)(`div`,{className:`remote-link-sheet-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:Pe,children:l(`link.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-danger`,onClick:()=>void Ie(),disabled:z===`remove`,children:W.force?l(`remoteLink.forceRemove.confirm`):l(`link.disconnect`)})]})]})})]}):(0,Q.jsxs)(`div`,{className:`remote-link-page`,children:[(0,Q.jsx)(`div`,{className:`page-head`,children:(0,Q.jsx)(`h2`,{children:l(`link.title`)})}),(0,Q.jsx)($,{tone:`warn`,children:l(`link.sessionRequired`)}),fe&&(0,Q.jsx)(`div`,{className:`panel`,children:fe})]})}function PF(e){let t=document.documentElement,n=()=>t.style.setProperty(`--ocx-sticky-top-h`,String(Math.ceil(e.getBoundingClientRect().height)));n();let r=typeof ResizeObserver>`u`?null:new ResizeObserver(n);return r?.observe(e),()=>{r?.disconnect(),t.style.removeProperty(`--ocx-sticky-top-h`)}}var FF=6e4,IF=7,LF=8,RF=.8;function zF(e,t){try{return new Intl.DateTimeFormat(t,{hour:`2-digit`,minute:`2-digit`,hour12:!1}).format(e)}catch{return new Date(e).toTimeString().slice(0,5)}}function BF(e,t){return e.labelKey?t(e.labelKey):e.label??e.id}function VF(e,t){return e===`critical`?t(`quotaSummary.critical`):e===`warn`?t(`quotaSummary.warn`):``}function HF(e){try{return e.matches(`:focus-visible`)}catch{return!0}}function UF(e,t,n){(0,Z.useLayoutEffect)(()=>{if(!e)return;let r=()=>{let e=t.current,r=n.current;if(!e||!r)return;let i=e.getBoundingClientRect(),a=r.offsetWidth,o=document.documentElement.clientWidth||window.innerWidth,s=Math.max(LF,o-a-LF),c=Math.min(Math.max(i.left,LF),s);r.style.setProperty(`--qs-pop-top`,String(Math.round(i.bottom+IF))),r.style.setProperty(`--qs-pop-left`,String(Math.round(c))),r.style.setProperty(`--qs-pop-gap`,String(Math.round(i.bottom+IF)-i.bottom));let l=r.getBoundingClientRect();r.style.setProperty(`--qs-bridge-left`,String(Math.min(0,Math.max(0,i.left)-l.left))),r.style.setProperty(`--qs-bridge-right`,String(Math.min(0,l.right-Math.min(o,i.right))))};return r(),window.addEventListener(`scroll`,r,{capture:!0,passive:!0}),window.addEventListener(`resize`,r),()=>{window.removeEventListener(`scroll`,r,{capture:!0}),window.removeEventListener(`resize`,r)}},[e,t,n])}function WF({row:e,t,locale:n}){let[r,i]=(0,Z.useState)(!1),[a,o]=(0,Z.useState)(!1),[s,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(!1),d=(0,Z.useRef)(null),f=(0,Z.useRef)(null),p=(0,Z.useRef)(null),m=(0,Z.useRef)(``),h=(0,Z.useId)(),g=!l&&(r||a||s),_=(0,Z.useCallback)(()=>{i(!1),o(!1),c(!1)},[]);(0,Z.useEffect)(()=>{if(!g)return;let e=e=>{d.current&&!d.current.contains(e.target)&&c(!1)},t=e=>{if(e.key===`Escape`){let e=p.current?.contains(document.activeElement);_(),e&&(f.current?.focus(),u(!0))}};return document.addEventListener(`pointerdown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`pointerdown`,e),document.removeEventListener(`keydown`,t)}},[g,_]),UF(g,f,p);let v=e=>{e.pointerType!==`touch`&&i(!0)},y=e=>{e.pointerType!==`touch`&&i(!1),u(!1)},b=t=>{if(t.button!==0||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey)return;t.preventDefault();let n=m.current===`touch`;m.current=``,n&&!g?c(!0):(_(),n||u(!0),g_(e.provider))},{headline:x}=e,S=VF(e.severity,t);return(0,Q.jsxs)(`li`,{ref:d,className:`quota-summary-item quota-summary-item--${e.severity}`,onPointerEnter:v,onPointerLeave:y,onFocus:e=>{HF(e.target)&&(u(!1),o(!0))},onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||o(!1)},children:[(0,Q.jsxs)(`a`,{ref:f,href:`#${d_(e.provider)}`,className:`quota-summary-chip${g?` quota-summary-chip--open`:``}`,"aria-expanded":g,"aria-controls":g?h:void 0,"aria-describedby":g?`${h}-table`:void 0,onPointerDown:e=>{m.current=e.pointerType},onClick:b,children:[(0,Q.jsx)(`span`,{className:`quota-summary-name`,children:e.label}),(0,Q.jsx)(`span`,{className:`quota-summary-pct`,children:qe(x.percent)}),S&&(0,Q.jsx)(`span`,{className:`quota-summary-flag`,"aria-hidden":`true`,children:`!`}),S&&(0,Q.jsx)(`span`,{className:`sr-only`,children:S}),(0,Q.jsx)(`span`,{className:`sr-only`,children:t(`quotaSummary.openAccounts`)})]}),g&&(0,Q.jsxs)(`div`,{ref:p,id:h,className:`quota-summary-popover`,role:`group`,"aria-label":e.label,children:[(0,Q.jsxs)(`div`,{className:`quota-summary-popover-head`,children:[(0,Q.jsx)(`strong`,{children:e.label}),S&&(0,Q.jsx)(`span`,{className:`quota-summary-badge quota-summary-badge--${e.severity}`,children:S})]}),(0,Q.jsx)(`table`,{id:`${h}-table`,className:`quota-summary-table`,children:(0,Q.jsx)(`tbody`,{children:e.windows.map(e=>(0,Q.jsxs)(`tr`,{className:`quota-summary-row--${e.severity}`,children:[(0,Q.jsx)(`th`,{scope:`row`,children:BF(e,t)}),(0,Q.jsx)(`td`,{className:`quota-summary-row-pct`,children:qe(e.percent)}),(0,Q.jsx)(`td`,{className:`quota-summary-row-reset`,children:e.resetAt===void 0?`-`:fc(e.resetAt,t,n)})]},e.id))})}),(0,Q.jsxs)(`div`,{className:`quota-summary-popover-foot`,children:[e.updatedAt!==void 0&&(0,Q.jsx)(`span`,{children:t(e.observed?`quotaSummary.observedAt`:`quotaSummary.dataAt`,{time:zF(e.updatedAt,n)})}),(0,Q.jsx)(`a`,{href:`#${d_(e.provider)}`,className:`quota-summary-popover-link`,onPointerDown:e=>{m.current=e.pointerType},onClick:b,children:t(`quotaSummary.openAccounts`)})]})]})]})}var GF={overflow:!1,atStart:!0,atEnd:!0};function KF({rows:e,t,locale:n}){let r=(0,Z.useRef)(null),[i,a]=(0,Z.useState)(GF),o=(0,Z.useCallback)(()=>{let e=r.current;if(!e)return;let t=e.scrollWidth-e.clientWidth,n=t>1?{overflow:!0,atStart:e.scrollLeft<=1,atEnd:e.scrollLeft>=t-1}:GF;a(e=>e.overflow===n.overflow&&e.atStart===n.atStart&&e.atEnd===n.atEnd?e:n)},[]),s=e.map(e=>`${e.provider}:${e.label}:${qe(e.headline.percent)}:${e.severity}`).join(`|`);(0,Z.useEffect)(()=>{let e=r.current;if(!e)return;let t=requestAnimationFrame(o),n=typeof ResizeObserver>`u`?null:new ResizeObserver(()=>o());n?.observe(e);for(let t of Array.from(e.children))n?.observe(t);return()=>{cancelAnimationFrame(t),n?.disconnect()}},[o,s]);let c=e=>{let t=r.current;if(!t)return;let n=t.scrollWidth-t.clientWidth;if(e<0?t.scrollLeft<=1:t.scrollLeft>=n-1){o();return}let i=typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches;t.scrollBy({left:e*Math.max(t.clientWidth*RF,80),behavior:i?`auto`:`smooth`})};return(0,Q.jsxs)(`div`,{className:`quota-summary-scroller${i.overflow?` quota-summary-scroller--overflow`:``}`,children:[i.overflow&&(0,Q.jsx)(`button`,{type:`button`,className:`quota-summary-scroll quota-summary-scroll--prev`,"aria-label":t(`quotaSummary.scrollPrev`),title:t(`quotaSummary.scrollPrev`),"aria-disabled":i.atStart,onClick:()=>c(-1),children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`«`})}),(0,Q.jsx)(`ul`,{ref:r,className:`quota-summary-list`,onScroll:o,children:e.map(e=>(0,Q.jsx)(WF,{row:e,t,locale:n},e.provider))}),i.overflow&&(0,Q.jsx)(`button`,{type:`button`,className:`quota-summary-scroll quota-summary-scroll--next`,"aria-label":t(`quotaSummary.scrollNext`),title:t(`quotaSummary.scrollNext`),"aria-disabled":i.atEnd,onClick:()=>c(1),children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`»`})})]})}function qF({apiBase:e}){let{t,locale:n}=r(),i=(0,Z.useCallback)(async t=>{let n=await fetch(`${e}/api/provider-quotas`,{signal:t});if(!n.ok)throw Error(`quota summary load failed`);let r=await n.json();return{fetchedAt:Date.now(),reports:oe(r?.reports)}},[e]),a=uo(`ocx.quota-summary.provider-quotas.v1:${e}`,[e],i,{isEmpty:e=>Object.keys(e.reports).length===0,pollMs:FF,pauseWhenHidden:!0}),o=a.data;if(!o)return null;let s=et(o.reports,e=>Ce(e,t));if(s.length===0)return null;let c=!a.lastAttemptOk;return(0,Q.jsxs)(`section`,{className:`quota-summary-bar`,"aria-label":t(`quotaSummary.aria`),ref:PF,children:[(0,Q.jsx)(KF,{rows:s,t,locale:n}),(0,Q.jsx)(`span`,{className:`quota-summary-updated${c?` quota-summary-updated--stale`:``}`,title:c?t(`quotaSummary.refreshFailed`):void 0,children:t(`quotaSummary.updated`,{time:zF(o.fetchedAt,n)})}),(0,Q.jsx)(`span`,{className:`sr-only`,role:`status`,"aria-live":`polite`,children:c?t(`quotaSummary.refreshFailed`):``})]})}var JF=3e5,YF=6e5,XF=`https://github.com/lidge-jun/opencodex`;async function ZF(e,t){let n=await fetch(e,{signal:t});return n.ok?await n.json():null}function QF({apiBase:e,onOpenUpdate:t,onOpenTerminalCommand:r}){let i=n(),[a,o]=(0,Z.useState)(!1),[s,c]=(0,Z.useState)(null),l=Wt(`sidebar-star:${e}`,[e],t=>ZF(`${e}/api/github/star`,t),{pollMs:JF}),u=_o(e),d=Wt(`sidebar-update-badge:`+u,[u],e=>ZF(u,e),{pollMs:mo()?6e4:YF}),f=l.data?.state??null,p=s!==null&&s.basedOn===f?s.state:f??`not-starred`,m=l.data?.url??XF,h=p===`starred`,g=d.data,_=g?.updateAvailable===!0,v=g?.latestVersion??null,y=()=>window.open(m,`_blank`,`noopener,noreferrer`),b=async()=>{if(!(h||a)){if(p===`unauthenticated`)y();else{o(!0);try{let t=await fetch(`${e}/api/github/star`,{method:`POST`}),n=t.ok?await t.json():null;if(n?.ok===!0){c({state:`starred`,basedOn:f});return}n?.state&&c({state:n.state,basedOn:f}),y()}catch{y()}finally{o(!1),l.refresh()}}}},x=i(h?`sidebar.starred`:p===`unauthenticated`?`sidebar.starUnauthenticated`:`sidebar.star`),S=_&&v?i(`sidebar.updateAvailable`,{version:v}):mo()?i(`sidebar.desktopUpdate`):i(`sidebar.checkUpdate`);return(0,Q.jsxs)(`div`,{className:`sidebar-github-row`,children:[(0,Q.jsxs)(`a`,{className:`sidebar-link sidebar-github-link`,href:m,target:`_blank`,rel:`noreferrer`,children:[(0,Q.jsx)(Pe,{}),` `,i(`common.github`)]}),(0,Q.jsxs)(`div`,{className:`sidebar-github-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-orb${h?` sidebar-orb--starred`:``}`,onClick:()=>{b()},disabled:a||h,"aria-label":x,"aria-pressed":h,title:x,children:(0,Q.jsx)(re,{"aria-hidden":`true`,...h?{fill:`currentColor`}:{}})}),(0,Q.jsxs)(`button`,{type:`button`,className:`sidebar-orb${_?` sidebar-orb--update`:``}`,onClick:t,"aria-label":S,title:S,children:[(0,Q.jsx)(je,{"aria-hidden":`true`}),_&&(0,Q.jsx)(`span`,{className:`sidebar-orb-dot`,"aria-hidden":`true`})]}),mo()&&(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:r,"aria-label":i(`sidebar.terminalCommand`),title:i(`sidebar.terminalCommand`),children:(0,Q.jsx)(me,{"aria-hidden":`true`})})]})]})}var $F=`ocx-desktop-star-onboarding`,eI=`https://github.com/lidge-jun/opencodex`,tI=1200;function nI(){try{return window.localStorage.getItem($F)!==null}catch{return!0}}function rI(){try{window.localStorage.setItem($F,`seen`)}catch{}}function iI(e){window.location.assign(e)}function aI({apiBase:e,enabled:t}){let[n,r]=(0,Z.useState)(null),[i,a]=(0,Z.useState)(nI);(0,Z.useEffect)(()=>{if(!t||i||!mo())return;let n=new AbortController,o=window.setTimeout(()=>{fetch(`${e}/api/github/star`,{signal:n.signal}).then(async e=>e.ok?await e.json():{}).catch(()=>n.signal.aborted?null:{}).then(e=>{e&&(e.state===`starred`?(rI(),a(!0)):r(e))})},tI);return()=>{window.clearTimeout(o),n.abort()}},[e,t,i]);let o=(0,Z.useCallback)(()=>{rI(),a(!0)},[]);return i||!t||!n?null:(0,Q.jsx)(oI,{apiBase:e,status:n,onClose:o})}function oI({apiBase:e,status:t,onClose:r}){let i=n(),a=(0,Z.useId)(),o=(0,Z.useId)(),s=(0,Z.useRef)(null),[c,l]=(0,Z.useState)(`prompt`),u=t.url??eI,d=t.state===`not-starred`;(0,Z.useEffect)(()=>{let e=s.current;e&&!e.open&&e.showModal()},[]);let f=(0,Z.useCallback)(e=>{e.preventDefault(),c!==`starring`&&r()},[r,c]),p=()=>{iI(u),r()},m=async()=>{l(`starring`);try{let t=await fetch(`${e}/api/github/star`,{method:`POST`});if((t.ok?await t.json():null)?.ok===!0){Kt(`sidebar-star:${e}`,{state:`starred`,url:u}),l(`thanks`);return}}catch{}l(`failed`)},h=c===`thanks`,g=c===`failed`;return(0,Q.jsxs)(`dialog`,{ref:s,"aria-labelledby":a,"aria-describedby":o,className:`modal-overlay star-onboarding-overlay`,onCancel:f,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":i(`common.close`),tabIndex:-1,onClick:()=>{c!==`starring`&&r()}}),(0,Q.jsxs)(`div`,{className:`modal-card star-onboarding`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsx)(`span`,{className:`star-onboarding-mark${h?` star-onboarding-mark--done`:``}`,"aria-hidden":`true`,children:(0,Q.jsx)(re,{...h?{fill:`currentColor`}:{}})}),(0,Q.jsx)(`h3`,{id:a,className:`star-onboarding-title`,children:i(h?`onboarding.star.thanks`:`onboarding.star.title`)}),(0,Q.jsx)(`p`,{id:o,className:`star-onboarding-body`,children:i(h?`onboarding.star.thanksBody`:g?`onboarding.star.failed`:`onboarding.star.body`)}),h?(0,Q.jsx)(`div`,{className:`star-onboarding-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:r,autoFocus:!0,children:i(`onboarding.star.done`)})}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`star-onboarding-actions`,children:[d&&!g?(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,disabled:c===`starring`,onClick:()=>{m()},autoFocus:!0,children:[(0,Q.jsx)(re,{"aria-hidden":`true`}),i(c===`starring`?`onboarding.star.starring`:`onboarding.star.cta`)]}):(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:p,autoFocus:!0,children:[(0,Q.jsx)(Pe,{"aria-hidden":`true`}),i(g?`onboarding.star.openPage`:`onboarding.star.cta`)]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:c===`starring`,onClick:r,children:i(`onboarding.star.later`)})]}),(0,Q.jsxs)(`p`,{className:`star-onboarding-hint`,children:[i(d&&!g?`onboarding.star.ghHint`:`onboarding.star.browserHint`),d&&!g&&(0,Q.jsxs)(Q.Fragment,{children:[` `,(0,Q.jsx)(`button`,{type:`button`,className:`star-onboarding-link`,disabled:c===`starring`,onClick:p,children:i(`onboarding.star.openPage`)})]})]})]})]})]})}var sI=[{id:`dashboard`,tkey:`nav.dashboard`,Icon:Ke,pages:[`dashboard`]},{id:`connect`,tkey:`nav.connect`,Icon:ut,pages:[`integrations`],embedded:[`claude`]},{id:`codex-set`,tkey:`nav.codexSet`,Icon:$e,pages:[`codex-set`]},{id:`providers`,tkey:`nav.providers`,Icon:de,pages:[`providers`]},{id:`models`,tkey:`nav.models`,Icon:ze,pages:[`models`]},{id:`subagents`,tkey:`nav.subagents`,Icon:Qe,pages:[`subagents`,`advisor`]},{id:`usage-logs`,tkey:`nav.usageLogs`,Icon:P,pages:[`usage`,`logs`,`storage`]},{id:`remote`,tkey:`nav.remote`,Icon:ot,pages:[`remote`,`remote-workspace`]}];function cI(e){return sI.find(t=>t.pages.includes(e)||t.embedded?.includes(e))??null}function lI(e,t){return e.pages.filter(e=>e!==`remote-workspace`||t.remoteWorkspaceAvailable)}function uI({items:e,currentPage:t,onNavigate:n,ariaLabel:r,onFocusOrphaned:i}){let a=(0,Z.useRef)(null),o=(0,Z.useRef)(null),s=(0,Z.useRef)(i);(0,Z.useLayoutEffect)(()=>{s.current=i}),(0,Z.useLayoutEffect)(()=>{let e=a.current;return()=>{e&&e.contains(e.ownerDocument.activeElement)&&s.current?.()}},[]),(0,Z.useLayoutEffect)(()=>{let t=a.current,n=o.current;t&&n!==null&&(t.contains(t.ownerDocument.activeElement)||e.some(e=>e.page===n)||(t.querySelector(`[aria-current="page"]`)??t.querySelector(`button`))?.focus())},[e]);let c=()=>[...a.current?.querySelectorAll(`button`)??[]],l=e=>{let t=c(),n=t.indexOf(e.currentTarget),r=null;e.key===`ArrowRight`?r=(n+1)%t.length:e.key===`ArrowLeft`?r=(n-1+t.length)%t.length:e.key===`Home`?r=0:e.key===`End`&&(r=t.length-1),r!==null&&(e.preventDefault(),t[r]?.focus())};return(0,Q.jsx)(`nav`,{ref:a,className:`section-switcher`,"aria-label":r,onFocus:e=>{o.current=e.target.dataset.sectionPage??null},onBlur:e=>{if(a.current?.contains(e.relatedTarget))return;let t=e.target;window.setTimeout(()=>{t.isConnected&&(o.current=null)},0)},children:e.map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`section-switcher-btn`,"data-section-page":e.page,"aria-current":e.page===t?`page`:void 0,onClick:()=>{e.page!==t&&n(e.page)},onKeyDown:l,children:e.label},e.page))})}var dI=[`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 fI(){try{for(let e of dI)localStorage.removeItem(e)}catch{}}function pI(){let[e,t]=(0,Z.useState)(Wg);(0,Z.useEffect)(()=>{fI()},[]);let n=(0,Z.useCallback)(e=>{let n=t_(e);n.replaceTo&&Yt(n.replaceTo),t(n.page)},[]);return(0,Z.useEffect)(()=>{let e=()=>{n(qt(window.location.hash))};return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[n]),(0,Z.useEffect)(()=>{let n=t_(qt(window.location.hash));n.replaceTo&&Yt(n.replaceTo),n.page!==e&&t(n.page)},[e]),{page:e,setPageState:t,navigateToPage:(e,n)=>{Xt(n?`${e}/${n}`:e),t(e)}}}var mI=15e3,hI=3e3;function gI(e,t,n){return typeof e?.message==`string`&&e.message.trim()?e.message:typeof e?.error==`string`&&e.error.trim()?e.error:n(t)}async function _I(e,t,n){try{return(await t(`${e}/healthz`,{method:`GET`,cache:`no-store`,signal:AbortSignal.timeout(n)})).ok?`answering`:`undecided`}catch{return`gone`}}async function vI(e,t={}){let{fetchFn:n=fetch,timeoutMs:r=mI,formatFailure:i=e=>`Failed to stop proxy (HTTP ${e}).`,formatStillRunning:a=()=>`The proxy is still answering, so it did not stop.`,formatUnknown:o=()=>`The proxy did not confirm the stop. Check whether it is still running.`,mode:s=`standalone`,livenessTimeoutMs:c=hI}=t,l;try{l=await n(`${e}${s===`client`?`/api/machine/disconnect`:`/api/stop`}`,{method:`POST`,...s===`client`?{headers:{"Content-Type":`application/json`},body:`{}`}:{},signal:AbortSignal.timeout(r)})}catch{if(s===`client`)return{status:`unknown`,message:o()};let t=await _I(e,n,c);return t===`gone`?{status:`accepted`}:t===`answering`?{status:`unknown`,message:a()}:{status:`unknown`,message:o()}}let u=null,d=!0;try{u=await l.json()}catch{d=!1}return!l.ok||u?.success===!1?{status:`rejected`,message:gI(u,l.status,i)}:d?{status:`accepted`}:{status:`unknown`,message:o()}}var yI=`ocx-desktop-zoom`,bI=.5,xI=.1;function SI(e){return e===`macos`||e===`linux`}function CI(e){return Number.isFinite(e)?Math.round(Math.min(Math.max(e,bI),3)*100)/100:1}function wI(e,t){return t===`reset`?1:CI(e+(t===`in`?xI:-.1))}function TI(e){return Math.round(e*100)}function EI(e=typeof localStorage>`u`?void 0:localStorage){try{let t=e?.getItem(yI);return t==null?1:CI(Number(t))}catch{return 1}}function DI(e,t=typeof localStorage>`u`?void 0:localStorage){try{t?.setItem(yI,String(e))}catch{}}function OI(e,t){return(t===`macos`?e.metaKey:e.ctrlKey)?e.key===`-`||e.key===`_`?`out`:e.key===`=`||e.key===`+`?`in`:e.key===`0`?`reset`:null:null}function kI(e,t){if(!Number.isFinite(t)||t===0)return{accumulated:e,action:null};let n=(Math.sign(e)===Math.sign(t)?e:0)+t;return Math.abs(n)<50?{accumulated:n,action:null}:{accumulated:0,action:n<0?`in`:`out`}}async function AI(e){let t=window.__TAURI_INTERNALS__?.invoke??window.__TAURI__?.core?.invoke;if(!t)return!1;try{return await t(`plugin:webview|set_webview_zoom`,{value:e}),!0}catch{return!1}}var jI=`ocx-sidebar-collapsed`;function MI(e=typeof localStorage>`u`?void 0:localStorage){try{return e?.getItem(jI)===`1`}catch{return!1}}function NI(e){try{localStorage.setItem(jI,e?`1`:`0`)}catch{}}function PI(e){return e instanceof HTMLElement&&(e.isContentEditable||e.closest(`input, textarea, select, [contenteditable]`)!==null)}function FI({shortcut:e=!1}={}){let[t,n]=(0,Z.useState)(MI),r=(0,Z.useCallback)(()=>n(e=>!e),[]);return(0,Z.useEffect)(()=>{NI(t)},[t]),(0,Z.useEffect)(()=>{if(!e)return;let t=e=>{!(e.metaKey||e.ctrlKey)||e.altKey||e.shiftKey||(e.key===`b`||e.key===`B`)&&(PI(e.target)||(e.preventDefault(),r()))};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[r,e]),{collapsed:t,toggle:r}}function II({managed:e}){let[t,n]=(0,Z.useState)(EI),r=(0,Z.useCallback)(e=>n(t=>wI(t,e)),[]),i=(0,Z.useRef)(0);return(0,Z.useEffect)(()=>{e&&(AI(t),DI(t))},[e,t]),(0,Z.useEffect)(()=>{if(!e)return;let t=vo(),n=e=>{let n=OI(e,t);n&&(e.preventDefault(),e.stopImmediatePropagation(),r(n))},a=e=>{if(!e.ctrlKey)return;e.preventDefault(),e.stopImmediatePropagation();let t=kI(i.current,e.deltaY);i.current=t.accumulated,t.action&&r(t.action)},o=e=>{e.ctrlKey&&(e.preventDefault(),e.stopImmediatePropagation())};return window.addEventListener(`keydown`,n,{capture:!0}),window.addEventListener(`wheel`,a,{capture:!0,passive:!1}),window.addEventListener(`mousewheel`,o,{capture:!0,passive:!1}),()=>{window.removeEventListener(`keydown`,n,{capture:!0}),window.removeEventListener(`wheel`,a,{capture:!0}),window.removeEventListener(`mousewheel`,o,{capture:!0})}},[e,r]),{zoom:t,percent:TI(t),canZoomIn:t<3,canZoomOut:t>bI,step:r}}function LI({percent:e,canZoomIn:t,canZoomOut:r,onStep:i}){let a=n();return(0,Q.jsxs)(`div`,{className:`zoom-control`,role:`group`,"aria-label":a(`zoom.label`),title:a(`zoom.label`),children:[(0,Q.jsx)(`button`,{type:`button`,className:`zoom-control__btn`,disabled:!r,onClick:()=>i(`out`),"aria-label":a(`zoom.out`),title:a(`zoom.out`),children:(0,Q.jsx)(B,{"aria-hidden":!0})}),(0,Q.jsxs)(`button`,{type:`button`,className:`zoom-control__value`,onClick:()=>i(`reset`),"aria-label":a(`zoom.reset`),title:a(`zoom.reset`),children:[e,`%`]}),(0,Q.jsx)(`button`,{type:`button`,className:`zoom-control__btn`,disabled:!t,onClick:()=>i(`in`),"aria-label":a(`zoom.in`),title:a(`zoom.in`),children:(0,Q.jsx)(I,{"aria-hidden":!0})})]})}var RI=[{mode:`light`,tkey:`theme.light`,Icon:ie},{mode:`dark`,tkey:`theme.dark`,Icon:ve},{mode:`system`,tkey:`theme.system`,Icon:ot}];function zI({theme:e,onChange:t}){let r=n();return(0,Q.jsx)(`div`,{className:`theme-switch`,role:`group`,"aria-label":r(`theme.label`),children:RI.map(({mode:n,tkey:i,Icon:a})=>(0,Q.jsx)(`button`,{type:`button`,className:`theme-switch__btn`,"aria-pressed":e===n,"aria-label":r(i),title:r(i),onClick:()=>t(n),children:(0,Q.jsx)(a,{"aria-hidden":!0})},n))})}function BI(e){try{window.__TAURI__?.core?.invoke?.(e).catch(()=>{})}catch{}}var VI=`a, button, input, select, textarea, summary, [role='button'], [role='link'], [contenteditable]`;function HI(e){return e instanceof Element&&e.closest(VI)!==null}function UI(){return{onMouseDown:e=>{e.button!==0||HI(e.target)||BI(`plugin:window|start_dragging`)},onDoubleClick:e=>{HI(e.target)||BI(`plugin:window|toggle_maximize`)}}}function WI(e){let t=window.__TAURI__?.core,n=window.devicePixelRatio,r=Number.isFinite(n)&&n>0?Math.max(2,n):2,i=!0,a=0,o,s=()=>{let t=window.devicePixelRatio,n=Number.isFinite(t)&&t>0?r/t:1,i=Math.max(1,n);if(e.classList.toggle(`app--reduced-zoom`,i>1),e.style.setProperty(`--titlebar-h`,`${Math.ceil(40*i)}px`),n>=1){e.style.setProperty(`--tl-inset`,`${Math.ceil(80*i)}px`),e.style.setProperty(`--chrome-clear`,`${Math.ceil(124*i)}px`);return}let a=Math.ceil(80*n);e.style.setProperty(`--tl-inset`,`${a}px`),e.style.setProperty(`--chrome-clear`,`${a+44}px`)},c=()=>{if(!t?.invoke)return;let e=++a;t.invoke(`plugin:window|scale_factor`).then(t=>{i&&e===a&&typeof t==`number`&&Number.isFinite(t)&&t>0&&(r=t,s())}).catch(()=>{})},l=()=>{s(),clearTimeout(o),o=setTimeout(c,80)};return s(),c(),window.addEventListener(`resize`,l),window.addEventListener(`focus`,c),()=>{i=!1,clearTimeout(o),window.removeEventListener(`resize`,l),window.removeEventListener(`focus`,c)}}function GI({collapsed:e,onToggle:t}){let r=n()(e?`nav.expandSidebar`:`nav.collapseSidebar`);return(0,Q.jsx)(`div`,{className:`sidebar-top`,...UI(),children:(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-collapse`,onClick:t,"aria-expanded":!e,"aria-controls":`app-sidebar`,"aria-label":r,title:r,children:(0,Q.jsx)(ee,{})})})}function KI({children:e}){return(0,Q.jsx)(`div`,{className:`main-top`,...UI(),children:e})}var qI={dashboard:`nav.dashboard`,startup:`nav.startup`,providers:`nav.providers`,models:`nav.models`,subagents:`nav.subagents`,advisor:`nav.advisor`,logs:`nav.logs`,usage:`nav.usage`,storage:`nav.storage`,remote:`nav.remote`,"remote-workspace":`nav.remoteWorkspace`,"codex-set":`nav.codexSet`,integrations:`nav.connect`,claude:`nav.claude`},JI=``,YI=f(JI);p(YI),T();var XI=`ocx-theme`;function ZI({available:e,apiBase:t,hubOrigin:r,onOpenRemoteLink:i}){let a=n();return e?(0,Q.jsx)(yF,{apiBase:t,hubOrigin:r}):(0,Q.jsxs)(`section`,{className:`panel`,children:[(0,Q.jsx)(`h2`,{children:a(`nav.remoteWorkspace`)}),(0,Q.jsxs)($,{tone:`warn`,children:[a(`link.workspaceUnavailable`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:i,children:a(`nav.remote`)})]})]})}function QI(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 $I(){let e=localStorage.getItem(XI);return e===`light`||e===`dark`?e:`system`}function eL(){let e=document.querySelector(`.sidebar .nav-item.active`),t=e?.getBoundingClientRect(),n=!!t&&t.width>0&&t.height>0&&t.right>0&&t.left<window.innerWidth&&t.bottom>0&&t.top<window.innerHeight;if(e&&n){e.focus({preventScroll:!0});return}let r=document.querySelector(`main.main`);r&&(r.tabIndex=-1,r.focus({preventScroll:!0}))}function tL(){let{page:t,navigateToPage:i}=pI(),[a,o]=(0,Z.useState)(wC);(0,Z.useEffect)(()=>{let e=()=>o(wC());return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]);let[s,c]=(0,Z.useState)($I),{locale:l,setLocale:f}=r(),y=n(),[b,x]=(0,Z.useState)(YI),[C,w]=(0,Z.useState)(()=>!u()),[T,O]=(0,Z.useState)(!1),[k,A]=(0,Z.useState)(()=>m(`shared`)),[M,P]=(0,Z.useState)(0),[F,I]=(0,Z.useState)(!1),[L,R]=(0,Z.useState)(!1),[z,B]=(0,Z.useState)(!1),[V,H]=(0,Z.useState)(null),[U,ee]=(0,Z.useState)(0),W=(0,Z.useCallback)((e,t)=>{H({tone:t,text:e}),ee(e=>e+1)},[]);(0,Z.useEffect)(()=>{let e=e=>{e.detail?.plane===`shared`&&!m(`shared`)&&A(!1)},t=e=>{e.detail?.plane===`shared`&&m(`shared`)&&A(!0)};window.addEventListener(d,e),window.addEventListener(v,t);let n=e=>{e.detail?.plane===`shared`&&P(e=>e+1)};return window.addEventListener(E,n),()=>{window.removeEventListener(d,e),window.removeEventListener(v,t),window.removeEventListener(E,n)}},[]),(0,Z.useEffect)(()=>{let e=new AbortController;return g(JI,e.signal).then(async t=>{p(t),x(t),t.connected&&!m(`shared`)&&await D(`shared`,e.signal),!e.signal.aborted&&(A(m(`shared`)),O(!1),w(!0))}).catch(()=>{e.signal.aborted||(O(!0),w(!0))}),()=>e.abort()},[]);let te=_(`machine`,b),G=_(`shared`,b);(0,Z.useEffect)(()=>{if(!k)return;let e=new AbortController;return fetch(`${G}/api/remote-workspace`,{signal:e.signal,cache:`no-store`}).then(e=>e.ok?e.json():Promise.reject(Error(`unavailable`))).then(t=>{e.signal.aborted||R(t.available===!0)}).catch(()=>{e.signal.aborted||R(!1)}),()=>e.abort()},[t,k,G]);let ne=k&&L,K=cI(t),re=K?lI(K,{remoteWorkspaceAvailable:ne}):[],q=t===`claude`?`integrations`:t,J=t===`remote`&&N()===`hub`,Y=J&&F,[ie,X]=(0,Z.useState)(!1),oe=mo(),{collapsed:se,toggle:ce}=FI({shortcut:oe}),le=oe&&vo()===`macos`,ue=oe&&SI(vo()),de=II({managed:ue}),fe=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{if(le&&fe.current)return WI(fe.current)},[le]);let pe=(0,Z.useRef)(null),me=(0,Z.useRef)(null),he=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>{let e=()=>X(!1);return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]),(0,Z.useEffect)(()=>{if(!mo())return;let e=e=>{let t=e.target;if(!(t instanceof Element))return;let n=t.closest(`a[href]`);if(!(n instanceof HTMLAnchorElement))return;let r=n.href;Co(r)&&(e.preventDefault(),window.location.assign(r))};return document.addEventListener(`click`,e,!0),()=>document.removeEventListener(`click`,e,!0)},[]),(0,Z.useEffect)(()=>{let e=document.documentElement;s===`system`?(e.removeAttribute(`data-theme`),localStorage.removeItem(XI)):(e.setAttribute(`data-theme`,s),localStorage.setItem(XI,s))},[s]),(0,Z.useEffect)(()=>{if(V?.tone!==`ok`)return;let e=window.setTimeout(()=>H(null),4500);return()=>window.clearTimeout(e)},[V,U]);let _e=Wt(`app-healthz:${te}`,[te,C],async e=>{let t=await fetch(`${te}/healthz`,{signal:e});return t.ok?QI(await t.json()):null},{pollMs:3e4,enabled:C}),ve=(0,Q.jsx)(zI,{theme:s,onChange:c}),ye=_e.data??`2.95.1`,[be,Se]=(0,Z.useState)(!1);(0,Z.useEffect)(()=>{if(!ie)return;let e=e=>{e.key===`Escape`&&X(!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}},[ie]),(0,Z.useEffect)(()=>{if(ie){he.current=!0;let e=setTimeout(()=>me.current?.focus(),200);return()=>clearTimeout(e)}he.current&&(he.current=!1,pe.current?.focus())},[ie]),(0,Z.useEffect)(()=>{let e=window.matchMedia(`(min-width: 761px)`),t=()=>{e.matches&&X(!1)};return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]);let[Ce,we]=(0,Z.useState)(0),{restarting:Te,restart:Ee}=Mv(G,{onSettled:()=>we(e=>e+1),report:W}),De=async()=>{if(!await ha({message:y(b.connected?`connection.disconnectConfirm`:`dash.stopConfirm`),confirmLabel:y(b.connected?`connection.disconnect`:`dash.stop`),tone:`danger`}))return;Se(!0);let e=await vI(te,{formatFailure:e=>y(`dash.stopFailed`,{status:String(e)}),formatStillRunning:()=>y(`dash.stopStillRunning`),formatUnknown:()=>y(`dash.stopUnknown`),mode:b.connected?`client`:`standalone`});e.status!==`accepted`&&(Se(!1),W(e.message,e.status===`rejected`?`err`:`warn`))},Oe=async()=>{if(z)return;B(!0);let e=await S(`shared`);B(!1),e?A(!1):W(y(h(`shared`)?`connection.forgetDeviceFailed`:`connection.sessionLogoutFailed`),`err`)},ke=h(`shared`),Ae=y(ke?`connection.forgetDevice`:`connection.sessionLogout`),je=(0,Q.jsxs)(`button`,{type:`button`,className:`brand brand-home`,onClick:()=>{i(`dashboard`),X(!1)},"aria-label":y(`nav.goHome`),title:y(`nav.goHome`),...t===`dashboard`?{"aria-current":`page`}:{},children:[(0,Q.jsx)(`span`,{className:`brand-logo`,role:`img`,"aria-label":y(`app.logoAria`)}),(0,Q.jsx)(`span`,{className:`name`,children:`opencodex`}),(0,Q.jsxs)(`span`,{className:`ver`,title:ye,children:[`v`,ye]})]}),Me=C&&t!==`startup`&&(!b.connected||k)&&(0,Q.jsx)(db,{pageName:y(`quotaSummary.aria`),title:y(`errorBoundary.title`),message:y(`errorBoundary.message`),detailsLabel:y(`errorBoundary.details`),reloadLabel:y(`errorBoundary.reload`),children:(0,Q.jsx)(qF,{apiBase:G})},G);return(0,Q.jsxs)(`div`,{ref:fe,className:`app${oe?` app--desktop`:``}${le?` app--macos`:``}${se?` app--nav-collapsed`:``}`,children:[(0,Q.jsx)(aI,{apiBase:G,enabled:C&&!b.connected}),V&&(0,Q.jsx)(un,{tone:V.tone,onDismiss:()=>H(null),dismissLabel:y(`common.close`),children:V.text}),(0,Q.jsxs)(`header`,{className:`mobile-topbar`,inert:ie,...oe?UI():{},children:[(0,Q.jsx)(`button`,{ref:pe,type:`button`,className:`menu-toggle`,onClick:()=>X(e=>!e),"aria-expanded":ie,"aria-controls":`app-sidebar`,"aria-label":y(ie?`nav.closeMenu`:`nav.openMenu`),title:y(ie?`nav.closeMenu`:`nav.openMenu`),children:(0,Q.jsx)(ge,{})}),je,(0,Q.jsxs)(`div`,{className:`mobile-topbar-actions`,children:[(b.connected||ke)&&k&&(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:()=>{Oe()},disabled:z,"aria-label":z?y(`connection.sessionLoggingOut`):Ae,title:Ae,children:(0,Q.jsx)(xe,{})}),(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-orb sidebar-orb--danger`,onClick:De,disabled:be,"aria-label":y(b.connected?`connection.disconnect`:`dash.stop`),title:y(b.connected?`connection.disconnect`:`dash.stop`),children:(0,Q.jsx)(Ve,{})}),(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:()=>{Ee()},disabled:Te,"aria-label":y(`dash.codexRestart`),title:y(`dash.codexRestart`),children:(0,Q.jsx)(ae,{})})]})]}),ie&&(0,Q.jsx)(`div`,{className:`drawer-scrim`,onClick:()=>X(!1),"aria-hidden":`true`}),(0,Q.jsx)(GI,{collapsed:se,onToggle:ce}),(0,Q.jsxs)(`aside`,{id:`app-sidebar`,className:`sidebar${ie?` open`:``}`,ref:me,tabIndex:-1,children:[(0,Q.jsxs)(`div`,{className:`drawer-head`,children:[je,(0,Q.jsx)(`button`,{type:`button`,className:`menu-toggle drawer-close`,onClick:()=>X(!1),"aria-label":y(`nav.closeMenu`),title:y(`nav.closeMenu`),children:(0,Q.jsx)(xe,{})})]}),(0,Q.jsx)(`nav`,{children:sI.map(e=>{let{id:t,tkey:n,Icon:r}=e,a=K?.id===t;return(0,Q.jsx)(`div`,{className:`nav-entry`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`nav-item${a?` active`:``}`,"data-page":e.pages[0],"data-group":t,onClick:()=>{i(e.pages[0]),X(!1)},"aria-current":a?`page`:void 0,children:[(0,Q.jsx)(r,{}),` `,y(n)]})},t)})}),(0,Q.jsxs)(`div`,{className:`sidebar-foot`,children:[(0,Q.jsxs)(`div`,{className:`lang-toggle`,children:[(0,Q.jsx)(Xe,{"aria-hidden":!0}),(0,Q.jsx)(dn,{value:l,options:j.map(t=>({value:t.code,label:e(t.code)})),onChange:e=>f(e),label:y(`lang.label`),placement:`right`,portal:!1,style:{flex:1,minWidth:0,width:`100%`}})]}),ue?(0,Q.jsxs)(`div`,{className:`sidebar-display-row`,children:[ve,(0,Q.jsx)(LI,{percent:de.percent,canZoomIn:de.canZoomIn,canZoomOut:de.canZoomOut,onStep:de.step})]}):(0,Q.jsxs)(`div`,{className:`sidebar-action-row sidebar-action-row--theme`,children:[(0,Q.jsx)(`span`,{className:`sidebar-action-label`,children:y(`theme.label`)}),ve]}),(0,Q.jsxs)(`div`,{className:`sidebar-action-row`,children:[(0,Q.jsx)(`span`,{className:`sidebar-action-label`,children:y(`dash.actions`)}),(0,Q.jsxs)(`div`,{className:`sidebar-action-orbs`,children:[(b.connected||ke)&&k&&(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:()=>{Oe()},disabled:z,"aria-label":z?y(`connection.sessionLoggingOut`):Ae,title:Ae,children:(0,Q.jsx)(xe,{})}),(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-orb sidebar-orb--danger`,onClick:De,disabled:be,"aria-label":y(be?`dash.stopping`:b.connected?`connection.disconnect`:`dash.stop`),title:y(be?`dash.stopping`:b.connected?`connection.disconnect`:`dash.stop`),children:(0,Q.jsx)(Ve,{})}),(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:()=>{Ee()},disabled:Te,"aria-label":y(Te?`dash.codexRestarting`:`dash.codexRestart`),title:y(Te?`dash.codexRestarting`:`dash.codexRestart`),children:(0,Q.jsx)(ae,{})})]})]}),(0,Q.jsx)(QF,{apiBase:G,onOpenUpdate:()=>{X(!1),!bo()&&i(`dashboard`,`update`)},onOpenTerminalCommand:()=>{X(!1),So()}})]})]}),(0,Q.jsxs)(`main`,{className:`main`,inert:ie,children:[oe?(0,Q.jsx)(KI,{children:Me}):Me,(0,Q.jsxs)(`div`,{className:`main-inner${t===`models`&&a===`combos`?` main-inner--combos`:``}`,children:[C&&re.length>1&&(0,Q.jsx)(uI,{items:re.map(e=>({page:e,label:y(qI[e])})),currentPage:t,onNavigate:i,ariaLabel:y(`nav.sectionNavigation`),onFocusOrphaned:eL}),C&&b.link&&(0,Q.jsx)($,{tone:`warn`,children:b.link.home?y(`connection.linkManaged`,{home:b.link.home,linkId:b.link.linkId}):y(`connection.linkManagedUnnamed`,{linkId:b.link.linkId})}),(0,Q.jsx)(db,{pageName:y(qI[q]),title:y(`errorBoundary.title`),message:y(`errorBoundary.message`),detailsLabel:y(`errorBoundary.details`),reloadLabel:y(`errorBoundary.reload`),children:C?(0,Q.jsxs)(Q.Fragment,{children:[T&&(0,Q.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:y(`connection.machineUnavailable`)}),(b.connected&&!k||Y)&&(0,Q.jsx)(Zk,{target:b.shared,focusOnMount:Y,onConnected:async e=>{Y&&await Fk(G,void 0,e),e.throwIfAborted(),I(!1),A(m(`shared`)),P(e=>e+1)}},`${b.shared.serverOrigin}:${b.shared.bootstrapPath}`),t===`dashboard`&&(0,Q.jsx)(Fs,{apiBase:G,readOnly:b.link!==void 0,connected:b.connected,authenticationPending:b.connected&&!k,refreshEpoch:M}),t===`startup`&&(0,Q.jsx)(GP,{apiBase:G,machineApiBase:te,connected:b.connected}),t===`providers`&&(0,Q.jsx)(b_,{apiBase:G}),t===`models`&&(0,Q.jsx)(XC,{apiBase:G,restartEpoch:Ce,connected:b.connected,catalogSyncedAt:b.catalogSyncedAt,reportRestart:W},G),t===`subagents`&&(0,Q.jsx)(xw,{apiBase:G},G),t===`advisor`&&(0,Q.jsx)(rw,{apiBase:G},G),t===`logs`&&(0,Q.jsx)(FE,{apiBase:G}),t===`usage`&&(0,Q.jsx)(BD,{apiBase:G,connected:b.connected,apiKeyId:b.apiKeyId}),t===`storage`&&(0,Q.jsx)(hO,{apiBase:G}),t===`remote`&&!Y&&(0,Q.jsx)(NF,{apiBase:G,sessionReady:k,pairingRecoveryAvailable:J,onRequestPairing:()=>I(!0),workspaceAvailable:ne,onOpenWorkspace:()=>i(`remote-workspace`)},`${G}:${M}`),t===`remote-workspace`&&(0,Q.jsx)(ZI,{available:ne,apiBase:G,hubOrigin:b.shared.serverOrigin,onOpenRemoteLink:()=>i(`remote`)}),t===`codex-set`&&(0,Q.jsx)(oA,{apiBase:G,machineApiBase:te,connected:b.connected}),q===`integrations`&&(0,Q.jsx)(MP,{apiBase:G,machineApiBase:te,connected:b.connected})]}):(0,Q.jsx)(`div`,{className:`alert`,children:y(`connection.discovering`)})},q)]})]})]})}export{ZI as RemoteWorkspaceRoute,tL as default};
58
+ IdentityFile ~/.ssh/id_ed25519`})})]})),(0,Q.jsx)(`a`,{href:`https://opencodex.me/guides/remote-link/`,target:`_blank`,rel:`noopener noreferrer`,children:l(`link.setup.guide`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>void Ee(),disabled:z!==null,children:l(C===`failed`?`link.retry`:`link.rescan`)})]}),(0,Q.jsxs)(`div`,{className:`remote-link-form`,children:[(0,Q.jsx)(`label`,{className:`field-label`,htmlFor:`remote-link-alias`,children:l(`link.alias`)}),(0,Q.jsx)(`input`,{id:`remote-link-alias`,"aria-describedby":`remote-link-alias-help`,className:`input`,spellCheck:!1,value:D,onChange:e=>k(e.target.value),placeholder:l(`link.aliasPlaceholder`),autoComplete:`off`}),(0,Q.jsx)(`p`,{id:`remote-link-alias-help`,className:`remote-link-info`,children:l(`link.aliasRequired`)}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>void Oe(),disabled:!D.trim()||z!==null,children:[(0,Q.jsx)(ut,{}),l(z===`probe`?`link.probing`:`link.probe`)]})]}),j&&(0,Q.jsxs)(`div`,{className:`remote-link-panel`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`span`,{className:`remote-link-info`,children:l(`link.hostFingerprint`)}),(0,Q.jsx)(`p`,{className:`remote-link-fingerprint`,children:(0,Q.jsx)(`code`,{children:j.fingerprint})}),(0,Q.jsx)(`span`,{className:`remote-link-info`,children:j.keyType})]}),(0,Q.jsxs)(`label`,{children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:F,onChange:e=>L(e.target.checked)}),` `,l(`link.confirmFingerprint`)]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>void ke(),disabled:!F||z!==null,children:l(z===`confirm`?`link.confirming`:`link.confirm`)})]}),N&&(0,Q.jsxs)(`div`,{className:`remote-link-panel`,children:[(0,Q.jsx)(`p`,{className:`remote-link-info`,children:l(`link.ocxVersion`,{version:N.ocxVersion})}),p===`child`&&be&&(0,Q.jsx)($,{tone:`warn`,children:l(`remoteLink.findHome.notice`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>void(p===`child`&&be?je():Ae()),disabled:z!==null||p===`child`&&!Se,children:l(p===`child`&&be?z===`join`?`remoteLink.joining`:`remoteLink.findHome.connect`:z===`apply`?`link.applying`:`link.apply`)})]}),x&&C!==`failed`&&V&&(0,Q.jsx)(MF,{error:V}),U&&V?.key!==`remoteLink.error.join_restart_failed`&&(0,Q.jsxs)(`div`,{children:[U.phase===`probe`&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`remote-link-info`,children:l(`link.probeHelp`)}),(0,Q.jsx)(`pre`,{children:(0,Q.jsx)(`code`,{children:`ssh -o BatchMode=yes <alias> true`})})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:Ne,disabled:z!==null,children:l(`link.retry`)})]}),(0,Q.jsx)(`div`,{className:`remote-link-sheet-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:ye,children:l(`link.cancel`)})})]})]}),(0,Q.jsx)(`dialog`,{ref:q,className:`remote-link-confirm-dialog`,"aria-labelledby":`remote-link-confirm-title`,onCancel:e=>{e.preventDefault(),Pe()},children:W&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`h3`,{id:`remote-link-confirm-title`,children:W.force?l(`remoteLink.forceRemove.title`,{alias:W.row.alias}):l(`link.disconnect`)}),(0,Q.jsx)(`p`,{children:W.force?(0,Q.jsx)(O,{k:`remoteLink.forceRemove.body`,cmd:`ocx disconnect`,vars:{alias:W.row.alias}}):l(`link.disconnectConfirm`,{alias:W.row.alias})}),G&&(0,Q.jsx)(`p`,{className:`remote-link-error`,role:`alert`,children:l(G)}),(0,Q.jsxs)(`div`,{className:`remote-link-sheet-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:Pe,children:l(`link.cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-danger`,onClick:()=>void Ie(),disabled:z===`remove`,children:W.force?l(`remoteLink.forceRemove.confirm`):l(`link.disconnect`)})]})]})})]}):(0,Q.jsxs)(`div`,{className:`remote-link-page`,children:[(0,Q.jsx)(`div`,{className:`page-head`,children:(0,Q.jsx)(`h2`,{children:l(`link.title`)})}),(0,Q.jsx)($,{tone:`warn`,children:l(`link.sessionRequired`)}),fe&&(0,Q.jsx)(`div`,{className:`panel`,children:fe})]})}function PF(e){let t=document.documentElement,n=()=>t.style.setProperty(`--ocx-sticky-top-h`,String(Math.ceil(e.getBoundingClientRect().height)));n();let r=typeof ResizeObserver>`u`?null:new ResizeObserver(n);return r?.observe(e),()=>{r?.disconnect(),t.style.removeProperty(`--ocx-sticky-top-h`)}}var FF=6e4,IF=7,LF=8,RF=.8;function zF(e,t){try{return new Intl.DateTimeFormat(t,{hour:`2-digit`,minute:`2-digit`,hour12:!1}).format(e)}catch{return new Date(e).toTimeString().slice(0,5)}}function BF(e,t){return e.labelKey?t(e.labelKey):e.label??e.id}function VF(e,t){return e===`critical`?t(`quotaSummary.critical`):e===`warn`?t(`quotaSummary.warn`):``}function HF(e){try{return e.matches(`:focus-visible`)}catch{return!0}}function UF(e,t,n){(0,Z.useLayoutEffect)(()=>{if(!e)return;let r=()=>{let e=t.current,r=n.current;if(!e||!r)return;let i=e.getBoundingClientRect(),a=r.offsetWidth,o=document.documentElement.clientWidth||window.innerWidth,s=Math.max(LF,o-a-LF),c=Math.min(Math.max(i.left,LF),s);r.style.setProperty(`--qs-pop-top`,String(Math.round(i.bottom+IF))),r.style.setProperty(`--qs-pop-left`,String(Math.round(c))),r.style.setProperty(`--qs-pop-gap`,String(Math.round(i.bottom+IF)-i.bottom));let l=r.getBoundingClientRect();r.style.setProperty(`--qs-bridge-left`,String(Math.min(0,Math.max(0,i.left)-l.left))),r.style.setProperty(`--qs-bridge-right`,String(Math.min(0,l.right-Math.min(o,i.right))))};return r(),window.addEventListener(`scroll`,r,{capture:!0,passive:!0}),window.addEventListener(`resize`,r),()=>{window.removeEventListener(`scroll`,r,{capture:!0}),window.removeEventListener(`resize`,r)}},[e,t,n])}function WF({row:e,t,locale:n}){let[r,i]=(0,Z.useState)(!1),[a,o]=(0,Z.useState)(!1),[s,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(!1),d=(0,Z.useRef)(null),f=(0,Z.useRef)(null),p=(0,Z.useRef)(null),m=(0,Z.useRef)(``),h=(0,Z.useId)(),g=!l&&(r||a||s),_=(0,Z.useCallback)(()=>{i(!1),o(!1),c(!1)},[]);(0,Z.useEffect)(()=>{if(!g)return;let e=e=>{d.current&&!d.current.contains(e.target)&&c(!1)},t=e=>{if(e.key===`Escape`){let e=p.current?.contains(document.activeElement);_(),e&&(f.current?.focus(),u(!0))}};return document.addEventListener(`pointerdown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`pointerdown`,e),document.removeEventListener(`keydown`,t)}},[g,_]),UF(g,f,p);let v=e=>{e.pointerType!==`touch`&&i(!0)},y=e=>{e.pointerType!==`touch`&&i(!1),u(!1)},b=t=>{if(t.button!==0||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey)return;t.preventDefault();let n=m.current===`touch`;m.current=``,n&&!g?c(!0):(_(),n||u(!0),g_(e.provider))},{headline:x}=e,S=VF(e.severity,t);return(0,Q.jsxs)(`li`,{ref:d,className:`quota-summary-item quota-summary-item--${e.severity}`,onPointerEnter:v,onPointerLeave:y,onFocus:e=>{HF(e.target)&&(u(!1),o(!0))},onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||o(!1)},children:[(0,Q.jsxs)(`a`,{ref:f,href:`#${d_(e.provider)}`,className:`quota-summary-chip${g?` quota-summary-chip--open`:``}`,"aria-expanded":g,"aria-controls":g?h:void 0,"aria-describedby":g?`${h}-table`:void 0,onPointerDown:e=>{m.current=e.pointerType},onClick:b,children:[(0,Q.jsx)(`span`,{className:`quota-summary-name`,children:e.label}),(0,Q.jsx)(`span`,{className:`quota-summary-pct`,children:qe(x.percent)}),S&&(0,Q.jsx)(`span`,{className:`quota-summary-flag`,"aria-hidden":`true`,children:`!`}),S&&(0,Q.jsx)(`span`,{className:`sr-only`,children:S}),(0,Q.jsx)(`span`,{className:`sr-only`,children:t(`quotaSummary.openAccounts`)})]}),g&&(0,Q.jsxs)(`div`,{ref:p,id:h,className:`quota-summary-popover`,role:`group`,"aria-label":e.label,children:[(0,Q.jsxs)(`div`,{className:`quota-summary-popover-head`,children:[(0,Q.jsx)(`strong`,{children:e.label}),S&&(0,Q.jsx)(`span`,{className:`quota-summary-badge quota-summary-badge--${e.severity}`,children:S})]}),(0,Q.jsx)(`table`,{id:`${h}-table`,className:`quota-summary-table`,children:(0,Q.jsx)(`tbody`,{children:e.windows.map(e=>(0,Q.jsxs)(`tr`,{className:`quota-summary-row--${e.severity}`,children:[(0,Q.jsx)(`th`,{scope:`row`,children:BF(e,t)}),(0,Q.jsx)(`td`,{className:`quota-summary-row-pct`,children:qe(e.percent)}),(0,Q.jsx)(`td`,{className:`quota-summary-row-reset`,children:e.resetAt===void 0?`-`:fc(e.resetAt,t,n)})]},e.id))})}),(0,Q.jsxs)(`div`,{className:`quota-summary-popover-foot`,children:[e.updatedAt!==void 0&&(0,Q.jsx)(`span`,{children:t(e.observed?`quotaSummary.observedAt`:`quotaSummary.dataAt`,{time:zF(e.updatedAt,n)})}),(0,Q.jsx)(`a`,{href:`#${d_(e.provider)}`,className:`quota-summary-popover-link`,onPointerDown:e=>{m.current=e.pointerType},onClick:b,children:t(`quotaSummary.openAccounts`)})]})]})]})}var GF={overflow:!1,atStart:!0,atEnd:!0};function KF({rows:e,t,locale:n}){let r=(0,Z.useRef)(null),[i,a]=(0,Z.useState)(GF),o=(0,Z.useCallback)(()=>{let e=r.current;if(!e)return;let t=e.scrollWidth-e.clientWidth,n=t>1?{overflow:!0,atStart:e.scrollLeft<=1,atEnd:e.scrollLeft>=t-1}:GF;a(e=>e.overflow===n.overflow&&e.atStart===n.atStart&&e.atEnd===n.atEnd?e:n)},[]),s=e.map(e=>`${e.provider}:${e.label}:${qe(e.headline.percent)}:${e.severity}`).join(`|`);(0,Z.useEffect)(()=>{let e=r.current;if(!e)return;let t=requestAnimationFrame(o),n=typeof ResizeObserver>`u`?null:new ResizeObserver(()=>o());n?.observe(e);for(let t of Array.from(e.children))n?.observe(t);return()=>{cancelAnimationFrame(t),n?.disconnect()}},[o,s]);let c=e=>{let t=r.current;if(!t)return;let n=t.scrollWidth-t.clientWidth;if(e<0?t.scrollLeft<=1:t.scrollLeft>=n-1){o();return}let i=typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches;t.scrollBy({left:e*Math.max(t.clientWidth*RF,80),behavior:i?`auto`:`smooth`})};return(0,Q.jsxs)(`div`,{className:`quota-summary-scroller${i.overflow?` quota-summary-scroller--overflow`:``}`,children:[i.overflow&&(0,Q.jsx)(`button`,{type:`button`,className:`quota-summary-scroll quota-summary-scroll--prev`,"aria-label":t(`quotaSummary.scrollPrev`),title:t(`quotaSummary.scrollPrev`),"aria-disabled":i.atStart,onClick:()=>c(-1),children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`«`})}),(0,Q.jsx)(`ul`,{ref:r,className:`quota-summary-list`,onScroll:o,children:e.map(e=>(0,Q.jsx)(WF,{row:e,t,locale:n},e.provider))}),i.overflow&&(0,Q.jsx)(`button`,{type:`button`,className:`quota-summary-scroll quota-summary-scroll--next`,"aria-label":t(`quotaSummary.scrollNext`),title:t(`quotaSummary.scrollNext`),"aria-disabled":i.atEnd,onClick:()=>c(1),children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`»`})})]})}function qF({apiBase:e}){let{t,locale:n}=r(),i=(0,Z.useCallback)(async t=>{let n=await fetch(`${e}/api/provider-quotas`,{signal:t});if(!n.ok)throw Error(`quota summary load failed`);let r=await n.json();return{fetchedAt:Date.now(),reports:oe(r?.reports)}},[e]),a=uo(`ocx.quota-summary.provider-quotas.v1:${e}`,[e],i,{isEmpty:e=>Object.keys(e.reports).length===0,pollMs:FF,pauseWhenHidden:!0}),o=a.data;if(!o)return null;let s=et(o.reports,e=>Ce(e,t));if(s.length===0)return null;let c=!a.lastAttemptOk;return(0,Q.jsxs)(`section`,{className:`quota-summary-bar`,"aria-label":t(`quotaSummary.aria`),ref:PF,children:[(0,Q.jsx)(KF,{rows:s,t,locale:n}),(0,Q.jsx)(`span`,{className:`quota-summary-updated${c?` quota-summary-updated--stale`:``}`,title:c?t(`quotaSummary.refreshFailed`):void 0,children:t(`quotaSummary.updated`,{time:zF(o.fetchedAt,n)})}),(0,Q.jsx)(`span`,{className:`sr-only`,role:`status`,"aria-live":`polite`,children:c?t(`quotaSummary.refreshFailed`):``})]})}var JF=3e5,YF=6e5,XF=`https://github.com/lidge-jun/opencodex`;async function ZF(e,t){let n=await fetch(e,{signal:t});return n.ok?await n.json():null}function QF({apiBase:e,onOpenUpdate:t,onOpenTerminalCommand:r}){let i=n(),[a,o]=(0,Z.useState)(!1),[s,c]=(0,Z.useState)(null),l=Wt(`sidebar-star:${e}`,[e],t=>ZF(`${e}/api/github/star`,t),{pollMs:JF}),u=_o(e),d=Wt(`sidebar-update-badge:`+u,[u],e=>ZF(u,e),{pollMs:mo()?6e4:YF}),f=l.data?.state??null,p=s!==null&&s.basedOn===f?s.state:f??`not-starred`,m=l.data?.url??XF,h=p===`starred`,g=d.data,_=g?.updateAvailable===!0,v=g?.latestVersion??null,y=()=>window.open(m,`_blank`,`noopener,noreferrer`),b=async()=>{if(!(h||a)){if(p===`unauthenticated`)y();else{o(!0);try{let t=await fetch(`${e}/api/github/star`,{method:`POST`}),n=t.ok?await t.json():null;if(n?.ok===!0){c({state:`starred`,basedOn:f});return}n?.state&&c({state:n.state,basedOn:f}),y()}catch{y()}finally{o(!1),l.refresh()}}}},x=i(h?`sidebar.starred`:p===`unauthenticated`?`sidebar.starUnauthenticated`:`sidebar.star`),S=_&&v?i(`sidebar.updateAvailable`,{version:v}):mo()?i(`sidebar.desktopUpdate`):i(`sidebar.checkUpdate`);return(0,Q.jsxs)(`div`,{className:`sidebar-github-row`,children:[(0,Q.jsxs)(`a`,{className:`sidebar-link sidebar-github-link`,href:m,target:`_blank`,rel:`noreferrer`,children:[(0,Q.jsx)(Pe,{}),` `,i(`common.github`)]}),(0,Q.jsxs)(`div`,{className:`sidebar-github-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-orb${h?` sidebar-orb--starred`:``}`,onClick:()=>{b()},disabled:a||h,"aria-label":x,"aria-pressed":h,title:x,children:(0,Q.jsx)(re,{"aria-hidden":`true`,...h?{fill:`currentColor`}:{}})}),(0,Q.jsxs)(`button`,{type:`button`,className:`sidebar-orb${_?` sidebar-orb--update`:``}`,onClick:t,"aria-label":S,title:S,children:[(0,Q.jsx)(je,{"aria-hidden":`true`}),_&&(0,Q.jsx)(`span`,{className:`sidebar-orb-dot`,"aria-hidden":`true`})]}),mo()&&(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:r,"aria-label":i(`sidebar.terminalCommand`),title:i(`sidebar.terminalCommand`),children:(0,Q.jsx)(me,{"aria-hidden":`true`})})]})]})}var $F=`ocx-desktop-star-onboarding`,eI=`https://github.com/lidge-jun/opencodex`,tI=1200;function nI(){try{return window.localStorage.getItem($F)!==null}catch{return!0}}function rI(){try{window.localStorage.setItem($F,`seen`)}catch{}}function iI(e){window.location.assign(e)}function aI({apiBase:e,enabled:t}){let[n,r]=(0,Z.useState)(null),[i,a]=(0,Z.useState)(nI);(0,Z.useEffect)(()=>{if(!t||i||!mo())return;let n=new AbortController,o=window.setTimeout(()=>{fetch(`${e}/api/github/star`,{signal:n.signal}).then(async e=>e.ok?await e.json():{}).catch(()=>n.signal.aborted?null:{}).then(e=>{e&&(e.state===`starred`?(rI(),a(!0)):r(e))})},tI);return()=>{window.clearTimeout(o),n.abort()}},[e,t,i]);let o=(0,Z.useCallback)(()=>{rI(),a(!0)},[]);return i||!t||!n?null:(0,Q.jsx)(oI,{apiBase:e,status:n,onClose:o})}function oI({apiBase:e,status:t,onClose:r}){let i=n(),a=(0,Z.useId)(),o=(0,Z.useId)(),s=(0,Z.useRef)(null),[c,l]=(0,Z.useState)(`prompt`),u=t.url??eI,d=t.state===`not-starred`;(0,Z.useEffect)(()=>{let e=s.current;e&&!e.open&&e.showModal()},[]);let f=(0,Z.useCallback)(e=>{e.preventDefault(),c!==`starring`&&r()},[r,c]),p=()=>{iI(u),r()},m=async()=>{l(`starring`);try{let t=await fetch(`${e}/api/github/star`,{method:`POST`});if((t.ok?await t.json():null)?.ok===!0){Kt(`sidebar-star:${e}`,{state:`starred`,url:u}),l(`thanks`);return}}catch{}l(`failed`)},h=c===`thanks`,g=c===`failed`;return(0,Q.jsxs)(`dialog`,{ref:s,"aria-labelledby":a,"aria-describedby":o,className:`modal-overlay star-onboarding-overlay`,onCancel:f,children:[(0,Q.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":i(`common.close`),tabIndex:-1,onClick:()=>{c!==`starring`&&r()}}),(0,Q.jsxs)(`div`,{className:`modal-card star-onboarding`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsx)(`span`,{className:`star-onboarding-mark${h?` star-onboarding-mark--done`:``}`,"aria-hidden":`true`,children:(0,Q.jsx)(re,{...h?{fill:`currentColor`}:{}})}),(0,Q.jsx)(`h3`,{id:a,className:`star-onboarding-title`,children:i(h?`onboarding.star.thanks`:`onboarding.star.title`)}),(0,Q.jsx)(`p`,{id:o,className:`star-onboarding-body`,children:i(h?`onboarding.star.thanksBody`:g?`onboarding.star.failed`:`onboarding.star.body`)}),h?(0,Q.jsx)(`div`,{className:`star-onboarding-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:r,autoFocus:!0,children:i(`onboarding.star.done`)})}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`star-onboarding-actions`,children:[d&&!g?(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,disabled:c===`starring`,onClick:()=>{m()},autoFocus:!0,children:[(0,Q.jsx)(re,{"aria-hidden":`true`}),i(c===`starring`?`onboarding.star.starring`:`onboarding.star.cta`)]}):(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:p,autoFocus:!0,children:[(0,Q.jsx)(Pe,{"aria-hidden":`true`}),i(g?`onboarding.star.openPage`:`onboarding.star.cta`)]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:c===`starring`,onClick:r,children:i(`onboarding.star.later`)})]}),(0,Q.jsxs)(`p`,{className:`star-onboarding-hint`,children:[i(d&&!g?`onboarding.star.ghHint`:`onboarding.star.browserHint`),d&&!g&&(0,Q.jsxs)(Q.Fragment,{children:[` `,(0,Q.jsx)(`button`,{type:`button`,className:`star-onboarding-link`,disabled:c===`starring`,onClick:p,children:i(`onboarding.star.openPage`)})]})]})]})]})]})}var sI=[{id:`dashboard`,tkey:`nav.dashboard`,Icon:Ke,pages:[`dashboard`]},{id:`connect`,tkey:`nav.connect`,Icon:ut,pages:[`integrations`],embedded:[`claude`]},{id:`codex-set`,tkey:`nav.codexSet`,Icon:$e,pages:[`codex-set`]},{id:`providers`,tkey:`nav.providers`,Icon:de,pages:[`providers`]},{id:`models`,tkey:`nav.models`,Icon:ze,pages:[`models`]},{id:`subagents`,tkey:`nav.subagents`,Icon:Qe,pages:[`subagents`,`advisor`]},{id:`usage-logs`,tkey:`nav.usageLogs`,Icon:P,pages:[`usage`,`logs`,`storage`]},{id:`remote`,tkey:`nav.remote`,Icon:ot,pages:[`remote`,`remote-workspace`]}];function cI(e){return sI.find(t=>t.pages.includes(e)||t.embedded?.includes(e))??null}function lI(e,t){return e.pages.filter(e=>e!==`remote-workspace`||t.remoteWorkspaceAvailable)}function uI({items:e,currentPage:t,onNavigate:n,ariaLabel:r,onFocusOrphaned:i}){let a=(0,Z.useRef)(null),o=(0,Z.useRef)(null),s=(0,Z.useRef)(i);(0,Z.useLayoutEffect)(()=>{s.current=i}),(0,Z.useLayoutEffect)(()=>{let e=a.current;return()=>{e&&e.contains(e.ownerDocument.activeElement)&&s.current?.()}},[]),(0,Z.useLayoutEffect)(()=>{let t=a.current,n=o.current;t&&n!==null&&(t.contains(t.ownerDocument.activeElement)||e.some(e=>e.page===n)||(t.querySelector(`[aria-current="page"]`)??t.querySelector(`button`))?.focus())},[e]);let c=()=>[...a.current?.querySelectorAll(`button`)??[]],l=e=>{let t=c(),n=t.indexOf(e.currentTarget),r=null;e.key===`ArrowRight`?r=(n+1)%t.length:e.key===`ArrowLeft`?r=(n-1+t.length)%t.length:e.key===`Home`?r=0:e.key===`End`&&(r=t.length-1),r!==null&&(e.preventDefault(),t[r]?.focus())};return(0,Q.jsx)(`nav`,{ref:a,className:`section-switcher`,"aria-label":r,onFocus:e=>{o.current=e.target.dataset.sectionPage??null},onBlur:e=>{if(a.current?.contains(e.relatedTarget))return;let t=e.target;window.setTimeout(()=>{t.isConnected&&(o.current=null)},0)},children:e.map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`section-switcher-btn`,"data-section-page":e.page,"aria-current":e.page===t?`page`:void 0,onClick:()=>{e.page!==t&&n(e.page)},onKeyDown:l,children:e.label},e.page))})}var dI=[`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 fI(){try{for(let e of dI)localStorage.removeItem(e)}catch{}}function pI(){let[e,t]=(0,Z.useState)(Wg);(0,Z.useEffect)(()=>{fI()},[]);let n=(0,Z.useCallback)(e=>{let n=t_(e);n.replaceTo&&Yt(n.replaceTo),t(n.page)},[]);return(0,Z.useEffect)(()=>{let e=()=>{n(qt(window.location.hash))};return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[n]),(0,Z.useEffect)(()=>{let n=t_(qt(window.location.hash));n.replaceTo&&Yt(n.replaceTo),n.page!==e&&t(n.page)},[e]),{page:e,setPageState:t,navigateToPage:(e,n)=>{Xt(n?`${e}/${n}`:e),t(e)}}}var mI=15e3,hI=3e3;function gI(e,t,n){return typeof e?.message==`string`&&e.message.trim()?e.message:typeof e?.error==`string`&&e.error.trim()?e.error:n(t)}async function _I(e,t,n){try{return(await t(`${e}/healthz`,{method:`GET`,cache:`no-store`,signal:AbortSignal.timeout(n)})).ok?`answering`:`undecided`}catch{return`gone`}}async function vI(e,t={}){let{fetchFn:n=fetch,timeoutMs:r=mI,formatFailure:i=e=>`Failed to stop proxy (HTTP ${e}).`,formatStillRunning:a=()=>`The proxy is still answering, so it did not stop.`,formatUnknown:o=()=>`The proxy did not confirm the stop. Check whether it is still running.`,mode:s=`standalone`,livenessTimeoutMs:c=hI}=t,l;try{l=await n(`${e}${s===`client`?`/api/machine/disconnect`:`/api/stop`}`,{method:`POST`,...s===`client`?{headers:{"Content-Type":`application/json`},body:`{}`}:{},signal:AbortSignal.timeout(r)})}catch{if(s===`client`)return{status:`unknown`,message:o()};let t=await _I(e,n,c);return t===`gone`?{status:`accepted`}:t===`answering`?{status:`unknown`,message:a()}:{status:`unknown`,message:o()}}let u=null,d=!0;try{u=await l.json()}catch{d=!1}return!l.ok||u?.success===!1?{status:`rejected`,message:gI(u,l.status,i)}:d?{status:`accepted`}:{status:`unknown`,message:o()}}var yI=`ocx-desktop-zoom`,bI=.5,xI=.1;function SI(e){return e===`macos`||e===`linux`}function CI(e){return Number.isFinite(e)?Math.round(Math.min(Math.max(e,bI),3)*100)/100:1}function wI(e,t){return t===`reset`?1:CI(e+(t===`in`?xI:-.1))}function TI(e){return Math.round(e*100)}function EI(e=typeof localStorage>`u`?void 0:localStorage){try{let t=e?.getItem(yI);return t==null?1:CI(Number(t))}catch{return 1}}function DI(e,t=typeof localStorage>`u`?void 0:localStorage){try{t?.setItem(yI,String(e))}catch{}}function OI(e,t){return(t===`macos`?e.metaKey:e.ctrlKey)?e.key===`-`||e.key===`_`?`out`:e.key===`=`||e.key===`+`?`in`:e.key===`0`?`reset`:null:null}function kI(e,t){if(!Number.isFinite(t)||t===0)return{accumulated:e,action:null};let n=(Math.sign(e)===Math.sign(t)?e:0)+t;return Math.abs(n)<50?{accumulated:n,action:null}:{accumulated:0,action:n<0?`in`:`out`}}async function AI(e){let t=window.__TAURI_INTERNALS__?.invoke??window.__TAURI__?.core?.invoke;if(!t)return!1;try{return await t(`plugin:webview|set_webview_zoom`,{value:e}),!0}catch{return!1}}var jI=`ocx-sidebar-collapsed`;function MI(e=typeof localStorage>`u`?void 0:localStorage){try{return e?.getItem(jI)===`1`}catch{return!1}}function NI(e){try{localStorage.setItem(jI,e?`1`:`0`)}catch{}}function PI(e){return e instanceof HTMLElement&&(e.isContentEditable||e.closest(`input, textarea, select, [contenteditable]`)!==null)}function FI({shortcut:e=!1}={}){let[t,n]=(0,Z.useState)(MI),r=(0,Z.useCallback)(()=>n(e=>!e),[]);return(0,Z.useEffect)(()=>{NI(t)},[t]),(0,Z.useEffect)(()=>{if(!e)return;let t=e=>{!(e.metaKey||e.ctrlKey)||e.altKey||e.shiftKey||(e.key===`b`||e.key===`B`)&&(PI(e.target)||(e.preventDefault(),r()))};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[r,e]),{collapsed:t,toggle:r}}function II({managed:e}){let[t,n]=(0,Z.useState)(EI),r=(0,Z.useCallback)(e=>n(t=>wI(t,e)),[]),i=(0,Z.useRef)(0);return(0,Z.useEffect)(()=>{e&&(AI(t),DI(t))},[e,t]),(0,Z.useEffect)(()=>{if(!e)return;let t=vo(),n=e=>{let n=OI(e,t);n&&(e.preventDefault(),e.stopImmediatePropagation(),r(n))},a=e=>{if(!e.ctrlKey)return;e.preventDefault(),e.stopImmediatePropagation();let t=kI(i.current,e.deltaY);i.current=t.accumulated,t.action&&r(t.action)},o=e=>{e.ctrlKey&&(e.preventDefault(),e.stopImmediatePropagation())};return window.addEventListener(`keydown`,n,{capture:!0}),window.addEventListener(`wheel`,a,{capture:!0,passive:!1}),window.addEventListener(`mousewheel`,o,{capture:!0,passive:!1}),()=>{window.removeEventListener(`keydown`,n,{capture:!0}),window.removeEventListener(`wheel`,a,{capture:!0}),window.removeEventListener(`mousewheel`,o,{capture:!0})}},[e,r]),{zoom:t,percent:TI(t),canZoomIn:t<3,canZoomOut:t>bI,step:r}}function LI({percent:e,canZoomIn:t,canZoomOut:r,onStep:i}){let a=n();return(0,Q.jsxs)(`div`,{className:`zoom-control`,role:`group`,"aria-label":a(`zoom.label`),title:a(`zoom.label`),children:[(0,Q.jsx)(`button`,{type:`button`,className:`zoom-control__btn`,disabled:!r,onClick:()=>i(`out`),"aria-label":a(`zoom.out`),title:a(`zoom.out`),children:(0,Q.jsx)(B,{"aria-hidden":!0})}),(0,Q.jsxs)(`button`,{type:`button`,className:`zoom-control__value`,onClick:()=>i(`reset`),"aria-label":a(`zoom.reset`),title:a(`zoom.reset`),children:[e,`%`]}),(0,Q.jsx)(`button`,{type:`button`,className:`zoom-control__btn`,disabled:!t,onClick:()=>i(`in`),"aria-label":a(`zoom.in`),title:a(`zoom.in`),children:(0,Q.jsx)(I,{"aria-hidden":!0})})]})}var RI=[{mode:`light`,tkey:`theme.light`,Icon:ie},{mode:`dark`,tkey:`theme.dark`,Icon:ve},{mode:`system`,tkey:`theme.system`,Icon:ot}];function zI({theme:e,onChange:t}){let r=n();return(0,Q.jsx)(`div`,{className:`theme-switch`,role:`group`,"aria-label":r(`theme.label`),children:RI.map(({mode:n,tkey:i,Icon:a})=>(0,Q.jsx)(`button`,{type:`button`,className:`theme-switch__btn`,"aria-pressed":e===n,"aria-label":r(i),title:r(i),onClick:()=>t(n),children:(0,Q.jsx)(a,{"aria-hidden":!0})},n))})}function BI(e){try{window.__TAURI__?.core?.invoke?.(e).catch(()=>{})}catch{}}var VI=`a, button, input, select, textarea, summary, [role='button'], [role='link'], [contenteditable]`;function HI(e){return e instanceof Element&&e.closest(VI)!==null}function UI(){return{onMouseDown:e=>{e.button!==0||HI(e.target)||BI(`plugin:window|start_dragging`)},onDoubleClick:e=>{HI(e.target)||BI(`plugin:window|toggle_maximize`)}}}function WI(e){let t=window.__TAURI__?.core,n=window.devicePixelRatio,r=Number.isFinite(n)&&n>0?Math.max(2,n):2,i=!0,a=0,o,s=()=>{let t=window.devicePixelRatio,n=Number.isFinite(t)&&t>0?r/t:1,i=Math.max(1,n);if(e.classList.toggle(`app--reduced-zoom`,i>1),e.style.setProperty(`--titlebar-h`,`${Math.ceil(40*i)}px`),n>=1){e.style.setProperty(`--tl-inset`,`${Math.ceil(80*i)}px`),e.style.setProperty(`--chrome-clear`,`${Math.ceil(124*i)}px`);return}let a=Math.ceil(80*n);e.style.setProperty(`--tl-inset`,`${a}px`),e.style.setProperty(`--chrome-clear`,`${a+44}px`)},c=()=>{if(!t?.invoke)return;let e=++a;t.invoke(`plugin:window|scale_factor`).then(t=>{i&&e===a&&typeof t==`number`&&Number.isFinite(t)&&t>0&&(r=t,s())}).catch(()=>{})},l=()=>{s(),clearTimeout(o),o=setTimeout(c,80)};return s(),c(),window.addEventListener(`resize`,l),window.addEventListener(`focus`,c),()=>{i=!1,clearTimeout(o),window.removeEventListener(`resize`,l),window.removeEventListener(`focus`,c)}}function GI({collapsed:e,onToggle:t}){let r=n()(e?`nav.expandSidebar`:`nav.collapseSidebar`);return(0,Q.jsx)(`div`,{className:`sidebar-top`,...UI(),children:(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-collapse`,onClick:t,"aria-expanded":!e,"aria-controls":`app-sidebar`,"aria-label":r,title:r,children:(0,Q.jsx)(ee,{})})})}function KI({children:e}){return(0,Q.jsx)(`div`,{className:`main-top`,...UI(),children:e})}var qI={dashboard:`nav.dashboard`,startup:`nav.startup`,providers:`nav.providers`,models:`nav.models`,subagents:`nav.subagents`,advisor:`nav.advisor`,logs:`nav.logs`,usage:`nav.usage`,storage:`nav.storage`,remote:`nav.remote`,"remote-workspace":`nav.remoteWorkspace`,"codex-set":`nav.codexSet`,integrations:`nav.connect`,claude:`nav.claude`},JI=``,YI=f(JI);p(YI),T();var XI=`ocx-theme`;function ZI({available:e,apiBase:t,hubOrigin:r,onOpenRemoteLink:i}){let a=n();return e?(0,Q.jsx)(yF,{apiBase:t,hubOrigin:r}):(0,Q.jsxs)(`section`,{className:`panel`,children:[(0,Q.jsx)(`h2`,{children:a(`nav.remoteWorkspace`)}),(0,Q.jsxs)($,{tone:`warn`,children:[a(`link.workspaceUnavailable`),` `,(0,Q.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:i,children:a(`nav.remote`)})]})]})}function QI(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 $I(){let e=localStorage.getItem(XI);return e===`light`||e===`dark`?e:`system`}function eL(){let e=document.querySelector(`.sidebar .nav-item.active`),t=e?.getBoundingClientRect(),n=!!t&&t.width>0&&t.height>0&&t.right>0&&t.left<window.innerWidth&&t.bottom>0&&t.top<window.innerHeight;if(e&&n){e.focus({preventScroll:!0});return}let r=document.querySelector(`main.main`);r&&(r.tabIndex=-1,r.focus({preventScroll:!0}))}function tL(){let{page:t,navigateToPage:i}=pI(),[a,o]=(0,Z.useState)(wC);(0,Z.useEffect)(()=>{let e=()=>o(wC());return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]);let[s,c]=(0,Z.useState)($I),{locale:l,setLocale:f}=r(),y=n(),[b,x]=(0,Z.useState)(YI),[C,w]=(0,Z.useState)(()=>!u()),[T,O]=(0,Z.useState)(!1),[k,A]=(0,Z.useState)(()=>m(`shared`)),[M,P]=(0,Z.useState)(0),[F,I]=(0,Z.useState)(!1),[L,R]=(0,Z.useState)(!1),[z,B]=(0,Z.useState)(!1),[V,H]=(0,Z.useState)(null),[U,ee]=(0,Z.useState)(0),W=(0,Z.useCallback)((e,t)=>{H({tone:t,text:e}),ee(e=>e+1)},[]);(0,Z.useEffect)(()=>{let e=e=>{e.detail?.plane===`shared`&&!m(`shared`)&&A(!1)},t=e=>{e.detail?.plane===`shared`&&m(`shared`)&&A(!0)};window.addEventListener(d,e),window.addEventListener(v,t);let n=e=>{e.detail?.plane===`shared`&&P(e=>e+1)};return window.addEventListener(E,n),()=>{window.removeEventListener(d,e),window.removeEventListener(v,t),window.removeEventListener(E,n)}},[]),(0,Z.useEffect)(()=>{let e=new AbortController;return g(JI,e.signal).then(async t=>{p(t),x(t),t.connected&&!m(`shared`)&&await D(`shared`,e.signal),!e.signal.aborted&&(A(m(`shared`)),O(!1),w(!0))}).catch(()=>{e.signal.aborted||(O(!0),w(!0))}),()=>e.abort()},[]);let te=_(`machine`,b),G=_(`shared`,b);(0,Z.useEffect)(()=>{if(!k)return;let e=new AbortController;return fetch(`${G}/api/remote-workspace`,{signal:e.signal,cache:`no-store`}).then(e=>e.ok?e.json():Promise.reject(Error(`unavailable`))).then(t=>{e.signal.aborted||R(t.available===!0)}).catch(()=>{e.signal.aborted||R(!1)}),()=>e.abort()},[t,k,G]);let ne=k&&L,K=cI(t),re=K?lI(K,{remoteWorkspaceAvailable:ne}):[],q=t===`claude`?`integrations`:t,J=t===`remote`&&N()===`hub`,Y=J&&F,[ie,X]=(0,Z.useState)(!1),oe=mo(),{collapsed:se,toggle:ce}=FI({shortcut:oe}),le=oe&&vo()===`macos`,ue=oe&&SI(vo()),de=II({managed:ue}),fe=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{if(le&&fe.current)return WI(fe.current)},[le]);let pe=(0,Z.useRef)(null),me=(0,Z.useRef)(null),he=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>{let e=()=>X(!1);return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]),(0,Z.useEffect)(()=>{if(!mo())return;let e=e=>{let t=e.target;if(!(t instanceof Element))return;let n=t.closest(`a[href]`);if(!(n instanceof HTMLAnchorElement))return;let r=n.href;Co(r)&&(e.preventDefault(),window.location.assign(r))};return document.addEventListener(`click`,e,!0),()=>document.removeEventListener(`click`,e,!0)},[]),(0,Z.useEffect)(()=>{let e=document.documentElement;s===`system`?(e.removeAttribute(`data-theme`),localStorage.removeItem(XI)):(e.setAttribute(`data-theme`,s),localStorage.setItem(XI,s))},[s]),(0,Z.useEffect)(()=>{if(V?.tone!==`ok`)return;let e=window.setTimeout(()=>H(null),4500);return()=>window.clearTimeout(e)},[V,U]);let _e=Wt(`app-healthz:${te}`,[te,C],async e=>{let t=await fetch(`${te}/healthz`,{signal:e});return t.ok?QI(await t.json()):null},{pollMs:3e4,enabled:C}),ve=(0,Q.jsx)(zI,{theme:s,onChange:c}),ye=_e.data??`2.95.3`,[be,Se]=(0,Z.useState)(!1);(0,Z.useEffect)(()=>{if(!ie)return;let e=e=>{e.key===`Escape`&&X(!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}},[ie]),(0,Z.useEffect)(()=>{if(ie){he.current=!0;let e=setTimeout(()=>me.current?.focus(),200);return()=>clearTimeout(e)}he.current&&(he.current=!1,pe.current?.focus())},[ie]),(0,Z.useEffect)(()=>{let e=window.matchMedia(`(min-width: 761px)`),t=()=>{e.matches&&X(!1)};return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]);let[Ce,we]=(0,Z.useState)(0),{restarting:Te,restart:Ee}=Mv(G,{onSettled:()=>we(e=>e+1),report:W}),De=async()=>{if(!await ha({message:y(b.connected?`connection.disconnectConfirm`:`dash.stopConfirm`),confirmLabel:y(b.connected?`connection.disconnect`:`dash.stop`),tone:`danger`}))return;Se(!0);let e=await vI(te,{formatFailure:e=>y(`dash.stopFailed`,{status:String(e)}),formatStillRunning:()=>y(`dash.stopStillRunning`),formatUnknown:()=>y(`dash.stopUnknown`),mode:b.connected?`client`:`standalone`});e.status!==`accepted`&&(Se(!1),W(e.message,e.status===`rejected`?`err`:`warn`))},Oe=async()=>{if(z)return;B(!0);let e=await S(`shared`);B(!1),e?A(!1):W(y(h(`shared`)?`connection.forgetDeviceFailed`:`connection.sessionLogoutFailed`),`err`)},ke=h(`shared`),Ae=y(ke?`connection.forgetDevice`:`connection.sessionLogout`),je=(0,Q.jsxs)(`button`,{type:`button`,className:`brand brand-home`,onClick:()=>{i(`dashboard`),X(!1)},"aria-label":y(`nav.goHome`),title:y(`nav.goHome`),...t===`dashboard`?{"aria-current":`page`}:{},children:[(0,Q.jsx)(`span`,{className:`brand-logo`,role:`img`,"aria-label":y(`app.logoAria`)}),(0,Q.jsx)(`span`,{className:`name`,children:`opencodex`}),(0,Q.jsxs)(`span`,{className:`ver`,title:ye,children:[`v`,ye]})]}),Me=C&&t!==`startup`&&(!b.connected||k)&&(0,Q.jsx)(db,{pageName:y(`quotaSummary.aria`),title:y(`errorBoundary.title`),message:y(`errorBoundary.message`),detailsLabel:y(`errorBoundary.details`),reloadLabel:y(`errorBoundary.reload`),children:(0,Q.jsx)(qF,{apiBase:G})},G);return(0,Q.jsxs)(`div`,{ref:fe,className:`app${oe?` app--desktop`:``}${le?` app--macos`:``}${se?` app--nav-collapsed`:``}`,children:[(0,Q.jsx)(aI,{apiBase:G,enabled:C&&!b.connected}),V&&(0,Q.jsx)(un,{tone:V.tone,onDismiss:()=>H(null),dismissLabel:y(`common.close`),children:V.text}),(0,Q.jsxs)(`header`,{className:`mobile-topbar`,inert:ie,...oe?UI():{},children:[(0,Q.jsx)(`button`,{ref:pe,type:`button`,className:`menu-toggle`,onClick:()=>X(e=>!e),"aria-expanded":ie,"aria-controls":`app-sidebar`,"aria-label":y(ie?`nav.closeMenu`:`nav.openMenu`),title:y(ie?`nav.closeMenu`:`nav.openMenu`),children:(0,Q.jsx)(ge,{})}),je,(0,Q.jsxs)(`div`,{className:`mobile-topbar-actions`,children:[(b.connected||ke)&&k&&(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:()=>{Oe()},disabled:z,"aria-label":z?y(`connection.sessionLoggingOut`):Ae,title:Ae,children:(0,Q.jsx)(xe,{})}),(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-orb sidebar-orb--danger`,onClick:De,disabled:be,"aria-label":y(b.connected?`connection.disconnect`:`dash.stop`),title:y(b.connected?`connection.disconnect`:`dash.stop`),children:(0,Q.jsx)(Ve,{})}),(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:()=>{Ee()},disabled:Te,"aria-label":y(`dash.codexRestart`),title:y(`dash.codexRestart`),children:(0,Q.jsx)(ae,{})})]})]}),ie&&(0,Q.jsx)(`div`,{className:`drawer-scrim`,onClick:()=>X(!1),"aria-hidden":`true`}),(0,Q.jsx)(GI,{collapsed:se,onToggle:ce}),(0,Q.jsxs)(`aside`,{id:`app-sidebar`,className:`sidebar${ie?` open`:``}`,ref:me,tabIndex:-1,children:[(0,Q.jsxs)(`div`,{className:`drawer-head`,children:[je,(0,Q.jsx)(`button`,{type:`button`,className:`menu-toggle drawer-close`,onClick:()=>X(!1),"aria-label":y(`nav.closeMenu`),title:y(`nav.closeMenu`),children:(0,Q.jsx)(xe,{})})]}),(0,Q.jsx)(`nav`,{children:sI.map(e=>{let{id:t,tkey:n,Icon:r}=e,a=K?.id===t;return(0,Q.jsx)(`div`,{className:`nav-entry`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`nav-item${a?` active`:``}`,"data-page":e.pages[0],"data-group":t,onClick:()=>{i(e.pages[0]),X(!1)},"aria-current":a?`page`:void 0,children:[(0,Q.jsx)(r,{}),` `,y(n)]})},t)})}),(0,Q.jsxs)(`div`,{className:`sidebar-foot`,children:[(0,Q.jsxs)(`div`,{className:`lang-toggle`,children:[(0,Q.jsx)(Xe,{"aria-hidden":!0}),(0,Q.jsx)(dn,{value:l,options:j.map(t=>({value:t.code,label:e(t.code)})),onChange:e=>f(e),label:y(`lang.label`),placement:`right`,portal:!1,style:{flex:1,minWidth:0,width:`100%`}})]}),ue?(0,Q.jsxs)(`div`,{className:`sidebar-display-row`,children:[ve,(0,Q.jsx)(LI,{percent:de.percent,canZoomIn:de.canZoomIn,canZoomOut:de.canZoomOut,onStep:de.step})]}):(0,Q.jsxs)(`div`,{className:`sidebar-action-row sidebar-action-row--theme`,children:[(0,Q.jsx)(`span`,{className:`sidebar-action-label`,children:y(`theme.label`)}),ve]}),(0,Q.jsxs)(`div`,{className:`sidebar-action-row`,children:[(0,Q.jsx)(`span`,{className:`sidebar-action-label`,children:y(`dash.actions`)}),(0,Q.jsxs)(`div`,{className:`sidebar-action-orbs`,children:[(b.connected||ke)&&k&&(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:()=>{Oe()},disabled:z,"aria-label":z?y(`connection.sessionLoggingOut`):Ae,title:Ae,children:(0,Q.jsx)(xe,{})}),(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-orb sidebar-orb--danger`,onClick:De,disabled:be,"aria-label":y(be?`dash.stopping`:b.connected?`connection.disconnect`:`dash.stop`),title:y(be?`dash.stopping`:b.connected?`connection.disconnect`:`dash.stop`),children:(0,Q.jsx)(Ve,{})}),(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:()=>{Ee()},disabled:Te,"aria-label":y(Te?`dash.codexRestarting`:`dash.codexRestart`),title:y(Te?`dash.codexRestarting`:`dash.codexRestart`),children:(0,Q.jsx)(ae,{})})]})]}),(0,Q.jsx)(QF,{apiBase:G,onOpenUpdate:()=>{X(!1),!bo()&&i(`dashboard`,`update`)},onOpenTerminalCommand:()=>{X(!1),So()}})]})]}),(0,Q.jsxs)(`main`,{className:`main`,inert:ie,children:[oe?(0,Q.jsx)(KI,{children:Me}):Me,(0,Q.jsxs)(`div`,{className:`main-inner${t===`models`&&a===`combos`?` main-inner--combos`:``}`,children:[C&&re.length>1&&(0,Q.jsx)(uI,{items:re.map(e=>({page:e,label:y(qI[e])})),currentPage:t,onNavigate:i,ariaLabel:y(`nav.sectionNavigation`),onFocusOrphaned:eL}),C&&b.link&&(0,Q.jsx)($,{tone:`warn`,children:b.link.home?y(`connection.linkManaged`,{home:b.link.home,linkId:b.link.linkId}):y(`connection.linkManagedUnnamed`,{linkId:b.link.linkId})}),(0,Q.jsx)(db,{pageName:y(qI[q]),title:y(`errorBoundary.title`),message:y(`errorBoundary.message`),detailsLabel:y(`errorBoundary.details`),reloadLabel:y(`errorBoundary.reload`),children:C?(0,Q.jsxs)(Q.Fragment,{children:[T&&(0,Q.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:y(`connection.machineUnavailable`)}),(b.connected&&!k||Y)&&(0,Q.jsx)(Zk,{target:b.shared,focusOnMount:Y,onConnected:async e=>{Y&&await Fk(G,void 0,e),e.throwIfAborted(),I(!1),A(m(`shared`)),P(e=>e+1)}},`${b.shared.serverOrigin}:${b.shared.bootstrapPath}`),t===`dashboard`&&(0,Q.jsx)(Fs,{apiBase:G,readOnly:b.link!==void 0,connected:b.connected,authenticationPending:b.connected&&!k,refreshEpoch:M}),t===`startup`&&(0,Q.jsx)(GP,{apiBase:G,machineApiBase:te,connected:b.connected}),t===`providers`&&(0,Q.jsx)(b_,{apiBase:G}),t===`models`&&(0,Q.jsx)(XC,{apiBase:G,restartEpoch:Ce,connected:b.connected,catalogSyncedAt:b.catalogSyncedAt,reportRestart:W},G),t===`subagents`&&(0,Q.jsx)(xw,{apiBase:G},G),t===`advisor`&&(0,Q.jsx)(rw,{apiBase:G},G),t===`logs`&&(0,Q.jsx)(FE,{apiBase:G}),t===`usage`&&(0,Q.jsx)(BD,{apiBase:G,connected:b.connected,apiKeyId:b.apiKeyId}),t===`storage`&&(0,Q.jsx)(hO,{apiBase:G}),t===`remote`&&!Y&&(0,Q.jsx)(NF,{apiBase:G,sessionReady:k,pairingRecoveryAvailable:J,onRequestPairing:()=>I(!0),workspaceAvailable:ne,onOpenWorkspace:()=>i(`remote-workspace`)},`${G}:${M}`),t===`remote-workspace`&&(0,Q.jsx)(ZI,{available:ne,apiBase:G,hubOrigin:b.shared.serverOrigin,onOpenRemoteLink:()=>i(`remote`)}),t===`codex-set`&&(0,Q.jsx)(oA,{apiBase:G,machineApiBase:te,connected:b.connected}),q===`integrations`&&(0,Q.jsx)(MP,{apiBase:G,machineApiBase:te,connected:b.connected})]}):(0,Q.jsx)(`div`,{className:`alert`,children:y(`connection.discovering`)})},q)]})]})]})}export{ZI as RemoteWorkspaceRoute,tL as default};