pilotswarm 0.4.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,87 +0,0 @@
1
- function Xo(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var es={exports:{}},R={};var mn;function Jo(){if(mn)return R;mn=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),s=Symbol.for("react.fragment"),n=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),o=Symbol.for("react.consumer"),r=Symbol.for("react.context"),a=Symbol.for("react.forward_ref"),l=Symbol.for("react.suspense"),p=Symbol.for("react.memo"),u=Symbol.for("react.lazy"),d=Symbol.for("react.activity"),f=Symbol.iterator;function h(S){return S===null||typeof S!="object"?null:(S=f&&S[f]||S["@@iterator"],typeof S=="function"?S:null)}var m={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},g=Object.assign,I={};function y(S,C,A){this.props=S,this.context=C,this.refs=I,this.updater=A||m}y.prototype.isReactComponent={},y.prototype.setState=function(S,C){if(typeof S!="object"&&typeof S!="function"&&S!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,S,C,"setState")},y.prototype.forceUpdate=function(S){this.updater.enqueueForceUpdate(this,S,"forceUpdate")};function x(){}x.prototype=y.prototype;function E(S,C,A){this.props=S,this.context=C,this.refs=I,this.updater=A||m}var v=E.prototype=new x;v.constructor=E,g(v,y.prototype),v.isPureReactComponent=!0;var T=Array.isArray;function O(){}var M={H:null,A:null,T:null,S:null},k=Object.prototype.hasOwnProperty;function N(S,C,A){var P=A.ref;return{$$typeof:t,type:S,key:C,ref:P!==void 0?P:null,props:A}}function L(S,C){return N(S.type,C,S.props)}function Y(S){return typeof S=="object"&&S!==null&&S.$$typeof===t}function _(S){var C={"=":"=0",":":"=2"};return"$"+S.replace(/[=:]/g,function(A){return C[A]})}var W=/\/+/g;function U(S,C){return typeof S=="object"&&S!==null&&S.key!=null?_(""+S.key):C.toString(36)}function ee(S){switch(S.status){case"fulfilled":return S.value;case"rejected":throw S.reason;default:switch(typeof S.status=="string"?S.then(O,O):(S.status="pending",S.then(function(C){S.status==="pending"&&(S.status="fulfilled",S.value=C)},function(C){S.status==="pending"&&(S.status="rejected",S.reason=C)})),S.status){case"fulfilled":return S.value;case"rejected":throw S.reason}}throw S}function J(S,C,A,P,$){var G=typeof S;(G==="undefined"||G==="boolean")&&(S=null);var j=!1;if(S===null)j=!0;else switch(G){case"bigint":case"string":case"number":j=!0;break;case"object":switch(S.$$typeof){case t:case e:j=!0;break;case u:return j=S._init,J(j(S._payload),C,A,P,$)}}if(j)return $=$(S),j=P===""?"."+U(S,0):P,T($)?(A="",j!=null&&(A=j.replace(W,"$&/")+"/"),J($,C,A,"",function(Zt){return Zt})):$!=null&&(Y($)&&($=L($,A+($.key==null||S&&S.key===$.key?"":(""+$.key).replace(W,"$&/")+"/")+j)),C.push($)),1;j=0;var ae=P===""?".":P+":";if(T(S))for(var te=0;te<S.length;te++)P=S[te],G=ae+U(P,te),j+=J(P,C,A,G,$);else if(te=h(S),typeof te=="function")for(S=te.call(S),te=0;!(P=S.next()).done;)P=P.value,G=ae+U(P,te++),j+=J(P,C,A,G,$);else if(G==="object"){if(typeof S.then=="function")return J(ee(S),C,A,P,$);throw C=String(S),Error("Objects are not valid as a React child (found: "+(C==="[object Object]"?"object with keys {"+Object.keys(S).join(", ")+"}":C)+"). If you meant to render a collection of children, use an array instead.")}return j}function D(S,C,A){if(S==null)return S;var P=[],$=0;return J(S,P,"","",function(G){return C.call(A,G,$++)}),P}function se(S){if(S._status===-1){var C=S._result;C=C(),C.then(function(A){(S._status===0||S._status===-1)&&(S._status=1,S._result=A)},function(A){(S._status===0||S._status===-1)&&(S._status=2,S._result=A)}),S._status===-1&&(S._status=0,S._result=C)}if(S._status===1)return S._result.default;throw S._result}var It=typeof reportError=="function"?reportError:function(S){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var C=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof S=="object"&&S!==null&&typeof S.message=="string"?String(S.message):String(S),error:S});if(!window.dispatchEvent(C))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",S);return}console.error(S)},Jt={map:D,forEach:function(S,C,A){D(S,function(){C.apply(this,arguments)},A)},count:function(S){var C=0;return D(S,function(){C++}),C},toArray:function(S){return D(S,function(C){return C})||[]},only:function(S){if(!Y(S))throw Error("React.Children.only expected to receive a single React element child.");return S}};return R.Activity=d,R.Children=Jt,R.Component=y,R.Fragment=s,R.Profiler=i,R.PureComponent=E,R.StrictMode=n,R.Suspense=l,R.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=M,R.__COMPILER_RUNTIME={__proto__:null,c:function(S){return M.H.useMemoCache(S)}},R.cache=function(S){return function(){return S.apply(null,arguments)}},R.cacheSignal=function(){return null},R.cloneElement=function(S,C,A){if(S==null)throw Error("The argument must be a React element, but you passed "+S+".");var P=g({},S.props),$=S.key;if(C!=null)for(G in C.key!==void 0&&($=""+C.key),C)!k.call(C,G)||G==="key"||G==="__self"||G==="__source"||G==="ref"&&C.ref===void 0||(P[G]=C[G]);var G=arguments.length-2;if(G===1)P.children=A;else if(1<G){for(var j=Array(G),ae=0;ae<G;ae++)j[ae]=arguments[ae+2];P.children=j}return N(S.type,$,P)},R.createContext=function(S){return S={$$typeof:r,_currentValue:S,_currentValue2:S,_threadCount:0,Provider:null,Consumer:null},S.Provider=S,S.Consumer={$$typeof:o,_context:S},S},R.createElement=function(S,C,A){var P,$={},G=null;if(C!=null)for(P in C.key!==void 0&&(G=""+C.key),C)k.call(C,P)&&P!=="key"&&P!=="__self"&&P!=="__source"&&($[P]=C[P]);var j=arguments.length-2;if(j===1)$.children=A;else if(1<j){for(var ae=Array(j),te=0;te<j;te++)ae[te]=arguments[te+2];$.children=ae}if(S&&S.defaultProps)for(P in j=S.defaultProps,j)$[P]===void 0&&($[P]=j[P]);return N(S,G,$)},R.createRef=function(){return{current:null}},R.forwardRef=function(S){return{$$typeof:a,render:S}},R.isValidElement=Y,R.lazy=function(S){return{$$typeof:u,_payload:{_status:-1,_result:S},_init:se}},R.memo=function(S,C){return{$$typeof:p,type:S,compare:C===void 0?null:C}},R.startTransition=function(S){var C=M.T,A={};M.T=A;try{var P=S(),$=M.S;$!==null&&$(A,P),typeof P=="object"&&P!==null&&typeof P.then=="function"&&P.then(O,It)}catch(G){It(G)}finally{C!==null&&A.types!==null&&(C.types=A.types),M.T=C}},R.unstable_useCacheRefresh=function(){return M.H.useCacheRefresh()},R.use=function(S){return M.H.use(S)},R.useActionState=function(S,C,A){return M.H.useActionState(S,C,A)},R.useCallback=function(S,C){return M.H.useCallback(S,C)},R.useContext=function(S){return M.H.useContext(S)},R.useDebugValue=function(){},R.useDeferredValue=function(S,C){return M.H.useDeferredValue(S,C)},R.useEffect=function(S,C){return M.H.useEffect(S,C)},R.useEffectEvent=function(S){return M.H.useEffectEvent(S)},R.useId=function(){return M.H.useId()},R.useImperativeHandle=function(S,C,A){return M.H.useImperativeHandle(S,C,A)},R.useInsertionEffect=function(S,C){return M.H.useInsertionEffect(S,C)},R.useLayoutEffect=function(S,C){return M.H.useLayoutEffect(S,C)},R.useMemo=function(S,C){return M.H.useMemo(S,C)},R.useOptimistic=function(S,C){return M.H.useOptimistic(S,C)},R.useReducer=function(S,C,A){return M.H.useReducer(S,C,A)},R.useRef=function(S){return M.H.useRef(S)},R.useState=function(S){return M.H.useState(S)},R.useSyncExternalStore=function(S,C,A){return M.H.useSyncExternalStore(S,C,A)},R.useTransition=function(){return M.H.useTransition()},R.version="19.2.4",R}var gn;function Zo(){return gn||(gn=1,es.exports=Jo()),es.exports}var er=Zo();const c=Xo(er),tr=c.createContext(null);function he(){const t=c.useContext(tr);if(!t)throw new Error("useUiPlatform must be used within a UiPlatformProvider");return t}function H(t,e,s=Object.is){const n=c.useRef(e),i=c.useRef(s);n.current=e,i.current=s;const[o,r]=c.useState(()=>e(t.getState())),a=c.useRef(o);return c.useEffect(()=>{a.current=o},[o]),c.useEffect(()=>t.subscribe(l=>{const p=n.current(l);i.current(a.current,p)||(a.current=p,r(p))}),[t]),o}const yn=[".  ",".. ","..."];function Ti(t,e=360){const[s,n]=c.useState(0);return c.useEffect(()=>{if(!t){n(0);return}const i=setInterval(()=>{n(o=>(o+1)%yn.length)},e);return()=>clearInterval(i)},[t,e]),t?yn[s]:""}function ki(t,e=""){if(!Array.isArray(t)||t.length===0)return null;if(!e)return t;const s=t[t.length-1]||{};return[...t,{text:e,color:s.color||"gray",bold:!!s.bold,underline:!!s.underline,backgroundColor:s.backgroundColor}]}const w={SESSIONS:"sessions",CHAT:"chat",INSPECTOR:"inspector",ACTIVITY:"activity",PROMPT:"prompt",ADMIN:"admin"},ge=["sequence","logs","nodes","history","files","stats"],b={REFRESH:"refresh",NEW_SESSION:"newSession",OPEN_MODEL_PICKER:"openModelPicker",OPEN_THEME_PICKER:"openThemePicker",OPEN_RENAME_SESSION:"openRenameSession",OPEN_SESSION_FILTER:"openSessionFilter",OPEN_TERMINATE_PICKER:"openTerminatePicker",OPEN_MOVE_TO_GROUP:"openMoveToGroup",CREATE_SESSION_GROUP:"createSessionGroup",OPEN_ARTIFACT_UPLOAD:"openArtifactUpload",TOGGLE_CHAT_VIEW:"toggleChatView",CLOSE_MODAL:"closeModal",MODAL_PREV:"modalPrev",MODAL_NEXT:"modalNext",MODAL_PANE_PREV:"modalPanePrev",MODAL_PANE_NEXT:"modalPaneNext",MODAL_CONFIRM:"modalConfirm",SEND_PROMPT:"sendPrompt",FOCUS_NEXT:"focusNext",FOCUS_PREV:"focusPrev",FOCUS_LEFT:"focusLeft",FOCUS_RIGHT:"focusRight",FOCUS_PROMPT:"focusPrompt",FOCUS_SESSIONS:"focusSessions",MOVE_SESSION_UP:"moveSessionUp",MOVE_SESSION_DOWN:"moveSessionDown",EXPAND_SESSION:"expandSession",COLLAPSE_SESSION:"collapseSession",NEXT_INSPECTOR_TAB:"nextInspectorTab",PREV_INSPECTOR_TAB:"prevInspectorTab",CYCLE_INSPECTOR_TAB:"cycleInspectorTab",GROW_LEFT_PANE:"growLeftPane",GROW_RIGHT_PANE:"growRightPane",GROW_SESSION_PANE:"growSessionPane",SHRINK_SESSION_PANE:"shrinkSessionPane",OPEN_ARTIFACT_PICKER:"openArtifactPicker",TOGGLE_LOG_TAIL:"toggleLogTail",TOGGLE_STATS_VIEW:"toggleStatsView",OPEN_LOG_FILTER:"openLogFilter",OPEN_FILES_FILTER:"openFilesFilter",MOVE_FILE_UP:"moveFileUp",MOVE_FILE_DOWN:"moveFileDown",DOWNLOAD_SELECTED_FILE:"downloadSelectedFile",DELETE_SELECTED_FILE:"deleteSelectedFile",OPEN_SELECTED_FILE:"openSelectedFile",TOGGLE_FILE_PREVIEW_FULLSCREEN:"toggleFilePreviewFullscreen",TOGGLE_PANE_FULLSCREEN:"togglePaneFullscreen",SCROLL_UP:"scrollUp",SCROLL_DOWN:"scrollDown",PAGE_UP:"pageUp",PAGE_DOWN:"pageDown",EXPAND_HISTORY:"expandHistory",SCROLL_TOP:"scrollTop",SCROLL_BOTTOM:"scrollBottom",DONE_SESSION:"doneSession",CANCEL_SESSION:"cancelSession",STOP_TURN:"stopTurn",DELETE_SESSION:"deleteSession",PIN_SESSION:"pinSession",TOGGLE_SELECT_MODE:"toggleSelectMode",TOGGLE_SESSION_SELECTION:"toggleSessionSelection",CLEAR_SESSION_SELECTION:"clearSessionSelection",OPEN_HISTORY_FORMAT:"openHistoryFormat",REFRESH_EXECUTION_HISTORY:"refreshExecutionHistory",EXPORT_EXECUTION_HISTORY:"exportExecutionHistory",OPEN_ADMIN_CONSOLE:"openAdminConsole",CLOSE_ADMIN_CONSOLE:"closeAdminConsole",ADMIN_REFRESH_PROFILE:"adminRefreshProfile",ADMIN_BEGIN_EDIT_GHCP_KEY:"adminBeginEditGhcpKey",ADMIN_CANCEL_EDIT_GHCP_KEY:"adminCancelEditGhcpKey",ADMIN_SAVE_GHCP_KEY:"adminSaveGhcpKey",ADMIN_CLEAR_GHCP_KEY:"adminClearGhcpKey"};function Ze(t,e,s){const n=t.indexOf(e),o=((n===-1?0:n)+s+t.length)%t.length;return t[o]}function Bs(t){const e=typeof t?.utilization=="number"?t.utilization:typeof t?.tokenLimit=="number"&&t.tokenLimit>0&&typeof t?.currentTokens=="number"?t.currentTokens/t.tokenLimit:null;return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.min(100,Math.round(e*100)))}function Is(t){return typeof t!="number"||!Number.isFinite(t)||t<0?"?":t>=1e6?`${t>=1e7?Math.round(t/1e6):Math.round(t/1e5)/10}`.replace(/\.0$/,"")+"m":t>=1e3?`${t>=1e5?Math.round(t/1e3):Math.round(t/100)/10}`.replace(/\.0$/,"")+"k":String(Math.round(t))}function sr(t){const e=Bs(t);return e==null?"gray":e>=85?"red":e>=70?"yellow":"gray"}function nr(t){if(!t||!(typeof t.tokenLimit=="number"&&t.tokenLimit>0&&typeof t.currentTokens=="number"&&t.currentTokens>=0))return null;const e=Bs(t);return e==null?null:{text:`ctx ${Is(t.currentTokens)}/${Is(t.tokenLimit)} ${e}%`,color:sr(t)}}function ir(t){if(!t)return null;const e=t.compaction;if(e?.state==="running")return{text:"[compact]",color:"magenta"};if(e?.state==="failed")return{text:"[compact !]",color:"red"};const s=Bs(t);return s==null||s<70?null:{text:`[ctx ${s}%]`,color:s>=85?"red":"yellow"}}function or(t){const e=t?.compaction;return!e||typeof e!="object"?null:e.state==="running"?{text:"[compacting]",color:"magenta"}:e.state==="failed"?{text:"[compact failed]",color:"red"}:null}function Mi(t){return!t||typeof t!="object"?null:{...t,...t.compaction&&typeof t.compaction=="object"?{compaction:{...t.compaction}}:{}}}function rr(t){if(t instanceof Date)return t.getTime();const e=new Date(t).getTime();return Number.isFinite(e)?e:Date.now()}function Pi(t,e,s={},n={}){if(!e)return null;const i=Mi(t)||{},o=rr(n.timestamp);return e==="session.usage_info"?typeof s.tokenLimit!="number"||typeof s.currentTokens!="number"||typeof s.messagesLength!="number"?null:(i.tokenLimit=s.tokenLimit,i.currentTokens=s.currentTokens,i.messagesLength=s.messagesLength,i.utilization=s.tokenLimit>0?s.currentTokens/s.tokenLimit:0,typeof s.systemTokens=="number"&&(i.systemTokens=s.systemTokens),typeof s.conversationTokens=="number"&&(i.conversationTokens=s.conversationTokens),typeof s.toolDefinitionsTokens=="number"&&(i.toolDefinitionsTokens=s.toolDefinitionsTokens),typeof s.isInitial=="boolean"&&(i.isInitial=s.isInitial),i):e==="assistant.usage"?(typeof s.inputTokens=="number"&&(i.lastInputTokens=s.inputTokens),typeof s.outputTokens=="number"&&(i.lastOutputTokens=s.outputTokens),typeof s.cacheReadTokens=="number"&&(i.lastCacheReadTokens=s.cacheReadTokens),typeof s.cacheWriteTokens=="number"&&(i.lastCacheWriteTokens=s.cacheWriteTokens),i):e==="session.compaction_start"?(i.compaction={...i.compaction||{},state:"running",startedAt:o,completedAt:void 0,error:void 0},i):e==="session.compaction_complete"?(i.compaction={...i.compaction||{},state:s.success===!1?"failed":"succeeded",completedAt:o,error:typeof s.error=="string"?s.error:void 0,preCompactionTokens:typeof s.preCompactionTokens=="number"?s.preCompactionTokens:void 0,postCompactionTokens:typeof s.postCompactionTokens=="number"?s.postCompactionTokens:void 0,preCompactionMessagesLength:typeof s.preCompactionMessagesLength=="number"?s.preCompactionMessagesLength:void 0,messagesRemoved:typeof s.messagesRemoved=="number"?s.messagesRemoved:void 0,tokensRemoved:typeof s.tokensRemoved=="number"?s.tokensRemoved:void 0,systemTokens:typeof s.systemTokens=="number"?s.systemTokens:void 0,conversationTokens:typeof s.conversationTokens=="number"?s.conversationTokens:void 0,toolDefinitionsTokens:typeof s.toolDefinitionsTokens=="number"?s.toolDefinitionsTokens:void 0,inputTokens:typeof s.compactionTokensUsed?.input=="number"?s.compactionTokensUsed.input:void 0,outputTokens:typeof s.compactionTokensUsed?.output=="number"?s.compactionTokensUsed.output:void 0,cachedInputTokens:typeof s.compactionTokensUsed?.cachedInput=="number"?s.compactionTokensUsed.cachedInput:void 0},typeof s.postCompactionTokens=="number"&&typeof i.tokenLimit=="number"&&i.tokenLimit>0&&(i.currentTokens=s.postCompactionTokens,i.utilization=s.postCompactionTokens/i.tokenLimit),typeof s.preCompactionMessagesLength=="number"&&typeof s.messagesRemoved=="number"&&(i.messagesLength=Math.max(0,s.preCompactionMessagesLength-s.messagesRemoved)),typeof s.systemTokens=="number"&&(i.systemTokens=s.systemTokens),typeof s.conversationTokens=="number"&&(i.conversationTokens=s.conversationTokens),typeof s.toolDefinitionsTokens=="number"&&(i.toolDefinitionsTokens=s.toolDefinitionsTokens),i):null}function ar(t,e,s={}){const n=t?[{text:`[${t}] `,color:"white"}]:[];return e==="session.compaction_start"?[...n,{text:"[compaction]",color:"magenta"},{text:" started",color:"white"}]:s.success===!1?[...n,{text:"[compaction]",color:"red"},{text:" failed",color:"white"},...typeof s.error=="string"&&s.error?[{text:`: ${s.error}`,color:"red"}]:[]]:[...n,{text:"[compaction]",color:"magenta"},{text:" complete",color:"white"},...typeof s.tokensRemoved=="number"?[{text:` freed ${Is(s.tokensRemoved)}`,color:"gray"}]:[]]}const xs=/\{(\/?)([a-z-]+)\}/g,lr={color:null,bold:!1,underline:!1},Rt=/artifact:\/\/([a-f0-9-]+)\/([^\s"'{}]+)/g,Sn=/session:\/\/([A-Za-z0-9-]+)/g,cr={black:"black",red:"red",green:"green",yellow:"yellow",blue:"blue",magenta:"magenta",cyan:"cyan",white:"white",gray:"gray",grey:"gray"};function Mt(t){return{color:t.color,bold:t.bold,underline:t.underline}}function ur(t,e,s){const n=Mt(t);if(e==="bold")return n.bold=!s,n;if(e==="underline")return n.underline=!s,n;if(e.endsWith("-fg")){const i=e.slice(0,-3);return n.color=s?null:cr[i]||null,n}return n}function Ni(t){return String(t||"").replace(xs,"")}function Oi(t){const e=[],n=String(t||"").split(`
2
- `);for(const i of n){const o=[];let r=Mt(lr),a=0,l;for(;(l=xs.exec(i))!==null;){const[p,u,d]=l;l.index>a&&o.push({text:i.slice(a,l.index),...Mt(r)}),r=ur(r,d,u==="/"),a=l.index+p.length}(a<i.length||o.length===0)&&o.push({text:i.slice(a),...Mt(r)}),e.push(o),xs.lastIndex=0}return e}function K(t){return String(t||"").slice(0,8)}function Ri(t){const e=String(t||"");return e?e.includes(":")?e.split(":").slice(1).join(":"):e:""}function ce(t){if(!t)return"";try{return(t instanceof Date?t:new Date(t)).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})}catch{return""}}function dr(t,e={}){if(!t)return"";try{return(t instanceof Date?t:new Date(t)).toLocaleString("en-GB",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1,...e})}catch{return""}}function at(t){if(typeof t!="number"||!Number.isFinite(t)||t<0)return"?";const e=Math.round(t),s=Math.floor(e/3600),n=Math.floor(e%3600/60),i=e%60;return s>0?`${s}h ${n}m`:n>0?`${n}m ${i}s`:`${i}s`}function fr(t){if(t==null)return"";if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}function pr(t,e,s){const n=t.indexOf(e,s);return n>=0?n:-1}function Ft(t){return/[A-Za-z0-9_]/u.test(String(t||""))}function bn(t,e,s){const n=t[e+s.length]||"";if(!n||/\s/u.test(n))return!1;if(!s.includes("_"))return!0;const i=t[e-1]||"";return!(Ft(i)&&Ft(n))}function hr(t,e,s){const n=t[e-1]||"";if(!n||/\s/u.test(n))return!1;if(!s.includes("_"))return!0;const i=t[e+s.length]||"";return!(Ft(n)&&Ft(i))}function wn(t,e,s){let n=s;for(;n<t.length;){const i=t.indexOf(e,n);if(i<0)return-1;if(hr(t,i,e))return i;n=i+e.length}return-1}function mr(t){let e=String(t||""),s="";for(;e&&/[.,!?;:]/u.test(e[e.length-1]||"");)s=`${e[e.length-1]}${s}`,e=e.slice(0,-1);return{url:e,trailing:s}}function gr(t,e,s){let n=0;for(;t.slice(s+n,s+n+e.length)===e;)n+=e.length;return n}function et(t,e,s={}){if(!e)return;const n=t[t.length-1];if(n&&n.color===(s.color||null)&&!!n.bold==!!s.bold&&!!n.underline==!!s.underline&&n.backgroundColor===s.backgroundColor&&n.href===s.href){n.text+=e;return}t.push({text:e,color:s.color||null,bold:!!s.bold,underline:!!s.underline,backgroundColor:s.backgroundColor||void 0,href:s.href||void 0})}function ke(t,e){if(e){if(e.type==="text"){const s=t[t.length-1];if(s?.type==="text"){s.text+=e.text||"";return}}t.push(e)}}function Fi(t){return(t||[]).map(e=>e?.text||"").join("")}function Pt(t){return pe(Fi(t))}function yr(t,e){const s=Math.max(0,Number(e)||0);if(s<=0)return[];const n=[];let i=s;for(const o of t||[]){if(i<=0)break;const r=String(o?.text||"");if(!r)continue;const a=yt(r,i);a&&(n.push({...o,text:a}),i-=pe(a))}return n}function _i(t,e){const s=Math.max(0,Number(e)||0),n=yr(t,s),i=Pt(n),o=Math.max(0,s-i);return o>0&&n.push({text:" ".repeat(o),color:null,bold:!1,underline:!1}),n}function Li(t,e){const s=Math.max(1,Number(e)||1),n=[];let i=[],o=0;function r(){if(i.length===0){n.push([{text:"",color:null,bold:!1,underline:!1}]);return}n.push(i),i=[],o=0}for(const a of t||[]){let l=String(a?.text||"");if(l)for(;l.length>0;){const p=Math.max(1,s-o),u=yt(l,p);if(!u)break;if(u.length===l.length||pe(u)<p){i.push({...a,text:u}),o+=pe(u),l=l.slice(u.length),o>=s&&r();continue}const d=u.lastIndexOf(" ");if(d>0&&(o>0||d>0)){const f=u.slice(0,d+1);i.push({...a,text:f}),o+=pe(f),l=l.slice(f.length),r()}else i.push({...a,text:u}),o+=pe(u),l=l.slice(u.length),o>=s&&r()}}return(i.length>0||n.length===0)&&r(),n}function Sr(t,e){return e?(t||[]).map(s=>String(s?.text||"").trim()?{...s,color:e}:{...s}):t}function $i(t){if(!t)return t;let e=String(t);for(;;){const s=e.replace(/[*_`]+$/g,"").replace(/[)\]}>!,;:?]+$/g,"").replace(/(\.[A-Za-z0-9]{1,16})\.+$/g,"$1");if(s===e)return e;e=s}}function br(t){const e=String(t||"");return Rt.lastIndex=0,[...e.matchAll(Rt)].map(s=>{const n=s[1],i=$i(s[2]);return!n||!i?null:{sessionId:n,filename:i,uri:`artifact://${n}/${i}`}}).filter(Boolean)}function Ue(t){const e=String(t||"");if(!e)return e;Rt.lastIndex=0;const s=e.replace(Rt,(n,i,o)=>{const r=$i(o);return!i||!r?n:`[artifact: ${r}](artifact://${i}/${r}) (press a to download)`});return Sn.lastIndex=0,s.replace(Sn,(n,i)=>i?`[session: ${K(i)}](session://${i})`:n)}function Ds(t=""){const e=String(t||""),s=[];let n=0;for(;n<e.length;){if(e[n]==="`"){const o=gr(e,"`",n),r="`".repeat(o),a=pr(e,r,n+o);if(a>n+o-1){ke(s,{type:"code",text:e.slice(n+o,a)}),n=a+o;continue}}if(e.startsWith("**",n)||e.startsWith("__",n)){const o=e.slice(n,n+2),r=bn(e,n,o)?wn(e,o,n+2):-1;if(r>n+2){ke(s,{type:"strong",text:e.slice(n+2,r)}),n=r+2;continue}}if(e[n]==="["){const o=/^\[([^\]]+)\]\(([^)]+)\)/.exec(e.slice(n));if(o){ke(s,{type:"link",text:o[1],href:o[2]}),n+=o[0].length;continue}}if(e.startsWith("<http://",n)||e.startsWith("<https://",n)){const o=e.indexOf(">",n+1);if(o>n+1){const r=e.slice(n+1,o);ke(s,{type:"link",text:r,href:r}),n=o+1;continue}}if(e.startsWith("http://",n)||e.startsWith("https://",n)){let o=n;for(;o<e.length&&!/\s/u.test(e[o]||"");)o+=1;const{url:r,trailing:a}=mr(e.slice(n,o));if(r){ke(s,{type:"link",text:r,href:r}),a&&ke(s,{type:"text",text:a}),n=o;continue}}if((e[n]==="*"||e[n]==="_")&&e[n+1]!==" "&&e[n-1]!==e[n]&&bn(e,n,e[n])){const o=e[n],r=wn(e,o,n+1);if(r>n+1){ke(s,{type:"em",text:e.slice(n+1,r)}),n=r+1;continue}}let i=e.length;for(const o of["<https://","<http://","https://","http://","**","__","`","[","*","_"]){const r=e.indexOf(o,n+1);r!==-1&&r<i&&(i=r)}ke(s,{type:"text",text:e.slice(n,i)}),n=i}return s.length>0?s:[{type:"text",text:""}]}function wr(t=""){return Ds(t).filter(e=>e?.type==="link"&&/^https?:\/\//i.test(String(e?.href||""))).map(e=>({href:String(e.href||"").trim(),text:String(e.text||e.href||"").trim()})).filter(e=>e.href)}function nt(t){const e=Ds(t),s=[];for(const n of e){if(n.type==="code"){et(s,n.text,{color:"cyan"});continue}if(n.type==="strong"){et(s,n.text,{bold:!0});continue}if(n.type==="em"){et(s,n.text,{underline:!0});continue}if(n.type==="link"){et(s,n.text,{color:"cyan",underline:!0,href:n.href});continue}et(s,n.text)}return s.length>0?s:[{text:"",color:null,bold:!1,underline:!1}]}function We(t){return/^\s*\|.*\|\s*$/.test(t)||/^\s*\|?[:\- ]+\|[:\-| ]+\|?\s*$/.test(t)}function Ve(t){const e=String(t||"").trim().replace(/^\|/,"").replace(/\|$/,""),s=[];let n="",i=!1;for(const o of e){if(i){n+=o,i=!1;continue}if(o==="\\"){i=!0;continue}if(o==="|"){s.push(n.trim()),n="";continue}n+=o}return s.push(n.trim()),s}function _t(t){return t.length>0&&t.every(e=>/^:?-{3,}:?$/.test(String(e||"").replace(/\s+/g,"")))}function pe(t){return Array.from(String(t||"")).length}function yt(t,e){if(e<=0)return"";let s="",n=0;for(const i of Array.from(String(t||""))){if(n+1>e)break;s+=i,n+=1}return s}function Bi(t,e){const s=String(t||""),n=Math.max(0,e-pe(s));return s+" ".repeat(n)}function Di(t){return Fi(nt(t))}function Ir(t,e){const s=Di(t).replace(/\s+/g," ").trim();if(!s)return[""];const n=s.split(" "),i=[];let o="";const r=a=>{let l=a;for(;pe(l)>e;){const p=yt(l,e);if(!p)break;o&&(i.push(o),o=""),i.push(p),l=l.slice(p.length)}return l};for(const a of n){const l=r(a);if(!l)continue;if(!o){o=l;continue}const p=`${o} ${l}`;pe(p)<=e?o=p:(i.push(o),o=l)}return o&&i.push(o),i.length>0?i:[""]}function xr(t,e){const s=Math.max(1,...t.map(u=>u.length)),n=Math.max(s*3,e-(s*3+1)),i=Array.from({length:s},(u,d)=>Math.max(3,...t.map(f=>pe(f[d]||"")))),o=Array.from({length:s},(u,d)=>Math.max(3,...t.map(f=>Math.max(0,...String(f[d]||"").split(/\s+/).filter(Boolean).map(h=>pe(h)))))),r=Array.from({length:s},(u,d)=>Math.max(3,Math.min(Math.max(pe(t[0]?.[d]||"")||3,o[d]),24)));if(i.reduce((u,d)=>u+d,0)<=n)return i;const l=r.slice();let p=n-l.reduce((u,d)=>u+d,0);if(p<0){const u=Math.max(3,Math.floor(n/s));return l.map((d,f)=>f===s-1?Math.max(3,n-u*(s-1)):u)}for(;p>0;){let u=0,d=-1/0;for(let f=0;f<s;f++){const h=i[f]-l[f];h>d&&(d=h,u=f)}if(d<=0){l[s-1]+=p;break}l[u]+=1,p-=1}return l}function Er(t,e){if(!t||t.length===0)return"";const s=Math.max(1,...t.map(f=>f.length)),i=t.map(f=>Array.from({length:s},(h,m)=>f[m]||"")).map(f=>f.map(h=>Di(h))),o=xr(i,e),r=[],a=`┌${o.map(f=>"─".repeat(f+2)).join("┬")}┐`,l=`├${o.map(f=>"─".repeat(f+2)).join("┼")}┤`,p=`└${o.map(f=>"─".repeat(f+2)).join("┴")}┘`,u=f=>{const h=f.map((g,I)=>Ir(g,o[I])),m=Math.max(...h.map(g=>g.length));for(let g=0;g<m;g++){const I=h.map((y,x)=>Bi(y[g]||"",o[x]));r.push(`│ ${I.join(" │ ")} │`)}};r.push(a),u(i[0]),r.push(l);const d=i.slice(1);for(const f of d)u(f);return r.push(p),r.join(`
3
- `)}function vr(t,e){const s=String(t||"").split(`
4
- `),n=[];let i=!1;for(let o=0;o<s.length;o++){const r=s[o];if(r.trim().startsWith("```")){i=!i,n.push(r);continue}if(i){n.push(r);continue}const l=s[o+1];if(!We(r)||!We(l)){n.push(r);continue}const p=Ve(r),u=Ve(l);if(!_t(u)||p.length!==u.length){n.push(r);continue}const d=[p];for(o+=1;o+1<s.length&&We(s[o+1]);){o+=1;const f=Ve(s[o]);_t(f)||d.push(f)}n.push(Er(d,e))}return n.join(`
5
- `)}function Cr(t,e){const s=String(t||"");if(!s)return[""];const n=[];let i=s;for(;i.length>0;){const o=yt(i,e);if(!o)break;n.push(o),i=i.slice(o.length)}return n.length>0?n:[""]}function In(t,e){const s=Math.max(12,e),n=t?` ${String(t).trim()} `:" code ",i=yt(n,Math.max(1,s-4)),o=Math.max(0,s-i.length-2);return[{text:`┌${i}${"─".repeat(o)}┐`,color:"gray"}]}function xn(t){return[{text:`└${"─".repeat(Math.max(1,t-2))}┘`,color:"gray"}]}function En(t,e){const s=Math.max(8,e),n=Math.max(1,s-2),i=[];for(const o of t){const r=Cr(o,n);for(const a of r)i.push([{text:"│",color:"gray"},{text:Bi(a,n),color:"cyan"},{text:"│",color:"gray"}]);r.length===0&&i.push([{text:"│",color:"gray"},{text:" ".repeat(n),color:"cyan"},{text:"│",color:"gray"}])}return i.length===0&&i.push([{text:"│",color:"gray"},{text:" ".repeat(n),color:"cyan"},{text:"│",color:"gray"}]),i}function ut(t,e={}){const s=[],n=Math.max(20,Number(e?.width)||80),i=e.tableMode==="sentinel"?"sentinel":"boxArt",r=(i==="boxArt"?vr(String(t||""),n):String(t||"")).split(`
6
- `);let a=!1,l="",p=[];for(let u=0;u<r.length;u+=1){const d=r[u],f=d.trim();if(f.startsWith("```")){a?(s.push(In(l,Math.max(8,n))),s.push(...En(p,Math.max(8,n))),s.push(xn(Math.max(8,n))),a=!1,l="",p=[]):(a=!0,l=f.slice(3).trim(),p=[]);continue}if(a){p.push(d);continue}if(i==="sentinel"&&d&&We(d)){const y=r[u+1]||"";if(We(y)){const x=Ve(d),E=Ve(y);if(_t(E)&&x.length===E.length){const v=[];let T=u+2;for(;T<r.length&&We(r[T]);){const O=Ve(r[T]);_t(O)||v.push(O),T+=1}s.push({kind:"markdownTable",header:x,rows:v}),u=T-1;continue}}}if(!d){s.push([{text:"",color:null}]);continue}const h=/^(#{1,6})\s+(.*)$/.exec(d);if(h){s.push([{text:h[2],color:"white",bold:!0}]);continue}const m=/^>\s?(.*)$/.exec(d);if(m){s.push([{text:"> ",color:"gray"},...nt(m[1]).map(y=>({...y,color:y.color||"gray"}))]);continue}const g=/^\s*[-*]\s+(.*)$/.exec(d);if(g){s.push([{text:"• ",color:"gray"},...nt(g[1])]);continue}const I=/^\s*(\d+)\.\s+(.*)$/.exec(d);if(I){s.push([{text:`${I[1]}. `,color:"gray"},...nt(I[2])]);continue}s.push(nt(d))}return a&&(s.push(In(l,Math.max(8,n))),s.push(...En(p,Math.max(8,n))),s.push(xn(Math.max(8,n)))),s}function Q({title:t="SYSTEM",timestamp:e="",body:s="",width:n=80,titleColor:i="yellow",borderColor:o="gray",bodyColor:r=null,fitToContent:a=!1}={}){const l=Math.max(a?12:20,Number(n)||(a?12:20)),p=Math.max(1,l-4),u=[{text:` ${String(t||"SYSTEM").toUpperCase()} `,color:i,bold:!0},...e?[{text:` ${String(e)} `,color:"gray"}]:[]],d=ut(String(s||""),{width:p}),f=d.length>0?d.flatMap(x=>Li(x,p)):[[{text:"",color:null}]],h=r?f.map(x=>Sr(x,r)):f,m=h.reduce((x,E)=>Math.max(x,Pt(E)),0),g=a?Math.min(l,Math.max(12,Pt(u)+3,m+4)):l,I=Math.max(1,g-4),y=Math.max(0,g-Pt(u)-3);return[[{text:"┌─",color:o},...u,{text:`${"─".repeat(y)}┐`,color:o}],...h.map(x=>[{text:"│ ",color:o},..._i(x,I),{text:" │",color:o}]),[{text:`└${"─".repeat(Math.max(1,g-2))}┘`,color:o}],[{text:"",color:null}]]}function St(t,e="PilotSwarm"){const s=e||"PilotSwarm",n=String(t?.agentId||"");if(n==="pilotswarm")return s;if(n==="sweeper")return"Sweeper Agent";if(n==="resourcemgr")return"Resource Manager Agent";if(n==="facts-manager")return"Facts Manager";const i=String(t?.title||"").trim();return/^pilotswarm(?: agent)?$/i.test(i)?s:/^sweeper agent$/i.test(i)||/^sweeper$/i.test(i)?"Sweeper Agent":/^resource manager agent$/i.test(i)||/^resourcemgr$/i.test(i)?"Resource Manager Agent":/^facts manager$/i.test(i)||/^facts-manager$/i.test(i)?"Facts Manager":i||"System Agent"}function Hi(t){const e=St(t,"PilotSwarm");return e==="PilotSwarm"?0:e==="Sweeper Agent"?1:e==="Resource Manager Agent"?2:e==="Facts Manager"?3:10}const V=300,Ar=[V,1e3,3e3,1e4];function xe(t,e){const s=Array.isArray(t)?t.filter(Boolean):[],n=Math.max(V,Number(e)||V);return s.length>n?s.slice(-n):s}function ve(t){return String(t||"").replace(/\r\n/g,`
7
- `).trim()}function vn(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.isNaN(e.getTime()))return"";try{return e.toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1,timeZoneName:"short"}).replace(/,\s*/g," ").replace(/\s+/g," ").trim()}catch{return e.toISOString().replace(/\.000Z$/,"Z")}}const Gi=/^The session was dehydrated and has been rehydrated on a new worker(?: \([^)]+\))?\./i,Tr=/^The session was dehydrated and has been rehydrated on a new worker(?: \([^)]+\))?\.\s*The LLM conversation history is preserved\.?/i;function Hs(t){return Gi.test(ve(t))}function Ne(t){const e=String(t||"").replace(/\r\n/g,`
8
- `).trim();if(!e)return"";const s=e.replace(Tr,"").trimStart();return s!==e?s.trim():Hs(e)?e.replace(Gi,"").trim():e}function ji(t){const e=String(t||"").replace(/\r\n/g,`
9
- `).split(`
10
- `),s=[];let n=[];function i(){n.length!==0&&(s.push({kind:"text",text:n.join(`
11
- `)}),n=[])}for(let o=0;o<e.length;){const r=e[o];if(!/^\s*\[SYSTEM:/i.test(r)){n.push(r),o+=1;continue}const a=/^\s*\[SYSTEM:\s*(.*?)\]\s*$/i.exec(r);if(a){i(),s.push({kind:"system",text:a[1].trim()}),o+=1;continue}const l=[r.replace(/^\s*\[SYSTEM:\s*/i,"")];let p=-1;for(let u=o+1;u<e.length;u+=1){const d=e[u];if(d.trim()==="]"){p=u;break}if(/\]\s*$/.test(d.trim())){const f=d.replace(/\]\s*$/,"");f.trim()&&l.push(f),p=u;break}l.push(d)}if(p===-1){n.push(r),o+=1;continue}i(),s.push({kind:"system",text:l.join(`
12
- `).trim()}),o=p+1}return i(),s}function Ui(t,e){const s=String(t||"").replace(/\r\n/g,`
13
- `);return e==="user"||e==="assistant"?ji(s).filter(n=>n.kind==="text").map(n=>n.text).join(`
14
- `).trim():s.trim()}function kr(t,e){return e!=="user"&&e!=="assistant"?[]:ji(t).filter(s=>s.kind==="system").map(s=>s.text).filter(Boolean)}function Cn(t){const e=ve(t?.text||"");if(!e)return"";if(t?.role==="user"||t?.role==="assistant"){const s=Ui(e,t.role);if(s)return s}return Ne(e)}function Gs(t){const e=String(t||"").replace(/\r\n/g,`
15
- `).trim(),s='The user was asked: "',n=`"
16
- The user responded: "`;if(!e.startsWith(s)||!e.endsWith('"'))return null;const i=e.indexOf(n,s.length);if(i===-1)return null;const o=e.slice(s.length,i),r=e.slice(i+n.length,-1);return!o.trim()||!r.trim()?null:{question:o,answer:r}}function Mr(t){return ve(Ni(t)).length>0}function Pr(t){const e=ve(t);return e?/^\[SYSTEM:/i.test(e)||/^\[CHILD_UPDATE\b/i.test(e)||/^\[SESSION_MESSAGE(?:_RESPONSE)?\b/i.test(e)||/^Buffered child updates arrived /i.test(e)||/^There is an active recurring schedule every /i.test(e)||/^It remains active automatically after this turn completes/i.test(e)||/^Sub-agent spawned successfully\./i.test(e)||/^Message sent to sub-agent /i.test(e)||/^No sub-agents have been spawned yet\./i.test(e)||/^Sub-agent status report \(/i.test(e)||/^Active sessions \(/i.test(e)||/^Sub-agents completed:/i.test(e)||/^Sub-agent .* has been (completed gracefully|cancelled|deleted)\./i.test(e)||/^The runtime recovered this session after the worker lost the live Copilot session\./i.test(e)||/^The runtime recovered this session after the live Copilot session was lost on a worker\./i.test(e)||/^The runtime is replaying this turn after a worker restart/i.test(e)||/^The runtime detected missing Copilot session state for /i.test(e)||/^(spawn_agent|message_agent|check_agents|wait_for_agents|complete_agent|cancel_agent|delete_agent) failed/i.test(e):!1}function Nr(t){return/^\[SESSION_MESSAGE(?:_RESPONSE)?\b/i.test(ve(t))}function He(t,e){const s=String(t||""),n=`${e}=`,i=s.indexOf(n);if(i<0)return"";const o=s.slice(i+n.length),r=[" request_id="," from="," subject="," reason="," expects_response="," expires_at="," verdict="];let a=o.length;for(const l of r){const p=o.indexOf(l);p>=0&&(a=Math.min(a,p))}return o.slice(0,a).trim()}function Or(t,e){const s=ve(e);if(!s)return null;const n=/^\[SESSION_MESSAGE\s+([^\]]+)\]\n?/i.exec(s);if(n){const o=n[1],r=`
17
- Request body:
18
- `,a=s.indexOf(r),l=a>=0?s.slice(a+r.length).trim():s.slice(n[0].length).trim(),p=He(o,"request_id"),u=He(o,"from"),d=He(o,"subject"),f=/\bexpects_response=true\b/i.test(o),h=[u?`From: session-${K(u)}`:"",p?`Request ID: ${p}`:"",d?`Subject: ${d}`:"",f?"Response: required":"Response: not required","",l].filter((m,g)=>g===4||String(m||"").trim());return{id:`${t.sessionId}:${t.seq}`,role:"system",text:h.join(`
19
- `),time:ce(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime(),cardTitle:f?"Session Request":"Session Message",cardTitleColor:"cyan",cardBorderColor:"cyan"}}const i=/^\[SESSION_MESSAGE_RESPONSE\s+([^\]]+)\]\n?/i.exec(s);if(i){const o=i[1],r=/^This is the requested cross-session response\.[^\n]*\n\n?/i,a=s.slice(i[0].length).trim().replace(r,"").trim(),l=He(o,"request_id"),p=He(o,"from"),u=He(o,"verdict")||"answered",d=[p?`From: session-${K(p)}`:"",l?`Request ID: ${l}`:"",`Verdict: ${u}`,"",a].filter((f,h)=>h===3||String(f||"").trim());return{id:`${t.sessionId}:${t.seq}`,role:"system",text:d.join(`
20
- `),time:ce(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime(),cardTitle:"Session Reply",cardTitleColor:"green",cardBorderColor:"green"}}return null}function Rr(t,e,s){return t?.eventType==="system.message"||(e==="user"||e==="assistant")&&Pr(s)?"system":e}function Fr(t,e){if(!t||!e||t.role!==e.role)return!1;const s=Cn(t),n=Cn(e);if(!s||!n||s!==n)return!1;const i=Number(t.createdAt||0),o=Number(e.createdAt||0);return t.optimistic||e.optimistic?!0:!i||!o?!1:Math.abs(i-o)<=1e4}function qe(t=[]){const e=[];for(const s of t){if(!s)continue;const n=e[e.length-1];if(!Fr(n,s)){e.push(s);continue}if(n?.optimistic&&!s?.optimistic){e[e.length-1]=s;continue}if(!n?.optimistic&&s?.optimistic)continue;const i=Number(n?.createdAt||0),o=Number(s?.createdAt||0);e[e.length-1]=o>=i?s:n}return e}function Ke(t,e){const s=Qe(t),n=Or(t,s);if(n)return n;const i=Ui(s,e);return Mr(i)?{id:`${t.sessionId}:${t.seq}`,role:Rr(t,e,i),text:i,time:ce(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime()}:null}function Wi(t){return t?.eventType!=="system.message"?!1:!Nr(Qe(t))}function Lt(t,e){return kr(Qe(t),e).map((s,n)=>dt({...t,seq:`${t?.seq??"?"}:system:${n+1}`,eventType:"system.message",data:{content:s}})).filter(Boolean)}function _r(t,e){if(!Array.isArray(t)||e?.role!=="user")return[...t||[]];const s=ve(e.text),n=Gs(e.text),i=n?ve(n.answer):"";let o=!1;return t.filter(r=>{if(o||!r?.optimistic||r.role!==e.role)return!0;const a=ve(r.text);return a!==s&&a!==i?!0:(o=!0,!1)})}function Qe(t){const e=t?.data;if(typeof e=="string")return e;if(e&&typeof e=="object"){if(typeof e.content=="string")return e.content;if(typeof e.text=="string")return e.text;if(typeof e.message=="string")return e.message;if(typeof e.question=="string")return e.question}return fr(e)}function Lr(t){return(t||[]).map(e=>e?.text||"").join("")}function $r(t,e=120){const s=String(t||"").replace(/\s+/g," ").trim();return s?s.length>e?`${s.slice(0,e-3)}...`:s:""}function js(t=[]){const e=new Set,s=[];for(const n of t){const i=String(n||"").trim();if(!i)continue;const o=i.toLowerCase();e.has(o)||(e.add(o),s.push(i))}return s.join(" | ")}function Br(t,e=""){return js([t?.data?.reason,t?.data?.detail,t?.data?.message,t?.data?.error,e])}function Dr(t,e=""){return js([t?.data?.message,t?.data?.detail,t?.data?.error,e])}function Hr(t,e=""){const s=Qe(t),n=Ne(e);return js([Ne(s),n,t?.data?.detail,t?.data?.message])}function Gr(t){return t==null?"null":typeof t=="string"?JSON.stringify(t.length>32?`${t.slice(0,29)}...`:t):typeof t=="number"||typeof t=="boolean"?String(t):Array.isArray(t)?`[${t.length}]`:typeof t=="object"?"{...}":String(t)}function jr(t,e){if(!e||typeof e!="object")return"";if(t==="wait"){const i=e.seconds!=null?`${e.seconds}s`:"?",o=e.preserveWorkerAffinity===!0?" preserve=true":"",r=typeof e.reason=="string"&&e.reason?` reason=${JSON.stringify(e.reason)}`:"";return` ${i}${o}${r}`}if(t==="cron"){if(e.action==="cancel")return" cancel";const i=e.seconds!=null?`${e.seconds}s`:"?",o=typeof e.reason=="string"&&e.reason?` reason=${JSON.stringify(e.reason)}`:"";return` ${i}${o}`}const s=Object.entries(e).slice(0,4).map(([i,o])=>`${i}=${Gr(o)}`);if(s.length===0)return"";const n=Object.keys(e).length>s.length?", ...":"";return` ${s.join(", ")}${n}`}function Us(t){return t?[{text:`[${t}] `,color:"white"}]:[]}function z(t,e,s,n="",i="white"){return[...Us(t),{text:e,color:s},...n?[{text:` ${n}`,color:i}]:[]]}function Ur(t,e=96){return $r(Ni(Qe(t)),e)||""}function ts(t,e,s="start"){const n=typeof e?.data?.toolCallId=="string"?e.data.toolCallId:"",i=typeof e?.data?.requestId=="string"?e.data.requestId:"",o=e?.data?.toolName||e?.data?.name||(n?`tool call ${n.slice(0,8)}`:i?`tool request ${i.slice(0,8)}`:"tool"),r=e?.data?.arguments||e?.data?.args,a=e?.data?.durableSessionId,l=jr(o,r),p=s==="start"?"▶":s==="partial"?"…":"✓",u=s==="start"?"yellow":s==="partial"?"cyan":"green";return[...Us(t),{text:`${p} ${o}${l}`,color:u},...a?[{text:` [sess ${K(a)}]`,color:"gray"}]:[]]}function dt(t){const e=ce(t.createdAt),s=Ur(t);let n=null;switch(t.eventType){case"assistant.usage":case"session.info":case"session.idle":case"session.usage_info":case"pending_messages.modified":case"pending_messages.cancelled":case"abort":case"assistant.turn_end":case"assistant.streaming_progress":return null;case"tool.execution_start":n=ts(e,t,"start");break;case"tool.execution_complete":n=ts(e,t,"complete");break;case"tool.execution_partial_result":n=ts(e,t,"partial");break;case"tool.execution_progress":{const i=(t?.data??{})||{},o=i.toolName||i.name||"tool",r=typeof i.message=="string"&&i.message?i.message:typeof i.detail=="string"&&i.detail?i.detail:i.percent!=null?`${Math.round(Number(i.percent))}%`:"running…";n=z(e,"[tool]","cyan",`${o} ${r}`,"white");break}case"assistant.reasoning":n=z(e,"[reasoning]","gray",s||"…","white");break;case"assistant.intent":{const i=(t?.data??{})||{},o=typeof i.summary=="string"&&i.summary?i.summary:typeof i.intent=="string"&&i.intent?i.intent:s||"";n=z(e,"[intent]","gray",o||"…","white");break}case"assistant.turn_start":n=z(e,"[turn start]","gray",s);break;case"session.turn_completed":n=z(e,"[turn completed]","gray",t?.data?.iteration!=null?`iter ${t.data.iteration}`:s);break;case"session.lossy_handoff":n=z(e,"[lossy handoff]","yellow",Dr(t,s)||"handoff to a new worker");break;case"session.dehydrated":n=z(e,"[dehydrated]","cyan",Br(t,s));break;case"session.hydrated":case"session.rehydrated":n=z(e,"[rehydrated]","green",s);break;case"session.wait_started":{const i=t?.data?.seconds!=null?`${t.data.seconds}s`:"?",o=typeof t?.data?.reason=="string"&&t.data.reason?` reason=${JSON.stringify(t.data.reason)}`:"",r=t?.data?.preserveAffinity?" preserve=true":"";n=z(e,"[wait]","yellow",`${i}${r}${o}`.trim());break}case"session.input_required_started":n=z(e,"[input]","yellow",s);break;case"session.agent_spawned":n=z(e,"[spawn]","cyan",t?.data?.agentId||K(t?.data?.childSessionId),"white");break;case"session.cron_started":n=z(e,"[cron]","magenta",`started${t?.data?.seconds!=null?` ${t.data.seconds}s`:""}${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_at_scheduled":case"session.cron_at_started":n=z(e,"[cron]","magenta",`scheduled${t?.data?.nextFireAt?` ${vn(t.data.nextFireAt)}`:""}${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_fired":n=z(e,"[cron]","magenta",`fired${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_at_fired":n=z(e,"[cron]","magenta",`fired${t?.data?.scheduledAt?` ${vn(t.data.scheduledAt)}`:""}${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_cancelled":case"session.cron_at_cancelled":n=z(e,"[cron]","magenta",`cancelled${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_at_completed":n=z(e,"[cron]","magenta",`completed${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.command_received":n=z(e,"[command]","magenta",`/${t?.data?.cmd||"?"}${s?` ${s}`:""}`);break;case"session.command_completed":n=z(e,"[command]","magenta",`/${t?.data?.cmd||"?"} ok${s?` ${s}`:""}`);break;case"session.compaction_start":case"session.compaction_complete":n=ar(e,t.eventType,t.data||{});break;case"session.error":n=z(e,"[error]","red",s||"session error","white");break;case"system.message":Hs(Qe(t))?n=z(e,"[rehydrated]","green",Hr(t,s)||"conversation preserved"):n=z(e,"[system]","gray",s||"system message");break;default:n=[...Us(e),{text:`[${t.eventType}]`,color:"gray"},...s?[{text:` ${s}`,color:"white"}]:[]];break}return{id:`${t.sessionId}:${t.seq}`,eventType:t.eventType,time:e,seq:Number.isFinite(Number(t?.seq))?Number(t.seq):0,createdAt:t?.createdAt instanceof Date?t.createdAt.getTime():t?.createdAt?new Date(t.createdAt).getTime():0,text:Lr(n),line:n}}function Wr(t=V){const e=Math.max(V,Number(t)||V);return Ar.find(n=>n>e)||Math.min(1e5,e*2)}function xt(t=[],e={}){const s=Math.max(V,Number(e.requestedLimit??e.eventLimit??V)||V),n=[],i=[],o=[];for(const r of t){if(o.push(r),r.eventType==="user.message"){i.push(...Lt(r,"user"));const l=Ke(r,"user");l&&n.push(l);continue}if(r.eventType==="assistant.message"){i.push(...Lt(r,"assistant"));const l=Ke(r,"assistant");l&&n.push(l);continue}if(r.eventType==="system.message"){if(Wi(r)){const l=dt(r);l&&i.push(l)}else{const l=Ke(r,"system");l&&n.push(l)}continue}const a=dt(r);a&&i.push(a)}return{chat:qe(n),activity:i,events:o.slice(-s),loadedEventLimit:s,loadedEventCount:o.length,hasOlderEvents:o.length>=s}}function Vr(t,e){const s=Array.isArray(t?.events)?t.events:[],n=Math.max(V,Number(t?.loadedEventLimit??V)||V),i=s.length>0&&s[s.length-1]?.seq===e?.seq?s:[...s,e].slice(-n),o={chat:xe(t?.chat||[],n),activity:xe(t?.activity||[],n),events:i,lastSeq:e.seq,loadedEventLimit:n,loadedEventCount:Math.max(Number(t?.loadedEventCount||0),i.length),hasOlderEvents:!!t?.hasOlderEvents};if(e.eventType==="user.message"){o.activity.push(...Lt(e,"user")),o.activity=xe(o.activity,n);const a=Ke(e,"user");return a&&(o.chat=_r(o.chat,a),o.chat.push(a),o.chat=xe(qe(o.chat),n)),o}if(e.eventType==="assistant.message"){o.activity.push(...Lt(e,"assistant")),o.activity=xe(o.activity,n);const a=Ke(e,"assistant");return a&&(o.chat.push(a),o.chat=xe(qe(o.chat),n)),o}if(e.eventType==="system.message"){if(Wi(e)){const a=dt(e);a&&(o.activity.push(a),o.activity=xe(o.activity,n))}else{const a=Ke(e,"system");if(!a)return o;o.chat.push(a),o.chat=xe(qe(o.chat),n)}return o}const r=dt(e);return r&&(o.activity.push(r),o.activity=xe(o.activity,n)),o}function ss(t,e=null){const s=typeof e?.splash=="string"&&e.splash.trim()?e.splash:t?.splash;return s?[{id:`splash:${e?.isSystem?St(e,t?.title||"PilotSwarm"):e?.title||t?.title||"PilotSwarm"}`,role:"system",text:`${s}
21
-
22
- {gray-fg}Start interacting with this session to replace the splash screen.{/gray-fg}`,time:"",splash:!0}]:[]}const qr=.7,Kr=30,An=36,ns=18,is=18,os=0,Vi=3,ft=6,Ws=10,zr=.25,Yr=.5,Nt=6,Es=10,Qr=.336,rs=Nt,as=Es,ls=ft,cs=Ws;function it(t,e,s){return Math.max(e,Math.min(s,t))}function Xr(t){return[w.SESSIONS,w.CHAT,w.INSPECTOR,w.ACTIVITY].includes(t)?t:null}function Jr(t={}){return{width:Math.max(40,Number(t.width)||120),height:Math.max(18,Number(t.height)||40)}}function ze(t=""){const e=String(t||"").split(`
23
- `).length;return it(e,1,Vi)}function Zr(t){return Math.max(ft,Math.floor(t*zr))}function ea(t,e){const s=Math.floor(Math.max(0,Number(t)||0)*Yr),n=Math.max(ft,e-Ws);return Math.max(ft,Math.min(n,s))}function lt(t,e=0,s=1,n=0,i=0,o=null){const r=Jr(t),a=r.width,l=r.height,p=it(Number(s)||1,1,Vi),u=Xr(o),d=5+p,f=Math.max(18,l-d),m=Math.floor(a*qr)+(Number(e)||0),g=a-m-os;let I=!1,y=!1;m<=ns&&g>is?I=!0:g<=is&&m>ns?y=!0:m<=ns&&g<=is&&(y=e>=0,I=!y);let x,E;I?(x=0,E=a):y?(x=a,E=0):(x=it(m,Kr,a-An-os),E=Math.max(An,a-x-os));const T=Zr(f)+(Number(n)||0),O=f-T;let M=!1,k=!1;O<=cs&&T>ls?k=!0:T<=ls&&O>cs?M=!0:O<=cs&&T<=ls&&(k=(Number(n)||0)>=0,M=!k);let N,L;if(M)N=0,L=f;else if(k)N=f,L=0;else{const se=ea(l,f);N=it(T,ft,se),L=Math.max(Ws,f-N)}const _=Math.max(Nt,Math.floor(f*Qr))+(Number(i)||0),W=f-_;let U=!1,ee=!1;W<=as&&_>rs?U=!0:_<=rs&&W>as?ee=!0:W<=as&&_<=rs&&(U=(Number(i)||0)>=0,ee=!U);let J,D;return U?(J=f,D=0):ee?(D=f,J=0):(J=it(_,Nt,Math.max(Nt,f-Es)),D=Math.max(Es,f-J)),{viewport:r,totalWidth:a,totalHeight:l,reservedRows:d,bodyHeight:f,promptRows:p,fullscreenPane:u,paneAdjust:Number(e)||0,sessionPaneAdjust:Number(n)||0,activityPaneAdjust:Number(i)||0,leftHidden:I,rightHidden:y,inspectorHidden:U,activityHidden:ee,sessionHidden:M,chatHidden:k,leftWidth:x,rightWidth:E,sessionPaneHeight:N,chatPaneHeight:L,activityPaneHeight:J,inspectorPaneHeight:D}}function vs(t){if(t?.fullscreenPane)return[t.fullscreenPane,w.PROMPT];if(t?.leftHidden)return[w.INSPECTOR,w.ACTIVITY,w.PROMPT];if(t?.rightHidden)return[...t?.sessionHidden?[w.CHAT]:t?.chatHidden?[w.SESSIONS]:[w.SESSIONS,w.CHAT],w.PROMPT];if(t?.sessionHidden){const e=t?.inspectorHidden?[w.ACTIVITY]:t?.activityHidden?[w.INSPECTOR]:[w.INSPECTOR,w.ACTIVITY];return[w.CHAT,...e,w.PROMPT]}if(t?.chatHidden){const e=t?.inspectorHidden?[w.ACTIVITY]:t?.activityHidden?[w.INSPECTOR]:[w.INSPECTOR,w.ACTIVITY];return[w.SESSIONS,...e,w.PROMPT]}return t?.inspectorHidden?[w.SESSIONS,w.CHAT,w.ACTIVITY,w.PROMPT]:t?.activityHidden?[w.SESSIONS,w.CHAT,w.INSPECTOR,w.PROMPT]:[w.SESSIONS,w.CHAT,w.INSPECTOR,w.ACTIVITY,w.PROMPT]}function Ee(t,e){const s=vs(e);return s.includes(t)?t:s[0]||w.PROMPT}function ta(t,e){return e?.fullscreenPane?e.fullscreenPane:e?.leftHidden?{[w.PROMPT]:w.PROMPT,[w.ACTIVITY]:w.INSPECTOR,[w.INSPECTOR]:w.INSPECTOR}[t]||w.INSPECTOR:e?.rightHidden?{[w.PROMPT]:w.PROMPT,[w.CHAT]:e?.sessionHidden?w.CHAT:w.SESSIONS,[w.SESSIONS]:w.SESSIONS}[t]||(e?.sessionHidden?w.CHAT:w.SESSIONS):{[w.PROMPT]:e?.sessionHidden?w.CHAT:w.SESSIONS,[w.ACTIVITY]:e?.chatHidden?w.SESSIONS:w.CHAT,[w.INSPECTOR]:e?.chatHidden?w.SESSIONS:w.CHAT,[w.CHAT]:e?.sessionHidden?w.CHAT:w.SESSIONS,[w.SESSIONS]:w.SESSIONS}[t]||(e?.sessionHidden?w.CHAT:w.SESSIONS)}function sa(t,e){return e?.fullscreenPane?e.fullscreenPane:e?.leftHidden?{[w.PROMPT]:w.PROMPT,[w.INSPECTOR]:w.ACTIVITY,[w.ACTIVITY]:w.ACTIVITY}[t]||w.INSPECTOR:e?.rightHidden?{[w.PROMPT]:w.PROMPT,[w.SESSIONS]:e?.chatHidden?w.SESSIONS:w.CHAT,[w.CHAT]:w.CHAT}[t]||(e?.chatHidden?w.SESSIONS:w.CHAT):e?.inspectorHidden?{[w.PROMPT]:w.PROMPT,[w.SESSIONS]:w.CHAT,[w.CHAT]:w.ACTIVITY,[w.ACTIVITY]:w.ACTIVITY}[t]||w.CHAT:e?.activityHidden?{[w.PROMPT]:w.PROMPT,[w.SESSIONS]:w.CHAT,[w.CHAT]:w.INSPECTOR,[w.INSPECTOR]:w.INSPECTOR}[t]||w.CHAT:{[w.PROMPT]:w.PROMPT,[w.SESSIONS]:w.CHAT,[w.CHAT]:w.INSPECTOR,[w.INSPECTOR]:w.ACTIVITY,[w.ACTIVITY]:w.ACTIVITY}[t]||w.CHAT}function Tn(t){return t?.isSystem?Hi(t):Number.MAX_SAFE_INTEGER}function na(t=[]){const e=new Map;for(let s=0;s<t.length;s+=1){const n=t[s]?.sessionId;!n||e.has(n)||e.set(n,s)}return e}function ia(t=[]){if(t instanceof Map)return new Map(t);if(Array.isArray(t))return na(t);const e=new Map;for(const[s,n]of Object.entries(t||{}))!s||typeof n!="number"||Number.isNaN(n)||e.set(s,n);return e}function oa(t){return!!(t&&!t.isSystem&&(t.isGroup||!t.parentSessionId&&!t.groupId))}function kn(t,e){return!!(oa(t)&&e&&e.has(t.sessionId))}function Mn(t,e){return t.isSystem?0:t.isGroup&&kn(t,e)?1:kn(t,e)?2:t.isGroup?3:4}function Pn(t){const e=t?.updatedAt??t?.summaryUpdatedAt??t?.latestSummaryUpdatedAt,s=typeof e=="number"?e:Date.parse(e||"");return Number.isFinite(s)?s:0}function Nn(t,e,s,n){const i=Mn(t,n),o=Mn(e,n);if(i!==o)return i-o;const r=Tn(t),a=Tn(e);if(r!==a)return r-a;const l=s.get(t.sessionId),p=s.get(e.sessionId);if(typeof l=="number"&&typeof p=="number"&&l!==p)return l-p;const u=Pn(t),d=Pn(e);if(u>0&&d>0&&u!==d)return d-u;const f=(e.createdAt||0)-(t.createdAt||0);if(f!==0)return f;const h=String(t.title||""),m=String(e.title||""),g=h.localeCompare(m);return g!==0?g:String(t.sessionId||"").localeCompare(String(e.sessionId||""))}function Pe(t=[],e=new Set,s=[],n=null){const i=new Map,o=new Map,r=ia(s),a=n instanceof Set?n:new Set(Array.isArray(n)?n:[]);for(const d of t)i.set(d.sessionId,d);for(const d of t){const f=!d.isGroup&&d.groupId&&!d.parentSessionId&&i.has(`group:${d.groupId}`)?`group:${d.groupId}`:null,h=d.parentSessionId||f;!h||!i.has(h)||(o.has(h)||o.set(h,[]),o.get(h).push(d))}for(const d of o.values())d.sort((f,h)=>Nn(f,h,r,a));const l=t.filter(d=>!(d.parentSessionId&&i.has(d.parentSessionId)||!d.isGroup&&d.groupId&&!d.parentSessionId&&i.has(`group:${d.groupId}`))).sort((d,f)=>Nn(d,f,r,a)),p=[];function u(d,f){const h=o.get(d.sessionId)||[];if(p.push({sessionId:d.sessionId,depth:f,hasChildren:h.length>0,collapsed:e.has(d.sessionId)}),!e.has(d.sessionId))for(const m of h)u(m,f+1)}for(const d of l)u(d,0);return p}function ra(t){return Object.freeze({...t,page:Object.freeze({...t.page||{}}),terminal:Object.freeze({...t.terminal||{}}),tui:Object.freeze({...t.tui||{}})})}function Z({id:t,label:e,description:s,page:n,terminal:i,tui:o={}}){const r={background:n?.background||i?.background||"#000000",surface:i?.background||n?.background||"#000000",foreground:i?.foreground||n?.foreground||"#ffffff",white:i?.foreground||n?.foreground||"#ffffff",gray:n?.hintColor||i?.brightBlack||i?.white||"#999999",black:i?.black||"#000000",red:i?.red||"#ff5555",green:i?.green||"#55ff55",yellow:i?.yellow||"#ffff55",blue:i?.blue||"#5555ff",magenta:i?.magenta||"#ff55ff",cyan:i?.cyan||"#55ffff",userChat:"#ffd866",userChatLabel:"#ffec99",activeHighlightBackground:i?.blue||"#5555ff",activeHighlightForeground:i?.background||"#000000",selectionBackground:i?.cursor||i?.blue||"#5555ff",selectionForeground:i?.cursorAccent||i?.background||"#000000",promptCursorBackground:i?.cursor||i?.green||"#55ff55",promptCursorForeground:i?.cursorAccent||i?.background||"#000000"};return ra({id:t,label:e,description:s,page:n,terminal:i,tui:{...r,...o}})}const aa=Z({id:"github-dark",label:"GitHub Dark",description:"GitHub dark palette with soft blue accents and cool neutrals.",page:{background:"#0d1117",foreground:"#e6edf3",overlayBackground:"#0d1117",overlayForeground:"#e6edf3",hintColor:"#8b949e",modalBackdrop:"rgba(1, 4, 9, 0.64)",modalBackground:"#161b22",modalBorder:"#30363d",modalForeground:"#e6edf3",modalMuted:"#8b949e",modalSelectedBackground:"#1f6feb33",modalSelectedBorder:"#2f81f7",modalSelectedForeground:"#79c0ff"},terminal:{background:"#0d1117",foreground:"#e6edf3",cursor:"#2f81f7",cursorAccent:"#0d1117",selectionBackground:"rgba(56, 139, 253, 0.28)",black:"#484f58",red:"#ff7b72",green:"#3fb950",yellow:"#d29922",blue:"#58a6ff",magenta:"#bc8cff",cyan:"#39c5cf",white:"#b1bac4",brightBlack:"#6e7681",brightRed:"#ffa198",brightGreen:"#56d364",brightYellow:"#e3b341",brightBlue:"#79c0ff",brightMagenta:"#d2a8ff",brightCyan:"#56d4dd",brightWhite:"#f0f6fc"},tui:{surface:"#0d1117",activeHighlightBackground:"#1f4b7a",activeHighlightForeground:"#f0f6fc",selectionBackground:"#79c0ff",selectionForeground:"#0d1117",promptCursorBackground:"#2f81f7",promptCursorForeground:"#0d1117"}}),la=Z({id:"github-light",label:"GitHub Light",description:"GitHub light palette with crisp neutrals, blue actions, and high-contrast status colors.",page:{background:"#ffffff",foreground:"#1f2328",overlayBackground:"#ffffff",overlayForeground:"#1f2328",hintColor:"#57606a",modalBackdrop:"rgba(31, 35, 40, 0.34)",modalBackground:"#ffffff",modalBorder:"#d0d7de",modalForeground:"#1f2328",modalMuted:"#57606a",modalSelectedBackground:"#ddf4ff",modalSelectedBorder:"#0969da",modalSelectedForeground:"#0550ae"},terminal:{background:"#ffffff",foreground:"#1f2328",cursor:"#0969da",cursorAccent:"#ffffff",selectionBackground:"#ddf4ff",black:"#24292f",red:"#cf222e",green:"#1a7f37",yellow:"#9a6700",blue:"#0969da",magenta:"#8250df",cyan:"#1b7c83",white:"#6e7781",brightBlack:"#57606a",brightRed:"#a40e26",brightGreen:"#116329",brightYellow:"#7d4e00",brightBlue:"#0550ae",brightMagenta:"#6639ba",brightCyan:"#0f6f78",brightWhite:"#1f2328"},tui:{surface:"#ffffff",border:"#d0d7de",userChat:"#0969da",userChatLabel:"#0550ae",activeHighlightBackground:"#ddf4ff",activeHighlightForeground:"#0550ae",selectionBackground:"#0969da",selectionForeground:"#ffffff",promptCursorBackground:"#0969da",promptCursorForeground:"#ffffff"}}),ca=Z({id:"daylight",label:"Daylight",description:"Crisp white workspace with near-black text and deep saturated accents — every color slot holds AA contrast.",page:{background:"#ffffff",foreground:"#111827",overlayBackground:"#ffffff",overlayForeground:"#111827",hintColor:"#4b5563",modalBackdrop:"rgba(17, 24, 39, 0.35)",modalBackground:"#ffffff",modalBorder:"#d1d5db",modalForeground:"#111827",modalMuted:"#4b5563",modalSelectedBackground:"#dbeafe",modalSelectedBorder:"#1d4ed8",modalSelectedForeground:"#1e3a8a"},terminal:{background:"#ffffff",foreground:"#111827",cursor:"#1d4ed8",cursorAccent:"#ffffff",selectionBackground:"#bfdbfe",black:"#111827",red:"#b91c1c",green:"#047857",yellow:"#92400e",blue:"#1d4ed8",magenta:"#6d28d9",cyan:"#0e7490",white:"#4b5563",brightBlack:"#374151",brightRed:"#991b1b",brightGreen:"#065f46",brightYellow:"#78350f",brightBlue:"#1e40af",brightMagenta:"#5b21b6",brightCyan:"#155e75",brightWhite:"#111827"},tui:{surface:"#ffffff",border:"#d1d5db",userChat:"#1e40af",userChatLabel:"#1e3a8a",activeHighlightBackground:"#dbeafe",activeHighlightForeground:"#1e3a8a",selectionBackground:"#1d4ed8",selectionForeground:"#ffffff",promptCursorBackground:"#1d4ed8",promptCursorForeground:"#ffffff"}}),ua=Z({id:"paper-ink",label:"Paper Ink",description:"Warm paper background with true-ink text and letterpress accents — warmth without washed-out output.",page:{background:"#faf6ef",foreground:"#1c1917",overlayBackground:"#fffdf8",overlayForeground:"#1c1917",hintColor:"#57534e",modalBackdrop:"rgba(28, 25, 23, 0.35)",modalBackground:"#fffdf8",modalBorder:"#d6cfc2",modalForeground:"#1c1917",modalMuted:"#57534e",modalSelectedBackground:"#f1e4c7",modalSelectedBorder:"#854d0e",modalSelectedForeground:"#713f12"},terminal:{background:"#faf6ef",foreground:"#1c1917",cursor:"#9f1239",cursorAccent:"#fffdf8",selectionBackground:"#f1e4c7",black:"#1c1917",red:"#9f1239",green:"#3f6212",yellow:"#854d0e",blue:"#1e40af",magenta:"#86198f",cyan:"#0f766e",white:"#57534e",brightBlack:"#44403c",brightRed:"#881337",brightGreen:"#365314",brightYellow:"#713f12",brightBlue:"#1e3a8a",brightMagenta:"#701a75",brightCyan:"#115e59",brightWhite:"#1c1917"},tui:{surface:"#fffdf8",border:"#d6cfc2",userChat:"#1e40af",userChatLabel:"#1e3a8a",activeHighlightBackground:"#f1e4c7",activeHighlightForeground:"#713f12",selectionBackground:"#854d0e",selectionForeground:"#fffdf8",promptCursorBackground:"#9f1239",promptCursorForeground:"#fffdf8"}}),da=Z({id:"light-high-contrast",label:"Light High Contrast",description:"Pure black on white with maximum-contrast accents — nothing washes out, ever.",page:{background:"#ffffff",foreground:"#000000",overlayBackground:"#ffffff",overlayForeground:"#000000",hintColor:"#333333",modalBackdrop:"rgba(0, 0, 0, 0.4)",modalBackground:"#ffffff",modalBorder:"#767676",modalForeground:"#000000",modalMuted:"#333333",modalSelectedBackground:"#cce5ff",modalSelectedBorder:"#0000cc",modalSelectedForeground:"#00008b"},terminal:{background:"#ffffff",foreground:"#000000",cursor:"#0000cc",cursorAccent:"#ffffff",selectionBackground:"#b3d7ff",black:"#000000",red:"#a80000",green:"#006400",yellow:"#5c4500",blue:"#0000cc",magenta:"#77008c",cyan:"#005f6b",white:"#333333",brightBlack:"#1a1a1a",brightRed:"#8b0000",brightGreen:"#004b00",brightYellow:"#4a3700",brightBlue:"#0000a0",brightMagenta:"#5f0070",brightCyan:"#004a54",brightWhite:"#000000"},tui:{surface:"#ffffff",border:"#767676",userChat:"#0000cc",userChatLabel:"#00008b",activeHighlightBackground:"#cce5ff",activeHighlightForeground:"#00008b",selectionBackground:"#0000cc",selectionForeground:"#ffffff",promptCursorBackground:"#0000cc",promptCursorForeground:"#ffffff"}}),fa=Z({id:"cobalt2",label:"Cobalt2",description:"Electric blue shell with bright yellow accents and saturated syntax colors.",page:{background:"#193549",foreground:"#ffffff",overlayBackground:"#193549",overlayForeground:"#ffffff",hintColor:"#a8c5e6",modalBackdrop:"rgba(7, 17, 28, 0.68)",modalBackground:"#224b68",modalBorder:"#2e6c99",modalForeground:"#ffffff",modalMuted:"#a8c5e6",modalSelectedBackground:"#ffc600",modalSelectedBorder:"#ffc600",modalSelectedForeground:"#193549"},terminal:{background:"#193549",foreground:"#ffffff",cursor:"#ffc600",cursorAccent:"#193549",selectionBackground:"rgba(255, 255, 255, 0.18)",black:"#000000",red:"#ff628c",green:"#3ad900",yellow:"#ff9d00",blue:"#0088ff",magenta:"#ff628c",cyan:"#80ffbb",white:"#ffffff",brightBlack:"#666666",brightRed:"#ff628c",brightGreen:"#3ad900",brightYellow:"#ff9d00",brightBlue:"#0088ff",brightMagenta:"#ff9d00",brightCyan:"#80ffbb",brightWhite:"#ffffff"},tui:{surface:"#193549",activeHighlightBackground:"#0f5f91",activeHighlightForeground:"#ffffff",selectionBackground:"#ffc600",selectionForeground:"#193549",promptCursorBackground:"#ffc600",promptCursorForeground:"#193549"}}),pa=Z({id:"dracula",label:"Dracula",description:"Classic Dracula contrast with neon green, pink, and violet accents.",page:{background:"#282a36",foreground:"#f8f8f2",overlayBackground:"#282a36",overlayForeground:"#f8f8f2",hintColor:"#bd93f9",modalBackdrop:"rgba(24, 25, 33, 0.72)",modalBackground:"#313442",modalBorder:"#6272a4",modalForeground:"#f8f8f2",modalMuted:"#bd93f9",modalSelectedBackground:"#44475a",modalSelectedBorder:"#bd93f9",modalSelectedForeground:"#f8f8f2"},terminal:{background:"#282a36",foreground:"#f8f8f2",cursor:"#f8f8f2",cursorAccent:"#282a36",selectionBackground:"rgba(189, 147, 249, 0.24)",black:"#21222c",red:"#ff5555",green:"#50fa7b",yellow:"#f1fa8c",blue:"#bd93f9",magenta:"#ff79c6",cyan:"#8be9fd",white:"#f8f8f2",brightBlack:"#6272a4",brightRed:"#ff6e6e",brightGreen:"#69ff94",brightYellow:"#ffffa5",brightBlue:"#d6acff",brightMagenta:"#ff92df",brightCyan:"#a4ffff",brightWhite:"#ffffff"},tui:{surface:"#282a36",activeHighlightBackground:"#44475a",activeHighlightForeground:"#f8f8f2",selectionBackground:"#bd93f9",selectionForeground:"#282a36",promptCursorBackground:"#f8f8f2",promptCursorForeground:"#282a36"}}),ha=Z({id:"catppuccin-mocha",label:"Catppuccin Mocha",description:"Creamy dark palette with soft pastels and high legibility.",page:{background:"#1e1e2e",foreground:"#cdd6f4",overlayBackground:"#1e1e2e",overlayForeground:"#cdd6f4",hintColor:"#bac2de",modalBackdrop:"rgba(17, 17, 27, 0.74)",modalBackground:"#313244",modalBorder:"#585b70",modalForeground:"#cdd6f4",modalMuted:"#bac2de",modalSelectedBackground:"#45475a",modalSelectedBorder:"#89b4fa",modalSelectedForeground:"#cdd6f4"},terminal:{background:"#1e1e2e",foreground:"#cdd6f4",cursor:"#f5e0dc",cursorAccent:"#1e1e2e",selectionBackground:"rgba(137, 180, 250, 0.22)",black:"#45475a",red:"#f38ba8",green:"#a6e3a1",yellow:"#f9e2af",blue:"#89b4fa",magenta:"#f5c2e7",cyan:"#94e2d5",white:"#bac2de",brightBlack:"#585b70",brightRed:"#f38ba8",brightGreen:"#a6e3a1",brightYellow:"#f9e2af",brightBlue:"#89b4fa",brightMagenta:"#f5c2e7",brightCyan:"#94e2d5",brightWhite:"#f5e0dc"},tui:{surface:"#1e1e2e",activeHighlightBackground:"#45475a",activeHighlightForeground:"#cdd6f4",selectionBackground:"#89b4fa",selectionForeground:"#1e1e2e",promptCursorBackground:"#f5e0dc",promptCursorForeground:"#1e1e2e"}}),ma=Z({id:"hacker-x-matrix",label:"Hacker X - Matrix",description:"Black-and-phosphor terminal palette with vivid green glow and CRT-style contrast.",page:{background:"#030603",foreground:"#c8ffc8",overlayBackground:"#030603",overlayForeground:"#c8ffc8",hintColor:"#59a659",modalBackdrop:"rgba(0, 6, 0, 0.82)",modalBackground:"#081208",modalBorder:"#1f5f1f",modalForeground:"#d6ffd6",modalMuted:"#6dbb6d",modalSelectedBackground:"#0f240f",modalSelectedBorder:"#39ff14",modalSelectedForeground:"#dfffdf"},terminal:{background:"#000000",foreground:"#c8ffc8",cursor:"#39ff14",cursorAccent:"#000000",selectionBackground:"rgba(57, 255, 20, 0.2)",black:"#031003",red:"#39ff14",green:"#2a7a22",yellow:"#4a8a30",blue:"#1a6a4a",magenta:"#2a7a3a",cyan:"#2a8a5a",white:"#b7f7b7",brightBlack:"#59a659",brightRed:"#9aff86",brightGreen:"#7dff66",brightYellow:"#e0ff8a",brightBlue:"#61ffc2",brightMagenta:"#b4ffb4",brightCyan:"#98ffe0",brightWhite:"#e8ffe8"},tui:{surface:"#030603",activeHighlightBackground:"#1a3a1a",activeHighlightForeground:"#e8ffe8",selectionBackground:"#39ff14",selectionForeground:"#000000",promptCursorBackground:"#39ff14",promptCursorForeground:"#000000"}}),ga=Z({id:"hacker-x-orion-prime",label:"Hacker X - Orion Prime",description:"Deep-space navy palette with electric cyan, violet, and amber accents.",page:{background:"#0a0f1e",foreground:"#e8f2ff",overlayBackground:"#0a0f1e",overlayForeground:"#e8f2ff",hintColor:"#7e90b5",modalBackdrop:"rgba(6, 10, 24, 0.76)",modalBackground:"#121a30",modalBorder:"#2d4a73",modalForeground:"#edf5ff",modalMuted:"#93a7cc",modalSelectedBackground:"#19365f",modalSelectedBorder:"#55c2ff",modalSelectedForeground:"#f3fbff"},terminal:{background:"#0a0f1e",foreground:"#e8f2ff",cursor:"#55c2ff",cursorAccent:"#0a0f1e",selectionBackground:"rgba(85, 194, 255, 0.22)",black:"#10182b",red:"#ff6b88",green:"#67f5c2",yellow:"#ffd36b",blue:"#55c2ff",magenta:"#c79bff",cyan:"#7ceeff",white:"#c3d4ef",brightBlack:"#7e90b5",brightRed:"#ff8aa2",brightGreen:"#8cffd8",brightYellow:"#ffe28f",brightBlue:"#8fdcff",brightMagenta:"#d8b6ff",brightCyan:"#a2f5ff",brightWhite:"#ffffff"},tui:{surface:"#0c1325",activeHighlightBackground:"#173052",activeHighlightForeground:"#f3fbff",selectionBackground:"#55c2ff",selectionForeground:"#0a0f1e",promptCursorBackground:"#55c2ff",promptCursorForeground:"#0a0f1e"}}),ya=Z({id:"tokyo-night",label:"Tokyo Night",description:"Deep blue-gray canvas with vivid neon accents inspired by Tokyo city lights.",page:{background:"#1a1b26",foreground:"#a9b1d6",overlayBackground:"#1a1b26",overlayForeground:"#a9b1d6",hintColor:"#737aa2",modalBackdrop:"rgba(26, 27, 38, 0.74)",modalBackground:"#24283b",modalBorder:"#414868",modalForeground:"#a9b1d6",modalMuted:"#737aa2",modalSelectedBackground:"#33467c",modalSelectedBorder:"#7aa2f7",modalSelectedForeground:"#c0caf5"},terminal:{background:"#1a1b26",foreground:"#a9b1d6",cursor:"#c0caf5",cursorAccent:"#1a1b26",selectionBackground:"rgba(122, 162, 247, 0.22)",black:"#414868",red:"#f7768e",green:"#9ece6a",yellow:"#e0af68",blue:"#7aa2f7",magenta:"#bb9af7",cyan:"#7dcfff",white:"#a9b1d6",brightBlack:"#565f89",brightRed:"#f7768e",brightGreen:"#9ece6a",brightYellow:"#e0af68",brightBlue:"#7aa2f7",brightMagenta:"#bb9af7",brightCyan:"#7dcfff",brightWhite:"#c0caf5"},tui:{surface:"#1a1b26",activeHighlightBackground:"#33467c",activeHighlightForeground:"#c0caf5",selectionBackground:"#7aa2f7",selectionForeground:"#1a1b26",promptCursorBackground:"#c0caf5",promptCursorForeground:"#1a1b26"}}),Sa=Z({id:"gruvbox-dark",label:"Gruvbox Dark",description:"Retro warm palette with earthy browns, oranges, and high readability.",page:{background:"#282828",foreground:"#ebdbb2",overlayBackground:"#282828",overlayForeground:"#ebdbb2",hintColor:"#a89984",modalBackdrop:"rgba(40, 40, 40, 0.74)",modalBackground:"#3c3836",modalBorder:"#504945",modalForeground:"#ebdbb2",modalMuted:"#a89984",modalSelectedBackground:"#504945",modalSelectedBorder:"#fabd2f",modalSelectedForeground:"#fbf1c7"},terminal:{background:"#282828",foreground:"#ebdbb2",cursor:"#ebdbb2",cursorAccent:"#282828",selectionBackground:"rgba(250, 189, 47, 0.22)",black:"#282828",red:"#cc241d",green:"#98971a",yellow:"#d79921",blue:"#458588",magenta:"#b16286",cyan:"#689d6a",white:"#a89984",brightBlack:"#928374",brightRed:"#fb4934",brightGreen:"#b8bb26",brightYellow:"#fabd2f",brightBlue:"#83a598",brightMagenta:"#d3869b",brightCyan:"#8ec07c",brightWhite:"#ebdbb2"},tui:{surface:"#282828",activeHighlightBackground:"#504945",activeHighlightForeground:"#fbf1c7",selectionBackground:"#fabd2f",selectionForeground:"#282828",promptCursorBackground:"#ebdbb2",promptCursorForeground:"#282828"}}),ba=Z({id:"noctis",label:"Noctis",description:"Dark cyan-tinted palette with warm and cold medium contrast accents.",page:{background:"#052529",foreground:"#b2cacd",overlayBackground:"#052529",overlayForeground:"#b2cacd",hintColor:"#40d4e7",modalBackdrop:"rgba(3, 25, 27, 0.72)",modalBackground:"#073940",modalBorder:"#0e6671",modalForeground:"#b2cacd",modalMuted:"#87a7ab",modalSelectedBackground:"#0b515b",modalSelectedBorder:"#40d4e7",modalSelectedForeground:"#ebfdff"},terminal:{background:"#03191b",foreground:"#b2cacd",cursor:"#85efff",cursorAccent:"#03191b",selectionBackground:"rgba(22, 159, 177, 0.27)",black:"#324a4d",red:"#e66533",green:"#49e9a6",yellow:"#e4b781",blue:"#49ace9",magenta:"#df769b",cyan:"#49d6e9",white:"#b2cacd",brightBlack:"#5e878c",brightRed:"#e97749",brightGreen:"#60ebb1",brightYellow:"#e69533",brightBlue:"#60b6eb",brightMagenta:"#e798b3",brightCyan:"#60dbeb",brightWhite:"#c1d4d7"},tui:{surface:"#03191b",activeHighlightBackground:"#083d44",activeHighlightForeground:"#ebfdff",selectionBackground:"#169fb1",selectionForeground:"#052529",promptCursorBackground:"#85efff",promptCursorForeground:"#03191b"}}),qi=Z({id:"noctis-obscuro",label:"Noctis Obscuro",description:"Deep obsidian palette with cool blue accents and restrained contrast for long sessions.",page:{background:"#0b1117",foreground:"#c7d1da",overlayBackground:"#0b1117",overlayForeground:"#c7d1da",hintColor:"#7cc6ff",modalBackdrop:"rgba(5, 9, 13, 0.74)",modalBackground:"#121a23",modalBorder:"#28455b",modalForeground:"#d7e2eb",modalMuted:"#8f9dab",modalSelectedBackground:"#173041",modalSelectedBorder:"#7cc6ff",modalSelectedForeground:"#eef6ff"},terminal:{background:"#060b10",foreground:"#c7d1da",cursor:"#9fd4ff",cursorAccent:"#060b10",selectionBackground:"rgba(72, 125, 170, 0.30)",black:"#2a3138",red:"#ef6b73",green:"#7ddc8f",yellow:"#d9b36c",blue:"#68aee8",magenta:"#b28cff",cyan:"#58c9d4",white:"#c7d1da",brightBlack:"#6e7a86",brightRed:"#f28a92",brightGreen:"#97e5a6",brightYellow:"#e4c28b",brightBlue:"#86c1f1",brightMagenta:"#c6a7ff",brightCyan:"#7ad7df",brightWhite:"#e5edf5"},tui:{surface:"#060b10",activeHighlightBackground:"#123142",activeHighlightForeground:"#eef6ff",selectionBackground:"#4a7baa",selectionForeground:"#0b1117",promptCursorBackground:"#9fd4ff",promptCursorForeground:"#060b10"}}),wa=Z({id:"dark-high-contrast",label:"Dark High Contrast",description:"Pure black background with maximum contrast ANSI colors for accessibility.",page:{background:"#000000",foreground:"#ffffff",overlayBackground:"#000000",overlayForeground:"#ffffff",hintColor:"#3794ff",modalBackdrop:"rgba(0, 0, 0, 0.85)",modalBackground:"#0c0c0c",modalBorder:"#6fc3df",modalForeground:"#ffffff",modalMuted:"#9d9d9d",modalSelectedBackground:"#0f4a85",modalSelectedBorder:"#f38518",modalSelectedForeground:"#ffffff"},terminal:{background:"#000000",foreground:"#ffffff",cursor:"#ffffff",cursorAccent:"#000000",selectionBackground:"rgba(255, 255, 255, 0.3)",black:"#000000",red:"#f44747",green:"#73c991",yellow:"#e5e510",blue:"#3794ff",magenta:"#bc3fbc",cyan:"#29b8db",white:"#e5e5e5",brightBlack:"#666666",brightRed:"#f14c4c",brightGreen:"#89d185",brightYellow:"#f5f543",brightBlue:"#6fc3df",brightMagenta:"#d670d6",brightCyan:"#2ee2e2",brightWhite:"#ffffff"},tui:{surface:"#000000",activeHighlightBackground:"#0f4a85",activeHighlightForeground:"#ffffff",selectionBackground:"#f38518",selectionForeground:"#000000",promptCursorBackground:"#ffffff",promptCursorForeground:"#000000"}}),Ia=Z({id:"terminal-green",label:"Terminal Green",description:"Classic black terminal with phosphor green text, amber warnings, and crisp operator contrast.",page:{background:"#020503",foreground:"#c9f7d3",overlayBackground:"#020503",overlayForeground:"#d9ffe0",hintColor:"#7ee787",modalBackdrop:"rgba(0, 6, 2, 0.82)",modalBackground:"#061109",modalBorder:"#245c33",modalForeground:"#d9ffe0",modalMuted:"#83a98c",modalSelectedBackground:"#0b2a14",modalSelectedBorder:"#63e27a",modalSelectedForeground:"#ecfff0"},terminal:{background:"#020503",foreground:"#c9f7d3",cursor:"#8cff9f",cursorAccent:"#020503",selectionBackground:"#174923",black:"#061109",red:"#ff5f5f",green:"#63e27a",yellow:"#d6b95f",blue:"#5aa7ff",magenta:"#c586ff",cyan:"#5ce1d8",white:"#c9f7d3",brightBlack:"#5b7a61",brightRed:"#ff7f7f",brightGreen:"#8cff9f",brightYellow:"#f0d982",brightBlue:"#82bdff",brightMagenta:"#d9a8ff",brightCyan:"#89f4ee",brightWhite:"#effff1"},tui:{surface:"#020503",border:"#245c33",userChat:"#f0d982",userChatLabel:"#fff0a8",activeHighlightBackground:"#0b2a14",activeHighlightForeground:"#ecfff0",selectionBackground:"#63e27a",selectionForeground:"#020503",promptCursorBackground:"#8cff9f",promptCursorForeground:"#020503"}}),xa=Z({id:"solarized-ops",label:"Solarized Ops",description:"Solarized-inspired operations palette with deep blue-green surfaces and balanced long-session contrast.",page:{background:"#002b36",foreground:"#d7e2d0",overlayBackground:"#073642",overlayForeground:"#e5efe4",hintColor:"#93a1a1",modalBackdrop:"rgba(0, 20, 25, 0.74)",modalBackground:"#073642",modalBorder:"#2f5d67",modalForeground:"#e5efe4",modalMuted:"#93a1a1",modalSelectedBackground:"#164b56",modalSelectedBorder:"#2aa198",modalSelectedForeground:"#fdf6e3"},terminal:{background:"#002b36",foreground:"#d7e2d0",cursor:"#2aa198",cursorAccent:"#002b36",selectionBackground:"#164b56",black:"#073642",red:"#dc322f",green:"#859900",yellow:"#b58900",blue:"#268bd2",magenta:"#6c71c4",cyan:"#2aa198",white:"#eee8d5",brightBlack:"#586e75",brightRed:"#cb4b16",brightGreen:"#93a100",brightYellow:"#c79b00",brightBlue:"#3aa0e6",brightMagenta:"#7b80d6",brightCyan:"#36b5ac",brightWhite:"#fdf6e3"},tui:{surface:"#073642",border:"#2f5d67",userChat:"#b58900",userChatLabel:"#f0d47a",activeHighlightBackground:"#164b56",activeHighlightForeground:"#fdf6e3",selectionBackground:"#268bd2",selectionForeground:"#002b36",promptCursorBackground:"#2aa198",promptCursorForeground:"#002b36"}}),Ea=Z({id:"high-contrast-mono",label:"High Contrast Mono",description:"Accessibility-first monochrome theme with cobalt selection and severity colors only where they matter.",page:{background:"#000000",foreground:"#f8f8f2",overlayBackground:"#050505",overlayForeground:"#ffffff",hintColor:"#b8b8b8",modalBackdrop:"rgba(0, 0, 0, 0.88)",modalBackground:"#050505",modalBorder:"#d8d8d8",modalForeground:"#ffffff",modalMuted:"#b8b8b8",modalSelectedBackground:"#003f88",modalSelectedBorder:"#ffffff",modalSelectedForeground:"#ffffff"},terminal:{background:"#000000",foreground:"#f8f8f2",cursor:"#ffffff",cursorAccent:"#000000",selectionBackground:"#003f88",black:"#000000",red:"#ff4d4d",green:"#00d084",yellow:"#ffd84d",blue:"#4da3ff",magenta:"#d8d8d8",cyan:"#ffffff",white:"#f8f8f2",brightBlack:"#8a8a8a",brightRed:"#ff6b6b",brightGreen:"#28e29a",brightYellow:"#ffe173",brightBlue:"#73b8ff",brightMagenta:"#ffffff",brightCyan:"#ffffff",brightWhite:"#ffffff"},tui:{surface:"#000000",border:"#d8d8d8",userChat:"#ffffff",userChatLabel:"#d8d8d8",activeHighlightBackground:"#003f88",activeHighlightForeground:"#ffffff",selectionBackground:"#ffffff",selectionForeground:"#000000",promptCursorBackground:"#ffffff",promptCursorForeground:"#000000"}}),Ki=Object.freeze([pa,aa,la,ca,ua,da,fa,ga,ma,ha,ya,Sa,ba,qi,wa,Ia,xa,Ea].sort((t,e)=>t.label.localeCompare(e.label,void 0,{sensitivity:"base"}))),va=new Map(Ki.map(t=>[t.id,t])),Ca=qi.id;function Aa(){return Ki}function Ae(t){return t?va.get(t)??null:null}const Ta=new Set(["agent","user","system"]);function $t(t){const e=Array.isArray(t?.ownerKeys)?[...new Set(t.ownerKeys.map(n=>String(n||"").trim()).filter(Boolean))]:[];return{all:t&&typeof t=="object"?t?.all===!0:!0,includeSystem:t?.includeSystem===!0,includeUnowned:t?.includeUnowned===!0,includeMe:t?.includeMe===!0,ownerKeys:e}}function ka(t){if(typeof t=="string"){const i=t.trim();return i?{filename:i,sizeBytes:null,contentType:"",isBinary:!1,uploadedAt:"",source:"agent"}:null}if(!t||typeof t!="object")return null;const e=String(t.filename||"").trim();if(!e)return null;const s=Number(t.sizeBytes),n=typeof t.contentType=="string"?t.contentType:"";return{filename:e,sizeBytes:Number.isFinite(s)&&s>=0?s:null,contentType:n,isBinary:t.isBinary===!0,uploadedAt:typeof t.uploadedAt=="string"?t.uploadedAt:"",source:Ta.has(t.source)?t.source:"agent"}}function Bt(t){const e=Array.isArray(t)?t:[],s=[],n=new Set;for(const i of e){const o=ka(i);!o||n.has(o.filename)||(n.add(o.filename),s.push(o))}return s}function Ma(t,e){const s=String(e||"").trim();return s&&Bt(t).find(n=>n.filename===s)||null}function Vs(t){const e=t&&typeof t=="object"?t:{},s=Number(e.paneAdjust),n=Number(e.sessionPaneAdjust),i=Number(e.portalSessionColumnAdjust),o=Number(e.activityPaneAdjust);return{paneAdjust:Number.isFinite(s)?Math.trunc(s):0,sessionPaneAdjust:Number.isFinite(n)?Math.trunc(n):0,portalSessionColumnAdjust:Number.isFinite(i)?Math.trunc(i):0,activityPaneAdjust:Number.isFinite(o)?Math.trunc(o):0}}function Dt(t){if(!Array.isArray(t))return[];const e=new Set,s=[];for(const n of t){const i=String(n||"").trim();!i||e.has(i)||(e.add(i),s.push(i))}return s}function Cs(t){if(!Array.isArray(t))return new Set;const e=new Set;for(const s of t){const n=String(s||"").trim();n&&e.add(n)}return e}function zi(t){if(t==null)return null;const e=String(t).trim();return e||null}function Pa({mode:t="local",branding:e=null,themeId:s=null,chatViewMode:n=null,sessionOwnerFilter:i=null,layoutAdjustments:o=null,pinnedSessionIds:r=null,collapsedSessionIds:a=null,activeSessionId:l=null}={}){const p=i!=null,u=a!=null,d=Vs(o);return{branding:e||{title:"PilotSwarm",splash:"{bold}{cyan-fg}PilotSwarm{/cyan-fg}{/bold}"},auth:{principal:null,authorization:null},ui:{focusRegion:w.SESSIONS,inspectorTab:ge[0],chatViewMode:n==="summary"?"summary":"transcript",statsViewMode:"session",prompt:"",promptCursor:0,promptRows:1,promptAttachments:[],promptEdit:null,statusText:"Starting PilotSwarm...",themeId:Ae(s)?.id||Ca,modal:null,fullscreenPane:null,layout:{...d,viewportWidth:120,viewportHeight:40},scroll:{chat:0,inspector:0,activity:0,filePreview:0},followBottom:{inspector:!0,activity:!0}},connection:{mode:t,connected:!1,workersOnline:null,error:null},sessions:{byId:{},flat:[],activeSessionId:zi(l),collapsedIds:Cs(a),collapsedIdsExplicit:u,pinnedIds:Dt(r),selectedIds:[],selectMode:!1,orderById:{},nextOrderOrdinal:0,filterQuery:"",ownerFilterExplicit:p,ownerFilter:$t(i)},history:{bySessionId:new Map},outbox:{bySessionId:{}},orchestration:{bySessionId:{}},executionHistory:{bySessionId:{},format:"pretty"},files:{bySessionId:{},fullscreen:!1,selectedArtifactId:null,filter:{scope:"selectedSession",query:""}},logs:{available:!1,availabilityReason:"Log tailing disabled: no K8S_CONTEXT configured in the env file.",tailing:!1,entries:[],filter:{source:"allNodes",level:"all",format:"pretty"}},sessionStats:{bySessionId:{}},fleetStats:{loading:!1,data:null,userStats:null,fetchedAt:0},admin:{visible:!1,loading:!1,loadError:null,profile:null,ghcpKey:{editing:!1,draft:"",cursorIndex:0,saving:!1,error:null,lastSavedAt:0}}}}function Yi(t){const e=String(t||"");return/\bConnection is closed\b/i.test(e)||/\bLive Copilot connection lost\b/i.test(e)}function Na(t,e){return!(!Yi(t?.error)||e?.error!==void 0||String(e?.status||"")!=="running"||["Completed","Failed","Terminated"].includes(String(e?.orchestrationStatus||"")))}const Qi="activeHighlightBackground",qs="activeHighlightForeground",us="userChat",Oa="userChatLabel",On=new WeakMap,Rn=new WeakMap;function Ra(t){return t||qs}function Xi(t,{preserveColors:e=!1}={}){return(t||[]).map(s=>({...s,color:e?Ra(s?.color):qs,backgroundColor:Qi,bold:s?.bold??!0}))}function Te(t,{color:e=qs,bold:s=!0}={}){return{text:t,color:e,backgroundColor:Qi,bold:s}}function Se(t,e){return[{text:String(t||""),color:e,bold:!0}]}const Fa=72;function Ji(t){const e=Number(t)||0;return e>0&&e<=Fa}function Ks(t){if(!t)return"unknown";const e=t.status||"unknown";return t.cronActive===!0&&(e==="waiting"||e==="idle"||e==="unknown")?"cron_waiting":e}function _a(t){const e=Ks(t);return!e||e==="unknown"?"":e==="cron_waiting"?"waiting":e}function La(t){const e=Zi(t);return!e||e==="unknown"?"":e==="cron_waiting"?"waiting":e}function Zi(t){return t?.rowVisualStatus||Ks(t)}function eo(t){return t==="Completed"||t==="Failed"||t==="Terminated"}function zs(t){const e=Ks(t);return t?.orchestrationStatus==="Failed"||e==="failed"?"failed":e==="error"||e==="running"&&Yi(t?.error)&&!eo(t?.orchestrationStatus)?"warning":null}function to(t,e="local"){const s=zs(t);if(s)return s;const n=Zi(t);if(e==="remote"&&eo(t?.orchestrationStatus)&&n!=="cron_waiting"&&n!=="waiting"&&n!=="input_required"){if(t?.orchestrationStatus==="Completed")return"completed";if(t?.orchestrationStatus==="Terminated")return"terminated"}return n==="terminated"?"terminated":n}function pt(t,e="local"){switch(to(t,e)){case"running":return"green";case"cron_waiting":return"yellow";case"waiting":return"yellow";case"input_required":return"cyan";case"cancelled":return"gray";case"warning":return"yellow";case"failed":return"red";case"terminated":return"gray";case"completed":return"gray";case"idle":return"white";default:return"white"}}function so(t,e="local"){switch(to(t,e)){case"running":return"*";case"cron_waiting":return"~";case"waiting":return"~";case"input_required":return"?";case"cancelled":return"x";case"warning":return"!";case"failed":case"terminated":return"x";case"idle":return"";default:return""}}function Ht(t){const e=String(t?.provider||"").trim(),s=String(t?.subject||"").trim();return e&&s?`${e}${s}`:null}function Ys(t,e="unknown user"){return String(t?.displayName||t?.email||"").trim()||e}function Fn(t){const e=String(t||"").trim();if(!e)return"";const s=e.replace(/@.*/u,"").split(/[^A-Za-z0-9]+/u).map(i=>i.trim()).filter(Boolean);return s.length>=2?`${s[0][0]}${s[1][0]}`.toLowerCase():(s[0]||e).replace(/[^A-Za-z0-9]/gu,"").slice(0,2).toLowerCase()}function $a(t){return Fn(t?.displayName)||Fn(t?.email)||"?"}function Ba(t){return!!(t.auth?.principal||t.sessions?.ownerFilter&&t.sessions.ownerFilter.all!==!0||Object.values(t.sessions?.byId||{}).some(e=>e?.owner))}function Da(t,e,s=!1){const n=Js(t,e);return!s||t?.isSystem?n:`(${t?.owner?$a(t.owner):"?"}) ${n}`}function no(t,e={}){return!t?.isGroup||!t?.groupId?[]:Object.values(e||{}).filter(s=>s&&!s.isGroup&&!s.parentSessionId&&s.groupId===t.groupId)}function Qs(t,e={}){if(!t?.isGroup)return t?.owner??null;if(t.owner)return t.owner;const s=new Map;for(const n of no(t,e)){const i=Ht(n?.owner);i&&!s.has(i)&&s.set(i,n.owner)}return s.size===1?s.values().next().value:null}function _n(t){return String(t||"").toLowerCase().replace(/[^a-z0-9]+/gu,"")}function Ln(t,e){const s=_n(t),n=_n(e?.agentId);return!!(s&&n&&s===n)}function Ha(t){if(!t?.agentId||t?.isSystem)return null;const e=String(t?.title||"").trim();if(!e)return null;const s=" · ",n=e.lastIndexOf(s);if(n>0){const r=e.slice(0,n).trim(),a=e.slice(n+s.length).trim();if(r&&Ln(a,t))return{displayTitle:r,agentTitle:a}}const i=/^(.+?)\s+[–—-]\s+(.+)$/u.exec(e);if(i){const r=i[1].trim(),a=i[2].trim();if(r&&a)return{displayTitle:a,agentTitle:r}}const o=e.indexOf(": ");if(o>0){const r=e.slice(0,o).trim(),a=e.slice(o+2).trim();if(a&&Ln(r,t))return{displayTitle:a,agentTitle:r}}return null}function Ga(t){const e=String(t||""),s=e.indexOf(": ");if(s<=0)return null;const n=e.slice(0,s).trim(),i=e.slice(s+2).trim();return!n||!i?null:{userTitle:i,typeTitle:n}}function Xs(t){const e=String(t?.title||"").trim(),s=Ha(t);if(!s)return e;const n=Ga(s.displayTitle);return n?`${n.userTitle} · ${n.typeTitle} · ${s.agentTitle}`:`${s.displayTitle} · ${s.agentTitle}`}function Js(t,e){const s=K(t?.sessionId);if(t?.isSystem)return`${St(t,e)} (${s})`;const n=Xs(t);return n?n.includes(s)?n:`${n} (${s})`:`(${s})`}function $n(t,e={},s={},n=void 0){if(!e||e.all===!0)return!0;if(t?.isSystem)return e.includeSystem===!0;const i=Ht(n!==void 0?n:t?.owner);if(!i)return e.includeUnowned===!0;const o=Ht(s?.principal);return e.includeMe&&o&&i===o?!0:Array.isArray(e.ownerKeys)&&e.ownerKeys.includes(i)}function io(t,e={},s={},n=null){const i=Qs(t,n||{});if($n(t,e,s,i))return!0;if(!n)return!1;if(t?.isGroup)return no(t,n).some(a=>io(a,e,s,n));let o=t,r=0;for(;o?.parentSessionId&&r<16;){const a=n[o.parentSessionId];if(!a)return!1;if($n(a,e,s))return!0;o=a,r+=1}return!1}function ja(t){return(t||[]).map(e=>e?.text||"").join("")}function Zs(t){const e=new Map,s=new Map;for(const n of Object.values(t||{})){const i=n?.parentSessionId;i&&(s.set(n.sessionId,i),e.has(i)||e.set(i,[]),e.get(i).push(n.sessionId))}return{childMap:e,parentMap:s}}function Bn(t){const{childMap:e}=Zs(t),s=new Map;function n(i){if(s.has(i))return s.get(i);const r=(e.get(i)||[]).reduce((a,l)=>a+1+n(l),0);return s.set(i,r),r}for(const i of Object.keys(t||{}))n(i);return s}function Dn(t=[],e={}){const{parentMap:s}=Zs(e),n=new Map;for(const i of t){let o=s.get(i.sessionId);for(;o;)n.set(o,(n.get(o)||0)+1),o=s.get(o)}return n}function en(t={}){if(!t||typeof t!="object")return Bn(t);const e=On.get(t);if(e)return e;const s=Bn(t);return On.set(t,s),s}function tn(t=[],e={}){if(!Array.isArray(t))return Dn(t,e);const s=Rn.get(t);if(s)return s;const n=Dn(t,e);return Rn.set(t,n),n}function oo(t,e,s,n){const i=s.get(t)||0,o=n.get(t)||0,r=Math.max(0,i-o),a=e?.collapsed?i:r;return a?{text:`[+${a}]`,color:"cyan"}:null}function As(t){if(!t)return"scheduled";const e=t instanceof Date?t:new Date(t);if(Number.isNaN(e.getTime()))return"scheduled";try{return e.toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1,timeZoneName:"short"}).replace(/,\s*/g," ").replace(/\s+/g," ").trim()}catch{return e.toISOString().replace(/\.000Z$/,"Z")}}function Ua(t){return t?.cronActive===!0&&t?.cronKind==="wall-clock"?{text:`[cron ${As(t.cronNextFireAt)}]`,color:"magenta"}:t?.cronActive===!0&&typeof t?.cronInterval=="number"?{text:`[cron ${at(t.cronInterval)}]`,color:"magenta"}:null}function ro(t){return!!(t&&!t.isSystem&&(t.isGroup||!t.parentSessionId&&!t.groupId))}function Wa(t,e){const s=[],n=La(t);n&&s.push({text:n,color:pt(t,e)});const i=ho(t?.model,t?.reasoningEffort);i&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:i,color:"cyan"}));const o=nr(t?.contextUsage);o&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:o.text,color:o.color}));const r=or(t?.contextUsage);return r&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:r.text,color:r.color})),s}function Va(t,e,s,n,i){const o=[],r=s.connection?.mode||"local",a=t.depth>0?`${" ".repeat(Math.max(0,t.depth-1))}└ `:"";a&&o.push({text:a,color:"gray"});const l=new Set(Array.isArray(s.sessions?.pinnedIds)?s.sessions.pinnedIds:[]),p=new Set(Array.isArray(s.sessions?.selectedIds)?s.sessions.selectedIds:[]),u=!!s.sessions?.selectMode,d=p.has(t.sessionId),f=l.has(t.sessionId);if(u&&o.push({text:d?"[x] ":"[ ] ",color:d?"cyan":"gray",bold:d}),t.depth===0&&ro(e)&&l.size>0&&(f&&!e?.isSystem?o.push({text:"📌 ",color:"yellow"}):o.push({text:" ",color:"gray"})),e?.isGroup)o.push({text:"🗂 ",color:"cyan",bold:!0});else if(e?.isSystem)o.push({text:"⚙ ",color:"yellow",bold:!0});else{const k=so(e,r);o.push({text:k?`${k} `:" ",color:pt(e,r)})}const h=e?.isGroup?"cyan":e?.isSystem?"yellow":pt(e,r),m=Qs(e,s.sessions?.byId||{}),g=Da(m!==(e?.owner??null)?{...e,owner:m}:e,s.branding?.title||"PilotSwarm",Ba(s)),I=e?.updatedAt||e?.summaryUpdatedAt||e?.latestSummaryUpdatedAt||e?.createdAt||0,y=I?dr(I):"",x=[...o,{text:g,color:h,bold:!!e?.isSystem}],E=oo(e?.sessionId,t,n,i);E&&x.push({text:` ${E.text}`,color:E.color,bold:E.bold});const v=[];e?.isGroup&&e?.memberCount!=null&&v.push({text:`${e.memberCount} member${e.memberCount===1?"":"s"}`,color:"gray"}),y&&(v.length>0&&v.push({text:" · ",color:"gray"}),v.push({text:y,color:"gray"}));const T=[];for(const k of[Ua(e),ir(e?.contextUsage)])k&&(T.length>0&&T.push({text:" ",color:"gray"}),T.push({text:k.text,color:k.color,bold:k.bold}));const O=Wa(e,r);return{runs:[...x,...v.length>0?[{text:" ",color:"gray"},...v]:[],...T.length>0?[{text:" ",color:"gray"},...T]:[]],titleRuns:x,metaRuns:v,badgeRuns:T,selectedMetaRuns:O}}function ao(t){return String(t||"").trim().toLowerCase()}function Le(t,e){const s=ao(e);return s?String(t||"").toLowerCase().includes(s):!0}function ht(t){const e=en(t.sessions.byId),s=tn(t.sessions.flat,t.sessions.byId),n=ao(t.sessions?.filterQuery||""),i=t.sessions?.ownerFilter||{all:!0},o=t.auth||{},r=new Set(Array.isArray(t.sessions?.pinnedIds)?t.sessions.pinnedIds:[]),a=new Set(Array.isArray(t.sessions?.selectedIds)?t.sessions.selectedIds:[]);return t.sessions.flat.map(l=>{const p=t.sessions.byId[l.sessionId],u=Va(l,p,t,e,s);return{sessionId:l.sessionId,text:ja(u.runs),...u,depth:l.depth,status:p?.status,statusColor:pt(p,t.connection?.mode||"local"),active:l.sessionId===t.sessions.activeSessionId,isSystem:!!p?.isSystem,isGroup:!!p?.isGroup,hasChildren:l.hasChildren,collapsed:l.collapsed,pinned:r.has(l.sessionId),selected:a.has(l.sessionId),canPin:ro(p)}}).filter(l=>{const p=t.sessions.byId[l.sessionId];if(!io(p,i,o,t.sessions.byId))return!1;const u=Qs(p,t.sessions.byId),d=u?`${Ys(u,"")} ${u.email||""}`:"",f=`${p?.shortSummary||""} ${p?.summaryState?.intent||""} ${p?.summaryState?.summary||""}`;return Le(l.text,n)||Le(l.sessionId,n)||Le(d,n)||Le(f,n)})}function Ts(t,e=8){const s=ht(t);if(s.length===0)return[];const n=new Set(s.map(d=>d.sessionId)),i=(Array.isArray(t.sessions?.flat)?t.sessions.flat:[]).filter(d=>n.has(d.sessionId)),o=i.findIndex(d=>d.sessionId===t.sessions.activeSessionId),r=Math.max(0,o);if(i.length<=e)return s;const a=Math.floor(e/2);let l=Math.max(0,r-a),p=Math.min(i.length,l+e);p>i.length&&(p=i.length,l=Math.max(0,p-e));const u=i.slice(l,p);return en(t.sessions.byId),tn(i,t.sessions.byId),s.filter(d=>u.some(f=>f.sessionId===d.sessionId))}function Ce(t){const e=t.sessions.activeSessionId;return e&&t.sessions.byId[e]||null}function qa(t){return!t||t.isGroup?!1:(t.status||"")==="running"}function Ka(t){const e=t?.pendingQuestion;if(!e?.question)return null;const s=[String(e.question).trim()],n=Array.isArray(e.choices)?e.choices.filter(i=>typeof i=="string"&&i.trim()):[];if(n.length>0){s.push("","Choices:");for(const i of n)s.push(`- ${i}`)}return n.length>0&&e.allowFreeform===!1?s.push("","Reply with one of the choices above in the prompt below."):n.length>0?s.push("","Reply with one of the choices above, or type a free-form answer below."):s.push("","Type your answer in the prompt below and press Enter."),{id:`pending-question:${t.sessionId}:${e.question}`,role:"system",text:s.join(`
24
- `),time:"",createdAt:t.updatedAt||Date.now(),cardTitle:"Question",cardTitleColor:"cyan",cardBorderColor:"cyan"}}function za(t,e=[]){const s=t?.answeredPendingQuestion,n=String(s?.question||"").trim(),i=String(s?.answer||"").trim();if(!n||!i||lo(e,n))return null;const o=s.pendingPhase==="queued"?"queued":"pending",r=Number(s.answeredAt||0)||t.updatedAt||Date.now();return{id:`answered-question:${t.sessionId}:${n}:${r}`,role:"user",text:`The user was asked: "${n}"
25
- The user responded: "${i}"`,time:"",createdAt:r,optimistic:!0,pendingPhase:o}}function Ya(t,e){if(!t||!e?.id)return null;const s=String(e.text||"").trim();return s?{id:`pending-outbox:${t}:${e.id}`,role:"user",text:s,time:"",createdAt:Number(e.createdAt)||Date.now(),pendingPhase:e.phase==="cancelling"?"cancelling":e.phase==="queued"?"queued":"pending"}:null}function lo(t,e){const s=String(e||"").trim();return s?(t||[]).some(n=>Gs(n?.text||"")?.question?.trim()===s):!1}function Qa(t){const e=String(t?.error||"").trim();if(!e)return null;const s=zs(t);if(!s)return null;const n=s==="failed",i=n?e:`${e}
26
-
27
- The orchestration is still running, so this may be transient.`;return{id:`session-error:${t.sessionId}:${s}:${e}`,role:"system",text:i,time:"",createdAt:t.updatedAt||Date.now(),cardTitle:n?"Error":"Warning",cardTitleColor:n?"red":"yellow",cardBorderColor:n?"red":"yellow"}}function Hn(t=[],e){for(let s=t.length-1;s>=0;s-=1){const n=t[s];if(n?.eventType===e)return Number(n?.seq||0)}return 0}function Xa(t){const e=String(t||"").replace(/\s+/g," ").trim();return e?e.replace(/^\[[^\]]+\]\s*/,"").replace(/^\[[^\]]+\]\s*/,"").trim():""}function Ja(t,e=0){const s=Array.isArray(t?.activity)?t.activity:[],n=new Set(["assistant.reasoning","assistant.turn_start","session.turn_started","session.turn_completed"]);for(let i=s.length-1;i>=0;i-=1){const o=s[i];if(!o||n.has(o.eventType)||Number(o?.seq||0)<=e)continue;const r=Xa(o.text);if(r)return{...o,summaryText:r}}return null}function Za(t,e,s=[],n=[]){if(!t||t?.pendingQuestion?.question)return null;const i=String(t?.status||"").toLowerCase();if(i==="completed"||i==="failed"||i==="cancelled")return null;const o=(s||[]).filter(T=>T?.role==="user"||T?.role==="assistant"),r=o[o.length-1]||null,a=r?.role==="user",l=a&&r?.optimistic===!0,p=(n||[]).filter(T=>T?.phase==="pending").length,u=(n||[]).filter(T=>T?.phase==="queued").length,d=(n||[]).filter(T=>T?.phase==="cancelling").length,f=Array.isArray(e?.events)?e.events:[],h=Hn(f,"user.message"),m=Hn(f,"assistant.message"),g=h>m;if(i==="waiting"||i==="input_required"||!a&&!g&&i!=="running"&&!l)return null;const I=Math.max(h,m),y=f.filter(T=>T?.eventType==="assistant.reasoning"&&Number(T?.seq||0)>I),x=y[y.length-1]||null,E=String(x?.data?.content||x?.data?.text||x?.data?.message||"").trim();if(E)return{kind:"thinking",label:"Thinking",text:E,createdAt:x?.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:m,tokenSeq:x?.seq||0};const v=Ja(e,I);return v?.summaryText?{kind:i==="running"?"working":"sending",label:i==="running"?"Working":"Sending",text:v.summaryText,createdAt:v.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:m,tokenSeq:v.seq||0}:p>0?{kind:"pending",label:p===1?"Pending":`Pending ${p}`,text:p===1?"One prompt is waiting to be sent.":`${p} prompts are waiting to be sent.`,createdAt:n[n.length-1]?.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:m,tokenSeq:0}:u>0?{kind:"queued",label:u===1?"Queued":`Queued ${u}`,text:u===1?"One prompt is durably queued, waiting for the LLM to receive it.":`${u} prompts are durably queued, waiting for the LLM to receive them.`,createdAt:n[n.length-1]?.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:m,tokenSeq:0}:d>0?{kind:"cancelling",label:d===1?"Cancelling":`Cancelling ${d}`,text:d===1?"One queued prompt is waiting for cancellation confirmation.":`${d} queued prompts are waiting for cancellation confirmation.`,createdAt:n[n.length-1]?.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:m,tokenSeq:0}:l?{kind:"sending",label:"Sending",text:"Working on it...",createdAt:r?.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:m,tokenSeq:0}:i==="running"?{kind:"working",label:"Working",text:"Working on it...",createdAt:t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:m,tokenSeq:0}:null}function sn(t){const e=t.sessions.activeSessionId,s=e&&t.sessions.byId[e]||null;if(!e)return ss(t.branding);if(s?.isGroup){const p=Object.values(t.sessions.byId||{}).filter(h=>h&&!h.isGroup&&h.groupId===s.groupId&&!h.parentSessionId),u=h=>String(h??"").replace(/\|/g,"\\|").replace(/[\r\n]+/g," ").trim()||" ",d=p.map(h=>`| ${u(h.title||h.sessionId)} | ${u(h.status||"unknown")} | ${u(h.shortSummary||"")} |`),f=[`# ${s.title||s.groupId}`,s.shortSummary||"","","| Metric | Count |","|---|---:|",`| Members | ${s.memberCount??p.length} |`,`| Running | ${s.runningCount??0} |`,`| Waiting | ${s.waitingCount??0} |`,`| Completed | ${s.completedCount??0} |`,`| Failed | ${s.failedCount??0} |`,`| Cancelled | ${s.cancelledCount??0} |`,"","## Members",...d.length>0?["| Session | Status | Summary |","|---|---|---|",...d]:["_No top-level members._"]];return[{id:`group-details:${s.sessionId}`,role:"system",noChrome:!0,text:f.filter((h,m)=>m===1||String(h||"").length>0).join(`
28
- `),createdAt:s.updatedAt||Date.now()}]}if(t.ui?.chatViewMode==="summary")return el(s);const n=t.history.bySessionId.get(e),i=n?.chat||[],o=s?.pendingQuestion?.question&&!lo(i,s.pendingQuestion.question)?Ka(s):null,r=za(s,i),a=Qa(s);if((!n||i.length===0)&&!o&&!r&&!a)return ss(t.branding,s);const l=i.length>0?[...i]:ss(t.branding,s);return o&&l.push(o),r&&l.push(r),a&&l.push(a),l}function el(t){const e=p=>{const u=String(p||"");return u.includes("\\n")?u.replace(/\\\\n/g,`
29
- `).replace(/\\n/g,`
30
- `):u},s=t?.summaryState&&typeof t.summaryState=="object"&&!Array.isArray(t.summaryState)?t.summaryState:null,n=s?.state&&typeof s.state=="object"&&!Array.isArray(s.state)?s.state:null,i=Xs(t)||t?.title||t?.sessionId||"Session",o=[];o.push(`# ${i}`),o.push("");const r=[],a=_a(t);if(a&&r.push(["Status",a]),s?.intent&&r.push(["Intent",String(s.intent)]),t?.summaryUpdatedAt){const p=ce(t.summaryUpdatedAt);p&&r.push(["Updated",p])}for(const[p,u]of r)o.push(`**${p}:** ${u}`);r.length>0&&o.push("");const l=e(s?.summary||t?.shortSummary||"").trim();if(l&&(o.push(l),o.push("")),n){const p=Object.entries(n).filter(([,u])=>u!=null&&!(typeof u=="string"&&!u.trim()));if(p.length>0){o.push("## State");for(const[u,d]of p)if(Array.isArray(d))if(d.length===0)o.push(`- **${u}:** _(empty)_`);else{o.push(`- **${u}:**`);for(const f of d.slice(0,16)){const h=typeof f=="string"?e(f):JSON.stringify(f);o.push(` - ${h}`)}}else if(d&&typeof d=="object"){o.push(`- **${u}:**`);for(const[f,h]of Object.entries(d).slice(0,16)){const m=typeof h=="string"?e(h):JSON.stringify(h);o.push(` - **${f}:** ${m}`)}}else o.push(`- **${u}:** ${e(String(d))}`);o.push("")}}for(const[p,u]of[["Blockers","blockers"],["Open Questions","openQuestions"],["Next Actions","nextActions"]]){const d=Array.isArray(s?.[u])?s[u].filter(Boolean).slice(0,12):[];if(d.length!==0){o.push(`## ${p}`);for(const f of d)o.push(`- ${typeof f=="string"?e(f):JSON.stringify(f)}`);o.push("")}}for(!s&&!l&&o.push("_No summary has been written yet for this session._");o.length>0&&o[o.length-1]==="";)o.pop();return[{id:`summary:${t?.sessionId||"none"}`,role:"system",noChrome:!0,text:o.join(`
31
- `),createdAt:t?.summaryUpdatedAt||t?.updatedAt||Date.now()}]}function tl(t){const e=t.sessions.activeSessionId;return e?Array.isArray(t.outbox?.bySessionId?.[e])?t.outbox.bySessionId[e].map(s=>Ya(e,s)).filter(Boolean):[]:[]}function ds(t,e="gray",s={}){return[{text:t,color:e,bold:!!s.bold,underline:!!s.underline}]}function sl(t){const e=ce(t?.createdAt||t?.time),s=t?.role==="user"?"You":t?.role==="assistant"?"Agent":t?.role==="system"?"System":"PilotSwarm";let n=null,i=null;t?.pendingPhase==="pending"?(n="○",i="yellow"):t?.pendingPhase==="queued"?(n="✓",i="cyan"):t?.pendingPhase==="cancelling"?(n="x",i="red"):t?.role==="user"&&!t?.optimistic&&!t?.pendingPhase&&(n="✓✓",i="green");const o=t?.pendingPhase==="pending"?"yellow":t?.pendingPhase==="queued"?"cyan":t?.pendingPhase==="cancelling"?"red":t?.role==="user"?Oa:t?.role==="assistant"?"green":t?.role==="system"?"yellow":"white",r=e?`[${e}] `:"",a=[...ds(r,"gray")];return n&&a.push(...ds(`${n} `,i)),a.push(...ds(`${s}: `,o,{bold:!0})),a}function Oe(t){return Array.isArray(t)?(t||[]).map(e=>e?.text||"").join(""):t?.kind==="markdownTable"?"[table]":String(t?.text||"")}function co(){return[{text:"",color:null}]}function nl(t){const e=(t||[]).find(n=>Oe(n).trim().length>0);if(e?.kind==="markdownTable")return!0;const s=Oe(e).trimStart();return/^[┌│└]/.test(s)}function Gt(t){const e=Array.isArray(t)?[...t]:[];for(;e.length>0;){const s=e[0];if(Oe(s).trim().length>0)break;e.shift()}return e}function il(t){const e=String(t||"").replace(/\r\n/g,`
32
- `),s=e.trim();if(!s)return null;if(s.startsWith("[SYSTEM:")&&s.endsWith("]"))return{leadingText:"",systemText:s.slice(8,-1).trim()};const n=e.lastIndexOf(`
33
-
34
- [SYSTEM:`);if(n>=0&&e.trimEnd().endsWith("]")){const i=e.slice(0,n).trimEnd(),o=e.slice(n+2).trim();if(o.startsWith("[SYSTEM:"))return{leadingText:i,systemText:o.slice(8,-1).trim()}}return ol.test(s)?{leadingText:"",systemText:s}:null}const ol=/^(?:Sub-agents?\s+completed\b|Sub-agent\s+status\s+report\b|Active\s+sessions\b|No\s+(?:tracked\s+sub-agents|running\s+sub-agents|sub-agents\s+have\s+been\s+spawned)\b|spawn_agent\s+failed\b|message_agent\s+failed\b|complete_agent\s+failed\b)/i;function uo(t){const e=il(t);if(e){const r=[];e.leadingText&&r.push({kind:"text",text:e.leadingText});const a=Ne(e.systemText);return a&&r.push({kind:"system",text:a}),r}const s=String(t||"").replace(/\r\n/g,`
35
- `).split(`
36
- `),n=[];let i=[];function o(){i.length!==0&&(n.push({kind:"text",text:i.join(`
37
- `)}),i=[])}for(let r=0;r<s.length;){const a=s[r];if(!/^\s*\[SYSTEM:/i.test(a)){i.push(a),r+=1;continue}const l=/^\s*\[SYSTEM:\s*(.*?)\]\s*$/i.exec(a);if(l){o();const f=Ne(l[1].trim());if(!f){r+=1;continue}n.push({kind:"system",text:f}),r+=1;continue}const p=[a.replace(/^\s*\[SYSTEM:\s*/i,"")];let u=-1;for(let f=r+1;f<s.length;f+=1){const h=s[f];if(h.trim()==="]"){u=f;break}if(/\]\s*$/.test(h.trim())){const m=h.replace(/\]\s*$/,"");m.trim()&&p.push(m),u=f;break}p.push(h)}if(u===-1){i.push(a),r+=1;continue}o();const d=Ne(p.join(`
38
- `).trim());if(!d){r=u+1;continue}n.push({kind:"system",text:d}),r=u+1}return o(),n}function rl(t){return t?t?.role==="system"?!Hs(t?.text||"")||!!Ne(t?.text||""):t?.role!=="user"&&t?.role!=="assistant"?!1:uo(t?.text||"").some(e=>e.kind==="system"):!1}function Gn(t){return rl(t)?"system":t?.role||"other"}function fo(t,e){return!t||!e?!1:Gn(t)!==Gn(e)}function al(t){const e=String(t||"").replace(/\s+/g," ").trim();if(!e)return"System notice.";const s=/^The session was dehydrated and has been rehydrated on a new worker(?: \(([^)]+)\))?\./.exec(e);if(s)return s[1]?`Session rehydrated on a new worker (${s[1]}).`:"Session rehydrated on a new worker.";const i=/^(.{1,160}?[.!?])(?:\s|$)/.exec(e)?.[1]?.trim()||e;return i.length>=e.length?i.length>160?`${i.slice(0,159).trimEnd()}…`:i:`${i}…`}function ll(t,e=""){const s=al(t);return{kind:"systemNotice",text:`${e?`[${e}] `:""}System: ${s}`,summary:s,body:Ue(t),color:"gray"}}function jn({title:t,summary:e,body:s,timestamp:n="",color:i="gray"}){const o=String(t||"System").trim()||"System",r=String(e||"").replace(/\s+/g," ").trim();return{kind:"systemNotice",text:`${n?`[${n}] `:""}${o}${r?`: ${r}`:""}`,summary:r,body:Ue(s||r),color:i}}function cl(t){return t?.label?[{text:t.label,color:t.kind==="working"?"yellow":"cyan",bold:!0}]:null}function ul(t,e){return e?(t||[]).map(s=>Array.isArray(s)?s.map(n=>({...n,color:n?.color||e})):s):t}function dl(t){const e=(t||[]).find(s=>Oe(s).trim().length>0);return e?Oe(e).trimStart().startsWith("┌"):!1}function jt(t,e){!Array.isArray(e)||e.length===0||(t.length>0&&dl(e)&&Oe(t[t.length-1]).trim().length>0&&t.push([{text:"",color:null}]),t.push(...e))}function fl(t){const e=String(t||""),s=/^\s*Sub-agent\s+completed\b/i.test(e),n=/^\s*Sub-agents\s+completed/i.test(e);if(!s&&!n)return null;const i=[],o=/(?:^|\n)\s*-\s*Agent\s+(\S+)\s*\n\s*Task:\s*"([^"]*)"\s*\n\s*Status:\s*(\S+)\s*\n\s*Result:\s*([\s\S]*?)(?=(?:\n\s*-\s*Agent\s+\S+)|$)/g;let r;for(;(r=o.exec(e))!==null;)i.push({agentId:r[1],task:r[2],status:r[3],result:r[4].trim()});return i.length===0?null:s||i.length===1?{kind:"subAgentSingle",...i[0]}:{kind:"subAgentMulti",agents:i}}function pl(t,e,s){const n=Math.max(20,Number(s)||20),i=ce(e?.createdAt||e?.time),o=fl(t),r=a=>{const l=String(a||"").replace(/^session-/i,"");return K(l)||l||String(a||"")};if(o?.kind==="subAgentSingle"){const a=r(o.agentId),l=[o.task?`**Task:** ${o.task}`:"",o.status?`**Status:** ${o.status}`:"","",o.result||"_(no result)_"].filter((p,u)=>u===2||p).join(`
39
- `);return[jn({title:`Sub-agent Response — ${a}`,summary:o.status||"completed",timestamp:i,body:l,color:"cyan"})]}if(o?.kind==="subAgentMulti"){const a=o.agents.map(p=>{const u=r(p.agentId),d=p.task?`**Task:** ${p.task}`:"",f=p.status?`**Status:** ${p.status}`:"";return`${[`### ${u}`,d,f].filter(Boolean).join(`
40
- `)}
41
-
42
- ${p.result||"_(no result)_"}`}),l=o.agents.map(p=>`${r(p.agentId)} ${p.status||"completed"}`).join(" · ");return[jn({title:`Sub-agent Responses (${o.agents.length})`,summary:l,timestamp:i,body:a.join(`
43
-
44
- ---
45
-
46
- `),color:"cyan"})]}return Q({title:"System",timestamp:i,body:t,width:n,titleColor:"yellow",borderColor:"gray",bodyColor:"gray",fitToContent:!0})}function hl(t,e){const s=Math.max(12,Math.min(72,Number(e)||12)),n=Math.max(1,s-4),i=ce(t?.createdAt||t?.time),o=String(t?.thinkingLabel||"Thinking…").trim()||"Thinking…",r=t?.progressKind==="working"?"yellow":(t?.progressKind==="sending","cyan"),a=q([{text:` ⠋ ${o} `,color:r,bold:!0},...i?[{text:` ${i} `,color:"gray"}]:[]],Math.max(1,s-3)),l=a.reduce((f,h)=>f+String(h?.text||"").length,0),p=Math.max(0,s-l-3),u=String(t?.text||"").trim()?Gt(ut(Ue(t.text),{width:n})).flatMap(f=>Li(f,n)):[],d=[[{text:"┌─",color:"gray"},...a,{text:`${"─".repeat(p)}┐`,color:"gray"}]];for(const f of u)d.push([{text:"│ ",color:"gray"},..._i(f.map(h=>({...h,color:h?.color&&h.color!=="white"?h.color:"gray"})),n),{text:" │",color:"gray"}]);return d.push([{text:`└${"─".repeat(Math.max(1,s-2))}┘`,color:"gray"}]),d.push([{text:"",color:null}]),d}function Ut(t,e,s={}){if(t?.splash)return[{kind:"markup",value:t.text}];if(t?.thinking)return hl(t,e);if(t?.noChrome)return Gt(ut(Ue(t?.text||""),{width:Math.max(20,e),tableMode:s.tableMode}));if(t?.role==="user"){const l=Gs(t?.text||"");if(l)return[...Q({title:"Question",timestamp:ce(t?.createdAt||t?.time),body:l.question,width:Math.max(20,e),titleColor:us,borderColor:us}),...Ut({...t,text:l.answer},e,s)]}if(s.allowLeadingSystemNotices!==!1&&(t?.role==="user"||t?.role==="assistant")){const l=uo(t?.text||"");if(l.some(p=>p.kind==="system")){const p=[];let u=!1;for(const f of l)f.kind!=="system"&&f.text.trim()&&(jt(p,Ut({...t,text:f.text},e,{...s,allowLeadingSystemNotices:!1,skipPrefix:u})),u=!0);if(p.length>0)return p;const d=[];for(const f of l)f.kind!=="system"||!f.text.trim()||jt(d,pl(f.text,t,e));if(d.length>0)return d}}if(t?.role!=="user"&&t?.role!=="assistant"){const l=Ne(t?.text||"");if(t?.role==="system"&&!l)return[];const p=!!t?.cardTitle&&String(t.cardTitle).toLowerCase()!=="system";if(t?.role==="system"&&!p)return[ll(l||t?.text||"",ce(t?.createdAt||t?.time))];const u=t?.role==="system"&&(!t?.cardTitle||String(t.cardTitle).toLowerCase()==="system");return Q({title:t?.cardTitle||(t?.role==="system"?"System":"PilotSwarm"),timestamp:ce(t?.createdAt||t?.time),body:Ue(t?.text||""),width:Math.max(20,e),titleColor:t?.cardTitleColor||(t?.role==="system"?"yellow":"cyan"),borderColor:t?.cardBorderColor||"gray",...u?{bodyColor:"gray",fitToContent:!0}:{}})}const n=Gt(ut(Ue(t?.text||""),{width:e,tableMode:s.tableMode})),i=ul(n,t?.pendingPhase==="cancelling"?"red":t?.role==="user"?us:null),o=s.skipPrefix?[]:sl(t);if(i.length===0)return o.length>0?[o]:[];if(nl(i))return o.length>0?[o,...i]:i;const r=[];let a=o.length===0;for(const l of i){if(!Array.isArray(l)){a||(r.push(o),a=!0),r.push(l);continue}a?r.push(l):(r.push([...o,...l]),a=!0)}return r}function nn(t,e=80,s={}){const n=sn(t);if(!n||n.length===0)return[{text:"No messages yet.",color:"gray"}];const i=s?.tableMode?{tableMode:s.tableMode}:{},o=[];for(const[r,a]of n.entries()){const l=Ut(a,e,i);jt(o,l);const p=n[r+1];p&&fo(a,p)&&Oe(o[o.length-1]).trim().length>0&&o.push(co())}return o.length>0?o:[{text:"No messages yet.",color:"gray"}]}function po(t,e=80,s={}){const n=tl(t);if(!n||n.length===0)return[];const i=Math.max(20,Number(e)||80),o=n.filter(m=>m.pendingPhase==="queued").length,r=n.filter(m=>m.pendingPhase==="pending").length,a=n.filter(m=>m.pendingPhase==="cancelling").length,l=[];r>0&&l.push(`${r} pending`),o>0&&l.push(`${o} queued`),a>0&&l.push(`${a} cancelling`);const u=` queued prompts: ${l.length>0?l.join(" · "):"queued prompts"} `,d=Math.max(1,i-u.length),f=[[{text:u,color:"gray"},{text:"─".repeat(d),color:"gray"}]],h=s?.tableMode?{tableMode:s.tableMode}:{};for(const[m,g]of n.entries()){jt(f,Ut(g,i,h));const I=n[m+1];I&&fo(g,I)&&Oe(f[f.length-1]).trim().length>0&&f.push(co())}return f}function ml(t){const e=sn(t),s=[],n=new Set;for(const i of e||[])for(const o of br(i?.text||"")){const r=`${o.sessionId}/${o.filename}`;n.has(r)||(n.add(r),s.push(o))}return s}function gl(t){const e=sn(t),s=[],n=new Set;for(const i of e||[])for(const o of wr(i?.text||"")){const r=String(o.href||"").trim();!r||n.has(r)||(n.add(r),s.push({href:r,text:String(o.text||r).trim()||r}))}return s}function ho(t,e){const s=Ri(t);if(!s)return"";const n=String(e||"").trim();return n?`${s}:${n}`:s}function yl(t){return Ri(t)||"(unknown)"}function mo(t,e={}){const s=Ce(t),n=t.sessions?.byId||{},i=Array.isArray(t.sessions?.flat)?t.sessions.flat:[],o=en(n),r=tn(i,n),a=Ji(e?.width);if(!s)return{color:"cyan",title:Se("Chat","cyan"),titleRight:null,animateTitleRight:!1};const l=K(s.sessionId),p=s.isSystem?"yellow":"cyan",u=Se(s.isSystem?`⚙ ${St(s,t.branding?.title||"PilotSwarm")}`:Xs(s)||"Chat",p),d=i.find(I=>I.sessionId===s.sessionId),f=oo(s.sessionId,d,o,r);f&&u.push({text:` ${f.text}`,color:f.color}),a||u.push({text:` [${l}]`,color:"gray"});const h=t.history?.bySessionId?.get(s.sessionId)||null,m=Array.isArray(t.outbox?.bySessionId?.[s.sessionId])?t.outbox.bySessionId[s.sessionId]:[],g=t.ui?.chatViewMode==="summary"?null:Za(s,h,h?.chat||[],m);return{color:s.isSystem?"yellow":"cyan",title:u,titleRight:cl(g),animateTitleRight:!!g}}function Sl(t){const e=t.sessions.activeSessionId;return e?t.history.bySessionId.get(e)?.activity||[]:[]}function on(t,e=12){const s=Sl(t),n=Ce(t),i=Se("Activity","gray");return n?.isGroup?{title:i,disabled:!0,lines:[{text:Ao,color:"gray"}]}:(n?.statusVersion!=null&&i.push({text:` [current session v${n.statusVersion}]`,color:"gray"}),{title:i,lines:s.length>0?s.map(o=>o.line||[{text:o.text,color:"white"}]):[{text:"No activity yet",color:"gray"}]})}function go(t){switch(String(t||"").toLowerCase()){case"error":return"red";case"warn":return"yellow";case"debug":return"blue";case"trace":return"magenta";default:return"green"}}function yo(t,e){return t==="orchestration"?"magenta":t==="activity"?"cyan":go(e)}function bl(t){return t==="raw"?"raw summary":"pretty text"}function wl(t){return t?.sessionId?`session-${t.sessionId}`:null}function Il(t,e){const s=Array.isArray(t.logs?.entries)?t.logs.entries:[],n=t.logs?.filter||{},i=wl(e);return s.filter(o=>!(!o||n.source==="currentOrchestration"&&i&&o.orchId!==i||n.level&&n.level!=="all"&&String(o.level||"").toLowerCase()!==n.level))}function xl(t){const e=qt(t?.podName)||t?.podName||"node",s=t?.sessionId||(String(t?.orchId||"").startsWith("session-")?String(t.orchId).slice(8):""),n=String(t?.level||"info").toUpperCase(),i=t?.category==="orchestration"?"◆":t?.category==="activity"?"●":"•";return[{text:`[${t?.time||"--:--:--"}] `,color:"gray"},{text:`${i} `,color:yo(t?.category,t?.level)},{text:`${e} `,color:"white",bold:!0},...s?[{text:`[${K(s)}] `,color:"gray"}]:[],{text:`${n} `,color:go(t?.level),bold:!0},{text:t?.rawLine||t?.message||"",color:"white"}]}function El(t){const e=t?.sessionId||(String(t?.orchId||"").startsWith("session-")?String(t.orchId).slice(8):"");return[{text:`${e?`[${K(e)}] `:""}${t?.prettyMessage||t?.message||t?.rawLine||""}`,color:yo(t?.category,t?.level),bold:String(t?.level||"").toLowerCase()==="warn"||String(t?.level||"").toLowerCase()==="error"}]}function vl(t,e){const s=t.logs||{},n=s.filter||{},i=[{text:"Scope: ",color:"gray"},{text:n.source==="currentOrchestration"?"current orchestration":"all nodes",color:"white"},{text:" Level: ",color:"gray"},{text:n.level||"all",color:"white"},{text:" Format: ",color:"gray"},{text:bl(n.format),color:"white"}];if(!s.available)return[{text:s.availabilityReason||"Log tailing disabled: no K8S_CONTEXT configured in the env file.",color:"yellow"},{text:"",color:"gray"},i];if(!s.tailing)return[{text:"Press t to start log tailing.",color:"cyan",bold:!0},{text:"Press f to open log filters.",color:"gray"},{text:"",color:"gray"},i];const o=Il(t,e);return o.length===0?[{text:"Tailing logs…",color:"cyan"},{text:"No logs match the current filter yet.",color:"gray"},{text:"",color:"gray"},i]:[i,{text:"",color:"gray"},...o.map(r=>n.format==="raw"?xl(r):El(r))]}function Un(t){return/\.(md|markdown|mdown|mkd|mdx)$/i.test(String(t||""))}function Cl(t){return/\.(json|jsonl)$/i.test(String(t||""))}function Al(t){return ge.map(e=>({text:e===t?`[${e}] `:`${e} `,color:e===t?"magenta":"gray",bold:e===t}))}function Tl(t=""){const e=String(t||"").split(`
47
- `);return e.length>0?e.map(s=>({text:s,color:"white"})):[{text:"",color:"white"}]}function Wn(t,{selected:e=!1,width:s=24,label:n=null}={}){const i=Math.max(8,s),o=Un(t)?"# ":Cl(t)?"{ ":"• ",r=So(`${o}${n||t}`,i).padEnd(i," ");return e?Te(r):{text:r,color:Un(t)?"cyan":"white",bold:!1}}function de(t){return t.files?.filter?.scope==="allSessions"?"allSessions":"selectedSession"}function kl(t,e={}){if(!t)return new Set;const{childMap:s}=Zs(e),n=new Set([t]),i=[t];for(;i.length>0;){const o=i.shift(),r=s.get(o)||[];for(const a of r)!a||n.has(a)||(n.add(a),i.push(a))}return n}function Wt(t,e=de(t)){const s=Ce(t)?.sessionId||null,n=Array.isArray(t.sessions?.flat)?t.sessions.flat.map(l=>l?.sessionId||l).filter(Boolean):[],i=Object.keys(t.files?.bySessionId||{}).filter(Boolean);if(e==="allSessions")return[...new Set([...n,...i])];const o=kl(s,t.sessions?.byId||{});if(o.size===0)return[];const r=[],a=new Set;for(const l of[s,...n,...Object.keys(t.sessions?.byId||{}),...i])!l||a.has(l)||!o.has(l)||(r.push(l),a.add(l));for(const l of o)a.has(l)||r.push(l);return r}function mt(t){const e=de(t);Ce(t)?.sessionId;const s=t.files?.filter?.query||"",n=Wt(t,e),i=e==="allSessions"||n.length>1,o=[];for(const r of n){const a=Bt(t.files?.bySessionId?.[r]?.entries);for(const l of a){const p=l.filename;o.push({id:`${r}/${p}`,sessionId:r,filename:p,entry:l,label:i?`[${K(r)}] ${p}`:p})}}return o.filter(r=>Le(r.filename,s)||Le(r.sessionId,s)||Le(r.label,s))}function Me(t){const e=mt(t);if(e.length===0)return null;const s=t.files?.selectedArtifactId||null;if(s){const r=e.find(a=>a.id===s);if(r)return r}if(de(t)==="allSessions"){const r=Ce(t)?.sessionId||null,a=r&&t.files?.bySessionId?.[r]?.selectedFilename||null;if(r&&a){const l=e.find(p=>p.sessionId===r&&p.filename===a);if(l)return l}return e[0]}const i=Ce(t)?.sessionId||null,o=i&&t.files?.bySessionId?.[i]?.selectedFilename||null;return e.find(r=>r.sessionId===i&&r.filename===o)||e[0]}function rn(t,e={}){const s=Ce(t),n=Math.max(12,Number(e?.listWidth)||Number(e?.width)||24),i=Math.max(18,Number(e?.previewWidth)||Number(e?.width)||36),o=e?.showHints!==!1,r=s?.sessionId||null,a=de(t),l=t.files?.filter?.query||"",p=mt(t),u=Me(t),d=u?.filename||null,f=Math.max(0,p.findIndex(_=>_.id===u?.id)),h=u?.sessionId&&d&&t.files?.bySessionId?.[u.sessionId]?.previews?.[d]||null,m=h||u?.entry||null,g=s?K(s.sessionId):"",I=Wt(t,a),y=a!=="allSessions"&&I.some(_=>_&&_!==r),x=[...new Set([...Array.isArray(t.sessions?.flat)?t.sessions.flat.map(_=>_?.sessionId||_):[],...Object.keys(t.files?.bySessionId||{})])].filter(Boolean),E=a==="allSessions"&&x.some(_=>!t.files?.bySessionId?.[_]?.loaded||t.files?.bySessionId?.[_]?.loading),v=a==="allSessions"&&x.map(_=>t.files?.bySessionId?.[_]?.error).find(Boolean)||null,T=[Al("files"),...s||a==="allSessions"?[]:[{text:"No session selected.",color:"gray"}]];if(a==="allSessions")E&&p.length===0?T.push({text:"Loading exported files across all sessions…",color:"gray"}):v&&p.length===0?T.push({text:v,color:"red"}):p.length===0?(T.push({text:l?`No artifacts matched "${l}" across any session.`:"No exported files across any session yet.",color:"gray"}),T.push({text:l?"Clear the query or switch back to the selected session.":"Switch the filter back to the selected session or wait for agents to export artifacts.",color:"gray"})):T.push(...p.map((_,W)=>Wn(_.filename,{selected:W===f,width:n,label:_.label})));else if(s){const _=r?t.files?.bySessionId?.[r]:null;Array.isArray(_?.entries)&&_.entries;const W=p.filter(U=>I.includes(U.sessionId));_?.loading?T.push({text:"Loading exported files…",color:"gray"}):_?.error?T.push({text:_.error,color:"red"}):W.length===0&&I.every(U=>{const ee=t.files?.bySessionId?.[U]?.entries;return!Array.isArray(ee)||ee.length===0})?(T.push({text:l?`No artifacts matched "${l}" for this ${y?"session tree":"session"}.`:`No exported files for this ${y?"session tree":"session"} yet.`,color:"gray"}),T.push({text:l?"Clear the query or upload an artifact to this session.":y?"Artifacts exported by this session or any child session will appear here.":"Agents must write/export artifacts before they appear here.",color:"gray"})):T.push(...W.map((U,ee)=>Wn(U.filename,{selected:ee===f,width:n,label:U.label})))}let O,M;!s&&a!=="allSessions"?(M=[{text:"Preview",color:"cyan",bold:!0}],O=[{text:"No session selected.",color:"gray"}]):d?h?.loading?(M=[{text:`Preview: ${d}`,color:"cyan",bold:!0},...(a==="allSessions"||u?.sessionId&&u.sessionId!==r)&&u?.sessionId?[{text:` · ${K(u.sessionId)}`,color:"gray"}]:[]],O=[{text:"Loading file preview…",color:"gray"}]):h?.error?(M=[{text:`Preview: ${d}`,color:"cyan",bold:!0},...(a==="allSessions"||u?.sessionId&&u.sessionId!==r)&&u?.sessionId?[{text:` · ${K(u.sessionId)}`,color:"gray"}]:[]],O=[{text:h.error,color:"red"}]):(M=[{text:`Preview: ${d}`,color:"cyan",bold:!0},...(a==="allSessions"||u?.sessionId&&u.sessionId!==r)&&u?.sessionId?[{text:` · ${K(u.sessionId)}`,color:"gray"}]:[],...h?.renderMode==="markdown"?[{text:" [md]",color:"gray"}]:h?.isBinary===!0?[{text:" [file]",color:"gray"}]:h?.renderMode==="note"?[{text:" [note]",color:"gray"}]:[]],O=h?.renderMode==="markdown"?Gt(ut(h?.content||"",{width:i})):Tl(h?.content||"")):(M=[{text:"Preview",color:"cyan",bold:!0}],O=[{text:"Select a file to preview it here.",color:"gray"}]);const k=a==="allSessions"?"Files: all sessions":s?`Files: ${g}${y?" tree":""}`:"Files",N=a==="allSessions"?"all sessions":s?`${g}${y?" tree":""}`:"Files",L=a==="allSessions"?`Artifacts${p.length>0?` [${p.length}]`:""}`:`Artifacts${y?" tree":""}${p.length>0?` [${p.length}]`:""}`,Y=l?` · @${l}`:"";return{panelTitle:[{text:`${k}${Y}`,color:"magenta",bold:!0}],panelTitleMobile:[{text:`${N}${Y}`,color:"magenta",bold:!0}],listTitle:[{text:`${L}${Y}`,color:"cyan",bold:!0}],listLines:T,listBodyLines:T.slice(1),selectedIndex:f,selectedFilename:d,selectedSessionId:u?.sessionId||null,scope:a,previewTitle:M,previewLines:O,previewContent:h?.content||"",previewContentType:h?.contentType||"",previewRenderMode:h?.renderMode||null,previewIsBinary:m?.isBinary===!0,previewSizeBytes:m?.sizeBytes??null,previewUploadedAt:m?.uploadedAt||"",previewSource:m?.source||null,previewError:h?.error||null,previewLoading:!!h?.loading,previewScrollOffset:t.ui.scroll.filePreview||0,fullscreen:!!t.files?.fullscreen,fullscreenTitle:[{text:k,color:"magenta",bold:!0},...d?[{text:" · ",color:"gray"},{text:d,color:"cyan",bold:!0}]:[],...o?[{text:" [f filter] [u upload] [a download] [x delete] [o open] [v/esc close fullscreen]",color:"gray"}]:[]]}}function Ml(t){const e=t.admin||{},s=e.profile||null,n=e.ghcpKey||{editing:!1,draft:"",saving:!1,error:null},i=s?{provider:s.provider||"",subject:s.subject||"",email:s.email||null,displayName:s.displayName||null}:t.auth?.principal||null,o=n.saving?"Saving...":n.editing?"Editing — Enter to save, Esc to cancel":s?.githubCopilotKeySet?"Configured (overrides env GITHUB_TOKEN for this user)":"Not configured (using env GITHUB_TOKEN fallback)",r=[];return n.editing?(r.push({id:"save",label:"Save",key:"Enter"}),r.push({id:"cancel",label:"Cancel",key:"Esc"})):(r.push({id:"edit",label:s?.githubCopilotKeySet?"Replace key":"Set key",key:"e"}),s?.githubCopilotKeySet&&r.push({id:"clear",label:"Clear key",key:"c"}),r.push({id:"refresh",label:"Refresh",key:"r"})),r.push({id:"close",label:"Close console",key:n.editing?"Ctrl+Esc":"Esc"}),{visible:!!e.visible,loading:!!e.loading,loadError:e.loadError||null,principal:i,ghcpKey:{configured:!!s?.githubCopilotKeySet,editing:!!n.editing,draft:n.draft||"",cursorIndex:Math.max(0,Math.min(Number(n.cursorIndex)||0,String(n.draft||"").length)),saving:!!n.saving,error:n.error||null,statusText:o},actions:r}}function Pl(t){const e=t.ui.focusRegion,s=t.ui.fullscreenPane||null,n=Ce(t),i=!!n?.pendingQuestion?.question,o=n?.sessionId&&Array.isArray(t.outbox?.bySessionId?.[n.sessionId])?t.outbox.bySessionId[n.sessionId]:[],r=o.length>0,a=o.some(y=>y?.phase==="pending"),l=t.ui.promptEdit?.sessionId===n?.sessionId,p=l&&t.ui.promptEdit?.phase==="queued",u=l&&t.ui.promptEdit?.phase==="cancelling",d=s===e?"v/esc close fullscreen":"v fullscreen";if(t.ui.modal?.type==="artifactUpload")return{left:"Upload a local file into this session's artifact store",right:"type path · left/right move · enter upload · esc cancel"};if(t.ui.modal?.type==="renameSession")return{left:"Rename the selected session title",right:"type title · left/right move · enter save · esc cancel"};if(t.ui.modal?.type==="artifactPicker")return{left:"Select a linked artifact or URL",right:"up/down move · enter open/download · a/esc close"};if(t.ui.modal?.type==="modelPicker")return{left:"Select a model for the new session",right:"up/down move · enter next · esc cancel"};if(t.ui.modal?.type==="reasoningEffortPicker")return{left:"Select reasoning effort for the new session",right:"up/down move · enter create · esc cancel"};if(t.ui.modal?.type==="themePicker")return{left:"Select a shared portal/TUI theme",right:"up/down move · enter apply · esc close"};if(t.ui.modal?.type==="sessionAgentPicker")return{left:"Select an agent for the new session",right:"up/down move · enter create · esc cancel"};if(t.ui.modal?.type==="sessionGroupPicker")return{left:"Move selected session(s) to a group",right:"up/down move · enter choose · esc cancel"};if(t.ui.modal?.type==="sessionGroupName")return{left:"Name the new group",right:"type name · left/right move · enter create · esc cancel"};if(t.ui.modal?.type==="logFilter")return{left:"Adjust log filters",right:"tab/shift-tab filter · up/down change · enter close · esc close"};if(t.ui.modal?.type==="filesFilter")return{left:"Adjust files browser filters",right:"tab/shift-tab filter · up/down change · enter close · esc close"};if(t.ui.modal?.type==="sessionOwnerFilter")return{left:"Adjust session filters",right:"up/down choose · space toggle · esc close"};const f=!!t.sessions?.selectMode,h=Array.isArray(t.sessions?.selectedIds)?t.sessions.selectedIds.length:0;if(f&&e===w.SESSIONS)return{left:`Select mode · ${h} selected`,right:"up/down move · space toggle · ctrl-g group · c cancel · d complete · D hard delete · V/esc exit"};const g=(t.ui?.chatViewMode==="summary"?"summary":"transcript")==="summary"?"s transcript":"s summary",I={[w.SESSIONS]:`up/down switch · ctrl-u/ctrl-d page · ctrl-g move group · f filter · P pin · V select · d done · D delete · r refresh · t title · ${d} · {/} session pane · [/] side pane · T themes · a linked items · drag copy · tab next pane · p prompt`,[w.CHAT]:`${g} · j/k scroll · ctrl-u/ctrl-d page · e older history · g/G top/bottom · d done · ${d} · {/} session pane · [/] side pane · T themes · a linked items · drag copy · tab next pane · p prompt`,[w.INSPECTOR]:t.ui.inspectorTab==="logs"?`j/k scroll · ctrl-u/ctrl-d page · g/G top/bottom · d done · t tail · f filter · ${d} · left/right tab · [/] side pane · T themes · a linked items · drag copy · tab next pane`:t.ui.inspectorTab==="stats"?`j/k scroll · ctrl-u/ctrl-d page · g/G top/bottom · f cycle session/fleet/users · d done · ${d} · left/right tab · [/] side pane · T themes · m next tab · tab next pane`:t.ui.inspectorTab==="files"?t.files?.fullscreen?"a download · x delete · u/ctrl-a upload · o open · f filter · j/k scroll · ctrl-u/ctrl-d page · g/G top/bottom · d done · v/esc close fullscreen · left/right tab · {/} session pane · [/] side pane · T themes · tab next pane":"j/k files · a download · x delete · u/ctrl-a upload · o open · f filter · ctrl-u/ctrl-d page preview · g/G preview top/bottom · d done · v fullscreen · left/right tab · {/} session pane · [/] side pane · T themes · tab next pane":t.ui.inspectorTab==="history"?`j/k scroll · ctrl-u/ctrl-d page · g/G top/bottom · f format · r refresh · a save artifact · d done · ${d} · left/right tab · [/] side pane · T themes · m next tab · tab next pane`:`j/k scroll · ctrl-u/ctrl-d page · g/G top/bottom · d done · ${d} · left/right tab · [/] side pane · T themes · h/l focus · a linked items · drag copy · m next tab · tab next pane`,[w.ACTIVITY]:`j/k scroll · ctrl-u/ctrl-d page · g/G top/bottom · d done · ${d} · {/} session pane · [/] side pane · T themes · a linked items · drag copy · h left · tab next pane`,[w.PROMPT]:i?`type answer · enter reply · alt-enter newline · T themes · arrows move · alt-left/right word · alt-delete word · @ artifacts · @@ sessions · ${s?"esc pane":"esc sessions"}`:l?p?`queued prompt selected · d delete · up/down cycle queued · enter/esc new prompt · ${s?"esc pane":"esc sessions"}`:u?`cancelling prompt selected · up/down cycle queued · enter/esc new prompt · ${s?"esc pane":"esc sessions"}`:`edit pending prompt · enter send batch · up/down cycle pending · esc cancel · alt-enter newline · @ artifacts · @@ sessions · ${s?"esc pane":"esc sessions"}`:a?`type message · enter queues · enter on empty sends batch · up/down recall pending · alt-enter newline · @ artifacts · @@ sessions · ${s?"esc pane":"esc sessions"}`:r?`type message · enter queues behind durable items · up/down recall pending · alt-enter newline · @ artifacts · @@ sessions · ${s?"esc pane":"esc sessions"}`:`type message · enter send · alt-enter newline · T themes · arrows move · alt-left/right word · alt-delete word · @ artifacts · @@ sessions · ${s?"esc pane":"esc sessions"}`};return{left:t.ui.statusText,right:I[e]||I[w.SESSIONS]}}function Xe(t){return(t||[]).reduce((e,s)=>e+String(s?.text||"").length,0)}function q(t,e){if(e<=0)return[];const s=[];let n=e;for(const i of t||[]){if(n<=0)break;const o=String(i?.text||"");if(!o)continue;const r=o.length>n&&n>1?`${o.slice(0,n-1)}…`:o.slice(0,n);r&&(s.push({...i,text:r}),n-=r.length)}return s}function we(t){return Array.from(String(t||"")).length}function So(t,e){const s=String(t||"");return e<=0?"":we(s)<=e?s:e===1?Array.from(s)[0]||"":`${Array.from(s).slice(0,e-1).join("")}…`}function $e(t,e){const s=So(t,e),n=Math.max(0,e-we(s));return s+" ".repeat(n)}function F(t,e="white",s={}){return{text:String(t||""),color:e,...s}}function ne(t){const e=Number(t);if(!Number.isFinite(e)||e<0)return"?";if(e<1024)return`${Math.round(e)} B`;if(e<1024*1024){const n=e/1024;return`${n>=10?Math.round(n):n.toFixed(1)} KB`}const s=e/(1024*1024);return`${s>=10?Math.round(s):s.toFixed(1)} MB`}function bo(t,e=18){const s=String(t||"").replace(/\s+/g," ").trim();return s?we(s)>e?`${Array.from(s).slice(0,Math.max(1,e-1)).join("")}…`:s:""}function Nl(t){const e=t?.data;if(typeof e=="string")return e;if(e&&typeof e=="object"){if(typeof e.content=="string")return e.content;if(typeof e.text=="string")return e.text;if(typeof e.message=="string")return e.message;if(typeof e.question=="string")return e.question}return""}function wo(t=[]){const e=new Set,s=[];for(const n of t){const i=String(n||"").trim();if(!i)continue;const o=i.toLowerCase();e.has(o)||(e.add(o),s.push(i))}return s.join(" | ")}function Ol(t,e=""){return wo([t?.data?.reason==="cron_at"?"cron":t?.data?.reason,t?.data?.detail,t?.data?.message,t?.data?.error,e])}function Rl(t,e=""){return wo([t?.data?.message,t?.data?.detail,t?.data?.error,e])}function qt(t){const e=String(t||"").trim();if(!e||e==="(unknown)")return null;const s=e.split(/[/:]/).pop()||e,n=s.length<=5?s:s.slice(-5);return n.replace(/^[^a-zA-Z0-9]+/,"")||n}const Fl=300*1e3,_l="last 5m";function an(t){let e=0;for(const s of t.history.bySessionId.values())for(const n of s?.events||[]){const i=n?.createdAt instanceof Date?n.createdAt.getTime():new Date(n?.createdAt||0).getTime();Number.isFinite(i)&&(e=Math.max(e,i))}return(!Number.isFinite(e)||e<=0)&&(e=Date.now()),{startMs:e-Fl,endMs:e,label:_l}}function Ll(t,e){if(!t||!e)return!1;const s=Number(t.createdAtMs||0);return Number.isFinite(s)?s>=e.startMs&&s<=e.endMs:!1}function Io(t,e){if(!t||!e)return!1;const s=t?.createdAt instanceof Date?t.createdAt.getTime():new Date(t?.createdAt||0).getTime();return Number.isFinite(s)?s>=e.startMs&&s<=e.endMs:!1}const $l=new Set(["wait","timer","cron_start","cron_fire","cron_cancel","spawn","cmd_recv","cmd_done"]);function Bl(t){return $l.has(t)}function Dl(t){const e=ce(t?.createdAt),s=qt(t?.workerNodeId),n=Nl(t),i=bo(n,20),o=t?.createdAt instanceof Date?t.createdAt.getTime():new Date(t?.createdAt||0).getTime(),r={time:e,createdAtMs:Number.isFinite(o)?o:0,nodeLabel:s,color:"white",detail:"",type:"other"};switch(t?.eventType){case"session.turn_started":return{...r,type:"turn_start",color:"gray",detail:`turn ${t?.data?.iteration??"?"}`};case"session.turn_completed":{const a=Number(t?.data?.turnIndex??t?.data?.iteration);return{...r,type:"turn_end",color:"gray",detail:`turn ${t?.data?.iteration??"?"} done`,...Number.isFinite(a)?{completedTurn:a}:{}}}case"user.message":return{...r,type:"user_msg",color:"white",detail:i?`>> ${i}`:">> user"};case"assistant.message":return{...r,type:"response",color:"green",detail:i?`< ${i}`:"< response"};case"system.message":return{...r,type:"system",color:"yellow",detail:i||"system"};case"session.wait_started":return{...r,type:"wait",color:"yellow",detail:`wait ${at(t?.data?.seconds??0)}`};case"session.wait_completed":return{...r,type:"timer",color:"yellow",detail:`${at(t?.data?.seconds??0)} up`};case"session.lossy_handoff":{const a=Rl(t,i);return{...r,type:"dehydrate",color:"yellow",detail:a?`lossy ${a}`:"lossy handoff"}}case"session.dehydrated":return{...r,type:"dehydrate",color:"cyan",detail:`ZZ ${Ol(t,i)}`.trim()};case"session.rehydrated":case"session.hydrated":return{...r,type:"hydrate",color:"green",detail:"rehydrated"};case"session.agent_spawned":return{...r,type:"spawn",color:"cyan",detail:`spawn ${t?.data?.agentId||K(t?.data?.childSessionId)||"agent"}`};case"session.cron_started":return{...r,type:"cron_start",color:"magenta",detail:`cron ${at(t?.data?.intervalSeconds??0)}`};case"session.cron_at_scheduled":case"session.cron_at_started":return{...r,type:"cron_start",color:"magenta",detail:`cron ${As(t?.data?.nextFireAtMs??t?.data?.nextFireAt)}`};case"session.cron_fired":return{...r,type:"cron_fire",color:"magenta",detail:"cron fired"};case"session.cron_at_fired":return{...r,type:"cron_fire",color:"magenta",detail:`cron fired ${As(t?.data?.scheduledAt)}`};case"session.cron_cancelled":case"session.cron_at_cancelled":return{...r,type:"cron_cancel",color:"magenta",detail:"cron off"};case"session.cron_at_completed":return{...r,type:"cron_cancel",color:"magenta",detail:"cron done"};case"session.command_received":return{...r,type:"cmd_recv",color:"magenta",detail:`/${t?.data?.cmd||"?"}`};case"session.command_completed":return{...r,type:"cmd_done",color:"magenta",detail:`/${t?.data?.cmd||"?"} ok`};case"session.compaction_start":return{...r,type:"compaction",color:"gray",detail:"compaction…"};case"session.compaction_complete":return{...r,type:"compaction",color:"gray",detail:"compacted"};case"session.error":return{...r,type:"error",color:"red",detail:i||"error"};default:return null}}function xo(t=[]){const e=[];for(const s of t||[]){const n=Dl(s);n&&e.push({...n,nodeLabel:Bl(n.type)?"orch":n.nodeLabel||"orch"})}return e}function Hl(t=[]){const e=[];for(let s=0;s<t.length;s+=1){const n=t[s];if(n?.type!=="spawn"||n?.nodeLabel!=="orch"){e.push(n);continue}let i=1;for(;s+i<t.length;){const o=t[s+i];if(o?.type!=="spawn"||o?.nodeLabel!=="orch"||o?.time!==n.time)break;i+=1}if(i===1){e.push(n);continue}e.push({...n,detail:`spawn x${i}`}),s+=i-1}return e}function Gl(t){const e=String(t?.error||"").trim();if(!e)return null;const s=zs(t);if(!s)return null;const n=t?.updatedAt?Number(t.updatedAt):Date.now(),i=Number.isFinite(n)?n:Date.now();return{time:ce(i),createdAtMs:i,nodeLabel:"orch",color:s==="failed"?"red":"yellow",detail:`${s==="failed"?"ERR":"WARN"} ${bo(e,20)||(s==="failed"?"error":"warning")}`,type:s==="failed"?"error":"warning"}}function jl(t,e){const s=Gl(e);return!s||(t||[]).some(i=>!i||i.nodeLabel!=="orch"||i.detail!==s.detail?!1:Math.abs(Number(i.createdAtMs||0)-s.createdAtMs)<=6e4)?t:[...t||[],s]}function Ul(t,e,s){if(!Number.isFinite(e)||!Number.isFinite(s)||s<e)return[];const n=new Set;for(const i of t.history.bySessionId.values()){const o=xo(i?.events||[]);for(const r of o){if(!r?.nodeLabel||r.nodeLabel==="orch")continue;const a=Number(r.createdAtMs||0);Number.isFinite(a)&&(a<e||a>s||n.add(r.nodeLabel))}}return Array.from(n).sort((i,o)=>i.localeCompare(o))}function Wl(t,e){const s=new Set;for(const n of t.history.bySessionId.values())for(const i of n?.events||[]){if(!Io(i,e))continue;const o=qt(i?.workerNodeId);o&&s.add(o)}return Array.from(s).sort((n,i)=>n.localeCompare(i))}function Vl(t,e,s){const n=[{text:$e("TIME",e),color:"white",bold:!0},{text:" ",color:null}];return t.forEach((i,o)=>{o>0&&n.push({text:" ",color:null}),n.push({text:$e(i,s),color:"white",bold:!0})}),n}function ql(t,e,s){return F(`${"-".repeat(e)} ${t.map(()=>"─".repeat(s)).join(" ")}`,"gray")}function Kl(t,e,s){const n=t?.orchestration?.bySessionId?.[e?.sessionId]||null;let i="loading orchestration stats...";if(n)if(n.loading&&!n.stats)i="loading orchestration stats...";else if(!n.stats)i="orchestration stats unavailable";else{const o=n.stats,r=[],a=[];if(typeof o.orchestrationVersion=="string"&&o.orchestrationVersion&&(r.push(`v ${o.orchestrationVersion}`),a.push(`v${o.orchestrationVersion}`)),o.historyEventCount!=null&&(r.push(`hist ${Number(o.historyEventCount)||0} ev`),a.push(`h${Number(o.historyEventCount)||0}`)),o.historySizeBytes!=null){const l=ne(o.historySizeBytes);r.push(l),a.push(l)}o.queuePendingCount!=null&&(r.push(`q ${Number(o.queuePendingCount)||0}`),a.push(`q${Number(o.queuePendingCount)||0}`)),o.kvUserKeyCount!=null&&(r.push(`kv ${Number(o.kvUserKeyCount)||0} keys`),a.push(`kv${Number(o.kvUserKeyCount)||0}`)),o.kvTotalValueBytes!=null&&r.push(ne(o.kvTotalValueBytes)),i=s<=40?a.join(" · "):r.join(" | "),i||(i="orchestration stats unavailable")}return s<=52?[q([{text:"Stats ",color:"cyan",bold:!0},{text:i,color:"white"}],Math.max(18,s))]:Q({title:"Stats",body:i,width:Math.max(24,s),titleColor:"cyan",borderColor:"gray",fitToContent:!0}).slice(0,-1)}function zl(t,e,s,n){const i=e.includes(t.nodeLabel)?t.nodeLabel:e.includes("…")?"…":e[e.length-1],o=[{text:$e(t.time||"",s),color:"white"},{text:" ",color:null}];return e.forEach((r,a)=>{a>0&&o.push({text:" ",color:null}),r===i?o.push({text:$e(t.detail||"",n),color:t.color||"white",bold:!!t.bold,underline:!!t.underline,...t.completedTurn!=null?{completedTurn:t.completedTurn}:{}}):o.push({text:$e("│",n),color:"gray"})}),o}function Yl(t,e){const s=[];return t.forEach((n,i)=>{i>0&&s.push({text:" ",color:null}),s.push({text:$e(n,e),color:"white",bold:!0})}),s}function Ql(t,e,s,n={}){const i=!!n?.allowWideColumns,o=Kl(t,e,s),r=t.history.bySessionId.get(e.sessionId),a=jl(Hl(xo(r?.events||[])),e);if(a.length===0)return{stickyLines:o,lines:[F("No events yet - interact with this session to populate the sequence diagram.")]};const l=an(t),p=a.filter(v=>Ll(v,l)),u=(p.length>0?p:a).slice(-48),d=Ul(t,l.startMs,l.endMs),f=Array.from(new Set(u.map(v=>v.nodeLabel).filter(v=>v&&v!=="orch"))).sort((v,T)=>v.localeCompare(T)),h=d.length>0?d:f,m=8,g=Math.max(18,s),I=Math.max(1,Math.floor((g-m-1)/6));let y=["orch",...h];if(!i&&y.length>I){const v=Math.max(1,I-1);y=[...y.slice(0,v),"…"]}const x=Math.max(0,y.length-1),E=Math.max(4,Math.floor((g-m-1-x)/Math.max(1,y.length)));return{stickyLines:[...o,F(`Window: ${l.label}`,"gray"),Vl(y,m,E),ql(y,m,E)],lines:u.map(v=>zl(v,y,m,E))}}function Xl(t){const e=[],s=new Set;for(const n of t.sessions.flat||[])!n?.sessionId||s.has(n.sessionId)||(s.add(n.sessionId),e.push(n.sessionId));for(const n of Object.keys(t.sessions.byId||{}))s.has(n)||(s.add(n),e.push(n));return e}function Jl(t,e=null){const s=t?.events||[];for(let n=s.length-1;n>=0;n-=1){if(e&&!Io(s[n],e))continue;const i=qt(s[n]?.workerNodeId);if(i)return i}return null}function Zl(t,e,s,n){const i=s>=16?t?.isSystem?St(t,e):t?.title||K(t?.sessionId):K(t?.sessionId),o=t?.isSystem?"⚙ ":`${so(t)||"."} `,r=$e(`${o}${i}`,s);return n?Te(r):{text:r,color:t?.isSystem?"yellow":pt(t),bold:!!t?.isSystem}}function ec(t,e,s={}){const n=!!s?.allowWideColumns,i=Xl(t);if(i.length===0)return[F("No sessions available for the node map.","gray")];const o=an(t),r=new Map,a=Wl(t,o);let l=0,p=0;for(const y of i){const x=t.sessions.byId[y];if(!x)continue;const E=t.history.bySessionId.get(y);E?.events||(l+=1);const v=Jl(E,o);!v||!a.includes(v)||(p+=1,r.has(v)||r.set(v,[]),r.get(v).push(x))}if(a.length===0)return[F(`No worker activity in the ${o.label} window.`,"gray")];const u=Math.max(18,e),d=Math.max(1,Math.floor((u+1)/10));let f=a;if(!n&&a.length>d){const y=Math.max(0,d-1),x=[],E=a.slice(0,y);for(const v of a.slice(y))x.push(...r.get(v)||[]);r.set("…",x),f=[...E,"…"]}const h=Math.max(0,f.length-1),m=Math.max(8,Math.floor((u-h)/Math.max(1,f.length))),g=f.reduce((y,x)=>Math.max(y,(r.get(x)||[]).length),0),I=[F(`Window: ${o.label}`,"gray"),Yl(f,m),F(f.map(()=>"─".repeat(m)).join(" "),"gray")];for(let y=0;y<g;y+=1){const x=[];f.forEach((E,v)=>{v>0&&x.push({text:" ",color:null});const T=(r.get(E)||[])[y];if(!T){x.push({text:" ".repeat(m),color:null});return}x.push(Zl(T,t.branding?.title||"PilotSwarm",m,T.sessionId===t.sessions.activeSessionId))}),I.push(x)}return l>0&&(I.push(F("","gray")),I.push(F(`Loading worker history for ${l} session(s)…`,"gray"))),p===0&&(I.push(F("","gray")),I.push(F(`No sessions mapped onto worker nodes in the ${o.label} window.`,"gray"))),I}function tc(t,e=72){const s=t.ui.modal;if(!s||s.type!=="modelPicker")return null;const n=Array.isArray(s.groups)?s.groups:[],i=Math.max(0,Number(s.selectedIndex)||0),o=Math.max(24,e-4),r=[],a=[];let l=0;for(const h of n){const m=q([{text:`${h.providerId}`,color:"cyan",bold:!0},{text:` (${h.providerType||"provider"})`,color:"gray"}],o);r.push(m),a.push(null);for(const g of h.models||[]){const I=Array.isArray(s.items)?s.items.findIndex(v=>v.id===g.id):-1,y=I===i,x=q([{text:"· ",color:"gray"},{text:g.modelName||g.qualifiedName||g.id,color:"white",bold:!!g.isDefault},...g.cost?[{text:` [${g.cost}]`,color:"gray"}]:[],...g.isDefault?[{text:" ← current default",color:"gray"}]:[]],o),E=y?Te(x.map(v=>v.text).join("").padEnd(o," ")):x;y&&(l=r.length),r.push(E),a.push(I>=0?I:null)}}const p=Array.isArray(s.items)&&s.items[i]||null,u=Array.isArray(p?.supportedReasoningEfforts)?p.supportedReasoningEfforts.filter(Boolean):[],d=typeof p?.defaultReasoningEffort=="string"?p.defaultReasoningEffort:null,f=p?[[{text:p.modelName||p.qualifiedName||p.id,color:"white",bold:!0}],[{text:`${p.providerId} (${p.providerType||"provider"})`,color:"gray"}],...p.cost?[[{text:`Cost: ${p.cost}`,color:"gray"}]]:[],...u.length>0?[[{text:`Reasoning: ${u.join(", ")}`,color:"gray"}]]:[],...d?[[{text:`Default reasoning: ${d}`,color:"gray"}]]:[],[{text:"",color:"gray"}],[{text:p.description||"No description available for this model.",color:p.description?"white":"gray"}]]:[[{text:"No model selected.",color:"gray"}]];return{title:s.title||"Select model for new session",rows:r,rowItemIndexes:a,selectedRowIndex:l,detailsTitle:"Model Details",detailsLines:f,idealWidth:Math.min(Math.max(46,r.reduce((h,m)=>Array.isArray(m)?Math.max(h,Xe(m)):Math.max(h,String(m?.text||"").length),0)+4),e)}}function sc(t,e=76){const s=t.ui.modal;if(!s||s.type!=="sessionAgentPicker")return null;const n=Array.isArray(s.items)?s.items:[],i=Math.max(0,Number(s.selectedIndex)||0),o=Math.max(24,e-4),r=n.map((d,f)=>{const h=f===i,m=q([{text:d?.kind==="generic"?"○ ":"· ",color:"gray"},{text:d?.title||d?.agentName||d?.id||"Agent",color:"white",bold:!0},...d?.kind==="generic"?[{text:" [generic]",color:"gray"}]:[{text:` (${d?.agentName||d?.id||"agent"})`,color:"gray"}]],o);return h?Te(m.map(g=>g.text).join("").padEnd(o," ")):m}),a=n[i]||null,l=s.sessionOptions?.model||null,p=s.sessionOptions?.reasoningEffort||null,u=a?[[{text:a.title||a.agentName||a.id||"Agent",color:"white",bold:!0}],...a.kind==="generic"?[[{text:"Open-ended session",color:"gray"}]]:[[{text:a.agentName||a.id||"agent",color:"gray"}]],...l?[[{text:`Model: ${l}`,color:"gray"}]]:[],...p?[[{text:`Reasoning: ${p}`,color:"gray"}]]:[],[{text:"",color:"gray"}],[{text:a.description||(a.kind==="generic"?"Create a general-purpose session without a specialized named agent.":"No description available for this agent."),color:a.description?"white":"gray"}],[{text:"",color:"gray"}],[{text:a.tools?.length?`Tools: ${a.tools.join(", ")}`:"Tools: system defaults only",color:"gray"}]]:[[{text:"No agent selected.",color:"gray"}]];return{title:s.title||"Select agent for new session",rows:r,selectedRowIndex:i,detailsTitle:"Agent Details",detailsLines:u,idealWidth:Math.min(Math.max(52,r.reduce((d,f)=>Array.isArray(f)?Math.max(d,Xe(f)):Math.max(d,String(f?.text||"").length),0)+4),e)}}function nc(t,e=64){const s=t.ui.modal;if(!s||s.type!=="reasoningEffortPicker")return null;const n=Array.isArray(s.items)?s.items:[],i=Math.max(0,Number(s.selectedIndex)||0),o=Math.max(24,e-4),r=n.map((u,d)=>{const f=d===i,h=q([{text:"· ",color:"gray"},{text:String(u?.label||u?.id||"effort"),color:"white",bold:!0},...u?.isDefault?[{text:" ← model default",color:"gray"}]:[]],o);return f?Te(h.map(m=>m.text).join("").padEnd(o," ")):h}),a=n[i]||null,l=s.modelItem||null,p=[[{text:l?.modelName||l?.qualifiedName||"Selected model",color:"white",bold:!0}],[{text:`${l?.providerId||"provider"} (${l?.providerType||"provider"})`,color:"gray"}],[{text:"",color:"gray"}],[{text:a?.id?`Using reasoning effort: ${a.id}`:"Choose an effort.",color:"white"}]];return{title:s.title||"Select reasoning effort",rows:r,selectedRowIndex:i,detailsTitle:"Reasoning Details",detailsLines:p,idealWidth:Math.min(Math.max(46,r.reduce((u,d)=>Array.isArray(d)?Math.max(u,Xe(d)):Math.max(u,String(d?.text||"").length),0)+4),e)}}function ic(t,e=72){const s=t.ui.modal;if(!s||s.type!=="sessionGroupPicker")return null;const n=Array.isArray(s.items)?s.items:[],i=Math.max(0,Number(s.selectedIndex)||0),o=Math.max(24,e-4),r=Array.isArray(s.sessionIds)?s.sessionIds.length:0,a=n.map((u,d)=>{const f=d===i,h=u?.kind==="noGroup"?"○ ":u?.kind==="newGroup"?"+ ":"🗂 ",m=q([{text:h,color:u?.kind==="group"?"cyan":"gray",bold:u?.kind!=="noGroup"},{text:u?.label||u?.groupId||"Group",color:"white",bold:!0},...u?.kind==="group"?[{text:` (${u.memberCount??0})`,color:"gray"}]:[]],o);return f?Te(m.map(g=>g.text).join("").padEnd(o," ")):m}),l=n[i]||null,p=l?[[{text:l.label||l.groupId||"Group",color:"white",bold:!0}],[{text:`${r} session${r===1?"":"s"} selected`,color:"gray"}],...l.kind==="group"?[[{text:`${l.memberCount??0} current member${l.memberCount===1?"":"s"}`,color:"gray"}]]:[],[{text:"",color:"gray"}],[{text:l.description||"Move selected session(s) to this group.",color:"white"}]]:[[{text:"No group selected.",color:"gray"}]];return{title:s.title||"Move to Group",rows:a,selectedRowIndex:i,detailsTitle:"Move Details",detailsLines:p,idealWidth:Math.min(Math.max(50,a.reduce((u,d)=>Array.isArray(d)?Math.max(u,Xe(d)):Math.max(u,String(d?.text||"").length),0)+4),e)}}function oc(t,e=76){const s=t.ui.modal;if(!s||s.type!=="renameSession")return null;const n=String(s.value||""),i=typeof s.agentTitlePrefix=="string"&&s.agentTitlePrefix.trim()?s.agentTitlePrefix.trim():null,o=String(s.currentTitle||"").trim(),r=n.trim()?i?`${i}: ${n.trim()}`:n.trim():i?`${i}: …`:"…",a=[[{text:"Current: ",color:"gray"},{text:o||"(untitled session)",color:o?"white":"gray"}],[{text:"Saved as: ",color:"gray"},{text:r,color:"white",bold:!0}],...i?[[{text:"Named-agent prefix stays fixed.",color:"gray"}]]:[]];return{title:s.title||"Rename Session",value:n,cursorIndex:Math.max(0,Math.min(Number(s.cursorIndex)||0,n.length)),placeholder:i?"Type the title after the fixed agent name":"Type a session title",helpTitle:"Rename Rules",helpLines:[[{text:"Enter",color:"cyan",bold:!0},{text:" save ",color:"gray"},{text:"Esc",color:"cyan",bold:!0},{text:" cancel",color:"gray"}],[{text:"",color:"gray"}],[{text:"Manual titles stop future automatic LLM title changes for this session.",color:"gray"}]],detailsLines:a,idealWidth:Math.min(Math.max(56,we(o||"(untitled session)")+18,we(r)+18),e)}}function rc(t,e=76){const s=t.ui.modal;if(!s||s.type!=="sessionGroupName")return null;const n=String(s.value||""),i=Array.isArray(s.sessionIds)?s.sessionIds.length:0,o=n.trim()||"…";return{title:s.title||"New Group",value:n,cursorIndex:Math.max(0,Math.min(Number(s.cursorIndex)||0,n.length)),placeholder:"Type a group name",helpTitle:"Group Name",helpLines:[[{text:"Enter",color:"cyan",bold:!0},{text:" create and move ",color:"gray"},{text:"Esc",color:"cyan",bold:!0},{text:" cancel",color:"gray"}],[{text:"",color:"gray"}],[{text:`The new group will contain ${i} selected session${i===1?"":"s"}.`,color:"gray"}]],detailsLines:[[{text:"New group: ",color:"gray"},{text:o,color:"white",bold:!0}],[{text:"Groups are containers only; session actions remain per-session.",color:"gray"}]],idealWidth:Math.min(Math.max(56,we(o)+18),e)}}function ac(t,e=82){const s=t.ui.modal;if(!s||s.type!=="artifactUpload")return null;const n=String(s.value||""),i=s.sessionId||t.ui.promptAttachments?.[0]?.sessionId||t.sessions?.activeSessionId||null,o=i&&t.sessions?.byId?.[i]||null,r=i?o?Js(o,t.branding?.title):K(i):"A new session will be created on upload",a=[[{text:"Target: ",color:"gray"},{text:r,color:i?"white":"gray",bold:!!i}]];return{title:s.title||"Upload Artifact",value:n,cursorIndex:Math.max(0,Math.min(Number(s.cursorIndex)||0,n.length)),placeholder:"~/path/to/file.md",helpTitle:"Upload Rules",helpLines:[[{text:"Enter",color:"cyan",bold:!0},{text:" upload ",color:"gray"},{text:"Esc",color:"cyan",bold:!0},{text:" cancel",color:"gray"}],[{text:"",color:"gray"}],[{text:"The file is uploaded into this session's artifact store immediately.",color:"gray"}],[{text:"Use the files browser or @-driven browsing in the prompt to reference it after upload.",color:"gray"}]],detailsLines:a,idealWidth:Math.min(Math.max(60,we(n||"~/path/to/file.md")+20,we(r)+20),e)}}function ln(t,e={},s=96,n="Filters",i="Choose how this pane is filtered and rendered."){const o=Array.isArray(t.items)?t.items:[],r=Math.max(0,Number(t.selectedIndex)||0),a=o[r]||null,l=o.map((p,u)=>{const d=e?.[p.id]||p.options?.[0]?.id,f=(p.options||[]).map(h=>h.id===d?Te(h.label):{text:h.label,color:"white"});return{id:p.id,title:p.label,focused:u===r,description:p.description||"",lines:f.length>0?f:[{text:"No options available.",color:"gray"}],idealWidth:Math.max(20,String(p.label||"").length+4,...(p.options||[]).map(h=>String(h?.label||"").length+4))}});return{title:t.title||n,panes:l,helpTitle:a?.label||n,helpLines:[[{text:a?.description||i,color:"white"}],[{text:"",color:"gray"}],[{text:"Tab/Shift-Tab",color:"cyan",bold:!0},{text:" switch filter ",color:"gray"},{text:"Up/Down",color:"cyan",bold:!0},{text:" change value ",color:"gray"},{text:"Enter",color:"cyan",bold:!0},{text:" close ",color:"gray"},{text:"Esc",color:"cyan",bold:!0},{text:" cancel",color:"gray"}]],footerRuns:[{text:"Tab/Shift-Tab",color:"cyan",bold:!0},{text:" switch filter · ",color:"gray"},{text:"Up/Down",color:"cyan",bold:!0},{text:" change value · ",color:"gray"},{text:"Enter",color:"cyan",bold:!0},{text:" close · ",color:"gray"},{text:"Esc",color:"cyan",bold:!0},{text:" cancel",color:"gray"}],idealWidth:Math.min(Math.max(72,l.reduce((p,u)=>p+u.idealWidth,0)+Math.max(0,l.length-1)*2+4),s)}}function Eo(t,e={},s={}){return t?t.kind==="all"?e?.all===!0:e?.all===!0?!1:t.kind==="system"?e?.includeSystem===!0:t.kind==="unowned"?e?.includeUnowned===!0:t.kind==="me"?e?.includeMe===!0&&!!Ht(s?.principal):t.kind==="owner"?Array.isArray(e?.ownerKeys)&&e.ownerKeys.includes(t.ownerKey):!1:!1}function Vn(t=[],e={},s={}){if(e?.all===!0)return"All sessions";const n=t.filter(i=>i?.kind!=="all"&&Eo(i,e,s)).map(i=>i.kind==="me"?"Me":i.label);return n.length>0?n.join(" + "):"All sessions"}function lc(t,e=88){const s=t.ui.modal;if(!s||s.type!=="sessionOwnerFilter")return null;const n=Array.isArray(s.items)?s.items:[],i=t.sessions?.ownerFilter||{all:!0},o=t.auth||{},r=Math.max(0,Math.min(Number(s.selectedIndex)||0,Math.max(0,n.length-1))),a=n[r]||null,l=n.map((u,d)=>{const f=Eo(u,i,o),h=u.kind==="system"?"yellow":u.kind==="unowned"?"gray":u.kind==="all"?"cyan":"white",m=[{text:f?"[x] ":"[ ] ",color:f?"cyan":"gray",bold:f},{text:u.label||u.id,color:h,bold:f}];return d===r?Xi(m,{preserveColors:!0}):m}),p=[[{text:"Active: ",color:"gray"},{text:Vn(n,i,o),color:"white",bold:!0}],[{text:"",color:"gray"}],[{text:a?.description||"Toggle which session owners appear in the session list.",color:"white"}],[{text:"",color:"gray"}],[{text:"Space",color:"cyan",bold:!0},{text:" toggle ",color:"gray"},{text:"Esc",color:"cyan",bold:!0},{text:" close",color:"gray"}]];return{title:s.title||"Session Filter",rows:l.length>0?l:[{text:"No filter entries available.",color:"gray"}],selectedRowIndex:r,detailsTitle:a?.label||"Session Filter",detailsLines:p,idealWidth:Math.min(Math.max(48,l.reduce((u,d)=>Math.max(u,Array.isArray(d)?Xe(d):we(d?.text||"")),0)+8,we(Vn(n,i,o))+16),e)}}function cc(t,e=96){const s=t.ui.modal;return!s||s.type!=="logFilter"?null:ln(s,t.logs?.filter||{},e,"Log Filters","Choose how the log pane is filtered and rendered.")}function uc(t,e=88){const s=t.ui.modal;return!s||s.type!=="filesFilter"?null:ln(s,t.files?.filter||{},e,"Files Filter","Choose whether the files browser shows the selected session tree or aggregates artifacts across all sessions.")}function dc(t,e=88){const s=t.ui.modal;if(!s||s.type!=="artifactPicker")return null;const n=Array.isArray(s.items)?s.items:[],i=Math.max(0,Number(s.selectedIndex)||0),o=Math.max(28,e-4),r=n.filter(h=>h.kind==="artifact"),a=n.filter(h=>h.kind==="url"),l=r.reduce((h,m)=>{const g=t.files?.bySessionId?.[m.sessionId]?.downloads?.[m.filename];return h+(g?.localPath?1:0)},0),p=Math.max(0,r.length-l),u=n.map((h,m)=>{let g;if(h.kind==="downloadAll")g=q([{text:"dl ",color:"cyan",bold:!0},{text:"Download All",color:"white",bold:!0},{text:` [${p} pending]`,color:"gray"}],o);else if(h.kind==="url")g=q([{text:"go ",color:"cyan",bold:!0},{text:h.text&&h.text!==h.href?h.text:h.href,color:"white",bold:!0},...h.text&&h.text!==h.href?[{text:` ${h.href}`,color:"gray"}]:[]],o);else{const I=t.files?.bySessionId?.[h.sessionId]?.downloads?.[h.filename];g=q([{text:I?.localPath?"ok ":"dl ",color:I?.localPath?"green":"cyan",bold:!0},{text:`${K(h.sessionId)}/`,color:"gray"},{text:h.filename,color:"white"}],o)}return m!==i?g:Te(g.map(I=>I.text).join("").padEnd(o," "))}),d=n[i]||null;let f=[[{text:"No linked item selected.",color:"gray"}]];if(d?.kind==="downloadAll")f=[[{text:`${r.length} artifacts available`,color:"white",bold:!0}],...a.length>0?[[{text:`${a.length} links available`,color:"gray"}]]:[],[{text:`${l} already downloaded`,color:"gray"}],[{text:`${p} pending download`,color:"gray"}],...s.exportDirectory?[[{text:`Save location: ${s.exportDirectory}`,color:"white"}]]:[],[{text:"",color:"gray"}],[{text:"Press Enter to download all pending artifacts.",color:"white"}],[{text:"Press a or Esc to close the picker.",color:"gray"}]];else if(d?.kind==="url")f=[[{text:d.text||d.href,color:"white",bold:!0}],[{text:d.href,color:"gray"}],[{text:"",color:"gray"}],[{text:"Press Enter to open this link in the browser.",color:"white"}],[{text:"Press a or Esc to close the picker.",color:"gray"}]];else if(d?.kind==="artifact"){const h=t.sessions?.byId?.[d.sessionId]||null,m=t.files?.bySessionId?.[d.sessionId]?.downloads?.[d.filename]||null;f=[[{text:d.filename,color:"white",bold:!0}],[{text:h?Js(h,t.branding?.title):K(d.sessionId),color:"gray"}],...m?.localPath?[[{text:`Saved to: ${m.localPath}`,color:"white"}]]:s.exportDirectory?[[{text:`Save location: ${s.exportDirectory}`,color:"white"}]]:[],[{text:"",color:"gray"}],[{text:m?.localPath?"Press Enter to download this artifact again.":"Press Enter to download this artifact.",color:"white"}],[{text:"Press a or Esc to close the picker.",color:"gray"}]]}return{title:s.title||"Linked Items",rows:u.length>0?u:[{text:"No linked items available.",color:"gray"}],selectedRowIndex:i,detailsTitle:"Linked Item Details",detailsLines:f,confirmLabel:a.length>0?r.length>0?"Open / Download":"Open":"Download",idealWidth:Math.min(Math.max(54,u.reduce((h,m)=>Array.isArray(m)?Math.max(h,Xe(m)):Math.max(h,String(m?.text||"").length),0)+4),e)}}function B(t){return t==null||!Number.isFinite(t)?"0":t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e4?`${(t/1e3).toFixed(1)}K`:t>=1e3?t.toLocaleString("en-US"):String(t)}function vo(t){if(!t)return"—";const e=Date.now()-t;return e<6e4?`${Math.max(1,Math.floor(e/1e3))}s ago`:e<36e5?`${Math.floor(e/6e4)}m ago`:e<864e5?`${Math.floor(e/36e5)}h ago`:`${Math.floor(e/864e5)}d ago`}function Et(t){if(!t)return"—";const e=t instanceof Date?t:new Date(t);return Number.isNaN(e.getTime())?"—":e.toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",second:"2-digit",timeZoneName:"short"})}function ot(t){return["session","fleet","users"].includes(t)?t:"session"}function Kt(t,e){const s=ot(t),n=[{text:"View ",color:"cyan",bold:!0}];for(const i of["session","fleet","users"])n.push({text:i===s?`[${i}]`:i,color:i===s?"magenta":"gray",bold:i===s}),n.push({text:" ",color:"gray"});return n.push({text:" [f cycle]",color:"gray"}),q(n,e)}function fc(t,e,s){if(!e)return[F("No session selected.")];const n=t.sessionStats?.bySessionId?.[e.sessionId]||null;if(!n||n.loading&&!n.summary)return[F("Loading session stats...")];const i=n.summary;if(!i)return[F("Session stats unavailable.")];const o=[],r=Math.max(24,s);o.push(Kt("session",r)),o.push(F("")),o.push(q([{text:"Session ",color:"cyan",bold:!0},{text:K(e.sessionId),color:"white"}],r));const a=e.isSystem?"system":e.owner?"user":"unowned",l=e.isSystem?"system":e.owner?Ys(e.owner):"(?) unowned",p=e.owner?.email||"—";o.push(q([{text:"Owner ",color:"cyan",bold:!0},{text:l,color:e.owner?"white":"gray"}],r)),o.push(q([{text:"Email ",color:"cyan",bold:!0},{text:p,color:e.owner?.email?"white":"gray"}],r)),o.push(q([{text:"Type ",color:"cyan",bold:!0},{text:a,color:a==="user"?"white":"gray"}],r)),i.agentId&&o.push(q([{text:"Agent ",color:"cyan",bold:!0},{text:i.agentId,color:"white"}],r));const u=ho(i.model||e.model,i.reasoningEffort||e.reasoningEffort);u&&o.push(q([{text:"Model ",color:"cyan",bold:!0},{text:u,color:"white"}],r)),e.createdAt&&o.push(q([{text:"Created ",color:"cyan",bold:!0},{text:Et(e.createdAt),color:"white"}],r)),e.updatedAt&&o.push(q([{text:"Updated ",color:"cyan",bold:!0},{text:Et(e.updatedAt),color:"white"}],r)),o.push(F(""));const d=Array.isArray(n.tokensByModel)?n.tokensByModel:[];d.length>1&&(o.push(...Q({title:"Models",body:d.map(O=>`${yl(O.model)} · ${O.turnCount||0} turns · ${B(O.totalTokensInput)} in / ${B(O.totalTokensOutput)} out`).join(`
48
- `),width:r,titleColor:"cyan",borderColor:"gray",fitToContent:!0})),o.push(F("")));const f=(i.tokensInput||0)+(i.tokensOutput||0),h=i.cacheHitRatio,m=h==null?"—":`${(h*100).toFixed(1)}%`;o.push(...Q({title:"Tokens",body:Be([["Input",B(i.tokensInput)],["Output",B(i.tokensOutput)],["Total",B(f)],["Cache Read",B(i.tokensCacheRead)],["Cache Write",B(i.tokensCacheWrite)],["Hit Ratio",m]]),width:r,titleColor:"green",borderColor:"gray",fitToContent:!0})),o.push(F("")),o.push(...Q({title:"Persistence",body:Be([["Snapshot",ne(i.snapshotSizeBytes)],["Dehydrations",String(i.dehydrationCount)],["Hydrations",String(i.hydrationCount)],["Lossy Handoffs",String(i.lossyHandoffCount)],["Last Dehydrated",i.lastDehydratedAt?Et(i.lastDehydratedAt):null],["Last Hydrated",i.lastHydratedAt?Et(i.lastHydratedAt):null]]),width:r,titleColor:"yellow",borderColor:"gray",fitToContent:!0}));const g=n.treeStats?.tree;if(g&&g.sessionCount>1){const O=g.cacheHitRatio,M=O==null?"—":`${(O*100).toFixed(1)}%`,k=(g.totalTokensInput||0)+(g.totalTokensOutput||0);o.push(F("")),o.push(...Q({title:`Tree (${g.sessionCount} sessions)`,body:Be([["Input",B(g.totalTokensInput)],["Output",B(g.totalTokensOutput)],["Total",B(k)],["Cache Read",B(g.totalTokensCacheRead)],["Cache Write",B(g.totalTokensCacheWrite)],["Hit Ratio",M],["Snapshot",ne(g.totalSnapshotSizeBytes)],["Dehydrations",String(g.totalDehydrationCount)],["Hydrations",String(g.totalHydrationCount)]]),width:r,titleColor:"magenta",borderColor:"gray",fitToContent:!0}));const N=Array.isArray(n.treeStats?.byModel)?n.treeStats.byModel:[];N.length>1&&(o.push(F("")),o.push(...Q({title:"Tree By Model",body:Sc(N),width:r,titleColor:"cyan",borderColor:"gray",fitToContent:!0})))}const I=Array.isArray(n.skillUsage)?n.skillUsage:[];I.length>0&&(o.push(F("")),o.push(...Q({title:`Skills (${I.length})`,body:qn(I,r),width:r,titleColor:"cyan",borderColor:"gray",fitToContent:!0})));const y=n.treeSkillUsage,x=Array.isArray(y?.rolledUp)?y.rolledUp:[],E=Array.isArray(y?.perSession)?y.perSession.length:0;x.length>0&&E>1&&(o.push(F("")),o.push(...Q({title:`Tree Skills (${x.length})`,body:qn(x,r),width:r,titleColor:"cyan",borderColor:"gray",fitToContent:!0})));const v=n.factsStats,T=n.treeFactsStats;if(v&&Array.isArray(v.rows)&&v.rows.length>0){o.push(F(""));const O=Co(v.rows),M=O?O.split(`
49
- `).length:0,k=`${v.totalCount} · ${ne(v.totalBytes)}`;let N=O;T&&T.totalCount>v.totalCount&&(N+=`
50
- Tree (${T.sessionIds.length} sessions): ${T.totalCount} · ${ne(T.totalBytes)}`),M>0&&o.push(...Q({title:`Facts (${k})`,body:N,width:r,titleColor:"blue",borderColor:"gray",fitToContent:!0}))}return o}function Be(t,e={}){const s=e.gap??2,n=(t||[]).filter(a=>Array.isArray(a)&&a[1]!=null&&a[1]!=="");if(n.length===0)return"";const i=n.reduce((a,[l])=>Math.max(a,String(l).length),0),o=n.reduce((a,[,l])=>Math.max(a,String(l).length),0),r=" ".repeat(s);return n.map(([a,l])=>`${String(a).padEnd(i)}${r}${String(l).padStart(o)}`).join(`
51
- `)}function zt(t,e){const s=String(t??"");if(!Number.isFinite(e)||e<=0)return s;const n=Math.floor(e);return s.length<=n?s:n<=1?s.slice(0,n):`${s.slice(0,n-1)}…`}function bt(t,e={}){const s=e.gap??2,n=(t||[]).filter(a=>Array.isArray(a)&&a.length>0);if(n.length===0)return"";const i=n.reduce((a,l)=>Math.max(a,l.length),0),o=new Array(i).fill(0);for(const a of n)for(let l=0;l<i;l+=1){const p=a[l]==null?"":String(a[l]);p.length>o[l]&&(o[l]=p.length)}const r=" ".repeat(s);return n.map(a=>a.map((l,p)=>{const u=l==null?"":String(l);return p===0?u.padEnd(o[p]):u.padStart(o[p])}).join(r)).join(`
52
- `)}function qn(t,e){const s=t.slice().sort((d,f)=>(f.invocations||0)-(d.invocations||0)).slice(0,12),n=s.map(d=>`${d.invocations||0} inv`),i=n.reduce((d,f)=>Math.max(d,f.length),0),a=4+2+i,l=Number.isFinite(e)&&e>0?Math.max(8,Math.floor(e)-a):1/0,p=s.map((d,f)=>{const h=d.kind==="learned"?"L":"S",m=String(d.name||"(unknown)");return[zt(`${h} ${m}`,l),n[f]]}),u=bt(p);return t.length>s.length?`${u}
53
- … ${t.length-s.length} more`:u}function Co(t){const s=t.slice().sort((n,i)=>(i.factCount||0)-(n.factCount||0)).map(n=>[String(n.namespace||"(other)"),String(n.factCount||0),ne(n.totalValueBytes||0)]);return bt(s)}function pc(t){const e=t.oldestUnreconciledAgeSeconds==null?"-":at(Math.max(0,Number(t.oldestUnreconciledAgeSeconds)||0));return bt([["pending",String(Number(t.pendingTotal)||0)],["unreconciled",String(Number(t.unreconciled)||0)],["ttl-blocked",String(Number(t.ttlBlocked)||0)],["oldest",e],["reconciled",String(Number(t.reconciledUnswept)||0)]])}function hc(t){switch(t){case"facts_search":return"facts search";case"facts_similar":return"facts similar";case"search_skills":return"skill search";case"graph_search_nodes":return"graph nodes";case"graph_search_edges":return"graph edges";case"graph_neighbourhood":return"graph hood";default:return String(t||"retrieval")}}function mc(t,e){const s=t.slice().sort((d,f)=>(Number(f.calls)||0)-(Number(d.calls)||0)).slice(0,12),n=s.map(d=>`${Number(d.calls)||0} calls`),i=s.map(d=>`${Number(d.totalResults)||0} res`),o=n.reduce((d,f)=>Math.max(d,f.length),0),r=i.reduce((d,f)=>Math.max(d,f.length),0),a=6+o+2+r,l=Number.isFinite(e)&&e>0?Math.max(10,Math.floor(e)-a):1/0,p=s.map((d,f)=>{const h=d.namespace?` ${d.namespace}`:"";return[zt(`${hc(d.operation)}${h}`,l),n[f],i[f]]}),u=bt(p);return t.length>s.length?`${u}
54
- … ${t.length-s.length} more`:u}function gc(t,e){const s=t.fleetStats;if(!s||s.loading&&!s.data)return[F("Loading fleet stats...")];const n=s.data;if(!n)return[F("Fleet stats unavailable.")];const i=[],o=Math.max(24,e);i.push(Kt("fleet",o)),i.push(F(""));const r=n.windowStart?`Since: ${vo(n.windowStart).replace(" ago","")}`:"All time",a=n.earliestSessionCreatedAt?`Earliest: ${new Date(n.earliestSessionCreatedAt).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}`:"";i.push(q([{text:r,color:"cyan"},{text:a?` ${a}`:"",color:"gray"}],o)),i.push(q([{text:`Sessions: ${n.totals.sessionCount}`,color:"white"},{text:` Tokens: ${B(n.totals.totalTokensInput)} in / ${B(n.totals.totalTokensOutput)} out`,color:"white"}],o)),i.push(F(""));const l=new Map;for(const g of n.byAgent||[]){const I=g.model||"(default)",y=l.get(I)||{totalTokensInput:0,totalTokensOutput:0,totalTokensCacheRead:0,totalTokensCacheWrite:0,totalSnapshotSizeBytes:0,turnCount:0};y.totalTokensInput+=Number(g.totalTokensInput)||0,y.totalTokensOutput+=Number(g.totalTokensOutput)||0,y.totalTokensCacheRead+=Number(g.totalTokensCacheRead)||0,y.totalTokensCacheWrite+=Number(g.totalTokensCacheWrite)||0,y.totalSnapshotSizeBytes+=Number(g.totalSnapshotSizeBytes)||0,y.turnCount+=Number(g.turnCount)||0,l.set(I,y)}if(l.size>0){const g=[];for(const[I,y]of l.entries()){const x=y.totalTokensInput>0?y.totalTokensCacheRead/y.totalTokensInput:null;g.push(I),g.push(cn(y,x)),g.push("")}i.push(...Q({title:"Tokens By Model",body:g.join(`
55
- `).trimEnd(),width:o,titleColor:"cyan",borderColor:"gray",fitToContent:!0})),i.push(F(""))}const p=n.totals.cacheHitRatio,u=p==null?"—":`${(p*100).toFixed(1)}%`;i.push(...Q({title:"Fleet Totals",body:Be([["Sessions",String(n.totals.sessionCount)],["Tokens In",B(n.totals.totalTokensInput)],["Tokens Out",B(n.totals.totalTokensOutput)],["Total Tokens",B(n.totals.totalTokensInput+n.totals.totalTokensOutput)],["Cache Read",B(n.totals.totalTokensCacheRead)],["Cache Write",B(n.totals.totalTokensCacheWrite)],["Hit Ratio",u],["Snapshots",ne(n.totals.totalSnapshotSizeBytes)]]),width:o,titleColor:"green",borderColor:"gray",fitToContent:!0}));const d=(Array.isArray(s.skillUsage?.rows)?s.skillUsage.rows:[]).filter(g=>!(g&&g.agentId==="facts-manager"&&String(g.name||"").startsWith("skills/")));d.length>0&&(i.push(F("")),i.push(...Q({title:`Fleet Skills (${d.length})`,body:yc(d,e),width:o,titleColor:"cyan",borderColor:"gray",fitToContent:!0})));const f=Array.isArray(s.retrievalUsage?.rows)?s.retrievalUsage.rows:[];if(f.length>0){const g=f.reduce((I,y)=>I+(Number(y.calls)||0),0);i.push(F("")),i.push(...Q({title:`Fleet Retrieval (${B(g)})`,body:mc(f,e),width:o,titleColor:"magenta",borderColor:"gray",fitToContent:!0}))}const h=s.sharedFactsStats;if(h&&Array.isArray(h.rows)&&h.rows.length>0){i.push(F(""));const g=`${h.totalCount} · ${ne(h.totalBytes)}`;i.push(...Q({title:`Shared Facts (${g})`,body:Co(h.rows),width:o,titleColor:"blue",borderColor:"gray",fitToContent:!0}))}const m=s.factsTombstoneStats;return m&&Number(m.pendingTotal)>0&&(i.push(F("")),i.push(...Q({title:`Fact Tombstones (${Number(m.pendingTotal)||0})`,body:pc(m),width:o,titleColor:"yellow",borderColor:"gray",fitToContent:!0}))),i}function yc(t,e){const n=t.slice().sort((m,g)=>{const I=T=>T==="learned"?1:0,y=I(m.kind)-I(g.kind);if(y!==0)return y;const x=m.agentId?0:1,E=g.agentId?0:1;if(x!==E)return x-E;const v=String(m.agentId||"").localeCompare(String(g.agentId||""));return v!==0?v:String(m.name||"").localeCompare(String(g.name||""))}).slice(0,15),i=n.map(m=>`${m.invocations||0} inv`),o=n.map(m=>`${m.sessionCount||0} sess`),r=i.reduce((m,g)=>Math.max(m,g.length),0),a=o.reduce((m,g)=>Math.max(m,g.length),0),l=4,p=2,u=l+p+r+p+a,d=Number.isFinite(e)&&e>0?Math.max(10,Math.floor(e)-u):1/0,f=n.map((m,g)=>{const I=m.kind==="learned"?"L":"S",y=m.agentId||".",x=String(m.name||"(unknown)");return[zt(`${I} ${y}/${x}`,d),i[g],o[g]]}),h=bt(f);return t.length>n.length?`${h}
56
- … ${t.length-n.length} more`:h}function Sc(t){const e=t.slice().sort((n,i)=>(i.totalTokensInput||0)-(n.totalTokensInput||0)),s=[];for(const n of e){const i=n.cacheHitRatio;s.push(`${String(n.model||"(unknown)")} · ${n.sessionCount||0} sess · ${n.turnCount||0} turns`),s.push(cn(n,i)),s.push("")}return s.join(`
57
- `).trimEnd()}function cn(t,e){const s=e==null?"—":`${(e*100).toFixed(1)}%`,n=(Number(t.totalTokensInput)||0)+(Number(t.totalTokensOutput)||0),i=[["Input",B(t.totalTokensInput||0)],["Output",B(t.totalTokensOutput||0)],["Total",B(n)],["Turns",B(t.turnCount||0)],["Cache Read",B(t.totalTokensCacheRead||0)],["Cache Write",B(t.totalTokensCacheWrite||0)],["Hit Ratio",s],["Snapshot",ne(t.totalSnapshotSizeBytes||0)]];return Number.isFinite(Number(t.totalOrchestrationHistorySizeBytes))&&i.push(["Orch",ne(t.totalOrchestrationHistorySizeBytes||0)]),Be(i).split(`
58
- `).map(r=>` ${r}`).join(`
59
- `)}function ks(t){return t?.ownerKind==="system"?"System":t?.ownerKind==="unowned"?"Unowned":Ys(t?.owner,"Unknown User")}function bc(t){if(t?.ownerKind!=="user")return"";const e=String(t?.owner?.email||"").trim(),s=ks(t);return e&&e!==s?e:""}function wc(t,e){const s=Array.isArray(t?.byModel)?t.byModel:[];if(s.length===0)return"";const n=s.slice().sort((o,r)=>(r.totalTokensInput||0)-(o.totalTokensInput||0)).slice(0,6),i=[];for(const o of n){const r=zt(String(o.model||"(default)"),Math.max(12,e-10));i.push(`${r} · ${o.sessionCount||0} sess · ${o.turnCount||0} turns`),i.push(cn(o,o.cacheHitRatio)),i.push("")}return s.length>n.length&&i.push(`… ${s.length-n.length} more models`),i.join(`
60
- `).trimEnd()}function Ic(t,e){const s=t.fleetStats;if(!s||s.loading&&!s.userStats)return[F("Loading user stats...")];const n=s.userStats;if(!n)return[F("User stats unavailable.")];const i=[],o=Math.max(24,e);i.push(Kt("users",o)),i.push(F(""));const r=n.windowStart?`Since: ${vo(n.windowStart).replace(" ago","")}`:"All time",a=n.earliestSessionCreatedAt?`Earliest: ${new Date(n.earliestSessionCreatedAt).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}`:"";i.push(q([{text:r,color:"cyan"},{text:a?` ${a}`:"",color:"gray"}],o)),i.push(q([{text:`Users: ${Array.isArray(n.users)?n.users.length:0}`,color:"white"},{text:` Sessions: ${n.totals.sessionCount||0}`,color:"white"}],o)),i.push(F(""));const l=n.totals.cacheHitRatio,p=l==null?"—":`${(l*100).toFixed(1)}%`;i.push(...Q({title:"User Totals",body:Be([["Sessions",String(n.totals.sessionCount||0)],["Tokens In",B(n.totals.totalTokensInput||0)],["Tokens Out",B(n.totals.totalTokensOutput||0)],["Total Tokens",B((n.totals.totalTokensInput||0)+(n.totals.totalTokensOutput||0))],["Cache Read",B(n.totals.totalTokensCacheRead||0)],["Cache Write",B(n.totals.totalTokensCacheWrite||0)],["Hit Ratio",p],["Snapshots",ne(n.totals.totalSnapshotSizeBytes||0)],["Orch Size",ne(n.totals.totalOrchestrationHistorySizeBytes||0)]]),width:o,titleColor:"green",borderColor:"gray",fitToContent:!0}));const u=Array.isArray(n.users)?n.users:[],d=u.slice().sort((f,h)=>(h.totalTokensInput||0)-(f.totalTokensInput||0)||(h.totalSnapshotSizeBytes||0)-(f.totalSnapshotSizeBytes||0)).slice(0,8);for(const f of d){const h=bc(f),m=f.cacheHitRatio,g=m==null?"—":`${(m*100).toFixed(1)}%`,I=h?`${ks(f)} <${h}>`:ks(f),y=Be([["Sessions",String(f.sessionCount||0)],["Tokens In",B(f.totalTokensInput||0)],["Tokens Out",B(f.totalTokensOutput||0)],["Total Tokens",B((f.totalTokensInput||0)+(f.totalTokensOutput||0))],["Cache Read",B(f.totalTokensCacheRead||0)],["Cache Write",B(f.totalTokensCacheWrite||0)],["Hit Ratio",g],["Snapshots",ne(f.totalSnapshotSizeBytes||0)],["Orch Size",ne(f.totalOrchestrationHistorySizeBytes||0)]]),x=wc(f,o);i.push(F("")),i.push(...Q({title:`${I} (${f.sessionCount||0})`,body:x?`${y}
61
-
62
- ${x}`:y,width:o,titleColor:f.ownerKind==="user"?"cyan":"yellow",borderColor:"gray",fitToContent:!0}))}return u.length>d.length&&(i.push(F("")),i.push(F(`… ${u.length-d.length} more users`))),i}function Fe(t,e={}){const s=Ce(t),n=t.ui.inspectorTab,i=Math.max(18,Number(e?.width)||36),o=!!e?.allowWideColumns,r=Ji(i);if(s?.isGroup)return{title:Se("Inspector","magenta"),activeTab:n,tabs:ge,disabled:!0,stickyLines:[],lines:[F(Ao,"gray")]};const a=s?K(s.sessionId):"",l=n==="sequence"||n==="nodes"?an(t):null,p=n==="nodes"?[...Se("Node Map","magenta"),...r?[]:[{text:` [${l.label}]`,color:"gray"}]]:s?n==="sequence"?[...Se(r?"Sequence":`Sequence: ${a}`,"magenta"),...r?[]:[{text:` [${l.label}]`,color:"gray"}]]:n==="logs"?[...Se(r?"Logs":`Logs: ${a}`,"magenta")]:n==="history"?[...Se(r?"History":`History: ${a}`,"magenta")]:n==="stats"?[...Se(r?"Stats":`Stats: ${a}`,"magenta"),{text:` [${ot(t.ui?.statsViewMode)}]`,color:"gray"}]:[...Se(r?"Files":`Files: ${a}`,"magenta")]:n==="stats"?`Stats: ${ot(t.ui?.statsViewMode).replace(/^./u,f=>f.toUpperCase())}`:"No session selected";let u,d=[];switch(n){case"sequence":{const f=s?Ql(t,s,i,{allowWideColumns:o}):{stickyLines:[],lines:["No session selected."]};d=f.stickyLines||[],u=f.lines;break}case"logs":u=s?vl(t,s):["No session selected."];break;case"nodes":u=ec(t,i,{allowWideColumns:o});break;case"files":u=s?["Files view is rendered in the shared host layout."]:["No session selected."];break;case"history":u=s?Cc(t,s):["No session selected."];break;case"stats":u=ot(t.ui?.statsViewMode)==="users"?Ic(t,i):ot(t.ui?.statsViewMode)==="fleet"?gc(t,i):s?fc(t,s,i):[Kt("session",Math.max(24,i)),F(""),F("No session selected. Press f to cycle to fleet or users view.")];break;default:u=["Inspector view is scaffolded in the new architecture."];break}return{title:p,activeTab:n,tabs:ge,stickyLines:d,lines:u}}const xc={OrchestratorStarted:"green",OrchestratorCompleted:"green",ExecutionStarted:"cyan",ExecutionCompleted:"cyan",TaskScheduled:"yellow",TaskCompleted:"yellow",TaskFailed:"red",SubOrchestrationCreated:"magenta",SubOrchestrationCompleted:"magenta",SubOrchestrationFailed:"red",TimerCreated:"blue",TimerFired:"blue",EventRaised:"white",EventSent:"white",CustomStatusUpdated:"gray"},Ao="Select a session to see details.";function Ec(t){const e=t.timestampMs?new Date(t.timestampMs).toISOString().slice(11,23):"???",s=xc[t.kind]||"gray",n=[],i=[{text:`#${t.eventId}`,color:"white",bold:!0},{text:` ${e}`,color:"gray"},{text:` ${t.kind}`,color:s,bold:t.kind.includes("Failed")}];if(t.sourceEventId!=null&&i.push({text:` ←#${t.sourceEventId}`,color:"cyan"}),n.push(i),t.data)try{const o=JSON.parse(t.data);if(typeof o=="object"&&o!==null)for(const[r,a]of Object.entries(o)){const l=typeof a=="string"?a:JSON.stringify(a),p=l.length>100?l.slice(0,97)+"...":l;n.push([{text:` ${r}: `,color:"yellow"},{text:p,color:"white"}])}else n.push({text:` ${String(o).slice(0,120)}`,color:"white"})}catch{const o=t.data.length>120?t.data.slice(0,117)+"...":t.data;n.push({text:` ${o}`,color:"white"})}return n}function vc(t){const e={...t};if(e.data)try{e.data=JSON.parse(e.data)}catch{}return JSON.stringify(e,null,2)}function Cc(t,e){const s=t.executionHistory?.bySessionId?.[e.sessionId];if(!s)return["No execution history loaded. Press r to refresh."];if(s.loading)return["Loading execution history..."];if(s.error)return[`Error: ${s.error}`];const n=s.events;if(!Array.isArray(n)||n.length===0)return["No history events found."];const i=t.executionHistory?.format||"pretty",o=[];if(o.push({text:`${n.length} event(s) · format: ${i}`,color:"gray"}),o.push(""),i==="raw")for(let r=0;r<n.length;r++){const a=vc(n[r]).split(`
63
- `);for(const l of a)o.push({text:l,color:"gray"});r<n.length-1&&o.push({text:"────────────────────────────────",color:"gray"})}else for(let r=0;r<n.length;r++){const a=Ec(n[r]);for(const l of a)o.push(l);r<n.length-1&&o.push({text:"────────────────────────────────",color:"gray"})}return o}function Ac(t,e=88){const s=t.ui.modal;return!s||s.type!=="historyFormat"?null:ln(s,{format:t.executionHistory?.format||"pretty"},e,"Execution History Format","Choose the display format for duroxide execution history events.")}function Kn(t=[]){const e=[];for(const s of t)e.length>0&&e.push({text:" ",color:"gray"}),e.push({text:`${s.label} `,color:"gray"}),e.push({text:"██",color:s.color,backgroundColor:s.color});return e}function Tc(t,e=80){const s=t.ui.modal;if(!s||s.type!=="themePicker")return null;const n=Array.isArray(s.items)?s.items:[],i=Math.max(0,Number(s.selectedIndex)||0),o=n[i]||null,r=s.currentThemeId||t.ui.themeId||null,a=n.find(f=>f.id===r)||null,l=o&&o.id!==r,p=Math.max(24,e-4),u=n.map((f,h)=>{const m=f.id===r?" [current]":"",g=`${f.label}${m}`.slice(0,p);return h===i?Te(g.padEnd(p," ")):[{text:g,color:f.id===r?"cyan":"white",bold:f.id===r}]}),d=o?[[{text:`theme: ${o.description||"Shared theme for the portal and native TUI."}`,color:"white"}],{text:"",color:"gray"},[{text:l?`Previewing now. Cancel reverts to ${a?.label||"the previous theme"}.`:"Currently active in this TUI session.",color:l?"yellow":"green"}],Kn([{label:"bg",color:o.tui?.background||o.terminal?.background||"#000000"},{label:"surface",color:o.tui?.surface||o.terminal?.background||"#000000"},{label:"fg",color:o.tui?.white||o.terminal?.foreground||"#ffffff"}]),Kn([{label:"blue",color:o.tui?.blue||o.terminal?.blue||"#5555ff"},{label:"green",color:o.tui?.green||o.terminal?.green||"#55ff55"},{label:"magenta",color:o.tui?.magenta||o.terminal?.magenta||"#ff55ff"},{label:"yellow",color:o.tui?.yellow||o.terminal?.yellow||"#ffff55"}]),{text:"",color:"gray"},[{text:"Selecting previews immediately. Apply Theme keeps it; Cancel restores the previous theme.",color:"gray"}]]:[{text:"No themes available.",color:"gray"}];return{title:s.title||"Theme Picker",idealWidth:Math.max(60,Math.min(e,80)),rows:u,selectedRowIndex:i,detailsTitle:"Theme Details",detailsLines:d}}function kc(t){const e=t.ui.modal;return!e||e.type!=="confirm"?null:{title:e.title||"Confirm",message:e.message||"Are you sure?",confirmLabel:e.confirmLabel||"Confirm"}}function zn(t){return new Map(t)}function fs(t){return new Set(t)}function Mc(t){return Array.isArray(t)?[...t]:[]}function Pc(t){return Array.isArray(t)?[...t]:[]}const Nc=5e3;function Ms(t,e){const s=[],n=new Set;for(const i of t||[])!i||n.has(i)||e[i]&&(n.add(i),s.push(i));return s}function To(t){return!!(t&&!t.isSystem&&(t.isGroup||!t.parentSessionId&&!t.groupId))}function ps(t,e){return Ms(t,e).filter(s=>To(e[s]))}function Oc(t=[]){const e=new Set((t||[]).map(n=>n?.sessionId).filter(Boolean)),s=new Set;for(const n of t||[]){if(!n?.sessionId)continue;n.isGroup&&s.add(n.sessionId);const i=n.parentSessionId;i&&e.has(i)&&s.add(i)}return s}function ko(t,e){const s=Oc(Object.values(e||{})),n=new Set;for(const i of t||[])s.has(i)&&n.add(i);return n}function Rc(t,e){const s=[],n=new Set([t]);let i=e?.[t]||null;for(;i;){let o=null;if(i.parentSessionId&&e?.[i.parentSessionId]?o=i.parentSessionId:!i.isGroup&&i.groupId&&e?.[`group:${i.groupId}`]&&(o=`group:${i.groupId}`),!o||n.has(o))break;s.push(o),n.add(o),i=e[o]||null}return s}function Fc(t,e,s){const n=ko(t,e);if(!s||!e?.[s])return n;for(const i of Rc(s,e))n.delete(i);return n}function _c(t,e){if(t===e)return!0;if(!(t instanceof Set)||!(e instanceof Set)||t.size!==e.size)return!1;for(const s of t)if(!e.has(s))return!1;return!0}function Lc(t){return{...t||{}}}function ye(t){return{...t||{}}}function Yn(t){return{...t||{}}}function vt(t){return{...t||{}}}function hs(t){return{scope:t?.scope==="allSessions"?"allSessions":"selectedSession",query:typeof t?.query=="string"?t.query:""}}function $c(t){return(Array.isArray(t)?t.filter(Boolean):[]).slice(-1e3)}function Bc(t){return[w.SESSIONS,w.CHAT,w.INSPECTOR,w.ACTIVITY].includes(t)?t:null}function ms(t,e){const s=Array.isArray(t)?t.filter(Boolean):[],n=Math.max(V,Number(e)||V);return s.length>n?s.slice(-n):s}function Ps(t,e){if(Object.is(t,e))return!0;if(Array.isArray(t)||Array.isArray(e)){if(!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length)return!1;for(let i=0;i<t.length;i+=1)if(!Ps(t[i],e[i]))return!1;return!0}if(!t||!e||typeof t!="object"||typeof e!="object")return!1;const s=Object.keys(t),n=Object.keys(e);if(s.length!==n.length)return!1;for(const i of s)if(!Object.prototype.hasOwnProperty.call(e,i)||!Ps(t[i],e[i]))return!1;return!0}function Qn(t={},e={}){let s=t||{};for(const[n,i]of Object.entries(e||{}))if(i!==void 0){if(n==="pendingQuestion"&&Dc(t,i)){s===t&&(s={...t||{}}),s.pendingQuestion=null;continue}Ps(t?.[n],i)||(s===t&&(s={...t||{}}),s[n]=i)}return s}function Xn(t){if(!t)return"unknown";const e=t.status||"unknown";return t.cronActive===!0&&(e==="waiting"||e==="idle"||e==="unknown")?"cron_waiting":e}function Jn(t,e,s){if(!e?.sessionId||e.isGroup)return e;const n=Xn(e),i=t?.rowVisualStatus||Xn(t||e);if(!t)return e.rowVisualStatus===n&&e.rowVisualStatusCandidate==null&&e.rowVisualStatusCandidateSince==null?e:{...e,rowVisualStatus:n,rowVisualStatusCandidate:void 0,rowVisualStatusCandidateSince:void 0};if(n===i)return e.rowVisualStatus===n&&e.rowVisualStatusCandidate==null&&e.rowVisualStatusCandidateSince==null?e:{...e,rowVisualStatus:n,rowVisualStatusCandidate:void 0,rowVisualStatusCandidateSince:void 0};const r=t.rowVisualStatusCandidate===n&&Number(t.rowVisualStatusCandidateSince)||s;return s-r>=Nc?{...e,rowVisualStatus:n,rowVisualStatusCandidate:void 0,rowVisualStatusCandidateSince:void 0}:e.rowVisualStatus===i&&e.rowVisualStatusCandidate===n&&Number(e.rowVisualStatusCandidateSince)===r?e:{...e,rowVisualStatus:i,rowVisualStatusCandidate:n,rowVisualStatusCandidateSince:r}}function Zn(t){return String(t?.question||"").trim()}function Dc(t,e){const s=Zn(t?.answeredPendingQuestion),n=Zn(e);return!!(s&&n&&s===n)}function Hc(t=[]){const e=(t||[]).find(n=>n?.sessionId&&n.isSystem&&Hi(n)===0);return e?.sessionId?e.sessionId:(t||[]).find(n=>n?.sessionId)?.sessionId||null}function ei(t=[]){const e=new Set((t||[]).map(n=>n?.sessionId).filter(Boolean)),s=new Set;for(const n of t||[]){if(!n?.sessionId)continue;n.isGroup&&s.add(n.sessionId);const i=n.parentSessionId;i&&e.has(i)&&s.add(i)}return s}function ti(t={}){const e=String(t?.filterQuery||"").trim(),s=$t(t?.ownerFilter);return!!e||s.all!==!0}function Gc(t,e=[]){const s=ht(t),n=t.sessions?.activeSessionId||null;if(n&&s.some(o=>o.sessionId===n)||n&&t.sessions?.byId?.[n]&&!ti(t.sessions))return n;if(ti(t.sessions))return s[0]?.sessionId||null;const i=s.length>0?s.map(o=>t.sessions?.byId?.[o.sessionId]||null).filter(Boolean):e;return Hc(i)}function jc(t,e){return e===t.sessions.activeSessionId?t.ui:{...t.ui,scroll:{...t.ui.scroll,chat:0,inspector:0,activity:0},followBottom:{...t.ui.followBottom||{},inspector:!0,activity:!0}}}function tt(t,e){const s={...t,sessions:e},n=Gc(s,Object.values(e.byId||{})),i=Fc(e.collapsedIds,e.byId,n);return{sessions:{...!_c(i,e.collapsedIds)?{...e,collapsedIds:i,flat:Pe(Object.values(e.byId||{}),i,e.orderById,e.pinnedIds)}:e,activeSessionId:n},ui:jc(t,n)}}function si(t={},e=0,s=[]){const n=Lc(t);let i=Number.isFinite(e)?e:0;for(const o of s||[]){const r=o?.sessionId;r&&typeof n[r]!="number"&&(n[r]=i,i+=1)}return{orderById:n,nextOrderOrdinal:i}}function Uc(t=[],e=[]){const s=Pe(t,new Set,{},e),n={};let i=0;for(const o of s){const r=o?.sessionId;!r||typeof n[r]=="number"||(n[r]=i,i+=1)}for(const o of t||[]){const r=o?.sessionId;!r||typeof n[r]=="number"||(n[r]=i,i+=1)}return{orderById:n,nextOrderOrdinal:i}}function Wc(t,e,s=null){const n=String(t||""),i=Number.isFinite(e)?e:Number.isFinite(s)?s:n.length;return Math.max(0,Math.min(i,n.length))}function ni(t,e){const s=String(t||"");return(Array.isArray(e)?e.filter(Boolean):[]).filter(i=>{const o=String(i?.token||"").trim();return o&&s.includes(o)})}function Vc(t,e){switch(e.type){case"connection/ready":return{...t,connection:{...t.connection,connected:!0,workersOnline:e.workersOnline??t.connection.workersOnline,error:null},ui:{...t.ui,statusText:e.statusText??t.ui.statusText??"Ready"}};case"connection/error":return{...t,connection:{...t.connection,connected:!1,error:e.error},ui:{...t.ui,statusText:e.statusText||e.error||"Connection error"}};case"auth/context":return{...t,auth:{principal:e.principal??null,authorization:e.authorization??null}};case"ui/status":return{...t,ui:{...t.ui,statusText:e.text}};case"ui/theme":return{...t,ui:{...t.ui,themeId:e.themeId||t.ui.themeId}};case"profileSettings/apply":{const s=e.settings&&typeof e.settings=="object"&&!Array.isArray(e.settings)?e.settings:{},n=Object.prototype.hasOwnProperty.call(s,"themeId")&&typeof s.themeId=="string"&&s.themeId.trim(),i=Object.prototype.hasOwnProperty.call(s,"sessionOwnerFilter"),o=Object.prototype.hasOwnProperty.call(s,"layoutAdjustments"),r=Object.prototype.hasOwnProperty.call(s,"chatViewMode")&&(s.chatViewMode==="summary"||s.chatViewMode==="transcript"),a=Object.prototype.hasOwnProperty.call(s,"pinnedSessionIds"),l=Object.prototype.hasOwnProperty.call(s,"collapsedSessionIds"),p=Object.prototype.hasOwnProperty.call(s,"activeSessionId"),u=Object.keys(t.sessions.byId||{}).length>0,d=o?{...t.ui.layout||{},...Vs(s.layoutAdjustments)}:t.ui.layout,f=a?u?ps(Dt(s.pinnedSessionIds),t.sessions.byId):Dt(s.pinnedSessionIds):t.sessions.pinnedIds,h=l?u?ko(Cs(s.collapsedSessionIds),t.sessions.byId):Cs(s.collapsedSessionIds):t.sessions.collapsedIds,m=p?zi(s.activeSessionId):t.sessions.activeSessionId,g={...t.sessions,...i?{ownerFilter:$t(s.sessionOwnerFilter),ownerFilterExplicit:!0}:{},pinnedIds:f,collapsedIds:h,collapsedIdsExplicit:l?!0:t.sessions.collapsedIdsExplicit,activeSessionId:m,flat:a||l?Pe(Object.values(t.sessions.byId),h,t.sessions.orderById,f):t.sessions.flat},I=u&&(i||a||l||p)?tt(t,g):{sessions:g,ui:t.ui};return{...t,sessions:I.sessions,ui:{...I.ui,themeId:n?s.themeId.trim():I.ui.themeId,chatViewMode:r?s.chatViewMode:I.ui.chatViewMode,layout:d}}}case"ui/chatViewMode":return e.mode!=="summary"&&e.mode!=="transcript"?t:{...t,ui:{...t.ui,chatViewMode:e.mode,scroll:{...t.ui.scroll,chat:0}}};case"ui/modal":return{...t,ui:{...t.ui,modal:e.modal??null}};case"ui/viewport":{const s=t.ui.layout?.viewportWidth??120,n=t.ui.layout?.viewportHeight??40,i=Math.max(40,e.width??s),o=Math.max(18,e.height??n);return i===s&&o===n?t:{...t,ui:{...t.ui,layout:{...t.ui.layout||{},viewportWidth:i,viewportHeight:o}}}}case"ui/paneAdjust":return{...t,ui:{...t.ui,layout:{...t.ui.layout||{},paneAdjust:Number(e.paneAdjust)||0}}};case"ui/sessionPaneAdjust":return{...t,ui:{...t.ui,layout:{...t.ui.layout||{},sessionPaneAdjust:Number(e.sessionPaneAdjust)||0}}};case"ui/portalSessionColumnAdjust":return{...t,ui:{...t.ui,layout:{...t.ui.layout||{},portalSessionColumnAdjust:Number(e.portalSessionColumnAdjust)||0}}};case"ui/activityPaneAdjust":return{...t,ui:{...t.ui,layout:{...t.ui.layout||{},activityPaneAdjust:Number(e.activityPaneAdjust)||0}}};case"ui/focus":return{...t,ui:{...t.ui,focusRegion:e.focusRegion}};case"sessions/filterQuery":{const s={...t.sessions,filterQuery:typeof e.query=="string"?e.query:""},n=tt(t,s);return{...t,sessions:n.sessions,ui:n.ui}}case"sessions/ownerFilter":{const s={...t.sessions,ownerFilterExplicit:!0,ownerFilter:$t(e.filter)},n=tt(t,s);return{...t,sessions:n.sessions,ui:n.ui}}case"ui/modalSelection":{const s=t.ui.modal;if(!s||!Array.isArray(s.items)||s.items.length===0)return t;const n=Math.max(0,Math.min(e.index??0,s.items.length-1)),i=s.type==="themePicker"?s.items[n]?.id:null;return{...t,ui:{...t.ui,...i?{themeId:i}:{},modal:{...s,selectedIndex:n}}}}case"ui/scroll":return{...t,ui:{...t.ui,scroll:{...t.ui.scroll,[e.pane]:Math.max(0,e.offset??0)}}};case"ui/followBottom":{if(e.pane!=="inspector"&&e.pane!=="activity")return t;const s=!!e.followBottom;return t.ui.followBottom?.[e.pane]===s?t:{...t,ui:{...t.ui,followBottom:{...t.ui.followBottom||{},[e.pane]:s}}}}case"ui/inspectorTab":return{...t,ui:{...t.ui,inspectorTab:e.inspectorTab,fullscreenPane:e.inspectorTab==="files"&&t.ui.fullscreenPane===w.INSPECTOR?null:t.ui.fullscreenPane,scroll:{...t.ui.scroll,inspector:0},followBottom:{...t.ui.followBottom||{},inspector:!0}},files:e.inspectorTab==="files"?t.files:{...t.files,fullscreen:!1}};case"ui/statsViewMode":return{...t,ui:{...t.ui,statsViewMode:["session","fleet","users"].includes(e.statsViewMode)?e.statsViewMode:"session",scroll:{...t.ui.scroll,inspector:0}}};case"ui/prompt":return{...t,ui:{...t.ui,prompt:e.prompt,promptCursor:Wc(e.prompt,e.promptCursor,t.ui.promptCursor),promptRows:ze(e.prompt),promptAttachments:ni(e.prompt,t.ui.promptAttachments)}};case"ui/promptEdit":return{...t,ui:{...t.ui,promptEdit:e.promptEdit??null}};case"ui/promptAttachments":return{...t,ui:{...t.ui,promptAttachments:ni(t.ui.prompt,e.attachments)}};case"sessions/loaded":{const s={};let n=!1;const i=Date.now();for(const E of e.sessions){const v=t.sessions.byId[E.sessionId],T=Jn(v,Qn(v,E),i);s[E.sessionId]=T,!n&&T!==v&&(n=!0)}t.sessions.activeSessionId&&t.sessions.byId[t.sessions.activeSessionId]&&!t.sessions.byId[t.sessions.activeSessionId]?.isGroup&&!s[t.sessions.activeSessionId]&&(s[t.sessions.activeSessionId]={...t.sessions.byId[t.sessions.activeSessionId]},n=!0);const o=Object.keys(t.sessions.byId),r=Object.keys(s);if(o.length!==r.length&&(n=!0),!n){for(const E of r)if(!t.sessions.byId[E]){n=!0;break}}if(!n)return t;const a=Object.values(s),l=Object.keys(t.sessions.orderById||{}).length>0,p=ei(a),u=!!t.sessions.collapsedIdsExplicit,{orderById:d,nextOrderOrdinal:f}=l?si(t.sessions.orderById,t.sessions.nextOrderOrdinal,a):Uc(a,t.sessions.pinnedIds),h=u?fs(t.sessions.collapsedIds):p;if(u){const E=ei(Object.values(t.sessions.byId));for(const v of p)E.has(v)||h.add(v)}const m=ps(t.sessions.pinnedIds,s),g=Ms(t.sessions.selectedIds,s),I=Pe(a,h,d,m),y={...t.sessions,byId:s,collapsedIds:h,collapsedIdsExplicit:u,pinnedIds:m,selectedIds:g,selectMode:t.sessions.selectMode&&g.length>0,flat:I,activeSessionId:t.sessions.activeSessionId,orderById:d,nextOrderOrdinal:f},x=tt(t,y);return{...t,sessions:x.sessions,ui:x.ui}}case"sessions/merged":{if(!e.session?.sessionId)return t;const s=t.sessions.byId[e.session.sessionId],n=Jn(s,Qn(s,e.session),Date.now());if(n===s)return t;const i={...t.sessions.byId,[e.session.sessionId]:n},o=ps(t.sessions.pinnedIds,i),{orderById:r,nextOrderOrdinal:a}=si(t.sessions.orderById,t.sessions.nextOrderOrdinal,Object.values(i)),l={...t.sessions,byId:i,pinnedIds:o,flat:Pe(Object.values(i),t.sessions.collapsedIds,r,o),activeSessionId:t.sessions.activeSessionId,orderById:r,nextOrderOrdinal:a},p=tt(t,l);return{...t,sessions:p.sessions,ui:p.ui}}case"sessions/selected":return{...t,sessions:{...t.sessions,activeSessionId:e.sessionId},ui:{...t.ui,scroll:{...t.ui.scroll,chat:0,inspector:0,activity:0},followBottom:{...t.ui.followBottom||{},inspector:!0,activity:!0}}};case"ui/fullscreenPane":{const s=Bc(e.fullscreenPane);return{...t,files:s?{...t.files,fullscreen:!1}:t.files,ui:{...t.ui,fullscreenPane:s,focusRegion:s||t.ui.focusRegion}}}case"sessions/collapse":{const s=fs(t.sessions.collapsedIds);return s.add(e.sessionId),{...t,sessions:{...t.sessions,collapsedIds:s,collapsedIdsExplicit:!0,flat:Pe(Object.values(t.sessions.byId),s,t.sessions.orderById,t.sessions.pinnedIds)}}}case"sessions/expand":{const s=fs(t.sessions.collapsedIds);return s.delete(e.sessionId),{...t,sessions:{...t.sessions,collapsedIds:s,collapsedIdsExplicit:!0,flat:Pe(Object.values(t.sessions.byId),s,t.sessions.orderById,t.sessions.pinnedIds)}}}case"sessions/pinToggle":{const s=String(e.sessionId||"").trim();if(!s)return t;const n=t.sessions.byId[s];if(!To(n))return t;const i=Mc(t.sessions.pinnedIds),r=i.indexOf(s)>=0?i.filter(a=>a!==s):[...i,s];return{...t,sessions:{...t.sessions,pinnedIds:r,flat:Pe(Object.values(t.sessions.byId),t.sessions.collapsedIds,t.sessions.orderById,r)}}}case"sessions/selectMode":{const s=!!e.enabled;return s===!!t.sessions.selectMode&&(s||t.sessions.selectedIds.length===0)?t:{...t,sessions:{...t.sessions,selectMode:s,selectedIds:s?t.sessions.selectedIds:[]}}}case"sessions/selectToggle":{const s=String(e.sessionId||"").trim(),n=s?t.sessions.byId[s]:null;if(!n||n.isSystem||n.isGroup)return t;const i=Pc(t.sessions.selectedIds),r=i.indexOf(s)>=0?i.filter(a=>a!==s):[...i,s];return{...t,sessions:{...t.sessions,selectedIds:r,selectMode:r.length>0?!0:t.sessions.selectMode}}}case"sessions/selectSet":{const s=Array.isArray(e.sessionIds)?e.sessionIds:[],n=Ms(s,t.sessions.byId).filter(i=>!t.sessions.byId[i]?.isSystem&&!t.sessions.byId[i]?.isGroup);return{...t,sessions:{...t.sessions,selectedIds:n,selectMode:n.length>0?!0:t.sessions.selectMode}}}case"sessions/selectClear":return t.sessions.selectedIds.length===0&&!t.sessions.selectMode?t:{...t,sessions:{...t.sessions,selectedIds:[],selectMode:!1}};case"history/set":{const s=t.history.bySessionId.get(e.sessionId)||null,n=s?.chat||[],i=Math.max(V,Number(e.history?.loadedEventLimit??s?.loadedEventLimit??V)||V),o=ms(qe(e.history?.chat||[]),i),r=n[n.length-1]?.id||null,a=o[o.length-1]?.id||null,l=e.sessionId===t.sessions.activeSessionId&&a!==r,p=zn(t.history.bySessionId);return p.set(e.sessionId,{...e.history||{},chat:o,activity:ms(e.history?.activity||[],i),events:ms(e.history?.events||[],i),loadedEventLimit:i}),{...t,history:{...t.history,bySessionId:p},ui:l?{...t.ui,scroll:{...t.ui.scroll,chat:0}}:t.ui}}case"history/evict":{const s=Array.isArray(e.sessionIds)?e.sessionIds:[];if(s.length===0)return t;const n=zn(t.history.bySessionId);for(const o of s)n.delete(o);const i=Yn(t.outbox?.bySessionId);for(const o of s)delete i[o];return{...t,history:{...t.history,bySessionId:n},outbox:{...t.outbox,bySessionId:i}}}case"outbox/setSessionItems":{const s=e.sessionId;if(!s)return t;const n=Array.isArray(e.items)?e.items.filter(Boolean):[],i=Yn(t.outbox?.bySessionId);return n.length===0?delete i[s]:i[s]=n,{...t,outbox:{...t.outbox,bySessionId:i}}}case"orchestration/statsLoading":{const s=vt(t.orchestration.bySessionId);return s[e.sessionId]={...s[e.sessionId]||{},loading:!0,error:null},{...t,orchestration:{...t.orchestration,bySessionId:s}}}case"orchestration/statsLoaded":{const s=vt(t.orchestration.bySessionId);return s[e.sessionId]={loading:!1,error:null,fetchedAt:e.fetchedAt||Date.now(),stats:e.stats||null},{...t,orchestration:{...t.orchestration,bySessionId:s}}}case"orchestration/statsError":{const s=vt(t.orchestration.bySessionId);return s[e.sessionId]={...s[e.sessionId]||{},loading:!1,error:e.error||"Failed to load orchestration stats",fetchedAt:e.fetchedAt||Date.now()},{...t,orchestration:{...t.orchestration,bySessionId:s}}}case"orchestration/evict":{const s=Array.isArray(e.sessionIds)?e.sessionIds:[];if(s.length===0)return t;const n=vt(t.orchestration.bySessionId);for(const i of s)delete n[i];return{...t,orchestration:{...t.orchestration,bySessionId:n}}}case"executionHistory/loading":{const s={...t.executionHistory?.bySessionId||{}};return s[e.sessionId]={...s[e.sessionId]||{},loading:!0,error:null},{...t,executionHistory:{...t.executionHistory,bySessionId:s}}}case"executionHistory/loaded":{const s={...t.executionHistory?.bySessionId||{}},n=e.events||[],i=1e3,o=n.length>i?n.slice(-i):n;return s[e.sessionId]={loading:!1,error:null,fetchedAt:e.fetchedAt||Date.now(),events:o},{...t,executionHistory:{...t.executionHistory,bySessionId:s}}}case"executionHistory/evict":{const s=Array.isArray(e.sessionIds)?e.sessionIds:[];if(s.length===0)return t;const n={...t.executionHistory?.bySessionId||{}};for(const i of s)delete n[i];return{...t,executionHistory:{...t.executionHistory,bySessionId:n}}}case"executionHistory/error":{const s={...t.executionHistory?.bySessionId||{}};return s[e.sessionId]={...s[e.sessionId]||{},loading:!1,error:e.error||"Failed to load execution history",fetchedAt:e.fetchedAt||Date.now()},{...t,executionHistory:{...t.executionHistory,bySessionId:s}}}case"executionHistory/format":return{...t,executionHistory:{...t.executionHistory,format:e.format||"pretty"}};case"sessionStats/loading":{const s={...t.sessionStats?.bySessionId||{}};return s[e.sessionId]={...s[e.sessionId]||{},loading:!0},{...t,sessionStats:{...t.sessionStats,bySessionId:s}}}case"sessionStats/loaded":{const s={...t.sessionStats?.bySessionId||{}};return s[e.sessionId]={loading:!1,fetchedAt:Date.now(),summary:e.summary||null,tokensByModel:Array.isArray(e.tokensByModel)?e.tokensByModel:[],treeStats:e.treeStats||null,skillUsage:e.skillUsage||null,treeSkillUsage:e.treeSkillUsage||null,factsStats:e.factsStats||null,treeFactsStats:e.treeFactsStats||null},{...t,sessionStats:{...t.sessionStats,bySessionId:s}}}case"fleetStats/loading":return{...t,fleetStats:{...t.fleetStats,loading:!0}};case"fleetStats/loaded":return{...t,fleetStats:{loading:!1,data:e.data||null,userStats:e.userStats||null,skillUsage:e.skillUsage||null,retrievalUsage:e.retrievalUsage||null,sharedFactsStats:e.sharedFactsStats||null,factsTombstoneStats:e.factsTombstoneStats||null,fetchedAt:Date.now()}};case"admin/visibility":{const s=!!e.visible;return t.admin.visible===s?t:{...t,admin:{...t.admin,visible:s,ghcpKey:s?t.admin.ghcpKey:{editing:!1,draft:"",saving:!1,error:null,lastSavedAt:t.admin.ghcpKey.lastSavedAt}}}}case"admin/profile/loading":return{...t,admin:{...t.admin,loading:!0,loadError:null}};case"admin/profile/loaded":return{...t,admin:{...t.admin,loading:!1,loadError:null,profile:e.profile||null,ghcpKey:{...t.admin.ghcpKey,error:t.admin.ghcpKey.editing?t.admin.ghcpKey.error:null}}};case"admin/profile/loadFailed":return{...t,admin:{...t.admin,loading:!1,loadError:e.error?String(e.error):"Failed to load profile"}};case"admin/ghcpKey/beginEdit":{const s=typeof e.draft=="string"?e.draft:"";return{...t,admin:{...t.admin,ghcpKey:{editing:!0,draft:s,cursorIndex:s.length,saving:!1,error:null,lastSavedAt:t.admin.ghcpKey.lastSavedAt}}}}case"admin/ghcpKey/setDraft":{if(!t.admin.ghcpKey.editing)return t;const s=typeof e.draft=="string"?e.draft:"",n=Number.isFinite(e.cursorIndex)?Number(e.cursorIndex):s.length,i=Math.max(0,Math.min(n,s.length));return s===t.admin.ghcpKey.draft&&i===t.admin.ghcpKey.cursorIndex?t:{...t,admin:{...t.admin,ghcpKey:{...t.admin.ghcpKey,draft:s,cursorIndex:i,error:null}}}}case"admin/ghcpKey/cancelEdit":return!t.admin.ghcpKey.editing&&!t.admin.ghcpKey.draft?t:{...t,admin:{...t.admin,ghcpKey:{editing:!1,draft:"",cursorIndex:0,saving:!1,error:null,lastSavedAt:t.admin.ghcpKey.lastSavedAt}}};case"admin/ghcpKey/saving":return{...t,admin:{...t.admin,ghcpKey:{...t.admin.ghcpKey,saving:!0,error:null}}};case"admin/ghcpKey/saveFailed":return{...t,admin:{...t.admin,ghcpKey:{...t.admin.ghcpKey,saving:!1,error:e.error?String(e.error):"Failed to save key"}}};case"admin/ghcpKey/saved":return{...t,admin:{...t.admin,profile:e.profile||t.admin.profile,ghcpKey:{editing:!1,draft:"",cursorIndex:0,saving:!1,error:null,lastSavedAt:Date.now()}}};case"files/evictPreviews":{const s=Array.isArray(e.sessionIds)?e.sessionIds:[];if(s.length===0)return t;const n=ye(t.files.bySessionId);for(const i of s)n[i]&&(n[i]={...n[i],previews:{}});return{...t,files:{...t.files,bySessionId:n}}}case"files/sessionLoading":{const s=ye(t.files.bySessionId),n=s[e.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:null};return s[e.sessionId]={...n,loading:!0,error:null},{...t,files:{...t.files,bySessionId:s}}}case"files/sessionLoaded":{const s=ye(t.files.bySessionId),n=s[e.sessionId]||{previews:{},downloads:{}},i=Bt(e.entries),o=a=>i.some(l=>l.filename===a),r=n.selectedFilename&&o(n.selectedFilename)?n.selectedFilename:e.selectedFilename&&o(e.selectedFilename)?e.selectedFilename:i[0]?.filename||null;return s[e.sessionId]={...n,entries:i,selectedFilename:r,loading:!1,loaded:!0,error:null},{...t,files:{...t.files,bySessionId:s}}}case"files/sessionError":{const s=ye(t.files.bySessionId),n=s[e.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:null};return s[e.sessionId]={...n,loading:!1,loaded:!0,error:e.error||"Failed to load files"},{...t,files:{...t.files,bySessionId:s}}}case"files/select":{const s=ye(t.files.bySessionId),n=s[e.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:null};return s[e.sessionId]={...n,selectedFilename:e.filename||null},{...t,files:{...t.files,bySessionId:s,selectedArtifactId:e.sessionId&&e.filename?`${e.sessionId}/${e.filename}`:t.files.selectedArtifactId},ui:{...t.ui,scroll:{...t.ui.scroll,filePreview:0}}}}case"files/selectGlobal":return{...t,files:{...t.files,selectedArtifactId:e.artifactId||null},ui:{...t.ui,scroll:{...t.ui.scroll,filePreview:0}}};case"files/previewLoading":{const s=ye(t.files.bySessionId),n=s[e.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:e.filename||null},i={...n.previews||{},[e.filename]:{...n.previews?.[e.filename]||{},loading:!0,error:null}};return s[e.sessionId]={...n,previews:i},{...t,files:{...t.files,bySessionId:s}}}case"files/previewLoaded":{const s=ye(t.files.bySessionId),n=s[e.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:e.filename||null},i={...n.previews||{},[e.filename]:{loading:!1,error:null,content:e.content||"",contentType:e.contentType||"text/plain",renderMode:e.renderMode||"text",isBinary:e.isBinary===!0,sizeBytes:Number.isFinite(e.sizeBytes)?e.sizeBytes:null,uploadedAt:e.uploadedAt||"",source:e.source||"agent"}};return s[e.sessionId]={...n,previews:i},{...t,files:{...t.files,bySessionId:s}}}case"files/previewError":{const s=ye(t.files.bySessionId),n=s[e.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:e.filename||null},i={...n.previews||{},[e.filename]:{...n.previews?.[e.filename]||{},loading:!1,error:e.error||"Failed to load file preview"}};return s[e.sessionId]={...n,previews:i},{...t,files:{...t.files,bySessionId:s}}}case"files/downloaded":{const s=ye(t.files.bySessionId),n=s[e.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:e.filename||null},i={...n.downloads||{},[e.filename]:{localPath:e.localPath||null,downloadedAt:e.downloadedAt||Date.now()}};return s[e.sessionId]={...n,downloads:i},{...t,files:{...t.files,bySessionId:s}}}case"files/deleted":{const s=ye(t.files.bySessionId),n=s[e.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:null},i=Bt(n.entries).filter(d=>d.filename!==e.filename),o=n.selectedFilename===e.filename?i[0]?.filename||null:n.selectedFilename,{[e.filename]:r,...a}=n.previews||{},{[e.filename]:l,...p}=n.downloads||{},u=e.sessionId&&e.filename?`${e.sessionId}/${e.filename}`:null;return s[e.sessionId]={...n,entries:i,previews:a,downloads:p,selectedFilename:o},{...t,files:{...t.files,bySessionId:s,selectedArtifactId:t.files.selectedArtifactId===u?o?`${e.sessionId}/${o}`:null:t.files.selectedArtifactId},ui:{...t.ui,scroll:{...t.ui.scroll,filePreview:0}}}}case"files/fullscreen":return{...t,files:{...t.files,fullscreen:!!e.fullscreen},ui:e.fullscreen?{...t.ui,focusRegion:"inspector",fullscreenPane:null}:t.ui};case"files/filter":return{...t,files:{...t.files,filter:{...hs(t.files.filter),...hs(e.filter)},...hs(e.filter).scope==="selectedSession"?{}:{selectedArtifactId:t.files.selectedArtifactId||null}},ui:{...t.ui,scroll:{...t.ui.scroll,filePreview:0}}};case"logs/config":return{...t,logs:{...t.logs,available:!!e.available,availabilityReason:e.availabilityReason||t.logs.availabilityReason}};case"logs/tailing":return{...t,logs:{...t.logs,tailing:!!e.tailing}};case"logs/filter":return{...t,logs:{...t.logs,filter:{...t.logs.filter,...e.filter||{}}}};case"logs/set":return{...t,logs:{...t.logs,entries:$c(e.entries)}};case"logs/append":{const s=(Array.isArray(e.entries)?e.entries:[e.entry]).filter(Boolean);if(s.length===0)return t;const n=[...t.logs.entries||[],...s],i=n.length>1e3?n.slice(-1e3):n;return{...t,logs:{...t.logs,entries:i}}}default:return t}}function qc(t,e){let s=e;const n=new Set;return{getState(){return s},dispatch(i){const o=t(s,i);if(Object.is(o,s))return i;s=o;for(const r of n)r(s,i);return i},subscribe(i){return n.add(i),()=>n.delete(i)}}}const Kc=2e4,zc=2e4,Yc=3e4,Qc=30,ii="Session refresh failed",Xc=3,Jc=200,Zc=5,eu=new Set([w.SESSIONS,w.CHAT,w.INSPECTOR,w.ACTIVITY]);function tu(t){if(!t?.groupId)return null;const e=t.latestSummaryUpdatedAt?new Date(t.latestSummaryUpdatedAt).getTime():null,s=t.memberCount??0;return{sessionId:`group:${t.groupId}`,groupId:t.groupId,isGroup:!0,title:t.title||t.groupId,status:"group",description:t.description??null,owner:t.owner??null,shortSummary:`${s} grouped session${s===1?"":"s"}`,summaryUpdatedAt:Number.isFinite(e)?e:null,latestSummaryUpdatedAt:Number.isFinite(e)?e:null,memberCount:s,runningCount:t.runningCount??0,waitingCount:t.waitingCount??0,completedCount:t.completedCount??0,failedCount:t.failedCount??0,cancelledCount:t.cancelledCount??0,createdAt:t.createdAt?new Date(t.createdAt).getTime():0,updatedAt:t.updatedAt?new Date(t.updatedAt).getTime():Date.now()}}function oi(t){return!t?.sessionId||t.isGroup?t:{...t,groupId:t.groupId??null,parentSessionId:t.parentSessionId??null}}function gs(t){return String(t||"").startsWith("group:")?String(t).slice(6):null}async function su(t){if(typeof t.listSessionsPage!="function")return t.listSessions();const e=[];let s=null;for(let n=0;n<Zc;n+=1){const i=await t.listSessionsPage({limit:Jc,cursor:s}),o=Array.isArray(i?.sessions)?i.sessions:[];if(e.push(...o),!i?.hasMore||!i?.nextCursor)break;s=i.nextCursor}return e}function nu(t=[]){const e=[],s=new Map;for(const n of t){const i=n?.providerId||"models";let o=s.get(i);o||(o={providerId:i,providerType:n?.providerType||"provider",models:[]},s.set(i,o),e.push(o)),o.models.push(n)}return e}function Ns(t){if(!Array.isArray(t))return[];const e=[];for(const s of t){const n=String(s||"").trim().toLowerCase();!n||e.includes(n)||e.push(n)}return e}function ri(t){const e=Ns(t?.supportedReasoningEfforts);if(e.length===0)return null;const s=String(t?.defaultReasoningEffort||"").trim().toLowerCase();return s&&e.includes(s)?s:e.includes("medium")?"medium":e[0]||null}function Mo(t=[]){for(let e=t.length-1;e>=0;e-=1){const s=t[e];if(s?.eventType!=="session.model_changed")continue;const n=s?.data;if(!n||typeof n!="object")continue;const i=typeof n.newModel=="string"&&n.newModel?n.newModel:typeof n.model=="string"&&n.model?n.model:void 0;if(i)return{model:i,...typeof n.newReasoningEffort=="string"||n.newReasoningEffort===null?{reasoningEffort:n.newReasoningEffort}:{}}}}function iu(t){return Mo([t])}function ou(t,e=[]){let s=Mi(t);for(const n of e){const i=Pi(s,n?.eventType,n?.data,{timestamp:n?.createdAt});i&&(s=i)}return s}function Vt(t,e){if(Object.is(t,e))return!0;if(Array.isArray(t)||Array.isArray(e)){if(!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length)return!1;for(let i=0;i<t.length;i+=1)if(!Vt(t[i],e[i]))return!1;return!0}if(!t||!e||typeof t!="object"||typeof e!="object")return!1;const s=Object.keys(t),n=Object.keys(e);if(s.length!==n.length)return!1;for(const i of s)if(!Object.prototype.hasOwnProperty.call(e,i)||!Vt(t[i],e[i]))return!1;return!0}function ai(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(t instanceof Date)return t.getTime();const e=Date.parse(t||"");return Number.isFinite(e)?e:0}function Po(t,e){const s=ai(t?.updatedAt),n=ai(e?.updatedAt);return s>0&&n>0&&n<=s}function ru(t){return!t||t==="idle"||t==="unknown"||t==="pending"}function au(t,e){return t?.status==="waiting"&&typeof t?.waitReason=="string"&&t.waitReason.trim().length>0&&(e?.waitReason===void 0||e?.waitReason===null)&&ru(e?.status)&&Po(t,e)}function lu(t,e){return t?.cronActive===!0&&e?.cronActive!==!0&&!Oo(e?.status)&&!No(e?.orchestrationStatus)&&Po(t,e)}function cu(t,e){if(!e?.sessionId)return null;const s={sessionId:e.sessionId};let n=!1;for(const[a,l]of Object.entries(e))a==="sessionId"||l===void 0||Vt(t?.[a],l)||(s[a]=l,n=!0);if(e.pendingQuestion===void 0&&t?.pendingQuestion&&e.status!=="input_required"&&(s.pendingQuestion=null,n=!0),au(t,e)?(s.status!==t.status&&(s.status=t.status,n=!0),s.waitReason!==t.waitReason&&(s.waitReason=t.waitReason,n=!0)):e.waitReason===void 0&&t?.waitReason&&e.status!=="waiting"&&e.status!=="input_required"&&(s.waitReason=null,n=!0),Na(t,e)?s.error!==t.error&&(s.error=t.error,n=!0):e.error===void 0&&t?.error&&e.status!=="failed"&&e.status!=="error"&&(s.error=null,n=!0),e.result===void 0&&t?.result&&e.status!=="completed"&&(s.result=null,n=!0),lu(t,e))for(const a of["cronActive","cronKind","cronInterval","cronReason","cronNextFireAt","cronTimezone","cronMaxFires","cronFiresCompleted"])t?.[a]!=null&&(Vt(s[a],t[a])||(s[a]=t[a],n=!0));else if(e.cronActive!==!0){t?.cronReason&&(s.cronReason=null,n=!0);for(const a of["cronKind","cronNextFireAt","cronTimezone","cronMaxFires","cronFiresCompleted"])t?.[a]!=null&&e[a]===void 0&&(s[a]=null,n=!0);t?.cronInterval!=null&&e.cronInterval===void 0&&(s.cronInterval=null,n=!0)}if((Oo(e.status)||No(e.orchestrationStatus))&&t?.contextUsage?.compaction?.state==="running"&&e.contextUsage===void 0){const a={...t.contextUsage};delete a.compaction,s.contextUsage=Object.keys(a).length>0?a:null,n=!0}return n?s:null}function li(t){return String(t||"").replace(/\r\n/g,`
64
- `).trim()}function No(t){return t==="Completed"||t==="Failed"||t==="Terminated"}function Oo(t){return t==="completed"||t==="failed"||t==="cancelled"}function ie(t){return String(t||"").slice(0,8)}function gt(t){const e=String(t?.provider||"").trim(),s=String(t?.subject||"").trim();return e&&s?`${e}${s}`:null}function Ct(t,e="unknown user"){return String(t?.displayName||t?.email||"").trim()||e}function uu(t){const e=t.auth?.principal||null,s=gt(e),n=[{id:"all",kind:"all",label:"All",description:"Show every session, including system and unowned sessions."},{id:"system",kind:"system",label:"System",description:"Show sessions created by system agents."},{id:"unowned",kind:"unowned",label:"Unowned",description:"Show non-system sessions that do not have an owner link."}];if(s){const o=Ct(e,"current user");n.push({id:"me",kind:"me",label:`Me (${o})`,ownerKey:s,description:"Show sessions owned by the authenticated user currently signed in."})}const i=new Map;for(const o of Object.values(t.sessions?.byId||{})){const r=o?.owner,a=gt(r);!a||a===s||i.has(a)||i.set(a,r)}for(const[o,r]of[...i.entries()].sort((a,l)=>Ct(a[1]).localeCompare(Ct(l[1])))){const a=Ct(r),l=String(r?.email||"").trim();n.push({id:`owner:${o}`,kind:"owner",ownerKey:o,label:l&&l!==a?`${a} <${l}>`:a,description:"Show sessions owned by this user."})}return n}function Os(t){return gt(t)?{all:!1,includeSystem:!0,includeUnowned:!1,includeMe:!0,ownerKeys:[]}:{all:!0,includeSystem:!1,includeUnowned:!1,includeMe:!1,ownerKeys:[]}}function du(t){return!!(t?.includeSystem||t?.includeUnowned||t?.includeMe||Array.isArray(t?.ownerKeys)&&t.ownerKeys.length>0)}function fu(t,e,s){const n=t||Os(s);if(!e)return n;if(e.kind==="all")return n.all?Os(s):{all:!0,includeSystem:!1,includeUnowned:!1,includeMe:!1,ownerKeys:[]};const i={...n,all:!1,ownerKeys:Array.isArray(n.ownerKeys)?[...n.ownerKeys]:[]};if(e.kind==="system"&&(i.includeSystem=!i.includeSystem),e.kind==="unowned"&&(i.includeUnowned=!i.includeUnowned),e.kind==="me"&&(i.includeMe=!i.includeMe),e.kind==="owner"&&e.ownerKey){const o=i.ownerKeys.indexOf(e.ownerKey);o>=0?i.ownerKeys.splice(o,1):i.ownerKeys.push(e.ownerKey)}return du(i)?i:{all:!0,includeSystem:!1,includeUnowned:!1,includeMe:!1,ownerKeys:[]}}function un(t){if(!t?.agentId||t?.isSystem)return null;const e=String(t?.title||"").trim();if(!e)return null;const s=e.indexOf(": ");return s>0?e.slice(0,s).trim()||null:e||null}function pu(t){const e=un(t);return e?Math.max(1,60-`${e}: `.length):60}function hu(t){const e=String(t?.title||"").trim();if(!e)return"";const s=un(t);if(s&&e.startsWith(`${s}: `)){const n=e.slice(`${s}: `.length).trim();return!n||n===ie(t?.sessionId)?"":n}return e===ie(t?.sessionId)?"":e}function ci(t,e){const s=String(e||"").trim();if(s)return s;const n=String(t||"").trim();return n?n.charAt(0).toUpperCase()+n.slice(1):"Agent"}function ui(t){return`📎 ${String(t||"").trim()}`}function di(t,e){const s=String(t||""),n=X(s,e,s.length),o=s.slice(0,n).match(/(^|\s)(@@?)([^\s]*)$/u);if(!o)return null;const r=o[2],a=String(o[3]||"");return{kind:r==="@@"?"sessions":"artifacts",query:a,signature:`${r}${a}`,tokenStart:(o.index||0)+String(o[1]||"").length,tokenEnd:n}}function mu(t,e,s,n){const i=String(t||""),o=X(i,e),r=X(i,s),a=String(n||"");return{prompt:`${i.slice(0,o)}${a}${i.slice(r)}`,cursor:o+a.length}}function gu(t,e="session"){return String(t||"").replace(/\s+/gu," ").trim()||e}function yu(t){const e=String(t?.sessionId||"").trim(),s=ie(e)||"session";return`Referenced session: ${gu(t?.title,s)} — session://${e}`}function fi(t,e,s){if(!e)return _e(t,String(t||"").length,s);const n=String(t||""),i=n.slice(e.tokenEnd,e.tokenEnd+1),o=!i||/\s/u.test(i);return mu(n,e.tokenStart,e.tokenEnd,`${String(s||"")}${o?" ":""}`)}function Su(t,e=[]){let s=String(t||"");for(const n of e||[]){const i=String(n?.token||"").trim();i&&(s=s.split(i).join(" "))}return s.replace(/[ \t]+\n/g,`
65
- `).replace(/\n[ \t]+/g,`
66
- `).replace(/[ \t]{2,}/g," ").trim()}function bu(t,e=[]){const s=Array.isArray(e)?e.filter(o=>o?.sessionId&&o?.filename):[];if(s.length===0)return String(t||"");const n=s.map(o=>`[Attached file: ${o.filename} — artifact://${o.sessionId}/${o.filename}]`),i=Su(t,s);return n.join(`
67
- `)+(i?`
68
-
69
- ${i}`:"")}function At(t,e){return String(t||"").replace(/\r?\n/g," ").slice(0,Math.max(0,Number(e)||0))}function Ro(t){return Array.from(String(t||"")).length}function wu(t){const e=[];for(const s of t||[]){if(s?.kind==="markup"){const n=Oi(s.value||"");for(const i of n)e.push(i);continue}if(Array.isArray(s)){e.push(s);continue}e.push(s)}return e}function Iu(t,e){const s=Math.max(1,Number(e)||1),n=Ro(t);return Math.max(1,Math.ceil(n/s))}function Ge(t,e){const s=Math.max(1,Number(e)||1);return wu(t).reduce((n,i)=>{if(!i)return n+1;if(Array.isArray(i)){const o=i.reduce((r,a)=>r+Ro(a?.text||""),0);return n+Math.max(1,Math.ceil(o/s))}return n+Iu(i.text||"",s)},0)}function X(t,e){const s=String(t||"");return Math.max(0,Math.min(Number(e)||0,s.length))}function Fo(t){return String(t||"").split(`
70
- `)}function xu(t,e){const n=String(t||"").slice(0,X(t,e)).split(`
71
- `),i=n[n.length-1]||"";return{line:Math.max(0,n.length-1),column:i.length}}function Eu(t,e,s){const n=Fo(t),i=Math.max(0,Math.min(Number(e)||0,Math.max(0,n.length-1))),o=Math.max(0,Math.min(Number(s)||0,n[i]?.length||0));let r=0;for(let a=0;a<i;a+=1)r+=(n[a]?.length||0)+1;return X(t,r+o)}function _e(t,e,s){const n=String(t||""),i=X(n,e),o=String(s||"");return{prompt:`${n.slice(0,i)}${o}${n.slice(i)}`,cursor:i+o.length}}function st(t,e){const s=String(t||""),n=X(s,e);return n<=0?{prompt:s,cursor:n}:{prompt:`${s.slice(0,n-1)}${s.slice(n)}`,cursor:n-1}}function Tt(t){return/\s/u.test(t||"")}function _o(t,e,s){const n=String(t||"");let i=X(n,e);if(s<0){for(;i>0&&Tt(n[i-1]);)i-=1;for(;i>0&&!Tt(n[i-1]);)i-=1;return i}for(;i<n.length&&Tt(n[i]);)i+=1;for(;i<n.length&&!Tt(n[i]);)i+=1;return i}function vu(t,e){const s=String(t||""),n=X(s,e),i=_o(s,n,-1);return i===n?{prompt:s,cursor:n}:{prompt:`${s.slice(0,i)}${s.slice(n)}`,cursor:i}}function Cu(t,e,s){const n=Fo(t);if(n.length<=1)return X(t,e);const i=xu(t,e),o=Math.max(0,Math.min(i.line+s,n.length-1));return o===i.line?X(t,e):Eu(t,o,i.column)}const pi=3e3,Au=new Set(["logs","sequence"]),Tu=2e5,ku=new Set([".md",".markdown",".mdown",".mkd",".mdx"]),Mu=new Set([".json",".jsonl"]),Pu=new Set([".png",".jpg",".jpeg",".gif",".webp",".svg",".ico",".pdf",".zip",".gz",".tgz",".tar",".wasm",".sqlite",".db"]);function Lo(t){const e=String(t||""),s=e.lastIndexOf(".");return s>=0?e.slice(s).toLowerCase():""}function Nu(t,e=""){const s=Lo(t),n=String(e||"").toLowerCase();return Pu.has(s)?!0:n.startsWith("image/")||n==="application/pdf"||n.startsWith("application/zip")||n==="application/wasm"}function hi(t,e=Tu){const s=String(t??"");return s.length<=e?s:`${s.slice(0,e)}
72
-
73
- [Preview truncated at ${e.toLocaleString()} characters. Open the artifact directly if you need the full file.]`}function Ou(t){const e=Number(t);if(!Number.isFinite(e)||e<0)return"?";if(e<1024)return`${Math.round(e)} B`;if(e<1024*1024){const n=e/1024;return`${n>=10?Math.round(n):n.toFixed(1)} KB`}const s=e/(1024*1024);return`${s>=10?Math.round(s):s.toFixed(1)} MB`}function Ru(t,e="",s=null){const n=[`Preview is not available here for ${t}.`,""];return e&&n.push(`Type: ${e}`),s!=null&&n.push(`Size: ${Ou(s)}`),n.push("Download the artifact to open it in the default app."),n.join(`
74
- `)}function mi(t,e,s="",n=null){const i=String(s||"").toLowerCase(),o=Lo(t);if(n?.isBinary===!0||Nu(t,s))return{content:Ru(t,n?.contentType||s,n?.sizeBytes??null),contentType:n?.contentType||s||"application/octet-stream",renderMode:"note",isBinary:!0,sizeBytes:n?.sizeBytes??null,uploadedAt:n?.uploadedAt||"",source:n?.source||"agent"};const r=hi(e);if(ku.has(o)||i.includes("markdown"))return{content:r,contentType:s||"text/markdown",renderMode:"markdown",isBinary:!1,sizeBytes:n?.sizeBytes??null,uploadedAt:n?.uploadedAt||"",source:n?.source||"agent"};if(Mu.has(o)||i.includes("json"))try{return{content:hi(JSON.stringify(JSON.parse(String(e??"")),null,2)),contentType:s||"application/json",renderMode:"text"}}catch{return{content:r,contentType:s||"application/json",renderMode:"text"}}return{content:r,contentType:s||"text/plain",renderMode:"text"}}class Fu{constructor({store:e,transport:s}){this.store=e,this.transport=s,this.catalogTimer=null,this.activeSessionUnsub=null,this.activeSessionSubscriptionId=null,this.activeSessionDetailTimer=null,this.activeSessionDetailSessionId=null,this.sessionRefreshTimer=null,this.sessionHistoryLoads=new Map,this.sessionHistoryExpansionLoads=new Map,this.sessionOrchestrationStatsLoads=new Map,this.outboxFlushPromises=new Map,this.logUnsubscribe=null,this.promptReferenceSignature=null,this.promptReferenceSyncVersion=0,this.chatTopHistoryLoadArmed=!1,this.chatTopHistoryLoadSessionId=null}getState(){return this.store.getState()}subscribe(e){return this.store.subscribe(e)}dispatch(e){return this.store.dispatch(e)}setStatus(e){this.dispatch({type:"ui/status",text:e})}getPromptAttachments(){const e=this.getState().ui.promptAttachments;return Array.isArray(e)?e.filter(Boolean):[]}setPromptAttachments(e){this.dispatch({type:"ui/promptAttachments",attachments:Array.isArray(e)?e:[]})}getSessionOutbox(e){if(!e)return[];const s=this.getState().outbox?.bySessionId?.[e];return Array.isArray(s)?s.filter(Boolean):[]}setSessionOutboxItems(e,s){e&&this.dispatch({type:"outbox/setSessionItems",sessionId:e,items:Array.isArray(s)?s:[]})}buildOutboxItem(e,s="pending"){const n=`msg:${Date.now()}:${Math.random().toString(36).slice(2,10)}`,i=s==="queued"||s==="cancelling"?s:"pending";return{id:n,text:String(e||""),createdAt:Date.now(),phase:i,clientMessageIds:[n]}}getPendingOutboxItems(e){return this.getSessionOutbox(e).filter(s=>s?.phase==="pending")}getQueuedOutboxItems(e){return this.getSessionOutbox(e).filter(s=>s?.phase==="queued")}getNavigableOutboxItems(e){return this.getSessionOutbox(e).filter(s=>s?.phase==="pending"||s?.phase==="queued"||s?.phase==="cancelling")}getEditableOutboxItems(e){return this.getPendingOutboxItems(e)}getPromptEditSessionMatch(e=this.getState().sessions.activeSessionId){const s=this.getState().ui.promptEdit;return s?.sessionId===e?s:null}enterPendingPromptEdit(e,s){if(!e||!s)return!1;const i=this.getNavigableOutboxItems(e).find(l=>l.id===s);if(!i)return!1;const o=this.getState().ui,r=this.getPromptEditSessionMatch(e),a=r?{...r,itemId:s,phase:i.phase}:{sessionId:e,itemId:s,phase:i.phase,draftPrompt:o.prompt,draftCursor:o.promptCursor};return this.dispatch({type:"ui/promptEdit",promptEdit:a}),this.setPrompt(i.text,i.text.length),this.setFocus(w.PROMPT),!0}exitPendingPromptEdit({restoreDraft:e=!0}={}){const s=this.getState().ui.promptEdit;return s?(this.dispatch({type:"ui/promptEdit",promptEdit:null}),e&&this.setPrompt(s.draftPrompt||"",Number.isFinite(s.draftCursor)?s.draftCursor:String(s.draftPrompt||"").length),!0):!1}selectPreviousPendingPrompt(e=this.getState().sessions.activeSessionId){const s=this.getNavigableOutboxItems(e);if(s.length===0)return!1;const n=this.getPromptEditSessionMatch(e);if(!n)return this.enterPendingPromptEdit(e,s[s.length-1].id);const i=s.findIndex(o=>o.id===n.itemId);return i<=0?!1:this.enterPendingPromptEdit(e,s[i-1].id)}selectNextPendingPrompt(e=this.getState().sessions.activeSessionId){const s=this.getNavigableOutboxItems(e),n=this.getPromptEditSessionMatch(e);if(!n)return!1;const i=s.findIndex(o=>o.id===n.itemId);return i===-1||i>=s.length-1?this.exitPendingPromptEdit({restoreDraft:!0}):this.enterPendingPromptEdit(e,s[i+1].id)}async cancelSelectedOutboxPrompt(){const e=this.getState().ui.promptEdit;if(!e?.sessionId||!e?.itemId)return!1;const n=this.getSessionOutbox(e.sessionId).find(o=>o.id===e.itemId);return n?n.phase==="cancelling"?(this.exitPendingPromptEdit({restoreDraft:!0}),!1):await this.cancelOutboxItem(e.sessionId,e.itemId)?(this.exitPendingPromptEdit({restoreDraft:!0}),!0):!1:!1}cancelSelectedPendingPrompt(){const e=this.getState().ui.promptEdit;if(!e?.sessionId||!e?.itemId)return!1;const s=this.getSessionOutbox(e.sessionId);if(!s.find(o=>o.id===e.itemId&&o.phase==="pending"))return!1;const i=s.filter(o=>o.id!==e.itemId);return this.setSessionOutboxItems(e.sessionId,i),this.exitPendingPromptEdit({restoreDraft:!0}),this.dispatch({type:"ui/status",text:"Cancelled pending prompt"}),!0}async cancelOutboxItem(e,s){if(!e||!s)return!1;const n=this.getSessionOutbox(e),i=n.find(r=>r.id===s);if(!i||i.phase==="cancelling")return!1;this.getPromptEditSessionMatch(e)?.itemId===s&&this.exitPendingPromptEdit({restoreDraft:!0});const o=Array.isArray(i.clientMessageIds)&&i.clientMessageIds.length>0?i.clientMessageIds:[i.id];if(i.phase==="queued")if(this.setSessionOutboxItems(e,n.map(r=>r.id===s?{...r,phase:"cancelling"}:r)),typeof this.transport?.cancelPendingMessage=="function")try{await this.transport.cancelPendingMessage(e,o),this.dispatch({type:"ui/status",text:"Cancelling queued prompt"})}catch(r){return this.setSessionOutboxItems(e,n),this.dispatch({type:"ui/status",text:r?.message||String(r)}),!1}else this.dispatch({type:"ui/status",text:"Queued prompt marked cancelling (local only — transport has no cancel)"});else{const r=n.filter(a=>a.id!==s);if(this.setSessionOutboxItems(e,r),typeof this.transport?.cancelPendingMessage=="function")try{await this.transport.cancelPendingMessage(e,o)}catch{}this.dispatch({type:"ui/status",text:"Cancelled pending prompt"})}return!0}async cancelLatestQueuedOutbox(e=this.getState().sessions.activeSessionId){if(!e)return!1;const s=this.getQueuedOutboxItems(e);if(s.length===0)return!1;const n=s[s.length-1];return await this.cancelOutboxItem(e,n.id)}queuePromptInOutbox(e,s){const n=this.buildOutboxItem(s,"pending");return this.setSessionOutboxItems(e,[...this.getSessionOutbox(e),n]),n}acknowledgeOutboxPrompt(e,s,n=null){if(!e)return!1;const i=this.getSessionOutbox(e);if(n){const l=i.findIndex(p=>(p?.phase==="pending"||p?.phase==="queued"||p?.phase==="cancelling")&&Array.isArray(p.clientMessageIds)&&p.clientMessageIds.includes(n));if(l!==-1){const p=i[l];return this.setSessionOutboxItems(e,i.filter((u,d)=>d!==l)),this.getPromptEditSessionMatch(e)?.itemId===p?.id&&this.exitPendingPromptEdit({restoreDraft:!0}),!0}}const o=li(s);if(!o)return!1;const r=i.findIndex(l=>(l?.phase==="pending"||l?.phase==="queued"||l?.phase==="cancelling")&&li(l.text)===o);if(r===-1)return!1;const a=i[r];return this.setSessionOutboxItems(e,i.filter((l,p)=>p!==r)),this.getPromptEditSessionMatch(e)?.itemId===a?.id&&this.exitPendingPromptEdit({restoreDraft:!0}),!0}acknowledgeCancelledOutboxPrompt(e,s=[]){if(!e)return!1;const n=new Set((s||[]).filter(l=>typeof l=="string"&&l));if(n.size===0)return!1;const i=this.getSessionOutbox(e),o=i.filter(l=>l?.phase!=="cancelling"?!0:!(Array.isArray(l.clientMessageIds)?l.clientMessageIds:[l.id]).some(u=>n.has(u)));if(o.length===i.length)return!1;const r=new Set(i.filter(l=>!o.some(p=>p.id===l.id)).map(l=>l.id));this.setSessionOutboxItems(e,o);const a=this.getPromptEditSessionMatch(e);return a&&r.has(a.itemId)&&this.exitPendingPromptEdit({restoreDraft:!0}),!0}scheduleOutboxDispatch(e){if(!e||(this._outboxDispatchTimers||(this._outboxDispatchTimers=new Map),this._outboxDispatchTimers.has(e)))return;const s=setTimeout(()=>{this._outboxDispatchTimers.delete(e),this.dispatchPendingOutbox(e).catch(()=>{})},10);this._outboxDispatchTimers.set(e,s)}async dispatchPendingOutbox(e){if(!e)return!1;await Promise.resolve();const s=this.outboxFlushPromises.get(e);if(s)return await s.catch(()=>{}),this.getPendingOutboxItems(e).length>0&&this.scheduleOutboxDispatch(e),!1;const n=this.getPendingOutboxItems(e);if(n.length===0)return!1;const i=n.flatMap(d=>Array.isArray(d.clientMessageIds)&&d.clientMessageIds.length>0?d.clientMessageIds:[d.id]),o=n.map(d=>String(d.text||"")).join(`
75
-
76
- `),r={id:n[0].id,text:o,createdAt:n[0].createdAt||Date.now(),phase:"pending",clientMessageIds:i},a=new Set(n.map(d=>d.id)),l=this.getSessionOutbox(e).filter(d=>!a.has(d.id));this.setSessionOutboxItems(e,[...l,r]);const p=this.getPromptEditSessionMatch(e);p&&a.has(p.itemId)&&this.exitPendingPromptEdit({restoreDraft:!0});const u=(async()=>{await this.transport.sendMessage(e,r.text,{enqueueOnly:!0,clientMessageIds:r.clientMessageIds});const f=this.getSessionOutbox(e).map(h=>h.id===r.id?{...h,phase:"queued"}:h);return this.setSessionOutboxItems(e,f),this.syncSessionEvents(e).catch(()=>{}),this.scheduleSessionsRefresh(250),!0})().catch(d=>{const h=this.getSessionOutbox(e).flatMap(m=>m.id===r.id?n:[m]);throw this.setSessionOutboxItems(e,h),this.dispatch({type:"ui/status",text:d?.message||String(d)}),d}).finally(()=>{this.outboxFlushPromises.delete(e),this.getPendingOutboxItems(e).length>0&&this.scheduleOutboxDispatch(e)});return this.outboxFlushPromises.set(e,u),await u}async flushQueuedOutbox(e){return await this.dispatchPendingOutbox(e)}maybeFlushQueuedOutbox(e){return!e||this.getPendingOutboxItems(e).length===0?!1:(this.scheduleOutboxDispatch(e),!0)}getPromptReferenceContext(){const e=this.getState();return di(e.ui.prompt,e.ui.promptCursor)}acceptPromptReferenceAutocomplete(){const e=this.getPromptReferenceContext();return e?e.kind==="sessions"?this.acceptSessionPromptReference(e):this.acceptArtifactPromptReference(e):!1}acceptArtifactPromptReference(e=this.getPromptReferenceContext()){if(!e||e.kind!=="artifacts")return!1;const s=this.getState(),n=Me(s),i=n?.sessionId||s.sessions.activeSessionId||null,o=n?.filename||null;if(!i||!o)return!1;const r=ui(o),a=fi(s.ui.prompt,e,r),l=this.getPromptAttachments(),p=l.findIndex(f=>f?.sessionId===i&&f?.filename===o),u={...p>=0?l[p]:{},id:`${i}/${o}`,sessionId:i,filename:o,resolvedPath:o,token:r},d=p>=0?l.map((f,h)=>h===p?u:f):[...l,u];return this.setPrompt(a.prompt,a.cursor),this.setPromptAttachments(d),this.setFocus(w.PROMPT),this.dispatch({type:"ui/status",text:`Attached ${o}`}),!0}acceptSessionPromptReference(e=this.getPromptReferenceContext()){if(!e||e.kind!=="sessions")return!1;const s=this.getState(),i=ht(s)[0]||null,o=i?.sessionId&&s.sessions.byId[i.sessionId]||null;if(!o?.sessionId)return!1;const r=yu(o),a=fi(s.ui.prompt,e,r);return this.setPrompt(a.prompt,a.cursor),this.setFocus(w.PROMPT),this.dispatch({type:"ui/status",text:`Referenced session ${ie(o.sessionId)}`}),!0}setSessionFilterQuery(e=""){this.dispatch({type:"sessions/filterQuery",query:String(e||"")})}openSessionOwnerFilter(){const e=this.getState(),s=uu(e);this.dispatch({type:"ui/modal",modal:{type:"sessionOwnerFilter",title:"Session Filter",previousFocus:e.ui.focusRegion,selectedIndex:0,items:s}}),this.dispatch({type:"ui/status",text:"Up/Down choose entry · Space toggle · Esc close"})}toggleSessionOwnerFilter(e=null){const s=this.getState(),n=s.ui.modal;if(!n||n.type!=="sessionOwnerFilter")return;const i=e==null?Math.max(0,Number(n.selectedIndex)||0):Math.max(0,Number(e)||0),o=n.items?.[i];if(!o)return;const r=fu(s.sessions.ownerFilter,o,s.auth?.principal);this.dispatch({type:"sessions/ownerFilter",filter:r}),this.dispatch({type:"ui/modalSelection",index:i}),this.dispatch({type:"ui/status",text:`Session filter updated: ${o.label||o.id||"selection"}`})}setFilesFilter(e={}){this.dispatch({type:"files/filter",filter:e})}clearPromptReferenceBrowser(){this.promptReferenceSignature=null,this.promptReferenceSyncVersion+=1,this.getState().sessions.filterQuery&&this.setSessionFilterQuery(""),this.getState().files.filter?.query&&this.setFilesFilter({query:""})}syncPromptReferenceBrowser(){const e=this.getState(),s=di(e.ui.prompt,e.ui.promptCursor);if(!s){this.clearPromptReferenceBrowser();return}if(this.promptReferenceSignature===s.signature)return;if(this.promptReferenceSignature=s.signature,s.kind==="sessions"){this.promptReferenceSyncVersion+=1,this.setFilesFilter({query:""}),this.setSessionFilterQuery(s.query);return}const n=e.sessions.activeSessionId;if(this.setSessionFilterQuery(""),this.setFilesFilter({scope:"selectedSession",query:s.query}),!n)return;this.selectInspectorTab("files").catch(()=>{});const i=++this.promptReferenceSyncVersion;this.ensureFilesForScope("selectedSession").then(async()=>{if(this.promptReferenceSyncVersion!==i)return;const o=new Set(Wt(this.getState(),"selectedSession")),a=mt(this.getState()).filter(l=>o.has(l.sessionId))[0]||null;a?.filename&&(this.dispatch({type:"files/select",sessionId:a.sessionId,filename:a.filename}),await this.ensureFilePreview(a.sessionId,a.filename).catch(()=>{}))}).catch(()=>{})}async start(){await this.transport.start();const e=typeof this.transport.getAuthContext=="function"?this.transport.getAuthContext():null;this.dispatch({type:"auth/context",principal:e?.principal??null,authorization:e?.authorization??null}),this.getState().sessions.ownerFilterExplicit||this.dispatch({type:"sessions/ownerFilter",filter:Os(e?.principal??null)});const s=typeof this.transport.getLogConfig=="function"?this.transport.getLogConfig():null;s&&this.dispatch({type:"logs/config",available:s.available,availabilityReason:s.availabilityReason}),this.dispatch({type:"connection/ready",workersOnline:typeof this.transport.getWorkerCount=="function"?this.transport.getWorkerCount():null,statusText:"Connected"}),await this.refreshSessions(),this.catalogTimer=setInterval(()=>{this.refreshSessions().catch(n=>{this.dispatch({type:"connection/error",error:n?.message||String(n),statusText:ii})})},4e3)}async stop(){this.catalogTimer&&clearInterval(this.catalogTimer),this.catalogTimer=null,this.activeSessionDetailTimer&&clearTimeout(this.activeSessionDetailTimer),this.activeSessionDetailTimer=null,this.activeSessionDetailSessionId=null,this.sessionRefreshTimer&&clearTimeout(this.sessionRefreshTimer),this.sessionRefreshTimer=null,this.sessionHistoryExpansionLoads.clear(),this.sessionOrchestrationStatsLoads.clear(),this.detachActiveSession(),this.detachLogStream(),await this.transport.stop()}detachActiveSession(){this.activeSessionUnsub&&(this.activeSessionUnsub(),this.activeSessionUnsub=null),this.activeSessionSubscriptionId=null}detachLogStream(){this.logUnsubscribe&&(this.logUnsubscribe(),this.logUnsubscribe=null)}async refreshSessions(){const e=this.getState(),s=!e.connection.connected||!!e.connection.error,n=e.ui.statusText===ii,i=this.getState().sessions.activeSessionId;let o=(await su(this.transport)).map(oi);if(typeof this.transport.listSessionGroups=="function"){const p=await this.transport.listSessionGroups().catch(()=>[]),u=(Array.isArray(p)?p:[]).map(tu).filter(Boolean);u.length>0&&(o=[...u,...o])}const r=i;if(r&&!o.some(p=>p?.sessionId===r)&&typeof this.transport.getSession=="function"){const p=await this.transport.getSession(r).catch(()=>null);p?.sessionId&&(o=[...o,oi(p)])}s&&this.dispatch({type:"connection/ready",workersOnline:typeof this.transport.getWorkerCount=="function"?this.transport.getWorkerCount():null,...n?{statusText:"Connected"}:{}}),this.dispatch({type:"sessions/loaded",sessions:o});const a=this.getState().sessions.activeSessionId,l=new Set;if(a){if(a!==i){this.getState().sessions.byId[a]?.isGroup||await this.loadSession(a);return}if(this.getState().sessions.byId[a]?.isGroup)return;this.getState().history.bySessionId.get(a)?.events?.length||await this.ensureSessionHistory(a,{force:!0}).catch(()=>{}),this.activeSessionSubscriptionId!==a&&this.attachActiveSession(a),await this.syncSessionDetail(a).catch(()=>{}),await this.syncSessionEvents(a).catch(()=>{}),l.add(a);const u=this.getState(),d=u.sessions.byId[a]||null;if(d?.parentSessionId&&typeof this.transport.getSession=="function"){const f=Object.values(u.sessions.byId).filter(h=>h?.parentSessionId===d.parentSessionId).map(h=>h.sessionId).filter(h=>h&&h!==a).slice(0,6);await Promise.all(f.map(h=>this.syncSessionDetail(h).catch(()=>{})));for(const h of f)l.add(h)}}await this.syncVisibleSessionDetails(l).catch(()=>{}),this.ensureInspectorData().catch(()=>{}),this.evictStaleSessionState()}evictStaleSessionState(){const e=this.getState(),s=e.sessions.activeSessionId,n=Date.now(),i=6e4,o=20,r=Object.entries(e.orchestration.bySessionId||{});if(r.length>o){const u=r.filter(([d,f])=>d!==s&&!f?.loading).sort((d,f)=>(d[1]?.fetchedAt||0)-(f[1]?.fetchedAt||0)).slice(0,r.length-o).filter(([,d])=>n-(d?.fetchedAt||0)>i);u.length>0&&this.dispatch({type:"orchestration/evict",sessionIds:u.map(([d])=>d)})}const a=Object.entries(e.executionHistory?.bySessionId||{});if(a.length>o){const u=a.filter(([d,f])=>d!==s&&!f?.loading).sort((d,f)=>(d[1]?.fetchedAt||0)-(f[1]?.fetchedAt||0)).slice(0,a.length-o).filter(([,d])=>n-(d?.fetchedAt||0)>i);u.length>0&&this.dispatch({type:"executionHistory/evict",sessionIds:u.map(([d])=>d)})}const l=Object.entries(e.files.bySessionId||{});if(l.length>o){const u=l.filter(([d])=>d!==s).slice(0,l.length-o);u.length>0&&this.dispatch({type:"files/evictPreviews",sessionIds:u.map(([d])=>d)})}const p=[...e.history.bySessionId.entries()];if(p.length>o*2){const u=p.filter(([d])=>d!==s).slice(0,p.length-o*2).map(([d])=>d);u.length>0&&this.dispatch({type:"history/evict",sessionIds:u})}}async syncVisibleSessionDetails(e=new Set){if(typeof this.transport.getSession!="function")return;const s=this.getState(),n=lt({width:s.ui.layout.viewportWidth,height:s.ui.layout.viewportHeight},s.ui.layout.paneAdjust,s.ui.promptRows??ze(s.ui.prompt),s.ui.layout.sessionPaneAdjust,s.ui.layout.activityPaneAdjust,s.ui.fullscreenPane),i=this.getSessionListMaxRows(n),o=Ts(s,i),r=[...new Set(o.map(a=>a.sessionId).filter(a=>a&&!e.has(a)))];r.length!==0&&await Promise.all(r.map(a=>this.syncSessionDetail(a).catch(()=>{})))}async ensureSessionHistory(e,{force:s=!1}={}){if(!e)return null;const n=this.getState().history.bySessionId.get(e),i=Math.max(V,Number(n?.loadedEventLimit??V)||V);if(!s&&n?.events)return n;if(!s&&this.sessionHistoryLoads.has(e))return this.sessionHistoryLoads.get(e);const o=(async()=>{const r=await this.transport.getSessionEvents(e,void 0,i),a={...xt(r,{requestedLimit:i}),lastSeq:r[r.length-1]?.seq||0};this.dispatch({type:"history/set",sessionId:e,history:a});for(const d of r||[])this.reconcileOutboxAgainstEvent(e,d);const l=Mo(r),p=this.getState().sessions.byId[e]||{},u=ou(p.contextUsage,r);return(l||u)&&this.dispatch({type:"sessions/merged",session:{sessionId:e,...l||{},...u?{contextUsage:u}:{}}}),a})().finally(()=>{this.sessionHistoryLoads.delete(e)});return this.sessionHistoryLoads.set(e,o),o}async ensureInspectorData(e=this.getState().ui.inspectorTab){if(e==="sequence"){const s=this.getState().sessions.activeSessionId;if(!s)return;await this.ensureSessionHistory(s).catch(()=>{}),await this.ensureOrchestrationStats(s).catch(()=>{});return}if(e==="nodes"){const s=this.getState(),n=lt({width:s.ui.layout.viewportWidth,height:s.ui.layout.viewportHeight},s.ui.layout.paneAdjust,s.ui.promptRows??ze(s.ui.prompt),s.ui.layout.sessionPaneAdjust,s.ui.layout.activityPaneAdjust,s.ui.fullscreenPane),i=this.getSessionListMaxRows(n),o=Ts(s,i),r=[...new Set(o.map(a=>a.sessionId).filter(Boolean))];if(r.length===0)return;await Promise.allSettled(r.map(a=>this.ensureSessionHistory(a)));return}if(e==="files"&&await this.ensureFilesForScope(de(this.getState())),e==="history"){const s=this.getState().sessions.activeSessionId,n=s&&this.getState().executionHistory?.bySessionId?.[s]||null;s&&!n&&await this.ensureExecutionHistory(s)}e==="stats"&&(await this.ensureSessionStats().catch(()=>{}),await this.ensureFleetStats().catch(()=>{}))}async ensureOrchestrationStats(e,{force:s=!1}={}){if(!e||typeof this.transport.getOrchestrationStats!="function")return null;const n=this.getState().orchestration.bySessionId?.[e]||null,i=Date.now();if(!s&&n?.loading||!s&&n&&Number.isFinite(n.fetchedAt)&&i-n.fetchedAt<Kc)return n;if(!s&&this.sessionOrchestrationStatsLoads.has(e))return this.sessionOrchestrationStatsLoads.get(e);this.dispatch({type:"orchestration/statsLoading",sessionId:e});const o=(async()=>{try{const r=await this.transport.getOrchestrationStats(e);return this.dispatch({type:"orchestration/statsLoaded",sessionId:e,stats:r,fetchedAt:Date.now()}),this.getState().orchestration.bySessionId?.[e]||null}catch(r){return this.dispatch({type:"orchestration/statsError",sessionId:e,error:r?.message||String(r),fetchedAt:Date.now()}),null}})().finally(()=>{this.sessionOrchestrationStatsLoads.delete(e)});return this.sessionOrchestrationStatsLoads.set(e,o),o}async ensureSessionStats({force:e=!1}={}){const s=this.getState().sessions.activeSessionId;if(!s||typeof this.transport.getSessionMetricSummary!="function")return;const n=this.getState().sessionStats?.bySessionId?.[s]||null,i=Date.now();if(!(!e&&n?.loading)&&!(!e&&n&&Number.isFinite(n.fetchedAt)&&i-n.fetchedAt<zc)){this.dispatch({type:"sessionStats/loading",sessionId:s});try{const[o,r,a,l,p,u,d]=await Promise.all([this.transport.getSessionMetricSummary(s),typeof this.transport.getSessionTokensByModel=="function"?this.transport.getSessionTokensByModel(s).catch(()=>[]):[],typeof this.transport.getSessionTreeStats=="function"?this.transport.getSessionTreeStats(s):null,typeof this.transport.getSessionSkillUsage=="function"?this.transport.getSessionSkillUsage(s).catch(()=>null):null,typeof this.transport.getSessionTreeSkillUsage=="function"?this.transport.getSessionTreeSkillUsage(s).catch(()=>null):null,typeof this.transport.getSessionFactsStats=="function"?this.transport.getSessionFactsStats(s).catch(()=>null):null,typeof this.transport.getSessionTreeFactsStats=="function"?this.transport.getSessionTreeFactsStats(s).catch(()=>null):null]);this.dispatch({type:"sessionStats/loaded",sessionId:s,summary:o,tokensByModel:r,treeStats:a,skillUsage:l,treeSkillUsage:p,factsStats:u,treeFactsStats:d})}catch{this.dispatch({type:"sessionStats/loaded",sessionId:s,summary:null,tokensByModel:[],treeStats:null,skillUsage:null,treeSkillUsage:null,factsStats:null,treeFactsStats:null})}}}async ensureFleetStats({force:e=!1}={}){if(typeof this.transport.getFleetStats!="function")return;const s=this.getState().fleetStats,n=Date.now();if(!(!e&&s?.loading)&&!(!e&&s?.data&&Number.isFinite(s.fetchedAt)&&n-s.fetchedAt<Yc)){this.dispatch({type:"fleetStats/loading"});try{const o={since:new Date(Date.now()-Qc*864e5),includeDeleted:!0},[r,a,l,p,u,d]=await Promise.all([this.transport.getFleetStats(o),typeof this.transport.getUserStats=="function"?this.transport.getUserStats(o).catch(()=>null):null,typeof this.transport.getFleetSkillUsage=="function"?this.transport.getFleetSkillUsage(o).catch(()=>null):null,typeof this.transport.getFleetRetrievalUsage=="function"?this.transport.getFleetRetrievalUsage(o).catch(()=>null):null,typeof this.transport.getSharedFactsStats=="function"?this.transport.getSharedFactsStats().catch(()=>null):null,typeof this.transport.getFactsTombstoneStats=="function"?this.transport.getFactsTombstoneStats().catch(()=>null):null]);this.dispatch({type:"fleetStats/loaded",data:r,userStats:a,skillUsage:l,retrievalUsage:p,sharedFactsStats:u,factsTombstoneStats:d})}catch{this.dispatch({type:"fleetStats/loaded",data:null,userStats:null,skillUsage:null,retrievalUsage:null,sharedFactsStats:null,factsTombstoneStats:null})}}}async openAdminConsole(){this.dispatch({type:"admin/visibility",visible:!0}),await this.refreshAdminProfile().catch(()=>{})}closeAdminConsole(){this.dispatch({type:"admin/visibility",visible:!1})}async refreshAdminProfile(){if(typeof this.transport.getCurrentUserProfile!="function")return this.dispatch({type:"admin/profile/loadFailed",error:"Admin Console is not available on this transport."}),null;this.dispatch({type:"admin/profile/loading"});try{const e=await this.transport.getCurrentUserProfile();return this.dispatch({type:"admin/profile/loaded",profile:e}),e||null}catch(e){return this.dispatch({type:"admin/profile/loadFailed",error:e?.message||String(e)}),null}}beginAdminEditGhcpKey(){this.dispatch({type:"admin/ghcpKey/beginEdit",draft:""})}setAdminGhcpKeyDraft(e,s=String(e||"").length){this.dispatch({type:"admin/ghcpKey/setDraft",draft:e,cursorIndex:s})}insertAdminGhcpKeyText(e){const s=this.getState().admin?.ghcpKey;if(!s?.editing)return;const n=String(e||"").replace(/\r?\n/g,""),i=_e(s.draft||"",s.cursorIndex||0,n);this.setAdminGhcpKeyDraft(i.prompt,i.cursor)}deleteAdminGhcpKeyChar(){const e=this.getState().admin?.ghcpKey;if(!e?.editing)return;const s=st(e.draft||"",e.cursorIndex||0);this.setAdminGhcpKeyDraft(s.prompt,s.cursor)}moveAdminGhcpKeyCursor(e){const s=this.getState().admin?.ghcpKey;if(!s?.editing)return;const n=s.draft||"";this.setAdminGhcpKeyDraft(n,X(n,(s.cursorIndex||0)+e))}moveAdminGhcpKeyCursorToBoundary(e){const s=this.getState().admin?.ghcpKey;if(!s?.editing)return;const n=s.draft||"";this.setAdminGhcpKeyDraft(n,e==="start"?0:n.length)}cancelAdminEditGhcpKey(){this.dispatch({type:"admin/ghcpKey/cancelEdit"})}async saveAdminGhcpKey(){if(typeof this.transport.setCurrentUserGitHubCopilotKey!="function"){this.dispatch({type:"admin/ghcpKey/saveFailed",error:"Admin Console is not available on this transport."});return}const e=String(this.getState().admin.ghcpKey.draft||"").trim();if(e.length===0){this.dispatch({type:"admin/ghcpKey/saveFailed",error:"Enter a key, or use Clear to remove the override."});return}this.dispatch({type:"admin/ghcpKey/saving"});try{const s=await this.transport.setCurrentUserGitHubCopilotKey({key:e});this.dispatch({type:"admin/ghcpKey/saved",profile:s})}catch(s){this.dispatch({type:"admin/ghcpKey/saveFailed",error:s?.message||String(s)})}}async clearAdminGhcpKey(){if(typeof this.transport.setCurrentUserGitHubCopilotKey!="function"){this.dispatch({type:"admin/ghcpKey/saveFailed",error:"Admin Console is not available on this transport."});return}this.dispatch({type:"admin/ghcpKey/saving"});try{const e=await this.transport.setCurrentUserGitHubCopilotKey({key:null});this.dispatch({type:"admin/ghcpKey/saved",profile:e})}catch(e){this.dispatch({type:"admin/ghcpKey/saveFailed",error:e?.message||String(e)})}}async ensureExecutionHistory(e,{force:s=!1}={}){if(!e||typeof this.transport.getExecutionHistory!="function")return null;const n=this.getState().executionHistory?.bySessionId?.[e]||null,i=Date.now();if(!s&&n?.loading||!s&&n&&Number.isFinite(n.fetchedAt)&&i-n.fetchedAt<15e3)return n;this.dispatch({type:"executionHistory/loading",sessionId:e});try{const o=await this.transport.getExecutionHistory(e);this.dispatch({type:"executionHistory/loaded",sessionId:e,events:o||[],fetchedAt:Date.now()})}catch(o){console.error("[executionHistory] fetch error:",o?.message||o),this.dispatch({type:"executionHistory/error",sessionId:e,error:o?.message||String(o),fetchedAt:Date.now()})}return this.getState().executionHistory?.bySessionId?.[e]||null}async ensureFilesForScope(e=de(this.getState()),{force:s=!1}={}){const n=Wt(this.getState(),e);return n.length===0?e==="allSessions"?[]:null:e==="allSessions"||n.length>1?Promise.allSettled(n.map(i=>this.ensureFilesForSession(i,{force:s}))):this.ensureFilesForSession(n[0],{force:s})}async ensureSelectedFilePreview(){const e=Me(this.getState());return!e?.sessionId||!e?.filename?null:this.ensureFilePreview(e.sessionId,e.filename).catch(()=>null)}async ensureFilesForSession(e,{force:s=!1}={}){if(!e||typeof this.transport.listArtifacts!="function")return null;const n=this.getState().files.bySessionId[e];if(!s&&n?.loading)return n;if(!s&&n?.loaded)return n.selectedFilename&&await this.ensureFilePreview(e,n.selectedFilename).catch(()=>{}),n;this.dispatch({type:"files/sessionLoading",sessionId:e});try{const i=await this.transport.listArtifacts(e);this.dispatch({type:"files/sessionLoaded",sessionId:e,entries:i});const o=this.getState().files.bySessionId[e];return o?.selectedFilename&&await this.ensureFilePreview(e,o.selectedFilename).catch(()=>{}),o}catch(i){return this.dispatch({type:"files/sessionError",sessionId:e,error:i?.message||String(i)}),null}}async ensureFilePreview(e,s,{force:n=!1}={}){if(!e||!s||typeof this.transport.downloadArtifact!="function")return null;const i=this.getState().files.bySessionId[e],o=i?.previews?.[s];let r=Ma(i?.entries,s);if(!n&&o?.loading||!n&&o&&(o.content!==void 0||o.error))return o;if(!r&&typeof this.transport.getArtifactMetadata=="function")try{r=await this.transport.getArtifactMetadata(e,s)}catch{r=null}this.dispatch({type:"files/previewLoading",sessionId:e,filename:s});try{const a=r?.isBinary===!0?mi(s,"",r.contentType||"",r):mi(s,await this.transport.downloadArtifact(e,s),r?.contentType||"",r);return this.dispatch({type:"files/previewLoaded",sessionId:e,filename:s,...a}),a}catch(a){return this.dispatch({type:"files/previewError",sessionId:e,filename:s,error:a?.message||String(a)}),null}}buildArtifactPickerItems(e=[],s=[]){const n=(e||[]).map(i=>({id:`${i.sessionId}/${i.filename}`,kind:"artifact",sessionId:i.sessionId,filename:i.filename}));for(const i of s||[]){const o=String(i?.href||"").trim();o&&n.push({id:`url:${o}`,kind:"url",href:o,text:String(i?.text||o).trim()||o})}return(e||[]).length>1&&n.push({id:"__downloadAll__",kind:"downloadAll"}),n}buildArtifactPickerModal({artifactLinks:e,httpLinks:s,previousFocus:n,selectedId:i}={}){const o=this.buildArtifactPickerItems(e,s);if(o.length===0)return null;const r=o.findIndex(a=>a.id===i);return{type:"artifactPicker",title:"Linked Items",previousFocus:n,artifactLinks:e,httpLinks:s,items:o,selectedIndex:r>=0?r:0,exportDirectory:typeof this.transport.getArtifactExportDirectory=="function"?this.transport.getArtifactExportDirectory():null}}getArtifactPickerSelectionId(){const e=this.getState().ui.modal;return!e||e.type!=="artifactPicker"?null:e.items?.[e.selectedIndex||0]?.id||null}replaceArtifactPickerModal(e=null){const s=this.getState().ui.modal;if(!s||s.type!=="artifactPicker")return;const n=this.buildArtifactPickerModal({artifactLinks:s.artifactLinks||[],httpLinks:s.httpLinks||[],previousFocus:s.previousFocus,selectedId:e||this.getArtifactPickerSelectionId()});if(!n){this.dispatch({type:"ui/modal",modal:null}),this.dispatch({type:"ui/status",text:"No linked artifacts or URLs in the current chat view"});return}this.dispatch({type:"ui/modal",modal:n})}async saveArtifactDownload(e,s){if(typeof this.transport.saveArtifactDownload!="function")return this.dispatch({type:"ui/status",text:"Artifact download is not supported by this transport"}),null;try{const n=await this.transport.saveArtifactDownload(e,s);this.dispatch({type:"files/downloaded",sessionId:e,filename:s,localPath:n?.localPath||"",downloadedAt:Date.now()});const i=this.getState().sessions.activeSessionId;return(e===i||this.getState().ui.inspectorTab==="files")&&(await this.ensureFilesForSession(e,{force:!0}).catch(()=>null),e===i&&(this.dispatch({type:"files/select",sessionId:e,filename:s}),this.getState().ui.inspectorTab==="files"&&await this.ensureFilePreview(e,s,{force:!0}).catch(()=>null))),n}catch(n){return this.dispatch({type:"ui/status",text:`Download failed: ${n?.message||String(n)}`}),null}}async openSelectedFileInDefaultApp(){const e=this.getState(),s=Me(e);if(!s?.sessionId||!s?.filename){this.dispatch({type:"ui/status",text:e.sessions.activeSessionId||de(e)==="allSessions"?"No file selected":"No session selected"});return}const{sessionId:n,filename:i}=s,o=de(e);if(typeof this.transport.openPathInDefaultApp!="function"){this.dispatch({type:"ui/status",text:"Opening files in the default app is not supported by this transport"});return}let r=e.files.bySessionId[n]?.downloads?.[i]?.localPath||null;if(r||(this.dispatch({type:"ui/status",text:`Downloading ${i} to open it...`}),r=(await this.saveArtifactDownload(n,i))?.localPath||null),!r){this.dispatch({type:"ui/status",text:`Open failed: could not save ${i} locally`});return}try{await this.transport.openPathInDefaultApp(r),this.dispatch({type:"ui/status",text:o==="allSessions"?`Opened ${ie(n)} ${i} in the default app`:`Opened ${i} in the default app`})}catch(a){this.dispatch({type:"ui/status",text:`Open failed: ${a?.message||String(a)}`})}}async downloadSelectedArtifact(){const e=Me(this.getState());if(!e?.sessionId||!e?.filename)return this.dispatch({type:"ui/status",text:"No artifact selected"}),null;this.dispatch({type:"ui/status",text:`Downloading ${e.filename}...`});const s=await this.saveArtifactDownload(e.sessionId,e.filename);return s?.localPath?(this.dispatch({type:"ui/status",text:`Downloaded ${e.filename}`}),s):null}async deleteSelectedArtifact({confirmed:e=!1}={}){const s=this.getState(),n=Me(s);if(!n?.sessionId||!n?.filename)return this.dispatch({type:"ui/status",text:"No artifact selected"}),!1;const i=de(s),o=i==="allSessions"?`${ie(n.sessionId)} ${n.filename}`:n.filename;if(!e)return this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Delete Artifact",message:`Delete artifact "${o}"? This action cannot be undone.`,confirmLabel:"Delete",action:"deleteArtifact",sessionId:n.sessionId,filename:n.filename,previousFocus:s.ui.focusRegion}}),!1;if(typeof this.transport.deleteArtifact!="function")return this.dispatch({type:"ui/status",text:"Artifact deletion is not supported by this transport"}),!1;try{await this.transport.deleteArtifact(n.sessionId,n.filename),this.dispatch({type:"files/deleted",sessionId:n.sessionId,filename:n.filename}),await this.ensureFilesForSession(n.sessionId,{force:!0}).catch(()=>null);const r=Me(this.getState());return r?.sessionId&&r?.filename&&await this.ensureFilePreview(r.sessionId,r.filename).catch(()=>null),this.dispatch({type:"ui/status",text:i==="allSessions"?`Deleted ${ie(n.sessionId)} ${n.filename}`:`Deleted ${n.filename}`}),!0}catch(r){return this.dispatch({type:"ui/status",text:`Delete failed: ${r?.message||String(r)}`}),!1}}async openArtifactPicker(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s){this.dispatch({type:"ui/status",text:"No session selected"});return}const n=ml(e),i=gl(e);if(n.length===0&&i.length===0){this.dispatch({type:"ui/status",text:"No linked artifacts or URLs in the current chat view"});return}const o=this.getState().files.bySessionId[s]?.selectedFilename||null,r=o?`${s}/${o}`:null,a=this.buildArtifactPickerModal({artifactLinks:n,httpLinks:i,previousFocus:e.ui.focusRegion,selectedId:r});if(!a){this.dispatch({type:"ui/status",text:"No linked artifacts or URLs in the current chat view"});return}this.dispatch({type:"ui/modal",modal:a}),this.dispatch({type:"ui/status",text:"Select a linked item and press Enter to open or download it"})}async downloadArtifactModalSelection(){const e=this.getState().ui.modal;if(!e||e.type!=="artifactPicker")return;const s=e.items?.[e.selectedIndex||0];if(!s)return;if(s.kind==="url"){if(typeof this.transport.openUrlInDefaultBrowser!="function"){this.dispatch({type:"ui/status",text:"Opening URLs is not supported by this transport"});return}this.dispatch({type:"ui/status",text:`Opening ${s.href}...`}),await this.transport.openUrlInDefaultBrowser(s.href),this.replaceArtifactPickerModal(s.id),this.dispatch({type:"ui/status",text:`Opened ${s.href}`});return}if(s.kind==="downloadAll"){const i=(e.items||[]).filter(r=>r.kind!=="artifact"?!1:!this.getState().files.bySessionId[r.sessionId]?.downloads?.[r.filename]?.localPath);if(i.length===0){this.dispatch({type:"ui/status",text:"All artifacts already downloaded"});return}this.dispatch({type:"ui/status",text:`Downloading ${i.length} artifacts...`});let o=0;for(const r of i)(await this.saveArtifactDownload(r.sessionId,r.filename))?.localPath&&(o+=1);this.replaceArtifactPickerModal(s.id),this.dispatch({type:"ui/status",text:`Downloaded ${o}/${i.length} artifacts`});return}this.dispatch({type:"ui/status",text:`Downloading ${s.filename}...`}),(await this.saveArtifactDownload(s.sessionId,s.filename))?.localPath&&(this.replaceArtifactPickerModal(s.id),this.dispatch({type:"ui/status",text:`Downloaded ${s.filename}`}))}async moveFileSelection(e){const s=de(this.getState());await this.ensureFilesForScope(s);const n=mt(this.getState());if(n.length===0)return;const i=Me(this.getState())||n[0],o=Math.max(0,n.findIndex(l=>l.id===i?.id)),r=Math.max(0,Math.min(n.length-1,o+e)),a=n[r];!a?.sessionId||!a?.filename||(s==="allSessions"?this.dispatch({type:"files/selectGlobal",artifactId:a.id}):this.dispatch({type:"files/select",sessionId:a.sessionId,filename:a.filename}),await this.ensureFilePreview(a.sessionId,a.filename).catch(()=>{}),this.dispatch({type:"ui/status",text:s==="allSessions"?`Previewing ${ie(a.sessionId)} ${a.filename}`:`Previewing ${a.filename}`}))}async selectFileBrowserItem(e){if(!e?.sessionId||!e?.filename)return;const s=de(this.getState());s==="allSessions"?this.dispatch({type:"files/selectGlobal",artifactId:e.id}):this.dispatch({type:"files/select",sessionId:e.sessionId,filename:e.filename}),await this.ensureFilePreview(e.sessionId,e.filename).catch(()=>{}),this.dispatch({type:"ui/status",text:s==="allSessions"?`Previewing ${ie(e.sessionId)} ${e.filename}`:`Previewing ${e.filename}`})}toggleFilePreviewFullscreen(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s){this.dispatch({type:"ui/status",text:"No session selected"});return}const n=e.files.bySessionId[s],i=!!e.files.fullscreen;if(!i&&!n?.selectedFilename){this.dispatch({type:"ui/status",text:"Select a file before entering fullscreen"});return}const o=!i;this.dispatch({type:"files/fullscreen",fullscreen:o}),this.dispatch({type:"ui/status",text:o?`Fullscreen files browser: ${n?.selectedFilename||""}`:"Closed fullscreen files browser"})}toggleFocusedPaneFullscreen(){const e=this.getState(),s=e.ui.focusRegion,n=e.ui.fullscreenPane||null,i=s===w.PROMPT?n:s;if(!eu.has(i)||i===w.INSPECTOR&&e.ui.inspectorTab==="files")return;const o=n===i?null:i;this.dispatch({type:"ui/fullscreenPane",fullscreenPane:o}),this.dispatch({type:"ui/status",text:o?`Fullscreen ${i} pane`:`Closed fullscreen ${i} pane`}),!o&&s===w.PROMPT&&this.setFocus(i)}openFilesFilter(){const e=de(this.getState());this.dispatch({type:"ui/modal",modal:{type:"filesFilter",title:"Files Filter",previousFocus:this.getState().ui.focusRegion,selectedIndex:0,items:[{id:"scope",label:"Scope",description:"Choose whether the files browser shows the selected session tree or aggregates exported files across all sessions.",options:[{id:"selectedSession",label:"Selected session tree"},{id:"allSessions",label:"All sessions"}]}]}}),this.dispatch({type:"ui/status",text:`Editing files filter: Scope = ${e==="allSessions"?"All sessions":"Selected session tree"}`})}async loadSession(e){if(!e)return;if(this.getState().sessions.activeSessionId!==e&&(this.getState().ui.promptEdit&&this.exitPendingPromptEdit({restoreDraft:!0}),this.dispatch({type:"sessions/selected",sessionId:e})),this.getState().sessions.byId[e]?.isGroup){this.detachActiveSession();return}await this.ensureSessionHistory(e,{force:!0}),await this.syncSessionDetail(e).catch(()=>{}),this.attachActiveSession(e),this.ensureInspectorData().catch(()=>{})}reconcileOutboxAgainstEvent(e,s){if(!(!e||!s)){if(s.eventType==="user.message"){const n=s?.data?.content,i=Array.isArray(s?.data?.clientMessageIds)?s.data.clientMessageIds.filter(o=>typeof o=="string"):typeof s?.data?.clientMessageId=="string"?[s.data.clientMessageId]:[];if(i.length>0)for(const o of i)this.acknowledgeOutboxPrompt(e,n,o);else typeof n=="string"&&n.trim()&&this.acknowledgeOutboxPrompt(e,n);return}if(s.eventType==="pending_messages.cancelled"){const n=Array.isArray(s?.data?.clientMessageIds)?s.data.clientMessageIds.filter(i=>typeof i=="string"):typeof s?.data?.clientMessageId=="string"?[s.data.clientMessageId]:[];this.acknowledgeCancelledOutboxPrompt(e,n)}}}mergeSessionEvent(e,s){if(!e||!s)return!1;const i=this.getState().history.bySessionId.get(e)||{chat:[],activity:[],lastSeq:0};if(s.seq<=(i.lastSeq||0))return!1;this.dispatch({type:"history/set",sessionId:e,history:Vr(i,s)}),this.reconcileOutboxAgainstEvent(e,s);const o=iu(s),r=this.getState().sessions.byId[e]||{sessionId:e},a=Pi(r.contextUsage,s.eventType,s.data,{timestamp:s.createdAt});return(o||a)&&this.dispatch({type:"sessions/merged",session:{sessionId:e,...o||{},...a?{contextUsage:a}:{}}}),this.maybeFlushQueuedOutbox(e,this.getState().sessions.byId[e]||r),this.scheduleSessionDetailSync(e),!0}async syncSessionEvents(e){if(!e||typeof this.transport.getSessionEvents!="function")return;const s=this.getState().history.bySessionId.get(e);if(!s?.events){await this.ensureSessionHistory(e,{force:!0});return}const n=Number(s.lastSeq||0),i=await this.transport.getSessionEvents(e,n,200);if(!(!Array.isArray(i)||i.length===0))for(const o of i)this.mergeSessionEvent(e,o)}attachActiveSession(e){this.activeSessionSubscriptionId===e&&this.activeSessionUnsub||(this.detachActiveSession(),this.activeSessionSubscriptionId=e,this.activeSessionUnsub=this.transport.subscribeSession(e,s=>{this.mergeSessionEvent(e,s)}),this.syncSessionEvents(e).catch(()=>{}))}scheduleSessionDetailSync(e,s=250){typeof this.transport.getSession!="function"||!e||(this.activeSessionDetailTimer&&clearTimeout(this.activeSessionDetailTimer),this.activeSessionDetailSessionId=e,this.activeSessionDetailTimer=setTimeout(()=>{const n=this.activeSessionDetailSessionId;this.activeSessionDetailTimer=null,this.activeSessionDetailSessionId=null,this.syncSessionDetail(n).catch(()=>{})},s))}scheduleSessionsRefresh(e=0){this.sessionRefreshTimer&&clearTimeout(this.sessionRefreshTimer),this.sessionRefreshTimer=setTimeout(()=>{this.sessionRefreshTimer=null,this.refreshSessions().catch(()=>{})},Math.max(0,e))}async syncSessionDetail(e){if(typeof this.transport.getSession!="function"||!e)return;const s=await this.transport.getSession(e);if(!s)return;const n=this.getState().sessions.byId[e]||null,i=cu(n,s);(i||n?.rowVisualStatusCandidate)&&this.dispatch({type:"sessions/merged",session:i||{sessionId:e}}),this.maybeFlushQueuedOutbox(e,s)}async createSession(e={}){try{const s=await this.transport.createSession(this.applyActiveGroupDefault(e));return await this.refreshSessions(),await this.loadSession(s.sessionId),this.setFocus(w.PROMPT),this.dispatch({type:"ui/status",text:`Created session ${s.sessionId.slice(0,8)}`}),s}catch(s){return this.dispatch({type:"ui/status",text:s?.message||String(s)||"Failed to create session"}),null}}async createSessionForAgent(e,s={}){if(typeof this.transport.createSessionForAgent!="function")throw new Error("Named-agent session creation is not supported by this transport");try{const n=await this.transport.createSessionForAgent(e,this.applyActiveGroupDefault(s));return await this.refreshSessions(),await this.loadSession(n.sessionId),this.setFocus(w.PROMPT),this.dispatch({type:"ui/status",text:`Created ${ci(e,s.title)} session ${n.sessionId.slice(0,8)}`}),n}catch(n){return this.dispatch({type:"ui/status",text:n?.message||String(n)||"Failed to create session"}),null}}getMovableGroupSessionSelection(){const e=this.getState();return(Array.isArray(e.sessions.selectedIds)&&e.sessions.selectedIds.length>0?e.sessions.selectedIds:e.sessions.activeSessionId?[e.sessions.activeSessionId]:[]).map(n=>e.sessions.byId[n]).filter(n=>n&&!n.isSystem&&!n.isGroup&&!n.parentSessionId)}async openMoveToGroupModal(){const e=this.getState(),s=this.getMovableGroupSessionSelection();if(s.length===0)return this.dispatch({type:"ui/status",text:"Select a top-level non-system session to move"}),null;if(typeof this.transport.listSessionGroups!="function")return this.dispatch({type:"ui/status",text:"Session groups are not supported by this transport"}),null;const n=await this.transport.listSessionGroups().catch(()=>[]),i=s.map(h=>h.sessionId),o=s.length===1&&s[0].groupId||null,r=new Set(s.map(h=>gt(h.owner)||"")),a=r.size===1?[...r][0]:null,l=r.size===1?s[0]?.owner??null:null,p=r.size===1?(Array.isArray(n)?n:[]).filter(h=>(gt(h.owner)||"")===a):[],u=r.size===1,d=[{id:"__no_group__",kind:"noGroup",label:"[No Group]",description:"Remove the selected session(s) from any group.",groupId:null,memberCount:0},...u?[{id:"__new_group__",kind:"newGroup",label:"[New Group]",description:"Create a new group for this owner, then move the selected session(s) into it.",groupId:null,memberCount:0,owner:l}]:[],...p.map(h=>({id:h.groupId,kind:"group",label:h.title||h.groupId,description:h.description||"Move selected session(s) into this group.",groupId:h.groupId,owner:h.owner??null,memberCount:h.memberCount??0}))],f=o?Math.max(0,d.findIndex(h=>h.groupId===o)):Math.min(1,d.length-1);return this.dispatch({type:"ui/modal",modal:{type:"sessionGroupPicker",title:s.length===1?"Move Session to Group":`Move ${s.length} Sessions to Group`,previousFocus:e.ui.focusRegion,sessionIds:i,sessionLabels:s.map(h=>h.title||h.sessionId.slice(0,8)),selectedIndex:f>=0?f:0,items:d}}),this.dispatch({type:"ui/status",text:u?"Choose a group, [New Group], or [No Group]":"Selected sessions have different owners; only [No Group] is available"}),d}async createSessionGroupFromSelection(){return this.openMoveToGroupModal()}async moveSessionsToGroup(e,s,{statusTitle:n=null}={}){const i=Array.from(new Set((Array.isArray(s)?s:[]).map(r=>String(r||"").trim()).filter(Boolean)));if(i.length===0)return this.dispatch({type:"ui/status",text:"No sessions selected to move"}),null;if(typeof this.transport.moveSessionsToGroup=="function")await this.transport.moveSessionsToGroup(e??null,i);else if(e&&typeof this.transport.assignSessionsToGroup=="function")await this.transport.assignSessionsToGroup(e,i);else return this.dispatch({type:"ui/status",text:"Moving sessions between groups is not supported by this transport"}),null;this.dispatch({type:"sessions/selectClear"}),await this.refreshSessions(),e&&await this.loadSession(`group:${e}`).catch(()=>{});const o=e?`group ${n||e}`:"No Group";return this.dispatch({type:"ui/status",text:`Moved ${i.length} session${i.length===1?"":"s"} to ${o}`}),!0}async confirmSessionGroupPickerModal(){const e=this.getState().ui.modal;if(!e||e.type!=="sessionGroupPicker")return;const s=e.items?.[e.selectedIndex||0];if(!s)return;if(s.kind==="newGroup"){const i=(e.sessionLabels||[]).length===1?`${e.sessionLabels[0]} Group`:`${(e.sessionIds||[]).length} Session Group`;this.dispatch({type:"ui/modal",modal:{type:"sessionGroupName",title:"New Group",previousFocus:e.previousFocus,sessionIds:e.sessionIds||[],owner:s.owner??null,value:i,cursorIndex:i.length,maxLength:80}}),this.dispatch({type:"ui/status",text:"Name the new group and press Enter"});return}const n=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n);try{await this.moveSessionsToGroup(s.kind==="noGroup"?null:s.groupId,e.sessionIds||[],{statusTitle:s.label})}catch(i){this.dispatch({type:"ui/status",text:`Move failed: ${i?.message||String(i)}`})}}updateSessionGroupNameModal(e){const s=this.getState().ui.modal;if(!s||s.type!=="sessionGroupName")return null;const n=typeof e=="function"?e(s):e;return n?(this.dispatch({type:"ui/modal",modal:{...s,...n}}),this.getState().ui.modal):null}setSessionGroupNameValue(e,s=String(e||"").length){const n=this.getState().ui.modal;if(!n||n.type!=="sessionGroupName")return;const i=At(e,n.maxLength||80),o=X(i,s);this.updateSessionGroupNameModal({value:i,cursorIndex:o})}insertSessionGroupNameText(e){const s=this.getState().ui.modal;if(!s||s.type!=="sessionGroupName")return;const n=_e(s.value||"",s.cursorIndex||0,At(e,s.maxLength||80));this.setSessionGroupNameValue(n.prompt,n.cursor)}deleteSessionGroupNameChar(){const e=this.getState().ui.modal;if(!e||e.type!=="sessionGroupName")return;const s=st(e.value||"",e.cursorIndex||0);this.setSessionGroupNameValue(s.prompt,s.cursor)}moveSessionGroupNameCursor(e){const s=this.getState().ui.modal;!s||s.type!=="sessionGroupName"||this.setSessionGroupNameValue(s.value||"",X(s.value||"",(s.cursorIndex||0)+e))}moveSessionGroupNameCursorToBoundary(e){const s=this.getState().ui.modal;!s||s.type!=="sessionGroupName"||this.setSessionGroupNameValue(s.value||"",e==="start"?0:String(s.value||"").length)}async confirmSessionGroupNameModal(){const e=this.getState().ui.modal;if(!e||e.type!=="sessionGroupName")return;const s=String(e.value||"").trim();if(!s){this.dispatch({type:"ui/status",text:"Group name cannot be empty"});return}if(typeof this.transport.createSessionGroup!="function"){this.dispatch({type:"ui/status",text:"Session grouping is not supported by this transport"});return}const n=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n);try{const i=await this.transport.createSessionGroup({title:s,description:`${(e.sessionIds||[]).length} grouped session${(e.sessionIds||[]).length===1?"":"s"}`,sessionIds:e.sessionIds||[],owner:e.owner??null});await this.moveSessionsToGroup(i.groupId,e.sessionIds||[],{statusTitle:i.title||s})}catch(i){this.dispatch({type:"ui/status",text:`Move failed: ${i?.message||String(i)}`})}}applyActiveGroupDefault(e={}){if(e&&Object.prototype.hasOwnProperty.call(e,"groupId"))return e;const s=this.getState(),n=s.sessions?.activeSessionId?s.sessions.byId[s.sessions.activeSessionId]:null,i=n?.isGroup?n.groupId||gs(n.sessionId):n?.groupId;return i?{...e,groupId:i}:e}getActiveSession(e=this.getState()){const s=e.sessions?.activeSessionId;return s&&e.sessions.byId[s]||null}toggleChatViewMode(){if(this.getActiveSession()?.isGroup){this.dispatch({type:"ui/status",text:"Session groups show group details"});return}const s=this.getState().ui?.chatViewMode==="summary"?"transcript":"summary";this.dispatch({type:"ui/chatViewMode",mode:s}),this.dispatch({type:"ui/status",text:s==="summary"?"Showing session summary":"Showing chat transcript"})}setChatViewMode(e){e!=="summary"&&e!=="transcript"||this.getActiveSession()?.isGroup||this.dispatch({type:"ui/chatViewMode",mode:e})}async openSessionAgentPicker(e={}){const s=typeof this.transport.listCreatableAgents=="function"?await this.transport.listCreatableAgents():[],i=(typeof this.transport.getSessionCreationPolicy=="function"?this.transport.getSessionCreationPolicy():null)?.creation?.allowGeneric??!0;if(!Array.isArray(s)||s.length===0){if(!i){this.dispatch({type:"ui/status",text:"No user-creatable agents are available for this app"});return}await this.createSession(e);return}const o=[];i&&o.push({id:"__generic__",kind:"generic",title:"Generic Session",description:"Open-ended session with no specialized agent boundary.",tools:[],splash:null,initialPrompt:null});for(const r of s){const a=String(r?.name||"").trim();a&&o.push({id:a,kind:"agent",agentName:a,title:ci(a,r?.title),description:String(r?.description||"").trim(),tools:Array.isArray(r?.tools)?r.tools.filter(Boolean):[],splash:typeof r?.splash=="string"&&r.splash.trim()?r.splash:null,initialPrompt:typeof r?.initialPrompt=="string"&&r.initialPrompt.trim()?r.initialPrompt:null})}this.dispatch({type:"ui/modal",modal:{type:"sessionAgentPicker",title:"Select agent for new session",items:o,selectedIndex:0,previousFocus:this.getState().ui.focusRegion,sessionOptions:e}}),this.dispatch({type:"ui/status",text:"Select an agent and press Enter"})}async openNewSessionFlow(e={}){if((typeof this.transport.getSessionCreationPolicy=="function"?this.transport.getSessionCreationPolicy():null)?.creation?.allowGeneric??!0){await this.createSession(e);return}if(typeof this.transport.listModels=="function"){await this.openModelPicker(e);return}await this.openSessionAgentPicker(e)}async openReasoningEffortPicker(e,s={}){const n=Ns(e?.supportedReasoningEfforts),i=s?.reasoningEffort||ri(e);if(!n.length||!i){if(s?.mode==="switchModel"){await this.switchSessionModel({...s,model:e?.id});return}await this.openSessionAgentPicker(s);return}const o=n.map(a=>({id:a,effort:a,label:a,isDefault:i===a})),r=Math.max(0,o.findIndex(a=>a.id===i));this.dispatch({type:"ui/modal",modal:{type:"reasoningEffortPicker",title:s?.mode==="switchModel"?`Switch reasoning for ${e?.modelName||e?.qualifiedName||"model"}`:`Reasoning effort for ${e?.modelName||e?.qualifiedName||"model"}`,items:o,selectedIndex:r,previousFocus:this.getState().ui.focusRegion,modelItem:e,sessionOptions:s}}),this.dispatch({type:"ui/status",text:"Select a reasoning effort and press Enter"})}async openModelPicker(e={}){if(typeof this.transport.listModels!="function"){await this.openSessionAgentPicker(e);return}const s=await this.transport.listModels();if(!Array.isArray(s)||s.length===0){this.dispatch({type:"ui/status",text:"No models available"});return}const n=typeof this.transport.getDefaultModel=="function"?this.transport.getDefaultModel():void 0,i=typeof this.transport.getModelsByProvider=="function"?this.transport.getModelsByProvider():nu(s),o=[],r=i.map(p=>({providerId:p.providerId,providerType:p.type||p.providerType,models:(p.models||[]).map(u=>{const d={id:u.qualifiedName,qualifiedName:u.qualifiedName,modelName:u.modelName||u.qualifiedName,providerId:u.providerId||p.providerId,providerType:u.providerType||p.type||p.providerType,description:u.description||"",cost:u.cost||null,supportedReasoningEfforts:Ns(u.supportedReasoningEfforts),defaultReasoningEffort:u.defaultReasoningEffort||null,isDefault:n===u.qualifiedName};return o.push(d),d})})).filter(p=>p.models.length>0),a=e?.model||n,l=Math.max(0,o.findIndex(p=>p.qualifiedName===a));this.dispatch({type:"ui/modal",modal:{type:"modelPicker",title:e?.mode==="switchModel"?"Switch model for session":"Select model for new session",items:o,groups:r,selectedIndex:l,previousFocus:this.getState().ui.focusRegion,sessionOptions:e}}),this.dispatch({type:"ui/status",text:"Select a model and press Enter"})}async openSwitchModelPicker(){const e=this.getState(),s=e.sessions.activeSessionId,n=s&&e.sessions.byId[s]||null;if(!n||n.isGroup){this.dispatch({type:"ui/status",text:"Select a session before switching model"});return}if(typeof this.transport.setSessionModel!="function"){this.dispatch({type:"ui/status",text:"Model switching is not supported by this transport"});return}await this.openModelPicker({mode:"switchModel",sessionId:s,model:n.model||void 0,reasoningEffort:n.reasoningEffort||void 0})}async switchSessionModel(e={}){const s=e.sessionId||this.getState().sessions.activeSessionId,n=String(e.model||"").trim();if(!s||!n){this.dispatch({type:"ui/status",text:"Select a model before switching"});return}if(typeof this.transport.setSessionModel!="function"){this.dispatch({type:"ui/status",text:"Model switching is not supported by this transport"});return}await this.transport.setSessionModel(s,{model:n,..."reasoningEffort"in e?{reasoningEffort:e.reasoningEffort??null}:{},source:"ui"}),this.dispatch({type:"ui/status",text:`Next turn will use ${e.reasoningEffort?`${n}:${e.reasoningEffort}`:n}`}),await this.refreshSessions()}openThemePicker(){const e=Aa().map(i=>({id:i.id,label:i.label,description:i.description,page:i.page,terminal:i.terminal,tui:i.tui}));if(e.length===0){this.dispatch({type:"ui/status",text:"No themes available"});return}const s=this.getState().ui.themeId,n=Math.max(0,e.findIndex(i=>i.id===s));this.dispatch({type:"ui/modal",modal:{type:"themePicker",title:"Theme Picker",items:e,selectedIndex:n,previousFocus:this.getState().ui.focusRegion,currentThemeId:s}}),this.dispatch({type:"ui/status",text:"Select a theme and press Enter"})}getPromptDraftSessionId(){return this.getPromptAttachments()[0]?.sessionId||null||this.getState().sessions.activeSessionId||null}openArtifactUploadModal(){if(typeof this.transport.uploadArtifactFromPath!="function"){this.dispatch({type:"ui/status",text:"Artifact upload is not supported by this transport"});return}const e=this.getState(),s=this.getPromptDraftSessionId();this.dispatch({type:"ui/modal",modal:{type:"artifactUpload",title:s?`Upload Artifact (${ie(s)})`:"Upload Artifact",sessionId:s,previousFocus:e.ui.focusRegion,value:"",cursorIndex:0}}),this.dispatch({type:"ui/status",text:s?"Paste a local file path and press Enter to upload it into this session's artifacts":"Paste a local file path and press Enter to upload it; a new session will be created if needed"})}updateArtifactUploadModal(e){const s=this.getState().ui.modal;if(!s||s.type!=="artifactUpload")return null;const n=typeof e=="function"?e(s):e;return n?(this.dispatch({type:"ui/modal",modal:{...s,...n}}),this.getState().ui.modal):null}setArtifactUploadValue(e,s=String(e||"").length){const n=this.getState().ui.modal;if(!n||n.type!=="artifactUpload")return;const i=String(e||"").replace(/\r?\n/g,""),o=X(i,s);this.updateArtifactUploadModal({value:i,cursorIndex:o})}insertArtifactUploadText(e){const s=this.getState().ui.modal;if(!s||s.type!=="artifactUpload")return;const n=_e(s.value||"",s.cursorIndex||0,String(e||"").replace(/\r?\n/g,""));this.setArtifactUploadValue(n.prompt,n.cursor)}deleteArtifactUploadChar(){const e=this.getState().ui.modal;if(!e||e.type!=="artifactUpload")return;const s=st(e.value||"",e.cursorIndex||0);this.setArtifactUploadValue(s.prompt,s.cursor)}moveArtifactUploadCursor(e){const s=this.getState().ui.modal;!s||s.type!=="artifactUpload"||this.setArtifactUploadValue(s.value||"",X(s.value||"",(s.cursorIndex||0)+e))}moveArtifactUploadCursorToBoundary(e){const s=this.getState().ui.modal;!s||s.type!=="artifactUpload"||this.setArtifactUploadValue(s.value||"",e==="start"?0:String(s.value||"").length)}async ensurePromptAttachmentSessionId(){const e=this.getPromptAttachments()[0]?.sessionId||null;if(e)return this.getState().sessions.activeSessionId!==e&&await this.loadSession(e),e;const s=this.getState().sessions.activeSessionId;if(s)return s;const n=await this.createSession({});if(!n?.sessionId)throw new Error("Create a session before attaching files");return n.sessionId}async finalizeArtifactUpload(e,{sessionId:s=null,suppressStatus:n=!1}={}){const i=s||e?.sessionId||await this.ensurePromptAttachmentSessionId();if(!i||!e?.filename)throw new Error("Upload did not return a session id and filename");return this.getState().sessions.activeSessionId!==i&&await this.loadSession(i),await this.ensureFilesForSession(i,{force:!0}).catch(()=>null),this.dispatch({type:"files/select",sessionId:i,filename:e.filename}),await this.ensureFilePreview(i,e.filename,{force:!0}).catch(()=>null),n||this.dispatch({type:"ui/status",text:`Uploaded ${e.filename}`}),{sessionId:i,filename:e.filename}}async applyUploadedPromptAttachment(e,{sessionId:s=null,suppressStatus:n=!1}={}){const i=s||e?.sessionId||await this.ensurePromptAttachmentSessionId();if(!i||!e?.filename)throw new Error("Upload did not return a session id and filename");const o=ui(e.filename),r=this.getState().ui.prompt,a=this.getState().ui.promptCursor,l=this.getPromptAttachments(),p=l.findIndex(d=>d?.sessionId===i&&d?.filename===e.filename);if(this.getState().sessions.activeSessionId!==i&&await this.loadSession(i),p===-1||!r.includes(l[p]?.token||o)){const d=_e(r,a,`${o} `);this.setPrompt(d.prompt,d.cursor)}const u=p>=0?l.map((d,f)=>f===p?{...d,sessionId:i,filename:e.filename,resolvedPath:e.resolvedPath||e.localPath||e.filename,sizeBytes:e.sizeBytes,token:o}:d):[...l,{id:`${i}/${e.filename}`,sessionId:i,filename:e.filename,resolvedPath:e.resolvedPath||e.localPath||e.filename,sizeBytes:e.sizeBytes,token:o}];return this.setPromptAttachments(u),await this.ensureFilesForSession(i,{force:!0}).catch(()=>null),this.dispatch({type:"files/select",sessionId:i,filename:e.filename}),this.getState().ui.inspectorTab==="files"&&await this.ensureFilePreview(i,e.filename,{force:!0}).catch(()=>null),this.setFocus(w.PROMPT),n||this.dispatch({type:"ui/status",text:p>=0?`Re-attached ${e.filename}`:`Attached ${e.filename}`}),{sessionId:i,existingAttachmentIndex:p,token:o}}async uploadArtifactFiles(e=[],{sessionId:s=null}={}){const n=Array.isArray(e)?e.filter(l=>l&&typeof l.name=="string"):[];if(n.length===0)return this.dispatch({type:"ui/status",text:"No files selected"}),[];if(typeof this.transport.uploadArtifactFromFile!="function")return this.dispatch({type:"ui/status",text:"Browser file uploads are not supported by this transport"}),[];this.dispatch({type:"ui/status",text:n.length===1?`Uploading ${n[0].name}...`:`Uploading ${n.length} artifact files...`});const i=s||await this.ensurePromptAttachmentSessionId(),o=[];let r=0,a=null;for(const l of n)try{const p=await this.transport.uploadArtifactFromFile(i,l);o.push(p),await this.finalizeArtifactUpload(p,{sessionId:i,suppressStatus:!0})}catch(p){r+=1,a=p}return o.length>0?this.dispatch({type:"ui/status",text:r>0?`Uploaded ${o.length}/${n.length} file(s); last error: ${a?.message||String(a)}`:o.length===1?`Uploaded ${o[0].filename}`:`Uploaded ${o.length} files`}):a&&this.dispatch({type:"ui/status",text:`Upload failed: ${a?.message||String(a)}`}),o}async uploadPromptAttachmentFiles(e=[]){return this.uploadArtifactFiles(e)}async confirmArtifactUploadModal(){const e=this.getState().ui.modal;if(!e||e.type!=="artifactUpload")return;const s=String(e.value||"").trim();if(!s){this.dispatch({type:"ui/status",text:"File path cannot be empty"});return}if(typeof this.transport.uploadArtifactFromPath!="function"){this.dispatch({type:"ui/status",text:"Artifact upload is not supported by this transport"});return}this.dispatch({type:"ui/status",text:"Uploading artifact..."});try{const n=e.sessionId||await this.ensurePromptAttachmentSessionId(),i=await this.transport.uploadArtifactFromPath(n,s),o=await this.finalizeArtifactUpload(i,{sessionId:n,suppressStatus:!0});this.dispatch({type:"ui/modal",modal:null}),this.dispatch({type:"ui/status",text:`Uploaded ${o.filename}`})}catch(n){this.dispatch({type:"ui/status",text:`Upload failed: ${n?.message||String(n)}`})}}openRenameSessionModal(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s){this.dispatch({type:"ui/status",text:"No session selected"});return}const n=e.sessions.byId[s];if(!n){this.dispatch({type:"ui/status",text:"No session selected"});return}if(n.isSystem){this.dispatch({type:"ui/status",text:"System session titles are fixed"});return}const i=hu(n),o=un(n),r=pu(n);this.dispatch({type:"ui/modal",modal:{type:"renameSession",title:`Rename (${ie(s)})`,sessionId:s,previousFocus:e.ui.focusRegion,value:i,cursorIndex:i.length,agentTitlePrefix:o,currentTitle:String(n.title||"").trim(),maxLength:r}}),this.dispatch({type:"ui/status",text:o?`Rename title for ${o}; the agent-name prefix stays fixed`:"Type a new session title and press Enter to save"})}async openTerminatePickerModal(){const e=this.getState(),s=Array.isArray(e.sessions.selectedIds)?e.sessions.selectedIds:[];if(e.sessions.selectMode&&s.length>=1){const o=this.getBulkSelectedSessionActions(e).eligible;if(o.length===0){this.dispatch({type:"ui/status",text:"No selected sessions can be terminated"});return}this.dispatch({type:"ui/modal",modal:{type:"terminatePicker",title:"Terminate Selected Sessions",previousFocus:e.ui.focusRegion,bulkCount:o.length,skippedCount:s.length-o.length,selectedIds:o.map(r=>r.sessionId)}}),this.dispatch({type:"ui/status",text:"Choose what to do with the selected sessions"});return}const n=e.sessions.activeSessionId;if(!n){this.dispatch({type:"ui/status",text:"No session selected"});return}const i=e.sessions.byId[n];if(!i){this.dispatch({type:"ui/status",text:"No session selected"});return}if(i.isSystem){const o=String(i.title||i.agentId||n.slice(0,8)).trim();this.dispatch({type:"ui/modal",modal:{type:"terminatePicker",title:"Restart System Session",sessionId:n,previousFocus:e.ui.focusRegion,sessionTitle:o,state:String(i.state||"").trim(),systemRestart:!0}}),this.dispatch({type:"ui/status",text:"Choose how to restart the system session"});return}if(i.isGroup){this.dispatch({type:"ui/status",text:"Groups are containers; manage sessions individually."});return}this.dispatch({type:"ui/modal",modal:{type:"terminatePicker",title:`Terminate (${ie(n)})`,sessionId:n,previousFocus:e.ui.focusRegion,sessionTitle:String(i.title||"").trim(),state:String(i.state||"").trim()}})}async pickTerminateAction(e){const s=this.getState().ui.modal;if(!s||s.type!=="terminatePicker")return;const n=s.previousFocus;this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n),e==="complete"?await this.completeActiveSession():e==="cancel"?await this.cancelActiveSession():e==="delete"&&await this.deleteActiveSession()}getBulkSelectedSessionActions(e=this.getState()){const s=Array.isArray(e.sessions.selectedIds)?e.sessions.selectedIds:[],i=[...new Set(s.map(r=>String(r||"").trim()).filter(Boolean))].map(r=>e.sessions.byId[r]).filter(Boolean),o=i.filter(r=>!r.isSystem&&!r.isGroup);return{selected:i,eligible:o,skippedCount:i.length-o.length}}updateRenameSessionModal(e){const s=this.getState().ui.modal;if(!s||s.type!=="renameSession")return null;const n=typeof e=="function"?e(s):e;return n?(this.dispatch({type:"ui/modal",modal:{...s,...n}}),this.getState().ui.modal):null}setRenameSessionValue(e,s=String(e||"").length){const n=this.getState().ui.modal;if(!n||n.type!=="renameSession")return;const i=At(e,n.maxLength),o=X(i,s);this.updateRenameSessionModal({value:i,cursorIndex:o})}insertRenameSessionText(e){const s=this.getState().ui.modal;if(!s||s.type!=="renameSession")return;const n=_e(s.value||"",s.cursorIndex||0,At(e,s.maxLength));this.setRenameSessionValue(n.prompt,n.cursor)}deleteRenameSessionChar(){const e=this.getState().ui.modal;if(!e||e.type!=="renameSession")return;const s=st(e.value||"",e.cursorIndex||0);this.setRenameSessionValue(s.prompt,s.cursor)}moveRenameSessionCursor(e){const s=this.getState().ui.modal;!s||s.type!=="renameSession"||this.setRenameSessionValue(s.value||"",X(s.value||"",(s.cursorIndex||0)+e))}moveRenameSessionCursorToBoundary(e){const s=this.getState().ui.modal;!s||s.type!=="renameSession"||this.setRenameSessionValue(s.value||"",e==="start"?0:String(s.value||"").length)}async confirmRenameSessionModal(){const e=this.getState().ui.modal;if(!e||e.type!=="renameSession")return;const s=e.sessionId;if(!s)return;const n=String(e.value||"").trim();if(!n){this.dispatch({type:"ui/status",text:"Title cannot be empty"});return}const i=this.getState().sessions.byId[s],o=i?.isGroup?i.groupId||gs(s):null;if(o){if(typeof this.transport.updateSessionGroup!="function"){this.dispatch({type:"ui/status",text:"Group renaming is not supported by this transport"});return}const a=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),a&&this.setFocus(a),this.dispatch({type:"ui/status",text:`Renaming group ${o.slice(0,8)}...`});try{await this.transport.updateSessionGroup(o,{title:n}),await this.refreshSessions(),this.dispatch({type:"ui/status",text:`Renamed group ${n}`})}catch(l){this.dispatch({type:"ui/status",text:`Rename failed: ${l?.message||String(l)}`})}return}if(typeof this.transport.renameSession!="function"){this.dispatch({type:"ui/status",text:"Session renaming is not supported by this transport"});return}const r=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),r&&this.setFocus(r),this.dispatch({type:"ui/status",text:`Renaming ${ie(s)}...`});try{await this.transport.renameSession(s,n),await this.refreshSessions(),this.scheduleSessionDetailSync(s,100),this.dispatch({type:"ui/status",text:`Renamed ${ie(s)}`})}catch(a){this.dispatch({type:"ui/status",text:`Rename failed: ${a?.message||String(a)}`})}}closeModal(){const e=this.getState().ui.modal;e&&(this.dispatch({type:"ui/modal",modal:null}),e.type==="themePicker"&&e.currentThemeId&&this.dispatch({type:"ui/theme",themeId:e.currentThemeId}),e.previousFocus&&this.setFocus(e.previousFocus),this.dispatch({type:"ui/status",text:"Connected"}))}moveModalSelection(e){const s=this.getState().ui.modal;if(!s||!Array.isArray(s.items)||s.items.length===0)return;if(s.type==="logFilter"||s.type==="filesFilter"||s.type==="historyFormat"){const o=Math.max(0,Math.min(Number(s.selectedIndex)||0,s.items.length-1)),r=s.items[o];if(!r||!Array.isArray(r.options)||r.options.length===0)return;const a=r.options.map(d=>d.id).filter(Boolean);if(a.length===0)return;const l=s.type==="filesFilter"?this.getState().files.filter?.[r.id]||a[0]:s.type==="historyFormat"?this.getState().executionHistory?.format||a[0]:this.getState().logs.filter?.[r.id]||a[0],p=Ze(a,l,e),u=r.options.find(d=>d.id===p)||r.options[0];this.dispatch({type:s.type==="filesFilter"?"files/filter":s.type==="historyFormat"?"executionHistory/format":"logs/filter",filter:s.type==="historyFormat"?void 0:{[r.id]:p},...s.type==="historyFormat"?{format:p}:{}}),s.type==="filesFilter"&&(this.ensureFilesForScope(p).catch(()=>{}),this.ensureSelectedFilePreview().catch(()=>{})),this.dispatch({type:"ui/status",text:`${s.type==="filesFilter"?"Files":s.type==="historyFormat"?"History":"Log"} filter updated: ${r.label} = ${u?.label||p}`});return}const n=Math.max(0,Number(s.selectedIndex)||0),i=Math.max(0,Math.min(n+e,s.items.length-1));this.dispatch({type:"ui/modalSelection",index:i})}moveModalPane(e){const s=this.getState().ui.modal;if(!s||s.type!=="logFilter"&&s.type!=="filesFilter"&&s.type!=="historyFormat"||!Array.isArray(s.items)||s.items.length===0)return;const i=(Math.max(0,Number(s.selectedIndex)||0)+e+s.items.length)%s.items.length,o=s.items[i],r=s.type==="filesFilter"?this.getState().files.filter?.[o.id]||o.options?.[0]?.id:s.type==="historyFormat"?this.getState().executionHistory?.format||o.options?.[0]?.id:this.getState().logs.filter?.[o.id]||o.options?.[0]?.id,a=o.options?.find(l=>l.id===r)||o.options?.[0];this.dispatch({type:"ui/modalSelection",index:i}),this.dispatch({type:"ui/status",text:`Editing ${o.label}: ${a?.label||r||""}`})}async confirmModal(){const e=this.getState().ui.modal;if(e){if(e.type==="confirm"){const s=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),s&&this.setFocus(s),e.action==="cancelSession"?await this.cancelActiveSession({confirmed:!0}):e.action==="completeSession"?await this.completeActiveSession("Completed by user",{confirmed:!0}):e.action==="deleteSession"?await this.deleteActiveSession({confirmed:!0}):e.action==="deleteArtifact"&&await this.deleteSelectedArtifact({confirmed:!0});return}if(e.type==="artifactUpload"){await this.confirmArtifactUploadModal();return}if(e.type==="renameSession"){await this.confirmRenameSessionModal();return}if(e.type==="sessionGroupPicker"){await this.confirmSessionGroupPickerModal();return}if(e.type==="sessionGroupName"){await this.confirmSessionGroupNameModal();return}if(e.type==="sessionOwnerFilter"){this.toggleSessionOwnerFilter();return}if(e.type==="filesFilter"){const s=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),s&&this.setFocus(s);return}if(e.type==="themePicker"){const s=e.items?.[e.selectedIndex||0],n=Ae(s?.id);if(!n){this.dispatch({type:"ui/status",text:"Unable to apply that theme"});return}const i=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),i&&this.setFocus(i),this.dispatch({type:"ui/status",text:`Applied theme: ${n.label}`});return}if(e.type==="modelPicker"){const s=e.items?.[e.selectedIndex||0],n=e.previousFocus;if(this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n),!s){if(e.sessionOptions?.mode==="switchModel"){this.dispatch({type:"ui/status",text:"No model selected"});return}await this.openSessionAgentPicker({});return}const i=ri(s);if(e.sessionOptions?.mode==="switchModel"){await this.openReasoningEffortPicker(s,{...e.sessionOptions||{},model:s.id,reasoningEffort:i??null});return}await this.openReasoningEffortPicker(s,{...e.sessionOptions||{},model:s.id,...i?{reasoningEffort:i}:{}});return}if(e.type==="reasoningEffortPicker"){const s=e.items?.[e.selectedIndex||0],n=e.previousFocus,i=e.sessionOptions||{};if(this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n),i?.mode==="switchModel"){await this.switchSessionModel({...i,...s?.id?{reasoningEffort:s.id}:{}});return}await this.openSessionAgentPicker({...i,...s?.id?{reasoningEffort:s.id}:{}});return}if(e.type==="sessionAgentPicker"){const s=e.items?.[e.selectedIndex||0],n=e.previousFocus,i=e.sessionOptions||{};if(this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n),!s||s.kind==="generic"){await this.createSession(i);return}await this.createSessionForAgent(s.agentName,{...i,...s.title?{title:s.title}:{},...s.splash?{splash:s.splash}:{},...s.initialPrompt?{initialPrompt:s.initialPrompt}:{}});return}if(e.type==="logFilter"){this.closeModal();return}if(e.type==="historyFormat"){this.closeModal();return}e.type==="artifactPicker"&&await this.downloadArtifactModalSelection()}}openLogFilter(){const e=this.getState().ui.focusRegion;this.dispatch({type:"ui/modal",modal:{type:"logFilter",title:"Log Filters",previousFocus:e,selectedIndex:0,items:[{id:"source",label:"Source nodes",description:"Choose whether the log pane shows logs from all nodes or only the current orchestration.",options:[{id:"allNodes",label:"All nodes"},{id:"currentOrchestration",label:"Current orchestration"}]},{id:"level",label:"Levels",description:"Filter logs by severity/verbosity level.",options:[{id:"all",label:"All"},{id:"info",label:"Info"},{id:"warn",label:"Warn"},{id:"error",label:"Error"},{id:"debug",label:"Debug"},{id:"trace",label:"Trace"}]},{id:"format",label:"Format",description:"Raw shows the structured time/node/level summary. Pretty shows the cleaned message text, colored by orchestration vs activity.",options:[{id:"pretty",label:"Pretty text"},{id:"raw",label:"Raw summary"}]}]}}),this.dispatch({type:"ui/status",text:"Tab/Shift-Tab switch filters · Up/Down change values · Enter close · Esc cancel"})}openHistoryFormat(){const e=this.getState().ui.focusRegion;this.dispatch({type:"ui/modal",modal:{type:"historyFormat",title:"Execution History Format",previousFocus:e,selectedIndex:0,items:[{id:"format",label:"Format",description:"Pretty prints a human-readable view with colored event kinds. Raw JSON shows the full event objects.",options:[{id:"pretty",label:"Pretty text"},{id:"raw",label:"Raw JSON"}]}]}}),this.dispatch({type:"ui/status",text:"Up/Down change format · Enter close · Esc cancel"})}toggleLogTail(){const e=this.getState().logs;if(!e.available){this.dispatch({type:"ui/status",text:e.availabilityReason||"Log tailing is not available in this environment"});return}if(e.tailing){this.detachLogStream(),typeof this.transport.stopLogTail=="function"&&this.transport.stopLogTail().catch(()=>{}),this.dispatch({type:"logs/tailing",tailing:!1}),this.dispatch({type:"ui/status",text:"Log tailing stopped"});return}if(typeof this.transport.startLogTail!="function"){this.dispatch({type:"ui/status",text:"Log tailing is not supported by this transport"});return}this.logUnsubscribe=this.transport.startLogTail(s=>{const n=Array.isArray(s)?s:[s];n.length>0&&this.dispatch({type:"logs/append",entries:n})}),this.dispatch({type:"logs/tailing",tailing:!0}),this.dispatch({type:"ui/status",text:"Log tailing started"})}async sendPrompt(){const e=this.getState(),s=e.ui.prompt,n=this.getPromptAttachments(),i=n[0]?.sessionId||null,o=bu(s,n);let r=e.sessions.activeSessionId;i&&(r=i,e.sessions.activeSessionId!==i&&await this.loadSession(i));let a=r&&e.sessions.byId[r]||null;if(r&&!a&&(a=this.getState().sessions.byId[r]||null),!r){const d=await this.createSession({});if(!d?.sessionId)return;r=d.sessionId,a=this.getState().sessions.byId[r]||null}if(!o.trim()){r&&this.getPendingOutboxItems(r).length>0&&await this.dispatchPendingOutbox(r).catch(()=>{});return}const l=a?.pendingQuestion||null,p=!!l?.question,u=this.getPromptEditSessionMatch(r);if(u){const d=this.getSessionOutbox(r).find(f=>f.id===u.itemId);if(d?.phase==="queued"||d?.phase==="cancelling"){this.exitPendingPromptEdit({restoreDraft:!0});return}this.setPrompt("",0),this.setPromptAttachments([]),await this.dispatchPendingOutbox(r).catch(()=>{});return}if(p&&typeof this.transport.sendAnswer=="function"){const d=Date.now(),f={...l,answer:o,answeredAt:d,pendingPhase:"pending"};this.setPrompt("",0),this.setPromptAttachments([]),this.dispatch({type:"sessions/merged",session:{sessionId:r,pendingQuestion:null,answeredPendingQuestion:f}}),this.dispatch({type:"ui/status",text:"Sending answer..."});try{await this.transport.sendAnswer(r,o),this.dispatch({type:"sessions/merged",session:{sessionId:r,answeredPendingQuestion:{...f,pendingPhase:"queued"}}}),this.scheduleSessionDetailSync(r,100),this.syncSessionEvents(r).catch(()=>{}),this.scheduleSessionsRefresh(1e3),this.dispatch({type:"ui/status",text:"Answer sent"})}catch(h){this.dispatch({type:"sessions/merged",session:{sessionId:r,answeredPendingQuestion:null}}),this.dispatch({type:"sessions/merged",session:{sessionId:r,pendingQuestion:l}}),String(this.getState().ui.prompt||"").trim()||this.setPrompt(o,String(o||"").length),this.dispatch({type:"ui/status",text:h?.message||String(h)})}return}this.queuePromptInOutbox(r,o),this.setPrompt("",0),this.setPromptAttachments([]),await this.dispatchPendingOutbox(r).catch(()=>{})}setPrompt(e,s=String(e||"").length){const n=String(e||""),i=Math.max(0,Math.min(Number.isFinite(s)?s:n.length,n.length)),o=this.getState().ui;if(!(o.prompt===n&&o.promptCursor===i)){if(o.promptEdit?.sessionId&&o.promptEdit?.itemId){const a=this.getSessionOutbox(o.promptEdit.sessionId).map(l=>l.id===o.promptEdit.itemId&&l.phase==="pending"?{...l,text:n}:l);this.setSessionOutboxItems(o.promptEdit.sessionId,a)}this.dispatch({type:"ui/prompt",prompt:n,promptCursor:i}),this.syncPromptReferenceBrowser()}}setPromptCursor(e){const s=this.getState().ui.prompt||"";this.setPrompt(s,e)}insertPromptText(e){const s=this.getState().ui,n=_e(s.prompt,s.promptCursor,e);this.setPrompt(n.prompt,n.cursor)}appendPromptChar(e){this.insertPromptText(e)}deletePromptChar(){const e=this.getState().ui,s=st(e.prompt,e.promptCursor);this.setPrompt(s.prompt,s.cursor)}deletePromptWordBackward(){const e=this.getState().ui,s=vu(e.prompt,e.promptCursor);this.setPrompt(s.prompt,s.cursor)}movePromptCursor(e){const s=this.getState().ui;this.setPrompt(s.prompt,X(s.prompt,s.promptCursor+e))}movePromptCursorWord(e){const s=this.getState().ui;this.setPrompt(s.prompt,_o(s.prompt,s.promptCursor,e))}movePromptCursorVertical(e){const s=this.getState().ui,n=Cu(s.prompt,s.promptCursor,e);if(n!==s.promptCursor){this.setPrompt(s.prompt,n);return}e<0&&this.selectPreviousPendingPrompt()||e>0&&this.selectNextPendingPrompt()||this.setPrompt(s.prompt,n)}getCurrentLayout(e={}){const s=this.getState().ui.layout||{},n=this.getState().ui,i=e.prompt??n.prompt;return lt({width:e.width??s.viewportWidth??120,height:e.height??s.viewportHeight??40},e.paneAdjust??s.paneAdjust??0,e.promptRows??n.promptRows??ze(i),e.sessionPaneAdjust??s.sessionPaneAdjust??0,e.activityPaneAdjust??s.activityPaneAdjust??0,e.fullscreenPane??n.fullscreenPane??null)}getSessionListMaxRows(e=this.getCurrentLayout()){const s=e.fullscreenPane===w.SESSIONS?e.bodyHeight:e.sessionPaneHeight;return Math.max(3,s-2)}setViewport(e={}){const s=Math.max(40,Number(e.width)||120),n=Math.max(18,Number(e.height)||40),i=this.getState().ui.layout||{};(i.viewportWidth!==s||i.viewportHeight!==n)&&this.dispatch({type:"ui/viewport",width:s,height:n});const o=this.getCurrentLayout({width:s,height:n}),r=this.getState().ui.focusRegion,a=Ee(r,o);a!==r&&this.setFocus(a)}setFocus(e){this.dispatch({type:"ui/focus",focusRegion:Ee(e,this.getCurrentLayout())})}focusNext(){const e=this.getCurrentLayout(),s=Ee(this.getState().ui.focusRegion,e),n=vs(e);this.setFocus(Ze(n,s,1))}focusPrev(){const e=this.getCurrentLayout(),s=Ee(this.getState().ui.focusRegion,e),n=vs(e);this.setFocus(Ze(n,s,-1))}focusLeft(){const e=this.getCurrentLayout(),s=Ee(this.getState().ui.focusRegion,e);this.setFocus(ta(s,e))}focusRight(){const e=this.getCurrentLayout(),s=Ee(this.getState().ui.focusRegion,e);this.setFocus(sa(s,e))}adjustPaneSplit(e){const s=this.getState().ui.layout||{},n=s.viewportWidth??120,i=Math.max(-n,Math.min(n,(s.paneAdjust||0)+e));this.dispatch({type:"ui/paneAdjust",paneAdjust:i});const o=this.getCurrentLayout({paneAdjust:i}),r=this.getState().ui.focusRegion,a=Ee(r,o);a!==r&&this.setFocus(a)}adjustSessionPaneSplit(e){const s=this.getState().ui.layout||{},i=this.getCurrentLayout().bodyHeight??s.viewportHeight??40,o=Math.max(-i,Math.min(i,(s.sessionPaneAdjust||0)+e));this.dispatch({type:"ui/sessionPaneAdjust",sessionPaneAdjust:o});const r=this.getCurrentLayout({sessionPaneAdjust:o}),a=this.getState().ui.focusRegion,l=Ee(a,r);l!==a&&this.setFocus(l)}adjustActivityPaneSplit(e){const s=this.getState().ui.layout||{},i=this.getCurrentLayout().bodyHeight??s.viewportHeight??40,o=Math.max(-i,Math.min(i,(s.activityPaneAdjust||0)+e));this.dispatch({type:"ui/activityPaneAdjust",activityPaneAdjust:o});const r=this.getCurrentLayout({activityPaneAdjust:o}),a=this.getState().ui.focusRegion,l=Ee(a,r);l!==a&&this.setFocus(l)}nextInspectorTab(){const e=this.getState().ui.inspectorTab,s=Ze(ge,e,1);this.dispatch({type:"ui/inspectorTab",inspectorTab:s}),this.ensureInspectorData(s).catch(()=>{})}prevInspectorTab(){const e=Ze(ge,this.getState().ui.inspectorTab,-1);this.dispatch({type:"ui/inspectorTab",inspectorTab:e}),this.ensureInspectorData(e).catch(()=>{})}cycleInspectorTab(){this.nextInspectorTab()}toggleStatsView(){const e=["session","fleet","users"],s=this.getState().ui.statsViewMode,n=e.includes(s)?e.indexOf(s):0,i=e[(n+1)%e.length];this.setStatsViewMode(i)}setStatsViewMode(e){this.dispatch({type:"ui/statsViewMode",statsViewMode:e}),this.getState().ui.inspectorTab==="stats"&&this.ensureInspectorData("stats").catch(()=>{})}async selectInspectorTab(e){ge.includes(e)&&(this.dispatch({type:"ui/inspectorTab",inspectorTab:e}),await this.ensureInspectorData(e).catch(()=>{}))}async moveSession(e){const s=this.getState(),n=ht(s);if(n.length===0)return;const i=s.sessions.activeSessionId||n[0].sessionId,o=Math.max(0,n.findIndex(l=>l.sessionId===i)),r=Math.max(0,Math.min(n.length-1,o+e)),a=n[r].sessionId;await this.loadSession(a)}getSessionPageSize(){const e=this.getCurrentLayout(),s=e.fullscreenPane===w.SESSIONS?e.bodyHeight:e.sessionPaneHeight;return Math.max(1,s-3)}async moveSessionPage(e){const s=this.getSessionPageSize();await this.moveSession(s*e)}inspectorUsesBottomScroll(){return Au.has(this.getState().ui.inspectorTab)}paneUsesStickyBottomFollow(e,s=this.getState()){return e==="activity"?!0:e==="inspector"?s.ui.inspectorTab==="logs":!1}isPaneFollowingBottom(e,s=this.getState()){return this.paneUsesStickyBottomFollow(e,s)?s.ui.followBottom?.[e]!==!1:!1}getPaneVisualScrollOffset(e,s=this.getState()){const n=this.getPaneMaxScrollOffset(e,s),i=Math.max(0,Math.min(Number(s.ui.scroll?.[e])||0,n));return this.isPaneFollowingBottom(e,s)?Math.max(0,n-i):i}applyPaneVisualScrollOffset(e,s,n={},i=this.getState()){const o=this.getPaneMaxScrollOffset(e,i),r=Math.max(0,Math.min(Number(s)||0,o));if(this.paneUsesStickyBottomFollow(e,i)){const a=n.followBottom!==void 0?!!n.followBottom:n.atBottom!==void 0?!!n.atBottom:r>=o;return this.dispatch({type:"ui/followBottom",pane:e,followBottom:a}),this.dispatch({type:"ui/scroll",pane:e,offset:a?0:r}),r}return this.dispatch({type:"ui/scroll",pane:e,offset:r}),r}updatePaneScrollFromViewport(e,s,n={}){const i=this.getState();if(this.paneUsesStickyBottomFollow(e,i)){this.applyPaneVisualScrollOffset(e,s,n,i);return}this.scrollPaneTo(e,s)}expandActiveSession(){const e=this.getState().sessions.activeSessionId;e&&this.dispatch({type:"sessions/expand",sessionId:e})}collapseActiveSession(){const e=this.getState().sessions.activeSessionId;e&&this.dispatch({type:"sessions/collapse",sessionId:e})}scrollPane(e,s){const n=this.getState(),i=this.getPaneMaxScrollOffset(e,n);if(this.paneUsesStickyBottomFollow(e,n)){const a=this.getPaneVisualScrollOffset(e,n),l=Math.max(0,Math.min(a-s,i));this.applyPaneVisualScrollOffset(e,l,{followBottom:l>=i},n);return}const o=Math.max(0,Math.min(Number(n.ui.scroll?.[e])||0,i)),r=Math.max(0,Math.min(o+s,i));this.dispatch({type:"ui/scroll",pane:e,offset:r}),e==="chat"&&s>0?o>=i?this.handleChatTopHistoryScrollIntent(r).catch(()=>{}):r>=i&&this.armChatTopHistoryLoad():e==="chat"&&s<0&&this.disarmChatTopHistoryLoad()}scrollPaneTo(e,s){const n=this.getState(),i=this.getPaneMaxScrollOffset(e,n),o=Math.max(0,Math.min(Number(s)||0,i));if(this.paneUsesStickyBottomFollow(e,n)){this.applyPaneVisualScrollOffset(e,o,{followBottom:o>=i},n);return}this.dispatch({type:"ui/scroll",pane:e,offset:o}),e==="chat"&&(i>0&&o>=i?this.armChatTopHistoryLoad():this.disarmChatTopHistoryLoad())}armChatTopHistoryLoad(){const e=this.getState().sessions.activeSessionId;e&&(this.chatTopHistoryLoadArmed=!0,this.chatTopHistoryLoadSessionId=e)}disarmChatTopHistoryLoad(){this.chatTopHistoryLoadArmed=!1,this.chatTopHistoryLoadSessionId=null}async handleChatTopHistoryScrollIntent(e){const n=this.getState().sessions.activeSessionId;if(n){if(!this.chatTopHistoryLoadArmed||this.chatTopHistoryLoadSessionId!==n){this.armChatTopHistoryLoad();return}await this.maybeAutoExpandActiveHistory(e,{pages:Xc})}}getScrollablePaneForFocus(){const e=this.getState().ui.focusRegion;return e===w.CHAT?"chat":e===w.ACTIVITY?"activity":e===w.INSPECTOR?this.getState().ui.inspectorTab==="files"?"filePreview":"inspector":null}scrollCurrentPane(e){const s=this.getScrollablePaneForFocus();if(!s)return;if(this.paneUsesStickyBottomFollow(s)){this.scrollPane(s,e);return}const n=s==="inspector"&&this.inspectorUsesBottomScroll(),i=s==="inspector"||s==="filePreview";this.scrollPane(s,i&&!n?-e:e)}scrollCurrentPaneToTop(){const e=this.getScrollablePaneForFocus();if(!e)return;if(this.paneUsesStickyBottomFollow(e)){this.applyPaneVisualScrollOffset(e,0,{followBottom:!1});return}const s=e==="inspector"&&this.inspectorUsesBottomScroll();if(e==="chat"||e==="activity"||s){this.scrollPaneTo(e,Number.MAX_SAFE_INTEGER);return}this.scrollPaneTo(e,0)}scrollCurrentPaneToBottom(){const e=this.getScrollablePaneForFocus();if(!e)return;if(this.paneUsesStickyBottomFollow(e)){this.applyPaneVisualScrollOffset(e,Number.MAX_SAFE_INTEGER,{followBottom:!0});return}const s=e==="inspector"&&this.inspectorUsesBottomScroll();if(e==="chat"||e==="activity"||s){this.scrollPaneTo(e,0);return}this.scrollPaneTo(e,Number.MAX_SAFE_INTEGER)}async expandActiveHistory(){const e=this.getState().sessions.activeSessionId;e&&await this.expandSessionHistory(e)}getActiveChatRenderMetrics(e=this.getState()){const s=this.getCurrentLayout();if(s.leftHidden)return{contentWidth:20,contentHeight:1,totalLines:0};const n=Math.max(20,s.leftWidth-4),i=Math.max(1,s.chatPaneHeight-2),o=nn(e,n),r=po(e,n),a=Math.min(Math.max(0,Math.floor(i*.34)),Ge(r,n)),l=Ge(o,n);return{contentWidth:n,contentHeight:Math.max(1,i-a),totalLines:l}}getActivityRenderMetrics(e=this.getState()){const s=this.getCurrentLayout();if(s.rightHidden||s.activityHidden)return{contentWidth:20,contentHeight:1,totalLines:0};const n=Math.max(20,s.rightWidth-4),i=Math.max(1,s.activityPaneHeight-2),o=e.sessions.activeSessionId,r={sessions:{activeSessionId:o,byId:o?{[o]:e.sessions.byId[o]||null}:{}},history:{bySessionId:o?new Map([[o,e.history.bySessionId.get(o)||null]]):new Map}},a=on(r);return{contentWidth:n,contentHeight:i,totalLines:Ge(a.lines,n)}}getInspectorRenderMetrics(e=this.getState()){const s=this.getCurrentLayout();if(s.rightHidden||s.inspectorHidden)return{contentWidth:20,contentHeight:1,stickyLineCount:0,totalLines:0};const n=Math.max(20,s.rightWidth-4),i=e.sessions.activeSessionId,o=i&&e.orchestration.bySessionId?.[i]||null,r={branding:e.branding,sessions:{activeSessionId:i,byId:e.sessions.byId,flat:e.sessions.flat},history:{bySessionId:e.history.bySessionId},orchestration:{bySessionId:i&&o?{[i]:o}:{}},logs:e.logs,sessionStats:e.sessionStats,fleetStats:e.fleetStats,ui:{inspectorTab:e.ui.inspectorTab,statsViewMode:e.ui.statsViewMode},executionHistory:e.executionHistory},a=Fe(r,{width:n}),l=a.tabs.map(f=>({text:f===a.activeTab?`[${f}] `:`${f} `,color:f===a.activeTab?"magenta":"gray",bold:f===a.activeTab})),p=(a.lines||[]).map(f=>typeof f=="string"?{text:f,color:"white"}:f),u=a.activeTab==="sequence"?[l,...(a.stickyLines||[]).map(f=>typeof f=="string"?{text:f,color:"white"}:f)]:[],d=a.activeTab==="sequence"?p:[l,...p];return{contentWidth:n,contentHeight:Math.max(1,s.inspectorPaneHeight-2),stickyLineCount:Ge(u,n),totalLines:Ge(d,n)}}getFilePreviewRenderMetrics(e=this.getState()){const s=this.getCurrentLayout();if((s.rightHidden||s.inspectorHidden)&&!e.files?.fullscreen)return{contentWidth:20,contentHeight:1,totalLines:0};const n=e.ui.inspectorTab==="files"&&!!e.files?.fullscreen,i=n?s.totalWidth:s.rightWidth,o=n?Math.max(10,s.bodyHeight):s.inspectorPaneHeight,r=Math.max(20,i-4),a=Math.max(8,r-4),l=e.sessions.activeSessionId,p=l&&e.sessions.byId[l]||null,u={sessions:{activeSessionId:l,byId:l&&p?{[l]:p}:{},flat:e.sessions.flat},files:{bySessionId:e.files.bySessionId,fullscreen:!!e.files.fullscreen,selectedArtifactId:e.files.selectedArtifactId,filter:e.files.filter},ui:{scroll:{filePreview:e.ui.scroll.filePreview}}},d=rn(u,{listWidth:a,previewWidth:a}),f=Math.max(9,o-4),h=Math.max(5,Math.min(10,Math.floor(f*.35)));let m=Math.max(5,Math.min(h,(d.listBodyLines||[]).length+2)),g=Math.max(5,f-m-1);const I=8;if(g<I){const y=I-g;m=Math.max(5,m-y),g=Math.max(5,f-m-1)}return{contentWidth:a,contentHeight:Math.max(1,g-2),totalLines:Ge(d.previewLines,a)}}getPaneMaxScrollOffset(e,s=this.getState()){if(!e)return 0;if(e==="chat"){const n=this.getActiveChatRenderMetrics(s);return Math.max(0,n.totalLines-n.contentHeight)}if(e==="activity"){const n=this.getActivityRenderMetrics(s);return Math.max(0,n.totalLines-n.contentHeight)}if(e==="inspector"){const n=this.getInspectorRenderMetrics(s),i=Math.min(n.contentHeight,n.stickyLineCount||0),o=Math.max(0,n.contentHeight-i);return Math.max(0,n.totalLines-o)}if(e==="filePreview"){const n=this.getFilePreviewRenderMetrics(s);return Math.max(0,n.totalLines-n.contentHeight)}return 0}async maybeAutoExpandActiveHistory(e,s={}){const n=this.getState(),i=n.sessions.activeSessionId;if(!i)return;const o=n.history.bySessionId.get(i);if(!o?.hasOlderEvents||this.sessionHistoryExpansionLoads.has(i))return;if(Number(o.loadedEventCount||0)>=pi){this.dispatch({type:"ui/status",text:"Reached automatic history limit. Press e to load more older CMS events."});return}const{contentHeight:r,totalLines:a}=this.getActiveChatRenderMetrics(n),l=Math.max(0,a-r);e<l||await this.expandSessionHistory(i,{requestedScrollOffset:e,autoTriggered:!0,pages:s.pages})}async expandSessionHistory(e,s={}){if(!e)return;if(this.sessionHistoryExpansionLoads.has(e))return this.sessionHistoryExpansionLoads.get(e);const n=this.getState(),i=n.history.bySessionId.get(e),o=Math.max(V,Number(i?.loadedEventLimit??V)||V),r=V,a=Array.isArray(i?.events)&&i.events.length>0?Number(i.events[0]?.seq||0):0;if(!i?.hasOlderEvents||a<=1){this.dispatch({type:"ui/status",text:"Already showing the oldest loaded history"});return}const l=e===n.sessions.activeSessionId,p=Number(s.requestedScrollOffset??n.ui.scroll?.chat??0),u=l?this.getActiveChatRenderMetrics(n).totalLines:0,d=(async()=>{let f;const h=Math.max(1,Math.floor(Number(s.pages)||1));if(typeof this.transport.getSessionEventsBefore=="function"&&a>0){f=i||xt([],{requestedLimit:o});for(let g=0;g<h;g+=1){const I=Array.isArray(f?.events)&&f.events.length>0?Number(f.events[0]?.seq||0):0;if(!f?.hasOlderEvents||I<=1){f={...f,hasOlderEvents:!1};break}if(Number(f.loadedEventCount||0)>=pi)break;const y=await this.transport.getSessionEventsBefore(e,I,r);if(!Array.isArray(y)||y.length===0){f={...f,hasOlderEvents:!1};break}const x=xt(y,{requestedLimit:r}),E=[...x.events||[],...f?.events||[]];if(f={chat:qe([...x.chat||[],...f?.chat||[]]),activity:[...x.activity||[],...f?.activity||[]],events:E,lastSeq:f?.lastSeq||f?.events?.[f?.events?.length-1]?.seq||y[y.length-1]?.seq||0,loadedEventLimit:E.length,loadedEventCount:E.length,hasOlderEvents:y.length>=r&&Number(y[0]?.seq||0)>1},!f.hasOlderEvents)break}}else{const g=Wr(o);if(g<=o){this.dispatch({type:"ui/status",text:i?.hasOlderEvents?`Already showing a large recent history window (${o} events)`:"Already showing the oldest loaded history"});return}const I=await this.transport.getSessionEvents(e,void 0,g);f={...xt(I,{requestedLimit:g}),lastSeq:I[I.length-1]?.seq||0}}this.dispatch({type:"history/set",sessionId:e,history:f});for(const g of f?.events||[])this.reconcileOutboxAgainstEvent(e,g);if(l&&p>0){const g=this.getState(),I=this.getActiveChatRenderMetrics(g).totalLines,y=Math.max(0,I-u);y>0&&this.dispatch({type:"ui/scroll",pane:"chat",offset:p+y})}const m=f.hasOlderEvents?s.autoTriggered?`Loaded older history page from CMS (${f.loadedEventCount} events loaded)`:`Loaded older history page (${f.loadedEventCount} events loaded)`:`Loaded full available history (${f.loadedEventCount} events)`;this.dispatch({type:"ui/status",text:m}),f.hasOlderEvents?s.autoTriggered&&l&&this.armChatTopHistoryLoad():this.disarmChatTopHistoryLoad()})().finally(()=>{this.sessionHistoryExpansionLoads.delete(e)});return this.sessionHistoryExpansionLoads.set(e,d),d}async cancelActiveSession({confirmed:e=!1}={}){const s=this.getState(),n=Array.isArray(s.sessions.selectedIds)?s.sessions.selectedIds:[];if(s.sessions.selectMode&&n.length>=1){const{eligible:r,skippedCount:a}=this.getBulkSelectedSessionActions(s);if(r.length===0){this.dispatch({type:"ui/status",text:"No cancellable sessions in selection (system sessions and groups are skipped)."});return}if(!e){this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Cancel Sessions",message:`Cancel ${r.length} selected session${r.length===1?"":"s"}?${a>0?` (${a} selected row${a===1?"":"s"} will be skipped)`:""}`,confirmLabel:"Cancel Sessions",action:"cancelSession",previousFocus:s.ui.focusRegion}});return}let l=0;const p=[];for(const d of r)try{await this.transport.cancelSession(d.sessionId),l+=1}catch(f){p.push(`${d.sessionId.slice(0,8)}: ${f?.message||String(f)}`)}this.dispatch({type:"sessions/selectClear"});const u=p.length===0?`Cancelled ${l} session${l===1?"":"s"}`:`Cancelled ${l}/${r.length}; ${p.length} failed: ${p.slice(0,2).join(", ")}${p.length>2?"…":""}`;this.dispatch({type:"ui/status",text:u}),await this.refreshSessions();return}const i=s.sessions.activeSessionId;if(!i)return;const o=s.sessions.byId[i];if(o?.isGroup){this.dispatch({type:"ui/status",text:"Groups are containers; cancel sessions individually."});return}if(o?.isSystem){if(typeof this.transport.restartSystemSession!="function"){this.dispatch({type:"ui/status",text:"System session restart is not supported by this transport"});return}if(!e){const r=o.title||o.agentId||i.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Terminate & Restart System Session",message:`Terminate system session "${r}" and start a fresh one?`,confirmLabel:"Terminate & Restart",action:"cancelSession",sessionId:i,previousFocus:s.ui.focusRegion}});return}await this.transport.restartSystemSession(o.agentId||i,{disposition:"terminate",reason:"Terminated by user for system-session restart"}),this.dispatch({type:"ui/status",text:`Restarted system session ${o.agentId||i.slice(0,8)}`}),await this.refreshSessions();return}if(!e){const a=o?.title||i.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Cancel Session",message:`Cancel session "${a}"? The session will stop processing.`,confirmLabel:"Cancel Session",action:"cancelSession",sessionId:i,previousFocus:s.ui.focusRegion}});return}await this.transport.cancelSession(i),this.dispatch({type:"ui/status",text:`Cancelled ${i.slice(0,8)}`}),await this.refreshSessions()}async stopActiveSessionTurn(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s)return;const n=e.sessions.byId[s];if(!n||n.isGroup){this.dispatch({type:"ui/status",text:"Select a session to stop its turn."});return}if(typeof this.transport.stopSessionTurn!="function"){this.dispatch({type:"ui/status",text:"Stop turn is not supported by this transport"});return}if(this._stopTurnInFlight||(this._stopTurnInFlight=new Set),!this._stopTurnInFlight.has(s)){this._stopTurnInFlight.add(s),this.dispatch({type:"ui/status",text:`Stopping turn for ${s.slice(0,8)}…`});try{const o=(await this.transport.stopSessionTurn(s,{reason:"Stopped by user"}))?.outcome||"stopped";o==="no_active_turn"?this.dispatch({type:"ui/status",text:"No active turn to stop"}):o==="timeout"?this.dispatch({type:"ui/status",text:"Stop requested — waiting for the turn to unwind"}):this.dispatch({type:"ui/status",text:`Stopped turn for ${s.slice(0,8)}`})}catch(i){this.dispatch({type:"ui/status",text:`Stop turn failed: ${i?.message||i}`})}finally{this._stopTurnInFlight.delete(s)}await this.refreshSessions(),await this.refreshActiveSessionDetail?.().catch?.(()=>{})}}togglePinActiveSession(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s)return;const n=e.sessions.byId[s];if(!n)return;if(n.isSystem){this.dispatch({type:"ui/status",text:"System sessions cannot be pinned."});return}if(!n.isGroup&&(n.parentSessionId||n.groupId)){this.dispatch({type:"ui/status",text:"Sessions inside groups or parents cannot be pinned."});return}const i=Array.isArray(e.sessions.pinnedIds)&&e.sessions.pinnedIds.includes(s);this.dispatch({type:"sessions/pinToggle",sessionId:s}),this.dispatch({type:"ui/status",text:i?`Unpinned ${s.slice(0,8)}`:`Pinned ${s.slice(0,8)}`})}toggleSessionSelectMode(){const e=this.getState(),s=!e.sessions.selectMode;if(this.dispatch({type:"sessions/selectMode",enabled:s}),s){const n=e.sessions.activeSessionId;n&&e.sessions.byId[n]&&this.dispatch({type:"sessions/selectToggle",sessionId:n}),this.dispatch({type:"ui/status",text:"Select mode: space toggles, Ctrl+G moves, c cancels, V/esc exits"})}else this.dispatch({type:"ui/status",text:"Select mode off"})}toggleActiveSessionSelection(){const e=this.getState(),s=e.sessions.activeSessionId;s&&(e.sessions.selectMode||this.dispatch({type:"sessions/selectMode",enabled:!0}),this.dispatch({type:"sessions/selectToggle",sessionId:s}))}setSessionSelection(e){const s=Array.isArray(e)?e:[];this.dispatch({type:"sessions/selectSet",sessionIds:s})}clearSessionSelection(){this.dispatch({type:"sessions/selectClear"})}async completeActiveSession(e="Completed by user",{confirmed:s=!1}={}){const n=this.getState(),i=Array.isArray(n.sessions.selectedIds)?n.sessions.selectedIds:[];if(n.sessions.selectMode&&i.length>=1){const{eligible:a,skippedCount:l}=this.getBulkSelectedSessionActions(n);if(a.length===0){this.dispatch({type:"ui/status",text:"No completable sessions in selection (system sessions and groups are skipped)."});return}if(!s){this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Complete Sessions",message:`Complete ${a.length} selected session${a.length===1?"":"s"}? This will cascade to their sub-agents.${l>0?` (${l} selected row${l===1?"":"s"} will be skipped)`:""}`,confirmLabel:"Complete Sessions",action:"completeSession",previousFocus:n.ui.focusRegion}});return}let p=0;const u=[];for(const f of a)try{await this.transport.completeSession(f.sessionId,e),p+=1}catch(h){u.push(`${f.sessionId.slice(0,8)}: ${h?.message||String(h)}`)}this.dispatch({type:"sessions/selectClear"});const d=u.length===0?`Completed ${p} session${p===1?"":"s"}`:`Completed ${p}/${a.length}; ${u.length} failed: ${u.slice(0,2).join(", ")}${u.length>2?"…":""}`;this.dispatch({type:"ui/status",text:d}),await this.refreshSessions();return}const o=this.getState().sessions.activeSessionId;if(!o)return;const r=this.getState().sessions.byId[o];if(r?.isGroup){this.dispatch({type:"ui/status",text:"Groups are containers; complete sessions individually."});return}if(r?.isSystem){if(typeof this.transport.restartSystemSession!="function"){this.dispatch({type:"ui/status",text:"System session restart is not supported by this transport"});return}if(!s){const a=r.title||r.agentId||o.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Complete & Restart System Session",message:`Mark system session "${a}" complete and start a fresh one?`,confirmLabel:"Complete & Restart",action:"completeSession",sessionId:o,previousFocus:this.getState().ui.focusRegion}});return}await this.transport.restartSystemSession(r.agentId||o,{disposition:"complete",reason:e}),this.dispatch({type:"ui/status",text:`Restarted system session ${r.agentId||o.slice(0,8)}`}),await this.refreshSessions();return}if(typeof this.transport.completeSession!="function"){this.dispatch({type:"ui/status",text:"Session completion is not supported by this transport"});return}if(r?.status==="completed"&&!r?.cronActive&&!r?.cronInterval){this.dispatch({type:"ui/status",text:`${o.slice(0,8)} is already completed`});return}if(!s){const a=r?.title||o.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Complete Session",message:`Complete session "${a}"? This will cascade to all sub-agents.`,confirmLabel:"Complete",action:"completeSession",sessionId:o,previousFocus:this.getState().ui.focusRegion}});return}this.dispatch({type:"ui/status",text:`Completing ${o.slice(0,8)} (cascading to sub-agents)...`});try{await this.transport.completeSession(o,e),await this.refreshSessions(),this.scheduleSessionDetailSync(o,100),this.scheduleSessionsRefresh(900)}catch(a){await this.loadSession(o).catch(()=>{}),this.dispatch({type:"ui/status",text:`Failed to send /done: ${a?.message||String(a)}`})}}async deleteActiveSession({confirmed:e=!1}={}){const s=this.getState(),n=Array.isArray(s.sessions.selectedIds)?s.sessions.selectedIds:[];if(s.sessions.selectMode&&n.length>=1){const{eligible:r,skippedCount:a}=this.getBulkSelectedSessionActions(s);if(r.length===0){this.dispatch({type:"ui/status",text:"No deletable sessions in selection (system sessions and groups are skipped)."});return}if(!e){this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Hard Delete Sessions",message:`Hard delete ${r.length} selected session${r.length===1?"":"s"}? This action cannot be undone.${a>0?` (${a} selected row${a===1?"":"s"} will be skipped)`:""}`,confirmLabel:"Hard Delete Sessions",action:"deleteSession",previousFocus:s.ui.focusRegion}});return}let l=0;const p=[];for(const d of r)try{await this.transport.deleteSession(d.sessionId),l+=1}catch(f){p.push(`${d.sessionId.slice(0,8)}: ${f?.message||String(f)}`)}this.dispatch({type:"sessions/selectClear"});const u=p.length===0?`Deleted ${l} session${l===1?"":"s"}`:`Deleted ${l}/${r.length}; ${p.length} failed: ${p.slice(0,2).join(", ")}${p.length>2?"…":""}`;this.dispatch({type:"ui/status",text:u}),await this.refreshSessions();return}const i=s.sessions.activeSessionId;if(!i)return;const o=s.sessions.byId[i];if(o?.isGroup){const r=o.groupId||gs(i);if(!r||typeof this.transport.deleteSessionGroup!="function"){this.dispatch({type:"ui/status",text:"Group deletion is not supported by this transport"});return}if(Number(o.memberCount||0)>0){this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Group Not Empty",message:`Group "${o.title||r}" is not empty. Move all sessions out of the group before deleting it.`,confirmLabel:"OK",action:"alert",alert:!0,previousFocus:s.ui.focusRegion}}),this.dispatch({type:"ui/status",text:"Move all sessions out of the group before deleting it."});return}if(!e){this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Delete Group",message:`Delete empty group "${o.title||r}"? This action cannot be undone.`,confirmLabel:"Delete Group",action:"deleteSession",sessionId:i,previousFocus:s.ui.focusRegion}});return}await this.transport.deleteSessionGroup(r),this.dispatch({type:"ui/status",text:`Deleted group ${o.title||r}`}),await this.refreshSessions();return}if(o?.isSystem){if(typeof this.transport.restartSystemSession!="function"){this.dispatch({type:"ui/status",text:"System session restart is not supported by this transport"});return}if(!e){const r=o.title||o.agentId||i.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Hard Delete & Restart System Session",message:`Hard delete system session "${r}" and start a fresh one? This removes the current orchestration immediately.`,confirmLabel:"Hard Delete & Restart",action:"deleteSession",sessionId:i,previousFocus:s.ui.focusRegion}});return}await this.transport.restartSystemSession(o.agentId||i,{disposition:"hard_delete",reason:"Hard-deleted by user for system-session restart"}),this.dispatch({type:"ui/status",text:`Restarted system session ${o.agentId||i.slice(0,8)}`}),await this.refreshSessions();return}if(!e){const a=o?.title||i.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Delete Session",message:`Delete session "${a}"? This action cannot be undone.`,confirmLabel:"Delete",action:"deleteSession",sessionId:i,previousFocus:s.ui.focusRegion}});return}await this.transport.deleteSession(i),this.dispatch({type:"ui/status",text:`Deleted ${i.slice(0,8)}`}),await this.refreshSessions()}async handleCommand(e){switch(e){case b.REFRESH:await this.refreshSessions();return;case b.NEW_SESSION:await this.openNewSessionFlow();return;case b.OPEN_MODEL_PICKER:await this.openModelPicker();return;case b.OPEN_THEME_PICKER:this.openThemePicker();return;case b.OPEN_RENAME_SESSION:this.openRenameSessionModal();return;case b.OPEN_SESSION_FILTER:this.openSessionOwnerFilter();return;case b.OPEN_TERMINATE_PICKER:await this.openTerminatePickerModal();return;case b.OPEN_MOVE_TO_GROUP:await this.openMoveToGroupModal();return;case b.CREATE_SESSION_GROUP:await this.openMoveToGroupModal();return;case b.OPEN_ARTIFACT_UPLOAD:this.openArtifactUploadModal();return;case b.TOGGLE_CHAT_VIEW:this.toggleChatViewMode();return;case b.CLOSE_MODAL:this.closeModal();return;case b.MODAL_PREV:this.moveModalSelection(-1);return;case b.MODAL_NEXT:this.moveModalSelection(1);return;case b.MODAL_PANE_PREV:this.moveModalPane(-1);return;case b.MODAL_PANE_NEXT:this.moveModalPane(1);return;case b.MODAL_CONFIRM:await this.confirmModal();return;case b.SEND_PROMPT:await this.sendPrompt();return;case b.FOCUS_NEXT:this.focusNext();return;case b.FOCUS_PREV:this.focusPrev();return;case b.FOCUS_LEFT:this.focusLeft();return;case b.FOCUS_RIGHT:this.focusRight();return;case b.FOCUS_PROMPT:this.setFocus(w.PROMPT);return;case b.FOCUS_SESSIONS:this.setFocus(w.SESSIONS);return;case b.MOVE_SESSION_UP:await this.moveSession(-1);return;case b.MOVE_SESSION_DOWN:await this.moveSession(1);return;case b.EXPAND_SESSION:this.expandActiveSession();return;case b.COLLAPSE_SESSION:this.collapseActiveSession();return;case b.NEXT_INSPECTOR_TAB:this.nextInspectorTab();return;case b.PREV_INSPECTOR_TAB:this.prevInspectorTab();return;case b.CYCLE_INSPECTOR_TAB:this.cycleInspectorTab();return;case b.GROW_LEFT_PANE:this.adjustPaneSplit(8);return;case b.GROW_RIGHT_PANE:this.adjustPaneSplit(-8);return;case b.GROW_SESSION_PANE:this.adjustSessionPaneSplit(2);return;case b.SHRINK_SESSION_PANE:this.adjustSessionPaneSplit(-2);return;case b.OPEN_ARTIFACT_PICKER:await this.openArtifactPicker();return;case b.TOGGLE_LOG_TAIL:this.toggleLogTail();return;case b.TOGGLE_STATS_VIEW:this.toggleStatsView();return;case b.OPEN_LOG_FILTER:this.openLogFilter();return;case b.OPEN_FILES_FILTER:this.openFilesFilter();return;case b.MOVE_FILE_UP:await this.moveFileSelection(-1);return;case b.MOVE_FILE_DOWN:await this.moveFileSelection(1);return;case b.DOWNLOAD_SELECTED_FILE:await this.downloadSelectedArtifact();return;case b.DELETE_SELECTED_FILE:await this.deleteSelectedArtifact();return;case b.OPEN_SELECTED_FILE:await this.openSelectedFileInDefaultApp();return;case b.TOGGLE_FILE_PREVIEW_FULLSCREEN:this.toggleFilePreviewFullscreen();return;case b.TOGGLE_PANE_FULLSCREEN:this.toggleFocusedPaneFullscreen();return;case b.SCROLL_UP:this.scrollCurrentPane(1);return;case b.SCROLL_DOWN:this.scrollCurrentPane(-1);return;case b.PAGE_UP:if(this.getState().ui.focusRegion===w.SESSIONS){await this.moveSessionPage(-1);return}this.scrollCurrentPane(10);return;case b.PAGE_DOWN:if(this.getState().ui.focusRegion===w.SESSIONS){await this.moveSessionPage(1);return}this.scrollCurrentPane(-10);return;case b.EXPAND_HISTORY:await this.expandActiveHistory();return;case b.SCROLL_TOP:this.scrollCurrentPaneToTop();return;case b.SCROLL_BOTTOM:this.scrollCurrentPaneToBottom();return;case b.CANCEL_SESSION:await this.cancelActiveSession();return;case b.STOP_TURN:await this.stopActiveSessionTurn();return;case b.DONE_SESSION:await this.completeActiveSession();return;case b.DELETE_SESSION:await this.deleteActiveSession();return;case b.PIN_SESSION:this.togglePinActiveSession();return;case b.TOGGLE_SELECT_MODE:this.toggleSessionSelectMode();return;case b.TOGGLE_SESSION_SELECTION:this.toggleActiveSessionSelection();return;case b.CLEAR_SESSION_SELECTION:this.clearSessionSelection();return;case b.OPEN_HISTORY_FORMAT:this.openHistoryFormat();return;case b.REFRESH_EXECUTION_HISTORY:{const s=this.getState().sessions.activeSessionId;s&&await this.ensureExecutionHistory(s,{force:!0});return}case b.EXPORT_EXECUTION_HISTORY:{await this.exportExecutionHistory();return}case b.OPEN_ADMIN_CONSOLE:await this.openAdminConsole();return;case b.CLOSE_ADMIN_CONSOLE:this.closeAdminConsole();return;case b.ADMIN_REFRESH_PROFILE:await this.refreshAdminProfile();return;case b.ADMIN_BEGIN_EDIT_GHCP_KEY:this.beginAdminEditGhcpKey();return;case b.ADMIN_CANCEL_EDIT_GHCP_KEY:this.cancelAdminEditGhcpKey();return;case b.ADMIN_SAVE_GHCP_KEY:await this.saveAdminGhcpKey();return;case b.ADMIN_CLEAR_GHCP_KEY:await this.clearAdminGhcpKey();return;default:return}}async exportExecutionHistory(){const e=this.getState().sessions.activeSessionId;if(!e){this.dispatch({type:"ui/status",text:"No session selected."});return}if(typeof this.transport.exportExecutionHistory!="function"){this.dispatch({type:"ui/status",text:"History export is not supported by this transport."});return}this.dispatch({type:"ui/status",text:"Exporting execution history..."});try{const s=await this.transport.exportExecutionHistory(e);s?.filename&&(await this.ensureFilesForSession(e,{force:!0}).catch(()=>null),this.dispatch({type:"files/select",sessionId:e,filename:s.filename}),this.dispatch({type:"files/selectGlobal",artifactId:`${e}/${s.filename}`}),await this.ensureFilePreview(e,s.filename,{force:!0}).catch(()=>null)),this.dispatch({type:"ui/status",text:s?.filename?`History saved as artifact ${s.filename}`:`History exported → ${s?.artifactLink||"artifact created"}`})}catch(s){this.dispatch({type:"ui/status",text:`Export failed: ${s?.message||String(s)}`})}}}const Yt=0;function ue(t,e){if(Object.is(t,e))return!0;if(!t||!e||typeof t!="object"||typeof e!="object")return!1;const s=Object.keys(t),n=Object.keys(e);if(s.length!==n.length)return!1;for(const i of s)if(!Object.prototype.hasOwnProperty.call(e,i)||!Object.is(t[i],e[i]))return!1;return!0}function ys(){try{const t=globalThis?.process,e=t?.memoryUsage;if(typeof e?.rss=="function"){const s=Number(e.rss());return Number.isFinite(s)&&s>0?s:null}if(typeof e=="function"){const s=Number(e.call(t)?.rss);return Number.isFinite(s)&&s>0?s:null}}catch{}return null}function _u(t){if(!Number.isFinite(t)||t<=0)return null;const e=Math.round(t/(1024*1024));return[{text:"rss ",color:"gray"},{text:`${e}M`,color:"white",bold:!0}]}function Lu(t,e=null){const s=[...Array.isArray(t)?t:[]],n=typeof e=="string"?e.trim():"";return n?(s.length>0&&s.push({text:" ",color:"gray"}),s.push({text:n,color:"cyan",bold:!0}),s):s.length>0?s:null}function $u(t=2e3){const[e,s]=c.useState(()=>ys());return c.useEffect(()=>{if(ys()==null)return;const n=()=>{const o=ys();o!=null&&s(r=>r===o?r:o)};n();const i=setInterval(n,t);return()=>clearInterval(i)},[t]),c.useMemo(()=>_u(e),[e])}function Je(t,e){return t&&e?{[t]:e}:{}}function gi(t){return typeof t=="string"?{text:t,color:"white"}:t}function wt(t,e,s,n,i,o){const r=(e.tabs||ge).map(d=>({text:d===e.activeTab?`[${d}] `:`${d} `,color:d===e.activeTab?"magenta":"gray",bold:d===e.activeTab})),a=(e.lines||[]).map(gi),l=(e.stickyLines||[]).map(gi),p=e.activeTab==="sequence"?[r,...l]:[],u=e.activeTab==="sequence"?a:[r,...a];return c.createElement(t.Panel,{title:e.title,color:"magenta",focused:s.focused,width:n,height:i,stickyLines:p,marginBottom:Yt,lines:u,scrollOffset:s.inspectorScroll,scrollMode:e.activeTab==="sequence"||e.activeTab==="logs"&&s.inspectorFollowBottom?"bottom":"top",paneId:"inspector",paneLabel:e.activeTab==="sequence"?"Sequence":"Inspector",frame:o})}function yi(t,e){const s=String(t||"");return e<=0?"":s.length<=e?s:e===1?s.slice(0,1):`${s.slice(0,e-1)}...`}c.memo(function({controller:e,maxRows:s,width:n,height:i,frame:o,versionLabel:r=null}){const a=he(),l=$u(),p=c.useMemo(()=>Lu(l,r),[l,r]),u=H(e,m=>({sessions:m.sessions,mode:m.connection?.mode||"local",brandingTitle:m.branding?.title||"PilotSwarm",focused:m.ui.focusRegion==="sessions"}),ue),d=c.useMemo(()=>({sessions:u.sessions,connection:{mode:u.mode},branding:{title:u.brandingTitle}}),[u.brandingTitle,u.mode,u.sessions]),f=c.useMemo(()=>Ts(d,s),[d,s]),h=c.useMemo(()=>f.length===0?[{text:"No sessions yet. Press n to create one.",color:"gray"}]:f.map(m=>m.active?Xi(m.runs,{preserveColors:!0}):m.runs),[f]);return c.createElement(a.Panel,{title:[{text:"Sessions",color:"yellow",bold:!0}],titleRight:p,color:"yellow",focused:u.focused,width:n,height:i,marginBottom:Yt,lines:h,paneId:"sessions",paneLabel:"Sessions",frame:o})});c.memo(function({controller:e,width:s,height:n,frame:i}){const o=he(),r=H(e,m=>{const g=m.sessions.activeSessionId;return{activeSessionId:g,activeSession:g&&m.sessions.byId[g]||null,activeHistory:g&&m.history.bySessionId.get(g)||null,branding:m.branding,connectionError:m.connection.error,connectionMode:m.connection.mode,chatViewMode:m.ui.chatViewMode||"transcript",chatScroll:m.ui.scroll.chat,focused:m.ui.focusRegion==="chat"}},ue),a=Math.max(20,s-4),l=c.useMemo(()=>{const m=new Map;return r.activeSessionId&&r.activeHistory&&m.set(r.activeSessionId,r.activeHistory),{branding:r.branding,connection:{error:r.connectionError,mode:r.connectionMode},ui:{chatViewMode:r.chatViewMode},sessions:{activeSessionId:r.activeSessionId,byId:Je(r.activeSessionId,r.activeSession)},history:{bySessionId:m}}},[r.activeHistory,r.activeSessionId,r.activeSession,r.branding,r.chatViewMode,r.connectionError,r.connectionMode]),p=c.useMemo(()=>mo(l,{width:a}),[a,l]),u=Ti(!!p?.animateTitleRight),d=c.useMemo(()=>ki(p?.titleRight,u),[u,p?.titleRight]),f=!r.activeSessionId&&r.connectionError,h=c.useMemo(()=>f?[{kind:"markup",value:r.branding.splash},{text:"",color:"gray"},{text:"Startup failed",color:"red",bold:!0},{text:r.connectionError,color:"white"},{text:"",color:"gray"},{text:"Check env credentials and model provider config, then relaunch.",color:"yellow"}]:nn(l,a),[r.branding.splash,r.connectionError,a,l,f]);return c.createElement(o.Panel,{title:p.title,titleRight:d,color:p.color,focused:r.focused,width:s,height:n,lines:h,scrollOffset:r.chatScroll,scrollMode:"bottom",paneId:"chat",paneLabel:"Chat",frame:i})});const Bu=c.memo(function({controller:e,width:s,height:n,shellTitle:i,focused:o=!1,frame:r,showFullscreenTitle:a=!1,embedded:l=!1}){const p=he(),u=H(e,L=>({activeSessionId:L.sessions.activeSessionId,activeSession:L.sessions.activeSessionId&&L.sessions.byId[L.sessions.activeSessionId]||null,sessionsFlat:L.sessions.flat,filesBySessionId:L.files.bySessionId,filesFullscreen:!!L.files.fullscreen,selectedArtifactId:L.files.selectedArtifactId,filesFilter:L.files.filter,filePreviewScroll:L.ui.scroll.filePreview}),ue),d=Math.max(20,s-4),f=c.useMemo(()=>({sessions:{activeSessionId:u.activeSessionId,byId:u.activeSessionId&&u.activeSession?{[u.activeSessionId]:u.activeSession}:{},flat:u.sessionsFlat},files:{bySessionId:u.filesBySessionId,fullscreen:u.filesFullscreen,selectedArtifactId:u.selectedArtifactId,filter:u.filesFilter},ui:{scroll:{filePreview:u.filePreviewScroll}}}),[u]),h=c.useMemo(()=>rn(f,{listWidth:Math.max(8,d-4),previewWidth:Math.max(8,d-4)}),[d,f]),m=i||(a?h.fullscreenTitle:h.panelTitle||h.listTitle)||[{text:"Files",color:"magenta",bold:!0}],g=Math.max(9,n-4),I=Math.max(5,Math.min(10,Math.floor(g*.35)));let y=Math.max(5,Math.min(I,(h.listBodyLines||[]).length+2)),x=Math.max(5,g-y-1);const E=8;if(x<E){const L=E-x;y=Math.max(5,y-L),x=Math.max(5,g-y-1)}const v=Math.max(1,y-2),T=Math.max(0,h.selectedIndex-Math.floor(v/2)),O=!l&&r?{x:r.x+2,y:r.y+2,width:d,height:y}:null,M=!l&&r?{x:r.x+2,y:r.y+2+y+1,width:d,height:x}:null,k=ge.map(L=>({text:L==="files"?`[${L}] `:`${L} `,color:L==="files"?"magenta":"gray",bold:L==="files"})),N=c.createElement(p.Column,{width:d},c.createElement(p.Lines,{lines:[k]}),c.createElement(p.Panel,{title:h.listTitle,color:"gray",focused:!1,width:d,height:y,lines:h.listBodyLines||h.listLines.slice(1),scrollOffset:T,scrollMode:"top",marginBottom:1,paneId:"files:list",paneLabel:"Files list",frame:O}),c.createElement(p.Panel,{title:h.previewTitle,color:"gray",focused:!1,width:d,height:x,lines:h.previewLines,scrollOffset:h.previewScrollOffset,scrollMode:"top",paneId:"files:preview",paneLabel:"File preview",frame:M}));return l?N:c.createElement(p.Panel,{title:m,color:"magenta",focused:o,width:s,height:n,marginBottom:Yt,paneId:"inspector",paneLabel:"Inspector",frame:r},N)}),Du=c.memo(function({controller:e,width:s,height:n,frame:i,meta:o}){const r=he(),a=Math.max(20,s-4),l=H(e,d=>({activeSessionId:d.sessions.activeSessionId,activeSession:d.sessions.activeSessionId&&d.sessions.byId[d.sessions.activeSessionId]||null}),ue),p=c.useMemo(()=>({sessions:{activeSessionId:l.activeSessionId,byId:Je(l.activeSessionId,l.activeSession)},ui:{inspectorTab:"files"}}),[l.activeSession,l.activeSessionId]),u=c.useMemo(()=>Fe(p,{width:a}),[a,p]);return c.createElement(r.Panel,{title:u.title,color:"magenta",focused:o.focused,width:s,height:n,marginBottom:Yt,paneId:"inspector",paneLabel:"Inspector",frame:i},c.createElement(Bu,{controller:e,width:s,height:n,frame:i,focused:o.focused,embedded:!0}))}),Hu=c.memo(function({controller:e,width:s,height:n,frame:i,meta:o}){const r=he(),a=Math.max(20,s-4),l=H(e,d=>({activeSessionId:d.sessions.activeSessionId,activeSession:d.sessions.activeSessionId&&d.sessions.byId[d.sessions.activeSessionId]||null,activeOrchestration:d.sessions.activeSessionId&&d.orchestration.bySessionId?.[d.sessions.activeSessionId]||null,histories:d.history.bySessionId}),ue),p=c.useMemo(()=>({sessions:{activeSessionId:l.activeSessionId,byId:Je(l.activeSessionId,l.activeSession)},history:{bySessionId:l.histories},orchestration:{bySessionId:l.activeSessionId&&l.activeOrchestration?{[l.activeSessionId]:l.activeOrchestration}:{}},ui:{inspectorTab:"sequence"}}),[l.activeOrchestration,l.activeSession,l.activeSessionId,l.histories]),u=c.useMemo(()=>Fe(p,{width:a}),[a,p]);return wt(r,u,o,s,n,i)}),Gu=c.memo(function({controller:e,width:s,height:n,frame:i,meta:o}){const r=he(),a=Math.max(20,s-4),l=H(e,d=>({activeSessionId:d.sessions.activeSessionId,activeSession:d.sessions.activeSessionId&&d.sessions.byId[d.sessions.activeSessionId]||null,logs:d.logs}),ue),p=c.useMemo(()=>({sessions:{activeSessionId:l.activeSessionId,byId:Je(l.activeSessionId,l.activeSession)},logs:l.logs,ui:{inspectorTab:"logs"}}),[l.activeSession,l.activeSessionId,l.logs]),u=c.useMemo(()=>Fe(p,{width:a}),[a,p]);return wt(r,u,o,s,n,i)}),ju=c.memo(function({controller:e,width:s,height:n,frame:i,meta:o}){const r=he(),a=Math.max(20,s-4),l=H(e,d=>({activeSessionId:d.sessions.activeSessionId,activeSession:d.sessions.activeSessionId&&d.sessions.byId[d.sessions.activeSessionId]||null,executionHistory:d.executionHistory}),ue),p=c.useMemo(()=>({sessions:{activeSessionId:l.activeSessionId,byId:Je(l.activeSessionId,l.activeSession)},executionHistory:l.executionHistory,ui:{inspectorTab:"history"}}),[l.activeSession,l.activeSessionId,l.executionHistory]),u=c.useMemo(()=>Fe(p,{width:a}),[a,p]);return wt(r,u,o,s,n,i)}),Uu=c.memo(function({controller:e,width:s,height:n,frame:i,meta:o}){const r=he(),a=Math.max(20,s-4),l=H(e,d=>({activeSessionId:d.sessions.activeSessionId,sessionsById:d.sessions.byId,sessionsFlat:d.sessions.flat,histories:d.history.bySessionId}),ue),p=c.useMemo(()=>({sessions:{activeSessionId:l.activeSessionId,byId:l.sessionsById,flat:l.sessionsFlat},history:{bySessionId:l.histories},ui:{inspectorTab:"nodes"}}),[l.activeSessionId,l.histories,l.sessionsById,l.sessionsFlat]),u=c.useMemo(()=>Fe(p,{width:a}),[a,p]);return wt(r,u,o,s,n,i)}),Wu=c.memo(function({controller:e,width:s,height:n,frame:i,meta:o}){const r=he(),a=Math.max(20,s-4),l=H(e,d=>({activeSessionId:d.sessions.activeSessionId,activeSession:d.sessions.activeSessionId&&d.sessions.byId[d.sessions.activeSessionId]||null,sessionStats:d.sessionStats,fleetStats:d.fleetStats,statsViewMode:d.ui.statsViewMode}),ue),p=c.useMemo(()=>({sessions:{activeSessionId:l.activeSessionId,byId:Je(l.activeSessionId,l.activeSession)},sessionStats:l.sessionStats,fleetStats:l.fleetStats,ui:{inspectorTab:"stats",statsViewMode:l.statsViewMode}}),[l.activeSession,l.activeSessionId,l.fleetStats,l.sessionStats,l.statsViewMode]),u=c.useMemo(()=>Fe(p,{width:a}),[a,p]);return wt(r,u,o,s,n,i)});c.memo(function({controller:e,width:s,height:n,frame:i}){const o=H(e,r=>({inspectorTab:r.ui.inspectorTab,inspectorScroll:r.ui.scroll.inspector,inspectorFollowBottom:r.ui.followBottom?.inspector!==!1,focused:r.ui.focusRegion==="inspector"}),ue);return o.inspectorTab==="files"?c.createElement(Du,{controller:e,width:s,height:n,frame:i,meta:o}):o.inspectorTab==="sequence"?c.createElement(Hu,{controller:e,width:s,height:n,frame:i,meta:o}):o.inspectorTab==="logs"?c.createElement(Gu,{controller:e,width:s,height:n,frame:i,meta:o}):o.inspectorTab==="history"?c.createElement(ju,{controller:e,width:s,height:n,frame:i,meta:o}):o.inspectorTab==="stats"?c.createElement(Wu,{controller:e,width:s,height:n,frame:i,meta:o}):c.createElement(Uu,{controller:e,width:s,height:n,frame:i,meta:o})});c.memo(function({controller:e,width:s,height:n,maxLines:i,frame:o}){const r=he(),a=H(e,u=>{const d=u.sessions.activeSessionId;return{sessionsById:u.sessions.byId,activeSessionId:d,activeSession:d&&u.sessions.byId[d]||null,activeHistory:d&&u.history.bySessionId.get(d)||null,scroll:u.ui.scroll.activity,followBottom:u.ui.followBottom?.activity!==!1,focused:u.ui.focusRegion==="activity"}},ue),l=c.useMemo(()=>{const u=new Map;return a.activeSessionId&&a.activeHistory&&u.set(a.activeSessionId,a.activeHistory),{sessions:{activeSessionId:a.activeSessionId,byId:a.sessionsById},history:{bySessionId:u}}},[a.activeHistory,a.activeSessionId,a.sessionsById]),p=c.useMemo(()=>on(l,i),[i,l]);return c.createElement(r.Panel,{title:p.title,color:"gray",focused:a.focused,width:s,height:n,lines:p.lines,scrollOffset:a.scroll,scrollMode:a.followBottom?"bottom":"top",paneId:"activity",paneLabel:"Activity",frame:o})});c.memo(function({controller:e,rows:s}){const n=he(),i=H(e,o=>{const r=o.sessions.activeSessionId,a=r&&o.sessions.byId[r]||null,l=r&&o.outbox?.bySessionId?.[r]?o.outbox.bySessionId[r]:[];return{prompt:o.ui.prompt,promptCursor:o.ui.promptCursor,focused:o.ui.focusRegion==="prompt",answeringQuestion:!!a?.pendingQuestion?.question,editingPending:o.ui.promptEdit?.sessionId===r,hasOutbox:l.length>0,hasPendingOutbox:l.some(p=>p?.phase==="pending")}},ue);return c.createElement(n.Input,{label:i.answeringQuestion?"answer":i.editingPending?"pending":"you",value:i.prompt,cursorIndex:i.promptCursor,focused:i.focused,placeholder:i.answeringQuestion?"Type an answer and press Enter":i.editingPending?"Edit pending prompt, Enter sends batch, Esc cancels":i.hasOutbox?"Type a message and press Enter to queue it":"Type a message and press Enter",rows:s})});c.memo(function({controller:e}){const s=he(),n=H(e,u=>({connected:u.connection.connected,workersOnline:u.connection.workersOnline,focusRegion:u.ui.focusRegion,inspectorTab:u.ui.inspectorTab,chatViewMode:u.ui.chatViewMode||"transcript",fullscreenPane:u.ui.fullscreenPane||null,logsAvailable:u.logs.available,logsTailing:u.logs.tailing,filesFullscreen:!!u.files.fullscreen,mode:u.connection.mode,statusText:u.ui.statusText,modal:u.ui.modal,activeSessionId:u.sessions.activeSessionId,activeSession:u.sessions.activeSessionId&&u.sessions.byId[u.sessions.activeSessionId]||null,selectedIds:u.sessions.selectedIds,selectMode:u.sessions.selectMode}),ue),i=c.useMemo(()=>({connection:{connected:n.connected,workersOnline:n.workersOnline,mode:n.mode},ui:{focusRegion:n.focusRegion,inspectorTab:n.inspectorTab,chatViewMode:n.chatViewMode,fullscreenPane:n.fullscreenPane,statusText:n.statusText,modal:n.modal},logs:{available:n.logsAvailable,tailing:n.logsTailing},files:{fullscreen:n.filesFullscreen},sessions:{activeSessionId:n.activeSessionId,selectedIds:n.selectedIds,selectMode:n.selectMode,byId:n.activeSessionId&&n.activeSession?{[n.activeSessionId]:n.activeSession}:{}}}),[n]),o=c.useMemo(()=>Pl(i),[i]),r=typeof s.getViewport=="function"?s.getViewport():{width:120},a=Math.max(20,(r.width||120)-4),l=Math.min(Math.max(18,Math.floor(a*.45)),a-8),p=Math.max(8,a-l-3);return c.createElement(s.StatusLine,{left:yi(o.left,p),right:yi(o.right,l)})});const $o=920,Bo=7,Do=19,dn=.24,Ho=16,Go=8,Vu=224,qu=190,Ku=48,je=16,jo=.5,kt=jo,zu=5e3,Yu=new Set(["low","medium","high","xhigh"]),Qu=["pilotswarm.theme","pilotswarm.sessionOwnerFilter","pilotswarm.chatFocus","pilotswarm.layoutAdjustments","pilotswarm.pinnedSessions"],Xu=["pilotswarm_theme","pilotswarm_session_owner_filter"],Si={sequence:"Sequence",logs:"Logs",nodes:"Node Map",history:"History",files:"Files",stats:"Stats"};function Ju(t,e,s){const n=Array.isArray(t)?t.filter(Boolean):[];if(n.length===0)return e;const i=n.indexOf(e),r=((i===-1?0:i)+s+n.length)%n.length;return n[r]}function Zu(t){return typeof t?.transport?.uploadArtifactFromFile=="function"}function ed(t){return typeof t?.transport?.uploadArtifactFromPath=="function"}function td(t){return typeof t?.transport?.listArtifacts=="function"}function sd(t){return typeof t?.transport?.deleteArtifact=="function"}function nd(t){return typeof t?.transport?.openPathInDefaultApp=="function"}function id(){if(!(typeof window>"u")){try{for(const t of Qu)window.localStorage.removeItem(t)}catch{}try{for(const t of Xu)document.cookie=`${t}=; Path=/; Max-Age=0; SameSite=Lax`}catch{}}}function Ye(t){const e=t&&typeof t=="object"&&!Array.isArray(t)?t:{},s={};if(typeof e.themeId=="string"&&e.themeId.trim()&&(s.themeId=e.themeId.trim()),fe(e,"sessionOwnerFilter")&&e.sessionOwnerFilter&&typeof e.sessionOwnerFilter=="object"&&(s.sessionOwnerFilter=e.sessionOwnerFilter),fe(e,"layoutAdjustments")&&(s.layoutAdjustments=Vs(e.layoutAdjustments)),fe(e,"pinnedSessionIds")&&(s.pinnedSessionIds=Dt(e.pinnedSessionIds)),fe(e,"collapsedSessionIds")&&(s.collapsedSessionIds=od(e.collapsedSessionIds)),fe(e,"activeSessionId")){const n=e.activeSessionId==null?null:String(e.activeSessionId).trim();s.activeSessionId=n||null}return(e.chatViewMode==="summary"||e.chatViewMode==="transcript")&&(s.chatViewMode=e.chatViewMode),s}function od(t){if(t instanceof Set){const n=[];for(const i of t){const o=String(i||"").trim();o&&n.push(o)}return n.sort(),n}if(!Array.isArray(t))return[];const e=new Set,s=[];for(const n of t){const i=String(n||"").trim();!i||e.has(i)||(e.add(i),s.push(i))}return s.sort(),s}function fe(t,e){return!!(t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,e))}function Ss(t){return Ye({themeId:t.themeId,sessionOwnerFilter:t.ownerFilter,layoutAdjustments:{paneAdjust:t.paneAdjust,sessionPaneAdjust:t.sessionPaneAdjust,portalSessionColumnAdjust:t.portalSessionColumnAdjust,activityPaneAdjust:t.activityPaneAdjust},pinnedSessionIds:t.pinnedIds,collapsedSessionIds:t.collapsedSessionIds,activeSessionId:t.activeSessionId,chatViewMode:t.chatViewMode})}function rd(t){return Ye({themeId:t?.ui?.themeId,sessionOwnerFilter:t?.sessions?.ownerFilter,layoutAdjustments:t?.ui?.layout,pinnedSessionIds:t?.sessions?.pinnedIds,collapsedSessionIds:t?.sessions?.collapsedIds,activeSessionId:t?.sessions?.activeSessionId,chatViewMode:t?.ui?.chatViewMode})}function ad(t,e){const s=Ye(t),n=Ye(e);return Ye({themeId:fe(s,"themeId")?s.themeId:n.themeId,sessionOwnerFilter:fe(s,"sessionOwnerFilter")?s.sessionOwnerFilter:n.sessionOwnerFilter,layoutAdjustments:fe(s,"layoutAdjustments")?s.layoutAdjustments:n.layoutAdjustments,pinnedSessionIds:fe(s,"pinnedSessionIds")?s.pinnedSessionIds:n.pinnedSessionIds,...fe(s,"collapsedSessionIds")?{collapsedSessionIds:s.collapsedSessionIds}:{},...fe(s,"activeSessionId")?{activeSessionId:s.activeSessionId}:{},...fe(s,"chatViewMode")?{chatViewMode:s.chatViewMode}:{}})}async function ld(t,e){return typeof t?.transport?.setCurrentUserProfileSettings!="function"?null:t.transport.setCurrentUserProfileSettings({settings:Ye(e)})}function fn(t){return td(t)?ge:ge.filter(e=>e!=="files")}function Ie(t,e){if(Object.is(t,e))return!0;if(!t||!e||typeof t!="object"||typeof e!="object")return!1;const s=Object.keys(t),n=Object.keys(e);if(s.length!==n.length)return!1;for(const i of s)if(!Object.prototype.hasOwnProperty.call(e,i)||!Object.is(t[i],e[i]))return!1;return!0}function Rs(t,e,s){return Math.max(e,Math.min(s,t))}function Fs(t){const e=Math.max(0,Number(t)||0),s=Math.max(0,e-Ho-Go*2),n=s*dn,i=Math.max(0,s-Vu);return{minAdjust:-n,maxAdjust:i-n}}function cd(t,e){const s=Fs(t),n=Math.max(0,Number(t)||0),o=Math.max(0,n-Ho-Go*2)*dn;return Rs(o+(Number(e)||0),0,o+s.maxAdjust)}function ud(t){return t<=Ku?"hidden":t<=qu?"compact":"wrap"}function Uo(t){const e=Number(t?.ui?.promptRows);return Number.isFinite(e)&&e>0?e:ze(t?.ui?.prompt||"")}function Qt(t){return lt({width:t.ui.layout?.viewportWidth??120,height:t.ui.layout?.viewportHeight??40},t.ui.layout?.paneAdjust??0,Uo(t),t.ui.layout?.sessionPaneAdjust??0)}function dd(t,e){const s=e==="sequence"?3:0;return Math.max(20,t-4-s)}function le(t){const e=[],s=n=>{const i=String(n||"");return!i.includes("\\n")||i.includes(`
77
- `)?i:i.replace(/\\n/g,`
78
- `)};for(const n of t||[]){if(n?.kind==="markup"){for(const i of Oi(n.value||""))e.push({kind:"runs",runs:i,preserve:!0});continue}if(n?.kind==="markdownTable"){e.push(n);continue}if(n?.kind==="runs"){const i=Array.isArray(n.runs)?n.runs:[];if(i.length===1){const o=i[0]||{},r=s(o.text||"");if(r.includes(`
79
- `)){const a=r.split(`
80
- `);for(const l of a)e.push({kind:"runs",runs:[{...o,text:l}]});continue}e.push({kind:"runs",runs:[{...o,text:r}]});continue}e.push({kind:"runs",runs:i.map(o=>({...o,text:s(o?.text||"")}))});continue}if(Array.isArray(n)){e.push({kind:"runs",runs:n});continue}if(n&&typeof n=="object"&&typeof n.text=="string"){const i=s(n.text);if(i.includes(`
81
- `)){const o=i.split(`
82
- `);for(const r of o)e.push({kind:"text",...n,text:r});continue}e.push({kind:"text",...n,text:i});continue}e.push({kind:"text",...n})}return e}function Re(t,e){if(e)return t?.tui?.[e]||t?.terminal?.[e]||t?.page?.[e]||e}function Wo(t=[]){return t.map(e=>String(e?.text||"")).join("")}function bi(t){return Array.isArray(t)?Wo(t):String(t||"")}function wi(t,e=40){if(!Array.isArray(t)){const i=String(t||"");return[{text:i.length>e?`${i.slice(0,e-1)}…`:i,color:"white",bold:!0}]}const s=[];let n=Math.max(8,e);for(const i of t){if(n<=0)break;if(i?.color==="gray"&&s.length>0)continue;const r=String(i?.text||"");if(!r)continue;const a=r.length>n&&n>1?`${r.slice(0,n-1)}…`:r.slice(0,n);a&&(s.push({...i,text:a}),n-=a.length)}return s.length>0?s:t}function fd(t){const e=Ae(t);if(!e||typeof document>"u")return;const s=document.documentElement;s.style.setProperty("--ps-page-background",e.page.background),s.style.setProperty("--ps-page-foreground",e.page.foreground),s.style.setProperty("--ps-surface",e.tui.surface),s.style.setProperty("--ps-background",e.tui.background),s.style.setProperty("--ps-foreground",e.tui.foreground),s.style.setProperty("--ps-muted",e.tui.gray),s.style.setProperty("--ps-border",e.tui.border||e.tui.gray),s.style.setProperty("--ps-selection-background",e.tui.selectionBackground),s.style.setProperty("--ps-selection-foreground",e.tui.selectionForeground),s.style.setProperty("--ps-highlight-background",e.tui.activeHighlightBackground),s.style.setProperty("--ps-highlight-foreground",e.tui.activeHighlightForeground),s.style.setProperty("--ps-modal-backdrop",e.page.modalBackdrop),s.style.setProperty("--ps-modal-background",e.page.modalBackground),s.style.setProperty("--ps-modal-border",e.page.modalBorder),s.style.setProperty("--ps-modal-foreground",e.page.modalForeground),s.style.setProperty("--ps-modal-muted",e.page.modalMuted),s.style.setProperty("--ps-modal-selected-background",e.page.modalSelectedBackground),s.style.setProperty("--ps-modal-selected-border",e.page.modalSelectedBorder),s.style.setProperty("--ps-modal-selected-foreground",e.page.modalSelectedForeground)}function Ii(t){const[e,s]=c.useState({width:0,height:0});return c.useLayoutEffect(()=>{const n=t.current;if(!n)return;const i=()=>{s({width:n.clientWidth,height:n.clientHeight})};i();const o=new ResizeObserver(i);return o.observe(n),window.addEventListener("resize",i),()=>{o.disconnect(),window.removeEventListener("resize",i)}},[t]),e}function pd(t){const e=Math.max(320,t.width||window.innerWidth||1280),s=Math.max(320,t.height||window.innerHeight||800);return{width:Math.max(40,Math.floor(e/Bo)),height:Math.max(18,Math.floor(s/Do))}}function hd(t){if(!t)return 0;const e=Math.max(0,t.scrollHeight-t.clientHeight);return Math.max(0,e-t.scrollTop)}function md(t){return hd(t)<=jo}function gd(t,e,s,n,i,o,{stickyBottom:r=!1}={}){const a=c.useMemo(()=>le(e),[e]),l=c.useRef(null),p=c.useRef({scrollMode:n,scrollOffset:s});c.useLayoutEffect(()=>{const f=t.current;if(!f)return;const h=p.current,m=Math.max(0,f.scrollHeight-f.clientHeight),g=r&&n==="top"&&h?.scrollMode==="top"&&h?.scrollOffset===s,I=Math.max(0,Number(s)||0)*je,y=g?Math.max(0,Math.min(f.scrollTop,m)):n==="bottom"?Math.max(0,m-I):Math.min(m,I);if(Math.abs(f.scrollTop-y)>kt){const x={target:y};l.current=x,f.scrollTop=y,window.requestAnimationFrame(()=>{l.current===x&&(l.current=null)})}p.current={scrollMode:n,scrollOffset:s}},[a,t,n,s,r]);const u=c.useCallback(()=>{const f=t.current;if(!f||!i)return;const h=l.current;if(h){if(Math.abs(f.scrollTop-h.target)<=kt)return;l.current=null}const m=Math.max(0,f.scrollHeight-f.clientHeight);if(m<=0)return;if(r&&typeof o.updatePaneScrollFromViewport=="function"){o.updatePaneScrollFromViewport(i,Math.max(0,f.scrollTop)/je,{atBottom:md(f)});return}const g=n==="bottom"?Math.max(0,m-f.scrollTop):Math.max(0,f.scrollTop);o.dispatch({type:"ui/scroll",pane:i,offset:g/je}),i==="chat"&&n==="bottom"&&f.scrollTop<=kt&&o.armChatTopHistoryLoad?.()},[o,i,t,n,r]),d=c.useCallback(f=>{const h=t.current;if(!h||i!=="chat"||n!=="bottom"||f.deltaY>=0||h.scrollTop>kt)return;const m=Math.max(0,h.scrollHeight-h.clientHeight);o.handleChatTopHistoryScrollIntent?.(m/je)},[o,i,t,n]);return{normalizedLines:a,onScroll:u,onWheel:d}}function oe({runs:t,theme:e}){return c.createElement(c.Fragment,null,(t||[]).map((s,n)=>{const i={color:Re(e,s.color),backgroundColor:Re(e,s.backgroundColor),fontWeight:s.bold?700:400,textDecoration:s.underline?"underline":"none"},o=String(s?.href||"").trim();return/^https?:\/\//i.test(o)?c.createElement("a",{key:`${n}:${s.text||""}`,className:"ps-md-link",href:o,target:"_blank",rel:"noreferrer",style:i},s.text||""):c.createElement("span",{key:`${n}:${s.text||""}`,style:i},s.text||"")}))}function yd({line:t,theme:e}){const s=String(t?.body||"").trim();return c.createElement("details",{className:"ps-system-notice"},c.createElement("summary",{className:"ps-system-notice-summary",style:{color:Re(e,t?.color)||"var(--ps-muted)"}},c.createElement("span",{className:"ps-system-notice-summary-text"},t?.text||"System notice")),s?c.createElement("div",{className:"ps-system-notice-body"},c.createElement(Ko,{content:s,theme:e})):null)}function re({line:t,theme:e,className:s=""}){const n=s?`ps-line ${s}`:"ps-line";return t?t.kind==="systemNotice"?c.createElement(yd,{line:t,theme:e}):t.kind==="runs"?c.createElement("div",{className:n},c.createElement(oe,{runs:t.runs,theme:e})):c.createElement("div",{className:n,style:{color:Re(e,t.color),backgroundColor:Re(e,t.backgroundColor),fontWeight:t.bold?700:400,textDecoration:t.underline?"underline":"none"}},t.text||" "):c.createElement("div",{className:n}," ")}function me(t){return t?t.kind==="runs"?Wo(t.runs):String(t.text||""):""}function Sd(t,e,s,n){const i=c.useRef(!1);return c.useLayoutEffect(()=>{const o=t.current;if(!o)return;const r=Math.max(0,o.scrollHeight-o.clientHeight),a=Math.min(r,Math.max(0,Number(e)||0)*je);Math.abs(o.scrollTop-a)>2&&(i.current=!0,o.scrollTop=a,window.requestAnimationFrame(()=>{i.current=!1}))},[t,e]),c.useCallback(()=>{if(i.current)return;const o=t.current;!o||!s||o.scrollHeight<=o.clientHeight||n.dispatch({type:"ui/scroll",pane:s,offset:Math.max(0,o.scrollTop)/je})},[n,s,t])}function be(t,e,s="md"){return Ds(t).map((n,i)=>{const o=`${s}:${i}`;return n.type==="code"?c.createElement("code",{key:o,className:"ps-md-inline-code"},n.text):n.type==="strong"?c.createElement("strong",{key:o,className:"ps-md-strong"},be(n.text,e,`${o}:strong`)):n.type==="em"?c.createElement("em",{key:o,className:"ps-md-em"},be(n.text,e,`${o}:em`)):n.type==="link"?c.createElement("a",{key:o,className:"ps-md-link",href:n.href,target:"_blank",rel:"noreferrer",style:{color:Re(e,"cyan")}},n.text):c.createElement(c.Fragment,{key:o},n.text)})}function _s(t=""){return String(t||"").replace(/\s+/g," ").trim()}const bd=["description","mechanism","details","notes","summary","message","comment","reason","body","content","explanation","rationale","one-liner"],wd=24,Id=32,xd=6,xi=30,Ed=56,bs=.4,vd=1.4,Cd=2;function Vo(t=[]){const e=Math.max(0,...t.map(m=>m.length));if(e<=0)return null;const s=t[0]||[],n=Math.max(1,t.length-1),i=Array.from({length:e},()=>({max:0,spaceCells:0}));for(let m=0;m<t.length;m+=1){const g=t[m];for(let I=0;I<e;I+=1){const y=_s(g[I]||"");y.length>i[I].max&&(i[I].max=y.length),m>0&&/\s/.test(y)&&(i[I].spaceCells+=1)}}let o=-1,r=0;for(let m=0;m<e;m+=1){const g=i[m];if(g.max<wd||g.spaceCells/n<.4)continue;const y=_s(s[m]||"").toLowerCase(),x=bd.some(v=>y.includes(v))?60:0,E=g.max+x;E>r&&(r=E,o=m)}if(o<0)return null;const a=i.map((m,g)=>g===o?0:Math.max(xd,Math.min(m.max+2,Id))),l=a.reduce((m,g)=>m+g,0),p=i[o],u=Math.max(xi,Math.min(p.max*.45,Ed,Math.max(xi,l*vd))),d=a.map((m,g)=>g===o?u:m),f=d.reduce((m,g)=>m+g,0);if(f>0&&d[o]/f<bs){const m=f-d[o];d[o]=m*(bs/(1-bs))}const h=d.reduce((m,g)=>m+g,0);return h>0?{widths:d.map(m=>`${(m/h*100).toFixed(2)}%`),flexIndex:o,minWidth:`${Math.ceil(h+Cd)}ch`}:null}function qo(t=[],e=0){return Array.from({length:e},(s,n)=>(Array.isArray(t)?t:[]).map(o=>_s(o?.[n]||"")).filter(Boolean).join(" / ")||null)}function Ei(t="",e=""){const s=String(t||"");return/^\s*#{1,6}\s+/.test(s)||/^\s*>/.test(s)||/^\s*([-*]|\d+\.)\s+/.test(s)||/^\s*```/.test(s)||s.includes("|")&&/^\s*\|?[\s:-]+(?:\|[\s:-]+)+\|?\s*$/.test(String(e||""))}function vi(t=""){return String(t||"").trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(s=>s.trim())}function Ad(t=""){const s=String(t||"").replace(/\r\n?/g,`
83
- `).split(`
84
- `),n=[];for(let i=0;i<s.length;){const o=s[i],r=o.trim();if(!r){i+=1;continue}const a=/^```(\S*)\s*$/.exec(r);if(a){const d=a[1]||"",f=[];for(i+=1;i<s.length&&!/^```/.test(s[i].trim());)f.push(s[i]),i+=1;i<s.length&&(i+=1),n.push({type:"code",language:d,content:f.join(`
85
- `)});continue}const l=/^(#{1,6})\s+(.*)$/.exec(o);if(l){n.push({type:"heading",level:l[1].length,text:l[2].trim()}),i+=1;continue}if(o.includes("|")&&i+1<s.length&&/^\s*\|?[\s:-]+(?:\|[\s:-]+)+\|?\s*$/.test(s[i+1].trim())){const d=vi(o);i+=2;const f=[];for(;i<s.length&&s[i].includes("|")&&s[i].trim();)f.push(vi(s[i])),i+=1;n.push({type:"table",header:d,rows:f});continue}if(/^\s*>/.test(o)){const d=[];for(;i<s.length&&/^\s*>/.test(s[i]);)d.push(s[i].replace(/^\s*>\s?/,"")),i+=1;n.push({type:"blockquote",text:d.join(`
86
- `).trim()});continue}const p=/^(\s*)([-*]|\d+\.)\s+(.*)$/.exec(o);if(p){const d=/\d+\./.test(p[2]),f=[];for(;i<s.length;){const h=s[i],m=/^(\s*)([-*]|\d+\.)\s+(.*)$/.exec(h);if(!m||/\d+\./.test(m[2])!==d)break;const g=[m[3].trim()];for(i+=1;i<s.length&&s[i].trim()&&!/^(\s*)([-*]|\d+\.)\s+/.test(s[i])&&!Ei(s[i],s[i+1]||"");)g.push(s[i].trim()),i+=1;if(f.push(g.join(" ")),!s[i]?.trim())break}n.push({type:"list",ordered:d,items:f});continue}const u=[o.trim()];for(i+=1;i<s.length&&s[i].trim()&&!Ei(s[i],s[i+1]||"");)u.push(s[i].trim()),i+=1;n.push({type:"paragraph",text:u.join(" ")})}return n}function Ko({content:t,theme:e}){const s=c.useMemo(()=>Ad(t),[t]);return s.length===0?c.createElement("div",{className:"ps-empty-state"},"No preview content."):c.createElement("div",{className:"ps-markdown-preview"},s.map((n,i)=>{if(n.type==="heading")return c.createElement("div",{key:`block:${i}`,className:`ps-md-heading is-h${n.level}`},be(n.text,e,`heading:${i}`));if(n.type==="code")return c.createElement("section",{key:`block:${i}`,className:"ps-md-code-block"},c.createElement("div",{className:"ps-md-code-header"},n.language||"text"),c.createElement("pre",{className:"ps-md-code-pre"},c.createElement("code",null,n.content)));if(n.type==="blockquote")return c.createElement("blockquote",{key:`block:${i}`,className:"ps-md-quote"},be(n.text,e,`quote:${i}`));if(n.type==="list"){const o=n.ordered?"ol":"ul";return c.createElement(o,{key:`block:${i}`,className:`ps-md-list${n.ordered?" is-ordered":""}`},n.items.map((r,a)=>c.createElement("li",{key:`item:${a}`,className:"ps-md-list-item"},be(r,e,`list:${i}:${a}`))))}if(n.type==="table"){const o=Math.max(n.header.length||0,...n.rows.map(m=>m.length)),r=o>0&&o<=6,a=r?Vo([n.header,...n.rows]):null,l=!!a,p=a?a.flexIndex:-1,u=m=>m===p?"is-flex-column":null,d=qo([n.header],o),f=`ps-md-table${r?" is-fit-width":""}${l?" has-flex-column":""}`,h=`ps-md-table-wrap${r?" is-fit-width":""}${l?" has-flex-column":""}`;return c.createElement("div",{key:`block:${i}`,className:h},c.createElement("table",{className:f,style:a?.minWidth?{"--ps-table-min-width":a.minWidth}:void 0},a?c.createElement("colgroup",null,a.widths.map((m,g)=>c.createElement("col",{key:`col:${g}`,className:u(g)||void 0,style:{width:m}}))):null,c.createElement("thead",null,c.createElement("tr",null,n.header.map((m,g)=>c.createElement("th",{key:`head:${g}`,className:u(g)||void 0},be(m,e,`table:${i}:head:${g}`))))),c.createElement("tbody",null,n.rows.map((m,g)=>c.createElement("tr",{key:`row:${g}`},m.map((I,y)=>c.createElement("td",{key:`cell:${g}:${y}`,className:u(y)||void 0,"data-label":d[y]||void 0},c.createElement("span",{className:"ps-table-cell-value"},be(I,e,`table:${i}:${g}:${y}`)))))))))}return c.createElement("p",{key:`block:${i}`,className:"ps-md-paragraph"},be(n.text,e,`para:${i}`))}))}function Td({controller:t,title:e,color:s,focused:n,scrollOffset:i=0,paneKey:o,theme:r,content:a}){const l=c.useRef(null),p=Sd(l,i,o,t);return c.createElement(De,{title:e,color:s,focused:n,theme:r},c.createElement("div",{ref:l,className:"ps-scroll-panel ps-markdown-scroll",onScroll:p},c.createElement(Ko,{content:a,theme:r})))}function kd(t){const e=Number(t);if(!Number.isFinite(e)||e<0)return"Unknown size";if(e<1024)return`${Math.round(e)} B`;if(e<1024*1024){const n=e/1024;return`${n>=10?Math.round(n):n.toFixed(1)} KB`}const s=e/(1024*1024);return`${s>=10?Math.round(s):s.toFixed(1)} MB`}function Md({title:t,color:e,focused:s,theme:n,filename:i,contentType:o,sizeBytes:r,source:a,uploadedAt:l}){const p=[];o&&p.push(o),r!=null&&p.push(kd(r)),a&&p.push(a);const u=l?new Date(l).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}):"";return c.createElement(De,{title:t,color:e,focused:s,theme:n},c.createElement("div",{className:"ps-binary-preview-card"},c.createElement("div",{className:"ps-binary-preview-kicker"},"Binary artifact"),c.createElement("h3",{className:"ps-binary-preview-title"},i||"Artifact"),p.length>0?c.createElement("div",{className:"ps-binary-preview-meta"},p.join(" • ")):null,u?c.createElement("div",{className:"ps-binary-preview-time"},`Uploaded ${u}`):null,c.createElement("p",{className:"ps-binary-preview-copy"},"Preview is intentionally disabled for non-text artifacts in the browser workspace. Use Download to save the file and open it in the default app.")))}function Ot(t){const e=String(t||"").trim();return e.startsWith("┌")&&e.endsWith("┐")}function ws(t){const e=String(t||"").trim();return e.startsWith("└")&&e.endsWith("┘")}function Pd(t){const e=String(t||"").trim();return e.startsWith("├")&&e.endsWith("┤")}function ct(t){const e=String(t||"").trim();return e.startsWith("│")&&e.endsWith("│")}function Nd(t){const e=String(me(t)||"").trim();return Ot(e)?e.slice(1,-1).replace(/^─+/u,"").replace(/─+$/u,"").trim():""}function Od(t){if(t?.kind==="runs"&&Array.isArray(t.runs)&&t.runs.length>=3)return String(t.runs[1]?.text||"").replace(/\s+$/u,"");const e=me(t);return ct(e)?String(e).slice(1,-1).replace(/\s+$/u,""):String(e||"")}function Rd(t=[]){const e=(t||[]).map(s=>({...s}));return e.length===0?e:(e[0].text=String(e[0].text||"").replace(/^\s+/,""),e[e.length-1].text=String(e[e.length-1].text||"").replace(/\s+$/,""),e.filter((s,n)=>String(s.text||"").length>0||e.length===1||n===0))}function Ci(t,{fallbackColor:e=null}={}){return t?.kind==="runs"&&Array.isArray(t.runs)&&t.runs.length>=3?Rd(t.runs.slice(1,-1)):[{text:me(t).replace(/^\s*[┌│]\s?/,"").replace(/\s?[┐│]\s*$/,"").replace(/^─+/,"").replace(/─+$/,"").trim(),color:e}]}function Fd(t){const e=String(t||"").trim();return ct(e)?e.slice(1,-1).split("│").map(s=>s.trim()):[]}function _d(t="",e=""){const s=String(t||"").trimEnd(),n=String(e||"").trimStart();if(!s||!n)return!1;const i=s.slice(-1),o=n[0];return!!(/^[,.;:!?%)\]}>]/u.test(o)||/^[._/\\-]/u.test(o)||/[([{<._/\\-]$/u.test(i)||/\.[A-Za-z0-9]{0,4}$/u.test(s)&&/^[A-Za-z0-9]/u.test(o))}function Ld(t=[]){const e=(Array.isArray(t)?t:[t]).map(s=>String(s||"").trim()).filter(Boolean);return e.length===0?"":e.slice(1).reduce((s,n)=>_d(s,n)?`${s}${n}`:`${s} ${n}`,e[0])}function Ai(t=[]){const e=Math.max(0,...t.map(s=>s.length));return Array.from({length:e},(s,n)=>Ld(t.map(i=>String(i[n]||"").trim()).filter(Boolean)))}function $d(t=[]){const e=[];for(let s=0;s<t.length;){const n=t[s];if(n?.preserve){const o=[];for(;s<t.length&&t[s]?.preserve;)o.push(t[s]),s+=1;e.push({type:"preserve",lines:o});continue}if(n?.kind==="markdownTable"){e.push({type:"table",headerRows:Array.isArray(n.header)&&n.header.length>0?[n.header]:[],bodyRows:Array.isArray(n.rows)?n.rows:[]}),s+=1;continue}const i=me(n);if(Ot(i)&&i.includes("┬")){const o=[],r=[];let a=[],l=!0;for(s+=1;s<t.length;){const p=t[s],u=me(p);if(ws(u)){if(a.length>0){const d=Ai(a);d.length>0&&(l?o.push(d):r.push(d))}s+=1;break}if(Pd(u)){if(a.length>0){const d=Ai(a);d.length>0&&(l?o.push(d):r.push(d))}a=[],l=!1,s+=1;continue}if(ct(u)){const d=Fd(u);d.length>0&&a.push(d)}s+=1}e.push({type:"table",headerRows:o,bodyRows:r});continue}if(n?.kind==="runs"&&Array.isArray(n.runs)&&n.runs.length===1&&Ot(i)){const o=Nd(n),r=[];for(s+=1;s<t.length;){const a=t[s],l=me(a);if(ws(l)){s+=1;break}ct(l)?r.push(Od(a)):r.push(me(a)),s+=1}s<t.length&&me(t[s]).trim().length===0&&(s+=1),e.push({type:"code",language:o||"text",content:r.join(`
87
- `)});continue}if(n?.kind==="runs"&&Array.isArray(n.runs)&&n.runs.length>2&&Ot(i)){const o=Ci(n),r=n.runs[0]?.color||"gray",a=[];for(s+=1;s<t.length;){const l=t[s],p=me(l);if(ws(p)){s+=1;break}ct(p)?a.push(Ci(l)):a.push(l?.kind==="runs"?l.runs:[{text:me(l),color:l?.color||null}]),s+=1}s<t.length&&me(t[s]).trim().length===0&&(s+=1),e.push({type:"card",headerRuns:o,bodyLines:a,borderColor:r});continue}e.push({type:"line",line:n}),s+=1}return e}function Bd({lines:t,theme:e}){const s=c.useMemo(()=>$d(t),[t]);return c.createElement(c.Fragment,null,s.map((n,i)=>{if(n.type==="preserve")return c.createElement("div",{key:`preserve:${i}`,className:"ps-chat-preserve-block"},n.lines.map((o,r)=>c.createElement(re,{key:`preserve:${i}:${r}`,line:o,theme:e,className:"ps-line-preserve"})));if(n.type==="code")return c.createElement("section",{key:`code:${i}`,className:"ps-md-code-block ps-chat-code-block"},c.createElement("div",{className:"ps-md-code-header"},n.language||"text"),c.createElement("pre",{className:"ps-md-code-pre"},c.createElement("code",null,n.content||"")));if(n.type==="card")return c.createElement("section",{key:`card:${i}`,className:"ps-chat-card",style:{"--ps-chat-card-accent":Re(e,n.borderColor)||"var(--ps-border)"}},c.createElement("header",{className:"ps-chat-card-header"},c.createElement(oe,{runs:n.headerRuns,theme:e})),c.createElement("div",{className:"ps-chat-card-body"},(n.bodyLines||[]).map((o,r)=>c.createElement("div",{key:`card:${i}:line:${r}`,className:"ps-chat-card-line"},c.createElement(oe,{runs:o,theme:e})))));if(n.type==="table"){const o=n.headerRows||[],r=n.bodyRows||[],a=Math.max(1,...o.map(I=>I.length),...r.map(I=>I.length)),l=a<=6,p=l?Vo([...o,...r]):null,u=!!p,d=p?p.flexIndex:-1,f=I=>I===d?"is-flex-column":null,h=qo(o,a),m=`ps-chat-table${l?" is-fit-width":""}${u?" has-flex-column":""}`,g=`ps-chat-table-wrap${l?" is-fit-width":""}${u?" has-flex-column":""}`;return c.createElement("div",{key:`table:${i}`,className:g},c.createElement("table",{className:m,style:p?.minWidth?{"--ps-table-min-width":p.minWidth}:void 0},p?c.createElement("colgroup",null,p.widths.map((I,y)=>c.createElement("col",{key:`col:${y}`,className:f(y)||void 0,style:{width:I}}))):null,o.length>0?c.createElement("thead",null,o.map((I,y)=>c.createElement("tr",{key:`thead:${y}`},Array.from({length:a},(x,E)=>c.createElement("th",{key:`th:${y}:${E}`,className:f(E)||void 0},be(I[E]||"",e,`chat-table:${i}:head:${y}:${E}`)))))):null,c.createElement("tbody",null,r.map((I,y)=>c.createElement("tr",{key:`tbody:${y}`},Array.from({length:a},(x,E)=>c.createElement("td",{key:`td:${y}:${E}`,className:f(E)||void 0,"data-label":h[E]||void 0},c.createElement("span",{className:"ps-table-cell-value"},be(I[E]||"",e,`chat-table:${i}:${y}:${E}`)))))))))}return c.createElement(re,{key:`line:${i}`,line:n.line,theme:e})}))}function De({title:t,titleRight:e=null,color:s="gray",focused:n=!1,actions:i=null,children:o,theme:r,className:a=""}){const l=Re(r,s);return c.createElement("section",{className:`ps-panel${n?" is-focused":""}${a?` ${a}`:""}`,style:{"--ps-panel-accent":l||"var(--ps-border)"}},c.createElement("header",{className:"ps-panel-header"},c.createElement("div",{className:"ps-panel-title"},Array.isArray(t)?c.createElement(oe,{runs:t,theme:r}):bi(t)),e||i?c.createElement("div",{className:"ps-panel-header-right"},e?c.createElement("div",{className:"ps-panel-title-right"},Array.isArray(e)?c.createElement(oe,{runs:e,theme:r}):bi(e)):null,i?c.createElement("div",{className:"ps-panel-actions"},i):null):null),c.createElement("div",{className:"ps-panel-body"},o))}function Dd({lines:t,theme:e,completionByTurn:s}){const[n,i]=c.useState(()=>new Set),o=c.useCallback(u=>{i(d=>{const f=new Set(d);return f.has(u)?f.delete(u):f.add(u),f})},[]),r=u=>Number(u||0).toLocaleString("en-US"),a=u=>{const d=Number(u||0);if(!Number.isFinite(d))return"?K";const f=d/1e3,h=Math.abs(f)>=10?1:2;return`${f.toFixed(h)}K`},l=u=>{const d=Number(u||0);return Number.isFinite(d)?`${(d/1e3).toFixed(1)}s`:"?s"},p=u=>{const d=String(u||"").trim();if(!d)return"unknown";const f=d.split(":").filter(Boolean),h=f[f.length-1]||"",m=f.length>1&&Yu.has(h.toLowerCase())?f.length-2:f.length-1;return f[Math.max(0,m)]||f[0]||"unknown"};return c.createElement(c.Fragment,null,t.map((u,d)=>{const f=u?.kind==="runs"&&Array.isArray(u.runs)?u.runs.find(M=>M?.completedTurn!=null)?.completedTurn:null,h=f!=null?s.get(Number(f)):null;if(!h)return c.createElement(re,{key:`line:${d}`,line:u,theme:e});const m=h.data||{},g=String(h.seq??`${m.turnIndex??f}:${h.createdAt??d}`),I=n.has(g),y=m.reasoningEffort?`${m.model||"(unknown)"}:${m.reasoningEffort}`:m.model||"(unknown)",x=p(m.model),E=m.durationMs!=null?l(m.durationMs):"duration n/a",v=m.durationMs!=null?`${r(m.durationMs)} ms`:"duration n/a",T=`${a(m.tokensInput)} / ${a(m.tokensOutput)}`,O=[["model",y],["started",m.startedAt?new Date(m.startedAt).toLocaleString():null],["ended",m.endedAt?new Date(m.endedAt).toLocaleString():null],["duration",v],["tokens",`${r(m.tokensInput)} in / ${r(m.tokensOutput)} out`],["cache",`${r(m.tokensCacheRead)} read / ${r(m.tokensCacheWrite)} write`],["tools",`${r(m.toolCalls)} calls / ${r(m.toolErrors)} errors`],["names",Array.isArray(m.toolNames)&&m.toolNames.length?m.toolNames.join(", "):null],["worker",m.workerNodeId||null],["result",m.resultType||null],["error",m.errorMessage||null]].filter(([,M])=>M!=null&&M!=="");return c.createElement(c.Fragment,{key:`seq:${d}`},c.createElement(re,{line:u,theme:e}),c.createElement("button",{type:"button",className:"ps-sequence-turn-divider",onClick:()=>o(g)},c.createElement("span",{className:"ps-sequence-turn-caret"},I?"v":">"),c.createElement("span",{className:"ps-sequence-turn-rule"},"--- "),c.createElement("span",{className:"ps-sequence-turn-key"},"Mod: "),c.createElement("span",{className:"ps-sequence-turn-model"},x),c.createElement("span",{className:"ps-sequence-turn-rule"}," ("),c.createElement("span",{className:"ps-sequence-turn-key"},"tok: "),c.createElement("span",{className:"ps-sequence-turn-tokens"},T),c.createElement("span",{className:"ps-sequence-turn-rule"},", "),c.createElement("span",{className:"ps-sequence-turn-key"},"dur: "),c.createElement("span",{className:"ps-sequence-turn-duration"},E),c.createElement("span",{className:"ps-sequence-turn-rule"},") ---")),I?c.createElement("div",{className:"ps-sequence-turn-details"},O.map(([M,k])=>c.createElement("div",{key:M},c.createElement("span",{className:"ps-sequence-turn-detail-label"},`${M}: `),c.createElement("span",null,String(k))))):null)}))}function Xt({title:t,titleRight:e=null,color:s,focused:n,actions:i,lines:o,stickyLines:r=[],bottomStickyLines:a=[],scrollOffset:l=0,scrollMode:p="top",paneKey:u,controller:d,className:f="",panelClassName:h="",topContent:m=null,bottomContent:g=null,structuredBlocks:I=!1,stickyBottom:y=!1,renderBody:x=null}){const E=H(d,D=>D.ui.themeId),v=Ae(E),T=c.useRef(null),O=c.useRef(null),M=c.useRef(!1),{normalizedLines:k,onScroll:N,onWheel:L}=gd(T,o,l,p,u,d,{stickyBottom:y}),Y=c.useMemo(()=>le(r),[r]),_=c.useMemo(()=>le(a),[a]),W=f.includes("is-preserve")&&h.includes("has-preserved-sticky"),U=c.useCallback((D,se)=>{!D||!se||Math.abs((se.scrollLeft||0)-(D.scrollLeft||0))<=1||(M.current=!0,se.scrollLeft=D.scrollLeft,window.requestAnimationFrame(()=>{M.current=!1}))},[]),ee=c.useCallback(D=>{N(),!(!W||M.current)&&U(D.currentTarget,O.current)},[N,W,U]),J=c.useCallback(D=>{!W||M.current||U(D.currentTarget,T.current)},[W,U]);return c.createElement(De,{title:t,titleRight:e,color:s,focused:n,actions:i,theme:v,className:h},m,Y.length>0?c.createElement("div",{ref:O,className:`ps-panel-sticky${W?" is-scroll-sync":""}`,onScroll:J},Y.map((D,se)=>c.createElement(re,{key:`sticky:${se}`,line:D,theme:v}))):null,c.createElement("div",{ref:T,className:`ps-scroll-panel ${f}`.trim(),onScroll:ee,onWheel:L},typeof x=="function"?x(k,v):I?c.createElement(Bd,{lines:k,theme:v}):k.map((D,se)=>c.createElement(re,{key:`line:${se}`,line:D,theme:v}))),_.length>0?c.createElement("div",{className:"ps-panel-bottom-sticky"},_.map((D,se)=>c.createElement(re,{key:`bottom-sticky:${se}`,line:D,theme:v}))):null,g)}function Hd({row:t,theme:e,structured:s=!1}){if(!(s&&Array.isArray(t.titleRuns)))return Array.isArray(t.runs)?c.createElement(oe,{runs:t.runs,theme:e}):t.text;const i=Array.isArray(t.metaRuns)&&t.metaRuns.length>0,o=Array.isArray(t.badgeRuns)&&t.badgeRuns.length>0,r=t.active&&Array.isArray(t.selectedMetaRuns)&&t.selectedMetaRuns.length>0;return c.createElement(c.Fragment,null,c.createElement("div",{className:"ps-session-row-title"},c.createElement(oe,{runs:t.titleRuns,theme:e}),i?c.createElement("span",{className:"ps-session-row-meta"},c.createElement(oe,{runs:[{text:" ",color:"gray"},...t.metaRuns],theme:e})):null),o?c.createElement("div",{className:"ps-session-row-badges"},c.createElement(oe,{runs:t.badgeRuns,theme:e})):null,r?c.createElement("div",{className:"ps-session-row-selected-meta"},c.createElement(oe,{runs:t.selectedMetaRuns,theme:e})):null)}function pn({controller:t,actions:e=null,panelClassName:s="",structuredRows:n=!1}){const i=H(t,k=>k.ui.themeId),o=Ae(i),r=c.useRef(new Map),a=H(t,k=>({activeSessionId:k.sessions.activeSessionId,sessionsById:k.sessions.byId,sessionsFlat:k.sessions.flat,filterQuery:k.sessions.filterQuery||"",ownerFilter:k.sessions.ownerFilter,pinnedIds:k.sessions.pinnedIds,selectedIds:k.sessions.selectedIds,selectMode:k.sessions.selectMode,auth:k.auth,connectionMode:k.connection?.mode||"local",modalOpen:!!k.ui.modal,focused:k.ui.focusRegion==="sessions"}),Ie),l=c.useMemo(()=>ht({sessions:{activeSessionId:a.activeSessionId,byId:a.sessionsById,flat:a.sessionsFlat,filterQuery:a.filterQuery,ownerFilter:a.ownerFilter,pinnedIds:a.pinnedIds,selectedIds:a.selectedIds,selectMode:a.selectMode},auth:a.auth,connection:{mode:a.connectionMode}}),[a.activeSessionId,a.auth,a.connectionMode,a.filterQuery,a.ownerFilter,a.pinnedIds,a.selectedIds,a.selectMode,a.sessionsById,a.sessionsFlat]),p=a.activeSessionId&&a.sessionsById[a.activeSessionId]||null,u=!!(p&&!p.isSystem),d=Array.isArray(a.selectedIds)?a.selectedIds.length:0,f=d>1,h=!!(p&&!p.isSystem&&(p.isGroup||!p.parentSessionId&&!p.groupId)),m=!!(p&&Array.isArray(a.pinnedIds)&&a.pinnedIds.includes(p.sessionId)),g=!!(p?.isGroup&&Number(p.memberCount||0)===0),I=f?Array.isArray(a.selectedIds)&&a.selectedIds.some(k=>{const N=a.sessionsById[k];return N&&!N.isSystem&&!N.isGroup}):p?.isGroup?!0:!!p,y=p?.isGroup?"Delete":f?`Terminate (${d})`:p?.isSystem?"Restart":"Terminate",E=d>0?a.selectedIds.filter(k=>{const N=a.sessionsById[k];return N&&!N.isSystem&&!N.isGroup&&!N.parentSessionId}):p&&!p.isSystem&&!p.isGroup&&!p.parentSessionId?[p.sessionId]:[],v=E.length>0,T=`ps-session-pane${s?` ${s}`:""}`,O=c.useCallback((k,N)=>{k&&(N?r.current.set(k,N):r.current.delete(k))},[]);c.useEffect(()=>{if(a.modalOpen||!a.focused||!a.activeSessionId)return;const k=r.current.get(a.activeSessionId);k&&(document.activeElement!==k&&k.focus({preventScroll:!0}),k.scrollIntoView({block:"nearest"}))},[a.activeSessionId,a.focused,a.modalOpen]);const M=c.createElement(c.Fragment,null,f?c.createElement("span",{className:"ps-mini-button-label",style:{padding:"0 6px",fontSize:"12px",opacity:.85},title:"Multiple sessions selected. Move to group or cancel selected sessions; click Clear to exit."},`${d} selected`):null,f?c.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>t.handleCommand(b.CLEAR_SESSION_SELECTION).catch(()=>{}),title:"Clear multi-selection"},"Clear"):c.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>t.handleCommand(b.PIN_SESSION).catch(()=>{}),disabled:!h,title:h?m?"Unpin this session":"Pin this session to the top of the list":"Only top-level non-system sessions can be pinned"},m?"Unpin":"Pin"),c.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>t.handleCommand(b.OPEN_MOVE_TO_GROUP).catch(()=>{}),disabled:!v,title:v?E.length>1?`Move ${E.length} selected sessions to a group`:"Move this session to a group":"Select a top-level non-system session to move to a group"},E.length>1?`Group (${E.length})`:"Group"),c.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>t.handleCommand(b.OPEN_RENAME_SESSION).catch(()=>{}),disabled:!u||f,title:f?"Disabled while multiple sessions are selected":void 0},"Rename"),c.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>t.handleCommand(p?.isGroup?b.DELETE_SESSION:b.OPEN_TERMINATE_PICKER).catch(()=>{}),disabled:!I,title:f?`Terminate ${d} selected sessions (Mark Completed, Cancel, or Delete)`:p?.isGroup?g?"Delete this empty group":"Show why this group cannot be deleted yet":p?.isSystem?"Restart this system session; choose complete, terminate, or hard delete disposition":"Mark Completed, Cancel, or Delete the active session"},y),e);return c.createElement(De,{title:[{text:"Sessions",color:"yellow",bold:!0}],color:"yellow",focused:a.focused,theme:o,actions:M,className:T},c.createElement("div",{className:"ps-action-list ps-session-list"},l.length===0?c.createElement("div",{className:"ps-empty-state"},a.filterQuery?`No sessions matched "@@${a.filterQuery}".`:"No sessions yet."):l.map(k=>c.createElement("button",{key:k.sessionId,type:"button",ref:N=>O(k.sessionId,N),className:`ps-list-button ps-session-list-button${k.active?" is-selected":""}${k.selected?" is-multiselected":""}${k.pinned?" is-pinned":""}`,tabIndex:k.active?0:-1,"aria-selected":k.active?"true":"false",onClick:N=>{if(N.metaKey||N.ctrlKey){N.preventDefault(),a.selectMode||t.dispatch({type:"sessions/selectMode",enabled:!0}),t.dispatch({type:"sessions/selectToggle",sessionId:k.sessionId}),t.setFocus("sessions");return}if(N.shiftKey&&a.activeSessionId){N.preventDefault();const Y=l.map(U=>U.sessionId),_=Y.indexOf(a.activeSessionId),W=Y.indexOf(k.sessionId);if(_>=0&&W>=0){const[U,ee]=_<=W?[_,W]:[W,_],J=Y.slice(U,ee+1),D=Array.from(new Set([...a.selectedIds||[],...J]));t.setSessionSelection(D),t.setFocus("sessions");return}}if(k.hasChildren&&k.active){t.dispatch({type:k.collapsed?"sessions/expand":"sessions/collapse",sessionId:k.sessionId}),t.setFocus("sessions");return}a.selectMode&&t.dispatch({type:"sessions/selectClear"}),t.setFocus("sessions"),k.active||t.loadSession(k.sessionId).catch(()=>{})}},c.createElement("div",{className:"ps-line ps-session-row-content",style:{paddingInlineStart:`${Math.max(0,k.depth)*18}px`}},c.createElement(Hd,{row:k,theme:o,structured:n}))))))}function hn({controller:t,mobile:e=!1,fullWidth:s=!1,showComposer:n=!0}){const i=H(t,h=>h.ui.themeId);Ae(i);const o=H(t,h=>{const m=h.sessions.activeSessionId,g=Qt(h),I=s||e?g.totalWidth:g.leftWidth,y=Math.max(20,I-4);return{activeSessionId:m,activeHistory:m&&h.history.bySessionId.get(m)||null,activeOutbox:m&&h.outbox?.bySessionId?.[m]?h.outbox.bySessionId[m]:[],branding:h.branding,connection:h.connection,sessionsById:h.sessions.byId,sessionsFlat:h.sessions.flat,inspectorTab:h.ui.inspectorTab,chatViewMode:h.ui.chatViewMode||"transcript",activeSessionIsGroup:!!(m&&h.sessions.byId[m]?.isGroup),focused:h.ui.focusRegion==="chat",scroll:h.ui.scroll.chat,contentWidth:y}},Ie),r=c.useMemo(()=>({branding:o.branding,connection:o.connection,sessions:{activeSessionId:o.activeSessionId,byId:o.sessionsById,flat:o.sessionsFlat},history:{bySessionId:o.activeSessionId&&o.activeHistory?new Map([[o.activeSessionId,o.activeHistory]]):new Map},outbox:{bySessionId:o.activeSessionId?{[o.activeSessionId]:o.activeOutbox}:{}},ui:{inspectorTab:o.inspectorTab,chatViewMode:o.chatViewMode}}),[o.activeHistory,o.activeSessionId,o.activeOutbox,o.branding,o.connection,o.chatViewMode,o.inspectorTab,o.sessionsById,o.sessionsFlat]),a=c.useMemo(()=>mo(r,{width:o.contentWidth}),[r,o.contentWidth]),l=Ti(!!a.animateTitleRight),p=c.useMemo(()=>ki(a.titleRight,a.animateTitleRight?l:""),[l,a.animateTitleRight,a.titleRight]),u=c.useMemo(()=>nn(r,o.contentWidth,{tableMode:"sentinel"}),[r,o.contentWidth]),d=c.useMemo(()=>po(r,o.contentWidth,{tableMode:"sentinel"}),[r,o.contentWidth]),f=n&&!o.activeSessionIsGroup&&o.chatViewMode!=="summary"?c.createElement("div",{className:"ps-chat-composer"},c.createElement(Vd,{controller:t,mobile:e,active:!0})):null;return c.createElement(Xt,{controller:t,title:e?wi(a.title,28):a.title,titleRight:e&&p?wi(p,18):p,actions:null,color:a.color,focused:o.focused,lines:u,bottomStickyLines:d,scrollOffset:o.scroll,scrollMode:"bottom",paneKey:"chat",className:"is-wrapped",panelClassName:"ps-chat-panel",bottomContent:f,structuredBlocks:!0})}function Gd({controller:t,sessionsCollapsed:e,setSessionsCollapsed:s}){const n=H(t,r=>r.ui.themeId),i=Ae(n),o=c.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>s(r=>!r)},e?"Show":"Hide");return c.createElement("div",{className:"ps-mobile-workspace"},e?c.createElement(De,{title:[{text:"Sessions",color:"yellow",bold:!0}],color:"yellow",focused:!1,theme:i,actions:o,className:"ps-mobile-session-collapsed"},c.createElement("div",{className:"ps-mobile-session-summary"},"Session list collapsed.")):c.createElement(pn,{controller:t,actions:o,panelClassName:"ps-mobile-session-pane"}),c.createElement("div",{className:"ps-mobile-chat-pane"},c.createElement(hn,{controller:t,mobile:!0,fullWidth:!0})))}function zo({activeTab:t,controller:e}){const s=c.useMemo(()=>fn(e),[e]),n=typeof window<"u"&&(window.innerWidth||0)>0&&(window.innerWidth||0)<$o,i=o=>n&&o==="nodes"?"Map":Si[o]||o;return c.createElement("div",{className:"ps-tab-row"},s.map(o=>c.createElement("button",{key:o,type:"button",className:`ps-tab${t===o?" is-active":""}`,title:`Switch to ${Si[o]||o}`,"aria-pressed":t===o,onClick:()=>{e.setFocus("inspector"),e.selectInspectorTab(o).catch(()=>{})}},i(o))))}function jd({controller:t,focused:e,mobile:s=!1}){const n=H(t,y=>y.ui.themeId),i=Ae(n),o=c.useRef(null),r=H(t,y=>{const x=y.sessions.activeSessionId,E=Qt(y),v=s||y.files.fullscreen?y.ui.layout?.viewportWidth??120:E.rightWidth;return{activeSessionId:x,sessionsById:y.sessions.byId,sessionsFlat:y.sessions.flat,filesBySessionId:y.files.bySessionId,filesFilter:y.files.filter,selectedArtifactId:y.files.selectedArtifactId,focused:e,previewScroll:y.ui.scroll.filePreview,fullscreen:!!y.files.fullscreen,contentWidth:Math.max(20,v-4),canBrowserUpload:Zu(t),canPathUpload:ed(t),canDeleteArtifacts:sd(t),canOpenLocally:nd(t)}},Ie),a=c.useMemo(()=>({sessions:{activeSessionId:r.activeSessionId,byId:r.sessionsById,flat:r.sessionsFlat},files:{bySessionId:r.filesBySessionId,selectedArtifactId:r.selectedArtifactId,filter:r.filesFilter,fullscreen:r.fullscreen},ui:{scroll:{filePreview:r.previewScroll}}}),[r.activeSessionId,r.filesBySessionId,r.filesFilter,r.fullscreen,r.previewScroll,r.selectedArtifactId,r.sessionsById,r.sessionsFlat]),l=c.useMemo(()=>rn(a,{listWidth:Math.max(18,r.contentWidth-4),previewWidth:Math.max(18,r.contentWidth-4),showHints:!1}),[a,r.contentWidth]),p=c.useMemo(()=>mt(a),[a]),u=p.length>0,d=c.useCallback(y=>{const x=Array.isArray(y)?y.filter(Boolean):[];x.length!==0&&t.uploadArtifactFiles(x).catch(()=>{})},[t]),f=c.useCallback(()=>{if(r.canBrowserUpload&&o.current){o.current.click();return}r.canPathUpload&&t.handleCommand(b.OPEN_ARTIFACT_UPLOAD).catch(()=>{})},[t,r.canBrowserUpload,r.canPathUpload]),h=c.createElement(c.Fragment,null,c.createElement("input",{ref:o,type:"file",className:"ps-hidden-file-input",multiple:!0,tabIndex:-1,"aria-hidden":"true",onChange:y=>{d(Array.from(y.currentTarget.files||[])),y.currentTarget.value=""}}),c.createElement("button",{type:"button",className:"ps-mini-button",onClick:f,disabled:!r.canBrowserUpload&&!r.canPathUpload},"Up"),c.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>t.handleCommand(b.DOWNLOAD_SELECTED_FILE).catch(()=>{}),disabled:!u},"Down"),r.canDeleteArtifacts?c.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>t.handleCommand(b.DELETE_SELECTED_FILE).catch(()=>{}),disabled:!u},"Delete"):null,r.canOpenLocally?c.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>t.handleCommand(b.OPEN_SELECTED_FILE).catch(()=>{}),disabled:!u},"Open"):null,c.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>t.handleCommand(b.OPEN_FILES_FILTER).catch(()=>{})},"Filter"),c.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>t.handleCommand(b.TOGGLE_FILE_PREVIEW_FULLSCREEN).catch(()=>{})},r.fullscreen?"Close":"FS")),m=p.length===0?le(l.listBodyLines||[]).map((y,x)=>c.createElement(re,{key:`empty:${x}`,line:y,theme:i})):p.map((y,x)=>c.createElement("button",{key:y.id,type:"button",className:`ps-list-button${x===l.selectedIndex?" is-selected":""}`,onClick:()=>{t.setFocus("inspector"),t.selectFileBrowserItem(y).catch(()=>{})}},c.createElement(re,{line:le([l.listBodyLines?.[x]])[0],theme:i}))),g=l.previewRenderMode==="markdown"&&!l.previewLoading&&!l.previewError?c.createElement(Td,{controller:t,title:l.previewTitle,color:"cyan",focused:!1,scrollOffset:r.previewScroll,paneKey:"filePreview",theme:i,content:l.previewContent||""}):l.previewIsBinary&&!l.previewLoading&&!l.previewError?c.createElement(Md,{title:l.previewTitle,color:"cyan",focused:!1,theme:i,filename:l.selectedFilename,contentType:l.previewContentType,sizeBytes:l.previewSizeBytes,source:l.previewSource,uploadedAt:l.previewUploadedAt}):c.createElement(Xt,{controller:t,title:l.previewTitle,color:"cyan",focused:!1,lines:l.previewLines,scrollOffset:r.previewScroll,scrollMode:"top",paneKey:"filePreview",className:"is-preview is-wrapped"}),I=r;return c.createElement(De,{title:I.fullscreen?l.fullscreenTitle:s&&l.panelTitleMobile?l.panelTitleMobile:l.panelTitle,color:"magenta",focused:I.focused,actions:h,theme:i},c.createElement(zo,{activeTab:"files",controller:t}),I.fullscreen?g:c.createElement("div",{className:"ps-files-grid"},c.createElement(De,{title:l.listTitle,color:"cyan",theme:i},c.createElement("div",{className:"ps-action-list"},m)),g))}function rt({controller:t,mobile:e=!1,panelClassName:s="",extraActions:n=null}){const i=H(t,d=>{const f=Qt(d),h=d.ui.inspectorTab,m=e?d.ui.layout?.viewportWidth??120:f.rightWidth;return{inspectorTab:h,statsViewMode:d.ui.statsViewMode,activeSessionId:d.sessions.activeSessionId,sessionsById:d.sessions.byId,sessionsFlat:d.sessions.flat,historyBySessionId:d.history.bySessionId,sessionStats:d.sessionStats,fleetStats:d.fleetStats,connection:d.connection,orchestrationBySessionId:d.orchestration.bySessionId,executionHistoryBySessionId:d.executionHistory?.bySessionId||{},executionHistoryFormat:d.executionHistory?.format||"pretty",logs:d.logs,files:d.files,focused:d.ui.focusRegion==="inspector",scroll:d.ui.scroll.inspector,followBottom:d.ui.followBottom?.inspector!==!1,logsTailing:d.logs.tailing,filesFullscreen:!!d.files.fullscreen,contentWidth:dd(m,h)}},Ie),o=c.useMemo(()=>({sessions:{activeSessionId:i.activeSessionId,byId:i.sessionsById,flat:i.sessionsFlat},history:{bySessionId:i.historyBySessionId},sessionStats:i.sessionStats,fleetStats:i.fleetStats,connection:i.connection,ui:{inspectorTab:i.inspectorTab,statsViewMode:i.statsViewMode,scroll:{inspector:i.scroll}},logs:i.logs,files:i.files,orchestration:{bySessionId:i.orchestrationBySessionId},executionHistory:{bySessionId:i.executionHistoryBySessionId,format:i.executionHistoryFormat}}),[i.activeSessionId,i.connection,i.executionHistoryBySessionId,i.executionHistoryFormat,i.fleetStats,i.files,i.historyBySessionId,i.inspectorTab,i.sessionStats,i.statsViewMode,i.logs,i.orchestrationBySessionId,i.scroll,i.sessionsById,i.sessionsFlat]),r=c.useMemo(()=>Fe(o,{width:i.contentWidth,allowWideColumns:e}),[e,o,i.contentWidth]),a=c.useMemo(()=>{const d=i.activeSessionId&&i.historyBySessionId?.get(i.activeSessionId)||null,f=new Map;for(const h of d?.events||[]){if(h?.eventType!=="session.turn_completed")continue;const m=Number(h?.data?.turnIndex??h?.data?.iteration);Number.isFinite(m)&&f.set(m,h)}return f},[i.activeSessionId,i.historyBySessionId]),l=c.useCallback((d,f)=>c.createElement(Dd,{lines:d,theme:f,completionByTurn:a}),[a]);if(i.inspectorTab==="files"&&!r.disabled)return c.createElement(jd,{controller:t,focused:i.focused,mobile:e});const p=[];if(i.inspectorTab==="logs")p.push(c.createElement("button",{key:"tail",type:"button",className:"ps-mini-button",onClick:()=>t.handleCommand(b.TOGGLE_LOG_TAIL).catch(()=>{})},i.logsTailing?"Stop Tail":"Tail")),p.push(c.createElement("button",{key:"filter",type:"button",className:"ps-mini-button",onClick:()=>t.handleCommand(b.OPEN_LOG_FILTER).catch(()=>{})},"Filter"));else if(i.inspectorTab==="history")p.push(c.createElement("button",{key:"refresh",type:"button",className:"ps-mini-button",onClick:()=>t.handleCommand(b.REFRESH_EXECUTION_HISTORY).catch(()=>{})},"Refresh")),p.push(c.createElement("button",{key:"save",type:"button",className:"ps-mini-button",onClick:()=>t.handleCommand(b.EXPORT_EXECUTION_HISTORY).catch(()=>{})},"Artifact"));else if(i.inspectorTab==="stats")for(const d of["session","fleet","users"])p.push(c.createElement("button",{key:`stats-view:${d}`,type:"button",className:`ps-mini-button${i.statsViewMode===d?" is-active":""}`,onClick:()=>t.setStatsViewMode(d)},d.replace(/^./u,f=>f.toUpperCase())));const u=n?p.concat(n):p;return c.createElement(Xt,{controller:t,title:r.title,color:"magenta",focused:i.focused,actions:u,topContent:c.createElement(zo,{activeTab:r.activeTab,controller:t}),stickyLines:r.stickyLines||[],lines:r.lines,renderBody:r.activeTab==="sequence"?l:null,scrollOffset:i.scroll,scrollMode:r.activeTab==="sequence"||r.activeTab==="logs"&&i.followBottom?"bottom":"top",stickyBottom:r.activeTab==="logs",paneKey:"inspector",className:r.activeTab==="history"||r.activeTab==="logs"?"is-wrapped":"is-preserve",panelClassName:`${r.activeTab==="sequence"?"has-preserved-sticky":""}${s?` ${s}`:""}`.trim()})}function Ls({controller:t,panelClassName:e="",extraActions:s=null}){const n=H(t,r=>{const a=r.sessions.activeSessionId,l=Qt(r),p=Math.max(3,l.activityPaneHeight-2);return{activeSessionId:a,activeSession:a&&r.sessions.byId[a]||null,activeHistory:a&&r.history.bySessionId.get(a)||null,focused:r.ui.focusRegion==="activity",scroll:r.ui.scroll.activity,followBottom:r.ui.followBottom?.activity!==!1,maxLines:p}},Ie),i=c.useMemo(()=>({sessions:{activeSessionId:n.activeSessionId,byId:n.activeSessionId&&n.activeSession?{[n.activeSessionId]:n.activeSession}:{}},history:{bySessionId:n.activeSessionId&&n.activeHistory?new Map([[n.activeSessionId,n.activeHistory]]):new Map}}),[n.activeHistory,n.activeSession,n.activeSessionId]),o=c.useMemo(()=>on(i,n.maxLines),[i,n.maxLines]);return c.createElement(Xt,{controller:t,title:o.title,color:"gray",focused:n.focused,actions:s,lines:o.lines,scrollOffset:n.scroll,scrollMode:n.followBottom?"bottom":"top",stickyBottom:!0,paneKey:"activity",className:"is-wrapped",panelClassName:e})}const $s=[{id:"sessions",label:"Sessions",side:"left"},{id:"inspector",label:"Inspector",side:"right"},{id:"activity",label:"Activity",side:"right"}];function Ud({controller:t,pane:e,onClose:s,mobile:n=!1}){if(!e)return null;let i=null;e==="sessions"?i=c.createElement(pn,{controller:t,panelClassName:"ps-chat-focus-pane",structuredRows:n,actions:c.createElement("button",{type:"button",className:"ps-mini-button",onClick:s},"Close")}):e==="inspector"?i=c.createElement(rt,{controller:t,mobile:!1,panelClassName:"ps-chat-focus-pane",extraActions:c.createElement("button",{type:"button",className:"ps-mini-button",onClick:s},"Close")}):e==="activity"&&(i=c.createElement(Ls,{controller:t,panelClassName:"ps-chat-focus-pane",extraActions:c.createElement("button",{type:"button",className:"ps-mini-button",onClick:s},"Close")}));const o=$s.find(r=>r.id===e);return c.createElement("div",{className:`ps-chat-focus-overlay${o?.side==="left"?" is-left":" is-right"}`},i)}function Wd({controller:t,openPane:e,onTogglePane:s,onExitFocus:n,mobile:i=!1}){const o=H(t,a=>a.ui.focusRegion),r=i?c.createElement("div",{className:"ps-chat-focus-rail"},c.createElement("button",{type:"button",className:"ps-mini-button ps-chat-focus-button",onClick:n},"Exit Focus"),c.createElement("button",{type:"button",className:`ps-mini-button ps-chat-focus-button${e==="sessions"?" is-active":""}`,onClick:()=>s("sessions")},"Sessions")):c.createElement("div",{className:"ps-chat-focus-rail"},$s.map(a=>c.createElement("button",{key:a.id,type:"button",className:`ps-mini-button ps-chat-focus-button${e===a.id?" is-active":""}`,"aria-pressed":e===a.id?"true":"false",onClick:()=>s(a.id)},a.label)),c.createElement("div",{className:"ps-chat-focus-status"},e?`Focused: ${$s.find(a=>a.id===e)?.label||e}`:`Focused: ${o==="prompt"?"Prompt":"Chat"}`));return c.createElement("div",{className:"ps-chat-focus-shell"},r,c.createElement("div",{className:"ps-chat-focus-body"},c.createElement(hn,{controller:t,mobile:i,fullWidth:!0}),c.createElement(Ud,{controller:t,pane:e,onClose:()=>s(e),mobile:i})))}function Vd({controller:t,mobile:e,active:s=!0,onAfterSend:n=null}){const i=H(t,g=>{const I=g.sessions.activeSessionId,y=I&&g.sessions.byId[I]||null,x=I&&g.outbox?.bySessionId?.[I]?g.outbox.bySessionId[I]:[];return{value:g.ui.prompt,cursor:g.ui.promptCursor,focused:g.ui.focusRegion==="prompt",modalOpen:!!g.ui.modal,answerMode:!!y?.pendingQuestion?.question,canStopTurn:qa(y),hasOutbox:x.length>0,hasPendingOutbox:x.some(E=>E?.phase==="pending"),pendingCount:x.filter(E=>E?.phase==="pending").length,editingPending:g.ui.promptEdit?.sessionId===I,selectedOutboxPhase:g.ui.promptEdit?.sessionId===I&&g.ui.promptEdit?.phase||null}},Ie),o=c.useRef(null);c.useEffect(()=>{const g=o.current;if(!(!s||i.modalOpen||!i.focused||!g)){if(document.activeElement!==g)try{g.focus({preventScroll:!0})}catch{g.focus()}g.setSelectionRange(i.cursor,i.cursor)}},[s,i.cursor,i.focused,i.modalOpen]);const r=c.useCallback(()=>{t.handleCommand(b.SEND_PROMPT).catch(()=>{}).finally(()=>{n?.()})},[t,n]),[a,l]=c.useState(!1),p=c.useCallback(()=>{l(!0),t.handleCommand(b.STOP_TURN).catch(()=>{}).finally(()=>l(!1))},[t]),u=c.useCallback(()=>{if(t.getState().ui.promptEdit){typeof t.cancelSelectedOutboxPrompt=="function"?t.cancelSelectedOutboxPrompt().catch(()=>{}):t.cancelSelectedPendingPrompt();return}typeof t.cancelLatestQueuedOutbox=="function"&&t.cancelLatestQueuedOutbox().catch(()=>{})},[t]),d=i.editingPending||i.hasPendingOutbox&&!i.value.trim()?"⇪":i.hasOutbox?"+":"❯",f=i.selectedOutboxPhase==="queued",h=i.selectedOutboxPhase==="cancelling",m=f||h;return c.createElement("div",{className:`ps-prompt-shell${e?" is-mobile":""}`},c.createElement("label",{className:"ps-prompt-label"},i.answerMode?"answer":h?"cancelling":f?"queued":i.editingPending?"pending":"you"),c.createElement("textarea",{ref:o,className:"ps-prompt-input",rows:e?2:Math.max(2,ze(i.value)),value:i.value,readOnly:m,placeholder:i.answerMode?"Type an answer and press Enter":i.editingPending?h?"Cancellation requested":f?"Queued message selected":"Edit the pending message, then send or cancel it":i.hasOutbox?"Type a message and press Enter to queue it behind the pending batch":"Type a message and press Enter",enterKeyHint:"send",onFocus:()=>t.setFocus("prompt"),onSelect:g=>t.setPromptCursor(g.currentTarget.selectionStart||0),onChange:g=>t.setPrompt(g.currentTarget.value,g.currentTarget.selectionStart||g.currentTarget.value.length),onKeyDown:g=>{if(g.key==="Tab"&&!g.shiftKey&&t.acceptPromptReferenceAutocomplete()){g.preventDefault();return}if(g.key==="ArrowUp"&&!g.shiftKey&&!g.metaKey&&!g.altKey){g.preventDefault(),t.movePromptCursorVertical(-1);return}if(g.key==="ArrowDown"&&!g.shiftKey&&!g.metaKey&&!g.altKey){g.preventDefault(),t.movePromptCursorVertical(1);return}if(g.key==="Escape"&&i.editingPending){if(g.preventDefault(),m){t.exitPendingPromptEdit({restoreDraft:!0});return}u();return}g.key==="Enter"&&!g.shiftKey&&!g.metaKey&&!e&&(g.preventDefault(),r())}}),c.createElement("div",{className:"ps-prompt-actions"},i.editingPending&&!h?c.createElement("button",{type:"button",className:"ps-mini-button",title:f?"Delete selected queued prompt":"Cancel selected pending prompt","aria-label":f?"Delete selected queued prompt":"Cancel selected pending prompt",onClick:u},f?"Delete":"Cancel"):null,i.canStopTurn||a?c.createElement("button",{type:"button",className:`ps-stop-button${a?" is-stopping":""}`,title:"Stop the current turn (the session stays alive and returns to idle)","aria-label":"Stop the current turn",disabled:a,onClick:p},"■"):null,c.createElement("button",{type:"button",className:`ps-send-button${e?" is-inline":""}`,title:i.editingPending||i.hasPendingOutbox&&!i.value.trim()?"Send all queued prompts":i.hasOutbox?"Queue prompt behind the pending batch":"Send prompt","aria-label":i.editingPending||i.hasPendingOutbox&&!i.value.trim()?"Send queued prompts":i.hasOutbox?"Queue prompt":"Send prompt",onClick:r},d)))}function qd({controller:t,mobile:e,chatFocusMode:s=!1,onToggleChatFocus:n=null,chatFocusDisabled:i=!1}){const o=H(t,u=>!!u.admin?.visible),r=H(t,u=>({mode:u.ui.chatViewMode||"transcript",activeSessionIsGroup:!!(u.sessions.activeSessionId&&u.sessions.byId[u.sessions.activeSessionId]?.isGroup),hasActiveSession:!!(u.sessions.activeSessionId&&u.sessions.byId[u.sessions.activeSessionId])}),Ie),a=!r.hasActiveSession||r.activeSessionIsGroup,l=[{key:"new",label:"New",onClick:()=>t.handleCommand(b.NEW_SESSION).catch(()=>{})},{key:"model",label:e?"Model":"New + Model",onClick:()=>t.handleCommand(b.OPEN_MODEL_PICKER).catch(()=>{})},{key:"switch-model",label:e?"Switch":"Switch Model",onClick:()=>t.openSwitchModelPicker().catch(u=>{t.dispatch({type:"ui/status",text:u?.message||String(u)||"Failed to switch model"})}),disabled:a,title:a?"Select a session to switch its model":"Switch the selected session model at the next turn boundary"},{key:"filter",label:"Filter",onClick:()=>t.handleCommand(b.OPEN_SESSION_FILTER).catch(()=>{})},{key:"theme",label:"Theme",onClick:()=>t.handleCommand(b.OPEN_THEME_PICKER).catch(()=>{})},{key:"summary",label:r.mode==="summary"?"Chat":"Summary",onClick:()=>t.setChatViewMode(r.mode==="summary"?"transcript":"summary"),disabled:r.activeSessionIsGroup,title:r.activeSessionIsGroup?"Groups show group details":"Toggle Chat / Summary view",active:r.mode==="summary"},...n?[{key:"focus",label:e?s?"Exit Focus":"Focus":s?"Exit Focus":"Chat Focus",onClick:n,disabled:i,active:s}]:[],{key:"admin",label:o?"Close Admin":"Admin",onClick:()=>t.handleCommand(o?b.CLOSE_ADMIN_CONSOLE:b.OPEN_ADMIN_CONSOLE).catch(()=>{}),active:o}],p=u=>c.createElement("button",{key:u.key,type:"button",className:`ps-toolbar-button${u.active?" is-active":""}`,onClick:u.onClick,disabled:!!u.disabled,title:u.title},u.label);if(e){const u=l.slice(0,4),d=l.slice(4);return c.createElement("div",{className:"ps-toolbar is-mobile"},c.createElement("div",{className:"ps-toolbar-row ps-toolbar-row-primary"},u.map(p)),c.createElement("div",{className:"ps-toolbar-row ps-toolbar-row-secondary"},c.createElement("div",{className:"ps-toolbar-row-actions"},d.map(p))))}return c.createElement("div",{className:"ps-toolbar"},c.createElement("div",{className:"ps-toolbar-actions"},l.map(p)))}function Kd({controller:t,paneAdjust:e=0}){const s=c.useRef(null),[n,i]=c.useState(!1);return c.useEffect(()=>{if(!n)return;const o=()=>{s.current=null,i(!1),document.body.classList.remove("is-resizing-pane-x")},r=a=>{const l=s.current;if(!l)return;const p=Math.round((a.clientX-l.startX)/Bo),u=p-l.appliedCells;u&&(t.adjustPaneSplit(u),l.appliedCells=p)};return window.addEventListener("pointermove",r),window.addEventListener("pointerup",o),window.addEventListener("pointercancel",o),()=>{window.removeEventListener("pointermove",r),window.removeEventListener("pointerup",o),window.removeEventListener("pointercancel",o),document.body.classList.remove("is-resizing-pane-x")}},[t,n]),c.createElement("button",{type:"button",className:`ps-column-resizer${n?" is-dragging":""}`,title:"Drag to resize the inspector column. Double-click to reset.","aria-label":"Resize inspector column",onPointerDown:o=>{o.button===0&&(o.preventDefault(),s.current={startX:o.clientX,appliedCells:0},i(!0),document.body.classList.add("is-resizing-pane-x"))},onDoubleClick:()=>{e&&t.adjustPaneSplit(-e)},onKeyDown:o=>{if(o.key==="ArrowLeft"){o.preventDefault(),t.handleCommand(b.GROW_RIGHT_PANE).catch(()=>{});return}o.key==="ArrowRight"&&(o.preventDefault(),t.handleCommand(b.GROW_LEFT_PANE).catch(()=>{}))}},c.createElement("span",{className:"ps-column-resizer-handle","aria-hidden":"true"},c.createElement("span",{className:"ps-column-resizer-dot"}),c.createElement("span",{className:"ps-column-resizer-dot"}),c.createElement("span",{className:"ps-column-resizer-dot"})))}function zd({controller:t,portalSessionColumnAdjust:e=0}){const s=c.useRef(null),[n,i]=c.useState(!1);return c.useEffect(()=>{if(!n)return;const o=()=>{s.current=null,i(!1),document.body.classList.remove("is-resizing-pane-x")},r=a=>{const l=s.current;if(!l)return;const p=Rs(l.startAdjust+(a.clientX-l.startX),l.minAdjust,l.maxAdjust);t.dispatch({type:"ui/portalSessionColumnAdjust",portalSessionColumnAdjust:p})};return window.addEventListener("pointermove",r),window.addEventListener("pointerup",o),window.addEventListener("pointercancel",o),()=>{window.removeEventListener("pointermove",r),window.removeEventListener("pointerup",o),window.removeEventListener("pointercancel",o),document.body.classList.remove("is-resizing-pane-x")}},[t,n]),c.createElement("button",{type:"button",className:`ps-column-resizer${n?" is-dragging":""}`,title:"Drag to resize the sessions and chat columns. Double-click to reset.","aria-label":"Resize sessions and chat columns",onPointerDown:o=>{if(o.button!==0)return;o.preventDefault();const r=o.currentTarget.closest(".ps-workspace-main-grid"),a=Fs(r?.getBoundingClientRect?.().width);s.current={startX:o.clientX,startAdjust:Number(e)||0,minAdjust:a.minAdjust,maxAdjust:a.maxAdjust},i(!0),document.body.classList.add("is-resizing-pane-x")},onDoubleClick:()=>{t.dispatch({type:"ui/portalSessionColumnAdjust",portalSessionColumnAdjust:0})},onKeyDown:o=>{const r=o.currentTarget.closest(".ps-workspace-main-grid"),a=Fs(r?.getBoundingClientRect?.().width),l=p=>{const u=Rs((Number(e)||0)+p,a.minAdjust,a.maxAdjust);t.dispatch({type:"ui/portalSessionColumnAdjust",portalSessionColumnAdjust:u})};if(o.key==="ArrowLeft"){o.preventDefault(),l(-24);return}o.key==="ArrowRight"&&(o.preventDefault(),l(24))}},c.createElement("span",{className:"ps-column-resizer-handle","aria-hidden":"true"},c.createElement("span",{className:"ps-column-resizer-dot"}),c.createElement("span",{className:"ps-column-resizer-dot"}),c.createElement("span",{className:"ps-column-resizer-dot"})))}function Yd({controller:t,activityPaneAdjust:e=0}){const s=c.useRef(null),[n,i]=c.useState(!1);return c.useEffect(()=>{if(!n)return;const o=()=>{s.current=null,i(!1),document.body.classList.remove("is-resizing-pane-y")},r=a=>{const l=s.current;if(!l)return;const p=Math.round((a.clientY-l.startY)/Do),u=p-l.appliedCells;u&&(t.adjustActivityPaneSplit(-u),l.appliedCells=p)};return window.addEventListener("pointermove",r),window.addEventListener("pointerup",o),window.addEventListener("pointercancel",o),()=>{window.removeEventListener("pointermove",r),window.removeEventListener("pointerup",o),window.removeEventListener("pointercancel",o),document.body.classList.remove("is-resizing-pane-y")}},[t,n]),c.createElement("button",{type:"button",className:`ps-row-resizer${n?" is-dragging":""}`,title:"Drag to resize the activity pane. Double-click to reset.","aria-label":"Resize activity pane",onPointerDown:o=>{o.button===0&&(o.preventDefault(),s.current={startY:o.clientY,appliedCells:0},i(!0),document.body.classList.add("is-resizing-pane-y"))},onDoubleClick:()=>{e&&t.adjustActivityPaneSplit(-e)},onKeyDown:o=>{if(o.key==="ArrowUp"){o.preventDefault(),t.adjustActivityPaneSplit(1);return}o.key==="ArrowDown"&&(o.preventDefault(),t.adjustActivityPaneSplit(-1))}},c.createElement("span",{className:"ps-row-resizer-handle","aria-hidden":"true"},c.createElement("span",{className:"ps-row-resizer-dot"}),c.createElement("span",{className:"ps-row-resizer-dot"}),c.createElement("span",{className:"ps-row-resizer-dot"})))}function Qd({activePane:t,setActivePane:e,controller:s}){const n=[{id:"workspace",label:"Main",focus:"chat"},{id:"inspector",label:"Inspector",focus:"inspector"},{id:"activity",label:"Activity",focus:"activity"}];return c.createElement("div",{className:"ps-mobile-nav"},n.map(i=>c.createElement("button",{key:i.id,type:"button",className:`ps-mobile-nav-button${t===i.id?" is-active":""}`,onClick:()=>{e(i.id),s.setFocus(i.focus)}},i.label)))}function Xd({controller:t}){const e=H(t,f=>f.ui.themeId),s=Ae(e),n=H(t,f=>({rawModal:f.ui.modal,themePicker:Tc(f),modelPicker:tc(f),reasoningEffortPicker:nc(f),sessionAgentPicker:sc(f),sessionGroupPicker:ic(f),sessionGroupName:rc(f),artifactPicker:dc(f),logFilter:cc(f),filesFilter:uc(f),historyFormat:Ac(f),renameSession:oc(f),sessionOwnerFilter:lc(f),artifactUpload:ac(f),confirm:kc(f),logsFilter:f.logs.filter,filesFilterState:f.files.filter,historyFormatState:f.executionHistory?.format||"pretty"}),Ie),i=n.rawModal,o=c.useRef(null),r=c.useRef(null),a=c.useRef(null);if(c.useEffect(()=>{if(i?.type!=="renameSession"||!n.renameSession)return;const f=o.current;if(f){if(document.activeElement!==f)try{f.focus({preventScroll:!0})}catch{f.focus()}f.setSelectionRange(n.renameSession.cursorIndex,n.renameSession.cursorIndex)}},[i?.type,n.renameSession?.cursorIndex,n.renameSession?.value]),c.useEffect(()=>{if(i?.type!=="sessionGroupName"||!n.sessionGroupName)return;const f=r.current;if(f){if(document.activeElement!==f)try{f.focus({preventScroll:!0})}catch{f.focus()}f.setSelectionRange(n.sessionGroupName.cursorIndex,n.sessionGroupName.cursorIndex)}},[i?.type,n.sessionGroupName?.cursorIndex,n.sessionGroupName?.value]),c.useEffect(()=>{if(!i||!["themePicker","modelPicker","reasoningEffortPicker","sessionAgentPicker","sessionGroupPicker","artifactPicker","sessionOwnerFilter","logFilter","filesFilter","historyFormat"].includes(i.type))return;const f=a.current;if(!f)return;const h=f.querySelector(".ps-list-button.is-selected");h&&typeof h.scrollIntoView=="function"&&h.scrollIntoView({block:"nearest"})},[i?.type,i?.selectedIndex,n.themePicker?.selectedRowIndex,n.modelPicker?.selectedRowIndex,n.reasoningEffortPicker?.selectedRowIndex,n.sessionAgentPicker?.selectedRowIndex,n.sessionGroupPicker?.selectedRowIndex,n.artifactPicker?.selectedRowIndex,n.sessionOwnerFilter?.selectedRowIndex,n.logFilter?.selectedRowIndex,n.filesFilter?.selectedRowIndex,n.historyFormat?.selectedRowIndex]),!i)return null;const l=()=>t.handleCommand(b.CLOSE_MODAL).catch(()=>{}),p=(f,h="Apply")=>{const m=Array.isArray(f.rows)?f.rows:[],g=Array.isArray(f.rowItemIndexes)?f.rowItemIndexes:null,I=i.type==="modelPicker"||i.type==="reasoningEffortPicker"||i.type==="sessionAgentPicker",y=g&&g.length===m.length?m.map((x,E)=>{const v=g[E],T=Array.isArray(x)?x:le([x])[0]?.runs||[{text:x?.text||"",color:x?.color}];if(v==null||v<0)return c.createElement("div",{key:`row:${E}`,className:"ps-line ps-modal-list-heading-line"},c.createElement(oe,{runs:T,theme:s}));const O=i.items?.[v];return c.createElement("button",{key:O?.id||`row:${E}`,type:"button",className:`ps-list-button ps-modal-list-button${v===i.selectedIndex?" is-selected":""}${I?" is-hanging":""}`,onClick:()=>t.dispatch({type:"ui/modalSelection",index:v})},c.createElement("div",{className:"ps-line ps-modal-list-line"},c.createElement(oe,{runs:T,theme:s})))}):(i.items||[]).map((x,E)=>c.createElement("button",{key:x.id||E,type:"button",className:`ps-list-button ps-modal-list-button${E===i.selectedIndex?" is-selected":""}${I?" is-hanging":""}`,onClick:()=>t.dispatch({type:"ui/modalSelection",index:E})},c.createElement("div",{className:"ps-line ps-modal-list-line"},c.createElement(oe,{runs:Array.isArray(m?.[E])?m[E]:le([m?.[E]])[0]?.runs||[{text:m?.[E]?.text||"",color:m?.[E]?.color}],theme:s}))));return c.createElement("div",{className:"ps-modal-backdrop",onClick:l},c.createElement("div",{className:`ps-modal${i.type==="themePicker"?" is-theme-picker":""}`,onClick:x=>x.stopPropagation()},c.createElement("div",{className:"ps-modal-header"},c.createElement("div",{className:"ps-modal-title"},f.title),c.createElement("button",{type:"button",className:"ps-modal-close",onClick:l},"Close")),c.createElement("div",{className:"ps-modal-grid"},c.createElement("div",{ref:a,className:"ps-modal-list"},y),c.createElement("div",{className:"ps-modal-details"},c.createElement("div",{className:"ps-modal-details-title"},f.detailsTitle||"Details"),le(f.detailsLines||[]).map((x,E)=>c.createElement(re,{key:`detail:${E}`,line:x,theme:s,className:"ps-modal-detail-line"})))),c.createElement("div",{className:"ps-modal-footer"},c.createElement("button",{type:"button",className:"ps-modal-button",onClick:l},"Cancel"),c.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(b.MODAL_CONFIRM).catch(()=>{})},h))))};if(i.type==="confirm"&&n.confirm){const f=!!i.alert,h=!f&&i.action==="deleteSession";return c.createElement("div",{className:"ps-modal-backdrop",onClick:l},c.createElement("div",{className:"ps-modal is-narrow",onClick:m=>m.stopPropagation()},c.createElement("div",{className:"ps-modal-header"},c.createElement("div",{className:"ps-modal-title"},n.confirm.title),c.createElement("button",{type:"button",className:"ps-modal-close",onClick:l},"Close")),c.createElement("div",{className:"ps-modal-body",style:{padding:"16px 20px"}},c.createElement("p",{style:{color:"#94a3b8",margin:0}},n.confirm.message)),c.createElement("div",{className:"ps-modal-footer"},f?null:c.createElement("button",{type:"button",className:"ps-modal-button",onClick:l},"Cancel"),c.createElement("button",{type:"button",className:`ps-modal-button ${h?"is-danger":"is-primary"}`,onClick:()=>t.handleCommand(b.MODAL_CONFIRM).catch(()=>{})},n.confirm.confirmLabel))))}if(i.type==="themePicker"&&n.themePicker)return p(n.themePicker,"Apply Theme");const u=i.sessionOptions?.mode==="switchModel"?"Switch Model":"Create Session";if(i.type==="modelPicker"&&n.modelPicker)return p(n.modelPicker,u);if(i.type==="reasoningEffortPicker"&&n.reasoningEffortPicker)return p(n.reasoningEffortPicker,u);if(i.type==="sessionAgentPicker"&&n.sessionAgentPicker)return p(n.sessionAgentPicker,"Create Session");if(i.type==="sessionGroupPicker"&&n.sessionGroupPicker)return p(n.sessionGroupPicker,"Move");if(i.type==="artifactPicker"&&n.artifactPicker)return p(n.artifactPicker,n.artifactPicker.confirmLabel||"Open / Download");if(i.type==="sessionOwnerFilter"&&n.sessionOwnerFilter){const f=n.sessionOwnerFilter,h=Array.isArray(f.rows)?f.rows:[];return c.createElement("div",{className:"ps-modal-backdrop",onClick:l},c.createElement("div",{className:"ps-modal",onClick:m=>m.stopPropagation()},c.createElement("div",{className:"ps-modal-header"},c.createElement("div",{className:"ps-modal-title"},f.title),c.createElement("button",{type:"button",className:"ps-modal-close",onClick:l},"Close")),c.createElement("div",{className:"ps-modal-grid"},c.createElement("div",{ref:a,className:"ps-modal-list"},(i.items||[]).map((m,g)=>c.createElement("button",{key:m.id||g,type:"button",className:`ps-list-button ps-modal-list-button${g===i.selectedIndex?" is-selected":""}`,onClick:()=>t.toggleSessionOwnerFilter(g)},c.createElement("div",{className:"ps-line ps-modal-list-line"},c.createElement(oe,{runs:Array.isArray(h?.[g])?h[g]:le([h?.[g]])[0]?.runs||[{text:h?.[g]?.text||"",color:h?.[g]?.color}],theme:s}))))),c.createElement("div",{className:"ps-modal-details"},c.createElement("div",{className:"ps-modal-details-title"},f.detailsTitle||"Details"),le(f.detailsLines||[]).map((m,g)=>c.createElement(re,{key:`detail:${g}`,line:m,theme:s,className:"ps-modal-detail-line"})))),c.createElement("div",{className:"ps-modal-footer"},c.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:l},"Done"))))}if(i.type==="renameSession"&&n.renameSession)return c.createElement("div",{className:"ps-modal-backdrop",onClick:l},c.createElement("div",{className:"ps-modal is-narrow",onClick:f=>f.stopPropagation()},c.createElement("div",{className:"ps-modal-header"},c.createElement("div",{className:"ps-modal-title"},n.renameSession.title),c.createElement("button",{type:"button",className:"ps-modal-close",onClick:l},"Close")),c.createElement("input",{ref:o,className:"ps-modal-input",value:n.renameSession.value,placeholder:n.renameSession.placeholder,onChange:f=>t.setRenameSessionValue(f.currentTarget.value,f.currentTarget.selectionStart??f.currentTarget.value.length),onKeyDown:f=>{f.key==="Enter"&&(f.preventDefault(),t.handleCommand(b.MODAL_CONFIRM).catch(()=>{}))},autoFocus:!0}),c.createElement("div",{className:"ps-modal-details"},le(n.renameSession.helpLines||[]).map((f,h)=>c.createElement(re,{key:`help:${h}`,line:f,theme:s,className:"ps-modal-detail-line"}))),c.createElement("div",{className:"ps-modal-footer"},c.createElement("button",{type:"button",className:"ps-modal-button",onClick:l},"Cancel"),c.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(b.MODAL_CONFIRM).catch(()=>{})},"Save"))));if(i.type==="sessionGroupName"&&n.sessionGroupName)return c.createElement("div",{className:"ps-modal-backdrop",onClick:l},c.createElement("div",{className:"ps-modal is-narrow",onClick:f=>f.stopPropagation()},c.createElement("div",{className:"ps-modal-header"},c.createElement("div",{className:"ps-modal-title"},n.sessionGroupName.title),c.createElement("button",{type:"button",className:"ps-modal-close",onClick:l},"Close")),c.createElement("input",{ref:r,className:"ps-modal-input",value:n.sessionGroupName.value,placeholder:n.sessionGroupName.placeholder,onChange:f=>t.setSessionGroupNameValue(f.currentTarget.value,f.currentTarget.selectionStart??f.currentTarget.value.length),onKeyDown:f=>{f.key==="Enter"&&(f.preventDefault(),t.handleCommand(b.MODAL_CONFIRM).catch(()=>{}))},autoFocus:!0}),c.createElement("div",{className:"ps-modal-details"},le(n.sessionGroupName.helpLines||[]).map((f,h)=>c.createElement(re,{key:`help:${h}`,line:f,theme:s,className:"ps-modal-detail-line"}))),c.createElement("div",{className:"ps-modal-footer"},c.createElement("button",{type:"button",className:"ps-modal-button",onClick:l},"Cancel"),c.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(b.MODAL_CONFIRM).catch(()=>{})},"Create and Move"))));if(i.type==="terminatePicker"){const f=Number(i.bulkCount)>1,h=!!i.systemRestart,m=String(i.sessionTitle||"").trim()||"this session",g=Number(i.bulkCount)||0,I=f?`What should happen to the ${g} selected sessions? Choose an action; you'll be asked to confirm.`:h?`How should "${m}" be restarted? Choose a disposition; you'll be asked to confirm.`:`What should happen to "${m}"? Choose an action; you'll be asked to confirm.`,y=x=>()=>{t.pickTerminateAction(x).catch(()=>{})};return c.createElement("div",{className:"ps-modal-backdrop",onClick:l},c.createElement("div",{className:"ps-modal is-narrow",onClick:x=>x.stopPropagation()},c.createElement("div",{className:"ps-modal-header"},c.createElement("div",{className:"ps-modal-title"},i.title||"Terminate session"),c.createElement("button",{type:"button",className:"ps-modal-close",onClick:l},"Close")),c.createElement("div",{className:"ps-modal-body",style:{padding:"12px 16px 4px"}},c.createElement("p",{style:{color:"#94a3b8",margin:0}},I)),c.createElement("div",{className:"ps-modal-body",style:{padding:"10px 16px 16px",display:"flex",flexDirection:"column",gap:8}},c.createElement("button",{type:"button",className:"ps-modal-button is-primary",style:{width:"100%",justifyContent:"flex-start"},onClick:y("complete")},f?`Mark ${g} Completed`:h?"Complete & Restart":"Mark Completed"),c.createElement("button",{type:"button",className:"ps-modal-button",style:{width:"100%",justifyContent:"flex-start"},onClick:y("cancel")},f?`Cancel ${g} Sessions`:h?"Terminate & Restart":"Cancel Session"),c.createElement("button",{type:"button",className:"ps-modal-button is-danger",style:{width:"100%",justifyContent:"flex-start"},onClick:y("delete")},f?`Hard Delete ${g} Sessions`:h?"Hard Delete & Restart":"Delete Session")),c.createElement("div",{className:"ps-modal-footer"},c.createElement("button",{type:"button",className:"ps-modal-button",onClick:l},"Close"))))}if(i.type==="artifactUpload"&&n.artifactUpload)return c.createElement("div",{className:"ps-modal-backdrop",onClick:l},c.createElement("div",{className:"ps-modal is-narrow",onClick:f=>f.stopPropagation()},c.createElement("div",{className:"ps-modal-header"},c.createElement("div",{className:"ps-modal-title"},n.artifactUpload.title),c.createElement("button",{type:"button",className:"ps-modal-close",onClick:l},"Close")),c.createElement("input",{className:"ps-modal-input",value:n.artifactUpload.value,placeholder:n.artifactUpload.placeholder,onChange:f=>t.setArtifactUploadValue(f.currentTarget.value,f.currentTarget.selectionStart||f.currentTarget.value.length),autoFocus:!0}),c.createElement("div",{className:"ps-modal-details"},le(n.artifactUpload.helpLines||[]).map((f,h)=>c.createElement(re,{key:`help:${h}`,line:f,theme:s,className:"ps-modal-detail-line"}))),c.createElement("div",{className:"ps-modal-footer"},c.createElement("button",{type:"button",className:"ps-modal-button",onClick:l},"Cancel"),c.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(b.MODAL_CONFIRM).catch(()=>{})},"Attach"))));const d=i.type==="logFilter"?n.logFilter:i.type==="filesFilter"?n.filesFilter:i.type==="historyFormat"?n.historyFormat:null;return d?c.createElement("div",{className:"ps-modal-backdrop",onClick:l},c.createElement("div",{className:"ps-modal is-wide",onClick:f=>f.stopPropagation()},c.createElement("div",{className:"ps-modal-header"},c.createElement("div",{className:"ps-modal-title"},d.title),c.createElement("button",{type:"button",className:"ps-modal-close",onClick:l},"Close")),c.createElement("div",{className:"ps-filter-grid"},(i.items||[]).map((f,h)=>{const m=i.type==="filesFilter"?n.filesFilterState?.[f.id]||f.options?.[0]?.id:i.type==="historyFormat"?n.historyFormatState:n.logsFilter?.[f.id]||f.options?.[0]?.id;return c.createElement("div",{key:f.id||h,className:"ps-filter-column"},c.createElement("div",{className:"ps-filter-title"},f.label),(f.options||[]).map(g=>c.createElement("button",{key:g.id,type:"button",className:`ps-filter-option${g.id===m?" is-selected":""}`,onClick:()=>{t.dispatch({type:"ui/modalSelection",index:h}),i.type==="historyFormat"?t.dispatch({type:"executionHistory/format",format:g.id}):i.type==="filesFilter"?(t.dispatch({type:"files/filter",filter:{[f.id]:g.id}}),t.ensureFilesForScope(g.id).catch(()=>{})):t.dispatch({type:"logs/filter",filter:{[f.id]:g.id}})}},g.label)))})),c.createElement("div",{className:"ps-modal-footer"},c.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:l},"Done")))):null}function Jd(t,e){c.useEffect(()=>{const s=n=>{const i=n.target,o=i instanceof HTMLElement&&(i.tagName==="TEXTAREA"||i.tagName==="INPUT"||i.isContentEditable),r=t.getState().ui.modal,a=fn(t),l=t.getState().ui.inspectorTab,p=t.getState().ui.focusRegion,u=!n.metaKey&&!n.ctrlKey&&!n.altKey,d=!n.metaKey&&!n.ctrlKey&&!n.altKey&&n.key==="T"&&n.shiftKey,f=!n.metaKey&&!n.ctrlKey&&!n.altKey&&n.key==="N"&&n.shiftKey,h=m=>{const g=Ju(a,l,m);t.selectInspectorTab(g).catch(()=>{})};if(!o&&d){n.preventDefault(),t.handleCommand(b.OPEN_THEME_PICKER).catch(()=>{});return}if(!o&&f){n.preventDefault(),t.handleCommand(b.OPEN_MODEL_PICKER).catch(()=>{});return}if(r&&!o){if(n.key==="Escape"||r.type==="confirm"&&n.key==="n"){n.preventDefault(),t.handleCommand(b.CLOSE_MODAL).catch(()=>{});return}if(n.key==="Enter"||r.type==="confirm"&&n.key==="y"){n.preventDefault(),t.handleCommand(b.MODAL_CONFIRM).catch(()=>{});return}if(n.key==="Tab"&&n.shiftKey){n.preventDefault(),t.handleCommand(b.MODAL_PANE_PREV).catch(()=>{});return}if(n.key==="Tab"){n.preventDefault(),t.handleCommand(b.MODAL_PANE_NEXT).catch(()=>{});return}if(n.key==="ArrowUp"||n.key==="k"){n.preventDefault(),t.handleCommand(b.MODAL_PREV).catch(()=>{});return}(n.key==="ArrowDown"||n.key==="j")&&(n.preventDefault(),t.handleCommand(b.MODAL_NEXT).catch(()=>{}));return}if(!o){if(n.key==="r"&&u&&p!=="prompt"){n.preventDefault(),t.handleCommand(b.REFRESH).catch(()=>{});return}if(p==="chat"&&n.key==="s"&&u){n.preventDefault(),t.handleCommand(b.TOGGLE_CHAT_VIEW).catch(()=>{});return}if(n.key==="n"&&u){n.preventDefault(),t.handleCommand(b.NEW_SESSION).catch(()=>{});return}if(p==="inspector"&&l==="files"&&(n.key==="u"&&u||(n.ctrlKey||n.metaKey)&&n.key.toLowerCase()==="a")){n.preventDefault(),t.handleCommand(b.OPEN_ARTIFACT_UPLOAD).catch(()=>{});return}if(p==="inspector"&&l==="files"&&n.key==="a"&&u){n.preventDefault(),t.handleCommand(b.DOWNLOAD_SELECTED_FILE).catch(()=>{});return}if(p==="inspector"&&l==="files"&&n.key==="x"&&u){n.preventDefault(),t.handleCommand(b.DELETE_SELECTED_FILE).catch(()=>{});return}if(p==="inspector"&&l==="files"&&n.key==="o"&&u){n.preventDefault(),t.handleCommand(b.OPEN_SELECTED_FILE).catch(()=>{});return}if(p==="inspector"&&l==="files"&&n.key==="f"&&u){n.preventDefault(),t.handleCommand(b.OPEN_FILES_FILTER).catch(()=>{});return}if(p==="inspector"&&l==="stats"&&n.key==="f"&&u){n.preventDefault(),t.handleCommand(b.TOGGLE_STATS_VIEW).catch(()=>{});return}if(p==="inspector"&&l==="files"&&n.key==="v"&&u){n.preventDefault(),t.handleCommand(b.TOGGLE_FILE_PREVIEW_FULLSCREEN).catch(()=>{});return}if(p==="inspector"&&l==="logs"&&n.key==="t"&&u){n.preventDefault(),t.handleCommand(b.TOGGLE_LOG_TAIL).catch(()=>{});return}if(p==="inspector"&&l==="logs"&&n.key==="f"&&u){n.preventDefault(),t.handleCommand(b.OPEN_LOG_FILTER).catch(()=>{});return}if(p==="inspector"&&l==="history"&&n.key==="f"&&u){n.preventDefault(),t.handleCommand(b.OPEN_HISTORY_FORMAT).catch(()=>{});return}if(p==="inspector"&&l==="history"&&n.key==="r"&&u){n.preventDefault(),t.handleCommand(b.REFRESH_EXECUTION_HISTORY).catch(()=>{});return}if(p==="inspector"&&l==="history"&&n.key==="a"&&u){n.preventDefault(),t.handleCommand(b.EXPORT_EXECUTION_HISTORY).catch(()=>{});return}if(n.key==="a"&&u){n.preventDefault(),t.handleCommand(b.OPEN_ARTIFACT_PICKER).catch(()=>{});return}if(n.key==="p"&&u){n.preventDefault(),t.handleCommand(b.FOCUS_PROMPT).catch(()=>{});return}if(n.key==="c"&&u){n.preventDefault(),t.handleCommand(b.CANCEL_SESSION).catch(()=>{});return}if(n.key==="d"&&u){n.preventDefault(),t.handleCommand(b.DONE_SESSION).catch(()=>{});return}if(n.key==="D"&&n.shiftKey&&!n.metaKey&&!n.ctrlKey&&!n.altKey){n.preventDefault(),t.handleCommand(b.DELETE_SESSION).catch(()=>{});return}if(n.key==="m"&&u&&p==="inspector"){n.preventDefault(),h(1);return}if(n.key==="["&&u){n.preventDefault(),t.handleCommand(b.GROW_LEFT_PANE).catch(()=>{});return}if(n.key==="]"&&u){n.preventDefault(),t.handleCommand(b.GROW_RIGHT_PANE).catch(()=>{});return}if(n.key==="{"&&u){n.preventDefault(),t.handleCommand(b.SHRINK_SESSION_PANE).catch(()=>{});return}if(n.key==="}"&&u){n.preventDefault(),t.handleCommand(b.GROW_SESSION_PANE).catch(()=>{});return}if(p==="inspector"&&n.key==="ArrowLeft"){n.preventDefault(),h(-1);return}if(p==="inspector"&&n.key==="ArrowRight"){n.preventDefault(),h(1);return}if(p==="sessions"&&(n.key==="ArrowUp"||n.key==="k")){n.preventDefault(),t.handleCommand(b.MOVE_SESSION_UP).catch(()=>{});return}if(p==="sessions"&&(n.key==="ArrowDown"||n.key==="j")){n.preventDefault(),t.handleCommand(b.MOVE_SESSION_DOWN).catch(()=>{});return}if(p==="sessions"&&n.ctrlKey&&n.key.toLowerCase()==="g"&&!n.metaKey&&!n.altKey){n.preventDefault(),t.handleCommand(b.OPEN_MOVE_TO_GROUP).catch(()=>{});return}if(p==="sessions"&&(n.key==="PageUp"||n.ctrlKey&&n.key.toLowerCase()==="u")){n.preventDefault(),t.handleCommand(b.PAGE_UP).catch(()=>{});return}if(p==="sessions"&&(n.key==="PageDown"||n.ctrlKey&&n.key.toLowerCase()==="d")){n.preventDefault(),t.handleCommand(b.PAGE_DOWN).catch(()=>{});return}if(p==="sessions"&&n.key==="t"&&u){n.preventDefault(),t.handleCommand(b.OPEN_RENAME_SESSION).catch(()=>{});return}if(!e&&(n.key==="PageUp"||n.ctrlKey&&n.key.toLowerCase()==="u")){n.preventDefault(),t.handleCommand(b.PAGE_UP).catch(()=>{});return}if(!e&&(n.key==="PageDown"||n.ctrlKey&&n.key.toLowerCase()==="d")){n.preventDefault(),t.handleCommand(b.PAGE_DOWN).catch(()=>{});return}if(!e&&n.key==="g"&&u){n.preventDefault(),t.handleCommand(b.SCROLL_TOP).catch(()=>{});return}if(!e&&n.key==="G"&&n.shiftKey&&!n.metaKey&&!n.ctrlKey&&!n.altKey){n.preventDefault(),t.handleCommand(b.SCROLL_BOTTOM).catch(()=>{});return}if(p!=="prompt"&&n.key==="h"&&u){n.preventDefault(),t.handleCommand(b.FOCUS_LEFT).catch(()=>{});return}if(p!=="prompt"&&n.key==="l"&&u){n.preventDefault(),t.handleCommand(b.FOCUS_RIGHT).catch(()=>{});return}if(!e&&(n.key==="ArrowUp"||n.key==="k")){n.preventDefault(),t.handleCommand(b.SCROLL_UP).catch(()=>{});return}if(!e&&(n.key==="ArrowDown"||n.key==="j")){n.preventDefault(),t.handleCommand(b.SCROLL_DOWN).catch(()=>{});return}!e&&n.key==="Escape"&&(n.preventDefault(),t.handleCommand(b.FOCUS_SESSIONS).catch(()=>{}))}};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[t,e])}function Zd(t){if(!t)return"Unknown user";const e=String(t.displayName||"").trim(),s=String(t.email||"").trim();if(e&&s&&e.toLowerCase()!==s.toLowerCase())return`${e} <${s}>`;if(e)return e;if(s)return s;const n=String(t.provider||"").trim(),i=String(t.subject||"").trim();return[n,i].filter(Boolean).join(":")||"user"}function ef({controller:t}){const e=H(t,Ml,Ie),s=c.useRef(null);c.useEffect(()=>{if(e.ghcpKey.editing){const d=window.requestAnimationFrame(()=>{s.current&&s.current.focus()});return()=>window.cancelAnimationFrame(d)}},[e.ghcpKey.editing]);const n=c.useCallback(()=>{t.closeAdminConsole()},[t]),i=c.useCallback(()=>{t.refreshAdminProfile().catch(()=>{})},[t]),o=c.useCallback(()=>{t.beginAdminEditGhcpKey()},[t]),r=c.useCallback(()=>{t.cancelAdminEditGhcpKey()},[t]),a=c.useCallback(()=>{t.clearAdminGhcpKey().catch(()=>{})},[t]),l=c.useCallback(d=>{d.preventDefault(),t.saveAdminGhcpKey().catch(()=>{})},[t]),p=c.useCallback(d=>{t.setAdminGhcpKeyDraft(d.target.value)},[t]),u=Zd(e.principal);return c.createElement("div",{className:"ps-admin-console"},c.createElement("header",{className:"ps-admin-console__header"},c.createElement("h2",null,"Admin Console"),c.createElement("button",{type:"button",className:"ps-mini-button",onClick:n},"Close")),c.createElement("section",{className:"ps-admin-console__identity"},c.createElement("dl",null,c.createElement("dt",null,"Signed in as"),c.createElement("dd",null,u))),e.loadError?c.createElement("div",{className:"ps-admin-console__error",role:"alert"},e.loadError):null,c.createElement("section",{className:"ps-admin-console__section"},c.createElement("h3",null,"GitHub Copilot key"),c.createElement("p",{className:"ps-admin-console__hint"},"Per-user override for the GitHub Copilot model provider token. ","When set, this key is used instead of the worker's env-supplied ","GITHUB_TOKEN for sessions you own. Clearing the key reverts to ","the worker default."),c.createElement("p",{className:`ps-admin-console__status${e.ghcpKey.error?" is-error":""}`},e.ghcpKey.error||e.ghcpKey.statusText),e.ghcpKey.editing?c.createElement("form",{className:"ps-admin-console__form",onSubmit:l},c.createElement("input",{ref:s,type:"password",autoComplete:"off",spellCheck:!1,value:e.ghcpKey.draft,disabled:e.ghcpKey.saving,placeholder:"Paste GitHub Copilot key",onChange:p}),c.createElement("div",{className:"ps-admin-console__actions"},c.createElement("button",{type:"submit",className:"ps-primary-button",disabled:e.ghcpKey.saving},e.ghcpKey.saving?"Saving...":"Save"),c.createElement("button",{type:"button",className:"ps-mini-button",onClick:r,disabled:e.ghcpKey.saving},"Cancel"))):c.createElement("div",{className:"ps-admin-console__actions"},c.createElement("button",{type:"button",className:"ps-primary-button",onClick:o},e.ghcpKey.configured?"Replace key":"Set key"),e.ghcpKey.configured?c.createElement("button",{type:"button",className:"ps-mini-button",onClick:a},"Clear key"):null,c.createElement("button",{type:"button",className:"ps-mini-button",onClick:i},e.loading?"Refreshing...":"Refresh"))))}function sf({transport:t,mode:e="remote",branding:s=null}={}){id();const n=qc(Vc,Pa({mode:e,branding:s}));return new Fu({store:n,transport:t})}function nf({controller:t}){const e=c.useRef(null),s=c.useRef(null),n=Ii(e),i=Ii(s),o=pd(n),[r,a]=c.useState(!1),[l,p]=c.useState(null),u=H(t,A=>({themeId:A.ui.themeId,ownerFilter:A.sessions.ownerFilter,pinnedIds:A.sessions.pinnedIds,collapsedSessionIds:A.sessions.collapsedIds,activeSessionId:A.sessions.activeSessionId||null,promptRows:Uo(A),chatViewMode:A.ui.chatViewMode||"transcript",activeSessionIsGroup:!!(A.sessions.activeSessionId&&A.sessions.byId[A.sessions.activeSessionId]?.isGroup),paneAdjust:A.ui.layout?.paneAdjust??0,sessionPaneAdjust:A.ui.layout?.sessionPaneAdjust??0,portalSessionColumnAdjust:A.ui.layout?.portalSessionColumnAdjust??0,activityPaneAdjust:A.ui.layout?.activityPaneAdjust??0,focusRegion:A.ui.focusRegion,inspectorTab:A.ui.inspectorTab,filesFullscreen:!!A.files.fullscreen,adminVisible:!!A.admin?.visible}),Ie),d=c.useRef(!1),f=c.useRef(null),h=c.useRef(null),m=c.useRef(null),g=c.useRef(!1),I=c.useRef(!1),y=c.useRef(null),x=c.useRef(null),[E,v]=c.useState("workspace"),[T,O]=c.useState(!1),M=(n.width||window.innerWidth||0)<$o,N=u.activeSessionIsGroup||u.chatViewMode==="summary"?0:u.promptRows;Jd(t,M),c.useEffect(()=>{t.setViewport(o)},[t,o.height,o.width]),c.useEffect(()=>{let A=!0;d.current=!1,f.current=null,y.current=null,x.current=rd(t.getState()),h.current&&(clearTimeout(h.current),h.current=null),m.current&&(clearInterval(m.current),m.current=null),g.current=!1,I.current=!1;const P=t.transport;if(typeof P?.getCurrentUserProfile!="function"||typeof P?.setCurrentUserProfileSettings!="function")return d.current=!0,()=>{A=!1};const $=async()=>{if(!(!A||g.current)){g.current=!0;try{const G=await P.getCurrentUserProfile();if(!A)return;const j=ad(G?.profileSettings,x.current),ae=JSON.stringify(j),te=Ss(t.getState()),Zt=JSON.stringify(te),Yo=d.current&&f.current!=null&&Zt!==f.current;!(h.current||I.current||Yo)&&y.current!==ae&&(t.dispatch({type:"profileSettings/apply",settings:j}),y.current=ae);const Qo=Ss(t.getState());f.current=JSON.stringify(Qo),d.current=!0}catch{if(!A)return;d.current=!0}finally{g.current=!1}}};return $().catch(()=>{}),m.current=setInterval(()=>{$().catch(()=>{})},zu),()=>{A=!1,h.current&&(clearTimeout(h.current),h.current=null),m.current&&(clearInterval(m.current),m.current=null),g.current=!1}},[t]),c.useEffect(()=>{if(!d.current)return;const A=Ss(u),P=JSON.stringify(A);f.current!==P&&(f.current=P,h.current&&clearTimeout(h.current),h.current=setTimeout(()=>{h.current=null,I.current=!0,ld(t,A).catch(()=>{}).finally(()=>{I.current=!1})},400))},[t,u.activeSessionId,u.activityPaneAdjust,u.chatViewMode,u.collapsedSessionIds,u.ownerFilter,u.paneAdjust,u.pinnedIds,u.portalSessionColumnAdjust,u.sessionPaneAdjust,u.themeId]),c.useEffect(()=>{fd(u.themeId)},[u.themeId]),c.useEffect(()=>{M&&u.focusRegion!=="prompt"&&v(u.focusRegion==="activity"?"activity":u.focusRegion==="inspector"?"inspector":"workspace")},[M,u.focusRegion]),c.useEffect(()=>{const A=fn(t);!A.includes(u.inspectorTab)&&A.length>0&&t.selectInspectorTab(A[0]).catch(()=>{})},[t,u.inspectorTab]);const L=c.useMemo(()=>lt(o,u.paneAdjust,N,u.sessionPaneAdjust,u.activityPaneAdjust),[o,u.activityPaneAdjust,u.paneAdjust,N,u.sessionPaneAdjust]),Y=u.filesFullscreen&&u.inspectorTab==="files";c.useEffect(()=>{!Y||!r||(a(!1),p(null))},[r,Y]);const _=c.useCallback(()=>{a(A=>{const P=!A;return P?t.setFocus("chat"):p(null),P})},[t]),W=c.useCallback(A=>{p(P=>{const $=P===A?null:A;return t.setFocus($||"chat"),$})},[t]),U=Math.max(0,(n.width||0)*.68),ee=i.width||U,J=cd(ee,u.portalSessionColumnAdjust),D=ud(J),se=D==="hidden"?"0px":`clamp(0px, calc(${dn*100}% + ${Number(u.portalSessionColumnAdjust)||0}px), max(0px, calc(100% - 14rem - 32px)))`,It=c.createElement("div",{className:"ps-workspace-grid",style:{gridTemplateColumns:`minmax(0, ${L.leftWidth}fr) 16px minmax(0, ${L.rightWidth}fr)`}},c.createElement("div",{ref:s,className:`ps-workspace-main-grid is-session-${D}`,style:{gridTemplateColumns:`${se} 16px minmax(14rem, 1fr)`}},D!=="hidden"?c.createElement("div",{className:"ps-workspace-pane-slot",style:{gridColumn:"1"}},c.createElement(pn,{controller:t,structuredRows:!0})):null,c.createElement("div",{style:{gridColumn:"2",minWidth:0,display:"flex"}},c.createElement(zd,{controller:t,portalSessionColumnAdjust:u.portalSessionColumnAdjust})),c.createElement("div",{className:"ps-workspace-pane-slot",style:{gridColumn:"3"}},c.createElement(hn,{controller:t}))),c.createElement(Kd,{controller:t,paneAdjust:u.paneAdjust}),c.createElement("div",{className:"ps-workspace-column",style:{gridTemplateRows:`${L.inspectorPaneHeight}fr 16px ${L.activityPaneHeight}fr`}},c.createElement("div",{className:"ps-workspace-pane-slot",style:{gridRow:"1"}},L.inspectorHidden?null:c.createElement(rt,{controller:t,mobile:!1})),c.createElement("div",{style:{gridRow:"2",minHeight:0,display:"flex",flexDirection:"column"}},c.createElement(Yd,{controller:t,activityPaneAdjust:u.activityPaneAdjust})),c.createElement("div",{className:"ps-workspace-pane-slot",style:{gridRow:"3"}},L.activityHidden?null:c.createElement(Ls,{controller:t})))),Jt=c.createElement(Wd,{controller:t,openPane:l,onTogglePane:W,onExitFocus:_,mobile:M}),S=c.createElement("div",{className:"ps-workspace-full"},c.createElement(rt,{controller:t,mobile:!1}));let C=null;return Y?C=c.createElement("div",{className:"ps-mobile-pane-fill"},c.createElement(rt,{controller:t,mobile:!0})):E==="inspector"?C=c.createElement("div",{className:"ps-mobile-pane-fill"},c.createElement(rt,{controller:t,mobile:!0})):E==="activity"?C=c.createElement("div",{className:"ps-mobile-pane-fill"},c.createElement(Ls,{controller:t})):C=c.createElement(Gd,{controller:t,sessionsCollapsed:T,setSessionsCollapsed:O}),c.createElement("div",{ref:e,className:"ps-web-shell"},M&&(r||E==="inspector"||E==="activity")?null:c.createElement(qd,{controller:t,mobile:M,chatFocusMode:r,onToggleChatFocus:_,chatFocusDisabled:Y}),c.createElement("div",{className:"ps-workspace"},u.adminVisible?c.createElement(ef,{controller:t}):Y?S:r?Jt:M?C:It),M&&!r?c.createElement(Qd,{activePane:E,setActivePane:v,controller:t}):null,c.createElement(Xd,{controller:t}))}export{nf as P,c as R,sf as c,Zo as r,Pl as s};