pilotswarm 0.5.13 → 0.5.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -0
- package/mcp/README.md +12 -0
- package/mcp/dist/src/context.d.ts +13 -0
- package/mcp/dist/src/context.d.ts.map +1 -1
- package/mcp/dist/src/context.js +20 -0
- package/mcp/dist/src/context.js.map +1 -1
- package/mcp/dist/src/tools/capabilities.d.ts +3 -0
- package/mcp/dist/src/tools/capabilities.d.ts.map +1 -1
- package/mcp/dist/src/tools/capabilities.js +8 -0
- package/mcp/dist/src/tools/capabilities.js.map +1 -1
- package/mcp/dist/src/tools/sessions.d.ts.map +1 -1
- package/mcp/dist/src/tools/sessions.js +114 -0
- package/mcp/dist/src/tools/sessions.js.map +1 -1
- package/package.json +3 -2
- package/tui/src/app.js +19 -2
- package/tui/src/auth/cli.js +13 -0
- package/tui/src/node-sdk-transport.js +53 -8
- package/tui/tui-splash-mobile.txt +5 -7
- package/tui/tui-splash.txt +13 -9
- package/ui/core/src/commands.js +2 -0
- package/ui/core/src/controller.js +275 -6
- package/ui/core/src/history.js +19 -1
- package/ui/core/src/reducer.js +4 -0
- package/ui/core/src/selectors.js +139 -14
- package/ui/core/src/themes/helpers.js +4 -0
- package/ui/react/src/components.js +95 -6
- package/ui/react/src/web-app.js +555 -117
- package/web/api/router.js +7 -6
- package/web/api/ws.js +9 -0
- package/web/auth/index.js +5 -0
- package/web/auth/providers/dev.js +119 -0
- package/web/authz.js +142 -0
- package/web/dist/assets/index-BnxC8cNG.js +24 -0
- package/web/dist/assets/{index-oldX95Tp.css → index-Bx6KHIaj.css} +1 -1
- package/web/dist/assets/pilotswarm-NE7H63ha.js +90 -0
- package/web/dist/assets/react-l0sNRNKZ.js +1 -0
- package/web/dist/index.html +3 -4
- package/web/runtime.js +453 -9
- package/web/server.js +2 -2
- package/web/dist/assets/index-bQ2QInMX.js +0 -24
- package/web/dist/assets/pilotswarm-DRs6o-lA.js +0 -90
- package/web/dist/assets/react-C9iQPS2h.js +0 -1
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
function Sr(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var as={exports:{}},B={};var Tn;function br(){if(Tn)return B;Tn=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(b){return b===null||typeof b!="object"?null:(b=p&&b[p]||b["@@iterator"],typeof b=="function"?b:null)}var g={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},m=Object.assign,x={};function y(b,w,A){this.props=b,this.context=w,this.refs=x,this.updater=A||g}y.prototype.isReactComponent={},y.prototype.setState=function(b,w){if(typeof b!="object"&&typeof b!="function"&&b!=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,b,w,"setState")},y.prototype.forceUpdate=function(b){this.updater.enqueueForceUpdate(this,b,"forceUpdate")};function S(){}S.prototype=y.prototype;function E(b,w,A){this.props=b,this.context=w,this.refs=x,this.updater=A||g}var T=E.prototype=new S;T.constructor=E,m(T,y.prototype),T.isPureReactComponent=!0;var C=Array.isArray;function _(){}var k={H:null,A:null,T:null,S:null},R=Object.prototype.hasOwnProperty;function N(b,w,A){var M=A.ref;return{$$typeof:t,type:b,key:w,ref:M!==void 0?M:null,props:A}}function O(b,w){return N(b.type,w,b.props)}function U(b){return typeof b=="object"&&b!==null&&b.$$typeof===t}function L(b){var w={"=":"=0",":":"=2"};return"$"+b.replace(/[=:]/g,function(A){return w[A]})}var K=/\/+/g;function P(b,w){return typeof b=="object"&&b!==null&&b.key!=null?L(""+b.key):w.toString(36)}function F(b){switch(b.status){case"fulfilled":return b.value;case"rejected":throw b.reason;default:switch(typeof b.status=="string"?b.then(_,_):(b.status="pending",b.then(function(w){b.status==="pending"&&(b.status="fulfilled",b.value=w)},function(w){b.status==="pending"&&(b.status="rejected",b.reason=w)})),b.status){case"fulfilled":return b.value;case"rejected":throw b.reason}}throw b}function V(b,w,A,M,$){var H=typeof b;(H==="undefined"||H==="boolean")&&(b=null);var j=!1;if(b===null)j=!0;else switch(H){case"bigint":case"string":case"number":j=!0;break;case"object":switch(b.$$typeof){case t:case e:j=!0;break;case d:return j=b._init,V(j(b._payload),w,A,M,$)}}if(j)return $=$(b),j=M===""?"."+P(b,0):M,C($)?(A="",j!=null&&(A=j.replace(K,"$&/")+"/"),V($,w,A,"",function(rs){return rs})):$!=null&&(U($)&&($=O($,A+($.key==null||b&&b.key===$.key?"":(""+$.key).replace(K,"$&/")+"/")+j)),w.push($)),1;j=0;var re=M===""?".":M+":";if(C(b))for(var ie=0;ie<b.length;ie++)M=b[ie],H=re+P(M,ie),j+=V(M,w,A,H,$);else if(ie=h(b),typeof ie=="function")for(b=ie.call(b),ie=0;!(M=b.next()).done;)M=M.value,H=re+P(M,ie++),j+=V(M,w,A,H,$);else if(H==="object"){if(typeof b.then=="function")return V(F(b),w,A,M,$);throw w=String(b),Error("Objects are not valid as a React child (found: "+(w==="[object Object]"?"object with keys {"+Object.keys(b).join(", ")+"}":w)+"). If you meant to render a collection of children, use an array instead.")}return j}function q(b,w,A){if(b==null)return b;var M=[],$=0;return V(b,M,"","",function(H){return w.call(A,H,$++)}),M}function ne(b){if(b._status===-1){var w=b._result;w=w(),w.then(function(A){(b._status===0||b._status===-1)&&(b._status=1,b._result=A)},function(A){(b._status===0||b._status===-1)&&(b._status=2,b._result=A)}),b._status===-1&&(b._status=0,b._result=w)}if(b._status===1)return b._result.default;throw b._result}var ce=typeof reportError=="function"?reportError:function(b){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var w=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof b=="object"&&b!==null&&typeof b.message=="string"?String(b.message):String(b),error:b});if(!window.dispatchEvent(w))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",b);return}console.error(b)},ue={map:q,forEach:function(b,w,A){q(b,function(){w.apply(this,arguments)},A)},count:function(b){var w=0;return q(b,function(){w++}),w},toArray:function(b){return q(b,function(w){return w})||[]},only:function(b){if(!U(b))throw Error("React.Children.only expected to receive a single React element child.");return b}};return B.Activity=f,B.Children=ue,B.Component=y,B.Fragment=s,B.Profiler=i,B.PureComponent=E,B.StrictMode=n,B.Suspense=l,B.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=k,B.__COMPILER_RUNTIME={__proto__:null,c:function(b){return k.H.useMemoCache(b)}},B.cache=function(b){return function(){return b.apply(null,arguments)}},B.cacheSignal=function(){return null},B.cloneElement=function(b,w,A){if(b==null)throw Error("The argument must be a React element, but you passed "+b+".");var M=m({},b.props),$=b.key;if(w!=null)for(H in w.key!==void 0&&($=""+w.key),w)!R.call(w,H)||H==="key"||H==="__self"||H==="__source"||H==="ref"&&w.ref===void 0||(M[H]=w[H]);var H=arguments.length-2;if(H===1)M.children=A;else if(1<H){for(var j=Array(H),re=0;re<H;re++)j[re]=arguments[re+2];M.children=j}return N(b.type,$,M)},B.createContext=function(b){return b={$$typeof:r,_currentValue:b,_currentValue2:b,_threadCount:0,Provider:null,Consumer:null},b.Provider=b,b.Consumer={$$typeof:o,_context:b},b},B.createElement=function(b,w,A){var M,$={},H=null;if(w!=null)for(M in w.key!==void 0&&(H=""+w.key),w)R.call(w,M)&&M!=="key"&&M!=="__self"&&M!=="__source"&&($[M]=w[M]);var j=arguments.length-2;if(j===1)$.children=A;else if(1<j){for(var re=Array(j),ie=0;ie<j;ie++)re[ie]=arguments[ie+2];$.children=re}if(b&&b.defaultProps)for(M in j=b.defaultProps,j)$[M]===void 0&&($[M]=j[M]);return N(b,H,$)},B.createRef=function(){return{current:null}},B.forwardRef=function(b){return{$$typeof:a,render:b}},B.isValidElement=U,B.lazy=function(b){return{$$typeof:d,_payload:{_status:-1,_result:b},_init:ne}},B.memo=function(b,w){return{$$typeof:c,type:b,compare:w===void 0?null:w}},B.startTransition=function(b){var w=k.T,A={};k.T=A;try{var M=b(),$=k.S;$!==null&&$(A,M),typeof M=="object"&&M!==null&&typeof M.then=="function"&&M.then(_,ce)}catch(H){ce(H)}finally{w!==null&&A.types!==null&&(w.types=A.types),k.T=w}},B.unstable_useCacheRefresh=function(){return k.H.useCacheRefresh()},B.use=function(b){return k.H.use(b)},B.useActionState=function(b,w,A){return k.H.useActionState(b,w,A)},B.useCallback=function(b,w){return k.H.useCallback(b,w)},B.useContext=function(b){return k.H.useContext(b)},B.useDebugValue=function(){},B.useDeferredValue=function(b,w){return k.H.useDeferredValue(b,w)},B.useEffect=function(b,w){return k.H.useEffect(b,w)},B.useEffectEvent=function(b){return k.H.useEffectEvent(b)},B.useId=function(){return k.H.useId()},B.useImperativeHandle=function(b,w,A){return k.H.useImperativeHandle(b,w,A)},B.useInsertionEffect=function(b,w){return k.H.useInsertionEffect(b,w)},B.useLayoutEffect=function(b,w){return k.H.useLayoutEffect(b,w)},B.useMemo=function(b,w){return k.H.useMemo(b,w)},B.useOptimistic=function(b,w){return k.H.useOptimistic(b,w)},B.useReducer=function(b,w,A){return k.H.useReducer(b,w,A)},B.useRef=function(b){return k.H.useRef(b)},B.useState=function(b){return k.H.useState(b)},B.useSyncExternalStore=function(b,w,A){return k.H.useSyncExternalStore(b,w,A)},B.useTransition=function(){return k.H.useTransition()},B.version="19.2.4",B}var An;function Ki(){return An||(An=1,as.exports=br()),as.exports}var wr=Ki();const u=Sr(wr);var ls={exports:{}},oe={};var Cn;function xr(){if(Cn)return oe;Cn=1;var t=Ki();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 oe.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=n,oe.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)},oe.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()}},oe.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))},oe.prefetchDNS=function(l){typeof l=="string"&&n.d.D(l)},oe.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})}},oe.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)},oe.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})}},oe.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)},oe.requestFormReset=function(l){n.d.r(l)},oe.unstable_batchedUpdates=function(l,c){return l(c)},oe.useFormState=function(l,c,d){return r.H.useFormState(l,c,d)},oe.useFormStatus=function(){return r.H.useHostTransitionStatus()},oe.version="19.2.4",oe}var kn;function Ir(){if(kn)return ls.exports;kn=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(),ls.exports=xr(),ls.exports}const Er=u.createContext(null);function Se(){const t=u.useContext(Er);if(!t)throw new Error("useUiPlatform must be used within a UiPlatformProvider");return t}function W(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 Mn=[". ",".. ","..."],Pn=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];function zi(t,e=120){const[s,n]=u.useState(0);return u.useEffect(()=>{if(!t){n(0);return}const i=setInterval(()=>{n(o=>(o+1)%Pn.length)},e);return()=>clearInterval(i)},[t,e]),t?Pn[s]:""}function Yi(t,e=360){const[s,n]=u.useState(0);return u.useEffect(()=>{if(!t){n(0);return}const i=setInterval(()=>{n(o=>(o+1)%Mn.length)},e);return()=>clearInterval(i)},[t,e]),t?Mn[s]:""}function Qi(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 v={SESSIONS:"sessions",CHAT:"chat",INSPECTOR:"inspector",ACTIVITY:"activity",PROMPT:"prompt",ADMIN:"admin"},we=["sequence","logs","nodes","history","files","stats"],I={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 ze(t,e,s){const n=t.indexOf(e),o=((n===-1?0:n)+s+t.length)%t.length;return t[o]}function qs(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 Ms(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 vr(t){const e=qs(t);return e==null?"gray":e>=85?"red":e>=70?"yellow":"gray"}function Tr(t){if(!t||!(typeof t.tokenLimit=="number"&&t.tokenLimit>0&&typeof t.currentTokens=="number"&&t.currentTokens>=0))return null;const e=qs(t);return e==null?null:{text:`ctx ${Ms(t.currentTokens)}/${Ms(t.tokenLimit)} ${e}%`,color:vr(t)}}function Ar(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 Xi(t){return!t||typeof t!="object"?null:{...t,...t.compaction&&typeof t.compaction=="object"?{compaction:{...t.compaction}}:{}}}function Cr(t){if(t instanceof Date)return t.getTime();const e=new Date(t).getTime();return Number.isFinite(e)?e:Date.now()}function Ji(t,e,s={},n={}){if(!e)return null;const i=Xi(t)||{},o=Cr(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 kr(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 ${Ms(s.tokensRemoved)}`,color:"gray"}]:[]]}const Ps=/\{(\/?)([a-z-]+)\}/g,Mr={color:null,bold:!1,underline:!1},Bt=/artifact:\/\/([a-f0-9-]+)\/([^\s"'{}]+)/g,Nn=/session:\/\/([A-Za-z0-9-]+)/g,Pr={black:"black",red:"red",green:"green",yellow:"yellow",blue:"blue",magenta:"magenta",cyan:"cyan",white:"white",gray:"gray",grey:"gray"};function Lt(t){return{color:t.color,bold:t.bold,underline:t.underline}}function Nr(t,e,s){const n=Lt(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:Pr[i]||null,n}return n}function Ks(t){return String(t||"").replace(Ps,"")}function Zi(t){const e=[],n=String(t||"").split(`
|
|
2
|
+
`);for(const i of n){const o=[];let r=Lt(Mr),a=0,l;for(;(l=Ps.exec(i))!==null;){const[c,d,f]=l;l.index>a&&o.push({text:i.slice(a,l.index),...Lt(r)}),r=Nr(r,f,d==="/"),a=l.index+c.length}(a<i.length||o.length===0)&&o.push({text:i.slice(a),...Lt(r)}),e.push(o),Ps.lastIndex=0}return e}function Q(t){return String(t||"").slice(0,8)}function eo(t){const e=String(t||"");return e?e.includes(":")?e.split(":").slice(1).join(":"):e:""}function pe(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 bt(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 Or(t){if(t==null)return"";if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}function _r(t,e,s){const n=t.indexOf(e,s);return n>=0?n:-1}function Dt(t){return/[A-Za-z0-9_]/u.test(String(t||""))}function On(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!(Dt(i)&&Dt(n))}function Rr(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!(Dt(n)&&Dt(i))}function _n(t,e,s){let n=s;for(;n<t.length;){const i=t.indexOf(e,n);if(i<0)return-1;if(Rr(t,i,e))return i;n=i+e.length}return-1}function Lr(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 Fr(t,e,s){let n=0;for(;t.slice(s+n,s+n+e.length)===e;)n+=e.length;return n}function ft(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 Re(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 to(t){return(t||[]).map(e=>e?.text||"").join("")}function Ft(t){return ye(to(t))}function $r(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=Ct(r,i);a&&(n.push({...o,text:a}),i-=ye(a))}return n}function so(t,e){const s=Math.max(0,Number(e)||0),n=$r(t,s),i=Ft(n),o=Math.max(0,s-i);return o>0&&n.push({text:" ".repeat(o),color:null,bold:!1,underline:!1}),n}function no(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=Ct(l,c);if(!d)break;if(d.length===l.length||ye(d)<c){i.push({...a,text:d}),o+=ye(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+=ye(p),l=l.slice(p.length),r()}else i.push({...a,text:d}),o+=ye(d),l=l.slice(d.length),o>=s&&r()}}return(i.length>0||n.length===0)&&r(),n}function Br(t,e){return e?(t||[]).map(s=>String(s?.text||"").trim()?{...s,color:e}:{...s}):t}function io(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 Dr(t){const e=String(t||"");return Bt.lastIndex=0,[...e.matchAll(Bt)].map(s=>{const n=s[1],i=io(s[2]);return!n||!i?null:{sessionId:n,filename:i,uri:`artifact://${n}/${i}`}}).filter(Boolean)}function Ze(t){const e=String(t||"");if(!e)return e;Bt.lastIndex=0;const s=e.replace(Bt,(n,i,o)=>{const r=io(o);return!i||!r?n:`[artifact: ${r}](artifact://${i}/${r}) (press a to download)`});return Nn.lastIndex=0,s.replace(Nn,(n,i)=>i?`[session: ${Q(i)}](session://${i})`:n)}function zs(t=""){const e=String(t||""),s=[];let n=0;for(;n<e.length;){if(e[n]==="`"){const o=Fr(e,"`",n),r="`".repeat(o),a=_r(e,r,n+o);if(a>n+o-1){Re(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=On(e,n,o)?_n(e,o,n+2):-1;if(r>n+2){Re(s,{type:"strong",text:e.slice(n+2,r)}),n=r+2;continue}}if(e[n]==="["){const o=/^\[([^\]]+)\]\(([^)]+)\)/.exec(e.slice(n));if(o){Re(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);Re(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}=Lr(e.slice(n,o));if(r){Re(s,{type:"link",text:r,href:r}),a&&Re(s,{type:"text",text:a}),n=o;continue}}if((e[n]==="*"||e[n]==="_")&&e[n+1]!==" "&&e[n-1]!==e[n]&&On(e,n,e[n])){const o=e[n],r=_n(e,o,n+1);if(r>n+1){Re(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)}Re(s,{type:"text",text:e.slice(n,i)}),n=i}return s.length>0?s:[{type:"text",text:""}]}function Hr(t=""){return zs(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 mt(t){const e=zs(t),s=[];for(const n of e){if(n.type==="code"){ft(s,n.text,{color:"cyan"});continue}if(n.type==="strong"){ft(s,n.text,{bold:!0});continue}if(n.type==="em"){ft(s,n.text,{underline:!0});continue}if(n.type==="link"){ft(s,n.text,{color:"cyan",underline:!0,href:n.href});continue}ft(s,n.text)}return s.length>0?s:[{text:"",color:null,bold:!1,underline:!1}]}function et(t){return/^\s*\|.*\|\s*$/.test(t)||/^\s*\|?[:\- ]+\|[:\-| ]+\|?\s*$/.test(t)}function tt(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 Ht(t){return t.length>0&&t.every(e=>/^:?-{3,}:?$/.test(String(e||"").replace(/\s+/g,"")))}function ye(t){return Array.from(String(t||"")).length}function Ct(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 oo(t,e){const s=String(t||""),n=Math.max(0,e-ye(s));return s+" ".repeat(n)}function ro(t){return to(mt(t))}function Gr(t,e){const s=ro(t).replace(/\s+/g," ").trim();if(!s)return[""];const n=s.split(" "),i=[];let o="";const r=a=>{let l=a;for(;ye(l)>e;){const c=Ct(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}`;ye(c)<=e?o=c:(i.push(o),o=l)}return o&&i.push(o),i.length>0?i:[""]}function Ur(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=>ye(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=>ye(h)))))),r=Array.from({length:s},(d,f)=>Math.max(3,Math.min(Math.max(ye(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 jr(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,g)=>p[g]||"")).map(p=>p.map(h=>ro(h))),o=Ur(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((m,x)=>Gr(m,o[x])),g=Math.max(...h.map(m=>m.length));for(let m=0;m<g;m++){const x=h.map((y,S)=>oo(y[m]||"",o[S]));r.push(`│ ${x.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 Wr(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(!et(r)||!et(l)){n.push(r);continue}const c=tt(r),d=tt(l);if(!Ht(d)||c.length!==d.length){n.push(r);continue}const f=[c];for(o+=1;o+1<s.length&&et(s[o+1]);){o+=1;const p=tt(s[o]);Ht(p)||f.push(p)}n.push(jr(f,e))}return n.join(`
|
|
5
|
+
`)}function Vr(t,e){const s=String(t||"");if(!s)return[""];const n=[];let i=s;for(;i.length>0;){const o=Ct(i,e);if(!o)break;n.push(o),i=i.slice(o.length)}return n.length>0?n:[""]}function Rn(t,e){const s=Math.max(12,e),n=t?` ${String(t).trim()} `:" code ",i=Ct(n,Math.max(1,s-4)),o=Math.max(0,s-i.length-2);return[{text:`┌${i}${"─".repeat(o)}┐`,color:"gray"}]}function Ln(t){return[{text:`└${"─".repeat(Math.max(1,t-2))}┘`,color:"gray"}]}function Fn(t,e){const s=Math.max(8,e),n=Math.max(1,s-2),i=[];for(const o of t){const r=Vr(o,n);for(const a of r)i.push([{text:"│",color:"gray"},{text:oo(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 It(t,e={}){const s=[],n=Math.max(20,Number(e?.width)||80),i=e.tableMode==="sentinel"?"sentinel":"boxArt",r=(i==="boxArt"?Wr(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(Rn(l,Math.max(8,n))),s.push(...Fn(c,Math.max(8,n))),s.push(Ln(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&&et(f)){const y=r[d+1]||"";if(et(y)){const S=tt(f),E=tt(y);if(Ht(E)&&S.length===E.length){const T=[];let C=d+2;for(;C<r.length&&et(r[C]);){const _=tt(r[C]);Ht(_)||T.push(_),C+=1}s.push({kind:"markdownTable",header:S,rows:T}),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 g=/^>\s?(.*)$/.exec(f);if(g){s.push([{text:"> ",color:"gray"},...mt(g[1]).map(y=>({...y,color:y.color||"gray"}))]);continue}const m=/^\s*[-*]\s+(.*)$/.exec(f);if(m){s.push([{text:"• ",color:"gray"},...mt(m[1])]);continue}const x=/^\s*(\d+)\.\s+(.*)$/.exec(f);if(x){s.push([{text:`${x[1]}. `,color:"gray"},...mt(x[2])]);continue}s.push(mt(f))}return a&&(s.push(Rn(l,Math.max(8,n))),s.push(...Fn(c,Math.max(8,n))),s.push(Ln(Math.max(8,n)))),s}function Z({title:t="SYSTEM",timestamp:e="",body:s="",width:n=80,titleColor:i="yellow",borderColor:o="gray",bodyColor:r=null,fitToContent:a=!1}={}){const l=Math.max(a?12:20,Number(n)||(a?12:20)),c=Math.max(1,l-4),d=[{text:` ${String(t||"SYSTEM").toUpperCase()} `,color:i,bold:!0},...e?[{text:` ${String(e)} `,color:"gray"}]:[]],f=It(String(s||""),{width:c}),p=f.length>0?f.flatMap(S=>no(S,c)):[[{text:"",color:null}]],h=r?p.map(S=>Br(S,r)):p,g=h.reduce((S,E)=>Math.max(S,Ft(E)),0),m=a?Math.min(l,Math.max(12,Ft(d)+3,g+4)):l,x=Math.max(1,m-4),y=Math.max(0,m-Ft(d)-3);return[[{text:"┌─",color:o},...d,{text:`${"─".repeat(y)}┐`,color:o}],...h.map(S=>[{text:"│ ",color:o},...so(S,x),{text:" │",color:o}]),[{text:`└${"─".repeat(Math.max(1,m-2))}┘`,color:o}],[{text:"",color:null}]]}function ct(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 ao(t){const e=ct(t,"PilotSwarm");return e==="PilotSwarm"?0:e==="Sweeper Agent"?1:e==="Resource Manager Agent"?2:e==="Facts Manager"?3:10}const Y=300,qr=[Y,1e3,3e3,1e4],Kr=["user.message","assistant.message","system.message"];function Me(t,e){const s=Array.isArray(t)?t.filter(Boolean):[],n=Math.max(Y,Number(e)||Y);return s.length>n?s.slice(-n):s}function Oe(t){return String(t||"").replace(/\r\n/g,`
|
|
7
|
+
`).trim()}function $n(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 lo=/^The session was dehydrated and has been rehydrated on a new worker(?: \([^)]+\))?\./i,zr=/^The session was dehydrated and has been rehydrated on a new worker(?: \([^)]+\))?\.\s*The LLM conversation history is preserved\.?/i;function Ys(t){return lo.test(Oe(t))}function Be(t){const e=String(t||"").replace(/\r\n/g,`
|
|
8
|
+
`).trim();if(!e)return"";const s=e.replace(zr,"").trimStart();return s!==e?s.trim():Ys(e)?e.replace(lo,"").trim():e}function co(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 uo(t,e){const s=String(t||"").replace(/\r\n/g,`
|
|
13
|
+
`);return e==="user"||e==="assistant"?co(s).filter(n=>n.kind==="text").map(n=>n.text).join(`
|
|
14
|
+
`).trim():s.trim()}function Yr(t,e){return e!=="user"&&e!=="assistant"?[]:co(t).filter(s=>s.kind==="system").map(s=>s.text).filter(Boolean)}function Bn(t){const e=Oe(t?.text||"");if(!e)return"";if(t?.role==="user"||t?.role==="assistant"){const s=uo(e,t.role);if(s)return s}return Be(e)}function Qs(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 Qr(t){return Oe(Ks(t)).length>0}function Xr(t){const e=Oe(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 Jr(t){return/^\[SESSION_MESSAGE(?:_RESPONSE)?\b/i.test(Oe(t))}function Ye(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 Zr(t,e){const s=Oe(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=Ye(o,"request_id"),d=Ye(o,"from"),f=Ye(o,"subject"),p=/\bexpects_response=true\b/i.test(o),h=[d?`From: session-${Q(d)}`:"",c?`Request ID: ${c}`:"",f?`Subject: ${f}`:"",p?"Response: required":"Response: not required","",l].filter((g,m)=>m===4||String(g||"").trim());return{id:`${t.sessionId}:${t.seq}`,role:"system",text:h.join(`
|
|
19
|
+
`),time:pe(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=Ye(o,"request_id"),c=Ye(o,"from"),d=Ye(o,"verdict")||"answered",f=[c?`From: session-${Q(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:pe(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 ea(t,e,s){return t?.eventType==="system.message"||(e==="user"||e==="assistant")&&Xr(s)?"system":e}function ta(t,e){if(!t||!e||t.role!==e.role)return!1;const s=Bn(t),n=Bn(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 st(t=[]){const e=[];for(const s of t){if(!s)continue;const n=e[e.length-1];if(!ta(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 sa(t){return typeof t=="string"?t.replace(/^\[FROM:[^\]\n]*\]\n?/,""):t}function nt(t,e){const s=ut(t),n=Zr(t,s);if(n)return n;const i=sa(uo(s,e));if(!Qr(i))return null;const o=Array.isArray(t?.data?.clientMessageIds)?t.data.clientMessageIds.filter(a=>typeof a=="string"&&a):[],r=t?.data?.sender&&typeof t.data.sender=="object"?t.data.sender:null;return{id:`${t.sessionId}:${t.seq}`,role:ea(t,e,i),text:i,time:pe(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime(),...o.length>0?{clientMessageIds:o}:{},...r?{sender:r}:{}}}function fo(t){return t?.eventType!=="system.message"?!1:!Jr(ut(t))}function Gt(t,e){return Yr(ut(t),e).map((s,n)=>Et({...t,seq:`${t?.seq??"?"}:system:${n+1}`,eventType:"system.message",data:{content:s}})).filter(Boolean)}function na(t,e){if(!Array.isArray(t)||e?.role!=="user")return[...t||[]];const s=Oe(e.text),n=Qs(e.text),i=n?Oe(n.answer):"";let o=!1;return t.filter(r=>{if(o||!r?.optimistic||r.role!==e.role)return!0;const a=Oe(r.text);return a!==s&&a!==i?!0:(o=!0,!1)})}function ut(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 Or(e)}function ia(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 Xs(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 ra(t,e=""){return Xs([t?.data?.reason,t?.data?.detail,t?.data?.message,t?.data?.error,e])}function aa(t,e=""){return Xs([t?.data?.message,t?.data?.detail,t?.data?.error,e])}function la(t,e=""){const s=ut(t),n=Be(e);return Xs([Be(s),n,t?.data?.detail,t?.data?.message])}function ca(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 ua(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}=${ca(o)}`);if(s.length===0)return"";const n=Object.keys(e).length>s.length?", ...":"";return` ${s.join(", ")}${n}`}function Js(t){return t?[{text:`[${t}] `,color:"white"}]:[]}function X(t,e,s,n="",i="white"){return[...Js(t),{text:e,color:s},...n?[{text:` ${n}`,color:i}]:[]]}function da(t,e=96){return oa(Ks(ut(t)),e)||""}function cs(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=ua(o,r),c=s==="start"?"▶":s==="partial"?"…":"✓",d=s==="start"?"yellow":s==="partial"?"cyan":"green";return[...Js(t),{text:`${c} ${o}${l}`,color:d},...a?[{text:` [sess ${Q(a)}]`,color:"gray"}]:[]]}function Et(t){const e=pe(t.createdAt),s=da(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=cs(e,t,"start");break;case"tool.execution_complete":n=cs(e,t,"complete");break;case"tool.execution_partial_result":n=cs(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=X(e,"[tool]","cyan",`${o} ${r}`,"white");break}case"assistant.reasoning":n=X(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=X(e,"[intent]","gray",o||"…","white");break}case"assistant.turn_start":n=X(e,"[turn start]","gray",s);break;case"session.turn_completed":n=X(e,"[turn completed]","gray",t?.data?.iteration!=null?`iter ${t.data.iteration}`:s);break;case"session.lossy_handoff":n=X(e,"[lossy handoff]","yellow",aa(t,s)||"handoff to a new worker");break;case"session.dehydrated":n=X(e,"[dehydrated]","cyan",ra(t,s));break;case"session.hydrated":case"session.rehydrated":n=X(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=X(e,"[wait]","yellow",`${i}${r}${o}`.trim());break}case"session.input_required_started":n=X(e,"[input]","yellow",s);break;case"session.agent_spawned":n=X(e,"[spawn]","cyan",t?.data?.agentId||Q(t?.data?.childSessionId),"white");break;case"session.cron_started":n=X(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=X(e,"[cron]","magenta",`scheduled${t?.data?.nextFireAt?` ${$n(t.data.nextFireAt)}`:""}${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_fired":n=X(e,"[cron]","magenta",`fired${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_at_fired":n=X(e,"[cron]","magenta",`fired${t?.data?.scheduledAt?` ${$n(t.data.scheduledAt)}`:""}${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_cancelled":case"session.cron_at_cancelled":n=X(e,"[cron]","magenta",`cancelled${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_at_completed":n=X(e,"[cron]","magenta",`completed${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.command_received":n=X(e,"[command]","magenta",`/${t?.data?.cmd||"?"}${s?` ${s}`:""}`);break;case"session.command_completed":n=X(e,"[command]","magenta",`/${t?.data?.cmd||"?"} ok${s?` ${s}`:""}`);break;case"session.compaction_start":case"session.compaction_complete":n=kr(e,t.eventType,t.data||{});break;case"session.error":n=X(e,"[error]","red",s||"session error","white");break;case"system.message":Ys(ut(t))?n=X(e,"[rehydrated]","green",la(t,s)||"conversation preserved"):n=X(e,"[system]","gray",s||"system message");break;default:n=[...Js(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:ia(n),line:n}}function fa(t=Y){const e=Math.max(Y,Number(t)||Y);return qr.find(n=>n>e)||Math.min(1e5,e*2)}function Pt(t=[],e={}){const s=Math.max(Y,Number(e.requestedLimit??e.eventLimit??Y)||Y),n=[],i=[],o=[];for(const r of t){if(o.push(r),r.eventType==="user.message"){i.push(...Gt(r,"user"));const l=nt(r,"user");l&&n.push(l);continue}if(r.eventType==="assistant.message"){i.push(...Gt(r,"assistant"));const l=nt(r,"assistant");l&&n.push(l);continue}if(r.eventType==="system.message"){if(fo(r)){const l=Et(r);l&&i.push(l)}else{const l=nt(r,"system");l&&n.push(l)}continue}const a=Et(r);a&&i.push(a)}return{chat:st(n),activity:i,events:o.slice(-s),loadedEventLimit:s,loadedEventCount:o.length,hasOlderEvents:o.length>=s}}function Dn(t,e){const s=Array.isArray(t?.events)?t.events:[],n=Math.max(Y,Number(t?.loadedEventLimit??Y)||Y),i=s.length>0&&s[s.length-1]?.seq===e?.seq?s:[...s,e].slice(-n),o={chat:Me(t?.chat||[],n),activity:Me(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(...Gt(e,"user")),o.activity=Me(o.activity,n);const a=nt(e,"user");return a&&(Array.isArray(a.clientMessageIds)&&a.clientMessageIds.some(l=>o.stoppedMessageIds.includes(l))&&(a.stopped=!0),o.chat=na(o.chat,a),o.chat.push(a),o.chat=Me(st(o.chat),n)),o}if(e.eventType==="assistant.message"){o.activity.push(...Gt(e,"assistant")),o.activity=Me(o.activity,n);const a=nt(e,"assistant");return a&&(o.chat.push(a),o.chat=Me(st(o.chat),n)),o}if(e.eventType==="system.message"){if(fo(e)){const a=Et(e);a&&(o.activity.push(a),o.activity=Me(o.activity,n))}else{const a=nt(e,"system");if(!a)return o;o.chat.push(a),o.chat=Me(st(o.chat),n)}return o}const r=Et(e);return r&&(o.activity.push(r),o.activity=Me(o.activity,n)),o}function us(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?ct(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 pa=.7,ha=30,Hn=36,ds=18,fs=18,ps=0,po=3,at=6,Jt=10,ma=.25,ga=.5,it=6,Ut=10,ho=.336,hs=it,ms=Ut,gs=at,ys=Jt;function gt(t,e,s){return Math.max(e,Math.min(s,t))}function ya(t){return[v.SESSIONS,v.CHAT,v.INSPECTOR,v.ACTIVITY].includes(t)?t:null}function Sa(t={}){return{width:Math.max(40,Number(t.width)||120),height:Math.max(18,Number(t.height)||40)}}function ot(t=""){const e=String(t||"").split(`
|
|
25
|
+
`).length;return gt(e,1,po)}function mo(t){return Math.max(at,Math.floor(t*ma))}function go(t,e){const s=Math.floor(Math.max(0,Number(t)||0)*ga),n=Math.max(at,e-Jt);return Math.max(at,Math.min(n,s))}function wt(t,e=0,s=1,n=0,i=0,o=null){const r=Sa(t),a=r.width,l=r.height,c=gt(Number(s)||1,1,po),d=ya(o),f=5+c,p=Math.max(18,l-f),g=Math.floor(a*pa)+(Number(e)||0),m=a-g-ps;let x=!1,y=!1;g<=ds&&m>fs?x=!0:m<=fs&&g>ds?y=!0:g<=ds&&m<=fs&&(y=e>=0,x=!y);let S,E;x?(S=0,E=a):y?(S=a,E=0):(S=gt(g,ha,a-Hn-ps),E=Math.max(Hn,a-S-ps));const C=mo(p)+(Number(n)||0),_=p-C;let k=!1,R=!1;_<=ys&&C>gs?R=!0:C<=gs&&_>ys?k=!0:_<=ys&&C<=gs&&(R=(Number(n)||0)>=0,k=!R);let N,O;if(k)N=0,O=p;else if(R)N=p,O=0;else{const ne=go(l,p);N=gt(C,at,ne),O=Math.max(Jt,p-N)}const L=Math.max(it,Math.floor(p*ho))+(Number(i)||0),K=p-L;let P=!1,F=!1;K<=ms&&L>hs?P=!0:L<=hs&&K>ms?F=!0:K<=ms&&L<=hs&&(P=(Number(i)||0)>=0,F=!P);let V,q;return P?(V=p,q=0):F?(q=p,V=0):(V=gt(L,it,Math.max(it,p-Ut)),q=Math.max(Ut,p-V)),{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:x,rightHidden:y,inspectorHidden:P,activityHidden:F,sessionHidden:k,chatHidden:R,leftWidth:S,rightWidth:E,sessionPaneHeight:N,chatPaneHeight:O,activityPaneHeight:V,inspectorPaneHeight:q}}function Ns(t){if(t?.fullscreenPane)return[t.fullscreenPane,v.PROMPT];if(t?.leftHidden)return[v.INSPECTOR,v.ACTIVITY,v.PROMPT];if(t?.rightHidden)return[...t?.sessionHidden?[v.CHAT]:t?.chatHidden?[v.SESSIONS]:[v.SESSIONS,v.CHAT],v.PROMPT];if(t?.sessionHidden){const e=t?.inspectorHidden?[v.ACTIVITY]:t?.activityHidden?[v.INSPECTOR]:[v.INSPECTOR,v.ACTIVITY];return[v.CHAT,...e,v.PROMPT]}if(t?.chatHidden){const e=t?.inspectorHidden?[v.ACTIVITY]:t?.activityHidden?[v.INSPECTOR]:[v.INSPECTOR,v.ACTIVITY];return[v.SESSIONS,...e,v.PROMPT]}return t?.inspectorHidden?[v.SESSIONS,v.CHAT,v.ACTIVITY,v.PROMPT]:t?.activityHidden?[v.SESSIONS,v.CHAT,v.INSPECTOR,v.PROMPT]:[v.SESSIONS,v.CHAT,v.INSPECTOR,v.ACTIVITY,v.PROMPT]}function Pe(t,e){const s=Ns(e);return s.includes(t)?t:s[0]||v.PROMPT}function ba(t,e){return e?.fullscreenPane?e.fullscreenPane:e?.leftHidden?{[v.PROMPT]:v.PROMPT,[v.ACTIVITY]:v.INSPECTOR,[v.INSPECTOR]:v.INSPECTOR}[t]||v.INSPECTOR:e?.rightHidden?{[v.PROMPT]:v.PROMPT,[v.CHAT]:e?.sessionHidden?v.CHAT:v.SESSIONS,[v.SESSIONS]:v.SESSIONS}[t]||(e?.sessionHidden?v.CHAT:v.SESSIONS):{[v.PROMPT]:e?.sessionHidden?v.CHAT:v.SESSIONS,[v.ACTIVITY]:e?.chatHidden?v.SESSIONS:v.CHAT,[v.INSPECTOR]:e?.chatHidden?v.SESSIONS:v.CHAT,[v.CHAT]:e?.sessionHidden?v.CHAT:v.SESSIONS,[v.SESSIONS]:v.SESSIONS}[t]||(e?.sessionHidden?v.CHAT:v.SESSIONS)}function wa(t,e){return e?.fullscreenPane?e.fullscreenPane:e?.leftHidden?{[v.PROMPT]:v.PROMPT,[v.INSPECTOR]:v.ACTIVITY,[v.ACTIVITY]:v.ACTIVITY}[t]||v.INSPECTOR:e?.rightHidden?{[v.PROMPT]:v.PROMPT,[v.SESSIONS]:e?.chatHidden?v.SESSIONS:v.CHAT,[v.CHAT]:v.CHAT}[t]||(e?.chatHidden?v.SESSIONS:v.CHAT):e?.inspectorHidden?{[v.PROMPT]:v.PROMPT,[v.SESSIONS]:v.CHAT,[v.CHAT]:v.ACTIVITY,[v.ACTIVITY]:v.ACTIVITY}[t]||v.CHAT:e?.activityHidden?{[v.PROMPT]:v.PROMPT,[v.SESSIONS]:v.CHAT,[v.CHAT]:v.INSPECTOR,[v.INSPECTOR]:v.INSPECTOR}[t]||v.CHAT:{[v.PROMPT]:v.PROMPT,[v.SESSIONS]:v.CHAT,[v.CHAT]:v.INSPECTOR,[v.INSPECTOR]:v.ACTIVITY,[v.ACTIVITY]:v.ACTIVITY}[t]||v.CHAT}function Gn(t){return t?.isSystem?ao(t):Number.MAX_SAFE_INTEGER}function xa(t=[]){const e=new Map;for(let s=0;s<t.length;s+=1){const n=t[s]?.sessionId;!n||e.has(n)||e.set(n,s)}return e}function Ia(t=[]){if(t instanceof Map)return new Map(t);if(Array.isArray(t))return xa(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 Ea(t){return!!(t&&!t.isSystem&&(t.isGroup||!t.parentSessionId&&!t.groupId))}function Un(t,e){return!!(Ea(t)&&e&&e.has(t.sessionId))}function jn(t,e){return t.isSystem?0:t.isGroup&&Un(t,e)?1:Un(t,e)?2:t.isGroup?3:4}function Wn(t){const e=t?.updatedAt??t?.summaryUpdatedAt??t?.latestSummaryUpdatedAt,s=typeof e=="number"?e:Date.parse(e||"");return Number.isFinite(s)?s:0}function Vn(t,e,s,n){const i=jn(t,n),o=jn(e,n);if(i!==o)return i-o;const r=Gn(t),a=Gn(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=Wn(t),f=Wn(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||""),g=String(e.title||""),m=h.localeCompare(g);return m!==0?m:String(t.sessionId||"").localeCompare(String(e.sessionId||""))}function $e(t=[],e=new Set,s=[],n=null){const i=new Map,o=new Map,r=Ia(s),a=n instanceof Set?n:new Set(Array.isArray(n)?n:[]);for(const 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)=>Vn(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)=>Vn(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 g of h)d(g,p+1)}for(const f of l)d(f,0);return c}function va(t){return Object.freeze({...t,page:Object.freeze({...t.page||{}}),terminal:Object.freeze({...t.terminal||{}}),tui:Object.freeze({...t.tui||{}})})}function te({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 va({id:t,label:e,description:s,page:n,terminal:i,tui:{...r,...o}})}const Ta=te({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"}}),Aa=te({id:"github-light",label:"GitHub Light",description:"GitHub light palette with crisp neutrals, blue actions, and high-contrast status colors.",page:{background:"#ffffff",foreground:"#1f2328",overlayBackground:"#ffffff",overlayForeground:"#1f2328",hintColor:"#57606a",modalBackdrop:"rgba(31, 35, 40, 0.34)",modalBackground:"#ffffff",modalBorder:"#d0d7de",modalForeground:"#1f2328",modalMuted:"#57606a",modalSelectedBackground:"#ddf4ff",modalSelectedBorder:"#0969da",modalSelectedForeground:"#0550ae"},terminal:{background:"#ffffff",foreground:"#1f2328",cursor:"#0969da",cursorAccent:"#ffffff",selectionBackground:"#ddf4ff",black:"#24292f",red:"#cf222e",green:"#1a7f37",yellow:"#9a6700",blue:"#0969da",magenta:"#8250df",cyan:"#1b7c83",white:"#6e7781",brightBlack:"#57606a",brightRed:"#a40e26",brightGreen:"#116329",brightYellow:"#7d4e00",brightBlue:"#0550ae",brightMagenta:"#6639ba",brightCyan:"#0f6f78",brightWhite:"#1f2328"},tui:{surface:"#ffffff",border:"#d0d7de",userChat:"#0969da",userChatLabel:"#0550ae",activeHighlightBackground:"#ddf4ff",activeHighlightForeground:"#0550ae",selectionBackground:"#0969da",selectionForeground:"#ffffff",promptCursorBackground:"#0969da",promptCursorForeground:"#ffffff"}}),Ca=te({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"}}),ka=te({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"}}),Ma=te({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"}}),Pa=te({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"}}),Na=te({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"}}),Oa=te({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"}}),_a=te({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"}}),Ra=te({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"}}),La=te({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"}}),Fa=te({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"}}),$a=te({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"}}),yo=te({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"}}),Ba=te({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"}}),Da=te({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"}}),Ha=te({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"}}),Ga=te({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"}}),So=Object.freeze([Na,Ta,Aa,Ca,ka,Ma,Pa,Ra,_a,Oa,La,Fa,$a,yo,Ba,Da,Ha,Ga].sort((t,e)=>t.label.localeCompare(e.label,void 0,{sensitivity:"base"}))),Ua=new Map(So.map(t=>[t.id,t])),ja=yo.id;function Wa(){return So}function _e(t){return t?Ua.get(t)??null:null}const Va=new Set(["agent","user","system"]);function jt(t){const e=Array.isArray(t?.ownerKeys)?[...new Set(t.ownerKeys.map(n=>String(n||"").trim()).filter(Boolean))]:[];return{all:t&&typeof t=="object"?t?.all===!0:!0,includeSystem:t?.includeSystem===!0,includeUnowned:t?.includeUnowned===!0,includeMe:t?.includeMe===!0,ownerKeys:e}}function qa(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:Va.has(t.source)?t.source:"agent"}}function Wt(t){const e=Array.isArray(t)?t:[],s=[],n=new Set;for(const i of e){const o=qa(i);!o||n.has(o.filename)||(n.add(o.filename),s.push(o))}return s}function Ka(t,e){const s=String(e||"").trim();return s&&Wt(t).find(n=>n.filename===s)||null}function Zs(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 Vt(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 Os(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 bo(t){if(t==null)return null;const e=String(t).trim();return e||null}function za({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=Zs(o);return{branding:e||{title:"PilotSwarm",splash:"{bold}{cyan-fg}PilotSwarm{/cyan-fg}{/bold}"},auth:{principal:null,authorization:null},ui:{focusRegion:v.SESSIONS,inspectorTab:we[0],sequenceExpandedTurns:[],sequenceSelectedTurn:null,chatViewMode:n==="summary"?"summary":"transcript",statsViewMode:"session",prompt:"",promptCursor:0,promptRows:1,promptAttachments:[],promptEdit:null,statusText:"Starting PilotSwarm...",themeId:_e(s)?.id||ja,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:bo(l),collapsedIds:Os(a),collapsedIdsExplicit:d,pinnedIds:Vt(r),selectedIds:[],selectMode:!1,orderById:{},nextOrderOrdinal:0,filterQuery:"",ownerFilterExplicit:c,ownerFilter:jt(i)},history:{bySessionId:new Map},outbox:{bySessionId:{}},orchestration:{bySessionId:{}},executionHistory:{bySessionId:{},format:"pretty"},files:{bySessionId:{},fullscreen:!1,selectedArtifactId:null,filter:{scope:"selectedSession",query:""}},logs:{available:!1,availabilityReason:"Log tailing disabled: no K8S_CONTEXT configured in the env file.",tailing:!1,entries:[],filter:{source:"allNodes",level:"all",format:"pretty"}},sessionStats:{bySessionId:{}},fleetStats:{loading:!1,data:null,userStats:null,fetchedAt:0},admin:{visible:!1,loading:!1,loadError:null,profile:null,ghcpKey:{editing:!1,draft:"",cursorIndex:0,saving:!1,error:null,lastSavedAt:0,storeAsSystem:!1},systemGhcpKey:{supported:!1,loading:!1,configured:!1,changedBy:null,changedAt:null,error:null}}}}function wo(t){const e=String(t||"");return/\bConnection is closed\b/i.test(e)||/\bLive Copilot connection lost\b/i.test(e)}function Ya(t,e){return!(!wo(t?.error)||e?.error!==void 0||String(e?.status||"")!=="running"||["Completed","Failed","Terminated"].includes(String(e?.orchestrationStatus||"")))}const xo="activeHighlightBackground",en="activeHighlightForeground",Ss="userChat",Qa="userChatLabel",Xa="otherUserChatLabel",qn=new WeakMap,Kn=new WeakMap;function Ja(t){return t||en}function Io(t,{preserveColors:e=!1}={}){return(t||[]).map(s=>({...s,color:e?Ja(s?.color):en,backgroundColor:xo,bold:s?.bold??!0}))}function Ee(t,{color:e=en,bold:s=!0}={}){return{text:t,color:e,backgroundColor:xo,bold:s}}function Te(t,e){return[{text:String(t||""),color:e,bold:!0}]}const Za=72;function Eo(t){const e=Number(t)||0;return e>0&&e<=Za}function tn(t){if(!t)return"unknown";const e=t.status||"unknown";return t.cronActive===!0&&(e==="waiting"||e==="idle"||e==="unknown")?"cron_waiting":e}function el(t){const e=tn(t);return!e||e==="unknown"?"":e==="cron_waiting"?"waiting":e}function tl(t){const e=vo(t);return!e||e==="unknown"?"":e==="cron_waiting"?"waiting":e}function vo(t){return t?.rowVisualStatus||tn(t)}function To(t){return t==="Completed"||t==="Failed"||t==="Terminated"}function sn(t){const e=tn(t);return t?.orchestrationStatus==="Failed"||e==="failed"?"failed":e==="error"||e==="running"&&wo(t?.error)&&!To(t?.orchestrationStatus)?"warning":null}function Ao(t,e="local"){const s=sn(t);if(s)return s;const n=vo(t);if(e==="remote"&&To(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 vt(t,e="local"){switch(Ao(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 Co(t,e="local"){switch(Ao(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 xe(t){const e=String(t?.provider||"").trim(),s=String(t?.subject||"").trim();return e&&s?`${e}${s}`:null}function nn(t,e="unknown user"){return String(t?.displayName||t?.email||"").trim()||e}const sl=xe({provider:"system",subject:"system"});function zn(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 nl(t){return zn(t?.displayName)||zn(t?.email)||"?"}function il(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=xe(s.owner);if(n&&(e.add(n),e.size>1))return!0}return!1}function ko(t,e={}){return!t?.isGroup||!t?.groupId?[]:Object.values(e||{}).filter(s=>s&&!s.isGroup&&!s.parentSessionId&&s.groupId===t.groupId)}function on(t,e={}){if(!t?.isGroup)return t?.owner??null;if(t.owner)return t.owner;const s=new Map;for(const n of ko(t,e)){const i=xe(n?.owner);i&&!s.has(i)&&s.set(i,n.owner)}return s.size===1?s.values().next().value:null}function Yn(t){return String(t||"").toLowerCase().replace(/[^a-z0-9]+/gu,"")}function Qn(t,e){const s=Yn(t),n=Yn(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&&Qn(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&&Qn(r,t))return{displayTitle:a,agentTitle:r}}return null}function rl(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 Zt(t){const e=String(t?.title||"").trim(),s=ol(t);if(!s)return e;const n=rl(s.displayTitle);return n?`${n.userTitle} · ${n.typeTitle} · ${s.agentTitle}`:`${s.displayTitle} · ${s.agentTitle}`}function Mo(t,e){const s=Q(t?.sessionId);if(t?.isSystem)return`${ct(t,e)} (${s})`;const n=Zt(t);return n?n.includes(s)?n:`${n} (${s})`:`(${s})`}function Xn(t,e={},s={},n=void 0){if(!e||e.all===!0)return!0;if(t?.isSystem)return e.includeSystem===!0;const i=xe(n!==void 0?n:t?.owner);if(!i)return e.includeUnowned===!0;if(i===sl)return e.includeSystem===!0;const o=xe(s?.principal);return e.includeMe&&o&&i===o?!0:Array.isArray(e.ownerKeys)&&e.ownerKeys.includes(i)}function Po(t,e={},s={},n=null){const i=on(t,n||{});if(Xn(t,e,s,i))return!0;if(!n)return!1;if(t?.isGroup)return ko(t,n).some(a=>Po(a,e,s,n));let o=t,r=0;for(;o?.parentSessionId&&r<16;){const a=n[o.parentSessionId];if(!a)return!1;if(Xn(a,e,s))return!0;o=a,r+=1}return!1}function al(t){return(t||[]).map(e=>e?.text||"").join("")}function rn(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 Jn(t){const{childMap:e}=rn(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 Zn(t=[],e={}){const{parentMap:s}=rn(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 an(t={}){if(!t||typeof t!="object")return Jn(t);const e=qn.get(t);if(e)return e;const s=Jn(t);return qn.set(t,s),s}function ln(t=[],e={}){if(!Array.isArray(t))return Zn(t,e);const s=Kn.get(t);if(s)return s;const n=Zn(t,e);return Kn.set(t,n),n}function No(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 _s(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 ${_s(t.cronNextFireAt)}]`,color:"magenta"}:t?.cronActive===!0&&typeof t?.cronInterval=="number"?{text:`[cron ${bt(t.cronInterval)}]`,color:"magenta"}:null}function Oo(t){return!!(t&&!t.isSystem&&(t.isGroup||!t.parentSessionId&&!t.groupId))}function cl(t,e){const s=[],n=tl(t);n&&s.push({text:n,color:vt(t,e)});const i=pn(t?.model,t?.reasoningEffort);i&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:i,color:"cyan"}));const o=Tr(t?.contextUsage);o&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:o.text,color:o.color}));const r=Ar(t?.contextUsage);return r&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:r.text,color:r.color})),s}function ul(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&&Oo(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 F=Co(e,r);o.push({text:F?`${F} `:" ",color:vt(e,r)})}const h=e?.isGroup?"cyan":e?.isSystem?"yellow":vt(e,r),g=on(e,s.sessions?.byId||{}),m=Q(e?.sessionId),x=e?.updatedAt||e?.summaryUpdatedAt||e?.latestSummaryUpdatedAt||e?.createdAt||0,y=x?Uc(x):"",S=pn(e?.model,e?.reasoningEffort),E=e?.isSystem?ct(e,s.branding?.title||"PilotSwarm"):Zt(e),T=!!(e?.isSystem||e?.isGroup||E&&E.trim()),C=[...o];if(il(s)&&!e?.isSystem&&!e?.isGroup){const F=g?nl(g):"?",V=xe(s?.auth?.principal),q=V&&xe(g)===V;C.push({text:`[${F}] `,color:q?"green":"cyan",bold:!0})}T?C.push({text:E,color:h,bold:!!(e?.isSystem||e?.isGroup)}):(C.push({text:m,color:h}),y&&(C.push({text:" · ",color:"gray"}),C.push({text:y,color:"gray"})),S&&(C.push({text:" · ",color:"gray"}),C.push({text:S,color:"green"})));const _=No(e?.sessionId,t,n,i);_&&C.push({text:` ${_.text}`,color:_.color,bold:_.bold});const k=ll(e);k&&C.push({text:" ⏱",color:"magenta"});const R=[],N=e?.contextUsage?.compaction?.state,O=qs(e?.contextUsage);e?.isGroup?e?.memberCount!=null&&R.push({text:`${e.memberCount}`,color:"gray"}):N==="running"?R.push({text:"⇊",color:"magenta"}):N==="failed"?R.push({text:"!",color:"red"}):O!=null?R.push({text:`${O}%`,color:O>=85?"red":O>=70?"yellow":"green"}):R.push({text:"—",color:"gray"});const U=[];e?.isGroup&&e?.memberCount!=null&&(U.push({text:`${e.memberCount} member${e.memberCount===1?"":"s"}`,color:"gray"}),y&&(U.push({text:" · ",color:"gray"}),U.push({text:y,color:"gray"})));const L=[],K=()=>{L.length&&L.push({text:" · ",color:"gray"})};if(e?.isGroup)L.push(...U);else{T&&(L.push({text:m,color:"cyan"}),y&&(K(),L.push({text:y,color:"gray"})),S&&(K(),L.push({text:S,color:"green"})));const F=e?.contextUsage;F&&Number.isFinite(F.currentTokens)&&Number.isFinite(F.tokenLimit)&&F.tokenLimit>0&&(K(),L.push({text:`ctx ${G(F.currentTokens)}/${G(F.tokenLimit)}`,color:"gray"}));const V=n?.[e?.sessionId];V&&(K(),L.push({text:`${V} child${V===1?"":"ren"}`,color:"gray"})),k&&(K(),L.push({text:k.text,color:k.color})),(e?.visibility==="shared_read"||e?.visibility==="shared_write")&&(K(),L.push({text:e.visibility==="shared_write"?"shared·write":"shared·read",color:"magenta"}))}return{runs:[...C,...T&&y&&!e?.isGroup?[{text:" ",color:"gray"},{text:y,color:"gray"}]:[],...R.length&&!e?.isGroup?[{text:" · ",color:"gray"},...R]:[],...e?.isGroup&&U.length?[{text:" ",color:"gray"},...U]:[]],titleRuns:C,ctxRuns:R,metaRuns:U,badgeRuns:[],selectedMetaRuns:L,detailRuns:L}}function _o(t){return String(t||"").trim().toLowerCase()}function We(t,e){const s=_o(e);return s?String(t||"").toLowerCase().includes(s):!0}function Tt(t){const e=an(t.sessions.byId),s=ln(t.sessions.flat,t.sessions.byId),n=_o(t.sessions?.filterQuery||""),i=t.sessions?.ownerFilter||{all:!0},o=t.auth||{},r=new Set(Array.isArray(t.sessions?.pinnedIds)?t.sessions.pinnedIds:[]),a=new Set(Array.isArray(t.sessions?.selectedIds)?t.sessions.selectedIds:[]);return t.sessions.flat.map(l=>{const c=t.sessions.byId[l.sessionId],d=ul(l,c,t,e,s);return{sessionId:l.sessionId,text:al(d.runs),...d,depth:l.depth,status:c?.status,statusColor:vt(c,t.connection?.mode||"local"),active:l.sessionId===t.sessions.activeSessionId,isSystem:!!c?.isSystem,isGroup:!!c?.isGroup,hasChildren:l.hasChildren,collapsed:l.collapsed,pinned:r.has(l.sessionId),selected:a.has(l.sessionId),canPin:Oo(c)}}).filter(l=>{const c=t.sessions.byId[l.sessionId];if(!Po(c,i,o,t.sessions.byId))return!1;const d=on(c,t.sessions.byId),f=d?`${nn(d,"")} ${d.email||""}`:"",p=`${c?.shortSummary||""} ${c?.summaryState?.intent||""} ${c?.summaryState?.summary||""}`;return We(l.text,n)||We(l.sessionId,n)||We(f,n)||We(p,n)})}function Rs(t,e=8){const s=Tt(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 an(t.sessions.byId),ln(i,t.sessions.byId),s.filter(f=>d.some(p=>p.sessionId===f.sessionId))}function Ie(t){const e=t.sessions.activeSessionId;return e&&t.sessions.byId[e]||null}function Ro(t){return!t||t.isGroup?!1:(t.status||"")==="running"}function dl(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 fl(t,e=[]){const s=t?.answeredPendingQuestion,n=String(s?.question||"").trim(),i=String(s?.answer||"").trim();if(!n||!i||Lo(e,n))return null;const o=s.pendingPhase==="queued"?"queued":"pending",r=Number(s.answeredAt||0)||t.updatedAt||Date.now();return{id:`answered-question:${t.sessionId}:${n}:${r}`,role:"user",text:`The user was asked: "${n}"
|
|
27
|
+
The user responded: "${i}"`,time:"",createdAt:r,optimistic:!0,pendingPhase:o}}function pl(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 Lo(t,e){const s=String(e||"").trim();return s?(t||[]).some(n=>Qs(n?.text||"")?.question?.trim()===s):!1}function hl(t){const e=String(t?.error||"").trim();if(!e)return null;const s=sn(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 ei(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 ml(t){const e=String(t||"").replace(/\s+/g," ").trim();return e?e.replace(/^\[[^\]]+\]\s*/,"").replace(/^\[[^\]]+\]\s*/,"").trim():""}function gl(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=ml(o.text);if(r)return{...o,summaryText:r}}return null}function yl(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=ei(p,"user.message"),g=ei(p,"assistant.message"),m=h>g;if(i==="waiting"||i==="input_required"||!a&&!m&&i!=="running"&&!l)return null;const x=Math.max(h,g),y=p.filter(C=>C?.eventType==="assistant.reasoning"&&Number(C?.seq||0)>x),S=y[y.length-1]||null,E=String(S?.data?.content||S?.data?.text||S?.data?.message||"").trim();if(E)return{kind:"thinking",label:"Thinking",text:E,createdAt:S?.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:g,tokenSeq:S?.seq||0};const T=gl(e,x);return T?.summaryText?{kind:i==="running"?"working":"sending",label:i==="running"?"Working":"Sending",text:T.summaryText,createdAt:T.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:g,tokenSeq:T.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:g,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:g,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:g,tokenSeq:0}:l?{kind:"sending",label:"Sending",text:"Working on it...",createdAt:r?.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:g,tokenSeq:0}:i==="running"?{kind:"working",label:"Working",text:"Working on it...",createdAt:t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:g,tokenSeq:0}:null}function cn(t){const e=t.sessions.activeSessionId,s=e&&t.sessions.byId[e]||null;if(!e)return us(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,g)=>g===1||String(h||"").length>0).join(`
|
|
30
|
+
`),createdAt:s.updatedAt||Date.now()}]}if(t.ui?.chatViewMode==="summary")return Sl(s);const n=t.history.bySessionId.get(e),i=n?.chat||[],o=s?.pendingQuestion?.question&&!Lo(i,s.pendingQuestion.question)?dl(s):null,r=fl(s,i),a=hl(s);if((!n||i.length===0)&&!o&&!r&&!a)return us(t.branding,s);const l=i.length>0?[...i]:us(t.branding,s);return o&&l.push(o),r&&l.push(r),a&&l.push(a),l}function Sl(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=Zt(t)||t?.title||t?.sessionId||"Session",o=[];o.push(`# ${i}`),o.push("");const r=[],a=el(t);if(a&&r.push(["Status",a]),s?.intent&&r.push(["Intent",String(s.intent)]),t?.summaryUpdatedAt){const c=pe(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 g=typeof h=="string"?e(h):JSON.stringify(h);o.push(` - **${p}:** ${g}`)}}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 bl(t){const e=t.sessions.activeSessionId;return e?Array.isArray(t.outbox?.bySessionId?.[e])?t.outbox.bySessionId[e].map(s=>pl(e,s)).filter(Boolean):[]:[]}function bs(t,e="gray",s={}){return[{text:t,color:e,bold:!!s.bold,underline:!!s.underline}]}function wl(t,e={}){const s=pe(t?.createdAt||t?.time),n=t?.sender,i=n?.kind==="user"?xe(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 g=null,m=null;t?.pendingPhase==="pending"?(g="○",m="yellow"):t?.pendingPhase==="queued"?(g="✓",m="cyan"):t?.pendingPhase==="cancelling"||t?.pendingPhase==="rejected"?(g="x",m="red"):t?.role==="user"&&!t?.optimistic&&!t?.pendingPhase&&(t?.stopped?(g="⊘",m="yellow"):(g="✓✓",m="green"));const x=t?.pendingPhase==="pending"?"yellow":t?.pendingPhase==="queued"?"cyan":t?.pendingPhase==="cancelling"||t?.pendingPhase==="rejected"?"red":d?Xa:t?.role==="user"?Qa:t?.role==="assistant"?"green":t?.role==="system"?"yellow":"white",y=s?`[${s}] `:"",S=[...bs(y,"gray")];return g&&S.push(...bs(`${g} `,m)),S.push(...bs(`${h}: `,x,{bold:!0})),S}function He(t){return Array.isArray(t)?(t||[]).map(e=>e?.text||"").join(""):t?.kind==="markdownTable"?"[table]":String(t?.text||"")}function Fo(){return[{text:"",color:null}]}function xl(t){const e=(t||[]).find(n=>He(n).trim().length>0);if(e?.kind==="markdownTable")return!0;const s=He(e).trimStart();return/^[┌│└]/.test(s)}function qt(t){const e=Array.isArray(t)?[...t]:[];for(;e.length>0;){const s=e[0];if(He(s).trim().length>0)break;e.shift()}return e}function Il(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 El.test(s)?{leadingText:"",systemText:s}:null}const El=/^(?: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 $o(t){const e=Il(t);if(e){const r=[];e.leadingText&&r.push({kind:"text",text:e.leadingText});const a=Be(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=Be(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 g=h.replace(/\]\s*$/,"");g.trim()&&c.push(g),d=p;break}c.push(h)}if(d===-1){i.push(a),r+=1;continue}o();const f=Be(c.join(`
|
|
40
|
+
`).trim());if(!f){r=d+1;continue}n.push({kind:"system",text:f}),r=d+1}return o(),n}function vl(t){return t?t?.role==="system"?!Ys(t?.text||"")||!!Be(t?.text||""):t?.role!=="user"&&t?.role!=="assistant"?!1:$o(t?.text||"").some(e=>e.kind==="system"):!1}function ti(t){return vl(t)?"system":t?.role||"other"}function Bo(t,e){return!t||!e?!1:ti(t)!==ti(e)}function Tl(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 Al(t,e=""){const s=Tl(t);return{kind:"systemNotice",text:`${e?`[${e}] `:""}System: ${s}`,summary:s,body:Ze(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:Ze(s||r),color:i}}function Cl(t){return t?.label?[{text:t.label,color:t.kind==="working"?"yellow":"cyan",bold:!0}]:null}function kl(t,e){return e?(t||[]).map(s=>Array.isArray(s)?s.map(n=>({...n,color:n?.color||e})):s):t}function Ml(t){const e=(t||[]).find(s=>He(s).trim().length>0);return e?He(e).trimStart().startsWith("┌"):!1}function Kt(t,e){!Array.isArray(e)||e.length===0||(t.length>0&&Ml(e)&&He(t[t.length-1]).trim().length>0&&t.push([{text:"",color:null}]),t.push(...e))}function Pl(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 Nl(t,e,s){const n=Math.max(20,Number(s)||20),i=pe(e?.createdAt||e?.time),o=Pl(t),r=a=>{const l=String(a||"").replace(/^session-/i,"");return Q(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 Z({title:"System",timestamp:i,body:t,width:n,titleColor:"yellow",borderColor:"gray",bodyColor:"gray",fitToContent:!0})}function Ol(t,e){const s=Math.max(12,Math.min(72,Number(e)||12)),n=Math.max(1,s-4),i=pe(t?.createdAt||t?.time),o=String(t?.thinkingLabel||"Thinking…").trim()||"Thinking…",r=t?.progressKind==="working"?"yellow":(t?.progressKind==="sending","cyan"),a=z([{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()?qt(It(Ze(t.text),{width:n})).flatMap(p=>no(p,n)):[],f=[[{text:"┌─",color:"gray"},...a,{text:`${"─".repeat(c)}┐`,color:"gray"}]];for(const p of d)f.push([{text:"│ ",color:"gray"},...so(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 _l(t){return String(t||"").split(`
|
|
49
|
+
`).reduce((e,s)=>Math.max(e,Ks(s).length),0)}function zt(t,e,s={}){if(t?.splash){const l=t.mobileText&&_l(t.text)>e;return[{kind:"markup",value:l?t.mobileText:t.text,splashAlt:!l&&t.mobileText?t.mobileText:null}]}if(t?.thinking)return Ol(t,e);if(t?.noChrome)return qt(It(Ze(t?.text||""),{width:Math.max(20,e),tableMode:s.tableMode}));if(t?.role==="user"){const l=Qs(t?.text||"");if(l)return[...Z({title:"Question",timestamp:pe(t?.createdAt||t?.time),body:l.question,width:Math.max(20,e),titleColor:Ss,borderColor:Ss}),...zt({...t,text:l.answer},e,s)]}if(s.allowLeadingSystemNotices!==!1&&(t?.role==="user"||t?.role==="assistant")){const l=$o(t?.text||"");if(l.some(c=>c.kind==="system")){const c=[];let d=!1;for(const p of l)p.kind!=="system"&&p.text.trim()&&(Kt(c,zt({...t,text:p.text},e,{...s,allowLeadingSystemNotices:!1,skipPrefix:d})),d=!0);if(c.length>0)return c;const f=[];for(const p of l)p.kind!=="system"||!p.text.trim()||Kt(f,Nl(p.text,t,e));if(f.length>0)return f}}if(t?.role!=="user"&&t?.role!=="assistant"){const l=Be(t?.text||"");if(t?.role==="system"&&!l)return[];const c=!!t?.cardTitle&&String(t.cardTitle).toLowerCase()!=="system";if(t?.role==="system"&&!c)return[Al(l||t?.text||"",pe(t?.createdAt||t?.time))];const d=t?.role==="system"&&(!t?.cardTitle||String(t.cardTitle).toLowerCase()==="system");return Z({title:t?.cardTitle||(t?.role==="system"?"System":"PilotSwarm"),timestamp:pe(t?.createdAt||t?.time),body:Ze(t?.text||""),width:Math.max(20,e),titleColor:t?.cardTitleColor||(t?.role==="system"?"yellow":"cyan"),borderColor:t?.cardBorderColor||"gray",...d?{bodyColor:"gray",fitToContent:!0}:{}})}const n=qt(It(Ze(t?.text||""),{width:e,tableMode:s.tableMode})),i=kl(n,t?.pendingPhase==="cancelling"?"red":t?.role==="user"?Ss:null),o=s.skipPrefix?[]:wl(t,s);if(i.length===0)return o.length>0?[o]:[];if(xl(i))return o.length>0?[o,...i]:i;const r=[];let a=o.length===0;for(const l of i){if(!Array.isArray(l)){a||(r.push(o),a=!0),r.push(l);continue}a?r.push(l):(r.push([...o,...l]),a=!0)}return r}const Rl=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 Ll(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 Fl=new Set(["read_facts","facts_search","facts_similar","facts_read_uncrawled","facts_tombstone_stats"]),$l=new Set(["store_fact","delete_fact","facts_set_crawled","facts_purge_tombstones","facts_force_purge"]);function Bl(t,e){const s=String(t||"").toLowerCase();return s==="search_skills"||s.includes("skill")?e?"loading skills…":"loaded skills":Fl.has(s)?e?"reading facts…":"read facts":$l.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 Dl(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=Bl(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 un(t,e={}){if(t?.ui?.chatViewMode==="summary")return[];const s=Ie(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 S=o.length-1;S>=0;S-=1)if(o[S]?.role==="user"){r=Number(o[S]?.createdAt||0);break}const a=Array.isArray(i?.activity)?i.activity:[];let l=0,c=0;for(let S=a.length-1;S>=0;S-=1){const E=a[S],T=E?.eventType,C=Number(E?.createdAt||0);if(!l&&T==="assistant.turn_start"&&(l=C),!c&&(T==="assistant.turn_end"||T==="session.turn_completed")&&(c=C),l&&c)break}let d=0;r>c?d=r:l>c&&(d=l);let f=null;for(let S=a.length-1;S>=0;S-=1){const E=a[S];if(!(!E||Rl.has(E.eventType))){if(Number(E.createdAt||0)<=c)break;f=E;break}}const p=Number.isFinite(e.now)?e.now:Date.now(),h=d>0?Ll(p-d):"",g=String(e.spinnerFrame||"").trim()||"●",m=f?Dl(f):"",x=[{text:`${g} `,color:"cyan"},{text:"Working",color:"cyan"},...h?[{text:` · ${h}`,color:"gray"}]:[],...m?[{text:` — ${m}`,color:"gray"}]:[]],y=Math.max(24,Math.min(120,Math.floor(Number(e.maxWidth)||80)));return[z(x,y)]}function dn(t,e=80,s={}){const n=cn(t);if(!n||n.length===0)return[{text:"No messages yet.",color:"gray"}];const i=xe(t?.auth?.principal),o=t?.sessions?.activeSessionId,r=o?t?.sessions?.byId?.[o]:null,a=xe(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=zt(p,e,c);Kt(d,h);const g=n[f+1];g&&Bo(p,g)&&He(d[d.length-1]).trim().length>0&&d.push(Fo())}return d.length>0?d:[{text:"No messages yet.",color:"gray"}]}function fn(t,e=80,s={}){const n=bl(t);if(!n||n.length===0)return[];const i=Math.max(20,Number(e)||80),o=n.filter(m=>m.pendingPhase==="queued").length,r=n.filter(m=>m.pendingPhase==="pending").length,a=n.filter(m=>m.pendingPhase==="cancelling").length,l=n.filter(m=>m.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"}]],g=s?.tableMode?{tableMode:s.tableMode}:{};for(const[m,x]of n.entries()){Kt(h,zt(x,i,g));const y=n[m+1];y&&Bo(x,y)&&He(h[h.length-1]).trim().length>0&&h.push(Fo())}return h}function Hl(t){const e=cn(t),s=[],n=new Set;for(const i of e||[])for(const o of Dr(i?.text||"")){const r=`${o.sessionId}/${o.filename}`;n.has(r)||(n.add(r),s.push(o))}return s}function Gl(t){const e=cn(t),s=[],n=new Set;for(const i of e||[])for(const o of Hr(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 pn(t,e){const s=eo(t);if(!s)return"";const n=String(e||"").trim();return n?`${s}:${n}`:s}function Ul(t){return eo(t)||"(unknown)"}function Do(t,e={}){const s=Ie(t),n=t.sessions?.byId||{},i=Array.isArray(t.sessions?.flat)?t.sessions.flat:[],o=an(n),r=ln(i,n),a=Eo(e?.width);if(!s)return{color:"cyan",title:Te("Chat","cyan"),titleRight:null,animateTitleRight:!1};const l=Q(s.sessionId),c=s.isSystem?"yellow":"cyan",d=Te(s.isSystem?`⚙ ${ct(s,t.branding?.title||"PilotSwarm")}`:Zt(s)||"Chat",c),f=i.find(T=>T.sessionId===s.sessionId),p=No(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,g=Array.isArray(t.outbox?.bySessionId?.[s.sessionId])?t.outbox.bySessionId[s.sessionId]:[],m=t.ui?.chatViewMode==="summary"?null:yl(s,h,h?.chat||[],g),x=t.connection?.mode||"local",y=cl(s,x),S=Cl(m),E=S?[...y,...y.length?[{text:" · ",color:"gray"}]:[],...S]:y;return{color:s.isSystem?"yellow":"cyan",title:d,titleRight:E.length?E:null,animateTitleRight:!!m}}function jl(t){const e=t.sessions.activeSessionId;return e?t.history.bySessionId.get(e)?.activity||[]:[]}function hn(t,e=12){const s=jl(t),n=Ie(t),i=Te("Activity","gray");return n?.isGroup?{title:i,disabled:!0,lines:[{text:Qo,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 Ho(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 Go(t,e){return t==="orchestration"?"magenta":t==="activity"?"cyan":Ho(e)}function Wl(t){return t==="raw"?"raw summary":"pretty text"}function Vl(t){return t?.sessionId?`session-${t.sessionId}`:null}function ql(t,e){const s=Array.isArray(t.logs?.entries)?t.logs.entries:[],n=t.logs?.filter||{},i=Vl(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 Kl(t){const e=es(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:Go(t?.category,t?.level)},{text:`${e} `,color:"white",bold:!0},...s?[{text:`[${Q(s)}] `,color:"gray"}]:[],{text:`${n} `,color:Ho(t?.level),bold:!0},{text:t?.rawLine||t?.message||"",color:"white"}]}function zl(t){const e=t?.sessionId||(String(t?.orchId||"").startsWith("session-")?String(t.orchId).slice(8):"");return[{text:`${e?`[${Q(e)}] `:""}${t?.prettyMessage||t?.message||t?.rawLine||""}`,color:Go(t?.category,t?.level),bold:String(t?.level||"").toLowerCase()==="warn"||String(t?.level||"").toLowerCase()==="error"}]}function Yl(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:Wl(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=ql(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"?Kl(r):zl(r))]}function ni(t){return/\.(md|markdown|mdown|mkd|mdx)$/i.test(String(t||""))}function Ql(t){return/\.(json|jsonl)$/i.test(String(t||""))}function Xl(t){return we.map(e=>({text:e===t?`[${e}] `:`${e} `,color:e===t?"magenta":"gray",bold:e===t}))}function Jl(t=""){const e=String(t||"").split(`
|
|
50
|
+
`);return e.length>0?e.map(s=>({text:s,color:"white"})):[{text:"",color:"white"}]}function ii(t,{selected:e=!1,width:s=24,label:n=null}={}){const i=Math.max(8,s),o=ni(t)?"# ":Ql(t)?"{ ":"• ",r=Uo(`${o}${n||t}`,i).padEnd(i," ");return e?Ee(r):{text:r,color:ni(t)?"cyan":"white",bold:!1}}function me(t){return t.files?.filter?.scope==="allSessions"?"allSessions":"selectedSession"}function Zl(t,e={}){if(!t)return new Set;const{childMap:s}=rn(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 Yt(t,e=me(t)){const s=Ie(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=Zl(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 At(t){const e=me(t);Ie(t)?.sessionId;const s=t.files?.filter?.query||"",n=Yt(t,e),i=e==="allSessions"||n.length>1,o=[];for(const r of n){const a=Wt(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?`[${Q(r)}] ${c}`:c})}}return o.filter(r=>We(r.filename,s)||We(r.sessionId,s)||We(r.label,s))}function Le(t){const e=At(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(me(t)==="allSessions"){const r=Ie(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=Ie(t)?.sessionId||null,o=i&&t.files?.bySessionId?.[i]?.selectedFilename||null;return e.find(r=>r.sessionId===i&&r.filename===o)||e[0]}function mn(t,e={}){const s=Ie(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=me(t),l=t.files?.filter?.query||"",c=At(t),d=Le(t),f=d?.filename||null,p=Math.max(0,c.findIndex(L=>L.id===d?.id)),h=d?.sessionId&&f&&t.files?.bySessionId?.[d.sessionId]?.previews?.[f]||null,g=h||d?.entry||null,m=s?Q(s.sessionId):"",x=Yt(t,a),y=a!=="allSessions"&&x.some(L=>L&&L!==r),S=[...new Set([...Array.isArray(t.sessions?.flat)?t.sessions.flat.map(L=>L?.sessionId||L):[],...Object.keys(t.files?.bySessionId||{})])].filter(Boolean),E=a==="allSessions"&&S.some(L=>!t.files?.bySessionId?.[L]?.loaded||t.files?.bySessionId?.[L]?.loading),T=a==="allSessions"&&S.map(L=>t.files?.bySessionId?.[L]?.error).find(Boolean)||null,C=[Xl("files"),...s||a==="allSessions"?[]:[{text:"No session selected.",color:"gray"}]];if(a==="allSessions")E&&c.length===0?C.push({text:"Loading exported files across all sessions…",color:"gray"}):T&&c.length===0?C.push({text:T,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((L,K)=>ii(L.filename,{selected:K===p,width:n,label:L.label})));else if(s){const L=r?t.files?.bySessionId?.[r]:null;Array.isArray(L?.entries)&&L.entries;const K=c.filter(P=>x.includes(P.sessionId));L?.loading?C.push({text:"Loading exported files…",color:"gray"}):L?.error?C.push({text:L.error,color:"red"}):K.length===0&&x.every(P=>{const F=t.files?.bySessionId?.[P]?.entries;return!Array.isArray(F)||F.length===0})?(C.push({text:l?`No artifacts matched "${l}" for this ${y?"session tree":"session"}.`:`No exported files for this ${y?"session tree":"session"} yet.`,color:"gray"}),C.push({text:l?"Clear the query or upload an artifact to this session.":y?"Artifacts exported by this session or any child session will appear here.":"Agents must write/export artifacts before they appear here.",color:"gray"})):C.push(...K.map((P,F)=>ii(P.filename,{selected:F===p,width:n,label:P.label})))}let _,k;!s&&a!=="allSessions"?(k=[{text:"Preview",color:"cyan",bold:!0}],_=[{text:"No session selected.",color:"gray"}]):f?h?.loading?(k=[{text:`Preview: ${f}`,color:"cyan",bold:!0},...(a==="allSessions"||d?.sessionId&&d.sessionId!==r)&&d?.sessionId?[{text:` · ${Q(d.sessionId)}`,color:"gray"}]:[]],_=[{text:"Loading file preview…",color:"gray"}]):h?.error?(k=[{text:`Preview: ${f}`,color:"cyan",bold:!0},...(a==="allSessions"||d?.sessionId&&d.sessionId!==r)&&d?.sessionId?[{text:` · ${Q(d.sessionId)}`,color:"gray"}]:[]],_=[{text:h.error,color:"red"}]):(k=[{text:`Preview: ${f}`,color:"cyan",bold:!0},...(a==="allSessions"||d?.sessionId&&d.sessionId!==r)&&d?.sessionId?[{text:` · ${Q(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"}]:[]],_=h?.renderMode==="markdown"?qt(It(h?.content||"",{width:i})):Jl(h?.content||"")):(k=[{text:"Preview",color:"cyan",bold:!0}],_=[{text:"Select a file to preview it here.",color:"gray"}]);const R=a==="allSessions"?"Files: all sessions":s?`Files: ${m}${y?" tree":""}`:"Files",N=a==="allSessions"?"all sessions":s?`${m}${y?" tree":""}`:"Files",O=a==="allSessions"?`Artifacts${c.length>0?` [${c.length}]`:""}`:`Artifacts${y?" tree":""}${c.length>0?` [${c.length}]`:""}`,U=l?` · @${l}`:"";return{panelTitle:[{text:`${R}${U}`,color:"magenta",bold:!0}],panelTitleMobile:[{text:`${N}${U}`,color:"magenta",bold:!0}],listTitle:[{text:`${O}${U}`,color:"cyan",bold:!0}],listLines:C,listBodyLines:C.slice(1),selectedIndex:p,selectedFilename:f,selectedSessionId:d?.sessionId||null,scope:a,previewTitle:k,previewLines:_,previewContent:h?.content||"",previewContentType:h?.contentType||"",previewRenderMode:h?.renderMode||null,previewIsBinary:g?.isBinary===!0,previewSizeBytes:g?.sizeBytes??null,previewUploadedAt:g?.uploadedAt||"",previewSource:g?.source||null,previewError:h?.error||null,previewLoading:!!h?.loading,previewScrollOffset:t.ui.scroll.filePreview||0,fullscreen:!!t.files?.fullscreen,fullscreenTitle:[{text:R,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 ec(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 tc(t){const e=t.ui.focusRegion,s=t.ui.fullscreenPane||null,n=Ie(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(S=>S?.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===v.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 m=(t.ui?.chatViewMode==="summary"?"summary":"transcript")==="summary"?"s transcript":"s summary",x={[v.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",[v.CHAT]:`${m} · 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`,[v.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`,[v.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`,[v.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 y=x[e]||x[v.SESSIONS];return Ro(Ie(t))&&(y=`ctrl-x stop · ${y}`),{left:t.ui.statusText,right:y}}function Ke(t){return(t||[]).reduce((e,s)=>e+String(s?.text||"").length,0)}function z(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 Ce(t){return Array.from(String(t||"")).length}function Uo(t,e){const s=String(t||"");return e<=0?"":Ce(s)<=e?s:e===1?Array.from(s)[0]||"":`${Array.from(s).slice(0,e-1).join("")}…`}function De(t,e){const s=Uo(t,e),n=Math.max(0,e-Ce(s));return s+" ".repeat(n)}function D(t,e="white",s={}){return{text:String(t||""),color:e,...s}}function se(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 oi(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 jo(t,e=18){const s=String(t||"").replace(/\s+/g," ").trim();return s?Ce(s)>e?`${Array.from(s).slice(0,Math.max(1,e-1)).join("")}…`:s:""}function sc(t){const e=t?.data;if(typeof e=="string")return e;if(e&&typeof e=="object"){if(typeof e.content=="string")return e.content;if(typeof e.text=="string")return e.text;if(typeof e.message=="string")return e.message;if(typeof e.question=="string")return e.question}return""}function Wo(t=[]){const e=new Set,s=[];for(const n of t){const i=String(n||"").trim();if(!i)continue;const o=i.toLowerCase();e.has(o)||(e.add(o),s.push(i))}return s.join(" | ")}function nc(t,e=""){return Wo([t?.data?.reason==="cron_at"?"cron":t?.data?.reason,t?.data?.detail,t?.data?.message,t?.data?.error,e])}function ic(t,e=""){return Wo([t?.data?.message,t?.data?.detail,t?.data?.error,e])}function es(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 oc=300*1e3,rc="last 5m";function gn(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-oc,endMs:e,label:rc}}function ac(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 Vo(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 lc=new Set(["wait","timer","cron_start","cron_fire","cron_cancel","spawn","cmd_recv","cmd_done"]);function cc(t){return lc.has(t)}function uc(t){const e=pe(t?.createdAt),s=es(t?.workerNodeId),n=sc(t),i=jo(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 ${bt(t?.data?.seconds??0)}`};case"session.wait_completed":return{...r,type:"timer",color:"yellow",detail:`${bt(t?.data?.seconds??0)} up`};case"session.lossy_handoff":{const a=ic(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 ${nc(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||Q(t?.data?.childSessionId)||"agent"}`};case"session.cron_started":return{...r,type:"cron_start",color:"magenta",detail:`cron ${bt(t?.data?.intervalSeconds??0)}`};case"session.cron_at_scheduled":case"session.cron_at_started":return{...r,type:"cron_start",color:"magenta",detail:`cron ${_s(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 ${_s(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 qo(t=[]){const e=[];for(const s of t||[]){const n=uc(s);n&&e.push({...n,nodeLabel:cc(n.type)?"orch":n.nodeLabel||"orch"})}return e}function dc(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 fc(t){const e=String(t?.error||"").trim();if(!e)return null;const s=sn(t);if(!s)return null;const n=t?.updatedAt?Number(t.updatedAt):Date.now(),i=Number.isFinite(n)?n:Date.now();return{time:pe(i),createdAtMs:i,nodeLabel:"orch",color:s==="failed"?"red":"yellow",detail:`${s==="failed"?"ERR":"WARN"} ${jo(e,20)||(s==="failed"?"error":"warning")}`,type:s==="failed"?"error":"warning"}}function pc(t,e){const s=fc(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 hc(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=qo(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 mc(t,e){const s=new Set;for(const n of t.history.bySessionId.values())for(const i of n?.events||[]){if(!Vo(i,e))continue;const o=es(i?.workerNodeId);o&&s.add(o)}return Array.from(s).sort((n,i)=>n.localeCompare(i))}function gc(t,e,s){const n=[{text:De("TIME",e),color:"white",bold:!0},{text:" ",color:null}];return t.forEach((i,o)=>{o>0&&n.push({text:" ",color:null}),n.push({text:De(i,s),color:"white",bold:!0})}),n}function yc(t,e,s){return D(`${"-".repeat(e)} ${t.map(()=>"─".repeat(s)).join(" ")}`,"gray")}function Sc(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=se(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(se(o.kvTotalValueBytes)),i=s<=40?a.join(" · "):r.join(" | "),i||(i="orchestration stats unavailable")}return s<=52?[z([{text:"Stats ",color:"cyan",bold:!0},{text:i,color:"white"}],Math.max(18,s))]:Z({title:"Stats",body:i,width:Math.max(24,s),titleColor:"cyan",borderColor:"gray",fitToContent:!0}).slice(0,-1)}function bc(t,e,s,n){const i=e.includes(t.nodeLabel)?t.nodeLabel:e.includes("…")?"…":e[e.length-1],o=[{text:De(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:De(t.detail||"",n),color:t.color||"white",bold:!!t.bold,underline:!!t.underline,...t.completedTurn!=null?{completedTurn:t.completedTurn}:{}}):o.push({text:De("│",n),color:"gray"})}),o}function wc(t,e){const s=[];return t.forEach((n,i)=>{i>0&&s.push({text:" ",color:null}),s.push({text:De(n,e),color:"white",bold:!0})}),s}const xc=new Set(["low","medium","high","xhigh","minimal","none"]);function Ic(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 ri(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 je(t){return Number(t||0).toLocaleString("en-US")}function Ec(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 vc(t,{expanded:e,selected:s,maxWidth:n}){const i=e?"v":">",o=Ic(t?.model),r=t?.durationMs!=null?`${(Number(t.durationMs)/1e3).toFixed(1)}s`:"n/a",a=`${i} Mod: ${o} tok ${ri(t?.tokensInput)}/${ri(t?.tokensOutput)} dur ${r}`,l=[];if(s?l.push(Ee(De(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?`${je(t.durationMs)} ms`:null],["tokens",`${je(t?.tokensInput)} in / ${je(t?.tokensOutput)} out`],["cache",`${je(t?.tokensCacheRead)} read / ${je(t?.tokensCacheWrite)} write`],["tools",`${je(t?.toolCalls)} calls / ${je(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 Tc(t,e,s,n={}){const i=!!n?.allowWideColumns,o=Sc(t,e,s),r=t.history.bySessionId.get(e.sessionId),a=pc(dc(qo(r?.events||[])),e);if(a.length===0)return{stickyLines:o,lines:[D("No events yet - interact with this session to populate the sequence diagram.")]};const l=gn(t),c=a.filter(N=>ac(N,l)),d=(c.length>0?c:a).slice(-48),f=hc(t,l.startMs,l.endMs),p=Array.from(new Set(d.map(N=>N.nodeLabel).filter(N=>N&&N!=="orch"))).sort((N,O)=>N.localeCompare(O)),h=f.length>0?f:p,g=8,m=Math.max(18,s),x=Math.max(1,Math.floor((m-g-1)/6));let y=["orch",...h];if(!i&&y.length>x){const N=Math.max(1,x-1);y=[...y.slice(0,N),"…"]}const S=Math.max(0,y.length-1),E=Math.max(4,Math.floor((m-g-1-S)/Math.max(1,y.length))),T=n?.sequenceExpansion||null,C=T?Ec(r?.events||[]):null,_=T?new Set((T.expandedTurns||[]).map(Number)):null,k=T&&T.selectedTurn!=null?Number(T.selectedTurn):null,R=[];for(const N of d)if(R.push(bc(N,y,g,E)),T&&N.completedTurn!=null){const O=Number(N.completedTurn),U=C.get(O);if(U)for(const L of vc(U,{expanded:_.has(O),selected:k===O,maxWidth:m}))R.push(L)}return{stickyLines:[...o,D(`Window: ${l.label}`,"gray"),gc(y,g,E),yc(y,g,E)],lines:R}}function Ac(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 Cc(t,e=null){const s=t?.events||[];for(let n=s.length-1;n>=0;n-=1){if(e&&!Vo(s[n],e))continue;const i=es(s[n]?.workerNodeId);if(i)return i}return null}function kc(t,e,s,n){const i=s>=16?t?.isSystem?ct(t,e):t?.title||Q(t?.sessionId):Q(t?.sessionId),o=t?.isSystem?"⚙ ":`${Co(t)||"."} `,r=De(`${o}${i}`,s);return n?Ee(r):{text:r,color:t?.isSystem?"yellow":vt(t),bold:!!t?.isSystem}}function Mc(t,e,s={}){const n=!!s?.allowWideColumns,i=Ac(t);if(i.length===0)return[D("No sessions available for the node map.","gray")];const o=gn(t),r=new Map,a=mc(t,o);let l=0,c=0;for(const y of i){const S=t.sessions.byId[y];if(!S)continue;const E=t.history.bySessionId.get(y);E?.events||(l+=1);const T=Cc(E,o);!T||!a.includes(T)||(c+=1,r.has(T)||r.set(T,[]),r.get(T).push(S))}if(a.length===0)return[D(`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 y=Math.max(0,f-1),S=[],E=a.slice(0,y);for(const T of a.slice(y))S.push(...r.get(T)||[]);r.set("…",S),p=[...E,"…"]}const h=Math.max(0,p.length-1),g=Math.max(8,Math.floor((d-h)/Math.max(1,p.length))),m=p.reduce((y,S)=>Math.max(y,(r.get(S)||[]).length),0),x=[D(`Window: ${o.label}`,"gray"),wc(p,g),D(p.map(()=>"─".repeat(g)).join(" "),"gray")];for(let y=0;y<m;y+=1){const S=[];p.forEach((E,T)=>{T>0&&S.push({text:" ",color:null});const C=(r.get(E)||[])[y];if(!C){S.push({text:" ".repeat(g),color:null});return}S.push(kc(C,t.branding?.title||"PilotSwarm",g,C.sessionId===t.sessions.activeSessionId))}),x.push(S)}return l>0&&(x.push(D("","gray")),x.push(D(`Loading worker history for ${l} session(s)…`,"gray"))),c===0&&(x.push(D("","gray")),x.push(D(`No sessions mapped onto worker nodes in the ${o.label} window.`,"gray"))),x}function Pc(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 g=z([{text:`${h.providerId}`,color:"cyan",bold:!0},{text:` (${h.providerType||"provider"})`,color:"gray"}],o);r.push(g),a.push(null);for(const m of h.models||[]){const x=Array.isArray(s.items)?s.items.findIndex(T=>T.id===m.id):-1,y=x===i,S=z([{text:"· ",color:"gray"},{text:m.modelName||m.qualifiedName||m.id,color:"white",bold:!!m.isDefault},...m.cost?[{text:` [${m.cost}]`,color:"gray"}]:[],...m.isDefault?[{text:" ← current default",color:"gray"}]:[]],o),E=y?Ee(S.map(T=>T.text).join("").padEnd(o," ")):S;y&&(l=r.length),r.push(E),a.push(x>=0?x: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"}]]:[],[{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,g)=>Array.isArray(g)?Math.max(h,Ke(g)):Math.max(h,String(g?.text||"").length),0)+4),e)}}function Nc(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,g=z([{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?Ee(g.map(m=>m.text).join("").padEnd(o," ")):g}),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,Ke(p)):Math.max(f,String(p?.text||"").length),0)+4),e)}}function Oc(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=z([{text:"· ",color:"gray"},{text:String(d?.label||d?.id||"effort"),color:"white",bold:!0},...d?.isDefault?[{text:" ← model default",color:"gray"}]:[]],o);return p?Ee(h.map(g=>g.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,Ke(f)):Math.max(d,String(f?.text||"").length),0)+4),e)}}function _c(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((d,f)=>{const p=f===i,h=z([{text:"· ",color:"gray"},{text:String(d?.label||d?.id||"tier"),color:"white",bold:!0},...d?.isDefault?[{text:" ← model default",color:"gray"}]:[]],o);return p?Ee(h.map(g=>g.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 context window: ${a.id}`:"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:c,idealWidth:Math.min(Math.max(46,r.reduce((d,f)=>Array.isArray(f)?Math.max(d,Ke(f)):Math.max(d,String(f?.text||"").length),0)+4),e)}}function Rc(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"?"+ ":"🗂 ",g=z([{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?Ee(g.map(m=>m.text).join("").padEnd(o," ")):g}),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,Ke(f)):Math.max(d,String(f?.text||"").length),0)+4),e)}}function Lc(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,Ce(o||"(untitled session)")+18,Ce(r)+18),e)}}function Fc(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,Ce(o)+18),e)}}function $c(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?Mo(o,t.branding?.title):Q(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,Ce(n||"~/path/to/file.md")+20,Ce(r)+20),e)}}function yn(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?Ee(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 Ko(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&&!!xe(s?.principal):t.kind==="owner"?Array.isArray(e?.ownerKeys)&&e.ownerKeys.includes(t.ownerKey):!1:!1}function ai(t=[],e={},s={}){if(e?.all===!0)return"All sessions";const n=t.filter(i=>i?.kind!=="all"&&Ko(i,e,s)).map(i=>i.kind==="me"?"Me":i.label);return n.length>0?n.join(" + "):"All sessions"}function Bc(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=Ko(d,i,o),h=d.kind==="system"?"yellow":d.kind==="unowned"?"gray":d.kind==="all"?"cyan":"white",g=[{text:p?"[x] ":"[ ] ",color:p?"cyan":"gray",bold:p},{text:d.label||d.id,color:h,bold:p}];return f===r?Io(g,{preserveColors:!0}):g}),c=[[{text:"Active: ",color:"gray"},{text:ai(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)?Ke(f):Ce(f?.text||"")),0)+8,Ce(ai(n,i,o))+16),e)}}function Dc(t,e=96){const s=t.ui.modal;return!s||s.type!=="logFilter"?null:yn(s,t.logs?.filter||{},e,"Log Filters","Choose how the log pane is filtered and rendered.")}function Hc(t,e=88){const s=t.ui.modal;return!s||s.type!=="filesFilter"?null:yn(s,t.files?.filter||{},e,"Files Filter","Choose whether the files browser shows the selected session tree or aggregates artifacts across all sessions.")}function Gc(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,g)=>{const m=t.files?.bySessionId?.[g.sessionId]?.downloads?.[g.filename];return h+(m?.localPath?1:0)},0),c=Math.max(0,r.length-l),d=n.map((h,g)=>{let m;if(h.kind==="downloadAll")m=z([{text:"dl ",color:"cyan",bold:!0},{text:"Download All",color:"white",bold:!0},{text:` [${c} pending]`,color:"gray"}],o);else if(h.kind==="url")m=z([{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 x=t.files?.bySessionId?.[h.sessionId]?.downloads?.[h.filename];m=z([{text:x?.localPath?"ok ":"dl ",color:x?.localPath?"green":"cyan",bold:!0},{text:`${Q(h.sessionId)}/`,color:"gray"},{text:h.filename,color:"white"}],o)}return g!==i?m:Ee(m.map(x=>x.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,g=t.files?.bySessionId?.[f.sessionId]?.downloads?.[f.filename]||null;p=[[{text:f.filename,color:"white",bold:!0}],[{text:h?Mo(h,t.branding?.title):Q(f.sessionId),color:"gray"}],...g?.localPath?[[{text:`Saved to: ${g.localPath}`,color:"white"}]]:s.exportDirectory?[[{text:`Save location: ${s.exportDirectory}`,color:"white"}]]:[],[{text:"",color:"gray"}],[{text:g?.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,g)=>Array.isArray(g)?Math.max(h,Ke(g)):Math.max(h,String(g?.text||"").length),0)+4),e)}}function G(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 zo(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 Uc(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 Nt(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 yt(t){return["session","fleet","users"].includes(t)?t:"session"}function ts(t,e){const s=yt(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"}),z(n,e)}function jc(t,e,s){if(!e)return[D("No session selected.")];const n=t.sessionStats?.bySessionId?.[e.sessionId]||null;if(!n||n.loading&&!n.summary)return[D("Loading session stats...")];const i=n.summary;if(!i)return[D("Session stats unavailable.")];const o=[],r=Math.max(24,s);o.push(ts("session",r)),o.push(D("")),o.push(z([{text:"Session ",color:"cyan",bold:!0},{text:Q(e.sessionId),color:"white"}],r));const a=e.isSystem?"system":e.owner?"user":"unowned",l=e.isSystem?"system":e.owner?nn(e.owner):"(?) unowned",c=e.owner?.email||"—";o.push(z([{text:"Owner ",color:"cyan",bold:!0},{text:l,color:e.owner?"white":"gray"}],r)),o.push(z([{text:"Email ",color:"cyan",bold:!0},{text:c,color:e.owner?.email?"white":"gray"}],r)),o.push(z([{text:"Type ",color:"cyan",bold:!0},{text:a,color:a==="user"?"white":"gray"}],r)),i.agentId&&o.push(z([{text:"Agent ",color:"cyan",bold:!0},{text:i.agentId,color:"white"}],r));const d=pn(i.model||e.model,i.reasoningEffort||e.reasoningEffort);d&&o.push(z([{text:"Model ",color:"cyan",bold:!0},{text:d,color:"white"}],r)),e.createdAt&&o.push(z([{text:"Created ",color:"cyan",bold:!0},{text:Nt(e.createdAt),color:"white"}],r)),e.updatedAt&&o.push(z([{text:"Updated ",color:"cyan",bold:!0},{text:Nt(e.updatedAt),color:"white"}],r)),o.push(D(""));const f=Array.isArray(n.tokensByModel)?n.tokensByModel:[];f.length>1&&(o.push(...Z({title:"Models",body:f.map(_=>`${Ul(_.model)} · ${_.turnCount||0} turns · ${G(_.totalTokensInput)} in / ${G(_.totalTokensOutput)} out`).join(`
|
|
51
|
+
`),width:r,titleColor:"cyan",borderColor:"gray",fitToContent:!0})),o.push(D("")));const p=(i.tokensInput||0)+(i.tokensOutput||0),h=i.cacheHitRatio,g=h==null?"—":`${(h*100).toFixed(1)}%`;o.push(...Z({title:"Tokens",body:Ve([["Input",G(i.tokensInput)],["Output",G(i.tokensOutput)],["Total",G(p)],["Cache Read",G(i.tokensCacheRead)],["Cache Write",G(i.tokensCacheWrite)],["Hit Ratio",g]]),width:r,titleColor:"green",borderColor:"gray",fitToContent:!0})),o.push(D("")),o.push(...Z({title:"Persistence",body:Ve([["Snapshot",se(i.snapshotSizeBytes)],["Uncompressed",i.rawSizeBytes?se(i.rawSizeBytes):null],["Compression",oi(i.rawSizeBytes,i.snapshotSizeBytes)],["Dehydrations",String(i.dehydrationCount)],["Hydrations",String(i.hydrationCount)],["Lossy Handoffs",String(i.lossyHandoffCount)],["Last Dehydrated",i.lastDehydratedAt?Nt(i.lastDehydratedAt):null],["Last Hydrated",i.lastHydratedAt?Nt(i.lastHydratedAt):null]]),width:r,titleColor:"yellow",borderColor:"gray",fitToContent:!0}));const m=n.treeStats?.tree;if(m&&m.sessionCount>1){const _=m.cacheHitRatio,k=_==null?"—":`${(_*100).toFixed(1)}%`,R=(m.totalTokensInput||0)+(m.totalTokensOutput||0);o.push(D("")),o.push(...Z({title:`Tree (${m.sessionCount} sessions)`,body:Ve([["Input",G(m.totalTokensInput)],["Output",G(m.totalTokensOutput)],["Total",G(R)],["Cache Read",G(m.totalTokensCacheRead)],["Cache Write",G(m.totalTokensCacheWrite)],["Hit Ratio",k],["Snapshot",se(m.totalSnapshotSizeBytes)],["Uncompressed",m.totalRawSizeBytes?se(m.totalRawSizeBytes):null],["Compression",oi(m.totalRawSizeBytes,m.totalSnapshotSizeBytes)],["Dehydrations",String(m.totalDehydrationCount)],["Hydrations",String(m.totalHydrationCount)]]),width:r,titleColor:"magenta",borderColor:"gray",fitToContent:!0}));const N=Array.isArray(n.treeStats?.byModel)?n.treeStats.byModel:[];N.length>1&&(o.push(D("")),o.push(...Z({title:"Tree By Model",body:Yc(N),width:r,titleColor:"cyan",borderColor:"gray",fitToContent:!0})))}const x=Array.isArray(n.skillUsage)?n.skillUsage:[];x.length>0&&(o.push(D("")),o.push(...Z({title:`Skills (${x.length})`,body:li(x,r),width:r,titleColor:"cyan",borderColor:"gray",fitToContent:!0})));const y=n.treeSkillUsage,S=Array.isArray(y?.rolledUp)?y.rolledUp:[],E=Array.isArray(y?.perSession)?y.perSession.length:0;S.length>0&&E>1&&(o.push(D("")),o.push(...Z({title:`Tree Skills (${S.length})`,body:li(S,r),width:r,titleColor:"cyan",borderColor:"gray",fitToContent:!0})));const T=n.factsStats,C=n.treeFactsStats;if(T&&Array.isArray(T.rows)&&T.rows.length>0){o.push(D(""));const _=Yo(T.rows),k=_?_.split(`
|
|
52
|
+
`).length:0,R=`${T.totalCount} · ${se(T.totalBytes)}`;let N=_;C&&C.totalCount>T.totalCount&&(N+=`
|
|
53
|
+
Tree (${C.sessionIds.length} sessions): ${C.totalCount} · ${se(C.totalBytes)}`),k>0&&o.push(...Z({title:`Facts (${R})`,body:N,width:r,titleColor:"blue",borderColor:"gray",fitToContent:!0}))}return o}function Ve(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 ss(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 kt(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 li(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",g=String(f.name||"(unknown)");return[ss(`${h} ${g}`,l),n[p]]}),d=kt(c);return t.length>s.length?`${d}
|
|
56
|
+
… ${t.length-s.length} more`:d}function Yo(t){const s=t.slice().sort((n,i)=>(i.factCount||0)-(n.factCount||0)).map(n=>[String(n.namespace||"(other)"),String(n.factCount||0),se(n.totalValueBytes||0)]);return kt(s)}function Wc(t){const e=t.oldestUnreconciledAgeSeconds==null?"-":bt(Math.max(0,Number(t.oldestUnreconciledAgeSeconds)||0));return kt([["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 Vc(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 qc(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[ss(`${Vc(f.operation)}${h}`,l),n[p],i[p]]}),d=kt(c);return t.length>s.length?`${d}
|
|
57
|
+
… ${t.length-s.length} more`:d}function Kc(t,e){const s=t.fleetStats;if(!s||s.loading&&!s.data)return[D("Loading fleet stats...")];const n=s.data;if(!n)return[D("Fleet stats unavailable.")];const i=[],o=Math.max(24,e);i.push(ts("fleet",o)),i.push(D(""));const r=n.windowStart?`Since: ${zo(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(z([{text:r,color:"cyan"},{text:a?` ${a}`:"",color:"gray"}],o)),i.push(z([{text:`Sessions: ${n.totals.sessionCount}`,color:"white"},{text:` Tokens: ${G(n.totals.totalTokensInput)} in / ${G(n.totals.totalTokensOutput)} out`,color:"white"}],o)),i.push(D(""));const l=new Map;for(const m of n.byAgent||[]){const x=m.model||"(default)",y=l.get(x)||{totalTokensInput:0,totalTokensOutput:0,totalTokensCacheRead:0,totalTokensCacheWrite:0,totalSnapshotSizeBytes:0,turnCount:0};y.totalTokensInput+=Number(m.totalTokensInput)||0,y.totalTokensOutput+=Number(m.totalTokensOutput)||0,y.totalTokensCacheRead+=Number(m.totalTokensCacheRead)||0,y.totalTokensCacheWrite+=Number(m.totalTokensCacheWrite)||0,y.totalSnapshotSizeBytes+=Number(m.totalSnapshotSizeBytes)||0,y.turnCount+=Number(m.turnCount)||0,l.set(x,y)}if(l.size>0){const m=[];for(const[x,y]of l.entries()){const S=y.totalTokensInput>0?y.totalTokensCacheRead/y.totalTokensInput:null;m.push(x),m.push(Sn(y,S)),m.push("")}i.push(...Z({title:"Tokens By Model",body:m.join(`
|
|
58
|
+
`).trimEnd(),width:o,titleColor:"cyan",borderColor:"gray",fitToContent:!0})),i.push(D(""))}const c=n.totals.cacheHitRatio,d=c==null?"—":`${(c*100).toFixed(1)}%`;i.push(...Z({title:"Fleet Totals",body:Ve([["Sessions",String(n.totals.sessionCount)],["Tokens In",G(n.totals.totalTokensInput)],["Tokens Out",G(n.totals.totalTokensOutput)],["Total Tokens",G(n.totals.totalTokensInput+n.totals.totalTokensOutput)],["Cache Read",G(n.totals.totalTokensCacheRead)],["Cache Write",G(n.totals.totalTokensCacheWrite)],["Hit Ratio",d],["Snapshots",se(n.totals.totalSnapshotSizeBytes)]]),width:o,titleColor:"green",borderColor:"gray",fitToContent:!0}));const f=(Array.isArray(s.skillUsage?.rows)?s.skillUsage.rows:[]).filter(m=>!(m&&m.agentId==="facts-manager"&&String(m.name||"").startsWith("skills/")));f.length>0&&(i.push(D("")),i.push(...Z({title:`Fleet Skills (${f.length})`,body:zc(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 m=p.reduce((x,y)=>x+(Number(y.calls)||0),0);i.push(D("")),i.push(...Z({title:`Fleet Retrieval (${G(m)})`,body:qc(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(D(""));const m=`${h.totalCount} · ${se(h.totalBytes)}`;i.push(...Z({title:`Shared Facts (${m})`,body:Yo(h.rows),width:o,titleColor:"blue",borderColor:"gray",fitToContent:!0}))}const g=s.factsTombstoneStats;return g&&Number(g.pendingTotal)>0&&(i.push(D("")),i.push(...Z({title:`Fact Tombstones (${Number(g.pendingTotal)||0})`,body:Wc(g),width:o,titleColor:"yellow",borderColor:"gray",fitToContent:!0}))),i}function zc(t,e){const n=t.slice().sort((g,m)=>{const x=C=>C==="learned"?1:0,y=x(g.kind)-x(m.kind);if(y!==0)return y;const S=g.agentId?0:1,E=m.agentId?0:1;if(S!==E)return S-E;const T=String(g.agentId||"").localeCompare(String(m.agentId||""));return T!==0?T:String(g.name||"").localeCompare(String(m.name||""))}).slice(0,15),i=n.map(g=>`${g.invocations||0} inv`),o=n.map(g=>`${g.sessionCount||0} sess`),r=i.reduce((g,m)=>Math.max(g,m.length),0),a=o.reduce((g,m)=>Math.max(g,m.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((g,m)=>{const x=g.kind==="learned"?"L":"S",y=g.agentId||".",S=String(g.name||"(unknown)");return[ss(`${x} ${y}/${S}`,f),i[m],o[m]]}),h=kt(p);return t.length>n.length?`${h}
|
|
59
|
+
… ${t.length-n.length} more`:h}function Yc(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(Sn(n,i)),s.push("")}return s.join(`
|
|
60
|
+
`).trimEnd()}function Sn(t,e){const s=e==null?"—":`${(e*100).toFixed(1)}%`,n=(Number(t.totalTokensInput)||0)+(Number(t.totalTokensOutput)||0),i=[["Input",G(t.totalTokensInput||0)],["Output",G(t.totalTokensOutput||0)],["Total",G(n)],["Turns",G(t.turnCount||0)],["Cache Read",G(t.totalTokensCacheRead||0)],["Cache Write",G(t.totalTokensCacheWrite||0)],["Hit Ratio",s],["Snapshot",se(t.totalSnapshotSizeBytes||0)]];return Number.isFinite(Number(t.totalOrchestrationHistorySizeBytes))&&i.push(["Orch",se(t.totalOrchestrationHistorySizeBytes||0)]),Ve(i).split(`
|
|
61
|
+
`).map(r=>` ${r}`).join(`
|
|
62
|
+
`)}function Ls(t){return t?.ownerKind==="system"?"System":t?.ownerKind==="unowned"?"Unowned":nn(t?.owner,"Unknown User")}function Qc(t){if(t?.ownerKind!=="user")return"";const e=String(t?.owner?.email||"").trim(),s=Ls(t);return e&&e!==s?e:""}function Xc(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=ss(String(o.model||"(default)"),Math.max(12,e-10));i.push(`${r} · ${o.sessionCount||0} sess · ${o.turnCount||0} turns`),i.push(Sn(o,o.cacheHitRatio)),i.push("")}return s.length>n.length&&i.push(`… ${s.length-n.length} more models`),i.join(`
|
|
63
|
+
`).trimEnd()}function Jc(t,e){const s=t.fleetStats;if(!s||s.loading&&!s.userStats)return[D("Loading user stats...")];const n=s.userStats;if(!n)return[D("User stats unavailable.")];const i=[],o=Math.max(24,e);i.push(ts("users",o)),i.push(D(""));const r=n.windowStart?`Since: ${zo(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(z([{text:r,color:"cyan"},{text:a?` ${a}`:"",color:"gray"}],o)),i.push(z([{text:`Users: ${Array.isArray(n.users)?n.users.length:0}`,color:"white"},{text:` Sessions: ${n.totals.sessionCount||0}`,color:"white"}],o)),i.push(D(""));const l=n.totals.cacheHitRatio,c=l==null?"—":`${(l*100).toFixed(1)}%`;i.push(...Z({title:"User Totals",body:Ve([["Sessions",String(n.totals.sessionCount||0)],["Tokens In",G(n.totals.totalTokensInput||0)],["Tokens Out",G(n.totals.totalTokensOutput||0)],["Total Tokens",G((n.totals.totalTokensInput||0)+(n.totals.totalTokensOutput||0))],["Cache Read",G(n.totals.totalTokensCacheRead||0)],["Cache Write",G(n.totals.totalTokensCacheWrite||0)],["Hit Ratio",c],["Snapshots",se(n.totals.totalSnapshotSizeBytes||0)],["Orch Size",se(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=Qc(p),g=p.cacheHitRatio,m=g==null?"—":`${(g*100).toFixed(1)}%`,x=h?`${Ls(p)} <${h}>`:Ls(p),y=Ve([["Sessions",String(p.sessionCount||0)],["Tokens In",G(p.totalTokensInput||0)],["Tokens Out",G(p.totalTokensOutput||0)],["Total Tokens",G((p.totalTokensInput||0)+(p.totalTokensOutput||0))],["Cache Read",G(p.totalTokensCacheRead||0)],["Cache Write",G(p.totalTokensCacheWrite||0)],["Hit Ratio",m],["Snapshots",se(p.totalSnapshotSizeBytes||0)],["Orch Size",se(p.totalOrchestrationHistorySizeBytes||0)]]),S=Xc(p,o);i.push(D("")),i.push(...Z({title:`${x} (${p.sessionCount||0})`,body:S?`${y}
|
|
64
|
+
|
|
65
|
+
${S}`:y,width:o,titleColor:p.ownerKind==="user"?"cyan":"yellow",borderColor:"gray",fitToContent:!0}))}return d.length>f.length&&(i.push(D("")),i.push(D(`… ${d.length-f.length} more users`))),i}function Ue(t,e={}){const s=Ie(t),n=t.ui.inspectorTab,i=Math.max(18,Number(e?.width)||36),o=!!e?.allowWideColumns,r=Eo(i);if(s?.isGroup)return{title:Te("Inspector","magenta"),activeTab:n,tabs:we,disabled:!0,stickyLines:[],lines:[D(Qo,"gray")]};const a=s?Q(s.sessionId):"",l=n==="sequence"||n==="nodes"?gn(t):null,c=n==="nodes"?[...Te("Node Map","magenta"),...r?[]:[{text:` [${l.label}]`,color:"gray"}]]:s?n==="sequence"?[...Te(r?"Sequence":`Sequence: ${a}`,"magenta"),...r?[]:[{text:` [${l.label}]`,color:"gray"}]]:n==="logs"?[...Te(r?"Logs":`Logs: ${a}`,"magenta")]:n==="history"?[...Te(r?"History":`History: ${a}`,"magenta")]:n==="stats"?[...Te(r?"Stats":`Stats: ${a}`,"magenta"),{text:` [${yt(t.ui?.statsViewMode)}]`,color:"gray"}]:[...Te(r?"Files":`Files: ${a}`,"magenta")]:n==="stats"?`Stats: ${yt(t.ui?.statsViewMode).replace(/^./u,p=>p.toUpperCase())}`:"No session selected";let d,f=[];switch(n){case"sequence":{const p=s?Tc(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?Yl(t,s):["No session selected."];break;case"nodes":d=Mc(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?su(t,s):["No session selected."];break;case"stats":d=yt(t.ui?.statsViewMode)==="users"?Jc(t,i):yt(t.ui?.statsViewMode)==="fleet"?Kc(t,i):s?jc(t,s,i):[ts("session",Math.max(24,i)),D(""),D("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:we,stickyLines:f,lines:d}}const Zc={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"},Qo="Select a session to see details.";function eu(t){const e=t.timestampMs?new Date(t.timestampMs).toISOString().slice(11,23):"???",s=Zc[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 tu(t){const e={...t};if(e.data)try{e.data=JSON.parse(e.data)}catch{}return JSON.stringify(e,null,2)}function su(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=tu(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=eu(n[r]);for(const l of a)o.push(l);r<n.length-1&&o.push({text:"────────────────────────────────",color:"gray"})}return o}function nu(t,e=88){const s=t.ui.modal;return!s||s.type!=="historyFormat"?null:yn(s,{format:t.executionHistory?.format||"pretty"},e,"Execution History Format","Choose the display format for duroxide execution history events.")}function ci(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 iu(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 g=p.id===r?" [current]":"",m=`${p.label}${g}`.slice(0,c);return h===i?Ee(m.padEnd(c," ")):[{text:m,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"}],ci([{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"}]),ci([{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 ou(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 ui(t){return new Map(t)}function ws(t){return new Set(t)}function ru(t){return Array.isArray(t)?[...t]:[]}function au(t){return Array.isArray(t)?[...t]:[]}const lu=5e3;function Fs(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 Xo(t){return!!(t&&!t.isSystem&&(t.isGroup||!t.parentSessionId&&!t.groupId))}function xs(t,e){return Fs(t,e).filter(s=>Xo(e[s]))}function cu(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 Jo(t,e){const s=cu(Object.values(e||{})),n=new Set;for(const i of t||[])s.has(i)&&n.add(i);return n}function uu(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 du(t,e,s){const n=Jo(t,e);if(!s||!e?.[s])return n;for(const i of uu(s,e))n.delete(i);return n}function fu(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 pu(t){return{...t||{}}}function ve(t){return{...t||{}}}function di(t){return{...t||{}}}function Ot(t){return{...t||{}}}function Is(t){return{scope:t?.scope==="allSessions"?"allSessions":"selectedSession",query:typeof t?.query=="string"?t.query:""}}function hu(t){return(Array.isArray(t)?t.filter(Boolean):[]).slice(-1e3)}function mu(t){return[v.SESSIONS,v.CHAT,v.INSPECTOR,v.ACTIVITY].includes(t)?t:null}function Es(t,e){const s=Array.isArray(t)?t.filter(Boolean):[],n=Math.max(Y,Number(e)||Y);return s.length>n?s.slice(-n):s}function $s(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(!$s(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)||!$s(t[i],e[i]))return!1;return!0}function fi(t={},e={}){let s=t||{};for(const[n,i]of Object.entries(e||{}))if(i!==void 0){if(n==="pendingQuestion"&&gu(t,i)){s===t&&(s={...t||{}}),s.pendingQuestion=null;continue}$s(t?.[n],i)||(s===t&&(s={...t||{}}),s[n]=i)}return s}function pi(t){if(!t)return"unknown";const e=t.status||"unknown";return t.cronActive===!0&&(e==="waiting"||e==="idle"||e==="unknown")?"cron_waiting":e}function hi(t,e,s){if(!e?.sessionId||e.isGroup)return e;const n=pi(e),i=t?.rowVisualStatus||pi(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>=lu?{...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 mi(t){return String(t?.question||"").trim()}function gu(t,e){const s=mi(t?.answeredPendingQuestion),n=mi(e);return!!(s&&n&&s===n)}function yu(t=[]){const e=(t||[]).find(n=>n?.sessionId&&n.isSystem&&ao(n)===0);return e?.sessionId?e.sessionId:(t||[]).find(n=>n?.sessionId)?.sessionId||null}function gi(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 yi(t={}){const e=String(t?.filterQuery||"").trim(),s=jt(t?.ownerFilter);return!!e||s.all!==!0}function Su(t,e=[]){const s=Tt(t),n=t.sessions?.activeSessionId||null;if(n&&s.some(o=>o.sessionId===n)||n&&t.sessions?.byId?.[n]&&!yi(t.sessions))return n;if(yi(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 yu(i)}function bu(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 pt(t,e){const s={...t,sessions:e},n=Su(s,Object.values(e.byId||{})),i=du(e.collapsedIds,e.byId,n);return{sessions:{...!fu(i,e.collapsedIds)?{...e,collapsedIds:i,flat:$e(Object.values(e.byId||{}),i,e.orderById,e.pinnedIds)}:e,activeSessionId:n},ui:bu(t,n)}}function Si(t={},e=0,s=[]){const n=pu(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 wu(t=[],e=[]){const s=$e(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 xu(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=>{const o=String(i?.token||"").trim();return o&&s.includes(o)})}function Iu(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=Object.prototype.hasOwnProperty.call(s,"activeSessionId"),d=Object.keys(t.sessions.byId||{}).length>0,f=o?{...t.ui.layout||{},...Zs(s.layoutAdjustments)}:t.ui.layout,p=a?d?xs(Vt(s.pinnedSessionIds),t.sessions.byId):Vt(s.pinnedSessionIds):t.sessions.pinnedIds,h=l?d?Jo(Os(s.collapsedSessionIds),t.sessions.byId):Os(s.collapsedSessionIds):t.sessions.collapsedIds,g=c?bo(s.activeSessionId):t.sessions.activeSessionId,m={...t.sessions,...i?{ownerFilter:jt(s.sessionOwnerFilter),ownerFilterExplicit:!0}:{},pinnedIds:p,collapsedIds:h,collapsedIdsExplicit:l?!0:t.sessions.collapsedIdsExplicit,activeSessionId:g,flat:a||l?$e(Object.values(t.sessions.byId),h,t.sessions.orderById,p):t.sessions.flat},x=d&&(i||a||l||c)?pt(t,m):{sessions:m,ui:t.ui};return{...t,sessions:x.sessions,ui:{...x.ui,themeId:n?s.themeId.trim():x.ui.themeId,chatViewMode:r?s.chatViewMode:x.ui.chatViewMode,layout:f}}}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:""},n=pt(t,s);return{...t,sessions:n.sessions,ui:n.ui}}case"sessions/ownerFilter":{const s={...t.sessions,ownerFilterExplicit:!0,ownerFilter:jt(e.filter)},n=pt(t,s);return{...t,sessions:n.sessions,ui:n.ui}}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===v.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:xu(e.prompt,e.promptCursor,t.ui.promptCursor),promptRows:ot(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 E of e.sessions){const T=t.sessions.byId[E.sessionId],C=hi(T,fi(T,E),i);s[E.sessionId]=C,!n&&C!==T&&(n=!0)}t.sessions.activeSessionId&&t.sessions.byId[t.sessions.activeSessionId]&&!t.sessions.byId[t.sessions.activeSessionId]?.isGroup&&!s[t.sessions.activeSessionId]&&(s[t.sessions.activeSessionId]={...t.sessions.byId[t.sessions.activeSessionId]},n=!0);const o=Object.keys(t.sessions.byId),r=Object.keys(s);if(o.length!==r.length&&(n=!0),!n){for(const E of r)if(!t.sessions.byId[E]){n=!0;break}}if(!n)return t;const a=Object.values(s),l=Object.keys(t.sessions.orderById||{}).length>0,c=gi(a),d=!!t.sessions.collapsedIdsExplicit,{orderById:f,nextOrderOrdinal:p}=l?Si(t.sessions.orderById,t.sessions.nextOrderOrdinal,a):wu(a,t.sessions.pinnedIds),h=d?ws(t.sessions.collapsedIds):c;if(d){const E=gi(Object.values(t.sessions.byId));for(const T of c)E.has(T)||h.add(T)}const g=xs(t.sessions.pinnedIds,s),m=Fs(t.sessions.selectedIds,s),x=$e(a,h,f,g),y={...t.sessions,byId:s,collapsedIds:h,collapsedIdsExplicit:d,pinnedIds:g,selectedIds:m,selectMode:t.sessions.selectMode&&m.length>0,flat:x,activeSessionId:t.sessions.activeSessionId,orderById:f,nextOrderOrdinal:p},S=pt(t,y);return{...t,sessions:S.sessions,ui:S.ui}}case"sessions/merged":{if(!e.session?.sessionId)return t;const s=t.sessions.byId[e.session.sessionId],n=hi(s,fi(s,e.session),Date.now());if(n===s)return t;const i={...t.sessions.byId,[e.session.sessionId]:n},o=xs(t.sessions.pinnedIds,i),{orderById:r,nextOrderOrdinal:a}=Si(t.sessions.orderById,t.sessions.nextOrderOrdinal,Object.values(i)),l={...t.sessions,byId:i,pinnedIds:o,flat:$e(Object.values(i),t.sessions.collapsedIds,r,o),activeSessionId:t.sessions.activeSessionId,orderById:r,nextOrderOrdinal:a},c=pt(t,l);return{...t,sessions:c.sessions,ui:c.ui}}case"sessions/selected":{const s=t.sessions.activeSessionId,n={...t.ui.chatScrollBySession||{}};return s&&s!==e.sessionId&&(n[s]=Number(t.ui.scroll?.chat)||0),{...t,sessions:{...t.sessions,activeSessionId:e.sessionId},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=mu(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=ws(t.sessions.collapsedIds);return s.add(e.sessionId),{...t,sessions:{...t.sessions,collapsedIds:s,collapsedIdsExplicit:!0,flat:$e(Object.values(t.sessions.byId),s,t.sessions.orderById,t.sessions.pinnedIds)}}}case"sessions/expand":{const s=ws(t.sessions.collapsedIds);return s.delete(e.sessionId),{...t,sessions:{...t.sessions,collapsedIds:s,collapsedIdsExplicit:!0,flat:$e(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(!Xo(n))return t;const i=ru(t.sessions.pinnedIds),r=i.indexOf(s)>=0?i.filter(a=>a!==s):[...i,s];return{...t,sessions:{...t.sessions,pinnedIds:r,flat:$e(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=au(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=Fs(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(Y,Number(e.history?.loadedEventLimit??s?.loadedEventLimit??Y)||Y),o=Es(st(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=ui(t.history.bySessionId);return c.set(e.sessionId,{...e.history||{},chat:o,activity:Es(e.history?.activity||[],i),events:Es(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=ui(t.history.bySessionId);for(const r of s)n.delete(r);const i=di(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=di(t.outbox?.bySessionId);return n.length===0?delete i[s]:i[s]=n,{...t,outbox:{...t.outbox,bySessionId:i}}}case"orchestration/statsLoading":{const s=Ot(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=Ot(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=Ot(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=Ot(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=ve(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=ve(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=ve(t.files.bySessionId),n=s[e.sessionId]||{previews:{},downloads:{}},i=Wt(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=ve(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=ve(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=ve(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=ve(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=ve(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=ve(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=ve(t.files.bySessionId),n=s[e.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:null},i=Wt(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:{...Is(t.files.filter),...Is(e.filter)},...Is(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:hu(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 Eu(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 vu=2e4,Tu=2e4,Au=3e4,Cu=30,wi="Session refresh failed",ku=3,Mu=200,Pu=5,Nu=new Set([v.SESSIONS,v.CHAT,v.INSPECTOR,v.ACTIVITY]);function Ou(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 xi(t){return!t?.sessionId||t.isGroup?t:{...t,groupId:t.groupId??null,parentSessionId:t.parentSessionId??null}}function vs(t){return String(t||"").startsWith("group:")?String(t).slice(6):null}async function _u(t){if(typeof t.listSessionsPage!="function")return t.listSessions();const e=[];let s=null;for(let n=0;n<Pu;n+=1){const i=await t.listSessionsPage({limit:Mu,cursor:s}),o=Array.isArray(i?.sessions)?i.sessions:[];if(e.push(...o),!i?.hasMore||!i?.nextCursor)break;s=i.nextCursor}return e}function Ru(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 Bs(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 Ii(t){const e=Bs(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 Ds(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 Lu(t){const e=Ds(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 Ei={default:"Default (smaller window)",long_context:"Long context (larger window, higher cost)"};function Hs(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 Fu(t){return Hs([t])}function vi(t,e=[]){let s=Xi(t);for(const n of e){const i=Ji(s,n?.eventType,n?.data,{timestamp:n?.createdAt});i&&(s=i)}return s}function Qt(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(!Qt(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)||!Qt(t[i],e[i]))return!1;return!0}function Ti(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 bn(t,e){const s=Ti(t?.updatedAt),n=Ti(e?.updatedAt);return s>0&&n>0&&n<=s}function $u(t){return!t||t==="idle"||t==="unknown"||t==="pending"}function Bu(t,e){return t?.status==="waiting"&&typeof t?.waitReason=="string"&&t.waitReason.trim().length>0&&(e?.waitReason===void 0||e?.waitReason===null)&&$u(e?.status)&&bn(t,e)}function Du(t,e){return t?.cronActive===!0&&e?.cronActive!==!0&&!er(e?.status)&&!Zo(e?.orchestrationStatus)&&bn(t,e)}function Hu(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||Qt(t?.[a],l)||(s[a]=l,n=!0);if(e.pendingQuestion===void 0&&t?.pendingQuestion&&e.status!=="input_required"&&!bn(t,e)&&(s.pendingQuestion=null,n=!0),Bu(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),Ya(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),Du(t,e))for(const a of["cronActive","cronKind","cronInterval","cronReason","cronNextFireAt","cronTimezone","cronMaxFires","cronFiresCompleted"])t?.[a]!=null&&(Qt(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((er(e.status)||Zo(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 Ai(t){return String(t||"").replace(/\r\n/g,`
|
|
67
|
+
`).trim()}function Zo(t){return t==="Completed"||t==="Failed"||t==="Terminated"}function er(t){return t==="completed"||t==="failed"||t==="cancelled"}function ae(t){return String(t||"").slice(0,8)}function lt(t){const e=String(t?.provider||"").trim(),s=String(t?.subject||"").trim();return e&&s?`${e}${s}`:null}function _t(t,e="unknown user"){return String(t?.displayName||t?.email||"").trim()||e}const Gu=lt({provider:"system",subject:"system"});function Ci(t){const e=t.auth?.principal||null,s=lt(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=_t(e,"current user");n.push({id:"me",kind:"me",label:`Me (${o})`,ownerKey:s,description:"Show sessions owned by the authenticated user currently signed in."})}const i=new Map;for(const o of Object.values(t.sessions?.byId||{})){const r=o?.owner,a=lt(r);!a||a===s||a===Gu||i.has(a)||i.set(a,r)}for(const[o,r]of[...i.entries()].sort((a,l)=>_t(a[1]).localeCompare(_t(l[1])))){const a=_t(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 Xt(t){return lt(t)?{all:!1,includeSystem:!0,includeUnowned:!1,includeMe:!0,ownerKeys:[]}:{all:!0,includeSystem:!1,includeUnowned:!1,includeMe:!1,ownerKeys:[]}}function Uu(t){return!!(t?.includeSystem||t?.includeUnowned||t?.includeMe||Array.isArray(t?.ownerKeys)&&t.ownerKeys.length>0)}function ju(t,e,s){const n=t||Xt(s);if(!e)return n;if(e.kind==="all")return n.all?Xt(s):{all:!0,includeSystem:!1,includeUnowned:!1,includeMe:!1,ownerKeys:[]};const i={...n,all:!1,ownerKeys:Array.isArray(n.ownerKeys)?[...n.ownerKeys]:[]};if(e.kind==="system"&&(i.includeSystem=!i.includeSystem),e.kind==="unowned"&&(i.includeUnowned=!i.includeUnowned),e.kind==="me"&&(i.includeMe=!i.includeMe),e.kind==="owner"&&e.ownerKey){const o=i.ownerKeys.indexOf(e.ownerKey);o>=0?i.ownerKeys.splice(o,1):i.ownerKeys.push(e.ownerKey)}return Uu(i)?i:{all:!0,includeSystem:!1,includeUnowned:!1,includeMe:!1,ownerKeys:[]}}function wn(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 Wu(t){const e=wn(t);return e?Math.max(1,60-`${e}: `.length):60}function Vu(t){const e=String(t?.title||"").trim();if(!e)return"";const s=wn(t);if(s&&e.startsWith(`${s}: `)){const n=e.slice(`${s}: `.length).trim();return!n||n===ae(t?.sessionId)?"":n}return e===ae(t?.sessionId)?"":e}function ki(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 Mi(t){return`📎 ${String(t||"").trim()}`}function Pi(t,e){const s=String(t||""),n=J(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 qu(t,e,s,n){const i=String(t||""),o=J(i,e),r=J(i,s),a=String(n||"");return{prompt:`${i.slice(0,o)}${a}${i.slice(r)}`,cursor:o+a.length}}function Ku(t,e="session"){return String(t||"").replace(/\s+/gu," ").trim()||e}function zu(t){const e=String(t?.sessionId||"").trim(),s=ae(e)||"session";return`Referenced session: ${Ku(t?.title,s)} — session://${e}`}function Ni(t,e,s){if(!e)return Fe(t,String(t||"").length,s);const n=String(t||""),i=n.slice(e.tokenEnd,e.tokenEnd+1),o=!i||/\s/u.test(i);return qu(n,e.tokenStart,e.tokenEnd,`${String(s||"")}${o?" ":""}`)}function Yu(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()}function Qu(t,e=[]){const s=Array.isArray(e)?e.filter(o=>o?.sessionId&&o?.filename):[];if(s.length===0)return String(t||"");const n=s.map(o=>`[Attached file: ${o.filename} — artifact://${o.sessionId}/${o.filename}]`),i=Yu(t,s);return n.join(`
|
|
70
|
+
`)+(i?`
|
|
71
|
+
|
|
72
|
+
${i}`:"")}function Qe(t,e){return String(t||"").replace(/\r?\n/g," ").slice(0,Math.max(0,Number(e)||0))}function tr(t){return Array.from(String(t||"")).length}function Xu(t){const e=[];for(const s of t||[]){if(s?.kind==="markup"){const n=Zi(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 Ju(t,e){const s=Math.max(1,Number(e)||1),n=tr(t);return Math.max(1,Math.ceil(n/s))}function Xe(t,e){const s=Math.max(1,Number(e)||1);return Xu(t).reduce((n,i)=>{if(!i)return n+1;if(Array.isArray(i)){const o=i.reduce((r,a)=>r+tr(a?.text||""),0);return n+Math.max(1,Math.ceil(o/s))}return n+Ju(i.text||"",s)},0)}function J(t,e){const s=String(t||"");return Math.max(0,Math.min(Number(e)||0,s.length))}function sr(t){return String(t||"").split(`
|
|
73
|
+
`)}function Zu(t,e){const n=String(t||"").slice(0,J(t,e)).split(`
|
|
74
|
+
`),i=n[n.length-1]||"";return{line:Math.max(0,n.length-1),column:i.length}}function ed(t,e,s){const n=sr(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 J(t,r+o)}function Fe(t,e,s){const n=String(t||""),i=J(n,e),o=String(s||"");return{prompt:`${n.slice(0,i)}${o}${n.slice(i)}`,cursor:i+o.length}}function Je(t,e){const s=String(t||""),n=J(s,e);return n<=0?{prompt:s,cursor:n}:{prompt:`${s.slice(0,n-1)}${s.slice(n)}`,cursor:n-1}}function Rt(t){return/\s/u.test(t||"")}function nr(t,e,s){const n=String(t||"");let i=J(n,e);if(s<0){for(;i>0&&Rt(n[i-1]);)i-=1;for(;i>0&&!Rt(n[i-1]);)i-=1;return i}for(;i<n.length&&Rt(n[i]);)i+=1;for(;i<n.length&&!Rt(n[i]);)i+=1;return i}function td(t,e){const s=String(t||""),n=J(s,e),i=nr(s,n,-1);return i===n?{prompt:s,cursor:n}:{prompt:`${s.slice(0,i)}${s.slice(n)}`,cursor:i}}function sd(t,e,s){const n=sr(t);if(n.length<=1)return J(t,e);const i=Zu(t,e),o=Math.max(0,Math.min(i.line+s,n.length-1));return o===i.line?J(t,e):ed(t,o,i.column)}const Oi=3e3,nd=new Set(["logs","sequence"]),id=2e5,od=new Set([".md",".markdown",".mdown",".mkd",".mdx"]),rd=new Set([".json",".jsonl"]),ad=new Set([".png",".jpg",".jpeg",".gif",".webp",".svg",".ico",".pdf",".zip",".gz",".tgz",".tar",".wasm",".sqlite",".db"]);function ir(t){const e=String(t||""),s=e.lastIndexOf(".");return s>=0?e.slice(s).toLowerCase():""}function ld(t,e=""){const s=ir(t),n=String(e||"").toLowerCase();return ad.has(s)?!0:n.startsWith("image/")||n==="application/pdf"||n.startsWith("application/zip")||n==="application/wasm"}function _i(t,e=id){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 cd(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 ud(t,e="",s=null){const n=[`Preview is not available here for ${t}.`,""];return e&&n.push(`Type: ${e}`),s!=null&&n.push(`Size: ${cd(s)}`),n.push("Download the artifact to open it in the default app."),n.join(`
|
|
77
|
+
`)}function Ri(t,e,s="",n=null){const i=String(s||"").toLowerCase(),o=ir(t);if(n?.isBinary===!0||ld(t,s))return{content:ud(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=_i(e);if(od.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(rd.has(o)||i.includes("json"))try{return{content:_i(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 dd{constructor({store:e,transport:s}){this.store=e,this.transport=s,this.catalogTimer=null,this.activeSessionUnsub=null,this.activeSessionSubscriptionId=null,this.activeSessionDetailTimer=null,this.activeSessionDetailSessionId=null,this.sessionRefreshTimer=null,this.sessionHistoryLoads=new Map,this.sessionHistoryExpansionLoads=new Map,this.sessionOrchestrationStatsLoads=new Map,this.outboxFlushPromises=new Map,this.logUnsubscribe=null,this.promptReferenceSignature=null,this.promptReferenceSyncVersion=0,this.chatTopHistoryLoadArmed=!1,this.chatTopHistoryLoadSessionId=null}getState(){return this.store.getState()}subscribe(e){return this.store.subscribe(e)}dispatch(e){return this.store.dispatch(e)}setStatus(e){this.dispatch({type:"ui/status",text:e})}getPromptAttachments(){const e=this.getState().ui.promptAttachments;return Array.isArray(e)?e.filter(Boolean):[]}setPromptAttachments(e){this.dispatch({type:"ui/promptAttachments",attachments:Array.isArray(e)?e:[]})}getSessionOutbox(e){if(!e)return[];const s=this.getState().outbox?.bySessionId?.[e];return Array.isArray(s)?s.filter(Boolean):[]}setSessionOutboxItems(e,s){e&&this.dispatch({type:"outbox/setSessionItems",sessionId:e,items:Array.isArray(s)?s:[]})}buildOutboxItem(e,s="pending"){const n=`msg:${Date.now()}:${Math.random().toString(36).slice(2,10)}`,i=s==="queued"||s==="cancelling"?s:"pending";return{id:n,text:String(e||""),createdAt:Date.now(),phase:i,clientMessageIds:[n]}}getPendingOutboxItems(e){return this.getSessionOutbox(e).filter(s=>s?.phase==="pending")}getQueuedOutboxItems(e){return this.getSessionOutbox(e).filter(s=>s?.phase==="queued")}getNavigableOutboxItems(e){return this.getSessionOutbox(e).filter(s=>s?.phase==="pending"||s?.phase==="queued"||s?.phase==="cancelling")}getEditableOutboxItems(e){return this.getPendingOutboxItems(e)}getPromptEditSessionMatch(e=this.getState().sessions.activeSessionId){const s=this.getState().ui.promptEdit;return s?.sessionId===e?s:null}enterPendingPromptEdit(e,s){if(!e||!s)return!1;const i=this.getNavigableOutboxItems(e).find(l=>l.id===s);if(!i)return!1;const o=this.getState().ui,r=this.getPromptEditSessionMatch(e),a=r?{...r,itemId:s,phase:i.phase}:{sessionId:e,itemId:s,phase:i.phase,draftPrompt:o.prompt,draftCursor:o.promptCursor};return this.dispatch({type:"ui/promptEdit",promptEdit:a}),this.setPrompt(i.text,i.text.length),this.setFocus(v.PROMPT),!0}exitPendingPromptEdit({restoreDraft:e=!0}={}){const s=this.getState().ui.promptEdit;return s?(this.dispatch({type:"ui/promptEdit",promptEdit:null}),e&&this.setPrompt(s.draftPrompt||"",Number.isFinite(s.draftCursor)?s.draftCursor:String(s.draftPrompt||"").length),!0):!1}selectPreviousPendingPrompt(e=this.getState().sessions.activeSessionId){const s=this.getNavigableOutboxItems(e);if(s.length===0)return!1;const n=this.getPromptEditSessionMatch(e);if(!n)return this.enterPendingPromptEdit(e,s[s.length-1].id);const i=s.findIndex(o=>o.id===n.itemId);return i<=0?!1:this.enterPendingPromptEdit(e,s[i-1].id)}selectNextPendingPrompt(e=this.getState().sessions.activeSessionId){const s=this.getNavigableOutboxItems(e),n=this.getPromptEditSessionMatch(e);if(!n)return!1;const i=s.findIndex(o=>o.id===n.itemId);return i===-1||i>=s.length-1?this.exitPendingPromptEdit({restoreDraft:!0}):this.enterPendingPromptEdit(e,s[i+1].id)}async cancelSelectedOutboxPrompt(){const e=this.getState().ui.promptEdit;if(!e?.sessionId||!e?.itemId)return!1;const n=this.getSessionOutbox(e.sessionId).find(o=>o.id===e.itemId);return n?n.phase==="cancelling"?(this.exitPendingPromptEdit({restoreDraft:!0}),!1):await this.cancelOutboxItem(e.sessionId,e.itemId)?(this.exitPendingPromptEdit({restoreDraft:!0}),!0):!1:!1}cancelSelectedPendingPrompt(){const e=this.getState().ui.promptEdit;if(!e?.sessionId||!e?.itemId)return!1;const s=this.getSessionOutbox(e.sessionId);if(!s.find(o=>o.id===e.itemId&&o.phase==="pending"))return!1;const i=s.filter(o=>o.id!==e.itemId);return this.setSessionOutboxItems(e.sessionId,i),this.exitPendingPromptEdit({restoreDraft:!0}),this.dispatch({type:"ui/status",text:"Cancelled pending prompt"}),!0}async cancelOutboxItem(e,s){if(!e||!s)return!1;const n=this.getSessionOutbox(e),i=n.find(r=>r.id===s);if(!i||i.phase==="cancelling")return!1;this.getPromptEditSessionMatch(e)?.itemId===s&&this.exitPendingPromptEdit({restoreDraft:!0});const o=Array.isArray(i.clientMessageIds)&&i.clientMessageIds.length>0?i.clientMessageIds:[i.id];if(i.phase==="queued")if(this.setSessionOutboxItems(e,n.map(r=>r.id===s?{...r,phase:"cancelling"}:r)),typeof this.transport?.cancelPendingMessage=="function")try{await this.transport.cancelPendingMessage(e,o),this.dispatch({type:"ui/status",text:"Cancelling queued prompt"})}catch(r){return this.setSessionOutboxItems(e,n),this.dispatch({type:"ui/status",text:r?.message||String(r)}),!1}else this.dispatch({type:"ui/status",text:"Queued prompt marked cancelling (local only — transport has no cancel)"});else{const r=n.filter(a=>a.id!==s);if(this.setSessionOutboxItems(e,r),typeof this.transport?.cancelPendingMessage=="function")try{await this.transport.cancelPendingMessage(e,o)}catch{}this.dispatch({type:"ui/status",text:"Cancelled pending prompt"})}return!0}async cancelLatestQueuedOutbox(e=this.getState().sessions.activeSessionId){if(!e)return!1;const s=this.getQueuedOutboxItems(e);if(s.length===0)return!1;const n=s[s.length-1];return await this.cancelOutboxItem(e,n.id)}queuePromptInOutbox(e,s){const n=this.buildOutboxItem(s,"pending");return this.setSessionOutboxItems(e,[...this.getSessionOutbox(e),n]),n}acknowledgeOutboxPrompt(e,s,n=null){if(!e)return!1;const i=this.getSessionOutbox(e);if(n){const l=i.findIndex(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=Ai(s);if(!o)return!1;const r=i.findIndex(l=>(l?.phase==="pending"||l?.phase==="queued"||l?.phase==="cancelling")&&Ai(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);if(n.length===0)return!1;const i=n.flatMap(f=>Array.isArray(f.clientMessageIds)&&f.clientMessageIds.length>0?f.clientMessageIds:[f.id]),o=n.map(f=>String(f.text||"")).join(`
|
|
78
|
+
|
|
79
|
+
`),r={id:n[0].id,text:o,createdAt:n[0].createdAt||Date.now(),phase:"pending",clientMessageIds:i},a=new Set(n.map(f=>f.id)),l=this.getSessionOutbox(e).filter(f=>!a.has(f.id));this.setSessionOutboxItems(e,[...l,r]);const c=this.getPromptEditSessionMatch(e);c&&a.has(c.itemId)&&this.exitPendingPromptEdit({restoreDraft:!0});const d=(async()=>{await this.transport.sendMessage(e,r.text,{enqueueOnly:!0,clientMessageIds:r.clientMessageIds});const p=this.getSessionOutbox(e).map(h=>h.id===r.id?{...h,phase:"queued"}:h);return this.setSessionOutboxItems(e,p),this.syncSessionEvents(e).catch(()=>{}),this.scheduleSessionsRefresh(250),!0})().catch(f=>{const p=f?.code==="FORBIDDEN"||f?.code==="UNAUTHORIZED"||f?.status===403||f?.status===401,h=this.getSessionOutbox(e);if(p){const g=h.map(m=>m.id===r.id?{...m,phase:"rejected"}:m);this.setSessionOutboxItems(e,g),setTimeout(()=>{const m=this.getSessionOutbox(e),x=m.filter(y=>!(y.id===r.id&&y.phase==="rejected"));x.length!==m.length&&this.setSessionOutboxItems(e,x)},6e3)}else{const g=h.flatMap(m=>m.id===r.id?n:[m]);this.setSessionOutboxItems(e,g)}throw this.dispatch({type:"ui/status",text:f?.message||String(f)}),f}).finally(()=>{this.outboxFlushPromises.delete(e),this.getPendingOutboxItems(e).length>0&&this.scheduleOutboxDispatch(e)});return this.outboxFlushPromises.set(e,d),await d}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 Pi(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=Le(s),i=n?.sessionId||s.sessions.activeSessionId||null,o=n?.filename||null;if(!i||!o)return!1;const r=Mi(o),a=Ni(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(v.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=Tt(s)[0]||null,o=i?.sessionId&&s.sessions.byId[i.sessionId]||null;if(!o?.sessionId)return!1;const r=zu(o),a=Ni(s.ui.prompt,e,r);return this.setPrompt(a.prompt,a.cursor),this.setFocus(v.PROMPT),this.dispatch({type:"ui/status",text:`Referenced session ${ae(o.sessionId)}`}),!0}setSessionFilterQuery(e=""){this.dispatch({type:"sessions/filterQuery",query:String(e||"")})}openSessionOwnerFilter(){const e=this.getState(),s=Ci(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=ju(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=Ci(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=Pi(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(Yt(this.getState(),"selectedSession")),a=At(this.getState()).filter(l=>o.has(l.sessionId))[0]||null;a?.filename&&(this.dispatch({type:"files/select",sessionId:a.sessionId,filename:a.filename}),await this.ensureFilePreview(a.sessionId,a.filename).catch(()=>{}))}).catch(()=>{})}async start(){await this.transport.start();const e=typeof this.transport.getAuthContext=="function"?this.transport.getAuthContext():null;this.dispatch({type:"auth/context",principal:e?.principal??null,authorization:e?.authorization??null}),this.getState().sessions.ownerFilterExplicit||this.dispatch({type:"sessions/ownerFilter",filter:Xt(e?.principal??null)});const s=typeof this.transport.getLogConfig=="function"?this.transport.getLogConfig():null;s&&this.dispatch({type:"logs/config",available:s.available,availabilityReason:s.availabilityReason}),this.dispatch({type:"connection/ready",workersOnline:typeof this.transport.getWorkerCount=="function"?this.transport.getWorkerCount():null,statusText:"Connected"}),await this.refreshSessions(),this.catalogTimer=setInterval(()=>{this.refreshSessions().catch(n=>{this.dispatch({type:"connection/error",error:n?.message||String(n),statusText:wi})})},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===wi,i=this.getState().sessions.activeSessionId;let o=(await _u(this.transport)).map(xi);if(typeof this.transport.listSessionGroups=="function"){const c=await this.transport.listSessionGroups().catch(()=>[]),d=(Array.isArray(c)?c:[]).map(Ou).filter(Boolean);d.length>0&&(o=[...d,...o])}const r=i;if(r&&!o.some(c=>c?.sessionId===r)&&typeof this.transport.getSession=="function"){const c=await this.transport.getSession(r).catch(()=>null);c?.sessionId&&(o=[...o,xi(c)])}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 a=this.getState().sessions.activeSessionId,l=new Set;if(a){if(a!==i){this.getState().sessions.byId[a]?.isGroup||await this.loadSession(a);return}if(this.getState().sessions.byId[a]?.isGroup)return;this.getState().history.bySessionId.get(a)?.events?.length||await this.ensureSessionHistory(a,{force:!0}).catch(()=>{}),this.activeSessionSubscriptionId!==a&&this.attachActiveSession(a),await this.syncSessionDetail(a).catch(()=>{}),await this.syncSessionEvents(a).catch(()=>{}),l.add(a);const d=this.getState(),f=d.sessions.byId[a]||null;if(f?.parentSessionId&&typeof this.transport.getSession=="function"){const p=Object.values(d.sessions.byId).filter(h=>h?.parentSessionId===f.parentSessionId).map(h=>h.sessionId).filter(h=>h&&h!==a).slice(0,6);await Promise.all(p.map(h=>this.syncSessionDetail(h).catch(()=>{})));for(const h of p)l.add(h)}}await this.syncVisibleSessionDetails(l).catch(()=>{}),this.ensureInspectorData().catch(()=>{}),this.evictStaleSessionState()}evictStaleSessionState(){const e=this.getState(),s=e.sessions.activeSessionId,n=Date.now(),i=6e4,o=20,r=Object.entries(e.orchestration.bySessionId||{});if(r.length>o){const 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=wt({width:s.ui.layout.viewportWidth,height:s.ui.layout.viewportHeight},s.ui.layout.paneAdjust,s.ui.promptRows??ot(s.ui.prompt),s.ui.layout.sessionPaneAdjust,s.ui.layout.activityPaneAdjust,s.ui.fullscreenPane),i=this.getSessionListMaxRows(n),o=Rs(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=Dn(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=Hs(o),l=this.getState().sessions.byId[e]||{},c=vi(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(Y,Number(n?.loadedEventLimit??Y)||Y);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={...Pt(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=Hs(a),d=this.getState().sessions.byId[e]||{},f=vi(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=wt({width:s.ui.layout.viewportWidth,height:s.ui.layout.viewportHeight},s.ui.layout.paneAdjust,s.ui.promptRows??ot(s.ui.prompt),s.ui.layout.sessionPaneAdjust,s.ui.layout.activityPaneAdjust,s.ui.fullscreenPane),i=this.getSessionListMaxRows(n),o=Rs(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(me(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<vu)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<Tu)){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<Au)){this.dispatch({type:"fleetStats/loading"});try{const o={since:new Date(Date.now()-Cu*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=Fe(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=Je(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,J(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=me(this.getState()),{force:s=!1}={}){const n=Yt(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=Le(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=Ka(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?Ri(s,"",r.contentType||"",r):Ri(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=Le(e);if(!s?.sessionId||!s?.filename){this.dispatch({type:"ui/status",text:e.sessions.activeSessionId||me(e)==="allSessions"?"No file selected":"No session selected"});return}const{sessionId:n,filename:i}=s,o=me(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 ${ae(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=Le(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=Le(s);if(!n?.sessionId||!n?.filename)return this.dispatch({type:"ui/status",text:"No artifact selected"}),!1;const i=me(s),o=i==="allSessions"?`${ae(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=Le(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 ${ae(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=Hl(e),i=Gl(e);if(n.length===0&&i.length===0){this.dispatch({type:"ui/status",text:"No linked artifacts or URLs in the current chat view"});return}const o=this.getState().files.bySessionId[s]?.selectedFilename||null,r=o?`${s}/${o}`:null,a=this.buildArtifactPickerModal({artifactLinks:n,httpLinks:i,previousFocus:e.ui.focusRegion,selectedId:r});if(!a){this.dispatch({type:"ui/status",text:"No linked artifacts or URLs in the current chat view"});return}this.dispatch({type:"ui/modal",modal:a}),this.dispatch({type:"ui/status",text:"Select a linked item and press Enter to open or download it"})}async downloadArtifactModalSelection(){const e=this.getState().ui.modal;if(!e||e.type!=="artifactPicker")return;const s=e.items?.[e.selectedIndex||0];if(!s)return;if(s.kind==="url"){if(typeof this.transport.openUrlInDefaultBrowser!="function"){this.dispatch({type:"ui/status",text:"Opening URLs is not supported by this transport"});return}this.dispatch({type:"ui/status",text:`Opening ${s.href}...`}),await this.transport.openUrlInDefaultBrowser(s.href),this.replaceArtifactPickerModal(s.id),this.dispatch({type:"ui/status",text:`Opened ${s.href}`});return}if(s.kind==="downloadAll"){const i=(e.items||[]).filter(r=>r.kind!=="artifact"?!1:!this.getState().files.bySessionId[r.sessionId]?.downloads?.[r.filename]?.localPath);if(i.length===0){this.dispatch({type:"ui/status",text:"All artifacts already downloaded"});return}this.dispatch({type:"ui/status",text:`Downloading ${i.length} artifacts...`});let o=0;for(const r of i)(await this.saveArtifactDownload(r.sessionId,r.filename))?.localPath&&(o+=1);this.replaceArtifactPickerModal(s.id),this.dispatch({type:"ui/status",text:`Downloaded ${o}/${i.length} artifacts`});return}this.dispatch({type:"ui/status",text:`Downloading ${s.filename}...`}),(await this.saveArtifactDownload(s.sessionId,s.filename))?.localPath&&(this.replaceArtifactPickerModal(s.id),this.dispatch({type:"ui/status",text:`Downloaded ${s.filename}`}))}async moveFileSelection(e){const s=me(this.getState());await this.ensureFilesForScope(s);const n=At(this.getState());if(n.length===0)return;const i=Le(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 ${ae(a.sessionId)} ${a.filename}`:`Previewing ${a.filename}`}))}async selectFileBrowserItem(e){if(!e?.sessionId||!e?.filename)return;const s=me(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 ${ae(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===v.PROMPT?n:s;if(!Nu.has(i)||i===v.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===v.PROMPT&&this.setFocus(i)}openFilesFilter(){const e=me(this.getState());this.dispatch({type:"ui/modal",modal:{type:"filesFilter",title:"Files Filter",previousFocus:this.getState().ui.focusRegion,selectedIndex:0,items:[{id:"scope",label:"Scope",description:"Choose whether the files browser shows the selected session tree or aggregates exported files across all sessions.",options:[{id:"selectedSession",label:"Selected session tree"},{id:"allSessions",label:"All sessions"}]}]}}),this.dispatch({type:"ui/status",text:`Editing files filter: Scope = ${e==="allSessions"?"All sessions":"Selected session tree"}`})}async loadSession(e){if(!e)return;if(this.getState().sessions.activeSessionId!==e&&(this.getState().ui.promptEdit&&this.exitPendingPromptEdit({restoreDraft:!0}),this.dispatch({type:"sessions/selected",sessionId:e}),this.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:Dn(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=Fu(s),r=this.getState().sessions.byId[e]||{sessionId:e},a=Ji(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=Hu(n,s);(i||n?.rowVisualStatusCandidate)&&this.dispatch({type:"sessions/merged",session:i||{sessionId:e}}),this.maybeFlushQueuedOutbox(e,s)}async createSession(e={}){try{const s=await this.transport.createSession(this.applyActiveGroupDefault(e));return await this.refreshSessions(),await this.loadSession(s.sessionId),this.setFocus(v.PROMPT),this.dispatch({type:"ui/status",text:`Created session ${s.sessionId.slice(0,8)}`}),s}catch(s){return this.dispatch({type:"ui/status",text:s?.message||String(s)||"Failed to create session"}),null}}async createSessionForAgent(e,s={}){if(typeof this.transport.createSessionForAgent!="function")throw new Error("Named-agent session creation is not supported by this transport");try{const n=await this.transport.createSessionForAgent(e,this.applyActiveGroupDefault(s));return await this.refreshSessions(),await this.loadSession(n.sessionId),this.setFocus(v.PROMPT),this.dispatch({type:"ui/status",text:`Created ${ki(e,s.title)} session ${n.sessionId.slice(0,8)}`}),n}catch(n){return this.dispatch({type:"ui/status",text:n?.message||String(n)||"Failed to create session"}),null}}getMovableGroupSessionSelection(){const e=this.getState();return(Array.isArray(e.sessions.selectedIds)&&e.sessions.selectedIds.length>0?e.sessions.selectedIds:e.sessions.activeSessionId?[e.sessions.activeSessionId]:[]).map(n=>e.sessions.byId[n]).filter(n=>n&&!n.isSystem&&!n.isGroup&&!n.parentSessionId)}async openMoveToGroupModal(){const e=this.getState(),s=this.getMovableGroupSessionSelection();if(s.length===0)return this.dispatch({type:"ui/status",text:"Select a top-level non-system session to move"}),null;if(typeof this.transport.listSessionGroups!="function")return this.dispatch({type:"ui/status",text:"Session groups are not supported by this transport"}),null;const n=await this.transport.listSessionGroups().catch(()=>[]),i=s.map(h=>h.sessionId),o=s.length===1&&s[0].groupId||null,r=new Set(s.map(h=>lt(h.owner)||"")),a=r.size===1?[...r][0]:null,l=r.size===1?s[0]?.owner??null:null,c=r.size===1?(Array.isArray(n)?n:[]).filter(h=>(lt(h.owner)||"")===a):[],d=r.size===1,f=[{id:"__no_group__",kind:"noGroup",label:"[No Group]",description:"Remove the selected session(s) from any group.",groupId:null,memberCount:0},...d?[{id:"__new_group__",kind:"newGroup",label:"[New Group]",description:"Create a new group for this owner, then move the selected session(s) into it.",groupId:null,memberCount:0,owner:l}]:[],...c.map(h=>({id:h.groupId,kind:"group",label:h.title||h.groupId,description:h.description||"Move selected session(s) into this group.",groupId:h.groupId,owner:h.owner??null,memberCount:h.memberCount??0}))],p=o?Math.max(0,f.findIndex(h=>h.groupId===o)):Math.min(1,f.length-1);return this.dispatch({type:"ui/modal",modal:{type:"sessionGroupPicker",title:s.length===1?"Move Session to Group":`Move ${s.length} Sessions to Group`,previousFocus:e.ui.focusRegion,sessionIds:i,sessionLabels:s.map(h=>h.title||h.sessionId.slice(0,8)),selectedIndex:p>=0?p:0,items:f}}),this.dispatch({type:"ui/status",text:d?"Choose a group, [New Group], or [No Group]":"Selected sessions have different owners; only [No Group] is available"}),f}async createSessionGroupFromSelection(){return this.openMoveToGroupModal()}async moveSessionsToGroup(e,s,{statusTitle:n=null}={}){const i=Array.from(new Set((Array.isArray(s)?s:[]).map(r=>String(r||"").trim()).filter(Boolean)));if(i.length===0)return this.dispatch({type:"ui/status",text:"No sessions selected to move"}),null;if(typeof this.transport.moveSessionsToGroup=="function")await this.transport.moveSessionsToGroup(e??null,i);else if(e&&typeof this.transport.assignSessionsToGroup=="function")await this.transport.assignSessionsToGroup(e,i);else return this.dispatch({type:"ui/status",text:"Moving sessions between groups is not supported by this transport"}),null;this.dispatch({type:"sessions/selectClear"}),await this.refreshSessions(),e&&await this.loadSession(`group:${e}`).catch(()=>{});const o=e?`group ${n||e}`:"No Group";return this.dispatch({type:"ui/status",text:`Moved ${i.length} session${i.length===1?"":"s"} to ${o}`}),!0}async confirmSessionGroupPickerModal(){const e=this.getState().ui.modal;if(!e||e.type!=="sessionGroupPicker")return;const s=e.items?.[e.selectedIndex||0];if(!s)return;if(s.kind==="newGroup"){const i=(e.sessionLabels||[]).length===1?`${e.sessionLabels[0]} Group`:`${(e.sessionIds||[]).length} Session Group`;this.dispatch({type:"ui/modal",modal:{type:"sessionGroupName",title:"New Group",previousFocus:e.previousFocus,sessionIds:e.sessionIds||[],owner:s.owner??null,value:i,cursorIndex:i.length,maxLength:80}}),this.dispatch({type:"ui/status",text:"Name the new group and press Enter"});return}const n=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n);try{await this.moveSessionsToGroup(s.kind==="noGroup"?null:s.groupId,e.sessionIds||[],{statusTitle:s.label})}catch(i){this.dispatch({type:"ui/status",text:`Move failed: ${i?.message||String(i)}`})}}updateSessionGroupNameModal(e){const s=this.getState().ui.modal;if(!s||s.type!=="sessionGroupName")return null;const n=typeof e=="function"?e(s):e;return n?(this.dispatch({type:"ui/modal",modal:{...s,...n}}),this.getState().ui.modal):null}setSessionGroupNameValue(e,s=String(e||"").length){const n=this.getState().ui.modal;if(!n||n.type!=="sessionGroupName")return;const i=Qe(e,n.maxLength||80),o=J(i,s);this.updateSessionGroupNameModal({value:i,cursorIndex:o})}insertSessionGroupNameText(e){const s=this.getState().ui.modal;if(!s||s.type!=="sessionGroupName")return;const n=Fe(s.value||"",s.cursorIndex||0,Qe(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=Je(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||"",J(s.value||"",(s.cursorIndex||0)+e))}moveSessionGroupNameCursorToBoundary(e){const s=this.getState().ui.modal;!s||s.type!=="sessionGroupName"||this.setSessionGroupNameValue(s.value||"",e==="start"?0:String(s.value||"").length)}async confirmSessionGroupNameModal(){const e=this.getState().ui.modal;if(!e||e.type!=="sessionGroupName")return;const s=String(e.value||"").trim();if(!s){this.dispatch({type:"ui/status",text:"Group name cannot be empty"});return}if(typeof this.transport.createSessionGroup!="function"){this.dispatch({type:"ui/status",text:"Session grouping is not supported by this transport"});return}const n=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n);try{const i=await this.transport.createSessionGroup({title:s,description:`${(e.sessionIds||[]).length} grouped session${(e.sessionIds||[]).length===1?"":"s"}`,sessionIds:e.sessionIds||[],owner:e.owner??null});await this.moveSessionsToGroup(i.groupId,e.sessionIds||[],{statusTitle:i.title||s})}catch(i){this.dispatch({type:"ui/status",text:`Move failed: ${i?.message||String(i)}`})}}applyActiveGroupDefault(e={}){if(e&&Object.prototype.hasOwnProperty.call(e,"groupId"))return e;const s=this.getState(),n=s.sessions?.activeSessionId?s.sessions.byId[s.sessions.activeSessionId]:null,i=n?.isGroup?n.groupId||vs(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:ki(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=Bs(e?.supportedReasoningEfforts),i=s?.reasoningEffort||Ii(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=Ds(e?.supportedContextTiers),i=s?.contextTier||Lu(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,label:Ei[a]||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():Ru(s),o=[],r=i.map(c=>({providerId:c.providerId,providerType:c.type||c.providerType,models:(c.models||[]).map(d=>{const f={id:d.qualifiedName,qualifiedName:d.qualifiedName,modelName:d.modelName||d.qualifiedName,providerId:d.providerId||c.providerId,providerType:d.providerType||c.type||c.providerType,description:d.description||"",cost:d.cost||null,supportedReasoningEfforts:Bs(d.supportedReasoningEfforts),defaultReasoningEffort:d.defaultReasoningEffort||null,supportedContextTiers:Ds(d.supportedContextTiers),defaultContextTier:d.defaultContextTier||null,isDefault:n===d.qualifiedName};return o.push(f),f})})).filter(c=>c.models.length>0),a=e?.model||n,l=Math.max(0,o.findIndex(c=>c.qualifiedName===a));this.dispatch({type:"ui/modal",modal:{type:"modelPicker",title:e?.mode==="switchModel"?"Switch model for session":"Select model for new session",items:o,groups:r,selectedIndex:l,previousFocus:this.getState().ui.focusRegion,sessionOptions:e}}),this.dispatch({type:"ui/status",text:"Select a model and press Enter"})}async openSwitchModelPicker(){const e=this.getState(),s=e.sessions.activeSessionId,n=s&&e.sessions.byId[s]||null;if(!n||n.isGroup){this.dispatch({type:"ui/status",text:"Select a session before switching model"});return}if(typeof this.transport.setSessionModel!="function"){this.dispatch({type:"ui/status",text:"Model switching is not supported by this transport"});return}await this.openModelPicker({mode:"switchModel",sessionId:s,model:n.model||void 0,reasoningEffort:n.reasoningEffort||void 0})}async switchSessionModel(e={}){const s=e.sessionId||this.getState().sessions.activeSessionId,n=String(e.model||"").trim();if(!s||!n){this.dispatch({type:"ui/status",text:"Select a model before switching"});return}if(typeof this.transport.setSessionModel!="function"){this.dispatch({type:"ui/status",text:"Model switching is not supported by this transport"});return}await this.transport.setSessionModel(s,{model:n,..."reasoningEffort"in e?{reasoningEffort:e.reasoningEffort??null}:{},..."contextTier"in e?{contextTier:e.contextTier??null}:{},source:"ui"});const i=e.reasoningEffort?`${n}:${e.reasoningEffort}`:n,o=e.contextTier?` · ${Ei[e.contextTier]||e.contextTier}`:"";this.dispatch({type:"ui/status",text:`Next turn will use ${i}${o}`}),await this.refreshSessions()}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=Wa().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 (${ae(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=J(i,s);this.updateArtifactUploadModal({value:i,cursorIndex:o})}insertArtifactUploadText(e){const s=this.getState().ui.modal;if(!s||s.type!=="artifactUpload")return;const n=Fe(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=Je(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||"",J(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=Mi(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=Fe(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(v.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});this.dispatch({type:"ui/modal",modal:null}),this.dispatch({type:"ui/status",text:`Uploaded ${o.filename}`})}catch(n){this.dispatch({type:"ui/status",text:`Upload failed: ${n?.message||String(n)}`})}}openRenameSessionModal(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s){this.dispatch({type:"ui/status",text:"No session selected"});return}const n=e.sessions.byId[s];if(!n){this.dispatch({type:"ui/status",text:"No session selected"});return}if(n.isSystem){this.dispatch({type:"ui/status",text:"System session titles are fixed"});return}const i=Vu(n),o=wn(n),r=Wu(n);this.dispatch({type:"ui/modal",modal:{type:"renameSession",title:`Rename (${ae(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 (${ae(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=Qe(e,n.maxLength),o=J(i,s);this.updateRenameSessionModal({value:i,cursorIndex:o})}insertRenameSessionText(e){const s=this.getState().ui.modal;if(!s||s.type!=="renameSession")return;const n=Fe(s.value||"",s.cursorIndex||0,Qe(e,s.maxLength));this.setRenameSessionValue(n.prompt,n.cursor)}deleteRenameSessionChar(){const e=this.getState().ui.modal;if(!e||e.type!=="renameSession")return;const s=Je(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||"",J(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||vs(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 ${ae(s)}...`});try{await this.transport.renameSession(s,n),await this.refreshSessions(),this.scheduleSessionDetailSync(s,100),this.dispatch({type:"ui/status",text:`Renamed ${ae(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=ze(["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 (${ae(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=Qe(e,120),o=J(i,s);this.updateShareSessionModal({value:i,cursorIndex:o})}insertShareSessionText(e){const s=this.getState().ui.modal;if(!s||s.type!=="shareSession")return;const n=Fe(s.value||"",s.cursorIndex||0,Qe(e,120));this.setShareSessionValue(n.prompt,n.cursor)}deleteShareSessionChar(){const e=this.getState().ui.modal;if(!e||e.type!=="shareSession")return;const s=Je(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||"",J(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(),g=(e.shares||[]).find(m=>m.subject&&String(m.subject).toLowerCase()===h||m.email&&String(m.email).toLowerCase()===h||m.displayName&&String(m.displayName).toLowerCase()===h);if(!g){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:g.provider,subject:g.subject}),this.dispatch({type:"ui/status",text:`Revoked ${o}`})}catch(m){this.dispatch({type:"ui/status",text:m?.message||String(m)})}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 g=Array.isArray(h)?h:[];if(p=g.find(m=>m.displayName&&m.displayName.toLowerCase()===f||m.email&&m.email.toLowerCase()===f||m.subject&&m.subject.toLowerCase()===f)||null,!p){const m=g.filter(x=>x.displayName&&x.displayName.toLowerCase().includes(f)||x.email&&x.email.toLowerCase().includes(f)||x.subject&&x.subject.toLowerCase().includes(f));if(m.length===1)p=m[0];else if(m.length>1){this.dispatch({type:"ui/status",text:`"${d}" is ambiguous (${m.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=ze(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=_e(s?.id);if(!n){this.dispatch({type:"ui/status",text:"Unable to apply that theme"});return}const i=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),i&&this.setFocus(i),this.dispatch({type:"ui/status",text:`Applied theme: ${n.label}`});return}if(e.type==="modelPicker"){const s=e.items?.[e.selectedIndex||0],n=e.previousFocus;if(this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n),!s){if(e.sessionOptions?.mode==="switchModel"){this.dispatch({type:"ui/status",text:"No model selected"});return}await this.openSessionAgentPicker({});return}const i=Ii(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=Qu(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 f=await this.createSession({});if(!f?.sessionId)return;r=f.sessionId,a=this.getState().sessions.byId[r]||null}if(!o.trim()){r&&this.getPendingOutboxItems(r).length>0&&await this.dispatchPendingOutbox(r).catch(()=>{});return}const l=a?.pendingQuestion||null,c=!!l?.question,d=this.getPromptEditSessionMatch(r);if(d){const f=this.getSessionOutbox(r).find(p=>p.id===d.itemId);if(f?.phase==="queued"||f?.phase==="cancelling"){this.exitPendingPromptEdit({restoreDraft:!0});return}this.setPrompt("",0),this.setPromptAttachments([]),await this.dispatchPendingOutbox(r).catch(()=>{});return}if(c&&typeof this.transport.sendAnswer=="function"){const f=Date.now(),p={...l,answer:o,answeredAt:f,pendingPhase:"pending"};this.setPrompt("",0),this.setPromptAttachments([]),this.dispatch({type:"sessions/merged",session:{sessionId:r,pendingQuestion:null,answeredPendingQuestion:p}}),this.dispatch({type:"ui/status",text:"Sending answer..."});try{await this.transport.sendAnswer(r,o),this.dispatch({type:"sessions/merged",session:{sessionId:r,answeredPendingQuestion:{...p,pendingPhase:"queued"}}}),this.scheduleSessionDetailSync(r,100),this.syncSessionEvents(r).catch(()=>{}),this.scheduleSessionsRefresh(1e3),this.dispatch({type:"ui/status",text:"Answer sent"})}catch(h){this.dispatch({type:"sessions/merged",session:{sessionId:r,answeredPendingQuestion:null}}),this.dispatch({type:"sessions/merged",session:{sessionId:r,pendingQuestion:l}}),String(this.getState().ui.prompt||"").trim()||this.setPrompt(o,String(o||"").length),this.dispatch({type:"ui/status",text:h?.message||String(h)})}return}this.queuePromptInOutbox(r,o),this.setPrompt("",0),this.setPromptAttachments([]),await this.dispatchPendingOutbox(r).catch(()=>{})}setPrompt(e,s=String(e||"").length){const n=String(e||""),i=Math.max(0,Math.min(Number.isFinite(s)?s:n.length,n.length)),o=this.getState().ui;if(!(o.prompt===n&&o.promptCursor===i)){if(o.promptEdit?.sessionId&&o.promptEdit?.itemId){const a=this.getSessionOutbox(o.promptEdit.sessionId).map(l=>l.id===o.promptEdit.itemId&&l.phase==="pending"?{...l,text:n}:l);this.setSessionOutboxItems(o.promptEdit.sessionId,a)}this.dispatch({type:"ui/prompt",prompt:n,promptCursor:i}),this.syncPromptReferenceBrowser()}}setPromptCursor(e){const s=this.getState().ui.prompt||"";this.setPrompt(s,e)}insertPromptText(e){const s=this.getState().ui,n=Fe(s.prompt,s.promptCursor,e);this.setPrompt(n.prompt,n.cursor)}appendPromptChar(e){this.insertPromptText(e)}deletePromptChar(){const e=this.getState().ui,s=Je(e.prompt,e.promptCursor);this.setPrompt(s.prompt,s.cursor)}deletePromptWordBackward(){const e=this.getState().ui,s=td(e.prompt,e.promptCursor);this.setPrompt(s.prompt,s.cursor)}movePromptCursor(e){const s=this.getState().ui;this.setPrompt(s.prompt,J(s.prompt,s.promptCursor+e))}movePromptCursorWord(e){const s=this.getState().ui;this.setPrompt(s.prompt,nr(s.prompt,s.promptCursor,e))}movePromptCursorVertical(e){const s=this.getState().ui,n=sd(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 wt({width:e.width??s.viewportWidth??120,height:e.height??s.viewportHeight??40},e.paneAdjust??s.paneAdjust??0,e.promptRows??n.promptRows??ot(i),e.sessionPaneAdjust??s.sessionPaneAdjust??0,e.activityPaneAdjust??s.activityPaneAdjust??0,e.fullscreenPane??n.fullscreenPane??null)}getSessionListMaxRows(e=this.getCurrentLayout()){const s=e.fullscreenPane===v.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=Pe(r,o);a!==r&&this.setFocus(a)}setFocus(e){this.dispatch({type:"ui/focus",focusRegion:Pe(e,this.getCurrentLayout())})}focusNext(){const e=this.getCurrentLayout(),s=Pe(this.getState().ui.focusRegion,e),n=Ns(e);this.setFocus(ze(n,s,1))}focusPrev(){const e=this.getCurrentLayout(),s=Pe(this.getState().ui.focusRegion,e),n=Ns(e);this.setFocus(ze(n,s,-1))}focusLeft(){const e=this.getCurrentLayout(),s=Pe(this.getState().ui.focusRegion,e);this.setFocus(ba(s,e))}focusRight(){const e=this.getCurrentLayout(),s=Pe(this.getState().ui.focusRegion,e);this.setFocus(wa(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=Pe(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=Pe(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=Pe(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===v.SESSIONS||s===v.CHAT){const a=mo(i),l=at+1,c=Math.min(go(o,i),i-Jt-1),d=s===v.CHAT?-e:e,f=r(n.sessionPaneAdjust,d,l-a,c-a);this.dispatch({type:"ui/sessionPaneAdjust",sessionPaneAdjust:f})}else if(s===v.INSPECTOR||s===v.ACTIVITY){const a=Math.max(it,Math.floor(i*ho)),l=it+1,c=i-Ut-1,d=s===v.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=ze(we,e,1);this.dispatch({type:"ui/inspectorTab",inspectorTab:s}),this.ensureInspectorData(s).catch(()=>{})}prevInspectorTab(){const e=ze(we,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){we.includes(e)&&(this.dispatch({type:"ui/inspectorTab",inspectorTab:e}),await this.ensureInspectorData(e).catch(()=>{}))}async moveSession(e){const s=this.getState(),n=Tt(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===v.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 nd.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:ku,force:!!s.force})}}getScrollablePaneForFocus(){const e=this.getState().ui.focusRegion;return e===v.CHAT?"chat":e===v.ACTIVITY?"activity":e===v.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=dn(e,n),r=[...fn(e,n),...un(e)],a=Math.min(Math.max(0,Math.floor(i*.34)),Xe(r,n)),l=Xe(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=hn(r);return{contentWidth:n,contentHeight:i,totalLines:Xe(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=Ue(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:Xe(d,n),totalLines:Xe(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=mn(d,{listWidth:a,previewWidth:a}),p=Math.max(9,o-4),h=Math.max(5,Math.min(10,Math.floor(p*.35)));let g=Math.max(5,Math.min(h,(f.listBodyLines||[]).length+2)),m=Math.max(5,p-g-1);const x=8;if(m<x){const y=x-m;g=Math.max(5,g-y),m=Math.max(5,p-g-1)}return{contentWidth:a,contentHeight:Math.max(1,m-2),totalLines:Xe(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)>=Oi){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:Kr})}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(Y,Number(i?.loadedEventLimit??Y)||Y),r=Y,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)),g=Array.isArray(s.eventTypes)&&s.eventTypes.length>0?s.eventTypes:void 0;if(typeof this.transport.getSessionEventsBefore=="function"&&a>0){p=i||Pt([],{requestedLimit:o});for(let y=0;y<h;y+=1){const S=Array.isArray(p?.events)&&p.events.length>0?Number(p.events[0]?.seq||0):0;if(!p?.hasOlderEvents||S<=1){p={...p,hasOlderEvents:!1};break}if(Number(p.loadedEventCount||0)>=Oi)break;const E=await this.transport.getSessionEventsBefore(e,S,r,g);if(!Array.isArray(E)||E.length===0){p={...p,hasOlderEvents:!1};break}const T=Pt(E,{requestedLimit:r}),C=[...T.events||[],...p?.events||[]];if(p={chat:st([...T.chat||[],...p?.chat||[]]),activity:[...T.activity||[],...p?.activity||[]],events:C,lastSeq:p?.lastSeq||p?.events?.[p?.events?.length-1]?.seq||E[E.length-1]?.seq||0,loadedEventLimit:C.length,loadedEventCount:C.length,hasOlderEvents:E.length>=r&&Number(E[0]?.seq||0)>1},!p.hasOlderEvents)break}}else{const y=fa(o);if(y<=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 S=await this.transport.getSessionEvents(e,void 0,y);p={...Pt(S,{requestedLimit:y}),lastSeq:S[S.length-1]?.seq||0}}this.dispatch({type:"history/set",sessionId:e,history:p});for(const y of p?.events||[])this.reconcileOutboxAgainstEvent(e,y);const m=Array.isArray(i?.chat)&&i.chat.length>0;if(l&&!m)this.dispatch({type:"ui/scroll",pane:"chat",offset:0});else if(l&&c>0){const y=this.getState(),S=this.getActiveChatRenderMetrics(y).totalLines,E=Math.max(0,S-d);E>0&&this.dispatch({type:"ui/scroll",pane:"chat",offset:c+E})}const x=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:x}),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||vs(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 I.REFRESH:await this.refreshSessions();return;case I.NEW_SESSION:await this.openNewSessionFlow();return;case I.OPEN_MODEL_PICKER:await this.openModelPicker();return;case I.OPEN_SWITCH_MODEL_PICKER:await this.openSwitchModelPicker();return;case I.OPEN_THEME_PICKER:this.openThemePicker();return;case I.OPEN_RENAME_SESSION:this.openRenameSessionModal();return;case I.CYCLE_SESSION_VISIBILITY:await this.cycleSessionVisibility();return;case I.OPEN_SHARE_SESSION:await this.openShareSessionModal();return;case I.OPEN_SESSION_FILTER:this.openSessionOwnerFilter();return;case I.OPEN_TERMINATE_PICKER:await this.openTerminatePickerModal();return;case I.OPEN_MOVE_TO_GROUP:await this.openMoveToGroupModal();return;case I.CREATE_SESSION_GROUP:await this.openMoveToGroupModal();return;case I.OPEN_ARTIFACT_UPLOAD:this.openArtifactUploadModal();return;case I.TOGGLE_CHAT_VIEW:this.toggleChatViewMode();return;case I.CLOSE_MODAL:this.closeModal();return;case I.MODAL_PREV:this.moveModalSelection(-1);return;case I.MODAL_NEXT:this.moveModalSelection(1);return;case I.MODAL_PANE_PREV:this.moveModalPane(-1);return;case I.MODAL_PANE_NEXT:this.moveModalPane(1);return;case I.MODAL_CONFIRM:await this.confirmModal();return;case I.SEND_PROMPT:await this.sendPrompt();return;case I.FOCUS_NEXT:this.focusNext();return;case I.FOCUS_PREV:this.focusPrev();return;case I.FOCUS_LEFT:this.focusLeft();return;case I.FOCUS_RIGHT:this.focusRight();return;case I.FOCUS_PROMPT:this.setFocus(v.PROMPT);return;case I.FOCUS_SESSIONS:this.setFocus(v.SESSIONS);return;case I.MOVE_SESSION_UP:await this.moveSession(-1);return;case I.MOVE_SESSION_DOWN:await this.moveSession(1);return;case I.EXPAND_SESSION:this.expandActiveSession();return;case I.COLLAPSE_SESSION:this.collapseActiveSession();return;case I.NEXT_INSPECTOR_TAB:this.nextInspectorTab();return;case I.PREV_INSPECTOR_TAB:this.prevInspectorTab();return;case I.CYCLE_INSPECTOR_TAB:this.cycleInspectorTab();return;case I.GROW_LEFT_PANE:this.adjustPaneSplit(8);return;case I.GROW_RIGHT_PANE:this.adjustPaneSplit(-8);return;case I.GROW_SESSION_PANE:this.adjustSessionPaneSplit(2);return;case I.SHRINK_SESSION_PANE:this.adjustSessionPaneSplit(-2);return;case I.GROW_FOCUSED_PANE:this.resizeFocusedPane(2);return;case I.SHRINK_FOCUSED_PANE:this.resizeFocusedPane(-2);return;case I.OPEN_ARTIFACT_PICKER:await this.openArtifactPicker();return;case I.OPEN_HELP:this.openHelpModal();return;case I.SEQUENCE_SELECT_PREV:this.moveSequenceSelection(-1);return;case I.SEQUENCE_SELECT_NEXT:this.moveSequenceSelection(1);return;case I.TOGGLE_SEQUENCE_TURN:this.toggleSequenceTurnExpanded();return;case I.TOGGLE_LOG_TAIL:this.toggleLogTail();return;case I.TOGGLE_STATS_VIEW:this.toggleStatsView();return;case I.OPEN_LOG_FILTER:this.openLogFilter();return;case I.OPEN_FILES_FILTER:this.openFilesFilter();return;case I.MOVE_FILE_UP:await this.moveFileSelection(-1);return;case I.MOVE_FILE_DOWN:await this.moveFileSelection(1);return;case I.DOWNLOAD_SELECTED_FILE:await this.downloadSelectedArtifact();return;case I.DELETE_SELECTED_FILE:await this.deleteSelectedArtifact();return;case I.OPEN_SELECTED_FILE:await this.openSelectedFileInDefaultApp();return;case I.TOGGLE_FILE_PREVIEW_FULLSCREEN:this.toggleFilePreviewFullscreen();return;case I.TOGGLE_PANE_FULLSCREEN:this.toggleFocusedPaneFullscreen();return;case I.SCROLL_UP:this.scrollCurrentPane(1);return;case I.SCROLL_DOWN:this.scrollCurrentPane(-1);return;case I.PAGE_UP:if(this.getState().ui.focusRegion===v.SESSIONS){await this.moveSessionPage(-1);return}this.scrollCurrentPane(10);return;case I.PAGE_DOWN:if(this.getState().ui.focusRegion===v.SESSIONS){await this.moveSessionPage(1);return}this.scrollCurrentPane(-10);return;case I.EXPAND_HISTORY:await this.expandActiveHistory();return;case I.SCROLL_TOP:this.scrollCurrentPaneToTop();return;case I.SCROLL_BOTTOM:this.scrollCurrentPaneToBottom();return;case I.CANCEL_SESSION:await this.cancelActiveSession();return;case I.STOP_TURN:await this.stopActiveSessionTurn();return;case I.DONE_SESSION:await this.completeActiveSession();return;case I.DELETE_SESSION:await this.deleteActiveSession();return;case I.PIN_SESSION:this.togglePinActiveSession();return;case I.TOGGLE_SELECT_MODE:this.toggleSessionSelectMode();return;case I.TOGGLE_SESSION_SELECTION:this.toggleActiveSessionSelection();return;case I.CLEAR_SESSION_SELECTION:this.clearSessionSelection();return;case I.OPEN_HISTORY_FORMAT:this.openHistoryFormat();return;case I.REFRESH_EXECUTION_HISTORY:{const s=this.getState().sessions.activeSessionId;s&&await this.ensureExecutionHistory(s,{force:!0});return}case I.EXPORT_EXECUTION_HISTORY:{await this.exportExecutionHistory();return}case I.OPEN_ADMIN_CONSOLE:await this.openAdminConsole();return;case I.CLOSE_ADMIN_CONSOLE:this.closeAdminConsole();return;case I.ADMIN_REFRESH_PROFILE:await this.refreshAdminProfile();return;case I.ADMIN_BEGIN_EDIT_GHCP_KEY:this.beginAdminEditGhcpKey();return;case I.ADMIN_CANCEL_EDIT_GHCP_KEY:this.cancelAdminEditGhcpKey();return;case I.ADMIN_SAVE_GHCP_KEY:await this.saveAdminGhcpKey();return;case I.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 ns=0;function he(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 Ts(){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 fd(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 pd(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 hd(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 md(t=2e3){const[e,s]=u.useState(()=>Ts());return u.useEffect(()=>{if(Ts()==null)return;const n=()=>{const o=Ts();o!=null&&s(r=>r===o?r:o)};n();const i=setInterval(n,t);return()=>clearInterval(i)},[t]),u.useMemo(()=>fd(e),[e])}function dt(t,e){return t&&e?{[t]:e}:{}}function Li(t){return typeof t=="string"?{text:t,color:"white"}:t}function Mt(t,e,s,n,i,o){const r=(e.tabs||we).map(f=>({text:f===e.activeTab?`[${f}] `:`${f} `,color:f===e.activeTab?"magenta":"gray",bold:f===e.activeTab})),a=(e.lines||[]).map(Li),l=(e.stickyLines||[]).map(Li),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:ns,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 Fi(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=Se(),l=md(),c=W(e,g=>({sessions:g.sessions,mode:g.connection?.mode||"local",brandingTitle:g.branding?.title||"PilotSwarm",focused:g.ui.focusRegion==="sessions",identityLabel:pd(g.auth)}),he),d=u.useMemo(()=>hd(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(()=>Rs(f,s),[f,s]),h=u.useMemo(()=>p.length===0?[{text:"No sessions yet. Press n to create one.",color:"gray"}]:p.map(g=>g.active?Io(g.runs,{preserveColors:!0}):g.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:ns,lines:h,paneId:"sessions",paneLabel:"Sessions",frame:o})});u.memo(function({controller:e,width:s,height:n,frame:i}){const o=Se(),r=W(e,E=>{const T=E.sessions.activeSessionId;return{activeSessionId:T,activeSession:T&&E.sessions.byId[T]||null,activeHistory:T&&E.history.bySessionId.get(T)||null,activeOutbox:T&&E.outbox?.bySessionId?.[T]||null,authPrincipal:E.auth?.principal||null,branding:E.branding,connectionError:E.connection.error,connectionMode:E.connection.mode,chatViewMode:E.ui.chatViewMode||"transcript",chatScroll:E.ui.scroll.chat,focused:E.ui.focusRegion==="chat"}},he),a=Math.max(20,s-4),l=u.useMemo(()=>{const E=new Map;return r.activeSessionId&&r.activeHistory&&E.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:dt(r.activeSessionId,r.activeSession)},history:{bySessionId:E},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(()=>Do(l,{width:a}),[a,l]),d=Yi(!!c?.animateTitleRight),f=u.useMemo(()=>Qi(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"}]:dn(l,a),[r.branding.splash,r.connectionError,a,l,p]),g=String(r.activeSession?.status||"").toLowerCase()==="running",m=zi(g),x=u.useMemo(()=>p?[]:un(l,{spinnerFrame:m,maxWidth:a}),[l,p,m,a]),y=u.useMemo(()=>p?[]:fn(l,a),[l,p,a]),S=u.useMemo(()=>y.length>0||x.length>0?[...y,...x]:[],[y,x]);return u.createElement(o.Panel,{title:c.title,titleRight:f,color:c.color,focused:r.focused,width:s,height:n,lines:h,bottomStickyLines:S,scrollOffset:r.chatScroll,scrollMode:"bottom",paneId:"chat",paneLabel:"Chat",frame:i})});const gd=u.memo(function({controller:e,width:s,height:n,shellTitle:i,focused:o=!1,frame:r,showFullscreenTitle:a=!1,embedded:l=!1}){const c=Se(),d=W(e,O=>({activeSessionId:O.sessions.activeSessionId,activeSession:O.sessions.activeSessionId&&O.sessions.byId[O.sessions.activeSessionId]||null,sessionsFlat:O.sessions.flat,filesBySessionId:O.files.bySessionId,filesFullscreen:!!O.files.fullscreen,selectedArtifactId:O.files.selectedArtifactId,filesFilter:O.files.filter,filePreviewScroll:O.ui.scroll.filePreview}),he),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(()=>mn(p,{listWidth:Math.max(8,f-4),previewWidth:Math.max(8,f-4)}),[f,p]),g=i||(a?h.fullscreenTitle:h.panelTitle||h.listTitle)||[{text:"Files",color:"magenta",bold:!0}],m=Math.max(9,n-4),x=Math.max(5,Math.min(10,Math.floor(m*.35)));let y=Math.max(5,Math.min(x,(h.listBodyLines||[]).length+2)),S=Math.max(5,m-y-1);const E=8;if(S<E){const O=E-S;y=Math.max(5,y-O),S=Math.max(5,m-y-1)}const T=Math.max(1,y-2),C=Math.max(0,h.selectedIndex-Math.floor(T/2)),_=!l&&r?{x:r.x+2,y:r.y+2,width:f,height:y}:null,k=!l&&r?{x:r.x+2,y:r.y+2+y+1,width:f,height:S}:null,R=we.map(O=>({text:O==="files"?`[${O}] `:`${O} `,color:O==="files"?"magenta":"gray",bold:O==="files"})),N=u.createElement(c.Column,{width:f},u.createElement(c.Lines,{lines:[R]}),u.createElement(c.Panel,{title:h.listTitle,color:"gray",focused:!1,width:f,height:y,lines:h.listBodyLines||h.listLines.slice(1),scrollOffset:C,scrollMode:"top",marginBottom:1,paneId:"files:list",paneLabel:"Files list",frame:_}),u.createElement(c.Panel,{title:h.previewTitle,color:"gray",focused:!1,width:f,height:S,lines:h.previewLines,scrollOffset:h.previewScrollOffset,scrollMode:"top",paneId:"files:preview",paneLabel:"File preview",frame:k}));return l?N:u.createElement(c.Panel,{title:g,color:"magenta",focused:o,width:s,height:n,marginBottom:ns,paneId:"inspector",paneLabel:"Inspector",frame:r},N)}),yd=u.memo(function({controller:e,width:s,height:n,frame:i,meta:o}){const r=Se(),a=Math.max(20,s-4),l=W(e,f=>({activeSessionId:f.sessions.activeSessionId,activeSession:f.sessions.activeSessionId&&f.sessions.byId[f.sessions.activeSessionId]||null}),he),c=u.useMemo(()=>({sessions:{activeSessionId:l.activeSessionId,byId:dt(l.activeSessionId,l.activeSession)},ui:{inspectorTab:"files"}}),[l.activeSession,l.activeSessionId]),d=u.useMemo(()=>Ue(c,{width:a}),[a,c]);return u.createElement(r.Panel,{title:d.title,color:"magenta",focused:o.focused,width:s,height:n,marginBottom:ns,paneId:"inspector",paneLabel:"Inspector",frame:i},u.createElement(gd,{controller:e,width:s,height:n,frame:i,focused:o.focused,embedded:!0}))}),Sd=u.memo(function({controller:e,width:s,height:n,frame:i,meta:o}){const r=Se(),a=Math.max(20,s-4),l=W(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}),he),c=u.useMemo(()=>({sessions:{activeSessionId:l.activeSessionId,byId:dt(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(()=>Ue(c,{width:a,sequenceExpansion:{expandedTurns:l.expandedTurns||[],selectedTurn:l.selectedTurn??null}}),[a,c,l.expandedTurns,l.selectedTurn]);return Mt(r,d,o,s,n,i)}),bd=u.memo(function({controller:e,width:s,height:n,frame:i,meta:o}){const r=Se(),a=Math.max(20,s-4),l=W(e,f=>({activeSessionId:f.sessions.activeSessionId,activeSession:f.sessions.activeSessionId&&f.sessions.byId[f.sessions.activeSessionId]||null,logs:f.logs}),he),c=u.useMemo(()=>({sessions:{activeSessionId:l.activeSessionId,byId:dt(l.activeSessionId,l.activeSession)},logs:l.logs,ui:{inspectorTab:"logs"}}),[l.activeSession,l.activeSessionId,l.logs]),d=u.useMemo(()=>Ue(c,{width:a}),[a,c]);return Mt(r,d,o,s,n,i)}),wd=u.memo(function({controller:e,width:s,height:n,frame:i,meta:o}){const r=Se(),a=Math.max(20,s-4),l=W(e,f=>({activeSessionId:f.sessions.activeSessionId,activeSession:f.sessions.activeSessionId&&f.sessions.byId[f.sessions.activeSessionId]||null,executionHistory:f.executionHistory}),he),c=u.useMemo(()=>({sessions:{activeSessionId:l.activeSessionId,byId:dt(l.activeSessionId,l.activeSession)},executionHistory:l.executionHistory,ui:{inspectorTab:"history"}}),[l.activeSession,l.activeSessionId,l.executionHistory]),d=u.useMemo(()=>Ue(c,{width:a}),[a,c]);return Mt(r,d,o,s,n,i)}),xd=u.memo(function({controller:e,width:s,height:n,frame:i,meta:o}){const r=Se(),a=Math.max(20,s-4),l=W(e,f=>({activeSessionId:f.sessions.activeSessionId,sessionsById:f.sessions.byId,sessionsFlat:f.sessions.flat,histories:f.history.bySessionId}),he),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(()=>Ue(c,{width:a}),[a,c]);return Mt(r,d,o,s,n,i)}),Id=u.memo(function({controller:e,width:s,height:n,frame:i,meta:o}){const r=Se(),a=Math.max(20,s-4),l=W(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}),he),c=u.useMemo(()=>({sessions:{activeSessionId:l.activeSessionId,byId:dt(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(()=>Ue(c,{width:a}),[a,c]);return Mt(r,d,o,s,n,i)});u.memo(function({controller:e,width:s,height:n,frame:i}){const o=W(e,r=>({inspectorTab:r.ui.inspectorTab,inspectorScroll:r.ui.scroll.inspector,inspectorFollowBottom:r.ui.followBottom?.inspector!==!1,focused:r.ui.focusRegion==="inspector"}),he);return o.inspectorTab==="files"?u.createElement(yd,{controller:e,width:s,height:n,frame:i,meta:o}):o.inspectorTab==="sequence"?u.createElement(Sd,{controller:e,width:s,height:n,frame:i,meta:o}):o.inspectorTab==="logs"?u.createElement(bd,{controller:e,width:s,height:n,frame:i,meta:o}):o.inspectorTab==="history"?u.createElement(wd,{controller:e,width:s,height:n,frame:i,meta:o}):o.inspectorTab==="stats"?u.createElement(Id,{controller:e,width:s,height:n,frame:i,meta:o}):u.createElement(xd,{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=Se(),a=W(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"}},he),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(()=>hn(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=Se(),i=W(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")}},he);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=Se(),n=W(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}),he),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(()=>tc(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:Fi(o.left,c),right:Fi(o.right,l)})});var Ed=Ir();const vd=920,or=7,rr=19,xn=.24,ar=16,lr=8,Td=224,Ad=190,Cd=48,Ne=16,cr=.5,ht=cr,kd=24,Md=700,Pd=5e3,Nd=new Set(["low","medium","high","xhigh"]),Od=["pilotswarm.theme","pilotswarm.sessionOwnerFilter","pilotswarm.chatFocus","pilotswarm.layoutAdjustments","pilotswarm.pinnedSessions"],_d=["pilotswarm_theme","pilotswarm_session_owner_filter"],Rd={sequence:"Sequence",logs:"Logs",nodes:"Node Map",history:"History",files:"Files",stats:"Stats"},Ld={sequence:"⇶",logs:"≣",nodes:"⬡",history:"⟲",files:"⧉",stats:"▁▄▇"};function Fd(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 $d(t){return typeof t?.transport?.uploadArtifactFromFile=="function"}function Bd(t){return typeof t?.transport?.uploadArtifactFromPath=="function"}function Dd(t){return typeof t?.transport?.listArtifacts=="function"}function Hd(t){return typeof t?.transport?.deleteArtifact=="function"}function Gd(t){return typeof t?.transport?.openPathInDefaultApp=="function"}function Ud(){if(!(typeof window>"u")){try{for(const t of Od)window.localStorage.removeItem(t)}catch{}try{for(const t of _d)document.cookie=`${t}=; Path=/; Max-Age=0; SameSite=Lax`}catch{}}}function rt(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()),ge(e,"sessionOwnerFilter")&&e.sessionOwnerFilter&&typeof e.sessionOwnerFilter=="object"&&(s.sessionOwnerFilter=e.sessionOwnerFilter),ge(e,"layoutAdjustments")&&(s.layoutAdjustments=Zs(e.layoutAdjustments)),ge(e,"pinnedSessionIds")&&(s.pinnedSessionIds=Vt(e.pinnedSessionIds)),ge(e,"collapsedSessionIds")&&(s.collapsedSessionIds=jd(e.collapsedSessionIds)),ge(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 jd(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 ge(t,e){return!!(t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,e))}function As(t){return rt({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 $i(t){return rt({themeId:t?.ui?.themeId,sessionOwnerFilter:Xt(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 Wd(t,e){const s=rt(t),n=rt(e);return rt({themeId:ge(s,"themeId")?s.themeId:n.themeId,sessionOwnerFilter:ge(s,"sessionOwnerFilter")?s.sessionOwnerFilter:n.sessionOwnerFilter,layoutAdjustments:ge(s,"layoutAdjustments")?s.layoutAdjustments:n.layoutAdjustments,pinnedSessionIds:ge(s,"pinnedSessionIds")?s.pinnedSessionIds:n.pinnedSessionIds,...ge(s,"collapsedSessionIds")?{collapsedSessionIds:s.collapsedSessionIds}:{},...ge(s,"activeSessionId")?{activeSessionId:s.activeSessionId}:{},...ge(s,"chatViewMode")?{chatViewMode:s.chatViewMode}:{}})}async function Vd(t,e){return typeof t?.transport?.setCurrentUserProfileSettings!="function"?null:t.transport.setCurrentUserProfileSettings({settings:rt(e)})}function In(t){return Dd(t)?we:we.filter(e=>e!=="files")}function ke(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 Gs(t,e,s){return Math.max(e,Math.min(s,t))}function Us(t){const e=Math.max(0,Number(t)||0),s=Math.max(0,e-ar-lr*2),n=s*xn,i=Math.max(0,s-Td);return{minAdjust:-n,maxAdjust:i-n}}function qd(t,e){const s=Us(t),n=Math.max(0,Number(t)||0),o=Math.max(0,n-ar-lr*2)*xn;return Gs(o+(Number(e)||0),0,o+s.maxAdjust)}function Kd(t){return t<=Cd?"hidden":t<=Ad?"compact":"wrap"}function ur(t){const e=Number(t?.ui?.promptRows);return Number.isFinite(e)&&e>0?e:ot(t?.ui?.prompt||"")}function is(t){return wt({width:t.ui.layout?.viewportWidth??120,height:t.ui.layout?.viewportHeight??40},t.ui.layout?.paneAdjust??0,ur(t),t.ui.layout?.sessionPaneAdjust??0)}function zd(t,e){const s=e==="sequence"?3:0;return Math.max(20,t-4-s)}function de(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 Zi(o.text||""))e.push({kind:"runs",runs:r,preserve:!0,splashVariant:o.variant});continue}if(n?.kind==="markdownTable"){e.push(n);continue}if(n?.kind==="runs"){const i=Array.isArray(n.runs)?n.runs:[];if(i.length===1){const o=i[0]||{},r=s(o.text||"");if(r.includes(`
|
|
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 Ge(t,e){if(e)return t?.tui?.[e]||t?.terminal?.[e]||t?.page?.[e]||e}function dr(t=[]){return t.map(e=>String(e?.text||"")).join("")}function Bi(t){return Array.isArray(t)?dr(t):String(t||"")}function Di(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 Yd(t){const e=_e(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 Hi(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 Qd(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/or)),height:Math.max(18,Math.floor(s/rr))}}function Xd(t){if(!t)return 0;const e=Math.max(0,t.scrollHeight-t.clientHeight);return Math.max(0,e-t.scrollTop)}function Jd(t){return Xd(t)<=cr}function Zd(t,e,s,n,i,o,{stickyBottom:r=!1}={}){const a=u.useMemo(()=>de(e),[e]),l=u.useRef(null),c=u.useRef({scrollMode:n,scrollOffset:s}),d=u.useRef({touching:!1,lastUserScrollAt:0,lastDispatchedOffset:null});u.useLayoutEffect(()=>{const y=t.current;if(!y)return;const S=c.current,E=d.current,T=typeof performance<"u"?performance.now():Date.now(),C=E.touching||T-(E.lastUserScrollAt||0)<Md,_=E.lastDispatchedOffset!=null&&Math.abs((Number(s)||0)-E.lastDispatchedOffset)<2;if(C&&n===S?.scrollMode&&(s===S?.scrollOffset||_)){c.current={scrollMode:n,scrollOffset:s};return}const k=Math.max(0,y.scrollHeight-y.clientHeight),R=r&&n==="top"&&S?.scrollMode==="top"&&S?.scrollOffset===s,N=Math.max(0,Number(s)||0)*Ne,O=R?Math.max(0,Math.min(y.scrollTop,k)):n==="bottom"?Math.max(0,k-N):Math.min(k,N);if(Math.abs(y.scrollTop-O)>ht){const U={target:O};l.current=U,y.scrollTop=O,window.requestAnimationFrame(()=>{l.current===U&&(l.current=null)})}c.current={scrollMode:n,scrollOffset:s}},[a,t,n,s,r]);const f=u.useCallback(()=>{const y=t.current;if(!y||!i)return;const S=l.current;if(S){if(Math.abs(y.scrollTop-S.target)<=ht)return;l.current=null}d.current.lastUserScrollAt=typeof performance<"u"?performance.now():Date.now();const E=Math.max(0,y.scrollHeight-y.clientHeight);if(E<=0)return;if(r&&typeof o.updatePaneScrollFromViewport=="function"){const C=Math.max(0,y.scrollTop)/Ne;d.current.lastDispatchedOffset=C,o.updatePaneScrollFromViewport(i,C,{atBottom:Jd(y)});return}const T=n==="bottom"?Math.max(0,E-y.scrollTop):Math.max(0,y.scrollTop);d.current.lastDispatchedOffset=T/Ne,o.dispatch({type:"ui/scroll",pane:i,offset:T/Ne}),i==="chat"&&n==="bottom"&&y.scrollTop<=ht&&o.armChatTopHistoryLoad?.()},[o,i,t,n,r]),p=u.useCallback(y=>{const S=t.current;if(!S||i!=="chat"||n!=="bottom"||y.deltaY>=0||S.scrollTop>ht)return;const E=Math.max(0,S.scrollHeight-S.clientHeight);o.handleChatTopHistoryScrollIntent?.(E/Ne)},[o,i,t,n]),h=u.useRef({startY:null,fired:!1}),g=u.useCallback(y=>{d.current.touching=!0,!(i!=="chat"||n!=="bottom")&&(h.current={startY:y.touches?.[0]?.clientY??null,fired:!1})},[i,n]),m=u.useCallback(()=>{d.current.touching=!1,d.current.lastUserScrollAt=typeof performance<"u"?performance.now():Date.now()},[]),x=u.useCallback(y=>{const S=t.current,E=h.current;if(!S||i!=="chat"||n!=="bottom"||E.fired||E.startY==null||S.scrollTop>ht)return;const T=y.touches?.[0]?.clientY;if(T==null||T-E.startY<kd)return;E.fired=!0;const C=Math.max(0,S.scrollHeight-S.clientHeight);o.handleChatTopHistoryScrollIntent?.(C/Ne+1,{force:!0})},[o,i,t,n]);return{normalizedLines:a,onScroll:f,onWheel:p,onTouchStart:g,onTouchMove:x,onTouchEnd:m}}function fe({runs:t,theme:e}){return u.createElement(u.Fragment,null,(t||[]).map((s,n)=>{const i={color:Ge(e,s.color),backgroundColor:Ge(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 ef({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:Ge(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(hr,{content:s,theme:e})):null)}function le({line:t,theme:e,className:s=""}){const n=s?`ps-line ${s}`:"ps-line";return t?t.kind==="systemNotice"?u.createElement(ef,{line:t,theme:e}):t.kind==="runs"?u.createElement("div",{className:n},u.createElement(fe,{runs:t.runs,theme:e})):u.createElement("div",{className:n,style:{color:Ge(e,t.color),backgroundColor:Ge(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"?dr(t.runs):String(t.text||""):""}function tf(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)*Ne);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)/Ne})},[n,s,t])}function Ae(t,e,s="md"){return zs(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"},Ae(n.text,e,`${o}:strong`)):n.type==="em"?u.createElement("em",{key:o,className:"ps-md-em"},Ae(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:Ge(e,"cyan")}},n.text):u.createElement(u.Fragment,{key:o},n.text)})}function js(t=""){return String(t||"").replace(/\s+/g," ").trim()}const sf=["description","mechanism","details","notes","summary","message","comment","reason","body","content","explanation","rationale","one-liner"],nf=24,of=32,rf=6,Gi=30,af=56,Cs=.4,lf=1.4,cf=2;function fr(t=[]){const e=Math.max(0,...t.map(g=>g.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 g=0;g<t.length;g+=1){const m=t[g];for(let x=0;x<e;x+=1){const y=js(m[x]||"");y.length>i[x].max&&(i[x].max=y.length),g>0&&/\s/.test(y)&&(i[x].spaceCells+=1)}}let o=-1,r=0;for(let g=0;g<e;g+=1){const m=i[g];if(m.max<nf||m.spaceCells/n<.4)continue;const y=js(s[g]||"").toLowerCase(),S=sf.some(T=>y.includes(T))?60:0,E=m.max+S;E>r&&(r=E,o=g)}if(o<0)return null;const a=i.map((g,m)=>m===o?0:Math.max(rf,Math.min(g.max+2,of))),l=a.reduce((g,m)=>g+m,0),c=i[o],d=Math.max(Gi,Math.min(c.max*.45,af,Math.max(Gi,l*lf))),f=a.map((g,m)=>m===o?d:g),p=f.reduce((g,m)=>g+m,0);if(p>0&&f[o]/p<Cs){const g=p-f[o];f[o]=g*(Cs/(1-Cs))}const h=f.reduce((g,m)=>g+m,0);return h>0?{widths:f.map(g=>`${(g/h*100).toFixed(2)}%`),flexIndex:o,minWidth:`${Math.ceil(h+cf)}ch`}:null}function pr(t=[],e=0){return Array.from({length:e},(s,n)=>(Array.isArray(t)?t:[]).map(o=>js(o?.[n]||"")).filter(Boolean).join(" / ")||null)}function Ui(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 ji(t=""){return String(t||"").trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(s=>s.trim())}function uf(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=ji(o);i+=2;const p=[];for(;i<s.length&&s[i].includes("|")&&s[i].trim();)p.push(ji(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],g=/^(\s*)([-*]|\d+\.)\s+(.*)$/.exec(h);if(!g||/\d+\./.test(g[2])!==f)break;const m=[g[3].trim()];for(i+=1;i<s.length&&s[i].trim()&&!/^(\s*)([-*]|\d+\.)\s+/.test(s[i])&&!Ui(s[i],s[i+1]||"");)m.push(s[i].trim()),i+=1;if(p.push(m.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()&&!Ui(s[i],s[i+1]||"");)d.push(s[i].trim()),i+=1;n.push({type:"paragraph",text:d.join(" ")})}return n}function hr({content:t,theme:e}){const s=u.useMemo(()=>uf(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}`},Ae(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"},Ae(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"},Ae(r,e,`list:${i}:${a}`))))}if(n.type==="table"){const o=Math.max(n.header.length||0,...n.rows.map(g=>g.length)),r=o>0&&o<=6,a=r?fr([n.header,...n.rows]):null,l=!!a,c=a?a.flexIndex:-1,d=g=>g===c?"is-flex-column":null,f=pr([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((g,m)=>u.createElement("col",{key:`col:${m}`,className:d(m)||void 0,style:{width:g}}))):null,u.createElement("thead",null,u.createElement("tr",null,n.header.map((g,m)=>u.createElement("th",{key:`head:${m}`,className:d(m)||void 0},Ae(g,e,`table:${i}:head:${m}`))))),u.createElement("tbody",null,n.rows.map((g,m)=>u.createElement("tr",{key:`row:${m}`},g.map((x,y)=>u.createElement("td",{key:`cell:${m}:${y}`,className:d(y)||void 0,"data-label":f[y]||void 0},u.createElement("span",{className:"ps-table-cell-value"},Ae(x,e,`table:${i}:${m}:${y}`)))))))))}return u.createElement("p",{key:`block:${i}`,className:"ps-md-paragraph"},Ae(n.text,e,`para:${i}`))}))}function df({controller:t,title:e,color:s,focused:n,scrollOffset:i=0,paneKey:o,theme:r,content:a}){const l=u.useRef(null),c=tf(l,i,o,t);return u.createElement(qe,{title:e,color:s,focused:n,theme:r},u.createElement("div",{ref:l,className:"ps-scroll-panel ps-markdown-scroll",onScroll:c},u.createElement(hr,{content:a,theme:r})))}function ff(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 pf({title:t,color:e,focused:s,theme:n,filename:i,contentType:o,sizeBytes:r,source:a,uploadedAt:l}){const c=[];o&&c.push(o),r!=null&&c.push(ff(r)),a&&c.push(a);const d=l?new Date(l).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}):"";return u.createElement(qe,{title:t,color:e,focused:s,theme:n},u.createElement("div",{className:"ps-binary-preview-card"},u.createElement("div",{className:"ps-binary-preview-kicker"},"Binary artifact"),u.createElement("h3",{className:"ps-binary-preview-title"},i||"Artifact"),c.length>0?u.createElement("div",{className:"ps-binary-preview-meta"},c.join(" • ")):null,d?u.createElement("div",{className:"ps-binary-preview-time"},`Uploaded ${d}`):null,u.createElement("p",{className:"ps-binary-preview-copy"},"Preview is intentionally disabled for non-text artifacts in the browser workspace. Use Download to save the file and open it in the default app.")))}function $t(t){const e=String(t||"").trim();return e.startsWith("┌")&&e.endsWith("┐")}function ks(t){const e=String(t||"").trim();return e.startsWith("└")&&e.endsWith("┘")}function hf(t){const e=String(t||"").trim();return e.startsWith("├")&&e.endsWith("┤")}function xt(t){const e=String(t||"").trim();return e.startsWith("│")&&e.endsWith("│")}function mf(t){const e=String(be(t)||"").trim();return $t(e)?e.slice(1,-1).replace(/^─+/u,"").replace(/─+$/u,"").trim():""}function gf(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 xt(e)?String(e).slice(1,-1).replace(/\s+$/u,""):String(e||"")}function yf(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 Wi(t,{fallbackColor:e=null}={}){return t?.kind==="runs"&&Array.isArray(t.runs)&&t.runs.length>=3?yf(t.runs.slice(1,-1)):[{text:be(t).replace(/^\s*[┌│]\s?/,"").replace(/\s?[┐│]\s*$/,"").replace(/^─+/,"").replace(/─+$/,"").trim(),color:e}]}function Sf(t){const e=String(t||"").trim();return xt(e)?e.slice(1,-1).split("│").map(s=>s.trim()):[]}function bf(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 wf(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)=>bf(s,n)?`${s}${n}`:`${s} ${n}`,e[0])}function Vi(t=[]){const e=Math.max(0,...t.map(s=>s.length));return Array.from({length:e},(s,n)=>wf(t.map(i=>String(i[n]||"").trim()).filter(Boolean)))}function xf(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==="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($t(i)&&i.includes("┬")){const o=[],r=[];let a=[],l=!0;for(s+=1;s<t.length;){const c=t[s],d=be(c);if(ks(d)){if(a.length>0){const f=Vi(a);f.length>0&&(l?o.push(f):r.push(f))}s+=1;break}if(hf(d)){if(a.length>0){const f=Vi(a);f.length>0&&(l?o.push(f):r.push(f))}a=[],l=!1,s+=1;continue}if(xt(d)){const f=Sf(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&&$t(i)){const o=mf(n),r=[];for(s+=1;s<t.length;){const a=t[s],l=be(a);if(ks(l)){s+=1;break}xt(l)?r.push(gf(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&&$t(i)){const o=Wi(n),r=n.runs[0]?.color||"gray",a=[];for(s+=1;s<t.length;){const l=t[s],c=be(l);if(ks(c)){s+=1;break}xt(c)?a.push(Wi(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 If({lines:t,theme:e}){const s=u.useMemo(()=>xf(t),[t]);return u.createElement(u.Fragment,null,s.map((n,i)=>{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(le,{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":Ge(e,n.borderColor)||"var(--ps-border)"}},u.createElement("header",{className:"ps-chat-card-header"},u.createElement(fe,{runs:n.headerRuns,theme:e})),u.createElement("div",{className:"ps-chat-card-body"},(n.bodyLines||[]).map((o,r)=>u.createElement("div",{key:`card:${i}:line:${r}`,className:"ps-chat-card-line"},u.createElement(fe,{runs:o,theme:e})))));if(n.type==="table"){const o=n.headerRows||[],r=n.bodyRows||[],a=Math.max(1,...o.map(x=>x.length),...r.map(x=>x.length)),l=a<=6,c=l?fr([...o,...r]):null,d=!!c,f=c?c.flexIndex:-1,p=x=>x===f?"is-flex-column":null,h=pr(o,a),g=`ps-chat-table${l?" is-fit-width":""}${d?" has-flex-column":""}`,m=`ps-chat-table-wrap${l?" is-fit-width":""}${d?" has-flex-column":""}`;return u.createElement("div",{key:`table:${i}`,className:m},u.createElement("table",{className:g,style:c?.minWidth?{"--ps-table-min-width":c.minWidth}:void 0},c?u.createElement("colgroup",null,c.widths.map((x,y)=>u.createElement("col",{key:`col:${y}`,className:p(y)||void 0,style:{width:x}}))):null,o.length>0?u.createElement("thead",null,o.map((x,y)=>u.createElement("tr",{key:`thead:${y}`},Array.from({length:a},(S,E)=>u.createElement("th",{key:`th:${y}:${E}`,className:p(E)||void 0},Ae(x[E]||"",e,`chat-table:${i}:head:${y}:${E}`)))))):null,u.createElement("tbody",null,r.map((x,y)=>u.createElement("tr",{key:`tbody:${y}`},Array.from({length:a},(S,E)=>u.createElement("td",{key:`td:${y}:${E}`,className:p(E)||void 0,"data-label":h[E]||void 0},u.createElement("span",{className:"ps-table-cell-value"},Ae(x[E]||"",e,`chat-table:${i}:${y}:${E}`)))))))))}return u.createElement(le,{key:`line:${i}`,line:n.line,theme:e})}))}function qe({title:t,titleRight:e=null,color:s="gray",focused:n=!1,actions:i=null,children:o,theme:r,className:a=""}){const l=Ge(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(fe,{runs:t,theme:r}):Bi(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(fe,{runs:e,theme:r}):Bi(e)):null,i?u.createElement("div",{className:"ps-panel-actions"},i):null):null),u.createElement("div",{className:"ps-panel-body"},o))}function Ef({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]||"",g=p.length>1&&Nd.has(h.toLowerCase())?p.length-2:p.length-1;return p[Math.max(0,g)]||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(k=>k?.completedTurn!=null)?.completedTurn:null,h=p!=null?s.get(Number(p)):null;if(!h)return u.createElement(le,{key:`line:${f}`,line:d,theme:e});const g=h.data||{},m=String(h.seq??`${g.turnIndex??p}:${h.createdAt??f}`),x=n.has(m),y=g.reasoningEffort?`${g.model||"(unknown)"}:${g.reasoningEffort}`:g.model||"(unknown)",S=c(g.model),E=g.durationMs!=null?l(g.durationMs):"duration n/a",T=g.durationMs!=null?`${r(g.durationMs)} ms`:"duration n/a",C=`${a(g.tokensInput)} / ${a(g.tokensOutput)}`,_=[["model",y],["started",g.startedAt?new Date(g.startedAt).toLocaleString():null],["ended",g.endedAt?new Date(g.endedAt).toLocaleString():null],["duration",T],["tokens",`${r(g.tokensInput)} in / ${r(g.tokensOutput)} out`],["cache",`${r(g.tokensCacheRead)} read / ${r(g.tokensCacheWrite)} write`],["tools",`${r(g.toolCalls)} calls / ${r(g.toolErrors)} errors`],["names",Array.isArray(g.toolNames)&&g.toolNames.length?g.toolNames.join(", "):null],["worker",g.workerNodeId||null],["result",g.resultType||null],["error",g.errorMessage||null]].filter(([,k])=>k!=null&&k!=="");return u.createElement(u.Fragment,{key:`seq:${f}`},u.createElement(le,{line:d,theme:e}),u.createElement("button",{type:"button",className:"ps-sequence-turn-divider",onClick:()=>o(m)},u.createElement("span",{className:"ps-sequence-turn-caret"},x?"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"},S),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"},E),u.createElement("span",{className:"ps-sequence-turn-rule"},") ---")),x?u.createElement("div",{className:"ps-sequence-turn-details"},_.map(([k,R])=>u.createElement("div",{key:k},u.createElement("span",{className:"ps-sequence-turn-detail-label"},`${k}: `),u.createElement("span",null,String(R))))):null)}))}function os({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:g=null,bottomContent:m=null,structuredBlocks:x=!1,stickyBottom:y=!1,renderBody:S=null}){const E=W(f,A=>A.ui.themeId),T=_e(E),C=u.useRef(null),_=u.useRef(null),k=u.useRef(!1),{normalizedLines:R,onScroll:N,onWheel:O,onTouchStart:U,onTouchMove:L,onTouchEnd:K}=Zd(C,o,l,c,d,f,{stickyBottom:y}),P=u.useMemo(()=>de(r),[r]),F=u.useMemo(()=>de(a),[a]),V=p.includes("is-preserve")&&h.includes("has-preserved-sticky"),q=u.useCallback((A,M)=>{!A||!M||Math.abs((M.scrollLeft||0)-(A.scrollLeft||0))<=1||(k.current=!0,M.scrollLeft=A.scrollLeft,window.requestAnimationFrame(()=>{k.current=!1}))},[]),[ne,ce]=u.useState({up:!1,down:!1}),ue=u.useCallback(A=>{if(!A)return;const M=A.scrollHeight-A.scrollTop-A.clientHeight>4,$=A.scrollTop>4;ce(H=>H.up===M&&H.down===$?H:{up:M,down:$})},[]),b=u.useCallback(A=>{N(),ue(A.currentTarget),!(!V||k.current)&&q(A.currentTarget,_.current)},[N,V,q,ue]);u.useEffect(()=>{ue(C.current)});const w=u.useCallback(A=>{!V||k.current||q(A.currentTarget,C.current)},[V,q]);return u.createElement(qe,{title:t,titleRight:e,color:s,focused:n,actions:i,theme:T,className:h},g,P.length>0?u.createElement("div",{ref:_,className:`ps-panel-sticky${V?" is-scroll-sync":""}`,onScroll:w},P.map((A,M)=>u.createElement(le,{key:`sticky:${M}`,line:A,theme:T}))):null,u.createElement("div",{ref:C,className:`ps-scroll-panel ${p}${ne.down?" is-scrolled-down":""}${ne.up?" is-scrolled-up":""}`.trim(),onScroll:b,onWheel:O,onTouchStart:U,onTouchMove:L,onTouchEnd:K,onTouchCancel:K},typeof S=="function"?S(R,T):x?u.createElement(If,{lines:R,theme:T}):R.map((A,M)=>u.createElement(le,{key:`line:${M}`,line:A,theme:T}))),F.length>0?u.createElement("div",{className:"ps-panel-bottom-sticky"},F.map((A,M)=>u.createElement(le,{key:`bottom-sticky:${M}`,line:A,theme:T}))):null,m)}function vf({row:t,theme:e,structured:s=!1}){if(!(s&&Array.isArray(t.titleRuns)))return Array.isArray(t.runs)?u.createElement(fe,{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(fe,{runs:t.titleRuns,theme:e})),r?u.createElement("div",{className:"ps-session-row-ctx"},u.createElement(fe,{runs:i,theme:e})):null),a?u.createElement("div",{className:"ps-session-row-detail"},u.createElement(fe,{runs:o,theme:e})):null)}function En({controller:t,actions:e=null,panelClassName:s="",structuredRows:n=!1}){const i=W(t,P=>P.ui.themeId),o=_e(i),r=u.useRef(new Map),a=W(t,P=>({activeSessionId:P.sessions.activeSessionId,sessionsById:P.sessions.byId,sessionsFlat:P.sessions.flat,filterQuery:P.sessions.filterQuery||"",ownerFilter:P.sessions.ownerFilter,pinnedIds:P.sessions.pinnedIds,selectedIds:P.sessions.selectedIds,selectMode:P.sessions.selectMode,auth:P.auth,connectionMode:P.connection?.mode||"local",modalOpen:!!P.ui.modal,focused:P.ui.focusRegion==="sessions"}),ke),l=u.useMemo(()=>Tt({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=a.auth?.principal||null,h=a.auth?.authorization?.role,g=h==="admin"||h==="anonymous",m=!!(c?.owner&&p&&String(c.owner.provider)===String(p.provider)&&String(c.owner.subject)===String(p.subject)),x=!!(c&&!c.isSystem&&!c.isGroup&&(g||m)),y=Array.isArray(a.selectedIds)?a.selectedIds.length:0,S=y>1,E=!!(c&&!c.isSystem&&(c.isGroup||!c.parentSessionId&&!c.groupId)),T=!!(c&&Array.isArray(a.pinnedIds)&&a.pinnedIds.includes(c.sessionId)),C=!!(c?.isGroup&&Number(c.memberCount||0)===0),_=S?Array.isArray(a.selectedIds)&&a.selectedIds.some(P=>{const F=a.sessionsById[P];return F&&!F.isSystem&&!F.isGroup}):c?.isGroup?!0:!!c,k=c?.isGroup?"Delete":S?`Terminate (${y})`:c?.isSystem?"Restart":"Terminate",N=y>0?a.selectedIds.filter(P=>{const F=a.sessionsById[P];return F&&!F.isSystem&&!F.isGroup&&!F.parentSessionId}):c&&!c.isSystem&&!c.isGroup&&!c.parentSessionId?[c.sessionId]:[],O=N.length>0,U=`ps-session-pane${s?` ${s}`:""}`,L=u.useCallback((P,F)=>{P&&(F?r.current.set(P,F):r.current.delete(P))},[]);u.useEffect(()=>{if(a.modalOpen||!a.focused||!a.activeSessionId)return;const P=r.current.get(a.activeSessionId);P&&(document.activeElement!==P&&P.focus({preventScroll:!0}),P.scrollIntoView({block:"nearest"}))},[a.activeSessionId,a.focused,a.modalOpen]);const K=u.createElement(u.Fragment,null,S?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."},`${y} selected`):null,S?u.createElement(ee,{className:"ps-mini-button",icon:"✕",label:"Clear multi-selection",onClick:()=>t.handleCommand(I.CLEAR_SESSION_SELECTION).catch(()=>{})}):u.createElement(ee,{className:"ps-mini-button",icon:"📌",onClick:()=>t.handleCommand(I.PIN_SESSION).catch(()=>{}),disabled:!E,active:T,label:E?T?"Unpin this session":"Pin this session to the top of the list":"Only top-level non-system sessions can be pinned"}),u.createElement(ee,{className:"ps-mini-button",icon:N.length>1?`⊞${N.length}`:"⊞",onClick:()=>t.handleCommand(I.OPEN_MOVE_TO_GROUP).catch(()=>{}),disabled:!O,label:O?N.length>1?`Move ${N.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(ee,{className:"ps-mini-button",icon:u.createElement(Tf),onClick:()=>{const P=c?.sessionId;if(!P||typeof window>"u"||!window.location)return;const F=`${window.location.origin}${window.location.pathname}?session=${encodeURIComponent(P)}`;navigator?.clipboard?.writeText&&navigator.clipboard.writeText(F).catch(()=>{}),t.dispatch({type:"ui/status",text:"Session link copied to clipboard"})},disabled:!c||c.isGroup||S,label:"Share — copy a direct link to this session"}),u.createElement(ee,{className:"ps-mini-button",icon:"✎",onClick:()=>f(!0),disabled:!x||S,label:S?"Disabled while multiple sessions are selected":"Modify — rename and share access"}),u.createElement(ee,{className:"ps-mini-button",icon:c?.isSystem?"↻":"⊗",onClick:()=>t.handleCommand(c?.isGroup?I.DELETE_SESSION:I.OPEN_TERMINATE_PICKER).catch(()=>{}),disabled:!_,label:S?`Terminate ${y} selected sessions (Mark Completed, Cancel, or Delete)`:c?.isGroup?C?"Delete this empty group":"This group cannot be deleted yet":c?.isSystem?"Restart this system session (complete, terminate, or hard delete)":`${k} — mark completed, cancel, or delete`}),e);return u.createElement(u.Fragment,null,u.createElement(qe,{title:[{text:"Sessions",color:"yellow",bold:!0}],color:"yellow",focused:a.focused,theme:o,actions:K,className:U},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(P=>u.createElement("button",{key:P.sessionId,type:"button",ref:F=>L(P.sessionId,F),className:`ps-list-button ps-session-list-button${P.active?" is-selected":""}${P.selected?" is-multiselected":""}${P.pinned?" is-pinned":""}`,tabIndex:P.active?0:-1,"aria-selected":P.active?"true":"false",onClick:F=>{if(F.metaKey||F.ctrlKey){F.preventDefault(),a.selectMode||t.dispatch({type:"sessions/selectMode",enabled:!0}),t.dispatch({type:"sessions/selectToggle",sessionId:P.sessionId}),t.setFocus("sessions");return}if(F.shiftKey&&a.activeSessionId){F.preventDefault();const q=l.map(ue=>ue.sessionId),ne=q.indexOf(a.activeSessionId),ce=q.indexOf(P.sessionId);if(ne>=0&&ce>=0){const[ue,b]=ne<=ce?[ne,ce]:[ce,ne],w=q.slice(ue,b+1),A=Array.from(new Set([...a.selectedIds||[],...w]));t.setSessionSelection(A),t.setFocus("sessions");return}}if(P.hasChildren&&P.active){t.dispatch({type:P.collapsed?"sessions/expand":"sessions/collapse",sessionId:P.sessionId}),t.setFocus("sessions");return}a.selectMode&&t.dispatch({type:"sessions/selectClear"}),t.setFocus("sessions"),P.active||t.loadSession(P.sessionId).catch(()=>{})}},u.createElement("div",{className:"ps-line ps-session-row-content",style:{paddingInlineStart:`${Math.max(0,P.depth)*18}px`}},u.createElement(vf,{row:P,theme:o,structured:n})))))),d&&c&&!c.isGroup?u.createElement(Cf,{controller:t,sessionId:c.sessionId,initialTitle:c.title||"",principal:a.auth?.principal||null,onClose:()=>f(!1),onChanged:()=>{}}):null)}const qi={private:{glyph:"🔒",label:"Private"},shared_read:{glyph:"👁",label:"Shared · read"},shared_write:{glyph:"✎",label:"Shared · write"}};function Tf(){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("circle",{cx:"18",cy:"5",r:"3"}),u.createElement("circle",{cx:"6",cy:"12",r:"3"}),u.createElement("circle",{cx:"18",cy:"19",r:"3"}),u.createElement("line",{x1:"8.6",y1:"10.5",x2:"15.4",y2:"6.5"}),u.createElement("line",{x1:"8.6",y1:"13.5",x2:"15.4",y2:"17.5"}))}function Af(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 Cf({controller:t,sessionId:e,initialTitle:s,principal:n,onClose:i,onChanged:o}){const[r,a]=u.useState(null),[l,c]=u.useState(s||""),[d,f]=u.useState([]),[p,h]=u.useState("private"),[g,m]=u.useState(""),[x,y]=u.useState("write"),[S,E]=u.useState([]),[T,C]=u.useState(!1),[_,k]=u.useState(null);u.useEffect(()=>{let w=!1;return t.transport.getSessionAccess(e).then(A=>{!w&&A&&(a(A),h(A.visibility||"private"))}).catch(()=>{}),typeof t.transport.listKnownUsers=="function"&&t.transport.listKnownUsers({limit:500}).then(A=>{w||E(Array.isArray(A)?A:[])}).catch(()=>{}),()=>{w=!0}},[t,e]);const R=u.useCallback(()=>{t.transport.listSessionShares(e).then(w=>f(Array.isArray(w)?w:[])).catch(()=>f([]))},[t,e]);u.useEffect(()=>{R()},[R]);const N=async w=>{C(!0),k(null);try{await w(),o?.()}catch(A){k(A?.message||String(A))}finally{C(!1)}},O=()=>N(async()=>{await t.transport.renameSession(e,l.trim())}),U=w=>N(async()=>{await t.transport.setSessionVisibility(e,w),h(w)}),L=w=>{const A=w.trim().toLowerCase();if(!A)return null;const M=S.find($=>$.displayName&&$.displayName.toLowerCase()===A||$.email&&$.email.toLowerCase()===A||$.subject&&$.subject.toLowerCase()===A);return M||{provider:n?.provider||"dev",subject:w.trim(),email:null,displayName:null}},K=w=>N(async()=>{await t.transport.grantSessionShare(e,{provider:w.provider,subject:w.subject,email:w.email??null,displayName:w.displayName??null},x),m(""),R()}),P=()=>{const w=L(g);w&&K(w)},F=new Set(d.map(w=>`${w.provider}${w.subject}`)),V=r?.owner?`${r.owner.provider}${r.owner.subject}`:null,q=g.trim().toLowerCase(),ne=q?S.filter(w=>{const A=`${w.provider}${w.subject}`;return A===V||F.has(A)?!1:w.displayName&&w.displayName.toLowerCase().includes(q)||w.email&&w.email.toLowerCase().includes(q)||w.subject&&w.subject.toLowerCase().includes(q)}).slice(0,25):[],ce=w=>N(async()=>{await t.transport.revokeSessionShare(e,{provider:w.provider,subject:w.subject}),R()}),ue=!!r?.canManage,b=w=>w.stopPropagation();return u.createElement("div",{className:"ps-share-overlay",onClick:i},u.createElement("div",{className:"ps-share-modal",onClick:b},u.createElement("div",{className:"ps-share-modal-head"},u.createElement("span",null,"Modify session"),u.createElement("button",{className:"ps-modal-close",onClick:i},"✕")),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:l,disabled:T,onChange:w=>c(w.target.value),onKeyDown:w=>{w.key==="Enter"&&O()}}),u.createElement("button",{className:"ps-mini-button",disabled:T||!l.trim(),onClick:O},"Save")),ue?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(w=>u.createElement("label",{key:w,className:`ps-share-radio${p===w?" is-active":""}`},u.createElement("input",{type:"radio",name:"visibility",checked:p===w,disabled:T,onChange:()=>U(w)}),u.createElement("span",{className:"ps-share-radio-glyph"},qi[w].glyph),u.createElement("span",null,qi[w].label),u.createElement("span",{className:"ps-share-radio-hint"},w==="private"?"only you and admins":w==="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."),d.length===0?u.createElement("div",{className:"ps-share-empty"},"No individual grants — everyone has the general access above."):d.map(w=>u.createElement("div",{key:`${w.provider}/${w.subject}`,className:"ps-share-grant-row"},u.createElement("span",{className:"ps-share-grant-name"},w.displayName||w.subject),u.createElement("span",{className:"ps-share-grant-access"},`can ${w.access}`),u.createElement("button",{className:"ps-mini-button",disabled:T,onClick:()=>ce(w)},"Revoke"))),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:g,disabled:T,autoComplete:"off",onChange:w=>m(w.target.value),onKeyDown:w=>{w.key==="Enter"&&P()}}),u.createElement("select",{className:"ps-share-add-select",value:x,disabled:T,onChange:w=>y(w.target.value)},u.createElement("option",{value:"read"},"can read"),u.createElement("option",{value:"write"},"can write")),u.createElement("button",{className:"ps-mini-button",disabled:T||!g.trim(),onClick:P},"Add")),ne.length>0?u.createElement("div",{className:"ps-share-suggestions"},ne.map(w=>u.createElement("button",{key:`${w.provider}/${w.subject}`,type:"button",className:"ps-share-suggestion",disabled:T,onClick:()=>K(w)},u.createElement("span",{className:"ps-share-suggestion-name"},w.displayName||w.subject),w.email?u.createElement("span",{className:"ps-share-suggestion-email"},w.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.")):null,_?u.createElement("div",{className:"ps-share-error"},_):null))}function vn({controller:t,mobile:e=!1,fullWidth:s=!1,showComposer:n=!0}){const i=W(t,T=>T.ui.themeId);_e(i);const o=W(t,T=>{const C=T.sessions.activeSessionId,_=is(T),k=s||e?_.totalWidth:_.leftWidth,R=Math.max(20,k-4);return{activeSessionId:C,activeHistory:C&&T.history.bySessionId.get(C)||null,activeOutbox:C&&T.outbox?.bySessionId?.[C]?T.outbox.bySessionId[C]:[],branding:T.branding,connection:T.connection,sessionsById:T.sessions.byId,sessionsFlat:T.sessions.flat,inspectorTab:T.ui.inspectorTab,chatViewMode:T.ui.chatViewMode||"transcript",activeSessionIsGroup:!!(C&&T.sessions.byId[C]?.isGroup),activeSessionStatus:C?String(T.sessions.byId[C]?.status||"").toLowerCase():"",focused:T.ui.focusRegion==="chat",scroll:T.ui.scroll.chat,authPrincipal:T.auth?.principal||null,contentWidth:R}},ke),r=u.useMemo(()=>({branding:o.branding,connection:o.connection,auth:{principal:o.authPrincipal},sessions:{activeSessionId:o.activeSessionId,byId:o.sessionsById,flat:o.sessionsFlat},history:{bySessionId:o.activeSessionId&&o.activeHistory?new Map([[o.activeSessionId,o.activeHistory]]):new Map},outbox:{bySessionId:o.activeSessionId?{[o.activeSessionId]:o.activeOutbox}:{}},ui:{inspectorTab:o.inspectorTab,chatViewMode:o.chatViewMode}}),[o.activeHistory,o.activeSessionId,o.activeOutbox,o.authPrincipal,o.branding,o.connection,o.chatViewMode,o.inspectorTab,o.sessionsById,o.sessionsFlat]),a=u.useMemo(()=>Do(r,{width:o.contentWidth}),[r,o.contentWidth]),l=Yi(!!a.animateTitleRight),c=u.useMemo(()=>Qi(a.titleRight,a.animateTitleRight?l:""),[l,a.animateTitleRight,a.titleRight]),d=u.useMemo(()=>dn(r,o.contentWidth,{tableMode:"sentinel"}),[r,o.contentWidth]),f=zi(o.activeSessionStatus==="running"),h=u.useMemo(()=>un(r,{spinnerFrame:f,maxWidth:o.contentWidth}),[r,f,o.contentWidth]),g=u.useMemo(()=>fn(r,o.contentWidth,{tableMode:"sentinel"}),[r,o.contentWidth]),m=u.useMemo(()=>h.length>0?[...g,...h]:g,[g,h]),{access:x}=Af(t,o.activeSessionId,o.activeSessionIsGroup),y=n&&!o.activeSessionIsGroup&&o.chatViewMode!=="summary",S=!!x&&x.canWrite===!1,E=y?u.createElement("div",{className:"ps-chat-composer"},S?u.createElement("div",{className:"ps-composer-readonly"},`You have view access to this session. Ask ${x.owner?.displayName||x.owner?.email||"the owner"} for write access to participate.`):u.createElement(Of,{controller:t,mobile:e,active:!0})):null;return u.createElement(os,{controller:t,title:e?Di(a.title,28):a.title,titleRight:e&&c?Di(c,18):c,actions:null,color:a.color,focused:o.focused,lines:d,bottomStickyLines:m,scrollOffset:o.scroll,scrollMode:"bottom",paneKey:"chat",className:"is-wrapped",panelClassName:"ps-chat-panel",bottomContent:E,structuredBlocks:!0})}function kf({controller:t,sessionsCollapsed:e,setSessionsCollapsed:s}){const n=W(t,r=>r.ui.themeId),i=_e(n),o=u.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>s(r=>!r)},e?"Show":"Hide");return u.createElement("div",{className:"ps-mobile-workspace"},e?u.createElement(qe,{title:[{text:"Sessions",color:"yellow",bold:!0}],color:"yellow",focused:!1,theme:i,actions:o,className:"ps-mobile-session-collapsed"},u.createElement("div",{className:"ps-mobile-session-summary"},"Session list collapsed.")):u.createElement(En,{controller:t,actions:o,panelClassName:"ps-mobile-session-pane"}),u.createElement("div",{className:"ps-mobile-chat-pane"},u.createElement(vn,{controller:t,mobile:!0,fullWidth:!0})))}function mr({activeTab:t,controller:e}){const s=u.useMemo(()=>In(e),[e]);return u.createElement("div",{className:"ps-tab-row ps-tab-row-icons"},s.map(n=>u.createElement(ee,{key:n,icon:Ld[n]||"•",label:Rd[n]||n,active:t===n,onClick:()=>{e.setFocus("inspector"),e.selectInspectorTab(n).catch(()=>{})}})))}function Mf({controller:t,focused:e,mobile:s=!1}){const n=W(t,y=>y.ui.themeId),i=_e(n),o=u.useRef(null),r=W(t,y=>{const S=y.sessions.activeSessionId,E=is(y),T=s||y.files.fullscreen?y.ui.layout?.viewportWidth??120:E.rightWidth;return{activeSessionId:S,sessionsById:y.sessions.byId,sessionsFlat:y.sessions.flat,filesBySessionId:y.files.bySessionId,filesFilter:y.files.filter,selectedArtifactId:y.files.selectedArtifactId,focused:e,previewScroll:y.ui.scroll.filePreview,fullscreen:!!y.files.fullscreen,contentWidth:Math.max(20,T-4),canBrowserUpload:$d(t),canPathUpload:Bd(t),canDeleteArtifacts:Hd(t),canOpenLocally:Gd(t)}},ke),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(()=>mn(a,{listWidth:Math.max(18,r.contentWidth-4),previewWidth:Math.max(18,r.contentWidth-4),showHints:!1}),[a,r.contentWidth]),c=u.useMemo(()=>At(a),[a]),d=c.length>0,f=u.useCallback(y=>{const S=Array.isArray(y)?y.filter(Boolean):[];S.length!==0&&t.uploadArtifactFiles(S).catch(()=>{})},[t]),p=u.useCallback(()=>{if(r.canBrowserUpload&&o.current){o.current.click();return}r.canPathUpload&&t.handleCommand(I.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:y=>{f(Array.from(y.currentTarget.files||[])),y.currentTarget.value=""}}),u.createElement(ee,{icon:"↥",label:"Upload",onClick:p,disabled:!r.canBrowserUpload&&!r.canPathUpload}),u.createElement(ee,{icon:"↧",label:"Download",onClick:()=>t.handleCommand(I.DOWNLOAD_SELECTED_FILE).catch(()=>{}),disabled:!d}),r.canDeleteArtifacts?u.createElement(ee,{icon:"✕",label:"Delete",onClick:()=>t.handleCommand(I.DELETE_SELECTED_FILE).catch(()=>{}),disabled:!d}):null,r.canOpenLocally?u.createElement(ee,{icon:"↗",label:"Open locally",onClick:()=>t.handleCommand(I.OPEN_SELECTED_FILE).catch(()=>{}),disabled:!d}):null,u.createElement(ee,{icon:"▾",label:"Filter",onClick:()=>t.handleCommand(I.OPEN_FILES_FILTER).catch(()=>{})}),u.createElement(ee,{icon:r.fullscreen?"⇱":"⛶",label:r.fullscreen?"Exit fullscreen":"Fullscreen",onClick:()=>t.handleCommand(I.TOGGLE_FILE_PREVIEW_FULLSCREEN).catch(()=>{})})),g=c.length===0?de(l.listBodyLines||[]).map((y,S)=>u.createElement(le,{key:`empty:${S}`,line:y,theme:i})):c.map((y,S)=>u.createElement("button",{key:y.id,type:"button",className:`ps-list-button${S===l.selectedIndex?" is-selected":""}`,onClick:()=>{t.setFocus("inspector"),t.selectFileBrowserItem(y).catch(()=>{})}},u.createElement(le,{line:de([l.listBodyLines?.[S]])[0],theme:i}))),m=l.previewRenderMode==="markdown"&&!l.previewLoading&&!l.previewError?u.createElement(df,{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(pf,{title:l.previewTitle,color:"cyan",focused:!1,theme:i,filename:l.selectedFilename,contentType:l.previewContentType,sizeBytes:l.previewSizeBytes,source:l.previewSource,uploadedAt:l.previewUploadedAt}):u.createElement(os,{controller:t,title:l.previewTitle,color:"cyan",focused:!1,lines:l.previewLines,scrollOffset:r.previewScroll,scrollMode:"top",paneKey:"filePreview",className:"is-preview is-wrapped"}),x=r;return u.createElement(qe,{title:x.fullscreen?l.fullscreenTitle:s&&l.panelTitleMobile?l.panelTitleMobile:l.panelTitle,color:"magenta",focused:x.focused,actions:h,theme:i},u.createElement(mr,{activeTab:"files",controller:t}),x.fullscreen?m:u.createElement("div",{className:"ps-files-grid"},u.createElement(qe,{title:l.listTitle,color:"cyan",theme:i},u.createElement("div",{className:"ps-action-list"},g)),m))}function St({controller:t,mobile:e=!1,panelClassName:s="",extraActions:n=null}){const i=W(t,f=>{const p=is(f),h=f.ui.inspectorTab,g=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:zd(g,h)}},ke),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(()=>Ue(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 g=Number(h?.data?.turnIndex??h?.data?.iteration);Number.isFinite(g)&&p.set(g,h)}return p},[i.activeSessionId,i.historyBySessionId]),l=u.useCallback((f,p)=>u.createElement(Ef,{lines:f,theme:p,completionByTurn:a}),[a]);if(i.inspectorTab==="files"&&!r.disabled)return u.createElement(Mf,{controller:t,focused:i.focused,mobile:e});const c=[];if(i.inspectorTab==="logs")c.push(u.createElement(ee,{key:"tail",icon:i.logsTailing?"■":"⇣",label:i.logsTailing?"Stop tailing":"Tail (follow)",active:i.logsTailing,onClick:()=>t.handleCommand(I.TOGGLE_LOG_TAIL).catch(()=>{})})),c.push(u.createElement(ee,{key:"filter",icon:"▾",label:"Filter",onClick:()=>t.handleCommand(I.OPEN_LOG_FILTER).catch(()=>{})}));else if(i.inspectorTab==="history")c.push(u.createElement(ee,{key:"refresh",icon:"↻",label:"Refresh",onClick:()=>t.handleCommand(I.REFRESH_EXECUTION_HISTORY).catch(()=>{})})),c.push(u.createElement(ee,{key:"save",icon:"⇩",label:"Export as artifact",onClick:()=>t.handleCommand(I.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(ee,{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(os,{controller:t,title:r.title,color:"magenta",focused:i.focused,actions:d,topContent:u.createElement(mr,{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 Ws({controller:t,panelClassName:e="",extraActions:s=null}){const n=W(t,r=>{const a=r.sessions.activeSessionId,l=is(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}},ke),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(()=>hn(i,n.maxLines),[i,n.maxLines]);return u.createElement(os,{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 Vs=[{id:"sessions",label:"Sessions",side:"left"},{id:"inspector",label:"Inspector",side:"right"},{id:"activity",label:"Activity",side:"right"}];function Pf({controller:t,pane:e,onClose:s,mobile:n=!1}){if(!e)return null;let i=null;e==="sessions"?i=u.createElement(En,{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(St,{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(Ws,{controller:t,panelClassName:"ps-chat-focus-pane",extraActions:u.createElement("button",{type:"button",className:"ps-mini-button",onClick:s},"Close")}));const o=Vs.find(r=>r.id===e);return u.createElement("div",{className:`ps-chat-focus-overlay${o?.side==="left"?" is-left":" is-right"}`},i)}function Nf({controller:t,openPane:e,onTogglePane:s,onExitFocus:n,mobile:i=!1}){const o=W(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"},Vs.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: ${Vs.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(vn,{controller:t,mobile:i,fullWidth:!0}),u.createElement(Pf,{controller:t,pane:e,onClose:()=>s(e),mobile:i})))}function Of({controller:t,mobile:e,active:s=!0,onAfterSend:n=null}){const i=W(t,m=>{const x=m.sessions.activeSessionId,y=x&&m.sessions.byId[x]||null,S=x&&m.outbox?.bySessionId?.[x]?m.outbox.bySessionId[x]:[];return{value:m.ui.prompt,cursor:m.ui.promptCursor,focused:m.ui.focusRegion==="prompt",modalOpen:!!m.ui.modal,answerMode:!!y?.pendingQuestion?.question,canStopTurn:Ro(y),hasOutbox:S.length>0,hasPendingOutbox:S.some(E=>E?.phase==="pending"),pendingCount:S.filter(E=>E?.phase==="pending").length,editingPending:m.ui.promptEdit?.sessionId===x,selectedOutboxPhase:m.ui.promptEdit?.sessionId===x&&m.ui.promptEdit?.phase||null}},ke),o=u.useRef(null);u.useEffect(()=>{const m=o.current;if(!(!s||i.modalOpen||!i.focused||!m)){if(document.activeElement!==m)try{m.focus({preventScroll:!0})}catch{m.focus()}m.setSelectionRange(i.cursor,i.cursor)}},[s,i.cursor,i.focused,i.modalOpen]);const r=u.useCallback(()=>{t.handleCommand(I.SEND_PROMPT).catch(()=>{}).finally(()=>{n?.()})},[t,n]),[a,l]=u.useState(!1),c=u.useCallback(()=>{l(!0),t.handleCommand(I.STOP_TURN).catch(()=>{}).finally(()=>l(!1))},[t]),d=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]),f=i.editingPending||i.hasPendingOutbox&&!i.value.trim()?"⇪":i.hasOutbox?"+":"❯",p=i.selectedOutboxPhase==="queued",h=i.selectedOutboxPhase==="cancelling",g=p||h;return u.createElement("div",{className:`ps-prompt-shell${e?" is-mobile":""}`},u.createElement("label",{className:"ps-prompt-label"},i.answerMode?"answer":h?"cancelling":p?"queued":i.editingPending?"pending":"you"),u.createElement("textarea",{ref:o,className:"ps-prompt-input",rows:e?2:Math.max(2,ot(i.value)),value:i.value,readOnly:g,placeholder:i.answerMode?"Type an answer and press Enter":i.editingPending?h?"Cancellation requested":p?"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:m=>t.setPromptCursor(m.currentTarget.selectionStart||0),onChange:m=>t.setPrompt(m.currentTarget.value,m.currentTarget.selectionStart||m.currentTarget.value.length),onKeyDown:m=>{if(m.key==="Tab"&&!m.shiftKey&&t.acceptPromptReferenceAutocomplete()){m.preventDefault();return}if(m.key==="ArrowUp"&&!m.shiftKey&&!m.metaKey&&!m.altKey){m.preventDefault(),t.movePromptCursorVertical(-1);return}if(m.key==="ArrowDown"&&!m.shiftKey&&!m.metaKey&&!m.altKey){m.preventDefault(),t.movePromptCursorVertical(1);return}if(m.key==="Escape"&&i.editingPending){if(m.preventDefault(),g){t.exitPendingPromptEdit({restoreDraft:!0});return}d();return}m.key==="Enter"&&!m.shiftKey&&!m.metaKey&&!e&&(m.preventDefault(),r())}}),u.createElement("div",{className:"ps-prompt-actions"},i.editingPending&&!h?u.createElement("button",{type:"button",className:"ps-mini-button",title:p?"Delete selected queued prompt":"Cancel selected pending prompt","aria-label":p?"Delete selected queued prompt":"Cancel selected pending prompt",onClick:d},p?"Delete":"Cancel"):null,i.canStopTurn||a?u.createElement("button",{type:"button",className:`ps-stop-button${a?" is-stopping":""}`,title:"Stop the current turn (the session stays alive and returns to idle)","aria-label":"Stop the current turn",disabled:a,onClick:c},"■"):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:r},f)))}const _f=1e3;function ee({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 k=c.current.offsetWidth/2,R=6,N=Math.max(k+R,Math.min(r.x,window.innerWidth-k-R));c.current.style.left=`${N}px`},[r]);const p=(k=!1)=>{const R=l.current;if(!R||typeof window>"u")return;const N=R.getBoundingClientRect(),O=k?N.top-44<0:N.bottom+44<window.innerHeight;a({x:N.left+N.width/2,y:O?N.bottom+6:N.top-6,placement:O?"below":"above"})},h=u.useRef(null),g=u.useRef(null),m=k=>{k.pointerType==="mouse"&&(clearTimeout(d.current),clearTimeout(h.current),d.current=setTimeout(p,_f))},x=k=>{k.pointerType==="mouse"&&(clearTimeout(d.current),clearTimeout(h.current),a(null))},y=k=>{k.pointerType!=="mouse"&&(f.current=!1,g.current={x:k.clientX,y:k.clientY},clearTimeout(d.current),clearTimeout(h.current),d.current=setTimeout(()=>{f.current=!0,p(!0)},450))},S=k=>{if(k.pointerType==="mouse"||!g.current)return;const R=k.clientX-g.current.x,N=k.clientY-g.current.y;R*R+N*N>100&&(g.current=null,clearTimeout(d.current),a(null))},E=k=>{k.pointerType!=="mouse"&&(g.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 T=k=>{if(f.current){f.current=!1,k.preventDefault?.();return}n||s?.(k)},C=k=>{k.preventDefault?.()},_=r&&typeof document<"u"&&document.body?Ed.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:T,disabled:n,"aria-label":e,onPointerEnter:m,onPointerLeave:x,onPointerDown:y,onPointerMove:S,onPointerUp:E,onPointerCancel:E,onContextMenu:C},u.createElement("span",{className:"ps-icon-button-glyph","aria-hidden":"true"},t),_)}function Rf({controller:t,mobile:e,chatFocusMode:s=!1,onToggleChatFocus:n=null,chatFocusDisabled:i=!1}){const o=W(t,d=>!!d.admin?.visible),r=W(t,d=>({mode:d.ui.chatViewMode||"transcript",activeSessionIsGroup:!!(d.sessions.activeSessionId&&d.sessions.byId[d.sessions.activeSessionId]?.isGroup),hasActiveSession:!!(d.sessions.activeSessionId&&d.sessions.byId[d.sessions.activeSessionId])}),ke),a=!r.hasActiveSession||r.activeSessionIsGroup,l=[{key:"new",icon:"+",label:"New session",onClick:()=>t.handleCommand(I.NEW_SESSION).catch(()=>{})},{key:"model",icon:"+⚙",label:"New session + choose model",onClick:()=>t.handleCommand(I.OPEN_MODEL_PICKER).catch(()=>{})},{key:"switch-model",icon:"⇄",label:a?"Select a session to switch its model":"Switch the selected session's model",onClick:()=>t.openSwitchModelPicker().catch(d=>{t.dispatch({type:"ui/status",text:d?.message||String(d)||"Failed to switch model"})}),disabled:a},{key:"filter",icon:"▾",label:"Filter sessions",onClick:()=>t.handleCommand(I.OPEN_SESSION_FILTER).catch(()=>{})},{key:"theme",icon:"◑",label:"Theme",onClick:()=>t.handleCommand(I.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?I.CLOSE_ADMIN_CONSOLE:I.OPEN_ADMIN_CONSOLE).catch(()=>{}),active:o}],c=d=>u.createElement(ee,{key:d.key,icon:d.icon,label:d.label,onClick:d.onClick,disabled:!!d.disabled,active:!!d.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"},l.map(c)))):u.createElement("div",{className:"ps-toolbar"},u.createElement("div",{className:"ps-toolbar-actions"},l.map(c)))}function Lf({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)/or),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(I.GROW_RIGHT_PANE).catch(()=>{});return}o.key==="ArrowRight"&&(o.preventDefault(),t.handleCommand(I.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 Ff({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=Gs(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=Us(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=Us(r?.getBoundingClientRect?.().width),l=c=>{const d=Gs((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 $f({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)/rr),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 Bf({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 Df({controller:t}){const e=W(t,p=>p.ui.themeId),s=_e(e),n=W(t,p=>({rawModal:p.ui.modal,themePicker:iu(p),modelPicker:Pc(p),reasoningEffortPicker:Oc(p),contextTierPicker:_c(p),sessionAgentPicker:Nc(p),sessionGroupPicker:Rc(p),sessionGroupName:Fc(p),artifactPicker:Gc(p),logFilter:Dc(p),filesFilter:Hc(p),historyFormat:nu(p),renameSession:Lc(p),sessionOwnerFilter:Bc(p),artifactUpload:$c(p),confirm:ou(p),logsFilter:p.logs.filter,filesFilterState:p.files.filter,historyFormatState:p.executionHistory?.format||"pretty"}),ke),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(I.CLOSE_MODAL).catch(()=>{}),c=(p,h="Apply")=>{const g=Array.isArray(p.rows)?p.rows:[],m=Array.isArray(p.rowItemIndexes)?p.rowItemIndexes:null,x=i.type==="modelPicker"||i.type==="reasoningEffortPicker"||i.type==="contextTierPicker"||i.type==="sessionAgentPicker",y=m&&m.length===g.length?g.map((S,E)=>{const T=m[E],C=Array.isArray(S)?S:de([S])[0]?.runs||[{text:S?.text||"",color:S?.color}];if(T==null||T<0)return u.createElement("div",{key:`row:${E}`,className:"ps-line ps-modal-list-heading-line"},u.createElement(fe,{runs:C,theme:s}));const _=i.items?.[T];return u.createElement("button",{key:_?.id||`row:${E}`,type:"button",className:`ps-list-button ps-modal-list-button${T===i.selectedIndex?" is-selected":""}${x?" is-hanging":""}`,onClick:()=>t.dispatch({type:"ui/modalSelection",index:T})},u.createElement("div",{className:"ps-line ps-modal-list-line"},u.createElement(fe,{runs:C,theme:s})))}):(i.items||[]).map((S,E)=>u.createElement("button",{key:S.id||E,type:"button",className:`ps-list-button ps-modal-list-button${E===i.selectedIndex?" is-selected":""}${x?" is-hanging":""}`,onClick:()=>t.dispatch({type:"ui/modalSelection",index:E})},u.createElement("div",{className:"ps-line ps-modal-list-line"},u.createElement(fe,{runs:Array.isArray(g?.[E])?g[E]:de([g?.[E]])[0]?.runs||[{text:g?.[E]?.text||"",color:g?.[E]?.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:S=>S.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"},y),u.createElement("div",{className:"ps-modal-details"},u.createElement("div",{className:"ps-modal-details-title"},p.detailsTitle||"Details"),de(p.detailsLines||[]).map((S,E)=>u.createElement(le,{key:`detail:${E}`,line:S,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(I.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:g=>g.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(I.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:g=>g.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((g,m)=>u.createElement("button",{key:g.id||m,type:"button",className:`ps-list-button ps-modal-list-button${m===i.selectedIndex?" is-selected":""}`,onClick:()=>t.toggleSessionOwnerFilter(m)},u.createElement("div",{className:"ps-line ps-modal-list-line"},u.createElement(fe,{runs:Array.isArray(h?.[m])?h[m]:de([h?.[m]])[0]?.runs||[{text:h?.[m]?.text||"",color:h?.[m]?.color}],theme:s}))))),u.createElement("div",{className:"ps-modal-details"},u.createElement("div",{className:"ps-modal-details-title"},p.detailsTitle||"Details"),de(p.detailsLines||[]).map((g,m)=>u.createElement(le,{key:`detail:${m}`,line:g,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(I.MODAL_CONFIRM).catch(()=>{}))},autoFocus:!0}),u.createElement("div",{className:"ps-modal-details"},de(n.renameSession.helpLines||[]).map((p,h)=>u.createElement(le,{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(I.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(I.MODAL_CONFIRM).catch(()=>{}))},autoFocus:!0}),u.createElement("div",{className:"ps-modal-details"},de(n.sessionGroupName.helpLines||[]).map((p,h)=>u.createElement(le,{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(I.MODAL_CONFIRM).catch(()=>{})},"Create and Move"))));if(i.type==="terminatePicker"){const p=Number(i.bulkCount)>1,h=!!i.systemRestart,g=String(i.sessionTitle||"").trim()||"this session",m=Number(i.bulkCount)||0,x=p?`What should happen to the ${m} selected sessions? Choose an action; you'll be asked to confirm.`:h?`How should "${g}" be restarted? Choose a disposition; you'll be asked to confirm.`:`What should happen to "${g}"? Choose an action; you'll be asked to confirm.`,y=S=>()=>{t.pickTerminateAction(S).catch(()=>{})};return u.createElement("div",{className:"ps-modal-backdrop",onClick:l},u.createElement("div",{className:"ps-modal is-narrow",onClick:S=>S.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}},x)),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:y("complete")},p?`Mark ${m} Completed`:h?"Complete & Restart":"Mark Completed"),u.createElement("button",{type:"button",className:"ps-modal-button",style:{width:"100%",justifyContent:"flex-start"},onClick:y("cancel")},p?`Cancel ${m} Sessions`:h?"Terminate & Restart":"Cancel Session"),u.createElement("button",{type:"button",className:"ps-modal-button is-danger",style:{width:"100%",justifyContent:"flex-start"},onClick:y("delete")},p?`Hard Delete ${m} 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"},de(n.artifactUpload.helpLines||[]).map((p,h)=>u.createElement(le,{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(I.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 g=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(m=>u.createElement("button",{key:m.id,type:"button",className:`ps-filter-option${m.id===g?" is-selected":""}`,onClick:()=>{t.dispatch({type:"ui/modalSelection",index:h}),i.type==="historyFormat"?t.dispatch({type:"executionHistory/format",format:m.id}):i.type==="filesFilter"?(t.dispatch({type:"files/filter",filter:{[p.id]:m.id}}),t.ensureFilesForScope(m.id).catch(()=>{})):t.dispatch({type:"logs/filter",filter:{[p.id]:m.id}})}},m.label)))})),u.createElement("div",{className:"ps-modal-footer"},u.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:l},"Done")))):null}function Hf(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=In(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=g=>{const m=Fd(a,l,g);t.selectInspectorTab(m).catch(()=>{})};if(!o&&f){n.preventDefault(),t.handleCommand(I.OPEN_THEME_PICKER).catch(()=>{});return}if(!o&&p){n.preventDefault(),t.handleCommand(I.OPEN_MODEL_PICKER).catch(()=>{});return}if(r&&!o){if(n.key==="Escape"||r.type==="confirm"&&n.key==="n"){n.preventDefault(),t.handleCommand(I.CLOSE_MODAL).catch(()=>{});return}if(n.key==="Enter"||r.type==="confirm"&&n.key==="y"){n.preventDefault(),t.handleCommand(I.MODAL_CONFIRM).catch(()=>{});return}if(n.key==="Tab"&&n.shiftKey){n.preventDefault(),t.handleCommand(I.MODAL_PANE_PREV).catch(()=>{});return}if(n.key==="Tab"){n.preventDefault(),t.handleCommand(I.MODAL_PANE_NEXT).catch(()=>{});return}if(n.key==="ArrowUp"||n.key==="k"){n.preventDefault(),t.handleCommand(I.MODAL_PREV).catch(()=>{});return}(n.key==="ArrowDown"||n.key==="j")&&(n.preventDefault(),t.handleCommand(I.MODAL_NEXT).catch(()=>{}));return}if(!o){if(n.key==="r"&&d&&c!=="prompt"){n.preventDefault(),t.handleCommand(I.REFRESH).catch(()=>{});return}if(c==="chat"&&n.key==="s"&&d){n.preventDefault(),t.handleCommand(I.TOGGLE_CHAT_VIEW).catch(()=>{});return}if(n.key==="n"&&d){n.preventDefault(),t.handleCommand(I.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(I.OPEN_ARTIFACT_UPLOAD).catch(()=>{});return}if(c==="inspector"&&l==="files"&&n.key==="a"&&d){n.preventDefault(),t.handleCommand(I.DOWNLOAD_SELECTED_FILE).catch(()=>{});return}if(c==="inspector"&&l==="files"&&n.key==="x"&&d){n.preventDefault(),t.handleCommand(I.DELETE_SELECTED_FILE).catch(()=>{});return}if(c==="inspector"&&l==="files"&&n.key==="o"&&d){n.preventDefault(),t.handleCommand(I.OPEN_SELECTED_FILE).catch(()=>{});return}if(c==="inspector"&&l==="files"&&n.key==="f"&&d){n.preventDefault(),t.handleCommand(I.OPEN_FILES_FILTER).catch(()=>{});return}if(c==="inspector"&&l==="stats"&&n.key==="f"&&d){n.preventDefault(),t.handleCommand(I.TOGGLE_STATS_VIEW).catch(()=>{});return}if(c==="inspector"&&l==="files"&&n.key==="v"&&d){n.preventDefault(),t.handleCommand(I.TOGGLE_FILE_PREVIEW_FULLSCREEN).catch(()=>{});return}if(c==="inspector"&&l==="logs"&&n.key==="t"&&d){n.preventDefault(),t.handleCommand(I.TOGGLE_LOG_TAIL).catch(()=>{});return}if(c==="inspector"&&l==="logs"&&n.key==="f"&&d){n.preventDefault(),t.handleCommand(I.OPEN_LOG_FILTER).catch(()=>{});return}if(c==="inspector"&&l==="history"&&n.key==="f"&&d){n.preventDefault(),t.handleCommand(I.OPEN_HISTORY_FORMAT).catch(()=>{});return}if(c==="inspector"&&l==="history"&&n.key==="r"&&d){n.preventDefault(),t.handleCommand(I.REFRESH_EXECUTION_HISTORY).catch(()=>{});return}if(c==="inspector"&&l==="history"&&n.key==="a"&&d){n.preventDefault(),t.handleCommand(I.EXPORT_EXECUTION_HISTORY).catch(()=>{});return}if(n.key==="a"&&d){n.preventDefault(),t.handleCommand(I.OPEN_ARTIFACT_PICKER).catch(()=>{});return}if(n.key==="p"&&d){n.preventDefault(),t.handleCommand(I.FOCUS_PROMPT).catch(()=>{});return}if(n.key==="c"&&d){n.preventDefault(),t.handleCommand(I.CANCEL_SESSION).catch(()=>{});return}if(n.key==="d"&&d){n.preventDefault(),t.handleCommand(I.DONE_SESSION).catch(()=>{});return}if(n.key==="D"&&n.shiftKey&&!n.metaKey&&!n.ctrlKey&&!n.altKey){n.preventDefault(),t.handleCommand(I.DELETE_SESSION).catch(()=>{});return}if(n.key==="m"&&d&&c==="inspector"){n.preventDefault(),h(1);return}if(n.key==="["&&d){n.preventDefault(),t.handleCommand(I.GROW_LEFT_PANE).catch(()=>{});return}if(n.key==="]"&&d){n.preventDefault(),t.handleCommand(I.GROW_RIGHT_PANE).catch(()=>{});return}if(n.key==="{"&&d){n.preventDefault(),t.handleCommand(I.SHRINK_SESSION_PANE).catch(()=>{});return}if(n.key==="}"&&d){n.preventDefault(),t.handleCommand(I.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(I.MOVE_SESSION_UP).catch(()=>{});return}if(c==="sessions"&&(n.key==="ArrowDown"||n.key==="j")){n.preventDefault(),t.handleCommand(I.MOVE_SESSION_DOWN).catch(()=>{});return}if(c==="sessions"&&n.ctrlKey&&n.key.toLowerCase()==="g"&&!n.metaKey&&!n.altKey){n.preventDefault(),t.handleCommand(I.OPEN_MOVE_TO_GROUP).catch(()=>{});return}if(c==="sessions"&&(n.key==="PageUp"||n.ctrlKey&&n.key.toLowerCase()==="u")){n.preventDefault(),t.handleCommand(I.PAGE_UP).catch(()=>{});return}if(c==="sessions"&&(n.key==="PageDown"||n.ctrlKey&&n.key.toLowerCase()==="d")){n.preventDefault(),t.handleCommand(I.PAGE_DOWN).catch(()=>{});return}if(c==="sessions"&&n.key==="t"&&d){n.preventDefault(),t.handleCommand(I.OPEN_RENAME_SESSION).catch(()=>{});return}if(!e&&(n.key==="PageUp"||n.ctrlKey&&n.key.toLowerCase()==="u")){n.preventDefault(),t.handleCommand(I.PAGE_UP).catch(()=>{});return}if(!e&&(n.key==="PageDown"||n.ctrlKey&&n.key.toLowerCase()==="d")){n.preventDefault(),t.handleCommand(I.PAGE_DOWN).catch(()=>{});return}if(!e&&n.key==="g"&&d){n.preventDefault(),t.handleCommand(I.SCROLL_TOP).catch(()=>{});return}if(!e&&n.key==="G"&&n.shiftKey&&!n.metaKey&&!n.ctrlKey&&!n.altKey){n.preventDefault(),t.handleCommand(I.SCROLL_BOTTOM).catch(()=>{});return}if(c!=="prompt"&&n.key==="h"&&d){n.preventDefault(),t.handleCommand(I.FOCUS_LEFT).catch(()=>{});return}if(c!=="prompt"&&n.key==="l"&&d){n.preventDefault(),t.handleCommand(I.FOCUS_RIGHT).catch(()=>{});return}if(!e&&(n.key==="ArrowUp"||n.key==="k")){n.preventDefault(),t.handleCommand(I.SCROLL_UP).catch(()=>{});return}if(!e&&(n.key==="ArrowDown"||n.key==="j")){n.preventDefault(),t.handleCommand(I.SCROLL_DOWN).catch(()=>{});return}!e&&n.key==="Escape"&&(n.preventDefault(),t.handleCommand(I.FOCUS_SESSIONS).catch(()=>{}))}};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[t,e])}function Gf(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 Uf({controller:t}){const e=W(t,ec,ke),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=Gf(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 Wf({transport:t,mode:e="remote",branding:s=null}={}){Ud();const n=Eu(Iu,za({mode:e,branding:s}));return new dd({store:n,transport:t})}function Vf({controller:t}){const e=u.useRef(null),s=u.useRef(null),n=Hi(e),i=Hi(s),o=Qd(n);u.useEffect(()=>{const A=()=>{const H=document.createElement("span");H.style.cssText="position:absolute;visibility:hidden;white-space:pre;";const j=document.querySelector(".ps-scroll-panel .ps-line")||document.querySelector(".ps-line");j&&(H.style.font=window.getComputedStyle(j).font),H.textContent="0".repeat(100),(j?.parentElement||document.body).appendChild(H);const re=H.getBoundingClientRect().width/100||8;H.remove(),t.dispatch({type:"ui/viewport",width:Math.floor(window.innerWidth/re),height:Math.floor(window.innerHeight/Ne)})};A();let M;const $=()=>{clearTimeout(M),M=setTimeout(A,150)};return window.addEventListener("resize",$),window.addEventListener("orientationchange",$),()=>{clearTimeout(M),window.removeEventListener("resize",$),window.removeEventListener("orientationchange",$)}},[t]);const[r,a]=u.useState(!1),[l,c]=u.useState(null),d=W(t,A=>({themeId:A.ui.themeId,ownerFilter:A.sessions.ownerFilter,pinnedIds:A.sessions.pinnedIds,collapsedSessionIds:A.sessions.collapsedIds,activeSessionId:A.sessions.activeSessionId||null,promptRows:ur(A),chatViewMode:A.ui.chatViewMode||"transcript",activeSessionIsGroup:!!(A.sessions.activeSessionId&&A.sessions.byId[A.sessions.activeSessionId]?.isGroup),paneAdjust:A.ui.layout?.paneAdjust??0,sessionPaneAdjust:A.ui.layout?.sessionPaneAdjust??0,portalSessionColumnAdjust:A.ui.layout?.portalSessionColumnAdjust??0,activityPaneAdjust:A.ui.layout?.activityPaneAdjust??0,focusRegion:A.ui.focusRegion,inspectorTab:A.ui.inspectorTab,filesFullscreen:!!A.files.fullscreen,adminVisible:!!A.admin?.visible}),ke),f=u.useRef(!1),p=u.useRef(null),h=u.useRef(null),g=u.useRef(null),m=u.useRef(!1),x=u.useRef(!1),y=u.useRef(null),S=u.useRef(null),[E,T]=u.useState("workspace"),[C,_]=u.useState(!1),k=(n.width||window.innerWidth||0)<vd,N=d.activeSessionIsGroup||d.chatViewMode==="summary"?0:d.promptRows;Hf(t,k),u.useEffect(()=>{t.setViewport(o)},[t,o.height,o.width]),u.useEffect(()=>{let A=!0;f.current=!1,p.current=null,y.current=null,S.current=$i(t.getState()),h.current&&(clearTimeout(h.current),h.current=null),g.current&&(clearInterval(g.current),g.current=null),m.current=!1,x.current=!1;const M=t.transport;if(typeof M?.getCurrentUserProfile!="function"||typeof M?.setCurrentUserProfileSettings!="function")return f.current=!0,()=>{A=!1};const $=async()=>{if(!(!A||m.current)){m.current=!0;try{const H=await M.getCurrentUserProfile();if(!A)return;S.current=$i(t.getState());const j=Wd(H?.profileSettings,S.current),re=JSON.stringify(j),ie=As(t.getState()),rs=JSON.stringify(ie),gr=f.current&&p.current!=null&&rs!==p.current;!(h.current||x.current||gr)&&y.current!==re&&(t.dispatch({type:"profileSettings/apply",settings:j}),y.current=re);const yr=As(t.getState());p.current=JSON.stringify(yr),f.current=!0}catch{if(!A)return;f.current=!0}finally{m.current=!1}}};return $().catch(()=>{}),g.current=setInterval(()=>{$().catch(()=>{})},Pd),()=>{A=!1,h.current&&(clearTimeout(h.current),h.current=null),g.current&&(clearInterval(g.current),g.current=null),m.current=!1}},[t]),u.useEffect(()=>{if(!f.current)return;const A=As(d),M=JSON.stringify(A);p.current!==M&&(p.current=M,h.current&&clearTimeout(h.current),h.current=setTimeout(()=>{h.current=null,x.current=!0,Vd(t,A).catch(()=>{}).finally(()=>{x.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(()=>{Yd(d.themeId)},[d.themeId]),u.useEffect(()=>{k&&d.focusRegion!=="prompt"&&T(d.focusRegion==="activity"?"activity":d.focusRegion==="inspector"?"inspector":"workspace")},[k,d.focusRegion]),u.useEffect(()=>{const A=In(t);!A.includes(d.inspectorTab)&&A.length>0&&t.selectInspectorTab(A[0]).catch(()=>{})},[t,d.inspectorTab]);const O=u.useMemo(()=>wt(o,d.paneAdjust,N,d.sessionPaneAdjust,d.activityPaneAdjust),[o,d.activityPaneAdjust,d.paneAdjust,N,d.sessionPaneAdjust]),U=d.filesFullscreen&&d.inspectorTab==="files";u.useEffect(()=>{!U||!r||(a(!1),c(null))},[r,U]);const L=u.useCallback(()=>{a(A=>{const M=!A;return M?t.setFocus("chat"):c(null),M})},[t]),K=u.useCallback(A=>{c(M=>{const $=M===A?null:A;return t.setFocus($||"chat"),$})},[t]),P=Math.max(0,(n.width||0)*.68),F=i.width||P,V=qd(F,d.portalSessionColumnAdjust),q=Kd(V),ne=q==="hidden"?"0px":`clamp(0px, calc(${xn*100}% + ${Number(d.portalSessionColumnAdjust)||0}px), max(0px, calc(100% - 14rem - 32px)))`,ce=u.createElement("div",{className:"ps-workspace-grid",style:{gridTemplateColumns:`minmax(0, ${O.leftWidth}fr) 16px minmax(0, ${O.rightWidth}fr)`}},u.createElement("div",{ref:s,className:`ps-workspace-main-grid is-session-${q}`,style:{gridTemplateColumns:`${ne} 16px minmax(14rem, 1fr)`}},q!=="hidden"?u.createElement("div",{className:"ps-workspace-pane-slot",style:{gridColumn:"1"}},u.createElement(En,{controller:t,structuredRows:!0})):null,u.createElement("div",{style:{gridColumn:"2",minWidth:0,display:"flex"}},u.createElement(Ff,{controller:t,portalSessionColumnAdjust:d.portalSessionColumnAdjust})),u.createElement("div",{className:"ps-workspace-pane-slot",style:{gridColumn:"3"}},u.createElement(vn,{controller:t}))),u.createElement(Lf,{controller:t,paneAdjust:d.paneAdjust}),u.createElement("div",{className:"ps-workspace-column",style:{gridTemplateRows:`${O.inspectorPaneHeight}fr 16px ${O.activityPaneHeight}fr`}},u.createElement("div",{className:"ps-workspace-pane-slot",style:{gridRow:"1"}},O.inspectorHidden?null:u.createElement(St,{controller:t,mobile:!1})),u.createElement("div",{style:{gridRow:"2",minHeight:0,display:"flex",flexDirection:"column"}},u.createElement($f,{controller:t,activityPaneAdjust:d.activityPaneAdjust})),u.createElement("div",{className:"ps-workspace-pane-slot",style:{gridRow:"3"}},O.activityHidden?null:u.createElement(Ws,{controller:t})))),ue=u.createElement(Nf,{controller:t,openPane:l,onTogglePane:K,onExitFocus:L,mobile:k}),b=u.createElement("div",{className:"ps-workspace-full"},u.createElement(St,{controller:t,mobile:!1}));let w=null;return U?w=u.createElement("div",{className:"ps-mobile-pane-fill"},u.createElement(St,{controller:t,mobile:!0})):E==="inspector"?w=u.createElement("div",{className:"ps-mobile-pane-fill"},u.createElement(St,{controller:t,mobile:!0})):E==="activity"?w=u.createElement("div",{className:"ps-mobile-pane-fill"},u.createElement(Ws,{controller:t})):w=u.createElement(kf,{controller:t,sessionsCollapsed:C,setSessionsCollapsed:_}),u.createElement("div",{ref:e,className:"ps-web-shell"},k&&(r||E==="inspector"||E==="activity")?null:u.createElement(Rf,{controller:t,mobile:k,chatFocusMode:r,onToggleChatFocus:L,chatFocusDisabled:U}),u.createElement("div",{className:"ps-workspace"},d.adminVisible?u.createElement(Uf,{controller:t}):U?b:r?ue:k?w:ce),k&&!r?u.createElement(Bf,{activePane:E,setActivePane:T,controller:t}):null,u.createElement(Df,{controller:t}))}export{Vf as P,u as R,Ir as a,Wf as c,Ki as r,tc as s};
|