shraga 0.1.117 → 0.1.118

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.
@@ -1904,7 +1904,7 @@ https://github.com/highlightjs/highlight.js/issues/2277`),bn=ve,At=je),rt===void
1904
1904
  `)},LM=function(){var e=parseInt(document.body.getAttribute(Cu)||"0",10);return isFinite(e)?e:0},dre=function(){b.useEffect(function(){return document.body.setAttribute(Cu,(LM()+1).toString()),function(){var e=LM()-1;e<=0?document.body.removeAttribute(Cu):document.body.setAttribute(Cu,e.toString())}},[])},fre=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,i=r===void 0?"margin":r;dre();var a=b.useMemo(function(){return lre(i)},[i]);return b.createElement(cre,{styles:ure(a,!t,i,n?"":"!important")})},o1=!1;if(typeof window<"u")try{var Ap=Object.defineProperty({},"passive",{get:function(){return o1=!0,!0}});window.addEventListener("test",Ap,Ap),window.removeEventListener("test",Ap,Ap)}catch{o1=!1}var nu=o1?{passive:!1}:!1,hre=function(e){return e.tagName==="TEXTAREA"},fz=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!hre(e)&&n[t]==="visible")},mre=function(e){return fz(e,"overflowY")},pre=function(e){return fz(e,"overflowX")},zM=function(e,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var i=hz(e,r);if(i){var a=mz(e,r),s=a[1],l=a[2];if(s>l)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},gre=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},vre=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},hz=function(e,t){return e==="v"?mre(t):pre(t)},mz=function(e,t){return e==="v"?gre(t):vre(t)},yre=function(e,t){return e==="h"&&t==="rtl"?-1:1},bre=function(e,t,n,r,i){var a=yre(e,window.getComputedStyle(t).direction),s=a*r,l=n.target,u=t.contains(l),d=!1,h=s>0,m=0,p=0;do{if(!l)break;var g=mz(e,l),w=g[0],x=g[1],E=g[2],_=x-E-a*w;(w||_)&&hz(e,l)&&(m+=_,p+=w);var k=l.parentNode;l=k&&k.nodeType===Node.DOCUMENT_FRAGMENT_NODE?k.host:k}while(!u&&l!==document.body||u&&(t.contains(l)||t===l));return(h&&Math.abs(m)<1||!h&&Math.abs(p)<1)&&(d=!0),d},kp=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},$M=function(e){return[e.deltaX,e.deltaY]},BM=function(e){return e&&"current"in e?e.current:e},xre=function(e,t){return e[0]===t[0]&&e[1]===t[1]},wre=function(e){return`
1905
1905
  .block-interactivity-`.concat(e,` {pointer-events: none;}
1906
1906
  .allow-interactivity-`).concat(e,` {pointer-events: all;}
1907
- `)},Ere=0,ru=[];function Sre(e){var t=b.useRef([]),n=b.useRef([0,0]),r=b.useRef(),i=b.useState(Ere++)[0],a=b.useState(dz)[0],s=b.useRef(e);b.useEffect(function(){s.current=e},[e]),b.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(i));var x=R7([e.lockRef.current],(e.shards||[]).map(BM),!0).filter(Boolean);return x.forEach(function(E){return E.classList.add("allow-interactivity-".concat(i))}),function(){document.body.classList.remove("block-interactivity-".concat(i)),x.forEach(function(E){return E.classList.remove("allow-interactivity-".concat(i))})}}},[e.inert,e.lockRef.current,e.shards]);var l=b.useCallback(function(x,E){if("touches"in x&&x.touches.length===2||x.type==="wheel"&&x.ctrlKey)return!s.current.allowPinchZoom;var _=kp(x),k=n.current,O="deltaX"in x?x.deltaX:k[0]-_[0],N="deltaY"in x?x.deltaY:k[1]-_[1],C,T=x.target,M=Math.abs(O)>Math.abs(N)?"h":"v";if("touches"in x&&M==="h"&&T.type==="range")return!1;var D=window.getSelection(),j=D&&D.anchorNode,R=j?j===T||j.contains(T):!1;if(R)return!1;var H=zM(M,T);if(!H)return!0;if(H?C=M:(C=M==="v"?"h":"v",H=zM(M,T)),!H)return!1;if(!r.current&&"changedTouches"in x&&(O||N)&&(r.current=C),!C)return!0;var P=r.current||C;return bre(P,E,x,P==="h"?O:N)},[]),u=b.useCallback(function(x){var E=x;if(!(!ru.length||ru[ru.length-1]!==a)){var _="deltaY"in E?$M(E):kp(E),k=t.current.filter(function(C){return C.name===E.type&&(C.target===E.target||E.target===C.shadowParent)&&xre(C.delta,_)})[0];if(k&&k.should){E.cancelable&&E.preventDefault();return}if(!k){var O=(s.current.shards||[]).map(BM).filter(Boolean).filter(function(C){return C.contains(E.target)}),N=O.length>0?l(E,O[0]):!s.current.noIsolation;N&&E.cancelable&&E.preventDefault()}}},[]),d=b.useCallback(function(x,E,_,k){var O={name:x,delta:E,target:_,should:k,shadowParent:_re(_)};t.current.push(O),setTimeout(function(){t.current=t.current.filter(function(N){return N!==O})},1)},[]),h=b.useCallback(function(x){n.current=kp(x),r.current=void 0},[]),m=b.useCallback(function(x){d(x.type,$M(x),x.target,l(x,e.lockRef.current))},[]),p=b.useCallback(function(x){d(x.type,kp(x),x.target,l(x,e.lockRef.current))},[]);b.useEffect(function(){return ru.push(a),e.setCallbacks({onScrollCapture:m,onWheelCapture:m,onTouchMoveCapture:p}),document.addEventListener("wheel",u,nu),document.addEventListener("touchmove",u,nu),document.addEventListener("touchstart",h,nu),function(){ru=ru.filter(function(x){return x!==a}),document.removeEventListener("wheel",u,nu),document.removeEventListener("touchmove",u,nu),document.removeEventListener("touchstart",h,nu)}},[]);var g=e.removeScrollBar,w=e.inert;return b.createElement(b.Fragment,null,w?b.createElement(a,{styles:wre(i)}):null,g?b.createElement(fre,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function _re(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const Are=Jne(uz,Sre);var vS=b.forwardRef(function(e,t){return b.createElement(Wv,xa({},e,{ref:t,sideCar:Are}))});vS.classNames=Wv.classNames;var kre=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},iu=new WeakMap,Op=new WeakMap,Np={},Lx=0,pz=function(e){return e&&(e.host||pz(e.parentNode))},Ore=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=pz(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},Nre=function(e,t,n,r){var i=Ore(t,Array.isArray(e)?e:[e]);Np[n]||(Np[n]=new WeakMap);var a=Np[n],s=[],l=new Set,u=new Set(i),d=function(m){!m||l.has(m)||(l.add(m),d(m.parentNode))};i.forEach(d);var h=function(m){!m||u.has(m)||Array.prototype.forEach.call(m.children,function(p){if(l.has(p))h(p);else try{var g=p.getAttribute(r),w=g!==null&&g!=="false",x=(iu.get(p)||0)+1,E=(a.get(p)||0)+1;iu.set(p,x),a.set(p,E),s.push(p),x===1&&w&&Op.set(p,!0),E===1&&p.setAttribute(n,"true"),w||p.setAttribute(r,"true")}catch(_){console.error("aria-hidden: cannot operate on ",p,_)}})};return h(t),l.clear(),Lx++,function(){s.forEach(function(m){var p=iu.get(m)-1,g=a.get(m)-1;iu.set(m,p),a.set(m,g),p||(Op.has(m)||m.removeAttribute(r),Op.delete(m)),g||m.removeAttribute(n)}),Lx--,Lx||(iu=new WeakMap,iu=new WeakMap,Op=new WeakMap,Np={})}},gz=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),i=kre(e);return i?(r.push.apply(r,Array.from(i.querySelectorAll("[aria-live], script"))),Nre(r,i,n,"aria-hidden")):function(){return null}},Yv="Dialog",[vz]=hL(Yv),[Cre,Ji]=vz(Yv),yz=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:i,onOpenChange:a,modal:s=!0}=e,l=b.useRef(null),u=b.useRef(null),[d,h]=_ne({prop:r,defaultProp:i??!1,onChange:a,caller:Yv});return y.jsx(Cre,{scope:t,triggerRef:l,contentRef:u,contentId:Mx(),titleId:Mx(),descriptionId:Mx(),open:d,onOpenChange:h,onOpenToggle:b.useCallback(()=>h(m=>!m),[h]),modal:s,children:n})};yz.displayName=Yv;var bz="DialogTrigger",xz=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=Ji(bz,n),a=ui(t,i.triggerRef);return y.jsx(Fr.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":ES(i.open),...r,ref:a,onClick:Sr(e.onClick,i.onOpenToggle)})});xz.displayName=bz;var yS="DialogPortal",[Tre,wz]=vz(yS,{forceMount:void 0}),Ez=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:i}=e,a=Ji(yS,t);return y.jsx(Tre,{scope:t,forceMount:n,children:b.Children.map(r,s=>y.jsx(Xs,{present:n||a.open,children:y.jsx(lz,{asChild:!0,container:i,children:s})}))})};Ez.displayName=yS;var Pg="DialogOverlay",bS=b.forwardRef((e,t)=>{const n=wz(Pg,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,a=Ji(Pg,e.__scopeDialog);return a.modal?y.jsx(Xs,{present:r||a.open,children:y.jsx(Ire,{...i,ref:t})}):null});bS.displayName=Pg;var Mre=GE("DialogOverlay.RemoveScroll"),Ire=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=Ji(Pg,n),a=Ine(),s=ui(t,a);return y.jsx(vS,{as:Mre,allowPinchZoom:!0,shards:[i.contentRef],children:y.jsx(Fr.div,{"data-state":ES(i.open),...r,ref:s,style:{pointerEvents:"auto",...r.style}})})}),Uu="DialogContent",xS=b.forwardRef((e,t)=>{const n=wz(Uu,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,a=Ji(Uu,e.__scopeDialog);return y.jsx(Xs,{present:r||a.open,children:a.modal?y.jsx(Rre,{...i,ref:t}):y.jsx(Pre,{...i,ref:t})})});xS.displayName=Uu;var Rre=b.forwardRef((e,t)=>{const n=Ji(Uu,e.__scopeDialog),r=b.useRef(null),i=ui(t,n.contentRef,r);return b.useEffect(()=>{const a=r.current;if(a)return gz(a)},[]),y.jsx(Sz,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,onCloseAutoFocus:Sr(e.onCloseAutoFocus,a=>{var s;a.preventDefault(),(s=n.triggerRef.current)==null||s.focus()}),onPointerDownOutside:Sr(e.onPointerDownOutside,a=>{const s=a.detail.originalEvent,l=s.button===0&&s.ctrlKey===!0;(s.button===2||l)&&a.preventDefault()}),onFocusOutside:Sr(e.onFocusOutside,a=>a.preventDefault())})}),Pre=b.forwardRef((e,t)=>{const n=Ji(Uu,e.__scopeDialog),r=b.useRef(!1),i=b.useRef(!1);return y.jsx(Sz,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:a=>{var s,l;(s=e.onCloseAutoFocus)==null||s.call(e,a),a.defaultPrevented||(r.current||(l=n.triggerRef.current)==null||l.focus(),a.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:a=>{var u,d;(u=e.onInteractOutside)==null||u.call(e,a),a.defaultPrevented||(r.current=!0,a.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const s=a.target;((d=n.triggerRef.current)==null?void 0:d.contains(s))&&a.preventDefault(),a.detail.originalEvent.type==="focusin"&&i.current&&a.preventDefault()}})}),Sz=b.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:a,...s}=e,l=Ji(Uu,n);return Kne(),y.jsx(y.Fragment,{children:y.jsx(oz,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:a,children:y.jsx(iz,{role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":ES(l.open),...s,ref:t,deferPointerDownOutside:!0,onDismiss:()=>l.onOpenChange(!1)})})})}),_z="DialogTitle",wS=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=Ji(_z,n);return y.jsx(Fr.h2,{id:i.titleId,...r,ref:t})});wS.displayName=_z;var Az="DialogDescription",Dre=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=Ji(Az,n);return y.jsx(Fr.p,{id:i.descriptionId,...r,ref:t})});Dre.displayName=Az;var kz="DialogClose",Oz=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=Ji(kz,n);return y.jsx(Fr.button,{type:"button",...r,ref:t,onClick:Sr(e.onClick,()=>i.onOpenChange(!1))})});Oz.displayName=kz;function ES(e){return e?"open":"closed"}const Oo=yz,rd=xz,jre=Ez,Nz=b.forwardRef(({className:e,...t},n)=>y.jsx(bS,{ref:n,className:Be("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));Nz.displayName=bS.displayName;const Na=b.forwardRef(({className:e,children:t,...n},r)=>y.jsxs(jre,{children:[y.jsx(Nz,{}),y.jsxs(xS,{ref:r,className:Be("fixed left-[50%] top-[50%] z-50 flex flex-col w-[calc(100vw-2rem)] max-w-lg max-h-[85dvh] overflow-y-auto translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-4 sm:p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 sm:rounded-lg",e),...n,children:[t,y.jsxs(Oz,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[y.jsx(Ql,{className:"h-4 w-4"}),y.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Na.displayName=xS.displayName;function Bs({className:e,...t}){return y.jsx("div",{className:Be("shrink-0 flex flex-col space-y-1.5 text-center sm:text-left",e),...t})}function Cz({className:e,...t}){return y.jsx("div",{"data-dialog-body":!0,className:Be("flex-1 min-h-0 overflow-y-auto -mx-4 px-4 sm:-mx-6 sm:px-6",e),...t})}function Tz({className:e,...t}){return y.jsx("div",{className:Be("shrink-0 -mx-4 px-4 pt-3 border-t sm:-mx-6 sm:px-6","flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",e),...t})}const No=b.forwardRef(({className:e,...t},n)=>y.jsx(wS,{ref:n,className:Be("text-lg font-semibold leading-none tracking-tight",e),...t}));No.displayName=wS.displayName;const Lre=new Set(["png","jpg","jpeg","gif","webp","svg","ico","bmp","avif"]),zre=new Set(["pdf","mp4","webm","mp3","ogg","wav"]);async function $re(e,t){const n=await t();if(!n)return[];const r=await fetch(`/api/workspace/ls?path=${encodeURIComponent(e)}`,{headers:{Authorization:`Bearer ${n}`}});return r.ok?(await r.json()).entries??[]:[]}function Bre({getToken:e,onRefresh:t,refreshKey:n}){const[r,i]=b.useState(new Map),[a,s]=b.useState(()=>new Set),[l,u]=b.useState(null),[d,h]=b.useState(!1),[m,p]=b.useState("fit"),[g,w]=b.useState(null),[x,E]=b.useState(null),_=b.useRef(null),[k,O]=b.useState(null),[N,C]=b.useState(!1),[T,M]=b.useState([]),D=b.useCallback(async U=>{const K=await $re(U,e);i(F=>new Map(F).set(U,K))},[e]);b.useEffect(()=>{D(""),a.forEach(U=>D(U))},[D,n]);const j=r.get("")??[],R=b.useCallback(U=>{try{const K=U.contentDocument;if(!(K!=null&&K.body))return;const F=Math.max(K.body.offsetWidth,K.body.scrollWidth),V=Math.max(K.body.offsetHeight,K.body.scrollHeight);F&&V&&E({w:F,h:V})}catch{}},[]),H=b.useCallback(()=>{const U=_.current,K=x;if(!U||!K)return;const F=16,V=U.clientWidth-F,$=U.clientHeight-F,L=Math.min(V/K.w,$/K.h,1);w({scale:L,w:K.w,h:K.h})},[x]);b.useEffect(()=>{if(!(l!=null&&l.html)||m!=="fit"){w(null);return}const U=_.current;if(!U)return;const K=new ResizeObserver(()=>requestAnimationFrame(H));return K.observe(U),()=>K.disconnect()},[l==null?void 0:l.html,d,m,H]),b.useEffect(()=>{N&&e().then(U=>{U&&fetch("/api/data-sync/log",{headers:{Authorization:`Bearer ${U}`}}).then(K=>K.json()).then(M).catch(()=>{})})},[N]);const P=U=>{s(K=>{const F=new Set(K);return F.has(U)?F.delete(U):(F.add(U),r.has(U)||D(U)),F})},G=(U,K)=>{const F=new URLSearchParams({path:U});return k&&F.set("token",k),K&&F.set("dl","1"),`/api/workspace/raw?${F}`},q=async U=>{var V;const K=await e();if(!K)return;O(K);const F=((V=U.split(".").pop())==null?void 0:V.toLowerCase())??"";if(F==="html"||F==="htm"){u({path:U,content:"",binary:!1,html:!0});return}if(Lre.has(F)){u({path:U,content:"",binary:!1,image:!0});return}if(zre.has(F)){u({path:U,content:"",binary:!1,html:!0});return}try{const $=await fetch(`/api/workspace/file?path=${encodeURIComponent(U)}`,{headers:{Authorization:`Bearer ${K}`}});if(!$.ok)return;const L=await $.json();u({path:U,content:L.content,binary:!!L.binary})}catch{}},X=(U,K)=>y.jsx(y.Fragment,{children:U.map(F=>{const V=F.path.split("/").pop();return y.jsxs("div",{children:[F.type==="dir"?y.jsxs("button",{onClick:()=>P(F.path),className:"w-full flex items-center gap-1 px-2 py-1 rounded hover:bg-accent/50 text-left text-sm",style:{paddingLeft:8+K*12},children:[y.jsx(Ys,{className:Be("w-3 h-3 shrink-0 transition-transform",a.has(F.path)&&"rotate-90")}),y.jsx(JG,{className:"w-3.5 h-3.5 shrink-0 text-muted-foreground"}),y.jsx("span",{className:"truncate",children:V})]}):y.jsxs("button",{onClick:()=>q(F.path),className:"w-full flex items-center gap-1 px-2 py-1 rounded hover:bg-accent/50 text-left text-sm",style:{paddingLeft:8+K*12+12},title:F.oneLiner||F.path,children:[y.jsx(UE,{className:"w-3.5 h-3.5 shrink-0 text-muted-foreground"}),y.jsx("span",{className:"truncate",children:V})]}),F.type==="dir"&&a.has(F.path)&&X(r.get(F.path)??[],K+1)]},F.path)})});return y.jsxs(y.Fragment,{children:[y.jsxs("div",{className:"flex items-center justify-between px-3 pt-2 pb-1 shrink-0",children:[y.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",children:"Workspace"}),y.jsxs("div",{className:"flex items-center gap-0.5",children:[y.jsx("button",{onClick:()=>C(!0),className:"p-0.5 rounded hover:bg-accent text-muted-foreground",title:"Activity log",children:y.jsx(tV,{className:"w-3 h-3"})}),y.jsx("button",{onClick:()=>{D(""),a.forEach(U=>D(U)),t==null||t()},className:"p-0.5 rounded hover:bg-accent text-muted-foreground",title:"Refresh",children:y.jsx(ed,{className:"w-3 h-3"})})]})]}),y.jsx("div",{className:"px-1 pb-2 overflow-y-auto min-h-0",children:j.length===0?y.jsx("p",{className:"text-xs text-muted-foreground px-3 py-2",children:"Empty. Drop .md files into data/workspace/ or ask the agent to create some."}):X(j,0)}),y.jsx(Oo,{open:!!l,onOpenChange:U=>{U||(u(null),h(!1),p("fit"),E(null))},children:y.jsxs(Na,{className:Be(l!=null&&l.html?Be("!flex !flex-col !p-0 !gap-0 overflow-hidden",d?"max-w-none w-[100vw] h-[100vh] rounded-none border-0":"max-w-[90vw] w-[90vw] h-[85vh]"):"max-w-3xl max-h-[80vh] !flex !flex-col overflow-hidden"),children:[y.jsxs("div",{className:"absolute right-12 top-4 flex items-center gap-1.5 z-10",children:[(l==null?void 0:l.html)&&y.jsxs(y.Fragment,{children:[y.jsx("button",{onClick:()=>p(U=>U==="fit"?"scroll":"fit"),className:"rounded-sm opacity-70 hover:opacity-100 text-muted-foreground",title:m==="fit"?"Switch to scrollable (1:1)":"Switch to scale-to-fit",children:m==="fit"?y.jsx(oV,{className:"w-4 h-4"}):y.jsx(fV,{className:"w-4 h-4"})}),y.jsx("button",{onClick:()=>h(U=>!U),className:"rounded-sm opacity-70 hover:opacity-100 text-muted-foreground",title:d?"Restore":"Maximize",children:d?y.jsx(HE,{className:"w-4 h-4"}):y.jsx(FE,{className:"w-4 h-4"})})]}),l&&y.jsx("a",{href:G(l.path,!0),download:!0,className:"rounded-sm opacity-70 hover:opacity-100 text-muted-foreground",title:"Download",children:y.jsx(lL,{className:"w-4 h-4"})})]}),y.jsx(Bs,{className:Be((l==null?void 0:l.html)&&"px-4 py-3 shrink-0 border-b"),children:y.jsx(No,{className:"font-mono text-sm truncate pr-16",children:l==null?void 0:l.path})}),y.jsx("div",{ref:l!=null&&l.html?_:void 0,className:Be(l!=null&&l.html?Be("flex-1 min-h-0 bg-muted/10",m==="fit"?"overflow-hidden flex items-center justify-center":"overflow-auto"):"flex-1 min-h-0 overflow-y-auto"),children:l!=null&&l.html?m==="fit"?y.jsx("div",{style:g?{width:g.w*g.scale,height:g.h*g.scale}:{width:"100%",height:"100%"},children:y.jsx("iframe",{src:G(l.path),className:"border-0 bg-white origin-top-left",title:l.path,onLoad:U=>{R(U.currentTarget),H()},style:g?{width:g.w,height:g.h,transform:`scale(${g.scale})`}:{width:"100%",height:"100%"}})}):y.jsx("iframe",{src:G(l.path),className:"border-0 bg-white mx-auto block",title:l.path,onLoad:U=>R(U.currentTarget),style:{width:(x==null?void 0:x.w)||"100%",height:(x==null?void 0:x.h)||"100%"}}):l!=null&&l.image?y.jsx("div",{className:"flex items-center justify-center p-4",children:y.jsx("img",{src:G(l.path),alt:l.path,className:"max-w-full max-h-[70vh] object-contain"})}):l!=null&&l.binary?y.jsx("p",{className:"text-sm text-muted-foreground",children:"(binary file — preview unavailable)"}):l!=null&&l.path.toLowerCase().endsWith(".md")||l!=null&&l.path.toLowerCase().endsWith(".markdown")?y.jsx("div",{className:"text-sm",children:y.jsx(d3,{remarkPlugins:[D3],rehypePlugins:[rz],className:"prose prose-sm max-w-none dark:prose-invert prose-pre:bg-muted prose-pre:border prose-code:before:content-none prose-code:after:content-none",children:l.content})}):y.jsx("pre",{className:"text-xs whitespace-pre-wrap break-all",children:l==null?void 0:l.content})})]})}),y.jsx(Oo,{open:N,onOpenChange:C,children:y.jsxs(Na,{className:"max-w-2xl max-h-[80vh] overflow-hidden flex flex-col",children:[y.jsx(Bs,{children:y.jsx(No,{className:"text-sm",children:"Activity Log"})}),y.jsxs("div",{className:"overflow-y-auto flex-1 space-y-2",children:[T.map(U=>y.jsxs("div",{className:"border-b border-border/50 pb-2 last:border-0",children:[y.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[y.jsx("span",{className:"text-sm text-foreground",children:U.message}),y.jsx("span",{className:"text-[10px] text-muted-foreground shrink-0",children:Ure(U.date)})]}),U.files.length>0&&y.jsx("div",{className:"text-[11px] text-muted-foreground mt-0.5",children:U.files.map(K=>y.jsx("span",{className:"inline-block mr-2 font-mono",children:K},K))})]},U.hash)),T.length===0&&y.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No activity yet"})]})]})})]})}function Ure(e){const t=new Date(e),r=new Date().getTime()-t.getTime(),i=Math.floor(r/6e4);if(i<60)return`${i}m ago`;const a=Math.floor(i/60);return a<24?`${a}h ago`:t.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function ag(e,t=Date.now()){if(!e)return null;const n=new Date(e).getTime()-t;if(!Number.isFinite(n)||n<=0)return null;const r=Math.round(n/6e4);if(r<1)return"1m";if(r<60)return`${r}m`;const i=Math.floor(r/60),a=r%60;if(i<48)return a?`${i}h ${a}m`:`${i}h`;const s=Math.floor(i/24),l=i%24;return l?`${s}d ${l}h`:`${s}d`}const Fre=/resets\s+(\d{1,2})(?::(\d{2}))?\s*(am|pm)?\s*\(UTC\)/i;function Hre(e,t=Date.now(),n=Date.now()){var m;const r=e.match(Fre);if(!r)return e;let i=Number(r[1]);const a=r[2]?Number(r[2]):0,s=(m=r[3])==null?void 0:m.toLowerCase();if(s==="pm"&&i<12&&(i+=12),s==="am"&&i===12&&(i=0),i>23||a>59)return e;const l=new Date(t),u=new Date(Date.UTC(l.getUTCFullYear(),l.getUTCMonth(),l.getUTCDate(),i,a));u.getTime()<=t&&u.setUTCDate(u.getUTCDate()+1);const d=u.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"}),h=ag(u.toISOString(),n);return e.replace(r[0],`resets ${d}${h?` (in ${h})`:""}`)}var Kre=Object.defineProperty,id=(e,t)=>Kre(e,"name",{value:t,configurable:!0}),Mz=!!(typeof window<"u"&&window.document&&window.document.createElement);function Ds(e,t,{checkForDefaultPrevented:n=!0}={}){return id(function(i){if(e==null||e(i),n===!1||!i||!i.defaultPrevented)return t==null?void 0:t(i)},"handleEvent")}id(Ds,"composeEventHandlers");function qre(e){var t;if(!Mz)throw new Error("Cannot access window outside of the DOM");return((t=e==null?void 0:e.ownerDocument)==null?void 0:t.defaultView)??window}id(qre,"getOwnerWindow");function s1(e){if(!Mz)throw new Error("Cannot access document outside of the DOM");return(e==null?void 0:e.ownerDocument)??document}id(s1,"getOwnerDocument");function Iz(e,t=!1){const{activeElement:n}=s1(e);if(!(n!=null&&n.nodeName))return null;if(Rz(n)&&n.contentDocument)return Iz(n.contentDocument.body,t);if(t){const r=n.getAttribute("aria-activedescendant");if(r){const i=s1(n).getElementById(r);if(i)return i}}return n}id(Iz,"getActiveElement");function Rz(e){return e.tagName==="IFRAME"}id(Rz,"isFrame");var Gre=Object.defineProperty,SS=(e,t)=>Gre(e,"name",{value:t,configurable:!0});function l1(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}SS(l1,"setRef");function Pz(...e){return t=>{let n=!1;const r=e.map(i=>{const a=l1(i,t);return!n&&typeof a=="function"&&(n=!0),a});if(n)return()=>{for(let i=0;i<r.length;i++){const a=r[i];typeof a=="function"?a():l1(e[i],null)}}}}SS(Pz,"composeRefs");function ad(...e){return b.useCallback(Pz(...e),e)}SS(ad,"useComposedRefs");var Vre=Object.defineProperty,Ni=(e,t)=>Vre(e,"name",{value:t,configurable:!0});function Wre(e,t){const n=b.createContext(t);n.displayName=e+"Context";const r=Ni(a=>{const{children:s,...l}=a,u=b.useMemo(()=>l,Object.values(l));return y.jsx(n.Provider,{value:u,children:s})},"Provider");r.displayName=e+"Provider";function i(a,s={}){const{optional:l=!1}=s,u=b.useContext(n);if(u)return u;if(t!==void 0)return t;if(!l)throw new Error(`\`${a}\` must be used within \`${e}\``)}return Ni(i,"useContext"),[r,i]}Ni(Wre,"createContext");function Dz(e,t=[]){let n=[];function r(a,s){const l=b.createContext(s);l.displayName=a+"Context";const u=n.length;n=[...n,s];const d=Ni(m=>{var _;const{scope:p,children:g,...w}=m,x=((_=p==null?void 0:p[e])==null?void 0:_[u])||l,E=b.useMemo(()=>w,Object.values(w));return y.jsx(x.Provider,{value:E,children:g})},"Provider");d.displayName=a+"Provider";function h(m,p,g={}){var _;const{optional:w=!1}=g,x=((_=p==null?void 0:p[e])==null?void 0:_[u])||l,E=b.useContext(x);if(E)return E;if(s!==void 0)return s;if(!w)throw new Error(`\`${m}\` must be used within \`${a}\``)}return Ni(h,"useContext"),[d,h]}Ni(r,"createContext");const i=Ni(()=>{const a=n.map(s=>b.createContext(s));return Ni(function(l){const u=(l==null?void 0:l[e])||a;return b.useMemo(()=>({[`__scope${e}`]:{...l,[e]:u}}),[l,u])},"useScope")},"createScope");return i.scopeName=e,[r,jz(i,...t)]}Ni(Dz,"createContextScope");function jz(...e){const t=e[0];if(e.length===1)return t;const n=Ni(()=>{const r=e.map(i=>({useScope:i(),scopeName:i.scopeName}));return Ni(function(a){const s=r.reduce((l,{useScope:u,scopeName:d})=>{const m=u(a)[`__scope${d}`];return{...l,...m}},{});return b.useMemo(()=>({[`__scope${t.scopeName}`]:s}),[s])},"useComposedScopes")},"createScope");return n.scopeName=t.scopeName,n}Ni(jz,"composeContextScopes");var Yre=Object.defineProperty,ea=(e,t)=>Yre(e,"name",{value:t,configurable:!0});function _S(e){const t=b.forwardRef((n,r)=>{let{children:i,...a}=n,s=null,l=!1;const u=[];c1(i)&&typeof Cp=="function"&&(i=Cp(i._payload)),b.Children.forEach(i,p=>{var g;if(Bz(p)){l=!0;const w=p;let x="child"in w.props?w.props.child:w.props.children;c1(x)&&typeof Cp=="function"&&(x=Cp(x._payload)),s=Zre(w,x),u.push((g=s==null?void 0:s.props)==null?void 0:g.children)}else u.push(p)}),s?s=b.cloneElement(s,void 0,u):!l&&b.Children.count(i)===1&&b.isValidElement(i)&&(s=i);const d=s?$z(s):void 0,h=ad(r,d);if(!s){if(i||i===0)throw new Error(l?eie(e):Jre(e));return i}const m=zz(a,s.props??{});return s.type!==b.Fragment&&(m.ref=r?h:d),b.cloneElement(s,m)});return t.displayName=`${e}.Slot`,t}ea(_S,"createSlot");var Lz=Symbol.for("radix.slottable");function Xre(e){const t=ea(n=>"child"in n?n.children(n.child):n.children,"Slottable");return t.displayName=`${e}.Slottable`,t.__radixId=Lz,t}ea(Xre,"createSlottable");var Zre=ea((e,t)=>{if("child"in e.props){const n=e.props.child;return b.isValidElement(n)?b.cloneElement(n,void 0,e.props.children(n.props.children)):null}return b.isValidElement(t)?t:null},"getSlottableElementFromSlottable");function zz(e,t){const n={...t};for(const r in t){const i=e[r],a=t[r];/^on[A-Z]/.test(r)?i&&a?n[r]=(...l)=>{const u=a(...l);return i(...l),u}:i&&(n[r]=i):r==="style"?n[r]={...i,...a}:r==="className"&&(n[r]=[i,a].filter(Boolean).join(" "))}return{...e,...n}}ea(zz,"mergeProps");function $z(e){var r,i;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(i=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:i.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}ea($z,"getElementRef");function Bz(e){return b.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Lz}ea(Bz,"isSlottable");var Qre=Symbol.for("react.lazy");function c1(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===Qre&&"_payload"in e&&Uz(e._payload)}ea(c1,"isLazyComponent");function Uz(e){return typeof e=="object"&&e!==null&&"then"in e}ea(Uz,"isPromiseLike");var Jre=ea(e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,"createSlotError"),eie=ea(e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,"createSlottableError"),Cp=ja[" use ".trim().toString()],tie=Object.defineProperty,nie=(e,t)=>tie(e,"name",{value:t,configurable:!0}),rie=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Xv=rie.reduce((e,t)=>{const n=_S(`Primitive.${t}`),r=b.forwardRef((i,a)=>{const{asChild:s,...l}=i,u=s?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),y.jsx(u,{...l,ref:a})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function Fz(e,t){e&&La.flushSync(()=>e.dispatchEvent(t))}nie(Fz,"dispatchDiscreteCustomEvent");var iie=Object.defineProperty,aie=(e,t)=>iie(e,"name",{value:t,configurable:!0});function Zv(e){const t=b.useRef(e);return b.useEffect(()=>{t.current=e}),b.useMemo(()=>((...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)}),[])}aie(Zv,"useCallbackRef");var oie=Object.defineProperty,qn=(e,t)=>oie(e,"name",{value:t,configurable:!0}),u1="dismissableLayer.update",sie="dismissableLayer.pointerDownOutside",lie="dismissableLayer.focusOutside",UM,Hz=b.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),cie=b.forwardRef(qn(function(t,n){const{disableOutsidePointerEvents:r=!1,deferPointerDownOutside:i=!1,onEscapeKeyDown:a,onPointerDownOutside:s,onFocusOutside:l,onInteractOutside:u,onDismiss:d,...h}=t,m=b.useContext(Hz),[p,g]=b.useState(null),w=(p==null?void 0:p.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,x]=b.useState({}),E=ad(n,g),_=Array.from(m.layers),[k]=[...m.layersWithOutsidePointerEventsDisabled].slice(-1),O=k?_.indexOf(k):-1,N=p?_.indexOf(p):-1,C=m.layersWithOutsidePointerEventsDisabled.size>0,T=N>=O,M=b.useRef(!1),D=Kz(P=>{s==null||s(P),u==null||u(P),P.defaultPrevented||d==null||d()},{ownerDocument:w,deferPointerDownOutside:i,isDeferredPointerDownOutsideRef:M,dismissableSurfaces:m.dismissableSurfaces,shouldHandlePointerDownOutside:b.useCallback(P=>{if(!(P instanceof Node))return!1;const G=[...m.branches].some(q=>q.contains(P));return T&&!G},[m.branches,T])}),j=qz(P=>{if(i&&M.current)return;const G=P.target;[...m.branches].some(X=>X.contains(G))||(l==null||l(P),u==null||u(P),P.defaultPrevented||d==null||d())},w),R=p?N===_.length-1:!1,H=Zv(P=>{P.key==="Escape"&&(a==null||a(P),!P.defaultPrevented&&d&&(P.preventDefault(),d()))});return b.useEffect(()=>{if(R)return w.addEventListener("keydown",H,{capture:!0}),()=>w.removeEventListener("keydown",H,{capture:!0})},[w,R,H]),b.useEffect(()=>{if(p)return r&&(m.layersWithOutsidePointerEventsDisabled.size===0&&(UM=w.body.style.pointerEvents,w.body.style.pointerEvents="none"),m.layersWithOutsidePointerEventsDisabled.add(p)),m.layers.add(p),d1(),()=>{r&&(m.layersWithOutsidePointerEventsDisabled.delete(p),m.layersWithOutsidePointerEventsDisabled.size===0&&(w.body.style.pointerEvents=UM))}},[p,w,r,m]),b.useEffect(()=>()=>{p&&(m.layers.delete(p),m.layersWithOutsidePointerEventsDisabled.delete(p),d1())},[p,m]),b.useEffect(()=>{const P=qn(()=>x({}),"handleUpdate");return document.addEventListener(u1,P),()=>document.removeEventListener(u1,P)},[]),y.jsx(Xv.div,{...h,ref:E,style:{pointerEvents:C?T?"auto":"none":void 0,...t.style},onFocusCapture:Ds(t.onFocusCapture,j.onFocusCapture),onBlurCapture:Ds(t.onBlurCapture,j.onBlurCapture),onPointerDownCapture:Ds(t.onPointerDownCapture,D.onPointerDownCapture)})},"DismissableLayer"));function uie(){const e=b.useContext(Hz),[t,n]=b.useState(null);return b.useEffect(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),n}qn(uie,"useDismissableLayerSurface");var die=qn(()=>!0,"IS_TRUE");function Kz(e,t){const{ownerDocument:n=globalThis==null?void 0:globalThis.document,deferPointerDownOutside:r=!1,isDeferredPointerDownOutsideRef:i,dismissableSurfaces:a,shouldHandlePointerDownOutside:s=die}=t,l=Zv(e),u=b.useRef(!1),d=b.useRef(!1),h=b.useRef(new Map),m=b.useRef(()=>{});return b.useEffect(()=>{function p(){d.current=!1,i.current=!1,h.current.clear()}qn(p,"resetOutsideInteraction");function g(){return Array.from(h.current.values()).some(Boolean)}qn(g,"isOutsideInteractionIntercepted");function w(O){if(!d.current)return;const N=O.target;N instanceof Node&&[...a].some(T=>T.contains(N))||h.current.set(O.type,!0),O.type==="click"&&window.setTimeout(()=>{d.current&&m.current()},0)}qn(w,"handleInteractionCapture");function x(O){d.current&&h.current.set(O.type,!1)}qn(x,"handleInteractionBubble");const E=qn(O=>{if(O.target&&!u.current){let N=function(){n.removeEventListener("click",m.current);const T=g();p(),T||AS(sie,l,C,{discrete:!0})};if(qn(N,"handleAndDispatchPointerDownOutsideEvent"),!s(O.target)){n.removeEventListener("click",m.current),p(),u.current=!1;return}const C={originalEvent:O};d.current=!0,i.current=r&&O.button===0,h.current.clear(),!r||O.button!==0?N():(n.removeEventListener("click",m.current),m.current=N,n.addEventListener("click",m.current,{once:!0}))}else n.removeEventListener("click",m.current),p();u.current=!1},"handlePointerDown"),_=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const O of _)n.addEventListener(O,w,!0),n.addEventListener(O,x);const k=window.setTimeout(()=>{n.addEventListener("pointerdown",E)},0);return()=>{window.clearTimeout(k),n.removeEventListener("pointerdown",E),n.removeEventListener("click",m.current);for(const O of _)n.removeEventListener(O,w,!0),n.removeEventListener(O,x)}},[n,l,r,i,a,s]),{onPointerDownCapture:qn(()=>u.current=!0,"onPointerDownCapture")}}qn(Kz,"usePointerDownOutside");function qz(e,t=globalThis==null?void 0:globalThis.document){const n=Zv(e),r=b.useRef(!1);return b.useEffect(()=>{const i=qn(a=>{a.target&&!r.current&&AS(lie,n,{originalEvent:a},{discrete:!1})},"handleFocus");return t.addEventListener("focusin",i),()=>t.removeEventListener("focusin",i)},[t,n]),{onFocusCapture:qn(()=>r.current=!0,"onFocusCapture"),onBlurCapture:qn(()=>r.current=!1,"onBlurCapture")}}qn(qz,"useFocusOutside");function d1(){const e=new CustomEvent(u1);document.dispatchEvent(e)}qn(d1,"dispatchUpdate");function AS(e,t,n,{discrete:r}){const i=n.originalEvent.target,a=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?Fz(i,a):i.dispatchEvent(a)}qn(AS,"handleAndDispatchCustomEvent");var fie=Object.defineProperty,kS=(e,t)=>fie(e,"name",{value:t,configurable:!0}),Tp=0,da=null;function hie(e){return OS(),e.children}kS(hie,"FocusGuards");function OS(){b.useEffect(()=>{da||(da={start:f1(),end:f1()});const{start:e,end:t}=da;return document.body.firstElementChild!==e&&document.body.insertAdjacentElement("afterbegin",e),document.body.lastElementChild!==t&&document.body.insertAdjacentElement("beforeend",t),Tp++,()=>{Tp===1&&(da==null||da.start.remove(),da==null||da.end.remove(),da=null),Tp=Math.max(0,Tp-1)}},[])}kS(OS,"useFocusGuards");function f1(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}kS(f1,"createFocusGuard");var mie=Object.defineProperty,pie=(e,t)=>mie(e,"name",{value:t,configurable:!0});function h1(e){const t=b.useRef(e);return b.useEffect(()=>{t.current=e}),b.useMemo(()=>((...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)}),[])}pie(h1,"useCallbackRef");var gie=Object.defineProperty,xr=(e,t)=>gie(e,"name",{value:t,configurable:!0}),zx="focusScope.autoFocusOnMount",$x="focusScope.autoFocusOnUnmount",FM={bubbles:!1,cancelable:!0},vie=b.forwardRef(xr(function(t,n){const{loop:r=!1,trapped:i=!1,onMountAutoFocus:a,onUnmountAutoFocus:s,...l}=t,[u,d]=b.useState(null),h=h1(a),m=h1(s),p=b.useRef(null),g=ad(n,d),w=b.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;b.useEffect(()=>{if(i){let E=function(N){if(w.paused||!u)return;const C=N.target;u.contains(C)?p.current=C:uo(p.current,{select:!0})},_=function(N){if(w.paused||!u)return;const C=N.relatedTarget;C!==null&&(u.contains(C)||uo(p.current,{select:!0}))},k=function(N){if(document.activeElement===document.body)for(const T of N)T.removedNodes.length>0&&uo(u)};xr(E,"handleFocusIn"),xr(_,"handleFocusOut"),xr(k,"handleMutations"),document.addEventListener("focusin",E),document.addEventListener("focusout",_);const O=new MutationObserver(k);return u&&O.observe(u,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",E),document.removeEventListener("focusout",_),O.disconnect()}}},[i,u,w.paused]),b.useEffect(()=>{if(u){HM.add(w);const E=document.activeElement;if(!u.contains(E)){const k=new CustomEvent(zx,FM);u.addEventListener(zx,h),u.dispatchEvent(k),k.defaultPrevented||(Gz(Zz(NS(u)),{select:!0}),document.activeElement===E&&uo(u))}return()=>{u.removeEventListener(zx,h),setTimeout(()=>{const k=new CustomEvent($x,FM);u.addEventListener($x,m),u.dispatchEvent(k),k.defaultPrevented||uo(E??document.body,{select:!0}),u.removeEventListener($x,m),HM.remove(w)},0)}}},[u,h,m,w]);const x=b.useCallback(E=>{if(!r&&!i||w.paused)return;const _=E.key==="Tab"&&!E.altKey&&!E.ctrlKey&&!E.metaKey,k=document.activeElement;if(_&&k){const O=E.currentTarget,[N,C]=Vz(O);N&&C?!E.shiftKey&&k===C?(E.preventDefault(),r&&uo(N,{select:!0})):E.shiftKey&&k===N&&(E.preventDefault(),r&&uo(C,{select:!0})):k===O&&E.preventDefault()}},[r,i,w.paused]);return y.jsx(Xv.div,{tabIndex:-1,...l,ref:g,onKeyDown:x})},"FocusScope"));function Gz(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(uo(r,{select:t}),document.activeElement!==n)return}xr(Gz,"focusFirst");function Vz(e){const t=NS(e),n=m1(t,e),r=m1(t.reverse(),e);return[n,r]}xr(Vz,"getTabbableEdges");function NS(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:xr(r=>{const i=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||i?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP},"acceptNode")});for(;n.nextNode();)t.push(n.currentNode);return t}xr(NS,"getTabbableCandidates");function m1(e,t){const n=typeof t.checkVisibility=="function"&&t.checkVisibility({checkVisibilityCSS:!0});for(const r of e)if(!(n?!r.checkVisibility({checkVisibilityCSS:!0}):Wz(r,{upTo:t})))return r}xr(m1,"findVisible");function Wz(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}xr(Wz,"isHidden");function Yz(e){return e instanceof HTMLInputElement&&"select"in e}xr(Yz,"isSelectableInput");function uo(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&Yz(e)&&t&&e.select()}}xr(uo,"focus");var HM=Xz();function Xz(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=p1(e,t),e.unshift(t)},remove(t){var n;e=p1(e,t),(n=e[0])==null||n.resume()}}}xr(Xz,"createFocusScopesStack");function p1(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}xr(p1,"arrayRemove");function Zz(e){return e.filter(t=>t.tagName!=="A")}xr(Zz,"removeLinks");var yie=globalThis!=null&&globalThis.document?b.useLayoutEffect:()=>{},bie=Object.defineProperty,xie=(e,t)=>bie(e,"name",{value:t,configurable:!0}),wie=ja[" useId ".trim().toString()]||(()=>{}),Eie=0;function Qz(e){const[t,n]=b.useState(wie());return yie(()=>{e||n(r=>r??String(Eie++))},[e]),e||(t?`radix-${t}`:"")}xie(Qz,"useId");const Sie=["top","right","bottom","left"],Us=Math.min,xo=Math.max,Dg=Math.round,Mp=Math.floor,wo=e=>({x:e,y:e}),_ie={left:"right",right:"left",bottom:"top",top:"bottom"};function Jz(e,t,n){return xo(e,Us(t,n))}function Co(e,t){return typeof e=="function"?e(t):e}function Fs(e){return e.split("-")[0]}function od(e){return e.split("-")[1]}function CS(e){return e==="x"?"y":"x"}function TS(e){return e==="y"?"height":"width"}function wa(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function MS(e){return CS(wa(e))}function Aie(e,t,n){n===void 0&&(n=!1);const r=od(e),i=MS(e),a=TS(i);let s=i==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[a]>t.floating[a]&&(s=jg(s)),[s,jg(s)]}function kie(e){const t=jg(e);return[g1(e),t,g1(t)]}function g1(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const KM=["left","right"],qM=["right","left"],Oie=["top","bottom"],Nie=["bottom","top"];function Cie(e,t,n){switch(e){case"top":case"bottom":return n?t?qM:KM:t?KM:qM;case"left":case"right":return t?Oie:Nie;default:return[]}}function Tie(e,t,n,r){const i=od(e);let a=Cie(Fs(e),n==="start",r);return i&&(a=a.map(s=>s+"-"+i),t&&(a=a.concat(a.map(g1)))),a}function jg(e){const t=Fs(e);return _ie[t]+e.slice(t.length)}function Mie(e){var t,n,r,i;return{top:(t=e.top)!=null?t:0,right:(n=e.right)!=null?n:0,bottom:(r=e.bottom)!=null?r:0,left:(i=e.left)!=null?i:0}}function e$(e){return typeof e!="number"?Mie(e):{top:e,right:e,bottom:e,left:e}}function Lg(e){const{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function GM(e,t,n){let{reference:r,floating:i}=e;const a=wa(t),s=MS(t),l=TS(s),u=Fs(t),d=a==="y",h=r.x+r.width/2-i.width/2,m=r.y+r.height/2-i.height/2,p=r[l]/2-i[l]/2;let g;switch(u){case"top":g={x:h,y:r.y-i.height};break;case"bottom":g={x:h,y:r.y+r.height};break;case"right":g={x:r.x+r.width,y:m};break;case"left":g={x:r.x-i.width,y:m};break;default:g={x:r.x,y:r.y}}const w=od(t);return w&&(g[s]+=p*(w==="end"?1:-1)*(n&&d?-1:1)),g}async function Iie(e,t){var n;t===void 0&&(t={});const{x:r,y:i,platform:a,rects:s,elements:l,strategy:u}=e,{boundary:d="clippingAncestors",rootBoundary:h="viewport",elementContext:m="floating",altBoundary:p=!1,padding:g=0}=Co(t,e),w=e$(g),E=l[p?m==="floating"?"reference":"floating":m],_=Lg(await a.getClippingRect({element:(n=await(a.isElement==null?void 0:a.isElement(E)))==null||n?E:E.contextElement||await(a.getDocumentElement==null?void 0:a.getDocumentElement(l.floating)),boundary:d,rootBoundary:h,strategy:u})),k=m==="floating"?{x:r,y:i,width:s.floating.width,height:s.floating.height}:s.reference,O=await(a.getOffsetParent==null?void 0:a.getOffsetParent(l.floating)),N=await(a.isElement==null?void 0:a.isElement(O))&&await(a.getScale==null?void 0:a.getScale(O))||{x:1,y:1},C=Lg(a.convertOffsetParentRelativeRectToViewportRelativeRect?await a.convertOffsetParentRelativeRectToViewportRelativeRect({elements:l,rect:k,offsetParent:O,strategy:u}):k);return{top:(_.top-C.top+w.top)/N.y,bottom:(C.bottom-_.bottom+w.bottom)/N.y,left:(_.left-C.left+w.left)/N.x,right:(C.right-_.right+w.right)/N.x}}const Rie=50,Pie=async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:a=[],platform:s}=n,l=s.detectOverflow?s:{...s,detectOverflow:Iie},u=await(s.isRTL==null?void 0:s.isRTL(t));let d=await s.getElementRects({reference:e,floating:t,strategy:i}),{x:h,y:m}=GM(d,r,u),p=r,g=0;const w={};for(let x=0;x<a.length;x++){const E=a[x];if(!E)continue;const{name:_,fn:k}=E,{x:O,y:N,data:C,reset:T}=await k({x:h,y:m,initialPlacement:r,placement:p,strategy:i,middlewareData:w,rects:d,platform:l,elements:{reference:e,floating:t}});h=O??h,m=N??m,w[_]={...w[_],...C},T&&g<Rie&&(g++,typeof T=="object"&&(T.placement&&(p=T.placement),T.rects&&(d=T.rects===!0?await s.getElementRects({reference:e,floating:t,strategy:i}):T.rects),{x:h,y:m}=GM(d,p,u)),x=-1)}return{x:h,y:m,placement:p,strategy:i,middlewareData:w}},Die=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:i,rects:a,platform:s,elements:l,middlewareData:u}=t,{element:d,padding:h=0}=Co(e,t)||{};if(d==null)return{};const m=e$(h),p={x:n,y:r},g=MS(i),w=TS(g),x=await s.getDimensions(d),E=g==="y",_=E?"top":"left",k=E?"bottom":"right",O=E?"clientHeight":"clientWidth",N=a.reference[w]+a.reference[g]-p[g]-a.floating[w],C=p[g]-a.reference[g],T=await(s.getOffsetParent==null?void 0:s.getOffsetParent(d));let M=T?T[O]:0;(!M||!await(s.isElement==null?void 0:s.isElement(T)))&&(M=l.floating[O]||a.floating[w]);const D=N/2-C/2,j=M/2-x[w]/2-1,R=Us(m[_],j),H=Us(m[k],j),P=M-x[w]-H,G=M/2-x[w]/2+D,q=Jz(R,G,P),X=!u.arrow&&od(i)!=null&&G!==q&&a.reference[w]/2-(G<R?R:H)-x[w]/2<0,U=X?G<R?G-R:G-P:0;return{[g]:p[g]+U,data:{[g]:q,centerOffset:G-q-U,...X&&{alignmentOffset:U}},reset:X}}}),jie=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:i,middlewareData:a,rects:s,initialPlacement:l,platform:u,elements:d}=t,{mainAxis:h=!0,crossAxis:m=!0,fallbackPlacements:p,fallbackStrategy:g="bestFit",fallbackAxisSideDirection:w="none",flipAlignment:x=!0,...E}=Co(e,t);if((n=a.arrow)!=null&&n.alignmentOffset)return{};const _=Fs(i),k=wa(l),O=Fs(l)===l,N=await(u.isRTL==null?void 0:u.isRTL(d.floating)),C=p||(O||!x?[jg(l)]:kie(l)),T=w!=="none";!p&&T&&C.push(...Tie(l,x,w,N));const M=[l,...C],D=await u.detectOverflow(t,E),j=[];let R=((r=a.flip)==null?void 0:r.overflows)||[];if(h&&j.push(D[_]),m){const q=Aie(i,s,N);j.push(D[q[0]],D[q[1]])}if(R=[...R,{placement:i,overflows:j}],!j.every(q=>q<=0)){var H,P;const q=(((H=a.flip)==null?void 0:H.index)||0)+1,X=M[q];if(X&&(!(m==="alignment"?k!==wa(X):!1)||R.every(F=>wa(F.placement)===k?F.overflows[0]>0:!0)))return{data:{index:q,overflows:R},reset:{placement:X}};let U=(P=R.filter(K=>K.overflows[0]<=0).sort((K,F)=>K.overflows[1]-F.overflows[1])[0])==null?void 0:P.placement;if(!U)switch(g){case"bestFit":{var G;const K=(G=R.filter(F=>{if(T){const V=wa(F.placement);return V===k||V==="y"}return!0}).map(F=>[F.placement,F.overflows.filter(V=>V>0).reduce((V,$)=>V+$,0)]).sort((F,V)=>F[1]-V[1])[0])==null?void 0:G[0];K&&(U=K);break}case"initialPlacement":U=l;break}if(i!==U)return{reset:{placement:U}}}return{}}}};function VM(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function WM(e){return Sie.some(t=>e[t]>=0)}const Lie=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n,platform:r}=t,{strategy:i="referenceHidden",...a}=Co(e,t);switch(i){case"referenceHidden":{const s=await r.detectOverflow(t,{...a,elementContext:"reference"}),l=VM(s,n.reference);return{data:{referenceHiddenOffsets:l,referenceHidden:WM(l)}}}case"escaped":{const s=await r.detectOverflow(t,{...a,altBoundary:!0}),l=VM(s,n.floating);return{data:{escapedOffsets:l,escaped:WM(l)}}}default:return{}}}}},t$=new Set(["left","top"]);async function zie(e,t){const{placement:n,platform:r,elements:i}=e,a=await(r.isRTL==null?void 0:r.isRTL(i.floating)),s=Fs(n),l=od(n),u=wa(n)==="y",d=t$.has(s)?-1:1,h=a&&u?-1:1,m=Co(t,e);let{mainAxis:p,crossAxis:g,alignmentAxis:w}=typeof m=="number"?{mainAxis:m,crossAxis:0,alignmentAxis:null}:{mainAxis:m.mainAxis||0,crossAxis:m.crossAxis||0,alignmentAxis:m.alignmentAxis};return l&&typeof w=="number"&&(g=l==="end"?w*-1:w),u?{x:g*h,y:p*d}:{x:p*d,y:g*h}}const $ie=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:i,y:a,placement:s,middlewareData:l}=t,u=await zie(t,e);return s===((n=l.offset)==null?void 0:n.placement)&&(r=l.arrow)!=null&&r.alignmentOffset?{}:{x:i+u.x,y:a+u.y,data:{...u,placement:s}}}}},Bie=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i,platform:a}=t,{mainAxis:s=!0,crossAxis:l=!1,limiter:u={fn:k=>{let{x:O,y:N}=k;return{x:O,y:N}}},...d}=Co(e,t),h={x:n,y:r},m=await a.detectOverflow(t,d),p=wa(i),g=CS(p);let w=h[g],x=h[p];const E=(k,O)=>Jz(O+m[k==="y"?"top":"left"],O,O-m[k==="y"?"bottom":"right"]);s&&(w=E(g,w)),l&&(x=E(p,x));const _=u.fn({...t,[g]:w,[p]:x});return{..._,data:{x:_.x-n,y:_.y-r,enabled:{[g]:s,[p]:l}}}}}},Uie=function(e){return e===void 0&&(e={}),{options:e,fn(t){var n,r;const{x:i,y:a,placement:s,rects:l,middlewareData:u}=t,{offset:d=0,mainAxis:h=!0,crossAxis:m=!0}=Co(e,t),p={x:i,y:a},g=wa(s),w=CS(g);let x=p[w],E=p[g];const _=Co(d,t),k=typeof _=="number"?{mainAxis:_,crossAxis:0}:{mainAxis:(n=_.mainAxis)!=null?n:0,crossAxis:(r=_.crossAxis)!=null?r:0};if(h){const C=w==="y"?"height":"width",T=l.reference[w]-l.floating[C]+k.mainAxis,M=l.reference[w]+l.reference[C]-k.mainAxis;x<T?x=T:x>M&&(x=M)}if(m){var O,N;const C=w==="y"?"width":"height",T=t$.has(Fs(s)),M=l.reference[g]-l.floating[C]+(T&&((O=u.offset)==null?void 0:O[g])||0)+(T?0:k.crossAxis),D=l.reference[g]+l.reference[C]+(T?0:((N=u.offset)==null?void 0:N[g])||0)-(T?k.crossAxis:0);E<M?E=M:E>D&&(E=D)}return{[w]:x,[g]:E}}}},Fie=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:i,elements:a}=t,{apply:s=()=>{},...l}=Co(e,t),u=await i.detectOverflow(t,l),d=Fs(n),h=od(n),m=wa(n)==="y",{width:p,height:g}=r.floating;let w,x;d==="top"||d==="bottom"?(w=d,x=h===(await(i.isRTL==null?void 0:i.isRTL(a.floating))?"start":"end")?"left":"right"):(x=d,w=h==="end"?"top":"bottom");const E=g-u.top-u.bottom,_=p-u.left-u.right,k=Us(g-u[w],E),O=Us(p-u[x],_),N=t.middlewareData.shift,C=!N;let T=k,M=O;N!=null&&N.enabled.x&&(M=_),N!=null&&N.enabled.y&&(T=E),C&&!h&&(m?M=p-2*xo(u.left,u.right):T=g-2*xo(u.top,u.bottom)),await s({...t,availableWidth:M,availableHeight:T});const D=await i.getDimensions(a.floating);return p!==D.width||g!==D.height?{reset:{rects:!0}}:{}}}};function Qv(){return typeof window<"u"}function sd(e){return n$(e)?(e.nodeName||"").toLowerCase():"#document"}function Ur(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function jo(e){var t;return(t=(n$(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function n$(e){return Qv()?e instanceof Node||e instanceof Ur(e).Node:!1}function Ca(e){return Qv()?e instanceof Element||e instanceof Ur(e).Element:!1}function Qs(e){return Qv()?e instanceof HTMLElement||e instanceof Ur(e).HTMLElement:!1}function YM(e){return!Qv()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Ur(e).ShadowRoot}function Jv(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=Ta(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!=="inline"&&i!=="contents"}function Hie(e){return/^(table|td|th)$/.test(sd(e))}function ey(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}const Kie=/transform|translate|scale|rotate|perspective|filter/,qie=/paint|layout|strict|content/,_l=e=>!!e&&e!=="none";let Bx;function IS(e){const t=Ca(e)?Ta(e):e;return _l(t.transform)||_l(t.translate)||_l(t.scale)||_l(t.rotate)||_l(t.perspective)||!RS()&&(_l(t.backdropFilter)||_l(t.filter))||Kie.test(t.willChange||"")||qie.test(t.contain||"")}function Gie(e){let t=ec(e);for(;Qs(t)&&!nh(t);){if(IS(t))return t;if(ey(t))return null;t=ec(t)}return null}function RS(){return Bx==null&&(Bx=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Bx}function nh(e){return/^(html|body|#document)$/.test(sd(e))}function Ta(e){return Ur(e).getComputedStyle(e)}function ty(e){return Ca(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function ec(e){if(sd(e)==="html")return e;const t=e.assignedSlot||e.parentNode||YM(e)&&e.host||jo(e);return YM(t)?t.host:t}function r$(e){const t=ec(e);return nh(t)?(e.ownerDocument||e).body:Qs(t)&&Jv(t)?t:r$(t)}function rh(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const i=r$(e),a=i===((r=e.ownerDocument)==null?void 0:r.body),s=Ur(i);if(a){const l=v1(s);return t.concat(s,s.visualViewport||[],Jv(i)?i:[],l&&n?rh(l):[])}else return t.concat(i,rh(i,[],n))}function v1(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function i$(e){const t=Ta(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=Qs(e),a=i?e.offsetWidth:n,s=i?e.offsetHeight:r,l=Dg(n)!==a||Dg(r)!==s;return l&&(n=a,r=s),{width:n,height:r,$:l}}function PS(e){return Ca(e)?e:e.contextElement}function Tu(e){const t=PS(e);if(!Qs(t))return wo(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:a}=i$(t);let s=(a?Dg(n.width):n.width)/r,l=(a?Dg(n.height):n.height)/i;return(!s||!Number.isFinite(s))&&(s=1),(!l||!Number.isFinite(l))&&(l=1),{x:s,y:l}}const Vie=wo(0);function a$(e){const t=Ur(e);return!RS()||!t.visualViewport?Vie:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function Wie(e,t,n){return t===void 0&&(t=!1),!!n&&t&&n===Ur(e)}function tc(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const i=e.getBoundingClientRect(),a=PS(e);let s=wo(1);t&&(r?Ca(r)&&(s=Tu(r)):s=Tu(e));const l=Wie(a,n,r)?a$(a):wo(0);let u=(i.left+l.x)/s.x,d=(i.top+l.y)/s.y,h=i.width/s.x,m=i.height/s.y;if(a&&r){const p=Ur(a),g=Ca(r)?Ur(r):r;let w=p,x=v1(w);for(;x&&g!==w;){const E=Tu(x),_=x.getBoundingClientRect(),k=Ta(x),O=_.left+(x.clientLeft+parseFloat(k.paddingLeft))*E.x,N=_.top+(x.clientTop+parseFloat(k.paddingTop))*E.y;u*=E.x,d*=E.y,h*=E.x,m*=E.y,u+=O,d+=N,w=Ur(x),x=v1(w)}}return Lg({width:h,height:m,x:u,y:d})}function ny(e,t){const n=ty(e).scrollLeft;return t?t.left+n:tc(jo(e)).left+n}function o$(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-ny(e,n),i=n.top+t.scrollTop;return{x:r,y:i}}function Yie(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const a=i==="fixed",s=jo(r),l=t?ey(t.floating):!1;if(r===s||l&&a)return n;let u={scrollLeft:0,scrollTop:0},d=wo(1);const h=wo(0),m=Qs(r);if((m||!a)&&((sd(r)!=="body"||Jv(s))&&(u=ty(r)),m)){const g=tc(r);d=Tu(r),h.x=g.x+r.clientLeft,h.y=g.y+r.clientTop}const p=s&&!m&&!a?o$(s,u):wo(0);return{width:n.width*d.x,height:n.height*d.y,x:n.x*d.x-u.scrollLeft*d.x+h.x+p.x,y:n.y*d.y-u.scrollTop*d.y+h.y+p.y}}function Xie(e){return e.getClientRects?Array.from(e.getClientRects()):[]}function Zie(e){const t=ty(e),n=e.ownerDocument.body,r=xo(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=xo(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight);let a=-t.scrollLeft+ny(e);const s=-t.scrollTop;return Ta(n).direction==="rtl"&&(a+=xo(e.clientWidth,n.clientWidth)-r),{width:r,height:i,x:a,y:s}}const Qie=25;function Jie(e,t,n){n===void 0&&(n="viewport");const r=n==="layoutViewport",i=Ur(e),a=jo(e),s=i.visualViewport;let l=a.clientWidth,u=a.clientHeight,d=0,h=0;if(s){const p=!RS()||t==="fixed";r?p||(d=-s.offsetLeft,h=-s.offsetTop):(l=s.width,u=s.height,p&&(d=s.offsetLeft,h=s.offsetTop))}if(ny(a)<=0){const p=a.ownerDocument,g=p.body,w=getComputedStyle(g),x=p.compatMode==="CSS1Compat"&&parseFloat(w.marginLeft)+parseFloat(w.marginRight)||0,E=Math.abs(a.clientWidth-g.clientWidth-x),_=getComputedStyle(a).scrollbarGutter==="stable both-edges"?E/2:E;_<=Qie&&(l-=_)}return{width:l,height:u,x:d,y:h}}function eae(e,t){const n=tc(e,!0,t==="fixed"),r=n.top+e.clientTop,i=n.left+e.clientLeft,a=Tu(e),s=e.clientWidth*a.x,l=e.clientHeight*a.y,u=i*a.x,d=r*a.y;return{width:s,height:l,x:u,y:d}}function XM(e,t,n){let r;if(t==="viewport"||t==="layoutViewport")r=Jie(e,n,t);else if(t==="document")r=Zie(jo(e));else if(Ca(t))r=eae(t,n);else{const i=a$(e);r={x:t.x-i.x,y:t.y-i.y,width:t.width,height:t.height}}return Lg(r)}function tae(e,t){const n=t.get(e);if(n)return n;let r=rh(e,[],!1).filter(l=>Ca(l)&&sd(l)!=="body"),i=null;const a=Ta(e).position==="fixed";let s=a?ec(e):e;for(;Ca(s)&&!nh(s);){const l=Ta(s),u=IS(s),d=i?i.position:a?"fixed":"";!u&&(d==="fixed"||d==="absolute"&&l.position==="static")?r=r.filter(m=>m!==s):i=l,s=ec(s)}return t.set(e,r),r}function nae(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const s=[...n==="clippingAncestors"?ey(t)?[]:tae(t,this._c):[].concat(n),r],l=XM(t,s[0],i);let u=l.top,d=l.right,h=l.bottom,m=l.left;for(let p=1;p<s.length;p++){const g=XM(t,s[p],i);u=xo(g.top,u),d=Us(g.right,d),h=Us(g.bottom,h),m=xo(g.left,m)}return{width:d-m,height:h-u,x:m,y:u}}function rae(e){const{width:t,height:n}=i$(e);return{width:t,height:n}}function iae(e,t,n){const r=Qs(t),i=jo(t),a=n==="fixed",s=tc(e,!0,a,t);let l={scrollLeft:0,scrollTop:0};const u=wo(0);if((r||!a)&&((sd(t)!=="body"||Jv(i))&&(l=ty(t)),r)){const p=tc(t,!0,a,t);u.x=p.x+t.clientLeft,u.y=p.y+t.clientTop}!r&&i&&(u.x=ny(i));const d=i&&!r&&!a?o$(i,l):wo(0),h=s.left+l.scrollLeft-u.x-d.x,m=s.top+l.scrollTop-u.y-d.y;return{x:h,y:m,width:s.width,height:s.height}}function Ux(e){return Ta(e).position==="static"}function ZM(e,t){if(!Qs(e)||Ta(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return jo(e)===n&&(n=n.ownerDocument.body),n}function s$(e,t){const n=Ur(e);if(ey(e))return n;if(!Qs(e)){let i=ec(e);for(;i&&!nh(i);){if(Ca(i)&&!Ux(i))return i;i=ec(i)}return n}let r=ZM(e,t);for(;r&&Hie(r)&&Ux(r);)r=ZM(r,t);return r&&nh(r)&&Ux(r)&&!IS(r)?n:r||Gie(e)||n}const aae=async function(e){const t=this.getOffsetParent||s$,n=this.getDimensions,r=await n(e.floating);return{reference:iae(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function oae(e){return Ta(e).direction==="rtl"}const sae={convertOffsetParentRelativeRectToViewportRelativeRect:Yie,getDocumentElement:jo,getClippingRect:nae,getOffsetParent:s$,getElementRects:aae,getClientRects:Xie,getDimensions:rae,getScale:Tu,isElement:Ca,isRTL:oae};function l$(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function lae(e,t,n){let r=null,i;const a=jo(e);function s(){var h;clearTimeout(i),(h=r)==null||h.disconnect(),r=null}function l(h,m){h===void 0&&(h=!1),m===void 0&&(m=1),s();const p=e.getBoundingClientRect(),{left:g,top:w,width:x,height:E}=p;if(h||t(),!x||!E)return;const _=Mp(w),k=Mp(a.clientWidth-(g+x)),O=Mp(a.clientHeight-(w+E)),N=Mp(g),T={rootMargin:-_+"px "+-k+"px "+-O+"px "+-N+"px",threshold:xo(0,Us(1,m))||1};let M=!0;function D(j){const R=j[0].intersectionRatio;if(!l$(p,e.getBoundingClientRect()))return l();if(R!==m){if(!M)return l();R?l(!1,R):i=setTimeout(()=>{l(!1,1e-7)},1e3)}M=!1}try{r=new IntersectionObserver(D,{...T,root:a.ownerDocument})}catch{r=new IntersectionObserver(D,T)}r.observe(e)}const u=Ur(e),d=()=>l(n);return u.addEventListener("resize",d),l(!0),()=>{u.removeEventListener("resize",d),s()}}function cae(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:i=!0,ancestorResize:a=!0,elementResize:s=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:u=!1}=r,d=PS(e),h=i||a?[...d?rh(d):[],...t?rh(t):[]]:[];h.forEach(_=>{i&&_.addEventListener("scroll",n),a&&_.addEventListener("resize",n)});const m=d&&l?lae(d,n,a):null;let p=-1,g=null;s&&(g=new ResizeObserver(_=>{let[k]=_;k&&k.target===d&&g&&t&&(g.unobserve(t),cancelAnimationFrame(p),p=requestAnimationFrame(()=>{var O;(O=g)==null||O.observe(t)})),n()}),d&&!u&&g.observe(d),t&&g.observe(t));let w,x=u?tc(e):null;u&&E();function E(){const _=tc(e);x&&!l$(x,_)&&n(),x=_,w=requestAnimationFrame(E)}return n(),()=>{var _;h.forEach(k=>{i&&k.removeEventListener("scroll",n),a&&k.removeEventListener("resize",n)}),m==null||m(),(_=g)==null||_.disconnect(),g=null,u&&cancelAnimationFrame(w)}}const uae=$ie,dae=Bie,fae=jie,hae=Fie,mae=Lie,QM=Die,pae=Uie,gae=(e,t,n)=>{const r=new Map,i=n??{},a={...sae,...i.platform,_c:r};return Pie(e,t,{...i,platform:a})};var vae=typeof document<"u",yae=function(){},og=vae?b.useLayoutEffect:yae;function zg(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,i;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!zg(e[r],t[r]))return!1;return!0}if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,i[r]))return!1;for(r=n;r--!==0;){const a=i[r];if(!(a==="_owner"&&e.$$typeof)&&!zg(e[a],t[a]))return!1}return!0}return e!==e&&t!==t}function c$(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function JM(e,t){const n=c$(e);return Math.round(t*n)/n}function Fx(e){const t=b.useRef(e);return og(()=>{t.current=e}),t}function bae(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:i,elements:{reference:a,floating:s}={},transform:l=!0,whileElementsMounted:u,open:d}=e,[h,m]=b.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[p,g]=b.useState(r);zg(p,r)||g(r);const[w,x]=b.useState(null),[E,_]=b.useState(null),k=b.useCallback(F=>{F!==T.current&&(T.current=F,x(F))},[]),O=b.useCallback(F=>{F!==M.current&&(M.current=F,_(F))},[]),N=a||w,C=s||E,T=b.useRef(null),M=b.useRef(null),D=b.useRef(h),j=u!=null,R=Fx(u),H=Fx(i),P=Fx(d),G=b.useCallback(()=>{if(!T.current||!M.current)return;const F={placement:t,strategy:n,middleware:p};H.current&&(F.platform=H.current),gae(T.current,M.current,F).then(V=>{const $={...V,isPositioned:P.current!==!1};q.current&&!zg(D.current,$)&&(D.current=$,La.flushSync(()=>{m($)}))})},[p,t,n,H,P]);og(()=>{d===!1&&D.current.isPositioned&&(D.current.isPositioned=!1,m(F=>({...F,isPositioned:!1})))},[d]);const q=b.useRef(!1);og(()=>(q.current=!0,()=>{q.current=!1}),[]),og(()=>{if(N&&(T.current=N),C&&(M.current=C),N&&C){if(R.current)return R.current(N,C,G);G()}},[N,C,G,R,j]);const X=b.useMemo(()=>({reference:T,floating:M,setReference:k,setFloating:O}),[k,O]),U=b.useMemo(()=>({reference:N,floating:C}),[N,C]),K=b.useMemo(()=>{const F={position:n,left:0,top:0};if(!U.floating)return F;const V=JM(U.floating,h.x),$=JM(U.floating,h.y);return l?{...F,transform:"translate("+V+"px, "+$+"px)",...c$(U.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:V,top:$}},[n,l,U.floating,h.x,h.y]);return b.useMemo(()=>({...h,update:G,refs:X,elements:U,floatingStyles:K}),[h,G,X,U,K])}const xae=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:i}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?QM({element:r.current,padding:i}).fn(n):{}:r?QM({element:r,padding:i}).fn(n):{}}}},wae=(e,t)=>{const n=uae(e);return{name:n.name,fn:n.fn,options:[e,t]}},Eae=(e,t)=>{const n=dae(e);return{name:n.name,fn:n.fn,options:[e,t]}},Sae=(e,t)=>({fn:pae(e).fn,options:[e,t]}),_ae=(e,t)=>{const n=fae(e);return{name:n.name,fn:n.fn,options:[e,t]}},Aae=(e,t)=>{const n=hae(e);return{name:n.name,fn:n.fn,options:[e,t]}},kae=(e,t)=>{const n=mae(e);return{name:n.name,fn:n.fn,options:[e,t]}},Oae=(e,t)=>{const n=xae(e);return{name:n.name,fn:n.fn,options:[e,t]}};var Nae=Object.defineProperty,DS=(e,t)=>Nae(e,"name",{value:t,configurable:!0});function y1(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}DS(y1,"setRef");function u$(...e){return t=>{let n=!1;const r=e.map(i=>{const a=y1(i,t);return!n&&typeof a=="function"&&(n=!0),a});if(n)return()=>{for(let i=0;i<r.length;i++){const a=r[i];typeof a=="function"?a():y1(e[i],null)}}}}DS(u$,"composeRefs");function ry(...e){return b.useCallback(u$(...e),e)}DS(ry,"useComposedRefs");var Cae=Object.defineProperty,Ci=(e,t)=>Cae(e,"name",{value:t,configurable:!0});function Tae(e,t){const n=b.createContext(t);n.displayName=e+"Context";const r=Ci(a=>{const{children:s,...l}=a,u=b.useMemo(()=>l,Object.values(l));return y.jsx(n.Provider,{value:u,children:s})},"Provider");r.displayName=e+"Provider";function i(a,s={}){const{optional:l=!1}=s,u=b.useContext(n);if(u)return u;if(t!==void 0)return t;if(!l)throw new Error(`\`${a}\` must be used within \`${e}\``)}return Ci(i,"useContext"),[r,i]}Ci(Tae,"createContext");function d$(e,t=[]){let n=[];function r(a,s){const l=b.createContext(s);l.displayName=a+"Context";const u=n.length;n=[...n,s];const d=Ci(m=>{var _;const{scope:p,children:g,...w}=m,x=((_=p==null?void 0:p[e])==null?void 0:_[u])||l,E=b.useMemo(()=>w,Object.values(w));return y.jsx(x.Provider,{value:E,children:g})},"Provider");d.displayName=a+"Provider";function h(m,p,g={}){var _;const{optional:w=!1}=g,x=((_=p==null?void 0:p[e])==null?void 0:_[u])||l,E=b.useContext(x);if(E)return E;if(s!==void 0)return s;if(!w)throw new Error(`\`${m}\` must be used within \`${a}\``)}return Ci(h,"useContext"),[d,h]}Ci(r,"createContext");const i=Ci(()=>{const a=n.map(s=>b.createContext(s));return Ci(function(l){const u=(l==null?void 0:l[e])||a;return b.useMemo(()=>({[`__scope${e}`]:{...l,[e]:u}}),[l,u])},"useScope")},"createScope");return i.scopeName=e,[r,f$(i,...t)]}Ci(d$,"createContextScope");function f$(...e){const t=e[0];if(e.length===1)return t;const n=Ci(()=>{const r=e.map(i=>({useScope:i(),scopeName:i.scopeName}));return Ci(function(a){const s=r.reduce((l,{useScope:u,scopeName:d})=>{const m=u(a)[`__scope${d}`];return{...l,...m}},{});return b.useMemo(()=>({[`__scope${t.scopeName}`]:s}),[s])},"useComposedScopes")},"createScope");return n.scopeName=t.scopeName,n}Ci(f$,"composeContextScopes");var Mae=Object.defineProperty,ta=(e,t)=>Mae(e,"name",{value:t,configurable:!0});function h$(e){const t=b.forwardRef((n,r)=>{let{children:i,...a}=n,s=null,l=!1;const u=[];b1(i)&&typeof Ip=="function"&&(i=Ip(i._payload)),b.Children.forEach(i,p=>{var g;if(v$(p)){l=!0;const w=p;let x="child"in w.props?w.props.child:w.props.children;b1(x)&&typeof Ip=="function"&&(x=Ip(x._payload)),s=Rae(w,x),u.push((g=s==null?void 0:s.props)==null?void 0:g.children)}else u.push(p)}),s?s=b.cloneElement(s,void 0,u):!l&&b.Children.count(i)===1&&b.isValidElement(i)&&(s=i);const d=s?g$(s):void 0,h=ry(r,d);if(!s){if(i||i===0)throw new Error(l?jae(e):Dae(e));return i}const m=p$(a,s.props??{});return s.type!==b.Fragment&&(m.ref=r?h:d),b.cloneElement(s,m)});return t.displayName=`${e}.Slot`,t}ta(h$,"createSlot");var m$=Symbol.for("radix.slottable");function Iae(e){const t=ta(n=>"child"in n?n.children(n.child):n.children,"Slottable");return t.displayName=`${e}.Slottable`,t.__radixId=m$,t}ta(Iae,"createSlottable");var Rae=ta((e,t)=>{if("child"in e.props){const n=e.props.child;return b.isValidElement(n)?b.cloneElement(n,void 0,e.props.children(n.props.children)):null}return b.isValidElement(t)?t:null},"getSlottableElementFromSlottable");function p$(e,t){const n={...t};for(const r in t){const i=e[r],a=t[r];/^on[A-Z]/.test(r)?i&&a?n[r]=(...l)=>{const u=a(...l);return i(...l),u}:i&&(n[r]=i):r==="style"?n[r]={...i,...a}:r==="className"&&(n[r]=[i,a].filter(Boolean).join(" "))}return{...e,...n}}ta(p$,"mergeProps");function g$(e){var r,i;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(i=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:i.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}ta(g$,"getElementRef");function v$(e){return b.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===m$}ta(v$,"isSlottable");var Pae=Symbol.for("react.lazy");function b1(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===Pae&&"_payload"in e&&y$(e._payload)}ta(b1,"isLazyComponent");function y$(e){return typeof e=="object"&&e!==null&&"then"in e}ta(y$,"isPromiseLike");var Dae=ta(e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,"createSlotError"),jae=ta(e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,"createSlottableError"),Ip=ja[" use ".trim().toString()],Lae=Object.defineProperty,zae=(e,t)=>Lae(e,"name",{value:t,configurable:!0}),$ae=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],b$=$ae.reduce((e,t)=>{const n=h$(`Primitive.${t}`),r=b.forwardRef((i,a)=>{const{asChild:s,...l}=i,u=s?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),y.jsx(u,{...l,ref:a})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function Bae(e,t){e&&La.flushSync(()=>e.dispatchEvent(t))}zae(Bae,"dispatchDiscreteCustomEvent");var Uae=Object.defineProperty,Fae=(e,t)=>Uae(e,"name",{value:t,configurable:!0});function x$(e){const t=b.useRef(e);return b.useEffect(()=>{t.current=e}),b.useMemo(()=>((...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)}),[])}Fae(x$,"useCallbackRef");var Hx=globalThis!=null&&globalThis.document?b.useLayoutEffect:()=>{},Hae=globalThis!=null&&globalThis.document?b.useLayoutEffect:()=>{},Kae=Object.defineProperty,qae=(e,t)=>Kae(e,"name",{value:t,configurable:!0});function w$(e){const[t,n]=b.useState(void 0);return Hae(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(i=>{if(!Array.isArray(i)||!i.length)return;const a=i[0];let s,l;if("borderBoxSize"in a){const u=a.borderBoxSize,d=Array.isArray(u)?u[0]:u;s=d.inlineSize,l=d.blockSize}else s=e.offsetWidth,l=e.offsetHeight;n({width:s,height:l})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}qae(w$,"useSize");var Gae=Object.defineProperty,js=(e,t)=>Gae(e,"name",{value:t,configurable:!0}),E$="Popper",[S$,_$]=d$(E$),[Vae,A$]=S$(E$),Wae=js(e=>{const{__scopePopper:t,children:n}=e,[r,i]=b.useState(null),[a,s]=b.useState(void 0);return y.jsx(Vae,{scope:t,anchor:r,onAnchorChange:i,placementState:a,setPlacementState:s,children:n})},"Popper"),Yae="PopperAnchor",Xae=b.forwardRef(js(function(t,n){const{__scopePopper:r,virtualRef:i,...a}=t,s=A$(Yae,r),l=b.useRef(null),u=s.onAnchorChange,d=b.useCallback(x=>{l.current=x,x&&u(x)},[u]),h=ry(n,d),m=b.useRef(null);b.useEffect(()=>{if(!i)return;const x=m.current;m.current=i.current,x!==m.current&&u(m.current)});const p=s.placementState&&iy(s.placementState),g=p==null?void 0:p[0],w=p==null?void 0:p[1];return i?null:y.jsx(b$.div,{"data-radix-popper-side":g,"data-radix-popper-align":w,...a,ref:h})},"PopperAnchor")),k$="PopperContent",[Zae,sCe]=S$(k$),Qae=b.forwardRef(js(function(t,n){var fe,Ee,Te,de,nt,He,Ae;const{__scopePopper:r,side:i="bottom",sideOffset:a=0,align:s="center",alignOffset:l=0,arrowPadding:u=0,avoidCollisions:d=!0,collisionBoundary:h=[],collisionPadding:m=0,sticky:p="partial",hideWhenDetached:g=!1,updatePositionStrategy:w="optimized",onPlaced:x,...E}=t,_=A$(k$,r),[k,O]=b.useState(null),N=ry(n,O),[C,T]=b.useState(null),M=w$(C),D=(M==null?void 0:M.width)??0,j=(M==null?void 0:M.height)??0,R=i+(s!=="center"?"-"+s:""),H=typeof m=="number"?m:{top:0,right:0,bottom:0,left:0,...m},P=Array.isArray(h)?h:[h],G=P.length>0,q={padding:H,boundary:P.filter(O$),altBoundary:G},{refs:X,floatingStyles:U,placement:K,isPositioned:F,middlewareData:V}=bae({strategy:"fixed",placement:R,whileElementsMounted:js((...De)=>cae(...De,{animationFrame:w==="always"}),"whileElementsMounted"),elements:{reference:_.anchor},middleware:[wae({mainAxis:a+j,alignmentAxis:l}),d&&Eae({mainAxis:!0,crossAxis:!1,limiter:p==="partial"?Sae():void 0,...q}),d&&_ae({...q}),Aae({...q,apply:js(({elements:De,rects:Ht,availableWidth:un,availableHeight:Yn})=>{const{width:Or,height:ji}=Ht.reference,ir=De.floating.style;ir.setProperty("--radix-popper-available-width",`${un}px`),ir.setProperty("--radix-popper-available-height",`${Yn}px`),ir.setProperty("--radix-popper-anchor-width",`${Or}px`),ir.setProperty("--radix-popper-anchor-height",`${ji}px`)},"apply")}),C&&Oae({element:C,padding:u}),Jae({arrowWidth:D,arrowHeight:j}),g&&kae({strategy:"referenceHidden",...q,boundary:G?q.boundary:void 0})]}),$=_.setPlacementState;Hx(()=>($(K),()=>{$(void 0)}),[K,$]);const[L,W]=iy(K),z=x$(x);Hx(()=>{F&&(z==null||z())},[F,z]);const ie=(fe=V.arrow)==null?void 0:fe.x,he=(Ee=V.arrow)==null?void 0:Ee.y,ge=((Te=V.arrow)==null?void 0:Te.centerOffset)!==0,[Se,ze]=b.useState();return Hx(()=>{k&&ze(window.getComputedStyle(k).zIndex)},[k]),y.jsx("div",{ref:X.setFloating,"data-radix-popper-content-wrapper":"",style:{...U,transform:F?U.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Se,"--radix-popper-transform-origin":[(de=V.transformOrigin)==null?void 0:de.x,(nt=V.transformOrigin)==null?void 0:nt.y].join(" "),...((He=V.hide)==null?void 0:He.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:t.dir,children:y.jsx(Zae,{scope:r,placedSide:L,placedAlign:W,onArrowChange:T,arrowX:ie,arrowY:he,shouldHideArrow:ge,children:y.jsx(b$.div,{"data-side":L,"data-align":W,...E,ref:N,style:{...E.style,animation:F?(Ae=E.style)==null?void 0:Ae.animation:"none"}})})})},"PopperContent"));function O$(e){return e!==null}js(O$,"isNotNull");var Jae=js(e=>({name:"transformOrigin",options:e,fn(t){var E,_,k;const{placement:n,rects:r,middlewareData:i}=t,s=((E=i.arrow)==null?void 0:E.centerOffset)!==0,l=s?0:e.arrowWidth,u=s?0:e.arrowHeight,[d,h]=iy(n),m={start:"0%",center:"50%",end:"100%"}[h],p=(((_=i.arrow)==null?void 0:_.x)??0)+l/2,g=(((k=i.arrow)==null?void 0:k.y)??0)+u/2;let w="",x="";return d==="bottom"?(w=s?m:`${p}px`,x=`${-u}px`):d==="top"?(w=s?m:`${p}px`,x=`${r.floating.height+u}px`):d==="right"?(w=`${-u}px`,x=s?m:`${g}px`):d==="left"&&(w=`${r.floating.width+u}px`,x=s?m:`${g}px`),{data:{x:w,y:x}}}}),"transformOrigin");function iy(e){const[t,n="center"]=e.split("-");return[t,n]}js(iy,"getSideAndAlignFromPlacement");var eoe=Wae,toe=Xae,noe=Qae,roe=globalThis!=null&&globalThis.document?b.useLayoutEffect:()=>{},ioe=Object.defineProperty,aoe=(e,t)=>ioe(e,"name",{value:t,configurable:!0}),ooe=b.forwardRef(aoe(function(t,n){var u;const{container:r,...i}=t,[a,s]=b.useState(!1);roe(()=>s(!0),[]);const l=r||a&&((u=globalThis==null?void 0:globalThis.document)==null?void 0:u.body);return l?La.createPortal(y.jsx(Xv.div,{...i,ref:n}),l):null},"Portal")),eI=globalThis!=null&&globalThis.document?b.useLayoutEffect:()=>{},soe=Object.defineProperty,To=(e,t)=>soe(e,"name",{value:t,configurable:!0});function N$(e,t){return b.useReducer((n,r)=>t[n][r]??n,e)}To(N$,"useStateMachine");var C$=To(e=>{const{present:t,children:n}=e,r=T$(t),i=typeof n=="function"?n({present:r.isPresent}):b.Children.only(n),a=M$(r.ref,I$(i));return typeof n=="function"||r.isPresent?b.cloneElement(i,{ref:a}):null},"Presence");function T$(e){const[t,n]=b.useState(),r=b.useRef(null),i=b.useRef(e),a=b.useRef("none"),s=b.useRef(void 0),l=e?"mounted":"unmounted",[u,d]=N$(l,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return b.useEffect(()=>{u==="mounted"?(a.current=s.current??bu(r.current),s.current=void 0):a.current="none"},[u]),eI(()=>{const h=r.current,m=i.current;if(m!==e){const g=a.current,w=bu(h);e?(s.current=w,d("MOUNT")):w==="none"||(h==null?void 0:h.display)==="none"?d("UNMOUNT"):d(m&&g!==w?"ANIMATION_OUT":"UNMOUNT"),i.current=e}},[e,d]),eI(()=>{if(t){let h;const m=t.ownerDocument.defaultView??window,p=To(w=>{const E=bu(r.current).includes(CSS.escape(w.animationName));if(w.target===t&&E&&(d("ANIMATION_END"),!i.current)){const _=t.style.animationFillMode;t.style.animationFillMode="forwards",h=m.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=_)})}},"handleAnimationEnd"),g=To(w=>{w.target===t&&(a.current=bu(r.current))},"handleAnimationStart");return t.addEventListener("animationstart",g),t.addEventListener("animationcancel",p),t.addEventListener("animationend",p),()=>{m.clearTimeout(h),t.removeEventListener("animationstart",g),t.removeEventListener("animationcancel",p),t.removeEventListener("animationend",p)}}else d("ANIMATION_END")},[t,d]),{isPresent:["mounted","unmountSuspended"].includes(u),ref:b.useCallback(h=>{if(h){const m=getComputedStyle(h);r.current=m,s.current=bu(m)}else r.current=null;n(h)},[])}}To(T$,"usePresence");function x1(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}To(x1,"setRef");function M$(...e){const t=b.useRef(e);return t.current=e,b.useCallback(n=>{const r=t.current;let i=!1;const a=r.map(s=>{const l=x1(s,n);return!i&&typeof l=="function"&&(i=!0),l});if(i)return()=>{for(let s=0;s<a.length;s++){const l=a[s];typeof l=="function"?l():x1(r[s],null)}}},[])}To(M$,"useStableComposedRefs");function bu(e){return(e==null?void 0:e.animationName)||"none"}To(bu,"getAnimationName");function I$(e){var r,i;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(i=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:i.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}To(I$,"getElementRef");var R$=globalThis!=null&&globalThis.document?b.useLayoutEffect:()=>{},loe=Object.defineProperty,coe=(e,t)=>loe(e,"name",{value:t,configurable:!0}),tI=ja[" useEffectEvent ".trim().toString()],nI=ja[" useInsertionEffect ".trim().toString()];function P$(e){if(typeof tI=="function")return tI(e);const t=b.useRef(()=>{throw new Error("Cannot call an event handler while rendering.")});return typeof nI=="function"?nI(()=>{t.current=e}):R$(()=>{t.current=e}),b.useMemo(()=>((...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)}),[])}coe(P$,"useEffectEvent");var uoe=Object.defineProperty,Nh=(e,t)=>uoe(e,"name",{value:t,configurable:!0}),doe=ja[" useInsertionEffect ".trim().toString()]||R$;function D$({prop:e,defaultProp:t,onChange:n=Nh(()=>{},"onChange"),caller:r}){const[i,a,s]=j$({defaultProp:t,onChange:n}),l=e!==void 0,u=l?e:i,d=b.useCallback(h=>{var m;if(l){const p=L$(h)?h(e):h;p!==e&&((m=s.current)==null||m.call(s,p))}else a(h)},[l,e,a,s]);return[u,d]}Nh(D$,"useControllableState");function j$({defaultProp:e,onChange:t}){const[n,r]=b.useState(e),i=b.useRef(n),a=b.useRef(t);return doe(()=>{a.current=t},[t]),b.useEffect(()=>{var s;i.current!==n&&((s=a.current)==null||s.call(a,n),i.current=n)},[n,i]),[n,r,a]}Nh(j$,"useUncontrolledState");function L$(e){return typeof e=="function"}Nh(L$,"isFunction");var rI=Symbol("RADIX:SYNC_STATE");function foe(e,t,n,r){const{prop:i,defaultProp:a,onChange:s,caller:l}=t,u=i!==void 0,d=P$(s),h=[{...n,state:a}];r&&h.push(r);const[m,p]=b.useReducer((E,_)=>{if(_.type===rI)return{...E,state:_.state};const k=e(E,_);return u&&!Object.is(k.state,E.state)&&d(k.state),k},...h),g=m.state,w=b.useRef(g);b.useEffect(()=>{w.current!==g&&(w.current=g,u||d(g))},[g,w,u]);const x=b.useMemo(()=>i!==void 0?{...m,state:i}:m,[m,i]);return b.useEffect(()=>{u&&!Object.is(i,m.state)&&p({type:rI,state:i})},[i,m.state,u]),[x,p]}Nh(foe,"useControllableStateReducer");var hoe=Object.defineProperty,Js=(e,t)=>hoe(e,"name",{value:t,configurable:!0}),jS="Popover",[z$,lCe]=Dz(jS,[_$]),LS=_$(),[moe,ld]=z$(jS),poe=Js(e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:i,onOpenChange:a,modal:s=!1}=e,l=LS(t),u=b.useRef(null),[d,h]=b.useState(!1),[m,p]=D$({prop:r,defaultProp:i??!1,onChange:a,caller:jS});return y.jsx(eoe,{...l,children:y.jsx(moe,{scope:t,contentId:Qz(),triggerRef:u,open:m,onOpenChange:p,onOpenToggle:b.useCallback(()=>p(g=>!g),[p]),hasCustomAnchor:d,onCustomAnchorAdd:b.useCallback(()=>h(!0),[]),onCustomAnchorRemove:b.useCallback(()=>h(!1),[]),modal:s,children:n})})},"Popover"),goe="PopoverTrigger",voe=b.forwardRef(Js(function(t,n){const{__scopePopover:r,...i}=t,a=ld(goe,r),s=LS(r),l=ad(n,a.triggerRef),u=y.jsx(Xv.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.open?a.contentId:void 0,"data-state":zS(a.open),...i,ref:l,onClick:Ds(t.onClick,a.onOpenToggle)});return a.hasCustomAnchor?u:y.jsx(toe,{asChild:!0,...s,children:u})},"PopoverTrigger")),$$="PopoverPortal",[yoe,boe]=z$($$,{forceMount:void 0}),xoe=Js(e=>{const{__scopePopover:t,forceMount:n,children:r,container:i}=e,a=ld($$,t);return y.jsx(yoe,{scope:t,forceMount:n,children:y.jsx(C$,{present:n||a.open,children:y.jsx(ooe,{asChild:!0,container:i,children:r})})})},"PopoverPortal"),ih="PopoverContent",woe=b.forwardRef(Js(function(t,n){const r=boe(ih,t.__scopePopover),{forceMount:i=r.forceMount,...a}=t,s=ld(ih,t.__scopePopover);return y.jsx(C$,{present:i||s.open,children:s.modal?y.jsx(Soe,{...a,ref:n}):y.jsx(_oe,{...a,ref:n})})},"PopoverContent")),Eoe=_S("PopoverContent.RemoveScroll"),Soe=b.forwardRef(Js(function(t,n){const r=ld(ih,t.__scopePopover),i=b.useRef(null),a=ad(n,i),s=b.useRef(!1);return b.useEffect(()=>{const l=i.current;if(l)return gz(l)},[]),y.jsx(vS,{as:Eoe,allowPinchZoom:!0,children:y.jsx(B$,{...t,ref:a,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Ds(t.onCloseAutoFocus,l=>{var u;l.preventDefault(),s.current||(u=r.triggerRef.current)==null||u.focus()}),onPointerDownOutside:Ds(t.onPointerDownOutside,l=>{const u=l.detail.originalEvent,d=u.button===0&&u.ctrlKey===!0,h=u.button===2||d;s.current=h},{checkForDefaultPrevented:!1}),onFocusOutside:Ds(t.onFocusOutside,l=>l.preventDefault(),{checkForDefaultPrevented:!1})})})},"PopoverContentModal")),_oe=b.forwardRef(Js(function(t,n){const r=ld(ih,t.__scopePopover),i=b.useRef(!1),a=b.useRef(!1);return y.jsx(B$,{...t,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{var l,u;(l=t.onCloseAutoFocus)==null||l.call(t,s),s.defaultPrevented||(i.current||(u=r.triggerRef.current)==null||u.focus(),s.preventDefault()),i.current=!1,a.current=!1},onInteractOutside:s=>{var d,h;(d=t.onInteractOutside)==null||d.call(t,s),s.defaultPrevented||(i.current=!0,s.detail.originalEvent.type==="pointerdown"&&(a.current=!0));const l=s.target;((h=r.triggerRef.current)==null?void 0:h.contains(l))&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&a.current&&s.preventDefault()}})},"PopoverContentNonModal")),B$=b.forwardRef(Js(function(t,n){const{__scopePopover:r,trapFocus:i,onOpenAutoFocus:a,onCloseAutoFocus:s,disableOutsidePointerEvents:l,onEscapeKeyDown:u,onPointerDownOutside:d,onFocusOutside:h,onInteractOutside:m,...p}=t,g=ld(ih,r),w=LS(r);return OS(),y.jsx(vie,{asChild:!0,loop:!0,trapped:i,onMountAutoFocus:a,onUnmountAutoFocus:s,children:y.jsx(cie,{asChild:!0,disableOutsidePointerEvents:l,onInteractOutside:m,onEscapeKeyDown:u,onPointerDownOutside:d,onFocusOutside:h,onDismiss:()=>g.onOpenChange(!1),deferPointerDownOutside:!0,children:y.jsx(noe,{"data-state":zS(g.open),role:"dialog",id:g.contentId,...w,...p,ref:n,style:{...p.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})},"PopoverContentImpl"));function zS(e){return e?"open":"closed"}Js(zS,"getState");var Aoe=poe,koe=voe,Ooe=xoe,U$=woe;const Noe=Aoe,Coe=koe,F$=b.forwardRef(({className:e,align:t="start",side:n="top",sideOffset:r=8,collisionPadding:i=8,...a},s)=>y.jsx(Ooe,{children:y.jsx(U$,{ref:s,align:t,side:n,sideOffset:r,collisionPadding:i,className:Be("z-50 w-64 max-w-[calc(100vw-1rem)] rounded-md border bg-card p-3 text-card-foreground shadow-md outline-none","data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...a})}));F$.displayName=U$.displayName;const H$=92,K$=96;function Kx(e){if(!Number.isFinite(e)||e<0)return"?";const t=["B","KB","MB","GB","TB","PB"];let n=0;for(;e>=1024&&n<t.length-1;)e/=1024,n++;return`${e<10&&n>0?e.toFixed(1):Math.round(e)} ${t[n]}`}const iI=3e5;function Toe({socket:e,getToken:t}){const[n,r]=b.useState([]);if(b.useEffect(()=>{t().then(a=>a?fetch("/api/stats",{headers:{Authorization:`Bearer ${a}`}}):null).then(a=>a==null?void 0:a.json()).then(a=>(a==null?void 0:a.samples)&&r(a.samples)).catch(a=>console.warn("[MachineStats] seed failed",a))},[t]),b.useEffect(()=>{if(!e)return;const a=e.on(s=>{s.type==="stats"&&r(l=>[...l,s.sample].slice(-120))});return()=>{a()}},[e]),!n.length)return null;const i=n[n.length-1];return y.jsxs("div",{className:"w-full flex flex-wrap items-center justify-center gap-x-2 gap-y-0.5 text-[10px] text-muted-foreground/60",children:[y.jsx(sg,{label:"cpu",value:i.cpu,series:n.map(a=>a.cpu)}),y.jsx(sg,{label:"mem",value:i.mem,series:n.map(a=>a.mem)}),i.disk>=0&&y.jsx(sg,{label:"disk",value:i.disk,severity:zoe(i.disk),title:Boe(i)}),y.jsx(Moe,{getToken:t})]})}function Moe({getToken:e}){const[t,n]=b.useState(null);return b.useEffect(()=>{let r=!0,i=0;const a=async()=>{var d;try{const h=await e();if(!h)return;i=Date.now();const m=await fetch("/api/claude-usage",{headers:{Authorization:`Bearer ${h}`}});if(!r)return;if(m.status===204){n(null);return}if(m.status!==200)return;const p=await m.json();if(!r||!((d=p==null?void 0:p.limits)!=null&&d.length))return;n(p)}catch(h){console.warn("[MachineStats] claude usage poll failed",h)}},s=()=>{document.visibilityState==="visible"&&a()},l=()=>{document.visibilityState==="visible"&&Date.now()-i>=iI&&a()};s();const u=setInterval(s,iI);return document.addEventListener("visibilitychange",l),()=>{r=!1,clearInterval(u),document.removeEventListener("visibilitychange",l)}},[e]),y.jsx(Ioe,{usage:t})}function Ioe({usage:e}){const t=e&&q$(e.limits),[n,r]=b.useState(w1),i=b.useRef(null),a=()=>{i.current&&(clearTimeout(i.current),i.current=null)},s=b.useCallback((l,u=0)=>{if(a(),!u){r(d=>oI(d,l));return}i.current=setTimeout(()=>{i.current=null,r(d=>oI(d,l))},u)},[]);return b.useEffect(()=>a,[]),!e||!t?null:y.jsxs(Noe,{open:n.open,onOpenChange:l=>s(l?{type:"activate"}:{type:"dismiss"}),children:[y.jsx(Coe,{asChild:!0,children:y.jsx("button",{type:"button","aria-label":"claude usage breakdown",className:"cursor-default rounded-sm outline-none focus-visible:ring-1 focus-visible:ring-ring",onPointerEnter:l=>s({type:"pointerenter",pointerType:l.pointerType},Roe),onPointerLeave:l=>s({type:"pointerleave",pointerType:l.pointerType},aI),children:y.jsx(sg,{label:"usage",value:t.percent,severity:t.severity})})}),y.jsx(F$,{onOpenAutoFocus:l=>l.preventDefault(),onPointerEnter:()=>a(),onPointerLeave:l=>s({type:"pointerleave",pointerType:l.pointerType},aI),children:y.jsx(Poe,{usage:e})})]})}const Roe=120,aI=80,w1={open:!1,byHover:!1};function oI(e,t){switch(t.type){case"pointerenter":return sI(t.pointerType)?{open:!0,byHover:!0}:e;case"pointerleave":return sI(t.pointerType)&&e.byHover?w1:e;case"activate":return{open:!0,byHover:!1};case"dismiss":return w1}}const sI=e=>e==="mouse"||e==="";function Poe({usage:e}){const t=q$(e.limits);return y.jsxs("div",{className:"text-[11px] leading-tight",children:[y.jsxs("div",{className:"flex items-baseline justify-between gap-2 pb-2 text-muted-foreground",children:[y.jsx("span",{className:"uppercase tracking-wide",children:"claude usage"}),e.subscriptionType&&y.jsxs("span",{className:"tabular-nums",children:[e.subscriptionType," plan"]})]}),y.jsxs("div",{className:"-mt-1 flex items-baseline justify-between gap-2 pb-2 text-[10px] text-muted-foreground",children:[e.account&&y.jsx("span",{className:"truncate",title:e.account,children:e.account}),y.jsx("span",{className:Be("shrink-0",e.stale&&"text-amber-500"),children:joe(e)})]}),e.stale&&e.error&&y.jsxs("div",{"data-refresh-error":!0,className:"-mt-1 pb-2 text-[10px] text-amber-500 break-words",children:[e.error,ag(e.retryAt??null)&&` · retrying in ${ag(e.retryAt??null)}`]}),y.jsx("div",{className:"flex flex-col gap-3",children:e.limits.map((n,r)=>{const i=ag(n.resetsAt),a=n===t;return y.jsxs("div",{"data-headline":a||void 0,className:Be("flex flex-col gap-1",!a&&"opacity-60"),children:[y.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[y.jsxs("span",{className:Be("truncate",a&&"font-medium"),children:[a&&y.jsx("span",{className:"mr-1 text-muted-foreground","aria-hidden":!0,children:"▸"}),Doe(n)]}),y.jsxs("span",{className:Be("tabular-nums shrink-0",E1(n.percent,n.severity)),children:[n.percent,"%"]})]}),y.jsx(G$,{value:n.percent,className:Be("w-full",E1(n.percent,n.severity))}),y.jsx("span",{className:"text-[10px] text-muted-foreground",children:i?`resets in ${i}`:"no reset reported"})]},`${n.kind}-${r}`)})}),y.jsx("div",{className:"mt-3 border-t pt-2 text-[10px] text-muted-foreground",children:"▸ is the window the strip is showing"})]})}function Doe(e){return e.scopeLabel?`${e.scopeLabel} window`:e.kind==="session"?"current session":e.kind==="weekly_all"?"all models":e.kind.replace(/_/g," ")}function q$(e){return e.reduce((t,n)=>!t||n.percent>t.percent?n:t,null)}function joe(e){const t=Loe(e.fetchedAt);return t?e.stale?`${t} old — refresh failed`:`updated ${t} ago`:e.stale?"last reading — refresh failed":"updated just now"}function Loe(e){if(!e)return null;const t=Date.now()-new Date(e).getTime();if(!Number.isFinite(t))return null;const n=Math.round(Math.max(0,t)/6e4);if(n<1)return null;if(n<60)return`${n}m`;const r=Math.floor(n/60),i=n%60;return r<24?i?`${r}h ${i}m`:`${r}h`:`${Math.floor(r/24)}d`}function zoe(e){return e>=K$?"critical":e>=H$?"warning":"ok"}const $oe={critical:"text-red-500",exceeded:"text-red-500",warning:"text-amber-500",warn:"text-amber-500",ok:"text-emerald-500"};function E1(e,t){const n=t?$oe[t]:void 0;return n||(e>=90?"text-red-500":e>=75?"text-amber-500":"text-emerald-500")}function Boe(e){const t=`warn at ${H$}%, critical at ${K$}%`;if(e.diskUsedBytes==null||e.diskTotalBytes==null)return`disk ${e.disk}% used — ${t}`;const n=Math.max(0,e.diskTotalBytes-e.diskUsedBytes);return`disk ${e.disk}% used — ${Kx(e.diskUsedBytes)} of ${Kx(e.diskTotalBytes)}, ${Kx(n)} free — ${t}`}function sg({label:e,value:t,series:n,title:r,severity:i}){const a=E1(t,i),s=r??(n?`${e} ${t}% — last ${n.length} samples`:void 0);return y.jsxs("span",{className:"flex items-center gap-1",title:s,children:[y.jsx("span",{className:"uppercase tracking-wide",children:e}),n?y.jsx(Uoe,{series:n,className:a}):y.jsx(G$,{value:t,className:a}),y.jsxs("span",{className:Be("tabular-nums",a),children:[t,"%"]})]})}function G$({value:e,className:t}){const i=Math.max(0,Math.min(100,e))/100*40;return y.jsxs("svg",{width:40,height:12,viewBox:"0 0 40 12",className:Be("overflow-visible",t),preserveAspectRatio:"none",children:[y.jsx("rect",{x:0,y:12/2-2,width:40,height:4,rx:2,fill:"currentColor",opacity:.2}),i>0&&y.jsx("rect",{x:0,y:12/2-2,width:i,height:4,rx:2,fill:"currentColor"})]})}function Uoe({series:e,className:t}){const i=e.length;if(i<2)return null;const a=e.map((s,l)=>{const u=i>1?l/(i-1)*40:0,d=12-Math.max(0,Math.min(100,s))/100*12;return`${u.toFixed(1)},${d.toFixed(1)}`}).join(" ");return y.jsx("svg",{width:40,height:12,viewBox:"0 0 40 12",className:Be("overflow-visible",t),preserveAspectRatio:"none",children:y.jsx("polyline",{points:a,fill:"none",stroke:"currentColor",strokeWidth:1,strokeLinejoin:"round",strokeLinecap:"round"})})}const kf=50;function Foe({getToken:e,filter:t,refreshKey:n,hydrateIds:r}){const[i,a]=b.useState([]),[s,l]=b.useState(null),[u,d]=b.useState(!1),[h,m]=b.useState({}),p=b.useRef(new Set),g=b.useRef(null),w=b.useRef(null),x=b.useRef(t);x.current=t;const E=b.useRef(kf),_=b.useRef(t);_.current!==t&&(_.current=t,E.current=kf);const k=b.useCallback(async(M,D)=>{const j=await e();if(!j||D!=null&&D.aborted)return null;const R=await fetch(`/api/sessions?${new URLSearchParams(M)}`,{signal:D,headers:{Authorization:`Bearer ${j}`}});if(!R.ok)return null;const H=await R.json();return Array.isArray(H==null?void 0:H.sessions)?H:null},[e]),O=b.useCallback(async(M,D,j)=>{const R=[];let H,P=null;for(;R.length<M;){const G={filter:D,limit:String(Math.min(kf,M-R.length))};H&&(G.before=H);const q=await k(G,j);if(!q)return null;if(R.push(...q.sessions),P=q.nextCursor,!P||!q.sessions.length)break;H=P}return{sessions:R,nextCursor:P}},[k]);b.useEffect(()=>{var D,j;(D=g.current)==null||D.abort(),(j=w.current)==null||j.abort();const M=new AbortController;return g.current=M,d(!0),p.current.clear(),m({}),O(E.current,t,M.signal).then(R=>{!R||M.signal.aborted||(a(R.sessions),l(R.nextCursor))}).catch(()=>{}).finally(()=>{M.signal.aborted||d(!1)}),()=>M.abort()},[O,t,n]);const N=b.useCallback(()=>{var j;if(!s||u)return;(j=w.current)==null||j.abort();const M=new AbortController;w.current=M;const D=x.current;d(!0),k({filter:D,limit:String(kf),before:s},M.signal).then(R=>{!R||M.signal.aborted||D!==x.current||(a(H=>{const P=new Set(H.map(q=>q.sessionId)),G=[...H,...R.sessions.filter(q=>!P.has(q.sessionId))];return E.current=Math.max(kf,G.length),G}),l(R.nextCursor))}).catch(()=>{}).finally(()=>{M.signal.aborted||d(!1)})},[s,u,k]),C=b.useMemo(()=>{const M=new Map;for(const D of Object.values(h))M.set(D.sessionId,D);for(const D of i)M.set(D.sessionId,D);return M},[i,h]),T=r.join(",");return b.useEffect(()=>{const M=r.filter(j=>!!j&&!C.has(j)&&!p.current.has(j)).slice(0,200);if(!M.length)return;for(const j of M)p.current.add(j);let D=!1;return k({ids:M.join(",")}).then(j=>{!j||D||m(R=>{const H={...R};for(const P of j.sessions)H[P.sessionId]=P;return H})}).catch(()=>{}),()=>{D=!0}},[T,C,k]),{sessions:i,cursor:s,loading:u,byId:C,loadMore:N}}const Of="0.1.117";function Hoe(e){const t=Date.now()-e,n=Math.floor(t/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const r=Math.floor(n/60);if(r<24)return`${r}h ago`;const i=Math.floor(r/24);return i<7?`${i}d ago`:new Date(e).toLocaleDateString(void 0,{month:"short",day:"numeric"})}const Nf="w-4 h-4 mt-0.5 shrink-0";function Koe(e){const t=e.slackContext;return(t==null?void 0:t.type)==="dm"?y.jsx(aV,{className:`${Nf} text-purple-400`}):(t==null?void 0:t.type)==="mention"?y.jsx(qG,{className:`${Nf} text-blue-400`}):(t==null?void 0:t.type)==="channel"?y.jsx(eV,{className:`${Nf} text-green-400`}):e.sessionId.startsWith("slack-")?y.jsx(Gw,{className:`${Nf} text-yellow-400`}):y.jsx(Gw,{className:`${Nf} text-muted-foreground`})}function qoe(e){const t=e.slackContext;return(t==null?void 0:t.type)==="dm"?`DM${t.userName?` · ${t.userName}`:""}`:(t==null?void 0:t.type)==="mention"?`@mention${t.channelName?` · #${t.channelName}`:""}`:(t==null?void 0:t.type)==="channel"?`#${t.channelName||"channel"}`:e.sessionId.startsWith("slack-")?"Slack":null}function Goe(e,t,n){return Object.keys(e).map(r=>t.get(r)).filter(r=>!!r&&(n==="all"||r.mine!==!1))}const lI="chats-filter",cI="chats-unread-filter";function Voe({getToken:e,activeSessionId:t,onSelect:n,onNew:r,refreshKey:i,workspaceRefreshKey:a,onRefreshWorkspace:s,unreads:l={},busySessions:u=new Set,socket:d}){var F;const h=za(),[m,p]=b.useState(()=>localStorage.getItem(lI)||"mine"),[g,w]=b.useState(()=>localStorage.getItem(cI)==="true"),[x,E]=b.useState(""),_=b.useRef(null);function k(V){p(V),localStorage.setItem(lI,V)}function O(){const V=!g;w(V),localStorage.setItem(cI,String(V))}const N=b.useMemo(()=>[t,...Object.keys(l)].filter(V=>!!V),[t,l]),{sessions:C,cursor:T,loading:M,byId:D,loadMore:j}=Foe({getToken:e,filter:m,refreshKey:i,hydrateIds:N}),R=b.useMemo(()=>Goe(l,D,m),[l,D,m]),H=R.length,P=b.useMemo(()=>g?[...R].sort((V,$)=>$.lastModified-V.lastModified):C,[g,R,C]),G=t&&!P.some(V=>V.sessionId===t)?D.get(t):void 0;b.useEffect(()=>{_.current&&_.current.scrollIntoView({block:"nearest"})},[t,P,G]);const q=b.useRef(null),X=b.useRef(j);X.current=j,b.useEffect(()=>{const V=q.current;if(!V||!T||g)return;const $=new IntersectionObserver(L=>{L.some(W=>W.isIntersecting)&&X.current()},{rootMargin:"300px"});return $.observe(V),()=>$.disconnect()},[T,M,g]),b.useEffect(()=>{e().then(V=>V?fetch("/api/version",{headers:{Authorization:`Bearer ${V}`}}):null).then(V=>V==null?void 0:V.json()).then(V=>V&&E(V.version)).catch(()=>{})},[]);const U=!!x&&x!=="unknown"&&Of!=="dev"&&x!==Of;b.useEffect(()=>{U&&console.warn(`[shraga] stale client bundle: built from v${Of}, server runs v${x} — rebuild dist/client`)},[U,x]);function K(V){const $=l[V.sessionId],L=u.has(V.sessionId)||V.runStatus==="running"||V.scheduleRunStatus==="running",W=!L&&(!!V.lastStopReason||V.scheduleRunStatus==="error"||V.scheduleRunStatus==="aborted"),z=L?"border-amber-500":W?"border-red-500":$?"border-blue-500":"",ie=!!(L||W||$);return y.jsx("button",{ref:V.sessionId===t?_:void 0,onClick:()=>n(V.sessionId,V.title),className:Be("w-full text-left px-3 py-2.5 text-sm transition-colors hover:bg-accent/50 group",ie?`rounded-r-lg border-l-[3px] ${z}`:"rounded-lg",t===V.sessionId&&"bg-accent"),children:y.jsxs("div",{className:"flex items-start gap-2",children:[Koe(V),y.jsxs("div",{className:"min-w-0 flex-1",children:[y.jsx("span",{className:Be("block truncate text-sm leading-snug",$&&"font-semibold"),children:V.title||"New session"}),y.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5",children:[y.jsx("span",{className:"text-[10px] text-muted-foreground font-medium",children:qoe(V)||V.userName}),y.jsx("span",{className:"text-[10px] text-muted-foreground/50",children:"·"}),y.jsx("span",{className:"text-[10px] text-muted-foreground",children:Hoe(V.lastModified)})]})]})]})},V.sessionId)}return y.jsxs("div",{className:"flex flex-col h-full bg-muted/30",children:[y.jsx("div",{className:"p-3",children:y.jsxs(we,{variant:"outline",size:"sm",className:"w-full gap-2 justify-start",onClick:r,title:"New Chat (Ctrl+N)",children:[y.jsx(ko,{className:"w-4 h-4"})," New Chat",y.jsx("span",{className:"ml-auto flex items-center gap-0.5 text-[10px] text-muted-foreground/50 font-mono",children:"⌃N"})]})}),y.jsx("div",{className:"border-b shrink-0 flex flex-col max-h-[40vh]",children:y.jsx(Bre,{getToken:e,onRefresh:s,refreshKey:a})}),y.jsxs("div",{className:"flex items-center justify-between px-3 pt-2 pb-1",children:[y.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",children:"Chats"}),y.jsxs("div",{className:"flex gap-0.5",children:[["mine","all"].map(V=>y.jsx("button",{onClick:()=>k(V),className:Be("text-[10px] px-1.5 rounded-full transition-colors capitalize leading-none",m===V?"text-foreground font-medium":"text-muted-foreground/60 hover:text-muted-foreground"),children:V},V)),y.jsxs("button",{onClick:O,className:Be("text-[10px] px-1.5 rounded-full transition-colors leading-none",g?"text-blue-600 dark:text-blue-400 font-medium":"text-muted-foreground/60 hover:text-muted-foreground"),children:["unread",H>0&&y.jsx("span",{className:"inline-block w-1.5 h-1.5 ml-1 rounded-full bg-blue-500 align-middle"})]})]})]}),y.jsx(OL,{className:"flex-1",children:y.jsxs("div",{className:"px-2 pb-2 space-y-0.5",children:[P.length===0&&!G&&y.jsx("p",{className:"text-xs text-muted-foreground px-3 py-6 text-center",children:M?"Loading…":g?"No unread conversations":"No conversations yet"}),G&&K(G),P.map(K),!g&&T&&y.jsx("div",{ref:q,className:"py-3 text-center text-[11px] text-muted-foreground/60",children:M?"Loading older…":"···"})]})}),y.jsxs("div",{className:"px-4 py-2 flex flex-col items-center gap-1",children:[y.jsx(Toe,{socket:d??null,getToken:e}),(F=h.sidebarExtras)==null?void 0:F.call(h),x&&(U?y.jsxs("button",{onClick:()=>location.reload(),title:`This page was built from v${Of}, the server runs v${x} — reload to update`,className:"text-[10px] text-amber-400 hover:text-amber-300 text-center underline decoration-dotted",children:["⚠️ stale page (v",Of," → v",x,") · reload"]}):y.jsxs("div",{className:"text-[10px] text-muted-foreground/50 text-center",children:["v",x]}))]})]})}function ni(e,t){const n=e[e.length-1];if((n==null?void 0:n.role)==="assistant"){if(t.type==="text"||t.type==="thinking"){const r=[...n.blocks],i=r[r.length-1];return(i==null?void 0:i.type)===t.type?(r[r.length-1]={...i,text:i.text+t.text},[...e.slice(0,-1),{...n,blocks:r}]):[...e.slice(0,-1),{...n,blocks:[...r,t]}]}return[...e.slice(0,-1),{...n,blocks:[...n.blocks,t]}]}return[...e,{id:Ms(),role:"assistant",blocks:[t]}]}function uI(e,t,n="text"){const r=e[e.length-1],i={type:n,text:t};return(r==null?void 0:r.role)==="assistant"?[...e.slice(0,-1),{...r,blocks:[...r.blocks,i]}]:[...e,{id:Ms(),role:"assistant",blocks:[i]}]}function V$(e,t,n){for(let r=e.length-1;r>=0;r--){const i=e[r];if(i.role!=="assistant")continue;const a=i.blocks.findIndex(l=>l.type==="tool_use"&&l.toolUseId===t);if(a===-1)continue;const s=[...i.blocks];return s[a]={...s[a],input:n},[...e.slice(0,r),{...i,blocks:s},...e.slice(r+1)]}return e}function Woe(e,t){const[n,r]=b.useState([]),[i,a]=b.useState(!1),[s,l]=b.useState([]),u=b.useRef(t.initialSessionId),d=b.useRef(!1),h=b.useRef(s);h.current=s;const m=b.useRef(t.getToken);m.current=t.getToken;const p=b.useRef(t.onNewSession);p.current=t.onNewSession;const g=b.useRef(t.onDirectivesChanged);g.current=t.onDirectivesChanged;const w=b.useRef(t.onParticipantsChanged);w.current=t.onParticipantsChanged;const x=b.useRef(t.onEvent);x.current=t.onEvent;const E=b.useRef(e);E.current=e;const _=b.useCallback(P=>P!=null&&P===u.current,[]),k=b.useCallback(async()=>{var G;const P=u.current;if(P)try{const X=await(await jl(`/api/sessions/${P}/messages`,m.current)).json();r(nL(X)),a(!!X.busy),(G=w.current)==null||G.call(w,Array.isArray(X.participants)&&X.participants.length>1)}catch{}},[]);b.useEffect(()=>{if(!e)return;const P=e.on(G=>{var X,U,K,F,V,$;(X=x.current)==null||X.call(x,G);const q=G;if(q.type==="compact_marker")return _(q.sessionId)?r(L=>[...L,{id:Ms(),role:"assistant",blocks:[{type:"compact_marker",summary:q.summary??"",compactedCount:q.compactedCount??0}]}]):void 0;switch(G.type){case"thinking_delta":return _(G.sessionId)?r(L=>ni(L,{type:"thinking",text:G.text})):void 0;case"text_delta":return _(G.sessionId)?r(L=>ni(L,{type:"text",text:G.text})):void 0;case"tool_use":return _(G.sessionId)?r(L=>ni(L,{type:"tool_use",tool:G.tool,toolUseId:G.toolUseId,input:G.input})):void 0;case"tool_use_input":return _(G.sessionId)?r(L=>V$(L,G.toolUseId,G.input)):void 0;case"tool_result":return _(G.sessionId)?r(L=>ni(L,{type:"tool_result",toolUseId:G.toolUseId,output:G.output})):void 0;case"tool_result_image":return _(G.sessionId)?r(L=>ni(L,{type:"image",src:G.dataUrl})):void 0;case"permission_request":return _(G.sessionId)?r(L=>ni(L,{type:"permission_request",id:G.id,tool:G.tool,input:G.input})):void 0;case"question_request":return _(G.sessionId)?r(L=>ni(L,{type:"question_request",id:G.id,questions:G.questions})):void 0;case"directives":return d.current?(U=g.current)==null?void 0:U.call(g,G.directives):void 0;case"session_id":return!d.current||u.current?void 0:(u.current=G.sessionId,(K=p.current)==null?void 0:K.call(p,G.sessionId));case"forked":return G.sourceSessionId!==u.current?void 0:(u.current=G.sessionId,(F=p.current)==null?void 0:F.call(p,G.sessionId));case"session_busy":G.sessionId===u.current&&a(G.busy);return;case"session_stream":return G.sessionId!==u.current?void 0:Yoe(r,G.event);case"session_messages_changed":G.sessionId===u.current&&k();return;case"done":{if(G.sessionId!==u.current)return;G.stopReason==="max_turns_reached"&&r(W=>ni(W,{type:"text",text:`
1907
+ `)},Ere=0,ru=[];function Sre(e){var t=b.useRef([]),n=b.useRef([0,0]),r=b.useRef(),i=b.useState(Ere++)[0],a=b.useState(dz)[0],s=b.useRef(e);b.useEffect(function(){s.current=e},[e]),b.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(i));var x=R7([e.lockRef.current],(e.shards||[]).map(BM),!0).filter(Boolean);return x.forEach(function(E){return E.classList.add("allow-interactivity-".concat(i))}),function(){document.body.classList.remove("block-interactivity-".concat(i)),x.forEach(function(E){return E.classList.remove("allow-interactivity-".concat(i))})}}},[e.inert,e.lockRef.current,e.shards]);var l=b.useCallback(function(x,E){if("touches"in x&&x.touches.length===2||x.type==="wheel"&&x.ctrlKey)return!s.current.allowPinchZoom;var _=kp(x),k=n.current,O="deltaX"in x?x.deltaX:k[0]-_[0],N="deltaY"in x?x.deltaY:k[1]-_[1],C,T=x.target,M=Math.abs(O)>Math.abs(N)?"h":"v";if("touches"in x&&M==="h"&&T.type==="range")return!1;var D=window.getSelection(),j=D&&D.anchorNode,R=j?j===T||j.contains(T):!1;if(R)return!1;var H=zM(M,T);if(!H)return!0;if(H?C=M:(C=M==="v"?"h":"v",H=zM(M,T)),!H)return!1;if(!r.current&&"changedTouches"in x&&(O||N)&&(r.current=C),!C)return!0;var P=r.current||C;return bre(P,E,x,P==="h"?O:N)},[]),u=b.useCallback(function(x){var E=x;if(!(!ru.length||ru[ru.length-1]!==a)){var _="deltaY"in E?$M(E):kp(E),k=t.current.filter(function(C){return C.name===E.type&&(C.target===E.target||E.target===C.shadowParent)&&xre(C.delta,_)})[0];if(k&&k.should){E.cancelable&&E.preventDefault();return}if(!k){var O=(s.current.shards||[]).map(BM).filter(Boolean).filter(function(C){return C.contains(E.target)}),N=O.length>0?l(E,O[0]):!s.current.noIsolation;N&&E.cancelable&&E.preventDefault()}}},[]),d=b.useCallback(function(x,E,_,k){var O={name:x,delta:E,target:_,should:k,shadowParent:_re(_)};t.current.push(O),setTimeout(function(){t.current=t.current.filter(function(N){return N!==O})},1)},[]),h=b.useCallback(function(x){n.current=kp(x),r.current=void 0},[]),m=b.useCallback(function(x){d(x.type,$M(x),x.target,l(x,e.lockRef.current))},[]),p=b.useCallback(function(x){d(x.type,kp(x),x.target,l(x,e.lockRef.current))},[]);b.useEffect(function(){return ru.push(a),e.setCallbacks({onScrollCapture:m,onWheelCapture:m,onTouchMoveCapture:p}),document.addEventListener("wheel",u,nu),document.addEventListener("touchmove",u,nu),document.addEventListener("touchstart",h,nu),function(){ru=ru.filter(function(x){return x!==a}),document.removeEventListener("wheel",u,nu),document.removeEventListener("touchmove",u,nu),document.removeEventListener("touchstart",h,nu)}},[]);var g=e.removeScrollBar,w=e.inert;return b.createElement(b.Fragment,null,w?b.createElement(a,{styles:wre(i)}):null,g?b.createElement(fre,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function _re(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const Are=Jne(uz,Sre);var vS=b.forwardRef(function(e,t){return b.createElement(Wv,xa({},e,{ref:t,sideCar:Are}))});vS.classNames=Wv.classNames;var kre=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},iu=new WeakMap,Op=new WeakMap,Np={},Lx=0,pz=function(e){return e&&(e.host||pz(e.parentNode))},Ore=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=pz(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},Nre=function(e,t,n,r){var i=Ore(t,Array.isArray(e)?e:[e]);Np[n]||(Np[n]=new WeakMap);var a=Np[n],s=[],l=new Set,u=new Set(i),d=function(m){!m||l.has(m)||(l.add(m),d(m.parentNode))};i.forEach(d);var h=function(m){!m||u.has(m)||Array.prototype.forEach.call(m.children,function(p){if(l.has(p))h(p);else try{var g=p.getAttribute(r),w=g!==null&&g!=="false",x=(iu.get(p)||0)+1,E=(a.get(p)||0)+1;iu.set(p,x),a.set(p,E),s.push(p),x===1&&w&&Op.set(p,!0),E===1&&p.setAttribute(n,"true"),w||p.setAttribute(r,"true")}catch(_){console.error("aria-hidden: cannot operate on ",p,_)}})};return h(t),l.clear(),Lx++,function(){s.forEach(function(m){var p=iu.get(m)-1,g=a.get(m)-1;iu.set(m,p),a.set(m,g),p||(Op.has(m)||m.removeAttribute(r),Op.delete(m)),g||m.removeAttribute(n)}),Lx--,Lx||(iu=new WeakMap,iu=new WeakMap,Op=new WeakMap,Np={})}},gz=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),i=kre(e);return i?(r.push.apply(r,Array.from(i.querySelectorAll("[aria-live], script"))),Nre(r,i,n,"aria-hidden")):function(){return null}},Yv="Dialog",[vz]=hL(Yv),[Cre,Ji]=vz(Yv),yz=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:i,onOpenChange:a,modal:s=!0}=e,l=b.useRef(null),u=b.useRef(null),[d,h]=_ne({prop:r,defaultProp:i??!1,onChange:a,caller:Yv});return y.jsx(Cre,{scope:t,triggerRef:l,contentRef:u,contentId:Mx(),titleId:Mx(),descriptionId:Mx(),open:d,onOpenChange:h,onOpenToggle:b.useCallback(()=>h(m=>!m),[h]),modal:s,children:n})};yz.displayName=Yv;var bz="DialogTrigger",xz=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=Ji(bz,n),a=ui(t,i.triggerRef);return y.jsx(Fr.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":ES(i.open),...r,ref:a,onClick:Sr(e.onClick,i.onOpenToggle)})});xz.displayName=bz;var yS="DialogPortal",[Tre,wz]=vz(yS,{forceMount:void 0}),Ez=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:i}=e,a=Ji(yS,t);return y.jsx(Tre,{scope:t,forceMount:n,children:b.Children.map(r,s=>y.jsx(Xs,{present:n||a.open,children:y.jsx(lz,{asChild:!0,container:i,children:s})}))})};Ez.displayName=yS;var Pg="DialogOverlay",bS=b.forwardRef((e,t)=>{const n=wz(Pg,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,a=Ji(Pg,e.__scopeDialog);return a.modal?y.jsx(Xs,{present:r||a.open,children:y.jsx(Ire,{...i,ref:t})}):null});bS.displayName=Pg;var Mre=GE("DialogOverlay.RemoveScroll"),Ire=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=Ji(Pg,n),a=Ine(),s=ui(t,a);return y.jsx(vS,{as:Mre,allowPinchZoom:!0,shards:[i.contentRef],children:y.jsx(Fr.div,{"data-state":ES(i.open),...r,ref:s,style:{pointerEvents:"auto",...r.style}})})}),Uu="DialogContent",xS=b.forwardRef((e,t)=>{const n=wz(Uu,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,a=Ji(Uu,e.__scopeDialog);return y.jsx(Xs,{present:r||a.open,children:a.modal?y.jsx(Rre,{...i,ref:t}):y.jsx(Pre,{...i,ref:t})})});xS.displayName=Uu;var Rre=b.forwardRef((e,t)=>{const n=Ji(Uu,e.__scopeDialog),r=b.useRef(null),i=ui(t,n.contentRef,r);return b.useEffect(()=>{const a=r.current;if(a)return gz(a)},[]),y.jsx(Sz,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,onCloseAutoFocus:Sr(e.onCloseAutoFocus,a=>{var s;a.preventDefault(),(s=n.triggerRef.current)==null||s.focus()}),onPointerDownOutside:Sr(e.onPointerDownOutside,a=>{const s=a.detail.originalEvent,l=s.button===0&&s.ctrlKey===!0;(s.button===2||l)&&a.preventDefault()}),onFocusOutside:Sr(e.onFocusOutside,a=>a.preventDefault())})}),Pre=b.forwardRef((e,t)=>{const n=Ji(Uu,e.__scopeDialog),r=b.useRef(!1),i=b.useRef(!1);return y.jsx(Sz,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:a=>{var s,l;(s=e.onCloseAutoFocus)==null||s.call(e,a),a.defaultPrevented||(r.current||(l=n.triggerRef.current)==null||l.focus(),a.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:a=>{var u,d;(u=e.onInteractOutside)==null||u.call(e,a),a.defaultPrevented||(r.current=!0,a.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const s=a.target;((d=n.triggerRef.current)==null?void 0:d.contains(s))&&a.preventDefault(),a.detail.originalEvent.type==="focusin"&&i.current&&a.preventDefault()}})}),Sz=b.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:a,...s}=e,l=Ji(Uu,n);return Kne(),y.jsx(y.Fragment,{children:y.jsx(oz,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:a,children:y.jsx(iz,{role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":ES(l.open),...s,ref:t,deferPointerDownOutside:!0,onDismiss:()=>l.onOpenChange(!1)})})})}),_z="DialogTitle",wS=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=Ji(_z,n);return y.jsx(Fr.h2,{id:i.titleId,...r,ref:t})});wS.displayName=_z;var Az="DialogDescription",Dre=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=Ji(Az,n);return y.jsx(Fr.p,{id:i.descriptionId,...r,ref:t})});Dre.displayName=Az;var kz="DialogClose",Oz=b.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,i=Ji(kz,n);return y.jsx(Fr.button,{type:"button",...r,ref:t,onClick:Sr(e.onClick,()=>i.onOpenChange(!1))})});Oz.displayName=kz;function ES(e){return e?"open":"closed"}const Oo=yz,rd=xz,jre=Ez,Nz=b.forwardRef(({className:e,...t},n)=>y.jsx(bS,{ref:n,className:Be("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));Nz.displayName=bS.displayName;const Na=b.forwardRef(({className:e,children:t,...n},r)=>y.jsxs(jre,{children:[y.jsx(Nz,{}),y.jsxs(xS,{ref:r,className:Be("fixed left-[50%] top-[50%] z-50 flex flex-col w-[calc(100vw-2rem)] max-w-lg max-h-[85dvh] overflow-y-auto translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-4 sm:p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 sm:rounded-lg",e),...n,children:[t,y.jsxs(Oz,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[y.jsx(Ql,{className:"h-4 w-4"}),y.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Na.displayName=xS.displayName;function Bs({className:e,...t}){return y.jsx("div",{className:Be("shrink-0 flex flex-col space-y-1.5 text-center sm:text-left",e),...t})}function Cz({className:e,...t}){return y.jsx("div",{"data-dialog-body":!0,className:Be("flex-1 min-h-0 overflow-y-auto -mx-4 px-4 sm:-mx-6 sm:px-6",e),...t})}function Tz({className:e,...t}){return y.jsx("div",{className:Be("shrink-0 -mx-4 px-4 pt-3 border-t sm:-mx-6 sm:px-6","flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",e),...t})}const No=b.forwardRef(({className:e,...t},n)=>y.jsx(wS,{ref:n,className:Be("text-lg font-semibold leading-none tracking-tight",e),...t}));No.displayName=wS.displayName;const Lre=new Set(["png","jpg","jpeg","gif","webp","svg","ico","bmp","avif"]),zre=new Set(["pdf","mp4","webm","mp3","ogg","wav"]);async function $re(e,t){const n=await t();if(!n)return[];const r=await fetch(`/api/workspace/ls?path=${encodeURIComponent(e)}`,{headers:{Authorization:`Bearer ${n}`}});return r.ok?(await r.json()).entries??[]:[]}function Bre({getToken:e,onRefresh:t,refreshKey:n}){const[r,i]=b.useState(new Map),[a,s]=b.useState(()=>new Set),[l,u]=b.useState(null),[d,h]=b.useState(!1),[m,p]=b.useState("fit"),[g,w]=b.useState(null),[x,E]=b.useState(null),_=b.useRef(null),[k,O]=b.useState(null),[N,C]=b.useState(!1),[T,M]=b.useState([]),D=b.useCallback(async U=>{const K=await $re(U,e);i(F=>new Map(F).set(U,K))},[e]);b.useEffect(()=>{D(""),a.forEach(U=>D(U))},[D,n]);const j=r.get("")??[],R=b.useCallback(U=>{try{const K=U.contentDocument;if(!(K!=null&&K.body))return;const F=Math.max(K.body.offsetWidth,K.body.scrollWidth),V=Math.max(K.body.offsetHeight,K.body.scrollHeight);F&&V&&E({w:F,h:V})}catch{}},[]),H=b.useCallback(()=>{const U=_.current,K=x;if(!U||!K)return;const F=16,V=U.clientWidth-F,$=U.clientHeight-F,L=Math.min(V/K.w,$/K.h,1);w({scale:L,w:K.w,h:K.h})},[x]);b.useEffect(()=>{if(!(l!=null&&l.html)||m!=="fit"){w(null);return}const U=_.current;if(!U)return;const K=new ResizeObserver(()=>requestAnimationFrame(H));return K.observe(U),()=>K.disconnect()},[l==null?void 0:l.html,d,m,H]),b.useEffect(()=>{N&&e().then(U=>{U&&fetch("/api/data-sync/log",{headers:{Authorization:`Bearer ${U}`}}).then(K=>K.json()).then(M).catch(()=>{})})},[N]);const P=U=>{s(K=>{const F=new Set(K);return F.has(U)?F.delete(U):(F.add(U),r.has(U)||D(U)),F})},G=(U,K)=>{const F=new URLSearchParams({path:U});return k&&F.set("token",k),K&&F.set("dl","1"),`/api/workspace/raw?${F}`},q=async U=>{var V;const K=await e();if(!K)return;O(K);const F=((V=U.split(".").pop())==null?void 0:V.toLowerCase())??"";if(F==="html"||F==="htm"){u({path:U,content:"",binary:!1,html:!0});return}if(Lre.has(F)){u({path:U,content:"",binary:!1,image:!0});return}if(zre.has(F)){u({path:U,content:"",binary:!1,html:!0});return}try{const $=await fetch(`/api/workspace/file?path=${encodeURIComponent(U)}`,{headers:{Authorization:`Bearer ${K}`}});if(!$.ok)return;const L=await $.json();u({path:U,content:L.content,binary:!!L.binary})}catch{}},X=(U,K)=>y.jsx(y.Fragment,{children:U.map(F=>{const V=F.path.split("/").pop();return y.jsxs("div",{children:[F.type==="dir"?y.jsxs("button",{onClick:()=>P(F.path),className:"w-full flex items-center gap-1 px-2 py-1 rounded hover:bg-accent/50 text-left text-sm",style:{paddingLeft:8+K*12},children:[y.jsx(Ys,{className:Be("w-3 h-3 shrink-0 transition-transform",a.has(F.path)&&"rotate-90")}),y.jsx(JG,{className:"w-3.5 h-3.5 shrink-0 text-muted-foreground"}),y.jsx("span",{className:"truncate",children:V})]}):y.jsxs("button",{onClick:()=>q(F.path),className:"w-full flex items-center gap-1 px-2 py-1 rounded hover:bg-accent/50 text-left text-sm",style:{paddingLeft:8+K*12+12},title:F.oneLiner||F.path,children:[y.jsx(UE,{className:"w-3.5 h-3.5 shrink-0 text-muted-foreground"}),y.jsx("span",{className:"truncate",children:V})]}),F.type==="dir"&&a.has(F.path)&&X(r.get(F.path)??[],K+1)]},F.path)})});return y.jsxs(y.Fragment,{children:[y.jsxs("div",{className:"flex items-center justify-between px-3 pt-2 pb-1 shrink-0",children:[y.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",children:"Workspace"}),y.jsxs("div",{className:"flex items-center gap-0.5",children:[y.jsx("button",{onClick:()=>C(!0),className:"p-0.5 rounded hover:bg-accent text-muted-foreground",title:"Activity log",children:y.jsx(tV,{className:"w-3 h-3"})}),y.jsx("button",{onClick:()=>{D(""),a.forEach(U=>D(U)),t==null||t()},className:"p-0.5 rounded hover:bg-accent text-muted-foreground",title:"Refresh",children:y.jsx(ed,{className:"w-3 h-3"})})]})]}),y.jsx("div",{className:"px-1 pb-2 overflow-y-auto min-h-0",children:j.length===0?y.jsx("p",{className:"text-xs text-muted-foreground px-3 py-2",children:"Empty. Drop .md files into data/workspace/ or ask the agent to create some."}):X(j,0)}),y.jsx(Oo,{open:!!l,onOpenChange:U=>{U||(u(null),h(!1),p("fit"),E(null))},children:y.jsxs(Na,{className:Be(l!=null&&l.html?Be("!flex !flex-col !p-0 !gap-0 overflow-hidden",d?"max-w-none w-[100vw] h-[100vh] rounded-none border-0":"max-w-[90vw] w-[90vw] h-[85vh]"):"max-w-3xl max-h-[80vh] !flex !flex-col overflow-hidden"),children:[y.jsxs("div",{className:"absolute right-12 top-4 flex items-center gap-1.5 z-10",children:[(l==null?void 0:l.html)&&y.jsxs(y.Fragment,{children:[y.jsx("button",{onClick:()=>p(U=>U==="fit"?"scroll":"fit"),className:"rounded-sm opacity-70 hover:opacity-100 text-muted-foreground",title:m==="fit"?"Switch to scrollable (1:1)":"Switch to scale-to-fit",children:m==="fit"?y.jsx(oV,{className:"w-4 h-4"}):y.jsx(fV,{className:"w-4 h-4"})}),y.jsx("button",{onClick:()=>h(U=>!U),className:"rounded-sm opacity-70 hover:opacity-100 text-muted-foreground",title:d?"Restore":"Maximize",children:d?y.jsx(HE,{className:"w-4 h-4"}):y.jsx(FE,{className:"w-4 h-4"})})]}),l&&y.jsx("a",{href:G(l.path,!0),download:!0,className:"rounded-sm opacity-70 hover:opacity-100 text-muted-foreground",title:"Download",children:y.jsx(lL,{className:"w-4 h-4"})})]}),y.jsx(Bs,{className:Be((l==null?void 0:l.html)&&"px-4 py-3 shrink-0 border-b"),children:y.jsx(No,{className:"font-mono text-sm truncate pr-16",children:l==null?void 0:l.path})}),y.jsx("div",{ref:l!=null&&l.html?_:void 0,className:Be(l!=null&&l.html?Be("flex-1 min-h-0 bg-muted/10",m==="fit"?"overflow-hidden flex items-center justify-center":"overflow-auto"):"flex-1 min-h-0 overflow-y-auto"),children:l!=null&&l.html?m==="fit"?y.jsx("div",{style:g?{width:g.w*g.scale,height:g.h*g.scale}:{width:"100%",height:"100%"},children:y.jsx("iframe",{src:G(l.path),className:"border-0 bg-white origin-top-left",title:l.path,onLoad:U=>{R(U.currentTarget),H()},style:g?{width:g.w,height:g.h,transform:`scale(${g.scale})`}:{width:"100%",height:"100%"}})}):y.jsx("iframe",{src:G(l.path),className:"border-0 bg-white mx-auto block",title:l.path,onLoad:U=>R(U.currentTarget),style:{width:(x==null?void 0:x.w)||"100%",height:(x==null?void 0:x.h)||"100%"}}):l!=null&&l.image?y.jsx("div",{className:"flex items-center justify-center p-4",children:y.jsx("img",{src:G(l.path),alt:l.path,className:"max-w-full max-h-[70vh] object-contain"})}):l!=null&&l.binary?y.jsx("p",{className:"text-sm text-muted-foreground",children:"(binary file — preview unavailable)"}):l!=null&&l.path.toLowerCase().endsWith(".md")||l!=null&&l.path.toLowerCase().endsWith(".markdown")?y.jsx("div",{className:"text-sm",children:y.jsx(d3,{remarkPlugins:[D3],rehypePlugins:[rz],className:"prose prose-sm max-w-none dark:prose-invert prose-pre:bg-muted prose-pre:border prose-code:before:content-none prose-code:after:content-none",children:l.content})}):y.jsx("pre",{className:"text-xs whitespace-pre-wrap break-all",children:l==null?void 0:l.content})})]})}),y.jsx(Oo,{open:N,onOpenChange:C,children:y.jsxs(Na,{className:"max-w-2xl max-h-[80vh] overflow-hidden flex flex-col",children:[y.jsx(Bs,{children:y.jsx(No,{className:"text-sm",children:"Activity Log"})}),y.jsxs("div",{className:"overflow-y-auto flex-1 space-y-2",children:[T.map(U=>y.jsxs("div",{className:"border-b border-border/50 pb-2 last:border-0",children:[y.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[y.jsx("span",{className:"text-sm text-foreground",children:U.message}),y.jsx("span",{className:"text-[10px] text-muted-foreground shrink-0",children:Ure(U.date)})]}),U.files.length>0&&y.jsx("div",{className:"text-[11px] text-muted-foreground mt-0.5",children:U.files.map(K=>y.jsx("span",{className:"inline-block mr-2 font-mono",children:K},K))})]},U.hash)),T.length===0&&y.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No activity yet"})]})]})})]})}function Ure(e){const t=new Date(e),r=new Date().getTime()-t.getTime(),i=Math.floor(r/6e4);if(i<60)return`${i}m ago`;const a=Math.floor(i/60);return a<24?`${a}h ago`:t.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function ag(e,t=Date.now()){if(!e)return null;const n=new Date(e).getTime()-t;if(!Number.isFinite(n)||n<=0)return null;const r=Math.round(n/6e4);if(r<1)return"1m";if(r<60)return`${r}m`;const i=Math.floor(r/60),a=r%60;if(i<48)return a?`${i}h ${a}m`:`${i}h`;const s=Math.floor(i/24),l=i%24;return l?`${s}d ${l}h`:`${s}d`}const Fre=/resets\s+(\d{1,2})(?::(\d{2}))?\s*(am|pm)?\s*\(UTC\)/i;function Hre(e,t=Date.now(),n=Date.now()){var m;const r=e.match(Fre);if(!r)return e;let i=Number(r[1]);const a=r[2]?Number(r[2]):0,s=(m=r[3])==null?void 0:m.toLowerCase();if(s==="pm"&&i<12&&(i+=12),s==="am"&&i===12&&(i=0),i>23||a>59)return e;const l=new Date(t),u=new Date(Date.UTC(l.getUTCFullYear(),l.getUTCMonth(),l.getUTCDate(),i,a));u.getTime()<=t&&u.setUTCDate(u.getUTCDate()+1);const d=u.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"}),h=ag(u.toISOString(),n);return e.replace(r[0],`resets ${d}${h?` (in ${h})`:""}`)}var Kre=Object.defineProperty,id=(e,t)=>Kre(e,"name",{value:t,configurable:!0}),Mz=!!(typeof window<"u"&&window.document&&window.document.createElement);function Ds(e,t,{checkForDefaultPrevented:n=!0}={}){return id(function(i){if(e==null||e(i),n===!1||!i||!i.defaultPrevented)return t==null?void 0:t(i)},"handleEvent")}id(Ds,"composeEventHandlers");function qre(e){var t;if(!Mz)throw new Error("Cannot access window outside of the DOM");return((t=e==null?void 0:e.ownerDocument)==null?void 0:t.defaultView)??window}id(qre,"getOwnerWindow");function s1(e){if(!Mz)throw new Error("Cannot access document outside of the DOM");return(e==null?void 0:e.ownerDocument)??document}id(s1,"getOwnerDocument");function Iz(e,t=!1){const{activeElement:n}=s1(e);if(!(n!=null&&n.nodeName))return null;if(Rz(n)&&n.contentDocument)return Iz(n.contentDocument.body,t);if(t){const r=n.getAttribute("aria-activedescendant");if(r){const i=s1(n).getElementById(r);if(i)return i}}return n}id(Iz,"getActiveElement");function Rz(e){return e.tagName==="IFRAME"}id(Rz,"isFrame");var Gre=Object.defineProperty,SS=(e,t)=>Gre(e,"name",{value:t,configurable:!0});function l1(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}SS(l1,"setRef");function Pz(...e){return t=>{let n=!1;const r=e.map(i=>{const a=l1(i,t);return!n&&typeof a=="function"&&(n=!0),a});if(n)return()=>{for(let i=0;i<r.length;i++){const a=r[i];typeof a=="function"?a():l1(e[i],null)}}}}SS(Pz,"composeRefs");function ad(...e){return b.useCallback(Pz(...e),e)}SS(ad,"useComposedRefs");var Vre=Object.defineProperty,Ni=(e,t)=>Vre(e,"name",{value:t,configurable:!0});function Wre(e,t){const n=b.createContext(t);n.displayName=e+"Context";const r=Ni(a=>{const{children:s,...l}=a,u=b.useMemo(()=>l,Object.values(l));return y.jsx(n.Provider,{value:u,children:s})},"Provider");r.displayName=e+"Provider";function i(a,s={}){const{optional:l=!1}=s,u=b.useContext(n);if(u)return u;if(t!==void 0)return t;if(!l)throw new Error(`\`${a}\` must be used within \`${e}\``)}return Ni(i,"useContext"),[r,i]}Ni(Wre,"createContext");function Dz(e,t=[]){let n=[];function r(a,s){const l=b.createContext(s);l.displayName=a+"Context";const u=n.length;n=[...n,s];const d=Ni(m=>{var _;const{scope:p,children:g,...w}=m,x=((_=p==null?void 0:p[e])==null?void 0:_[u])||l,E=b.useMemo(()=>w,Object.values(w));return y.jsx(x.Provider,{value:E,children:g})},"Provider");d.displayName=a+"Provider";function h(m,p,g={}){var _;const{optional:w=!1}=g,x=((_=p==null?void 0:p[e])==null?void 0:_[u])||l,E=b.useContext(x);if(E)return E;if(s!==void 0)return s;if(!w)throw new Error(`\`${m}\` must be used within \`${a}\``)}return Ni(h,"useContext"),[d,h]}Ni(r,"createContext");const i=Ni(()=>{const a=n.map(s=>b.createContext(s));return Ni(function(l){const u=(l==null?void 0:l[e])||a;return b.useMemo(()=>({[`__scope${e}`]:{...l,[e]:u}}),[l,u])},"useScope")},"createScope");return i.scopeName=e,[r,jz(i,...t)]}Ni(Dz,"createContextScope");function jz(...e){const t=e[0];if(e.length===1)return t;const n=Ni(()=>{const r=e.map(i=>({useScope:i(),scopeName:i.scopeName}));return Ni(function(a){const s=r.reduce((l,{useScope:u,scopeName:d})=>{const m=u(a)[`__scope${d}`];return{...l,...m}},{});return b.useMemo(()=>({[`__scope${t.scopeName}`]:s}),[s])},"useComposedScopes")},"createScope");return n.scopeName=t.scopeName,n}Ni(jz,"composeContextScopes");var Yre=Object.defineProperty,ea=(e,t)=>Yre(e,"name",{value:t,configurable:!0});function _S(e){const t=b.forwardRef((n,r)=>{let{children:i,...a}=n,s=null,l=!1;const u=[];c1(i)&&typeof Cp=="function"&&(i=Cp(i._payload)),b.Children.forEach(i,p=>{var g;if(Bz(p)){l=!0;const w=p;let x="child"in w.props?w.props.child:w.props.children;c1(x)&&typeof Cp=="function"&&(x=Cp(x._payload)),s=Zre(w,x),u.push((g=s==null?void 0:s.props)==null?void 0:g.children)}else u.push(p)}),s?s=b.cloneElement(s,void 0,u):!l&&b.Children.count(i)===1&&b.isValidElement(i)&&(s=i);const d=s?$z(s):void 0,h=ad(r,d);if(!s){if(i||i===0)throw new Error(l?eie(e):Jre(e));return i}const m=zz(a,s.props??{});return s.type!==b.Fragment&&(m.ref=r?h:d),b.cloneElement(s,m)});return t.displayName=`${e}.Slot`,t}ea(_S,"createSlot");var Lz=Symbol.for("radix.slottable");function Xre(e){const t=ea(n=>"child"in n?n.children(n.child):n.children,"Slottable");return t.displayName=`${e}.Slottable`,t.__radixId=Lz,t}ea(Xre,"createSlottable");var Zre=ea((e,t)=>{if("child"in e.props){const n=e.props.child;return b.isValidElement(n)?b.cloneElement(n,void 0,e.props.children(n.props.children)):null}return b.isValidElement(t)?t:null},"getSlottableElementFromSlottable");function zz(e,t){const n={...t};for(const r in t){const i=e[r],a=t[r];/^on[A-Z]/.test(r)?i&&a?n[r]=(...l)=>{const u=a(...l);return i(...l),u}:i&&(n[r]=i):r==="style"?n[r]={...i,...a}:r==="className"&&(n[r]=[i,a].filter(Boolean).join(" "))}return{...e,...n}}ea(zz,"mergeProps");function $z(e){var r,i;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(i=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:i.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}ea($z,"getElementRef");function Bz(e){return b.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Lz}ea(Bz,"isSlottable");var Qre=Symbol.for("react.lazy");function c1(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===Qre&&"_payload"in e&&Uz(e._payload)}ea(c1,"isLazyComponent");function Uz(e){return typeof e=="object"&&e!==null&&"then"in e}ea(Uz,"isPromiseLike");var Jre=ea(e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,"createSlotError"),eie=ea(e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,"createSlottableError"),Cp=ja[" use ".trim().toString()],tie=Object.defineProperty,nie=(e,t)=>tie(e,"name",{value:t,configurable:!0}),rie=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Xv=rie.reduce((e,t)=>{const n=_S(`Primitive.${t}`),r=b.forwardRef((i,a)=>{const{asChild:s,...l}=i,u=s?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),y.jsx(u,{...l,ref:a})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function Fz(e,t){e&&La.flushSync(()=>e.dispatchEvent(t))}nie(Fz,"dispatchDiscreteCustomEvent");var iie=Object.defineProperty,aie=(e,t)=>iie(e,"name",{value:t,configurable:!0});function Zv(e){const t=b.useRef(e);return b.useEffect(()=>{t.current=e}),b.useMemo(()=>((...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)}),[])}aie(Zv,"useCallbackRef");var oie=Object.defineProperty,qn=(e,t)=>oie(e,"name",{value:t,configurable:!0}),u1="dismissableLayer.update",sie="dismissableLayer.pointerDownOutside",lie="dismissableLayer.focusOutside",UM,Hz=b.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),cie=b.forwardRef(qn(function(t,n){const{disableOutsidePointerEvents:r=!1,deferPointerDownOutside:i=!1,onEscapeKeyDown:a,onPointerDownOutside:s,onFocusOutside:l,onInteractOutside:u,onDismiss:d,...h}=t,m=b.useContext(Hz),[p,g]=b.useState(null),w=(p==null?void 0:p.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,x]=b.useState({}),E=ad(n,g),_=Array.from(m.layers),[k]=[...m.layersWithOutsidePointerEventsDisabled].slice(-1),O=k?_.indexOf(k):-1,N=p?_.indexOf(p):-1,C=m.layersWithOutsidePointerEventsDisabled.size>0,T=N>=O,M=b.useRef(!1),D=Kz(P=>{s==null||s(P),u==null||u(P),P.defaultPrevented||d==null||d()},{ownerDocument:w,deferPointerDownOutside:i,isDeferredPointerDownOutsideRef:M,dismissableSurfaces:m.dismissableSurfaces,shouldHandlePointerDownOutside:b.useCallback(P=>{if(!(P instanceof Node))return!1;const G=[...m.branches].some(q=>q.contains(P));return T&&!G},[m.branches,T])}),j=qz(P=>{if(i&&M.current)return;const G=P.target;[...m.branches].some(X=>X.contains(G))||(l==null||l(P),u==null||u(P),P.defaultPrevented||d==null||d())},w),R=p?N===_.length-1:!1,H=Zv(P=>{P.key==="Escape"&&(a==null||a(P),!P.defaultPrevented&&d&&(P.preventDefault(),d()))});return b.useEffect(()=>{if(R)return w.addEventListener("keydown",H,{capture:!0}),()=>w.removeEventListener("keydown",H,{capture:!0})},[w,R,H]),b.useEffect(()=>{if(p)return r&&(m.layersWithOutsidePointerEventsDisabled.size===0&&(UM=w.body.style.pointerEvents,w.body.style.pointerEvents="none"),m.layersWithOutsidePointerEventsDisabled.add(p)),m.layers.add(p),d1(),()=>{r&&(m.layersWithOutsidePointerEventsDisabled.delete(p),m.layersWithOutsidePointerEventsDisabled.size===0&&(w.body.style.pointerEvents=UM))}},[p,w,r,m]),b.useEffect(()=>()=>{p&&(m.layers.delete(p),m.layersWithOutsidePointerEventsDisabled.delete(p),d1())},[p,m]),b.useEffect(()=>{const P=qn(()=>x({}),"handleUpdate");return document.addEventListener(u1,P),()=>document.removeEventListener(u1,P)},[]),y.jsx(Xv.div,{...h,ref:E,style:{pointerEvents:C?T?"auto":"none":void 0,...t.style},onFocusCapture:Ds(t.onFocusCapture,j.onFocusCapture),onBlurCapture:Ds(t.onBlurCapture,j.onBlurCapture),onPointerDownCapture:Ds(t.onPointerDownCapture,D.onPointerDownCapture)})},"DismissableLayer"));function uie(){const e=b.useContext(Hz),[t,n]=b.useState(null);return b.useEffect(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),n}qn(uie,"useDismissableLayerSurface");var die=qn(()=>!0,"IS_TRUE");function Kz(e,t){const{ownerDocument:n=globalThis==null?void 0:globalThis.document,deferPointerDownOutside:r=!1,isDeferredPointerDownOutsideRef:i,dismissableSurfaces:a,shouldHandlePointerDownOutside:s=die}=t,l=Zv(e),u=b.useRef(!1),d=b.useRef(!1),h=b.useRef(new Map),m=b.useRef(()=>{});return b.useEffect(()=>{function p(){d.current=!1,i.current=!1,h.current.clear()}qn(p,"resetOutsideInteraction");function g(){return Array.from(h.current.values()).some(Boolean)}qn(g,"isOutsideInteractionIntercepted");function w(O){if(!d.current)return;const N=O.target;N instanceof Node&&[...a].some(T=>T.contains(N))||h.current.set(O.type,!0),O.type==="click"&&window.setTimeout(()=>{d.current&&m.current()},0)}qn(w,"handleInteractionCapture");function x(O){d.current&&h.current.set(O.type,!1)}qn(x,"handleInteractionBubble");const E=qn(O=>{if(O.target&&!u.current){let N=function(){n.removeEventListener("click",m.current);const T=g();p(),T||AS(sie,l,C,{discrete:!0})};if(qn(N,"handleAndDispatchPointerDownOutsideEvent"),!s(O.target)){n.removeEventListener("click",m.current),p(),u.current=!1;return}const C={originalEvent:O};d.current=!0,i.current=r&&O.button===0,h.current.clear(),!r||O.button!==0?N():(n.removeEventListener("click",m.current),m.current=N,n.addEventListener("click",m.current,{once:!0}))}else n.removeEventListener("click",m.current),p();u.current=!1},"handlePointerDown"),_=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const O of _)n.addEventListener(O,w,!0),n.addEventListener(O,x);const k=window.setTimeout(()=>{n.addEventListener("pointerdown",E)},0);return()=>{window.clearTimeout(k),n.removeEventListener("pointerdown",E),n.removeEventListener("click",m.current);for(const O of _)n.removeEventListener(O,w,!0),n.removeEventListener(O,x)}},[n,l,r,i,a,s]),{onPointerDownCapture:qn(()=>u.current=!0,"onPointerDownCapture")}}qn(Kz,"usePointerDownOutside");function qz(e,t=globalThis==null?void 0:globalThis.document){const n=Zv(e),r=b.useRef(!1);return b.useEffect(()=>{const i=qn(a=>{a.target&&!r.current&&AS(lie,n,{originalEvent:a},{discrete:!1})},"handleFocus");return t.addEventListener("focusin",i),()=>t.removeEventListener("focusin",i)},[t,n]),{onFocusCapture:qn(()=>r.current=!0,"onFocusCapture"),onBlurCapture:qn(()=>r.current=!1,"onBlurCapture")}}qn(qz,"useFocusOutside");function d1(){const e=new CustomEvent(u1);document.dispatchEvent(e)}qn(d1,"dispatchUpdate");function AS(e,t,n,{discrete:r}){const i=n.originalEvent.target,a=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?Fz(i,a):i.dispatchEvent(a)}qn(AS,"handleAndDispatchCustomEvent");var fie=Object.defineProperty,kS=(e,t)=>fie(e,"name",{value:t,configurable:!0}),Tp=0,da=null;function hie(e){return OS(),e.children}kS(hie,"FocusGuards");function OS(){b.useEffect(()=>{da||(da={start:f1(),end:f1()});const{start:e,end:t}=da;return document.body.firstElementChild!==e&&document.body.insertAdjacentElement("afterbegin",e),document.body.lastElementChild!==t&&document.body.insertAdjacentElement("beforeend",t),Tp++,()=>{Tp===1&&(da==null||da.start.remove(),da==null||da.end.remove(),da=null),Tp=Math.max(0,Tp-1)}},[])}kS(OS,"useFocusGuards");function f1(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}kS(f1,"createFocusGuard");var mie=Object.defineProperty,pie=(e,t)=>mie(e,"name",{value:t,configurable:!0});function h1(e){const t=b.useRef(e);return b.useEffect(()=>{t.current=e}),b.useMemo(()=>((...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)}),[])}pie(h1,"useCallbackRef");var gie=Object.defineProperty,xr=(e,t)=>gie(e,"name",{value:t,configurable:!0}),zx="focusScope.autoFocusOnMount",$x="focusScope.autoFocusOnUnmount",FM={bubbles:!1,cancelable:!0},vie=b.forwardRef(xr(function(t,n){const{loop:r=!1,trapped:i=!1,onMountAutoFocus:a,onUnmountAutoFocus:s,...l}=t,[u,d]=b.useState(null),h=h1(a),m=h1(s),p=b.useRef(null),g=ad(n,d),w=b.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;b.useEffect(()=>{if(i){let E=function(N){if(w.paused||!u)return;const C=N.target;u.contains(C)?p.current=C:uo(p.current,{select:!0})},_=function(N){if(w.paused||!u)return;const C=N.relatedTarget;C!==null&&(u.contains(C)||uo(p.current,{select:!0}))},k=function(N){if(document.activeElement===document.body)for(const T of N)T.removedNodes.length>0&&uo(u)};xr(E,"handleFocusIn"),xr(_,"handleFocusOut"),xr(k,"handleMutations"),document.addEventListener("focusin",E),document.addEventListener("focusout",_);const O=new MutationObserver(k);return u&&O.observe(u,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",E),document.removeEventListener("focusout",_),O.disconnect()}}},[i,u,w.paused]),b.useEffect(()=>{if(u){HM.add(w);const E=document.activeElement;if(!u.contains(E)){const k=new CustomEvent(zx,FM);u.addEventListener(zx,h),u.dispatchEvent(k),k.defaultPrevented||(Gz(Zz(NS(u)),{select:!0}),document.activeElement===E&&uo(u))}return()=>{u.removeEventListener(zx,h),setTimeout(()=>{const k=new CustomEvent($x,FM);u.addEventListener($x,m),u.dispatchEvent(k),k.defaultPrevented||uo(E??document.body,{select:!0}),u.removeEventListener($x,m),HM.remove(w)},0)}}},[u,h,m,w]);const x=b.useCallback(E=>{if(!r&&!i||w.paused)return;const _=E.key==="Tab"&&!E.altKey&&!E.ctrlKey&&!E.metaKey,k=document.activeElement;if(_&&k){const O=E.currentTarget,[N,C]=Vz(O);N&&C?!E.shiftKey&&k===C?(E.preventDefault(),r&&uo(N,{select:!0})):E.shiftKey&&k===N&&(E.preventDefault(),r&&uo(C,{select:!0})):k===O&&E.preventDefault()}},[r,i,w.paused]);return y.jsx(Xv.div,{tabIndex:-1,...l,ref:g,onKeyDown:x})},"FocusScope"));function Gz(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(uo(r,{select:t}),document.activeElement!==n)return}xr(Gz,"focusFirst");function Vz(e){const t=NS(e),n=m1(t,e),r=m1(t.reverse(),e);return[n,r]}xr(Vz,"getTabbableEdges");function NS(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:xr(r=>{const i=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||i?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP},"acceptNode")});for(;n.nextNode();)t.push(n.currentNode);return t}xr(NS,"getTabbableCandidates");function m1(e,t){const n=typeof t.checkVisibility=="function"&&t.checkVisibility({checkVisibilityCSS:!0});for(const r of e)if(!(n?!r.checkVisibility({checkVisibilityCSS:!0}):Wz(r,{upTo:t})))return r}xr(m1,"findVisible");function Wz(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}xr(Wz,"isHidden");function Yz(e){return e instanceof HTMLInputElement&&"select"in e}xr(Yz,"isSelectableInput");function uo(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&Yz(e)&&t&&e.select()}}xr(uo,"focus");var HM=Xz();function Xz(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=p1(e,t),e.unshift(t)},remove(t){var n;e=p1(e,t),(n=e[0])==null||n.resume()}}}xr(Xz,"createFocusScopesStack");function p1(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}xr(p1,"arrayRemove");function Zz(e){return e.filter(t=>t.tagName!=="A")}xr(Zz,"removeLinks");var yie=globalThis!=null&&globalThis.document?b.useLayoutEffect:()=>{},bie=Object.defineProperty,xie=(e,t)=>bie(e,"name",{value:t,configurable:!0}),wie=ja[" useId ".trim().toString()]||(()=>{}),Eie=0;function Qz(e){const[t,n]=b.useState(wie());return yie(()=>{e||n(r=>r??String(Eie++))},[e]),e||(t?`radix-${t}`:"")}xie(Qz,"useId");const Sie=["top","right","bottom","left"],Us=Math.min,xo=Math.max,Dg=Math.round,Mp=Math.floor,wo=e=>({x:e,y:e}),_ie={left:"right",right:"left",bottom:"top",top:"bottom"};function Jz(e,t,n){return xo(e,Us(t,n))}function Co(e,t){return typeof e=="function"?e(t):e}function Fs(e){return e.split("-")[0]}function od(e){return e.split("-")[1]}function CS(e){return e==="x"?"y":"x"}function TS(e){return e==="y"?"height":"width"}function wa(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function MS(e){return CS(wa(e))}function Aie(e,t,n){n===void 0&&(n=!1);const r=od(e),i=MS(e),a=TS(i);let s=i==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[a]>t.floating[a]&&(s=jg(s)),[s,jg(s)]}function kie(e){const t=jg(e);return[g1(e),t,g1(t)]}function g1(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const KM=["left","right"],qM=["right","left"],Oie=["top","bottom"],Nie=["bottom","top"];function Cie(e,t,n){switch(e){case"top":case"bottom":return n?t?qM:KM:t?KM:qM;case"left":case"right":return t?Oie:Nie;default:return[]}}function Tie(e,t,n,r){const i=od(e);let a=Cie(Fs(e),n==="start",r);return i&&(a=a.map(s=>s+"-"+i),t&&(a=a.concat(a.map(g1)))),a}function jg(e){const t=Fs(e);return _ie[t]+e.slice(t.length)}function Mie(e){var t,n,r,i;return{top:(t=e.top)!=null?t:0,right:(n=e.right)!=null?n:0,bottom:(r=e.bottom)!=null?r:0,left:(i=e.left)!=null?i:0}}function e$(e){return typeof e!="number"?Mie(e):{top:e,right:e,bottom:e,left:e}}function Lg(e){const{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function GM(e,t,n){let{reference:r,floating:i}=e;const a=wa(t),s=MS(t),l=TS(s),u=Fs(t),d=a==="y",h=r.x+r.width/2-i.width/2,m=r.y+r.height/2-i.height/2,p=r[l]/2-i[l]/2;let g;switch(u){case"top":g={x:h,y:r.y-i.height};break;case"bottom":g={x:h,y:r.y+r.height};break;case"right":g={x:r.x+r.width,y:m};break;case"left":g={x:r.x-i.width,y:m};break;default:g={x:r.x,y:r.y}}const w=od(t);return w&&(g[s]+=p*(w==="end"?1:-1)*(n&&d?-1:1)),g}async function Iie(e,t){var n;t===void 0&&(t={});const{x:r,y:i,platform:a,rects:s,elements:l,strategy:u}=e,{boundary:d="clippingAncestors",rootBoundary:h="viewport",elementContext:m="floating",altBoundary:p=!1,padding:g=0}=Co(t,e),w=e$(g),E=l[p?m==="floating"?"reference":"floating":m],_=Lg(await a.getClippingRect({element:(n=await(a.isElement==null?void 0:a.isElement(E)))==null||n?E:E.contextElement||await(a.getDocumentElement==null?void 0:a.getDocumentElement(l.floating)),boundary:d,rootBoundary:h,strategy:u})),k=m==="floating"?{x:r,y:i,width:s.floating.width,height:s.floating.height}:s.reference,O=await(a.getOffsetParent==null?void 0:a.getOffsetParent(l.floating)),N=await(a.isElement==null?void 0:a.isElement(O))&&await(a.getScale==null?void 0:a.getScale(O))||{x:1,y:1},C=Lg(a.convertOffsetParentRelativeRectToViewportRelativeRect?await a.convertOffsetParentRelativeRectToViewportRelativeRect({elements:l,rect:k,offsetParent:O,strategy:u}):k);return{top:(_.top-C.top+w.top)/N.y,bottom:(C.bottom-_.bottom+w.bottom)/N.y,left:(_.left-C.left+w.left)/N.x,right:(C.right-_.right+w.right)/N.x}}const Rie=50,Pie=async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:a=[],platform:s}=n,l=s.detectOverflow?s:{...s,detectOverflow:Iie},u=await(s.isRTL==null?void 0:s.isRTL(t));let d=await s.getElementRects({reference:e,floating:t,strategy:i}),{x:h,y:m}=GM(d,r,u),p=r,g=0;const w={};for(let x=0;x<a.length;x++){const E=a[x];if(!E)continue;const{name:_,fn:k}=E,{x:O,y:N,data:C,reset:T}=await k({x:h,y:m,initialPlacement:r,placement:p,strategy:i,middlewareData:w,rects:d,platform:l,elements:{reference:e,floating:t}});h=O??h,m=N??m,w[_]={...w[_],...C},T&&g<Rie&&(g++,typeof T=="object"&&(T.placement&&(p=T.placement),T.rects&&(d=T.rects===!0?await s.getElementRects({reference:e,floating:t,strategy:i}):T.rects),{x:h,y:m}=GM(d,p,u)),x=-1)}return{x:h,y:m,placement:p,strategy:i,middlewareData:w}},Die=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:i,rects:a,platform:s,elements:l,middlewareData:u}=t,{element:d,padding:h=0}=Co(e,t)||{};if(d==null)return{};const m=e$(h),p={x:n,y:r},g=MS(i),w=TS(g),x=await s.getDimensions(d),E=g==="y",_=E?"top":"left",k=E?"bottom":"right",O=E?"clientHeight":"clientWidth",N=a.reference[w]+a.reference[g]-p[g]-a.floating[w],C=p[g]-a.reference[g],T=await(s.getOffsetParent==null?void 0:s.getOffsetParent(d));let M=T?T[O]:0;(!M||!await(s.isElement==null?void 0:s.isElement(T)))&&(M=l.floating[O]||a.floating[w]);const D=N/2-C/2,j=M/2-x[w]/2-1,R=Us(m[_],j),H=Us(m[k],j),P=M-x[w]-H,G=M/2-x[w]/2+D,q=Jz(R,G,P),X=!u.arrow&&od(i)!=null&&G!==q&&a.reference[w]/2-(G<R?R:H)-x[w]/2<0,U=X?G<R?G-R:G-P:0;return{[g]:p[g]+U,data:{[g]:q,centerOffset:G-q-U,...X&&{alignmentOffset:U}},reset:X}}}),jie=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:i,middlewareData:a,rects:s,initialPlacement:l,platform:u,elements:d}=t,{mainAxis:h=!0,crossAxis:m=!0,fallbackPlacements:p,fallbackStrategy:g="bestFit",fallbackAxisSideDirection:w="none",flipAlignment:x=!0,...E}=Co(e,t);if((n=a.arrow)!=null&&n.alignmentOffset)return{};const _=Fs(i),k=wa(l),O=Fs(l)===l,N=await(u.isRTL==null?void 0:u.isRTL(d.floating)),C=p||(O||!x?[jg(l)]:kie(l)),T=w!=="none";!p&&T&&C.push(...Tie(l,x,w,N));const M=[l,...C],D=await u.detectOverflow(t,E),j=[];let R=((r=a.flip)==null?void 0:r.overflows)||[];if(h&&j.push(D[_]),m){const q=Aie(i,s,N);j.push(D[q[0]],D[q[1]])}if(R=[...R,{placement:i,overflows:j}],!j.every(q=>q<=0)){var H,P;const q=(((H=a.flip)==null?void 0:H.index)||0)+1,X=M[q];if(X&&(!(m==="alignment"?k!==wa(X):!1)||R.every(F=>wa(F.placement)===k?F.overflows[0]>0:!0)))return{data:{index:q,overflows:R},reset:{placement:X}};let U=(P=R.filter(K=>K.overflows[0]<=0).sort((K,F)=>K.overflows[1]-F.overflows[1])[0])==null?void 0:P.placement;if(!U)switch(g){case"bestFit":{var G;const K=(G=R.filter(F=>{if(T){const V=wa(F.placement);return V===k||V==="y"}return!0}).map(F=>[F.placement,F.overflows.filter(V=>V>0).reduce((V,$)=>V+$,0)]).sort((F,V)=>F[1]-V[1])[0])==null?void 0:G[0];K&&(U=K);break}case"initialPlacement":U=l;break}if(i!==U)return{reset:{placement:U}}}return{}}}};function VM(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function WM(e){return Sie.some(t=>e[t]>=0)}const Lie=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n,platform:r}=t,{strategy:i="referenceHidden",...a}=Co(e,t);switch(i){case"referenceHidden":{const s=await r.detectOverflow(t,{...a,elementContext:"reference"}),l=VM(s,n.reference);return{data:{referenceHiddenOffsets:l,referenceHidden:WM(l)}}}case"escaped":{const s=await r.detectOverflow(t,{...a,altBoundary:!0}),l=VM(s,n.floating);return{data:{escapedOffsets:l,escaped:WM(l)}}}default:return{}}}}},t$=new Set(["left","top"]);async function zie(e,t){const{placement:n,platform:r,elements:i}=e,a=await(r.isRTL==null?void 0:r.isRTL(i.floating)),s=Fs(n),l=od(n),u=wa(n)==="y",d=t$.has(s)?-1:1,h=a&&u?-1:1,m=Co(t,e);let{mainAxis:p,crossAxis:g,alignmentAxis:w}=typeof m=="number"?{mainAxis:m,crossAxis:0,alignmentAxis:null}:{mainAxis:m.mainAxis||0,crossAxis:m.crossAxis||0,alignmentAxis:m.alignmentAxis};return l&&typeof w=="number"&&(g=l==="end"?w*-1:w),u?{x:g*h,y:p*d}:{x:p*d,y:g*h}}const $ie=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:i,y:a,placement:s,middlewareData:l}=t,u=await zie(t,e);return s===((n=l.offset)==null?void 0:n.placement)&&(r=l.arrow)!=null&&r.alignmentOffset?{}:{x:i+u.x,y:a+u.y,data:{...u,placement:s}}}}},Bie=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i,platform:a}=t,{mainAxis:s=!0,crossAxis:l=!1,limiter:u={fn:k=>{let{x:O,y:N}=k;return{x:O,y:N}}},...d}=Co(e,t),h={x:n,y:r},m=await a.detectOverflow(t,d),p=wa(i),g=CS(p);let w=h[g],x=h[p];const E=(k,O)=>Jz(O+m[k==="y"?"top":"left"],O,O-m[k==="y"?"bottom":"right"]);s&&(w=E(g,w)),l&&(x=E(p,x));const _=u.fn({...t,[g]:w,[p]:x});return{..._,data:{x:_.x-n,y:_.y-r,enabled:{[g]:s,[p]:l}}}}}},Uie=function(e){return e===void 0&&(e={}),{options:e,fn(t){var n,r;const{x:i,y:a,placement:s,rects:l,middlewareData:u}=t,{offset:d=0,mainAxis:h=!0,crossAxis:m=!0}=Co(e,t),p={x:i,y:a},g=wa(s),w=CS(g);let x=p[w],E=p[g];const _=Co(d,t),k=typeof _=="number"?{mainAxis:_,crossAxis:0}:{mainAxis:(n=_.mainAxis)!=null?n:0,crossAxis:(r=_.crossAxis)!=null?r:0};if(h){const C=w==="y"?"height":"width",T=l.reference[w]-l.floating[C]+k.mainAxis,M=l.reference[w]+l.reference[C]-k.mainAxis;x<T?x=T:x>M&&(x=M)}if(m){var O,N;const C=w==="y"?"width":"height",T=t$.has(Fs(s)),M=l.reference[g]-l.floating[C]+(T&&((O=u.offset)==null?void 0:O[g])||0)+(T?0:k.crossAxis),D=l.reference[g]+l.reference[C]+(T?0:((N=u.offset)==null?void 0:N[g])||0)-(T?k.crossAxis:0);E<M?E=M:E>D&&(E=D)}return{[w]:x,[g]:E}}}},Fie=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:i,elements:a}=t,{apply:s=()=>{},...l}=Co(e,t),u=await i.detectOverflow(t,l),d=Fs(n),h=od(n),m=wa(n)==="y",{width:p,height:g}=r.floating;let w,x;d==="top"||d==="bottom"?(w=d,x=h===(await(i.isRTL==null?void 0:i.isRTL(a.floating))?"start":"end")?"left":"right"):(x=d,w=h==="end"?"top":"bottom");const E=g-u.top-u.bottom,_=p-u.left-u.right,k=Us(g-u[w],E),O=Us(p-u[x],_),N=t.middlewareData.shift,C=!N;let T=k,M=O;N!=null&&N.enabled.x&&(M=_),N!=null&&N.enabled.y&&(T=E),C&&!h&&(m?M=p-2*xo(u.left,u.right):T=g-2*xo(u.top,u.bottom)),await s({...t,availableWidth:M,availableHeight:T});const D=await i.getDimensions(a.floating);return p!==D.width||g!==D.height?{reset:{rects:!0}}:{}}}};function Qv(){return typeof window<"u"}function sd(e){return n$(e)?(e.nodeName||"").toLowerCase():"#document"}function Ur(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function jo(e){var t;return(t=(n$(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function n$(e){return Qv()?e instanceof Node||e instanceof Ur(e).Node:!1}function Ca(e){return Qv()?e instanceof Element||e instanceof Ur(e).Element:!1}function Qs(e){return Qv()?e instanceof HTMLElement||e instanceof Ur(e).HTMLElement:!1}function YM(e){return!Qv()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Ur(e).ShadowRoot}function Jv(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=Ta(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!=="inline"&&i!=="contents"}function Hie(e){return/^(table|td|th)$/.test(sd(e))}function ey(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}const Kie=/transform|translate|scale|rotate|perspective|filter/,qie=/paint|layout|strict|content/,_l=e=>!!e&&e!=="none";let Bx;function IS(e){const t=Ca(e)?Ta(e):e;return _l(t.transform)||_l(t.translate)||_l(t.scale)||_l(t.rotate)||_l(t.perspective)||!RS()&&(_l(t.backdropFilter)||_l(t.filter))||Kie.test(t.willChange||"")||qie.test(t.contain||"")}function Gie(e){let t=ec(e);for(;Qs(t)&&!nh(t);){if(IS(t))return t;if(ey(t))return null;t=ec(t)}return null}function RS(){return Bx==null&&(Bx=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Bx}function nh(e){return/^(html|body|#document)$/.test(sd(e))}function Ta(e){return Ur(e).getComputedStyle(e)}function ty(e){return Ca(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function ec(e){if(sd(e)==="html")return e;const t=e.assignedSlot||e.parentNode||YM(e)&&e.host||jo(e);return YM(t)?t.host:t}function r$(e){const t=ec(e);return nh(t)?(e.ownerDocument||e).body:Qs(t)&&Jv(t)?t:r$(t)}function rh(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const i=r$(e),a=i===((r=e.ownerDocument)==null?void 0:r.body),s=Ur(i);if(a){const l=v1(s);return t.concat(s,s.visualViewport||[],Jv(i)?i:[],l&&n?rh(l):[])}else return t.concat(i,rh(i,[],n))}function v1(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function i$(e){const t=Ta(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=Qs(e),a=i?e.offsetWidth:n,s=i?e.offsetHeight:r,l=Dg(n)!==a||Dg(r)!==s;return l&&(n=a,r=s),{width:n,height:r,$:l}}function PS(e){return Ca(e)?e:e.contextElement}function Tu(e){const t=PS(e);if(!Qs(t))return wo(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:a}=i$(t);let s=(a?Dg(n.width):n.width)/r,l=(a?Dg(n.height):n.height)/i;return(!s||!Number.isFinite(s))&&(s=1),(!l||!Number.isFinite(l))&&(l=1),{x:s,y:l}}const Vie=wo(0);function a$(e){const t=Ur(e);return!RS()||!t.visualViewport?Vie:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function Wie(e,t,n){return t===void 0&&(t=!1),!!n&&t&&n===Ur(e)}function tc(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const i=e.getBoundingClientRect(),a=PS(e);let s=wo(1);t&&(r?Ca(r)&&(s=Tu(r)):s=Tu(e));const l=Wie(a,n,r)?a$(a):wo(0);let u=(i.left+l.x)/s.x,d=(i.top+l.y)/s.y,h=i.width/s.x,m=i.height/s.y;if(a&&r){const p=Ur(a),g=Ca(r)?Ur(r):r;let w=p,x=v1(w);for(;x&&g!==w;){const E=Tu(x),_=x.getBoundingClientRect(),k=Ta(x),O=_.left+(x.clientLeft+parseFloat(k.paddingLeft))*E.x,N=_.top+(x.clientTop+parseFloat(k.paddingTop))*E.y;u*=E.x,d*=E.y,h*=E.x,m*=E.y,u+=O,d+=N,w=Ur(x),x=v1(w)}}return Lg({width:h,height:m,x:u,y:d})}function ny(e,t){const n=ty(e).scrollLeft;return t?t.left+n:tc(jo(e)).left+n}function o$(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-ny(e,n),i=n.top+t.scrollTop;return{x:r,y:i}}function Yie(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const a=i==="fixed",s=jo(r),l=t?ey(t.floating):!1;if(r===s||l&&a)return n;let u={scrollLeft:0,scrollTop:0},d=wo(1);const h=wo(0),m=Qs(r);if((m||!a)&&((sd(r)!=="body"||Jv(s))&&(u=ty(r)),m)){const g=tc(r);d=Tu(r),h.x=g.x+r.clientLeft,h.y=g.y+r.clientTop}const p=s&&!m&&!a?o$(s,u):wo(0);return{width:n.width*d.x,height:n.height*d.y,x:n.x*d.x-u.scrollLeft*d.x+h.x+p.x,y:n.y*d.y-u.scrollTop*d.y+h.y+p.y}}function Xie(e){return e.getClientRects?Array.from(e.getClientRects()):[]}function Zie(e){const t=ty(e),n=e.ownerDocument.body,r=xo(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=xo(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight);let a=-t.scrollLeft+ny(e);const s=-t.scrollTop;return Ta(n).direction==="rtl"&&(a+=xo(e.clientWidth,n.clientWidth)-r),{width:r,height:i,x:a,y:s}}const Qie=25;function Jie(e,t,n){n===void 0&&(n="viewport");const r=n==="layoutViewport",i=Ur(e),a=jo(e),s=i.visualViewport;let l=a.clientWidth,u=a.clientHeight,d=0,h=0;if(s){const p=!RS()||t==="fixed";r?p||(d=-s.offsetLeft,h=-s.offsetTop):(l=s.width,u=s.height,p&&(d=s.offsetLeft,h=s.offsetTop))}if(ny(a)<=0){const p=a.ownerDocument,g=p.body,w=getComputedStyle(g),x=p.compatMode==="CSS1Compat"&&parseFloat(w.marginLeft)+parseFloat(w.marginRight)||0,E=Math.abs(a.clientWidth-g.clientWidth-x),_=getComputedStyle(a).scrollbarGutter==="stable both-edges"?E/2:E;_<=Qie&&(l-=_)}return{width:l,height:u,x:d,y:h}}function eae(e,t){const n=tc(e,!0,t==="fixed"),r=n.top+e.clientTop,i=n.left+e.clientLeft,a=Tu(e),s=e.clientWidth*a.x,l=e.clientHeight*a.y,u=i*a.x,d=r*a.y;return{width:s,height:l,x:u,y:d}}function XM(e,t,n){let r;if(t==="viewport"||t==="layoutViewport")r=Jie(e,n,t);else if(t==="document")r=Zie(jo(e));else if(Ca(t))r=eae(t,n);else{const i=a$(e);r={x:t.x-i.x,y:t.y-i.y,width:t.width,height:t.height}}return Lg(r)}function tae(e,t){const n=t.get(e);if(n)return n;let r=rh(e,[],!1).filter(l=>Ca(l)&&sd(l)!=="body"),i=null;const a=Ta(e).position==="fixed";let s=a?ec(e):e;for(;Ca(s)&&!nh(s);){const l=Ta(s),u=IS(s),d=i?i.position:a?"fixed":"";!u&&(d==="fixed"||d==="absolute"&&l.position==="static")?r=r.filter(m=>m!==s):i=l,s=ec(s)}return t.set(e,r),r}function nae(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const s=[...n==="clippingAncestors"?ey(t)?[]:tae(t,this._c):[].concat(n),r],l=XM(t,s[0],i);let u=l.top,d=l.right,h=l.bottom,m=l.left;for(let p=1;p<s.length;p++){const g=XM(t,s[p],i);u=xo(g.top,u),d=Us(g.right,d),h=Us(g.bottom,h),m=xo(g.left,m)}return{width:d-m,height:h-u,x:m,y:u}}function rae(e){const{width:t,height:n}=i$(e);return{width:t,height:n}}function iae(e,t,n){const r=Qs(t),i=jo(t),a=n==="fixed",s=tc(e,!0,a,t);let l={scrollLeft:0,scrollTop:0};const u=wo(0);if((r||!a)&&((sd(t)!=="body"||Jv(i))&&(l=ty(t)),r)){const p=tc(t,!0,a,t);u.x=p.x+t.clientLeft,u.y=p.y+t.clientTop}!r&&i&&(u.x=ny(i));const d=i&&!r&&!a?o$(i,l):wo(0),h=s.left+l.scrollLeft-u.x-d.x,m=s.top+l.scrollTop-u.y-d.y;return{x:h,y:m,width:s.width,height:s.height}}function Ux(e){return Ta(e).position==="static"}function ZM(e,t){if(!Qs(e)||Ta(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return jo(e)===n&&(n=n.ownerDocument.body),n}function s$(e,t){const n=Ur(e);if(ey(e))return n;if(!Qs(e)){let i=ec(e);for(;i&&!nh(i);){if(Ca(i)&&!Ux(i))return i;i=ec(i)}return n}let r=ZM(e,t);for(;r&&Hie(r)&&Ux(r);)r=ZM(r,t);return r&&nh(r)&&Ux(r)&&!IS(r)?n:r||Gie(e)||n}const aae=async function(e){const t=this.getOffsetParent||s$,n=this.getDimensions,r=await n(e.floating);return{reference:iae(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function oae(e){return Ta(e).direction==="rtl"}const sae={convertOffsetParentRelativeRectToViewportRelativeRect:Yie,getDocumentElement:jo,getClippingRect:nae,getOffsetParent:s$,getElementRects:aae,getClientRects:Xie,getDimensions:rae,getScale:Tu,isElement:Ca,isRTL:oae};function l$(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function lae(e,t,n){let r=null,i;const a=jo(e);function s(){var h;clearTimeout(i),(h=r)==null||h.disconnect(),r=null}function l(h,m){h===void 0&&(h=!1),m===void 0&&(m=1),s();const p=e.getBoundingClientRect(),{left:g,top:w,width:x,height:E}=p;if(h||t(),!x||!E)return;const _=Mp(w),k=Mp(a.clientWidth-(g+x)),O=Mp(a.clientHeight-(w+E)),N=Mp(g),T={rootMargin:-_+"px "+-k+"px "+-O+"px "+-N+"px",threshold:xo(0,Us(1,m))||1};let M=!0;function D(j){const R=j[0].intersectionRatio;if(!l$(p,e.getBoundingClientRect()))return l();if(R!==m){if(!M)return l();R?l(!1,R):i=setTimeout(()=>{l(!1,1e-7)},1e3)}M=!1}try{r=new IntersectionObserver(D,{...T,root:a.ownerDocument})}catch{r=new IntersectionObserver(D,T)}r.observe(e)}const u=Ur(e),d=()=>l(n);return u.addEventListener("resize",d),l(!0),()=>{u.removeEventListener("resize",d),s()}}function cae(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:i=!0,ancestorResize:a=!0,elementResize:s=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:u=!1}=r,d=PS(e),h=i||a?[...d?rh(d):[],...t?rh(t):[]]:[];h.forEach(_=>{i&&_.addEventListener("scroll",n),a&&_.addEventListener("resize",n)});const m=d&&l?lae(d,n,a):null;let p=-1,g=null;s&&(g=new ResizeObserver(_=>{let[k]=_;k&&k.target===d&&g&&t&&(g.unobserve(t),cancelAnimationFrame(p),p=requestAnimationFrame(()=>{var O;(O=g)==null||O.observe(t)})),n()}),d&&!u&&g.observe(d),t&&g.observe(t));let w,x=u?tc(e):null;u&&E();function E(){const _=tc(e);x&&!l$(x,_)&&n(),x=_,w=requestAnimationFrame(E)}return n(),()=>{var _;h.forEach(k=>{i&&k.removeEventListener("scroll",n),a&&k.removeEventListener("resize",n)}),m==null||m(),(_=g)==null||_.disconnect(),g=null,u&&cancelAnimationFrame(w)}}const uae=$ie,dae=Bie,fae=jie,hae=Fie,mae=Lie,QM=Die,pae=Uie,gae=(e,t,n)=>{const r=new Map,i=n??{},a={...sae,...i.platform,_c:r};return Pie(e,t,{...i,platform:a})};var vae=typeof document<"u",yae=function(){},og=vae?b.useLayoutEffect:yae;function zg(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,i;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!zg(e[r],t[r]))return!1;return!0}if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,i[r]))return!1;for(r=n;r--!==0;){const a=i[r];if(!(a==="_owner"&&e.$$typeof)&&!zg(e[a],t[a]))return!1}return!0}return e!==e&&t!==t}function c$(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function JM(e,t){const n=c$(e);return Math.round(t*n)/n}function Fx(e){const t=b.useRef(e);return og(()=>{t.current=e}),t}function bae(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:i,elements:{reference:a,floating:s}={},transform:l=!0,whileElementsMounted:u,open:d}=e,[h,m]=b.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[p,g]=b.useState(r);zg(p,r)||g(r);const[w,x]=b.useState(null),[E,_]=b.useState(null),k=b.useCallback(F=>{F!==T.current&&(T.current=F,x(F))},[]),O=b.useCallback(F=>{F!==M.current&&(M.current=F,_(F))},[]),N=a||w,C=s||E,T=b.useRef(null),M=b.useRef(null),D=b.useRef(h),j=u!=null,R=Fx(u),H=Fx(i),P=Fx(d),G=b.useCallback(()=>{if(!T.current||!M.current)return;const F={placement:t,strategy:n,middleware:p};H.current&&(F.platform=H.current),gae(T.current,M.current,F).then(V=>{const $={...V,isPositioned:P.current!==!1};q.current&&!zg(D.current,$)&&(D.current=$,La.flushSync(()=>{m($)}))})},[p,t,n,H,P]);og(()=>{d===!1&&D.current.isPositioned&&(D.current.isPositioned=!1,m(F=>({...F,isPositioned:!1})))},[d]);const q=b.useRef(!1);og(()=>(q.current=!0,()=>{q.current=!1}),[]),og(()=>{if(N&&(T.current=N),C&&(M.current=C),N&&C){if(R.current)return R.current(N,C,G);G()}},[N,C,G,R,j]);const X=b.useMemo(()=>({reference:T,floating:M,setReference:k,setFloating:O}),[k,O]),U=b.useMemo(()=>({reference:N,floating:C}),[N,C]),K=b.useMemo(()=>{const F={position:n,left:0,top:0};if(!U.floating)return F;const V=JM(U.floating,h.x),$=JM(U.floating,h.y);return l?{...F,transform:"translate("+V+"px, "+$+"px)",...c$(U.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:V,top:$}},[n,l,U.floating,h.x,h.y]);return b.useMemo(()=>({...h,update:G,refs:X,elements:U,floatingStyles:K}),[h,G,X,U,K])}const xae=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:i}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?QM({element:r.current,padding:i}).fn(n):{}:r?QM({element:r,padding:i}).fn(n):{}}}},wae=(e,t)=>{const n=uae(e);return{name:n.name,fn:n.fn,options:[e,t]}},Eae=(e,t)=>{const n=dae(e);return{name:n.name,fn:n.fn,options:[e,t]}},Sae=(e,t)=>({fn:pae(e).fn,options:[e,t]}),_ae=(e,t)=>{const n=fae(e);return{name:n.name,fn:n.fn,options:[e,t]}},Aae=(e,t)=>{const n=hae(e);return{name:n.name,fn:n.fn,options:[e,t]}},kae=(e,t)=>{const n=mae(e);return{name:n.name,fn:n.fn,options:[e,t]}},Oae=(e,t)=>{const n=xae(e);return{name:n.name,fn:n.fn,options:[e,t]}};var Nae=Object.defineProperty,DS=(e,t)=>Nae(e,"name",{value:t,configurable:!0});function y1(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}DS(y1,"setRef");function u$(...e){return t=>{let n=!1;const r=e.map(i=>{const a=y1(i,t);return!n&&typeof a=="function"&&(n=!0),a});if(n)return()=>{for(let i=0;i<r.length;i++){const a=r[i];typeof a=="function"?a():y1(e[i],null)}}}}DS(u$,"composeRefs");function ry(...e){return b.useCallback(u$(...e),e)}DS(ry,"useComposedRefs");var Cae=Object.defineProperty,Ci=(e,t)=>Cae(e,"name",{value:t,configurable:!0});function Tae(e,t){const n=b.createContext(t);n.displayName=e+"Context";const r=Ci(a=>{const{children:s,...l}=a,u=b.useMemo(()=>l,Object.values(l));return y.jsx(n.Provider,{value:u,children:s})},"Provider");r.displayName=e+"Provider";function i(a,s={}){const{optional:l=!1}=s,u=b.useContext(n);if(u)return u;if(t!==void 0)return t;if(!l)throw new Error(`\`${a}\` must be used within \`${e}\``)}return Ci(i,"useContext"),[r,i]}Ci(Tae,"createContext");function d$(e,t=[]){let n=[];function r(a,s){const l=b.createContext(s);l.displayName=a+"Context";const u=n.length;n=[...n,s];const d=Ci(m=>{var _;const{scope:p,children:g,...w}=m,x=((_=p==null?void 0:p[e])==null?void 0:_[u])||l,E=b.useMemo(()=>w,Object.values(w));return y.jsx(x.Provider,{value:E,children:g})},"Provider");d.displayName=a+"Provider";function h(m,p,g={}){var _;const{optional:w=!1}=g,x=((_=p==null?void 0:p[e])==null?void 0:_[u])||l,E=b.useContext(x);if(E)return E;if(s!==void 0)return s;if(!w)throw new Error(`\`${m}\` must be used within \`${a}\``)}return Ci(h,"useContext"),[d,h]}Ci(r,"createContext");const i=Ci(()=>{const a=n.map(s=>b.createContext(s));return Ci(function(l){const u=(l==null?void 0:l[e])||a;return b.useMemo(()=>({[`__scope${e}`]:{...l,[e]:u}}),[l,u])},"useScope")},"createScope");return i.scopeName=e,[r,f$(i,...t)]}Ci(d$,"createContextScope");function f$(...e){const t=e[0];if(e.length===1)return t;const n=Ci(()=>{const r=e.map(i=>({useScope:i(),scopeName:i.scopeName}));return Ci(function(a){const s=r.reduce((l,{useScope:u,scopeName:d})=>{const m=u(a)[`__scope${d}`];return{...l,...m}},{});return b.useMemo(()=>({[`__scope${t.scopeName}`]:s}),[s])},"useComposedScopes")},"createScope");return n.scopeName=t.scopeName,n}Ci(f$,"composeContextScopes");var Mae=Object.defineProperty,ta=(e,t)=>Mae(e,"name",{value:t,configurable:!0});function h$(e){const t=b.forwardRef((n,r)=>{let{children:i,...a}=n,s=null,l=!1;const u=[];b1(i)&&typeof Ip=="function"&&(i=Ip(i._payload)),b.Children.forEach(i,p=>{var g;if(v$(p)){l=!0;const w=p;let x="child"in w.props?w.props.child:w.props.children;b1(x)&&typeof Ip=="function"&&(x=Ip(x._payload)),s=Rae(w,x),u.push((g=s==null?void 0:s.props)==null?void 0:g.children)}else u.push(p)}),s?s=b.cloneElement(s,void 0,u):!l&&b.Children.count(i)===1&&b.isValidElement(i)&&(s=i);const d=s?g$(s):void 0,h=ry(r,d);if(!s){if(i||i===0)throw new Error(l?jae(e):Dae(e));return i}const m=p$(a,s.props??{});return s.type!==b.Fragment&&(m.ref=r?h:d),b.cloneElement(s,m)});return t.displayName=`${e}.Slot`,t}ta(h$,"createSlot");var m$=Symbol.for("radix.slottable");function Iae(e){const t=ta(n=>"child"in n?n.children(n.child):n.children,"Slottable");return t.displayName=`${e}.Slottable`,t.__radixId=m$,t}ta(Iae,"createSlottable");var Rae=ta((e,t)=>{if("child"in e.props){const n=e.props.child;return b.isValidElement(n)?b.cloneElement(n,void 0,e.props.children(n.props.children)):null}return b.isValidElement(t)?t:null},"getSlottableElementFromSlottable");function p$(e,t){const n={...t};for(const r in t){const i=e[r],a=t[r];/^on[A-Z]/.test(r)?i&&a?n[r]=(...l)=>{const u=a(...l);return i(...l),u}:i&&(n[r]=i):r==="style"?n[r]={...i,...a}:r==="className"&&(n[r]=[i,a].filter(Boolean).join(" "))}return{...e,...n}}ta(p$,"mergeProps");function g$(e){var r,i;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(i=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:i.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}ta(g$,"getElementRef");function v$(e){return b.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===m$}ta(v$,"isSlottable");var Pae=Symbol.for("react.lazy");function b1(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===Pae&&"_payload"in e&&y$(e._payload)}ta(b1,"isLazyComponent");function y$(e){return typeof e=="object"&&e!==null&&"then"in e}ta(y$,"isPromiseLike");var Dae=ta(e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,"createSlotError"),jae=ta(e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,"createSlottableError"),Ip=ja[" use ".trim().toString()],Lae=Object.defineProperty,zae=(e,t)=>Lae(e,"name",{value:t,configurable:!0}),$ae=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],b$=$ae.reduce((e,t)=>{const n=h$(`Primitive.${t}`),r=b.forwardRef((i,a)=>{const{asChild:s,...l}=i,u=s?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),y.jsx(u,{...l,ref:a})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function Bae(e,t){e&&La.flushSync(()=>e.dispatchEvent(t))}zae(Bae,"dispatchDiscreteCustomEvent");var Uae=Object.defineProperty,Fae=(e,t)=>Uae(e,"name",{value:t,configurable:!0});function x$(e){const t=b.useRef(e);return b.useEffect(()=>{t.current=e}),b.useMemo(()=>((...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)}),[])}Fae(x$,"useCallbackRef");var Hx=globalThis!=null&&globalThis.document?b.useLayoutEffect:()=>{},Hae=globalThis!=null&&globalThis.document?b.useLayoutEffect:()=>{},Kae=Object.defineProperty,qae=(e,t)=>Kae(e,"name",{value:t,configurable:!0});function w$(e){const[t,n]=b.useState(void 0);return Hae(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(i=>{if(!Array.isArray(i)||!i.length)return;const a=i[0];let s,l;if("borderBoxSize"in a){const u=a.borderBoxSize,d=Array.isArray(u)?u[0]:u;s=d.inlineSize,l=d.blockSize}else s=e.offsetWidth,l=e.offsetHeight;n({width:s,height:l})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}qae(w$,"useSize");var Gae=Object.defineProperty,js=(e,t)=>Gae(e,"name",{value:t,configurable:!0}),E$="Popper",[S$,_$]=d$(E$),[Vae,A$]=S$(E$),Wae=js(e=>{const{__scopePopper:t,children:n}=e,[r,i]=b.useState(null),[a,s]=b.useState(void 0);return y.jsx(Vae,{scope:t,anchor:r,onAnchorChange:i,placementState:a,setPlacementState:s,children:n})},"Popper"),Yae="PopperAnchor",Xae=b.forwardRef(js(function(t,n){const{__scopePopper:r,virtualRef:i,...a}=t,s=A$(Yae,r),l=b.useRef(null),u=s.onAnchorChange,d=b.useCallback(x=>{l.current=x,x&&u(x)},[u]),h=ry(n,d),m=b.useRef(null);b.useEffect(()=>{if(!i)return;const x=m.current;m.current=i.current,x!==m.current&&u(m.current)});const p=s.placementState&&iy(s.placementState),g=p==null?void 0:p[0],w=p==null?void 0:p[1];return i?null:y.jsx(b$.div,{"data-radix-popper-side":g,"data-radix-popper-align":w,...a,ref:h})},"PopperAnchor")),k$="PopperContent",[Zae,sCe]=S$(k$),Qae=b.forwardRef(js(function(t,n){var fe,Ee,Te,de,nt,He,Ae;const{__scopePopper:r,side:i="bottom",sideOffset:a=0,align:s="center",alignOffset:l=0,arrowPadding:u=0,avoidCollisions:d=!0,collisionBoundary:h=[],collisionPadding:m=0,sticky:p="partial",hideWhenDetached:g=!1,updatePositionStrategy:w="optimized",onPlaced:x,...E}=t,_=A$(k$,r),[k,O]=b.useState(null),N=ry(n,O),[C,T]=b.useState(null),M=w$(C),D=(M==null?void 0:M.width)??0,j=(M==null?void 0:M.height)??0,R=i+(s!=="center"?"-"+s:""),H=typeof m=="number"?m:{top:0,right:0,bottom:0,left:0,...m},P=Array.isArray(h)?h:[h],G=P.length>0,q={padding:H,boundary:P.filter(O$),altBoundary:G},{refs:X,floatingStyles:U,placement:K,isPositioned:F,middlewareData:V}=bae({strategy:"fixed",placement:R,whileElementsMounted:js((...De)=>cae(...De,{animationFrame:w==="always"}),"whileElementsMounted"),elements:{reference:_.anchor},middleware:[wae({mainAxis:a+j,alignmentAxis:l}),d&&Eae({mainAxis:!0,crossAxis:!1,limiter:p==="partial"?Sae():void 0,...q}),d&&_ae({...q}),Aae({...q,apply:js(({elements:De,rects:Ht,availableWidth:un,availableHeight:Yn})=>{const{width:Or,height:ji}=Ht.reference,ir=De.floating.style;ir.setProperty("--radix-popper-available-width",`${un}px`),ir.setProperty("--radix-popper-available-height",`${Yn}px`),ir.setProperty("--radix-popper-anchor-width",`${Or}px`),ir.setProperty("--radix-popper-anchor-height",`${ji}px`)},"apply")}),C&&Oae({element:C,padding:u}),Jae({arrowWidth:D,arrowHeight:j}),g&&kae({strategy:"referenceHidden",...q,boundary:G?q.boundary:void 0})]}),$=_.setPlacementState;Hx(()=>($(K),()=>{$(void 0)}),[K,$]);const[L,W]=iy(K),z=x$(x);Hx(()=>{F&&(z==null||z())},[F,z]);const ie=(fe=V.arrow)==null?void 0:fe.x,he=(Ee=V.arrow)==null?void 0:Ee.y,ge=((Te=V.arrow)==null?void 0:Te.centerOffset)!==0,[Se,ze]=b.useState();return Hx(()=>{k&&ze(window.getComputedStyle(k).zIndex)},[k]),y.jsx("div",{ref:X.setFloating,"data-radix-popper-content-wrapper":"",style:{...U,transform:F?U.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Se,"--radix-popper-transform-origin":[(de=V.transformOrigin)==null?void 0:de.x,(nt=V.transformOrigin)==null?void 0:nt.y].join(" "),...((He=V.hide)==null?void 0:He.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:t.dir,children:y.jsx(Zae,{scope:r,placedSide:L,placedAlign:W,onArrowChange:T,arrowX:ie,arrowY:he,shouldHideArrow:ge,children:y.jsx(b$.div,{"data-side":L,"data-align":W,...E,ref:N,style:{...E.style,animation:F?(Ae=E.style)==null?void 0:Ae.animation:"none"}})})})},"PopperContent"));function O$(e){return e!==null}js(O$,"isNotNull");var Jae=js(e=>({name:"transformOrigin",options:e,fn(t){var E,_,k;const{placement:n,rects:r,middlewareData:i}=t,s=((E=i.arrow)==null?void 0:E.centerOffset)!==0,l=s?0:e.arrowWidth,u=s?0:e.arrowHeight,[d,h]=iy(n),m={start:"0%",center:"50%",end:"100%"}[h],p=(((_=i.arrow)==null?void 0:_.x)??0)+l/2,g=(((k=i.arrow)==null?void 0:k.y)??0)+u/2;let w="",x="";return d==="bottom"?(w=s?m:`${p}px`,x=`${-u}px`):d==="top"?(w=s?m:`${p}px`,x=`${r.floating.height+u}px`):d==="right"?(w=`${-u}px`,x=s?m:`${g}px`):d==="left"&&(w=`${r.floating.width+u}px`,x=s?m:`${g}px`),{data:{x:w,y:x}}}}),"transformOrigin");function iy(e){const[t,n="center"]=e.split("-");return[t,n]}js(iy,"getSideAndAlignFromPlacement");var eoe=Wae,toe=Xae,noe=Qae,roe=globalThis!=null&&globalThis.document?b.useLayoutEffect:()=>{},ioe=Object.defineProperty,aoe=(e,t)=>ioe(e,"name",{value:t,configurable:!0}),ooe=b.forwardRef(aoe(function(t,n){var u;const{container:r,...i}=t,[a,s]=b.useState(!1);roe(()=>s(!0),[]);const l=r||a&&((u=globalThis==null?void 0:globalThis.document)==null?void 0:u.body);return l?La.createPortal(y.jsx(Xv.div,{...i,ref:n}),l):null},"Portal")),eI=globalThis!=null&&globalThis.document?b.useLayoutEffect:()=>{},soe=Object.defineProperty,To=(e,t)=>soe(e,"name",{value:t,configurable:!0});function N$(e,t){return b.useReducer((n,r)=>t[n][r]??n,e)}To(N$,"useStateMachine");var C$=To(e=>{const{present:t,children:n}=e,r=T$(t),i=typeof n=="function"?n({present:r.isPresent}):b.Children.only(n),a=M$(r.ref,I$(i));return typeof n=="function"||r.isPresent?b.cloneElement(i,{ref:a}):null},"Presence");function T$(e){const[t,n]=b.useState(),r=b.useRef(null),i=b.useRef(e),a=b.useRef("none"),s=b.useRef(void 0),l=e?"mounted":"unmounted",[u,d]=N$(l,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return b.useEffect(()=>{u==="mounted"?(a.current=s.current??bu(r.current),s.current=void 0):a.current="none"},[u]),eI(()=>{const h=r.current,m=i.current;if(m!==e){const g=a.current,w=bu(h);e?(s.current=w,d("MOUNT")):w==="none"||(h==null?void 0:h.display)==="none"?d("UNMOUNT"):d(m&&g!==w?"ANIMATION_OUT":"UNMOUNT"),i.current=e}},[e,d]),eI(()=>{if(t){let h;const m=t.ownerDocument.defaultView??window,p=To(w=>{const E=bu(r.current).includes(CSS.escape(w.animationName));if(w.target===t&&E&&(d("ANIMATION_END"),!i.current)){const _=t.style.animationFillMode;t.style.animationFillMode="forwards",h=m.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=_)})}},"handleAnimationEnd"),g=To(w=>{w.target===t&&(a.current=bu(r.current))},"handleAnimationStart");return t.addEventListener("animationstart",g),t.addEventListener("animationcancel",p),t.addEventListener("animationend",p),()=>{m.clearTimeout(h),t.removeEventListener("animationstart",g),t.removeEventListener("animationcancel",p),t.removeEventListener("animationend",p)}}else d("ANIMATION_END")},[t,d]),{isPresent:["mounted","unmountSuspended"].includes(u),ref:b.useCallback(h=>{if(h){const m=getComputedStyle(h);r.current=m,s.current=bu(m)}else r.current=null;n(h)},[])}}To(T$,"usePresence");function x1(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}To(x1,"setRef");function M$(...e){const t=b.useRef(e);return t.current=e,b.useCallback(n=>{const r=t.current;let i=!1;const a=r.map(s=>{const l=x1(s,n);return!i&&typeof l=="function"&&(i=!0),l});if(i)return()=>{for(let s=0;s<a.length;s++){const l=a[s];typeof l=="function"?l():x1(r[s],null)}}},[])}To(M$,"useStableComposedRefs");function bu(e){return(e==null?void 0:e.animationName)||"none"}To(bu,"getAnimationName");function I$(e){var r,i;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(i=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:i.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}To(I$,"getElementRef");var R$=globalThis!=null&&globalThis.document?b.useLayoutEffect:()=>{},loe=Object.defineProperty,coe=(e,t)=>loe(e,"name",{value:t,configurable:!0}),tI=ja[" useEffectEvent ".trim().toString()],nI=ja[" useInsertionEffect ".trim().toString()];function P$(e){if(typeof tI=="function")return tI(e);const t=b.useRef(()=>{throw new Error("Cannot call an event handler while rendering.")});return typeof nI=="function"?nI(()=>{t.current=e}):R$(()=>{t.current=e}),b.useMemo(()=>((...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)}),[])}coe(P$,"useEffectEvent");var uoe=Object.defineProperty,Nh=(e,t)=>uoe(e,"name",{value:t,configurable:!0}),doe=ja[" useInsertionEffect ".trim().toString()]||R$;function D$({prop:e,defaultProp:t,onChange:n=Nh(()=>{},"onChange"),caller:r}){const[i,a,s]=j$({defaultProp:t,onChange:n}),l=e!==void 0,u=l?e:i,d=b.useCallback(h=>{var m;if(l){const p=L$(h)?h(e):h;p!==e&&((m=s.current)==null||m.call(s,p))}else a(h)},[l,e,a,s]);return[u,d]}Nh(D$,"useControllableState");function j$({defaultProp:e,onChange:t}){const[n,r]=b.useState(e),i=b.useRef(n),a=b.useRef(t);return doe(()=>{a.current=t},[t]),b.useEffect(()=>{var s;i.current!==n&&((s=a.current)==null||s.call(a,n),i.current=n)},[n,i]),[n,r,a]}Nh(j$,"useUncontrolledState");function L$(e){return typeof e=="function"}Nh(L$,"isFunction");var rI=Symbol("RADIX:SYNC_STATE");function foe(e,t,n,r){const{prop:i,defaultProp:a,onChange:s,caller:l}=t,u=i!==void 0,d=P$(s),h=[{...n,state:a}];r&&h.push(r);const[m,p]=b.useReducer((E,_)=>{if(_.type===rI)return{...E,state:_.state};const k=e(E,_);return u&&!Object.is(k.state,E.state)&&d(k.state),k},...h),g=m.state,w=b.useRef(g);b.useEffect(()=>{w.current!==g&&(w.current=g,u||d(g))},[g,w,u]);const x=b.useMemo(()=>i!==void 0?{...m,state:i}:m,[m,i]);return b.useEffect(()=>{u&&!Object.is(i,m.state)&&p({type:rI,state:i})},[i,m.state,u]),[x,p]}Nh(foe,"useControllableStateReducer");var hoe=Object.defineProperty,Js=(e,t)=>hoe(e,"name",{value:t,configurable:!0}),jS="Popover",[z$,lCe]=Dz(jS,[_$]),LS=_$(),[moe,ld]=z$(jS),poe=Js(e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:i,onOpenChange:a,modal:s=!1}=e,l=LS(t),u=b.useRef(null),[d,h]=b.useState(!1),[m,p]=D$({prop:r,defaultProp:i??!1,onChange:a,caller:jS});return y.jsx(eoe,{...l,children:y.jsx(moe,{scope:t,contentId:Qz(),triggerRef:u,open:m,onOpenChange:p,onOpenToggle:b.useCallback(()=>p(g=>!g),[p]),hasCustomAnchor:d,onCustomAnchorAdd:b.useCallback(()=>h(!0),[]),onCustomAnchorRemove:b.useCallback(()=>h(!1),[]),modal:s,children:n})})},"Popover"),goe="PopoverTrigger",voe=b.forwardRef(Js(function(t,n){const{__scopePopover:r,...i}=t,a=ld(goe,r),s=LS(r),l=ad(n,a.triggerRef),u=y.jsx(Xv.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.open?a.contentId:void 0,"data-state":zS(a.open),...i,ref:l,onClick:Ds(t.onClick,a.onOpenToggle)});return a.hasCustomAnchor?u:y.jsx(toe,{asChild:!0,...s,children:u})},"PopoverTrigger")),$$="PopoverPortal",[yoe,boe]=z$($$,{forceMount:void 0}),xoe=Js(e=>{const{__scopePopover:t,forceMount:n,children:r,container:i}=e,a=ld($$,t);return y.jsx(yoe,{scope:t,forceMount:n,children:y.jsx(C$,{present:n||a.open,children:y.jsx(ooe,{asChild:!0,container:i,children:r})})})},"PopoverPortal"),ih="PopoverContent",woe=b.forwardRef(Js(function(t,n){const r=boe(ih,t.__scopePopover),{forceMount:i=r.forceMount,...a}=t,s=ld(ih,t.__scopePopover);return y.jsx(C$,{present:i||s.open,children:s.modal?y.jsx(Soe,{...a,ref:n}):y.jsx(_oe,{...a,ref:n})})},"PopoverContent")),Eoe=_S("PopoverContent.RemoveScroll"),Soe=b.forwardRef(Js(function(t,n){const r=ld(ih,t.__scopePopover),i=b.useRef(null),a=ad(n,i),s=b.useRef(!1);return b.useEffect(()=>{const l=i.current;if(l)return gz(l)},[]),y.jsx(vS,{as:Eoe,allowPinchZoom:!0,children:y.jsx(B$,{...t,ref:a,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Ds(t.onCloseAutoFocus,l=>{var u;l.preventDefault(),s.current||(u=r.triggerRef.current)==null||u.focus()}),onPointerDownOutside:Ds(t.onPointerDownOutside,l=>{const u=l.detail.originalEvent,d=u.button===0&&u.ctrlKey===!0,h=u.button===2||d;s.current=h},{checkForDefaultPrevented:!1}),onFocusOutside:Ds(t.onFocusOutside,l=>l.preventDefault(),{checkForDefaultPrevented:!1})})})},"PopoverContentModal")),_oe=b.forwardRef(Js(function(t,n){const r=ld(ih,t.__scopePopover),i=b.useRef(!1),a=b.useRef(!1);return y.jsx(B$,{...t,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{var l,u;(l=t.onCloseAutoFocus)==null||l.call(t,s),s.defaultPrevented||(i.current||(u=r.triggerRef.current)==null||u.focus(),s.preventDefault()),i.current=!1,a.current=!1},onInteractOutside:s=>{var d,h;(d=t.onInteractOutside)==null||d.call(t,s),s.defaultPrevented||(i.current=!0,s.detail.originalEvent.type==="pointerdown"&&(a.current=!0));const l=s.target;((h=r.triggerRef.current)==null?void 0:h.contains(l))&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&a.current&&s.preventDefault()}})},"PopoverContentNonModal")),B$=b.forwardRef(Js(function(t,n){const{__scopePopover:r,trapFocus:i,onOpenAutoFocus:a,onCloseAutoFocus:s,disableOutsidePointerEvents:l,onEscapeKeyDown:u,onPointerDownOutside:d,onFocusOutside:h,onInteractOutside:m,...p}=t,g=ld(ih,r),w=LS(r);return OS(),y.jsx(vie,{asChild:!0,loop:!0,trapped:i,onMountAutoFocus:a,onUnmountAutoFocus:s,children:y.jsx(cie,{asChild:!0,disableOutsidePointerEvents:l,onInteractOutside:m,onEscapeKeyDown:u,onPointerDownOutside:d,onFocusOutside:h,onDismiss:()=>g.onOpenChange(!1),deferPointerDownOutside:!0,children:y.jsx(noe,{"data-state":zS(g.open),role:"dialog",id:g.contentId,...w,...p,ref:n,style:{...p.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})},"PopoverContentImpl"));function zS(e){return e?"open":"closed"}Js(zS,"getState");var Aoe=poe,koe=voe,Ooe=xoe,U$=woe;const Noe=Aoe,Coe=koe,F$=b.forwardRef(({className:e,align:t="start",side:n="top",sideOffset:r=8,collisionPadding:i=8,...a},s)=>y.jsx(Ooe,{children:y.jsx(U$,{ref:s,align:t,side:n,sideOffset:r,collisionPadding:i,className:Be("z-50 w-64 max-w-[calc(100vw-1rem)] rounded-md border bg-card p-3 text-card-foreground shadow-md outline-none","data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...a})}));F$.displayName=U$.displayName;const H$=92,K$=96;function Kx(e){if(!Number.isFinite(e)||e<0)return"?";const t=["B","KB","MB","GB","TB","PB"];let n=0;for(;e>=1024&&n<t.length-1;)e/=1024,n++;return`${e<10&&n>0?e.toFixed(1):Math.round(e)} ${t[n]}`}const iI=3e5;function Toe({socket:e,getToken:t}){const[n,r]=b.useState([]);if(b.useEffect(()=>{t().then(a=>a?fetch("/api/stats",{headers:{Authorization:`Bearer ${a}`}}):null).then(a=>a==null?void 0:a.json()).then(a=>(a==null?void 0:a.samples)&&r(a.samples)).catch(a=>console.warn("[MachineStats] seed failed",a))},[t]),b.useEffect(()=>{if(!e)return;const a=e.on(s=>{s.type==="stats"&&r(l=>[...l,s.sample].slice(-120))});return()=>{a()}},[e]),!n.length)return null;const i=n[n.length-1];return y.jsxs("div",{className:"w-full flex flex-wrap items-center justify-center gap-x-2 gap-y-0.5 text-[10px] text-muted-foreground/60",children:[y.jsx(sg,{label:"cpu",value:i.cpu,series:n.map(a=>a.cpu)}),y.jsx(sg,{label:"mem",value:i.mem,series:n.map(a=>a.mem)}),i.disk>=0&&y.jsx(sg,{label:"disk",value:i.disk,severity:zoe(i.disk),title:Boe(i)}),y.jsx(Moe,{getToken:t})]})}function Moe({getToken:e}){const[t,n]=b.useState(null);return b.useEffect(()=>{let r=!0,i=0;const a=async()=>{var d;try{const h=await e();if(!h)return;i=Date.now();const m=await fetch("/api/claude-usage",{headers:{Authorization:`Bearer ${h}`}});if(!r)return;if(m.status===204){n(null);return}if(m.status!==200)return;const p=await m.json();if(!r||!((d=p==null?void 0:p.limits)!=null&&d.length))return;n(p)}catch(h){console.warn("[MachineStats] claude usage poll failed",h)}},s=()=>{document.visibilityState==="visible"&&a()},l=()=>{document.visibilityState==="visible"&&Date.now()-i>=iI&&a()};s();const u=setInterval(s,iI);return document.addEventListener("visibilitychange",l),()=>{r=!1,clearInterval(u),document.removeEventListener("visibilitychange",l)}},[e]),y.jsx(Ioe,{usage:t})}function Ioe({usage:e}){const t=e&&q$(e.limits),[n,r]=b.useState(w1),i=b.useRef(null),a=()=>{i.current&&(clearTimeout(i.current),i.current=null)},s=b.useCallback((l,u=0)=>{if(a(),!u){r(d=>oI(d,l));return}i.current=setTimeout(()=>{i.current=null,r(d=>oI(d,l))},u)},[]);return b.useEffect(()=>a,[]),!e||!t?null:y.jsxs(Noe,{open:n.open,onOpenChange:l=>s(l?{type:"activate"}:{type:"dismiss"}),children:[y.jsx(Coe,{asChild:!0,children:y.jsx("button",{type:"button","aria-label":"claude usage breakdown",className:"cursor-default rounded-sm outline-none focus-visible:ring-1 focus-visible:ring-ring",onPointerEnter:l=>s({type:"pointerenter",pointerType:l.pointerType},Roe),onPointerLeave:l=>s({type:"pointerleave",pointerType:l.pointerType},aI),children:y.jsx(sg,{label:"usage",value:t.percent,severity:t.severity})})}),y.jsx(F$,{onOpenAutoFocus:l=>l.preventDefault(),onPointerEnter:()=>a(),onPointerLeave:l=>s({type:"pointerleave",pointerType:l.pointerType},aI),children:y.jsx(Poe,{usage:e})})]})}const Roe=120,aI=80,w1={open:!1,byHover:!1};function oI(e,t){switch(t.type){case"pointerenter":return sI(t.pointerType)?{open:!0,byHover:!0}:e;case"pointerleave":return sI(t.pointerType)&&e.byHover?w1:e;case"activate":return{open:!0,byHover:!1};case"dismiss":return w1}}const sI=e=>e==="mouse"||e==="";function Poe({usage:e}){const t=q$(e.limits);return y.jsxs("div",{className:"text-[11px] leading-tight",children:[y.jsxs("div",{className:"flex items-baseline justify-between gap-2 pb-2 text-muted-foreground",children:[y.jsx("span",{className:"uppercase tracking-wide",children:"claude usage"}),e.subscriptionType&&y.jsxs("span",{className:"tabular-nums",children:[e.subscriptionType," plan"]})]}),y.jsxs("div",{className:"-mt-1 flex items-baseline justify-between gap-2 pb-2 text-[10px] text-muted-foreground",children:[e.account&&y.jsx("span",{className:"truncate",title:e.account,children:e.account}),y.jsx("span",{className:Be("shrink-0",e.stale&&"text-amber-500"),children:joe(e)})]}),e.stale&&e.error&&y.jsxs("div",{"data-refresh-error":!0,className:"-mt-1 pb-2 text-[10px] text-amber-500 break-words",children:[e.error,ag(e.retryAt??null)&&` · retrying in ${ag(e.retryAt??null)}`]}),y.jsx("div",{className:"flex flex-col gap-3",children:e.limits.map((n,r)=>{const i=ag(n.resetsAt),a=n===t;return y.jsxs("div",{"data-headline":a||void 0,className:Be("flex flex-col gap-1",!a&&"opacity-60"),children:[y.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[y.jsxs("span",{className:Be("truncate",a&&"font-medium"),children:[a&&y.jsx("span",{className:"mr-1 text-muted-foreground","aria-hidden":!0,children:"▸"}),Doe(n)]}),y.jsxs("span",{className:Be("tabular-nums shrink-0",E1(n.percent,n.severity)),children:[n.percent,"%"]})]}),y.jsx(G$,{value:n.percent,className:Be("w-full",E1(n.percent,n.severity))}),y.jsx("span",{className:"text-[10px] text-muted-foreground",children:i?`resets in ${i}`:"no reset reported"})]},`${n.kind}-${r}`)})}),y.jsx("div",{className:"mt-3 border-t pt-2 text-[10px] text-muted-foreground",children:"▸ is the window the strip is showing"})]})}function Doe(e){return e.scopeLabel?`${e.scopeLabel} window`:e.kind==="session"?"current session":e.kind==="weekly_all"?"all models":e.kind.replace(/_/g," ")}function q$(e){return e.reduce((t,n)=>!t||n.percent>t.percent?n:t,null)}function joe(e){const t=Loe(e.fetchedAt);return t?e.stale?`${t} old — refresh failed`:`updated ${t} ago`:e.stale?"last reading — refresh failed":"updated just now"}function Loe(e){if(!e)return null;const t=Date.now()-new Date(e).getTime();if(!Number.isFinite(t))return null;const n=Math.round(Math.max(0,t)/6e4);if(n<1)return null;if(n<60)return`${n}m`;const r=Math.floor(n/60),i=n%60;return r<24?i?`${r}h ${i}m`:`${r}h`:`${Math.floor(r/24)}d`}function zoe(e){return e>=K$?"critical":e>=H$?"warning":"ok"}const $oe={critical:"text-red-500",exceeded:"text-red-500",warning:"text-amber-500",warn:"text-amber-500",ok:"text-emerald-500"};function E1(e,t){const n=t?$oe[t]:void 0;return n||(e>=90?"text-red-500":e>=75?"text-amber-500":"text-emerald-500")}function Boe(e){const t=`warn at ${H$}%, critical at ${K$}%`;if(e.diskUsedBytes==null||e.diskTotalBytes==null)return`disk ${e.disk}% used — ${t}`;const n=Math.max(0,e.diskTotalBytes-e.diskUsedBytes);return`disk ${e.disk}% used — ${Kx(e.diskUsedBytes)} of ${Kx(e.diskTotalBytes)}, ${Kx(n)} free — ${t}`}function sg({label:e,value:t,series:n,title:r,severity:i}){const a=E1(t,i),s=r??(n?`${e} ${t}% — last ${n.length} samples`:void 0);return y.jsxs("span",{className:"flex items-center gap-1",title:s,children:[y.jsx("span",{className:"uppercase tracking-wide",children:e}),n?y.jsx(Uoe,{series:n,className:a}):y.jsx(G$,{value:t,className:a}),y.jsxs("span",{className:Be("tabular-nums",a),children:[t,"%"]})]})}function G$({value:e,className:t}){const i=Math.max(0,Math.min(100,e))/100*40;return y.jsxs("svg",{width:40,height:12,viewBox:"0 0 40 12",className:Be("overflow-visible",t),preserveAspectRatio:"none",children:[y.jsx("rect",{x:0,y:12/2-2,width:40,height:4,rx:2,fill:"currentColor",opacity:.2}),i>0&&y.jsx("rect",{x:0,y:12/2-2,width:i,height:4,rx:2,fill:"currentColor"})]})}function Uoe({series:e,className:t}){const i=e.length;if(i<2)return null;const a=e.map((s,l)=>{const u=i>1?l/(i-1)*40:0,d=12-Math.max(0,Math.min(100,s))/100*12;return`${u.toFixed(1)},${d.toFixed(1)}`}).join(" ");return y.jsx("svg",{width:40,height:12,viewBox:"0 0 40 12",className:Be("overflow-visible",t),preserveAspectRatio:"none",children:y.jsx("polyline",{points:a,fill:"none",stroke:"currentColor",strokeWidth:1,strokeLinejoin:"round",strokeLinecap:"round"})})}const kf=50;function Foe({getToken:e,filter:t,refreshKey:n,hydrateIds:r}){const[i,a]=b.useState([]),[s,l]=b.useState(null),[u,d]=b.useState(!1),[h,m]=b.useState({}),p=b.useRef(new Set),g=b.useRef(null),w=b.useRef(null),x=b.useRef(t);x.current=t;const E=b.useRef(kf),_=b.useRef(t);_.current!==t&&(_.current=t,E.current=kf);const k=b.useCallback(async(M,D)=>{const j=await e();if(!j||D!=null&&D.aborted)return null;const R=await fetch(`/api/sessions?${new URLSearchParams(M)}`,{signal:D,headers:{Authorization:`Bearer ${j}`}});if(!R.ok)return null;const H=await R.json();return Array.isArray(H==null?void 0:H.sessions)?H:null},[e]),O=b.useCallback(async(M,D,j)=>{const R=[];let H,P=null;for(;R.length<M;){const G={filter:D,limit:String(Math.min(kf,M-R.length))};H&&(G.before=H);const q=await k(G,j);if(!q)return null;if(R.push(...q.sessions),P=q.nextCursor,!P||!q.sessions.length)break;H=P}return{sessions:R,nextCursor:P}},[k]);b.useEffect(()=>{var D,j;(D=g.current)==null||D.abort(),(j=w.current)==null||j.abort();const M=new AbortController;return g.current=M,d(!0),p.current.clear(),m({}),O(E.current,t,M.signal).then(R=>{!R||M.signal.aborted||(a(R.sessions),l(R.nextCursor))}).catch(()=>{}).finally(()=>{M.signal.aborted||d(!1)}),()=>M.abort()},[O,t,n]);const N=b.useCallback(()=>{var j;if(!s||u)return;(j=w.current)==null||j.abort();const M=new AbortController;w.current=M;const D=x.current;d(!0),k({filter:D,limit:String(kf),before:s},M.signal).then(R=>{!R||M.signal.aborted||D!==x.current||(a(H=>{const P=new Set(H.map(q=>q.sessionId)),G=[...H,...R.sessions.filter(q=>!P.has(q.sessionId))];return E.current=Math.max(kf,G.length),G}),l(R.nextCursor))}).catch(()=>{}).finally(()=>{M.signal.aborted||d(!1)})},[s,u,k]),C=b.useMemo(()=>{const M=new Map;for(const D of Object.values(h))M.set(D.sessionId,D);for(const D of i)M.set(D.sessionId,D);return M},[i,h]),T=r.join(",");return b.useEffect(()=>{const M=r.filter(j=>!!j&&!C.has(j)&&!p.current.has(j)).slice(0,200);if(!M.length)return;for(const j of M)p.current.add(j);let D=!1;return k({ids:M.join(",")}).then(j=>{!j||D||m(R=>{const H={...R};for(const P of j.sessions)H[P.sessionId]=P;return H})}).catch(()=>{}),()=>{D=!0}},[T,C,k]),{sessions:i,cursor:s,loading:u,byId:C,loadMore:N}}const Of="0.1.118";function Hoe(e){const t=Date.now()-e,n=Math.floor(t/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const r=Math.floor(n/60);if(r<24)return`${r}h ago`;const i=Math.floor(r/24);return i<7?`${i}d ago`:new Date(e).toLocaleDateString(void 0,{month:"short",day:"numeric"})}const Nf="w-4 h-4 mt-0.5 shrink-0";function Koe(e){const t=e.slackContext;return(t==null?void 0:t.type)==="dm"?y.jsx(aV,{className:`${Nf} text-purple-400`}):(t==null?void 0:t.type)==="mention"?y.jsx(qG,{className:`${Nf} text-blue-400`}):(t==null?void 0:t.type)==="channel"?y.jsx(eV,{className:`${Nf} text-green-400`}):e.sessionId.startsWith("slack-")?y.jsx(Gw,{className:`${Nf} text-yellow-400`}):y.jsx(Gw,{className:`${Nf} text-muted-foreground`})}function qoe(e){const t=e.slackContext;return(t==null?void 0:t.type)==="dm"?`DM${t.userName?` · ${t.userName}`:""}`:(t==null?void 0:t.type)==="mention"?`@mention${t.channelName?` · #${t.channelName}`:""}`:(t==null?void 0:t.type)==="channel"?`#${t.channelName||"channel"}`:e.sessionId.startsWith("slack-")?"Slack":null}function Goe(e,t,n){return Object.keys(e).map(r=>t.get(r)).filter(r=>!!r&&(n==="all"||r.mine!==!1))}const lI="chats-filter",cI="chats-unread-filter";function Voe({getToken:e,activeSessionId:t,onSelect:n,onNew:r,refreshKey:i,workspaceRefreshKey:a,onRefreshWorkspace:s,unreads:l={},busySessions:u=new Set,socket:d}){var F;const h=za(),[m,p]=b.useState(()=>localStorage.getItem(lI)||"mine"),[g,w]=b.useState(()=>localStorage.getItem(cI)==="true"),[x,E]=b.useState(""),_=b.useRef(null);function k(V){p(V),localStorage.setItem(lI,V)}function O(){const V=!g;w(V),localStorage.setItem(cI,String(V))}const N=b.useMemo(()=>[t,...Object.keys(l)].filter(V=>!!V),[t,l]),{sessions:C,cursor:T,loading:M,byId:D,loadMore:j}=Foe({getToken:e,filter:m,refreshKey:i,hydrateIds:N}),R=b.useMemo(()=>Goe(l,D,m),[l,D,m]),H=R.length,P=b.useMemo(()=>g?[...R].sort((V,$)=>$.lastModified-V.lastModified):C,[g,R,C]),G=t&&!P.some(V=>V.sessionId===t)?D.get(t):void 0;b.useEffect(()=>{_.current&&_.current.scrollIntoView({block:"nearest"})},[t,P,G]);const q=b.useRef(null),X=b.useRef(j);X.current=j,b.useEffect(()=>{const V=q.current;if(!V||!T||g)return;const $=new IntersectionObserver(L=>{L.some(W=>W.isIntersecting)&&X.current()},{rootMargin:"300px"});return $.observe(V),()=>$.disconnect()},[T,M,g]),b.useEffect(()=>{e().then(V=>V?fetch("/api/version",{headers:{Authorization:`Bearer ${V}`}}):null).then(V=>V==null?void 0:V.json()).then(V=>V&&E(V.version)).catch(()=>{})},[]);const U=!!x&&x!=="unknown"&&Of!=="dev"&&x!==Of;b.useEffect(()=>{U&&console.warn(`[shraga] stale client bundle: built from v${Of}, server runs v${x} — rebuild dist/client`)},[U,x]);function K(V){const $=l[V.sessionId],L=u.has(V.sessionId)||V.runStatus==="running"||V.scheduleRunStatus==="running",W=!L&&(!!V.lastStopReason||V.scheduleRunStatus==="error"||V.scheduleRunStatus==="aborted"),z=L?"border-amber-500":W?"border-red-500":$?"border-blue-500":"",ie=!!(L||W||$);return y.jsx("button",{ref:V.sessionId===t?_:void 0,onClick:()=>n(V.sessionId,V.title),className:Be("w-full text-left px-3 py-2.5 text-sm transition-colors hover:bg-accent/50 group",ie?`rounded-r-lg border-l-[3px] ${z}`:"rounded-lg",t===V.sessionId&&"bg-accent"),children:y.jsxs("div",{className:"flex items-start gap-2",children:[Koe(V),y.jsxs("div",{className:"min-w-0 flex-1",children:[y.jsx("span",{className:Be("block truncate text-sm leading-snug",$&&"font-semibold"),children:V.title||"New session"}),y.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5",children:[y.jsx("span",{className:"text-[10px] text-muted-foreground font-medium",children:qoe(V)||V.userName}),y.jsx("span",{className:"text-[10px] text-muted-foreground/50",children:"·"}),y.jsx("span",{className:"text-[10px] text-muted-foreground",children:Hoe(V.lastModified)})]})]})]})},V.sessionId)}return y.jsxs("div",{className:"flex flex-col h-full bg-muted/30",children:[y.jsx("div",{className:"p-3",children:y.jsxs(we,{variant:"outline",size:"sm",className:"w-full gap-2 justify-start",onClick:r,title:"New Chat (Ctrl+N)",children:[y.jsx(ko,{className:"w-4 h-4"})," New Chat",y.jsx("span",{className:"ml-auto flex items-center gap-0.5 text-[10px] text-muted-foreground/50 font-mono",children:"⌃N"})]})}),y.jsx("div",{className:"border-b shrink-0 flex flex-col max-h-[40vh]",children:y.jsx(Bre,{getToken:e,onRefresh:s,refreshKey:a})}),y.jsxs("div",{className:"flex items-center justify-between px-3 pt-2 pb-1",children:[y.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",children:"Chats"}),y.jsxs("div",{className:"flex gap-0.5",children:[["mine","all"].map(V=>y.jsx("button",{onClick:()=>k(V),className:Be("text-[10px] px-1.5 rounded-full transition-colors capitalize leading-none",m===V?"text-foreground font-medium":"text-muted-foreground/60 hover:text-muted-foreground"),children:V},V)),y.jsxs("button",{onClick:O,className:Be("text-[10px] px-1.5 rounded-full transition-colors leading-none",g?"text-blue-600 dark:text-blue-400 font-medium":"text-muted-foreground/60 hover:text-muted-foreground"),children:["unread",H>0&&y.jsx("span",{className:"inline-block w-1.5 h-1.5 ml-1 rounded-full bg-blue-500 align-middle"})]})]})]}),y.jsx(OL,{className:"flex-1",children:y.jsxs("div",{className:"px-2 pb-2 space-y-0.5",children:[P.length===0&&!G&&y.jsx("p",{className:"text-xs text-muted-foreground px-3 py-6 text-center",children:M?"Loading…":g?"No unread conversations":"No conversations yet"}),G&&K(G),P.map(K),!g&&T&&y.jsx("div",{ref:q,className:"py-3 text-center text-[11px] text-muted-foreground/60",children:M?"Loading older…":"···"})]})}),y.jsxs("div",{className:"px-4 py-2 flex flex-col items-center gap-1",children:[y.jsx(Toe,{socket:d??null,getToken:e}),(F=h.sidebarExtras)==null?void 0:F.call(h),x&&(U?y.jsxs("button",{onClick:()=>location.reload(),title:`This page was built from v${Of}, the server runs v${x} — reload to update`,className:"text-[10px] text-amber-400 hover:text-amber-300 text-center underline decoration-dotted",children:["⚠️ stale page (v",Of," → v",x,") · reload"]}):y.jsxs("div",{className:"text-[10px] text-muted-foreground/50 text-center",children:["v",x]}))]})]})}function ni(e,t){const n=e[e.length-1];if((n==null?void 0:n.role)==="assistant"){if(t.type==="text"||t.type==="thinking"){const r=[...n.blocks],i=r[r.length-1];return(i==null?void 0:i.type)===t.type?(r[r.length-1]={...i,text:i.text+t.text},[...e.slice(0,-1),{...n,blocks:r}]):[...e.slice(0,-1),{...n,blocks:[...r,t]}]}return[...e.slice(0,-1),{...n,blocks:[...n.blocks,t]}]}return[...e,{id:Ms(),role:"assistant",blocks:[t]}]}function uI(e,t,n="text"){const r=e[e.length-1],i={type:n,text:t};return(r==null?void 0:r.role)==="assistant"?[...e.slice(0,-1),{...r,blocks:[...r.blocks,i]}]:[...e,{id:Ms(),role:"assistant",blocks:[i]}]}function V$(e,t,n){for(let r=e.length-1;r>=0;r--){const i=e[r];if(i.role!=="assistant")continue;const a=i.blocks.findIndex(l=>l.type==="tool_use"&&l.toolUseId===t);if(a===-1)continue;const s=[...i.blocks];return s[a]={...s[a],input:n},[...e.slice(0,r),{...i,blocks:s},...e.slice(r+1)]}return e}function Woe(e,t){const[n,r]=b.useState([]),[i,a]=b.useState(!1),[s,l]=b.useState([]),u=b.useRef(t.initialSessionId),d=b.useRef(!1),h=b.useRef(s);h.current=s;const m=b.useRef(t.getToken);m.current=t.getToken;const p=b.useRef(t.onNewSession);p.current=t.onNewSession;const g=b.useRef(t.onDirectivesChanged);g.current=t.onDirectivesChanged;const w=b.useRef(t.onParticipantsChanged);w.current=t.onParticipantsChanged;const x=b.useRef(t.onEvent);x.current=t.onEvent;const E=b.useRef(e);E.current=e;const _=b.useCallback(P=>P!=null&&P===u.current,[]),k=b.useCallback(async()=>{var G;const P=u.current;if(P)try{const X=await(await jl(`/api/sessions/${P}/messages`,m.current)).json();r(nL(X)),a(!!X.busy),(G=w.current)==null||G.call(w,Array.isArray(X.participants)&&X.participants.length>1)}catch{}},[]);b.useEffect(()=>{if(!e)return;const P=e.on(G=>{var X,U,K,F,V,$;(X=x.current)==null||X.call(x,G);const q=G;if(q.type==="compact_marker")return _(q.sessionId)?r(L=>[...L,{id:Ms(),role:"assistant",blocks:[{type:"compact_marker",summary:q.summary??"",compactedCount:q.compactedCount??0}]}]):void 0;switch(G.type){case"thinking_delta":return _(G.sessionId)?r(L=>ni(L,{type:"thinking",text:G.text})):void 0;case"text_delta":return _(G.sessionId)?r(L=>ni(L,{type:"text",text:G.text})):void 0;case"tool_use":return _(G.sessionId)?r(L=>ni(L,{type:"tool_use",tool:G.tool,toolUseId:G.toolUseId,input:G.input})):void 0;case"tool_use_input":return _(G.sessionId)?r(L=>V$(L,G.toolUseId,G.input)):void 0;case"tool_result":return _(G.sessionId)?r(L=>ni(L,{type:"tool_result",toolUseId:G.toolUseId,output:G.output})):void 0;case"tool_result_image":return _(G.sessionId)?r(L=>ni(L,{type:"image",src:G.dataUrl})):void 0;case"permission_request":return _(G.sessionId)?r(L=>ni(L,{type:"permission_request",id:G.id,tool:G.tool,input:G.input})):void 0;case"question_request":return _(G.sessionId)?r(L=>ni(L,{type:"question_request",id:G.id,questions:G.questions})):void 0;case"directives":return d.current?(U=g.current)==null?void 0:U.call(g,G.directives):void 0;case"session_id":return!d.current||u.current?void 0:(u.current=G.sessionId,(K=p.current)==null?void 0:K.call(p,G.sessionId));case"forked":return G.sourceSessionId!==u.current?void 0:(u.current=G.sessionId,(F=p.current)==null?void 0:F.call(p,G.sessionId));case"session_busy":G.sessionId===u.current&&a(G.busy);return;case"session_stream":return G.sessionId!==u.current?void 0:Yoe(r,G.event);case"session_messages_changed":G.sessionId===u.current&&k();return;case"done":{if(G.sessionId!==u.current)return;G.stopReason==="max_turns_reached"&&r(W=>ni(W,{type:"text",text:`
1908
1908
 
1909
1909
  ---
1910
1910
  ⚠️ Reached the maximum number of steps for this turn. Send "continue" to pick up where I left off.`})),(V=p.current)==null||V.call(p,G.sessionId);const L=h.current;if(L.length>0){const W=L.join(`
@@ -2006,4 +2006,4 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
2006
2006
  Account: ${e.email}${e.plan?`
2007
2007
  Plan: ${e.plan}`:""}
2008
2008
  ${n==="personal login"?"Personal login (routed to this user)":"Shared login (the agent box account)"}`;return{localPart:t,plan:e.plan,kind:n,title:r}}function oNe({sessionId:e,config:t,sessionDirectives:n,actualModel:r,actualEngine:i,actualAccount:a,scheduleId:s,onScheduleClick:l}){const[u,d]=b.useState(!1),{provenance:h,engine:m,engineIsNative:p,engineMismatch:g,rawModel:w,billingProvider:x}=iNe({requestedEngine:(n==null?void 0:n.engine)||t.engine,requestedModel:(n==null?void 0:n.model)||t.model,actualEngine:i,actualModel:r}),E=w.replace("claude-",""),_=m&&!p?`${m} · ${E}`:E,k=h==="pending",O=k?" border border-dashed border-current/40 opacity-80":"",N=k?"Nothing has run in this conversation yet — this is what the next turn is set to use.":h==="ran-model"?"Model recorded from the last turn. The engine that ran it was not recorded (this conversation predates engine tracking), so it is not named here.":"Engine and model that actually ran the last turn.",C=!k&&m==="claude-code"?a:void 0,T=m==="claude-code"&&(!!C||t.claudeAuthSource==="subscription"),M=C?aNe(C):void 0,D=x?T?"sub":x==="cursor"?"plan":"metered":"unknown",j=D==="unknown"?"bg-muted text-muted-foreground ring-border":D==="sub"?"bg-emerald-50 text-emerald-700 ring-emerald-600/20 dark:bg-emerald-950/50 dark:text-emerald-300 dark:ring-emerald-400/30":D==="plan"?"bg-amber-50 text-amber-700 ring-amber-600/20 dark:bg-amber-950/50 dark:text-amber-300 dark:ring-amber-400/30":"bg-rose-50 text-rose-700 ring-rose-600/20 dark:bg-rose-950/50 dark:text-rose-300 dark:ring-rose-400/30",R=D==="unknown"?"The engine that ran this turn was not recorded and the model id carries no provider prefix — the billed provider cannot be named from what was stored.":D==="sub"?(M==null?void 0:M.title)??"Claude.ai subscription (OAuth login) — no API key in use":D==="plan"?`Runs on your ${x} API key — usage may draw on your ${x} plan/subscription`:`Runs on your ${x} API key — metered per-token billing`,H=t.permissionMode||"acceptEdits",P=H==="bypassPermissions"?"bypass":H==="plan"?"plan":H==="default"?"prompt":"edits",G=(n==null?void 0:n.thinking)||t.thinking,q=()=>{e&&(navigator.clipboard.writeText(e),d(!0),setTimeout(()=>d(!1),1500))};return y.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[y.jsx("span",{title:N,className:`inline-flex items-center rounded-md bg-blue-50 px-1.5 py-0.5 text-[10px] font-medium text-blue-700 ring-1 ring-inset ring-blue-600/20 dark:bg-blue-950/50 dark:text-blue-300 dark:ring-blue-400/30${O}`,children:k?`→ ${_}`:_}),y.jsxs("span",{title:k?`${N} ${R}`:R,"data-account":M?C.email:void 0,className:`inline-flex min-w-0 items-center whitespace-nowrap rounded-md px-1.5 py-0.5 text-[10px] font-medium ring-1 ring-inset ${j}${O}`,children:[D==="unknown"?"API·?":T?"sub":`API·${x}`,D==="sub"&&M&&y.jsxs(y.Fragment,{children:[y.jsx("span",{"aria-hidden":"true",children:" · "}),y.jsx("span",{className:"max-w-[4.5rem] truncate sm:max-w-[10rem]",children:M.localPart}),M.plan&&y.jsxs("span",{className:"hidden sm:inline",children:[" · ",M.plan]})]})]}),g&&y.jsxs("span",{title:`This session requests the "${g}" engine, but the last turn actually ran on "${m}" — so the chips above report ${m}, and that provider was billed.`,className:"inline-flex items-center rounded-md bg-rose-50 px-1.5 py-0.5 text-[10px] font-medium text-rose-700 ring-1 ring-inset ring-rose-600/20 dark:bg-rose-950/50 dark:text-rose-300 dark:ring-rose-400/30",children:["≠ ",g]}),y.jsx("span",{className:"inline-flex items-center rounded-md bg-amber-50 px-1.5 py-0.5 text-[10px] font-medium text-amber-700 ring-1 ring-inset ring-amber-600/20 dark:bg-amber-950/50 dark:text-amber-300 dark:ring-amber-400/30",children:P}),y.jsxs("span",{className:"inline-flex items-center rounded-md bg-green-50 px-1.5 py-0.5 text-[10px] font-medium text-green-700 ring-1 ring-inset ring-green-600/20 dark:bg-green-950/50 dark:text-green-300 dark:ring-green-400/30",children:[(n==null?void 0:n.turns)??t.maxTurns??50," steps"]}),G&&G!=="disabled"&&y.jsx("span",{className:"inline-flex items-center rounded-md bg-violet-50 px-1.5 py-0.5 text-[10px] font-medium text-violet-700 ring-1 ring-inset ring-violet-600/20 dark:bg-violet-950/50 dark:text-violet-300 dark:ring-violet-400/30",children:"think"}),e&&y.jsxs("button",{onClick:q,className:"inline-flex items-center gap-0.5 rounded-md bg-muted px-1.5 py-0.5 text-[10px] font-mono text-muted-foreground ring-1 ring-inset ring-border hover:bg-accent transition-colors",title:`Session: ${e}
2009
- Click to copy`,children:[e.slice(0,8),u?y.jsx(Wi,{className:"w-2.5 h-2.5"}):y.jsx(Bv,{className:"w-2.5 h-2.5"})]}),s&&y.jsxs("button",{onClick:l,className:"inline-flex items-center gap-0.5 rounded-md bg-purple-50 px-1.5 py-0.5 text-[10px] font-mono text-purple-700 ring-1 ring-inset ring-purple-600/20 dark:bg-purple-950/50 dark:text-purple-300 dark:ring-purple-400/30 hover:bg-purple-100 dark:hover:bg-purple-950/70 transition-colors",title:"Open schedule details",children:[y.jsx(BE,{className:"w-2.5 h-2.5"}),s.slice(0,8)]})]})}function sNe({sessionId:e,agentConfig:t,sessionDirectives:n,sessionLastModel:r,sessionLastEngine:i,sessionLastAccount:a,sessionScheduleId:s,artifactCount:l,getToken:u,onConfigSaved:d,onDirectivesSaved:h,onFork:m,onToggleArtifacts:p,onScheduleClick:g}){return y.jsxs("div",{className:"flex items-center gap-1.5 px-2 sm:px-3 py-1.5 border-b bg-background/60 overflow-x-auto",children:[y.jsx(oNe,{sessionId:e,config:t,sessionDirectives:n,actualModel:r,actualEngine:i,actualAccount:a,scheduleId:s,onScheduleClick:g}),y.jsx("div",{className:"flex-1"}),e&&y.jsx(we,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",onClick:m,title:"Fork conversation",children:y.jsx(cL,{className:"w-3.5 h-3.5"})}),y.jsx(rNe,{getToken:u,onSaved:d,sessionId:e,sessionDirectives:n,onDirectivesSaved:h}),l>0&&y.jsx(we,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",onClick:p,title:"Toggle artifacts panel",children:y.jsx(iV,{className:"w-3.5 h-3.5"})})]})}function lNe({nodeId:e,sessionId:t}){var $;const n=$E(),r=za(),i=b.useRef(null),[a,s]=b.useState(),[l,u]=b.useState([]),d=b.useRef(void 0),[h,m]=b.useState(t),p=b.useRef(h);p.current=h;const g=b.useRef(t).current,[w,x]=b.useState(),[E,_]=b.useState(),[k,O]=b.useState(),[N,C]=b.useState(),[T,M]=b.useState(),[D,j]=b.useState(!1),R=Zoe(h,n.getToken,n.token),H=b.useRef(!1),P=b.useCallback(L=>{n.bumpSidebar(),L!==p.current&&(m(L),n.assignSession(e,L))},[n,e]),G=b.useCallback(L=>{L.type==="artifact"?L.sessionId===p.current&&R.handleArtifactEvent(L):L.type==="directives"?H.current&&(O(void 0),C(void 0),M(void 0)):L.type==="model_resolved"&&L.sessionId===p.current&&(O(L.model),C(L.engine),M(L.account))},[n,e,R]),q=Woe(n.socket,{getToken:n.getToken,initialSessionId:t,onNewSession:P,onDirectivesChanged:x,onParticipantsChanged:j,onEvent:G});H.current=q.busy,b.useEffect(()=>{if(!g)return;let L=!1;return(async()=>{try{const z=await(await jl(`/api/sessions/${g}/messages`,n.getToken)).json();if(L)return;q.setMessages(nL(z)),j(Array.isArray(z.participants)&&z.participants.length>1),z.busy&&q.setBusy(!0)}catch(W){L||console.error("[pane] history load failed:",W)}})(),()=>{L=!0}},[g]),b.useEffect(()=>{if(!h){x(void 0),_(void 0),O(void 0),C(void 0),M(void 0);return}jl(`/api/sessions/${h}/meta`,n.getToken).then(L=>L.json()).then(L=>{x(L.directives),_(L.scheduleId),O(L.lastModel),C(L.lastEngine),M(L.lastAccount),L.runStatus==="running"&&q.setBusy(!0)}).catch(()=>{})},[h,n.getToken]);const X=b.useCallback((L,W,z)=>{var ie;q.sendMessage(L,p.current,z,W,(ie=d.current)==null?void 0:ie.call(d))},[q]),U={sessionId:h,busy:q.busy,socket:n.socket,getToken:n.getToken,setInputCtx:s,setSendOptions:L=>{d.current=L},setInputText:L=>{var W;return(W=i.current)==null?void 0:W.setText(L)},send:(L,W,z)=>q.sendMessage(L,p.current,void 0,void 0,W,(z==null?void 0:z.echo)!==!1),appendAssistant:L=>q.setMessages(W=>W.concat({id:Ms(),role:"assistant",blocks:L})),setStatusItems:u},K=b.useCallback(async L=>{const W=await n.getToken();if(!W)return null;try{return await(await fetch("/api/upload",{method:"POST",headers:{Authorization:`Bearer ${W}`,"x-filename":encodeURIComponent(L.name),"Content-Type":L.type||"application/octet-stream","x-session-id":p.current||""},body:L})).json()}catch(z){return console.error("[upload] Failed:",z),null}},[n]),F=b.useCallback(async L=>{const W=p.current;if(!W)return;const z=await n.getToken();if(z)try{const ie=await fetch(`/api/sessions/${W}/fork`,{method:"POST",headers:{Authorization:`Bearer ${z}`,"Content-Type":"application/json"},body:JSON.stringify(L!=null?{truncateAtIndex:L}:{})});if(!ie.ok){console.error("[fork] server error:",(await ie.json().catch(()=>({}))).error||ie.status);return}const{sessionId:he}=await ie.json();n.bumpSidebar(),n.openSession(he)}catch(ie){console.error("[fork] failed:",ie)}},[n]),V=b.useCallback((L,W,z)=>{if(q.busy)return;const ie=q.messages.findIndex(he=>he.id===L);ie>=0&&q.setMessages(q.messages.slice(0,ie)),X(W,ie>=0?ie:void 0,z)},[q,X]);return y.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[($=r.conversationController)==null?void 0:$.call(r,U),y.jsx(sNe,{sessionId:h,agentConfig:n.agentConfig,sessionDirectives:w,sessionLastModel:k,sessionLastEngine:N,sessionLastAccount:T,sessionScheduleId:E,artifactCount:R.artifacts.length,getToken:n.getToken,onConfigSaved:n.setAgentConfig,onDirectivesSaved:x,onFork:()=>F(),onToggleArtifacts:R.togglePanel,onScheduleClick:n.openSchedules}),y.jsxs("div",{className:"flex-1 flex min-h-0",children:[y.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[y.jsx(OOe,{messages:q.messages,busy:q.busy,multiParticipant:D,connectionStatus:n.connectionStatus??void 0,onPermissionRespond:q.respondPermission,onQuestionRespond:q.respondQuestion,onReplay:V,onEdit:V,onFork:L=>F(L),statusItems:l}),y.jsx(HOe,{ref:i,onSend:(L,W)=>X(L,void 0,W),onSteer:q.steer,onQueue:q.addToQueue,onRemoveQueued:q.removeFromQueue,queue:q.queue,onUpload:K,onCancel:q.cancel,disabled:!1,busy:q.busy,skills:n.skills,workspaceFiles:n.workspaceFiles,sessionId:h,inputCtx:a})]}),R.panelOpen&&R.artifacts.length>0&&h&&y.jsx(qOe,{artifacts:R.artifacts,selectedId:R.selectedId,sessionId:h,getToken:n.getToken,onSelect:R.selectArtifact,onClose:R.closePanel})]})]})}function ZA(e,t=!0){const[n,r]=b.useState();return b.useEffect(()=>{if(!t)return;let i=!0;return e().then(a=>{!a||!i||fetch("/api/config",{headers:{Authorization:`Bearer ${a}`}}).then(s=>{if(!s.ok)throw new Error(`HTTP ${s.status}`);return s.json()}).then(s=>{i&&r(!!s.isOwner)}).catch(s=>console.warn("[isOwner] load failed",s))}),()=>{i=!1}},[t,e]),n}const cNe=()=>({command:"",args:[],env:{}});function DD({getToken:e,trigger:t}){const[n,r]=b.useState({}),[i,a]=b.useState(!1),[s,l]=b.useState(!1),[u,d]=b.useState(null),h=ZA(e,i),m=h===!0,[p,g]=b.useState(new Set),w=M=>g(D=>{const j=new Set(D);return j.has(M)?j.delete(M):j.add(M),j});b.useEffect(()=>{i&&e().then(M=>{M&&fetch("/api/mcps",{headers:{Authorization:`Bearer ${M}`}}).then(D=>{if(!D.ok)throw new Error(`HTTP ${D.status}`);return D.json()}).then(r).catch(D=>console.error("[McpManager] fetch failed",D))})},[i,e]);const x=async()=>{l(!0),d(null);const M=await e();try{const D=await fetch("/api/mcps",{method:"PUT",headers:{Authorization:`Bearer ${M??""}`,"Content-Type":"application/json"},body:JSON.stringify(n)});if(!D.ok)throw new Error((await D.json().catch(j=>(console.warn("[McpManager] error response not JSON",D.status,j),{}))).error||`HTTP ${D.status}`);a(!1)}catch(D){console.error("[McpManager] save failed",D),d(D.message||"Save failed")}finally{l(!1)}},E=()=>{const M=`server-${Date.now()}`;r(D=>({...D,[M]:cNe()}))},_=M=>{r(D=>{const j={...D};return delete j[M],j})},k=(M,D,j)=>{r(R=>({...R,[M]:{...R[M],[D]:D==="args"?j.split(" "):j}}))},O=(M,D,j)=>{r(R=>{const H={...R[M].env},P=H[D]??"";return delete H[D],j.trim()&&(H[j.trim()]=P),{...R,[M]:{...R[M],env:H}}})},N=(M,D,j)=>{r(R=>({...R,[M]:{...R[M],env:{...R[M].env,[D]:j}}}))},C=(M,D)=>{r(j=>{const R={...j[M].env};return delete R[D],{...j,[M]:{...j[M],env:R}}})},T=M=>{const D=`KEY_${Date.now()}`;r(j=>({...j,[M]:{...j[M],env:{...j[M].env,[D]:""}}}))};return y.jsxs(Oo,{open:i,onOpenChange:a,children:[y.jsx(rd,{asChild:!0,children:t||y.jsx(we,{variant:"ghost",size:"icon",title:"MCP Servers",children:y.jsx(dL,{className:"w-4 h-4"})})}),y.jsxs(Na,{className:"max-w-[95vw] sm:max-w-2xl",children:[y.jsx(Bs,{children:y.jsx(No,{children:"MCP Servers"})}),y.jsxs(Cz,{className:"space-y-4",children:[h===!1&&y.jsx("p",{className:"text-xs text-muted-foreground rounded-md bg-muted/50 px-3 py-2",children:"Read-only — only an owner can change MCP servers."}),y.jsxs("fieldset",{disabled:!m,className:"space-y-4 min-w-0",children:[Object.entries(n).map(([M,D])=>{const j=!!D.readonly;return y.jsxs("div",{className:`border rounded-lg p-4 space-y-3 ${j?"opacity-70":""}`,children:[y.jsxs("div",{className:"flex items-center justify-between",children:[y.jsxs("span",{className:"font-medium text-sm flex items-center gap-1.5",children:[j&&y.jsx(tg,{className:"w-3 h-3 text-muted-foreground"}),M]}),!j&&y.jsx(we,{variant:"ghost",size:"icon",onClick:()=>_(M),children:y.jsx(Xi,{className:"w-4 h-4 text-destructive"})})]}),j?y.jsx("p",{className:"text-xs text-muted-foreground",children:"Configured in shraga.config.ts"}):y.jsxs("div",{className:"grid gap-2",children:[y.jsx(ft,{placeholder:"Command (e.g. npx)",value:D.command,onChange:R=>k(M,"command",R.target.value)}),y.jsx(ft,{placeholder:"Args (space-separated)",value:(D.args||[]).join(" "),onChange:R=>k(M,"args",R.target.value)}),Object.entries(D.env||{}).length>0&&y.jsxs("div",{className:"space-y-2",children:[y.jsx("span",{className:"text-xs text-muted-foreground",children:"Environment variables"}),Object.entries(D.env||{}).map(([R,H])=>y.jsxs("div",{className:"flex gap-2 items-center",children:[y.jsx(ft,{className:"w-1/3 font-mono text-xs",value:R,onChange:P=>O(M,R,P.target.value),placeholder:"KEY"}),p.has(`${M}:${R}`)?y.jsx(ft,{className:"flex-1 font-mono text-xs",placeholder:"paste new value",autoFocus:!0,onChange:P=>N(M,R,P.target.value),onBlur:()=>w(`${M}:${R}`)}):y.jsx("span",{className:"flex-1 font-mono text-xs text-muted-foreground truncate cursor-pointer px-3 py-2 border rounded-md bg-background hover:border-ring",onClick:()=>w(`${M}:${R}`),title:"Click to change",children:H||"(empty — click to set)"}),y.jsx(we,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",onClick:()=>C(M,R),children:y.jsx(Xi,{className:"w-3 h-3 text-muted-foreground"})})]},R))]}),y.jsx(we,{variant:"ghost",size:"sm",className:"text-xs text-muted-foreground",onClick:()=>T(M),children:"+ Add env var"})]})]},M)}),Object.keys(n).length===0&&y.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No MCP servers configured"})]}),u&&y.jsx("p",{className:"text-sm text-destructive",children:u})]}),m&&y.jsxs(Tz,{className:"flex gap-2",children:[y.jsxs(we,{variant:"outline",onClick:E,className:"gap-2",children:[y.jsx(ko,{className:"w-4 h-4"})," Add Server"]}),y.jsx(we,{onClick:x,disabled:s,children:s?"Saving…":"Save"})]})]})]})}function QA(e){return typeof e=="string"?e:e.name}function jD(e){return typeof e=="string"?!1:e.capped===!0||typeof e.capped=="number"&&e.capped>0}function Cl(e,t){return e.some(n=>QA(n)===t)}function LD(e,t){return e.find(n=>QA(n)===t)}async function co(e,t,n){return fetch(e,{...n,headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json",...(n==null?void 0:n.headers)??{}}})}function zD({getToken:e,onSkillsChange:t,trigger:n}){const[r,i]=b.useState(!1),[a,s]=b.useState([]),[l,u]=b.useState([]),[d,h]=b.useState([]),[m,p]=b.useState(null),[g,w]=b.useState(""),[x,E]=b.useState(!1),[_,k]=b.useState(null),[O,N]=b.useState(""),[C,T]=b.useState(null),M=ZA(e,r),D=M===!0,R=(m?l.includes(m):!1)||!D,H=async(L,W)=>{if(L.ok)return T(null),!0;const z=(await L.json().catch(ie=>(console.warn(`[SkillsManager] ${W} error response not JSON`,L.status,ie),{}))).error||`HTTP ${L.status}`;return console.warn(`[SkillsManager] ${W} failed`,z),T(`${W} failed: ${z}`),!1},P=async()=>{const L=await e();if(!L)return;const[W,z]=await Promise.all([co("/api/skills",L),co("/api/skills-defaults",L)]),ie=await W.json(),he=await z.json();s(ie.skills),u(ie.builtins),h(he),t==null||t(ie.skills)},G=async L=>{const W=await e();if(!W)return;const ie=await(await co(`/api/skills/${L}`,W)).json();w(ie.content),p(L),E(!1)},q=async()=>{if(!m||R)return;const L=await e();if(!L)return;const W=await co(`/api/skills/${m}`,L,{method:"PUT",body:JSON.stringify({content:g})});await H(W,"Save")&&E(!1)},X=async()=>{const L=O.trim().replace(/\s+/g,"-");if(!L)return;const W=await e();if(W){if(_==="create"){const z=await co(`/api/skills/${L}`,W,{method:"PUT",body:JSON.stringify({content:""})});if(!await H(z,"Create"))return;await P(),await G(L)}else if(_==="duplicate"&&m){const z=await co(`/api/skills/${m}/duplicate`,W,{method:"POST",body:JSON.stringify({newName:L})});if(!await H(z,"Duplicate"))return;await P(),await G(L)}else if(_==="rename"&&m){const z=await co(`/api/skills/${m}/rename`,W,{method:"POST",body:JSON.stringify({newName:L})});if(!await H(z,"Rename"))return;await P(),await G(L)}k(null),N("")}},U=async L=>{const W=await e();if(!W)return;const z=await co(`/api/skills/${L}`,W,{method:"DELETE"});await H(z,"Delete")&&(m===L&&(p(null),w("")),await P())},K=async L=>{const W=await e();if(!W)return;const z=Cl(d,L)?d.filter(he=>QA(he)!==L):[...d,L],ie=await co("/api/skills-defaults",W,{method:"PUT",body:JSON.stringify(z)});await H(ie,"Update defaults")&&h(z)},F=L=>{k(L),N(L==="rename"&&m?m:L==="duplicate"&&m?`${m}-copy`:"")},V=()=>{k(null),N("")};b.useEffect(()=>{r&&P()},[r]);const $=_==="create"?"skill-name":_==="rename"?"new-name":"copy-name";return y.jsxs(Oo,{open:r,onOpenChange:i,children:[y.jsx(rd,{asChild:!0,children:n||y.jsx(we,{variant:"ghost",size:"icon",title:"Skills",className:"h-8 w-8",children:y.jsx(qw,{className:"w-4 h-4"})})}),y.jsxs(Na,{className:"max-w-[95vw] sm:max-w-2xl h-[70dvh] sm:h-[520px] flex flex-col gap-0 p-0",children:[y.jsx(Bs,{className:"px-4 pt-4 pb-2 border-b shrink-0",children:y.jsxs(No,{className:"flex items-center gap-2",children:[y.jsx(qw,{className:"w-4 h-4"})," Skills"]})}),y.jsxs("div",{className:"flex flex-col sm:flex-row flex-1 overflow-hidden",children:[y.jsxs("div",{className:`sm:w-52 border-r flex flex-col shrink-0 ${m?"hidden sm:flex":"flex"}`,children:[y.jsx("div",{className:"flex-1 overflow-y-auto py-1",children:a.map(L=>y.jsxs("div",{className:`group flex items-center gap-1.5 px-3 py-1.5 cursor-pointer text-sm hover:bg-accent transition-colors ${m===L?"bg-accent font-medium":""}`,onClick:()=>G(L),children:[y.jsx("button",{className:`shrink-0 transition-colors ${Cl(d,L)?"text-amber-500":"text-muted-foreground/30"} ${D&&!Cl(d,L)?"hover:text-amber-400":""}`,disabled:!D,onClick:W=>{W.stopPropagation(),D&&K(L)},title:D?Cl(d,L)?"Remove from defaults":"Set as default (always active)":Cl(d,L)?"Default (only an owner can change)":"Only an owner can change defaults",children:y.jsx(xT,{className:`w-3 h-3 ${Cl(d,L)?"fill-current":""}`})}),y.jsxs("span",{className:"truncate flex-1",children:["@",L]}),l.includes(L)&&y.jsx("span",{title:"Built-in (read-only)",children:y.jsx(tg,{className:"w-2.5 h-2.5 text-muted-foreground/40 shrink-0"})}),!l.includes(L)&&D&&y.jsx("button",{className:"opacity-0 group-hover:opacity-100 text-muted-foreground hover:text-destructive transition-opacity shrink-0",onClick:W=>{W.stopPropagation(),U(L)},title:"Delete",children:y.jsx(Xi,{className:"w-3 h-3"})})]},L))}),y.jsxs("div",{className:"border-t p-2",children:[_?y.jsxs("div",{className:"flex gap-1",children:[y.jsx(ft,{value:O,onChange:L=>N(L.target.value),onKeyDown:L=>{L.key==="Enter"&&X(),L.key==="Escape"&&V()},placeholder:$,className:"h-7 text-xs",autoFocus:!0}),y.jsx(we,{size:"icon",className:"h-7 w-7 shrink-0",onClick:X,children:y.jsx(Wi,{className:"w-3 h-3"})}),y.jsx(we,{size:"icon",variant:"ghost",className:"h-7 w-7 shrink-0",onClick:V,children:y.jsx(Ql,{className:"w-3 h-3"})})]}):D?y.jsxs(we,{variant:"outline",size:"sm",className:"w-full h-7 text-xs",onClick:()=>F("create"),children:[y.jsx(ko,{className:"w-3 h-3 mr-1"})," New skill"]}):y.jsx("p",{className:"text-[11px] text-muted-foreground text-center",children:M===!1?"Read-only — only an owner can change skills":""}),C&&y.jsx("p",{className:"text-[11px] text-destructive mt-1 break-words",children:C})]})]}),y.jsx("div",{className:`flex-1 flex flex-col overflow-hidden ${m?"":"hidden sm:flex"}`,children:m?y.jsxs(y.Fragment,{children:[y.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b text-sm shrink-0",children:[y.jsxs("div",{className:"flex items-center gap-0.5 font-medium",children:[y.jsx("button",{className:"sm:hidden mr-1.5 text-muted-foreground",onClick:()=>{p(null),w(""),E(!1)},children:y.jsx(oL,{className:"w-4 h-4"})}),y.jsx("span",{className:"text-muted-foreground",children:"@"}),y.jsx("span",{children:m})]}),y.jsxs("div",{className:"flex items-center gap-1.5",children:[R&&y.jsxs("span",{className:"text-[10px] text-muted-foreground bg-muted px-1.5 py-0.5 rounded font-medium flex items-center gap-0.5",children:[y.jsx(tg,{className:"w-2.5 h-2.5"})," read-only"]}),Cl(d,m)&&y.jsxs(y.Fragment,{children:[y.jsx("span",{className:"text-[10px] text-amber-600 bg-amber-50 dark:bg-amber-950/50 dark:text-amber-400 px-1.5 py-0.5 rounded font-medium",children:"default"}),y.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded font-medium ${jD(LD(d,m))?"text-blue-600 bg-blue-50 dark:bg-blue-950/50 dark:text-blue-400":"text-emerald-600 bg-emerald-50 dark:bg-emerald-950/50 dark:text-emerald-400"}`,children:jD(LD(d,m))?"capped":"full"})]}),D&&y.jsx(we,{variant:"ghost",size:"sm",className:"h-6 text-xs px-1.5",onClick:()=>F("duplicate"),title:"Duplicate",children:y.jsx(Bv,{className:"w-3 h-3"})}),!R&&y.jsx(we,{variant:"ghost",size:"sm",className:"h-6 text-xs px-1.5",onClick:()=>F("rename"),title:"Rename",children:y.jsx(KE,{className:"w-3 h-3"})}),x&&!R&&y.jsxs(we,{size:"sm",className:"h-6 text-xs",onClick:q,children:[y.jsx(Wi,{className:"w-3 h-3 mr-1"})," Save"]})]})]}),y.jsx(Vy,{value:g,onChange:L=>{R||(w(L.target.value),E(!0))},readOnly:R,className:`flex-1 resize-none rounded-none border-0 font-mono text-xs focus-visible:ring-0 ${R?"opacity-70 cursor-default":""}`,placeholder:"Write the skill instructions here…"})]}):y.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center text-muted-foreground text-sm gap-1",children:[y.jsx("p",{children:"Select or create a skill"}),y.jsxs("p",{className:"text-xs",children:[y.jsx(xT,{className:"w-3 h-3 inline fill-amber-500 text-amber-500"})," = injected in every conversation"]}),y.jsxs("p",{className:"text-xs",children:[y.jsx(tg,{className:"w-3 h-3 inline"})," = built-in, duplicate to customize"]})]})})]})]})]})}function uNe(e,t,n=0){const[r,i]=b.useState([]),[a,s]=b.useState([]),[l,u]=b.useState(!1),[d,h]=b.useState(!1),[m,p]=b.useState(null),g=b.useCallback(async()=>{h(!0),p(null);try{const k=await Ki("/api/modules",e,{expect:[404]});i(k.installed??[]),s(k.available??[]),u(!1)}catch(k){/^404\b/.test(k.message)?u(!0):p(k.message)}finally{h(!1)}},[e]);b.useEffect(()=>{t&&g()},[t,g,n]);const w=b.useCallback(async k=>{await Ki("/api/modules/install",e,{method:"POST",body:JSON.stringify(k)}),await g()},[e,g]),x=b.useCallback(async(k,O)=>{await Ki(`/api/modules/${k}/${O?"enable":"disable"}`,e,{method:"POST"}),await g()},[e,g]),E=b.useCallback(async(k,O)=>{await Ki(`/api/modules/${k}/config`,e,{method:"PUT",body:JSON.stringify({config:O})}),await g()},[e,g]),_=b.useCallback(async k=>{await Ki(`/api/modules/${k}`,e,{method:"DELETE"}),await g()},[e,g]);return{installed:r,available:a,unsupported:l,loading:d,error:m,refresh:g,install:w,toggle:x,updateConfig:E,uninstall:_}}function E8({checked:e,onChange:t,title:n,disabled:r}){return y.jsx("button",{type:"button",role:"switch","aria-checked":e,title:n,disabled:r,onClick:()=>t(!e),className:`relative inline-flex h-6 w-11 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors disabled:opacity-50 disabled:cursor-not-allowed ${e?"bg-primary":"bg-muted"}`,children:y.jsx("span",{className:`pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform ${e?"translate-x-5":"translate-x-0"}`})})}function $D(e){const t=Object.keys(e.config??{});return t.length===0?"":t.slice(0,3).map(n=>`${n}: ${String(e.config[n])}`).join(" · ")+(t.length>3?` · +${t.length-3}`:"")}function dNe({schema:e,config:t,onSave:n,saving:r}){const[i,a]=b.useState(()=>{const h={};for(const[m,p]of Object.entries(e)){const g=t[m]??p.default;h[m]=p.type==="boolean"?!!g:g==null?"":String(g)}return h}),[s,l]=b.useState({}),u=(h,m)=>{a(p=>({...p,[h]:m})),l(p=>p[h]?{...p,[h]:""}:p)},d=()=>{const h={},m={};for(const[p,g]of Object.entries(e)){const w=i[p];if(g.type==="boolean"){const E=!!w;if(!E&&t[p]===void 0&&typeof g.default!="boolean")continue;h[p]=E;continue}const x=String(w??"").trim();if(x===""){(g.type==="number"&&typeof g.default=="number"&&Number.isFinite(g.default)||g.type==="string"&&typeof g.default=="string"&&g.default!=="")&&(h[p]=g.default);continue}if(g.type==="number"){const E=Number(x);if(!Number.isFinite(E)){m[p]="Not a number";continue}h[p]=E}else h[p]=x}if(Object.values(m).some(Boolean)){l(m);return}l({}),n(h)};return y.jsxs("div",{className:"space-y-2 pt-2",children:[Object.entries(e).map(([h,m])=>y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx("label",{className:"text-xs w-36 shrink-0 truncate",title:m.description||h,children:h}),m.type==="boolean"?y.jsx(E8,{checked:!!i[h],onChange:p=>u(h,p)}):y.jsxs("div",{className:"flex-1 min-w-0",children:[y.jsx(ft,{type:"text",inputMode:m.type==="number"?"decimal":void 0,value:String(i[h]??""),onChange:p=>u(h,p.target.value),className:`h-7 text-xs w-full ${s[h]?"border-destructive":""}`,placeholder:m.description}),s[h]&&y.jsx("p",{className:"text-[10px] text-destructive mt-0.5",children:s[h]})]})]},h)),y.jsxs(we,{size:"sm",className:"h-6 text-xs",disabled:r,onClick:d,children:[r?y.jsx(Yi,{className:"w-3 h-3 mr-1 animate-spin"}):y.jsx(Wi,{className:"w-3 h-3 mr-1"})," Save config"]})]})}function BD({getToken:e,trigger:t}){const[n,r]=b.useState(!1),{installed:i,available:a,unsupported:s,loading:l,error:u,install:d,toggle:h,updateConfig:m,uninstall:p}=uNe(e,n),[g,w]=b.useState(null),[x,E]=b.useState(null),[_,k]=b.useState(null),O=async(C,T)=>{if(!x){E(C),k(null);try{await T()}catch(M){k(M.message)}finally{E(null)}}},N=a.filter(C=>!C.installed);return y.jsxs(Oo,{open:n,onOpenChange:r,children:[y.jsx(rd,{asChild:!0,children:t||y.jsx(we,{variant:"ghost",size:"icon",title:"Modules",className:"h-8 w-8",children:y.jsx(Kw,{className:"w-4 h-4"})})}),y.jsxs(Na,{className:"max-w-[95vw] sm:max-w-2xl h-[70dvh] sm:h-[520px] flex flex-col gap-0 p-0",children:[y.jsx(Bs,{className:"px-4 pt-4 pb-2 border-b shrink-0",children:y.jsxs(No,{className:"flex items-center gap-2",children:[y.jsx(Kw,{className:"w-4 h-4"})," Modules"]})}),y.jsxs("div",{className:"flex-1 overflow-y-auto p-3 space-y-4",children:[s&&y.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"This server does not support modules yet."}),(u||_)&&y.jsx("p",{className:"text-xs text-destructive",children:_||u}),l&&i.length===0&&!s&&y.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"Loading…"}),!s&&!l&&i.length===0&&N.length===0&&!u&&y.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No modules available."}),i.length>0&&y.jsxs("div",{className:"space-y-2",children:[y.jsx("h3",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Installed"}),i.map(C=>{const T=g===C.name,M=C.configSchema&&Object.keys(C.configSchema).length>0,D=[C.skillCount?`provides ${C.skillCount} skill${C.skillCount===1?"":"s"}`:"",C.scheduleCount?`${C.scheduleCount} schedule${C.scheduleCount===1?"":"s"}`:""].filter(Boolean).join(", ");return y.jsxs("div",{className:"border rounded-lg p-3 space-y-1",children:[y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx(E8,{checked:C.enabled,onChange:j=>O(`toggle-${C.name}`,()=>h(C.name,j)),title:C.enabled?"Disable":"Enable",disabled:x===`toggle-${C.name}`}),y.jsx("span",{className:"font-medium text-sm truncate",children:C.name}),y.jsxs("span",{className:"text-[10px] font-mono px-1.5 py-0.5 rounded bg-muted text-muted-foreground shrink-0",children:["v",C.version]}),!C.enabled&&y.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-muted text-muted-foreground shrink-0",children:"disabled"}),y.jsx("div",{className:"flex-1"}),x===`toggle-${C.name}`&&y.jsx(Yi,{className:"w-3 h-3 animate-spin text-muted-foreground"}),(M||C.readme)&&y.jsx("button",{className:"text-muted-foreground hover:text-foreground transition-colors",onClick:()=>w(T?null:C.name),title:"Details",children:T?y.jsx(VG,{className:"w-3.5 h-3.5"}):y.jsx(Ys,{className:"w-3.5 h-3.5"})}),y.jsx("button",{className:"text-muted-foreground hover:text-destructive transition-colors",onClick:()=>{confirm(`Uninstall module "${C.name}"? Its skills and schedules will be removed (seeds/data stay).`)&&O(`rm-${C.name}`,()=>p(C.name))},title:"Uninstall",children:y.jsx(Xi,{className:"w-3.5 h-3.5"})})]}),C.description&&y.jsx("p",{className:"text-xs text-muted-foreground",children:C.description}),D&&y.jsx("p",{className:"text-[10px] text-muted-foreground",children:D}),!T&&$D(C)&&y.jsx("p",{className:"text-[10px] font-mono text-muted-foreground truncate",children:$D(C)}),T&&C.readme&&y.jsx("pre",{className:"text-[11px] text-muted-foreground whitespace-pre-wrap font-sans bg-muted/40 rounded p-2 max-h-48 overflow-y-auto",children:C.readme}),T&&M&&y.jsx(dNe,{schema:C.configSchema,config:C.config,saving:x===`cfg-${C.name}`,onSave:j=>O(`cfg-${C.name}`,()=>m(C.name,j))},JSON.stringify(C.config))]},C.name)})]}),N.length>0&&y.jsxs("div",{className:"space-y-2",children:[y.jsx("h3",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Available"}),N.map(C=>y.jsxs("div",{className:"border rounded-lg p-3 flex items-center gap-2",children:[y.jsxs("div",{className:"min-w-0 flex-1",children:[y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx("span",{className:"font-medium text-sm truncate",children:C.name}),y.jsxs("span",{className:"text-[10px] font-mono px-1.5 py-0.5 rounded bg-muted text-muted-foreground shrink-0",children:["v",C.version]})]}),C.description&&y.jsx("p",{className:"text-xs text-muted-foreground",children:C.description})]}),y.jsxs(we,{size:"sm",variant:"outline",className:"h-7 text-xs shrink-0",disabled:x===`install-${C.name}`,onClick:()=>O(`install-${C.name}`,()=>d({name:C.name})),children:[x===`install-${C.name}`?y.jsx(Yi,{className:"w-3 h-3 mr-1 animate-spin"}):y.jsx(lL,{className:"w-3 h-3 mr-1"}),"Install"]})]},C.name))]})]})]})]})}async function Tl(e,t,n){const r=await t(),i=await fetch(e,{...n,headers:{Authorization:`Bearer ${r??""}`,"Content-Type":"application/json",...n==null?void 0:n.headers}});if(!i.ok){const a=await i.json().catch(()=>({}));throw new Error(a.error||`${i.status} ${i.statusText}`)}return i.json()}function fNe(e,t,n=0){const[r,i]=b.useState([]),[a,s]=b.useState(new Set),[l,u]=b.useState(!1),[d,h]=b.useState(null),m=b.useCallback(async()=>{u(!0),h(null);try{const k=await Tl("/api/schedules",e);i(k.schedules),s(new Set(k.runningIds))}catch(k){h(k.message)}finally{u(!1)}},[e]);b.useEffect(()=>{t&&m()},[t,m,n]);const p=b.useCallback(async k=>{const O=await Tl("/api/schedules",e,{method:"POST",body:JSON.stringify(k)});return await m(),O},[e,m]),g=b.useCallback(async(k,O)=>{const N=await Tl(`/api/schedules/${k}`,e,{method:"PUT",body:JSON.stringify(O)});return await m(),N},[e,m]),w=b.useCallback(async k=>{await Tl(`/api/schedules/${k}`,e,{method:"DELETE"}),await m()},[e,m]),x=b.useCallback(async(k,O)=>{await Tl(`/api/schedules/${k}/toggle`,e,{method:"POST",body:JSON.stringify({enabled:O})}),await m()},[e,m]),E=b.useCallback(async(k,O)=>{const N=await Tl(`/api/schedules/${k}/run`,e,{method:"POST",body:JSON.stringify(O?{override:O}:{})});return await m(),N.sessionId},[e,m]),_=b.useCallback(async k=>{await Tl(`/api/schedules/${k}/cancel`,e,{method:"POST"}),await m()},[e,m]);return{schedules:r,serverRunningIds:a,loading:l,error:d,refresh:m,create:p,update:g,remove:w,toggle:x,runNow:E,cancelRun:_}}var Tw={exports:{}},UD;function hNe(){return UD||(UD=1,(function(e,t){(function(r,i){e.exports=i()})(globalThis,()=>(()=>{var n={949(s,l,u){Object.defineProperty(l,"__esModule",{value:!0}),l.CronParser=void 0;var d=u(515),h=(function(){function m(p,g,w){g===void 0&&(g=!0),w===void 0&&(w=!1),this.expression=p,this.dayOfWeekStartIndexZero=g,this.monthStartIndexZero=w}return m.prototype.parse=function(){var p,g,w=(p=this.expression)!==null&&p!==void 0?p:"";if(w==="@reboot")return g=["@reboot","","","","","",""],g;if(w.startsWith("@")){var x=this.parseSpecial(this.expression);g=this.extractParts(x)}else g=this.extractParts(this.expression);return this.normalize(g),this.validate(g),g},m.prototype.parseSpecial=function(p){var g={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 * *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@midnight":"0 0 * * *","@hourly":"0 * * * *","@reboot":"@reboot"},w=g[p];if(!w)throw new Error("Unknown special expression.");return w},m.prototype.extractParts=function(p){if(!this.expression)throw new Error("cron expression is empty");for(var g=p.trim().split(/[ ]+/),w=0;w<g.length;w++)if(g[w].includes(",")){var x=g[w].split(",").map(function(_){return _.trim()}).filter(function(_){return _!==""}).map(function(_){return isNaN(Number(_))?_:Number(_)}).filter(function(_){return _!==null&&_!==""});x.length===0&&x.push("*"),x.sort(function(_,k){return _!==null&&k!==null?_-k:0}),g[w]=x.map(function(_){return _!==null?_.toString():""}).join(",")}if(g.length<5)throw new Error("Expression has only ".concat(g.length," part").concat(g.length==1?"":"s",". At least 5 parts are required."));if(g.length==5)g.unshift(""),g.push("");else if(g.length==6){var E=/\d{4}$/.test(g[5])||g[4]=="?"||g[2]=="?";E?g.unshift(""):g.push("")}else if(g.length>7)throw new Error("Expression has ".concat(g.length," parts; too many!"));return g},m.prototype.normalize=function(p){var g=this;if(p[3]=p[3].replace("?","*"),p[5]=p[5].replace("?","*"),p[2]=p[2].replace("?","*"),p[0].indexOf("0/")==0&&(p[0]=p[0].replace("0/","*/")),p[1].indexOf("0/")==0&&(p[1]=p[1].replace("0/","*/")),p[2].indexOf("0/")==0&&(p[2]=p[2].replace("0/","*/")),p[3].indexOf("1/")==0&&(p[3]=p[3].replace("1/","*/")),p[4].indexOf("1/")==0&&(p[4]=p[4].replace("1/","*/")),p[6].indexOf("1/")==0&&(p[6]=p[6].replace("1/","*/")),p[5]=p[5].replace(/(^\d)|([^#/\s]\d)/g,function(C){var T=C.replace(/\D/,""),M=T;return g.dayOfWeekStartIndexZero?T=="7"&&(M="0"):M=(parseInt(T)-1).toString(),C.replace(T,M)}),p[5]=="L"&&(p[5]="6"),p[3]=="?"&&(p[3]="*"),p[3].indexOf("W")>-1&&(p[3].indexOf(",")>-1||p[3].indexOf("-")>-1))throw new Error("The 'W' character can be specified only when the day-of-month is a single day, not a range or list of days.");var w={SUN:0,MON:1,TUE:2,WED:3,THU:4,FRI:5,SAT:6};for(var x in w)p[5]=p[5].replace(new RegExp(x,"gi"),w[x].toString());p[4]=p[4].replace(/(^\d{1,2})|([^#/\s]\d{1,2})/g,function(C){var T=C.replace(/\D/,""),M=T;return g.monthStartIndexZero&&(M=(parseInt(T)+1).toString()),C.replace(T,M)});var E={JAN:1,FEB:2,MAR:3,APR:4,MAY:5,JUN:6,JUL:7,AUG:8,SEP:9,OCT:10,NOV:11,DEC:12};for(var _ in E)p[4]=p[4].replace(new RegExp(_,"gi"),E[_].toString());p[0]=="0"&&(p[0]=""),!/\*|\-|\,|\//.test(p[2])&&(/\*|\//.test(p[1])||/\*|\//.test(p[0]))&&(p[2]+="-".concat(p[2]));for(var k=0;k<p.length;k++)if(p[k].indexOf(",")!=-1&&(p[k]=p[k].split(",").filter(function(C){return C!==""}).join(",")||"*"),p[k]=="*/1"&&(p[k]="*"),p[k].indexOf("/")>-1&&!/^\*|\-|\,/.test(p[k])){var O=null;switch(k){case 4:O="12";break;case 5:O="6";break;case 6:O="9999";break;default:O=null;break}if(O!==null){var N=p[k].split("/");p[k]="".concat(N[0],"-").concat(O,"/").concat(N[1])}}},m.prototype.validate=function(p){var g="0-9,\\-*/";this.validateOnlyExpectedCharactersFound(p[0],g),this.validateOnlyExpectedCharactersFound(p[1],g),this.validateOnlyExpectedCharactersFound(p[2],g),this.validateOnlyExpectedCharactersFound(p[3],"0-9,\\-*/LW"),this.validateOnlyExpectedCharactersFound(p[4],g),this.validateOnlyExpectedCharactersFound(p[5],"0-9,\\-*/L#"),this.validateOnlyExpectedCharactersFound(p[6],g),this.validateAnyRanges(p)},m.prototype.validateAnyRanges=function(p){d.default.secondRange(p[0]),d.default.minuteRange(p[1]),d.default.hourRange(p[2]),d.default.dayOfMonthRange(p[3]),d.default.monthRange(p[4],this.monthStartIndexZero),d.default.dayOfWeekRange(p[5],this.dayOfWeekStartIndexZero)},m.prototype.validateOnlyExpectedCharactersFound=function(p,g){var w=p.match(new RegExp("[^".concat(g,"]+"),"gi"));if(w&&w.length)throw new Error("Expression contains invalid values: '".concat(w.toString(),"'"))},m})();l.CronParser=h},333(s,l,u){Object.defineProperty(l,"__esModule",{value:!0}),l.ExpressionDescriptor=void 0;var d=u(823),h=u(949),m=(function(){function p(g,w){if(this.expression=g,this.options=w,this.expressionParts=new Array(5),!this.options.locale&&p.defaultLocale&&(this.options.locale=p.defaultLocale),!p.locales[this.options.locale]){var x=Object.keys(p.locales)[0];console.warn("Locale '".concat(this.options.locale,"' could not be found; falling back to '").concat(x,"'.")),this.options.locale=x}this.i18n=p.locales[this.options.locale],w.use24HourTimeFormat===void 0&&(w.use24HourTimeFormat=this.i18n.use24HourTimeFormatByDefault())}return p.toString=function(g,w){var x=w===void 0?{}:w,E=x.throwExceptionOnParseError,_=E===void 0?!0:E,k=x.verbose,O=k===void 0?!1:k,N=x.dayOfWeekStartIndexZero,C=N===void 0?!0:N,T=x.monthStartIndexZero,M=T===void 0?!1:T,D=x.use24HourTimeFormat,j=x.trimHoursLeadingZero,R=j===void 0?!1:j,H=x.locale,P=H===void 0?null:H,G=x.logicalAndDayFields,q=G===void 0?!1:G,X={throwExceptionOnParseError:_,verbose:O,dayOfWeekStartIndexZero:C,monthStartIndexZero:M,use24HourTimeFormat:D,trimHoursLeadingZero:R,locale:P,logicalAndDayFields:q};X.tzOffset&&console.warn("'tzOffset' option has been deprecated and is no longer supported.");var U=new p(g,X);return U.getFullDescription()},p.initialize=function(g,w){w===void 0&&(w="en"),p.specialCharacters=["/","-",",","*"],p.defaultLocale=w,g.load(p.locales)},p.prototype.getFullDescription=function(){var g,w,x="";try{var E=new h.CronParser(this.expression,this.options.dayOfWeekStartIndexZero,this.options.monthStartIndexZero);if(this.expressionParts=E.parse(),this.expressionParts[0]==="@reboot")return((w=(g=this.i18n).atReboot)===null||w===void 0?void 0:w.call(g))||"Run once, at startup";var _=this.getTimeOfDayDescription(),k=this.getDayOfMonthDescription(),O=this.getMonthDescription(),N=this.getDayOfWeekDescription(),C=this.getYearDescription();x+=_+k+N+O+C,x=this.transformVerbosity(x,!!this.options.verbose),x=x.charAt(0).toLocaleUpperCase()+x.substr(1)}catch(T){if(!this.options.throwExceptionOnParseError)x=this.i18n.anErrorOccuredWhenGeneratingTheExpressionD();else throw"".concat(T)}return x},p.prototype.getTimeOfDayDescription=function(){var g=this.expressionParts[0],w=this.expressionParts[1],x=this.expressionParts[2],E="";if(!d.StringUtilities.containsAny(w,p.specialCharacters)&&!d.StringUtilities.containsAny(x,p.specialCharacters)&&!d.StringUtilities.containsAny(g,p.specialCharacters))E+=this.i18n.atSpace()+this.formatTime(x,w,g);else if(!g&&w.indexOf("-")>-1&&!(w.indexOf(",")>-1)&&!(w.indexOf("/")>-1)&&!d.StringUtilities.containsAny(x,p.specialCharacters)){var _=w.split("-");E+=d.StringUtilities.format(this.i18n.everyMinuteBetweenX0AndX1(),this.formatTime(x,_[0],""),this.formatTime(x,_[1],""))}else if(!g&&x.indexOf(",")>-1&&x.indexOf("-")==-1&&x.indexOf("/")==-1&&!d.StringUtilities.containsAny(w,p.specialCharacters)){var k=x.split(",");E+=this.i18n.at();for(var O=0;O<k.length;O++)E&&(E+=" "),E+=this.formatTime(k[O],w,""),O<k.length-2&&(E+=","),O==k.length-2&&(E+=this.i18n.spaceAnd())}else{var N=this.getSecondsDescription(),C=this.getMinutesDescription(),T=this.getHoursDescription();if(E+=N,E&&C&&(E+=", "),E+=C,C===T)return E;E&&T&&(E+=", "),E+=T}return E},p.prototype.getSecondsDescription=function(){var g=this,w=this.getSegmentDescription(this.expressionParts[0],this.i18n.everySecond(),function(x){return x},function(x){return d.StringUtilities.format(g.i18n.everyX0Seconds(x),x)},function(x){return g.i18n.secondsX0ThroughX1PastTheMinute()},function(x){return x=="0"?"":parseInt(x)<20?g.i18n.atX0SecondsPastTheMinute(x):g.i18n.atX0SecondsPastTheMinuteGt20()||g.i18n.atX0SecondsPastTheMinute(x)});return w},p.prototype.getMinutesDescription=function(){var g=this,w=this.expressionParts[0],x=this.expressionParts[2],E=this.getSegmentDescription(this.expressionParts[1],this.i18n.everyMinute(),function(_){return _},function(_){return d.StringUtilities.format(g.i18n.everyX0Minutes(_),_)},function(_){return g.i18n.minutesX0ThroughX1PastTheHour()},function(_){var k,O;try{return _=="0"&&x.indexOf("/")==-1&&w==""?g.i18n.everyHour():_=="0"?((O=(k=g.i18n).onTheHour)===null||O===void 0?void 0:O.call(k))||g.i18n.atX0MinutesPastTheHour(_):parseInt(_)<20?g.i18n.atX0MinutesPastTheHour(_):g.i18n.atX0MinutesPastTheHourGt20()||g.i18n.atX0MinutesPastTheHour(_)}catch{return g.i18n.atX0MinutesPastTheHour(_)}});return E},p.prototype.getHoursDescription=function(){var g=this,w=this.expressionParts[2],x=0,E=[];w.split("/")[0].split(",").forEach(function(O){var N=O.split("-");N.length===2&&E.push({value:N[1],index:x+1}),x+=N.length});var _=0,k=this.getSegmentDescription(w,this.i18n.everyHour(),function(O){var N=E.find(function(T){return T.value===O&&T.index===_}),C=N&&g.expressionParts[1]!=="0";return _++,C?g.formatTime(O,"59",""):g.formatTime(O,"0","")},function(O){return d.StringUtilities.format(g.i18n.everyX0Hours(O),O)},function(O){return g.i18n.betweenX0AndX1()},function(O){return g.i18n.atX0()});return k},p.prototype.getDayOfWeekDescription=function(){var g=this,w=this.i18n.daysOfTheWeek(),x=null;return this.expressionParts[5]=="*"?x="":x=this.getSegmentDescription(this.expressionParts[5],this.i18n.commaEveryDay(),function(E,_){var k=E;E.indexOf("#")>-1?k=E.substring(0,E.indexOf("#")):E.indexOf("L")>-1&&(k=k.replace("L",""));var O=parseInt(k),N=g.i18n.daysOfTheWeekInCase?g.i18n.daysOfTheWeekInCase(_)[O]:w[O];if(E.indexOf("#")>-1){var C=null,T=E.substring(E.indexOf("#")+1),M=E.substring(0,E.indexOf("#"));switch(T){case"1":C=g.i18n.first(M);break;case"2":C=g.i18n.second(M);break;case"3":C=g.i18n.third(M);break;case"4":C=g.i18n.fourth(M);break;case"5":C=g.i18n.fifth(M);break}N=C+" "+N}return N},function(E){return parseInt(E)==1?"":d.StringUtilities.format(g.i18n.commaEveryX0DaysOfTheWeek(E),E)},function(E){var _=E.substring(0,E.indexOf("-")),k=g.expressionParts[3]!="*";return k?g.i18n.commaAndX0ThroughX1(_):g.i18n.commaX0ThroughX1(_)},function(E){var _=null;if(E.indexOf("#")>-1){var k=E.substring(E.indexOf("#")+1),O=E.substring(0,E.indexOf("#"));_=g.i18n.commaOnThe(k,O).trim()+g.i18n.spaceX0OfTheMonth()}else if(E.indexOf("L")>-1)_=g.i18n.commaOnTheLastX0OfTheMonth(E.replace("L",""));else{var N=g.expressionParts[3]!="*";N?g.options.logicalAndDayFields?_=g.i18n.commaOnlyOnX0(E):_=g.i18n.commaAndOnX0():_=g.i18n.commaOnlyOnX0(E)}return _}),x},p.prototype.getMonthDescription=function(){var g=this,w=this.i18n.monthsOfTheYear(),x=this.getSegmentDescription(this.expressionParts[4],"",function(E,_){return _&&g.i18n.monthsOfTheYearInCase?g.i18n.monthsOfTheYearInCase(_)[parseInt(E)-1]:w[parseInt(E)-1]},function(E){return parseInt(E)==1?"":d.StringUtilities.format(g.i18n.commaEveryX0Months(E),E)},function(E){return g.i18n.commaMonthX0ThroughMonthX1()||g.i18n.commaX0ThroughX1()},function(E){return g.i18n.commaOnlyInMonthX0?g.i18n.commaOnlyInMonthX0():g.i18n.commaOnlyInX0()});return x},p.prototype.getDayOfMonthDescription=function(){var g=this,w=null,x=this.expressionParts[3];switch(x){case"L":w=this.i18n.commaOnTheLastDayOfTheMonth();break;case"WL":case"LW":w=this.i18n.commaOnTheLastWeekdayOfTheMonth();break;default:var E=x.match(/(\d{1,2}W)|(W\d{1,2})/);if(E){var _=parseInt(E[0].replace("W","")),k=_==1?this.i18n.firstWeekday():d.StringUtilities.format(this.i18n.weekdayNearestDayX0(),_.toString());w=d.StringUtilities.format(this.i18n.commaOnTheX0OfTheMonth(),k);break}else{var O=x.match(/L-(\d{1,2})/);if(O){var N=O[1];w=d.StringUtilities.format(this.i18n.commaDaysBeforeTheLastDayOfTheMonth(N),N);break}else{if(x=="*"&&this.expressionParts[5]!="*")return"";w=this.getSegmentDescription(x,this.i18n.commaEveryDay(),function(C){return C=="L"?g.i18n.lastDay():g.i18n.dayX0?d.StringUtilities.format(g.i18n.dayX0(),C):C},function(C){return C=="1"?g.i18n.commaEveryDay():g.i18n.commaEveryX0Days(C)},function(C){return g.i18n.commaBetweenDayX0AndX1OfTheMonth(C)},function(C){return g.i18n.commaOnDayX0OfTheMonth(C)})}break}}return w},p.prototype.getYearDescription=function(){var g=this,w=this.getSegmentDescription(this.expressionParts[6],"",function(x){return/^\d+$/.test(x)?new Date(parseInt(x),1).getFullYear().toString():x},function(x){return d.StringUtilities.format(g.i18n.commaEveryX0Years(x),x)},function(x){return g.i18n.commaYearX0ThroughYearX1()||g.i18n.commaX0ThroughX1()},function(x){return g.i18n.commaOnlyInYearX0?g.i18n.commaOnlyInYearX0():g.i18n.commaOnlyInX0()});return w},p.prototype.getSegmentDescription=function(g,w,x,E,_,k){var O=null,N=g.indexOf("/")>-1,C=g.indexOf("-")>-1,T=g.indexOf(",")>-1;if(!g)O="";else if(g==="*")O=w;else if(!N&&!C&&!T)O=d.StringUtilities.format(k(g),x(g));else if(T){for(var M=g.split(","),D="",j=this.i18n.spaceAnd(),R=0;R<M.length;R++)if(R>0&&M.length>2&&(D+=",",R<M.length-1&&(D+=" ")),R>0&&M.length>1&&(R==M.length-1||M.length==2)&&(D+=j==","&&M.length>2?" ":"".concat(j," ")),M[R].indexOf("/")>-1||M[R].indexOf("-")>-1){var H=M[R].indexOf("-")>-1&&M[R].indexOf("/")==-1,P=this.getSegmentDescription(M[R],w,x,E,H?this.i18n.commaX0ThroughX1:_,k);H&&(P=P.replace(", ","")),D+=P}else if(!N)D+=x(M[R]);else{var G=this.getSegmentDescription(M[R],w,x,E,_,k);G&&G.startsWith(", ")&&(G=G.substring(2)),D+=G}N?O=D:O=d.StringUtilities.format(k(g),D)}else if(N){var M=g.split("/");if(O=d.StringUtilities.format(E(M[1]),M[1]),M[0].indexOf("-")>-1){var q=this.generateRangeSegmentDescription(M[0],_,x);q.indexOf(", ")!=0&&(O+=", "),O+=q}else if(M[0].indexOf("*")==-1){var X=d.StringUtilities.format(k(M[0]),x(M[0]));X=X.replace(", ",""),O+=d.StringUtilities.format(this.i18n.commaStartingX0(),X)}}else C&&(O=this.generateRangeSegmentDescription(g,_,x));return O},p.prototype.generateRangeSegmentDescription=function(g,w,x){var E="",_=g.split("-"),k=x(_[0],1),O=x(_[1],2),N=w(g);return E+=d.StringUtilities.format(N,k,O),E},p.prototype.formatTime=function(g,w,x){var E=0,_=0,k=parseInt(g)+E,O=parseInt(w)+_;O>=60?(O-=60,k+=1):O<0&&(O+=60,k-=1),k>=24?k=k-24:k<0&&(k=24+k);var N="",C=!1;this.options.use24HourTimeFormat||(C=!!(this.i18n.setPeriodBeforeTime&&this.i18n.setPeriodBeforeTime()),N=C?"".concat(this.getPeriod(k)," "):" ".concat(this.getPeriod(k)),k>12&&(k-=12),k===0&&(k=12));var T="";x&&(T=":".concat(("00"+x).substring(x.length)));var M=k.toString(),D=("00"+M).substring(M.length),j=O.toString(),R=("00"+j).substring(j.length),H=this.options.trimHoursLeadingZero?M:D;return"".concat(C?N:"").concat(H,":").concat(R).concat(T).concat(C?"":N)},p.prototype.transformVerbosity=function(g,w){if(!w&&(g=g.replace(new RegExp(", ".concat(this.i18n.everyMinute()),"g"),""),g=g.replace(new RegExp(", ".concat(this.i18n.everyHour()),"g"),""),g=g.replace(new RegExp(this.i18n.commaEveryDay(),"g"),""),g=g.replace(/\, ?$/,""),this.i18n.conciseVerbosityReplacements))for(var x=0,E=Object.entries(this.i18n.conciseVerbosityReplacements());x<E.length;x++){var _=E[x],k=_[0],O=_[1];g=g.replace(new RegExp(k,"g"),O)}return g},p.prototype.getPeriod=function(g){return g>=12?this.i18n.pm&&this.i18n.pm()||"PM":this.i18n.am&&this.i18n.am()||"AM"},p.locales={},p})();l.ExpressionDescriptor=m},747(s,l,u){Object.defineProperty(l,"__esModule",{value:!0}),l.enLocaleLoader=void 0;var d=u(486),h=(function(){function m(){}return m.prototype.load=function(p){p.en=new d.en},m})();l.enLocaleLoader=h},486(s,l){Object.defineProperty(l,"__esModule",{value:!0}),l.en=void 0;var u=(function(){function d(){}return d.prototype.atX0SecondsPastTheMinuteGt20=function(){return null},d.prototype.atX0MinutesPastTheHourGt20=function(){return null},d.prototype.commaMonthX0ThroughMonthX1=function(){return null},d.prototype.commaYearX0ThroughYearX1=function(){return null},d.prototype.use24HourTimeFormatByDefault=function(){return!1},d.prototype.anErrorOccuredWhenGeneratingTheExpressionD=function(){return"An error occurred when generating the expression description. Check the cron expression syntax."},d.prototype.everyMinute=function(){return"every minute"},d.prototype.everyHour=function(){return"every hour"},d.prototype.atSpace=function(){return"At "},d.prototype.everyMinuteBetweenX0AndX1=function(){return"Every minute between %s and %s"},d.prototype.at=function(){return"At"},d.prototype.spaceAnd=function(){return" and"},d.prototype.everySecond=function(){return"every second"},d.prototype.everyX0Seconds=function(){return"every %s seconds"},d.prototype.secondsX0ThroughX1PastTheMinute=function(){return"seconds %s through %s past the minute"},d.prototype.atX0SecondsPastTheMinute=function(){return"at %s seconds past the minute"},d.prototype.everyX0Minutes=function(){return"every %s minutes"},d.prototype.minutesX0ThroughX1PastTheHour=function(){return"minutes %s through %s past the hour"},d.prototype.atX0MinutesPastTheHour=function(){return"at %s minutes past the hour"},d.prototype.everyX0Hours=function(){return"every %s hours"},d.prototype.betweenX0AndX1=function(){return"between %s and %s"},d.prototype.atX0=function(){return"at %s"},d.prototype.commaEveryDay=function(){return", every day"},d.prototype.commaEveryX0DaysOfTheWeek=function(){return", every %s days of the week"},d.prototype.commaX0ThroughX1=function(){return", %s through %s"},d.prototype.commaAndX0ThroughX1=function(){return", %s through %s"},d.prototype.first=function(){return"first"},d.prototype.second=function(){return"second"},d.prototype.third=function(){return"third"},d.prototype.fourth=function(){return"fourth"},d.prototype.fifth=function(){return"fifth"},d.prototype.commaOnThe=function(){return", on the "},d.prototype.spaceX0OfTheMonth=function(){return" %s of the month"},d.prototype.lastDay=function(){return"the last day"},d.prototype.commaOnTheLastX0OfTheMonth=function(){return", on the last %s of the month"},d.prototype.commaOnlyOnX0=function(){return", only on %s"},d.prototype.commaAndOnX0=function(){return", and on %s"},d.prototype.commaEveryX0Months=function(){return", every %s months"},d.prototype.commaOnlyInX0=function(){return", only in %s"},d.prototype.commaOnTheLastDayOfTheMonth=function(){return", on the last day of the month"},d.prototype.commaOnTheLastWeekdayOfTheMonth=function(){return", on the last weekday of the month"},d.prototype.commaDaysBeforeTheLastDayOfTheMonth=function(){return", %s days before the last day of the month"},d.prototype.firstWeekday=function(){return"first weekday"},d.prototype.weekdayNearestDayX0=function(){return"weekday nearest day %s"},d.prototype.commaOnTheX0OfTheMonth=function(){return", on the %s of the month"},d.prototype.commaEveryX0Days=function(){return", every %s days in a month"},d.prototype.commaBetweenDayX0AndX1OfTheMonth=function(){return", between day %s and %s of the month"},d.prototype.commaOnDayX0OfTheMonth=function(){return", on day %s of the month"},d.prototype.commaEveryHour=function(){return", every hour"},d.prototype.commaEveryX0Years=function(){return", every %s years"},d.prototype.commaStartingX0=function(){return", starting %s"},d.prototype.daysOfTheWeek=function(){return["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},d.prototype.monthsOfTheYear=function(){return["January","February","March","April","May","June","July","August","September","October","November","December"]},d.prototype.atReboot=function(){return"Run once, at startup"},d.prototype.onTheHour=function(){return"on the hour"},d})();l.en=u},515(s,l){Object.defineProperty(l,"__esModule",{value:!0});function u(h,m){if(!h)throw new Error(m)}var d=(function(){function h(){}return h.secondRange=function(m){for(var p=m.split(","),g=0;g<p.length;g++)if(!isNaN(parseInt(p[g],10))){var w=parseInt(p[g],10);u(w>=0&&w<=59,"seconds part must be >= 0 and <= 59")}},h.minuteRange=function(m){for(var p=m.split(","),g=0;g<p.length;g++)if(!isNaN(parseInt(p[g],10))){var w=parseInt(p[g],10);u(w>=0&&w<=59,"minutes part must be >= 0 and <= 59")}},h.hourRange=function(m){for(var p=m.split(","),g=0;g<p.length;g++)if(!isNaN(parseInt(p[g],10))){var w=parseInt(p[g],10);u(w>=0&&w<=23,"hours part must be >= 0 and <= 23")}},h.dayOfMonthRange=function(m){for(var p=m.split(","),g=0;g<p.length;g++)if(!isNaN(parseInt(p[g],10))){var w=parseInt(p[g],10);u(w>=1&&w<=31,"DOM part must be >= 1 and <= 31")}},h.monthRange=function(m,p){for(var g=m.split(","),w=0;w<g.length;w++)if(!isNaN(parseInt(g[w],10))){var x=parseInt(g[w],10);u(x>=1&&x<=12,p?"month part must be >= 0 and <= 11":"month part must be >= 1 and <= 12")}},h.dayOfWeekRange=function(m,p){for(var g=m.split(","),w=0;w<g.length;w++)if(!isNaN(parseInt(g[w],10))){var x=parseInt(g[w],10);u(x>=0&&x<=6,p?"DOW part must be >= 0 and <= 6":"DOW part must be >= 1 and <= 7")}},h})();l.default=d},823(s,l){Object.defineProperty(l,"__esModule",{value:!0}),l.StringUtilities=void 0;var u=(function(){function d(){}return d.format=function(h){for(var m=[],p=1;p<arguments.length;p++)m[p-1]=arguments[p];return h.replace(/%s/g,function(g){return m.shift()})},d.containsAny=function(h,m){return m.some(function(p){return h.indexOf(p)>-1})},d})();l.StringUtilities=u}},r={};function i(s){var l=r[s];if(l!==void 0)return l.exports;var u=r[s]={exports:{}};return n[s](u,u.exports,i),u.exports}var a={};return(()=>{var s=a;Object.defineProperty(s,"__esModule",{value:!0}),s.toString=void 0;var l=i(333),u=i(747);l.ExpressionDescriptor.initialize(new u.enLocaleLoader),s.default=l.ExpressionDescriptor;var d=l.ExpressionDescriptor.toString;s.toString=d})(),a})())})(Tw)),Tw.exports}var mNe=hNe();const S8=Xu(mNe);function pNe(e){return e.trigger.kind}function gNe(e){var n;const t=e.trigger;if(t.kind==="once")return`Once at ${new Date(t.at).toLocaleString()}`;if(t.kind==="interval"){const r=Math.round(t.everyMs/1e3);return r>=86400?`Every ${Math.round(r/86400)}d`:r>=3600?`Every ${Math.round(r/3600)}h`:r>=60?`Every ${Math.round(r/60)}m`:`Every ${r}s`}if(t.kind==="event"){const r=t.match?Object.entries(t.match).map(([i,a])=>`${i}=${a}`).join(", "):"";return`On event "${t.source}"${r?` where ${r}`:""}`}try{const r=t.tz||"UTC",i=vNe(t.expr,r),a=S8.toString(t.expr),s=r==="UTC"?"UTC":((n=r.split("/").pop())==null?void 0:n.replace(/_/g," "))||r;return i?`${i} (${a} ${s})`:`${a} ${s}`}catch{return t.expr}}function vNe(e,t){try{const n=e.split(/\s+/);if(n.length<5)return null;const r=parseInt(n[0],10),i=parseInt(n[1],10);if(isNaN(r)||isNaN(i))return null;const a=new Date,s=new Date(a.toLocaleString("en-US",{timeZone:t})).getTime()-new Date(a.toLocaleString("en-US",{timeZone:"UTC"})).getTime(),l=new Date;return l.setUTCHours(i,r,0,0),new Date(l.getTime()-s).toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit",hour12:!1,timeZone:"UTC"})}catch{return null}}function FD(e){if(!e)return"—";const t=e-Date.now(),n=Math.abs(t),r=Math.round(n/6e4);if(n<6e4)return t>0?"in <1m":"<1m ago";if(r<60)return t>0?`in ${r}m`:`${r}m ago`;const i=Math.round(r/60);if(i<24)return t>0?`in ${i}h`:`${i}h ago`;const a=Math.round(i/24);return t>0?`in ${a}d`:`${a}d ago`}const yNe={ok:"bg-green-50 text-green-700 dark:bg-green-950/50 dark:text-green-300",error:"bg-red-50 text-red-700 dark:bg-red-950/50 dark:text-red-300",running:"bg-blue-50 text-blue-700 dark:bg-blue-950/50 dark:text-blue-300",aborted:"bg-amber-50 text-amber-700 dark:bg-amber-950/50 dark:text-amber-300"};function bNe(e){return e.scope==="system"}function xNe(e){return e==="prompt"?"Additional instructions (appended to prompt)":e==="bash"?"Override command":"Override args"}function wNe(e){return e==="prompt"?"e.g. Dry run — compose the message but do NOT post to Slack":e==="bash"?"e.g. bun run report:fb-ads-spend --dry-run":"e.g. --dry-run"}function ENe(e,t){var n;return e.scope==="system"?"system":((n=e.createdBy)==null?void 0:n.uid)===t?"mine":"others"}function SNe({schedules:e,currentUserUid:t,onCreate:n,onEdit:r,onDelete:i,onToggle:a,onRunNow:s,onCancel:l,onOpenRun:u,runningIds:d=new Set}){const[h,m]=b.useState(null),[p,g]=b.useState(""),[w,x]=b.useState({mine:!0,others:!0,system:!0}),[E,_]=b.useState({once:!0,interval:!0,cron:!0,event:!0}),[k,O]=b.useState(!1),N=j=>x(R=>{if(Object.values(R).every(Boolean))return{mine:!1,others:!1,system:!1,[j]:!0};const P={...R,[j]:!R[j]};return Object.values(P).some(Boolean)?P:{mine:!0,others:!0,system:!0}}),C=j=>_(R=>{if(Object.values(R).every(Boolean))return{once:!1,interval:!1,cron:!1,event:!1,[j]:!0};const P={...R,[j]:!R[j]};return Object.values(P).some(Boolean)?P:{once:!0,interval:!0,cron:!0,event:!0}}),T=e.filter(j=>w[ENe(j,t)]&&E[pNe(j)]),M=j=>{const R=localStorage.getItem(`schedule-override-${j.id}`);g(R??""),m(j.id)},D=async()=>{if(h){O(!0);try{const j=p.trim()||void 0;j&&localStorage.setItem(`schedule-override-${h}`,j);const R=await s(h,j);m(null),g(""),R&&u(R)}finally{O(!1)}}};return y.jsxs("div",{className:"space-y-3",children:[y.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[y.jsxs("div",{className:"flex gap-1 flex-wrap",children:[["mine","others","system"].map(j=>y.jsx("button",{onClick:()=>N(j),className:`text-[11px] px-2 py-0.5 rounded-full border transition-colors ${w[j]?"bg-primary text-primary-foreground border-primary":"bg-transparent text-muted-foreground border-border hover:border-muted-foreground"}`,children:j},j)),y.jsx("span",{className:"w-px h-4 bg-border mx-1"}),["once","interval","cron","event"].map(j=>y.jsx("button",{onClick:()=>C(j),className:`text-[11px] px-2 py-0.5 rounded-full border transition-colors ${E[j]?"bg-primary text-primary-foreground border-primary":"bg-transparent text-muted-foreground border-border hover:border-muted-foreground"}`,children:j},j))]}),y.jsxs(we,{size:"sm",onClick:n,className:"gap-1",children:[y.jsx(ko,{className:"w-4 h-4"})," New schedule"]})]}),T.length===0&&y.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:e.length===0?"No schedules yet.":"No schedules match filters."}),T.map(j=>{var R,H;return y.jsxs("div",{className:"border rounded-lg p-3 space-y-2 overflow-hidden",children:[y.jsxs("div",{className:"flex items-start justify-between gap-2 flex-wrap",children:[y.jsxs("div",{className:"min-w-0 flex-1",children:[y.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-wrap",children:[y.jsx("input",{type:"checkbox",checked:j.enabled,onChange:P=>a(j.id,P.target.checked),title:j.enabled?"Disable":"Enable",className:"shrink-0"}),y.jsx("span",{className:"font-medium text-sm truncate max-w-[280px]",title:j.name,children:j.name}),y.jsx("span",{className:"shrink-0 text-[10px] font-mono px-1.5 py-0.5 rounded bg-muted text-muted-foreground",children:j.task.kind}),y.jsx("span",{className:"shrink-0 text-[10px] font-mono px-1.5 py-0.5 rounded bg-muted text-muted-foreground",children:j.trigger.kind}),d.has(j.id)&&y.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] px-1.5 py-0.5 rounded bg-blue-50 text-blue-700 dark:bg-blue-950/50 dark:text-blue-300",children:[y.jsx(Yi,{className:"w-3 h-3 animate-spin"}),"running"]}),y.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-blue-50 text-blue-700 dark:bg-blue-950/50 dark:text-blue-300",children:bNe(j)?"system":((H=(R=j.createdBy)==null?void 0:R.email)==null?void 0:H.split("@")[0])??"unknown"})]}),y.jsx("div",{className:"mt-1 text-xs text-muted-foreground truncate",children:gNe(j)}),y.jsxs("div",{className:"mt-1 flex items-center gap-3 text-xs text-muted-foreground",children:[y.jsxs("span",{children:["Next: ",j.enabled?FD(j.nextRun):"disabled"]}),j.lastRun&&y.jsxs("button",{className:`px-1.5 py-0.5 rounded text-[10px] ${yNe[j.lastRun.status]??""}`,onClick:()=>u(j.lastRun.sessionId),title:"Open last run",children:["last: ",j.lastRun.status," ",FD(j.lastRun.at)]}),y.jsxs("span",{children:["runs: ",j.runCount??0]})]})]}),y.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[d.has(j.id)?y.jsx(we,{variant:"ghost",size:"icon",title:"Stop run",onClick:()=>l(j.id),children:y.jsx(fL,{className:"w-4 h-4 text-destructive"})}):y.jsx(we,{variant:"ghost",size:"icon",title:"Run now",onClick:()=>M(j),children:y.jsx(cV,{className:"w-4 h-4"})}),y.jsx(we,{variant:"ghost",size:"icon",title:"Edit",onClick:()=>r(j),children:y.jsx(KE,{className:"w-4 h-4"})}),y.jsx(we,{variant:"ghost",size:"icon",title:"Delete",onClick:()=>i(j.id),children:y.jsx(Xi,{className:"w-4 h-4 text-destructive"})})]})]}),h===j.id&&y.jsxs("div",{className:"border-t pt-2 mt-2 space-y-2",children:[y.jsx("label",{className:"text-xs text-muted-foreground",children:xNe(j.task.kind)}),y.jsx("input",{type:"text",className:"w-full text-sm border rounded px-2 py-1.5 bg-background",placeholder:wNe(j.task.kind),value:p,onChange:P=>g(P.target.value),onKeyDown:P=>{P.key==="Enter"&&!k&&D(),P.key==="Escape"&&m(null)},disabled:k,autoFocus:!0}),y.jsxs("div",{className:"flex gap-2 justify-end",children:[y.jsx(we,{size:"sm",variant:"ghost",onClick:()=>m(null),disabled:k,children:"Cancel"}),y.jsx(we,{size:"sm",onClick:D,disabled:k,children:k?"Running...":"Run"})]})]})]},j.id)})]})}function _Ne(e){const{directives:t}=XOe(e),n=XA(e,{strict:!0}).groups.some(r=>r.split(",").some(i=>/^\s*engine\s*:/i.test(i)));return{engine:t.engine,model:t.model,engineExplicit:n}}const ANe=/^(engine|model)\s*:/i;function kNe(e,t){var h;const{groups:n,body:r}=XA(e,{strict:!0}),i=[];let a=!1;for(const m of n)for(const p of m.split(",").map(g=>g.trim()).filter(Boolean)){if(ANe.test(p))continue;if(p.includes(":")){i.push(p);continue}const g=!a&&!!_E(p);a=!0,g||i.push(p)}const s=t.model?(h=_E(t.model))==null?void 0:h.engine:void 0,l=t.engine&&t.engine!==s?t.engine:void 0,d=[...[l&&`engine:${l}`,t.model&&`model:${t.model}`].filter(Boolean),...i];return d.length?`[${d.join(",")}] ${r}`:r}function ONe(e){const t=new Date(e??Date.now()+6e4),n=r=>String(r).padStart(2,"0");return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}T${n(t.getHours())}:${n(t.getMinutes())}`}const NNe=[{label:"1 min",ms:6e4},{label:"5 min",ms:5*6e4},{label:"15 min",ms:15*6e4},{label:"1 hour",ms:60*6e4},{label:"6 hours",ms:360*6e4},{label:"1 day",ms:1440*6e4}],CNe=[{label:"Every hour",expr:"0 * * * *"},{label:"Daily 9am",expr:"0 9 * * *"},{label:"Weekdays 9am",expr:"0 9 * * 1-5"},{label:"Mondays 9am",expr:"0 9 * * 1"}];function TNe({match:e,onChange:t}){const n=Object.entries(e),r=(s,l,u)=>{const d={};n.forEach(([h,m],p)=>{d[p===s?l:h]=p===s?u:m}),t(d)},i=s=>t(Object.fromEntries(n.filter((l,u)=>u!==s))),a=()=>t({...e,"":""});return y.jsxs("div",{className:"space-y-1",children:[y.jsx("label",{className:"text-xs text-muted-foreground",children:"Match filter (optional — all must match)"}),n.map(([s,l],u)=>y.jsxs("div",{className:"flex gap-1",children:[y.jsx(ft,{className:"text-xs font-mono",value:s,onChange:d=>r(u,d.target.value,l),placeholder:"payload.path (e.g. type)"}),y.jsx(ft,{className:"text-xs font-mono",value:l,onChange:d=>r(u,s,d.target.value),placeholder:"value (e.g. invoice.paid)"}),y.jsx(we,{type:"button",variant:"ghost",size:"sm",onClick:()=>i(u),children:"×"})]},u)),y.jsx(we,{type:"button",variant:"outline",size:"sm",onClick:a,children:"+ Add filter"})]})}function MNe({prompt:e,onChange:t,getToken:n}){const{engines:r}=w8(n),i=r.length>0,a=b.useMemo(()=>_Ne(e),[e,i]),s=a.engineExplicit?r.find(g=>g.name===a.engine):void 0,l=s?[{engine:s.name,models:s.models}]:r.map(g=>({engine:g.name,models:g.models})),u=(g,w)=>!g||w.includes(g),d=u(a.model,l.flatMap(g=>g.models.map(w=>w.value))),h=u(a.engine,r.map(g=>g.name)),m=g=>t(kNe(e,{engine:a.engineExplicit?a.engine:void 0,model:a.model,...g})),p="h-8 rounded-md border border-input bg-background px-2 text-xs";return y.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[y.jsx("label",{className:"text-xs text-muted-foreground",children:"Runtime"}),y.jsxs("select",{className:p,disabled:!i,value:a.engine??"",onChange:g=>m({engine:g.target.value||void 0,model:void 0}),children:[y.jsx("option",{value:"",children:"Default engine (agent config)"}),!h&&y.jsxs("option",{value:a.engine,children:[a.engine," — not registered on this server"]}),r.map(g=>y.jsx("option",{value:g.name,children:g.name},g.name))]}),y.jsxs("select",{className:p,disabled:!i,value:a.model??"",onChange:g=>m({model:g.target.value||void 0}),children:[y.jsx("option",{value:"",children:"Default model (agent config)"}),!d&&y.jsxs("option",{value:a.model,children:[a.model," — not offered by this engine"]}),l.map(({engine:g,models:w})=>y.jsx("optgroup",{label:g,children:w.filter(x=>x.value).map(x=>y.jsx("option",{value:x.value,children:x.label||x.value},`${g}:${x.value}`))},g))]}),!i&&y.jsx("span",{className:"text-[10px] text-muted-foreground",children:"loading engines…"})]})}function HD({getToken:e,initial:t,onSave:n,onCancel:r,skills:i=[],workspaceFiles:a=[]}){const s=b.useMemo(()=>Intl.DateTimeFormat().resolvedOptions().timeZone,[]),[l,u]=b.useState((t==null?void 0:t.name)??"New schedule"),[d,h]=b.useState((t==null?void 0:t.enabled)??!0),[m,p]=b.useState((t==null?void 0:t.trigger)??{kind:"cron",expr:"0 9 * * *",tz:s}),[g,w]=b.useState((t==null?void 0:t.task)??{kind:"prompt",prompt:""}),[x,E]=b.useState(!1),[_,k]=b.useState(null),O=b.useMemo(()=>{if(m.kind!=="cron")return"";try{return S8.toString(m.expr)}catch{return"Invalid cron"}},[m]),N=async()=>{E(!0),k(null);try{await n({name:l,enabled:d,trigger:m,task:g})}catch(C){k(C.message)}finally{E(!1)}};return y.jsxs("div",{className:"space-y-4",children:[y.jsxs("div",{className:"space-y-1",children:[y.jsx("label",{className:"text-xs text-muted-foreground",children:"Name"}),y.jsx(ft,{value:l,onChange:C=>u(C.target.value),placeholder:"e.g. Daily standup summary"})]}),y.jsxs("div",{className:"space-y-2",children:[y.jsx("label",{className:"text-xs text-muted-foreground",children:"Trigger"}),y.jsx("div",{className:"flex gap-1",children:["once","interval","cron","event"].map(C=>y.jsx(we,{type:"button",variant:m.kind===C?"default":"outline",size:"sm",onClick:()=>{p(C==="once"?{kind:"once",at:Date.now()+5*6e4}:C==="interval"?{kind:"interval",everyMs:60*6e4}:C==="event"?{kind:"event",source:""}:{kind:"cron",expr:"0 9 * * *",tz:s})},children:C},C))}),m.kind==="once"&&y.jsx(ft,{type:"datetime-local",value:ONe(m.at),onChange:C=>{const T=new Date(C.target.value);isNaN(T.getTime())||p({kind:"once",at:T.getTime()})}}),m.kind==="interval"&&y.jsxs("div",{className:"space-y-2",children:[y.jsx("div",{className:"flex gap-1 flex-wrap",children:NNe.map(C=>y.jsx(we,{type:"button",variant:m.everyMs===C.ms?"default":"outline",size:"sm",onClick:()=>p({kind:"interval",everyMs:C.ms}),children:C.label},C.ms))}),y.jsx(ft,{type:"number",min:1,value:Math.round(m.everyMs/1e3),onChange:C=>p({kind:"interval",everyMs:Math.max(1,Number(C.target.value))*1e3}),placeholder:"seconds"}),y.jsxs("p",{className:"text-xs text-muted-foreground",children:["Every ",Math.round(m.everyMs/1e3),"s"]})]}),m.kind==="cron"&&y.jsxs("div",{className:"space-y-2",children:[y.jsx("div",{className:"flex gap-1 flex-wrap",children:CNe.map(C=>y.jsx(we,{type:"button",variant:"outline",size:"sm",onClick:()=>p({kind:"cron",expr:C.expr,tz:s}),children:C.label},C.expr))}),y.jsx(ft,{className:"font-mono text-xs",value:m.expr,onChange:C=>p({...m,expr:C.target.value}),placeholder:"0 9 * * *"}),y.jsx(ft,{className:"text-xs",value:m.tz,onChange:C=>p({...m,tz:C.target.value}),placeholder:"IANA timezone"}),y.jsxs("p",{className:"text-xs text-muted-foreground",children:[O," (",m.tz,")"]})]}),m.kind==="event"&&y.jsxs("div",{className:"space-y-2",children:[y.jsx(ft,{value:m.source,onChange:C=>p({...m,source:C.target.value}),placeholder:"Event source (e.g. stripe, github, deploy)"}),y.jsxs("p",{className:"text-xs text-muted-foreground",children:["Fires when an event with this source arrives via ",y.jsxs("code",{children:["POST /api/events/",m.source||":source"]})," or ",y.jsx("code",{children:"ctx.emitEvent()"}),"."]}),y.jsx(TNe,{match:m.match??{},onChange:C=>p({...m,match:C})})]})]}),y.jsxs("div",{className:"space-y-2",children:[y.jsx("label",{className:"text-xs text-muted-foreground",children:"Task"}),y.jsx("div",{className:"flex gap-1",children:["prompt","bash"].map(C=>y.jsx(we,{type:"button",variant:g.kind===C?"default":"outline",size:"sm",onClick:()=>w(C==="prompt"?{kind:"prompt",prompt:""}:{kind:"bash",command:""}),children:C==="prompt"?"Prompt":"Bash command"},C))}),g.kind==="prompt"?y.jsxs(y.Fragment,{children:[y.jsx(MNe,{prompt:g.prompt,getToken:e,onChange:C=>w({...g,prompt:C})}),y.jsx(v8,{rows:5,value:g.prompt,onChange:C=>w({...g,prompt:C}),placeholder:"What should the agent do? (@ for skills, / for commands)",skills:i,workspaceFiles:a,autoResize:!1,className:"flex min-h-[80px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"})]}):g.kind==="bash"?y.jsx(Vy,{rows:3,className:"font-mono text-xs",value:g.command,onChange:C=>w({...g,command:C.target.value}),placeholder:"ls -la ~/"}):y.jsxs("p",{className:"text-xs text-muted-foreground",children:["Command: ",g.command]})]}),y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx("input",{id:"sched-enabled",type:"checkbox",checked:d,onChange:C=>h(C.target.checked)}),y.jsx("label",{htmlFor:"sched-enabled",className:"text-sm",children:"Enabled"})]}),_&&y.jsx("p",{className:"text-xs text-destructive",children:_}),y.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[y.jsx(we,{variant:"outline",onClick:r,disabled:x,children:"Cancel"}),y.jsx(we,{onClick:N,disabled:x,children:x?"Saving…":"Save"})]})]})}const KD=b.forwardRef(function({getToken:t,onOpenSession:n,refreshKey:r=0,runningIds:i=new Set,skills:a=[],workspaceFiles:s=[],trigger:l},u){const[d,h]=b.useState(!1),{user:m}=Yj(),{schedules:p,serverRunningIds:g,create:w,update:x,remove:E,toggle:_,runNow:k,cancelRun:O}=fNe(t,d,r);b.useImperativeHandle(u,()=>({open:()=>h(!0)}),[]);const[N,C]=b.useState(null),[T,M]=b.useState(!1),[D,j]=b.useState(new Set),R=()=>{C(null),M(!1)},H=async(P,G)=>{j(q=>new Set(q).add(P));try{return await k(P,G)}finally{setTimeout(()=>{j(q=>{const X=new Set(q);return X.delete(P),X})},1500)}};return y.jsxs(Oo,{open:d,onOpenChange:P=>{h(P),P||R()},children:[y.jsx(rd,{asChild:!0,children:l||y.jsx(we,{variant:"ghost",size:"icon",className:"h-8 w-8",title:"Scheduled Tasks",children:y.jsx(BE,{className:"w-4 h-4"})})}),y.jsxs(Na,{className:"max-w-[95vw] sm:max-w-2xl",children:[y.jsx(Bs,{children:y.jsx(No,{children:T?"New Schedule":N?`Edit: ${N.name}`:"Scheduled Tasks"})}),T?y.jsx(HD,{getToken:t,onSave:async P=>{await w(P),R()},onCancel:R,skills:a,workspaceFiles:s},"__new__"):N?y.jsx(HD,{getToken:t,initial:N,onSave:async P=>{await x(N.id,P),R()},onCancel:R,skills:a,workspaceFiles:s},N.id):y.jsx(SNe,{schedules:p,currentUserUid:m==null?void 0:m.uid,onCreate:()=>M(!0),onEdit:P=>C(P),onDelete:P=>{confirm("Delete this schedule?")&&E(P)},onToggle:_,onRunNow:H,onCancel:O,runningIds:new Set([...i,...g,...D]),onOpenRun:P=>{h(!1),n(P)}})]})]})});function INe(e){const t=ZA(e),n=b.useCallback(async(r,i="GET",a)=>{try{return await Ki(`/api/owner${r}`,e,{method:i,...a!==void 0?{body:JSON.stringify(a)}:{}})}catch(s){throw console.warn(`[owner] ${i} ${r} failed: ${(s==null?void 0:s.message)??s}`),s}},[e]);return{isOwner:t,call:n}}const _8=["user","email","slack","apikey","internal","anonymous"],_r="h-7 rounded-md border border-input bg-background px-2 text-xs",Er="h-7 text-xs",Ct="text-left font-medium text-muted-foreground px-2 py-1 whitespace-nowrap",Tt="px-2 py-1 align-top",fr="text-muted-foreground hover:text-foreground disabled:opacity-40 transition-colors",Yl=e=>new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),RNe=e=>Object.entries(e).map(([t,n])=>`${t}=${Array.isArray(n)?n.join("|"):String(n)}`).join(" ");function wd(){const[e,t]=b.useState(null),[n,r]=b.useState(null);return{busy:e,error:n,run:async(a,s)=>{if(!e){t(a),r(null);try{await s()}catch(l){r((l==null?void 0:l.message)??String(l))}finally{t(null)}}}}}function rl({error:e}){if(!e)return null;const t=/^Invalid policy: (.*)$/s.exec(e);return y.jsx("div",{className:"text-xs text-destructive border border-destructive/40 rounded-md p-2",children:t?y.jsxs(y.Fragment,{children:[y.jsx("p",{className:"font-medium",children:"Invalid policy — not saved:"}),y.jsx("ul",{className:"list-disc pl-4",children:t[1].split("; ").map((n,r)=>y.jsx("li",{children:n},r))})]}):e})}function A8({value:e,onChange:t,placeholder:n}){const r=(e??[]).join(", "),[i,a]=b.useState(r);return b.useEffect(()=>a(r),[r]),y.jsx(ft,{className:Er,value:i,placeholder:n,onChange:s=>a(s.target.value),onBlur:()=>t(i.split(",").map(s=>s.trim()).filter(Boolean))})}function k8(e,t,n=[]){return{canRevoke:r=>/^(user|internal):/.test(r)&&r!=="internal:agent-internal",canBlock:r=>!n.includes(r),revoke:async r=>{confirm(`Revoke every token issued to ${r}? They must sign in again.`)&&(await e("/tokens/revoke","POST",{principalId:r}),await t())},block:async r=>{const i=prompt(`Block ${r}? Reason (optional):`);i!==null&&(await e("/blocks","POST",{match:{id:r},until:null,reason:i}),await t())}}}const PNe=[["never",0],["1 day",1],["7 days",7],["30 days",30],["90 days",90]];function DNe({call:e,roles:t}){const[n,r]=b.useState(null),[i,a]=b.useState({label:"",role:"",days:0}),[s,l]=b.useState(null),{busy:u,error:d,run:h}=wd(),m=b.useCallback(async()=>r((await e("/api-keys")).keys),[e]);b.useEffect(()=>{h("load",m)},[m]);const p=()=>h("create",async()=>{const w=await e("/api-keys","POST",{label:i.label||"Unnamed",...i.role?{role:i.role}:{},...i.days?{expiresAt:Date.now()+i.days*864e5}:{}});l(w),a({label:"",role:"",days:0}),await m()}),g=w=>navigator.clipboard.writeText(w).catch(x=>console.warn("[owner] clipboard write failed",x));return y.jsxs("div",{className:"space-y-3",children:[y.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[y.jsx(ft,{className:`${Er} w-48`,placeholder:"label",value:i.label,onChange:w=>a({...i,label:w.target.value})}),y.jsxs("select",{className:_r,value:i.role,onChange:w=>a({...i,role:w.target.value}),title:"Role cap (never above the creator)",children:[y.jsx("option",{value:"",children:"role: creator's (uncapped)"}),t.map(w=>y.jsxs("option",{value:w,children:["role cap: ",w]},w))]}),y.jsx("select",{className:_r,value:i.days,onChange:w=>a({...i,days:Number(w.target.value)}),children:PNe.map(([w,x])=>y.jsxs("option",{value:x,children:["expires: ",w]},x))}),y.jsxs(we,{size:"sm",className:"h-7 text-xs",disabled:!!u,onClick:p,children:[u==="create"?y.jsx(Yi,{className:"w-3 h-3 mr-1 animate-spin"}):y.jsx(ko,{className:"w-3 h-3 mr-1"})," Create key"]})]}),s&&y.jsxs("div",{className:"border border-amber-500/50 bg-amber-500/10 rounded-lg p-2 space-y-1",children:[y.jsxs("p",{className:"text-xs font-medium",children:['Key "',s.label,`" — copy it now, it won't be shown again:`]}),y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx("code",{className:"text-xs font-mono break-all flex-1 select-all",children:s.key}),y.jsx("button",{className:fr,title:"Copy",onClick:()=>g(s.key),children:y.jsx(Bv,{className:"w-3.5 h-3.5"})}),y.jsx(we,{size:"sm",variant:"ghost",className:"h-6 text-xs",onClick:()=>l(null),children:"Done"})]})]}),y.jsx(rl,{error:d}),y.jsx("div",{className:"border rounded-lg overflow-x-auto",children:y.jsxs("table",{className:"w-full text-xs",children:[y.jsx("thead",{className:"bg-muted/40",children:y.jsxs("tr",{children:[y.jsx("th",{className:Ct,children:"Label"}),y.jsx("th",{className:Ct,children:"Key"}),y.jsx("th",{className:Ct,children:"Creator"}),y.jsx("th",{className:Ct,children:"Role"}),y.jsx("th",{className:Ct,children:"Created"}),y.jsx("th",{className:Ct,children:"Expires"}),y.jsx("th",{className:Ct})]})}),y.jsxs("tbody",{className:"divide-y",children:[n==null?void 0:n.map(w=>{const x=w.expiresAt!==void 0&&w.expiresAt<=Date.now();return y.jsxs("tr",{className:x?"opacity-50":"",children:[y.jsx("td",{className:Tt,children:w.label}),y.jsx("td",{className:`${Tt} font-mono`,children:w.keyPreview}),y.jsx("td",{className:Tt,children:w.email}),y.jsx("td",{className:Tt,children:w.role??y.jsx("span",{className:"text-muted-foreground",children:"creator's"})}),y.jsx("td",{className:`${Tt} whitespace-nowrap`,children:Yl(w.createdAt)}),y.jsx("td",{className:`${Tt} whitespace-nowrap`,children:w.expiresAt?`${Yl(w.expiresAt)}${x?" (expired)":""}`:"never"}),y.jsx("td",{className:`${Tt} text-right`,children:y.jsx("button",{className:`${fr} hover:text-destructive`,title:"Revoke",disabled:!!u,onClick:()=>{confirm(`Revoke key "${w.label}" (${w.keyPreview})?`)&&h(`rm-${w.id}`,async()=>{await e(`/api-keys/${w.id}`,"DELETE"),await m()})},children:y.jsx(Xi,{className:"w-3.5 h-3.5"})})})]},w.id)}),n&&!n.length&&y.jsx("tr",{children:y.jsx("td",{colSpan:7,className:"text-center text-muted-foreground py-6",children:"No API keys."})})]})]})})]})}const jNe=({brokenAt:e,planted:t})=>[e&&!(e.reason==="not-regular-file"&&(t!=null&&t.length))?`chain broken at ${e.file||"audit dir"}${e.line?`:${e.line}`:""} (${e.reason})`:"",t!=null&&t.length?`planted entries (not regular files): ${t.join(", ")}`:""].filter(Boolean).join(" · ")||"chain verify failed",LNe=["auth.allow","auth.deny","role.resolve","turn.start","turn.end","tool.allow","tool.deny","guard.limit","guard.block","escalate","policy.change","policy.tamper","key.create","key.revoke","token.revoke","session.delete"],zNe=100;function $Ne({call:e,onOpenSession:t,onPolicyChange:n,ownerIds:r}){const[i,a]=b.useState({principal:"",type:"",from:"",to:""}),[s,l]=b.useState([]),[u,d]=b.useState(),[h,m]=b.useState(null),[p,g]=b.useState(new Set),{busy:w,error:x,run:E}=wd(),_=k8(e,n,r),k=(M,D,j)=>E(M,async()=>{try{await j()}catch(R){throw(R==null?void 0:R.status)!==404?R:(g(H=>new Set(H).add(D)),new Error("Conversation no longer exists"))}}),O=M=>{const D=new URLSearchParams({limit:String(zNe)});return i.principal.trim()&&D.set("principal",i.principal.trim()),i.type&&D.set("type",i.type),i.from&&D.set("from",new Date(i.from).toISOString()),i.to&&D.set("to",new Date(i.to).toISOString()),M&&D.set("cursor",M),e(`/audit?${D}`)},N=b.useCallback(()=>E("load",async()=>{const M=await O();l(M.items),d(M.nextCursor)}),[e,i]),C=()=>E("more",async()=>{const M=await O(u);l(D=>[...D,...M.items]),d(M.nextCursor)}),T=()=>E("verify",async()=>m(await e("/audit/verify")));return b.useEffect(()=>{N(),T()},[]),y.jsxs("div",{className:"space-y-2",children:[y.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[y.jsx(ft,{className:`${Er} w-56`,placeholder:"principal (exact id)",value:i.principal,onChange:M=>a({...i,principal:M.target.value}),onKeyDown:M=>M.key==="Enter"&&N()}),y.jsxs("select",{className:_r,value:i.type,onChange:M=>a({...i,type:M.target.value}),children:[y.jsx("option",{value:"",children:"all types"}),LNe.map(M=>y.jsx("option",{value:M,children:M},M))]}),y.jsx("label",{className:"text-[10px] text-muted-foreground",children:"from"}),y.jsx("input",{type:"datetime-local",className:_r,value:i.from,onChange:M=>a({...i,from:M.target.value})}),y.jsx("label",{className:"text-[10px] text-muted-foreground",children:"to"}),y.jsx("input",{type:"datetime-local",className:_r,value:i.to,onChange:M=>a({...i,to:M.target.value})}),y.jsxs(we,{size:"sm",className:"h-7 text-xs",disabled:!!w,onClick:N,children:[w==="load"?y.jsx(Yi,{className:"w-3 h-3 mr-1 animate-spin"}):y.jsx(ed,{className:"w-3 h-3 mr-1"})," Search"]}),y.jsx("div",{className:"flex-1"}),h&&y.jsxs("button",{onClick:T,title:"Re-verify the hash chain",className:`flex items-center gap-1 text-[11px] px-2 py-0.5 rounded-full border ${h.ok?"border-green-500/50 text-green-600 dark:text-green-400":"border-destructive text-destructive"}`,children:[h.ok?y.jsx(Lu,{className:"w-3.5 h-3.5"}):y.jsx(mV,{className:"w-3.5 h-3.5"}),h.ok?`chain verified · ${h.lines} lines`:jNe(h)]})]}),y.jsx(rl,{error:x}),y.jsx("div",{className:"border rounded-lg overflow-x-auto",children:y.jsxs("table",{className:"w-full text-xs",children:[y.jsx("thead",{className:"bg-muted/40",children:y.jsxs("tr",{children:[y.jsx("th",{className:Ct,children:"Time"}),y.jsx("th",{className:Ct,children:"Type"}),y.jsx("th",{className:Ct,children:"Principal"}),y.jsx("th",{className:Ct,children:"Role"}),y.jsx("th",{className:Ct,children:"Target / reason"}),y.jsx("th",{className:Ct})]})}),y.jsxs("tbody",{className:"divide-y",children:[s.map(M=>y.jsxs("tr",{children:[y.jsx("td",{className:`${Tt} whitespace-nowrap`,title:M.ts,children:Yl(M.ts)}),y.jsx("td",{className:`${Tt} font-mono whitespace-nowrap ${/deny|block|tamper/.test(M.type)?"text-destructive":""}`,children:M.type}),y.jsx("td",{className:`${Tt} font-mono break-all`,children:M.principal?y.jsx("button",{className:"hover:underline text-left",title:"Filter by this principal",onClick:()=>a({...i,principal:M.principal}),children:M.principal}):"—"}),y.jsx("td",{className:Tt,children:M.role??"—"}),y.jsx("td",{className:`${Tt} break-all`,children:[M.target,M.reason].filter(Boolean).join(" · ")||"—"}),y.jsxs("td",{className:`${Tt} whitespace-nowrap text-right`,children:[M.sessionId&&!p.has(M.sessionId)&&y.jsx("button",{className:`${fr} mr-2`,title:"Open session",disabled:!!w,onClick:()=>k("open",M.sessionId,()=>t(M.sessionId)),children:y.jsx(YG,{className:"w-3.5 h-3.5"})}),M.principal&&_.canRevoke(M.principal)&&y.jsx("button",{className:`${fr} mr-2`,title:"Revoke tokens",disabled:!!w,onClick:()=>E("rv",()=>_.revoke(M.principal)),children:y.jsx(uL,{className:"w-3.5 h-3.5"})}),M.principal&&_.canBlock(M.principal)&&y.jsx("button",{className:`${fr} hover:text-destructive`,title:"Block principal",disabled:!!w,onClick:()=>E("bl",()=>_.block(M.principal)),children:y.jsx(sL,{className:"w-3.5 h-3.5"})})]})]},M.hash)),!s.length&&w!=="load"&&y.jsx("tr",{children:y.jsx("td",{colSpan:6,className:"text-center text-muted-foreground py-6",children:"No audit records match."})})]})]})}),u&&y.jsxs(we,{size:"sm",variant:"outline",className:"h-7 text-xs",disabled:!!w,onClick:C,children:[w==="more"&&y.jsx(Yi,{className:"w-3 h-3 mr-1 animate-spin"})," Load older"]})]})}const hu=e=>{const{blocklist:t,tokensValidAfter:n,...r}=e;return JSON.stringify(r)};function O8(e,t,n){const[r,i]=b.useState(e),[a,s]=b.useState(()=>structuredClone(e.policy)),l=hu(a)!==hu(r.policy);b.useEffect(()=>{!l||hu(e.policy)===hu(a)?(i(e),s(structuredClone(e.policy))):hu(e.policy)===hu(r.policy)&&i(e)},[e]),b.useEffect(()=>{n==null||n(l)},[l,n]),b.useEffect(()=>()=>n==null?void 0:n(!1),[n]);const u=wd(),d=y.jsxs("div",{className:"flex items-center gap-2 sticky -bottom-3 z-10 -mx-3 -mb-3 px-3 pt-2 pb-3 bg-background border-t",children:[y.jsxs(we,{size:"sm",className:"h-7 text-xs",disabled:!l||!!u.busy,onClick:()=>u.run("save",()=>t(a,r.version)),children:[u.busy?y.jsx(Yi,{className:"w-3 h-3 mr-1 animate-spin"}):y.jsx(Wi,{className:"w-3 h-3 mr-1"})," Save policy"]}),y.jsxs(we,{size:"sm",variant:"ghost",className:"h-7 text-xs",disabled:!l,onClick:()=>{i(e),s(structuredClone(e.policy))},children:[y.jsx(bV,{className:"w-3 h-3 mr-1"})," Discard"]}),l&&y.jsx("span",{className:"text-[10px] text-amber-500",children:"unsaved changes"})]});return{draft:a,setDraft:s,error:u.error,saveBar:d}}function BNe({doc:e,save:t,onDirty:n}){const{draft:r,setDraft:i,error:a,saveBar:s}=O8(e,t,n),[l,u]=b.useState(""),[d,h]=b.useState(""),m=Object.keys(r.profiles),p=(x,E)=>i(_=>({..._,roles:{..._.roles,[x]:{..._.roles[x],...E}}})),g=(x,E)=>i(_=>({..._,profiles:{..._.profiles,[x]:{..._.profiles[x],...E}}})),w=(x,E)=>Object.fromEntries(Object.entries(x).filter(([_])=>_!==E));return y.jsxs("div",{className:"space-y-4",children:[y.jsx(rl,{error:a}),y.jsxs("section",{className:"space-y-2",children:[y.jsx("h3",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Roles"}),y.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Owners come only from the OWNERS env; this row only picks their rank and profile."}),y.jsx("div",{className:"border rounded-lg divide-y",children:Object.entries(r.roles).sort((x,E)=>E[1].rank-x[1].rank).map(([x,E])=>y.jsxs("div",{className:"flex items-center gap-2 p-2",children:[y.jsx("span",{className:"text-sm font-medium w-28 truncate",children:x}),y.jsx("label",{className:"text-[10px] text-muted-foreground",children:"rank"}),y.jsx(ft,{type:"number",className:`${Er} w-20`,value:Number.isFinite(E.rank)?E.rank:"",onChange:_=>p(x,{rank:_.target.value===""?NaN:Number(_.target.value)})}),y.jsx("label",{className:"text-[10px] text-muted-foreground",children:"profile"}),y.jsxs("select",{className:_r,value:E.profile,onChange:_=>p(x,{profile:_.target.value}),children:[!m.includes(E.profile)&&y.jsxs("option",{value:E.profile,children:[E.profile," (missing)"]}),m.map(_=>y.jsx("option",{value:_,children:_},_))]}),y.jsx("div",{className:"flex-1"}),x!=="owner"&&y.jsx("button",{className:`${fr} hover:text-destructive`,title:"Remove role",onClick:()=>i(_=>({..._,roles:w(_.roles,x)})),children:y.jsx(Xi,{className:"w-3.5 h-3.5"})})]},x))}),y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx(ft,{className:`${Er} w-40`,placeholder:"new role name",value:l,onChange:x=>u(x.target.value.trim())}),y.jsxs(we,{size:"sm",variant:"outline",className:"h-7 text-xs",disabled:!l||l in r.roles,onClick:()=>{i(x=>({...x,roles:{...x.roles,[l]:{rank:10,profile:m.includes("none")?"none":m[0]}}})),u("")},children:[y.jsx(ko,{className:"w-3 h-3 mr-1"})," Add role"]}),y.jsx("div",{className:"flex-1"}),y.jsx("label",{className:"text-[10px] text-muted-foreground",children:"default role"}),y.jsx("select",{className:_r,value:r.default,onChange:x=>i(E=>({...E,default:x.target.value})),children:Object.keys(r.roles).filter(x=>x!=="owner").map(x=>y.jsx("option",{value:x,children:x},x))})]})]}),y.jsxs("section",{className:"space-y-2",children:[y.jsx("h3",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Profiles"}),Object.entries(r.profiles).map(([x,E])=>y.jsxs("div",{className:"border rounded-lg p-3 space-y-2",children:[y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx("span",{className:"text-sm font-medium",children:x}),y.jsx("div",{className:"flex-1"}),y.jsx("button",{className:`${fr} hover:text-destructive`,title:"Remove profile",onClick:()=>i(_=>({..._,profiles:w(_.profiles,x)})),children:y.jsx(Xi,{className:"w-3.5 h-3.5"})})]}),y.jsxs("div",{className:"grid grid-cols-[4.5rem_1fr] gap-x-2 gap-y-1.5 items-center",children:[["tools","mcps","env"].map(_=>y.jsx(Xp,{label:_,children:y.jsx(A8,{value:E[_],onChange:k=>g(x,{[_]:k}),placeholder:'comma-separated, "*" = all'})},_)),y.jsx(Xp,{label:"rate",children:y.jsx(ft,{className:`${Er} w-28`,value:E.rate,placeholder:"120/h",onChange:_=>g(x,{rate:_.target.value.trim()})})}),y.jsx(Xp,{label:"readScope",children:y.jsx("select",{className:`${_r} w-28`,value:E.readScope,onChange:_=>g(x,{readScope:_.target.value}),children:["all","own","none"].map(_=>y.jsx("option",{value:_,children:_},_))})}),y.jsx(Xp,{label:"outbound",children:y.jsx("input",{type:"checkbox",className:"h-4 w-4 justify-self-start",checked:E.outbound,onChange:_=>g(x,{outbound:_.target.checked})})})]})]},x)),y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx(ft,{className:`${Er} w-40`,placeholder:"new profile name",value:d,onChange:x=>h(x.target.value.trim())}),y.jsxs(we,{size:"sm",variant:"outline",className:"h-7 text-xs",disabled:!d||d in r.profiles,onClick:()=>{i(x=>({...x,profiles:{...x.profiles,[d]:{tools:[],mcps:[],env:[],outbound:!1,readScope:"none",rate:"0"}}})),h("")},children:[y.jsx(ko,{className:"w-3 h-3 mr-1"})," Add profile"]})]})]}),s]})}function Xp({label:e,children:t}){return y.jsxs(y.Fragment,{children:[y.jsx("label",{className:"text-[11px] text-muted-foreground",children:e}),t]})}const UNe=new Set(["kind","id","emailIn","domain","verified"]);function FNe({doc:e,save:t,call:n,onDirty:r}){const{draft:i,setDraft:a,error:s,saveBar:l}=O8(e,t,r),u=Object.keys(i.roles).filter(p=>p!=="owner"),d=p=>a(g=>({...g,bindings:p([...g.bindings])})),h=(p,g,w)=>d(x=>{const E={...x[p].match};return w===void 0||w===""||Array.isArray(w)&&!w.length?delete E[g]:E[g]=w,x[p]={...x[p],match:E},x}),m=(p,g)=>d(w=>{const[x]=w.splice(p,1);return w.splice(g,0,x),w});return y.jsxs("div",{className:"space-y-4",children:[y.jsx(rl,{error:s}),y.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Ordered — the first matching binding decides the role; no match → default role ",y.jsx("b",{children:i.default}),"."]}),y.jsxs("div",{className:"space-y-2",children:[i.bindings.map((p,g)=>{const w=Object.entries(p.match).filter(([x])=>!UNe.has(x));return y.jsxs("div",{className:"border rounded-lg p-2 space-y-1.5",children:[y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsxs("span",{className:"text-[10px] font-mono text-muted-foreground w-5",children:["#",g+1]}),y.jsx("label",{className:"text-[10px] text-muted-foreground",children:"role"}),y.jsxs("select",{className:_r,value:p.role,onChange:x=>d(E=>(E[g]={...E[g],role:x.target.value},E)),children:[!u.includes(p.role)&&y.jsxs("option",{value:p.role,children:[p.role," (invalid)"]}),u.map(x=>y.jsx("option",{value:x,children:x},x))]}),y.jsx("div",{className:"flex-1"}),y.jsx("button",{className:fr,title:"Move up",disabled:g===0,onClick:()=>m(g,g-1),children:y.jsx(KG,{className:"w-3.5 h-3.5"})}),y.jsx("button",{className:fr,title:"Move down",disabled:g===i.bindings.length-1,onClick:()=>m(g,g+1),children:y.jsx(HG,{className:"w-3.5 h-3.5"})}),y.jsx("button",{className:`${fr} hover:text-destructive`,title:"Remove",onClick:()=>d(x=>x.filter((E,_)=>_!==g)),children:y.jsx(Xi,{className:"w-3.5 h-3.5"})})]}),y.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[y.jsxs("select",{className:_r,title:"kind",value:p.match.kind??"",onChange:x=>h(g,"kind",x.target.value),children:[y.jsx("option",{value:"",children:"any kind"}),_8.map(x=>y.jsx("option",{value:x,children:x},x))]}),y.jsxs("select",{className:_r,title:"verified",value:p.match.verified===void 0?"":String(p.match.verified),onChange:x=>h(g,"verified",x.target.value===""?void 0:x.target.value==="true"),children:[y.jsx("option",{value:"",children:"verified: any"}),y.jsx("option",{value:"true",children:"verified"}),y.jsx("option",{value:"false",children:"unverified"})]}),y.jsx(ft,{className:`${Er} w-40`,placeholder:"domain",value:p.match.domain??"",onChange:x=>h(g,"domain",x.target.value.trim())}),y.jsx(ft,{className:`${Er} w-48`,placeholder:"id (e.g. slack:U123)",value:p.match.id??"",onChange:x=>h(g,"id",x.target.value.trim())}),y.jsx("div",{className:"flex-1 min-w-48",children:y.jsx(A8,{value:p.match.emailIn,onChange:x=>h(g,"emailIn",x),placeholder:"emails (comma-separated)"})})]}),w.length>0&&y.jsxs("p",{className:"text-[10px] font-mono text-muted-foreground",children:["also matches: ",JSON.stringify(Object.fromEntries(w))]})]},g)}),y.jsxs(we,{size:"sm",variant:"outline",className:"h-7 text-xs",disabled:!u.length,onClick:()=>d(p=>[...p,{match:{kind:"user"},role:u.includes("guest")?"guest":u[u.length-1]}]),children:[y.jsx(ko,{className:"w-3 h-3 mr-1"})," Add binding"]})]}),l,y.jsx(HNe,{call:n})]})}function HNe({call:e}){const[t,n]=b.useState({kind:"user",email:"",id:"",verified:!0,lane:"",role:""}),[r,i]=b.useState(null),{busy:a,error:s,run:l}=wd(),u=h=>{n(m=>({...m,...h})),i(null)},d=()=>l("test",async()=>{i(await e("/policy/test","POST",{kind:t.kind,verified:t.verified,...t.email?{email:t.email}:{},...t.id?{id:t.id}:{},...t.lane?{lane:t.lane}:{},...t.role?{role:t.role}:{}}))});return y.jsxs("section",{className:"border rounded-lg p-3 space-y-2 bg-muted/20",children:[y.jsxs("h3",{className:"text-xs font-medium flex items-center gap-1.5",children:[y.jsx(QG,{className:"w-3.5 h-3.5"})," Test a principal ",y.jsx("span",{className:"text-muted-foreground font-normal",children:"(against the SAVED policy)"})]}),y.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[y.jsx("select",{className:_r,value:t.kind,onChange:h=>u({kind:h.target.value}),children:_8.map(h=>y.jsx("option",{value:h,children:h},h))}),y.jsx(ft,{className:`${Er} w-52`,placeholder:t.kind==="apikey"?"creator email":"email",value:t.email,onChange:h=>u({email:h.target.value.trim()})}),y.jsx(ft,{className:`${Er} w-32`,placeholder:"id (optional)",value:t.id,onChange:h=>u({id:h.target.value.trim()})}),t.kind==="internal"&&y.jsx(ft,{className:`${Er} w-28`,placeholder:"lane",value:t.lane,onChange:h=>u({lane:h.target.value.trim()})}),t.kind==="apikey"&&y.jsx(ft,{className:`${Er} w-28`,placeholder:"key role cap",value:t.role,onChange:h=>u({role:h.target.value.trim()})}),y.jsxs("label",{className:"flex items-center gap-1 text-xs",children:[y.jsx("input",{type:"checkbox",checked:t.verified,onChange:h=>u({verified:h.target.checked})})," verified"]}),y.jsxs(we,{size:"sm",className:"h-7 text-xs",disabled:!!a,onClick:d,children:[a&&y.jsx(Yi,{className:"w-3 h-3 mr-1 animate-spin"})," Resolve"]})]}),y.jsx(rl,{error:s}),r&&y.jsxs("p",{className:"text-xs font-mono",children:[r.principal," → role ",y.jsx("b",{children:r.role})," · rank ",r.rank," · profile ",y.jsx("b",{children:r.profile}),r.blocked&&y.jsxs("span",{className:"text-destructive",children:[" · BLOCKED",r.blocked.reason?` (${r.blocked.reason})`:""]})]})]})}const KNe=[["permanent",0],["1 hour",3600],["24 hours",86400],["7 days",604800],["30 days",2592e3]];function qNe({call:e,onPolicyChange:t}){const[n,r]=b.useState(null),[i,a]=b.useState({field:"id",value:"",ttl:0,reason:""}),{busy:s,error:l,run:u}=wd(),d=b.useCallback(async()=>r(await e("/blocks")),[e]);b.useEffect(()=>{u("load",d)},[d]);const h=()=>u("add",async()=>{const p=i.value.trim(),g=i.field==="emailIn"?{emailIn:[p]}:{[i.field]:p};await e("/blocks","POST",{match:g,until:i.ttl?Math.floor(Date.now()/1e3)+i.ttl:null,reason:i.reason}),a({...i,value:"",reason:""}),await Promise.all([d(),t()])}),m=p=>u("rm",async()=>{await e("/blocks","DELETE",p),await Promise.all([d(),t()])});return y.jsxs("div",{className:"space-y-4",children:[y.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[y.jsxs("select",{className:_r,value:i.field,onChange:p=>a({...i,field:p.target.value}),children:[y.jsx("option",{value:"id",children:"principal id"}),y.jsx("option",{value:"emailIn",children:"email"}),y.jsx("option",{value:"domain",children:"domain"})]}),y.jsx(ft,{className:`${Er} w-56`,placeholder:i.field==="id"?"user:x@y.com / slack:U123":i.field==="domain"?"spam.tld":"x@y.com",value:i.value,onChange:p=>a({...i,value:p.target.value})}),y.jsx("select",{className:_r,value:i.ttl,onChange:p=>a({...i,ttl:Number(p.target.value)}),children:KNe.map(([p,g])=>y.jsx("option",{value:g,children:p},g))}),y.jsx(ft,{className:`${Er} w-40`,placeholder:"reason",value:i.reason,onChange:p=>a({...i,reason:p.target.value})}),y.jsxs(we,{size:"sm",className:"h-7 text-xs",disabled:!!s||!i.value.trim(),onClick:h,children:[s==="add"?y.jsx(Yi,{className:"w-3 h-3 mr-1 animate-spin"}):y.jsx(ko,{className:"w-3 h-3 mr-1"})," Block"]}),y.jsx("button",{className:fr,title:"Refresh",onClick:()=>u("load",d),children:y.jsx(ed,{className:`w-3.5 h-3.5 ${s==="load"?"animate-spin":""}`})})]}),y.jsx(rl,{error:l}),y.jsxs("section",{className:"space-y-1",children:[y.jsx("h3",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Manual (policy)"}),y.jsx("div",{className:"border rounded-lg overflow-x-auto",children:y.jsxs("table",{className:"w-full text-xs",children:[y.jsx("thead",{className:"bg-muted/40",children:y.jsxs("tr",{children:[y.jsx("th",{className:Ct,children:"Match"}),y.jsx("th",{className:Ct,children:"Until"}),y.jsx("th",{className:Ct,children:"Reason"}),y.jsx("th",{className:Ct})]})}),y.jsxs("tbody",{className:"divide-y",children:[n==null?void 0:n.manual.map(p=>{const g=p.until!==null&&p.until*1e3<=Date.now();return y.jsxs("tr",{className:g?"opacity-50":"",children:[y.jsx("td",{className:`${Tt} font-mono break-all`,children:RNe(p.match)}),y.jsx("td",{className:`${Tt} whitespace-nowrap`,children:p.until===null?"permanent":`${Yl(p.until*1e3)}${g?" (expired)":""}`}),y.jsx("td",{className:Tt,children:p.reason||"—"}),y.jsx("td",{className:`${Tt} text-right`,children:y.jsx("button",{className:`${fr} hover:text-destructive`,title:"Remove",disabled:!!s,onClick:()=>m({source:"manual",index:p.index,match:p.match}),children:y.jsx(Xi,{className:"w-3.5 h-3.5"})})})]},p.index)}),n&&!n.manual.length&&y.jsx("tr",{children:y.jsx("td",{colSpan:4,className:"text-center text-muted-foreground py-4",children:"No manual blocks."})})]})]})})]}),y.jsxs("section",{className:"space-y-1",children:[y.jsx("h3",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Automatic (guard)"}),y.jsx("div",{className:"border rounded-lg overflow-x-auto",children:y.jsxs("table",{className:"w-full text-xs",children:[y.jsx("thead",{className:"bg-muted/40",children:y.jsxs("tr",{children:[y.jsx("th",{className:Ct,children:"Key"}),y.jsx("th",{className:Ct,children:"Since"}),y.jsx("th",{className:Ct,children:"Until"}),y.jsx("th",{className:Ct,children:"Reason"}),y.jsx("th",{className:Ct})]})}),y.jsxs("tbody",{className:"divide-y",children:[n==null?void 0:n.auto.map(p=>y.jsxs("tr",{children:[y.jsx("td",{className:`${Tt} font-mono break-all`,children:p.key}),y.jsx("td",{className:`${Tt} whitespace-nowrap`,children:Yl(p.at)}),y.jsx("td",{className:`${Tt} whitespace-nowrap`,children:Yl(p.until)}),y.jsx("td",{className:Tt,children:p.reason}),y.jsx("td",{className:`${Tt} text-right`,children:y.jsx("button",{className:`${fr} hover:text-destructive`,title:"Clear",disabled:!!s,onClick:()=>m({source:"auto",key:p.key}),children:y.jsx(Xi,{className:"w-3.5 h-3.5"})})})]},p.key)),n&&!n.auto.length&&y.jsx("tr",{children:y.jsx("td",{colSpan:5,className:"text-center text-muted-foreground py-4",children:"No active auto-blocks."})})]})]})})]})]})}function GNe({call:e,onPolicyChange:t,ownerIds:n}){const[r,i]=b.useState(7),[a,s]=b.useState(null),{busy:l,error:u,run:d}=wd(),h=k8(e,t,n),m=b.useCallback(()=>d("load",async()=>s(await e(`/principals?days=${r}`))),[e,r]);return b.useEffect(()=>{m()},[m]),y.jsxs("div",{className:"space-y-2",children:[y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx("span",{className:"text-xs text-muted-foreground",children:"Seen in the audit, last"}),y.jsx("select",{className:_r,value:r,onChange:p=>i(Number(p.target.value)),children:[1,7,30,90].map(p=>y.jsxs("option",{value:p,children:[p," day",p>1?"s":""]},p))}),y.jsx("button",{className:fr,title:"Refresh",onClick:m,children:y.jsx(ed,{className:`w-3.5 h-3.5 ${l==="load"?"animate-spin":""}`})}),(a==null?void 0:a.truncated)&&y.jsx("span",{className:"text-[10px] text-amber-500",children:"scan capped — older activity omitted"})]}),y.jsx(rl,{error:u}),y.jsx("div",{className:"border rounded-lg overflow-x-auto",children:y.jsxs("table",{className:"w-full text-xs",children:[y.jsx("thead",{className:"bg-muted/40",children:y.jsxs("tr",{children:[y.jsx("th",{className:Ct,children:"Principal"}),y.jsx("th",{className:Ct,children:"Kind"}),y.jsx("th",{className:Ct,children:"Last role"}),y.jsx("th",{className:Ct,children:"Last seen"}),y.jsx("th",{className:Ct,children:"Turns"}),y.jsx("th",{className:Ct,title:"Includes shadow (would-deny) verdicts",children:"Denies"}),y.jsx("th",{className:Ct})]})}),y.jsxs("tbody",{className:"divide-y",children:[a==null?void 0:a.principals.map(p=>y.jsxs("tr",{children:[y.jsx("td",{className:`${Tt} font-mono break-all`,children:p.id}),y.jsx("td",{className:Tt,children:p.kind}),y.jsx("td",{className:Tt,children:p.lastRole??"—"}),y.jsx("td",{className:`${Tt} whitespace-nowrap`,children:Yl(p.lastSeen)}),y.jsx("td",{className:Tt,children:p.turns}),y.jsx("td",{className:`${Tt} ${p.denies?"text-destructive":""}`,children:p.denies}),y.jsxs("td",{className:`${Tt} whitespace-nowrap text-right`,children:[h.canRevoke(p.id)&&y.jsx("button",{className:`${fr} mr-2`,title:"Revoke tokens",disabled:!!l,onClick:()=>d(`rv-${p.id}`,()=>h.revoke(p.id)),children:y.jsx(uL,{className:"w-3.5 h-3.5"})}),h.canBlock(p.id)&&y.jsx("button",{className:`${fr} hover:text-destructive`,title:"Block",disabled:!!l,onClick:()=>d(`bl-${p.id}`,()=>h.block(p.id)),children:y.jsx(sL,{className:"w-3.5 h-3.5"})})]})]},p.id)),a&&!a.principals.length&&y.jsx("tr",{children:y.jsx("td",{colSpan:7,className:"text-center text-muted-foreground py-6",children:"No principals in this window."})})]})]})})]})}const N8=[["roles","Roles & Profiles"],["bindings","Bindings"],["principals","Principals"],["keys","API keys"],["blocks","Blocklist"],["audit","Audit"]],C8="owner-console-tab";function VNe(){try{const e=localStorage.getItem(C8);return N8.some(([t])=>t===e)?e:"roles"}catch{return"roles"}}function qD({call:e,onOpenSession:t,trigger:n}){const[r,i]=b.useState(!1),[a,s]=b.useState(VNe),[l,u]=b.useState(null),[d,h]=b.useState(null),m=b.useCallback(async()=>{try{u(await e("/policy")),h(null)}catch(k){h((k==null?void 0:k.message)??String(k))}},[e]);b.useEffect(()=>{r&&m()},[r,m]);const p=async(k,O)=>{await e("/policy","PUT",{policy:k,version:O}),await m()},[g,w]=b.useState(!1),x=()=>!g||confirm("You have unsaved policy edits. Discard them?"),E=k=>{if(!(k===a||!x())){s(k);try{localStorage.setItem(C8,k)}catch(O){console.warn("[owner] could not persist tab",O)}}},_=l?Object.keys(l.policy.roles).filter(k=>k!=="owner"):[];return y.jsxs(Oo,{open:r,onOpenChange:k=>{(k||x())&&i(k)},children:[y.jsx(rd,{asChild:!0,children:n}),y.jsxs(Na,{className:"max-w-[95vw] sm:max-w-5xl h-[85dvh] flex flex-col gap-0 p-0",children:[y.jsxs(Bs,{className:"px-4 pt-4 pb-2 border-b shrink-0",children:[y.jsxs(No,{className:"flex items-center gap-2",children:[y.jsx(Lu,{className:"w-4 h-4"})," Owner Console",y.jsx(we,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-1",title:"Reload policy",onClick:m,children:y.jsx(ed,{className:"w-3.5 h-3.5"})})]}),y.jsx("div",{className:"flex gap-1 overflow-x-auto pt-2",role:"tablist",children:N8.map(([k,O])=>y.jsx("button",{role:"tab","aria-selected":a===k,onClick:()=>E(k),className:Be("text-xs px-2.5 py-1 rounded-md whitespace-nowrap transition-colors",a===k?"bg-accent text-foreground font-medium":"text-muted-foreground hover:text-foreground"),children:O},k))})]}),y.jsxs("div",{className:"flex-1 overflow-y-auto p-3 space-y-3",children:[y.jsx(rl,{error:d}),l&&!l.valid&&y.jsx("p",{className:"text-xs text-destructive border border-destructive/40 rounded-md p-2",children:"The policy file is invalid — the server is failing closed (owners only). Saving a valid policy restores it."}),(a==="roles"||a==="bindings")&&!l&&!d&&y.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"Loading…"}),a==="roles"&&l&&y.jsx(BNe,{doc:l,save:p,onDirty:w}),a==="bindings"&&l&&y.jsx(FNe,{doc:l,save:p,call:e,onDirty:w}),a==="principals"&&y.jsx(GNe,{call:e,onPolicyChange:m,ownerIds:(l==null?void 0:l.ownerIds)??[]}),a==="keys"&&y.jsx(DNe,{call:e,roles:_}),a==="blocks"&&y.jsx(qNe,{call:e,onPolicyChange:m}),a==="audit"&&y.jsx($Ne,{call:e,onPolicyChange:m,ownerIds:(l==null?void 0:l.ownerIds)??[],onOpenSession:async k=>{await t(k),i(!1)}})]})]})]})}function T8(){const e=localStorage.getItem("dark-mode");return e!==null?e==="true":window.matchMedia("(prefers-color-scheme: dark)").matches}let Xl=typeof window<"u"?T8():!0;const AE=new Set;function M8(){document.documentElement.classList.toggle("dark",Xl),localStorage.setItem("dark-mode",String(Xl)),AE.forEach(e=>e())}typeof window<"u"&&M8();function I8(e){e!==Xl&&(Xl=e,M8())}function WNe(e){AE.add(e);const t=n=>{n.key==="dark-mode"&&I8(T8())};return window.addEventListener("storage",t),()=>{AE.delete(e),window.removeEventListener("storage",t)}}function YNe(){return{dark:b.useSyncExternalStore(WNe,()=>Xl,()=>Xl),toggle:()=>I8(!Xl)}}const GD=4;function XNe(e,t){const[n,r]=b.useState({}),[i,a]=b.useState([]),s=b.useRef(t);s.current=t;const l=b.useRef(!document.hidden),u=b.useRef(e);u.current=e,b.useEffect(()=>{const x=()=>{var k;l.current=!document.hidden,(k=u.current)==null||k.sendPresence(s.current,l.current),l.current&&s.current&&h(s.current)},E=()=>{var k;l.current=!0,(k=u.current)==null||k.sendPresence(s.current,!0),s.current&&h(s.current)},_=()=>{var k;l.current=!1,(k=u.current)==null||k.sendPresence(s.current,!1)};return document.addEventListener("visibilitychange",x),window.addEventListener("focus",E),window.addEventListener("blur",_),()=>{document.removeEventListener("visibilitychange",x),window.removeEventListener("focus",E),window.removeEventListener("blur",_)}},[]),b.useEffect(()=>{e==null||e.sendPresence(t,l.current),t&&l.current&&h(t)},[t,e]),b.useEffect(()=>{},[i.length]);const d=b.useCallback(x=>{var E,_;if(x.type==="unread"){if(s.current===x.sessionId&&l.current){(E=u.current)==null||E.markRead(x.sessionId);return}r(O=>({...O,[x.sessionId]:{count:x.count,preview:x.preview,source:x.source,title:x.title}})),a(O=>{const N=O.filter(T=>T.sessionId!==x.sessionId);return[{id:`${x.sessionId}-${Date.now()}`,sessionId:x.sessionId,preview:x.preview,title:x.title,ts:Date.now()},...N].slice(0,GD)})}if(x.type==="unread_sync"){const k={};for(const[O,N]of Object.entries(x.sessions)){if(O===s.current&&l.current){(_=u.current)==null||_.markRead(O);continue}k[O]={count:N.count,preview:N.preview,source:N.source,title:N.title}}r(k)}x.type==="unread_cleared"&&r(k=>{const O={...k};return delete O[x.sessionId],O})},[]),h=b.useCallback(x=>{var E;r(_=>{if(!_[x])return _;const k={..._};return delete k[x],k}),a(_=>_.filter(k=>k.sessionId!==x)),(E=u.current)==null||E.markRead(x)},[]),m=b.useCallback(x=>{a(E=>E.filter(_=>_.id!==x))},[]),p=b.useCallback(x=>{s.current===x.sessionId&&l.current||a(E=>{const _=E.filter(O=>O.sessionId!==x.sessionId);return[{id:`${x.sessionId}-${Date.now()}`,sessionId:x.sessionId,preview:x.preview,title:x.title,ts:Date.now()},..._].slice(0,GD)})},[]),g=Object.keys(n).length;b.useEffect(()=>{const x="Shraga";document.title=g>0?`(${g}) ${x}`:x,ZNe(g)},[g]);const w=b.useRef(0);return b.useEffect(()=>{g>w.current,w.current=g},[g]),{unreads:n,toasts:i,totalUnread:g,markRead:h,dismissToast:m,addToast:p,handleUnreadEvent:d}}let mu=null,Mw=null;function ZNe(e){if(typeof document>"u")return;if(!Mw){const n=document.querySelector('link[rel="icon"]');Mw=(n==null?void 0:n.href)??""}if(e===0){VD(Mw||"");return}mu||(mu=document.createElement("canvas"),mu.width=32,mu.height=32);const t=mu.getContext("2d");t&&(t.clearRect(0,0,32,32),t.fillStyle="#6366f1",t.beginPath(),t.arc(16,16,14,0,Math.PI*2),t.fill(),t.fillStyle="#ef4444",t.beginPath(),t.arc(24,8,8,0,Math.PI*2),t.fill(),t.fillStyle="#fff",t.font="bold 10px sans-serif",t.textAlign="center",t.textBaseline="middle",t.fillText(e>9?"9+":String(e),24,8),VD(mu.toDataURL()))}function VD(e){let t=document.querySelector('link[rel="icon"]');t||(t=document.createElement("link"),t.rel="icon",document.head.appendChild(t)),t.href!==e&&(t.href=e)}function QNe({toasts:e,onDismiss:t,onOpen:n}){return e.length===0?null:y.jsx("div",{className:"fixed bottom-4 right-4 z-[100] flex flex-col-reverse gap-2 max-w-sm w-full pointer-events-none",children:e.map((r,i)=>y.jsxs("div",{className:Be("pointer-events-auto bg-white dark:bg-zinc-800 border border-zinc-300 dark:border-zinc-600 rounded-lg shadow-[0_8px_30px_rgb(0,0,0,0.12)] dark:shadow-[0_8px_30px_rgb(0,0,0,0.5)] p-3 pr-7 cursor-pointer relative","transform transition-all duration-300 ease-out","hover:bg-zinc-50 dark:hover:bg-zinc-700 group",i===0?"animate-in slide-in-from-bottom-2 fade-in":""),onClick:()=>{n(r.sessionId),t(r.id)},children:[y.jsx("button",{onClick:a=>{a.stopPropagation(),t(r.id)},className:"absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity p-0.5 hover:bg-muted rounded",children:y.jsx(Ql,{className:"w-3 h-3 text-muted-foreground"})}),y.jsxs("div",{className:"flex items-start gap-2.5",children:[y.jsx(Gw,{className:"w-4 h-4 mt-0.5 shrink-0 text-blue-500"}),y.jsxs("div",{className:"flex-1 min-w-0",children:[y.jsx("div",{className:"text-xs font-medium text-foreground truncate",children:r.title||`Session ${r.sessionId.slice(0,8)}`}),y.jsx("div",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-2",children:r.preview})]})]})]},r.id))})}const JNe={"wrong-backend":{icon:uV,classes:"bg-red-600 text-white border-red-700"},offline:{icon:wV,classes:"bg-red-600 text-white border-red-700"},"server-error":{icon:hV,classes:"bg-amber-500 text-amber-950 border-amber-600"},"ws-down":{icon:yV,classes:"bg-amber-500 text-amber-950 border-amber-600"}};function WD(){const[e,t]=b.useState(null);if(b.useEffect(()=>Gq(t),[]),!e)return null;const{icon:n,classes:r}=JNe[e.kind];return y.jsx("div",{role:"alert","data-testid":"backend-status-banner","data-fault-kind":e.kind,className:Be("shrink-0 border-b px-3 py-2 text-xs",r),style:{paddingTop:"max(0.5rem, env(safe-area-inset-top))"},children:y.jsxs("div",{className:"flex items-start gap-2",children:[y.jsx(n,{className:"w-4 h-4 mt-0.5 shrink-0"}),y.jsxs("div",{className:"min-w-0 flex-1",children:[y.jsx("div",{className:"font-semibold",children:e.title}),y.jsx("div",{className:"opacity-90 mt-0.5",children:e.hint}),(e.path||e.status!==void 0)&&y.jsxs("div",{className:"opacity-75 mt-0.5 font-mono text-[11px] break-all",children:[e.path??"websocket",e.status!==void 0?` → ${e.status}`:""]})]}),y.jsxs("button",{onClick:()=>window.location.reload(),className:"shrink-0 inline-flex items-center gap-1 rounded bg-white/20 hover:bg-white/30 px-2 py-1 font-semibold transition-colors",children:[y.jsx(ed,{className:"w-3 h-3"}),"Retry"]})]})})}const pu=jv.forComponent("App");function YD(){return new URLSearchParams(window.location.search).get("session")||void 0}function eCe(e){const t=new URL(window.location.href);e?t.searchParams.set("session",e):t.searchParams.delete("session");const n=t.toString()!==window.location.href;e&&n?window.history.pushState(null,"",t.toString()):window.history.replaceState(null,"",t.toString())}function tCe(){return y.jsx($G,{value:{},children:y.jsx(nCe,{})})}function nCe(){var In,vt;const e=za(),{dark:t,toggle:n}=YNe(),{user:r,token:i,getToken:a,loading:s,mode:l,needsSetup:u,loginLocal:d,registerLocal:h,logout:m}=Yj(),{isOwner:p,call:g}=INe(a),[w,x]=b.useState(()=>localStorage.getItem("shraga:sidebarOpen")!=="false"),E=b.useCallback(me=>{x(Xe=>{const en=typeof me=="function"?me(Xe):me;return localStorage.setItem("shraga:sidebarOpen",String(en)),en})},[]),[_,k]=b.useState(!1),[O,N]=b.useState({top:52,right:8}),C=b.useRef(null),T=b.useCallback(()=>{var Xe;const me=(Xe=C.current)==null?void 0:Xe.getBoundingClientRect();me&&N({top:me.bottom+4,right:Math.max(4,window.innerWidth-me.right)}),k(en=>!en)},[]),[M,D]=b.useState({}),j=b.useRef(null),[R,H]=b.useState(0),[P,G]=b.useState(0),[q,X]=b.useState(new Set),[U,K]=b.useState([]),[F,V]=b.useState([]),[$,L]=b.useState(0),[W,z]=b.useState(new Set),[ie,he]=b.useState(!1),[ge,Se]=b.useState(()=>localStorage.getItem("shraga:authorized")==="1"?!0:null),[ze,fe]=b.useState(()=>YD()),Ee=b.useCallback((me,Xe)=>fe(me),[]),Te=b.useCallback((me,Xe)=>fe(Xe),[]),de=b.useCallback((me,Xe)=>{},[]),nt=b.useCallback(()=>H(me=>me+1),[]),He=b.useRef(!1);b.useEffect(()=>{if(!i){!He.current&&localStorage.getItem("shraga:authorized")!=="1"&&Se(null);return}a().then(async me=>{var Xe,en,di;if(!me)return Se(!1);try{const gn=await fetch("/api/config",{headers:{Authorization:`Bearer ${me}`}});if(zv("/api/config",gn),gn.ok)return He.current=!0,localStorage.setItem("shraga:authorized","1"),Se(!0);const Li=await gn.json().catch(()=>({}));if(gn.status===401&&((Xe=Li.error)!=null&&Xe.includes("audience")||(en=Li.error)!=null&&en.includes("aud"))){pu.warn("token audience mismatch — signing out stale session"),m();return}if(gn.status===403&&((di=Li.error)!=null&&di.toLowerCase().includes("whitelist")))return localStorage.removeItem("shraga:authorized"),Se(!1);if(He.current)return;Se(gn.status!==401&&gn.status!==403)}catch(gn){if($v("/api/config",gn),pu.warn("auth probe could not reach /api/config",gn),He.current)return;Se(!0)}})},[i,a]);const Ae=b.useCallback(()=>{i&&(L(me=>me+1),jl("/api/workspace",a).then(me=>me.json()).then(me=>V(me.entries??[])).catch(me=>pu.warn("workspace refresh failed",me)))},[i,a]),De=b.useCallback(me=>{G(Xe=>Xe+1),me.type==="schedule:run_started"?(X(Xe=>new Set(Xe).add(me.scheduleId)),nt()):me.type==="schedule:run_finished"?(X(Xe=>{const en=new Set(Xe);return en.delete(me.scheduleId),en}),nt()):me.type==="schedule:deleted"&&X(Xe=>{const en=new Set(Xe);return en.delete(me.id),en})},[nt]),Ht=b.useRef(null),un=b.useRef(null),Yn=b.useRef(null),Or=b.useRef(ze);Or.current=ze;const ji=b.useCallback(me=>{var Xe,en;if((Xe=Yn.current)==null||Xe.call(Yn,me),me.type.startsWith("schedule:")){De(me);return}switch(me.type,me.type){case"workspace_change":Ht.current||(Ht.current=setTimeout(()=>{Ht.current=null,Ae()},1e3));break;case"session_title_updated":nt();break;case"session_messages_changed":nt(),me.sessionId===Or.current&&((en=un.current)==null||en.call(un,me.sessionId));break;case"session_busy":z(di=>{const gn=new Set(di);return me.busy?gn.add(me.sessionId):gn.delete(me.sessionId),gn}),me.busy||nt();break}},[De,Ae,nt]),{socket:ir,connectionStatus:ia,authError:Gt}=Qq(i,a,ji),{unreads:Ko,toasts:oe,markRead:pe,dismissToast:$e,addToast:Je,handleUnreadEvent:mt}=XNe(ir,ze),Fn=b.useCallback(async me=>{await Ki(`/api/sessions/${encodeURIComponent(me)}/meta`,a),Ee(me),pe(me)},[a,Ee,pe]);Yn.current=mt,un.current=pe,DG({socket:ir,getToken:a,pushEnabled:ie,activeSessionId:ze,switchTo:()=>{},openSession:Ee,onForegroundMessage:me=>{var en;const Xe=typeof((en=me.data)==null?void 0:en.session)=="string"?me.data.session:void 0;Xe&&Je({sessionId:Xe,preview:me.body||"New message",title:me.title})}}),b.useEffect(()=>{jG()},[]),b.useEffect(()=>{eCe(ze),ze&&pe(ze)},[ze,pe]),b.useEffect(()=>{const me=()=>fe(YD());return window.addEventListener("popstate",me),()=>window.removeEventListener("popstate",me)},[]),b.useEffect(()=>{i&&(jl("/api/config",a).then(me=>me.json()).then(D).catch(me=>pu.warn("config load failed",me)),jl("/api/skills",a).then(me=>me.json()).then(me=>K(me.skills)).catch(me=>pu.warn("skills load failed",me)),jl("/api/features",a).then(me=>me.json()).then(me=>he(!!me.push)).catch(me=>pu.warn("features load failed",me)))},[i,a]),b.useEffect(()=>{Ae()},[Ae]);const Nr=b.useCallback(()=>{fe(void 0),window.innerWidth<640&&E(!1)},[E]),dn=b.useMemo(()=>F.filter(me=>me.type==="file").map(me=>me.path),[F]),Jt=b.useMemo(()=>({socket:ir,connectionStatus:ia,getToken:a,token:i,agentConfig:M,setAgentConfig:D,activeSessionId:ze,skills:U,workspaceFiles:dn,openSchedules:()=>{var me;return(me=j.current)==null?void 0:me.open()},markRead:pe,bumpSidebar:nt,assignSession:Te,renameTab:de,openSession:Ee}),[ir,ia,a,i,M,ze,U,dn,pe,nt,Te,de,Ee]);return s?y.jsx("div",{className:"flex h-full items-center justify-center text-muted-foreground text-sm",children:"Loading…"}):!r||!i?y.jsxs("div",{className:"flex h-full flex-col",children:[y.jsx(WD,{}),y.jsx("div",{className:"flex-1 min-h-0",children:y.jsx(zV,{mode:l,needsSetup:u,onLoginLocal:d,onRegisterLocal:h})})]}):ge===null?y.jsx("div",{className:"flex h-full items-center justify-center text-muted-foreground text-sm",children:"Verifying access…"}):!ge||Gt?y.jsx("div",{className:"flex h-full items-center justify-center bg-background",children:y.jsxs("div",{className:"flex flex-col items-center gap-4 p-8 rounded-xl border bg-card shadow-sm w-full max-w-sm text-center",children:[y.jsx("div",{className:"flex items-center justify-center w-12 h-12 rounded-full bg-destructive/10 text-destructive",children:y.jsx(ux,{className:"w-6 h-6"})}),y.jsx("h2",{className:"text-lg font-semibold",children:"Access Denied"}),y.jsx("p",{className:"text-sm text-muted-foreground",children:"Your account is not authorized to use this app."}),y.jsxs("p",{className:"text-xs text-muted-foreground",children:["Signed in as ",r.email]}),y.jsx(we,{variant:"outline",onClick:()=>m(),children:"Sign out"})]})}):window.location.pathname==="/oauth/authorize"?y.jsx($V,{getToken:a,userEmail:r.email??""}):window.location.pathname==="/cli-auth"?y.jsx(BV,{getToken:a,userEmail:r.email??""}):y.jsxs("div",{className:"flex h-full flex-col",children:[y.jsx(WD,{}),y.jsxs("div",{className:"flex flex-1 min-h-0",children:[w&&y.jsxs("div",{className:"fixed inset-0 z-50 bg-background sm:relative sm:inset-auto sm:z-auto sm:w-64 sm:shrink-0 sm:border-r flex flex-col",children:[y.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b sm:hidden",style:{paddingTop:"max(0.5rem, env(safe-area-inset-top))"},children:[y.jsx("span",{className:"text-sm font-medium",children:"Sessions"}),y.jsx(we,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>E(!1),children:y.jsx(bT,{className:"w-4 h-4"})})]}),y.jsx("div",{className:"flex-1 min-h-0",children:y.jsx(Voe,{getToken:a,activeSessionId:ze,onSelect:(me,Xe)=>{Ee(me,Xe),pe(me),window.innerWidth<640&&E(!1)},onNew:Nr,refreshKey:R,workspaceRefreshKey:$,onRefreshWorkspace:Ae,unreads:Ko,busySessions:W,socket:ir})})]}),y.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[y.jsx("header",{className:"border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60",style:{paddingTop:"env(safe-area-inset-top)"},children:y.jsxs("div",{className:"flex items-center gap-1.5 sm:gap-2 px-2 sm:px-3 py-1.5",children:[y.jsx(we,{variant:"ghost",size:"icon",className:"h-9 w-9 sm:h-8 sm:w-8 shrink-0",onClick:()=>E(!w),title:"Toggle sidebar",children:w?y.jsx(bT,{className:"w-4 h-4"}):y.jsx(sV,{className:"w-4 h-4"})}),y.jsx(we,{variant:"ghost",size:"icon",className:"h-9 w-9 sm:h-8 sm:w-8 shrink-0",onClick:Nr,title:"New chat (⌘N)",children:y.jsx(gV,{className:"w-4 h-4"})}),y.jsx("div",{className:"flex-1"}),y.jsxs("div",{className:"hidden sm:flex items-center gap-0.5 shrink-0",children:[y.jsx(we,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:n,title:t?"Light mode":"Dark mode",children:t?y.jsx(wT,{className:"w-4 h-4"}):y.jsx(yT,{className:"w-4 h-4"})}),(In=e.headerActions)==null?void 0:In.call(e),p&&y.jsx(qD,{call:g,onOpenSession:Fn,trigger:y.jsx(we,{variant:"ghost",size:"icon",className:"h-8 w-8",title:"Owner Console",children:y.jsx(Lu,{className:"w-4 h-4"})})}),y.jsx(DD,{getToken:a}),y.jsx(zD,{getToken:a,onSkillsChange:K}),y.jsx(BD,{getToken:a}),y.jsx(KD,{ref:j,getToken:a,refreshKey:P,runningIds:q,onOpenSession:me=>Ee(me),skills:U,workspaceFiles:dn}),y.jsx(we,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>m(),title:"Sign out",children:y.jsx(ux,{className:"w-4 h-4"})})]}),y.jsxs("div",{className:"relative sm:hidden shrink-0",children:[y.jsx(we,{ref:C,variant:"ghost",size:"icon",className:"h-9 w-9",onClick:T,children:y.jsx(WG,{className:"w-4 h-4"})}),_&&La.createPortal(y.jsxs(y.Fragment,{children:[y.jsx("div",{className:"fixed inset-0 z-[1090] cursor-pointer",onClick:()=>k(!1)}),y.jsxs("div",{className:"fixed z-[1100] border rounded-lg shadow-lg p-1 min-w-[170px] bg-white dark:bg-zinc-900 whitespace-nowrap",style:{top:O.top,right:O.right},children:[(vt=e.headerActions)==null?void 0:vt.call(e),p&&y.jsx(qD,{call:g,onOpenSession:Fn,trigger:y.jsxs("button",{className:"flex w-full items-center gap-2.5 rounded-md px-3 py-2.5 text-sm hover:bg-accent",children:[y.jsx(Lu,{className:"w-3.5 h-3.5"})," Owner Console"]})}),y.jsx(DD,{getToken:a,trigger:y.jsxs("button",{className:"flex w-full items-center gap-2.5 rounded-md px-3 py-2.5 text-sm hover:bg-accent",children:[y.jsx(dL,{className:"w-3.5 h-3.5"})," MCPs"]})}),y.jsx(zD,{getToken:a,onSkillsChange:K,trigger:y.jsxs("button",{className:"flex w-full items-center gap-2.5 rounded-md px-3 py-2.5 text-sm hover:bg-accent",children:[y.jsx(qw,{className:"w-3.5 h-3.5"})," Skills"]})}),y.jsx(BD,{getToken:a,trigger:y.jsxs("button",{className:"flex w-full items-center gap-2.5 rounded-md px-3 py-2.5 text-sm hover:bg-accent",children:[y.jsx(Kw,{className:"w-3.5 h-3.5"})," Modules"]})}),y.jsx(KD,{getToken:a,refreshKey:P,runningIds:q,onOpenSession:me=>Ee(me),skills:U,workspaceFiles:dn,trigger:y.jsxs("button",{className:"flex w-full items-center gap-2.5 rounded-md px-3 py-2.5 text-sm hover:bg-accent",children:[y.jsx(BE,{className:"w-3.5 h-3.5"})," Schedules"]})}),y.jsx("div",{className:"border-t my-1"}),y.jsxs("button",{className:"flex w-full items-center gap-2.5 rounded-md px-3 py-2.5 text-sm hover:bg-accent",onClick:()=>{k(!1),n()},children:[t?y.jsx(wT,{className:"w-3.5 h-3.5"}):y.jsx(yT,{className:"w-3.5 h-3.5"}),t?"Light mode":"Dark mode"]}),y.jsxs("button",{className:"flex w-full items-center gap-2.5 rounded-md px-3 py-2.5 text-sm hover:bg-accent",onClick:()=>m(),children:[y.jsx(ux,{className:"w-3.5 h-3.5"})," Sign out"]})]})]}),document.body)]})]})}),ia==="update_available"&&y.jsxs("div",{className:"flex items-center justify-center gap-3 py-2.5 px-4 bg-amber-500 dark:bg-amber-600 text-white text-sm font-medium animate-pulse",children:[y.jsx("span",{children:"A new version is available"}),y.jsx("button",{onClick:()=>window.location.reload(),className:"px-3 py-1 bg-white text-amber-700 rounded font-semibold text-xs hover:bg-amber-50 transition-colors",children:"Reload now"})]}),y.jsx(zG,{value:Jt,children:y.jsx("div",{className:"flex-1 min-h-0",children:y.jsx(lNe,{nodeId:"main",sessionId:ze},ze??"new")})})]}),y.jsx(QNe,{toasts:oe,onDismiss:$e,onOpen:me=>{Ee(me),pe(me)}})]})]})}const XD="unclaw:",rCe="shraga:";function iCe(){try{const e=Object.keys(localStorage).filter(t=>t.startsWith(XD));for(const t of e){const n=rCe+t.slice(XD.length);if(localStorage.getItem(n)===null){const r=localStorage.getItem(t);r!==null&&localStorage.setItem(n,r)}localStorage.removeItem(t)}}catch(e){console.warn("[storage] legacy key migration skipped:",e instanceof Error?e.message:String(e))}}iCe();V9.createRoot(document.getElementById("root")).render(y.jsx(b.StrictMode,{children:y.jsx(tCe,{})}));
2009
+ Click to copy`,children:[e.slice(0,8),u?y.jsx(Wi,{className:"w-2.5 h-2.5"}):y.jsx(Bv,{className:"w-2.5 h-2.5"})]}),s&&y.jsxs("button",{onClick:l,className:"inline-flex items-center gap-0.5 rounded-md bg-purple-50 px-1.5 py-0.5 text-[10px] font-mono text-purple-700 ring-1 ring-inset ring-purple-600/20 dark:bg-purple-950/50 dark:text-purple-300 dark:ring-purple-400/30 hover:bg-purple-100 dark:hover:bg-purple-950/70 transition-colors",title:"Open schedule details",children:[y.jsx(BE,{className:"w-2.5 h-2.5"}),s.slice(0,8)]})]})}function sNe({sessionId:e,agentConfig:t,sessionDirectives:n,sessionLastModel:r,sessionLastEngine:i,sessionLastAccount:a,sessionScheduleId:s,artifactCount:l,getToken:u,onConfigSaved:d,onDirectivesSaved:h,onFork:m,onToggleArtifacts:p,onScheduleClick:g}){return y.jsxs("div",{className:"flex items-center gap-1.5 px-2 sm:px-3 py-1.5 border-b bg-background/60 overflow-x-auto",children:[y.jsx(oNe,{sessionId:e,config:t,sessionDirectives:n,actualModel:r,actualEngine:i,actualAccount:a,scheduleId:s,onScheduleClick:g}),y.jsx("div",{className:"flex-1"}),e&&y.jsx(we,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",onClick:m,title:"Fork conversation",children:y.jsx(cL,{className:"w-3.5 h-3.5"})}),y.jsx(rNe,{getToken:u,onSaved:d,sessionId:e,sessionDirectives:n,onDirectivesSaved:h}),l>0&&y.jsx(we,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",onClick:p,title:"Toggle artifacts panel",children:y.jsx(iV,{className:"w-3.5 h-3.5"})})]})}function lNe({nodeId:e,sessionId:t}){var $;const n=$E(),r=za(),i=b.useRef(null),[a,s]=b.useState(),[l,u]=b.useState([]),d=b.useRef(void 0),[h,m]=b.useState(t),p=b.useRef(h);p.current=h;const g=b.useRef(t).current,[w,x]=b.useState(),[E,_]=b.useState(),[k,O]=b.useState(),[N,C]=b.useState(),[T,M]=b.useState(),[D,j]=b.useState(!1),R=Zoe(h,n.getToken,n.token),H=b.useRef(!1),P=b.useCallback(L=>{n.bumpSidebar(),L!==p.current&&(m(L),n.assignSession(e,L))},[n,e]),G=b.useCallback(L=>{L.type==="artifact"?L.sessionId===p.current&&R.handleArtifactEvent(L):L.type==="directives"?H.current&&(O(void 0),C(void 0),M(void 0)):L.type==="model_resolved"&&L.sessionId===p.current&&(O(L.model),C(L.engine),M(L.account))},[n,e,R]),q=Woe(n.socket,{getToken:n.getToken,initialSessionId:t,onNewSession:P,onDirectivesChanged:x,onParticipantsChanged:j,onEvent:G});H.current=q.busy,b.useEffect(()=>{if(!g)return;let L=!1;return(async()=>{try{const z=await(await jl(`/api/sessions/${g}/messages`,n.getToken)).json();if(L)return;q.setMessages(nL(z)),j(Array.isArray(z.participants)&&z.participants.length>1),z.busy&&q.setBusy(!0)}catch(W){L||console.error("[pane] history load failed:",W)}})(),()=>{L=!0}},[g]),b.useEffect(()=>{if(!h){x(void 0),_(void 0),O(void 0),C(void 0),M(void 0);return}jl(`/api/sessions/${h}/meta`,n.getToken).then(L=>L.json()).then(L=>{x(L.directives),_(L.scheduleId),O(L.lastModel),C(L.lastEngine),M(L.lastAccount),L.runStatus==="running"&&q.setBusy(!0)}).catch(()=>{})},[h,n.getToken]);const X=b.useCallback((L,W,z)=>{var ie;q.sendMessage(L,p.current,z,W,(ie=d.current)==null?void 0:ie.call(d))},[q]),U={sessionId:h,busy:q.busy,socket:n.socket,getToken:n.getToken,setInputCtx:s,setSendOptions:L=>{d.current=L},setInputText:L=>{var W;return(W=i.current)==null?void 0:W.setText(L)},send:(L,W,z)=>q.sendMessage(L,p.current,void 0,void 0,W,(z==null?void 0:z.echo)!==!1),appendAssistant:L=>q.setMessages(W=>W.concat({id:Ms(),role:"assistant",blocks:L})),setStatusItems:u},K=b.useCallback(async L=>{const W=await n.getToken();if(!W)return null;try{return await(await fetch("/api/upload",{method:"POST",headers:{Authorization:`Bearer ${W}`,"x-filename":encodeURIComponent(L.name),"Content-Type":L.type||"application/octet-stream","x-session-id":p.current||""},body:L})).json()}catch(z){return console.error("[upload] Failed:",z),null}},[n]),F=b.useCallback(async L=>{const W=p.current;if(!W)return;const z=await n.getToken();if(z)try{const ie=await fetch(`/api/sessions/${W}/fork`,{method:"POST",headers:{Authorization:`Bearer ${z}`,"Content-Type":"application/json"},body:JSON.stringify(L!=null?{truncateAtIndex:L}:{})});if(!ie.ok){console.error("[fork] server error:",(await ie.json().catch(()=>({}))).error||ie.status);return}const{sessionId:he}=await ie.json();n.bumpSidebar(),n.openSession(he)}catch(ie){console.error("[fork] failed:",ie)}},[n]),V=b.useCallback((L,W,z)=>{if(q.busy)return;const ie=q.messages.findIndex(he=>he.id===L);ie>=0&&q.setMessages(q.messages.slice(0,ie)),X(W,ie>=0?ie:void 0,z)},[q,X]);return y.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[($=r.conversationController)==null?void 0:$.call(r,U),y.jsx(sNe,{sessionId:h,agentConfig:n.agentConfig,sessionDirectives:w,sessionLastModel:k,sessionLastEngine:N,sessionLastAccount:T,sessionScheduleId:E,artifactCount:R.artifacts.length,getToken:n.getToken,onConfigSaved:n.setAgentConfig,onDirectivesSaved:x,onFork:()=>F(),onToggleArtifacts:R.togglePanel,onScheduleClick:n.openSchedules}),y.jsxs("div",{className:"flex-1 flex min-h-0",children:[y.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[y.jsx(OOe,{messages:q.messages,busy:q.busy,multiParticipant:D,connectionStatus:n.connectionStatus??void 0,onPermissionRespond:q.respondPermission,onQuestionRespond:q.respondQuestion,onReplay:V,onEdit:V,onFork:L=>F(L),statusItems:l}),y.jsx(HOe,{ref:i,onSend:(L,W)=>X(L,void 0,W),onSteer:q.steer,onQueue:q.addToQueue,onRemoveQueued:q.removeFromQueue,queue:q.queue,onUpload:K,onCancel:q.cancel,disabled:!1,busy:q.busy,skills:n.skills,workspaceFiles:n.workspaceFiles,sessionId:h,inputCtx:a})]}),R.panelOpen&&R.artifacts.length>0&&h&&y.jsx(qOe,{artifacts:R.artifacts,selectedId:R.selectedId,sessionId:h,getToken:n.getToken,onSelect:R.selectArtifact,onClose:R.closePanel})]})]})}function ZA(e,t=!0){const[n,r]=b.useState();return b.useEffect(()=>{if(!t){r(void 0);return}let i=!0;return e().then(a=>{!a||!i||fetch("/api/config",{headers:{Authorization:`Bearer ${a}`}}).then(s=>{if(!s.ok)throw new Error(`HTTP ${s.status}`);return s.json()}).then(s=>{i&&r(!!s.isOwner)}).catch(s=>console.warn("[isOwner] load failed",s))}),()=>{i=!1}},[t,e]),n}const cNe=()=>({command:"",args:[],env:{}});function DD({getToken:e,trigger:t}){const[n,r]=b.useState({}),[i,a]=b.useState(!1),[s,l]=b.useState(!1),[u,d]=b.useState(null),h=ZA(e,i),m=h===!0,[p,g]=b.useState(new Set),w=M=>g(D=>{const j=new Set(D);return j.has(M)?j.delete(M):j.add(M),j});b.useEffect(()=>{i&&e().then(M=>{M&&fetch("/api/mcps",{headers:{Authorization:`Bearer ${M}`}}).then(D=>{if(!D.ok)throw new Error(`HTTP ${D.status}`);return D.json()}).then(r).catch(D=>console.error("[McpManager] fetch failed",D))})},[i,e]);const x=async()=>{l(!0),d(null);const M=await e();try{const D=await fetch("/api/mcps",{method:"PUT",headers:{Authorization:`Bearer ${M??""}`,"Content-Type":"application/json"},body:JSON.stringify(n)});if(!D.ok)throw new Error((await D.json().catch(j=>(console.warn("[McpManager] error response not JSON",D.status,j),{}))).error||`HTTP ${D.status}`);a(!1)}catch(D){console.error("[McpManager] save failed",D),d(D.message||"Save failed")}finally{l(!1)}},E=()=>{const M=`server-${Date.now()}`;r(D=>({...D,[M]:cNe()}))},_=M=>{r(D=>{const j={...D};return delete j[M],j})},k=(M,D,j)=>{r(R=>({...R,[M]:{...R[M],[D]:D==="args"?j.split(" "):j}}))},O=(M,D,j)=>{r(R=>{const H={...R[M].env},P=H[D]??"";return delete H[D],j.trim()&&(H[j.trim()]=P),{...R,[M]:{...R[M],env:H}}})},N=(M,D,j)=>{r(R=>({...R,[M]:{...R[M],env:{...R[M].env,[D]:j}}}))},C=(M,D)=>{r(j=>{const R={...j[M].env};return delete R[D],{...j,[M]:{...j[M],env:R}}})},T=M=>{const D=`KEY_${Date.now()}`;r(j=>({...j,[M]:{...j[M],env:{...j[M].env,[D]:""}}}))};return y.jsxs(Oo,{open:i,onOpenChange:a,children:[y.jsx(rd,{asChild:!0,children:t||y.jsx(we,{variant:"ghost",size:"icon",title:"MCP Servers",children:y.jsx(dL,{className:"w-4 h-4"})})}),y.jsxs(Na,{className:"max-w-[95vw] sm:max-w-2xl",children:[y.jsx(Bs,{children:y.jsx(No,{children:"MCP Servers"})}),y.jsxs(Cz,{className:"space-y-4",children:[h===!1&&y.jsx("p",{className:"text-xs text-muted-foreground rounded-md bg-muted/50 px-3 py-2",children:"Read-only — only an owner can change MCP servers."}),y.jsxs("fieldset",{disabled:!m,className:"space-y-4 min-w-0",children:[Object.entries(n).map(([M,D])=>{const j=!!D.readonly;return y.jsxs("div",{className:`border rounded-lg p-4 space-y-3 ${j?"opacity-70":""}`,children:[y.jsxs("div",{className:"flex items-center justify-between",children:[y.jsxs("span",{className:"font-medium text-sm flex items-center gap-1.5",children:[j&&y.jsx(tg,{className:"w-3 h-3 text-muted-foreground"}),M]}),!j&&y.jsx(we,{variant:"ghost",size:"icon",onClick:()=>_(M),children:y.jsx(Xi,{className:"w-4 h-4 text-destructive"})})]}),j?y.jsx("p",{className:"text-xs text-muted-foreground",children:"Configured in shraga.config.ts"}):y.jsxs("div",{className:"grid gap-2",children:[y.jsx(ft,{placeholder:"Command (e.g. npx)",value:D.command,onChange:R=>k(M,"command",R.target.value)}),y.jsx(ft,{placeholder:"Args (space-separated)",value:(D.args||[]).join(" "),onChange:R=>k(M,"args",R.target.value)}),Object.entries(D.env||{}).length>0&&y.jsxs("div",{className:"space-y-2",children:[y.jsx("span",{className:"text-xs text-muted-foreground",children:"Environment variables"}),Object.entries(D.env||{}).map(([R,H])=>y.jsxs("div",{className:"flex gap-2 items-center",children:[y.jsx(ft,{className:"w-1/3 font-mono text-xs",value:R,onChange:P=>O(M,R,P.target.value),placeholder:"KEY"}),p.has(`${M}:${R}`)?y.jsx(ft,{className:"flex-1 font-mono text-xs",placeholder:"paste new value",autoFocus:!0,onChange:P=>N(M,R,P.target.value),onBlur:()=>w(`${M}:${R}`)}):y.jsx("span",{className:"flex-1 font-mono text-xs text-muted-foreground truncate cursor-pointer px-3 py-2 border rounded-md bg-background hover:border-ring",onClick:()=>w(`${M}:${R}`),title:"Click to change",children:H||"(empty — click to set)"}),y.jsx(we,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",onClick:()=>C(M,R),children:y.jsx(Xi,{className:"w-3 h-3 text-muted-foreground"})})]},R))]}),y.jsx(we,{variant:"ghost",size:"sm",className:"text-xs text-muted-foreground",onClick:()=>T(M),children:"+ Add env var"})]})]},M)}),Object.keys(n).length===0&&y.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No MCP servers configured"})]}),u&&y.jsx("p",{className:"text-sm text-destructive",children:u})]}),m&&y.jsxs(Tz,{className:"flex gap-2",children:[y.jsxs(we,{variant:"outline",onClick:E,className:"gap-2",children:[y.jsx(ko,{className:"w-4 h-4"})," Add Server"]}),y.jsx(we,{onClick:x,disabled:s,children:s?"Saving…":"Save"})]})]})]})}function QA(e){return typeof e=="string"?e:e.name}function jD(e){return typeof e=="string"?!1:e.capped===!0||typeof e.capped=="number"&&e.capped>0}function Cl(e,t){return e.some(n=>QA(n)===t)}function LD(e,t){return e.find(n=>QA(n)===t)}async function co(e,t,n){return fetch(e,{...n,headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json",...(n==null?void 0:n.headers)??{}}})}function zD({getToken:e,onSkillsChange:t,trigger:n}){const[r,i]=b.useState(!1),[a,s]=b.useState([]),[l,u]=b.useState([]),[d,h]=b.useState([]),[m,p]=b.useState(null),[g,w]=b.useState(""),[x,E]=b.useState(!1),[_,k]=b.useState(null),[O,N]=b.useState(""),[C,T]=b.useState(null),M=ZA(e,r),D=M===!0,R=(m?l.includes(m):!1)||!D,H=async(L,W)=>{if(L.ok)return T(null),!0;const z=(await L.json().catch(ie=>(console.warn(`[SkillsManager] ${W} error response not JSON`,L.status,ie),{}))).error||`HTTP ${L.status}`;return console.warn(`[SkillsManager] ${W} failed`,z),T(`${W} failed: ${z}`),!1},P=async()=>{const L=await e();if(!L)return;const[W,z]=await Promise.all([co("/api/skills",L),co("/api/skills-defaults",L)]),ie=await W.json(),he=await z.json();s(ie.skills),u(ie.builtins),h(he),t==null||t(ie.skills)},G=async L=>{const W=await e();if(!W)return;const ie=await(await co(`/api/skills/${L}`,W)).json();w(ie.content),p(L),E(!1)},q=async()=>{if(!m||R)return;const L=await e();if(!L)return;const W=await co(`/api/skills/${m}`,L,{method:"PUT",body:JSON.stringify({content:g})});await H(W,"Save")&&E(!1)},X=async()=>{const L=O.trim().replace(/\s+/g,"-");if(!L)return;const W=await e();if(W){if(_==="create"){const z=await co(`/api/skills/${L}`,W,{method:"PUT",body:JSON.stringify({content:""})});if(!await H(z,"Create"))return;await P(),await G(L)}else if(_==="duplicate"&&m){const z=await co(`/api/skills/${m}/duplicate`,W,{method:"POST",body:JSON.stringify({newName:L})});if(!await H(z,"Duplicate"))return;await P(),await G(L)}else if(_==="rename"&&m){const z=await co(`/api/skills/${m}/rename`,W,{method:"POST",body:JSON.stringify({newName:L})});if(!await H(z,"Rename"))return;await P(),await G(L)}k(null),N("")}},U=async L=>{const W=await e();if(!W)return;const z=await co(`/api/skills/${L}`,W,{method:"DELETE"});await H(z,"Delete")&&(m===L&&(p(null),w("")),await P())},K=async L=>{const W=await e();if(!W)return;const z=Cl(d,L)?d.filter(he=>QA(he)!==L):[...d,L],ie=await co("/api/skills-defaults",W,{method:"PUT",body:JSON.stringify(z)});await H(ie,"Update defaults")&&h(z)},F=L=>{k(L),N(L==="rename"&&m?m:L==="duplicate"&&m?`${m}-copy`:"")},V=()=>{k(null),N("")};b.useEffect(()=>{r&&P()},[r]);const $=_==="create"?"skill-name":_==="rename"?"new-name":"copy-name";return y.jsxs(Oo,{open:r,onOpenChange:i,children:[y.jsx(rd,{asChild:!0,children:n||y.jsx(we,{variant:"ghost",size:"icon",title:"Skills",className:"h-8 w-8",children:y.jsx(qw,{className:"w-4 h-4"})})}),y.jsxs(Na,{className:"max-w-[95vw] sm:max-w-2xl h-[70dvh] sm:h-[520px] flex flex-col gap-0 p-0",children:[y.jsx(Bs,{className:"px-4 pt-4 pb-2 border-b shrink-0",children:y.jsxs(No,{className:"flex items-center gap-2",children:[y.jsx(qw,{className:"w-4 h-4"})," Skills"]})}),y.jsxs("div",{className:"flex flex-col sm:flex-row flex-1 overflow-hidden",children:[y.jsxs("div",{className:`sm:w-52 border-r flex flex-col shrink-0 ${m?"hidden sm:flex":"flex"}`,children:[y.jsx("div",{className:"flex-1 overflow-y-auto py-1",children:a.map(L=>y.jsxs("div",{className:`group flex items-center gap-1.5 px-3 py-1.5 cursor-pointer text-sm hover:bg-accent transition-colors ${m===L?"bg-accent font-medium":""}`,onClick:()=>G(L),children:[y.jsx("button",{className:`shrink-0 transition-colors ${Cl(d,L)?"text-amber-500":"text-muted-foreground/30"} ${D&&!Cl(d,L)?"hover:text-amber-400":""}`,disabled:!D,onClick:W=>{W.stopPropagation(),D&&K(L)},title:D?Cl(d,L)?"Remove from defaults":"Set as default (always active)":Cl(d,L)?"Default (only an owner can change)":"Only an owner can change defaults",children:y.jsx(xT,{className:`w-3 h-3 ${Cl(d,L)?"fill-current":""}`})}),y.jsxs("span",{className:"truncate flex-1",children:["@",L]}),l.includes(L)&&y.jsx("span",{title:"Built-in (read-only)",children:y.jsx(tg,{className:"w-2.5 h-2.5 text-muted-foreground/40 shrink-0"})}),!l.includes(L)&&D&&y.jsx("button",{className:"opacity-0 group-hover:opacity-100 text-muted-foreground hover:text-destructive transition-opacity shrink-0",onClick:W=>{W.stopPropagation(),U(L)},title:"Delete",children:y.jsx(Xi,{className:"w-3 h-3"})})]},L))}),y.jsxs("div",{className:"border-t p-2",children:[_?y.jsxs("div",{className:"flex gap-1",children:[y.jsx(ft,{value:O,onChange:L=>N(L.target.value),onKeyDown:L=>{L.key==="Enter"&&X(),L.key==="Escape"&&V()},placeholder:$,className:"h-7 text-xs",autoFocus:!0}),y.jsx(we,{size:"icon",className:"h-7 w-7 shrink-0",onClick:X,children:y.jsx(Wi,{className:"w-3 h-3"})}),y.jsx(we,{size:"icon",variant:"ghost",className:"h-7 w-7 shrink-0",onClick:V,children:y.jsx(Ql,{className:"w-3 h-3"})})]}):D?y.jsxs(we,{variant:"outline",size:"sm",className:"w-full h-7 text-xs",onClick:()=>F("create"),children:[y.jsx(ko,{className:"w-3 h-3 mr-1"})," New skill"]}):y.jsx("p",{className:"text-[11px] text-muted-foreground text-center",children:M===!1?"Read-only — only an owner can change skills":""}),C&&y.jsx("p",{className:"text-[11px] text-destructive mt-1 break-words",children:C})]})]}),y.jsx("div",{className:`flex-1 flex flex-col overflow-hidden ${m?"":"hidden sm:flex"}`,children:m?y.jsxs(y.Fragment,{children:[y.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b text-sm shrink-0",children:[y.jsxs("div",{className:"flex items-center gap-0.5 font-medium",children:[y.jsx("button",{className:"sm:hidden mr-1.5 text-muted-foreground",onClick:()=>{p(null),w(""),E(!1)},children:y.jsx(oL,{className:"w-4 h-4"})}),y.jsx("span",{className:"text-muted-foreground",children:"@"}),y.jsx("span",{children:m})]}),y.jsxs("div",{className:"flex items-center gap-1.5",children:[R&&y.jsxs("span",{className:"text-[10px] text-muted-foreground bg-muted px-1.5 py-0.5 rounded font-medium flex items-center gap-0.5",children:[y.jsx(tg,{className:"w-2.5 h-2.5"})," read-only"]}),Cl(d,m)&&y.jsxs(y.Fragment,{children:[y.jsx("span",{className:"text-[10px] text-amber-600 bg-amber-50 dark:bg-amber-950/50 dark:text-amber-400 px-1.5 py-0.5 rounded font-medium",children:"default"}),y.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded font-medium ${jD(LD(d,m))?"text-blue-600 bg-blue-50 dark:bg-blue-950/50 dark:text-blue-400":"text-emerald-600 bg-emerald-50 dark:bg-emerald-950/50 dark:text-emerald-400"}`,children:jD(LD(d,m))?"capped":"full"})]}),D&&y.jsx(we,{variant:"ghost",size:"sm",className:"h-6 text-xs px-1.5",onClick:()=>F("duplicate"),title:"Duplicate",children:y.jsx(Bv,{className:"w-3 h-3"})}),!R&&y.jsx(we,{variant:"ghost",size:"sm",className:"h-6 text-xs px-1.5",onClick:()=>F("rename"),title:"Rename",children:y.jsx(KE,{className:"w-3 h-3"})}),x&&!R&&y.jsxs(we,{size:"sm",className:"h-6 text-xs",onClick:q,children:[y.jsx(Wi,{className:"w-3 h-3 mr-1"})," Save"]})]})]}),y.jsx(Vy,{value:g,onChange:L=>{R||(w(L.target.value),E(!0))},readOnly:R,className:`flex-1 resize-none rounded-none border-0 font-mono text-xs focus-visible:ring-0 ${R?"opacity-70 cursor-default":""}`,placeholder:"Write the skill instructions here…"})]}):y.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center text-muted-foreground text-sm gap-1",children:[y.jsx("p",{children:"Select or create a skill"}),y.jsxs("p",{className:"text-xs",children:[y.jsx(xT,{className:"w-3 h-3 inline fill-amber-500 text-amber-500"})," = injected in every conversation"]}),y.jsxs("p",{className:"text-xs",children:[y.jsx(tg,{className:"w-3 h-3 inline"})," = built-in, duplicate to customize"]})]})})]})]})]})}function uNe(e,t,n=0){const[r,i]=b.useState([]),[a,s]=b.useState([]),[l,u]=b.useState(!1),[d,h]=b.useState(!1),[m,p]=b.useState(null),g=b.useCallback(async()=>{h(!0),p(null);try{const k=await Ki("/api/modules",e,{expect:[404]});i(k.installed??[]),s(k.available??[]),u(!1)}catch(k){/^404\b/.test(k.message)?u(!0):p(k.message)}finally{h(!1)}},[e]);b.useEffect(()=>{t&&g()},[t,g,n]);const w=b.useCallback(async k=>{await Ki("/api/modules/install",e,{method:"POST",body:JSON.stringify(k)}),await g()},[e,g]),x=b.useCallback(async(k,O)=>{await Ki(`/api/modules/${k}/${O?"enable":"disable"}`,e,{method:"POST"}),await g()},[e,g]),E=b.useCallback(async(k,O)=>{await Ki(`/api/modules/${k}/config`,e,{method:"PUT",body:JSON.stringify({config:O})}),await g()},[e,g]),_=b.useCallback(async k=>{await Ki(`/api/modules/${k}`,e,{method:"DELETE"}),await g()},[e,g]);return{installed:r,available:a,unsupported:l,loading:d,error:m,refresh:g,install:w,toggle:x,updateConfig:E,uninstall:_}}function E8({checked:e,onChange:t,title:n,disabled:r}){return y.jsx("button",{type:"button",role:"switch","aria-checked":e,title:n,disabled:r,onClick:()=>t(!e),className:`relative inline-flex h-6 w-11 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors disabled:opacity-50 disabled:cursor-not-allowed ${e?"bg-primary":"bg-muted"}`,children:y.jsx("span",{className:`pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform ${e?"translate-x-5":"translate-x-0"}`})})}function $D(e){const t=Object.keys(e.config??{});return t.length===0?"":t.slice(0,3).map(n=>`${n}: ${String(e.config[n])}`).join(" · ")+(t.length>3?` · +${t.length-3}`:"")}function dNe({schema:e,config:t,onSave:n,saving:r}){const[i,a]=b.useState(()=>{const h={};for(const[m,p]of Object.entries(e)){const g=t[m]??p.default;h[m]=p.type==="boolean"?!!g:g==null?"":String(g)}return h}),[s,l]=b.useState({}),u=(h,m)=>{a(p=>({...p,[h]:m})),l(p=>p[h]?{...p,[h]:""}:p)},d=()=>{const h={},m={};for(const[p,g]of Object.entries(e)){const w=i[p];if(g.type==="boolean"){const E=!!w;if(!E&&t[p]===void 0&&typeof g.default!="boolean")continue;h[p]=E;continue}const x=String(w??"").trim();if(x===""){(g.type==="number"&&typeof g.default=="number"&&Number.isFinite(g.default)||g.type==="string"&&typeof g.default=="string"&&g.default!=="")&&(h[p]=g.default);continue}if(g.type==="number"){const E=Number(x);if(!Number.isFinite(E)){m[p]="Not a number";continue}h[p]=E}else h[p]=x}if(Object.values(m).some(Boolean)){l(m);return}l({}),n(h)};return y.jsxs("div",{className:"space-y-2 pt-2",children:[Object.entries(e).map(([h,m])=>y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx("label",{className:"text-xs w-36 shrink-0 truncate",title:m.description||h,children:h}),m.type==="boolean"?y.jsx(E8,{checked:!!i[h],onChange:p=>u(h,p)}):y.jsxs("div",{className:"flex-1 min-w-0",children:[y.jsx(ft,{type:"text",inputMode:m.type==="number"?"decimal":void 0,value:String(i[h]??""),onChange:p=>u(h,p.target.value),className:`h-7 text-xs w-full ${s[h]?"border-destructive":""}`,placeholder:m.description}),s[h]&&y.jsx("p",{className:"text-[10px] text-destructive mt-0.5",children:s[h]})]})]},h)),y.jsxs(we,{size:"sm",className:"h-6 text-xs",disabled:r,onClick:d,children:[r?y.jsx(Yi,{className:"w-3 h-3 mr-1 animate-spin"}):y.jsx(Wi,{className:"w-3 h-3 mr-1"})," Save config"]})]})}function BD({getToken:e,trigger:t}){const[n,r]=b.useState(!1),{installed:i,available:a,unsupported:s,loading:l,error:u,install:d,toggle:h,updateConfig:m,uninstall:p}=uNe(e,n),[g,w]=b.useState(null),[x,E]=b.useState(null),[_,k]=b.useState(null),O=async(C,T)=>{if(!x){E(C),k(null);try{await T()}catch(M){k(M.message)}finally{E(null)}}},N=a.filter(C=>!C.installed);return y.jsxs(Oo,{open:n,onOpenChange:r,children:[y.jsx(rd,{asChild:!0,children:t||y.jsx(we,{variant:"ghost",size:"icon",title:"Modules",className:"h-8 w-8",children:y.jsx(Kw,{className:"w-4 h-4"})})}),y.jsxs(Na,{className:"max-w-[95vw] sm:max-w-2xl h-[70dvh] sm:h-[520px] flex flex-col gap-0 p-0",children:[y.jsx(Bs,{className:"px-4 pt-4 pb-2 border-b shrink-0",children:y.jsxs(No,{className:"flex items-center gap-2",children:[y.jsx(Kw,{className:"w-4 h-4"})," Modules"]})}),y.jsxs("div",{className:"flex-1 overflow-y-auto p-3 space-y-4",children:[s&&y.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"This server does not support modules yet."}),(u||_)&&y.jsx("p",{className:"text-xs text-destructive",children:_||u}),l&&i.length===0&&!s&&y.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"Loading…"}),!s&&!l&&i.length===0&&N.length===0&&!u&&y.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No modules available."}),i.length>0&&y.jsxs("div",{className:"space-y-2",children:[y.jsx("h3",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Installed"}),i.map(C=>{const T=g===C.name,M=C.configSchema&&Object.keys(C.configSchema).length>0,D=[C.skillCount?`provides ${C.skillCount} skill${C.skillCount===1?"":"s"}`:"",C.scheduleCount?`${C.scheduleCount} schedule${C.scheduleCount===1?"":"s"}`:""].filter(Boolean).join(", ");return y.jsxs("div",{className:"border rounded-lg p-3 space-y-1",children:[y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx(E8,{checked:C.enabled,onChange:j=>O(`toggle-${C.name}`,()=>h(C.name,j)),title:C.enabled?"Disable":"Enable",disabled:x===`toggle-${C.name}`}),y.jsx("span",{className:"font-medium text-sm truncate",children:C.name}),y.jsxs("span",{className:"text-[10px] font-mono px-1.5 py-0.5 rounded bg-muted text-muted-foreground shrink-0",children:["v",C.version]}),!C.enabled&&y.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-muted text-muted-foreground shrink-0",children:"disabled"}),y.jsx("div",{className:"flex-1"}),x===`toggle-${C.name}`&&y.jsx(Yi,{className:"w-3 h-3 animate-spin text-muted-foreground"}),(M||C.readme)&&y.jsx("button",{className:"text-muted-foreground hover:text-foreground transition-colors",onClick:()=>w(T?null:C.name),title:"Details",children:T?y.jsx(VG,{className:"w-3.5 h-3.5"}):y.jsx(Ys,{className:"w-3.5 h-3.5"})}),y.jsx("button",{className:"text-muted-foreground hover:text-destructive transition-colors",onClick:()=>{confirm(`Uninstall module "${C.name}"? Its skills and schedules will be removed (seeds/data stay).`)&&O(`rm-${C.name}`,()=>p(C.name))},title:"Uninstall",children:y.jsx(Xi,{className:"w-3.5 h-3.5"})})]}),C.description&&y.jsx("p",{className:"text-xs text-muted-foreground",children:C.description}),D&&y.jsx("p",{className:"text-[10px] text-muted-foreground",children:D}),!T&&$D(C)&&y.jsx("p",{className:"text-[10px] font-mono text-muted-foreground truncate",children:$D(C)}),T&&C.readme&&y.jsx("pre",{className:"text-[11px] text-muted-foreground whitespace-pre-wrap font-sans bg-muted/40 rounded p-2 max-h-48 overflow-y-auto",children:C.readme}),T&&M&&y.jsx(dNe,{schema:C.configSchema,config:C.config,saving:x===`cfg-${C.name}`,onSave:j=>O(`cfg-${C.name}`,()=>m(C.name,j))},JSON.stringify(C.config))]},C.name)})]}),N.length>0&&y.jsxs("div",{className:"space-y-2",children:[y.jsx("h3",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Available"}),N.map(C=>y.jsxs("div",{className:"border rounded-lg p-3 flex items-center gap-2",children:[y.jsxs("div",{className:"min-w-0 flex-1",children:[y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx("span",{className:"font-medium text-sm truncate",children:C.name}),y.jsxs("span",{className:"text-[10px] font-mono px-1.5 py-0.5 rounded bg-muted text-muted-foreground shrink-0",children:["v",C.version]})]}),C.description&&y.jsx("p",{className:"text-xs text-muted-foreground",children:C.description})]}),y.jsxs(we,{size:"sm",variant:"outline",className:"h-7 text-xs shrink-0",disabled:x===`install-${C.name}`,onClick:()=>O(`install-${C.name}`,()=>d({name:C.name})),children:[x===`install-${C.name}`?y.jsx(Yi,{className:"w-3 h-3 mr-1 animate-spin"}):y.jsx(lL,{className:"w-3 h-3 mr-1"}),"Install"]})]},C.name))]})]})]})]})}async function Tl(e,t,n){const r=await t(),i=await fetch(e,{...n,headers:{Authorization:`Bearer ${r??""}`,"Content-Type":"application/json",...n==null?void 0:n.headers}});if(!i.ok){const a=await i.json().catch(()=>({}));throw new Error(a.error||`${i.status} ${i.statusText}`)}return i.json()}function fNe(e,t,n=0){const[r,i]=b.useState([]),[a,s]=b.useState(new Set),[l,u]=b.useState(!1),[d,h]=b.useState(null),m=b.useCallback(async()=>{u(!0),h(null);try{const k=await Tl("/api/schedules",e);i(k.schedules),s(new Set(k.runningIds))}catch(k){h(k.message)}finally{u(!1)}},[e]);b.useEffect(()=>{t&&m()},[t,m,n]);const p=b.useCallback(async k=>{const O=await Tl("/api/schedules",e,{method:"POST",body:JSON.stringify(k)});return await m(),O},[e,m]),g=b.useCallback(async(k,O)=>{const N=await Tl(`/api/schedules/${k}`,e,{method:"PUT",body:JSON.stringify(O)});return await m(),N},[e,m]),w=b.useCallback(async k=>{await Tl(`/api/schedules/${k}`,e,{method:"DELETE"}),await m()},[e,m]),x=b.useCallback(async(k,O)=>{await Tl(`/api/schedules/${k}/toggle`,e,{method:"POST",body:JSON.stringify({enabled:O})}),await m()},[e,m]),E=b.useCallback(async(k,O)=>{const N=await Tl(`/api/schedules/${k}/run`,e,{method:"POST",body:JSON.stringify(O?{override:O}:{})});return await m(),N.sessionId},[e,m]),_=b.useCallback(async k=>{await Tl(`/api/schedules/${k}/cancel`,e,{method:"POST"}),await m()},[e,m]);return{schedules:r,serverRunningIds:a,loading:l,error:d,refresh:m,create:p,update:g,remove:w,toggle:x,runNow:E,cancelRun:_}}var Tw={exports:{}},UD;function hNe(){return UD||(UD=1,(function(e,t){(function(r,i){e.exports=i()})(globalThis,()=>(()=>{var n={949(s,l,u){Object.defineProperty(l,"__esModule",{value:!0}),l.CronParser=void 0;var d=u(515),h=(function(){function m(p,g,w){g===void 0&&(g=!0),w===void 0&&(w=!1),this.expression=p,this.dayOfWeekStartIndexZero=g,this.monthStartIndexZero=w}return m.prototype.parse=function(){var p,g,w=(p=this.expression)!==null&&p!==void 0?p:"";if(w==="@reboot")return g=["@reboot","","","","","",""],g;if(w.startsWith("@")){var x=this.parseSpecial(this.expression);g=this.extractParts(x)}else g=this.extractParts(this.expression);return this.normalize(g),this.validate(g),g},m.prototype.parseSpecial=function(p){var g={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 * *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@midnight":"0 0 * * *","@hourly":"0 * * * *","@reboot":"@reboot"},w=g[p];if(!w)throw new Error("Unknown special expression.");return w},m.prototype.extractParts=function(p){if(!this.expression)throw new Error("cron expression is empty");for(var g=p.trim().split(/[ ]+/),w=0;w<g.length;w++)if(g[w].includes(",")){var x=g[w].split(",").map(function(_){return _.trim()}).filter(function(_){return _!==""}).map(function(_){return isNaN(Number(_))?_:Number(_)}).filter(function(_){return _!==null&&_!==""});x.length===0&&x.push("*"),x.sort(function(_,k){return _!==null&&k!==null?_-k:0}),g[w]=x.map(function(_){return _!==null?_.toString():""}).join(",")}if(g.length<5)throw new Error("Expression has only ".concat(g.length," part").concat(g.length==1?"":"s",". At least 5 parts are required."));if(g.length==5)g.unshift(""),g.push("");else if(g.length==6){var E=/\d{4}$/.test(g[5])||g[4]=="?"||g[2]=="?";E?g.unshift(""):g.push("")}else if(g.length>7)throw new Error("Expression has ".concat(g.length," parts; too many!"));return g},m.prototype.normalize=function(p){var g=this;if(p[3]=p[3].replace("?","*"),p[5]=p[5].replace("?","*"),p[2]=p[2].replace("?","*"),p[0].indexOf("0/")==0&&(p[0]=p[0].replace("0/","*/")),p[1].indexOf("0/")==0&&(p[1]=p[1].replace("0/","*/")),p[2].indexOf("0/")==0&&(p[2]=p[2].replace("0/","*/")),p[3].indexOf("1/")==0&&(p[3]=p[3].replace("1/","*/")),p[4].indexOf("1/")==0&&(p[4]=p[4].replace("1/","*/")),p[6].indexOf("1/")==0&&(p[6]=p[6].replace("1/","*/")),p[5]=p[5].replace(/(^\d)|([^#/\s]\d)/g,function(C){var T=C.replace(/\D/,""),M=T;return g.dayOfWeekStartIndexZero?T=="7"&&(M="0"):M=(parseInt(T)-1).toString(),C.replace(T,M)}),p[5]=="L"&&(p[5]="6"),p[3]=="?"&&(p[3]="*"),p[3].indexOf("W")>-1&&(p[3].indexOf(",")>-1||p[3].indexOf("-")>-1))throw new Error("The 'W' character can be specified only when the day-of-month is a single day, not a range or list of days.");var w={SUN:0,MON:1,TUE:2,WED:3,THU:4,FRI:5,SAT:6};for(var x in w)p[5]=p[5].replace(new RegExp(x,"gi"),w[x].toString());p[4]=p[4].replace(/(^\d{1,2})|([^#/\s]\d{1,2})/g,function(C){var T=C.replace(/\D/,""),M=T;return g.monthStartIndexZero&&(M=(parseInt(T)+1).toString()),C.replace(T,M)});var E={JAN:1,FEB:2,MAR:3,APR:4,MAY:5,JUN:6,JUL:7,AUG:8,SEP:9,OCT:10,NOV:11,DEC:12};for(var _ in E)p[4]=p[4].replace(new RegExp(_,"gi"),E[_].toString());p[0]=="0"&&(p[0]=""),!/\*|\-|\,|\//.test(p[2])&&(/\*|\//.test(p[1])||/\*|\//.test(p[0]))&&(p[2]+="-".concat(p[2]));for(var k=0;k<p.length;k++)if(p[k].indexOf(",")!=-1&&(p[k]=p[k].split(",").filter(function(C){return C!==""}).join(",")||"*"),p[k]=="*/1"&&(p[k]="*"),p[k].indexOf("/")>-1&&!/^\*|\-|\,/.test(p[k])){var O=null;switch(k){case 4:O="12";break;case 5:O="6";break;case 6:O="9999";break;default:O=null;break}if(O!==null){var N=p[k].split("/");p[k]="".concat(N[0],"-").concat(O,"/").concat(N[1])}}},m.prototype.validate=function(p){var g="0-9,\\-*/";this.validateOnlyExpectedCharactersFound(p[0],g),this.validateOnlyExpectedCharactersFound(p[1],g),this.validateOnlyExpectedCharactersFound(p[2],g),this.validateOnlyExpectedCharactersFound(p[3],"0-9,\\-*/LW"),this.validateOnlyExpectedCharactersFound(p[4],g),this.validateOnlyExpectedCharactersFound(p[5],"0-9,\\-*/L#"),this.validateOnlyExpectedCharactersFound(p[6],g),this.validateAnyRanges(p)},m.prototype.validateAnyRanges=function(p){d.default.secondRange(p[0]),d.default.minuteRange(p[1]),d.default.hourRange(p[2]),d.default.dayOfMonthRange(p[3]),d.default.monthRange(p[4],this.monthStartIndexZero),d.default.dayOfWeekRange(p[5],this.dayOfWeekStartIndexZero)},m.prototype.validateOnlyExpectedCharactersFound=function(p,g){var w=p.match(new RegExp("[^".concat(g,"]+"),"gi"));if(w&&w.length)throw new Error("Expression contains invalid values: '".concat(w.toString(),"'"))},m})();l.CronParser=h},333(s,l,u){Object.defineProperty(l,"__esModule",{value:!0}),l.ExpressionDescriptor=void 0;var d=u(823),h=u(949),m=(function(){function p(g,w){if(this.expression=g,this.options=w,this.expressionParts=new Array(5),!this.options.locale&&p.defaultLocale&&(this.options.locale=p.defaultLocale),!p.locales[this.options.locale]){var x=Object.keys(p.locales)[0];console.warn("Locale '".concat(this.options.locale,"' could not be found; falling back to '").concat(x,"'.")),this.options.locale=x}this.i18n=p.locales[this.options.locale],w.use24HourTimeFormat===void 0&&(w.use24HourTimeFormat=this.i18n.use24HourTimeFormatByDefault())}return p.toString=function(g,w){var x=w===void 0?{}:w,E=x.throwExceptionOnParseError,_=E===void 0?!0:E,k=x.verbose,O=k===void 0?!1:k,N=x.dayOfWeekStartIndexZero,C=N===void 0?!0:N,T=x.monthStartIndexZero,M=T===void 0?!1:T,D=x.use24HourTimeFormat,j=x.trimHoursLeadingZero,R=j===void 0?!1:j,H=x.locale,P=H===void 0?null:H,G=x.logicalAndDayFields,q=G===void 0?!1:G,X={throwExceptionOnParseError:_,verbose:O,dayOfWeekStartIndexZero:C,monthStartIndexZero:M,use24HourTimeFormat:D,trimHoursLeadingZero:R,locale:P,logicalAndDayFields:q};X.tzOffset&&console.warn("'tzOffset' option has been deprecated and is no longer supported.");var U=new p(g,X);return U.getFullDescription()},p.initialize=function(g,w){w===void 0&&(w="en"),p.specialCharacters=["/","-",",","*"],p.defaultLocale=w,g.load(p.locales)},p.prototype.getFullDescription=function(){var g,w,x="";try{var E=new h.CronParser(this.expression,this.options.dayOfWeekStartIndexZero,this.options.monthStartIndexZero);if(this.expressionParts=E.parse(),this.expressionParts[0]==="@reboot")return((w=(g=this.i18n).atReboot)===null||w===void 0?void 0:w.call(g))||"Run once, at startup";var _=this.getTimeOfDayDescription(),k=this.getDayOfMonthDescription(),O=this.getMonthDescription(),N=this.getDayOfWeekDescription(),C=this.getYearDescription();x+=_+k+N+O+C,x=this.transformVerbosity(x,!!this.options.verbose),x=x.charAt(0).toLocaleUpperCase()+x.substr(1)}catch(T){if(!this.options.throwExceptionOnParseError)x=this.i18n.anErrorOccuredWhenGeneratingTheExpressionD();else throw"".concat(T)}return x},p.prototype.getTimeOfDayDescription=function(){var g=this.expressionParts[0],w=this.expressionParts[1],x=this.expressionParts[2],E="";if(!d.StringUtilities.containsAny(w,p.specialCharacters)&&!d.StringUtilities.containsAny(x,p.specialCharacters)&&!d.StringUtilities.containsAny(g,p.specialCharacters))E+=this.i18n.atSpace()+this.formatTime(x,w,g);else if(!g&&w.indexOf("-")>-1&&!(w.indexOf(",")>-1)&&!(w.indexOf("/")>-1)&&!d.StringUtilities.containsAny(x,p.specialCharacters)){var _=w.split("-");E+=d.StringUtilities.format(this.i18n.everyMinuteBetweenX0AndX1(),this.formatTime(x,_[0],""),this.formatTime(x,_[1],""))}else if(!g&&x.indexOf(",")>-1&&x.indexOf("-")==-1&&x.indexOf("/")==-1&&!d.StringUtilities.containsAny(w,p.specialCharacters)){var k=x.split(",");E+=this.i18n.at();for(var O=0;O<k.length;O++)E&&(E+=" "),E+=this.formatTime(k[O],w,""),O<k.length-2&&(E+=","),O==k.length-2&&(E+=this.i18n.spaceAnd())}else{var N=this.getSecondsDescription(),C=this.getMinutesDescription(),T=this.getHoursDescription();if(E+=N,E&&C&&(E+=", "),E+=C,C===T)return E;E&&T&&(E+=", "),E+=T}return E},p.prototype.getSecondsDescription=function(){var g=this,w=this.getSegmentDescription(this.expressionParts[0],this.i18n.everySecond(),function(x){return x},function(x){return d.StringUtilities.format(g.i18n.everyX0Seconds(x),x)},function(x){return g.i18n.secondsX0ThroughX1PastTheMinute()},function(x){return x=="0"?"":parseInt(x)<20?g.i18n.atX0SecondsPastTheMinute(x):g.i18n.atX0SecondsPastTheMinuteGt20()||g.i18n.atX0SecondsPastTheMinute(x)});return w},p.prototype.getMinutesDescription=function(){var g=this,w=this.expressionParts[0],x=this.expressionParts[2],E=this.getSegmentDescription(this.expressionParts[1],this.i18n.everyMinute(),function(_){return _},function(_){return d.StringUtilities.format(g.i18n.everyX0Minutes(_),_)},function(_){return g.i18n.minutesX0ThroughX1PastTheHour()},function(_){var k,O;try{return _=="0"&&x.indexOf("/")==-1&&w==""?g.i18n.everyHour():_=="0"?((O=(k=g.i18n).onTheHour)===null||O===void 0?void 0:O.call(k))||g.i18n.atX0MinutesPastTheHour(_):parseInt(_)<20?g.i18n.atX0MinutesPastTheHour(_):g.i18n.atX0MinutesPastTheHourGt20()||g.i18n.atX0MinutesPastTheHour(_)}catch{return g.i18n.atX0MinutesPastTheHour(_)}});return E},p.prototype.getHoursDescription=function(){var g=this,w=this.expressionParts[2],x=0,E=[];w.split("/")[0].split(",").forEach(function(O){var N=O.split("-");N.length===2&&E.push({value:N[1],index:x+1}),x+=N.length});var _=0,k=this.getSegmentDescription(w,this.i18n.everyHour(),function(O){var N=E.find(function(T){return T.value===O&&T.index===_}),C=N&&g.expressionParts[1]!=="0";return _++,C?g.formatTime(O,"59",""):g.formatTime(O,"0","")},function(O){return d.StringUtilities.format(g.i18n.everyX0Hours(O),O)},function(O){return g.i18n.betweenX0AndX1()},function(O){return g.i18n.atX0()});return k},p.prototype.getDayOfWeekDescription=function(){var g=this,w=this.i18n.daysOfTheWeek(),x=null;return this.expressionParts[5]=="*"?x="":x=this.getSegmentDescription(this.expressionParts[5],this.i18n.commaEveryDay(),function(E,_){var k=E;E.indexOf("#")>-1?k=E.substring(0,E.indexOf("#")):E.indexOf("L")>-1&&(k=k.replace("L",""));var O=parseInt(k),N=g.i18n.daysOfTheWeekInCase?g.i18n.daysOfTheWeekInCase(_)[O]:w[O];if(E.indexOf("#")>-1){var C=null,T=E.substring(E.indexOf("#")+1),M=E.substring(0,E.indexOf("#"));switch(T){case"1":C=g.i18n.first(M);break;case"2":C=g.i18n.second(M);break;case"3":C=g.i18n.third(M);break;case"4":C=g.i18n.fourth(M);break;case"5":C=g.i18n.fifth(M);break}N=C+" "+N}return N},function(E){return parseInt(E)==1?"":d.StringUtilities.format(g.i18n.commaEveryX0DaysOfTheWeek(E),E)},function(E){var _=E.substring(0,E.indexOf("-")),k=g.expressionParts[3]!="*";return k?g.i18n.commaAndX0ThroughX1(_):g.i18n.commaX0ThroughX1(_)},function(E){var _=null;if(E.indexOf("#")>-1){var k=E.substring(E.indexOf("#")+1),O=E.substring(0,E.indexOf("#"));_=g.i18n.commaOnThe(k,O).trim()+g.i18n.spaceX0OfTheMonth()}else if(E.indexOf("L")>-1)_=g.i18n.commaOnTheLastX0OfTheMonth(E.replace("L",""));else{var N=g.expressionParts[3]!="*";N?g.options.logicalAndDayFields?_=g.i18n.commaOnlyOnX0(E):_=g.i18n.commaAndOnX0():_=g.i18n.commaOnlyOnX0(E)}return _}),x},p.prototype.getMonthDescription=function(){var g=this,w=this.i18n.monthsOfTheYear(),x=this.getSegmentDescription(this.expressionParts[4],"",function(E,_){return _&&g.i18n.monthsOfTheYearInCase?g.i18n.monthsOfTheYearInCase(_)[parseInt(E)-1]:w[parseInt(E)-1]},function(E){return parseInt(E)==1?"":d.StringUtilities.format(g.i18n.commaEveryX0Months(E),E)},function(E){return g.i18n.commaMonthX0ThroughMonthX1()||g.i18n.commaX0ThroughX1()},function(E){return g.i18n.commaOnlyInMonthX0?g.i18n.commaOnlyInMonthX0():g.i18n.commaOnlyInX0()});return x},p.prototype.getDayOfMonthDescription=function(){var g=this,w=null,x=this.expressionParts[3];switch(x){case"L":w=this.i18n.commaOnTheLastDayOfTheMonth();break;case"WL":case"LW":w=this.i18n.commaOnTheLastWeekdayOfTheMonth();break;default:var E=x.match(/(\d{1,2}W)|(W\d{1,2})/);if(E){var _=parseInt(E[0].replace("W","")),k=_==1?this.i18n.firstWeekday():d.StringUtilities.format(this.i18n.weekdayNearestDayX0(),_.toString());w=d.StringUtilities.format(this.i18n.commaOnTheX0OfTheMonth(),k);break}else{var O=x.match(/L-(\d{1,2})/);if(O){var N=O[1];w=d.StringUtilities.format(this.i18n.commaDaysBeforeTheLastDayOfTheMonth(N),N);break}else{if(x=="*"&&this.expressionParts[5]!="*")return"";w=this.getSegmentDescription(x,this.i18n.commaEveryDay(),function(C){return C=="L"?g.i18n.lastDay():g.i18n.dayX0?d.StringUtilities.format(g.i18n.dayX0(),C):C},function(C){return C=="1"?g.i18n.commaEveryDay():g.i18n.commaEveryX0Days(C)},function(C){return g.i18n.commaBetweenDayX0AndX1OfTheMonth(C)},function(C){return g.i18n.commaOnDayX0OfTheMonth(C)})}break}}return w},p.prototype.getYearDescription=function(){var g=this,w=this.getSegmentDescription(this.expressionParts[6],"",function(x){return/^\d+$/.test(x)?new Date(parseInt(x),1).getFullYear().toString():x},function(x){return d.StringUtilities.format(g.i18n.commaEveryX0Years(x),x)},function(x){return g.i18n.commaYearX0ThroughYearX1()||g.i18n.commaX0ThroughX1()},function(x){return g.i18n.commaOnlyInYearX0?g.i18n.commaOnlyInYearX0():g.i18n.commaOnlyInX0()});return w},p.prototype.getSegmentDescription=function(g,w,x,E,_,k){var O=null,N=g.indexOf("/")>-1,C=g.indexOf("-")>-1,T=g.indexOf(",")>-1;if(!g)O="";else if(g==="*")O=w;else if(!N&&!C&&!T)O=d.StringUtilities.format(k(g),x(g));else if(T){for(var M=g.split(","),D="",j=this.i18n.spaceAnd(),R=0;R<M.length;R++)if(R>0&&M.length>2&&(D+=",",R<M.length-1&&(D+=" ")),R>0&&M.length>1&&(R==M.length-1||M.length==2)&&(D+=j==","&&M.length>2?" ":"".concat(j," ")),M[R].indexOf("/")>-1||M[R].indexOf("-")>-1){var H=M[R].indexOf("-")>-1&&M[R].indexOf("/")==-1,P=this.getSegmentDescription(M[R],w,x,E,H?this.i18n.commaX0ThroughX1:_,k);H&&(P=P.replace(", ","")),D+=P}else if(!N)D+=x(M[R]);else{var G=this.getSegmentDescription(M[R],w,x,E,_,k);G&&G.startsWith(", ")&&(G=G.substring(2)),D+=G}N?O=D:O=d.StringUtilities.format(k(g),D)}else if(N){var M=g.split("/");if(O=d.StringUtilities.format(E(M[1]),M[1]),M[0].indexOf("-")>-1){var q=this.generateRangeSegmentDescription(M[0],_,x);q.indexOf(", ")!=0&&(O+=", "),O+=q}else if(M[0].indexOf("*")==-1){var X=d.StringUtilities.format(k(M[0]),x(M[0]));X=X.replace(", ",""),O+=d.StringUtilities.format(this.i18n.commaStartingX0(),X)}}else C&&(O=this.generateRangeSegmentDescription(g,_,x));return O},p.prototype.generateRangeSegmentDescription=function(g,w,x){var E="",_=g.split("-"),k=x(_[0],1),O=x(_[1],2),N=w(g);return E+=d.StringUtilities.format(N,k,O),E},p.prototype.formatTime=function(g,w,x){var E=0,_=0,k=parseInt(g)+E,O=parseInt(w)+_;O>=60?(O-=60,k+=1):O<0&&(O+=60,k-=1),k>=24?k=k-24:k<0&&(k=24+k);var N="",C=!1;this.options.use24HourTimeFormat||(C=!!(this.i18n.setPeriodBeforeTime&&this.i18n.setPeriodBeforeTime()),N=C?"".concat(this.getPeriod(k)," "):" ".concat(this.getPeriod(k)),k>12&&(k-=12),k===0&&(k=12));var T="";x&&(T=":".concat(("00"+x).substring(x.length)));var M=k.toString(),D=("00"+M).substring(M.length),j=O.toString(),R=("00"+j).substring(j.length),H=this.options.trimHoursLeadingZero?M:D;return"".concat(C?N:"").concat(H,":").concat(R).concat(T).concat(C?"":N)},p.prototype.transformVerbosity=function(g,w){if(!w&&(g=g.replace(new RegExp(", ".concat(this.i18n.everyMinute()),"g"),""),g=g.replace(new RegExp(", ".concat(this.i18n.everyHour()),"g"),""),g=g.replace(new RegExp(this.i18n.commaEveryDay(),"g"),""),g=g.replace(/\, ?$/,""),this.i18n.conciseVerbosityReplacements))for(var x=0,E=Object.entries(this.i18n.conciseVerbosityReplacements());x<E.length;x++){var _=E[x],k=_[0],O=_[1];g=g.replace(new RegExp(k,"g"),O)}return g},p.prototype.getPeriod=function(g){return g>=12?this.i18n.pm&&this.i18n.pm()||"PM":this.i18n.am&&this.i18n.am()||"AM"},p.locales={},p})();l.ExpressionDescriptor=m},747(s,l,u){Object.defineProperty(l,"__esModule",{value:!0}),l.enLocaleLoader=void 0;var d=u(486),h=(function(){function m(){}return m.prototype.load=function(p){p.en=new d.en},m})();l.enLocaleLoader=h},486(s,l){Object.defineProperty(l,"__esModule",{value:!0}),l.en=void 0;var u=(function(){function d(){}return d.prototype.atX0SecondsPastTheMinuteGt20=function(){return null},d.prototype.atX0MinutesPastTheHourGt20=function(){return null},d.prototype.commaMonthX0ThroughMonthX1=function(){return null},d.prototype.commaYearX0ThroughYearX1=function(){return null},d.prototype.use24HourTimeFormatByDefault=function(){return!1},d.prototype.anErrorOccuredWhenGeneratingTheExpressionD=function(){return"An error occurred when generating the expression description. Check the cron expression syntax."},d.prototype.everyMinute=function(){return"every minute"},d.prototype.everyHour=function(){return"every hour"},d.prototype.atSpace=function(){return"At "},d.prototype.everyMinuteBetweenX0AndX1=function(){return"Every minute between %s and %s"},d.prototype.at=function(){return"At"},d.prototype.spaceAnd=function(){return" and"},d.prototype.everySecond=function(){return"every second"},d.prototype.everyX0Seconds=function(){return"every %s seconds"},d.prototype.secondsX0ThroughX1PastTheMinute=function(){return"seconds %s through %s past the minute"},d.prototype.atX0SecondsPastTheMinute=function(){return"at %s seconds past the minute"},d.prototype.everyX0Minutes=function(){return"every %s minutes"},d.prototype.minutesX0ThroughX1PastTheHour=function(){return"minutes %s through %s past the hour"},d.prototype.atX0MinutesPastTheHour=function(){return"at %s minutes past the hour"},d.prototype.everyX0Hours=function(){return"every %s hours"},d.prototype.betweenX0AndX1=function(){return"between %s and %s"},d.prototype.atX0=function(){return"at %s"},d.prototype.commaEveryDay=function(){return", every day"},d.prototype.commaEveryX0DaysOfTheWeek=function(){return", every %s days of the week"},d.prototype.commaX0ThroughX1=function(){return", %s through %s"},d.prototype.commaAndX0ThroughX1=function(){return", %s through %s"},d.prototype.first=function(){return"first"},d.prototype.second=function(){return"second"},d.prototype.third=function(){return"third"},d.prototype.fourth=function(){return"fourth"},d.prototype.fifth=function(){return"fifth"},d.prototype.commaOnThe=function(){return", on the "},d.prototype.spaceX0OfTheMonth=function(){return" %s of the month"},d.prototype.lastDay=function(){return"the last day"},d.prototype.commaOnTheLastX0OfTheMonth=function(){return", on the last %s of the month"},d.prototype.commaOnlyOnX0=function(){return", only on %s"},d.prototype.commaAndOnX0=function(){return", and on %s"},d.prototype.commaEveryX0Months=function(){return", every %s months"},d.prototype.commaOnlyInX0=function(){return", only in %s"},d.prototype.commaOnTheLastDayOfTheMonth=function(){return", on the last day of the month"},d.prototype.commaOnTheLastWeekdayOfTheMonth=function(){return", on the last weekday of the month"},d.prototype.commaDaysBeforeTheLastDayOfTheMonth=function(){return", %s days before the last day of the month"},d.prototype.firstWeekday=function(){return"first weekday"},d.prototype.weekdayNearestDayX0=function(){return"weekday nearest day %s"},d.prototype.commaOnTheX0OfTheMonth=function(){return", on the %s of the month"},d.prototype.commaEveryX0Days=function(){return", every %s days in a month"},d.prototype.commaBetweenDayX0AndX1OfTheMonth=function(){return", between day %s and %s of the month"},d.prototype.commaOnDayX0OfTheMonth=function(){return", on day %s of the month"},d.prototype.commaEveryHour=function(){return", every hour"},d.prototype.commaEveryX0Years=function(){return", every %s years"},d.prototype.commaStartingX0=function(){return", starting %s"},d.prototype.daysOfTheWeek=function(){return["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},d.prototype.monthsOfTheYear=function(){return["January","February","March","April","May","June","July","August","September","October","November","December"]},d.prototype.atReboot=function(){return"Run once, at startup"},d.prototype.onTheHour=function(){return"on the hour"},d})();l.en=u},515(s,l){Object.defineProperty(l,"__esModule",{value:!0});function u(h,m){if(!h)throw new Error(m)}var d=(function(){function h(){}return h.secondRange=function(m){for(var p=m.split(","),g=0;g<p.length;g++)if(!isNaN(parseInt(p[g],10))){var w=parseInt(p[g],10);u(w>=0&&w<=59,"seconds part must be >= 0 and <= 59")}},h.minuteRange=function(m){for(var p=m.split(","),g=0;g<p.length;g++)if(!isNaN(parseInt(p[g],10))){var w=parseInt(p[g],10);u(w>=0&&w<=59,"minutes part must be >= 0 and <= 59")}},h.hourRange=function(m){for(var p=m.split(","),g=0;g<p.length;g++)if(!isNaN(parseInt(p[g],10))){var w=parseInt(p[g],10);u(w>=0&&w<=23,"hours part must be >= 0 and <= 23")}},h.dayOfMonthRange=function(m){for(var p=m.split(","),g=0;g<p.length;g++)if(!isNaN(parseInt(p[g],10))){var w=parseInt(p[g],10);u(w>=1&&w<=31,"DOM part must be >= 1 and <= 31")}},h.monthRange=function(m,p){for(var g=m.split(","),w=0;w<g.length;w++)if(!isNaN(parseInt(g[w],10))){var x=parseInt(g[w],10);u(x>=1&&x<=12,p?"month part must be >= 0 and <= 11":"month part must be >= 1 and <= 12")}},h.dayOfWeekRange=function(m,p){for(var g=m.split(","),w=0;w<g.length;w++)if(!isNaN(parseInt(g[w],10))){var x=parseInt(g[w],10);u(x>=0&&x<=6,p?"DOW part must be >= 0 and <= 6":"DOW part must be >= 1 and <= 7")}},h})();l.default=d},823(s,l){Object.defineProperty(l,"__esModule",{value:!0}),l.StringUtilities=void 0;var u=(function(){function d(){}return d.format=function(h){for(var m=[],p=1;p<arguments.length;p++)m[p-1]=arguments[p];return h.replace(/%s/g,function(g){return m.shift()})},d.containsAny=function(h,m){return m.some(function(p){return h.indexOf(p)>-1})},d})();l.StringUtilities=u}},r={};function i(s){var l=r[s];if(l!==void 0)return l.exports;var u=r[s]={exports:{}};return n[s](u,u.exports,i),u.exports}var a={};return(()=>{var s=a;Object.defineProperty(s,"__esModule",{value:!0}),s.toString=void 0;var l=i(333),u=i(747);l.ExpressionDescriptor.initialize(new u.enLocaleLoader),s.default=l.ExpressionDescriptor;var d=l.ExpressionDescriptor.toString;s.toString=d})(),a})())})(Tw)),Tw.exports}var mNe=hNe();const S8=Xu(mNe);function pNe(e){return e.trigger.kind}function gNe(e){var n;const t=e.trigger;if(t.kind==="once")return`Once at ${new Date(t.at).toLocaleString()}`;if(t.kind==="interval"){const r=Math.round(t.everyMs/1e3);return r>=86400?`Every ${Math.round(r/86400)}d`:r>=3600?`Every ${Math.round(r/3600)}h`:r>=60?`Every ${Math.round(r/60)}m`:`Every ${r}s`}if(t.kind==="event"){const r=t.match?Object.entries(t.match).map(([i,a])=>`${i}=${a}`).join(", "):"";return`On event "${t.source}"${r?` where ${r}`:""}`}try{const r=t.tz||"UTC",i=vNe(t.expr,r),a=S8.toString(t.expr),s=r==="UTC"?"UTC":((n=r.split("/").pop())==null?void 0:n.replace(/_/g," "))||r;return i?`${i} (${a} ${s})`:`${a} ${s}`}catch{return t.expr}}function vNe(e,t){try{const n=e.split(/\s+/);if(n.length<5)return null;const r=parseInt(n[0],10),i=parseInt(n[1],10);if(isNaN(r)||isNaN(i))return null;const a=new Date,s=new Date(a.toLocaleString("en-US",{timeZone:t})).getTime()-new Date(a.toLocaleString("en-US",{timeZone:"UTC"})).getTime(),l=new Date;return l.setUTCHours(i,r,0,0),new Date(l.getTime()-s).toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit",hour12:!1,timeZone:"UTC"})}catch{return null}}function FD(e){if(!e)return"—";const t=e-Date.now(),n=Math.abs(t),r=Math.round(n/6e4);if(n<6e4)return t>0?"in <1m":"<1m ago";if(r<60)return t>0?`in ${r}m`:`${r}m ago`;const i=Math.round(r/60);if(i<24)return t>0?`in ${i}h`:`${i}h ago`;const a=Math.round(i/24);return t>0?`in ${a}d`:`${a}d ago`}const yNe={ok:"bg-green-50 text-green-700 dark:bg-green-950/50 dark:text-green-300",error:"bg-red-50 text-red-700 dark:bg-red-950/50 dark:text-red-300",running:"bg-blue-50 text-blue-700 dark:bg-blue-950/50 dark:text-blue-300",aborted:"bg-amber-50 text-amber-700 dark:bg-amber-950/50 dark:text-amber-300"};function bNe(e){return e.scope==="system"}function xNe(e){return e==="prompt"?"Additional instructions (appended to prompt)":e==="bash"?"Override command":"Override args"}function wNe(e){return e==="prompt"?"e.g. Dry run — compose the message but do NOT post to Slack":e==="bash"?"e.g. bun run report:fb-ads-spend --dry-run":"e.g. --dry-run"}function ENe(e,t){var n;return e.scope==="system"?"system":((n=e.createdBy)==null?void 0:n.uid)===t?"mine":"others"}function SNe({schedules:e,currentUserUid:t,onCreate:n,onEdit:r,onDelete:i,onToggle:a,onRunNow:s,onCancel:l,onOpenRun:u,runningIds:d=new Set}){const[h,m]=b.useState(null),[p,g]=b.useState(""),[w,x]=b.useState({mine:!0,others:!0,system:!0}),[E,_]=b.useState({once:!0,interval:!0,cron:!0,event:!0}),[k,O]=b.useState(!1),N=j=>x(R=>{if(Object.values(R).every(Boolean))return{mine:!1,others:!1,system:!1,[j]:!0};const P={...R,[j]:!R[j]};return Object.values(P).some(Boolean)?P:{mine:!0,others:!0,system:!0}}),C=j=>_(R=>{if(Object.values(R).every(Boolean))return{once:!1,interval:!1,cron:!1,event:!1,[j]:!0};const P={...R,[j]:!R[j]};return Object.values(P).some(Boolean)?P:{once:!0,interval:!0,cron:!0,event:!0}}),T=e.filter(j=>w[ENe(j,t)]&&E[pNe(j)]),M=j=>{const R=localStorage.getItem(`schedule-override-${j.id}`);g(R??""),m(j.id)},D=async()=>{if(h){O(!0);try{const j=p.trim()||void 0;j&&localStorage.setItem(`schedule-override-${h}`,j);const R=await s(h,j);m(null),g(""),R&&u(R)}finally{O(!1)}}};return y.jsxs("div",{className:"space-y-3",children:[y.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[y.jsxs("div",{className:"flex gap-1 flex-wrap",children:[["mine","others","system"].map(j=>y.jsx("button",{onClick:()=>N(j),className:`text-[11px] px-2 py-0.5 rounded-full border transition-colors ${w[j]?"bg-primary text-primary-foreground border-primary":"bg-transparent text-muted-foreground border-border hover:border-muted-foreground"}`,children:j},j)),y.jsx("span",{className:"w-px h-4 bg-border mx-1"}),["once","interval","cron","event"].map(j=>y.jsx("button",{onClick:()=>C(j),className:`text-[11px] px-2 py-0.5 rounded-full border transition-colors ${E[j]?"bg-primary text-primary-foreground border-primary":"bg-transparent text-muted-foreground border-border hover:border-muted-foreground"}`,children:j},j))]}),y.jsxs(we,{size:"sm",onClick:n,className:"gap-1",children:[y.jsx(ko,{className:"w-4 h-4"})," New schedule"]})]}),T.length===0&&y.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:e.length===0?"No schedules yet.":"No schedules match filters."}),T.map(j=>{var R,H;return y.jsxs("div",{className:"border rounded-lg p-3 space-y-2 overflow-hidden",children:[y.jsxs("div",{className:"flex items-start justify-between gap-2 flex-wrap",children:[y.jsxs("div",{className:"min-w-0 flex-1",children:[y.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-wrap",children:[y.jsx("input",{type:"checkbox",checked:j.enabled,onChange:P=>a(j.id,P.target.checked),title:j.enabled?"Disable":"Enable",className:"shrink-0"}),y.jsx("span",{className:"font-medium text-sm truncate max-w-[280px]",title:j.name,children:j.name}),y.jsx("span",{className:"shrink-0 text-[10px] font-mono px-1.5 py-0.5 rounded bg-muted text-muted-foreground",children:j.task.kind}),y.jsx("span",{className:"shrink-0 text-[10px] font-mono px-1.5 py-0.5 rounded bg-muted text-muted-foreground",children:j.trigger.kind}),d.has(j.id)&&y.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] px-1.5 py-0.5 rounded bg-blue-50 text-blue-700 dark:bg-blue-950/50 dark:text-blue-300",children:[y.jsx(Yi,{className:"w-3 h-3 animate-spin"}),"running"]}),y.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-blue-50 text-blue-700 dark:bg-blue-950/50 dark:text-blue-300",children:bNe(j)?"system":((H=(R=j.createdBy)==null?void 0:R.email)==null?void 0:H.split("@")[0])??"unknown"})]}),y.jsx("div",{className:"mt-1 text-xs text-muted-foreground truncate",children:gNe(j)}),y.jsxs("div",{className:"mt-1 flex items-center gap-3 text-xs text-muted-foreground",children:[y.jsxs("span",{children:["Next: ",j.enabled?FD(j.nextRun):"disabled"]}),j.lastRun&&y.jsxs("button",{className:`px-1.5 py-0.5 rounded text-[10px] ${yNe[j.lastRun.status]??""}`,onClick:()=>u(j.lastRun.sessionId),title:"Open last run",children:["last: ",j.lastRun.status," ",FD(j.lastRun.at)]}),y.jsxs("span",{children:["runs: ",j.runCount??0]})]})]}),y.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[d.has(j.id)?y.jsx(we,{variant:"ghost",size:"icon",title:"Stop run",onClick:()=>l(j.id),children:y.jsx(fL,{className:"w-4 h-4 text-destructive"})}):y.jsx(we,{variant:"ghost",size:"icon",title:"Run now",onClick:()=>M(j),children:y.jsx(cV,{className:"w-4 h-4"})}),y.jsx(we,{variant:"ghost",size:"icon",title:"Edit",onClick:()=>r(j),children:y.jsx(KE,{className:"w-4 h-4"})}),y.jsx(we,{variant:"ghost",size:"icon",title:"Delete",onClick:()=>i(j.id),children:y.jsx(Xi,{className:"w-4 h-4 text-destructive"})})]})]}),h===j.id&&y.jsxs("div",{className:"border-t pt-2 mt-2 space-y-2",children:[y.jsx("label",{className:"text-xs text-muted-foreground",children:xNe(j.task.kind)}),y.jsx("input",{type:"text",className:"w-full text-sm border rounded px-2 py-1.5 bg-background",placeholder:wNe(j.task.kind),value:p,onChange:P=>g(P.target.value),onKeyDown:P=>{P.key==="Enter"&&!k&&D(),P.key==="Escape"&&m(null)},disabled:k,autoFocus:!0}),y.jsxs("div",{className:"flex gap-2 justify-end",children:[y.jsx(we,{size:"sm",variant:"ghost",onClick:()=>m(null),disabled:k,children:"Cancel"}),y.jsx(we,{size:"sm",onClick:D,disabled:k,children:k?"Running...":"Run"})]})]})]},j.id)})]})}function _Ne(e){const{directives:t}=XOe(e),n=XA(e,{strict:!0}).groups.some(r=>r.split(",").some(i=>/^\s*engine\s*:/i.test(i)));return{engine:t.engine,model:t.model,engineExplicit:n}}const ANe=/^(engine|model)\s*:/i;function kNe(e,t){var h;const{groups:n,body:r}=XA(e,{strict:!0}),i=[];let a=!1;for(const m of n)for(const p of m.split(",").map(g=>g.trim()).filter(Boolean)){if(ANe.test(p))continue;if(p.includes(":")){i.push(p);continue}const g=!a&&!!_E(p);a=!0,g||i.push(p)}const s=t.model?(h=_E(t.model))==null?void 0:h.engine:void 0,l=t.engine&&t.engine!==s?t.engine:void 0,d=[...[l&&`engine:${l}`,t.model&&`model:${t.model}`].filter(Boolean),...i];return d.length?`[${d.join(",")}] ${r}`:r}function ONe(e){const t=new Date(e??Date.now()+6e4),n=r=>String(r).padStart(2,"0");return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}T${n(t.getHours())}:${n(t.getMinutes())}`}const NNe=[{label:"1 min",ms:6e4},{label:"5 min",ms:5*6e4},{label:"15 min",ms:15*6e4},{label:"1 hour",ms:60*6e4},{label:"6 hours",ms:360*6e4},{label:"1 day",ms:1440*6e4}],CNe=[{label:"Every hour",expr:"0 * * * *"},{label:"Daily 9am",expr:"0 9 * * *"},{label:"Weekdays 9am",expr:"0 9 * * 1-5"},{label:"Mondays 9am",expr:"0 9 * * 1"}];function TNe({match:e,onChange:t}){const n=Object.entries(e),r=(s,l,u)=>{const d={};n.forEach(([h,m],p)=>{d[p===s?l:h]=p===s?u:m}),t(d)},i=s=>t(Object.fromEntries(n.filter((l,u)=>u!==s))),a=()=>t({...e,"":""});return y.jsxs("div",{className:"space-y-1",children:[y.jsx("label",{className:"text-xs text-muted-foreground",children:"Match filter (optional — all must match)"}),n.map(([s,l],u)=>y.jsxs("div",{className:"flex gap-1",children:[y.jsx(ft,{className:"text-xs font-mono",value:s,onChange:d=>r(u,d.target.value,l),placeholder:"payload.path (e.g. type)"}),y.jsx(ft,{className:"text-xs font-mono",value:l,onChange:d=>r(u,s,d.target.value),placeholder:"value (e.g. invoice.paid)"}),y.jsx(we,{type:"button",variant:"ghost",size:"sm",onClick:()=>i(u),children:"×"})]},u)),y.jsx(we,{type:"button",variant:"outline",size:"sm",onClick:a,children:"+ Add filter"})]})}function MNe({prompt:e,onChange:t,getToken:n}){const{engines:r}=w8(n),i=r.length>0,a=b.useMemo(()=>_Ne(e),[e,i]),s=a.engineExplicit?r.find(g=>g.name===a.engine):void 0,l=s?[{engine:s.name,models:s.models}]:r.map(g=>({engine:g.name,models:g.models})),u=(g,w)=>!g||w.includes(g),d=u(a.model,l.flatMap(g=>g.models.map(w=>w.value))),h=u(a.engine,r.map(g=>g.name)),m=g=>t(kNe(e,{engine:a.engineExplicit?a.engine:void 0,model:a.model,...g})),p="h-8 rounded-md border border-input bg-background px-2 text-xs";return y.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[y.jsx("label",{className:"text-xs text-muted-foreground",children:"Runtime"}),y.jsxs("select",{className:p,disabled:!i,value:a.engine??"",onChange:g=>m({engine:g.target.value||void 0,model:void 0}),children:[y.jsx("option",{value:"",children:"Default engine (agent config)"}),!h&&y.jsxs("option",{value:a.engine,children:[a.engine," — not registered on this server"]}),r.map(g=>y.jsx("option",{value:g.name,children:g.name},g.name))]}),y.jsxs("select",{className:p,disabled:!i,value:a.model??"",onChange:g=>m({model:g.target.value||void 0}),children:[y.jsx("option",{value:"",children:"Default model (agent config)"}),!d&&y.jsxs("option",{value:a.model,children:[a.model," — not offered by this engine"]}),l.map(({engine:g,models:w})=>y.jsx("optgroup",{label:g,children:w.filter(x=>x.value).map(x=>y.jsx("option",{value:x.value,children:x.label||x.value},`${g}:${x.value}`))},g))]}),!i&&y.jsx("span",{className:"text-[10px] text-muted-foreground",children:"loading engines…"})]})}function HD({getToken:e,initial:t,onSave:n,onCancel:r,skills:i=[],workspaceFiles:a=[]}){const s=b.useMemo(()=>Intl.DateTimeFormat().resolvedOptions().timeZone,[]),[l,u]=b.useState((t==null?void 0:t.name)??"New schedule"),[d,h]=b.useState((t==null?void 0:t.enabled)??!0),[m,p]=b.useState((t==null?void 0:t.trigger)??{kind:"cron",expr:"0 9 * * *",tz:s}),[g,w]=b.useState((t==null?void 0:t.task)??{kind:"prompt",prompt:""}),[x,E]=b.useState(!1),[_,k]=b.useState(null),O=b.useMemo(()=>{if(m.kind!=="cron")return"";try{return S8.toString(m.expr)}catch{return"Invalid cron"}},[m]),N=async()=>{E(!0),k(null);try{await n({name:l,enabled:d,trigger:m,task:g})}catch(C){k(C.message)}finally{E(!1)}};return y.jsxs("div",{className:"space-y-4",children:[y.jsxs("div",{className:"space-y-1",children:[y.jsx("label",{className:"text-xs text-muted-foreground",children:"Name"}),y.jsx(ft,{value:l,onChange:C=>u(C.target.value),placeholder:"e.g. Daily standup summary"})]}),y.jsxs("div",{className:"space-y-2",children:[y.jsx("label",{className:"text-xs text-muted-foreground",children:"Trigger"}),y.jsx("div",{className:"flex gap-1",children:["once","interval","cron","event"].map(C=>y.jsx(we,{type:"button",variant:m.kind===C?"default":"outline",size:"sm",onClick:()=>{p(C==="once"?{kind:"once",at:Date.now()+5*6e4}:C==="interval"?{kind:"interval",everyMs:60*6e4}:C==="event"?{kind:"event",source:""}:{kind:"cron",expr:"0 9 * * *",tz:s})},children:C},C))}),m.kind==="once"&&y.jsx(ft,{type:"datetime-local",value:ONe(m.at),onChange:C=>{const T=new Date(C.target.value);isNaN(T.getTime())||p({kind:"once",at:T.getTime()})}}),m.kind==="interval"&&y.jsxs("div",{className:"space-y-2",children:[y.jsx("div",{className:"flex gap-1 flex-wrap",children:NNe.map(C=>y.jsx(we,{type:"button",variant:m.everyMs===C.ms?"default":"outline",size:"sm",onClick:()=>p({kind:"interval",everyMs:C.ms}),children:C.label},C.ms))}),y.jsx(ft,{type:"number",min:1,value:Math.round(m.everyMs/1e3),onChange:C=>p({kind:"interval",everyMs:Math.max(1,Number(C.target.value))*1e3}),placeholder:"seconds"}),y.jsxs("p",{className:"text-xs text-muted-foreground",children:["Every ",Math.round(m.everyMs/1e3),"s"]})]}),m.kind==="cron"&&y.jsxs("div",{className:"space-y-2",children:[y.jsx("div",{className:"flex gap-1 flex-wrap",children:CNe.map(C=>y.jsx(we,{type:"button",variant:"outline",size:"sm",onClick:()=>p({kind:"cron",expr:C.expr,tz:s}),children:C.label},C.expr))}),y.jsx(ft,{className:"font-mono text-xs",value:m.expr,onChange:C=>p({...m,expr:C.target.value}),placeholder:"0 9 * * *"}),y.jsx(ft,{className:"text-xs",value:m.tz,onChange:C=>p({...m,tz:C.target.value}),placeholder:"IANA timezone"}),y.jsxs("p",{className:"text-xs text-muted-foreground",children:[O," (",m.tz,")"]})]}),m.kind==="event"&&y.jsxs("div",{className:"space-y-2",children:[y.jsx(ft,{value:m.source,onChange:C=>p({...m,source:C.target.value}),placeholder:"Event source (e.g. stripe, github, deploy)"}),y.jsxs("p",{className:"text-xs text-muted-foreground",children:["Fires when an event with this source arrives via ",y.jsxs("code",{children:["POST /api/events/",m.source||":source"]})," or ",y.jsx("code",{children:"ctx.emitEvent()"}),"."]}),y.jsx(TNe,{match:m.match??{},onChange:C=>p({...m,match:C})})]})]}),y.jsxs("div",{className:"space-y-2",children:[y.jsx("label",{className:"text-xs text-muted-foreground",children:"Task"}),y.jsx("div",{className:"flex gap-1",children:["prompt","bash"].map(C=>y.jsx(we,{type:"button",variant:g.kind===C?"default":"outline",size:"sm",onClick:()=>w(C==="prompt"?{kind:"prompt",prompt:""}:{kind:"bash",command:""}),children:C==="prompt"?"Prompt":"Bash command"},C))}),g.kind==="prompt"?y.jsxs(y.Fragment,{children:[y.jsx(MNe,{prompt:g.prompt,getToken:e,onChange:C=>w({...g,prompt:C})}),y.jsx(v8,{rows:5,value:g.prompt,onChange:C=>w({...g,prompt:C}),placeholder:"What should the agent do? (@ for skills, / for commands)",skills:i,workspaceFiles:a,autoResize:!1,className:"flex min-h-[80px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"})]}):g.kind==="bash"?y.jsx(Vy,{rows:3,className:"font-mono text-xs",value:g.command,onChange:C=>w({...g,command:C.target.value}),placeholder:"ls -la ~/"}):y.jsxs("p",{className:"text-xs text-muted-foreground",children:["Command: ",g.command]})]}),y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx("input",{id:"sched-enabled",type:"checkbox",checked:d,onChange:C=>h(C.target.checked)}),y.jsx("label",{htmlFor:"sched-enabled",className:"text-sm",children:"Enabled"})]}),_&&y.jsx("p",{className:"text-xs text-destructive",children:_}),y.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[y.jsx(we,{variant:"outline",onClick:r,disabled:x,children:"Cancel"}),y.jsx(we,{onClick:N,disabled:x,children:x?"Saving…":"Save"})]})]})}const KD=b.forwardRef(function({getToken:t,onOpenSession:n,refreshKey:r=0,runningIds:i=new Set,skills:a=[],workspaceFiles:s=[],trigger:l},u){const[d,h]=b.useState(!1),{user:m}=Yj(),{schedules:p,serverRunningIds:g,create:w,update:x,remove:E,toggle:_,runNow:k,cancelRun:O}=fNe(t,d,r);b.useImperativeHandle(u,()=>({open:()=>h(!0)}),[]);const[N,C]=b.useState(null),[T,M]=b.useState(!1),[D,j]=b.useState(new Set),R=()=>{C(null),M(!1)},H=async(P,G)=>{j(q=>new Set(q).add(P));try{return await k(P,G)}finally{setTimeout(()=>{j(q=>{const X=new Set(q);return X.delete(P),X})},1500)}};return y.jsxs(Oo,{open:d,onOpenChange:P=>{h(P),P||R()},children:[y.jsx(rd,{asChild:!0,children:l||y.jsx(we,{variant:"ghost",size:"icon",className:"h-8 w-8",title:"Scheduled Tasks",children:y.jsx(BE,{className:"w-4 h-4"})})}),y.jsxs(Na,{className:"max-w-[95vw] sm:max-w-2xl",children:[y.jsx(Bs,{children:y.jsx(No,{children:T?"New Schedule":N?`Edit: ${N.name}`:"Scheduled Tasks"})}),T?y.jsx(HD,{getToken:t,onSave:async P=>{await w(P),R()},onCancel:R,skills:a,workspaceFiles:s},"__new__"):N?y.jsx(HD,{getToken:t,initial:N,onSave:async P=>{await x(N.id,P),R()},onCancel:R,skills:a,workspaceFiles:s},N.id):y.jsx(SNe,{schedules:p,currentUserUid:m==null?void 0:m.uid,onCreate:()=>M(!0),onEdit:P=>C(P),onDelete:P=>{confirm("Delete this schedule?")&&E(P)},onToggle:_,onRunNow:H,onCancel:O,runningIds:new Set([...i,...g,...D]),onOpenRun:P=>{h(!1),n(P)}})]})]})});function INe(e,t=!0){const n=ZA(e,t),r=b.useCallback(async(i,a="GET",s)=>{try{return await Ki(`/api/owner${i}`,e,{method:a,...s!==void 0?{body:JSON.stringify(s)}:{}})}catch(l){throw console.warn(`[owner] ${a} ${i} failed: ${(l==null?void 0:l.message)??l}`),l}},[e]);return{isOwner:n,call:r}}const _8=["user","email","slack","apikey","internal","anonymous"],_r="h-7 rounded-md border border-input bg-background px-2 text-xs",Er="h-7 text-xs",Ct="text-left font-medium text-muted-foreground px-2 py-1 whitespace-nowrap",Tt="px-2 py-1 align-top",fr="text-muted-foreground hover:text-foreground disabled:opacity-40 transition-colors",Yl=e=>new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),RNe=e=>Object.entries(e).map(([t,n])=>`${t}=${Array.isArray(n)?n.join("|"):String(n)}`).join(" ");function wd(){const[e,t]=b.useState(null),[n,r]=b.useState(null);return{busy:e,error:n,run:async(a,s)=>{if(!e){t(a),r(null);try{await s()}catch(l){r((l==null?void 0:l.message)??String(l))}finally{t(null)}}}}}function rl({error:e}){if(!e)return null;const t=/^Invalid policy: (.*)$/s.exec(e);return y.jsx("div",{className:"text-xs text-destructive border border-destructive/40 rounded-md p-2",children:t?y.jsxs(y.Fragment,{children:[y.jsx("p",{className:"font-medium",children:"Invalid policy — not saved:"}),y.jsx("ul",{className:"list-disc pl-4",children:t[1].split("; ").map((n,r)=>y.jsx("li",{children:n},r))})]}):e})}function A8({value:e,onChange:t,placeholder:n}){const r=(e??[]).join(", "),[i,a]=b.useState(r);return b.useEffect(()=>a(r),[r]),y.jsx(ft,{className:Er,value:i,placeholder:n,onChange:s=>a(s.target.value),onBlur:()=>t(i.split(",").map(s=>s.trim()).filter(Boolean))})}function k8(e,t,n=[]){return{canRevoke:r=>/^(user|internal):/.test(r)&&r!=="internal:agent-internal",canBlock:r=>!n.includes(r),revoke:async r=>{confirm(`Revoke every token issued to ${r}? They must sign in again.`)&&(await e("/tokens/revoke","POST",{principalId:r}),await t())},block:async r=>{const i=prompt(`Block ${r}? Reason (optional):`);i!==null&&(await e("/blocks","POST",{match:{id:r},until:null,reason:i}),await t())}}}const PNe=[["never",0],["1 day",1],["7 days",7],["30 days",30],["90 days",90]];function DNe({call:e,roles:t}){const[n,r]=b.useState(null),[i,a]=b.useState({label:"",role:"",days:0}),[s,l]=b.useState(null),{busy:u,error:d,run:h}=wd(),m=b.useCallback(async()=>r((await e("/api-keys")).keys),[e]);b.useEffect(()=>{h("load",m)},[m]);const p=()=>h("create",async()=>{const w=await e("/api-keys","POST",{label:i.label||"Unnamed",...i.role?{role:i.role}:{},...i.days?{expiresAt:Date.now()+i.days*864e5}:{}});l(w),a({label:"",role:"",days:0}),await m()}),g=w=>navigator.clipboard.writeText(w).catch(x=>console.warn("[owner] clipboard write failed",x));return y.jsxs("div",{className:"space-y-3",children:[y.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[y.jsx(ft,{className:`${Er} w-48`,placeholder:"label",value:i.label,onChange:w=>a({...i,label:w.target.value})}),y.jsxs("select",{className:_r,value:i.role,onChange:w=>a({...i,role:w.target.value}),title:"Role cap (never above the creator)",children:[y.jsx("option",{value:"",children:"role: creator's (uncapped)"}),t.map(w=>y.jsxs("option",{value:w,children:["role cap: ",w]},w))]}),y.jsx("select",{className:_r,value:i.days,onChange:w=>a({...i,days:Number(w.target.value)}),children:PNe.map(([w,x])=>y.jsxs("option",{value:x,children:["expires: ",w]},x))}),y.jsxs(we,{size:"sm",className:"h-7 text-xs",disabled:!!u,onClick:p,children:[u==="create"?y.jsx(Yi,{className:"w-3 h-3 mr-1 animate-spin"}):y.jsx(ko,{className:"w-3 h-3 mr-1"})," Create key"]})]}),s&&y.jsxs("div",{className:"border border-amber-500/50 bg-amber-500/10 rounded-lg p-2 space-y-1",children:[y.jsxs("p",{className:"text-xs font-medium",children:['Key "',s.label,`" — copy it now, it won't be shown again:`]}),y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx("code",{className:"text-xs font-mono break-all flex-1 select-all",children:s.key}),y.jsx("button",{className:fr,title:"Copy",onClick:()=>g(s.key),children:y.jsx(Bv,{className:"w-3.5 h-3.5"})}),y.jsx(we,{size:"sm",variant:"ghost",className:"h-6 text-xs",onClick:()=>l(null),children:"Done"})]})]}),y.jsx(rl,{error:d}),y.jsx("div",{className:"border rounded-lg overflow-x-auto",children:y.jsxs("table",{className:"w-full text-xs",children:[y.jsx("thead",{className:"bg-muted/40",children:y.jsxs("tr",{children:[y.jsx("th",{className:Ct,children:"Label"}),y.jsx("th",{className:Ct,children:"Key"}),y.jsx("th",{className:Ct,children:"Creator"}),y.jsx("th",{className:Ct,children:"Role"}),y.jsx("th",{className:Ct,children:"Created"}),y.jsx("th",{className:Ct,children:"Expires"}),y.jsx("th",{className:Ct})]})}),y.jsxs("tbody",{className:"divide-y",children:[n==null?void 0:n.map(w=>{const x=w.expiresAt!==void 0&&w.expiresAt<=Date.now();return y.jsxs("tr",{className:x?"opacity-50":"",children:[y.jsx("td",{className:Tt,children:w.label}),y.jsx("td",{className:`${Tt} font-mono`,children:w.keyPreview}),y.jsx("td",{className:Tt,children:w.email}),y.jsx("td",{className:Tt,children:w.role??y.jsx("span",{className:"text-muted-foreground",children:"creator's"})}),y.jsx("td",{className:`${Tt} whitespace-nowrap`,children:Yl(w.createdAt)}),y.jsx("td",{className:`${Tt} whitespace-nowrap`,children:w.expiresAt?`${Yl(w.expiresAt)}${x?" (expired)":""}`:"never"}),y.jsx("td",{className:`${Tt} text-right`,children:y.jsx("button",{className:`${fr} hover:text-destructive`,title:"Revoke",disabled:!!u,onClick:()=>{confirm(`Revoke key "${w.label}" (${w.keyPreview})?`)&&h(`rm-${w.id}`,async()=>{await e(`/api-keys/${w.id}`,"DELETE"),await m()})},children:y.jsx(Xi,{className:"w-3.5 h-3.5"})})})]},w.id)}),n&&!n.length&&y.jsx("tr",{children:y.jsx("td",{colSpan:7,className:"text-center text-muted-foreground py-6",children:"No API keys."})})]})]})})]})}const jNe=({brokenAt:e,planted:t})=>[e&&!(e.reason==="not-regular-file"&&(t!=null&&t.length))?`chain broken at ${e.file||"audit dir"}${e.line?`:${e.line}`:""} (${e.reason})`:"",t!=null&&t.length?`planted entries (not regular files): ${t.join(", ")}`:""].filter(Boolean).join(" · ")||"chain verify failed",LNe=["auth.allow","auth.deny","role.resolve","turn.start","turn.end","tool.allow","tool.deny","guard.limit","guard.block","escalate","policy.change","policy.tamper","key.create","key.revoke","token.revoke","session.delete"],zNe=100;function $Ne({call:e,onOpenSession:t,onPolicyChange:n,ownerIds:r}){const[i,a]=b.useState({principal:"",type:"",from:"",to:""}),[s,l]=b.useState([]),[u,d]=b.useState(),[h,m]=b.useState(null),[p,g]=b.useState(new Set),{busy:w,error:x,run:E}=wd(),_=k8(e,n,r),k=(M,D,j)=>E(M,async()=>{try{await j()}catch(R){throw(R==null?void 0:R.status)!==404?R:(g(H=>new Set(H).add(D)),new Error("Conversation no longer exists"))}}),O=M=>{const D=new URLSearchParams({limit:String(zNe)});return i.principal.trim()&&D.set("principal",i.principal.trim()),i.type&&D.set("type",i.type),i.from&&D.set("from",new Date(i.from).toISOString()),i.to&&D.set("to",new Date(i.to).toISOString()),M&&D.set("cursor",M),e(`/audit?${D}`)},N=b.useCallback(()=>E("load",async()=>{const M=await O();l(M.items),d(M.nextCursor)}),[e,i]),C=()=>E("more",async()=>{const M=await O(u);l(D=>[...D,...M.items]),d(M.nextCursor)}),T=()=>E("verify",async()=>m(await e("/audit/verify")));return b.useEffect(()=>{N(),T()},[]),y.jsxs("div",{className:"space-y-2",children:[y.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[y.jsx(ft,{className:`${Er} w-56`,placeholder:"principal (exact id)",value:i.principal,onChange:M=>a({...i,principal:M.target.value}),onKeyDown:M=>M.key==="Enter"&&N()}),y.jsxs("select",{className:_r,value:i.type,onChange:M=>a({...i,type:M.target.value}),children:[y.jsx("option",{value:"",children:"all types"}),LNe.map(M=>y.jsx("option",{value:M,children:M},M))]}),y.jsx("label",{className:"text-[10px] text-muted-foreground",children:"from"}),y.jsx("input",{type:"datetime-local",className:_r,value:i.from,onChange:M=>a({...i,from:M.target.value})}),y.jsx("label",{className:"text-[10px] text-muted-foreground",children:"to"}),y.jsx("input",{type:"datetime-local",className:_r,value:i.to,onChange:M=>a({...i,to:M.target.value})}),y.jsxs(we,{size:"sm",className:"h-7 text-xs",disabled:!!w,onClick:N,children:[w==="load"?y.jsx(Yi,{className:"w-3 h-3 mr-1 animate-spin"}):y.jsx(ed,{className:"w-3 h-3 mr-1"})," Search"]}),y.jsx("div",{className:"flex-1"}),h&&y.jsxs("button",{onClick:T,title:"Re-verify the hash chain",className:`flex items-center gap-1 text-[11px] px-2 py-0.5 rounded-full border ${h.ok?"border-green-500/50 text-green-600 dark:text-green-400":"border-destructive text-destructive"}`,children:[h.ok?y.jsx(Lu,{className:"w-3.5 h-3.5"}):y.jsx(mV,{className:"w-3.5 h-3.5"}),h.ok?`chain verified · ${h.lines} lines`:jNe(h)]})]}),y.jsx(rl,{error:x}),y.jsx("div",{className:"border rounded-lg overflow-x-auto",children:y.jsxs("table",{className:"w-full text-xs",children:[y.jsx("thead",{className:"bg-muted/40",children:y.jsxs("tr",{children:[y.jsx("th",{className:Ct,children:"Time"}),y.jsx("th",{className:Ct,children:"Type"}),y.jsx("th",{className:Ct,children:"Principal"}),y.jsx("th",{className:Ct,children:"Role"}),y.jsx("th",{className:Ct,children:"Target / reason"}),y.jsx("th",{className:Ct})]})}),y.jsxs("tbody",{className:"divide-y",children:[s.map(M=>y.jsxs("tr",{children:[y.jsx("td",{className:`${Tt} whitespace-nowrap`,title:M.ts,children:Yl(M.ts)}),y.jsx("td",{className:`${Tt} font-mono whitespace-nowrap ${/deny|block|tamper/.test(M.type)?"text-destructive":""}`,children:M.type}),y.jsx("td",{className:`${Tt} font-mono break-all`,children:M.principal?y.jsx("button",{className:"hover:underline text-left",title:"Filter by this principal",onClick:()=>a({...i,principal:M.principal}),children:M.principal}):"—"}),y.jsx("td",{className:Tt,children:M.role??"—"}),y.jsx("td",{className:`${Tt} break-all`,children:[M.target,M.reason].filter(Boolean).join(" · ")||"—"}),y.jsxs("td",{className:`${Tt} whitespace-nowrap text-right`,children:[M.sessionId&&!p.has(M.sessionId)&&y.jsx("button",{className:`${fr} mr-2`,title:"Open session",disabled:!!w,onClick:()=>k("open",M.sessionId,()=>t(M.sessionId)),children:y.jsx(YG,{className:"w-3.5 h-3.5"})}),M.principal&&_.canRevoke(M.principal)&&y.jsx("button",{className:`${fr} mr-2`,title:"Revoke tokens",disabled:!!w,onClick:()=>E("rv",()=>_.revoke(M.principal)),children:y.jsx(uL,{className:"w-3.5 h-3.5"})}),M.principal&&_.canBlock(M.principal)&&y.jsx("button",{className:`${fr} hover:text-destructive`,title:"Block principal",disabled:!!w,onClick:()=>E("bl",()=>_.block(M.principal)),children:y.jsx(sL,{className:"w-3.5 h-3.5"})})]})]},M.hash)),!s.length&&w!=="load"&&y.jsx("tr",{children:y.jsx("td",{colSpan:6,className:"text-center text-muted-foreground py-6",children:"No audit records match."})})]})]})}),u&&y.jsxs(we,{size:"sm",variant:"outline",className:"h-7 text-xs",disabled:!!w,onClick:C,children:[w==="more"&&y.jsx(Yi,{className:"w-3 h-3 mr-1 animate-spin"})," Load older"]})]})}const hu=e=>{const{blocklist:t,tokensValidAfter:n,...r}=e;return JSON.stringify(r)};function O8(e,t,n){const[r,i]=b.useState(e),[a,s]=b.useState(()=>structuredClone(e.policy)),l=hu(a)!==hu(r.policy);b.useEffect(()=>{!l||hu(e.policy)===hu(a)?(i(e),s(structuredClone(e.policy))):hu(e.policy)===hu(r.policy)&&i(e)},[e]),b.useEffect(()=>{n==null||n(l)},[l,n]),b.useEffect(()=>()=>n==null?void 0:n(!1),[n]);const u=wd(),d=y.jsxs("div",{className:"flex items-center gap-2 sticky -bottom-3 z-10 -mx-3 -mb-3 px-3 pt-2 pb-3 bg-background border-t",children:[y.jsxs(we,{size:"sm",className:"h-7 text-xs",disabled:!l||!!u.busy,onClick:()=>u.run("save",()=>t(a,r.version)),children:[u.busy?y.jsx(Yi,{className:"w-3 h-3 mr-1 animate-spin"}):y.jsx(Wi,{className:"w-3 h-3 mr-1"})," Save policy"]}),y.jsxs(we,{size:"sm",variant:"ghost",className:"h-7 text-xs",disabled:!l,onClick:()=>{i(e),s(structuredClone(e.policy))},children:[y.jsx(bV,{className:"w-3 h-3 mr-1"})," Discard"]}),l&&y.jsx("span",{className:"text-[10px] text-amber-500",children:"unsaved changes"})]});return{draft:a,setDraft:s,error:u.error,saveBar:d}}function BNe({doc:e,save:t,onDirty:n}){const{draft:r,setDraft:i,error:a,saveBar:s}=O8(e,t,n),[l,u]=b.useState(""),[d,h]=b.useState(""),m=Object.keys(r.profiles),p=(x,E)=>i(_=>({..._,roles:{..._.roles,[x]:{..._.roles[x],...E}}})),g=(x,E)=>i(_=>({..._,profiles:{..._.profiles,[x]:{..._.profiles[x],...E}}})),w=(x,E)=>Object.fromEntries(Object.entries(x).filter(([_])=>_!==E));return y.jsxs("div",{className:"space-y-4",children:[y.jsx(rl,{error:a}),y.jsxs("section",{className:"space-y-2",children:[y.jsx("h3",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Roles"}),y.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Owners come only from the OWNERS env; this row only picks their rank and profile."}),y.jsx("div",{className:"border rounded-lg divide-y",children:Object.entries(r.roles).sort((x,E)=>E[1].rank-x[1].rank).map(([x,E])=>y.jsxs("div",{className:"flex items-center gap-2 p-2",children:[y.jsx("span",{className:"text-sm font-medium w-28 truncate",children:x}),y.jsx("label",{className:"text-[10px] text-muted-foreground",children:"rank"}),y.jsx(ft,{type:"number",className:`${Er} w-20`,value:Number.isFinite(E.rank)?E.rank:"",onChange:_=>p(x,{rank:_.target.value===""?NaN:Number(_.target.value)})}),y.jsx("label",{className:"text-[10px] text-muted-foreground",children:"profile"}),y.jsxs("select",{className:_r,value:E.profile,onChange:_=>p(x,{profile:_.target.value}),children:[!m.includes(E.profile)&&y.jsxs("option",{value:E.profile,children:[E.profile," (missing)"]}),m.map(_=>y.jsx("option",{value:_,children:_},_))]}),y.jsx("div",{className:"flex-1"}),x!=="owner"&&y.jsx("button",{className:`${fr} hover:text-destructive`,title:"Remove role",onClick:()=>i(_=>({..._,roles:w(_.roles,x)})),children:y.jsx(Xi,{className:"w-3.5 h-3.5"})})]},x))}),y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx(ft,{className:`${Er} w-40`,placeholder:"new role name",value:l,onChange:x=>u(x.target.value.trim())}),y.jsxs(we,{size:"sm",variant:"outline",className:"h-7 text-xs",disabled:!l||l in r.roles,onClick:()=>{i(x=>({...x,roles:{...x.roles,[l]:{rank:10,profile:m.includes("none")?"none":m[0]}}})),u("")},children:[y.jsx(ko,{className:"w-3 h-3 mr-1"})," Add role"]}),y.jsx("div",{className:"flex-1"}),y.jsx("label",{className:"text-[10px] text-muted-foreground",children:"default role"}),y.jsx("select",{className:_r,value:r.default,onChange:x=>i(E=>({...E,default:x.target.value})),children:Object.keys(r.roles).filter(x=>x!=="owner").map(x=>y.jsx("option",{value:x,children:x},x))})]})]}),y.jsxs("section",{className:"space-y-2",children:[y.jsx("h3",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Profiles"}),Object.entries(r.profiles).map(([x,E])=>y.jsxs("div",{className:"border rounded-lg p-3 space-y-2",children:[y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx("span",{className:"text-sm font-medium",children:x}),y.jsx("div",{className:"flex-1"}),y.jsx("button",{className:`${fr} hover:text-destructive`,title:"Remove profile",onClick:()=>i(_=>({..._,profiles:w(_.profiles,x)})),children:y.jsx(Xi,{className:"w-3.5 h-3.5"})})]}),y.jsxs("div",{className:"grid grid-cols-[4.5rem_1fr] gap-x-2 gap-y-1.5 items-center",children:[["tools","mcps","env"].map(_=>y.jsx(Xp,{label:_,children:y.jsx(A8,{value:E[_],onChange:k=>g(x,{[_]:k}),placeholder:'comma-separated, "*" = all'})},_)),y.jsx(Xp,{label:"rate",children:y.jsx(ft,{className:`${Er} w-28`,value:E.rate,placeholder:"120/h",onChange:_=>g(x,{rate:_.target.value.trim()})})}),y.jsx(Xp,{label:"readScope",children:y.jsx("select",{className:`${_r} w-28`,value:E.readScope,onChange:_=>g(x,{readScope:_.target.value}),children:["all","own","none"].map(_=>y.jsx("option",{value:_,children:_},_))})}),y.jsx(Xp,{label:"outbound",children:y.jsx("input",{type:"checkbox",className:"h-4 w-4 justify-self-start",checked:E.outbound,onChange:_=>g(x,{outbound:_.target.checked})})})]})]},x)),y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx(ft,{className:`${Er} w-40`,placeholder:"new profile name",value:d,onChange:x=>h(x.target.value.trim())}),y.jsxs(we,{size:"sm",variant:"outline",className:"h-7 text-xs",disabled:!d||d in r.profiles,onClick:()=>{i(x=>({...x,profiles:{...x.profiles,[d]:{tools:[],mcps:[],env:[],outbound:!1,readScope:"none",rate:"0"}}})),h("")},children:[y.jsx(ko,{className:"w-3 h-3 mr-1"})," Add profile"]})]})]}),s]})}function Xp({label:e,children:t}){return y.jsxs(y.Fragment,{children:[y.jsx("label",{className:"text-[11px] text-muted-foreground",children:e}),t]})}const UNe=new Set(["kind","id","emailIn","domain","verified"]);function FNe({doc:e,save:t,call:n,onDirty:r}){const{draft:i,setDraft:a,error:s,saveBar:l}=O8(e,t,r),u=Object.keys(i.roles).filter(p=>p!=="owner"),d=p=>a(g=>({...g,bindings:p([...g.bindings])})),h=(p,g,w)=>d(x=>{const E={...x[p].match};return w===void 0||w===""||Array.isArray(w)&&!w.length?delete E[g]:E[g]=w,x[p]={...x[p],match:E},x}),m=(p,g)=>d(w=>{const[x]=w.splice(p,1);return w.splice(g,0,x),w});return y.jsxs("div",{className:"space-y-4",children:[y.jsx(rl,{error:s}),y.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Ordered — the first matching binding decides the role; no match → default role ",y.jsx("b",{children:i.default}),"."]}),y.jsxs("div",{className:"space-y-2",children:[i.bindings.map((p,g)=>{const w=Object.entries(p.match).filter(([x])=>!UNe.has(x));return y.jsxs("div",{className:"border rounded-lg p-2 space-y-1.5",children:[y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsxs("span",{className:"text-[10px] font-mono text-muted-foreground w-5",children:["#",g+1]}),y.jsx("label",{className:"text-[10px] text-muted-foreground",children:"role"}),y.jsxs("select",{className:_r,value:p.role,onChange:x=>d(E=>(E[g]={...E[g],role:x.target.value},E)),children:[!u.includes(p.role)&&y.jsxs("option",{value:p.role,children:[p.role," (invalid)"]}),u.map(x=>y.jsx("option",{value:x,children:x},x))]}),y.jsx("div",{className:"flex-1"}),y.jsx("button",{className:fr,title:"Move up",disabled:g===0,onClick:()=>m(g,g-1),children:y.jsx(KG,{className:"w-3.5 h-3.5"})}),y.jsx("button",{className:fr,title:"Move down",disabled:g===i.bindings.length-1,onClick:()=>m(g,g+1),children:y.jsx(HG,{className:"w-3.5 h-3.5"})}),y.jsx("button",{className:`${fr} hover:text-destructive`,title:"Remove",onClick:()=>d(x=>x.filter((E,_)=>_!==g)),children:y.jsx(Xi,{className:"w-3.5 h-3.5"})})]}),y.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[y.jsxs("select",{className:_r,title:"kind",value:p.match.kind??"",onChange:x=>h(g,"kind",x.target.value),children:[y.jsx("option",{value:"",children:"any kind"}),_8.map(x=>y.jsx("option",{value:x,children:x},x))]}),y.jsxs("select",{className:_r,title:"verified",value:p.match.verified===void 0?"":String(p.match.verified),onChange:x=>h(g,"verified",x.target.value===""?void 0:x.target.value==="true"),children:[y.jsx("option",{value:"",children:"verified: any"}),y.jsx("option",{value:"true",children:"verified"}),y.jsx("option",{value:"false",children:"unverified"})]}),y.jsx(ft,{className:`${Er} w-40`,placeholder:"domain",value:p.match.domain??"",onChange:x=>h(g,"domain",x.target.value.trim())}),y.jsx(ft,{className:`${Er} w-48`,placeholder:"id (e.g. slack:U123)",value:p.match.id??"",onChange:x=>h(g,"id",x.target.value.trim())}),y.jsx("div",{className:"flex-1 min-w-48",children:y.jsx(A8,{value:p.match.emailIn,onChange:x=>h(g,"emailIn",x),placeholder:"emails (comma-separated)"})})]}),w.length>0&&y.jsxs("p",{className:"text-[10px] font-mono text-muted-foreground",children:["also matches: ",JSON.stringify(Object.fromEntries(w))]})]},g)}),y.jsxs(we,{size:"sm",variant:"outline",className:"h-7 text-xs",disabled:!u.length,onClick:()=>d(p=>[...p,{match:{kind:"user"},role:u.includes("guest")?"guest":u[u.length-1]}]),children:[y.jsx(ko,{className:"w-3 h-3 mr-1"})," Add binding"]})]}),l,y.jsx(HNe,{call:n})]})}function HNe({call:e}){const[t,n]=b.useState({kind:"user",email:"",id:"",verified:!0,lane:"",role:""}),[r,i]=b.useState(null),{busy:a,error:s,run:l}=wd(),u=h=>{n(m=>({...m,...h})),i(null)},d=()=>l("test",async()=>{i(await e("/policy/test","POST",{kind:t.kind,verified:t.verified,...t.email?{email:t.email}:{},...t.id?{id:t.id}:{},...t.lane?{lane:t.lane}:{},...t.role?{role:t.role}:{}}))});return y.jsxs("section",{className:"border rounded-lg p-3 space-y-2 bg-muted/20",children:[y.jsxs("h3",{className:"text-xs font-medium flex items-center gap-1.5",children:[y.jsx(QG,{className:"w-3.5 h-3.5"})," Test a principal ",y.jsx("span",{className:"text-muted-foreground font-normal",children:"(against the SAVED policy)"})]}),y.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[y.jsx("select",{className:_r,value:t.kind,onChange:h=>u({kind:h.target.value}),children:_8.map(h=>y.jsx("option",{value:h,children:h},h))}),y.jsx(ft,{className:`${Er} w-52`,placeholder:t.kind==="apikey"?"creator email":"email",value:t.email,onChange:h=>u({email:h.target.value.trim()})}),y.jsx(ft,{className:`${Er} w-32`,placeholder:"id (optional)",value:t.id,onChange:h=>u({id:h.target.value.trim()})}),t.kind==="internal"&&y.jsx(ft,{className:`${Er} w-28`,placeholder:"lane",value:t.lane,onChange:h=>u({lane:h.target.value.trim()})}),t.kind==="apikey"&&y.jsx(ft,{className:`${Er} w-28`,placeholder:"key role cap",value:t.role,onChange:h=>u({role:h.target.value.trim()})}),y.jsxs("label",{className:"flex items-center gap-1 text-xs",children:[y.jsx("input",{type:"checkbox",checked:t.verified,onChange:h=>u({verified:h.target.checked})})," verified"]}),y.jsxs(we,{size:"sm",className:"h-7 text-xs",disabled:!!a,onClick:d,children:[a&&y.jsx(Yi,{className:"w-3 h-3 mr-1 animate-spin"})," Resolve"]})]}),y.jsx(rl,{error:s}),r&&y.jsxs("p",{className:"text-xs font-mono",children:[r.principal," → role ",y.jsx("b",{children:r.role})," · rank ",r.rank," · profile ",y.jsx("b",{children:r.profile}),r.blocked&&y.jsxs("span",{className:"text-destructive",children:[" · BLOCKED",r.blocked.reason?` (${r.blocked.reason})`:""]})]})]})}const KNe=[["permanent",0],["1 hour",3600],["24 hours",86400],["7 days",604800],["30 days",2592e3]];function qNe({call:e,onPolicyChange:t}){const[n,r]=b.useState(null),[i,a]=b.useState({field:"id",value:"",ttl:0,reason:""}),{busy:s,error:l,run:u}=wd(),d=b.useCallback(async()=>r(await e("/blocks")),[e]);b.useEffect(()=>{u("load",d)},[d]);const h=()=>u("add",async()=>{const p=i.value.trim(),g=i.field==="emailIn"?{emailIn:[p]}:{[i.field]:p};await e("/blocks","POST",{match:g,until:i.ttl?Math.floor(Date.now()/1e3)+i.ttl:null,reason:i.reason}),a({...i,value:"",reason:""}),await Promise.all([d(),t()])}),m=p=>u("rm",async()=>{await e("/blocks","DELETE",p),await Promise.all([d(),t()])});return y.jsxs("div",{className:"space-y-4",children:[y.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[y.jsxs("select",{className:_r,value:i.field,onChange:p=>a({...i,field:p.target.value}),children:[y.jsx("option",{value:"id",children:"principal id"}),y.jsx("option",{value:"emailIn",children:"email"}),y.jsx("option",{value:"domain",children:"domain"})]}),y.jsx(ft,{className:`${Er} w-56`,placeholder:i.field==="id"?"user:x@y.com / slack:U123":i.field==="domain"?"spam.tld":"x@y.com",value:i.value,onChange:p=>a({...i,value:p.target.value})}),y.jsx("select",{className:_r,value:i.ttl,onChange:p=>a({...i,ttl:Number(p.target.value)}),children:KNe.map(([p,g])=>y.jsx("option",{value:g,children:p},g))}),y.jsx(ft,{className:`${Er} w-40`,placeholder:"reason",value:i.reason,onChange:p=>a({...i,reason:p.target.value})}),y.jsxs(we,{size:"sm",className:"h-7 text-xs",disabled:!!s||!i.value.trim(),onClick:h,children:[s==="add"?y.jsx(Yi,{className:"w-3 h-3 mr-1 animate-spin"}):y.jsx(ko,{className:"w-3 h-3 mr-1"})," Block"]}),y.jsx("button",{className:fr,title:"Refresh",onClick:()=>u("load",d),children:y.jsx(ed,{className:`w-3.5 h-3.5 ${s==="load"?"animate-spin":""}`})})]}),y.jsx(rl,{error:l}),y.jsxs("section",{className:"space-y-1",children:[y.jsx("h3",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Manual (policy)"}),y.jsx("div",{className:"border rounded-lg overflow-x-auto",children:y.jsxs("table",{className:"w-full text-xs",children:[y.jsx("thead",{className:"bg-muted/40",children:y.jsxs("tr",{children:[y.jsx("th",{className:Ct,children:"Match"}),y.jsx("th",{className:Ct,children:"Until"}),y.jsx("th",{className:Ct,children:"Reason"}),y.jsx("th",{className:Ct})]})}),y.jsxs("tbody",{className:"divide-y",children:[n==null?void 0:n.manual.map(p=>{const g=p.until!==null&&p.until*1e3<=Date.now();return y.jsxs("tr",{className:g?"opacity-50":"",children:[y.jsx("td",{className:`${Tt} font-mono break-all`,children:RNe(p.match)}),y.jsx("td",{className:`${Tt} whitespace-nowrap`,children:p.until===null?"permanent":`${Yl(p.until*1e3)}${g?" (expired)":""}`}),y.jsx("td",{className:Tt,children:p.reason||"—"}),y.jsx("td",{className:`${Tt} text-right`,children:y.jsx("button",{className:`${fr} hover:text-destructive`,title:"Remove",disabled:!!s,onClick:()=>m({source:"manual",index:p.index,match:p.match}),children:y.jsx(Xi,{className:"w-3.5 h-3.5"})})})]},p.index)}),n&&!n.manual.length&&y.jsx("tr",{children:y.jsx("td",{colSpan:4,className:"text-center text-muted-foreground py-4",children:"No manual blocks."})})]})]})})]}),y.jsxs("section",{className:"space-y-1",children:[y.jsx("h3",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Automatic (guard)"}),y.jsx("div",{className:"border rounded-lg overflow-x-auto",children:y.jsxs("table",{className:"w-full text-xs",children:[y.jsx("thead",{className:"bg-muted/40",children:y.jsxs("tr",{children:[y.jsx("th",{className:Ct,children:"Key"}),y.jsx("th",{className:Ct,children:"Since"}),y.jsx("th",{className:Ct,children:"Until"}),y.jsx("th",{className:Ct,children:"Reason"}),y.jsx("th",{className:Ct})]})}),y.jsxs("tbody",{className:"divide-y",children:[n==null?void 0:n.auto.map(p=>y.jsxs("tr",{children:[y.jsx("td",{className:`${Tt} font-mono break-all`,children:p.key}),y.jsx("td",{className:`${Tt} whitespace-nowrap`,children:Yl(p.at)}),y.jsx("td",{className:`${Tt} whitespace-nowrap`,children:Yl(p.until)}),y.jsx("td",{className:Tt,children:p.reason}),y.jsx("td",{className:`${Tt} text-right`,children:y.jsx("button",{className:`${fr} hover:text-destructive`,title:"Clear",disabled:!!s,onClick:()=>m({source:"auto",key:p.key}),children:y.jsx(Xi,{className:"w-3.5 h-3.5"})})})]},p.key)),n&&!n.auto.length&&y.jsx("tr",{children:y.jsx("td",{colSpan:5,className:"text-center text-muted-foreground py-4",children:"No active auto-blocks."})})]})]})})]})]})}function GNe({call:e,onPolicyChange:t,ownerIds:n}){const[r,i]=b.useState(7),[a,s]=b.useState(null),{busy:l,error:u,run:d}=wd(),h=k8(e,t,n),m=b.useCallback(()=>d("load",async()=>s(await e(`/principals?days=${r}`))),[e,r]);return b.useEffect(()=>{m()},[m]),y.jsxs("div",{className:"space-y-2",children:[y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx("span",{className:"text-xs text-muted-foreground",children:"Seen in the audit, last"}),y.jsx("select",{className:_r,value:r,onChange:p=>i(Number(p.target.value)),children:[1,7,30,90].map(p=>y.jsxs("option",{value:p,children:[p," day",p>1?"s":""]},p))}),y.jsx("button",{className:fr,title:"Refresh",onClick:m,children:y.jsx(ed,{className:`w-3.5 h-3.5 ${l==="load"?"animate-spin":""}`})}),(a==null?void 0:a.truncated)&&y.jsx("span",{className:"text-[10px] text-amber-500",children:"scan capped — older activity omitted"})]}),y.jsx(rl,{error:u}),y.jsx("div",{className:"border rounded-lg overflow-x-auto",children:y.jsxs("table",{className:"w-full text-xs",children:[y.jsx("thead",{className:"bg-muted/40",children:y.jsxs("tr",{children:[y.jsx("th",{className:Ct,children:"Principal"}),y.jsx("th",{className:Ct,children:"Kind"}),y.jsx("th",{className:Ct,children:"Last role"}),y.jsx("th",{className:Ct,children:"Last seen"}),y.jsx("th",{className:Ct,children:"Turns"}),y.jsx("th",{className:Ct,title:"Includes shadow (would-deny) verdicts",children:"Denies"}),y.jsx("th",{className:Ct})]})}),y.jsxs("tbody",{className:"divide-y",children:[a==null?void 0:a.principals.map(p=>y.jsxs("tr",{children:[y.jsx("td",{className:`${Tt} font-mono break-all`,children:p.id}),y.jsx("td",{className:Tt,children:p.kind}),y.jsx("td",{className:Tt,children:p.lastRole??"—"}),y.jsx("td",{className:`${Tt} whitespace-nowrap`,children:Yl(p.lastSeen)}),y.jsx("td",{className:Tt,children:p.turns}),y.jsx("td",{className:`${Tt} ${p.denies?"text-destructive":""}`,children:p.denies}),y.jsxs("td",{className:`${Tt} whitespace-nowrap text-right`,children:[h.canRevoke(p.id)&&y.jsx("button",{className:`${fr} mr-2`,title:"Revoke tokens",disabled:!!l,onClick:()=>d(`rv-${p.id}`,()=>h.revoke(p.id)),children:y.jsx(uL,{className:"w-3.5 h-3.5"})}),h.canBlock(p.id)&&y.jsx("button",{className:`${fr} hover:text-destructive`,title:"Block",disabled:!!l,onClick:()=>d(`bl-${p.id}`,()=>h.block(p.id)),children:y.jsx(sL,{className:"w-3.5 h-3.5"})})]})]},p.id)),a&&!a.principals.length&&y.jsx("tr",{children:y.jsx("td",{colSpan:7,className:"text-center text-muted-foreground py-6",children:"No principals in this window."})})]})]})})]})}const N8=[["roles","Roles & Profiles"],["bindings","Bindings"],["principals","Principals"],["keys","API keys"],["blocks","Blocklist"],["audit","Audit"]],C8="owner-console-tab";function VNe(){try{const e=localStorage.getItem(C8);return N8.some(([t])=>t===e)?e:"roles"}catch{return"roles"}}function qD({call:e,onOpenSession:t,trigger:n}){const[r,i]=b.useState(!1),[a,s]=b.useState(VNe),[l,u]=b.useState(null),[d,h]=b.useState(null),m=b.useCallback(async()=>{try{u(await e("/policy")),h(null)}catch(k){h((k==null?void 0:k.message)??String(k))}},[e]);b.useEffect(()=>{r&&m()},[r,m]);const p=async(k,O)=>{await e("/policy","PUT",{policy:k,version:O}),await m()},[g,w]=b.useState(!1),x=()=>!g||confirm("You have unsaved policy edits. Discard them?"),E=k=>{if(!(k===a||!x())){s(k);try{localStorage.setItem(C8,k)}catch(O){console.warn("[owner] could not persist tab",O)}}},_=l?Object.keys(l.policy.roles).filter(k=>k!=="owner"):[];return y.jsxs(Oo,{open:r,onOpenChange:k=>{(k||x())&&i(k)},children:[y.jsx(rd,{asChild:!0,children:n}),y.jsxs(Na,{className:"max-w-[95vw] sm:max-w-5xl h-[85dvh] flex flex-col gap-0 p-0",children:[y.jsxs(Bs,{className:"px-4 pt-4 pb-2 border-b shrink-0",children:[y.jsxs(No,{className:"flex items-center gap-2",children:[y.jsx(Lu,{className:"w-4 h-4"})," Owner Console",y.jsx(we,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-1",title:"Reload policy",onClick:m,children:y.jsx(ed,{className:"w-3.5 h-3.5"})})]}),y.jsx("div",{className:"flex gap-1 overflow-x-auto pt-2",role:"tablist",children:N8.map(([k,O])=>y.jsx("button",{role:"tab","aria-selected":a===k,onClick:()=>E(k),className:Be("text-xs px-2.5 py-1 rounded-md whitespace-nowrap transition-colors",a===k?"bg-accent text-foreground font-medium":"text-muted-foreground hover:text-foreground"),children:O},k))})]}),y.jsxs("div",{className:"flex-1 overflow-y-auto p-3 space-y-3",children:[y.jsx(rl,{error:d}),l&&!l.valid&&y.jsx("p",{className:"text-xs text-destructive border border-destructive/40 rounded-md p-2",children:"The policy file is invalid — the server is failing closed (owners only). Saving a valid policy restores it."}),(a==="roles"||a==="bindings")&&!l&&!d&&y.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"Loading…"}),a==="roles"&&l&&y.jsx(BNe,{doc:l,save:p,onDirty:w}),a==="bindings"&&l&&y.jsx(FNe,{doc:l,save:p,call:e,onDirty:w}),a==="principals"&&y.jsx(GNe,{call:e,onPolicyChange:m,ownerIds:(l==null?void 0:l.ownerIds)??[]}),a==="keys"&&y.jsx(DNe,{call:e,roles:_}),a==="blocks"&&y.jsx(qNe,{call:e,onPolicyChange:m}),a==="audit"&&y.jsx($Ne,{call:e,onPolicyChange:m,ownerIds:(l==null?void 0:l.ownerIds)??[],onOpenSession:async k=>{await t(k),i(!1)}})]})]})]})}function T8(){const e=localStorage.getItem("dark-mode");return e!==null?e==="true":window.matchMedia("(prefers-color-scheme: dark)").matches}let Xl=typeof window<"u"?T8():!0;const AE=new Set;function M8(){document.documentElement.classList.toggle("dark",Xl),localStorage.setItem("dark-mode",String(Xl)),AE.forEach(e=>e())}typeof window<"u"&&M8();function I8(e){e!==Xl&&(Xl=e,M8())}function WNe(e){AE.add(e);const t=n=>{n.key==="dark-mode"&&I8(T8())};return window.addEventListener("storage",t),()=>{AE.delete(e),window.removeEventListener("storage",t)}}function YNe(){return{dark:b.useSyncExternalStore(WNe,()=>Xl,()=>Xl),toggle:()=>I8(!Xl)}}const GD=4;function XNe(e,t){const[n,r]=b.useState({}),[i,a]=b.useState([]),s=b.useRef(t);s.current=t;const l=b.useRef(!document.hidden),u=b.useRef(e);u.current=e,b.useEffect(()=>{const x=()=>{var k;l.current=!document.hidden,(k=u.current)==null||k.sendPresence(s.current,l.current),l.current&&s.current&&h(s.current)},E=()=>{var k;l.current=!0,(k=u.current)==null||k.sendPresence(s.current,!0),s.current&&h(s.current)},_=()=>{var k;l.current=!1,(k=u.current)==null||k.sendPresence(s.current,!1)};return document.addEventListener("visibilitychange",x),window.addEventListener("focus",E),window.addEventListener("blur",_),()=>{document.removeEventListener("visibilitychange",x),window.removeEventListener("focus",E),window.removeEventListener("blur",_)}},[]),b.useEffect(()=>{e==null||e.sendPresence(t,l.current),t&&l.current&&h(t)},[t,e]),b.useEffect(()=>{},[i.length]);const d=b.useCallback(x=>{var E,_;if(x.type==="unread"){if(s.current===x.sessionId&&l.current){(E=u.current)==null||E.markRead(x.sessionId);return}r(O=>({...O,[x.sessionId]:{count:x.count,preview:x.preview,source:x.source,title:x.title}})),a(O=>{const N=O.filter(T=>T.sessionId!==x.sessionId);return[{id:`${x.sessionId}-${Date.now()}`,sessionId:x.sessionId,preview:x.preview,title:x.title,ts:Date.now()},...N].slice(0,GD)})}if(x.type==="unread_sync"){const k={};for(const[O,N]of Object.entries(x.sessions)){if(O===s.current&&l.current){(_=u.current)==null||_.markRead(O);continue}k[O]={count:N.count,preview:N.preview,source:N.source,title:N.title}}r(k)}x.type==="unread_cleared"&&r(k=>{const O={...k};return delete O[x.sessionId],O})},[]),h=b.useCallback(x=>{var E;r(_=>{if(!_[x])return _;const k={..._};return delete k[x],k}),a(_=>_.filter(k=>k.sessionId!==x)),(E=u.current)==null||E.markRead(x)},[]),m=b.useCallback(x=>{a(E=>E.filter(_=>_.id!==x))},[]),p=b.useCallback(x=>{s.current===x.sessionId&&l.current||a(E=>{const _=E.filter(O=>O.sessionId!==x.sessionId);return[{id:`${x.sessionId}-${Date.now()}`,sessionId:x.sessionId,preview:x.preview,title:x.title,ts:Date.now()},..._].slice(0,GD)})},[]),g=Object.keys(n).length;b.useEffect(()=>{const x="Shraga";document.title=g>0?`(${g}) ${x}`:x,ZNe(g)},[g]);const w=b.useRef(0);return b.useEffect(()=>{g>w.current,w.current=g},[g]),{unreads:n,toasts:i,totalUnread:g,markRead:h,dismissToast:m,addToast:p,handleUnreadEvent:d}}let mu=null,Mw=null;function ZNe(e){if(typeof document>"u")return;if(!Mw){const n=document.querySelector('link[rel="icon"]');Mw=(n==null?void 0:n.href)??""}if(e===0){VD(Mw||"");return}mu||(mu=document.createElement("canvas"),mu.width=32,mu.height=32);const t=mu.getContext("2d");t&&(t.clearRect(0,0,32,32),t.fillStyle="#6366f1",t.beginPath(),t.arc(16,16,14,0,Math.PI*2),t.fill(),t.fillStyle="#ef4444",t.beginPath(),t.arc(24,8,8,0,Math.PI*2),t.fill(),t.fillStyle="#fff",t.font="bold 10px sans-serif",t.textAlign="center",t.textBaseline="middle",t.fillText(e>9?"9+":String(e),24,8),VD(mu.toDataURL()))}function VD(e){let t=document.querySelector('link[rel="icon"]');t||(t=document.createElement("link"),t.rel="icon",document.head.appendChild(t)),t.href!==e&&(t.href=e)}function QNe({toasts:e,onDismiss:t,onOpen:n}){return e.length===0?null:y.jsx("div",{className:"fixed bottom-4 right-4 z-[100] flex flex-col-reverse gap-2 max-w-sm w-full pointer-events-none",children:e.map((r,i)=>y.jsxs("div",{className:Be("pointer-events-auto bg-white dark:bg-zinc-800 border border-zinc-300 dark:border-zinc-600 rounded-lg shadow-[0_8px_30px_rgb(0,0,0,0.12)] dark:shadow-[0_8px_30px_rgb(0,0,0,0.5)] p-3 pr-7 cursor-pointer relative","transform transition-all duration-300 ease-out","hover:bg-zinc-50 dark:hover:bg-zinc-700 group",i===0?"animate-in slide-in-from-bottom-2 fade-in":""),onClick:()=>{n(r.sessionId),t(r.id)},children:[y.jsx("button",{onClick:a=>{a.stopPropagation(),t(r.id)},className:"absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity p-0.5 hover:bg-muted rounded",children:y.jsx(Ql,{className:"w-3 h-3 text-muted-foreground"})}),y.jsxs("div",{className:"flex items-start gap-2.5",children:[y.jsx(Gw,{className:"w-4 h-4 mt-0.5 shrink-0 text-blue-500"}),y.jsxs("div",{className:"flex-1 min-w-0",children:[y.jsx("div",{className:"text-xs font-medium text-foreground truncate",children:r.title||`Session ${r.sessionId.slice(0,8)}`}),y.jsx("div",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-2",children:r.preview})]})]})]},r.id))})}const JNe={"wrong-backend":{icon:uV,classes:"bg-red-600 text-white border-red-700"},offline:{icon:wV,classes:"bg-red-600 text-white border-red-700"},"server-error":{icon:hV,classes:"bg-amber-500 text-amber-950 border-amber-600"},"ws-down":{icon:yV,classes:"bg-amber-500 text-amber-950 border-amber-600"}};function WD(){const[e,t]=b.useState(null);if(b.useEffect(()=>Gq(t),[]),!e)return null;const{icon:n,classes:r}=JNe[e.kind];return y.jsx("div",{role:"alert","data-testid":"backend-status-banner","data-fault-kind":e.kind,className:Be("shrink-0 border-b px-3 py-2 text-xs",r),style:{paddingTop:"max(0.5rem, env(safe-area-inset-top))"},children:y.jsxs("div",{className:"flex items-start gap-2",children:[y.jsx(n,{className:"w-4 h-4 mt-0.5 shrink-0"}),y.jsxs("div",{className:"min-w-0 flex-1",children:[y.jsx("div",{className:"font-semibold",children:e.title}),y.jsx("div",{className:"opacity-90 mt-0.5",children:e.hint}),(e.path||e.status!==void 0)&&y.jsxs("div",{className:"opacity-75 mt-0.5 font-mono text-[11px] break-all",children:[e.path??"websocket",e.status!==void 0?` → ${e.status}`:""]})]}),y.jsxs("button",{onClick:()=>window.location.reload(),className:"shrink-0 inline-flex items-center gap-1 rounded bg-white/20 hover:bg-white/30 px-2 py-1 font-semibold transition-colors",children:[y.jsx(ed,{className:"w-3 h-3"}),"Retry"]})]})})}const pu=jv.forComponent("App");function YD(){return new URLSearchParams(window.location.search).get("session")||void 0}function eCe(e){const t=new URL(window.location.href);e?t.searchParams.set("session",e):t.searchParams.delete("session");const n=t.toString()!==window.location.href;e&&n?window.history.pushState(null,"",t.toString()):window.history.replaceState(null,"",t.toString())}function tCe(){return y.jsx($G,{value:{},children:y.jsx(nCe,{})})}function nCe(){var In,vt;const e=za(),{dark:t,toggle:n}=YNe(),{user:r,token:i,getToken:a,loading:s,mode:l,needsSetup:u,loginLocal:d,registerLocal:h,logout:m}=Yj(),{isOwner:p,call:g}=INe(a,!!r),[w,x]=b.useState(()=>localStorage.getItem("shraga:sidebarOpen")!=="false"),E=b.useCallback(me=>{x(Xe=>{const en=typeof me=="function"?me(Xe):me;return localStorage.setItem("shraga:sidebarOpen",String(en)),en})},[]),[_,k]=b.useState(!1),[O,N]=b.useState({top:52,right:8}),C=b.useRef(null),T=b.useCallback(()=>{var Xe;const me=(Xe=C.current)==null?void 0:Xe.getBoundingClientRect();me&&N({top:me.bottom+4,right:Math.max(4,window.innerWidth-me.right)}),k(en=>!en)},[]),[M,D]=b.useState({}),j=b.useRef(null),[R,H]=b.useState(0),[P,G]=b.useState(0),[q,X]=b.useState(new Set),[U,K]=b.useState([]),[F,V]=b.useState([]),[$,L]=b.useState(0),[W,z]=b.useState(new Set),[ie,he]=b.useState(!1),[ge,Se]=b.useState(()=>localStorage.getItem("shraga:authorized")==="1"?!0:null),[ze,fe]=b.useState(()=>YD()),Ee=b.useCallback((me,Xe)=>fe(me),[]),Te=b.useCallback((me,Xe)=>fe(Xe),[]),de=b.useCallback((me,Xe)=>{},[]),nt=b.useCallback(()=>H(me=>me+1),[]),He=b.useRef(!1);b.useEffect(()=>{if(!i){!He.current&&localStorage.getItem("shraga:authorized")!=="1"&&Se(null);return}a().then(async me=>{var Xe,en,di;if(!me)return Se(!1);try{const gn=await fetch("/api/config",{headers:{Authorization:`Bearer ${me}`}});if(zv("/api/config",gn),gn.ok)return He.current=!0,localStorage.setItem("shraga:authorized","1"),Se(!0);const Li=await gn.json().catch(()=>({}));if(gn.status===401&&((Xe=Li.error)!=null&&Xe.includes("audience")||(en=Li.error)!=null&&en.includes("aud"))){pu.warn("token audience mismatch — signing out stale session"),m();return}if(gn.status===403&&((di=Li.error)!=null&&di.toLowerCase().includes("whitelist")))return localStorage.removeItem("shraga:authorized"),Se(!1);if(He.current)return;Se(gn.status!==401&&gn.status!==403)}catch(gn){if($v("/api/config",gn),pu.warn("auth probe could not reach /api/config",gn),He.current)return;Se(!0)}})},[i,a]);const Ae=b.useCallback(()=>{i&&(L(me=>me+1),jl("/api/workspace",a).then(me=>me.json()).then(me=>V(me.entries??[])).catch(me=>pu.warn("workspace refresh failed",me)))},[i,a]),De=b.useCallback(me=>{G(Xe=>Xe+1),me.type==="schedule:run_started"?(X(Xe=>new Set(Xe).add(me.scheduleId)),nt()):me.type==="schedule:run_finished"?(X(Xe=>{const en=new Set(Xe);return en.delete(me.scheduleId),en}),nt()):me.type==="schedule:deleted"&&X(Xe=>{const en=new Set(Xe);return en.delete(me.id),en})},[nt]),Ht=b.useRef(null),un=b.useRef(null),Yn=b.useRef(null),Or=b.useRef(ze);Or.current=ze;const ji=b.useCallback(me=>{var Xe,en;if((Xe=Yn.current)==null||Xe.call(Yn,me),me.type.startsWith("schedule:")){De(me);return}switch(me.type,me.type){case"workspace_change":Ht.current||(Ht.current=setTimeout(()=>{Ht.current=null,Ae()},1e3));break;case"session_title_updated":nt();break;case"session_messages_changed":nt(),me.sessionId===Or.current&&((en=un.current)==null||en.call(un,me.sessionId));break;case"session_busy":z(di=>{const gn=new Set(di);return me.busy?gn.add(me.sessionId):gn.delete(me.sessionId),gn}),me.busy||nt();break}},[De,Ae,nt]),{socket:ir,connectionStatus:ia,authError:Gt}=Qq(i,a,ji),{unreads:Ko,toasts:oe,markRead:pe,dismissToast:$e,addToast:Je,handleUnreadEvent:mt}=XNe(ir,ze),Fn=b.useCallback(async me=>{await Ki(`/api/sessions/${encodeURIComponent(me)}/meta`,a),Ee(me),pe(me)},[a,Ee,pe]);Yn.current=mt,un.current=pe,DG({socket:ir,getToken:a,pushEnabled:ie,activeSessionId:ze,switchTo:()=>{},openSession:Ee,onForegroundMessage:me=>{var en;const Xe=typeof((en=me.data)==null?void 0:en.session)=="string"?me.data.session:void 0;Xe&&Je({sessionId:Xe,preview:me.body||"New message",title:me.title})}}),b.useEffect(()=>{jG()},[]),b.useEffect(()=>{eCe(ze),ze&&pe(ze)},[ze,pe]),b.useEffect(()=>{const me=()=>fe(YD());return window.addEventListener("popstate",me),()=>window.removeEventListener("popstate",me)},[]),b.useEffect(()=>{i&&(jl("/api/config",a).then(me=>me.json()).then(D).catch(me=>pu.warn("config load failed",me)),jl("/api/skills",a).then(me=>me.json()).then(me=>K(me.skills)).catch(me=>pu.warn("skills load failed",me)),jl("/api/features",a).then(me=>me.json()).then(me=>he(!!me.push)).catch(me=>pu.warn("features load failed",me)))},[i,a]),b.useEffect(()=>{Ae()},[Ae]);const Nr=b.useCallback(()=>{fe(void 0),window.innerWidth<640&&E(!1)},[E]),dn=b.useMemo(()=>F.filter(me=>me.type==="file").map(me=>me.path),[F]),Jt=b.useMemo(()=>({socket:ir,connectionStatus:ia,getToken:a,token:i,agentConfig:M,setAgentConfig:D,activeSessionId:ze,skills:U,workspaceFiles:dn,openSchedules:()=>{var me;return(me=j.current)==null?void 0:me.open()},markRead:pe,bumpSidebar:nt,assignSession:Te,renameTab:de,openSession:Ee}),[ir,ia,a,i,M,ze,U,dn,pe,nt,Te,de,Ee]);return s?y.jsx("div",{className:"flex h-full items-center justify-center text-muted-foreground text-sm",children:"Loading…"}):!r||!i?y.jsxs("div",{className:"flex h-full flex-col",children:[y.jsx(WD,{}),y.jsx("div",{className:"flex-1 min-h-0",children:y.jsx(zV,{mode:l,needsSetup:u,onLoginLocal:d,onRegisterLocal:h})})]}):ge===null?y.jsx("div",{className:"flex h-full items-center justify-center text-muted-foreground text-sm",children:"Verifying access…"}):!ge||Gt?y.jsx("div",{className:"flex h-full items-center justify-center bg-background",children:y.jsxs("div",{className:"flex flex-col items-center gap-4 p-8 rounded-xl border bg-card shadow-sm w-full max-w-sm text-center",children:[y.jsx("div",{className:"flex items-center justify-center w-12 h-12 rounded-full bg-destructive/10 text-destructive",children:y.jsx(ux,{className:"w-6 h-6"})}),y.jsx("h2",{className:"text-lg font-semibold",children:"Access Denied"}),y.jsx("p",{className:"text-sm text-muted-foreground",children:"Your account is not authorized to use this app."}),y.jsxs("p",{className:"text-xs text-muted-foreground",children:["Signed in as ",r.email]}),y.jsx(we,{variant:"outline",onClick:()=>m(),children:"Sign out"})]})}):window.location.pathname==="/oauth/authorize"?y.jsx($V,{getToken:a,userEmail:r.email??""}):window.location.pathname==="/cli-auth"?y.jsx(BV,{getToken:a,userEmail:r.email??""}):y.jsxs("div",{className:"flex h-full flex-col",children:[y.jsx(WD,{}),y.jsxs("div",{className:"flex flex-1 min-h-0",children:[w&&y.jsxs("div",{className:"fixed inset-0 z-50 bg-background sm:relative sm:inset-auto sm:z-auto sm:w-64 sm:shrink-0 sm:border-r flex flex-col",children:[y.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b sm:hidden",style:{paddingTop:"max(0.5rem, env(safe-area-inset-top))"},children:[y.jsx("span",{className:"text-sm font-medium",children:"Sessions"}),y.jsx(we,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>E(!1),children:y.jsx(bT,{className:"w-4 h-4"})})]}),y.jsx("div",{className:"flex-1 min-h-0",children:y.jsx(Voe,{getToken:a,activeSessionId:ze,onSelect:(me,Xe)=>{Ee(me,Xe),pe(me),window.innerWidth<640&&E(!1)},onNew:Nr,refreshKey:R,workspaceRefreshKey:$,onRefreshWorkspace:Ae,unreads:Ko,busySessions:W,socket:ir})})]}),y.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[y.jsx("header",{className:"border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60",style:{paddingTop:"env(safe-area-inset-top)"},children:y.jsxs("div",{className:"flex items-center gap-1.5 sm:gap-2 px-2 sm:px-3 py-1.5",children:[y.jsx(we,{variant:"ghost",size:"icon",className:"h-9 w-9 sm:h-8 sm:w-8 shrink-0",onClick:()=>E(!w),title:"Toggle sidebar",children:w?y.jsx(bT,{className:"w-4 h-4"}):y.jsx(sV,{className:"w-4 h-4"})}),y.jsx(we,{variant:"ghost",size:"icon",className:"h-9 w-9 sm:h-8 sm:w-8 shrink-0",onClick:Nr,title:"New chat (⌘N)",children:y.jsx(gV,{className:"w-4 h-4"})}),y.jsx("div",{className:"flex-1"}),y.jsxs("div",{className:"hidden sm:flex items-center gap-0.5 shrink-0",children:[y.jsx(we,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:n,title:t?"Light mode":"Dark mode",children:t?y.jsx(wT,{className:"w-4 h-4"}):y.jsx(yT,{className:"w-4 h-4"})}),(In=e.headerActions)==null?void 0:In.call(e),p&&y.jsx(qD,{call:g,onOpenSession:Fn,trigger:y.jsx(we,{variant:"ghost",size:"icon",className:"h-8 w-8",title:"Owner Console",children:y.jsx(Lu,{className:"w-4 h-4"})})}),y.jsx(DD,{getToken:a}),y.jsx(zD,{getToken:a,onSkillsChange:K}),y.jsx(BD,{getToken:a}),y.jsx(KD,{ref:j,getToken:a,refreshKey:P,runningIds:q,onOpenSession:me=>Ee(me),skills:U,workspaceFiles:dn}),y.jsx(we,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>m(),title:"Sign out",children:y.jsx(ux,{className:"w-4 h-4"})})]}),y.jsxs("div",{className:"relative sm:hidden shrink-0",children:[y.jsx(we,{ref:C,variant:"ghost",size:"icon",className:"h-9 w-9",onClick:T,children:y.jsx(WG,{className:"w-4 h-4"})}),_&&La.createPortal(y.jsxs(y.Fragment,{children:[y.jsx("div",{className:"fixed inset-0 z-[1090] cursor-pointer",onClick:()=>k(!1)}),y.jsxs("div",{className:"fixed z-[1100] border rounded-lg shadow-lg p-1 min-w-[170px] bg-white dark:bg-zinc-900 whitespace-nowrap",style:{top:O.top,right:O.right},children:[(vt=e.headerActions)==null?void 0:vt.call(e),p&&y.jsx(qD,{call:g,onOpenSession:Fn,trigger:y.jsxs("button",{className:"flex w-full items-center gap-2.5 rounded-md px-3 py-2.5 text-sm hover:bg-accent",children:[y.jsx(Lu,{className:"w-3.5 h-3.5"})," Owner Console"]})}),y.jsx(DD,{getToken:a,trigger:y.jsxs("button",{className:"flex w-full items-center gap-2.5 rounded-md px-3 py-2.5 text-sm hover:bg-accent",children:[y.jsx(dL,{className:"w-3.5 h-3.5"})," MCPs"]})}),y.jsx(zD,{getToken:a,onSkillsChange:K,trigger:y.jsxs("button",{className:"flex w-full items-center gap-2.5 rounded-md px-3 py-2.5 text-sm hover:bg-accent",children:[y.jsx(qw,{className:"w-3.5 h-3.5"})," Skills"]})}),y.jsx(BD,{getToken:a,trigger:y.jsxs("button",{className:"flex w-full items-center gap-2.5 rounded-md px-3 py-2.5 text-sm hover:bg-accent",children:[y.jsx(Kw,{className:"w-3.5 h-3.5"})," Modules"]})}),y.jsx(KD,{getToken:a,refreshKey:P,runningIds:q,onOpenSession:me=>Ee(me),skills:U,workspaceFiles:dn,trigger:y.jsxs("button",{className:"flex w-full items-center gap-2.5 rounded-md px-3 py-2.5 text-sm hover:bg-accent",children:[y.jsx(BE,{className:"w-3.5 h-3.5"})," Schedules"]})}),y.jsx("div",{className:"border-t my-1"}),y.jsxs("button",{className:"flex w-full items-center gap-2.5 rounded-md px-3 py-2.5 text-sm hover:bg-accent",onClick:()=>{k(!1),n()},children:[t?y.jsx(wT,{className:"w-3.5 h-3.5"}):y.jsx(yT,{className:"w-3.5 h-3.5"}),t?"Light mode":"Dark mode"]}),y.jsxs("button",{className:"flex w-full items-center gap-2.5 rounded-md px-3 py-2.5 text-sm hover:bg-accent",onClick:()=>m(),children:[y.jsx(ux,{className:"w-3.5 h-3.5"})," Sign out"]})]})]}),document.body)]})]})}),ia==="update_available"&&y.jsxs("div",{className:"flex items-center justify-center gap-3 py-2.5 px-4 bg-amber-500 dark:bg-amber-600 text-white text-sm font-medium animate-pulse",children:[y.jsx("span",{children:"A new version is available"}),y.jsx("button",{onClick:()=>window.location.reload(),className:"px-3 py-1 bg-white text-amber-700 rounded font-semibold text-xs hover:bg-amber-50 transition-colors",children:"Reload now"})]}),y.jsx(zG,{value:Jt,children:y.jsx("div",{className:"flex-1 min-h-0",children:y.jsx(lNe,{nodeId:"main",sessionId:ze},ze??"new")})})]}),y.jsx(QNe,{toasts:oe,onDismiss:$e,onOpen:me=>{Ee(me),pe(me)}})]})]})}const XD="unclaw:",rCe="shraga:";function iCe(){try{const e=Object.keys(localStorage).filter(t=>t.startsWith(XD));for(const t of e){const n=rCe+t.slice(XD.length);if(localStorage.getItem(n)===null){const r=localStorage.getItem(t);r!==null&&localStorage.setItem(n,r)}localStorage.removeItem(t)}}catch(e){console.warn("[storage] legacy key migration skipped:",e instanceof Error?e.message:String(e))}}iCe();V9.createRoot(document.getElementById("root")).render(y.jsx(b.StrictMode,{children:y.jsx(tCe,{})}));