@openscout/scout 0.2.50 → 0.2.51
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/assets/{arc.es-Bmw-NdXC.js → arc.es-CXoMwIWo.js} +1 -1
- package/dist/client/assets/{index-Dq8Oi6wM.js → index-CGoQ5qP4.js} +1 -1
- package/dist/client/index.html +1 -1
- package/dist/main.mjs +77 -17
- package/dist/pair-supervisor.mjs +5 -5
- package/dist/scout-control-plane-web.mjs +25 -19
- package/package.json +2 -2
|
@@ -137,4 +137,4 @@ ${S}`,h++;break;case"id":f=S.includes("\0")?void 0:S;break;case"retry":/^\d+$/.t
|
|
|
137
137
|
.xterm .xterm-scrollable-element > .shadow.left { display: block; top: 3px; left: 0; height: 100%; width: 3px; }
|
|
138
138
|
`;function I$(){if(typeof document>"u"||document.querySelector("[data-xterm-css]"))return;const e=document.createElement("style");e.setAttribute("data-xterm-css",""),e.textContent=z$,document.head.appendChild(e)}function L$(e){return new Promise((t,s)=>{const r=new FileReader;r.onload=()=>{const i=r.result;t(i.split(",")[1])},r.onerror=s,r.readAsDataURL(e)})}function P$({relay:e,fontSize:t=12,fontFamily:s="'JetBrains Mono', 'Hack Nerd Font', monospace",configItems:r,onOpenSettings:i,onStartService:l}){const{status:c,error:f,exitCode:p,cwd:h,setCwd:g,sendInput:v,resize:x,onData:w,connect:T,disconnect:N}=e,[A,C]=b.useState(!1),{apiBaseUrl:j}=Wl(),S=b.useRef(null),_=b.useRef(null),R=b.useRef(null),M=b.useRef(null),[O,I]=b.useState(!1),[H,F]=b.useState(!1),$=b.useRef(0);b.useEffect(()=>{const P=S.current;if(!P)return;const G=te=>{te.key===" "&&!te.metaKey&&!te.ctrlKey&&!te.altKey&&te.stopPropagation()};return P.addEventListener("keydown",G),()=>P.removeEventListener("keydown",G)},[]);const L=`${j}/api/relay/upload`,Y=b.useCallback(async P=>{try{const G=await L$(P),te=await fetch(L,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:P.name,data:G})}),{path:ee}=await te.json();return ee||null}catch(G){return console.error("File upload failed:",G),null}},[L]);b.useEffect(()=>{const P=S.current;if(!P)return;const G=async te=>{if(!te.clipboardData)return;const ee=Array.from(te.clipboardData.items).filter(ve=>ve.type.startsWith("image/"));if(ee.length!==0){te.preventDefault(),te.stopPropagation();for(const ve of ee){const he=ve.getAsFile();if(!he)continue;const pe=await Y(he);pe&&v(pe)}}};return P.addEventListener("paste",G),()=>P.removeEventListener("paste",G)},[v,Y]);const re=b.useCallback(P=>{P.preventDefault(),P.dataTransfer.dropEffect="copy"},[]),Q=b.useCallback(P=>{P.preventDefault(),$.current++,P.dataTransfer.types.includes("Files")&&F(!0)},[]),z=b.useCallback(P=>{P.preventDefault(),$.current--,$.current===0&&F(!1)},[]),Z=b.useCallback(async P=>{P.preventDefault(),$.current=0,F(!1);const G=Array.from(P.dataTransfer.files).filter(te=>te.type.startsWith("image/"));if(G.length!==0)for(const te of G){const ee=await Y(te);ee&&v(ee)}},[v,Y]);b.useEffect(()=>{let P=!1,G=null;async function te(){const[{Terminal:ee},{FitAddon:ve},he]=await Promise.all([_l(()=>import("./xterm-B-qIQCd3.js"),[]),_l(()=>import("./addon-fit-DX4qG4td.js"),[]),_l(()=>import("./addon-webgl-DCtw1yLn.js"),[]).catch(()=>null)]);if(I$(),P||!_.current)return;G=new ee({fontSize:t,fontFamily:s,theme:D$,cursorBlink:!0,cursorStyle:"bar",allowTransparency:!0,scrollback:5e3,convertEol:!1,allowProposedApi:!0});const pe=new ve;if(G.loadAddon(pe),G.open(_.current),he)try{const xe=new he.WebglAddon;xe.onContextLoss(()=>{xe.dispose()}),G.loadAddon(xe)}catch{}try{pe.fit()}catch{}R.current=G,M.current=pe,x(G.cols,G.rows),G.onData(xe=>{v(xe)}),I(!0)}return te(),()=>{P=!0,G&&(G.dispose(),R.current=null,M.current=null)}},[]),b.useEffect(()=>{const P=R.current;if(P){P.options.fontSize=t,P.options.fontFamily=s;try{M.current?.fit()}catch{}}},[t,s]),b.useEffect(()=>{if(O)return w(P=>{R.current?.write(P)}),()=>{w(()=>{})}},[O,w]),b.useEffect(()=>{const P=_.current;if(!P||!O)return;const G=new ResizeObserver(()=>{const te=M.current,ee=R.current;if(!(!te||!ee))try{te.fit(),x(ee.cols,ee.rows)}catch{}});return G.observe(P),()=>G.disconnect()},[O,x]),b.useEffect(()=>{c==="connected"&&R.current&&R.current.focus()},[c]);const B=b.useCallback(()=>{c==="connected"&&R.current&&R.current.focus()},[c]),ie=c==="error"&&f==="Relay service is not running",W=b.useCallback(async()=>{if(l){C(!0);try{await l()&&setTimeout(()=>T(),500)}finally{C(!1)}}},[l,T]);let D=null;return ie?D=d.jsxs("div",{className:"flex flex-col items-center gap-4 max-w-xs text-center px-4",children:[d.jsx("div",{className:"w-8 h-8 rounded-full bg-amber-500/10 border border-amber-500/20 flex items-center justify-center",children:d.jsx("span",{className:"text-amber-400 text-[14px]",children:"!"})}),d.jsxs("div",{children:[d.jsx("div",{className:"text-[12px] text-neutral-300 font-medium mb-1",children:"Relay service not running"}),d.jsx("div",{className:"text-[11px] text-neutral-500 leading-relaxed",children:l?"Start the relay service to open a terminal session.":"Start the relay service from the Workspace Manager."})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[l&&d.jsx("button",{type:"button",onClick:W,disabled:A,className:"text-[11px] px-4 py-1.5 rounded-full border border-emerald-500/30 text-emerald-400 hover:bg-emerald-500/10 transition-colors font-medium disabled:opacity-50",children:A?"Starting...":"Start Service"}),d.jsx("button",{type:"button",onClick:()=>T(),className:"text-[11px] px-3 py-1.5 rounded-full border border-neutral-700 text-neutral-400 hover:text-neutral-300 hover:bg-white/5 transition-colors",children:"Retry"}),i&&d.jsx("button",{type:"button",onClick:i,className:"text-[11px] px-3 py-1.5 rounded-full border border-neutral-700 text-neutral-400 hover:text-neutral-300 hover:bg-white/5 transition-colors",children:"Settings"})]})]}):c==="error"&&f?D=d.jsxs("div",{className:"flex flex-col items-center gap-3 max-w-md text-center px-4",children:[d.jsx("div",{className:"w-8 h-8 rounded-full bg-red-500/10 flex items-center justify-center",children:d.jsx("span",{className:"text-red-400 text-sm",children:"!"})}),d.jsx("span",{className:"text-red-400 text-[12px] font-medium",children:"Session failed"}),d.jsx("code",{className:"text-[11px] text-neutral-400 bg-neutral-800/80 px-3 py-2 rounded-md whitespace-pre-wrap leading-relaxed max-h-32 overflow-y-auto w-full text-left",children:f}),p!==null&&p!==0&&d.jsxs("span",{className:"text-[10px] text-neutral-600",children:["Exit code ",p]}),d.jsx("button",{type:"button",onClick:()=>T(),className:"text-[11px] px-3 py-1 rounded-full border border-cyan-500/30 text-cyan-400 hover:bg-cyan-500/10 transition-colors",children:"Retry"})]}):c==="disconnected"?D=d.jsxs("div",{className:"flex flex-col items-center gap-4 max-w-xs text-center px-4",children:[d.jsx("div",{className:"w-8 h-8 rounded-full bg-neutral-800 border border-neutral-700 flex items-center justify-center",children:d.jsx("span",{className:"text-neutral-500 text-[14px]",children:"▷"})}),d.jsxs("div",{children:[d.jsx("div",{className:"text-[12px] text-neutral-300 font-medium mb-1",children:"Terminal relay disconnected"}),d.jsx("div",{className:"text-[11px] text-neutral-500 leading-relaxed",children:"Set working directory and connect."})]}),d.jsxs("form",{className:"w-full",onSubmit:P=>{P.preventDefault(),T()},children:[d.jsx("label",{className:"text-[10px] font-mono text-neutral-500 uppercase tracking-wider mb-1 block text-left",children:"Working Directory"}),d.jsx("input",{type:"text",value:h,onChange:P=>g(P.target.value),placeholder:"~/dev/my-project",className:"w-full bg-neutral-800/80 border border-neutral-700/50 rounded px-3 py-1.5 text-[11px] font-mono text-neutral-200 placeholder:text-neutral-600 outline-none focus:border-cyan-500/40 transition-colors",spellCheck:!1,autoComplete:"off"})]}),r&&r.length>0&&d.jsx("div",{className:"w-full grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-[10px] font-mono bg-neutral-800/60 border border-neutral-700/40 rounded-md px-3 py-2",children:r.map(P=>d.jsxs("div",{className:"contents",children:[d.jsx("span",{className:"text-neutral-500",children:P.label}),d.jsx("span",{className:"text-neutral-400 truncate text-left",children:P.value})]},P.label))}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{type:"button",onClick:()=>T(),className:"text-[11px] px-4 py-1.5 rounded-full border border-cyan-500/30 text-cyan-400 hover:bg-cyan-500/10 transition-colors font-medium",children:"Connect"}),i&&d.jsx("button",{type:"button",onClick:i,className:"text-[11px] px-3 py-1.5 rounded-full border border-neutral-700 text-neutral-400 hover:text-neutral-300 hover:bg-white/5 transition-colors",children:"Settings"})]})]}):c==="connecting"&&(D=d.jsxs("div",{className:"flex flex-col items-center gap-3 text-center",children:[d.jsx("div",{className:"w-6 h-6 border-2 border-neutral-600 border-t-cyan-400 rounded-full animate-spin"}),d.jsx("span",{className:"text-[12px] text-neutral-400",children:"Connecting to relay..."}),d.jsx("button",{type:"button",onClick:()=>{N()},className:"text-[10px] px-3 py-1 rounded-full border border-neutral-700 text-neutral-500 hover:text-neutral-300 hover:bg-white/5 transition-colors",children:"Cancel"})]})),d.jsxs("div",{ref:S,className:"relative flex flex-col h-full overflow-hidden",onClick:B,onDragOver:re,onDragEnter:Q,onDragLeave:z,onDrop:Z,children:[D&&d.jsx("div",{className:"flex items-center justify-center h-full font-mono text-[12px] absolute inset-0 z-10 bg-neutral-900/90",children:D}),H&&d.jsx("div",{className:"absolute inset-0 z-20 flex items-center justify-center bg-cyan-500/10 border-2 border-dashed border-cyan-500/50 rounded pointer-events-none",children:d.jsx("span",{className:"text-cyan-400 font-mono text-sm",children:"Drop image to get path"})}),d.jsx("div",{ref:_,className:"flex-1 min-h-0 min-w-0 overflow-hidden",style:{visibility:D?"hidden":"visible",padding:"4px 8px"}})]})}function U$(e={}){const{url:t="ws://localhost:3600",systemPrompt:s,cwd:r,workspaceFiles:i,autoConnect:l=!1,sessionKey:c,orphanTTL:f,backend:p,tmuxSession:h,agent:g,provider:v,model:x}=e,w=c?`hudson.relay.${c}`:null,T=()=>{if(!w)return null;try{return localStorage.getItem(w)}catch{return null}},N=he=>{if(w)try{he?localStorage.setItem(w,he):localStorage.removeItem(w)}catch{}},[A,C]=b.useState("disconnected"),[j,S]=b.useState(null),[_,R]=b.useState(null),[M,O]=b.useState(null),[I,H]=b.useState(r||"~"),F=b.useRef(null),$=b.useRef(null),L=b.useRef({cols:80,rows:24}),Y=b.useRef(!1),re=b.useRef(I);re.current=I;const Q=b.useRef(T()),z=b.useRef(null),Z=b.useCallback(he=>{const pe=F.current;pe&&pe.readyState===WebSocket.OPEN&&pe.send(JSON.stringify(he))},[]),B=b.useCallback(()=>{$.current&&(clearTimeout($.current),$.current=null);const he=F.current;he&&(he.close(),F.current=null),Y.current=!1,C("disconnected")},[]),ie=b.useCallback(()=>{const he=re.current;return{type:"session:init",cols:L.current.cols,rows:L.current.rows,...s?{systemPrompt:s}:{},...he?{cwd:he}:{},...i?{workspaceFiles:i}:{},...f?{orphanTTL:f}:{},...p?{backend:p}:{},...h?{tmuxSession:h}:{},...g?{agent:g}:{},...v?{provider:v}:{},...x?{model:x}:{}}},[s,i,f,p,h,g,v,x]),W=b.useCallback(()=>{Y.current||(Y.current=!0,Q.current?Z({type:"session:reconnect",sessionId:Q.current,cols:L.current.cols,rows:L.current.rows}):Z(ie()))},[Z,ie]),D=b.useCallback(async()=>{F.current&&(F.current.close(),F.current=null),Y.current=!1,C("connecting"),R(null),O(null);const he=t.replace(/^ws(s?):\/\//,"http$1://");try{await fetch(`${he}/health`,{signal:AbortSignal.timeout(2e3)})}catch{C("error"),R("Relay service is not running");return}const pe=new WebSocket(t);F.current=pe,pe.onopen=()=>{W()},pe.onmessage=xe=>{try{const ke=JSON.parse(xe.data);switch(ke.type){case"session:ready":Q.current=ke.sessionId,N(ke.sessionId),S(ke.sessionId),C("connected"),R(null),O(null);break;case"session:expired":{Q.current=null,N(null),Y.current=!1,z.current&&z.current("\x1B[2J\x1B[H"),Z(ie()),Y.current=!0;break}case"session:error":C("error"),R(ke.error||"Session failed to start");break;case"terminal:data":z.current&&ke.data&&z.current(ke.data);break;case"session:exit":Q.current=null,N(null),S(null),O(ke.exitCode??null),ke.exitCode!==0?(C("error"),R(ke.reason||`Process exited with code ${ke.exitCode}`)):C("disconnected");break;case"session:detached":Q.current=null,N(null),S(null);break}}catch{}},pe.onclose=()=>{F.current=null,Y.current=!1,C(xe=>xe==="error"?xe:"disconnected")},pe.onerror=()=>{C("error"),R("Could not connect to relay")}},[t,W,Z,s,i]),P=b.useCallback(he=>{Z({type:"terminal:input",data:he})},[Z]),G=b.useCallback(he=>{Z({type:"terminal:input",data:he+"\r"})},[Z]),te=b.useCallback((he,pe)=>{L.current={cols:he,rows:pe},Y.current&&Z({type:"terminal:resize",cols:he,rows:pe})},[Z]),ee=b.useCallback(he=>{z.current=he},[]);b.useEffect(()=>(l&&D(),()=>{B()}),[]);const ve=b.useCallback(()=>{if(B(),Q.current=null,S(null),c)try{sessionStorage.removeItem(`hudson.relay.${c}`)}catch{}R(null),O(null),setTimeout(()=>D(),200)},[B,D,c]);return{status:A,sessionId:j,error:_,exitCode:M,cwd:I,setCwd:H,onData:ee,sendInput:P,sendLine:G,resize:te,connect:D,disconnect:B,restart:ve}}var Kp,vS;function $$(){if(vS)return Kp;vS=1;function e(t,s){if(typeof t!="function")throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof t}\`.`);let r,i=0;return function(...c){clearTimeout(r);const f=Date.now(),p=f-i,h=s-p;h<=0?(i=f,t.apply(this,c)):r=setTimeout(()=>{i=Date.now(),t.apply(this,c)},h)}}return Kp=e,Kp}var V$=$$();const B$=FS(V$);var _C=(e,t,s)=>{if(!t.has(e))throw TypeError("Cannot "+s)},St=(e,t,s)=>(_C(e,t,"read from private field"),s?s.call(e):t.get(e)),Ms=(e,t,s)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,s)},Vr=(e,t,s,r)=>(_C(e,t,"write to private field"),t.set(e,s),s);function Z$(e,t){return t!=null?B$(e,t):e}var os,ed,td,vl,bl,xl,Li,Qm,eg,H$=class{constructor(e=[]){Ms(this,os,void 0),Ms(this,ed,"ready"),Ms(this,td,void 0),Ms(this,vl,new Set),Ms(this,bl,new Set),Ms(this,xl,new Set),this.pushMessage=t=>{Vr(this,os,St(this,os).concat(t)),St(this,Li).call(this)},this.popMessage=()=>{Vr(this,os,St(this,os).slice(0,-1)),St(this,Li).call(this)},this.replaceMessage=(t,s)=>{Vr(this,os,[...St(this,os).slice(0,t),this.snapshot(s),...St(this,os).slice(t+1)]),St(this,Li).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,s)=>{const r=s?Z$(t,s):t;return St(this,vl).add(r),()=>{St(this,vl).delete(r)}},this["~registerStatusCallback"]=t=>(St(this,bl).add(t),()=>{St(this,bl).delete(t)}),this["~registerErrorCallback"]=t=>(St(this,xl).add(t),()=>{St(this,xl).delete(t)}),Ms(this,Li,()=>{St(this,vl).forEach(t=>t())}),Ms(this,Qm,()=>{St(this,bl).forEach(t=>t())}),Ms(this,eg,()=>{St(this,xl).forEach(t=>t())}),Vr(this,os,e)}get status(){return St(this,ed)}set status(e){Vr(this,ed,e),St(this,Qm).call(this)}get error(){return St(this,td)}set error(e){Vr(this,td,e),St(this,eg).call(this)}get messages(){return St(this,os)}set messages(e){Vr(this,os,[...e]),St(this,Li).call(this)}};os=new WeakMap;ed=new WeakMap;td=new WeakMap;vl=new WeakMap;bl=new WeakMap;xl=new WeakMap;Li=new WeakMap;Qm=new WeakMap;eg=new WeakMap;var Pi,bS=class extends _${constructor({messages:e,...t}){const s=new H$(e);super({...t,state:s}),Ms(this,Pi,void 0),this["~registerMessagesCallback"]=(r,i)=>St(this,Pi)["~registerMessagesCallback"](r,i),this["~registerStatusCallback"]=r=>St(this,Pi)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>St(this,Pi)["~registerErrorCallback"](r),Vr(this,Pi,s)}};Pi=new WeakMap;function F$({experimental_throttle:e,resume:t=!1,...s}={}){const r=b.useRef("chat"in s?{}:{onToolCall:s.onToolCall,onData:s.onData,onFinish:s.onFinish,onError:s.onError,sendAutomaticallyWhen:s.sendAutomaticallyWhen});"chat"in s||(r.current={onToolCall:s.onToolCall,onData:s.onData,onFinish:s.onFinish,onError:s.onError,sendAutomaticallyWhen:s.sendAutomaticallyWhen});const i={...s,onToolCall:x=>{var w,T;return(T=(w=r.current).onToolCall)==null?void 0:T.call(w,x)},onData:x=>{var w,T;return(T=(w=r.current).onData)==null?void 0:T.call(w,x)},onFinish:x=>{var w,T;return(T=(w=r.current).onFinish)==null?void 0:T.call(w,x)},onError:x=>{var w,T;return(T=(w=r.current).onError)==null?void 0:T.call(w,x)},sendAutomaticallyWhen:x=>{var w,T,N;return(N=(T=(w=r.current).sendAutomaticallyWhen)==null?void 0:T.call(w,x))!=null?N:!1}},l=b.useRef("chat"in s?s.chat:new bS(i));("chat"in s&&s.chat!==l.current||"id"in s&&l.current.id!==s.id)&&(l.current="chat"in s?s.chat:new bS(i));const f=b.useCallback(x=>l.current["~registerMessagesCallback"](x,e),[e,l.current.id]),p=b.useSyncExternalStore(f,()=>l.current.messages,()=>l.current.messages),h=b.useSyncExternalStore(l.current["~registerStatusCallback"],()=>l.current.status,()=>l.current.status),g=b.useSyncExternalStore(l.current["~registerErrorCallback"],()=>l.current.error,()=>l.current.error),v=b.useCallback(x=>{typeof x=="function"&&(x=x(l.current.messages)),l.current.messages=x},[l]);return b.useEffect(()=>{t&&l.current.resumeStream()},[t,l]),{id:l.current.id,messages:p,setMessages:v,sendMessage:l.current.sendMessage,regenerate:l.current.regenerate,clearError:l.current.clearError,stop:l.current.stop,error:g,resumeStream:l.current.resumeStream,status:h,addToolResult:l.current.addToolOutput,addToolOutput:l.current.addToolOutput,addToolApprovalResponse:l.current.addToolApprovalResponse}}function q$(e){try{const t=localStorage.getItem(e);if(t)return JSON.parse(t)}catch{}}function Y$(e,t){try{localStorage.setItem(e,JSON.stringify(t)),window.dispatchEvent(new CustomEvent("hudson:saved",{detail:{key:e}}))}catch{}}const G$=()=>()=>{},X$=()=>!0,K$=()=>!1;function W$(){return b.useSyncExternalStore(G$,X$,K$)}function ur(e,t){const s=W$(),[r,i]=b.useState(t),l=b.useRef(!1);if(s&&!l.current){l.current=!0;const c=q$(e);c!==void 0&&i(c)}return b.useEffect(()=>{s&&Y$(e,r)},[e,r,s]),[r,i]}function J$(e){const t={};for(const s of e.attachmentsRef.current??[])if(e.activeAttachmentsRef.current.has(s.label)){const r=s.content();r!==null&&(t[s.label.toLowerCase()]=r)}return{toolset:e.toolsetRef.current,context:{...e.contextRef.current,...t},mode:e.modeRef.current,sessionId:e.sessionIdRef.current,provider:e.providerRef.current,model:e.modelRef.current}}function Q$(e,t){e.current?.(t)}function eV(e,t){e.current?.(t)}function tV(e){const t=new Set;for(const s of e??[])if(s.role==="assistant")for(const r of s.parts??[])r&&Ha(r)&&t.add(r.toolCallId);return t}function nV({toolset:e,chatId:t,initialMessages:s,context:r,onToolCall:i,mode:l,attachments:c,provider:f,model:p,sessionId:h,onSessionIdChange:g,onFinish:v,onError:x}){const w=b.useRef(i),T=b.useRef(v),N=b.useRef(x),A=b.useRef(h??crypto.randomUUID()),[C,j]=b.useState(new Set),S=b.useCallback(B=>{j(ie=>{const W=new Set(ie);return W.has(B)?W.delete(B):W.add(B),W})},[]),[_]=ur("hudson.settings",{}),R=l??_.aiMode??"api",M=b.useRef(C),O=b.useRef(c),I=b.useRef(r),H=b.useRef(e),F=b.useRef(R),$=b.useRef(f),L=b.useRef(p);b.useEffect(()=>{w.current=i},[i]),b.useEffect(()=>{T.current=v},[v]),b.useEffect(()=>{N.current=x},[x]),b.useEffect(()=>{h&&h!==A.current&&(A.current=h)},[h]),b.useEffect(()=>{g?.(A.current)},[g]),b.useEffect(()=>{M.current=C},[C]),b.useEffect(()=>{O.current=c},[c]),b.useEffect(()=>{I.current=r},[r]),b.useEffect(()=>{H.current=e},[e]),b.useEffect(()=>{F.current=R},[R]),b.useEffect(()=>{$.current=f},[f]),b.useEffect(()=>{L.current=p},[p]);const Y=b.useMemo(()=>new AC({api:"/api/ai/chat",body:()=>J$({activeAttachmentsRef:M,attachmentsRef:O,contextRef:I,toolsetRef:H,modeRef:F,sessionIdRef:A,providerRef:$,modelRef:L})}),[]),re=F$({id:t,messages:s,transport:Y,onFinish:B=>Q$(T,B),onError:B=>eV(N,B)}),Q=b.useRef(tV(s)),z=b.useCallback(()=>{const B=crypto.randomUUID();A.current=B,g?.(B),Q.current.clear(),re.setMessages([])},[re,g]),{messages:Z}=re;return b.useEffect(()=>{if(w.current){for(const B of Z)if(B.role==="assistant"){for(const ie of B.parts??[])if(ie&&Ha(ie)){if("state"in ie&&ie.state==="input-streaming")continue;const W=ie.toolCallId;if(!Q.current.has(W)){Q.current.add(W);const D=RC(ie);w.current?.(D,ie.input??{})}}}}},[Z]),{messages:Z,sendMessage:re.sendMessage,stop:re.stop,status:re.status,setMessages:re.setMessages,clearChat:z,error:re.error,mode:R,attachments:c??[],activeAttachments:C,toggleAttachment:S}}function sV({app:e,commands:t,state:s,provider:r,model:i,onFinish:l}){const c=b.useMemo(()=>(e.intents??[]).map(h=>({commandId:h.commandId,title:h.title,description:h.description,category:h.category,keywords:h.keywords,shortcut:h.shortcut,dangerous:h.dangerous,params:h.params?.map(g=>({name:g.name,description:g.description,type:g.type,optional:g.optional,enum:g.enum}))})),[e.intents]),f=b.useMemo(()=>({appId:e.id,appName:e.name,appDescription:e.description,intents:c,state:s}),[e.id,e.name,e.description,c,s]),p=b.useCallback(h=>{const g=t.find(v=>v.id===h);if(!g){console.warn(`[useAssistant] no command for id "${h}"`);return}g.action()},[t]);return nV({toolset:"intents",context:f,provider:r,model:i,onFinish:l,onToolCall:(h,g)=>{if(h!=="dispatch")return;const v=g.commandId;typeof v=="string"&&p(v)}})}const rV="audio/ogg;codecs=opus";function aV(){return typeof MediaRecorder>"u"?void 0:["audio/ogg;codecs=opus","audio/mp4;codecs=mp4a.40.2","audio/mp4","audio/webm;codecs=opus"].find(t=>MediaRecorder.isTypeSupported(t))}function Wp(e){e?.getTracks().forEach(t=>t.stop())}function iV(e){return e.includes("wav")?"wav":e.includes("aac")||e.includes("mp4")?"aac":"opus"}function xS(e,t){return t||e.find(r=>r.type)?.type||rV}function wS(e){const t=typeof window<"u"?window.location.origin:"this origin";if(e&&typeof e=="object"&&"code"in e&&"message"in e){const s=e;if(s.code==="network_error")return{status:"unavailable",message:"Vox Companion is not reachable on 127.0.0.1:43115. Install Vox.app, or launch it if it is already installed."};if(s.code==="http_error"){const r=s.message??"";return r.includes("Origin not allowed")||r.includes("403")?{status:"error",message:`Vox rejected this origin. Allowlist ${t} in Vox settings and try again.`}:{status:"error",message:"Vox returned an error while transcribing. Check Vox and try again."}}}if(e instanceof DOMException){if(e.name==="NotAllowedError")return{status:"error",message:"Microphone access was denied."};if(e.name==="NotFoundError")return{status:"error",message:"No microphone is available."}}return e instanceof Error?{status:"error",message:e.message}:{status:"error",message:"Voice capture failed."}}async function oV(){const t=(await _l(()=>import("./index-TVkH_WDG.js"),[])).createVoxdClient();return{probe:()=>t.probe(),transcribe:({audio:s,format:r,language:i,metadata:l})=>t.transcribe({audio:s,format:r,language:i,metadata:l})}}function lV(e){const{onTranscript:t,surface:s="hudson-assistant",metadata:r,language:i="en",transcribe:l,probe:c}=e,[f,p]=b.useState("idle"),[h,g]=b.useState(null),[v,x]=b.useState(null),w=b.useRef(null),T=b.useRef(null),N=b.useRef([]),A=b.useRef(t);A.current=t;const C=b.useRef(r);C.current=r;const j=b.useRef(null),S=b.useMemo(()=>typeof MediaRecorder<"u"&&typeof navigator<"u"&&!!navigator.mediaDevices?.getUserMedia,[]),_=b.useCallback(async()=>l?{probe:c??(async()=>!0),transcribe:l}:(j.current||(j.current=await oV()),j.current),[l,c]),R=b.useCallback(async(I,H)=>{if(Wp(T.current),T.current=null,w.current=null,I.length===0){p("error"),g("No audio was captured.");return}p("transcribing"),g(null);try{const F=await _(),$=xS(I,H),Y=(await F.transcribe({audio:new Blob(I,{type:$}),format:iV($),language:i,metadata:{surface:s,...C.current}})).text.trim();if(!Y)throw new Error("Transcription returned empty text.");x(Y),p("ready"),A.current(Y)}catch(F){const $=wS(F);p($.status),g($.message)}},[_,i,s]),M=b.useCallback(async()=>{if(!(f==="recording"||f==="transcribing")){if(!S){p("error"),g("This browser cannot capture microphone audio.");return}g(null),x(null);try{if(!await(await _()).probe()){p("unavailable"),g("Vox Companion is not reachable on 127.0.0.1:43115. Install Vox.app, or launch it if it is already installed.");return}const F=await navigator.mediaDevices.getUserMedia({audio:!0}),$=aV(),L=$?new MediaRecorder(F,{mimeType:$}):new MediaRecorder(F);N.current=[],T.current=F,w.current=L,L.ondataavailable=Y=>{Y.data.size>0&&N.current.push(Y.data)},L.onerror=()=>{Wp(T.current),T.current=null,w.current=null,N.current=[],p("error"),g("Voice capture failed while recording.")},L.onstop=()=>{const Y=[...N.current];N.current=[],R(Y,xS(Y,L.mimeType||$||""))},L.start(),p("recording")}catch(I){const H=wS(I);p(H.status),g(H.message)}}},[R,_,S,f]),O=b.useCallback(()=>{const I=w.current;!I||I.state!=="recording"||(p("transcribing"),I.stop())},[]);return b.useEffect(()=>()=>{const I=w.current;if(I&&I.state==="recording")try{I.stop()}catch{}Wp(T.current),T.current=null,w.current=null,N.current=[]},[]),{status:f,error:h,lastTranscript:v,start:M,stop:O,isSupported:S}}function cV(){return typeof document>"u"?"wav":document.createElement("audio").canPlayType('audio/mp4; codecs="mp4a.40.2"')?"aac":"wav"}function uV(){const{apiBaseUrl:e}=Wl(),[t,s]=b.useState("idle"),[r,i]=b.useState(null),l=b.useRef(null),c=b.useRef(null),f=b.useRef(0),p=b.useCallback(()=>{f.current+=1;const g=l.current;g&&(g.onended=null,g.onerror=null,g.pause(),l.current=null),c.current&&(URL.revokeObjectURL(c.current),c.current=null),s(v=>v==="speaking"||v==="synthesizing"?"idle":v)},[]),h=b.useCallback(async(g,v={})=>{if(!g||!g.trim())return;const x=f.current+1;f.current=x,s("synthesizing"),i(null);try{const w=await fetch(`${e}/v1/audio/speech`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:g,provider:v.provider,model:v.model,voice:v.voice||void 0,rate:v.rate,format:cV(),metadata:v.metadata})}),T=await w.json();if(!w.ok)throw new Error(T.error||`Speech synthesis failed (${w.status}).`);const N=T.audio?.base64??T.audioBase64,A=T.audio?.mimeType??T.mimeType??"audio/wav";if(!N)throw new Error("Speech synthesis returned no audio.");if(f.current!==x)return;l.current&&(l.current.pause(),l.current=null),c.current&&(URL.revokeObjectURL(c.current),c.current=null);const C=Uint8Array.from(atob(N),R=>R.charCodeAt(0)),j=new Blob([C],{type:A}),S=URL.createObjectURL(j),_=new Audio(S);l.current=_,c.current=S,s("speaking"),_.onended=()=>{l.current===_&&(l.current=null),c.current===S&&(URL.revokeObjectURL(S),c.current=null),s(R=>R==="speaking"?"idle":R)},_.onerror=()=>{l.current===_&&(l.current=null),c.current===S&&(URL.revokeObjectURL(S),c.current=null),s("error"),i("Reply audio could not be played in this browser.")},await _.play()}catch(w){if(f.current!==x)return;p(),s("error"),i(w instanceof Error?w.message:"Reply speech failed.")}},[e,p]);return b.useEffect(()=>()=>{const g=l.current;g&&(g.onended=null,g.onerror=null,g.pause()),c.current&&URL.revokeObjectURL(c.current),l.current=null,c.current=null},[]),{status:t,error:r,speak:h,stop:p,isPlaying:t==="synthesizing"||t==="speaking"}}const dV=3,fV=6,hV=4,pV=320,mV=760,gV=480,yV={balanced:{spokenReplyStyle:"adaptive",spokenReplyLongResponse:"invite",spokenReplyCodeResponse:"summary",spokenReplyMaxChars:720}},hl=yV.balanced;function Wr(e){return e.replace(/\s+/g," ").trim()}function kC(e){return e.replace(/<think>[\s\S]*?<\/think>/g," ")}function SS(e){return Wr(e.replace(/```[\s\S]*?```/g," ").replace(/`([^`]+)`/g,"$1").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/^#{1,6}\s+/gm,"").replace(/^\s*>\s?/gm,"").replace(/^\s*[-*+]\s+/gm,"").replace(/^\s*\d+\.\s+/gm,"").replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/~~([^~]+)~~/g,"$1").replace(/\|/g," ").replace(/\n{2,}/g,`
|
|
139
139
|
`).replace(/\n/g," "))}function vV(e){return Wr(e).split(new RegExp("(?<=[.!?])\\s+")).map(t=>t.trim()).filter(Boolean)}function Jp(e,t){if(e.length<=t)return e;const s=e.slice(0,t).trim(),r=s.lastIndexOf(" ");return(r>Math.floor(t*.6)?s.slice(0,r):s).replace(/[,:; -]+$/,"").trim()}function Du(e){return e&&(/[.!?]$/.test(e)?e:`${e}.`)}function MC(e,t,s){const r=vV(e);if(r.length===0)return Du(Jp(Wr(e),s));const i=[];for(const c of r){const f=Wr([...i,c].join(" "));if(i.length>0&&f.length>s||(i.push(c),i.length>=t))break}if(i.length===0)return Du(Jp(r[0]??e,s));const l=Wr(i.join(" "));return l.length<=s?Du(l):Du(Jp(l,s))}function bV(e){return typeof e=="string"?{...hl,spokenReplyStyle:e}:{spokenReplyStyle:e.spokenReplyStyle??hl.spokenReplyStyle,spokenReplyLongResponse:e.spokenReplyLongResponse??hl.spokenReplyLongResponse,spokenReplyCodeResponse:e.spokenReplyCodeResponse??hl.spokenReplyCodeResponse,spokenReplyMaxChars:e.spokenReplyMaxChars??hl.spokenReplyMaxChars}}function xV(e){switch(e){case"full":return{maxSentences:fV,maxChars:mV};case"adaptive":return{maxSentences:hV,maxChars:gV};default:return{maxSentences:dV,maxChars:pV}}}function wV(e){const t=kC(e),s=[...t.matchAll(/```[\s\S]*?```/g)],r=[...t.matchAll(/`[^`]+`/g)],i=t.replace(/```[\s\S]*?```/g," ").replace(/`([^`]+)`/g," $1 "),l=SS(t),c=SS(i),f=s.reduce((h,g)=>h+g[0].length,0)+r.reduce((h,g)=>h+g[0].length,0),p=s.length>0||r.length>=2||f>120&&f>l.length*.18||/(const|let|function|class|interface|return|import|export)\s+/.test(t)&&/[{}();]/.test(t);return{cleaned:l,proseOnly:c,codeHeavy:p}}function yy(e,t){const{maxSentences:s,maxChars:r}=xV(t);return MC(e,s,r)}function tg(e){return MC(e,3,260)}function SV(e,t){switch(t.spokenReplyLongResponse){case"summary":return tg(e.cleaned);case"invite":{const s=tg(e.cleaned);return Wr(`${s} The full details are in the written reply. We can talk through any part you want.`)}default:return yy(e.cleaned,t.spokenReplyStyle)}}function EV(e,t){switch(t.spokenReplyCodeResponse){case"read":return yy(e.cleaned,t.spokenReplyStyle);case"mention":return"I included code in the written reply. I can walk through the implementation if you want.";default:{const s=e.proseOnly||e.cleaned,r=s?tg(s):"";return r?Wr(`${r} I also included code in the written reply. I can walk through the implementation if you want.`):"I included code in the written reply. I can walk through the implementation or focus on one piece if you want."}}}function NV(e){const t=(e.parts??[]).filter(s=>s.type==="text").map(s=>"text"in s?s.text??"":"").join("");return Wr(kC(t))}function TV(e,t){const s=bV(t),r=wV(e);return r.cleaned?r.codeHeavy&&s.spokenReplyCodeResponse!=="read"?EV(r,s):r.cleaned.length>s.spokenReplyMaxChars&&s.spokenReplyLongResponse!=="verbatim"?SV(r,s):yy(r.cleaned,s.spokenReplyStyle):""}const jV={autoSend:!0,speakReplies:!1,replyProvider:"system",replyModel:"system",replyVoice:"",replyRate:1,spokenReplyStyle:"adaptive",spokenReplyLongResponse:"invite",spokenReplyCodeResponse:"summary",spokenReplyMaxChars:720};function CV({app:e,commands:t,state:s,relayUrl:r="ws://localhost:3600",cwd:i,agent:l="pi",provider:c,model:f,backend:p="pty",tmuxSession:h,workspaceFiles:g,onOpenSettings:v,onStartService:x,voice:w,voiceEnabled:T=!0}){const[N,A]=ur(`assistant.${e.id}.mode`,"relay"),[C,j]=b.useState(""),S=b.useMemo(()=>({...jV,...w}),[w]),[_,R]=ur(`assistant.${e.id}.voice.speakReplies`,S.speakReplies),{serviceApiUrl:M}=Wl(),O=b.useMemo(()=>AV(e),[e]),I=U$({url:r,systemPrompt:O,cwd:i,workspaceFiles:g,sessionKey:`assistant-${e.id}`,backend:p,tmuxSession:h,agent:l,provider:l==="pi"?c:void 0,model:l==="pi"?f:void 0}),H=b.useCallback(async()=>{if(x)return x();try{return(await(await fetch(`${M}/api/services/execute`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serviceId:"relay",action:"start",triggeredBy:"assistant"})})).json()).success===!0}catch{return!1}},[x,M]),F=b.useMemo(()=>{const D=[{label:"Relay",value:r},{label:"Agent",value:l}];return i&&D.push({label:"CWD",value:i}),l==="pi"&&f&&D.push({label:"Model",value:f}),D},[r,l,i,f]),$=uV(),[L,Y]=b.useState("text"),re=sV({app:e,commands:t,state:s,provider:c,model:f,onFinish:({message:D,isAbort:P,isDisconnect:G,isError:te})=>{if(!T||!_||P||G||te||D.role!=="assistant")return;const ee=NV(D),ve=TV(ee,S);ve&&$.speak(ve,{provider:S.replyProvider,model:S.replyModel,voice:S.replyVoice||void 0,rate:S.replyRate,metadata:{surface:"hudson-assistant",appId:e.id,source:L}})}}),Q=lV({surface:"hudson-assistant",metadata:{appId:e.id},onTranscript:D=>{const P=[C.trim(),D].filter(Boolean).join(" ");S.autoSend&&re.status!=="streaming"&&re.status!=="submitted"?(j(""),Y("voice"),re.sendMessage({text:P})):j(P)}}),z=b.useCallback(()=>{Q.status==="recording"?Q.stop():Q.start()},[Q]),Z=e.intents?.length??0,B=T,ie=Q.status==="transcribing",W=Q.status==="recording";return d.jsxs("div",{className:"flex flex-col h-full",children:[d.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 border-b border-neutral-700/50 bg-neutral-900/50",children:[d.jsx(WS,{size:11,className:"text-cyan-400/60"}),d.jsx("span",{className:"text-[10px] font-mono uppercase tracking-wider text-neutral-500",children:"Assistant"}),d.jsxs("span",{className:"text-[10px] font-mono text-neutral-600",children:["· ",e.name]}),d.jsx("div",{className:"flex-1"}),B&&N==="chat"&&d.jsx("button",{type:"button",onClick:()=>{_&&$.stop(),R(!_)},className:`p-1 rounded transition-colors ${_?"text-cyan-300 hover:text-cyan-200":"text-neutral-500 hover:text-neutral-300"}`,title:_?"Speaker on (click to mute)":"Speaker off (click to enable)",children:$.isPlaying?d.jsx(Tx,{size:12,className:"animate-spin"}):_?d.jsx(f_,{size:12}):d.jsx(p_,{size:12})}),d.jsxs("div",{className:"flex items-center gap-1 rounded-full border border-neutral-700 p-0.5",children:[d.jsx(NS,{active:N==="relay",onClick:()=>A("relay"),children:"Relay"}),d.jsx(NS,{active:N==="chat",onClick:()=>A("chat"),children:"Chat"})]}),N==="relay"&&I.status==="connected"&&d.jsx("button",{type:"button",onClick:()=>I.restart(),className:"text-[10px] px-2 py-0.5 rounded-full border text-cyan-400 border-cyan-500/30 hover:bg-cyan-500/10 transition-colors",title:"Kill session and start fresh",children:"Restart"}),N==="relay"&&I.status==="connected"&&d.jsx("button",{type:"button",onClick:()=>I.disconnect(),className:"text-[10px] px-2 py-0.5 rounded-full border text-red-400 border-red-500/30 hover:bg-red-500/10 transition-colors",children:"Disconnect"}),N==="relay"&&I.status!=="connected"&&I.status!=="connecting"&&d.jsx("button",{type:"button",onClick:()=>I.connect(),className:"text-[10px] px-2 py-0.5 rounded-full border text-emerald-400 border-emerald-500/30 hover:bg-emerald-500/10 transition-colors",children:"Connect"})]}),d.jsx("div",{className:"flex-1 min-h-0",children:N==="relay"?d.jsx(P$,{relay:I,configItems:F,onOpenSettings:v,onStartService:H}):d.jsx(k$,{chat:re,placeholder:Z===0?`Ask about ${e.name} — no intents declared, conversation only.`:`Ask ${e.name} to do something… (${Z} intent${Z===1?"":"s"})`,inputValue:C,onInputChange:D=>{L==="voice"&&D.length===0&&Y("text"),j(D)},inputExtras:B&&Q.isSupported?d.jsx("button",{type:"button",onClick:z,disabled:ie,className:`p-1 rounded transition-colors disabled:opacity-30 ${W?"bg-red-500/15 text-red-300 hover:bg-red-500/20":"text-neutral-500 hover:text-cyan-400"}`,title:W?"Stop recording":"Record voice prompt",children:ie?d.jsx(Tx,{size:12,className:"animate-spin"}):W?d.jsx(JS,{size:11}):d.jsx(B2,{size:12})}):void 0,inputStatus:B?d.jsx(RV,{inputStatus:Q.status,inputError:Q.error,outputStatus:$.status,outputError:$.error}):void 0})})]})}function RV({inputStatus:e,inputError:t,outputStatus:s,outputError:r}){const i=ES(e)??ES(s),l=t??r;return!i&&!l?null:d.jsxs("div",{className:"flex items-center gap-2",children:[i&&d.jsx("span",{className:`text-[10px] px-2 py-0.5 rounded-full border font-mono ${i.className}`,children:i.label}),l&&d.jsx("span",{className:"text-[10px] text-neutral-500 truncate flex-1",title:l,children:l})]})}function ES(e){switch(e){case"recording":return{label:"listening",className:"border-red-500/20 bg-red-500/10 text-red-300"};case"transcribing":return{label:"transcribing",className:"border-amber-500/20 bg-amber-500/10 text-amber-300"};case"ready":return{label:"draft ready",className:"border-cyan-500/20 bg-cyan-500/10 text-cyan-300"};case"synthesizing":return{label:"voicing",className:"border-cyan-500/20 bg-cyan-500/10 text-cyan-300"};case"speaking":return{label:"speaking",className:"border-emerald-500/20 bg-emerald-500/10 text-emerald-300"};case"unavailable":return{label:"voice offline",className:"border-amber-500/20 bg-amber-500/10 text-amber-300"};case"error":return{label:"voice error",className:"border-red-500/20 bg-red-500/10 text-red-300"};default:return null}}function NS({active:e,onClick:t,children:s}){return d.jsx("button",{type:"button",onClick:t,className:`text-[10px] px-2 py-0.5 rounded-full transition-colors ${e?"bg-cyan-500/15 text-cyan-300":"text-neutral-500 hover:text-neutral-300"}`,children:s})}function AV(e){const t=[`You are working alongside the user inside the **${e.name}** Hudson app.`];e.description&&t.push(e.description);const s=e.intents??[];if(s.length>0){t.push("","## What this app can do (for context)");for(const r of s)t.push(`- ${r.title} — ${r.description}`);t.push("","These actions live inside the running app. You can describe them to the user, but you do not invoke them yourself — the user can trigger any of them via the command palette (Cmd+K).")}return t.push("","## How to behave","- Be terse. The user is in a terminal; respect their attention.","- Use your own tools (file ops, shell, etc.) freely if it helps.","- When asked to change something inside the app itself, prefer guiding the user to the matching command rather than hacking around it."),t.join(`
|
|
140
|
-
`)}function _V({app:e,assistant:t=!0}){return d.jsx(e.Provider,{children:d.jsx(kV,{app:e,assistantEnabled:t})})}function kV({app:e,assistantEnabled:t}){const{navTotalHeight:s}=iy(),r=e.hooks.useCommands(),i=e.hooks.useStatus(),l=e.hooks.useSearch?.()??null,c=e.hooks.useNavCenter?.()??null,f=e.hooks.useNavActions?.()??null,p=e.hooks.useLayoutMode?.()??e.mode,h=e.hooks.useActiveToolHint?.()??null,g=e.hooks.useTakeover?.()??null,v=g?.active===!0,x=v&&g?.dismissible===!0,w=g?.onDismiss,T=e.slots.Takeover,[N,A]=ur(`appshell.${e.id}.left`,!1),[C,j]=ur(`appshell.${e.id}.right`,!1),[S,_]=ur(`appshell.${e.id}.leftW`,260),[R,M]=ur(`appshell.${e.id}.rightW`,280),[O,I]=b.useState({x:0,y:0}),[H,F]=b.useState(1),$=b.useCallback(oe=>{I(ge=>({x:ge.x+oe.x,y:ge.y+oe.y}))},[]),L=b.useCallback(oe=>{F(oe)},[]),[Y,re]=b.useState(!1),[Q,z]=b.useState(!1),[Z,B]=ur(`appshell.${e.id}.termH`,320),ie=!!e.slots.Terminal,W=b.useMemo(()=>{const oe=[];return ie&&oe.push("terminal"),t&&oe.push("assistant"),oe},[ie,t]),D=W[0]??"terminal",[P,G]=ur(`appshell.${e.id}.drawerTab`,D),te=W.includes(P)?P:D,[ee,ve]=b.useState(!1),[he,pe]=b.useState(new Set),xe=b.useCallback(oe=>{pe(ge=>{const me=new Set(ge);return me.has(oe)?me.delete(oe):me.add(oe),me})},[]),ke=b.useCallback(oe=>ge=>{ge.preventDefault();const me=ge.clientX,Ne=oe==="left"?S:R,Te=oe==="left"?_:M,qe=oe==="left"?1:-1,nt=zt=>{const $t=(zt.clientX-me)*qe;Te(Math.max(200,Math.min(500,Ne+$t)))},Ze=()=>{document.removeEventListener("mousemove",nt),document.removeEventListener("mouseup",Ze)};document.addEventListener("mousemove",nt),document.addEventListener("mouseup",Ze)},[S,R,_,M]),fe=b.useMemo(()=>{const oe=[{id:"shell:toggle-left",label:"Toggle Left Panel",shortcut:"Cmd+[",action:()=>A(ge=>!ge)},{id:"shell:toggle-right",label:"Toggle Right Panel",shortcut:"Cmd+]",action:()=>j(ge=>!ge)},{id:"shell:toggle-terminal",label:"Toggle Terminal",shortcut:"Ctrl+`",action:()=>re(ge=>!ge)}];return t&&oe.push({id:"shell:toggle-assistant",label:"Toggle Assistant",shortcut:"Cmd+J",action:()=>{G("assistant"),re(ge=>!ge||P!=="assistant")}}),oe},[A,j,t,P,G]),Me=b.useMemo(()=>[...r,...fe],[r,fe]);b.useEffect(()=>{const oe=ge=>{v||((ge.metaKey||ge.ctrlKey)&&ge.key==="k"&&(ge.preventDefault(),ve(!0)),(ge.metaKey||ge.ctrlKey)&&ge.key==="["&&(ge.preventDefault(),A(me=>!me)),(ge.metaKey||ge.ctrlKey)&&ge.key==="]"&&(ge.preventDefault(),j(me=>!me)),ge.ctrlKey&&ge.key==="`"&&(ge.preventDefault(),re(me=>!me)),t&&(ge.metaKey||ge.ctrlKey)&&ge.key==="j"&&(ge.preventDefault(),G("assistant"),re(me=>!(me&&te==="assistant"))))};return window.addEventListener("keydown",oe),()=>window.removeEventListener("keydown",oe)},[A,j,t,te,G,v]);const Ee=e.slots.Inspector,He=e.slots.RightPanel,ae=e.tools&&e.tools.length>0,se=d.jsxs(d.Fragment,{children:[Ee&&d.jsx(Ee,{}),!Ee&&He&&d.jsx(He,{}),ae&&d.jsx("div",{className:"border-t border-neutral-700/50",children:e.tools.map(oe=>{const ge=he.has(oe.id);return d.jsxs("div",{children:[d.jsxs("button",{onClick:()=>xe(oe.id),className:`w-full flex items-center gap-2 px-4 py-2.5 text-[11px] font-mono tracking-wider uppercase transition-colors hover:bg-white/5 ${h===oe.id?"text-emerald-400":"text-neutral-300"}`,children:[ge?d.jsx(R2,{size:10}):d.jsx(_2,{size:10}),d.jsx("span",{className:"text-neutral-400",children:oe.icon}),d.jsx("span",{className:"font-bold",children:oe.name})]}),ge&&d.jsx("div",{className:"px-4 pb-3",children:d.jsx(oe.Component,{})})]},oe.id)})})]}),ye=d.jsxs(d.Fragment,{children:[e.slots.LeftFooter&&d.jsx(e.slots.LeftFooter,{}),d.jsx(cL,{onOpenCommandPalette:()=>ve(!0)})]}),Se=b.useRef(null),we=b.useRef(null);b.useEffect(()=>{const oe=Se.current;oe&&(v?oe.setAttribute("inert",""):oe.removeAttribute("inert"))},[v]),b.useEffect(()=>{if(!v)return;const oe=we.current;if(oe&&(oe.querySelector('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])')??oe).focus(),!x)return;const ge=me=>{me.key==="Escape"&&(me.preventDefault(),w?.())};return window.addEventListener("keydown",ge),()=>window.removeEventListener("keydown",ge)},[v,x,w]);const Re=p==="panel"?{position:"absolute",top:s,bottom:28,left:N?0:S,right:C?0:R,overflow:"auto",transition:"left 200ms ease, right 200ms ease"}:{};return d.jsxs(d.Fragment,{children:[d.jsx("div",{ref:Se,"aria-hidden":v?!0:void 0,style:{display:"contents"},children:d.jsx(nL,{mode:p,panOffset:O,scale:H,onPan:$,onZoom:L,hud:d.jsxs(d.Fragment,{children:[d.jsx(iL,{title:e.name.toUpperCase(),search:l??void 0,center:c,actions:f}),d.jsx(R1,{side:"left",title:e.leftPanel?.title??"Navigation",icon:e.leftPanel?.icon,isCollapsed:N,onToggleCollapse:()=>A(!N),width:S,onResizeStart:ke("left"),footer:ye,headerActions:e.leftPanel?.headerActions&&d.jsx(e.leftPanel.headerActions,{}),children:e.slots.LeftPanel&&d.jsx(e.slots.LeftPanel,{})}),d.jsx(R1,{side:"right",title:e.rightPanel?.title??"Inspector",icon:e.rightPanel?.icon,isCollapsed:C,onToggleCollapse:()=>j(!C),width:R,onResizeStart:ke("right"),headerActions:e.rightPanel?.headerActions&&d.jsx(e.rightPanel.headerActions,{}),children:se}),d.jsx(lL,{status:i,onToggleTerminal:()=>re(oe=>!oe),isTerminalOpen:Y}),d.jsx("div",{className:"pointer-events-none",style:{position:"fixed",left:N?0:S,right:C?0:R,bottom:0,top:0,zIndex:45,transition:"left 200ms ease, right 200ms ease",transform:"translateZ(0)"},children:d.jsxs(dL,{isOpen:Y,onClose:()=>re(!1),onToggleMaximize:()=>z(oe=>!oe),isMaximized:Q,height:Z,onHeightChange:B,title:d.jsx(MV,{tabs:W,active:te,onSelect:G}),children:[te==="terminal"&&(e.slots.Terminal?d.jsx(e.slots.Terminal,{}):d.jsx("div",{className:"p-4 font-mono text-[12px] text-neutral-400",children:"No terminal content"})),te==="assistant"&&d.jsx(CV,{app:e,commands:r})]})}),d.jsx(uL,{isOpen:ee,onClose:()=>ve(!1),commands:Me})]}),children:d.jsx("div",{style:Re,className:"frame-scrollbar",children:d.jsx(e.slots.Content,{})})})}),v&&T?d.jsx("div",{ref:we,tabIndex:-1,role:"dialog","aria-modal":"true",style:{position:"fixed",inset:0,zIndex:80,outline:"none"},children:d.jsx(T,{})}):null]})}function MV({tabs:e,active:t,onSelect:s}){return e.length===0?null:d.jsx("div",{className:"flex items-center gap-0.5",children:e.map(r=>{const i=r===t,l=r==="terminal"?QS:WS,c=r==="terminal"?"TERMINAL":"ASSISTANT",f=r==="terminal"?"text-emerald-400":"text-cyan-400";return d.jsxs("button",{type:"button",onClick:()=>s(r),className:`flex items-center gap-1.5 px-2.5 py-1 rounded text-xs font-bold tracking-widest font-mono transition-colors ${i?`${f} bg-white/[0.04]`:"text-neutral-500 hover:text-neutral-300"}`,children:[d.jsx(l,{size:13}),d.jsx("span",{children:c})]},r)})})}const OC=(...e)=>e.filter((t,s,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===s).join(" ").trim();const OV=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const DV=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,s,r)=>r?r.toUpperCase():s.toLowerCase());const TS=e=>{const t=DV(e);return t.charAt(0).toUpperCase()+t.slice(1)};var zV={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const IV=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0;return!1};const LV=b.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:s=2,absoluteStrokeWidth:r,className:i="",children:l,iconNode:c,...f},p)=>b.createElement("svg",{ref:p,...zV,width:t,height:t,stroke:e,strokeWidth:r?Number(s)*24/Number(t):s,className:OC("lucide",i),...!l&&!IV(f)&&{"aria-hidden":"true"},...f},[...c.map(([h,g])=>b.createElement(h,g)),...Array.isArray(l)?l:[l]]));const ca=(e,t)=>{const s=b.forwardRef(({className:r,...i},l)=>b.createElement(LV,{ref:l,iconNode:t,className:OC(`lucide-${OV(TS(e))}`,`lucide-${e}`,r),...i}));return s.displayName=TS(e),s};const PV=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],UV=ca("activity",PV);const $V=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"r6nss1"}]],VV=ca("house",$V);const BV=[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]],ZV=ca("layers",BV);const HV=[["path",{d:"M16 10a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 14.286V4a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z",key:"1n2ejm"}],["path",{d:"M20 9a2 2 0 0 1 2 2v10.286a.71.71 0 0 1-1.212.502l-2.202-2.202A2 2 0 0 0 17.172 19H10a2 2 0 0 1-2-2v-1",key:"1qfcsi"}]],FV=ca("messages-square",HV);const qV=[["rect",{x:"16",y:"16",width:"6",height:"6",rx:"1",key:"4q2zg0"}],["rect",{x:"2",y:"16",width:"6",height:"6",rx:"1",key:"8cvhb9"}],["rect",{x:"9",y:"2",width:"6",height:"6",rx:"1",key:"1egb70"}],["path",{d:"M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3",key:"1jsf9p"}],["path",{d:"M12 12V8",key:"2874zd"}]],YV=ca("network",qV);const GV=[["path",{d:"M16.247 7.761a6 6 0 0 1 0 8.478",key:"1fwjs5"}],["path",{d:"M19.075 4.933a10 10 0 0 1 0 14.134",key:"ehdyv1"}],["path",{d:"M4.925 19.067a10 10 0 0 1 0-14.134",key:"1q22gi"}],["path",{d:"M7.753 16.239a6 6 0 0 1 0-8.478",key:"r2q7qm"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]],XV=ca("radio",GV);const KV=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],WV=ca("settings",KV);const JV=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["path",{d:"M16 3.128a4 4 0 0 1 0 7.744",key:"16gr8j"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],QV=ca("users",JV);function Qp(){const e=window.location.pathname.replace(/^\/+/,"").split("/").filter(Boolean);return e[0]==="agent"&&e[1]?{view:"agent-info",conversationId:decodeURIComponent(e[1])}:e[0]==="agents"&&e[1]&&e[2]==="c"&&e[3]?{view:"agents",agentId:decodeURIComponent(e[1]),conversationId:decodeURIComponent(e[3])}:e[0]==="agents"&&e[1]?{view:"agents",agentId:decodeURIComponent(e[1])}:e[0]==="agents"?{view:"agents"}:e[0]==="fleet"?{view:"fleet"}:e[0]==="c"&&e[1]?{view:"conversation",conversationId:decodeURIComponent(e[1])}:e[0]==="sessions"&&e[1]?{view:"sessions",sessionId:decodeURIComponent(e[1])}:e[0]==="sessions"?{view:"sessions"}:e[0]==="mesh"?{view:"mesh"}:e[0]==="activity"?{view:"activity"}:e[0]==="work"&&e[1]?{view:"work",workId:decodeURIComponent(e[1])}:e[0]==="settings"?{view:"settings"}:{view:"inbox"}}function eB(e){switch(e.view){case"inbox":return"/";case"conversation":return`/c/${encodeURIComponent(e.conversationId)}`;case"agent-info":return`/agent/${encodeURIComponent(e.conversationId)}`;case"agents":return e.agentId?e.conversationId?`/agents/${encodeURIComponent(e.agentId)}/c/${encodeURIComponent(e.conversationId)}`:`/agents/${encodeURIComponent(e.agentId)}`:"/agents";case"fleet":return"/fleet";case"sessions":return e.sessionId?`/sessions/${encodeURIComponent(e.sessionId)}`:"/sessions";case"mesh":return"/mesh";case"activity":return"/activity";case"work":return`/work/${encodeURIComponent(e.workId)}`;case"settings":return"/settings"}}function em(e){switch(e.view){case"conversation":return`conv:${e.conversationId}`;case"agent-info":return`agent-info:${e.conversationId}`;case"agents":return e.conversationId?`agent-conv:${e.conversationId}`:e.agentId?`agent:${e.agentId}`:"agents";case"sessions":return e.sessionId?`session:${e.sessionId}`:"sessions";case"work":return`work:${e.workId}`;default:return e.view}}function tB(){const[e,t]=b.useState(Qp),s=b.useRef({});b.useEffect(()=>{const i=()=>{const l=Qp();t(l),requestAnimationFrame(()=>{window.scrollTo(0,s.current[em(l)]??0)})};return window.addEventListener("popstate",i),()=>window.removeEventListener("popstate",i)},[]);const r=b.useCallback(i=>{s.current[em(Qp())]=window.scrollY,window.history.pushState(null,"",eB(i)),t(i),requestAnimationFrame(()=>{window.scrollTo(0,s.current[em(i)]??0)})},[]);return{route:e,navigate:r}}function DC(e){const t=e.match(/^dm\.operator\.(.+)$/);return t?t[1]:null}function ng(e){return`dm.operator.${e}`}async function ot(e,t){const s=await fetch(e,{...t,headers:{...t?.headers??{},...t?.body?{"content-type":"application/json"}:{}}});if(!s.ok){const i=await s.text();throw new Error(i||`HTTP ${s.status}`)}const r=await s.text();if(r)return JSON.parse(r)}const nB=["hello","node.upserted","actor.registered","agent.registered","agent.endpoint.upserted","conversation.upserted","binding.upserted","message.posted","invocation.requested","flight.updated","delivery.planned","delivery.attempted","delivery.state.changed","collaboration.upserted","collaboration.event.appended","scout.dispatched"];function sB(e){try{return JSON.parse(e)}catch{return{kind:"unknown"}}}function Kn(e){const t=b.useRef(e);t.current=e,b.useEffect(()=>{let s=null,r=null;function i(){s=new EventSource("/api/events");const l=c=>{t.current(sB(c.data))};s.onmessage=l;for(const c of nB)s.addEventListener(c,l);s.onerror=()=>{s?.close(),r=setTimeout(i,3e3)}}return i(),()=>{s?.close(),r&&clearTimeout(r)}},[])}function ws(e){return e==="working"?"working":!e||e==="offline"?"offline":"available"}function Fa(e){return ws(e)!=="offline"}function ao(e){switch(ws(e)){case"working":return"Working";case"available":return"Available";default:return"Offline"}}const zC={current:null,setMenu:null};function mo(){return b.useCallback((e,t)=>{e.preventDefault(),e.stopPropagation(),zC.setMenu?.({position:{x:e.clientX,y:e.clientY},items:t})},[])}function rB({children:e}){const[t,s]=b.useState(null),r=b.useRef(null);zC.setMenu=s;const i=b.useCallback(()=>s(null),[]);return b.useEffect(()=>{if(!t)return;const l=()=>i(),c=p=>{p.key==="Escape"&&i()},f=()=>i();return window.addEventListener("mousedown",l,!0),window.addEventListener("keydown",c),window.addEventListener("scroll",f,!0),window.addEventListener("contextmenu",i,!0),()=>{window.removeEventListener("mousedown",l,!0),window.removeEventListener("keydown",c),window.removeEventListener("scroll",f,!0),window.removeEventListener("contextmenu",i,!0)}},[t,i]),b.useEffect(()=>{if(!t||!r.current)return;const l=r.current,c=l.getBoundingClientRect(),f=window.innerWidth,p=window.innerHeight;let h=t.position.x,g=t.position.y;h+c.width>f-8&&(h=f-c.width-8),g+c.height>p-8&&(g=p-c.height-8),h<8&&(h=8),g<8&&(g=8),l.style.left=`${h}px`,l.style.top=`${g}px`},[t]),t?d.jsxs(d.Fragment,{children:[e,d.jsx("div",{ref:r,className:"s-context-menu",style:{left:t.position.x,top:t.position.y},role:"menu",onMouseDown:l=>l.stopPropagation(),children:t.items.map((l,c)=>l.kind==="separator"?d.jsx("div",{className:"s-context-menu-sep",role:"separator"},c):d.jsxs("button",{type:"button",className:"s-context-menu-item",role:"menuitem",onClick:()=>{l.onSelect(),i()},children:[d.jsx("span",{className:"s-context-menu-label",children:l.label}),l.shortcut&&d.jsx("span",{className:"s-context-menu-shortcut",children:l.shortcut})]},c))})]}):d.jsx(d.Fragment,{children:e})}const IC=b.createContext(null);function Yt(){const e=b.useContext(IC);if(!e)throw new Error("useScout must be used inside ScoutProvider");return e}function aB({children:e}){const{route:t,navigate:s}=tB(),[r,i]=b.useState([]),[l,c]=b.useState([]),[f,p]=b.useState(null),[h,g]=b.useState(!1),v=b.useCallback(()=>g(!0),[]),x=b.useCallback(async()=>{const[A,C]=await Promise.allSettled([ot("/api/agents"),ot("/api/messages")]);A.status==="fulfilled"&&i(A.value),C.status==="fulfilled"&&c(C.value)},[]),w=b.useCallback(async()=>{try{const A=await ot("/api/onboarding/state");p(A)}catch{p({hasLocalConfig:!0,hasProjectConfig:!0,hasOperatorName:!0,localConfigPath:null,projectRoot:null,currentDirectory:null,operatorName:null,operatorNameSuggestion:null})}},[]);b.useEffect(()=>{x(),w()},[x,w]),Kn(x);const T=b.useMemo(()=>r.filter(A=>Fa(A.state)).length,[r]),N=b.useMemo(()=>({route:t,navigate:s,agents:r,messages:l,onlineCount:T,reload:x,onboarding:f,refreshOnboarding:w,onboardingSkipped:h,skipOnboarding:v}),[t,s,r,l,T,x,f,w,h,v]);return d.jsx(IC.Provider,{value:N,children:d.jsx("div",{"data-scout-theme":!0,style:{"--hud-font-sans":"'Inter', ui-sans-serif, system-ui, sans-serif","--hud-font-mono":"'JetBrains Mono', ui-monospace, Menlo, monospace","--hud-font-serif":"'Spectral', Georgia, serif"},children:d.jsx(rB,{children:e})})})}const iB={ask_sent:"asked",ask_replied:"replied",ask_failed:"failed",ask_working:"working",flight_created:"task started",flight_updated:"task updated",message_sent:"sent",message_received:"received",agent_online:"online",agent_offline:"offline"};function oB(e){return iB[e]??e.replace(/_/g," ")}const jS=["#6366f1","#8b5cf6","#0ea5e9","#14b8a6","#f59e0b","#ef4444","#ec4899","#10b981"];function Ts(e){let t=0;for(let s=0;s<e.length;s++)t=(t<<5)-t+e.charCodeAt(s)|0;return jS[Math.abs(t)%jS.length]}function ec(e){switch(ws(e)){case"working":return"var(--green)";case"available":return"var(--accent)";default:return"var(--dim)"}}const lB={workspace:"workspace",worktree:"workspace",branch:"workspace",profile:"profile",persona:"profile",harness:"harness",runtime:"harness",node:"node",host:"node"};function cB(e){return e.trim().replace(/^@+/,"").replace(/[.,!?;)\]]+$/,"")}function Is(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}const uB="scout";function dB(e){return lB[Is(e)]??null}function LC(e){const t=Is(e.definitionId),s=e.workspaceQualifier?Is(e.workspaceQualifier):void 0,r=e.profile?Is(e.profile):void 0,i=e.harness?Is(e.harness):void 0,l=e.nodeQualifier?Is(e.nodeQualifier):void 0;return t?{definitionId:t,...s?{workspaceQualifier:s}:{},...r?{profile:r}:{},...i?{harness:i}:{},...l?{nodeQualifier:l}:{}}:null}function fB(e){const t=e.split(".").filter(Boolean),s=t.shift();if(!s)return null;const r={definitionId:s},i=[];for(const l of t){if(l.includes(":")){const[c,f=""]=l.split(":",2),p=dB(c),h=Is(f);if(!p||!h)return null;p==="workspace"?r.workspaceQualifier=h:p==="profile"?r.profile=h:p==="harness"?r.harness=h:p==="node"&&(r.nodeQualifier=h);continue}i.push(l)}if(i.length===1){const l=Is(i[0]);if(!l)return null;r.workspaceQualifier=l}else if(i.length===2){const l=Is(i[0]),c=Is(i[1]);if(!l||!c)return null;r.workspaceQualifier||(r.workspaceQualifier=l),r.nodeQualifier||(r.nodeQualifier=c)}else if(i.length>2)return null;return pB(r,{raw:e})}function hB(e){const t=cB(e);return!t||t.includes("@")||t.includes("#")?null:fB(t)}function CS(e,t={}){const s=LC(e);if(!s)return t.includeSigil===!1?"":"@";const i=[`${t.includeSigil===!1?"":"@"}${s.definitionId}`];return s.workspaceQualifier&&i.push(s.workspaceQualifier),s.profile&&i.push(`profile:${s.profile}`),s.harness&&i.push(`harness:${s.harness}`),s.nodeQualifier&&i.push(`node:${s.nodeQualifier}`),i.join(".")}function pB(e,t={}){const s=LC(e);return s?{raw:t.raw??CS(s,{includeSigil:!1}),label:CS(s),definitionId:s.definitionId,...s.nodeQualifier?{nodeQualifier:s.nodeQualifier}:{},...s.workspaceQualifier?{workspaceQualifier:s.workspaceQualifier}:{},...s.profile?{profile:s.profile}:{},...s.harness?{harness:s.harness}:{}}:null}function mB(e){return gB(e).parsed}function gB(e){const t=Array.from(e.matchAll(/(^|\s)@([a-z0-9][a-z0-9._/:-]*)/gi)),s=new Map,r=[];for(const i of t){const l=i[2]??"",c=hB(l);if(!c){l&&r.push(`@${l}`);continue}s.set(c.label,c)}return{parsed:Array.from(s.values()),unparsed:Array.from(new Set(r))}}function yB(e,t){if(t.length===0)return[{kind:"text",value:e}];const s=new Map;for(const c of t)s.set(c.label.toLowerCase(),c);const r=[];let i=e;const l=/@([a-z0-9][a-z0-9._/:-]*)/i;for(;i.length>0;){const c=l.exec(i);if(!c||c.index===void 0){r.push({kind:"text",value:i});break}c.index>0&&r.push({kind:"text",value:i.slice(0,c.index)});const f=c[0],p=f.toLowerCase(),h=s.get(p);h?r.push({kind:"mention",identity:h}):r.push({kind:"text",value:f}),i=i.slice(c.index+f.length)}return r}function vB(e,t){const s=[],r=/\*\*(.+?)\*\*/g;let i=0,l,c=0;for(;(l=r.exec(e))!==null;)l.index>i&&s.push(d.jsx("span",{children:e.slice(i,l.index)},`${t}-${c++}`)),s.push(d.jsx("strong",{children:l[1]},`${t}-${c++}`)),i=l.index+l[0].length;return i<e.length&&s.push(d.jsx("span",{children:e.slice(i)},`${t}-${c++}`)),s.length>0?s:[d.jsx("span",{children:e},t)]}function Yn(e){if(!e)return e??"";const t=mB(e);return yB(e,t).flatMap((r,i)=>{if(r.kind==="text")return vB(r.value,i*100);const{identity:l}=r,f=l.definitionId===uB?"var(--accent)":Ts(l.definitionId);return d.jsx("span",{className:"s-mention",style:{"--mention-color":f},children:l.label},i)})}function tt(e){const t=e<1e12?e*1e3:e,s=Math.floor((Date.now()-t)/1e3);return s<5?"now":s<60?`${s}s`:s<3600?`${Math.floor(s/60)}m`:s<86400?`${Math.floor(s/3600)}h`:`${Math.floor(s/86400)}d`}function Ia(e){return new Date(e<1e12?e*1e3:e).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit",second:"2-digit"})}const bB={"agent.registered":"registered","agent.online":"came online","agent.offline":"went offline","flight.started":"started task","flight.completed":"completed task","flight.updated":"updated task","message.sent":"sent message","message.received":"received message","collaboration.ask":"asked a question","collaboration.answer":"answered",ask_sent:"asked",ask_replied:"replied",ask_working:"working",flight_created:"started task",flight_updated:"updated task",message_sent:"sent",message_received:"received"},xB={presence:{label:"Presence",tone:"notice"},work:{label:"Execution",tone:"working"},message:{label:"Delivery",tone:"completed"},collaboration:{label:"Coordination",tone:"working"},system:{label:"System",tone:"notice"}};function PC(e){return bB[e]??e.replace(/[._]/g," ")}function wB(e){return e.startsWith("agent.")||e.includes("registered")||e.includes("online")||e.includes("offline")?"presence":e.startsWith("flight")||e.startsWith("ask_")?"work":e.startsWith("message")?"message":e.startsWith("collaboration")?"collaboration":"system"}function SB(e){return(e??"system").charAt(0).toUpperCase()}function UC(e){return e.length<=14?e:`${e.slice(0,8)}...${e.slice(-4)}`}function EB(e){if(!e)return null;const t=e.split("/").filter(Boolean);return t[t.length-1]??e}function NB(e){return`${e.actorName??"system"} ${PC(e.kind)}`}function TB(e){return e.workspaceRoot?`Recorded from ${e.workspaceRoot}.`:e.conversationId?`Linked to thread ${UC(e.conversationId)}.`:"No additional detail was captured for this event."}function jB({navigate:e}){const[t,s]=b.useState([]),[r,i]=b.useState(null),[l,c]=b.useState(!0),[f,p]=b.useState(!1),[h,g]=b.useState(null),[v,x]=b.useState(null),w=b.useRef([]),T=b.useRef(0),N=b.useRef(null),A=mo();b.useEffect(()=>{w.current=t},[t]);const C=b.useCallback(async(M="initial")=>{const O=++T.current;!(w.current.length>0)&&M!=="background"?(c(!0),g(null)):p(!0);try{const H=await ot("/api/activity");if(O!==T.current)return;s(H),g(null),x(Date.now()),i(F=>H.some($=>$.id===F)?F:null)}catch(H){if(O!==T.current)return;g(H instanceof Error?H.message:String(H))}finally{O===T.current&&(c(!1),p(!1))}},[]),j=b.useCallback(()=>{N.current||(N.current=setTimeout(()=>{N.current=null,C("background")},250))},[C]);b.useEffect(()=>(C("initial"),()=>{N.current&&clearTimeout(N.current)}),[C]),Kn(j);const S=b.useMemo(()=>{const M=new Set(t.map(I=>I.actorName??"system")),O=new Set(t.map(I=>I.conversationId).filter(I=>!!I));return[{label:"Events",value:`${t.length}`,detail:t.length>0?`Latest ${tt(t[0].ts)}`:"Waiting for records"},{label:"Actors",value:`${M.size}`,detail:M.size>0?"Distinct event owners":"No actors yet"},{label:"Threads",value:`${O.size}`,detail:O.size>0?"Conversation-linked records":"No linked threads"}]},[t]),_=!l&&t.length===0&&!!h,R=!l&&t.length===0&&!h;return d.jsxs("div",{className:"sys-surface-page",children:[d.jsxs("div",{className:"sys-page-head",children:[d.jsxs("div",{className:"sys-page-title-group",children:[d.jsx("h2",{className:"sys-page-title",children:"Activity"}),d.jsx("p",{className:"sys-page-subtitle",children:"Broker events, task execution, and collaboration handoffs."})]}),d.jsxs("div",{className:"sys-page-actions",children:[d.jsx("div",{className:"sys-sync-note",children:l?"Loading audit ledger...":h&&t.length>0?`Showing last confirmed snapshot from ${v?tt(v):"earlier"}`:v?`Updated ${tt(v)}`:"Waiting for first snapshot"}),d.jsx("button",{type:"button",className:"s-btn",disabled:l||f,onClick:()=>{C("manual")},children:f?"Refreshing...":"Refresh"})]})]}),d.jsx("div",{className:"sys-stat-grid",children:S.map(M=>d.jsxs("div",{className:"sys-stat-card",children:[d.jsx("span",{className:"sys-stat-label",children:M.label}),d.jsx("strong",{className:"sys-stat-value",children:M.value}),d.jsx("span",{className:"sys-stat-detail",children:M.detail})]},M.label))}),h&&t.length>0&&d.jsxs("div",{className:"sys-banner sys-banner-warning",children:[d.jsx("strong",{children:"Refresh failed."}),d.jsx("span",{children:h})]}),l&&t.length===0&&d.jsxs("div",{className:"sys-panel sys-state-card",children:[d.jsx("h3",{className:"sys-state-title",children:"Loading activity"}),d.jsx("p",{className:"sys-state-body",children:"Pulling the latest records from the broker database."})]}),_&&d.jsxs("div",{className:"sys-panel sys-state-card sys-state-card-error",children:[d.jsx("h3",{className:"sys-state-title",children:"Activity is unavailable"}),d.jsx("p",{className:"sys-state-body",children:h}),d.jsx("div",{className:"sys-inline-actions",children:d.jsx("button",{type:"button",className:"s-btn",onClick:()=>{C("manual")},children:"Try again"})})]}),R&&d.jsxs("div",{className:"sys-panel sys-state-card",children:[d.jsx("h3",{className:"sys-state-title",children:"No activity yet"}),d.jsx("p",{className:"sys-state-body",children:"Events appear here after agents register, send messages, or advance work."})]}),t.length>0&&d.jsx("div",{className:"sys-audit-list",children:t.map(M=>{const O=r===M.id,I=wB(M.kind),H=xB[I],F=EB(M.workspaceRoot),$=M.summary&&M.summary!==M.title?M.summary:TB(M);return d.jsxs("article",{className:`sys-audit-entry${O?" sys-audit-entry-expanded":""}`,onContextMenu:L=>{const Y=window.getSelection()?.toString().trim(),re=[];Y&&(re.push({kind:"action",label:"Copy Selection",shortcut:"⌘C",onSelect:()=>navigator.clipboard.writeText(Y)}),re.push({kind:"separator"}));const Q=M.title??M.summary??"";Q&&re.push({kind:"action",label:"Copy Details",onSelect:()=>navigator.clipboard.writeText(Q)}),M.actorName&&re.push({kind:"action",label:"Copy Actor",onSelect:()=>navigator.clipboard.writeText(M.actorName)}),re.push({kind:"action",label:"Copy Event ID",onSelect:()=>navigator.clipboard.writeText(M.id)}),M.conversationId&&(re.push({kind:"separator"}),re.push({kind:"action",label:"Open Thread",onSelect:()=>e({view:"conversation",conversationId:M.conversationId})})),A(L,re)},children:[d.jsxs("button",{type:"button",className:"sys-audit-toggle","aria-expanded":O,onClick:()=>i(O?null:M.id),children:[d.jsxs("div",{className:"sys-audit-stamp",children:[d.jsx("span",{className:"sys-audit-time",children:tt(M.ts)}),d.jsx("span",{className:"sys-audit-date",children:Ia(M.ts)})]}),d.jsx("div",{className:`sys-audit-marker sys-audit-marker-${H.tone}`,children:d.jsx("span",{})}),d.jsxs("div",{className:"sys-audit-body",children:[d.jsxs("div",{className:"sys-audit-topline",children:[d.jsx("span",{className:"sys-audit-category",children:H.label}),d.jsx("span",{className:"sys-audit-kind",children:PC(M.kind)})]}),d.jsx("h3",{className:"sys-audit-title",children:Yn(M.title??NB(M))}),d.jsx("p",{className:"sys-audit-summary",children:Yn($)}),d.jsxs("div",{className:"sys-audit-meta",children:[d.jsxs("span",{className:"sys-audit-meta-item",children:[d.jsx("span",{className:"sys-audit-avatar",style:{background:Ts(M.actorName??"system")},children:SB(M.actorName)}),M.actorName??"system"]}),F&&d.jsxs("span",{className:"sys-audit-meta-item",children:["Workspace ",F]}),M.conversationId&&d.jsxs("span",{className:"sys-audit-meta-item",children:["Thread ",UC(M.conversationId)]})]})]}),d.jsx("div",{className:"sys-audit-expand",children:O?"Close":"Details"})]}),O&&d.jsxs("div",{className:"sys-audit-details",children:[d.jsxs("div",{className:"sys-detail-grid",children:[d.jsxs("div",{className:"sys-detail-card",children:[d.jsx("span",{className:"sys-detail-label",children:"Event"}),d.jsx("code",{className:"sys-detail-value",children:M.kind})]}),d.jsxs("div",{className:"sys-detail-card",children:[d.jsx("span",{className:"sys-detail-label",children:"Recorded"}),d.jsx("span",{className:"sys-detail-value",children:Ia(M.ts)})]}),d.jsxs("div",{className:"sys-detail-card",children:[d.jsx("span",{className:"sys-detail-label",children:"Actor"}),d.jsx("span",{className:"sys-detail-value",children:M.actorName??"system"})]}),d.jsxs("div",{className:"sys-detail-card",children:[d.jsx("span",{className:"sys-detail-label",children:"Workspace"}),d.jsx("span",{className:"sys-detail-value",children:M.workspaceRoot??"Not attached"})]}),d.jsxs("div",{className:"sys-detail-card",children:[d.jsx("span",{className:"sys-detail-label",children:"Thread"}),d.jsx("span",{className:"sys-detail-value",children:M.conversationId??"Not attached"})]}),d.jsxs("div",{className:"sys-detail-card",children:[d.jsx("span",{className:"sys-detail-label",children:"Record id"}),d.jsx("code",{className:"sys-detail-value",children:M.id})]})]}),M.conversationId&&d.jsx("div",{className:"sys-inline-actions",children:d.jsx("button",{type:"button",className:"s-btn s-btn-sm",onClick:()=>e({view:"conversation",conversationId:M.conversationId}),children:"Open thread"})})]})]},M.id)})})]})}function CB(e){const t=e.split(".");return t[t.length-1]||e}function pl(e){return e?e.replace(/_/g," "):null}function RB({values:e}){return d.jsx("span",{className:"s-agent-token-list",children:e.map(t=>d.jsx("span",{className:"s-agent-token",children:t},t))})}function zu({title:e,items:t}){return t.length===0?null:d.jsxs("section",{className:"s-agent-profile-card",children:[d.jsx("div",{className:"s-agent-profile-card-header",children:d.jsx("div",{className:"s-agent-profile-card-title",children:e})}),d.jsx("div",{className:"s-agent-meta-card-body",children:t.map(s=>d.jsxs("div",{className:"s-agent-meta-row",children:[d.jsx("span",{className:"s-agent-meta-label",children:s.label}),d.jsx("span",{className:"s-agent-meta-value",children:s.value})]},s.label))})]})}function AB({conversationId:e,navigate:t}){const{agents:s}=Yt(),[r,i]=b.useState(null),[l,c]=b.useState(null),f=DC(e),p=b.useCallback(async()=>{c(null);try{const N=await ot(`/api/session/${encodeURIComponent(e)}`).catch(()=>null);i(N)}catch(N){c(N instanceof Error?N.message:String(N)),i(null)}},[e]);b.useEffect(()=>{p()},[p]),Kn(p);const h=r?.agentId??f,g=b.useMemo(()=>h?s.find(N=>N.id===h)??null:null,[s,h]);if(!g)return d.jsxs("div",{children:[d.jsx("button",{type:"button",className:"s-back",onClick:()=>t({view:"conversation",conversationId:e}),children:"← Back"}),l&&d.jsx("p",{className:"s-error",children:l}),d.jsx("div",{className:"s-empty",children:d.jsx("p",{children:"Agent not found"})})]});const v=[{label:"Agent ID",value:g.id},...g.handle?[{label:"Handle",value:`@${g.handle}`}]:[],{label:"Class",value:pl(g.agentClass)??"—"},...g.role?[{label:"Role",value:g.role}]:[],...g.selector?[{label:"Selector",value:g.selector}]:[]],x=[...g.project?[{label:"Project",value:g.project}]:[],...g.branch?[{label:"Branch",value:g.branch}]:[],...g.projectRoot?[{label:"Path",value:g.projectRoot}]:[],...g.cwd?[{label:"Working dir",value:g.cwd}]:[]],w=[{label:"State",value:ao(g.state)},...g.harness?[{label:"Harness",value:g.harness}]:[],...g.transport?[{label:"Transport",value:pl(g.transport)??g.transport}]:[],...g.wakePolicy?[{label:"Wake policy",value:pl(g.wakePolicy)??g.wakePolicy}]:[],...g.capabilities.length>0?[{label:"Capabilities",value:d.jsx(RB,{values:g.capabilities})}]:[]],T=[{label:"Conversation ID",value:e},...r?.title?[{label:"Title",value:r.title}]:[],...r?.workspaceRoot?[{label:"Workspace",value:r.workspaceRoot}]:[],...r?.currentBranch?[{label:"Session branch",value:r.currentBranch}]:[],...r?.messageCount!=null?[{label:"Messages",value:String(r.messageCount)}]:[],...r?.lastMessageAt?[{label:"Last message",value:Ia(r.lastMessageAt)}]:[],...g.harnessSessionId?[{label:"Harness session",value:g.harnessSessionId}]:[],...g.harnessLogPath?[{label:"Harness log",value:g.harnessLogPath}]:[]];return d.jsxs("div",{className:"s-agent-profile-page",children:[d.jsxs("div",{className:"s-agent-profile-page-topbar",children:[d.jsx("button",{type:"button",className:"s-back",onClick:()=>t({view:"conversation",conversationId:e}),children:"← Conversation"}),d.jsx("button",{type:"button",className:"s-btn",onClick:()=>t({view:"agents",agentId:g.id}),children:"Open in Agents"})]}),l&&d.jsx("p",{className:"s-error",children:l}),d.jsxs("section",{className:"s-agent-profile-hero",children:[d.jsx("div",{className:"s-agent-profile-hero-main",children:d.jsxs("div",{className:"s-agent-profile-hero-title-row",children:[d.jsx("div",{className:"s-avatar s-agent-profile-hero-avatar",style:{background:Ts(g.name)},children:g.name[0].toUpperCase()}),d.jsxs("div",{className:"s-agent-profile-hero-copy",children:[d.jsxs("div",{className:"s-agent-casefile-title-meta",children:[d.jsx("span",{className:"s-agent-casefile-record",children:CB(g.id)}),d.jsxs("span",{className:`s-agent-state-chip s-agent-state-chip-${ws(g.state)}`,children:[d.jsx("span",{className:"s-dot",style:{background:ec(g.state)}}),ao(g.state)]})]}),d.jsx("h1",{className:"s-agent-profile-hero-title",children:g.name}),d.jsx("p",{className:"s-agent-profile-hero-copyline",children:[g.handle?`@${g.handle}`:null,g.project,g.branch,pl(g.role)??pl(g.agentClass)].filter(Boolean).join(" • ")}),d.jsxs("p",{className:"s-agent-profile-hero-context",children:[r?.title?`Conversation: ${r.title}.`:"Attached to the current conversation.",g.updatedAt?` Updated ${tt(g.updatedAt)}.`:""]})]})]})}),d.jsx("div",{className:"s-agent-profile-hero-actions",children:d.jsx("button",{type:"button",className:"s-btn s-btn-primary",onClick:()=>t({view:"conversation",conversationId:e}),children:"Open conversation"})})]}),d.jsxs("div",{className:"s-agent-profile-grid",children:[d.jsx(zu,{title:"Identity",items:v}),d.jsx(zu,{title:"Workspace",items:x}),d.jsx(zu,{title:"Runtime",items:w}),d.jsx(zu,{title:"Conversation context",items:T})]})]})}function _B(e){return e.attention==="interrupt"?"failed":e.state==="done"?"completed":e.attention==="badge"||e.state==="waiting"||e.state==="review"?"updated":"working"}function kB(e){switch(e){case"review":return"In review";case"waiting":return"Waiting";case"working":return"Working";case"done":return"Done";default:return e.replace(/_/g," ")}}function MB(e){switch(e){case"badge":return"Needs attention";case"interrupt":return"Blocked";default:return null}}function OB({items:e,navigate:t,emptyTitle:s,emptyDetail:r}){if(e.length===0){const i=[{titleWidth:"56%",metaWidths:["18%","14%","16%"],summaryWidth:"74%"},{titleWidth:"48%",metaWidths:["16%","20%","12%"],summaryWidth:"62%"}];return d.jsxs("div",{className:"s-work-empty-state",children:[d.jsxs("div",{className:"s-work-empty-copy",children:[d.jsx("p",{className:"s-work-empty-kicker",children:"Quiet for now"}),d.jsx("p",{className:"s-work-empty-title",children:s}),r&&d.jsx("p",{className:"s-work-empty-detail",children:r})]}),d.jsx("div",{className:"s-work-empty-skeleton","aria-hidden":"true",children:i.map((l,c)=>d.jsxs("div",{className:"s-work-empty-row",children:[d.jsxs("div",{className:"s-work-empty-row-header",children:[d.jsx("span",{className:"s-work-empty-line s-work-empty-line-title",style:{width:l.titleWidth}}),d.jsx("span",{className:"s-work-empty-pill"})]}),d.jsx("div",{className:"s-work-empty-row-meta",children:l.metaWidths.map(f=>d.jsx("span",{className:"s-work-empty-line s-work-empty-line-meta",style:{width:f}},f))}),d.jsx("span",{className:"s-work-empty-line s-work-empty-line-summary",style:{width:l.summaryWidth}})]},c))})]})}return d.jsx("div",{className:"s-work-list",children:e.map(i=>{const l=!!i.id||!!i.conversationId,c=MB(i.attention),f=i.ownerName??i.ownerId??"Unassigned",p=i.id?()=>t({view:"work",workId:i.id}):i.conversationId?()=>t({view:"conversation",conversationId:i.conversationId}):void 0;return d.jsxs("div",{className:`s-work-row${l?" s-work-row-clickable":""}`,onClick:p,children:[d.jsxs("div",{className:"s-work-row-header",children:[d.jsxs("div",{className:"s-work-row-title-wrap",children:[d.jsx("span",{className:"s-work-row-title",children:i.title}),i.priority&&d.jsx("span",{className:"s-badge",children:i.priority})]}),d.jsx("span",{className:`s-pill s-pill-${_B(i)}`,children:i.currentPhase})]}),d.jsxs("div",{className:"s-work-row-meta",children:[d.jsx("span",{children:f}),d.jsx("span",{children:kB(i.state)}),i.activeChildWorkCount>0&&d.jsxs("span",{children:[i.activeChildWorkCount," child",i.activeChildWorkCount===1?"":"ren"]}),i.activeFlightCount>0&&d.jsxs("span",{children:[i.activeFlightCount," flight",i.activeFlightCount===1?"":"s"]}),c&&d.jsx("span",{children:c}),d.jsx("span",{children:tt(i.lastMeaningfulAt)})]}),i.lastMeaningfulSummary&&d.jsx("p",{className:"s-work-row-summary",children:Yn(i.lastMeaningfulSummary)})]},i.id)})})}const sg=new Set(["completed","failed","cancelled"]),DB={direct:"Direct message",channel:"Channel",group_direct:"Group",thread:"Thread"};function In(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?null:e<1e12?e*1e3:e}function zB(e){if(!e)return null;const t=e.replace(/[\\/]+$/,"");return t?t.split(/[\\/]/).filter(Boolean).at(-1)??t:null}function IB(e){return e.kind==="direct"&&e.agentName?e.agentName:e.title.replace(/\s*<>\s*/g," · ")}function tm(e){const t=In(e);return t===null?"":new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(t)}function LB(e,t){const s=In(e),r=In(t);if(s===null||r===null)return!1;const i=new Date(s),l=new Date(r);return i.getFullYear()===l.getFullYear()&&i.getMonth()===l.getMonth()&&i.getDate()===l.getDate()}function RS(e){const t=In(e);if(t===null)return"";const s=new Date(t),r=new Date,i=new Date(r.getFullYear(),r.getMonth(),r.getDate()).getTime(),l=new Date(s.getFullYear(),s.getMonth(),s.getDate()).getTime(),c=1440*60*1e3;return l===i?"Today":l===i-c?"Yesterday":new Intl.DateTimeFormat(void 0,{weekday:"short",month:"short",day:"numeric"}).format(t)}function PB(e){switch(e){case"status":return"Status";case"system":return"System";case"scout.dispatch":return"Dispatch";default:return null}}function Iu(e){return[...e].sort((t,s)=>(In(t.createdAt)??0)-(In(s.createdAt)??0))}function UB(e){return e.filter(t=>!sg.has(t.state)).sort((t,s)=>(In(s.startedAt)??0)-(In(t.startedAt)??0))[0]??null}function AS(e,t,s){return{id:e.id,invocationId:e.invocationId,agentId:e.targetAgentId||s,agentName:null,conversationId:t,collaborationRecordId:null,state:e.state,summary:e.summary??null,startedAt:e.startedAt??null,completedAt:e.completedAt??null}}function $B(e){const t=e.metadata?.scoutDispatch;if(!t||typeof t!="object")return null;const s=t;return!s.id||!s.kind||!Array.isArray(s.candidates)?null:s}function rg(e,t){if(e.class==="operator")return!0;const s=e.actorName?.toLowerCase()??"";return s===t.toLowerCase()||s==="operator"||s==="you"}function VB(e,t){return e.reduce((s,r)=>{if(rg(r,t))return s;const i=In(r.createdAt);return i===null?s:s===null||i>s?i:s},null)}function BB(e,t){switch(t){case"queued":return`${e} has your message and is waiting to start.`;case"waking":return`${e} is waking up now.`;case"waiting":return`${e} is thinking through the request.`;case"running":return`${e} is working on your request.`;default:return`${e} is working on it.`}}function ZB(e){const{agentName:t,agentState:s,sending:r,currentFlight:i,showWorkingTurn:l}=e;if(r&&!i)return{label:"Sending",detail:`Handing your message to ${t}.`,tone:"pending",showStrip:!0,showTyping:!1};if(i&&l){const c=i.summary?.trim()||BB(t,i.state);switch(i.state){case"queued":return{label:"Queued",detail:c,tone:"pending",showStrip:!0,showTyping:!0};case"waking":return{label:"Coming online",detail:c,tone:"working",showStrip:!0,showTyping:!0};case"waiting":return{label:"Thinking",detail:c,tone:"working",showStrip:!0,showTyping:!0};default:return{label:"Working",detail:c,tone:"working",showStrip:!0,showTyping:!0}}}return Fa(s)?{label:"Available",detail:`${t} is connected.`,tone:"idle",showStrip:!1,showTyping:!1}:{label:"Offline",detail:`${t} is offline right now. Sending a message will wake it up.`,tone:"offline",showStrip:!0,showTyping:!1}}function HB(e,t){switch(e.tone){case"pending":return"var(--accent)";case"working":return"var(--green)";case"offline":return"var(--dim)";default:return ec(t)}}function FB(){return d.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[d.jsx("path",{d:"m3 11 18-8-8 18-2.8-7.2L3 11Z"}),d.jsx("path",{d:"M10.2 13.8 21 3"})]})}function qB(){return d.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:d.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})})}function _S({label:e,value:t}){return d.jsxs("div",{className:"s-conv-meta-row",children:[d.jsx("span",{className:"s-conv-meta-label",children:e}),d.jsx("span",{className:"s-conv-meta-value",children:t})]})}function YB(e){if(!e)return null;const t=e.participantIds.filter(s=>s!=="operator");return t.length===0?null:t.join(", ")}function ag({conversationId:e,navigate:t}){const{agents:s}=Yt(),[r,i]=b.useState(null),[l,c]=b.useState([]),[f,p]=b.useState(null),[h,g]=b.useState(null),v=b.useRef(null),x=b.useRef(null),w=b.useRef(new Set),T=b.useRef(null),N=b.useRef(0),A=DC(e),C=r?.agentId??A,j=r?.kind==="direct"||A!==null,S=b.useMemo(()=>C?s.find(ae=>ae.id===C)??null:null,[s,C]),_=b.useCallback(async()=>{g(null);try{const ae=await ot(`/api/session/${encodeURIComponent(e)}`).catch(()=>null);i(ae);const se=ae?.agentId??A,ye=ae?.kind==="direct"&&se&&se.startsWith("local-session-agent-")?ng(se):e;if(ye!==e){t({view:"conversation",conversationId:ye});return}const[Se,we]=await Promise.all([ot(`/api/messages?conversationId=${encodeURIComponent(ye)}&limit=300`),ot(`/api/flights?conversationId=${encodeURIComponent(ye)}`)]);c(Iu(Se)),w.current=new Set(we.map(Re=>Re.invocationId)),p(UB(we))}catch(ae){g(ae instanceof Error?ae.message:String(ae))}},[e,A,t]);b.useEffect(()=>{_()},[_]),b.useEffect(()=>{T.current=f},[f]);const[R,M]=b.useState(""),[O,I]=b.useState(!1),[H,F]=b.useState("operator"),[$,L]=b.useState(null);b.useEffect(()=>{const ae=x.current;if(!ae)return;ae.style.height="0px";const se=Math.min(Math.max(ae.scrollHeight,40),160);ae.style.height=`${se}px`,ae.style.overflowY=ae.scrollHeight>se?"auto":"hidden"},[R]),b.useEffect(()=>{ot("/api/user").then(ae=>F(ae.name)).catch(()=>{})},[]);const Y=b.useMemo(()=>VB(l,H),[l,H]);b.useEffect(()=>{$===null||Y===null||Y>=$&&L(null)},[$,Y]);const re=b.useMemo(()=>!f||sg.has(f.state)?!1:(In(f.startedAt)??$??Date.now())>=(Y??0),[$,f,Y]),Q=O||$!==null||re,z=S?.name??r?.agentName??r?.title??C??"Conversation",Z=b.useMemo(()=>ZB({agentName:z,agentState:S?.state??null,sending:O,currentFlight:f,showWorkingTurn:re}),[S?.state,z,f,O,re]),B=r?IB(r):z,ie=r?.kind?DB[r.kind]??r.kind:"Conversation",W=YB(r)??e,D=zB(r?.workspaceRoot),P=r?.lastMessageAt??l[l.length-1]?.createdAt??null,G=[D?{label:D,title:r?.workspaceRoot??void 0}:null,r?.currentBranch?{label:r.currentBranch,title:r.currentBranch}:null,S?.harness??r?.harness?{label:S?.harness??r?.harness??"",title:void 0}:null].filter(ae=>!!ae);Kn(b.useCallback(ae=>{if(ae.kind==="message.posted"){const se=ae.payload?.message;if(!se||se.conversationId!==e)return;const ye=se.actorId===C,Se={id:se.id,conversationId:se.conversationId,actorName:ye?z:H,body:se.body,createdAt:se.createdAt,class:ye?se.class:"operator"};if(c(we=>{if(we.some(Re=>Re.id===se.id))return we;if(!ye){const Re=we.findIndex(oe=>oe.id.startsWith("optimistic-")&&oe.body===se.body&&Math.abs((In(oe.createdAt)??0)-(In(se.createdAt)??0))<=6e4);if(Re!==-1){const oe=[...we];return oe[Re]=Se,Iu(oe)}}return Iu([...we,Se])}),ye){const we=In(se.createdAt)??Date.now();L(Re=>Re===null||we<Re?Re:null),p(Re=>{if(!Re)return Re;const oe=In(Re.startedAt)??0;return we>=oe?null:Re})}return}if(ae.kind==="invocation.requested"){const se=ae.payload?.invocation;if(!se||se.targetAgentId!==C||se.conversationId!==e)return;w.current.add(se.id),L(ye=>ye??Date.now());return}if(ae.kind==="flight.updated"){const se=ae.payload?.flight;if(!se||se.targetAgentId!==C||!(w.current.has(se.invocationId)||T.current?.id===se.id))return;if(sg.has(se.state)){p(Se=>Se?.id===se.id?null:Se),_();return}w.current.add(se.invocationId),p(AS(se,e,C??""));return}ae.kind!=="agent.endpoint.upserted"&&ae.kind==="unknown"&&_()},[C,z,e,_,H])),b.useEffect(()=>{if(!Q)return;const ae=setInterval(()=>{_()},5e3);return()=>clearInterval(ae)},[Q,_]),b.useEffect(()=>{const ae=()=>{if(document.visibilityState!=="visible")return;const se=Date.now();se-N.current<1e3||(N.current=se,_())};return window.addEventListener("focus",ae),document.addEventListener("visibilitychange",ae),()=>{window.removeEventListener("focus",ae),document.removeEventListener("visibilitychange",ae)}},[_]);const te=l.length+(Z.showTyping?1:0),ee=b.useRef(0);b.useEffect(()=>{te>ee.current&&v.current?.scrollIntoView({behavior:"smooth"}),ee.current=te},[te]);const[,ve]=b.useState(0);b.useEffect(()=>{const ae=setInterval(()=>ve(se=>se+1),15e3);return()=>clearInterval(ae)},[]);const he=async ae=>{const se=ae.trim();if(!se||O)return;const ye=Date.now(),Se={id:`optimistic-${ye}`,conversationId:e,actorName:H,body:se,createdAt:ye,class:"operator"};I(!0),L(ye),g(null),c(we=>Iu([...we,Se]));try{const we=await ot("/api/send",{method:"POST",body:JSON.stringify({body:se,conversationId:e})});we.flight&&(w.current.add(we.flight.invocationId),p(AS(we.flight,e,C??"")))}catch(we){c(Re=>Re.filter(oe=>oe.id!==Se.id)),L(null),g(we instanceof Error?we.message:String(we))}finally{I(!1)}},pe=async()=>{const ae=R.trim();ae&&(M(""),await he(ae))},xe=async()=>{if(C)try{await ot("/api/agents/"+encodeURIComponent(C)+"/interrupt",{method:"POST",body:JSON.stringify({})})}catch{}},ke=Z.tone==="working"||Z.tone==="pending",fe=!R.trim()&&ke,Me=mo(),Ee=b.useCallback((ae,se)=>{const ye=window.getSelection()?.toString().trim(),Se=[];ye&&(Se.push({kind:"action",label:"Copy Selection",shortcut:"⌘C",onSelect:()=>navigator.clipboard.writeText(ye)}),Se.push({kind:"separator"})),Se.push({kind:"action",label:"Copy Message",onSelect:()=>navigator.clipboard.writeText(se.body)}),se.actorName&&!rg(se,H)&&Se.push({kind:"action",label:"Copy Agent ID",onSelect:()=>navigator.clipboard.writeText(se.actorName??"")}),Se.push({kind:"separator"}),Se.push({kind:"action",label:"Copy Message ID",onSelect:()=>navigator.clipboard.writeText(se.id)}),Me(ae,Se)},[H,Me]),He=async(ae,se)=>{const ye=`@${se.agentId} `,Se=R.trim();if(Se){M(""),await he(`${ye}${Se}`);return}M(ye),x.current?.focus()};return d.jsxs("div",{className:"s-conversation s-inbox-thread-redesign",children:[d.jsxs("div",{className:"s-conv-header",onClick:()=>j?t({view:"agent-info",conversationId:e}):void 0,style:j?void 0:{cursor:"default"},onContextMenu:ae=>{const se=[{kind:"action",label:"Copy Title",onSelect:()=>navigator.clipboard.writeText(B)}];C&&se.push({kind:"action",label:"Copy Agent ID",onSelect:()=>navigator.clipboard.writeText(C)}),se.push({kind:"action",label:"Copy Conversation ID",onSelect:()=>navigator.clipboard.writeText(e)}),Me(ae,se)},children:[d.jsx("button",{type:"button",className:"s-back",onClick:ae=>{ae.stopPropagation(),t(j?{view:"inbox"}:{view:"sessions"})},children:"←"}),d.jsxs("div",{className:"s-thread-header-copy",children:[d.jsxs("div",{className:"s-thread-header-main",children:[d.jsx("div",{className:"s-avatar s-avatar-sm",style:{background:Ts(z)},children:z[0]?.toUpperCase()??"?"}),d.jsxs("div",{className:"s-conv-header-info",children:[d.jsx("span",{className:"s-conv-header-name",children:B}),d.jsxs("span",{className:"s-conv-header-state",title:j?Z.detail:W,children:[d.jsx("span",{className:"s-dot s-dot-sm",style:{background:HB(Z,S?.state??null)}}),j?Z.label:W]})]})]}),d.jsxs("div",{className:"s-thread-header-meta",children:[d.jsx("span",{className:"s-thread-kicker",children:ie}),P&&d.jsx("span",{className:"s-thread-header-updated s-tabular",title:tm(P),children:tt(P)})]})]}),G.length>0&&d.jsx("div",{className:"s-thread-header-chips","aria-label":"Thread details",children:G.map((ae,se)=>d.jsx("span",{className:"s-thread-chip",title:ae.title,children:ae.label},`${ae.label}-${se}`))}),j&&C&&d.jsx("span",{className:"s-chevron"})]}),Z.showStrip&&d.jsxs("div",{className:`s-conv-status s-conv-status-${Z.tone}`,"aria-live":"polite",children:[d.jsx("span",{className:"s-conv-status-dot"}),d.jsxs("div",{className:"s-conv-status-copy",children:[d.jsx("span",{className:"s-conv-status-label",children:Z.label}),d.jsx("span",{className:"s-conv-status-detail",children:Z.detail})]})]}),j&&S&&(S.harnessSessionId||S.harnessLogPath)&&d.jsxs("details",{className:"s-conv-meta-disclosure",children:[d.jsx("summary",{className:"s-conv-meta-toggle",children:"Session details"}),d.jsxs("div",{className:"s-conv-meta","aria-label":"Agent session metadata",children:[S.harnessSessionId&&d.jsx(_S,{label:"Harness Session",value:S.harnessSessionId}),S.harnessLogPath&&d.jsx(_S,{label:"Harness Log",value:S.harnessLogPath})]})]}),h&&d.jsx("p",{className:"s-error",children:h}),d.jsxs("div",{className:"s-messages",children:[l.length===0?d.jsxs("div",{className:"s-empty s-thread-empty",children:[d.jsx("p",{children:"No messages yet"}),d.jsx("p",{children:j?`Start a conversation with ${z}.`:"Start the thread below."})]}):l.map((ae,se)=>{const ye=rg(ae,H),Se=$B(ae),we=Se?"scout.dispatch":ae.class,Re=PB(we),oe=se===0||!LB(l[se-1]?.createdAt,ae.createdAt),ge=tm(ae.createdAt);return d.jsxs("div",{className:"s-thread-message-block",children:[oe&&d.jsxs("div",{className:"s-thread-day-divider","aria-label":RS(ae.createdAt),children:[d.jsx("span",{className:"s-thread-day-line","aria-hidden":"true"}),d.jsx("span",{className:"s-thread-day-label",children:RS(ae.createdAt)}),d.jsx("span",{className:"s-thread-day-line","aria-hidden":"true"})]}),d.jsx("article",{className:`s-msg s-row-message${ye?" s-msg-you":""}`,"data-class":we,onContextMenu:me=>Ee(me,ae),children:d.jsxs("div",{className:"s-msg-card",children:[d.jsxs("div",{className:"s-msg-header",children:[d.jsxs("div",{className:"s-msg-meta",children:[d.jsx("span",{className:"s-msg-actor",children:ye?"You":ae.actorName}),Re&&d.jsx("span",{className:"s-msg-kind",children:Re})]}),d.jsx("span",{className:"s-msg-time",title:ge,children:tt(ae.createdAt)})]}),d.jsx("div",{className:"s-msg-body",title:ge,children:Yn(ae.body)}),Se&&Se.candidates.length>0&&d.jsx("div",{className:"s-scout-dispatch",children:Se.candidates.map(me=>d.jsxs("button",{type:"button",className:"s-scout-tile",onClick:()=>{He(Se,me)},children:[d.jsxs("span",{className:"s-scout-tile-id",children:["@",me.agentId]}),d.jsx("span",{className:"s-scout-tile-state",children:me.endpointState}),d.jsx("span",{className:"s-scout-tile-meta",children:[me.workspace,me.node,me.projectRoot].filter(Boolean).join(" · ")||me.displayName})]},me.agentId))})]})})]},ae.id)}),Z.showTyping&&d.jsx("div",{className:"s-thread-message-block",children:d.jsx("div",{className:"s-msg s-msg-working","aria-live":"polite",children:d.jsxs("div",{className:"s-msg-card s-msg-working-card",children:[d.jsxs("div",{className:"s-msg-header",children:[d.jsxs("div",{className:"s-msg-meta",children:[d.jsx("span",{className:"s-msg-actor",children:z}),d.jsx("span",{className:"s-msg-kind",children:"Live"})]}),d.jsx("span",{className:"s-msg-time",title:f?.startedAt?tm(f.startedAt):"now",children:f?.startedAt?tt(f.startedAt):"now"})]}),d.jsxs("div",{className:"s-msg-working-body",children:[d.jsxs("span",{className:"s-typing-indicator","aria-hidden":"true",children:[d.jsx("span",{className:"s-typing-dot"}),d.jsx("span",{className:"s-typing-dot"}),d.jsx("span",{className:"s-typing-dot"})]}),d.jsx("span",{className:"s-msg-working-copy",children:Z.detail})]})]})})}),d.jsx("div",{ref:v})]}),d.jsx("form",{className:"s-compose",onSubmit:ae=>{ae.preventDefault(),pe()},children:d.jsxs("div",{className:"s-thread-compose-shell",children:[d.jsx("textarea",{ref:x,className:"s-compose-input",placeholder:`Message ${z}...`,value:R,onChange:ae=>M(ae.target.value),onKeyDown:ae=>{ae.key!=="Enter"||ae.shiftKey||ae.nativeEvent.isComposing||(ae.preventDefault(),!O&&R.trim()&&pe())},rows:1}),d.jsxs("div",{className:"s-thread-compose-footer",children:[d.jsx("span",{className:"s-thread-compose-hint",children:O?"Sending…":fe?"Stop":ke?d.jsxs(d.Fragment,{children:[d.jsx("kbd",{className:"s-kbd",children:"↵"})," steer"]}):d.jsxs(d.Fragment,{children:[d.jsx("kbd",{className:"s-kbd",children:"↵"})," send",d.jsx("kbd",{className:"s-kbd",children:"⇧↵"})," newline"]})}),fe?d.jsx("button",{type:"button",className:"s-compose-send s-compose-stop",onClick:()=>{xe()},"aria-label":"Stop agent",children:d.jsx(qB,{})}):d.jsx("button",{type:"submit",className:"s-compose-send",disabled:O||!R.trim(),"aria-label":"Send message",children:d.jsx(FB,{})})]})]})})]})}function $C(e,t){if(t.filter(i=>i.name===e.name).length<=1)return{name:e.name,qualifier:null};const r=e.project??e.branch??e.id.replace(/^.*\./,"");return{name:e.name,qualifier:r}}function nm(e){return e?e.replace(/_/g," "):null}function GB(e){return e?tt(e):"—"}function XB(e){const t=[...e].filter(i=>i.kind==="direct"&&!!i.agentId).sort((i,l)=>(l.lastMessageAt??0)-(i.lastMessageAt??0)),s=new Map,r=new Map;for(const i of t){const l=i.agentId;s.has(l)||(s.set(l,i.id),r.set(l,i))}return{conversationByAgentId:s,sessionByAgentId:r}}function KB({label:e,value:t}){return d.jsxs("div",{className:"s-agent-meta-row",children:[d.jsx("span",{className:"s-agent-meta-label",children:e}),d.jsx("span",{className:"s-agent-meta-value",children:t})]})}function WB({values:e}){return d.jsx("span",{className:"s-agent-token-list",children:e.map(t=>d.jsx("span",{className:"s-agent-token",children:t},t))})}function JB({title:e,count:t,children:s}){return d.jsxs("section",{className:"s-agent-roster-section",children:[d.jsxs("div",{className:"s-agent-roster-section-header",children:[d.jsx("div",{className:"s-agent-roster-section-title",children:e}),d.jsx("span",{className:"s-agent-roster-section-count",children:t})]}),d.jsx("div",{className:"s-agent-roster-stack",children:s})]})}function QB({agents:e}){return e.length===0?null:d.jsxs("div",{className:"s-agent-overview-empty",children:[d.jsx("h2",{className:"s-agent-overview-empty-title",children:"Select an agent"}),d.jsx("p",{className:"s-agent-overview-empty-copy",children:"Pick an agent from the roster to view its profile, current work, and session context."})]})}function e7({agent:e,allAgents:t,session:s,conversationId:r,navigate:i}){const{name:l,qualifier:c}=$C(e,t),[f,p]=b.useState([]),h=ws(e.state),g=mo(),v=b.useCallback(async()=>{try{p(await ot(`/api/work?agentId=${encodeURIComponent(e.id)}`))}catch{p([])}},[e.id]);b.useEffect(()=>{v()},[v]),Kn(v);const x=[...e.project?[{label:"Project",value:e.project}]:[],...e.branch?[{label:"Branch",value:e.branch}]:[],...e.harness?[{label:"Harness",value:e.harness}]:[],...e.transport?[{label:"Transport",value:nm(e.transport)??e.transport}]:[],...e.projectRoot?[{label:"Path",value:e.projectRoot}]:[],...s?.workspaceRoot?[{label:"Workspace",value:s.workspaceRoot}]:[],...s?.currentBranch?[{label:"Session branch",value:s.currentBranch}]:[]];return d.jsxs("div",{className:"s-agent-casefile",children:[d.jsx("button",{type:"button",className:"s-back s-agent-mobile-back",onClick:()=>i({view:"agents"}),children:"← All agents"}),d.jsxs("section",{className:"s-agent-detail-identity",onContextMenu:w=>{const T=window.getSelection()?.toString().trim(),N=[];T&&(N.push({kind:"action",label:"Copy Selection",shortcut:"⌘C",onSelect:()=>navigator.clipboard.writeText(T)}),N.push({kind:"separator"})),N.push({kind:"action",label:"Copy Agent Name",onSelect:()=>navigator.clipboard.writeText(l)}),N.push({kind:"action",label:"Copy Agent ID",onSelect:()=>navigator.clipboard.writeText(e.id)}),e.handle&&N.push({kind:"action",label:`Copy @${e.handle}`,onSelect:()=>navigator.clipboard.writeText(`@${e.handle}`)}),g(w,N)},children:[d.jsx("div",{className:"s-avatar s-agent-casefile-avatar",style:{background:Ts(e.name)},children:e.name[0].toUpperCase()}),d.jsxs("div",{className:"s-agent-detail-identity-copy",children:[d.jsxs("h2",{className:"s-agent-detail-identity-name",children:[l,c&&d.jsx("span",{className:"s-agent-casefile-title-qualifier",children:c})]}),d.jsxs("div",{className:"s-agent-detail-identity-meta",children:[e.handle&&d.jsxs("span",{className:"s-agent-detail-handle",children:["@",e.handle]}),d.jsxs("span",{className:`s-agent-state-chip s-agent-state-chip-${h}`,children:[d.jsx("span",{className:"s-dot",style:{background:ec(e.state)}}),ao(e.state)]}),e.updatedAt&&d.jsx("span",{className:"s-agent-detail-updated",children:tt(e.updatedAt)})]}),d.jsx("p",{className:"s-agent-detail-identity-desc",children:[nm(e.role)??nm(e.agentClass),e.project].filter(Boolean).join(" · ")}),d.jsxs("div",{className:"s-agent-detail-actions",children:[d.jsx("button",{type:"button",className:"s-btn s-btn-primary",onClick:()=>r&&i({view:"agents",agentId:e.id,conversationId:r}),disabled:!r,children:r?"Open conversation":"No conversation"}),e.capabilities.length>0&&d.jsx("div",{className:"s-agent-detail-capabilities",children:d.jsx(WB,{values:e.capabilities})})]})]})]}),x.length>0&&d.jsxs("section",{className:"s-agent-detail-context",children:[d.jsx("h3",{className:"s-agent-detail-section-title",children:"Context"}),d.jsx("div",{className:"s-agent-meta-card-body",children:x.map(w=>d.jsx(KB,{label:w.label,value:w.value},w.label))})]}),d.jsxs("section",{className:"s-agent-detail-work",children:[d.jsx("h3",{className:"s-agent-detail-section-title",children:"Active work"}),d.jsx(OB,{items:f,navigate:i,emptyTitle:"Nothing in flight",emptyDetail:"New asks, handoffs, and follow-ups will stack here once this agent picks up work."})]})]})}function t7({navigate:e,selectedAgentId:t,conversationId:s}){const{agents:r}=Yt(),[i,l]=b.useState([]),c=b.useCallback(async()=>{const R=await ot("/api/sessions").catch(()=>null);R&&l(R)},[]);b.useEffect(()=>{c()},[c]),Kn(c);const f=[...r].sort((R,M)=>{const O={working:0,available:1,offline:2},I=O[ws(R.state)]-O[ws(M.state)];if(I!==0)return I;const H=(M.updatedAt??0)-(R.updatedAt??0);return H!==0?H:R.name.localeCompare(M.name)}),p=[{key:"working",title:"Working",agents:f.filter(R=>ws(R.state)==="working")},{key:"available",title:"Available",agents:f.filter(R=>ws(R.state)==="available")},{key:"offline",title:"Offline",agents:f.filter(R=>ws(R.state)==="offline")}],h=t?r.find(R=>R.id===t)??null:null,{conversationByAgentId:g,sessionByAgentId:v}=XB(i),x=r.length>0,w=200,T=440,N="scout-agents-roster-w",[A,C]=b.useState(()=>{try{const R=localStorage.getItem(N);if(R){const M=Number(R);if(M>=w&&M<=T)return M}}catch{}return 280}),j=b.useRef(!1),S=b.useRef(null);b.useEffect(()=>{try{localStorage.setItem(N,String(A))}catch{}},[A]);const _=b.useCallback(R=>{R.preventDefault(),j.current=!0,document.body.style.cursor="col-resize",document.body.style.userSelect="none";const M=S.current?.getBoundingClientRect().left??0,O=H=>{j.current&&C(Math.min(T,Math.max(w,H.clientX-M)))},I=()=>{j.current=!1,document.body.style.cursor="",document.body.style.userSelect="",document.removeEventListener("mousemove",O),document.removeEventListener("mouseup",I)};document.addEventListener("mousemove",O),document.addEventListener("mouseup",I)},[]);return d.jsxs("div",{className:["s-agents-layout","s-agents-browser",x?"s-agents-layout-split":"",h?"s-agents-browser-selected":""].filter(Boolean).join(" "),style:{"--agents-roster-w":`${A}px`},children:[d.jsx("div",{ref:S,className:"s-agents-list-panel s-agents-browser-list",children:d.jsxs("div",{className:"s-agent-roster",children:[d.jsx("div",{className:"s-agent-roster-header",children:d.jsxs("div",{children:[d.jsx("h2",{className:"s-section-title s-agent-roster-title",children:"Agents"}),d.jsxs("p",{className:"s-agent-roster-copy",children:[r.length," total · ",p[0].agents.length," working · ",p[1].agents.length," available"]})]})}),r.length===0?d.jsxs("div",{className:"s-empty s-agent-roster-empty",children:[d.jsx("p",{children:"No agents"}),d.jsx("p",{children:"Agents appear here when they connect to the broker."})]}):p.filter(R=>R.agents.length>0).map(R=>d.jsx(JB,{title:R.title,count:R.agents.length,children:R.agents.map(M=>d.jsx(n7,{agent:M,allAgents:r,selected:M.id===t,onClick:()=>e({view:"agents",agentId:M.id})},M.id))},R.key))]})}),x&&d.jsxs(d.Fragment,{children:[d.jsx("div",{className:"s-agents-roster-resize",onMouseDown:_,role:"separator","aria-orientation":"vertical"}),d.jsx("div",{className:"s-agents-detail-panel s-agents-browser-detail",children:s&&h?d.jsx(ag,{conversationId:s,navigate:e}):h?d.jsx(e7,{agent:h,allAgents:r,session:v.get(h.id)??null,conversationId:g.get(h.id)??h.conversationId??null,navigate:e}):d.jsx(QB,{agents:r})})]})]})}function n7({agent:e,allAgents:t,selected:s,onClick:r}){const{name:i,qualifier:l}=$C(e,t),c=ws(e.state),f=mo();return d.jsxs("div",{className:`s-agent-list-row s-agent-roster-row${s?" s-agent-list-row-active":""}`,onClick:r,onContextMenu:p=>{const h=[{kind:"action",label:"Copy Agent Name",onSelect:()=>navigator.clipboard.writeText(i)},{kind:"action",label:"Copy Agent ID",onSelect:()=>navigator.clipboard.writeText(e.id)}];e.handle&&h.push({kind:"action",label:`Copy @${e.handle}`,onSelect:()=>navigator.clipboard.writeText(`@${e.handle}`)}),f(p,h)},children:[d.jsxs("div",{className:"s-agent-roster-avatar-wrap",children:[d.jsx("div",{className:"s-avatar s-avatar-sm",style:{background:Ts(e.name)},children:e.name[0].toUpperCase()}),d.jsx("span",{className:`s-agent-roster-avatar-status s-agent-roster-avatar-status-${c}`,style:{background:ec(e.state)}})]}),d.jsx("div",{className:"s-agent-list-body s-agent-roster-row-body",children:d.jsxs("div",{className:"s-agent-roster-row-top",children:[d.jsxs("div",{className:"s-agent-list-header",children:[d.jsx("span",{className:"s-agent-list-name",children:i}),l&&d.jsx("span",{className:"s-agent-list-qualifier",children:l})]}),d.jsx("span",{className:"s-agent-roster-row-time",children:GB(e.updatedAt)})]})})]})}function s7(e){switch(e){case"queued":case"working":return"working";case"needs_attention":return"updated";case"failed":return"failed";default:return"completed"}}function r7(e){return e.conversationId?{view:"conversation",conversationId:e.conversationId}:{view:"agents",agentId:e.agentId}}function a7(e){return e.kind==="work_item"&&e.recordId?{view:"work",workId:e.recordId}:e.conversationId?{view:"conversation",conversationId:e.conversationId}:e.agentId?{view:"agents",agentId:e.agentId}:null}function i7(e){return e.recordId?{view:"work",workId:e.recordId}:e.conversationId?{view:"conversation",conversationId:e.conversationId}:e.agentId?{view:"agents",agentId:e.agentId}:null}function Lu({title:e,detail:t,count:s}){return d.jsxs(d.Fragment,{children:[d.jsxs("div",{className:"s-dashboard-panel-header",children:[d.jsx("div",{children:d.jsx("h3",{children:e})}),d.jsx("span",{className:"s-dashboard-count",style:s===0?{opacity:.4}:void 0,children:s})]}),d.jsx("p",{className:"s-dashboard-panel-copy",children:t})]})}function kS({ask:e,navigate:t,section:s}){const r=r7(e),i=e.completedAt?`finished ${tt(e.completedAt)}`:e.startedAt?`started ${tt(e.startedAt)}`:`updated ${tt(e.updatedAt)}`;return d.jsxs("div",{className:`s-work-row s-work-row-clickable s-dashboard-fleet-row s-dashboard-fleet-row-${s}`,"data-status":e.status,onClick:()=>t(r),children:[d.jsxs("div",{className:"s-work-row-header",children:[d.jsxs("div",{className:"s-fleet-row-title-wrap",children:[d.jsx("div",{className:"s-avatar s-avatar-sm",style:{background:Ts(e.agentName??e.agentId)},children:(e.agentName??e.agentId)[0]?.toUpperCase()??"?"}),d.jsxs("div",{className:"s-fleet-row-title-copy",children:[d.jsxs("div",{className:"s-work-row-title-wrap",children:[d.jsx("span",{className:"s-work-row-title",children:e.agentName??e.agentId}),e.harness&&d.jsx("span",{className:"s-badge",children:e.harness})]}),d.jsxs("div",{className:"s-work-row-meta",style:{marginTop:2},children:[d.jsx("span",{className:"s-dot",style:{background:ec(e.agentState)}}),d.jsx("span",{children:ao(e.agentState)}),d.jsx("span",{children:i})]})]})]}),d.jsx("span",{className:`s-pill s-pill-${s7(e.status)}`,children:e.statusLabel})]}),d.jsx("p",{className:"s-work-row-summary",children:Yn(e.task)}),e.summary&&d.jsx("p",{className:"s-work-row-summary",style:{marginTop:8},children:Yn(e.summary)})]})}function o7({item:e,navigate:t}){const s=a7(e),r=e.kind==="question"?"question":e.state.replace(/_/g," "),i=e.acceptanceState!=="none"?e.acceptanceState.replace(/_/g," "):e.kind==="question"?"awaiting answer":"your move";return d.jsxs("div",{className:`s-work-row s-dashboard-fleet-row s-dashboard-fleet-attention-row${s?" s-work-row-clickable":""}`,onClick:s?()=>t(s):void 0,children:[d.jsxs("div",{className:"s-work-row-header",children:[d.jsx("div",{className:"s-work-row-title-wrap",children:d.jsx("span",{className:"s-work-row-title",children:e.title})}),d.jsx("span",{className:"s-pill s-pill-updated",children:"Needs your input"})]}),d.jsxs("div",{className:"s-work-row-meta",children:[d.jsx("span",{children:e.kind==="question"?"question":"work item"}),e.agentName&&d.jsx("span",{children:e.agentName}),d.jsx("span",{children:r}),d.jsx("span",{children:i}),d.jsx("span",{children:tt(e.updatedAt)})]}),e.summary&&d.jsx("p",{className:"s-work-row-summary",children:Yn(e.summary)})]})}function l7({item:e,navigate:t}){const s=i7(e);return d.jsxs("div",{className:`s-dashboard-activity-row${s?" s-dashboard-activity-row-clickable":""}`,onClick:s?()=>t(s):void 0,children:[d.jsx("div",{className:"s-avatar s-avatar-sm",style:{background:Ts(e.actorName??e.agentId??"system")},children:(e.actorName??e.agentId??"S")[0]?.toUpperCase()??"S"}),d.jsxs("div",{className:"s-dashboard-activity-body",children:[d.jsxs("div",{className:"s-dashboard-activity-header",children:[d.jsx("span",{className:"s-dashboard-activity-actor",children:e.actorName??"system"}),d.jsx("span",{className:"s-dashboard-activity-kind",children:oB(e.kind)}),d.jsx("span",{className:"s-time",children:tt(e.ts)})]}),(e.title||e.summary)&&d.jsx("p",{className:"s-dashboard-activity-summary",children:Yn(e.title??e.summary??"")}),e.title&&e.summary&&d.jsx("p",{className:"s-dashboard-activity-note",children:Yn(e.summary)})]})]})}function c7({navigate:e}){const[t,s]=b.useState(null),r=b.useCallback(async()=>{try{s(await ot("/api/fleet"))}catch{s(null)}},[]);b.useEffect(()=>{r()},[r]),Kn(r);const i=t?.activeAsks??[],l=t?.recentCompleted??[],c=t?.needsAttention??[],f=t?.activity??[],p=c.length>0?`${c.length} item${c.length===1?" is":"s are"} waiting on you. Clear ${c.length===1?"it":"those"} first, then monitor the rest of the queue.`:i.length>0?`${i.length} ask${i.length===1?" is":"s are"} currently in flight. The queue is clear of interruptions.`:l.length>0?"Nothing is actively running right now. Recent finishes are ready for review.":"No asks have moved through the fleet yet. Start work and this becomes the operations board.";return d.jsxs("div",{className:"s-home s-dashboard-screen s-dashboard-fleet",children:[d.jsx("div",{className:"s-dashboard-hero s-dashboard-hero-fleet",children:d.jsxs("div",{className:"s-dashboard-hero-copy",children:[d.jsxs("div",{className:"s-dashboard-hero-head",children:[d.jsx("h2",{children:"Fleet"}),t&&d.jsxs("span",{className:"s-time",children:["Updated ",tt(t.generatedAt)]})]}),d.jsx("p",{children:p}),d.jsxs("div",{className:"s-dashboard-summary-grid",children:[d.jsxs("div",{className:`s-dashboard-summary-card${(t?.totals.needsAttention??0)>0?" s-dashboard-summary-card-attention":""}`,children:[d.jsx("div",{className:"s-dashboard-summary-label",children:"Needs input"}),d.jsx("div",{className:"s-dashboard-summary-value",children:t?.totals.needsAttention??0}),d.jsx("div",{className:"s-dashboard-summary-meta",children:"Questions, reviews, or decisions waiting on you"})]}),d.jsxs("div",{className:"s-dashboard-summary-card",children:[d.jsx("div",{className:"s-dashboard-summary-label",children:"Active asks"}),d.jsx("div",{className:"s-dashboard-summary-value",children:t?.totals.active??0}),d.jsx("div",{className:"s-dashboard-summary-meta",children:"Currently in flight across the fleet"})]}),d.jsxs("div",{className:`s-dashboard-summary-card${(t?.totals.recentCompleted??0)>0?" s-dashboard-summary-card-finished":""}`,children:[d.jsx("div",{className:"s-dashboard-summary-label",children:"Finished"}),d.jsx("div",{className:"s-dashboard-summary-value",children:t?.totals.recentCompleted??0}),d.jsx("div",{className:"s-dashboard-summary-meta",children:"Recent completions and failures to review"})]}),d.jsxs("div",{className:"s-dashboard-summary-card",children:[d.jsx("div",{className:"s-dashboard-summary-label",children:"Activity"}),d.jsx("div",{className:"s-dashboard-summary-value",children:t?.totals.activity??0}),d.jsx("div",{className:"s-dashboard-summary-meta",children:"Recent events across the fleet"})]})]})]})}),d.jsxs("div",{className:"s-dashboard-fleet-stack",children:[d.jsxs("section",{className:`s-dashboard-panel${c.length>0?" s-dashboard-panel-attention":""}`,children:[d.jsx(Lu,{title:"Needs your input",detail:"Handle interruptions, pending answers, and review requests first.",count:c.length}),c.length===0?d.jsxs("div",{className:"s-empty",children:[d.jsx("p",{children:"Nothing is waiting on you"}),d.jsx("p",{children:"When agents ask a question or a work item needs review, it will land here first."})]}):d.jsx("div",{className:"s-work-list",children:c.map(h=>d.jsx(o7,{item:h,navigate:e},h.recordId))})]}),d.jsxs("div",{className:"s-dashboard-fleet-columns",children:[d.jsxs("section",{className:"s-dashboard-panel s-dashboard-panel-active",children:[d.jsx(Lu,{title:"Active asks",detail:"The asks still in flight across the fleet.",count:i.length}),i.length===0?d.jsxs("div",{className:"s-empty",children:[d.jsx("p",{children:"No active asks"}),d.jsx("p",{children:"New agent work will appear here while it is still in progress."})]}):d.jsx("div",{className:"s-work-list",children:i.map(h=>d.jsx(kS,{ask:h,navigate:e,section:"active"},h.invocationId))})]}),d.jsxs("section",{className:"s-dashboard-panel s-dashboard-panel-finished",children:[d.jsx(Lu,{title:"Recent finishes",detail:"Review completions and failures once the active queue is stable.",count:l.length}),l.length===0?d.jsxs("div",{className:"s-empty",children:[d.jsx("p",{children:"No recent finishes"}),d.jsx("p",{children:"Completed asks and failures will show up here once they settle."})]}):d.jsx("div",{className:"s-work-list",children:l.map(h=>d.jsx(kS,{ask:h,navigate:e,section:"finished"},h.invocationId))})]})]}),d.jsxs("section",{className:"s-dashboard-panel s-dashboard-panel-activity",children:[d.jsx(Lu,{title:"Recent activity",detail:"The broader event stream behind the queue.",count:f.length}),f.length===0?d.jsxs("div",{className:"s-empty",children:[d.jsx("p",{children:"No recent fleet activity"}),d.jsx("p",{children:"Messages, asks, and other agent activity will stream here."})]}):d.jsx("div",{className:"s-dashboard-activity-feed",children:f.slice(0,20).map(h=>d.jsx(l7,{item:h,navigate:e},h.id))})]})]})]})}function u7(){const e=window.getSelection();return e!==null&&e.toString().trim().length>0}function VC(e){u7()||e()}const d7={"agent.registered":"registered","agent.online":"came online","agent.offline":"went offline","flight.started":"started task","flight.completed":"completed task","message.sent":"sent message","message.received":"received message","collaboration.ask":"asked a question","collaboration.answer":"answered"};function f7(e){return d7[e]??e.replace(/[._]/g," ")}function h7({item:e,navigate:t}){const s=e.conversationId?{view:"conversation",conversationId:e.conversationId}:null,r=mo(),i=b.useCallback(l=>{const c=e.title??e.summary??"",f=window.getSelection()?.toString().trim(),p=[];f&&(p.push({kind:"action",label:"Copy Selection",shortcut:"⌘C",onSelect:()=>navigator.clipboard.writeText(f)}),p.push({kind:"separator"})),c&&p.push({kind:"action",label:"Copy Details",onSelect:()=>navigator.clipboard.writeText(c)}),e.actorName&&p.push({kind:"action",label:"Copy Actor Name",onSelect:()=>navigator.clipboard.writeText(e.actorName)}),s&&(p.push({kind:"separator"}),p.push({kind:"action",label:"Open Conversation",onSelect:()=>t(s)})),p.length>0&&r(l,p)},[e,s,t,r]);return d.jsxs("div",{className:`s-dashboard-activity-row${s?" s-dashboard-activity-row-clickable":""}`,onClick:s?()=>VC(()=>t(s)):void 0,onContextMenu:i,children:[d.jsx("div",{className:"s-dashboard-activity-time",children:tt(e.ts)}),d.jsxs("div",{className:"s-dashboard-activity-body",children:[d.jsxs("div",{className:"s-dashboard-activity-header",children:[d.jsx("span",{className:"s-dashboard-activity-actor",children:e.actorName??"system"}),d.jsx("span",{className:"s-dashboard-activity-kind",children:f7(e.kind)})]}),(e.title||e.summary)&&d.jsx("p",{className:"s-dashboard-activity-summary",children:Yn(e.title??e.summary??"")})]})]})}function p7({navigate:e}){const[t,s]=b.useState([]),r=b.useCallback(async()=>{try{const l=await ot("/api/activity");s(l)}catch{}},[]);b.useEffect(()=>{r()},[r]),Kn(r);const i=t.slice(0,20);return d.jsx("div",{className:"s-home s-dashboard-screen",children:d.jsx("div",{className:"s-dashboard-body s-dashboard-body-solo",children:d.jsxs("main",{className:"s-dashboard-main",children:[d.jsxs("div",{className:"s-dashboard-section-head",children:[d.jsx("h3",{children:"Activity"}),t.length>0&&d.jsx("span",{className:"s-dashboard-count",children:t.length})]}),i.length===0?d.jsxs("div",{className:"s-empty",children:[d.jsx("p",{children:"No activity yet"}),d.jsx("p",{children:"Events appear here as agents connect and work."})]}):d.jsx("div",{className:"s-dashboard-activity-feed",children:i.map(l=>d.jsx(h7,{item:l,navigate:e},l.id))}),t.length>20&&d.jsx("button",{type:"button",className:"s-dashboard-see-all",onClick:()=>e({view:"activity"}),children:"See all activity"})]})})})}const m7=b.lazy(()=>_l(()=>import("./arc.es-Bmw-NdXC.js"),[]).then(e=>({default:e.ArcDiagram})));function Ua(e){if(!e)return"";const t=e.replace(/^https?:\/\//,"").split("/")[0],[s]=t.split(":");return s.split(".")[0]}function g7(e){const t=e.hostName?.trim();if(t&&t.toLowerCase()!=="localhost")return Ua(t)||t;const s=e.dnsName?.trim().replace(/\.$/,"");return s?Ua(s)||s:Ua(e.name)||e.name}function ig(e){if(!e)return"";const t=e.replace(/^https?:\/\//,"").split("/")[0],[s]=t.split(":");return s.replace(/\.$/,"").toLowerCase()}function Zr(e){const t=ig(e);return t?t.split(".")[0]??t:""}function y7(e){return e.brokerUrl?Ua(e.brokerUrl):e.hostName?Ua(e.hostName):e.id.slice(0,10)}function v7(e,t){return Math.abs(e)>=Math.abs(t)?e>=0?["right","left"]:["left","right"]:t>=0?["bottom","top"]:["top","bottom"]}function b7(e,t){const s=Zr(t.hostName||t.name),r=Zr(e.localNode?.hostName||e.localNode?.name);return!!r&&s===r}function x7(e,t){const s=new Set([Zr(e.hostName),Zr(e.name),...e.addresses.map(i=>ig(i)),...e.addresses.map(i=>Zr(i))].filter(Boolean)),r=new Set([Zr(t.hostName),Zr(t.name),ig(t.brokerUrl),Zr(t.brokerUrl)].filter(Boolean));for(const i of s)if(r.has(i))return!0;return!1}function w7(e){if(!e.localNode)return null;const t=e.localNode.id,s=Object.values(e.nodes).filter(x=>x.id!==t),r=e.tailscale.peers.filter(x=>!b7(e,x)).filter(x=>!s.some(w=>x7(x,w))),i=[...s.map(x=>({kind:"mesh",peer:x})),...r.map(x=>({kind:"tailnet",peer:x}))],l=800,c=300,f=l/2,p=c/2,h={[t]:{x:f,y:p,size:"m"}},g={[t]:{icon:"Database",name:Ua(e.localNode.hostName)||e.localNode.name||"broker",subtitle:"this node",color:"violet"}},v=[];if(i.length===0)h.__placeholder={x:f+220,y:p,size:"m"},g.__placeholder={icon:"CircleDashed",name:"No peers yet",subtitle:"awaiting discovery",color:"zinc"},v.push({from:t,to:"__placeholder",fromAnchor:"right",toAnchor:"left",style:"pending"});else{const x=i.length,w=Math.min(170,100+x*10);i.forEach(({kind:T,peer:N},A)=>{const C=A/x*Math.PI*2-Math.PI/2,j=Math.round(f+w*Math.cos(C)),S=Math.round(p+w*Math.sin(C)),_=T==="mesh"?N.id:`tailnet:${N.id}`,R=T==="mesh"?Ua(N.hostName)||N.name||"peer":g7(N)||"tailnet",M=T==="mesh"?y7(N):N.online?N.addresses[0]??"tailnet only":"tailnet offline";h[_]={x:j,y:S,size:T==="mesh"?"m":"s"},g[_]={icon:T==="mesh"?"Database":"CircleDashed",name:R,subtitle:M,color:T==="mesh"?N.advertiseScope==="mesh"?"emerald":"zinc":N.online?"sky":"zinc"};const[O,I]=v7(j-f,S-p);v.push({from:t,to:_,fromAnchor:O,toAnchor:I,style:T==="mesh"?N.advertiseScope==="mesh"?"mesh":"local":N.online?"tailnet":"tailnet-offline"})})}return{layout:{width:l,height:c},nodes:h,nodeData:g,connectors:v,connectorStyles:{mesh:{color:"emerald",strokeWidth:2,label:"mesh"},local:{color:"zinc",strokeWidth:1.5},tailnet:{color:"sky",strokeWidth:1.5,dashed:!0,label:"tailnet"},"tailnet-offline":{color:"zinc",strokeWidth:1.25,dashed:!0,label:"tailnet"},pending:{color:"zinc",strokeWidth:1.5,dashed:!0}}}}function S7({mesh:e}){const t=b.useMemo(()=>w7(e),[e]);return t?d.jsx("div",{className:"s-mesh-topology",children:d.jsx(b.Suspense,{fallback:d.jsx("div",{className:"s-mesh-topology-fallback"}),children:d.jsx(m7,{data:t,className:"s-mesh-topology-canvas",mode:"light",theme:"cool",interactive:!0,showArcToggle:!1,defaultZoom:"fit",maxFitZoom:.95,hoverEffects:{dim:!0,lift:!0,glow:!0,highlightEdges:!0}})})}):null}function E7(e){return e.code==="local_only"?"notice":e.severity==="error"?"error":"warning"}function N7(e){switch(e.code){case"local_only":return"Not discoverable";case"mesh_loopback":return"Wrong address";case"discovery_unconfigured":return"No path";default:return"Offline"}}function T7(e){return e?e.replace(/^https?:\/\//,"").split("/")[0]??e:"Unavailable"}function j7(e){const t=e.hostName?.trim();if(t&&t.toLowerCase()!=="localhost")return t;const s=e.dnsName?.trim().replace(/\.$/,"");return s?s.split(".")[0]??s:e.name}function C7(e){return e==="mesh"?"Announced to mesh":e==="local"?"Local only":e||"Not advertised"}function R7(e){return e.identity.discoverable?"success":e.health.reachable?"warning":"danger"}function A7(e){return e.identity.discoverable?"Discoverable":e.health.reachable?"Not discoverable":"Broker offline"}function _7(e){return!e.health.reachable||e.issues.some(t=>t.severity==="error")?"danger":e.issues.length>0?"warning":"success"}function k7(e){return e.health.reachable?e.issues.some(t=>t.severity==="error")?"Degraded":e.issues.length>0?"Needs attention":"Healthy":"Broker unreachable"}function M7({issue:e}){const t=E7(e);return d.jsxs("article",{className:`sys-issue-card sys-issue-card-${t}`,children:[d.jsxs("div",{className:"sys-issue-head",children:[d.jsx("h3",{className:"sys-issue-title",children:e.title}),d.jsx("span",{className:`sys-chip sys-chip-${t==="error"?"failed":t}`,children:N7(e)})]}),d.jsx("p",{className:"sys-issue-body",children:e.summary}),(e.action||e.actionCommand)&&d.jsxs("div",{className:"sys-issue-action",children:[e.actionCommand&&d.jsx("code",{className:"sys-code-inline",children:e.actionCommand}),e.action&&d.jsx("span",{children:e.action})]})]})}function O7({navigate:e}){const[t,s]=b.useState(null),[r,i]=b.useState(!0),[l,c]=b.useState(!1),[f,p]=b.useState(!1),[h,g]=b.useState(null),[v,x]=b.useState(null),[w,T]=b.useState(null),N=b.useRef(null),A=b.useRef(0);b.useEffect(()=>{N.current=t},[t]);const C=b.useCallback(async(L="initial")=>{const Y=++A.current;!(N.current!==null)&&L!=="background"?(i(!0),x(null)):c(!0);try{const Q=await ot("/api/mesh");if(Y!==A.current)return;s(Q),x(null),T(Date.now())}catch(Q){if(Y!==A.current)return;x(Q instanceof Error?Q.message:String(Q))}finally{Y===A.current&&(i(!1),c(!1))}},[]);b.useEffect(()=>{C("initial")},[C]),b.useEffect(()=>{const L=setInterval(()=>{C("background")},1e4);return()=>clearInterval(L)},[C]);const j=b.useCallback(async()=>{p(!0),g(null);try{const L=await ot("/api/mesh/announce",{method:"POST",body:"{}"});s(L),N.current=L,x(null),T(Date.now()),g({tone:L.identity.discoverable?"success":"warning",title:L.identity.discoverable?"Mesh updated.":"Mesh updated, but still needs attention.",message:L.identity.discoverable?"This broker is now announced to the mesh.":"Mesh visibility was updated, but this broker still is not peer-reachable."})}catch(L){g({tone:"warning",title:"Could not announce broker.",message:L instanceof Error?L.message:String(L)})}finally{p(!1)}},[]),S=t?_7(t):"warning",_=t?k7(t):"Loading",R=t?Object.values(t.nodes):[],M=t?.localNode?.id,O=t?.localNode?.hostName?.toLowerCase(),I=R.filter(L=>L.id!==M),H=(t?.tailscale.peers??[]).filter(L=>{const Y=L.hostName?.toLowerCase();return!Y||Y==="localhost"?!0:!(O&&(Y===O||Y.startsWith(`${O.split(".")[0]}.`)))}),F=t?t.issues.length>0?t.issues:t.warnings.map((L,Y)=>({code:`fallback-${Y}`,severity:"warning",title:"Mesh notice",summary:L,action:null,actionCommand:null})):[],$=b.useMemo(()=>t?[{label:"Broker",value:t.health.reachable?"Reachable":"Unavailable",detail:t.health.error??T7(t.brokerUrl)},{label:"Discoverable",value:t.identity.discoverable?"Yes":"No",detail:t.identity.modeLabel},{label:"Mesh peers",value:`${I.length}`,detail:I.length>0?"Remote brokers in this mesh":"No remote brokers discovered"},{label:"Tailnet",value:t.tailscale.available?`${H.filter(L=>L.online).length}/${H.length}`:"Unavailable",detail:t.tailscale.available?"Online peers / visible peers":"Tailscale peers not detected"}]:[],[H,t,I.length]);return d.jsxs("div",{className:"sys-surface-page",children:[d.jsxs("div",{className:"sys-page-head",children:[d.jsxs("div",{className:"sys-page-title-group",children:[d.jsx("h2",{className:"sys-page-title",children:"Mesh"}),d.jsx("p",{className:"sys-page-subtitle",children:"Who this broker is, whether peers can discover it, and what the current mesh can see."})]}),d.jsxs("div",{className:"sys-page-actions",children:[d.jsx("span",{className:`sys-chip sys-chip-${S}`,children:_}),d.jsx("div",{className:"sys-sync-note",children:r?"Loading system snapshot...":v&&t?`Showing last confirmed snapshot from ${w?tt(w):"earlier"}`:w?`Confirmed ${tt(w)}`:"Waiting for first snapshot"}),d.jsx("button",{type:"button",className:"s-btn",disabled:r||l,onClick:()=>{C("manual")},children:l?"Refreshing...":"Refresh"})]})]}),v&&t&&d.jsxs("div",{className:"sys-banner sys-banner-warning",children:[d.jsx("strong",{children:"Mesh refresh failed."}),d.jsx("span",{children:v})]}),r&&!t&&d.jsxs("div",{className:"sys-panel sys-state-card",children:[d.jsx("h3",{className:"sys-state-title",children:"Loading mesh status"}),d.jsx("p",{className:"sys-state-body",children:"Inspecting broker reachability and peer discovery inputs."})]}),!r&&!t&&v&&d.jsxs("div",{className:"sys-panel sys-state-card sys-state-card-error",children:[d.jsx("h3",{className:"sys-state-title",children:"Mesh status is unavailable"}),d.jsx("p",{className:"sys-state-body",children:v}),d.jsx("div",{className:"sys-inline-actions",children:d.jsx("button",{type:"button",className:"s-btn",onClick:()=>{C("manual")},children:"Try again"})})]}),t&&d.jsxs(d.Fragment,{children:[d.jsxs("section",{className:"sys-panel sys-mesh-identity",children:[d.jsxs("div",{className:"sys-section-head",children:[d.jsxs("div",{children:[d.jsx("h3",{className:"sys-section-title",children:"This broker"}),d.jsx("p",{className:"sys-section-subtitle",children:"The identity peers will learn if they discover this machine."})]}),d.jsx("span",{className:`sys-chip sys-chip-${R7(t)}`,children:A7(t)})]}),d.jsxs("div",{className:"sys-detail-grid",children:[d.jsxs("div",{className:"sys-detail-card",children:[d.jsx("span",{className:"sys-detail-label",children:"Who Am I"}),d.jsx("span",{className:"sys-detail-value",children:t.identity.name??t.localNode?.name??"Unavailable"})]}),d.jsxs("div",{className:"sys-detail-card",children:[d.jsx("span",{className:"sys-detail-label",children:"Node ID"}),d.jsx("code",{className:"sys-detail-value",children:t.identity.nodeId??"Unavailable"})]}),d.jsxs("div",{className:"sys-detail-card",children:[d.jsx("span",{className:"sys-detail-label",children:"Mesh"}),d.jsx("code",{className:"sys-detail-value",children:t.identity.meshId??"Unassigned"})]}),d.jsxs("div",{className:"sys-detail-card",children:[d.jsx("span",{className:"sys-detail-label",children:"Mode"}),d.jsx("span",{className:"sys-detail-value",children:t.identity.modeLabel})]}),d.jsxs("div",{className:"sys-detail-card",children:[d.jsx("span",{className:"sys-detail-label",children:"Discoverable"}),d.jsx("span",{className:"sys-detail-value",children:t.identity.discoverable?"Yes":"No"})]}),d.jsxs("div",{className:"sys-detail-card",children:[d.jsx("span",{className:"sys-detail-label",children:"Announced As"}),d.jsx("code",{className:"sys-detail-value",children:t.identity.announceUrl??"Not announced"})]})]}),d.jsxs("div",{className:`sys-banner ${t.identity.discoverable?"sys-banner-success":"sys-banner-muted"}`,children:[d.jsx("strong",{children:"How peers find you."}),d.jsx("span",{children:t.identity.discoveryDetail})]}),!t.identity.discoverable&&t.health.reachable&&d.jsx("div",{className:"sys-inline-actions",children:d.jsx("button",{type:"button",className:"s-btn",disabled:f,onClick:()=>{j()},children:f?"Announcing...":"Announce on mesh"})}),h&&d.jsxs("div",{className:`sys-banner ${h.tone==="success"?"sys-banner-success":"sys-banner-warning"}`,children:[d.jsx("strong",{children:h.title}),d.jsx("span",{children:h.message})]})]}),d.jsx("div",{className:"sys-stat-grid",children:$.map(L=>d.jsxs("div",{className:"sys-stat-card",children:[d.jsx("span",{className:"sys-stat-label",children:L.label}),d.jsx("strong",{className:"sys-stat-value",children:L.value}),d.jsx("span",{className:"sys-stat-detail",children:L.detail})]},L.label))}),d.jsxs("section",{className:"sys-panel",children:[d.jsx("div",{className:"sys-section-head",children:d.jsxs("div",{children:[d.jsx("h3",{className:"sys-section-title",children:"Health notices"}),d.jsx("p",{className:"sys-section-subtitle",children:"Warnings and errors from the current broker and discovery snapshot."})]})}),F.length>0?d.jsx("div",{className:"sys-issue-grid",children:F.map((L,Y)=>d.jsx(M7,{issue:L},`${L.code}-${Y}`))}):d.jsxs("div",{className:"sys-list-empty",children:[d.jsx("h3",{children:"No active mesh warnings"}),d.jsx("p",{children:"The broker is reachable and discovery inputs look healthy from this page."})]})]}),d.jsxs("section",{className:"sys-panel",children:[d.jsx("div",{className:"sys-section-head",children:d.jsxs("div",{children:[d.jsx("h3",{className:"sys-section-title",children:"Topology"}),d.jsx("p",{className:"sys-section-subtitle",children:"Current broker relationships plus visible tailnet peers from this machine."})]})}),t.localNode?d.jsx(S7,{mesh:t}):d.jsxs("div",{className:"sys-list-empty",children:[d.jsx("h3",{children:"Topology unavailable"}),d.jsx("p",{children:"A local node record is required before the topology view can render."})]})]}),d.jsxs("section",{className:"sys-panel",children:[d.jsx("div",{className:"sys-section-head",children:d.jsxs("div",{children:[d.jsx("h3",{className:"sys-section-title",children:"Discovered peers"}),d.jsxs("p",{className:"sys-section-subtitle",children:["Remote brokers registered in ",t.meshId??"this mesh","."]})]})}),I.length===0?d.jsxs("div",{className:"sys-list-empty",children:[d.jsx("h3",{children:"No remote brokers discovered"}),d.jsx("p",{children:"This can be normal on a single-node setup. If you expect peers, check the health notices above."})]}):d.jsx("div",{className:"sys-list-grid",children:I.map(L=>d.jsxs("article",{className:"sys-list-card",children:[d.jsxs("div",{className:"sys-list-card-head",children:[d.jsx("h3",{className:"sys-list-card-title",children:L.name}),d.jsx("span",{className:`sys-chip sys-chip-${L.advertiseScope==="mesh"?"success":"neutral"}`,children:C7(L.advertiseScope)})]}),d.jsxs("div",{className:"sys-list-card-detail",children:[d.jsx("span",{className:"sys-detail-label",children:"Node id"}),d.jsx("code",{className:"sys-detail-value",children:L.id})]}),L.brokerUrl&&d.jsxs("div",{className:"sys-list-card-detail",children:[d.jsx("span",{className:"sys-detail-label",children:"Broker"}),d.jsx("code",{className:"sys-detail-value",children:L.brokerUrl})]}),d.jsxs("div",{className:"sys-list-card-detail",children:[d.jsx("span",{className:"sys-detail-label",children:"Last seen"}),d.jsx("span",{className:"sys-detail-value",children:L.lastSeenAt?tt(L.lastSeenAt):"Recently registered"})]})]},L.id))})]}),d.jsxs("section",{className:"sys-panel",children:[d.jsx("div",{className:"sys-section-head",children:d.jsxs("div",{children:[d.jsx("h3",{className:"sys-section-title",children:"Tailnet"}),d.jsx("p",{className:"sys-section-subtitle",children:"External Tailscale peers visible from this machine."})]})}),H.length===0?d.jsxs("div",{className:"sys-list-empty",children:[d.jsx("h3",{children:"No external tailnet peers"}),d.jsx("p",{children:t.tailscale.available?"Only this host is visible in the current tailnet snapshot.":"Tailscale peers were not detected on this machine."})]}):d.jsx("div",{className:"sys-list-grid",children:H.map(L=>d.jsxs("article",{className:"sys-list-card",children:[d.jsxs("div",{className:"sys-list-card-head",children:[d.jsx("h3",{className:"sys-list-card-title",children:j7(L)}),d.jsx("span",{className:`sys-chip sys-chip-${L.online?"success":"failed"}`,children:L.online?"Online":"Offline"})]}),d.jsxs("div",{className:"sys-list-card-detail",children:[d.jsx("span",{className:"sys-detail-label",children:"Address"}),d.jsx("code",{className:"sys-detail-value",children:L.addresses?.[0]??"Unavailable"})]}),d.jsxs("div",{className:"sys-list-card-detail",children:[d.jsx("span",{className:"sys-detail-label",children:"Platform"}),d.jsx("span",{className:"sys-detail-value",children:L.os??"Unknown"})]})]},L.id))})]})]})]})}const D7=[[/```[\s\S]*?```/g," "],[/`([^`]+)`/g,"$1"],[/!\[([^\]]*)\]\([^)]+\)/g,"$1"],[/\[([^\]]+)\]\([^)]+\)/g,"$1"],[/\*\*(.+?)\*\*/g,"$1"],[/__(.+?)__/g,"$1"],[new RegExp("(?<!\\*)\\*(?!\\*)([^*\\n]+)\\*(?!\\*)","g"),"$1"],[new RegExp("(?<!_)_(?!_)([^_\\n]+)_(?!_)","g"),"$1"],[/~~(.+?)~~/g,"$1"],[/^#{1,6}\s+/gm,""],[/^>\s?/gm,""],[/^[-*+]\s+/gm,""],[/^\d+\.\s+/gm,""],[/^---+\s*$/gm,""],[/^\s*\|.*\|\s*$/gm,""]];function z7(e,t=140){if(!e)return"";let s=e;for(const[r,i]of D7)s=s.replace(r,i);return s=s.replace(/\s+/g," ").trim(),s.length>t&&(s=`${s.slice(0,t-1)}…`),s}const BC="scout:sessions:lastViewed";function ZC(){if(typeof localStorage>"u")return{};try{const e=localStorage.getItem(BC);if(!e)return{};const t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function I7(e,t=Date.now()){const s=ZC();s[e]=t;try{localStorage.setItem(BC,JSON.stringify(s))}catch{}return s}function sm(e,t,s){return e?e>(s[t]??0):!1}const MS={direct:"DM",channel:"Channel",group_direct:"Group",thread:"Thread"},L7=new Set(["all","direct","channel","group_direct","thread"]);function og(e){return typeof window>"u"?"":new URLSearchParams(window.location.search).get(e)??""}function P7(e){if(typeof window>"u")return;const t=new URLSearchParams(window.location.search);for(const[r,i]of Object.entries(e))i===null||i===""?t.delete(r):t.set(r,i);const s=t.toString();window.history.replaceState(null,"",window.location.pathname+(s?`?${s}`:""))}function U7(){const e=og("view");return L7.has(e)?e:"all"}function $7(e){return e.kind==="direct"&&e.agentName?e.agentName:e.title.replace(/\s*<>\s*/g," · ")}function V7(e){if(!e)return null;const t=e.replace(/[\\/]+$/,"");return t?t.split(/[\\/]/).filter(Boolean).at(-1)??t:null}function B7(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return"";const t=e<1e12?e*1e3:e;return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(t)}function Z7({navigate:e}){const[t,s]=b.useState([]),[r,i]=b.useState(()=>U7()),[l,c]=b.useState(()=>og("q")),[f,p]=b.useState(()=>og("unread")==="1"),[h,g]=b.useState(()=>ZC()),[v,x]=b.useState(0),[w,T]=b.useState(null),N=b.useRef(null),A=b.useRef(null),C=mo(),j=b.useCallback(async()=>{T(null);try{const $=await ot("/api/sessions");s($.sort((L,Y)=>(Y.lastMessageAt??0)-(L.lastMessageAt??0)))}catch($){T($ instanceof Error?$.message:String($))}},[]);b.useEffect(()=>{j()},[j]),Kn(j);const[,S]=b.useState(0);b.useEffect(()=>{const $=setInterval(()=>S(L=>L+1),15e3);return()=>clearInterval($)},[]),b.useEffect(()=>{P7({view:r==="all"?null:r,q:l.trim()||null,unread:f?"1":null})},[r,l,f]);const _=b.useMemo(()=>Array.from(new Set(t.map($=>$.kind))),[t]),R=b.useMemo(()=>{const $={all:t.length};for(const L of t)$[L.kind]=($[L.kind]??0)+1;return $},[t]),M=b.useMemo(()=>t.filter($=>sm($.lastMessageAt,$.id,h)).length,[t,h]),O=b.useMemo(()=>{const $=l.trim().toLowerCase();return t.filter(L=>!(r!=="all"&&L.kind!==r||f&&!sm(L.lastMessageAt,L.id,h)||$&&![L.title,L.preview,L.agentName??"",L.harness??"",...L.participantIds].join(" ").toLowerCase().includes($)))},[t,r,f,h,l]);b.useEffect(()=>{v>=O.length&&x(Math.max(0,O.length-1))},[O.length,v]);const I=b.useCallback($=>{g(I7($.id)),e({view:"conversation",conversationId:$.id})},[e]);b.useEffect(()=>{function $(L){const Y=L.target,re=Y instanceof HTMLInputElement||Y instanceof HTMLTextAreaElement||Y instanceof HTMLElement&&Y.isContentEditable;if((L.metaKey||L.ctrlKey)&&L.key.toLowerCase()==="k"){L.preventDefault(),N.current?.focus(),N.current?.select();return}if(re){L.key==="Escape"&&Y===N.current&&N.current?.blur();return}if(L.key==="/"){L.preventDefault(),N.current?.focus();return}if(L.key==="j"||L.key==="ArrowDown"){L.preventDefault(),x(Q=>Math.min(O.length-1,Q+1));return}if(L.key==="k"||L.key==="ArrowUp"){L.preventDefault(),x(Q=>Math.max(0,Q-1));return}if(L.key==="Enter"||L.key==="o"){const Q=O[v];Q&&(L.preventDefault(),I(Q))}}return window.addEventListener("keydown",$),()=>window.removeEventListener("keydown",$)},[O,v,I]),b.useEffect(()=>{A.current?.querySelector(`[data-idx="${v}"]`)?.scrollIntoView({block:"nearest"})},[v]);const H=_.length>1,F=f?M>0?`${M} unread threads need attention.`:"No unread threads right now.":O.length===t.length?"Recent activity across every conversation.":`${O.length} conversations match the current filters.`;return d.jsxs("div",{className:"s-sessions-screen s-inbox-thread-redesign",children:[d.jsx("section",{className:"s-thread-overview",children:d.jsxs("div",{className:"s-thread-overview-copy",children:[d.jsxs("div",{className:"s-sessions-header s-thread-overview-heading",children:[d.jsx("h2",{className:"s-page-title",children:"Sessions"}),d.jsxs("span",{className:"s-meta s-tabular",children:[O.length," of ",t.length]})]}),d.jsx("p",{className:"s-thread-overview-summary",children:F})]})}),d.jsxs("section",{className:"s-thread-panel s-thread-panel-list",children:[d.jsxs("div",{className:"s-sessions-toolbar",children:[H&&d.jsxs("div",{className:"s-seg",role:"tablist","aria-label":"Session kind",children:[d.jsx(OS,{label:"All",count:R.all,pressed:r==="all",onClick:()=>i("all")}),_.map($=>d.jsx(OS,{label:MS[$]??$,count:R[$]??0,pressed:r===$,onClick:()=>i($)},$))]}),d.jsxs("button",{type:"button",className:`s-seg-standalone${f?" is-on":""}`,onClick:()=>p($=>!$),"aria-pressed":f,title:"Show unread only",children:[d.jsx("span",{className:"s-dot s-dot-sm","aria-hidden":"true"}),d.jsx("span",{children:"Unread"}),M>0&&d.jsx("span",{className:"s-seg-count",children:M})]}),d.jsxs("div",{className:"s-search",children:[d.jsx("input",{ref:N,type:"text",className:"s-search-input",placeholder:"Search conversations…",value:l,onChange:$=>c($.target.value),onKeyDown:$=>{$.key==="Escape"&&(l?c(""):$.target.blur())}}),d.jsx("kbd",{className:"s-search-kbd",children:"⌘K"})]})]}),w&&d.jsx("p",{className:"s-error",children:w}),O.length===0?d.jsxs("div",{className:"s-empty s-thread-empty-state",children:[d.jsx("p",{children:l||f?"No matches":"No conversations"}),d.jsx("p",{children:l?"Try a different search term.":f?"You're all caught up.":"Conversations appear here when agents communicate."})]}):d.jsx("div",{className:"s-inbox",ref:A,role:"listbox","aria-label":"Sessions",children:O.map(($,L)=>{const Y=$7($),re=($.agentName??Y)[0]?.toUpperCase()??"?",Q=sm($.lastMessageAt,$.id,h),z=L===v,Z=z7($.preview,160),B=MS[$.kind]??$.kind,ie=V7($.workspaceRoot);return d.jsxs("div",{"data-idx":L,"data-unread":Q?"true":"false","data-selected":z?"true":"false",className:"s-inbox-row",role:"option","aria-selected":z,tabIndex:z?0:-1,onClick:()=>{VC(()=>{x(L),I($)})},onMouseEnter:()=>x(L),onContextMenu:W=>{const D=window.getSelection()?.toString().trim(),P=[];D&&(P.push({kind:"action",label:"Copy Selection",shortcut:"⌘C",onSelect:()=>navigator.clipboard.writeText(D)}),P.push({kind:"separator"})),P.push({kind:"action",label:"Open Conversation",onSelect:()=>I($)}),P.push({kind:"action",label:"Copy Title",onSelect:()=>navigator.clipboard.writeText(Y)}),$.id&&P.push({kind:"action",label:"Copy Conversation ID",onSelect:()=>navigator.clipboard.writeText($.id)}),C(W,P)},children:[d.jsxs("div",{className:"s-session-avatar-wrap",children:[d.jsx("div",{className:"s-avatar",style:{background:Ts($.agentName??Y)},"aria-hidden":"true",children:re}),Q&&d.jsx("span",{className:"s-session-unread-dot","aria-hidden":"true"})]}),d.jsxs("div",{className:"s-inbox-body",children:[d.jsxs("div",{className:"s-inbox-header",children:[d.jsx("div",{className:"s-session-heading",children:d.jsx("span",{className:"s-inbox-name",title:Y,children:Y})}),d.jsx("div",{className:"s-session-trailing",children:$.lastMessageAt&&d.jsx("span",{className:"s-inbox-time s-tabular",title:B7($.lastMessageAt),children:tt($.lastMessageAt)})})]}),Z?d.jsx("p",{className:"s-inbox-preview",children:Z}):d.jsx("p",{className:"s-inbox-preview s-inbox-preview-empty",children:"No messages yet"}),d.jsxs("div",{className:"s-session-meta-row","aria-label":"Conversation details",children:[d.jsx("span",{className:"s-session-pill",children:B}),ie&&d.jsx("span",{className:"s-session-pill",title:$.workspaceRoot??void 0,children:ie}),$.currentBranch&&d.jsx("span",{className:"s-session-pill",title:$.currentBranch,children:$.currentBranch})]})]})]},$.id)})})]})]})}function OS({label:e,count:t,pressed:s,onClick:r}){return d.jsxs("button",{type:"button",className:"s-seg-btn","aria-pressed":s,onClick:r,children:[d.jsx("span",{children:e}),d.jsx("span",{className:"s-seg-count",children:t})]})}var Oa=(e=>(e[e.Border=-1]="Border",e[e.Data=0]="Data",e[e.Function=1]="Function",e[e.Position=2]="Position",e[e.Timing=3]="Timing",e[e.Alignment=4]="Alignment",e))(Oa||{});const H7=[0,1],HC=[1,0],FC=[2,3],qC=[3,2],F7={L:H7,M:HC,Q:FC,H:qC},q7=/^\d*$/,Y7=/^[A-Z0-9 $%*+./:-]*$/,rm="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:",vy=1,by=40,DS=3,G7=3,Pu=40,X7=10,YC=[[-1,7,10,15,20,26,18,20,24,30,18,20,24,26,30,22,24,28,30,28,28,28,28,30,30,26,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],[-1,13,22,18,26,18,24,18,22,20,24,28,26,24,20,30,24,28,28,26,30,28,30,30,30,30,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,17,28,22,16,22,28,26,26,24,28,24,28,22,24,24,30,28,28,26,28,30,24,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30]],GC=[[-1,1,1,1,1,1,2,2,2,2,4,4,4,4,4,6,6,6,6,7,8,8,9,9,10,12,12,12,13,14,15,16,17,18,19,19,20,21,22,24,25],[-1,1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49],[-1,1,1,2,2,4,4,6,6,8,8,8,10,12,16,12,17,16,18,21,20,23,23,25,27,29,34,34,35,38,40,43,45,48,51,53,56,59,62,65,68],[-1,1,1,2,4,4,4,5,6,8,8,11,11,16,16,18,16,19,21,25,25,25,34,30,32,35,37,40,42,45,48,51,54,57,60,63,66,70,74,77,81]];class K7{constructor(t,s,r,i){if(this.version=t,this.ecc=s,t<vy||t>by)throw new RangeError("Version value out of range");if(i<-1||i>7)throw new RangeError("Mask value out of range");this.size=t*4+17;const l=Array.from({length:this.size}).fill(!1);for(let f=0;f<this.size;f++)this.modules.push(l.slice()),this.types.push(l.map(()=>0));this.drawFunctionPatterns();const c=this.addEccAndInterleave(r);if(this.drawCodewords(c),i===-1){let f=1e9;for(let p=0;p<8;p++){this.applyMask(p),this.drawFormatBits(p);const h=this.getPenaltyScore();h<f&&(i=p,f=h),this.applyMask(p)}}this.mask=i,this.applyMask(i),this.drawFormatBits(i)}size;mask;modules=[];types=[];getModule(t,s){return t>=0&&t<this.size&&s>=0&&s<this.size&&this.modules[s][t]}drawFunctionPatterns(){for(let r=0;r<this.size;r++)this.setFunctionModule(6,r,r%2===0,Oa.Timing),this.setFunctionModule(r,6,r%2===0,Oa.Timing);this.drawFinderPattern(3,3),this.drawFinderPattern(this.size-4,3),this.drawFinderPattern(3,this.size-4);const t=this.getAlignmentPatternPositions(),s=t.length;for(let r=0;r<s;r++)for(let i=0;i<s;i++)r===0&&i===0||r===0&&i===s-1||r===s-1&&i===0||this.drawAlignmentPattern(t[r],t[i]);this.drawFormatBits(0),this.drawVersion()}drawFormatBits(t){const s=this.ecc[1]<<3|t;let r=s;for(let l=0;l<10;l++)r=r<<1^(r>>>9)*1335;const i=(s<<10|r)^21522;for(let l=0;l<=5;l++)this.setFunctionModule(8,l,cr(i,l));this.setFunctionModule(8,7,cr(i,6)),this.setFunctionModule(8,8,cr(i,7)),this.setFunctionModule(7,8,cr(i,8));for(let l=9;l<15;l++)this.setFunctionModule(14-l,8,cr(i,l));for(let l=0;l<8;l++)this.setFunctionModule(this.size-1-l,8,cr(i,l));for(let l=8;l<15;l++)this.setFunctionModule(8,this.size-15+l,cr(i,l));this.setFunctionModule(8,this.size-8,!0)}drawVersion(){if(this.version<7)return;let t=this.version;for(let r=0;r<12;r++)t=t<<1^(t>>>11)*7973;const s=this.version<<12|t;for(let r=0;r<18;r++){const i=cr(s,r),l=this.size-11+r%3,c=Math.floor(r/3);this.setFunctionModule(l,c,i),this.setFunctionModule(c,l,i)}}drawFinderPattern(t,s){for(let r=-4;r<=4;r++)for(let i=-4;i<=4;i++){const l=Math.max(Math.abs(i),Math.abs(r)),c=t+i,f=s+r;c>=0&&c<this.size&&f>=0&&f<this.size&&this.setFunctionModule(c,f,l!==2&&l!==4,Oa.Position)}}drawAlignmentPattern(t,s){for(let r=-2;r<=2;r++)for(let i=-2;i<=2;i++)this.setFunctionModule(t+i,s+r,Math.max(Math.abs(i),Math.abs(r))!==1,Oa.Alignment)}setFunctionModule(t,s,r,i=Oa.Function){this.modules[s][t]=r,this.types[s][t]=i}addEccAndInterleave(t){const s=this.version,r=this.ecc;if(t.length!==nd(s,r))throw new RangeError("Invalid argument");const i=GC[r[0]][s],l=YC[r[0]][s],c=Math.floor(lg(s)/8),f=i-c%i,p=Math.floor(c/i),h=[],g=aZ(l);for(let x=0,w=0;x<i;x++){const T=t.slice(w,w+p-l+(x<f?0:1));w+=T.length;const N=iZ(T,g);x<f&&T.push(0),h.push(T.concat(N))}const v=[];for(let x=0;x<h[0].length;x++)h.forEach((w,T)=>{(x!==p-l||T>=f)&&v.push(w[x])});return v}drawCodewords(t){if(t.length!==Math.floor(lg(this.version)/8))throw new RangeError("Invalid argument");let s=0;for(let r=this.size-1;r>=1;r-=2){r===6&&(r=5);for(let i=0;i<this.size;i++)for(let l=0;l<2;l++){const c=r-l,p=(r+1&2)===0?this.size-1-i:i;!this.types[p][c]&&s<t.length*8&&(this.modules[p][c]=cr(t[s>>>3],7-(s&7)),s++)}}}applyMask(t){if(t<0||t>7)throw new RangeError("Mask value out of range");for(let s=0;s<this.size;s++)for(let r=0;r<this.size;r++){let i;switch(t){case 0:i=(r+s)%2===0;break;case 1:i=s%2===0;break;case 2:i=r%3===0;break;case 3:i=(r+s)%3===0;break;case 4:i=(Math.floor(r/3)+Math.floor(s/2))%2===0;break;case 5:i=r*s%2+r*s%3===0;break;case 6:i=(r*s%2+r*s%3)%2===0;break;case 7:i=((r+s)%2+r*s%3)%2===0;break;default:throw new Error("Unreachable")}!this.types[s][r]&&i&&(this.modules[s][r]=!this.modules[s][r])}}getPenaltyScore(){let t=0;for(let l=0;l<this.size;l++){let c=!1,f=0;const p=[0,0,0,0,0,0,0];for(let h=0;h<this.size;h++)this.modules[l][h]===c?(f++,f===5?t+=DS:f>5&&t++):(this.finderPenaltyAddHistory(f,p),c||(t+=this.finderPenaltyCountPatterns(p)*Pu),c=this.modules[l][h],f=1);t+=this.finderPenaltyTerminateAndCount(c,f,p)*Pu}for(let l=0;l<this.size;l++){let c=!1,f=0;const p=[0,0,0,0,0,0,0];for(let h=0;h<this.size;h++)this.modules[h][l]===c?(f++,f===5?t+=DS:f>5&&t++):(this.finderPenaltyAddHistory(f,p),c||(t+=this.finderPenaltyCountPatterns(p)*Pu),c=this.modules[h][l],f=1);t+=this.finderPenaltyTerminateAndCount(c,f,p)*Pu}for(let l=0;l<this.size-1;l++)for(let c=0;c<this.size-1;c++){const f=this.modules[l][c];f===this.modules[l][c+1]&&f===this.modules[l+1][c]&&f===this.modules[l+1][c+1]&&(t+=G7)}let s=0;for(const l of this.modules)s=l.reduce((c,f)=>c+(f?1:0),s);const r=this.size*this.size,i=Math.ceil(Math.abs(s*20-r*10)/r)-1;return t+=i*X7,t}getAlignmentPatternPositions(){if(this.version===1)return[];{const t=Math.floor(this.version/7)+2,s=this.version===32?26:Math.ceil((this.version*4+4)/(t*2-2))*2,r=[6];for(let i=this.size-7;r.length<t;i-=s)r.splice(1,0,i);return r}}finderPenaltyCountPatterns(t){const s=t[1],r=s>0&&t[2]===s&&t[3]===s*3&&t[4]===s&&t[5]===s;return(r&&t[0]>=s*4&&t[6]>=s?1:0)+(r&&t[6]>=s*4&&t[0]>=s?1:0)}finderPenaltyTerminateAndCount(t,s,r){return t&&(this.finderPenaltyAddHistory(s,r),s=0),s+=this.size,this.finderPenaltyAddHistory(s,r),this.finderPenaltyCountPatterns(r)}finderPenaltyAddHistory(t,s){s[0]===0&&(t+=this.size),s.pop(),s.unshift(t)}}function dr(e,t,s){if(t<0||t>31||e>>>t)throw new RangeError("Value out of range");for(let r=t-1;r>=0;r--)s.push(e>>>r&1)}function cr(e,t){return(e>>>t&1)!==0}class xy{constructor(t,s,r){if(this.mode=t,this.numChars=s,this.bitData=r,s<0)throw new RangeError("Invalid argument");this.bitData=r.slice()}getData(){return this.bitData.slice()}}const W7=[1,10,12,14],J7=[2,9,11,13],Q7=[4,8,16,16];function XC(e,t){return e[Math.floor((t+7)/17)+1]}function KC(e){const t=[];for(const s of e)dr(s,8,t);return new xy(Q7,e.length,t)}function eZ(e){if(!WC(e))throw new RangeError("String contains non-numeric characters");const t=[];for(let s=0;s<e.length;){const r=Math.min(e.length-s,3);dr(Number.parseInt(e.substring(s,s+r),10),r*3+1,t),s+=r}return new xy(W7,e.length,t)}function tZ(e){if(!JC(e))throw new RangeError("String contains unencodable characters in alphanumeric mode");const t=[];let s;for(s=0;s+2<=e.length;s+=2){let r=rm.indexOf(e.charAt(s))*45;r+=rm.indexOf(e.charAt(s+1)),dr(r,11,t)}return s<e.length&&dr(rm.indexOf(e.charAt(s)),6,t),new xy(J7,e.length,t)}function nZ(e){return e===""?[]:WC(e)?[eZ(e)]:JC(e)?[tZ(e)]:[KC(rZ(e))]}function WC(e){return q7.test(e)}function JC(e){return Y7.test(e)}function sZ(e,t){let s=0;for(const r of e){const i=XC(r.mode,t);if(r.numChars>=1<<i)return Number.POSITIVE_INFINITY;s+=4+i+r.bitData.length}return s}function rZ(e){e=encodeURI(e);const t=[];for(let s=0;s<e.length;s++)e.charAt(s)!=="%"?t.push(e.charCodeAt(s)):(t.push(Number.parseInt(e.substring(s+1,s+3),16)),s+=2);return t}function lg(e){if(e<vy||e>by)throw new RangeError("Version number out of range");let t=(16*e+128)*e+64;if(e>=2){const s=Math.floor(e/7)+2;t-=(25*s-10)*s-55,e>=7&&(t-=36)}return t}function nd(e,t){return Math.floor(lg(e)/8)-YC[t[0]][e]*GC[t[0]][e]}function aZ(e){if(e<1||e>255)throw new RangeError("Degree out of range");const t=[];for(let r=0;r<e-1;r++)t.push(0);t.push(1);let s=1;for(let r=0;r<e;r++){for(let i=0;i<t.length;i++)t[i]=cg(t[i],s),i+1<t.length&&(t[i]^=t[i+1]);s=cg(s,2)}return t}function iZ(e,t){const s=t.map(r=>0);for(const r of e){const i=r^s.shift();s.push(0),t.forEach((l,c)=>s[c]^=cg(l,i))}return s}function cg(e,t){if(e>>>8||t>>>8)throw new RangeError("Byte out of range");let s=0;for(let r=7;r>=0;r--)s=s<<1^(s>>>7)*285,s^=(t>>>r&1)*e;return s}function oZ(e,t,s=1,r=40,i=-1,l=!0){if(!(vy<=s&&s<=r&&r<=by)||i<-1||i>7)throw new RangeError("Invalid value");let c,f;for(c=s;;c++){const v=nd(c,t)*8,x=sZ(e,c);if(x<=v){f=x;break}if(c>=r)throw new RangeError("Data too long")}for(const v of[HC,FC,qC])l&&f<=nd(c,v)*8&&(t=v);const p=[];for(const v of e){dr(v.mode[0],4,p),dr(v.numChars,XC(v.mode,c),p);for(const x of v.getData())p.push(x)}const h=nd(c,t)*8;dr(0,Math.min(4,h-p.length),p),dr(0,(8-p.length%8)%8,p);for(let v=236;p.length<h;v^=253)dr(v,8,p);const g=Array.from({length:Math.ceil(p.length/8)},()=>0);return p.forEach((v,x)=>g[x>>>3]|=v<<7-(x&7)),new K7(c,t,g,i)}function lZ(e,t){const{ecc:s="L",boostEcc:r=!1,minVersion:i=1,maxVersion:l=40,maskPattern:c=-1,border:f=1}=t||{},p=typeof e=="string"?nZ(e):Array.isArray(e)?[KC(e)]:void 0;if(!p)throw new Error(`uqr only supports encoding string and binary data, but got: ${typeof e}`);const h=oZ(p,F7[s],i,l,c,r),g=cZ({version:h.version,maskPattern:h.mask,size:h.size,data:h.modules,types:h.types},f);return t?.invert&&(g.data=g.data.map(v=>v.map(x=>!x))),t?.onEncoded?.(g),g}function cZ(e,t=1){if(!t)return e;const{size:s}=e,r=s+t*2;e.size=r,e.data.forEach(l=>{for(let c=0;c<t;c++)l.unshift(!1),l.push(!1)});for(let l=0;l<t;l++)e.data.unshift(Array.from({length:r},c=>!1)),e.data.push(Array.from({length:r},c=>!1));const i=Oa.Border;e.types.forEach(l=>{for(let c=0;c<t;c++)l.unshift(i),l.push(i)});for(let l=0;l<t;l++)e.types.unshift(Array.from({length:r},c=>i)),e.types.push(Array.from({length:r},c=>i));return e}function zS(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function uZ(e,t={}){const s=lZ(e,t),{pixelSize:r=10,whiteColor:i="white",blackColor:l="black"}=t,c=s.size*r,f=s.size*r;let p=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${f} ${c}">`;const h=[];for(let g=0;g<s.size;g++)for(let v=0;v<s.size;v++){const x=v*r,w=g*r;s.data[g][v]&&h.push(`M${x},${w}h${r}v${r}h-${r}z`)}return p+=`<rect fill="${zS(i)}" width="${f}" height="${c}"/>`,p+=`<path fill="${zS(l)}" d="${h.join("")}"/>`,p+="</svg>",p}function dZ(e){return e?e.replace(/^wss?:\/\//,"").replace(/:\d+$/,""):null}function IS(e){return e?e.length<=18?e:`${e.slice(0,10)}...${e.slice(-6)}`:null}function fZ(e){return e?e.status==="paired"||e.status==="connected"?"success":e.status==="error"||e.status==="closed"?"danger":"warning":"warning"}function hZ(e,t){if(!e)return null;const s=Math.max(0,Math.floor((e-t)/1e3));if(s===0)return null;if(s<60)return`${s}s`;const r=Math.floor(s/60),i=s%60;return i>0?`${r}m ${i}s`:`${r}m`}function LS({value:e}){const[t,s]=b.useState(!1),r=b.useCallback(()=>{navigator.clipboard.writeText(e).then(()=>{s(!0),setTimeout(()=>s(!1),1500)})},[e]);return d.jsx("button",{type:"button",className:"sys-copy-btn",onClick:r,title:"Copy",children:t?d.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:d.jsx("polyline",{points:"20 6 9 17 4 12"})}):d.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[d.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),d.jsx("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})}function pZ({navigate:e}){const[t,s]=b.useState(null),[r,i]=b.useState(""),[l,c]=b.useState(""),[f,p]=b.useState(!0),[h,g]=b.useState(!1),[v,x]=b.useState(!1),[w,T]=b.useState(null),[N,A]=b.useState(null),[C,j]=b.useState(null),[S,_]=b.useState(null),[R,M]=b.useState(()=>Date.now()),[O,I]=b.useState(null),H=b.useRef(null),F=b.useRef(0),$=b.useRef(null);b.useEffect(()=>{H.current=t},[t]),b.useEffect(()=>{$.current=w},[w]);const L=b.useCallback(async(ee="initial")=>{if(ee==="background"&&$.current)return;const ve=++F.current;!(H.current!==null)&&ee!=="background"?(p(!0),A(null)):g(!0);try{const pe=await ot(ee==="manual"?"/api/pairing-state/refresh":"/api/pairing-state");if(ve!==F.current)return;s(pe),A(null),_(Date.now())}catch(pe){if(ve!==F.current)return;A(pe instanceof Error?pe.message:String(pe))}finally{ve===F.current&&(p(!1),g(!1))}},[]),Y=b.useCallback(async()=>{try{const ee=await ot("/api/user");c(ee.name),i(ee.name),j(null)}catch(ee){j(ee instanceof Error?ee.message:String(ee))}},[]);b.useEffect(()=>{L("initial"),Y()},[L,Y]),b.useEffect(()=>{const ee=setInterval(()=>{L("background")},1e4);return()=>clearInterval(ee)},[L]),b.useEffect(()=>{if(!t?.pairing?.expiresAt)return;M(Date.now());const ee=setInterval(()=>{M(Date.now())},1e3);return()=>clearInterval(ee)},[t?.pairing?.expiresAt]);const re=b.useCallback(async()=>{x(!0),j(null);try{const ee=await ot("/api/user",{method:"POST",body:JSON.stringify({name:r})});c(ee.name),i(ee.name)}catch(ee){j(ee instanceof Error?ee.message:String(ee))}finally{x(!1)}},[r]),Q=b.useCallback(async ee=>{const ve=++F.current;T(ee),A(null);try{const he=await ot("/api/pairing/control",{method:"POST",body:JSON.stringify({action:ee})});if(ve!==F.current)return;s(he),_(Date.now())}catch(he){if(ve!==F.current)return;A(he instanceof Error?he.message:String(he))}finally{ve===F.current&&T(null)}},[]),z=b.useCallback(async ee=>{I(ee);try{await ot(`/api/pairing/peers/${encodeURIComponent(ee)}`,{method:"DELETE"}),L("manual")}catch{}finally{I(null)}},[L]),Z=b.useMemo(()=>{const ee=t?.pairing?.qrValue?.trim();return ee?uZ(ee,{border:2,ecc:"M",pixelSize:8}):null},[t?.pairing?.qrValue]),B=dZ(t?.pairing?.relay??t?.relay??null),ie=hZ(t?.pairing?.expiresAt,R),D=(t?.trustedPeers.find(ee=>ee.fingerprint===t.connectedPeerFingerprint)??null)?.name??IS(t?.connectedPeerFingerprint??null),P=fZ(t),G=r.trim()!==l,te=!f&&!t&&!!N;return d.jsxs("div",{className:"sys-surface-page sys-settings-page",children:[d.jsxs("div",{className:"sys-page-head",children:[d.jsxs("div",{className:"sys-page-title-group",children:[d.jsx("h2",{className:"sys-page-title",children:"Settings"}),d.jsx("p",{className:"sys-page-subtitle",children:"Identity, pairing, and trusted devices."})]}),d.jsxs("div",{className:"sys-page-actions",children:[t&&d.jsx("span",{className:`sys-chip sys-chip-${P}`,children:t.statusLabel}),d.jsx("div",{className:"sys-sync-note",children:f?"Loading...":N&&t?`Snapshot from ${S?tt(S):"earlier"}`:S?`Updated ${tt(S)}`:""}),d.jsx("button",{type:"button",className:"s-btn",disabled:f||h||!!w,onClick:()=>{L("manual")},children:h?"Refreshing...":"Refresh"})]})]}),N&&t&&d.jsxs("div",{className:"sys-banner sys-banner-warning",children:[d.jsx("strong",{children:"Refresh failed."}),d.jsx("span",{children:N})]}),C&&d.jsxs("div",{className:"sys-banner sys-banner-warning",children:[d.jsx("strong",{children:"Identity error."}),d.jsx("span",{children:C})]}),f&&!t&&d.jsxs("div",{className:"sys-panel sys-state-card",children:[d.jsx("h3",{className:"sys-state-title",children:"Loading settings"}),d.jsx("p",{className:"sys-state-body",children:"Checking relay status and trusted peers."})]}),te&&d.jsxs("div",{className:"sys-panel sys-state-card sys-state-card-error",children:[d.jsx("h3",{className:"sys-state-title",children:"Pairing unavailable"}),d.jsx("p",{className:"sys-state-body",children:N}),d.jsx("div",{className:"sys-inline-actions",children:d.jsx("button",{type:"button",className:"s-btn",onClick:()=>{L("manual")},children:"Try again"})})]}),d.jsxs("div",{className:"sys-settings-hero",children:[d.jsx("div",{className:"sys-settings-qr-col",children:Z?d.jsxs("div",{className:"sys-settings-qr-frame",children:[d.jsx("div",{className:"s-qr",dangerouslySetInnerHTML:{__html:Z}}),ie&&d.jsxs("span",{className:"sys-settings-qr-expires",children:["Expires in ",ie]})]}):d.jsx("div",{className:"sys-settings-qr-empty",children:d.jsx("span",{className:"sys-settings-qr-empty-label",children:t?.isRunning?"Waiting for QR...":"Start pairing to generate QR"})})}),d.jsxs("div",{className:"sys-settings-info-col",children:[d.jsxs("div",{className:"sys-input-row",children:[d.jsx("input",{className:"sys-input",type:"text",placeholder:"Your name",value:r,onChange:ee=>i(ee.target.value),onKeyDown:ee=>{ee.key==="Enter"&&G&&!v&&re()}}),d.jsx("button",{type:"button",className:"s-btn s-btn-primary",disabled:!G||v,onClick:()=>{re()},children:v?"Saving...":"Save"})]}),d.jsxs("div",{className:"sys-settings-kv-list",children:[t?.identityFingerprint&&d.jsxs("div",{className:"sys-settings-kv",children:[d.jsx("span",{className:"sys-settings-kv-label",children:"Fingerprint"}),d.jsxs("span",{className:"sys-settings-kv-value",children:[d.jsx("code",{children:t.identityFingerprint}),d.jsx(LS,{value:t.identityFingerprint})]})]}),B&&d.jsxs("div",{className:"sys-settings-kv",children:[d.jsx("span",{className:"sys-settings-kv-label",children:"Relay"}),d.jsxs("span",{className:"sys-settings-kv-value",children:[d.jsx("code",{children:B}),d.jsx(LS,{value:B})]})]}),t?.statusDetail&&d.jsxs("div",{className:"sys-settings-kv",children:[d.jsx("span",{className:"sys-settings-kv-label",children:"Status"}),d.jsx("span",{className:"sys-settings-kv-value sys-settings-kv-nowrap",children:t.statusDetail})]}),D&&d.jsxs("div",{className:"sys-settings-kv",children:[d.jsx("span",{className:"sys-settings-kv-label",children:"Connected"}),d.jsx("span",{className:"sys-settings-kv-value",children:D})]}),t?.secure&&d.jsxs("div",{className:"sys-settings-kv",children:[d.jsx("span",{className:"sys-settings-kv-label",children:"Security"}),d.jsx("span",{className:"sys-settings-kv-value",children:d.jsx("span",{className:"sys-chip sys-chip-success",style:{margin:0},children:"Noise XX"})})]})]}),t&&d.jsx("div",{className:"sys-inline-actions sys-settings-controls",children:t.isRunning?d.jsxs(d.Fragment,{children:[d.jsx("button",{type:"button",className:"s-btn",disabled:!!w,onClick:()=>{Q("restart")},children:w==="restart"?"Restarting...":"Restart"}),d.jsx("button",{type:"button",className:"s-btn",disabled:!!w,onClick:()=>{Q("stop")},children:w==="stop"?"Stopping...":"Stop"})]}):d.jsx("button",{type:"button",className:"s-btn s-btn-primary",disabled:!!w,onClick:()=>{Q("start")},children:w==="start"?"Starting...":"Start pairing"})})]})]}),t&&d.jsxs("section",{className:"sys-settings-peers",children:[d.jsx("div",{className:"sys-section-head",children:d.jsxs("div",{children:[d.jsx("h3",{className:"sys-section-title",children:"Trusted peers"}),d.jsxs("p",{className:"sys-section-subtitle",children:[t.trustedPeers.length," device",t.trustedPeers.length!==1?"s":""," paired with this broker."]})]})}),t.trustedPeers.length===0?d.jsxs("div",{className:"sys-list-empty",children:[d.jsx("h3",{children:"No trusted peers"}),d.jsx("p",{children:"Devices appear here after completing pairing."})]}):d.jsxs("table",{className:"sys-peers-table",children:[d.jsx("thead",{children:d.jsxs("tr",{children:[d.jsx("th",{children:"Device"}),d.jsx("th",{children:"Fingerprint"}),d.jsx("th",{children:"Paired"}),d.jsx("th",{children:"Last seen"}),d.jsx("th",{})]})}),d.jsx("tbody",{children:t.trustedPeers.map(ee=>{const ve=ee.fingerprint===t.connectedPeerFingerprint;return d.jsxs("tr",{className:ve?"sys-peers-row-connected":"",children:[d.jsx("td",{children:d.jsxs("span",{className:"sys-peers-name",children:[ee.name??IS(ee.fingerprint)??"Peer",ve&&d.jsx("span",{className:"sys-chip sys-chip-success sys-peers-badge",children:"Connected"})]})}),d.jsx("td",{children:d.jsx("code",{className:"sys-peers-fp",children:ee.fingerprint})}),d.jsx("td",{children:ee.pairedAtLabel??"—"}),d.jsx("td",{children:ee.lastSeenLabel??"—"}),d.jsx("td",{children:d.jsx("button",{type:"button",className:"sys-peers-remove",disabled:O===ee.fingerprint,onClick:()=>{z(ee.fingerprint)},title:"Remove peer",children:O===ee.fingerprint?"...":"Remove"})})]},ee.fingerprint)})})]})]})]})}function mZ(e){return e.attention==="interrupt"?"failed":e.state==="done"?"completed":e.attention==="badge"||e.state==="waiting"||e.state==="review"?"updated":"working"}function am(e){switch(e){case"review":return"In review";case"waiting":return"Waiting";case"working":return"Working";case"done":return"Done";default:return e.replace(/_/g," ")}}function gZ(e){switch(e){case"badge":return"Needs attention";case"interrupt":return"Blocked";default:return null}}function yZ(e){switch(e.kind){case"flight_started":return"flight started";case"flight_completed":return e.detailKind?`flight ${e.detailKind}`:"flight ended";case"message":return"message";default:return e.title??e.detailKind??"event"}}function PS(e){return e.kind==="message"?"message":e.kind==="flight_started"?"flight":e.kind==="flight_completed"?e.detailKind?.includes("fail")?"alert":"done":e.detailKind?.includes("interrupt")||e.detailKind?.includes("block")?"alert":"system"}function im({title:e,items:t}){return t.length===0?null:d.jsxs("section",{className:"s-work-fact-card",children:[d.jsx("div",{className:"s-work-fact-card-header",children:d.jsx("div",{className:"s-work-fact-card-title",children:e})}),d.jsx("div",{className:"s-work-fact-card-body",children:t.map(s=>d.jsxs("div",{className:"s-work-fact-row",children:[d.jsx("span",{className:"s-work-fact-label",children:s.label}),d.jsx("span",{className:"s-work-fact-value",children:s.value})]},s.label))})]})}function US({label:e,value:t,onClick:s}){return d.jsxs("button",{type:"button",className:"s-work-action-row",onClick:s,children:[d.jsx("span",{className:"s-work-action-row-label",children:e}),d.jsx("span",{className:"s-work-action-row-value",children:t})]})}function vZ(e){const t=e.split(".");return t[t.length-1]||e}function bZ({workId:e,navigate:t}){const[s,r]=b.useState(null),[i,l]=b.useState(null),[c,f]=b.useState(!1),p=b.useCallback(async()=>{l(null);try{const N=await ot(`/api/work/${encodeURIComponent(e)}`);r(N)}catch(N){l(N instanceof Error?N.message:String(N)),r(null)}finally{f(!0)}},[e]);if(b.useEffect(()=>{f(!1),p()},[p]),Kn(p),!c)return d.jsxs("div",{children:[d.jsx("button",{type:"button",className:"s-back",onClick:()=>t({view:"inbox"}),children:"← Back"}),d.jsx("div",{className:"s-empty",children:d.jsx("p",{children:"Loading…"})})]});if(!s)return d.jsxs("div",{children:[d.jsx("button",{type:"button",className:"s-back",onClick:()=>t({view:"inbox"}),children:"← Back"}),i&&d.jsx("p",{className:"s-error",children:i}),d.jsx("div",{className:"s-empty",children:d.jsx("p",{children:"Work item not found"})})]});const h=gZ(s.attention),g=s.ownerName??s.ownerId??"Unassigned",v=s.nextMoveOwnerName??s.nextMoveOwnerId??"—",x=[{label:"State",value:am(s.state)},{label:"Acceptance",value:s.acceptanceState.replace(/_/g," ")},{label:"Phase",value:s.currentPhase},...h?[{label:"Attention",value:h}]:[]],w=[{label:"Owner",value:g},{label:"Next move",value:v},...s.priority?[{label:"Priority",value:s.priority}]:[],{label:"Conversation",value:s.conversationId?"Attached":"None"}],T=[{label:"Case ID",value:s.id},{label:"Created",value:Ia(s.createdAt)},{label:"Updated",value:Ia(s.updatedAt)},{label:"Last activity",value:Ia(s.lastMeaningfulAt)}];return d.jsxs("div",{className:"s-work-detail s-work-casefile",children:[d.jsxs("div",{className:"s-work-casefile-topbar",children:[d.jsx("button",{type:"button",className:"s-back",onClick:()=>t({view:"inbox"}),children:"← Back"}),d.jsxs("span",{className:"s-work-casefile-record",children:["Case ",vZ(s.id)]})]}),i&&d.jsx("p",{className:"s-error",children:i}),d.jsx("section",{className:"s-work-casefile-hero",children:d.jsxs("div",{className:"s-work-casefile-hero-main",children:[d.jsxs("div",{className:"s-work-casefile-title-row",children:[d.jsx("h1",{className:"s-work-casefile-title",children:s.title}),d.jsx("span",{className:`s-pill s-pill-${mZ(s)}`,children:s.currentPhase})]}),s.lastMeaningfulSummary&&d.jsx("div",{className:"s-work-casefile-summary",children:Yn(s.lastMeaningfulSummary)}),d.jsxs("div",{className:"s-work-casefile-meta",children:[d.jsxs("span",{children:["Updated ",tt(s.updatedAt)]}),d.jsx("span",{children:g}),d.jsx("span",{children:am(s.state)}),h&&d.jsx("span",{children:h}),s.priority&&d.jsxs("span",{children:["Priority ",s.priority]})]})]})}),d.jsxs("div",{className:"s-work-casefile-layout",children:[d.jsxs("div",{className:"s-work-casefile-main",children:[d.jsxs("section",{className:"s-work-casefile-section",children:[d.jsx("div",{className:"s-agent-section-heading",children:d.jsx("h2",{className:"s-agent-section-title",children:"Case facts"})}),d.jsxs("div",{className:"s-work-fact-grid",children:[d.jsx(im,{title:"Status",items:x}),d.jsx(im,{title:"Assignment",items:w})]})]}),s.activeFlights.length>0&&d.jsxs("section",{className:"s-work-casefile-section",children:[d.jsx("div",{className:"s-agent-section-heading",children:d.jsx("h2",{className:"s-agent-section-title",children:"Flights"})}),d.jsx("div",{className:"s-work-flight-list",children:s.activeFlights.map(N=>d.jsxs("button",{type:"button",className:"s-work-flight-card",onClick:N.conversationId?()=>t({view:"conversation",conversationId:N.conversationId}):void 0,disabled:!N.conversationId,children:[d.jsxs("div",{className:"s-work-flight-card-header",children:[d.jsx("span",{className:"s-work-flight-card-title",children:N.agentName??N.agentId}),d.jsx("span",{className:"s-pill s-pill-working",children:N.state})]}),d.jsxs("div",{className:"s-work-flight-card-meta",children:[d.jsx("span",{children:N.startedAt?`Started ${tt(N.startedAt)}`:"Start time unavailable"}),N.completedAt&&d.jsxs("span",{children:["Completed ",tt(N.completedAt)]})]}),N.summary&&d.jsx("div",{className:"s-work-flight-card-copy",children:N.summary})]},N.id))})]}),s.childWork.length>0&&d.jsxs("section",{className:"s-work-casefile-section",children:[d.jsx("div",{className:"s-agent-section-heading",children:d.jsx("h2",{className:"s-agent-section-title",children:"Child work"})}),d.jsx("div",{className:"s-work-related-list",children:s.childWork.map(N=>d.jsxs("button",{type:"button",className:"s-work-related-card",onClick:()=>t({view:"work",workId:N.id}),children:[d.jsxs("div",{className:"s-work-related-card-header",children:[d.jsx("span",{className:"s-work-related-card-title",children:N.title}),d.jsx("span",{className:`s-pill s-pill-${N.attention==="interrupt"?"failed":"updated"}`,children:N.currentPhase})]}),d.jsxs("div",{className:"s-work-related-card-meta",children:[d.jsx("span",{children:N.ownerName??N.ownerId??"Unassigned"}),d.jsx("span",{children:am(N.state)}),d.jsx("span",{children:tt(N.lastMeaningfulAt)})]}),N.lastMeaningfulSummary&&d.jsx("div",{className:"s-work-related-card-copy",children:Yn(N.lastMeaningfulSummary)})]},N.id))})]}),d.jsxs("section",{className:"s-work-casefile-section",children:[d.jsx("div",{className:"s-agent-section-heading",children:d.jsx("h2",{className:"s-agent-section-title",children:"Timeline"})}),s.timeline.length===0?d.jsxs("div",{className:"s-empty",children:[d.jsx("p",{children:"No activity yet."}),d.jsx("p",{children:"Timeline events will appear once the case receives messages or coordination updates."})]}):d.jsx("div",{className:"s-work-timeline",children:s.timeline.map(N=>d.jsxs("button",{type:"button",className:`s-work-timeline-entry${N.conversationId?" s-work-timeline-entry-clickable":""}`,onClick:N.conversationId?()=>t({view:"conversation",conversationId:N.conversationId}):void 0,disabled:!N.conversationId,children:[d.jsx("span",{className:`s-work-timeline-marker s-work-timeline-marker-${PS(N)}`}),d.jsxs("div",{className:"s-work-timeline-content",children:[d.jsxs("div",{className:"s-work-timeline-header",children:[d.jsx("span",{className:"s-work-timeline-time",children:tt(N.at)}),d.jsx("span",{className:`s-work-timeline-kind s-work-timeline-kind-${PS(N)}`,children:yZ(N)})]}),d.jsx("div",{className:"s-work-timeline-actor",children:N.actorName??"system"}),N.title&&d.jsx("div",{className:"s-work-timeline-title",children:N.title}),N.summary&&d.jsx("div",{className:"s-work-timeline-summary",children:Yn(N.summary)}),d.jsx("div",{className:"s-work-timeline-stamp",children:Ia(N.at)})]})]},N.id))})]})]}),d.jsxs("aside",{className:"s-work-casefile-side",children:[d.jsx(im,{title:"Record",items:T}),d.jsxs("section",{className:"s-work-fact-card",children:[d.jsx("div",{className:"s-work-fact-card-header",children:d.jsx("div",{className:"s-work-fact-card-title",children:"Links"})}),d.jsxs("div",{className:"s-work-action-list",children:[s.conversationId?d.jsx(US,{label:"Conversation",value:"Open thread",onClick:()=>t({view:"conversation",conversationId:s.conversationId})}):d.jsx("div",{className:"s-work-action-list-empty",children:"No conversation attached."}),s.parentId&&s.parentTitle?d.jsx(US,{label:"Parent",value:s.parentTitle,onClick:()=>t({view:"work",workId:s.parentId})}):d.jsx("div",{className:"s-work-action-list-empty",children:"No parent work item."})]})]})]})]})]})}function xZ(){const{route:e,navigate:t}=Yt();return d.jsx(wZ,{children:SZ(e,t)})}function wZ({children:e}){return d.jsx("div",{style:{background:"var(--bg)",color:"var(--ink)",minHeight:"100%",height:"100%",display:"flex",flexDirection:"column"},children:e})}function SZ(e,t){switch(e.view){case"conversation":return d.jsx(ag,{conversationId:e.conversationId,navigate:t});case"agent-info":return d.jsx(AB,{conversationId:e.conversationId,navigate:t});case"settings":return d.jsx(pZ,{navigate:t});case"agents":return d.jsx(t7,{navigate:t,selectedAgentId:e.agentId,conversationId:e.conversationId});case"fleet":return d.jsx(c7,{navigate:t});case"sessions":return e.sessionId?d.jsx(ag,{conversationId:e.sessionId,navigate:t}):d.jsx(Z7,{navigate:t});case"mesh":return d.jsx(O7,{navigate:t});case"activity":return d.jsx(jB,{navigate:t});case"work":return d.jsx(bZ,{workId:e.workId,navigate:t});default:return d.jsx(p7,{navigate:t})}}function EZ(){const{route:e,agents:t}=Yt();if(e.view!=="agents")return null;const s=e.agentId?t.find(i=>i.id===e.agentId)??null:null;if(!s){const i=t.filter(l=>Fa(l.state)).length;return d.jsxs("div",{className:"flex flex-col h-full overflow-y-auto frame-scrollbar p-4 gap-4 text-[11px]",children:[d.jsx(_s,{label:"Total",value:`${t.length}`}),d.jsx(_s,{label:"Working",value:`${i}`}),d.jsx(_s,{label:"Available",value:`${t.length-i}`}),d.jsx("div",{className:"mt-2 text-[10px] font-mono uppercase tracking-[0.15em] text-white/25 leading-relaxed",children:"Select an agent from the roster to see its identity + session context here."})]})}const r=Fa(s.state);return d.jsxs("div",{className:"flex flex-col h-full overflow-y-auto frame-scrollbar p-4 gap-4 text-[11px]",children:[d.jsxs("div",{className:"flex items-center gap-3 pb-3 border-b border-white/[0.04]",children:[d.jsxs("div",{className:"relative w-10 h-10 rounded-full flex items-center justify-center text-[13px] font-mono text-black/80 shrink-0",style:{background:Ts(s.name)},children:[s.name[0]?.toUpperCase()??"?",r&&d.jsx("span",{className:"absolute -right-0.5 -bottom-0.5 w-2.5 h-2.5 rounded-full bg-emerald-400 ring-2 ring-neutral-950"})]}),d.jsxs("div",{className:"flex flex-col min-w-0 flex-1",children:[d.jsx("span",{className:"text-[13px] text-white/90 truncate",children:s.name}),s.handle&&d.jsxs("span",{className:"text-[10px] font-mono text-cyan-400/70",children:["@",s.handle]})]})]}),d.jsxs(Uu,{label:"State",children:[d.jsxs("div",{className:"flex items-baseline gap-2",children:[d.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${r?"bg-emerald-400":"bg-white/20"}`}),d.jsx("span",{className:"text-[12px] text-white/80 capitalize",children:ao(s.state)})]}),s.updatedAt&&d.jsxs("div",{className:"text-[10px] font-mono text-white/30 mt-1",children:["Updated ",tt(s.updatedAt)]})]}),d.jsxs(Uu,{label:"Identity",children:[d.jsx(_s,{label:"Class",value:s.agentClass}),s.role&&d.jsx(_s,{label:"Role",value:s.role}),s.harness&&d.jsx(_s,{label:"Harness",value:s.harness}),s.transport&&d.jsx(_s,{label:"Transport",value:s.transport})]}),(s.project||s.branch||s.cwd)&&d.jsxs(Uu,{label:"Project",children:[s.project&&d.jsx(_s,{label:"Name",value:s.project}),s.branch&&d.jsx(_s,{label:"Branch",value:s.branch}),s.cwd&&d.jsx(_s,{label:"Cwd",value:s.cwd})]}),s.capabilities.length>0&&d.jsx(Uu,{label:`Capabilities · ${s.capabilities.length}`,children:d.jsx("div",{className:"flex flex-wrap gap-1",children:s.capabilities.map(i=>d.jsx("span",{className:"text-[10px] font-mono text-white/50 px-1.5 py-0.5 rounded-sm bg-white/[0.04]",children:i},i))})})]})}function Uu({label:e,children:t}){return d.jsxs("div",{className:"flex flex-col",children:[d.jsx("div",{className:"text-[9px] font-mono uppercase tracking-[0.15em] text-white/30 mb-1.5",children:e}),t]})}function _s({label:e,value:t}){return d.jsxs("div",{className:"flex items-baseline justify-between py-0.5 gap-2",children:[d.jsx("span",{className:"text-[10px] font-mono uppercase tracking-wider text-white/30 shrink-0",children:e}),d.jsx("span",{className:"text-[11px] text-white/70 font-mono truncate",children:t})]})}function NZ(){const[e,t]=b.useState(null),s=b.useCallback(async()=>{try{t(await ot("/api/fleet"))}catch{}},[]);if(b.useEffect(()=>{s()},[s]),Kn(s),!e)return d.jsx("div",{className:"flex items-center justify-center h-full text-[11px] font-mono uppercase tracking-[0.15em] text-white/25",children:"Loading fleet…"});const r=e.totals;return d.jsxs("div",{className:"flex flex-col h-full overflow-y-auto frame-scrollbar p-4 gap-4 text-[11px]",children:[d.jsxs("div",{className:"text-[9px] font-mono uppercase tracking-[0.15em] text-white/30",children:["Updated ",tt(e.generatedAt)]}),d.jsx($u,{label:"Needs Input",value:r.needsAttention,emphasis:r.needsAttention>0?"warn":"muted"}),d.jsx($u,{label:"Active Asks",value:r.active}),d.jsx($u,{label:"Recent Finished",value:r.recentCompleted,emphasis:r.recentCompleted>0?"good":"muted"}),d.jsx($u,{label:"Activity",value:r.activity})]})}function $u({label:e,value:t,emphasis:s}){const r=s==="good"?"text-emerald-300/90":s==="warn"?"text-amber-300/90":s==="muted"?"text-white/40":"text-white/80";return d.jsxs("div",{className:"flex flex-col pb-3 border-b border-white/[0.04] last:border-b-0",children:[d.jsx("span",{className:`text-[24px] font-mono tabular-nums leading-none ${r}`,children:t}),d.jsx("span",{className:"text-[9px] font-mono uppercase tracking-[0.15em] text-white/30 mt-1",children:e})]})}function TZ(){const{agents:e,navigate:t}=Yt();if(e.length===0)return d.jsxs("div",{className:"flex flex-col h-full items-center justify-center px-4 text-center text-[11px] text-white/30 font-mono leading-relaxed",children:[d.jsx("div",{className:"mb-1 uppercase tracking-[0.15em]",children:"No agents"}),d.jsx("div",{children:"Connect an agent to see your roster here."})]});const s=e.filter(i=>Fa(i.state)),r=e.filter(i=>!Fa(i.state));return d.jsxs("div",{className:"flex flex-col h-full overflow-y-auto frame-scrollbar p-4 gap-4 text-[11px]",children:[s.length>0&&d.jsx($S,{label:"Online",count:s.length,children:s.map(i=>d.jsx(VS,{agent:i,navigate:t},i.id))}),r.length>0&&d.jsx($S,{label:"Standby",count:r.length,children:r.map(i=>d.jsx(VS,{agent:i,navigate:t,dim:!0},i.id))})]})}function $S({label:e,count:t,children:s}){return d.jsxs("div",{className:"flex flex-col",children:[d.jsxs("div",{className:"flex items-baseline justify-between mb-1.5",children:[d.jsx("span",{className:"text-[9px] font-mono uppercase tracking-[0.15em] text-white/30",children:e}),d.jsx("span",{className:"text-[9px] font-mono tabular-nums text-white/25",children:t})]}),d.jsx("div",{className:"flex flex-col gap-0.5",children:s})]})}function VS({agent:e,navigate:t,dim:s}){const r=Fa(e.state);return d.jsxs("button",{onClick:()=>t({view:"agents",agentId:e.id}),className:`group flex items-center gap-2.5 px-2 py-1.5 rounded-sm text-left transition-colors ${s?"opacity-60 hover:opacity-100 hover:bg-white/[0.03]":"hover:bg-white/[0.03]"}`,children:[d.jsxs("div",{className:"relative w-6 h-6 rounded-full flex items-center justify-center text-[10px] font-mono text-black/80 shrink-0",style:{background:Ts(e.name)},children:[e.name[0]?.toUpperCase()??"?",r&&d.jsx("span",{className:"absolute -right-0.5 -bottom-0.5 w-2 h-2 rounded-full bg-emerald-400 ring-2 ring-neutral-950"})]}),d.jsxs("div",{className:"flex flex-col min-w-0 flex-1",children:[d.jsx("span",{className:"text-[12px] text-white/80 truncate group-hover:text-white transition-colors",children:e.name}),d.jsx("span",{className:"text-[10px] font-mono text-white/30 truncate",children:ao(e.state)})]}),e.updatedAt&&d.jsx("span",{className:"text-[9px] font-mono tabular-nums text-white/25 shrink-0",children:tt(e.updatedAt)})]})}function jZ(){const{route:e}=Yt(),[t,s]=b.useState([]),r=b.useCallback(async()=>{try{s(await ot("/api/sessions"))}catch{}},[]);if(b.useEffect(()=>{r()},[r]),Kn(r),e.view!=="sessions")return null;const i=e.sessionId?t.find(l=>l.id===e.sessionId)??null:null;if(!i){const l=new Set(t.map(f=>f.kind)),c=t.filter(f=>f.currentBranch).length;return d.jsxs("div",{className:"flex flex-col h-full overflow-y-auto frame-scrollbar p-4 gap-4 text-[11px]",children:[d.jsx(ks,{label:"Total",value:`${t.length}`}),d.jsx(ks,{label:"Kinds",value:`${l.size}`}),d.jsx(ks,{label:"Branched",value:`${c}`}),d.jsx("div",{className:"mt-2 text-[10px] font-mono uppercase tracking-[0.15em] text-white/25 leading-relaxed",children:"Select a session from the list to see its context here."})]})}return d.jsxs("div",{className:"flex flex-col h-full overflow-y-auto frame-scrollbar p-4 gap-4 text-[11px]",children:[d.jsxs("div",{className:"pb-3 border-b border-white/[0.04]",children:[d.jsx("div",{className:"text-[13px] text-white/90 leading-snug",children:i.title}),d.jsx("div",{className:"text-[10px] font-mono uppercase tracking-wider text-cyan-400/70 mt-1",children:i.kind})]}),i.agentName&&d.jsxs(Vu,{label:"Agent",children:[d.jsx(ks,{label:"Name",value:i.agentName}),i.harness&&d.jsx(ks,{label:"Harness",value:i.harness})]}),(i.currentBranch||i.workspaceRoot)&&d.jsxs(Vu,{label:"Workspace",children:[i.currentBranch&&d.jsx(ks,{label:"Branch",value:i.currentBranch}),i.workspaceRoot&&d.jsx(ks,{label:"Root",value:i.workspaceRoot})]}),d.jsxs(Vu,{label:"Activity",children:[d.jsx(ks,{label:"Messages",value:`${i.messageCount}`}),i.lastMessageAt&&d.jsx(ks,{label:"Last",value:tt(i.lastMessageAt)}),i.participantIds.length>0&&d.jsx(ks,{label:"Participants",value:`${i.participantIds.length}`})]}),i.preview&&d.jsx(Vu,{label:"Preview",children:d.jsxs("div",{className:"text-[11px] text-white/60 leading-relaxed italic",children:['"',i.preview,'"']})})]})}function Vu({label:e,children:t}){return d.jsxs("div",{className:"flex flex-col",children:[d.jsx("div",{className:"text-[9px] font-mono uppercase tracking-[0.15em] text-white/30 mb-1.5",children:e}),t]})}function ks({label:e,value:t}){return d.jsxs("div",{className:"flex items-baseline justify-between py-0.5 gap-2",children:[d.jsx("span",{className:"text-[10px] font-mono uppercase tracking-wider text-white/30 shrink-0",children:e}),d.jsx("span",{className:"text-[11px] text-white/70 font-mono truncate",children:t})]})}function CZ(){const{route:e}=Yt(),t=e.view==="work"?e.workId:null,[s,r]=b.useState(null),i=b.useCallback(async()=>{if(!t){r(null);return}try{r(await ot(`/api/work/${encodeURIComponent(t)}`))}catch{r(null)}},[t]);if(b.useEffect(()=>{i()},[i]),Kn(i),e.view!=="work")return null;if(!s)return d.jsx("div",{className:"flex items-center justify-center h-full text-[11px] font-mono uppercase tracking-[0.15em] text-white/25 text-center px-4",children:"Loading work item…"});const l=AZ(s.state);return d.jsxs("div",{className:"flex flex-col h-full overflow-y-auto frame-scrollbar p-4 gap-4 text-[11px]",children:[d.jsxs("div",{className:"pb-3 border-b border-white/[0.04]",children:[d.jsxs("div",{className:"text-[9px] font-mono uppercase tracking-[0.15em] text-cyan-400/70 mb-1",children:["Case ",RZ(s.id)]}),d.jsx("div",{className:"text-[13px] text-white/90 leading-snug",children:s.title})]}),d.jsxs(Bu,{label:"State",children:[d.jsxs("div",{className:"flex items-baseline gap-2",children:[d.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${l.dot}`}),d.jsx("span",{className:`text-[12px] capitalize ${l.text}`,children:s.state.replace(/_/g," ")})]}),d.jsxs("div",{className:"text-[10px] font-mono text-white/30 mt-1",children:["Phase · ",s.currentPhase]})]}),d.jsxs(Bu,{label:"Ownership",children:[s.ownerName&&d.jsx(zi,{label:"Owner",value:s.ownerName}),s.nextMoveOwnerName&&d.jsx(zi,{label:"Next move",value:s.nextMoveOwnerName}),s.priority&&d.jsx(zi,{label:"Priority",value:s.priority})]}),d.jsxs(Bu,{label:"Activity",children:[d.jsx(zi,{label:"Children",value:`${s.activeChildWorkCount}`}),d.jsx(zi,{label:"Flights",value:`${s.activeFlightCount}`}),s.lastMeaningfulAt&&d.jsx(zi,{label:"Last update",value:tt(s.lastMeaningfulAt)})]}),s.attention!=="silent"&&d.jsx("div",{className:`text-[10px] font-mono uppercase tracking-wider px-2 py-1 rounded-sm ${s.attention==="interrupt"?"text-red-300/90 bg-red-500/10 border border-red-500/20":"text-amber-300/90 bg-amber-500/10 border border-amber-500/20"}`,children:s.attention==="interrupt"?"Interrupt":"Needs attention"}),s.lastMeaningfulSummary&&d.jsx(Bu,{label:"Latest",children:d.jsx("div",{className:"text-[11px] text-white/60 leading-relaxed italic",children:s.lastMeaningfulSummary})})]})}function RZ(e){return e.length>10?`${e.slice(0,8)}…`:e}function AZ(e){return/complete|done|finished/i.test(e)?{dot:"bg-emerald-400",text:"text-emerald-300/90"}:/fail|error/i.test(e)?{dot:"bg-red-400",text:"text-red-300/90"}:/block|wait|pause/i.test(e)?{dot:"bg-amber-400",text:"text-amber-300/90"}:/active|working|in[_-]?progress/i.test(e)?{dot:"bg-cyan-400",text:"text-cyan-300/90"}:{dot:"bg-white/30",text:"text-white/70"}}function Bu({label:e,children:t}){return d.jsxs("div",{className:"flex flex-col",children:[d.jsx("div",{className:"text-[9px] font-mono uppercase tracking-[0.15em] text-white/30 mb-1.5",children:e}),t]})}function zi({label:e,value:t}){return d.jsxs("div",{className:"flex items-baseline justify-between py-0.5 gap-2",children:[d.jsx("span",{className:"text-[10px] font-mono uppercase tracking-wider text-white/30 shrink-0",children:e}),d.jsx("span",{className:"text-[11px] text-white/70 font-mono truncate",children:t})]})}function _Z(){const{route:e}=Yt();switch(e.view){case"inbox":return d.jsx(TZ,{});case"agents":case"agent-info":return d.jsx(EZ,{});case"fleet":return d.jsx(NZ,{});case"sessions":case"conversation":return d.jsx(jZ,{});case"work":return d.jsx(CZ,{});default:return null}}const kZ=[{view:"inbox",label:"Home",icon:VV,target:{view:"inbox"}},{view:"agents",label:"Agents",icon:QV,target:{view:"agents"}},{view:"fleet",label:"Fleet",icon:ZV,target:{view:"fleet"}},{view:"sessions",label:"Sessions",icon:FV,target:{view:"sessions"}},{view:"activity",label:"Activity",icon:UV,target:{view:"activity"}},{view:"mesh",label:"Mesh",icon:YV,target:{view:"mesh"}}],MZ=[{view:"settings",label:"Settings",icon:WV,target:{view:"settings"}}];function OZ(){const{route:e,navigate:t}=Yt();return d.jsxs("div",{className:"flex flex-col h-full py-2",children:[d.jsx("nav",{className:"flex flex-col",children:kZ.map(s=>d.jsx(BS,{item:s,activeView:e.view,navigate:t},s.view))}),d.jsx("div",{className:"flex-1"}),d.jsx("nav",{className:"flex flex-col",children:MZ.map(s=>d.jsx(BS,{item:s,activeView:e.view,navigate:t},s.view))})]})}function BS({item:e,activeView:t,navigate:s}){const r=t===e.view,i=e.icon;return d.jsxs("button",{onClick:()=>s(e.target),className:`group w-full flex items-center gap-2.5 px-3 py-1.5 text-left transition-colors border-l-2 ${r?"bg-cyan-500/5 border-l-cyan-400/40 text-white/80":"border-l-transparent text-white/40 hover:bg-white/[0.02] hover:text-white/60"}`,children:[d.jsx(i,{size:13,strokeWidth:1.5,className:r?"text-cyan-400/70":"text-white/30 group-hover:text-white/50"}),d.jsx("span",{className:"text-[12px]",children:e.label})]})}function DZ(){const{onboarding:e}=Yt();return e?e.hasLocalConfig?e.hasOperatorName?e.hasProjectConfig?null:d.jsx(om,{children:d.jsx(LZ,{})}):d.jsx(om,{children:d.jsx(IZ,{})}):d.jsx(om,{children:d.jsx(zZ,{})}):null}function om({children:e}){return d.jsx("div",{style:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",overflow:"auto",background:"var(--bg)",color:"var(--ink)"},children:d.jsx("div",{style:{width:"100%",maxWidth:720,padding:"80px 72px",display:"flex",flexDirection:"column",gap:40},children:e})})}function wy({eyebrow:e,title:t,description:s}){return d.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[d.jsx("div",{style:PZ,children:e}),d.jsx("div",{style:UZ,children:t}),d.jsx("div",{style:$Z,children:s})]})}function Sy({primary:e,onPrimary:t,primaryDisabled:s,busy:r}){const{skipOnboarding:i}=Yt();return d.jsxs("div",{style:{display:"flex",alignItems:"center",gap:24,paddingTop:8},children:[d.jsx("button",{type:"button",onClick:t,disabled:s||r,style:{...BZ,opacity:s||r?.5:1,cursor:s||r?"default":"pointer"},children:r?"Working…":e}),d.jsx("button",{type:"button",onClick:i,style:ZZ,onMouseEnter:l=>{l.currentTarget.style.color="rgba(255,255,255,0.8)"},onMouseLeave:l=>{l.currentTarget.style.color="rgba(255,255,255,0.45)"},children:"Skip for now"})]})}function Ey({message:e}){return e?d.jsx("div",{style:{borderRadius:8,border:"1px solid rgba(239,68,68,0.35)",backgroundColor:"rgba(239,68,68,0.08)",color:"rgba(252,165,165,0.95)",padding:"12px 16px",fontSize:12,lineHeight:1.5},children:e}):null}function zZ(){const{onboarding:e,refreshOnboarding:t}=Yt(),[s,r]=b.useState(!1),[i,l]=b.useState(null),c=async()=>{r(!0),l(null);try{await ot("/api/onboarding/init",{method:"POST",body:"{}"}),await t()}catch(f){l(f instanceof Error?f.message:String(f))}finally{r(!1)}};return d.jsxs(d.Fragment,{children:[d.jsx(wy,{eyebrow:"First-run setup",title:"Welcome to Scout",description:d.jsxs(d.Fragment,{children:["Scout needs a local config before it can talk to the broker, the web app, and paired devices. This writes"," ",d.jsx("code",{style:dg,children:"~/.openscout/config.json"})," with sensible defaults — you can edit it any time."]})}),d.jsxs("ul",{style:HZ,children:[d.jsx(ZS,{label:"Local config (~/.openscout/config.json)",done:!1,hint:"missing"}),d.jsx(ZS,{label:".openscout/project.json in a repo",done:!!e?.hasProjectConfig,hint:e?.hasProjectConfig?e.projectRoot??void 0:"checked after setup"})]}),d.jsx(Ey,{message:i}),d.jsx(Sy,{primary:"Initialize Scout",onPrimary:()=>{c()},busy:s})]})}function IZ(){const{onboarding:e,refreshOnboarding:t}=Yt(),s=e?.operatorNameSuggestion??"",[r,i]=b.useState(s),[l,c]=b.useState(!1),[f,p]=b.useState(null);b.useEffect(()=>{!r&&s&&i(s)},[s,r]);const h=async()=>{const g=r.trim();if(!g){p("Name is required.");return}c(!0),p(null);try{await ot("/api/user",{method:"POST",body:JSON.stringify({name:g})}),await t()}catch(v){p(v instanceof Error?v.message:String(v))}finally{c(!1)}};return d.jsxs(d.Fragment,{children:[d.jsx(wy,{eyebrow:"Step 1 of 2",title:"What should we call you?",description:"Your name shows up on messages you send and in any agent that speaks for you. You can change it later in Settings."}),d.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[d.jsx("label",{style:sd,children:"Your name"}),d.jsx("input",{autoFocus:!0,value:r,onChange:g=>{i(g.target.value),p(null)},onKeyDown:g=>{g.key==="Enter"&&h()},placeholder:s||"Operator",style:ug}),s?d.jsx("div",{style:{fontSize:11,color:"rgba(255,255,255,0.4)",fontFamily:"var(--hud-font-mono)"},children:"Prefilled from your machine."}):null]}),d.jsx(Ey,{message:f}),d.jsx(Sy,{primary:"Continue",onPrimary:()=>{h()},busy:l,primaryDisabled:!r.trim()})]})}function LZ(){const{onboarding:e,refreshOnboarding:t}=Yt(),s=e?.currentDirectory??"",[r,i]=b.useState([s||"~/dev"]),[l,c]=b.useState(s),[f,p]=b.useState("claude"),[h,g]=b.useState(!1),[v,x]=b.useState(null),w=(C,j)=>{i(S=>S.map((_,R)=>R===C?j:_))},T=()=>i(C=>[...C,""]),N=C=>i(j=>j.filter((S,_)=>_!==C)),A=async()=>{const C=r.map(S=>S.trim()).filter(Boolean),j=l.trim();if(!j){x("Pick where Scout should anchor this context.");return}g(!0),x(null);try{await ot("/api/onboarding/project",{method:"POST",body:JSON.stringify({contextRoot:j,sourceRoots:C,defaultHarness:f})}),await t()}catch(S){x(S instanceof Error?S.message:String(S))}finally{g(!1)}};return d.jsxs(d.Fragment,{children:[d.jsx(wy,{eyebrow:"Step 2 of 2",title:"Where do your repos live?",description:d.jsxs(d.Fragment,{children:["Scout scans these folders for projects and anchors this context at"," ",d.jsx("code",{style:dg,children:"<context>/.openscout/project.json"}),"."]})}),d.jsxs("div",{style:lm,children:[d.jsx("label",{style:sd,children:"Scan folders"}),d.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[r.map((C,j)=>d.jsxs("div",{style:{display:"flex",gap:8},children:[d.jsx("input",{value:C,onChange:S=>w(j,S.target.value),placeholder:j===0?"~/dev":"Add another folder",style:{...ug,flex:1}}),d.jsx("button",{type:"button",onClick:()=>N(j),disabled:r.length<=1,style:{...HS,opacity:r.length<=1?.4:1,cursor:r.length<=1?"default":"pointer"},"aria-label":`Remove folder ${j+1}`,children:"−"})]},j)),d.jsx("button",{type:"button",onClick:T,style:{...HS,alignSelf:"flex-start"},children:"+ Add folder"})]})]}),d.jsxs("div",{style:lm,children:[d.jsx("label",{style:sd,children:"Context root"}),d.jsx("input",{value:l,onChange:C=>c(C.target.value),placeholder:"~/dev",style:ug}),d.jsxs("div",{style:VZ,children:["Scout writes ",d.jsx("code",{style:dg,children:".openscout/project.json"})," ","inside this folder."]})]}),d.jsxs("div",{style:lm,children:[d.jsx("label",{style:sd,children:"Default harness"}),d.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:["claude","codex"].map(C=>{const j=f===C;return d.jsxs("button",{type:"button",onClick:()=>p(C),style:{...FZ,borderColor:j?"var(--accent, #2dd4bf)":"rgba(255,255,255,0.12)",backgroundColor:j?"rgba(45,212,191,0.08)":"rgba(255,255,255,0.02)"},children:[d.jsx("div",{style:{fontSize:15,fontWeight:600,textTransform:"capitalize"},children:C}),d.jsx("div",{style:{fontSize:12,color:"rgba(255,255,255,0.55)",marginTop:6,lineHeight:1.5},children:C==="claude"?"Anthropic Claude Code — local CLI agent.":"OpenAI Codex — cloud agentic sandbox."})]},C)})})]}),d.jsx(Ey,{message:v}),d.jsx(Sy,{primary:"Create project",onPrimary:()=>{A()},busy:h,primaryDisabled:!l.trim()})]})}function ZS({label:e,done:t,hint:s}){return d.jsxs("li",{style:{display:"flex",alignItems:"flex-start",gap:16},children:[d.jsx("span",{style:{marginTop:2,width:20,height:20,borderRadius:999,display:"flex",alignItems:"center",justifyContent:"center",fontSize:11,fontWeight:700,flexShrink:0,backgroundColor:t?"rgba(34,197,94,0.15)":"rgba(239,68,68,0.12)",color:t?"#4ade80":"#f87171"},children:t?"✓":"•"}),d.jsxs("div",{style:{minWidth:0},children:[d.jsx("div",{style:{fontSize:13,lineHeight:1.5,color:t?"rgba(255,255,255,0.75)":"rgba(255,255,255,0.9)"},children:e}),s?d.jsx("div",{style:{fontSize:11,fontFamily:"var(--hud-font-mono)",color:"rgba(255,255,255,0.35)",marginTop:4,wordBreak:"break-all"},children:s}):null]})]})}const PZ={fontSize:11,fontFamily:"var(--hud-font-mono)",textTransform:"uppercase",letterSpacing:"0.18em",color:"rgba(255,255,255,0.4)"},UZ={fontSize:36,fontWeight:600,letterSpacing:"-0.01em",lineHeight:1.15},$Z={fontSize:15,lineHeight:1.75,color:"rgba(255,255,255,0.6)",maxWidth:580},lm={display:"flex",flexDirection:"column",gap:10},sd={fontSize:11,fontFamily:"var(--hud-font-mono)",textTransform:"uppercase",letterSpacing:"0.15em",color:"rgba(255,255,255,0.5)"},ug={width:"100%",padding:"10px 14px",fontSize:14,fontFamily:"var(--hud-font-mono)",color:"rgba(255,255,255,0.92)",backgroundColor:"rgba(255,255,255,0.04)",border:"1px solid rgba(255,255,255,0.12)",borderRadius:8,outline:"none",boxSizing:"border-box"},VZ={fontSize:12,color:"rgba(255,255,255,0.45)",lineHeight:1.6},dg={fontFamily:"var(--hud-font-mono)",fontSize:12,padding:"2px 6px",borderRadius:4,backgroundColor:"rgba(255,255,255,0.06)"},BZ={fontSize:13,fontWeight:600,padding:"12px 24px",borderRadius:10,backgroundColor:"var(--accent, #2dd4bf)",color:"#0b0d12",border:"none",transition:"opacity 0.15s ease"},HS={fontSize:13,fontWeight:500,padding:"10px 14px",borderRadius:8,backgroundColor:"rgba(255,255,255,0.04)",border:"1px solid rgba(255,255,255,0.12)",color:"rgba(255,255,255,0.85)",transition:"all 0.15s ease"},ZZ={fontSize:12,color:"rgba(255,255,255,0.45)",textDecoration:"underline dotted rgba(255,255,255,0.25)",textUnderlineOffset:4,background:"none",border:"none",cursor:"pointer",padding:"4px 2px",transition:"color 0.15s ease"},HZ={display:"flex",flexDirection:"column",gap:20,margin:0,padding:0,listStyle:"none"},FZ={textAlign:"left",padding:"16px 18px",borderRadius:12,border:"1px solid rgba(255,255,255,0.12)",color:"rgba(255,255,255,0.9)",cursor:"pointer",transition:"all 0.15s ease"};function qZ(){const{navigate:e,agents:t,reload:s}=Yt(),r=b.useCallback(async i=>{await ot(`/api/agents/${encodeURIComponent(i)}/interrupt`,{method:"POST",body:JSON.stringify({})})},[]);return b.useMemo(()=>{const i=[{id:"nav:home",label:"Go to Home",action:()=>e({view:"inbox"}),shortcut:"Cmd+1"},{id:"nav:agents",label:"Go to Agents",action:()=>e({view:"agents"}),shortcut:"Cmd+2"},{id:"nav:fleet",label:"Go to Fleet",action:()=>e({view:"fleet"}),shortcut:"Cmd+3"},{id:"nav:sessions",label:"Go to Sessions",action:()=>e({view:"sessions"}),shortcut:"Cmd+4"},{id:"nav:activity",label:"Go to Activity",action:()=>e({view:"activity"}),shortcut:"Cmd+5"},{id:"nav:mesh",label:"Go to Mesh",action:()=>e({view:"mesh"}),shortcut:"Cmd+6"},{id:"nav:settings",label:"Open Settings",action:()=>e({view:"settings"}),shortcut:"Cmd+,"},{id:"nav:pair",label:"Pair Device",action:()=>e({view:"settings"})},{id:"scout:reload",label:"Reload Agents",action:()=>{s()}}];for(const l of t)i.push({id:`scout:open:${l.id}`,label:`Open ${l.name}`,action:()=>e({view:"conversation",conversationId:ng(l.id)})}),i.push({id:`scout:send:${l.id}`,label:`Send message to ${l.name}`,action:()=>e({view:"conversation",conversationId:ng(l.id)})}),i.push({id:`scout:interrupt:${l.id}`,label:`Interrupt ${l.name}`,action:()=>{r(l.id)}});return i},[t,r,e,s])}function YZ(){const{agents:e,onlineCount:t}=Yt();return e.length===0?{label:"offline",color:"neutral"}:t===0?{label:`0/${e.length} agents`,color:"amber"}:{label:`${t}/${e.length} agents`,color:"emerald"}}const GZ={inbox:"Home",conversation:"Conversation","agent-info":"Agent",agents:"Agents",fleet:"Fleet",sessions:"Sessions",activity:"Activity",mesh:"Mesh",settings:"Settings",work:"Work"};function XZ(){const{route:e}=Yt(),t=GZ[e.view]??e.view;return b.createElement("span",{className:"text-[10px] font-mono uppercase tracking-wider text-white/40"},t)}function KZ(){const{navigate:e}=Yt();return b.createElement("button",{onClick:()=>e({view:"settings"}),className:"px-2 py-1 rounded-sm text-[11px] font-mono uppercase tracking-wider text-white/60 hover:text-white/90 hover:bg-white/[0.04] border border-white/[0.06] transition-colors"},"Pair device")}function WZ(){return"panel"}function JZ(){const{onboarding:e,onboardingSkipped:t,skipOnboarding:s}=Yt();if(!e)return null;if(t)return{active:!1,dismissible:!0};const r=!e.hasLocalConfig,i=!e.hasProjectConfig,l=!e.hasOperatorName;return{active:r||l||i,dismissible:!0,onDismiss:s}}const QZ=[{commandId:"nav:home",title:"Go to Home",description:"Navigate to the home screen showing the agent inbox",category:"navigation",keywords:["home","inbox","dashboard"],shortcut:"Cmd+1"},{commandId:"nav:agents",title:"Go to Agents",description:"Navigate to the agents roster showing all registered agents",category:"navigation",keywords:["agents","roster","list"],shortcut:"Cmd+2"},{commandId:"nav:fleet",title:"Go to Fleet",description:"Navigate to the fleet overview with agent status summary",category:"navigation",keywords:["fleet","overview","status"],shortcut:"Cmd+3"},{commandId:"nav:sessions",title:"Go to Sessions",description:"Navigate to the sessions list showing all active conversations",category:"navigation",keywords:["sessions","conversations","threads"],shortcut:"Cmd+4"},{commandId:"nav:activity",title:"Go to Activity",description:"Navigate to the activity feed showing recent events",category:"navigation",keywords:["activity","feed","events","log"],shortcut:"Cmd+5"},{commandId:"nav:mesh",title:"Go to Mesh",description:"Navigate to the mesh network view showing nodes and topology",category:"navigation",keywords:["mesh","network","nodes","peers","topology"],shortcut:"Cmd+6"},{commandId:"nav:settings",title:"Open Settings",description:"Open the settings screen for pairing, identity, and relay config",category:"settings",keywords:["settings","preferences","config","pair"],shortcut:"Cmd+,"},{commandId:"nav:pair",title:"Pair Device",description:"Open the device pairing flow to connect a mobile device",category:"settings",keywords:["pair","qr","device","phone","mobile"]},{commandId:"scout:reload",title:"Reload Agents",description:"Refresh the agent list and message state from the broker",category:"workspace",keywords:["reload","refresh","sync"]},{commandId:"scout:open:*",title:"Open Agent Conversation",description:"Open a direct message conversation with a specific agent. The commandId is scout:open:{agentId} where agentId comes from the current agent roster.",category:"navigation",keywords:["open","chat","conversation","dm","message"],params:[{name:"agentId",description:"The agent identifier to open",type:"string"}]},{commandId:"scout:send:*",title:"Send Message to Agent",description:"Send a text message to a specific agent. The commandId is scout:send:{agentId}. Requires a message parameter.",category:"workspace",keywords:["send","message","tell","ask","request"],params:[{name:"agentId",description:"The agent identifier to message",type:"string"},{name:"message",description:"The message body to send",type:"string"}]},{commandId:"scout:interrupt:*",title:"Interrupt Agent",description:"Send Ctrl-C to interrupt a working agent. The commandId is scout:interrupt:{agentId}.",category:"workspace",keywords:["stop","interrupt","cancel","halt","kill"],dangerous:!0,params:[{name:"agentId",description:"The agent identifier to interrupt",type:"string"}]}],eH={id:"openscout",name:"Scout",description:"All your agents, one message away. Scout is a control plane for managing coding agents — it shows their status, routes messages between them, and lets you steer, interrupt, or dispatch work to any agent in the fleet.",mode:"panel",Provider:aB,leftPanel:{title:"Scout",icon:b.createElement(XV,{size:12})},slots:{Content:xZ,LeftPanel:OZ,Inspector:_Z,Takeover:DZ},intents:QZ,hooks:{useCommands:qZ,useStatus:YZ,useNavCenter:XZ,useNavActions:KZ,useLayoutMode:WZ,useTakeover:JZ}},QC=document.getElementById("root");if(!QC)throw new Error("missing #root");x2.createRoot(QC).render(d.jsx(b.StrictMode,{children:d.jsx(_V,{app:eH})}));export{YS as F,qS as f,d as j,b as r};
|
|
140
|
+
`)}function _V({app:e,assistant:t=!0}){return d.jsx(e.Provider,{children:d.jsx(kV,{app:e,assistantEnabled:t})})}function kV({app:e,assistantEnabled:t}){const{navTotalHeight:s}=iy(),r=e.hooks.useCommands(),i=e.hooks.useStatus(),l=e.hooks.useSearch?.()??null,c=e.hooks.useNavCenter?.()??null,f=e.hooks.useNavActions?.()??null,p=e.hooks.useLayoutMode?.()??e.mode,h=e.hooks.useActiveToolHint?.()??null,g=e.hooks.useTakeover?.()??null,v=g?.active===!0,x=v&&g?.dismissible===!0,w=g?.onDismiss,T=e.slots.Takeover,[N,A]=ur(`appshell.${e.id}.left`,!1),[C,j]=ur(`appshell.${e.id}.right`,!1),[S,_]=ur(`appshell.${e.id}.leftW`,260),[R,M]=ur(`appshell.${e.id}.rightW`,280),[O,I]=b.useState({x:0,y:0}),[H,F]=b.useState(1),$=b.useCallback(oe=>{I(ge=>({x:ge.x+oe.x,y:ge.y+oe.y}))},[]),L=b.useCallback(oe=>{F(oe)},[]),[Y,re]=b.useState(!1),[Q,z]=b.useState(!1),[Z,B]=ur(`appshell.${e.id}.termH`,320),ie=!!e.slots.Terminal,W=b.useMemo(()=>{const oe=[];return ie&&oe.push("terminal"),t&&oe.push("assistant"),oe},[ie,t]),D=W[0]??"terminal",[P,G]=ur(`appshell.${e.id}.drawerTab`,D),te=W.includes(P)?P:D,[ee,ve]=b.useState(!1),[he,pe]=b.useState(new Set),xe=b.useCallback(oe=>{pe(ge=>{const me=new Set(ge);return me.has(oe)?me.delete(oe):me.add(oe),me})},[]),ke=b.useCallback(oe=>ge=>{ge.preventDefault();const me=ge.clientX,Ne=oe==="left"?S:R,Te=oe==="left"?_:M,qe=oe==="left"?1:-1,nt=zt=>{const $t=(zt.clientX-me)*qe;Te(Math.max(200,Math.min(500,Ne+$t)))},Ze=()=>{document.removeEventListener("mousemove",nt),document.removeEventListener("mouseup",Ze)};document.addEventListener("mousemove",nt),document.addEventListener("mouseup",Ze)},[S,R,_,M]),fe=b.useMemo(()=>{const oe=[{id:"shell:toggle-left",label:"Toggle Left Panel",shortcut:"Cmd+[",action:()=>A(ge=>!ge)},{id:"shell:toggle-right",label:"Toggle Right Panel",shortcut:"Cmd+]",action:()=>j(ge=>!ge)},{id:"shell:toggle-terminal",label:"Toggle Terminal",shortcut:"Ctrl+`",action:()=>re(ge=>!ge)}];return t&&oe.push({id:"shell:toggle-assistant",label:"Toggle Assistant",shortcut:"Cmd+J",action:()=>{G("assistant"),re(ge=>!ge||P!=="assistant")}}),oe},[A,j,t,P,G]),Me=b.useMemo(()=>[...r,...fe],[r,fe]);b.useEffect(()=>{const oe=ge=>{v||((ge.metaKey||ge.ctrlKey)&&ge.key==="k"&&(ge.preventDefault(),ve(!0)),(ge.metaKey||ge.ctrlKey)&&ge.key==="["&&(ge.preventDefault(),A(me=>!me)),(ge.metaKey||ge.ctrlKey)&&ge.key==="]"&&(ge.preventDefault(),j(me=>!me)),ge.ctrlKey&&ge.key==="`"&&(ge.preventDefault(),re(me=>!me)),t&&(ge.metaKey||ge.ctrlKey)&&ge.key==="j"&&(ge.preventDefault(),G("assistant"),re(me=>!(me&&te==="assistant"))))};return window.addEventListener("keydown",oe),()=>window.removeEventListener("keydown",oe)},[A,j,t,te,G,v]);const Ee=e.slots.Inspector,He=e.slots.RightPanel,ae=e.tools&&e.tools.length>0,se=d.jsxs(d.Fragment,{children:[Ee&&d.jsx(Ee,{}),!Ee&&He&&d.jsx(He,{}),ae&&d.jsx("div",{className:"border-t border-neutral-700/50",children:e.tools.map(oe=>{const ge=he.has(oe.id);return d.jsxs("div",{children:[d.jsxs("button",{onClick:()=>xe(oe.id),className:`w-full flex items-center gap-2 px-4 py-2.5 text-[11px] font-mono tracking-wider uppercase transition-colors hover:bg-white/5 ${h===oe.id?"text-emerald-400":"text-neutral-300"}`,children:[ge?d.jsx(R2,{size:10}):d.jsx(_2,{size:10}),d.jsx("span",{className:"text-neutral-400",children:oe.icon}),d.jsx("span",{className:"font-bold",children:oe.name})]}),ge&&d.jsx("div",{className:"px-4 pb-3",children:d.jsx(oe.Component,{})})]},oe.id)})})]}),ye=d.jsxs(d.Fragment,{children:[e.slots.LeftFooter&&d.jsx(e.slots.LeftFooter,{}),d.jsx(cL,{onOpenCommandPalette:()=>ve(!0)})]}),Se=b.useRef(null),we=b.useRef(null);b.useEffect(()=>{const oe=Se.current;oe&&(v?oe.setAttribute("inert",""):oe.removeAttribute("inert"))},[v]),b.useEffect(()=>{if(!v)return;const oe=we.current;if(oe&&(oe.querySelector('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])')??oe).focus(),!x)return;const ge=me=>{me.key==="Escape"&&(me.preventDefault(),w?.())};return window.addEventListener("keydown",ge),()=>window.removeEventListener("keydown",ge)},[v,x,w]);const Re=p==="panel"?{position:"absolute",top:s,bottom:28,left:N?0:S,right:C?0:R,overflow:"auto",transition:"left 200ms ease, right 200ms ease"}:{};return d.jsxs(d.Fragment,{children:[d.jsx("div",{ref:Se,"aria-hidden":v?!0:void 0,style:{display:"contents"},children:d.jsx(nL,{mode:p,panOffset:O,scale:H,onPan:$,onZoom:L,hud:d.jsxs(d.Fragment,{children:[d.jsx(iL,{title:e.name.toUpperCase(),search:l??void 0,center:c,actions:f}),d.jsx(R1,{side:"left",title:e.leftPanel?.title??"Navigation",icon:e.leftPanel?.icon,isCollapsed:N,onToggleCollapse:()=>A(!N),width:S,onResizeStart:ke("left"),footer:ye,headerActions:e.leftPanel?.headerActions&&d.jsx(e.leftPanel.headerActions,{}),children:e.slots.LeftPanel&&d.jsx(e.slots.LeftPanel,{})}),d.jsx(R1,{side:"right",title:e.rightPanel?.title??"Inspector",icon:e.rightPanel?.icon,isCollapsed:C,onToggleCollapse:()=>j(!C),width:R,onResizeStart:ke("right"),headerActions:e.rightPanel?.headerActions&&d.jsx(e.rightPanel.headerActions,{}),children:se}),d.jsx(lL,{status:i,onToggleTerminal:()=>re(oe=>!oe),isTerminalOpen:Y}),d.jsx("div",{className:"pointer-events-none",style:{position:"fixed",left:N?0:S,right:C?0:R,bottom:0,top:0,zIndex:45,transition:"left 200ms ease, right 200ms ease",transform:"translateZ(0)"},children:d.jsxs(dL,{isOpen:Y,onClose:()=>re(!1),onToggleMaximize:()=>z(oe=>!oe),isMaximized:Q,height:Z,onHeightChange:B,title:d.jsx(MV,{tabs:W,active:te,onSelect:G}),children:[te==="terminal"&&(e.slots.Terminal?d.jsx(e.slots.Terminal,{}):d.jsx("div",{className:"p-4 font-mono text-[12px] text-neutral-400",children:"No terminal content"})),te==="assistant"&&d.jsx(CV,{app:e,commands:r})]})}),d.jsx(uL,{isOpen:ee,onClose:()=>ve(!1),commands:Me})]}),children:d.jsx("div",{style:Re,className:"frame-scrollbar",children:d.jsx(e.slots.Content,{})})})}),v&&T?d.jsx("div",{ref:we,tabIndex:-1,role:"dialog","aria-modal":"true",style:{position:"fixed",inset:0,zIndex:80,outline:"none"},children:d.jsx(T,{})}):null]})}function MV({tabs:e,active:t,onSelect:s}){return e.length===0?null:d.jsx("div",{className:"flex items-center gap-0.5",children:e.map(r=>{const i=r===t,l=r==="terminal"?QS:WS,c=r==="terminal"?"TERMINAL":"ASSISTANT",f=r==="terminal"?"text-emerald-400":"text-cyan-400";return d.jsxs("button",{type:"button",onClick:()=>s(r),className:`flex items-center gap-1.5 px-2.5 py-1 rounded text-xs font-bold tracking-widest font-mono transition-colors ${i?`${f} bg-white/[0.04]`:"text-neutral-500 hover:text-neutral-300"}`,children:[d.jsx(l,{size:13}),d.jsx("span",{children:c})]},r)})})}const OC=(...e)=>e.filter((t,s,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===s).join(" ").trim();const OV=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const DV=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,s,r)=>r?r.toUpperCase():s.toLowerCase());const TS=e=>{const t=DV(e);return t.charAt(0).toUpperCase()+t.slice(1)};var zV={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const IV=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0;return!1};const LV=b.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:s=2,absoluteStrokeWidth:r,className:i="",children:l,iconNode:c,...f},p)=>b.createElement("svg",{ref:p,...zV,width:t,height:t,stroke:e,strokeWidth:r?Number(s)*24/Number(t):s,className:OC("lucide",i),...!l&&!IV(f)&&{"aria-hidden":"true"},...f},[...c.map(([h,g])=>b.createElement(h,g)),...Array.isArray(l)?l:[l]]));const ca=(e,t)=>{const s=b.forwardRef(({className:r,...i},l)=>b.createElement(LV,{ref:l,iconNode:t,className:OC(`lucide-${OV(TS(e))}`,`lucide-${e}`,r),...i}));return s.displayName=TS(e),s};const PV=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],UV=ca("activity",PV);const $V=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"r6nss1"}]],VV=ca("house",$V);const BV=[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]],ZV=ca("layers",BV);const HV=[["path",{d:"M16 10a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 14.286V4a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z",key:"1n2ejm"}],["path",{d:"M20 9a2 2 0 0 1 2 2v10.286a.71.71 0 0 1-1.212.502l-2.202-2.202A2 2 0 0 0 17.172 19H10a2 2 0 0 1-2-2v-1",key:"1qfcsi"}]],FV=ca("messages-square",HV);const qV=[["rect",{x:"16",y:"16",width:"6",height:"6",rx:"1",key:"4q2zg0"}],["rect",{x:"2",y:"16",width:"6",height:"6",rx:"1",key:"8cvhb9"}],["rect",{x:"9",y:"2",width:"6",height:"6",rx:"1",key:"1egb70"}],["path",{d:"M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3",key:"1jsf9p"}],["path",{d:"M12 12V8",key:"2874zd"}]],YV=ca("network",qV);const GV=[["path",{d:"M16.247 7.761a6 6 0 0 1 0 8.478",key:"1fwjs5"}],["path",{d:"M19.075 4.933a10 10 0 0 1 0 14.134",key:"ehdyv1"}],["path",{d:"M4.925 19.067a10 10 0 0 1 0-14.134",key:"1q22gi"}],["path",{d:"M7.753 16.239a6 6 0 0 1 0-8.478",key:"r2q7qm"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]],XV=ca("radio",GV);const KV=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],WV=ca("settings",KV);const JV=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["path",{d:"M16 3.128a4 4 0 0 1 0 7.744",key:"16gr8j"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],QV=ca("users",JV);function Qp(){const e=window.location.pathname.replace(/^\/+/,"").split("/").filter(Boolean);return e[0]==="agent"&&e[1]?{view:"agent-info",conversationId:decodeURIComponent(e[1])}:e[0]==="agents"&&e[1]&&e[2]==="c"&&e[3]?{view:"agents",agentId:decodeURIComponent(e[1]),conversationId:decodeURIComponent(e[3])}:e[0]==="agents"&&e[1]?{view:"agents",agentId:decodeURIComponent(e[1])}:e[0]==="agents"?{view:"agents"}:e[0]==="fleet"?{view:"fleet"}:e[0]==="c"&&e[1]?{view:"conversation",conversationId:decodeURIComponent(e[1])}:e[0]==="sessions"&&e[1]?{view:"sessions",sessionId:decodeURIComponent(e[1])}:e[0]==="sessions"?{view:"sessions"}:e[0]==="mesh"?{view:"mesh"}:e[0]==="activity"?{view:"activity"}:e[0]==="work"&&e[1]?{view:"work",workId:decodeURIComponent(e[1])}:e[0]==="settings"?{view:"settings"}:{view:"inbox"}}function eB(e){switch(e.view){case"inbox":return"/";case"conversation":return`/c/${encodeURIComponent(e.conversationId)}`;case"agent-info":return`/agent/${encodeURIComponent(e.conversationId)}`;case"agents":return e.agentId?e.conversationId?`/agents/${encodeURIComponent(e.agentId)}/c/${encodeURIComponent(e.conversationId)}`:`/agents/${encodeURIComponent(e.agentId)}`:"/agents";case"fleet":return"/fleet";case"sessions":return e.sessionId?`/sessions/${encodeURIComponent(e.sessionId)}`:"/sessions";case"mesh":return"/mesh";case"activity":return"/activity";case"work":return`/work/${encodeURIComponent(e.workId)}`;case"settings":return"/settings"}}function em(e){switch(e.view){case"conversation":return`conv:${e.conversationId}`;case"agent-info":return`agent-info:${e.conversationId}`;case"agents":return e.conversationId?`agent-conv:${e.conversationId}`:e.agentId?`agent:${e.agentId}`:"agents";case"sessions":return e.sessionId?`session:${e.sessionId}`:"sessions";case"work":return`work:${e.workId}`;default:return e.view}}function tB(){const[e,t]=b.useState(Qp),s=b.useRef({});b.useEffect(()=>{const i=()=>{const l=Qp();t(l),requestAnimationFrame(()=>{window.scrollTo(0,s.current[em(l)]??0)})};return window.addEventListener("popstate",i),()=>window.removeEventListener("popstate",i)},[]);const r=b.useCallback(i=>{s.current[em(Qp())]=window.scrollY,window.history.pushState(null,"",eB(i)),t(i),requestAnimationFrame(()=>{window.scrollTo(0,s.current[em(i)]??0)})},[]);return{route:e,navigate:r}}function DC(e){const t=e.match(/^dm\.operator\.(.+)$/);return t?t[1]:null}function ng(e){return`dm.operator.${e}`}async function ot(e,t){const s=await fetch(e,{...t,headers:{...t?.headers??{},...t?.body?{"content-type":"application/json"}:{}}});if(!s.ok){const i=await s.text();let l=i||`HTTP ${s.status}`;try{const c=JSON.parse(i);c?.error&&(l=c.error)}catch{}throw new Error(l)}const r=await s.text();if(r)return JSON.parse(r)}const nB=["hello","node.upserted","actor.registered","agent.registered","agent.endpoint.upserted","conversation.upserted","binding.upserted","message.posted","invocation.requested","flight.updated","delivery.planned","delivery.attempted","delivery.state.changed","collaboration.upserted","collaboration.event.appended","scout.dispatched"];function sB(e){try{return JSON.parse(e)}catch{return{kind:"unknown"}}}function Kn(e){const t=b.useRef(e);t.current=e,b.useEffect(()=>{let s=null,r=null,i=0;function l(){s=new EventSource("/api/events");const c=f=>{t.current(sB(f.data))};s.onopen=()=>{i=0},s.onmessage=c;for(const f of nB)s.addEventListener(f,c);s.onerror=()=>{s?.close(),i++;const f=Math.min(3e3*2**(i-1),6e4);r=setTimeout(l,f)}}return l(),()=>{s?.close(),r&&clearTimeout(r)}},[])}function ws(e){return e==="working"?"working":!e||e==="offline"?"offline":"available"}function Fa(e){return ws(e)!=="offline"}function ao(e){switch(ws(e)){case"working":return"Working";case"available":return"Available";default:return"Offline"}}const zC={current:null,setMenu:null};function mo(){return b.useCallback((e,t)=>{e.preventDefault(),e.stopPropagation(),zC.setMenu?.({position:{x:e.clientX,y:e.clientY},items:t})},[])}function rB({children:e}){const[t,s]=b.useState(null),r=b.useRef(null);zC.setMenu=s;const i=b.useCallback(()=>s(null),[]);return b.useEffect(()=>{if(!t)return;const l=()=>i(),c=p=>{p.key==="Escape"&&i()},f=()=>i();return window.addEventListener("mousedown",l,!0),window.addEventListener("keydown",c),window.addEventListener("scroll",f,!0),window.addEventListener("contextmenu",i,!0),()=>{window.removeEventListener("mousedown",l,!0),window.removeEventListener("keydown",c),window.removeEventListener("scroll",f,!0),window.removeEventListener("contextmenu",i,!0)}},[t,i]),b.useEffect(()=>{if(!t||!r.current)return;const l=r.current,c=l.getBoundingClientRect(),f=window.innerWidth,p=window.innerHeight;let h=t.position.x,g=t.position.y;h+c.width>f-8&&(h=f-c.width-8),g+c.height>p-8&&(g=p-c.height-8),h<8&&(h=8),g<8&&(g=8),l.style.left=`${h}px`,l.style.top=`${g}px`},[t]),t?d.jsxs(d.Fragment,{children:[e,d.jsx("div",{ref:r,className:"s-context-menu",style:{left:t.position.x,top:t.position.y},role:"menu",onMouseDown:l=>l.stopPropagation(),children:t.items.map((l,c)=>l.kind==="separator"?d.jsx("div",{className:"s-context-menu-sep",role:"separator"},c):d.jsxs("button",{type:"button",className:"s-context-menu-item",role:"menuitem",onClick:()=>{l.onSelect(),i()},children:[d.jsx("span",{className:"s-context-menu-label",children:l.label}),l.shortcut&&d.jsx("span",{className:"s-context-menu-shortcut",children:l.shortcut})]},c))})]}):d.jsx(d.Fragment,{children:e})}const IC=b.createContext(null);function Yt(){const e=b.useContext(IC);if(!e)throw new Error("useScout must be used inside ScoutProvider");return e}function aB({children:e}){const{route:t,navigate:s}=tB(),[r,i]=b.useState([]),[l,c]=b.useState([]),[f,p]=b.useState(null),[h,g]=b.useState(!1),v=b.useCallback(()=>g(!0),[]),x=b.useCallback(async()=>{const[A,C]=await Promise.allSettled([ot("/api/agents"),ot("/api/messages")]);A.status==="fulfilled"&&i(A.value),C.status==="fulfilled"&&c(C.value)},[]),w=b.useCallback(async()=>{try{const A=await ot("/api/onboarding/state");p(A)}catch{p({hasLocalConfig:!0,hasProjectConfig:!0,hasOperatorName:!0,localConfigPath:null,projectRoot:null,currentDirectory:null,operatorName:null,operatorNameSuggestion:null})}},[]);b.useEffect(()=>{x(),w()},[x,w]),Kn(x);const T=b.useMemo(()=>r.filter(A=>Fa(A.state)).length,[r]),N=b.useMemo(()=>({route:t,navigate:s,agents:r,messages:l,onlineCount:T,reload:x,onboarding:f,refreshOnboarding:w,onboardingSkipped:h,skipOnboarding:v}),[t,s,r,l,T,x,f,w,h,v]);return d.jsx(IC.Provider,{value:N,children:d.jsx("div",{"data-scout-theme":!0,style:{"--hud-font-sans":"'Inter', ui-sans-serif, system-ui, sans-serif","--hud-font-mono":"'JetBrains Mono', ui-monospace, Menlo, monospace","--hud-font-serif":"'Spectral', Georgia, serif"},children:d.jsx(rB,{children:e})})})}const iB={ask_sent:"asked",ask_replied:"replied",ask_failed:"failed",ask_working:"working",flight_created:"task started",flight_updated:"task updated",message_sent:"sent",message_received:"received",agent_online:"online",agent_offline:"offline"};function oB(e){return iB[e]??e.replace(/_/g," ")}const jS=["#6366f1","#8b5cf6","#0ea5e9","#14b8a6","#f59e0b","#ef4444","#ec4899","#10b981"];function Ts(e){let t=0;for(let s=0;s<e.length;s++)t=(t<<5)-t+e.charCodeAt(s)|0;return jS[Math.abs(t)%jS.length]}function ec(e){switch(ws(e)){case"working":return"var(--green)";case"available":return"var(--accent)";default:return"var(--dim)"}}const lB={workspace:"workspace",worktree:"workspace",branch:"workspace",profile:"profile",persona:"profile",harness:"harness",runtime:"harness",node:"node",host:"node"};function cB(e){return e.trim().replace(/^@+/,"").replace(/[.,!?;)\]]+$/,"")}function Is(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}const uB="scout";function dB(e){return lB[Is(e)]??null}function LC(e){const t=Is(e.definitionId),s=e.workspaceQualifier?Is(e.workspaceQualifier):void 0,r=e.profile?Is(e.profile):void 0,i=e.harness?Is(e.harness):void 0,l=e.nodeQualifier?Is(e.nodeQualifier):void 0;return t?{definitionId:t,...s?{workspaceQualifier:s}:{},...r?{profile:r}:{},...i?{harness:i}:{},...l?{nodeQualifier:l}:{}}:null}function fB(e){const t=e.split(".").filter(Boolean),s=t.shift();if(!s)return null;const r={definitionId:s},i=[];for(const l of t){if(l.includes(":")){const[c,f=""]=l.split(":",2),p=dB(c),h=Is(f);if(!p||!h)return null;p==="workspace"?r.workspaceQualifier=h:p==="profile"?r.profile=h:p==="harness"?r.harness=h:p==="node"&&(r.nodeQualifier=h);continue}i.push(l)}if(i.length===1){const l=Is(i[0]);if(!l)return null;r.workspaceQualifier=l}else if(i.length===2){const l=Is(i[0]),c=Is(i[1]);if(!l||!c)return null;r.workspaceQualifier||(r.workspaceQualifier=l),r.nodeQualifier||(r.nodeQualifier=c)}else if(i.length>2)return null;return pB(r,{raw:e})}function hB(e){const t=cB(e);return!t||t.includes("@")||t.includes("#")?null:fB(t)}function CS(e,t={}){const s=LC(e);if(!s)return t.includeSigil===!1?"":"@";const i=[`${t.includeSigil===!1?"":"@"}${s.definitionId}`];return s.workspaceQualifier&&i.push(s.workspaceQualifier),s.profile&&i.push(`profile:${s.profile}`),s.harness&&i.push(`harness:${s.harness}`),s.nodeQualifier&&i.push(`node:${s.nodeQualifier}`),i.join(".")}function pB(e,t={}){const s=LC(e);return s?{raw:t.raw??CS(s,{includeSigil:!1}),label:CS(s),definitionId:s.definitionId,...s.nodeQualifier?{nodeQualifier:s.nodeQualifier}:{},...s.workspaceQualifier?{workspaceQualifier:s.workspaceQualifier}:{},...s.profile?{profile:s.profile}:{},...s.harness?{harness:s.harness}:{}}:null}function mB(e){return gB(e).parsed}function gB(e){const t=Array.from(e.matchAll(/(^|\s)@([a-z0-9][a-z0-9._/:-]*)/gi)),s=new Map,r=[];for(const i of t){const l=i[2]??"",c=hB(l);if(!c){l&&r.push(`@${l}`);continue}s.set(c.label,c)}return{parsed:Array.from(s.values()),unparsed:Array.from(new Set(r))}}function yB(e,t){if(t.length===0)return[{kind:"text",value:e}];const s=new Map;for(const c of t)s.set(c.label.toLowerCase(),c);const r=[];let i=e;const l=/@([a-z0-9][a-z0-9._/:-]*)/i;for(;i.length>0;){const c=l.exec(i);if(!c||c.index===void 0){r.push({kind:"text",value:i});break}c.index>0&&r.push({kind:"text",value:i.slice(0,c.index)});const f=c[0],p=f.toLowerCase(),h=s.get(p);h?r.push({kind:"mention",identity:h}):r.push({kind:"text",value:f}),i=i.slice(c.index+f.length)}return r}function vB(e,t){const s=[],r=/\*\*(.+?)\*\*/g;let i=0,l,c=0;for(;(l=r.exec(e))!==null;)l.index>i&&s.push(d.jsx("span",{children:e.slice(i,l.index)},`${t}-${c++}`)),s.push(d.jsx("strong",{children:l[1]},`${t}-${c++}`)),i=l.index+l[0].length;return i<e.length&&s.push(d.jsx("span",{children:e.slice(i)},`${t}-${c++}`)),s.length>0?s:[d.jsx("span",{children:e},t)]}function Yn(e){if(!e)return e??"";const t=mB(e);return yB(e,t).flatMap((r,i)=>{if(r.kind==="text")return vB(r.value,i*100);const{identity:l}=r,f=l.definitionId===uB?"var(--accent)":Ts(l.definitionId);return d.jsx("span",{className:"s-mention",style:{"--mention-color":f},children:l.label},i)})}function tt(e){const t=e<1e12?e*1e3:e,s=Math.floor((Date.now()-t)/1e3);return s<5?"now":s<60?`${s}s`:s<3600?`${Math.floor(s/60)}m`:s<86400?`${Math.floor(s/3600)}h`:`${Math.floor(s/86400)}d`}function Ia(e){return new Date(e<1e12?e*1e3:e).toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit",second:"2-digit"})}const bB={"agent.registered":"registered","agent.online":"came online","agent.offline":"went offline","flight.started":"started task","flight.completed":"completed task","flight.updated":"updated task","message.sent":"sent message","message.received":"received message","collaboration.ask":"asked a question","collaboration.answer":"answered",ask_sent:"asked",ask_replied:"replied",ask_working:"working",flight_created:"started task",flight_updated:"updated task",message_sent:"sent",message_received:"received"},xB={presence:{label:"Presence",tone:"notice"},work:{label:"Execution",tone:"working"},message:{label:"Delivery",tone:"completed"},collaboration:{label:"Coordination",tone:"working"},system:{label:"System",tone:"notice"}};function PC(e){return bB[e]??e.replace(/[._]/g," ")}function wB(e){return e.startsWith("agent.")||e.includes("registered")||e.includes("online")||e.includes("offline")?"presence":e.startsWith("flight")||e.startsWith("ask_")?"work":e.startsWith("message")?"message":e.startsWith("collaboration")?"collaboration":"system"}function SB(e){return(e??"system").charAt(0).toUpperCase()}function UC(e){return e.length<=14?e:`${e.slice(0,8)}...${e.slice(-4)}`}function EB(e){if(!e)return null;const t=e.split("/").filter(Boolean);return t[t.length-1]??e}function NB(e){return`${e.actorName??"system"} ${PC(e.kind)}`}function TB(e){return e.workspaceRoot?`Recorded from ${e.workspaceRoot}.`:e.conversationId?`Linked to thread ${UC(e.conversationId)}.`:"No additional detail was captured for this event."}function jB({navigate:e}){const[t,s]=b.useState([]),[r,i]=b.useState(null),[l,c]=b.useState(!0),[f,p]=b.useState(!1),[h,g]=b.useState(null),[v,x]=b.useState(null),w=b.useRef([]),T=b.useRef(0),N=b.useRef(null),A=mo();b.useEffect(()=>{w.current=t},[t]);const C=b.useCallback(async(M="initial")=>{const O=++T.current;!(w.current.length>0)&&M!=="background"?(c(!0),g(null)):p(!0);try{const H=await ot("/api/activity");if(O!==T.current)return;s(H),g(null),x(Date.now()),i(F=>H.some($=>$.id===F)?F:null)}catch(H){if(O!==T.current)return;g(H instanceof Error?H.message:String(H))}finally{O===T.current&&(c(!1),p(!1))}},[]),j=b.useCallback(()=>{N.current||(N.current=setTimeout(()=>{N.current=null,C("background")},250))},[C]);b.useEffect(()=>(C("initial"),()=>{N.current&&clearTimeout(N.current)}),[C]),Kn(j);const S=b.useMemo(()=>{const M=new Set(t.map(I=>I.actorName??"system")),O=new Set(t.map(I=>I.conversationId).filter(I=>!!I));return[{label:"Events",value:`${t.length}`,detail:t.length>0?`Latest ${tt(t[0].ts)}`:"Waiting for records"},{label:"Actors",value:`${M.size}`,detail:M.size>0?"Distinct event owners":"No actors yet"},{label:"Threads",value:`${O.size}`,detail:O.size>0?"Conversation-linked records":"No linked threads"}]},[t]),_=!l&&t.length===0&&!!h,R=!l&&t.length===0&&!h;return d.jsxs("div",{className:"sys-surface-page",children:[d.jsxs("div",{className:"sys-page-head",children:[d.jsxs("div",{className:"sys-page-title-group",children:[d.jsx("h2",{className:"sys-page-title",children:"Activity"}),d.jsx("p",{className:"sys-page-subtitle",children:"Broker events, task execution, and collaboration handoffs."})]}),d.jsxs("div",{className:"sys-page-actions",children:[d.jsx("div",{className:"sys-sync-note",children:l?"Loading audit ledger...":h&&t.length>0?`Showing last confirmed snapshot from ${v?tt(v):"earlier"}`:v?`Updated ${tt(v)}`:"Waiting for first snapshot"}),d.jsx("button",{type:"button",className:"s-btn",disabled:l||f,onClick:()=>{C("manual")},children:f?"Refreshing...":"Refresh"})]})]}),d.jsx("div",{className:"sys-stat-grid",children:S.map(M=>d.jsxs("div",{className:"sys-stat-card",children:[d.jsx("span",{className:"sys-stat-label",children:M.label}),d.jsx("strong",{className:"sys-stat-value",children:M.value}),d.jsx("span",{className:"sys-stat-detail",children:M.detail})]},M.label))}),h&&t.length>0&&d.jsxs("div",{className:"sys-banner sys-banner-warning",children:[d.jsx("strong",{children:"Refresh failed."}),d.jsx("span",{children:h})]}),l&&t.length===0&&d.jsxs("div",{className:"sys-panel sys-state-card",children:[d.jsx("h3",{className:"sys-state-title",children:"Loading activity"}),d.jsx("p",{className:"sys-state-body",children:"Pulling the latest records from the broker database."})]}),_&&d.jsxs("div",{className:"sys-panel sys-state-card sys-state-card-error",children:[d.jsx("h3",{className:"sys-state-title",children:"Activity is unavailable"}),d.jsx("p",{className:"sys-state-body",children:h}),d.jsx("div",{className:"sys-inline-actions",children:d.jsx("button",{type:"button",className:"s-btn",onClick:()=>{C("manual")},children:"Try again"})})]}),R&&d.jsxs("div",{className:"sys-panel sys-state-card",children:[d.jsx("h3",{className:"sys-state-title",children:"No activity yet"}),d.jsx("p",{className:"sys-state-body",children:"Events appear here after agents register, send messages, or advance work."})]}),t.length>0&&d.jsx("div",{className:"sys-audit-list",children:t.map(M=>{const O=r===M.id,I=wB(M.kind),H=xB[I],F=EB(M.workspaceRoot),$=M.summary&&M.summary!==M.title?M.summary:TB(M);return d.jsxs("article",{className:`sys-audit-entry${O?" sys-audit-entry-expanded":""}`,onContextMenu:L=>{const Y=window.getSelection()?.toString().trim(),re=[];Y&&(re.push({kind:"action",label:"Copy Selection",shortcut:"⌘C",onSelect:()=>navigator.clipboard.writeText(Y)}),re.push({kind:"separator"}));const Q=M.title??M.summary??"";Q&&re.push({kind:"action",label:"Copy Details",onSelect:()=>navigator.clipboard.writeText(Q)}),M.actorName&&re.push({kind:"action",label:"Copy Actor",onSelect:()=>navigator.clipboard.writeText(M.actorName)}),re.push({kind:"action",label:"Copy Event ID",onSelect:()=>navigator.clipboard.writeText(M.id)}),M.conversationId&&(re.push({kind:"separator"}),re.push({kind:"action",label:"Open Thread",onSelect:()=>e({view:"conversation",conversationId:M.conversationId})})),A(L,re)},children:[d.jsxs("button",{type:"button",className:"sys-audit-toggle","aria-expanded":O,onClick:()=>i(O?null:M.id),children:[d.jsxs("div",{className:"sys-audit-stamp",children:[d.jsx("span",{className:"sys-audit-time",children:tt(M.ts)}),d.jsx("span",{className:"sys-audit-date",children:Ia(M.ts)})]}),d.jsx("div",{className:`sys-audit-marker sys-audit-marker-${H.tone}`,children:d.jsx("span",{})}),d.jsxs("div",{className:"sys-audit-body",children:[d.jsxs("div",{className:"sys-audit-topline",children:[d.jsx("span",{className:"sys-audit-category",children:H.label}),d.jsx("span",{className:"sys-audit-kind",children:PC(M.kind)})]}),d.jsx("h3",{className:"sys-audit-title",children:Yn(M.title??NB(M))}),d.jsx("p",{className:"sys-audit-summary",children:Yn($)}),d.jsxs("div",{className:"sys-audit-meta",children:[d.jsxs("span",{className:"sys-audit-meta-item",children:[d.jsx("span",{className:"sys-audit-avatar",style:{background:Ts(M.actorName??"system")},children:SB(M.actorName)}),M.actorName??"system"]}),F&&d.jsxs("span",{className:"sys-audit-meta-item",children:["Workspace ",F]}),M.conversationId&&d.jsxs("span",{className:"sys-audit-meta-item",children:["Thread ",UC(M.conversationId)]})]})]}),d.jsx("div",{className:"sys-audit-expand",children:O?"Close":"Details"})]}),O&&d.jsxs("div",{className:"sys-audit-details",children:[d.jsxs("div",{className:"sys-detail-grid",children:[d.jsxs("div",{className:"sys-detail-card",children:[d.jsx("span",{className:"sys-detail-label",children:"Event"}),d.jsx("code",{className:"sys-detail-value",children:M.kind})]}),d.jsxs("div",{className:"sys-detail-card",children:[d.jsx("span",{className:"sys-detail-label",children:"Recorded"}),d.jsx("span",{className:"sys-detail-value",children:Ia(M.ts)})]}),d.jsxs("div",{className:"sys-detail-card",children:[d.jsx("span",{className:"sys-detail-label",children:"Actor"}),d.jsx("span",{className:"sys-detail-value",children:M.actorName??"system"})]}),d.jsxs("div",{className:"sys-detail-card",children:[d.jsx("span",{className:"sys-detail-label",children:"Workspace"}),d.jsx("span",{className:"sys-detail-value",children:M.workspaceRoot??"Not attached"})]}),d.jsxs("div",{className:"sys-detail-card",children:[d.jsx("span",{className:"sys-detail-label",children:"Thread"}),d.jsx("span",{className:"sys-detail-value",children:M.conversationId??"Not attached"})]}),d.jsxs("div",{className:"sys-detail-card",children:[d.jsx("span",{className:"sys-detail-label",children:"Record id"}),d.jsx("code",{className:"sys-detail-value",children:M.id})]})]}),M.conversationId&&d.jsx("div",{className:"sys-inline-actions",children:d.jsx("button",{type:"button",className:"s-btn s-btn-sm",onClick:()=>e({view:"conversation",conversationId:M.conversationId}),children:"Open thread"})})]})]},M.id)})})]})}function CB(e){const t=e.split(".");return t[t.length-1]||e}function pl(e){return e?e.replace(/_/g," "):null}function RB({values:e}){return d.jsx("span",{className:"s-agent-token-list",children:e.map(t=>d.jsx("span",{className:"s-agent-token",children:t},t))})}function zu({title:e,items:t}){return t.length===0?null:d.jsxs("section",{className:"s-agent-profile-card",children:[d.jsx("div",{className:"s-agent-profile-card-header",children:d.jsx("div",{className:"s-agent-profile-card-title",children:e})}),d.jsx("div",{className:"s-agent-meta-card-body",children:t.map(s=>d.jsxs("div",{className:"s-agent-meta-row",children:[d.jsx("span",{className:"s-agent-meta-label",children:s.label}),d.jsx("span",{className:"s-agent-meta-value",children:s.value})]},s.label))})]})}function AB({conversationId:e,navigate:t}){const{agents:s}=Yt(),[r,i]=b.useState(null),[l,c]=b.useState(null),f=DC(e),p=b.useCallback(async()=>{c(null);try{const N=await ot(`/api/session/${encodeURIComponent(e)}`).catch(()=>null);i(N)}catch(N){c(N instanceof Error?N.message:String(N)),i(null)}},[e]);b.useEffect(()=>{p()},[p]),Kn(p);const h=r?.agentId??f,g=b.useMemo(()=>h?s.find(N=>N.id===h)??null:null,[s,h]);if(!g)return d.jsxs("div",{children:[d.jsx("button",{type:"button",className:"s-back",onClick:()=>t({view:"conversation",conversationId:e}),children:"← Back"}),l&&d.jsx("p",{className:"s-error",children:l}),d.jsx("div",{className:"s-empty",children:d.jsx("p",{children:"Agent not found"})})]});const v=[{label:"Agent ID",value:g.id},...g.handle?[{label:"Handle",value:`@${g.handle}`}]:[],{label:"Class",value:pl(g.agentClass)??"—"},...g.role?[{label:"Role",value:g.role}]:[],...g.selector?[{label:"Selector",value:g.selector}]:[]],x=[...g.project?[{label:"Project",value:g.project}]:[],...g.branch?[{label:"Branch",value:g.branch}]:[],...g.projectRoot?[{label:"Path",value:g.projectRoot}]:[],...g.cwd?[{label:"Working dir",value:g.cwd}]:[]],w=[{label:"State",value:ao(g.state)},...g.harness?[{label:"Harness",value:g.harness}]:[],...g.transport?[{label:"Transport",value:pl(g.transport)??g.transport}]:[],...g.wakePolicy?[{label:"Wake policy",value:pl(g.wakePolicy)??g.wakePolicy}]:[],...g.capabilities.length>0?[{label:"Capabilities",value:d.jsx(RB,{values:g.capabilities})}]:[]],T=[{label:"Conversation ID",value:e},...r?.title?[{label:"Title",value:r.title}]:[],...r?.workspaceRoot?[{label:"Workspace",value:r.workspaceRoot}]:[],...r?.currentBranch?[{label:"Session branch",value:r.currentBranch}]:[],...r?.messageCount!=null?[{label:"Messages",value:String(r.messageCount)}]:[],...r?.lastMessageAt?[{label:"Last message",value:Ia(r.lastMessageAt)}]:[],...g.harnessSessionId?[{label:"Harness session",value:g.harnessSessionId}]:[],...g.harnessLogPath?[{label:"Harness log",value:g.harnessLogPath}]:[]];return d.jsxs("div",{className:"s-agent-profile-page",children:[d.jsxs("div",{className:"s-agent-profile-page-topbar",children:[d.jsx("button",{type:"button",className:"s-back",onClick:()=>t({view:"conversation",conversationId:e}),children:"← Conversation"}),d.jsx("button",{type:"button",className:"s-btn",onClick:()=>t({view:"agents",agentId:g.id}),children:"Open in Agents"})]}),l&&d.jsx("p",{className:"s-error",children:l}),d.jsxs("section",{className:"s-agent-profile-hero",children:[d.jsx("div",{className:"s-agent-profile-hero-main",children:d.jsxs("div",{className:"s-agent-profile-hero-title-row",children:[d.jsx("div",{className:"s-avatar s-agent-profile-hero-avatar",style:{background:Ts(g.name)},children:g.name[0].toUpperCase()}),d.jsxs("div",{className:"s-agent-profile-hero-copy",children:[d.jsxs("div",{className:"s-agent-casefile-title-meta",children:[d.jsx("span",{className:"s-agent-casefile-record",children:CB(g.id)}),d.jsxs("span",{className:`s-agent-state-chip s-agent-state-chip-${ws(g.state)}`,children:[d.jsx("span",{className:"s-dot",style:{background:ec(g.state)}}),ao(g.state)]})]}),d.jsx("h1",{className:"s-agent-profile-hero-title",children:g.name}),d.jsx("p",{className:"s-agent-profile-hero-copyline",children:[g.handle?`@${g.handle}`:null,g.project,g.branch,pl(g.role)??pl(g.agentClass)].filter(Boolean).join(" • ")}),d.jsxs("p",{className:"s-agent-profile-hero-context",children:[r?.title?`Conversation: ${r.title}.`:"Attached to the current conversation.",g.updatedAt?` Updated ${tt(g.updatedAt)}.`:""]})]})]})}),d.jsx("div",{className:"s-agent-profile-hero-actions",children:d.jsx("button",{type:"button",className:"s-btn s-btn-primary",onClick:()=>t({view:"conversation",conversationId:e}),children:"Open conversation"})})]}),d.jsxs("div",{className:"s-agent-profile-grid",children:[d.jsx(zu,{title:"Identity",items:v}),d.jsx(zu,{title:"Workspace",items:x}),d.jsx(zu,{title:"Runtime",items:w}),d.jsx(zu,{title:"Conversation context",items:T})]})]})}function _B(e){return e.attention==="interrupt"?"failed":e.state==="done"?"completed":e.attention==="badge"||e.state==="waiting"||e.state==="review"?"updated":"working"}function kB(e){switch(e){case"review":return"In review";case"waiting":return"Waiting";case"working":return"Working";case"done":return"Done";default:return e.replace(/_/g," ")}}function MB(e){switch(e){case"badge":return"Needs attention";case"interrupt":return"Blocked";default:return null}}function OB({items:e,navigate:t,emptyTitle:s,emptyDetail:r}){if(e.length===0){const i=[{titleWidth:"56%",metaWidths:["18%","14%","16%"],summaryWidth:"74%"},{titleWidth:"48%",metaWidths:["16%","20%","12%"],summaryWidth:"62%"}];return d.jsxs("div",{className:"s-work-empty-state",children:[d.jsxs("div",{className:"s-work-empty-copy",children:[d.jsx("p",{className:"s-work-empty-kicker",children:"Quiet for now"}),d.jsx("p",{className:"s-work-empty-title",children:s}),r&&d.jsx("p",{className:"s-work-empty-detail",children:r})]}),d.jsx("div",{className:"s-work-empty-skeleton","aria-hidden":"true",children:i.map((l,c)=>d.jsxs("div",{className:"s-work-empty-row",children:[d.jsxs("div",{className:"s-work-empty-row-header",children:[d.jsx("span",{className:"s-work-empty-line s-work-empty-line-title",style:{width:l.titleWidth}}),d.jsx("span",{className:"s-work-empty-pill"})]}),d.jsx("div",{className:"s-work-empty-row-meta",children:l.metaWidths.map(f=>d.jsx("span",{className:"s-work-empty-line s-work-empty-line-meta",style:{width:f}},f))}),d.jsx("span",{className:"s-work-empty-line s-work-empty-line-summary",style:{width:l.summaryWidth}})]},c))})]})}return d.jsx("div",{className:"s-work-list",children:e.map(i=>{const l=!!i.id||!!i.conversationId,c=MB(i.attention),f=i.ownerName??i.ownerId??"Unassigned",p=i.id?()=>t({view:"work",workId:i.id}):i.conversationId?()=>t({view:"conversation",conversationId:i.conversationId}):void 0;return d.jsxs("div",{className:`s-work-row${l?" s-work-row-clickable":""}`,onClick:p,children:[d.jsxs("div",{className:"s-work-row-header",children:[d.jsxs("div",{className:"s-work-row-title-wrap",children:[d.jsx("span",{className:"s-work-row-title",children:i.title}),i.priority&&d.jsx("span",{className:"s-badge",children:i.priority})]}),d.jsx("span",{className:`s-pill s-pill-${_B(i)}`,children:i.currentPhase})]}),d.jsxs("div",{className:"s-work-row-meta",children:[d.jsx("span",{children:f}),d.jsx("span",{children:kB(i.state)}),i.activeChildWorkCount>0&&d.jsxs("span",{children:[i.activeChildWorkCount," child",i.activeChildWorkCount===1?"":"ren"]}),i.activeFlightCount>0&&d.jsxs("span",{children:[i.activeFlightCount," flight",i.activeFlightCount===1?"":"s"]}),c&&d.jsx("span",{children:c}),d.jsx("span",{children:tt(i.lastMeaningfulAt)})]}),i.lastMeaningfulSummary&&d.jsx("p",{className:"s-work-row-summary",children:Yn(i.lastMeaningfulSummary)})]},i.id)})})}const sg=new Set(["completed","failed","cancelled"]),DB={direct:"Direct message",channel:"Channel",group_direct:"Group",thread:"Thread"};function In(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?null:e<1e12?e*1e3:e}function zB(e){if(!e)return null;const t=e.replace(/[\\/]+$/,"");return t?t.split(/[\\/]/).filter(Boolean).at(-1)??t:null}function IB(e){return e.kind==="direct"&&e.agentName?e.agentName:e.title.replace(/\s*<>\s*/g," · ")}function tm(e){const t=In(e);return t===null?"":new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(t)}function LB(e,t){const s=In(e),r=In(t);if(s===null||r===null)return!1;const i=new Date(s),l=new Date(r);return i.getFullYear()===l.getFullYear()&&i.getMonth()===l.getMonth()&&i.getDate()===l.getDate()}function RS(e){const t=In(e);if(t===null)return"";const s=new Date(t),r=new Date,i=new Date(r.getFullYear(),r.getMonth(),r.getDate()).getTime(),l=new Date(s.getFullYear(),s.getMonth(),s.getDate()).getTime(),c=1440*60*1e3;return l===i?"Today":l===i-c?"Yesterday":new Intl.DateTimeFormat(void 0,{weekday:"short",month:"short",day:"numeric"}).format(t)}function PB(e){switch(e){case"status":return"Status";case"system":return"System";case"scout.dispatch":return"Dispatch";default:return null}}function Iu(e){return[...e].sort((t,s)=>(In(t.createdAt)??0)-(In(s.createdAt)??0))}function UB(e){return e.filter(t=>!sg.has(t.state)).sort((t,s)=>(In(s.startedAt)??0)-(In(t.startedAt)??0))[0]??null}function AS(e,t,s){return{id:e.id,invocationId:e.invocationId,agentId:e.targetAgentId||s,agentName:null,conversationId:t,collaborationRecordId:null,state:e.state,summary:e.summary??null,startedAt:e.startedAt??null,completedAt:e.completedAt??null}}function $B(e){const t=e.metadata?.scoutDispatch;if(!t||typeof t!="object")return null;const s=t;return!s.id||!s.kind||!Array.isArray(s.candidates)?null:s}function rg(e,t){if(e.class==="operator")return!0;const s=e.actorName?.toLowerCase()??"";return s===t.toLowerCase()||s==="operator"||s==="you"}function VB(e,t){return e.reduce((s,r)=>{if(rg(r,t))return s;const i=In(r.createdAt);return i===null?s:s===null||i>s?i:s},null)}function BB(e,t){switch(t){case"queued":return`${e} has your message and is waiting to start.`;case"waking":return`${e} is waking up now.`;case"waiting":return`${e} is thinking through the request.`;case"running":return`${e} is working on your request.`;default:return`${e} is working on it.`}}function ZB(e){const{agentName:t,agentState:s,sending:r,currentFlight:i,showWorkingTurn:l}=e;if(r&&!i)return{label:"Sending",detail:`Handing your message to ${t}.`,tone:"pending",showStrip:!0,showTyping:!1};if(i&&l){const c=i.summary?.trim()||BB(t,i.state);switch(i.state){case"queued":return{label:"Queued",detail:c,tone:"pending",showStrip:!0,showTyping:!0};case"waking":return{label:"Coming online",detail:c,tone:"working",showStrip:!0,showTyping:!0};case"waiting":return{label:"Thinking",detail:c,tone:"working",showStrip:!0,showTyping:!0};default:return{label:"Working",detail:c,tone:"working",showStrip:!0,showTyping:!0}}}return Fa(s)?{label:"Available",detail:`${t} is connected.`,tone:"idle",showStrip:!1,showTyping:!1}:{label:"Offline",detail:`${t} is offline right now. Sending a message will wake it up.`,tone:"offline",showStrip:!0,showTyping:!1}}function HB(e,t){switch(e.tone){case"pending":return"var(--accent)";case"working":return"var(--green)";case"offline":return"var(--dim)";default:return ec(t)}}function FB(){return d.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[d.jsx("path",{d:"m3 11 18-8-8 18-2.8-7.2L3 11Z"}),d.jsx("path",{d:"M10.2 13.8 21 3"})]})}function qB(){return d.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:d.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})})}function _S({label:e,value:t}){return d.jsxs("div",{className:"s-conv-meta-row",children:[d.jsx("span",{className:"s-conv-meta-label",children:e}),d.jsx("span",{className:"s-conv-meta-value",children:t})]})}function YB(e){if(!e)return null;const t=e.participantIds.filter(s=>s!=="operator");return t.length===0?null:t.join(", ")}function ag({conversationId:e,navigate:t}){const{agents:s}=Yt(),[r,i]=b.useState(null),[l,c]=b.useState([]),[f,p]=b.useState(null),[h,g]=b.useState(null),v=b.useRef(null),x=b.useRef(null),w=b.useRef(new Set),T=b.useRef(null),N=b.useRef(0),A=DC(e),C=r?.agentId??A,j=r?.kind==="direct"||A!==null,S=b.useMemo(()=>C?s.find(ae=>ae.id===C)??null:null,[s,C]),_=b.useCallback(async()=>{g(null);try{const ae=await ot(`/api/session/${encodeURIComponent(e)}`).catch(()=>null);i(ae);const se=ae?.agentId??A,ye=ae?.kind==="direct"&&se&&se.startsWith("local-session-agent-")?ng(se):e;if(ye!==e){t({view:"conversation",conversationId:ye});return}const[Se,we]=await Promise.all([ot(`/api/messages?conversationId=${encodeURIComponent(ye)}&limit=300`),ot(`/api/flights?conversationId=${encodeURIComponent(ye)}`)]);c(Iu(Se)),w.current=new Set(we.map(Re=>Re.invocationId)),p(UB(we))}catch(ae){g(ae instanceof Error?ae.message:String(ae))}},[e,A,t]);b.useEffect(()=>{_()},[_]),b.useEffect(()=>{T.current=f},[f]);const[R,M]=b.useState(""),[O,I]=b.useState(!1),[H,F]=b.useState("operator"),[$,L]=b.useState(null);b.useEffect(()=>{const ae=x.current;if(!ae)return;ae.style.height="0px";const se=Math.min(Math.max(ae.scrollHeight,40),160);ae.style.height=`${se}px`,ae.style.overflowY=ae.scrollHeight>se?"auto":"hidden"},[R]),b.useEffect(()=>{ot("/api/user").then(ae=>F(ae.name)).catch(()=>{})},[]);const Y=b.useMemo(()=>VB(l,H),[l,H]);b.useEffect(()=>{$===null||Y===null||Y>=$&&L(null)},[$,Y]);const re=b.useMemo(()=>!f||sg.has(f.state)?!1:(In(f.startedAt)??$??Date.now())>=(Y??0),[$,f,Y]),Q=O||$!==null||re,z=S?.name??r?.agentName??r?.title??C??"Conversation",Z=b.useMemo(()=>ZB({agentName:z,agentState:S?.state??null,sending:O,currentFlight:f,showWorkingTurn:re}),[S?.state,z,f,O,re]),B=r?IB(r):z,ie=r?.kind?DB[r.kind]??r.kind:"Conversation",W=YB(r)??e,D=zB(r?.workspaceRoot),P=r?.lastMessageAt??l[l.length-1]?.createdAt??null,G=[D?{label:D,title:r?.workspaceRoot??void 0}:null,r?.currentBranch?{label:r.currentBranch,title:r.currentBranch}:null,S?.harness??r?.harness?{label:S?.harness??r?.harness??"",title:void 0}:null].filter(ae=>!!ae);Kn(b.useCallback(ae=>{if(ae.kind==="message.posted"){const se=ae.payload?.message;if(!se||se.conversationId!==e)return;const ye=se.actorId===C,Se={id:se.id,conversationId:se.conversationId,actorName:ye?z:H,body:se.body,createdAt:se.createdAt,class:ye?se.class:"operator"};if(c(we=>{if(we.some(Re=>Re.id===se.id))return we;if(!ye){const Re=we.findIndex(oe=>oe.id.startsWith("optimistic-")&&oe.body===se.body&&Math.abs((In(oe.createdAt)??0)-(In(se.createdAt)??0))<=6e4);if(Re!==-1){const oe=[...we];return oe[Re]=Se,Iu(oe)}}return Iu([...we,Se])}),ye){const we=In(se.createdAt)??Date.now();L(Re=>Re===null||we<Re?Re:null),p(Re=>{if(!Re)return Re;const oe=In(Re.startedAt)??0;return we>=oe?null:Re})}return}if(ae.kind==="invocation.requested"){const se=ae.payload?.invocation;if(!se||se.targetAgentId!==C||se.conversationId!==e)return;w.current.add(se.id),L(ye=>ye??Date.now());return}if(ae.kind==="flight.updated"){const se=ae.payload?.flight;if(!se||se.targetAgentId!==C||!(w.current.has(se.invocationId)||T.current?.id===se.id))return;if(sg.has(se.state)){p(Se=>Se?.id===se.id?null:Se),_();return}w.current.add(se.invocationId),p(AS(se,e,C??""));return}ae.kind!=="agent.endpoint.upserted"&&ae.kind==="unknown"&&_()},[C,z,e,_,H])),b.useEffect(()=>{if(!Q)return;const ae=setInterval(()=>{_()},5e3);return()=>clearInterval(ae)},[Q,_]),b.useEffect(()=>{const ae=()=>{if(document.visibilityState!=="visible")return;const se=Date.now();se-N.current<1e3||(N.current=se,_())};return window.addEventListener("focus",ae),document.addEventListener("visibilitychange",ae),()=>{window.removeEventListener("focus",ae),document.removeEventListener("visibilitychange",ae)}},[_]);const te=l.length+(Z.showTyping?1:0),ee=b.useRef(0);b.useEffect(()=>{te>ee.current&&v.current?.scrollIntoView({behavior:"smooth"}),ee.current=te},[te]);const[,ve]=b.useState(0);b.useEffect(()=>{const ae=setInterval(()=>ve(se=>se+1),15e3);return()=>clearInterval(ae)},[]);const he=async ae=>{const se=ae.trim();if(!se||O)return;const ye=Date.now(),Se={id:`optimistic-${ye}`,conversationId:e,actorName:H,body:se,createdAt:ye,class:"operator"};I(!0),L(ye),g(null),c(we=>Iu([...we,Se]));try{const we=await ot("/api/send",{method:"POST",body:JSON.stringify({body:se,conversationId:e})});we.flight&&(w.current.add(we.flight.invocationId),p(AS(we.flight,e,C??"")))}catch(we){c(Re=>Re.filter(oe=>oe.id!==Se.id)),L(null),g(we instanceof Error?we.message:String(we))}finally{I(!1)}},pe=async()=>{const ae=R.trim();ae&&(M(""),await he(ae))},xe=async()=>{if(C)try{await ot("/api/agents/"+encodeURIComponent(C)+"/interrupt",{method:"POST",body:JSON.stringify({})})}catch{}},ke=Z.tone==="working"||Z.tone==="pending",fe=!R.trim()&&ke,Me=mo(),Ee=b.useCallback((ae,se)=>{const ye=window.getSelection()?.toString().trim(),Se=[];ye&&(Se.push({kind:"action",label:"Copy Selection",shortcut:"⌘C",onSelect:()=>navigator.clipboard.writeText(ye)}),Se.push({kind:"separator"})),Se.push({kind:"action",label:"Copy Message",onSelect:()=>navigator.clipboard.writeText(se.body)}),se.actorName&&!rg(se,H)&&Se.push({kind:"action",label:"Copy Agent ID",onSelect:()=>navigator.clipboard.writeText(se.actorName??"")}),Se.push({kind:"separator"}),Se.push({kind:"action",label:"Copy Message ID",onSelect:()=>navigator.clipboard.writeText(se.id)}),Me(ae,Se)},[H,Me]),He=async(ae,se)=>{const ye=`@${se.agentId} `,Se=R.trim();if(Se){M(""),await he(`${ye}${Se}`);return}M(ye),x.current?.focus()};return d.jsxs("div",{className:"s-conversation s-inbox-thread-redesign",children:[d.jsxs("div",{className:"s-conv-header",onClick:()=>j?t({view:"agent-info",conversationId:e}):void 0,style:j?void 0:{cursor:"default"},onContextMenu:ae=>{const se=[{kind:"action",label:"Copy Title",onSelect:()=>navigator.clipboard.writeText(B)}];C&&se.push({kind:"action",label:"Copy Agent ID",onSelect:()=>navigator.clipboard.writeText(C)}),se.push({kind:"action",label:"Copy Conversation ID",onSelect:()=>navigator.clipboard.writeText(e)}),Me(ae,se)},children:[d.jsx("button",{type:"button",className:"s-back",onClick:ae=>{ae.stopPropagation(),t(j?{view:"inbox"}:{view:"sessions"})},children:"←"}),d.jsxs("div",{className:"s-thread-header-copy",children:[d.jsxs("div",{className:"s-thread-header-main",children:[d.jsx("div",{className:"s-avatar s-avatar-sm",style:{background:Ts(z)},children:z[0]?.toUpperCase()??"?"}),d.jsxs("div",{className:"s-conv-header-info",children:[d.jsx("span",{className:"s-conv-header-name",children:B}),d.jsxs("span",{className:"s-conv-header-state",title:j?Z.detail:W,children:[d.jsx("span",{className:"s-dot s-dot-sm",style:{background:HB(Z,S?.state??null)}}),j?Z.label:W]})]})]}),d.jsxs("div",{className:"s-thread-header-meta",children:[d.jsx("span",{className:"s-thread-kicker",children:ie}),P&&d.jsx("span",{className:"s-thread-header-updated s-tabular",title:tm(P),children:tt(P)})]})]}),G.length>0&&d.jsx("div",{className:"s-thread-header-chips","aria-label":"Thread details",children:G.map((ae,se)=>d.jsx("span",{className:"s-thread-chip",title:ae.title,children:ae.label},`${ae.label}-${se}`))}),j&&C&&d.jsx("span",{className:"s-chevron"})]}),Z.showStrip&&d.jsxs("div",{className:`s-conv-status s-conv-status-${Z.tone}`,"aria-live":"polite",children:[d.jsx("span",{className:"s-conv-status-dot"}),d.jsxs("div",{className:"s-conv-status-copy",children:[d.jsx("span",{className:"s-conv-status-label",children:Z.label}),d.jsx("span",{className:"s-conv-status-detail",children:Z.detail})]})]}),j&&S&&(S.harnessSessionId||S.harnessLogPath)&&d.jsxs("details",{className:"s-conv-meta-disclosure",children:[d.jsx("summary",{className:"s-conv-meta-toggle",children:"Session details"}),d.jsxs("div",{className:"s-conv-meta","aria-label":"Agent session metadata",children:[S.harnessSessionId&&d.jsx(_S,{label:"Harness Session",value:S.harnessSessionId}),S.harnessLogPath&&d.jsx(_S,{label:"Harness Log",value:S.harnessLogPath})]})]}),h&&d.jsx("p",{className:"s-error",children:h}),d.jsxs("div",{className:"s-messages",children:[l.length===0?d.jsxs("div",{className:"s-empty s-thread-empty",children:[d.jsx("p",{children:"No messages yet"}),d.jsx("p",{children:j?`Start a conversation with ${z}.`:"Start the thread below."})]}):l.map((ae,se)=>{const ye=rg(ae,H),Se=$B(ae),we=Se?"scout.dispatch":ae.class,Re=PB(we),oe=se===0||!LB(l[se-1]?.createdAt,ae.createdAt),ge=tm(ae.createdAt);return d.jsxs("div",{className:"s-thread-message-block",children:[oe&&d.jsxs("div",{className:"s-thread-day-divider","aria-label":RS(ae.createdAt),children:[d.jsx("span",{className:"s-thread-day-line","aria-hidden":"true"}),d.jsx("span",{className:"s-thread-day-label",children:RS(ae.createdAt)}),d.jsx("span",{className:"s-thread-day-line","aria-hidden":"true"})]}),d.jsx("article",{className:`s-msg s-row-message${ye?" s-msg-you":""}`,"data-class":we,onContextMenu:me=>Ee(me,ae),children:d.jsxs("div",{className:"s-msg-card",children:[d.jsxs("div",{className:"s-msg-header",children:[d.jsxs("div",{className:"s-msg-meta",children:[d.jsx("span",{className:"s-msg-actor",children:ye?"You":ae.actorName}),Re&&d.jsx("span",{className:"s-msg-kind",children:Re})]}),d.jsx("span",{className:"s-msg-time",title:ge,children:tt(ae.createdAt)})]}),d.jsx("div",{className:"s-msg-body",title:ge,children:Yn(ae.body)}),Se&&Se.candidates.length>0&&d.jsx("div",{className:"s-scout-dispatch",children:Se.candidates.map(me=>d.jsxs("button",{type:"button",className:"s-scout-tile",onClick:()=>{He(Se,me)},children:[d.jsxs("span",{className:"s-scout-tile-id",children:["@",me.agentId]}),d.jsx("span",{className:"s-scout-tile-state",children:me.endpointState}),d.jsx("span",{className:"s-scout-tile-meta",children:[me.workspace,me.node,me.projectRoot].filter(Boolean).join(" · ")||me.displayName})]},me.agentId))})]})})]},ae.id)}),Z.showTyping&&d.jsx("div",{className:"s-thread-message-block",children:d.jsx("div",{className:"s-msg s-msg-working","aria-live":"polite",children:d.jsxs("div",{className:"s-msg-card s-msg-working-card",children:[d.jsxs("div",{className:"s-msg-header",children:[d.jsxs("div",{className:"s-msg-meta",children:[d.jsx("span",{className:"s-msg-actor",children:z}),d.jsx("span",{className:"s-msg-kind",children:"Live"})]}),d.jsx("span",{className:"s-msg-time",title:f?.startedAt?tm(f.startedAt):"now",children:f?.startedAt?tt(f.startedAt):"now"})]}),d.jsxs("div",{className:"s-msg-working-body",children:[d.jsxs("span",{className:"s-typing-indicator","aria-hidden":"true",children:[d.jsx("span",{className:"s-typing-dot"}),d.jsx("span",{className:"s-typing-dot"}),d.jsx("span",{className:"s-typing-dot"})]}),d.jsx("span",{className:"s-msg-working-copy",children:Z.detail})]})]})})}),d.jsx("div",{ref:v})]}),d.jsx("form",{className:"s-compose",onSubmit:ae=>{ae.preventDefault(),pe()},children:d.jsxs("div",{className:"s-thread-compose-shell",children:[d.jsx("textarea",{ref:x,className:"s-compose-input",placeholder:`Message ${z}...`,value:R,onChange:ae=>M(ae.target.value),onKeyDown:ae=>{ae.key!=="Enter"||ae.shiftKey||ae.nativeEvent.isComposing||(ae.preventDefault(),!O&&R.trim()&&pe())},rows:1}),d.jsxs("div",{className:"s-thread-compose-footer",children:[d.jsx("span",{className:"s-thread-compose-hint",children:O?"Sending…":fe?"Stop":ke?d.jsxs(d.Fragment,{children:[d.jsx("kbd",{className:"s-kbd",children:"↵"})," steer"]}):d.jsxs(d.Fragment,{children:[d.jsx("kbd",{className:"s-kbd",children:"↵"})," send",d.jsx("kbd",{className:"s-kbd",children:"⇧↵"})," newline"]})}),fe?d.jsx("button",{type:"button",className:"s-compose-send s-compose-stop",onClick:()=>{xe()},"aria-label":"Stop agent",children:d.jsx(qB,{})}):d.jsx("button",{type:"submit",className:"s-compose-send",disabled:O||!R.trim(),"aria-label":"Send message",children:d.jsx(FB,{})})]})]})})]})}function $C(e,t){if(t.filter(i=>i.name===e.name).length<=1)return{name:e.name,qualifier:null};const r=e.project??e.branch??e.id.replace(/^.*\./,"");return{name:e.name,qualifier:r}}function nm(e){return e?e.replace(/_/g," "):null}function GB(e){return e?tt(e):"—"}function XB(e){const t=[...e].filter(i=>i.kind==="direct"&&!!i.agentId).sort((i,l)=>(l.lastMessageAt??0)-(i.lastMessageAt??0)),s=new Map,r=new Map;for(const i of t){const l=i.agentId;s.has(l)||(s.set(l,i.id),r.set(l,i))}return{conversationByAgentId:s,sessionByAgentId:r}}function KB({label:e,value:t}){return d.jsxs("div",{className:"s-agent-meta-row",children:[d.jsx("span",{className:"s-agent-meta-label",children:e}),d.jsx("span",{className:"s-agent-meta-value",children:t})]})}function WB({values:e}){return d.jsx("span",{className:"s-agent-token-list",children:e.map(t=>d.jsx("span",{className:"s-agent-token",children:t},t))})}function JB({title:e,count:t,children:s}){return d.jsxs("section",{className:"s-agent-roster-section",children:[d.jsxs("div",{className:"s-agent-roster-section-header",children:[d.jsx("div",{className:"s-agent-roster-section-title",children:e}),d.jsx("span",{className:"s-agent-roster-section-count",children:t})]}),d.jsx("div",{className:"s-agent-roster-stack",children:s})]})}function QB({agents:e}){return e.length===0?null:d.jsxs("div",{className:"s-agent-overview-empty",children:[d.jsx("h2",{className:"s-agent-overview-empty-title",children:"Select an agent"}),d.jsx("p",{className:"s-agent-overview-empty-copy",children:"Pick an agent from the roster to view its profile, current work, and session context."})]})}function e7({agent:e,allAgents:t,session:s,conversationId:r,navigate:i}){const{name:l,qualifier:c}=$C(e,t),[f,p]=b.useState([]),h=ws(e.state),g=mo(),v=b.useCallback(async()=>{try{p(await ot(`/api/work?agentId=${encodeURIComponent(e.id)}`))}catch{p([])}},[e.id]);b.useEffect(()=>{v()},[v]),Kn(v);const x=[...e.project?[{label:"Project",value:e.project}]:[],...e.branch?[{label:"Branch",value:e.branch}]:[],...e.harness?[{label:"Harness",value:e.harness}]:[],...e.transport?[{label:"Transport",value:nm(e.transport)??e.transport}]:[],...e.projectRoot?[{label:"Path",value:e.projectRoot}]:[],...s?.workspaceRoot?[{label:"Workspace",value:s.workspaceRoot}]:[],...s?.currentBranch?[{label:"Session branch",value:s.currentBranch}]:[]];return d.jsxs("div",{className:"s-agent-casefile",children:[d.jsx("button",{type:"button",className:"s-back s-agent-mobile-back",onClick:()=>i({view:"agents"}),children:"← All agents"}),d.jsxs("section",{className:"s-agent-detail-identity",onContextMenu:w=>{const T=window.getSelection()?.toString().trim(),N=[];T&&(N.push({kind:"action",label:"Copy Selection",shortcut:"⌘C",onSelect:()=>navigator.clipboard.writeText(T)}),N.push({kind:"separator"})),N.push({kind:"action",label:"Copy Agent Name",onSelect:()=>navigator.clipboard.writeText(l)}),N.push({kind:"action",label:"Copy Agent ID",onSelect:()=>navigator.clipboard.writeText(e.id)}),e.handle&&N.push({kind:"action",label:`Copy @${e.handle}`,onSelect:()=>navigator.clipboard.writeText(`@${e.handle}`)}),g(w,N)},children:[d.jsx("div",{className:"s-avatar s-agent-casefile-avatar",style:{background:Ts(e.name)},children:e.name[0].toUpperCase()}),d.jsxs("div",{className:"s-agent-detail-identity-copy",children:[d.jsxs("h2",{className:"s-agent-detail-identity-name",children:[l,c&&d.jsx("span",{className:"s-agent-casefile-title-qualifier",children:c})]}),d.jsxs("div",{className:"s-agent-detail-identity-meta",children:[e.handle&&d.jsxs("span",{className:"s-agent-detail-handle",children:["@",e.handle]}),d.jsxs("span",{className:`s-agent-state-chip s-agent-state-chip-${h}`,children:[d.jsx("span",{className:"s-dot",style:{background:ec(e.state)}}),ao(e.state)]}),e.updatedAt&&d.jsx("span",{className:"s-agent-detail-updated",children:tt(e.updatedAt)})]}),d.jsx("p",{className:"s-agent-detail-identity-desc",children:[nm(e.role)??nm(e.agentClass),e.project].filter(Boolean).join(" · ")}),d.jsxs("div",{className:"s-agent-detail-actions",children:[d.jsx("button",{type:"button",className:"s-btn s-btn-primary",onClick:()=>r&&i({view:"agents",agentId:e.id,conversationId:r}),disabled:!r,children:r?"Open conversation":"No conversation"}),e.capabilities.length>0&&d.jsx("div",{className:"s-agent-detail-capabilities",children:d.jsx(WB,{values:e.capabilities})})]})]})]}),x.length>0&&d.jsxs("section",{className:"s-agent-detail-context",children:[d.jsx("h3",{className:"s-agent-detail-section-title",children:"Context"}),d.jsx("div",{className:"s-agent-meta-card-body",children:x.map(w=>d.jsx(KB,{label:w.label,value:w.value},w.label))})]}),d.jsxs("section",{className:"s-agent-detail-work",children:[d.jsx("h3",{className:"s-agent-detail-section-title",children:"Active work"}),d.jsx(OB,{items:f,navigate:i,emptyTitle:"Nothing in flight",emptyDetail:"New asks, handoffs, and follow-ups will stack here once this agent picks up work."})]})]})}function t7({navigate:e,selectedAgentId:t,conversationId:s}){const{agents:r}=Yt(),[i,l]=b.useState([]),c=b.useCallback(async()=>{const R=await ot("/api/sessions").catch(()=>null);R&&l(R)},[]);b.useEffect(()=>{c()},[c]),Kn(c);const f=[...r].sort((R,M)=>{const O={working:0,available:1,offline:2},I=O[ws(R.state)]-O[ws(M.state)];if(I!==0)return I;const H=(M.updatedAt??0)-(R.updatedAt??0);return H!==0?H:R.name.localeCompare(M.name)}),p=[{key:"working",title:"Working",agents:f.filter(R=>ws(R.state)==="working")},{key:"available",title:"Available",agents:f.filter(R=>ws(R.state)==="available")},{key:"offline",title:"Offline",agents:f.filter(R=>ws(R.state)==="offline")}],h=t?r.find(R=>R.id===t)??null:null,{conversationByAgentId:g,sessionByAgentId:v}=XB(i),x=r.length>0,w=200,T=440,N="scout-agents-roster-w",[A,C]=b.useState(()=>{try{const R=localStorage.getItem(N);if(R){const M=Number(R);if(M>=w&&M<=T)return M}}catch{}return 280}),j=b.useRef(!1),S=b.useRef(null);b.useEffect(()=>{try{localStorage.setItem(N,String(A))}catch{}},[A]);const _=b.useCallback(R=>{R.preventDefault(),j.current=!0,document.body.style.cursor="col-resize",document.body.style.userSelect="none";const M=S.current?.getBoundingClientRect().left??0,O=H=>{j.current&&C(Math.min(T,Math.max(w,H.clientX-M)))},I=()=>{j.current=!1,document.body.style.cursor="",document.body.style.userSelect="",document.removeEventListener("mousemove",O),document.removeEventListener("mouseup",I)};document.addEventListener("mousemove",O),document.addEventListener("mouseup",I)},[]);return d.jsxs("div",{className:["s-agents-layout","s-agents-browser",x?"s-agents-layout-split":"",h?"s-agents-browser-selected":""].filter(Boolean).join(" "),style:{"--agents-roster-w":`${A}px`},children:[d.jsx("div",{ref:S,className:"s-agents-list-panel s-agents-browser-list",children:d.jsxs("div",{className:"s-agent-roster",children:[d.jsx("div",{className:"s-agent-roster-header",children:d.jsxs("div",{children:[d.jsx("h2",{className:"s-section-title s-agent-roster-title",children:"Agents"}),d.jsxs("p",{className:"s-agent-roster-copy",children:[r.length," total · ",p[0].agents.length," working · ",p[1].agents.length," available"]})]})}),r.length===0?d.jsxs("div",{className:"s-empty s-agent-roster-empty",children:[d.jsx("p",{children:"No agents"}),d.jsx("p",{children:"Agents appear here when they connect to the broker."})]}):p.filter(R=>R.agents.length>0).map(R=>d.jsx(JB,{title:R.title,count:R.agents.length,children:R.agents.map(M=>d.jsx(n7,{agent:M,allAgents:r,selected:M.id===t,onClick:()=>e({view:"agents",agentId:M.id})},M.id))},R.key))]})}),x&&d.jsxs(d.Fragment,{children:[d.jsx("div",{className:"s-agents-roster-resize",onMouseDown:_,role:"separator","aria-orientation":"vertical"}),d.jsx("div",{className:"s-agents-detail-panel s-agents-browser-detail",children:s&&h?d.jsx(ag,{conversationId:s,navigate:e}):h?d.jsx(e7,{agent:h,allAgents:r,session:v.get(h.id)??null,conversationId:g.get(h.id)??h.conversationId??null,navigate:e}):d.jsx(QB,{agents:r})})]})]})}function n7({agent:e,allAgents:t,selected:s,onClick:r}){const{name:i,qualifier:l}=$C(e,t),c=ws(e.state),f=mo();return d.jsxs("div",{className:`s-agent-list-row s-agent-roster-row${s?" s-agent-list-row-active":""}`,onClick:r,onContextMenu:p=>{const h=[{kind:"action",label:"Copy Agent Name",onSelect:()=>navigator.clipboard.writeText(i)},{kind:"action",label:"Copy Agent ID",onSelect:()=>navigator.clipboard.writeText(e.id)}];e.handle&&h.push({kind:"action",label:`Copy @${e.handle}`,onSelect:()=>navigator.clipboard.writeText(`@${e.handle}`)}),f(p,h)},children:[d.jsxs("div",{className:"s-agent-roster-avatar-wrap",children:[d.jsx("div",{className:"s-avatar s-avatar-sm",style:{background:Ts(e.name)},children:e.name[0].toUpperCase()}),d.jsx("span",{className:`s-agent-roster-avatar-status s-agent-roster-avatar-status-${c}`,style:{background:ec(e.state)}})]}),d.jsx("div",{className:"s-agent-list-body s-agent-roster-row-body",children:d.jsxs("div",{className:"s-agent-roster-row-top",children:[d.jsxs("div",{className:"s-agent-list-header",children:[d.jsx("span",{className:"s-agent-list-name",children:i}),l&&d.jsx("span",{className:"s-agent-list-qualifier",children:l})]}),d.jsx("span",{className:"s-agent-roster-row-time",children:GB(e.updatedAt)})]})})]})}function s7(e){switch(e){case"queued":case"working":return"working";case"needs_attention":return"updated";case"failed":return"failed";default:return"completed"}}function r7(e){return e.conversationId?{view:"conversation",conversationId:e.conversationId}:{view:"agents",agentId:e.agentId}}function a7(e){return e.kind==="work_item"&&e.recordId?{view:"work",workId:e.recordId}:e.conversationId?{view:"conversation",conversationId:e.conversationId}:e.agentId?{view:"agents",agentId:e.agentId}:null}function i7(e){return e.recordId?{view:"work",workId:e.recordId}:e.conversationId?{view:"conversation",conversationId:e.conversationId}:e.agentId?{view:"agents",agentId:e.agentId}:null}function Lu({title:e,detail:t,count:s}){return d.jsxs(d.Fragment,{children:[d.jsxs("div",{className:"s-dashboard-panel-header",children:[d.jsx("div",{children:d.jsx("h3",{children:e})}),d.jsx("span",{className:"s-dashboard-count",style:s===0?{opacity:.4}:void 0,children:s})]}),d.jsx("p",{className:"s-dashboard-panel-copy",children:t})]})}function kS({ask:e,navigate:t,section:s}){const r=r7(e),i=e.completedAt?`finished ${tt(e.completedAt)}`:e.startedAt?`started ${tt(e.startedAt)}`:`updated ${tt(e.updatedAt)}`;return d.jsxs("div",{className:`s-work-row s-work-row-clickable s-dashboard-fleet-row s-dashboard-fleet-row-${s}`,"data-status":e.status,onClick:()=>t(r),children:[d.jsxs("div",{className:"s-work-row-header",children:[d.jsxs("div",{className:"s-fleet-row-title-wrap",children:[d.jsx("div",{className:"s-avatar s-avatar-sm",style:{background:Ts(e.agentName??e.agentId)},children:(e.agentName??e.agentId)[0]?.toUpperCase()??"?"}),d.jsxs("div",{className:"s-fleet-row-title-copy",children:[d.jsxs("div",{className:"s-work-row-title-wrap",children:[d.jsx("span",{className:"s-work-row-title",children:e.agentName??e.agentId}),e.harness&&d.jsx("span",{className:"s-badge",children:e.harness})]}),d.jsxs("div",{className:"s-work-row-meta",style:{marginTop:2},children:[d.jsx("span",{className:"s-dot",style:{background:ec(e.agentState)}}),d.jsx("span",{children:ao(e.agentState)}),d.jsx("span",{children:i})]})]})]}),d.jsx("span",{className:`s-pill s-pill-${s7(e.status)}`,children:e.statusLabel})]}),d.jsx("p",{className:"s-work-row-summary",children:Yn(e.task)}),e.summary&&d.jsx("p",{className:"s-work-row-summary",style:{marginTop:8},children:Yn(e.summary)})]})}function o7({item:e,navigate:t}){const s=a7(e),r=e.kind==="question"?"question":e.state.replace(/_/g," "),i=e.acceptanceState!=="none"?e.acceptanceState.replace(/_/g," "):e.kind==="question"?"awaiting answer":"your move";return d.jsxs("div",{className:`s-work-row s-dashboard-fleet-row s-dashboard-fleet-attention-row${s?" s-work-row-clickable":""}`,onClick:s?()=>t(s):void 0,children:[d.jsxs("div",{className:"s-work-row-header",children:[d.jsx("div",{className:"s-work-row-title-wrap",children:d.jsx("span",{className:"s-work-row-title",children:e.title})}),d.jsx("span",{className:"s-pill s-pill-updated",children:"Needs your input"})]}),d.jsxs("div",{className:"s-work-row-meta",children:[d.jsx("span",{children:e.kind==="question"?"question":"work item"}),e.agentName&&d.jsx("span",{children:e.agentName}),d.jsx("span",{children:r}),d.jsx("span",{children:i}),d.jsx("span",{children:tt(e.updatedAt)})]}),e.summary&&d.jsx("p",{className:"s-work-row-summary",children:Yn(e.summary)})]})}function l7({item:e,navigate:t}){const s=i7(e);return d.jsxs("div",{className:`s-dashboard-activity-row${s?" s-dashboard-activity-row-clickable":""}`,onClick:s?()=>t(s):void 0,children:[d.jsx("div",{className:"s-avatar s-avatar-sm",style:{background:Ts(e.actorName??e.agentId??"system")},children:(e.actorName??e.agentId??"S")[0]?.toUpperCase()??"S"}),d.jsxs("div",{className:"s-dashboard-activity-body",children:[d.jsxs("div",{className:"s-dashboard-activity-header",children:[d.jsx("span",{className:"s-dashboard-activity-actor",children:e.actorName??"system"}),d.jsx("span",{className:"s-dashboard-activity-kind",children:oB(e.kind)}),d.jsx("span",{className:"s-time",children:tt(e.ts)})]}),(e.title||e.summary)&&d.jsx("p",{className:"s-dashboard-activity-summary",children:Yn(e.title??e.summary??"")}),e.title&&e.summary&&d.jsx("p",{className:"s-dashboard-activity-note",children:Yn(e.summary)})]})]})}function c7({navigate:e}){const[t,s]=b.useState(null),r=b.useCallback(async()=>{try{s(await ot("/api/fleet"))}catch{s(null)}},[]);b.useEffect(()=>{r()},[r]),Kn(r);const i=t?.activeAsks??[],l=t?.recentCompleted??[],c=t?.needsAttention??[],f=t?.activity??[],p=c.length>0?`${c.length} item${c.length===1?" is":"s are"} waiting on you. Clear ${c.length===1?"it":"those"} first, then monitor the rest of the queue.`:i.length>0?`${i.length} ask${i.length===1?" is":"s are"} currently in flight. The queue is clear of interruptions.`:l.length>0?"Nothing is actively running right now. Recent finishes are ready for review.":"No asks have moved through the fleet yet. Start work and this becomes the operations board.";return d.jsxs("div",{className:"s-home s-dashboard-screen s-dashboard-fleet",children:[d.jsx("div",{className:"s-dashboard-hero s-dashboard-hero-fleet",children:d.jsxs("div",{className:"s-dashboard-hero-copy",children:[d.jsxs("div",{className:"s-dashboard-hero-head",children:[d.jsx("h2",{children:"Fleet"}),t&&d.jsxs("span",{className:"s-time",children:["Updated ",tt(t.generatedAt)]})]}),d.jsx("p",{children:p}),d.jsxs("div",{className:"s-dashboard-summary-grid",children:[d.jsxs("div",{className:`s-dashboard-summary-card${(t?.totals.needsAttention??0)>0?" s-dashboard-summary-card-attention":""}`,children:[d.jsx("div",{className:"s-dashboard-summary-label",children:"Needs input"}),d.jsx("div",{className:"s-dashboard-summary-value",children:t?.totals.needsAttention??0}),d.jsx("div",{className:"s-dashboard-summary-meta",children:"Questions, reviews, or decisions waiting on you"})]}),d.jsxs("div",{className:"s-dashboard-summary-card",children:[d.jsx("div",{className:"s-dashboard-summary-label",children:"Active asks"}),d.jsx("div",{className:"s-dashboard-summary-value",children:t?.totals.active??0}),d.jsx("div",{className:"s-dashboard-summary-meta",children:"Currently in flight across the fleet"})]}),d.jsxs("div",{className:`s-dashboard-summary-card${(t?.totals.recentCompleted??0)>0?" s-dashboard-summary-card-finished":""}`,children:[d.jsx("div",{className:"s-dashboard-summary-label",children:"Finished"}),d.jsx("div",{className:"s-dashboard-summary-value",children:t?.totals.recentCompleted??0}),d.jsx("div",{className:"s-dashboard-summary-meta",children:"Recent completions and failures to review"})]}),d.jsxs("div",{className:"s-dashboard-summary-card",children:[d.jsx("div",{className:"s-dashboard-summary-label",children:"Activity"}),d.jsx("div",{className:"s-dashboard-summary-value",children:t?.totals.activity??0}),d.jsx("div",{className:"s-dashboard-summary-meta",children:"Recent events across the fleet"})]})]})]})}),d.jsxs("div",{className:"s-dashboard-fleet-stack",children:[d.jsxs("section",{className:`s-dashboard-panel${c.length>0?" s-dashboard-panel-attention":""}`,children:[d.jsx(Lu,{title:"Needs your input",detail:"Handle interruptions, pending answers, and review requests first.",count:c.length}),c.length===0?d.jsxs("div",{className:"s-empty",children:[d.jsx("p",{children:"Nothing is waiting on you"}),d.jsx("p",{children:"When agents ask a question or a work item needs review, it will land here first."})]}):d.jsx("div",{className:"s-work-list",children:c.map(h=>d.jsx(o7,{item:h,navigate:e},h.recordId))})]}),d.jsxs("div",{className:"s-dashboard-fleet-columns",children:[d.jsxs("section",{className:"s-dashboard-panel s-dashboard-panel-active",children:[d.jsx(Lu,{title:"Active asks",detail:"The asks still in flight across the fleet.",count:i.length}),i.length===0?d.jsxs("div",{className:"s-empty",children:[d.jsx("p",{children:"No active asks"}),d.jsx("p",{children:"New agent work will appear here while it is still in progress."})]}):d.jsx("div",{className:"s-work-list",children:i.map(h=>d.jsx(kS,{ask:h,navigate:e,section:"active"},h.invocationId))})]}),d.jsxs("section",{className:"s-dashboard-panel s-dashboard-panel-finished",children:[d.jsx(Lu,{title:"Recent finishes",detail:"Review completions and failures once the active queue is stable.",count:l.length}),l.length===0?d.jsxs("div",{className:"s-empty",children:[d.jsx("p",{children:"No recent finishes"}),d.jsx("p",{children:"Completed asks and failures will show up here once they settle."})]}):d.jsx("div",{className:"s-work-list",children:l.map(h=>d.jsx(kS,{ask:h,navigate:e,section:"finished"},h.invocationId))})]})]}),d.jsxs("section",{className:"s-dashboard-panel s-dashboard-panel-activity",children:[d.jsx(Lu,{title:"Recent activity",detail:"The broader event stream behind the queue.",count:f.length}),f.length===0?d.jsxs("div",{className:"s-empty",children:[d.jsx("p",{children:"No recent fleet activity"}),d.jsx("p",{children:"Messages, asks, and other agent activity will stream here."})]}):d.jsx("div",{className:"s-dashboard-activity-feed",children:f.slice(0,20).map(h=>d.jsx(l7,{item:h,navigate:e},h.id))})]})]})]})}function u7(){const e=window.getSelection();return e!==null&&e.toString().trim().length>0}function VC(e){u7()||e()}const d7={"agent.registered":"registered","agent.online":"came online","agent.offline":"went offline","flight.started":"started task","flight.completed":"completed task","message.sent":"sent message","message.received":"received message","collaboration.ask":"asked a question","collaboration.answer":"answered"};function f7(e){return d7[e]??e.replace(/[._]/g," ")}function h7({item:e,navigate:t}){const s=e.conversationId?{view:"conversation",conversationId:e.conversationId}:null,r=mo(),i=b.useCallback(l=>{const c=e.title??e.summary??"",f=window.getSelection()?.toString().trim(),p=[];f&&(p.push({kind:"action",label:"Copy Selection",shortcut:"⌘C",onSelect:()=>navigator.clipboard.writeText(f)}),p.push({kind:"separator"})),c&&p.push({kind:"action",label:"Copy Details",onSelect:()=>navigator.clipboard.writeText(c)}),e.actorName&&p.push({kind:"action",label:"Copy Actor Name",onSelect:()=>navigator.clipboard.writeText(e.actorName)}),s&&(p.push({kind:"separator"}),p.push({kind:"action",label:"Open Conversation",onSelect:()=>t(s)})),p.length>0&&r(l,p)},[e,s,t,r]);return d.jsxs("div",{className:`s-dashboard-activity-row${s?" s-dashboard-activity-row-clickable":""}`,onClick:s?()=>VC(()=>t(s)):void 0,onContextMenu:i,children:[d.jsx("div",{className:"s-dashboard-activity-time",children:tt(e.ts)}),d.jsxs("div",{className:"s-dashboard-activity-body",children:[d.jsxs("div",{className:"s-dashboard-activity-header",children:[d.jsx("span",{className:"s-dashboard-activity-actor",children:e.actorName??"system"}),d.jsx("span",{className:"s-dashboard-activity-kind",children:f7(e.kind)})]}),(e.title||e.summary)&&d.jsx("p",{className:"s-dashboard-activity-summary",children:Yn(e.title??e.summary??"")})]})]})}function p7({navigate:e}){const[t,s]=b.useState([]),r=b.useCallback(async()=>{try{const l=await ot("/api/activity");s(l)}catch{}},[]);b.useEffect(()=>{r()},[r]),Kn(r);const i=t.slice(0,20);return d.jsx("div",{className:"s-home s-dashboard-screen",children:d.jsx("div",{className:"s-dashboard-body s-dashboard-body-solo",children:d.jsxs("main",{className:"s-dashboard-main",children:[d.jsxs("div",{className:"s-dashboard-section-head",children:[d.jsx("h3",{children:"Activity"}),t.length>0&&d.jsx("span",{className:"s-dashboard-count",children:t.length})]}),i.length===0?d.jsxs("div",{className:"s-empty",children:[d.jsx("p",{children:"No activity yet"}),d.jsx("p",{children:"Events appear here as agents connect and work."})]}):d.jsx("div",{className:"s-dashboard-activity-feed",children:i.map(l=>d.jsx(h7,{item:l,navigate:e},l.id))}),t.length>20&&d.jsx("button",{type:"button",className:"s-dashboard-see-all",onClick:()=>e({view:"activity"}),children:"See all activity"})]})})})}const m7=b.lazy(()=>_l(()=>import("./arc.es-CXoMwIWo.js"),[]).then(e=>({default:e.ArcDiagram})));function Ua(e){if(!e)return"";const t=e.replace(/^https?:\/\//,"").split("/")[0],[s]=t.split(":");return s.split(".")[0]}function g7(e){const t=e.hostName?.trim();if(t&&t.toLowerCase()!=="localhost")return Ua(t)||t;const s=e.dnsName?.trim().replace(/\.$/,"");return s?Ua(s)||s:Ua(e.name)||e.name}function ig(e){if(!e)return"";const t=e.replace(/^https?:\/\//,"").split("/")[0],[s]=t.split(":");return s.replace(/\.$/,"").toLowerCase()}function Zr(e){const t=ig(e);return t?t.split(".")[0]??t:""}function y7(e){return e.brokerUrl?Ua(e.brokerUrl):e.hostName?Ua(e.hostName):e.id.slice(0,10)}function v7(e,t){return Math.abs(e)>=Math.abs(t)?e>=0?["right","left"]:["left","right"]:t>=0?["bottom","top"]:["top","bottom"]}function b7(e,t){const s=Zr(t.hostName||t.name),r=Zr(e.localNode?.hostName||e.localNode?.name);return!!r&&s===r}function x7(e,t){const s=new Set([Zr(e.hostName),Zr(e.name),...e.addresses.map(i=>ig(i)),...e.addresses.map(i=>Zr(i))].filter(Boolean)),r=new Set([Zr(t.hostName),Zr(t.name),ig(t.brokerUrl),Zr(t.brokerUrl)].filter(Boolean));for(const i of s)if(r.has(i))return!0;return!1}function w7(e){if(!e.localNode)return null;const t=e.localNode.id,s=Object.values(e.nodes).filter(x=>x.id!==t),r=e.tailscale.peers.filter(x=>!b7(e,x)).filter(x=>!s.some(w=>x7(x,w))),i=[...s.map(x=>({kind:"mesh",peer:x})),...r.map(x=>({kind:"tailnet",peer:x}))],l=800,c=300,f=l/2,p=c/2,h={[t]:{x:f,y:p,size:"m"}},g={[t]:{icon:"Database",name:Ua(e.localNode.hostName)||e.localNode.name||"broker",subtitle:"this node",color:"violet"}},v=[];if(i.length===0)h.__placeholder={x:f+220,y:p,size:"m"},g.__placeholder={icon:"CircleDashed",name:"No peers yet",subtitle:"awaiting discovery",color:"zinc"},v.push({from:t,to:"__placeholder",fromAnchor:"right",toAnchor:"left",style:"pending"});else{const x=i.length,w=Math.min(170,100+x*10);i.forEach(({kind:T,peer:N},A)=>{const C=A/x*Math.PI*2-Math.PI/2,j=Math.round(f+w*Math.cos(C)),S=Math.round(p+w*Math.sin(C)),_=T==="mesh"?N.id:`tailnet:${N.id}`,R=T==="mesh"?Ua(N.hostName)||N.name||"peer":g7(N)||"tailnet",M=T==="mesh"?y7(N):N.online?N.addresses[0]??"tailnet only":"tailnet offline";h[_]={x:j,y:S,size:T==="mesh"?"m":"s"},g[_]={icon:T==="mesh"?"Database":"CircleDashed",name:R,subtitle:M,color:T==="mesh"?N.advertiseScope==="mesh"?"emerald":"zinc":N.online?"sky":"zinc"};const[O,I]=v7(j-f,S-p);v.push({from:t,to:_,fromAnchor:O,toAnchor:I,style:T==="mesh"?N.advertiseScope==="mesh"?"mesh":"local":N.online?"tailnet":"tailnet-offline"})})}return{layout:{width:l,height:c},nodes:h,nodeData:g,connectors:v,connectorStyles:{mesh:{color:"emerald",strokeWidth:2,label:"mesh"},local:{color:"zinc",strokeWidth:1.5},tailnet:{color:"sky",strokeWidth:1.5,dashed:!0,label:"tailnet"},"tailnet-offline":{color:"zinc",strokeWidth:1.25,dashed:!0,label:"tailnet"},pending:{color:"zinc",strokeWidth:1.5,dashed:!0}}}}function S7({mesh:e}){const t=b.useMemo(()=>w7(e),[e]);return t?d.jsx("div",{className:"s-mesh-topology",children:d.jsx(b.Suspense,{fallback:d.jsx("div",{className:"s-mesh-topology-fallback"}),children:d.jsx(m7,{data:t,className:"s-mesh-topology-canvas",mode:"light",theme:"cool",interactive:!0,showArcToggle:!1,defaultZoom:"fit",maxFitZoom:.95,hoverEffects:{dim:!0,lift:!0,glow:!0,highlightEdges:!0}})})}):null}function E7(e){return e.code==="local_only"?"notice":e.severity==="error"?"error":"warning"}function N7(e){switch(e.code){case"local_only":return"Not discoverable";case"mesh_loopback":return"Wrong address";case"discovery_unconfigured":return"No path";default:return"Offline"}}function T7(e){return e?e.replace(/^https?:\/\//,"").split("/")[0]??e:"Unavailable"}function j7(e){const t=e.hostName?.trim();if(t&&t.toLowerCase()!=="localhost")return t;const s=e.dnsName?.trim().replace(/\.$/,"");return s?s.split(".")[0]??s:e.name}function C7(e){return e==="mesh"?"Announced to mesh":e==="local"?"Local only":e||"Not advertised"}function R7(e){return e.identity.discoverable?"success":e.health.reachable?"warning":"danger"}function A7(e){return e.identity.discoverable?"Discoverable":e.health.reachable?"Not discoverable":"Broker offline"}function _7(e){return!e.health.reachable||e.issues.some(t=>t.severity==="error")?"danger":e.issues.length>0?"warning":"success"}function k7(e){return e.health.reachable?e.issues.some(t=>t.severity==="error")?"Degraded":e.issues.length>0?"Needs attention":"Healthy":"Broker unreachable"}function M7({issue:e}){const t=E7(e);return d.jsxs("article",{className:`sys-issue-card sys-issue-card-${t}`,children:[d.jsxs("div",{className:"sys-issue-head",children:[d.jsx("h3",{className:"sys-issue-title",children:e.title}),d.jsx("span",{className:`sys-chip sys-chip-${t==="error"?"failed":t}`,children:N7(e)})]}),d.jsx("p",{className:"sys-issue-body",children:e.summary}),(e.action||e.actionCommand)&&d.jsxs("div",{className:"sys-issue-action",children:[e.actionCommand&&d.jsx("code",{className:"sys-code-inline",children:e.actionCommand}),e.action&&d.jsx("span",{children:e.action})]})]})}function O7({navigate:e}){const[t,s]=b.useState(null),[r,i]=b.useState(!0),[l,c]=b.useState(!1),[f,p]=b.useState(!1),[h,g]=b.useState(null),[v,x]=b.useState(null),[w,T]=b.useState(null),N=b.useRef(null),A=b.useRef(0);b.useEffect(()=>{N.current=t},[t]);const C=b.useCallback(async(L="initial")=>{const Y=++A.current;!(N.current!==null)&&L!=="background"?(i(!0),x(null)):c(!0);try{const Q=await ot("/api/mesh");if(Y!==A.current)return;s(Q),x(null),T(Date.now())}catch(Q){if(Y!==A.current)return;x(Q instanceof Error?Q.message:String(Q))}finally{Y===A.current&&(i(!1),c(!1))}},[]);b.useEffect(()=>{C("initial")},[C]),b.useEffect(()=>{const L=setInterval(()=>{C("background")},1e4);return()=>clearInterval(L)},[C]);const j=b.useCallback(async()=>{p(!0),g(null);try{const L=await ot("/api/mesh/announce",{method:"POST",body:"{}"});s(L),N.current=L,x(null),T(Date.now()),g({tone:L.identity.discoverable?"success":"warning",title:L.identity.discoverable?"Mesh updated.":"Mesh updated, but still needs attention.",message:L.identity.discoverable?"This broker is now announced to the mesh.":"Mesh visibility was updated, but this broker still is not peer-reachable."})}catch(L){g({tone:"warning",title:"Could not announce broker.",message:L instanceof Error?L.message:String(L)})}finally{p(!1)}},[]),S=t?_7(t):"warning",_=t?k7(t):"Loading",R=t?Object.values(t.nodes):[],M=t?.localNode?.id,O=t?.localNode?.hostName?.toLowerCase(),I=R.filter(L=>L.id!==M),H=(t?.tailscale.peers??[]).filter(L=>{const Y=L.hostName?.toLowerCase();return!Y||Y==="localhost"?!0:!(O&&(Y===O||Y.startsWith(`${O.split(".")[0]}.`)))}),F=t?t.issues.length>0?t.issues:t.warnings.map((L,Y)=>({code:`fallback-${Y}`,severity:"warning",title:"Mesh notice",summary:L,action:null,actionCommand:null})):[],$=b.useMemo(()=>t?[{label:"Broker",value:t.health.reachable?"Reachable":"Unavailable",detail:t.health.error??T7(t.brokerUrl)},{label:"Discoverable",value:t.identity.discoverable?"Yes":"No",detail:t.identity.modeLabel},{label:"Mesh peers",value:`${I.length}`,detail:I.length>0?"Remote brokers in this mesh":"No remote brokers discovered"},{label:"Tailnet",value:t.tailscale.available?`${H.filter(L=>L.online).length}/${H.length}`:"Unavailable",detail:t.tailscale.available?"Online peers / visible peers":"Tailscale peers not detected"}]:[],[H,t,I.length]);return d.jsxs("div",{className:"sys-surface-page",children:[d.jsxs("div",{className:"sys-page-head",children:[d.jsxs("div",{className:"sys-page-title-group",children:[d.jsx("h2",{className:"sys-page-title",children:"Mesh"}),d.jsx("p",{className:"sys-page-subtitle",children:"Who this broker is, whether peers can discover it, and what the current mesh can see."})]}),d.jsxs("div",{className:"sys-page-actions",children:[d.jsx("span",{className:`sys-chip sys-chip-${S}`,children:_}),d.jsx("div",{className:"sys-sync-note",children:r?"Loading system snapshot...":v&&t?`Showing last confirmed snapshot from ${w?tt(w):"earlier"}`:w?`Confirmed ${tt(w)}`:"Waiting for first snapshot"}),d.jsx("button",{type:"button",className:"s-btn",disabled:r||l,onClick:()=>{C("manual")},children:l?"Refreshing...":"Refresh"})]})]}),v&&t&&d.jsxs("div",{className:"sys-banner sys-banner-warning",children:[d.jsx("strong",{children:"Mesh refresh failed."}),d.jsx("span",{children:v})]}),r&&!t&&d.jsxs("div",{className:"sys-panel sys-state-card",children:[d.jsx("h3",{className:"sys-state-title",children:"Loading mesh status"}),d.jsx("p",{className:"sys-state-body",children:"Inspecting broker reachability and peer discovery inputs."})]}),!r&&!t&&v&&d.jsxs("div",{className:"sys-panel sys-state-card sys-state-card-error",children:[d.jsx("h3",{className:"sys-state-title",children:"Mesh status is unavailable"}),d.jsx("p",{className:"sys-state-body",children:v}),d.jsx("div",{className:"sys-inline-actions",children:d.jsx("button",{type:"button",className:"s-btn",onClick:()=>{C("manual")},children:"Try again"})})]}),t&&d.jsxs(d.Fragment,{children:[d.jsxs("section",{className:"sys-panel sys-mesh-identity",children:[d.jsxs("div",{className:"sys-section-head",children:[d.jsxs("div",{children:[d.jsx("h3",{className:"sys-section-title",children:"This broker"}),d.jsx("p",{className:"sys-section-subtitle",children:"The identity peers will learn if they discover this machine."})]}),d.jsx("span",{className:`sys-chip sys-chip-${R7(t)}`,children:A7(t)})]}),d.jsxs("div",{className:"sys-detail-grid",children:[d.jsxs("div",{className:"sys-detail-card",children:[d.jsx("span",{className:"sys-detail-label",children:"Who Am I"}),d.jsx("span",{className:"sys-detail-value",children:t.identity.name??t.localNode?.name??"Unavailable"})]}),d.jsxs("div",{className:"sys-detail-card",children:[d.jsx("span",{className:"sys-detail-label",children:"Node ID"}),d.jsx("code",{className:"sys-detail-value",children:t.identity.nodeId??"Unavailable"})]}),d.jsxs("div",{className:"sys-detail-card",children:[d.jsx("span",{className:"sys-detail-label",children:"Mesh"}),d.jsx("code",{className:"sys-detail-value",children:t.identity.meshId??"Unassigned"})]}),d.jsxs("div",{className:"sys-detail-card",children:[d.jsx("span",{className:"sys-detail-label",children:"Mode"}),d.jsx("span",{className:"sys-detail-value",children:t.identity.modeLabel})]}),d.jsxs("div",{className:"sys-detail-card",children:[d.jsx("span",{className:"sys-detail-label",children:"Discoverable"}),d.jsx("span",{className:"sys-detail-value",children:t.identity.discoverable?"Yes":"No"})]}),d.jsxs("div",{className:"sys-detail-card",children:[d.jsx("span",{className:"sys-detail-label",children:"Announced As"}),d.jsx("code",{className:"sys-detail-value",children:t.identity.announceUrl??"Not announced"})]})]}),d.jsxs("div",{className:`sys-banner ${t.identity.discoverable?"sys-banner-success":"sys-banner-muted"}`,children:[d.jsx("strong",{children:"How peers find you."}),d.jsx("span",{children:t.identity.discoveryDetail})]}),!t.identity.discoverable&&t.health.reachable&&d.jsx("div",{className:"sys-inline-actions",children:d.jsx("button",{type:"button",className:"s-btn",disabled:f,onClick:()=>{j()},children:f?"Announcing...":"Announce on mesh"})}),h&&d.jsxs("div",{className:`sys-banner ${h.tone==="success"?"sys-banner-success":"sys-banner-warning"}`,children:[d.jsx("strong",{children:h.title}),d.jsx("span",{children:h.message})]})]}),d.jsx("div",{className:"sys-stat-grid",children:$.map(L=>d.jsxs("div",{className:"sys-stat-card",children:[d.jsx("span",{className:"sys-stat-label",children:L.label}),d.jsx("strong",{className:"sys-stat-value",children:L.value}),d.jsx("span",{className:"sys-stat-detail",children:L.detail})]},L.label))}),d.jsxs("section",{className:"sys-panel",children:[d.jsx("div",{className:"sys-section-head",children:d.jsxs("div",{children:[d.jsx("h3",{className:"sys-section-title",children:"Health notices"}),d.jsx("p",{className:"sys-section-subtitle",children:"Warnings and errors from the current broker and discovery snapshot."})]})}),F.length>0?d.jsx("div",{className:"sys-issue-grid",children:F.map((L,Y)=>d.jsx(M7,{issue:L},`${L.code}-${Y}`))}):d.jsxs("div",{className:"sys-list-empty",children:[d.jsx("h3",{children:"No active mesh warnings"}),d.jsx("p",{children:"The broker is reachable and discovery inputs look healthy from this page."})]})]}),d.jsxs("section",{className:"sys-panel",children:[d.jsx("div",{className:"sys-section-head",children:d.jsxs("div",{children:[d.jsx("h3",{className:"sys-section-title",children:"Topology"}),d.jsx("p",{className:"sys-section-subtitle",children:"Current broker relationships plus visible tailnet peers from this machine."})]})}),t.localNode?d.jsx(S7,{mesh:t}):d.jsxs("div",{className:"sys-list-empty",children:[d.jsx("h3",{children:"Topology unavailable"}),d.jsx("p",{children:"A local node record is required before the topology view can render."})]})]}),d.jsxs("section",{className:"sys-panel",children:[d.jsx("div",{className:"sys-section-head",children:d.jsxs("div",{children:[d.jsx("h3",{className:"sys-section-title",children:"Discovered peers"}),d.jsxs("p",{className:"sys-section-subtitle",children:["Remote brokers registered in ",t.meshId??"this mesh","."]})]})}),I.length===0?d.jsxs("div",{className:"sys-list-empty",children:[d.jsx("h3",{children:"No remote brokers discovered"}),d.jsx("p",{children:"This can be normal on a single-node setup. If you expect peers, check the health notices above."})]}):d.jsx("div",{className:"sys-list-grid",children:I.map(L=>d.jsxs("article",{className:"sys-list-card",children:[d.jsxs("div",{className:"sys-list-card-head",children:[d.jsx("h3",{className:"sys-list-card-title",children:L.name}),d.jsx("span",{className:`sys-chip sys-chip-${L.advertiseScope==="mesh"?"success":"neutral"}`,children:C7(L.advertiseScope)})]}),d.jsxs("div",{className:"sys-list-card-detail",children:[d.jsx("span",{className:"sys-detail-label",children:"Node id"}),d.jsx("code",{className:"sys-detail-value",children:L.id})]}),L.brokerUrl&&d.jsxs("div",{className:"sys-list-card-detail",children:[d.jsx("span",{className:"sys-detail-label",children:"Broker"}),d.jsx("code",{className:"sys-detail-value",children:L.brokerUrl})]}),d.jsxs("div",{className:"sys-list-card-detail",children:[d.jsx("span",{className:"sys-detail-label",children:"Last seen"}),d.jsx("span",{className:"sys-detail-value",children:L.lastSeenAt?tt(L.lastSeenAt):"Recently registered"})]})]},L.id))})]}),d.jsxs("section",{className:"sys-panel",children:[d.jsx("div",{className:"sys-section-head",children:d.jsxs("div",{children:[d.jsx("h3",{className:"sys-section-title",children:"Tailnet"}),d.jsx("p",{className:"sys-section-subtitle",children:"External Tailscale peers visible from this machine."})]})}),H.length===0?d.jsxs("div",{className:"sys-list-empty",children:[d.jsx("h3",{children:"No external tailnet peers"}),d.jsx("p",{children:t.tailscale.available?"Only this host is visible in the current tailnet snapshot.":"Tailscale peers were not detected on this machine."})]}):d.jsx("div",{className:"sys-list-grid",children:H.map(L=>d.jsxs("article",{className:"sys-list-card",children:[d.jsxs("div",{className:"sys-list-card-head",children:[d.jsx("h3",{className:"sys-list-card-title",children:j7(L)}),d.jsx("span",{className:`sys-chip sys-chip-${L.online?"success":"failed"}`,children:L.online?"Online":"Offline"})]}),d.jsxs("div",{className:"sys-list-card-detail",children:[d.jsx("span",{className:"sys-detail-label",children:"Address"}),d.jsx("code",{className:"sys-detail-value",children:L.addresses?.[0]??"Unavailable"})]}),d.jsxs("div",{className:"sys-list-card-detail",children:[d.jsx("span",{className:"sys-detail-label",children:"Platform"}),d.jsx("span",{className:"sys-detail-value",children:L.os??"Unknown"})]})]},L.id))})]})]})]})}const D7=[[/```[\s\S]*?```/g," "],[/`([^`]+)`/g,"$1"],[/!\[([^\]]*)\]\([^)]+\)/g,"$1"],[/\[([^\]]+)\]\([^)]+\)/g,"$1"],[/\*\*(.+?)\*\*/g,"$1"],[/__(.+?)__/g,"$1"],[new RegExp("(?<!\\*)\\*(?!\\*)([^*\\n]+)\\*(?!\\*)","g"),"$1"],[new RegExp("(?<!_)_(?!_)([^_\\n]+)_(?!_)","g"),"$1"],[/~~(.+?)~~/g,"$1"],[/^#{1,6}\s+/gm,""],[/^>\s?/gm,""],[/^[-*+]\s+/gm,""],[/^\d+\.\s+/gm,""],[/^---+\s*$/gm,""],[/^\s*\|.*\|\s*$/gm,""]];function z7(e,t=140){if(!e)return"";let s=e;for(const[r,i]of D7)s=s.replace(r,i);return s=s.replace(/\s+/g," ").trim(),s.length>t&&(s=`${s.slice(0,t-1)}…`),s}const BC="scout:sessions:lastViewed";function ZC(){if(typeof localStorage>"u")return{};try{const e=localStorage.getItem(BC);if(!e)return{};const t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function I7(e,t=Date.now()){const s=ZC();s[e]=t;try{localStorage.setItem(BC,JSON.stringify(s))}catch{}return s}function sm(e,t,s){return e?e>(s[t]??0):!1}const MS={direct:"DM",channel:"Channel",group_direct:"Group",thread:"Thread"},L7=new Set(["all","direct","channel","group_direct","thread"]);function og(e){return typeof window>"u"?"":new URLSearchParams(window.location.search).get(e)??""}function P7(e){if(typeof window>"u")return;const t=new URLSearchParams(window.location.search);for(const[r,i]of Object.entries(e))i===null||i===""?t.delete(r):t.set(r,i);const s=t.toString();window.history.replaceState(null,"",window.location.pathname+(s?`?${s}`:""))}function U7(){const e=og("view");return L7.has(e)?e:"all"}function $7(e){return e.kind==="direct"&&e.agentName?e.agentName:e.title.replace(/\s*<>\s*/g," · ")}function V7(e){if(!e)return null;const t=e.replace(/[\\/]+$/,"");return t?t.split(/[\\/]/).filter(Boolean).at(-1)??t:null}function B7(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return"";const t=e<1e12?e*1e3:e;return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(t)}function Z7({navigate:e}){const[t,s]=b.useState([]),[r,i]=b.useState(()=>U7()),[l,c]=b.useState(()=>og("q")),[f,p]=b.useState(()=>og("unread")==="1"),[h,g]=b.useState(()=>ZC()),[v,x]=b.useState(0),[w,T]=b.useState(null),N=b.useRef(null),A=b.useRef(null),C=mo(),j=b.useCallback(async()=>{T(null);try{const $=await ot("/api/sessions");s($.sort((L,Y)=>(Y.lastMessageAt??0)-(L.lastMessageAt??0)))}catch($){T($ instanceof Error?$.message:String($))}},[]);b.useEffect(()=>{j()},[j]),Kn(j);const[,S]=b.useState(0);b.useEffect(()=>{const $=setInterval(()=>S(L=>L+1),15e3);return()=>clearInterval($)},[]),b.useEffect(()=>{P7({view:r==="all"?null:r,q:l.trim()||null,unread:f?"1":null})},[r,l,f]);const _=b.useMemo(()=>Array.from(new Set(t.map($=>$.kind))),[t]),R=b.useMemo(()=>{const $={all:t.length};for(const L of t)$[L.kind]=($[L.kind]??0)+1;return $},[t]),M=b.useMemo(()=>t.filter($=>sm($.lastMessageAt,$.id,h)).length,[t,h]),O=b.useMemo(()=>{const $=l.trim().toLowerCase();return t.filter(L=>!(r!=="all"&&L.kind!==r||f&&!sm(L.lastMessageAt,L.id,h)||$&&![L.title,L.preview,L.agentName??"",L.harness??"",...L.participantIds].join(" ").toLowerCase().includes($)))},[t,r,f,h,l]);b.useEffect(()=>{v>=O.length&&x(Math.max(0,O.length-1))},[O.length,v]);const I=b.useCallback($=>{g(I7($.id)),e({view:"conversation",conversationId:$.id})},[e]);b.useEffect(()=>{function $(L){const Y=L.target,re=Y instanceof HTMLInputElement||Y instanceof HTMLTextAreaElement||Y instanceof HTMLElement&&Y.isContentEditable;if((L.metaKey||L.ctrlKey)&&L.key.toLowerCase()==="k"){L.preventDefault(),N.current?.focus(),N.current?.select();return}if(re){L.key==="Escape"&&Y===N.current&&N.current?.blur();return}if(L.key==="/"){L.preventDefault(),N.current?.focus();return}if(L.key==="j"||L.key==="ArrowDown"){L.preventDefault(),x(Q=>Math.min(O.length-1,Q+1));return}if(L.key==="k"||L.key==="ArrowUp"){L.preventDefault(),x(Q=>Math.max(0,Q-1));return}if(L.key==="Enter"||L.key==="o"){const Q=O[v];Q&&(L.preventDefault(),I(Q))}}return window.addEventListener("keydown",$),()=>window.removeEventListener("keydown",$)},[O,v,I]),b.useEffect(()=>{A.current?.querySelector(`[data-idx="${v}"]`)?.scrollIntoView({block:"nearest"})},[v]);const H=_.length>1,F=f?M>0?`${M} unread threads need attention.`:"No unread threads right now.":O.length===t.length?"Recent activity across every conversation.":`${O.length} conversations match the current filters.`;return d.jsxs("div",{className:"s-sessions-screen s-inbox-thread-redesign",children:[d.jsx("section",{className:"s-thread-overview",children:d.jsxs("div",{className:"s-thread-overview-copy",children:[d.jsxs("div",{className:"s-sessions-header s-thread-overview-heading",children:[d.jsx("h2",{className:"s-page-title",children:"Sessions"}),d.jsxs("span",{className:"s-meta s-tabular",children:[O.length," of ",t.length]})]}),d.jsx("p",{className:"s-thread-overview-summary",children:F})]})}),d.jsxs("section",{className:"s-thread-panel s-thread-panel-list",children:[d.jsxs("div",{className:"s-sessions-toolbar",children:[H&&d.jsxs("div",{className:"s-seg",role:"tablist","aria-label":"Session kind",children:[d.jsx(OS,{label:"All",count:R.all,pressed:r==="all",onClick:()=>i("all")}),_.map($=>d.jsx(OS,{label:MS[$]??$,count:R[$]??0,pressed:r===$,onClick:()=>i($)},$))]}),d.jsxs("button",{type:"button",className:`s-seg-standalone${f?" is-on":""}`,onClick:()=>p($=>!$),"aria-pressed":f,title:"Show unread only",children:[d.jsx("span",{className:"s-dot s-dot-sm","aria-hidden":"true"}),d.jsx("span",{children:"Unread"}),M>0&&d.jsx("span",{className:"s-seg-count",children:M})]}),d.jsxs("div",{className:"s-search",children:[d.jsx("input",{ref:N,type:"text",className:"s-search-input",placeholder:"Search conversations…",value:l,onChange:$=>c($.target.value),onKeyDown:$=>{$.key==="Escape"&&(l?c(""):$.target.blur())}}),d.jsx("kbd",{className:"s-search-kbd",children:"⌘K"})]})]}),w&&d.jsx("p",{className:"s-error",children:w}),O.length===0?d.jsxs("div",{className:"s-empty s-thread-empty-state",children:[d.jsx("p",{children:l||f?"No matches":"No conversations"}),d.jsx("p",{children:l?"Try a different search term.":f?"You're all caught up.":"Conversations appear here when agents communicate."})]}):d.jsx("div",{className:"s-inbox",ref:A,role:"listbox","aria-label":"Sessions",children:O.map(($,L)=>{const Y=$7($),re=($.agentName??Y)[0]?.toUpperCase()??"?",Q=sm($.lastMessageAt,$.id,h),z=L===v,Z=z7($.preview,160),B=MS[$.kind]??$.kind,ie=V7($.workspaceRoot);return d.jsxs("div",{"data-idx":L,"data-unread":Q?"true":"false","data-selected":z?"true":"false",className:"s-inbox-row",role:"option","aria-selected":z,tabIndex:z?0:-1,onClick:()=>{VC(()=>{x(L),I($)})},onMouseEnter:()=>x(L),onContextMenu:W=>{const D=window.getSelection()?.toString().trim(),P=[];D&&(P.push({kind:"action",label:"Copy Selection",shortcut:"⌘C",onSelect:()=>navigator.clipboard.writeText(D)}),P.push({kind:"separator"})),P.push({kind:"action",label:"Open Conversation",onSelect:()=>I($)}),P.push({kind:"action",label:"Copy Title",onSelect:()=>navigator.clipboard.writeText(Y)}),$.id&&P.push({kind:"action",label:"Copy Conversation ID",onSelect:()=>navigator.clipboard.writeText($.id)}),C(W,P)},children:[d.jsxs("div",{className:"s-session-avatar-wrap",children:[d.jsx("div",{className:"s-avatar",style:{background:Ts($.agentName??Y)},"aria-hidden":"true",children:re}),Q&&d.jsx("span",{className:"s-session-unread-dot","aria-hidden":"true"})]}),d.jsxs("div",{className:"s-inbox-body",children:[d.jsxs("div",{className:"s-inbox-header",children:[d.jsx("div",{className:"s-session-heading",children:d.jsx("span",{className:"s-inbox-name",title:Y,children:Y})}),d.jsx("div",{className:"s-session-trailing",children:$.lastMessageAt&&d.jsx("span",{className:"s-inbox-time s-tabular",title:B7($.lastMessageAt),children:tt($.lastMessageAt)})})]}),Z?d.jsx("p",{className:"s-inbox-preview",children:Z}):d.jsx("p",{className:"s-inbox-preview s-inbox-preview-empty",children:"No messages yet"}),d.jsxs("div",{className:"s-session-meta-row","aria-label":"Conversation details",children:[d.jsx("span",{className:"s-session-pill",children:B}),ie&&d.jsx("span",{className:"s-session-pill",title:$.workspaceRoot??void 0,children:ie}),$.currentBranch&&d.jsx("span",{className:"s-session-pill",title:$.currentBranch,children:$.currentBranch})]})]})]},$.id)})})]})]})}function OS({label:e,count:t,pressed:s,onClick:r}){return d.jsxs("button",{type:"button",className:"s-seg-btn","aria-pressed":s,onClick:r,children:[d.jsx("span",{children:e}),d.jsx("span",{className:"s-seg-count",children:t})]})}var Oa=(e=>(e[e.Border=-1]="Border",e[e.Data=0]="Data",e[e.Function=1]="Function",e[e.Position=2]="Position",e[e.Timing=3]="Timing",e[e.Alignment=4]="Alignment",e))(Oa||{});const H7=[0,1],HC=[1,0],FC=[2,3],qC=[3,2],F7={L:H7,M:HC,Q:FC,H:qC},q7=/^\d*$/,Y7=/^[A-Z0-9 $%*+./:-]*$/,rm="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:",vy=1,by=40,DS=3,G7=3,Pu=40,X7=10,YC=[[-1,7,10,15,20,26,18,20,24,30,18,20,24,26,30,22,24,28,30,28,28,28,28,30,30,26,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],[-1,13,22,18,26,18,24,18,22,20,24,28,26,24,20,30,24,28,28,26,30,28,30,30,30,30,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,17,28,22,16,22,28,26,26,24,28,24,28,22,24,24,30,28,28,26,28,30,24,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30]],GC=[[-1,1,1,1,1,1,2,2,2,2,4,4,4,4,4,6,6,6,6,7,8,8,9,9,10,12,12,12,13,14,15,16,17,18,19,19,20,21,22,24,25],[-1,1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49],[-1,1,1,2,2,4,4,6,6,8,8,8,10,12,16,12,17,16,18,21,20,23,23,25,27,29,34,34,35,38,40,43,45,48,51,53,56,59,62,65,68],[-1,1,1,2,4,4,4,5,6,8,8,11,11,16,16,18,16,19,21,25,25,25,34,30,32,35,37,40,42,45,48,51,54,57,60,63,66,70,74,77,81]];class K7{constructor(t,s,r,i){if(this.version=t,this.ecc=s,t<vy||t>by)throw new RangeError("Version value out of range");if(i<-1||i>7)throw new RangeError("Mask value out of range");this.size=t*4+17;const l=Array.from({length:this.size}).fill(!1);for(let f=0;f<this.size;f++)this.modules.push(l.slice()),this.types.push(l.map(()=>0));this.drawFunctionPatterns();const c=this.addEccAndInterleave(r);if(this.drawCodewords(c),i===-1){let f=1e9;for(let p=0;p<8;p++){this.applyMask(p),this.drawFormatBits(p);const h=this.getPenaltyScore();h<f&&(i=p,f=h),this.applyMask(p)}}this.mask=i,this.applyMask(i),this.drawFormatBits(i)}size;mask;modules=[];types=[];getModule(t,s){return t>=0&&t<this.size&&s>=0&&s<this.size&&this.modules[s][t]}drawFunctionPatterns(){for(let r=0;r<this.size;r++)this.setFunctionModule(6,r,r%2===0,Oa.Timing),this.setFunctionModule(r,6,r%2===0,Oa.Timing);this.drawFinderPattern(3,3),this.drawFinderPattern(this.size-4,3),this.drawFinderPattern(3,this.size-4);const t=this.getAlignmentPatternPositions(),s=t.length;for(let r=0;r<s;r++)for(let i=0;i<s;i++)r===0&&i===0||r===0&&i===s-1||r===s-1&&i===0||this.drawAlignmentPattern(t[r],t[i]);this.drawFormatBits(0),this.drawVersion()}drawFormatBits(t){const s=this.ecc[1]<<3|t;let r=s;for(let l=0;l<10;l++)r=r<<1^(r>>>9)*1335;const i=(s<<10|r)^21522;for(let l=0;l<=5;l++)this.setFunctionModule(8,l,cr(i,l));this.setFunctionModule(8,7,cr(i,6)),this.setFunctionModule(8,8,cr(i,7)),this.setFunctionModule(7,8,cr(i,8));for(let l=9;l<15;l++)this.setFunctionModule(14-l,8,cr(i,l));for(let l=0;l<8;l++)this.setFunctionModule(this.size-1-l,8,cr(i,l));for(let l=8;l<15;l++)this.setFunctionModule(8,this.size-15+l,cr(i,l));this.setFunctionModule(8,this.size-8,!0)}drawVersion(){if(this.version<7)return;let t=this.version;for(let r=0;r<12;r++)t=t<<1^(t>>>11)*7973;const s=this.version<<12|t;for(let r=0;r<18;r++){const i=cr(s,r),l=this.size-11+r%3,c=Math.floor(r/3);this.setFunctionModule(l,c,i),this.setFunctionModule(c,l,i)}}drawFinderPattern(t,s){for(let r=-4;r<=4;r++)for(let i=-4;i<=4;i++){const l=Math.max(Math.abs(i),Math.abs(r)),c=t+i,f=s+r;c>=0&&c<this.size&&f>=0&&f<this.size&&this.setFunctionModule(c,f,l!==2&&l!==4,Oa.Position)}}drawAlignmentPattern(t,s){for(let r=-2;r<=2;r++)for(let i=-2;i<=2;i++)this.setFunctionModule(t+i,s+r,Math.max(Math.abs(i),Math.abs(r))!==1,Oa.Alignment)}setFunctionModule(t,s,r,i=Oa.Function){this.modules[s][t]=r,this.types[s][t]=i}addEccAndInterleave(t){const s=this.version,r=this.ecc;if(t.length!==nd(s,r))throw new RangeError("Invalid argument");const i=GC[r[0]][s],l=YC[r[0]][s],c=Math.floor(lg(s)/8),f=i-c%i,p=Math.floor(c/i),h=[],g=aZ(l);for(let x=0,w=0;x<i;x++){const T=t.slice(w,w+p-l+(x<f?0:1));w+=T.length;const N=iZ(T,g);x<f&&T.push(0),h.push(T.concat(N))}const v=[];for(let x=0;x<h[0].length;x++)h.forEach((w,T)=>{(x!==p-l||T>=f)&&v.push(w[x])});return v}drawCodewords(t){if(t.length!==Math.floor(lg(this.version)/8))throw new RangeError("Invalid argument");let s=0;for(let r=this.size-1;r>=1;r-=2){r===6&&(r=5);for(let i=0;i<this.size;i++)for(let l=0;l<2;l++){const c=r-l,p=(r+1&2)===0?this.size-1-i:i;!this.types[p][c]&&s<t.length*8&&(this.modules[p][c]=cr(t[s>>>3],7-(s&7)),s++)}}}applyMask(t){if(t<0||t>7)throw new RangeError("Mask value out of range");for(let s=0;s<this.size;s++)for(let r=0;r<this.size;r++){let i;switch(t){case 0:i=(r+s)%2===0;break;case 1:i=s%2===0;break;case 2:i=r%3===0;break;case 3:i=(r+s)%3===0;break;case 4:i=(Math.floor(r/3)+Math.floor(s/2))%2===0;break;case 5:i=r*s%2+r*s%3===0;break;case 6:i=(r*s%2+r*s%3)%2===0;break;case 7:i=((r+s)%2+r*s%3)%2===0;break;default:throw new Error("Unreachable")}!this.types[s][r]&&i&&(this.modules[s][r]=!this.modules[s][r])}}getPenaltyScore(){let t=0;for(let l=0;l<this.size;l++){let c=!1,f=0;const p=[0,0,0,0,0,0,0];for(let h=0;h<this.size;h++)this.modules[l][h]===c?(f++,f===5?t+=DS:f>5&&t++):(this.finderPenaltyAddHistory(f,p),c||(t+=this.finderPenaltyCountPatterns(p)*Pu),c=this.modules[l][h],f=1);t+=this.finderPenaltyTerminateAndCount(c,f,p)*Pu}for(let l=0;l<this.size;l++){let c=!1,f=0;const p=[0,0,0,0,0,0,0];for(let h=0;h<this.size;h++)this.modules[h][l]===c?(f++,f===5?t+=DS:f>5&&t++):(this.finderPenaltyAddHistory(f,p),c||(t+=this.finderPenaltyCountPatterns(p)*Pu),c=this.modules[h][l],f=1);t+=this.finderPenaltyTerminateAndCount(c,f,p)*Pu}for(let l=0;l<this.size-1;l++)for(let c=0;c<this.size-1;c++){const f=this.modules[l][c];f===this.modules[l][c+1]&&f===this.modules[l+1][c]&&f===this.modules[l+1][c+1]&&(t+=G7)}let s=0;for(const l of this.modules)s=l.reduce((c,f)=>c+(f?1:0),s);const r=this.size*this.size,i=Math.ceil(Math.abs(s*20-r*10)/r)-1;return t+=i*X7,t}getAlignmentPatternPositions(){if(this.version===1)return[];{const t=Math.floor(this.version/7)+2,s=this.version===32?26:Math.ceil((this.version*4+4)/(t*2-2))*2,r=[6];for(let i=this.size-7;r.length<t;i-=s)r.splice(1,0,i);return r}}finderPenaltyCountPatterns(t){const s=t[1],r=s>0&&t[2]===s&&t[3]===s*3&&t[4]===s&&t[5]===s;return(r&&t[0]>=s*4&&t[6]>=s?1:0)+(r&&t[6]>=s*4&&t[0]>=s?1:0)}finderPenaltyTerminateAndCount(t,s,r){return t&&(this.finderPenaltyAddHistory(s,r),s=0),s+=this.size,this.finderPenaltyAddHistory(s,r),this.finderPenaltyCountPatterns(r)}finderPenaltyAddHistory(t,s){s[0]===0&&(t+=this.size),s.pop(),s.unshift(t)}}function dr(e,t,s){if(t<0||t>31||e>>>t)throw new RangeError("Value out of range");for(let r=t-1;r>=0;r--)s.push(e>>>r&1)}function cr(e,t){return(e>>>t&1)!==0}class xy{constructor(t,s,r){if(this.mode=t,this.numChars=s,this.bitData=r,s<0)throw new RangeError("Invalid argument");this.bitData=r.slice()}getData(){return this.bitData.slice()}}const W7=[1,10,12,14],J7=[2,9,11,13],Q7=[4,8,16,16];function XC(e,t){return e[Math.floor((t+7)/17)+1]}function KC(e){const t=[];for(const s of e)dr(s,8,t);return new xy(Q7,e.length,t)}function eZ(e){if(!WC(e))throw new RangeError("String contains non-numeric characters");const t=[];for(let s=0;s<e.length;){const r=Math.min(e.length-s,3);dr(Number.parseInt(e.substring(s,s+r),10),r*3+1,t),s+=r}return new xy(W7,e.length,t)}function tZ(e){if(!JC(e))throw new RangeError("String contains unencodable characters in alphanumeric mode");const t=[];let s;for(s=0;s+2<=e.length;s+=2){let r=rm.indexOf(e.charAt(s))*45;r+=rm.indexOf(e.charAt(s+1)),dr(r,11,t)}return s<e.length&&dr(rm.indexOf(e.charAt(s)),6,t),new xy(J7,e.length,t)}function nZ(e){return e===""?[]:WC(e)?[eZ(e)]:JC(e)?[tZ(e)]:[KC(rZ(e))]}function WC(e){return q7.test(e)}function JC(e){return Y7.test(e)}function sZ(e,t){let s=0;for(const r of e){const i=XC(r.mode,t);if(r.numChars>=1<<i)return Number.POSITIVE_INFINITY;s+=4+i+r.bitData.length}return s}function rZ(e){e=encodeURI(e);const t=[];for(let s=0;s<e.length;s++)e.charAt(s)!=="%"?t.push(e.charCodeAt(s)):(t.push(Number.parseInt(e.substring(s+1,s+3),16)),s+=2);return t}function lg(e){if(e<vy||e>by)throw new RangeError("Version number out of range");let t=(16*e+128)*e+64;if(e>=2){const s=Math.floor(e/7)+2;t-=(25*s-10)*s-55,e>=7&&(t-=36)}return t}function nd(e,t){return Math.floor(lg(e)/8)-YC[t[0]][e]*GC[t[0]][e]}function aZ(e){if(e<1||e>255)throw new RangeError("Degree out of range");const t=[];for(let r=0;r<e-1;r++)t.push(0);t.push(1);let s=1;for(let r=0;r<e;r++){for(let i=0;i<t.length;i++)t[i]=cg(t[i],s),i+1<t.length&&(t[i]^=t[i+1]);s=cg(s,2)}return t}function iZ(e,t){const s=t.map(r=>0);for(const r of e){const i=r^s.shift();s.push(0),t.forEach((l,c)=>s[c]^=cg(l,i))}return s}function cg(e,t){if(e>>>8||t>>>8)throw new RangeError("Byte out of range");let s=0;for(let r=7;r>=0;r--)s=s<<1^(s>>>7)*285,s^=(t>>>r&1)*e;return s}function oZ(e,t,s=1,r=40,i=-1,l=!0){if(!(vy<=s&&s<=r&&r<=by)||i<-1||i>7)throw new RangeError("Invalid value");let c,f;for(c=s;;c++){const v=nd(c,t)*8,x=sZ(e,c);if(x<=v){f=x;break}if(c>=r)throw new RangeError("Data too long")}for(const v of[HC,FC,qC])l&&f<=nd(c,v)*8&&(t=v);const p=[];for(const v of e){dr(v.mode[0],4,p),dr(v.numChars,XC(v.mode,c),p);for(const x of v.getData())p.push(x)}const h=nd(c,t)*8;dr(0,Math.min(4,h-p.length),p),dr(0,(8-p.length%8)%8,p);for(let v=236;p.length<h;v^=253)dr(v,8,p);const g=Array.from({length:Math.ceil(p.length/8)},()=>0);return p.forEach((v,x)=>g[x>>>3]|=v<<7-(x&7)),new K7(c,t,g,i)}function lZ(e,t){const{ecc:s="L",boostEcc:r=!1,minVersion:i=1,maxVersion:l=40,maskPattern:c=-1,border:f=1}=t||{},p=typeof e=="string"?nZ(e):Array.isArray(e)?[KC(e)]:void 0;if(!p)throw new Error(`uqr only supports encoding string and binary data, but got: ${typeof e}`);const h=oZ(p,F7[s],i,l,c,r),g=cZ({version:h.version,maskPattern:h.mask,size:h.size,data:h.modules,types:h.types},f);return t?.invert&&(g.data=g.data.map(v=>v.map(x=>!x))),t?.onEncoded?.(g),g}function cZ(e,t=1){if(!t)return e;const{size:s}=e,r=s+t*2;e.size=r,e.data.forEach(l=>{for(let c=0;c<t;c++)l.unshift(!1),l.push(!1)});for(let l=0;l<t;l++)e.data.unshift(Array.from({length:r},c=>!1)),e.data.push(Array.from({length:r},c=>!1));const i=Oa.Border;e.types.forEach(l=>{for(let c=0;c<t;c++)l.unshift(i),l.push(i)});for(let l=0;l<t;l++)e.types.unshift(Array.from({length:r},c=>i)),e.types.push(Array.from({length:r},c=>i));return e}function zS(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function uZ(e,t={}){const s=lZ(e,t),{pixelSize:r=10,whiteColor:i="white",blackColor:l="black"}=t,c=s.size*r,f=s.size*r;let p=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${f} ${c}">`;const h=[];for(let g=0;g<s.size;g++)for(let v=0;v<s.size;v++){const x=v*r,w=g*r;s.data[g][v]&&h.push(`M${x},${w}h${r}v${r}h-${r}z`)}return p+=`<rect fill="${zS(i)}" width="${f}" height="${c}"/>`,p+=`<path fill="${zS(l)}" d="${h.join("")}"/>`,p+="</svg>",p}function dZ(e){return e?e.replace(/^wss?:\/\//,"").replace(/:\d+$/,""):null}function IS(e){return e?e.length<=18?e:`${e.slice(0,10)}...${e.slice(-6)}`:null}function fZ(e){return e?e.status==="paired"||e.status==="connected"?"success":e.status==="error"||e.status==="closed"?"danger":"warning":"warning"}function hZ(e,t){if(!e)return null;const s=Math.max(0,Math.floor((e-t)/1e3));if(s===0)return null;if(s<60)return`${s}s`;const r=Math.floor(s/60),i=s%60;return i>0?`${r}m ${i}s`:`${r}m`}function LS({value:e}){const[t,s]=b.useState(!1),r=b.useCallback(()=>{navigator.clipboard.writeText(e).then(()=>{s(!0),setTimeout(()=>s(!1),1500)})},[e]);return d.jsx("button",{type:"button",className:"sys-copy-btn",onClick:r,title:"Copy",children:t?d.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:d.jsx("polyline",{points:"20 6 9 17 4 12"})}):d.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[d.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),d.jsx("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})}function pZ({navigate:e}){const[t,s]=b.useState(null),[r,i]=b.useState(""),[l,c]=b.useState(""),[f,p]=b.useState(!0),[h,g]=b.useState(!1),[v,x]=b.useState(!1),[w,T]=b.useState(null),[N,A]=b.useState(null),[C,j]=b.useState(null),[S,_]=b.useState(null),[R,M]=b.useState(()=>Date.now()),[O,I]=b.useState(null),H=b.useRef(null),F=b.useRef(0),$=b.useRef(null);b.useEffect(()=>{H.current=t},[t]),b.useEffect(()=>{$.current=w},[w]);const L=b.useCallback(async(ee="initial")=>{if(ee==="background"&&$.current)return;const ve=++F.current;!(H.current!==null)&&ee!=="background"?(p(!0),A(null)):g(!0);try{const pe=await ot(ee==="manual"?"/api/pairing-state/refresh":"/api/pairing-state");if(ve!==F.current)return;s(pe),A(null),_(Date.now())}catch(pe){if(ve!==F.current)return;A(pe instanceof Error?pe.message:String(pe))}finally{ve===F.current&&(p(!1),g(!1))}},[]),Y=b.useCallback(async()=>{try{const ee=await ot("/api/user");c(ee.name),i(ee.name),j(null)}catch(ee){j(ee instanceof Error?ee.message:String(ee))}},[]);b.useEffect(()=>{L("initial"),Y()},[L,Y]),b.useEffect(()=>{const ee=setInterval(()=>{L("background")},1e4);return()=>clearInterval(ee)},[L]),b.useEffect(()=>{if(!t?.pairing?.expiresAt)return;M(Date.now());const ee=setInterval(()=>{M(Date.now())},1e3);return()=>clearInterval(ee)},[t?.pairing?.expiresAt]);const re=b.useCallback(async()=>{x(!0),j(null);try{const ee=await ot("/api/user",{method:"POST",body:JSON.stringify({name:r})});c(ee.name),i(ee.name)}catch(ee){j(ee instanceof Error?ee.message:String(ee))}finally{x(!1)}},[r]),Q=b.useCallback(async ee=>{const ve=++F.current;T(ee),A(null);try{const he=await ot("/api/pairing/control",{method:"POST",body:JSON.stringify({action:ee})});if(ve!==F.current)return;s(he),_(Date.now())}catch(he){if(ve!==F.current)return;A(he instanceof Error?he.message:String(he))}finally{ve===F.current&&T(null)}},[]),z=b.useCallback(async ee=>{I(ee);try{await ot(`/api/pairing/peers/${encodeURIComponent(ee)}`,{method:"DELETE"}),L("manual")}catch{}finally{I(null)}},[L]),Z=b.useMemo(()=>{const ee=t?.pairing?.qrValue?.trim();return ee?uZ(ee,{border:2,ecc:"M",pixelSize:8}):null},[t?.pairing?.qrValue]),B=dZ(t?.pairing?.relay??t?.relay??null),ie=hZ(t?.pairing?.expiresAt,R),D=(t?.trustedPeers.find(ee=>ee.fingerprint===t.connectedPeerFingerprint)??null)?.name??IS(t?.connectedPeerFingerprint??null),P=fZ(t),G=r.trim()!==l,te=!f&&!t&&!!N;return d.jsxs("div",{className:"sys-surface-page sys-settings-page",children:[d.jsxs("div",{className:"sys-page-head",children:[d.jsxs("div",{className:"sys-page-title-group",children:[d.jsx("h2",{className:"sys-page-title",children:"Settings"}),d.jsx("p",{className:"sys-page-subtitle",children:"Identity, pairing, and trusted devices."})]}),d.jsxs("div",{className:"sys-page-actions",children:[t&&d.jsx("span",{className:`sys-chip sys-chip-${P}`,children:t.statusLabel}),d.jsx("div",{className:"sys-sync-note",children:f?"Loading...":N&&t?`Snapshot from ${S?tt(S):"earlier"}`:S?`Updated ${tt(S)}`:""}),d.jsx("button",{type:"button",className:"s-btn",disabled:f||h||!!w,onClick:()=>{L("manual")},children:h?"Refreshing...":"Refresh"})]})]}),N&&t&&d.jsxs("div",{className:"sys-banner sys-banner-warning",children:[d.jsx("strong",{children:"Refresh failed."}),d.jsx("span",{children:N})]}),C&&d.jsxs("div",{className:"sys-banner sys-banner-warning",children:[d.jsx("strong",{children:"Identity error."}),d.jsx("span",{children:C})]}),f&&!t&&d.jsxs("div",{className:"sys-panel sys-state-card",children:[d.jsx("h3",{className:"sys-state-title",children:"Loading settings"}),d.jsx("p",{className:"sys-state-body",children:"Checking relay status and trusted peers."})]}),te&&d.jsxs("div",{className:"sys-panel sys-state-card sys-state-card-error",children:[d.jsx("h3",{className:"sys-state-title",children:"Pairing unavailable"}),d.jsx("p",{className:"sys-state-body",children:N}),d.jsx("div",{className:"sys-inline-actions",children:d.jsx("button",{type:"button",className:"s-btn",onClick:()=>{L("manual")},children:"Try again"})})]}),d.jsxs("div",{className:"sys-settings-hero",children:[d.jsx("div",{className:"sys-settings-qr-col",children:Z?d.jsxs("div",{className:"sys-settings-qr-frame",children:[d.jsx("div",{className:"s-qr",dangerouslySetInnerHTML:{__html:Z}}),ie&&d.jsxs("span",{className:"sys-settings-qr-expires",children:["Expires in ",ie]})]}):d.jsx("div",{className:"sys-settings-qr-empty",children:d.jsx("span",{className:"sys-settings-qr-empty-label",children:t?.isRunning?"Waiting for QR...":"Start pairing to generate QR"})})}),d.jsxs("div",{className:"sys-settings-info-col",children:[d.jsxs("div",{className:"sys-input-row",children:[d.jsx("input",{className:"sys-input",type:"text",placeholder:"Your name",value:r,onChange:ee=>i(ee.target.value),onKeyDown:ee=>{ee.key==="Enter"&&G&&!v&&re()}}),d.jsx("button",{type:"button",className:"s-btn s-btn-primary",disabled:!G||v,onClick:()=>{re()},children:v?"Saving...":"Save"})]}),d.jsxs("div",{className:"sys-settings-kv-list",children:[t?.identityFingerprint&&d.jsxs("div",{className:"sys-settings-kv",children:[d.jsx("span",{className:"sys-settings-kv-label",children:"Fingerprint"}),d.jsxs("span",{className:"sys-settings-kv-value",children:[d.jsx("code",{children:t.identityFingerprint}),d.jsx(LS,{value:t.identityFingerprint})]})]}),B&&d.jsxs("div",{className:"sys-settings-kv",children:[d.jsx("span",{className:"sys-settings-kv-label",children:"Relay"}),d.jsxs("span",{className:"sys-settings-kv-value",children:[d.jsx("code",{children:B}),d.jsx(LS,{value:B})]})]}),t?.statusDetail&&d.jsxs("div",{className:"sys-settings-kv",children:[d.jsx("span",{className:"sys-settings-kv-label",children:"Status"}),d.jsx("span",{className:"sys-settings-kv-value sys-settings-kv-nowrap",children:t.statusDetail})]}),D&&d.jsxs("div",{className:"sys-settings-kv",children:[d.jsx("span",{className:"sys-settings-kv-label",children:"Connected"}),d.jsx("span",{className:"sys-settings-kv-value",children:D})]}),t?.secure&&d.jsxs("div",{className:"sys-settings-kv",children:[d.jsx("span",{className:"sys-settings-kv-label",children:"Security"}),d.jsx("span",{className:"sys-settings-kv-value",children:d.jsx("span",{className:"sys-chip sys-chip-success",style:{margin:0},children:"Noise XX"})})]})]}),t&&d.jsx("div",{className:"sys-inline-actions sys-settings-controls",children:t.isRunning?d.jsxs(d.Fragment,{children:[d.jsx("button",{type:"button",className:"s-btn",disabled:!!w,onClick:()=>{Q("restart")},children:w==="restart"?"Restarting...":"Restart"}),d.jsx("button",{type:"button",className:"s-btn",disabled:!!w,onClick:()=>{Q("stop")},children:w==="stop"?"Stopping...":"Stop"})]}):d.jsx("button",{type:"button",className:"s-btn s-btn-primary",disabled:!!w,onClick:()=>{Q("start")},children:w==="start"?"Starting...":"Start pairing"})})]})]}),t&&d.jsxs("section",{className:"sys-settings-peers",children:[d.jsx("div",{className:"sys-section-head",children:d.jsxs("div",{children:[d.jsx("h3",{className:"sys-section-title",children:"Trusted peers"}),d.jsxs("p",{className:"sys-section-subtitle",children:[t.trustedPeers.length," device",t.trustedPeers.length!==1?"s":""," paired with this broker."]})]})}),t.trustedPeers.length===0?d.jsxs("div",{className:"sys-list-empty",children:[d.jsx("h3",{children:"No trusted peers"}),d.jsx("p",{children:"Devices appear here after completing pairing."})]}):d.jsxs("table",{className:"sys-peers-table",children:[d.jsx("thead",{children:d.jsxs("tr",{children:[d.jsx("th",{children:"Device"}),d.jsx("th",{children:"Fingerprint"}),d.jsx("th",{children:"Paired"}),d.jsx("th",{children:"Last seen"}),d.jsx("th",{})]})}),d.jsx("tbody",{children:t.trustedPeers.map(ee=>{const ve=ee.fingerprint===t.connectedPeerFingerprint;return d.jsxs("tr",{className:ve?"sys-peers-row-connected":"",children:[d.jsx("td",{children:d.jsxs("span",{className:"sys-peers-name",children:[ee.name??IS(ee.fingerprint)??"Peer",ve&&d.jsx("span",{className:"sys-chip sys-chip-success sys-peers-badge",children:"Connected"})]})}),d.jsx("td",{children:d.jsx("code",{className:"sys-peers-fp",children:ee.fingerprint})}),d.jsx("td",{children:ee.pairedAtLabel??"—"}),d.jsx("td",{children:ee.lastSeenLabel??"—"}),d.jsx("td",{children:d.jsx("button",{type:"button",className:"sys-peers-remove",disabled:O===ee.fingerprint,onClick:()=>{z(ee.fingerprint)},title:"Remove peer",children:O===ee.fingerprint?"...":"Remove"})})]},ee.fingerprint)})})]})]})]})}function mZ(e){return e.attention==="interrupt"?"failed":e.state==="done"?"completed":e.attention==="badge"||e.state==="waiting"||e.state==="review"?"updated":"working"}function am(e){switch(e){case"review":return"In review";case"waiting":return"Waiting";case"working":return"Working";case"done":return"Done";default:return e.replace(/_/g," ")}}function gZ(e){switch(e){case"badge":return"Needs attention";case"interrupt":return"Blocked";default:return null}}function yZ(e){switch(e.kind){case"flight_started":return"flight started";case"flight_completed":return e.detailKind?`flight ${e.detailKind}`:"flight ended";case"message":return"message";default:return e.title??e.detailKind??"event"}}function PS(e){return e.kind==="message"?"message":e.kind==="flight_started"?"flight":e.kind==="flight_completed"?e.detailKind?.includes("fail")?"alert":"done":e.detailKind?.includes("interrupt")||e.detailKind?.includes("block")?"alert":"system"}function im({title:e,items:t}){return t.length===0?null:d.jsxs("section",{className:"s-work-fact-card",children:[d.jsx("div",{className:"s-work-fact-card-header",children:d.jsx("div",{className:"s-work-fact-card-title",children:e})}),d.jsx("div",{className:"s-work-fact-card-body",children:t.map(s=>d.jsxs("div",{className:"s-work-fact-row",children:[d.jsx("span",{className:"s-work-fact-label",children:s.label}),d.jsx("span",{className:"s-work-fact-value",children:s.value})]},s.label))})]})}function US({label:e,value:t,onClick:s}){return d.jsxs("button",{type:"button",className:"s-work-action-row",onClick:s,children:[d.jsx("span",{className:"s-work-action-row-label",children:e}),d.jsx("span",{className:"s-work-action-row-value",children:t})]})}function vZ(e){const t=e.split(".");return t[t.length-1]||e}function bZ({workId:e,navigate:t}){const[s,r]=b.useState(null),[i,l]=b.useState(null),[c,f]=b.useState(!1),p=b.useCallback(async()=>{l(null);try{const N=await ot(`/api/work/${encodeURIComponent(e)}`);r(N)}catch(N){l(N instanceof Error?N.message:String(N)),r(null)}finally{f(!0)}},[e]);if(b.useEffect(()=>{f(!1),p()},[p]),Kn(p),!c)return d.jsxs("div",{children:[d.jsx("button",{type:"button",className:"s-back",onClick:()=>t({view:"inbox"}),children:"← Back"}),d.jsx("div",{className:"s-empty",children:d.jsx("p",{children:"Loading…"})})]});if(!s)return d.jsxs("div",{children:[d.jsx("button",{type:"button",className:"s-back",onClick:()=>t({view:"inbox"}),children:"← Back"}),i&&d.jsx("p",{className:"s-error",children:i}),d.jsx("div",{className:"s-empty",children:d.jsx("p",{children:"Work item not found"})})]});const h=gZ(s.attention),g=s.ownerName??s.ownerId??"Unassigned",v=s.nextMoveOwnerName??s.nextMoveOwnerId??"—",x=[{label:"State",value:am(s.state)},{label:"Acceptance",value:s.acceptanceState.replace(/_/g," ")},{label:"Phase",value:s.currentPhase},...h?[{label:"Attention",value:h}]:[]],w=[{label:"Owner",value:g},{label:"Next move",value:v},...s.priority?[{label:"Priority",value:s.priority}]:[],{label:"Conversation",value:s.conversationId?"Attached":"None"}],T=[{label:"Case ID",value:s.id},{label:"Created",value:Ia(s.createdAt)},{label:"Updated",value:Ia(s.updatedAt)},{label:"Last activity",value:Ia(s.lastMeaningfulAt)}];return d.jsxs("div",{className:"s-work-detail s-work-casefile",children:[d.jsxs("div",{className:"s-work-casefile-topbar",children:[d.jsx("button",{type:"button",className:"s-back",onClick:()=>t({view:"inbox"}),children:"← Back"}),d.jsxs("span",{className:"s-work-casefile-record",children:["Case ",vZ(s.id)]})]}),i&&d.jsx("p",{className:"s-error",children:i}),d.jsx("section",{className:"s-work-casefile-hero",children:d.jsxs("div",{className:"s-work-casefile-hero-main",children:[d.jsxs("div",{className:"s-work-casefile-title-row",children:[d.jsx("h1",{className:"s-work-casefile-title",children:s.title}),d.jsx("span",{className:`s-pill s-pill-${mZ(s)}`,children:s.currentPhase})]}),s.lastMeaningfulSummary&&d.jsx("div",{className:"s-work-casefile-summary",children:Yn(s.lastMeaningfulSummary)}),d.jsxs("div",{className:"s-work-casefile-meta",children:[d.jsxs("span",{children:["Updated ",tt(s.updatedAt)]}),d.jsx("span",{children:g}),d.jsx("span",{children:am(s.state)}),h&&d.jsx("span",{children:h}),s.priority&&d.jsxs("span",{children:["Priority ",s.priority]})]})]})}),d.jsxs("div",{className:"s-work-casefile-layout",children:[d.jsxs("div",{className:"s-work-casefile-main",children:[d.jsxs("section",{className:"s-work-casefile-section",children:[d.jsx("div",{className:"s-agent-section-heading",children:d.jsx("h2",{className:"s-agent-section-title",children:"Case facts"})}),d.jsxs("div",{className:"s-work-fact-grid",children:[d.jsx(im,{title:"Status",items:x}),d.jsx(im,{title:"Assignment",items:w})]})]}),s.activeFlights.length>0&&d.jsxs("section",{className:"s-work-casefile-section",children:[d.jsx("div",{className:"s-agent-section-heading",children:d.jsx("h2",{className:"s-agent-section-title",children:"Flights"})}),d.jsx("div",{className:"s-work-flight-list",children:s.activeFlights.map(N=>d.jsxs("button",{type:"button",className:"s-work-flight-card",onClick:N.conversationId?()=>t({view:"conversation",conversationId:N.conversationId}):void 0,disabled:!N.conversationId,children:[d.jsxs("div",{className:"s-work-flight-card-header",children:[d.jsx("span",{className:"s-work-flight-card-title",children:N.agentName??N.agentId}),d.jsx("span",{className:"s-pill s-pill-working",children:N.state})]}),d.jsxs("div",{className:"s-work-flight-card-meta",children:[d.jsx("span",{children:N.startedAt?`Started ${tt(N.startedAt)}`:"Start time unavailable"}),N.completedAt&&d.jsxs("span",{children:["Completed ",tt(N.completedAt)]})]}),N.summary&&d.jsx("div",{className:"s-work-flight-card-copy",children:N.summary})]},N.id))})]}),s.childWork.length>0&&d.jsxs("section",{className:"s-work-casefile-section",children:[d.jsx("div",{className:"s-agent-section-heading",children:d.jsx("h2",{className:"s-agent-section-title",children:"Child work"})}),d.jsx("div",{className:"s-work-related-list",children:s.childWork.map(N=>d.jsxs("button",{type:"button",className:"s-work-related-card",onClick:()=>t({view:"work",workId:N.id}),children:[d.jsxs("div",{className:"s-work-related-card-header",children:[d.jsx("span",{className:"s-work-related-card-title",children:N.title}),d.jsx("span",{className:`s-pill s-pill-${N.attention==="interrupt"?"failed":"updated"}`,children:N.currentPhase})]}),d.jsxs("div",{className:"s-work-related-card-meta",children:[d.jsx("span",{children:N.ownerName??N.ownerId??"Unassigned"}),d.jsx("span",{children:am(N.state)}),d.jsx("span",{children:tt(N.lastMeaningfulAt)})]}),N.lastMeaningfulSummary&&d.jsx("div",{className:"s-work-related-card-copy",children:Yn(N.lastMeaningfulSummary)})]},N.id))})]}),d.jsxs("section",{className:"s-work-casefile-section",children:[d.jsx("div",{className:"s-agent-section-heading",children:d.jsx("h2",{className:"s-agent-section-title",children:"Timeline"})}),s.timeline.length===0?d.jsxs("div",{className:"s-empty",children:[d.jsx("p",{children:"No activity yet."}),d.jsx("p",{children:"Timeline events will appear once the case receives messages or coordination updates."})]}):d.jsx("div",{className:"s-work-timeline",children:s.timeline.map(N=>d.jsxs("button",{type:"button",className:`s-work-timeline-entry${N.conversationId?" s-work-timeline-entry-clickable":""}`,onClick:N.conversationId?()=>t({view:"conversation",conversationId:N.conversationId}):void 0,disabled:!N.conversationId,children:[d.jsx("span",{className:`s-work-timeline-marker s-work-timeline-marker-${PS(N)}`}),d.jsxs("div",{className:"s-work-timeline-content",children:[d.jsxs("div",{className:"s-work-timeline-header",children:[d.jsx("span",{className:"s-work-timeline-time",children:tt(N.at)}),d.jsx("span",{className:`s-work-timeline-kind s-work-timeline-kind-${PS(N)}`,children:yZ(N)})]}),d.jsx("div",{className:"s-work-timeline-actor",children:N.actorName??"system"}),N.title&&d.jsx("div",{className:"s-work-timeline-title",children:N.title}),N.summary&&d.jsx("div",{className:"s-work-timeline-summary",children:Yn(N.summary)}),d.jsx("div",{className:"s-work-timeline-stamp",children:Ia(N.at)})]})]},N.id))})]})]}),d.jsxs("aside",{className:"s-work-casefile-side",children:[d.jsx(im,{title:"Record",items:T}),d.jsxs("section",{className:"s-work-fact-card",children:[d.jsx("div",{className:"s-work-fact-card-header",children:d.jsx("div",{className:"s-work-fact-card-title",children:"Links"})}),d.jsxs("div",{className:"s-work-action-list",children:[s.conversationId?d.jsx(US,{label:"Conversation",value:"Open thread",onClick:()=>t({view:"conversation",conversationId:s.conversationId})}):d.jsx("div",{className:"s-work-action-list-empty",children:"No conversation attached."}),s.parentId&&s.parentTitle?d.jsx(US,{label:"Parent",value:s.parentTitle,onClick:()=>t({view:"work",workId:s.parentId})}):d.jsx("div",{className:"s-work-action-list-empty",children:"No parent work item."})]})]})]})]})]})}function xZ(){const{route:e,navigate:t}=Yt();return d.jsx(wZ,{children:SZ(e,t)})}function wZ({children:e}){return d.jsx("div",{style:{background:"var(--bg)",color:"var(--ink)",minHeight:"100%",height:"100%",display:"flex",flexDirection:"column"},children:e})}function SZ(e,t){switch(e.view){case"conversation":return d.jsx(ag,{conversationId:e.conversationId,navigate:t});case"agent-info":return d.jsx(AB,{conversationId:e.conversationId,navigate:t});case"settings":return d.jsx(pZ,{navigate:t});case"agents":return d.jsx(t7,{navigate:t,selectedAgentId:e.agentId,conversationId:e.conversationId});case"fleet":return d.jsx(c7,{navigate:t});case"sessions":return e.sessionId?d.jsx(ag,{conversationId:e.sessionId,navigate:t}):d.jsx(Z7,{navigate:t});case"mesh":return d.jsx(O7,{navigate:t});case"activity":return d.jsx(jB,{navigate:t});case"work":return d.jsx(bZ,{workId:e.workId,navigate:t});default:return d.jsx(p7,{navigate:t})}}function EZ(){const{route:e,agents:t}=Yt();if(e.view!=="agents")return null;const s=e.agentId?t.find(i=>i.id===e.agentId)??null:null;if(!s){const i=t.filter(l=>Fa(l.state)).length;return d.jsxs("div",{className:"flex flex-col h-full overflow-y-auto frame-scrollbar p-4 gap-4 text-[11px]",children:[d.jsx(_s,{label:"Total",value:`${t.length}`}),d.jsx(_s,{label:"Working",value:`${i}`}),d.jsx(_s,{label:"Available",value:`${t.length-i}`}),d.jsx("div",{className:"mt-2 text-[10px] font-mono uppercase tracking-[0.15em] text-white/25 leading-relaxed",children:"Select an agent from the roster to see its identity + session context here."})]})}const r=Fa(s.state);return d.jsxs("div",{className:"flex flex-col h-full overflow-y-auto frame-scrollbar p-4 gap-4 text-[11px]",children:[d.jsxs("div",{className:"flex items-center gap-3 pb-3 border-b border-white/[0.04]",children:[d.jsxs("div",{className:"relative w-10 h-10 rounded-full flex items-center justify-center text-[13px] font-mono text-black/80 shrink-0",style:{background:Ts(s.name)},children:[s.name[0]?.toUpperCase()??"?",r&&d.jsx("span",{className:"absolute -right-0.5 -bottom-0.5 w-2.5 h-2.5 rounded-full bg-emerald-400 ring-2 ring-neutral-950"})]}),d.jsxs("div",{className:"flex flex-col min-w-0 flex-1",children:[d.jsx("span",{className:"text-[13px] text-white/90 truncate",children:s.name}),s.handle&&d.jsxs("span",{className:"text-[10px] font-mono text-cyan-400/70",children:["@",s.handle]})]})]}),d.jsxs(Uu,{label:"State",children:[d.jsxs("div",{className:"flex items-baseline gap-2",children:[d.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${r?"bg-emerald-400":"bg-white/20"}`}),d.jsx("span",{className:"text-[12px] text-white/80 capitalize",children:ao(s.state)})]}),s.updatedAt&&d.jsxs("div",{className:"text-[10px] font-mono text-white/30 mt-1",children:["Updated ",tt(s.updatedAt)]})]}),d.jsxs(Uu,{label:"Identity",children:[d.jsx(_s,{label:"Class",value:s.agentClass}),s.role&&d.jsx(_s,{label:"Role",value:s.role}),s.harness&&d.jsx(_s,{label:"Harness",value:s.harness}),s.transport&&d.jsx(_s,{label:"Transport",value:s.transport})]}),(s.project||s.branch||s.cwd)&&d.jsxs(Uu,{label:"Project",children:[s.project&&d.jsx(_s,{label:"Name",value:s.project}),s.branch&&d.jsx(_s,{label:"Branch",value:s.branch}),s.cwd&&d.jsx(_s,{label:"Cwd",value:s.cwd})]}),s.capabilities.length>0&&d.jsx(Uu,{label:`Capabilities · ${s.capabilities.length}`,children:d.jsx("div",{className:"flex flex-wrap gap-1",children:s.capabilities.map(i=>d.jsx("span",{className:"text-[10px] font-mono text-white/50 px-1.5 py-0.5 rounded-sm bg-white/[0.04]",children:i},i))})})]})}function Uu({label:e,children:t}){return d.jsxs("div",{className:"flex flex-col",children:[d.jsx("div",{className:"text-[9px] font-mono uppercase tracking-[0.15em] text-white/30 mb-1.5",children:e}),t]})}function _s({label:e,value:t}){return d.jsxs("div",{className:"flex items-baseline justify-between py-0.5 gap-2",children:[d.jsx("span",{className:"text-[10px] font-mono uppercase tracking-wider text-white/30 shrink-0",children:e}),d.jsx("span",{className:"text-[11px] text-white/70 font-mono truncate",children:t})]})}function NZ(){const[e,t]=b.useState(null),s=b.useCallback(async()=>{try{t(await ot("/api/fleet"))}catch{}},[]);if(b.useEffect(()=>{s()},[s]),Kn(s),!e)return d.jsx("div",{className:"flex items-center justify-center h-full text-[11px] font-mono uppercase tracking-[0.15em] text-white/25",children:"Loading fleet…"});const r=e.totals;return d.jsxs("div",{className:"flex flex-col h-full overflow-y-auto frame-scrollbar p-4 gap-4 text-[11px]",children:[d.jsxs("div",{className:"text-[9px] font-mono uppercase tracking-[0.15em] text-white/30",children:["Updated ",tt(e.generatedAt)]}),d.jsx($u,{label:"Needs Input",value:r.needsAttention,emphasis:r.needsAttention>0?"warn":"muted"}),d.jsx($u,{label:"Active Asks",value:r.active}),d.jsx($u,{label:"Recent Finished",value:r.recentCompleted,emphasis:r.recentCompleted>0?"good":"muted"}),d.jsx($u,{label:"Activity",value:r.activity})]})}function $u({label:e,value:t,emphasis:s}){const r=s==="good"?"text-emerald-300/90":s==="warn"?"text-amber-300/90":s==="muted"?"text-white/40":"text-white/80";return d.jsxs("div",{className:"flex flex-col pb-3 border-b border-white/[0.04] last:border-b-0",children:[d.jsx("span",{className:`text-[24px] font-mono tabular-nums leading-none ${r}`,children:t}),d.jsx("span",{className:"text-[9px] font-mono uppercase tracking-[0.15em] text-white/30 mt-1",children:e})]})}function TZ(){const{agents:e,navigate:t}=Yt();if(e.length===0)return d.jsxs("div",{className:"flex flex-col h-full items-center justify-center px-4 text-center text-[11px] text-white/30 font-mono leading-relaxed",children:[d.jsx("div",{className:"mb-1 uppercase tracking-[0.15em]",children:"No agents"}),d.jsx("div",{children:"Connect an agent to see your roster here."})]});const s=e.filter(i=>Fa(i.state)),r=e.filter(i=>!Fa(i.state));return d.jsxs("div",{className:"flex flex-col h-full overflow-y-auto frame-scrollbar p-4 gap-4 text-[11px]",children:[s.length>0&&d.jsx($S,{label:"Online",count:s.length,children:s.map(i=>d.jsx(VS,{agent:i,navigate:t},i.id))}),r.length>0&&d.jsx($S,{label:"Standby",count:r.length,children:r.map(i=>d.jsx(VS,{agent:i,navigate:t,dim:!0},i.id))})]})}function $S({label:e,count:t,children:s}){return d.jsxs("div",{className:"flex flex-col",children:[d.jsxs("div",{className:"flex items-baseline justify-between mb-1.5",children:[d.jsx("span",{className:"text-[9px] font-mono uppercase tracking-[0.15em] text-white/30",children:e}),d.jsx("span",{className:"text-[9px] font-mono tabular-nums text-white/25",children:t})]}),d.jsx("div",{className:"flex flex-col gap-0.5",children:s})]})}function VS({agent:e,navigate:t,dim:s}){const r=Fa(e.state);return d.jsxs("button",{onClick:()=>t({view:"agents",agentId:e.id}),className:`group flex items-center gap-2.5 px-2 py-1.5 rounded-sm text-left transition-colors ${s?"opacity-60 hover:opacity-100 hover:bg-white/[0.03]":"hover:bg-white/[0.03]"}`,children:[d.jsxs("div",{className:"relative w-6 h-6 rounded-full flex items-center justify-center text-[10px] font-mono text-black/80 shrink-0",style:{background:Ts(e.name)},children:[e.name[0]?.toUpperCase()??"?",r&&d.jsx("span",{className:"absolute -right-0.5 -bottom-0.5 w-2 h-2 rounded-full bg-emerald-400 ring-2 ring-neutral-950"})]}),d.jsxs("div",{className:"flex flex-col min-w-0 flex-1",children:[d.jsx("span",{className:"text-[12px] text-white/80 truncate group-hover:text-white transition-colors",children:e.name}),d.jsx("span",{className:"text-[10px] font-mono text-white/30 truncate",children:ao(e.state)})]}),e.updatedAt&&d.jsx("span",{className:"text-[9px] font-mono tabular-nums text-white/25 shrink-0",children:tt(e.updatedAt)})]})}function jZ(){const{route:e}=Yt(),[t,s]=b.useState([]),r=b.useCallback(async()=>{try{s(await ot("/api/sessions"))}catch{}},[]);if(b.useEffect(()=>{r()},[r]),Kn(r),e.view!=="sessions")return null;const i=e.sessionId?t.find(l=>l.id===e.sessionId)??null:null;if(!i){const l=new Set(t.map(f=>f.kind)),c=t.filter(f=>f.currentBranch).length;return d.jsxs("div",{className:"flex flex-col h-full overflow-y-auto frame-scrollbar p-4 gap-4 text-[11px]",children:[d.jsx(ks,{label:"Total",value:`${t.length}`}),d.jsx(ks,{label:"Kinds",value:`${l.size}`}),d.jsx(ks,{label:"Branched",value:`${c}`}),d.jsx("div",{className:"mt-2 text-[10px] font-mono uppercase tracking-[0.15em] text-white/25 leading-relaxed",children:"Select a session from the list to see its context here."})]})}return d.jsxs("div",{className:"flex flex-col h-full overflow-y-auto frame-scrollbar p-4 gap-4 text-[11px]",children:[d.jsxs("div",{className:"pb-3 border-b border-white/[0.04]",children:[d.jsx("div",{className:"text-[13px] text-white/90 leading-snug",children:i.title}),d.jsx("div",{className:"text-[10px] font-mono uppercase tracking-wider text-cyan-400/70 mt-1",children:i.kind})]}),i.agentName&&d.jsxs(Vu,{label:"Agent",children:[d.jsx(ks,{label:"Name",value:i.agentName}),i.harness&&d.jsx(ks,{label:"Harness",value:i.harness})]}),(i.currentBranch||i.workspaceRoot)&&d.jsxs(Vu,{label:"Workspace",children:[i.currentBranch&&d.jsx(ks,{label:"Branch",value:i.currentBranch}),i.workspaceRoot&&d.jsx(ks,{label:"Root",value:i.workspaceRoot})]}),d.jsxs(Vu,{label:"Activity",children:[d.jsx(ks,{label:"Messages",value:`${i.messageCount}`}),i.lastMessageAt&&d.jsx(ks,{label:"Last",value:tt(i.lastMessageAt)}),i.participantIds.length>0&&d.jsx(ks,{label:"Participants",value:`${i.participantIds.length}`})]}),i.preview&&d.jsx(Vu,{label:"Preview",children:d.jsxs("div",{className:"text-[11px] text-white/60 leading-relaxed italic",children:['"',i.preview,'"']})})]})}function Vu({label:e,children:t}){return d.jsxs("div",{className:"flex flex-col",children:[d.jsx("div",{className:"text-[9px] font-mono uppercase tracking-[0.15em] text-white/30 mb-1.5",children:e}),t]})}function ks({label:e,value:t}){return d.jsxs("div",{className:"flex items-baseline justify-between py-0.5 gap-2",children:[d.jsx("span",{className:"text-[10px] font-mono uppercase tracking-wider text-white/30 shrink-0",children:e}),d.jsx("span",{className:"text-[11px] text-white/70 font-mono truncate",children:t})]})}function CZ(){const{route:e}=Yt(),t=e.view==="work"?e.workId:null,[s,r]=b.useState(null),i=b.useCallback(async()=>{if(!t){r(null);return}try{r(await ot(`/api/work/${encodeURIComponent(t)}`))}catch{r(null)}},[t]);if(b.useEffect(()=>{i()},[i]),Kn(i),e.view!=="work")return null;if(!s)return d.jsx("div",{className:"flex items-center justify-center h-full text-[11px] font-mono uppercase tracking-[0.15em] text-white/25 text-center px-4",children:"Loading work item…"});const l=AZ(s.state);return d.jsxs("div",{className:"flex flex-col h-full overflow-y-auto frame-scrollbar p-4 gap-4 text-[11px]",children:[d.jsxs("div",{className:"pb-3 border-b border-white/[0.04]",children:[d.jsxs("div",{className:"text-[9px] font-mono uppercase tracking-[0.15em] text-cyan-400/70 mb-1",children:["Case ",RZ(s.id)]}),d.jsx("div",{className:"text-[13px] text-white/90 leading-snug",children:s.title})]}),d.jsxs(Bu,{label:"State",children:[d.jsxs("div",{className:"flex items-baseline gap-2",children:[d.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${l.dot}`}),d.jsx("span",{className:`text-[12px] capitalize ${l.text}`,children:s.state.replace(/_/g," ")})]}),d.jsxs("div",{className:"text-[10px] font-mono text-white/30 mt-1",children:["Phase · ",s.currentPhase]})]}),d.jsxs(Bu,{label:"Ownership",children:[s.ownerName&&d.jsx(zi,{label:"Owner",value:s.ownerName}),s.nextMoveOwnerName&&d.jsx(zi,{label:"Next move",value:s.nextMoveOwnerName}),s.priority&&d.jsx(zi,{label:"Priority",value:s.priority})]}),d.jsxs(Bu,{label:"Activity",children:[d.jsx(zi,{label:"Children",value:`${s.activeChildWorkCount}`}),d.jsx(zi,{label:"Flights",value:`${s.activeFlightCount}`}),s.lastMeaningfulAt&&d.jsx(zi,{label:"Last update",value:tt(s.lastMeaningfulAt)})]}),s.attention!=="silent"&&d.jsx("div",{className:`text-[10px] font-mono uppercase tracking-wider px-2 py-1 rounded-sm ${s.attention==="interrupt"?"text-red-300/90 bg-red-500/10 border border-red-500/20":"text-amber-300/90 bg-amber-500/10 border border-amber-500/20"}`,children:s.attention==="interrupt"?"Interrupt":"Needs attention"}),s.lastMeaningfulSummary&&d.jsx(Bu,{label:"Latest",children:d.jsx("div",{className:"text-[11px] text-white/60 leading-relaxed italic",children:s.lastMeaningfulSummary})})]})}function RZ(e){return e.length>10?`${e.slice(0,8)}…`:e}function AZ(e){return/complete|done|finished/i.test(e)?{dot:"bg-emerald-400",text:"text-emerald-300/90"}:/fail|error/i.test(e)?{dot:"bg-red-400",text:"text-red-300/90"}:/block|wait|pause/i.test(e)?{dot:"bg-amber-400",text:"text-amber-300/90"}:/active|working|in[_-]?progress/i.test(e)?{dot:"bg-cyan-400",text:"text-cyan-300/90"}:{dot:"bg-white/30",text:"text-white/70"}}function Bu({label:e,children:t}){return d.jsxs("div",{className:"flex flex-col",children:[d.jsx("div",{className:"text-[9px] font-mono uppercase tracking-[0.15em] text-white/30 mb-1.5",children:e}),t]})}function zi({label:e,value:t}){return d.jsxs("div",{className:"flex items-baseline justify-between py-0.5 gap-2",children:[d.jsx("span",{className:"text-[10px] font-mono uppercase tracking-wider text-white/30 shrink-0",children:e}),d.jsx("span",{className:"text-[11px] text-white/70 font-mono truncate",children:t})]})}function _Z(){const{route:e}=Yt();switch(e.view){case"inbox":return d.jsx(TZ,{});case"agents":case"agent-info":return d.jsx(EZ,{});case"fleet":return d.jsx(NZ,{});case"sessions":case"conversation":return d.jsx(jZ,{});case"work":return d.jsx(CZ,{});default:return null}}const kZ=[{view:"inbox",label:"Home",icon:VV,target:{view:"inbox"}},{view:"agents",label:"Agents",icon:QV,target:{view:"agents"}},{view:"fleet",label:"Fleet",icon:ZV,target:{view:"fleet"}},{view:"sessions",label:"Sessions",icon:FV,target:{view:"sessions"}},{view:"activity",label:"Activity",icon:UV,target:{view:"activity"}},{view:"mesh",label:"Mesh",icon:YV,target:{view:"mesh"}}],MZ=[{view:"settings",label:"Settings",icon:WV,target:{view:"settings"}}];function OZ(){const{route:e,navigate:t}=Yt();return d.jsxs("div",{className:"flex flex-col h-full py-2",children:[d.jsx("nav",{className:"flex flex-col",children:kZ.map(s=>d.jsx(BS,{item:s,activeView:e.view,navigate:t},s.view))}),d.jsx("div",{className:"flex-1"}),d.jsx("nav",{className:"flex flex-col",children:MZ.map(s=>d.jsx(BS,{item:s,activeView:e.view,navigate:t},s.view))})]})}function BS({item:e,activeView:t,navigate:s}){const r=t===e.view,i=e.icon;return d.jsxs("button",{onClick:()=>s(e.target),className:`group w-full flex items-center gap-2.5 px-3 py-1.5 text-left transition-colors border-l-2 ${r?"bg-cyan-500/5 border-l-cyan-400/40 text-white/80":"border-l-transparent text-white/40 hover:bg-white/[0.02] hover:text-white/60"}`,children:[d.jsx(i,{size:13,strokeWidth:1.5,className:r?"text-cyan-400/70":"text-white/30 group-hover:text-white/50"}),d.jsx("span",{className:"text-[12px]",children:e.label})]})}function DZ(){const{onboarding:e}=Yt();return e?e.hasLocalConfig?e.hasOperatorName?e.hasProjectConfig?null:d.jsx(om,{children:d.jsx(LZ,{})}):d.jsx(om,{children:d.jsx(IZ,{})}):d.jsx(om,{children:d.jsx(zZ,{})}):null}function om({children:e}){return d.jsx("div",{style:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",overflow:"auto",background:"var(--bg)",color:"var(--ink)"},children:d.jsx("div",{style:{width:"100%",maxWidth:720,padding:"80px 72px",display:"flex",flexDirection:"column",gap:40},children:e})})}function wy({eyebrow:e,title:t,description:s}){return d.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[d.jsx("div",{style:PZ,children:e}),d.jsx("div",{style:UZ,children:t}),d.jsx("div",{style:$Z,children:s})]})}function Sy({primary:e,onPrimary:t,primaryDisabled:s,busy:r}){const{skipOnboarding:i}=Yt();return d.jsxs("div",{style:{display:"flex",alignItems:"center",gap:24,paddingTop:8},children:[d.jsx("button",{type:"button",onClick:t,disabled:s||r,style:{...BZ,opacity:s||r?.5:1,cursor:s||r?"default":"pointer"},children:r?"Working…":e}),d.jsx("button",{type:"button",onClick:i,style:ZZ,onMouseEnter:l=>{l.currentTarget.style.color="rgba(255,255,255,0.8)"},onMouseLeave:l=>{l.currentTarget.style.color="rgba(255,255,255,0.45)"},children:"Skip for now"})]})}function Ey({message:e}){return e?d.jsx("div",{style:{borderRadius:8,border:"1px solid rgba(239,68,68,0.35)",backgroundColor:"rgba(239,68,68,0.08)",color:"rgba(252,165,165,0.95)",padding:"12px 16px",fontSize:12,lineHeight:1.5},children:e}):null}function zZ(){const{onboarding:e,refreshOnboarding:t}=Yt(),[s,r]=b.useState(!1),[i,l]=b.useState(null),c=async()=>{r(!0),l(null);try{await ot("/api/onboarding/init",{method:"POST",body:"{}"}),await t()}catch(f){l(f instanceof Error?f.message:String(f))}finally{r(!1)}};return d.jsxs(d.Fragment,{children:[d.jsx(wy,{eyebrow:"First-run setup",title:"Welcome to Scout",description:d.jsxs(d.Fragment,{children:["Scout needs a local config before it can talk to the broker, the web app, and paired devices. This writes"," ",d.jsx("code",{style:dg,children:"~/.openscout/config.json"})," with sensible defaults — you can edit it any time."]})}),d.jsxs("ul",{style:HZ,children:[d.jsx(ZS,{label:"Local config (~/.openscout/config.json)",done:!1,hint:"missing"}),d.jsx(ZS,{label:".openscout/project.json in a repo",done:!!e?.hasProjectConfig,hint:e?.hasProjectConfig?e.projectRoot??void 0:"checked after setup"})]}),d.jsx(Ey,{message:i}),d.jsx(Sy,{primary:"Initialize Scout",onPrimary:()=>{c()},busy:s})]})}function IZ(){const{onboarding:e,refreshOnboarding:t}=Yt(),s=e?.operatorNameSuggestion??"",[r,i]=b.useState(s),[l,c]=b.useState(!1),[f,p]=b.useState(null);b.useEffect(()=>{!r&&s&&i(s)},[s,r]);const h=async()=>{const g=r.trim();if(!g){p("Name is required.");return}c(!0),p(null);try{await ot("/api/user",{method:"POST",body:JSON.stringify({name:g})}),await t()}catch(v){p(v instanceof Error?v.message:String(v))}finally{c(!1)}};return d.jsxs(d.Fragment,{children:[d.jsx(wy,{eyebrow:"Step 1 of 2",title:"What should we call you?",description:"Your name shows up on messages you send and in any agent that speaks for you. You can change it later in Settings."}),d.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[d.jsx("label",{style:sd,children:"Your name"}),d.jsx("input",{autoFocus:!0,value:r,onChange:g=>{i(g.target.value),p(null)},onKeyDown:g=>{g.key==="Enter"&&h()},placeholder:s||"Operator",style:ug}),s?d.jsx("div",{style:{fontSize:11,color:"rgba(255,255,255,0.4)",fontFamily:"var(--hud-font-mono)"},children:"Prefilled from your machine."}):null]}),d.jsx(Ey,{message:f}),d.jsx(Sy,{primary:"Continue",onPrimary:()=>{h()},busy:l,primaryDisabled:!r.trim()})]})}function LZ(){const{onboarding:e,refreshOnboarding:t}=Yt(),s=e?.currentDirectory??"",[r,i]=b.useState([s||"~/dev"]),[l,c]=b.useState(s),[f,p]=b.useState("claude"),[h,g]=b.useState(!1),[v,x]=b.useState(null),w=(C,j)=>{i(S=>S.map((_,R)=>R===C?j:_))},T=()=>i(C=>[...C,""]),N=C=>i(j=>j.filter((S,_)=>_!==C)),A=async()=>{const C=r.map(S=>S.trim()).filter(Boolean),j=l.trim();if(!j){x("Pick where Scout should anchor this context.");return}g(!0),x(null);try{await ot("/api/onboarding/project",{method:"POST",body:JSON.stringify({contextRoot:j,sourceRoots:C,defaultHarness:f})}),await t()}catch(S){x(S instanceof Error?S.message:String(S))}finally{g(!1)}};return d.jsxs(d.Fragment,{children:[d.jsx(wy,{eyebrow:"Step 2 of 2",title:"Where do your repos live?",description:d.jsxs(d.Fragment,{children:["Scout scans these folders for projects and anchors this context at"," ",d.jsx("code",{style:dg,children:"<context>/.openscout/project.json"}),"."]})}),d.jsxs("div",{style:lm,children:[d.jsx("label",{style:sd,children:"Scan folders"}),d.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[r.map((C,j)=>d.jsxs("div",{style:{display:"flex",gap:8},children:[d.jsx("input",{value:C,onChange:S=>w(j,S.target.value),placeholder:j===0?"~/dev":"Add another folder",style:{...ug,flex:1}}),d.jsx("button",{type:"button",onClick:()=>N(j),disabled:r.length<=1,style:{...HS,opacity:r.length<=1?.4:1,cursor:r.length<=1?"default":"pointer"},"aria-label":`Remove folder ${j+1}`,children:"−"})]},j)),d.jsx("button",{type:"button",onClick:T,style:{...HS,alignSelf:"flex-start"},children:"+ Add folder"})]})]}),d.jsxs("div",{style:lm,children:[d.jsx("label",{style:sd,children:"Context root"}),d.jsx("input",{value:l,onChange:C=>c(C.target.value),placeholder:"~/dev",style:ug}),d.jsxs("div",{style:VZ,children:["Scout writes ",d.jsx("code",{style:dg,children:".openscout/project.json"})," ","inside this folder."]})]}),d.jsxs("div",{style:lm,children:[d.jsx("label",{style:sd,children:"Default harness"}),d.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:["claude","codex"].map(C=>{const j=f===C;return d.jsxs("button",{type:"button",onClick:()=>p(C),style:{...FZ,borderColor:j?"var(--accent, #2dd4bf)":"rgba(255,255,255,0.12)",backgroundColor:j?"rgba(45,212,191,0.08)":"rgba(255,255,255,0.02)"},children:[d.jsx("div",{style:{fontSize:15,fontWeight:600,textTransform:"capitalize"},children:C}),d.jsx("div",{style:{fontSize:12,color:"rgba(255,255,255,0.55)",marginTop:6,lineHeight:1.5},children:C==="claude"?"Anthropic Claude Code — local CLI agent.":"OpenAI Codex — cloud agentic sandbox."})]},C)})})]}),d.jsx(Ey,{message:v}),d.jsx(Sy,{primary:"Create project",onPrimary:()=>{A()},busy:h,primaryDisabled:!l.trim()})]})}function ZS({label:e,done:t,hint:s}){return d.jsxs("li",{style:{display:"flex",alignItems:"flex-start",gap:16},children:[d.jsx("span",{style:{marginTop:2,width:20,height:20,borderRadius:999,display:"flex",alignItems:"center",justifyContent:"center",fontSize:11,fontWeight:700,flexShrink:0,backgroundColor:t?"rgba(34,197,94,0.15)":"rgba(239,68,68,0.12)",color:t?"#4ade80":"#f87171"},children:t?"✓":"•"}),d.jsxs("div",{style:{minWidth:0},children:[d.jsx("div",{style:{fontSize:13,lineHeight:1.5,color:t?"rgba(255,255,255,0.75)":"rgba(255,255,255,0.9)"},children:e}),s?d.jsx("div",{style:{fontSize:11,fontFamily:"var(--hud-font-mono)",color:"rgba(255,255,255,0.35)",marginTop:4,wordBreak:"break-all"},children:s}):null]})]})}const PZ={fontSize:11,fontFamily:"var(--hud-font-mono)",textTransform:"uppercase",letterSpacing:"0.18em",color:"rgba(255,255,255,0.4)"},UZ={fontSize:36,fontWeight:600,letterSpacing:"-0.01em",lineHeight:1.15},$Z={fontSize:15,lineHeight:1.75,color:"rgba(255,255,255,0.6)",maxWidth:580},lm={display:"flex",flexDirection:"column",gap:10},sd={fontSize:11,fontFamily:"var(--hud-font-mono)",textTransform:"uppercase",letterSpacing:"0.15em",color:"rgba(255,255,255,0.5)"},ug={width:"100%",padding:"10px 14px",fontSize:14,fontFamily:"var(--hud-font-mono)",color:"rgba(255,255,255,0.92)",backgroundColor:"rgba(255,255,255,0.04)",border:"1px solid rgba(255,255,255,0.12)",borderRadius:8,outline:"none",boxSizing:"border-box"},VZ={fontSize:12,color:"rgba(255,255,255,0.45)",lineHeight:1.6},dg={fontFamily:"var(--hud-font-mono)",fontSize:12,padding:"2px 6px",borderRadius:4,backgroundColor:"rgba(255,255,255,0.06)"},BZ={fontSize:13,fontWeight:600,padding:"12px 24px",borderRadius:10,backgroundColor:"var(--accent, #2dd4bf)",color:"#0b0d12",border:"none",transition:"opacity 0.15s ease"},HS={fontSize:13,fontWeight:500,padding:"10px 14px",borderRadius:8,backgroundColor:"rgba(255,255,255,0.04)",border:"1px solid rgba(255,255,255,0.12)",color:"rgba(255,255,255,0.85)",transition:"all 0.15s ease"},ZZ={fontSize:12,color:"rgba(255,255,255,0.45)",textDecoration:"underline dotted rgba(255,255,255,0.25)",textUnderlineOffset:4,background:"none",border:"none",cursor:"pointer",padding:"4px 2px",transition:"color 0.15s ease"},HZ={display:"flex",flexDirection:"column",gap:20,margin:0,padding:0,listStyle:"none"},FZ={textAlign:"left",padding:"16px 18px",borderRadius:12,border:"1px solid rgba(255,255,255,0.12)",color:"rgba(255,255,255,0.9)",cursor:"pointer",transition:"all 0.15s ease"};function qZ(){const{navigate:e,agents:t,reload:s}=Yt(),r=b.useCallback(async i=>{await ot(`/api/agents/${encodeURIComponent(i)}/interrupt`,{method:"POST",body:JSON.stringify({})})},[]);return b.useMemo(()=>{const i=[{id:"nav:home",label:"Go to Home",action:()=>e({view:"inbox"}),shortcut:"Cmd+1"},{id:"nav:agents",label:"Go to Agents",action:()=>e({view:"agents"}),shortcut:"Cmd+2"},{id:"nav:fleet",label:"Go to Fleet",action:()=>e({view:"fleet"}),shortcut:"Cmd+3"},{id:"nav:sessions",label:"Go to Sessions",action:()=>e({view:"sessions"}),shortcut:"Cmd+4"},{id:"nav:activity",label:"Go to Activity",action:()=>e({view:"activity"}),shortcut:"Cmd+5"},{id:"nav:mesh",label:"Go to Mesh",action:()=>e({view:"mesh"}),shortcut:"Cmd+6"},{id:"nav:settings",label:"Open Settings",action:()=>e({view:"settings"}),shortcut:"Cmd+,"},{id:"nav:pair",label:"Pair Device",action:()=>e({view:"settings"})},{id:"scout:reload",label:"Reload Agents",action:()=>{s()}}];for(const l of t)i.push({id:`scout:open:${l.id}`,label:`Open ${l.name}`,action:()=>e({view:"conversation",conversationId:ng(l.id)})}),i.push({id:`scout:send:${l.id}`,label:`Send message to ${l.name}`,action:()=>e({view:"conversation",conversationId:ng(l.id)})}),i.push({id:`scout:interrupt:${l.id}`,label:`Interrupt ${l.name}`,action:()=>{r(l.id)}});return i},[t,r,e,s])}function YZ(){const{agents:e,onlineCount:t}=Yt();return e.length===0?{label:"offline",color:"neutral"}:t===0?{label:`0/${e.length} agents`,color:"amber"}:{label:`${t}/${e.length} agents`,color:"emerald"}}const GZ={inbox:"Home",conversation:"Conversation","agent-info":"Agent",agents:"Agents",fleet:"Fleet",sessions:"Sessions",activity:"Activity",mesh:"Mesh",settings:"Settings",work:"Work"};function XZ(){const{route:e}=Yt(),t=GZ[e.view]??e.view;return b.createElement("span",{className:"text-[10px] font-mono uppercase tracking-wider text-white/40"},t)}function KZ(){const{navigate:e}=Yt();return b.createElement("button",{onClick:()=>e({view:"settings"}),className:"px-2 py-1 rounded-sm text-[11px] font-mono uppercase tracking-wider text-white/60 hover:text-white/90 hover:bg-white/[0.04] border border-white/[0.06] transition-colors"},"Pair device")}function WZ(){return"panel"}function JZ(){const{onboarding:e,onboardingSkipped:t,skipOnboarding:s}=Yt();if(!e)return null;if(t)return{active:!1,dismissible:!0};const r=!e.hasLocalConfig,i=!e.hasProjectConfig,l=!e.hasOperatorName;return{active:r||l||i,dismissible:!0,onDismiss:s}}const QZ=[{commandId:"nav:home",title:"Go to Home",description:"Navigate to the home screen showing the agent inbox",category:"navigation",keywords:["home","inbox","dashboard"],shortcut:"Cmd+1"},{commandId:"nav:agents",title:"Go to Agents",description:"Navigate to the agents roster showing all registered agents",category:"navigation",keywords:["agents","roster","list"],shortcut:"Cmd+2"},{commandId:"nav:fleet",title:"Go to Fleet",description:"Navigate to the fleet overview with agent status summary",category:"navigation",keywords:["fleet","overview","status"],shortcut:"Cmd+3"},{commandId:"nav:sessions",title:"Go to Sessions",description:"Navigate to the sessions list showing all active conversations",category:"navigation",keywords:["sessions","conversations","threads"],shortcut:"Cmd+4"},{commandId:"nav:activity",title:"Go to Activity",description:"Navigate to the activity feed showing recent events",category:"navigation",keywords:["activity","feed","events","log"],shortcut:"Cmd+5"},{commandId:"nav:mesh",title:"Go to Mesh",description:"Navigate to the mesh network view showing nodes and topology",category:"navigation",keywords:["mesh","network","nodes","peers","topology"],shortcut:"Cmd+6"},{commandId:"nav:settings",title:"Open Settings",description:"Open the settings screen for pairing, identity, and relay config",category:"settings",keywords:["settings","preferences","config","pair"],shortcut:"Cmd+,"},{commandId:"nav:pair",title:"Pair Device",description:"Open the device pairing flow to connect a mobile device",category:"settings",keywords:["pair","qr","device","phone","mobile"]},{commandId:"scout:reload",title:"Reload Agents",description:"Refresh the agent list and message state from the broker",category:"workspace",keywords:["reload","refresh","sync"]},{commandId:"scout:open:*",title:"Open Agent Conversation",description:"Open a direct message conversation with a specific agent. The commandId is scout:open:{agentId} where agentId comes from the current agent roster.",category:"navigation",keywords:["open","chat","conversation","dm","message"],params:[{name:"agentId",description:"The agent identifier to open",type:"string"}]},{commandId:"scout:send:*",title:"Send Message to Agent",description:"Send a text message to a specific agent. The commandId is scout:send:{agentId}. Requires a message parameter.",category:"workspace",keywords:["send","message","tell","ask","request"],params:[{name:"agentId",description:"The agent identifier to message",type:"string"},{name:"message",description:"The message body to send",type:"string"}]},{commandId:"scout:interrupt:*",title:"Interrupt Agent",description:"Send Ctrl-C to interrupt a working agent. The commandId is scout:interrupt:{agentId}.",category:"workspace",keywords:["stop","interrupt","cancel","halt","kill"],dangerous:!0,params:[{name:"agentId",description:"The agent identifier to interrupt",type:"string"}]}],eH={id:"openscout",name:"Scout",description:"All your agents, one message away. Scout is a control plane for managing coding agents — it shows their status, routes messages between them, and lets you steer, interrupt, or dispatch work to any agent in the fleet.",mode:"panel",Provider:aB,leftPanel:{title:"Scout",icon:b.createElement(XV,{size:12})},slots:{Content:xZ,LeftPanel:OZ,Inspector:_Z,Takeover:DZ},intents:QZ,hooks:{useCommands:qZ,useStatus:YZ,useNavCenter:XZ,useNavActions:KZ,useLayoutMode:WZ,useTakeover:JZ}},QC=document.getElementById("root");if(!QC)throw new Error("missing #root");x2.createRoot(QC).render(d.jsx(b.StrictMode,{children:d.jsx(_V,{app:eH})}));export{YS as F,qS as f,d as j,b as r};
|