pilotswarm 0.5.19 → 0.5.21

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,90 +0,0 @@
1
- function Kr(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var gs={exports:{}},D={};var Hn;function qr(){if(Hn)return D;Hn=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"),c=Symbol.for("react.memo"),d=Symbol.for("react.lazy"),f=Symbol.for("react.activity"),p=Symbol.iterator;function h(y){return y===null||typeof y!="object"?null:(y=p&&y[p]||y["@@iterator"],typeof y=="function"?y:null)}var m={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},g=Object.assign,b={};function S(y,k,N){this.props=y,this.context=k,this.refs=b,this.updater=N||m}S.prototype.isReactComponent={},S.prototype.setState=function(y,k){if(typeof y!="object"&&typeof y!="function"&&y!=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,y,k,"setState")},S.prototype.forceUpdate=function(y){this.updater.enqueueForceUpdate(this,y,"forceUpdate")};function w(){}w.prototype=S.prototype;function I(y,k,N){this.props=y,this.context=k,this.refs=b,this.updater=N||m}var A=I.prototype=new w;A.constructor=I,g(A,S.prototype),A.isPureReactComponent=!0;var C=Array.isArray;function v(){}var T={H:null,A:null,T:null,S:null},M=Object.prototype.hasOwnProperty;function O(y,k,N){var _=N.ref;return{$$typeof:t,type:y,key:k,ref:_!==void 0?_:null,props:N}}function L(y,k){return O(y.type,k,y.props)}function H(y){return typeof y=="object"&&y!==null&&y.$$typeof===t}function F(y){var k={"=":"=0",":":"=2"};return"$"+y.replace(/[=:]/g,function(N){return k[N]})}var q=/\/+/g;function Y(y,k){return typeof y=="object"&&y!==null&&y.key!=null?F(""+y.key):k.toString(36)}function U(y){switch(y.status){case"fulfilled":return y.value;case"rejected":throw y.reason;default:switch(typeof y.status=="string"?y.then(v,v):(y.status="pending",y.then(function(k){y.status==="pending"&&(y.status="fulfilled",y.value=k)},function(k){y.status==="pending"&&(y.status="rejected",y.reason=k)})),y.status){case"fulfilled":return y.value;case"rejected":throw y.reason}}throw y}function W(y,k,N,_,$){var B=typeof y;(B==="undefined"||B==="boolean")&&(y=null);var V=!1;if(y===null)V=!0;else switch(B){case"bigint":case"string":case"number":V=!0;break;case"object":switch(y.$$typeof){case t:case e:V=!0;break;case d:return V=y._init,W(V(y._payload),k,N,_,$)}}if(V)return $=$(y),V=_===""?"."+Y(y,0):_,C($)?(N="",V!=null&&(N=V.replace(q,"$&/")+"/"),W($,k,N,"",function(It){return It})):$!=null&&(H($)&&($=L($,N+($.key==null||y&&y.key===$.key?"":(""+$.key).replace(q,"$&/")+"/")+V)),k.push($)),1;V=0;var ae=_===""?".":_+":";if(C(y))for(var te=0;te<y.length;te++)_=y[te],B=ae+Y(_,te),V+=W(_,k,N,B,$);else if(te=h(y),typeof te=="function")for(y=te.call(y),te=0;!(_=y.next()).done;)_=_.value,B=ae+Y(_,te++),V+=W(_,k,N,B,$);else if(B==="object"){if(typeof y.then=="function")return W(U(y),k,N,_,$);throw k=String(y),Error("Objects are not valid as a React child (found: "+(k==="[object Object]"?"object with keys {"+Object.keys(y).join(", ")+"}":k)+"). If you meant to render a collection of children, use an array instead.")}return V}function Z(y,k,N){if(y==null)return y;var _=[],$=0;return W(y,_,"","",function(B){return k.call(N,B,$++)}),_}function Se(y){if(y._status===-1){var k=y._result;k=k(),k.then(function(N){(y._status===0||y._status===-1)&&(y._status=1,y._result=N)},function(N){(y._status===0||y._status===-1)&&(y._status=2,y._result=N)}),y._status===-1&&(y._status=0,y._result=k)}if(y._status===1)return y._result.default;throw y._result}var ie=typeof reportError=="function"?reportError:function(y){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var k=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof y=="object"&&y!==null&&typeof y.message=="string"?String(y.message):String(y),error:y});if(!window.dispatchEvent(k))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",y);return}console.error(y)},R={map:Z,forEach:function(y,k,N){Z(y,function(){k.apply(this,arguments)},N)},count:function(y){var k=0;return Z(y,function(){k++}),k},toArray:function(y){return Z(y,function(k){return k})||[]},only:function(y){if(!H(y))throw Error("React.Children.only expected to receive a single React element child.");return y}};return D.Activity=f,D.Children=R,D.Component=S,D.Fragment=s,D.Profiler=i,D.PureComponent=I,D.StrictMode=n,D.Suspense=l,D.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=T,D.__COMPILER_RUNTIME={__proto__:null,c:function(y){return T.H.useMemoCache(y)}},D.cache=function(y){return function(){return y.apply(null,arguments)}},D.cacheSignal=function(){return null},D.cloneElement=function(y,k,N){if(y==null)throw Error("The argument must be a React element, but you passed "+y+".");var _=g({},y.props),$=y.key;if(k!=null)for(B in k.key!==void 0&&($=""+k.key),k)!M.call(k,B)||B==="key"||B==="__self"||B==="__source"||B==="ref"&&k.ref===void 0||(_[B]=k[B]);var B=arguments.length-2;if(B===1)_.children=N;else if(1<B){for(var V=Array(B),ae=0;ae<B;ae++)V[ae]=arguments[ae+2];_.children=V}return O(y.type,$,_)},D.createContext=function(y){return y={$$typeof:r,_currentValue:y,_currentValue2:y,_threadCount:0,Provider:null,Consumer:null},y.Provider=y,y.Consumer={$$typeof:o,_context:y},y},D.createElement=function(y,k,N){var _,$={},B=null;if(k!=null)for(_ in k.key!==void 0&&(B=""+k.key),k)M.call(k,_)&&_!=="key"&&_!=="__self"&&_!=="__source"&&($[_]=k[_]);var V=arguments.length-2;if(V===1)$.children=N;else if(1<V){for(var ae=Array(V),te=0;te<V;te++)ae[te]=arguments[te+2];$.children=ae}if(y&&y.defaultProps)for(_ in V=y.defaultProps,V)$[_]===void 0&&($[_]=V[_]);return O(y,B,$)},D.createRef=function(){return{current:null}},D.forwardRef=function(y){return{$$typeof:a,render:y}},D.isValidElement=H,D.lazy=function(y){return{$$typeof:d,_payload:{_status:-1,_result:y},_init:Se}},D.memo=function(y,k){return{$$typeof:c,type:y,compare:k===void 0?null:k}},D.startTransition=function(y){var k=T.T,N={};T.T=N;try{var _=y(),$=T.S;$!==null&&$(N,_),typeof _=="object"&&_!==null&&typeof _.then=="function"&&_.then(v,ie)}catch(B){ie(B)}finally{k!==null&&N.types!==null&&(k.types=N.types),T.T=k}},D.unstable_useCacheRefresh=function(){return T.H.useCacheRefresh()},D.use=function(y){return T.H.use(y)},D.useActionState=function(y,k,N){return T.H.useActionState(y,k,N)},D.useCallback=function(y,k){return T.H.useCallback(y,k)},D.useContext=function(y){return T.H.useContext(y)},D.useDebugValue=function(){},D.useDeferredValue=function(y,k){return T.H.useDeferredValue(y,k)},D.useEffect=function(y,k){return T.H.useEffect(y,k)},D.useEffectEvent=function(y){return T.H.useEffectEvent(y)},D.useId=function(){return T.H.useId()},D.useImperativeHandle=function(y,k,N){return T.H.useImperativeHandle(y,k,N)},D.useInsertionEffect=function(y,k){return T.H.useInsertionEffect(y,k)},D.useLayoutEffect=function(y,k){return T.H.useLayoutEffect(y,k)},D.useMemo=function(y,k){return T.H.useMemo(y,k)},D.useOptimistic=function(y,k){return T.H.useOptimistic(y,k)},D.useReducer=function(y,k,N){return T.H.useReducer(y,k,N)},D.useRef=function(y){return T.H.useRef(y)},D.useState=function(y){return T.H.useState(y)},D.useSyncExternalStore=function(y,k,N){return T.H.useSyncExternalStore(y,k,N)},D.useTransition=function(){return T.H.useTransition()},D.version="19.2.4",D}var Gn;function go(){return Gn||(Gn=1,gs.exports=qr()),gs.exports}var zr=go();const u=Kr(zr);var ys={exports:{}},ce={};var Un;function Yr(){if(Un)return ce;Un=1;var t=go();function e(l){var c="https://react.dev/errors/"+l;if(1<arguments.length){c+="?args[]="+encodeURIComponent(arguments[1]);for(var d=2;d<arguments.length;d++)c+="&args[]="+encodeURIComponent(arguments[d])}return"Minified React error #"+l+"; visit "+c+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function s(){}var n={d:{f:s,r:function(){throw Error(e(522))},D:s,C:s,L:s,m:s,X:s,S:s,M:s},p:0,findDOMNode:null},i=Symbol.for("react.portal");function o(l,c,d){var f=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:i,key:f==null?null:""+f,children:l,containerInfo:c,implementation:d}}var r=t.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function a(l,c){if(l==="font")return"";if(typeof c=="string")return c==="use-credentials"?c:""}return ce.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=n,ce.createPortal=function(l,c){var d=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!c||c.nodeType!==1&&c.nodeType!==9&&c.nodeType!==11)throw Error(e(299));return o(l,c,null,d)},ce.flushSync=function(l){var c=r.T,d=n.p;try{if(r.T=null,n.p=2,l)return l()}finally{r.T=c,n.p=d,n.d.f()}},ce.preconnect=function(l,c){typeof l=="string"&&(c?(c=c.crossOrigin,c=typeof c=="string"?c==="use-credentials"?c:"":void 0):c=null,n.d.C(l,c))},ce.prefetchDNS=function(l){typeof l=="string"&&n.d.D(l)},ce.preinit=function(l,c){if(typeof l=="string"&&c&&typeof c.as=="string"){var d=c.as,f=a(d,c.crossOrigin),p=typeof c.integrity=="string"?c.integrity:void 0,h=typeof c.fetchPriority=="string"?c.fetchPriority:void 0;d==="style"?n.d.S(l,typeof c.precedence=="string"?c.precedence:void 0,{crossOrigin:f,integrity:p,fetchPriority:h}):d==="script"&&n.d.X(l,{crossOrigin:f,integrity:p,fetchPriority:h,nonce:typeof c.nonce=="string"?c.nonce:void 0})}},ce.preinitModule=function(l,c){if(typeof l=="string")if(typeof c=="object"&&c!==null){if(c.as==null||c.as==="script"){var d=a(c.as,c.crossOrigin);n.d.M(l,{crossOrigin:d,integrity:typeof c.integrity=="string"?c.integrity:void 0,nonce:typeof c.nonce=="string"?c.nonce:void 0})}}else c==null&&n.d.M(l)},ce.preload=function(l,c){if(typeof l=="string"&&typeof c=="object"&&c!==null&&typeof c.as=="string"){var d=c.as,f=a(d,c.crossOrigin);n.d.L(l,d,{crossOrigin:f,integrity:typeof c.integrity=="string"?c.integrity:void 0,nonce:typeof c.nonce=="string"?c.nonce:void 0,type:typeof c.type=="string"?c.type:void 0,fetchPriority:typeof c.fetchPriority=="string"?c.fetchPriority:void 0,referrerPolicy:typeof c.referrerPolicy=="string"?c.referrerPolicy:void 0,imageSrcSet:typeof c.imageSrcSet=="string"?c.imageSrcSet:void 0,imageSizes:typeof c.imageSizes=="string"?c.imageSizes:void 0,media:typeof c.media=="string"?c.media:void 0})}},ce.preloadModule=function(l,c){if(typeof l=="string")if(c){var d=a(c.as,c.crossOrigin);n.d.m(l,{as:typeof c.as=="string"&&c.as!=="script"?c.as:void 0,crossOrigin:d,integrity:typeof c.integrity=="string"?c.integrity:void 0})}else n.d.m(l)},ce.requestFormReset=function(l){n.d.r(l)},ce.unstable_batchedUpdates=function(l,c){return l(c)},ce.useFormState=function(l,c,d){return r.H.useFormState(l,c,d)},ce.useFormStatus=function(){return r.H.useHostTransitionStatus()},ce.version="19.2.4",ce}var jn;function Qr(){if(jn)return ys.exports;jn=1;function t(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(t)}catch(e){console.error(e)}}return t(),ys.exports=Yr(),ys.exports}const Xr=u.createContext(null);function xe(){const t=u.useContext(Xr);if(!t)throw new Error("useUiPlatform must be used within a UiPlatformProvider");return t}function K(t,e,s=Object.is){const n=u.useRef(e),i=u.useRef(s);n.current=e,i.current=s;const[o,r]=u.useState(()=>e(t.getState())),a=u.useRef(o);return u.useEffect(()=>{a.current=o},[o]),u.useEffect(()=>t.subscribe(l=>{const c=n.current(l);i.current(a.current,c)||(a.current=c,r(c))}),[t]),o}const Wn=[".  ",".. ","..."],Vn=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];function yo(t,e=120){const[s,n]=u.useState(0);return u.useEffect(()=>{if(!t){n(0);return}const i=setInterval(()=>{n(o=>(o+1)%Vn.length)},e);return()=>clearInterval(i)},[t,e]),t?Vn[s]:""}function So(t,e=360){const[s,n]=u.useState(0);return u.useEffect(()=>{if(!t){n(0);return}const i=setInterval(()=>{n(o=>(o+1)%Wn.length)},e);return()=>clearInterval(i)},[t,e]),t?Wn[s]:""}function bo(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 E={SESSIONS:"sessions",CHAT:"chat",INSPECTOR:"inspector",ACTIVITY:"activity",PROMPT:"prompt",ADMIN:"admin"},ve=["sequence","logs","nodes","history","files","stats"],x={REFRESH:"refresh",NEW_SESSION:"newSession",OPEN_MODEL_PICKER:"openModelPicker",OPEN_SWITCH_MODEL_PICKER:"openSwitchModelPicker",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",GROW_FOCUSED_PANE:"growFocusedPane",SHRINK_FOCUSED_PANE:"shrinkFocusedPane",OPEN_ARTIFACT_PICKER:"openArtifactPicker",OPEN_HELP:"openHelp",SEQUENCE_SELECT_PREV:"sequenceSelectPrev",SEQUENCE_SELECT_NEXT:"sequenceSelectNext",TOGGLE_SEQUENCE_TURN:"toggleSequenceTurn",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",CYCLE_SESSION_VISIBILITY:"cycleSessionVisibility",OPEN_SHARE_SESSION:"openShareSession",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 tt(t,e,s){const n=t.indexOf(e),o=((n===-1?0:n)+s+t.length)%t.length;return t[o]}function on(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 Gs(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 Jr(t){const e=on(t);return e==null?"gray":e>=85?"red":e>=70?"yellow":"gray"}function Zr(t){if(!t||!(typeof t.tokenLimit=="number"&&t.tokenLimit>0&&typeof t.currentTokens=="number"&&t.currentTokens>=0))return null;const e=on(t);return e==null?null:{text:`ctx ${Gs(t.currentTokens)}/${Gs(t.tokenLimit)} ${e}%`,color:Jr(t)}}function ea(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 wo(t){return!t||typeof t!="object"?null:{...t,...t.compaction&&typeof t.compaction=="object"?{compaction:{...t.compaction}}:{}}}function ta(t){if(t instanceof Date)return t.getTime();const e=new Date(t).getTime();return Number.isFinite(e)?e:Date.now()}function Io(t,e,s={},n={}){if(!e)return null;const i=wo(t)||{},o=ta(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 sa(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 ${Gs(s.tokensRemoved)}`,color:"gray"}]:[]]}const Us=/\{(\/?)([a-z-]+)\}/g,na={color:null,bold:!1,underline:!1},Kt=/artifact:\/\/([a-f0-9-]+)\/([^\s"'{}]+)/g,Kn=/session:\/\/([A-Za-z0-9-]+)/g,ia={black:"black",red:"red",green:"green",yellow:"yellow",blue:"blue",magenta:"magenta",cyan:"cyan",white:"white",gray:"gray",grey:"gray"};function jt(t){return{color:t.color,bold:t.bold,underline:t.underline}}function oa(t,e,s){const n=jt(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:ia[i]||null,n}return n}function rn(t){return String(t||"").replace(Us,"")}function xo(t){const e=[],n=String(t||"").split(`
2
- `);for(const i of n){const o=[];let r=jt(na),a=0,l;for(;(l=Us.exec(i))!==null;){const[c,d,f]=l;l.index>a&&o.push({text:i.slice(a,l.index),...jt(r)}),r=oa(r,f,d==="/"),a=l.index+c.length}(a<i.length||o.length===0)&&o.push({text:i.slice(a),...jt(r)}),e.push(o),Us.lastIndex=0}return e}function J(t){return String(t||"").slice(0,8)}function vo(t){const e=String(t||"");return e?e.includes(":")?e.split(":").slice(1).join(":"):e:""}function ge(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 kt(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 ra(t){if(t==null)return"";if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}function aa(t,e,s){const n=t.indexOf(e,s);return n>=0?n:-1}function qt(t){return/[A-Za-z0-9_]/u.test(String(t||""))}function qn(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!(qt(i)&&qt(n))}function la(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!(qt(n)&&qt(i))}function zn(t,e,s){let n=s;for(;n<t.length;){const i=t.indexOf(e,n);if(i<0)return-1;if(la(t,i,e))return i;n=i+e.length}return-1}function ca(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 ua(t,e,s){let n=0;for(;t.slice(s+n,s+n+e.length)===e;)n+=e.length;return n}function xt(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 Ge(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 Eo(t){return(t||[]).map(e=>e?.text||"").join("")}function Wt(t){return Ie(Eo(t))}function da(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=Rt(r,i);a&&(n.push({...o,text:a}),i-=Ie(a))}return n}function Ao(t,e){const s=Math.max(0,Number(e)||0),n=da(t,s),i=Wt(n),o=Math.max(0,s-i);return o>0&&n.push({text:" ".repeat(o),color:null,bold:!1,underline:!1}),n}function To(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 c=Math.max(1,s-o),d=Rt(l,c);if(!d)break;if(d.length===l.length||Ie(d)<c){i.push({...a,text:d}),o+=Ie(d),l=l.slice(d.length),o>=s&&r();continue}const f=d.lastIndexOf(" ");if(f>0&&(o>0||f>0)){const p=d.slice(0,f+1);i.push({...a,text:p}),o+=Ie(p),l=l.slice(p.length),r()}else i.push({...a,text:d}),o+=Ie(d),l=l.slice(d.length),o>=s&&r()}}return(i.length>0||n.length===0)&&r(),n}function Yn(t,e){return e?(t||[]).map(s=>String(s?.text||"").trim()?{...s,color:e}:{...s}):t}function Co(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 fa(t){const e=String(t||"");return Kt.lastIndex=0,[...e.matchAll(Kt)].map(s=>{const n=s[1],i=Co(s[2]);return!n||!i?null:{sessionId:n,filename:i,uri:`artifact://${n}/${i}`}}).filter(Boolean)}function at(t){const e=String(t||"");if(!e)return e;Kt.lastIndex=0;const s=e.replace(Kt,(n,i,o)=>{const r=Co(o);return!i||!r?n:`[artifact: ${r}](artifact://${i}/${r}) (press a to download)`});return Kn.lastIndex=0,s.replace(Kn,(n,i)=>i?`[session: ${J(i)}](session://${i})`:n)}function an(t=""){const e=String(t||""),s=[];let n=0;for(;n<e.length;){if(e[n]==="`"){const o=ua(e,"`",n),r="`".repeat(o),a=aa(e,r,n+o);if(a>n+o-1){Ge(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=qn(e,n,o)?zn(e,o,n+2):-1;if(r>n+2){Ge(s,{type:"strong",text:e.slice(n+2,r)}),n=r+2;continue}}if(e[n]==="["){const o=/^\[([^\]]+)\]\(([^)]+)\)/.exec(e.slice(n));if(o){Ge(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);Ge(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}=ca(e.slice(n,o));if(r){Ge(s,{type:"link",text:r,href:r}),a&&Ge(s,{type:"text",text:a}),n=o;continue}}if((e[n]==="*"||e[n]==="_")&&e[n+1]!==" "&&e[n-1]!==e[n]&&qn(e,n,e[n])){const o=e[n],r=zn(e,o,n+1);if(r>n+1){Ge(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)}Ge(s,{type:"text",text:e.slice(n,i)}),n=i}return s.length>0?s:[{type:"text",text:""}]}function pa(t=""){return an(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 Et(t){const e=an(t),s=[];for(const n of e){if(n.type==="code"){xt(s,n.text,{color:"cyan"});continue}if(n.type==="strong"){xt(s,n.text,{bold:!0});continue}if(n.type==="em"){xt(s,n.text,{underline:!0});continue}if(n.type==="link"){xt(s,n.text,{color:"cyan",underline:!0,href:n.href});continue}xt(s,n.text)}return s.length>0?s:[{text:"",color:null,bold:!1,underline:!1}]}function lt(t){return/^\s*\|.*\|\s*$/.test(t)||/^\s*\|?[:\- ]+\|[:\-| ]+\|?\s*$/.test(t)}function ct(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 zt(t){return t.length>0&&t.every(e=>/^:?-+:?$/.test(String(e||"").replace(/\s+/g,"")))}function Ie(t){return Array.from(String(t||"")).length}function Rt(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 ko(t,e){const s=String(t||""),n=Math.max(0,e-Ie(s));return s+" ".repeat(n)}function Mo(t){return Eo(Et(t))}function ha(t,e){const s=Mo(t).replace(/\s+/g," ").trim();if(!s)return[""];const n=s.split(" "),i=[];let o="";const r=a=>{let l=a;for(;Ie(l)>e;){const c=Rt(l,e);if(!c)break;o&&(i.push(o),o=""),i.push(c),l=l.slice(c.length)}return l};for(const a of n){const l=r(a);if(!l)continue;if(!o){o=l;continue}const c=`${o} ${l}`;Ie(c)<=e?o=c:(i.push(o),o=l)}return o&&i.push(o),i.length>0?i:[""]}function ma(t,e){const s=Math.max(1,...t.map(d=>d.length)),n=Math.max(s*3,e-(s*3+1)),i=Array.from({length:s},(d,f)=>Math.max(3,...t.map(p=>Ie(p[f]||"")))),o=Array.from({length:s},(d,f)=>Math.max(3,...t.map(p=>Math.max(0,...String(p[f]||"").split(/\s+/).filter(Boolean).map(h=>Ie(h)))))),r=Array.from({length:s},(d,f)=>Math.max(3,Math.min(Math.max(Ie(t[0]?.[f]||"")||3,o[f]),24)));if(i.reduce((d,f)=>d+f,0)<=n)return i;const l=r.slice();let c=n-l.reduce((d,f)=>d+f,0);if(c<0){const d=Math.max(3,Math.floor(n/s));return l.map((f,p)=>p===s-1?Math.max(3,n-d*(s-1)):d)}for(;c>0;){let d=0,f=-1/0;for(let p=0;p<s;p++){const h=i[p]-l[p];h>f&&(f=h,d=p)}if(f<=0){l[s-1]+=c;break}l[d]+=1,c-=1}return l}function ga(t,e){if(!t||t.length===0)return"";const s=Math.max(1,...t.map(p=>p.length)),i=t.map(p=>Array.from({length:s},(h,m)=>p[m]||"")).map(p=>p.map(h=>Mo(h))),o=ma(i,e),r=[],a=`┌${o.map(p=>"─".repeat(p+2)).join("┬")}┐`,l=`├${o.map(p=>"─".repeat(p+2)).join("┼")}┤`,c=`└${o.map(p=>"─".repeat(p+2)).join("┴")}┘`,d=p=>{const h=p.map((g,b)=>ha(g,o[b])),m=Math.max(...h.map(g=>g.length));for(let g=0;g<m;g++){const b=h.map((S,w)=>ko(S[g]||"",o[w]));r.push(`│ ${b.join(" │ ")} │`)}};r.push(a),d(i[0]),r.push(l);const f=i.slice(1);for(const p of f)d(p);return r.push(c),r.join(`
3
- `)}function ya(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(!lt(r)||!lt(l)){n.push(r);continue}const c=ct(r),d=ct(l);if(!zt(d)||c.length!==d.length){n.push(r);continue}const f=[c];for(o+=1;o+1<s.length&&lt(s[o+1]);){o+=1;const p=ct(s[o]);zt(p)||f.push(p)}n.push(ga(f,e))}return n.join(`
5
- `)}function Sa(t,e){const s=String(t||"");if(!s)return[""];const n=[];let i=s;for(;i.length>0;){const o=Rt(i,e);if(!o)break;n.push(o),i=i.slice(o.length)}return n.length>0?n:[""]}function Qn(t,e){const s=Math.max(12,e),n=t?` ${String(t).trim()} `:" code ",i=Rt(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 Jn(t,e){const s=Math.max(8,e),n=Math.max(1,s-2),i=[];for(const o of t){const r=Sa(o,n);for(const a of r)i.push([{text:"│",color:"gray"},{text:ko(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 mt(t,e={}){const s=[],n=Math.max(20,Number(e?.width)||80),i=e.tableMode==="sentinel"?"sentinel":"boxArt",r=(i==="boxArt"?ya(String(t||""),n):String(t||"")).split(`
6
- `);let a=!1,l="",c=[];for(let d=0;d<r.length;d+=1){const f=r[d],p=f.trim();if(p.startsWith("```")){a?(s.push(Qn(l,Math.max(8,n))),s.push(...Jn(c,Math.max(8,n))),s.push(Xn(Math.max(8,n))),a=!1,l="",c=[]):(a=!0,l=p.slice(3).trim(),c=[]);continue}if(a){c.push(f);continue}if(i==="sentinel"&&f&&lt(f)){const S=r[d+1]||"";if(lt(S)){const w=ct(f),I=ct(S);if(zt(I)&&w.length===I.length){const A=[];let C=d+2;for(;C<r.length&&lt(r[C]);){const v=ct(r[C]);zt(v)||A.push(v),C+=1}s.push({kind:"markdownTable",header:w,rows:A}),d=C-1;continue}}}if(!f){s.push([{text:"",color:null}]);continue}const h=/^(#{1,6})\s+(.*)$/.exec(f);if(h){s.push([{text:h[2],color:"white",bold:!0}]);continue}const m=/^>\s?(.*)$/.exec(f);if(m){s.push([{text:"> ",color:"gray"},...Et(m[1]).map(S=>({...S,color:S.color||"gray"}))]);continue}const g=/^\s*[-*]\s+(.*)$/.exec(f);if(g){s.push([{text:"• ",color:"gray"},...Et(g[1])]);continue}const b=/^\s*(\d+)\.\s+(.*)$/.exec(f);if(b){s.push([{text:`${b[1]}. `,color:"gray"},...Et(b[2])]);continue}s.push(Et(f))}return a&&(s.push(Qn(l,Math.max(8,n))),s.push(...Jn(c,Math.max(8,n))),s.push(Xn(Math.max(8,n)))),s}function ne({title:t="SYSTEM",timestamp:e="",body:s="",width:n=80,titleColor:i="yellow",borderColor:o="gray",bodyColor:r=null,fitToContent:a=!1,tableMode:l=null}={}){const c=Math.max(a?12:20,Number(n)||(a?12:20)),d=Math.max(1,c-4),f=[{text:` ${String(t||"SYSTEM").toUpperCase()} `,color:i,bold:!0},...e?[{text:` ${String(e)} `,color:"gray"}]:[]];if(l==="sentinel"){const I=mt(String(s||""),{width:d,tableMode:l}),A=r?I.map(C=>Array.isArray(C)?Yn(C,r):C):I;return[{kind:"cardStart",runs:f,borderColor:o},...A,{kind:"cardEnd"},[{text:"",color:null}]]}const p=mt(String(s||""),{width:d}),h=p.length>0?p.flatMap(I=>To(I,d)):[[{text:"",color:null}]],m=r?h.map(I=>Yn(I,r)):h,g=m.reduce((I,A)=>Math.max(I,Wt(A)),0),b=a?Math.min(c,Math.max(12,Wt(f)+3,g+4)):c,S=Math.max(1,b-4),w=Math.max(0,b-Wt(f)-3);return[[{text:"┌─",color:o},...f,{text:`${"─".repeat(w)}┐`,color:o}],...m.map(I=>[{text:"│ ",color:o},...Ao(I,S),{text:" │",color:o}]),[{text:`└${"─".repeat(Math.max(1,b-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 Po(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 X=300,ba=[X,1e3,3e3,1e4],wa=["user.message","assistant.message","system.message"];function Le(t,e){const s=Array.isArray(t)?t.filter(Boolean):[],n=Math.max(X,Number(e)||X);return s.length>n?s.slice(-n):s}function He(t){return String(t||"").replace(/\r\n/g,`
7
- `).trim()}function Zn(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 No=/^The session was dehydrated and has been rehydrated on a new worker(?: \([^)]+\))?\./i,Ia=/^The session was dehydrated and has been rehydrated on a new worker(?: \([^)]+\))?\.\s*The LLM conversation history is preserved\.?/i;function ln(t){return No.test(He(t))}function We(t){const e=String(t||"").replace(/\r\n/g,`
8
- `).trim();if(!e)return"";const s=e.replace(Ia,"").trimStart();return s!==e?s.trim():ln(e)?e.replace(No,"").trim():e}function Oo(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 c=-1;for(let d=o+1;d<e.length;d+=1){const f=e[d];if(f.trim()==="]"){c=d;break}if(/\]\s*$/.test(f.trim())){const p=f.replace(/\]\s*$/,"");p.trim()&&l.push(p),c=d;break}l.push(f)}if(c===-1){n.push(r),o+=1;continue}i(),s.push({kind:"system",text:l.join(`
12
- `).trim()}),o=c+1}return i(),s}function _o(t,e){const s=String(t||"").replace(/\r\n/g,`
13
- `);return e==="user"||e==="assistant"?Oo(s).filter(n=>n.kind==="text").map(n=>n.text).join(`
14
- `).trim():s.trim()}function xa(t,e){return e!=="user"&&e!=="assistant"?[]:Oo(t).filter(s=>s.kind==="system").map(s=>s.text).filter(Boolean)}function ei(t){const e=He(t?.text||"");if(!e)return"";if(t?.role==="user"||t?.role==="assistant"){const s=_o(e,t.role);if(s)return s}return We(e)}function cn(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 va(t){return He(rn(t)).length>0}function Ea(t){const e=He(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 Aa(t){return/^\[SESSION_MESSAGE(?:_RESPONSE)?\b/i.test(He(t))}function st(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 c=o.indexOf(l);c>=0&&(a=Math.min(a,c))}return o.slice(0,a).trim()}function Ta(t,e){const s=He(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(),c=st(o,"request_id"),d=st(o,"from"),f=st(o,"subject"),p=/\bexpects_response=true\b/i.test(o),h=[d?`From: session-${J(d)}`:"",c?`Request ID: ${c}`:"",f?`Subject: ${f}`:"",p?"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:ge(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime(),cardTitle:p?"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=st(o,"request_id"),c=st(o,"from"),d=st(o,"verdict")||"answered",f=[c?`From: session-${J(c)}`:"",l?`Request ID: ${l}`:"",`Verdict: ${d}`,"",a].filter((p,h)=>h===3||String(p||"").trim());return{id:`${t.sessionId}:${t.seq}`,role:"system",text:f.join(`
20
- `),time:ge(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 Ca(t,e,s){return t?.eventType==="system.message"||(e==="user"||e==="assistant")&&Ea(s)?"system":e}function ka(t,e){if(!t||!e||t.role!==e.role)return!1;const s=ei(t),n=ei(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 ut(t=[]){const e=[];for(const s of t){if(!s)continue;const n=e[e.length-1];if(!ka(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 Ma(t){return typeof t=="string"?t.replace(/^\[FROM:[^\]\n]*\]\n?/,""):t}function dt(t,e){const s=bt(t),n=Ta(t,s);if(n)return n;const i=Ma(_o(s,e));if(!va(i))return null;const o=Array.isArray(t?.data?.clientMessageIds)?t.data.clientMessageIds.filter(l=>typeof l=="string"&&l):[],r=t?.data?.sender&&typeof t.data.sender=="object"?t.data.sender:null,a=Array.isArray(t?.data?.attachments)?t.data.attachments.filter(l=>l&&typeof l.filename=="string"&&l.filename):[];return{id:`${t.sessionId}:${t.seq}`,role:Ca(t,e,i),text:i,time:ge(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime(),...o.length>0?{clientMessageIds:o}:{},...r?{sender:r}:{},...a.length>0?{attachments:a}:{}}}function Ro(t){return t?.eventType!=="system.message"?!1:!Aa(bt(t))}function Yt(t,e){return xa(bt(t),e).map((s,n)=>Nt({...t,seq:`${t?.seq??"?"}:system:${n+1}`,eventType:"system.message",data:{content:s}})).filter(Boolean)}function Pa(t,e){if(!Array.isArray(t)||e?.role!=="user")return[...t||[]];const s=He(e.text),n=cn(e.text),i=n?He(n.answer):"";let o=!1;return t.filter(r=>{if(o||!r?.optimistic||r.role!==e.role)return!0;const a=He(r.text);return a!==s&&a!==i?!0:(o=!0,!1)})}function bt(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 ra(e)}function Na(t){return(t||[]).map(e=>e?.text||"").join("")}function Oa(t,e=120){const s=String(t||"").replace(/\s+/g," ").trim();return s?s.length>e?`${s.slice(0,e-3)}...`:s:""}function un(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 _a(t,e=""){return un([t?.data?.reason,t?.data?.detail,t?.data?.message,t?.data?.error,e])}function Ra(t,e=""){return un([t?.data?.message,t?.data?.detail,t?.data?.error,e])}function La(t,e=""){const s=bt(t),n=We(e);return un([We(s),n,t?.data?.detail,t?.data?.message])}function Fa(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 $a(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}=${Fa(o)}`);if(s.length===0)return"";const n=Object.keys(e).length>s.length?", ...":"";return` ${s.join(", ")}${n}`}function dn(t){return t?[{text:`[${t}] `,color:"white"}]:[]}function ee(t,e,s,n="",i="white"){return[...dn(t),{text:e,color:s},...n?[{text:` ${n}`,color:i}]:[]]}function Ba(t,e=96){return Oa(rn(bt(t)),e)||""}function Ss(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=$a(o,r),c=s==="start"?"▶":s==="partial"?"…":"✓",d=s==="start"?"yellow":s==="partial"?"cyan":"green";return[...dn(t),{text:`${c} ${o}${l}`,color:d},...a?[{text:` [sess ${J(a)}]`,color:"gray"}]:[]]}function Nt(t){const e=ge(t.createdAt),s=Ba(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=Ss(e,t,"start");break;case"tool.execution_complete":n=Ss(e,t,"complete");break;case"tool.execution_partial_result":n=Ss(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=ee(e,"[tool]","cyan",`${o} ${r}`,"white");break}case"assistant.reasoning":n=ee(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=ee(e,"[intent]","gray",o||"…","white");break}case"assistant.turn_start":n=ee(e,"[turn start]","gray",s);break;case"session.turn_completed":n=ee(e,"[turn completed]","gray",t?.data?.iteration!=null?`iter ${t.data.iteration}`:s);break;case"session.lossy_handoff":n=ee(e,"[lossy handoff]","yellow",Ra(t,s)||"handoff to a new worker");break;case"session.dehydrated":n=ee(e,"[dehydrated]","cyan",_a(t,s));break;case"session.hydrated":case"session.rehydrated":n=ee(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=ee(e,"[wait]","yellow",`${i}${r}${o}`.trim());break}case"session.input_required_started":n=ee(e,"[input]","yellow",s);break;case"session.agent_spawned":n=ee(e,"[spawn]","cyan",t?.data?.agentId||J(t?.data?.childSessionId),"white");break;case"session.cron_started":n=ee(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=ee(e,"[cron]","magenta",`scheduled${t?.data?.nextFireAt?` ${Zn(t.data.nextFireAt)}`:""}${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_fired":n=ee(e,"[cron]","magenta",`fired${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_at_fired":n=ee(e,"[cron]","magenta",`fired${t?.data?.scheduledAt?` ${Zn(t.data.scheduledAt)}`:""}${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_cancelled":case"session.cron_at_cancelled":n=ee(e,"[cron]","magenta",`cancelled${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_at_completed":n=ee(e,"[cron]","magenta",`completed${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.command_received":n=ee(e,"[command]","magenta",`/${t?.data?.cmd||"?"}${s?` ${s}`:""}`);break;case"session.command_completed":n=ee(e,"[command]","magenta",`/${t?.data?.cmd||"?"} ok${s?` ${s}`:""}`);break;case"session.compaction_start":case"session.compaction_complete":n=sa(e,t.eventType,t.data||{});break;case"session.error":n=ee(e,"[error]","red",s||"session error","white");break;case"system.message":ln(bt(t))?n=ee(e,"[rehydrated]","green",La(t,s)||"conversation preserved"):n=ee(e,"[system]","gray",s||"system message");break;default:n=[...dn(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:Na(n),line:n}}function Da(t=X){const e=Math.max(X,Number(t)||X);return ba.find(n=>n>e)||Math.min(1e5,e*2)}function Bt(t=[],e={}){const s=Math.max(X,Number(e.requestedLimit??e.eventLimit??X)||X),n=[],i=[],o=[];for(const r of t){if(o.push(r),r.eventType==="user.message"){i.push(...Yt(r,"user"));const l=dt(r,"user");l&&n.push(l);continue}if(r.eventType==="assistant.message"){i.push(...Yt(r,"assistant"));const l=dt(r,"assistant");l&&n.push(l);continue}if(r.eventType==="system.message"){if(Ro(r)){const l=Nt(r);l&&i.push(l)}else{const l=dt(r,"system");l&&n.push(l)}continue}const a=Nt(r);a&&i.push(a)}return{chat:ut(n),activity:i,events:o.slice(-s),loadedEventLimit:s,loadedEventCount:o.length,hasOlderEvents:o.length>=s}}function ti(t,e){const s=Array.isArray(t?.events)?t.events:[],n=Math.max(X,Number(t?.loadedEventLimit??X)||X),i=s.length>0&&s[s.length-1]?.seq===e?.seq?s:[...s,e].slice(-n),o={chat:Le(t?.chat||[],n),activity:Le(t?.activity||[],n),events:i,lastSeq:e.seq,loadedEventLimit:n,loadedEventCount:Math.max(Number(t?.loadedEventCount||0),i.length),hasOlderEvents:!!t?.hasOlderEvents,stoppedMessageIds:Array.isArray(t?.stoppedMessageIds)?t.stoppedMessageIds:[]};if(e.eventType==="session.turn_stopped"){const a=Array.isArray(e?.data?.clientMessageIds)?e.data.clientMessageIds.filter(l=>typeof l=="string"&&l):[];if(a.length>0){const l=new Set([...o.stoppedMessageIds,...a]);o.stoppedMessageIds=Array.from(l),o.chat=o.chat.map(c=>Array.isArray(c.clientMessageIds)&&c.clientMessageIds.some(d=>l.has(d))?{...c,stopped:!0}:c)}return o}if(e.eventType==="user.message"){o.activity.push(...Yt(e,"user")),o.activity=Le(o.activity,n);const a=dt(e,"user");return a&&(Array.isArray(a.clientMessageIds)&&a.clientMessageIds.some(l=>o.stoppedMessageIds.includes(l))&&(a.stopped=!0),o.chat=Pa(o.chat,a),o.chat.push(a),o.chat=Le(ut(o.chat),n)),o}if(e.eventType==="assistant.message"){o.activity.push(...Yt(e,"assistant")),o.activity=Le(o.activity,n);const a=dt(e,"assistant");return a&&(o.chat.push(a),o.chat=Le(ut(o.chat),n)),o}if(e.eventType==="system.message"){if(Ro(e)){const a=Nt(e);a&&(o.activity.push(a),o.activity=Le(o.activity,n))}else{const a=dt(e,"system");if(!a)return o;o.chat.push(a),o.chat=Le(ut(o.chat),n)}return o}const r=Nt(e);return r&&(o.activity.push(r),o.activity=Le(o.activity,n)),o}function bs(t,e=null){const s=typeof e?.splash=="string"&&e.splash.trim()?e.splash:null,n=s||t?.splash;if(!n)return[];const i=s?e?.splashMobile:t?.splashMobile,o=typeof i=="string"&&i.trim()?i:null,r=e?.isSystem?St(e,t?.title||"PilotSwarm"):e?.title||t?.title||"PilotSwarm",a="{gray-fg}Start interacting with this session to replace the splash screen.{/gray-fg}";return[{id:`splash:${r}`,role:"system",text:`${n}
21
-
22
- ${a}`,...o?{mobileText:`${o}
23
-
24
- ${a}`}:{},time:"",splash:!0}]}const Ha=.7,Ga=30,si=36,ws=18,Is=18,xs=0,Lo=3,gt=6,as=10,Ua=.25,ja=.5,ft=6,Qt=10,Fo=.336,vs=ft,Es=Qt,As=gt,Ts=as;function At(t,e,s){return Math.max(e,Math.min(s,t))}function Wa(t){return[E.SESSIONS,E.CHAT,E.INSPECTOR,E.ACTIVITY].includes(t)?t:null}function Va(t={}){return{width:Math.max(40,Number(t.width)||120),height:Math.max(18,Number(t.height)||40)}}function pt(t=""){const e=String(t||"").split(`
25
- `).length;return At(e,1,Lo)}function $o(t){return Math.max(gt,Math.floor(t*Ua))}function Bo(t,e){const s=Math.floor(Math.max(0,Number(t)||0)*ja),n=Math.max(gt,e-as);return Math.max(gt,Math.min(n,s))}function Mt(t,e=0,s=1,n=0,i=0,o=null){const r=Va(t),a=r.width,l=r.height,c=At(Number(s)||1,1,Lo),d=Wa(o),f=5+c,p=Math.max(18,l-f),m=Math.floor(a*Ha)+(Number(e)||0),g=a-m-xs;let b=!1,S=!1;m<=ws&&g>Is?b=!0:g<=Is&&m>ws?S=!0:m<=ws&&g<=Is&&(S=e>=0,b=!S);let w,I;b?(w=0,I=a):S?(w=a,I=0):(w=At(m,Ga,a-si-xs),I=Math.max(si,a-w-xs));const C=$o(p)+(Number(n)||0),v=p-C;let T=!1,M=!1;v<=Ts&&C>As?M=!0:C<=As&&v>Ts?T=!0:v<=Ts&&C<=As&&(M=(Number(n)||0)>=0,T=!M);let O,L;if(T)O=0,L=p;else if(M)O=p,L=0;else{const Se=Bo(l,p);O=At(C,gt,Se),L=Math.max(as,p-O)}const F=Math.max(ft,Math.floor(p*Fo))+(Number(i)||0),q=p-F;let Y=!1,U=!1;q<=Es&&F>vs?Y=!0:F<=vs&&q>Es?U=!0:q<=Es&&F<=vs&&(Y=(Number(i)||0)>=0,U=!Y);let W,Z;return Y?(W=p,Z=0):U?(Z=p,W=0):(W=At(F,ft,Math.max(ft,p-Qt)),Z=Math.max(Qt,p-W)),{viewport:r,totalWidth:a,totalHeight:l,reservedRows:f,bodyHeight:p,promptRows:c,fullscreenPane:d,paneAdjust:Number(e)||0,sessionPaneAdjust:Number(n)||0,activityPaneAdjust:Number(i)||0,leftHidden:b,rightHidden:S,inspectorHidden:Y,activityHidden:U,sessionHidden:T,chatHidden:M,leftWidth:w,rightWidth:I,sessionPaneHeight:O,chatPaneHeight:L,activityPaneHeight:W,inspectorPaneHeight:Z}}function js(t){if(t?.fullscreenPane)return[t.fullscreenPane,E.PROMPT];if(t?.leftHidden)return[E.INSPECTOR,E.ACTIVITY,E.PROMPT];if(t?.rightHidden)return[...t?.sessionHidden?[E.CHAT]:t?.chatHidden?[E.SESSIONS]:[E.SESSIONS,E.CHAT],E.PROMPT];if(t?.sessionHidden){const e=t?.inspectorHidden?[E.ACTIVITY]:t?.activityHidden?[E.INSPECTOR]:[E.INSPECTOR,E.ACTIVITY];return[E.CHAT,...e,E.PROMPT]}if(t?.chatHidden){const e=t?.inspectorHidden?[E.ACTIVITY]:t?.activityHidden?[E.INSPECTOR]:[E.INSPECTOR,E.ACTIVITY];return[E.SESSIONS,...e,E.PROMPT]}return t?.inspectorHidden?[E.SESSIONS,E.CHAT,E.ACTIVITY,E.PROMPT]:t?.activityHidden?[E.SESSIONS,E.CHAT,E.INSPECTOR,E.PROMPT]:[E.SESSIONS,E.CHAT,E.INSPECTOR,E.ACTIVITY,E.PROMPT]}function Fe(t,e){const s=js(e);return s.includes(t)?t:s[0]||E.PROMPT}function Ka(t,e){return e?.fullscreenPane?e.fullscreenPane:e?.leftHidden?{[E.PROMPT]:E.PROMPT,[E.ACTIVITY]:E.INSPECTOR,[E.INSPECTOR]:E.INSPECTOR}[t]||E.INSPECTOR:e?.rightHidden?{[E.PROMPT]:E.PROMPT,[E.CHAT]:e?.sessionHidden?E.CHAT:E.SESSIONS,[E.SESSIONS]:E.SESSIONS}[t]||(e?.sessionHidden?E.CHAT:E.SESSIONS):{[E.PROMPT]:e?.sessionHidden?E.CHAT:E.SESSIONS,[E.ACTIVITY]:e?.chatHidden?E.SESSIONS:E.CHAT,[E.INSPECTOR]:e?.chatHidden?E.SESSIONS:E.CHAT,[E.CHAT]:e?.sessionHidden?E.CHAT:E.SESSIONS,[E.SESSIONS]:E.SESSIONS}[t]||(e?.sessionHidden?E.CHAT:E.SESSIONS)}function qa(t,e){return e?.fullscreenPane?e.fullscreenPane:e?.leftHidden?{[E.PROMPT]:E.PROMPT,[E.INSPECTOR]:E.ACTIVITY,[E.ACTIVITY]:E.ACTIVITY}[t]||E.INSPECTOR:e?.rightHidden?{[E.PROMPT]:E.PROMPT,[E.SESSIONS]:e?.chatHidden?E.SESSIONS:E.CHAT,[E.CHAT]:E.CHAT}[t]||(e?.chatHidden?E.SESSIONS:E.CHAT):e?.inspectorHidden?{[E.PROMPT]:E.PROMPT,[E.SESSIONS]:E.CHAT,[E.CHAT]:E.ACTIVITY,[E.ACTIVITY]:E.ACTIVITY}[t]||E.CHAT:e?.activityHidden?{[E.PROMPT]:E.PROMPT,[E.SESSIONS]:E.CHAT,[E.CHAT]:E.INSPECTOR,[E.INSPECTOR]:E.INSPECTOR}[t]||E.CHAT:{[E.PROMPT]:E.PROMPT,[E.SESSIONS]:E.CHAT,[E.CHAT]:E.INSPECTOR,[E.INSPECTOR]:E.ACTIVITY,[E.ACTIVITY]:E.ACTIVITY}[t]||E.CHAT}function ni(t){return t?.isSystem?Po(t):Number.MAX_SAFE_INTEGER}function za(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 Ya(t=[]){if(t instanceof Map)return new Map(t);if(Array.isArray(t))return za(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 Qa(t){return!!(t&&!t.isSystem&&(t.isGroup||!t.parentSessionId&&!t.groupId))}function ii(t,e){return!!(Qa(t)&&e&&e.has(t.sessionId))}function oi(t,e){return t.isSystem?0:t.isGroup&&ii(t,e)?1:ii(t,e)?2:t.isGroup?3:4}function ri(t){const e=t?.updatedAt??t?.summaryUpdatedAt??t?.latestSummaryUpdatedAt,s=typeof e=="number"?e:Date.parse(e||"");return Number.isFinite(s)?s:0}function ai(t,e,s,n){const i=oi(t,n),o=oi(e,n);if(i!==o)return i-o;const r=ni(t),a=ni(e);if(r!==a)return r-a;const l=s.get(t.sessionId),c=s.get(e.sessionId);if(typeof l=="number"&&typeof c=="number"&&l!==c)return l-c;const d=ri(t),f=ri(e);if(d>0&&f>0&&d!==f)return f-d;const p=(e.createdAt||0)-(t.createdAt||0);if(p!==0)return p;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 Be(t=[],e=new Set,s=[],n=null){const i=new Map,o=new Map,r=Ya(s),a=n instanceof Set?n:new Set(Array.isArray(n)?n:[]);for(const f of t)i.set(f.sessionId,f);for(const f of t){const p=!f.isGroup&&f.groupId&&!f.parentSessionId&&i.has(`group:${f.groupId}`)?`group:${f.groupId}`:null,h=f.parentSessionId||p;!h||!i.has(h)||(o.has(h)||o.set(h,[]),o.get(h).push(f))}for(const f of o.values())f.sort((p,h)=>ai(p,h,r,a));const l=t.filter(f=>!(f.parentSessionId&&i.has(f.parentSessionId)||!f.isGroup&&f.groupId&&!f.parentSessionId&&i.has(`group:${f.groupId}`))).sort((f,p)=>ai(f,p,r,a)),c=[];function d(f,p){const h=o.get(f.sessionId)||[];if(c.push({sessionId:f.sessionId,depth:p,hasChildren:h.length>0,collapsed:e.has(f.sessionId)}),!e.has(f.sessionId))for(const m of h)d(m,p+1)}for(const f of l)d(f,0);return c}function Xa(t){return Object.freeze({...t,page:Object.freeze({...t.page||{}}),terminal:Object.freeze({...t.terminal||{}}),tui:Object.freeze({...t.tui||{}})})}function re({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",otherUserChatLabel:i?.brightMagenta||i?.magenta||"#c9a3ff",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 Xa({id:t,label:e,description:s,page:n,terminal:i,tui:{...r,...o}})}const Ja=re({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"}}),Za=re({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"}}),el=re({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"}}),tl=re({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"}}),sl=re({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"}}),nl=re({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"}}),il=re({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"}}),ol=re({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"}}),rl=re({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"}}),al=re({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"}}),ll=re({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"}}),cl=re({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"}}),ul=re({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"}}),Do=re({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"}}),dl=re({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"}}),fl=re({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"}}),pl=re({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"}}),hl=re({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"}}),Ho=Object.freeze([il,Ja,Za,el,tl,sl,nl,al,rl,ol,ll,cl,ul,Do,dl,fl,pl,hl].sort((t,e)=>t.label.localeCompare(e.label,void 0,{sensitivity:"base"}))),ml=new Map(Ho.map(t=>[t.id,t])),gl=Do.id;function yl(){return Ho}function ze(t){return t?ml.get(t)??null:null}const Sl=new Set(["agent","user","system"]);function Xt(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,includeShared:t?.includeShared===!0,ownerKeys:e}}function bl(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:Sl.has(t.source)?t.source:"agent"}}function Jt(t){const e=Array.isArray(t)?t:[],s=[],n=new Set;for(const i of e){const o=bl(i);!o||n.has(o.filename)||(n.add(o.filename),s.push(o))}return s}function wl(t,e){const s=String(e||"").trim();return s&&Jt(t).find(n=>n.filename===s)||null}function fn(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 Zt(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 Ws(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 Go(t){if(t==null)return null;const e=String(t).trim();return e||null}function Il({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 c=i!=null,d=a!=null,f=fn(o);return{branding:e||{title:"PilotSwarm",splash:"{bold}{cyan-fg}PilotSwarm{/cyan-fg}{/bold}"},auth:{principal:null,authorization:null},ui:{focusRegion:E.SESSIONS,inspectorTab:ve[0],sequenceExpandedTurns:[],sequenceSelectedTurn:null,chatViewMode:n==="summary"?"summary":"transcript",statsViewMode:"session",prompt:"",promptCursor:0,promptRows:1,promptAttachments:[],promptEdit:null,statusText:"Starting PilotSwarm...",themeId:ze(s)?.id||gl,modal:null,fullscreenPane:null,layout:{...f,viewportWidth:120,viewportHeight:40},scroll:{chat:0,inspector:0,activity:0,filePreview:0},chatScrollBySession:{},followBottom:{inspector:!0,activity:!0}},connection:{mode:t,connected:!1,workersOnline:null,error:null},sessions:{byId:{},flat:[],activeSessionId:Go(l),collapsedIds:Ws(a),collapsedIdsExplicit:d,pinnedIds:Zt(r),selectedIds:[],selectMode:!1,orderById:{},nextOrderOrdinal:0,filterQuery:"",ownerFilterExplicit:c,ownerFilter:Xt(i),navigationIntent:null,filterExceptionId:null},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,storeAsSystem:!1},systemGhcpKey:{supported:!1,loading:!1,configured:!1,changedBy:null,changedAt:null,error:null}}}}function Uo(t){const e=String(t||"");return/\bConnection is closed\b/i.test(e)||/\bLive Copilot connection lost\b/i.test(e)}function xl(t,e){return!(!Uo(t?.error)||e?.error!==void 0||String(e?.status||"")!=="running"||["Completed","Failed","Terminated"].includes(String(e?.orchestrationStatus||"")))}const jo="activeHighlightBackground",pn="activeHighlightForeground",Cs="userChat",vl="userChatLabel",El="otherUserChatLabel",li=new WeakMap,ci=new WeakMap;function Al(t){return t||pn}function Wo(t,{preserveColors:e=!1}={}){return(t||[]).map(s=>({...s,color:e?Al(s?.color):pn,backgroundColor:jo,bold:s?.bold??!0}))}function Ce(t,{color:e=pn,bold:s=!0}={}){return{text:t,color:e,backgroundColor:jo,bold:s}}function Pe(t,e){return[{text:String(t||""),color:e,bold:!0}]}const Tl=72;function Vo(t){const e=Number(t)||0;return e>0&&e<=Tl}function hn(t){if(!t)return"unknown";const e=t.status||"unknown";return t.cronActive===!0&&(e==="waiting"||e==="idle"||e==="unknown")?"cron_waiting":e}function Cl(t){const e=hn(t);return!e||e==="unknown"?"":e==="cron_waiting"?"waiting":e}function kl(t){const e=Ko(t);return!e||e==="unknown"?"":e==="cron_waiting"?"waiting":e}function Ko(t){return t?.rowVisualStatus||hn(t)}function qo(t){return t==="Completed"||t==="Failed"||t==="Terminated"}function mn(t){const e=hn(t);return t?.orchestrationStatus==="Failed"||e==="failed"?"failed":e==="error"||e==="running"&&Uo(t?.error)&&!qo(t?.orchestrationStatus)?"warning":null}function zo(t,e="local"){const s=mn(t);if(s)return s;const n=Ko(t);if(e==="remote"&&qo(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 Ot(t,e="local"){switch(zo(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 Yo(t,e="local"){switch(zo(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 Ee(t){const e=String(t?.provider||"").trim(),s=String(t?.subject||"").trim();return e&&s?`${e}${s}`:null}function gn(t,e="unknown user"){return String(t?.displayName||t?.email||"").trim()||e}const Ml=Ee({provider:"system",subject:"system"});function ui(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 Pl(t){return ui(t?.displayName)||ui(t?.email)||"?"}function Nl(t){if(t.sessions?.ownerFilter&&t.sessions.ownerFilter.all!==!0)return!0;const e=new Set;for(const s of Object.values(t.sessions?.byId||{})){if(!s||s.isSystem||s.isGroup)continue;const n=Ee(s.owner);if(n&&(e.add(n),e.size>1))return!0}return!1}function Qo(t,e={}){return!t?.isGroup||!t?.groupId?[]:Object.values(e||{}).filter(s=>s&&!s.isGroup&&!s.parentSessionId&&s.groupId===t.groupId)}function yn(t,e={}){if(!t?.isGroup)return t?.owner??null;if(t.owner)return t.owner;const s=new Map;for(const n of Qo(t,e)){const i=Ee(n?.owner);i&&!s.has(i)&&s.set(i,n.owner)}return s.size===1?s.values().next().value:null}function di(t){return String(t||"").toLowerCase().replace(/[^a-z0-9]+/gu,"")}function fi(t,e){const s=di(t),n=di(e?.agentId);return!!(s&&n&&s===n)}function Ol(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&&fi(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&&fi(r,t))return{displayTitle:a,agentTitle:r}}return null}function _l(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 ls(t){const e=String(t?.title||"").trim(),s=Ol(t);if(!s)return e;const n=_l(s.displayTitle);return n?`${n.userTitle} · ${n.typeTitle} · ${s.agentTitle}`:`${s.displayTitle} · ${s.agentTitle}`}function Xo(t,e){const s=J(t?.sessionId);if(t?.isSystem)return`${St(t,e)} (${s})`;const n=ls(t);return n?n.includes(s)?n:`${n} (${s})`:`(${s})`}function pi(t,e={},s={},n=void 0){if(!e||e.all===!0)return!0;if(t?.isSystem)return e.includeSystem===!0;const i=Ee(n!==void 0?n:t?.owner);if(!i)return e.includeUnowned===!0;if(i===Ml)return e.includeSystem===!0;const o=Ee(s?.principal);return e.includeMe&&o&&i===o||e.includeShared===!0&&i!==o?!0:Array.isArray(e.ownerKeys)&&e.ownerKeys.includes(i)}function Jo(t,e={},s={},n=null){const i=yn(t,n||{});if(pi(t,e,s,i))return!0;if(!n)return!1;if(t?.isGroup)return Qo(t,n).some(a=>Jo(a,e,s,n));let o=t,r=0;for(;o?.parentSessionId&&r<16;){const a=n[o.parentSessionId];if(!a)return!1;if(pi(a,e,s))return!0;o=a,r+=1}return!1}function Rl(t){return(t||[]).map(e=>e?.text||"").join("")}function Sn(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 hi(t){const{childMap:e}=Sn(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 mi(t=[],e={}){const{parentMap:s}=Sn(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 bn(t={}){if(!t||typeof t!="object")return hi(t);const e=li.get(t);if(e)return e;const s=hi(t);return li.set(t,s),s}function wn(t=[],e={}){if(!Array.isArray(t))return mi(t,e);const s=ci.get(t);if(s)return s;const n=mi(t,e);return ci.set(t,n),n}function Zo(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 Vs(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 Ll(t){return t?.cronActive===!0&&t?.cronKind==="wall-clock"?{text:`[cron ${Vs(t.cronNextFireAt)}]`,color:"magenta"}:t?.cronActive===!0&&typeof t?.cronInterval=="number"?{text:`[cron ${kt(t.cronInterval)}]`,color:"magenta"}:null}function er(t){return!!(t&&!t.isSystem&&(t.isGroup||!t.parentSessionId&&!t.groupId))}function Fl(t,e){const s=[],n=kl(t);n&&s.push({text:n,color:Ot(t,e)});const i=An(t?.model,t?.reasoningEffort);i&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:i,color:"cyan"}));const o=Zr(t?.contextUsage);o&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:o.text,color:o.color}));const r=ea(t?.contextUsage);return r&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:r.text,color:r.color})),s}function $l(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:[]),c=new Set(Array.isArray(s.sessions?.selectedIds)?s.sessions.selectedIds:[]),d=!!s.sessions?.selectMode,f=c.has(t.sessionId),p=l.has(t.sessionId);if(d&&o.push({text:f?"[x] ":"[ ] ",color:f?"cyan":"gray",bold:f}),t.depth===0&&er(e)&&l.size>0&&(p&&!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 U=Yo(e,r);o.push({text:U?`${U} `:" ",color:Ot(e,r)})}const h=e?.isGroup?"cyan":e?.isSystem?"yellow":Ot(e,r),m=yn(e,s.sessions?.byId||{}),g=J(e?.sessionId),b=e?.updatedAt||e?.summaryUpdatedAt||e?.latestSummaryUpdatedAt||e?.createdAt||0,S=b?Su(b):"",w=An(e?.model,e?.reasoningEffort),I=e?.isSystem?St(e,s.branding?.title||"PilotSwarm"):ls(e),A=!!(e?.isSystem||e?.isGroup||I&&I.trim()),C=[...o];if(Nl(s)&&!e?.isSystem&&!e?.isGroup){const U=m?Pl(m):"?",W=Ee(s?.auth?.principal),Z=W&&Ee(m)===W;C.push({text:`[${U}] `,color:Z?"green":"cyan",bold:!0})}A?C.push({text:I,color:h,bold:!!(e?.isSystem||e?.isGroup)}):(C.push({text:g,color:h}),S&&(C.push({text:" · ",color:"gray"}),C.push({text:S,color:"gray"})),w&&(C.push({text:" · ",color:"gray"}),C.push({text:w,color:"green"})));const v=Zo(e?.sessionId,t,n,i);v&&C.push({text:` ${v.text}`,color:v.color,bold:v.bold});const T=Ll(e);T&&C.push({text:" ⏱",color:"magenta"});const M=[],O=e?.contextUsage?.compaction?.state,L=on(e?.contextUsage);e?.isGroup?e?.memberCount!=null&&M.push({text:`${e.memberCount}`,color:"gray"}):O==="running"?M.push({text:"⇊",color:"magenta"}):O==="failed"?M.push({text:"!",color:"red"}):L!=null?M.push({text:`${L}%`,color:L>=85?"red":L>=70?"yellow":"green"}):M.push({text:"—",color:"gray"});const H=[];e?.isGroup&&e?.memberCount!=null&&(H.push({text:`${e.memberCount} member${e.memberCount===1?"":"s"}`,color:"gray"}),S&&(H.push({text:" · ",color:"gray"}),H.push({text:S,color:"gray"})));const F=[],q=()=>{F.length&&F.push({text:" · ",color:"gray"})};if(e?.isGroup)F.push(...H);else{A&&(F.push({text:g,color:"cyan"}),S&&(q(),F.push({text:S,color:"gray"})),w&&(q(),F.push({text:w,color:"green"})));const U=e?.contextUsage;U&&Number.isFinite(U.currentTokens)&&Number.isFinite(U.tokenLimit)&&U.tokenLimit>0&&(q(),F.push({text:`ctx ${j(U.currentTokens)}/${j(U.tokenLimit)}`,color:"gray"}));const W=n?.[e?.sessionId];W&&(q(),F.push({text:`${W} child${W===1?"":"ren"}`,color:"gray"})),T&&(q(),F.push({text:T.text,color:T.color})),(e?.visibility==="shared_read"||e?.visibility==="shared_write")&&(q(),F.push({text:e.visibility==="shared_write"?"shared·write":"shared·read",color:"magenta"}))}return{runs:[...C,...A&&S&&!e?.isGroup?[{text:" ",color:"gray"},{text:S,color:"gray"}]:[],...M.length&&!e?.isGroup?[{text:" · ",color:"gray"},...M]:[],...e?.isGroup&&H.length?[{text:" ",color:"gray"},...H]:[]],titleRuns:C,ctxRuns:M,metaRuns:H,badgeRuns:[],selectedMetaRuns:F,detailRuns:F}}function tr(t){return String(t||"").trim().toLowerCase()}function Xe(t,e){const s=tr(e);return s?String(t||"").toLowerCase().includes(s):!0}function Bl(t){const e=t?.filterExceptionId||null,s=t?.byId||{};if(!e||!s[e])return null;const n=new Set([e]);let i=s[e],o=0;for(;i&&o<16;){let r=null;if(i.parentSessionId&&s[i.parentSessionId]?r=i.parentSessionId:!i.isGroup&&i.groupId&&s[`group:${i.groupId}`]&&(r=`group:${i.groupId}`),!r||n.has(r))break;n.add(r),i=s[r],o+=1}return n}function yt(t){const e=bn(t.sessions.byId),s=wn(t.sessions.flat,t.sessions.byId),n=tr(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:[]),l=Bl(t.sessions);return t.sessions.flat.map(c=>{const d=t.sessions.byId[c.sessionId],f=$l(c,d,t,e,s);return{sessionId:c.sessionId,text:Rl(f.runs),...f,depth:c.depth,status:d?.status,statusColor:Ot(d,t.connection?.mode||"local"),active:c.sessionId===t.sessions.activeSessionId,isSystem:!!d?.isSystem,isGroup:!!d?.isGroup,hasChildren:c.hasChildren,collapsed:c.collapsed,pinned:r.has(c.sessionId),selected:a.has(c.sessionId),canPin:er(d)}}).filter(c=>{if(l?.has(c.sessionId))return!0;const d=t.sessions.byId[c.sessionId];if(!Jo(d,i,o,t.sessions.byId))return!1;const f=yn(d,t.sessions.byId),p=f?`${gn(f,"")} ${f.email||""}`:"",h=`${d?.shortSummary||""} ${d?.summaryState?.intent||""} ${d?.summaryState?.summary||""}`;return Xe(c.text,n)||Xe(c.sessionId,n)||Xe(p,n)||Xe(h,n)})}function Ks(t,e=8){const s=yt(t);if(s.length===0)return[];const n=new Set(s.map(f=>f.sessionId)),i=(Array.isArray(t.sessions?.flat)?t.sessions.flat:[]).filter(f=>n.has(f.sessionId)),o=i.findIndex(f=>f.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),c=Math.min(i.length,l+e);c>i.length&&(c=i.length,l=Math.max(0,c-e));const d=i.slice(l,c);return bn(t.sessions.byId),wn(i,t.sessions.byId),s.filter(f=>d.some(p=>p.sessionId===f.sessionId))}function Ae(t){const e=t.sessions.activeSessionId;return e&&t.sessions.byId[e]||null}function Dl(t){const e=t.sessions?.navigationIntent;if(!e||e.status!=="failed")return null;const s=e.errorKind==="not_found"?"not_found":"network";return{sessionId:e.sessionId,errorKind:s,retryable:s==="network",message:s==="not_found"?"This session was not found or has not been shared with you.":"Could not load the linked session. Check your connection and try again."}}function Np(t){const e=t.sessions?.filterExceptionId||null;return!e||!t.sessions?.byId?.[e]?null:"Showing linked session outside your current filters."}function sr(t){return!t||t.isGroup?!1:(t.status||"")==="running"}function Hl(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(`
26
- `),time:"",createdAt:t.updatedAt||Date.now(),cardTitle:"Question",cardTitleColor:"cyan",cardBorderColor:"cyan"}}function Gl(t,e=[]){const s=t?.answeredPendingQuestion,n=String(s?.question||"").trim(),i=String(s?.answer||"").trim();if(!n||!i||nr(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}"
27
- The user responded: "${i}"`,time:"",createdAt:r,optimistic:!0,pendingPhase:o}}function Ul(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==="rejected"?"rejected":e.phase==="queued"?"queued":"pending"}:null}function nr(t,e){const s=String(e||"").trim();return s?(t||[]).some(n=>cn(n?.text||"")?.question?.trim()===s):!1}function jl(t){const e=String(t?.error||"").trim();if(!e)return null;const s=mn(t);if(!s)return null;const n=s==="failed",i=n?e:`${e}
28
-
29
- 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 gi(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 Wl(t){const e=String(t||"").replace(/\s+/g," ").trim();return e?e.replace(/^\[[^\]]+\]\s*/,"").replace(/^\[[^\]]+\]\s*/,"").trim():""}function Vl(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=Wl(o.text);if(r)return{...o,summaryText:r}}return null}function Kl(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(C=>C?.role==="user"||C?.role==="assistant"),r=o[o.length-1]||null,a=r?.role==="user",l=a&&r?.optimistic===!0,c=(n||[]).filter(C=>C?.phase==="pending").length,d=(n||[]).filter(C=>C?.phase==="queued").length,f=(n||[]).filter(C=>C?.phase==="cancelling").length,p=Array.isArray(e?.events)?e.events:[],h=gi(p,"user.message"),m=gi(p,"assistant.message"),g=h>m;if(i==="waiting"||i==="input_required"||!a&&!g&&i!=="running"&&!l)return null;const b=Math.max(h,m),S=p.filter(C=>C?.eventType==="assistant.reasoning"&&Number(C?.seq||0)>b),w=S[S.length-1]||null,I=String(w?.data?.content||w?.data?.text||w?.data?.message||"").trim();if(I)return{kind:"thinking",label:"Thinking",text:I,createdAt:w?.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:m,tokenSeq:w?.seq||0};const A=Vl(e,b);return A?.summaryText?{kind:i==="running"?"working":"sending",label:i==="running"?"Working":"Sending",text:A.summaryText,createdAt:A.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:m,tokenSeq:A.seq||0}:c>0?{kind:"pending",label:c===1?"Pending":`Pending ${c}`,text:c===1?"One prompt is waiting to be sent.":`${c} prompts are waiting to be sent.`,createdAt:n[n.length-1]?.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:m,tokenSeq:0}:d>0?{kind:"queued",label:d===1?"Queued":`Queued ${d}`,text:d===1?"One prompt is durably queued, waiting for the LLM to receive it.":`${d} 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}:f>0?{kind:"cancelling",label:f===1?"Cancelling":`Cancelling ${f}`,text:f===1?"One queued prompt is waiting for cancellation confirmation.":`${f} 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 In(t){const e=t.sessions.activeSessionId,s=e&&t.sessions.byId[e]||null;if(!e)return bs(t.branding);if(s?.isGroup){const c=Object.values(t.sessions.byId||{}).filter(h=>h&&!h.isGroup&&h.groupId===s.groupId&&!h.parentSessionId),d=h=>String(h??"").replace(/\|/g,"\\|").replace(/[\r\n]+/g," ").trim()||" ",f=c.map(h=>`| ${d(h.title||h.sessionId)} | ${d(h.status||"unknown")} | ${d(h.shortSummary||"")} |`),p=[`# ${s.title||s.groupId}`,s.shortSummary||"","","| Metric | Count |","|---|---:|",`| Members | ${s.memberCount??c.length} |`,`| Running | ${s.runningCount??0} |`,`| Waiting | ${s.waitingCount??0} |`,`| Completed | ${s.completedCount??0} |`,`| Failed | ${s.failedCount??0} |`,`| Cancelled | ${s.cancelledCount??0} |`,"","## Members",...f.length>0?["| Session | Status | Summary |","|---|---|---|",...f]:["_No top-level members._"]];return[{id:`group-details:${s.sessionId}`,role:"system",noChrome:!0,text:p.filter((h,m)=>m===1||String(h||"").length>0).join(`
30
- `),createdAt:s.updatedAt||Date.now()}]}if(t.ui?.chatViewMode==="summary")return ql(s);const n=t.history.bySessionId.get(e),i=n?.chat||[],o=s?.pendingQuestion?.question&&!nr(i,s.pendingQuestion.question)?Hl(s):null,r=Gl(s,i),a=jl(s);if((!n||i.length===0)&&!o&&!r&&!a)return bs(t.branding,s);const l=i.length>0?[...i]:bs(t.branding,s);return o&&l.push(o),r&&l.push(r),a&&l.push(a),l}function ql(t){const e=c=>{const d=String(c||"");return d.includes("\\n")?d.replace(/\\\\n/g,`
31
- `).replace(/\\n/g,`
32
- `):d},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=ls(t)||t?.title||t?.sessionId||"Session",o=[];o.push(`# ${i}`),o.push("");const r=[],a=Cl(t);if(a&&r.push(["Status",a]),s?.intent&&r.push(["Intent",String(s.intent)]),t?.summaryUpdatedAt){const c=ge(t.summaryUpdatedAt);c&&r.push(["Updated",c])}for(const[c,d]of r)o.push(`**${c}:** ${d}`);r.length>0&&o.push("");const l=e(s?.summary||t?.shortSummary||"").trim();if(l&&(o.push(l),o.push("")),n){const c=Object.entries(n).filter(([,d])=>d!=null&&!(typeof d=="string"&&!d.trim()));if(c.length>0){o.push("## State");for(const[d,f]of c)if(Array.isArray(f))if(f.length===0)o.push(`- **${d}:** _(empty)_`);else{o.push(`- **${d}:**`);for(const p of f.slice(0,16)){const h=typeof p=="string"?e(p):JSON.stringify(p);o.push(` - ${h}`)}}else if(f&&typeof f=="object"){o.push(`- **${d}:**`);for(const[p,h]of Object.entries(f).slice(0,16)){const m=typeof h=="string"?e(h):JSON.stringify(h);o.push(` - **${p}:** ${m}`)}}else o.push(`- **${d}:** ${e(String(f))}`);o.push("")}}for(const[c,d]of[["Blockers","blockers"],["Open Questions","openQuestions"],["Next Actions","nextActions"]]){const f=Array.isArray(s?.[d])?s[d].filter(Boolean).slice(0,12):[];if(f.length!==0){o.push(`## ${c}`);for(const p of f)o.push(`- ${typeof p=="string"?e(p):JSON.stringify(p)}`);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(`
33
- `),createdAt:t?.summaryUpdatedAt||t?.updatedAt||Date.now()}]}function zl(t){const e=t.sessions.activeSessionId;return e?Array.isArray(t.outbox?.bySessionId?.[e])?t.outbox.bySessionId[e].map(s=>Ul(e,s)).filter(Boolean):[]:[]}function ks(t,e="gray",s={}){return[{text:t,color:e,bold:!!s.bold,underline:!!s.underline}]}function Yl(t,e={}){const s=ge(t?.createdAt||t?.time),n=t?.sender,i=n?.kind==="user"?Ee(n):null,o=e?.viewerKey||null,r=e?.ownerKey||null,a=e?.sharedContext===!0,l=t?.role==="user",d=a&&l&&i&&!(l&&i&&o&&i===o),p=a&&l&&r&&(i&&i===r||!i&&o&&o===r)?" (owner)":"",h=l?(d?n.display||n.subject||"User":"You")+p:t?.role==="assistant"?"Agent":t?.role==="system"?"System":"PilotSwarm";let m=null,g=null;t?.pendingPhase==="pending"?(m="○",g="yellow"):t?.pendingPhase==="queued"?(m="✓",g="cyan"):t?.pendingPhase==="cancelling"||t?.pendingPhase==="rejected"?(m="x",g="red"):t?.role==="user"&&!t?.optimistic&&!t?.pendingPhase&&(t?.stopped?(m="⊘",g="yellow"):(m="✓✓",g="green"));const b=t?.pendingPhase==="pending"?"yellow":t?.pendingPhase==="queued"?"cyan":t?.pendingPhase==="cancelling"||t?.pendingPhase==="rejected"?"red":d?El:t?.role==="user"?vl:t?.role==="assistant"?"green":t?.role==="system"?"yellow":"white",S=s?`[${s}] `:"",w=[...ks(S,"gray")];return m&&w.push(...ks(`${m} `,g)),w.push(...ks(`${h}: `,b,{bold:!0})),w}function Ke(t){return Array.isArray(t)?(t||[]).map(e=>e?.text||"").join(""):t?.kind==="markdownTable"?"[table]":String(t?.text||"")}function ir(){return[{text:"",color:null}]}function Ql(t){const e=(t||[]).find(n=>Ke(n).trim().length>0);if(e?.kind==="markdownTable")return!0;const s=Ke(e).trimStart();return/^[┌│└]/.test(s)}function es(t){const e=Array.isArray(t)?[...t]:[];for(;e.length>0;){const s=e[0];if(Ke(s).trim().length>0)break;e.shift()}return e}function Xl(t){const e=String(t||"").replace(/\r\n/g,`
34
- `),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(`
35
-
36
- [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 Jl.test(s)?{leadingText:"",systemText:s}:null}const Jl=/^(?: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 or(t){const e=Xl(t);if(e){const r=[];e.leadingText&&r.push({kind:"text",text:e.leadingText});const a=We(e.systemText);return a&&r.push({kind:"system",text:a}),r}const s=String(t||"").replace(/\r\n/g,`
37
- `).split(`
38
- `),n=[];let i=[];function o(){i.length!==0&&(n.push({kind:"text",text:i.join(`
39
- `)}),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 p=We(l[1].trim());if(!p){r+=1;continue}n.push({kind:"system",text:p}),r+=1;continue}const c=[a.replace(/^\s*\[SYSTEM:\s*/i,"")];let d=-1;for(let p=r+1;p<s.length;p+=1){const h=s[p];if(h.trim()==="]"){d=p;break}if(/\]\s*$/.test(h.trim())){const m=h.replace(/\]\s*$/,"");m.trim()&&c.push(m),d=p;break}c.push(h)}if(d===-1){i.push(a),r+=1;continue}o();const f=We(c.join(`
40
- `).trim());if(!f){r=d+1;continue}n.push({kind:"system",text:f}),r=d+1}return o(),n}function Zl(t){return t?t?.role==="system"?!ln(t?.text||"")||!!We(t?.text||""):t?.role!=="user"&&t?.role!=="assistant"?!1:or(t?.text||"").some(e=>e.kind==="system"):!1}function yi(t){return Zl(t)?"system":t?.role||"other"}function rr(t,e){return!t||!e?!1:yi(t)!==yi(e)}function ec(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 tc(t,e=""){const s=ec(t);return{kind:"systemNotice",text:`${e?`[${e}] `:""}System: ${s}`,summary:s,body:at(t),color:"gray"}}function Si({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:at(s||r),color:i}}function sc(t){return t?.label?[{text:t.label,color:t.kind==="working"?"yellow":"cyan",bold:!0}]:null}function nc(t,e){return e?(t||[]).map(s=>Array.isArray(s)?s.map(n=>({...n,color:n?.color||e})):s):t}function ic(t){const e=(t||[]).find(s=>Ke(s).trim().length>0);return e?Ke(e).trimStart().startsWith("┌"):!1}function ts(t,e){!Array.isArray(e)||e.length===0||(t.length>0&&ic(e)&&Ke(t[t.length-1]).trim().length>0&&t.push([{text:"",color:null}]),t.push(...e))}function oc(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 rc(t,e,s){const n=Math.max(20,Number(s)||20),i=ge(e?.createdAt||e?.time),o=oc(t),r=a=>{const l=String(a||"").replace(/^session-/i,"");return J(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((c,d)=>d===2||c).join(`
41
- `);return[Si({title:`Sub-agent Response — ${a}`,summary:o.status||"completed",timestamp:i,body:l,color:"cyan"})]}if(o?.kind==="subAgentMulti"){const a=o.agents.map(c=>{const d=r(c.agentId),f=c.task?`**Task:** ${c.task}`:"",p=c.status?`**Status:** ${c.status}`:"";return`${[`### ${d}`,f,p].filter(Boolean).join(`
42
- `)}
43
-
44
- ${c.result||"_(no result)_"}`}),l=o.agents.map(c=>`${r(c.agentId)} ${c.status||"completed"}`).join(" · ");return[Si({title:`Sub-agent Responses (${o.agents.length})`,summary:l,timestamp:i,body:a.join(`
45
-
46
- ---
47
-
48
- `),color:"cyan"})]}return ne({title:"System",timestamp:i,body:t,width:n,titleColor:"yellow",borderColor:"gray",bodyColor:"gray",fitToContent:!0})}function ac(t,e){const s=Math.max(12,Math.min(72,Number(e)||12)),n=Math.max(1,s-4),i=ge(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((p,h)=>p+String(h?.text||"").length,0),c=Math.max(0,s-l-3),d=String(t?.text||"").trim()?es(mt(at(t.text),{width:n})).flatMap(p=>To(p,n)):[],f=[[{text:"┌─",color:"gray"},...a,{text:`${"─".repeat(c)}┐`,color:"gray"}]];for(const p of d)f.push([{text:"│ ",color:"gray"},...Ao(p.map(h=>({...h,color:h?.color&&h.color!=="white"?h.color:"gray"})),n),{text:" │",color:"gray"}]);return f.push([{text:`└${"─".repeat(Math.max(1,s-2))}┘`,color:"gray"}]),f.push([{text:"",color:null}]),f}function lc(t){return String(t||"").split(`
49
- `).reduce((e,s)=>Math.max(e,rn(s).length),0)}function ss(t,e,s={}){if(t?.splash){const c=t.mobileText&&lc(t.text)>e;return[{kind:"markup",value:c?t.mobileText:t.text,splashAlt:!c&&t.mobileText?t.mobileText:null}]}if(t?.thinking)return ac(t,e);if(t?.noChrome)return es(mt(at(t?.text||""),{width:Math.max(20,e),tableMode:s.tableMode}));if(t?.role==="user"){const c=cn(t?.text||"");if(c)return[...ne({title:"Question",timestamp:ge(t?.createdAt||t?.time),body:c.question,width:Math.max(20,e),titleColor:Cs,borderColor:Cs,tableMode:s.tableMode}),...ss({...t,text:c.answer},e,s)]}if(s.allowLeadingSystemNotices!==!1&&(t?.role==="user"||t?.role==="assistant")){const c=or(t?.text||"");if(c.some(d=>d.kind==="system")){const d=[];let f=!1;for(const h of c)h.kind!=="system"&&h.text.trim()&&(ts(d,ss({...t,text:h.text},e,{...s,allowLeadingSystemNotices:!1,skipPrefix:f})),f=!0);if(d.length>0)return d;const p=[];for(const h of c)h.kind!=="system"||!h.text.trim()||ts(p,rc(h.text,t,e));if(p.length>0)return p}}if(t?.role!=="user"&&t?.role!=="assistant"){const c=We(t?.text||"");if(t?.role==="system"&&!c)return[];const d=!!t?.cardTitle&&String(t.cardTitle).toLowerCase()!=="system";if(t?.role==="system"&&!d)return[tc(c||t?.text||"",ge(t?.createdAt||t?.time))];const f=t?.role==="system"&&(!t?.cardTitle||String(t.cardTitle).toLowerCase()==="system");return ne({title:t?.cardTitle||(t?.role==="system"?"System":"PilotSwarm"),timestamp:ge(t?.createdAt||t?.time),body:at(t?.text||""),width:Math.max(20,e),titleColor:t?.cardTitleColor||(t?.role==="system"?"yellow":"cyan"),borderColor:t?.cardBorderColor||"gray",tableMode:s.tableMode,...f?{bodyColor:"gray",fitToContent:!0}:{}})}const n=es(mt(at(t?.text||""),{width:e,tableMode:s.tableMode})),i=nc(n,t?.pendingPhase==="cancelling"?"red":t?.role==="user"?Cs:null),o=s.skipPrefix?[]:Yl(t,s),r=cc(t,s);if(i.length===0){const c=o.length>0?[o]:[];return r.length>0?[...c,...r]:c}if(Ql(i)){const c=o.length>0?[o,...i]:i;return r.length>0?[...c,...r]:c}const a=[];let l=o.length===0;for(const c of i){if(!Array.isArray(c)){l||(a.push(o),l=!0),a.push(c);continue}l?a.push(c):(a.push([...o,...c]),l=!0)}return a.push(...r),a}function cc(t,e={}){const s=Array.isArray(t?.attachments)?t.attachments:[];return s.length===0?[]:e.tableMode==="sentinel"?[{kind:"imageAttachments",sessionId:String(t?.id||"").split(":")[0]||null,attachments:s}]:s.map(n=>{const i=Number(n?.sizeBytes)||0,o=i>=1024*1024?`${(i/(1024*1024)).toFixed(1)} MB`:i>=1024?`${Math.round(i/1024)} KB`:`${i} B`;return[{text:" ",color:null},{text:`[image: ${n.filename}${i>0?` · ${o}`:""}]`,color:"cyan"}]})}const uc=new Set(["assistant.usage","session.info","session.idle","session.usage_info","pending_messages.modified","pending_messages.cancelled","abort","assistant.turn_start","assistant.turn_end","assistant.streaming_progress","session.turn_completed","tool.execution_partial_result","tool.execution_progress"]);function dc(t){const e=Math.max(0,Math.floor((Number(t)||0)/1e3));if(e<60)return`${e}s`;const s=Math.floor(e/60),n=e%60;if(s<60)return`${s}m ${String(n).padStart(2,"0")}s`;const i=Math.floor(s/60),o=s%60;return`${i}h ${String(o).padStart(2,"0")}m`}const fc=new Set(["read_facts","facts_search","facts_similar","facts_read_uncrawled","facts_tombstone_stats"]),pc=new Set(["store_fact","delete_fact","facts_set_crawled","facts_purge_tombstones","facts_force_purge"]);function hc(t,e){const s=String(t||"").toLowerCase();return s==="search_skills"||s.includes("skill")?e?"loading skills…":"loaded skills":fc.has(s)?e?"reading facts…":"read facts":pc.has(s)?e?"writing facts…":"wrote facts":s.startsWith("graph_")?/upsert|delete|archive|merge|remove|set_/.test(s)?e?"writing to the graph…":"wrote to the graph":e?"reading the graph…":"read the graph":s.startsWith("facts_")||s.endsWith("_fact")||s.endsWith("_facts")?/store|write|set|delete|purge|update/.test(s)?e?"writing facts…":"wrote facts":e?"reading facts…":"read facts":""}function mc(t){const e=String(t?.eventType||"");if(e==="tool.execution_start"||e==="tool.execution_complete"){const n=(String(t?.text||"").replace(/^\s*\d{1,2}:\d{2}(?::\d{2})?\s*/,"").replace(/^\[[^\]]+\]\s*/,"").replace(/^[^A-Za-z0-9_]+/,"").trim().match(/^[A-Za-z0-9_.:-]+/)||[""])[0];if(!n)return"running tools…";const i=hc(n,e==="tool.execution_start");if(i)return i;const o=n.length>28?`${n.slice(0,27)}…`:n;return e==="tool.execution_start"?`running tool: ${o}…`:`finished tool: ${o}`}switch(e){case"skill.invoked":return"loading skills…";case"learned_skill.read":return"loading skills…";case"skills.searched":return"loading skills…";case"facts.searched":case"facts.similar":return"reading facts…";case"graph.searched":case"graph.node_searched":case"graph.node_loaded":return"reading the graph…";case"graph.namespace_mutated":return"writing to the graph…";case"assistant.reasoning":return"thinking…";case"assistant.intent":return"planning…";case"assistant.message_start":case"assistant.message":return"writing reply…";case"session.compaction_start":return"compacting context…";case"session.compaction_complete":return"context compacted";case"session.dehydrated":return"dehydrating…";case"session.hydrated":case"session.rehydrated":return"rehydrating…";case"session.agent_spawned":return"coordinating agents…";case"session.wait_started":return"waiting…";case"session.input_required_started":return"awaiting input…";case"session.lossy_handoff":return"moving to a new worker…";case"session.error":return"recovering from an error…";default:return""}}function xn(t,e={}){if(t?.ui?.chatViewMode==="summary")return[];const s=Ae(t);if(!s||s.isGroup)return[];if(String(s?.status||"").toLowerCase()!=="running")return[];const i=t.history?.bySessionId?.get(s.sessionId)||null,o=Array.isArray(i?.chat)?i.chat:[];let r=0;for(let w=o.length-1;w>=0;w-=1)if(o[w]?.role==="user"){r=Number(o[w]?.createdAt||0);break}const a=Array.isArray(i?.activity)?i.activity:[];let l=0,c=0;for(let w=a.length-1;w>=0;w-=1){const I=a[w],A=I?.eventType,C=Number(I?.createdAt||0);if(!l&&A==="assistant.turn_start"&&(l=C),!c&&(A==="assistant.turn_end"||A==="session.turn_completed")&&(c=C),l&&c)break}let d=0;r>c?d=r:l>c&&(d=l);let f=null;for(let w=a.length-1;w>=0;w-=1){const I=a[w];if(!(!I||uc.has(I.eventType))){if(Number(I.createdAt||0)<=c)break;f=I;break}}const p=Number.isFinite(e.now)?e.now:Date.now(),h=d>0?dc(p-d):"",m=String(e.spinnerFrame||"").trim()||"●",g=f?mc(f):"",b=[{text:`${m} `,color:"cyan"},{text:"Working",color:"cyan"},...h?[{text:` · ${h}`,color:"gray"}]:[],...g?[{text:` — ${g}`,color:"gray"}]:[]],S=Math.max(24,Math.min(120,Math.floor(Number(e.maxWidth)||80)));return[Q(b,S)]}function vn(t,e=80,s={}){const n=In(t);if(!n||n.length===0)return[{text:"No messages yet.",color:"gray"}];const i=Ee(t?.auth?.principal),o=t?.sessions?.activeSessionId,r=o?t?.sessions?.byId?.[o]:null,a=Ee(r?.owner),l=!!(r&&(r.visibility&&r.visibility!=="private"||a&&i&&a!==i)),c={...s?.tableMode?{tableMode:s.tableMode}:{},...i?{viewerKey:i}:{},...a?{ownerKey:a}:{},...l?{sharedContext:!0}:{}},d=[];for(const[f,p]of n.entries()){const h=ss(p,e,c);ts(d,h);const m=n[f+1];m&&rr(p,m)&&Ke(d[d.length-1]).trim().length>0&&d.push(ir())}return d.length>0?d:[{text:"No messages yet.",color:"gray"}]}function En(t,e=80,s={}){const n=zl(t);if(!n||n.length===0)return[];const i=Math.max(20,Number(e)||80),o=n.filter(g=>g.pendingPhase==="queued").length,r=n.filter(g=>g.pendingPhase==="pending").length,a=n.filter(g=>g.pendingPhase==="cancelling").length,l=n.filter(g=>g.pendingPhase==="rejected").length,c=[];r>0&&c.push(`${r} pending`),o>0&&c.push(`${o} queued`),a>0&&c.push(`${a} cancelling`),l>0&&c.push(`${l} rejected`);const f=` queued prompts: ${c.length>0?c.join(" · "):"queued prompts"} `,p=Math.max(1,i-f.length),h=[[{text:f,color:"gray"},{text:"─".repeat(p),color:"gray"}]],m=s?.tableMode?{tableMode:s.tableMode}:{};for(const[g,b]of n.entries()){ts(h,ss(b,i,m));const S=n[g+1];S&&rr(b,S)&&Ke(h[h.length-1]).trim().length>0&&h.push(ir())}return h}function gc(t){const e=In(t),s=[],n=new Set;for(const i of e||[])for(const o of fa(i?.text||"")){const r=`${o.sessionId}/${o.filename}`;n.has(r)||(n.add(r),s.push(o))}return s}function yc(t){const e=In(t),s=[],n=new Set;for(const i of e||[])for(const o of pa(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 An(t,e){const s=vo(t);if(!s)return"";const n=String(e||"").trim();return n?`${s}:${n}`:s}function Sc(t){return vo(t)||"(unknown)"}function ar(t,e={}){const s=Ae(t),n=t.sessions?.byId||{},i=Array.isArray(t.sessions?.flat)?t.sessions.flat:[],o=bn(n),r=wn(i,n),a=Vo(e?.width);if(!s)return{color:"cyan",title:Pe("Chat","cyan"),titleRight:null,animateTitleRight:!1};const l=J(s.sessionId),c=s.isSystem?"yellow":"cyan",d=Pe(s.isSystem?`⚙ ${St(s,t.branding?.title||"PilotSwarm")}`:ls(s)||"Chat",c),f=i.find(A=>A.sessionId===s.sessionId),p=Zo(s.sessionId,f,o,r);p&&d.push({text:` ${p.text}`,color:p.color}),a||d.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:Kl(s,h,h?.chat||[],m),b=t.connection?.mode||"local",S=Fl(s,b),w=sc(g),I=w?[...S,...S.length?[{text:" · ",color:"gray"}]:[],...w]:S;return{color:s.isSystem?"yellow":"cyan",title:d,titleRight:I.length?I:null,animateTitleRight:!!g}}function bc(t){const e=t.sessions.activeSessionId;return e?t.history.bySessionId.get(e)?.activity||[]:[]}function Tn(t,e=12){const s=bc(t),n=Ae(t),i=Pe("Activity","gray");return n?.isGroup?{title:i,disabled:!0,lines:[{text:Sr,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 lr(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 cr(t,e){return t==="orchestration"?"magenta":t==="activity"?"cyan":lr(e)}function wc(t){return t==="raw"?"raw summary":"pretty text"}function Ic(t){return t?.sessionId?`session-${t.sessionId}`:null}function xc(t,e){const s=Array.isArray(t.logs?.entries)?t.logs.entries:[],n=t.logs?.filter||{},i=Ic(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 vc(t){const e=cs(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:cr(t?.category,t?.level)},{text:`${e} `,color:"white",bold:!0},...s?[{text:`[${J(s)}] `,color:"gray"}]:[],{text:`${n} `,color:lr(t?.level),bold:!0},{text:t?.rawLine||t?.message||"",color:"white"}]}function Ec(t){const e=t?.sessionId||(String(t?.orchId||"").startsWith("session-")?String(t.orchId).slice(8):"");return[{text:`${e?`[${J(e)}] `:""}${t?.prettyMessage||t?.message||t?.rawLine||""}`,color:cr(t?.category,t?.level),bold:String(t?.level||"").toLowerCase()==="warn"||String(t?.level||"").toLowerCase()==="error"}]}function Ac(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:wc(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=xc(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"?vc(r):Ec(r))]}function bi(t){return/\.(md|markdown|mdown|mkd|mdx)$/i.test(String(t||""))}function Tc(t){return/\.(json|jsonl)$/i.test(String(t||""))}function Cc(t){return ve.map(e=>({text:e===t?`[${e}] `:`${e} `,color:e===t?"magenta":"gray",bold:e===t}))}function kc(t=""){const e=String(t||"").split(`
50
- `);return e.length>0?e.map(s=>({text:s,color:"white"})):[{text:"",color:"white"}]}function wi(t,{selected:e=!1,width:s=24,label:n=null}={}){const i=Math.max(8,s),o=bi(t)?"# ":Tc(t)?"{ ":"• ",r=ur(`${o}${n||t}`,i).padEnd(i," ");return e?Ce(r):{text:r,color:bi(t)?"cyan":"white",bold:!1}}function we(t){return t.files?.filter?.scope==="allSessions"?"allSessions":"selectedSession"}function Mc(t,e={}){if(!t)return new Set;const{childMap:s}=Sn(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 ns(t,e=we(t)){const s=Ae(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=Mc(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 _t(t){const e=we(t);Ae(t)?.sessionId;const s=t.files?.filter?.query||"",n=ns(t,e),i=e==="allSessions"||n.length>1,o=[];for(const r of n){const a=Jt(t.files?.bySessionId?.[r]?.entries);for(const l of a){const c=l.filename;o.push({id:`${r}/${c}`,sessionId:r,filename:c,entry:l,label:i?`[${J(r)}] ${c}`:c})}}return o.filter(r=>Xe(r.filename,s)||Xe(r.sessionId,s)||Xe(r.label,s))}function Ue(t){const e=_t(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(we(t)==="allSessions"){const r=Ae(t)?.sessionId||null,a=r&&t.files?.bySessionId?.[r]?.selectedFilename||null;if(r&&a){const l=e.find(c=>c.sessionId===r&&c.filename===a);if(l)return l}return e[0]}const i=Ae(t)?.sessionId||null,o=i&&t.files?.bySessionId?.[i]?.selectedFilename||null;return e.find(r=>r.sessionId===i&&r.filename===o)||e[0]}function Cn(t,e={}){const s=Ae(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=we(t),l=t.files?.filter?.query||"",c=_t(t),d=Ue(t),f=d?.filename||null,p=Math.max(0,c.findIndex(F=>F.id===d?.id)),h=d?.sessionId&&f&&t.files?.bySessionId?.[d.sessionId]?.previews?.[f]||null,m=h||d?.entry||null,g=s?J(s.sessionId):"",b=ns(t,a),S=a!=="allSessions"&&b.some(F=>F&&F!==r),w=[...new Set([...Array.isArray(t.sessions?.flat)?t.sessions.flat.map(F=>F?.sessionId||F):[],...Object.keys(t.files?.bySessionId||{})])].filter(Boolean),I=a==="allSessions"&&w.some(F=>!t.files?.bySessionId?.[F]?.loaded||t.files?.bySessionId?.[F]?.loading),A=a==="allSessions"&&w.map(F=>t.files?.bySessionId?.[F]?.error).find(Boolean)||null,C=[Cc("files"),...s||a==="allSessions"?[]:[{text:"No session selected.",color:"gray"}]];if(a==="allSessions")I&&c.length===0?C.push({text:"Loading exported files across all sessions…",color:"gray"}):A&&c.length===0?C.push({text:A,color:"red"}):c.length===0?(C.push({text:l?`No artifacts matched "${l}" across any session.`:"No exported files across any session yet.",color:"gray"}),C.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"})):C.push(...c.map((F,q)=>wi(F.filename,{selected:q===p,width:n,label:F.label})));else if(s){const F=r?t.files?.bySessionId?.[r]:null;Array.isArray(F?.entries)&&F.entries;const q=c.filter(Y=>b.includes(Y.sessionId));F?.loading?C.push({text:"Loading exported files…",color:"gray"}):F?.error?C.push({text:F.error,color:"red"}):q.length===0&&b.every(Y=>{const U=t.files?.bySessionId?.[Y]?.entries;return!Array.isArray(U)||U.length===0})?(C.push({text:l?`No artifacts matched "${l}" for this ${S?"session tree":"session"}.`:`No exported files for this ${S?"session tree":"session"} yet.`,color:"gray"}),C.push({text:l?"Clear the query or upload an artifact to this session.":S?"Artifacts exported by this session or any child session will appear here.":"Agents must write/export artifacts before they appear here.",color:"gray"})):C.push(...q.map((Y,U)=>wi(Y.filename,{selected:U===p,width:n,label:Y.label})))}let v,T;!s&&a!=="allSessions"?(T=[{text:"Preview",color:"cyan",bold:!0}],v=[{text:"No session selected.",color:"gray"}]):f?h?.loading?(T=[{text:`Preview: ${f}`,color:"cyan",bold:!0},...(a==="allSessions"||d?.sessionId&&d.sessionId!==r)&&d?.sessionId?[{text:` · ${J(d.sessionId)}`,color:"gray"}]:[]],v=[{text:"Loading file preview…",color:"gray"}]):h?.error?(T=[{text:`Preview: ${f}`,color:"cyan",bold:!0},...(a==="allSessions"||d?.sessionId&&d.sessionId!==r)&&d?.sessionId?[{text:` · ${J(d.sessionId)}`,color:"gray"}]:[]],v=[{text:h.error,color:"red"}]):(T=[{text:`Preview: ${f}`,color:"cyan",bold:!0},...(a==="allSessions"||d?.sessionId&&d.sessionId!==r)&&d?.sessionId?[{text:` · ${J(d.sessionId)}`,color:"gray"}]:[],...h?.renderMode==="markdown"?[{text:" [md]",color:"gray"}]:h?.isBinary===!0?[{text:" [file]",color:"gray"}]:h?.renderMode==="note"?[{text:" [note]",color:"gray"}]:[]],v=h?.renderMode==="markdown"?es(mt(h?.content||"",{width:i})):kc(h?.content||"")):(T=[{text:"Preview",color:"cyan",bold:!0}],v=[{text:"Select a file to preview it here.",color:"gray"}]);const M=a==="allSessions"?"Files: all sessions":s?`Files: ${g}${S?" tree":""}`:"Files",O=a==="allSessions"?"all sessions":s?`${g}${S?" tree":""}`:"Files",L=a==="allSessions"?`Artifacts${c.length>0?` [${c.length}]`:""}`:`Artifacts${S?" tree":""}${c.length>0?` [${c.length}]`:""}`,H=l?` · @${l}`:"";return{panelTitle:[{text:`${M}${H}`,color:"magenta",bold:!0}],panelTitleMobile:[{text:`${O}${H}`,color:"magenta",bold:!0}],listTitle:[{text:`${L}${H}`,color:"cyan",bold:!0}],listLines:C,listBodyLines:C.slice(1),selectedIndex:p,selectedFilename:f,selectedSessionId:d?.sessionId||null,scope:a,previewTitle:T,previewLines:v,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:M,color:"magenta",bold:!0},...f?[{text:" · ",color:"gray"},{text:f,color:"cyan",bold:!0}]:[],...o?[{text:" [f filter] [u upload] [a download] [x delete] [o open] [v/esc close fullscreen]",color:"gray"}]:[]]}}function Pc(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=e.systemGhcpKey||{supported:!1,loading:!1,configured:!1,changedBy:null,changedAt:null,error:null},r=!!s?.isAdmin,a=r&&!!n.storeAsSystem,l=a?!!o.configured:!!s?.githubCopilotKeySet,c=a?"System key":"key",d=o.configured&&o.changedBy?` (set by ${o.changedBy})`:"",f=n.saving?"Saving...":n.editing?"Editing — Enter to save, Esc to cancel":a?o.configured?`System key configured — ownerless system sessions use it for GitHub Copilot models${d}`:"System key not configured — ownerless system sessions fall back to env GITHUB_TOKEN":s?.githubCopilotKeySet?"Configured (overrides env GITHUB_TOKEN for this user)":"Not configured (using env GITHUB_TOKEN fallback)",p=[];return n.editing?(p.push({id:"save",label:"Save",key:"Enter"}),p.push({id:"cancel",label:"Cancel",key:"Esc"})):(p.push({id:"edit",label:l?`Replace ${c}`:`Set ${c}`,key:"e"}),l&&p.push({id:"clear",label:`Clear ${c}`,key:"c"}),p.push({id:"refresh",label:"Refresh",key:"r"})),p.push({id:"close",label:"Close console",key:n.editing?"Ctrl+Esc":"Esc"}),{visible:!!e.visible,loading:!!e.loading,loadError:e.loadError||null,principal:i,isAdmin:r,ghcpKey:{configured:!!s?.githubCopilotKeySet,targetConfigured:l,storeAsSystem:a,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:f},systemGhcpKey:{supported:!!o.supported,loading:!!o.loading,configured:!!o.configured,changedBy:o.changedBy||null,changedAt:o.changedAt||null,error:o.error||null},actions:p}}function Nc(t){const e=t.ui.focusRegion,s=t.ui.fullscreenPane||null,n=Ae(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(w=>w?.phase==="pending"),l=t.ui.promptEdit?.sessionId===n?.sessionId,c=l&&t.ui.promptEdit?.phase==="queued",d=l&&t.ui.promptEdit?.phase==="cancelling",f=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==="shareSession")return{left:"Share the selected session",right:"name [r|w] grants · -name revokes · enter apply · esc close"};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 p=!!t.sessions?.selectMode,h=Array.isArray(t.sessions?.selectedIds)?t.sessions.selectedIds.length:0;if(p&&e===E.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",b={[E.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 · v visibility · S share · [/] resize pane · {/} columns · T themes · ? help · a linked items · drag copy · tab next pane · p prompt",[E.CHAT]:`${g} · j/k scroll · ctrl-u/ctrl-d page · e older history · g/G top/bottom · d done · ${f} · [/] resize pane · {/} columns · T themes · ? help · a linked items · drag copy · tab next pane · p prompt`,[E.INSPECTOR]:t.ui.inspectorTab==="logs"?`j/k scroll · ctrl-u/ctrl-d page · g/G top/bottom · d done · t tail · f filter · ${f} · left/right tab · [/] resize pane · {/} columns · T themes · ? help · 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 · ${f} · left/right tab · [/] resize pane · {/} columns · T themes · ? help · 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 · [/] resize pane · {/} columns · T themes · ? help · 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 · [/] resize pane · {/} columns · T themes · ? help · 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 · ${f} · left/right tab · [/] resize pane · {/} columns · T themes · ? help · m next tab · tab next pane`:t.ui.inspectorTab==="sequence"?`j/k turn · enter expand · ctrl-u/ctrl-d page · g/G top/bottom · d done · ${f} · left/right tab · [/] resize pane · {/} columns · T themes · ? help · m next tab · tab next pane`:`j/k scroll · ctrl-u/ctrl-d page · g/G top/bottom · d done · ${f} · left/right tab · [/] resize pane · {/} columns · T themes · ? help · h/l focus · a linked items · drag copy · m next tab · tab next pane`,[E.ACTIVITY]:`j/k scroll · ctrl-u/ctrl-d page · g/G top/bottom · d done · ${f} · [/] resize pane · {/} columns · T themes · ? help · a linked items · drag copy · h left · tab next pane`,[E.PROMPT]:i?`type answer · enter reply · alt-enter newline · T themes · ? help · arrows move · alt-left/right word · alt-delete word · @ artifacts · @@ sessions · ${s?"esc pane":"esc sessions"}`:l?c?`queued prompt selected · d delete · up/down cycle queued · enter/esc new prompt · ${s?"esc pane":"esc sessions"}`:d?`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 · ? help · arrows move · alt-left/right word · alt-delete word · @ artifacts · @@ sessions · ${s?"esc pane":"esc sessions"}`};let S=b[e]||b[E.SESSIONS];return sr(Ae(t))&&(S=`ctrl-x stop · ${S}`),{left:t.ui.statusText,right:S}}function et(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 Oe(t){return Array.from(String(t||"")).length}function ur(t,e){const s=String(t||"");return e<=0?"":Oe(s)<=e?s:e===1?Array.from(s)[0]||"":`${Array.from(s).slice(0,e-1).join("")}…`}function Ve(t,e){const s=ur(t,e),n=Math.max(0,e-Oe(s));return s+" ".repeat(n)}function G(t,e="white",s={}){return{text:String(t||""),color:e,...s}}function le(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 Ii(t,e){const s=Number(t),n=Number(e);if(!Number.isFinite(s)||!Number.isFinite(n)||s<=0||n<=0)return null;const i=s/n;return`${i>=10?i.toFixed(0):i.toFixed(1)}×`}function dr(t,e=18){const s=String(t||"").replace(/\s+/g," ").trim();return s?Oe(s)>e?`${Array.from(s).slice(0,Math.max(1,e-1)).join("")}…`:s:""}function Oc(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 fr(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 _c(t,e=""){return fr([t?.data?.reason==="cron_at"?"cron":t?.data?.reason,t?.data?.detail,t?.data?.message,t?.data?.error,e])}function Rc(t,e=""){return fr([t?.data?.message,t?.data?.detail,t?.data?.error,e])}function cs(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 Lc=300*1e3,Fc="last 5m";function kn(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-Lc,endMs:e,label:Fc}}function $c(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 pr(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 Bc=new Set(["wait","timer","cron_start","cron_fire","cron_cancel","spawn","cmd_recv","cmd_done"]);function Dc(t){return Bc.has(t)}function Hc(t){const e=ge(t?.createdAt),s=cs(t?.workerNodeId),n=Oc(t),i=dr(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 ${kt(t?.data?.seconds??0)}`};case"session.wait_completed":return{...r,type:"timer",color:"yellow",detail:`${kt(t?.data?.seconds??0)} up`};case"session.lossy_handoff":{const a=Rc(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 ${_c(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||J(t?.data?.childSessionId)||"agent"}`};case"session.cron_started":return{...r,type:"cron_start",color:"magenta",detail:`cron ${kt(t?.data?.intervalSeconds??0)}`};case"session.cron_at_scheduled":case"session.cron_at_started":return{...r,type:"cron_start",color:"magenta",detail:`cron ${Vs(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 ${Vs(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 hr(t=[]){const e=[];for(const s of t||[]){const n=Hc(s);n&&e.push({...n,nodeLabel:Dc(n.type)?"orch":n.nodeLabel||"orch"})}return e}function Gc(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 Uc(t){const e=String(t?.error||"").trim();if(!e)return null;const s=mn(t);if(!s)return null;const n=t?.updatedAt?Number(t.updatedAt):Date.now(),i=Number.isFinite(n)?n:Date.now();return{time:ge(i),createdAtMs:i,nodeLabel:"orch",color:s==="failed"?"red":"yellow",detail:`${s==="failed"?"ERR":"WARN"} ${dr(e,20)||(s==="failed"?"error":"warning")}`,type:s==="failed"?"error":"warning"}}function jc(t,e){const s=Uc(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 Wc(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=hr(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 Vc(t,e){const s=new Set;for(const n of t.history.bySessionId.values())for(const i of n?.events||[]){if(!pr(i,e))continue;const o=cs(i?.workerNodeId);o&&s.add(o)}return Array.from(s).sort((n,i)=>n.localeCompare(i))}function Kc(t,e,s){const n=[{text:Ve("TIME",e),color:"white",bold:!0},{text:" ",color:null}];return t.forEach((i,o)=>{o>0&&n.push({text:" ",color:null}),n.push({text:Ve(i,s),color:"white",bold:!0})}),n}function qc(t,e,s){return G(`${"-".repeat(e)} ${t.map(()=>"─".repeat(s)).join(" ")}`,"gray")}function zc(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=le(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(le(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))]:ne({title:"Stats",body:i,width:Math.max(24,s),titleColor:"cyan",borderColor:"gray",fitToContent:!0}).slice(0,-1)}function Yc(t,e,s,n){const i=e.includes(t.nodeLabel)?t.nodeLabel:e.includes("…")?"…":e[e.length-1],o=[{text:Ve(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:Ve(t.detail||"",n),color:t.color||"white",bold:!!t.bold,underline:!!t.underline,...t.completedTurn!=null?{completedTurn:t.completedTurn}:{}}):o.push({text:Ve("│",n),color:"gray"})}),o}function Qc(t,e){const s=[];return t.forEach((n,i)=>{i>0&&s.push({text:" ",color:null}),s.push({text:Ve(n,e),color:"white",bold:!0})}),s}const Xc=new Set(["none","minimal","low","medium","high","xhigh","max"]);function Jc(t){const e=String(t||"").trim();if(!e)return"unknown";const s=e.split(":").filter(Boolean);if(s.length===0)return"unknown";const n=String(s[s.length-1]).toLowerCase(),i=s.length>1&&Xc.has(n)?s.length-2:s.length-1;return s[Math.max(0,i)]||s[0]||"unknown"}function xi(t){const e=Number(t||0);if(!Number.isFinite(e))return"?K";const s=e/1e3;return`${s.toFixed(Math.abs(s)>=10?1:2)}K`}function Qe(t){return Number(t||0).toLocaleString("en-US")}function Zc(t){const e=new Map;for(const s of t||[]){if(s?.eventType!=="session.turn_completed")continue;const n=Number(s?.data?.turnIndex??s?.data?.iteration);Number.isFinite(n)&&e.set(n,s.data||{})}return e}function eu(t,{expanded:e,selected:s,maxWidth:n}){const i=e?"v":">",o=Jc(t?.model),r=t?.durationMs!=null?`${(Number(t.durationMs)/1e3).toFixed(1)}s`:"n/a",a=`${i} Mod: ${o} tok ${xi(t?.tokensInput)}/${xi(t?.tokensOutput)} dur ${r}`,l=[];if(s?l.push(Ce(Ve(a,Math.max(18,n)))):l.push([{text:a,color:"magenta"}]),e){const c=[["model",t?.reasoningEffort?`${t?.model||"(unknown)"}:${t.reasoningEffort}`:t?.model||"(unknown)"],["duration",t?.durationMs!=null?`${Qe(t.durationMs)} ms`:null],["tokens",`${Qe(t?.tokensInput)} in / ${Qe(t?.tokensOutput)} out`],["cache",`${Qe(t?.tokensCacheRead)} read / ${Qe(t?.tokensCacheWrite)} write`],["tools",`${Qe(t?.toolCalls)} calls / ${Qe(t?.toolErrors)} errors`],["names",Array.isArray(t?.toolNames)&&t.toolNames.length?t.toolNames.join(", "):null],["worker",t?.workerNodeId||null],["result",t?.resultType||null],["error",t?.errorMessage||null]].filter(([,d])=>d!=null&&d!=="");for(const[d,f]of c)l.push([{text:` ${d}: `,color:"gray"},{text:String(f),color:"white"}])}return l}function tu(t,e,s,n={}){const i=!!n?.allowWideColumns,o=zc(t,e,s),r=t.history.bySessionId.get(e.sessionId),a=jc(Gc(hr(r?.events||[])),e);if(a.length===0)return{stickyLines:o,lines:[G("No events yet - interact with this session to populate the sequence diagram.")]};const l=kn(t),c=a.filter(O=>$c(O,l)),d=(c.length>0?c:a).slice(-48),f=Wc(t,l.startMs,l.endMs),p=Array.from(new Set(d.map(O=>O.nodeLabel).filter(O=>O&&O!=="orch"))).sort((O,L)=>O.localeCompare(L)),h=f.length>0?f:p,m=8,g=Math.max(18,s),b=Math.max(1,Math.floor((g-m-1)/6));let S=["orch",...h];if(!i&&S.length>b){const O=Math.max(1,b-1);S=[...S.slice(0,O),"…"]}const w=Math.max(0,S.length-1),I=Math.max(4,Math.floor((g-m-1-w)/Math.max(1,S.length))),A=n?.sequenceExpansion||null,C=A?Zc(r?.events||[]):null,v=A?new Set((A.expandedTurns||[]).map(Number)):null,T=A&&A.selectedTurn!=null?Number(A.selectedTurn):null,M=[];for(const O of d)if(M.push(Yc(O,S,m,I)),A&&O.completedTurn!=null){const L=Number(O.completedTurn),H=C.get(L);if(H)for(const F of eu(H,{expanded:v.has(L),selected:T===L,maxWidth:g}))M.push(F)}return{stickyLines:[...o,G(`Window: ${l.label}`,"gray"),Kc(S,m,I),qc(S,m,I)],lines:M}}function su(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 nu(t,e=null){const s=t?.events||[];for(let n=s.length-1;n>=0;n-=1){if(e&&!pr(s[n],e))continue;const i=cs(s[n]?.workerNodeId);if(i)return i}return null}function iu(t,e,s,n){const i=s>=16?t?.isSystem?St(t,e):t?.title||J(t?.sessionId):J(t?.sessionId),o=t?.isSystem?"⚙ ":`${Yo(t)||"."} `,r=Ve(`${o}${i}`,s);return n?Ce(r):{text:r,color:t?.isSystem?"yellow":Ot(t),bold:!!t?.isSystem}}function ou(t,e,s={}){const n=!!s?.allowWideColumns,i=su(t);if(i.length===0)return[G("No sessions available for the node map.","gray")];const o=kn(t),r=new Map,a=Vc(t,o);let l=0,c=0;for(const S of i){const w=t.sessions.byId[S];if(!w)continue;const I=t.history.bySessionId.get(S);I?.events||(l+=1);const A=nu(I,o);!A||!a.includes(A)||(c+=1,r.has(A)||r.set(A,[]),r.get(A).push(w))}if(a.length===0)return[G(`No worker activity in the ${o.label} window.`,"gray")];const d=Math.max(18,e),f=Math.max(1,Math.floor((d+1)/10));let p=a;if(!n&&a.length>f){const S=Math.max(0,f-1),w=[],I=a.slice(0,S);for(const A of a.slice(S))w.push(...r.get(A)||[]);r.set("…",w),p=[...I,"…"]}const h=Math.max(0,p.length-1),m=Math.max(8,Math.floor((d-h)/Math.max(1,p.length))),g=p.reduce((S,w)=>Math.max(S,(r.get(w)||[]).length),0),b=[G(`Window: ${o.label}`,"gray"),Qc(p,m),G(p.map(()=>"─".repeat(m)).join(" "),"gray")];for(let S=0;S<g;S+=1){const w=[];p.forEach((I,A)=>{A>0&&w.push({text:" ",color:null});const C=(r.get(I)||[])[S];if(!C){w.push({text:" ".repeat(m),color:null});return}w.push(iu(C,t.branding?.title||"PilotSwarm",m,C.sessionId===t.sessions.activeSessionId))}),b.push(w)}return l>0&&(b.push(G("","gray")),b.push(G(`Loading worker history for ${l} session(s)…`,"gray"))),c===0&&(b.push(G("","gray")),b.push(G(`No sessions mapped onto worker nodes in the ${o.label} window.`,"gray"))),b}function ru(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 b=Array.isArray(s.items)?s.items.findIndex(C=>C.id===g.id):-1,S=b===i,w=!!g.disabled,I=Q([{text:"· ",color:"gray"},{text:g.modelName||g.qualifiedName||g.id,color:w?"gray":"white",bold:!!g.isDefault&&!w},...g.cost?[{text:` [${g.cost}]`,color:"gray"}]:[],...w?[{text:" ⊘ needs GitHub key",color:"yellow"}]:[],...g.isDefault?[{text:" ← current default",color:"gray"}]:[]],o),A=S?Ce(I.map(C=>C.text).join("").padEnd(o," ")):I;S&&(l=r.length),r.push(A),a.push(b>=0?b:null)}}const c=Array.isArray(s.items)&&s.items[i]||null,d=Array.isArray(c?.supportedReasoningEfforts)?c.supportedReasoningEfforts.filter(Boolean):[],f=typeof c?.defaultReasoningEffort=="string"?c.defaultReasoningEffort:null,p=c?[[{text:c.modelName||c.qualifiedName||c.id,color:"white",bold:!0}],[{text:`${c.providerId} (${c.providerType||"provider"})`,color:"gray"}],...c.cost?[[{text:`Cost: ${c.cost}`,color:"gray"}]]:[],...d.length>0?[[{text:`Reasoning: ${d.join(", ")}`,color:"gray"}]]:[],...f?[[{text:`Default reasoning: ${f}`,color:"gray"}]]:[],...c.disabled?[[{text:"Unavailable: requires a GitHub Copilot key. Add yours in the Admin console, then reopen this picker.",color:"yellow"}]]:[],[{text:"",color:"gray"}],[{text:c.description||"No description available for this model.",color:c.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:p,idealWidth:Math.min(Math.max(46,r.reduce((h,m)=>Array.isArray(m)?Math.max(h,et(m)):Math.max(h,String(m?.text||"").length),0)+4),e)}}function au(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((f,p)=>{const h=p===i,m=Q([{text:f?.kind==="generic"?"○ ":"· ",color:"gray"},{text:f?.title||f?.agentName||f?.id||"Agent",color:"white",bold:!0},...f?.kind==="generic"?[{text:" [generic]",color:"gray"}]:[{text:` (${f?.agentName||f?.id||"agent"})`,color:"gray"}]],o);return h?Ce(m.map(g=>g.text).join("").padEnd(o," ")):m}),a=n[i]||null,l=s.sessionOptions?.model||null,c=s.sessionOptions?.reasoningEffort||null,d=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"}]]:[],...c?[[{text:`Reasoning: ${c}`,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:d,idealWidth:Math.min(Math.max(52,r.reduce((f,p)=>Array.isArray(p)?Math.max(f,et(p)):Math.max(f,String(p?.text||"").length),0)+4),e)}}function lu(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((d,f)=>{const p=f===i,h=Q([{text:"· ",color:"gray"},{text:String(d?.label||d?.id||"effort"),color:"white",bold:!0},...d?.isDefault?[{text:" ← model default",color:"gray"}]:[]],o);return p?Ce(h.map(m=>m.text).join("").padEnd(o," ")):h}),a=n[i]||null,l=s.modelItem||null,c=[[{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:c,idealWidth:Math.min(Math.max(46,r.reduce((d,f)=>Array.isArray(f)?Math.max(d,et(f)):Math.max(d,String(f?.text||"").length),0)+4),e)}}function cu(t,e=64){const s=t.ui.modal;if(!s||s.type!=="contextTierPicker")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((f,p)=>{const h=p===i,m=Q([{text:"· ",color:"gray"},{text:String(f?.label||f?.id||"tier"),color:"white",bold:!0},...f?.isDefault?[{text:" ← model default",color:"gray"}]:[]],o);return h?Ce(m.map(g=>g.text).join("").padEnd(o," ")):m}),a=n[i]||null,l=s.modelItem||null,c=a?.label||a?.id,d=[[{text:l?.modelName||l?.qualifiedName||"Selected model",color:"white",bold:!0}],[{text:`${l?.providerId||"provider"} (${l?.providerType||"provider"})`,color:"gray"}],[{text:"",color:"gray"}],[{text:c?`Using context window: ${c}`:"Choose a context window.",color:"white"}],[{text:"Long context costs more per token.",color:"gray"}]];return{title:s.title||"Select context window",rows:r,selectedRowIndex:i,detailsTitle:"Context Window",detailsLines:d,idealWidth:Math.min(Math.max(46,r.reduce((f,p)=>Array.isArray(p)?Math.max(f,et(p)):Math.max(f,String(p?.text||"").length),0)+4),e)}}function uu(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((d,f)=>{const p=f===i,h=d?.kind==="noGroup"?"○ ":d?.kind==="newGroup"?"+ ":"🗂 ",m=Q([{text:h,color:d?.kind==="group"?"cyan":"gray",bold:d?.kind!=="noGroup"},{text:d?.label||d?.groupId||"Group",color:"white",bold:!0},...d?.kind==="group"?[{text:` (${d.memberCount??0})`,color:"gray"}]:[]],o);return p?Ce(m.map(g=>g.text).join("").padEnd(o," ")):m}),l=n[i]||null,c=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:c,idealWidth:Math.min(Math.max(50,a.reduce((d,f)=>Array.isArray(f)?Math.max(d,et(f)):Math.max(d,String(f?.text||"").length),0)+4),e)}}function du(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,Oe(o||"(untitled session)")+18,Oe(r)+18),e)}}function fu(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,Oe(o)+18),e)}}function pu(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?Xo(o,t.branding?.title):J(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,Oe(n||"~/path/to/file.md")+20,Oe(r)+20),e)}}function Mn(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((c,d)=>{const f=e?.[c.id]||c.options?.[0]?.id,p=(c.options||[]).map(h=>h.id===f?Ce(h.label):{text:h.label,color:"white"});return{id:c.id,title:c.label,focused:d===r,description:c.description||"",lines:p.length>0?p:[{text:"No options available.",color:"gray"}],idealWidth:Math.max(20,String(c.label||"").length+4,...(c.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((c,d)=>c+d.idealWidth,0)+Math.max(0,l.length-1)*2+4),s)}}function mr(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&&!!Ee(s?.principal):t.kind==="shared"?e?.includeShared===!0:t.kind==="owner"?Array.isArray(e?.ownerKeys)&&e.ownerKeys.includes(t.ownerKey):!1:!1}function vi(t=[],e={},s={}){if(e?.all===!0)return"All sessions";const n=t.filter(i=>i?.kind!=="all"&&mr(i,e,s)).map(i=>i.kind==="me"?"Me":i.label);return n.length>0?n.join(" + "):"All sessions"}function hu(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((d,f)=>{const p=mr(d,i,o),h=d.kind==="system"?"yellow":d.kind==="unowned"?"gray":d.kind==="all"?"cyan":"white",m=[{text:p?"[x] ":"[ ] ",color:p?"cyan":"gray",bold:p},{text:d.label||d.id,color:h,bold:p}];return f===r?Wo(m,{preserveColors:!0}):m}),c=[[{text:"Active: ",color:"gray"},{text:vi(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:c,idealWidth:Math.min(Math.max(48,l.reduce((d,f)=>Math.max(d,Array.isArray(f)?et(f):Oe(f?.text||"")),0)+8,Oe(vi(n,i,o))+16),e)}}function mu(t,e=96){const s=t.ui.modal;return!s||s.type!=="logFilter"?null:Mn(s,t.logs?.filter||{},e,"Log Filters","Choose how the log pane is filtered and rendered.")}function gu(t,e=88){const s=t.ui.modal;return!s||s.type!=="filesFilter"?null:Mn(s,t.files?.filter||{},e,"Files Filter","Choose whether the files browser shows the selected session tree or aggregates artifacts across all sessions.")}function yu(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),c=Math.max(0,r.length-l),d=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:` [${c} 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 b=t.files?.bySessionId?.[h.sessionId]?.downloads?.[h.filename];g=Q([{text:b?.localPath?"ok ":"dl ",color:b?.localPath?"green":"cyan",bold:!0},{text:`${J(h.sessionId)}/`,color:"gray"},{text:h.filename,color:"white"}],o)}return m!==i?g:Ce(g.map(b=>b.text).join("").padEnd(o," "))}),f=n[i]||null;let p=[[{text:"No linked item selected.",color:"gray"}]];if(f?.kind==="downloadAll")p=[[{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:`${c} 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(f?.kind==="url")p=[[{text:f.text||f.href,color:"white",bold:!0}],[{text:f.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(f?.kind==="artifact"){const h=t.sessions?.byId?.[f.sessionId]||null,m=t.files?.bySessionId?.[f.sessionId]?.downloads?.[f.filename]||null;p=[[{text:f.filename,color:"white",bold:!0}],[{text:h?Xo(h,t.branding?.title):J(f.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:d.length>0?d:[{text:"No linked items available.",color:"gray"}],selectedRowIndex:i,detailsTitle:"Linked Item Details",detailsLines:p,confirmLabel:a.length>0?r.length>0?"Open / Download":"Open":"Download",idealWidth:Math.min(Math.max(54,d.reduce((h,m)=>Array.isArray(m)?Math.max(h,et(m)):Math.max(h,String(m?.text||"").length),0)+4),e)}}function j(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 gr(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 Su(t){if(!t)return"—";const e=Date.now()-t;if(e<6e4)return"<1min";const s=Math.floor(e/6e4);if(s<60)return`${s}min`;const n=Math.floor(s/60);if(n<24)return`${n}h${String(s%60).padStart(2,"0")}m`;const i=Math.floor(n/24);return i<14?`${i}d${String(n%24).padStart(2,"0")}h`:`${Math.floor(i/7)}w`}function Dt(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 Tt(t){return["session","fleet","users"].includes(t)?t:"session"}function us(t,e){const s=Tt(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 bu(t,e,s){if(!e)return[G("No session selected.")];const n=t.sessionStats?.bySessionId?.[e.sessionId]||null;if(!n||n.loading&&!n.summary)return[G("Loading session stats...")];const i=n.summary;if(!i)return[G("Session stats unavailable.")];const o=[],r=Math.max(24,s);o.push(us("session",r)),o.push(G("")),o.push(Q([{text:"Session ",color:"cyan",bold:!0},{text:J(e.sessionId),color:"white"}],r));const a=e.isSystem?"system":e.owner?"user":"unowned",l=e.isSystem?"system":e.owner?gn(e.owner):"(?) unowned",c=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:c,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 d=An(i.model||e.model,i.reasoningEffort||e.reasoningEffort);d&&o.push(Q([{text:"Model ",color:"cyan",bold:!0},{text:d,color:"white"}],r)),e.createdAt&&o.push(Q([{text:"Created ",color:"cyan",bold:!0},{text:Dt(e.createdAt),color:"white"}],r)),e.updatedAt&&o.push(Q([{text:"Updated ",color:"cyan",bold:!0},{text:Dt(e.updatedAt),color:"white"}],r)),o.push(G(""));const f=Array.isArray(n.tokensByModel)?n.tokensByModel:[];f.length>1&&(o.push(...ne({title:"Models",body:f.map(v=>`${Sc(v.model)} · ${v.turnCount||0} turns · ${j(v.totalTokensInput)} in / ${j(v.totalTokensOutput)} out`).join(`
51
- `),width:r,titleColor:"cyan",borderColor:"gray",fitToContent:!0})),o.push(G("")));const p=(i.tokensInput||0)+(i.tokensOutput||0),h=i.cacheHitRatio,m=h==null?"—":`${(h*100).toFixed(1)}%`;o.push(...ne({title:"Tokens",body:Je([["Input",j(i.tokensInput)],["Output",j(i.tokensOutput)],["Total",j(p)],["Cache Read",j(i.tokensCacheRead)],["Cache Write",j(i.tokensCacheWrite)],["Hit Ratio",m]]),width:r,titleColor:"green",borderColor:"gray",fitToContent:!0})),o.push(G("")),o.push(...ne({title:"Persistence",body:Je([["Snapshot",le(i.snapshotSizeBytes)],["Uncompressed",i.rawSizeBytes?le(i.rawSizeBytes):null],["Compression",Ii(i.rawSizeBytes,i.snapshotSizeBytes)],["Dehydrations",String(i.dehydrationCount)],["Hydrations",String(i.hydrationCount)],["Lossy Handoffs",String(i.lossyHandoffCount)],["Last Dehydrated",i.lastDehydratedAt?Dt(i.lastDehydratedAt):null],["Last Hydrated",i.lastHydratedAt?Dt(i.lastHydratedAt):null]]),width:r,titleColor:"yellow",borderColor:"gray",fitToContent:!0}));const g=n.treeStats?.tree;if(g&&g.sessionCount>1){const v=g.cacheHitRatio,T=v==null?"—":`${(v*100).toFixed(1)}%`,M=(g.totalTokensInput||0)+(g.totalTokensOutput||0);o.push(G("")),o.push(...ne({title:`Tree (${g.sessionCount} sessions)`,body:Je([["Input",j(g.totalTokensInput)],["Output",j(g.totalTokensOutput)],["Total",j(M)],["Cache Read",j(g.totalTokensCacheRead)],["Cache Write",j(g.totalTokensCacheWrite)],["Hit Ratio",T],["Snapshot",le(g.totalSnapshotSizeBytes)],["Uncompressed",g.totalRawSizeBytes?le(g.totalRawSizeBytes):null],["Compression",Ii(g.totalRawSizeBytes,g.totalSnapshotSizeBytes)],["Dehydrations",String(g.totalDehydrationCount)],["Hydrations",String(g.totalHydrationCount)]]),width:r,titleColor:"magenta",borderColor:"gray",fitToContent:!0}));const O=Array.isArray(n.treeStats?.byModel)?n.treeStats.byModel:[];O.length>1&&(o.push(G("")),o.push(...ne({title:"Tree By Model",body:Au(O),width:r,titleColor:"cyan",borderColor:"gray",fitToContent:!0})))}const b=Array.isArray(n.skillUsage)?n.skillUsage:[];b.length>0&&(o.push(G("")),o.push(...ne({title:`Skills (${b.length})`,body:Ei(b,r),width:r,titleColor:"cyan",borderColor:"gray",fitToContent:!0})));const S=n.treeSkillUsage,w=Array.isArray(S?.rolledUp)?S.rolledUp:[],I=Array.isArray(S?.perSession)?S.perSession.length:0;w.length>0&&I>1&&(o.push(G("")),o.push(...ne({title:`Tree Skills (${w.length})`,body:Ei(w,r),width:r,titleColor:"cyan",borderColor:"gray",fitToContent:!0})));const A=n.factsStats,C=n.treeFactsStats;if(A&&Array.isArray(A.rows)&&A.rows.length>0){o.push(G(""));const v=yr(A.rows),T=v?v.split(`
52
- `).length:0,M=`${A.totalCount} · ${le(A.totalBytes)}`;let O=v;C&&C.totalCount>A.totalCount&&(O+=`
53
- Tree (${C.sessionIds.length} sessions): ${C.totalCount} · ${le(C.totalBytes)}`),T>0&&o.push(...ne({title:`Facts (${M})`,body:O,width:r,titleColor:"blue",borderColor:"gray",fitToContent:!0}))}return o}function Je(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(`
54
- `)}function ds(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 Lt(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 c=a[l]==null?"":String(a[l]);c.length>o[l]&&(o[l]=c.length)}const r=" ".repeat(s);return n.map(a=>a.map((l,c)=>{const d=l==null?"":String(l);return c===0?d.padEnd(o[c]):d.padStart(o[c])}).join(r)).join(`
55
- `)}function Ei(t,e){const s=t.slice().sort((f,p)=>(p.invocations||0)-(f.invocations||0)).slice(0,12),n=s.map(f=>`${f.invocations||0} inv`),i=n.reduce((f,p)=>Math.max(f,p.length),0),a=4+2+i,l=Number.isFinite(e)&&e>0?Math.max(8,Math.floor(e)-a):1/0,c=s.map((f,p)=>{const h=f.kind==="learned"?"L":"S",m=String(f.name||"(unknown)");return[ds(`${h} ${m}`,l),n[p]]}),d=Lt(c);return t.length>s.length?`${d}
56
- … ${t.length-s.length} more`:d}function yr(t){const s=t.slice().sort((n,i)=>(i.factCount||0)-(n.factCount||0)).map(n=>[String(n.namespace||"(other)"),String(n.factCount||0),le(n.totalValueBytes||0)]);return Lt(s)}function wu(t){const e=t.oldestUnreconciledAgeSeconds==null?"-":kt(Math.max(0,Number(t.oldestUnreconciledAgeSeconds)||0));return Lt([["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 Iu(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 xu(t,e){const s=t.slice().sort((f,p)=>(Number(p.calls)||0)-(Number(f.calls)||0)).slice(0,12),n=s.map(f=>`${Number(f.calls)||0} calls`),i=s.map(f=>`${Number(f.totalResults)||0} res`),o=n.reduce((f,p)=>Math.max(f,p.length),0),r=i.reduce((f,p)=>Math.max(f,p.length),0),a=6+o+2+r,l=Number.isFinite(e)&&e>0?Math.max(10,Math.floor(e)-a):1/0,c=s.map((f,p)=>{const h=f.namespace?` ${f.namespace}`:"";return[ds(`${Iu(f.operation)}${h}`,l),n[p],i[p]]}),d=Lt(c);return t.length>s.length?`${d}
57
- … ${t.length-s.length} more`:d}function vu(t,e){const s=t.fleetStats;if(!s||s.loading&&!s.data)return[G("Loading fleet stats...")];const n=s.data;if(!n)return[G("Fleet stats unavailable.")];const i=[],o=Math.max(24,e);i.push(us("fleet",o)),i.push(G(""));const r=n.windowStart?`Since: ${gr(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: ${j(n.totals.totalTokensInput)} in / ${j(n.totals.totalTokensOutput)} out`,color:"white"}],o)),i.push(G(""));const l=new Map;for(const g of n.byAgent||[]){const b=g.model||"(default)",S=l.get(b)||{totalTokensInput:0,totalTokensOutput:0,totalTokensCacheRead:0,totalTokensCacheWrite:0,totalSnapshotSizeBytes:0,turnCount:0};S.totalTokensInput+=Number(g.totalTokensInput)||0,S.totalTokensOutput+=Number(g.totalTokensOutput)||0,S.totalTokensCacheRead+=Number(g.totalTokensCacheRead)||0,S.totalTokensCacheWrite+=Number(g.totalTokensCacheWrite)||0,S.totalSnapshotSizeBytes+=Number(g.totalSnapshotSizeBytes)||0,S.turnCount+=Number(g.turnCount)||0,l.set(b,S)}if(l.size>0){const g=[];for(const[b,S]of l.entries()){const w=S.totalTokensInput>0?S.totalTokensCacheRead/S.totalTokensInput:null;g.push(b),g.push(Pn(S,w)),g.push("")}i.push(...ne({title:"Tokens By Model",body:g.join(`
58
- `).trimEnd(),width:o,titleColor:"cyan",borderColor:"gray",fitToContent:!0})),i.push(G(""))}const c=n.totals.cacheHitRatio,d=c==null?"—":`${(c*100).toFixed(1)}%`;i.push(...ne({title:"Fleet Totals",body:Je([["Sessions",String(n.totals.sessionCount)],["Tokens In",j(n.totals.totalTokensInput)],["Tokens Out",j(n.totals.totalTokensOutput)],["Total Tokens",j(n.totals.totalTokensInput+n.totals.totalTokensOutput)],["Cache Read",j(n.totals.totalTokensCacheRead)],["Cache Write",j(n.totals.totalTokensCacheWrite)],["Hit Ratio",d],["Snapshots",le(n.totals.totalSnapshotSizeBytes)]]),width:o,titleColor:"green",borderColor:"gray",fitToContent:!0}));const f=(Array.isArray(s.skillUsage?.rows)?s.skillUsage.rows:[]).filter(g=>!(g&&g.agentId==="facts-manager"&&String(g.name||"").startsWith("skills/")));f.length>0&&(i.push(G("")),i.push(...ne({title:`Fleet Skills (${f.length})`,body:Eu(f,e),width:o,titleColor:"cyan",borderColor:"gray",fitToContent:!0})));const p=Array.isArray(s.retrievalUsage?.rows)?s.retrievalUsage.rows:[];if(p.length>0){const g=p.reduce((b,S)=>b+(Number(S.calls)||0),0);i.push(G("")),i.push(...ne({title:`Fleet Retrieval (${j(g)})`,body:xu(p,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(G(""));const g=`${h.totalCount} · ${le(h.totalBytes)}`;i.push(...ne({title:`Shared Facts (${g})`,body:yr(h.rows),width:o,titleColor:"blue",borderColor:"gray",fitToContent:!0}))}const m=s.factsTombstoneStats;return m&&Number(m.pendingTotal)>0&&(i.push(G("")),i.push(...ne({title:`Fact Tombstones (${Number(m.pendingTotal)||0})`,body:wu(m),width:o,titleColor:"yellow",borderColor:"gray",fitToContent:!0}))),i}function Eu(t,e){const n=t.slice().sort((m,g)=>{const b=C=>C==="learned"?1:0,S=b(m.kind)-b(g.kind);if(S!==0)return S;const w=m.agentId?0:1,I=g.agentId?0:1;if(w!==I)return w-I;const A=String(m.agentId||"").localeCompare(String(g.agentId||""));return A!==0?A: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,c=2,d=l+c+r+c+a,f=Number.isFinite(e)&&e>0?Math.max(10,Math.floor(e)-d):1/0,p=n.map((m,g)=>{const b=m.kind==="learned"?"L":"S",S=m.agentId||".",w=String(m.name||"(unknown)");return[ds(`${b} ${S}/${w}`,f),i[g],o[g]]}),h=Lt(p);return t.length>n.length?`${h}
59
- … ${t.length-n.length} more`:h}function Au(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(Pn(n,i)),s.push("")}return s.join(`
60
- `).trimEnd()}function Pn(t,e){const s=e==null?"—":`${(e*100).toFixed(1)}%`,n=(Number(t.totalTokensInput)||0)+(Number(t.totalTokensOutput)||0),i=[["Input",j(t.totalTokensInput||0)],["Output",j(t.totalTokensOutput||0)],["Total",j(n)],["Turns",j(t.turnCount||0)],["Cache Read",j(t.totalTokensCacheRead||0)],["Cache Write",j(t.totalTokensCacheWrite||0)],["Hit Ratio",s],["Snapshot",le(t.totalSnapshotSizeBytes||0)]];return Number.isFinite(Number(t.totalOrchestrationHistorySizeBytes))&&i.push(["Orch",le(t.totalOrchestrationHistorySizeBytes||0)]),Je(i).split(`
61
- `).map(r=>` ${r}`).join(`
62
- `)}function qs(t){return t?.ownerKind==="system"?"System":t?.ownerKind==="unowned"?"Unowned":gn(t?.owner,"Unknown User")}function Tu(t){if(t?.ownerKind!=="user")return"";const e=String(t?.owner?.email||"").trim(),s=qs(t);return e&&e!==s?e:""}function Cu(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=ds(String(o.model||"(default)"),Math.max(12,e-10));i.push(`${r} · ${o.sessionCount||0} sess · ${o.turnCount||0} turns`),i.push(Pn(o,o.cacheHitRatio)),i.push("")}return s.length>n.length&&i.push(`… ${s.length-n.length} more models`),i.join(`
63
- `).trimEnd()}function ku(t,e){const s=t.fleetStats;if(!s||s.loading&&!s.userStats)return[G("Loading user stats...")];const n=s.userStats;if(!n)return[G("User stats unavailable.")];const i=[],o=Math.max(24,e);i.push(us("users",o)),i.push(G(""));const r=n.windowStart?`Since: ${gr(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(G(""));const l=n.totals.cacheHitRatio,c=l==null?"—":`${(l*100).toFixed(1)}%`;i.push(...ne({title:"User Totals",body:Je([["Sessions",String(n.totals.sessionCount||0)],["Tokens In",j(n.totals.totalTokensInput||0)],["Tokens Out",j(n.totals.totalTokensOutput||0)],["Total Tokens",j((n.totals.totalTokensInput||0)+(n.totals.totalTokensOutput||0))],["Cache Read",j(n.totals.totalTokensCacheRead||0)],["Cache Write",j(n.totals.totalTokensCacheWrite||0)],["Hit Ratio",c],["Snapshots",le(n.totals.totalSnapshotSizeBytes||0)],["Orch Size",le(n.totals.totalOrchestrationHistorySizeBytes||0)]]),width:o,titleColor:"green",borderColor:"gray",fitToContent:!0}));const d=Array.isArray(n.users)?n.users:[],f=d.slice().sort((p,h)=>(h.totalTokensInput||0)-(p.totalTokensInput||0)||(h.totalSnapshotSizeBytes||0)-(p.totalSnapshotSizeBytes||0)).slice(0,8);for(const p of f){const h=Tu(p),m=p.cacheHitRatio,g=m==null?"—":`${(m*100).toFixed(1)}%`,b=h?`${qs(p)} <${h}>`:qs(p),S=Je([["Sessions",String(p.sessionCount||0)],["Tokens In",j(p.totalTokensInput||0)],["Tokens Out",j(p.totalTokensOutput||0)],["Total Tokens",j((p.totalTokensInput||0)+(p.totalTokensOutput||0))],["Cache Read",j(p.totalTokensCacheRead||0)],["Cache Write",j(p.totalTokensCacheWrite||0)],["Hit Ratio",g],["Snapshots",le(p.totalSnapshotSizeBytes||0)],["Orch Size",le(p.totalOrchestrationHistorySizeBytes||0)]]),w=Cu(p,o);i.push(G("")),i.push(...ne({title:`${b} (${p.sessionCount||0})`,body:w?`${S}
64
-
65
- ${w}`:S,width:o,titleColor:p.ownerKind==="user"?"cyan":"yellow",borderColor:"gray",fitToContent:!0}))}return d.length>f.length&&(i.push(G("")),i.push(G(`… ${d.length-f.length} more users`))),i}function Ye(t,e={}){const s=Ae(t),n=t.ui.inspectorTab,i=Math.max(18,Number(e?.width)||36),o=!!e?.allowWideColumns,r=Vo(i);if(s?.isGroup)return{title:Pe("Inspector","magenta"),activeTab:n,tabs:ve,disabled:!0,stickyLines:[],lines:[G(Sr,"gray")]};const a=s?J(s.sessionId):"",l=n==="sequence"||n==="nodes"?kn(t):null,c=n==="nodes"?[...Pe("Node Map","magenta"),...r?[]:[{text:` [${l.label}]`,color:"gray"}]]:s?n==="sequence"?[...Pe(r?"Sequence":`Sequence: ${a}`,"magenta"),...r?[]:[{text:` [${l.label}]`,color:"gray"}]]:n==="logs"?[...Pe(r?"Logs":`Logs: ${a}`,"magenta")]:n==="history"?[...Pe(r?"History":`History: ${a}`,"magenta")]:n==="stats"?[...Pe(r?"Stats":`Stats: ${a}`,"magenta"),{text:` [${Tt(t.ui?.statsViewMode)}]`,color:"gray"}]:[...Pe(r?"Files":`Files: ${a}`,"magenta")]:n==="stats"?`Stats: ${Tt(t.ui?.statsViewMode).replace(/^./u,p=>p.toUpperCase())}`:"No session selected";let d,f=[];switch(n){case"sequence":{const p=s?tu(t,s,i,{allowWideColumns:o,sequenceExpansion:e?.sequenceExpansion||null}):{stickyLines:[],lines:["No session selected."]};f=p.stickyLines||[],d=p.lines;break}case"logs":d=s?Ac(t,s):["No session selected."];break;case"nodes":d=ou(t,i,{allowWideColumns:o});break;case"files":d=s?["Files view is rendered in the shared host layout."]:["No session selected."];break;case"history":d=s?Ou(t,s):["No session selected."];break;case"stats":d=Tt(t.ui?.statsViewMode)==="users"?ku(t,i):Tt(t.ui?.statsViewMode)==="fleet"?vu(t,i):s?bu(t,s,i):[us("session",Math.max(24,i)),G(""),G("No session selected. Press f to cycle to fleet or users view.")];break;default:d=["Inspector view is scaffolded in the new architecture."];break}return{title:c,activeTab:n,tabs:ve,stickyLines:f,lines:d}}const Mu={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"},Sr="Select a session to see details.";function Pu(t){const e=t.timestampMs?new Date(t.timestampMs).toISOString().slice(11,23):"???",s=Mu[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),c=l.length>100?l.slice(0,97)+"...":l;n.push([{text:` ${r}: `,color:"yellow"},{text:c,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 Nu(t){const e={...t};if(e.data)try{e.data=JSON.parse(e.data)}catch{}return JSON.stringify(e,null,2)}function Ou(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=Nu(n[r]).split(`
66
- `);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=Pu(n[r]);for(const l of a)o.push(l);r<n.length-1&&o.push({text:"────────────────────────────────",color:"gray"})}return o}function _u(t,e=88){const s=t.ui.modal;return!s||s.type!=="historyFormat"?null:Mn(s,{format:t.executionHistory?.format||"pretty"},e,"Execution History Format","Choose the display format for duroxide execution history events.")}function Ai(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 Ru(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(p=>p.id===r)||null,l=o&&o.id!==r,c=Math.max(24,e-4),d=n.map((p,h)=>{const m=p.id===r?" [current]":"",g=`${p.label}${m}`.slice(0,c);return h===i?Ce(g.padEnd(c," ")):[{text:g,color:p.id===r?"cyan":"white",bold:p.id===r}]}),f=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"}],Ai([{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"}]),Ai([{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:d,selectedRowIndex:i,detailsTitle:"Theme Details",detailsLines:f}}function Lu(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 Ti(t){return new Map(t)}function Ms(t){return new Set(t)}function Fu(t){return Array.isArray(t)?[...t]:[]}function $u(t){return Array.isArray(t)?[...t]:[]}const Bu=5e3;function zs(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 br(t){return!!(t&&!t.isSystem&&(t.isGroup||!t.parentSessionId&&!t.groupId))}function Ps(t,e){return zs(t,e).filter(s=>br(e[s]))}function Du(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 wr(t,e){const s=Du(Object.values(e||{})),n=new Set;for(const i of t||[])s.has(i)&&n.add(i);return n}function Hu(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 Ci(t,e,s){const n=wr(t,e);if(!s||!e?.[s])return n;for(const i of Hu(s,e))n.delete(i);return n}function ki(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 Gu(t){return{...t||{}}}function Me(t){return{...t||{}}}function Mi(t){return{...t||{}}}function Ht(t){return{...t||{}}}function Ns(t){return{scope:t?.scope==="allSessions"?"allSessions":"selectedSession",query:typeof t?.query=="string"?t.query:""}}function Uu(t){return(Array.isArray(t)?t.filter(Boolean):[]).slice(-1e3)}function ju(t){return[E.SESSIONS,E.CHAT,E.INSPECTOR,E.ACTIVITY].includes(t)?t:null}function Os(t,e){const s=Array.isArray(t)?t.filter(Boolean):[],n=Math.max(X,Number(e)||X);return s.length>n?s.slice(-n):s}function Ys(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(!Ys(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)||!Ys(t[i],e[i]))return!1;return!0}function Pi(t){const e=t?.updatedAt;if(typeof e=="number"&&Number.isFinite(e))return e;if(e instanceof Date)return e.getTime();const s=Date.parse(e||"");return Number.isFinite(s)?s:0}function Wu(t,e){const s=Pi(t),n=Pi(e);return s>0&&n>0&&n<=s}const Vu=new Set(["completed","failed","cancelled","error"]);function Ku(t,e){const s=String(e?.status??"").toLowerCase();if(t?.status!=="running"||s==="running"||Vu.has(s))return!1;const n=Number(t?.statusVersion),i=Number(e?.statusVersion);return Number.isFinite(n)&&n>0&&Number.isFinite(i)&&i>0?i<=n:Wu(t,e)}function Ni(t={},e={}){let s=t||{};const n=Ku(t,e);for(const[i,o]of Object.entries(e||{}))if(o!==void 0&&!(i==="status"&&n)){if(i==="pendingQuestion"&&qu(t,o)){s===t&&(s={...t||{}}),s.pendingQuestion=null;continue}Ys(t?.[i],o)||(s===t&&(s={...t||{}}),s[i]=o)}return s}function Oi(t){if(!t)return"unknown";const e=t.status||"unknown";return t.cronActive===!0&&(e==="waiting"||e==="idle"||e==="unknown")?"cron_waiting":e}function _i(t,e,s){if(!e?.sessionId||e.isGroup)return e;const n=Oi(e),i=t?.rowVisualStatus||Oi(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>=Bu?{...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 Ri(t){return String(t?.question||"").trim()}function qu(t,e){const s=Ri(t?.answeredPendingQuestion),n=Ri(e);return!!(s&&n&&s===n)}function zu(t=[]){const e=(t||[]).find(n=>n?.sessionId&&n.isSystem&&Po(n)===0);return e?.sessionId?e.sessionId:(t||[]).find(n=>n?.sessionId)?.sessionId||null}function Li(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 Fi(t={}){const e=String(t?.filterQuery||"").trim(),s=Xt(t?.ownerFilter);return!!e||s.all!==!0}function Yu(t,e=[]){const s=yt(t),n=t.sessions?.activeSessionId||null;if(n&&s.some(o=>o.sessionId===n)||t.sessions?.navigationIntent||n&&t.sessions?.byId?.[n]&&!Fi(t.sessions))return n;if(Fi(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 zu(i)}function Qu(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 nt(t,e){let s=e;const n=s.navigationIntent||null,i=n&&n.status!=="failed"&&s.byId?.[n.sessionId]?n.sessionId:null;i&&(s={...s,activeSessionId:i,navigationIntent:n.status==="resolved"?n:{sessionId:n.sessionId,status:"resolved"}});const o=s.activeSessionId||null;if(o&&s.byId?.[o]){const f=Ci(s.collapsedIds,s.byId,o);ki(f,s.collapsedIds)||(s={...s,collapsedIds:f,flat:Be(Object.values(s.byId||{}),f,s.orderById,s.pinnedIds)})}i&&s.filterExceptionId!==i&&(yt({...t,sessions:s}).some(p=>p.sessionId===i)||(s={...s,filterExceptionId:i}));const r={...t,sessions:s},a=Yu(r,Object.values(s.byId||{})),l=Ci(s.collapsedIds,s.byId,a);return{sessions:{...!ki(l,s.collapsedIds)?{...s,collapsedIds:l,flat:Be(Object.values(s.byId||{}),l,s.orderById,s.pinnedIds)}:s,activeSessionId:a},ui:Qu(t,a)}}function $i(t={},e=0,s=[]){const n=Gu(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 Xu(t=[],e=[]){const s=Be(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 Ju(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 Bi(t,e){const s=String(t||"");return(Array.isArray(e)?e.filter(Boolean):[]).filter(i=>{if(i?.kind==="image")return!0;const o=String(i?.token||"").trim();return o&&s.includes(o)})}function Zu(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"),c=!!(t.sessions.navigationIntent&&t.sessions.navigationIntent.status!=="failed"),d=Object.prototype.hasOwnProperty.call(s,"activeSessionId")&&!c,f=Object.keys(t.sessions.byId||{}).length>0,p=o?{...t.ui.layout||{},...fn(s.layoutAdjustments)}:t.ui.layout,h=a?f?Ps(Zt(s.pinnedSessionIds),t.sessions.byId):Zt(s.pinnedSessionIds):t.sessions.pinnedIds,m=l?f?wr(Ws(s.collapsedSessionIds),t.sessions.byId):Ws(s.collapsedSessionIds):t.sessions.collapsedIds,g=d?Go(s.activeSessionId):t.sessions.activeSessionId,b={...t.sessions,...i?{ownerFilter:Xt(s.sessionOwnerFilter),ownerFilterExplicit:!0}:{},pinnedIds:h,collapsedIds:m,collapsedIdsExplicit:l?!0:t.sessions.collapsedIdsExplicit,activeSessionId:g,flat:a||l?Be(Object.values(t.sessions.byId),m,t.sessions.orderById,h):t.sessions.flat},S=f&&(i||a||l||d)?nt(t,b):{sessions:b,ui:t.ui};return{...t,sessions:S.sessions,ui:{...S.ui,themeId:n?s.themeId.trim():S.ui.themeId,chatViewMode:r?s.chatViewMode:S.ui.chatViewMode,layout:p}}}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"ui/sequenceExpandedTurns":return{...t,ui:{...t.ui,sequenceExpandedTurns:Array.isArray(e.turns)?e.turns:[]}};case"ui/sequenceSelectedTurn":return{...t,ui:{...t.ui,sequenceSelectedTurn:e.turn==null?null:Number(e.turn)}};case"sessions/filterQuery":{const s={...t.sessions,filterQuery:typeof e.query=="string"?e.query:"",navigationIntent:null,filterExceptionId:null},n=nt(t,s);return{...t,sessions:n.sessions,ui:n.ui}}case"sessions/ownerFilter":{const s={...t.sessions,ownerFilterExplicit:!0,ownerFilter:Xt(e.filter),navigationIntent:null,filterExceptionId:null},n=nt(t,s);return{...t,sessions:n.sessions,ui:n.ui}}case"sessions/navigationIntent":{const s=String(e.sessionId||"").trim();if(!s)return t;const n={...t.sessions,navigationIntent:{sessionId:s,status:"pending"},filterExceptionId:null},i=nt(t,n);return{...t,sessions:i.sessions,ui:i.ui}}case"sessions/navigationIntentFailed":{const s=t.sessions.navigationIntent,n=String(e.sessionId||"").trim();return!s||n&&s.sessionId!==n?t:{...t,sessions:{...t.sessions,navigationIntent:{sessionId:s.sessionId,status:"failed",errorKind:e.errorKind==="not_found"?"not_found":"network"}}}}case"ui/modalSelection":{const s=t.ui.modal;if(!s)return t;if(s.type==="help")return{...t,ui:{...t.ui,modal:{...s,selectedIndex:Math.max(0,Number(e.index)||0)}}};if(!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===E.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:Ju(e.prompt,e.promptCursor,t.ui.promptCursor),promptRows:pt(e.prompt),promptAttachments:Bi(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:Bi(t.ui.prompt,e.attachments)}};case"sessions/loaded":{const s={};let n=!1;const i=Date.now();for(const I of e.sessions){const A=t.sessions.byId[I.sessionId],C=_i(A,Ni(A,I),i);s[I.sessionId]=C,!n&&C!==A&&(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 I of r)if(!t.sessions.byId[I]){n=!0;break}}if(!n)return t;const a=Object.values(s),l=Object.keys(t.sessions.orderById||{}).length>0,c=Li(a),d=!!t.sessions.collapsedIdsExplicit,{orderById:f,nextOrderOrdinal:p}=l?$i(t.sessions.orderById,t.sessions.nextOrderOrdinal,a):Xu(a,t.sessions.pinnedIds),h=d?Ms(t.sessions.collapsedIds):c;if(d){const I=Li(Object.values(t.sessions.byId));for(const A of c)I.has(A)||h.add(A)}const m=Ps(t.sessions.pinnedIds,s),g=zs(t.sessions.selectedIds,s),b=Be(a,h,f,m),S={...t.sessions,byId:s,collapsedIds:h,collapsedIdsExplicit:d,pinnedIds:m,selectedIds:g,selectMode:t.sessions.selectMode&&g.length>0,flat:b,activeSessionId:t.sessions.activeSessionId,orderById:f,nextOrderOrdinal:p},w=nt(t,S);return{...t,sessions:w.sessions,ui:w.ui}}case"sessions/merged":{if(!e.session?.sessionId)return t;const s=t.sessions.byId[e.session.sessionId],n=_i(s,Ni(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}=$i(t.sessions.orderById,t.sessions.nextOrderOrdinal,Object.values(i)),l={...t.sessions,byId:i,pinnedIds:o,flat:Be(Object.values(i),t.sessions.collapsedIds,r,o),activeSessionId:t.sessions.activeSessionId,orderById:r,nextOrderOrdinal:a},c=nt(t,l);return{...t,sessions:c.sessions,ui:c.ui}}case"sessions/selected":{const s=t.sessions.activeSessionId,n={...t.ui.chatScrollBySession||{}};s&&s!==e.sessionId&&(n[s]=Number(t.ui.scroll?.chat)||0);const i=!!(t.sessions.navigationIntent&&t.sessions.navigationIntent.sessionId!==e.sessionId);return{...t,sessions:{...t.sessions,activeSessionId:e.sessionId,...i?{navigationIntent:null,filterExceptionId:null}:{}},ui:{...t.ui,chatScrollBySession:n,statusText:s!==e.sessionId?"":t.ui.statusText,scroll:{...t.ui.scroll,chat:Number(n[e.sessionId])||0,inspector:0,activity:0},followBottom:{...t.ui.followBottom||{},inspector:!0,activity:!0}}}}case"ui/fullscreenPane":{const s=ju(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=Ms(t.sessions.collapsedIds);return s.add(e.sessionId),{...t,sessions:{...t.sessions,collapsedIds:s,collapsedIdsExplicit:!0,flat:Be(Object.values(t.sessions.byId),s,t.sessions.orderById,t.sessions.pinnedIds)}}}case"sessions/expand":{const s=Ms(t.sessions.collapsedIds);return s.delete(e.sessionId),{...t,sessions:{...t.sessions,collapsedIds:s,collapsedIdsExplicit:!0,flat:Be(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(!br(n))return t;const i=Fu(t.sessions.pinnedIds),r=i.indexOf(s)>=0?i.filter(a=>a!==s):[...i,s];return{...t,sessions:{...t.sessions,pinnedIds:r,flat:Be(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=$u(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=zs(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(X,Number(e.history?.loadedEventLimit??s?.loadedEventLimit??X)||X),o=Os(ut(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,c=Ti(t.history.bySessionId);return c.set(e.sessionId,{...e.history||{},chat:o,activity:Os(e.history?.activity||[],i),events:Os(e.history?.events||[],i),loadedEventLimit:i}),{...t,history:{...t.history,bySessionId:c},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=Ti(t.history.bySessionId);for(const r of s)n.delete(r);const i=Mi(t.outbox?.bySessionId);for(const r of s)delete i[r];const o={...t.ui.chatScrollBySession||{}};for(const r of s)delete o[r];return{...t,history:{...t.history,bySessionId:n},outbox:{...t.outbox,bySessionId:i},ui:{...t.ui,chatScrollBySession:o}}}case"outbox/setSessionItems":{const s=e.sessionId;if(!s)return t;const n=Array.isArray(e.items)?e.items.filter(Boolean):[],i=Mi(t.outbox?.bySessionId);return n.length===0?delete i[s]:i[s]=n,{...t,outbox:{...t.outbox,bySessionId:i}}}case"orchestration/statsLoading":{const s=Ht(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=Ht(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=Ht(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=Ht(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,storeAsSystem:!!t.admin.ghcpKey.storeAsSystem}}}}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,storeAsSystem:!!t.admin.ghcpKey.storeAsSystem}}};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(),storeAsSystem:!!t.admin.ghcpKey.storeAsSystem}}};case"admin/ghcpKey/setSystemTarget":{const s=!!e.value;return!!t.admin.ghcpKey.storeAsSystem===s?t:{...t,admin:{...t.admin,ghcpKey:{...t.admin.ghcpKey,storeAsSystem:s,error:null}}}}case"admin/systemGhcpKey/loading":return{...t,admin:{...t.admin,systemGhcpKey:{...t.admin.systemGhcpKey,loading:!0,error:null}}};case"admin/systemGhcpKey/loaded":{const s=e.status||{};return{...t,admin:{...t.admin,systemGhcpKey:{supported:!0,loading:!1,configured:!!s.configured,changedBy:s.changedBy||null,changedAt:s.changedAt||null,error:null}}}}case"admin/systemGhcpKey/loadFailed":return{...t,admin:{...t.admin,systemGhcpKey:{...t.admin.systemGhcpKey,loading:!1,error:e.error?String(e.error):"Failed to load System key status"}}};case"admin/systemGhcpKey/saved":{const s=e.status||{};return{...t,admin:{...t.admin,ghcpKey:{editing:!1,draft:"",cursorIndex:0,saving:!1,error:null,lastSavedAt:Date.now(),storeAsSystem:!!t.admin.ghcpKey.storeAsSystem},systemGhcpKey:{supported:!0,loading:!1,configured:!!s.configured,changedBy:s.changedBy||null,changedAt:s.changedAt||null,error:null}}}}case"files/evictPreviews":{const s=Array.isArray(e.sessionIds)?e.sessionIds:[];if(s.length===0)return t;const n=Me(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=Me(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=Me(t.files.bySessionId),n=s[e.sessionId]||{previews:{},downloads:{}},i=Jt(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=Me(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=Me(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=Me(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=Me(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=Me(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=Me(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=Me(t.files.bySessionId),n=s[e.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:null},i=Jt(n.entries).filter(f=>f.filename!==e.filename),o=n.selectedFilename===e.filename?i[0]?.filename||null:n.selectedFilename,{[e.filename]:r,...a}=n.previews||{},{[e.filename]:l,...c}=n.downloads||{},d=e.sessionId&&e.filename?`${e.sessionId}/${e.filename}`:null;return s[e.sessionId]={...n,entries:i,previews:a,downloads:c,selectedFilename:o},{...t,files:{...t.files,bySessionId:s,selectedArtifactId:t.files.selectedArtifactId===d?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:{...Ns(t.files.filter),...Ns(e.filter)},...Ns(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:Uu(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 ed(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 td=2e4,sd=2e4,nd=3e4,id=30,Di="Session refresh failed",od=3,rd=200,ad=5,ld=new Set([E.SESSIONS,E.CHAT,E.INSPECTOR,E.ACTIVITY]);function cd(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 _s(t){return!t?.sessionId||t.isGroup?t:{...t,groupId:t.viewerGroupId??null,parentSessionId:t.parentSessionId??null}}function Rs(t){return String(t||"").startsWith("group:")?String(t).slice(6):null}function ud(t){const e=new Map;for(const s of t||[]){const n=s?.reason==="system"?"system":"not found";e.set(n,(e.get(n)||0)+1)}return[...e.entries()].map(([s,n])=>`${n} ${s}`).join(", ")}function Ls(t){const e=Number(t?.status),s=String(t?.code||"").toUpperCase();return e===404||e===403||s==="NOT_FOUND"||s==="FORBIDDEN"?"not_found":"network"}async function dd(t){if(typeof t.listSessionsPage!="function")return t.listSessions();const e=[];let s=null;for(let n=0;n<ad;n+=1){const i=await t.listSessionsPage({limit:rd,cursor:s}),o=Array.isArray(i?.sessions)?i.sessions:[];if(e.push(...o),!i?.hasMore||!i?.nextCursor)break;s=i.nextCursor}return e}function fd(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 Qs(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 Hi(t){const e=Qs(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 Xs(t){if(!Array.isArray(t))return[];const e=[];for(const s of t){const n=String(s||"").trim().toLowerCase();!n||e.includes(n)||n!=="default"&&n!=="long_context"||e.push(n)}return e}function pd(t){const e=Xs(t?.supportedContextTiers);if(e.length===0)return null;const s=String(t?.defaultContextTier||"").trim().toLowerCase();return s&&e.includes(s)?s:e.includes("default")?"default":e[0]||null}const Ir={default:"Default (smaller window)",long_context:"Long context (larger window, higher cost)"};function hd(t){const e=Number(t);return!Number.isSafeInteger(e)||e<=0?null:e%1e6===0?`${e/1e6}M`:e%1e3===0?`${e/1e3}K`:e.toLocaleString("en-US")}function md(t,e){const s=hd(e);return s?t==="long_context"?`Long context (${s} tokens, higher cost)`:`Default (${s} tokens)`:Ir[t]||t}function Js(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 gd(t){return Js([t])}function Gi(t,e=[]){let s=wo(t);for(const n of e){const i=Io(s,n?.eventType,n?.data,{timestamp:n?.createdAt});i&&(s=i)}return s}function is(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(!is(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)||!is(t[i],e[i]))return!1;return!0}function Ui(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 Nn(t,e){const s=Ui(t?.updatedAt),n=Ui(e?.updatedAt);return s>0&&n>0&&n<=s}function yd(t){return!t||t==="idle"||t==="unknown"||t==="pending"}function Sd(t,e){return t?.status==="waiting"&&typeof t?.waitReason=="string"&&t.waitReason.trim().length>0&&(e?.waitReason===void 0||e?.waitReason===null)&&yd(e?.status)&&Nn(t,e)}function bd(t,e){return t?.cronActive===!0&&e?.cronActive!==!0&&!vr(e?.status)&&!xr(e?.orchestrationStatus)&&Nn(t,e)}function wd(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||is(t?.[a],l)||(s[a]=l,n=!0);if(e.pendingQuestion===void 0&&t?.pendingQuestion&&e.status!=="input_required"&&!Nn(t,e)&&(s.pendingQuestion=null,n=!0),Sd(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),xl(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),bd(t,e))for(const a of["cronActive","cronKind","cronInterval","cronReason","cronNextFireAt","cronTimezone","cronMaxFires","cronFiresCompleted"])t?.[a]!=null&&(is(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((vr(e.status)||xr(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 ji(t){return String(t||"").replace(/\r\n/g,`
67
- `).trim()}function xr(t){return t==="Completed"||t==="Failed"||t==="Terminated"}function vr(t){return t==="completed"||t==="failed"||t==="cancelled"}function ue(t){return String(t||"").slice(0,8)}function os(t){const e=String(t?.provider||"").trim(),s=String(t?.subject||"").trim();return e&&s?`${e}${s}`:null}function Gt(t,e="unknown user"){return String(t?.displayName||t?.email||"").trim()||e}const Id=os({provider:"system",subject:"system"});function Wi(t){const e=t.auth?.principal||null,s=os(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=Gt(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."}),n.push({id:"shared",kind:"shared",label:"Shared with me",description:"Show sessions other users have shared with you."})}const i=new Map;for(const o of Object.values(t.sessions?.byId||{})){const r=o?.owner,a=os(r);!a||a===s||a===Id||i.has(a)||i.set(a,r)}for(const[o,r]of[...i.entries()].sort((a,l)=>Gt(a[1]).localeCompare(Gt(l[1])))){const a=Gt(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 rs(t){return os(t)?{all:!1,includeSystem:!0,includeUnowned:!1,includeMe:!0,includeShared:!0,ownerKeys:[]}:{all:!0,includeSystem:!1,includeUnowned:!1,includeMe:!1,includeShared:!1,ownerKeys:[]}}function xd(t){return!!(t?.includeSystem||t?.includeUnowned||t?.includeMe||t?.includeShared||Array.isArray(t?.ownerKeys)&&t.ownerKeys.length>0)}function vd(t,e,s){const n=t||rs(s);if(!e)return n;if(e.kind==="all")return n.all?rs(s):{all:!0,includeSystem:!1,includeUnowned:!1,includeMe:!1,includeShared:!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==="shared"&&(i.includeShared=!i.includeShared),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 xd(i)?i:{all:!0,includeSystem:!1,includeUnowned:!1,includeMe:!1,includeShared:!1,ownerKeys:[]}}function On(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 Ed(t){const e=On(t);return e?Math.max(1,60-`${e}: `.length):60}function Ad(t){const e=String(t?.title||"").trim();if(!e)return"";const s=On(t);if(s&&e.startsWith(`${s}: `)){const n=e.slice(`${s}: `.length).trim();return!n||n===ue(t?.sessionId)?"":n}return e===ue(t?.sessionId)?"":e}function Vi(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 Ki(t){return`📎 ${String(t||"").trim()}`}function qi(t,e){const s=String(t||""),n=se(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 Td(t,e,s,n){const i=String(t||""),o=se(i,e),r=se(i,s),a=String(n||"");return{prompt:`${i.slice(0,o)}${a}${i.slice(r)}`,cursor:o+a.length}}function Cd(t,e="session"){return String(t||"").replace(/\s+/gu," ").trim()||e}function kd(t){const e=String(t?.sessionId||"").trim(),s=ue(e)||"session";return`Referenced session: ${Cd(t?.title,s)} — session://${e}`}function zi(t,e,s){if(!e)return je(t,String(t||"").length,s);const n=String(t||""),i=n.slice(e.tokenEnd,e.tokenEnd+1),o=!i||/\s/u.test(i);return Td(n,e.tokenStart,e.tokenEnd,`${String(s||"")}${o?" ":""}`)}function Md(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,`
68
- `).replace(/\n[ \t]+/g,`
69
- `).replace(/[ \t]{2,}/g," ").trim()}const Yi=new Set(["image/png","image/jpeg","image/gif","image/webp"]),Qi=4*1024*1024,Fs=4;function Pd(t,e=[]){const s=Array.isArray(e)?e.filter(o=>o?.sessionId&&o?.filename&&o?.kind!=="image"):[];if(s.length===0)return String(t||"");const n=s.map(o=>`[Attached file: ${o.filename} — artifact://${o.sessionId}/${o.filename}]`),i=Md(t,s);return n.join(`
70
- `)+(i?`
71
-
72
- ${i}`:"")}function it(t,e){return String(t||"").replace(/\r?\n/g," ").slice(0,Math.max(0,Number(e)||0))}function Er(t){return Array.from(String(t||"")).length}function Nd(t){const e=[];for(const s of t||[]){if(s?.kind==="markup"){const n=xo(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 Od(t,e){const s=Math.max(1,Number(e)||1),n=Er(t);return Math.max(1,Math.ceil(n/s))}function ot(t,e){const s=Math.max(1,Number(e)||1);return Nd(t).reduce((n,i)=>{if(!i)return n+1;if(Array.isArray(i)){const o=i.reduce((r,a)=>r+Er(a?.text||""),0);return n+Math.max(1,Math.ceil(o/s))}return n+Od(i.text||"",s)},0)}function se(t,e){const s=String(t||"");return Math.max(0,Math.min(Number(e)||0,s.length))}function Ar(t){return String(t||"").split(`
73
- `)}function _d(t,e){const n=String(t||"").slice(0,se(t,e)).split(`
74
- `),i=n[n.length-1]||"";return{line:Math.max(0,n.length-1),column:i.length}}function Rd(t,e,s){const n=Ar(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 se(t,r+o)}function je(t,e,s){const n=String(t||""),i=se(n,e),o=String(s||"");return{prompt:`${n.slice(0,i)}${o}${n.slice(i)}`,cursor:i+o.length}}function rt(t,e){const s=String(t||""),n=se(s,e);return n<=0?{prompt:s,cursor:n}:{prompt:`${s.slice(0,n-1)}${s.slice(n)}`,cursor:n-1}}function Ut(t){return/\s/u.test(t||"")}function Tr(t,e,s){const n=String(t||"");let i=se(n,e);if(s<0){for(;i>0&&Ut(n[i-1]);)i-=1;for(;i>0&&!Ut(n[i-1]);)i-=1;return i}for(;i<n.length&&Ut(n[i]);)i+=1;for(;i<n.length&&!Ut(n[i]);)i+=1;return i}function Ld(t,e){const s=String(t||""),n=se(s,e),i=Tr(s,n,-1);return i===n?{prompt:s,cursor:n}:{prompt:`${s.slice(0,i)}${s.slice(n)}`,cursor:i}}function Fd(t,e,s){const n=Ar(t);if(n.length<=1)return se(t,e);const i=_d(t,e),o=Math.max(0,Math.min(i.line+s,n.length-1));return o===i.line?se(t,e):Rd(t,o,i.column)}const Xi=3e3,$d=new Set(["logs","sequence"]),Bd=2e5,Dd=new Set([".md",".markdown",".mdown",".mkd",".mdx"]),Hd=new Set([".json",".jsonl"]),Gd=new Set([".png",".jpg",".jpeg",".gif",".webp",".svg",".ico",".pdf",".zip",".gz",".tgz",".tar",".wasm",".sqlite",".db"]);function Cr(t){const e=String(t||""),s=e.lastIndexOf(".");return s>=0?e.slice(s).toLowerCase():""}function Ud(t,e=""){const s=Cr(t),n=String(e||"").toLowerCase();return Gd.has(s)?!0:n.startsWith("image/")||n==="application/pdf"||n.startsWith("application/zip")||n==="application/wasm"}function Ji(t,e=Bd){const s=String(t??"");return s.length<=e?s:`${s.slice(0,e)}
75
-
76
- [Preview truncated at ${e.toLocaleString()} characters. Open the artifact directly if you need the full file.]`}function jd(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 Wd(t,e="",s=null){const n=[`Preview is not available here for ${t}.`,""];return e&&n.push(`Type: ${e}`),s!=null&&n.push(`Size: ${jd(s)}`),n.push("Download the artifact to open it in the default app."),n.join(`
77
- `)}function Zi(t,e,s="",n=null){const i=String(s||"").toLowerCase(),o=Cr(t);if(n?.isBinary===!0||Ud(t,s))return{content:Wd(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=Ji(e);if(Dd.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(Hd.has(o)||i.includes("json"))try{return{content:Ji(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 Vd{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,attempted:!1,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).filter(s=>s?.attempted!==!0)}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(E.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,n=null){const i=this.buildOutboxItem(s,"pending");return Array.isArray(n?.attachments)&&n.attachments.length>0&&(i.attachments=n.attachments),this.setSessionOutboxItems(e,[...this.getSessionOutbox(e),i]),i}addPendingImageFiles(e){const s=Array.from(e||[]).filter(Boolean),n=this.getPromptAttachments(),i=n.filter(a=>a?.kind==="image"),o=[],r=[];for(const a of s){const l=String(a.type||"").toLowerCase();if(!Yi.has(l)){r.push({name:a.name||"image",reason:"unsupported type"});continue}if((Number(a.size)||0)>Qi){r.push({name:a.name||"image",reason:"over 4 MB"});continue}if(i.length+o.length>=Fs){r.push({name:a.name||"image",reason:`max ${Fs} images`});continue}o.push({kind:"image",file:a,filename:String(a.name||"image"),contentType:l,sizeBytes:Number(a.size)||0})}return o.length>0&&this.setPromptAttachments([...n,...o]),r.length>0&&this.dispatch({type:"ui/status",text:`Skipped ${r.map(a=>`${a.name} (${a.reason})`).join(", ")}`}),{accepted:o.length,rejected:r}}stageUploadedImageAttachment(e,s){const n=String(e?.contentType||"").toLowerCase();return!Yi.has(n)||(Number(e?.sizeBytes)||0)>Qi||this.getPromptAttachments().filter(o=>o?.kind==="image").length>=Fs?!1:(this.setPromptAttachments([...this.getPromptAttachments(),{kind:"image",uploaded:!0,sessionId:s,filename:e.filename,contentType:n,sizeBytes:Number(e?.sizeBytes)||0}]),!0)}async pasteImageFromClipboard(){if(typeof this.transport.captureClipboardImage!="function"||typeof this.transport.uploadArtifactFromPath!="function")return this.dispatch({type:"ui/status",text:"Clipboard image paste is not supported by this transport"}),!1;let e=null;try{e=await this.transport.captureClipboardImage()}catch(s){return this.dispatch({type:"ui/status",text:`Clipboard read failed: ${s?.message||s}`}),!1}if(!e?.path)return this.dispatch({type:"ui/status",text:"No image on the clipboard"}),!1;this.dispatch({type:"ui/status",text:"Attaching clipboard image..."});try{const s=this.getPromptDraftSessionId()||await this.ensurePromptAttachmentSessionId(),n=await this.transport.uploadArtifactFromPath(s,e.path),i=await this.finalizeArtifactUpload(n,{sessionId:s,suppressStatus:!0});return this.stageUploadedImageAttachment(i,s)?(this.dispatch({type:"ui/status",text:`Clipboard image attached to your next message (${i.filename})`}),!0):(this.dispatch({type:"ui/status",text:`Uploaded ${i.filename} (not attachable: type/size/count limit)`}),!1)}catch(s){return this.dispatch({type:"ui/status",text:`Clipboard image attach failed: ${s?.message||s}`}),!1}}removePendingImageAttachment(e){const s=this.getPromptAttachments(),i=s.filter(o=>o?.kind==="image")[e];i&&this.setPromptAttachments(s.filter(o=>o!==i))}async uploadPendingImageAttachments(e,s,n){const i=[],o=String(n||Date.now()).replace(/[^a-zA-Z0-9_-]/g,"").slice(-24)||"img";let r=0;for(const a of s){if(!a.file){a.uploaded&&a.filename&&i.push({filename:a.filename});continue}r+=1;const l={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp"}[a.contentType]||"png",c=`attach-${o}-${r}.${l}`;await this.transport.uploadArtifactFromFile(e,a.file,c),i.push({filename:c})}return i}acknowledgeOutboxPrompt(e,s,n=null){if(!e)return!1;const i=this.getSessionOutbox(e);if(n){const l=i.findIndex(c=>(c?.phase==="pending"||c?.phase==="queued"||c?.phase==="cancelling")&&Array.isArray(c.clientMessageIds)&&c.clientMessageIds.includes(n));if(l!==-1){const c=i[l];return this.setSessionOutboxItems(e,i.filter((d,f)=>f!==l)),this.getPromptEditSessionMatch(e)?.itemId===c?.id&&this.exitPendingPromptEdit({restoreDraft:!0}),!0}}const o=ji(s);if(!o)return!1;const r=i.findIndex(l=>(l?.phase==="pending"||l?.phase==="queued"||l?.phase==="cancelling")&&ji(l.text)===o);if(r===-1)return!1;const a=i[r];return this.setSessionOutboxItems(e,i.filter((l,c)=>c!==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(d=>n.has(d)));if(o.length===i.length)return!1;const r=new Set(i.filter(l=>!o.some(c=>c.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),i=n.find(m=>m?.attempted===!0),o=i?[i]:n.filter(m=>m?.attempted!==!0);if(o.length===0)return!1;const r=o.flatMap(m=>Array.isArray(m.clientMessageIds)&&m.clientMessageIds.length>0?m.clientMessageIds:[m.id]),a=o.map(m=>String(m.text||"")).join(`
78
-
79
- `),l=o.flatMap(m=>Array.isArray(m.attachments)?m.attachments:[]),c={id:o[0].id,text:a,createdAt:o[0].createdAt||Date.now(),phase:"pending",attempted:!0,clientMessageIds:r,...l.length>0?{attachments:l}:{}},d=new Set(o.map(m=>m.id)),f=this.getSessionOutbox(e).filter(m=>!d.has(m.id));this.setSessionOutboxItems(e,[...f,c]);const p=this.getPromptEditSessionMatch(e);p&&d.has(p.itemId)&&this.exitPendingPromptEdit({restoreDraft:!0});const h=(async()=>{await this.transport.sendMessage(e,c.text,{enqueueOnly:!0,clientMessageIds:c.clientMessageIds,...Array.isArray(c.attachments)&&c.attachments.length>0?{attachments:c.attachments}:{}});const g=this.getSessionOutbox(e).map(b=>b.id===c.id?{...b,phase:"queued"}:b);return this.setSessionOutboxItems(e,g),this.syncSessionEvents(e).catch(()=>{}),this.scheduleSessionsRefresh(250),!0})().catch(m=>{const g=m?.code==="FORBIDDEN"||m?.code==="UNAUTHORIZED"||m?.status===403||m?.status===401,b=this.getSessionOutbox(e);if(g){const S=b.map(w=>w.id===c.id?{...w,phase:"rejected"}:w);this.setSessionOutboxItems(e,S),setTimeout(()=>{const w=this.getSessionOutbox(e),I=w.filter(A=>!(A.id===c.id&&A.phase==="rejected"));I.length!==w.length&&this.setSessionOutboxItems(e,I)},6e3)}else{const S=b.map(w=>w.id===c.id?{...c,phase:"pending",attempted:!0}:w);this.setSessionOutboxItems(e,S)}throw this.dispatch({type:"ui/status",text:m?.message||String(m)}),m}).finally(()=>{this.outboxFlushPromises.delete(e),this.getPendingOutboxItems(e).length>0&&this.scheduleOutboxDispatch(e)});return this.outboxFlushPromises.set(e,h),await h}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 qi(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=Ue(s),i=n?.sessionId||s.sessions.activeSessionId||null,o=n?.filename||null;if(!i||!o)return!1;const r=Ki(o),a=zi(s.ui.prompt,e,r),l=this.getPromptAttachments(),c=l.findIndex(p=>p?.sessionId===i&&p?.filename===o),d={...c>=0?l[c]:{},id:`${i}/${o}`,sessionId:i,filename:o,resolvedPath:o,token:r},f=c>=0?l.map((p,h)=>h===c?d:p):[...l,d];return this.setPrompt(a.prompt,a.cursor),this.setPromptAttachments(f),this.setFocus(E.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=yt(s)[0]||null,o=i?.sessionId&&s.sessions.byId[i.sessionId]||null;if(!o?.sessionId)return!1;const r=kd(o),a=zi(s.ui.prompt,e,r);return this.setPrompt(a.prompt,a.cursor),this.setFocus(E.PROMPT),this.dispatch({type:"ui/status",text:`Referenced session ${ue(o.sessionId)}`}),!0}setSessionFilterQuery(e=""){this.dispatch({type:"sessions/filterQuery",query:String(e||"")})}openSessionOwnerFilter(){const e=this.getState(),s=Wi(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=vd(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"}`})}refreshOpenSessionOwnerFilterModal(){const e=this.getState(),s=e.ui.modal;if(!s||s.type!=="sessionOwnerFilter")return;const n=Wi(e),i=Array.isArray(s.items)?s.items:[];if(i.length===n.length&&i.every((c,d)=>c?.id===n[d]?.id))return;const r=i[Math.max(0,Number(s.selectedIndex)||0)]?.id,a=r!=null?n.findIndex(c=>c.id===r):-1,l=a>=0?a:Math.max(0,Math.min(Number(s.selectedIndex)||0,Math.max(0,n.length-1)));this.dispatch({type:"ui/modal",modal:{...s,items:n,selectedIndex:l}})}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=qi(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(ns(this.getState(),"selectedSession")),a=_t(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({initialSessionId:e=null}={}){await this.transport.start();const s=typeof this.transport.getAuthContext=="function"?this.transport.getAuthContext():null;this.dispatch({type:"auth/context",principal:s?.principal??null,authorization:s?.authorization??null}),this.getState().sessions.ownerFilterExplicit||this.dispatch({type:"sessions/ownerFilter",filter:rs(s?.principal??null)});const n=typeof this.transport.getLogConfig=="function"?this.transport.getLogConfig():null;n&&this.dispatch({type:"logs/config",available:n.available,availabilityReason:n.availabilityReason}),this.dispatch({type:"connection/ready",workersOnline:typeof this.transport.getWorkerCount=="function"?this.transport.getWorkerCount():null,statusText:"Connected"});const i=String(e||"").trim();i&&this.dispatch({type:"sessions/navigationIntent",sessionId:i}),await this.refreshSessions(),this.catalogTimer=setInterval(()=>{this.refreshSessions().catch(o=>{this.dispatch({type:"connection/error",error:o?.message||String(o),statusText:Di})})},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===Di,i=this.getState().sessions.activeSessionId;let o=(await dd(this.transport)).map(_s);if(typeof this.transport.listSessionGroups=="function"){const d=await this.transport.listSessionGroups().catch(()=>[]),f=(Array.isArray(d)?d:[]).map(cd).filter(Boolean);f.length>0&&(o=[...f,...o])}const r=e.sessions.navigationIntent;if(r?.status==="pending"&&!o.some(d=>d?.sessionId===r.sessionId)&&typeof this.transport.getSession=="function")try{const d=await this.transport.getSession(r.sessionId);d?.sessionId?o=[...o,_s(d)]:this.dispatch({type:"sessions/navigationIntentFailed",sessionId:r.sessionId,errorKind:"not_found"})}catch(d){this.dispatch({type:"sessions/navigationIntentFailed",sessionId:r.sessionId,errorKind:Ls(d)})}const a=i;if(a&&!o.some(d=>d?.sessionId===a)&&typeof this.transport.getSession=="function"){const d=await this.transport.getSession(a).catch(()=>null);d?.sessionId&&(o=[...o,_s(d)])}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}),this.refreshOpenSessionOwnerFilterModal();const l=this.getState().sessions.activeSessionId,c=new Set;if(l){if(l!==i){if(!this.getState().sessions.byId[l]?.isGroup){const h=this.getState().sessions.navigationIntent;if(h&&h.sessionId===l&&h.status!=="failed")try{await this.loadSession(l)}catch(m){this.dispatch({type:"sessions/navigationIntentFailed",sessionId:l,errorKind:Ls(m)})}else await this.loadSession(l)}return}if(this.getState().sessions.byId[l]?.isGroup)return;this.getState().history.bySessionId.get(l)?.events?.length||await this.ensureSessionHistory(l,{force:!0}).catch(()=>{}),this.activeSessionSubscriptionId!==l&&this.attachActiveSession(l),await this.syncSessionDetail(l).catch(()=>{}),await this.syncSessionEvents(l).catch(()=>{}),c.add(l);const f=this.getState(),p=f.sessions.byId[l]||null;if(p?.parentSessionId&&typeof this.transport.getSession=="function"){const h=Object.values(f.sessions.byId).filter(m=>m?.parentSessionId===p.parentSessionId).map(m=>m.sessionId).filter(m=>m&&m!==l).slice(0,6);await Promise.all(h.map(m=>this.syncSessionDetail(m).catch(()=>{})));for(const m of h)c.add(m)}}await this.syncVisibleSessionDetails(c).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 d=r.filter(([f,p])=>f!==s&&!p?.loading).sort((f,p)=>(f[1]?.fetchedAt||0)-(p[1]?.fetchedAt||0)).slice(0,r.length-o).filter(([,f])=>n-(f?.fetchedAt||0)>i);d.length>0&&this.dispatch({type:"orchestration/evict",sessionIds:d.map(([f])=>f)})}const a=Object.entries(e.executionHistory?.bySessionId||{});if(a.length>o){const d=a.filter(([f,p])=>f!==s&&!p?.loading).sort((f,p)=>(f[1]?.fetchedAt||0)-(p[1]?.fetchedAt||0)).slice(0,a.length-o).filter(([,f])=>n-(f?.fetchedAt||0)>i);d.length>0&&this.dispatch({type:"executionHistory/evict",sessionIds:d.map(([f])=>f)})}const l=Object.entries(e.files.bySessionId||{});if(l.length>o){const d=l.filter(([f])=>f!==s).slice(0,l.length-o);d.length>0&&this.dispatch({type:"files/evictPreviews",sessionIds:d.map(([f])=>f)})}const c=[...e.history.bySessionId.entries()];if(c.length>o*2){const d=c.filter(([f])=>f!==s).slice(0,c.length-o*2).map(([f])=>f);d.length>0&&this.dispatch({type:"history/evict",sessionIds:d})}}async syncVisibleSessionDetails(e=new Set){if(typeof this.transport.getSession!="function")return;const s=this.getState(),n=Mt({width:s.ui.layout.viewportWidth,height:s.ui.layout.viewportHeight},s.ui.layout.paneAdjust,s.ui.promptRows??pt(s.ui.prompt),s.ui.layout.sessionPaneAdjust,s.ui.layout.activityPaneAdjust,s.ui.fullscreenPane),i=this.getSessionListMaxRows(n),o=Ks(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 catchUpSessionHistory(e,s,n){let o;try{o=await this.transport.getSessionEvents(e,n,1e3)}catch{return null}if(!Array.isArray(o)||o.length>=1e3)return null;if(o.length===0)return s;let r=s;for(const d of o)r=ti(r,d);r={...r,loadedEventLimit:Math.max(Number(s.loadedEventLimit)||0,Array.isArray(r.events)?r.events.length:0)},this.dispatch({type:"history/set",sessionId:e,history:r});for(const d of o)this.reconcileOutboxAgainstEvent(e,d);const a=Js(o),l=this.getState().sessions.byId[e]||{},c=Gi(l.contextUsage,o);return(a||c)&&this.dispatch({type:"sessions/merged",session:{sessionId:e,...a||{},...c?{contextUsage:c}:{}}}),r}async ensureSessionHistory(e,{force:s=!1}={}){if(!e)return null;const n=this.getState().history.bySessionId.get(e),i=Math.max(X,Number(n?.loadedEventLimit??X)||X);if(!s&&n?.events)return n;if(!s&&this.sessionHistoryLoads.has(e))return this.sessionHistoryLoads.get(e);const o=Number(n?.lastSeq)||0;if(s&&o>0&&Array.isArray(n?.events)&&n.events.length>0){const a=await this.catchUpSessionHistory(e,n,o);if(a)return a}const r=(async()=>{const a=await this.transport.getSessionEvents(e,void 0,i),l={...Bt(a,{requestedLimit:i}),lastSeq:a[a.length-1]?.seq||0};this.dispatch({type:"history/set",sessionId:e,history:l});for(const p of a||[])this.reconcileOutboxAgainstEvent(e,p);const c=Js(a),d=this.getState().sessions.byId[e]||{},f=Gi(d.contextUsage,a);return(c||f)&&this.dispatch({type:"sessions/merged",session:{sessionId:e,...c||{},...f?{contextUsage:f}:{}}}),l})().finally(()=>{this.sessionHistoryLoads.delete(e)});return this.sessionHistoryLoads.set(e,r),r}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=Mt({width:s.ui.layout.viewportWidth,height:s.ui.layout.viewportHeight},s.ui.layout.paneAdjust,s.ui.promptRows??pt(s.ui.prompt),s.ui.layout.sessionPaneAdjust,s.ui.layout.activityPaneAdjust,s.ui.fullscreenPane),i=this.getSessionListMaxRows(n),o=Ks(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(we(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<td)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<sd)){this.dispatch({type:"sessionStats/loading",sessionId:s});try{const[o,r,a,l,c,d,f]=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:c,factsStats:d,treeFactsStats:f})}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<nd)){this.dispatch({type:"fleetStats/loading"});try{const o={since:new Date(Date.now()-id*864e5),includeDeleted:!0},[r,a,l,c,d,f]=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:c,sharedFactsStats:d,factsTombstoneStats:f})}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}),await this.refreshSystemGhcpKeyStatus(e),e||null}catch(e){return this.dispatch({type:"admin/profile/loadFailed",error:e?.message||String(e)}),null}}async refreshSystemGhcpKeyStatus(e=null){if(!(e||this.getState().admin?.profile||null)?.isAdmin||typeof this.transport.getSystemGitHubCopilotKeyStatus!="function")return null;this.dispatch({type:"admin/systemGhcpKey/loading"});try{const n=await this.transport.getSystemGitHubCopilotKeyStatus();return this.dispatch({type:"admin/systemGhcpKey/loaded",status:n}),n||null}catch(n){return this.dispatch({type:"admin/systemGhcpKey/loadFailed",error:n?.message||String(n)}),null}}setAdminGhcpKeyStoreAsSystem(e){e&&!this.getState().admin?.profile?.isAdmin||this.dispatch({type:"admin/ghcpKey/setSystemTarget",value:!!e})}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=je(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=rt(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,se(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(){const e=!!this.getState().admin.ghcpKey.storeAsSystem,s=e?"setSystemGitHubCopilotKey":"setCurrentUserGitHubCopilotKey";if(typeof this.transport[s]!="function"){this.dispatch({type:"admin/ghcpKey/saveFailed",error:e?"This deployment does not support System keys yet.":"Admin Console is not available on this transport."});return}const n=String(this.getState().admin.ghcpKey.draft||"").trim();if(n.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{if(e){const i=await this.transport.setSystemGitHubCopilotKey({key:n});this.dispatch({type:"admin/systemGhcpKey/saved",status:i})}else{const i=await this.transport.setCurrentUserGitHubCopilotKey({key:n});this.dispatch({type:"admin/ghcpKey/saved",profile:i})}}catch(i){this.dispatch({type:"admin/ghcpKey/saveFailed",error:i?.message||String(i)})}}async clearAdminGhcpKey(){const e=!!this.getState().admin.ghcpKey.storeAsSystem,s=e?"setSystemGitHubCopilotKey":"setCurrentUserGitHubCopilotKey";if(typeof this.transport[s]!="function"){this.dispatch({type:"admin/ghcpKey/saveFailed",error:e?"This deployment does not support System keys yet.":"Admin Console is not available on this transport."});return}this.dispatch({type:"admin/ghcpKey/saving"});try{if(e){const n=await this.transport.setSystemGitHubCopilotKey({key:null});this.dispatch({type:"admin/systemGhcpKey/saved",status:n})}else{const n=await this.transport.setCurrentUserGitHubCopilotKey({key:null});this.dispatch({type:"admin/ghcpKey/saved",profile:n})}}catch(n){this.dispatch({type:"admin/ghcpKey/saveFailed",error:n?.message||String(n)})}}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=we(this.getState()),{force:s=!1}={}){const n=ns(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=Ue(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=wl(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?Zi(s,"",r.contentType||"",r):Zi(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=Ue(e);if(!s?.sessionId||!s?.filename){this.dispatch({type:"ui/status",text:e.sessions.activeSessionId||we(e)==="allSessions"?"No file selected":"No session selected"});return}const{sessionId:n,filename:i}=s,o=we(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 ${ue(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=Ue(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=Ue(s);if(!n?.sessionId||!n?.filename)return this.dispatch({type:"ui/status",text:"No artifact selected"}),!1;const i=we(s),o=i==="allSessions"?`${ue(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=Ue(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 ${ue(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=gc(e),i=yc(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=we(this.getState());await this.ensureFilesForScope(s);const n=_t(this.getState());if(n.length===0)return;const i=Ue(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 ${ue(a.sessionId)} ${a.filename}`:`Previewing ${a.filename}`}))}async selectFileBrowserItem(e){if(!e?.sessionId||!e?.filename)return;const s=we(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 ${ue(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===E.PROMPT?n:s;if(!ld.has(i)||i===E.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===E.PROMPT&&this.setFocus(i)}openFilesFilter(){const e=we(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"}`})}setNavigationIntent(e){const s=String(e||"").trim();if(!s)return;this.dispatch({type:"sessions/navigationIntent",sessionId:s});const n=this.getState();if(n.sessions.byId[s]){this.loadSession(s).catch(i=>{this.dispatch({type:"sessions/navigationIntentFailed",sessionId:s,errorKind:Ls(i)})});return}Object.keys(n.sessions.byId).length>0&&this.scheduleSessionsRefresh(0)}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.dispatch({type:"ui/sequenceExpandedTurns",turns:[]}),this.dispatch({type:"ui/sequenceSelectedTurn",turn:null})),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:ti(i,s)}),s.eventType==="session.input_required_started"&&s.data?.question&&this.dispatch({type:"sessions/merged",session:{sessionId:e,status:"input_required",pendingQuestion:{question:s.data.question,choices:Array.isArray(s.data.choices)?s.data.choices:void 0,allowFreeform:s.data.allowFreeform??!0}}}),this.reconcileOutboxAgainstEvent(e,s);const o=gd(s),r=this.getState().sessions.byId[e]||{sessionId:e},a=Io(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=wd(n,s);(i||n?.rowVisualStatusCandidate)&&this.dispatch({type:"sessions/merged",session:i||{sessionId:e}}),this.maybeFlushQueuedOutbox(e,s)}async createSession(e={}){try{const s=this.applyActiveGroupDefault(e),n=await this.transport.createSession(s);return await this.placeCreatedSessionInGroup(n,s.groupId??null),await this.refreshSessions(),await this.loadSession(n.sessionId),this.setFocus(E.PROMPT),this.dispatch({type:"ui/status",text:`Created session ${n.sessionId.slice(0,8)}`}),n}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=this.applyActiveGroupDefault(s),i=await this.transport.createSessionForAgent(e,n);return await this.placeCreatedSessionInGroup(i,n.groupId??null),await this.refreshSessions(),await this.loadSession(i.sessionId),this.setFocus(E.PROMPT),this.dispatch({type:"ui/status",text:`Created ${Vi(e,s.title)} session ${i.sessionId.slice(0,8)}`}),i}catch(n){return this.dispatch({type:"ui/status",text:n?.message||String(n)||"Failed to create session"}),null}}async placeCreatedSessionInGroup(e,s){!s||!e?.sessionId||typeof this.transport.placeSessionsInGroup=="function"&&(e.viewerGroupId??null)!==s&&await this.transport.placeSessionsInGroup([e.sessionId],s).catch(()=>{})}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(l=>l.sessionId),o=s.length===1&&s[0].groupId||null,r=[{id:"__no_group__",kind:"noGroup",label:"[No Group]",description:"Remove the selected session(s) from any group.",groupId:null,memberCount:0},{id:"__new_group__",kind:"newGroup",label:"[New Group]",description:"Create a new group, then move the selected session(s) into it.",groupId:null,memberCount:0},...(Array.isArray(n)?n:[]).map(l=>({id:l.groupId,kind:"group",label:l.title||l.groupId,description:l.description||"Move selected session(s) into this group.",groupId:l.groupId,memberCount:l.memberCount??0}))],a=o?Math.max(0,r.findIndex(l=>l.groupId===o)):Math.min(1,r.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(l=>l.title||l.sessionId.slice(0,8)),selectedIndex:a>=0?a:0,items:r}}),this.dispatch({type:"ui/status",text:"Choose a group, [New Group], or [No Group]"}),r}async createSessionGroupFromSelection(){return this.openMoveToGroupModal()}async moveSessionsToGroup(e,s,{statusTitle:n=null}={}){const i=Array.from(new Set((Array.isArray(s)?s:[]).map(f=>String(f||"").trim()).filter(Boolean)));if(i.length===0)return this.dispatch({type:"ui/status",text:"No sessions selected to move"}),null;let o=null;if(typeof this.transport.placeSessionsInGroup=="function")o=await this.transport.placeSessionsInGroup(i,e??null);else 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;const r=Array.isArray(o)?o.filter(Boolean):null,a=r?r.filter(f=>f.placed!==!0):[],l=r?r.filter(f=>f.placed===!0).length:i.length;this.dispatch({type:"sessions/selectClear"}),await this.refreshSessions(),e&&l>0&&await this.loadSession(`group:${e}`).catch(()=>{});const c=e?`group ${n||e}`:"No Group",d=a.length>0?` · skipped ${a.length} (${ud(a)})`:"";return this.dispatch({type:"ui/status",text:l>0?`Moved ${l} session${l===1?"":"s"} to ${c}${d}`:`No sessions moved to ${c}${d}`}),l>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||[],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=it(e,n.maxLength||80),o=se(i,s);this.updateSessionGroupNameModal({value:i,cursorIndex:o})}insertSessionGroupNameText(e){const s=this.getState().ui.modal;if(!s||s.type!=="sessionGroupName")return;const n=je(s.value||"",s.cursorIndex||0,it(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=rt(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||"",se(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||[]});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||Rs(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,splashMobile:null,initialPrompt:null});for(const r of s){const a=String(r?.name||"").trim();a&&o.push({id:a,kind:"agent",agentName:a,title:Vi(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,splashMobile:typeof r?.splashMobile=="string"&&r.splashMobile.trim()?r.splashMobile: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=Qs(e?.supportedReasoningEfforts),i=s?.reasoningEffort||Hi(e);if(!n.length||!i){await this.openContextTierPicker(e,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 openContextTierPicker(e,s={}){const n=Xs(e?.supportedContextTiers),i=s?.contextTier||pd(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,tier:a,tokenLimit:e?.contextWindowSizes?.[a]||null,label:md(a,e?.contextWindowSizes?.[a]),isDefault:i===a})),r=Math.max(0,o.findIndex(a=>a.id===i));this.dispatch({type:"ui/modal",modal:{type:"contextTierPicker",title:`Context window 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 context window 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():fd(s),o=await this._resolveGhcpUserKeySet(),r=[],a=i.map(d=>({providerId:d.providerId,providerType:d.type||d.providerType,models:(d.models||[]).map(f=>{const p=f.providerType||d.type||d.providerType,h=p==="github"&&f.credentialAvailable===!1&&o===!1,m={id:f.qualifiedName,qualifiedName:f.qualifiedName,modelName:f.modelName||f.qualifiedName,providerId:f.providerId||d.providerId,providerType:p,description:f.description||"",cost:f.cost||null,supportedReasoningEfforts:Qs(f.supportedReasoningEfforts),defaultReasoningEffort:f.defaultReasoningEffort||null,supportedContextTiers:Xs(f.supportedContextTiers),defaultContextTier:f.defaultContextTier||null,contextWindowSizes:f.contextWindowSizes||null,isDefault:n===f.qualifiedName,ghcpKeyMissing:h,disabled:h};return r.push(m),m})})).filter(d=>d.models.length>0),l=e?.model||n;let c=r.findIndex(d=>d.qualifiedName===l&&!d.disabled);c<0&&(c=r.findIndex(d=>!d.disabled)),c<0&&(c=0),this.dispatch({type:"ui/modal",modal:{type:"modelPicker",title:e?.mode==="switchModel"?"Switch model for session":"Select model for new session",items:r,groups:a,selectedIndex:c,previousFocus:this.getState().ui.focusRegion,sessionOptions:e}}),this.dispatch({type:"ui/status",text:"Select a model and press Enter"})}async _resolveGhcpUserKeySet(){const e=this.getState().admin?.profile;if(typeof e?.githubCopilotKeySet=="boolean")return e.githubCopilotKeySet;if(typeof this.transport.getCurrentUserProfile!="function")return null;try{const s=await this.transport.getCurrentUserProfile();return s&&typeof s.githubCopilotKeySet=="boolean"?s.githubCopilotKeySet:!1}catch{return null}}async openSwitchModelPicker(e=null){this._onSwitchModelApplied=typeof e=="function"?e:null;const s=this.getState(),n=s.sessions.activeSessionId,i=n&&s.sessions.byId[n]||null;if(!i||i.isGroup){this._onSwitchModelApplied=null,this.dispatch({type:"ui/status",text:"Select a session before switching model"});return}if(typeof this.transport.setSessionModel!="function"){this._onSwitchModelApplied=null,this.dispatch({type:"ui/status",text:"Model switching is not supported by this transport"});return}await this.openModelPicker({mode:"switchModel",sessionId:n,model:i.model||void 0,reasoningEffort:i.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}:{},..."contextTier"in e?{contextTier:e.contextTier??null}:{},source:"ui"});const i=e.reasoningEffort?`${n}:${e.reasoningEffort}`:n,o=e.contextTier?` · ${Ir[e.contextTier]||e.contextTier}`:"";this.dispatch({type:"ui/status",text:`Next turn will use ${i}${o}`}),await this.refreshSessions();const r=this._onSwitchModelApplied;this._onSwitchModelApplied=null,typeof r=="function"&&r()}openHelpModal(){this.dispatch({type:"ui/modal",modal:{type:"help",title:"Keybindings",selectedIndex:0,previousFocus:this.getState().ui.focusRegion}}),this.dispatch({type:"ui/status",text:"Keybindings — ? or Esc to close"})}openThemePicker(){const e=yl().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 (${ue(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=se(i,s);this.updateArtifactUploadModal({value:i,cursorIndex:o})}insertArtifactUploadText(e){const s=this.getState().ui.modal;if(!s||s.type!=="artifactUpload")return;const n=je(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=rt(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||"",se(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=Ki(e.filename),r=this.getState().ui.prompt,a=this.getState().ui.promptCursor,l=this.getPromptAttachments(),c=l.findIndex(f=>f?.sessionId===i&&f?.filename===e.filename);if(this.getState().sessions.activeSessionId!==i&&await this.loadSession(i),c===-1||!r.includes(l[c]?.token||o)){const f=je(r,a,`${o} `);this.setPrompt(f.prompt,f.cursor)}const d=c>=0?l.map((f,p)=>p===c?{...f,sessionId:i,filename:e.filename,resolvedPath:e.resolvedPath||e.localPath||e.filename,sizeBytes:e.sizeBytes,token:o}:f):[...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(d),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(E.PROMPT),n||this.dispatch({type:"ui/status",text:c>=0?`Re-attached ${e.filename}`:`Attached ${e.filename}`}),{sessionId:i,existingAttachmentIndex:c,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 c=await this.transport.uploadArtifactFromFile(i,l);o.push(c),await this.finalizeArtifactUpload(c,{sessionId:i,suppressStatus:!0})}catch(c){r+=1,a=c}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});if(this.dispatch({type:"ui/modal",modal:null}),this.stageUploadedImageAttachment(o,n)){this.dispatch({type:"ui/status",text:`Uploaded ${o.filename} — attached to your next message`});return}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=Ad(n),o=On(n),r=Ed(n);this.dispatch({type:"ui/modal",modal:{type:"renameSession",title:`Rename (${ue(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 (${ue(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=it(e,n.maxLength),o=se(i,s);this.updateRenameSessionModal({value:i,cursorIndex:o})}insertRenameSessionText(e){const s=this.getState().ui.modal;if(!s||s.type!=="renameSession")return;const n=je(s.value||"",s.cursorIndex||0,it(e,s.maxLength));this.setRenameSessionValue(n.prompt,n.cursor)}deleteRenameSessionChar(){const e=this.getState().ui.modal;if(!e||e.type!=="renameSession")return;const s=rt(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||"",se(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||Rs(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 ${ue(s)}...`});try{await this.transport.renameSession(s,n),await this.refreshSessions(),this.scheduleSessionDetailSync(s,100),this.dispatch({type:"ui/status",text:`Renamed ${ue(s)}`})}catch(a){this.dispatch({type:"ui/status",text:`Rename failed: ${a?.message||String(a)}`})}}async cycleSessionVisibility(){const e=this.getState(),s=e.sessions.activeSessionId,n=s?e.sessions.byId[s]:null;if(!n){this.dispatch({type:"ui/status",text:"No session selected"});return}if(n.isSystem){this.dispatch({type:"ui/status",text:"System sessions are always private"});return}if(n.isGroup){this.dispatch({type:"ui/status",text:"Groups don't have visibility"});return}if(typeof this.transport.setSessionVisibility!="function"){this.dispatch({type:"ui/status",text:"Not supported by this transport"});return}const i=tt(["private","shared_read","shared_write"],n.visibility||"private",1);try{await this.transport.setSessionVisibility(s,i),await this.refreshSessions(),this.dispatch({type:"ui/status",text:`Visibility → ${i}`})}catch(o){this.dispatch({type:"ui/status",text:o?.message||String(o)})}}async openShareSessionModal(){const e=this.getState(),s=e.sessions.activeSessionId,n=s?e.sessions.byId[s]:null;if(!n){this.dispatch({type:"ui/status",text:"No session selected"});return}if(n.isSystem){this.dispatch({type:"ui/status",text:"System sessions are always private"});return}if(n.isGroup){this.dispatch({type:"ui/status",text:"Groups can't be shared"});return}if(typeof this.transport.listSessionShares!="function"){this.dispatch({type:"ui/status",text:"Session sharing is not supported by this transport"});return}let i;try{i=await this.transport.listSessionShares(s)}catch(o){this.dispatch({type:"ui/status",text:o?.message||String(o)});return}this.dispatch({type:"ui/modal",modal:{type:"shareSession",title:`Share (${ue(s)})`,sessionId:s,previousFocus:e.ui.focusRegion,value:"",cursorIndex:0,shares:Array.isArray(i)?i:[],visibility:n.visibility||"private"}}),this.dispatch({type:"ui/status",text:"name [r|w] grants · -name revokes · Enter apply"})}updateShareSessionModal(e){const s=this.getState().ui.modal;if(!s||s.type!=="shareSession")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}setShareSessionValue(e,s=String(e||"").length){const n=this.getState().ui.modal;if(!n||n.type!=="shareSession")return;const i=it(e,120),o=se(i,s);this.updateShareSessionModal({value:i,cursorIndex:o})}insertShareSessionText(e){const s=this.getState().ui.modal;if(!s||s.type!=="shareSession")return;const n=je(s.value||"",s.cursorIndex||0,it(e,120));this.setShareSessionValue(n.prompt,n.cursor)}deleteShareSessionChar(){const e=this.getState().ui.modal;if(!e||e.type!=="shareSession")return;const s=rt(e.value||"",e.cursorIndex||0);this.setShareSessionValue(s.prompt,s.cursor)}moveShareSessionCursor(e){const s=this.getState().ui.modal;!s||s.type!=="shareSession"||this.setShareSessionValue(s.value||"",se(s.value||"",(s.cursorIndex||0)+e))}moveShareSessionCursorToBoundary(e){const s=this.getState().ui.modal;!s||s.type!=="shareSession"||this.setShareSessionValue(s.value||"",e==="start"?0:String(s.value||"").length)}async confirmShareSessionModal(){const e=this.getState().ui.modal;if(!e||e.type!=="shareSession")return;const s=e.sessionId;if(!s)return;const n=String(e.value||"").trim(),i=e.previousFocus;if(!n){this.dispatch({type:"ui/modal",modal:null}),i&&this.setFocus(i);return}const o=n.startsWith("-")?n.slice(1).trim():n.toLowerCase().startsWith("revoke ")?n.slice(7).trim():null;if(o!==null){const h=o.toLowerCase(),m=(e.shares||[]).find(g=>g.subject&&String(g.subject).toLowerCase()===h||g.email&&String(g.email).toLowerCase()===h||g.displayName&&String(g.displayName).toLowerCase()===h);if(!m){this.dispatch({type:"ui/status",text:`No grant matching "${o}"`});return}this.dispatch({type:"ui/modal",modal:null}),i&&this.setFocus(i);try{await this.transport.revokeSessionShare(s,{provider:m.provider,subject:m.subject}),this.dispatch({type:"ui/status",text:`Revoked ${o}`})}catch(g){this.dispatch({type:"ui/status",text:g?.message||String(g)})}return}const r=n.split(/\s+/),a={r:"read",read:"read",w:"write",write:"write"},l=r.length>1?r[r.length-1].toLowerCase():null,c=l&&a[l]?a[l]:"read",d=l&&a[l]?r.slice(0,-1).join(" "):n,f=d.toLowerCase();let p=null;if(typeof this.transport.listKnownUsers=="function"){let h=[];try{h=await this.transport.listKnownUsers({limit:500})}catch{h=[]}const m=Array.isArray(h)?h:[];if(p=m.find(g=>g.displayName&&g.displayName.toLowerCase()===f||g.email&&g.email.toLowerCase()===f||g.subject&&g.subject.toLowerCase()===f)||null,!p){const g=m.filter(b=>b.displayName&&b.displayName.toLowerCase().includes(f)||b.email&&b.email.toLowerCase().includes(f)||b.subject&&b.subject.toLowerCase().includes(f));if(g.length===1)p=g[0];else if(g.length>1){this.dispatch({type:"ui/status",text:`"${d}" is ambiguous (${g.length} matches)`});return}}}p||(p={provider:(this.getState().auth?.principal||null)?.provider||"dev",subject:d,email:null,displayName:null}),this.dispatch({type:"ui/modal",modal:null}),i&&this.setFocus(i);try{await this.transport.grantSessionShare(s,{provider:p.provider,subject:p.subject,email:p.email??null,displayName:p.displayName??null},c),this.dispatch({type:"ui/status",text:`Granted ${c} to ${d}`})}catch(h){this.dispatch({type:"ui/status",text:h?.message||String(h)})}}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)return;if(s.type==="help"){const o=Math.max(0,Number(s.selectedIndex)||0);this.dispatch({type:"ui/modalSelection",index:Math.max(0,o+e)});return}if(!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(f=>f.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],c=tt(a,l,e),d=r.options.find(f=>f.id===c)||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]:c},...s.type==="historyFormat"?{format:c}:{}}),s.type==="filesFilter"&&(this.ensureFilesForScope(c).catch(()=>{}),this.ensureSelectedFilePreview().catch(()=>{})),this.dispatch({type:"ui/status",text:`${s.type==="filesFilter"?"Files":s.type==="historyFormat"?"History":"Log"} filter updated: ${r.label} = ${d?.label||c}`});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==="help"){this.closeModal();return}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==="shareSession"){await this.confirmShareSessionModal();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=ze(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];if(s?.disabled){this.dispatch({type:"ui/status",text:s.ghcpKeyMissing?"This model needs a GitHub Copilot key — add yours in the Admin console first":"This model is not available"});return}const 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=Hi(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||{};this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n),await this.openContextTierPicker(e.modelItem,{...i,...s?.id?{reasoningEffort:s.id}:{}});return}if(e.type==="contextTierPicker"){const s=e.items?.[e.selectedIndex||0],n=e.previousFocus,i=e.sessionOptions||{};this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n);const o={...i,...s?.id?{contextTier:s.id}:{}};if(i?.mode==="switchModel"){await this.switchSessionModel({...o,model:e.modelItem?.id||i.model});return}await this.openSessionAgentPicker(o);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.splashMobile?{splashMobile:s.splashMobile}:{},...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=Pd(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 g=await this.createSession({});if(!g?.sessionId)return;r=g.sessionId,a=this.getState().sessions.byId[r]||null}const l=n.some(g=>g?.kind==="image");if(!o.trim()&&!l){r&&this.getPendingOutboxItems(r).length>0&&await this.dispatchPendingOutbox(r).catch(()=>{});return}const c=a?.pendingQuestion||null,d=!!c?.question,f=this.getPromptEditSessionMatch(r);if(f){const g=this.getSessionOutbox(r).find(b=>b.id===f.itemId);if(g?.phase==="queued"||g?.phase==="cancelling"){this.exitPendingPromptEdit({restoreDraft:!0});return}this.setPrompt("",0),this.setPromptAttachments([]),await this.dispatchPendingOutbox(r).catch(()=>{});return}if(d&&typeof this.transport.sendAnswer=="function"){const g=Date.now(),b={...c,answer:o,answeredAt:g,pendingPhase:"pending"};this.setPrompt("",0),this.setPromptAttachments([]),this.dispatch({type:"sessions/merged",session:{sessionId:r,pendingQuestion:null,answeredPendingQuestion:b}}),this.dispatch({type:"ui/status",text:"Sending answer..."});try{await this.transport.sendAnswer(r,o),this.dispatch({type:"sessions/merged",session:{sessionId:r,answeredPendingQuestion:{...b,pendingPhase:"queued"}}}),this.scheduleSessionDetailSync(r,100),this.syncSessionEvents(r).catch(()=>{}),this.scheduleSessionsRefresh(1e3),this.dispatch({type:"ui/status",text:"Answer sent"})}catch(S){this.dispatch({type:"sessions/merged",session:{sessionId:r,answeredPendingQuestion:null}}),this.dispatch({type:"sessions/merged",session:{sessionId:r,pendingQuestion:c}}),String(this.getState().ui.prompt||"").trim()||this.setPrompt(o,String(o||"").length),this.dispatch({type:"ui/status",text:S?.message||String(S)})}return}const p=n.filter(g=>g?.kind==="image");let h=null;if(p.length>0){if(p.some(S=>S.file)&&typeof this.transport.uploadArtifactFromFile!="function"){this.dispatch({type:"ui/status",text:"This transport does not support image attachments."});return}const b=this.buildOutboxItem("","pending");this.dispatch({type:"ui/status",text:`Uploading ${p.length} image${p.length>1?"s":""}...`});try{h=await this.uploadPendingImageAttachments(r,p,b.id),this.dispatch({type:"ui/status",text:""})}catch(S){this.dispatch({type:"ui/status",text:`Image upload failed: ${S?.message||S}`});return}}const m=o.trim()?o:h&&h.length>0?"See the attached image(s).":o;this.queuePromptInOutbox(r,m,h?{attachments:h}:null),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.attempted!==!0?{...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=je(s.prompt,s.promptCursor,e);this.setPrompt(n.prompt,n.cursor)}appendPromptChar(e){this.insertPromptText(e)}deletePromptChar(){const e=this.getState().ui,s=rt(e.prompt,e.promptCursor);this.setPrompt(s.prompt,s.cursor)}deletePromptWordBackward(){const e=this.getState().ui,s=Ld(e.prompt,e.promptCursor);this.setPrompt(s.prompt,s.cursor)}movePromptCursor(e){const s=this.getState().ui;this.setPrompt(s.prompt,se(s.prompt,s.promptCursor+e))}movePromptCursorWord(e){const s=this.getState().ui;this.setPrompt(s.prompt,Tr(s.prompt,s.promptCursor,e))}movePromptCursorVertical(e){const s=this.getState().ui,n=Fd(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 Mt({width:e.width??s.viewportWidth??120,height:e.height??s.viewportHeight??40},e.paneAdjust??s.paneAdjust??0,e.promptRows??n.promptRows??pt(i),e.sessionPaneAdjust??s.sessionPaneAdjust??0,e.activityPaneAdjust??s.activityPaneAdjust??0,e.fullscreenPane??n.fullscreenPane??null)}getSessionListMaxRows(e=this.getCurrentLayout()){const s=e.fullscreenPane===E.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=Fe(r,o);a!==r&&this.setFocus(a)}setFocus(e){this.dispatch({type:"ui/focus",focusRegion:Fe(e,this.getCurrentLayout())})}focusNext(){const e=this.getCurrentLayout(),s=Fe(this.getState().ui.focusRegion,e),n=js(e);this.setFocus(tt(n,s,1))}focusPrev(){const e=this.getCurrentLayout(),s=Fe(this.getState().ui.focusRegion,e),n=js(e);this.setFocus(tt(n,s,-1))}focusLeft(){const e=this.getCurrentLayout(),s=Fe(this.getState().ui.focusRegion,e);this.setFocus(Ka(s,e))}focusRight(){const e=this.getCurrentLayout(),s=Fe(this.getState().ui.focusRegion,e);this.setFocus(qa(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=Fe(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=Fe(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=Fe(a,r);l!==a&&this.setFocus(l)}resizeFocusedPane(e){const s=this.getState().ui.focusRegion,n=this.getState().ui.layout||{},i=this.getCurrentLayout().bodyHeight??n.viewportHeight??40,o=n.viewportHeight??40,r=(a,l,c,d)=>{const f=Math.max(c,d);return Math.max(c,Math.min(f,(a||0)+l))};if(s===E.SESSIONS||s===E.CHAT){const a=$o(i),l=gt+1,c=Math.min(Bo(o,i),i-as-1),d=s===E.CHAT?-e:e,f=r(n.sessionPaneAdjust,d,l-a,c-a);this.dispatch({type:"ui/sessionPaneAdjust",sessionPaneAdjust:f})}else if(s===E.INSPECTOR||s===E.ACTIVITY){const a=Math.max(ft,Math.floor(i*Fo)),l=ft+1,c=i-Qt-1,d=s===E.INSPECTOR?-e:e,f=r(n.activityPaneAdjust,d,l-a,c-a);this.dispatch({type:"ui/activityPaneAdjust",activityPaneAdjust:f})}}getActiveSequenceCompletedTurns(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s)return[];const n=e.history.bySessionId?.get?.(s),i=[],o=new Set;for(const r of n?.events||[]){if(r?.eventType!=="session.turn_completed")continue;const a=Number(r?.data?.turnIndex??r?.data?.iteration);!Number.isFinite(a)||o.has(a)||(o.add(a),i.push(a))}return i.sort((r,a)=>r-a),i}moveSequenceSelection(e){const s=this.getActiveSequenceCompletedTurns();if(s.length===0)return;const n=s.indexOf(Number(this.getState().ui.sequenceSelectedTurn)),i=n===-1?s.length-1:Math.max(0,Math.min(s.length-1,n+e));this.dispatch({type:"ui/sequenceSelectedTurn",turn:s[i]})}toggleSequenceTurnExpanded(){const e=this.getActiveSequenceCompletedTurns();if(e.length===0)return;let s=Number(this.getState().ui.sequenceSelectedTurn);e.includes(s)||(s=e[e.length-1],this.dispatch({type:"ui/sequenceSelectedTurn",turn:s}));const n=Array.isArray(this.getState().ui.sequenceExpandedTurns)?this.getState().ui.sequenceExpandedTurns.map(Number):[],i=n.includes(s)?n.filter(o=>o!==s):[...n,s];this.dispatch({type:"ui/sequenceExpandedTurns",turns:i})}nextInspectorTab(){const e=this.getState().ui.inspectorTab,s=tt(ve,e,1);this.dispatch({type:"ui/inspectorTab",inspectorTab:s}),this.ensureInspectorData(s).catch(()=>{})}prevInspectorTab(){const e=tt(ve,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){ve.includes(e)&&(this.dispatch({type:"ui/inspectorTab",inspectorTab:e}),await this.ensureInspectorData(e).catch(()=>{}))}async moveSession(e){const s=this.getState(),n=yt(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===E.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 $d.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,s={}){const i=this.getState().sessions.activeSessionId;if(i){if(!s.force&&(!this.chatTopHistoryLoadArmed||this.chatTopHistoryLoadSessionId!==i)){this.armChatTopHistoryLoad();return}await this.maybeAutoExpandActiveHistory(e,{pages:od,force:!!s.force})}}getScrollablePaneForFocus(){const e=this.getState().ui.focusRegion;return e===E.CHAT?"chat":e===E.ACTIVITY?"activity":e===E.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=vn(e,n),r=[...En(e,n),...xn(e)],a=Math.min(Math.max(0,Math.floor(i*.34)),ot(r,n)),l=ot(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=Tn(r);return{contentWidth:n,contentHeight:i,totalLines:ot(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=Ye(r,{width:n}),l=a.tabs.map(p=>({text:p===a.activeTab?`[${p}] `:`${p} `,color:p===a.activeTab?"magenta":"gray",bold:p===a.activeTab})),c=(a.lines||[]).map(p=>typeof p=="string"?{text:p,color:"white"}:p),d=a.activeTab==="sequence"?[l,...(a.stickyLines||[]).map(p=>typeof p=="string"?{text:p,color:"white"}:p)]:[],f=a.activeTab==="sequence"?c:[l,...c];return{contentWidth:n,contentHeight:Math.max(1,s.inspectorPaneHeight-2),stickyLineCount:ot(d,n),totalLines:ot(f,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,c=l&&e.sessions.byId[l]||null,d={sessions:{activeSessionId:l,byId:l&&c?{[l]:c}:{},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}}},f=Cn(d,{listWidth:a,previewWidth:a}),p=Math.max(9,o-4),h=Math.max(5,Math.min(10,Math.floor(p*.35)));let m=Math.max(5,Math.min(h,(f.listBodyLines||[]).length+2)),g=Math.max(5,p-m-1);const b=8;if(g<b){const S=b-g;m=Math.max(5,m-S),g=Math.max(5,p-m-1)}return{contentWidth:a,contentHeight:Math.max(1,g-2),totalLines:ot(f.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)>=Xi){this.dispatch({type:"ui/status",text:"Reached automatic history limit. Press e to load more older CMS events."});return}const r=Array.isArray(o?.chat)&&o.chat.length>0;if(!s.force&&r){const{contentHeight:a,totalLines:l}=this.getActiveChatRenderMetrics(n),c=Math.max(0,l-a);if(e<c)return}await this.expandSessionHistory(i,{requestedScrollOffset:e,autoTriggered:!0,pages:s.pages,eventTypes:wa})}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(X,Number(i?.loadedEventLimit??X)||X),r=X,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,c=Number(s.requestedScrollOffset??n.ui.scroll?.chat??0),d=l?this.getActiveChatRenderMetrics(n).totalLines:0,f=(async()=>{let p;const h=Math.max(1,Math.floor(Number(s.pages)||1)),m=Array.isArray(s.eventTypes)&&s.eventTypes.length>0?s.eventTypes:void 0;if(typeof this.transport.getSessionEventsBefore=="function"&&a>0){p=i||Bt([],{requestedLimit:o});for(let S=0;S<h;S+=1){const w=Array.isArray(p?.events)&&p.events.length>0?Number(p.events[0]?.seq||0):0;if(!p?.hasOlderEvents||w<=1){p={...p,hasOlderEvents:!1};break}if(Number(p.loadedEventCount||0)>=Xi)break;const I=await this.transport.getSessionEventsBefore(e,w,r,m);if(!Array.isArray(I)||I.length===0){p={...p,hasOlderEvents:!1};break}const A=Bt(I,{requestedLimit:r}),C=[...A.events||[],...p?.events||[]];if(p={chat:ut([...A.chat||[],...p?.chat||[]]),activity:[...A.activity||[],...p?.activity||[]],events:C,lastSeq:p?.lastSeq||p?.events?.[p?.events?.length-1]?.seq||I[I.length-1]?.seq||0,loadedEventLimit:C.length,loadedEventCount:C.length,hasOlderEvents:I.length>=r&&Number(I[0]?.seq||0)>1},!p.hasOlderEvents)break}}else{const S=Da(o);if(S<=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 w=await this.transport.getSessionEvents(e,void 0,S);p={...Bt(w,{requestedLimit:S}),lastSeq:w[w.length-1]?.seq||0}}this.dispatch({type:"history/set",sessionId:e,history:p});for(const S of p?.events||[])this.reconcileOutboxAgainstEvent(e,S);const g=Array.isArray(i?.chat)&&i.chat.length>0;if(l&&!g)this.dispatch({type:"ui/scroll",pane:"chat",offset:0});else if(l&&c>0){const S=this.getState(),w=this.getActiveChatRenderMetrics(S).totalLines,I=Math.max(0,w-d);I>0&&this.dispatch({type:"ui/scroll",pane:"chat",offset:c+I})}const b=p.hasOlderEvents?s.autoTriggered?`Loaded older history page from CMS (${p.loadedEventCount} events loaded)`:`Loaded older history page (${p.loadedEventCount} events loaded)`:`Loaded full available history (${p.loadedEventCount} events)`;this.dispatch({type:"ui/status",text:b}),p.hasOlderEvents?s.autoTriggered&&l&&this.armChatTopHistoryLoad():this.disarmChatTopHistoryLoad()})().finally(()=>{this.sessionHistoryExpansionLoads.delete(e)});return this.sessionHistoryExpansionLoads.set(e,f),f}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 c=[];for(const f of r)try{await this.transport.cancelSession(f.sessionId),l+=1}catch(p){c.push(`${f.sessionId.slice(0,8)}: ${p?.message||String(p)}`)}this.dispatch({type:"sessions/selectClear"});const d=c.length===0?`Cancelled ${l} session${l===1?"":"s"}`:`Cancelled ${l}/${r.length}; ${c.length} failed: ${c.slice(0,2).join(", ")}${c.length>2?"…":""}`;this.dispatch({type:"ui/status",text:d}),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 c=0;const d=[];for(const p of a)try{await this.transport.completeSession(p.sessionId,e),c+=1}catch(h){d.push(`${p.sessionId.slice(0,8)}: ${h?.message||String(h)}`)}this.dispatch({type:"sessions/selectClear"});const f=d.length===0?`Completed ${c} session${c===1?"":"s"}`:`Completed ${c}/${a.length}; ${d.length} failed: ${d.slice(0,2).join(", ")}${d.length>2?"…":""}`;this.dispatch({type:"ui/status",text:f}),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 c=[];for(const f of r)try{await this.transport.deleteSession(f.sessionId),l+=1}catch(p){c.push(`${f.sessionId.slice(0,8)}: ${p?.message||String(p)}`)}this.dispatch({type:"sessions/selectClear"});const d=c.length===0?`Deleted ${l} session${l===1?"":"s"}`:`Deleted ${l}/${r.length}; ${c.length} failed: ${c.slice(0,2).join(", ")}${c.length>2?"…":""}`;this.dispatch({type:"ui/status",text:d}),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||Rs(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 x.REFRESH:await this.refreshSessions();return;case x.NEW_SESSION:await this.openNewSessionFlow();return;case x.OPEN_MODEL_PICKER:await this.openModelPicker();return;case x.OPEN_SWITCH_MODEL_PICKER:await this.openSwitchModelPicker();return;case x.OPEN_THEME_PICKER:this.openThemePicker();return;case x.OPEN_RENAME_SESSION:this.openRenameSessionModal();return;case x.CYCLE_SESSION_VISIBILITY:await this.cycleSessionVisibility();return;case x.OPEN_SHARE_SESSION:await this.openShareSessionModal();return;case x.OPEN_SESSION_FILTER:this.openSessionOwnerFilter();return;case x.OPEN_TERMINATE_PICKER:await this.openTerminatePickerModal();return;case x.OPEN_MOVE_TO_GROUP:await this.openMoveToGroupModal();return;case x.CREATE_SESSION_GROUP:await this.openMoveToGroupModal();return;case x.OPEN_ARTIFACT_UPLOAD:this.openArtifactUploadModal();return;case x.TOGGLE_CHAT_VIEW:this.toggleChatViewMode();return;case x.CLOSE_MODAL:this.closeModal();return;case x.MODAL_PREV:this.moveModalSelection(-1);return;case x.MODAL_NEXT:this.moveModalSelection(1);return;case x.MODAL_PANE_PREV:this.moveModalPane(-1);return;case x.MODAL_PANE_NEXT:this.moveModalPane(1);return;case x.MODAL_CONFIRM:await this.confirmModal();return;case x.SEND_PROMPT:await this.sendPrompt();return;case x.FOCUS_NEXT:this.focusNext();return;case x.FOCUS_PREV:this.focusPrev();return;case x.FOCUS_LEFT:this.focusLeft();return;case x.FOCUS_RIGHT:this.focusRight();return;case x.FOCUS_PROMPT:this.setFocus(E.PROMPT);return;case x.FOCUS_SESSIONS:this.setFocus(E.SESSIONS);return;case x.MOVE_SESSION_UP:await this.moveSession(-1);return;case x.MOVE_SESSION_DOWN:await this.moveSession(1);return;case x.EXPAND_SESSION:this.expandActiveSession();return;case x.COLLAPSE_SESSION:this.collapseActiveSession();return;case x.NEXT_INSPECTOR_TAB:this.nextInspectorTab();return;case x.PREV_INSPECTOR_TAB:this.prevInspectorTab();return;case x.CYCLE_INSPECTOR_TAB:this.cycleInspectorTab();return;case x.GROW_LEFT_PANE:this.adjustPaneSplit(8);return;case x.GROW_RIGHT_PANE:this.adjustPaneSplit(-8);return;case x.GROW_SESSION_PANE:this.adjustSessionPaneSplit(2);return;case x.SHRINK_SESSION_PANE:this.adjustSessionPaneSplit(-2);return;case x.GROW_FOCUSED_PANE:this.resizeFocusedPane(2);return;case x.SHRINK_FOCUSED_PANE:this.resizeFocusedPane(-2);return;case x.OPEN_ARTIFACT_PICKER:await this.openArtifactPicker();return;case x.OPEN_HELP:this.openHelpModal();return;case x.SEQUENCE_SELECT_PREV:this.moveSequenceSelection(-1);return;case x.SEQUENCE_SELECT_NEXT:this.moveSequenceSelection(1);return;case x.TOGGLE_SEQUENCE_TURN:this.toggleSequenceTurnExpanded();return;case x.TOGGLE_LOG_TAIL:this.toggleLogTail();return;case x.TOGGLE_STATS_VIEW:this.toggleStatsView();return;case x.OPEN_LOG_FILTER:this.openLogFilter();return;case x.OPEN_FILES_FILTER:this.openFilesFilter();return;case x.MOVE_FILE_UP:await this.moveFileSelection(-1);return;case x.MOVE_FILE_DOWN:await this.moveFileSelection(1);return;case x.DOWNLOAD_SELECTED_FILE:await this.downloadSelectedArtifact();return;case x.DELETE_SELECTED_FILE:await this.deleteSelectedArtifact();return;case x.OPEN_SELECTED_FILE:await this.openSelectedFileInDefaultApp();return;case x.TOGGLE_FILE_PREVIEW_FULLSCREEN:this.toggleFilePreviewFullscreen();return;case x.TOGGLE_PANE_FULLSCREEN:this.toggleFocusedPaneFullscreen();return;case x.SCROLL_UP:this.scrollCurrentPane(1);return;case x.SCROLL_DOWN:this.scrollCurrentPane(-1);return;case x.PAGE_UP:if(this.getState().ui.focusRegion===E.SESSIONS){await this.moveSessionPage(-1);return}this.scrollCurrentPane(10);return;case x.PAGE_DOWN:if(this.getState().ui.focusRegion===E.SESSIONS){await this.moveSessionPage(1);return}this.scrollCurrentPane(-10);return;case x.EXPAND_HISTORY:await this.expandActiveHistory();return;case x.SCROLL_TOP:this.scrollCurrentPaneToTop();return;case x.SCROLL_BOTTOM:this.scrollCurrentPaneToBottom();return;case x.CANCEL_SESSION:await this.cancelActiveSession();return;case x.STOP_TURN:await this.stopActiveSessionTurn();return;case x.DONE_SESSION:await this.completeActiveSession();return;case x.DELETE_SESSION:await this.deleteActiveSession();return;case x.PIN_SESSION:this.togglePinActiveSession();return;case x.TOGGLE_SELECT_MODE:this.toggleSessionSelectMode();return;case x.TOGGLE_SESSION_SELECTION:this.toggleActiveSessionSelection();return;case x.CLEAR_SESSION_SELECTION:this.clearSessionSelection();return;case x.OPEN_HISTORY_FORMAT:this.openHistoryFormat();return;case x.REFRESH_EXECUTION_HISTORY:{const s=this.getState().sessions.activeSessionId;s&&await this.ensureExecutionHistory(s,{force:!0});return}case x.EXPORT_EXECUTION_HISTORY:{await this.exportExecutionHistory();return}case x.OPEN_ADMIN_CONSOLE:await this.openAdminConsole();return;case x.CLOSE_ADMIN_CONSOLE:this.closeAdminConsole();return;case x.ADMIN_REFRESH_PROFILE:await this.refreshAdminProfile();return;case x.ADMIN_BEGIN_EDIT_GHCP_KEY:this.beginAdminEditGhcpKey();return;case x.ADMIN_CANCEL_EDIT_GHCP_KEY:this.cancelAdminEditGhcpKey();return;case x.ADMIN_SAVE_GHCP_KEY:await this.saveAdminGhcpKey();return;case x.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 fs=0;function ye(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 $s(){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 Kd(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 qd(t){const e=t?.principal;if(!e)return null;const s=e.displayName||e.email||e.subject||null;return s?t?.authorization?.role==="admin"||Array.isArray(e.roles)&&e.roles.includes("admin")?`(*) ${s}`:s:null}function zd(t,e=null,s=null){const n=[],i=typeof s=="string"?s.trim():"";i&&n.push({text:i,color:"yellow",bold:!0}),Array.isArray(t)&&t.length>0&&(n.length>0&&n.push({text:" ",color:"gray"}),n.push(...t));const o=typeof e=="string"?e.trim():"";return o?(n.length>0&&n.push({text:" ",color:"gray"}),n.push({text:o,color:"cyan",bold:!0}),n):n.length>0?n:null}function Yd(t=2e3){const[e,s]=u.useState(()=>$s());return u.useEffect(()=>{if($s()==null)return;const n=()=>{const o=$s();o!=null&&s(r=>r===o?r:o)};n();const i=setInterval(n,t);return()=>clearInterval(i)},[t]),u.useMemo(()=>Kd(e),[e])}function wt(t,e){return t&&e?{[t]:e}:{}}function eo(t){return typeof t=="string"?{text:t,color:"white"}:t}function Ft(t,e,s,n,i,o){const r=(e.tabs||ve).map(f=>({text:f===e.activeTab?`[${f}] `:`${f} `,color:f===e.activeTab?"magenta":"gray",bold:f===e.activeTab})),a=(e.lines||[]).map(eo),l=(e.stickyLines||[]).map(eo),c=e.activeTab==="sequence"?[r,...l]:[],d=e.activeTab==="sequence"?a:[r,...a];return u.createElement(t.Panel,{title:e.title,color:"magenta",focused:s.focused,width:n,height:i,stickyLines:c,marginBottom:fs,lines:d,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 to(t,e){const s=String(t||"");return e<=0?"":s.length<=e?s:e===1?s.slice(0,1):`${s.slice(0,e-1)}...`}u.memo(function({controller:e,maxRows:s,width:n,height:i,frame:o,versionLabel:r=null}){const a=xe(),l=Yd(),c=K(e,m=>({sessions:m.sessions,mode:m.connection?.mode||"local",brandingTitle:m.branding?.title||"PilotSwarm",focused:m.ui.focusRegion==="sessions",identityLabel:qd(m.auth)}),ye),d=u.useMemo(()=>zd(l,r,c.identityLabel),[l,r,c.identityLabel]),f=u.useMemo(()=>({sessions:c.sessions,connection:{mode:c.mode},branding:{title:c.brandingTitle}}),[c.brandingTitle,c.mode,c.sessions]),p=u.useMemo(()=>Ks(f,s),[f,s]),h=u.useMemo(()=>p.length===0?[{text:"No sessions yet. Press n to create one.",color:"gray"}]:p.map(m=>m.active?Wo(m.runs,{preserveColors:!0}):m.runs),[p]);return u.createElement(a.Panel,{title:[{text:"Sessions",color:"yellow",bold:!0}],titleRight:d,color:"yellow",focused:c.focused,width:n,height:i,marginBottom:fs,lines:h,paneId:"sessions",paneLabel:"Sessions",frame:o})});u.memo(function({controller:e,width:s,height:n,frame:i}){const o=xe(),r=K(e,I=>{const A=I.sessions.activeSessionId;return{activeSessionId:A,activeSession:A&&I.sessions.byId[A]||null,activeHistory:A&&I.history.bySessionId.get(A)||null,activeOutbox:A&&I.outbox?.bySessionId?.[A]||null,authPrincipal:I.auth?.principal||null,branding:I.branding,connectionError:I.connection.error,connectionMode:I.connection.mode,chatViewMode:I.ui.chatViewMode||"transcript",chatScroll:I.ui.scroll.chat,focused:I.ui.focusRegion==="chat"}},ye),a=Math.max(20,s-4),l=u.useMemo(()=>{const I=new Map;return r.activeSessionId&&r.activeHistory&&I.set(r.activeSessionId,r.activeHistory),{branding:r.branding,auth:{principal:r.authPrincipal},connection:{error:r.connectionError,mode:r.connectionMode},ui:{chatViewMode:r.chatViewMode},sessions:{activeSessionId:r.activeSessionId,byId:wt(r.activeSessionId,r.activeSession)},history:{bySessionId:I},outbox:{bySessionId:r.activeSessionId&&r.activeOutbox?{[r.activeSessionId]:r.activeOutbox}:{}}}},[r.activeHistory,r.activeSessionId,r.activeSession,r.activeOutbox,r.authPrincipal,r.branding,r.chatViewMode,r.connectionError,r.connectionMode]),c=u.useMemo(()=>ar(l,{width:a}),[a,l]),d=So(!!c?.animateTitleRight),f=u.useMemo(()=>bo(c?.titleRight,d),[d,c?.titleRight]),p=!r.activeSessionId&&r.connectionError,h=u.useMemo(()=>p?[{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"}]:vn(l,a),[r.branding.splash,r.connectionError,a,l,p]),m=String(r.activeSession?.status||"").toLowerCase()==="running",g=yo(m),b=u.useMemo(()=>p?[]:xn(l,{spinnerFrame:g,maxWidth:a}),[l,p,g,a]),S=u.useMemo(()=>p?[]:En(l,a),[l,p,a]),w=u.useMemo(()=>S.length>0||b.length>0?[...S,...b]:[],[S,b]);return u.createElement(o.Panel,{title:c.title,titleRight:f,color:c.color,focused:r.focused,width:s,height:n,lines:h,bottomStickyLines:w,scrollOffset:r.chatScroll,scrollMode:"bottom",paneId:"chat",paneLabel:"Chat",frame:i})});const Qd=u.memo(function({controller:e,width:s,height:n,shellTitle:i,focused:o=!1,frame:r,showFullscreenTitle:a=!1,embedded:l=!1}){const c=xe(),d=K(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}),ye),f=Math.max(20,s-4),p=u.useMemo(()=>({sessions:{activeSessionId:d.activeSessionId,byId:d.activeSessionId&&d.activeSession?{[d.activeSessionId]:d.activeSession}:{},flat:d.sessionsFlat},files:{bySessionId:d.filesBySessionId,fullscreen:d.filesFullscreen,selectedArtifactId:d.selectedArtifactId,filter:d.filesFilter},ui:{scroll:{filePreview:d.filePreviewScroll}}}),[d]),h=u.useMemo(()=>Cn(p,{listWidth:Math.max(8,f-4),previewWidth:Math.max(8,f-4)}),[f,p]),m=i||(a?h.fullscreenTitle:h.panelTitle||h.listTitle)||[{text:"Files",color:"magenta",bold:!0}],g=Math.max(9,n-4),b=Math.max(5,Math.min(10,Math.floor(g*.35)));let S=Math.max(5,Math.min(b,(h.listBodyLines||[]).length+2)),w=Math.max(5,g-S-1);const I=8;if(w<I){const L=I-w;S=Math.max(5,S-L),w=Math.max(5,g-S-1)}const A=Math.max(1,S-2),C=Math.max(0,h.selectedIndex-Math.floor(A/2)),v=!l&&r?{x:r.x+2,y:r.y+2,width:f,height:S}:null,T=!l&&r?{x:r.x+2,y:r.y+2+S+1,width:f,height:w}:null,M=ve.map(L=>({text:L==="files"?`[${L}] `:`${L} `,color:L==="files"?"magenta":"gray",bold:L==="files"})),O=u.createElement(c.Column,{width:f},u.createElement(c.Lines,{lines:[M]}),u.createElement(c.Panel,{title:h.listTitle,color:"gray",focused:!1,width:f,height:S,lines:h.listBodyLines||h.listLines.slice(1),scrollOffset:C,scrollMode:"top",marginBottom:1,paneId:"files:list",paneLabel:"Files list",frame:v}),u.createElement(c.Panel,{title:h.previewTitle,color:"gray",focused:!1,width:f,height:w,lines:h.previewLines,scrollOffset:h.previewScrollOffset,scrollMode:"top",paneId:"files:preview",paneLabel:"File preview",frame:T}));return l?O:u.createElement(c.Panel,{title:m,color:"magenta",focused:o,width:s,height:n,marginBottom:fs,paneId:"inspector",paneLabel:"Inspector",frame:r},O)}),Xd=u.memo(function({controller:e,width:s,height:n,frame:i,meta:o}){const r=xe(),a=Math.max(20,s-4),l=K(e,f=>({activeSessionId:f.sessions.activeSessionId,activeSession:f.sessions.activeSessionId&&f.sessions.byId[f.sessions.activeSessionId]||null}),ye),c=u.useMemo(()=>({sessions:{activeSessionId:l.activeSessionId,byId:wt(l.activeSessionId,l.activeSession)},ui:{inspectorTab:"files"}}),[l.activeSession,l.activeSessionId]),d=u.useMemo(()=>Ye(c,{width:a}),[a,c]);return u.createElement(r.Panel,{title:d.title,color:"magenta",focused:o.focused,width:s,height:n,marginBottom:fs,paneId:"inspector",paneLabel:"Inspector",frame:i},u.createElement(Qd,{controller:e,width:s,height:n,frame:i,focused:o.focused,embedded:!0}))}),Jd=u.memo(function({controller:e,width:s,height:n,frame:i,meta:o}){const r=xe(),a=Math.max(20,s-4),l=K(e,f=>({activeSessionId:f.sessions.activeSessionId,activeSession:f.sessions.activeSessionId&&f.sessions.byId[f.sessions.activeSessionId]||null,activeOrchestration:f.sessions.activeSessionId&&f.orchestration.bySessionId?.[f.sessions.activeSessionId]||null,histories:f.history.bySessionId,expandedTurns:f.ui.sequenceExpandedTurns,selectedTurn:f.ui.sequenceSelectedTurn}),ye),c=u.useMemo(()=>({sessions:{activeSessionId:l.activeSessionId,byId:wt(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]),d=u.useMemo(()=>Ye(c,{width:a,sequenceExpansion:{expandedTurns:l.expandedTurns||[],selectedTurn:l.selectedTurn??null}}),[a,c,l.expandedTurns,l.selectedTurn]);return Ft(r,d,o,s,n,i)}),Zd=u.memo(function({controller:e,width:s,height:n,frame:i,meta:o}){const r=xe(),a=Math.max(20,s-4),l=K(e,f=>({activeSessionId:f.sessions.activeSessionId,activeSession:f.sessions.activeSessionId&&f.sessions.byId[f.sessions.activeSessionId]||null,logs:f.logs}),ye),c=u.useMemo(()=>({sessions:{activeSessionId:l.activeSessionId,byId:wt(l.activeSessionId,l.activeSession)},logs:l.logs,ui:{inspectorTab:"logs"}}),[l.activeSession,l.activeSessionId,l.logs]),d=u.useMemo(()=>Ye(c,{width:a}),[a,c]);return Ft(r,d,o,s,n,i)}),ef=u.memo(function({controller:e,width:s,height:n,frame:i,meta:o}){const r=xe(),a=Math.max(20,s-4),l=K(e,f=>({activeSessionId:f.sessions.activeSessionId,activeSession:f.sessions.activeSessionId&&f.sessions.byId[f.sessions.activeSessionId]||null,executionHistory:f.executionHistory}),ye),c=u.useMemo(()=>({sessions:{activeSessionId:l.activeSessionId,byId:wt(l.activeSessionId,l.activeSession)},executionHistory:l.executionHistory,ui:{inspectorTab:"history"}}),[l.activeSession,l.activeSessionId,l.executionHistory]),d=u.useMemo(()=>Ye(c,{width:a}),[a,c]);return Ft(r,d,o,s,n,i)}),tf=u.memo(function({controller:e,width:s,height:n,frame:i,meta:o}){const r=xe(),a=Math.max(20,s-4),l=K(e,f=>({activeSessionId:f.sessions.activeSessionId,sessionsById:f.sessions.byId,sessionsFlat:f.sessions.flat,histories:f.history.bySessionId}),ye),c=u.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]),d=u.useMemo(()=>Ye(c,{width:a}),[a,c]);return Ft(r,d,o,s,n,i)}),sf=u.memo(function({controller:e,width:s,height:n,frame:i,meta:o}){const r=xe(),a=Math.max(20,s-4),l=K(e,f=>({activeSessionId:f.sessions.activeSessionId,activeSession:f.sessions.activeSessionId&&f.sessions.byId[f.sessions.activeSessionId]||null,sessionStats:f.sessionStats,fleetStats:f.fleetStats,statsViewMode:f.ui.statsViewMode}),ye),c=u.useMemo(()=>({sessions:{activeSessionId:l.activeSessionId,byId:wt(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]),d=u.useMemo(()=>Ye(c,{width:a}),[a,c]);return Ft(r,d,o,s,n,i)});u.memo(function({controller:e,width:s,height:n,frame:i}){const o=K(e,r=>({inspectorTab:r.ui.inspectorTab,inspectorScroll:r.ui.scroll.inspector,inspectorFollowBottom:r.ui.followBottom?.inspector!==!1,focused:r.ui.focusRegion==="inspector"}),ye);return o.inspectorTab==="files"?u.createElement(Xd,{controller:e,width:s,height:n,frame:i,meta:o}):o.inspectorTab==="sequence"?u.createElement(Jd,{controller:e,width:s,height:n,frame:i,meta:o}):o.inspectorTab==="logs"?u.createElement(Zd,{controller:e,width:s,height:n,frame:i,meta:o}):o.inspectorTab==="history"?u.createElement(ef,{controller:e,width:s,height:n,frame:i,meta:o}):o.inspectorTab==="stats"?u.createElement(sf,{controller:e,width:s,height:n,frame:i,meta:o}):u.createElement(tf,{controller:e,width:s,height:n,frame:i,meta:o})});u.memo(function({controller:e,width:s,height:n,maxLines:i,frame:o}){const r=xe(),a=K(e,d=>{const f=d.sessions.activeSessionId;return{sessionsById:d.sessions.byId,activeSessionId:f,activeSession:f&&d.sessions.byId[f]||null,activeHistory:f&&d.history.bySessionId.get(f)||null,scroll:d.ui.scroll.activity,followBottom:d.ui.followBottom?.activity!==!1,focused:d.ui.focusRegion==="activity"}},ye),l=u.useMemo(()=>{const d=new Map;return a.activeSessionId&&a.activeHistory&&d.set(a.activeSessionId,a.activeHistory),{sessions:{activeSessionId:a.activeSessionId,byId:a.sessionsById},history:{bySessionId:d}}},[a.activeHistory,a.activeSessionId,a.sessionsById]),c=u.useMemo(()=>Tn(l,i),[i,l]);return u.createElement(r.Panel,{title:c.title,color:"gray",focused:a.focused,width:s,height:n,lines:c.lines,scrollOffset:a.scroll,scrollMode:a.followBottom?"bottom":"top",paneId:"activity",paneLabel:"Activity",frame:o})});u.memo(function({controller:e,rows:s}){const n=xe(),i=K(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(c=>c?.phase==="pending")}},ye);return u.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})});u.memo(function({controller:e}){const s=xe(),n=K(e,d=>({connected:d.connection.connected,workersOnline:d.connection.workersOnline,focusRegion:d.ui.focusRegion,inspectorTab:d.ui.inspectorTab,chatViewMode:d.ui.chatViewMode||"transcript",fullscreenPane:d.ui.fullscreenPane||null,logsAvailable:d.logs.available,logsTailing:d.logs.tailing,filesFullscreen:!!d.files.fullscreen,mode:d.connection.mode,statusText:d.ui.statusText,modal:d.ui.modal,activeSessionId:d.sessions.activeSessionId,activeSession:d.sessions.activeSessionId&&d.sessions.byId[d.sessions.activeSessionId]||null,selectedIds:d.sessions.selectedIds,selectMode:d.sessions.selectMode}),ye),i=u.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=u.useMemo(()=>Nc(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),c=Math.max(8,a-l-3);return u.createElement(s.StatusLine,{left:to(o.left,c),right:to(o.right,l)})});var nf=Qr();const of=920,kr=7,Mr=19,_n=.24,Pr=16,Nr=8,rf=224,af=190,lf=48,De=16,Or=.5,vt=Or,cf=24,uf=700,df=5e3,ff=new Set(["low","medium","high","xhigh"]),pf=["pilotswarm.theme","pilotswarm.sessionOwnerFilter","pilotswarm.chatFocus","pilotswarm.layoutAdjustments","pilotswarm.pinnedSessions"],hf=["pilotswarm_theme","pilotswarm_session_owner_filter"],mf={sequence:"Sequence",logs:"Logs",nodes:"Node Map",history:"History",files:"Files",stats:"Stats"},gf={sequence:"⇶",logs:"≣",nodes:"⬡",history:"⟲",files:"⧉",stats:"▁▄▇"};function yf(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 Sf(t){return typeof t?.transport?.uploadArtifactFromFile=="function"}function bf(t){return typeof t?.transport?.uploadArtifactFromPath=="function"}function wf(t){return typeof t?.transport?.listArtifacts=="function"}function If(t){return typeof t?.transport?.deleteArtifact=="function"}function xf(t){return typeof t?.transport?.openPathInDefaultApp=="function"}const vf="Session link copied to clipboard",Ef="Only people with access can open this link.";function Af(t){return!t||typeof window>"u"||!window.location?null:`${window.location.origin}${window.location.pathname}?session=${encodeURIComponent(t)}`}function so(t){navigator?.clipboard?.writeText&&navigator.clipboard.writeText(t).catch(()=>{})}async function Tf(t,e){try{const s=t.transport;if(typeof s?.getSessionAccess=="function"&&((await s.getSessionAccess(e))?.visibility||"private")==="private"){const i=typeof s.listSessionShares=="function"?await s.listSessionShares(e).catch(()=>[]):[];return!Array.isArray(i)||i.length===0}}catch{}return!1}function Cf(){if(!(typeof window>"u")){try{for(const t of pf)window.localStorage.removeItem(t)}catch{}try{for(const t of hf)document.cookie=`${t}=; Path=/; Max-Age=0; SameSite=Lax`}catch{}}}function ht(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()),he(e,"sessionOwnerFilter")&&e.sessionOwnerFilter&&typeof e.sessionOwnerFilter=="object"){const n=e.sessionOwnerFilter;s.sessionOwnerFilter=he(n,"includeShared")?n:{...n,includeShared:!0}}if(he(e,"layoutAdjustments")&&(s.layoutAdjustments=fn(e.layoutAdjustments)),he(e,"pinnedSessionIds")&&(s.pinnedSessionIds=Zt(e.pinnedSessionIds)),he(e,"collapsedSessionIds")&&(s.collapsedSessionIds=kf(e.collapsedSessionIds)),he(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 kf(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 he(t,e){return!!(t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,e))}function Bs(t){return ht({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 no(t){return ht({themeId:t?.ui?.themeId,sessionOwnerFilter:rs(t?.auth?.principal??null),layoutAdjustments:t?.ui?.layout,pinnedSessionIds:t?.sessions?.pinnedIds,collapsedSessionIds:t?.sessions?.collapsedIds,activeSessionId:t?.sessions?.activeSessionId,chatViewMode:t?.ui?.chatViewMode})}function Mf(t,e){const s=ht(t),n=ht(e);return ht({themeId:he(s,"themeId")?s.themeId:n.themeId,sessionOwnerFilter:he(s,"sessionOwnerFilter")?s.sessionOwnerFilter:n.sessionOwnerFilter,layoutAdjustments:he(s,"layoutAdjustments")?s.layoutAdjustments:n.layoutAdjustments,pinnedSessionIds:he(s,"pinnedSessionIds")?s.pinnedSessionIds:n.pinnedSessionIds,...he(s,"collapsedSessionIds")?{collapsedSessionIds:s.collapsedSessionIds}:{},...he(s,"activeSessionId")?{activeSessionId:s.activeSessionId}:{},...he(s,"chatViewMode")?{chatViewMode:s.chatViewMode}:{}})}async function Pf(t,e){return typeof t?.transport?.setCurrentUserProfileSettings!="function"?null:t.transport.setCurrentUserProfileSettings({settings:ht(e)})}function Rn(t){return wf(t)?ve:ve.filter(e=>e!=="files")}function Te(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 Zs(t,e,s){return Math.max(e,Math.min(s,t))}function en(t){const e=Math.max(0,Number(t)||0),s=Math.max(0,e-Pr-Nr*2),n=s*_n,i=Math.max(0,s-rf);return{minAdjust:-n,maxAdjust:i-n}}function Nf(t,e){const s=en(t),n=Math.max(0,Number(t)||0),o=Math.max(0,n-Pr-Nr*2)*_n;return Zs(o+(Number(e)||0),0,o+s.maxAdjust)}function Of(t){return t<=lf?"hidden":t<=af?"compact":"wrap"}function _r(t){const e=Number(t?.ui?.promptRows);return Number.isFinite(e)&&e>0?e:pt(t?.ui?.prompt||"")}function ps(t){return Mt({width:t.ui.layout?.viewportWidth??120,height:t.ui.layout?.viewportHeight??40},t.ui.layout?.paneAdjust??0,_r(t),t.ui.layout?.sessionPaneAdjust??0)}function _f(t,e){const s=e==="sequence"?3:0;return Math.max(20,t-4-s)}function pe(t){const e=[],s=n=>{const i=String(n||"");return!i.includes("\\n")||i.includes(`
80
- `)?i:i.replace(/\\n/g,`
81
- `)};for(const n of t||[]){if(n?.kind==="markup"){const i=n.splashAlt?[{text:n.value,variant:"desktop"},{text:n.splashAlt,variant:"mobile"}]:[{text:n.value,variant:null}];for(const o of i)for(const r of xo(o.text||""))e.push({kind:"runs",runs:r,preserve:!0,splashVariant:o.variant});continue}if(n?.kind==="markdownTable"||n?.kind==="cardStart"||n?.kind==="cardEnd"||n?.kind==="imageAttachments"){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(`
82
- `)){const a=r.split(`
83
- `);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(`
84
- `)){const o=i.split(`
85
- `);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 qe(t,e){if(e)return t?.tui?.[e]||t?.terminal?.[e]||t?.page?.[e]||e}function Rr(t=[]){return t.map(e=>String(e?.text||"")).join("")}function io(t){return Array.isArray(t)?Rr(t):String(t||"")}function oo(t,e=40){if(!Array.isArray(t)){const o=String(t||"");return[{text:o.length>e?`${o.slice(0,e-1)}…`:o,color:"white",bold:!0}]}const s=[],n=o=>/^[\s·—-]+$/.test(String(o?.text||""));let i=Math.max(8,e);for(const o of t){if(i<=0)break;if(o?.color==="gray"&&s.length>0&&!n(o))continue;const a=String(o?.text||"");if(!a)continue;if(n(o)&&i<a.length+2)break;const l=a.length>i&&i>1?`${a.slice(0,i-1)}…`:a.slice(0,i);l&&(s.push({...o,text:l}),i-=l.length)}for(;s.length>0&&n(s[s.length-1]);)s.pop();return s.length>0?s:t}function Rf(t){const e=ze(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 ro(t){const[e,s]=u.useState({width:0,height:0});return u.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 Lf(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/kr)),height:Math.max(18,Math.floor(s/Mr))}}function Ff(t){if(!t)return 0;const e=Math.max(0,t.scrollHeight-t.clientHeight);return Math.max(0,e-t.scrollTop)}function $f(t){return Ff(t)<=Or}function Bf(t,e,s,n=!1){if(!t)return 0;const i=Math.max(0,t.scrollHeight-t.clientHeight);if(n)return Math.max(0,Math.min(t.scrollTop,i));const o=Math.max(0,Number(e)||0)*De;return s==="bottom"?Math.max(0,i-o):Math.min(i,o)}function Df(t,e,s,n,i,o,{stickyBottom:r=!1}={}){const a=u.useMemo(()=>pe(e),[e]),l=u.useRef(null),c=u.useRef({scrollMode:n,scrollOffset:s}),d=u.useRef({touching:!1,lastUserScrollAt:0,lastDispatchedOffset:null}),f=u.useRef({width:null,height:null}),[p,h]=u.useState(0);u.useLayoutEffect(()=>{const A=t.current;if(!A||typeof ResizeObserver>"u")return;f.current={width:A.clientWidth,height:A.clientHeight};const C=new ResizeObserver(()=>{const v={width:A.clientWidth,height:A.clientHeight},T=f.current;v.width===T.width&&v.height===T.height||(f.current=v,h(M=>M+1))});return C.observe(A),()=>C.disconnect()},[t]),u.useLayoutEffect(()=>{const A=t.current;if(!A)return;const C=c.current,v=d.current,T=typeof performance<"u"?performance.now():Date.now(),M=v.touching||T-(v.lastUserScrollAt||0)<uf,O=v.lastDispatchedOffset!=null&&Math.abs((Number(s)||0)-v.lastDispatchedOffset)<2;if(M&&n===C?.scrollMode&&(s===C?.scrollOffset||O)){c.current={scrollMode:n,scrollOffset:s};return}const L=r&&n==="top"&&C?.scrollMode==="top"&&C?.scrollOffset===s,H=Bf(A,s,n,L);if(Math.abs(A.scrollTop-H)>vt){const F={target:H};l.current=F,A.scrollTop=H,window.requestAnimationFrame(()=>{l.current===F&&(l.current=null)})}c.current={scrollMode:n,scrollOffset:s}},[a,t,n,s,r,p]);const m=u.useCallback(()=>{const A=t.current;if(!A||!i)return;const C=l.current;if(C){if(Math.abs(A.scrollTop-C.target)<=vt)return;l.current=null}d.current.lastUserScrollAt=typeof performance<"u"?performance.now():Date.now();const v=Math.max(0,A.scrollHeight-A.clientHeight);if(v<=0)return;if(r&&typeof o.updatePaneScrollFromViewport=="function"){const M=Math.max(0,A.scrollTop)/De;d.current.lastDispatchedOffset=M,o.updatePaneScrollFromViewport(i,M,{atBottom:$f(A)});return}const T=n==="bottom"?Math.max(0,v-A.scrollTop):Math.max(0,A.scrollTop);d.current.lastDispatchedOffset=T/De,o.dispatch({type:"ui/scroll",pane:i,offset:T/De}),i==="chat"&&n==="bottom"&&A.scrollTop<=vt&&o.armChatTopHistoryLoad?.()},[o,i,t,n,r]),g=u.useCallback(A=>{const C=t.current;if(!C||i!=="chat"||n!=="bottom"||A.deltaY>=0||C.scrollTop>vt)return;const v=Math.max(0,C.scrollHeight-C.clientHeight);o.handleChatTopHistoryScrollIntent?.(v/De)},[o,i,t,n]),b=u.useRef({startY:null,fired:!1}),S=u.useCallback(A=>{d.current.touching=!0,!(i!=="chat"||n!=="bottom")&&(b.current={startY:A.touches?.[0]?.clientY??null,fired:!1})},[i,n]),w=u.useCallback(()=>{d.current.touching=!1,d.current.lastUserScrollAt=typeof performance<"u"?performance.now():Date.now()},[]),I=u.useCallback(A=>{const C=t.current,v=b.current;if(!C||i!=="chat"||n!=="bottom"||v.fired||v.startY==null||C.scrollTop>vt)return;const T=A.touches?.[0]?.clientY;if(T==null||T-v.startY<cf)return;v.fired=!0;const M=Math.max(0,C.scrollHeight-C.clientHeight);o.handleChatTopHistoryScrollIntent?.(M/De+1,{force:!0})},[o,i,t,n]);return{normalizedLines:a,onScroll:m,onWheel:g,onTouchStart:S,onTouchMove:I,onTouchEnd:w}}function me({runs:t,theme:e}){return u.createElement(u.Fragment,null,(t||[]).map((s,n)=>{const i={color:qe(e,s.color),backgroundColor:qe(e,s.backgroundColor),fontWeight:s.bold?700:400,textDecoration:s.underline?"underline":"none"},o=String(s?.href||"").trim();return/^https?:\/\//i.test(o)?u.createElement("a",{key:`${n}:${s.text||""}`,className:"ps-md-link",href:o,target:"_blank",rel:"noreferrer",style:i},s.text||""):u.createElement("span",{key:`${n}:${s.text||""}`,style:i},s.text||"")}))}function Hf({line:t,theme:e}){const s=String(t?.body||"").trim();return u.createElement("details",{className:"ps-system-notice"},u.createElement("summary",{className:"ps-system-notice-summary",style:{color:qe(e,t?.color)||"var(--ps-muted)"}},u.createElement("span",{className:"ps-system-notice-summary-text"},t?.text||"System notice")),s?u.createElement("div",{className:"ps-system-notice-body"},u.createElement($r,{content:s,theme:e})):null)}function fe({line:t,theme:e,className:s=""}){const n=s?`ps-line ${s}`:"ps-line";return t?t.kind==="systemNotice"?u.createElement(Hf,{line:t,theme:e}):t.kind==="runs"?u.createElement("div",{className:n},u.createElement(me,{runs:t.runs,theme:e})):u.createElement("div",{className:n,style:{color:qe(e,t.color),backgroundColor:qe(e,t.backgroundColor),fontWeight:t.bold?700:400,textDecoration:t.underline?"underline":"none"}},t.text||" "):u.createElement("div",{className:n}," ")}function be(t){return t?t.kind==="runs"?Rr(t.runs):String(t.text||""):""}function Gf(t,e,s,n){const i=u.useRef(!1);return u.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)*De);Math.abs(o.scrollTop-a)>2&&(i.current=!0,o.scrollTop=a,window.requestAnimationFrame(()=>{i.current=!1}))},[t,e]),u.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)/De})},[n,s,t])}function Ne(t,e,s="md"){return an(t).map((n,i)=>{const o=`${s}:${i}`;return n.type==="code"?u.createElement("code",{key:o,className:"ps-md-inline-code"},n.text):n.type==="strong"?u.createElement("strong",{key:o,className:"ps-md-strong"},Ne(n.text,e,`${o}:strong`)):n.type==="em"?u.createElement("em",{key:o,className:"ps-md-em"},Ne(n.text,e,`${o}:em`)):n.type==="link"?u.createElement("a",{key:o,className:"ps-md-link",href:n.href,target:"_blank",rel:"noreferrer",style:{color:qe(e,"cyan")}},n.text):u.createElement(u.Fragment,{key:o},n.text)})}function tn(t=""){return String(t||"").replace(/\s+/g," ").trim()}const Uf=["description","mechanism","details","notes","summary","message","comment","reason","body","content","explanation","rationale","one-liner"],jf=24,Wf=32,Vf=6,ao=30,Kf=56,Ds=.4,qf=1.4,zf=2;function Lr(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 b=0;b<e;b+=1){const S=tn(g[b]||"");S.length>i[b].max&&(i[b].max=S.length),m>0&&/\s/.test(S)&&(i[b].spaceCells+=1)}}let o=-1,r=0;for(let m=0;m<e;m+=1){const g=i[m];if(g.max<jf||g.spaceCells/n<.4)continue;const S=tn(s[m]||"").toLowerCase(),w=Uf.some(A=>S.includes(A))?60:0,I=g.max+w;I>r&&(r=I,o=m)}if(o<0)return null;const a=i.map((m,g)=>g===o?0:Math.max(Vf,Math.min(m.max+2,Wf))),l=a.reduce((m,g)=>m+g,0),c=i[o],d=Math.max(ao,Math.min(c.max*.45,Kf,Math.max(ao,l*qf))),f=a.map((m,g)=>g===o?d:m),p=f.reduce((m,g)=>m+g,0);if(p>0&&f[o]/p<Ds){const m=p-f[o];f[o]=m*(Ds/(1-Ds))}const h=f.reduce((m,g)=>m+g,0);return h>0?{widths:f.map(m=>`${(m/h*100).toFixed(2)}%`),flexIndex:o,minWidth:`${Math.ceil(h+zf)}ch`}:null}function Fr(t=[],e=0){return Array.from({length:e},(s,n)=>(Array.isArray(t)?t:[]).map(o=>tn(o?.[n]||"")).filter(Boolean).join(" / ")||null)}function lo(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 co(t=""){return String(t||"").trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(s=>s.trim())}function Yf(t=""){const s=String(t||"").replace(/\r\n?/g,`
86
- `).split(`
87
- `),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 f=a[1]||"",p=[];for(i+=1;i<s.length&&!/^```/.test(s[i].trim());)p.push(s[i]),i+=1;i<s.length&&(i+=1),n.push({type:"code",language:f,content:p.join(`
88
- `)});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 f=co(o);i+=2;const p=[];for(;i<s.length&&s[i].includes("|")&&s[i].trim();)p.push(co(s[i])),i+=1;n.push({type:"table",header:f,rows:p});continue}if(/^\s*>/.test(o)){const f=[];for(;i<s.length&&/^\s*>/.test(s[i]);)f.push(s[i].replace(/^\s*>\s?/,"")),i+=1;n.push({type:"blockquote",text:f.join(`
89
- `).trim()});continue}const c=/^(\s*)([-*]|\d+\.)\s+(.*)$/.exec(o);if(c){const f=/\d+\./.test(c[2]),p=[];for(;i<s.length;){const h=s[i],m=/^(\s*)([-*]|\d+\.)\s+(.*)$/.exec(h);if(!m||/\d+\./.test(m[2])!==f)break;const g=[m[3].trim()];for(i+=1;i<s.length&&s[i].trim()&&!/^(\s*)([-*]|\d+\.)\s+/.test(s[i])&&!lo(s[i],s[i+1]||"");)g.push(s[i].trim()),i+=1;if(p.push(g.join(" ")),!s[i]?.trim())break}n.push({type:"list",ordered:f,items:p});continue}const d=[o.trim()];for(i+=1;i<s.length&&s[i].trim()&&!lo(s[i],s[i+1]||"");)d.push(s[i].trim()),i+=1;n.push({type:"paragraph",text:d.join(" ")})}return n}function $r({content:t,theme:e}){const s=u.useMemo(()=>Yf(t),[t]);return s.length===0?u.createElement("div",{className:"ps-empty-state"},"No preview content."):u.createElement("div",{className:"ps-markdown-preview"},s.map((n,i)=>{if(n.type==="heading")return u.createElement("div",{key:`block:${i}`,className:`ps-md-heading is-h${n.level}`},Ne(n.text,e,`heading:${i}`));if(n.type==="code")return u.createElement("section",{key:`block:${i}`,className:"ps-md-code-block"},u.createElement("div",{className:"ps-md-code-header"},n.language||"text"),u.createElement("pre",{className:"ps-md-code-pre"},u.createElement("code",null,n.content)));if(n.type==="blockquote")return u.createElement("blockquote",{key:`block:${i}`,className:"ps-md-quote"},Ne(n.text,e,`quote:${i}`));if(n.type==="list"){const o=n.ordered?"ol":"ul";return u.createElement(o,{key:`block:${i}`,className:`ps-md-list${n.ordered?" is-ordered":""}`},n.items.map((r,a)=>u.createElement("li",{key:`item:${a}`,className:"ps-md-list-item"},Ne(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?Lr([n.header,...n.rows]):null,l=!!a,c=a?a.flexIndex:-1,d=m=>m===c?"is-flex-column":null,f=Fr([n.header],o),p=`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 u.createElement("div",{key:`block:${i}`,className:h},u.createElement("table",{className:p,style:a?.minWidth?{"--ps-table-min-width":a.minWidth}:void 0},a?u.createElement("colgroup",null,a.widths.map((m,g)=>u.createElement("col",{key:`col:${g}`,className:d(g)||void 0,style:{width:m}}))):null,u.createElement("thead",null,u.createElement("tr",null,n.header.map((m,g)=>u.createElement("th",{key:`head:${g}`,className:d(g)||void 0},Ne(m,e,`table:${i}:head:${g}`))))),u.createElement("tbody",null,n.rows.map((m,g)=>u.createElement("tr",{key:`row:${g}`},m.map((b,S)=>u.createElement("td",{key:`cell:${g}:${S}`,className:d(S)||void 0,"data-label":f[S]||void 0},u.createElement("span",{className:"ps-table-cell-value"},Ne(b,e,`table:${i}:${g}:${S}`)))))))))}return u.createElement("p",{key:`block:${i}`,className:"ps-md-paragraph"},Ne(n.text,e,`para:${i}`))}))}function Qf({controller:t,title:e,color:s,focused:n,scrollOffset:i=0,paneKey:o,theme:r,content:a}){const l=u.useRef(null),c=Gf(l,i,o,t);return u.createElement(Ze,{title:e,color:s,focused:n,theme:r},u.createElement("div",{ref:l,className:"ps-scroll-panel ps-markdown-scroll",onScroll:c},u.createElement($r,{content:a,theme:r})))}function Xf(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 Jf({title:t,color:e,focused:s,theme:n,filename:i,contentType:o,sizeBytes:r,source:a,uploadedAt:l,controller:c=null,sessionId:d=null}){const f=[];o&&f.push(o),r!=null&&f.push(Xf(r)),a&&f.push(a);const p=l?new Date(l).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}):"",h=/^image\/(png|jpeg|gif|webp)$/i.test(String(o||"")),[m,g]=u.useState(null);return u.useEffect(()=>{if(g(null),!h||!c||!d||!i)return;let b=!1;return Dr(c,d,i).then(S=>{b||g(S)}).catch(()=>{b||g("error")}),()=>{b=!0}},[h,c,d,i]),u.createElement(Ze,{title:t,color:e,focused:s,theme:n},u.createElement("div",{className:"ps-binary-preview-card"},u.createElement("div",{className:"ps-binary-preview-kicker"},h?"Image artifact":"Binary artifact"),u.createElement("h3",{className:"ps-binary-preview-title"},i||"Artifact"),f.length>0?u.createElement("div",{className:"ps-binary-preview-meta"},f.join(" • ")):null,p?u.createElement("div",{className:"ps-binary-preview-time"},`Uploaded ${p}`):null,h&&m&&m!=="error"?u.createElement("img",{className:"ps-binary-preview-image",src:m,alt:i||"artifact image",onClick:()=>{try{window.open(m,"_blank","noopener")}catch{}}}):u.createElement("p",{className:"ps-binary-preview-copy"},h?m==="error"?"Could not load the image preview. Use Download to save the file.":"Loading image preview…":"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 Vt(t){const e=String(t||"").trim();return e.startsWith("┌")&&e.endsWith("┐")}function Hs(t){const e=String(t||"").trim();return e.startsWith("└")&&e.endsWith("┘")}function Zf(t){const e=String(t||"").trim();return e.startsWith("├")&&e.endsWith("┤")}function Pt(t){const e=String(t||"").trim();return e.startsWith("│")&&e.endsWith("│")}function ep(t){const e=String(be(t)||"").trim();return Vt(e)?e.slice(1,-1).replace(/^─+/u,"").replace(/─+$/u,"").trim():""}function tp(t){if(t?.kind==="runs"&&Array.isArray(t.runs)&&t.runs.length>=3)return String(t.runs[1]?.text||"").replace(/\s+$/u,"");const e=be(t);return Pt(e)?String(e).slice(1,-1).replace(/\s+$/u,""):String(e||"")}function sp(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 uo(t,{fallbackColor:e=null}={}){return t?.kind==="runs"&&Array.isArray(t.runs)&&t.runs.length>=3?sp(t.runs.slice(1,-1)):[{text:be(t).replace(/^\s*[┌│]\s?/,"").replace(/\s?[┐│]\s*$/,"").replace(/^─+/,"").replace(/─+$/,"").trim(),color:e}]}function np(t){const e=String(t||"").trim();return Pt(e)?e.slice(1,-1).split("│").map(s=>s.trim()):[]}function ip(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 op(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)=>ip(s,n)?`${s}${n}`:`${s} ${n}`,e[0])}function fo(t=[]){const e=Math.max(0,...t.map(s=>s.length));return Array.from({length:e},(s,n)=>op(t.map(i=>String(i[n]||"").trim()).filter(Boolean)))}function Br(t=[]){const e=[];for(let s=0;s<t.length;){const n=t[s];if(n?.preserve){const o=n.splashVariant||null,r=[];for(;s<t.length&&t[s]?.preserve&&(t[s].splashVariant||null)===o;)r.push(t[s]),s+=1;e.push({type:"preserve",lines:r,splashVariant:o});continue}if(n?.kind==="cardStart"){const o=[];for(s+=1;s<t.length&&t[s]?.kind!=="cardEnd";)o.push(t[s]),s+=1;s<t.length&&(s+=1),s<t.length&&be(t[s]).trim().length===0&&(s+=1),e.push({type:"card",headerRuns:Array.isArray(n.runs)?n.runs:[],borderColor:n.borderColor||"gray",blocks:Br(o)});continue}if(n?.kind==="imageAttachments"){e.push({type:"imageAttachments",sessionId:n.sessionId||null,attachments:Array.isArray(n.attachments)?n.attachments:[]}),s+=1;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=be(n);if(Vt(i)&&i.includes("┬")){const o=[],r=[];let a=[],l=!0;for(s+=1;s<t.length;){const c=t[s],d=be(c);if(Hs(d)){if(a.length>0){const f=fo(a);f.length>0&&(l?o.push(f):r.push(f))}s+=1;break}if(Zf(d)){if(a.length>0){const f=fo(a);f.length>0&&(l?o.push(f):r.push(f))}a=[],l=!1,s+=1;continue}if(Pt(d)){const f=np(d);f.length>0&&a.push(f)}s+=1}e.push({type:"table",headerRows:o,bodyRows:r});continue}if(n?.kind==="runs"&&Array.isArray(n.runs)&&n.runs.length===1&&Vt(i)){const o=ep(n),r=[];for(s+=1;s<t.length;){const a=t[s],l=be(a);if(Hs(l)){s+=1;break}Pt(l)?r.push(tp(a)):r.push(be(a)),s+=1}s<t.length&&be(t[s]).trim().length===0&&(s+=1),e.push({type:"code",language:o||"text",content:r.join(`
90
- `)});continue}if(n?.kind==="runs"&&Array.isArray(n.runs)&&n.runs.length>2&&Vt(i)){const o=uo(n),r=n.runs[0]?.color||"gray",a=[];for(s+=1;s<t.length;){const l=t[s],c=be(l);if(Hs(c)){s+=1;break}Pt(c)?a.push(uo(l)):a.push(l?.kind==="runs"?l.runs:[{text:be(l),color:l?.color||null}]),s+=1}s<t.length&&be(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 rp({lines:t,theme:e,controller:s=null}){const n=u.useMemo(()=>Br(t),[t]);return u.createElement(Hr,{blocks:n,theme:e,controller:s})}const $e=new Map,ap=60;function Dr(t,e,s){const n=`${e}/${s}`,i=$e.get(n);if(i)return $e.delete(n),$e.set(n,i),i;const o=t?.transport?.api?.downloadArtifactResponse;if(typeof o!="function")return Promise.reject(new Error("artifact download unavailable"));const r=o.call(t.transport.api,e,s).then(async a=>{if(!a?.ok)throw new Error(`download failed (${a?.status})`);const l=await a.blob();return URL.createObjectURL(l)}).catch(a=>{throw $e.get(n)===r&&$e.delete(n),a});for($e.set(n,r);$e.size>ap;){const[a,l]=$e.entries().next().value;$e.delete(a),Promise.resolve(l).then(c=>URL.revokeObjectURL(c)).catch(()=>{})}return r}function lp({controller:t,sessionId:e,attachments:s}){const[n,i]=u.useState({});return u.useEffect(()=>{if(!t||!e)return;let o=!1;for(const r of s){const a=r?.filename;a&&Dr(t,e,a).then(l=>{o||i(c=>c[a]===l?c:{...c,[a]:l})}).catch(()=>{o||i(l=>l[a]==="error"?l:{...l,[a]:"error"})})}return()=>{o=!0}},[t,e,s]),u.createElement("div",{className:"ps-chat-image-strip"},s.map((o,r)=>{const a=o?.filename||`image-${r}`,l=n[a];return l&&l!=="error"?u.createElement("img",{key:`thumb:${r}:${a}`,className:"ps-chat-image-thumb",src:l,alt:a,title:`${a} — click to view full size`,onClick:()=>{try{window.open(l,"_blank","noopener")}catch{}}}):u.createElement("div",{key:`thumb:${r}:${a}`,className:`ps-chat-image-thumb is-pending${l==="error"?" is-error":""}`,title:a},l==="error"?"⚠":"🖼")}))}function Hr({blocks:t,theme:e,controller:s=null}){return u.createElement(u.Fragment,null,(t||[]).map((n,i)=>{if(n.type==="imageAttachments")return u.createElement(lp,{key:`imageAttachments:${i}`,controller:s,sessionId:n.sessionId,attachments:n.attachments});if(n.type==="preserve"){const o=n.splashVariant?` is-splash-${n.splashVariant}`:"";return u.createElement("div",{key:`preserve:${i}`,className:`ps-chat-preserve-block${o}`},n.lines.map((r,a)=>u.createElement(fe,{key:`preserve:${i}:${a}`,line:r,theme:e,className:"ps-line-preserve"})))}if(n.type==="code")return u.createElement("section",{key:`code:${i}`,className:"ps-md-code-block ps-chat-code-block"},u.createElement("div",{className:"ps-md-code-header"},n.language||"text"),u.createElement("pre",{className:"ps-md-code-pre"},u.createElement("code",null,n.content||"")));if(n.type==="card")return u.createElement("section",{key:`card:${i}`,className:"ps-chat-card",style:{"--ps-chat-card-accent":qe(e,n.borderColor)||"var(--ps-border)"}},u.createElement("header",{className:"ps-chat-card-header"},u.createElement(me,{runs:n.headerRuns,theme:e})),u.createElement("div",{className:"ps-chat-card-body"},Array.isArray(n.blocks)?u.createElement(Hr,{blocks:n.blocks,theme:e,controller:s}):(n.bodyLines||[]).map((o,r)=>u.createElement("div",{key:`card:${i}:line:${r}`,className:"ps-chat-card-line"},u.createElement(me,{runs:o,theme:e})))));if(n.type==="table"){const o=n.headerRows||[],r=n.bodyRows||[],a=Math.max(1,...o.map(b=>b.length),...r.map(b=>b.length)),l=a<=6,c=l?Lr([...o,...r]):null,d=!!c,f=c?c.flexIndex:-1,p=b=>b===f?"is-flex-column":null,h=Fr(o,a),m=`ps-chat-table${l?" is-fit-width":""}${d?" has-flex-column":""}`,g=`ps-chat-table-wrap${l?" is-fit-width":""}${d?" has-flex-column":""}`;return u.createElement("div",{key:`table:${i}`,className:g},u.createElement("table",{className:m,style:c?.minWidth?{"--ps-table-min-width":c.minWidth}:void 0},c?u.createElement("colgroup",null,c.widths.map((b,S)=>u.createElement("col",{key:`col:${S}`,className:p(S)||void 0,style:{width:b}}))):null,o.length>0?u.createElement("thead",null,o.map((b,S)=>u.createElement("tr",{key:`thead:${S}`},Array.from({length:a},(w,I)=>u.createElement("th",{key:`th:${S}:${I}`,className:p(I)||void 0},Ne(b[I]||"",e,`chat-table:${i}:head:${S}:${I}`)))))):null,u.createElement("tbody",null,r.map((b,S)=>u.createElement("tr",{key:`tbody:${S}`},Array.from({length:a},(w,I)=>u.createElement("td",{key:`td:${S}:${I}`,className:p(I)||void 0,"data-label":h[I]||void 0},u.createElement("span",{className:"ps-table-cell-value"},Ne(b[I]||"",e,`chat-table:${i}:${S}:${I}`)))))))))}return u.createElement(fe,{key:`line:${i}`,line:n.line,theme:e})}))}function Ze({title:t,titleRight:e=null,color:s="gray",focused:n=!1,actions:i=null,children:o,theme:r,className:a=""}){const l=qe(r,s);return u.createElement("section",{className:`ps-panel${n?" is-focused":""}${a?` ${a}`:""}`,style:{"--ps-panel-accent":l||"var(--ps-border)"}},u.createElement("header",{className:"ps-panel-header"},u.createElement("div",{className:"ps-panel-title"},Array.isArray(t)?u.createElement(me,{runs:t,theme:r}):io(t)),e||i?u.createElement("div",{className:"ps-panel-header-right"},e?u.createElement("div",{className:"ps-panel-title-right"},Array.isArray(e)?u.createElement(me,{runs:e,theme:r}):io(e)):null,i?u.createElement("div",{className:"ps-panel-actions"},i):null):null),u.createElement("div",{className:"ps-panel-body"},o))}function cp({lines:t,theme:e,completionByTurn:s}){const[n,i]=u.useState(()=>new Set),o=u.useCallback(d=>{i(f=>{const p=new Set(f);return p.has(d)?p.delete(d):p.add(d),p})},[]),r=d=>Number(d||0).toLocaleString("en-US"),a=d=>{const f=Number(d||0);if(!Number.isFinite(f))return"?K";const p=f/1e3,h=Math.abs(p)>=10?1:2;return`${p.toFixed(h)}K`},l=d=>{const f=Number(d||0);return Number.isFinite(f)?`${(f/1e3).toFixed(1)}s`:"?s"},c=d=>{const f=String(d||"").trim();if(!f)return"unknown";const p=f.split(":").filter(Boolean),h=p[p.length-1]||"",m=p.length>1&&ff.has(h.toLowerCase())?p.length-2:p.length-1;return p[Math.max(0,m)]||p[0]||"unknown"};return u.createElement(u.Fragment,null,t.map((d,f)=>{const p=d?.kind==="runs"&&Array.isArray(d.runs)?d.runs.find(T=>T?.completedTurn!=null)?.completedTurn:null,h=p!=null?s.get(Number(p)):null;if(!h)return u.createElement(fe,{key:`line:${f}`,line:d,theme:e});const m=h.data||{},g=String(h.seq??`${m.turnIndex??p}:${h.createdAt??f}`),b=n.has(g),S=m.reasoningEffort?`${m.model||"(unknown)"}:${m.reasoningEffort}`:m.model||"(unknown)",w=c(m.model),I=m.durationMs!=null?l(m.durationMs):"duration n/a",A=m.durationMs!=null?`${r(m.durationMs)} ms`:"duration n/a",C=`${a(m.tokensInput)} / ${a(m.tokensOutput)}`,v=[["model",S],["started",m.startedAt?new Date(m.startedAt).toLocaleString():null],["ended",m.endedAt?new Date(m.endedAt).toLocaleString():null],["duration",A],["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(([,T])=>T!=null&&T!=="");return u.createElement(u.Fragment,{key:`seq:${f}`},u.createElement(fe,{line:d,theme:e}),u.createElement("button",{type:"button",className:"ps-sequence-turn-divider",onClick:()=>o(g)},u.createElement("span",{className:"ps-sequence-turn-caret"},b?"v":">"),u.createElement("span",{className:"ps-sequence-turn-rule"},"--- "),u.createElement("span",{className:"ps-sequence-turn-key"},"Mod: "),u.createElement("span",{className:"ps-sequence-turn-model"},w),u.createElement("span",{className:"ps-sequence-turn-rule"}," ("),u.createElement("span",{className:"ps-sequence-turn-key"},"tok: "),u.createElement("span",{className:"ps-sequence-turn-tokens"},C),u.createElement("span",{className:"ps-sequence-turn-rule"},", "),u.createElement("span",{className:"ps-sequence-turn-key"},"dur: "),u.createElement("span",{className:"ps-sequence-turn-duration"},I),u.createElement("span",{className:"ps-sequence-turn-rule"},") ---")),b?u.createElement("div",{className:"ps-sequence-turn-details"},v.map(([T,M])=>u.createElement("div",{key:T},u.createElement("span",{className:"ps-sequence-turn-detail-label"},`${T}: `),u.createElement("span",null,String(M))))):null)}))}function hs({title:t,titleRight:e=null,color:s,focused:n,actions:i,lines:o,stickyLines:r=[],bottomStickyLines:a=[],scrollOffset:l=0,scrollMode:c="top",paneKey:d,controller:f,className:p="",panelClassName:h="",topContent:m=null,bottomContent:g=null,structuredBlocks:b=!1,stickyBottom:S=!1,renderBody:w=null}){const I=K(f,N=>N.ui.themeId),A=ze(I),C=u.useRef(null),v=u.useRef(null),T=u.useRef(!1),{normalizedLines:M,onScroll:O,onWheel:L,onTouchStart:H,onTouchMove:F,onTouchEnd:q}=Df(C,o,l,c,d,f,{stickyBottom:S}),Y=u.useMemo(()=>pe(r),[r]),U=u.useMemo(()=>pe(a),[a]),W=p.includes("is-preserve")&&h.includes("has-preserved-sticky"),Z=u.useCallback((N,_)=>{!N||!_||Math.abs((_.scrollLeft||0)-(N.scrollLeft||0))<=1||(T.current=!0,_.scrollLeft=N.scrollLeft,window.requestAnimationFrame(()=>{T.current=!1}))},[]),[Se,ie]=u.useState({up:!1,down:!1}),R=u.useCallback(N=>{if(!N)return;const _=N.scrollHeight-N.scrollTop-N.clientHeight>4,$=N.scrollTop>4;ie(B=>B.up===_&&B.down===$?B:{up:_,down:$})},[]),y=u.useCallback(N=>{O(),R(N.currentTarget),!(!W||T.current)&&Z(N.currentTarget,v.current)},[O,W,Z,R]);u.useEffect(()=>{R(C.current)});const k=u.useCallback(N=>{!W||T.current||Z(N.currentTarget,C.current)},[W,Z]);return u.createElement(Ze,{title:t,titleRight:e,color:s,focused:n,actions:i,theme:A,className:h},m,Y.length>0?u.createElement("div",{ref:v,className:`ps-panel-sticky${W?" is-scroll-sync":""}`,onScroll:k},Y.map((N,_)=>u.createElement(fe,{key:`sticky:${_}`,line:N,theme:A}))):null,u.createElement("div",{ref:C,className:`ps-scroll-panel ${p}${Se.down?" is-scrolled-down":""}${Se.up?" is-scrolled-up":""}`.trim(),onScroll:y,onWheel:L,onTouchStart:H,onTouchMove:F,onTouchEnd:q,onTouchCancel:q},typeof w=="function"?w(M,A):b?u.createElement(rp,{lines:M,theme:A,controller:f}):M.map((N,_)=>u.createElement(fe,{key:`line:${_}`,line:N,theme:A}))),U.length>0?u.createElement("div",{className:"ps-panel-bottom-sticky"},U.map((N,_)=>u.createElement(fe,{key:`bottom-sticky:${_}`,line:N,theme:A}))):null,g)}function up({row:t,theme:e,structured:s=!1}){if(!(s&&Array.isArray(t.titleRuns)))return Array.isArray(t.runs)?u.createElement(me,{runs:t.runs,theme:e}):t.text;const i=Array.isArray(t.ctxRuns)?t.ctxRuns:[],o=Array.isArray(t.detailRuns)?t.detailRuns:Array.isArray(t.selectedMetaRuns)?t.selectedMetaRuns:[],r=i.length>0,a=t.active&&o.length>0;return u.createElement(u.Fragment,null,u.createElement("div",{className:"ps-session-row-line"},u.createElement("div",{className:"ps-session-row-title"},u.createElement(me,{runs:t.titleRuns,theme:e})),r?u.createElement("div",{className:"ps-session-row-ctx"},u.createElement(me,{runs:i,theme:e})):null),a?u.createElement("div",{className:"ps-session-row-detail"},u.createElement(me,{runs:o,theme:e})):null)}function Ln({controller:t,actions:e=null,panelClassName:s="",structuredRows:n=!1}){const i=K(t,R=>R.ui.themeId),o=ze(i),r=u.useRef(new Map),a=K(t,R=>({activeSessionId:R.sessions.activeSessionId,sessionsById:R.sessions.byId,sessionsFlat:R.sessions.flat,filterQuery:R.sessions.filterQuery||"",ownerFilter:R.sessions.ownerFilter,pinnedIds:R.sessions.pinnedIds,selectedIds:R.sessions.selectedIds,selectMode:R.sessions.selectMode,auth:R.auth,connectionMode:R.connection?.mode||"local",modalOpen:!!R.ui.modal,focused:R.ui.focusRegion==="sessions"}),Te),l=u.useMemo(()=>yt({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]),c=a.activeSessionId&&a.sessionsById[a.activeSessionId]||null,[d,f]=u.useState(!1),[p,h]=u.useState(null),m=u.useRef(!1),g=["modelPicker","reasoningEffortPicker","contextTierPicker"],b=K(t,R=>g.includes(R.ui.modal?.type));u.useEffect(()=>{!b&&m.current&&(m.current=!1,f(!0))},[b]);const S=()=>{m.current=!0,f(!1),t.openSwitchModelPicker(()=>{m.current=!1}).then(()=>{!g.includes(t.getState().ui.modal?.type)&&m.current&&(m.current=!1,f(!0))}).catch(R=>{m.current=!1,f(!0),t.dispatch({type:"ui/status",text:R?.message||String(R)||"Failed to switch model"})})},w=a.auth?.principal||null,I=a.auth?.authorization?.role,A=I==="admin"||I==="anonymous",C=!!(c?.owner&&w&&String(c.owner.provider)===String(w.provider)&&String(c.owner.subject)===String(w.subject)),v=!!(c&&!c.isSystem&&!c.isGroup&&(A||C)),T=Array.isArray(a.selectedIds)?a.selectedIds.length:0,M=T>1,O=!!(c&&!c.isSystem&&(c.isGroup||!c.parentSessionId&&!c.groupId)),L=!!(c&&Array.isArray(a.pinnedIds)&&a.pinnedIds.includes(c.sessionId)),H=!!(c?.isGroup&&Number(c.memberCount||0)===0),F=M?Array.isArray(a.selectedIds)&&a.selectedIds.some(R=>{const y=a.sessionsById[R];return y&&!y.isSystem&&!y.isGroup}):c?.isGroup?!0:!!c,q=c?.isGroup?"Delete":M?`Terminate (${T})`:c?.isSystem?"Restart":"Terminate",U=T>0?a.selectedIds.filter(R=>{const y=a.sessionsById[R];return y&&!y.isSystem&&!y.isGroup&&!y.parentSessionId}):c&&!c.isSystem&&!c.isGroup&&!c.parentSessionId?[c.sessionId]:[],W=U.length>0,Z=`ps-session-pane${s?` ${s}`:""}`,Se=u.useCallback((R,y)=>{R&&(y?r.current.set(R,y):r.current.delete(R))},[]);u.useEffect(()=>{if(a.modalOpen||!a.focused||!a.activeSessionId)return;const R=r.current.get(a.activeSessionId);R&&(document.activeElement!==R&&R.focus({preventScroll:!0}),R.scrollIntoView({block:"nearest"}))},[a.activeSessionId,a.focused,a.modalOpen]);const ie=u.createElement(u.Fragment,null,M?u.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."},`${T} selected`):null,M?u.createElement(oe,{className:"ps-mini-button",icon:"✕",label:"Clear multi-selection",onClick:()=>t.handleCommand(x.CLEAR_SESSION_SELECTION).catch(()=>{})}):u.createElement(oe,{className:"ps-mini-button",icon:"📌",onClick:()=>t.handleCommand(x.PIN_SESSION).catch(()=>{}),disabled:!O,active:L,label:O?L?"Unpin this session":"Pin this session to the top of the list":"Only top-level non-system sessions can be pinned"}),u.createElement(oe,{className:"ps-mini-button",icon:U.length>1?`⊞${U.length}`:"⊞",onClick:()=>t.handleCommand(x.OPEN_MOVE_TO_GROUP).catch(()=>{}),disabled:!W,label:W?U.length>1?`Move ${U.length} selected sessions to a group`:"Move this session to a group":"Select a top-level non-system session to move to a group"}),u.createElement(oe,{className:"ps-mini-button",icon:u.createElement(fp),onClick:()=>f(!0),disabled:!v||M,label:M?"Disabled while multiple sessions are selected":"Manage session — rename, switch model, and sharing"}),u.createElement(oe,{className:"ps-mini-button",icon:u.createElement(pp),onClick:()=>{const R=c?.sessionId;if(!R)return;const y=Af(R);y&&(so(y),h({url:y,warn:!1}),Tf(t,R).then(k=>{h(N=>N&&N.url===y?{...N,warn:k}:N)}).catch(()=>{}))},disabled:!c||c.isGroup||M,label:"Copy link — copy a direct link to this session"}),u.createElement(oe,{className:"ps-mini-button",icon:c?.isSystem?"↻":"⊗",onClick:()=>t.handleCommand(c?.isGroup?x.DELETE_SESSION:x.OPEN_TERMINATE_PICKER).catch(()=>{}),disabled:!F,label:M?`Terminate ${T} selected sessions (Mark Completed, Cancel, or Delete)`:c?.isGroup?H?"Delete this empty group":"This group cannot be deleted yet":c?.isSystem?"Restart this system session (complete, terminate, or hard delete)":`${q} — mark completed, cancel, or delete`}),e);return u.createElement(u.Fragment,null,u.createElement(Ze,{title:[{text:"Sessions",color:"yellow",bold:!0}],color:"yellow",focused:a.focused,theme:o,actions:ie,className:Z},u.createElement("div",{className:"ps-action-list ps-session-list"},l.length===0?u.createElement("div",{className:"ps-empty-state"},a.filterQuery?`No sessions matched "@@${a.filterQuery}".`:"No sessions yet."):l.map(R=>u.createElement("button",{key:R.sessionId,type:"button",ref:y=>Se(R.sessionId,y),className:`ps-list-button ps-session-list-button${R.active?" is-selected":""}${R.selected?" is-multiselected":""}${R.pinned?" is-pinned":""}`,tabIndex:R.active?0:-1,"aria-selected":R.active?"true":"false",onClick:y=>{if(y.metaKey||y.ctrlKey){y.preventDefault(),a.selectMode||t.dispatch({type:"sessions/selectMode",enabled:!0}),t.dispatch({type:"sessions/selectToggle",sessionId:R.sessionId}),t.setFocus("sessions");return}if(y.shiftKey&&a.activeSessionId){y.preventDefault();const N=l.map(B=>B.sessionId),_=N.indexOf(a.activeSessionId),$=N.indexOf(R.sessionId);if(_>=0&&$>=0){const[B,V]=_<=$?[_,$]:[$,_],ae=N.slice(B,V+1),te=Array.from(new Set([...a.selectedIds||[],...ae]));t.setSessionSelection(te),t.setFocus("sessions");return}}if(R.hasChildren&&R.active){t.dispatch({type:R.collapsed?"sessions/expand":"sessions/collapse",sessionId:R.sessionId}),t.setFocus("sessions");return}a.selectMode&&t.dispatch({type:"sessions/selectClear"}),t.setFocus("sessions"),R.active||t.loadSession(R.sessionId).catch(()=>{})}},u.createElement("div",{className:"ps-line ps-session-row-content",style:{paddingInlineStart:`${Math.max(0,R.depth)*4}px`}},u.createElement(up,{row:R,theme:o,structured:n})))))),d&&c&&!c.isGroup?u.createElement(mp,{controller:t,sessionId:c.sessionId,initialTitle:c.title||"",currentModel:c.model||"",currentReasoningEffort:c.reasoningEffort||"",principal:a.auth?.principal||null,onClose:()=>f(!1),onSwitchModel:S,onChanged:()=>{}}):null,p?u.createElement(dp,{url:p.url,warn:p.warn,onCopyAgain:()=>{so(p.url),t.dispatch({type:"ui/status",text:vf})},onClose:()=>h(null)}):null)}function dp({url:t,warn:e,onCopyAgain:s,onClose:n}){const i=u.useRef(null);u.useEffect(()=>{const r=i.current;r&&(r.focus(),r.select())},[]);const o=r=>r.stopPropagation();return u.createElement("div",{className:"ps-share-overlay",onClick:n},u.createElement("div",{className:"ps-link-modal",onClick:o},u.createElement("div",{className:"ps-share-modal-head"},u.createElement("span",null,"Link copied"),u.createElement("button",{className:"ps-modal-close",onClick:n},"✕")),u.createElement("div",{className:"ps-share-section-sub"},"Copied to your clipboard — anyone with access can open the session from this link."),u.createElement("div",{className:"ps-link-row"},u.createElement("input",{ref:i,className:"ps-link-input",readOnly:!0,value:t,onFocus:()=>i.current?.select()}),u.createElement("button",{className:"ps-mini-button",onClick:s},"Copy")),e?u.createElement("div",{className:"ps-link-warn"},Ef):null))}const po={private:{glyph:"🔒",label:"Private"},shared_read:{glyph:"👁",label:"Shared · read"},shared_write:{glyph:"✎",label:"Shared · write"}};function fp(){return u.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},u.createElement("line",{x1:"4",y1:"6",x2:"20",y2:"6"}),u.createElement("line",{x1:"4",y1:"12",x2:"20",y2:"12"}),u.createElement("line",{x1:"4",y1:"18",x2:"20",y2:"18"}),u.createElement("circle",{cx:"9",cy:"6",r:"2",fill:"currentColor"}),u.createElement("circle",{cx:"15",cy:"12",r:"2",fill:"currentColor"}),u.createElement("circle",{cx:"8",cy:"18",r:"2",fill:"currentColor"}))}function pp(){return u.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},u.createElement("path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}),u.createElement("path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"}))}function hp(t,e,s){const[n,i]=u.useState({access:null,loading:!1}),o=u.useCallback(()=>{if(!e||s||typeof t.transport.getSessionAccess!="function"){i({access:null,loading:!1});return}let r=!1;return i(a=>({...a,loading:!0})),t.transport.getSessionAccess(e).then(a=>{r||i({access:a,loading:!1})}).catch(()=>{r||i({access:null,loading:!1})}),()=>{r=!0}},[t,e,s]);return u.useEffect(()=>o(),[o]),{access:n.access,loading:n.loading,reload:o}}function mp({controller:t,sessionId:e,initialTitle:s,currentModel:n,currentReasoningEffort:i,principal:o,onClose:r,onSwitchModel:a,onChanged:l}){const[c,d]=u.useState("general"),[f,p]=u.useState(null),[h,m]=u.useState(s||""),[g,b]=u.useState([]),[S,w]=u.useState([]),[I,A]=u.useState("private"),[C,v]=u.useState(""),[T,M]=u.useState("write"),[O,L]=u.useState([]),[H,F]=u.useState(!1),[q,Y]=u.useState(null);u.useEffect(()=>{let P=!1;return t.transport.getSessionAccess(e).then(z=>{!P&&z&&(p(z),A(z.visibility||"private"))}).catch(()=>{}),typeof t.transport.listKnownUsers=="function"&&t.transport.listKnownUsers({limit:500}).then(z=>{P||L(Array.isArray(z)?z:[])}).catch(()=>{}),()=>{P=!0}},[t,e]);const U=u.useCallback(()=>{t.transport.listSessionShares(e).then(P=>{const z=Array.isArray(P)?P:[];b(z),w(z)}).catch(()=>{b([]),w([])})},[t,e]);u.useEffect(()=>{U()},[U]);const W=async P=>{F(!0),Y(null);try{await P(),l?.()}catch(z){Y(z?.message||String(z))}finally{F(!1)}},Z=()=>W(async()=>{await t.transport.renameSession(e,h.trim())}),Se=P=>{const z=P.trim().toLowerCase();if(!z)return null;const ke=O.find(de=>de.displayName&&de.displayName.toLowerCase()===z||de.email&&de.email.toLowerCase()===z||de.subject&&de.subject.toLowerCase()===z);return ke||{provider:o?.provider||"dev",subject:P.trim(),email:null,displayName:null}},ie=P=>`${P.provider}${P.subject}`,R=P=>{const z=ie(P);w(ke=>[...ke.filter(de=>ie(de)!==z),{provider:P.provider,subject:P.subject,email:P.email??null,displayName:P.displayName??null,access:T}]),v("")},y=()=>{const P=Se(C);P&&R(P)},k=P=>{const z=ie(P);w(ke=>ke.filter(de=>ie(de)!==z))},N=new Set(S.map(ie)),_=f?.owner?`${f.owner.provider}${f.owner.subject}`:null,$=C.trim().toLowerCase(),B=$?O.filter(P=>{const z=ie(P);return z===_||N.has(z)?!1:P.displayName&&P.displayName.toLowerCase().includes($)||P.email&&P.email.toLowerCase().includes($)||P.subject&&P.subject.toLowerCase().includes($)}).slice(0,25):[],V=!!f?.canManage,ae=f?.visibility||"private",te=new Set(S.map(P=>`${ie(P)}:${P.access}`)),It=new Set(g.map(P=>`${ie(P)}:${P.access}`)),ms=te.size!==It.size||[...te].some(P=>!It.has(P)),$n=V&&(I!==ae||ms),Ur=()=>W(async()=>{I!==ae&&await t.transport.setSessionVisibility(e,I);const P=new Map(g.map(_e=>[ie(_e),_e])),z=new Map(S.map(_e=>[ie(_e),_e]));for(const[_e,Re]of z){const Dn=P.get(_e);(!Dn||Dn.access!==Re.access)&&await t.transport.grantSessionShare(e,{provider:Re.provider,subject:Re.subject,email:Re.email??null,displayName:Re.displayName??null},Re.access)}for(const[_e,Re]of P)z.has(_e)||await t.transport.revokeSessionShare(e,{provider:Re.provider,subject:Re.subject});const ke=await t.transport.listSessionShares(e).catch(()=>null);Array.isArray(ke)&&(b(ke),w(ke));const de=await t.transport.getSessionAccess(e).catch(()=>null);de&&(p(de),A(de.visibility||"private")),t.dispatch({type:"ui/status",text:"Access updated."})}),jr=a||(()=>{r(),t.openSwitchModelPicker().catch(P=>{t.dispatch({type:"ui/status",text:P?.message||String(P)||"Failed to switch model"})})}),Wr=n?i?`${n}:${i}`:n:"—",Bn=[{id:"general",label:"General"},...V?[{id:"access",label:"Access"}]:[]],$t=Bn.some(P=>P.id===c)?c:"general",Vr=P=>P.stopPropagation();return u.createElement("div",{className:"ps-share-overlay",onClick:r},u.createElement("div",{className:"ps-share-modal",onClick:Vr},u.createElement("div",{className:"ps-share-modal-head"},u.createElement("span",null,"Manage session"),u.createElement("button",{className:"ps-modal-close",onClick:r},"✕")),u.createElement("div",{className:"ps-manage-tabs",role:"tablist"},Bn.map(P=>u.createElement("button",{key:P.id,type:"button",role:"tab","aria-selected":$t===P.id?"true":"false",className:`ps-manage-tab${$t===P.id?" is-active":""}`,onClick:()=>d(P.id)},P.label))),$t==="general"?u.createElement(u.Fragment,null,u.createElement("div",{className:"ps-share-section-label"},"Name"),u.createElement("div",{className:"ps-share-add-row"},u.createElement("input",{className:"ps-share-add-input",placeholder:"Session title",value:h,disabled:H,onChange:P=>m(P.target.value),onKeyDown:P=>{P.key==="Enter"&&Z()}}),u.createElement("button",{className:"ps-mini-button",disabled:H||!h.trim(),onClick:Z},"Save")),u.createElement("div",{className:"ps-share-section-label"},"Model"),u.createElement("div",{className:"ps-share-section-sub"},"The model this session uses on its next turn."),u.createElement("div",{className:"ps-share-add-row"},u.createElement("span",{className:"ps-manage-model-current"},Wr),u.createElement("button",{className:"ps-mini-button",disabled:H,onClick:jr},"Switch model…"))):null,$t==="access"&&V?u.createElement(u.Fragment,null,u.createElement("div",{className:"ps-share-section-label"},"General access"),u.createElement("div",{className:"ps-share-section-sub"},"The baseline level for everyone signed in to this workspace."),["private","shared_read","shared_write"].map(P=>u.createElement("label",{key:P,className:`ps-share-radio${I===P?" is-active":""}`},u.createElement("input",{type:"radio",name:"visibility",checked:I===P,disabled:H,onChange:()=>A(P)}),u.createElement("span",{className:"ps-share-radio-glyph"},po[P].glyph),u.createElement("span",null,po[P].label),u.createElement("span",{className:"ps-share-radio-hint"},P==="private"?"only you and admins":P==="shared_read"?"everyone here can view":"everyone here can view and send"))),u.createElement("div",{className:"ps-share-section-label"},"Special access"),u.createElement("div",{className:"ps-share-section-sub"},"Give specific people more than the general level. A person's grant wins over general access."),S.length===0?u.createElement("div",{className:"ps-share-empty"},"No individual grants — everyone has the general access above."):S.map(P=>u.createElement("div",{key:`${P.provider}/${P.subject}`,className:"ps-share-grant-row"},u.createElement("span",{className:"ps-share-grant-name"},P.displayName||P.subject),u.createElement("span",{className:"ps-share-grant-access"},`can ${P.access}`),u.createElement("button",{className:"ps-mini-button",disabled:H,onClick:()=>k(P)},"Remove"))),u.createElement("div",{className:"ps-share-add-wrap"},u.createElement("div",{className:"ps-share-add-row"},u.createElement("input",{className:"ps-share-add-input",placeholder:"Name, email, or id",value:C,disabled:H,autoComplete:"off",onChange:P=>v(P.target.value),onKeyDown:P=>{P.key==="Enter"&&y()}}),u.createElement("select",{className:"ps-share-add-select",value:T,disabled:H,onChange:P=>M(P.target.value)},u.createElement("option",{value:"read"},"can read"),u.createElement("option",{value:"write"},"can write")),u.createElement("button",{className:"ps-mini-button",disabled:H||!C.trim(),onClick:y},"Add")),B.length>0?u.createElement("div",{className:"ps-share-suggestions"},B.map(P=>u.createElement("button",{key:`${P.provider}/${P.subject}`,type:"button",className:"ps-share-suggestion",disabled:H,onClick:()=>R(P)},u.createElement("span",{className:"ps-share-suggestion-name"},P.displayName||P.subject),P.email?u.createElement("span",{className:"ps-share-suggestion-email"},P.email):null))):null),u.createElement("div",{className:"ps-share-foot-hint"},"Sharing applies to this session and its sub-agents. Suggestions are people who have signed in before — you can also grant by email to someone who hasn't; it takes effect when they first sign in."),u.createElement("div",{className:"ps-manage-apply-bar"},u.createElement("span",{className:"ps-share-section-sub"},$n?"Unsaved access changes.":"No changes to apply."),u.createElement("button",{className:"ps-mini-button ps-manage-apply",disabled:H||!$n,onClick:Ur},"Apply"))):null,q?u.createElement("div",{className:"ps-share-error"},q):null))}function Fn({controller:t,mobile:e=!1,fullWidth:s=!1,showComposer:n=!0}){const i=K(t,T=>T.ui.themeId),o=ze(i),r=K(t,T=>{const M=T.sessions.activeSessionId,O=ps(T),L=s||e?O.totalWidth:O.leftWidth,H=Math.max(20,L-4);return{activeSessionId:M,activeHistory:M&&T.history.bySessionId.get(M)||null,activeOutbox:M&&T.outbox?.bySessionId?.[M]?T.outbox.bySessionId[M]:[],branding:T.branding,connection:T.connection,sessionsById:T.sessions.byId,sessionsFlat:T.sessions.flat,inspectorTab:T.ui.inspectorTab,chatViewMode:T.ui.chatViewMode||"transcript",activeSessionIsGroup:!!(M&&T.sessions.byId[M]?.isGroup),activeSessionStatus:M?String(T.sessions.byId[M]?.status||"").toLowerCase():"",focused:T.ui.focusRegion==="chat",scroll:T.ui.scroll.chat,authPrincipal:T.auth?.principal||null,contentWidth:H}},Te),a=u.useMemo(()=>({branding:r.branding,connection:r.connection,auth:{principal:r.authPrincipal},sessions:{activeSessionId:r.activeSessionId,byId:r.sessionsById,flat:r.sessionsFlat},history:{bySessionId:r.activeSessionId&&r.activeHistory?new Map([[r.activeSessionId,r.activeHistory]]):new Map},outbox:{bySessionId:r.activeSessionId?{[r.activeSessionId]:r.activeOutbox}:{}},ui:{inspectorTab:r.inspectorTab,chatViewMode:r.chatViewMode}}),[r.activeHistory,r.activeSessionId,r.activeOutbox,r.authPrincipal,r.branding,r.connection,r.chatViewMode,r.inspectorTab,r.sessionsById,r.sessionsFlat]),l=u.useMemo(()=>ar(a,{width:r.contentWidth}),[a,r.contentWidth]),c=So(!!l.animateTitleRight),d=u.useMemo(()=>bo(l.titleRight,l.animateTitleRight?c:""),[c,l.animateTitleRight,l.titleRight]),f=u.useMemo(()=>vn(a,r.contentWidth,{tableMode:"sentinel"}),[a,r.contentWidth]),p=yo(r.activeSessionStatus==="running"),m=u.useMemo(()=>xn(a,{spinnerFrame:p,maxWidth:r.contentWidth}),[a,p,r.contentWidth]),g=u.useMemo(()=>En(a,r.contentWidth,{tableMode:"sentinel"}),[a,r.contentWidth]),b=u.useMemo(()=>m.length>0?[...g,...m]:g,[g,m]),{access:S}=hp(t,r.activeSessionId,r.activeSessionIsGroup),w=K(t,Dl,Te),I=n&&!r.activeSessionIsGroup&&r.chatViewMode!=="summary",A=!!S&&S.canWrite===!1,C=I?u.createElement("div",{className:"ps-chat-composer"},A?u.createElement("div",{className:"ps-composer-readonly"},`You have view access to this session. Ask ${S.owner?.displayName||S.owner?.email||"the owner"} for write access to participate.`):u.createElement(wp,{controller:t,mobile:e,active:!0})):null,v=!!(r.activeSessionId&&r.sessionsById[r.activeSessionId]);return w&&!v?u.createElement(Ze,{title:l.title,color:l.color,focused:r.focused,theme:o,className:"ps-chat-panel"},u.createElement("div",{className:"ps-empty-state ps-nav-error-state"},u.createElement("div",{className:"ps-nav-error-message"},w.message),w.retryable?u.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>t.setNavigationIntent(w.sessionId)},"Retry"):null)):u.createElement(hs,{controller:t,title:e?oo(l.title,28):l.title,titleRight:e&&d?oo(d,18):d,actions:null,color:l.color,focused:r.focused,lines:f,bottomStickyLines:b,scrollOffset:r.scroll,scrollMode:"bottom",paneKey:"chat",className:"is-wrapped",panelClassName:"ps-chat-panel",bottomContent:C,structuredBlocks:!0})}function gp({controller:t}){return u.createElement("div",{className:"ps-mobile-workspace"},u.createElement(Ln,{controller:t,panelClassName:"ps-mobile-session-pane"}),u.createElement("div",{className:"ps-mobile-chat-pane"},u.createElement(Fn,{controller:t,mobile:!0,fullWidth:!0})))}function Gr({activeTab:t,controller:e}){const s=u.useMemo(()=>Rn(e),[e]);return u.createElement("div",{className:"ps-tab-row ps-tab-row-icons"},s.map(n=>u.createElement(oe,{key:n,icon:gf[n]||"•",label:mf[n]||n,active:t===n,onClick:()=>{e.setFocus("inspector"),e.selectInspectorTab(n).catch(()=>{})}})))}function yp({controller:t,focused:e,mobile:s=!1}){const n=K(t,S=>S.ui.themeId),i=ze(n),o=u.useRef(null),r=K(t,S=>{const w=S.sessions.activeSessionId,I=ps(S),A=s||S.files.fullscreen?S.ui.layout?.viewportWidth??120:I.rightWidth;return{activeSessionId:w,sessionsById:S.sessions.byId,sessionsFlat:S.sessions.flat,filesBySessionId:S.files.bySessionId,filesFilter:S.files.filter,selectedArtifactId:S.files.selectedArtifactId,focused:e,previewScroll:S.ui.scroll.filePreview,fullscreen:!!S.files.fullscreen,contentWidth:Math.max(20,A-4),canBrowserUpload:Sf(t),canPathUpload:bf(t),canDeleteArtifacts:If(t),canOpenLocally:xf(t)}},Te),a=u.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=u.useMemo(()=>Cn(a,{listWidth:Math.max(18,r.contentWidth-4),previewWidth:Math.max(18,r.contentWidth-4),showHints:!1}),[a,r.contentWidth]),c=u.useMemo(()=>_t(a),[a]),d=c.length>0,f=u.useCallback(S=>{const w=Array.isArray(S)?S.filter(Boolean):[];w.length!==0&&t.uploadArtifactFiles(w).catch(()=>{})},[t]),p=u.useCallback(()=>{if(r.canBrowserUpload&&o.current){o.current.click();return}r.canPathUpload&&t.handleCommand(x.OPEN_ARTIFACT_UPLOAD).catch(()=>{})},[t,r.canBrowserUpload,r.canPathUpload]),h=u.createElement(u.Fragment,null,u.createElement("input",{ref:o,type:"file",className:"ps-hidden-file-input",multiple:!0,tabIndex:-1,"aria-hidden":"true",onChange:S=>{f(Array.from(S.currentTarget.files||[])),S.currentTarget.value=""}}),u.createElement(oe,{icon:"↥",label:"Upload",onClick:p,disabled:!r.canBrowserUpload&&!r.canPathUpload}),u.createElement(oe,{icon:"↧",label:"Download",onClick:()=>t.handleCommand(x.DOWNLOAD_SELECTED_FILE).catch(()=>{}),disabled:!d}),r.canDeleteArtifacts?u.createElement(oe,{icon:"✕",label:"Delete",onClick:()=>t.handleCommand(x.DELETE_SELECTED_FILE).catch(()=>{}),disabled:!d}):null,r.canOpenLocally?u.createElement(oe,{icon:"↗",label:"Open locally",onClick:()=>t.handleCommand(x.OPEN_SELECTED_FILE).catch(()=>{}),disabled:!d}):null,u.createElement(oe,{icon:"▾",label:"Filter",onClick:()=>t.handleCommand(x.OPEN_FILES_FILTER).catch(()=>{})}),u.createElement(oe,{icon:r.fullscreen?"⇱":"⛶",label:r.fullscreen?"Exit fullscreen":"Fullscreen",onClick:()=>t.handleCommand(x.TOGGLE_FILE_PREVIEW_FULLSCREEN).catch(()=>{})})),m=c.length===0?pe(l.listBodyLines||[]).map((S,w)=>u.createElement(fe,{key:`empty:${w}`,line:S,theme:i})):c.map((S,w)=>u.createElement("button",{key:S.id,type:"button",className:`ps-list-button${w===l.selectedIndex?" is-selected":""}`,onClick:()=>{t.setFocus("inspector"),t.selectFileBrowserItem(S).catch(()=>{})}},u.createElement(fe,{line:pe([l.listBodyLines?.[w]])[0],theme:i}))),g=l.previewRenderMode==="markdown"&&!l.previewLoading&&!l.previewError?u.createElement(Qf,{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?u.createElement(Jf,{title:l.previewTitle,color:"cyan",focused:!1,theme:i,filename:l.selectedFilename,contentType:l.previewContentType,sizeBytes:l.previewSizeBytes,source:l.previewSource,uploadedAt:l.previewUploadedAt,controller:t,sessionId:l.selectedSessionId}):u.createElement(hs,{controller:t,title:l.previewTitle,color:"cyan",focused:!1,lines:l.previewLines,scrollOffset:r.previewScroll,scrollMode:"top",paneKey:"filePreview",className:"is-preview is-wrapped"}),b=r;return u.createElement(Ze,{title:b.fullscreen?l.fullscreenTitle:s&&l.panelTitleMobile?l.panelTitleMobile:l.panelTitle,color:"magenta",focused:b.focused,actions:h,theme:i},u.createElement(Gr,{activeTab:"files",controller:t}),b.fullscreen?g:u.createElement("div",{className:"ps-files-grid"},u.createElement(Ze,{title:l.listTitle,color:"cyan",theme:i},u.createElement("div",{className:"ps-action-list"},m)),g))}function Ct({controller:t,mobile:e=!1,panelClassName:s="",extraActions:n=null}){const i=K(t,f=>{const p=ps(f),h=f.ui.inspectorTab,m=e?f.ui.layout?.viewportWidth??120:p.rightWidth;return{inspectorTab:h,statsViewMode:f.ui.statsViewMode,activeSessionId:f.sessions.activeSessionId,sessionsById:f.sessions.byId,sessionsFlat:f.sessions.flat,historyBySessionId:f.history.bySessionId,sessionStats:f.sessionStats,fleetStats:f.fleetStats,connection:f.connection,orchestrationBySessionId:f.orchestration.bySessionId,executionHistoryBySessionId:f.executionHistory?.bySessionId||{},executionHistoryFormat:f.executionHistory?.format||"pretty",logs:f.logs,files:f.files,focused:f.ui.focusRegion==="inspector",scroll:f.ui.scroll.inspector,followBottom:f.ui.followBottom?.inspector!==!1,logsTailing:f.logs.tailing,filesFullscreen:!!f.files.fullscreen,contentWidth:_f(m,h)}},Te),o=u.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=u.useMemo(()=>Ye(o,{width:i.contentWidth,allowWideColumns:e}),[e,o,i.contentWidth]),a=u.useMemo(()=>{const f=i.activeSessionId&&i.historyBySessionId?.get(i.activeSessionId)||null,p=new Map;for(const h of f?.events||[]){if(h?.eventType!=="session.turn_completed")continue;const m=Number(h?.data?.turnIndex??h?.data?.iteration);Number.isFinite(m)&&p.set(m,h)}return p},[i.activeSessionId,i.historyBySessionId]),l=u.useCallback((f,p)=>u.createElement(cp,{lines:f,theme:p,completionByTurn:a}),[a]);if(i.inspectorTab==="files"&&!r.disabled)return u.createElement(yp,{controller:t,focused:i.focused,mobile:e});const c=[];if(i.inspectorTab==="logs")c.push(u.createElement(oe,{key:"tail",icon:i.logsTailing?"■":"⇣",label:i.logsTailing?"Stop tailing":"Tail (follow)",active:i.logsTailing,onClick:()=>t.handleCommand(x.TOGGLE_LOG_TAIL).catch(()=>{})})),c.push(u.createElement(oe,{key:"filter",icon:"▾",label:"Filter",onClick:()=>t.handleCommand(x.OPEN_LOG_FILTER).catch(()=>{})}));else if(i.inspectorTab==="history")c.push(u.createElement(oe,{key:"refresh",icon:"↻",label:"Refresh",onClick:()=>t.handleCommand(x.REFRESH_EXECUTION_HISTORY).catch(()=>{})})),c.push(u.createElement(oe,{key:"save",icon:"⇩",label:"Export as artifact",onClick:()=>t.handleCommand(x.EXPORT_EXECUTION_HISTORY).catch(()=>{})}));else if(i.inspectorTab==="stats"){const f={session:"◉",fleet:"⬢",users:"⚇"};for(const p of["session","fleet","users"])c.push(u.createElement(oe,{key:`stats-view:${p}`,icon:f[p],label:`${p.replace(/^./u,h=>h.toUpperCase())} stats`,active:i.statsViewMode===p,onClick:()=>t.setStatsViewMode(p)}))}const d=n?c.concat(n):c;return u.createElement(hs,{controller:t,title:r.title,color:"magenta",focused:i.focused,actions:d,topContent:u.createElement(Gr,{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 sn({controller:t,panelClassName:e="",extraActions:s=null}){const n=K(t,r=>{const a=r.sessions.activeSessionId,l=ps(r),c=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:c}},Te),i=u.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=u.useMemo(()=>Tn(i,n.maxLines),[i,n.maxLines]);return u.createElement(hs,{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 nn=[{id:"sessions",label:"Sessions",side:"left"},{id:"inspector",label:"Inspector",side:"right"},{id:"activity",label:"Activity",side:"right"}];function Sp({controller:t,pane:e,onClose:s,mobile:n=!1}){if(!e)return null;let i=null;e==="sessions"?i=u.createElement(Ln,{controller:t,panelClassName:"ps-chat-focus-pane",structuredRows:n,actions:u.createElement("button",{type:"button",className:"ps-mini-button",onClick:s},"Close")}):e==="inspector"?i=u.createElement(Ct,{controller:t,mobile:!1,panelClassName:"ps-chat-focus-pane",extraActions:u.createElement("button",{type:"button",className:"ps-mini-button",onClick:s},"Close")}):e==="activity"&&(i=u.createElement(sn,{controller:t,panelClassName:"ps-chat-focus-pane",extraActions:u.createElement("button",{type:"button",className:"ps-mini-button",onClick:s},"Close")}));const o=nn.find(r=>r.id===e);return u.createElement("div",{className:`ps-chat-focus-overlay${o?.side==="left"?" is-left":" is-right"}`},i)}function bp({controller:t,openPane:e,onTogglePane:s,onExitFocus:n,mobile:i=!1}){const o=K(t,a=>a.ui.focusRegion),r=i?u.createElement("div",{className:"ps-chat-focus-rail"},u.createElement("button",{type:"button",className:"ps-mini-button ps-chat-focus-button",onClick:n},"Exit Focus"),u.createElement("button",{type:"button",className:`ps-mini-button ps-chat-focus-button${e==="sessions"?" is-active":""}`,onClick:()=>s("sessions")},"Sessions")):u.createElement("div",{className:"ps-chat-focus-rail"},nn.map(a=>u.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)),u.createElement("div",{className:"ps-chat-focus-status"},e?`Focused: ${nn.find(a=>a.id===e)?.label||e}`:`Focused: ${o==="prompt"?"Prompt":"Chat"}`));return u.createElement("div",{className:"ps-chat-focus-shell"},r,u.createElement("div",{className:"ps-chat-focus-body"},u.createElement(Fn,{controller:t,mobile:i,fullWidth:!0}),u.createElement(Sp,{controller:t,pane:e,onClose:()=>s(e),mobile:i})))}const ho=Object.freeze([]);function mo(t){const e=Number(t)||0;return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:e>=1024?`${Math.round(e/1024)} KB`:`${e} B`}function wp({controller:t,mobile:e,active:s=!0,onAfterSend:n=null}){const i=K(t,v=>{const T=v.sessions.activeSessionId,M=T&&v.sessions.byId[T]||null,O=T&&v.outbox?.bySessionId?.[T]?v.outbox.bySessionId[T]:[];return{value:v.ui.prompt,cursor:v.ui.promptCursor,focused:v.ui.focusRegion==="prompt",modalOpen:!!v.ui.modal,answerMode:!!M?.pendingQuestion?.question,canStopTurn:sr(M),hasOutbox:O.length>0,hasPendingOutbox:O.some(L=>L?.phase==="pending"),pendingCount:O.filter(L=>L?.phase==="pending").length,editingPending:v.ui.promptEdit?.sessionId===T,selectedOutboxPhase:v.ui.promptEdit?.sessionId===T&&v.ui.promptEdit?.phase||null,promptAttachments:v.ui.promptAttachments||ho}},Te),o=u.useRef(null),r=u.useRef(null),[a,l]=u.useState(!1),c=typeof t.transport?.supportsPromptImageAttachments=="function"&&t.transport.supportsPromptImageAttachments()&&typeof t.transport?.uploadArtifactFromFile=="function",d=c?i.promptAttachments.filter(v=>v?.kind==="image"):ho,f=u.useRef(new Map);u.useEffect(()=>{const v=f.current,T=new Set(d.map(M=>M.file));for(const[M,O]of v)T.has(M)||(URL.revokeObjectURL(O),v.delete(M));for(const M of d)if(M.file&&!v.has(M.file))try{v.set(M.file,URL.createObjectURL(M.file))}catch{}},[d]),u.useEffect(()=>()=>{for(const v of f.current.values())URL.revokeObjectURL(v);f.current.clear()},[]);const p=u.useCallback(v=>{if(!c)return 0;const T=Array.from(v||[]).filter(O=>O&&typeof O.type=="string"&&O.type.startsWith("image/"));return T.length===0?0:t.addPendingImageFiles(T)?.accepted||0},[t,c]);u.useEffect(()=>{const v=o.current;if(!(!s||i.modalOpen||!i.focused||!v)){if(document.activeElement!==v)try{v.focus({preventScroll:!0})}catch{v.focus()}v.setSelectionRange(i.cursor,i.cursor)}},[s,i.cursor,i.focused,i.modalOpen]);const h=u.useCallback(()=>{t.handleCommand(x.SEND_PROMPT).catch(()=>{}).finally(()=>{n?.()})},[t,n]),[m,g]=u.useState(!1),b=u.useCallback(()=>{g(!0),t.handleCommand(x.STOP_TURN).catch(()=>{}).finally(()=>g(!1))},[t]),S=u.useCallback(()=>{if(t.getState().ui.promptEdit){typeof t.cancelSelectedOutboxPrompt=="function"?t.cancelSelectedOutboxPrompt().catch(()=>{}):t.cancelSelectedPendingPrompt();return}typeof t.cancelLatestQueuedOutbox=="function"&&t.cancelLatestQueuedOutbox().catch(()=>{})},[t]),w=i.editingPending||i.hasPendingOutbox&&!i.value.trim()?"⇪":i.hasOutbox?"+":"❯",I=i.selectedOutboxPhase==="queued",A=i.selectedOutboxPhase==="cancelling",C=I||A;return u.createElement("div",{className:`ps-prompt-shell${e?" is-mobile":""}${a?" is-drag-over":""}`,...c?{onDragOver:v=>{v.dataTransfer?.types?.includes?.("Files")&&(v.preventDefault(),l(!0))},onDragLeave:v=>{v.currentTarget.contains(v.relatedTarget)||l(!1)},onDrop:v=>{l(!1),v.dataTransfer?.files?.length&&(v.preventDefault(),p(v.dataTransfer.files))}}:{}},d.length>0?u.createElement("div",{className:"ps-prompt-attachments"},d.map((v,T)=>{const M=v.file?f.current.get(v.file):null;return u.createElement("div",{key:`attach:${T}:${v.filename}`,className:"ps-attach-chip",title:`${v.filename} · ${mo(v.sizeBytes)}`},M?u.createElement("img",{className:"ps-attach-thumb",src:M,alt:v.filename}):u.createElement("div",{className:"ps-attach-thumb is-placeholder"},"🖼"),u.createElement("div",{className:"ps-attach-size"},mo(v.sizeBytes)),u.createElement("button",{type:"button",className:"ps-attach-remove",title:`Remove ${v.filename}`,"aria-label":`Remove attachment ${v.filename}`,onClick:()=>t.removePendingImageAttachment(T)},"✕"))})):null,u.createElement("label",{className:"ps-prompt-label"},i.answerMode?"answer":A?"cancelling":I?"queued":i.editingPending?"pending":"you"),u.createElement("textarea",{ref:o,className:"ps-prompt-input",rows:e?2:Math.max(2,pt(i.value)),value:i.value,readOnly:C,placeholder:i.answerMode?"Type an answer and press Enter":i.editingPending?A?"Cancellation requested":I?"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:v=>t.setPromptCursor(v.currentTarget.selectionStart||0),onChange:v=>t.setPrompt(v.currentTarget.value,v.currentTarget.selectionStart||v.currentTarget.value.length),onPaste:c?v=>{const M=Array.from(v.clipboardData?.items||[]).filter(O=>O.kind==="file"&&O.type.startsWith("image/")).map(O=>O.getAsFile()).filter(Boolean);M.length>0&&p(M)>0&&v.preventDefault()}:void 0,onKeyDown:v=>{if(v.key==="Tab"&&!v.shiftKey&&t.acceptPromptReferenceAutocomplete()){v.preventDefault();return}if(v.key==="ArrowUp"&&!v.shiftKey&&!v.metaKey&&!v.altKey){v.preventDefault(),t.movePromptCursorVertical(-1);return}if(v.key==="ArrowDown"&&!v.shiftKey&&!v.metaKey&&!v.altKey){v.preventDefault(),t.movePromptCursorVertical(1);return}if(v.key==="Escape"&&i.editingPending){if(v.preventDefault(),C){t.exitPendingPromptEdit({restoreDraft:!0});return}S();return}v.key==="Enter"&&!v.shiftKey&&!v.metaKey&&!e&&(v.preventDefault(),h())}}),u.createElement("div",{className:"ps-prompt-actions"},c?u.createElement(u.Fragment,null,u.createElement("input",{ref:r,type:"file",accept:"image/*",multiple:!0,className:"ps-hidden-file-input","aria-hidden":!0,tabIndex:-1,onChange:v=>{p(v.currentTarget.files),v.currentTarget.value=""}}),u.createElement("button",{type:"button",className:"ps-mini-button ps-attach-button",title:"Attach images (or paste / drop them into the composer)","aria-label":"Attach images",onClick:()=>r.current?.click()},"📎")):null,i.editingPending&&!A?u.createElement("button",{type:"button",className:"ps-mini-button",title:I?"Delete selected queued prompt":"Cancel selected pending prompt","aria-label":I?"Delete selected queued prompt":"Cancel selected pending prompt",onClick:S},I?"Delete":"Cancel"):null,i.canStopTurn||m?u.createElement("button",{type:"button",className:`ps-stop-button${m?" is-stopping":""}`,title:"Stop the current turn (the session stays alive and returns to idle)","aria-label":"Stop the current turn",disabled:m,onClick:b},"■"):null,u.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:h},w)))}const Ip=1e3;function oe({icon:t,label:e,onClick:s,disabled:n=!1,active:i=!1,className:o="ps-toolbar-button"}){const[r,a]=u.useState(null),l=u.useRef(null),c=u.useRef(null),d=u.useRef(null),f=u.useRef(!1);u.useLayoutEffect(()=>{if(!r||!c.current||typeof window>"u")return;const T=c.current.offsetWidth/2,M=6,O=Math.max(T+M,Math.min(r.x,window.innerWidth-T-M));c.current.style.left=`${O}px`},[r]);const p=(T=!1)=>{const M=l.current;if(!M||typeof window>"u")return;const O=M.getBoundingClientRect(),L=T?O.top-44<0:O.bottom+44<window.innerHeight;a({x:O.left+O.width/2,y:L?O.bottom+6:O.top-6,placement:L?"below":"above"})},h=u.useRef(null),m=u.useRef(null),g=T=>{T.pointerType==="mouse"&&(clearTimeout(d.current),clearTimeout(h.current),d.current=setTimeout(p,Ip))},b=T=>{T.pointerType==="mouse"&&(clearTimeout(d.current),clearTimeout(h.current),a(null))},S=T=>{T.pointerType!=="mouse"&&(f.current=!1,m.current={x:T.clientX,y:T.clientY},clearTimeout(d.current),clearTimeout(h.current),d.current=setTimeout(()=>{f.current=!0,p(!0)},450))},w=T=>{if(T.pointerType==="mouse"||!m.current)return;const M=T.clientX-m.current.x,O=T.clientY-m.current.y;M*M+O*O>100&&(m.current=null,clearTimeout(d.current),a(null))},I=T=>{T.pointerType!=="mouse"&&(m.current=null,clearTimeout(d.current),f.current?(clearTimeout(h.current),h.current=setTimeout(()=>a(null),3e3),setTimeout(()=>{f.current=!1},250)):a(null))};u.useEffect(()=>()=>{clearTimeout(d.current),clearTimeout(h.current)},[]);const A=T=>{if(f.current){f.current=!1,T.preventDefault?.();return}n||s?.(T)},C=T=>{T.preventDefault?.()},v=r&&typeof document<"u"&&document.body?nf.createPortal(u.createElement("span",{ref:c,className:`ps-icon-tooltip is-${r.placement}`,role:"tooltip",style:{left:`${r.x}px`,top:`${r.y}px`}},e),document.body):null;return u.createElement("button",{ref:l,type:"button",className:`${o} ps-icon-button${i?" is-active":""}`,onClick:A,disabled:n,"aria-label":e,onPointerEnter:g,onPointerLeave:b,onPointerDown:S,onPointerMove:w,onPointerUp:I,onPointerCancel:I,onContextMenu:C},u.createElement("span",{className:"ps-icon-button-glyph","aria-hidden":"true"},t),v)}function xp({controller:t,mobile:e,chatFocusMode:s=!1,onToggleChatFocus:n=null,chatFocusDisabled:i=!1}){const o=K(t,c=>!!c.admin?.visible),r=K(t,c=>({mode:c.ui.chatViewMode||"transcript",activeSessionIsGroup:!!(c.sessions.activeSessionId&&c.sessions.byId[c.sessions.activeSessionId]?.isGroup)}),Te),a=[{key:"new",icon:"+",label:"New session",onClick:()=>t.handleCommand(x.NEW_SESSION).catch(()=>{})},{key:"model",icon:"+⚙",label:"New session + choose model",onClick:()=>t.handleCommand(x.OPEN_MODEL_PICKER).catch(()=>{})},{key:"filter",icon:"▾",label:"Filter sessions",onClick:()=>t.handleCommand(x.OPEN_SESSION_FILTER).catch(()=>{})},{key:"theme",icon:"◑",label:"Theme",onClick:()=>t.handleCommand(x.OPEN_THEME_PICKER).catch(()=>{})},{key:"summary",icon:r.mode==="summary"?"💬":"≣",label:r.activeSessionIsGroup?"Groups show group details":r.mode==="summary"?"Show chat transcript":"Show summary",onClick:()=>t.setChatViewMode(r.mode==="summary"?"transcript":"summary"),disabled:r.activeSessionIsGroup,active:r.mode==="summary"},...n?[{key:"focus",icon:s?"⇱":"⛶",label:s?"Exit focus mode":"Focus the chat pane",onClick:n,disabled:i,active:s}]:[],{key:"admin",icon:"⚙",label:o?"Close admin console":"Admin console",onClick:()=>t.handleCommand(o?x.CLOSE_ADMIN_CONSOLE:x.OPEN_ADMIN_CONSOLE).catch(()=>{}),active:o}],l=c=>u.createElement(oe,{key:c.key,icon:c.icon,label:c.label,onClick:c.onClick,disabled:!!c.disabled,active:!!c.active});return e?u.createElement("div",{className:"ps-toolbar is-mobile"},u.createElement("div",{className:"ps-toolbar-row ps-toolbar-row-primary"},u.createElement("div",{className:"ps-toolbar-row-actions"},a.map(l)))):u.createElement("div",{className:"ps-toolbar"},u.createElement("div",{className:"ps-toolbar-actions"},a.map(l)))}function vp({controller:t,paneAdjust:e=0}){const s=u.useRef(null),[n,i]=u.useState(!1);return u.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 c=Math.round((a.clientX-l.startX)/kr),d=c-l.appliedCells;d&&(t.adjustPaneSplit(d),l.appliedCells=c)};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]),u.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(x.GROW_RIGHT_PANE).catch(()=>{});return}o.key==="ArrowRight"&&(o.preventDefault(),t.handleCommand(x.GROW_LEFT_PANE).catch(()=>{}))}},u.createElement("span",{className:"ps-column-resizer-handle","aria-hidden":"true"},u.createElement("span",{className:"ps-column-resizer-dot"}),u.createElement("span",{className:"ps-column-resizer-dot"}),u.createElement("span",{className:"ps-column-resizer-dot"})))}function Ep({controller:t,portalSessionColumnAdjust:e=0}){const s=u.useRef(null),[n,i]=u.useState(!1);return u.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 c=Zs(l.startAdjust+(a.clientX-l.startX),l.minAdjust,l.maxAdjust);t.dispatch({type:"ui/portalSessionColumnAdjust",portalSessionColumnAdjust:c})};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]),u.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=en(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=en(r?.getBoundingClientRect?.().width),l=c=>{const d=Zs((Number(e)||0)+c,a.minAdjust,a.maxAdjust);t.dispatch({type:"ui/portalSessionColumnAdjust",portalSessionColumnAdjust:d})};if(o.key==="ArrowLeft"){o.preventDefault(),l(-24);return}o.key==="ArrowRight"&&(o.preventDefault(),l(24))}},u.createElement("span",{className:"ps-column-resizer-handle","aria-hidden":"true"},u.createElement("span",{className:"ps-column-resizer-dot"}),u.createElement("span",{className:"ps-column-resizer-dot"}),u.createElement("span",{className:"ps-column-resizer-dot"})))}function Ap({controller:t,activityPaneAdjust:e=0}){const s=u.useRef(null),[n,i]=u.useState(!1);return u.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 c=Math.round((a.clientY-l.startY)/Mr),d=c-l.appliedCells;d&&(t.adjustActivityPaneSplit(-d),l.appliedCells=c)};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]),u.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))}},u.createElement("span",{className:"ps-row-resizer-handle","aria-hidden":"true"},u.createElement("span",{className:"ps-row-resizer-dot"}),u.createElement("span",{className:"ps-row-resizer-dot"}),u.createElement("span",{className:"ps-row-resizer-dot"})))}function Tp({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 u.createElement("div",{className:"ps-mobile-nav"},n.map(i=>u.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 Cp({controller:t}){const e=K(t,p=>p.ui.themeId),s=ze(e),n=K(t,p=>({rawModal:p.ui.modal,themePicker:Ru(p),modelPicker:ru(p),reasoningEffortPicker:lu(p),contextTierPicker:cu(p),sessionAgentPicker:au(p),sessionGroupPicker:uu(p),sessionGroupName:fu(p),artifactPicker:yu(p),logFilter:mu(p),filesFilter:gu(p),historyFormat:_u(p),renameSession:du(p),sessionOwnerFilter:hu(p),artifactUpload:pu(p),confirm:Lu(p),logsFilter:p.logs.filter,filesFilterState:p.files.filter,historyFormatState:p.executionHistory?.format||"pretty"}),Te),i=n.rawModal,o=u.useRef(null),r=u.useRef(null),a=u.useRef(null);if(u.useEffect(()=>{if(i?.type!=="renameSession"||!n.renameSession)return;const p=o.current;if(p){if(document.activeElement!==p)try{p.focus({preventScroll:!0})}catch{p.focus()}p.setSelectionRange(n.renameSession.cursorIndex,n.renameSession.cursorIndex)}},[i?.type,n.renameSession?.cursorIndex,n.renameSession?.value]),u.useEffect(()=>{if(i?.type!=="sessionGroupName"||!n.sessionGroupName)return;const p=r.current;if(p){if(document.activeElement!==p)try{p.focus({preventScroll:!0})}catch{p.focus()}p.setSelectionRange(n.sessionGroupName.cursorIndex,n.sessionGroupName.cursorIndex)}},[i?.type,n.sessionGroupName?.cursorIndex,n.sessionGroupName?.value]),u.useEffect(()=>{if(!i||!["themePicker","modelPicker","reasoningEffortPicker","contextTierPicker","sessionAgentPicker","sessionGroupPicker","artifactPicker","sessionOwnerFilter","logFilter","filesFilter","historyFormat"].includes(i.type))return;const p=a.current;if(!p)return;const h=p.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.contextTierPicker?.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(x.CLOSE_MODAL).catch(()=>{}),c=(p,h="Apply")=>{const m=Array.isArray(p.rows)?p.rows:[],g=Array.isArray(p.rowItemIndexes)?p.rowItemIndexes:null,b=i.type==="modelPicker"||i.type==="reasoningEffortPicker"||i.type==="contextTierPicker"||i.type==="sessionAgentPicker",S=g&&g.length===m.length?m.map((w,I)=>{const A=g[I],C=Array.isArray(w)?w:pe([w])[0]?.runs||[{text:w?.text||"",color:w?.color}];if(A==null||A<0)return u.createElement("div",{key:`row:${I}`,className:"ps-line ps-modal-list-heading-line"},u.createElement(me,{runs:C,theme:s}));const v=i.items?.[A];return u.createElement("button",{key:v?.id||`row:${I}`,type:"button",className:`ps-list-button ps-modal-list-button${A===i.selectedIndex?" is-selected":""}${b?" is-hanging":""}${v?.disabled?" is-disabled":""}`,onClick:()=>t.dispatch({type:"ui/modalSelection",index:A})},u.createElement("div",{className:"ps-line ps-modal-list-line"},u.createElement(me,{runs:C,theme:s})))}):(i.items||[]).map((w,I)=>u.createElement("button",{key:w.id||I,type:"button",className:`ps-list-button ps-modal-list-button${I===i.selectedIndex?" is-selected":""}${b?" is-hanging":""}${w?.disabled?" is-disabled":""}`,onClick:()=>t.dispatch({type:"ui/modalSelection",index:I})},u.createElement("div",{className:"ps-line ps-modal-list-line"},u.createElement(me,{runs:Array.isArray(m?.[I])?m[I]:pe([m?.[I]])[0]?.runs||[{text:m?.[I]?.text||"",color:m?.[I]?.color}],theme:s}))));return u.createElement("div",{className:"ps-modal-backdrop",onClick:l},u.createElement("div",{className:`ps-modal${i.type==="themePicker"?" is-theme-picker":""}`,onClick:w=>w.stopPropagation()},u.createElement("div",{className:"ps-modal-header"},u.createElement("div",{className:"ps-modal-title"},p.title),u.createElement("button",{type:"button",className:"ps-modal-close",onClick:l},"Close")),u.createElement("div",{className:"ps-modal-grid"},u.createElement("div",{ref:a,className:"ps-modal-list"},S),u.createElement("div",{className:"ps-modal-details"},u.createElement("div",{className:"ps-modal-details-title"},p.detailsTitle||"Details"),pe(p.detailsLines||[]).map((w,I)=>u.createElement(fe,{key:`detail:${I}`,line:w,theme:s,className:"ps-modal-detail-line"})))),u.createElement("div",{className:"ps-modal-footer"},u.createElement("button",{type:"button",className:"ps-modal-button",onClick:l},"Cancel"),u.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(x.MODAL_CONFIRM).catch(()=>{})},h))))};if(i.type==="confirm"&&n.confirm){const p=!!i.alert,h=!p&&i.action==="deleteSession";return u.createElement("div",{className:"ps-modal-backdrop",onClick:l},u.createElement("div",{className:"ps-modal is-narrow",onClick:m=>m.stopPropagation()},u.createElement("div",{className:"ps-modal-header"},u.createElement("div",{className:"ps-modal-title"},n.confirm.title),u.createElement("button",{type:"button",className:"ps-modal-close",onClick:l},"Close")),u.createElement("div",{className:"ps-modal-body",style:{padding:"16px 20px"}},u.createElement("p",{style:{color:"#94a3b8",margin:0}},n.confirm.message)),u.createElement("div",{className:"ps-modal-footer"},p?null:u.createElement("button",{type:"button",className:"ps-modal-button",onClick:l},"Cancel"),u.createElement("button",{type:"button",className:`ps-modal-button ${h?"is-danger":"is-primary"}`,onClick:()=>t.handleCommand(x.MODAL_CONFIRM).catch(()=>{})},n.confirm.confirmLabel))))}if(i.type==="themePicker"&&n.themePicker)return c(n.themePicker,"Apply Theme");const d=i.sessionOptions?.mode==="switchModel"?"Switch Model":"Create Session";if(i.type==="modelPicker"&&n.modelPicker)return c(n.modelPicker,d);if(i.type==="reasoningEffortPicker"&&n.reasoningEffortPicker)return c(n.reasoningEffortPicker,d);if(i.type==="contextTierPicker"&&n.contextTierPicker)return c(n.contextTierPicker,d);if(i.type==="sessionAgentPicker"&&n.sessionAgentPicker)return c(n.sessionAgentPicker,"Create Session");if(i.type==="sessionGroupPicker"&&n.sessionGroupPicker)return c(n.sessionGroupPicker,"Move");if(i.type==="artifactPicker"&&n.artifactPicker)return c(n.artifactPicker,n.artifactPicker.confirmLabel||"Open / Download");if(i.type==="sessionOwnerFilter"&&n.sessionOwnerFilter){const p=n.sessionOwnerFilter,h=Array.isArray(p.rows)?p.rows:[];return u.createElement("div",{className:"ps-modal-backdrop",onClick:l},u.createElement("div",{className:"ps-modal",onClick:m=>m.stopPropagation()},u.createElement("div",{className:"ps-modal-header"},u.createElement("div",{className:"ps-modal-title"},p.title),u.createElement("button",{type:"button",className:"ps-modal-close",onClick:l},"Close")),u.createElement("div",{className:"ps-modal-grid"},u.createElement("div",{ref:a,className:"ps-modal-list"},(i.items||[]).map((m,g)=>u.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)},u.createElement("div",{className:"ps-line ps-modal-list-line"},u.createElement(me,{runs:Array.isArray(h?.[g])?h[g]:pe([h?.[g]])[0]?.runs||[{text:h?.[g]?.text||"",color:h?.[g]?.color}],theme:s}))))),u.createElement("div",{className:"ps-modal-details"},u.createElement("div",{className:"ps-modal-details-title"},p.detailsTitle||"Details"),pe(p.detailsLines||[]).map((m,g)=>u.createElement(fe,{key:`detail:${g}`,line:m,theme:s,className:"ps-modal-detail-line"})))),u.createElement("div",{className:"ps-modal-footer"},u.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:l},"Done"))))}if(i.type==="renameSession"&&n.renameSession)return u.createElement("div",{className:"ps-modal-backdrop",onClick:l},u.createElement("div",{className:"ps-modal is-narrow",onClick:p=>p.stopPropagation()},u.createElement("div",{className:"ps-modal-header"},u.createElement("div",{className:"ps-modal-title"},n.renameSession.title),u.createElement("button",{type:"button",className:"ps-modal-close",onClick:l},"Close")),u.createElement("input",{ref:o,className:"ps-modal-input",value:n.renameSession.value,placeholder:n.renameSession.placeholder,onChange:p=>t.setRenameSessionValue(p.currentTarget.value,p.currentTarget.selectionStart??p.currentTarget.value.length),onKeyDown:p=>{p.key==="Enter"&&(p.preventDefault(),t.handleCommand(x.MODAL_CONFIRM).catch(()=>{}))},autoFocus:!0}),u.createElement("div",{className:"ps-modal-details"},pe(n.renameSession.helpLines||[]).map((p,h)=>u.createElement(fe,{key:`help:${h}`,line:p,theme:s,className:"ps-modal-detail-line"}))),u.createElement("div",{className:"ps-modal-footer"},u.createElement("button",{type:"button",className:"ps-modal-button",onClick:l},"Cancel"),u.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(x.MODAL_CONFIRM).catch(()=>{})},"Save"))));if(i.type==="sessionGroupName"&&n.sessionGroupName)return u.createElement("div",{className:"ps-modal-backdrop",onClick:l},u.createElement("div",{className:"ps-modal is-narrow",onClick:p=>p.stopPropagation()},u.createElement("div",{className:"ps-modal-header"},u.createElement("div",{className:"ps-modal-title"},n.sessionGroupName.title),u.createElement("button",{type:"button",className:"ps-modal-close",onClick:l},"Close")),u.createElement("input",{ref:r,className:"ps-modal-input",value:n.sessionGroupName.value,placeholder:n.sessionGroupName.placeholder,onChange:p=>t.setSessionGroupNameValue(p.currentTarget.value,p.currentTarget.selectionStart??p.currentTarget.value.length),onKeyDown:p=>{p.key==="Enter"&&(p.preventDefault(),t.handleCommand(x.MODAL_CONFIRM).catch(()=>{}))},autoFocus:!0}),u.createElement("div",{className:"ps-modal-details"},pe(n.sessionGroupName.helpLines||[]).map((p,h)=>u.createElement(fe,{key:`help:${h}`,line:p,theme:s,className:"ps-modal-detail-line"}))),u.createElement("div",{className:"ps-modal-footer"},u.createElement("button",{type:"button",className:"ps-modal-button",onClick:l},"Cancel"),u.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(x.MODAL_CONFIRM).catch(()=>{})},"Create and Move"))));if(i.type==="terminatePicker"){const p=Number(i.bulkCount)>1,h=!!i.systemRestart,m=String(i.sessionTitle||"").trim()||"this session",g=Number(i.bulkCount)||0,b=p?`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.`,S=w=>()=>{t.pickTerminateAction(w).catch(()=>{})};return u.createElement("div",{className:"ps-modal-backdrop",onClick:l},u.createElement("div",{className:"ps-modal is-narrow",onClick:w=>w.stopPropagation()},u.createElement("div",{className:"ps-modal-header"},u.createElement("div",{className:"ps-modal-title"},i.title||"Terminate session"),u.createElement("button",{type:"button",className:"ps-modal-close",onClick:l},"Close")),u.createElement("div",{className:"ps-modal-body",style:{padding:"12px 16px 4px"}},u.createElement("p",{style:{color:"#94a3b8",margin:0}},b)),u.createElement("div",{className:"ps-modal-body",style:{padding:"10px 16px 16px",display:"flex",flexDirection:"column",gap:8}},u.createElement("button",{type:"button",className:"ps-modal-button is-primary",style:{width:"100%",justifyContent:"flex-start"},onClick:S("complete")},p?`Mark ${g} Completed`:h?"Complete & Restart":"Mark Completed"),u.createElement("button",{type:"button",className:"ps-modal-button",style:{width:"100%",justifyContent:"flex-start"},onClick:S("cancel")},p?`Cancel ${g} Sessions`:h?"Terminate & Restart":"Cancel Session"),u.createElement("button",{type:"button",className:"ps-modal-button is-danger",style:{width:"100%",justifyContent:"flex-start"},onClick:S("delete")},p?`Hard Delete ${g} Sessions`:h?"Hard Delete & Restart":"Delete Session")),u.createElement("div",{className:"ps-modal-footer"},u.createElement("button",{type:"button",className:"ps-modal-button",onClick:l},"Close"))))}if(i.type==="artifactUpload"&&n.artifactUpload)return u.createElement("div",{className:"ps-modal-backdrop",onClick:l},u.createElement("div",{className:"ps-modal is-narrow",onClick:p=>p.stopPropagation()},u.createElement("div",{className:"ps-modal-header"},u.createElement("div",{className:"ps-modal-title"},n.artifactUpload.title),u.createElement("button",{type:"button",className:"ps-modal-close",onClick:l},"Close")),u.createElement("input",{className:"ps-modal-input",value:n.artifactUpload.value,placeholder:n.artifactUpload.placeholder,onChange:p=>t.setArtifactUploadValue(p.currentTarget.value,p.currentTarget.selectionStart||p.currentTarget.value.length),autoFocus:!0}),u.createElement("div",{className:"ps-modal-details"},pe(n.artifactUpload.helpLines||[]).map((p,h)=>u.createElement(fe,{key:`help:${h}`,line:p,theme:s,className:"ps-modal-detail-line"}))),u.createElement("div",{className:"ps-modal-footer"},u.createElement("button",{type:"button",className:"ps-modal-button",onClick:l},"Cancel"),u.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(x.MODAL_CONFIRM).catch(()=>{})},"Attach"))));const f=i.type==="logFilter"?n.logFilter:i.type==="filesFilter"?n.filesFilter:i.type==="historyFormat"?n.historyFormat:null;return f?u.createElement("div",{className:"ps-modal-backdrop",onClick:l},u.createElement("div",{className:"ps-modal is-wide",onClick:p=>p.stopPropagation()},u.createElement("div",{className:"ps-modal-header"},u.createElement("div",{className:"ps-modal-title"},f.title),u.createElement("button",{type:"button",className:"ps-modal-close",onClick:l},"Close")),u.createElement("div",{className:"ps-filter-grid"},(i.items||[]).map((p,h)=>{const m=i.type==="filesFilter"?n.filesFilterState?.[p.id]||p.options?.[0]?.id:i.type==="historyFormat"?n.historyFormatState:n.logsFilter?.[p.id]||p.options?.[0]?.id;return u.createElement("div",{key:p.id||h,className:"ps-filter-column"},u.createElement("div",{className:"ps-filter-title"},p.label),(p.options||[]).map(g=>u.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:{[p.id]:g.id}}),t.ensureFilesForScope(g.id).catch(()=>{})):t.dispatch({type:"logs/filter",filter:{[p.id]:g.id}})}},g.label)))})),u.createElement("div",{className:"ps-modal-footer"},u.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:l},"Done")))):null}function kp(t,e){u.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=Rn(t),l=t.getState().ui.inspectorTab,c=t.getState().ui.focusRegion,d=!n.metaKey&&!n.ctrlKey&&!n.altKey,f=!n.metaKey&&!n.ctrlKey&&!n.altKey&&n.key==="T"&&n.shiftKey,p=!n.metaKey&&!n.ctrlKey&&!n.altKey&&n.key==="N"&&n.shiftKey,h=m=>{const g=yf(a,l,m);t.selectInspectorTab(g).catch(()=>{})};if(!o&&f){n.preventDefault(),t.handleCommand(x.OPEN_THEME_PICKER).catch(()=>{});return}if(!o&&p){n.preventDefault(),t.handleCommand(x.OPEN_MODEL_PICKER).catch(()=>{});return}if(r&&!o){if(n.key==="Escape"||r.type==="confirm"&&n.key==="n"){n.preventDefault(),t.handleCommand(x.CLOSE_MODAL).catch(()=>{});return}if(n.key==="Enter"||r.type==="confirm"&&n.key==="y"){n.preventDefault(),t.handleCommand(x.MODAL_CONFIRM).catch(()=>{});return}if(n.key==="Tab"&&n.shiftKey){n.preventDefault(),t.handleCommand(x.MODAL_PANE_PREV).catch(()=>{});return}if(n.key==="Tab"){n.preventDefault(),t.handleCommand(x.MODAL_PANE_NEXT).catch(()=>{});return}if(n.key==="ArrowUp"||n.key==="k"){n.preventDefault(),t.handleCommand(x.MODAL_PREV).catch(()=>{});return}(n.key==="ArrowDown"||n.key==="j")&&(n.preventDefault(),t.handleCommand(x.MODAL_NEXT).catch(()=>{}));return}if(!o){if(n.key==="r"&&d&&c!=="prompt"){n.preventDefault(),t.handleCommand(x.REFRESH).catch(()=>{});return}if(c==="chat"&&n.key==="s"&&d){n.preventDefault(),t.handleCommand(x.TOGGLE_CHAT_VIEW).catch(()=>{});return}if(n.key==="n"&&d){n.preventDefault(),t.handleCommand(x.NEW_SESSION).catch(()=>{});return}if(c==="inspector"&&l==="files"&&(n.key==="u"&&d||(n.ctrlKey||n.metaKey)&&n.key.toLowerCase()==="a")){n.preventDefault(),t.handleCommand(x.OPEN_ARTIFACT_UPLOAD).catch(()=>{});return}if(c==="inspector"&&l==="files"&&n.key==="a"&&d){n.preventDefault(),t.handleCommand(x.DOWNLOAD_SELECTED_FILE).catch(()=>{});return}if(c==="inspector"&&l==="files"&&n.key==="x"&&d){n.preventDefault(),t.handleCommand(x.DELETE_SELECTED_FILE).catch(()=>{});return}if(c==="inspector"&&l==="files"&&n.key==="o"&&d){n.preventDefault(),t.handleCommand(x.OPEN_SELECTED_FILE).catch(()=>{});return}if(c==="inspector"&&l==="files"&&n.key==="f"&&d){n.preventDefault(),t.handleCommand(x.OPEN_FILES_FILTER).catch(()=>{});return}if(c==="inspector"&&l==="stats"&&n.key==="f"&&d){n.preventDefault(),t.handleCommand(x.TOGGLE_STATS_VIEW).catch(()=>{});return}if(c==="inspector"&&l==="files"&&n.key==="v"&&d){n.preventDefault(),t.handleCommand(x.TOGGLE_FILE_PREVIEW_FULLSCREEN).catch(()=>{});return}if(c==="inspector"&&l==="logs"&&n.key==="t"&&d){n.preventDefault(),t.handleCommand(x.TOGGLE_LOG_TAIL).catch(()=>{});return}if(c==="inspector"&&l==="logs"&&n.key==="f"&&d){n.preventDefault(),t.handleCommand(x.OPEN_LOG_FILTER).catch(()=>{});return}if(c==="inspector"&&l==="history"&&n.key==="f"&&d){n.preventDefault(),t.handleCommand(x.OPEN_HISTORY_FORMAT).catch(()=>{});return}if(c==="inspector"&&l==="history"&&n.key==="r"&&d){n.preventDefault(),t.handleCommand(x.REFRESH_EXECUTION_HISTORY).catch(()=>{});return}if(c==="inspector"&&l==="history"&&n.key==="a"&&d){n.preventDefault(),t.handleCommand(x.EXPORT_EXECUTION_HISTORY).catch(()=>{});return}if(n.key==="a"&&d){n.preventDefault(),t.handleCommand(x.OPEN_ARTIFACT_PICKER).catch(()=>{});return}if(n.key==="p"&&d){n.preventDefault(),t.handleCommand(x.FOCUS_PROMPT).catch(()=>{});return}if(n.key==="c"&&d){n.preventDefault(),t.handleCommand(x.CANCEL_SESSION).catch(()=>{});return}if(n.key==="d"&&d){n.preventDefault(),t.handleCommand(x.DONE_SESSION).catch(()=>{});return}if(n.key==="D"&&n.shiftKey&&!n.metaKey&&!n.ctrlKey&&!n.altKey){n.preventDefault(),t.handleCommand(x.DELETE_SESSION).catch(()=>{});return}if(n.key==="m"&&d&&c==="inspector"){n.preventDefault(),h(1);return}if(n.key==="["&&d){n.preventDefault(),t.handleCommand(x.GROW_LEFT_PANE).catch(()=>{});return}if(n.key==="]"&&d){n.preventDefault(),t.handleCommand(x.GROW_RIGHT_PANE).catch(()=>{});return}if(n.key==="{"&&d){n.preventDefault(),t.handleCommand(x.SHRINK_SESSION_PANE).catch(()=>{});return}if(n.key==="}"&&d){n.preventDefault(),t.handleCommand(x.GROW_SESSION_PANE).catch(()=>{});return}if(c==="inspector"&&n.key==="ArrowLeft"){n.preventDefault(),h(-1);return}if(c==="inspector"&&n.key==="ArrowRight"){n.preventDefault(),h(1);return}if(c==="sessions"&&(n.key==="ArrowUp"||n.key==="k")){n.preventDefault(),t.handleCommand(x.MOVE_SESSION_UP).catch(()=>{});return}if(c==="sessions"&&(n.key==="ArrowDown"||n.key==="j")){n.preventDefault(),t.handleCommand(x.MOVE_SESSION_DOWN).catch(()=>{});return}if(c==="sessions"&&n.ctrlKey&&n.key.toLowerCase()==="g"&&!n.metaKey&&!n.altKey){n.preventDefault(),t.handleCommand(x.OPEN_MOVE_TO_GROUP).catch(()=>{});return}if(c==="sessions"&&(n.key==="PageUp"||n.ctrlKey&&n.key.toLowerCase()==="u")){n.preventDefault(),t.handleCommand(x.PAGE_UP).catch(()=>{});return}if(c==="sessions"&&(n.key==="PageDown"||n.ctrlKey&&n.key.toLowerCase()==="d")){n.preventDefault(),t.handleCommand(x.PAGE_DOWN).catch(()=>{});return}if(c==="sessions"&&n.key==="t"&&d){n.preventDefault(),t.handleCommand(x.OPEN_RENAME_SESSION).catch(()=>{});return}if(!e&&(n.key==="PageUp"||n.ctrlKey&&n.key.toLowerCase()==="u")){n.preventDefault(),t.handleCommand(x.PAGE_UP).catch(()=>{});return}if(!e&&(n.key==="PageDown"||n.ctrlKey&&n.key.toLowerCase()==="d")){n.preventDefault(),t.handleCommand(x.PAGE_DOWN).catch(()=>{});return}if(!e&&n.key==="g"&&d){n.preventDefault(),t.handleCommand(x.SCROLL_TOP).catch(()=>{});return}if(!e&&n.key==="G"&&n.shiftKey&&!n.metaKey&&!n.ctrlKey&&!n.altKey){n.preventDefault(),t.handleCommand(x.SCROLL_BOTTOM).catch(()=>{});return}if(c!=="prompt"&&n.key==="h"&&d){n.preventDefault(),t.handleCommand(x.FOCUS_LEFT).catch(()=>{});return}if(c!=="prompt"&&n.key==="l"&&d){n.preventDefault(),t.handleCommand(x.FOCUS_RIGHT).catch(()=>{});return}if(!e&&(n.key==="ArrowUp"||n.key==="k")){n.preventDefault(),t.handleCommand(x.SCROLL_UP).catch(()=>{});return}if(!e&&(n.key==="ArrowDown"||n.key==="j")){n.preventDefault(),t.handleCommand(x.SCROLL_DOWN).catch(()=>{});return}!e&&n.key==="Escape"&&(n.preventDefault(),t.handleCommand(x.FOCUS_SESSIONS).catch(()=>{}))}};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[t,e])}function Mp(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 Pp({controller:t}){const e=K(t,Pc,Te),s=u.useRef(null);u.useEffect(()=>{if(e.ghcpKey.editing){const f=window.requestAnimationFrame(()=>{s.current&&s.current.focus()});return()=>window.cancelAnimationFrame(f)}},[e.ghcpKey.editing]);const n=u.useCallback(()=>{t.closeAdminConsole()},[t]),i=u.useCallback(()=>{t.refreshAdminProfile().catch(()=>{})},[t]),o=u.useCallback(()=>{t.beginAdminEditGhcpKey()},[t]),r=u.useCallback(()=>{t.cancelAdminEditGhcpKey()},[t]),a=u.useCallback(()=>{t.clearAdminGhcpKey().catch(()=>{})},[t]),l=u.useCallback(f=>{f.preventDefault(),t.saveAdminGhcpKey().catch(()=>{})},[t]),c=u.useCallback(f=>{t.setAdminGhcpKeyDraft(f.target.value)},[t]),d=Mp(e.principal);return u.createElement("div",{className:"ps-admin-console"},u.createElement("header",{className:"ps-admin-console__header"},u.createElement("h2",null,"Admin Console"),u.createElement("button",{type:"button",className:"ps-mini-button",onClick:n},"Close")),u.createElement("section",{className:"ps-admin-console__identity"},u.createElement("dl",null,u.createElement("dt",null,"Signed in as"),u.createElement("dd",null,d))),e.loadError?u.createElement("div",{className:"ps-admin-console__error",role:"alert"},e.loadError):null,u.createElement("section",{className:"ps-admin-console__section"},u.createElement("h3",null,"GitHub Copilot key"),e.ghcpKey.storeAsSystem?u.createElement("p",{className:"ps-admin-console__hint"},"System-wide key for platform-managed (ownerless) system ","sessions — agent tuners, repo cache managers, and other ","sessions with no owner resolve this key for GitHub Copilot ","models. Clearing it reverts them to the worker default."):u.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."),e.isAdmin&&e.systemGhcpKey.supported?u.createElement("label",{className:"ps-admin-console__system-toggle"},u.createElement("input",{type:"checkbox",checked:e.ghcpKey.storeAsSystem,disabled:e.ghcpKey.saving,onChange:f=>t.setAdminGhcpKeyStoreAsSystem(f.target.checked)}),"Store as System key"):null,u.createElement("p",{className:`ps-admin-console__status${e.ghcpKey.error?" is-error":""}`},e.ghcpKey.error||e.ghcpKey.statusText),e.ghcpKey.editing?u.createElement("form",{className:"ps-admin-console__form",onSubmit:l},u.createElement("input",{ref:s,type:"password",autoComplete:"off",spellCheck:!1,value:e.ghcpKey.draft,disabled:e.ghcpKey.saving,placeholder:"Paste GitHub Copilot key",onChange:c}),u.createElement("div",{className:"ps-admin-console__actions"},u.createElement("button",{type:"submit",className:"ps-primary-button",disabled:e.ghcpKey.saving},e.ghcpKey.saving?"Saving...":"Save"),u.createElement("button",{type:"button",className:"ps-mini-button",onClick:r,disabled:e.ghcpKey.saving},"Cancel"))):u.createElement("div",{className:"ps-admin-console__actions"},u.createElement("button",{type:"button",className:"ps-primary-button",onClick:o},e.ghcpKey.targetConfigured?e.ghcpKey.storeAsSystem?"Replace System key":"Replace key":e.ghcpKey.storeAsSystem?"Set System key":"Set key"),e.ghcpKey.targetConfigured?u.createElement("button",{type:"button",className:"ps-mini-button",onClick:a},e.ghcpKey.storeAsSystem?"Clear System key":"Clear key"):null,u.createElement("button",{type:"button",className:"ps-mini-button",onClick:i},e.loading?"Refreshing...":"Refresh"))))}function Op({transport:t,mode:e="remote",branding:s=null}={}){Cf();const n=ed(Zu,Il({mode:e,branding:s}));return new Vd({store:n,transport:t})}function _p({controller:t}){const e=u.useRef(null),s=u.useRef(null),n=ro(e),i=ro(s),o=Lf(n);u.useEffect(()=>{const y=()=>{const _=document.createElement("span");_.style.cssText="position:absolute;visibility:hidden;white-space:pre;";const $=document.querySelector(".ps-scroll-panel .ps-line")||document.querySelector(".ps-line");$&&(_.style.font=window.getComputedStyle($).font),_.textContent="0".repeat(100),($?.parentElement||document.body).appendChild(_);const B=_.getBoundingClientRect().width/100||8;_.remove(),t.dispatch({type:"ui/viewport",width:Math.floor(window.innerWidth/B),height:Math.floor(window.innerHeight/De)})};y();let k;const N=()=>{clearTimeout(k),k=setTimeout(y,150)};return window.addEventListener("resize",N),window.addEventListener("orientationchange",N),()=>{clearTimeout(k),window.removeEventListener("resize",N),window.removeEventListener("orientationchange",N)}},[t]);const[r,a]=u.useState(!1),[l,c]=u.useState(null),d=K(t,y=>({themeId:y.ui.themeId,ownerFilter:y.sessions.ownerFilter,pinnedIds:y.sessions.pinnedIds,collapsedSessionIds:y.sessions.collapsedIds,activeSessionId:y.sessions.activeSessionId||null,promptRows:_r(y),chatViewMode:y.ui.chatViewMode||"transcript",activeSessionIsGroup:!!(y.sessions.activeSessionId&&y.sessions.byId[y.sessions.activeSessionId]?.isGroup),paneAdjust:y.ui.layout?.paneAdjust??0,sessionPaneAdjust:y.ui.layout?.sessionPaneAdjust??0,portalSessionColumnAdjust:y.ui.layout?.portalSessionColumnAdjust??0,activityPaneAdjust:y.ui.layout?.activityPaneAdjust??0,focusRegion:y.ui.focusRegion,inspectorTab:y.ui.inspectorTab,filesFullscreen:!!y.files.fullscreen,adminVisible:!!y.admin?.visible}),Te),f=u.useRef(!1),p=u.useRef(null),h=u.useRef(null),m=u.useRef(null),g=u.useRef(!1),b=u.useRef(!1),S=u.useRef(null),w=u.useRef(null),[I,A]=u.useState("workspace"),C=(n.width||window.innerWidth||0)<of,T=d.activeSessionIsGroup||d.chatViewMode==="summary"?0:d.promptRows;kp(t,C),u.useEffect(()=>{t.setViewport(o)},[t,o.height,o.width]),u.useEffect(()=>{let y=!0;f.current=!1,p.current=null,S.current=null,w.current=no(t.getState()),h.current&&(clearTimeout(h.current),h.current=null),m.current&&(clearInterval(m.current),m.current=null),g.current=!1,b.current=!1;const k=t.transport;if(typeof k?.getCurrentUserProfile!="function"||typeof k?.setCurrentUserProfileSettings!="function")return f.current=!0,()=>{y=!1};const N=async()=>{if(!(!y||g.current)){g.current=!0;try{const _=await k.getCurrentUserProfile();if(!y)return;w.current=no(t.getState());const $=Mf(_?.profileSettings,w.current),B=JSON.stringify($),V=Bs(t.getState()),ae=JSON.stringify(V),te=f.current&&p.current!=null&&ae!==p.current;!(h.current||b.current||te)&&S.current!==B&&(t.dispatch({type:"profileSettings/apply",settings:$}),S.current=B);const ms=Bs(t.getState());p.current=JSON.stringify(ms),f.current=!0}catch{if(!y)return;f.current=!0}finally{g.current=!1}}};return N().catch(()=>{}),m.current=setInterval(()=>{N().catch(()=>{})},df),()=>{y=!1,h.current&&(clearTimeout(h.current),h.current=null),m.current&&(clearInterval(m.current),m.current=null),g.current=!1}},[t]),u.useEffect(()=>{if(!f.current)return;const y=Bs(d),k=JSON.stringify(y);p.current!==k&&(p.current=k,h.current&&clearTimeout(h.current),h.current=setTimeout(()=>{h.current=null,b.current=!0,Pf(t,y).catch(()=>{}).finally(()=>{b.current=!1})},400))},[t,d.activeSessionId,d.activityPaneAdjust,d.chatViewMode,d.collapsedSessionIds,d.ownerFilter,d.paneAdjust,d.pinnedIds,d.portalSessionColumnAdjust,d.sessionPaneAdjust,d.themeId]),u.useEffect(()=>{Rf(d.themeId)},[d.themeId]),u.useEffect(()=>{C&&d.focusRegion!=="prompt"&&A(d.focusRegion==="activity"?"activity":d.focusRegion==="inspector"?"inspector":"workspace")},[C,d.focusRegion]),u.useEffect(()=>{const y=Rn(t);!y.includes(d.inspectorTab)&&y.length>0&&t.selectInspectorTab(y[0]).catch(()=>{})},[t,d.inspectorTab]);const M=u.useMemo(()=>Mt(o,d.paneAdjust,T,d.sessionPaneAdjust,d.activityPaneAdjust),[o,d.activityPaneAdjust,d.paneAdjust,T,d.sessionPaneAdjust]),O=d.filesFullscreen&&d.inspectorTab==="files";u.useEffect(()=>{!O||!r||(a(!1),c(null))},[r,O]);const L=u.useCallback(()=>{a(y=>{const k=!y;return k?t.setFocus("chat"):c(null),k})},[t]),H=u.useCallback(y=>{c(k=>{const N=k===y?null:y;return t.setFocus(N||"chat"),N})},[t]),F=Math.max(0,(n.width||0)*.68),q=i.width||F,Y=Nf(q,d.portalSessionColumnAdjust),U=Of(Y),W=U==="hidden"?"0px":`clamp(0px, calc(${_n*100}% + ${Number(d.portalSessionColumnAdjust)||0}px), max(0px, calc(100% - 14rem - 32px)))`,Z=u.createElement("div",{className:"ps-workspace-grid",style:{gridTemplateColumns:`minmax(0, ${M.leftWidth}fr) 16px minmax(0, ${M.rightWidth}fr)`}},u.createElement("div",{ref:s,className:`ps-workspace-main-grid is-session-${U}`,style:{gridTemplateColumns:`${W} 16px minmax(14rem, 1fr)`}},U!=="hidden"?u.createElement("div",{className:"ps-workspace-pane-slot",style:{gridColumn:"1"}},u.createElement(Ln,{controller:t,structuredRows:!0})):null,u.createElement("div",{style:{gridColumn:"2",minWidth:0,display:"flex"}},u.createElement(Ep,{controller:t,portalSessionColumnAdjust:d.portalSessionColumnAdjust})),u.createElement("div",{className:"ps-workspace-pane-slot",style:{gridColumn:"3"}},u.createElement(Fn,{controller:t}))),u.createElement(vp,{controller:t,paneAdjust:d.paneAdjust}),u.createElement("div",{className:"ps-workspace-column",style:{gridTemplateRows:`${M.inspectorPaneHeight}fr 16px ${M.activityPaneHeight}fr`}},u.createElement("div",{className:"ps-workspace-pane-slot",style:{gridRow:"1"}},M.inspectorHidden?null:u.createElement(Ct,{controller:t,mobile:!1})),u.createElement("div",{style:{gridRow:"2",minHeight:0,display:"flex",flexDirection:"column"}},u.createElement(Ap,{controller:t,activityPaneAdjust:d.activityPaneAdjust})),u.createElement("div",{className:"ps-workspace-pane-slot",style:{gridRow:"3"}},M.activityHidden?null:u.createElement(sn,{controller:t})))),Se=u.createElement(bp,{controller:t,openPane:l,onTogglePane:H,onExitFocus:L,mobile:C}),ie=u.createElement("div",{className:"ps-workspace-full"},u.createElement(Ct,{controller:t,mobile:!1}));let R=null;return O?R=u.createElement("div",{className:"ps-mobile-pane-fill"},u.createElement(Ct,{controller:t,mobile:!0})):I==="inspector"?R=u.createElement("div",{className:"ps-mobile-pane-fill"},u.createElement(Ct,{controller:t,mobile:!0})):I==="activity"?R=u.createElement("div",{className:"ps-mobile-pane-fill"},u.createElement(sn,{controller:t})):R=u.createElement(gp,{controller:t}),u.createElement("div",{ref:e,className:"ps-web-shell"},C&&(r||I==="inspector"||I==="activity")?null:u.createElement(xp,{controller:t,mobile:C,chatFocusMode:r,onToggleChatFocus:L,chatFocusDisabled:O}),u.createElement("div",{className:"ps-workspace"},d.adminVisible?u.createElement(Pp,{controller:t}):O?ie:r?Se:C?R:Z),C&&!r?u.createElement(Tp,{activePane:I,setActivePane:A,controller:t}):null,u.createElement(Cp,{controller:t}))}export{_p as P,u as R,Qr as a,Nc as b,Op as c,go as r,Np as s};